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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4713a782199f2eeb58436966ee34ada3a15d6414 | 2,766 | pas | Pascal | demo/unit1.pas | JurassicPork/MediaInfoLib | cba67e61e0d3d47dde46d330b55b02fae8231dd7 | [
"MIT"
]
| 4 | 2020-11-30T19:21:39.000Z | 2021-12-18T15:25:15.000Z | demo/unit1.pas | JurassicPork/MediaInfoLib | cba67e61e0d3d47dde46d330b55b02fae8231dd7 | [
"MIT"
]
| null | null | null | demo/unit1.pas | JurassicPork/MediaInfoLib | cba67e61e0d3d47dde46d330b55b02fae8231dd7 | [
"MIT"
]
| 1 | 2021-01-17T04:38:15.000Z | 2021-01-17T04:38:15.000Z | unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls,
Variants, MediaInfoDll;
type
{ TForm1 }
TForm1 = class(TForm)
Button1: TButton;
Memo1: TMemo;
OpenDialog1: TOpenDialog;
procedure Button1Click(Sender: TObject);
private
public
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
procedure TForm1.Button1Click(Sender: TObject);
var
HandleMI: PtrUint;
{$IFDEF WINDOWS}
To_Display: WideString;
CR: WideString;
filename: Widestring;
{$ELSE}
To_Display: String;
CR: String;
filename: String;
{$ENDIF}
begin
CR:=Chr(13) + Chr(10);
{$IF defined(WINDOWS)}
if (MediaInfoDLL_Load('mediainfo.dll')=false) then
begin
Memo1.Text := 'Error while loading mediainfo.dll';
exit;
end;
{$ELSEIF defined(DARWIN)}
if (MediaInfoDLL_Load('libmediainfo.0.dylib')=false) then
begin
Memo1.Text := 'Error while loading libmediainfo.0.dylib';
exit;
end;
{$ELSE } // Linux
if (MediaInfoDLL_Load('libmediainfo.so.0')=false) then
begin
Memo1.Text := 'Error while loading libmediainfo.so.0';
exit;
end;
{$ENDIF}
To_Display := MediaInfo_Option (0, 'Info_Version', '') + CR;
if OpenDialog1.Execute then
begin
filename := OpenDialog1.Filename;
HandleMI := MediaInfo_New();
MediaInfo_Option(HandleMI, 'CharSet', 'UTF-8');
To_Display := To_Display + 'Open' + CR;
{$IFDEF WINDOWS}
To_Display := To_Display + format('%d', [MediaInfo_Open(HandleMI, PWideChar(filename))]);
{$ELSE}
To_Display := To_Display + format('%d', [MediaInfo_Open(HandleMI, PChar(filename))]);
{$ENDIF}
To_Display := To_Display + CR + CR + 'Inform with Complete=false' + CR;
MediaInfo_Option (HandleMI, 'Complete', '');
To_Display := To_Display + MediaInfo_Inform(HandleMI, 0);
To_Display := To_Display + CR + CR + 'Inform with Complete=true' + CR;
MediaInfo_Option (HandleMI, 'Complete', '1');
To_Display := To_Display + MediaInfo_Inform(HandleMI, 0);
To_Display := To_Display + CR + CR + 'Custom Inform' + CR;
MediaInfo_Option (HandleMI, 'Inform', 'General;Example : FileSize=%FileSize% Bytes');
To_Display := To_Display + MediaInfo_Inform(HandleMI, 0);
MediaInfo_Option (HandleMI, 'Inform', '');
To_Display := To_Display + CR + CR + 'Get with Stream:=General and Parameter=^FileSize^' + CR;
To_Display := To_Display + MediaInfo_Get(HandleMI, Stream_General, 0, 'FileSize', Info_Text, Info_Name);
To_Display := To_Display + CR + CR + 'Close' + CR;
MediaInfo_Close(HandleMI);
MediaInfo_Delete(HandleMI);
Memo1.Text := To_Display;
end;
end;
end.
| 24.918919 | 110 | 0.649675 |
472be9023d2acca128cb238ae3cc0cebd1a7cfb9 | 332 | dpr | Pascal | fadeinout.dpr | imekon/fadeinout | 98c4705955dfbf2acf447d9417bbe9a7981334d6 | [
"MIT"
]
| null | null | null | fadeinout.dpr | imekon/fadeinout | 98c4705955dfbf2acf447d9417bbe9a7981334d6 | [
"MIT"
]
| null | null | null | fadeinout.dpr | imekon/fadeinout | 98c4705955dfbf2acf447d9417bbe9a7981334d6 | [
"MIT"
]
| null | null | null | program fadeinout;
{$R *.dres}
uses
System.StartUpCopy,
FMX.Forms,
main in 'main.pas' {MainForm},
actor in 'actor.pas',
helpers.bitmap in 'helpers.bitmap.pas',
actor.animation in 'actor.animation.pas';
{$R *.res}
begin
Application.Initialize;
Application.CreateForm(TMainForm, MainForm);
Application.Run;
end.
| 16.6 | 46 | 0.707831 |
f118a82434a2015fe08180f1f7b7b2c7b0a38d91 | 62,347 | pas | Pascal | Libraries/Spring4D/Tests/Source/Core/Spring.Tests.Container.pas | jomael/Concepts | 82d18029e41d55e897d007f826c021cdf63e53f8 | [
"Apache-2.0"
]
| 62 | 2016-01-20T16:26:25.000Z | 2022-02-28T14:25:52.000Z | Libraries/Spring4D/Tests/Source/Core/Spring.Tests.Container.pas | jomael/Concepts | 82d18029e41d55e897d007f826c021cdf63e53f8 | [
"Apache-2.0"
]
| null | null | null | Libraries/Spring4D/Tests/Source/Core/Spring.Tests.Container.pas | jomael/Concepts | 82d18029e41d55e897d007f826c021cdf63e53f8 | [
"Apache-2.0"
]
| 20 | 2016-09-08T00:15:22.000Z | 2022-01-26T13:13:08.000Z | {***************************************************************************}
{ }
{ Spring Framework for Delphi }
{ }
{ Copyright (c) 2009-2018 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. }
{ }
{***************************************************************************}
unit Spring.Tests.Container;
{$I Spring.inc}
{$I Spring.Tests.inc}
interface
uses
Classes,
SysUtils,
TestFramework,
Spring,
Spring.Services,
Spring.Container,
Spring.Container.Common,
// DO NOT CHANGE ORDER OF FOLLOWING UNITS !!!
Spring.Tests.Container.Interfaces,
Spring.Tests.Container.Components;
type
TContainerTestCase = class abstract(TTestCase)
protected
fContainer: TContainer;
procedure CheckIs(AInterface: IInterface; AClass: TClass; msg: string = ''); overload;
procedure SetUp; override;
procedure TearDown; override;
end;
{$IFDEF AUTOREFCOUNT}
TTestGlobalContainer = class(TTestCase)
published
procedure TestGlobalContainerDirectUse;
procedure TestGlobalContainerAssignToVariable;
procedure TestServiceLocatorDirectUse;
procedure TestServiceLocatorAssignToVariable;
end;
{$ENDIF}
TTestEmptyContainer = class(TContainerTestCase)
published
procedure TestResolveUnknownInterfaceService;
// procedure TestResolveUnknownClassService;
procedure TestRegisterNonGuidInterfaceService;
procedure TestRegisterGenericInterfaceService;
procedure TestRegisterUnassignableService;
procedure TestRegisterTwoUnnamedServicesImplicit;
procedure TestRegisterTwoUnnamedServicesExplicit;
procedure TestRegisterTwoNamedDifferentServices;
procedure TestResolveReturnsUnnamedService;
procedure TestResolveAll;
procedure TestResolveAllNonGeneric;
end;
TTestSimpleContainer = class(TContainerTestCase)
published
procedure TestIssue13;
procedure TestInterfaceService;
procedure TestAbstractClassService;
procedure TestServiceSameAsComponent;
procedure TestBootstrap;
procedure TestSingleton;
procedure TestTransient;
procedure TestPerThread;
procedure TestPooled;
procedure TestPooledRefCountedInterface;
procedure TestInitializable;
procedure TestRecyclable;
procedure TestDisposable;
procedure TestIssue41_DifferentName;
procedure TestIssue41_DifferentService;
procedure TestIssue41_DifferentLifetimes;
procedure TestIssue49;
procedure TestIssue50;
procedure TestResolveFuncWithTwoTypes;
procedure TestResolveUnknownClasses;
procedure TestResolveComponentDoesNotFallbackToTObject;
procedure TestResolveComponentDoesCallOverriddenConstructor;
procedure TestRecordConstructorNotConsidered;
{$IFDEF DELPHIXE_UP}
procedure TestClassContainsAbstractMethods;
{$ENDIF}
end;
// Same Service, Different Implementations
TTestDifferentServiceImplementations = class(TContainerTestCase)
private
fNameService: INameService;
fAnotherNameService: INameService;
fServices: TArray<INameService>;
fServiceValues: TArray<TValue>;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestNameService;
procedure TestAnotherNameService;
procedure TestResolveAll;
procedure TestResolveAllNonGeneric;
procedure TestUnsatisfiedDependency;
end;
// Same Component, Different Services
TTestImplementsDifferentServices = class(TContainerTestCase)
private
fNameService: INameService;
fAgeService: IAgeService;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestNameService;
procedure TestAgeService;
end;
TTestActivatorDelegate = class(TContainerTestCase)
private
fPrimitive: IPrimitive;
fExpectedInteger: Integer;
fExpectedString: string;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestNameService;
procedure TestIntegerArgument;
procedure TestStringArgument;
end;
TTypedInjectionTestCase = class abstract(TContainerTestCase)
private
fNameService: INameService;
fInjectionExplorer: IInjectionExplorer;
protected
procedure DoRegisterComponents; virtual; abstract;
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestConstructorInjection;
procedure TestMethodInjection;
procedure TestPropertyInjection;
procedure TestFieldInjection;
end;
TTestTypedInjectionByCoding = class(TTypedInjectionTestCase)
protected
procedure DoRegisterComponents; override;
end;
TTestTypedInjectionsByAttribute = class(TTypedInjectionTestCase)
protected
procedure DoRegisterComponents; override;
end;
TNamedInjectionsTestCase = class(TContainerTestCase)
private
fExplorer: IInjectionExplorer;
protected
procedure DoRegisterComponents; virtual;
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestConstructorInjection;
procedure TestMethodInjection;
procedure TestPropertyInjection;
procedure TestFieldInjection;
end;
TTestNamedInjectionsByCoding = class(TNamedInjectionsTestCase)
protected
procedure DoRegisterComponents; override;
end;
TTestNamedInjectionsByAttribute = class(TNamedInjectionsTestCase)
protected
procedure DoRegisterComponents; override;
end;
TTestDirectCircularDependency = class(TContainerTestCase)
protected
procedure SetUp; override;
published
procedure TestResolve;
end;
TTestCrossedCircularDependency = class(TContainerTestCase)
protected
procedure SetUp; override;
published
procedure TestResolveChicken;
procedure TestResolveEgg;
end;
TTestCircularReferenceLazySingleton = class(TContainerTestCase)
published
procedure TestResolveLazySingleton;
end;
TTestPerResolve = class(TContainerTestCase)
published
procedure TestResolveCircularDependency;
end;
TTestImplementsAttribute = class(TContainerTestCase)
published
procedure TestImplements;
end;
TTestRegisterInterfaces = class(TContainerTestCase)
published
procedure TestOneService;
procedure TestTwoServices;
procedure TestInheritedService;
procedure TestTwoServicesWithSameName;
procedure TestParentInterface;
end;
TTestDefaultResolve = class(TContainerTestCase)
published
procedure TestResolve;
procedure TestResolveDependency;
procedure TestRegisterDefault;
procedure TestNoDefault;
end;
TTestInjectionByValue = class(TContainerTestCase)
published
procedure TestInjectField;
end;
TTestResolverOverride = class(TContainerTestCase)
private
fDummy: TObject;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestResolve;
procedure TestResolveWithClass;
procedure TestResolveWithMultipleParams;
procedure TestResolveWithDependency;
procedure TestResolveWithDependencySubClass;
end;
TTestRegisterInterfaceTypes = class(TContainerTestCase)
published
procedure TestOneService;
procedure TestTwoServices;
procedure TestOneServiceAsSingleton;
procedure TestOneServiceAsSingletonPerThread;
procedure TestTwoRegistrations;
end;
TTestLazyDependencies = class(TContainerTestCase)
private
fCalled: Boolean;
protected
procedure SetUp; override;
procedure PerformChecks; virtual;
published
procedure TestDependencyTypeIsFunc;
{$IFNDEF IOSSIMULATOR}
procedure TestDependencyTypeIsRecord;
procedure TestDependencyTypeIsInterface;
{$ELSE}
// These tests fail due to some compiler/RTL problem, the circular
// dependency exception is raised but during re-raise in some finally block
// AV is raised instead. This is rare corner case not considered to be a
// major issue.
{$ENDIF}
procedure TestDependencyTypeIsSingletonAlreadyInstantiated;
procedure TestDependencyTypeIsSingletonNotYetInstantiated;
procedure TestResolveLazyOfSingletonCreatedLater;
end;
TTestLazyDependenciesDetectRecursion = class(TTestLazyDependencies)
protected
procedure PerformChecks; override;
end;
TTestManyDependencies = class(TContainerTestCase)
protected
procedure SetUp; override;
published
procedure TestInjectArray;
procedure TestInjectEnumerable;
procedure TestInjectArrayOfLazy;
procedure TestNoRecursion;
procedure TestNoRecursion_Issue18;
procedure TestNoRecursion_TwoDifferentModelsWithSameComponentType;
procedure TestRecursion_TwoDifferentModelsWithSameComponentType;
procedure TestResolveArrayOfLazy;
end;
TTestDecorators = class(TContainerTestCase)
protected
procedure SetUp; override;
published
procedure RegisterOneDecoratorResolveReturnsDecorator;
procedure RegisterOneDecoratorWithFailingConditionResolvesWithoutDecorator;
procedure RegisterTwoDecoratorsResolveReturnsLastDecorator;
procedure RegisterTwoDecoratorsResolveWithParameterReturnsCorrectValue;
procedure RegisterOneDecoratorInitializeIsCalled;
procedure RegisterTwoDecoratorsResolveLazyReturnsLastDecorator;
procedure RegisterTwoDecoratorsResolveArrayAllDecorated;
end;
implementation
uses
Spring.Collections,
Spring.Container.Core,
Spring.Container.Resolvers,
Spring.TestUtils,
{$IFDEF DELPHIXE_UP}
Spring.Mocking,
{$ENDIF}
Spring.Logging;
type
TObjectAccess = class(TObject);
{$REGION 'TContainerTestCase'}
procedure TContainerTestCase.CheckIs(AInterface: IInterface; AClass: TClass; msg: string);
begin
CheckIs(AInterface as TObject, AClass, msg);
end;
procedure TContainerTestCase.SetUp;
begin
inherited;
fContainer := TContainer.Create;
end;
procedure TContainerTestCase.TearDown;
begin
fContainer.Free;
inherited;
end;
{$ENDREGION}
{$REGION 'TTestGlobalContainer'}
{$IFDEF AUTOREFCOUNT}
procedure TTestGlobalContainer.TestGlobalContainerAssignToVariable;
var AContainer: TContainer;
begin
AContainer := GlobalContainer;
CheckEquals(2, TObjectAccess(AContainer).FRefCount);
end;
procedure TTestGlobalContainer.TestGlobalContainerDirectUse;
begin
CheckEquals(1, TObjectAccess(GlobalContainer).FRefCount);
end;
procedure TTestGlobalContainer.TestServiceLocatorAssignToVariable;
var ALocator: TServiceLocator;
begin
ALocator := ServiceLocator;
CheckEquals(2, TObjectAccess(ALocator).FRefCount);
end;
procedure TTestGlobalContainer.TestServiceLocatorDirectUse;
begin
CheckEquals(1, TObjectAccess(ServiceLocator).FRefCount);
end;
{$ENDIF}
{$ENDREGION}
{$REGION 'TTestEmptyContainer'}
procedure TTestEmptyContainer.TestResolveUnknownInterfaceService;
begin
ExpectedException := EResolveException;
fContainer.Resolve<INameService>;
end;
//procedure TTestEmptyContainer.TestResolveUnknownClassService;
//begin
// ExpectedException := EResolveException;
// fContainer.Resolve<TFoo2>;
//end;
procedure TTestEmptyContainer.TestRegisterNonGuidInterfaceService;
begin
ExpectedException := ERegistrationException;
fContainer.RegisterType<TNonGuid>.Implements<INonGuid>;
end;
procedure TTestEmptyContainer.TestRegisterTwoNamedDifferentServices;
var
nameService: INameService;
ageService: IAgeService;
begin
fContainer.RegisterType<TNameService>.Implements<INameService>;
fContainer.RegisterType<TNameAgeComponent>.Implements<IAgeService>;
fContainer.Build;
nameService := fContainer.Resolve<INameService>;
CheckTrue(nameService is TNameService);
ageService := fContainer.Resolve<IAgeService>;
CheckTrue(ageService is TNameAgeComponent);
end;
procedure TTestEmptyContainer.TestRegisterTwoUnnamedServicesExplicit;
var
service: INameService;
begin
fContainer.RegisterType<TNameService>.Implements<INameService>;
fContainer.RegisterType<TAnotherNameService>.Implements<INameService>;
fContainer.Build;
service := fContainer.Resolve<INameService>;
CheckTrue(service is TAnotherNameService);
end;
procedure TTestEmptyContainer.TestRegisterTwoUnnamedServicesImplicit;
var
service: INameService;
begin
fContainer.RegisterType<TNameService>;
fContainer.RegisterType<TAnotherNameService>;
fContainer.Build;
service := fContainer.Resolve<INameService>;
CheckTrue(service is TAnotherNameService);
end;
procedure TTestEmptyContainer.TestRegisterGenericInterfaceService;
begin
ExpectedException := ERegistrationException;
fContainer.RegisterType<TNonGuid<TObject>>.Implements<INonGuid<TObject>>;
end;
procedure TTestEmptyContainer.TestRegisterUnassignableService;
begin
ExpectedException := ERegistrationException;
fContainer.RegisterType<TContainer>.Implements<IDispatch>;
end;
procedure TTestEmptyContainer.TestResolveAll;
var
services: TArray<INameService>;
begin
services := fContainer.ResolveAll<INameService>;
CheckEquals(0, Length(services));
end;
procedure TTestEmptyContainer.TestResolveAllNonGeneric;
var
services: TArray<TValue>;
begin
services := fContainer.ResolveAll(TypeInfo(INameService));
CheckEquals(0, Length(services));
end;
procedure TTestEmptyContainer.TestResolveReturnsUnnamedService;
var
service: INameService;
begin
fContainer.RegisterType<TNameService>.Implements<INameService>;
fContainer.RegisterType<TAnotherNameService>.Implements<INameService>('some');
fContainer.Build;
service := fContainer.Resolve<INameService>;
CheckTrue(service is TNameService, 'service should be a TNameService instance.');
end;
{$ENDREGION}
{$REGION 'TTestSimpleContainer'}
procedure TTestSimpleContainer.TestInterfaceService;
var
service: INameService;
begin
fContainer.RegisterType<TNameService>.Implements<INameService>;
fContainer.Build;
service := fContainer.Resolve<INameService>;
try
CheckNotNull(service, 'service should not be nil.');
CheckTrue(service is TNameService, 'service should be a TNameService instance.');
CheckEquals(TNameService.NameString, service.Name);
finally
{$IFNDEF AUTOREFCOUNT}
fContainer.Release(service);
{$ENDIF}
service := nil;
end;
end;
procedure TTestSimpleContainer.TestIssue13;
begin
fContainer.RegisterType<TNameService>.Implements<INameService>.AsSingleton;
fContainer.Build;
Pass;
end;
procedure TTestSimpleContainer.TestAbstractClassService;
var
service: TAgeServiceBase;
begin
fContainer.RegisterType<TAgeServiceImpl>.Implements<TAgeServiceBase>;
fContainer.Build;
service := fContainer.Resolve<TAgeServiceBase>;
try
CheckIs(service, TAgeServiceImpl, 'service should be a TNameService instance.');
CheckEquals(TAgeServiceImpl.DefaultAge, service.Age);
finally
{$IFNDEF AUTOREFCOUNT}
fContainer.Release(service);
{$ELSE}
service := nil;
{$ENDIF}
end;
end;
procedure TTestSimpleContainer.TestServiceSameAsComponent;
var
service: TAgeServiceBase;
begin
fContainer.RegisterType<TAgeServiceImpl>;
fContainer.Build;
service := fContainer.Resolve<TAgeServiceImpl>;
try
CheckNotNull(service, 'service should not be null.');
CheckEquals(TAgeServiceImpl.DefaultAge, service.Age);
finally
{$IFNDEF AUTOREFCOUNT}
fContainer.Release(service);
{$ELSE}
service := nil;
{$ENDIF}
end;
end;
procedure TTestSimpleContainer.TestBootstrap;
var
component: TBootstrapComponent;
begin
fContainer.RegisterType<TNameService>.Implements<INameService>.AsSingleton;
fContainer.RegisterType<TAgeServiceImpl>.Implements<TAgeServiceBase>.AsSingleton;
fContainer.RegisterType<TBootstrapComponent>;
fContainer.Build;
component := fContainer.Resolve<TBootstrapComponent>;
try
CheckNotNull(component, 'component should not be nil.');
CheckNotNull(component.NameService, 'NameService');
CheckEquals(TNameService.NameString, component.NameService.Name);
CheckNotNull(component.AgeService, 'AgeService');
CheckEquals(TAgeServiceImpl.DefaultAge, component.AgeService.Age);
finally
{$IFNDEF AUTOREFCOUNT}
fContainer.Release(component);
{$ELSE}
component := nil;
{$ENDIF}
end;
end;
type
TAbstractMethodsTest = class
public
procedure FooBar; virtual; abstract;
end;
{$IFDEF DELPHIXE_UP}
procedure TTestSimpleContainer.TestClassContainsAbstractMethods;
var
logger: Mock<ILogger>;
begin
fContainer.Kernel.Logger := logger;
fContainer.RegisterType<TAbstractMethodsTest>;
fContainer.Build;
logger.Received(1).Warn(Arg.IsAny<string>);
Pass;
end;
{$ENDIF}
procedure TTestSimpleContainer.TestSingleton;
var
obj1, obj2: TAgeServiceBase;
begin
fContainer.RegisterType<TAgeServiceImpl>
.Implements<TAgeServiceBase>
.AsSingleton;
fContainer.Build;
obj1 := fContainer.Resolve<TAgeServiceBase>;
obj2 := fContainer.Resolve<TAgeServiceBase>;
try
CheckNotNull(obj1, 'obj1 should not be nil');
CheckNotNull(obj2, 'obj2 should not be nil');
CheckSame(obj1, obj2, 'obj1 should be the same as obj2.');
finally
{$IFNDEF AUTOREFCOUNT}
fContainer.Release(obj1);
try
// might raise an exception because ClassType is nil with FastMM4 full debug
fContainer.Release(obj2);
except
end;
{$ELSE}
obj1 := nil;
obj2 := nil;
{$ENDIF}
end;
end;
procedure TTestSimpleContainer.TestTransient;
var
obj1, obj2: TAgeServiceBase;
begin
fContainer.RegisterType<TAgeServiceImpl>
.Implements<TAgeServiceBase>;
fContainer.Build;
obj1 := fContainer.Resolve<TAgeServiceBase>;
obj2 := fContainer.Resolve<TAgeServiceBase>;
try
CheckNotNull(obj1, 'obj1 should not be nil');
CheckNotNull(obj2, 'obj2 should not be nil');
CheckTrue(obj1 <> obj2, 'obj1 should not be the same as obj2.');
finally
{$IFNDEF AUTOREFCOUNT}
fContainer.Release(obj1);
fContainer.Release(obj2);
{$ELSE}
obj1 := nil;
obj2 := nil;
{$ENDIF}
end;
end;
type
TTestSingletonThread = class(TThread)
protected
fContainer: TContainer;
fService1: INameService;
fService2: INameService;
procedure Execute; override;
public
constructor Create(container: TContainer);
property Service1: INameService read fService1;
property Service2: INameService read fService2;
end;
{ TTestSingletonThread }
constructor TTestSingletonThread.Create(container: TContainer);
begin
inherited Create(False);
fContainer := container;
end;
procedure TTestSingletonThread.Execute;
begin
fService1 := fContainer.Resolve<INameService>;
fService2 := fContainer.Resolve<INameService>;
end;
procedure TTestSimpleContainer.TestPerThread;
var
thread1, thread2: TTestSingletonThread;
begin
fContainer.RegisterType<TNameService>
.Implements<INameService>
.AsSingletonPerThread;
fContainer.Build;
thread1 := TTestSingletonThread.Create(fContainer);
thread2 := TTestSingletonThread.Create(fContainer);
try
thread1.WaitFor;
thread2.WaitFor;
CheckTrue(thread1.Service1 is TNameService, 'thread1.Service1 should be TNameService.');
CheckTrue(thread2.Service1 is TNameService, 'thread2.Service1 should be TNameService.');
CheckSame(thread1.Service1, thread1.Service2, 'thread1');
CheckSame(thread2.Service1, thread2.Service2, 'thread2');
CheckTrue(thread1.Service1 <> thread2.Service2, 'thread1 and thread2 should own different instances.');
finally
thread1.Free;
thread2.Free;
end;
end;
procedure TTestSimpleContainer.TestPooled;
var
service1, service2, service3: INameService;
count: Integer;
begin
count := 0;
fContainer.RegisterType<TNameService>
.Implements<INameService>
.DelegateTo(
function: TNameService
begin
Result := TNameService.Create;
Inc(count);
end)
.AsPooled(2, 2);
fContainer.Build;
CheckEquals(0, count); // pool did not create any instances yet
service1 := fContainer.Resolve<INameService>;
CheckEquals(2, count); // pool created the minimum number of instances upon first request
service2 := fContainer.Resolve<INameService>;
service3 := fContainer.Resolve<INameService>;
CheckEquals(3, count); // pool created one additional instance
service3 := nil;
service2 := nil;
service1 := nil;
service1 := fContainer.Resolve<INameService>; // pool collects unused instances up to maximum count
service2 := fContainer.Resolve<INameService>;
CheckEquals(3, count);
service3 := fContainer.Resolve<INameService>; // pool creates a new instance again
CheckEquals(4, count);
end;
procedure TTestSimpleContainer.TestPooledRefCountedInterface;
var
service1, service2, service3: INameService;
count: Integer;
begin
count := 0;
fContainer.RegisterType<TCustomNameService>
.Implements<INameService>
.DelegateTo(
function: TCustomNameService
begin
Result := TCustomNameService.Create;
Inc(count);
end)
.AsPooled(2, 2);
fContainer.Build;
CheckEquals(0, count); // pool did not create any instances yet
service1 := fContainer.Resolve<INameService>;
CheckEquals(2, count); // pool created the minimum number of instances upon first request
service2 := fContainer.Resolve<INameService>;
service3 := fContainer.Resolve<INameService>;
CheckEquals(3, count); // pool created one additional instance
service3 := nil;
service2 := nil;
service1 := nil;
service1 := fContainer.Resolve<INameService>; // pool collects unused instances up to maximum count
service2 := fContainer.Resolve<INameService>;
CheckEquals(3, count);
service3 := fContainer.Resolve<INameService>; // pool creates a new instance again
CheckEquals(4, count);
end;
procedure TTestSimpleContainer.TestRecordConstructorNotConsidered;
begin
fContainer.RegisterType<Lazy<INameService>>.DelegateTo(
function: Lazy<INameService>
begin
end);
// Lazy<T> has a constructor which the TConstructorInspector mistakenly inspected
fContainer.Build;
Pass;
end;
procedure TTestSimpleContainer.TestRecyclable;
var
service1, service2: IAnotherService;
instance: Pointer;
begin
fContainer.RegisterType<TRecyclableComponent>.AsPooled(2, 2);
fContainer.Build;
service1 := fContainer.Resolve<IAnotherService>;
service2 := fContainer.Resolve<IAnotherService>;
CheckTrue(service2 is TRecyclableComponent, 'Unknown component');
instance := TRecyclableComponent(service2); // remember second because the first will be returned again later
CheckTrue(TRecyclableComponent(instance).IsInitialized, 'IsInitialized');
CheckFalse(TRecyclableComponent(instance).IsRecycled, 'IsRecycled');
service1 := nil;
service2 := nil;
service1 := fContainer.Resolve<IAnotherService>; // pool has no available and collects all unused
CheckFalse(TRecyclableComponent(instance).IsInitialized, 'IsInitialized');
CheckTrue(TRecyclableComponent(instance).IsRecycled, 'IsRecycled');
end;
procedure TTestSimpleContainer.TestDisposable;
// place in a separate call to generate finalization around returned
// TRegistration
procedure Register;
begin
fContainer.RegisterType<TDisposableComponent>.AsSingleton;
end;
var
service: IAnotherService;
disposed: Boolean;
component: TDisposableComponent;
begin
Register;
fContainer.Build;
service := fContainer.Resolve<IAnotherService>;
component:=(service as TDisposableComponent);
component.OnDispose :=
procedure
begin
disposed := True;
end;
service := nil;
{$IFDEF AUTOREFCOUNT}
component := nil;
{$ENDIF}
disposed := False;
FreeAndNil(fContainer);
CheckTrue(disposed);
end;
type
TTestComponent = class(TComponent);
TTestComponent2 = class(TComponent)
private
fConstructorCalled: Boolean;
public
constructor Create(owner: TComponent); override;
end;
constructor TTestComponent2.Create(owner: TComponent);
begin
inherited;
fConstructorCalled := True;
end;
procedure TTestSimpleContainer.TestResolveComponentDoesCallOverriddenConstructor;
var
obj: TTestComponent2;
begin
fContainer.RegisterType<TTestComponent2>;
fContainer.Build;
obj := fContainer.Resolve<TTestComponent2>;
try
CheckIs(obj, TTestComponent2);
CheckTrue(obj.fConstructorCalled);
CheckNull(obj.Owner);
finally
obj.Free;
end;
end;
procedure TTestSimpleContainer.TestResolveComponentDoesNotFallbackToTObject;
var
obj: TComponent;
begin
fContainer.RegisterType<TTestComponent>;
fContainer.Build;
obj := fContainer.Resolve<TTestComponent>;
try
CheckIs(obj, TTestComponent);
Check(obj.ComponentStyle = [csInheritable]);
CheckNull(obj.Owner);
finally
obj.Free;
end;
end;
procedure TTestSimpleContainer.TestResolveFuncWithTwoTypes;
begin
fContainer.RegisterType<TNameService>;
fContainer.Build;
CheckException(EResolveException,
procedure
begin
fContainer.Resolve<TFunc<IAgeService, INameService>>;
end);
end;
procedure TTestSimpleContainer.TestResolveUnknownClasses;
var
factory: ISomeFactory;
begin
fContainer.RegisterType<ISomeService, TSomeService>;
fContainer.RegisterType<ISomeFactory, TSomeFactory>;
fContainer.Build;
factory := fContainer.Resolve<ISomeFactory>;
Pass;
end;
procedure TTestSimpleContainer.TestInitializable;
var
service: IAnotherService;
begin
fContainer.RegisterType<TInitializableComponent>;
fContainer.Build;
service := fContainer.Resolve<IAnotherService>;
CheckTrue(service is TInitializableComponent, 'Unknown component.');
CheckTrue(TInitializableComponent(service).IsInitialized, 'IsInitialized');
end;
procedure TTestSimpleContainer.TestIssue41_DifferentLifetimes;
var
service1, service2: INameService;
begin
fContainer.RegisterType<TDynamicNameService>.Implements<INameService>;
fContainer.RegisterType<TDynamicNameService>.Implements<IAnotherNameService>.AsSingleton;
fContainer.Build;
service1 := fContainer.Resolve<INameService>;
service2 := fContainer.Resolve<IAnotherNameService>;
Check((service1 as TObject) <> (service2 as TObject), 'resolved services should be different');
end;
procedure TTestSimpleContainer.TestIssue41_DifferentName;
var
service: INameService;
begin
fContainer.RegisterType<TDynamicNameService>.Implements<INameService>('first').DelegateTo(
function: TDynamicNameService
begin
Result := TDynamicNameService.Create('first');
end
);
fContainer.RegisterType<TDynamicNameService>.Implements<INameService>('second').DelegateTo(
function: TDynamicNameService
begin
Result := TDynamicNameService.Create('second');
end
);
fContainer.Build;
service := fContainer.Resolve<INameService>('second');
CheckEquals('second', service.Name, 'resolving of service "second" failed');
service := fContainer.Resolve<INameService>('first');
CheckEquals('first', service.Name, 'resolving of service "first" failed');
end;
procedure TTestSimpleContainer.TestIssue41_DifferentService;
var
service: INameService;
anotherService: IAnotherNameService;
begin
fContainer.RegisterType<TDynamicNameService>.Implements<INameService>.DelegateTo(
function: TDynamicNameService
begin
Result := TDynamicNameService.Create('first');
end
);
fContainer.RegisterType<TDynamicNameService>.Implements<IAnotherNameService>.DelegateTo(
function: TDynamicNameService
begin
Result := TDynamicNameService.Create('second');
end
);
fContainer.Build;
anotherService := fContainer.Resolve<IAnotherNameService>;
CheckEquals('second', anotherService.Name, 'resolving of service "second" failed');
service := fContainer.Resolve<INameService>;
CheckEquals('first', service.Name, 'resolving of service "first" failed');
end;
procedure TTestSimpleContainer.TestIssue49;
var
count: Integer;
obj: TNameServiceWithAggregation;
begin
fContainer.RegisterType<TNameServiceWithAggregation>.Implements<INameService>
.InjectField('fAgeService').InjectField('fAgeService')
.InjectProperty('AgeService').InjectProperty('AgeService')
.InjectMethod('Init').InjectMethod('Init');
fContainer.RegisterType<TNameAgeComponent>.Implements<IAgeService>.DelegateTo(
function: TNameAgeComponent
begin
Result := TNameAgeComponent.Create;
Inc(count);
end);
fContainer.Build;
fContainer.Build;
count := 0;
obj := fContainer.Resolve<INameService> as TNameServiceWithAggregation;
CheckEquals(2, count); // field and property
CheckEquals(1, obj.MethodCallCount);
end;
procedure TTestSimpleContainer.TestIssue50;
var
count: Integer;
obj: TNameServiceWithAggregation;
begin
fContainer.RegisterType<TNameServiceWithAggregation>.Implements<INameService>.DelegateTo(
function: TNameServiceWithAggregation
begin
Result := TNameServiceWithAggregation.Create;
end);
fContainer.RegisterType<TNameAgeComponent>.Implements<IAgeService>.DelegateTo(
function: TNameAgeComponent
begin
Result := TNameAgeComponent.Create;
Inc(count);
end);
fContainer.Build;
count := 0;
obj := fContainer.Resolve<INameService> as TNameServiceWithAggregation;
CheckEquals(2, count); // field and property
CheckEquals(1, obj.MethodCallCount);
end;
{$ENDREGION}
{$REGION 'TTestDifferentImplementations'}
procedure TTestDifferentServiceImplementations.SetUp;
begin
inherited SetUp;
fContainer.RegisterType<TNameService>
.Implements<INameService>('default')
.AsSingleton;
fContainer.RegisterType<TAnotherNameService>
.Implements<INameService>('another');
fContainer.Build;
fNameService := fContainer.Resolve<INameService>('default');
fAnotherNameService := fContainer.Resolve<INameService>('another');
fServices := fContainer.ResolveAll<INameService>;
fServiceValues := fContainer.ResolveAll(TypeInfo(INameService));
end;
procedure TTestDifferentServiceImplementations.TearDown;
begin
{$IFNDEF AUTOREFCOUNT}
fContainer.Release(fAnotherNameService);
{$ENDIF}
fAnotherNameService := nil;
{$IFNDEF AUTOREFCOUNT}
fContainer.Release(fNameService);
{$ENDIF}
fNameService := nil;
fServices := Default(TArray<INameService>);
fServiceValues := Default(TArray<TValue>);
inherited TearDown;
end;
procedure TTestDifferentServiceImplementations.TestNameService;
begin
CheckNotNull(fNameService, 'fNameService should not be nil.');
CheckTrue(fNameService is TNameService, 'fNameService should be an instance of TNameService.');
CheckEquals(TNameService.NameString, fNameService.Name);
end;
procedure TTestDifferentServiceImplementations.TestAnotherNameService;
begin
CheckNotNull(fAnotherNameService, 'fAnotherNameService should not be nil.');
CheckTrue(fAnotherNameService is TAnotherNameService, 'fAnotherNameService should be an instance of TAnotherNameService.');
CheckEquals(TAnotherNameService.NameString, fAnotherNameService.Name);
end;
procedure TTestDifferentServiceImplementations.TestResolveAll;
begin
CheckEquals(2, Length(fServices), 'Count of fServices should be 2.');
CheckTrue(fServices[0] is TNameService);
CheckTrue(fServices[1] is TAnotherNameService);
end;
procedure TTestDifferentServiceImplementations.TestResolveAllNonGeneric;
begin
CheckEquals(2, Length(fServiceValues), 'Count of fServiceValues should be 2.');
CheckTrue((fServiceValues[0].AsType<INameService>) is TNameService);
CheckTrue((fServiceValues[1].AsType<INameService>) is TAnotherNameService);
end;
procedure TTestDifferentServiceImplementations.TestUnsatisfiedDependency;
begin
ExpectedException := EResolveException;
fContainer.Resolve<INameService>;
end;
{$ENDREGION}
{$REGION 'TTestActivatorDelegate'}
procedure TTestActivatorDelegate.SetUp;
begin
inherited SetUp;
fExpectedInteger := 26;
fExpectedString := 'String';
fContainer.RegisterType<TNameService>
.Implements<INameService>
.AsSingleton;
fContainer.RegisterType<TPrimitiveComponent>
.Implements<IPrimitive>
.DelegateTo(
function: TPrimitiveComponent
begin
Result := TPrimitiveComponent.Create(
fContainer.Resolve<INameService>,
fExpectedInteger,
fExpectedString
);
end
);
fContainer.Build;
fPrimitive := fContainer.Resolve<IPrimitive>;
CheckNotNull(fPrimitive, 'fPrimitive should not be nil.');
CheckNotNull(fPrimitive.NameService, 'fPrimitive.NameService should not be nil.');
end;
procedure TTestActivatorDelegate.TestNameService;
begin
CheckNotNull(fPrimitive.NameService, 'NameService should not be nil.');
CheckTrue(fPrimitive.NameService is TNameService, 'Unexpected type.');
CheckEquals(TNameService.NameString, fPrimitive.NameService.Name);
end;
procedure TTestActivatorDelegate.TearDown;
begin
inherited;
fPrimitive := nil;
fExpectedString := '';
end;
procedure TTestActivatorDelegate.TestIntegerArgument;
begin
CheckEquals(fExpectedInteger, fPrimitive.IntegerArg);
end;
procedure TTestActivatorDelegate.TestStringArgument;
begin
CheckEquals(fExpectedString, fPrimitive.StringArg);
end;
{$ENDREGION}
{$REGION 'TTestTypedInjections'}
procedure TTypedInjectionTestCase.SetUp;
begin
inherited SetUp;
DoRegisterComponents;
fContainer.Build;
fNameService := fContainer.Resolve<INameService>;
CheckIs(fNameService, TNameService, 'fNameService should be TNameService.');
CheckEquals(TNameService.NameString, fNameService.Name, 'fNameService.Name is wrong.');
fInjectionExplorer := fContainer.Resolve<IInjectionExplorer>;
end;
procedure TTypedInjectionTestCase.TearDown;
begin
{$IFNDEF AUTOREFCOUNT}
fContainer.Release(fInjectionExplorer);
fContainer.Release(fNameService);
{$ENDIF}
fInjectionExplorer := nil;
fNameService := nil;
inherited TearDown;
end;
procedure TTypedInjectionTestCase.TestConstructorInjection;
begin
CheckSame(fNameService, fInjectionExplorer.ConstructorInjection);
end;
procedure TTypedInjectionTestCase.TestPropertyInjection;
begin
CheckSame(fNameService, fInjectionExplorer.PropertyInjection);
end;
procedure TTypedInjectionTestCase.TestMethodInjection;
begin
CheckSame(fNameService, fInjectionExplorer.MethodInjection);
end;
procedure TTypedInjectionTestCase.TestFieldInjection;
begin
CheckSame(fNameService, fInjectionExplorer.FieldInjection);
end;
{$ENDREGION}
{$REGION 'TTestTypedInjectionByCoding'}
procedure TTestTypedInjectionByCoding.DoRegisterComponents;
begin
fContainer.RegisterType<TNameService>
.Implements<INameService>
.AsSingleton;
fContainer.RegisterType<TInjectionExplorer>
.Implements<IInjectionExplorer>
.InjectConstructor([TypeInfo(INameService)])
.InjectProperty('PropertyInjection')
.InjectMethod('SetMethodInjection')
.InjectField('fFieldInjection');
end;
{$ENDREGION}
{$REGION 'TTestTypedInjectionsByAttribute'}
procedure TTestTypedInjectionsByAttribute.DoRegisterComponents;
begin
fContainer.RegisterType<TNameService>
.Implements<INameService>
.AsSingleton;
fContainer.RegisterType<TInjectionExplorerComponent>
.Implements<IInjectionExplorer>;
end;
{$ENDREGION}
{$REGION 'TTestDirectCircularDependency'}
procedure TTestDirectCircularDependency.SetUp;
begin
inherited SetUp;
fContainer.RegisterType<TCircularDependencyChicken>.Implements<IChicken>;
fContainer.Build;
end;
procedure TTestDirectCircularDependency.TestResolve;
var
chicken: IChicken;
begin
ExpectedException := ECircularDependencyException;
chicken := fContainer.Resolve<IChicken>;
Pass;
end;
{$ENDREGION}
{$REGION 'TTestCrossedCircularDependency'}
procedure TTestCrossedCircularDependency.SetUp;
begin
inherited SetUp;
fContainer.RegisterType<TCircularDependencyChicken>.Implements<IChicken>;
fContainer.RegisterType<TEgg>.Implements<IEgg>;
fContainer.Build;
end;
procedure TTestCrossedCircularDependency.TestResolveChicken;
var
chicken: IChicken;
begin
ExpectedException := ECircularDependencyException;
chicken := fContainer.Resolve<IChicken>;
end;
procedure TTestCrossedCircularDependency.TestResolveEgg;
var
egg: IEgg;
begin
ExpectedException := ECircularDependencyException;
egg := fContainer.Resolve<IEgg>;
end;
{$ENDREGION}
{$REGION 'TTestCircularReferenceLazySingleton'}
procedure TTestCircularReferenceLazySingleton.TestResolveLazySingleton;
var
chicken: IChicken;
begin
fContainer.RegisterType<TChicken>.AsSingleton;
fContainer.RegisterType<TEggLazyChicken>;
fContainer.Build;
chicken := fContainer.Resolve<IChicken>;
CheckSame(chicken, chicken.Egg.Chicken);
chicken.Egg := nil;
end;
{$ENDREGION}
{$REGION 'TTestPerResolve'}
procedure TTestPerResolve.TestResolveCircularDependency;
var
chicken: IChicken;
begin
fContainer.RegisterType<IChicken, TChicken>
.InjectConstructor
.PerResolve
.InjectProperty('Egg');
fContainer.RegisterType<IEgg, TEgg>;
fContainer.Build;
chicken := fContainer.Resolve<IChicken>;
CheckSame(chicken, chicken.Egg.Chicken);
chicken.Egg := nil;
end;
{$ENDREGION}
{$REGION 'TNamedInjectionsTestCase'}
procedure TNamedInjectionsTestCase.DoRegisterComponents;
begin
fContainer.RegisterType<TNameService>
.Implements<INameService>('default')
.AsSingleton;
fContainer.RegisterType<TAnotherNameService>
.Implements<INameService>('another')
.AsSingleton;
end;
procedure TNamedInjectionsTestCase.SetUp;
begin
inherited SetUp;
DoRegisterComponents;
fContainer.Build;
fExplorer := fContainer.Resolve<IInjectionExplorer>;
end;
procedure TNamedInjectionsTestCase.TearDown;
begin
inherited;
fExplorer := nil;
end;
procedure TNamedInjectionsTestCase.TestConstructorInjection;
begin
CheckNotNull(fExplorer.ConstructorInjection);
CheckEquals(TNameService.NameString, fExplorer.ConstructorInjection.Name);
end;
procedure TNamedInjectionsTestCase.TestPropertyInjection;
begin
CheckNotNull(fExplorer.PropertyInjection);
CheckEquals(TAnotherNameService.NameString, fExplorer.PropertyInjection.Name);
end;
procedure TNamedInjectionsTestCase.TestMethodInjection;
begin
CheckNotNull(fExplorer.MethodInjection);
CheckEquals(TAnotherNameService.NameString, fExplorer.MethodInjection.Name);
end;
procedure TNamedInjectionsTestCase.TestFieldInjection;
begin
CheckNotNull(fExplorer.FieldInjection);
CheckEquals(TNameService.NameString, fExplorer.FieldInjection.Name);
end;
{$ENDREGION}
{$REGION 'TTestNamedInjectionsByCoding'}
procedure TTestNamedInjectionsByCoding.DoRegisterComponents;
begin
inherited DoRegisterComponents;
fContainer.RegisterType<TInjectionExplorer>
.Implements<IInjectionExplorer>
.InjectConstructor(['default'])
.InjectProperty('PropertyInjection', 'another')
.InjectMethod('SetMethodInjection', ['another'])
.InjectField('fFieldInjection', 'default')
.AsSingleton;
end;
{$ENDREGION}
{$REGION 'TTestNamedInjectionsByAttribute'}
procedure TTestNamedInjectionsByAttribute.DoRegisterComponents;
begin
inherited DoRegisterComponents;
fContainer.RegisterType<TInjectionComponent>
.Implements<IInjectionExplorer>;
end;
{$ENDREGION}
{$REGION 'TTestImplementsDifferentServices'}
procedure TTestImplementsDifferentServices.SetUp;
begin
inherited SetUp;
fContainer.RegisterType<TNameService>
.Implements<INameService>('another');
fContainer.RegisterType<TNameAgeComponent>
.Implements<INameService>('default')
.Implements<IAgeService>
.AsSingleton;
fContainer.Build;
fNameService := fContainer.Resolve<INameService>('default');
fAgeService := fContainer.Resolve<IAgeService>;
CheckNotNull(fNameService, 'fNameService should not be nil.');
CheckNotNull(fAgeService, 'fAgeService should not be nil.');
end;
procedure TTestImplementsDifferentServices.TearDown;
begin
{$IFNDEF AUTOREFCOUNT}
fContainer.Release(fAgeService);
fContainer.Release(fNameService);
{$ENDIF}
fAgeService := nil;
fNameService := nil;
inherited TearDown;
end;
procedure TTestImplementsDifferentServices.TestNameService;
begin
Check(fNameService is TNameAgeComponent);
CheckEquals(TNameAgeComponent.NameString, fNameService.Name);
end;
procedure TTestImplementsDifferentServices.TestAgeService;
begin
Check(fAgeService is TNameAgeComponent);
CheckEquals(TNameAgeComponent.DefaultAge, fAgeService.Age);
end;
{$ENDREGION}
{$REGION 'TTestImplementsAttribute'}
type
IS1 = interface
['{E6DE68D5-988C-4817-880E-58903EE8B78C}']
end;
IS2 = interface
['{0DCC1BD5-28C1-4A94-8667-AC72BA25C682}']
end;
TS1 = class(TInterfacedObject, IS1)
end;
[Implements(TypeInfo(IS1), 'b')]
[Implements(TypeInfo(IS2))]
TS2 = class(TInterfacedObject, IS1, IS2)
end;
procedure TTestImplementsAttribute.TestImplements;
var
s1: IS1;
s2: IS2;
begin
fContainer.RegisterType<TS1>.Implements<IS1>('a');
fContainer.RegisterType<TS2>;
fContainer.Build;
s1 := fContainer.Resolve<IS1>('a');
CheckTrue(s1 is TS1, 'a');
s1 := fContainer.Resolve<IS1>('b');
CheckTrue(s1 is TS2, 'b');
s2 := fContainer.Resolve<IS2>;
CheckTrue(s2 is TS2, 's2');
end;
{$ENDREGION}
{$REGION 'TTestRegisterInterfaces'}
type
TComplex = class(TNameAgeComponent, IAnotherService)
end;
procedure TTestRegisterInterfaces.TestOneService;
var
service: INameService;
begin
fContainer.RegisterType<TNameService>;
fContainer.Build;
service := fContainer.Resolve<INameService>;
CheckTrue(service is TNameService);
end;
procedure TTestRegisterInterfaces.TestParentInterface;
var
service: INameService;
begin
fContainer.RegisterType<TDynamicNameService>.Implements<IAnotherNameService>('another');
fContainer.Build;
service := fContainer.Resolve<INameService>('another');
CheckIs(service, TDynamicNameService);
end;
procedure TTestRegisterInterfaces.TestTwoServices;
var
s1: INameService;
s2: IAgeService;
begin
fContainer.RegisterType<TNameAgeComponent>;
fContainer.Build;
s1 := fContainer.Resolve<INameService>;
s2 := fContainer.Resolve<IAgeService>;
CheckTrue(s1 is TNameAgeComponent, 's1');
CheckTrue(s2 is TNameAgeComponent, 's2');
end;
procedure TTestRegisterInterfaces.TestTwoServicesWithSameName;
var
s1: INameService;
s2: Spring.Tests.Container.Interfaces.INameService;
begin
fContainer.RegisterType<TNameServiceWithTwoInterfaces>;
fContainer.Build;
s1 := fContainer.Resolve<INameService>;
s2 := fContainer.Resolve<Spring.Tests.Container.Interfaces.INameService>;
CheckTrue(s1 is TNameServiceWithTwoInterfaces, 's1');
CheckTrue(s2 is TNameServiceWithTwoInterfaces, 's2');
end;
procedure TTestRegisterInterfaces.TestInheritedService;
var
s1: INameService;
s2: IAgeService;
s3: IAnotherService;
begin
CheckTrue(Assigned(TypeInfo(IAnotherService)));
fContainer.RegisterType<TComplex>;
fContainer.Build;
s1 := fContainer.Resolve<INameService>;
s2 := fContainer.Resolve<IAgeService>;
s3 := fContainer.Resolve<IAnotherService>;
CheckTrue(s1 is TComplex, 's1');
CheckTrue(s2 is TComplex, 's2');
CheckTrue(s3 is TComplex, 's3');
end;
{$ENDREGION}
{$REGION 'TTestDefaultResolve'}
procedure TTestDefaultResolve.TestNoDefault;
begin
StartExpectingException(EResolveException);
fContainer.Resolve<INameService>;
StopExpectingException;
end;
procedure TTestDefaultResolve.TestRegisterDefault;
begin
StartExpectingException(ERegistrationException);
fContainer.RegisterType<INameService, TNameService>.AsDefault<IAgeService>;
StopExpectingException;
end;
procedure TTestDefaultResolve.TestResolve;
var
service: INameService;
begin
fContainer.RegisterType<TNameService>.Implements<INameService>;
fContainer.RegisterType<TAnotherNameService>.Implements<INameService>('another');
fContainer.Build;
service := fContainer.Resolve<INameService>;
CheckEquals('Name', service.Name);
end;
procedure TTestDefaultResolve.TestResolveDependency;
var
component: TBootstrapComponent;
begin
fContainer.RegisterType<TNameService>.Implements<INameService>;
fContainer.RegisterType<TAnotherNameService>.Implements<INameService>('another');
fContainer.RegisterType<TBootstrapComponent>.AsSingleton;
fContainer.Build;
component := fContainer.Resolve<TBootstrapComponent>;
CheckEquals('Name', component.NameService.Name);
end;
{$ENDREGION}
{$REGION 'TTestInjectionByValue'}
procedure TTestInjectionByValue.TestInjectField;
begin
fContainer.RegisterType<TPrimitiveComponent>.Implements<IPrimitive>
.InjectField('fNameService', TValue.From<INameService>(TNameService.Create));
fContainer.Build;
CheckTrue(fContainer.Resolve<IPrimitive>.NameService <> nil)
end;
{$ENDREGION}
{$REGION 'TTestResolverOverride'}
procedure TTestResolverOverride.SetUp;
begin
inherited;
fDummy := TObject.Create;
end;
procedure TTestResolverOverride.TearDown;
begin
inherited;
fDummy.Free;
end;
procedure TTestResolverOverride.TestResolve;
begin
fContainer.RegisterType<TDynamicNameService>.Implements<INameService>('dynamic');
fContainer.Build;
CheckEquals('test', fContainer.Resolve<INameService>(['test']).Name);
CheckEquals('test', fContainer.Resolve<INameService>('dynamic', ['test']).Name);
CheckEquals('test', fContainer.Resolve<INameService>([TNamedValue.From('test', 'name')]).Name);
end;
procedure TTestResolverOverride.TestResolveWithClass;
begin
fContainer.RegisterType<TDynamicNameService>.Implements<INameService>('dynamic');
fContainer.Build;
CheckEquals(fdummy.ClassName, fContainer.Resolve<INameService>([fDummy]).Name);
CheckEquals(fdummy.ClassName, fContainer.Resolve<INameService>([TNamedValue.From(fDummy, 'obj')]).Name);
end;
procedure TTestResolverOverride.TestResolveWithDependency;
var
service: INameService;
begin
fContainer.RegisterType<TDynamicNameService>.Implements<INameService>('dynamic')
.InjectField('fAgeService');
fContainer.RegisterType<TNameAgeComponent>.Implements<IAgeService>;
fContainer.Build;
service := fContainer.Resolve<INameService>([fDummy]);
CheckEquals(fdummy.ClassName, service.Name);
CheckNotNull((service as TDynamicNameService).AgeService);
service := fContainer.Resolve<INameService>([TNamedValue.From(fDummy, 'obj')]);
CheckEquals(fdummy.ClassName, service.Name);
CheckNotNull((service as TDynamicNameService).AgeService);
end;
procedure TTestResolverOverride.TestResolveWithDependencySubClass;
var
service: INameService;
begin
fContainer.RegisterType<TDynamicNameService>.Implements<INameService>('dynamic')
.InjectField('fAgeService');
fContainer.RegisterType<TNameAgeComponent>.Implements<IAgeService>;
fContainer.Build;
// ctor requires TObject but we pass a sub class
fDummy.Free;
fDummy := TPersistent.Create;
service := fContainer.Resolve<INameService>([TNamedValue.From(fDummy, 'obj')]);
CheckEquals(fdummy.ClassName, service.Name);
CheckNotNull((service as TDynamicNameService).AgeService);
end;
procedure TTestResolverOverride.TestResolveWithMultipleParams;
begin
fContainer.RegisterType<TDynamicNameService>.Implements<INameService>('dynamic');
fContainer.Build;
CheckEquals('test' + fDummy.ClassName, fContainer.Resolve<INameService>(['test', fDummy]).Name);
CheckEquals(fdummy.ClassName, fContainer.Resolve<INameService>([TNamedValue.From(fDummy, 'obj')]).Name);
end;
{$ENDREGION}
{$REGION 'TTestRegisterFactory'}
procedure TTestRegisterInterfaceTypes.TestOneService;
begin
fContainer.RegisterType<INameService>.DelegateTo(
function: INameService
begin
Result := TDynamicNameService.Create('test');
end);
fContainer.Build;
CheckEquals('test', fContainer.Resolve<INameService>.Name);
end;
procedure TTestRegisterInterfaceTypes.TestOneServiceAsSingleton;
var
count: Integer;
begin
count := 0;
fContainer.RegisterType<INameService>.DelegateTo(
function: INameService
begin
Result := TDynamicNameService.Create('test');
Inc(count);
end).AsSingleton;
fContainer.Build;
CheckEquals('test', fContainer.Resolve<INameService>.Name);
CheckEquals('test', fContainer.Resolve<INameService>.Name);
CheckEquals(1, count);
end;
procedure TTestRegisterInterfaceTypes.TestOneServiceAsSingletonPerThread;
var
count: Integer;
begin
count := 0;
fContainer.RegisterType<INameService>.DelegateTo(
function: INameService
begin
Result := TDynamicNameService.Create('test');
Inc(count);
end).AsSingletonPerThread;
fContainer.Build;
CheckEquals('test', fContainer.Resolve<INameService>.Name);
CheckEquals('test', fContainer.Resolve<INameService>.Name);
CheckEquals(1, count);
end;
procedure TTestRegisterInterfaceTypes.TestTwoRegistrations;
begin
fContainer.RegisterType<INameService, INameService>('service1').DelegateTo(
function: INameService
begin
Result := TDynamicNameService.Create('service1');
end);
fContainer.RegisterType<INameService, INameService>('service2').DelegateTo(
function: INameService
begin
Result := TDynamicNameService.Create('service2');
end);
fContainer.Build;
CheckEquals('service1', fContainer.Resolve<INameService>('service1').Name);
CheckEquals('service2', fContainer.Resolve<INameService>('service2').Name);
end;
procedure TTestRegisterInterfaceTypes.TestTwoServices;
begin
fContainer.RegisterType<INameService, INameService>.DelegateTo(
function: INameService
begin
Result := TDynamicNameService.Create('test');
end).Implements<IAnotherNameService>('another');
fContainer.Build;
CheckEquals('test', fContainer.Resolve<INameService>.Name);
CheckEquals('test', fContainer.Resolve<IAnotherNameService>.Name);
end;
{$ENDREGION}
{$REGION 'TTestResolveLazy'}
procedure TTestLazyDependencies.PerformChecks;
var
nameService: INameService;
begin
fCalled := False;
nameService := fContainer.Resolve<INameService>('service');
CheckFalse(fCalled);
CheckEquals(TNameService.NameString, nameService.Name);
CheckTrue(fCalled);
end;
procedure TTestLazyDependencies.SetUp;
begin
inherited;
fContainer.RegisterType<INameService>.Implements<INameService>('lazy').DelegateTo(
function: INameService
begin
Result := TNameService.Create;
fCalled := True;
end);
end;
procedure TTestLazyDependencies.TestDependencyTypeIsFunc;
begin
fContainer.RegisterType<TNameServiceLazyWithFunc>.Implements<INameService>('service');
fContainer.Build;
PerformChecks;
end;
{$IFNDEF IOSSIMULATOR}
procedure TTestLazyDependencies.TestDependencyTypeIsInterface;
begin
fContainer.RegisterType<TNameServiceLazyWithInterface>.Implements<INameService>('service');
fContainer.Build;
PerformChecks;
end;
procedure TTestLazyDependencies.TestDependencyTypeIsRecord;
begin
fContainer.RegisterType<TNameServiceLazyWithRecord>.Implements<INameService>('service');
fContainer.Build;
PerformChecks;
end;
{$ENDIF}
type
TTestWithLazySingletonBase = class
private
fA: INameService;
fB: Lazy<INameService>;
public
property A: INameService read fA;
property B: Lazy<INameService> read fB;
end;
TTestWithLazySingletonResolveFirst = class(TTestWithLazySingletonBase)
public
constructor Create(const a: INameService; const b: Lazy<INameService>);
end;
TTestWithLazySingletonResolveLast = class(TTestWithLazySingletonBase)
public
constructor Create(const b: Lazy<INameService>; const a: INameService);
end;
constructor TTestWithLazySingletonResolveFirst.Create(const a: INameService;
const b: Lazy<INameService>);
begin
fA := a;
fB := b;
end;
constructor TTestWithLazySingletonResolveLast.Create(
const b: Lazy<INameService>; const a: INameService);
begin
fA := a;
fB := b;
end;
procedure TTestLazyDependencies.TestDependencyTypeIsSingletonAlreadyInstantiated;
var
test: TTestWithLazySingletonResolveFirst;
begin
fContainer.RegisterType<INameService, TNameService>.AsSingleton;
fContainer.RegisterType<TTestWithLazySingletonResolveFirst>;
fContainer.Build;
test := fContainer.Resolve<TTestWithLazySingletonResolveFirst>;
try
CheckSame(test.A, test.B.Value);
finally
test.Free;
end;
end;
procedure TTestLazyDependencies.TestDependencyTypeIsSingletonNotYetInstantiated;
var
test: TTestWithLazySingletonResolveLast;
begin
fContainer.RegisterType<INameService, TNameService>.AsSingleton;
fContainer.RegisterType<TTestWithLazySingletonResolveLast>;
fContainer.Build;
test := fContainer.Resolve<TTestWithLazySingletonResolveLast>;
try
CheckSame(test.A, test.B.Value);
finally
test.Free;
end;
end;
procedure TTestLazyDependencies.TestResolveLazyOfSingletonCreatedLater;
var
x: Lazy<INameService>;
y: INameService;
begin
fContainer.RegisterType<INameService, TNameService>.AsSingleton;
fContainer.Build;
x := fContainer.Resolve<Lazy<INameService>>;
CheckFalse(x.IsValueCreated);
CheckIs(x.Value, TNameService);
y := fContainer.Resolve<INameService>;
CheckSame(x.Value, y);
end;
{$ENDREGION}
{$REGION 'TTestResolveLazyRecursive'}
procedure TTestLazyDependenciesDetectRecursion.PerformChecks;
var
model: TComponentModel;
begin
model := fContainer.Kernel.Registry.FindOne('service');
fContainer.Kernel.Injector.InjectField(model, 'fNameService', 'service');
ExpectedException := ECircularDependencyException;
inherited;
end;
{$ENDREGION}
{$REGION 'TTestManyDependencies'}
procedure TTestManyDependencies.SetUp;
begin
inherited;
fContainer.RegisterType<ICollectionItem, TCollectionItemA>('a');
fContainer.RegisterType<ICollectionItem, TCollectionItemB>('b');
fContainer.RegisterType<ICollectionItem, TCollectionItemC>('c');
end;
procedure TTestManyDependencies.TestInjectArray;
var
service: ICollectionService;
begin
fContainer.RegisterType<ICollectionService, TCollectionServiceA>;
fContainer.Build;
service := fContainer.Resolve<ICollectionService>;
CheckEquals(3, Length(service.CollectionItems));
CheckIs(service.CollectionItems[0], TCollectionItemA);
CheckIs(service.CollectionItems[1], TCollectionItemB);
CheckIs(service.CollectionItems[2], TCollectionItemC);
end;
procedure TTestManyDependencies.TestInjectArrayOfLazy;
var
service: ICollectionService;
begin
fContainer.RegisterType<ICollectionService, TCollectionServiceC>;
fContainer.Build;
service := fContainer.Resolve<ICollectionService>;
CheckEquals(3, Length(service.CollectionItems));
CheckIs(service.CollectionItems[0], TCollectionItemA);
CheckIs(service.CollectionItems[1], TCollectionItemB);
CheckIs(service.CollectionItems[2], TCollectionItemC);
end;
procedure TTestManyDependencies.TestInjectEnumerable;
var
service: ICollectionService;
begin
fContainer.RegisterType<ICollectionService, TCollectionServiceB>;
fContainer.RegisterType<IInterface, TCollectionServiceB>;
fContainer.Build;
service := fContainer.Resolve<ICollectionService>;
CheckEquals(3, Length(service.CollectionItems));
CheckIs(service.CollectionItems[0], TCollectionItemA);
CheckIs(service.CollectionItems[1], TCollectionItemB);
CheckIs(service.CollectionItems[2], TCollectionItemC);
end;
procedure TTestManyDependencies.TestNoRecursion;
var
service: ICollectionItem;
begin
fContainer.RegisterType<ICollectionItem, TCollectionItemD>;
fContainer.Build;
service := fContainer.Resolve<ICollectionItem>;
CheckIs(service, TCollectionItemD);
CheckEquals(3, Length((service as TCollectionItemD).CollectionItems));
CheckIs((service as TCollectionItemD).CollectionItems[0], TCollectionItemA);
CheckIs((service as TCollectionItemD).CollectionItems[1], TCollectionItemB);
CheckIs((service as TCollectionItemD).CollectionItems[2], TCollectionItemC);
end;
procedure TTestManyDependencies.TestNoRecursion_Issue18;
var
service: ICollectionService;
begin
fContainer.RegisterType<ICollectionItem, TCollectionItemD>;
fContainer.RegisterType<ICollectionService, TCollectionServiceD>;
fContainer.Build;
service := fContainer.Resolve<ICollectionService>;
Pass;
end;
procedure TTestManyDependencies.TestNoRecursion_TwoDifferentModelsWithSameComponentType;
var
service: ICollectionItem;
begin
fContainer.RegisterType<ICollectionItem, TCollectionItemD>('d')
.DelegateTo(
function: TCollectionItemD
begin
Result := TCollectionItemD.Create(nil);
end);
fContainer.RegisterType<ICollectionItem, TCollectionItemD>;
fContainer.Build;
service := fContainer.Resolve<ICollectionItem>;
CheckEquals(4, Length((service as TCollectionItemD).CollectionItems));
end;
procedure TTestManyDependencies.TestRecursion_TwoDifferentModelsWithSameComponentType;
var
service: ICollectionItem;
begin
fContainer.RegisterType<ICollectionItem, TCollectionItemD>('d');
fContainer.RegisterType<ICollectionItem, TCollectionItemD>;
fContainer.Build;
ExpectedException := ECircularDependencyException;
service := fContainer.Resolve<ICollectionItem>;
CheckEquals(4, Length((service as TCollectionItemD).CollectionItems));
end;
procedure TTestManyDependencies.TestResolveArrayOfLazy;
var
services: TArray<Lazy<ICollectionItem>>;
service: Lazy<ICollectionItem>;
begin
fContainer.RegisterType<ICollectionItem, TCollectionItemD>;
fContainer.Build;
services := fContainer.ResolveAll<Lazy<ICollectionItem>>;
CheckEquals(3, Length(services));
CheckIs(services[0].Value, TCollectionItemA);
CheckIs(services[1].Value, TCollectionItemB);
CheckIs(services[2].Value, TCollectionItemC);
service := fContainer.Resolve<Lazy<ICollectionItem>>;
CheckIs(service.Value, TCollectionItemD);
end;
{$ENDREGION}
{$REGION 'TTestDecorators'}
procedure TTestDecorators.RegisterOneDecoratorInitializeIsCalled;
var
service: IAnotherService;
begin
fContainer.RegisterType<IAnotherService, TInitializableComponent>;
fContainer.RegisterDecorator<IAnotherService, TAnotherServiceDecorator>;
fContainer.Build;
service := fContainer.Resolve<IAnotherService>;
CheckIs(service, TAnotherServiceDecorator);
service := (service as TAnotherServiceDecorator).Service;
CheckIs(service, TInitializableComponent);
Check((service as TInitializableComponent).IsInitialized);
end;
procedure TTestDecorators.RegisterOneDecoratorResolveReturnsDecorator;
var
service: IAgeService;
begin
fContainer.RegisterDecorator<IAgeService, TAgeServiceDecorator>;
fContainer.Build;
service := fContainer.Resolve<IAgeService>;
CheckIs(service, TAgeServiceDecorator);
CheckEquals(TNameAgeComponent.DefaultAge, service.Age);
end;
procedure TTestDecorators.RegisterOneDecoratorWithFailingConditionResolvesWithoutDecorator;
var
service: IAgeService;
conditionCalled: Boolean;
begin
conditionCalled := False;
fContainer.RegisterDecorator<IAgeService, TAgeServiceDecorator>(
function(const m: TComponentModel): Boolean
begin
Result := False;
conditionCalled := True;
end);
CheckFalse(conditionCalled);
fContainer.Build;
service := fContainer.Resolve<IAgeService>;
CheckTrue(conditionCalled);
CheckIs(service, TNameAgeComponent);
CheckEquals(TNameAgeComponent.DefaultAge, service.Age);
end;
procedure TTestDecorators.RegisterTwoDecoratorsResolveArrayAllDecorated;
var
services: TArray<IAgeService>;
begin
fContainer.RegisterDecorator<IAgeService, TAgeServiceDecorator>;
fContainer.RegisterDecorator<IAgeService, TAgeServiceDecorator2>;
fContainer.RegisterType<IAgeService, TAgeService>('ageService');
fContainer.Build;
services := fContainer.Resolve<TArray<IAgeService>>;
CheckEquals(2, Length(services));
CheckIs(services[0], TAgeServiceDecorator2);
CheckIs(services[1], TAgeServiceDecorator2);
end;
procedure TTestDecorators.RegisterTwoDecoratorsResolveLazyReturnsLastDecorator;
var
service, service2: IAgeService;
begin
fContainer.RegisterDecorator<IAgeService, TAgeServiceDecorator>;
fContainer.RegisterDecorator<IAgeService, TAgeServiceDecorator2>;
fContainer.RegisterType<IAgeService, TAgeService>('ageService');
fContainer.Build;
service := fContainer.Resolve<IAgeService>('ageService');
CheckIs(service, TAgeServiceDecorator2);
service2 := (service as TAgeServiceDecorator2).AgeService;
CheckIs(service2, TAgeServiceDecorator);
service2 := (service2 as TAgeServiceDecorator).AgeService;
CheckIs(service2, TAgeService);
service2 := (service2 as TAgeService).AgeService;
CheckIs(service2, TAgeServiceDecorator2);
service2 := (service2 as TAgeServiceDecorator2).AgeService;
CheckIs(service2, TAgeServiceDecorator);
service2 := (service2 as TAgeServiceDecorator).AgeService;
CheckIs(service2, TNameAgeComponent);
end;
procedure TTestDecorators.RegisterTwoDecoratorsResolveReturnsLastDecorator;
var
service: IAgeService;
begin
fContainer.RegisterDecorator<IAgeService, TAgeServiceDecorator>;
fContainer.RegisterDecorator<IAgeService, TAgeServiceDecorator2>;
fContainer.Build;
service := fContainer.Resolve<IAgeService>;
CheckIs(service, TAgeServiceDecorator2);
CheckEquals(TNameAgeComponent.DefaultAge, service.Age);
end;
procedure TTestDecorators.RegisterTwoDecoratorsResolveWithParameterReturnsCorrectValue;
var
service: IAgeService;
begin
fContainer.RegisterDecorator<IAgeService, TAgeServiceDecorator>;
fContainer.RegisterDecorator<IAgeService, TAgeServiceDecorator2>;
fContainer.Build;
service := fContainer.Resolve<IAgeService>([42]);
CheckIs(service, TAgeServiceDecorator2);
CheckEquals(42, service.Age);
end;
procedure TTestDecorators.SetUp;
begin
inherited;
fContainer.RegisterType<TNameAgeComponent>;
fContainer.Build;
end;
{$ENDREGION}
end.
| 28.378243 | 125 | 0.772948 |
f19e9801de8dd4a6a5a04e53579c83fe3f08c367 | 133,979 | pas | Pascal | library/support/FHIR.Support.Html.pas | niaz819/fhirserver | fee45e1e57053a776b893dba543f700dd9cb9075 | [
"BSD-3-Clause"
]
| null | null | null | library/support/FHIR.Support.Html.pas | niaz819/fhirserver | fee45e1e57053a776b893dba543f700dd9cb9075 | [
"BSD-3-Clause"
]
| null | null | null | library/support/FHIR.Support.Html.pas | niaz819/fhirserver | fee45e1e57053a776b893dba543f700dd9cb9075 | [
"BSD-3-Clause"
]
| null | null | null | Unit FHIR.Support.Html;
{
Copyright (c) 2017+, 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.
}
Interface
Uses
SysUtils,
FHIR.Support.Base, FHIR.Support.Utilities, FHIR.Support.Stream, FHIR.Support.Collections, FHIR.Support.Xml;
Type
TFslHTMLToken = (ahtNull, ahtWhitespace, ahtComment, ahtIdentifier, ahtNumber,
ahtOpenTag, ahtCloseTag, ahtOpenTagForwardSlash, ahtCloseTagForwardSlash,
ahtOpenTagExclamation, ahtOpenTagQuery, ahtCloseTagQuery, ahtForwardSlash, ahtBackwardSlash, ahtExclamation,
ahtQuery, ahtEquals, ahtPeriod, ahtComma, ahtColon, ahtSemiColon, ahtUnderscore, ahtHyphen,
ahtAmpersand, ahtPercentage, ahtHash, ahtAt, ahtDollar, ahtCaret, ahtAsterisk,
ahtOpenRound, ahtCloseRound, ahtOpenSquare, ahtCloseSquare, ahtOpenBrace, ahtCloseBrace,
ahtPlus, ahtTilde, ahtBackQuote, ahtSingleQuote, ahtDoubleQuote, ahtPipe);
TFslHTMLTokens = Set Of TFslHTMLToken;
Function ToHTMLToken(cChar : Char) : TFslHTMLToken; Overload;
Const
HTMLTOKEN_STRING : Array[TFslHTMLToken] Of String =
('Null', 'Whitespace', 'Comment', 'Identifier', 'Number',
'<', '>', '</', '/>',
'<!', '<?', '?>', '/', '\', '!',
'?', '=', '.', ',', ':', ';', '_', '-',
'&', '%', '#', '@', '$', '^', '*',
'(', ')', '[', ']', '{', '}',
'+', '~', '`', '''', '"', '|');
HTMLTOKEN_SYMBOL_SET = [ahtForwardSlash, ahtBackwardSlash, ahtExclamation,
ahtQuery, ahtEquals, ahtPeriod, ahtComma, ahtColon, ahtSemiColon, ahtUnderscore, ahtHyphen,
ahtAmpersand, ahtPercentage, ahtHash, ahtAt, ahtDollar, ahtCaret, ahtAsterisk,
ahtOpenRound, ahtCloseRound, ahtOpenSquare, ahtCloseSquare, ahtOpenBrace, ahtCloseBrace,
ahtPlus, ahtTilde, ahtBackQuote, ahtSingleQuote, ahtDoubleQuote, ahtPipe];
HTMLTOKEN_BODY_SET = HTMLTOKEN_SYMBOL_SET + [ahtIdentifier, ahtNumber, ahtWhitespace];
Type
TFslCSSValues = Class(TFslStringMatch)
Private
Function GetMatch(Const sKey: String): String;
Procedure SetMatch(Const sKey, sValue: String);
Public
constructor Create; Override;
Property Matches[Const sKey : String] : String Read GetMatch Write SetMatch; Default;
End;
TFslCSSFragment = Class (TFslObject)
Private
FValues : TFslCSSValues;
Public
constructor Create; Override;
destructor Destroy; Override;
Function Link : TFslCSSFragment;
Function Clone : TFslCSSFragment;
Procedure Assign(oSource : TFslObject); Override;
Property Values : TFslCSSValues Read FValues;
End;
TFslCSSFragments = Class(TFslObjectList)
Private
Function GetFragment(iIndex: Integer): TFslCSSFragment;
Protected
Function ItemClass : TFslObjectClass; Override;
Public
Property Fragments[iIndex : Integer] : TFslCSSFragment Read GetFragment; Default;
End;
TFslCSSStyle = Class(TFslCSSFragment)
Private
FName : String;
Public
Function Link : TFslCSSStyle;
Function Clone : TFslCSSStyle;
Procedure Assign(oSource : TFslObject); Override;
Property Name : String Read FName Write FName;
End;
TFslCSSStyles = Class (TFslCSSFragments)
Private
Function GetScript(iIndex: Integer): TFslCSSStyle;
Protected
Function ItemClass : TFslObjectClass; Override;
Public
Property Styles[iIndex : Integer] : TFslCSSStyle Read GetScript; Default;
End;
TFslCSSClasses = Class(TFslStringList)
End;
Type
TFslHTMLAttributes = Class(TFslStringMatch)
Private
Function GetAttribute(Const sKey: String): String;
Procedure SetAttribute(Const sKey, sValue: String);
Public
constructor Create; Override;
Property Attribute[Const sKey : String] : String Read GetAttribute Write SetAttribute; Default;
End;
Type
TFslHTMLAlign = (haUnspecified, haLeft, haCenter, haRight, haJustify, haTop, haBottom);
TFslHTMLBreakClearType = (bctNone, bctLeft, bctRight, bctAll);
TFslHTMLHeadingLevel = (ahlOne, ahlTwo, ahlThree, ahlFour, ahlFive, ahlSix);
TFslHTMLOrderedListType = (ltArabic {1}, ltLowerAlpha {a}, ltUpperAlpha {A}, ltLowerRoman {i}, ltUpperRoman {I});
TFslHTMLUnorderedListType = (ltDisc, ltSquare, ltCircle);
TFslHTMLTableSectionType = (tstBody, tstHead, tstFoot);
TFslHTMLFormInputType = (fitText, fitPassword, fitCheckbox, fitRadio, fitSubmit, fitReset, fitFile, fitHidden, fitImage, fitButton);
TFslHTMLFormButtonType = (fbtSubmit, fbtReset, fbtButton);
TFslHTMLFormMethod = (fmGet, fmPost);
// support the use of Case Statements
TFslHTMLElementType = (ahError, ahComment, ahTextFragment, ahEntity, ahImageReference, ahAnchor,
ahBreak, ahSection, ahInLineSection, ahBlockSection, {ahLink, to be put back inb - this is a header link not an <a>}
ahSpan, ahEmphasis, ahStrong, ahCitation, ahDefinition,
ahCode, ahSample, ahKeyboardText, ahVariable, ahAbbrevation,
ahAcronym, ahTeleType, ahItalic, ahBold, ahBig,
ahSmall, ahStrikeOut, ahUnderline, ahFont, ahQuotation,
ahSuperScript, ahSubScript, ahBlockQuote, ahHorizontalRule, ahDiv,
ahParagraph, ahPreformatted, ahHeading, ahListItem, ahListElement,
ahOrderedList, ahUnOrderedList, ahDefinitionListItem, ahDefinitionList, ahTableCell,
ahTableRow, ahTableSection, ahTableCaption, ahTable, ahFormControl,
ahInput, ahButton, ahOptionItem, ahOptGroup, ahOption,
ahSelect, ahTextArea, ahForm, ahBody);
Const
ADVHTMLALIGN_NAMES : Array [TFslHTMLAlign] Of String = ('', 'Left', 'Center', 'Right', 'Justify', 'Top', 'Bottom');
ADVHTMLBREAKCLEARTYPE_NAMES : Array [TFslHTMLBreakClearType] Of String = ('None', 'Left', 'Right', 'All');
ADVHTMLHEADINGLEVEL_NAMES : Array [TFslHTMLHeadingLevel] Of String = ('H1', 'H2', 'H3', 'H4', 'H5', 'H6');
ADVHTMLORDEREDLISTTYPE_NAMES : Array [TFslHTMLOrderedListType] Of String = ('Arabic', 'LowerAlpha', 'UpperAlpha', 'LowerRoman', 'UpperRoman');
ADVHTMLUNORDEREDLISTTYPE_NAMES : Array [TFslHTMLUnorderedListType] Of String = ('Disc', 'Square', 'Circle');
ADVHTMLTABLESECTIONTYPE_NAMES : Array [TFslHTMLTableSectionType] Of String = ('Body', 'Head', 'Foot');
ADVHTMLFORMINPUTTYPE_NAMES : Array [TFslHTMLFormInputType] Of String = ('Text', 'Password', 'Checkbox', 'Radio', 'Submit', 'Reset', 'File', 'Hidden', 'Image', 'Button');
ADVHTMLFORMBUTTONTYPE_NAMES : Array [TFslHTMLFormButtonType] Of String = ('Submit', 'Reset', 'Button');
ADVHTMLFORMMETHOD_NAMES : Array [TFslHTMLFormMethod] Of String = ('Get', 'Post');
Type
// all objects in the DOM descend from one of these 3 classes
TFslHTMLObject = TFslObject;
TFslHTMLList = TFslObjectList;
TFslHTMLStrings = TFslStringList;
TFslHTMLColour = String; // for the moment, but something encoded is preferred later
{------------- HTML DOM Elements ----------------------------------------------}
// all html elements descend from this class, it supports the title="" attribute
TFslHTMLElement = Class (TFslHTMLObject)
Private
FTitleAttribute : String;
Public
Procedure Assign(oSource : TFslObject); Override;
Procedure Clear; Virtual;
Property TitleAttribute : String Read FTitleAttribute Write FTitleAttribute; // all elements can have a title, though it often mightn't mean anything
End;
TFslHTMLElements = Class(TFslHTMLList)
Private
Function GetElement(iIndex: Integer): TFslHTMLElement;
Protected
Function ItemClass : TFslObjectClass; Override;
Public
Property Element[iIndex : Integer] : TFslHTMLElement Read GetElement; Default;
End;
// all html body elements descend from this class. It supports
// the attributes id=, class=, and style=
TFslHTMLItem = Class (TFslHTMLElement)
Private
FId: String;
FClasses: TFslCSSClasses;
FStyle: TFslCSSFragment;
Procedure SetClasses(Const oValue: TFslCSSClasses);
Procedure SetStyle(Const oValue: TFslCSSFragment);
Public
constructor Create; Override;
destructor Destroy; Override;
Function Link : TFslHTMLItem;
Function Clone : TFslHTMLItem;
Procedure Assign(oSource : TFslObject); Override;
Function ElementType : TFslHTMLElementType; Virtual;
Property Classes : TFslCSSClasses Read FClasses Write SetClasses; // though there would usually only be one
Property Id : String Read FId Write FId;
Property Style : TFslCSSFragment Read FStyle Write SetStyle;
// property WorkingStyles : TCSSWorkingStyles read FWorkingStyles; // parser to ignore
End;
TFslHTMLItems = Class (TFslHTMLElements)
Private
Function GetHTMLItem(iIndex: Integer): TFslHTMLItem;
Protected
Function ItemClass : TFslObjectClass; Override;
Public
Property Item[iIndex : Integer] : TFslHTMLItem Read GetHTMLItem; Default;
End;
{------------- HTML Simple Elements -------------------------------------------}
// These 3 classes are descendents from TFslHTMLItem for convenience (so they
// can be members of a TFslHTMLItems, not because they can carry id, style, and classes
TFslHTMLComment = Class (TFslHTMLItem)
Private
FText: String;
Public
Function Link : TFslHTMLComment;
Function Clone : TFslHTMLComment;
Function ElementType : TFslHTMLElementType; Override;
Procedure Assign(oSource : TFslObject); Override;
Property Text : String Read FText Write FText; // may include cReturns, interpret literally
End;
// any text
TFslHTMLTextFragment = Class (TFslHTMLItem)
Private
FText: String;
Public
Function Link : TFslHTMLTextFragment;
Function Clone : TFslHTMLTextFragment;
Function ElementType : TFslHTMLElementType; Override;
Procedure Assign(oSource : TFslObject); Override;
Property Text : String Read FText Write FText; // do not collapse whitespace (because of pre)
End;
// it's not possible to collapse entities into the raw text stream, some
// have information processing significance
// &ent;
TFslHTMLEntity = Class (TFslHTMLItem)
Private
FEntity: String;
Public
Function Link : TFslHTMLEntity;
Function Clone : TFslHTMLEntity;
Function ElementType : TFslHTMLElementType; Override;
Procedure Assign(oSource : TFslObject); Override;
Property Entity : String Read FEntity Write FEntity; // may include cReturns
End;
// <img>
TFslHTMLImage = Class (TFslHTMLItem)
Private
FHorizontalSpace: String;
FAlternative : String;
FLongDescription: String;
FHeight: String;
FBorder: String;
FSource: String;
FName: String;
FVerticalSpace: String;
FWidth: String;
FAlign: TFslHTMLAlign;
Public
Function Link : TFslHTMLImage;
Function Clone : TFslHTMLImage;
Function ElementType : TFslHTMLElementType; Override;
Procedure Assign(oSource : TFslObject); Override;
Property Align : TFslHTMLAlign Read FAlign Write FAlign; // Top, Middle, Bottom, Left, Right
Property Alternative : String Read FAlternative Write FAlternative;
Property Border : String Read FBorder Write FBorder;
Property Height : String Read FHeight Write FHeight;
Property HorizontalSpace : String Read FHorizontalSpace Write FHorizontalSpace;
Property LongDescription : String Read FLongDescription Write FLongDescription;
Property Name : String Read FName Write FName;
Property Source : String Read FSource Write FSource;
Property VerticalSpace : String Read FVerticalSpace Write FVerticalSpace;
Property Width : String Read FWidth Write FWidth;
End;
// <br>
TFslHTMLBreak = Class (TFslHTMLItem)
Private
FClearType: TFslHTMLBreakClearType;
Public
Function Link : TFslHTMLBreak;
Function Clone : TFslHTMLBreak;
Function ElementType : TFslHTMLElementType; Override;
Procedure Assign(oSource : TFslObject); Override;
Property ClearType : TFslHTMLBreakClearType Read FClearType Write FClearType;
End;
{------------- HTML Sections --------------------------------------------------}
// base element of recursiveness in html structure. There is a few rules
// about what Sections can contain other sections, but these are vague and
// sometimes are makde across several layers (i.e. no forms in forms), so
// it's rarely possible to represent such constraints in this object model
TFslHTMLSection = Class (TFslHTMLItem)
Private
FItems: TFslHTMLItems;
Procedure SetItems(Const oValue: TFslHTMLItems);
Public
constructor Create; Override;
destructor Destroy; Override;
Function Link : TFslHTMLSection;
Function Clone : TFslHTMLSection;
Function ElementType : TFslHTMLElementType; Override;
Procedure Assign(oSource : TFslObject); Override;
Procedure Clear; Override;
Property Items : TFslHTMLItems Read FItems Write SetItems;
End;
TFslHTMLSections = Class (TFslHTMLItems);
// TFslHTMLInlineSection is an abstract concept, no direct HTML equivalent
// Inline sections fit into the text around them in an inline fashion
TFslHTMLInLineSection = Class (TFslHTMLSection);
TFslHTMLInLineSections = Class (TFslHTMLSections);
// TFslHTMLBlockSection is an abstract concept, no direct HTML equivalent
// Block sections Start a new line
TFslHTMLBlockSection = Class (TFslHTMLSection);
TFslHTMLBlockSections = Class (TFslHTMLSections);
{------------- HTML Inline Sections -------------------------------------------}
// <a name="" href="">
TFslHTMLAnchor = Class (TFslHTMLInLineSection)
Private
FURL: String;
FName: String;
FAccessKey: String;
Public
Function Link : TFslHTMLAnchor;
Function Clone : TFslHTMLAnchor;
Function ElementType : TFslHTMLElementType; Override;
Procedure Assign(oSource : TFslObject); Override;
Property URL : String Read FURL Write FURL;
Property Name : String Read FName Write FName;
Property AccessKey : String Read FAccessKey Write FAccessKey;
End;
// <span>
TFslHTMLSpan = Class (TFslHTMLInLineSection)
Private
FAlign: TFslHTMLAlign;
Public
Function Link : TFslHTMLSpan;
Function Clone : TFslHTMLSpan;
Function ElementType : TFslHTMLElementType; Override;
Procedure Assign(oSource : TFslObject); Override;
Property align : TFslHTMLAlign Read FAlign Write FAlign; // Left, Center, Right, Justify
End;
// <em> </em> - italics
TFslHTMLEmphasis = Class (TFslHTMLInLineSection)
Public
Function Link : TFslHTMLEmphasis;
Function Clone : TFslHTMLEmphasis;
Function ElementType : TFslHTMLElementType; Override;
End;
// <strong< </strong> - bold
TFslHTMLStrong = Class (TFslHTMLInLineSection)
Public
Function Link : TFslHTMLStrong;
Function Clone : TFslHTMLStrong;
Function ElementType : TFslHTMLElementType; Override;
End;
// <cit></cite>
TFslHTMLCitation = Class (TFslHTMLInLineSection)
Public
Function Link : TFslHTMLCitation;
Function Clone : TFslHTMLCitation;
Function ElementType : TFslHTMLElementType; Override;
End;
// <dfn></dfn>
TFslHTMLDefinition = Class (TFslHTMLInLineSection)
Public
Function Link : TFslHTMLDefinition;
Function Clone : TFslHTMLDefinition;
Function ElementType : TFslHTMLElementType; Override;
End;
// <code></code>
TFslHTMLCode = Class (TFslHTMLInLineSection)
Public
Function Link : TFslHTMLCode;
Function Clone : TFslHTMLCode;
Function ElementType : TFslHTMLElementType; Override;
End;
// <samp></samp>
TFslHTMLSample = Class (TFslHTMLInLineSection)
Public
Function Link : TFslHTMLSample;
Function Clone : TFslHTMLSample;
Function ElementType : TFslHTMLElementType; Override;
End;
// <kdb></kdb>
TFslHTMLKeyboardText = Class (TFslHTMLInLineSection)
Public
Function Link : TFslHTMLKeyboardText;
Function Clone : TFslHTMLKeyboardText;
Function ElementType : TFslHTMLElementType; Override;
End;
// <var></var>
TFslHTMLVariable = Class (TFslHTMLInLineSection)
Public
Function Link : TFslHTMLVariable;
Function Clone : TFslHTMLVariable;
Function ElementType : TFslHTMLElementType; Override;
End;
// <abbr></abbr>
TFslHTMLAbbrevation = Class (TFslHTMLInLineSection)
Public
Function Link : TFslHTMLAbbrevation;
Function Clone : TFslHTMLAbbrevation;
Function ElementType : TFslHTMLElementType; Override;
End;
// <Acronym></Acronym>
TFslHTMLAcronym = Class (TFslHTMLInLineSection)
Public
Function Link : TFslHTMLAcronym;
Function Clone : TFslHTMLAcronym;
Function ElementType : TFslHTMLElementType; Override;
End;
// <tt></tt> - fixed width
TFslHTMLTeleType = Class (TFslHTMLInLineSection)
Public
Function Link : TFslHTMLTeleType;
Function Clone : TFslHTMLTeleType;
Function ElementType : TFslHTMLElementType; Override;
End;
// <i></i>
TFslHTMLItalic = Class (TFslHTMLInLineSection)
Public
Function Link : TFslHTMLItalic;
Function Clone : TFslHTMLItalic;
Function ElementType : TFslHTMLElementType; Override;
End;
// <b></b>
TFslHTMLBold = Class (TFslHTMLInLineSection)
Public
Function Link : TFslHTMLBold;
Function Clone : TFslHTMLBold;
Function ElementType : TFslHTMLElementType; Override;
End;
// <big></big>
TFslHTMLBig = Class (TFslHTMLInLineSection)
Public
Function Link : TFslHTMLBig;
Function Clone : TFslHTMLBig;
Function ElementType : TFslHTMLElementType; Override;
End;
// <small></small>
TFslHTMLSmall = Class (TFslHTMLInLineSection)
Public
Function Link : TFslHTMLSmall;
Function Clone : TFslHTMLSmall;
Function ElementType : TFslHTMLElementType; Override;
End;
// <s></s> or <strike></strike>
TFslHTMLStrikeOut = Class (TFslHTMLInLineSection)
Public
Function Link : TFslHTMLStrikeOut;
Function Clone : TFslHTMLStrikeOut;
Function ElementType : TFslHTMLElementType; Override;
End;
// <u></u>
TFslHTMLUnderline = Class (TFslHTMLInLineSection)
Public
Function Link : TFslHTMLUnderline;
Function Clone : TFslHTMLUnderline;
Function ElementType : TFslHTMLElementType; Override;
End;
TFslHTMLFont = Class (TFslHTMLInLineSection)
Private
FSize: String;
FFace: String;
FColour: TFslHTMLColour;
Public
Function Link : TFslHTMLFont;
Function Clone : TFslHTMLFont;
Function ElementType : TFslHTMLElementType; Override;
Procedure Assign(oSource : TFslObject); Override;
Property Color : TFslHTMLColour Read FColour Write FColour;
Property Face : String Read FFace Write FFace; // leave as comma separated
Property Size : String Read FSize Write FSize;
End;
// <q></q>
TFslHTMLQuotation = Class (TFslHTMLInLineSection)
Public
Function Link : TFslHTMLQuotation;
Function Clone : TFslHTMLQuotation;
Function ElementType : TFslHTMLElementType; Override;
End;
// <super></super>
TFslHTMLSuperScript = Class (TFslHTMLInLineSection)
Public
Function Link : TFslHTMLSuperScript;
Function Clone : TFslHTMLSuperScript;
Function ElementType : TFslHTMLElementType; Override;
End;
// <sub></sub>
TFslHTMLSubScript = Class (TFslHTMLInLineSection)
Public
Function Link : TFslHTMLSubScript;
Function Clone : TFslHTMLSubScript;
Function ElementType : TFslHTMLElementType; Override;
End;
{------------- HTML Block Sections --------------------------------------------}
// <blockQuote></blockQuote> - usually indented
TFslHTMLBlockQuote = Class (TFslHTMLBlockSection)
Public
Function Link : TFslHTMLBlockQuote;
Function Clone : TFslHTMLBlockQuote;
Function ElementType : TFslHTMLElementType; Override;
End;
// <hr>
TFslHTMLHorizontalRule = Class (TFslHTMLBlockSection)
Private
FNoShade: Boolean;
FSize: String;
FWidth: String;
FAlign: TFslHTMLAlign;
Public
Function Link : TFslHTMLHorizontalRule;
Function Clone : TFslHTMLHorizontalRule;
Function ElementType : TFslHTMLElementType; Override;
Procedure Assign(oSource : TFslObject); Override;
Property Align : TFslHTMLAlign Read FAlign Write FAlign; // Left|middle|right
Property NoShade : Boolean Read FNoShade Write FNoShade;
Property Size : String Read FSize Write FSize;
Property Width : String Read FWidth Write FWidth;
End;
// <div>
TFslHTMLContainer = Class (TFslHTMLBlockSection)
Private
FAlign: TFslHTMLAlign;
Public
Function Link : TFslHTMLContainer;
Function Clone : TFslHTMLContainer;
Function ElementType : TFslHTMLElementType; Override;
Procedure Assign(oSource : TFslObject); Override;
Property align : TFslHTMLAlign Read FAlign Write FAlign; // Left, Center, Right, Justify
End;
// <p>
// parser note : Paragraphs cannot contain paragraphs, but they can contain Pre and Div (and div can contain paragraphs....)
TFslHTMLParagraph = Class (TFslHTMLContainer)
Public
Function Link : TFslHTMLParagraph;
Function Clone : TFslHTMLParagraph;
Function ElementType : TFslHTMLElementType; Override;
End;
// <pre>
TFslHTMLPreformatted = Class (TFslHTMLParagraph)
Public
Function Link : TFslHTMLPreformatted;
Function Clone : TFslHTMLPreformatted;
Function ElementType : TFslHTMLElementType; Override;
End;
// <h[N]></h[N]>
TFslHTMLHeading = Class (TFslHTMLBlockSection)
Private
FLevel: TFslHTMLHeadingLevel;
Public
Function Link : TFslHTMLHeading;
Function Clone : TFslHTMLHeading;
Function ElementType : TFslHTMLElementType; Override;
Procedure Assign(oSource : TFslObject); Override;
Property Level : TFslHTMLHeadingLevel Read FLevel Write FLevel;
End;
{------------- HTML Lists -----------------------------------------------------}
// <li>
TFslHTMLListItem = Class (TFslHTMLBlockSection)
Private
FValue: Integer;
FHasValue : Boolean;
Function GetHasValue: Boolean;
Function GetValue: Integer;
Procedure SetHasValue(Const Value: Boolean);
Procedure SetValue(Const Value: Integer);
Public
Function Link : TFslHTMLListItem;
Function Clone : TFslHTMLListItem;
Function ElementType : TFslHTMLElementType; Override;
Procedure Assign(oSource : TFslObject); Override;
Property Value : Integer Read GetValue Write SetValue; // only has meaning for OL lists.
Property HasValue : Boolean Read GetHasValue Write SetHasValue; // whether value is defined
End;
TFslHTMLListItems = Class (TFslHTMLBlockSections)
Private
Function GetListItem(iIndex: Integer): TFslHTMLListItem;
Protected
Function ItemClass : TFslObjectClass; Override;
Public
Property item[iIndex : Integer] : TFslHTMLListItem Read GetListItem; Default;
End;
// no html equivalent
TFslHTMLListElement = Class (TFslHTMLBlockSection)
Private
FCompact: Boolean;
FList: TFslHTMLListItems;
Procedure SetList(Const oValue: TFslHTMLListItems);
Public
constructor Create; Override;
destructor Destroy; Override;
Function Link : TFslHTMLListElement;
Function Clone : TFslHTMLListElement;
Function ElementType : TFslHTMLElementType; Override;
Procedure Assign(oSource : TFslObject); Override;
Property Compact : Boolean Read FCompact Write FCompact;
Property List : TFslHTMLListItems Read FList Write SetList;
End;
// <ol>
TFslHTMLOrderedList = Class (TFslHTMLListElement)
Private
FStart: Integer;
FListType: TFslHTMLOrderedListType;
Public
Function Link : TFslHTMLOrderedList;
Function Clone : TFslHTMLOrderedList;
Function ElementType : TFslHTMLElementType; Override;
Procedure Assign(oSource : TFslObject); Override;
Property listType : TFslHTMLOrderedListType Read FListType Write FListType;
Property Start : Integer Read FStart Write FStart;
End;
// <ul>
TFslHTMLUnorderedList = Class (TFslHTMLListElement)
Private
FListType: TFslHTMLUnorderedListType;
Public
Function Link : TFslHTMLUnorderedList;
Function Clone : TFslHTMLUnorderedList;
Function ElementType : TFslHTMLElementType; Override;
Procedure Assign(oSource : TFslObject); Override;
Property listType : TFslHTMLUnorderedListType Read FListType Write FListType;
End;
// <dt><dd> the <dd> section is the ancestor content
TFslHTMLDefinitionListItem = Class (TFslHTMLInlineSection)
Private
FTerm: TFslHTMLItem;
Procedure SetTerm(Const oValue: TFslHTMLItem);
Public
constructor Create; Override;
destructor Destroy; Override;
Function Link : TFslHTMLDefinitionListItem;
Function Clone : TFslHTMLDefinitionListItem;
Function ElementType : TFslHTMLElementType; Override;
Procedure Assign(oSource : TFslObject); Override;
Property Term : TFslHTMLItem Read FTerm Write SetTerm;
End;
TFslHTMLDefinitionListItems = Class (TFslHTMLInlineSections)
Private
Function GetListItem(iIndex: Integer): TFslHTMLDefinitionListItem;
Protected
Function ItemClass : TFslObjectClass; Override;
Public
Property item[iIndex : Integer] : TFslHTMLDefinitionListItem Read GetListItem; Default;
End;
// <dl>
TFslHTMLDefinitionList = Class (TFslHTMLBlockSection)
Private
FListItems: TFslHTMLDefinitionListItems;
Procedure SetListItems(Const oValue: TFslHTMLDefinitionListItems);
Public
constructor Create; Override;
destructor Destroy; Override;
Function Link : TFslHTMLDefinitionList;
Function Clone : TFslHTMLDefinitionList;
Function ElementType : TFslHTMLElementType; Override;
Procedure Assign(oSource : TFslObject); Override;
Property ListItems : TFslHTMLDefinitionListItems Read FListItems Write SetListItems;
End;
{------------- HTML Tables ----------------------------------------------------}
// <td></td> or <th></th> ( = isHeader)
TFslHTMLTableCell = Class (TFslHTMLBlockSection)
Private
FNoWrap: Boolean;
FRowspan: String;
FColspan: String;
FWidth: String;
FHeight: String;
FVertAlign: TFslHTMLAlign;
FHorizAlign: TFslHTMLAlign;
FBgColour: TFslHTMLColour;
FIsHeader: Boolean;
Public
Function Link : TFslHTMLTableCell;
Function Clone : TFslHTMLTableCell;
Function ElementType : TFslHTMLElementType; Override;
Procedure Assign(oSource : TFslObject); Override;
Property BgColor : TFslHTMLColour Read FBgColour Write FBgColour;
Property ColSpan : String Read FColspan Write FColspan;
Property Height : String Read FHeight Write FHeight;
Property HorizAlign : TFslHTMLAlign Read FHorizAlign Write FHorizAlign;
Property IsHeader : Boolean Read FIsHeader Write FIsHeader;
Property NoWrap : Boolean Read FNoWrap Write FNoWrap;
Property RowSpan : String Read FRowspan Write FRowspan;
Property VertAlign : TFslHTMLAlign Read FVertAlign Write FVertAlign;
Property Width : String Read FWidth Write FWidth;
End;
TFslHTMLTableCells = Class (TFslHTMLBlockSections)
Private
Function GetCell(iIndex: Integer): TFslHTMLTableCell;
Protected
Function ItemClass : TFslObjectClass; Override;
Public
Property Cell[iIndex : Integer] : TFslHTMLTableCell Read GetCell; Default;
End;
// <tr></tr>
TFslHTMLTableRow = Class (TFslHTMLItem)
Private
FVertAlign: TFslHTMLAlign;
FHorizAlign: TFslHTMLAlign;
FBgColour: TFslHTMLColour;
FCells: TFslHTMLTableCells;
Procedure SetCells(Const oValue: TFslHTMLTableCells);
Public
constructor Create; Override;
destructor Destroy; Override;
Function Link : TFslHTMLTableRow;
Function Clone : TFslHTMLTableRow;
Function ElementType : TFslHTMLElementType; Override;
Procedure Assign(oSource : TFslObject); Override;
Property BgColor : TFslHTMLColour Read FBgColour Write FBgColour;
Property Cells : TFslHTMLTableCells Read FCells Write SetCells;
Property HorizAlign : TFslHTMLAlign Read FHorizAlign Write FHorizAlign;
Property VertAlign : TFslHTMLAlign Read FVertAlign Write FVertAlign;
End;
TFslHTMLTableRows = Class (TFslHTMLItems)
Private
Function GetRow(iIndex: Integer): TFslHTMLTableRow;
Protected
Function ItemClass : TFslObjectClass; Override;
Public
Property Row[iIndex : Integer] : TFslHTMLTableRow Read GetRow; Default;
End;
// <THead>, <TBody>, <TFoot>
TFslHTMLTableSection = Class (TFslHTMLItem)
Private
FRows: TFslHTMLTableRows;
FSectionType: TFslHTMLTableSectionType;
Procedure SetRows(Const oValue: TFslHTMLTableRows);
Public
constructor Create; Override;
destructor Destroy; Override;
Function Link : TFslHTMLTableSection;
Function Clone : TFslHTMLTableSection;
Function ElementType : TFslHTMLElementType; Override;
Procedure Assign(oSource : TFslObject); Override;
Property Rows : TFslHTMLTableRows Read FRows Write SetRows;
Property SectionType : TFslHTMLTableSectionType Read FSectionType Write FSectionType;
End;
TFslHTMLTableSections = Class (TFslHTMLItems)
Private
Function GetSection(iIndex: Integer): TFslHTMLTableSection;
Protected
Function ItemClass : TFslObjectClass; Override;
Public
Property Section[iIndex : Integer] : TFslHTMLTableSection Read GetSection; Default;
End;
// <caption></caption>
TFslHTMLTableCaption = Class (TFslHTMLBlockSection)
Private
FAlign: TFslHTMLAlign;
Public
Function Link : TFslHTMLTableCaption;
Function Clone : TFslHTMLTableCaption;
Function ElementType : TFslHTMLElementType; Override;
Procedure Assign(oSource : TFslObject); Override;
Property Align : TFslHTMLAlign Read FAlign Write FAlign; //Top, Bottom, Left, Right
End;
// <table></table>
TFslHTMLTable = Class (TFslHTMLBlockSection)
Private
FSummary: String;
FWidth: String;
FCellpadding: String;
FCellspacing: String;
FBorder: String;
FAlign: TFslHTMLAlign;
FBgColour: TFslHTMLColour;
FCaption: TFslHTMLTableCaption;
FRows: TFslHTMLTableRows;
FSections: TFslHTMLTableSections;
Procedure SetCaption(Const oValue: TFslHTMLTableCaption);
Procedure SetRows(Const oValue: TFslHTMLTableRows);
Procedure SetSections(Const oValue: TFslHTMLTableSections);
Public
constructor Create; Override;
destructor Destroy; Override;
Function Link : TFslHTMLTable;
Function Clone : TFslHTMLTable;
Function ElementType : TFslHTMLElementType; Override;
Procedure Assign(oSource : TFslObject); Override;
// todo: frames and rules, colGroups, Cols
Property Align : TFslHTMLAlign Read FAlign Write FAlign; // Left|middle|right
Property AllRows : TFslHTMLTableRows Read FRows Write SetRows;
Property BgColor : TFslHTMLColour Read FBgColour Write FBgColour;
Property Border : String Read FBorder Write FBorder;
Property Caption : TFslHTMLTableCaption Read FCaption Write SetCaption;
Property Cellpadding : String Read FCellpadding Write FCellpadding;
Property Cellspacing : String Read FCellspacing Write FCellspacing;
Property Sections : TFslHTMLTableSections Read FSections Write SetSections;
Property Summary : String Read FSummary Write FSummary;
Property Width : String Read FWidth Write FWidth;
Property Rows : TFslHTMLTableRows Read FRows;
End;
{------------- HTML Forms -----------------------------------------------------}
TFslHTMLFormControl = Class (TFslHTMLItem)
Private
FDisabled: Boolean;
FTabIndex: String;
FName: String;
FValue: String;
Public
Function Link : TFslHTMLFormControl;
Function Clone : TFslHTMLFormControl;
Function ElementType : TFslHTMLElementType; Override;
Procedure Assign(oSource : TFslObject); Override;
Property Disabled : Boolean Read FDisabled Write FDisabled;
Property Name : String Read FName Write FName;
Property TabIndex : String Read FTabIndex Write FTabIndex;
Property Value : String Read FValue Write FValue;
End;
// <input>
TFslHTMLInput = Class (TFslHTMLFormControl)
Private
FReadOnly: Boolean;
FChecked: Boolean;
FSize: String;
FAccept: String;
FSource: String;
FMaxLength: String;
FAlternative: String;
FAlign: TFslHTMLAlign;
FInputType: TFslHTMLFormInputType;
Public
Function Link : TFslHTMLInput;
Function Clone : TFslHTMLInput;
Function ElementType : TFslHTMLElementType; Override;
Procedure Assign(oSource : TFslObject); Override;
Property Accept : String Read FAccept Write FAccept;
Property Align : TFslHTMLAlign Read FAlign Write FAlign; // Left|middle|right
Property Alternative : String Read FAlternative Write FAlternative;
Property Checked : Boolean Read FChecked Write FChecked;
Property InputType : TFslHTMLFormInputType Read FInputType Write FInputType;
Property MaxLength : String Read FMaxLength Write FMaxLength;
Property ReadOnly : Boolean Read FReadOnly Write FReadOnly;
Property Size : String Read FSize Write FSize;
Property Source : String Read FSource Write FSource;
End;
// <button>
TFslHTMLButton = Class (TFslHTMLFormControl)
Private
FButtonType: TFslHTMLFormButtonType;
Public
Function Link : TFslHTMLButton;
Function Clone : TFslHTMLButton;
Function ElementType : TFslHTMLElementType; Override;
Procedure Assign(oSource : TFslObject); Override;
Property ButtonType : TFslHTMLFormButtonType Read FButtonType Write FButtonType;
End;
// html 4 does not allow OptGroups to recurse. This structure allows for 0 optgroups or all optgroups
TFslHTMLOptionItem = Class (TFslHTMLItem) // TFslHTMLItem from DOM/HTML. What style etc might mean in this context, who knows?
Private
FDisabled: Boolean;
FCaption: String;
Public
Function Link : TFslHTMLOptionItem;
Function Clone : TFslHTMLOptionItem;
Function ElementType : TFslHTMLElementType; Override;
Procedure Assign(oSource : TFslObject); Override;
Property Caption : String Read FCaption Write FCaption; // was "label" in html
Property Disabled : Boolean Read FDisabled Write FDisabled;
End;
TFslHTMLOptionItems = Class (TFslHTMLItems)
Private
Function GetOption(iIndex: Integer): TFslHTMLOptionItem;
Protected
Function ItemClass : TFslObjectClass; Override;
Public
Property Option[iIndex : Integer] : TFslHTMLOptionItem Read GetOption; Default;
End;
// <optgroup>
TFslHTMLOptGroup = Class (TFslHTMLOptionItem)
Private
FOptions: TFslHTMLOptionItems;
Procedure SetOptions(Const oValue: TFslHTMLOptionItems);
Public
constructor Create; Override;
destructor Destroy; Override;
Function Link : TFslHTMLOptGroup;
Function Clone : TFslHTMLOptGroup;
Function ElementType : TFslHTMLElementType; Override;
Procedure Assign(oSource : TFslObject); Override;
Property Options : TFslHTMLOptionItems Read FOptions Write SetOptions;
End;
// <option>
TFslHTMLOption = Class (TFslHTMLOptionItem)
Private
FSelected: Boolean;
FValue: String;
Public
Function Link : TFslHTMLOption;
Function Clone : TFslHTMLOption;
Function ElementType : TFslHTMLElementType; Override;
Procedure Assign(oSource : TFslObject); Override;
Property Selected : Boolean Read FSelected Write FSelected;
Property Value : String Read FValue Write FValue;
End;
TFslHTMLSelect = Class (TFslHTMLFormControl)
Private
FMultiple: Boolean;
FSize: String;
FAllOptions: TFslHTMLOptionItems;
FOptions: TFslHTMLOptionItems;
Procedure SetAllOptions(Const oValue: TFslHTMLOptionItems);
Procedure SetOptions(Const oValue: TFslHTMLOptionItems);
Public
constructor Create; Override;
destructor Destroy; Override;
Function Link : TFslHTMLSelect;
Function Clone : TFslHTMLSelect;
Function ElementType : TFslHTMLElementType; Override;
Procedure Assign(oSource : TFslObject); Override;
Property AllOptions : TFslHTMLOptionItems Read FAllOptions Write SetAllOptions;
Property Multiple : Boolean Read FMultiple Write FMultiple;
Property Options : TFslHTMLOptionItems Read FOptions Write SetOptions;
Property Size : String Read FSize Write FSize;
End;
// <textarea>
// still to decide - how do we handle the content?
TFslHTMLTextArea = Class (TFslHTMLFormControl)
Private
FReadOnly: Boolean;
FRows: Integer;
FCols: Integer;
Public
Function Link : TFslHTMLTextArea;
Function Clone : TFslHTMLTextArea;
Function ElementType : TFslHTMLElementType; Override;
Procedure Assign(oSource : TFslObject); Override;
Property Cols : Integer Read FCols Write FCols;
Property ReadOnly : Boolean Read FReadOnly Write FReadOnly;
Property Rows : Integer Read FRows Write FRows;
End;
TFslHTMLForm = Class (TFslHTMLBlockSection)// forms cannot be contained in other forms
Private
FAction: String;
FEncType: String;
FName: String;
FMethod: TFslHTMLFormMethod;
Public
Function Link : TFslHTMLForm;
Function Clone : TFslHTMLForm;
Function ElementType : TFslHTMLElementType; Override;
Procedure Assign(oSource : TFslObject); Override;
Property Action : String Read FAction Write FAction;
Property EncType : String Read FEncType Write FEncType;
Property Method : TFslHTMLFormMethod Read FMethod Write FMethod;
Property Name : String Read FName Write FName;
// controls
End;
{------------- HTML Document Content ------------------------------------------}
TFslHTMLBody = Class (TFslHTMLBlockSection)
Private
FLinkColor: TFslHTMLColour;
FVlinkcolor: TFslHTMLColour;
FAlinkColor: TFslHTMLColour;
Public
Function Link : TFslHTMLBody;
Function Clone : TFslHTMLBody;
Function ElementType : TFslHTMLElementType; Override;
Procedure Assign(oSource : TFslObject); Override;
Property alinkColor : TFslHTMLColour Read FAlinkColor Write FAlinkColor;
Property linkColor : TFslHTMLColour Read FLinkColor Write FLinkColor;
Property vlinkcolor : TFslHTMLColour Read FVlinkcolor Write FVlinkcolor;
End;
TFslHTMLMetaEntry = Class (TFslHTMLElement)
Private
FHttpEquiv: String;
FContent: String;
FName: String;
FScheme: String;
Public
Function Link : TFslHTMLMetaEntry;
Function Clone : TFslHTMLMetaEntry;
Procedure Assign(oSource : TFslObject); Override;
Property Content : String Read FContent Write FContent;
Property HttpEquiv : String Read FHttpEquiv Write FHttpEquiv;
Property Name : String Read FName Write FName;
Property Scheme : String Read FScheme Write FScheme;
End;
TFslHTMLMetaEntries = Class (TFslHTMLElements)
Private
Function GetMeta(iIndex: Integer): TFslHTMLMetaEntry;
Protected
Function ItemClass : TFslObjectClass; Override;
Public
Property Meta[iIndex : Integer] : TFslHTMLMetaEntry Read GetMeta; Default;
End;
TFslHTMLHead = Class (TFslHTMLElement)
Private
FMeta: TFslHTMLMetaEntries;
FStyles: TFslCSSStyles;
FTitle: String;
Procedure SetMeta(Const oValue: TFslHTMLMetaEntries); // parser - collapse link and profile someday
Procedure SetStyles(Const oValue: TFslCSSStyles);
Public
constructor Create; Override;
destructor Destroy; Override;
Function Link : TFslHTMLHead;
Function Clone : TFslHTMLHead;
Procedure Assign(oSource : TFslObject); Override;
Procedure Clear; Override;
Property Meta : TFslHTMLMetaEntries Read FMeta Write SetMeta;
Property Styles : TFslCSSStyles Read FStyles Write SetStyles;
Property Title : String Read FTitle Write FTitle;
End;
TFslHtmlDocument = Class (TFslHTMLElement)
Private
FDTD: String;
FVersion: String;
FStyles: TFslCSSStyles;
FBody: TFslHTMLBody;
FHead: TFslHTMLHead;
Procedure SetBody(Const oValue: TFslHTMLBody);
Procedure SetHead(Const oValue: TFslHTMLHead);
Procedure SetStyles(Const oValue: TFslCSSStyles);
Public
constructor Create; Override;
destructor Destroy; Override;
Function Link : TFslHtmlDocument;
Function Clone : TFslHtmlDocument;
Procedure Assign(oSource : TFslObject); Override;
Procedure Clear; Override;
Property Version : String Read FVersion Write FVersion;
Property DTD : String Read FDTD Write FDTD;
Property Head : TFslHTMLHead Read FHead Write SetHead;
Property Styles : TFslCSSStyles Read FStyles Write SetStyles;
Property Body : TFslHTMLBody Read FBody Write SetBody;
// From DOM....
{ property Images : THTMLCollection;
property Applets : HTMLCollection;
property Links : HTMLCollection;
property Forms : HTMLCollection;
Function ElementType : TFslHTMLElementType; override;
property Anchors : HTMLCollection;
Function ElementById(sId : String) : Element;
Function ElementsByName(sName : String) : NodeList;}
End;
Type
TFslHTMLLexer = Class(TFslTextExtractor)
Private
FNextToken : TFslHTMLToken;
FCurrentToken : TFslHTMLToken;
FCurrentValue : String;
Public
Function ConsumeIdentifier : TFslHTMLToken;
Function ConsumeWhitespace : TFslHTMLToken;
Function ConsumeNumber : TFslHTMLToken;
Function ConsumeSymbol : TFslHTMLToken;
Function ConsumeToken : TFslHTMLToken; Overload;
Function NextToken : TFslHTMLToken;
Procedure ConsumeToken(aToken : TFslHTMLToken); Overload;
Property Value : String Read FCurrentValue Write FCurrentValue;
End;
Type
TFslHTMLParser = Class(TFslHTMLLexer)
Private
FAttributes : TFslHTMLAttributes;
FNextTagOpen : String;
FNextTagClose : String;
Protected
Procedure ConsumeIdentifier(Const sIdentifier : String);
Function ConsumeString: String;
Function NextIsTagOpen : Boolean;
Function NextIsTagClose : Boolean;
Function NextIsString : Boolean;
Function NextTagOpen : String; Overload;
Function NextTagClose : String; Overload;
Function ConsumeTagOpen : String; Overload;
Function ConsumeTagClose : String; Overload;
Procedure ConsumeTagOpen(Const sTag : String); Overload;
Procedure ConsumeTagClose(Const sTag : String); Overload;
Function NextTagOpen(Const sTag : String) : Boolean; Overload;
Function NextTagClose(Const sTag : String) : Boolean; Overload;
Function ConsumeTagBody : String;
Procedure ReadStyles(oStyles: TFslStringMatch; Const sValue: String);
Procedure ReadItem(oItem : TFslHTMLItem);
Procedure ConsumeTextFragment(oTextFragment : TFslHTMLTextFragment);
Procedure ConsumeParagraph(oParagraph : TFslHTMLParagraph);
Procedure ConsumeHeading(oHeading : TFslHTMLHeading);
Procedure ConsumeAnchor(oAnchor : TFslHTMLAnchor);
Procedure ConsumeFont(oFont : TFslHTMLFont);
Procedure ConsumeSpan(oSpan : TFslHTMLSpan);
Procedure ConsumeOrderedList(oList : TFslHTMLOrderedList);
Procedure ConsumeUnorderedList(oList : TFslHTMLUnorderedList);
Procedure ConsumeListItem(oItem : TFslHTMLListItem);
Procedure ConsumeItalic(oItalic : TFslHTMLItalic);
Procedure ConsumeBold(oBold : TFslHTMLBold);
Procedure ConsumeUnderline(oUnderline : TFslHTMLUnderline);
Procedure ConsumeBlockQuote(oBlockQuote : TFslHTMLBlockQuote);
Procedure ConsumeImage(oImage : TFslHTMLImage);
Procedure ConsumeTable(oTable : TFslHTMLTable);
Procedure ConsumeTableRow(oTableRow : TFslHTMLTableRow);
Procedure ConsumeTableCell(oTableCell : TFslHTMLTableCell);
Procedure ConsumeContainer(oContainer : TFslHTMLContainer);
Procedure ConsumeSubscript(oSubscript : TFslHTMLSubscript);
Procedure ConsumeSuperscript(oSuperscript : TFslHTMLSuperscript);
Procedure ConsumeBreak(oBreak : TFslHTMLBreak);
Procedure ConsumeHorizontalRule(oHorizontalRule : TFslHTMLHorizontalRule);
Procedure ConsumeInput(oInput : TFslHTMLInput);
Procedure ConsumePre(oPre : TFslHTMLPreformatted);
Procedure ConsumeStyles(oStyles : TFslCSSStyles);
Procedure ConsumeMetaEntry(oEntries : TFslHTMLMetaEntries);
Function ConsumeItem : TFslHTMLItem;
Procedure ConsumeSection(Const sTag : String); Overload;
Procedure ConsumeSection(Const sTag : String; oSection : TFslHTMLSection); Overload;
Procedure ConsumeItems(oItems : TFslHTMLItems);
Procedure ConsumeHead(oHead : TFslHTMLHead);
Procedure ConsumeBody(oBody : TFslHTMLBody);
Procedure ConsumeDocumentType(oDocument : TFslHTMLDocument);
Function ReduceToken: TFslHTMLToken; Overload;
Function ReduceToken(Const aTokens : TFslHTMLTokens) : TFslHTMLToken; Overload;
Procedure ReduceToken(aToken : TFslHTMLToken); Overload;
Function PeekToken : TFslHTMLToken;
Public
constructor Create; Override;
destructor Destroy; Override;
Procedure ConsumeDocument(oDocument : TFslHTMLDocument); Overload; Virtual;
Procedure ConsumeDocumentHead(oHead : TFslHTMLHead); Overload; Virtual;
End;
Type
TFslHTMLGreekSymbol = (
ahsCapsAlpha, ahsCapsBeta, ahsCapsGamma, ahsCapsDelta, ahsCapsEpsilon,
ahsCapsZeta, ahsCapsEta, ahsCapsTheta, ahsCapsIota, ahsCapsKappa,
ahsCapsLambda, ahsCapsMu, ahsCapsNu, ahsCapsXi, ahsCapsOmicron,
ahsCapsPi, ahsCapsRho, ahsCapsSigma, ahsCapsTau, ahsCapsUpsilon,
ahsCapsPhi, ahsCapsChi, ahsCapsPsi, ahsCapsOmega, ahsAlpha,
ahsBeta, ahsGamma, ahsDelta, ahsEpsilon, ahsZeta, ahsEta, ahsTheta,
ahsIota, ahsKappa, ahsLambda, ahsMu, ahsNu, ahsXi, ahsOmicron, ahsPi,
ahsRho, ahsSigmaf, ahsSigma, ahsTau, ahsUpsilon, ahsPhi, ahsChi, ahsPsi,
ahsOmega, ahsSpecialTheta, ahsSpecialUpsilonHooked, ahsSpecialPi);
TFslHTMLGreekSymbols = Set Of TFslHTMLGreekSymbol;
TFslHTMLMathSymbol = (
ahsNot, ahsMinus, ahsTimes, ahsPrime, ahsDblPrime, ahsFractionSlash,
ahsSuper2, ahsSuper3, ahsSuper1, ahsQuarter, ahsHalf, ahsThreeQuarter,
ahsPlusMinus, ahsForAll, ahsPartialDiff, ahsExist, ahsEmptySet, ahsNabla,
ahsIsIn, ahsNotIn, ahsContains, ahsProduct, ahsSum, ahsAsterisk, ahsSquareRoot,
ahsProportional, ahsInfinity, ahsAngle, ahsAnd, ahsOr, ahsIntersection,
ahsUnion, ahsIntegral, ahsTherefore, ahsSimilarTo, ahsApproxEqual,
ahsAsymptotic, ahsNotEqual, ahsEquivalent, ahsLessEqual, ahsGreaterEqual,
ahsSubset, ahsSuperset, ahsNotSubset, ahsSubSetEqual, ahsSupersetEqual,
ahsCirclePlus, ahsCircleTimes, ahsPerpendicular, ahsDot, ahsAlefSym);
TFslHTMLMathSymbols = Set Of TFslHTMLMathSymbol;
TFslHTMLSymbol = (
ahsQuote, ahsAmpersand, ahsLessThan, ahsGreaterThan, ahsLeftSingleQuote,
ahsRightSingleQuote,ahsSingleLowQuote, ahsLeftDoubleQuote, ahsRightDoubleQuote,
ahsDoubleLowQuote, ahsNonBreakingSpace,ahsDegrees, ahsCopyright, ahsRegistered,
ahsTrademark, ahsCent,ahsPound, ahsCurrency, ahsYen, ahsEuro, ahsLeftArrow, ahsUpArrow,
ahsRightArrow, ahsDownArrow, ahsleftRightArrow, ahsCarriageReturn, ahsLeftDoubleArrow,
ahsUpDoubleArrow, ahsRightDoubleArrow, ahsDownDoubleArrow, ahsLeftRightDoubleArrow,
ahsInvertedExcl, ahsInvertedQuestion, ahsBrokenVertical, ahsSection,
ahsUmlaut,ahsFeminineOrdinal, ahsLeftGuillemet, ahsRightGuillemet, ahsSoftHyphen,
ahsMacron,ahsAcute, ahsMicro, ahsParagraph, ahsMiddleDot, ahsCedilla,
ahsMasculineOrdinal, ahsLeftCeiling, ahsRightCeiling, ahsLeftFloor, ahsRightFloor,
ahsLeftAngle, ahsRightAngle, ahsLozenge, ahsSpades, ahsClubs,ahsHearts,
ahsDiams, ahsDagger, ahsDoubleDagger, ahsPerMille,ahsBullet, ahsHorizEllipsis,
ahsOverline, ahsWeierstrass, ahsImaginary, ahsReal);
TFslHTMLSymbols = Set Of TFslHTMLSymbol;
Type
TFslHTMLAdapter = Class(TFslStreamAdapter)
Private
FProduceXHTML : Boolean;
Public
Procedure Read(Var Buffer; iCount : Integer); Override;
Procedure Write(Const Buffer; iCount : Integer); Override;
Property ProduceXHTML : Boolean Read FProduceXHTML Write FProduceXHTML;
End;
TFslHTMLFormatter = Class(TFslXMLFormatter)
Private
FAdapter : TFslHTMLAdapter;
Function GetStyle: String;
Procedure SetStyle(Const Value: String);
Function GetProduceXHTML: Boolean;
Procedure SetProduceXHTML(Const Value: Boolean);
Protected
Procedure SetStream(oStream : TFslStream); Override;
Public
constructor Create; Override;
destructor Destroy; Override;
Function Link : TFslHTMLFormatter;
Function Clone : TFslHTMLFormatter;
Procedure ProduceDocumentType(Const sVersion, sDTD : String);
Procedure ProduceDocumentOpen;
Procedure ProduceDocumentClose;
Procedure ProduceHeadOpen;
Procedure ProduceHeadClose;
Procedure ProduceStyleOpen;
Procedure ProduceStyleClose;
Procedure ProduceStyleFragment(Const sName : String; oProperties : TFslStringMatch);
Procedure ProduceStyleFragmentOpen(Const sName : String);
Procedure ProduceStyleFragmentProperty(Const sName, sValue : String);
Procedure ProduceStyleFragmentClose;
Procedure ProduceBodyOpen;
Procedure ProduceBodyClose;
Procedure ProduceTitle(Const sTitle : String);
Procedure ProduceStylesheet(Const sFilename : String);
Procedure ProduceOpen(Const sTag : String; bInline : Boolean = False);
Procedure ProduceClose(Const sTag : String; bInline : Boolean = False);
Procedure ProduceInlineTag(Const sTag : String);
Procedure ProduceInlineDocument(Const sDocument : String);
Procedure ProduceHeading(Const sText : String; Const iLevel : Integer = 1);
Procedure ProducePreformatted(Const sData : String);
Procedure ProduceEscaped(Const sData : String);
Procedure ProduceAnchor(Const sCaption, sReference : String; Const sBookmark : String = ''; Const sTarget : String = '');
Procedure ProduceAnchorOpen(Const sReference : String; Const sBookmark : String = ''; Const sTarget : String = '');
Procedure ProduceAnchorClose;
Procedure ProduceBookmark(Const sBookmark : String);
Procedure ProduceImageReference(Const sReference : String; Const sAlternate : String = '');
Procedure ProduceLineBreak;
Procedure ProduceTableOpen;
Procedure ProduceTableClose;
Procedure ProduceTableHeadOpen;
Procedure ProduceTableHeadClose;
Procedure ProduceTableRowOpen;
Procedure ProduceTableRowClose;
Procedure ProduceTableCellOpen;
Procedure ProduceTableCellClose;
Procedure ProduceTableCellText(Const sText : String);
Procedure ProduceTableColumnGroupOpen;
Procedure ProduceTableColumnGroupClose;
Procedure ProduceTableColumn;
Procedure ProduceSpan(Const sText : String);
Procedure ProduceParagraph(Const sText : String);
Procedure ProduceMathSymbol(Const aSymbol : TFslHTMLMathSymbol);
Procedure ProduceGreekSymbol(Const aSymbol : TFslHTMLGreekSymbol);
Procedure ProduceSymbol(Const aSymbol : TFslHTMLSymbol);
Procedure ApplyAttributeAlignLeft;
Procedure ApplyAttributeAlignRight;
Procedure ApplyAttributeAlignCenter;
Procedure ApplyAttributeWidthPixel(Const iWidthPixel : Integer);
Procedure ApplyAttributeHeightPixel(Const iHeightPixel : Integer);
Procedure ApplyAttributeHeightPercentage(Const iHeightPercentage : Integer);
Property Style : String Read GetStyle Write SetStyle;
Property ProduceXHTML : Boolean Read GetProduceXHTML Write SetProduceXHTML;
End;
Const
HTML_GREEK_SYMBOL_VALUES : Array [TFslHTMLGreekSymbol] Of String = (
'Alpha', 'Beta', 'Gamma', 'Delta', 'Epsilon', 'Zeta', 'Eta', 'Theta',
'Iota', 'Kappa', 'Lambda', 'Mu', 'Nu', 'Xi', 'Omicron', 'Pi', 'Rho',
'Sigma', 'Tau', 'Upsilon', 'Phi', 'Chi', 'Psi', 'Omega', 'alpha',
'beta', 'gamma', 'delta', 'epsilon', 'zeta', 'eta', 'theta', 'iota', 'kappa',
'lambda', 'mu', 'nu', 'xi', 'omicron', 'pi', 'rho', 'sigmaf', 'sigma', 'tau',
'upsilon', 'phi', 'chi', 'psi', 'omega', 'thetasym', 'upsih', 'piv');
HTML_MATH_SYMBOL_VALUES : Array [TFslHTMLMathSymbol] Of String = (
'not', 'minus', 'times', 'prime', 'Prime', 'frasl', 'sup2', 'sup3', 'sup1',
'frac14', 'frac12', 'frac34', 'plusmn', 'forall', 'part', 'exist', 'empty',
'nabla', 'isin', 'notin', 'ni', 'prod', 'sum', 'lowast', 'radic', 'prop',
'infin', 'ang', 'and', 'or', 'cap', 'cup', 'int', 'there4', 'sim', 'cong',
'asymp', 'ne', 'equiv', 'le', 'ge', 'sub', 'sup', 'nsub', 'sube', 'supe',
'oplus', 'otimes', 'perp', '#8901', '#8501');
HTML_SYMBOL_VALUES : Array [TFslHTMLSymbol] Of String = (
'quot', 'amp', 'lt', 'gt', 'lsquo', 'rsquo', 'sbquo', 'ldquo', 'rdquo',
'bdquo', 'nbsp', 'deg', 'copy', 'reg', 'trade', 'cent', 'pound', 'curren',
'yen', 'euro', 'larr', 'uarr', 'rarr', 'darr', 'harr', 'crarr', 'lArr',
'uArr', 'rArr', 'dArr', 'hArr', 'iexcl', 'iquest', 'brvbar', 'sect', 'uml',
'ordf', 'laquo', 'raquo', 'shy', 'macr', 'acute', 'micro', 'para', 'middot',
'cedil', 'ordm', 'lceil', 'rceil', 'lfloor', 'rfloor', 'lang', 'rang', 'loz',
'spades', 'clubs', 'hearts', 'diams', 'dagger', 'Dagger', 'permil', 'bull',
'hellip', 'oline', 'weierp', 'image', 'real');
Implementation
Constructor TFslHTMLParser.Create;
Begin
Inherited;
FAttributes := TFslHTMLAttributes.Create;
FAttributes.Forced := True;
End;
Destructor TFslHTMLParser.Destroy;
Begin
FAttributes.Free;
Inherited;
End;
Function TFslHTMLParser.ReduceToken : TFslHTMLToken;
Begin
Result := PeekToken;
ConsumeToken;
End;
Function TFslHTMLParser.ReduceToken(Const aTokens: TFslHTMLTokens): TFslHTMLToken;
Begin
If Not (PeekToken In aTokens) Then
RaiseError('Reduce', StringFormat('Unexpected token found ''%s''.', [HTMLTOKEN_STRING[PeekToken]]));
Result := ReduceToken;
End;
Procedure TFslHTMLParser.ReduceToken(aToken: TFslHTMLToken);
Begin
If PeekToken <> aToken Then
RaiseError('ReduceToken', StringFormat('Expected token %s but found token %s.', [HTMLTOKEN_STRING[aToken], HTMLTOKEN_STRING[PeekToken]]));
ReduceToken;
End;
Function TFslHTMLParser.PeekToken: TFslHTMLToken;
Begin
Result := NextToken;
While Result In [ahtWhitespace, ahtComment] Do
Begin
ConsumeToken;
Result := NextToken;
End;
End;
Function TFslHTMLParser.NextIsTagOpen : Boolean;
Begin
Result := (FNextTagOpen <> '') Or (PeekToken In [ahtOpenTag, ahtOpenTagExclamation]);
End;
Function TFslHTMLParser.NextIsTagClose : Boolean;
Begin
Result := (FNextTagClose <> '') Or (PeekToken = ahtOpenTagForwardSlash);
End;
Function TFslHTMLParser.NextIsString: Boolean;
Begin
Result := PeekToken In [ahtSingleQuote, ahtDoubleQuote];
End;
Function TFslHTMLParser.NextTagOpen : String;
Var
sKey : String;
sValue : String;
Begin
If FNextTagOpen = '' Then
Begin
// <TagOpen> ::= '<' <Identifier> { <Attributes> } { '>' | '/>' }
ReduceToken(ahtOpenTag);
// Identifier
ReduceToken(ahtIdentifier);
FNextTagOpen := Value;
If PeekToken = ahtColon Then
Begin
ReduceToken(ahtColon);
ReduceToken(ahtIdentifier);
FNextTagOpen := FNextTagOpen + ':' + Value;
End;
FNextTagOpen := StringUpper(FNextTagOpen);
// Attributes
FAttributes.Clear;
While More And Not (PeekToken In [ahtCloseTag, ahtCloseTagForwardSlash]) Do
Begin { While }
ReduceToken(ahtIdentifier);
sKey := Value;
// TODO: handle namespaces properly 'xmlns:v="urn:schemas-microsoft-com:vml"'
If PeekToken = ahtColon Then
Begin
ReduceToken(ahtColon);
ReduceToken(ahtIdentifier);
sKey := sKey + ':' + Value;
End;
ReduceToken(ahtEquals);
If PeekToken In [ahtSingleQuote, ahtDoubleQuote] Then
Begin
sValue := ConsumeString;
End
Else
Begin
ReduceToken([ahtIdentifier, ahtNumber]);
sValue := Value;
End;
FAttributes.Add(sKey, sValue);
End; { While }
If PeekToken = ahtCloseTagForwardSlash Then
Begin
ReduceToken(ahtCloseTagForwardSlash);
FNextTagClose := FNextTagOpen;
End
Else
Begin
FNextTagClose := '';
ReduceToken(ahtCloseTag);
End;
End;
Result := FNextTagOpen;
End;
Function TFslHTMLParser.NextTagOpen(Const sTag: String): Boolean;
Begin
Assert(CheckCondition(UpperCase(sTag) = sTag, 'NextTagOpen', 'sTag must be uppercase.'));
Result := (NextIsTagOpen And (NextTagOpen = sTag));
End;
Function TFslHTMLParser.NextTagClose(Const sTag: String): Boolean;
Begin
Assert(CheckCondition(UpperCase(sTag) = sTag, 'NextTagClose', 'sTag must be uppercase.'));
Result := (NextIsTagClose And (NextTagClose = sTag));
End;
Function TFslHTMLParser.ConsumeTagOpen : String;
Begin
Result := NextTagOpen;
FNextTagOpen := '';
End;
Function TFslHTMLParser.NextTagClose : String;
Begin
If FNextTagClose = '' Then
Begin
// <TagClose> ::= '</' <Identifier> '>'
ReduceToken(ahtOpenTagForwardSlash);
// Identifier
ReduceToken(ahtIdentifier);
FNextTagClose := Value;
If PeekToken = ahtColon Then
Begin
ReduceToken(ahtColon);
ReduceToken(ahtIdentifier);
FNextTagClose := FNextTagClose + ':' + Value;
End;
FNextTagClose := StringUpper(FNextTagClose);
ReduceToken(ahtCloseTag);
FAttributes.Clear;
End;
Result := FNextTagClose;
End;
Function TFslHTMLParser.ConsumeTagClose : String;
Begin
Result := NextTagClose;
FNextTagClose := '';
End;
Procedure TFslHTMLParser.ConsumeTagOpen(Const sTag: String);
Var
sValue : String;
Begin
sValue := ConsumeTagOpen;
If Not StringEquals(sValue, sTag) Then
RaiseError('ConsumeTagOpen', StringFormat('Expected tag <%s> but found tag <%s>', [sTag, sValue]));
End;
Procedure TFslHTMLParser.ConsumeTagClose(Const sTag: String);
Var
sValue : String;
Begin
sValue := ConsumeTagClose;
If Not StringEquals(sValue, sTag) Then
RaiseError('ConsumeTagClose', StringFormat('Expected tag </%s> but found tag </%s>', [sTag, sValue]));
End;
Function TFslHTMLParser.ConsumeTagBody: String;
Begin
Result := '';
While More And (NextToken In HTMLTOKEN_BODY_SET) Do
Begin
ConsumeToken;
StringAppend(Result, Value, '');
End;
End;
Procedure TFslHTMLParser.ConsumeIdentifier(Const sIdentifier: String);
Begin
ReduceToken(ahtIdentifier);
If Not StringEquals(Value, sIdentifier) Then
RaiseError('ConsumeTagClose', StringFormat('Expected identifier ''%s'' but found identifier ''%s''', [sIdentifier, Value]));
End;
Function TFslHTMLParser.ConsumeString : String;
Var
aQuote : TFslHTMLToken;
Begin
Result := '';
If PeekToken = ahtSingleQuote Then
aQuote := ahtSingleQuote
Else
aQuote := ahtDoubleQuote;
ReduceToken(aQuote);
While More And (NextToken <> aQuote) Do
Begin
ConsumeToken;
Result := Result + Value;
End;
ReduceToken(aQuote);
End;
Function TFslHTMLParser.ConsumeItem: TFslHTMLItem;
Var
sTag : String;
Begin
Result := Nil;
Try
// TODO: smarter implementation.
//If (FNextTagOpen <> '') Or (PeekToken In [ahtOpenTag, ahtOpenTagExclamation]) Then
//Begin
// sTag := FNextTagOpen;
If NextIsTagOpen Then
Begin
sTag := NextTagOpen;
If sTag = 'P' Then
Begin
Result := TFslHTMLParagraph.Create;
ConsumeParagraph(TFslHTMLParagraph(Result));
End
Else If sTag = 'A' Then
Begin
Result := TFslHTMLAnchor.Create;
ConsumeAnchor(TFslHTMLAnchor(Result));
End
Else If sTag = 'I' Then
Begin
Result := TFslHTMLItalic.Create;
ConsumeItalic(TFslHTMLItalic(Result));
End
Else If sTag = 'B' Then
Begin
Result := TFslHTMLBold.Create;
ConsumeBold(TFslHTMLBold(Result));
End
Else If sTag = 'BR' Then
Begin
Result := TFslHTMLBreak.Create;
ConsumeBreak(TFslHTMLBreak(Result));
End
Else If sTag = 'HR' Then
Begin
Result := TFslHTMLHorizontalRule.Create;
ConsumeHorizontalRule(TFslHTMLHorizontalRule(Result));
End
Else If sTag = 'U' Then
Begin
Result := TFslHTMLUnderline.Create;
ConsumeUnderline(TFslHTMLUnderline(Result));
End
Else If sTag = 'UL' Then
Begin
Result := TFslHTMLUnorderedList.Create;
ConsumeUnorderedList(TFslHTMLUnorderedList(Result));
End
Else If sTag = 'OL' Then
Begin
Result := TFslHTMLOrderedList.Create;
ConsumeOrderedList(TFslHTMLOrderedList(Result));
End
Else If sTag = 'LI' Then
Begin
Result := TFslHTMLListItem.Create;
ConsumeListItem(TFslHTMLListItem(Result));
End
Else If sTag = 'SUP' Then
Begin
Result := TFslHTMLSuperscript.Create;
ConsumeSuperscript(TFslHTMLSuperscript(Result));
End
Else If sTag = 'SUB' Then
Begin
Result := TFslHTMLSubscript.Create;
ConsumeSubscript(TFslHTMLSubscript(Result));
End
Else If sTag = 'DIV' Then
Begin
Result := TFslHTMLContainer.Create;
ConsumeContainer(TFslHTMLContainer(Result));
End
Else If sTag = 'IMG' Then
Begin
Result := TFslHTMLImage.Create;
ConsumeImage(TFslHTMLImage(Result));
End
Else If sTag = 'FONT' Then
Begin
Result := TFslHTMLFont.Create;
ConsumeFont(TFslHTMLFont(Result));
End
Else If sTag = 'SPAN' Then
Begin
Result := TFslHTMLSpan.Create;
ConsumeSpan(TFslHTMLSpan(Result));
End
Else If sTag = 'TABLE' Then
Begin
Result := TFslHTMLTable.Create;
ConsumeTable(TFslHTMLTable(Result));
End
Else If sTag = 'TR' Then
Begin
Result := TFslHTMLTableRow.Create;
ConsumeTableRow(TFslHTMLTableRow(Result));
End
Else If (sTag = 'TD') Or (sTag = 'TH') Then
Begin
Result := TFslHTMLTableCell.Create;
ConsumeTableCell(TFslHTMLTableCell(Result));
End
Else If sTag = 'BLOCKQUOTE' Then
Begin
Result := TFslHTMLBlockQuote.Create;
ConsumeBlockQuote(TFslHTMLBlockQuote(Result));
End
Else If sTag = 'INPUT' Then
Begin
Result := TFslHTMLInput.Create;
ConsumeInput(TFslHTMLInput(Result));
End
Else If (Length(sTag) = 2) And (sTag[1] = 'H') And CharInSet(sTag[2], ['1'..'6']) Then
Begin
Result := TFslHTMLHeading.Create;
ConsumeHeading(TFslHTMLHeading(Result));
End
Else If sTag = 'PRE' Then
Begin
Result := TFslHTMLPreformatted.Create;
ConsumePre(TFslHTMLPreformatted(Result));
End
Else
Begin
// Ignore unknown tags.
ConsumeSection(sTag);
End
End
Else
Begin
Result := TFslHTMLTextFragment.Create;
ConsumeTextFragment(TFslHTMLTextFragment(Result));
End;
Assert(Not Assigned(Result) Or Invariants('ConsumeItem', Result, TFslHTMLItem, 'Result (' + sTag + ')'));
Result.Link;
Finally
Result.Free;
End;
End;
Procedure TFslHTMLParser.ConsumeSection(Const sTag: String);
Var
oSection : TFslHTMLSection;
Begin
// Ignore unhandled section.
oSection := TFslHTMLSection.Create;
Try
ConsumeSection(sTag, oSection);
Finally
oSection.Free;
End;
End;
Procedure TFslHTMLParser.ReadStyles(oStyles : TFslStringMatch; Const sValue: String);
Var
sTemp : String;
sItem : String;
iPos : Integer;
iSymbol : Integer;
sLeft : String;
sRight : String;
Begin
oStyles.Clear;
sTemp := sValue;
iPos := Pos(';', sTemp);
iSymbol := Length(';');
While (iPos > 0) Do
Begin
sItem := System.Copy(sTemp, 1, iPos - 1);
If StringSplit(sItem, ':', sLeft, sRight) Then
oStyles.Add(StringTrimWhitespace(sLeft), StringTrimWhitespace(sRight))
Else
oStyles.Add(StringTrimWhitespace(sItem), '');
System.Delete(sTemp, 1, iPos + iSymbol - 1);
iPos := Pos(';', sTemp);
End;
If sTemp <> '' Then
Begin
If StringSplit(sTemp, ':', sLeft, sRight) Then
oStyles.Add(StringTrimWhitespace(sLeft), StringTrimWhitespace(sRight))
Else
oStyles.Add(StringTrimWhitespace(sTemp), '');
End;
End;
Procedure TFslHTMLParser.ReadItem(oItem: TFslHTMLItem);
Begin
oItem.ID := FAttributes['ID'];
oItem.TitleAttribute := FAttributes['Title'];
ReadStyles(oItem.Style.Values, FAttributes['Style']);
oItem.Classes.AsText := FAttributes['Class'];
End;
Procedure TFslHTMLParser.ConsumeSection(Const sTag: String; oSection: TFslHTMLSection);
Begin
ConsumeTagOpen(sTag);
if (sTag[Length(sTag)] <> '/') Then
Begin
ReadItem(oSection);
ConsumeItems(oSection.Items);
If NextTagClose(sTag) Then
ConsumeTagClose(sTag);
End;
End;
Procedure TFslHTMLParser.ConsumeItems(oItems: TFslHTMLItems);
Var
oItem : TFslHTMLItem;
Begin
oItems.Clear;
While More And Not NextIsTagClose Do
Begin
oItem := ConsumeItem;
If Assigned(oItem) Then
oItems.Add(oItem);
End;
End;
Procedure TFslHTMLParser.ConsumeImage(oImage: TFslHTMLImage);
Begin
// <Image> ::= '<IMG' {<ImageAttributes>} '>'
//
// <ImageAttributes> ::= { 'src' '=' <URL> } { 'alt' '=' <String> } { 'longdesc' = <String> } { 'align' '=' <Align> }
//
// <Align> ::= 'left' | 'top' | 'right' | 'bottom' | 'middle'
ConsumeTagOpen('IMG');
oImage.Name := FAttributes['name'];
oImage.Source := FAttributes['src'];
oImage.Alternative := FAttributes['alt'];
oImage.LongDescription := FAttributes['longdesc'];
oImage.Width := FAttributes['width'];
oImage.Height := FAttributes['height'];
oImage.HorizontalSpace := FAttributes['hspace'];
oImage.VerticalSpace := FAttributes['vspace'];
oImage.Align := TFslHTMLAlign(IntegerMin(StringArrayIndexOf(ADVHTMLALIGN_NAMES, FAttributes['align']), 0));
ReadItem(oImage);
If NextTagClose('IMG') Then
ConsumeTagClose('IMG');
End;
Procedure TFslHTMLParser.ConsumeTableCell(oTableCell: TFslHTMLTableCell);
Var
sTag : String;
Begin
// <TableCell> ::= <TableDataCell> | <TableHeaderCell>
// <TableDataCell> ::= '<TD>' <TableCell>* '</TD>'
// <TableHeaderCell> ::= '<TH>' <TableCell>* '</TH>'
sTag := ConsumeTagOpen;
oTableCell.IsHeader := sTag = 'TH';
oTableCell.Width := FAttributes['width'];
oTableCell.Height := FAttributes['height'];
ReadItem(oTableCell);
ConsumeItems(oTableCell.Items);
ConsumeTagClose(sTag);
End;
Procedure TFslHTMLParser.ConsumeTableRow(oTableRow: TFslHTMLTableRow);
Var
oCell : TFslHTMLTableCell;
Begin
// <TableRow> ::= '<TR>' <TableCell>* '</TR>'
ConsumeTagOpen('TR');
ReadItem(oTableRow);
While More And Not NextIsTagClose Do
Begin
If NextTagOpen('TD') Or NextTagOpen('TH') Then
Begin
oCell := TFslHTMLTableCell.Create;
Try
ConsumeTableCell(oCell);
oTableRow.Cells.Add(oCell.Link);
Finally
oCell.Free;
End;
End
Else
Begin
// TODO: table row elements.
ConsumeSection(NextTagOpen);
End;
End;
ConsumeTagClose('TR');
End;
Procedure TFslHTMLParser.ConsumeTable(oTable: TFslHTMLTable);
Var
oRow : TFslHTMLTableRow;
sInnerTag : String;
Begin
// <Table> ::= '<TABLE>' <TableRow>* '</TABLE>'
// TODO: COLGROUPS, THEAD/TFOOT/TBODY
ConsumeTagOpen('TABLE');
ReadItem(oTable);
sInnerTag := '';
While More And ((sInnerTag <> '') Or Not NextIsTagClose) Do
Begin
If NextTagOpen('TR') Then
Begin
oRow := TFslHTMLTableRow.Create;
Try
ConsumeTableRow(oRow);
oTable.Rows.Add(oRow.Link);
Finally
oRow.Free;
End;
End
Else If NextIsTagOpen Then
Begin
sInnerTag := NextTagOpen();
If (sInnerTag = 'THEAD') Or (sInnerTag = 'TFOOT') Or (sInnerTag = 'TBODY') Then
ConsumeTagOpen(sInnerTag)
Else
RaiseError('ConsumeTable', 'Unexpected tag encountered inside table ' + sInnerTag);
End
Else If (sInnerTag <> '') Then
Begin
ConsumeTagClose(sInnerTag);
sInnerTag := '';
End;
End;
ConsumeTagClose('TABLE');
End;
Procedure TFslHTMLParser.ConsumeHeading(oHeading: TFslHTMLHeading);
Var
sTag : String;
iLevel : Integer;
Begin
// <Heading> ::= '<' <HeadingLevel> '>' <Item>* '</' <HeadingLevel '>'
//
// <HeadingLevel> ::= 'H1' | 'H2' | 'H3' | 'H4' | 'H5' | 'H6'
sTag := ConsumeTagOpen;
ReadItem(oHeading);
iLevel := StringToInteger32(Copy(sTag, 2, MaxInt)) - 1;
If (iLevel >= Integer(Low(TFslHTMLHeadingLevel))) And (iLevel <= Integer(High(TFslHTMLHeadingLevel))) Then
oHeading.Level := TFslHTMLHeadingLevel(iLevel)
Else
oHeading.Level := Low(TFslHTMLHeadingLevel);
ConsumeItems(oHeading.Items);
ConsumeTagClose(sTag);
End;
Procedure TFslHTMLParser.ConsumeAnchor(oAnchor : TFslHTMLAnchor);
Begin
// <Anchor> ::= '<A>' <Item>* '</A>'
ConsumeTagOpen('A');
ReadItem(oAnchor);
oAnchor.URL := FAttributes['href'];
oAnchor.Name := FAttributes['name'];
oAnchor.AccessKey := FAttributes['accesskey'];
ConsumeItems(oAnchor.Items);
ConsumeTagClose('A');
End;
Procedure TFslHTMLParser.ConsumeFont(oFont: TFslHTMLFont);
Begin
// <Font> ::= '<FONT>' <Item>* '</FONT>'
oFont.Color := FAttributes['color'];
ConsumeSection('FONT', oFont);
End;
Procedure TFslHTMLParser.ConsumeSpan(oSpan: TFslHTMLSpan);
Begin
// <Span> ::= '<Span>' <Item>* '</Span>'
ConsumeSection('SPAN', oSpan);
End;
Procedure TFslHTMLParser.ConsumeUnorderedList(oList: TFslHTMLUnorderedList);
Begin
// <UnorderedList> ::= '<UL>' <Item>* '</UL>'
ConsumeSection('UL', oList);
End;
Procedure TFslHTMLParser.ConsumeOrderedList(oList: TFslHTMLOrderedList);
Begin
// <OrderedList> ::= '<OL>' <Item>* '</OL>'
ConsumeSection('OL', oList);
End;
Procedure TFslHTMLParser.ConsumeListItem(oItem: TFslHTMLListItem);
Begin
// <ListItem> ::= '<LI value="">' <Item>* '</LI>'
oItem.Value := StrToIntDef(FAttributes['value'], 0);
oItem.HasValue := FAttributes['value'] <> '';
ConsumeSection('LI', oItem);
End;
Procedure TFslHTMLParser.ConsumeSubscript(oSubscript: TFslHTMLSubscript);
Begin
ConsumeSection('SUB', oSubscript);
End;
Procedure TFslHTMLParser.ConsumeSuperscript(oSuperscript: TFslHTMLSuperscript);
Begin
ConsumeSection('SUP', oSuperscript);
End;
Procedure TFslHTMLParser.ConsumeBreak(oBreak: TFslHTMLBreak);
Begin
// <Break> ::= '<BR>' Or '<BR />' Or '<BR></BR>'
ConsumeTagOpen('BR');
ReadItem(oBreak);
If NextTagClose('BR') Then
ConsumeTagClose('BR');
End;
Procedure TFslHTMLParser.ConsumeHorizontalRule(oHorizontalRule: TFslHTMLHorizontalRule);
Begin
// <HorizontalRule> ::= '<HR>' Or '<HR />' Or '<HR></HR>'
ConsumeTagOpen('HR');
ReadItem(oHorizontalRule);
If NextTagClose('HR') Then
ConsumeTagClose('HR');
End;
Procedure TFslHTMLParser.ConsumeInput(oInput: TFslHTMLInput);
Begin
// <Input> ::= '<INPUT' <InputAttributes> '>'
ConsumeTagOpen('INPUT');
End;
Procedure TFslHTMLParser.ConsumeBold(oBold: TFslHTMLBold);
Begin
ConsumeSection('B', oBold);
End;
Procedure TFslHTMLParser.ConsumeItalic(oItalic: TFslHTMLItalic);
Begin
ConsumeSection('I', oItalic);
End;
Procedure TFslHTMLParser.ConsumeUnderline(oUnderline: TFslHTMLUnderline);
Begin
ConsumeSection('U', oUnderline);
End;
Procedure TFslHTMLParser.ConsumeBlockQuote(oBlockQuote : TFslHTMLBlockQuote);
Begin
ConsumeSection('BLOCKQUOTE', oBlockQuote);
End;
Procedure TFslHTMLParser.ConsumeParagraph(oParagraph: TFslHTMLParagraph);
Begin
// <Paragraph> ::= '<P>' <Item>* '</P>'
ConsumeSection('P', oParagraph);
End;
Procedure TFslHTMLParser.ConsumeContainer(oContainer: TFslHTMLContainer);
Begin
ConsumeSection('DIV', oContainer);
End;
Procedure TFslHTMLParser.ConsumeTextFragment(oTextFragment : TFslHTMLTextFragment);
Begin
oTextFragment.Text := ConsumeTagBody;
End;
Procedure TFslHTMLParser.ConsumeBody(oBody: TFslHTMLBody);
Begin
// <Body> ::= '<BODY>' <Item>* '</BODY>'
ConsumeSection('BODY', oBody);
End;
Procedure TFslHTMLParser.ConsumeStyles(oStyles: TFslCSSStyles);
Var
oStyle : TFslCSSStyle;
sKey : String;
sValue : String;
Begin
// <Styles> ::= '<STYLE>' <Style>* '</STYLE>
// <Style> ::= <StyleName> '{' ( <StyleKey> ':' <StyleValue> ';' ) * '}'
ConsumeTagOpen('STYLE');
While More And Not NextTagClose('STYLE') Do
Begin
oStyle := TFslCSSStyle.Create;
Try
sValue := '';
While PeekToken In [ahtIdentifier, ahtColon, ahtPeriod, ahtHash] Do
Begin
ReduceToken;
StringAppend(sValue, Value);
End;
oStyle.Name := sValue;
If PeekToken = ahtOpenBrace Then
Begin
ReduceToken(ahtOpenBrace);
While More And (PeekToken <> ahtCloseBrace) Do
Begin
ReduceToken(ahtIdentifier);
sKey := Value;
ReduceToken(ahtColon);
sValue := '';
While PeekToken In [ahtNumber, ahtIdentifier, ahtHash] Do
Begin
ReduceToken;
StringAppend(sValue, Value);
End;
oStyle.Values.Add(sKey, sValue);
If PeekToken = ahtSemicolon Then
ReduceToken(ahtSemicolon);
End;
ReduceToken(ahtCloseBrace);
End;
oStyles.Add(oStyle.Link);
Finally
oStyle.Free;
End;
End;
ConsumeTagClose('STYLE');
End;
Procedure TFslHTMLParser.ConsumeMetaEntry(oEntries : TFslHTMLMetaEntries);
Var
oMetaEntry : TFslHTMLMetaEntry;
Begin
ConsumeTagOpen('META');
oMetaEntry := TFslHTMLMetaEntry.Create;
Try
oMetaEntry.HttpEquiv := FAttributes['http-equiv'];
oMetaEntry.Content := FAttributes['content'];
oMetaEntry.Name := FAttributes['name'];
oMetaEntry.Scheme := FAttributes['scheme'];
oEntries.Add(oMetaEntry.Link);
Finally
oMetaEntry.Free;
End;
If NextTagClose('META') Then
ConsumeTagClose('META');
End;
Procedure TFslHTMLParser.ConsumeHead(oHead: TFslHTMLHead);
Begin
// <Head> ::= '<HEAD>' { '<TITLE>' <Body> '</TITLE>' } { '<' 'META' <Attributes> '>' }
ConsumeTagOpen('HEAD');
ConsumeWhitespace;
While More And Not NextTagClose('HEAD') Do
Begin
If NextTagOpen('TITLE') Then
Begin
ConsumeTagOpen('TITLE');
oHead.Title := ConsumeTagBody;
ConsumeTagClose('TITLE');
End
Else If NextTagOpen('META') Then
Begin
ConsumeMetaEntry(oHead.Meta);
End
Else If NextTagOpen('LINK') Then
Begin
ConsumeSection('LINK');
End
Else If NextTagOpen('SCRIPT') Then
Begin
ConsumeSection('SCRIPT');
// TODO: Scripts
End
Else If NextTagOpen('STYLE') Then
Begin
ConsumeStyles(oHead.Styles);
End
Else
Begin
// TODO: Other head items.
RaiseError('ConsumeHead', StringFormat('Open tag ''%s'' not recognised.', [NextTagOpen]));
End;
ConsumeWhitespace;
End;
ConsumeTagClose('HEAD');
End;
Procedure TFslHTMLParser.ConsumeDocumentType(oDocument: TFslHTMLDocument);
Begin
// <DocumentType> ::= { '<' !DOCTYPE' 'HTML' 'PUBLIC' <Version> <DTD> '>' }
If PeekToken = ahtOpenTagQuery Then
Begin
ReduceToken(ahtOpenTagQuery);
ConsumeIdentifier('XML');
// Ignore XML all attributes
While PeekToken <> ahtCloseTagQuery Do
Begin
ReduceToken(ahtIdentifier);
ReduceToken(ahtEquals);
ConsumeString;
End;
ReduceToken(ahtCloseTagQuery);
End;
If PeekToken = ahtOpenTagExclamation Then
Begin
ReduceToken(ahtOpenTagExclamation);
ConsumeIdentifier('DOCTYPE');
ConsumeIdentifier('HTML');
ConsumeIdentifier('PUBLIC');
If NextIsString Then
Begin
oDocument.Version := ConsumeString;
If NextIsString Then
oDocument.DTD := ConsumeString;
End;
ReduceToken(ahtCloseTag);
End;
End;
Procedure TFslHTMLParser.ConsumeDocument(oDocument: TFslHTMLDocument);
Begin
// <Document> ::= <DocumentType> '<HTML>' { <Head> } { <Body> } | '</HTML>'
oDocument.Clear;
ConsumeDocumentType(oDocument);
If NextTagOpen('HTML') Then
Begin
ConsumeTagOpen('HTML');
ConsumeWhitespace;
If NextTagOpen('HEAD') Then
ConsumeHead(oDocument.Head);
ConsumeWhitespace;
If NextTagOpen('STYLE') Then
ConsumeStyles(oDocument.Styles);
ConsumeWhitespace;
If NextTagOpen('BODY') Then
ConsumeBody(oDocument.Body);
ConsumeWhitespace;
ConsumeTagClose('HTML');
End
Else
Begin
ConsumeItems(oDocument.Body.Items);
End;
End;
Procedure TFslHTMLParser.ConsumeDocumentHead(oHead : TFslHTMLHead);
Var
oDocument : TFslHTMLDocument;
Begin
oHead.Clear;
oDocument := TFslHTMLDocument.Create;
Try
ConsumeDocumentType(oDocument);
If NextTagOpen('HTML') Then
Begin
ConsumeTagOpen('HTML');
If NextTagOpen('HEAD') Then
ConsumeHead(oHead);
End;
Finally
oDocument.Free;
End;
End;
procedure TFslHTMLParser.ConsumePre(oPre: TFslHTMLPreformatted);
begin
ConsumeSection('PRE', oPre);
end;
Constructor TFslCSSFragment.Create;
Begin
Inherited;
FValues := TFslCSSValues.Create;
FValues.Symbol := ';';
FValues.Separator := ':';
End;
Destructor TFslCSSFragment.Destroy;
Begin
FValues.Free;
Inherited;
End;
Procedure TFslCSSFragment.Assign(oSource: TFslObject);
Begin
Inherited;
FValues.Assign(TFslCSSFragment(oSource).Values);
End;
Function TFslCSSFragment.Clone: TFslCSSFragment;
Begin
Result := TFslCSSFragment(Inherited Clone);
End;
Function TFslCSSFragment.Link: TFslCSSFragment;
Begin
Result := TFslCSSFragment(Inherited Link);
End;
Function TFslCSSFragments.GetFragment(iIndex: Integer): TFslCSSFragment;
Begin
Result := TFslCSSFragment(ObjectByIndex[iIndex]);
End;
Function TFslCSSFragments.ItemClass: TFslObjectClass;
Begin
Result := TFslCSSFragment;
End;
Procedure TFslCSSStyle.Assign(oSource: TFslObject);
Begin
Inherited;
Name := TFslCSSStyle(oSource).Name;
End;
Function TFslCSSStyle.Clone: TFslCSSStyle;
Begin
Result := TFslCSSStyle(Inherited Clone);
End;
Function TFslCSSStyle.Link: TFslCSSStyle;
Begin
Result := TFslCSSStyle(Inherited Link);
End;
Function TFslCSSStyles.GetScript(iIndex: Integer): TFslCSSStyle;
Begin
Result := TFslCSSStyle(ObjectByIndex[iIndex]);
End;
Function TFslCSSStyles.ItemClass: TFslObjectClass;
Begin
Result := TFslCSSStyle;
End;
Constructor TFslCSSValues.Create;
Begin
Inherited;
Forced := True;
End;
Function TFslCSSValues.GetMatch(Const sKey: String): String;
Begin
Result := GetValueByKey(sKey);
End;
Procedure TFslCSSValues.SetMatch(Const sKey, sValue: String);
Begin
SetValueByKey(sKey, sValue);
End;
Constructor TFslHTMLAttributes.Create;
Begin
Inherited;
Forced := True;
End;
Function TFslHTMLAttributes.GetAttribute(Const sKey: String): String;
Begin
Result := GetValueByKey(sKey);
End;
Procedure TFslHTMLAttributes.SetAttribute(Const sKey, sValue: String);
Begin
SetValueByKey(sKey, sValue);
End;
Procedure TFslHTMLElement.Assign(oSource: TFslObject);
Begin
Inherited;
FTitleAttribute := TFslHTMLElement(oSource).FTitleAttribute;
End;
Procedure TFslHTMLElement.Clear;
Begin
End;
Function TFslHTMLElements.ItemClass: TFslObjectClass;
Begin
Result := TFslHTMLElement;
End;
Function TFslHTMLElements.GetElement(iIndex: Integer): TFslHTMLElement;
Begin
Result := TFslHTMLElement(ObjectByIndex[iIndex]);
End;
Procedure TFslHTMLItem.Assign(oSource: TFslObject);
Begin
Inherited;
FId := TFslHTMLItem(oSource).FId;
FClasses.Assign(TFslHTMLItem(oSource).FClasses);
Style := TFslHTMLItem(oSource).FStyle.Link;
End;
Function TFslHTMLItem.Clone: TFslHTMLItem;
Begin
Result := TFslHTMLItem(Inherited Clone);
End;
Constructor TFslHTMLItem.Create;
Begin
Inherited;
FClasses := TFslCSSClasses.Create;
FStyle := TFslCSSFragment.Create;
FClasses.Symbol := ' ';
End;
Destructor TFslHTMLItem.Destroy;
Begin
FClasses.Free;
FStyle.Free;
Inherited;
End;
Function TFslHTMLItem.ElementType: TFslHTMLElementType;
Begin
Result := ahError;
RaiseError('ElementType', 'Need to override ElementType in '+ClassName);
End;
Function TFslHTMLItem.Link: TFslHTMLItem;
Begin
Result := TFslHTMLItem(Inherited Link);
End;
Procedure TFslHTMLItem.SetClasses(Const oValue: TFslCSSClasses);
Begin
FClasses.Free;
FClasses := oValue;
End;
Procedure TFslHTMLItem.SetStyle(Const oValue: TFslCSSFragment);
Begin
FStyle.Free;
FStyle := oValue;
End;
Function TFslHTMLItems.GetHTMLItem(iIndex: Integer): TFslHTMLItem;
Begin
Result := TFslHTMLItem(ObjectByIndex[iIndex]);
End;
Function TFslHTMLItems.ItemClass: TFslObjectClass;
Begin
Result := TFslHTMLItem;
End;
Procedure TFslHTMLComment.Assign(oSource: TFslObject);
Begin
Inherited;
FText := TFslHTMLComment(oSource).FText;
End;
Function TFslHTMLComment.Clone: TFslHTMLComment;
Begin
Result := TFslHTMLComment(Inherited Clone);
End;
Function TFslHTMLComment.ElementType: TFslHTMLElementType;
Begin
Result := ahComment;
End;
Function TFslHTMLComment.Link: TFslHTMLComment;
Begin
Result := TFslHTMLComment(Inherited Link);
End;
Procedure TFslHTMLTextFragment.Assign(oSource: TFslObject);
Begin
Inherited;
FText := TFslHTMLTextFragment(oSource).FText;
End;
Function TFslHTMLTextFragment.Clone: TFslHTMLTextFragment;
Begin
Result := TFslHTMLTextFragment(Inherited Clone);
End;
Function TFslHTMLTextFragment.ElementType: TFslHTMLElementType;
Begin
Result := ahTextFragment;
End;
Function TFslHTMLTextFragment.Link: TFslHTMLTextFragment;
Begin
Result := TFslHTMLTextFragment(Inherited Link);
End;
Procedure TFslHTMLEntity.Assign(oSource: TFslObject);
Begin
Inherited;
FEntity := TFslHTMLEntity(oSource).FEntity;
End;
Function TFslHTMLEntity.Clone: TFslHTMLEntity;
Begin
Result := TFslHTMLEntity(Inherited Clone);
End;
Function TFslHTMLEntity.ElementType: TFslHTMLElementType;
Begin
Result := ahEntity;
End;
Function TFslHTMLEntity.Link: TFslHTMLEntity;
Begin
Result := TFslHTMLEntity(Inherited Link);
End;
Procedure TFslHTMLImage.Assign(oSource: TFslObject);
Begin
Inherited;
FHorizontalSpace := TFslHTMLImage(oSource).FHorizontalSpace;
FAlternative := TFslHTMLImage(oSource).FAlternative;
FLongDescription := TFslHTMLImage(oSource).FLongDescription;
FHeight := TFslHTMLImage(oSource).FHeight;
FBorder := TFslHTMLImage(oSource).FBorder;
FSource := TFslHTMLImage(oSource).FSource;
FName := TFslHTMLImage(oSource).FName;
FVerticalSpace := TFslHTMLImage(oSource).FVerticalSpace;
FWidth := TFslHTMLImage(oSource).FWidth;
FAlign := TFslHTMLImage(oSource).FAlign;
End;
Function TFslHTMLImage.Clone: TFslHTMLImage;
Begin
Result := TFslHTMLImage(Inherited Clone);
End;
Function TFslHTMLImage.ElementType: TFslHTMLElementType;
Begin
Result := ahImageReference;
End;
Function TFslHTMLImage.Link: TFslHTMLImage;
Begin
Result := TFslHTMLImage(Inherited Link);
End;
Procedure TFslHTMLAnchor.Assign(oSource: TFslObject);
Begin
Inherited;
FURL := TFslHTMLAnchor(oSource).FURL;
FName := TFslHTMLAnchor(oSource).FName;
FAccessKey := TFslHTMLAnchor(oSource).FAccessKey;
End;
Function TFslHTMLAnchor.Clone: TFslHTMLAnchor;
Begin
Result := TFslHTMLAnchor(Inherited Clone);
End;
Function TFslHTMLAnchor.ElementType: TFslHTMLElementType;
Begin
Result := ahAnchor;
End;
Function TFslHTMLAnchor.Link: TFslHTMLAnchor;
Begin
Result := TFslHTMLAnchor(Inherited Link);
End;
Procedure TFslHTMLBreak.Assign(oSource: TFslObject);
Begin
Inherited;
FClearType := TFslHTMLBreak(oSource).FClearType;
End;
Function TFslHTMLBreak.Clone: TFslHTMLBreak;
Begin
Result := TFslHTMLBreak(Inherited Clone);
End;
Function TFslHTMLBreak.ElementType: TFslHTMLElementType;
Begin
Result := ahBreak;
End;
Function TFslHTMLBreak.Link: TFslHTMLBreak;
Begin
Result := TFslHTMLBreak(Inherited Link);
End;
Procedure TFslHTMLSection.Assign(oSource: TFslObject);
Begin
Inherited;
FItems.Assign(TFslHTMLSection(oSource).FItems);
End;
Procedure TFslHTMLSection.Clear;
Begin
Inherited;
FItems.Clear;
End;
Function TFslHTMLSection.Clone: TFslHTMLSection;
Begin
Result := TFslHTMLSection(Inherited Clone);
End;
Constructor TFslHTMLSection.Create;
Begin
Inherited;
FItems := TFslHTMLItems.Create;
End;
Destructor TFslHTMLSection.Destroy;
Begin
FItems.Free;
Inherited;
End;
Function TFslHTMLSection.ElementType: TFslHTMLElementType;
Begin
Result := ahSection;
End;
Function TFslHTMLSection.Link: TFslHTMLSection;
Begin
Result := TFslHTMLSection(Inherited Link);
End;
Procedure TFslHTMLSection.SetItems(Const oValue: TFslHTMLItems);
Begin
FItems.Free;
FItems := oValue;
End;
Procedure TFslHTMLSpan.Assign(oSource: TFslObject);
Begin
Inherited;
FAlign := TFslHTMLSpan(oSource).FAlign;
End;
Function TFslHTMLSpan.Clone: TFslHTMLSpan;
Begin
Result := TFslHTMLSpan(Inherited Clone);
End;
Function TFslHTMLSpan.ElementType: TFslHTMLElementType;
Begin
Result := ahSpan;
End;
Function TFslHTMLSpan.Link: TFslHTMLSpan;
Begin
Result := TFslHTMLSpan(Inherited Link);
End;
Function TFslHTMLEmphasis.Clone: TFslHTMLEmphasis;
Begin
Result := TFslHTMLEmphasis(Inherited Clone);
End;
Function TFslHTMLEmphasis.ElementType: TFslHTMLElementType;
Begin
Result := ahEmphasis;
End;
Function TFslHTMLEmphasis.Link: TFslHTMLEmphasis;
Begin
Result := TFslHTMLEmphasis(Inherited Link);
End;
Function TFslHTMLStrong.Clone: TFslHTMLStrong;
Begin
Result := TFslHTMLStrong(Inherited Clone);
End;
Function TFslHTMLStrong.ElementType: TFslHTMLElementType;
Begin
Result := ahStrong;
End;
Function TFslHTMLStrong.Link: TFslHTMLStrong;
Begin
Result := TFslHTMLStrong(Inherited Link);
End;
Function TFslHTMLCitation.Clone: TFslHTMLCitation;
Begin
Result := TFslHTMLCitation(Inherited Clone);
End;
Function TFslHTMLCitation.ElementType: TFslHTMLElementType;
Begin
Result := ahCitation;
End;
Function TFslHTMLCitation.Link: TFslHTMLCitation;
Begin
Result := TFslHTMLCitation(Inherited Link);
End;
Function TFslHTMLDefinition.Clone: TFslHTMLDefinition;
Begin
Result := TFslHTMLDefinition(Inherited Clone);
End;
Function TFslHTMLDefinition.ElementType: TFslHTMLElementType;
Begin
Result := ahDefinition;
End;
Function TFslHTMLDefinition.Link: TFslHTMLDefinition;
Begin
Result := TFslHTMLDefinition(Inherited Link);
End;
Function TFslHTMLCode.Clone: TFslHTMLCode;
Begin
Result := TFslHTMLCode(Inherited Clone);
End;
Function TFslHTMLCode.ElementType: TFslHTMLElementType;
Begin
Result := ahCode;
End;
Function TFslHTMLCode.Link: TFslHTMLCode;
Begin
Result := TFslHTMLCode(Inherited Link);
End;
Function TFslHTMLSample.Clone: TFslHTMLSample;
Begin
Result := TFslHTMLSample(Inherited Clone);
End;
Function TFslHTMLSample.ElementType: TFslHTMLElementType;
Begin
Result := ahSample;
End;
Function TFslHTMLSample.Link: TFslHTMLSample;
Begin
Result := TFslHTMLSample(Inherited Link);
End;
Function TFslHTMLKeyboardText.Clone: TFslHTMLKeyboardText;
Begin
Result := TFslHTMLKeyboardText(Inherited Clone);
End;
Function TFslHTMLKeyboardText.ElementType: TFslHTMLElementType;
Begin
Result := ahKeyboardText;
End;
Function TFslHTMLKeyboardText.Link: TFslHTMLKeyboardText;
Begin
Result := TFslHTMLKeyboardText(Inherited Link);
End;
Function TFslHTMLVariable.Clone: TFslHTMLVariable;
Begin
Result := TFslHTMLVariable(Inherited Clone);
End;
Function TFslHTMLVariable.ElementType: TFslHTMLElementType;
Begin
Result := ahVariable;
End;
Function TFslHTMLVariable.Link: TFslHTMLVariable;
Begin
Result := TFslHTMLVariable(Inherited Link);
End;
Function TFslHTMLAbbrevation.Clone: TFslHTMLAbbrevation;
Begin
Result := TFslHTMLAbbrevation(Inherited Clone);
End;
Function TFslHTMLAbbrevation.ElementType: TFslHTMLElementType;
Begin
Result := ahAbbrevation;
End;
Function TFslHTMLAbbrevation.Link: TFslHTMLAbbrevation;
Begin
Result := TFslHTMLAbbrevation(Inherited Link);
End;
Function TFslHTMLAcronym.Clone: TFslHTMLAcronym;
Begin
Result := TFslHTMLAcronym(Inherited Clone);
End;
Function TFslHTMLAcronym.ElementType: TFslHTMLElementType;
Begin
Result := ahAcronym;
End;
Function TFslHTMLAcronym.Link: TFslHTMLAcronym;
Begin
Result := TFslHTMLAcronym(Inherited Link);
End;
Function TFslHTMLTeleType.Clone: TFslHTMLTeleType;
Begin
Result := TFslHTMLTeleType(Inherited Clone);
End;
Function TFslHTMLTeleType.ElementType: TFslHTMLElementType;
Begin
Result := ahTeleType;
End;
Function TFslHTMLTeleType.Link: TFslHTMLTeleType;
Begin
Result := TFslHTMLTeleType(Inherited Link);
End;
Function TFslHTMLItalic.Clone: TFslHTMLItalic;
Begin
Result := TFslHTMLItalic(Inherited Clone);
End;
Function TFslHTMLItalic.ElementType: TFslHTMLElementType;
Begin
Result := ahItalic;
End;
Function TFslHTMLItalic.Link: TFslHTMLItalic;
Begin
Result := TFslHTMLItalic(Inherited Link);
End;
Function TFslHTMLBold.Clone: TFslHTMLBold;
Begin
Result := TFslHTMLBold(Inherited Clone);
End;
Function TFslHTMLBold.ElementType: TFslHTMLElementType;
Begin
Result := ahBold;
End;
Function TFslHTMLBold.Link: TFslHTMLBold;
Begin
Result := TFslHTMLBold(Inherited Link);
End;
Function TFslHTMLBig.Clone: TFslHTMLBig;
Begin
Result := TFslHTMLBig(Inherited Clone);
End;
Function TFslHTMLBig.ElementType: TFslHTMLElementType;
Begin
Result := ahBig;
End;
Function TFslHTMLBig.Link: TFslHTMLBig;
Begin
Result := TFslHTMLBig(Inherited Link);
End;
Function TFslHTMLSmall.Clone: TFslHTMLSmall;
Begin
Result := TFslHTMLSmall(Inherited Clone);
End;
Function TFslHTMLSmall.ElementType: TFslHTMLElementType;
Begin
Result := ahSmall;
End;
Function TFslHTMLSmall.Link: TFslHTMLSmall;
Begin
Result := TFslHTMLSmall(Inherited Link);
End;
Function TFslHTMLStrikeOut.Clone: TFslHTMLStrikeOut;
Begin
Result := TFslHTMLStrikeOut(Inherited Clone);
End;
Function TFslHTMLStrikeOut.ElementType: TFslHTMLElementType;
Begin
Result := ahStrikeOut;
End;
Function TFslHTMLStrikeOut.Link: TFslHTMLStrikeOut;
Begin
Result := TFslHTMLStrikeOut(Inherited Link);
End;
Function TFslHTMLUnderline.Clone: TFslHTMLUnderline;
Begin
Result := TFslHTMLUnderline(Inherited Clone);
End;
Function TFslHTMLUnderline.ElementType: TFslHTMLElementType;
Begin
Result := ahUnderline;
End;
Function TFslHTMLUnderline.Link: TFslHTMLUnderline;
Begin
Result := TFslHTMLUnderline(Inherited Link);
End;
Procedure TFslHTMLFont.Assign(oSource: TFslObject);
Begin
Inherited;
FSize := TFslHTMLFont(oSource).FSize;
FFace := TFslHTMLFont(oSource).FFace;
FColour := TFslHTMLFont(oSource).FColour;
End;
Function TFslHTMLFont.Clone: TFslHTMLFont;
Begin
Result := TFslHTMLFont(Inherited Clone);
End;
Function TFslHTMLFont.ElementType: TFslHTMLElementType;
Begin
Result := ahFont;
End;
Function TFslHTMLFont.Link: TFslHTMLFont;
Begin
Result := TFslHTMLFont(Inherited Link);
End;
Function TFslHTMLQuotation.Clone: TFslHTMLQuotation;
Begin
Result := TFslHTMLQuotation(Inherited Clone);
End;
Function TFslHTMLQuotation.ElementType: TFslHTMLElementType;
Begin
Result := ahQuotation;
End;
Function TFslHTMLQuotation.Link: TFslHTMLQuotation;
Begin
Result := TFslHTMLQuotation(Inherited Link);
End;
Function TFslHTMLSuperScript.Clone: TFslHTMLSuperScript;
Begin
Result := TFslHTMLSuperScript(Inherited Clone);
End;
Function TFslHTMLSuperScript.ElementType: TFslHTMLElementType;
Begin
Result := ahSuperScript;
End;
Function TFslHTMLSuperScript.Link: TFslHTMLSuperScript;
Begin
Result := TFslHTMLSuperScript(Inherited Link);
End;
Function TFslHTMLSubScript.Clone: TFslHTMLSubScript;
Begin
Result := TFslHTMLSubScript(Inherited Clone);
End;
Function TFslHTMLSubScript.ElementType: TFslHTMLElementType;
Begin
Result := ahSubScript;
End;
Function TFslHTMLSubScript.Link: TFslHTMLSubScript;
Begin
Result := TFslHTMLSubScript(Inherited Link);
End;
Function TFslHTMLBlockQuote.Clone: TFslHTMLBlockQuote;
Begin
Result := TFslHTMLBlockQuote(Inherited Clone);
End;
Function TFslHTMLBlockQuote.ElementType: TFslHTMLElementType;
Begin
Result := ahBlockQuote;
End;
Function TFslHTMLBlockQuote.Link: TFslHTMLBlockQuote;
Begin
Result := TFslHTMLBlockQuote(Inherited Link);
End;
Procedure TFslHTMLHorizontalRule.Assign(oSource: TFslObject);
Begin
Inherited;
FNoShade := TFslHTMLHorizontalRule(oSource).FNoShade;
FSize := TFslHTMLHorizontalRule(oSource).FSize;
FWidth := TFslHTMLHorizontalRule(oSource).FWidth;
FAlign := TFslHTMLHorizontalRule(oSource).FAlign;
End;
Function TFslHTMLHorizontalRule.Clone: TFslHTMLHorizontalRule;
Begin
Result := TFslHTMLHorizontalRule(Inherited Clone);
End;
Function TFslHTMLHorizontalRule.ElementType: TFslHTMLElementType;
Begin
Result := ahHorizontalRule;
End;
Function TFslHTMLHorizontalRule.Link: TFslHTMLHorizontalRule;
Begin
Result := TFslHTMLHorizontalRule(Inherited Link);
End;
Procedure TFslHTMLContainer.Assign(oSource: TFslObject);
Begin
Inherited;
FAlign := TFslHTMLContainer(oSource).FAlign;
End;
Function TFslHTMLContainer.Clone: TFslHTMLContainer;
Begin
Result := TFslHTMLContainer(Inherited Clone);
End;
Function TFslHTMLContainer.ElementType: TFslHTMLElementType;
Begin
Result := ahDiv;
End;
Function TFslHTMLContainer.Link: TFslHTMLContainer;
Begin
Result := TFslHTMLContainer(Inherited Link);
End;
Function TFslHTMLParagraph.Clone: TFslHTMLParagraph;
Begin
Result := TFslHTMLParagraph(Inherited Clone);
End;
Function TFslHTMLParagraph.ElementType: TFslHTMLElementType;
Begin
Result := ahParagraph;
End;
Function TFslHTMLParagraph.Link: TFslHTMLParagraph;
Begin
Result := TFslHTMLParagraph(Inherited Link);
End;
Function TFslHTMLPreformatted.Clone: TFslHTMLPreformatted;
Begin
Result := TFslHTMLPreformatted(Inherited Clone);
End;
Function TFslHTMLPreformatted.ElementType: TFslHTMLElementType;
Begin
Result := ahPreformatted;
End;
Function TFslHTMLPreformatted.Link: TFslHTMLPreformatted;
Begin
Result := TFslHTMLPreformatted(Inherited Link);
End;
Procedure TFslHTMLHeading.Assign(oSource: TFslObject);
Begin
Inherited;
FLevel := TFslHTMLHeading(oSource).FLevel;
End;
Function TFslHTMLHeading.Clone: TFslHTMLHeading;
Begin
Result := TFslHTMLHeading(Inherited Clone);
End;
Function TFslHTMLHeading.ElementType: TFslHTMLElementType;
Begin
Result := ahHeading;
End;
Function TFslHTMLHeading.Link: TFslHTMLHeading;
Begin
Result := TFslHTMLHeading(Inherited Link);
End;
Procedure TFslHTMLListItem.Assign(oSource: TFslObject);
Begin
Inherited;
FValue := TFslHTMLListItem(oSource).FValue;
FHasValue := TFslHTMLListItem(oSource).FHasValue;
End;
Function TFslHTMLListItem.Clone: TFslHTMLListItem;
Begin
Result := TFslHTMLListItem(Inherited Clone);
End;
Function TFslHTMLListItem.ElementType: TFslHTMLElementType;
Begin
Result := ahListItem;
End;
Function TFslHTMLListItem.GetHasValue: Boolean;
Begin
Result := FHasValue;
End;
Function TFslHTMLListItem.GetValue: Integer;
Begin
Assert(CheckCondition(FHasValue, 'GetValue', 'Must have a value'));
Result := FValue;
End;
Function TFslHTMLListItem.Link: TFslHTMLListItem;
Begin
Result := TFslHTMLListItem(Inherited Link);
End;
Function TFslHTMLListItems.GetListItem(iIndex: Integer): TFslHTMLListItem;
Begin
Result := TFslHTMLListItem(ObjectByIndex[iIndex]);
End;
Function TFslHTMLListItems.ItemClass: TFslObjectClass;
Begin
Result := TFslHTMLListItem;
End;
Procedure TFslHTMLListElement.Assign(oSource: TFslObject);
Begin
Inherited;
FCompact := TFslHTMLListElement(oSource).FCompact;
FList.Assign(TFslHTMLListElement(oSource).FList);
End;
Function TFslHTMLListElement.Clone: TFslHTMLListElement;
Begin
Result := TFslHTMLListElement(Inherited Clone);
End;
Constructor TFslHTMLListElement.Create;
Begin
Inherited;
FList := TFslHTMLListItems.Create;
End;
Destructor TFslHTMLListElement.Destroy;
Begin
FList.Free;
Inherited;
End;
Function TFslHTMLListElement.ElementType: TFslHTMLElementType;
Begin
Result := ahListElement;
End;
Function TFslHTMLListElement.Link: TFslHTMLListElement;
Begin
Result := TFslHTMLListElement(Inherited Link);
End;
Procedure TFslHTMLListElement.SetList(Const oValue: TFslHTMLListItems);
Begin
FList.Free;
FList := oValue;
End;
Procedure TFslHTMLOrderedList.Assign(oSource: TFslObject);
Begin
Inherited;
FStart := TFslHTMLOrderedList(oSource).FStart;
FListType := TFslHTMLOrderedList(oSource).FListType;
End;
Function TFslHTMLOrderedList.Clone: TFslHTMLOrderedList;
Begin
Result := TFslHTMLOrderedList(Inherited Clone);
End;
Function TFslHTMLOrderedList.ElementType: TFslHTMLElementType;
Begin
Result := ahOrderedList;
End;
Function TFslHTMLOrderedList.Link: TFslHTMLOrderedList;
Begin
Result := TFslHTMLOrderedList(Inherited Link);
End;
Procedure TFslHTMLUnorderedList.Assign(oSource: TFslObject);
Begin
Inherited;
FListType := TFslHTMLUnorderedList(oSource).FListType;
End;
Function TFslHTMLUnorderedList.Clone: TFslHTMLUnorderedList;
Begin
Result := TFslHTMLUnorderedList(Inherited Clone);
End;
Function TFslHTMLUnorderedList.ElementType: TFslHTMLElementType;
Begin
Result := ahUnOrderedList;
End;
Function TFslHTMLUnorderedList.Link: TFslHTMLUnorderedList;
Begin
Result := TFslHTMLUnorderedList(Inherited Link);
End;
Procedure TFslHTMLDefinitionListItem.Assign(oSource: TFslObject);
Begin
Inherited;
Term := TFslHTMLDefinitionListItem(oSource).FTerm.Link;
End;
Function TFslHTMLDefinitionListItem.Clone: TFslHTMLDefinitionListItem;
Begin
Result := TFslHTMLDefinitionListItem(Inherited Clone);
End;
Constructor TFslHTMLDefinitionListItem.Create;
Begin
Inherited;
FTerm := TFslHTMLItem.Create;
End;
Destructor TFslHTMLDefinitionListItem.Destroy;
Begin
FTerm.Free;
Inherited;
End;
Function TFslHTMLDefinitionListItem.ElementType: TFslHTMLElementType;
Begin
Result := ahDefinitionListItem;
End;
Function TFslHTMLDefinitionListItem.Link: TFslHTMLDefinitionListItem;
Begin
Result := TFslHTMLDefinitionListItem(Inherited Link);
End;
Procedure TFslHTMLDefinitionListItem.SetTerm(Const oValue: TFslHTMLItem);
Begin
FTerm.Free;
FTerm := oValue;
End;
Function TFslHTMLDefinitionListItems.GetListItem(iIndex: Integer): TFslHTMLDefinitionListItem;
Begin
Result := TFslHTMLDefinitionListItem(ObjectByIndex[iIndex]);
End;
Function TFslHTMLDefinitionListItems.ItemClass: TFslObjectClass;
Begin
Result := TFslHTMLDefinitionListItem;
End;
Procedure TFslHTMLDefinitionList.Assign(oSource: TFslObject);
Begin
Inherited;
FListItems.Assign(TFslHTMLDefinitionList(oSource).FListItems);
End;
Function TFslHTMLDefinitionList.Clone: TFslHTMLDefinitionList;
Begin
Result := TFslHTMLDefinitionList(Inherited Clone);
End;
Constructor TFslHTMLDefinitionList.Create;
Begin
Inherited;
FListItems := TFslHTMLDefinitionListItems.Create;
End;
Destructor TFslHTMLDefinitionList.Destroy;
Begin
FListItems.Free;
Inherited;
End;
Function TFslHTMLDefinitionList.ElementType: TFslHTMLElementType;
Begin
Result := ahDefinitionList;
End;
Function TFslHTMLDefinitionList.Link: TFslHTMLDefinitionList;
Begin
Result := TFslHTMLDefinitionList(Inherited Link);
End;
Procedure TFslHTMLDefinitionList.SetListItems(Const oValue: TFslHTMLDefinitionListItems);
Begin
FListItems.Free;
FListItems := oValue;
End;
Procedure TFslHTMLTableCell.Assign(oSource: TFslObject);
Begin
Inherited;
FNoWrap := TFslHTMLTableCell(oSource).FNoWrap;
FRowspan := TFslHTMLTableCell(oSource).FRowspan;
FColspan := TFslHTMLTableCell(oSource).FColspan;
FWidth := TFslHTMLTableCell(oSource).FWidth;
FHeight := TFslHTMLTableCell(oSource).FHeight;
FVertAlign := TFslHTMLTableCell(oSource).FVertAlign;
FHorizAlign := TFslHTMLTableCell(oSource).FHorizAlign;
FBgColour := TFslHTMLTableCell(oSource).FBgColour;
FIsHeader := TFslHTMLTableCell(oSource).FIsHeader;
End;
Function TFslHTMLTableCell.Clone: TFslHTMLTableCell;
Begin
Result := TFslHTMLTableCell(Inherited Clone);
End;
Function TFslHTMLTableCell.ElementType: TFslHTMLElementType;
Begin
Result := ahTableCell;
End;
Function TFslHTMLTableCell.Link: TFslHTMLTableCell;
Begin
Result := TFslHTMLTableCell(Inherited Link);
End;
Function TFslHTMLTableCells.GetCell(iIndex: Integer): TFslHTMLTableCell;
Begin
Result := TFslHTMLTableCell(ObjectByIndex[iIndex]);
End;
Function TFslHTMLTableCells.ItemClass: TFslObjectClass;
Begin
Result := TFslHTMLTableCell;
End;
Procedure TFslHTMLTableRow.Assign(oSource: TFslObject);
Begin
Inherited;
FVertAlign := TFslHTMLTableRow(oSource).FVertAlign;
FHorizAlign := TFslHTMLTableRow(oSource).FHorizAlign;
FBgColour := TFslHTMLTableRow(oSource).FBgColour;
FCells.Assign(TFslHTMLTableRow(oSource).FCells);
End;
Function TFslHTMLTableRow.Clone: TFslHTMLTableRow;
Begin
Result := TFslHTMLTableRow(Inherited Clone);
End;
Constructor TFslHTMLTableRow.Create;
Begin
Inherited;
FCells := TFslHTMLTableCells.Create;
End;
Destructor TFslHTMLTableRow.Destroy;
Begin
FCells.Free;
Inherited;
End;
Function TFslHTMLTableRow.ElementType: TFslHTMLElementType;
Begin
Result := ahTableRow;
End;
Function TFslHTMLTableRow.Link: TFslHTMLTableRow;
Begin
Result := TFslHTMLTableRow(Inherited Link);
End;
Procedure TFslHTMLTableRow.SetCells(Const oValue: TFslHTMLTableCells);
Begin
FCells.Free;
FCells := oValue;
End;
Function TFslHTMLTableRows.GetRow(iIndex: Integer): TFslHTMLTableRow;
Begin
Result := TFslHTMLTableRow(ObjectByIndex[iIndex]);
End;
Function TFslHTMLTableRows.ItemClass: TFslObjectClass;
Begin
Result := TFslHTMLTableRow;
End;
Procedure TFslHTMLTableSection.Assign(oSource: TFslObject);
Begin
Inherited;
FRows.Assign(TFslHTMLTableSection(oSource).FRows);
FSectionType := TFslHTMLTableSection(oSource).FSectionType;
End;
Function TFslHTMLTableSection.Clone: TFslHTMLTableSection;
Begin
Result := TFslHTMLTableSection(Inherited Clone);
End;
Constructor TFslHTMLTableSection.Create;
Begin
Inherited;
FRows := TFslHTMLTableRows.Create;
End;
Destructor TFslHTMLTableSection.Destroy;
Begin
FRows.Free;
Inherited;
End;
Function TFslHTMLTableSection.ElementType: TFslHTMLElementType;
Begin
Result := ahTableSection;
End;
Function TFslHTMLTableSection.Link: TFslHTMLTableSection;
Begin
Result := TFslHTMLTableSection(Inherited Link);
End;
Procedure TFslHTMLTableSection.SetRows(Const oValue: TFslHTMLTableRows);
Begin
FRows.Free;
FRows := oValue;
End;
Function TFslHTMLTableSections.GetSection(iIndex: Integer): TFslHTMLTableSection;
Begin
Result := TFslHTMLTableSection(ObjectByIndex[iIndex]);
End;
Function TFslHTMLTableSections.ItemClass: TFslObjectClass;
Begin
Result := TFslHTMLTableSection;
End;
Procedure TFslHTMLTableCaption.Assign(oSource: TFslObject);
Begin
Inherited;
FAlign := TFslHTMLTableCaption(oSource).FAlign;
End;
Function TFslHTMLTableCaption.Clone: TFslHTMLTableCaption;
Begin
Result := TFslHTMLTableCaption(Inherited Clone);
End;
Function TFslHTMLTableCaption.ElementType: TFslHTMLElementType;
Begin
Result := ahTableCaption;
End;
Function TFslHTMLTableCaption.Link: TFslHTMLTableCaption;
Begin
Result := TFslHTMLTableCaption(Inherited Link);
End;
Procedure TFslHTMLTable.Assign(oSource: TFslObject);
Begin
Inherited;
FSummary := TFslHTMLTable(oSource).FSummary;
FWidth := TFslHTMLTable(oSource).FWidth;
FCellpadding := TFslHTMLTable(oSource).FCellpadding;
FCellspacing := TFslHTMLTable(oSource).FCellspacing;
FBorder := TFslHTMLTable(oSource).FBorder;
FAlign := TFslHTMLTable(oSource).FAlign;
FBgColour := TFslHTMLTable(oSource).FBgColour;
Caption := TFslHTMLTable(oSource).FCaption.Link;
FRows.Assign(TFslHTMLTable(oSource).FRows);
FSections.Assign(TFslHTMLTable(oSource).FSections);
End;
Function TFslHTMLTable.Clone: TFslHTMLTable;
Begin
Result := TFslHTMLTable(Inherited Clone);
End;
Constructor TFslHTMLTable.Create;
Begin
Inherited;
FCaption := TFslHTMLTableCaption.Create;
FRows := TFslHTMLTableRows.Create;
FSections := TFslHTMLTableSections.Create;
End;
Destructor TFslHTMLTable.Destroy;
Begin
FCaption.Free;
FRows.Free;
FSections.Free;
Inherited;
End;
Function TFslHTMLTable.ElementType: TFslHTMLElementType;
Begin
Result := ahTable;
End;
Function TFslHTMLTable.Link: TFslHTMLTable;
Begin
Result := TFslHTMLTable(Inherited Link);
End;
Procedure TFslHTMLTable.SetCaption(Const oValue: TFslHTMLTableCaption);
Begin
FCaption.Free;
FCaption := oValue;
End;
Procedure TFslHTMLTable.SetRows(Const oValue: TFslHTMLTableRows);
Begin
FRows.Free;
FRows := oValue;
End;
Procedure TFslHTMLTable.SetSections(Const oValue: TFslHTMLTableSections);
Begin
FSections.Free;
FSections := oValue;
End;
Procedure TFslHTMLFormControl.Assign(oSource: TFslObject);
Begin
Inherited;
FDisabled := TFslHTMLFormControl(oSource).FDisabled;
FTabIndex := TFslHTMLFormControl(oSource).FTabIndex;
FName := TFslHTMLFormControl(oSource).FName;
FValue := TFslHTMLFormControl(oSource).FValue;
End;
Function TFslHTMLFormControl.Clone: TFslHTMLFormControl;
Begin
Result := TFslHTMLFormControl(Inherited Clone);
End;
Function TFslHTMLFormControl.ElementType: TFslHTMLElementType;
Begin
Result := ahFormControl;
End;
Function TFslHTMLFormControl.Link: TFslHTMLFormControl;
Begin
Result := TFslHTMLFormControl(Inherited Link);
End;
Procedure TFslHTMLInput.Assign(oSource: TFslObject);
Begin
Inherited;
FReadOnly := TFslHTMLInput(oSource).FReadOnly;
FChecked := TFslHTMLInput(oSource).FChecked;
FSize := TFslHTMLInput(oSource).FSize;
FAccept := TFslHTMLInput(oSource).FAccept;
FSource := TFslHTMLInput(oSource).FSource;
FMaxLength := TFslHTMLInput(oSource).FMaxLength;
FAlternative := TFslHTMLInput(oSource).FAlternative;
FAlign := TFslHTMLInput(oSource).FAlign;
FInputType := TFslHTMLInput(oSource).FInputType;
End;
Function TFslHTMLInput.Clone: TFslHTMLInput;
Begin
Result := TFslHTMLInput(Inherited Clone);
End;
Function TFslHTMLInput.ElementType: TFslHTMLElementType;
Begin
Result := ahInput;
End;
Function TFslHTMLInput.Link: TFslHTMLInput;
Begin
Result := TFslHTMLInput(Inherited Link);
End;
Procedure TFslHTMLButton.Assign(oSource: TFslObject);
Begin
Inherited;
FButtonType := TFslHTMLButton(oSource).FButtonType;
End;
Function TFslHTMLButton.Clone: TFslHTMLButton;
Begin
Result := TFslHTMLButton(Inherited Clone);
End;
Function TFslHTMLButton.ElementType: TFslHTMLElementType;
Begin
Result := ahButton;
End;
Function TFslHTMLButton.Link: TFslHTMLButton;
Begin
Result := TFslHTMLButton(Inherited Link);
End;
Procedure TFslHTMLOptionItem.Assign(oSource: TFslObject);
Begin
Inherited;
FDisabled := TFslHTMLOptionItem(oSource).FDisabled;
FCaption := TFslHTMLOptionItem(oSource).FCaption;
End;
Function TFslHTMLOptionItem.Clone: TFslHTMLOptionItem;
Begin
Result := TFslHTMLOptionItem(Inherited Clone);
End;
Function TFslHTMLOptionItem.ElementType: TFslHTMLElementType;
Begin
Result := ahOptionItem;
End;
Function TFslHTMLOptionItem.Link: TFslHTMLOptionItem;
Begin
Result := TFslHTMLOptionItem(Inherited Link);
End;
Function TFslHTMLOptionItems.GetOption(iIndex: Integer): TFslHTMLOptionItem;
Begin
Result := TFslHTMLOptionItem(ObjectByIndex[iIndex]);
End;
Function TFslHTMLOptionItems.ItemClass: TFslObjectClass;
Begin
Result := TFslHTMLOptionItem;
End;
Procedure TFslHTMLOptGroup.Assign(oSource: TFslObject);
Begin
Inherited;
FOptions.Assign(TFslHTMLOptGroup(oSource).FOptions);
End;
Function TFslHTMLOptGroup.Clone: TFslHTMLOptGroup;
Begin
Result := TFslHTMLOptGroup(Inherited Clone);
End;
Constructor TFslHTMLOptGroup.Create;
Begin
Inherited;
FOptions := TFslHTMLOptionItems.Create;
End;
Destructor TFslHTMLOptGroup.Destroy;
Begin
FOptions.Free;
Inherited;
End;
Function TFslHTMLOptGroup.ElementType: TFslHTMLElementType;
Begin
Result := ahOptGroup;
End;
Function TFslHTMLOptGroup.Link: TFslHTMLOptGroup;
Begin
Result := TFslHTMLOptGroup(Inherited Link);
End;
Procedure TFslHTMLOptGroup.SetOptions(Const oValue: TFslHTMLOptionItems);
Begin
FOptions.Free;
FOptions := oValue;
End;
Procedure TFslHTMLOption.Assign(oSource: TFslObject);
Begin
Inherited;
FSelected := TFslHTMLOption(oSource).FSelected;
FValue := TFslHTMLOption(oSource).FValue;
End;
Function TFslHTMLOption.Clone: TFslHTMLOption;
Begin
Result := TFslHTMLOption(Inherited Clone);
End;
Function TFslHTMLOption.ElementType: TFslHTMLElementType;
Begin
Result := ahOption;
End;
Function TFslHTMLOption.Link: TFslHTMLOption;
Begin
Result := TFslHTMLOption(Inherited Link);
End;
Procedure TFslHTMLSelect.Assign(oSource: TFslObject);
Begin
Inherited;
FMultiple := TFslHTMLSelect(oSource).FMultiple;
FSize := TFslHTMLSelect(oSource).FSize;
FAllOptions.Assign(TFslHTMLSelect(oSource).FAllOptions);
FOptions.Assign(TFslHTMLSelect(oSource).FOptions);
End;
Function TFslHTMLSelect.Clone: TFslHTMLSelect;
Begin
Result := TFslHTMLSelect(Inherited Clone);
End;
Constructor TFslHTMLSelect.Create;
Begin
Inherited;
FAllOptions := TFslHTMLOptionItems.Create;
FOptions := TFslHTMLOptionItems.Create;
End;
Destructor TFslHTMLSelect.Destroy;
Begin
FAllOptions.Free;
FOptions.Free;
Inherited;
End;
Function TFslHTMLSelect.ElementType: TFslHTMLElementType;
Begin
Result := ahSelect;
End;
Function TFslHTMLSelect.Link: TFslHTMLSelect;
Begin
Result := TFslHTMLSelect(Inherited Link);
End;
Procedure TFslHTMLSelect.SetAllOptions(Const oValue: TFslHTMLOptionItems);
Begin
FAllOptions.Free;
FAllOptions := oValue;
End;
Procedure TFslHTMLSelect.SetOptions(Const oValue: TFslHTMLOptionItems);
Begin
FOptions.Free;
FOptions := oValue;
End;
Procedure TFslHTMLTextArea.Assign(oSource: TFslObject);
Begin
Inherited;
FReadOnly := TFslHTMLTextArea(oSource).FReadOnly;
FRows := TFslHTMLTextArea(oSource).FRows;
FCols := TFslHTMLTextArea(oSource).FCols;
End;
Function TFslHTMLTextArea.Clone: TFslHTMLTextArea;
Begin
Result := TFslHTMLTextArea(Inherited Clone);
End;
Function TFslHTMLTextArea.ElementType: TFslHTMLElementType;
Begin
Result := ahTextArea;
End;
Function TFslHTMLTextArea.Link: TFslHTMLTextArea;
Begin
Result := TFslHTMLTextArea(Inherited Link);
End;
Procedure TFslHTMLForm.Assign(oSource: TFslObject);
Begin
Inherited;
FAction := TFslHTMLForm(oSource).FAction;
FEncType := TFslHTMLForm(oSource).FEncType;
FName := TFslHTMLForm(oSource).FName;
FMethod := TFslHTMLForm(oSource).FMethod;
End;
Function TFslHTMLForm.Clone: TFslHTMLForm;
Begin
Result := TFslHTMLForm(Inherited Clone);
End;
Function TFslHTMLForm.ElementType: TFslHTMLElementType;
Begin
Result := ahForm;
End;
Function TFslHTMLForm.Link: TFslHTMLForm;
Begin
Result := TFslHTMLForm(Inherited Link);
End;
Procedure TFslHTMLBody.Assign(oSource: TFslObject);
Begin
Inherited;
FLinkColor := TFslHTMLBody(oSource).FLinkColor;
FVlinkcolor := TFslHTMLBody(oSource).FVlinkcolor;
FAlinkColor := TFslHTMLBody(oSource).FAlinkColor;
End;
Function TFslHTMLBody.Clone: TFslHTMLBody;
Begin
Result := TFslHTMLBody(Inherited Clone);
End;
Function TFslHTMLBody.ElementType: TFslHTMLElementType;
Begin
Result := ahBody;
End;
Function TFslHTMLBody.Link: TFslHTMLBody;
Begin
Result := TFslHTMLBody(Inherited Link);
End;
Procedure TFslHTMLMetaEntry.Assign(oSource: TFslObject);
Begin
Inherited;
FHttpEquiv := TFslHTMLMetaEntry(oSource).FHttpEquiv;
FContent := TFslHTMLMetaEntry(oSource).FContent;
FName := TFslHTMLMetaEntry(oSource).FName;
FScheme := TFslHTMLMetaEntry(oSource).FScheme;
End;
Function TFslHTMLMetaEntry.Clone: TFslHTMLMetaEntry;
Begin
Result := TFslHTMLMetaEntry(Inherited Clone);
End;
Function TFslHTMLMetaEntry.Link: TFslHTMLMetaEntry;
Begin
Result := TFslHTMLMetaEntry(Inherited Link);
End;
Function TFslHTMLMetaEntries.GetMeta(iIndex: Integer): TFslHTMLMetaEntry;
Begin
Result := TFslHTMLMetaEntry(ObjectByIndex[iIndex]);
End;
Function TFslHTMLMetaEntries.ItemClass: TFslObjectClass;
Begin
Result := TFslHTMLMetaEntry;
End;
Procedure TFslHTMLHead.Assign(oSource: TFslObject);
Begin
Inherited;
FMeta.Assign(TFslHTMLHead(oSource).FMeta);
FStyles.Assign(TFslHTMLHead(oSource).FStyles);
FTitle := TFslHTMLHead(oSource).FTitle;
End;
Procedure TFslHTMLHead.Clear;
Begin
Inherited;
FMeta.Clear;
FStyles.Clear;
End;
Procedure TFslHtmlHead.SetStyles(Const oValue: TFslCSSStyles);
Begin
FStyles.Free;
FStyles := oValue;
End;
Function TFslHTMLHead.Clone: TFslHTMLHead;
Begin
Result := TFslHTMLHead(Inherited Clone);
End;
Constructor TFslHTMLHead.Create;
Begin
Inherited;
FMeta := TFslHTMLMetaEntries.Create;
FStyles := TFslCSSStyles.Create;
End;
Destructor TFslHTMLHead.Destroy;
Begin
FMeta.Free;
FStyles.Free;
Inherited;
End;
Function TFslHTMLHead.Link: TFslHTMLHead;
Begin
Result := TFslHTMLHead(Inherited Link);
End;
Procedure TFslHTMLHead.SetMeta(Const oValue: TFslHTMLMetaEntries);
Begin
FMeta.Free;
FMeta := oValue;
End;
Procedure TFslHtmlDocument.Assign(oSource: TFslObject);
Begin
Inherited;
FDTD := TFslHtmlDocument(oSource).FDTD;
FVersion := TFslHtmlDocument(oSource).FVersion;
FStyles.Assign(TFslHtmlDocument(oSource).FStyles);
Body := TFslHtmlDocument(oSource).FBody.Link;
Head := TFslHtmlDocument(oSource).FHead.Link;
End;
Procedure TFslHtmlDocument.Clear;
Begin
Inherited;
FDTD := 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd';
FVersion := '-//W3C//DTD XHTML 1.0 Strict//EN';
FBody.Clear;
FHead.Clear;
FStyles.Clear;
End;
Function TFslHtmlDocument.Clone: TFslHtmlDocument;
Begin
Result := TFslHtmlDocument(Inherited Clone);
End;
Constructor TFslHtmlDocument.Create;
Begin
Inherited;
FStyles := TFslCSSStyles.Create;
FBody := TFslHTMLBody.Create;
FHead := TFslHTMLHead.Create;
End;
Destructor TFslHtmlDocument.Destroy;
Begin
FStyles.Free;
FBody.Free;
FHead.Free;
Inherited;
End;
Function TFslHtmlDocument.Link: TFslHtmlDocument;
Begin
Result := TFslHtmlDocument(Inherited Link);
End;
Procedure TFslHtmlDocument.SetBody(Const oValue: TFslHTMLBody);
Begin
FBody.Free;
FBody := oValue;
End;
Procedure TFslHtmlDocument.SetHead(Const oValue: TFslHTMLHead);
Begin
FHead.Free;
FHead := oValue;
End;
Procedure TFslHtmlDocument.SetStyles(Const oValue: TFslCSSStyles);
Begin
FStyles.Free;
FStyles := oValue;
End;
Procedure TFslHTMLListItem.SetHasValue(Const Value: Boolean);
Begin
FHasValue := Value;
End;
Procedure TFslHTMLListItem.SetValue(Const Value: Integer);
Begin
FHasValue := True;
FValue := Value;
End;
Var
gTable : Array[Char] Of TFslHTMLToken;
Function ToHTMLToken(cChar : Char) : TFslHTMLToken;
Begin
Result := gTable[cChar];
if result = ahtNull then
result := ahtIdentifier;
End;
Function TFslHTMLLexer.ConsumeToken: TFslHTMLToken;
Begin
If FNextToken <> ahtNull Then
Begin
FCurrentToken := FNextToken;
FNextToken := ahtNull;
End
Else
Begin
Case NextCharacter Of
#0..' ' :
Begin
FCurrentToken := ConsumeWhitespace;
End; { Whitespace }
'0'..'9' :
Begin
FCurrentToken := ConsumeNumber;
End;
'a'..'z', 'A'..'Z', '_', '.' :
Begin
FCurrentToken := ConsumeIdentifier;
End; { Identifier }
'&' :
Begin
FCurrentToken := ConsumeSymbol;
End;
'?' :
Begin
FCurrentValue := ConsumeCharacter('?');
If More And (NextCharacter = '>') Then
Begin
FCurrentValue := FCurrentValue + ConsumeCharacter('>');
FCurrentToken := ahtCloseTagQuery;
End
Else
Begin
FCurrentToken := ahtQuery;
End;
End;
'<' :
Begin
FCurrentValue := ConsumeCharacter('<');
If More And (NextCharacter = '!') Then
Begin
FCurrentValue := FCurrentValue + ConsumeCharacter('!');
If NextCharacter <> '-' Then
FCurrentToken := ahtOpenTagExclamation
Else
Begin
FCurrentValue := FCurrentValue + ConsumeCharacter('-');
If More And (NextCharacter = '-') Then
Begin
FCurrentValue := ConsumeUntilString('-->');
FCurrentToken := ahtComment;
If More Then
ConsumeString('-->');
End
Else
Begin
FCurrentToken := ahtOpenTagExclamation;
ProduceCharacter('-');
End;
End;
End
Else If More And (NextCharacter = '/') Then
Begin
FCurrentValue := FCurrentValue + ConsumeCharacter('/');
FCurrentToken := ahtOpenTagForwardSlash;
End
Else If More And (NextCharacter = '?') Then
Begin
FCurrentValue := FCurrentValue + ConsumeCharacter('?');
FCurrentToken := ahtOpenTagQuery;
End
Else
Begin
FCurrentToken := ahtOpenTag;
End;
End;
'>' :
Begin
FCurrentValue := ConsumeCharacter('>');
FCurrentToken := ahtCloseTag;
End;
'/' :
Begin
FCurrentValue := ConsumeCharacter('/');
If NextCharacter = '>' Then
Begin
FCurrentValue := FCurrentValue + ConsumeCharacter('>');
FCurrentToken := ahtCloseTagForwardSlash;
End
Else
Begin
FCurrentToken := ahtForwardSlash;
End;
End;
Else
FCurrentValue := ConsumeCharacter;
FCurrentToken := ToHTMLToken(FCurrentValue[1]);
End;
{$IFOPT C+}
// ConsoleOpen;
// ConsoleWriteLine(FCurrentValue);
{$ENDIF}
End;
Result := FCurrentToken;
End;
Procedure TFslHTMLLexer.ConsumeToken(aToken: TFslHTMLToken);
Begin
If NextToken <> aToken Then
RaiseError('ConsumeToken', StringFormat('Expected token %s but found token %s.', [HTMLTOKEN_STRING[aToken], HTMLTOKEN_STRING[NextToken]]));
ConsumeToken;
End;
Function TFslHTMLLexer.NextToken: TFslHTMLToken;
Begin
If FNextToken = ahtNull Then
FNextToken := ConsumeToken;
Result := FNextToken;
End;
Function TFslHTMLLexer.ConsumeIdentifier : TFslHTMLToken;
Begin
FCurrentValue := ConsumeWhileCharacterSet(setAlphabet + ['_', '.']);
FCurrentValue := FCurrentValue + ConsumeWhileCharacterSet(setAlphanumeric + ['_', '-', '.', '/', '\']);
Result := ahtIdentifier;
End;
Function TFslHTMLLexer.ConsumeWhitespace: TFslHTMLToken;
Begin
FCurrentValue := '';
While More And (NextCharacter <= ' ') Do
FCurrentValue := FCurrentValue + ConsumeCharacter;
Result := ahtWhitespace;
End;
Function TFslHTMLLexer.ConsumeNumber: TFslHTMLToken;
Begin
FCurrentValue := '';
While More And CharInSet(NextCharacter, setNumbers) Do
FCurrentValue := FCurrentValue + ConsumeCharacter;
If NextCharacter = '.' Then
Begin
ConsumeCharacter('.');
FCurrentValue := FCurrentValue + '.';
While More And CharInSet(NextCharacter, setNumbers) Do
FCurrentValue := FCurrentValue + ConsumeCharacter;
End;
If More And (NextCharacter = '%') Then
FCurrentValue := FCurrentValue + ConsumeCharacter('%');
Result := ahtNumber;
End;
Function TFslHTMLLexer.ConsumeSymbol: TFslHTMLToken;
Begin
FCurrentValue := ConsumeCharacter('&');
If More Then
Begin
FCurrentValue := FCurrentValue + ConsumeUntilString(';');
If More Then
Begin
FCurrentValue := FCurrentValue + ConsumeCharacter(';');
If Lowercase(FCurrentValue) = ' ' Then
Begin
FCurrentValue := ' ';
Result := ahtIdentifier;
End
Else
Begin
FCurrentValue := DecodeXML(FCurrentValue);
If Length(FCurrentValue) = 1 Then
Result := ToHTMLToken(FCurrentValue[1])
Else
Result := ahtIdentifier;
End;
End
Else
Begin
Result := ahtIdentifier;
End;
End
Else
Begin
Result := ahtAmpersand;
End;
End;
Constructor TFslHTMLFormatter.Create;
Begin
Inherited;
FAdapter := TFslHTMLAdapter.Create;
End;
Destructor TFslHTMLFormatter.Destroy;
Begin
FAdapter.Free;
Inherited;
End;
Function TFslHTMLFormatter.Clone: TFslHTMLFormatter;
Begin
Result := TFslHTMLFormatter(Inherited Clone);
End;
Function TFslHTMLFormatter.Link: TFslHTMLFormatter;
Begin
Result := TFslHTMLFormatter(Inherited Link);
End;
Procedure TFslHTMLFormatter.SetStream(oStream: TFslStream);
Begin
Inherited;
FAdapter.Stream := oStream.Link;
End;
Procedure TFslHTMLFormatter.ProduceDocumentType(Const sVersion, sDTD : String);
Begin
ProduceLine(StringFormat('<!DOCTYPE html PUBLIC "%s" "%s">', [sVersion, sDTD]));
End;
Procedure TFslHTMLFormatter.ProduceDocumentOpen;
Begin
ProduceOpen('html');
End;
Procedure TFslHTMLFormatter.ProduceDocumentClose;
Begin
ProduceClose('html');
End;
Procedure TFslHTMLFormatter.ProduceHeadOpen;
Begin
ProduceOpen('head');
End;
Procedure TFslHTMLFormatter.ProduceHeadClose;
Begin
ProduceClose('head');
End;
Procedure TFslHTMLFormatter.ProduceStyleOpen;
Begin
ProduceOpen('style');
End;
Procedure TFslHTMLFormatter.ProduceStyleClose;
Begin
ProduceClose('style');
End;
Procedure TFslHTMLFormatter.ProduceStyleFragment(Const sName : String; oProperties : TFslStringMatch);
Var
aValue : TFslStringMatchItem;
iLoop : Integer;
Begin
ProduceStyleFragmentOpen(sName);
For iLoop := 0 To oProperties.Count - 1 Do
Begin
aValue := oProperties.MatchByIndex[iLoop];
ProduceStyleFragmentProperty(aValue.Key, aValue.Value);
End;
End;
Procedure TFslHTMLFormatter.ProduceStyleFragmentOpen(Const sName : String);
Begin
ProduceText(sName + ' { ');
LevelDown;
End;
Procedure TFslHTMLFormatter.ProduceStyleFragmentClose;
Begin
LevelUp;
ProduceText('}');
End;
Procedure TFslHTMLFormatter.ProduceStyleFragmentProperty(Const sName, sValue : String);
Begin
ProduceText(sName + ': ' + sValue + '; ');
End;
Procedure TFslHTMLFormatter.ProduceBodyOpen;
Begin
ProduceOpen('body');
End;
Procedure TFslHTMLFormatter.ProduceBodyClose;
Begin
ProduceClose('body');
End;
Procedure TFslHTMLFormatter.ProduceInlineTag(Const sTag : String);
Begin
ProduceInLine('<' + sTag + UseAttributes + ' />');
End;
Procedure TFslHTMLFormatter.ProduceOpen(Const sTag : String; bInline : Boolean);
Begin
If bInline Then
ProduceInline('<' + sTag + UseAttributes + '>')
Else
Begin
ProduceLine('<' + sTag + UseAttributes + '>');
LevelDown;
End;
End;
Procedure TFslHTMLFormatter.ProduceClose(Const sTag: String; bInline : Boolean);
Begin
If bInline Then
ProduceInline('</' + sTag + '>')
Else
Begin
LevelUp;
ProduceLine('</' + sTag + '>');
End;
End;
Procedure TFslHTMLFormatter.ProduceEscaped(Const sData: String);
Begin
FAdapter.Write(Pointer(sData)^, Length(sData));
End;
Procedure TFslHTMLFormatter.ProducePreformatted(Const sData: String);
Begin
ProduceLine('<pre' + UseAttributes + '>' + EncodeXML(sData) + '</pre>');
End;
Procedure TFslHTMLFormatter.ProduceAnchor(Const sCaption, sReference, sBookmark, sTarget : String);
Var
sLink : String;
Begin
sLink := sReference;
If sBookmark <> '' Then
sLink := sLink + '#' + sBookmark;
Attributes.add('href', sLink);
If sTarget <> '' Then
Attributes.add('target', sTarget);
ProduceLine(StringFormat('<a %s>%s</a>', [UseAttributes, EncodeXML(sCaption)]));
End;
Procedure TFslHTMLFormatter.ProduceAnchorOpen(Const sReference, sBookmark, sTarget : String);
Var
sLink : String;
Begin
sLink := sReference;
If sBookmark <> '' Then
sLink := sLink + '#' + sBookmark;
Attributes.add('href', sLink);
If sTarget <> '' Then
Attributes.add('target', sTarget);
ProduceOpen('a');
End;
Procedure TFslHTMLFormatter.ProduceAnchorClose;
Begin
ProduceClose('a');
End;
Procedure TFslHTMLFormatter.ProduceBookmark(Const sBookmark: String);
Begin
Attributes.add('name', sBookmark);
Attributes.add('id', sBookmark);
ProduceLine('<a' + UseAttributes + '></a>');
End;
Procedure TFslHTMLFormatter.ProduceTitle(Const sTitle: String);
Begin
ProduceText('title', sTitle);
End;
Procedure TFslHTMLFormatter.ProduceStylesheet(Const sFilename: String);
Begin
Attributes.Match['rel'] := 'stylesheet';
Attributes.Match['href'] := sFilename;
Attributes.Match['type'] := 'text/css';
ProduceTag('link');
End;
Procedure TFslHTMLFormatter.ProduceSymbol(Const aSymbol: TFslHTMLSymbol);
Begin
Produce('&' + HTML_SYMBOL_VALUES[aSymbol] + ';');
End;
Procedure TFslHTMLFormatter.ProduceGreekSymbol(Const aSymbol: TFslHTMLGreekSymbol);
Begin
Produce('&' + HTML_GREEK_SYMBOL_VALUES[aSymbol] + ';');
End;
Procedure TFslHTMLFormatter.ProduceMathSymbol(Const aSymbol: TFslHTMLMathSymbol);
Begin
Produce('&' + HTML_MATH_SYMBOL_VALUES[aSymbol] + ';');
End;
Function TFslHTMLFormatter.GetStyle: String;
Begin
Result := Attributes.Match['class'];
End;
Procedure TFslHTMLFormatter.SetStyle(Const Value: String);
Begin
Attributes.Match['class'] := Value;
End;
Procedure TFslHTMLFormatter.ProduceHeading(Const sText: String; Const iLevel : Integer);
Begin
ProduceText('h' + IntegerToString(iLevel), sText);
End;
Procedure TFslHTMLFormatter.ProduceLineBreak;
Begin
ProduceTag('br');
End;
Procedure TFslHTMLFormatter.ProduceTableCellText(Const sText: String);
Begin
ProduceText('td', sText);
End;
Procedure TFslHTMLFormatter.ProduceTableOpen;
Begin
ProduceOpen('table');
End;
Procedure TFslHTMLFormatter.ProduceTableClose;
Begin
ProduceClose('table');
End;
Procedure TFslHTMLFormatter.ProduceTableHeadOpen;
Begin
ProduceOpen('th');
End;
Procedure TFslHTMLFormatter.ProduceTableHeadClose;
Begin
ProduceClose('th');
End;
Procedure TFslHTMLFormatter.ProduceTableRowOpen;
Begin
ProduceOpen('tr');
End;
Procedure TFslHTMLFormatter.ProduceTableRowClose;
Begin
ProduceClose('tr');
End;
Procedure TFslHTMLFormatter.ProduceTableCellOpen;
Begin
ProduceOpen('td');
End;
Procedure TFslHTMLFormatter.ProduceTableCellClose;
Begin
ProduceClose('td');
End;
Procedure TFslHTMLFormatter.ProduceSpan(Const sText: String);
Begin
ProduceOpen('span');
ProduceEscaped(sText);
ProduceClose('span');
End;
Procedure TFslHTMLFormatter.ProduceParagraph(Const sText: String);
Begin
ProduceOpen('p');
ProduceEscaped(sText);
ProduceClose('p');
End;
Procedure TFslHTMLFormatter.ProduceInlineDocument(Const sDocument: String);
Var
iPos : Integer;
sContent : String;
Begin
// Style.
sContent := sDocument;
iPos := Pos('<head', sContent);
If iPos > 0 Then
Begin
Delete(sContent, 1, iPos - 1);
iPos := Pos('</head>', sContent);
If iPos > 0 Then
Begin
Delete(sContent, iPos + Length('</head>'), MaxInt);
//only the header section should remain in sContent now, so extract the style
//section from it if it exists
iPos := Pos('<style', sContent);
If iPos > 0 Then
Begin
Delete(sContent, 1, iPos + Length('<style'));
iPos := Pos('>', sContent);
If iPos > 0 Then
Begin
Delete(sContent, 1, iPos);
iPos := Pos('</style>', sContent);
If iPos > 0 Then
Begin
Delete(sContent, iPos, MaxInt);
ProduceStyleOpen;
Produce(sContent);
ProduceStyleClose;
End;
End;
End;
End;
End;
// Body.
sContent := sDocument;
iPos := Pos('<body', sContent);
If iPos > 0 Then
Begin
Delete(sContent, 1, iPos);
iPos := Pos('>', sContent);
If iPos > 0 Then
Begin
Delete(sContent, 1, iPos);
iPos := Pos('</body>', sContent);
If iPos > 0 Then
Delete(sContent, iPos, Length(sContent));
End;
End;
Produce(sContent);
End;
Procedure TFslHTMLFormatter.ProduceTableColumn;
Begin
ProduceInlineTag('col');
End;
Procedure TFslHTMLFormatter.ProduceTableColumnGroupClose;
Begin
ProduceClose('colgroup');
End;
Procedure TFslHTMLFormatter.ProduceTableColumnGroupOpen;
Begin
ProduceOpen('colgroup');
End;
Procedure TFslHTMLFormatter.ApplyAttributeAlignCenter;
Begin
Attributes.Match['align'] := 'center';
End;
Procedure TFslHTMLFormatter.ApplyAttributeAlignLeft;
Begin
Attributes.Match['align'] := 'left';
End;
Procedure TFslHTMLFormatter.ApplyAttributeAlignRight;
Begin
Attributes.Match['align'] := 'right';
End;
Procedure TFslHTMLFormatter.ApplyAttributeWidthPixel(Const iWidthPixel: Integer);
Begin
Attributes.Match['width'] := IntegerToString(iWidthPixel) + 'px';
End;
Procedure TFslHTMLFormatter.ApplyAttributeHeightPixel(Const iHeightPixel: Integer);
Begin
Attributes.Match['height'] := IntegerToString(iHeightPixel) + 'px';
End;
Procedure TFslHTMLFormatter.ApplyAttributeHeightPercentage(Const iHeightPercentage: Integer);
Begin
Attributes.Match['height'] := IntegerToString(iHeightPercentage) + '%';
End;
Procedure TFslHTMLFormatter.ProduceImageReference(Const sReference: String; Const sAlternate : String = '');
Begin
Attributes.Match['src'] := sReference;
Attributes.Match['alt'] := sAlternate;
ProduceInlineTag('img');
End;
Function TFslHTMLFormatter.GetProduceXHTML: Boolean;
Begin
Result := FAdapter.ProduceXHTML;
End;
Procedure TFslHTMLFormatter.SetProduceXHTML(Const Value: Boolean);
Begin
FAdapter.ProduceXHTML := True;
End;
Procedure TFslHTMLAdapter.Read(Var Buffer; iCount: Integer);
Var
iLoop : Cardinal;
pBuffer : PChar;
aType : Array[0..4] Of Char;
iType : Integer;
Begin
pBuffer := @Buffer;
iLoop := 0;
While (iLoop < iCount) Do
Begin
Inherited Read(pBuffer^, 1);
If (pBuffer^ = '&') Then
Begin
iType := 0;
// Read the next few bytes after the ampersand.
While Not CharInSet(aType[iType], [';'] + setWhitespace) And (iType <= High(aType)) Do
Begin
Inherited Read(aType[iType], 1);
Inc(iType);
End;
aType[iType] := #0;
If StringEquals(aType, 'lt;', 3) Then
pBuffer^ := '<'
Else If StringEquals(aType, 'gt;', 3) Then
pBuffer^ := '>'
Else If StringEquals(aType, 'amp;', 4) Then
pBuffer^ := '&'
Else
Begin
// Preserve the read ampersand and replace all the other characters
iType := 0;
While (aType[iType] <> #0) Do
Begin
Inc(pBuffer);
pBuffer^ := aType[iType];
Inc(iType);
End;
End;
End;
Inc(pBuffer);
Inc(iLoop);
End;
End;
Procedure TFslHTMLAdapter.Write(Const Buffer; iCount: Integer);
Var
pBuffer, pStart : PChar;
iLoop : Integer;
Begin
pBuffer := @Buffer;
pStart := pBuffer;
For iLoop := 0 To Integer(iCount) - 1 Do
Begin
Case pBuffer^ Of
{
#0..#31, #127..#255 :
Begin
Inherited Write('&#' + IntegerToString(Byte(pBuffer)^));
Inc(pBuffer);
pStart := pBuffer;
End;
}
'<' :
Begin
Inherited Write(pStart^, Cardinal(pBuffer) - Cardinal(pStart));
Inherited Write('<', 4);
Inc(pBuffer);
pStart := pBuffer;
End;
'>' :
Begin
Inherited Write(pStart^, Cardinal(pBuffer) - Cardinal(pStart));
Inherited Write('>', 4);
Inc(pBuffer);
pStart := pBuffer;
End;
'&' :
Begin
Inherited Write(pStart^, Cardinal(pBuffer) - Cardinal(pStart));
Inherited Write('&', 5);
Inc(pBuffer);
pStart := pBuffer;
End;
cEnter :
Begin
Inherited Write(pStart^, Cardinal(pBuffer) - Cardinal(pStart));
If FProduceXHTML Then
Inherited Write('<br />', 6)
Else
Inherited Write('<br>', 4);
Inc(pBuffer);
pStart := pBuffer;
End;
cFeed :
Begin
// Ignore Feed characters.
Inc(pBuffer);
End;
Else
Inc(pBuffer);
End;
End;
Inherited Write(pStart^, Cardinal(pBuffer) - Cardinal(pStart));
End;
Initialization
FillChar(gTable, SizeOf(gTable), ahtNull);
gTable['!'] := ahtExclamation;
gTable['?'] := ahtQuery;
gTable['='] := ahtEquals;
gTable['/'] := ahtForwardSlash;
gTable['\'] := ahtBackwardSlash;
gTable['.'] := ahtPeriod;
gTable[','] := ahtComma;
gTable[':'] := ahtColon;
gTable[';'] := ahtSemiColon;
gTable['_'] := ahtUnderscore;
gTable['-'] := ahtHyphen;
gTable['`'] := ahtBackQuote;
gTable[''''] := ahtSingleQuote;
gTable['"'] := ahtDoubleQuote;
gTable['~'] := ahtTilde;
gTable['@'] := ahtAt;
gTable['#'] := ahtHash;
gTable['$'] := ahtDollar;
gTable['%'] := ahtPercentage;
gTable['^'] := ahtCaret;
gTable['&'] := ahtAmpersand;
gTable['*'] := ahtAsterisk;
gTable['('] := ahtOpenRound;
gTable[')'] := ahtCloseRound;
gTable['+'] := ahtPlus;
gTable['['] := ahtOpenSquare;
gTable[']'] := ahtCloseSquare;
gTable['{'] := ahtOpenBrace;
gTable['}'] := ahtCloseBrace;
gTable['|'] := ahtPipe;
End.
| 24.69659 | 171 | 0.723248 |
851818cf433066d519ea58290df8002981cc390d | 319 | dpr | Pascal | TileAtrEditor.dpr | jkoncick/TileAtrEditor | 10d7879d75143bdcbb9cc0491c863b9b0e6a2f80 | [
"MIT"
]
| null | null | null | TileAtrEditor.dpr | jkoncick/TileAtrEditor | 10d7879d75143bdcbb9cc0491c863b9b0e6a2f80 | [
"MIT"
]
| null | null | null | TileAtrEditor.dpr | jkoncick/TileAtrEditor | 10d7879d75143bdcbb9cc0491c863b9b0e6a2f80 | [
"MIT"
]
| null | null | null | program TileAtrEditor;
uses
Forms,
main in 'main.pas' {MainWindow};
{$R *.res}
begin
Application.Initialize;
Application.HelpFile := 'Dune 2000 Tileset Attributes Editor';
Application.Title := 'D2K+ TileAtr Editor';
Application.CreateForm(TMainWindow, MainWindow);
Application.Run;
end.
| 19.9375 | 65 | 0.69906 |
4780736d78dcf9a341cbba485c87cbc2cdfd0f26 | 29,537 | pas | Pascal | Source/Ringbuffer.pas | atkins126/CircularBuffer | 669b0564ae513703b12c85406c7aed39f80db4bc | [
"Apache-2.0"
]
| 15 | 2020-08-24T05:25:47.000Z | 2022-02-07T19:37:07.000Z | Source/Ringbuffer.pas | UweRaabe/CircularBuffer | 098247da6a1228ae20db84bb755ff306266b71ca | [
"Apache-2.0"
]
| 1 | 2020-08-25T16:43:02.000Z | 2020-08-25T16:43:02.000Z | Source/Ringbuffer.pas | UweRaabe/CircularBuffer | 098247da6a1228ae20db84bb755ff306266b71ca | [
"Apache-2.0"
]
| 6 | 2020-10-10T04:31:47.000Z | 2021-12-01T17:24:58.000Z | {*****************************************************************************
The CircularBuffer team (see file NOTICE.txt) licenses this file
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.
*****************************************************************************}
unit Ringbuffer;
interface
uses
SysUtils, Generics.Collections;
type
/// <summary>
/// raised when there are more data written to the buffer than it can hold
/// </summary>
EBufferFullException = class(Exception);
/// <summary>
/// raised when a single element is taken from an empty buffer
/// </summary>
EBufferEmptyException = class(Exception);
/// <summary>
/// types of ring buffer events: <br />
/// </summary>
TRingbufferEventType = (
/// <summary>
/// at least one element was added
/// </summary>
evAdd,
/// <summary>
/// at least one element was removed or deleted or the buffer is cleared
/// </summary>
evRemove);
/// <summary>
/// Event type triggered by all operations manipulating the number of elements in the ring buffer: Add, Remove,
/// Delete...
/// </summary>
/// <param name="Count">
/// new number of elements in the buffer
/// </param>
/// <param name="Event">
/// type of event:
/// <list type="bullet">
/// <item>
/// evAdd when Count was increased,
/// </item>
/// <item>
/// evRemove when Count was decreased
/// </item>
/// </list>
/// </param>
TRingbufferNotify = procedure(Count: UInt32; Event:TRingbufferEventType) of Object;
/// <summary>
/// Implementation of a generic ring buffer for all types without taking any ownership. For a ring buffer freeing
/// all contained objects on Destroy use <c>TObjectRingBuffer<T></c>.
/// </summary>
/// <seealso cref="TObjectRingBuffer<T>">
/// TObjectRingBuffer<T>
/// </seealso>
TRingbuffer<T> = class(TObject)
type
/// <summary>
/// return and parameter type for most of the operators
/// </summary>
TRingbufferArray = TArray<T>;
strict private
/// <summary>
/// Indicates whether the ring buffer takes ownership of the instances
/// </summary>
FOwnsObjects : Boolean;
/// <summary>
/// Copies items into the already allocated Dest array. Since this is
/// coded the naive way it is only meant for managed types where move is wrong.
/// </summary>
/// <param name="Dest">
/// Already allocated target array where the copied items will be stored in
/// </param>
/// <param name="StartIndex">
/// Index of the first item to be copied
/// </param>
/// <param name="Count">
/// Number of items to copy
/// </param>
/// <remarks>
/// This method expects that the parameters given are valid!
/// </remarks>
procedure CopyItems(var Dest: TRingbufferArray; StartIndex, Count: UInt32); inline;
/// <summary>
/// Frees all object instances in the buffer if OwnsObject is true and
/// the type is an object based type. Sets the slots within the circular
/// buffer to nil as well.
/// </summary>
/// <param name="StartIndex">
/// Index of the first item to be deleted. Must be less than <c>EndIndex</c>
/// and in the range <c>0 .. Count - 1</c>. Thus wrapped buffer content
/// cannot be deleted in one go.
/// </param>
/// <param name="EndIndex">
/// Index of the last item to be deleted. Must be larger than <c>StartIndex</c>
/// and in the range <c>0 .. Count - 1.</c>
/// </param>
procedure FreeObjectsIfOwned(StartIndex, EndIndex: UInt32);
strict protected
/// <summary>
/// Static storage for all elements. The size is determined in the constructor.
/// </summary>
FItems : TRingbufferArray;
/// <summary>
/// Index of the first buffer item
/// </summary>
FStart : UInt32;
/// <summary>
/// Index of the next free buffer item, where an element can be written directly
/// </summary>
/// <remarks>
/// If <c>FNextFree = FStart</c> the buffer is either empty or full. The actual state is determined by <c>
/// FContainsData</c>: True means <i>the buffer is full</i>.
/// </remarks>
FNextFree : UInt32;
/// <summary>
/// Indicates whether the buffer actually contains data.
/// </summary>
/// <remarks>
/// If <c>FStart = FNextFree</c> the buffer is either empty or full. This field gives the missing information.
/// </remarks>
FContainsData : Boolean;
/// <summary>
/// This event is triggered by all operations manipulating the number of elements in the ring buffer: Add,
/// Remove, Delete... <br />
/// </summary>
FNotify : TRingbufferNotify;
/// <summary>
/// Returns the number of items currently in the ring buffer
/// </summary>
function GetCount: UInt32;
/// <summary>
/// Returns the number of elements that can be stored in the ring buffer
/// </summary>
function GetSize: UInt32;
/// <summary>
/// Increments the Tail marker, wrapping it to 0 when necessary
/// </summary>
/// <param name="Increment">
/// How much items the Tail should be advanced
/// </param>
/// <remarks>
/// The method assumes that the case <c>Tail+ Increment > First</c> is already taken care of by the caller
/// </remarks>
procedure AdvanceNextFree(Increment: UInt32); inline;
/// <summary>
/// Prototype method for freeing objects
/// </summary>
/// <param name="StartIndex">
/// Index of the first item to be deleted. Must be less than <c>EndIndex</c> and in the range <c>0 .. Count - 1</c>
/// . Thus wrapped buffer content cannot be deleted in one go.
/// </param>
/// <param name="EndIndex">
/// Index of the last item to be deleted. Must be larger than <c>StartIndex</c> and in the range <c>0 .. Count -
/// 1.</c>
/// </param>
/// <remarks>
/// The current implementation is empty, but is overridden in <c>TObjectRiungBuffer<T></c>.
/// </remarks>
procedure FreeOrNilItems(StartIndex, EndIndex: UInt32); virtual;
public
/// <summary>
/// Creates the ring buffer with the given size
/// </summary>
/// <param name="Size">
/// Number of elements the ring buffer will hold
/// </param>
constructor Create(Size: UInt32);
/// <summary>
/// Frees the ring buffer memory
/// </summary>
/// <example>
/// Any object instances in the ring buffer will not be freed. If the ring buffer shall be responsible for
/// managing the lifetime of those objects <c>TObjectRingbuffer<T></c> would be the better choice!
/// </example>
destructor Destroy; override;
/// <summary>
/// Appends the given item to the ring buffer
/// </summary>
/// <param name="Item">
/// Anzuhängendes Element
/// </param>
/// <exception cref="EBufferFullException">
/// not enough capacity
/// </exception>
/// <remarks>
/// If there is not enough capacity an <c>EBufferFullException</c> is raised. <br />
/// </remarks>
procedure Add(Item: T); overload; virtual;
/// <summary>
/// Appends multiple items to the ring buffer
/// </summary>
/// <param name="Items">
/// array of elements to append
/// </param>
/// <exception cref="EBufferFullException">
/// not enough capacity
/// </exception>
/// <remarks>
/// The size of the array must be less than the free capacity of the buffer. Otherwise an <c>EBufferFullException</c>
/// is raised.
/// </remarks>
procedure Add(Items:TRingbufferArray); overload; virtual;
/// <summary>
/// Returns the first element from the ring buffer and removes it
/// </summary>
/// <returns>
/// The element from the buffer which was longest in the buffer
/// </returns>
/// <exception cref="EBufferEmptyException">
/// buffer is empty
/// </exception>
/// <remarks>
/// If the buffer is empty an <c>EBufferEmptyException</c> is raised
/// </remarks>
function Remove:T; overload; virtual;
/// <summary>
/// Returns the first <c>RemoveCount</c> elements from the buffer
/// </summary>
/// <param name="RemoveCount">
/// Number of elements to retrieve
/// </param>
/// <returns>
/// Array mit einer maximalen Länge von Count
/// </returns>
/// <exception cref="EBufferEmptyException">
/// buffer is empty
/// </exception>
/// <exception cref="EArgumentOutOfRangeException">
/// <c>RemoveCount</c> exceeds buffer size
/// </exception>
/// <remarks>
/// <list type="bullet">
/// <item>
/// If there are less elements in the buffer as requested, only the vailable elements are returned
/// </item>
/// <item>
/// If the buffer is empty an EBufferEmptyException is raised.
/// </item>
/// <item>
/// If more elements are requested than the capacity of the buffer an EArgumentOutOfRangeException is
/// raised
/// </item>
/// </list>
/// </remarks>
function Remove(RemoveCount: UInt32):TRingbufferArray; overload; virtual;
/// <summary>
/// Removes the given number of elements from the buffers Head
/// </summary>
/// <param name="Count">
/// Number of elements to be deleted
/// </param>
/// <exception cref="EArgumentOutOfRangeException">
/// <c>Count</c> exceeds buffer size
/// </exception>
/// <remarks>
/// <para>
/// Elements are not overridden, but cannot be accessed after being deleted.
/// </para>
/// <para>
/// If more elements are to be deleted than are available in the buffer, the buffer is cleared.
/// </para>
/// <para>
/// If more elements are to be deleted than the capacity of the buffer an <b>EArgumentOutOfRangeException</b>
/// is raised.
/// </para>
/// </remarks>
procedure Delete(Count: UInt32); virtual;
/// <summary>
/// Clears the buffer and initializes Head and Tail
/// </summary>
/// <remarks>
/// There is no data overridden, but cannot be accessed any more.
/// </remarks>
procedure Clear; virtual;
/// <summary>
/// Returns an item from the buffer from the given position without removing it
/// </summary>
/// <param name="Index">
/// Index of the item to be returned. Range is <c>0 .. Count-1</c>. <c>0</c> is same as Head.
/// </param>
/// <returns>
/// Item at <c>Index</c> position. The item stays in the buffer.
/// </returns>
/// <exception cref="EArgumentOutOfRangeException">
/// <c>Index</c> exceeds available elements
/// </exception>
/// <remarks>
/// The allowed range for Index is 0 .. Count-1. If the index is outside this range an
/// EArgumentOutOfRangeException is raised. <br />
/// </remarks>
function Peek(Index: UInt32):T; overload;
/// <summary>
/// Retrieves multiple items from the buffer without removing them
/// </summary>
/// <param name="Index">
/// Index of the first element retrieved. Rangs is <c>0 .. Count-1</c>.
/// </param>
/// <param name="Count">
/// Number of items to retrieve.
/// </param>
/// <returns>
/// The items from <c>Index</c> position up to the requested count or less. The buffer content is not changed.
/// </returns>
/// <exception cref="EArgumentOutOfRangeException">
/// <c>Index</c> exceeds <c>Count - 1</c> or the buffer capacity
/// </exception>
/// <remarks>
/// <para>
/// If Index is larger than <c>Count - 1</c> an <b>EArgumentOutOfRangeException</b> is raised.
/// </para>
/// <para>
/// <c>Count = 0</c> returns an empty array.
/// </para>
/// <para>
/// If more items are requested than are available in the buffer the number of items returned is capped to
/// the possible number.
/// </para>
/// <para>
/// If more items are requested than the buffer capacity an <b>EArgumentOutOfRangeException</b> is raised.
/// </para>
/// </remarks>
function Peek(Index, Count: UInt32):TRingbufferArray overload;
/// <summary>
/// Returns the number of elements that can be stored in the ring buffer
/// </summary>
property Size : UInt32
read GetSize;
/// <summary>
/// Returns the number of items currently in the ring buffer
/// </summary>
property Count : UInt32
read GetCount;
/// <summary>
/// This event is triggered by all operations manipulating the number of elements in the ring buffer: Add,Remove,
/// Delete...
/// </summary>
property Notify : TRingbufferNotify
read FNotify
write FNotify;
/// <summary>
/// Indicates whether the ring buffer takes ownership of the instances <br />
/// </summary>
property OwnsObjects: Boolean
read FOwnsObjects
write FOwnsObjects;
end;
implementation
{ TRingbuffer<T> }
procedure TRingbuffer<T>.Add(Item: T);
begin
// nur hinzufügen wenn entweder noch Platz im Puffer oder wenn Puffer ganz
// leer (dann sind Start- und Ende Zeiger gleich, aber das FContaisData Flag
// ist noch false
if (Count < Size) or ((Count = Size) and not FContainsData) then
begin
FItems[FNextFree] := Item;
AdvanceNextFree(1);
FContainsData := true;
if assigned(FNotify) then
FNotify(Count, evAdd);
end
else
raise EBufferFullException.Create('Capacity of this ringbuffer is exhausted. '+
'Capacity is '+Size.ToString+' Start: '+
FStart.ToString+' End: '+FNextFree.ToString);
end;
procedure TRingbuffer<T>.Add(Items: TRingbufferArray);
var
FreeItemsAfterEnd : UInt32; // Anzahl freier Elemente zwischen Ende Marker und
// Ende des Arrays
i : UInt32;
begin
assert(length(Items) > 0, 'Hinzufügen eines leeren Arrays ist nicht sinnvoll');
// ist überhaupt noch soviel Platz im Puffer?
// Typecast nach Int64 um W1023 Warnung zu unterdrücken
if (length(Items) <= Int64(Size-Count)) then
begin
// leeres Array sollte eigentlich nicht vorkommen, aber falls im Release
// Build Assertions aus sind sollte es auch nicht abstürzen
if (length(Items) > 0) then
begin
// Passt das übergebene Array im Stück in den Puffer und der Puffer Inhalt
// geht derzeit auch nicht über die obere Grenze hinaus, oder muss es
// gesplittet werden? Typecast nach Int64 um W1023 Warnung zu unterdrücken
if (Int64(Size-FNextFree) >= length(Items)) then
begin
if not IsManagedType(T) then
Move(Items[0], FItems[FNextFree], length(Items) * SizeOf(Items[0]))
else
for i := 0 to length(Items) - 1 do
FItems[FNextFree + i] := Items[i];
end
else
begin
// restlichen Platz im Puffer berechnen
FreeItemsAfterEnd := Size - FNextFree;
if not IsManagedType(T) then
begin
// von Ende-Marker bis zum Array Ende
Move(Items[0], FItems[FNextFree], FreeItemsAfterEnd * SizeOf(Items[0]));
// restliche Daten vom Anfang an
Move(Items[FreeItemsAfterEnd], FItems[0],
(UInt32(length(Items))-FreeItemsAfterEnd) * SizeOf(Items[0]));
end
else
begin
for i := 0 to FreeItemsAfterEnd - 1 do
FItems[FNextFree + i] := Items[i];
for i := FreeItemsAfterEnd to length(Items) - 1 do
FItems[i-FreeItemsAfterEnd] := Items[i];
end;
end;
// Endeindex erhöhen
AdvanceNextFree(length(Items));
FContainsData := true;
if assigned(FNotify) then
FNotify(Count, evAdd);
end;
end
else
raise EBufferFullException.Create('Capacity of this ringbuffer is exhausted. '+
'Free space is '+(Size-Count).ToString+' Start: '+
FStart.ToString+' End: '+FNextFree.ToString);
end;
procedure TRingbuffer<T>.AdvanceNextFree(Increment: UInt32);
var
Remaining : UInt32; // Verbleibende Speicherplätze bis zur oberen Array Grenze
begin
Remaining := Size-FNextFree;
inc(FNextFree, Increment);
// Ende Marker über das Array-Ende hinaus erhöht
if (FNextFree > Size-1) then
FNextFree := (Increment-Remaining);
end;
procedure TRingbuffer<T>.Clear;
var
i : Integer;
begin
FStart := 0;
FNextFree := 0;
FContainsData := false;
FreeObjectsIfOwned(FStart, Size - 1);
// We exceet the upper end of the buffer so we need to clear the remaining
// objects from the beginning
if (FStart + Count > Size) then
FreeObjectsIfOwned(0, (FStart + Count) - Size - 1);
if IsManagedType(T) or (GetTypeKind(T) = tkClass) then
for i := 0 to High(FItems) do
FItems[i] := Default(T);
if assigned(FNotify) then
FNotify(0, evRemove);
end;
constructor TRingbuffer<T>.Create(Size: UInt32);
var
i : Integer;
begin
assert(Size >= 2, 'Puffer mit weniger als 2 Elementen sind nicht sinnvoll!');
inherited Create;
SetLength(FItems, Size);
for i := 0 to High(FItems) do
FItems[i] := Default(T);
FStart := 0;
FNextFree := 0;
FContainsData := false;
FNotify := nil;
end;
procedure TRingbuffer<T>.Delete(Count: UInt32);
var
Remaining : UInt32; // Verbleibende Speicherplätze bis zur oberen Array Grenze
i : Integer;
begin
if (Count <= Size) then
begin
// Puffer nur teilweise zu löschen?
if (Count < self.Count) then
begin
Remaining := Size - FStart;
// Pufferinhalt geht nicht über obere Array Grenze hinaus?
if (Count < Remaining) then
begin
if (Count > 0) then
begin
FreeObjectsIfOwned(FStart, FStart + Count - 1);
if IsManagedType(T) then
for i := FStart to FStart + Count - 1 do
FItems[i] := Default(T);
// Startmarker verschieben
FStart := FStart + Count;
end;
end
else
begin
if (Count > 0) then
begin
FreeObjectsIfOwned(FStart, FStart + Remaining - 1);
FreeObjectsIfOwned(0, Count - Remaining - 1);
if IsManagedType(T) then
begin
// clear until the high end
for i := FStart to Size - 1 do
FItems[i] := Default(T);
for i := 0 to Count - Remaining - 1 do
FItems[i] := Default(T);
end;
// Anzahl der Positionen um die insgesamt verschoben werden soll - Anzahl
// der Positionen bis zum oberen Array Ende abziehen ergibt neue
// Startposition vom Array-Anfang aus gesehen.
FStart := (Count - Remaining);
end;
end;
// nur benachrichtigen wenn überhaupt was gelöscht werden sollte
if assigned(FNotify) and (Count > 0) then
FNotify(Count, evRemove);
end
else
// alles zu löschen
Clear;
end
else
raise EArgumentOutOfRangeException.Create('Cannot delete more that buffer '+
'size elements. Size: '+Size.ToString+
' Elements to be deleted: '+Count.ToString);
end;
destructor TRingbuffer<T>.Destroy;
begin
FreeObjectsIfOwned(0, Size-1);
SetLength(FItems, 0);
inherited;
end;
procedure TRingbuffer<T>.FreeOrNilItems(StartIndex, EndIndex: UInt32);
begin
// absichtlich leer, wird in Kindklasse ausprogrammiert
end;
function TRingbuffer<T>.GetCount: UInt32;
var
l : Int64;
begin
// Puffer ist weder komplett leer noch komplett voll
if (FNextFree <> FStart) then
begin
// Je nach dem ob der Puffer gerade über das Ende hinaus geht und am Anfang
// weiter geht
if (FNextFree > FStart) then
result := FNextFree-FStart
else
begin
// Puffer geht über das Ende hinaus und beginnt am Array Anfang wieder
l := (length(FItems)-Int64(FStart))+FNextFree;
result := abs(l);
end;
end
else
// Start = Ende aber es sind daten da? Dann ist Puffer maximal gefüllt
if FContainsData then
result := Size
else
// Start = Ende und Puffer ist leer
result := 0;
end;
function TRingbuffer<T>.GetSize: UInt32;
begin
result := length(FItems);
end;
function TRingbuffer<T>.Peek(Index: UInt32): T;
var
reminder : UInt32;
begin
if (Index < Count) then
begin
// buffer doesn't wrap at the high array bound yet
if ((FStart+Index) < Size) then
result := FItems[FStart+Index]
else
begin
// how much does the buffer exceed the upper array bounds?
reminder := (FStart+Index)-Size;
result := FItems[reminder];
end;
end
else
raise EArgumentOutOfRangeException.Create('Invalid Index: '+Index.ToString+
' Max. Index: '+Count.ToString);
end;
procedure TRingbuffer<T>.CopyItems(var Dest: TRingbufferArray; StartIndex, Count: UInt32);
var
i, n : Integer;
begin
assert(assigned(Dest), 'Destination array not assigned');
assert(StartIndex < self.Count,
'StartIndex too high. StartIndex: ' + StartIndex.ToString +
' Count: ' + self.Count.ToString);
assert(Count <= self.Count,
'Cannot copy ' + Count.ToString + ' items when only ' +
self.Count.ToString + ' are in the buffer');
n := 0;
for i := StartIndex to StartIndex + Count-1 do
begin
Dest[n] := self.FItems[i];
inc(n);
end;
end;
function TRingbuffer<T>.Peek(Index, Count: UInt32): TRingbufferArray;
var
RemoveableCount : UInt32; // Number of removeable items, most times count
RemainingCount : UInt32; // Number of items from Start until Pufferende
i : UInt32;
begin
// Have more items been requested than fitting into the buffer?
// Is the index in the valid range?
if (Count <= Size) and (Index < self.Count) then
begin
// Ist überhaupt was im Puffer?
if (self.Count > 0) then
begin
// there are as many items in the buffer as shall be copied
if (Count <= self.Count) then
RemoveableCount := Count
else
// No, just remove as many as possible
RemoveableCount := self.Count;
SetLength(result, RemoveableCount);
// wraps the current buffer contents at the upper border of the buffer?
if ((FStart+Index+RemoveableCount) <= Size) then
begin
// No, one can copy directly
if not IsManagedType(T) then
Move(FItems[FStart+Index], result[0], RemoveableCount * SizeOf(FItems[0]))
else
if RemoveableCount > 0 then
CopyItems(result, FStart+Index, RemoveableCount);
end
else
begin
// Yes, two copy operations necessary
RemainingCount := (Size-(FStart+Index));
if not IsManagedType(T) then
// from Startindex until buffer end
Move(FItems[FStart+Index], result[0], RemainingCount * SizeOf(FItems[0]))
else
CopyItems(result, FStart+Index, RemainingCount);
// from start of the buffer until end-pointer
RemoveableCount := RemoveableCount-RemainingCount;
if not IsManagedType(T) then
Move(FItems[0], result[RemainingCount], RemoveableCount * SizeOf(FItems[0]))
else
for i := 0 to RemoveableCount - 1 do
result[RemainingCount + i] := FItems[i];
end;
end
else
SetLength(result, 0);
end
else
raise EArgumentOutOfRangeException.Create('Too many elements requested or '+
'index out of range. Size: '+
Size.ToString+'Index: '+
Index.ToString+' Count: '+Count.ToString);
end;
function TRingbuffer<T>.Remove(RemoveCount: UInt32): TRingbufferArray;
var
RemoveableCount : UInt32; // Anzahl entfernbarer Elemente, meist Count
RemainingCount : UInt32; // Anzahl Elemente von Start bis Pufferende
StillContainsData : Boolean; // Enthält der Puffer nach der Remove Operation
// immer noch Daten?
i : UInt32;
begin
if (RemoveCount > 0) then
begin
// wurden mehr Elemente angefordert als überhaupt je in den Puffer passen?
if (RemoveCount <= Size) then
begin
// Ist überhaupt was im Puffer?
if (Count > 0) then
begin
// es sind soviele Elemente im Puffer wie entfernt werden sollen
if (RemoveCount <= Count) then
RemoveableCount := RemoveCount
else
// Nein, also nur soviele entfernen wie überhaupt möglich
RemoveableCount := Count;
SetLength(result, RemoveableCount);
// wenn alle Elemente entfernt werden sollen muss Flag hinterher auf False
// gesetzt werden
StillContainsData := RemoveCount <> Count;
// geht der aktuelle Puffer inhalt über die obere Grenze (d.h. klappt um)?
if ((FStart + RemoveableCount) <= Size) then
begin
// Nein, also Elemente direkt kopierbar
if not IsManagedType(T) then
Move(FItems[FStart], result[0], RemoveableCount * SizeOf(FItems[0]))
else
for i := FStart to FStart + RemoveableCount - 1 do
begin
result[i-FStart] := FItems[i];
// Take care of the reference counting by setting it to default
// for the type
FItems[i] := Default(T);
end;
inc(FStart, RemoveableCount);
end
else
begin
// 2 Kopieroperationen nötig
RemainingCount := (Size-FStart);
// von Startzeiger bis Pufferende
if not IsManagedType(T) then
Move(FItems[FStart], result[0], RemainingCount * SizeOf(FItems[0]))
else
for i := FStart to FStart + RemainingCount - 1 do
begin
result[i-FStart] := FItems[i];
// Take care of the reference counting by setting it to default
// for the type
FItems[i] := Default(T);
end;
// von Pufferstart bis Endezeiger
RemoveableCount := RemoveableCount-RemainingCount;
if not IsManagedType(T) then
Move(FItems[0], result[RemainingCount], RemoveableCount * SizeOf(FItems[0]))
else
for i := 0 to RemoveableCount - 1 do
begin
result[RemainingCount + i] := FItems[i];
// Take care of the reference counting by setting it to default
// for the type
FItems[i] := Default(T);
end;
FStart := RemoveableCount;
end;
FContainsData := StillContainsData;
if assigned(FNotify) then
FNotify(RemoveCount, evRemove);
end
else
SetLength(result, 0);
end
else
raise EArgumentOutOfRangeException.Create('Too many elements requested: '+RemoveCount.ToString+
' Max. possible number: '+Size.ToString);
end
else
SetLength(Result, 0);
end;
function TRingbuffer<T>.Remove: T;
var
i : UInt32;
begin
// ist überhaupt was im Puffer?
if Count > 0 then
begin
result := FItems[FStart];
// for managed types we need to free it or decrement reference counter
if IsManagedType(T) or (GetTypeKind(T) = tkClass) then
FItems[FStart] := Default(T);
// Anfangsmarker verschieben
inc(FStart);
// obere Grenze überschritten?
if (FStart = Size) then
FStart := 0;
// wenn Start = Ende ist der Puffer leer
if (FStart = FNextFree) then
FContainsData := false;
if assigned(FNotify) then
FNotify(Count, evRemove);
end
else
raise EBufferEmptyException.Create('Attempt to remove an item from a '+
'completely empty buffer');
end;
procedure TRingbuffer<T>.FreeObjectsIfOwned(StartIndex, EndIndex: UInt32);
var
i : UInt32;
begin
assert(EndIndex <= Size, 'Endindex too high. Is: '+
EndIndex.ToString+' Allowed: '+Size.ToString);
assert(StartIndex <= EndIndex, 'Invalid range specified: '+
StartIndex.ToString+'/'+EndIndex.ToString);
if FOwnsObjects and (GetTypeKind(T) = tkClass) then
begin
for i := StartIndex to EndIndex do
PObject(@FItems[i])^.Free;
for i := StartIndex to EndIndex do
FItems[i] := Default(T);
end;
end;
end.
| 33.67959 | 123 | 0.602939 |
474a3dd1918b0a667611adf4ab53834cbfcefc92 | 774 | pas | Pascal | CAT/tests/13. custom tests/algorithms/crypto/CRC/crc16_kermit.pas | SkliarOleksandr/NextPascal | 4dc26abba6613f64c0e6b5864b3348711eb9617a | [
"Apache-2.0"
]
| 19 | 2018-10-22T23:45:31.000Z | 2021-05-16T00:06:49.000Z | CAT/tests/13. custom tests/algorithms/crypto/CRC/crc16_kermit.pas | SkliarOleksandr/NextPascal | 4dc26abba6613f64c0e6b5864b3348711eb9617a | [
"Apache-2.0"
]
| 1 | 2019-06-01T06:17:08.000Z | 2019-12-28T10:27:42.000Z | CAT/tests/13. custom tests/algorithms/crypto/CRC/crc16_kermit.pas | SkliarOleksandr/NextPascal | 4dc26abba6613f64c0e6b5864b3348711eb9617a | [
"Apache-2.0"
]
| 6 | 2018-08-30T05:16:21.000Z | 2021-05-12T20:25:43.000Z | unit crc16_kermit;
interface
implementation
type PByte = ^UInt8;
function Crc16Kermit(Data: PByte; Length: UInt16): UInt16;
var
i: Int32;
Val : UInt16;
CRC : UInt16;
LB, HB: UInt8;
Begin
CRC := 0;
for i := 0 to Length - 1 do
begin
Val := (((Data + i)^ XOR CRC) AND $0F) * $1081;
CRC := CRC SHR 4;
CRC := CRC XOR Val;
LB := (CRC and $FF);
Val := ((((Data + i)^ SHR 4) XOR LB) AND $0F);
CRC := CRC SHR 4;
CRC := CRC XOR (Val * $1081);
end;
LB := (CRC and $FF);
HB := (CRC shr 8);
Result := (LB SHL 8) OR HB;
end;
var Data: Int64;
CRC: UInt16;
procedure Test;
begin
Data := $AABBCCDD99887766;
CRC := Crc16Kermit(PByte(@Data), 8);
end;
initialization
Test();
finalization
Assert(CRC = 14171);
end. | 16.826087 | 58 | 0.571059 |
47a186de02e049c2f012fb2507b00e231faab1ae | 424 | dfm | Pascal | windows/src/buildtools/genkmnp/testkbd.dfm | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 1 | 2021-03-08T09:31:47.000Z | 2021-03-08T09:31:47.000Z | windows/src/buildtools/genkmnp/testkbd.dfm | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| null | null | null | windows/src/buildtools/genkmnp/testkbd.dfm | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| null | null | null | object Form2: TForm2
Left = 192
Top = 107
Width = 783
Height = 540
Caption = 'Form2'
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
object Label1: TLabel
Left = 112
Top = 88
Width = 32
Height = 13
Caption = 'Label1'
end
end
| 17.666667 | 32 | 0.636792 |
47664077a4989661a2a4697386448a3cb03349e1 | 225,941 | pas | Pascal | references/embarcadero/rio/10_3_2/patched/fmx/FMX.Platform.Mac.pas | marlonnardi/alcinoe | 5e14b2fca7adcc38e483771055b5623501433334 | [
"Apache-2.0"
]
| 1 | 2019-01-27T14:00:28.000Z | 2019-01-27T14:00:28.000Z | references/embarcadero/rio/10_3_2/patched/fmx/FMX.Platform.Mac.pas | marlonnardi/alcinoe | 5e14b2fca7adcc38e483771055b5623501433334 | [
"Apache-2.0"
]
| 2 | 2019-06-23T00:02:43.000Z | 2019-10-12T22:39:28.000Z | references/embarcadero/rio/10_3_2/patched/fmx/FMX.Platform.Mac.pas | marlonnardi/alcinoe | 5e14b2fca7adcc38e483771055b5623501433334 | [
"Apache-2.0"
]
| null | null | null | {*******************************************************}
{ }
{ Delphi FireMonkey Platform }
{ }
{ Copyright(c) 2011-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit FMX.Platform.Mac;
interface
{$SCOPEDENUMS ON}
uses
System.TypInfo,
Macapi.ObjectiveC, Macapi.CocoaTypes, System.Types, System.UITypes, System.Classes, System.Generics.Collections,
Macapi.Foundation, Macapi.AppKit, FMX.Types, FMX.Platform, FMX.Text, FMX.Forms, FMX.Controls, FMX.Graphics;
type
TMacWindowHandle = class(TWindowHandle)
private class var
FWindowHandles: TList<TMacWindowHandle>;
private
FHandle: TOCLocal;
FBufferSize: TSize;
FBuffer: CGContextRef;
FBits: Pointer;
FTrackingArea: NSTrackingArea;
function GetWindow: NSWindow;
function GetView: NSView;
function GetForm: TCommonCustomForm;
procedure UpdateLayer(const Ctx: CGContextRef);
procedure CreateBuffer;
procedure FreeBuffer;
protected
function GetScale: Single; override;
public
constructor Create(const AHandle: TOCLocal);
destructor Destroy; override;
class function FindForm(const window: NSWindow): TCommonCustomForm;
property Wnd: NSWindow read GetWindow;
property View: NSView read GetView;
property TrackingArea: NSTrackingArea read FTrackingArea;
property Form: TCommonCustomForm read GetForm;
property Handle: TOCLocal read FHandle;
end;
{ TFMXAlertDelegate }
AlertDelegate = interface(NSObject)
['{F7AE5530-0A75-4303-8F62-7ABCEB6EF8FE}']
procedure alertDidEndSelector(alert: Pointer; returnCode: NSInteger; contextInfo: Pointer); cdecl;
end;
TFMXAlertDelegate = class(TOCLocal, NSAlertDelegate)
public
Modal: Boolean;
Results: array of Integer;
Result: Integer;
constructor Create; //Needed to build this object correctly.
function GetObjectID: Pointer;
function GetObjectiveCClass: PTypeInfo; override;
procedure alertDidEndSelector(alert: Pointer; returnCode: NSInteger; contextInfo: Pointer); cdecl;
end;
function WindowHandleToPlatform(const AHandle: TWindowHandle): TMacWindowHandle;
procedure RegisterCorePlatformServices;
procedure UnregisterCorePlatformServices;
function PlatformHookObserverCallback(CancelIdle: Boolean; Mask: NSUInteger = NSAnyEventMask): Boolean;
procedure PlatformAlertCreated;
procedure PlatformAlertReleased;
function PlatformAlertCount: Integer;
implementation
uses
System.RTLConsts, System.SysUtils, System.SyncObjs, System.Rtti, System.Math, System.Messaging,
System.RegularExpressions, System.StrUtils, System.Variants, System.IOUtils, Macapi.QuartzCore,
Macapi.KeyCodes, Macapi.CoreGraphics, Macapi.ObjCRuntime, Macapi.CoreFoundation, Macapi.Helpers, Macapi.Mach,
FMX.Consts, FMX.Dialogs, FMX.Dialogs.Mac, FMX.Menus, FMX.Canvas.Mac, FMX.Canvas.GPU, FMX.Context.Mac, FMX.KeyMapping,
FMX.ExtCtrls, FMX.Gestures, FMX.Gestures.Mac, FMX.Styles, FMX.TextLayout, FMX.Types3D, FMX.Controls.Mac,
FMX.Forms.Border.Mac, FMX.Helpers.Mac, FMX.Surfaces;
const
IntervalPress = 1/SecsPerDay/10;
WaitMessageTimeout = 0.1;
SSpotlightFeature = 'Help';
type
{$M+}
TEventKind = (Other, Key, MouseOther, MouseDown, MouseUp, MouseMove);
TEventRec = record
Event: NSEvent;
EventKind: TEventKind;
Window: NSWindow;
View: NSView;
Form: TCommonCustomForm;
FormMousePos: TPointF;
ScreenMousePos: TPointF;
Shift: TShiftState;
Button: TMouseButton;
MouseInContent: Boolean;
HandledInApp: Boolean;
constructor Create(const AEvent: NSEvent);
end;
function IsPopupForm(const AForm: TCommonCustomForm): Boolean;
begin
Result := (AForm <> nil) and ((AForm.FormStyle = TFormStyle.Popup) or (AForm.Owner is TPopup) or (AForm is TCustomPopupForm));
end;
{ TEventRec }
constructor TEventRec.Create(const AEvent: NSEvent);
var
AutoReleasePool: NSAutoreleasePool;
LMousePoint, LScreenPos: NSPoint;
R: TRectF;
begin
// In this record contains the existing information about event.
FillChar(Self, SizeOf(Self), 0);
AutoReleasePool := TNSAutoreleasePool.Create;
try
Self.Event := AEvent;
{$REGION 'event kind'}
case AEvent.&type of
NSKeyDown, NSKeyUp:
Self.EventKind := TEventKind.Key;
NSLeftMouseDown, NSRightMouseDown, NSOtherMouseDown:
Self.EventKind := TEventKind.MouseDown;
NSLeftMouseUp, NSRightMouseUp, NSOtherMouseUp:
Self.EventKind := TEventKind.MouseUp;
NSMouseMoved, NSLeftMouseDragged, NSRightMouseDragged, NSOtherMouseDragged:
Self.EventKind := TEventKind.MouseMove;
NSMouseEntered, NSMouseExited, NSScrollWheel:
Self.EventKind := TEventKind.MouseOther;
end;
{$ENDREGION}
{$REGION 'shift state'}
Self.Shift := ShiftStateFromModFlags(AEvent.modifierFlags);
case AEvent.&type of
NSLeftMouseDown, NSLeftMouseUp, NSLeftMouseDragged:
Self.Shift := Self.Shift + [ssLeft];
NSRightMouseDown, NSRightMouseUp, NSRightMouseDragged:
Self.Shift := Self.Shift + [ssRight];
NSOtherMouseDown, NSOtherMouseUp, NSOtherMouseDragged:
Self.Shift := Self.Shift + [ssMiddle];
NSScrollWheel:
if Abs(AEvent.deltaX) > Abs(AEvent.deltaY) then
Self.Shift := Self.Shift + [ssHorizontal];
end;
if (Self.EventKind = TEventKind.MouseDown) and (AEvent.clickCount > 1) then
Self.Shift := Self.Shift + [ssDouble];
{$ENDREGION}
{$REGION 'mouse button'}
case AEvent.&type of
NSLeftMouseDown, NSLeftMouseUp:
Self.Button := TMouseButton.mbLeft;
NSRightMouseDown, NSRightMouseUp:
Self.Button := TMouseButton.mbRight;
NSOtherMouseDown, NSOtherMouseUp:
Self.Button := TMouseButton.mbMiddle;
end;
{$ENDREGION}
{$REGION 'system objects, Form, mouse coodinates'}
LMousePoint := AEvent.locationInWindow;
LScreenPos := LMousePoint;
if AEvent.window <> nil then
begin
Self.View := TNSView.Wrap(AEvent.window.contentView);
Self.Window := AEvent.window;
Self.Form := TMacWindowHandle.FindForm(AEvent.window);
Self.FormMousePos := TPointF.Create(LMousePoint.X, Self.View.bounds.size.height - LMousePoint.y);
LScreenPos := AEvent.window.convertBaseToScreen(LMousePoint);
end;
Self.ScreenMousePos := TPointF.Create(LScreenPos.X, MainScreenHeight - LScreenPos.y);
{$ENDREGION}
{$REGION 'test cursor pos in form'}
if Self.Form <> nil then
begin
if Self.Form is TCustomPopupForm then
Self.MouseInContent := TCustomPopupForm(Self.Form).ScreenContentRect.Contains(Self.ScreenMousePos)
else
begin
R := TRectF.Create(0, 0, Self.View.bounds.size.width, Self.View.bounds.size.height);
Self.MouseInContent := R.Contains(Self.FormMousePos);
end;
end;
{$ENDREGION}
finally
AutoReleasePool.release;
end;
end;
type
TOpenMenuItem = class(TMenuItem);
TOpenCustomForm = class(TCommonCustomForm);
THookEvent = procedure (const EventRec: TEventRec; var CancelIdle, CancelDefaultAction: Boolean) of object;
IFMXApplicationDelegate = interface(NSApplicationDelegate)
['{A54E08CA-77CC-4F22-B6D9-833DD6AB696D}']
procedure onMenuClicked(sender: NSMenuItem); cdecl;
end;
TFMXApplicationDelegate = class(TOCLocal, IFMXApplicationDelegate)
public
function applicationShouldTerminate(Notification: NSNotification): NSInteger; cdecl;
procedure applicationWillTerminate(Notification: NSNotification); cdecl;
procedure applicationDidFinishLaunching(Notification: NSNotification); cdecl;
function applicationDockMenu(sender: NSApplication): NSMenu; cdecl;
procedure applicationDidHide(Notification: NSNotification); cdecl;
procedure applicationDidUnhide(Notification: NSNotification); cdecl;
procedure onMenuClicked(sender: NSMenuItem); cdecl;
end;
TFMXMenuDelegate = class(TOCLocal, NSMenuDelegate)
public class var
FFMXMenuDictionary: TDictionary<Pointer, TMenuItem>;
public
class procedure RegisterMenu(const ALocalId: Pointer; const AMenuItem: TMenuItem);
class procedure UnregisterMenu(const ALocalId: Pointer);
class function GetMenuItem(const ALocalId: Pointer): TMenuItem;
procedure menuNeedsUpdate(menu: NSMenu); cdecl;
function numberOfItemsInMenu(menu: NSMenu): NSInteger; cdecl;
function menu(menu: NSMenu; updateItem: NSMenuItem; atIndex: NSInteger; shouldCancel: Boolean): Boolean; overload; cdecl;
procedure menu(menu: NSMenu; willHighlightItem: NSMenuItem); overload; cdecl;
function menuHasKeyEquivalent(menu: NSMenu; forEvent: NSEvent; target: Pointer; action: SEL): Boolean; cdecl;
procedure menuWillOpen(menu: NSMenu); cdecl;
procedure menuDidClose(menu: NSMenu); cdecl;
function confinementRectForMenu(menu: NSMenu; onScreen: NSScreen): NSRect; cdecl;
end;
{ TPlatformCocoa }
TCustomCursor = class
private
FData: NSData;
FImage: NSImage;
FCursor: NSCursor;
public
constructor Create(const ABytes: Pointer; const ALength: NSUInteger);
destructor Destroy; override;
property Cursor: NSCursor read FCursor;
end;
TPlatformCocoa = class(TInterfacedObject, IFMXApplicationService, IFMXSystemFontService, IFMXTimerService,
IFMXWindowService, IFMXMenuService, IFMXDragDropService, IFMXCursorService, IFMXMouseService,
IFMXScreenService, IFMXLocaleService, IFMXDialogService, IFMXTextService, IFMXContextService, IFMXCanvasService,
IFMXWindowBorderService, IFMXHideAppService, IFMXSystemInformationService, IFMXLoggingService,
IFMXFullScreenWindowService, IFMXListingService, IFMXSaveStateService, IFMXDeviceMetricsService,
IFMXDefaultMetricsService, IFMXKeyMappingService)
private const
DefaultMacFontSize = 13;
private type
TCurrentMenu = (System, Default, Main);
TMainMenuState = (Empty, Created, Recreated, Recreating);
private
NSApp: NSApplication;
FFMXApplicationDelegate: TFMXApplicationDelegate;
FFMXMenuDelegate: NSMenuDelegate;
FRunLoopObserver: CFRunLoopObserverRef;
FAppKitMod: HMODULE;
FHandleCounter: TFmxHandle;
FObjectiveCMap: TDictionary<TFmxHandle, IObjectiveC>;
FNSHandles: TList<TFmxHandle>;
FTimers: TList<TFmxHandle>;
FModalStack: TStack<TCommonCustomForm>;
FAlertCount: Integer;
FRestartModal: Boolean;
FMenuBar: NSMenu;
FMainMenu: NSMenu;
FAppleMenu: NSMenu;
FWindowMenu: NSMenu;
FInDestroyMenuItem: Boolean;
FDefaultMenu: TCurrentMenu;
FClassHookCount: Integer;
FTerminating: Boolean;
FRunning: Boolean;
FCursor: TCursor;
FCustomCursor: TCustomCursor;
FDisableClosePopups: Boolean;
FCanSetState: Boolean;
FPerformKeyExecuted: Boolean;
FHookEvent: THookEvent;
FMenuStack: TStack<IMenuView>;
FTitle: string;
FSaveStateStoragePath: string;
FMainMenuState: TMainMenuState;
FStoredButtons: NSUInteger;
FDefaultFontName: string;
FKeyMapping: TKeyMapping;
FHideUnhideApp: Boolean;
function NewFmxHandle: TFmxHandle;
procedure ValidateHandle(FmxHandle: TFmxHandle);
function HandleToObjC(FmxHandle: TFmxHandle): IObjectiveC; overload;
function HandleToObjC(FmxHandle: TFmxHandle; const IID: TGUID; out Intf): Boolean; overload;
function AllocHandle(const Objc: IObjectiveC): TFmxHandle;
procedure DeleteHandle(FmxHandle: TFmxHandle);
function CreateChildMenuItems(AChildMenu: IItemsContainer; AParentMenu: NSMenu): Boolean;
procedure DoReleaseWindow(AForm: TCommonCustomForm);
procedure RemoveChildHandles(const AMenu: IItemsContainer);
procedure HookFrame(const NSWin: NSWindow);
procedure UnHookFrame(const NSWin: NSWindow);
procedure ClearNSHandles;
function NewNSMenu(const Text: string): NSMenu;
function KeyProc(const Sender: TObject; const Form: TCommonCustomForm; const event: NSEvent; const IsInputContext,
IsDown: Boolean): Boolean;
procedure MouseEvent(const EventRec: TEventRec); overload;
procedure MouseEvent(const Event: NSevent); overload;
procedure ClearMenuItems;
procedure CreateMenu;
procedure CreateAppleMenu;
procedure UpdateAppleMenu(const ASubItems: IItemsContainer);
{ IFMXListingService }
function GetListingHeaderBehaviors: TListingHeaderBehaviors;
function GetListingSearchFeatures: TListingSearchFeatures;
function GetListingTransitionFeatures: TListingTransitionFeatures;
function GetListingEditModeFeatures: TListingEditModeFeatures;
function IFMXListingService.GetHeaderBehaviors = GetListingHeaderBehaviors;
function IFMXListingService.GetSearchFeatures = GetListingSearchFeatures;
function IFMXListingService.GetTransitionFeatures = GetListingTransitionFeatures;
function IFMXListingService.GetEditModeFeatures = GetListingEditModeFeatures;
{ IFMXSaveStateService }
function GetSaveStateFileName(const ABlockName: string): string;
function GetSaveStateBlock(const ABlockName: string; const ABlockData: TStream): Boolean;
function SetSaveStateBlock(const ABlockName: string; const ABlockData: TStream): Boolean;
function GetSaveStateStoragePath: string;
procedure SetSaveStateStoragePath(const ANewPath: string);
function GetSaveStateNotifications: Boolean;
function IFMXSaveStateService.GetBlock = GetSaveStateBlock;
function IFMXSaveStateService.SetBlock = SetSaveStateBlock;
function IFMXSaveStateService.GetStoragePath = GetSaveStateStoragePath;
procedure IFMXSaveStateService.SetStoragePath = SetSaveStateStoragePath;
function IFMXSaveStateService.GetNotifications = GetSaveStateNotifications;
{ IFMXDeviceMetricsService }
function GetDisplayMetrics: TDeviceDisplayMetrics;
procedure WakeMainThread(Sender: TObject);
function HookObserverCallback(CancelIdle: Boolean; Mask: NSUInteger = NSAnyEventMask): Boolean;
procedure MenuLoopEvent(const EventRec: TEventRec; var CancelIdle, CancelDefaultAction: Boolean);
property HookEvent: THookEvent read FHookEvent write FHookEvent;
function FindFormAtScreenPos(var AForm: TCommonCustomForm; const ScreenMousePos: TPointF): Boolean;
function ShowContextMenu(const AForm: TCommonCustomForm; const AScreenMousePos: TPointF): Boolean;
{ IFMXKeyMappingService }
/// <summary>Registers a platform key as the given virtual key.</summary>
function RegisterKeyMapping(const PlatformKey, VirtualKey: Word; const KeyKind: TKeyKind): Boolean;
/// <summary>Unegisters a platform key as the given virtual key.</summary>
function UnregisterKeyMapping(const PlatformKey: Word): Boolean;
/// <summary>Obtains the virtual key from a given platform key.</summary>
function PlatformKeyToVirtualKey(const PlatformKey: Word; var KeyKind: TKeyKind): Word;
/// <summary>Obtains the platform key from a given virtual key.</summary>
function VirtualKeyToPlatformKey(const VirtualKey: Word): Word;
//Methods for alert creatinon and destruction tracking
procedure AlertCreated;
procedure AlertReleased;
function AlertCount: Integer;
public
constructor Create;
destructor Destroy; override;
function DefaultAction(Key: Char; Shift: TShiftState): boolean;
class function ClosePopupForms: Boolean;
class function PrepareClosePopups(const SaveForm: TCommonCustomForm): Boolean;
{ IFMXApplicationService }
procedure Run;
function HandleMessage: Boolean;
procedure WaitMessage;
function GetDefaultTitle: string;
function GetTitle: string;
procedure SetTitle(const Value: string);
function GetVersionString: string;
function Terminating: Boolean;
function Running: Boolean;
procedure Terminate;
{ IFMXHideAppService }
function GetHidden: Boolean;
procedure SetHidden(const Value: boolean);
procedure HideOthers;
{ IFMXSystemFontService }
function GetDefaultFontFamilyName: string;
function GetDefaultFontSize: Single;
{ IFMXTimerService }
function CreateTimer(Interval: Integer; TimerFunc: TTimerProc): TFmxHandle;
function DestroyTimer(Timer: TFmxHandle): Boolean;
procedure DestroyTimers;
function GetTick: Double;
{ IFMXWindowService }
function FindForm(const AHandle: TWindowHandle): TCommonCustomForm;
function CreateWindow(const AForm: TCommonCustomForm): TWindowHandle;
procedure DestroyWindow(const AForm: TCommonCustomForm);
procedure ReleaseWindow(const AForm: TCommonCustomForm);
procedure ShowWindow(const AForm: TCommonCustomForm);
procedure HideWindow(const AForm: TCommonCustomForm);
procedure BringToFront(const AForm: TCommonCustomForm);
procedure SendToBack(const AForm: TCommonCustomForm);
procedure Activate(const AForm: TCommonCustomForm);
function ShowWindowModal(const AForm: TCommonCustomForm): TModalResult;
function CanShowModal: Boolean;
procedure InvalidateWindowRect(const AForm: TCommonCustomForm; R: TRectF);
procedure InvalidateImmediately(const AForm: TCommonCustomForm);
procedure SetWindowRect(const AForm: TCommonCustomForm; ARect: TRectF);
function GetWindowRect(const AForm: TCommonCustomForm): TRectF;
function GetClientSize(const AForm: TCommonCustomForm): TPointF;
procedure SetClientSize(const AForm: TCommonCustomForm; const ASize: TPointF);
procedure SetWindowCaption(const AForm: TCommonCustomForm; const ACaption: string);
procedure SetCapture(const AForm: TCommonCustomForm);
procedure SetWindowState(const AForm: TCommonCustomForm; const AState: TWindowState);
procedure ReleaseCapture(const AForm: TCommonCustomForm);
function ClientToScreen(const AForm: TCommonCustomForm; const Point: TPointF): TPointF;
function ScreenToClient(const AForm: TCommonCustomForm; const Point: TPointF): TPointF;
function GetWindowScale(const AForm: TCommonCustomForm): Single;
{ IFMXWindowBorderService }
function CreateWindowBorder(const AForm: TCommonCustomForm): TWindowBorder;
{ IFMXMenuService }
procedure StartMenuLoop(const AView: IMenuView);
function ShortCutToText(ShortCut: TShortCut): string;
procedure ShortCutToKey(ShortCut: TShortCut; var Key: Word; var Shift: TShiftState);
function TextToShortCut(Text: string): Integer;
procedure CreateOSMenu(AForm: TCommonCustomForm; const AMenu: IItemsContainer);
procedure UpdateMenuItem(const AItem: IItemsContainer; AChange: TMenuItemChanges);
procedure DestroyMenuItem(const AItem: IItemsContainer);
function IsMenuBarOnWindowBorder: Boolean;
procedure UpdateMenuBar;
{ IFMXDragDropService }
procedure BeginDragDrop(AForm: TCommonCustomForm; const Data: TDragObject; ABitmap: TBitmap);
{ IFMXCursorService }
procedure SetCursor(const ACursor: TCursor);
function GetCursor: TCursor;
{ IFMXMouseService }
function GetMousePos: TPointF;
{ IFMXScreenService }
function GetScreenSize: TPointF;
function GetScreenScale: Single;
function GetScreenOrientation: TScreenOrientation;
procedure SetScreenOrientation(AOrientations: TScreenOrientations);
{ IFMXLocaleService }
function GetCurrentLangID: string;
function GetLocaleFirstDayOfWeek: string;
function GetFirstWeekday: Byte;
{ IFMXDialogService }
function DialogOpenFiles(const ADialog: TOpenDialog; var AFiles: TStrings; AType: TDialogType): Boolean;
function DialogPrint(var ACollate, APrintToFile: Boolean;
var AFromPage, AToPage, ACopies: Integer; AMinPage, AMaxPage: Integer; var APrintRange: TPrintRange;
AOptions: TPrintDialogOptions): Boolean;
function PageSetupGetDefaults(var AMargin, AMinMargin: TRect; var APaperSize: TPointF;
AUnits: TPageMeasureUnits; AOptions: TPageSetupDialogOptions): Boolean;
function DialogPageSetup(var AMargin, AMinMargin :TRect; var APaperSize: TPointF;
var AUnits: TPageMeasureUnits; AOptions: TPageSetupDialogOptions): Boolean;
function DialogSaveFiles(const ADialog: TOpenDialog; var AFiles: TStrings): Boolean;
function DialogPrinterSetup: Boolean;
function MessageDialog(const AMessage: string; const ADialogType: TMsgDlgType; const AButtons: TMsgDlgButtons;
const ADefaultButton: TMsgDlgBtn; const AX, AY: Integer; const AHelpCtx: THelpContext;
const AHelpFileName: string): Integer; overload;
procedure MessageDialog(const AMessage: string; const ADialogType: TMsgDlgType; const AButtons: TMsgDlgButtons;
const ADefaultButton: TMsgDlgBtn; const AX, AY: Integer; const AHelpCtx: THelpContext; const AHelpFileName: string;
const ACloseDialogProc: TInputCloseDialogProc); overload;
function InputQuery(const ACaption: string; const APrompts: array of string;
var AValues: array of string; const ACloseQueryFunc: TInputCloseQueryFunc = nil): Boolean; overload;
procedure InputQuery(const ACaption: string; const APrompts, ADefaultValues: array of string;
const ACloseQueryProc: TInputCloseQueryProc); overload;
{ IFMXTextService }
function GetTextServiceClass: TTextServiceClass;
{ IFMXContextService }
procedure RegisterContextClasses;
procedure UnregisterContextClasses;
{ IFMXCanvasService }
procedure RegisterCanvasClasses;
procedure UnregisterCanvasClasses;
{ IFMXSystemInformationService }
function GetScrollingBehaviour: TScrollingBehaviours;
function GetMinScrollThumbSize: Single;
function GetCaretWidth: Integer;
function GetMenuShowDelay: Integer;
{ IFMXLoggingService }
procedure Log(const AFormat: string; const AParams: array of const);
{ IFMXWindowService }
procedure SetFullScreen(const AForm: TCommonCustomForm; const AValue: Boolean);
function GetFullScreen(const AForm: TCommonCustomForm): Boolean;
procedure SetShowFullScreenIcon(const AForm: TCommonCustomForm; const AValue: Boolean);
{ IFMXDefaultMetricsService }
function SupportsDefaultSize(const AComponent: TComponentKind): Boolean;
function GetDefaultSize(const AComponent: TComponentKind): TSize;
end;
TMultiDisplayMac = class (TInterfacedObject, IFMXMultiDisplayService)
private
FDisplayCount: Integer;
FWorkAreaRect: TRect;
FDesktopRect: TRect;
FDisplayList: TList<TDisplay>;
function NSRectToRect(const ANSRect: NSRect): TRect;
procedure UpdateDisplays;
function FindDisplay(const screen: NSScreen): TDisplay;
public
destructor Destroy; override;
procedure UpdateDisplayInformation;
function GetDisplayCount: Integer;
function GetDesktopCenterRect(const Size: TSize): TRect;
function GetWorkAreaRect: TRect;
function GetDesktopRect: TRect;
function GetDisplay(const Index: Integer): TDisplay;
function DisplayFromWindow(const Handle: TWindowHandle): TDisplay;
function DisplayFromPoint(const Handle: TWindowHandle; const Point: TPoint): TDisplay;
end;
{$M+}
TFMXWindow = class;
TTextServiceCocoa = class;
TFMXViewBase = class(TOCLocal, NSTextInputClient)
private
FOwner: TFMXWindow;
FShift: TShiftState;
FMarkedRange: NSRange;
FBackingStore: NSMutableAttributedString;//NSTextStorage;
FSelectedRange: NSRange;
FGestureControl: TComponent;
FCurrentGestureEngine: TPlatformGestureEngine;
FSwipePoint: TPointF;
FEventInfo: TGestureEventInfo;
private
procedure SetFirstGesturePoint(const AnEvent: NSEvent);
procedure SetTrackGesturePoint(const AnEvent: NSEvent);
function GetGestureControlUnderMouse(const APoint: TPointF): IGestureControl;
function GetGestureEngineUnderMouse(const APoint: TPointF): TPlatformGestureEngine;
procedure ReleaseGestureEngine;
procedure DiscardGestureEngine;
protected
function GetNativeView: NSView;
public
constructor Create(const AOwner: TFMXWindow);
destructor Destroy; override;
function acceptsFirstResponder: Boolean; cdecl;
function becomeFirstResponder: Boolean; cdecl;
function resignFirstResponder: Boolean; cdecl;
procedure drawRect(dirtyRect: NSRect); cdecl;
procedure keyDown(event: NSEvent); cdecl;
procedure keyUp(event: NSEvent); cdecl;
procedure scrollWheel(event: NSEvent); cdecl;
{ mouse }
procedure mouseMoved(theEvent: NSEvent); cdecl;
procedure mouseDown(theEvent: NSEvent); cdecl;
procedure mouseUp(theEvent: NSEvent); cdecl;
procedure mouseDragged(theEvent: NSEvent); cdecl;
procedure rightMouseDown(theEvent: NSEvent); cdecl;
procedure rightMouseUp(theEvent: NSEvent); cdecl;
procedure rightMouseDragged(theEvent: NSEvent); cdecl;
procedure otherMouseDown(theEvent: NSEvent); cdecl;
procedure otherMouseUp(theEvent: NSEvent); cdecl;
procedure otherMouseDragged(theEvent: NSEvent); cdecl;
{Touch and Gestures}
procedure magnifyWithEvent(event: NSEvent); cdecl;
procedure rotateWithEvent(event: NSEvent); cdecl;
procedure swipeWithEvent(event: NSEvent); cdecl;
procedure touchesBeganWithEvent(event: NSEvent); cdecl;
procedure touchesCancelledWithEvent(event: NSEvent); cdecl;
procedure touchesEndedWithEvent(event: NSEvent); cdecl;
procedure touchesMovedWithEvent(event: NSEvent); cdecl;
{ NSTextInputClient }
procedure insertText(text: Pointer {NSString}; replacementRange: NSRange); cdecl;
procedure doCommandBySelector(selector: SEL); cdecl;
procedure setMarkedText(text: Pointer {NSString}; selectedRange: NSRange; replacementRange: NSRange); cdecl;
procedure unMarkText; cdecl;
function selectedRange: NSRange; cdecl;
function markedRange: NSRange; cdecl;
function hasMarkedText: Boolean; cdecl;
function attributedSubstringForProposedRange(aRange: NSRange; actualRange: PNSRange): NSAttributedString; cdecl;
function validAttributesForMarkedText: Pointer {NSArray}; cdecl;
function firstRectForCharacterRange(aRange: NSRange; actualRange: PNSRange): NSRect; cdecl;
function characterIndexForPoint(aPoint: NSPoint): NSUInteger; cdecl;
function attributedString: NSAttributedString; cdecl;
function fractionOfDistanceThroughGlyphForPoint(aPoint: NSPoint): CGFloat; cdecl;
function baselineDeltaForCharacterAtIndex(anIndex: NSUInteger): CGFloat; cdecl;
function windowLevel: NSInteger; cdecl;
function drawsVerticallyForCharacterAtIndex(charIndex: NSUInteger): Boolean; cdecl;
{ Text Service }
function FocusedTextService: TTextServiceCocoa;
procedure UpdateTextServiceControl;
{ Notifications }
procedure frameChanged(notification: NSNotification); cdecl;
{ OpenGL }
procedure lockFocus; cdecl;
procedure surfaceNeedsUpdate(notification: NSNotification); cdecl;
{ }
property NativeView: NSView read GetNativeView;
property Owner: TFMXWindow read FOwner;
end;
FMXView = interface(NSView)
['{56304E8C-08A2-4386-B116-D4E364FDC2AD}']
function acceptsFirstResponder: Boolean; cdecl;
function becomeFirstResponder: Boolean; cdecl;
function resignFirstResponder: Boolean; cdecl;
procedure drawRect(dirtyRect: NSRect); cdecl;
procedure keyDown(event: NSEvent); cdecl;
procedure keyUp(event: NSEvent); cdecl;
procedure scrollWheel(event: NSEvent); cdecl;
procedure lockFocus; cdecl;
procedure surfaceNeedsUpdate(notification: NSNotification); cdecl;
{ mouse }
procedure mouseMoved(theEvent: NSEvent); cdecl;
procedure mouseDown(theEvent: NSEvent); cdecl;
procedure mouseUp(theEvent: NSEvent); cdecl;
procedure mouseDragged(theEvent: NSEvent); cdecl;
procedure rightMouseDown(theEvent: NSEvent); cdecl;
procedure rightMouseUp(theEvent: NSEvent); cdecl;
procedure rightMouseDragged(theEvent: NSEvent); cdecl;
procedure otherMouseDown(theEvent: NSEvent); cdecl;
procedure otherMouseUp(theEvent: NSEvent); cdecl;
procedure otherMouseDragged(theEvent: NSEvent); cdecl;
{ Touch and Gestures }
procedure magnifyWithEvent(event: NSEvent); cdecl;
procedure rotateWithEvent(event: NSEvent); cdecl;
procedure swipeWithEvent(event: NSEvent); cdecl;
procedure touchesBeganWithEvent(event: NSEvent); cdecl;
procedure touchesCancelledWithEvent(event: NSEvent); cdecl;
procedure touchesEndedWithEvent(event: NSEvent); cdecl;
procedure touchesMovedWithEvent(event: NSEvent); cdecl;
{ Notifications }
procedure frameChanged(notification: NSNotification); cdecl;
end;
TFMXView = class(TFMXViewBase, NSTextInputClient)
public
constructor Create(const AOwner: TFMXWindow; AFRameRect: NSRect);
destructor Destroy; override;
function GetObjectiveCClass: PTypeInfo; override;
end;
FMXWindow = interface(NSWindow)
['{A4C4B329-38C4-401F-8937-1C380801B1C8}']
function draggingEntered(Sender: Pointer): NSDragOperation; cdecl;
procedure draggingExited(Sender: Pointer {id}); cdecl;
function draggingUpdated(Sender: Pointer): NSDragOperation; cdecl;
function performDragOperation(Sender: Pointer): Boolean; cdecl;
function canBecomeKeyWindow: Boolean; cdecl;
function canBecomeMainWindow: Boolean; cdecl;
function acceptsFirstResponder: Boolean; cdecl;
function becomeFirstResponder: Boolean; cdecl;
function resignFirstResponder: Boolean; cdecl;
function performKeyEquivalent(event: NSEvent): Boolean; cdecl;
end;
TFMXWindow = class(TOCLocal) //(NSWindow)
private
FViewObj: TFMXViewBase;
FDelegate: NSWindowDelegate;
FDelayRelease: Boolean;
function CanActivate: Boolean; inline;
protected
function GetView: NSView;
procedure UpdateWindowState;
public
NeedUpdateShadow: Boolean;
Wnd: TCommonCustomForm;
LastEvent: NSEvent; // for DragNDrop
DragOperation: Integer;
function GetObjectiveCClass: PTypeInfo; override;
destructor Destroy; override;
function windowShouldClose(Sender: Pointer {id}): Boolean; cdecl;
procedure windowWillClose(notification: NSNotification); cdecl;
procedure windowDidBecomeKey(notification: NSNotification); cdecl;
procedure windowDidResignKey(notification: NSNotification); cdecl;
procedure windowDidResize(notification: NSNotification); cdecl;
procedure windowDidMiniaturize(notification: NSNotification); cdecl;
procedure windowDidDeminiaturize(notification: NSNotification); cdecl;
procedure windowDidEnterFullScreen(notification: NSNotification); cdecl;
procedure windowDidExitFullScreen(notification: NSNotification); cdecl;
procedure windowDidMove(notification: NSNotification); cdecl;
procedure windowDidChangeBackingProperties(notification: NSNotification); cdecl;
function draggingEntered(Sender: Pointer {NSDraggingInfo}): NSDragOperation; cdecl;
procedure draggingExited(Sender: Pointer {NSDraggingInfo} {id}); cdecl;
function draggingUpdated(Sender: Pointer {NSDraggingInfo}): NSDragOperation; cdecl;
function performDragOperation(Sender: Pointer {NSDraggingInfo}): Boolean; cdecl;
function acceptsFirstResponder: Boolean; cdecl;
function canBecomeKeyWindow: Boolean; cdecl;
function canBecomeMainWindow: Boolean; cdecl;
function becomeFirstResponder: Boolean; cdecl;
function resignFirstResponder: Boolean; cdecl;
function performKeyEquivalent(event: NSEvent): Boolean; cdecl;
property View: NSView read GetView;
end;
PFMXWindow = ^TFMXWindow;
{ TTextServiceCocoa }
TTextServiceCocoa = class(TTextService)
private
FCaretPosition: TPoint;
FText : string;
FMarkedText : string;
FImeMode: TImeMode;
protected
function GetText: string; override;
procedure SetText(const Value: string); override;
function GetCaretPosition: TPoint; override;
procedure SetCaretPosition(const Value: TPoint); override;
public
procedure InternalSetMarkedText( const AMarkedText: string ); override;
function InternalGetMarkedText: string; override;
procedure InternalStartIMEInput;
procedure InternalBreakIMEInput;
procedure InternalEndIMEInput;
function CombinedText: string; override;
function TargetClausePosition: TPoint; override;
procedure EnterControl(const FormHandle: TWindowHandle); override;
procedure ExitControl(const FormHandle: TWindowHandle); override;
procedure DrawSingleLine(const Canvas: TCanvas;
const ARect: TRectF; const FirstVisibleChar: Integer; const Font: TFont;
const AOpacity: Single; const Flags: TFillTextFlags; const ATextAlign: TTextAlign;
const AVTextAlign: TTextAlign = TTextAlign.Center;
const AWordWrap: Boolean = False); overload; override;
procedure DrawSingleLine(const Canvas: TCanvas;
const S: string;
const ARect: TRectF;
const Font: TFont;
const AOpacity: Single; const Flags: TFillTextFlags; const ATextAlign: TTextAlign;
const AVTextAlign: TTextAlign = TTextAlign.Center;
const AWordWrap: Boolean = False); overload; override;
function HasMarkedText: boolean; override;
function GetImeMode: TImeMode; override;
procedure SetImeMode(const Value: TImeMode); override;
private
FMarkedRange: NSRange;
FSelectedRange: NSRange;
public
constructor Create(const Owner: IControl; SupportMultiLine: Boolean); override;
destructor Destroy; override;
procedure SetMarkedRange(const Value: NSRange);
procedure SetSelectedRange(const Value: NSRange);
end;
function CGPointToPointF(const APoint: CGPoint): TPointF;
begin
Result.X := APoint.x;
Result.Y := APoint.y;
end;
function CGSizeToSizeF(const ASize: CGSize): TSizeF;
begin
Result.cx := ASize.width;
Result.cy := ASize.height;
end;
procedure SetMenuBitmap(const ANSMenuItem: NSMenuItem; const Item: TMenuItem);
var
Img: NSImage;
LBitmap: TBitmap;
begin
LBitmap := nil;
if (ANSMenuItem <> nil) and (Item <> nil) then
begin
if Item.Images <> nil then
LBitmap := Item.Images.Bitmap(TSizeF.Create(16, 16), Item.ImageIndex);
if LBitmap = nil then
LBitmap := Item.Bitmap;
if (LBitmap <> nil) and not LBitmap.IsEmpty then
Img := BitmapToMenuBitmap(LBitmap)
else
Img := nil;
try
ANSMenuItem.setImage(Img);
finally
if Img <> nil then
Img.release;
end;
end;
end;
var
PlatformCocoa: TPlatformCocoa;
MultiDisplayMac: TMultiDisplayMac;
procedure RegisterCorePlatformServices;
begin
PlatformCocoa := TPlatformCocoa.Create;
TPlatformServices.Current.AddPlatformService(IFMXApplicationService, PlatformCocoa);
TPlatformServices.Current.AddPlatformService(IFMXHideAppService, PlatformCocoa);
TPlatformServices.Current.AddPlatformService(IFMXSystemFontService, PlatformCocoa);
TPlatformServices.Current.AddPlatformService(IFMXTimerService, PlatformCocoa);
TPlatformServices.Current.AddPlatformService(IFMXWindowService, PlatformCocoa);
TPlatformServices.Current.AddPlatformService(IFMXMenuService, PlatformCocoa);
TPlatformServices.Current.AddPlatformService(IFMXDragDropService, PlatformCocoa);
TPlatformServices.Current.AddPlatformService(IFMXCursorService, PlatformCocoa);
TPlatformServices.Current.AddPlatformService(IFMXMouseService, PlatformCocoa);
TPlatformServices.Current.AddPlatformService(IFMXScreenService, PlatformCocoa);
TPlatformServices.Current.AddPlatformService(IFMXLocaleService, PlatformCocoa);
TPlatformServices.Current.AddPlatformService(IFMXDialogService, PlatformCocoa);
TPlatformServices.Current.AddPlatformService(IFMXTextService, PlatformCocoa);
TPlatformServices.Current.AddPlatformService(IFMXContextService, PlatformCocoa);
TPlatformServices.Current.AddPlatformService(IFMXCanvasService, PlatformCocoa);
TPlatformServices.Current.AddPlatformService(IFMXWindowBorderService, PlatformCocoa);
TPlatformServices.Current.AddPlatformService(IFMXSystemInformationService, PlatformCocoa);
TPlatformServices.Current.AddPlatformService(IFMXLoggingService, PlatformCocoa);
TPlatformServices.Current.AddPlatformService(IFMXFullScreenWindowService, PlatformCocoa);
TPlatformServices.Current.AddPlatformService(IFMXListingService, PlatformCocoa);
TPlatformServices.Current.AddPlatformService(IFMXSaveStateService, PlatformCocoa);
TPlatformServices.Current.AddPlatformService(IFMXDeviceMetricsService, PlatformCocoa);
TPlatformServices.Current.AddPlatformService(IFMXDefaultMetricsService, PlatformCocoa);
TPlatformServices.Current.AddPlatformService(IFMXKeyMappingService, PlatformCocoa);
MultiDisplayMac := TMultiDisplayMac.Create;
TPlatformServices.Current.AddPlatformService(IFMXMultiDisplayService, MultiDisplayMac);
end;
procedure UnregisterCorePlatformServices;
begin
end;
type
TMouseDownTimer = class (TTimer)
private
FEventRec: TEventRec;
procedure TimerProc(Sender: TObject);
protected
procedure DoOnTimer; override;
public
constructor Create(const EventRec: TEventRec); reintroduce;
end;
{ TMouseDownTimer }
constructor TMouseDownTimer.Create(const EventRec: TEventRec);
begin
inherited Create(EventRec.Form);
FEventRec := EventRec;
OnTimer := TimerProc;
Interval := 1;
Enabled := True;
end;
procedure TMouseDownTimer.DoOnTimer;
begin
Enabled := False;
if FEventRec.Form <> nil then
inherited;
Release;
end;
procedure TMouseDownTimer.TimerProc(Sender: TObject);
begin
TPlatformCocoa.PrepareClosePopups(nil);
TPlatformCocoa.ClosePopupForms;
if (ssRight in FEventRec.Shift) or ((ssLeft in FEventRec.Shift) and (ssCtrl in FEventRec.Shift)) then
begin
try
// Make sure the forms FMousePos has the correct coordinates for this event
FEventRec.Form.MouseDown(FEventRec.Button, FEventRec.Shift, FEventRec.FormMousePos.X, FEventRec.FormMousePos.Y);
PlatformCocoa.ShowContextMenu(FEventRec.Form, FEventRec.ScreenMousePos);
FEventRec.Form.MouseUp(FEventRec.Button, FEventRec.Shift, FEventRec.FormMousePos.X, FEventRec.FormMousePos.Y);
except
HandleException(FEventRec.Form);
end;
end;
end;
type
TKeyDownInfo = record
VKKeyCode: Integer;
Key: Word;
KeyChar: Char;
Initialized: Boolean;
end;
TDownKeyList = class(TList<TKeyDownInfo>)
strict private
class var FCurrent: TDownKeyList;
class function GetCurrent: TDownKeyList; static;
private
procedure AddKeyDown(const VKKeyCode: Integer);
procedure InitializeKeyDown(const Key: Word; const KeyChar: Char);
function RemoveKeyDown(const VKKeyCode: Integer; var Key: Word; var KeyChar: Char): Boolean;
class destructor UnInitialize;
class property Current: TDownKeyList read GetCurrent;
end;
{ TDownKeyList }
class function TDownKeyList.GetCurrent: TDownKeyList;
begin
if FCurrent = nil then
FCurrent := TDownKeyList.Create;
Result := FCurrent;
end;
class destructor TDownKeyList.UnInitialize;
begin
FCurrent.DisposeOf;
FCurrent := nil;
end;
procedure TDownKeyList.AddKeyDown(const VKKeyCode: Integer);
var
Info: TKeyDownInfo;
begin
if (VKKeyCode > 0) and ((Count = 0) or (Items[Count - 1].VKKeyCode <> VKKeyCode)) then
begin
FillChar(Info, SizeOf(Info), 0);
Info.VKKeyCode := VKKeyCode;
Add(Info);
end;
end;
procedure TDownKeyList.InitializeKeyDown(const Key: Word; const KeyChar: Char);
var
Info: TKeyDownInfo;
I, LastIndex: Integer;
begin
LastIndex := -1;
for I := Count - 1 downto 0 do
if not Items[I].Initialized then
LastIndex := I
else
Break;
if LastIndex >= 0 then
begin
Info := Items[LastIndex];
Info.Key := Key;
Info.KeyChar := KeyChar;
Info.Initialized := True;
Items[LastIndex] := Info;
for I := Count - 1 downto LastIndex + 1 do
Delete(I);
end;
end;
function TDownKeyList.RemoveKeyDown(const VKKeyCode: Integer; var Key: Word; var KeyChar: Char): Boolean;
var
Info: TKeyDownInfo;
I: Integer;
begin
Result := False;
if VKKeyCode > 0 then
for I := Count - 1 downto 0 do
begin
Info := Items[I];
if Info.VKKeyCode = VKKeyCode then
begin
Delete(I);
if not Result and Info.Initialized then
begin
Key := Info.Key;
KeyChar := Info.KeyChar;
Result := True;
end;
end;
end;
end;
procedure DoUpdateKey(var Key: Word;
var Ch: WideChar;
var Shift: TShiftState);
begin
//Zero out Key, if you pressed the usual character
if (Ch >= ' ') and
((Shift * [ssCtrl, ssCommand]) = []) then
begin
Shift := Shift - [ssAlt];
Key := 0;
end;
//Zero out Ch, if you pressed a keypad of the Alt, Ctrl, or Cmd
if (([ssAlt, ssCtrl, ssCommand] * Shift) <> []) and (Key > 0) then
Ch := #0;
end;
procedure DoKeyUp(const Sender: TObject;
Form: TCommonCustomForm;
Key: Word;
Ch: WideChar;
Shift: TShiftState);
begin
if Form <> nil then
try
if not TDownKeyList.Current.RemoveKeyDown(Key, Key, Ch) then
DoUpdateKey(Key, Ch, Shift);
Form.KeyUp(Key, Ch, Shift);
except
HandleException(Sender);
end;
end;
function DoKeyDown(const Sender: TObject;
const Form: TCommonCustomForm;
var Key: Word;
var Ch: WideChar;
Shift: TShiftState): boolean;
begin
TDownKeyList.Current.AddKeyDown(Key);
Result := False;
if Form <> nil then
try
DoUpdateKey(Key, Ch, Shift);
TDownKeyList.Current.InitializeKeyDown(Key, Ch);
Form.KeyDown(Key, Ch, Shift);
Result := Key = 0;
except
HandleException(Sender);
end;
end;
var
NSFMXPBoardtype: NSString;
function SendOSXMessage(const Sender: TObject; const OSXMessageClass: TOSXMessageClass;
const NSSender: NSObject): NSObject;
var
MessageObject: TOSXMessageObject;
begin
if OSXMessageClass = nil then
raise EArgumentNilException.Create(SArgumentNil);
MessageObject := TOSXMessageObject.Create(NSSender);
try
TMessageManager.DefaultManager.SendMessage(Sender, OSXMessageClass.Create(MessageObject, False), True);
Result := MessageObject.ReturnValue;
finally
MessageObject.Free;
end;
end;
{ TApplicationDelegate }
function TFMXApplicationDelegate.applicationDockMenu(sender: NSApplication): NSMenu;
var
ReturnValue: NSObject;
begin
ReturnValue := SendOSXMessage(Self, TApplicationDockMenuMessage, sender);
if ReturnValue <> nil then
Result := ReturnValue as NSMenu
else
Result := nil;
end;
function TFMXApplicationDelegate.applicationShouldTerminate(Notification: NSNotification): NSInteger;
begin
if (Application = nil) or (PlatformCocoa = nil) or PlatformCocoa.Terminating or
PlatformCocoa.DefaultAction('Q', [ssCommand]) then
Result := NSTerminateNow
else
Result := NSTerminateCancel;
end;
procedure TFMXApplicationDelegate.applicationDidHide(Notification: NSNotification);
begin
if (Application <> nil) and (Application.MainForm <> nil) and (not PlatformCocoa.FHideUnhideApp) then
begin
PlatformCocoa.FHideUnhideApp := True;
try
Application.MainForm.Visible := False;
finally
PlatformCocoa.FHideUnhideApp := False;
end;
end;
end;
procedure TFMXApplicationDelegate.applicationWillTerminate(Notification: NSNotification);
begin
SendOSXMessage(Self, TApplicationWillTerminateMessage, Notification);
end;
procedure TFMXApplicationDelegate.applicationDidUnhide(Notification: NSNotification);
begin
if (Application <> nil) and (Application.MainForm <> nil) and (not PlatformCocoa.FHideUnhideApp) then
begin
PlatformCocoa.FHideUnhideApp := True;
try
Application.MainForm.Visible := True;
finally
PlatformCocoa.FHideUnhideApp := False;
end;
end;
end;
procedure TFMXApplicationDelegate.onMenuClicked(sender: NSMenuItem);
begin
SendOSXMessage(Self, TApplicationMenuClickedMessage, sender);
end;
procedure TFMXApplicationDelegate.applicationDidFinishLaunching(Notification: NSNotification);
begin
SendOSXMessage(Self, TApplicationDidFinishLaunchingMessage, Notification);
end;
{ TPlatformCocoa }
constructor TPlatformCocoa.Create;
var
AutoReleasePool: NSAutoreleasePool;
begin
inherited;
FDefaultMenu := TCurrentMenu.System;
FAppKitMod := LoadLibrary('/System/Library/Frameworks/AppKit.framework/AppKit');
AutoReleasePool := TNSAutoreleasePool.Alloc;
try
AutoReleasePool.init;
NSApp := TNSApplication.Wrap(TNSApplication.OCClass.sharedApplication);
FFMXApplicationDelegate := TFMXApplicationDelegate.Create;
FFMXMenuDelegate := TFMXMenuDelegate.Create;
NSApp.setDelegate(IFMXApplicationDelegate(FFMXApplicationDelegate));
Application := TApplication.Create(nil);
FObjectiveCMap := TDictionary<TFmxHandle, IObjectiveC>.Create;
finally
AutoReleasePool.release;
end;
FNSHandles := TList<TFmxHandle>.Create;
FTimers := TList<TFmxHandle>.Create;
NSFMXPBoardtype := StrToNSStr('NSFMXPBoardtype' + UIntToStr(NativeUInt(Pointer(Application))));
FCanSetState := True;
FRunning := False;
FKeyMapping := TKeyMapping.Create;
System.Classes.WakeMainThread := WakeMainThread;
end;
destructor TPlatformCocoa.Destroy;
begin
DestroyTimers;
FTimers.Free;
ClearNSHandles;
FNSHandles.Free;
FreeAndNil(FMenuStack);
FreeAndNil(FModalStack);
FreeLibrary(FAppKitMod);
FreeAndNil(Application);
FObjectiveCMap.Free;
TFMXMenuDelegate.FFMXMenuDictionary.Free;
FKeyMapping.Free;
inherited;
end;
function TPlatformCocoa.DefaultAction(Key: Char; Shift: TShiftState): boolean;
var
Form: TCommonCustomForm;
begin
Result := False;
if (Shift = [ssCommand]) then
begin
if Key = 'Q' then
begin
try
if Application.MainForm <> nil then
begin
Application.MainForm.Close;
if not Terminating then
Exit;
end
else
begin
if Screen <> nil then
Screen.ActiveForm := nil;
Application.Terminate;
end;
except
HandleException(Application);
end;
Result := True;
end
else if Key = 'H' then
begin
SetHidden(not GetHidden);
Result := True;
end
else if (Key = 'W') and (Screen <> nil) then
begin
Form := Screen.ActiveForm;
if (Form <> nil) and (not (TFmxFormState.Modal in Form.FormState)) then
begin
Form.Close;
Result := True;
end;
end;
end;
if (Shift = [ssAlt, ssCommand]) and (Key = 'H') then
begin
HideOthers;
Result := True;
end;
end;
function VKeyFromKeyCode(AKeyCode: Word; Shift: TShiftState; var ISFNkey: boolean): Integer;
var
Kind: TKeyKind;
begin
Result:= PlatformCocoa.PlatformKeyToVirtualKey(AKeyCode, Kind);
ISFNkey := False;
ISFNkey := Kind = TKeyKind.Functional;
end;
function TPlatformCocoa.KeyProc(const Sender: TObject; const Form: TCommonCustomForm; const Event: NSEvent;
const IsInputContext, IsDown: Boolean): Boolean;
var
Shift: TShiftState;
Key: Word;
Ch: WideChar;
ShortcutKey: string;
I: Integer;
NSChars: NSString;
ISFNkey, IsModified: Boolean;
LHandle: TMacWindowHandle;
begin
Result := False;
Shift := ShiftStateFromModFlags(Event.modifierFlags);
IsModified := [ssAlt, ssCtrl, ssCommand] * Shift <> [];
Key := VKeyFromKeyCode(Event.keyCode, Shift, ISFNkey);
Ch := #0;
// Do not handle the modified letters in the KeyDown event
if not IsInputContext and not ISFNkey and IsDown then
begin
TDownKeyList.Current.AddKeyDown(Key);
Exit;
end;
if (Key <> 0) and (IsInputContext or ISFNkey) then
begin
if not IsInputContext then
Result := Key < vkSpace
else
Result := ISFNkey;
end;
if Result or ISFNkey or IsModified then
begin
Result := False;
if Form <> nil then
begin
LHandle := WindowHandleToPlatform(Form.Handle);
if (LHandle.Handle is TFMXWindow) and (not IsInputContext or (Key <> vkEscape)) then
begin
if IsModified and not ISFNkey then
begin
NSChars := Event.charactersIgnoringModifiers;
if NSChars <> nil then
ShortcutKey := NSStrToStr(NSChars);
for I := 0 to ShortcutKey.Length - 1 do
begin
if (UpCase(ShortcutKey.Chars[I]) >= 'A') and (UpCase(ShortcutKey.Chars[I]) <= 'Z') then
Key := Word(UpCase(ShortcutKey.Chars[I]));
end;
end;
if IsDown then
Result := DoKeyDown(Sender, Form, Key, Ch, Shift)
else
DoKeyUp(Sender, Form, Key, Ch, Shift);
end;
end;
if not Result and IsDown then
Result := DefaultAction(Char(Key), Shift);
end
else
begin
// handle is not modified by the letter
NSChars := Event.charactersIgnoringModifiers;
if NSChars <> nil then
ShortcutKey := NSStrToStr(NSChars);
for I := 0 to ShortcutKey.Length - 1 do
begin
Ch := ShortcutKey.Chars[I];
Key := Word(Ch);
if IsDown then
Result := DoKeyDown(Sender, Form, Key, Ch, Shift)
else
DoKeyUp(Sender, Form, Key, Ch, Shift);
end;
if not IsInputContext then
Result := True;
end;
end;
procedure TPlatformCocoa.MouseEvent(const EventRec: TEventRec);
var
LHandle: TMacWindowHandle;
MenuDisplayed: Boolean;
OldDisableClosePopups: Boolean;
Obj: IControl;
procedure InitLastEvent;
begin
if (EventRec.Form <> nil) and (EventRec.Form.Handle <> nil) and
(EventRec.EventKind in [TEventKind.MouseDown, TEventKind.MouseUp, TEventKind.MouseMove]) then
begin
LHandle := WindowHandleToPlatform(EventRec.Form.Handle);
if LHandle.Handle is TFMXWindow then
begin
if EventRec.EventKind = TEventKind.MouseUp then
TFMXWindow(LHandle.Handle).LastEvent := nil
else
TFMXWindow(LHandle.Handle).LastEvent := EventRec.Event;
end;
end;
end;
procedure CleanLastEvent;
begin
if (EventRec.Form <> nil) and (EventRec.Form.Handle <> nil) and
(EventRec.EventKind = TEventKind.MouseMove) and (LHandle.Handle is TFMXWindow) then
begin
LHandle := WindowHandleToPlatform(EventRec.Form.Handle);
if LHandle.Handle is TFMXWindow then
TFMXWindow(LHandle.Handle).LastEvent := nil;
end;
end;
begin
if EventRec.Form = nil then
Exit;
InitLastEvent;
try
case EventRec.EventKind of
TEventKind.MouseDown:
begin
// Popups
PrepareClosePopups(EventRec.Form);
// Activate
if not EventRec.Form.Active and (EventRec.Form.FormStyle <> TFormStyle.Popup) then
begin
OldDisableClosePopups := FDisableClosePopups;
try
FDisableClosePopups := True;
Activate(EventRec.Form);
finally
FDisableClosePopups := OldDisableClosePopups;
end;
Obj := EventRec.Form.ObjectAtPoint(EventRec.ScreenMousePos);
if (Obj <> nil) and (Obj.GetObject is TControl) and (EventRec.Button = TMouseButton.mbLeft) and
(TControl(Obj.GetObject).DragMode = TDragMode.dmAutomatic) then
EventRec.Form.MouseDown(EventRec.Button, EventRec.Shift, EventRec.FormMousePos.X,
EventRec.FormMousePos.Y)
else
begin
LHandle := WindowHandleToPlatform(EventRec.Form.Handle);
if LHandle.Handle is TFMXWindow then
TFMXWindow(LHandle.Handle).LastEvent := nil;
TMouseDownTimer.Create(EventRec);
end;
end
else
begin
// Context menu and mouse down
if (EventRec.Button = TMouseButton.mbRight) or ((EventRec.Button = TMouseButton.mbLeft) and
(ssCtrl in EventRec.Shift)) then
MenuDisplayed := ShowContextMenu(EventRec.Form, EventRec.ScreenMousePos)
else
MenuDisplayed := False;
if not MenuDisplayed then
try
EventRec.Form.MouseDown(EventRec.Button, EventRec.Shift, EventRec.FormMousePos.X,
EventRec.FormMousePos.Y);
except
HandleException(EventRec.Form);
end;
end;
end;
TEventKind.MouseUp:
begin
// mouse up
try
EventRec.Form.MouseUp(EventRec.Button, EventRec.Shift, EventRec.FormMousePos.X, EventRec.FormMousePos.Y);
except
HandleException(EventRec.Form);
end;
// popups
ClosePopupForms;
end;
TEventKind.MouseMove:
try
EventRec.Form.MouseMove(EventRec.Shift, EventRec.FormMousePos.X, EventRec.FormMousePos.Y);
except
HandleException(EventRec.Form);
end;
end;
finally
CleanLastEvent;
end;
end;
procedure TPlatformCocoa.MouseEvent(const Event: NSEvent);
var
LEventRec: TEventRec;
begin
LEventRec := TEventRec.Create(Event);
MouseEvent(LEventRec);
end;
{ App =========================================================================}
procedure RunLoopObserverCallback(observer: CFRunLoopObserverRef; activity: CFRunLoopActivity; info: Pointer); cdecl;
const
DefaultMask = NSSystemDefined or NSAppKitDefinedMask or NSApplicationDefinedMask or NSLeftMouseDownMask;
WithoutEventHandling = 0;
begin
if TThread.CurrentThread.ThreadID = MainThreadID then
CheckSynchronize;
if activity = kCFRunLoopBeforeTimers then
Exit;
if (PlatformCocoa <> nil) and (PlatformCocoa.NSApp <> nil) and (PlatformCocoa.FAlertCount = 0) then
begin
if (PlatformCocoa.FMainMenuState = TPlatformCocoa.TMainMenuState.Created) and (Application <> nil) and
(Application.MainForm <> nil) then
begin
PlatformCocoa.FMainMenuState := TPlatformCocoa.TMainMenuState.Recreated;
if TOpenCustomForm(Application.MainForm).MainMenu <> nil then
TMainMenu(TOpenCustomForm(Application.MainForm).MainMenu).RecreateOSMenu
else
Application.MainForm.RecreateOsMenu;
end;
if PlatformCocoa.NSApp.isActive then
PlatformCocoa.HookObserverCallback(False, WithoutEventHandling)
else
PlatformCocoa.HookObserverCallback(False, DefaultMask);
end;
end;
class function TPlatformCocoa.ClosePopupForms: Boolean;
begin
Result := False;
if Screen <> nil then
try
Result := Screen.ClosePopupForms;
except
HandleException(Screen);
end;
end;
class function TPlatformCocoa.PrepareClosePopups(const SaveForm: TCommonCustomForm): Boolean;
begin
Result := False;
if Screen <> nil then
try
Result := Screen.PrepareClosePopups(SaveForm);
except
HandleException(Screen);
end;
end;
function TPlatformCocoa.HookObserverCallback(CancelIdle: Boolean; Mask: NSUInteger = NSAnyEventMask): Boolean;
procedure Idle;
var
Done: Boolean;
begin
Done := False;
if Application <> nil then
try
FPerformKeyExecuted := False;
Application.DoIdle(Done);
except
HandleException(Application);
end;
end;
procedure DefaultMouseAction(const AEventRec: TEventRec);
var
TopModal: Boolean;
begin
if AEventRec.Form <> nil then
begin
if (AEventRec.Form.FormStyle <> TFormStyle.Popup) and (AEventRec.Shift * [ssLeft, ssRight, ssMiddle] <> []) and
(AEventRec.EventKind in [TEventKind.MouseMove, TEventKind.MouseDown]) and not AEventRec.MouseInContent then
begin
PrepareClosePopups(AEventRec.Form);
ClosePopupForms;
end;
if AEventRec.EventKind = TEventKind.MouseDown then
begin
TopModal := (FModalStack = nil) or (FModalStack.Count = 0) or (FModalStack.Peek = AEventRec.Form);
// if LeftClick on inactive form then perform event of mouse
if (FAlertCount = 0) and TopModal and (AEventRec.Button = TMouseButton.mbLeft) and not AEventRec.Form.Active and
(AEventRec.Form.FormStyle <> TFormStyle.Popup) then
MouseEvent(AEventRec);
end;
end;
end;
procedure EmulateCaptionClick;
var
Buttons: NSUInteger;
Form: TCommonCustomForm;
Pos: TPointF;
begin
Buttons := TNSEvent.OCClass.pressedMouseButtons;
try
if (Buttons <> 0) and (Buttons <> FStoredButtons) and (Screen <> nil) and (Screen.PopupFormCount > 0) then
try
Pos := GetMousePos;
if FindFormAtScreenPos(Form, Pos) then
begin
if Form.FormStyle <> TFormStyle.Popup then
begin
Pos := Form.ScreenToClient(Pos);
if Pos.Y < 0 then
begin
PrepareClosePopups(nil);
ClosePopupForms;
end;
end; // else do nothing
end
else
begin
PrepareClosePopups(nil);
ClosePopupForms;
end;
except
HandleException(Application);
end;
finally
FStoredButtons := Buttons;
end;
end;
var
AutoReleasePool: NSAutoreleasePool;
CancelDefaultAction: Boolean;
LEvent: NSEvent;
LEventRec: TEventRec;
OldDisableClosePopups: Boolean;
TimeoutDate: NSDate;
const
WaitTimeout = 0.001;
begin
Result := False;
CancelDefaultAction := False;
LEvent := nil;
if not CancelIdle then
Idle;
if Mask <> 0 then
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
TimeoutDate := TNSDate.Wrap(TNSDate.OCClass.dateWithTimeIntervalSinceNow(WaitTimeout));
LEvent := NSApp.nextEventMatchingMask(Mask, TimeoutDate, NSDefaultRunLoopMode, True);
try
if LEvent <> nil then
begin
Result := True;
LEventRec := TEventRec.Create(LEvent);
LEventRec.HandledInApp := True;
if Assigned(HookEvent) then
try
HookEvent(LEventRec, CancelIdle, CancelDefaultAction);
except
HandleException(LEventRec.Form);
end;
if not CancelDefaultAction then
DefaultMouseAction(LEventRec);
end;
finally
if not CancelDefaultAction and (LEvent <> nil) then
begin
OldDisableClosePopups := FDisableClosePopups;
try
FDisableClosePopups := True;
NSApp.sendEvent(LEvent);
finally
FDisableClosePopups := OldDisableClosePopups;
end;
end;
FPerformKeyExecuted := False;
end;
finally
AutoReleasePool.release;
end;
end;
if (Screen <> nil) and (Screen.PopupFormCount > 0) then
EmulateCaptionClick;
end;
procedure TPlatformCocoa.Run;
begin
FRunning := True;
CreateMenu;
Application.RealCreateForms;
// It's important to use kCFRunLoopBeforeTimers, because if event queue is constantly filled, it can cause
// the CheckSynchronize not to be called. And as one consequence, all pop-up forms are released through Release will not
// be released.
FRunLoopObserver := CFRunLoopObserverCreate(kCFAllocatorDefault, kCFRunLoopBeforeWaiting or kCFRunLoopBeforeTimers,
True, 0, RunLoopObserverCallback, nil);
CFRunLoopAddObserver(CFRunLoopGetCurrent, FRunLoopObserver, kCFRunLoopCommonModes);
NSApp.Run;
end;
function TPlatformCocoa.Terminating: Boolean;
begin
Result := FTerminating;
end;
function TPlatformCocoa.Running: Boolean;
begin
Result := FRunning;
end;
procedure TPlatformCocoa.Terminate;
begin
FRunning := False;
FTerminating := True;
NSApp.terminate(nil);
end;
function TPlatformCocoa.HandleToObjC(FmxHandle: TFmxHandle): IObjectiveC;
begin
TMonitor.Enter(FObjectiveCMap);
try
ValidateHandle(FmxHandle);
if FObjectiveCMap.ContainsKey(FmxHandle) then
Result := FObjectiveCMap[FmxHandle]
else
Result := nil;
finally
TMonitor.Exit(FObjectiveCMap);
end;
end;
function TPlatformCocoa.HandleMessage: Boolean;
begin
HookObserverCallback(True);
Result := False;
end;
procedure TPlatformCocoa.WaitMessage;
var
TimeoutDate: NSDate;
AutoReleasePool: NSAutoreleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
TimeoutDate := TNSDate.Wrap(TNSDate.OCClass.dateWithTimeIntervalSinceNow(WaitMessageTimeout));
NSApp.nextEventMatchingMask(NSAnyEventMask, TimeoutDate, NSDefaultRunLoopMode, False);
finally
AutoReleasePool.release;
end;
end;
procedure TPlatformCocoa.WakeMainThread(Sender: TObject);
var
NullEvent: NSEvent;
Origin: NSPoint;
AutoReleasePool: NSAutoReleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
NullEvent := TNSEvent.Wrap(TNSEvent.OCClass.otherEventWithType(NSApplicationDefined, Origin, 0, Now, 0, nil, 0, 0, 0));
TNSApplication.Wrap(TNSApplication.OCClass.sharedApplication).postEvent(NullEvent, True);
finally
AutoReleasePool.release;
end;
end;
function TPlatformCocoa.GetDefaultTitle: string;
var
AppNameKey: Pointer;
AppBundle: NSBundle;
NSAppName: NSString;
AutoReleasePool: NSAutoreleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
AppNameKey := NSObjectToID(StrToNSStr('CFBundleName'));
AppBundle := TNSBundle.Wrap(TNSBundle.OCClass.mainBundle);
NSAppName := TNSString.Wrap(AppBundle.infoDictionary.objectForKey(AppNameKey));
Result := NSStrToStr(NSAppName);
finally
AutoReleasePool.release;
end;
end;
function TPlatformCocoa.GetTitle: string;
begin
Result := FTitle;
end;
function TPlatformCocoa.GetVersionString: string;
var
VersionObject: Pointer;
begin
VersionObject := TNSBundle.Wrap(TNSBundle.OCClass.mainBundle).infoDictionary.objectForKey(
NSObjectToID(StrToNSStr('CFBundleVersion'))); // do not localize
if VersionObject <> nil then
Result := NSStrToStr(TNSString.Wrap(VersionObject))
else
Result := string.Empty;
end;
procedure TPlatformCocoa.SetTitle(const Value: string);
begin
if FTitle <> Value then
FTitle := Value;
end;
function TPlatformCocoa.GetHidden: Boolean;
begin
Result := NSApp.isHidden;
end;
procedure TPlatformCocoa.SetHidden(const Value: Boolean);
begin
if Value <> GetHidden then
begin
if Value then
NSApp.Hide(Self)
else
NSApp.UnHide(Self);
end;
end;
procedure TPlatformCocoa.SetScreenOrientation(AOrientations: TScreenOrientations);
begin
// Not needed for MAC
end;
procedure TPlatformCocoa.SetShowFullScreenIcon(const AForm: TCommonCustomForm; const AValue: Boolean);
var
NSWin: NSWindow;
AutoReleasePool: NSAutoreleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
NSWin := WindowHandleToPlatform(AForm.Handle).Wnd;
if AValue then
NSWin.setCollectionBehavior(NSWindowCollectionBehaviorFullScreenPrimary)
else
NSWin.setCollectionBehavior(NSWindowCollectionBehaviorDefault);
finally
AutoReleasePool.release;
end;
end;
procedure TPlatformCocoa.HideOthers;
begin
NSApp.hideOtherApplications(Self);
end;
function TPlatformCocoa.GetDisplayMetrics: TDeviceDisplayMetrics;
const
MacBasePPI = 110;
var
Screen: NSScreen;
ScreenSize: TPointF;
ScreenScale: Single;
begin
Screen := MainScreen;
ScreenSize := Screen.frame.size.ToSizeF;
ScreenScale := Screen.backingScaleFactor;
Result.PhysicalScreenSize := TSizeF.Create(ScreenSize.X * ScreenScale, ScreenSize.Y * ScreenScale).Truncate;
Result.RawScreenSize := Result.PhysicalScreenSize;
Result.LogicalScreenSize := TSize.Create(Trunc(ScreenSize.X), Trunc(ScreenSize.Y));
if Abs(ScreenSize.X) > 0 then
Result.AspectRatio := ScreenSize.Y / ScreenSize.X
else
Result.AspectRatio := 1;
Result.PixelsPerInch := Trunc(MacBasePPI * GetScreenScale);
Result.ScreenScale := ScreenScale;
Result.FontScale := ScreenScale;
end;
function TPlatformCocoa.RegisterKeyMapping(const PlatformKey, VirtualKey: Word; const KeyKind: TKeyKind): Boolean;
begin
Result := FKeyMapping.RegisterKeyMapping(PlatformKey, VirtualKey, KeyKind);
end;
function TPlatformCocoa.UnregisterKeyMapping(const PlatformKey: Word): Boolean;
begin
Result := FKeyMapping.UnregisterKeyMapping(PlatformKey);
end;
function TPlatformCocoa.PlatformKeyToVirtualKey(const PlatformKey: Word; var KeyKind: TKeyKind): Word;
begin
Result := FKeyMapping.PlatformKeyToVirtualKey(PlatformKey, KeyKind);
end;
function TPlatformCocoa.VirtualKeyToPlatformKey(const VirtualKey: Word): Word;
begin
Result := FKeyMapping.VirtualKeyToPlatformKey(VirtualKey);
end;
procedure TPlatformCocoa.AlertCreated;
begin
Inc(FAlertCount);
end;
procedure TPlatformCocoa.AlertReleased;
begin
if FAlertCount = 0 then
raise EInvalidOperation.Create(SAlertCreatedReleasedInconsistency);
Dec(FAlertCount);
end;
function TPlatformCocoa.AlertCount: Integer;
begin
Result := FAlertCount;
end;
{ Timer =======================================================================}
type
CocoaTimer = interface(NSObject)
['{337887FF-BA77-4703-BE0E-34DC1CB26276}']
procedure timerEvent; cdecl;
procedure release; cdecl;
end;
TCocoaTimer = class(TOCLocal)
private
FFunc: TTimerProc;
public
function GetObjectiveCClass: PTypeInfo; override;
procedure timerEvent; cdecl;
procedure SetTimerFunc(AFunc: TTimerProc);
procedure release; cdecl;
end;
function TCocoaTimer.GetObjectiveCClass: PTypeInfo;
begin
Result := TypeInfo(CocoaTimer);
end;
procedure TCocoaTimer.timerEvent;
begin
if Assigned(@FFunc) then
try
FFunc;
except
HandleException(nil);
end;
end;
procedure TCocoaTimer.release;
var
RC: NSUInteger;
begin
RC := NSObject(Super).retainCount;
NSObject(Super).release;
if RC = 1 then
Destroy;
end;
procedure TCocoaTimer.SetTimerFunc(AFunc: TTimerProc);
begin
FFunc := AFunc;
end;
function TPlatformCocoa.CreateTimer(Interval: Integer; TimerFunc: TTimerProc): TFmxHandle;
var
Timer: NSTimer;
User: TCocoaTimer;
LInterval: NSTimeInterval;
begin
Result := 0;
if not FTerminating and (Interval > 0) and Assigned(TimerFunc) then
begin
User := TCocoaTimer.Create;
try
User.SetTimerFunc(TimerFunc);
LInterval := Interval / 1000;
Timer := TNSTimer.Wrap(TNSTimer.OCClass.scheduledTimerWithTimeInterval(LInterval, User.GetObjectID,
sel_getUid('timerEvent'), User.GetObjectID, True));
TNSRunloop.Wrap(TNSRunLoop.OCClass.mainRunLoop).addTimer(Timer, NSRunLoopCommonModes);
Result := AllocHandle(Timer);
FTimers.Add(Result);
finally
// User is retained twice (because it's target) by the timer and released twice on timer invalidation.
NSObject(User.Super).release;
end;
end;
end;
function TPlatformCocoa.DestroyTimer(Timer: TFmxHandle): Boolean;
var
CocoaTimer: NSTimer;
I: Integer;
begin
Result := False;
if HandleToObjC(Timer, NSTimer, CocoaTimer) then
begin
Result := True;
CocoaTimer.invalidate;
DeleteHandle(Timer);
for I := FTimers.Count - 1 downto 0 do
if FTimers[I] = Timer then
begin
FTimers.Delete(I);
Break;
end;
end;
end;
procedure TPlatformCocoa.DestroyTimers;
var
I: Integer;
begin
for I := FTimers.Count - 1 downto 0 do
try
DestroyTimer(FTimers[I]);
except
Continue;
end;
end;
function TPlatformCocoa.GetTick: Double;
const
NanoToSeconds = 1E-9;
begin
Result := AbsoluteToNanoseconds(mach_absolute_time) * NanoToSeconds;
end;
{ Window ======================================================================}
{ TFMXView }
function TFMXView.GetObjectiveCClass: PTypeInfo;
begin
Result := TypeInfo(FMXView);
end;
constructor TFMXView.Create(const AOwner: TFMXWindow; AFrameRect: NSRect);
var
V: Pointer;
begin
inherited Create(AOwner);
V := NSView(Super).initWithFrame(AFrameRect);
if GetObjectID <> V then
UpdateObjectID(V);
NSView(Super).setAcceptsTouchEvents(True);
// NSWindow has special mode for merging several windows in one. Also user can Show/Hide tabs panel in the Window.
// In this cases NSWindow changes his content size without any legal way for catch this event. But technically,
// when NSWindow changes content it leads to changing frame of all subviews (form's view). So we subscribe on frame
// changed notification from form's view.
//
// When client size is changed we need to realign all controls on form and recreate canvas, because size is changed
// and we do it in this notification handler.
//
// Pay attention! We use NSViewFrameDidChangeNotification instead of NSViewBoundsDidChangeNotification, because
// for some reason in these cases (merging windows and show/hide tabs panel) View doesn't sent notification
// NSViewBoundsDidChangeNotification.
NSView(Super).setPostsFrameChangedNotifications(True);
TNSNotificationCenter.Wrap(TNSNotificationCenter.OCClass.defaultCenter).addObserver(GetObjectID, sel_getUid('frameChanged:'),
NSStringToID(StrToNSStr('NSViewFrameDidChangeNotification')), GetObjectID);
if TWindowStyle.GPUSurface in AOwner.Wnd.WindowStyle then
begin
if NSAppKitVersionNumber >= NSAppKitVersionNumber10_7 then
NSView(Super).setWantsBestResolutionOpenGLSurface(True);
FillChar(FEventInfo, Sizeof(FEventInfo), 0);
TNSNotificationCenter.Wrap(TNSNotificationCenter.OCClass.defaultCenter).addObserver(GetObjectID, sel_getUid('surfaceNeedsUpdate:'),
NSStringToID(NSViewGlobalFrameDidChangeNotification), GetObjectID);
end;
end;
destructor TFMXView.Destroy;
begin
TNSNotificationCenter.Wrap(TNSNotificationCenter.OCClass.defaultCenter).removeObserver(GetObjectID);
inherited;
end;
{ Text Service }
constructor TTextServiceCocoa.Create(const Owner: IControl; SupportMultiLine: Boolean);
begin
inherited;
end;
destructor TTextServiceCocoa.Destroy;
begin
inherited;
end;
function TTextServiceCocoa.GetText: string;
begin
Result := FText;
end;
procedure TTextServiceCocoa.SetText(const Value: string);
begin
FText := Value;
end;
function TTextServiceCocoa.GetCaretPosition: TPoint;
begin
Result := FCaretPosition;
end;
procedure TTextServiceCocoa.SetCaretPosition(const Value: TPoint);
begin
FCaretPosition := Value;
end;
procedure TTextServiceCocoa.InternalSetMarkedText( const AMarkedText: string );
begin
FMarkedText := AMarkedText;
(Owner as ITextInput).IMEStateUpdated;
end;
procedure TTextServiceCocoa.InternalBreakIMEInput;
begin
FMarkedText := string.Empty;
(Owner as ITextInput).IMEStateUpdated;
end;
procedure TTextServiceCocoa.InternalEndIMEInput;
begin
(Owner as ITextInput).EndIMEInput;
FMarkedText := string.Empty;
end;
procedure TTextServiceCocoa.InternalStartIMEInput;
begin
(Owner as ITextInput).StartIMEInput;
end;
function TTextServiceCocoa.InternalGetMarkedText: string;
begin
Result := FMarkedText;
end;
function TTextServiceCocoa.CombinedText: string;
begin
if FMarkedText <> '' then
Result := Copy(FText, 1, FCaretPosition.X) + FMarkedText + Copy(FText, FCaretPosition.X + 1, MaxInt)
else
Result := FText;
end;
function TTextServiceCocoa.TargetClausePosition: TPoint;
begin
Result := FCaretPosition;
Result.X := Result.X + FMarkedText.Length;
end;
procedure TTextServiceCocoa.EnterControl(const FormHandle: TWindowHandle);
begin
end;
procedure TTextServiceCocoa.ExitControl(const FormHandle: TWindowHandle);
var
Handle: TMacWindowHandle;
Range: NSRange;
begin
if not FMarkedText.IsEmpty then
begin
Handle := WindowHandleToPlatform(FormHandle);
Range.location := NSNotFound;
Range.length := 0;
TFMXWindow(Handle.Handle).FViewObj.insertText(TNSString.OCClass.stringWithString(StrToNSStr(FMarkedText)), Range);
end;
end;
procedure TTextServiceCocoa.DrawSingleLine(const Canvas: TCanvas;
const ARect: TRectF; const FirstVisibleChar: Integer; const Font: TFont;
const AOpacity: Single; const Flags: TFillTextFlags; const ATextAlign: TTextAlign;
const AVTextAlign: TTextAlign = TTextAlign.Center;
const AWordWrap: Boolean = False);
var
I: Integer;
S: string;
Layout: TTextLayout;
Region: TRegion;
begin
Layout := TTextLayoutManager.TextLayoutByCanvas(Canvas.ClassType).Create;
try
Layout.BeginUpdate;
Layout.TopLeft := ARect.TopLeft;
Layout.MaxSize := PointF(ARect.Width, ARect.Height);
Layout.WordWrap := AWordWrap;
Layout.HorizontalAlign := ATextAlign;
Layout.VerticalAlign := AVTextAlign;
Layout.Font := Font;
Layout.Color := Canvas.Fill.Color;
Layout.Opacity := AOpacity;
Layout.RightToLeft := TFillTextFlag.RightToLeft in Flags;
S := CombinedText;
Layout.Text := S.Substring(FirstVisibleChar - 1, S.Length - FirstVisibleChar + 1);
Layout.EndUpdate;
Layout.RenderLayout(Canvas);
if not FMarkedText.IsEmpty then
try
Canvas.Stroke.Assign(Canvas.Fill);
Canvas.Stroke.Thickness := 1;
Canvas.Stroke.Dash := TStrokeDash.Solid;
Region := Layout.RegionForRange(TTextRange.Create(CaretPosition.X, FMarkedText.Length));
for I := Low(Region) to High(Region) do
Canvas.DrawLine(
PointF(Region[I].Left, Region[I].Bottom),
PointF(Region[I].Right, Region[I].Bottom),
AOpacity, Canvas.Stroke);
if FSelectedRange.length > 0 then
begin
Canvas.Stroke.Thickness := 3;
Region := Layout.RegionForRange(TTextRange.Create(CaretPosition.X + Integer(FSelectedRange.location), FSelectedRange.length));
for I := Low(Region) to High(Region) do
Canvas.DrawLine(
PointF(Region[I].Left, Region[I].Bottom),
PointF(Region[I].Right, Region[I].Bottom),
AOpacity, Canvas.Stroke);
end;
finally
Canvas.Stroke.Thickness := 1;
Canvas.Stroke.Dash := TStrokeDash.Solid;
end;
finally
FreeAndNil(Layout);
end;
end;
procedure TTextServiceCocoa.DrawSingleLine(const Canvas: TCanvas;
const S: string;
const ARect: TRectF;
const Font: TFont;
const AOpacity: Single; const Flags: TFillTextFlags; const ATextAlign: TTextAlign;
const AVTextAlign: TTextAlign = TTextAlign.Center;
const AWordWrap: Boolean = False);
var
I: Integer;
Layout: TTextLayout;
Region: TRegion;
begin
Layout := TTextLayoutManager.TextLayoutByCanvas(Canvas.ClassType).Create;
try
Layout.BeginUpdate;
Layout.TopLeft := ARect.TopLeft;
Layout.MaxSize := PointF(ARect.Width, ARect.Height);
Layout.WordWrap := AWordWrap;
Layout.HorizontalAlign := ATextAlign;
Layout.VerticalAlign := AVTextAlign;
Layout.Font := Font;
Layout.Color := Canvas.Fill.Color;
Layout.Opacity := AOpacity;
Layout.RightToLeft := TFillTextFlag.RightToLeft in Flags;
Layout.Text := S;
Layout.EndUpdate;
Layout.RenderLayout(Canvas);
if not FMarkedText.IsEmpty then
try
Canvas.Stroke.Assign(Canvas.Fill);
Canvas.Stroke.Thickness := 1;
Canvas.Stroke.Dash := TStrokeDash.Solid;
Region := Layout.RegionForRange(TTextRange.Create(CaretPosition.X, FMarkedText.Length));
for I := Low(Region) to High(Region) do
Canvas.DrawLine(
PointF(Region[I].Left, Region[I].Bottom),
PointF(Region[I].Right, Region[I].Bottom),
AOpacity, Canvas.Stroke);
if FSelectedRange.length > 0 then
begin
Canvas.Stroke.Thickness := 3;
Region := Layout.RegionForRange(TTextRange.Create(CaretPosition.X + Integer(FSelectedRange.location), FSelectedRange.length));
for I := Low(Region) to High(Region) do
Canvas.DrawLine(
PointF(Region[I].Left, Region[I].Bottom),
PointF(Region[I].Right, Region[I].Bottom),
AOpacity, Canvas.Stroke);
end;
finally
Canvas.Stroke.Thickness := 1;
Canvas.Stroke.Dash := TStrokeDash.Solid;
end;
finally
FreeAndNil(Layout);
end;
end;
function TTextServiceCocoa.HasMarkedText: boolean;
begin
Result := FMarkedText <> '';
end;
function TTextServiceCocoa.GetImeMode: TImeMode;
begin
Result := FImeMode;
end;
procedure TTextServiceCocoa.SetImeMode(const Value: TImeMode);
begin
FImeMode := Value;
end;
procedure TTextServiceCocoa.SetMarkedRange(const Value: NSRange);
begin
FMarkedRange := Value;
end;
procedure TTextServiceCocoa.SetSelectedRange(const Value: NSRange);
begin
FSelectedRange := Value;
end;
function TPlatformCocoa.GetTextServiceClass: TTextServiceClass;
begin
Result := TTextServiceCocoa;
end;
{ TFMXViewBase }
constructor TFMXViewBase.Create(const AOwner: TFMXWindow);
begin
inherited Create;
FOwner := AOwner;
FBackingStore := TNSMutableAttributedString.Alloc;
FBackingStore := TNSMutableAttributedString.Wrap(FBackingStore.initWithString(StrToNSStr('')));
FMarkedRange.location := NSNotFound;
FMarkedRange.length := 0;
FSelectedRange.location := 0;
FSelectedRange.length := 0;
UpdateTextServiceControl;
end;
destructor TFMXViewBase.Destroy;
var
AutoReleasePool: NSAutoreleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
FBackingStore.release;
FOwner := nil;
NSView(Super).release;
finally
AutoreleasePool.release;
end;
inherited;
end;
type
TNSRectArray = array [0..$FFFF] of NSRect;
PNSRectArray = ^TNSRectArray;
procedure TFMXViewBase.drawRect(dirtyRect: NSRect);
var
nctx: NSGraphicsContext;
boundRect: NSRect;
PaintControl: IPaintControl;
UpdateRects: array of TRectF;
R: PNSRectArray;
I, RCount: NSInteger;
AutoReleasePool: NSAutoreleasePool;
begin
if FOwner = nil then
Exit;
AutoReleasePool := TNSAutoreleasePool.Create;
try
boundRect := NSView(Super).bounds;
NativeView.getRectsBeingDrawn(@R, @RCount);
SetLength(UpdateRects, RCount);
for I := 0 to RCount - 1 do
begin
UpdateRects[I] := RectF(R[I].origin.x, boundRect.size.height - R[I].origin.y - R[I].size.height,
R[I].origin.x + R[I].size.width, boundRect.size.height - R[I].origin.y);
end;
nctx := TNSGraphicsContext.Wrap(TNSGraphicsContext.OCClass.currentContext);
if Supports(FOwner.Wnd, IPaintControl, PaintControl) then
begin
if not (TWindowStyle.GPUSurface in FOwner.Wnd.WindowStyle) then
PaintControl.ContextHandle := THandle(nctx.graphicsPort);
PaintControl.PaintRects(UpdateRects);
if not (TWindowStyle.GPUSurface in FOwner.Wnd.WindowStyle) then
PaintControl.ContextHandle := 0;
end;
if (FOwner.Wnd.Transparency) then
WindowHandleToPlatform(FOwner.Wnd.Handle).UpdateLayer(nctx.graphicsPort);
if FOwner.NeedUpdateShadow and NSWindow(FOwner.Super).isVisible then
begin
NSWindow(FOwner.Super).invalidateShadow;
FOwner.NeedUpdateShadow := False;
end;
finally
AutoReleasePool.release;
end;
end;
function TFMXViewBase.GetGestureControlUnderMouse(const APoint: TPointF): IGestureControl;
var
LObject: IControl;
LGestureControl: TComponent;
begin
LObject := FOwner.Wnd.ObjectAtPoint(FOwner.Wnd.ClientToScreen(APoint));
if LObject <> nil then
LGestureControl := LObject.GetObject
else
LGestureControl := FOwner.Wnd;
Supports(LGestureControl, IGestureControl, Result);
end;
function TFMXViewBase.GetGestureEngineUnderMouse(const APoint: TPointF): TPlatformGestureEngine;
var
LControl: IGestureControl;
begin
Result := nil;
LControl := GetGestureControlUnderMouse(APoint);
if LControl <> nil then
Result := TPlatformGestureEngine(LControl.TouchManager.GestureEngine);
end;
function TFMXViewBase.GetNativeView: NSView;
begin
Result := NSView(Super);
end;
procedure TFMXViewBase.scrollWheel(event: NSEvent);
var
H: Boolean;
SS: TShiftState;
D: Single;
AutoReleasePool: NSAutoreleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
try
SS := ShiftStateFromModFlags(event.modifierFlags);
H := False;
D := 0;
if event.deltaY <> 0 then
D := event.deltaY
else if event.deltaX <> 0 then
begin
D := event.deltaX;
SS := SS + [ssHorizontal];
end;
if D <> 0 then
FOwner.Wnd.MouseWheel(SS, Round(D * 30), H)
except
HandleException(Self);
end;
finally
AutoReleasePool.release;
end;
end;
procedure TFMXViewBase.keyDown(event: NSEvent);
var
Performed: Boolean;
begin
FShift := [];
Performed := False;
if not hasMarkedText then // IME's conversion window.is active.
begin
FOwner.FDelayRelease := True;
try
if not PlatformCocoa.FPerformKeyExecuted then
Performed := PlatformCocoa.KeyProc(Self, FOwner.Wnd, event, False, True);
finally
FOwner.FDelayRelease := False;
if csDestroying in FOwner.Wnd.ComponentState then
FOwner.Wnd.Release;
end;
end;
if (not Performed) and (not (csDestroying in FOwner.Wnd.ComponentState)) then
NativeView.inputContext.handleEvent(event);
end;
procedure TFMXViewBase.keyUp(event: NSEvent);
var
K: word;
Ch: WideChar;
Shift: TShiftState;
VKKeyCode: Integer;
IsFNKey: boolean;
begin
if hasMarkedText then
begin
// IME's conversion window.is active.
VKKeyCode := VKeyFromKeyCode(event.keyCode, Shift, IsFNKey);
TDownKeyList.Current.RemoveKeyDown(VKKeyCode, K, Ch);
end
else
PlatformCocoa.KeyProc(Self, FOwner.Wnd, event, False, False);
end;
procedure TFMXViewBase.lockFocus;
var
ContextObject: IContextObject;
begin
NSView(Super).lockFocus;
if Supports(Owner.Wnd, IContextObject, ContextObject) then
TCustomContextOpenGL(ContextObject.Context).FormContext.setView(NSView(Super));
end;
procedure TFMXViewBase.mouseMoved(theEvent: NSEvent);
begin
if PlatformCocoa <> nil then
PlatformCocoa.MouseEvent(theEvent);
end;
procedure TFMXViewBase.mouseDown(theEvent: NSEvent);
begin
if PlatformCocoa <> nil then
PlatformCocoa.MouseEvent(theEvent);
SetFirstGesturePoint(theEvent);
end;
procedure TFMXViewBase.mouseUp(theEvent: NSEvent);
begin
if PlatformCocoa <> nil then
PlatformCocoa.MouseEvent(theEvent);
ReleaseGestureEngine;
end;
procedure TFMXViewBase.mouseDragged(theEvent: NSEvent);
begin
if PlatformCocoa <> nil then
PlatformCocoa.MouseEvent(theEvent);
SetTrackGesturePoint(theEvent);
end;
procedure TFMXViewBase.rightMouseDown(theEvent: NSEvent);
begin
if PlatformCocoa <> nil then
PlatformCocoa.MouseEvent(theEvent);
end;
procedure TFMXViewBase.rightMouseUp(theEvent: NSEvent);
begin
if PlatformCocoa <> nil then
PlatformCocoa.MouseEvent(theEvent);
end;
procedure TFMXViewBase.rightMouseDragged(theEvent: NSEvent);
begin
if PlatformCocoa <> nil then
PlatformCocoa.MouseEvent(theEvent);
end;
procedure TFMXViewBase.otherMouseDown(theEvent: NSEvent);
begin
if PlatformCocoa <> nil then
PlatformCocoa.MouseEvent(theEvent);
end;
procedure TFMXViewBase.otherMouseUp(theEvent: NSEvent);
begin
if PlatformCocoa <> nil then
PlatformCocoa.MouseEvent(theEvent);
end;
procedure TFMXViewBase.ReleaseGestureEngine;
const
LGestureTypes: TGestureTypes = [TGestureType.Standard, TGestureType.Recorded, TGestureType.Registered];
var
LEventInfo: TGestureEventInfo;
begin
if FCurrentGestureEngine <> nil then
begin
if FCurrentGestureEngine.PointCount > 1 then
begin
FillChar(LEventInfo, Sizeof(FEventInfo), 0);
if TPlatformGestureEngine.IsGesture(FCurrentGestureEngine.Points, FCurrentGestureEngine.GestureList,
LGestureTypes, LEventInfo) then
FCurrentGestureEngine.BroadcastGesture(FCurrentGestureEngine.Control, LEventInfo);
end;
// reset the points/touches
FCurrentGestureEngine.ClearPoints;
FCurrentGestureEngine := nil;
end;
end;
procedure TFMXViewBase.DiscardGestureEngine;
begin
if FCurrentGestureEngine <> nil then
begin
FCurrentGestureEngine.ClearPoints;
FCurrentGestureEngine := nil;
end;
end;
procedure TFMXViewBase.otherMouseDragged(theEvent: NSEvent);
begin
if PlatformCocoa <> nil then
PlatformCocoa.MouseEvent(theEvent);
end;
function TFMXViewBase.acceptsFirstResponder: Boolean;
begin
Result := True;
end;
function TFMXViewBase.becomeFirstResponder: Boolean;
begin
Result := True;
end;
function TFMXViewBase.resignFirstResponder: Boolean;
begin
Result := True;
end;
procedure TFMXViewBase.magnifyWithEvent(event: NSEvent);
var
Obj: IControl;
LTouches: NSSet;
LTouchesArray: NSArray;
LPoint, LPoint2: NSPoint;
LTouch: NSTouch;
LDeviceSize: NSSize;
I, J, Distance: Integer;
GestureObj: IGestureControl;
begin
{ Use mouseLocation instead of locationInWindow because gesture events do not have locationInWindow set
(gestures don't move the mouse cursor). We will consider that the gestures are for the control that is
under the mouse cursor (on OSX the gestures are for the view under the mouse cursor).}
LPoint := TNSEvent.OCClass.mouseLocation;
LPoint.y := MainScreenHeight - LPoint.y;
FEventInfo.Location := PointF(LPoint.x, LPoint.y);
// Get the control from "under" the gesture.
Obj := FOwner.Wnd.ObjectAtPoint(FOwner.Wnd.ClientToScreen(FEventInfo.Location));
if Obj <> nil then
FGestureControl := Obj.GetObject
else
FGestureControl := FOwner.Wnd;
if Supports(FGestureControl, IGestureControl, GestureObj) then
FGestureControl := GestureObj.GetFirstControlWithGesture(TInteractiveGesture.Zoom);
if FGestureControl <> nil then
begin
LTouches := event.touchesMatchingPhase(NSTouchPhaseTouching, NSView(Super));
if LTouches.count >= 2 then
begin
LTouchesArray := LTouches.allObjects;
LTouch := TNSTouch.Wrap(LTouchesArray.objectAtIndex(0));
LDeviceSize := LTouch.deviceSize;
FEventInfo.Distance := 0; //reset the distance
// Find the greatest distance between the touches.
for I := 0 to LTouches.count - 2 do
begin
LTouch := TNSTouch.Wrap(LTouchesArray.objectAtIndex(I));
LPoint := LTouch.normalizedPosition;
for J := 1 to LTouches.count - 1 do
begin
LTouch := TNSTouch.Wrap(LTouchesArray.objectAtIndex(J));
LPoint2 := LTouch.normalizedPosition;
Distance := Round(Sqrt(Sqr(LPoint.x * LDeviceSize.width - LPoint2.x * LDeviceSize.width) +
Sqr(LPoint.y * LDeviceSize.height - LPoint2.y * LDeviceSize.height)));
if Distance > FEventInfo.Distance then
FEventInfo.Distance := Distance;
end;
FEventInfo.GestureID := igiZoom;
if Supports(FGestureControl, IGestureControl, GestureObj) then
GestureObj.CMGesture(FEventInfo);
FEventInfo.Flags := [];
end
end
end
else
//send the message up the responder chain
NSView(Super).magnifyWithEvent(event);
end;
procedure TFMXViewBase.rotateWithEvent(event: NSEvent);
var
Obj: IControl;
LPoint: NSPoint;
GestureObj: IGestureControl;
begin
// Use mouseLocation instead of locationInWindow because gesture events do not have locationInWindow set
// (gestures don't move the mouse cursor). We will consider that the gestures are for the control that is
// under the mouse cursor (on OSX the gestures are for the view under the mouse cursor).
LPoint := TNSEvent.OCClass.mouseLocation;
LPoint.y := MainScreenHeight - LPoint.y;
FEventInfo.Location := LPoint.ToPointF;
// Get the control from "under" the gesture.
Obj := FOwner.Wnd.ObjectAtPoint(FOwner.Wnd.ClientToScreen(FEventInfo.location));
if Obj <> nil then
FGestureControl := Obj.GetObject
else
FGestureControl := FOwner.Wnd;
if Supports(FGestureControl, IGestureControl, GestureObj) then
FGestureControl := GestureObj.GetFirstControlWithGesture(TInteractiveGesture.Rotate);
if FGestureControl <> nil then
begin
//Transform degrees in radians and add them to the existing angle of rotation.
FEventInfo.Angle := FEventInfo.Angle + event.rotation* Pi / 180;
FEventInfo.GestureID := igiRotate;
if Supports(FGestureControl, IGestureControl, GestureObj) then
GestureObj.CMGesture(FEventInfo);
FEventInfo.Flags := [];
end
else
//send the message up the responder chain
NSView(Super).rotateWithEvent(event);
end;
procedure TFMXViewBase.surfaceNeedsUpdate(notification: NSNotification);
var
ContextObject: IContextObject;
begin
if Supports(Owner.Wnd, IContextObject, ContextObject) then
TCustomContextOpenGL(ContextObject.Context).FormContext.update;
end;
procedure TFMXViewBase.swipeWithEvent(event: NSEvent);
var
Obj: IControl;
LTouches: NSSet;
LTouchesArray: NSArray;
LPoint, LPoint2: NSPoint;
LTouch: NSTouch;
Width, Height: Single;
GestureObj: IGestureControl;
begin
// Use mouseLocation instead of locationInWindow because gesture events do not have locationInWindow set
// (gestures don't move the mouse cursor). We will consider that the gestures are for the control that is
// under the mouse cursor (on OSX the gestures are for the view under the mouse cursor).
LPoint := TNSEvent.OCClass.mouseLocation;
LPoint.y := MainScreenHeight - LPoint.y;
FSwipePoint := LPoint.ToPointF;
// Get the control from "under" the gesture.
Obj := FOwner.Wnd.ObjectAtPoint(FOwner.Wnd.ClientToScreen(FSwipePoint));
if Obj <> nil then
FGestureControl := Obj.GetObject
else
FGestureControl := FOwner.Wnd;
if Supports(FGestureControl, IGestureControl, GestureObj) then
FGestureControl := GestureObj.GetFirstControlWithGesture(TInteractiveGesture.Pan);
if FGestureControl <> nil then
begin
FEventInfo.Location := FSwipePoint;
LTouches := event.touchesMatchingPhase(NSTouchPhaseTouching, NSView(Super));
if LTouches.count = 2 then
begin
LTouchesArray := LTouches.allObjects;
LTouch := TNSTouch.Wrap(LTouchesArray.objectAtIndex(0));
LPoint := LTouch.normalizedPosition;
LTouch := TNSTouch.Wrap(LTouchesArray.objectAtIndex(1));
LPoint2 := LTouch.normalizedPosition;
//the distance between the 2 fingers
FEventInfo.Distance := Round(Sqrt(Sqr(LPoint.x - LPoint2.x) + Sqr(LPoint.y - LPoint2.y)));
LPoint.X := Min(LPoint.x, LPoint2.x) + Abs(LPoint.x - LPoint2.x);
LPoint.Y := 1.0 - Min(LPoint.y, LPoint2.y) + Abs(LPoint.y - LPoint2.y);
Width := 0;
Height := 0;
if FGestureControl is TCommonCustomForm then
begin
Width := TCommonCustomForm(FGestureControl).ClientWidth;
Height := TCommonCustomForm(FGestureControl).ClientHeight;
end
else if FGestureControl is TControl then
begin
Width := TControl(FGestureControl).Canvas.Width;
Height := TControl(FGestureControl).Canvas.Height;
end;
LPoint.x := LPoint.x * Width;
LPoint.y := LPoint.y * Height;
if event.deltaX <> 0 then
begin
//horizontal swipe
if event.deltaX > 0 then
begin
//swipe-left
LPoint.x := LPoint.x + FEventInfo.Location.X;
FEventInfo.Location := LPoint.ToPointF;
end
else
begin
// swipe-right
LPoint.X := FEventInfo.Location.x - LPoint.x;
FEventInfo.Location := LPoint.ToPointF;
end;
end
else if event.deltaY <> 0 then
begin
//vertical swipe
if event.deltaY > 0 then
begin
//swipe-up
LPoint.y := LPoint.y + FEventInfo.Location.Y;
FEventInfo.Location := LPoint.ToPointF;
end
else
begin
//swipe-down
LPoint.y := FEventInfo.Location.Y - LPoint.Y;
FEventInfo.Location := LPoint.ToPointF;
end;
end;
FSwipePoint := FEventInfo.Location;
end
else
begin
// send the message up the responder chain
NSView(Super).swipeWithEvent(event);
Exit;
end;
// EventInfo.Distance := Sqrt(Sqr(Point.X - Source.X) + Sqr(Point.Y - Source.Y));;
// EventInfo.InertiaVector := TPointF(SmallPointToPoint(InertiaVectorFromArgument(LGestureInfo.ullArguments)));
FEventInfo.GestureID := igiPan;
// send message to the control
if Supports(FGestureControl, IGestureControl, GestureObj) then
GestureObj.CMGesture(FEventInfo);
FEventInfo.Flags := [];
end
else
// send the message up the responder chain
NSView(Super).swipeWithEvent(event);
end;
procedure TFMXViewBase.touchesBeganWithEvent(event: NSEvent);
var
Obj: IControl;
LTouches: NSSet;
LTouchesArray: NSArray;
LPoint, LPoint2: NSPoint;
LLocation: TPointF;
LTouch: NSTouch;
Handled: Boolean;
GestureObj: IGestureControl;
begin
Handled := False;
FillChar(FEventInfo, Sizeof(FEventInfo), 0);
// Get the location of the gesture.
// Use mouseLocation instead of locationInWindow because gesture events do not have locationInWindow set
// (gestures don't move the mouse cursor). We will consider that the gestures are for the control that is
// under the mouse cursor (on OSX the gestures are for the view under the mouse cursor).
LPoint := TNSEvent.OCClass.mouseLocation;
LPoint.y := MainScreenHeight - LPoint.y;
LLocation := LPoint.ToPointF;
DiscardGestureEngine;
// Find the control from "under" the gesture.
Obj := FOwner.Wnd.ObjectAtPoint(LLocation);
if Obj <> nil then
FGestureControl := Obj.GetObject
else
FGestureControl := FOwner.Wnd;
if Supports(FGestureControl, IGestureControl, GestureObj) then
FGestureControl := GestureObj.GetFirstControlWithGestureEngine;
if Supports(FGestureControl, IGestureControl, GestureObj) then
begin
TPlatformGestureEngine(GestureObj.TouchManager.GestureEngine).InitialPoint := LLocation;
// Use NSTouch.normalizedPosition to get the movement of the fingers on the trackpad.
LTouches := event.touchesMatchingPhase(NSTouchPhaseTouching, NSView(Super));
if LTouches.count = 2 then
begin
LTouchesArray := LTouches.allObjects;
if FGestureControl <> nil then
begin
Handled := True;
LTouch := TNSTouch.Wrap(LTouchesArray.objectAtIndex(0));
LPoint := LTouch.normalizedPosition;
LTouch := TNSTouch.Wrap(LTouchesArray.objectAtIndex(1));
LPoint2 := LTouch.normalizedPosition;
LPoint.x := Min(LPoint.x, LPoint2.x) + Abs(LPoint.x - LPoint2.x);
LPoint.y := 1.0 - Min(LPoint.y, LPoint2.y) - Abs(LPoint.y - LPoint2.y);
// Retain the points/touches.
TPlatformGestureEngine(GestureObj.TouchManager.GestureEngine).ClearPoints;
TPlatformGestureEngine(GestureObj.TouchManager.GestureEngine).AddPoint(LPoint.x * 100, LPoint.y * 100);
end;
end;
end;
//set the gfBegin flag for interactive gestures.
FEventInfo.Flags := [TInteractiveGestureFlag.gfBegin];
if not Handled then
//send the message up the responder chain
NSView(Super).touchesBeganWithEvent(event);
end;
procedure TFMXViewBase.touchesCancelledWithEvent(event: NSEvent);
var
GestureObj: IGestureControl;
begin
if Supports(FGestureControl, IGestureControl, GestureObj) then
begin
//Handle "end" flag for interactive gestures.
if FEventInfo.GestureID > igiFirst then
begin
FEventInfo.Flags := [TInteractiveGestureFlag.gfEnd];
// send message to the control
GestureObj.CMGesture(FEventInfo);
FillChar(FEventInfo, Sizeof(FEventInfo), 0);
end;
//reset the points/touches
if GestureObj.TouchManager.GestureEngine <> nil then
TPlatformGestureEngine(GestureObj.TouchManager.GestureEngine).ClearPoints;
FGestureControl := nil;
end
else
//send the message up the responder chain
NSView(Super).touchesCancelledWithEvent(event);
end;
const
MIN_NO_GESTURE_POINTS = 10;
procedure TFMXViewBase.touchesEndedWithEvent(event: NSEvent);
var
LEngine: TPlatformGestureEngine;
Handled: Boolean;
GestureObj: IGestureControl;
const
LGestureTypes: TGestureTypes = [TGestureType.Standard, TGestureType.Recorded, TGestureType.Registered];
begin
Handled := False;
if Supports(FGestureControl, IGestureControl, GestureObj) then
begin
// Handle "end" flag for interactive gestures.
if FEventInfo.GestureID > igiFirst then
begin
FEventInfo.Flags := [TInteractiveGestureFlag.gfEnd];
// send message to the control
GestureObj.CMGesture(FEventInfo);
end;
if GestureObj.TouchManager.GestureEngine <> nil then
begin
// Handle standard gestures.
LEngine := TPlatformGestureEngine(GestureObj.TouchManager.GestureEngine);
if LEngine.PointCount > 1 then
begin
// Make sure there are at least MIN_NO_GESTURE_POINTS points.
if LEngine.PointCount < MIN_NO_GESTURE_POINTS then
LEngine.AddPoints(MIN_NO_GESTURE_POINTS - LEngine.PointCount);
FillChar(FEventInfo, Sizeof(FEventInfo), 0);
if TPlatformGestureEngine.IsGesture(LEngine.Points, LEngine.GestureList, LGestureTypes, FEventInfo) then
begin
LEngine.BroadcastGesture(FGestureControl, FEventInfo);
Handled := True;
end;
end;
// reset the points/touches
TPlatformGestureEngine(GestureObj.TouchManager.GestureEngine).ClearPoints;
end;
FGestureControl := nil;
FillChar(FEventInfo, Sizeof(FEventInfo), 0);
end;
if not Handled then
NSView(Super).touchesEndedWithEvent(event);
end;
procedure TFMXViewBase.touchesMovedWithEvent(event: NSEvent);
var
LTouches: NSSet;
LTouchesArray: NSArray;
LPoint, LPoint2: NSPoint;
LTouch: NSTouch;
Handled: Boolean;
GestureObj: IGestureControl;
begin
Handled := False;
if Supports(FGestureControl, IGestureControl, GestureObj) and (GestureObj.TouchManager.GestureEngine <> nil) then
begin
// retain the points/touches
LTouches := event.touchesMatchingPhase(NSTouchPhaseTouching, NSView(Super));
if LTouches.count = 2 then
begin
LTouchesArray := LTouches.allObjects;
// Retain the points/touches.
if FGestureControl <> nil then
begin
Handled := True;
LTouch := TNSTouch.Wrap(LTouchesArray.objectAtIndex(0));
LPoint := LTouch.normalizedPosition;
LTouch := TNSTouch.Wrap(LTouchesArray.objectAtIndex(1));
LPoint2 := LTouch.normalizedPosition;
LPoint.x := Min(LPoint.x, LPoint2.x) + Abs(LPoint.x - LPoint2.x);
LPoint.y := 1.0 - Min(LPoint.y, LPoint2.y) - Abs(LPoint.y - LPoint2.y);
// Retain the points/touches.
TPlatformGestureEngine(GestureObj.TouchManager.GestureEngine).AddPoint(LPoint.x * 100, LPoint.y * 100);
end;
end;
end;
if not Handled then
NSView(Super).touchesMovedWithEvent(event);
end;
{ NSTextInputClient }
function TFMXViewBase.hasMarkedText: Boolean;
begin
Result := FMarkedRange.location <> NSNotFound;
end;
function ToNSString(const text : Pointer; var NStr: NSString): Boolean;
begin
if TNSObject.Wrap(text).isKindOfClass(objc_getClass(MarshaledAString('NSAttributedString'))) then
begin
NStr := TNSString.Wrap(objc_msgSend(text, sel_getUid(MarshaledAString('string'))));
Result := True;
end
else
begin
NStr := TNSString.Wrap(text);
Result := False;
end;
end;
procedure TFMXViewBase.insertText(text: Pointer{NSString}; replacementRange: NSRange);
var
I: Integer;
K: Word;
R : NSRange;
Ch: WideChar;
Str: string;
NStr: NSString;
AutoReleasePool: NSAutoreleasePool;
TSC: ITextInput;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
if (FShift - [ssAlt, ssShift]) <> [] then
Exit;
if hasMarkedText then
begin
NativeView.inputContext.discardMarkedText;
try
if (FOwner.Wnd.Focused <> nil) and Supports(FOwner.Wnd.Focused, ITextInput, TSC) then
begin
TTextServiceCocoa(TSC.GetTextService).InternalSetMarkedText('');
TTextServiceCocoa(TSC.GetTextService).InternalEndIMEInput;
end;
except
HandleException(Self);
end;
end;
NativeView.inputContext.invalidateCharacterCoordinates;
ToNSString(text, NStr);
if NStr.length > 0 then
begin
Str := NSStrToStr(NStr);
for I := 0 to Str.Length - 1 do
begin
Ch := Str.Chars[I];
K := Ord(Ch);
DoKeyDown(Self, FOwner.Wnd, K, Ch, FShift);
end;
// Get a valid range
if replacementRange.location = NSNotFound then
if FMarkedRange.location <> NSNotFound then
replacementRange := FMarkedRange
else
replacementRange := FSelectedRange
else
begin
replacementRange.location := 0;
replacementRange.length := 0;
end;
NativeView.inputContext.invalidateCharacterCoordinates;
try
if (FOwner.Wnd.Focused <> nil) then
FOwner.Wnd.Focused.Repaint;
except
HandleException(Self);
end;
end;
FBackingStore.beginEditing;
R.location := 0;
R.length := FBackingStore.mutableString.length;
FBackingStore.deleteCharactersInRange(R);
FBackingStore.endEditing;
FMarkedRange.location := NSNotFound;
FMarkedRange.length := 0;
FSelectedRange.location := 0;
FSelectedRange.length := 0;
UpdateTextServiceControl;
finally
AutoReleasePool.release;
end;
end;
function TFMXViewBase.selectedRange: NSRange;
begin
Result := FSelectedRange;
end;
procedure TFMXViewBase.SetFirstGesturePoint(const AnEvent: NSEvent);
var
LPoint: NSPoint;
LLocation: TPointF;
LWindow: NSWindow;
begin
LWindow := AnEvent.window;
if LWindow <> nil then
begin
LPoint := AnEvent.locationInWindow;
LLocation := TPointF.Create(LPoint.X, NSView(Super).bounds.size.height - LPoint.y);
FCurrentGestureEngine := GetGestureEngineUnderMouse(LLocation);
if FCurrentGestureEngine <> nil then
begin
FCurrentGestureEngine.ClearPoints;
FCurrentGestureEngine.InitialPoint := LLocation;
end;
end;
end;
procedure TFMXViewBase.setMarkedText(text: Pointer {NSString}; selectedRange, replacementRange: NSRange);
var
NStr: NSString;
IsAttrString: Boolean;
TSC: ITextInput;
AutoReleasePool: NSAutoreleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
if not hasMarkedText then
try
if (FOwner.Wnd.Focused <> Nil) and Supports(FOwner.Wnd.Focused, ITextInput, TSC) then
TTextServiceCocoa(TSC.GetTextService).InternalStartIMEInput;
TDownKeyList.Current.Clear;
except
HandleException(Self);
end;
IsAttrString := ToNSString(text, NStr);
NativeView.inputContext.invalidateCharacterCoordinates;
// Get a valid range
if replacementRange.location = NSNotFound then
if FMarkedRange.location <> NSNotFound then
replacementRange := FMarkedRange
else
replacementRange := FSelectedRange
else
begin
replacementRange.location := 0;
replacementRange.length := 0;
end;
// Add the text
FBackingStore.beginEditing;
try
if NStr.length = 0 then
begin
FBackingStore.deleteCharactersInRange(replacementRange);
NativeView.inputContext.discardMarkedText;
FMarkedRange.location := NSNotFound;
FMarkedRange.length := 0;
FSelectedRange.location := 0;
FSelectedRange.length := 0;
UpdateTextServiceControl;
try
if (FOwner.Wnd.Focused <> nil) and Supports(FOwner.Wnd.Focused, ITextInput, TSC) then
begin
TTextServiceCocoa(TSC.GetTextService).InternalBreakIMEInput;
TTextServiceCocoa(TSC.GetTextService).InternalEndIMEInput;
end;
except
HandleException(Self);
end;
end
else
begin
FSelectedRange.location := replacementRange.location + selectedRange.location;
FSelectedRange.length := selectedRange.length;
FMarkedRange.location := replacementRange.location;
FMarkedRange.length := NStr.length;
UpdateTextServiceControl;
if IsAttrString then
FBackingStore.replaceCharactersInRange(replacementRange, TNSAttributedString.Wrap(text))
else
FBackingStore.replaceCharactersInRange(replacementRange, TNSString.Wrap(text));
try
if (FOwner.Wnd.Focused <> nil) and Supports(FOwner.Wnd.Focused, ITextInput, TSC) then
TSC.GetTextService.InternalSetMarkedText(NSStrToStr(NStr));
except
HandleException(Self);
end;
end;
finally
FBackingStore.endEditing;
end;
NativeView.inputContext.invalidateCharacterCoordinates;
try
if (FOwner.Wnd.Focused <> nil) then
FOwner.Wnd.Focused.Repaint;
except
HandleException(Self);
end;
finally
AutoReleasePool.release;
end;
end;
procedure TFMXViewBase.SetTrackGesturePoint(const AnEvent: NSEvent);
var
LPoint: NSPoint;
LLocation: TPointF;
LWindow: NSWindow;
LEngine: TPlatformGestureEngine;
begin
if FCurrentGestureEngine <> nil then
begin
LWindow := AnEvent.window;
if LWindow <> nil then
begin
LPoint := AnEvent.locationInWindow;
LLocation := TPointF.Create(LPoint.X, NSView(Super).bounds.size.height - LPoint.y);
LEngine := GetGestureEngineUnderMouse(LLocation);
if FCurrentGestureEngine <> LEngine then
ReleaseGestureEngine
else
FCurrentGestureEngine.AddPoint(LLocation.X, LLocation.Y);
end;
end;
end;
procedure TFMXViewBase.unMarkText;
var
TSC: ITextInput;
AutoReleasePool: NSAutoreleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
// NativeView.inputContext.invalidateCharacterCoordinates;
FMarkedRange.location := NSNotFound;
FMarkedRange.length := 0;
UpdateTextServiceControl;
try
if (FOwner.Wnd.Focused <> nil) and Supports(FOwner.Wnd.Focused, ITextInput, TSC) then
begin
TTextServiceCocoa(TSC.GetTextService).InternalSetMarkedText('');
end;
except
HandleException(Self);
end;
NativeView.inputContext.discardMarkedText;
finally
AutoReleasePool.release;
end;
end;
function TFMXViewBase.validAttributesForMarkedText: Pointer {NSArray};
var
Attribs: array[0..1] of Pointer;
Attrib: NSString;
AttrArray: NSArray;
begin
Attrib := NSMarkedClauseSegmentAttributeName;
Attribs[0] := NSObjectToID(Attrib);
Attrib := NSGlyphInfoAttributeName;
Attribs[1] := NSObjectToID(Attrib);
AttrArray := TNSArray.Wrap(TNSArray.OCClass.arrayWithObjects(@Attribs[0], 2));
Result := NSObjectToID(AttrArray);
// Attrib := NSMarkedClauseSegmentAttributeName;
// Attribs[0] := (Attrib as ILocalObject).GetObjectID;
// AttrArray := TNSArray.Wrap(TNSArray.OCClass.arrayWithObjects(@Attribs[0], 1));
// Result := (AttrArray as ILocalObject).GetObjectID;
end;
procedure TFMXViewBase.doCommandBySelector(selector: SEL);
begin
NativeView.doCommandBySelector(selector);
end;
function TFMXViewBase.drawsVerticallyForCharacterAtIndex(charIndex: NSUInteger): Boolean;
begin
Result := False;
end;
function TFMXViewBase.fractionOfDistanceThroughGlyphForPoint(aPoint: NSPoint): CGFloat;
begin
Result := 0;
end;
procedure TFMXViewBase.frameChanged(notification: NSNotification);
var
ContentFrame: NSRect;
begin
ContentFrame := NativeView.frame;
try
FOwner.Wnd.RecreateResources;
TOpenCustomForm(FOwner.Wnd).Realign;
except
HandleException(Self);
end;
end;
function TFMXViewBase.windowLevel: NSInteger;
begin
Result := NativeView.window.level;
end;
function TFMXViewBase.FocusedTextService: TTextServiceCocoa;
var
TSC : ITextInput;
begin
Result := nil;
if Owner <> nil then
if Owner.Wnd <> nil then
if Supports(FOwner.Wnd.Focused, ITextInput, TSC) then
Result := TTextServiceCocoa(TSC.GetTextService);
end;
procedure TFMXViewBase.UpdateTextServiceControl;
var
TSC: ITextInput;
begin
if (FOwner.Wnd.Focused <> Nil) and Supports(FOwner.Wnd.Focused, ITextInput, TSC) then
begin
TTextServiceCocoa( TSC.GetTextService ).SetMarkedRange(FMarkedRange);
TTextServiceCocoa( TSC.GetTextService ).SetSelectedRange(FSelectedRange);
end;
end;
function TFMXViewBase.attributedString: NSAttributedString;
begin
Result := FBackingStore;
end;
function TFMXViewBase.attributedSubstringForProposedRange(aRange: NSRange;
actualRange: PNSRange): NSAttributedString;
begin
// Get a valid range
if actualRange <> nil then
begin
if (aRange.location <> NSNotFound) and (aRange.location < (FBackingStore.length - 1)) then
actualRange^.location := aRange.location
else
actualRange^.location := 0;
if (aRange.length) <= (FBackingStore.length - actualRange^.location) then
actualRange^.length := aRange.length
else
actualRange^.length := FBackingStore.length - actualRange^.location - 1;
// Get the backing store matching the range
if (actualRange^.location = 0) and (actualRange^.length = FBackingStore.length) then
begin
Result := FBackingStore;
end
else
begin
Result := TNSAttributedString.Wrap(FBackingStore.attributedSubstringFromRange(actualRange^));
end;
end
else
Result := nil;
end;
function TFMXViewBase.baselineDeltaForCharacterAtIndex(
anIndex: NSUInteger): CGFloat;
begin
Result := 0;
end;
function TFMXViewBase.characterIndexForPoint(aPoint: NSPoint): NSUInteger;
begin
Result := 0;
end;
function TFMXViewBase.markedRange: NSRange;
begin
Result := FMarkedRange;
end;
{ TFMXWindow}
function TFMXWindow.GetObjectiveCClass: PTypeInfo;
begin
Result := TypeInfo(FMXWindow);
end;
function TFMXWindow.GetView: NSView;
begin
Result := FViewObj.NativeView;
end;
function TFMXWindow.windowShouldClose(Sender: Pointer): Boolean;
var
Action: TCloseAction;
begin
Result := False;
if Application = nil then
Exit;
if Application.Terminated then
Exit;
try
Action := Wnd.Close;
Result := Action in [TCloseAction.caHide, TCloseAction.caFree];
except
HandleException(Self);
end;
end;
procedure TFMXWindow.windowWillClose(notification: NSNotification);
var
LParent: NSWindow;
begin
if (Application <> nil) and (Application.MainForm <> nil) then
begin
LParent := WindowHandleToPlatform(Wnd.Handle).Wnd;
while (LParent <> nil) and (LParent <> WindowHandleToPlatform(Application.MainForm.Handle).Wnd) do
LParent := LParent.ParentWindow;
if LParent <> nil then
Application.Terminate;
end;
end;
procedure TFMXWindow.windowDidBecomeKey(notification: NSNotification);
begin
if Wnd.FormStyle <> TFormStyle.Popup then
begin
if (PlatformCocoa <> nil) and (not PlatformCocoa.FDisableClosePopups) then
begin
TPlatformCocoa.PrepareClosePopups(Wnd);
TPlatformCocoa.ClosePopupForms;
end;
try
if PlatformCocoa.FAlertCount = 0 then
Wnd.Activate;
except
HandleException(Self);
end;
end;
end;
procedure TFMXWindow.windowDidChangeBackingProperties(notification: NSNotification);
begin
if (Wnd = nil) or (Application = nil) or (Application.Terminated) then
Exit;
try
Wnd.RecreateResources;
TMessageManager.DefaultManager.SendMessage(nil, TScaleChangedMessage.Create(Wnd), True);
except
HandleException(Self);
end;
end;
procedure TFMXWindow.windowDidResignKey(notification: NSNotification);
begin
if (Wnd = nil) or (Application = nil) or (Application.Terminated) then
Exit;
try
Wnd.Deactivate;
except
HandleException(Self);
end;
end;
procedure TFMXWindow.UpdateWindowState;
var
NSWin: NSWindow;
begin
if (Wnd <> nil) and PlatformCocoa.FCanSetState then
begin
PlatformCocoa.FCanSetState := False;
try
NSWin := WindowHandleToPlatform(Wnd.Handle).Wnd;
if NSWin.isMiniaturized then
Wnd.WindowState := TWindowState.wsMinimized
else if IsZoomed(NSWin) then
Wnd.WindowState := TWindowState.wsMaximized
else
Wnd.WindowState := TWindowState.wsNormal;
finally
PlatformCocoa.FCanSetState := True;
end;
end;
end;
procedure TFMXWindow.windowDidResize(notification: NSNotification);
var
LFrame: NSRect;
AutoReleasePool: NSAutoreleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
UpdateWindowState;
LFrame := NSWindow(Super).frame;
try
Wnd.SetBounds(round(LFrame.origin.x),
round(MainScreenHeight - LFrame.origin.y - LFrame.size.height),
round(LFrame.size.width), round(LFrame.size.height));
except
HandleException(Self);
end;
finally
AutoReleasePool.release;
end;
end;
procedure TFMXWindow.windowDidMiniaturize(notification: NSNotification);
begin
UpdateWindowState;
end;
procedure TFMXWindow.windowDidDeminiaturize(notification: NSNotification);
begin
UpdateWindowState;
end;
procedure TFMXWindow.windowDidEnterFullScreen(notification: NSNotification);
begin
UpdateWindowState;
end;
procedure TFMXWindow.windowDidExitFullScreen(notification: NSNotification);
var
NSWin: NSWindow;
begin
if (Wnd <> nil) and PlatformCocoa.FCanSetState and (not Wnd.Visible) then
begin
PlatformCocoa.FCanSetState := False;
try
NSWin := WindowHandleToPlatform(Wnd.Handle).Wnd;
PlatformCocoa.SetShowFullScreenIcon(Wnd, Wnd.ShowFullScreenIcon);
NSWin.orderOut(nil);
finally
PlatformCocoa.FCanSetState := True;
end;
end;
UpdateWindowState;
end;
procedure TFMXWindow.windowDidMove(notification: NSNotification);
var
LFrame: NSRect;
AutoReleasePool: NSAutoreleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
LFrame := NSWindow(Super).frame;
try
Wnd.SetBounds(round(LFrame.origin.x),
round(MainScreenHeight - LFrame.origin.y - LFrame.size.height),
round(LFrame.size.width), round(LFrame.size.height));
except
HandleException(Self);
end;
finally
AutoReleasePool.release;
end;
end;
var
GlobalData: TDragObject;
function GetDataObject(sender: NSDraggingInfo): TDragObject;
var
PBoard: NSPasteboard;
Str: NSString;
Arr: NSArray;
W: string;
I: Integer;
AutoReleasePool: NSAutoreleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
FillChar(Result, SizeOf(Result), 0);
PBoard := sender.draggingPasteboard;
if PBoard.types.containsObject(NSObjectToID(NSFMXPboardType)) then
begin
Result := GlobalData;
Exit;
end;
if PBoard.types.containsObject(NSObjectToID(NSPasteboardTypeString)) then
begin
Str := PBoard.stringForType(NSPasteboardTypeString);
W := NSStrToStr(str);
Result.Data := W;
end;
if PBoard.types.containsObject(NSObjectToID(NSFilenamesPboardType)) then
begin
Arr := TNSArray.Wrap(PBoard.propertyListForType(NSFilenamesPboardType));
SetLength(Result.Files, Arr.count);
for I := 0 to Arr.count - 1 do
begin
Str := TNSString.Wrap(Arr.objectAtIndex(I));
W := NSStrToStr(Str);
Result.Files[I] := W;
end;
end;
finally
AutoReleasePool.release;
end;
end;
function TFMXWindow.draggingEntered(Sender: Pointer): NSDragOperation;
var
mp: NSPoint;
P: TPointF;
DragInfo: NSDraggingInfo;
AutoReleasePool: NSAutoreleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
DragInfo := TNSDraggingInfo.Wrap(Sender);
mp := DragInfo.draggingLocation;
mp.y := View.bounds.size.height - mp.y;
P := PointF(mp.x, mp.y);
try
Wnd.DragEnter(GetDataObject(DragInfo), Wnd.ClientToScreen(P));
except
HandleException(Self);
end;
Result := NSDragOperationEvery;
finally
AutoReleasePool.release;
end;
end;
procedure TFMXWindow.draggingExited(Sender: Pointer {id});
begin
try
Wnd.DragLeave;
except
HandleException(Self);
end;
end;
function TFMXWindow.draggingUpdated(Sender: Pointer): NSDragOperation;
var
mp: NSPoint;
P: TPointF;
Operation: TDragOperation;
DragInfo: NSDraggingInfo;
AutoReleasePool: NSAutoreleasePool;
begin
Result := NSDragOperationNone;
AutoReleasePool := TNSAutoreleasePool.Create;
try
DragInfo := TNSDraggingInfo.Wrap(Sender);
mp := DragInfo.draggingLocation;
mp.y := View.bounds.size.height - mp.y;
P := mp.ToPointF;
Operation := TDragOperation.None;
try
Wnd.DragOver(GetDataObject(DragInfo), Wnd.ClientToScreen(P), Operation);
except
HandleException(Self);
end;
case Operation of
TDragOperation.None:
Result := NSDragOperationNone;
TDragOperation.Move:
Result := NSDragOperationMove;
TDragOperation.Copy:
Result := NSDragOperationCopy;
TDragOperation.Link:
Result := NSDragOperationLink;
end;
DragOperation := Result;
finally
AutoReleasePool.release;
end;
end;
function TFMXWindow.performDragOperation(Sender: Pointer): Boolean;
var
mp: NSPoint;
P: TPointF;
DragInfo: NSDraggingInfo;
AutoReleasePool: NSAutoreleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
DragInfo := TNSDraggingInfo.Wrap(Sender);
mp := DragInfo.draggingLocation;
mp.y := View.bounds.size.height - mp.y;
P := mp.ToPointF;
try
Wnd.DragDrop(GetDataObject(DragInfo), Wnd.ClientToScreen(P));
except
HandleException(Self);
end;
Result := True;
finally
AutoReleasePool.release;
end;
end;
function TFMXWindow.performKeyEquivalent(event: NSEvent): Boolean;
var
AutoReleasePool: NSAutoreleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
Result := False;
if NSObjectToID(NSWindow(Super).firstResponder) = NSObjectToID(GetView) then
begin
//IME's conversion window.is active.
if (FViewObj <> nil) and FViewObj.hasMarkedText then
Exit;
if not PlatformCocoa.FPerformKeyExecuted then
Result := PlatformCocoa.KeyProc(Self, Wnd, event, True, True);
PlatformCocoa.FPerformKeyExecuted := True;
end;
finally
AutoReleasePool.release;
end;
end;
function TFMXWindow.CanActivate: Boolean;
begin
Result := (Wnd <> nil) and (Wnd.Handle <> nil) and (Wnd.FormStyle <> TFormStyle.Popup) and
((PlatformCocoa.FModalStack = nil) or (PlatformCocoa.FModalStack.Count = 0) or
(PlatformCocoa.FModalStack.Peek = Wnd));
end;
function TFMXWindow.acceptsFirstResponder: Boolean;
begin
Result := CanActivate;
end;
function TFMXWindow.becomeFirstResponder: Boolean;
begin
Result := True;
end;
function TFMXWindow.resignFirstResponder: Boolean;
begin
Result := True;
end;
function TFMXWindow.canBecomeKeyWindow: Boolean;
begin
Result := CanActivate;
end;
function TFMXWindow.canBecomeMainWindow: Boolean;
begin
Result := CanActivate;
end;
destructor TFMXWindow.Destroy;
begin
if FViewObj <> nil then
begin
FViewObj.NativeView.setHidden(True);
NSWindow(Super).setContentView(nil);
// A reference for the paint context was manually added when the window was
// created. Clear the reference here to avoid leaking view objects.
FViewObj._Release;
FViewObj := nil;
end;
if FDelegate <> nil then
begin
FDelegate := nil;
NSWindow(Super).setDelegate(nil);
end;
if Assigned(Wnd.Handle) then
NSWindow(Super).close;
Wnd := nil;
NSWindow(Super).release;
inherited;
end;
{ TFMXWindowDelegate }
type
TFMXWindowDelegate = class(TOCLocal, NSWindowDelegate)
private
FWindow: TFMXWindow;
public
constructor Create(AOwner: TFMXWindow);
destructor Destroy; override;
function windowShouldClose(Sender: Pointer {id}): Boolean; cdecl;
procedure windowWillClose(notification: NSNotification); cdecl;
procedure windowDidBecomeKey(notification: NSNotification); cdecl;
procedure windowDidResignKey(notification: NSNotification); cdecl;
procedure windowDidResize(notification: NSNotification); cdecl;
procedure windowDidMiniaturize(notification: NSNotification); cdecl;
procedure windowDidDeminiaturize(notification: NSNotification); cdecl;
procedure windowDidEnterFullScreen(notification: NSNotification); cdecl;
procedure windowDidExitFullScreen(notification: NSNotification); cdecl;
procedure windowDidMove(notification: NSNotification); cdecl;
procedure windowDidChangeBackingProperties(notification: NSNotification); cdecl;
end;
constructor TFMXWindowDelegate.Create(AOwner: TFMXWindow);
begin
inherited Create;
FWindow := AOwner;
end;
destructor TFMXWindowDelegate.Destroy;
begin
FWindow := nil;
objc_msgSend(GetObjectID, sel_getUid('release'));
inherited;
end;
procedure TFMXWindowDelegate.windowDidBecomeKey(notification: NSNotification);
begin
FWindow.windowDidBecomeKey(notification);
end;
procedure TFMXWindowDelegate.windowDidChangeBackingProperties(notification: NSNotification);
begin
FWindow.windowDidChangeBackingProperties(notification);
end;
procedure TFMXWindowDelegate.windowDidMove(notification: NSNotification);
begin
FWindow.windowDidMove(notification);
end;
procedure TFMXWindowDelegate.windowDidResignKey(notification: NSNotification);
begin
FWindow.windowDidResignKey(notification);
end;
procedure TFMXWindowDelegate.windowDidResize(notification: NSNotification);
begin
FWindow.windowDidResize(notification);
end;
procedure TFMXWindowDelegate.windowDidDeminiaturize(notification: NSNotification);
begin
FWindow.windowDidDeminiaturize(notification);
end;
procedure TFMXWindowDelegate.windowDidEnterFullScreen(notification: NSNotification);
begin
FWindow.windowDidEnterFullScreen(notification);
end;
procedure TFMXWindowDelegate.windowDidExitFullScreen(notification: NSNotification);
begin
FWindow.windowDidExitFullScreen(notification);
end;
procedure TFMXWindowDelegate.windowDidMiniaturize(notification: NSNotification);
begin
FWindow.windowDidMiniaturize(notification);
end;
function TFMXWindowDelegate.windowShouldClose(Sender: Pointer): Boolean;
begin
Result := FWindow.windowShouldClose(Sender);
end;
procedure TFMXWindowDelegate.windowWillClose(notification: NSNotification);
var
NSApp: NSApplication;
ModWin: NSWindow;
AutoReleasePool: NSAutoreleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
NSApp := TNSApplication.Wrap(TNSApplication.OCClass.sharedApplication);
ModWin := NSApp.modalWindow;
if (ModWin <> nil) and (FWindow <> nil) and
((ModWin as ILocalObject).GetObjectID = (FWindow.Super as ILocalObject).GetObjectID) then
NSApp.abortModal;
FWindow.windowWillClose(notification);
finally
AutoReleasePool.release;
end;
end;
function TPlatformCocoa.FindForm(const AHandle: TWindowHandle): TCommonCustomForm;
begin
Result := WindowHandleToPlatform(AHandle).Form;
end;
procedure objc_msgSendNSRect(theReceiver: Pointer; theSelector: Pointer; dirtyRect: NSRect); cdecl;
external libobjc name _PU + 'objc_msgSend';
procedure frameDrawRect(Self: Pointer; _cmd: Pointer; dirtyRect: NSRect); cdecl;
var
nctx: NSGraphicsContext;
windowRect: NSRect;
cornerRadius: Single;
Path: NSBezierPath;
Wnd: NSWindow;
WindowBorder: TWindowBorderCocoa;
Form: TCommonCustomForm;
AutoReleasePool: NSAutoreleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
Wnd := TNSView.Wrap(Self).window;
Form := TMacWindowHandle.FindForm(Wnd);
if (Form <> nil) and Form.Border.IsSupported then
begin
WindowBorder := TWindowBorderCocoa(Form.Border.WindowBorder);
windowRect := Wnd.frame;
windowRect.origin.x := 0;
windowRect.origin.y := 0;
cornerRadius := 4;
nctx := TNSGraphicsContext.Wrap(TNSGraphicsContext.OCClass.currentContext);
CGContextClearRect(nctx.graphicsPort, windowRect);
Path := TNSBezierPath.Wrap(TNSBezierPath.OCClass.bezierPathWithRoundedRect(windowRect, cornerRadius, cornerRadius));
Path.addClip;
CGContextTranslateCTM(nctx.graphicsPort, 0, Wnd.frame.size.height);
// CGContextScaleCTM(nctx.graphicsPort, 1, -1);
WindowBorder.Paint(nctx.graphicsPort);
end
else
begin
objc_msgSendNSRect(Self, sel_getUid('drawRectOriginal:'), dirtyRect);
end;
finally
AutoReleasePool.release;
end;
end;
procedure TPlatformCocoa.HookFrame(const NSWin: NSWindow);
const
{$IFDEF CPU64BITS}
MethodTypeString = 'v@:@{NSRect={NSPoint=dd}{NSSize=dd}}';
{$ELSE !CPU64BITS}
MethodTypeString = 'v@:@{NSRect={NSPoint=ff}{NSSize=ff}}';
{$ENDIF CPU64BITS}
var
FrameClass: Pointer;
M1, M2: Pointer;
AutoReleasePool: NSAutoreleasePool;
begin
Inc(FClassHookCount);
if FClassHookCount > 1 then Exit;
AutoReleasePool := TNSAutoreleasePool.Create;
try
// Replace drawRect method on window frame
FrameClass := object_getClass(TNSView.Wrap(NSWin.contentView).superview);
class_addMethod(FrameClass, sel_getUid('drawRectOriginal:'), @frameDrawRect, MethodTypeString);
M1 := class_getInstanceMethod(FrameClass, sel_getUid('drawRect:'));
M2 := class_getInstanceMethod(FrameClass, sel_getUid('drawRectOriginal:'));
method_exchangeImplementations(M1, M2);
//
finally
AutoReleasePool.release;
end;
end;
procedure TPlatformCocoa.UnHookFrame(const NSWin: NSWindow);
var
FrameClass: Pointer;
M1, M2: Pointer;
AutoReleasePool: NSAutoreleasePool;
begin
Dec(FClassHookCount);
if FClassHookCount > 0 then Exit;
AutoReleasePool := TNSAutoreleasePool.Create;
try
// restore old
FrameClass := object_getClass(TNSView.Wrap(NSWin.contentView).superview);
M1 := class_getInstanceMethod(FrameClass, sel_getUid('drawRect:'));
M2 := class_getInstanceMethod(FrameClass, sel_getUid('drawRectOriginal:'));
method_exchangeImplementations(M1, M2);
finally
AutoReleasePool.release;
end;
end;
function TPlatformCocoa.CreateWindow(const AForm: TCommonCustomForm): TWindowHandle;
var
Style: NSUInteger;
FMXWin: TFMXWindow;
NSWin: NSWindow;
NSTitle: NSString;
R: NSRect;
LocalObj: ILocalObject;
DraggedTypes: array[0..3] of Pointer;
RegTypes: NSArray;
PaintControl: IPaintControl;
AutoReleasePool: NSAutoReleasePool;
LParentWindow: NSWindow;
ParentLevel, NewLevel: NSInteger;
ContentView: NSView;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
FMXWin := TFMXWindow.Create;
NSWin := NSWindow(FMXWin.Super);
if AForm.Transparency or (AForm.BorderStyle = TFmxFormBorderStyle.None) then
Style := NSBorderlessWindowMask
else
begin
Style := NSTitledWindowMask or NSUnifiedTitleAndToolbarWindowMask;
if AForm.BorderStyle <> TFmxFormBorderStyle.None then
begin
if TBorderIcon.biMinimize in AForm.BorderIcons then
Style := Style or NSMiniaturizableWindowMask;
if TBorderIcon.biMaximize in AForm.BorderIcons then
Style := Style or NSWindowZoomButton;
if TBorderIcon.biSystemMenu in AForm.BorderIcons then
Style := Style or NSClosableWindowMask;
end;
if AForm.BorderStyle in [TFmxFormBorderStyle.Sizeable, TFmxFormBorderStyle.SizeToolWin] then
Style := Style or NSResizableWindowMask;
end;
R := TNSWindow.OCClass.contentRectForFrameRect(MakeNSRect(AForm.Left, MainScreenHeight - AForm.Top - AForm.height,
AForm.width, AForm.height), Style);
NSWin.initWithContentRect(R, Style, NSBackingStoreBuffered, False);
NSWin.setAcceptsMouseMovedEvents(True);
NSWin.setReleasedWhenClosed(False);
NSWin.setShowsToolbarButton(True);
NSWin.setBackgroundColor(TNSColor.Wrap(TNSColor.OCClass.clearColor));
if Supports(NSWin, NSPanel) then
begin
(NSWin as NSPanel).setBecomesKeyOnlyIfNeeded(True);
(NSWin as NSPanel).setWorksWhenModal(True);
(NSWin as NSPanel).setFloatingPanel(True);
end;
NSWin.useOptimizedDrawing(True);
NSTitle := StrToNSStr(AForm.Caption);
NSWin.setTitle(NSTitle);
// set level of window
case TOpenCustomForm(AForm).FormStyle of
TFormStyle.Popup: NewLevel := kCGMinimumWindowLevelKey;
TFormStyle.StayOnTop: NewLevel := kCGFloatingWindowLevelKey;
else
NewLevel := kCGBaseWindowLevelKey;
end;
if (AForm.ParentForm <> nil) and (AForm.ParentForm.Handle <> nil) then
begin
LParentWindow := WindowHandleToPlatform(AForm.ParentForm.Handle).Wnd;
if LParentWindow <> nil then
begin
ParentLevel := LParentWindow.level;
if ParentLevel < kCGScreenSaverWindowLevelKey then
Inc(ParentLevel);
NewLevel := Max(NewLevel, ParentLevel);
end;
end;
NSWin.setLevel(NewLevel);
FMXWin.Wnd := AForm;
HookFrame(NSWin);
R := MakeNSRect(0, 0, R.size.width, R.size.height);
FMXWin.FViewObj := TFMXView.Create(FMXWin, R);
if Supports(FMXWin.FViewObj, ILocalObject, LocalObj) then
begin
if Supports(AForm, IPaintControl, PaintControl) then
PaintControl.ContextHandle := THandle(LocalObj.GetObjectID);
FMXWin.FViewObj._AddRef;
end;
FMXWin.View.setAutoresizingMask(NSViewWidthSizable or NSViewHeightSizable);
ContentView := TNSView.Wrap(NSWin.contentView);
ContentView.setAutoresizesSubviews(True);
ContentView.addSubview(FMXWin.View);
ContentView.setWantsLayer(True);
if AForm.Transparency then
begin
NSWin.setOpaque(False);
NSWin.setHasShadow(False);
end
else
NSWin.setOpaque(True);
DraggedTypes[0] := NSObjectToID(NSPasteboardTypeString);
DraggedTypes[1] := NSObjectToID(NSFMXPBoardtype);
DraggedTypes[2] := NSObjectToID(NSFilenamesPboardType);
DraggedTypes[3] := nil;
RegTypes := TNSArray.Wrap(TNSArray.OCClass.arrayWithObjects(@DraggedTypes[0], 3));
NSWin.registerForDraggedTypes(RegTypes);
FMXWin.FDelegate := TFMXWindowDelegate.Create(FMXWin);
NSWin.setDelegate(FMXWin.FDelegate);
Result := TMacWindowHandle.Create(FMXWin);
finally
AutoReleasePool.release;
end;
end;
function TPlatformCocoa.CreateWindowBorder(const AForm: TCommonCustomForm): TWindowBorder;
begin
Result := FMX.Forms.Border.Mac.CreateWindowBorder(AForm);
end;
procedure TPlatformCocoa.DestroyWindow(const AForm: TCommonCustomForm);
var
NSWin: NSWindow;
LFMXWindow: TFMXWindow;
PaintControl: IPaintControl;
AutoReleasePool: NSAutoreleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
if AForm.Handle <> nil then
begin
LFMXWindow := TFMXWindow(WindowHandleToPlatform(AForm.Handle).Handle);
LFMXWindow.FViewObj.FOwner := nil;
NSWin := WindowHandleToPlatform(AForm.Handle).Wnd;
NSWin.setParentWindow(nil);
UnHookFrame(NSWin);
if NSWin.isVisible then
NSWin.orderOut(nil);
if Supports(AForm, IPaintControl, PaintControl) then
PaintControl.ContextHandle := 0;
end;
finally
AutoReleasePool.release;
end;
end;
procedure TPlatformCocoa.ReleaseWindow(const AForm: TCommonCustomForm);
begin
if AForm <> nil then
DoReleaseWindow(AForm);
end;
procedure TPlatformCocoa.DoReleaseWindow(AForm: TCommonCustomForm);
var
AutoReleasePool: NSAutoreleasePool;
LDisableClosePopups: Boolean;
Wnd: NSWindow;
begin
if AForm <> nil then
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
if AForm.Handle <> nil then
begin
LDisableClosePopups := FDisableClosePopups;
try
if AForm.FormStyle = TFormStyle.Popup then
FDisableClosePopups := True;
if (AForm.FormStyle = TFormStyle.Popup) and
(AForm.ParentForm <> nil) and
(AForm.ParentForm.FormStyle = TFormStyle.Popup) then
begin
Wnd := WindowHandleToPlatform(AForm.ParentForm.Handle).Wnd;
if (Wnd <> nil) and (NSApp <> nil) then
Wnd.makeKeyAndOrderFront(NSObjectToID(NSApp));
end;
Wnd := WindowHandleToPlatform(AForm.Handle).Wnd;
if Wnd <> nil then
begin
Wnd.setOneShot(True);
Wnd.orderOut(nil);
end;
finally
FDisableClosePopups := LDisableClosePopups;
end;
end;
finally
AutoReleasePool.release;
end;
end;
end;
procedure TPlatformCocoa.SetWindowRect(const AForm: TCommonCustomForm; ARect: TRectF);
var
AutoReleasePool: NSAutoreleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
WindowHandleToPlatform(AForm.Handle).Wnd.setFrame(MakeNSRect(ARect.Left, MainScreenHeight - ARect.Bottom,
ARect.Right - ARect.Left, ARect.Bottom - ARect.Top), True);
finally
AutoReleasePool.release;
end;
end;
function TPlatformCocoa.GetWindowRect(const AForm: TCommonCustomForm): TRectF;
var
NSWin: NSWindow;
AutoReleasePool: NSAutoreleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
NSWin := WindowHandleToPlatform(AForm.Handle).Wnd;
Result := TRectF.Create(NSWin.frame.origin.x, MainScreenHeight - NSWin.frame.origin.y - NSWin.frame.size.height,
NSWin.frame.origin.x + NSWin.frame.size.width, MainScreenHeight - NSWin.frame.origin.y);
finally
AutoReleasePool.release;
end;
end;
function TPlatformCocoa.GetWindowScale(const AForm: TCommonCustomForm): Single;
begin
Result := WindowHandleToPlatform(AForm.Handle).Wnd.backingScaleFactor;
end;
procedure TPlatformCocoa.InputQuery(const ACaption: string; const APrompts, ADefaultValues: array of string;
const ACloseQueryProc: TInputCloseQueryProc);
var
LResult: TModalResult;
LValues: array of string;
I: Integer;
begin
SetLength(LValues, Length(ADefaultValues));
for I := Low(ADefaultValues) to High(ADefaultValues) do
LValues[I] := ADefaultValues[I];
if InputQuery(ACaption, APrompts, LValues) then
LResult := mrOk
else
LResult := mrCancel;
if Assigned(ACloseQueryProc) then
ACloseQueryProc(LResult, LValues);
end;
procedure TPlatformCocoa.InvalidateImmediately(const AForm: TCommonCustomForm);
begin
InvalidateWindowRect(AForm, AForm.ClientRect);
end;
procedure TPlatformCocoa.InvalidateWindowRect(const AForm: TCommonCustomForm; R: TRectF);
var
View: NSView;
AutoReleasePool: NSAutoreleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
if IntersectRect(R, RectF(0, 0, AForm.width, AForm.height)) then
begin
View := WindowHandleToPlatform(AForm.Handle).View;
View.setNeedsDisplayInRect(MakeNSRect(R.Left, View.bounds.size.height - R.Bottom, R.Width, R.Height));
end;
finally
AutoReleasePool.release;
end;
end;
function TPlatformCocoa.IsMenuBarOnWindowBorder: Boolean;
begin
Result := False;
end;
constructor TFMXAlertDelegate.Create;
begin
inherited;
end;
function TFMXAlertDelegate.GetObjectID: Pointer;
begin
Result := inherited;
end;
function TFMXAlertDelegate.GetObjectiveCClass: PTypeInfo;
begin
Result := TypeInfo(AlertDelegate);
end;
procedure TFMXAlertDelegate.alertDidEndSelector(alert: Pointer; returnCode: NSInteger; contextInfo: Pointer);
var
R: NSInteger;
begin
R := returnCode - NSAlertFirstButtonReturn;
if InRange(R, 0, High(Results)) then
Result := Results[R]
else
Result := mrCancel;
Modal := False;
end;
var
MsgTitles: array[TMsgDlgType] of string = (SMsgDlgWarning, SMsgDlgError, SMsgDlgInformation, SMsgDlgConfirm, '');
ModalResults: array[TMsgDlgBtn] of Integer = (
mrYes, mrNo, mrOk, mrCancel, mrAbort, mrRetry, mrIgnore,
mrAll, mrNoToAll, mrYesToAll, 0, mrClose);
ButtonCaptions: array[TMsgDlgBtn] of string = (
SMsgDlgYes, SMsgDlgNo, SMsgDlgOK, SMsgDlgCancel, SMsgDlgAbort,
SMsgDlgRetry, SMsgDlgIgnore, SMsgDlgAll, SMsgDlgNoToAll, SMsgDlgYesToAll,
SMsgDlgHelp, SMsgDlgClose);
function TPlatformCocoa.MessageDialog(const AMessage: string; const ADialogType: TMsgDlgType;
const AButtons: TMsgDlgButtons; const ADefaultButton: TMsgDlgBtn; const AX, AY: Integer; const AHelpCtx: THelpContext;
const AHelpFileName: string): Integer;
var
Alert: NSAlert;
Delegate: TFMXAlertDelegate;
Session: NSModalSession;
NSWin: NSWindow;
S: SEL;
ActiveForm: TCommonCustomForm;
R: NSInteger;
AutoReleasePool: NSAutoreleasePool;
procedure AddButtons(IsDefault: Boolean);
var
B: TMsgDlgBtn;
procedure AddBtn(B: TMsgDlgBtn);
begin
SetLength(Delegate.Results, Length(Delegate.Results) + 1);
Delegate.Results[High(Delegate.Results)] := ModalResults[B];
Alert.addButtonWithTitle(StrToNSStr(ButtonCaptions[B]));
end;
begin
for B := Low(TMsgDlgBtn) to High(TMsgDlgBtn) do
if (B in AButtons) and (IsDefault xor (B <> ADefaultButton)) then
AddBtn(B);
if (not IsDefault) and (Length(Delegate.Results) = 0) then
AddBtn(ADefaultButton);
end;
begin
ActiveForm := nil;
AutoReleasePool := TNSAutoreleasePool.Create;
try
Delegate := TFMXAlertDelegate.Create;
try
Delegate.Modal := True;
if Screen <> nil then
begin
PrepareClosePopups(nil);
ClosePopupForms;
ActiveForm := Screen.ActiveForm;
if (ActiveForm <> nil) and (ActiveForm.Visible) and (ActiveForm.Handle <> nil) and
not (ActiveForm.Owner is TPopup) then
begin
NSWin := WindowHandleToPlatform(ActiveForm.Handle).Wnd;
if NSWin <> nil then
NSWin.retain;
end;
end;
S := sel_getUid('alertDidEndSelector:returnCode:contextInfo:');
Alert := TNSAlert.Create;
Alert.setInformativeText(StrToNSStr(AMessage));
Alert.setMessageText(StrToNSStr(MsgTitles[ADialogType]));
if ADialogType = TMsgDlgType.mtWarning then
Alert.setAlertStyle(NSWarningAlertStyle)
else if ADialogType = TMsgDlgType.mtError then
Alert.setAlertStyle(NSCriticalAlertStyle)
else
Alert.setAlertStyle(NSInformationalAlertStyle);
AddButtons(True);
AddButtons(False);
if NSWin <> nil then
begin
Alert.beginSheetModalForWindow(NSWin, Delegate.GetObjectID, S, nil);
if TFmxFormState.Modal in ActiveForm.FormState then
Session := nil
else
Session := NSApp.beginModalSessionForWindow(NSWin);
Inc(FAlertCount);
try
while Delegate.Modal do
begin
if Session <> nil then
NSApp.runModalSession(Session);
HookObserverCallback(False);
end;
finally
Dec(FAlertCount);
if Session <> nil then
NSApp.endModalSession(Session);
end;
Result := Delegate.Result;
end
else
begin
R := Alert.runModal - NSAlertFirstButtonReturn;
if (R >= 0) and (R < Length(Delegate.Results)) then
Result := Delegate.Results[R]
else
Result := mrCancel;
end;
finally
if NSWin <> nil then
NSWin.release;
if (ActiveForm <> nil) and (FAlertCount = 0) then
ActiveForm.Activate;
end;
finally
AutoReleasePool.release;
end;
end;
procedure TPlatformCocoa.MessageDialog(const AMessage: string; const ADialogType: TMsgDlgType;
const AButtons: TMsgDlgButtons; const ADefaultButton: TMsgDlgBtn; const AX, AY: Integer; const AHelpCtx: THelpContext;
const AHelpFileName: string; const ACloseDialogProc: TInputCloseDialogProc);
var
LResult: TModalResult;
begin
LResult := MessageDialog(AMessage, ADialogType, AButtons, ADefaultButton, AX, AY, AHelpCtx, AHelpFileName);
if Assigned(ACloseDialogProc) then
ACloseDialogProc(LResult);
end;
function TPlatformCocoa.InputQuery(const ACaption: string; const APrompts: array of string;
var AValues: array of string; const ACloseQueryFunc: TInputCloseQueryFunc): Boolean;
const
InputWidth = 400;
InputHeight = 24;
VerticalSpacing = 60;
PromptRelativePosition = 36;
function CreatePrompt(const YPos: Single; const Prompt: string; out Password: Boolean): NSTextField;
begin
Result := TNSTextField.Wrap(TNSTextField.Alloc.initWithFrame(MakeNSRect(0, YPos, InputWidth, InputHeight)));
Result.setDrawsBackground(False);
Result.setEditable(False);
Result.setSelectable(False);
Result.setBordered(False);
Result.setBackgroundColor(TNSColor.Wrap(TNSColor.OCClass.clearColor));
Password := (Prompt.Length > 0) and (Prompt.Chars[0] < #32);
Result.setStringValue(StrToNSStr(Prompt.Substring(IfThen(Password, 1, 0))));
end;
function CreateInput(const YPos: Single; const InitialValue: string; const Password: Boolean): NSTextField;
begin
if Password then
Result := TNSSecureTextField.Wrap(TNSSecureTextField.Alloc.initWithFrame(MakeNSRect(0, YPos, InputWidth,
InputHeight)))
else
Result := TNSTextField.Wrap(TNSTextField.Alloc.initWithFrame(MakeNSRect(0, YPos, InputWidth, InputHeight)));
Result.setStringValue(StrToNSStr(InitialValue));
end;
var
Alert: NSAlert;
Delegate: TFMXAlertDelegate;
Session: NSModalSession;
NSWin: NSWindow;
S: SEL;
View: NSView;
Inputs: array of NSTextField;
I: Integer;
ActiveForm: TCommonCustomForm;
AutoReleasePool: NSAutoreleasePool;
Password: Boolean;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
Result := False;
if (Length(AValues) > 0) and (Length(APrompts) > 0) then
begin
ActiveForm := nil;
Delegate := TFMXAlertDelegate.Create;
try
Delegate.Modal := True;
SetLength(Delegate.Results, 2);
Delegate.Results[0] := ModalResults[TMsgDlgBtn.mbOK];
Delegate.Results[1] := ModalResults[TMsgDlgBtn.mbCancel];
if Screen <> nil then
begin
ActiveForm := Screen.ActiveForm;
if (ActiveForm <> nil) and (ActiveForm.Visible) and (ActiveForm.Handle <> nil) and
not (ActiveForm.Owner is TPopup) then
begin
NSWin := WindowHandleToPlatform(ActiveForm.Handle).Wnd;
if NSWin <> nil then
NSWin.retain;
end;
end;
S := sel_getUid('alertDidEndSelector:returnCode:contextInfo:');
Alert := TNSAlert.Wrap(TNSAlert.Alloc.init);
Alert.setMessageText(StrToNSStr(ACaption));
Alert.addButtonWithTitle(StrToNSStr(ButtonCaptions[TMsgDlgBtn.mbOK]));
Alert.addButtonWithTitle(StrToNSStr(ButtonCaptions[TMsgDlgBtn.mbCancel]));
View := TNSView.Wrap(TNSView.Alloc.initWithFrame(MakeNSRect(0, 0, InputWidth, Length(AValues) * VerticalSpacing)));
SetLength(Inputs, Length(AValues));
for I := 0 to High(Inputs) do
begin
View.addSubview(CreatePrompt(View.frame.size.height - I * VerticalSpacing - PromptRelativePosition,
APrompts[I], Password));
Inputs[I] := CreateInput(View.frame.size.height - I * VerticalSpacing - VerticalSpacing, AValues[I], Password);
View.addSubview(Inputs[I]);
end;
Alert.setAccessoryView(View);
if NSWin <> nil then
begin
Alert.beginSheetModalForWindow(NSWin, Delegate.GetObjectID, S, nil);
if TFmxFormState.Modal in ActiveForm.FormState then
Session := nil
else
Session := NSApp.beginModalSessionForWindow(NSWin);
Inc(FAlertCount);
try
while Delegate.Modal do
begin
if Session <> nil then
NSApp.runModalSession(Session);
HookObserverCallback(False);
end;
finally
Dec(FAlertCount);
if Session <> nil then
NSApp.endModalSession(Session);
end;
Result := Delegate.Result = mrOk;
end
else
Result := Alert.runModal = NSAlertFirstButtonReturn;
for I := 0 to High(Inputs) do
AValues[I] := NSStrToStr(Inputs[I].stringValue);
finally
if NSWin <> nil then
NSWin.release;
if (ActiveForm <> nil) and (FAlertCount = 0) then
ActiveForm.Activate;
end;
end;
finally
AutoReleasePool.release;
end;
end;
function TPlatformCocoa.AllocHandle(const Objc: IObjectiveC): TFmxHandle;
begin
Result := NewFmxHandle;
TMonitor.Enter(FObjectiveCMap);
try
FObjectiveCMap.Add(Result, Objc);
finally
TMonitor.Exit(FObjectiveCMap);
end;
end;
function TPlatformCocoa.NewFmxHandle: TFmxHandle;
begin
{$IFDEF CPUX64}
Result := TInterlocked.Add(Int64(FHandleCounter), 16);
{$ENDIF}
{$IFDEF CPUX86}
Result := TInterlocked.Add(Integer(FHandleCounter), 16);
{$ENDIF}
end;
procedure TPlatformCocoa.SetWindowCaption(const AForm: TCommonCustomForm; const ACaption: string);
var
NSWin: NSWindow;
AutoReleasePool: NSAutoreleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
NSWin := WindowHandleToPlatform(AForm.Handle).Wnd;
NSWin.setTitle(StrToNSStr(ACaption));
finally
AutoReleasePool.release;
end;
end;
procedure TPlatformCocoa.SetWindowState(const AForm: TCommonCustomForm; const AState: TWindowState);
var
NSWin: NSWindow;
AutoReleasePool: NSAutoreleasePool;
begin
if (AForm.Visible or (TFmxFormState.Showing in AForm.FormState)) and FCanSetState then
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
NSWin := WindowHandleToPlatform(AForm.Handle).Wnd;
if NSWin <> nil then
begin
if (NSWin.styleMask and NSFullScreenWindowMask) <> 0 then
AForm.WindowState := TWindowState.wsMaximized
else
case AState of
TWindowState.wsMinimized:
if not NSWin.isMiniaturized then
NSWin.miniaturize(nil);
TWindowState.wsNormal:
begin
if NSWin.isMiniaturized then
NSWin.deminiaturize(nil);
if IsZoomed(NSWin) then
NSWin.zoom(nil);
end;
TWindowState.wsMaximized:
begin
if NSWin.isMiniaturized then
NSWin.deminiaturize(nil);
if not IsZoomed(NSWin) then
NSWin.zoom(nil);
end;
end;
end;
finally
AutoReleasePool.release;
end;
end;
end;
procedure TPlatformCocoa.RegisterCanvasClasses;
begin
if GlobalUseGPUCanvas then
FMX.Canvas.GPU.RegisterCanvasClasses;
FMX.Canvas.Mac.RegisterCanvasClasses;
end;
procedure TPlatformCocoa.UnregisterCanvasClasses;
begin
if GlobalUseGPUCanvas then
FMX.Canvas.GPU.UnregisterCanvasClasses;
FMX.Canvas.Mac.UnregisterCanvasClasses;
end;
procedure TPlatformCocoa.RegisterContextClasses;
begin
FMX.Context.Mac.RegisterContextClasses;
end;
procedure TPlatformCocoa.UnregisterContextClasses;
begin
FMX.Context.Mac.UnregisterContextClasses;
end;
procedure TPlatformCocoa.ReleaseCapture(const AForm: TCommonCustomForm);
begin
// Windows.ReleaseCapture;
end;
procedure TPlatformCocoa.SetCapture(const AForm: TCommonCustomForm);
begin
// Windows.SetCapture(AHandle);
end;
function TPlatformCocoa.GetCaretWidth: Integer;
begin
Result := 1;
end;
function TPlatformCocoa.GetMenuShowDelay: Integer;
begin
Result := 150;
end;
function TPlatformCocoa.GetClientSize(const AForm: TCommonCustomForm): TPointF;
var
LView: NSView;
AutoReleasePool: NSAutoreleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
LView := WindowHandleToPlatform(AForm.Handle).View;
Result := PointF(LView.frame.size.width, LView.frame.size.height);
finally
AutoReleasePool.release;
end;
end;
procedure TPlatformCocoa.HideWindow(const AForm: TCommonCustomForm);
var
NSWin: NSWindow;
begin
if (AForm <> nil) and (AForm.Handle <> nil) then
begin
NSWin := WindowHandleToPlatform(AForm.Handle).Wnd;
if NSWin <> nil then
begin
if (NSWin.styleMask and NSFullScreenWindowMask) <> 0 then
begin
NSWin.setCollectionBehavior(NSWindowCollectionBehaviorFullScreenPrimary);
NSWin.toggleFullScreen(nil);
end
else
NSWin.orderOut(nil);
NSWin.setParentWindow(nil);
end;
end;
end;
procedure TPlatformCocoa.ShowWindow(const AForm: TCommonCustomForm);
var
NSWin: NSWindow;
frame: NSRect;
AutoReleasePool: NSAutoReleasePool;
LWindowState: TWindowState;
ParentForm: TCommonCustomForm;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
if (Application <> nil) and (Application.MainForm = AForm) and not FHideUnhideApp then
NSApp.unhideWithoutActivation
else
begin
LWindowState := AForm.WindowState;
NSWin := WindowHandleToPlatform(AForm.Handle).Wnd;
if LWindowState <> TWindowState.wsMinimized then
begin
SetWindowState(AForm, LWindowState);
NSWin.makeKeyAndOrderFront(NSObjectToID(NSApp));
end;
if AForm = Application.MainForm then
begin
NSWin.makeMainWindow;
NSApp.activateIgnoringOtherApps(True);
end
else if IsPopupForm(AForm) then
begin
ParentForm := AForm.ParentForm;
while (ParentForm <> nil) and not (TFmxFormState.Modal in ParentForm.FormState) do
ParentForm := ParentForm.ParentForm;
if ParentForm <> nil then
NSWin.setParentWindow(WindowHandleToPlatform(ParentForm.Handle).Wnd);
end;
SetWindowState(AForm, LWindowState);
frame := NSWin.frame;
AForm.SetBounds(round(frame.origin.x), round(MainScreenHeight - frame.origin.y - frame.size.height),
round(frame.size.width), round(frame.size.height));
end;
finally
AutoReleasePool.release;
end;
end;
procedure TPlatformCocoa.BringToFront(const AForm: TCommonCustomForm);
var
AutoReleasePool: NSAutoreleasePool;
NSWin: NSWindow;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
NSWin := WindowHandleToPlatform(AForm.Handle).Wnd;
if (NSWin <> nil) and NSWin.isVisible then
NSWin.orderFront(nil);
finally
AutoReleasePool.release;
end;
end;
procedure TPlatformCocoa.SendToBack(const AForm: TCommonCustomForm);
var
AutoReleasePool: NSAutoreleasePool;
NSWin: NSWindow;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
NSWin := WindowHandleToPlatform(AForm.Handle).Wnd;
if (NSWin <> nil) and NSWin.isVisible then
NSWin.orderBack(nil);
finally
AutoReleasePool.release;
end;
end;
procedure TPlatformCocoa.Activate(const AForm: TCommonCustomForm);
var
AutoReleasePool: NSAutoreleasePool;
NSWin: NSWindow;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
NSWin := WindowHandleToPlatform(AForm.Handle).Wnd;
NSApp.activateIgnoringOtherApps(True);
NSWin.makeKeyAndOrderFront(NSObjectToID(NSApp));
finally
AutoReleasePool.release;
end;
end;
function TPlatformCocoa.ShowWindowModal(const AForm: TCommonCustomForm): TModalResult;
var
Session: NSModalSession;
MR: NSInteger;
NSWin: NSWindow;
AutoReleasePool: NSAutoreleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
AForm.HandleNeeded;
if FModalStack = nil then
FModalStack := TStack<TCommonCustomForm>.Create;
FRestartModal := False;
FModalStack.Push(AForm);
AForm.Show;
try
Result := mrNone;
NSWin := WindowHandleToPlatform(AForm.Handle).Wnd;
if NSWin <> nil then
NSWin.retain;
AForm.ModalResult := mrNone;
Session := NSApp.beginModalSessionForWindow(NSWin);
AForm.BringToFront;
while True do
begin
MR := NSApp.runModalSession(Session);
// Print and Save dialogs will cause a MR value of NSModalResponseCancel or NSModalResponseOK
if (MR <> NSModalResponseCancel) and (MR <> NSModalResponseOK) and (MR <> NSRunContinuesResponse) then
begin
if FRestartModal then
begin
FRestartModal := False;
NSApp.endModalSession(Session);
Session := NSApp.beginModalSessionForWindow(NSWin);
Continue;
end;
if AForm.Visible then
AForm.Hide;
Result := AForm.ModalResult;
if csDestroying in AForm.ComponentState then
DoReleaseWindow(AForm);
FModalStack.Pop;
if FModalStack.Count > 0 then
FRestartModal := True;
Break;
end;
if AForm.ModalResult <> 0 then
begin
AForm.CloseModal;
if AForm.ModalResult <> 0 then
begin
NSApp.stopModal;
Continue;
end;
end;
HookObserverCallback(False);
end;
NSApp.endModalSession(Session);
finally
if NSWin <> nil then
NSWin.release;
if (FModalStack.Count > 0) and (FModalStack.Peek = AForm) then
FModalStack.Pop;
end;
finally
AutoReleasePool.release;
end;
end;
function TPlatformCocoa.CanShowModal: Boolean;
begin
Result := True;
end;
function TPlatformCocoa.ClientToScreen(const AForm: TCommonCustomForm; const Point: TPointF): TPointF;
var
np: NSPoint;
NSWin: NSWindow;
AutoReleasePool: NSAutoreleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
NSWin := WindowHandleToPlatform(AForm.Handle).Wnd;
np := CGPointMake(Point.X, Point.Y);
np.y := TNSView.Wrap(NSWin.contentView).bounds.size.height - np.y;
Result := CGPointToPointF(NSWin.convertBaseToScreen(np));
Result.y := MainScreenHeight - Result.y;
finally
AutoReleasePool.release;
end;
end;
function TPlatformCocoa.ScreenToClient(const AForm: TCommonCustomForm; const Point: TPointF): TPointF;
var
np: NSPoint;
NSWin: NSWindow;
AutoReleasePool: NSAutoreleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
NSWin := WindowHandleToPlatform(AForm.Handle).Wnd;
np := CGPointMake(Point.X, Point.Y);
np.y := MainScreenHeight - np.y;
Result := CGPointToPointF(NSWin.convertScreenToBase(np));
Result.y := TNSView.Wrap(NSWin.contentView).bounds.size.height - Result.y;
finally
AutoReleasePool.release;
end;
end;
{ Menus }
function TPlatformCocoa.FindFormAtScreenPos(var AForm: TCommonCustomForm; const ScreenMousePos: TPointF): Boolean;
var
I: Integer;
ScreenPos: TPoint;
function Contains(const Form: TCommonCustomForm): Boolean;
var
R: TRect;
begin
Result := False;
if (Form <> nil) and Form.Visible then
begin
if Form is TCustomPopupForm then
R := TRect.Create(TCustomPopupForm(Form).ScreenContentRect.Round)
else
R := TRect.Create(TPoint.Create(Form.Left, Form.Top), Form.Width, Form.Height);
Result := R.Contains(ScreenPos);
if Result then
AForm := Form;
end;
end;
begin
Result := False;
if Screen <> nil then
begin
ScreenPos := TPoint.Create(Round(RoundTo(ScreenMousePos.X, 0)), Round(RoundTo(ScreenMousePos.y, 0)));
// Popups
for I := Screen.PopupFormCount - 1 downto 0 do
if Contains(Screen.PopupForms[I]) then
Exit(True);
// top forms
for I := Screen.FormCount - 1 downto 0 do
if (Screen.Forms[I].FormStyle = TFormStyle.StayOnTop) and Contains(Screen.Forms[I]) then
Exit(True);
// active form
if Contains(Screen.ActiveForm) then
Exit(True);
// other forms
for I := Screen.FormCount - 1 downto 0 do
if (Screen.Forms[I].FormStyle <> TFormStyle.StayOnTop) and Contains(Screen.Forms[I]) then
Exit(True);
end;
end;
function TPlatformCocoa.ShowContextMenu(const AForm: TCommonCustomForm; const AScreenMousePos: TPointF): Boolean;
var
Obj: IControl;
begin
Result := False;
if AForm <> nil then
begin
Obj := IControl(AForm.ObjectAtPoint(AScreenMousePos));
if (Obj <> nil) and (Obj.GetObject <> nil) then
try
Obj.SetFocus;
Result := Obj.ShowContextMenu(AScreenMousePos);
except
HandleException(AForm);
end;
end;
end;
procedure TPlatformCocoa.MenuLoopEvent(const EventRec: TEventRec; var CancelIdle, CancelDefaultAction: Boolean);
procedure EndLoop;
var
LView: IMenuView;
begin
LView := FMenuStack.Peek;
while LView <> nil do
begin
LView.Loop := False;
LView.Selected := nil;
LView := LView.ParentView;
end;
end;
procedure EndLoopAndClose;
var
LView: IMenuView;
begin
EndLoop;
LView := FMenuStack.Peek;
while (LView <> nil) do
begin
if LView.Parent is TPopup then
TPopup(LView.Parent).IsOpen := False;
LView := LView.ParentView;
end;
end;
function IsItemSelectable(const Item: TFmxObject): Boolean;
begin
Result := (Item is TMenuItem) and TMenuItem(Item).Visible and (TMenuItem(Item).Text <> SMenuSeparator);
end;
function ForwardSelectNextMenuItem(AView: IMenuView; AStartInd, AEndInd: Integer): Boolean;
var
I: Integer;
begin
Result := False;
if AView <> nil then
for I := AStartInd to AEndInd do
if IsItemSelectable(AView.GetItem(I)) then
begin
AView.Selected := TMenuItem(AView.GetItem(I));
Result := True;
Break;
end;
end;
function BackwardSelectNextMenuItem(AView: IMenuView; AStartInd, AEndInd: Integer): Boolean;
var
I: Integer;
begin
Result := False;
if AView <> nil then
for I := AStartInd downto AEndInd do
if IsItemSelectable(AView.GetItem(I)) then
begin
AView.Selected := TMenuItem(AView.GetItem(I));
Result := True;
Break;
end;
end;
procedure SelectFirstMenuItem(AView: IMenuView);
var
I: Integer;
begin
if AView <> nil then
begin
I := 0;
while (I < AView.GetItemsCount) and not IsItemSelectable(AView.GetItem(I)) do
Inc(I);
if I < AView.GetItemsCount then
AView.Selected := TMenuItem(AView.GetItem(I));
end;
end;
procedure SelectLastMenuItem(AView: IMenuView);
var
I: Integer;
begin
if AView <> nil then
begin
I := AView.GetItemsCount - 1;
while (I >= 0) and not IsItemSelectable(AView.GetItem(I)) do
Dec(I);
if I >= 0 then
AView.Selected := TMenuItem(AView.GetItem(I));
end;
end;
procedure SelectPrevMenuItem(AView: IMenuView);
begin
if AView <> nil then
if (AView.Selected = nil) or
not BackwardSelectNextMenuItem(AView, AView.Selected.Index - 1, 0) then
SelectLastMenuItem(AView);
end;
procedure SelectNextMenuItem(AView: IMenuView);
begin
if AView <> nil then
if (AView.Selected = nil) or
not ForwardSelectNextMenuItem(AView, AView.Selected.Index + 1, AView.GetItemsCount - 1) then
SelectFirstMenuItem(AView);
end;
function RedirectMouseEventToParentForm(AView: IMenuView): Boolean;
var
Root: IRoot;
Form: TCommonCustomForm;
FormMousePos: TPointF;
LEventRec: TEventRec;
begin
Result := False;
if (AView <> nil) and (AView.Parent <> nil) and (AView.GetObject <> nil) then
begin
Root := AView.GetObject.Root;
if (Root <> nil) and (Root.GetObject is TCommonCustomForm) then
begin
Form := TCommonCustomForm(Root.GetObject);
while (Form <> nil) and (IsPopup(Form)) do
Form := Form.ParentForm;
if (Form <> nil) and (Form.Handle <> nil) and (EventRec.EventKind = TEventKind.MouseDown) then
begin
FormMousePos := Form.ScreenToClient(EventRec.ScreenMousePos);
LEventRec := EventRec;
LEventRec.Form := Form;
LEventRec.FormMousePos := FormMousePos;
LEventRec.Event := nil;
TMouseDownTimer.Create(LEventRec);
Result := True;
end;
end;
end;
end;
procedure FindViewByEvent(var AView: IMenuView; var Item: TMenuItem);
var
Obj: IControl;
begin
AView := nil;
Obj := nil;
Item := nil;
repeat
if AView = nil then
AView := FMenuStack.Peek
else
AView := AView.ParentView;
if AView <> nil then
begin
Obj := AView.ObjectAtPoint(EventRec.ScreenMousePos);
if (Obj <> nil) and (Obj.GetObject is TMenuItem) then
Item := TMenuItem(Obj.GetObject);
end;
until (AView = nil) or (Item <> nil);
end;
var
LForm: TCommonCustomForm;
LFormMousePos: TPointF;
Key: Word;
LView, LCurrentView: IMenuView;
Item: TMenuItem;
begin
if (FMenuStack <> nil) and (FMenuStack.Count > 0) then
begin
LView := FMenuStack.Peek;
case EventRec.EventKind of
TEventKind.Other:
begin
case EventRec.Event.&type of
NSAppKitDefined:
if EventRec.Event.Subtype <> NSWindowMovedEventType then
EndLoopAndClose;
NSSystemDefined:
if not FindFormAtScreenPos(LForm, EventRec.ScreenMousePos) then
EndLoopAndClose;
end;
end;
TEventKind.Key:
begin
Key := EventRec.Event.keyCode;
if EventRec.Event.&type = NSKeyDown then
case Key of
KEY_ENTER, KEY_NUMPADENTER:
if (LView.Selected <> nil) then
begin
if LView.Selected.HavePopup then
LView.Selected.NeedPopup
else
begin
TOpenMenuItem(LView.Selected).Click;
EndLoopAndClose;
end;
end
else
EndLoopAndClose;
KEY_ESC:
begin
LView.Selected := nil;
EndLoopAndClose;
end;
KEY_LEFT:
if (LView.ParentView <> nil) and LView.ParentView.IsMenuBar then
begin
LView.Loop := False;
SelectPrevMenuItem(LView.ParentView);
if LView.ParentView.Selected <> nil then
LView.ParentView.Selected.NeedPopup;
end;
KEY_RIGHT:
if (LView.ParentView <> nil) and LView.ParentView.IsMenuBar then
begin
LView.Loop := False;
SelectNextMenuItem(LView.ParentView);
if LView.ParentView.Selected <> nil then
LView.ParentView.Selected.NeedPopup;
end;
KEY_UP:
SelectPrevMenuItem(LView);
KEY_DOWN:
SelectNextMenuItem(LView);
KEY_HOME, KEY_PAGUP:
SelectFirstMenuItem(LView);
KEY_END, KEY_PAGDN:
SelectLastMenuItem(LView);
end;
CancelDefaultAction := True;
end;
TEventKind.MouseDown:
begin
FindViewByEvent(LCurrentView, Item);
if (Item <> nil) and (LCurrentView = FMenuStack.Peek) then
begin
if not Item.IsSelected and Item.HavePopup then
Item.NeedPopup
else
begin
TOpenMenuItem(Item).Click;
EndLoopAndClose;
end;
end
else if LCurrentView = nil then
begin
RedirectMouseEventToParentForm(LView);
EndLoopAndClose;
CancelDefaultAction := True;
end
else
CancelDefaultAction := True;
end;
TEventKind.MouseMove:
if (LView.GetObject <> nil) and (LView.GetObject.Root is TCommonCustomForm) then
begin
LForm := TCommonCustomForm(LView.GetObject.Root);
LFormMousePos := LForm.ScreenToClient(EventRec.ScreenMousePos);
try
LForm.MouseMove(EventRec.Shift, LFormMousePos.X, LFormMousePos.y);
except
HandleException(LForm);
end;
CancelDefaultAction := True;
CancelIdle := True;
end;
end;
end;
end;
procedure TPlatformCocoa.StartMenuLoop(const AView: IMenuView);
var
AutoReleasePool: NSAutoreleasePool;
begin
if (AView <> nil) and (AView.GetObject <> nil) then
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
if FMenuStack = nil then
FMenuStack := TStack<IMenuView>.Create;
FMenuStack.Push(AView);
try
HookEvent := MenuLoopEvent;
AView.Loop := True;
try
while AView.Loop do
HookObserverCallback(False);
finally
AView.Loop := False;
end;
finally
FMenuStack.Pop;
if FMenuStack.Count = 0 then
begin
HookEvent := nil;
FreeAndNil(FMenuStack);
end;
end;
finally
AutoReleasePool.release;
end;
end;
end;
function TPlatformCocoa.SupportsDefaultSize(const AComponent: TComponentKind): Boolean;
begin
case AComponent of
TComponentKind.Calendar:
Result := True;
else
Result := False;
end;
end;
function TPlatformCocoa.HandleToObjC(FmxHandle: TFmxHandle; const IID: TGUID; out Intf): Boolean;
begin
Result := Supports(HandleToObjC(FmxHandle), IID, Intf);
end;
procedure TPlatformCocoa.ShortCutToKey(ShortCut: TShortCut; var Key: Word; var Shift: TShiftState);
begin
FMX.Helpers.Mac.ShortCutToKey(ShortCut, Key, Shift);
end;
function TPlatformCocoa.ShortCutToText(ShortCut: TShortCut): string;
begin
Result := FMX.Helpers.Mac.ShortCutToText(ShortCut);
end;
function TPlatformCocoa.TextToShortCut(Text: string): Integer;
begin
Result := FMX.Helpers.Mac.TextToShortCut(Text);
end;
{ TFMXOSMenuItem }
type
FMXOSMenuItem = interface(NSMenuItem)
['{A922028A-C1EE-41AF-8345-26671E6879AD}']
procedure DispatchMenuClick(Sender: Pointer); cdecl;
end;
TFMXOSMenuItem = class(TOCLocal)
private
FMXMenuItem: TMenuItem;
public
constructor Create(const AFMXMenuItem: TMenuItem);
destructor Destroy; override;
function GetObjectiveCClass: PTypeInfo; override;
procedure DispatchMenuClick(Sender: Pointer); cdecl;
end;
constructor TFMXOSMenuItem.Create(const AFMXMenuItem: TMenuItem);
var
Key: Char;
ModMask: NSUInteger;
AutoReleasePool: NSAutoreleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
inherited Create;
FMXMenuItem := AFMXMenuItem;
ShortCutToMACKey(FMXMenuItem.ShortCut, Key, ModMask);
UpdateObjectID(NSMenuItem(Super).initWithTitle(StrToNSStr(DelAmp(FMXMenuItem.Text)),
sel_getUid(MarshaledAString('DispatchMenuClick:')), StrToNSStr(Key)));
if AFMXMenuItem.IsChecked then
NSMenuItem(Super).setState(NSOnState);
if AFMXMenuItem.Enabled then
NSMenuItem(Super).setEnabled(True)
else
NSMenuItem(Super).setEnabled(False);
SetMenuBitmap(NSMenuItem(Super), AFMXMenuItem);
NSMenuItem(Super).setKeyEquivalentModifierMask(ModMask);
NSMenuItem(Super).setTarget(GetObjectID);
TFMXMenuDelegate.RegisterMenu(Self.GetObjectID, AFMXMenuItem);
finally
AutoReleasePool.Release;
end;
end;
destructor TFMXOSMenuItem.Destroy;
begin
TFMXMenuDelegate.UnregisterMenu(Self.GetObjectID);
NSMenuItem(Super).Release;
inherited;
end;
procedure TFMXOSMenuItem.DispatchMenuClick(Sender: Pointer);
begin
try
if ((Now - Application.LastKeyPress) > IntervalPress) and
(FMXMenuItem is TMenuItem) then
TOpenMenuItem(FMXMenuItem).Click;
except
HandleException(Self);
end;
end;
function TFMXOSMenuItem.GetObjectiveCClass: PTypeInfo;
begin
Result := TypeInfo(FMXOSMenuItem);
end;
procedure TPlatformCocoa.CreateMenu;
var
LWindowMenuItem: NSMenuItem;
begin
FMainMenu := TNSMenu.Create;
FMenuBar := TNSMenu.Wrap(FMainMenu.initWithTitle(StrToNSStr(string.Empty)));
FMenuBar.setAutoenablesItems(False);
NSApp.setMainMenu(FMenuBar);
CreateAppleMenu;
LWindowMenuItem := FMenuBar.addItemWithTitle(StrToNSStr(SMenuWindow), nil, StrToNSStr(string.Empty));
FWindowMenu := TNSMenu.Create;
FWindowMenu := TNSMenu.Wrap(FWindowMenu.initWithTitle(StrToNSStr(SMenuWindow)));
FMenuBar.setSubmenu(FWindowMenu, LWindowMenuItem);
NSApp.setWindowsMenu(FWindowMenu);
end;
procedure TPlatformCocoa.CreateAppleMenu;
var
LAppleMenuItem: NSMenuItem;
begin
LAppleMenuItem := FMenuBar.addItemWithTitle(StrToNSStr('Apple'), nil, StrToNSStr(''));
FAppleMenu := TNSMenu.Create;
FAppleMenu := TNSMenu.Wrap(FAppleMenu.initWithTitle(StrToNSStr('Apple')));
FMenuBar.setSubmenu(FAppleMenu, LAppleMenuItem);
UpdateAppleMenu(nil);
end;
procedure TPlatformCocoa.UpdateAppleMenu(const ASubItems: IItemsContainer);
var
LMenu: NSMenu;
LMenuItem: NSMenuItem;
LKey: Char;
LModifierMask: NSUInteger;
I: Integer;
begin
if ASubItems <> nil then
begin
for I := FAppleMenu.numberOfItems - 1 downto 0 do
FAppleMenu.removeItemAtIndex(I);
if CreateChildMenuItems(ASubItems, FAppleMenu) then
FAppleMenu.addItem(TNSMenuItem.Wrap(TNSMenuItem.OCClass.separatorItem));
end;
LMenuItem := FAppleMenu.addItemWithTitle(StrToNSStr(SMenuServices), nil, StrToNSStr(''));
LMenu := TNSMenu.Create;
LMenu := TNSMenu.Wrap(LMenu.initWithTitle(StrToNSStr(SMenuServices)));
FAppleMenu.setSubmenu(LMenu, LMenuItem);
NSApp.setServicesMenu(LMenu);
FAppleMenu.addItem(TNSMenuItem.Wrap(TNSMenuItem.OCClass.separatorItem));
LMenuItem := FAppleMenu.addItemWithTitle(StrToNSStr(Format(SMenuAppHide, [Application.Title])), sel_getUid(MarshaledAString('hide:')), StrToNSStr('h'));
LMenuItem.setTarget(NSObjectToID(NSApp));
LMenuItem := FAppleMenu.addItemWithTitle(StrToNSStr(SMenuAppHideOthers), sel_getUid(MarshaledAString('hideOtherApplications:')), StrToNSStr('h'));
LMenuItem.setKeyEquivalentModifierMask(NSCommandKeyMask or NSAlternateKeyMask);
LMenuItem.setTarget(NSObjectToID(NSApp));
LMenuItem := FAppleMenu.addItemWithTitle(StrToNSStr(SMenuShowAll), sel_getUid(MarshaledAString('unhideAllApplications:')), StrToNSStr(''));
LMenuItem.setTarget(NSObjectToID(NSApp));
FAppleMenu.addItem(TNSMenuItem.Wrap(TNSMenuItem.OCClass.separatorItem));
ShortCutToMACKey(CommandQShortCut, LKey, LModifierMask);
LMenuItem := FAppleMenu.addItemWithTitle(StrToNSStr(Format(SMenuAppQuit, [Application.Title])), sel_getUid(MarshaledAString('terminate:')),
StrToNSStr(LKey));
LMenuItem.setKeyEquivalentModifierMask(LModifierMask);
LMenuItem.setTarget(NSObjectToID(NSApp));
end;
function TPlatformCocoa.CreateChildMenuItems(AChildMenu: IItemsContainer; AParentMenu: NSMenu): Boolean;
var
I, J: Integer;
LChildMenuItem: TOpenMenuItem;
LNSSubMenuItem: TFMXOSMenuItem;
LNewSubMenu: NSMenu;
Items: IItemsContainer;
VisibleItemCount: Integer;
AutoReleasePool: NSAutoreleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
AParentMenu.setAutoenablesItems(False);
for J := 0 to AChildMenu.GetItemsCount - 1 do
if AChildMenu.GetItem(J) is TMenuItem then
begin
LChildMenuItem := TOpenMenuItem(AChildMenu.GetItem(J));
if LChildMenuItem.Visible then
begin
if LChildMenuItem.Text = SMenuSeparator then
AParentMenu.addItem(TNSMenuItem.Wrap(TNSMenuItem.OCClass.separatorItem))
else
begin
LNSSubMenuItem := TFMXOSMenuItem.Create(LChildMenuItem);
LChildMenuItem.Handle := AllocHandle(LNSSubMenuItem);
if Supports(AChildMenu.GetItem(J), IItemsContainer, Items) then
begin
VisibleItemCount := 0;
for I := 0 to Items.GetItemsCount - 1 do
if (Items.GetItem(I) is TMenuItem) and
(TMenuItem(Items.GetItem(I)).Visible) then
inc(VisibleItemCount);
if VisibleItemCount > 0 then
begin
LNewSubMenu := NewNsMenu(TMenuItem(AChildMenu.GetItem(J)).Text);
CreateChildMenuItems(Items, LNewSubMenu);
NSMenuItem(LNSSubMenuItem.Super).setSubmenu(LNewSubMenu);
end;
end;
AParentMenu.addItem(NSMenuItem(LNSSubMenuItem.Super));
end;
end;
end;
finally
AutoReleasePool.Release;
end;
end;
procedure TPlatformCocoa.RemoveChildHandles(const AMenu: IItemsContainer);
var
I: Integer;
MenuItem: TMenuItem;
AutoReleasePool: NSAutoreleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
for I := 0 to AMenu.GetItemsCount - 1 do
if (AMenu.GetItem(I) is TMenuItem) then
begin
MenuItem := TMenuItem(AMenu.GetItem(I));
RemoveChildHandles(MenuItem);
DestroyMenuItem(MenuItem);
end;
finally
AutoReleasePool.release;
end;
end;
procedure TPlatformCocoa.ClearNSHandles;
var I: Integer;
begin
for I := FNSHandles.Count - 1 downto 0 do
DeleteHandle(FNSHandles[I]);
FNSHandles.Clear;
end;
function TPlatformCocoa.NewNSMenu(const Text: string): NSMenu;
var
LNSMenu: NSMenu;
S: NSString;
AutoReleasePool: NSAutoreleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
inherited;
LNSMenu := TNSMenu.Alloc;
S := StrToNSStr(DelAmp(Text));
Result := TNSMenu.Wrap(LNSMenu.initWithTitle(S));
FNSHandles.Add(AllocHandle(Result));
Result.setDelegate(FFMXMenuDelegate);
finally
AutoReleasePool.release;
end;
end;
procedure TPlatformCocoa.ClearMenuItems;
var
I, LWindowItemIndex, LAppleMenuIndex: NSInteger;
begin
LWindowItemIndex := FMenuBar.indexOfItemWithSubmenu(FWindowMenu);
LAppleMenuIndex := FMenuBar.indexOfItemWithSubmenu(FAppleMenu);
for I := FMenuBar.numberOfItems - 1 downto 0 do
begin
// Clear all but the Window and "Apple" menus
if (I <> LWindowItemIndex) and (I <> LAppleMenuIndex) then
FMenuBar.removeItemAtIndex(I);
end;
end;
procedure TPlatformCocoa.CreateOSMenu(AForm: TCommonCustomForm; const AMenu: IItemsContainer);
var
LNSMenuItem: NSMenuItem;
LNewMenu: NSMenu;
MenuItem, FirstMenuItem: TOpenMenuItem;
I, J, VisibleItemCount: Integer;
AutoReleasePool: NSAutoreleasePool;
Native: INativeControl;
OldState: TMainMenuState;
LWindowMenuIndex: NSInteger;
begin
if FMainMenuState in [TMainMenuState.Empty, TMainMenuState.Recreated] then
begin
OldState := FMainMenuState;
try
FMainMenuState := TMainMenuState.Recreating;
AutoReleasePool := TNSAutoreleasePool.Create;
try
ClearMenuItems;
ClearNSHandles;
VisibleItemCount := 0;
if AMenu <> nil then
begin
RemoveChildHandles(AMenu);
if Supports(AMenu, INativeControl, Native) and Native.HandleSupported then
for I := 0 to AMenu.GetItemsCount - 1 do
if (AMenu.GetItem(I) is TMenuItem) and
(TMenuItem(AMenu.GetItem(I)).Visible) then
inc(VisibleItemCount);
end;
// TMainMenu items
if VisibleItemCount > 0 then
begin
J := 0;
FirstMenuItem := nil;
for I := 0 to AMenu.GetItemsCount - 1 do
if AMenu.GetItem(I) is TMenuItem then
begin
MenuItem := TOpenMenuItem(AMenu.GetItem(I));
if MenuItem.Visible then
begin
if FirstMenuItem <> nil then
begin
FDefaultMenu := TCurrentMenu.Main;
if J = VisibleItemCount - 1 then
LNewMenu := NewNSMenu(SSpotlightFeature)
else
LNewMenu := NewNSMenu('');
LNSMenuItem := TNSMenuItem.Alloc;
LNSMenuItem := TNSMenuItem.Wrap(LNSMenuItem.initWithTitle(StrToNSStr(''), nil, StrToNSStr('')));
LNSMenuItem.setSubmenu(LNewMenu);
SetMenuBitmap(LNSMenuItem, MenuItem);
if MenuItem.Enabled then
LNSMenuItem.setEnabled(True)
else
LNSMenuItem.setEnabled(False);
if MenuItem.IsChecked then
LNSMenuItem.setState(NSOnState);
if OldState > TMainMenuState.Empty then
CreateChildMenuItems((MenuItem as IItemsContainer), LNewMenu);
MenuItem.Handle := AllocHandle(LNSMenuItem);
LWindowMenuIndex := FMenuBar.indexOfItemWithSubmenu(FWindowMenu);
if MenuItem.Text.Equals(SSpotlightFeature) or (LWindowMenuIndex = -1) then
FMenuBar.addItem(LNSMenuItem)
else
FMenuBar.insertItem(LNSMenuItem, LWindowMenuIndex);
Inc(J);
end
else
begin
UpdateAppleMenu(MenuItem);
FirstMenuItem := MenuItem;
end;
end;
end;
for I := 0 to AMenu.GetItemsCount - 1 do
begin
if AMenu.GetItem(I) <> FirstMenuItem then
UpdateMenuItem(AMenu.GetItem(I) as IItemsContainer, [TMenuItemChange.Text]);
end;
end;
finally
AutoReleasePool.release;
end;
finally
if OldState < TMainMenuState.Recreated then
FMainMenuState := Succ(OldState)
else
FMainMenuState := OldState;
end;
end;
end;
procedure TPlatformCocoa.UpdateMenuBar;
begin
ClearMenuItems;
end;
procedure TPlatformCocoa.UpdateMenuItem(const AItem: IItemsContainer; AChange: TMenuItemChanges);
var
I: Integer;
LMenuItem: TMenuItem;
LHandle: TFmxHandle;
LNativeMenuItem: TFMXOSMenuItem;
LNSMenuItem: NSMenuItem;
IsTopLevelItem, IsFirstVisibleItem: Boolean;
Key: Char;
ModMask: NSUInteger;
AutoReleasePool: NSAutoreleasePool;
IObj: IObjectiveC;
Parent: TFmxObject;
MainMenu: TMainMenu;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
if AItem.GetObject is TMenuItem then
LMenuItem := TMenuItem(AItem.GetObject)
else
Exit;
LHandle := (LMenuItem as INativeControl).Handle;
// Invisible item does not have a handle
if (LHandle = 0) then
begin
// If you changed the visibility, then re-creates all the menus
if (TMenuItemChange.Visible in AChange) and LMenuItem.Visible then
begin
Parent := LMenuItem;
while (Parent is TFmxObject) and not (Parent is TMainMenu) do
Parent := Parent.Parent;
if Parent is TMainMenu then
TMainMenu(Parent).RecreateOSMenu;
end;
Exit;
end;
// If you changed the visibility of top level menu, then re-creates all menu
IsFirstVisibleItem := False;
IsTopLevelItem := LMenuItem.Parent is TMainMenu;
if IsTopLevelItem then
MainMenu := TMainMenu(LMenuItem.Parent)
else
MainMenu := nil;
if IsTopLevelItem and (TMenuItemChange.Visible in AChange) then
begin
MainMenu.RecreateOSMenu;
Exit;
end;
// else update this menu item
IObj := HandleToObjC(LHandle);
if IObj <> nil then
begin
if IObj.QueryInterface(NSMenuItem, LNSMenuItem) <> S_OK then
begin
LNativeMenuItem := IObj as TFMXOSMenuItem;
LNSMenuItem := LNativeMenuItem.Super as NSMenuItem;
end;
// Determine whether the menu item is the first visible and change text
if IsTopLevelItem then
for I := 0 to MainMenu.ItemsCount - 1 do
if (MainMenu.Items[I] is TMenuItem) and TMenuItem(MainMenu.Items[I]).Visible then
begin
IsFirstVisibleItem := MainMenu.Items[I] = LMenuItem;
Break;
end;
if (not IsFirstVisibleItem) and ([TMenuItemChange.Text, TMenuItemChange.Bitmap] * AChange <> []) then
begin
if LNSMenuItem.submenu <> nil then
LNSMenuItem.submenu.setTitle(StrToNSStr(DelAmp(LMenuItem.Text)));
LNSMenuItem.setTitle(StrToNSStr(DelAmp(LMenuItem.Text)));
SetMenuBitmap(LNSMenuItem, LMenuItem);
end;
// Change other params
if (TMenuItemChange.ShortCut in AChange) then
begin
ShortCutToMACKey(LMenuItem.ShortCut, Key, ModMask);
LNSMenuItem.setKeyEquivalent(StrToNSStr(Key));
LNSMenuItem.setKeyEquivalentModifierMask(ModMask);
end;
if TMenuItemChange.Enabled in AChange then
LNSMenuItem.setEnabled(LMenuItem.Enabled);
if TMenuItemChange.Visible in AChange then
LNSMenuItem.setHidden(not LMenuItem.Visible);
if TMenuItemChange.Checked in AChange then
begin
if LMenuItem.IsChecked then
LNSMenuItem.setState(NSOnState)
else
LNSMenuItem.setState(NSOffState);
end;
end
else
raise EInvalidFmxHandle.CreateFMT(SInvalidFmxHandle, [HexDisplayPrefix, SizeOf(LHandle) * 2, LHandle]);
finally
AutoReleasePool.release;
end;
end;
procedure TPlatformCocoa.DestroyMenuItem(const AItem: IItemsContainer);
var
P: TFmxObject;
Native: INativeControl;
AutoReleasePool: NSAutoreleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
if (not FInDestroyMenuItem) and
(AItem <> nil) and
(AItem.GetObject is TFmxObject) then
P := AItem.GetObject
else
Exit;
FInDestroyMenuItem := true;
try
if (P <> nil) and
(Supports(P, INativeControl, Native)) and
(Native.Handle <> 0) then
begin
if (P.Root <> nil) and (P.Root.GetObject is TCommonCustomForm) then
CreateOSMenu(TCommonCustomForm(P.Root.GetObject), nil);
DeleteHandle(Native.Handle);
Native.Handle := 0;
end;
finally
FInDestroyMenuItem := False;
end;
finally
AutoReleasePool.release;
end;
end;
procedure TPlatformCocoa.ValidateHandle(FmxHandle: TFmxHandle);
begin
if (FmxHandle and $F <> 0) then
raise EInvalidFmxHandle.CreateResFmt(@SInvalidFmxHandle, [HexDisplayPrefix, SizeOf(TFmxHandle) * 2, FmxHandle]);
end;
{ Drag and Drop ===============================================================}
procedure TPlatformCocoa.BeginDragDrop(AForm: TCommonCustomForm; const Data: TDragObject; ABitmap: TBitmap);
function AdjustOffset(const MousePos: NSPoint; const Width, Height: Single): NSPoint;
var
Coord: TPointF;
begin
if Data.Source is TControl then
begin
// bottom left point of control at form
Coord := TControl(Data.Source).LocalToAbsolute(TPointF.Create(0, TControl(Data.Source).Height));
// distance between bottom bound of control and bottom bound of form
Coord.Y := TNSView.Wrap(WindowHandleToPlatform(AForm.Handle).Wnd.contentView).bounds.size.height - Coord.y;
end
else
Coord := MousePos.ToPointF - TPointF.Create(Width / 2, Height / 2);
Result := CGPointMake(Coord.X, Coord.Y);
end;
var
Img: NSImage;
Scale: Single;
Pasteboard: NSPasteboard;
PboardTypes: NSArray;
FMXPBoardTypePtrs: array[0..1] of Pointer;
FMXPBoardTypePtrCount: Integer;
FMXWin: TFMXWindow;
AutoReleasePool: NSAutoreleasePool;
Control: IControl;
PNGStream: TMemoryStream;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
FMXWin := TFMXWindow(WindowHandleToPlatform(AForm.Handle).Handle);
if FMXWin.LastEvent <> nil then
begin
Img := BitmapToMacBitmap(ABitmap);
Scale := GetWindowScale(AForm);
if Scale > 1 then
Img.setSize(CGSizeMake(ABitmap.Width / Scale, ABitmap.Height / Scale));
Pasteboard := TNSPasteboard.Wrap(TNSPasteboard.OCClass.pasteboardWithName(NSDragPboard));
FMXPBoardTypePtrs[0] := NSObjectToID(NSFMXPBoardType);
FMXPBoardTypePtrCount := 1;
if Data.Data.IsType<string> then
begin
FMXPBoardTypePtrs[FMXPBoardTypePtrCount] := NSObjectToID(NSPasteboardTypeString);
Inc(FMXPBoardTypePtrCount);
end
else if Data.Data.IsType<TBitmap> or Data.Data.IsType<TBitmapSurface> then
begin
FMXPBoardTypePtrs[FMXPBoardTypePtrCount] := NSObjectToID(NSPasteboardTypePNG);
Inc(FMXPBoardTypePtrCount);
end;
PboardTypes := TNSArray.Wrap(TNSArray.OCClass.arrayWithObjects(@FMXPBoardTypePtrs, FMXPBoardTypePtrCount));
Pasteboard.declareTypes(PBoardTypes, NSObjectToID(Pasteboard));
if FMXPBoardTypePtrCount = 2 then
if Data.Data.IsType<string> then
Pasteboard.setString(StrToNSStr(Data.Data.ToString), NSPasteboardTypeString)
else if Data.Data.IsType<TBitmap> or Data.Data.IsType<TBitmapSurface> then
begin
PNGStream := TMemoryStream.Create;
try
if Data.Data.IsType<TBitmap> then
//Saving to stream without converting it to PNG SaveToStream doing it
Data.Data.AsType<TBitmap>.SaveToStream(PNGStream)
else
TBitmapCodecManager.SaveToStream(PNGStream, Data.Data.AsType<TBitmapSurface>, SPNGImageExtension);
Pasteboard.setData(TNSData.Wrap(TNSData.OCClass.dataWithBytes(PNGStream.Memory, pngStream.size)), NSPasteboardTypePNG);
finally
PNGStream.Free;
end;
end;
GlobalData := Data;
FMXWin.DragOperation := NSDragOperationNone;
NSWindow(FMXWin.Super).dragImage(Img,
AdjustOffset(FMXWin.LastEvent.locationInWindow, Img.size.width, Img.size.height),
CGSizeMake(0, 0), FMXWin.LastEvent, Pasteboard, NSObjectToID(FMXWin.View), True);
if (FMXWin.DragOperation = NSDragOperationNone) and Supports(Data.Source, IControl, Control) then
Control.DragEnd;
FMXWin.LastEvent := nil;
end;
finally
if Img <> nil then
Img.release;
AutoReleasePool.release;
end;
end;
procedure TPlatformCocoa.SetClientSize(const AForm: TCommonCustomForm; const ASize: TPointF);
var
NSWin: NSWindow;
OldFrame, Frame, R: NSRect;
AutoReleasePool: NSAutoreleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
NSWin := WindowHandleToPlatform(AForm.Handle).Wnd;
if NSWin.isVisible then
begin
OldFrame := NSWin.frame;
R.origin := OldFrame.origin;
R.size := CGSizeMake(ASize.X, ASize.Y);
Frame := NSWin.frameRectForContentRect(R);
Frame.origin.x := OldFrame.origin.x;
Frame.origin.y := OldFrame.origin.y + OldFrame.size.height - Frame.size.height;
NSWin.setFrame(Frame, True);
end
else
NSWin.setContentSize(CGSizeMake(ASize.X, ASize.Y));
finally
AutoReleasePool.release;
end;
end;
procedure TPlatformCocoa.SetCursor(const ACursor: TCursor);
const
SizeNWSECursor: array [0..192] of byte = (
$89, $50, $4E, $47, $0D, $0A, $1A, $0A, $00, $00, $00, $0D, $49, $48, $44, $52, $00, $00, $00, $10, $00, $00, $00, $10, $08, $06, $00, $00, $00, $1F, $F3, $FF, $61, $00, $00, $00, $88, $49, $44, $41,
$54, $78, $9C, $AC, $93, $4B, $0A, $C0, $20, $0C, $44, $45, $8A, $69, $D7, $5D, $7B, $00, $0F, $98, $EB, $6B, $15, $8C, $44, $F1, $1B, $3A, $20, $BA, $D0, $E7, $4C, $A2, $4A, $FD, $A1, $30, $D1, $36,
$20, $4D, $69, $00, $40, $59, $8B, $00, $FC, $B0, $08, $60, $8C, $A9, $6E, $BF, $A2, $44, $0E, $08, $82, $88, $EA, $8D, $DA, $02, $78, $EF, $43, $0B, $63, $31, $EE, $29, $80, $67, $26, $88, $D6, $BA,
$82, $58, $6B, $97, $69, $CA, $A6, $91, $93, $AD, $16, $3F, $51, $23, $48, $8A, $D9, $44, $EB, $8B, $AA, $3F, $2B, $F0, $3A, $4F, $16, $41, $A8, $C5, $47, $00, $96, $F7, $DC, $81, $73, $AE, $FB, $C8,
$44, $0E, $C4, $1F, $6D, $A5, $0F, $00, $00, $FF, $FF, $03, $00, $FD, $DF, $FC, $72, $CD, $04, $2F, $27, $00, $00, $00, $00, $49, $45, $4E, $44, $AE, $42, $60, $82
);
SizeNESWCursor: array [0..211] of byte = (
$89, $50, $4E, $47, $0D, $0A, $1A, $0A, $00, $00, $00, $0D, $49, $48, $44, $52, $00, $00, $00, $10, $00, $00, $00, $10, $08, $06, $00, $00, $00, $1F, $F3, $FF, $61, $00, $00, $00, $9B, $49, $44, $41,
$54, $78, $9C, $9C, $93, $51, $0E, $C0, $10, $0C, $86, $3D, $88, $CC, $F3, $0E, $E3, $2A, $2E, $E2, $04, $6E, $E0, $C5, $5D, $DC, $4D, $4C, $93, $CD, $1A, $46, $AD, $7F, $D2, $14, $49, $3F, $D5, $96,
$10, $0B, $95, $52, $48, $23, $55, $D6, $DA, $03, $80, $EB, $ED, $17, $20, $E7, $CC, $06, $1C, $29, $A5, $96, $85, $52, $AA, $79, $12, $A0, $AB, $62, $8C, $BC, $27, $9C, $55, $21, $84, $21, $18, $45,
$CD, $01, $52, $4A, $E1, $9C, $FB, $0C, $F6, $DE, $F7, $5D, $79, $0B, $85, $4F, $26, $37, $C3, $42, $0E, $33, $70, $6F, $86, $14, $B7, $AB, $8D, $01, $5F, $85, $32, $C6, $C0, $42, $93, $00, $DC, $A2,
$27, $D8, $5A, $0B, $DD, $58, $8F, $EC, $2C, $03, $18, $1E, $54, $13, $FE, $13, $B6, $01, $33, $ED, $02, $78, $5F, $B5, $EA, $02, $00, $00, $FF, $FF, $03, $00, $27, $CE, $7B, $C4, $F5, $A4, $B6, $D6,
$00, $00, $00, $00, $49, $45, $4E, $44, $AE, $42, $60, $82
);
SizeAllCursor: array [0..174] of byte = (
$89, $50, $4E, $47, $0D, $0A, $1A, $0A, $00, $00, $00, $0D, $49, $48, $44, $52, $00, $00, $00, $10, $00, $00, $00, $10, $08, $06, $00, $00, $00, $1F, $F3, $FF, $61, $00, $00, $00, $09, $70, $48, $59,
$73, $00, $00, $0B, $13, $00, $00, $0B, $13, $01, $00, $9A, $9C, $18, $00, $00, $00, $61, $49, $44, $41, $54, $78, $9C, $AC, $53, $CB, $0A, $00, $20, $0C, $1A, $F4, $FF, $DF, $6C, $10, $74, $68, $0F,
$17, $65, $E0, $A9, $74, $BA, $36, $03, $60, $04, $FB, $94, $6F, $28, $D9, $6C, $2C, $30, $91, $96, $DC, $89, $5C, $91, $99, $48, $95, $19, $49, $84, $E3, $2A, $13, $F0, $55, $B2, $CA, $C1, $49, $D5,
$B0, $D2, $81, $17, $A5, $99, $3B, $04, $AB, $AF, $02, $DF, $11, $24, $4D, $94, $7C, $A3, $64, $90, $24, $A3, $2C, $59, $A6, $EB, $75, $9E, $00, $00, $00, $FF, $FF, $03, $00, $3A, $00, $A6, $5B, $CC,
$0B, $A4, $58, $00, $00, $00, $00, $49, $45, $4E, $44, $AE, $42, $60, $82
);
WaitCursor: array [0..124] of byte = (
$89, $50, $4E, $47, $0D, $0A, $1A, $0A, $00, $00, $00, $0D, $49, $48, $44, $52, $00, $00, $00, $10, $00, $00, $00, $10, $08, $06, $00, $00, $00, $1F, $F3, $FF, $61, $00, $00, $00, $44, $49, $44, $41,
$54, $78, $9C, $62, $60, $C0, $0E, $FE, $E3, $C0, $44, $83, $21, $6E, $C0, $7F, $5C, $80, $18, $43, $70, $6A, $26, $D6, $10, $BA, $19, $80, $D3, $10, $6C, $0A, $C9, $33, $00, $59, $03, $45, $5E, $C0,
$65, $00, $94, $4D, $5A, $38, $10, $B2, $1D, $C5, $10, $1C, $98, $68, $30, $84, $0C, $00, $00, $00, $00, $FF, $FF, $03, $00, $A9, $31, $25, $E9, $C0, $2C, $FB, $9B, $00, $00, $00, $00, $49, $45, $4E,
$44, $AE, $42, $60, $82
);
HelpCursor: array [0..238] of byte = (
$89, $50, $4E, $47, $0D, $0A, $1A, $0A, $00, $00, $00, $0D, $49, $48, $44, $52, $00, $00, $00, $12, $00, $00, $00, $12, $08, $06, $00, $00, $00, $56, $CE, $8E, $57, $00, $00, $00, $B6, $49, $44, $41,
$54, $78, $9C, $A4, $94, $3B, $12, $80, $20, $0C, $44, $69, $6C, $6D, $6C, $BC, $83, $8D, $B5, $F7, $E0, $FE, $37, $01, $89, $93, $8C, $61, $F9, $18, $21, $33, $19, $15, $C9, $73, $B3, $46, $9D, $83,
$88, $31, $52, $36, $03, $F7, $17, $C5, $1A, $E2, $BD, $0F, $74, $89, $49, $EB, $9F, $30, $06, $05, $81, $70, $51, $D0, $6B, $66, $18, $15, $49, $01, $9F, $9F, $29, $77, $BD, $CE, $F7, $E8, $B8, $98,
$40, $1A, $D6, $00, $ED, $05, $4C, $79, $94, $B5, $C1, $80, $0B, $40, $D2, $1A, $A9, $5D, $BB, $AA, $30, $1B, $1E, $5D, $29, $B7, $AE, $57, $FC, $A4, $23, $ED, $CF, $D4, $00, $A4, $AF, $08, $D5, $C1,
$5B, $FC, $0F, $11, $D0, $34, $44, $83, $A6, $20, $4E, $08, $EF, $A7, $61, $32, $B7, $0A, $A9, $F8, $53, $CE, $8E, $05, $E4, $CA, $21, $1C, $F2, $A7, $A6, $68, $BC, $3D, $F0, $28, $53, $64, $F9, $11,
$48, $3C, $83, $59, $83, $FC, $8D, $85, $8B, $B7, $2F, $C8, $0D, $00, $00, $FF, $FF, $03, $00, $A5, $D1, $28, $C9, $B0, $25, $E3, $01, $00, $00, $00, $00, $49, $45, $4E, $44, $AE, $42, $60, $82
);
var
C: NSCursor;
AutoReleasePool: NSAutoreleasePool;
NewCustomCursor: TCustomCursor;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
NewCustomCursor := nil;
case ACursor of
crCross: C := TNSCursor.Wrap(TNSCursor.OCClass.crosshairCursor);
crArrow, crDefault: C := TNSCursor.Wrap(TNSCursor.OCClass.arrowCursor);
crIBeam: C := TNSCursor.Wrap(TNSCursor.OCClass.IBeamCursor);
crSizeNS: C := TNSCursor.Wrap(TNSCursor.OCClass.resizeUpDownCursor);
crSizeWE: C := TNSCursor.Wrap(TNSCursor.OCClass.resizeLeftRightCursor);
crUpArrow: C := TNSCursor.Wrap(TNSCursor.OCClass.resizeUpCursor);
crDrag, crMultiDrag: C := TNSCursor.Wrap(TNSCursor.OCClass.dragCopyCursor);
crHSplit: C := TNSCursor.Wrap(TNSCursor.OCClass.resizeLeftRightCursor);
crVSplit: C := TNSCursor.Wrap(TNSCursor.OCClass.resizeUpDownCursor);
crNoDrop, crNo: C := TNSCursor.Wrap(TNSCursor.OCClass.operationNotAllowedCursor);
crHandPoint: C := TNSCursor.Wrap(TNSCursor.OCClass.pointingHandCursor);
crAppStart, crSQLWait, crHourGlass: NewCustomCursor := TCustomCursor.Create(@WaitCursor[0], Length(WaitCursor));
crHelp: NewCustomCursor := TCustomCursor.Create(@HelpCursor[0], Length(HelpCursor));
crSizeNWSE: NewCustomCursor := TCustomCursor.Create(@SizeNWSECursor[0], Length(SizeNWSECursor));
crSizeNESW: NewCustomCursor := TCustomCursor.Create(@SizeNESWCursor[0], Length(SizeNESWCursor));
crSizeAll: NewCustomCursor := TCustomCursor.Create(@SizeAllCursor[0], Length(SizeAllCursor));
else
C := TNSCursor.Wrap(TNSCursor.OCClass.arrowCursor);
end;
if ACursor = crNone then
TNSCursor.OCClass.setHiddenUntilMouseMoves(True)
else
begin
TNSCursor.OCClass.setHiddenUntilMouseMoves(False);
// Remove old custom cursor
if FCustomCursor <> nil then
FreeAndNil(FCustomCursor);
// Set new custom cursor
if NewCustomCursor <> nil then
begin
FCustomCursor := NewCustomCursor;
C := FCustomCursor.Cursor;
end;
C.&set;
end;
FCursor := ACursor;
finally
AutoReleasePool.release;
end;
end;
function TPlatformCocoa.GetCursor: TCursor;
begin
Result := FCursor;
end;
procedure TPlatformCocoa.SetFullScreen(const AForm: TCommonCustomForm;
const AValue: Boolean);
var
NSWin: NSWindow;
AutoReleasePool: NSAutoreleasePool;
begin
if AValue and not (TFmxFormState.Showing in AForm.FormState) then
AForm.Visible := True;
if AForm.Visible or (TFmxFormState.Showing in AForm.FormState) then
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
NSWin := WindowHandleToPlatform(AForm.Handle).Wnd;
NSWin.setCollectionBehavior(NSWindowCollectionBehaviorFullScreenPrimary);
try
if not (AValue = ((NSWin.styleMask and NSFullScreenWindowMask) > 0)) then
NSWin.toggleFullScreen(nil);
finally
SetShowFullScreenIcon(AForm, AForm.ShowFullScreenIcon);
end;
finally
AutoReleasePool.release;
end;
end;
end;
{ Mouse ===============================================================}
function TPlatformCocoa.GetMousePos: TPointF;
var
P: NSPoint;
AutoReleasePool: NSAutoreleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
P := TNSEvent.OCClass.mouseLocation;
Result := P.ToPointF;
Result.y := MainScreenHeight - Result.y;
finally
AutoReleasePool.release;
end;
end;
function TPlatformCocoa.GetScreenSize: TPointF;
begin
Result := CGSizeToSizeF(MainScreen.Frame.Size)
end;
function TPlatformCocoa.GetScreenScale: Single;
begin
Result := MainScreen.backingScaleFactor;
end;
function TPlatformCocoa.GetScreenOrientation: TScreenOrientation;
begin
Result := TScreenOrientation.Landscape;
end;
{ IFMXSystemInformationService }
function TPlatformCocoa.GetScrollingBehaviour: TScrollingBehaviours;
begin
Result := [TScrollingBehaviour.BoundsAnimation, TScrollingBehaviour.AutoShowing];
end;
function TPlatformCocoa.GetMinScrollThumbSize: Single;
begin
Result := 25;
end;
{ IFMXScreenService }
{ International ===============================================================}
function TPlatformCocoa.GetCurrentLangID: string;
begin
Result := NSStrToStr(TNSLocale.Wrap(TNSLocale.OCClass.currentLocale).localeIdentifier);
if Length(Result) > 2 then
Delete(Result, 3, MaxInt);
end;
function TPlatformCocoa.GetDefaultFontFamilyName: String;
begin
if FDefaultFontName.IsEmpty then
FDefaultFontName := NSStrToStr(TNSFont.Wrap(TNSFont.OCClass.systemFontOfSize(DefaultMacFontSize)).fontName);
Result := FDefaultFontName;
end;
function TPlatformCocoa.GetDefaultFontSize: Single;
begin
Result := DefaultMacFontSize;
end;
function TPlatformCocoa.GetDefaultSize(const AComponent: TComponentKind): TSize;
begin
case AComponent of
TComponentKind.Calendar: Result := TSize.Create(230, 204);
else
Result := TSize.Create(80, 22);
end;
end;
function TPlatformCocoa.GetFirstWeekday: Byte;
const
MondayOffset = 1;
var
Calendar: NSCalendar;
AutoReleasePool: NSAutoreleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
Calendar := TNSCalendar.Wrap(TNSCalendar.OCClass.currentCalendar);
// On the OSX Zero index corresponds Sunday, so we need to add offset. Because in RTL DayMonday = 1
Result := Calendar.firstWeekday - MondayOffset;
finally
AutoReleasePool.release;
end;
end;
function TPlatformCocoa.GetFullScreen(const AForm: TCommonCustomForm): Boolean;
var
NSWin: NSWindow;
AutoReleasePool: NSAutoreleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
NSWin := WindowHandleToPlatform(AForm.Handle).Wnd;
Result := (NSWin.styleMask and NSFullScreenWindowMask) > 0;
finally
AutoReleasePool.release;
end;
end;
function TPlatformCocoa.GetLocaleFirstDayOfWeek: string;
var
cal: NSCalendar;
firstDay: NSUInteger;
AutoReleasePool: NSAutoreleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
cal:= TNSCalendar.Wrap(TNSCalendar.OCClass.currentCalendar);
firstDay:= Cal.firstWeekday;
Result:= IntToStr(firstDay);
finally
AutoReleasePool.release;
end;
end;
{ Dialogs ===============================================================}
function TPlatformCocoa.DialogOpenFiles(const ADialog: TOpenDialog; var AFiles: TStrings; AType: TDialogType): Boolean;
var
OpenFile: NSOpenPanel;
DefaultExt: string;
Filter: NSArray;
outcome: NSInteger;
I: Integer;
AutoReleasePool: NSAutoreleasePool;
function AllocFilterStr(const S: string; var Filter: NSArray): Boolean;
var
input, pattern: string;
FileTypes: array of string;
outcome, aux: TArray<string>;
i, j: Integer;
FileTypesNS: array of Pointer;
NStr: NSString;
begin
// First, split the string by using '|' as a separator
Result := False;
input := S;
pattern := '\|';
outcome := TRegEx.Split(input, pattern);
pattern := '\*\.';
SetLength(FileTypes, 0);
for i := 0 to length(outcome) - 1 do
begin
if Odd(i) then
if outcome[i] <> '*.*' then
if AnsiLeftStr(outcome[i], 2) = '*.' then
begin
aux := TRegEx.Split(outcome[i], pattern);
for j := 0 to length(aux) - 1 do
begin
aux[j] := Trim(aux[j]);
if aux[j] <> '' then
begin
if AnsiEndsStr(';', aux[j]) then
aux[j] := AnsiLeftStr(aux[j], length(aux[j]) - 1);
SetLength(FileTypes, length(FileTypes) + 1);
FileTypes[length(FileTypes) - 1] := aux[j];
end;
end;
end;
end;
// create the NSArray from the FileTypes array
SetLength(FileTypesNS, length(FileTypes));
for i := 0 to length(FileTypes) - 1 do
begin
NStr := StrToNSStr(FileTypes[i]);
FileTypesNS[i] := NSObjectToID(NStr);
end;
if length(FileTypes) > 0 then
begin
Filter := TNSArray.Wrap(TNSArray.OCClass.arrayWithObjects(@FileTypesNS[0], length(FileTypes)));
Result := True;
end;
end;
begin
Result := False;
DefaultExt := ADialog.DefaultExt;
AutoReleasePool := TNSAutoreleasePool.Create;
try
OpenFile := TNSOpenPanel.Wrap(TNSOpenPanel.OCClass.openPanel);
OpenFile.setAllowsMultipleSelection(TOpenOption.ofAllowMultiSelect in ADialog.Options);
OpenFile.setCanChooseFiles(AType <> TDialogType.Directory);
OpenFile.setCanChooseDirectories(AType = TDialogType.Directory);
OpenFile.setCanCreateDirectories(True);
AFiles.Clear;
if ADialog.InitialDir <> '' then
OpenFile.setDirectoryURL(TNSUrl.Wrap(TNSUrl.OCCLass.fileURLWithPath(StrToNSStr(ADialog.InitialDir))));
if ADialog.FileName <> '' then
OpenFile.setNameFieldStringValue(StrToNSStr(ADialog.FileName));
if ADialog.Filter <> '' then
begin
if AllocFilterStr(ADialog.Filter, Filter) then
begin
OpenFile.setAllowedFileTypes(Filter);
OpenFile.setAllowsOtherFileTypes(False);
end;
end;
if ADialog.Title <> '' then
OpenFile.setTitle(StrToNSStr(ADialog.Title));
OpenFile.retain;
try
outcome := OpenFile.runModal;
if (FModalStack <> nil) and (FModalStack.Count > 0) then
FRestartModal := True;
if outcome = NSOKButton then
begin
for I := 0 to OpenFile.URLs.count - 1 do
AFiles.Add(NSStrToStr(TNSUrl.Wrap(OpenFile.URLs.objectAtIndex(I)).relativePath));
if AFiles.Count > 0 then
ADialog.FileName := AFiles[0];
if DefaultExt <> '' then
if ExtractFileExt(ADialog.FileName) = '' then
ChangeFileExt(ADialog.FileName, DefaultExt);
Result := True;
end;
finally
OpenFile.release;
end;
finally
AutoReleasePool.release;
end;
end;
function TPlatformCocoa.DialogPrint(var ACollate, APrintToFile: Boolean;
var AFromPage, AToPage, ACopies: Integer; AMinPage, AMaxPage: Integer; var APrintRange: TPrintRange;
AOptions: TPrintDialogOptions): Boolean;
var
printPanel: NSPrintPanel;
printInfo: NSPrintInfo;
outcome : NSInteger;
dict: NSMutableDictionary;
AutoReleasePool: NSAutoreleasePool;
begin
Result := False;
AutoReleasePool := TNSAutoreleasePool.Create;
try
printInfo := TNSPrintInfo.Wrap(TNSPrintInfo.OCClass.sharedPrintInfo);
printPanel := TNSPrintPanel.Wrap(TNSPrintPanel.OCClass.printPanel);
dict := printInfo.dictionary;
dict.setValue(TNSNumber.OCClass.numberWithBool(ACollate), NSPrintMustCollate);
dict.setValue(TNSNumber.OCClass.numberWithInt(AFromPage), NSPrintFirstpage);
dict.setValue(TNSNumber.OCClass.numberWithInt(AToPage), NSPrintLastPage);
dict.setValue(TNSNumber.OCClass.numberWithInt(ACopies), NSPrintCopies);
if APrintrange = TPrintRange.prAllPages then
dict.setValue(TNSNumber.OCClass.numberWithBool(True), NSPrintAllPages);
if TPrintDialogOption.poPrintToFile in AOptions then
printInfo.setJobDisposition(NSPrintSaveJob);
printPanel.retain;
try
outcome := printPanel.runModalWithPrintInfo(printInfo);
if outcome = NSOKButton then
begin
ACollate := TNSNumber.Wrap(printInfo.dictionary.valueForKey(NSPrintMustCollate)).boolValue();
ACopies := TNSNumber.Wrap(printInfo.dictionary.valueForKey(NSPrintCopies)).integerValue();
if printInfo.jobDisposition = NSPrintSaveJob then
APrintToFile := True;
if TNSNumber.Wrap(printInfo.dictionary.valueForKey(NSPrintAllPages)).boolValue() = True then
APrintRange := TPrintRange.prAllPages
else
begin
APrintRange := TPrintRange.prPageNums;
AFromPage := TNSNumber.Wrap(printInfo.dictionary.valueForKey(NSPrintFirstpage)).integerValue();
AToPage := TNSNumber.Wrap(printInfo.dictionary.valueForKey(NSPrintLastPage)).integerValue();
end;
Result := True;
end;
finally
printPanel.release;
end;
finally
AutoReleasePool.release;
end;
end;
function TPlatformCocoa.PageSetupGetDefaults(var AMargin, AMinMargin: TRect; var APaperSize: TPointF; AUnits: TPageMeasureUnits; AOptions: TPageSetupDialogOptions): Boolean;
begin
Result := False;
end;
function TPlatformCocoa.DialogPageSetup(var AMargin, AMinMargin :TRect; var APaperSize: TPointF;
var AUnits: TPageMeasureUnits; AOptions: TPageSetupDialogOptions): Boolean;
const
POINTS_PER_INCHES = 72;
MM_PER_INCH = 25.4;
var
pageSetup: NSPageLayout;
printInfo: NSPrintInfo;
outcome: NSInteger;
AutoReleasePool: NSAutoreleasePool;
PaperSize: NSSize;
function ToPoints(Value: Single): Single;
begin
Result := Value /1000;
Result := Result * POINTS_PER_INCHES;
if AUnits = TPageMeasureUnits.pmMillimeters then
begin
Result := Result / MM_PER_INCH;
end;
end;
function FromPoints(Value: Single): Single;
begin
Result := Value * 1000;
Result := Result / POINTS_PER_INCHES;
if AUnits = TPageMeasureUnits.pmMillimeters then
begin
Result := Result * MM_PER_INCH;
end;
end;
begin
Result := False;
AutoReleasePool := TNSAutoreleasePool.Create;
try
printInfo := TNSPrintInfo.Wrap(TNSPrintInfo.OCClass.sharedPrintInfo);
pageSetup := TNSPageLayout.Wrap(TNSPageLayout.OCClass.pageLayout);
//Calculate paper size for MAC side
PaperSize := CGSizeMake(ToPoints(APaperSize.X), ToPoints(APaperSize.Y));
printInfo.setPaperSize(PaperSize);
//If psoMargins is set, use the margins specified by the user,
//else, let the panel use the defaults.
if TPageSetupDialogOption.psoMargins in AOptions then
begin
printInfo.setLeftMargin(ToPoints(AMargin.Left));
printInfo.setTopMargin(ToPoints(AMargin.Top));
printInfo.setRightMargin(ToPoints(AMargin.Right));
printInfo.setBottomMargin(ToPoints(AMargin.Bottom));
end;
printInfo.setHorizontallyCentered(False);
printInfo.setVerticallyCentered(False);
pageSetup.retain;
try
outcome := pageSetup.runModalWithPrintInfo(printInfo);
if outcome = NSOKButton then
begin
APaperSize := CGSizeToSizeF(printInfo.paperSize);
//transfrom from points into inches
APaperSize.X := FromPoints(APaperSize.X);
APaperSize.y := FromPoints(APaperSize.Y);
// Set the margins to the values from the dialog.
AMargin.Left := round(FromPoints(printInfo.LeftMargin));
AMargin.Top := round(FromPoints(printInfo.TopMargin));
AMargin.Right := round(FromPoints(printInfo.RightMargin));
AMargin.Bottom := round(FromPoints(printInfo.BottomMargin));
//if psoMinMargins is set in options, then adjust the margins to fit
if TPageSetupDialogOption.psoMinMargins in AOptions then
begin
if AMargin.Left < AMinMargin.Left then
AMargin.Left := AMinMargin.Left;
if AMargin.Top < AMinMargin.Top then
AMargin.Top := AMinMargin.Top;
if AMargin.Right < AMinMargin.Right then
AMargin.Right := AMinMargin.Right;
if AMargin.Bottom < AMinMargin.Bottom then
AMargin.Bottom := AMinMargin.Bottom;
end;
Result := True;
end;
finally
pageSetup.release;
end;
finally
AutoReleasePool.release;
end;
end;
function TPlatformCocoa.DialogPrinterSetup: Boolean;
begin
Result := False;
end;
function TPlatformCocoa.DialogSaveFiles(const ADialog: TOpenDialog; var AFiles: TStrings): Boolean;
var
SaveFile: NSSavePanel;
DefaultExt: string;
Filter: NSArray;
outcome : NSInteger;
FileName: TFileName;
AutoReleasePool: NSAutoreleasePool;
function AllocFilterStr(const AInput: string; var AFilter: NSArray): Boolean;
var
LFileTypes, LExtMasks, LFilters: TArray<string>;
LFileTypePointers: TArray<Pointer>;
LExt, LFileType: string;
LExists: Boolean;
I, J: Integer;
begin
Result := False;
LFilters := TRegEx.Split(AInput, '\|');
for I := 0 to Length(LFilters) - 1 do
begin
if Odd(I) and (LFilters[I] <> '.') and (AnsiLeftStr(LFilters[I], 2) = '*.') then
begin
LExtMasks := TRegEx.Split(LFilters[I], '\*\.');
for J := 0 to Length(LExtMasks) - 1 do
begin
LExt := LExtMasks[J].Trim;
if LExt <> '' then
begin
if AnsiEndsStr(';', LExt) then
LExt := AnsiLeftStr(LExt, Length(LExt) - 1);
LExists := False;
for LFileType in LFileTypes do
begin
if LFileType.Equals(LExt) then
begin
LExists := True;
Break;
end;
end;
if not LExists then
begin
SetLength(LFileTypes, Length(LFileTypes) + 1);
if SameText(LExt, ADialog.DefaultExt) then // NSSavePanel takes 1st one as default
begin
LFileTypes[High(LFileTypes)] := LFileTypes[0];
LFileTypes[0] := LExt;
end
else
LFileTypes[High(LFileTypes)] := LExt;
end;
end;
end;
end;
end;
SetLength(LFileTypePointers, Length(LFileTypes));
for I := 0 to Length(LFileTypes) - 1 do
LFileTypePointers[I] := StringToID(LFileTypes[I]);
if Length(LFileTypes) > 0 then
begin
AFilter := TNSArray.Wrap(TNSArray.OCClass.arrayWithObjects(@LFileTypePointers[0], Length(LFileTypePointers)));
Result := True;
end;
end;
begin
Result := False;
AutoReleasePool := TNSAutoreleasePool.Create;
try
SaveFile := TNSSavePanel.Wrap(TNSSavePanel.OCClass.savePanel);
if ADialog.InitialDir <> '' then
SaveFile.setDirectoryURL(TNSUrl.Wrap(TNSUrl.OCCLass.fileURLWithPath(StrToNSStr(ADialog.InitialDir))));
if ADialog.FileName <> '' then
SaveFile.setNameFieldStringValue(StrToNSStr(ADialog.FileName));
if ADialog.Filter <> '' then
begin
if AllocFilterStr(ADialog.Filter, Filter) then
SaveFile.setAllowedFileTypes(Filter);
end;
if ADialog.Title <> '' then
SaveFile.setTitle(StrToNSStr(ADialog.Title));
SaveFile.retain;
try
outcome := SaveFile.runModal;
if (FModalStack <> nil) and (FModalStack.Count > 0) then
FRestartModal := True;
if outcome = NSOKButton then
begin
FileName := NSStrToStr(SaveFile.URL.relativePath);
if DefaultExt <> '' then
if ExtractFileExt(FileName) = '' then
ChangeFileExt(FileName, DefaultExt);
ADialog.FileName := Filename;
Result := True;
end;
finally
SaveFile.release;
end;
finally
AutoReleasePool.release;
end;
end;
procedure TPlatformCocoa.DeleteHandle(FmxHandle: TFmxHandle);
var IObj: IObjectiveC;
Item: NSMenuItem;
Menu: NSMenu;
AutoReleasePool: NSAutoreleasePool;
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
ValidateHandle(FmxHandle);
TMonitor.Enter(FObjectiveCMap);
try
if FObjectiveCMap.TryGetValue(FmxHandle, IObj) then
begin
if IObj.QueryInterface(NSMenuItem, Item) = 0 then
begin
Item.release;
Item := nil;
end;
if IObj.QueryInterface(NSMenu, Menu) = 0 then
begin
Menu.release;
Menu := nil;
end;
FObjectiveCMap.Remove(FmxHandle);
IObj := nil;
end;
finally
TMonitor.Exit(FObjectiveCMap);
end;
finally
AutoReleasePool.release;
end;
end;
procedure TPlatformCocoa.Log(const AFormat: string; const AParams: array of const);
begin
if Length(AParams) = 0 then
WriteLn(AFormat)
else
WriteLn(Format(AFormat, AParams));
end;
function TPlatformCocoa.GetListingHeaderBehaviors: TListingHeaderBehaviors;
begin
Result := [];
end;
function TPlatformCocoa.GetListingSearchFeatures: TListingSearchFeatures;
begin
Result := [TListingSearchFeature.StayOnTop];
end;
function TPlatformCocoa.GetListingTransitionFeatures: TListingTransitionFeatures;
begin
Result := [TListingTransitionFeature.EditMode, TListingTransitionFeature.DeleteButtonSlide,
TListingTransitionFeature.PullToRefresh];
end;
function TPlatformCocoa.GetListingEditModeFeatures: TListingEditModeFeatures;
begin
Result := [];
end;
function TPlatformCocoa.GetSaveStateFileName(const ABlockName: string): string;
const
Separator = '_';
var
S: TStringBuilder;
FilePath: string;
begin
if FSaveStateStoragePath.IsEmpty then
FilePath := TPath.GetTempPath
else
FilePath := FSaveStateStoragePath;
S := TStringBuilder.Create(FilePath.Length + Length(Separator) + ABlockName.Length);
try
S.Append(FilePath);
S.Append(ChangeFileExt(ExtractFileName(ParamStr(0)), ''));
S.Append(Separator);
S.Append(ABlockName);
Result := S.ToString(True);
finally
S.Free;
end;
end;
function TPlatformCocoa.GetSaveStateBlock(const ABlockName: string; const ABlockData: TStream): Boolean;
procedure ReadPersistent(const AFileName: string);
var
S: TFileStream;
begin
S := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite);
try
ABlockData.CopyFrom(S, S.Size);
finally
S.Free;
end;
end;
var
LFileName: string;
begin
if ABlockName.IsEmpty or (ABlockData = nil) then
Exit(False);
LFileName := GetSaveStateFileName(ABlockName);
if not TFile.Exists(LFileName) then
Exit(False);
try
ReadPersistent(LFileName);
except
Exit(False);
end;
Result := True;
end;
function TPlatformCocoa.SetSaveStateBlock(const ABlockName: string; const ABlockData: TStream): Boolean;
procedure WritePersistent(const AFileName: string);
var
S: TFileStream;
begin
S := TFileStream.Create(AFileName, fmCreate or fmShareExclusive);
try
ABlockData.Seek(0, TSeekOrigin.soBeginning);
S.CopyFrom(ABlockData, ABlockData.Size);
finally
S.Free;
end;
end;
var
LFileName: string;
begin
if ABlockName.IsEmpty then
Exit(False);
LFileName := GetSaveStateFileName(ABlockName);
if (ABlockData = nil) or (ABlockData.Size < 1) then
begin
if TFile.Exists(LFileName) then
TFile.Delete(LFileName);
end
else
try
WritePersistent(LFileName);
except
Exit(False);
end;
Result := True;
end;
function TPlatformCocoa.GetSaveStateStoragePath: string;
begin
Result := FSaveStateStoragePath;
end;
procedure TPlatformCocoa.SetSaveStateStoragePath(const ANewPath: string);
begin
if not ANewPath.IsEmpty then
FSaveStateStoragePath := IncludeTrailingPathDelimiter(ANewPath)
else
FSaveStateStoragePath := '';
end;
function TPlatformCocoa.GetSaveStateNotifications: Boolean;
begin
Result := False;
end;
{ TMacWindowHandle }
function WindowHandleToPlatform(const AHandle: TWindowHandle): TMacWindowHandle;
begin
Result := TMacWindowHandle(AHandle);
end;
constructor TMacWindowHandle.Create(const AHandle: TOCLocal);
var
AutoReleasePool: NSAutoreleasePool;
boundRect: NSRect;
Options: NSTrackingAreaOptions;
begin
inherited Create;
FHandle := AHandle;
if IsPopup(Form) then
begin
AutoReleasePool := TNSAutoreleasePool.Create;
try
boundRect := MainScreenFrame;
Options := NSTrackingMouseMoved or NSTrackingActiveAlways or NSTrackingAssumeInside;
FTrackingArea := TNSTrackingArea.Wrap(TNSTrackingArea.Alloc.initWithRect(boundRect, Options,
View.superview, nil));
View.addTrackingArea(FTrackingArea);
finally
AutoReleasePool.release;
end;
end;
if FWindowHandles = nil then
FWindowHandles := TList<TMacWindowHandle>.Create;
FWindowHandles.Add(Self);
end;
destructor TMacWindowHandle.Destroy;
begin
if FTrackingArea <> nil then
begin
View.removeTrackingArea(FTrackingArea);
FTrackingArea.release;
FTrackingArea := nil;
end;
FWindowHandles.Remove(Self);
if FWindowHandles.Count = 0 then
FreeAndNil(FWindowHandles);
FreeBuffer;
TFMXWindow(FHandle).DisposeOf;
inherited;
end;
function TMacWindowHandle.GetForm: TCommonCustomForm;
begin
Result := TFMXWindow(FHandle).Wnd;
end;
function TMacWindowHandle.GetView: NSView;
begin
Result := TFMXWindow(FHandle).View;
end;
function TMacWindowHandle.GetWindow: NSWindow;
var
LSuper: IObjectiveCInstance;
LNSWindow: NSWindow;
begin
LSuper := TFMXWindow(FHandle).Super;
if LSuper.QueryInterface(NSWindow, LNSWindow) = S_OK then
Result := LNSWindow
else
Result := nil;
end;
function TMacWindowHandle.GetScale: Single;
begin
Result := Wnd.backingScaleFactor;
end;
procedure TMacWindowHandle.CreateBuffer;
var
ColorSpace: CGColorSpaceRef;
begin
FBufferSize := TSize.Create(Form.Width, Form.Height);
GetMem(FBits, FBufferSize.Width * FBufferSize.Height * 4);
ColorSpace := CGColorSpaceCreateDeviceRGB;
FBuffer := CGBitmapContextCreate(FBits, FBufferSize.Width, FBufferSize.Height, 8, FBufferSize.Width * 4, ColorSpace, kCGImageAlphaPremultipliedLast);
CGColorSpaceRelease(ColorSpace);
end;
procedure TMacWindowHandle.FreeBuffer;
begin
if FBits <> nil then
begin
CGContextRelease(FBuffer);
FreeMem(FBits);
FBits := nil;
FBufferSize := TSize.Create(0, 0);
end;
end;
procedure TMacWindowHandle.UpdateLayer(const Ctx: CGContextRef);
var
Img: CGImageRef;
R: CGRect;
ContextObject: IContextObject;
begin
if Supports(Form, IContextObject, ContextObject) and (ContextObject.Context <> nil) then
begin
if FBits = nil then
CreateBuffer
else if (FBufferSize.Width <> Form.Width) or (FBufferSize.Height <> Form.Height) then
begin
FreeBuffer;
CreateBuffer;
end;
{ Copy from Context }
ContextObject.Context.CopyToBits(FBits, FBufferSize.Width * 4, Rect(0, 0, FBufferSize.Width, FBufferSize.Height));
{ Draw }
R := CGRectMake(0, 0, FBufferSize.Width, FBufferSize.Height);
CGContextClearRect(Ctx, R);
Img := CGBitmapContextCreateImage(FBuffer);
CGContextDrawImage(Ctx, R, Img);
CGImageRelease(Img);
end;
end;
class function TMacWindowHandle.FindForm(const window: NSWindow): TCommonCustomForm;
var
I: Integer;
AutoReleasePool: NSAutoreleasePool;
begin
if FWindowHandles = nil then
Exit(nil);
AutoReleasePool := TNSAutoreleasePool.Create;
try
Result := nil;
for I := 0 to FWindowHandles.Count - 1 do
if NSObjectToID(FWindowHandles[I].Wnd) = NSObjectToID(window) then
begin
Result := FWindowHandles[I].Form;
Break;
end;
finally
AutoReleasePool.release;
end;
end;
{ TCursorInfo }
constructor TCustomCursor.Create(const ABytes: Pointer; const ALength: NSUInteger);
begin
FData := TNSData.Wrap(TNSData.Alloc.initWithBytes(ABytes, ALength));
FImage := TNSImage.Wrap(TNSImage.Alloc.initWithData(FData));
FCursor := TNSCursor.Wrap(TNSCursor.Alloc.initWithImage(FImage, CGPointMake(10, 10)));
end;
destructor TCustomCursor.Destroy;
begin
FCursor.release;
FImage.release;
FData.release;
end;
{ TMultiDisplayMac }
destructor TMultiDisplayMac.Destroy;
begin
FDisplayList.Free;
inherited;
end;
procedure TMultiDisplayMac.UpdateDisplayInformation;
begin
FDisplayCount := 0;
FDesktopRect := TRect.Empty;
FWorkAreaRect := TRect.Empty;
FreeAndNil(FDisplayList);
end;
function TMultiDisplayMac.GetDisplayCount: Integer;
begin
if FDisplayCount = 0 then
FDisplayCount := TNSScreen.OCClass.screens.count;
Result := FDisplayCount;
end;
function TMultiDisplayMac.GetDesktopCenterRect(const Size: TSize): TRect;
var
I, MinI: Integer;
DesktopCenter: TPoint;
Dist, MinDist: Double;
WorkArea: TRect;
begin
DesktopCenter := GetDesktopRect.CenterPoint;
Result := TRect.Create(TPoint.Create(DesktopCenter.X - Size.cx div 2, DesktopCenter.Y - Size.cy div 2), Size.cx,
Size.cy);
MinDist := MaxInt;
MinI := -1;
for I := 0 to GetDisplayCount - 1 do
begin
Dist := GetDisplay(I).WorkArea.CenterPoint.Distance(DesktopCenter);
if Dist < MinDist then
begin
MinDist := Dist;
MinI := I;
end;
end;
WorkArea := GetDisplay(MinI).WorkArea;
if Result.Top < WorkArea.Top then
Result.SetLocation(Result.Left, WorkArea.Top);
if Result.Bottom > WorkArea.Bottom then
Result.SetLocation(Result.Left, WorkArea.Bottom - Result.Height);
if Result.Left < WorkArea.Left then
Result.SetLocation(WorkArea.Left, Result.Top);
if Result.Right > WorkArea.Right then
Result.SetLocation(WorkArea.Right - Result.Width, Result.Top);
end;
function TMultiDisplayMac.GetDesktopRect: TRect;
var
I: Integer;
begin
if (FDesktopRect.Width <= 0) or (FDesktopRect.Height <= 0) then
begin
FDesktopRect := TRect.Empty;
for I := 0 to GetDisplayCount - 1 do
FDesktopRect.Union(GetDisplay(I).BoundsRect);
end;
Result := FDesktopRect;
end;
function TMultiDisplayMac.NSRectToRect(const ANSRect: NSRect): TRect;
var
LNSSize: NSSize;
begin
LNSSize := MainScreen.Frame.Size;
Result := TRect.Create(TPoint.Create(Round(ANSRect.origin.x),
Round(LNSSize.height - ANSRect.origin.y - ANSRect.size.height)), Round(ANSRect.size.width),
Round(ANSRect.size.height));
end;
procedure TMultiDisplayMac.UpdateDisplays;
procedure AddInfo(const I: Integer);
var
LNSScreen: NSScreen;
begin
LNSScreen := TNSScreen.Wrap(TNSScreen.OCClass.screens.objectAtIndex(I));
FDisplayList.Add(TDisplay.Create(I, I = 0, NSRectToRect(LNSScreen.frame), NSRectToRect(LNSScreen.visibleFrame)));
end;
var
I: Integer;
begin
UpdateDisplayInformation;
FDisplayCount := TNSScreen.OCClass.screens.count;
if FDisplayList = nil then
FDisplayList := TList<TDisplay>.Create
else
FDisplayList.Clear;
for I := 0 to FDisplayCount - 1 do
AddInfo(I);
end;
function TMultiDisplayMac.FindDisplay(const screen: NSScreen): TDisplay;
function DoFind(const R: TRect): Integer;
var
I: Integer;
begin
Result := -1;
if FDisplayList <> nil then
for I := 0 to FDisplayList.Count - 1 do
if R = FDisplayList[I].BoundsRect then
begin
Result := I;
Exit;
end;
end;
var
Index: Integer;
R: TRect;
begin
if screen = nil then
raise EInvalidFmxHandle.Create(sArgumentInvalid);
R := NSRectToRect(screen.Frame);
Index := DoFind(R);
if Index = -1 then
begin
UpdateDisplays;
Index := DoFind(R);
end;
if Index = -1 then
raise EInvalidArgument.Create(sArgumentInvalid)
else
Result := FDisplayList[Index];
end;
function TMultiDisplayMac.DisplayFromWindow(const Handle: TWindowHandle): TDisplay;
var
Wnd: TMacWindowHandle;
Form, ParentForm: TCommonCustomForm;
begin
if Handle = nil then
raise EArgumentNilException.Create(SArgumentNil);
Wnd := WindowHandleToPlatform(Handle);
if Wnd.Wnd <> nil then
Form := Wnd.FindForm(Wnd.Wnd)
else
Form := nil;
if IsPopupForm(Form) then
begin
ParentForm := Form.ParentForm;
while IsPopupForm(ParentForm) do
ParentForm := ParentForm.ParentForm;
if ParentForm <> nil then
Wnd := WindowHandleToPlatform(ParentForm.Handle);
end;
if (Wnd = nil) or (Wnd.Wnd = nil) then
raise EArgumentException.Create(sArgumentInvalid);
Result := FindDisplay(Wnd.Wnd.screen);
end;
function TMultiDisplayMac.DisplayFromPoint(const Handle: TWindowHandle; const Point: TPoint): TDisplay;
begin
Result := DisplayFromWindow(Handle);
end;
function TMultiDisplayMac.GetDisplay(const Index: Integer): TDisplay;
begin
if Index < 0 then
raise EListError.CreateFmt(SListIndexError, [Index]);
if (FDisplayList = nil) or (FDisplayList.Count <> GetDisplayCount) then
UpdateDisplays;
if Index >= GetDisplayCount then
raise EListError.CreateFmt(SListIndexError, [Index]);
Result := FDisplayList[Index];
end;
function TMultiDisplayMac.GetWorkAreaRect: TRect;
begin
if (FWorkAreaRect.Width <= 0) or (FWorkAreaRect.Height <= 0) then
FWorkAreaRect := NSRectToRect(MainScreen.visibleFrame);
Result := FWorkAreaRect;
end;
{ TFMXMenuDelegate }
function TFMXMenuDelegate.confinementRectForMenu(menu: NSMenu; onScreen: NSScreen): NSRect;
begin
Result.origin.x := 0;
Result.origin.y := 0;
Result.size.width := 0;
Result.size.height := 0;
end;
function TFMXMenuDelegate.menu(menu: NSMenu; updateItem: NSMenuItem; atIndex: NSInteger;
shouldCancel: Boolean): Boolean;
begin
Result := True;
end;
class function TFMXMenuDelegate.GetMenuItem(const ALocalId: Pointer): TMenuItem;
begin
if FFMXMenuDictionary <> nil then
FFMXMenuDictionary.TryGetValue(ALocalId, Result)
else
Result := nil;
end;
procedure TFMXMenuDelegate.menu(menu: NSMenu; willHighlightItem: NSMenuItem);
var
LMenu: TMenuItem;
begin
if (FFMXMenuDictionary <> nil) and FFMXMenuDictionary.TryGetValue(NSObjectToID(willHighlightItem), LMenu) then
Application.Hint := LMenu.Hint
else
Application.Hint := string.Empty;
end;
procedure TFMXMenuDelegate.menuDidClose(menu: NSMenu);
begin
Application.Hint := string.Empty;
end;
function TFMXMenuDelegate.menuHasKeyEquivalent(menu: NSMenu; forEvent: NSEvent; target: Pointer; action: SEL): Boolean;
begin
Result := False;
end;
procedure TFMXMenuDelegate.menuNeedsUpdate(menu: NSMenu);
begin
end;
procedure TFMXMenuDelegate.menuWillOpen(menu: NSMenu);
var
LMenu: TMenuItem;
begin
if (FFMXMenuDictionary <> nil) and FFMXMenuDictionary.TryGetValue(NSObjectToID(menu), LMenu) then
Application.Hint := LMenu.Hint
else
Application.Hint := string.Empty;
end;
function TFMXMenuDelegate.numberOfItemsInMenu(menu: NSMenu): NSInteger;
begin
Result := -1;
end;
class procedure TFMXMenuDelegate.RegisterMenu(const ALocalId: Pointer; const AMenuItem: TMenuItem);
begin
if FFMXMenuDictionary = nil then
FFMXMenuDictionary := TDictionary<Pointer, TMenuItem>.Create;
FFMXMenuDictionary.Add(ALocalId, AMenuItem);
end;
class procedure TFMXMenuDelegate.UnregisterMenu(const ALocalId: Pointer);
begin
if FFMXMenuDictionary <> nil then
begin
FFMXMenuDictionary.Remove(ALocalId);
if FFMXMenuDictionary.Count = 0 then
FreeAndNil(FFMXMenuDictionary);
end;
end;
function PlatformHookObserverCallback(CancelIdle: Boolean; Mask: NSUInteger = NSAnyEventMask): Boolean;
begin
Result := PlatformCocoa.HookObserverCallback(CancelIdle, Mask);
end;
procedure PlatformAlertCreated;
begin
PlatformCocoa.AlertCreated;
end;
procedure PlatformAlertReleased;
begin
PlatformCocoa.AlertReleased;
end;
function PlatformAlertCount: Integer;
begin
Result := PlatformCocoa.AlertCount;
end;
// We redeclare NSWindow interface locally, because RTL version of NSWindow doesn't have required method convertRectToScreen
// It's for Update only.
type
NSWindowClass = interface(NSResponderClass)
['{A292336C-262C-4450-BC36-CD0003044AB6}']
end;
NSWindow = interface(NSResponder)
['{07BF4FEA-F3A5-47CA-835B-9EC92E1983C1}']
function convertRectToScreen(frameRect: NSRect): NSRect; cdecl;
end;
TNSWindow = class(TOCGenericImport<NSWindowClass, NSWindow>) end;
function TFMXViewBase.firstRectForCharacterRange(aRange: NSRange;
actualRange: PNSRange): NSRect;
var
glyphRect: NSRect;
R: TRectF;
TSObj: ITextInput;
begin
if (FOwner.Wnd.Focused <> nil) and Supports(FOwner.Wnd.Focused, ITextInput, TSObj) then
R := TRectF.Create(TSObj.GetTargetClausePointF)
else if FOwner.Wnd.Focused <> nil then
R := TControl(FOwner.Wnd.Focused.GetObject).AbsoluteRect
else
R := TRectF.Empty;
glyphRect := MakeNSRect(R.Left, NativeView.bounds.size.height - R.Bottom, R.Width, R.Height);
// Convert the rect to screen coordinates
glyphRect := TNSView.Wrap(NativeView.window.contentView).convertRect(glyphRect, NativeView);
Result := TNSWindow.Wrap(NSObjectToId(NativeView.window)).convertRectToScreen(glyphRect);
end;
end.
| 31.791332 | 203 | 0.70302 |
83e99d6e665e4c911ea09077ed93830d13a8b322 | 5,574 | dfm | Pascal | Tools/FilePackageWithZDB/FilePackageWithZDBMainFrm.dfm | atkins126/zChinese | 47d7654ebc335767031473ccd308c508f351bd1c | [
"Apache-2.0"
]
| 35 | 2018-04-18T06:38:15.000Z | 2021-02-25T10:00:40.000Z | Tools/FilePackageWithZDB/FilePackageWithZDBMainFrm.dfm | atkins126/zChinese | 47d7654ebc335767031473ccd308c508f351bd1c | [
"Apache-2.0"
]
| null | null | null | Tools/FilePackageWithZDB/FilePackageWithZDBMainFrm.dfm | atkins126/zChinese | 47d7654ebc335767031473ccd308c508f351bd1c | [
"Apache-2.0"
]
| 9 | 2018-04-20T08:03:49.000Z | 2021-03-13T11:31:06.000Z | object FilePackageWithZDBMainForm: TFilePackageWithZDBMainForm
Left = 0
Top = 0
Caption = 'File Package.'
ClientHeight = 430
ClientWidth = 1082
Color = clBtnFace
DoubleBuffered = True
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
KeyPreview = True
OldCreateOrder = False
Position = poDesktopCenter
OnClose = FormClose
OnCloseQuery = FormCloseQuery
OnCreate = FormCreate
OnDestroy = FormDestroy
PixelsPerInch = 96
TextHeight = 13
object Splitter1: TSplitter
Left = 0
Top = 304
Width = 1082
Height = 5
Cursor = crVSplit
Align = alBottom
AutoSnap = False
ResizeStyle = rsUpdate
ExplicitTop = 389
ExplicitWidth = 1167
end
object TopPanel: TPanel
Left = 0
Top = 0
Width = 1082
Height = 41
Align = alTop
BorderWidth = 5
TabOrder = 0
object Bevel3: TBevel
Left = 303
Top = 6
Width = 10
Height = 29
Align = alLeft
Shape = bsSpacer
ExplicitLeft = 211
ExplicitTop = 2
ExplicitHeight = 39
end
object Bevel4: TBevel
Left = 133
Top = 6
Width = 10
Height = 29
Align = alLeft
Shape = bsSpacer
ExplicitLeft = 38
ExplicitTop = 8
ExplicitHeight = 33
end
object Bevel5: TBevel
Left = 193
Top = 6
Width = 10
Height = 29
Align = alLeft
Shape = bsSpacer
ExplicitLeft = 98
ExplicitTop = 0
ExplicitHeight = 33
end
object Bevel7: TBevel
Left = 841
Top = 6
Width = 10
Height = 29
Align = alLeft
Shape = bsSpacer
ExplicitLeft = 637
ExplicitTop = 0
ExplicitHeight = 33
end
object Bevel8: TBevel
Left = 606
Top = 6
Width = 10
Height = 29
Align = alLeft
Shape = bsSpacer
ExplicitLeft = 521
ExplicitHeight = 21
end
object NewButton: TButton
Left = 6
Top = 6
Width = 50
Height = 29
Align = alLeft
Caption = 'New'
TabOrder = 0
OnClick = NewButtonClick
end
object OpenButton: TButton
Left = 143
Top = 6
Width = 50
Height = 29
Align = alLeft
Caption = 'Open'
TabOrder = 2
OnClick = OpenButtonClick
end
object SaveButton: TButton
Left = 203
Top = 6
Width = 50
Height = 29
Align = alLeft
Caption = 'Save'
TabOrder = 3
OnClick = SaveButtonClick
end
object SaveAsButton: TButton
Left = 253
Top = 6
Width = 50
Height = 29
Align = alLeft
Caption = 'Save as'
TabOrder = 4
OnClick = SaveAsButtonClick
end
object MD5Edit: TMemo
Left = 616
Top = 6
Width = 225
Height = 29
Align = alLeft
ParentColor = True
TabOrder = 5
end
object CacheStateMemo: TMemo
Left = 851
Top = 6
Width = 225
Height = 29
Align = alClient
TabOrder = 7
end
object RecalcMD5Button: TButton
Left = 313
Top = 6
Width = 36
Height = 29
Align = alLeft
Caption = 'MD5'
TabOrder = 8
OnClick = RecalcMD5ButtonClick
end
object CompressAsButton: TButton
Left = 349
Top = 6
Width = 70
Height = 29
Align = alLeft
Caption = 'Build .OXC'
TabOrder = 9
OnClick = CompressAsButtonClick
end
object BuildIndexPackageButton: TButton
Left = 489
Top = 6
Width = 117
Height = 29
Align = alLeft
Caption = 'Build Index Package'
TabOrder = 6
OnClick = BuildIndexPackageButtonClick
end
object NewCustomButton: TButton
Left = 56
Top = 6
Width = 77
Height = 29
Align = alLeft
Caption = 'New Custom'
TabOrder = 1
OnClick = NewCustomButtonClick
end
object ParallelCompressAsButton: TButton
Left = 419
Top = 6
Width = 70
Height = 29
Align = alLeft
Caption = 'Build .OXP'
TabOrder = 10
OnClick = ParallelCompressAsButtonClick
end
end
object Memo: TMemo
Left = 0
Top = 309
Width = 1082
Height = 121
Align = alBottom
BorderStyle = bsNone
TabOrder = 1
WordWrap = False
end
object OpenDialog: TOpenDialog
Filter =
'all files(*.OX;*.OXC;*.OXP;*.ImgMat)|*.OX;*.OXC;*.OXP;*.ImgMat|O' +
'bject Data(*.OX)|*.OX|Compressed Object Data(*.OXC)|*.OXC|Parall' +
'el Compressed Object Data(*.OXP)|*.OXP|All(*.*)|*.*'
Options = [ofPathMustExist, ofFileMustExist, ofShareAware, ofNoTestFileCreate, ofEnableSizing]
Left = 56
Top = 104
end
object SaveDialog: TSaveDialog
DefaultExt = '.OX'
Filter = 'Object Data(*.OX)|*.OX|All(*.*)|*.*'
Options = [ofOverwritePrompt, ofHideReadOnly, ofPathMustExist, ofEnableSizing]
Left = 184
Top = 112
end
object Timer: TTimer
OnTimer = TimerTimer
Left = 56
Top = 160
end
object SaveAsCompressedDialog: TSaveDialog
DefaultExt = '.OXC'
Filter = 'Object Data(*.OXC)|*.OXC|All(*.*)|*.*'
Options = [ofOverwritePrompt, ofHideReadOnly, ofPathMustExist, ofEnableSizing]
Left = 184
Top = 160
end
object SaveAsParallelCompressedDialog: TSaveDialog
DefaultExt = '.OXP'
Filter = 'Object Data(*.OXP)|*.OXP|All(*.*)|*.*'
Options = [ofOverwritePrompt, ofHideReadOnly, ofPathMustExist, ofEnableSizing]
Left = 184
Top = 216
end
end
| 22.207171 | 98 | 0.58432 |
f1a8e856a0523e3764261a9e96ac293e7f7a0fb8 | 10,183 | pas | Pascal | Source/X2CLGraphics.pas | MvRens/x2cl | b2fb171e96033b6e4f22a0afff8de60160e34d1c | [
"Zlib"
]
| 3 | 2020-09-24T01:04:46.000Z | 2022-02-15T06:15:43.000Z | Source/X2CLGraphics.pas | bravesoftdz/x2cl | b2fb171e96033b6e4f22a0afff8de60160e34d1c | [
"Zlib"
]
| null | null | null | Source/X2CLGraphics.pas | bravesoftdz/x2cl | b2fb171e96033b6e4f22a0afff8de60160e34d1c | [
"Zlib"
]
| 3 | 2020-09-24T01:04:48.000Z | 2022-02-15T08:20:21.000Z | {
:: Implements various graphics-related classes and functions.
::
:: Part of the X2Software Component Library
:: http://www.x2software.net/
::
:: Last changed: $Date$
:: Revision: $Rev$
:: Author: $Author$
}
unit X2CLGraphics;
interface
uses
Classes,
Graphics,
Windows;
type
TX2Color32 = type TColor;
TDrawTextClipStyle = (csNone, csEllipsis, csPathEllipsis);
{$IFNDEF VER180}
TVerticalAlignment = (taTop, taBottom, taVerticalCenter);
{$ENDIF}
PRGBAArray = ^TRGBAArray;
TRGBAArray = array[Word] of TRGBQuad;
function Color32(AColor: TColor; AAlpha: Byte = 255): TX2Color32;
function DelphiColor(AColor: TX2Color32): TColor;
function RedValue(AColor: TX2Color32): Byte;
function GreenValue(AColor: TX2Color32): Byte;
function BlueValue(AColor: TX2Color32): Byte;
function AlphaValue(AColor: TX2Color32): Byte;
function Blend(ABackground: TColor; AForeground: TX2Color32): TColor;
{
:$ Provides a wrapper for the DrawText API.
}
procedure DrawText(ACanvas: TCanvas; const AText: String;
const ABounds: TRect;
AHorzAlignment: TAlignment = taLeftJustify;
AVertAlignment: TVerticalAlignment = taVerticalCenter;
AMultiLine: Boolean = False;
AClipStyle: TDrawTextClipStyle = csNone);
{
:$ Returns a pointer to the first physical scanline.
:: In bottom-up bitmaps, the most common kind, the Scanline property
:: compensates for this by returning the last physical row for Scanline[0];
:: the first visual row. For most effects, the order in which the rows are
:: processed is not important; speed is. This function returns the first
:: physical scanline, which can be used as a single big array for the whole
:: bitmap.
:! Note that every scanline is padded until it is a multiple of 4 bytes
:! (32 bits). For true lineair access, ensure the bitmap has a PixelFormat
:! of pf32bit.
}
function GetScanlinePointer(ABitmap: Graphics.TBitmap): Pointer;
{
:$ Wrapper for DrawFocusRect.
:: Ensures the canvas is set up correctly for a standard focus rectangle.
}
procedure DrawFocusRect(ACanvas: TCanvas; const ABounds: TRect);
{
:$ Draws one bitmap over another with the specified Alpha transparency.
:: Both bitmaps must be the same size.
}
procedure DrawBlended(ABackground, AForeground: Graphics.TBitmap; AAlpha: Byte);
{
:$ Draws a rectangle with a vertical gradient.
}
procedure GradientFillRect(ACanvas: TCanvas; ARect: TRect; AStartColor, AEndColor: TColor);
{
:$ Darkens a color with the specified value
}
function DarkenColor(const AColor: TColor; const AValue: Byte): TColor;
{
:$ Lightens a color with the specified value
}
function LightenColor(const AColor: TColor; const AValue: Byte): TColor;
implementation
function Color32(AColor: TColor; AAlpha: Byte): TX2Color32;
begin
Result := (ColorToRGB(AColor) and $00FFFFFF) or (AAlpha shl 24);
end;
function DelphiColor(AColor: TX2Color32): TColor;
begin
Result := (AColor and $00FFFFFF);
end;
function RedValue(AColor: TX2Color32): Byte;
begin
Result := (AColor and $000000FF);
end;
function GreenValue(AColor: TX2Color32): Byte;
begin
Result := (AColor and $0000FF00) shr 8;
end;
function BlueValue(AColor: TX2Color32): Byte;
begin
Result := (AColor and $00FF0000) shr 16;
end;
function AlphaValue(AColor: TX2Color32): Byte;
begin
Result := (AColor and $FF000000) shr 24;
end;
function Blend(ABackground: TColor; AForeground: TX2Color32): TColor;
var
backColor: TX2Color32;
backAlpha: Integer;
foreAlpha: Integer;
begin
foreAlpha := AlphaValue(AForeground);
if foreAlpha = 0 then
Result := ABackground
else if foreAlpha = 255 then
Result := DelphiColor(AForeground)
else
begin
backColor := Color32(ABackground);
backAlpha := 256 - foreAlpha;
Result := RGB(((RedValue(backColor) * backAlpha) +
(RedValue(AForeground) * foreAlpha)) shr 8,
((GreenValue(backColor) * backAlpha) +
(GreenValue(AForeground) * foreAlpha)) shr 8,
((BlueValue(backColor) * backAlpha) +
(BlueValue(AForeground) * foreAlpha)) shr 8);
end;
end;
procedure DrawText(ACanvas: TCanvas; const AText: String;
const ABounds: TRect; AHorzAlignment: TAlignment;
AVertAlignment: TVerticalAlignment;
AMultiLine: Boolean; AClipStyle: TDrawTextClipStyle);
const
HorzAlignmentFlags: array[TAlignment] of Cardinal =
(DT_LEFT, DT_RIGHT, DT_CENTER);
VertAlignmentFlags: array[TVerticalAlignment] of Cardinal =
(DT_TOP, DT_BOTTOM, DT_VCENTER);
MultiLineFlags: array[Boolean] of Cardinal =
(DT_SINGLELINE, 0);
ClipStyleFlags: array[TDrawTextClipStyle] of Cardinal =
(0, DT_END_ELLIPSIS, DT_PATH_ELLIPSIS);
var
flags: Cardinal;
bounds: TRect;
begin
flags := HorzAlignmentFlags[AHorzAlignment] or
VertAlignmentFlags[AVertAlignment] or
MultiLineFlags[AMultiLine] or
ClipStyleFlags[AClipStyle];
if AMultiLine and (AClipStyle <> csNone) then
flags := flags or DT_EDITCONTROL;
bounds := ABounds;
Windows.DrawText(ACanvas.Handle, PChar(AText), Length(AText), bounds, flags);
end;
function GetScanlinePointer(ABitmap: Graphics.TBitmap): Pointer;
var
firstScanline: Pointer;
lastScanline: Pointer;
begin
firstScanline := ABitmap.ScanLine[0];
lastScanline := ABitmap.ScanLine[Pred(ABitmap.Height)];
if Cardinal(firstScanline) > Cardinal(lastScanline) then
Result := lastScanline
else
Result := firstScanline;
end;
procedure DrawFocusRect(ACanvas: TCanvas; const ABounds: TRect);
begin
SetTextColor(ACanvas.Handle, ColorToRGB(clBlack));
Windows.DrawFocusRect(ACanvas.Handle, ABounds);
end;
procedure DrawBlended(ABackground, AForeground: Graphics.TBitmap; AAlpha: Byte);
var
sourcePixels: PRGBAArray;
destPixels: PRGBAArray;
sourcePixel: PRGBQuad;
pixelCount: Integer;
pixelIndex: Integer;
backAlpha: Integer;
foreAlpha: Integer;
begin
backAlpha := AAlpha;
foreAlpha := 256 - AAlpha;
pixelCount := AForeground.Width * AForeground.Height;
sourcePixels := GetScanlinePointer(AForeground);
destPixels := GetScanlinePointer(ABackground);
for pixelIndex := Pred(pixelCount) downto 0 do
with destPixels^[pixelIndex] do
begin
sourcePixel := @sourcePixels^[pixelIndex];
rgbRed := ((rgbRed * backAlpha) +
(sourcePixel^.rgbRed * foreAlpha)) shr 8;
rgbGreen := ((rgbGreen * backAlpha) +
(sourcePixel^.rgbGreen * foreAlpha)) shr 8;
rgbBlue := ((rgbBlue * backAlpha) +
(sourcePixel^.rgbBlue * foreAlpha)) shr 8;
end;
end;
procedure GradientFillRect(ACanvas: TCanvas; ARect: TRect; AStartColor, AEndColor: TColor);
function FixValue(AValue: Single): Single;
begin
Result := AValue;
if Result < 0 then
Result := 0;
if Result > 255 then
Result := 255;
end;
var
startColor: Cardinal;
endColor: Cardinal;
stepCount: Integer;
redValue: Single;
greenValue: Single;
blueValue: Single;
redStep: Single;
greenStep: Single;
blueStep: Single;
line: Integer;
begin
startColor := ColorToRGB(AStartColor);
endColor := ColorToRGB(AEndColor);
if startColor = endColor then
begin
ACanvas.Brush.Style := bsSolid;
ACanvas.Brush.Color := startColor;
ACanvas.FillRect(ARect);
end else
begin
redValue := GetRValue(startColor);
greenValue := GetGValue(startColor);
blueValue := GetBValue(startColor);
stepCount := ARect.Bottom - ARect.Top;
redStep := (GetRValue(endColor) - redValue) / stepCount;
greenStep := (GetGValue(endColor) - greenValue) / stepCount;
blueStep := (GetBValue(endColor) - blueValue) / stepCount;
ACanvas.Pen.Style := psSolid;
for line := ARect.Top to ARect.Bottom do
begin
ACanvas.Pen.Color := RGB(Trunc(redValue), Trunc(greenValue), Trunc(blueValue));
ACanvas.MoveTo(ARect.Left, line);
ACanvas.LineTo(ARect.Right, line);
redValue := FixValue(redValue + redStep);
greenValue := FixValue(greenValue + greenStep);
blueValue := FixValue(blueValue + blueStep);
end;
end;
end;
function DarkenColor(const AColor: TColor; const AValue: Byte): TColor;
var
cColor: Cardinal;
iRed: Integer;
iGreen: Integer;
iBlue: Integer;
begin
cColor := ColorToRGB(AColor);
iRed := (cColor and $FF0000) shr 16;;
iGreen := (cColor and $00FF00) shr 8;
iBlue := cColor and $0000FF;
Dec(iRed, AValue);
Dec(iGreen, AValue);
Dec(iBlue, AValue);
if iRed < 0 then iRed := 0;
if iGreen < 0 then iGreen := 0;
if iBlue < 0 then iBlue := 0;
Result := (iRed shl 16) + (iGreen shl 8) + iBlue;
end;
function LightenColor(const AColor: TColor; const AValue: Byte): TColor;
var
cColor: Cardinal;
iRed: Integer;
iGreen: Integer;
iBlue: Integer;
begin
cColor := ColorToRGB(AColor);
iRed := (cColor and $FF0000) shr 16;;
iGreen := (cColor and $00FF00) shr 8;
iBlue := cColor and $0000FF;
Inc(iRed, AValue);
Inc(iGreen, AValue);
Inc(iBlue, AValue);
if iRed > 255 then iRed := 255;
if iGreen > 255 then iGreen := 255;
if iBlue > 255 then iBlue := 255;
Result := (iRed shl 16) + (iGreen shl 8) + iBlue;
end;
end.
| 27.746594 | 94 | 0.631739 |
83856d85dd00afcff92d19c0755dd9cdb8793a8b | 1,746 | pas | Pascal | Projects/Stemma.p/Source/tools/frm_selectdialog.pas | joecare99/Public | 9eee060fbdd32bab33cf65044602976ac83f4b83 | [
"MIT"
]
| 11 | 2017-06-17T05:13:45.000Z | 2021-07-11T13:18:48.000Z | Projects/Stemma.p/Source/tools/frm_selectdialog.pas | joecare99/Public | 9eee060fbdd32bab33cf65044602976ac83f4b83 | [
"MIT"
]
| 2 | 2019-03-05T12:52:40.000Z | 2021-12-03T12:34:26.000Z | Projects/Stemma.p/Source/tools/frm_selectdialog.pas | joecare99/Public | 9eee060fbdd32bab33cf65044602976ac83f4b83 | [
"MIT"
]
| 6 | 2017-09-07T09:10:09.000Z | 2022-02-19T20:19:58.000Z | unit frm_SelectDialog;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
ButtonPanel;
type
{ TfrmSelectDialog }
TfrmSelectDialog = class(TForm)
ButtonPanel1: TButtonPanel;
ComboBox1: TComboBox;
StaticText1: TStaticText;
private
{ private declarations }
public
{ public declarations }
end;
var
frmSelectDialog: TfrmSelectDialog;
function SelectDialog(const ACaption, APrompt : String;const List:TStrings; var Value : String) : Boolean;overload;
function SelectDialog(const ACaption, APrompt : String;const List:TStrings; var Value : integer) : Boolean;overload;
implementation
function SelectDialog(const ACaption, APrompt: String; const List: TStrings;
var Value: String): Boolean;
begin
frmSelectDialog.Caption:=ACaption;
frmSelectDialog.StaticText1.Caption:=APrompt;
frmSelectDialog.ComboBox1.Items:=List;
frmSelectDialog.ComboBox1.Text:=Value;
if frmSelectDialog.ShowModal = mrOK then
begin
result := true;
Value:=frmSelectDialog.ComboBox1.Text;
end;
end;
function SelectDialog(const ACaption, APrompt: String; const List: TStrings;
var Value: integer): Boolean;
begin
frmSelectDialog.Caption:=ACaption;
frmSelectDialog.StaticText1.Caption:=APrompt;
frmSelectDialog.ComboBox1.Items:=List;
frmSelectDialog.ComboBox1.ItemIndex:=frmSelectDialog.ComboBox1.Items.IndexOfObject(TObject(ptrint(Value)));
if frmSelectDialog.ShowModal = mrOK then
begin
result := true;
Value:=ptrint(frmSelectDialog.ComboBox1.Items.Objects[frmSelectDialog.ComboBox1.ItemIndex]);
end;
end;
{$R *.lfm}
{ TfrmSelectDialog }
end.
| 25.676471 | 117 | 0.725659 |
8570ff530d458683eafcec3d1e4e256fac1697b0 | 22,563 | pas | Pascal | gitclient.pas | and3md/fpcupdeluxe | 89ae3888721528e721ac162bb0627690319a93f5 | [
"zlib-acknowledgement"
]
| null | null | null | gitclient.pas | and3md/fpcupdeluxe | 89ae3888721528e721ac162bb0627690319a93f5 | [
"zlib-acknowledgement"
]
| null | null | null | gitclient.pas | and3md/fpcupdeluxe | 89ae3888721528e721ac162bb0627690319a93f5 | [
"zlib-acknowledgement"
]
| null | null | null | { Classes for using git commands, based on git and svn classes
Copyright (C) 2012-2013 Reinier Olislagers, Ludo Brands
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version with the following modification:
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent modules,and
to copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the terms
and conditions of the license of that module. An independent module is a
module which is not derived from or based on this library. If you modify
this library, you may extend this exception to your version of the library,
but you are not obligated to do so. If you do not wish to do so, delete this
exception statement from your version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
for more details.
You should have received a copy of the GNU Library General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit gitclient;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,
repoclient;
const
// Custom return codes
FRET_LOCAL_REMOTE_URL_NOMATCH = repoclient.FRET_LOCAL_REMOTE_URL_NOMATCH;
FRET_WORKING_COPY_TOO_OLD = repoclient.FRET_WORKING_COPY_TOO_OLD;
FRET_UNKNOWN_REVISION = repoclient.FRET_UNKNOWN_REVISION;
type
EGitClientError = class(ERepoClientError);
{ TGitClient }
TGitClient = class(TRepoClient)
{ Support for http proxy via git config, e.g.
git config --global http.proxy $http_proxy
however, we're not writing config changes for users, so
we don't provide http proxy support for git. }
protected
procedure CheckOut(UseForce:boolean=false); override;
function GetProxyCommand: string;
function GetLocalRevision: string; override;
function GetRepoExecutable: string; override;
function GetRepoExecutableName: string; override;
function FindRepoExecutable: string; override;
public
procedure CheckOutOrUpdate; override;
function Commit(Message: string): boolean; override;
function GetDiffAll: string; override;
procedure SwitchURL; override;
procedure LocalModifications(var FileList: TStringList); override;
function LocalRepositoryExists: boolean; override;
procedure Log(var Log: TStringList); override;
procedure ParseFileList(const CommandOutput: string; var FileList: TStringList; const FilterCodes: array of string); override;
procedure Revert; override;
procedure Update; override;
function GetSVNRevision: string;
function GetGitHash: string;
end;
implementation
uses
StrUtils,
installerCore,
processutils,
fpcuputil;
{ TGitClient }
function TGitClient.GetRepoExecutableName: string;
begin
// Application name:
result := 'git';
end;
function TGitClient.FindRepoExecutable: string;
var
rv:integer;
begin
Result := FRepoExecutable;
// Look in path
// Windows: will also look for <gitName>.exe
if not FileExists(FRepoExecutable) then
FRepoExecutable := Which(RepoExecutableName+GetExeExt);
{$IFDEF MSWINDOWS}
// Git on Windows can be a .cmd file
//if not FileExists(FRepoExecutable) then
// FRepoExecutable := FindDefaultExecutablePath(RepoExecutableName + '.cmd');
// Git installed via msyswin
if not FileExists(FRepoExecutable) then
FRepoExecutable := 'C:\msysgit\bin\' + RepoExecutableName + '.exe';
// Some popular locations for Tortoisegit:
// Covers both 32 bit and 64 bit Windows.
if not FileExists(FRepoExecutable) then
FRepoExecutable := GetEnvironmentVariable('ProgramFiles')+'\TortoiseGit\bin\' + RepoExecutableName + '.exe';
if not FileExists(FRepoExecutable) then
FRepoExecutable := GetEnvironmentVariable('ProgramFiles(x86)')+'\TortoiseGit\bin\' + RepoExecutableName + '.exe';
// Commandline git tools
if not FileExists(FRepoExecutable) then
FRepoExecutable := GetEnvironmentVariable('ProgramFiles')+'\Git\bin\' + RepoExecutableName + '.exe';
if not FileExists(FRepoExecutable) then
FRepoExecutable := GetEnvironmentVariable('ProgramFiles(x86)')+'\Git\bin\' + RepoExecutableName + '.exe';
if not FileExists(FRepoExecutable) then
FRepoExecutable := 'C:\Program Files (x86)\Git\bin\' + RepoExecutableName + '.exe';
//Directory where current executable is:
if not FileExists(FRepoExecutable) then
FRepoExecutable := (SafeGetApplicationPath + RepoExecutableName + '.exe');
{$ENDIF MSWINDOWS}
if not FileExists(FRepoExecutable) then
begin
//current directory. Note: potential for misuse by malicious program.
{$IFDEF MSWINDOWS}
if FileExists(RepoExecutableName + '.exe') then
FRepoExecutable := RepoExecutableName + '.exe';
{$ELSE}
if FileExists(RepoExecutableName) then
FRepoExecutable := RepoExecutableName;
{$ENDIF MSWINDOWS}
end;
if FileExists(FRepoExecutable) then
begin
// Check for valid git executable:
//rv:=TInstaller(Parent).ExecuteCommand(DoubleQuoteIfNeeded(FRepoExecutable) + ' --version', Verbose);
//if rv<>0 then
if (NOT CheckExecutable(FRepoExecutable, ['--version'], '', true)) then
begin
FRepoExecutable := '';
//ThreadLog('GIT client found, but error code during check: '+InttoStr(rv),etError);
ThreadLog('GIT client found, but error code during check !',etError);
end;
end
else
begin
// File does not exist
// Make sure we don't call an arbitrary executable:
FRepoExecutable := '';
end;
Result := FRepoExecutable;
end;
function TGitClient.GetRepoExecutable: string;
begin
if not FileExists(FRepoExecutable) then
FindRepoExecutable;
if not FileExists(FRepoExecutable) then
Result := ''
else
Result := FRepoExecutable;
end;
procedure TGitClient.CheckOut(UseForce:boolean=false);
// SVN checkout is more or less equivalent to git clone
var
Command: string = '';
Output: string = '';
RetryAttempt: integer;
aBranch: string = '';
//TargetFile: string;
begin
if NOT ValidClient then exit;
// Invalidate our revision number cache
FLocalRevision := FRET_UNKNOWN_REVISION;
if DesiredBranch=''
then aBranch:='master'
else aBranch:=DesiredBranch;
// Actual clone/checkout
if ExportOnly then
begin
{
TargetFile := SysUtils.GetTempFileName;
Command := ' archive --format zip --output ' + TargetFile + ' --prefix=/ --remote=' + Repository + ' master';
FReturnCode := TInstaller(Parent).ExecuteCommand(DoubleQuoteIfNeeded(FRepoExecutable) + Command, Verbose);
FReturnCode := TInstaller(Parent).ExecuteCommand(FUnzip+' -o -d '+IncludeTrailingPathDelimiter(InstallDir)+' '+TargetFile,Verbose);
SysUtils.DeleteFile(TargetFile);
}
if DirectoryExists(IncludeTrailingPathDelimiter(LocalRepository)+'.git') then
begin
TInstaller(Parent).ExecuteCommandInDir(DoubleQuoteIfNeeded(FRepoExecutable) + ' fetch --all', LocalRepository, Verbose);
TInstaller(Parent).ExecuteCommandInDir(DoubleQuoteIfNeeded(FRepoExecutable) + ' reset --hard origin/'+aBranch, LocalRepository, Verbose);
end
else
begin
// initial : very shallow clone = fast !!
Command := ' clone --recurse-submodules --depth 1 -b ' + aBranch
end;
end
else
begin
//On Haiku, arm and aarch64, always get a shallow copy of the repo
{$if defined(CPUAARCH64) OR defined(CPUARM) OR (defined(CPUPOWERPC64) AND defined(FPC_ABI_ELFV2)) OR defined(Haiku) OR defined(AROS) OR defined(Morphos)}
Command := ' clone --recurse-submodules --depth 1 -b ' + aBranch;
{$else}
Command := ' clone --recurse-submodules -b ' + aBranch;
{$endif}
end;
if Command<>'' then
begin
if (Length(DesiredRevision)>0) AND (Uppercase(trim(DesiredRevision)) <> 'HEAD') then
Command := Command+ ' ' + DesiredRevision;
Command := Command + ' ' + Repository + ' ' + LocalRepository;
FReturnCode := TInstaller(Parent).ExecuteCommand(DoubleQuoteIfNeeded(FRepoExecutable) + Command, Output, Verbose);
FReturnOutput := Output;
end
else FReturnCode := 0;
if (ReturnCode=AbortedExitCode) then exit;
// If command fails, e.g. due to misconfigured firewalls blocking ICMP etc, retry a few times
RetryAttempt := 1;
if (FReturnCode <> 0) then
begin
// if we have a proxy, set it now !
if Length(GetProxyCommand)>0 then TInstaller(Parent).ExecuteCommand(DoubleQuoteIfNeeded(FRepoExecutable) + GetProxyCommand, Output, Verbose);
while (FReturnCode <> 0) and (RetryAttempt < ERRORMAXRETRIES) do
begin
Sleep(500); //Give everybody a chance to relax ;)
FReturnCode := TInstaller(Parent).ExecuteCommand(DoubleQuoteIfNeeded(FRepoExecutable) + Command, Output, Verbose); //attempt again
if (ReturnCode=AbortedExitCode) then exit;
RetryAttempt := RetryAttempt + 1;
end;
end;
end;
procedure TGitClient.CheckOutOrUpdate;
begin
if LocalRepositoryExists = false then
begin
if FReturnCode = FRET_LOCAL_REMOTE_URL_NOMATCH then
begin
// We could delete the entire directory and Clone
// but the user could take issue with that.
// We already set the return code, so just let caller handle it.
end
else
begin
// Clone (first download)
Checkout;
// If we use a desired revision, we'll need to update to that. Doesn't hurt anyway to run this command
if (FReturnCode<>AbortedExitCode) then Update;
end;
end
else
begin
// Update
Update;
end;
end;
function TGitClient.Commit(Message: string): boolean;
begin
result:=false;
FReturnCode := 0;
if ExportOnly then exit;
if NOT ValidClient then exit;
inherited Commit(Message);
FReturnCode := TInstaller(Parent).ExecuteCommandInDir(DoubleQuoteIfNeeded(FRepoExecutable) + ' commit --message='+Message, LocalRepository, Verbose);
//todo: do push to remote repo?
Result:=(FReturnCode=0);
end;
function TGitClient.GetDiffAll: string;
begin
result:='';
FReturnCode := 0;
if ExportOnly then exit;
if NOT ValidClient then exit;
//FReturnCode := TInstaller(Parent).ExecuteCommandInDir(DoubleQuoteIfNeeded(FRepoExecutable) + ' diff --git ', LocalRepository, Result, Verbose);
FReturnCode := TInstaller(Parent).ExecuteCommandInDir(DoubleQuoteIfNeeded(FRepoExecutable) + ' diff --no-prefix -p ', LocalRepository, Result, Verbose);
end;
procedure TGitClient.Log(var Log: TStringList);
var
s: string = '';
begin
FReturnCode := 0;
Log.Text := s;
if ExportOnly then exit;
if NOT ValidClient then exit;
FReturnCode := TInstaller(Parent).ExecuteCommandInDir(DoubleQuoteIfNeeded(FRepoExecutable) + ' log ', LocalRepository, s, Verbose);
Log.Text := s;
end;
procedure TGitClient.Revert;
begin
FReturnCode := 0;
if ExportOnly then exit;
if NOT ValidClient then exit;
//FReturnCode := TInstaller(Parent).ExecuteCommandInDir(DoubleQuoteIfNeeded(FRepoExecutable) + ' revert --all --no-backup ', LocalRepository, Verbose);
FReturnCode := TInstaller(Parent).ExecuteCommandInDir(DoubleQuoteIfNeeded(FRepoExecutable) + ' reset --hard ', LocalRepository, Verbose);
end;
procedure TGitClient.Update;
var
Command: string;
Output: string = '';
begin
FReturnCode := 0;
if ExportOnly then exit;
if NOT ValidClient then exit;
// Invalidate our revision number cache
FLocalRevision := FRET_UNKNOWN_REVISION;
// Get updates (equivalent to git fetch and git merge)
// --all: fetch all remotes
Command := ' pull --all --recurse-submodules=yes';
FReturnCode := TInstaller(Parent).ExecuteCommandInDir(DoubleQuoteIfNeeded(FRepoExecutable) + command, LocalRepository, Output, Verbose);
FReturnOutput := Output;
if FReturnCode = 0 then
begin
// Notice that the result of a merge will not be checked out in the submodule,
//"git submodule update" has to be called afterwards to bring the work tree up to date with the merge result.
Command := ' submodule update ';
FReturnCode := TInstaller(Parent).ExecuteCommandInDir(DoubleQuoteIfNeeded(FRepoExecutable) + command, LocalRepository, Verbose);
end;
if (FReturnCode = 0){ and (Length(DesiredRevision)>0) and (uppercase(trim(DesiredRevision)) <> 'HEAD')}
then
begin
//SSL Certificate problem
//git config --system http.sslCAPath /absolute/path/to/git/certificates
// always reset hard towards desired revision
Command := ' reset --hard ' + DesiredRevision;
FReturnCode := TInstaller(Parent).ExecuteCommandInDir(DoubleQuoteIfNeeded(FRepoExecutable) + command, LocalRepository, Verbose);
end;
end;
procedure TGitClient.ParseFileList(const CommandOutput: string; var FileList: TStringList; const FilterCodes: array of string);
// Parses file lists from git status outputs
// If FilterCodes specified, only returns the files that match one of the characters in the code (e.g 'CGM');
// Case-sensitive filter.
var
AllFilesRaw: TStringList;
Counter: integer;
FileName: string;
SpaceAfterStatus: integer;
StatusCode: string;
begin
AllFilesRaw := TStringList.Create;
try
AllFilesRaw.Text := CommandOutput;
for Counter := 0 to AllFilesRaw.Count - 1 do
begin
{ Output like (first column is a space)
D Aircraft/Socata-ST10/Models/Interior/Panel/Instruments/Switch/Switch.ac
M README
}
// Accept space in first column and entry on second column
// Get the first character after a space in the first 2 columns:
FileName := '';
StatusCode := Copy(Trim(Copy(AllFilesRaw[Counter], 1, 2)), 1, 1);
SpaceAfterStatus := PosEx(' ', AllFilesRaw[Counter], Pos(StatusCode, AllFilesRaw[Counter]));
// Process if there is one space after the status character, and
// we're either not filtering or we have a filter match
if (Copy(AllFilesRaw[Counter], SpaceAfterStatus, 1) = ' ') and ((High(FilterCodes) = 0) or
AnsiMatchStr(Statuscode, FilterCodes)) then
begin
// Replace / with \ for Windows:
FileName := (Trim(Copy(AllFilesRaw[Counter], SpaceAfterStatus, Length(AllFilesRaw[Counter]))));
FileName := StringReplace(FileName, '/', DirectorySeparator, [rfReplaceAll]);
if FileName <> '' then
FileList.Add(FileName);
end;
end;
finally
AllFilesRaw.Free;
end;
end;
procedure TGitClient.SwitchURL;
var
Command: string = '';
Output: string = '';
RetryAttempt: integer;
begin
FReturnCode := 0;
if ExportOnly then exit;
if NOT ValidClient then exit;
// Actual clone/checkout
Command := ' remote set-url origin ' + Repository + ' ' + LocalRepository;
FReturnCode := TInstaller(Parent).ExecuteCommand(DoubleQuoteIfNeeded(FRepoExecutable) + Command, Output, Verbose);
// If command fails, e.g. due to misconfigured firewalls blocking ICMP etc, retry a few times
RetryAttempt := 1;
if (FReturnCode <> 0) then
begin
// if we have a proxy, set it now !
if Length(GetProxyCommand)>0 then TInstaller(Parent).ExecuteCommand(DoubleQuoteIfNeeded(FRepoExecutable) + GetProxyCommand, Output, Verbose);
while (FReturnCode <> 0) and (RetryAttempt < ERRORMAXRETRIES) do
begin
Sleep(500); //Give everybody a chance to relax ;)
FReturnCode := TInstaller(Parent).ExecuteCommand(DoubleQuoteIfNeeded(FRepoExecutable) + Command, Output, Verbose); //attempt again
RetryAttempt := RetryAttempt + 1;
end;
end;
end;
procedure TGitClient.LocalModifications(var FileList: TStringList);
var
AllFiles: TStringList;
Output: string = '';
begin
FReturnCode := 0;
if ExportOnly then exit;
if NOT ValidClient then exit;
if NOT DirectoryExists(LocalRepository) then exit;
if (NOT Assigned(FileList)) then exit;
FileList.Clear;
// --porcelain indicate stable output;
// -z would indicate machine-parsable output but uses ascii 0 to terminate strings, which doesn't match ParseFileList;
FReturnCode := TInstaller(Parent).ExecuteCommandInDir(DoubleQuoteIfNeeded(FRepoExecutable) + ' status --porcelain --untracked-files=no ',
LocalRepository, Output, Verbose);
AllFiles := TStringList.Create;
try
// Modified, Added, Deleted, Renamed
ParseFileList(Output, AllFiles, ['M', 'A', 'D', 'R']);
FileList.AddStrings(AllFiles);
finally
AllFiles.Free;
end;
end;
function TGitClient.LocalRepositoryExists: boolean;
var
Output: string = '';
URL: string;
begin
Result := false;
FReturnCode := 0;
if ExportOnly then exit;
if NOT ValidClient then exit;
if NOT DirectoryExists(LocalRepository) then exit;
// This will output nothing to stdout and
// fatal: Not a git repository (or any of the parent directories): .git
// to std err
FReturnCode := TInstaller(Parent).ExecuteCommandInDir(DoubleQuoteIfNeeded(FRepoExecutable) + ' status --porcelain ', LocalRepository, Output, Verbose);
if FReturnCode = 0 then
begin
// There is a git repository here.
// Now, repository URL might differ from the one we've set
// Try to find out remote repo
FReturnCode := TInstaller(Parent).ExecuteCommandInDir(DoubleQuoteIfNeeded(FRepoExecutable) + ' config remote.origin.url ', LocalRepository, Output, Verbose);
if FReturnCode = 0 then
begin
URL := IncludeTrailingSlash(trim(Output));
end
else
begin
URL := ''; //explicitly fail
end;
if Repository = '' then
begin
Repository := URL;
Result := true;
end
else
begin
if StripUrl(Repository) = StripUrl(URL) then
begin
Result := true;
end
else
begin
// There is a repository here, but it was checked out
// from a different URL...
// Keep result false; show caller what's going on.
FLocalRevision := FRET_UNKNOWN_REVISION;
//FLocalRevisionWholeRepo := FRET_UNKNOWN_REVISION;
FReturnCode := FRET_LOCAL_REMOTE_URL_NOMATCH;
Repository := URL;
end;
end;
end;
end;
function TGitClient.GetProxyCommand: string;
var
s:string;
begin
if HTTPProxyHost<>'' then
begin
s:=HTTPProxyHost;
if Pos('http',s)<>1 then s:='https://'+s;
if HTTPProxyPort<>0 then s:=s+':'+IntToStr(HTTPProxyPort);
if HTTPProxyUser<>'' then
begin
s:='@'+s;
if HTTPProxyPassword<>'' then s:=':'+HTTPProxyPassword+s;
s:=HTTPProxyUser+s;
end;
result:=' config --local --add http.proxy '+s;
end
else
begin
result:='';
end;
end;
function TGitClient.GetLocalRevision: string;
var
Output: string = '';
i:integer;
begin
Result := Output;
FReturnCode := 0;
if ExportOnly then exit;
if NOT ValidClient then exit;
if NOT DirectoryExists(LocalRepository) then exit;
// Only update if we have invalid revision info, in order to minimize git info calls
if FLocalRevision = FRET_UNKNOWN_REVISION then
begin
//todo: find out: without max-count, I can get multiple entries. No idea what these mean!??
// alternative command: rev-parse --verify "HEAD^0" but that doesn't look as low-level ;)
try
//FReturnCode := TInstaller(Parent).ExecuteCommandInDir(DoubleQuoteIfNeeded(FRepoExecutable) + ' rev-list --max-count=1 HEAD ', LocalRepository, Output, Verbose);
FReturnCode := TInstaller(Parent).ExecuteCommandInDir(DoubleQuoteIfNeeded(FRepoExecutable) + ' describe --tags --all --long --always ', LocalRepository, Output, Verbose);
if FReturnCode = 0 then
begin
i:=RPos('/',Output);
if (i>0) then Delete(Output,1,i);
FLocalRevision := trim(Output)
end
else FLocalRevision := FRET_UNKNOWN_REVISION; //for compatibility with the svnclient code
except
FLocalRevision := FRET_UNKNOWN_REVISION; //for compatibility with the svnclient code
end;
end;
Result := FLocalRevision;
end;
function TGitClient.GetSVNRevision: string;
var
Output:string;
OutputSL:TStringList;
i,j:integer;
begin
result:='';
if ExportOnly then exit;
if NOT ValidClient then exit;
if NOT DirectoryExists(LocalRepository) then exit;
Output:='';
i:=TInstaller(Parent).ExecuteCommandInDir(DoubleQuoteIfNeeded(FRepoExecutable) + ' log -n 1 --grep=^git-svn-id:',LocalRepository, Output, Verbose);
if (i=0) then
begin
OutputSL:=TStringList.Create;
try
OutputSL.Text:=Output;
for i:=0 to (OutputSL.Count-1) do
begin
Output:=Trim(OutputSL.Strings[i]);
if Pos('git-svn-id:',Output)>0 then
begin
j:=Pos('@',Output);
if (j>0) then
begin
Delete(Output,1,j);
j:=Pos(' ',Output);
if (j>0) then
begin
Delete(Output,j,MaxInt);
result:=Trim(Output);
end;
end;
break;
end;
end;
finally
OutputSL.Free;
end;
end;
end;
function TGitClient.GetGitHash: string;
var
Output:string;
i,j:integer;
begin
result:='';
if ExportOnly then exit;
if NOT ValidClient then exit;
if NOT DirectoryExists(LocalRepository) then exit;
if (Length(DesiredRevision)=0) OR (Uppercase(trim(DesiredRevision)) = 'HEAD') then exit;
Output:='';
i:=TInstaller(Parent).ExecuteCommandInDir(FRepoExecutable,['log','--all','--grep=@'+DesiredRevision,'--pretty=oneline'],LocalRepository, Output, '', Verbose);
if (i=0) then
begin
j:=Pos(' ',Output);
if (j>0) then
begin
Delete(Output,j,MaxInt);
result:=Output;
end;
end;
end;
end.
| 35.199688 | 177 | 0.686212 |
f177e9b8f50568787e7dc04535134d836b479581 | 25,079 | pas | Pascal | components/jcl/source/prototypes/JclContainerIntf.pas | padcom/delcos | dc9e8ac8545c0e6c0b4e963d5baf0dc7d72d2bf0 | [
"Apache-2.0"
]
| 15 | 2016-08-24T07:32:49.000Z | 2021-11-16T11:25:00.000Z | components/jcl/source/prototypes/JclContainerIntf.pas | CWBudde/delcos | 656384c43c2980990ea691e4e52752d718fb0277 | [
"Apache-2.0"
]
| 1 | 2016-08-24T19:00:34.000Z | 2016-08-25T19:02:14.000Z | components/jcl/source/prototypes/JclContainerIntf.pas | padcom/delcos | dc9e8ac8545c0e6c0b4e963d5baf0dc7d72d2bf0 | [
"Apache-2.0"
]
| 4 | 2015-11-06T12:15:36.000Z | 2018-10-08T15:17:17.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 DCL_intf.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: }
{ Robert Marquardt (marquardt) }
{ Robert Rossmair (rrossmair) }
{ Florent Ouchet (outchy) }
{ }
{**************************************************************************************************}
{ }
{ The Delphi Container Library }
{ }
{**************************************************************************************************}
{ }
{ Last modified: $Date:: 2010-08-10 18:01:28 +0200 (mar., 10 août 2010) $ }
{ Revision: $Rev:: 3295 $ }
{ Author: $Author:: outchy $ }
{ }
{**************************************************************************************************}
unit JclContainerIntf;
{$I jcl.inc}
{$I containers\JclContainerIntf.int}
interface
uses
{$IFDEF UNITVERSIONING}
JclUnitVersioning,
{$ENDIF UNITVERSIONING}
Classes,
JclBase,
JclAnsiStrings,
JclWideStrings;
{$IFDEF BCB6}
{$DEFINE BUGGY_DEFAULT_INDEXED_PROP}
{$ENDIF BCB6}
{$IFDEF BCB10}
{$DEFINE BUGGY_DEFAULT_INDEXED_PROP}
{$ENDIF BCB10}
{$IFDEF BCB11}
{$DEFINE BUGGY_DEFAULT_INDEXED_PROP}
{$ENDIF BCB11}
const
DefaultContainerCapacity = 16;
type
// function pointer types
// iterate functions Type -> (void)
(*$JPPLOOP ALLTYPEINDEX ALLTYPECOUNT
{$JPPEXPANDMACRO ITERPROCEDURE(,,,)}*)
{$IFDEF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO ITERPROCEDURE(TIterateProcedure<T>,const ,AItem,T)}
{$ENDIF SUPPORTS_GENERICS}
// apply functions Type -> Type
(*$JPPLOOP ALLTYPEINDEX ALLTYPECOUNT
{$JPPEXPANDMACRO APPLYFUNCTION(,,,)}*)
{$IFDEF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO APPLYFUNCTION(TApplyFunction<T>,const ,AItem,T)}
{$ENDIF SUPPORTS_GENERICS}
// comparison functions Type -> Type -> Integer
(*$JPPLOOP ALLTYPEINDEX ALLTYPECOUNT
{$JPPEXPANDMACRO COMPAREFUNCTION(,,)}*)
{$IFDEF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO COMPAREFUNCTION(TCompare<T>,const ,T)}
{$ENDIF SUPPORTS_GENERICS}
// comparison for equality functions Type -> Type -> Boolean
(*$JPPLOOP ALLTYPEINDEX ALLTYPECOUNT
{$JPPEXPANDMACRO EQUALITYCOMPAREFUNCTION(,,)}*)
{$IFDEF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO EQUALITYCOMPAREFUNCTION(TEqualityCompare<T>,const ,T)}
{$ENDIF SUPPORTS_GENERICS}
// hash functions Type -> Integer
(*$JPPLOOP ALLTYPEINDEX ALLTYPECOUNT
{$JPPEXPANDMACRO HASHFUNCTION(,,,)}*)
{$IFDEF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO HASHFUNCTION(THashConvert<T>,const ,AItem,T)}
{$ENDIF SUPPORTS_GENERICS}
IJclLockable = interface
['{524AD65E-AE1B-4BC6-91C8-8181F0198BA9}']
procedure ReadLock;
procedure ReadUnlock;
procedure WriteLock;
procedure WriteUnlock;
end;
IJclAbstractIterator = interface{$IFDEF THREADSAFE}(IJclLockable){$ENDIF THREADSAFE}
['{1064D0B4-D9FC-475D-88BE-520490013B46}']
procedure Assign(const Source: IJclAbstractIterator);
procedure AssignTo(const Dest: IJclAbstractIterator);
function GetIteratorReference: TObject;
end;
IJclContainer = interface{$IFDEF THREADSAFE}(IJclLockable){$ENDIF THREADSAFE}
['{C517175A-028E-486A-BF27-5EF7FC3101D9}']
procedure Assign(const Source: IJclContainer);
procedure AssignTo(const Dest: IJclContainer);
function GetAllowDefaultElements: Boolean;
function GetContainerReference: TObject;
function GetDuplicates: TDuplicates;
function GetReadOnly: Boolean;
function GetRemoveSingleElement: Boolean;
function GetReturnDefaultElements: Boolean;
function GetThreadSafe: Boolean;
procedure SetAllowDefaultElements(Value: Boolean);
procedure SetDuplicates(Value: TDuplicates);
procedure SetReadOnly(Value: Boolean);
procedure SetRemoveSingleElement(Value: Boolean);
procedure SetReturnDefaultElements(Value: Boolean);
procedure SetThreadSafe(Value: Boolean);
property AllowDefaultElements: Boolean read GetAllowDefaultElements write SetAllowDefaultElements;
property Duplicates: TDuplicates read GetDuplicates write SetDuplicates;
property ReadOnly: Boolean read GetReadOnly write SetReadOnly;
property RemoveSingleElement: Boolean read GetRemoveSingleElement write SetRemoveSingleElement;
property ReturnDefaultElements: Boolean read GetReturnDefaultElements write SetReturnDefaultElements;
property ThreadSafe: Boolean read GetThreadSafe write SetThreadSafe;
end;
IJclStrContainer = interface(IJclContainer)
['{9753E1D7-F093-4D5C-8B32-40403F6F700E}']
function GetCaseSensitive: Boolean;
procedure SetCaseSensitive(Value: Boolean);
property CaseSensitive: Boolean read GetCaseSensitive write SetCaseSensitive;
end;
TJclAnsiStrEncoding = (seISO, seUTF8);
IJclAnsiStrContainer = interface(IJclStrContainer)
['{F8239357-B96F-46F1-A48E-B5DF25B5F1FA}']
function GetEncoding: TJclAnsiStrEncoding;
procedure SetEncoding(Value: TJclAnsiStrEncoding);
property Encoding: TJclAnsiStrEncoding read GetEncoding write SetEncoding;
end;
IJclAnsiStrFlatContainer = interface(IJclAnsiStrContainer)
['{8A45A4D4-6317-4CDF-8314-C3E5CC6899F4}']
procedure LoadFromStrings(Strings: TJclAnsiStrings);
procedure SaveToStrings(Strings: TJclAnsiStrings);
procedure AppendToStrings(Strings: TJclAnsiStrings);
procedure AppendFromStrings(Strings: TJclAnsiStrings);
function GetAsStrings: TJclAnsiStrings;
function GetAsDelimited(const Separator: AnsiString = AnsiLineBreak): AnsiString;
procedure AppendDelimited(const AString: AnsiString; const Separator: AnsiString = AnsiLineBreak);
procedure LoadDelimited(const AString: AnsiString; const Separator: AnsiString = AnsiLineBreak);
end;
TJclWideStrEncoding = (seUTF16);
IJclWideStrContainer = interface(IJclStrContainer)
['{875E1AC4-CA22-46BC-8999-048E5B9BF11D}']
function GetEncoding: TJclWideStrEncoding;
procedure SetEncoding(Value: TJclWideStrEncoding);
property Encoding: TJclWideStrEncoding read GetEncoding write SetEncoding;
end;
IJclWideStrFlatContainer = interface(IJclWideStrContainer)
['{5B001B93-CA1C-47A8-98B8-451CCB444930}']
procedure LoadFromStrings(Strings: TJclWideStrings);
procedure SaveToStrings(Strings: TJclWideStrings);
procedure AppendToStrings(Strings: TJclWideStrings);
procedure AppendFromStrings(Strings: TJclWideStrings);
function GetAsStrings: TJclWideStrings;
function GetAsDelimited(const Separator: WideString = WideLineBreak): WideString;
procedure AppendDelimited(const AString: WideString; const Separator: WideString = WideLineBreak);
procedure LoadDelimited(const AString: WideString; const Separator: WideString = WideLineBreak);
end;
{$IFDEF SUPPORTS_UNICODE_STRING}
IJclUnicodeStrContainer = interface(IJclStrContainer)
['{619BA29F-5E05-464D-B472-1C8453DBC707}']
end;
IJclUnicodeStrFlatContainer = interface(IJclUnicodeStrContainer)
['{3343D73E-4ADC-458E-8289-A4B83D1479D1}']
procedure LoadFromStrings(Strings: TJclUnicodeStrings);
procedure SaveToStrings(Strings: TJclUnicodeStrings);
procedure AppendToStrings(Strings: TJclUnicodeStrings);
procedure AppendFromStrings(Strings: TJclUnicodeStrings);
function GetAsStrings: TJclUnicodeStrings;
function GetAsDelimited(const Separator: UnicodeString = WideLineBreak): UnicodeString;
procedure AppendDelimited(const AString: UnicodeString; const Separator: UnicodeString = WideLineBreak);
procedure LoadDelimited(const AString: UnicodeString; const Separator: UnicodeString = WideLineBreak);
end;
{$ENDIF SUPPORTS_UNICODE_STRING}
IJclSingleContainer = interface(IJclContainer)
['{22BE88BD-87D1-4B4D-9FAB-F1B6D555C6A9}']
function GetPrecision: Single;
procedure SetPrecision(const Value: Single);
property Precision: Single read GetPrecision write SetPrecision;
end;
IJclDoubleContainer = interface(IJclContainer)
['{372B9354-DF6D-4CAA-A5A9-C50E1FEE5525}']
function GetPrecision: Double;
procedure SetPrecision(const Value: Double);
property Precision: Double read GetPrecision write SetPrecision;
end;
IJclExtendedContainer = interface(IJclContainer)
['{431A6482-FD5C-45A7-BE53-339A3CF75AC9}']
function GetPrecision: Extended;
procedure SetPrecision(const Value: Extended);
property Precision: Extended read GetPrecision write SetPrecision;
end;
{$IFDEF MATH_EXTENDED_PRECISION}
IJclFloatContainer = IJclExtendedContainer;
{$ENDIF MATH_EXTENDED_PRECISION}
{$IFDEF MATH_DOUBLE_PRECISION}
IJclFloatContainer = IJclDoubleContainer;
{$ENDIF MATH_DOUBLE_PRECISION}
{$IFDEF MATH_SINGLE_PRECISION}
IJclFloatContainer = IJclSingleContainer;
{$ENDIF MATH_SINGLE_PRECISION}
(*$JPPLOOP ALLTYPEINDEX ALLTYPECOUNT
{$JPPEXPANDMACRO EQUALITYCOMPARER(,,,,)}
*)
{$IFDEF SUPPORTS_GENERICS}
(*$JPPEXPANDMACRO EQUALITYCOMPARER(IJclEqualityComparer<T>,{4AF79AD6-D9F4-424B-BEAA-68857F9222B4},TEqualityCompare<T>,const ,T)*)
{$ENDIF SUPPORTS_GENERICS}
(*$JPPLOOP ALLTYPEINDEX ALLTYPECOUNT
{$JPPEXPANDMACRO COMPARER(,,,,)}
*)
{$IFDEF SUPPORTS_GENERICS}
(*$JPPEXPANDMACRO COMPARER(IJclComparer<T>,{830AFC8C-AA06-46F5-AABD-8EB46B2A9986},TCompare<T>,const ,T)*)
{$ENDIF SUPPORTS_GENERICS}
(*$JPPLOOP ALLTYPEINDEX ALLTYPECOUNT
{$JPPEXPANDMACRO HASHCONVERTER(,,,,,)}
*)
{$IFDEF SUPPORTS_GENERICS}
(*$JPPEXPANDMACRO HASHCONVERTER(IJclHashConverter<T>,{300AEA0E-7433-4C3E-99A6-E533212ACF42},THashConvert<T>,const ,AItem,T)*)
{$ENDIF SUPPORTS_GENERICS}
IJclIntfCloneable = interface
['{BCF77740-FB60-4306-9BD1-448AADE5FF4E}']
function IntfClone: IInterface;
end;
IJclCloneable = interface
['{D224AE70-2C93-4998-9479-1D513D75F2B2}']
function ObjectClone: TObject;
end;
TJclAutoPackStrategy = (apsDisabled, apsAgressive, apsProportional, apsIncremental);
// parameter signification depends on strategy
// - Disabled = unused (arrays are never packed)
// - Agressive = unused (arrays are always packed)
// - Proportional = ratio of empty slots before the array is packed
// number of empty slots is computed by this formula: Capacity div Parameter
// - Incremental = amount of empty slots before the array is packed
IJclPackable = interface
['{03802D2B-E0AB-4300-A777-0B8A2BD993DF}']
function CalcGrowCapacity(ACapacity, ASize: Integer): Integer;
function GetAutoPackParameter: Integer;
function GetAutoPackStrategy: TJclAutoPackStrategy;
function GetCapacity: Integer;
procedure Pack; // reduce used memory by eliminating empty storage area (force)
procedure SetAutoPackParameter(Value: Integer);
procedure SetAutoPackStrategy(Value: TJclAutoPackStrategy);
procedure SetCapacity(Value: Integer);
property AutoPackParameter: Integer read GetAutoPackParameter write SetAutoPackParameter;
property AutoPackStrategy: TJclAutoPackStrategy read GetAutoPackStrategy write SetAutoPackStrategy;
property Capacity: Integer read GetCapacity write SetCapacity;
end;
TJclAutoGrowStrategy = (agsDisabled, agsAgressive, agsProportional, agsIncremental);
// parameter signification depends on strategy
// - Disabled = unused (arrays never grow)
// - Agressive = unused (arrays always grow by 1 element)
// - Proportional = ratio of empty slots to add to the array
// number of empty slots is computed by this formula: Capacity div Parameter
// - Incremental = amount of empty slots to add to the array
IJclGrowable = interface(IJclPackable)
['{C71E8586-5688-444C-9BDD-9969D988123B}']
function CalcPackCapacity(ACapacity, ASize: Integer): Integer;
function GetAutoGrowParameter: Integer;
function GetAutoGrowStrategy: TJclAutoGrowStrategy;
procedure Grow;
procedure SetAutoGrowParameter(Value: Integer);
procedure SetAutoGrowStrategy(Value: TJclAutoGrowStrategy);
property AutoGrowParameter: Integer read GetAutoGrowParameter write SetAutoGrowParameter;
property AutoGrowStrategy: TJclAutoGrowStrategy read GetAutoGrowStrategy write SetAutoGrowStrategy;
end;
IJclObjectOwner = interface
['{5157EA13-924E-4A56-995D-36956441025C}']
function FreeObject(var AObject: TObject): TObject;
function GetOwnsObjects: Boolean;
property OwnsObjects: Boolean read GetOwnsObjects;
end;
IJclKeyOwner = interface
['{8BE209E6-2F85-44FD-B0CD-A8363C95349A}']
function FreeKey(var Key: TObject): TObject;
function GetOwnsKeys: Boolean;
property OwnsKeys: Boolean read GetOwnsKeys;
end;
IJclValueOwner = interface
['{3BCD98CE-7056-416A-A9E7-AE3AB2A62E54}']
function FreeValue(var Value: TObject): TObject;
function GetOwnsValues: Boolean;
property OwnsValues: Boolean read GetOwnsValues;
end;
{$IFDEF SUPPORTS_GENERICS}
IJclItemOwner<T> = interface
['{0CC220C1-E705-4B21-9F53-4AD340952165}']
function FreeItem(var AItem: T): T;
function GetOwnsItems: Boolean;
property OwnsItems: Boolean read GetOwnsItems;
end;
IJclPairOwner<TKey, TValue> = interface
['{321C1FF7-AA2E-4229-966A-7EC6417EA16D}']
function FreeKey(var Key: TKey): TKey;
function FreeValue(var Value: TValue): TValue;
function GetOwnsKeys: Boolean;
function GetOwnsValues: Boolean;
property OwnsKeys: Boolean read GetOwnsKeys;
property OwnsValues: Boolean read GetOwnsValues;
end;
{$ENDIF SUPPORTS_GENERICS}
(*$JPPLOOP ALLTYPEINDEX ALLTYPECOUNT
{$JPPEXPANDMACRO ITERATOR(,,,,,,,)}
*)
{$IFDEF SUPPORTS_GENERICS}
(*$JPPEXPANDMACRO ITERATOR(IJclIterator<T>,IJclAbstractIterator,{6E8547A4-5B5D-4831-8AE3-9C6D04071B11},const ,AItem,T,GetItem,SetItem)*)
{$ENDIF SUPPORTS_GENERICS}
(*$JPPLOOP ALLTYPEINDEX ALLTYPECOUNT
{$JPPEXPANDMACRO TREEITERATOR(,,,,,)}
*)
{$IFDEF SUPPORTS_GENERICS}
(*$JPPEXPANDMACRO TREEITERATOR(IJclTreeIterator<T>,IJclIterator<T>,{29A06DA4-D93A-40A5-8581-0FE85BC8384B},const ,AItem,T)*)
{$ENDIF SUPPORTS_GENERICS}
(*$JPPLOOP ALLTYPEINDEX ALLTYPECOUNT
{$JPPEXPANDMACRO BINTREEITERATOR(,,,)}
*)
{$IFDEF SUPPORTS_GENERICS}
(*$JPPEXPANDMACRO BINTREEITERATOR(IJclBinaryTreeIterator<T>,IJclTreeIterator<T>,{0CF5B0FC-C644-458C-BF48-2E093DAFEC26},T)*)
{$ENDIF SUPPORTS_GENERICS}
(*$JPPLOOP ALLTYPEINDEX ALLTYPECOUNT
{$JPPEXPANDMACRO COLLECTION(,,,,,,)}
*)
{$IFDEF SUPPORTS_GENERICS}
//DOM-IGNORE-BEGIN
(*$JPPEXPANDMACRO COLLECTION(IJclCollection<T>,IJclContainer,{67EE8AF3-19B0-4DCA-A730-3C9B261B8EC5},const ,AItem,T,IJclIterator<T>)*)
//DOM-IGNORE-END
{$ENDIF SUPPORTS_GENERICS}
(*$JPPLOOP ALLTYPEINDEX ALLTYPECOUNT
{$JPPEXPANDMACRO LIST(,,,,,,,,)}
*)
{$IFDEF SUPPORTS_GENERICS}
(*$JPPEXPANDMACRO LIST(IJclList<T>,IJclCollection<T>,{3B4BE3D7-8FF7-4163-91DF-3F73AE6935E7},const ,AItem,T,GetItem,SetItem,Items)*)
{$ENDIF SUPPORTS_GENERICS}
// Pointer functions for sort algorithms
(*$JPPLOOP ALLTYPEINDEX ALLTYPECOUNT
{$JPPEXPANDMACRO SORTPROC(,,)}*)
{$IFDEF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO SORTPROC(TSortProc<T>,IJclList<T>,TCompare<T>)}
{$ENDIF SUPPORTS_GENERICS}
(*$JPPLOOP ALLTYPEINDEX ALLTYPECOUNT
{$JPPEXPANDMACRO ARRAY(,,,,,,,,)}
*)
{$IFDEF SUPPORTS_GENERICS}
(*$JPPEXPANDMACRO ARRAY(IJclArray<T>,IJclList<T>,{38810C13-E35E-428A-B84F-D25FB994BE8E},const ,AItem,T,GetItem,SetItem,Items)*)
{$ENDIF SUPPORTS_GENERICS}
(*$JPPLOOP ALLTYPEINDEX ALLTYPECOUNT
{$JPPEXPANDMACRO SET(,,)}
*)
{$IFDEF SUPPORTS_GENERICS}
(*$JPPEXPANDMACRO SET(IJclSet<T>,IJclCollection<T>,{0B7CDB90-8588-4260-A54C-D87101C669EA})*)
{$ENDIF SUPPORTS_GENERICS}
TJclTraverseOrder = (toPreOrder, toOrder, toPostOrder);
(*$JPPLOOP ALLTYPEINDEX ALLTYPECOUNT
{$JPPEXPANDMACRO TREE(,,,)}
*)
{$IFDEF SUPPORTS_GENERICS}
(*$JPPEXPANDMACRO TREE(IJclTree<T>,IJclCollection<T>,{3F963AB5-5A75-41F9-A21B-7E7FB541A459},IJclTreeIterator<T>)*)
{$ENDIF SUPPORTS_GENERICS}
(*$JPPLOOP ALLMAPINDEX ALLMAPCOUNT
{$JPPEXPANDMACRO MAP(,,,,,,,,)}
*)
(*IJclMultiIntfIntfMap = interface(IJclIntfIntfMap)
['{497775A5-D3F1-49FC-A641-15CC9E77F3D0}']
function GetValues(const Key: IInterface): IJclIntfIterator;
function Count(const Key: IInterface): Integer;
end;*)
{$IFDEF SUPPORTS_GENERICS}
IHashable = interface
function GetHashCode: Integer;
end;
(*$JPPEXPANDMACRO MAP(IJclMap<TKey\,TValue>,IJclContainer,{22624C43-4828-4A1E-BDD4-4A7FE59AE135},const ,TKey,IJclSet<TKey>,const ,TValue,IJclCollection<TValue>)*)
{$ENDIF SUPPORTS_GENERICS}
(*$JPPLOOP ALLTYPEINDEX ALLTYPECOUNT
{$JPPEXPANDMACRO QUEUE(,,,,,)}
*)
{$IFDEF SUPPORTS_GENERICS}
(*$JPPEXPANDMACRO QUEUE(IJclQueue<T>,IJclContainer,{16AB909F-2194-46CF-BD89-B4207AC0CAB8},const ,AItem,T)*)
{$ENDIF SUPPORTS_GENERICS}
(*$JPPLOOP ALLMAPINDEX ALLMAPCOUNT
{$JPPEXPANDMACRO SORTEDMAP(,,,,)}
*)
{$IFDEF SUPPORTS_GENERICS}
(*$JPPEXPANDMACRO SORTEDMAP(IJclSortedMap<TKey\,TValue>,IJclMap<TKey\,TValue>,{C62B75C4-891B-442E-A5D6-9954E75A5C0C},const ,TKey)*)
{$ENDIF SUPPORTS_GENERICS}
(*$JPPLOOP ALLTYPEINDEX ALLTYPECOUNT
{$JPPEXPANDMACRO SORTEDSET(,,,,)}
*)
{$IFDEF SUPPORTS_GENERICS}
(*$JPPEXPANDMACRO SORTEDSET(IJclSortedSet<T>,IJclSet<T>,{30F836E3-2FB1-427E-A499-DFAE201633C8},const ,T)*)
{$ENDIF SUPPORTS_GENERICS}
(*$JPPLOOP ALLTYPEINDEX ALLTYPECOUNT
{$JPPEXPANDMACRO STACK(,,,,,)}
*)
{$IFDEF SUPPORTS_GENERICS}
(*$JPPEXPANDMACRO STACK(IJclStack<T>,IJclContainer,{2F08EAC9-270D-496E-BE10-5E975918A5F2},const ,AItem,T)*)
{$ENDIF SUPPORTS_GENERICS}
// Exceptions
EJclContainerError = class(EJclError);
EJclOutOfBoundsError = class(EJclContainerError)
public
// RsEOutOfBounds
constructor Create;
end;
EJclNoSuchElementError = class(EJclContainerError)
public
// RsEValueNotFound
constructor Create(const Value: string);
end;
EJclDuplicateElementError = class(EJclContainerError)
public
// RsEDuplicateElement
constructor Create;
end;
EJclIllegalArgumentError = class(EJclContainerError)
end;
EJclNoCollectionError = class(EJclIllegalArgumentError)
public
// RsENoCollection
constructor Create;
end;
EJclIllegalQueueCapacityError = class(EJclIllegalArgumentError)
public
// RsEIllegalQueueCapacity
constructor Create;
end;
EJclOperationNotSupportedError = class(EJclContainerError)
public
// RsEOperationNotSupported
constructor Create;
end;
EJclNoEqualityComparerError = class(EJclContainerError)
public
// RsENoEqualityComparer
constructor Create;
end;
EJclNoComparerError = class(EJclContainerError)
public
// RsENoComparer
constructor Create;
end;
EJclNoHashConverterError = class(EJclContainerError)
public
// RsENoHashConverter
constructor Create;
end;
EJclIllegalStateOperationError = class(EJclContainerError)
public
// RsEIllegalStateOperation
constructor Create;
end;
EJclAssignError = class(EJclContainerError)
public
// RsEAssignError
constructor Create;
end;
EJclReadOnlyError = class(EJclContainerError)
public
// RsEReadOnlyError
constructor Create;
end;
{$IFDEF UNITVERSIONING}
const
UnitVersioning: TUnitVersionInfo = (
RCSfile: '$URL: https://jcl.svn.sourceforge.net:443/svnroot/jcl/tags/JCL-2.2-Build3970/jcl/source/prototypes/JclContainerIntf.pas $';
Revision: '$Revision: 3295 $';
Date: '$Date: 2010-08-10 18:01:28 +0200 (mar., 10 août 2010) $';
LogPath: 'JCL\source\common';
Extra: '';
Data: nil
);
{$ENDIF UNITVERSIONING}
implementation
uses
SysUtils,
JclResources;
//=== { EJclOutOfBoundsError } ===============================================
constructor EJclOutOfBoundsError.Create;
begin
inherited CreateRes(@RsEOutOfBounds);
end;
//=== { EJclNoSuchElementError } =============================================
constructor EJclNoSuchElementError.Create(const Value: string);
begin
inherited CreateResFmt(@RsEValueNotFound, [Value]);
end;
//=== { EJclDuplicateElementError } ==========================================
constructor EJclDuplicateElementError.Create;
begin
inherited CreateRes(@RsEDuplicateElement);
end;
//=== { EJclIllegalQueueCapacityError } ======================================
constructor EJclIllegalQueueCapacityError.Create;
begin
inherited CreateRes(@RsEIllegalQueueCapacity);
end;
//=== { EJclNoCollectionError } ==============================================
constructor EJclNoCollectionError.Create;
begin
inherited CreateRes(@RsENoCollection);
end;
//=== { EJclOperationNotSupportedError } =====================================
constructor EJclOperationNotSupportedError.Create;
begin
inherited CreateRes(@RsEOperationNotSupported);
end;
//=== { EJclIllegalStateOperationError } =====================================
constructor EJclIllegalStateOperationError.Create;
begin
inherited CreateRes(@RsEIllegalStateOperation);
end;
//=== { EJclNoComparerError } ================================================
constructor EJclNoComparerError.Create;
begin
inherited CreateRes(@RsENoComparer);
end;
//=== { EJclNoEqualityComparerError } ========================================
constructor EJclNoEqualityComparerError.Create;
begin
inherited CreateRes(@RsENoEqualityComparer);
end;
//=== { EJclNoHashConverterError } ===========================================
constructor EJclNoHashConverterError.Create;
begin
inherited CreateRes(@RsENoHashConverter);
end;
//=== { EJclAssignError } ====================================================
constructor EJclAssignError.Create;
begin
inherited CreateRes(@RsEAssignError);
end;
//=== { EJclReadOnlyError } ==================================================
constructor EJclReadOnlyError.Create;
begin
inherited CreateRes(@RsEReadOnlyError);
end;
{$IFDEF UNITVERSIONING}
initialization
RegisterUnitVersion(HInstance, UnitVersioning);
finalization
UnregisterUnitVersion(HInstance);
{$ENDIF UNITVERSIONING}
end.
| 37.998485 | 165 | 0.653136 |
479660ad866ef20171eb4f07da09cff108d73c75 | 3,871 | pas | Pascal | Native/Delphi/Apps/InterfaceConstParmetersAndPrematureFreeing/src/InterfaceConstParmetersAndPrematureFreeingUnit.pas | jpluimers/bo.codeplex | 787ef3b5a8c6ced0a985361243c48a6c76f5d655 | [
"BSD-3-Clause"
]
| 5 | 2017-05-12T08:03:54.000Z | 2022-02-15T08:23:27.000Z | Native/Delphi/Apps/InterfaceConstParmetersAndPrematureFreeing/src/InterfaceConstParmetersAndPrematureFreeingUnit.pas | jpluimers/bo.codeplex | 787ef3b5a8c6ced0a985361243c48a6c76f5d655 | [
"BSD-3-Clause"
]
| null | null | null | Native/Delphi/Apps/InterfaceConstParmetersAndPrematureFreeing/src/InterfaceConstParmetersAndPrematureFreeingUnit.pas | jpluimers/bo.codeplex | 787ef3b5a8c6ced0a985361243c48a6c76f5d655 | [
"BSD-3-Clause"
]
| null | null | null | //{$define all}
unit InterfaceConstParmetersAndPrematureFreeingUnit;
interface
procedure Run;
implementation
uses
MyInterfacedObjectUnit,
DumpUnit, WritelnInterfacedObjectUnit;
{$ifdef all}
procedure NoPrematureFree(Reference: IInterface);
begin
Writeln(' 3.NoPrematureFree begin');
Dump(Reference); // now we do not premature free because the non-const parameter has an implicit reference count
Writeln(' 3.NoPrematureFree Reference is still alive, so it is safe to access it');
Writeln(' 3.NoPrematureFree end');
end;
procedure PrematureFree(const Reference: IInterface);
begin
Writeln(' 3.PrematureFree begin');
Dump(Reference); // now we premature free because the caller does not keep a reference to us
Writeln(' 3.PrematureFree Reference got destroyed if it had a RefCount of 1 upon entry, so now it can be unsafe to access it');
Writeln(' 3.PrematureFree end');
end;
{$endif all}
procedure PrematureFreeCrash(const Reference: IInterface);
begin
Writeln(' 3.PrematureFreeCrash begin');
try
Dump(Reference); // now we premature free because the caller does not keep a reference to us
Writeln(' 3.PrematureFreeCrash Reference got destroyed if it had a RefCount of 1 upon entry, so now it can be unsafe to access it');
Dump(Reference); // we might crash here
except
begin
Writeln(' 3.PrematureFreeCrash end with exception');
raise;
end;
end;
Writeln(' 3.PrematureFreeCrash end');
end;
{$ifdef all}
function CreateIInterfaceInstance: IInterface;
begin
Writeln(' 3.CreateIInterfaceInstance begin');
Result := TMyInterfacedObject.Create;
Writeln(' 3.CreateIInterfaceInstance begin');
end;
procedure RunNoPrematureFree;
begin
Writeln(' 2.RunNoPrematureFree begin');
NoPrematureFree(TMyInterfacedObject.Create);
Writeln(' 2.RunNoPrematureFree end');
end;
procedure RunNoPrematureFree_CreateIInterfaceInstance;
begin
Writeln(' 2.RunNoPrematureFree_CreateIInterfaceInstance begin');
NoPrematureFree(CreateIInterfaceInstance);
Writeln(' 2.RunNoPrematureFree_CreateIInterfaceInstance end');
end;
procedure RunPrematureFree;
begin
Writeln(' 2.RunPrematureFree begin');
PrematureFree(TMyInterfacedObject.Create);
Writeln(' 2.RunPrematureFree end');
end;
procedure RunPrematureFree_CreateIInterfaceInstance;
begin
Writeln(' 2.RunPrematureFree_CreateIInterfaceInstance begin');
PrematureFree(CreateIInterfaceInstance);
Writeln(' 2.RunPrematureFree_CreateIInterfaceInstance end');
end;
procedure RunPrematureFreeWithLocalVar();
var
Reference: IInterface;
begin
Writeln(' 2.RunPrematureFreeWithLocalVar begin');
Reference := TMyInterfacedObject.Create;
PrematureFree(Reference);
Writeln(' 2.RunPrematureFreeWithLocalVar end');
end;
{$endif all}
procedure RunPrematureFreeCrash;
begin
Writeln(' 2.RunPrematureFreeCrash begin');
PrematureFreeCrash(TWritelnInterfacedObject.Create);
Writeln(' 2.RunPrematureFreeCrash end');
end;
procedure Run;
begin
try
Writeln('1.Run begin');
{$ifdef all}
Writeln('');
Writeln('1.RunNoPrematureFree');
RunNoPrematureFree();
Writeln('');
Writeln('1.RunNoPrematureFree_CreateIInterfaceInstance');
RunNoPrematureFree_CreateIInterfaceInstance();
Writeln('');
Writeln('1.RunPrematureFree');
RunPrematureFree();
Writeln('');
Writeln('1.RunPrematureFree_CreateIInterfaceInstance');
RunPrematureFree_CreateIInterfaceInstance();
Writeln('');
Writeln('1.RunPrematureFreeWithLocalVar');
RunPrematureFreeWithLocalVar();
{$endif all}
Writeln('');
Writeln('1.RunPrematureFreeCrash');
RunPrematureFreeCrash();
finally
Writeln('');
Writeln('1.Run end');
end;
end;
end.
| 26.333333 | 139 | 0.724619 |
473ffaa09c12d4622c2aabbaeab23354b4328b94 | 28,793 | pas | Pascal | Version7/Source/Common/Notes.pas | dss-extensions/electricdss-src | fab07b5584090556b003ef037feb25ec2de3b7c9 | [
"BSD-3-Clause"
]
| 1 | 2022-01-23T14:43:30.000Z | 2022-01-23T14:43:30.000Z | Version8/Source/Common/Notes.pas | PMeira/electricdss-src | fab07b5584090556b003ef037feb25ec2de3b7c9 | [
"BSD-3-Clause"
]
| 7 | 2018-08-15T04:00:26.000Z | 2018-10-25T10:15:59.000Z | Version8/Source/Common/Notes.pas | PMeira/electricdss-src | fab07b5584090556b003ef037feb25ec2de3b7c9 | [
"BSD-3-Clause"
]
| null | null | null | unit Notes;
{
----------------------------------------------------------
Copyright (c) 2008-2015, Electric Power Research Institute, Inc.
All rights reserved.
----------------------------------------------------------
}
{Dummy module just for development notes.}
interface
implementation
{
TO DO:
* = done
*1. Fix so changing solution modes that requires changing the System Y matrix
causes the Y matrix to be rebuilt.
*2. Add capacitor.
*3. Add Harmonic source injection to the general load model
4. Add a specific harmonic source.
*5. Create a monitor mode that takes only magnitudes.
6. Create a monitor mode that does statistics on the fly.
7. Test other transformer connections.
*8. Add parsing of winding quantities as arrays Buses="HBus LBus Tbus" etc.
*9. Fix PCElement GetCurrent routine so that after a Solve Direct, it doesn't use inj currents.
Add a LastSolutionType variable.
*10. (Done this in conjunction with 14 - bus lists get rebuilt if changes)
Make Bus reference a usage count so that if bus.node is deleted from the network,
it is eliminated from the matrix. OR, add a small conductance to diagonal of the
System Y so that it will always solve although there is nothing connected to the node.
*11. Consolidate the Mode command interpreter in Solution and Exec into one function in Exec?,
*12. Add enable/disable property to all circuit elements.
*13. Code for opening and closing terminal switches?
*14. Handle reorder of system nodelist if a circuit element is disabled (or any other
change to the terminal connections.)
15. Add persistence - would make a great OO circuit database.
*16. Check power factor designation on load to see if leading (-) will work.
*16a. Make sure that the power factor is interpreted correctly for negative kW.
17. Resolve how multiple circuits will be handled. 2nd, 3rd, circuits are created with
a source with the same name as the first circuit. Edit command can find only first.
Also, some circuits might share elements with another circuit.
*18. help panel showing properties in a device's command list (Create a new form and let it
float freely).
*19. Add properties for symmetrical component quantities.
*20. Change syntax parser to allow default Edit command.
*21. Add Select to Interface.
*22. Check consistency of voltage definition between devices
23. Revise DSS design to have user-written stuff implemented as COM instead of DLL.
24. Look into Aggregation for ActiveX.
*25. Add UE-type calculations; Return in interface.
*26. Add EDC-like generator model that is negative load following load curves or dispatched
27. Current report prints a bogus number for single-phase loads.
?28. The Disable/Enable and Open/Close commands do not differentiate between objects of the same name in different ckts.
29. Problem with open terminal logic with delta-connected loads. IF open 2 phases, leaves 1 by 1 which is not correct.
*30. Monitor is not searching for full element name -- neither is Meter
*31. Monitor defaults to 3-phases, not the number of phases of the element.
*32. Set Yprim in Monitor to 1.e-12 on diagonal so it won't cause problem when misapplied
*33. Check Vsource short circuit data for correct computation.
*34. Add history window or file from which you can cut and paste commands or select and
execute commands.
*35. Monitor not indexing the currents right on transformers if not on the first terminal.
*36. Add Cancel button to simple error message and abort redirects and compile commands
37. Repair time should be part of base ckt element.
38. check the open terminal logic of loads
39. Save circuit will not save circuit over top of existing one.
40. Finish Equivalent model
41. Finish Sensor model for DSE
42. Connect Loadloss property on transformer to %R property
43. Implement NoLoadLoss property on transformer to insert a shunt resistance across a winding (1?)
LOG:
7-2-98: Notes unit added. Transformer was completed night before. Short circuit
testing done for 3-phase transformer. Need to test other configurations. Solve
Direct mode added. However, it was noted that there was no flag/logic to figure
out that the system Y needed to be rebuilt
7-4-98: Modified transformer to allow entry of connections and buses as arrays.
7-6-98: Added single quote and parens as legal for enclosing parameters with white space in the parser
7-9-98: Fixed bug where setting nphases for load was resetting the bus name to default value
Reversed order on Phases and Bus1 in Load.
Revised way reallocation of the BusNames array is done so that previous changes are preserved
and default names are only put in on initial allocation.
8-1-98: Added Capacitor, Tested.
Added Enabled flag to CktElement Class. No way to turn it off yet.
Fixed error in load connection interpretation (lower case)
Fixed up display in ShowResults
Removed Dynasolve command. Use 'set mode=dynamic' instead
Added 'enable' and 'disable' commands to Exec.
Changed Type=xxxx and Name=zzzz To Object=Class.Name to agree with IEEE PSAD.
8-2-98: Revised processing of bus lists so that bus name can be changed on the fly and
devices can be enabled and disabled.
Modified HashList to add a Clear Function, which leaves allocation alone, but
zeroes out the counters. Should be fast way to reestablish buslists, etc.
Enable/disable tested and refined. BusNameRedefined made property. Also sets
the flag to rebuild the SystemY.
Fixed up Show Voltages to order voltages by bus and node.
Added Open/Close command.
Moved check for open conductors to Base CktElement Class and called
'Inherited CalcYPrim' near the end of the routine. Works.
Tested Redirect.
Added facilities to handle blank lines and comments:
'//'at beginning of lines '/' may work as an abbreviation
Parser also allows ! anywhere on line.
Changed global systemY matrix flag to SystemYChanged.
8-3-98 Fixed bug where Enable was not always causing SystemY to be rebuilt
8-5-98 Add code to invalidate yprims of PCelements whenever solution is changed
from DIRECT mode to any of the power flow modes.
Added Substation classification as an option for Transformer class.
Set Sub=yes. Then when we look for substation losses, we can find them
by checking the IsSubstation value of a transformer.
Add lists of lines and transformers to the Circuit object so we can find
them more quickly too. Both are also kept in PDElement lists.
Found and fixed error in YEQ in load model - imaginary part had wrong sign.
8-6-98 Built VCL object.
Added DSSClass string to all elements because there was no way to figure out
the class of an object if you found it. (for reporting back through interface)
8-7-87 Built ActiveX control.
DSSXIMpl1.pas. Delphi converted most every thing but methods with arguments.
Fixed GetCurrents in monitor because it was default to base class. Had it report
current of monitored object terminal. Seems too work.
Wrote VB test app. Seems to work OK, except had to explicitely add
chdrive and chdir statements to get program to switch to working directory.
Discovered why when doing a new circuit twice the solution appeared to be messed up.
You can't have two objects with the same fully qualified name in the problem set
or the Edit command will only work on the first. Changed the TestForm to use the
More command instead of the Edit for changing the source.
8-12-98
Added Help command.
Added Compile as a synonym for Redirect.
Fixed bug in the bus redefinition that was not handling cases where not all
terminal-node connections were specified (in Circuit).
Fixed bug in transformer model where 1-phase wye connected voltage base
was being misinterpreted. (Recalc...)
Added Select Command to Executive
Added assumed 'edit' capability and parsing of element properties.
Added a TreeView box for Help that will automatically show all the property names.
Moved the Editcommand array to the DSSClass base class and dynamically allocated it
8-22-98
Added Fault object
Added Monte Carlo Fault Study.
Added modes to monitor to save various quantities other then just V&I.
Changed the way the buffer in Monitor object works.
8-23-98
Debugged monitor - indexing problem in MonBuffer. All modes check out.
Tested MFault algorithm. Seems to work. Kind of slow because rebuilds Y
matrix for each solution.
fixed bug in solution where the old sparseset was not being thrown away before
building a new one. This caused Esolve32 to crash after a bit, which was trapped
nicely by the raise exception in BuildYMatrix.
8-26-09
Fixed bug where fault random multiplier was inverse of what it should have been.
10-14-98
Delphi 4 introduced a Tmonitor to the system so I had to change the name of
the monitor type to TDSSMonitor.
Added Max kVA ratings to Transformer.
Added kvas= array parameter to transformer.
Changed way transformer voltage ratings are interpreted. Now like capacitor.
10-23-98 to 10-24-98
Added Property values, PropHelp to objects.
Added ? command to display a message dlg with the value of a property
Modified Dump command to dump only properties of an element when there
is a parameter on the Dump command line.
Modified Monitor to include the Mode on the header record.
10-26-98
Started addition of kWHMeter.
Completed revision of properties.
Made double-paned Help panel.
10-27-98
Fixed problem with sign of power factor in load.
Worked more on energy meter in prep for Poland IRP study.
10-28-98
Continued work on kWHMeter. Got zone established.
Changed voltage base in Load to agree with capacitor.
Got all help notes in.
Found some issues with multiple circuits.
Fixed load class/model issues.
10-29-98
Modified Ucmatrix to give Order property.
Issue worked at correcting load model.
Added solution counter to minimize recalc of current for UE search.
11-3/98
Moved NormAmps and EmergAmps to PDElement.
Added NormAmps, EmergAmps calculation to the Transformer based on the
first winding.
12-1-98
Fixed NormAmps calc in Transformer to properly account for line amps in 1-phase
L-L transformers.
Fixed the neutral definition of transformer Wye windings so that it automatically
gets set to something if neutral Z is specified.
12-2-98 - 12-5-98 Added kWhMeter
12-5-98
Found power flow algorithm had trouble converging if source was not somewhat grounded.
Solved just fine in Admittance mode, but not in current injection mode. Solved just
fine if a grounding transformer were added.
12-7-09
Fixed CktTree so that the correct pointers were being saved.
Added Save option to energy meter. MTR_metername.CSV
Added Take Action to Monitor to be consistent with meter.
12-21-98 Fixed indexing problem in transformer which resulted in improper YPrim for
3-winding transformer.
12-22-98 Removed base frequency conversion upon transferring data from Linecode to Line.
Set Line.Basefrequency = LineCode.BaseFrequency. thus, frequency compensation
is automatic in CalcYPrim.
12-30-98
Fixed bug in 3-winding transformer that caused the impedances to be rotated
by one winding.
1-4-99 Converted energy meter to trapezoidal integration so we can do load duration solutions.
1-9-99 Fixed offset in Monitor so it would properly index the currents when connected to
other than the first terminal of transformers etc which do not have numconds=numphases
1-11-99 to 1-13-99 Added generator and control panel. Miriad of misc fixes. New interface (4).
1-18-99 .. 1-20-99
Fixed DSSGlobal function to report Mode to interface correctly
Open command resulted in short circuit by eliminating row and column.
Fixed by doing a Kron reduction before eliminating row.
Set ErrorResult on ActiveElement property. =0 then it doesn't work!
NormalAmps and EmergAmps were not being brought over from line code
2-23-99
Added Abort to message dialog when in Redirect or Compile command.
Moved HelpFormX variable to Globals so we can dispose of the Form when we quit.
6/7/99
Fixed assignment problem in ImplSolution
Fixed bug in transformer creation that would sporadically give an overflow.
Added DefaultGrowthFactor. (%Growth)
6/8/99
Found that the Ellipse function in DSSGraph messed up the pen or brush or something.
Drew nodes after drawing the lines and it worked.
6/15/99
Added Version to interface and About box to DSS
Added startup validation and checking.
6/23/99 Fixed bug in which disabled device gets checked by energy meter
before energy meter is ready to be used.
6/24/99 Added IsOpen function to DSS Interface
4/18/03 Added propertysequence array and then implemented the SAVE command.
4/3/06 Changed Error Handling and Error Number
}
(* Debugging for MakePosSeq
FUNCTION DoMakePosSeq:Integer;
Var
CktElem:TDSSCktElement;
Begin
Result := 0;
ActiveCircuit.PositiveSequence := TRUE;
CktElem := ActiveCircuit.CktElements.First;
While CktElem<>Nil Do
Begin
CktElem.MakePosSequence;
CktElem := ActiveCircuit.CktElements.Next;
End;
End;
function IsGroundBus (const S: String) : Boolean;
var
i : Integer;
begin
Result := True;
i := pos ('.1', S);
if i > 0 then Result := False;
i := pos ('.2', S);
if i > 0 then Result := False;
i := pos ('.3', S);
if i > 0 then Result := False;
i := pos ('.', S);
if i = 0 then Result := False;
end;
procedure TDSSCktElement.MakePosSequence;
Var
i:Integer;
grnd: Boolean;
begin
For i := 1 to FNterms Do begin
grnd := IsGroundBus (FBusNames^[i]);
FBusNames^[i] := StripExtension(FBusNames^[i]);
if grnd then
FBusNames^[i] := FBusNames^[i] + '.0';
end;
end;
procedure TSwtControlObj.MakePosSequence;
begin
if ControlledElement <> Nil then begin
Nphases := ControlledElement.NPhases;
Nconds := FNphases;
Setbus(1, ControlledElement.GetBus(ElementTerminal));
end;
inherited;
end;
procedure TStorageControllerObj.MakePosSequence;
begin
if MonitoredElement <> Nil then begin
Nphases := MonitoredElement.NPhases;
Nconds := FNphases;
Setbus(1, MonitoredElement.GetBus(ElementTerminal));
end;
inherited;
end;
//----------------------------------------------------------------------------
PROCEDURE TStorageObj.MakePosSequence;
VAR
S :String;
V :Double;
Begin
S := 'Phases=1 conn=wye';
// Make sure voltage is line-neutral
If (Fnphases>1) or (connection<>0)
Then V := kVStorageBase/SQRT3
Else V := kVStorageBase;
S := S + Format(' kV=%-.5g',[V]);
If Fnphases>1 Then
Begin
S := S + Format(' kWrating=%-.5g PF=%-.5g',[kWrating/Fnphases, PFNominal]);
End;
Parser.CmdString := S;
Edit;
inherited; // write out other properties
End;
//=============================================================================
procedure TVsourceObj.MakePosSequence;
Var
S:String;
begin
S :='Phases=1 ';
S := S + Format('BasekV=%-.5g ', [kVbase/SQRT3]);
S := S + Format('R1=%-.5g ', [R1]);
S := S + Format('X1=%-.5g ', [X1]);
Parser.CmdString := S;
Edit;
inherited;
end;
procedure TSensorObj.MakePosSequence;
begin
if MeteredElement <> Nil then begin
Setbus(1, MeteredElement.GetBus(MeteredTerminal));
Nphases := MeteredElement.NPhases;
Nconds := MeteredElement.Nconds;
ClearSensor;
ValidSensor := TRUE;
AllocateSensorObjArrays;
ZeroSensorArrays;
RecalcVbase;
end;
Inherited;
end;
procedure TRelayObj.MakePosSequence;
begin
if MonitoredElement <> Nil then begin
Nphases := MonitoredElement.NPhases;
Nconds := FNphases;
Setbus(1, MonitoredElement.GetBus(ElementTerminal));
// Allocate a buffer bigenough to hold everything from the monitored element
ReAllocMem(cBuffer, SizeOF(cbuffer^[1]) * MonitoredElement.Yorder );
CondOffset := (ElementTerminal-1) * MonitoredElement.NConds; // for speedy sampling
end;
CASE FNPhases of
1: vbase := kVBase * 1000.0;
ELSE
vbase := kVBase/SQRT3 * 1000.0 ;
END;
PickupVolts47 := vbase * PctPickup47 * 0.01;
inherited;
end;
procedure TRegControlObj.MakePosSequence;
begin
if ControlledElement <> Nil then begin
Enabled := ControlledElement.Enabled;
If UsingRegulatedBus Then
Nphases := 1
Else
Nphases := ControlledElement.NPhases;
Nconds := FNphases;
IF Comparetext(ControlledElement.DSSClassName, 'transformer') = 0 THEN Begin
// Sets name of i-th terminal's connected bus in RegControl's buslist
// This value will be used to set the NodeRef array (see Sample function)
IF UsingRegulatedBus Then
Setbus(1, RegulatedBus) // hopefully this will actually exist
Else
Setbus(1, ControlledElement.GetBus(ElementTerminal));
ReAllocMem(VBuffer, SizeOF(Vbuffer^[1]) * ControlledElement.NPhases ); // buffer to hold regulator voltages
ReAllocMem(CBuffer, SizeOF(CBuffer^[1]) * ControlledElement.Yorder );
End;
end;
inherited;
end;
procedure TRecloserObj.MakePosSequence;
begin
if MonitoredElement <> Nil then begin
Nphases := MonitoredElement.NPhases;
Nconds := FNphases;
Setbus(1, MonitoredElement.GetBus(ElementTerminal));
// Allocate a buffer bigenough to hold everything from the monitored element
ReAllocMem(cBuffer, SizeOF(cbuffer^[1]) * MonitoredElement.Yorder );
CondOffset := (ElementTerminal-1) * MonitoredElement.NConds; // for speedy sampling
end;
inherited;
end;
procedure TReactorObj.MakePosSequence;
Var
S:String;
kvarperphase,phasekV, Rs, Rm:Double;
i,j:Integer;
begin
If FnPhases>1 Then
Begin
CASE SpecType OF
1:BEGIN // kvar
kvarPerPhase := kvarRating/Fnphases;
If (FnPhases>1) or ( Connection<>0) Then PhasekV := kVRating / SQRT3
Else PhasekV := kVRating;
S := 'Phases=1 ' + Format(' kV=%-.5g kvar=%-.5g',[PhasekV, kvarPerPhase]);
{Leave R as specified}
END;
2:BEGIN // R + j X
S := 'Phases=1 ';
END;
3:BEGIN // Matrices
S := 'Phases=1 ';
// R1
Rs := 0.0; // Avg Self
For i := 1 to FnPhases Do Rs := Rs + Rmatrix^[(i-1)*Fnphases + i];
Rs := Rs/FnPhases;
Rm := 0.0; //Avg mutual
For i := 2 to FnPhases Do
For j := i to FnPhases Do Rm := Rm + Rmatrix^[(i-1)*Fnphases + j];
Rm := Rm/(FnPhases*(Fnphases-1.0)/2.0);
S := S + Format(' R=%-.5g',[(Rs-Rm)]);
// X1
Rs := 0.0; // Avg Self
For i := 1 to FnPhases Do Rs := Rs + Xmatrix^[(i-1)*Fnphases + i];
Rs := Rs/FnPhases;
Rm := 0.0; //Avg mutual
For i := 2 to FnPhases Do
For j := i to FnPhases Do Rm := Rm + Xmatrix^[(i-1)*Fnphases + j];
Rm := Rm/(FnPhases*(Fnphases-1.0)/2.0);
S := S + Format(' X=%-.5g',[(Rs-Rm)]);
END;
END;
Parser.CmdString := S;
Edit;
End;
inherited;
end;
procedure TMonitorObj.MakePosSequence;
begin
if MeteredElement <> Nil then begin
Setbus(1, MeteredElement.GetBus(MeteredTerminal));
Nphases := MeteredElement.NPhases;
Nconds := MeteredElement.Nconds;
Case (Mode and MODEMASK) of
3: Begin
NumStateVars := TPCElement(MeteredElement).Numvariables;
ReallocMem(StateBuffer, Sizeof(StateBuffer^[1])*NumStatevars);
End;
Else
ReallocMem(CurrentBuffer, SizeOf(CurrentBuffer^[1])*MeteredElement.Yorder);
ReallocMem(VoltageBuffer, SizeOf(VoltageBuffer^[1])*MeteredElement.NConds);
End;
ClearMonitorStream;
ValidMonitor := TRUE;
end;
Inherited;
end;
procedure TLoadObj.MakePosSequence;
Var
S:String;
V:Double;
begin
S := 'Phases=1 conn=wye';
// Make sure voltage is line-neutral
If (Fnphases>1) or (connection<>0) Then V := kVLoadBase/SQRT3
Else V := kVLoadBase;
S := S + Format(' kV=%-.5g',[V]);
// Divide the load by no. phases
If Fnphases>1 Then
Begin
S := S + Format(' kW=%-.5g kvar=%-.5g',[kWbase/Fnphases, kvarbase/Fnphases]);
If FConnectedKVA>0.0 Then
S := S + Format(' xfkVA=%-.5g ',[FConnectedkVA/Fnphases]);
End;
Parser.CmdString := S;
Edit;
inherited;
end;
procedure TLineObj.MakePosSequence;
Var
S:String;
C1_new, Cs, Cm:Double;
Z1, ZS, Zm:Complex;
i,j:Integer;
begin
// set to single phase and make sure R1, X1, C1 set.
// If already single phase, let alone
If FnPhases>1 Then Begin
// Kill certain propertyvalue elements to get a cleaner looking save
PrpSequence^[3] := 0;
For i := 6 to 14 Do PrpSequence^[i] := 0;
If IsSwitch then begin
S := ' R1=1 X1=1 C1=1.1 Phases=1 Len=0.001'
end else begin
if SymComponentsModel then begin // keep the same Z1 and C1
Z1.re := R1;
Z1.im := X1;
C1_new := C1 * 1.0e9; // convert to nF
end else begin // matrix was input directly, or built from physical data
// average the diagonal and off-dialgonal elements
Zs := CZERO;
For i := 1 to FnPhases Do Caccum(Zs, Z.GetElement(i,i));
Zs := CdivReal(Zs, Fnphases);
Zm := CZERO;
For i := 1 to FnPhases-1 Do // Corrected 6-21-04
For j := i+1 to FnPhases Do Caccum(Zm, Z.GetElement(i,j));
Zm := CdivReal(Zm, (Fnphases*(FnPhases-1.0)/2.0));
Z1 := CSub(Zs, Zm);
// Do same for Capacitances
Cs := 0.0;
For i := 1 to FnPhases Do Cs := Cs + Yc.GetElement(i,i).im;
Cm := 0.0;
For i := 2 to FnPhases Do
For j := i+1 to FnPhases Do Cm := Cm + Yc.GetElement(i,j).im;
C1_new := (Cs - Cm)/TwoPi/BaseFrequency/(Fnphases*(FnPhases-1.0)/2.0) * 1.0e9; // nanofarads
end;
S := Format(' R1=%-.5g %-.5g C1=%-.5g Phases=1',[Z1.re, Z1.im, C1_new]);
end;
// Conductor Current Ratings
S := S + Format(' Normamps=%-.5g %-.5g',[NormAmps, EmergAmps]);
Parser.CmdString := S;
Edit;
End;
Inherited MakePosSequence;
end;
procedure TIsourceObj.MakePosSequence;
begin
If Fnphases>1 Then
Begin
Parser.CmdString := 'phases=1';
Edit;
End;
inherited;
end;
procedure TGeneratorObj.MakePosSequence;
Var
S :String;
V :Double;
begin
S := 'Phases=1 conn=wye';
// Make sure voltage is line-neutral
If (Fnphases>1) or (connection<>0) Then V := GenVars.kVGeneratorBase/SQRT3
Else V := GenVars.kVGeneratorBase;
S := S + Format(' kV=%-.5g',[V]);
// Divide the load by no. phases
If Fnphases>1 Then
Begin
S := S + Format(' kW=%-.5g PF=%-.5g',[kWbase/Fnphases, PFNominal]);
If (PrpSequence^[19]<>0) or (PrpSequence^[20]<>0) Then S := S + Format(' maxkvar=%-.5g minkvar=%-.5g',[kvarmax/Fnphases, kvarmin/Fnphases]);
If PrpSequence^[26]>0 Then S := S + Format(' kva=%-.5g ',[genvars.kvarating/Fnphases]);
If PrpSequence^[27]>0 Then S := S + Format(' MVA=%-.5g ',[genvars.kvarating/1000.0/Fnphases]);
End;
Parser.CmdString := S;
Edit;
inherited;
end;
procedure TGenDispatcherObj.MakePosSequence;
begin
if MonitoredElement <> Nil then begin
Nphases := ControlledElement.NPhases;
Nconds := FNphases;
Setbus(1, MonitoredElement.GetBus(ElementTerminal));
end;
inherited;
end;
procedure TEquivalentObj.MakePosSequence;
Var
S:String;
begin
/// ????
S :='Phases=1 ';
S := S + Format('BasekV=%-.5g ', [kVbase/SQRT3]);
S := S + Format('R1=%-.5g ', [R1]);
S := S + Format('X1=%-.5g ', [X1]);
Parser.CmdString := S;
Edit;
inherited;
end;
procedure TEnergyMeterobj.MakePosSequence;
begin
if MeteredElement <> Nil then begin
Setbus(1, MeteredElement.GetBus(MeteredTerminal));
Nphases := MeteredElement.NPhases;
Nconds := MeteredElement.Nconds;
AllocateSensorArrays;
IF BranchList <> NIL Then BranchList.Free;
BranchList := Nil;
end;
If HasFeeder Then MakeFeederObj;
Inherited;
end;
procedure TCapControlObj.MakePosSequence;
begin
if ControlledElement <> Nil then begin
Enabled := ControlledElement.Enabled;
Nphases := ControlledElement.NPhases;
Nconds := FNphases;
end;
if MonitoredElement <> Nil then begin
Setbus(1, MonitoredElement.GetBus(ElementTerminal));
// Allocate a buffer bigenough to hold everything from the monitored element
ReAllocMem(cBuffer, SizeOF(cbuffer^[1]) * MonitoredElement.Yorder );
CondOffset := (ElementTerminal-1) * MonitoredElement.NConds; // for speedy sampling
end;
inherited;
end;
procedure TCapacitorObj.MakePosSequence;
Var
S:String;
kvarperphase,phasekV, Cs, Cm:Double;
i,j:Integer;
begin
If FnPhases>1 Then
Begin
CASE SpecType OF
1:BEGIN // kvar
If (FnPhases>1) or ( Connection <> 0) Then PhasekV := kVRating / SQRT3
Else PhasekV := kVRating;
S := 'Phases=1 ' + Format(' kV=%-.5g kvar=(',[PhasekV]);
For i := 1 to FNumSteps Do Begin
kvarPerPhase := FkvarRating^[i]/Fnphases;
S := S+ Format(' %-.5g',[kvarPerPhase]);
End;
S := S +')';
{Leave R as specified}
END;
2:BEGIN //
S := 'Phases=1 ';
END;
3:BEGIN // C Matrix
S := 'Phases=1 ';
// R1
Cs := 0.0; // Avg Self
For i := 1 to FnPhases Do Cs := Cs + Cmatrix^[(i-1)*Fnphases + i];
Cs := Cs/FnPhases;
Cm := 0.0; //Avg mutual
For i := 2 to FnPhases Do
For j := i to FnPhases Do Cm := Cm + Cmatrix^[(i-1)*Fnphases + j];
Cm := Cm/(FnPhases*(Fnphases-1.0)/2.0);
S := S + Format(' Cuf=%-.5g',[(Cs-Cm)]);
END;
END;
Parser.CmdString := S;
Edit;
End;
inherited;
end;
*)
end.
| 37.104381 | 150 | 0.616817 |
4782c448a2dd51b60b91d405889d8cbd24287160 | 2,388 | pas | Pascal | Packages/Order Entry Results Reporting/CPRS/CPRS-Chart/Orders/fOrdersComplete.pas | rjwinchester/VistA | 6ada05a153ff670adcb62e1c83e55044a2a0f254 | [
"Apache-2.0"
]
| 72 | 2015-02-03T02:30:45.000Z | 2020-01-30T17:20:52.000Z | Packages/Order Entry Results Reporting/CPRS/CPRS-Chart/Orders/fOrdersComplete.pas | rjwinchester/VistA | 6ada05a153ff670adcb62e1c83e55044a2a0f254 | [
"Apache-2.0"
]
| 80 | 2016-04-19T12:04:06.000Z | 2020-01-31T14:35:19.000Z | Packages/Order Entry Results Reporting/CPRS/CPRS-Chart/Orders/fOrdersComplete.pas | rjwinchester/VistA | 6ada05a153ff670adcb62e1c83e55044a2a0f254 | [
"Apache-2.0"
]
| 67 | 2015-01-27T16:47:56.000Z | 2020-02-12T21:23:56.000Z | unit fOrdersComplete;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
fAutoSz, StdCtrls, ORFn, ORCtrls, VA508AccessibilityManager;
type
TfrmCompleteOrders = class(TfrmAutoSz)
Label1: TLabel;
lstOrders: TCaptionListBox;
cmdOK: TButton;
cmdCancel: TButton;
lblESCode: TLabel;
txtESCode: TCaptionEdit;
procedure FormCreate(Sender: TObject);
procedure cmdOKClick(Sender: TObject);
procedure cmdCancelClick(Sender: TObject);
private
OKPressed: Boolean;
ESCode: string;
end;
function ExecuteCompleteOrders(SelectedList: TList): Boolean;
implementation
{$R *.DFM}
uses XWBHash, rCore, rOrders, VAUtils;
function ExecuteCompleteOrders(SelectedList: TList): Boolean;
var
frmCompleteOrders: TfrmCompleteOrders;
i: Integer;
begin
Result := False;
if SelectedList.Count = 0 then Exit;
frmCompleteOrders := TfrmCompleteOrders.Create(Application);
try
ResizeFormToFont(TForm(frmCompleteOrders));
with SelectedList do for i := 0 to Count - 1 do
frmCompleteOrders.lstOrders.Items.Add(TOrder(Items[i]).Text);
frmCompleteOrders.ShowModal;
if frmCompleteOrders.OKPressed then
begin
with SelectedList do
for i := 0 to Count - 1 do CompleteOrder(TOrder(Items[i]), frmCompleteOrders.ESCode);
Result := True;
end;
finally
frmCompleteOrders.Release;
with SelectedList do for i := 0 to Count - 1 do UnlockOrder(TOrder(Items[i]).ID);
end;
end;
procedure TfrmCompleteOrders.FormCreate(Sender: TObject);
begin
inherited;
OKPressed := False;
end;
procedure TfrmCompleteOrders.cmdOKClick(Sender: TObject);
const
TX_NO_CODE = 'An electronic signature code must be entered to complete orders.';
TC_NO_CODE = 'Electronic Signature Code Required';
TX_BAD_CODE = 'The electronic signature code entered is not valid.';
TC_BAD_CODE = 'Invalid Electronic Signature Code';
begin
inherited;
if Length(txtESCode.Text) = 0 then
begin
InfoBox(TX_NO_CODE, TC_NO_CODE, MB_OK);
Exit;
end;
if not ValidESCode(txtESCode.Text) then
begin
InfoBox(TX_BAD_CODE, TC_BAD_CODE, MB_OK);
txtESCode.SetFocus;
txtESCode.SelectAll;
Exit;
end;
ESCode := Encrypt(txtESCode.Text);
OKPressed := True;
Close;
end;
procedure TfrmCompleteOrders.cmdCancelClick(Sender: TObject);
begin
inherited;
Close;
end;
end.
| 24.875 | 93 | 0.731993 |
47946afe34c5848f81d84f7a8b7c0c952bf5f427 | 598 | pas | Pascal | Apps1/NonModalFormUnit.pas | rustkas/dephi_do | 96025a01d5cb49136472b7e6bb5f037b27145fba | [
"MIT"
]
| null | null | null | Apps1/NonModalFormUnit.pas | rustkas/dephi_do | 96025a01d5cb49136472b7e6bb5f037b27145fba | [
"MIT"
]
| null | null | null | Apps1/NonModalFormUnit.pas | rustkas/dephi_do | 96025a01d5cb49136472b7e6bb5f037b27145fba | [
"MIT"
]
| null | null | null | unit NonModalFormUnit;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TNonModalForm = class(TForm)
Label1: TLabel;
bntClose: TButton;
btnCancel: TButton;
Edit1: TEdit;
procedure bntCloseClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
NonModalForm: TNonModalForm;
implementation
{$R *.dfm}
procedure TNonModalForm.bntCloseClick(Sender: TObject);
begin
CloseModal;
end;
end.
| 15.333333 | 98 | 0.727425 |
834f84f616eabf5f048860c1238e167126e73a3a | 42,260 | pas | Pascal | windows/src/ext/jedi/jcl/jcl/source/common/JclSchedule.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 219 | 2017-06-21T03:37:03.000Z | 2022-03-27T12:09:28.000Z | windows/src/ext/jedi/jcl/jcl/source/common/JclSchedule.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 4,451 | 2017-05-29T02:52:06.000Z | 2022-03-31T23:53:23.000Z | windows/src/ext/jedi/jcl/jcl/source/common/JclSchedule.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 72 | 2017-05-26T04:08:37.000Z | 2022-03-03T10:26:20.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 JclSchedule.pas. }
{ }
{ The Initial Developer of the Original Code is Marcel Bestebroer. }
{ Portions created Marcel Bestebroer are Copyright (C) Marcel Bestebroer. All rights reserved. }
{ }
{ Contributor(s): }
{ Marcel Bestebroer (marcelb) }
{ Robert Rossmair (rrossmair) }
{ Petr Vones (pvones) }
{ }
{**************************************************************************************************}
{ }
{ This unit contains scheduler classes. }
{ }
{**************************************************************************************************}
{ }
{ Last modified: $Date:: $ }
{ Revision: $Rev:: $ }
{ Author: $Author:: $ }
{ }
{**************************************************************************************************}
unit JclSchedule;
{$I jcl.inc}
interface
uses
{$IFDEF UNITVERSIONING}
JclUnitVersioning,
{$ENDIF UNITVERSIONING}
{$IFDEF HAS_UNITSCOPE}
System.SysUtils,
{$ELSE ~HAS_UNITSCOPE}
SysUtils,
{$ENDIF ~HAS_UNITSCOPE}
JclBase;
type
TScheduleRecurringKind = (srkOneShot, srkDaily, srkWeekly, srkMonthly, srkYearly);
TScheduleEndKind = (sekNone, sekDate, sekTriggerCount, sekDayCount);
TScheduleWeekDay = (swdMonday, swdTuesday, swdWednesday, swdThursday, swdFriday, swdSaturday,
swdSunday);
TScheduleWeekDays = set of TScheduleWeekDay;
TScheduleIndexKind = (sikNone, sikDay, sikWeekDay, sikWeekendDay, sikMonday, sikTuesday,
sikWednesday, sikThursday, sikFriday, sikSaturday, sikSunday);
const
sivFirst = 1;
sivSecond = 2;
sivThird = 3;
sivFourth = 4;
sivLast = -1;
type
// Forwards
IJclSchedule = interface;
IJclDailySchedule = interface;
IJclWeeklySchedule = interface;
IJclMonthlySchedule = interface;
IJclYearlySchedule = interface;
EJclScheduleError = class(EJclError);
ESchedule = EJclScheduleError;
IJclSchedule = interface(IUnknown)
['{1CC54450-7F84-4F27-B1C1-418C451DAD80}']
function GetStartDate: TTimeStamp;
function GetRecurringType: TScheduleRecurringKind;
function GetEndType: TScheduleEndKind;
function GetEndDate: TTimeStamp;
function GetEndCount: Cardinal;
procedure SetStartDate(const Value: TTimeStamp);
procedure SetRecurringType(Value: TScheduleRecurringKind);
procedure SetEndType(Value: TScheduleEndKind);
procedure SetEndDate(const Value: TTimeStamp);
procedure SetEndCount(Value: Cardinal);
function TriggerCount: Cardinal;
function DayCount: Cardinal;
function LastTriggered: TTimeStamp;
procedure InitToSavedState(const LastTriggerStamp: TTimeStamp; const LastTriggerCount,
LastDayCount: Cardinal);
procedure Reset;
function NextEvent(CountMissedEvents: Boolean = False): TTimeStamp;
function NextEventFrom(const FromEvent: TTimeStamp; CountMissedEvent: Boolean = False): TTimeStamp;
function NextEventFromNow(CountMissedEvents: Boolean = False): TTimeStamp;
property StartDate: TTimeStamp read GetStartDate write SetStartDate;
property RecurringType: TScheduleRecurringKind read GetRecurringType write SetRecurringType;
property EndType: TScheduleEndKind read GetEndType write SetEndType;
property EndDate: TTimeStamp read GetEndDate write SetEndDate;
property EndCount: Cardinal read GetEndCount write SetEndCount;
end;
IJclScheduleDayFrequency = interface(IUnknown)
['{6CF37F0D-56F4-4AE6-BBCA-7B9DFE60F50D}']
function GetStartTime: Cardinal;
function GetEndTime: Cardinal;
function GetInterval: Cardinal;
procedure SetStartTime(Value: Cardinal);
procedure SetEndTime(Value: Cardinal);
procedure SetInterval(Value: Cardinal);
property StartTime: Cardinal read GetStartTime write SetStartTime;
property EndTime: Cardinal read GetEndTime write SetEndTime;
property Interval: Cardinal read GetInterval write SetInterval;
end;
IJclDailySchedule = interface(IUnknown)
['{540E22C5-BE14-4539-AFB3-E24A67C58D8A}']
function GetEveryWeekDay: Boolean;
function GetInterval: Cardinal;
procedure SetEveryWeekDay(Value: Boolean);
procedure SetInterval(Value: Cardinal);
property EveryWeekDay: Boolean read GetEveryWeekDay write SetEveryWeekDay;
property Interval: Cardinal read GetInterval write SetInterval;
end;
IJclWeeklySchedule = interface(IUnknown)
['{73F15D99-C6A1-4526-8DE3-A2110E099BBC}']
function GetDaysOfWeek: TScheduleWeekDays;
function GetInterval: Cardinal;
procedure SetDaysOfWeek(Value: TScheduleWeekDays);
procedure SetInterval(Value: Cardinal);
property DaysOfWeek: TScheduleWeekDays read GetDaysOfWeek write SetDaysOfWeek;
property Interval: Cardinal read GetInterval write SetInterval;
end;
IJclMonthlySchedule = interface(IUnknown)
['{705E17FC-83E6-4385-8D2D-17013052E9B3}']
function GetIndexKind: TScheduleIndexKind;
function GetIndexValue: Integer;
function GetDay: Cardinal;
function GetInterval: Cardinal;
procedure SetIndexKind(Value: TScheduleIndexKind);
procedure SetIndexValue(Value: Integer);
procedure SetDay(Value: Cardinal);
procedure SetInterval(Value: Cardinal);
property IndexKind: TScheduleIndexKind read GetIndexKind write SetIndexKind;
property IndexValue: Integer read GetIndexValue write SetIndexValue;
property Day: Cardinal read GetDay write SetDay;
property Interval: Cardinal read GetInterval write SetInterval;
end;
IJclYearlySchedule = interface(IUnknown)
['{3E5303B0-FFA0-495A-96BB-14A718A01C1B}']
function GetIndexKind: TScheduleIndexKind;
function GetIndexValue: Integer;
function GetDay: Cardinal;
function GetMonth: Cardinal;
function GetInterval: Cardinal;
procedure SetIndexKind(Value: TScheduleIndexKind);
procedure SetIndexValue(Value: Integer);
procedure SetDay(Value: Cardinal);
procedure SetMonth(Value: Cardinal);
procedure SetInterval(Value: Cardinal);
property IndexKind: TScheduleIndexKind read GetIndexKind write SetIndexKind;
property IndexValue: Integer read GetIndexValue write SetIndexValue;
property Day: Cardinal read GetDay write SetDay;
property Month: Cardinal read GetMonth write SetMonth;
property Interval: Cardinal read GetInterval write SetInterval;
end;
function CreateSchedule: IJclSchedule;
{$IFDEF UNITVERSIONING}
const
UnitVersioning: TUnitVersionInfo = (
RCSfile: '$URL$';
Revision: '$Revision$';
Date: '$Date$';
LogPath: 'JCL\source\common';
Extra: '';
Data: nil
);
{$ENDIF UNITVERSIONING}
implementation
uses
JclDateTime, JclResources;
//=== { TJclScheduleAggregate } ==============================================
type
TJclScheduleAggregate = class(TAggregatedObject)
protected
procedure CheckInterfaceAllowed;
function InterfaceAllowed: Boolean;
function Schedule: IJclSchedule;
class function RecurringType: TScheduleRecurringKind; virtual;
function ValidStamp(const Stamp: TTimeStamp): Boolean; virtual; abstract;
procedure MakeValidStamp(var Stamp: TTimeStamp); virtual; abstract;
function NextValidStamp(const Stamp: TTimeStamp): TTimeStamp; virtual; abstract;
end;
procedure TJclScheduleAggregate.CheckInterfaceAllowed;
begin
if not InterfaceAllowed then
RunError(23); // reIntfCastError
end;
function TJclScheduleAggregate.InterfaceAllowed: Boolean;
begin
Result := Schedule.RecurringType = RecurringType;
end;
function TJclScheduleAggregate.Schedule: IJclSchedule;
begin
Result := Controller as IJclSchedule;
end;
class function TJclScheduleAggregate.RecurringType: TScheduleRecurringKind;
begin
Result := srkOneShot;
end;
//=== { TJclDayFrequency } ===================================================
type
TJclDayFrequency = class(TAggregatedObject, IJclScheduleDayFrequency, IInterface)
private
FStartTime: Cardinal;
FEndTime: Cardinal;
FInterval: Cardinal;
protected
function ValidStamp(const Stamp: TTimeStamp): Boolean;
function NextValidStamp(const Stamp: TTimeStamp): TTimeStamp;
public
constructor Create(const Controller: IUnknown);
{ IJclScheduleDayFrequency }
function GetStartTime: Cardinal;
function GetEndTime: Cardinal;
function GetInterval: Cardinal;
procedure SetStartTime(Value: Cardinal);
procedure SetEndTime(Value: Cardinal);
procedure SetInterval(Value: Cardinal);
property StartTime: Cardinal read GetStartTime write SetStartTime;
property EndTime: Cardinal read GetEndTime write SetEndTime;
property Interval: Cardinal read GetInterval write SetInterval;
end;
constructor TJclDayFrequency.Create(const Controller: IUnknown);
begin
inherited Create(Controller);
FStartTime := 0;
FEndTime := HoursToMSecs(24) - 1;
FInterval := 500;
end;
function TJclDayFrequency.ValidStamp(const Stamp: TTimeStamp): Boolean;
begin
Result := (Cardinal(Stamp.Time) >= FStartTime) and (Cardinal(Stamp.Time) <= FEndTime) and
((Cardinal(Stamp.Time) - FStartTime) mod FInterval = 0);
end;
function TJclDayFrequency.NextValidStamp(const Stamp: TTimeStamp): TTimeStamp;
begin
Result := Stamp;
if Stamp.Time < Integer(FStartTime) then
Result.Time := FStartTime
else
if ((Cardinal(Stamp.Time) - FStartTime) mod FInterval) <> 0 then
Result.Time := Stamp.Time + Integer(FInterval-(Cardinal(Stamp.Time) - FStartTime) mod FInterval)
else
Result.Time := Stamp.Time + Integer(FInterval);
if (Result.Time < 0) or (Cardinal(Result.Time) > FEndTime) then
Result := NullStamp;
end;
function TJclDayFrequency.GetStartTime: Cardinal;
begin
Result := FStartTime;
end;
function TJclDayFrequency.GetEndTime: Cardinal;
begin
Result := FEndTime;
end;
function TJclDayFrequency.GetInterval: Cardinal;
begin
Result := FInterval;
end;
procedure TJclDayFrequency.SetStartTime(Value: Cardinal);
begin
if Value <> FStartTime then
begin
if Value >= Cardinal(HoursToMSecs(24)) then
raise EJclScheduleError.CreateRes(@RsScheduleInvalidTime);
FStartTime := Value;
if EndTime < StartTime then
FEndTime := Value;
end;
end;
procedure TJclDayFrequency.SetEndTime(Value: Cardinal);
begin
if Value <> FEndTime then
begin
if Value < FStartTime then
raise EJclScheduleError.CreateRes(@RsScheduleEndBeforeStart);
if Value >= Cardinal(HoursToMSecs(24)) then
raise EJclScheduleError.CreateRes(@RsScheduleInvalidTime);
FEndTime := Value;
end;
end;
procedure TJclDayFrequency.SetInterval(Value: Cardinal);
begin
if Value <> FInterval then
begin
if Value >= Cardinal(HoursToMSecs(24)) then
raise EJclScheduleError.CreateRes(@RsScheduleInvalidTime);
if Value = 0 then
begin
FEndTime := FStartTime;
FInterval := 1;
end
else
FInterval := Value;
end;
end;
//=== { TJclDailySchedule } ==================================================
type
TJclDailySchedule = class(TJclScheduleAggregate, IJclDailySchedule, IInterface)
private
FEveryWeekDay: Boolean;
FInterval: Cardinal;
protected
class function RecurringType: TScheduleRecurringKind; override;
function ValidStamp(const Stamp: TTimeStamp): Boolean; override;
procedure MakeValidStamp(var Stamp: TTimeStamp); override;
function NextValidStamp(const Stamp: TTimeStamp): TTimeStamp; override;
public
constructor Create(const Controller: IUnknown);
{ IJclDailySchedule }
function GetEveryWeekDay: Boolean;
function GetInterval: Cardinal;
procedure SetEveryWeekDay(Value: Boolean);
procedure SetInterval(Value: Cardinal);
property EveryWeekDay: Boolean read GetEveryWeekDay write SetEveryWeekDay;
property Interval: Cardinal read GetInterval write SetInterval;
end;
constructor TJclDailySchedule.Create(const Controller: IUnknown);
begin
inherited Create(Controller);
FEveryWeekDay := True;
FInterval := 1;
end;
class function TJclDailySchedule.RecurringType: TScheduleRecurringKind;
begin
Result := srkDaily;
end;
function TJclDailySchedule.ValidStamp(const Stamp: TTimeStamp): Boolean;
begin
Result := (FEveryWeekDay and (TimeStampDOW(Stamp) < 6)) or
(not FEveryWeekDay and (Cardinal(Stamp.Date - Schedule.StartDate.Date) mod Interval = 0));
end;
procedure TJclDailySchedule.MakeValidStamp(var Stamp: TTimeStamp);
begin
if FEveryWeekDay and (TimeStampDOW(Stamp) >= 6) then
Inc(Stamp.Date, 2 - (TimeStampDOW(Stamp) - 6))
else
if not FEveryWeekDay and (Cardinal(Stamp.Date - Schedule.StartDate.Date) mod Interval <> 0) then
Inc(Stamp.Date, Interval - Cardinal(Stamp.Date - Schedule.StartDate.Date) mod Interval);
end;
function TJclDailySchedule.NextValidStamp(const Stamp: TTimeStamp): TTimeStamp;
begin
Result := Stamp;
MakeValidStamp(Result);
if EqualTimeStamps(Stamp, Result) then
begin
// Time stamp has not been adjusted (it was valid). Determine the next time stamp
if FEveryWeekDay then
begin
Inc(Result.Date);
MakeValidStamp(Result); // Skip over the weekend.
end
else
Inc(Result.Date, Interval); // always valid as we started with a valid stamp
end;
end;
function TJclDailySchedule.GetEveryWeekDay: Boolean;
begin
CheckInterfaceAllowed;
Result := FEveryWeekDay;
end;
function TJclDailySchedule.GetInterval: Cardinal;
begin
CheckInterfaceAllowed;
if EveryWeekDay then
Result := 0
else
Result := FInterval;
end;
procedure TJclDailySchedule.SetEveryWeekDay(Value: Boolean);
begin
CheckInterfaceAllowed;
FEveryWeekDay := Value;
end;
procedure TJclDailySchedule.SetInterval(Value: Cardinal);
begin
CheckInterfaceAllowed;
if Value = 0 then
raise EJclScheduleError.CreateRes(@RsScheduleIntervalZero);
if FEveryWeekDay then
FEveryWeekDay := False;
if Value <> FInterval then
FInterval := Value;
end;
//=== { TJclWeeklySchedule } =================================================
type
TJclWeeklySchedule = class(TJclScheduleAggregate, IJclWeeklySchedule, IInterface)
private
FDaysOfWeek: TScheduleWeekDays;
FInterval: Cardinal;
protected
class function RecurringType: TScheduleRecurringKind; override;
function ValidStamp(const Stamp: TTimeStamp): Boolean; override;
procedure MakeValidStamp(var Stamp: TTimeStamp); override;
function NextValidStamp(const Stamp: TTimeStamp): TTimeStamp; override;
public
constructor Create(const Controller: IUnknown);
{ IJclWeeklySchedule }
function GetDaysOfWeek: TScheduleWeekDays;
function GetInterval: Cardinal;
procedure SetDaysOfWeek(Value: TScheduleWeekDays);
procedure SetInterval(Value: Cardinal);
property DaysOfWeek: TScheduleWeekDays read GetDaysOfWeek write SetDaysOfWeek;
property Interval: Cardinal read GetInterval write SetInterval;
end;
constructor TJclWeeklySchedule.Create(const Controller: IUnknown);
begin
inherited Create(Controller);
FDaysOfWeek := [swdMonday];
FInterval := 1;
end;
class function TJclWeeklySchedule.RecurringType: TScheduleRecurringKind;
begin
Result := srkWeekly;
end;
function TJclWeeklySchedule.ValidStamp(const Stamp: TTimeStamp): Boolean;
begin
Result := (TScheduleWeekDay(TimeStampDOW(Stamp)) in DaysOfWeek) and
(Cardinal((Stamp.Date - Schedule.StartDate.Date) div 7) mod Interval = 0);
end;
procedure TJclWeeklySchedule.MakeValidStamp(var Stamp: TTimeStamp);
begin
while not (TScheduleWeekDay(TimeStampDOW(Stamp) - 1) in DaysOfWeek) do
Inc(Stamp.Date);
if (Stamp.Date - Schedule.StartDate.Date) <> 0 then
begin
if Cardinal((Stamp.Date - Schedule.StartDate.Date) div 7) mod Interval <> 0 then
Inc(Stamp.Date, 7 * (Interval -
(Cardinal((Stamp.Date - Schedule.StartDate.Date) div 7) mod Interval)));
end;
end;
function TJclWeeklySchedule.NextValidStamp(const Stamp: TTimeStamp): TTimeStamp;
begin
Result := Stamp;
MakeValidStamp(Result);
if EqualTimeStamps(Stamp, Result) then
begin
// Time stamp has not been adjusted (it was valid). Determine the next time stamp
Inc(Result.Date);
MakeValidStamp(Result); // Skip over unwanted days and weeks
end;
end;
function TJclWeeklySchedule.GetDaysOfWeek: TScheduleWeekDays;
begin
CheckInterfaceAllowed;
Result := FDaysOfWeek;
end;
function TJclWeeklySchedule.GetInterval: Cardinal;
begin
CheckInterfaceAllowed;
Result := FInterval;
end;
procedure TJclWeeklySchedule.SetDaysOfWeek(Value: TScheduleWeekDays);
begin
CheckInterfaceAllowed;
if Value = [] then
raise EJclScheduleError.CreateRes(@RsScheduleNoDaySpecified);
FDaysOfWeek := Value;
end;
procedure TJclWeeklySchedule.SetInterval(Value: Cardinal);
begin
CheckInterfaceAllowed;
if Value = 0 then
raise EJclScheduleError.CreateRes(@RsScheduleIntervalZero);
FInterval := Value;
end;
//=== { TJclMonthlySchedule } ================================================
type
TJclMonthlySchedule = class(TJclScheduleAggregate, IJclMonthlySchedule, IInterface)
private
FIndexKind: TScheduleIndexKind;
FIndexValue: Integer;
FDay: Cardinal;
FInterval: Cardinal;
protected
class function RecurringType: TScheduleRecurringKind; override;
function ValidStamp(const Stamp: TTimeStamp): Boolean; override;
procedure MakeValidStamp(var Stamp: TTimeStamp); override;
function NextValidStamp(const Stamp: TTimeStamp): TTimeStamp; override;
function ValidStampMonthIndex(const TYear, TMonth, TDay: Word): Boolean;
procedure MakeValidStampMonthIndex(var TYear, TMonth, TDay: Word);
public
constructor Create(const Controller: IUnknown);
{ IJclMonthlySchedule }
function GetIndexKind: TScheduleIndexKind;
function GetIndexValue: Integer;
function GetDay: Cardinal;
function GetInterval: Cardinal;
procedure SetIndexKind(Value: TScheduleIndexKind);
procedure SetIndexValue(Value: Integer);
procedure SetDay(Value: Cardinal);
procedure SetInterval(Value: Cardinal);
property IndexKind: TScheduleIndexKind read GetIndexKind write SetIndexKind;
property IndexValue: Integer read GetIndexValue write SetIndexValue;
property Day: Cardinal read GetDay write SetDay;
property Interval: Cardinal read GetInterval write SetInterval;
end;
constructor TJclMonthlySchedule.Create(const Controller: IUnknown);
begin
inherited Create(Controller);
FIndexKind := sikNone;
FIndexValue := sivFirst;
FDay := 1;
FInterval := 1;
end;
class function TJclMonthlySchedule.RecurringType: TScheduleRecurringKind;
begin
Result := srkMonthly;
end;
function TJclMonthlySchedule.ValidStamp(const Stamp: TTimeStamp): Boolean;
var
SYear, SMonth, SDay: Word;
TYear, TMonth, TDay: Word;
begin
DecodeDate(TimeStampToDateTime(Schedule.StartDate), SYear, SMonth, SDay);
DecodeDate(TimeStampToDateTime(Stamp), TYear, TMonth, TDay);
Result := (((TYear * 12 + TMonth) - (SYear * 12 + SMonth)) mod Integer(Interval) = 0) and
ValidStampMonthIndex(TYear, TMonth, TDay);
end;
procedure TJclMonthlySchedule.MakeValidStamp(var Stamp: TTimeStamp);
var
SYear, SMonth, SDay: Word;
TYear, TMonth, TDay: Word;
MonthDiff: Integer;
begin
DecodeDate(TimeStampToDateTime(Schedule.StartDate), SYear, SMonth, SDay);
DecodeDate(TimeStampToDateTime(Stamp), TYear, TMonth, TDay);
MonthDiff := (TYear * 12 + TMonth) - (SYear * 12 + SMonth);
if MonthDiff mod Integer(Interval) <> 0 then
begin
Inc(TMonth, Integer(Interval) - (MonthDiff mod Integer(Interval)));
if TMonth > 12 then
begin
Inc(TYear, TMonth div 12);
TMonth := TMonth mod 12;
end;
TDay := 1;
end;
MakeValidStampMonthIndex(TYear, TMonth, TDay);
while DateTimeToTimeStamp(JclDateTime.EncodeDate(TYear, TMonth, TDay)).Date < Stamp.Date do
begin
Inc(TMonth, Integer(Interval));
if TMonth > 12 then
begin
Inc(TYear, TMonth div 12);
TMonth := TMonth mod 12;
end;
MakeValidStampMonthIndex(TYear, TMonth, TDay);
end;
Stamp.Date := DateTimeToTimeStamp(JclDateTime.EncodeDate(TYear, TMonth, TDay)).Date;
end;
function TJclMonthlySchedule.NextValidStamp(const Stamp: TTimeStamp): TTimeStamp;
begin
Result := Stamp;
MakeValidStamp(Result);
if EqualTimeStamps(Stamp, Result) then
begin
// Time stamp has not been adjusted (it was valid). Determine the next time stamp
Inc(Result.Date);
MakeValidStamp(Result); // Skip over unwanted days and months
end;
end;
function TJclMonthlySchedule.ValidStampMonthIndex(const TYear, TMonth, TDay: Word): Boolean;
var
DIM: Integer;
TempDay: Integer;
begin
DIM := DaysInMonth(JclDateTime.EncodeDate(TYear, TMonth, 1));
case IndexKind of
sikNone:
Result := (TDay = Day) or ((Integer(Day) > DIM) and (TDay = DIM));
sikDay:
Result :=
((IndexValue = sivLast) and (TDay = DIM)) or
((IndexValue <> sivLast) and (
(TDay = IndexValue) or (
(IndexValue > DIM) and
(TDay = DIM)
) or (
(IndexValue < 0) and (
(TDay = DIM + 1 + IndexValue) or (
(-IndexValue > DIM) and
(TDay = 1)
)
)
)
));
sikWeekDay:
begin
case IndexValue of
sivFirst:
TempDay := FirstWeekDay(TYear, TMonth);
sivLast:
TempDay := LastWeekDay(TYear, TMonth);
else
TempDay := IndexedWeekDay(TYear, TMonth, IndexValue);
if TempDay = 0 then
begin
if IndexValue > 0 then
TempDay := LastWeekDay(TYear, TMonth)
else
if IndexValue < 0 then
TempDay := FirstWeekDay(TYear, TMonth);
end;
end;
Result := TDay = TempDay;
end;
sikWeekendDay:
begin
case IndexValue of
sivFirst:
TempDay := FirstWeekendDay(TYear, TMonth);
sivLast:
TempDay := LastWeekendDay(TYear, TMonth);
else
TempDay := IndexedWeekendDay(TYear, TMonth, IndexValue);
if TempDay = 0 then
begin
if IndexValue > 0 then
TempDay := LastWeekendDay(TYear, TMonth)
else
if IndexValue < 0 then
TempDay := FirstWeekendDay(TYear, TMonth);
end;
end;
Result := TDay = TempDay;
end;
sikMonday..sikSunday:
begin
case IndexValue of
sivFirst:
TempDay := FirstDayOfWeek(TYear, TMonth, Ord(IndexKind) - Ord(sikWeekendDay));
sivLast:
TempDay := LastDayOfWeek(TYear, TMonth, Ord(IndexKind) - Ord(sikWeekendDay));
else
TempDay := IndexedDayOfWeek(TYear, TMonth, Ord(IndexKind) - Ord(sikWeekendDay),
IndexValue);
if TempDay = 0 then
begin
if IndexValue > 0 then
TempDay := LastDayOfWeek(TYear, TMonth, Ord(IndexKind) - Ord(sikWeekendDay))
else
if IndexValue < 0 then
TempDay := FirstDayOfWeek(TYear, TMonth, Ord(IndexKind) - Ord(sikWeekendDay));
end;
end;
Result := TDay = TempDay;
end;
else
Result := False;
end;
end;
procedure TJclMonthlySchedule.MakeValidStampMonthIndex(var TYear, TMonth, TDay: Word);
var
DIM: Integer;
begin
DIM := DaysInMonth(JclDateTime.EncodeDate(TYear, TMonth, 1));
case IndexKind of
sikNone:
begin
TDay := Day;
if Integer(Day) > DIM then
TDay := DIM;
end;
sikDay:
begin
if (IndexValue = sivLast) or (Integer(IndexValue) > DIM) then
TDay := DIM
else
if IndexValue > 0 then
TDay := IndexValue
else
begin
if -IndexValue > DIM then
TDay := 1
else
TDay := DIM + 1 + IndexValue;
end;
end;
sikWeekDay:
begin
case IndexValue of
sivFirst:
TDay := FirstWeekDay(TYear, TMonth);
sivLast:
TDay := LastWeekDay(TYear, TMonth);
else
begin
TDay := IndexedWeekDay(TYear, TMonth, IndexValue);
if TDay = 0 then
begin
if IndexValue > 0 then
TDay := LastWeekDay(TYear, TMonth)
else
if IndexValue < 0 then
TDay := FirstWeekDay(TYear, TMonth);
end;
end;
end;
end;
sikWeekendDay:
begin
case IndexValue of
sivFirst:
TDay := FirstWeekendDay(TYear, TMonth);
sivLast:
TDay := LastWeekendDay(TYear, TMonth);
else
begin
TDay := IndexedWeekendDay(TYear, TMonth, IndexValue);
if TDay = 0 then
begin
if IndexValue > 0 then
TDay := LastWeekendDay(TYear, TMonth)
else
if IndexValue < 0 then
TDay := FirstWeekendDay(TYear, TMonth);
end;
end;
end;
end;
sikMonday..sikSunday:
begin
case IndexValue of
sivFirst:
TDay := FirstDayOfWeek(TYear, TMonth, Ord(IndexKind) - Ord(sikWeekendDay));
sivLast:
TDay := LastDayOfWeek(TYear, TMonth, Ord(IndexKind) - Ord(sikWeekendDay));
else
TDay := IndexedDayOfWeek(TYear, TMonth, Ord(IndexKind) - Ord(sikWeekendDay),
IndexValue);
if TDay = 0 then
begin
if IndexValue > 0 then
TDay := LastDayOfWeek(TYear, TMonth, Ord(IndexKind) - Ord(sikWeekendDay))
else
if IndexValue < 0 then
TDay := FirstDayOfWeek(TYear, TMonth, Ord(IndexKind) - Ord(sikWeekendDay));
end;
end;
end;
end;
end;
function TJclMonthlySchedule.GetIndexKind: TScheduleIndexKind;
begin
CheckInterfaceAllowed;
Result := FIndexKind;
end;
function TJclMonthlySchedule.GetIndexValue: Integer;
begin
CheckInterfaceAllowed;
if not (FIndexKind in [sikDay .. sikSunday]) then
raise EJclScheduleError.CreateRes(@RsScheduleIndexValueSup);
Result := FIndexValue;
end;
function TJclMonthlySchedule.GetDay: Cardinal;
begin
CheckInterfaceAllowed;
Result := FDay;
end;
function TJclMonthlySchedule.GetInterval: Cardinal;
begin
CheckInterfaceAllowed;
Result := FInterval;
end;
procedure TJclMonthlySchedule.SetIndexKind(Value: TScheduleIndexKind);
begin
CheckInterfaceAllowed;
FIndexKind := Value;
end;
procedure TJclMonthlySchedule.SetIndexValue(Value: Integer);
begin
CheckInterfaceAllowed;
if not (FIndexKind in [sikDay .. sikSunday]) then
raise EJclScheduleError.CreateRes(@RsScheduleIndexValueSup);
if Value = 0 then
raise EJclScheduleError.CreateRes(@RsScheduleIndexValueZero);
FIndexValue := Value;
end;
procedure TJclMonthlySchedule.SetDay(Value: Cardinal);
begin
CheckInterfaceAllowed;
if not (FIndexKind in [sikNone]) then
raise EJclScheduleError.CreateRes(@RsScheduleDayNotSupported);
if (Value = 0) or (Value > 31) then
raise EJclScheduleError.CreateRes(@RsScheduleDayInRange);
FDay := Value;
end;
procedure TJclMonthlySchedule.SetInterval(Value: Cardinal);
begin
CheckInterfaceAllowed;
if Value = 0 then
raise EJclScheduleError.CreateRes(@RsScheduleIntervalZero);
FInterval := Value;
end;
//=== { TJclYearlySchedule } =================================================
type
TJclYearlySchedule = class(TJclMonthlySchedule, IJclYearlySchedule, IInterface)
private
FMonth: Cardinal;
protected
class function RecurringType: TScheduleRecurringKind; override;
function ValidStamp(const Stamp: TTimeStamp): Boolean; override;
procedure MakeValidStamp(var Stamp: TTimeStamp); override;
function NextValidStamp(const Stamp: TTimeStamp): TTimeStamp; override;
public
constructor Create(const Controller: IUnknown);
{ IJclYearlySchedule }
function GetMonth: Cardinal;
procedure SetMonth(Value: Cardinal);
property Month: Cardinal read GetMonth write SetMonth;
end;
constructor TJclYearlySchedule.Create(const Controller: IUnknown);
begin
inherited Create(Controller);
FMonth := 1;
end;
class function TJclYearlySchedule.RecurringType: TScheduleRecurringKind;
begin
Result := srkYearly;
end;
function TJclYearlySchedule.ValidStamp(const Stamp: TTimeStamp): Boolean;
var
SYear, SMonth, SDay: Word;
TYear, TMonth, TDay: Word;
begin
JclDateTime.DecodeDate(TimeStampToDateTime(Schedule.StartDate), SYear, SMonth, SDay);
JclDateTime.DecodeDate(TimeStampToDateTime(Stamp), TYear, TMonth, TDay);
Result := ((TYear - SYear) mod Integer(Interval) = 0) and (TMonth = Month) and
ValidStampMonthIndex(TYear, TMonth, TDay);
end;
procedure TJclYearlySchedule.MakeValidStamp(var Stamp: TTimeStamp);
var
SYear, SMonth, SDay: Word;
TYear, TMonth, TDay: Word;
YearDiff: Integer;
begin
JclDateTime.DecodeDate(TimeStampToDateTime(Schedule.StartDate), SYear, SMonth, SDay);
JclDateTime.DecodeDate(TimeStampToDateTime(Stamp), TYear, TMonth, TDay);
YearDiff := TYear - SYear;
if YearDiff mod Integer(Interval) <> 0 then
begin
Inc(TYear, Integer(Interval) - (YearDiff mod Integer(Interval)));
TMonth := Month;
TDay := 1;
end;
MakeValidStampMonthIndex(TYear, TMonth, TDay);
while DateTimeToTimeStamp(JclDateTime.EncodeDate(TYear, TMonth, TDay)).Date < Stamp.Date do
begin
Inc(TYear, Integer(Interval));
TMonth := Month;
TDay := 1;
MakeValidStampMonthIndex(TYear, TMonth, TDay);
end;
Stamp.Date := DateTimeToTimeStamp(JclDateTime.EncodeDate(TYear, TMonth, TDay)).Date;
end;
function TJclYearlySchedule.NextValidStamp(const Stamp: TTimeStamp): TTimeStamp;
begin
Result := Stamp;
MakeValidStamp(Result);
if EqualTimeStamps(Stamp, Result) then
begin
// Time stamp has not been adjusted (it was valid). Determine the next time stamp
Inc(Result.Date);
MakeValidStamp(Result); // Skip over unwanted days and months
end;
end;
function TJclYearlySchedule.GetMonth: Cardinal;
begin
CheckInterfaceAllowed;
Result := FMonth;
end;
procedure TJclYearlySchedule.SetMonth(Value: Cardinal);
begin
CheckInterfaceAllowed;
if (Value < 1) or (Value > 12) then
raise EJclScheduleError.CreateRes(@RsScheduleMonthInRange);
FMonth := Value;
end;
//=== { TJclSchedule } =======================================================
type
TJclSchedule = class(TInterfacedObject, IJclSchedule, IJclScheduleDayFrequency, IJclDailySchedule,
IJclWeeklySchedule, IJclMonthlySchedule, IJclYearlySchedule)
private
FStartDate: TTimeStamp;
FRecurringType: TScheduleRecurringKind;
FEndType: TScheduleEndKind;
FEndDate: TTimeStamp;
FEndCount: Cardinal;
FDayFrequency: TJclDayFrequency;
FDailySchedule: TJclDailySchedule;
FWeeklySchedule: TJclWeeklySchedule;
FMonthlySchedule: TJclMonthlySchedule;
FYearlySchedule: TJclYearlySchedule;
protected
FTriggerCount: Cardinal;
FDayCount: Cardinal;
FLastEvent: TTimeStamp;
function GetNextEventStamp(const From: TTimeStamp): TTimeStamp;
public
constructor Create;
destructor Destroy; override;
{ IJclSchedule }
function GetStartDate: TTimeStamp;
function GetRecurringType: TScheduleRecurringKind;
function GetEndType: TScheduleEndKind;
function GetEndDate: TTimeStamp;
function GetEndCount: Cardinal;
procedure SetStartDate(const Value: TTimeStamp);
procedure SetRecurringType(Value: TScheduleRecurringKind);
procedure SetEndType(Value: TScheduleEndKind);
procedure SetEndDate(const Value: TTimeStamp);
procedure SetEndCount(Value: Cardinal);
function TriggerCount: Cardinal;
function DayCount: Cardinal;
function LastTriggered: TTimeStamp;
procedure InitToSavedState(const LastTriggerStamp: TTimeStamp; const LastTriggerCount,
LastDayCount: Cardinal);
procedure Reset;
function NextEvent(CountMissedEvents: Boolean = False): TTimeStamp;
function NextEventFrom(const FromEvent: TTimeStamp;
CountMissedEvent: Boolean = False): TTimeStamp;
function NextEventFromNow(CountMissedEvents: Boolean = False): TTimeStamp;
property StartDate: TTimeStamp read GetStartDate write SetStartDate;
property RecurringType: TScheduleRecurringKind read GetRecurringType write SetRecurringType;
property EndType: TScheduleEndKind read GetEndType write SetEndType;
property EndDate: TTimeStamp read GetEndDate write SetEndDate;
property EndCount: Cardinal read GetEndCount write SetEndCount;
{ IJclScheduleDayFrequency }
function GetDayFrequency: IJclScheduleDayFrequency;
property DayFrequency: IJclScheduleDayFrequency read GetDayFrequency implements IJclScheduleDayFrequency;
{ IJclDailySchedule }
function GetDailySchedule: IJclDailySchedule;
property DailySchedule: IJclDailySchedule read GetDailySchedule implements IJclDailySchedule;
{ IJclWeeklySchedule }
function GetWeeklySchedule: IJclWeeklySchedule;
property WeeklySchedule: IJclWeeklySchedule read GetWeeklySchedule implements IJclWeeklySchedule;
{ IJclMonthlySchedule }
function GetMonthlySchedule: IJclMonthlySchedule;
property MonthlySchedule: IJclMonthlySchedule read GetMonthlySchedule implements IJclMonthlySchedule;
{ IJclYearlySchedule }
function GetYearlySchedule: IJclYearlySchedule;
property YearlySchedule: IJclYearlySchedule read GetYearlySchedule implements IJclYearlySchedule;
end;
constructor TJclSchedule.Create;
var
InitialStamp: TTimeStamp;
begin
inherited Create;
FDayFrequency := TJclDayFrequency.Create(Self);
FDailySchedule := TJclDailySchedule.Create(Self);
FWeeklySchedule := TJclWeeklySchedule.Create(Self);
FMonthlySchedule := TJclMonthlySchedule.Create(Self);
FYearlySchedule := TJclYearlySchedule.Create(Self);
InitialStamp := DateTimeToTimeStamp(Now);
InitialStamp.Time := 1000 * (InitialStamp.Time div 1000); // strip of milliseconds
StartDate := InitialStamp;
EndType := sekNone;
RecurringType := srkOneShot;
end;
destructor TJclSchedule.Destroy;
begin
FreeAndNil(FYearlySchedule);
FreeAndNil(FMonthlySchedule);
FreeAndNil(FWeeklySchedule);
FreeAndNil(FDailySchedule);
FreeAndNil(FDayFrequency);
inherited Destroy;
end;
function TJclSchedule.GetDayFrequency: IJclScheduleDayFrequency;
begin
Result := FDayFrequency;
end;
function TJclSchedule.GetDailySchedule: IJclDailySchedule;
begin
Result := FDailySchedule;
end;
function TJclSchedule.GetWeeklySchedule: IJclWeeklySchedule;
begin
Result := FWeeklySchedule;
end;
function TJclSchedule.GetMonthlySchedule: IJclMonthlySchedule;
begin
Result := FMonthlySchedule;
end;
function TJclSchedule.GetYearlySchedule: IJclYearlySchedule;
begin
Result := FYearlySchedule;
end;
function TJclSchedule.GetNextEventStamp(const From: TTimeStamp): TTimeStamp;
var
UseFrom: TTimeStamp;
begin
Result := NullStamp;
UseFrom := From;
if (From.Date = 0) or (From.Date < StartDate.Date) then
begin
UseFrom := StartDate;
Dec(UseFrom.Time);
end;
case RecurringType of
srkOneShot:
if TriggerCount = 0 then
Result := StartDate;
srkDaily:
begin
Result := FDayFrequency.NextValidStamp(UseFrom);
if IsNullTimeStamp(Result) then
begin
Result.Date := UseFrom.Date;
Result.Time := FDayFrequency.StartTime;
Result := FDailySchedule.NextValidStamp(Result);
end
else
FDailySchedule.MakeValidStamp(Result);
end;
srkWeekly:
begin
Result := FDayFrequency.NextValidStamp(UseFrom);
if IsNullTimeStamp(Result) then
begin
Result.Date := UseFrom.Date;
Result.Time := FDayFrequency.StartTime;
Result := FWeeklySchedule.NextValidStamp(Result);
end
else
FWeeklySchedule.MakeValidStamp(Result);
end;
srkMonthly:
begin
Result := FDayFrequency.NextValidStamp(UseFrom);
if IsNullTimeStamp(Result) then
begin
Result.Date := UseFrom.Date;
Result.Time := FDayFrequency.StartTime;
Result := FMonthlySchedule.NextValidStamp(Result);
end
else
FMonthlySchedule.MakeValidStamp(Result);
end;
srkYearly:
begin
Result := FDayFrequency.NextValidStamp(UseFrom);
if IsNullTimeStamp(Result) then
begin
Result.Date := UseFrom.Date;
Result.Time := FDayFrequency.StartTime;
Result := FYearlySchedule.NextValidStamp(Result);
end
else
FYearlySchedule.MakeValidStamp(Result);
end;
end;
if CompareTimeStamps(Result, UseFrom) < 0 then
Result := NullStamp;
if not IsNullTimeStamp(Result) then
begin
if ((EndType = sekDate) and (CompareTimeStamps(Result, EndDate) > 0)) or
((EndType = sekDayCount) and (DayCount = EndCount) and (UseFrom.Date <> Result.Date)) or
((EndType = sekTriggerCount) and (TriggerCount = EndCount)) then
Result := NullStamp
else
begin
Inc(FTriggerCount);
if (UseFrom.Date <> Result.Date) or (DayCount = 0) then
Inc(FDayCount);
FLastEvent := Result;
end;
end;
end;
function TJclSchedule.GetStartDate: TTimeStamp;
begin
Result := FStartDate;
end;
function TJclSchedule.GetRecurringType: TScheduleRecurringKind;
begin
Result := FRecurringType;
end;
function TJclSchedule.GetEndType: TScheduleEndKind;
begin
Result := FEndType;
end;
function TJclSchedule.GetEndDate: TTimeStamp;
begin
Result := FEndDate;
end;
function TJclSchedule.GetEndCount: Cardinal;
begin
Result := FEndCount;
end;
procedure TJclSchedule.SetStartDate(const Value: TTimeStamp);
begin
FStartDate := Value;
end;
procedure TJclSchedule.SetRecurringType(Value: TScheduleRecurringKind);
begin
FRecurringType := Value;
end;
procedure TJclSchedule.SetEndType(Value: TScheduleEndKind);
begin
FEndType := Value;
end;
procedure TJclSchedule.SetEndDate(const Value: TTimeStamp);
begin
FEndDate := Value;
end;
procedure TJclSchedule.SetEndCount(Value: Cardinal);
begin
FEndCount := Value;
end;
function TJclSchedule.TriggerCount: Cardinal;
begin
Result := FTriggerCount;
end;
function TJclSchedule.DayCount: Cardinal;
begin
Result := FDayCount;
end;
function TJclSchedule.LastTriggered: TTimeStamp;
begin
Result := FLastEvent;
end;
procedure TJclSchedule.InitToSavedState(const LastTriggerStamp: TTimeStamp; const LastTriggerCount,
LastDayCount: Cardinal);
begin
FLastEvent := LastTriggerStamp;
FTriggerCount := LastTriggerCount;
FDayCount := LastDayCount;
end;
procedure TJclSchedule.Reset;
begin
FLastEvent := NullStamp;
FTriggerCount := 0;
FDayCount := 0;
end;
function TJclSchedule.NextEvent(CountMissedEvents: Boolean = False): TTimeStamp;
begin
Result := NextEventFrom(FLastEvent, CountMissedEvents);
end;
function TJclSchedule.NextEventFrom(const FromEvent: TTimeStamp;
CountMissedEvent: Boolean = False): TTimeStamp;
begin
if CountMissedEvent then
begin
Result := FLastEvent;
repeat
Result := GetNextEventStamp(Result);
until IsNullTimeStamp(Result) or (CompareTimeStamps(FromEvent, Result) <= 0);
end
else
Result := GetNextEventStamp(FromEvent);
end;
function TJclSchedule.NextEventFromNow(CountMissedEvents: Boolean = False): TTimeStamp;
begin
Result := NextEventFrom(DateTimeToTimeStamp(Now), CountMissedEvents);
end;
function CreateSchedule: IJclSchedule;
begin
Result := TJclSchedule.Create;
end;
{$IFDEF UNITVERSIONING}
initialization
RegisterUnitVersion(HInstance, UnitVersioning);
finalization
UnregisterUnitVersion(HInstance);
{$ENDIF UNITVERSIONING}
end.
| 32.234935 | 109 | 0.671699 |
83b9533246c9002aefe5ae6bd256f9f71dc41bd9 | 18,941 | dfm | Pascal | client/udmCore.dfm | victorgv/CleverHelpDesk | b36174250489b236dee06da908f3ea535fae7dd2 | [
"MIT"
]
| null | null | null | client/udmCore.dfm | victorgv/CleverHelpDesk | b36174250489b236dee06da908f3ea535fae7dd2 | [
"MIT"
]
| null | null | null | client/udmCore.dfm | victorgv/CleverHelpDesk | b36174250489b236dee06da908f3ea535fae7dd2 | [
"MIT"
]
| null | null | null | object dmCore: TdmCore
OldCreateOrder = False
OnCreate = DataModuleCreate
OnDestroy = DataModuleDestroy
Height = 379
Width = 443
object ti_userAuthenticated: TTimer
Interval = 150
OnTimer = ti_userAuthenticatedTimer
Left = 32
Top = 16
end
object RESTClient1: TRESTClient
BaseURL = 'http://localhost:8080/user/login'
Params = <>
Left = 32
Top = 104
end
object RESTRequest1: TRESTRequest
AssignedValues = [rvConnectTimeout, rvReadTimeout]
Client = RESTClient1
Method = rmPOST
Params = <
item
end>
Response = RESTResponse1
Left = 32
Top = 160
end
object RESTResponse1: TRESTResponse
Left = 32
Top = 216
end
object la_idiomas: TLang
Lang = 'es'
Left = 128
Top = 16
ResourcesBin = {
AD0100004C006F00670069006E000D000A002A002A002A00200069006E006600
6F0020002A002A002A000D000A0046006F00720067006F007400200070006100
7300730077006F00720064003F000D000A0045006D00610069006C000D000A00
500061007300730077006F00720064000D000A0053006F007500720063006500
0D000A0055007300650072000D000A004C0041005F004E004F004D0042005200
45005F005500530055004100520049004F000D000A00620074005F0065007800
690074000D000A00420054005F0043005200450041005F004E00550045005600
4F000D000A004400610074006F0073000D000A00450073007400610064006F00
0D000A005200650067006900730074007200610064006F000D000A0050006500
6E006400690065006E0074006500200049006E0066006F0072006D0061006300
6900F3006E000D000A00500061007200610064006F000D000A00540072006100
620061006A0061006E0064006F000D000A005400650072006D0069006E006100
64006F000D000A00430061006E00630065006C00610064006F000D000A004100
620069006500720074006F000D000A004300650072007200610064006F000D00
0A005400690070006F000D000A0041007300690067006E00610064006F000D00
0A005200650070006F0072007400610064006F000D000A00500072006F007900
6500630074006F000D000A005000720069006F00720069006400610064000D00
0A004D00750079002000620061006A0061000D000A00420061006A0061000D00
0A004E006F0072006D0061006C000D000A0041006C00740061000D000A004300
7200ED0074006900630061000D000A0044006500730063007200690070006300
6900F3006E000D000A00540049005F0043004F004D0045004E00540041005200
49004F0053000D000A004800690073007400F3007200690063006F000D000A00
490044000D000A004E006F006D006200720065000D000A005500730075006100
720069006F000D000A00500065007200660069006C000D000A00410044004D00
49004E000D000A004100470045004E0054000D000A0044006500730064006500
0D000A004D0069007300200020007400690063006B006500740073000D000A00
480061007300740061000D000A004100670065006E00740065000D000A000200
00000200000065006E00B10200004C006F00670069006E003D004C006F006700
69006E000D000A002A002A002A00200069006E0066006F0020002A002A002A00
3D002A002A002A00200069006E0066006F0020002A002A002A000D000A004600
6F00720067006F0074002000700061007300730077006F00720064003F003D00
46006F00720067006F0074002000700061007300730077006F00720064003F00
0D000A0045006D00610069006C003D0045006D00610069006C000D000A005000
61007300730077006F00720064003D00500061007300730077006F0072006400
0D000A0053006F0075007200630065003D0053006F0075007200630065000D00
0A004D005300470030003000300031003D0045006D00610069006C0020006900
7300200065006D007000740079000D000A0055007300650072003D0055007300
650072000D000A004400610074006F0073003D0044006100740061000D000A00
450073007400610064006F003D005300740061007400750073000D000A005200
650067006900730074007200610064006F003D00520065006700690073007400
65007200650064000D000A00500065006E006400690065006E00740065002000
49006E0066006F0072006D00610063006900F3006E003D005200650067006900
7300740065007200650064000D000A00500061007200610064006F003D005300
74006F0070007000650064000D000A00540072006100620061006A0061006E00
64006F003D0057006F0072006B0069006E0067000D000A005400650072006D00
69006E00610064006F003D00460069006E00690073006800650064000D000A00
430061006E00630065006C00610064006F003D00430061006E00630065006C00
650064000D000A004100620069006500720074006F003D004F00700065006E00
650064000D000A004300650072007200610064006F003D0043006C006F007300
650064000D000A005400690070006F003D0054007900700065000D000A004100
7300690067006E00610064006F003D00410073007300690067006E0065006400
0D000A005200650070006F0072007400610064006F003D005200650070006F00
72007400650064000D000A00500072006F0079006500630074006F003D005000
72006F006A006500630074000D000A005000720069006F007200690064006100
64003D005000720069006F0072006900740079000D000A004D00750079002000
620061006A0061003D00560065007200790020006C006F0077000D000A004200
61006A0061003D004C006F0077000D000A004E006F0072006D0061006C003D00
4E006F0072006D0061006C000D000A0041006C00740061003D00480069006700
68000D000A0043007200ED0074006900630061003D0043007200690074006900
630061006C000D000A00440065007300630072006900700063006900F3006E00
3D004400650073006300720069007000740069006F006E000D000A0048006900
73007400F3007200690063006F003D005200650070006F007200740065006400
0D000A00490044003D00490044000D000A004E006F006D006200720065003D00
4E0061006D0065000D000A005500730075006100720069006F003D0055007300
650072000D000A00500065007200660069006C003D0052006F006C0065000D00
0A00410044004D0049004E003D00410044004D0049004E000D000A0041004700
45004E0054003D004100470045004E0054000D000A0044006500730064006500
3D00460072006F006D000D000A004D0069007300200020007400690063006B00
6500740073003D004D00790020007400690063006B006500740073000D000A00
480061007300740061003D0054006F000D000A004100670065006E0074006500
3D004100670065006E0074000D000A000200000065007300E60000004C006F00
670069006E003D0041006300630065006400650072000D000A002A002A002A00
200069006E0066006F0020002A002A002A003D002A002A002A00200069006E00
66006F0072006D00610063006900F3006E0020002A002A002A000D000A004600
6F00720067006F0074002000700061007300730077006F00720064003F003D00
BF004F006C007600690064006F00200073007500200063006F006E0074007200
610073006500F10061003F000D000A0045006D00610069006C003D0045006D00
610069006C000D000A00500061007300730077006F00720064003D0043006F00
6E0074007200610073006500F10061000D000A0053006F007500720063006500
3D004F0072006900670065006E000D000A004D00530047003000300030003100
3D0045006D00610069006C002000650073007400E1002000760061006300ED00
6F000D000A0055007300650072003D005500730075006100720069006F000D00
0A004400610074006F0073003D004400610074006F0073000D000A0045007300
7400610064006F003D00450073007400610064006F000D000A00520065006700
6900730074007200610064006F003D0052006500670069007300740072006100
64006F000D000A00}
end
object AL_GLOBAL: TActionList
Left = 216
Top = 16
object AC_HardwareBack: TAction
Text = 'AC_HardwareBack'
ShortCut = 137
OnExecute = AC_HardwareBackExecute
end
end
object IL_LISTA_IMAGENES: TImageList
Source = <
item
MultiResBitmap.Height = 192
MultiResBitmap.Width = 140
MultiResBitmap = <
item
Width = 140
Height = 192
PNG = {
89504E470D0A1A0A0000000D494844520000008C000000C00806000000D65A8B
29000000017352474200AECE1CE90000000467414D410000B18F0BFC61050000
066849444154785EEDDDBF8B244518C6F13B2305030343035341117F6220DC5E
66E09F602622660A8A0AC2DD62A0A0A0A18218F907082606C2DD8181E02F4451
FF00330DCC34D3F799EE86DDB9EADD7E767AA6EAEDFE7EE0B56786DDB9DAEA67
AA7BAA67CACB97D6EBA8AF2B9B7B1DDD2FB9D96F6FF55BDD1F1E5B9535054661
B8D6DD1C0D864BA1194274BDDF223105E346D47F072A8566AE30E2800E1D94ED
5270187112A81D94ED525B084E835A0BCA76119A8668679476528B45702A6B79
54192B425341EB87A029C5BBA9035147977640C662B4D9B34CE72B532B556832
CDF4AA638799DA390DB3B5674DF50F870F5D46D8C7A1E4388AD16646738E2C3A
F751EDB2E3F5BB738F76FB08E22AA9234B1DECD6AE2119A3E0CC151E42338352
C73AB5AFA094EC1A1CB5153BD87507D478C5129A4A76E9F8163A7D97F6EB7761
2A75E4946AA9B377090DE733868B76748BAFCC8BFE2D4D1E9ACE9B87A99172FD
9B17996F69792E43EDBAE8DF54E3A3A0D6BFA91DA6749752DF6AB51A94932E3A
D2D42AB5F7DC7ECDF647A932BDABC8F642548D8626635854D994FE86D6EBB6D0
E83054FAC1D6EBDC21B34159FBFAD4F92C87A2C3CA78683AD5DFA51F68BD328E
2E83D4A30CA34B1D294F80EF88FF00535D5160F6F1A1242C14230C1C47040616
373057A374FD69BBF4F854BA4EB1EB73ACCD58BFEB5AD354B3F43B230C2C0406
1602030B818145273D9AC19B4A2748A50FD768CA78EAECAB7EBF74A2E53EC7B0
545856CEFCD758BF6B967EEAF3CCD1EF1BDBD3BF67D5E65A42811E2FFD7CA9C6
1AE73CC7DA6AACDF9DCB3AB3F43B872458080C2C04061602030B8181A5A5C094
DE36A2D34CDFB436C2109ADB391718F7AEB5C08C4D50AD95FAA2A9CF2EB7780E
A3D034F5AAAA446129CDCC56D5D2A5816D7A4ED5C9FF3DCD5A4CFD4EF5AA2F0D
C0C7A501B48DC0C04260602130B0101858080C2C04061602030B818185C0C042
60602130B0640ECC3D51EF457D1BF54F54F1625943A536AAAD1F44DD1B9552D6
C03C1DF573D4AB518F47DD19D53AB5516D7D39EAB7A867A2D2C9189887A334B2
DCB7B99793469877A39EDADC4B2463609E8B4AD7D1050AFE8BDDCD3C3206E6B1
7EBB040FF6DB343206E6917EBB043AA7492563607EECB74BF05DBF4D236360BE
EFB74BF04BBF4D2363603E8BFAA6BB99DA4F511F7737F3C8181875F46B517F6C
EEE5F457D41B51E9829F3130F275D44351EF47E93CE0DFA8D6A98D6AEB87510F
447D19954ED6C0C8DF511A699E88BA2BEAE462C52D96DAA8B6BE12A51126A5CC
81410504061602030B818185C0C04260602130B0101858080C2C04061602030B
818185C0C04260602130B0101858080C2C04061602034BE6C0DC1DA54FDE7F11
F5675469898D964A6D545BDF8AD2522529650DCCB0DCC73B51CF4665586F456D
545BDF8E52DB59EEE34086E53EEEDFDCCB494B95B0DCC7812C69B98FE7BB9B79
640CCCA3FD7609149A543206E6C97EBB04FA625B2A1903B3A4D51B7EE8B76964
0C8C16145C8A5FFB6D1A1903F36954BA5766C1EF519F7437F3C81818AD75FB7A
54DA2FB4072D24F066D4ADCDBD44320646BE8AD292191F45655AC5496DD5A8A2
A54A3ED703D9640D8C688479294A9D5F5A5EA3C5525B5F884ABB1852E6C0A002
02030B818185C0C04260602130B0101858080C2C04061602030B818185C0C042
60602130B0101858080C2C04061602034BE6C0B07A43055903C3EA0D95640C0C
AB3754943130ACDE5051C6C0B07A43451903C3EA0D15650C0CAB3754943130AC
DE5051C6C0B07A43451903C3EA0D15650C8CB07A4325590323ACDE5041E6C0A0
0202030B818185C0C04260602130B0101858080C2C04061602030B818185C0C0
4260602130B0101858080C2C04061602030B818185C0C04260602130B0101858
080C2C04061602030B818145DFF7D592A0535D8DBAD9DD3CE528EA4677F35CFA
FDE3EE2676A47EBFD6DD3C97FA5DFB6F9BB3EF36B6D7933DABF4E4257ABCF4F3
543B35160A6BDF71488285C0C04260602130B01098F598653D3D0203CB5C81D1
7BFCD2FC0CDA71BDDFEE64CE1186C9B876CDB66FE60C0C33B86DD23E99657419
1467F4466A6CA6779B1AA899C5D27350FB2FF5BD6ACAFE7267E98B0F8ED5D4C0
200F2E0D607F080C2C04061602030B818185C0C0E27E445393405C025816BDAD
9EFA314F3B3058390E49B0101858080C2C04061602038B02C3DB644CC60803C7
B1E6613471637DB716AB7579382495BEA40D9CB4C9C87048526834DAF0995C9C
A45C0C034A6C2F5DFA1F0AA79C9DC6EBCC2A0000000049454E44AE426082}
FileName = 'C:\victor\gitmio\CleverHelpDesk\client\icons\ticket.png'
end>
Name = 'Item 0'
end
item
MultiResBitmap.Height = 141
MultiResBitmap.Width = 172
MultiResBitmap = <
item
Width = 172
Height = 141
PNG = {
89504E470D0A1A0A0000000D49484452000000AC0000008D08060000002AC191
4B000000017352474200AECE1CE90000000467414D410000B18F0BFC61050000
09CD49444154785EED9D4BA82C571586AF5121444591189D08BEA39318244450
D11B417124226A4CE22084A8042782131391E84807E203111111C1800E02CE84
04C1E74050C1D72044C10C84A8083EA2A28251D7DF5DFB5AE9AC5D5D6BEFB55F
55FF071FD5B939A77A57EFBF57AD7A749F275C18938BB3E5EB8E0F0F847F27FF
E73BD3127C775AE2DFE6FF3E0C23043684F0EE69C950FA82E022C84384B8D7C0
22940C681B3E3A2D3F322DBBA2A7C0229810BB7886B40FBA0E6F2B10CE6F8BFF
A55DBBFBD032A863BABBE032A8DB70F3C16550B7E926838B8DD236966E4314A2
4D049755755F0E1D5A56D57D8A028542558452E7618B0E7A46B83213AED4109D
F95CD43ACF8D73B8DD57DC922D00D61BDE08355EF0AD83D710812A355FB0EBC0
E205D0069DE33CA4A42C08578936AECBD07A6F2843DA9612F3D90D9E1BC7A0F6
85F7DC36C76B8318D4BEF19CE766786C04833A165E735E1D844C1B8C456C3C19
0FCC3D42A7CDE95AAB86D623ACACAAE3935B6DAB85567BF2B536D91D9062E486
B6F85E3667806C01B64B4E8B502C170C2B5922271FEE2D624EDFCAB0EE87D4D0
BAB78AA9259F61DD1FA9A175CB4AF30190E1482D702EAD81B6E27332AC2425B4
D9AD414A7575EF47C8B068F9386772B14B6D050809A41EAC475B83CBA6A517E1
9B420801F814484A26C2D754AD26A5BAB26F253152FA59D30158CA13101223A5
35587D2CC4EA4A4A9092AB5555D6BA628695ACC5BAE75E5565B55F5C9290B5A4
B4068BB0BA92D258ABEC625BA0FDC2928458B156D9685B605D11AB2B4925B9CA
CE2F1C2C965E421C71B9C0644D3D213968998AA9B605DA0FC6643B4072C92A90
D6B3036C1F482ED663A643E6526F7E29F9D596978B6F13BF2CFE44FC83F857F1
01F15EF176F14AB13730EEB788F788BF10FF24CEC7FD2EF1A9626F3C43BC55C4
1831568C1963C7367C4DC4B8F133DE5833F498226929CF25DB811BC56F89DAF3
CEFD997887D8034F11DF236202B4B1CEC51BF003E2B3C51EB84DFCA1A88D75EE
8F44140A6F2CB97B4C1FABFD40CC12817DBEF87111EF6CED39637E5E7CB9D88A
17895F10B5B12D89CAF50AB1152F133F23FE4BD4C6A7F96FF173E235A217D6B6
E040D22F3982DD0D763FDA73ADF137628B16E149E2F7456D4C6BC4EEB7C4AEF6
1C684BF0DCDA98D688D7FB79A207497DACF580CB13F47D39931E44FF559B0F89
DA582C7E52ACCD67456D2C163DDF6CDAFA639A03AB9E0FCBE083A2F63C561F15
DF2DD6E2F5E2AF456D2C16FF22BE5DAC050EA0FE266A63B18A16CE03F3F19325
B0875F7002EF506BCFBA24CE26D4D8C55E217E55D4C690E2FDE273C5D2A01578
48D4C690E23FC4E788B9980EBC705A0B7F55A405EF103D03863E16EB2CCD6BC4
9B8E0F5D78A3888A5D9A378B5EBD27403B77CBF16116F80B40ABF1FE10A28537
4C4B4F4AACF394574D4B4F4AACF3941BA6A5276F9A963998CEC722B087467625
9E170C5E302D3DC1E9B1D2BC7A5A7A52A3C2BE705A7AE259B157D1B2C2BE645A
7A72F5B42CC933A7A5274F179F787C588C174F4B4F701EBA26175B061647C8DE
9458E729574D4B4F9E25E24C47491E99969EE032EED38E0FEBD032B00F4F4B4F
4AACF394DF4D4B4F7E2F96FA33AA81DF4E4B4FB04E84B61A2D03FBE0B4F4A4C4
3A4FF9F3B4F4249CDE2B094E69798373D155691958EF8B10A0E45D6481EF4D4B
4F70C34F69BE392D3DB96F5A56E5F4E4EC9296330AE7C0896CCF0B07B8C65DE3
F6BDEB44EDF973C46D89A5C179D31E2F1C98EE274085AD5195347089F063C787
D9FC47C45538ACB3343F15BF727CE8C237C41F1C1F16E59FE25DE2DF0FFF95CF
A7C512FDFC1287AC5A2E8D79565830EACD2FAF157F256A63B1F847F1AD624D70
4BA636168B9E37BF98EF6531DF7CE00C762B39938F23D516B717DE296AE3B1F8
09B136081ADA276D3C6BC4EBFD52D10B7360CDBF5000DC50FC29D17A27D197C4
578A2D18F57E5870AD884A8B564A1B5BCC2F8AD78B9E980B660F810DDC2CA24F
D19E7BEECFC5F7894F165B822B6BF8EC9936C625BF2E7A4F7C0AB825F3C7A236
C6B9F899F78A25CE2A69CF17F31058D3519A581AF4B5237D081157BEDE2FAEF9
6CD42FC50F8B35EE79580BAA7C8B0F2106B4D729E6E118CA1A58EF03AFAD8037
DA3BC5D8A7667BFDB46F4B2C7B777809ED7FC63C9465421C300736F4249673B1
AD6EF826DBC392A5C3F77185C05AEEFA664B40BC306729A5C2028696E4626D2D
1F9751AD678859FAF416D93EC9075C01CB095CC82A4B72D03215F352359E9F08
B67EC92C034B52493ED3747A973BD26CA1F45DF2649B24E7ECF4521B0FBE4869
ACD57571CF8F00CE7B8773F2E08B58D172B4E4D9805B0FBE92FB11B23B90152D
434B9EA5C84A0911B4EC2CB9BA186ABFBC245B03728EA285D0DA16401E809118
29615D5D5D81F5E00BB2CA92185A5ECE69A6F8BB82EC82AA39D256764EB60624
901256984CEA1332B424A5AD84D97BE9940330F6B344CBC539B3C30A52DF290C
ED7E492972D06DCF9CDA1A30B4FB2335AC2ED5754EEA4018DAFDD04D58416A6B
0019DA6D836CA486151623B53508BAF528A41B720A192C525DE7E486B6F80049
3586C9424EF9870CEDF80C9781DC014306773C725B00D86CDE19DAFD907B6015
C43A9AB2898D2051BC820ABB996786767B7806157637BF1E1B47DAE31D54D86D
DB878169035E2B5E2C529F12210D767F8C92135A06B63C788D21E6A9544883EE
612DF5CD2D18E8DDC78726F84D32EB387D632FBDD1E7DFC15AB320DC205ABF98
E52CA5038277B0E54562608F84D70CCB56814B0521455887C4B2CBE9BED72904
421876CFA577D1A51D7E0EB58D8AB997C022A05B08E75C6CCB26D0362EE608BB
BB14B05D21A4DA768F2CB66933F3860DD13632E6960801DD6248E1A6821AC02E
5EDBD898A383090CBDA8B67D5B7093410D58023B72FF1AAAA9B65D5B71D3410D
582671C4C0EEA59A6E3EA801ED4588394A60B75E4D7717D20036587B4162F6CE
16838AED812816C304B4974BB3BD5EE1C244623B7A9DD073973EE77FE172FEB3
EE974C470781D5DED59A7897F7462F15F5B40A0E530947C332D93DF5AF184BAB
A0CE83492AA34D48CCD6816D554DF19CAC9A9DA04D50CC5613563BA878AE1052
D21198106DC262D6A6665019D201C02E5E9BBC98354060ACE3CA91211D084B30
30B125A9594D210F9A06C4129052075C3583CA6A3A38DAA4C6F40C6CED6ACAA0
6E046D72637A4C38834A92C1446A931C3395DA21850CEA06297DC0D5A29A96EA
B349075802BB3608ACA6A41896609D0B2C834A8AA38520A616D81621850CEA4E
D1C210330404CB16416548770E265F0B46CC1621850C2A396039E06A21C6C7A0
924BF41858565312A5C5EE3D26834ACEA205A7A60C2931A185A8860C2A3183C0
68612A25434AB2A875C0C5A0EE9CCBA665CF84AF20C7976D14F9DE7C320E3D07
3604952125EE78F5B0DCE5932AE4049621254DB01E7831A8A43908A116CE2043
4ABA0395761E5C86943871E1C2FF009549626FB1DE7A490000000049454E44AE
426082}
FileName = 'C:\victor\gitmio\CleverHelpDesk\client\icons\comentario.png'
end>
Name = 'Comentario'
end>
Destination = <
item
Layers = <
item
Name = 'Item 0'
SourceRect.Right = 140.000000000000000000
SourceRect.Bottom = 192.000000000000000000
end>
end
item
Layers = <
item
Name = 'Comentario'
SourceRect.Right = 172.000000000000000000
SourceRect.Bottom = 141.000000000000000000
end>
end>
Left = 224
Top = 120
end
end
| 59.562893 | 84 | 0.810939 |
479f0651a4b99e9de0290d1cfe9bea793d23e5ec | 511 | pas | Pascal | NuttX/misc/pascal/tests/src/105-inflation.pas | qing191325/Firmware | f8734b5d2d995898d4d63a0bf379d1554bc87b1d | [
"BSD-3-Clause"
]
| 24 | 2019-08-13T02:39:01.000Z | 2022-03-03T15:44:54.000Z | NuttX/misc/pascal/tests/src/105-inflation.pas | qing191325/Firmware | f8734b5d2d995898d4d63a0bf379d1554bc87b1d | [
"BSD-3-Clause"
]
| 4 | 2020-11-16T02:03:09.000Z | 2021-08-19T08:16:48.000Z | NuttX/misc/pascal/tests/src/105-inflation.pas | qing191325/Firmware | f8734b5d2d995898d4d63a0bf379d1554bc87b1d | [
"BSD-3-Clause"
]
| 11 | 2019-07-28T09:11:40.000Z | 2022-03-17T08:08:27.000Z | { assuming annual inflation rates of 7, 8, and 10 per cent,
find the factor by which the frank, dollar, pound
sterlinh, 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.
| 18.25 | 60 | 0.504892 |
474597cb44611701866ed2397157b498c16fc43f | 4,591 | pas | Pascal | UFrmStart.pas | atkins126/Scrabble | 62601367c6190b713e3ebdb621aa614a51b3391e | [
"MIT"
]
| 5 | 2020-10-04T19:29:05.000Z | 2021-09-10T11:28:27.000Z | UFrmStart.pas | atkins126/Scrabble | 62601367c6190b713e3ebdb621aa614a51b3391e | [
"MIT"
]
| 3 | 2020-09-29T21:57:31.000Z | 2020-09-30T15:57:24.000Z | UFrmStart.pas | atkins126/Scrabble | 62601367c6190b713e3ebdb621aa614a51b3391e | [
"MIT"
]
| 3 | 2020-10-04T19:29:06.000Z | 2022-01-05T06:36:08.000Z | unit UFrmStart;
interface
uses Vcl.Forms, Vcl.Mask, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Controls, Vcl.Buttons,
System.Classes;
type
TFrmStart = class(TForm)
LbTitle: TLabel;
BtnJoin: TBitBtn;
BtnExit: TBitBtn;
EdPassword: TEdit;
LbPassword: TLabel;
BoxOper: TRadioGroup;
BoxClient: TPanel;
LbServerAddress: TLabel;
EdServerAddress: TEdit;
CkReconnect: TCheckBox;
BoxName: TPanel;
BoxReconnect: TPanel;
EdPlayerName: TEdit;
LbPlayerName: TLabel;
EdHash: TMaskEdit;
LbHash: TLabel;
LbLanguage: TLabel;
EdLanguage: TComboBox;
procedure FormCreate(Sender: TObject);
procedure BtnExitClick(Sender: TObject);
procedure BtnJoinClick(Sender: TObject);
procedure BoxOperClick(Sender: TObject);
procedure CkReconnectClick(Sender: TObject);
procedure EdLanguageChange(Sender: TObject);
private
procedure InitTransation;
procedure LoadLanguages;
public
procedure EnableControls(En: Boolean);
end;
var
FrmStart: TFrmStart;
implementation
{$R *.dfm}
uses UDMClient, UDMServer, UVars, UDams,
System.SysUtils, System.StrUtils,
UFrmMain, UFrmLog, ULanguage;
procedure TFrmStart.FormCreate(Sender: TObject);
begin
InitTransation;
LoadLanguages;
EdLanguage.ItemIndex := GetCurrentLanguageIndex;
EdPlayerName.MaxLength := 30;
BoxOper.ItemIndex := 0;
BoxOperClick(nil);
EdServerAddress.Text := 'localhost';
end;
procedure TFrmStart.InitTransation;
begin
LbTitle.Caption := Lang.Get('START_CAPTION');
LbPlayerName.Caption := Lang.Get('START_NAME');
LbHash.Caption := Lang.Get('START_HASH');
BoxOper.Caption := Lang.Get('START_OPERATION');
CkReconnect.Caption := Lang.Get('START_RECONNECT');
LbServerAddress.Caption := Lang.Get('START_SERVER_ADDR');
LbPassword.Caption := Lang.Get('START_CONN_PASSWORD');
LbLanguage.Caption := Lang.Get('START_LANGUAGE');
BoxOper.Items[0] := Lang.Get('MODE_CLIENT');
BoxOper.Items[1] := Lang.Get('MODE_SERVER');
BtnJoin.Caption := Lang.Get('START_BTN_JOIN');
BtnExit.Caption := Lang.Get('START_BTN_EXIT');
end;
procedure TFrmStart.BoxOperClick(Sender: TObject);
begin
pubModeServer := (BoxOper.ItemIndex=1);
CkReconnect.Visible := not pubModeServer;
BoxClient.Visible := not pubModeServer;
CkReconnectClick(nil);
end;
procedure TFrmStart.CkReconnectClick(Sender: TObject);
var
Reconnect: Boolean;
begin
Reconnect := CkReconnect.Checked and not pubModeServer;
BoxName.Visible := not Reconnect;
BoxReconnect.Visible := Reconnect;
end;
procedure TFrmStart.BtnJoinClick(Sender: TObject);
begin
if BoxName.Visible then
begin
EdPlayerName.Text := Trim(EdPlayerName.Text);
if EdPlayerName.Text = string.Empty then
begin
MsgError(Lang.Get('START_MSG_BLANK_NAME'));
EdPlayerName.SetFocus;
Exit;
end;
end;
if BoxReconnect.Visible then
begin
if EdHash.Text = string.Empty then //mask edit
begin
MsgError(Lang.Get('START_MSG_BLANK_HASH'));
EdHash.SetFocus;
Exit;
end;
if Length(EdHash.Text)<>EdHash.MaxLength then
begin
MsgError(Lang.Get('START_MSG_INVALID_HASH'));
EdHash.SetFocus;
Exit;
end;
end;
if BoxClient.Visible then
begin
EdServerAddress.Text := Trim(EdServerAddress.Text);
if EdServerAddress.Text = string.Empty then
begin
MsgError(Lang.Get('START_MSG_BLANK_SERVER_ADDR'));
EdServerAddress.SetFocus;
Exit;
end;
end;
//
if pubModeServer then
begin
//SERVER MODE
DMClient.C.Host := 'localhost';
DMServer.Initialize;
end else
begin
//CLIENT MODE
DMClient.C.Host := EdServerAddress.Text;
end;
EnableControls(False);
pubPlayerName := IfThen(BoxName.Visible, EdPlayerName.Text);
pubPlayerHash := IfThen(BoxReconnect.Visible, EdHash.Text);
pubPassword := EdPassword.Text;
Log(Lang.Get('LOG_CONNECTING'));
DMClient.C.Connect;
end;
procedure TFrmStart.EnableControls(En: Boolean);
begin
BtnJoin.Enabled := En;
BtnExit.Enabled := En;
Self.Enabled := En;
end;
procedure TFrmStart.BtnExitClick(Sender: TObject);
begin
Application.Terminate;
end;
procedure TFrmStart.LoadLanguages;
var
D: TLangDefinition;
begin
for D in LST_LANGUAGES do
EdLanguage.Items.Add(D.Name);
end;
procedure TFrmStart.EdLanguageChange(Sender: TObject);
begin
pubLanguageID := LST_LANGUAGES[EdLanguage.ItemIndex].ID;
FrmMain.ConfigLanguage(True); //save config language
Lang.LoadLanguage; //reload language
//reload screen translation
FrmMain.InitTranslation;
FrmStart.InitTransation;
end;
end.
| 22.840796 | 80 | 0.72054 |
47a91efad178c4e548bc8a96463cdafa67b6053a | 2,378 | pas | Pascal | UFrmMasksEdit.pas | fuadhs88/Updater | 4b59a3de11d82f2a479b57d5a461a9b579ddda49 | [
"MIT"
]
| 8 | 2020-12-14T05:23:30.000Z | 2021-09-10T11:28:29.000Z | UFrmMasksEdit.pas | fuadhs88/Updater | 4b59a3de11d82f2a479b57d5a461a9b579ddda49 | [
"MIT"
]
| null | null | null | UFrmMasksEdit.pas | fuadhs88/Updater | 4b59a3de11d82f2a479b57d5a461a9b579ddda49 | [
"MIT"
]
| 4 | 2021-01-30T19:37:41.000Z | 2021-11-12T18:14:57.000Z | unit UFrmMasksEdit;
interface
uses Vcl.Forms, Vcl.Buttons, Vcl.StdCtrls, Vcl.Controls, System.Classes,
//
UConfig;
type
TFrmMasksEdit = class(TForm)
Label1: TLabel;
EdName: TEdit;
Label3: TLabel;
EdMasks: TMemo;
BtnOK: TButton;
BtnCancel: TButton;
BtnHelp: TSpeedButton;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure BtnOKClick(Sender: TObject);
procedure BtnHelpClick(Sender: TObject);
private
Edit: Boolean;
MasksTable: TMasksTable;
function NameAlreadyExists: Boolean;
end;
var
FrmMasksEdit: TFrmMasksEdit;
function DoMasksEdit(Edit: Boolean; var MasksTable: TMasksTable): Boolean;
implementation
{$R *.dfm}
uses System.SysUtils, Vcl.Dialogs, System.UITypes, UCommon;
function DoMasksEdit;
begin
FrmMasksEdit := TFrmMasksEdit.Create(Application);
FrmMasksEdit.Edit := Edit;
FrmMasksEdit.MasksTable := MasksTable;
Result := FrmMasksEdit.ShowModal = mrOk;
if Result then MasksTable := FrmMasksEdit.MasksTable;
FrmMasksEdit.Free;
end;
procedure TFrmMasksEdit.FormCreate(Sender: TObject);
begin
Width := Width+8; //fix theme behavior
end;
procedure TFrmMasksEdit.FormShow(Sender: TObject);
begin
if Edit then
begin
Caption := 'Edit Masks Table';
EdName.Text := MasksTable.Name;
EdMasks.Text := MasksTable.Masks;
end;
end;
procedure TFrmMasksEdit.BtnOKClick(Sender: TObject);
begin
EdName.Text := Trim(EdName.Text);
if EdName.Text = string.Empty then
begin
MessageDlg('Name is empty', mtError, [mbOK], 0);
EdName.SetFocus;
Exit;
end;
if Pos(' ', EdName.Text)>0 then
begin
MessageDlg('Name cannot contain space character', mtError, [mbOK], 0);
EdName.SetFocus;
Exit;
end;
if NameAlreadyExists then
begin
MessageDlg('Name already exists', mtError, [mbOK], 0);
EdName.SetFocus;
Exit;
end;
//
if not Edit then
begin
MasksTable := TMasksTable.Create;
Config.MasksTables.Add(MasksTable);
end;
MasksTable.Name := EdName.Text;
MasksTable.Masks := EdMasks.Text;
ModalResult := mrOk;
end;
function TFrmMasksEdit.NameAlreadyExists: Boolean;
var
M: TMasksTable;
begin
M := Config.FindMasksTable(EdName.Text);
Result := (M<>nil) and (M<>MasksTable);
end;
procedure TFrmMasksEdit.BtnHelpClick(Sender: TObject);
begin
ShowMasksHelp;
end;
end.
| 19.983193 | 74 | 0.70942 |
4752760d973dedc4074ea238a68595f6d999b0e3 | 352 | pas | Pascal | WorkingWithComponents/bsdialog.pas | rustkas/dephi_do | 96025a01d5cb49136472b7e6bb5f037b27145fba | [
"MIT"
]
| null | null | null | WorkingWithComponents/bsdialog.pas | rustkas/dephi_do | 96025a01d5cb49136472b7e6bb5f037b27145fba | [
"MIT"
]
| null | null | null | WorkingWithComponents/bsdialog.pas | rustkas/dephi_do | 96025a01d5cb49136472b7e6bb5f037b27145fba | [
"MIT"
]
| null | null | null | unit bsdialog;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs;
type
TFbsdialog = class(TForm)
private
{ Private declarations }
public
{ Public declarations }
end;
var
Fbsdialog: TFbsdialog;
implementation
{$R *.dfm}
end.
| 14.08 | 98 | 0.71875 |
475d3edb8d4e5f14d77c476a024ce4e2787ff509 | 1,311 | dfm | Pascal | Capitulo8/3.5.Reflection/Server/ServerMethodsUnit1.dfm | diondcm/exemplos-delphi | 16b4d195981e5f3161d0a2c62f778bec5ba9f3d4 | [
"MIT"
]
| 10 | 2017-08-02T00:44:41.000Z | 2021-10-13T21:11:28.000Z | Capitulo8/3.5.Reflection/Server/ServerMethodsUnit1.dfm | diondcm/exemplos-delphi | 16b4d195981e5f3161d0a2c62f778bec5ba9f3d4 | [
"MIT"
]
| 10 | 2019-12-30T04:09:37.000Z | 2022-03-02T06:06:19.000Z | Capitulo8/3.5.Reflection/Server/ServerMethodsUnit1.dfm | diondcm/exemplos-delphi | 16b4d195981e5f3161d0a2c62f778bec5ba9f3d4 | [
"MIT"
]
| 9 | 2017-04-29T16:12:21.000Z | 2020-11-11T22:16:32.000Z | object ServerMethods1: TServerMethods1
OldCreateOrder = False
Height = 334
Width = 491
object qryPessoa: TFDQuery
Connection = FDConnection
SQL.Strings = (
'select * from pessoa')
Left = 200
Top = 152
end
object qryProduto: TFDQuery
Connection = FDConnection
SQL.Strings = (
'select * from produto')
Left = 280
Top = 152
end
object memProduto: TFDMemTable
FetchOptions.AssignedValues = [evMode]
FetchOptions.Mode = fmAll
ResourceOptions.AssignedValues = [rvSilentMode]
ResourceOptions.SilentMode = True
UpdateOptions.AssignedValues = [uvCheckRequired, uvAutoCommitUpdates]
UpdateOptions.CheckRequired = False
UpdateOptions.AutoCommitUpdates = True
Left = 280
Top = 248
end
object memPessoa: TFDMemTable
FetchOptions.AssignedValues = [evMode]
FetchOptions.Mode = fmAll
ResourceOptions.AssignedValues = [rvSilentMode]
ResourceOptions.SilentMode = True
UpdateOptions.AssignedValues = [uvCheckRequired, uvAutoCommitUpdates]
UpdateOptions.CheckRequired = False
UpdateOptions.AutoCommitUpdates = True
Left = 200
Top = 248
end
object FDConnection: TFDConnection
Params.Strings = (
'ConnectionDef=PG_Conn')
LoginPrompt = False
Left = 240
Top = 80
end
end
| 26.755102 | 73 | 0.707857 |
473ecc63d7580256333e1db5738a84625b28ddd7 | 50,337 | pas | Pascal | source/HtmlGlobals.pas | amikey/HtmlViewer | 8cb6ee2ea6c727da711a642bf417ce47d3b5cc2a | [
"MIT"
]
| null | null | null | source/HtmlGlobals.pas | amikey/HtmlViewer | 8cb6ee2ea6c727da711a642bf417ce47d3b5cc2a | [
"MIT"
]
| null | null | null | source/HtmlGlobals.pas | amikey/HtmlViewer | 8cb6ee2ea6c727da711a642bf417ce47d3b5cc2a | [
"MIT"
]
| null | null | null | {
Version 11.9
Copyright (c) 2008-2018 by HtmlViewer Team
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.
Note that the source modules HTMLGIF1.PAS and DITHERUNIT.PAS
are covered by separate copyright notices located in those modules.
}
unit HtmlGlobals;
{$I htmlcons.inc}
interface
uses
{$ifdef HasSystemUITypes}
System.UITypes,
{$endif}
{$ifdef UseVCLStyles}
Vcl.Themes,
{$endif}
{$ifdef MSWINDOWS}
Windows,
{$endif}
Classes, SysUtils, Graphics, Controls,
{$ifdef LCL}
LclIntf, LclType, LCLVersion, Types, Messages,
StdCtrls, Buttons, Forms, Base64, Dialogs, Process,
HtmlMisc,
WideStringsLcl,
{$ifdef DebugIt}
{$message 'HtmlViewer uses LCL standard controls.'}
{$endif}
{$else}
Consts, StrUtils, StdCtrls, ShellAPI,
{$ifdef UseTNT}
{$ifdef DebugIt}
{$message 'HtmlViewer uses TNT unicode controls.'}
{$endif}
Messages,
TntControls,
TntStdCtrls,
{$ifdef Compiler18_Plus}
WideStrings,
{$else}
TntWideStrings,
{$endif}
TntClasses,
{$else UseTNT}
{$ifdef DebugIt}
{$message 'HtmlViewer uses VCL standard controls.'}
{$endif}
Buttons,
Messages,
{$ifdef Compiler18_Plus}
WideStrings,
{$else}
TntWideStrings,
TntClasses,
{$endif}
{$endif UseTNT}
{$endif}
Clipbrd,
Math;
const
{$ifndef LCL}
lcl_fullversion = Integer(0);
fpc_fullversion = Integer(0);
{$endif}
{$ifndef MSWindows}
//Charsets defined in unit Windows:
ANSI_CHARSET = 0;
DEFAULT_CHARSET = 1;
SYMBOL_CHARSET = 2;
SHIFTJIS_CHARSET = 128;
HANGEUL_CHARSET = 129;
//JOHAB_CHARSET = 130;
GB2312_CHARSET = 134;
CHINESEBIG5_CHARSET = 136;
GREEK_CHARSET = 161;
TURKISH_CHARSET = 162;
//VIETNAMESE_CHARSET = 163;
HEBREW_CHARSET = 177;
ARABIC_CHARSET = 178;
RUSSIAN_CHARSET = 204;
THAI_CHARSET = 222;
EASTEUROPE_CHARSET = 238;
OEM_CHARSET = 255;
{$endif MSWindows}
// more charset constants
UNKNOWN_CHARSET = -1;
// some more codepage constants
CP_UNKNOWN = -1;
CP_UTF16LE = 1200;
CP_UTF16BE = 1201;
CP_ISO2022JP = 50220;
type
{$IFNDEF DOTNET}
{$IFNDEF FPC}
{$ifndef PtrInt_defined}
{$define PtrInt_defined}
//needed so that in FreePascal, we can use pointers of different sizes
{$IFDEF WIN32}
PtrInt = LongInt;
PtrUInt = LongWord;
{$ENDIF}
{$IFDEF WIN64}
PtrInt = Int64;
PtrUInt = Int64;
{$ENDIF}
//NOTE: The code below asumes a 32bit Linux architecture (such as target i386-linux)
{$IFDEF KYLIX}
PtrInt = LongInt;
PtrUInt = LongWord;
{$ENDIF}
{$ENDIF}
{$ENDIF}
{$ENDIF}
{$ifdef DebugIt}
{$ifdef UNICODE}
{$message 'Compiler uses unicode by default.'}
{$else}
{$message 'Compiler uses single byte chars by default.'}
{$endif}
{$message 'HtmlViewer uses unicode.'}
{$endif}
{$ifdef FPC}
{$else}
{$ifdef Compiler18_Plus}
{$else}
TWideStringList = class(TTntStringList);
{$endif}
{$endif}
{$ifdef UNICODE}
ThtChar = Char;
ThtString = string;
ThtStrings = TStrings;
ThtStringList = TStringList;
PhtChar = PChar;
{$else}
{$if fpc_fullversion < 30000}
UnicodeString = WideString;
{$ifend}
ThtChar = WideChar;
ThtString = WideString;
ThtStrings = TWideStrings;
ThtStringList = TWideStringList;
PhtChar = PWideChar;
{$endif}
ThtCharArray = array of ThtChar;
ThtStringArray = array of ThtString;
ThtIntegerArray = array of Integer;
ThtEdit = class({$ifdef UseTNT} TTntEdit {$else} TEdit {$endif})
protected
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
{$ifndef TEditHasTextHint}
private
FTextHint: ThtString;
FCanvas : TControlCanvas;
procedure WMPaint(var Message: TWMPaint); message WM_PAINT;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property TextHint: ThtString read FTextHint write FTextHint;
{$endif}
end;
ThtComboBox = class({$ifdef UseTNT} TTntComboBox {$else} TComboBox {$endif})
{$ifndef TComboBoxHasTextHint}
private
FTextHint: ThtString;
FCanvas : TControlCanvas;
procedure WMPaint(var Message: TWMPaint); message WM_PAINT;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property TextHint: ThtString read FTextHint write FTextHint;
{$endif}
end;
{Hack solution based on:
http://stackoverflow.com/questions/1465845/cuetext-equivalent-for-a-tmemo
}
ThtMemo = class({$ifdef UseTNT} TTntMemo {$else} TMemo {$endif})
private
FTextHint: TStrings;
FCanvas : TControlCanvas;
FMaxLength : Integer;
procedure SetMaxLength(const AValue: Integer);
procedure WMPaint(var Message: TWMPaint); message WM_PAINT;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property TextHint: TStrings read FTextHint {write FTextHint}; // BG, 29.07.2013: "write FTextHint" would produce memory leaks!!!
property MaxLength: Integer read FMaxLength write SetMaxLength;
end;
{$ifdef UseTNT}
ThtButton = TTntButton;
ThtMemoBase = TTntMemo;
ThtListbox = TTntListBox;
ThtCheckBox = TTntCheckBox;
ThtRadioButton = TTntRadioButton;
ThtHintWindow = TTntHintWindow;
{$else}
ThtButton = TBitBtn; //BG, 25.12.2010: TBitBtn uses correct charset, but TButton does not.
ThtListbox = TListbox;
ThtCheckBox = TCheckBox;
ThtRadioButton = TRadioButton;
ThtHintWindow = THintWindow;
{$endif}
{$ifdef HasSystemUITypes}
ThtScrollStyle = System.UITypes.TScrollStyle;
{$else}
ThtScrollStyle = TScrollStyle;
{$endif}
//BG, 10.12.2010: don't add virtual methods or fields. It is only used to access protected stuff of TCanvas.
ThtCanvas = class(TCanvas)
public
procedure htTextRect(const Rect: TRect; X, Y: Integer; const Text: ThtString);
end;
ThtGraphic = class(TGraphic)
{$ifdef LCL}
private
FTransparent: Boolean;
protected
function GetTransparent: Boolean; override;
procedure SetTransparent(Value: Boolean); override;
{$endif}
end;
{ ThtBitmap }
ThtBitmap = class(TBitmap)
private
procedure SetMask(AValue: TBitmap);
function GetMask: TBitmap;
procedure SetTransparentMask(AValue: Boolean);
protected
FMask: TBitmap;
FTransparent: boolean;
public
constructor Create(WithTransparentMask: Boolean = False); reintroduce; overload;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure Draw(ACanvas: TCanvas; const Rect: TRect); override;
procedure StretchDraw(ACanvas: TCanvas; const DestRect, SrcRect: TRect);
property BitmapMask: TBitmap read GetMask write SetMask;
property WithTransparentMask: Boolean read FTransparent write SetTransparentMask;
end;
const
EofChar = ThtChar(#0);
TabChar = ThtChar(#9);
LfChar = ThtChar(#10);
FfChar = ThtChar(#12);
CrChar = ThtChar(#13);
SpcChar = ThtChar(' ');
DotChar = ThtChar('.');
LessChar = ThtChar('<');
MinusChar = ThtChar('-');
GreaterChar = ThtChar('>');
PercentChar = ThtChar('%');
AmperChar = ThtChar('&');
StarChar = ThtChar('*');
CrLf = ThtString(#13#10);
CrLfTab = ThtString(#13#10#9);
NullRect: TRect = (Left: 0; Top: 0; Right: 0; Bottom: 0);
{$ifdef MSWindows}
FontSerif = ThtString('Times New Roman');
FontMono = ThtString('Courier New');
FontSans = ThtString('Arial');
FontHelvet = ThtString('Arial');
FontCursive = ThtString('Lucida Handwriting');
{$endif MSWindows}
{$ifdef Linux}
FontSerif = ThtString('Serif');
FontMono = ThtString('Monospace');
FontSans = ThtString('Sans');
FontHelvet = ThtString('Sans');
FontCursive = ThtString('Sans');
{$endif Linux}
{$ifdef Darwin}
FontSerif = ThtString('Times');
FontMono = ThtString('Courier');
FontSans = ThtString('Helvetica');
FontHelvet = ThtString('Helvetica');
FontCursive = ThtString('Apple Chancery');
{$endif Darwin}
{$ifdef LCL}
const
HWND_MESSAGE = HWND(-3);
//ANSI_CHARSET = 0; // ANSI charset (Windows-1252)
//DEFAULT_CHARSET = 1;
//SYMBOL_CHARSET = 2;
MAC_CHARSET = 77;
//SHIFTJIS_CHARSET = 128; // Shift JIS charset (Windows-932)
//HANGEUL_CHARSET = 129; // Hangeul charset (Windows-949)
JOHAB_CHARSET = 130; // Johab charset (Windows-1361)
//GB2312_CHARSET = 134; // GB2312 charset (Windows-936)
//CHINESEBIG5_CHARSET = 136; // Chinese Big5 charset (Windows-950)
//GREEK_CHARSET = 161; // Greek charset (Windows-1253)
//TURKISH_CHARSET = 162; // Turkish charset (Windows-1254)
VIETNAMESE_CHARSET = 163; // Vietnamese charset (Windows-1258)
//HEBREW_CHARSET = 177; // Hebrew charset (Windows-1255)
//ARABIC_CHARSET = 178; // Arabic charset (Windows-1256)
//BALTIC_CHARSET = 186; // Baltic charset (Windows-1257)
//RUSSIAN_CHARSET = 204; // Cyrillic charset (Windows-1251)
//THAI_CHARSET = 222; // Thai charset (Windows-874)
//EASTEUROPE_CHARSET = 238; // Eastern european charset (Windows-1250)
//OEM_CHARSET = 255;
const
{ Global Memory Flags }
GMEM_FIXED = 0;
{$EXTERNALSYM GMEM_FIXED}
GMEM_MOVEABLE = 2;
{$EXTERNALSYM GMEM_MOVEABLE}
GMEM_NOCOMPACT = $10;
{$EXTERNALSYM GMEM_NOCOMPACT}
GMEM_NODISCARD = $20;
{$EXTERNALSYM GMEM_NODISCARD}
GMEM_ZEROINIT = $40;
{$EXTERNALSYM GMEM_ZEROINIT}
GMEM_MODIFY = $80;
{$EXTERNALSYM GMEM_MODIFY}
GMEM_DISCARDABLE = $100;
{$EXTERNALSYM GMEM_DISCARDABLE}
GMEM_NOT_BANKED = $1000;
{$EXTERNALSYM GMEM_NOT_BANKED}
GMEM_SHARE = $2000;
{$EXTERNALSYM GMEM_SHARE}
GMEM_DDESHARE = $2000;
{$EXTERNALSYM GMEM_DDESHARE}
GMEM_NOTIFY = $4000;
{$EXTERNALSYM GMEM_NOTIFY}
GMEM_LOWER = GMEM_NOT_BANKED;
{$EXTERNALSYM GMEM_LOWER}
GMEM_VALID_FLAGS = 32626;
{$EXTERNALSYM GMEM_VALID_FLAGS}
GMEM_INVALID_HANDLE = $8000;
{$EXTERNALSYM GMEM_INVALID_HANDLE}
GHND = GMEM_MOVEABLE or GMEM_ZEROINIT;
{$EXTERNALSYM GHND}
GPTR = GMEM_FIXED or GMEM_ZEROINIT;
{$EXTERNALSYM GPTR}
// device caps
{$EXTERNALSYM SHADEBLENDCAPS}
SHADEBLENDCAPS = 45;
{$EXTERNALSYM SB_CONST_ALPHA}
SB_CONST_ALPHA = 1;
{
const
HeapAllocFlags = GMEM_MOVEABLE;
type
// missing in unit Graphics
TProgressStage = (
psStarting,
psRunning,
psEnding
);
}
procedure DecodeStream(Input, Output: TStream);
function PromptForFileName(var AFileName: string; const AFilter: string = '';
const ADefaultExt: string = ''; const ATitle: string = '';
const AInitialDir: string = ''; SaveDialog: Boolean = False): Boolean;
{$else}
// Open a document with the default application associated with it in the system
function OpenDocument(const APath: ThtString): Boolean;
{$endif}
function StartProcess(const ApplicationName, Params: string; ShowWindow: Word = SW_SHOW): Boolean;
{$ifndef Compiler17_Plus}
type
TBytes = array of byte;
{$endif}
var
IsWin95: Boolean;
IsWin32Platform: Boolean; {win95, 98, ME}
ColorBits: Byte;
ThePalette: HPalette; {the rainbow palette for 256 colors}
PalRelative: integer;
const
{DarkerColors and LighterColors need to be in the interface section for inlining to work.}
DarkerColors: array [0..255] of Byte = (
0, 1, 1, 2, 3, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9, 9,
10, 11, 11, 12, 13, 13, 14, 14, 15, 16, 16, 17, 18, 18, 19, 19,
20, 21, 21, 22, 23, 23, 24, 24, 25, 26, 26, 27, 28, 28, 29, 29,
30, 31, 31, 32, 33, 33, 34, 35, 35, 36, 36, 37, 38, 38, 39, 40,
40, 41, 41, 42, 43, 43, 44, 45, 45, 46, 46, 47, 48, 48, 49, 50,
50, 51, 51, 52, 53, 53, 54, 55, 55, 56, 56, 57, 58, 58, 59, 60,
60, 61, 61, 62, 63, 63, 64, 65, 65, 66, 67, 67, 68, 68, 69, 70,
70, 71, 72, 72, 73, 73, 74, 75, 75, 76, 77, 77, 78, 78, 79, 80,
80, 81, 82, 82, 83, 83, 84, 85, 85, 86, 87, 87, 88, 88, 89, 90,
90, 91, 92, 92, 93, 93, 94, 95, 95, 96, 97, 97, 98, 99, 99, 100,
100, 101, 102, 102, 103, 104, 104, 105, 105, 106, 107, 107, 108, 109, 109, 110,
110, 111, 112, 112, 113, 114, 114, 115, 115, 116, 117, 117, 118, 119, 119, 120,
120, 121, 122, 122, 123, 124, 124, 125, 125, 126, 127, 127, 128, 129, 129, 130,
131, 131, 132, 132, 133, 134, 134, 135, 136, 136, 137, 137, 138, 139, 139, 140,
141, 141, 142, 142, 143, 144, 144, 145, 146, 146, 147, 147, 148, 149, 149, 150,
151, 151, 152, 152, 153, 154, 154, 155, 156, 156, 157, 157, 158, 159, 159, 160
);
LighterColors: array [0..255] of Byte = (
128, 128, 129, 129, 130, 130, 131, 131, 132, 132, 133, 133, 134, 134, 135, 135,
136, 136, 137, 137, 138, 138, 139, 139, 140, 140, 141, 141, 142, 142, 143, 143,
144, 144, 145, 145, 146, 146, 147, 147, 148, 148, 149, 149, 150, 150, 151, 151,
152, 152, 153, 153, 154, 154, 155, 155, 156, 156, 157, 157, 158, 158, 159, 159,
160, 160, 161, 161, 162, 162, 163, 163, 164, 164, 165, 165, 166, 166, 167, 167,
168, 168, 169, 169, 170, 170, 171, 171, 172, 172, 173, 173, 174, 174, 175, 175,
176, 176, 177, 177, 178, 178, 179, 179, 180, 180, 181, 181, 182, 182, 183, 183,
184, 184, 185, 185, 186, 186, 187, 187, 188, 188, 189, 189, 190, 190, 191, 191,
192, 192, 193, 193, 194, 194, 195, 195, 196, 196, 197, 197, 198, 198, 199, 199,
200, 200, 201, 201, 202, 202, 203, 203, 204, 204, 205, 205, 206, 206, 207, 207,
208, 208, 209, 209, 210, 210, 211, 211, 212, 212, 213, 213, 214, 214, 215, 215,
216, 216, 217, 217, 218, 218, 219, 219, 220, 220, 221, 221, 222, 222, 223, 223,
224, 224, 225, 225, 226, 226, 227, 227, 228, 228, 229, 229, 230, 230, 231, 231,
232, 232, 233, 233, 234, 234, 235, 235, 236, 236, 237, 237, 238, 238, 239, 239,
240, 240, 241, 241, 242, 242, 243, 243, 244, 244, 245, 245, 246, 246, 247, 247,
248, 248, 249, 249, 250, 250, 251, 251, 252, 252, 253, 253, 254, 254, 255, 255
);
{$if not declared(CopyPalette)}
{$define CopyPaletteMissing}
function CopyPalette(Palette: HPALETTE): HPALETTE;
{$ifend}
function TransparentStretchBlt(DstDC: HDC; DstX, DstY, DstW, DstH: Integer;
SrcDC: HDC; SrcX, SrcY, SrcW, SrcH: Integer; MaskDC: HDC; MaskX,
MaskY: Integer): Boolean;
function htString(const Str: String): ThtString;
function htStringToString(const Str: ThtString): String;
procedure htAppendChr(var Dest: ThtString; C: ThtChar); {$ifdef UseInline} inline; {$endif}
procedure htAppendStr(var Dest: ThtString; const S: ThtString); {$ifdef UseInline} inline; {$endif}
procedure htSetString(var Dest: ThtString; Chr: PhtChar; Len: Integer); {$ifdef UseInline} inline; {$endif}
function htCompareStr(const S1, S2: ThtString): Integer; {$ifdef UseInline} inline; {$endif}
function htCompareText(const S1, S2: ThtString): Integer; {$ifdef UseInline} inline; {$endif}
function htSameText(const S1, S2: ThtString): Boolean; {$ifdef UseInline} inline; {$endif}
function htLowerCase(const Str: ThtString): ThtString; {$ifdef UseInline} inline; {$endif}
function htTrim(const Str: ThtString): ThtString; {$ifdef UseInline} inline; {$endif}
function htUpperCase(const Str: ThtString): ThtString; {$ifdef UseInline} inline; {$endif}
// htPos(SubStr, S, Offst): find substring in S starting at Offset: (formerly known as PosX)
function htPos(const SubStr, S: ThtString; Offset: Integer = 1): Integer;
function IsAlpha(Ch: ThtChar): Boolean; {$ifdef UseInline} inline; {$endif}
function IsDigit(Ch: ThtChar): Boolean; {$ifdef UseInline} inline; {$endif}
function RemoveQuotes(const S: ThtString): ThtString;
function htStringArrayToStr(const StrArray: ThtStringArray; Separator: ThtChar): ThtString;
function htSameStringArray(const A1, A2: ThtStringArray): Boolean;
procedure htSortStringArray(A: ThtStringArray);
//{$ifdef UnitConstsMissing}
//const
// SOutOfResources = 'Out of system resources';
// SInvalidBitmap = 'Bitmap image is not valid';
// SScanLine = 'Scan line index out of range';
//{$endif}
function PtrSub(P1, P2: Pointer): Integer; {$ifdef UseInline} inline; {$endif}
function PtrAdd(P1: Pointer; Offset: Integer): Pointer; {$ifdef UseInline} inline; {$endif}
procedure PtrInc(var P1; Offset: Integer); {$ifdef UseInline} inline; {$endif}
// BG, 17.04.2013: Color of Darker() and Lighter() must be RGB or palette values. Themed or system colors are not supported!
function Darker(Color : TColor): TColor; {$ifdef UseInline} inline; {$endif}
function Lighter(Color : TColor): TColor; {$ifdef UseInline} inline; {$endif}
//code movements from HTMLSubs
function FindSpaces(PStart : PWideChar; const ACount : Integer) : Integer; {$ifdef UseInline} inline; {$endif}
procedure InitFullBg(var FullBG : Graphics.TBitmap; const W, H: Integer; const AIsCopy : Boolean); {$ifdef UseInline} inline; {$endif}
procedure Circle(ACanvas : TCanvas; const X, Y, Rad: Integer); {$ifdef UseInline} inline; {$endif}
//alpha blend determination for Printers only
function CanPrintAlpha(ADC : HDC) : Boolean; {$ifdef UseInline} inline; {$endif}
procedure GetTSize(DC: HDC; P : PWideChar; N : Integer; out VSize : TSize); {$ifdef UseInline} inline; {$endif}
function ThemedColor(const AColor : TColor
{$ifdef has_StyleElements};const AUseThemes : Boolean{$endif}
): TColor; {$ifdef UseInline} inline; {$endif} //overload;
function TextEndsWith(const SubStr, S : ThtString) : Boolean; {$ifdef UseInline} inline; {$endif}
function TextStartsWith(const SubStr, S : ThtString) : Boolean; {$ifdef UseInline} inline; {$endif}
procedure CopyToClipBoardAsHtml(const Str: UTF8String);
procedure CopyToClipBoardAsText(const Str: ThtString);
implementation
{$ifndef TEditHasTextHint}
constructor ThtEdit.Create(AOwner: TComponent);
begin
inherited;
FCanvas := TControlCanvas.Create;
// FTextHintFont := TFont.Create;
// FTextHintFont.Color := clGrayText;
FCanvas.Control := Self;
end;
destructor ThtEdit.Destroy;
begin
// FreeAndNil(FTextHintFont);
FreeAndNil(FCanvas);
inherited;
end;
procedure ThtEdit.WMPaint(var Message: TWMPaint);
begin
inherited;
if (Text = '') and (not Focused) then
begin
FCanvas.Handle := Message.DC;
FCanvas.Font := Font;//FTextHintFont;
FCanvas.Font.Color := clGrayText;
FCanvas.TextOut(1, 1, {$ifdef LCL} UTF8Encode(FTextHint) {$else} FTextHint {$endif});
end;
end;
{$endif}
{$ifndef TComboBoxHasTextHint}
constructor ThtComboBox.Create(AOwner: TComponent);
begin
inherited;
FCanvas := TControlCanvas.Create;
// FTextHintFont := TFont.Create;
// FTextHintFont.Color := clGrayText;
FCanvas.Control := Self;
end;
destructor ThtComboBox.Destroy;
begin
// FreeAndNil(FTextHintFont);
FreeAndNil(FCanvas);
inherited;
end;
procedure ThtComboBox.WMPaint(var Message: TWMPaint);
begin
inherited;
if (Text = '') and (not Focused) then
begin
FCanvas.Handle := Message.DC;
FCanvas.Font := Font;//FTextHintFont;
FCanvas.Font.Color := clGrayText;
FCanvas.TextOut(1, 1, {$ifdef LCL} UTF8Encode(FTextHint) {$else} FTextHint {$endif});
end;
end;
{$endif}
constructor THtMemo.Create(AOwner: TComponent);
begin
inherited;
FTextHint := TStringList.Create;
FCanvas := TControlCanvas.Create;
// FTextHintFont := TFont.Create;
// FTextHintFont.Color := clGrayText;
TControlCanvas(FCanvas).Control := Self;
FMaxLength := 0;
end;
destructor THtMemo.Destroy;
begin
// FreeAndNil(FTextHintFont);
FreeAndNil(FCanvas);
FTextHint.Clear;
FreeAndNil(FTextHint);
inherited;
end;
procedure THtMemo.WMPaint(var Message: TWMPaint);
Var
i : integer;
TextHeight : Integer;
begin
inherited;
if (Text = '') and (not Focused) then
begin
FCanvas.Handle := Message.DC;
FCanvas.Font := Font;//FTextHintFont;
FCanvas.Font.Color := clGrayText;
TextHeight := FCanvas.TextHeight('MLZ'); //Dummy Text to determine Height
for i := 0 to FTextHint.Count - 1 do
FCanvas.TextOut(1, 1+(i*TextHeight), FTextHint[i]);
end;
end;
procedure THtMemo.SetMaxLength(const AValue : Integer);
begin
if AValue <> FMaxLength then begin
FMaxLength := AValue;
SendMessage(Handle, EM_LIMITTEXT, AValue, 0);
end;
end;
{$ifdef has_StyleElements}
function ThemedColor(const AColor : TColor; const AUseThemes : Boolean): TColor; {$ifdef UseInline} inline; {$endif} overload;
begin
if AUseThemes and TStyleManager.IsCustomStyleActive then begin
Result := StyleServices.GetSystemColor(AColor);
end else begin
Result := AColor;
end;
Result := ColorToRGB(Result);
end;
{$else}
function ThemedColor(const AColor : TColor): TColor;
{$ifdef UseInline} inline; {$endif}
begin
{$ifdef UseVCLStyles}
if TStyleManager.IsCustomStyleActive then begin
Result := StyleServices.GetSystemColor(AColor);
end else begin
Result := AColor;
end;
Result := ColorToRGB(Result);
{$else}
Result := ColorToRGB(AColor);
{$endif}
end;
{$endif}
procedure GetTSize(DC: HDC; P : PWideChar; N : Integer; out VSize : TSize);
{$ifdef UseInline} inline; {$endif}
var
Dummy: Integer;
begin
VSize.cx := 0;
VSize.cy := 0;
if not IsWin32Platform then
GetTextExtentExPointW(DC, P, N, 0, @Dummy, nil, VSize)
else
GetTextExtentPoint32W(DC, P, N, VSize); {win95, 98 ME}
end;
function CanPrintAlpha(ADC : HDC) : Boolean; {$ifdef UseInline} inline; {$endif}
begin
Result := GetDeviceCaps(ADC,SHADEBLENDCAPS) and SB_CONST_ALPHA > 0;
end;
function Darker(Color : TColor): TColor; {$ifdef UseInline} inline; {$endif}
{find a somewhat darker color for shading purposes}
var
Red, Green, Blue: Byte;
begin
Result := ColorToRGB(Color); //ThemedColor(Color{$ifdef has_StyleElements},AUseThemes{$endif});
Red := DarkerColors[Byte(Result )];
Green := DarkerColors[Byte(Result shr 8)];
Blue := DarkerColors[Byte(Result shr 16)];
Result := RGB(Red, Green, Blue);
end;
function Lighter(Color : TColor) : TColor; {$ifdef UseInline} inline; {$endif}
{find a somewhat lighter color for shading purposes}
var
Red, Green, Blue: Byte;
begin
Result := ColorToRGB(Color); // ThemedColor(Color{$ifdef has_StyleElements},AUseThemes{$endif});
Red := LighterColors[Byte(Result )];
Green := LighterColors[Byte(Result shr 8)];
Blue := LighterColors[Byte(Result shr 16)];
Result := RGB(Red, Green, Blue);
end;
function FindSpaces(PStart : PWideChar; const ACount : Integer) : Integer;
{$ifdef UseInline} inline; {$endif}
var
I: Integer;
begin
Result := 0;
for I := 0 to ACount - 2 do {-2 so as not to count end spaces}
if ((PStart + I)^ = ' ') or ((PStart + I)^ = #160) then
Inc(Result);
end;
procedure InitFullBg(var FullBG : Graphics.TBitmap; const W, H: Integer; const AIsCopy : Boolean);
{$ifdef UseInline} inline; {$endif}
begin
if not Assigned(FullBG) then
begin
FullBG := Graphics.TBitmap.Create;
if AIsCopy then
begin
FullBG.HandleType := bmDIB;
if ColorBits <= 8 then
FullBG.Palette := CopyPalette(ThePalette);
end;
end;
FullBG.Width := Max(W,2);
FullBG.Height := Max(H,2);
end;
procedure Circle(ACanvas : TCanvas; const X, Y, Rad: Integer);
{$ifdef UseInline} inline; {$endif}
begin
ACanvas.Ellipse(X, Y - Rad, X + Rad, Y);
end;
//-- BG ------------------------------------------------------------------------
function PtrSub(P1, P2: Pointer): Integer;
{$ifdef UseInline} inline; {$endif}
begin
{$ifdef FPC}
Result := P1 - P2;
{$else}
Result := PAnsiChar(P1) - PAnsiChar(P2);
{$endif}
end;
//-- BG ------------------------------------------------------------------------
function PtrAdd(P1: Pointer; Offset: Integer): Pointer;
{$ifdef UseInline} inline; {$endif}
begin
{$ifdef FPC}
Result := P1 + Offset;
{$else}
Result := PAnsiChar(P1) + Offset;
{$endif}
end;
//-- BG ------------------------------------------------------------------------
procedure PtrInc(var P1; Offset: Integer);
{$ifdef UseInline} inline; {$endif}
begin
{$ifdef FPC}
Inc(PAnsiChar(P1), Offset);
{$else}
Inc(PAnsiChar(P1), Offset);
{$endif}
end;
procedure CalcPalette(DC: HDC);
{$ifdef UseInline} inline; {$endif}
{calculate a rainbow palette, one with equally spaced colors}
const
Values: array[0..5] of integer = (55, 115, 165, 205, 235, 255);
var
LP: ^TLogPalette;
I, J, K, Sub: integer;
begin
GetMem(LP, Sizeof(TLogPalette) + 256 * Sizeof(TPaletteEntry));
try
with LP^ do
begin
palVersion := $300;
palNumEntries := 256;
GetSystemPaletteEntries(DC, 0, 256, palPalEntry);
Sub := 10; {start at entry 10}
for I := 0 to 5 do
for J := 0 to 5 do
for K := 0 to 5 do
if not ((I = 5) and (J = 5) and (K = 5)) then {skip the white}
with palPalEntry[Sub] do
begin
peBlue := Values[I];
peGreen := Values[J];
peRed := Values[K];
peFlags := 0;
Inc(Sub);
end;
for I := 1 to 24 do
if not (I in [7, 15, 21]) then {these would be duplicates}
with palPalEntry[Sub] do
begin
peBlue := 130 + 5 * I;
peGreen := 130 + 5 * I;
peRed := 130 + 5 * I;
peFlags := 0;
Inc(Sub);
end;
Sub := 245;
with palPalEntry[Sub] do
begin
peBlue := 254;
peGreen := 255;
peRed := 255;
peFlags := 0;
end;
ThePalette := CreatePalette(LP^);
end;
finally
FreeMem(LP, Sizeof(TLogPalette) + 256 * Sizeof(TPaletteEntry));
end;
end;
{$ifdef CopyPaletteMissing}
// -----------
// CopyPalette
// -----------
// Copies a HPALETTE.
//
// Copied from D3 graphics.pas. This is declared private in some old versions
// of Delphi 2 and is missing in Lazarus Component Library (LCL), so we have
// to implement it here to support those versions.
//
// Parameters:
// Palette The palette to copy.
//
// Returns:
// The handle to a new palette.
//
function CopyPalette(Palette: HPALETTE): HPALETTE;
{$ifdef UseInline} inline; {$endif}
var
PaletteSize: Integer;
LogPal: TMaxLogPalette;
begin
Result := 0;
if Palette = 0 then Exit;
PaletteSize := 0;
if GetObject(Palette, SizeOf(PaletteSize), @PaletteSize) = 0 then Exit;
if PaletteSize = 0 then Exit;
with LogPal do
begin
palVersion := $0300;
palNumEntries := PaletteSize;
GetPaletteEntries(Palette, 0, PaletteSize, palPalEntry);
end;
Result := CreatePalette(PLogPalette(@LogPal)^);
end;
{$endif CopyPaletteMissing}
const
SOutOfResources = 'Out of system resources';
var
SystemPalette16: HPalette; // 16 color palette that maps to the system palette
procedure OutOfResources;
begin
raise EOutOfResources.Create(SOutOfResources);
end;
procedure GDIError;
{$ifndef LCL}
var
ErrorCode: Integer;
Buf: array [Byte] of Char;
begin
ErrorCode := GetLastError;
if (ErrorCode <> 0) and (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, nil,
ErrorCode, LOCALE_USER_DEFAULT, Buf, sizeof(Buf), nil) <> 0) then
raise EOutOfResources.Create(Buf)
else
{$else}
begin
{$endif}
OutOfResources;
end;
function GDICheck(Value: PtrUInt): PtrUInt;
begin
if Value = 0 then GDIError;
Result := Value;
end;
function TransparentStretchBlt(DstDC: HDC; DstX, DstY, DstW, DstH: Integer;
SrcDC: HDC; SrcX, SrcY, SrcW, SrcH: Integer; MaskDC: HDC; MaskX,
MaskY: Integer): Boolean;
const
ROP_DstCopy = $00AA0029;
var
MemDC: HDC;
MemBmp: HBITMAP;
SaveObj: HGDIOBJ;
crText, crBack: TColorRef;
SavePal: HPALETTE;
begin
Result := True;
{$ifdef MSWindows}
if (Win32Platform = VER_PLATFORM_WIN32_NT) and (SrcW = DstW) and (SrcH = DstH) then
begin
MemBmp := GDICheck(CreateCompatibleBitmap(SrcDC, 1, 1));
MemBmp := SelectObject(MaskDC, MemBmp);
try
MaskBlt(
DstDC, DstX, DstY, DstW, DstH,
SrcDC, SrcX, SrcY,
MemBmp, MaskX, MaskY,
MakeRop4(ROP_DstCopy, SrcCopy));
finally
MemBmp := SelectObject(MaskDC, MemBmp);
DeleteObject(MemBmp);
end;
Exit;
end;
{$endif}
MemDC := GDICheck(CreateCompatibleDC(DstDC));
try
MemBmp := GDICheck(CreateCompatibleBitmap(SrcDC, SrcW, SrcH));
SaveObj := SelectObject(MemDC, MemBmp);
SavePal := SelectPalette(SrcDC, SystemPalette16, False);
try
SelectPalette(SrcDC, SavePal, False);
if SavePal <> 0 then
SavePal := SelectPalette(MemDC, SavePal, True)
else
SavePal := SelectPalette(MemDC, SystemPalette16, True);
RealizePalette(MemDC);
{ Mask out the transparent colored pixels of the source }
BitBlt(MemDC, 0, 0, SrcW, SrcH, MaskDC, MaskX, MaskY, SrcCopy);
BitBlt(MemDC, 0, 0, SrcW, SrcH, SrcDC, SrcX, SrcY, SrcErase);
{ Punch out a black hole in the background where the source image will go}
crText := SetTextColor(DstDC, $0);
crBack := SetBkColor(DstDC, $FFFFFF);
StretchBlt(DstDC, DstX, DstY, DstW, DstH, MaskDC, MaskX, MaskY, SrcW, SrcH, SrcAnd);
SetTextColor(DstDC, crText);
SetBkColor(DstDC, crBack);
StretchBlt(DstDC, DstX, DstY, DstW, DstH, MemDC, 0, 0, SrcW, SrcH, SrcInvert);
finally
SelectPalette(MemDC, SavePal, False);
SelectObject(MemDC, SaveObj);
DeleteObject(MemBmp);
end;
finally
DeleteDC(MemDC);
end;
end;
//-- BG ---------------------------------------------------------- 19.09.2018 --
function htString(const Str: String): ThtString;
begin
{$ifdef LCL}
Result := UTF8Decode(Str);
{$else}
Result := Str;
{$endif}
end;
function htStringToString(const Str: ThtString): String;
begin
{$ifdef LCL}
Result := UTF8Encode(Str);
{$else}
Result := Str;
{$endif}
end;
//-- BG ---------------------------------------------------------- 27.03.2011 --
procedure htAppendChr(var Dest: ThtString; C: ThtChar);
{$ifdef UseInline} inline; {$endif}
begin
SetLength(Dest, Length(Dest) + 1);
Dest[Length(Dest)] := C;
end;
//-- BG ---------------------------------------------------------- 27.03.2011 --
procedure htAppendStr(var Dest: ThtString; const S: ThtString);
{$ifdef UseInline} inline; {$endif}
var
L, N: Integer;
begin
L := Length(S);
if L > 0 then
begin
N := Length(Dest);
SetLength(Dest, N + L);
Move(S[1], Dest[N + 1], L * sizeof(ThtChar));
end;
end;
//-- BG ---------------------------------------------------------- 20.03.2011 --
function htCompareStr(const S1, S2: ThtString): Integer;
{$ifdef UseInline} inline; {$endif}
begin
{$ifdef UNICODE}
Result := CompareStr(S1, S2);
{$else}
Result := WideCompareStr(S1, S2);
{$endif}
end;
//-- BG ---------------------------------------------------------- 10.12.2010 --
function htCompareText(const S1, S2: ThtString): Integer;
{$ifdef UseInline} inline; {$endif}
begin
{$ifdef UNICODE}
Result := CompareText(S1, S2);
{$else}
Result := WideCompareText(S1, S2);
{$endif}
end;
//-- BG ---------------------------------------------------------- 10.10.2016 --
function htSameText(const S1, S2: ThtString): Boolean;
{$ifdef UseInline} inline; {$endif}
begin
Result := htCompareText(S1, S2) = 0;
end;
//-- BG ---------------------------------------------------------- 22.10.2016 --
function htStringArrayToStr(const StrArray: ThtStringArray; Separator: ThtChar): ThtString;
var
I: Integer;
begin
SetLength(Result, 0);
for I := Low(StrArray) to high(StrArray) do
begin
if Length(Result) > 0 then
htAppendChr(Result, Separator);
htAppendStr(Result, StrArray[I]);
end;
end;
//-- BG ---------------------------------------------------------- 20.03.2011 --
function htSameStringArray(const A1, A2: ThtStringArray): Boolean;
var
I, N: Integer;
begin
N := Length(A1);
Result := N = Length(A2);
if Result then
for I := 0 To N - 1 do
if htCompareStr(A1[I], A2[I]) <> 0 then
begin
Result := False;
break;
end;
end;
//-- BG ---------------------------------------------------------- 20.03.2011 --
procedure htSortStringArray(A: ThtStringArray);
procedure QuickSort(L, R: Integer);
var
I, J: Integer;
P, T: ThtString;
begin
repeat
I := L;
J := R;
P := A[(L + R) shr 1];
repeat
while htCompareStr(A[I], P) < 0 do
Inc(I);
while htCompareStr(A[J], P) > 0 do
Dec(J);
if I <= J then
begin
T := A[I];
A[I] := A[J];
A[J] := T;
Inc(I);
Dec(J);
end;
until I > J;
if L < J then
QuickSort(L, J);
L := I;
until I >= R;
end;
begin
if length(A) > 1 then
QuickSort(Low(A), High(A));
end;
//-- BG ---------------------------------------------------------- 28.01.2011 --
function htLowerCase(const Str: ThtString): ThtString;
{$ifdef UseInline} inline; {$endif}
begin
{$ifdef UNICODE}
// LowerCase() converts 7bit chars only while AnsiLowerCase() converts UnicodeStrings correctly.
// Actually it does the same as we do in the $else part except for Linux.
Result := AnsiLowerCase(Str);
{$else}
Result := WideLowerCase(Str);
{$endif}
end;
//-- BG ---------------------------------------------------------- 27.03.2011 --
procedure htSetString(var Dest: ThtString; Chr: PhtChar; Len: Integer);
{$ifdef UseInline} inline; {$endif}
begin
{$ifdef UNICODE}
SetString(Dest, Chr, Len);
{$else}
SetLength(Dest, Len);
Move(Chr^, Dest[1], Len * sizeof(ThtChar));
{$endif}
end;
//-- BG ---------------------------------------------------------- 09.08.2011 --
function htTrim(const Str: ThtString): ThtString;
{$ifdef UseInline} inline; {$endif}
begin
Result := Trim(Str);
end;
//-- BG ---------------------------------------------------------- 28.01.2011 --
function htUpperCase(const Str: ThtString): ThtString;
{$ifdef UseInline} inline; {$endif}
begin
{$ifdef UNICODE}
// UpperCase() converts 7bit chars only while AnsiUpperCase() converts UnicodeStrings correctly.
// Actually it does the same as we do in the $else part except for Linux.
Result := AnsiUpperCase(Str);
{$else}
Result := WideUpperCase(Str);
{$endif}
end;
//-- BG ---------------------------------------------------------- 21.08.2011 --
function IsAlpha(Ch: ThtChar): Boolean; {$ifdef UseInline} inline; {$endif}
begin
case Ch of
'a'..'z', 'A'..'Z':
Result := True;
else
Result := False;
end;
end;
//-- BG ---------------------------------------------------------- 21.08.2011 --
function IsDigit(Ch: ThtChar): Boolean; {$ifdef UseInline} inline; {$endif}
begin
case Ch of
'0'..'9':
Result := True;
else
Result := False;
end;
end;
{----------------RemoveQuotes}
function RemoveQuotes(const S: ThtString): ThtString;
{$ifdef UseInline} inline; {$endif}
{if ThtString is a quoted ThtString, remove the quotes (either ' or ")}
begin
Result := S;
if Length(Result) >= 2 then
begin
case Result[1] of
'"', '''':
if Result[Length(Result)] = Result[1] then
Result := Copy(Result, 2, Length(Result) - 2);
end;
end;
end;
function htPos(const SubStr, S: ThtString; Offset: Integer = 1): Integer;
{$ifdef UseInline} inline; {$endif}
{find substring in S starting at Offset}
var
S1: ThtString;
I: Integer;
begin
if Offset <= 1 then
Result := Pos(SubStr, S)
else
begin
S1 := Copy(S, Offset, Length(S) - Offset + 1);
I := Pos(SubStr, S1);
if I > 0 then
Result := I + Offset - 1
else
Result := 0;
end;
end;
function TextStartsWith(const SubStr, S : ThtString) : Boolean;
{$ifdef UseInline} inline; {$endif}
begin
Result := Copy(S,1,Length(SubStr)) = SubStr;
end;
function TextEndsWith(const SubStr, S : ThtString) : Boolean;
{$ifdef UseInline} inline; {$endif}
var l : Integer;
begin
l := Length(SubStr);
Result := Copy(S,Length(S)-l+1,l) = SubStr;
end;
{ ThtEdit }
procedure ThtEdit.KeyDown(var Key: Word; Shift: TShiftState);
begin
if (Key = Ord('A')) and ([ssCtrl] = Shift) then
SelectAll;
end;
{ ThtCanvas }
procedure ThtCanvas.htTextRect(const Rect: TRect; X, Y: Integer; const Text: ThtString);
{$ifdef LCL}
{$else}
var
Options: Longint;
{$endif LCL}
begin
{$ifdef LCL}
inherited TextRect(Rect, X, Y, Utf8Encode(Text));
{$else}
Changing;
RequiredState([csHandleValid, csFontValid, csBrushValid]);
Options := ETO_CLIPPED or TextFlags;
if Brush.Style <> bsClear then
Options := Options or ETO_OPAQUE;
if ((TextFlags and ETO_RTLREADING) <> 0) and
(CanvasOrientation = coRightToLeft) then Inc(X, TextWidth(Text) + 1);
Windows.ExtTextOutW(Handle, X, Y, Options, @Rect, PWideChar(Text), Length(Text), nil);
Changed;
{$endif LCL}
end;
{$ifdef LCL}
procedure DecodeStream(Input, Output: TStream);
const
BufferSize = 999;
var
Decoder: TBase64DecodingStream;
Buffer: array[1..BufferSize] of Byte;
Count: LongInt;
I, J: Integer;
begin
I := 0;
J := 0;
Decoder := TBase64DecodingStream.Create(Input, bdmMIME);
try
Decoder.Reset;
repeat
Count := Decoder.Read(Buffer[1], BufferSize);
Output.Write(Buffer[1], Count);
Inc(I);
Inc(J, Count);
until Count < BufferSize;
finally
Decoder.Free;
end;
end;
function PromptForFileName(var AFileName: string; const AFilter: string = '';
const ADefaultExt: string = ''; const ATitle: string = '';
const AInitialDir: string = ''; SaveDialog: Boolean = False): Boolean;
var
Dialog: TOpenDialog;
begin
if SaveDialog then
begin
Dialog := TSaveDialog.Create(nil);
Dialog.Options := Dialog.Options + [ofOverwritePrompt];
end
else
Dialog := TOpenDialog.Create(nil);
with Dialog do
try
Title := ATitle;
if Length(Title) = 0 then
if SaveDialog then
Title := 'Select Filename'
else
Title := 'Select File';
Filter := AFilter;
if Length(Filter) = 0 then
Filter := 'Any File (*.*)|*.*';
DefaultExt := ADefaultExt;
InitialDir := AInitialDir;
FileName := AFileName;
Result := Execute;
if Result then
AFileName := FileName;
finally
Free;
end;
end;
{$else}
// Open a document with the default application associated with it in the system
function OpenDocument(const APath: ThtString): Boolean;
begin
Result := ShellExecuteW(0, nil, PWideChar(APath), nil, nil, SW_SHOWNORMAL) > 32;
end;
{$endif LCL}
function StartProcess(const ApplicationName, Params: string; ShowWindow: Word): Boolean;
{$ifdef LCL}
var
Process: TProcess;
I: Integer;
begin
// uses TProcess although Lazarus documentation prefers RunCommand
// as RunCommand does not start an asynchronous process.
Process := TProcess.Create(nil);
try
Process.Executable := ApplicationName;
Process.Parameters.Add(Params);
Process.InheritHandles := False;
Process.ShowWindow := swoShow;
// Copy default environment variables
// including DISPLAY variable for GUI application to work
for I := 1 to GetEnvironmentVariableCount do
Process.Environment.Add(GetEnvironmentString(I));
Process.Execute;
Result := True;
finally
Process.Free;
end;
end;
{$else}
var
si: TStartupInfo;
pi: TProcessInformation;
CommandLine: string;
begin
FillMemory(@si, SizeOf(si), 0);
FillMemory(@pi, SizeOf(pi), 0);
si.cb := SizeOf(si);
si.dwFlags := STARTF_USESHOWWINDOW;
si.wShowWindow := ShowWindow;
CommandLine := ApplicationName;
if Pos(' ', CommandLine) > 0 then
CommandLine := '"' + CommandLine + '"';
if Length(Params) > 0 then
CommandLine := CommandLine + ' ' + Params;
UniqueString(CommandLine);
Result := CreateProcess(PChar(ApplicationName), PChar(CommandLine), nil, nil, False, 0, nil, nil, si, pi);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
end;
{$endif}
//-- BG ---------------------------------------------------------- 26.09.2016 --
procedure CopyToClipBoardAsHtml(const Str: UTF8String);
// Put SOURCE on the clipboard, using FORMAT as the clipboard format
const
HtmlClipboardFormat = 'HTML Format';
var
CF_HTML: UINT;
Len: Integer;
{$ifdef LCL}
Str1: UTF8String;
{$else}
Mem: HGLOBAL;
Buf: PAnsiChar;
{$endif}
begin
CF_HTML := RegisterClipboardFormat(HtmlClipboardFormat); {not sure this is necessary}
Len := Length(Str);
{$ifdef LCL}
Str1 := Str;
Clipboard.AddFormat(CF_HTML, Str1[1], Len);
{$else}
Mem := GlobalAlloc(GMEM_DDESHARE + GMEM_MOVEABLE, Len + 1);
try
Buf := GlobalLock(Mem);
try
Move(Str[1], Buf[0], Len);
Buf[Len] := #0;
SetClipboardData(CF_HTML, Mem);
finally
GlobalUnlock(Mem);
end;
except
GlobalFree(Mem);
end;
{$endif}
end;
//-- BG ---------------------------------------------------------- 26.09.2016 --
procedure CopyToClipboardAsText(const Str: ThtString);
{$ifdef LCL}
var
Utf8: Utf8String;
begin
Utf8 := Utf8Encode(Str);
Clipboard.AsText := Utf8;
end;
{$else}
var
Len: Integer;
Mem: HGLOBAL;
Wuf: PWideChar;
begin
Len := Length(Str);
Mem := GlobalAlloc(GMEM_DDESHARE + GMEM_MOVEABLE, (Len + 1) * SizeOf(WideChar));
try
Wuf := GlobalLock(Mem);
try
Move(Str[1], Wuf[0], Len * SizeOf(WideChar));
Wuf[Len] := #0;
// BG, 28.06.2012: use API method. The vcl clipboard does not support multiple formats.
SetClipboardData(CF_UNICODETEXT, Mem);
finally
GlobalUnlock(Mem);
end;
except
GlobalFree(Mem);
end;
end;
{$endif}
{ ThtGraphic }
{$ifdef LCL}
//-- BG ---------------------------------------------------------- 10.10.2016 --
function ThtGraphic.GetTransparent: Boolean;
begin
Result := FTransparent;
end;
//-- BG ---------------------------------------------------------- 10.10.2016 --
procedure ThtGraphic.SetTransparent(Value: Boolean);
begin
if FTransparent <> Value then
begin
FTransparent := Value;
Changed(Self);
end;
end;
{$endif}
{ ThtBitmap }
function ThtBitmap.GetMask: TBitmap;
{This returns mask for frame 1. Content is black, background is white}
begin
if not FTransparent then
Result := nil
else
Result := FMask;
end;
procedure ThtBitmap.SetTransparentMask(AValue: Boolean);
begin
if FTransparent <> AValue then
begin
FTransparent := AValue;
if not FTransparent then
FreeAndNil(FMask)
else if FMask = nil then
begin
FMask := ThtBitmap.Create;
FMask.TransparentMode := tmFixed;
FMask.TransparentColor := clNone;
end;
end;
end;
constructor ThtBitmap.Create(WithTransparentMask: Boolean);
begin
inherited Create;
SetTransparentMask( WithTransparentMask );
end;
procedure ThtBitmap.Assign(Source: TPersistent);
var
htSource: ThtBitmap absolute Source;
begin
{$ifdef LCL}
// LCL didn't copy PixelFormat before SVN-33344 (2011-11-05)
if Source is TCustomBitmap then
PixelFormat := TCustomBitmap(Source).PixelFormat;
{$endif}
inherited;
if Source is ThtBitmap then
begin
FTransparent := htSource.FTransparent;
SetMask(htSource.FMask);
end;
end;
destructor ThtBitmap.Destroy;
begin
FMask.Free;
inherited;
end;
procedure ThtBitmap.SetMask(AValue: TBitmap);
begin
if AValue = nil then
FreeAndNil(FMask)
else
begin
if FMask = nil then
begin
FMask := ThtBitmap.Create;
FMask.TransparentMode := tmFixed;
FMask.TransparentColor := clNone;
end;
FMask.Assign(AValue);
end;
end;
procedure ThtBitmap.Draw(ACanvas: TCanvas; const Rect: TRect);
{$ifdef LCL}
var
UseMaskHandle: HBitmap;
SrcDC: hDC;
DestDC: hDC;
begin
if (Width=0) or (Height=0)
then Exit;
BitmapHandleNeeded;
if not BitmapHandleAllocated then Exit;
if WithTransparentMask then
UseMaskHandle := FMask.Handle
else
UseMaskHandle := 0;
SrcDC := Canvas.GetUpdatedHandle([csHandleValid]);
ACanvas.Changing;
DestDC := ACanvas.GetUpdatedHandle([csHandleValid]);
StretchMaskBlt(
DestDC, Rect.Left, Rect.Top, Rect.Right - Rect.Left, Rect.Bottom - Rect.Top,
SrcDC, 0, 0, Width, Height,
UseMaskHandle, 0, 0, ACanvas.CopyMode);
ACanvas.Changed;
end;
{$else LCL}
var
OldPalette: HPalette;
RestorePalette: Boolean;
DoHalftone: Boolean;
Pt: TPoint;
BPP: Integer;
begin
with Rect do
begin
PaletteNeeded;
OldPalette := 0;
RestorePalette := False;
if Palette <> 0 then
begin
OldPalette := SelectPalette(ACanvas.Handle, Palette, True);
RealizePalette(ACanvas.Handle);
RestorePalette := True;
end;
BPP := GetDeviceCaps(ACanvas.Handle, BITSPIXEL) *
GetDeviceCaps(ACanvas.Handle, PLANES);
DoHalftone := (BPP <= 8) and (PixelFormat in [pf15bit, pf16bit, pf24bit]);
if DoHalftone then
begin
GetBrushOrgEx(ACanvas.Handle, pt);
SetStretchBltMode(ACanvas.Handle, HALFTONE);
SetBrushOrgEx(ACanvas.Handle, pt.x, pt.y, @pt);
end
else if not Monochrome then
SetStretchBltMode(ACanvas.Handle, STRETCH_DELETESCANS);
try
if FTransparent then
TransparentStretchBlt(
ACanvas.Handle, Left, Top, Right - Left, Bottom - Top,
Canvas.Handle, 0, 0, Width, Height,
FMask.Canvas.Handle, 0, 0) {LDB}
else
StretchBlt(
ACanvas.Handle, Left, Top, Right - Left, Bottom - Top,
Canvas.Handle, 0, 0, Width, Height,
ACanvas.CopyMode);
finally
if RestorePalette then
SelectPalette(ACanvas.Handle, OldPalette, True);
end;
end;
end;
{$endif LCL}
procedure ThtBitmap.StretchDraw(ACanvas: TCanvas; const DestRect, SrcRect: TRect);
{Draw parts of this bitmap on ACanvas}
{$ifdef LCL}
var
UseMaskHandle: HBitmap;
SrcDC: hDC;
DestDC: hDC;
begin
if (Width=0) or (Height=0)
then Exit;
BitmapHandleNeeded;
if not BitmapHandleAllocated then Exit;
if WithTransparentMask then
UseMaskHandle := FMask.Handle
else
UseMaskHandle := 0;
SrcDC := Canvas.GetUpdatedHandle([csHandleValid]);
ACanvas.Changing;
DestDC := ACanvas.GetUpdatedHandle([csHandleValid]);
StretchMaskBlt(
DestDC, DestRect.Left, DestRect.Top, DestRect.Right - DestRect.Left, DestRect.Bottom - DestRect.Top,
SrcDC, SrcRect.Left, SrcRect.Top, SrcRect.Right - SrcRect.Left, SrcRect.Bottom - SrcRect.Top,
UseMaskHandle, SrcRect.Left, SrcRect.Top, ACanvas.CopyMode);
ACanvas.Changed;
end;
{$else LCL}
var
OldPalette: HPalette;
RestorePalette: Boolean;
DoHalftone: Boolean;
Pt: TPoint;
BPP: Integer;
begin
with DestRect do
begin
PaletteNeeded;
OldPalette := 0;
RestorePalette := False;
if Palette <> 0 then
begin
OldPalette := SelectPalette(ACanvas.Handle, Palette, True);
RealizePalette(ACanvas.Handle);
RestorePalette := True;
end;
BPP := GetDeviceCaps(ACanvas.Handle, BITSPIXEL) *
GetDeviceCaps(ACanvas.Handle, PLANES);
DoHalftone := (BPP <= 8) and (PixelFormat in [pf15bit, pf16bit, pf24bit]);
if DoHalftone then
begin
GetBrushOrgEx(ACanvas.Handle, pt);
SetStretchBltMode(ACanvas.Handle, HALFTONE);
SetBrushOrgEx(ACanvas.Handle, pt.x, pt.y, @pt);
end
else if not Monochrome then
SetStretchBltMode(ACanvas.Handle, STRETCH_DELETESCANS);
try
if FTransparent then
TransparentStretchBlt(
ACanvas.Handle, Left, Top, Right - Left, Bottom - Top,
Canvas.Handle, SrcRect.Left, SrcRect.Top, SrcRect.Right - SrcRect.Left, SrcRect.Bottom - SrcRect.Top,
FMask.Canvas.Handle, SrcRect.Left, SrcRect.Top) {LDB}
else
StretchBlt(
ACanvas.Handle, Left, Top, Right - Left, Bottom - Top,
Canvas.Handle, SrcRect.Left, SrcRect.Top, SrcRect.Right - SrcRect.Left, SrcRect.Bottom - SrcRect.Top,
ACanvas.CopyMode);
finally
if RestorePalette then
SelectPalette(ACanvas.Handle, OldPalette, True);
end;
end;
end;
{$endif LCL}
{ initialization }
var
DC: HDC;
initialization
DC := GetDC(0);
try
ColorBits := GetDeviceCaps(DC, BitsPixel) * GetDeviceCaps(DC, Planes);
if ColorBits <= 4 then
ColorBits := 4
else if ColorBits <= 8 then
ColorBits := 8
else
ColorBits := 24;
ThePalette := 0;
if ColorBits = 8 then
CalcPalette(DC);
if ColorBits <= 8 then {use Palette Relative bit only when Palettes used}
PalRelative := $2000000
else
PalRelative := 0;
finally
ReleaseDC(0, DC);
end;
{$ifdef TransparentStretchBltMissing}
// Note: This doesn't return the same palette as the Delphi 3 system palette
// since the true system palette contains 20 entries and the Delphi 3 system
// palette only contains 16.
// For our purpose this doesn't matter since we do not care about the actual
// colors (or their number) in the palette.
// Stock objects doesn't have to be deleted.
SystemPalette16 := GetStockObject(DEFAULT_PALETTE);
{$endif}
{$ifdef FPC}
IsWin95 := False; // Use the same always with FPC
IsWin32Platform := False;
{$else}
IsWin95 := (Win32Platform = VER_PLATFORM_WIN32_WINDOWS) and (Win32MinorVersion in [0..9]);
IsWin32Platform := Win32Platform = VER_PLATFORM_WIN32_WINDOWS;
{$endif FPC}
finalization
if ThePalette <> 0 then
DeleteObject(ThePalette);
end.
| 28.846418 | 134 | 0.64543 |
8321c646c4ea687659acc89c42cd0a42f171a560 | 308 | dfm | Pascal | tests/altium_crap/Scripts/Delphiscript Scripts/SCH/CompReplace/ReplaceSelectedComponent.dfm | hanun2999/Altium-Schematic-Parser | a9bd5b1a865f92f2e3f749433fb29107af528498 | [
"MIT"
]
| 1 | 2020-06-08T11:17:46.000Z | 2020-06-08T11:17:46.000Z | tests/altium_crap/Scripts/Delphiscript Scripts/SCH/CompReplace/ReplaceSelectedComponent.dfm | hanun2999/Altium-Schematic-Parser | a9bd5b1a865f92f2e3f749433fb29107af528498 | [
"MIT"
]
| null | null | null | tests/altium_crap/Scripts/Delphiscript Scripts/SCH/CompReplace/ReplaceSelectedComponent.dfm | hanun2999/Altium-Schematic-Parser | a9bd5b1a865f92f2e3f749433fb29107af528498 | [
"MIT"
]
| null | null | null | object Form1: TForm1
Left = 0
Top = 0
Width = 320
Height = 240
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
| 18.117647 | 32 | 0.665584 |
f13595a41869f12bb40f7faad6741da00a7f90c2 | 2,049 | dfm | Pascal | MT/Data.Tela.ERP.dfm | diondcm/exemplos-delphi | 16b4d195981e5f3161d0a2c62f778bec5ba9f3d4 | [
"MIT"
]
| 10 | 2017-08-02T00:44:41.000Z | 2021-10-13T21:11:28.000Z | MT/Data.Tela.ERP.dfm | diondcm/exemplos-delphi | 16b4d195981e5f3161d0a2c62f778bec5ba9f3d4 | [
"MIT"
]
| 10 | 2019-12-30T04:09:37.000Z | 2022-03-02T06:06:19.000Z | MT/Data.Tela.ERP.dfm | diondcm/exemplos-delphi | 16b4d195981e5f3161d0a2c62f778bec5ba9f3d4 | [
"MIT"
]
| 9 | 2017-04-29T16:12:21.000Z | 2020-11-11T22:16:32.000Z | object dmdTelaERP: TdmdTelaERP
OldCreateOrder = False
Height = 413
Width = 730
object memCotacao: TFDMemTable
FetchOptions.AssignedValues = [evMode]
FetchOptions.Mode = fmAll
ResourceOptions.AssignedValues = [rvSilentMode]
ResourceOptions.SilentMode = True
UpdateOptions.AssignedValues = [uvCheckRequired, uvAutoCommitUpdates]
UpdateOptions.CheckRequired = False
UpdateOptions.AutoCommitUpdates = True
Left = 488
Top = 24
object memCotacaodescription: TStringField
FieldName = 'description'
Size = 200
end
object memCotacaoperiod: TStringField
FieldName = 'period'
Size = 50
end
object memCotacaounit: TStringField
FieldName = 'unit'
Size = 50
end
object memCotacaoname: TStringField
FieldName = 'name'
Size = 150
end
object memCotacaodata: TDateTimeField
FieldName = 'data'
end
object memCotacaovalor: TCurrencyField
FieldName = 'valor'
end
end
object RESTClient: TRESTClient
BaseURL = 'https://blockchain.info/charts/market-price?format=json'
Params = <>
Left = 552
Top = 72
end
object RESTResponse1: TRESTResponse
Left = 600
Top = 136
end
object RESTRequest: TRESTRequest
Client = RESTClient
Params = <>
Response = RESTResponse1
SynchronizedEvents = False
Left = 504
Top = 136
end
object FDConnection: TFDConnection
Params.Strings = (
'Database=C:\Desenv\Aqua\exemplos-delphi\SQLite\fast_novo.db'
'DriverID=SQLite')
LoginPrompt = False
Left = 136
Top = 24
end
object qryCliente: TFDQuery
Connection = FDConnection
SQL.Strings = (
'select * from CUSTOMER')
Left = 56
Top = 152
end
object qryCompras: TFDQuery
Connection = FDConnection
SQL.Strings = (
'select * from SALES')
Left = 136
Top = 152
end
object qryProjeto: TFDQuery
Connection = FDConnection
SQL.Strings = (
'select * from PROJECT')
Left = 224
Top = 152
end
end
| 23.825581 | 73 | 0.66325 |
47ba0d15518a9919d4a1216f5e235697de1be42b | 112,439 | pas | Pascal | cCVROM.pas | DanScottNI/delphi-stake | 24886384a0af55259d490d15d3171df6531f49c3 | [
"BSD-3-Clause",
"MIT"
]
| 1 | 2017-01-01T22:33:26.000Z | 2017-01-01T22:33:26.000Z | cCVROM.pas | DanScottNI/delphi-stake | 24886384a0af55259d490d15d3171df6531f49c3 | [
"BSD-3-Clause",
"MIT"
]
| null | null | null | cCVROM.pas | DanScottNI/delphi-stake | 24886384a0af55259d490d15d3171df6531f49c3 | [
"BSD-3-Clause",
"MIT"
]
| null | null | null | { License:
Copyright (c) 2004 Dan Scott
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 cCVROM;
interface
uses Forms,dialogs,Sysutils, Gr32,classes,MemINIHexFile,uEnemyType,
ImgList, jclFileUtils, gr32_image, cMusic, Contnrs,
ctitlescreen, cMisc, cCVObjects;
type
TEnemy = class
private
_Offset : Integer;
_EnemyType : TEnemyType;
_X : Byte;
_Y : Byte;
_Type : Byte;
public
constructor Create(pPointerOffset : Integer);
property EnemyType : TEnemyType read _EnemyType write _EnemyType;
property Offset : Integer read _Offset write _Offset;
property X : Byte read _X write _X;
property Y : Byte read _Y write _Y;
property EnemyItem : Byte read _Type write _Type;
end;
TEnemyData = record
// Offset : Integer;
PointerOffset : Integer;
Count : Integer;
end;
TCVScreen = class
private
_id : Integer;
// This is the length of the level position
// +1 is usually the start of the data.
_Offset : Integer;
_StageNumber : Integer;
_ScreenNumber : Integer;
_EnemyList : Integer;
_X : Integer;
_Y : Integer;
_MultiAreaBit : Boolean;
_Enabled : Boolean;
public
property ID : Integer read _ID write _ID;
property Offset : Integer read _Offset write _Offset;
property XPos : Integer read _X write _X;
property YPos : Integer read _Y write _Y;
property StageNumber : Integer read _StageNumber write _StageNumber;
property ScreenNumber : Integer read _ScreenNumber write _ScreenNumber;
property MultiAreaBit : Boolean read _MultiAreaBit write _MultiAreaBit;
property EnemyList : Integer read _EnemyList write _EnemyList;
property Enabled : Boolean read _Enabled write _Enabled;
end;
{ This is a class that will be used to store the
entrances. This is a descendant of the TObjectList class.
The reason that I am not using a TObjectList, is that
for every access, you have to explicitly cast your objects
to their correct type.}
TScreenList = class(TObjectList)
protected
function GetScreenItem(Index: Integer) : TCVScreen;
procedure SetScreenItem(Index: Integer; const Value: TCVScreen);
public
function Last : TCVScreen;
function Add(AObject: TCVScreen) : Integer;
property Items[Index: Integer] : TCVScreen read GetScreenItem write SetScreenItem;default;
end;
TLevel = class
private
_Name : String;
_BGPalOffset : Integer;
_TSAOffset : Integer;
_GFXOffset : Integer;
_NumberOfTiles : Byte;
_NumberOfScreens : Byte;
_Length : Byte;
_Height : Byte;
_StartX : Byte;
_StartY : Byte;
_NumberOfStages : Byte;
_NumberOfDoors : Integer;
_NumberOfEntrances : Integer;
_NumberOfSpikeCrushers : Integer;
_NumberOfFloatingPlatformSets : Integer;
_NumberOfNonStandardDoors : Integer;
_SpikeCrusherOffset : Integer;
_SpikeCrusherStage : Byte;
_StairPointers : Array Of Integer;
_BreakableBlockPointers : Array Of Integer;
_HiddenItemPointers : Array Of Integer;
_TimeOffsets : Array Of Integer;
_BossOffsets : Array Of Integer;
_NumberOfEnemySets : Integer;
_EnemyOffsets : Array Of TEnemyData;
function GetTimeVal(Index: Integer): Byte;
procedure SetTimeVal(Index: Integer; const Value: Byte);
function GetBossVal(Index: Integer): Byte;
procedure SetBossVal(Index: Integer; const Value: Byte);
public
// The stairs that are in the level.
Stairs : TStairList;
// The doors that are in the level.
Doors : TDoorList;
// Breakable blocks
BreakableBlocks : TBreakableBlockList;
// The entrances that are in the level.
Entrances : TEntranceList;
// The screens that are in the level.
Screens : TScreenList;
// The spike crushers that are in a level.
SpikeCrushers : TSpikeCrusherList;
// The floating platforms that are in a level.
FloatingPlatforms : TFloatingPlatformList;
// The non-standard doors that are in a level.
NonStandardDoors : TNonStandardDoorList;
// The hidden items that are in the level.
HiddenItems : THiddenItemList;
// The name of the level.
property Name : String read _Name write _Name;
property TimeVal[Index: Integer] : Byte read GetTimeVal write SetTimeVal;
property BossVal[Index: Integer] : Byte read GetBossVal write SetBossVal;
// The length of the level.
property Length : Byte read _Length write _Length;
// The height of the level.
property Height : Byte read _Height write _height;
// The number of tiles in the level.
property NumberOfLevelTiles : Byte read _NumberOfTiles write _NumberOfTiles;
// The number of stages in the level.
property NumberOfStages : Byte read _NumberOfStages write _NumberOfStages;
// The offset of the palette for the level.
property BGPaletteOffset : Integer read _BGPalOffset write _BGPalOffset;
// The offset of the TSA for the level.
property TSAOffset : Integer read _TSAOffset write _TSAOffset;
// The offset of the pattern table for the level.
property GFXOffset : Integer read _GFXOffset write _GFXOffset;
// The start X of the level.
property StartX : Byte read _StartX write _StartX;
// The start Y of the level.
property StartY : Byte read _StartY write _StartY;
// The number of enemy points in the level.
property NumberOfEnemySets : Integer read _NumberOfEnemySets write _NumberOfEnemySets;
// The number of screens in the level.
property NumberOfScreens : Byte read _NumberOfScreens write _NumberOfScreens;
function GetEnemyDataOffset(pScreenID : Integer) : Integer;
function GetEnemyDataPointer(pScreenID : Integer) : String;
function GetEnemyDataPointerOffset(pScreenID : Integer) : Integer;
destructor Destroy;override;
end;
{ This is a class that will be used to store the
levels. This is a descendant of the TObjectList class.
The reason that I am not using a TObjectList, is that
for every access, you have to explicitly cast your objects
to their correct type.}
TLevelList = class(TObjectList)
protected
_CurrentLevel : Integer;
function GetCurrentLevel: Integer;
procedure SetCurrentLevel(const Value: Integer);
function GetLevelItem(Index: Integer) : TLevel;
procedure SetLevelItem(Index: Integer; const Value: TLevel);
public
function Add(AObject: TLevel) : Integer;
property Items[Index: Integer] : TLevel read GetLevelItem write SetLevelItem;default;
property CurrentLevel : Integer read GetCurrentLevel write SetCurrentLevel;
end;
{ This is a class that will be used to store the
enemies. This is a descendant of the TObjectList class.
The reason that I am not using a TObjectList, is that
for every access, you have to explicitly cast your objects
to their correct type.}
TEnemyList = class(TObjectList)
private
function GetEnemyItem(Index: Integer): TEnemy;
procedure SetEnemyItem(Index: Integer; const Value: TEnemy);
public
function Last : TEnemy;
function Add(AObject: TEnemy) : Integer;
function NumberOfEnemies : integer;
function NumberOfCandleStands : Integer;
function NumberOfCandles : Integer;
function NumberOfEnemiesFilter(pIndex : Integer) : integer;
function NumberOfCandleStandsFilter(pIndex : Integer) : Integer;
function NumberOfCandlesFilter(pIndex : Integer) : Integer;
property Items[Index: Integer] : TEnemy read GetEnemyItem write SetEnemyItem;default;
end;
TCVROM = class
private
// _CurrentLevel : TLevel;
_SprPalOffset : Integer;
_CastleMapPalOffset : Integer;
_PatternTableItems : Integer;
_PatternTableStatusbar : Integer;
_Palette : Array [0..7,0..3] of Byte;
_PatternTable : Array [0.. 4095] of Byte;
_Level : Integer;
_Screen : Integer;
_ScreenData : Array [0 .. 7, 0..5] of Byte;
_DrawBlock : Array [0..255] of Boolean;
_Tiles : TBitmap32;
_NumberOfLevels : Integer;
_Map : Array Of Array Of Byte;
_SPFFolder : String;
_StairsFreeSpace : Integer;
_BreakableBlocksFreeSpace : Integer;
_EnemyPointer : Integer;
_NumberOfEnemies : Integer;
_DisableTitleScreen : Boolean;
_EnemyData : Array Of Byte;
procedure SetupMap();
procedure LoadScreenData();
procedure SetLevel(pLevel : Integer);
function GetLevel(): Integer;
// procedure DrawCVTile(pOffset: Integer; pBitmap: TBitmap32; pX, pY,
// pPalOffset, pDefaultColour: Integer);overload;
procedure DrawCVTile(pOffset: Integer; pBitmap: TBitmap32; pX, pY,
pIndex: Integer);overload;
procedure DrawLevelTile(pTileNumber: Byte);
procedure LoadPatternTable();
procedure DumpPatternTable(pFilename: String);
function GetNumberOfTiles: Integer; // Not required.
procedure SaveScreenData;
procedure LoadStairsData;
procedure SaveStairsData;
procedure LoadSpikeCrushersData;
procedure SaveSpikeCrushersData;
procedure LoadFloatingPlatformData;
procedure SaveFloatingPlatformData;
procedure LoadDoorsData;
procedure LoadEntranceData;
procedure SaveDoorsData;
procedure SaveEntranceData;
function GetScreen: Integer;
procedure SetScreen(const Value: Integer);
function GetMapHeight: Integer;
function GetMapWidth: Integer;
function GetLevelName: String;
function GetNumberOfStairs: Integer;
function GetLevelStartX: Integer;
function GetLevelStartY: Integer;
function GetFilename: String;
procedure LoadBreakableBlocksData;
function GetNumberOfBreakableBlocks: Integer;
procedure SaveBreakableBlocksData;
procedure LoadNonDoors;
procedure SaveNonDoors;
function GetEnemyArrData(index: Integer): Byte;
procedure SetEnemyArrData(index: Integer; const Value: Byte);
function GetEnemyDataSize: Integer;
function GetPalVal(index1, index2: Integer): Byte;
procedure SetPalVal(index1, index2: Integer; const Value: Byte);
function GetMapVal(index1, index2: Integer): Byte;
procedure SetMapVal(index1, index2: Integer; const Value: Byte);
function GetScreenData(index1, index2: Integer): Byte;
procedure SetScreenData(index1, index2: Integer; const Value: Byte);
procedure LoadHiddenItemsData;
procedure SaveHiddenItemsData;
function GetNumberOfHiddenItems: Integer;
procedure SetChanged(pChanged : Boolean);
function GetChanged() : Boolean;
public
CurrLevel : TLevel;
Levels : TLevelList;
SoundEffects : TSoundEffects;
Statistics : TStatistics;
CurrentPalette : Array [0..15] of Byte;
TitleScreen : TTitleScreen;
CastleIntro : TExTitleScreen;
Ending : TEndTitleScreen;
MusicPointers : TMusicPointersList;
MusicPointersTemplate : TMusicPointersTemplateList;
Damage : TDamage;
Enemies :TEnemyList;
IntroExpansion : TIntroExpansion;
constructor Create(pROMFileName,pDataFileName : string); overload;
destructor Destroy;override;
// functions
function AddNewStair: Integer;
function AddNewBreakableBlock : Integer;
function DrawTileSelector(pIndex: Integer; pBitmap: TBitmap32): Boolean;
function EditTSA(pBlock, pTileIndex1, pTileIndex2: Integer;
pNewTile: Byte): Integer;
function Export8x8Pat(pID: Integer) : T8x8Graphic;
function GetBreakableBlockUnderMouse(pX, pY: Integer): Integer;
function GetBreakableBlockXY(pStairID : Integer;pXY : Byte):Integer;
function GetCurrentScreenXYPos(pXY : Byte): Integer;
function GetDoorUnderMouse(pX,pY: Integer): Integer;
function GetDoorXY(pXY,pDoorID: Integer): Integer;
function GetNonDoorUnderMouse(pX,pY: Integer): Integer;
function GetNonDoorXY(pXY,pDoorID: Integer): Integer;
function GetEntranceUnderMouse(pX,pY : integer) : Integer;
function GetEntranceXY(pXY: Byte; pEntranceID : Integer): Integer;
function GetNumberOfBrBlocksInCurrentStage(): Byte;
function GetSpikeCrusherUnderMouse(pX, pY: Integer): Integer;
function GetSpikeCrusherXY(pStairID : Integer;pXY : Byte):Integer;
function GetFloatingPlatformUnderMouse(pX, pY: Integer): Integer;
function GetFloatingPlatformXY(pStairID : Integer;pXY : Byte):Integer;
function GetStageID: Integer;
function GetStairUnderMouse(pX, pY: Integer): Integer;
function GetStairXY(pStairID : Integer;pXY : Byte):Integer;
function IncrementBlockAttributes(pBlock, pTileIndex1,
pTileIndex2: Integer): Integer;
function IsCVROM : Boolean;
function MemoryMapper : Byte;
function MemoryMapperStr : String;
function PRGCount : Byte;
function CHRCount : Byte;
function FileSize : Integer;
function ReturnColor32NESPal(pElement: Integer): TColor32;
function Save : boolean;
// Procedures
procedure DeleteStair(pID : Integer);
procedure DeleteBreakableBlock(pID : Integer);
procedure DrawCurrentScreen(pBitmap: TBitmap32; pImageList : TBitmap32List;pDrawOptions : Byte);
procedure DrawEnemies(pBitmap :TBitmap32;pItemIndex,pIndex: Integer);
procedure DrawCandles(pBitmap :TBitmap32;pItemIndex,pIndex: Integer);
procedure DrawCandlestand(pBitmap :TBitmap32;pItemIndex,pIndex: Integer);
procedure DrawMap(pBitmap : TBitmap32);
procedure DrawPatternTable(pBitmap: TBitmap32; pPal: Integer);
procedure EraseTile(pTileID: Byte);
procedure ExportLevel(pFilename : String; pId: Integer; pAllow : Byte);
procedure GetScreenStairs(pStringList: TStringList; pStairID: Integer);
procedure GetStageScreenNumbers(pStringList : TStringList);
procedure GetScreenBrBlocks(pStringList: TStringList; pBlockID: Integer);
procedure GetScreenSpikeCrushers(pStringList: TStringList;
pCrusherID: Integer);
procedure GetScreenFloatingPlatform(pStringList: TStringList;
pFloatID: Integer);
procedure Import8x8Pat(pID : Integer; p8x8 : T8x8Graphic);
procedure ImportLevel(pFilename: String);
procedure IncrementStairDirection(pStairID: Integer);
procedure IncrementBrBlockItem(pBlockID : Integer);
procedure LevelName (pStringList : TStringList);
procedure LoadCurrentPalette();
procedure LoadDataFile(pFilename : String);
Procedure LoadDefaultPalette();
procedure LoadEnemyData;
procedure LoadEnemyPosData;
procedure LoadPaletteFile(pFilename : String);
procedure LoadSpritePalette();
procedure RefreshOnScreenTiles(pTileSelectorValue: Byte);
procedure SaveCurrentPalette();
procedure SaveEnemyData;
procedure SaveEnemyPosData;
procedure SaveSpritePalette();
procedure SavePatternTable;
procedure SetDoorXY(pDoorID,pX,pY : Integer);
procedure SetNonDoorXY(pDoorID,pX,pY : Integer);
procedure SetEntranceXY(pX,pY,pEntranceID : Integer);
procedure SetStairsXY(pStairID: Integer; pX, pY: Integer);
procedure SetBreakableBlockXY(pStairID: Integer; pX, pY: Integer);
procedure SetSpikeCrusherXY(pStairID: Integer; pX, pY: Integer);
procedure SetFloatingPlatformXY(pPlatID: Integer; pX, pY: Integer);
procedure TestTileDrawing;
// Properties
property AreaName : String read GetLevelName;
property DisableTitleScreen : Boolean read _DisableTitleScreen write _DisableTitleScreen;
property EnemyData[index : Integer] : Byte read GetEnemyArrData write SetEnemyArrData;
property EnemyDataSize : Integer read GetEnemyDataSize;
property Filename : String read GetFilename;
property Level : Integer read GetLevel write SetLevel;
property LevelStartX : Integer read GetLevelStartX;
property LevelStartY : Integer read GetLevelStartY;
property MapHeight : Integer read GetMapHeight;
property MapWidth : Integer read GetMapWidth;
property Map [index1 : Integer; index2 : Integer] : Byte read GetMapVal write SetMapVal;
property NumberOfBreakableBlocks : Integer read GetNumberOfBreakableBlocks;
property NumberOfHiddenItems : Integer read GetNumberOfHiddenItems;
property NumberOfEnemies : Integer read _NumberOfEnemies;
property NumberOfStairs : Integer read GetNumberOfStairs;
property NumberOfTiles : Integer read GetNumberOfTiles;
property Palette [index1 : Integer;index2: Integer] : Byte read GetPalVal write SetPalVal;
property ScreenID : Integer read GetScreen write SetScreen;
property ScreenData [index1 : Integer;index2 : Integer] : Byte read GetScreenData write SetScreenData;
property SPFFolder : String read _SPFFolder write _SPFFolder;
property Changed : Boolean read GetChanged write SetChanged;
end;
implementation
uses CROM, iNESImage;
{ TCVROM }
const
MAXSTAIRSINSTAGE : Integer = 30;
MAXBRBLOCKSINSTAGE : Integer = 5;
// Draw Options
DRAWOPTSTAIRS : Byte = 1;
DRAWOPTENTRANCES : Byte = 2;
DRAWOPTDOORS : Byte = 4;
DRAWOPTFLOATINGPLATFORMS : Byte = 8;
DRAWOPTBREAKABLEBLOCKS : Byte = 16;
DRAWOPTSPIKECRUSHERS : Byte = 32;
DRAWOPTHIDDENITEMS : Byte = 64;
DRAWOPTHORIZONTALBAR : Byte = 128;
// Export options
EXPORTLEVELS : Byte = 1;
EXPORTTSA : Byte = 2;
EXPORTGRAPHICS : Byte = 4;
EXPORTPALETTE : Byte = 8;
EXPORTENEMYDATA : Byte = 16;
var
StageColours : Array [0..6] of TColor32 = (
clBlue32,clRed32,clFuchsia32,clYellow32,clAqua32,clPurple32, clGray32);
constructor TCVROM.Create(pROMFileName, pDataFileName: string);
begin
if ROM <> nil then
FreeAndNil(ROM);
ROM := TiNESImage.Create(pROMFilename);
LoadDataFile(pDataFileName);
_tiles := TBitmap32.Create;
try
_tiles.width := 8192;
_tiles.Height := 32;
except
freeandNil(_Tiles);
end;
_Screen := -1;
LoadStairsData();
LoadBreakableBlocksData();
LoadHiddenItemsData();
LoadEnemyPosData();
end;
function TCVROM.GetLevel: Integer;
begin
result := _Level;
end;
procedure TCVROM.LoadDataFile(pFilename: String);
var
ini : TMemINIHexFile;
i,x,z,Num : Integer;
LevelLoad :TLevel;
ScreenLoad : TCVScreen;
Door : TDoor;
Entrance : TEntrance;
MusicPointer : TMusicPointers;
MusPointTemp : TMusicPointersTemplate;
NonDoor : TNonStandardDoor;
TGFX : TExTitleScreenGFX;
begin
ini := TMemINIHexFile.Create(pFilename);
try
_CastleMapPalOffset := INI.ReadHexValue('General','CastleMapPal');
_SprPalOffset := INI.ReadHexValue('General','SpritePalette');
_PatternTableStatusbar := INI.ReadHexValue('General','StatusBarGFX');
_PatternTableItems := INI.ReadHexValue('General','ItemsGFX');
_SPFFolder := INI.ReadString('SPF','Folder');
Levels := TLevelList.Create(True);
_StairsFreeSpace := INI.ReadHexValue('General','StairsFreeSpace');
_BreakableBlocksFreeSpace := INI.ReadHexValue('General','BreakableBlocksFreeSpace');
// Now load in the number of levels to load
_NumberOfLevels := INI.ReadInteger('General','NumberOfLevels');
// Load in the sound effects.
SoundEffects := TSoundEffects.Create;
SoundEffects.HeartOffset := INI.ReadHexValue('SoundEffectToggles','Heart');
SoundEffects.MoneyOffset := INI.ReadHexValue('SoundEffectToggles','Money');
SoundEffects.WhipOffset := INI.ReadHexValue('SoundEffectToggles','Whip');
SoundEffects.CastleDoorOffset := INI.ReadHexValue('SoundEffectToggles','CastleDoor');
SoundEffects.InvulnerabilityJar1Offset := INI.ReadHexValue('SoundEffectToggles','InvulnerabilityJar1');
SoundEffects.InvulnerabilityJar2Offset := INI.ReadHexValue('SoundEffectToggles','InvulnerabilityJar2');
SoundEffects.DoorOpeningOffset := INI.ReadHexValue('SoundEffectToggles','DoorOpening');
SoundEffects.HiddenItemOffset := INI.ReadHexValue('SoundEffectToggles','HiddenItem');
SoundEffects.ClrScrOffset := INI.ReadHexValue('SoundEffectToggles','ClrScr');
SoundEffects.ExtraLifeOffset := INI.ReadHexValue('SoundEffectToggles','1UP');
// Load in the title screen data
TitleScreen := TTitleScreen.Create;
_DisableTitleScreen := INI.ReadBool('TitleScreen','Disable',False);
TitleScreen.PointerOffset := INI.ReadHexValue('TitleScreen','Pointers');
TitleScreen.PaletteOffset := INI.ReadHexValue('TitleScreen','Palette');
TitleScreen.PatternTableOffset := INI.ReadHexValue('TitleScreen','PatternTable');
TitleScreen.OriginalCompressedSize := INI.ReadInteger('TitleScreen','OriginalCompressedSize');
TitleScreen.FreeSpace := INI.ReadHexValue('TitleScreen','TitleScreenFreeSpace');
TitleScreen.OriginalOffset := INI.ReadHexValue('TitleScreen','OriginalTitleScreenOffset');
// Load in the intro expansion data.
IntroExpansion := TIntroExpansion.Create;
IntroExpansion.IntroGFXOffset := INI.ReadHexValue('IntroExpansion','IntroGFXOffset');
IntroExpansion.NewIntroGFXOffset := INI.ReadHexValue('IntroExpansion','NewIntroGFXOffset');
IntroExpansion.IntroDataOffset := INI.ReadHexValue('IntroExpansion','IntroDataOffset');
IntroExpansion.NewIntroDataOffset := INI.ReadHexValue('IntroExpansion','NewIntroDataOffset');
IntroExpansion.IntroPointerOffset := INI.ReadHexValue('IntroExpansion','IntroPointer');
IntroExpansion.CHRRAMSettingsOffset := INI.ReadHexValue('IntroExpansion','CHRRAMSettings');
// Load in the castle intro data
CastleIntro := TExTitleScreen.Create;
CastleIntro.PointerOffset := INI.ReadHexValue('CastleIntro','Pointers');
CastleIntro.PaletteOffset := INI.ReadHexValue('CastleIntro','Palette');
CastleIntro.PatternTableOffset := INI.ReadHexValue('CastleIntro','PatternTable');
CastleIntro.OriginalCompressedSize := INI.ReadInteger('CastleIntro','OriginalCompressedSize');
CastleIntro.FreeSpace := INI.ReadHexValue('CastleIntro','TitleScreenFreeSpace');
CastleIntro.OriginalOffset := INI.ReadHexValue('CastleIntro','OriginalTitleScreenOffset');
CastleIntro.NumOfGFX := INI.ReadInteger('CastleIntro','NumOfGFX');
CastleIntro.SetGFXLength(CastleIntro.NumOfGFX);
for i := 0 to CastleIntro.NumOfGFX -1 do
begin
TGFX := CastleIntro.GFX[i];
TGFX.StartTile := INI.ReadHexValue('CastleIntro','GFX' + IntToStr(i+1) + 'PPU');
TGFX.Offset := INI.ReadHexValue('CastleIntro','GFX' + IntToStr(i+1) + 'Offset');
TGFX.NumOfTiles := INI.ReadInteger('CastleIntro','GFX' + IntToStr(i+1) + 'Num');
CastleIntro.GFX[i] := TGFX;
end;
// Load in the ending data
Ending := TEndTitleScreen.Create;
Ending.PointerOffset := INI.ReadHexValue('Ending','Pointers');
Ending.PaletteOffset := INI.ReadHexValue('Ending','Palette');
Ending.PatternTableOffset := INI.ReadHexValue('Ending','PatternTable');
Ending.OriginalCompressedSize := INI.ReadInteger('Ending','OriginalCompressedSize');
Ending.FreeSpace := INI.ReadHexValue('Ending','TitleScreenFreeSpace');
Ending.OriginalOffset := INI.ReadHexValue('Ending','OriginalTitleScreenOffset');
Ending.NumOfGFX := INI.ReadInteger('Ending','NumOfGFX');
ending.TextColourOffset := INI.ReadHexValue('Ending','TextColourOffset');
ending.SetGFXLength(Ending.NumOfGFX);
for i := 0 to Ending.NumOfGFX -1 do
begin
TGFX := Ending.GFX[i];
TGFX.StartTile := INI.ReadHexValue('Ending','GFX' + IntToStr(i+1) + 'PPU');
TGFX.Offset := INI.ReadHexValue('Ending','GFX' + IntToStr(i+1) + 'Offset');
TGFX.NumOfTiles := INI.ReadInteger('Ending','GFX' + IntToStr(i+1) + 'Num');
Ending.GFX[i] := TGFX;
end;
Ending.EndingTextPointerOffset := INI.Readhexvalue('Ending','TextPointersOffset');
Ending.NumberOfText := INI.ReadInteger('Ending','NumberOfText');
// Load in the statistics data
Statistics := TStatistics.Create;
Statistics.StartingHeartsOffset := INI.ReadHexValue('Statistics','StartingHearts');
Statistics.StartingLivesOffset := INI.ReadHexValue('Statistics','StartingLives');
Statistics.SmallHeartsOffset := INI.ReadHexValue('Statistics','SmallHeartValue');
Statistics.BigHeartsOffset := INI.ReadHexValue('Statistics','BigHeartValue');
Statistics.ClockCostOffset := INI.ReadHexValue('Statistics','ClockCost');
// Load in the damage values
Damage := TDamage.Create;
Damage.Stage1to6Offset := INI.ReadHexValue('Damage','Stage1to6');
Damage.Stage7to11Offset := INI.ReadHexValue('Damage','Stage7to11');
Damage.Stage12plusOffset := INI.ReadHexValue('Damage','Stage12Plus');
Damage.MeatOffset := INI.ReadHexValue('Damage','Meat');
// load in the music pointers
MusicPointers := TMusicPointersList.Create(true);
Num := INI.ReadInteger('MusicPointers','NumberOfPointers');
for i := 1 to num do
begin
MusicPointers.Add(TMusicPointers.Create);
MusicPointer := MusicPointers.Last;
MusicPointer.Name := INI.ReadString('MusicPointers','MusicPointer' + IntToStr(i) + 'Name');
MusicPointer.PointerOffset := INI.ReadHexValue('MusicPointers','MusicPointer'+IntToStr(i));
end;
// load in the music pointers
MusicPointersTemplate := TMusicPointersTemplateList.Create(true);
Num := INI.ReadInteger('MusicTemplate','NumberOfTemplates');
for i := 1 to num do
begin
MusicPointersTemplate.Add(TMusicPointersTemplate.Create);
MusPointTemp := MusicPointersTemplate.Last;
MusPointTemp.Name := INI.ReadString('MusicTemplate','MusicTemplate' + IntToStr(i) + 'Name');
MusPointTemp.Square1 := INI.ReadHexValue('MusicTemplate','MusicTemplate' + IntToStr(i) + 'Square1');
MusPointTemp.Square2 := INI.ReadHexValue('MusicTemplate','MusicTemplate' + IntToStr(i) + 'Square2');
MusPointTemp.Triangle := INI.ReadHexValue('MusicTemplate','MusicTemplate' + IntToStr(i) + 'Triangle');
end;
// Now load in the enemy pointer
_EnemyPointer := INI.ReadHexValue('EnemyDataTable','PointerOffset');
_NumberOfEnemies := INI.ReadInteger('EnemyDataTable','AmountOfEnemies');
// Now loop through all the blocks
for i := 0 to _NumberOfLevels - 1 do
begin
Levels.Add(TLevel.Create);
LevelLoad := TLevel(levels.last);
LevelLoad.Name := INI.ReadString('Level' + IntToStr(i),'LevelName');
LevelLoad.GFXOffset := INI.ReadHexValue('Level' + IntToStr(i),'GFXOffset');
LevelLoad.BGPaletteOffset := INI.ReadHexValue('Level' + IntToStr(i),'PaletteOffset');
LevelLoad.TSAOffset := INI.ReadHexValue('Level' + IntToStr(i),'TSAOffset');
LevelLoad.NumberOfLevelTiles := INI.ReadHexValue('Level' + IntToStr(i),'NumOfTiles');
LevelLoad.NumberOfScreens := INI.ReadInteger('Level' + IntToStr(i),'NumOfScreens');
LevelLoad.Length := INI.ReadInteger('Level' + IntToStr(i),'LevelLen');
LevelLoad.Height := INI.ReadInteger('Level' + IntToStr(i),'LevelHei');
LevelLoad.StartX := INI.ReadInteger('Level' + IntToStr(i),'LevelStartX');
LevelLoad.StartY := INI.ReadInteger('Level' + IntToStr(i),'LevelStartY');
LevelLoad._NumberOfEnemySets := INI.ReadInteger('Level' + IntToStr(i),'NumEnemyPoint');
SetLength(LevelLoad._EnemyOffsets,LevelLoad._NumberOfEnemySets);
for x := 0 to LevelLoad._NumberOfEnemySets - 1 do
begin
// LevelLoad._EnemyOffsets[x].Offset := INI.ReadHexValue('Level' + IntToStr(i),'Point' + IntToStr(x+1) + 'Enemy');
LevelLoad._EnemyOffsets[x].Count := INI.ReadInteger('Level' + IntToStr(i),'Point' + IntToStr(x+1) + 'Num');
LevelLoad._EnemyOffsets[x].PointerOffset := INI.ReadHexValue('Level' + IntToStr(i),'Point' + IntToStr(x+1) + 'EnemyPo');
end;
LevelLoad._NumberOfStages := INI.ReadInteger('Level' + IntToStr(i),'NumOfStages');
// Load in the location of the stair pointers.
SetLength(LevelLoad._StairPointers,LevelLoad._NumberOfStages);
for x := 0 to LevelLoad._NumberOfStages - 1 do
LevelLoad._StairPointers[x] := INI.ReadHexValue('Level' + IntToStr(i),'Stage' + IntToStr(x+1) + 'StairPointers');
// Load in the location of the hidden item pointers.
SetLength(LevelLoad._HiddenItemPointers,LevelLoad._NumberOfStages);
for x := 0 to LevelLoad._NumberOfStages - 1 do
LevelLoad._HiddenItemPointers[x] := INI.ReadHexValue('Level' + IntToStr(i),'Stage' + IntToStr(x+1) + 'HiddenItems');
// Load in the location of the breakable block pointers.
SetLength(LevelLoad._BreakableBlockPointers,LevelLoad._NumberOfStages);
for x := 0 to LevelLoad._NumberOfStages - 1 do
LevelLoad._BreakableBlockPointers[x] := INI.ReadHexValue('Level' + IntToStr(i),'Stage' + IntToStr(x+1) + 'BrBlockPointers');
// Load in the time offsets.
SetLength(LevelLoad._TimeOffsets,LevelLoad._NumberOfStages);
for x := 0 to LevelLoad._NumberOfStages - 1 do
LevelLoad._TimeOffsets[x] := INI.ReadHexValue('Level' + IntToStr(i),'Stage' + IntToStr(x+1) + 'Time');
// Load in the boss offsets.
SetLength(levelload._BossOffsets,LevelLoad._NumberOfStages);
for x := 0 to LevelLoad._NumberOfStages - 1 do
LevelLoad._BossOffsets[x] := INI.ReadHexValue('Level' + IntToStr(i),'Stage' + IntToStr(x+1) + 'Boss');
LevelLoad.Screens := TScreenList.Create(True);
for x := 0 to LevelLoad._NumberOfScreens - 1 do
begin
LevelLoad.Screens.Add(TCVScreen.Create);
ScreenLoad := LevelLoad.Screens.Last;
ScreenLoad.id := x;
ScreenLoad.Offset := INI.ReadHexValue('Level' + IntToStr(i),'Screen' + IntToStr(x) + 'Offset');
ScreenLoad.XPos := INI.ReadInteger('Level' + IntToStr(i),'Screen' + IntToStr(x) + 'X');
ScreenLoad.YPos := INI.ReadInteger('Level' + IntToStr(i),'Screen' + IntToStr(x) + 'Y');
ScreenLoad.StageNumber := INI.ReadInteger('Level' + IntToStr(i),'Screen' + IntToStr(x) + 'Stage');
ScreenLoad.ScreenNumber := INI.ReadInteger('Level' + IntToStr(i),'Screen' + IntToStr(x) + 'Screen');
ScreenLoad.EnemyList := INI.ReadInteger('Level' + IntToStr(i),'Screen' + IntToStr(x) + 'EnemyPoint');
ScreenLoad.MultiAreaBit := INI.ReadBool('Level' + IntToStr(i),'Screen' + IntToStr(x) + 'MultiAreaBitSet',False);
screenload.Enabled := INI.ReadBool('Level' + IntToStr(i),'Screen' + IntToStr(x) + 'Enabled',True);
end;
LevelLoad._NumberOfDoors := INI.ReadInteger('Level' + IntToStr(i),'NumOfDoors');
if LevelLoad._NumberOfDoors > 0 then
begin
LevelLoad.Doors := TDoorList.Create (True);
for x := 1 to LevelLoad._NumberOfDoors do
begin
LevelLoad.Doors.Add(TDoor.Create);
Door := LevelLoad.Doors.Last;
Door.Offset := INI.ReadHexValue('Level' + IntToStr(i),'Door' + IntToStr(x) + 'Offset');
Door.ScreenNumber := INI.ReadInteger('Level' + IntToStr(i),'Door' + IntToStr(x) + 'Screen');
Door.AnimationOffset := INI.ReadHexValue('Level' + IntToStr(i),'Door' + IntToStr(x) + 'AnimOffset');
Door.TileAnimationOffset := INI.ReadHexValue('Level' + IntToStr(i),'Door' + IntToStr(x) + 'TileOffset');
end;
end;
LevelLoad._NumberOfEntrances := INI.ReadInteger('Level' + IntToStr(i),'NumOfEntrances');
if LevelLoad._NumberOfEntrances > 0 then
begin
LevelLoad.Entrances := TEntranceList.Create (True);
for x := 1 to LevelLoad._NumberOfEntrances do
begin
LevelLoad.Entrances.Add(TEntrance.Create);
Entrance := LevelLoad.Entrances.Last;
Entrance.Offset := INI.ReadHexValue('Level' + IntToStr(i),'Entrance' + IntToStr(x) + 'Offset');
Entrance.StageNumber := INI.ReadInteger('Level' + IntToStr(i),'Entrance' + IntToStr(x) + 'Stage');
end;
end;
// Load the location of the spike crushers from the ROM.
// There should only be some in level 2, though.
LevelLoad._NumberOfSpikeCrushers := INI.ReadInteger('Level' + IntToStr(i),'NumOfSpikes');
if LevelLoad._NumberOfSpikeCrushers > 0 then
begin
LevelLoad._SpikeCrusherOffset := INI.ReadHexValue('Level' + IntToStr(i),'SpikeOffset');
LevelLoad._SpikeCrusherStage := INI.ReadInteger('Level' + IntToStr(i),'SpikeStage');
end;
LevelLoad._NumberOfFloatingPlatformSets := INI.ReadInteger('Level' + IntToStr(i),'NumOfFloatSets');
if LevelLoad._NumberOfFloatingPlatformSets > 0 then
begin
LevelLoad.FloatingPlatforms := TFloatingPlatformList.Create(True);
for x := 0 to LevelLoad._NumberOfFloatingPlatformSets - 1 do
begin
num := INI.ReadInteger('Level' + IntToStr(i),'FloatPlat' + IntToStr(x+1) + 'Num');
for z := 0 to num -1 do
begin
LevelLoad.FloatingPlatforms.Add(TFloatingPlatform.Create);
LevelLoad.FloatingPlatforms.Last.Stage := INI.ReadInteger('Level' + IntToStr(i),'FloatPlat' + IntToStr(x+1) + 'Stage');
LevelLoad.FloatingPlatforms.Last.Offset := INI.ReadHexValue('Level' + IntToStr(i),'FloatPlat' + IntToStr(x+1) + 'Offset') + (z * 8);
end;
end;
end;
LevelLoad._NumberOfNonStandardDoors := INI.ReadInteger('Level' + IntToStr(i),'NumOfNonStandardDoors',0);
if LevelLoad._NumberOfNonStandardDoors > 0 then
begin
LevelLoad.NonStandardDoors := TNonStandardDoorList.Create(True);
for x := 0 to LevelLoad._NumberOfNonStandardDoors - 1 do
begin
LevelLoad.NonStandardDoors.Add(TNonStandardDoor.Create);
NonDoor := LevelLoad.NonStandardDoors.Last;
NonDoor.Stage := INI.ReadInteger('Level' + IntToStr(i),'NonDoor' + IntToStr(x + 1) + 'Stage');
NonDoor.Offset := INI.ReadHexValue('Level' + IntToStr(i),'NonDoor' + IntToStr(x + 1) + 'Offset');
NonDoor.WalkToXOffset := INI.ReadHexValue('Level' + IntToStr(i),'NonDoor' + IntToStr(x + 1) + 'WalkTo');
end;
end;
end;
finally
FreeAndNil(INI);
end;
end;
procedure TCVROM.SetLevel(pLevel: Integer);
var
i : Integer;
begin
if _Screen > -1 then
begin
SaveScreenData();
SaveEnemyData();
SaveDoorsData();
SaveStairsData();
SaveBreakableBlocksData();
// SaveHiddenItemsData();
SaveEntranceData();
SaveSpikeCrushersData();
SaveFloatingPlatformData();
SaveNonDoors();
end;
for i := 0 to 255 do
_DrawBlock[i] := False;
// Levels.CurrentLevel := Levels[pLevel];
levels.CurrentLevel := pLevel;
_Level := pLevel;
CurrLevel := levels[_level];
_Screen := 0;
SetupMap;
LoadCurrentPalette();
LoadPatternTable();
LoadScreenData();
LoadEnemyData();
// LoadStairsData();
LoadDoorsData();
LoadEntranceData();
LoadSpikeCrushersData();
LoadFloatingPlatformData();
LoadNonDoors;
end;
procedure TCVROM.LoadPatternTable();
var
i : Integer;
begin
for i :=0 to 2303 do
_PatternTable[i] := ROM[CurrLevel._GFXOffset + i];
for i := 0 to 1023 do
_PatternTable[i+2304] := ROM[_PatternTableItems + i];
for i := 0 to 767 do
_PatternTable[i+3328] := ROM[_PatternTableStatusbar + i];
end;
procedure TCVROM.SavePatternTable();
var
i : Integer;
begin
for i :=0 to 2303 do
ROM[CurrLevel._GFXOffset + i] := _PatternTable[i];
for i := 0 to 1023 do
ROM[_PatternTableItems + i] := _PatternTable[i+2304];
for i := 0 to 767 do
ROM[_PatternTableStatusbar + i] := _PatternTable[i+3328];
end;
procedure TCVROM.EraseTile(pTileID : Byte);
var
i : Integer;
begin
for i := 0 to 15 do
_patterntable[(pTileID * 16) + i] := 0;
end;
procedure TCVROM.DumpPatternTable(pFilename : String);
var
Mem : TMemoryStream;
i : Integer;
begin
Mem := TMemoryStream.Create;
try
Mem.SetSize(high(_PatternTable));
Mem.Position :=0;
for i := 0 to mem.Size do
Mem.Write(_PatternTable[i],1);
Mem.SaveToFile(pFilename);
finally
FreeAndNil(Mem);
end;
end;
procedure TCVROM.DrawPatternTable(pBitmap : TBitmap32; pPal : Integer);
var
i,x : Integer;
begin
for i := 0 to 15 do
for x := 0 to 15 do
DrawCVTile((i*16 + x) * 16,pBitmap,x*8,i*8,pPal);
end;
procedure TCVROM.DrawLevelTile(pTileNumber : Byte);
var
i,x : Integer;
TilePal : Array [0..1,0..1] Of Byte;
begin
if assigned(_Tiles) = false then
exit;
TilePal[0,0] := (ROM[CurrLevel._TSAOffset +(ptilenumber*17)]) and 3;
tilepal[0,1] := (ROM[CurrLevel._TSAOffset +(ptilenumber*17)] shr 2) and 3;
tilepal[1,0] := (ROM[CurrLevel._TSAOffset +(ptilenumber*17)] shr 4) and 3;
tilepal[1,1] := (ROM[CurrLevel._TSAOffset +(ptilenumber*17)] shr 6) and 3;
for i := 0 to 3 do
for x := 0 to 3 do
ROM.DrawNESTile(@_PatternTable[ROM[CurrLevel._TSAOffset+ ((pTileNumber * 17)+1) + (i *4 + x)]*16] ,_tiles,(pTileNumber * 32) + x * 8,i*8,@_Palette[tilepal[i div 2,x div 2],0]);
// DrawCVTile(ROM[CurrLevel._TSAOffset+ ((pTileNumber * 17)+1) + (i *4 + x)]*16,_Tiles,(pTileNumber * 32) + x * 8,i*8,tilepal[i div 2,x div 2]);
end;
procedure TCVROM.LoadCurrentPalette();
var
i,x : Integer;
begin
for i := 0 to 3 do
for x := 0 to 3 do
_Palette[i,x] := ROM[CurrLevel._BGPalOffset + (i*4)+x];
end;
{procedure TCVROM.DrawCVTile(pOffset: Integer; pBitmap: TBitmap32; pX,
pY, pPalOffset, pDefaultColour : Integer);
var
x,y : Integer;
curBit, curBit2 : Char;
TempBin : String;
Tile1 : Array [0..15] of Byte;
begin
For y := 0 To 15 do
Tile1[y] := _PatternTable[pOffset+y];
for y := 0 to 7 do
begin
for x := 0 to 7 do
begin
TempBin := ROM.ByteToBin(Tile1[y]);
CurBit := TempBin[x + 1];
TempBin := ROM.ByteToBin(Tile1[y + 8]);
CurBit2 := TempBin[x + 1];
TempBin := CurBit + CurBit2;
if TempBin = '00' Then
pBitmap.Pixel[pX + x,py+y] := ROM.NESPal[pDefaultColour]
else if TempBin = '10' Then
pBitmap.Pixel[pX + x,py+y] := ROM.NESPal[ROM[pPalOffset]]
else if TempBin = '01' Then
pBitmap.Pixel[pX + x,py+y] := ROM.NESPal[ROM[pPalOffset+1]]
else if TempBin = '11' Then
pBitmap.Pixel[pX + x,py+y] := ROM.NESPal[ROM[pPalOffset+2]];
end;
end;
end;}
procedure TCVROM.SaveScreenData;
var
i, x : Integer;
TempScreen : TCVScreen;
begin
TempScreen := CurrLevel.Screens[_Screen];
For i := 0 To 7 do
For x := 0 To 5 do
ROM[TempScreen._Offset + (i * 6) + x] := _ScreenData[i, x];
end;
procedure TCVROM.DrawCurrentScreen(pBitmap: TBitmap32; pImageList : TBitmap32List;pDrawOptions : Byte);
var
i, x : Integer;
TempScreen : TCVScreen;
Stair : TStair;
Door : TDoor;
Entrance : TEntrance;
BrBlock : TBreakableBlock;
Spike : TSpikeCrusher;
Floaty : TFloatingPlatform;
NonDoor : TNonStandardDoor;
Hid : THiddenItem;
begin
TempScreen := CurrLevel.Screens[_Screen];
for i := 0 to 7 do
for x := 0 to 5 do
pBitmap.Draw(bounds(i*32,x * 32,32,32),bounds(_ScreenData[i,x] * 32,0,32,32),_Tiles);
if (pDrawOptions and DRAWOPTHORIZONTALBAR) = DRAWOPTHORIZONTALBAR then
begin
pBitmap.FillRect(0,0,pBitmap.Width,16,clBlack32);
end;
if (pDrawOptions and DRAWOPTSTAIRS) = DRAWOPTSTAIRS then
begin
if NumberOfStairs > 0 then
begin
for i := 0 to CurrLevel.Stairs.Count - 1 do
begin
Stair := CurrLevel.Stairs[i];
if (Stair.Stage = TempScreen._StageNumber) and (Stair.ScreenNumber = TempScreen._ScreenNumber) then
if TempScreen.MultiAreaBit = Stair.MultiAreaBit then
pBitmap.Draw(Stair.X,Stair.Y,pImageList.Bitmap[Stair.Direction]);
end;
end;
end;
if (pDrawOptions and DRAWOPTDOORS) = DRAWOPTDOORS then
begin
if CurrLevel.Doors <> nil then
begin
for i := 0 to CurrLevel.Doors.Count -1 do
begin
Door := CurrLevel.Doors[i];
if ScreenID = Door.ScreenNumber then
pBitmap.Draw(Door.X ,Door.Y,pImageList.Bitmap[4]);
end;
end;
if Assigned(CurrLevel.NonStandardDoors) = True then
begin
for i := 0 to CurrLevel.NonStandardDoors.Count -1 do
begin
NonDoor := CurrLevel.NonStandardDoors[i];
if (TempScreen.ScreenNumber = NonDoor.ScreenNumber) and (NonDoor.Stage = TempScreen.StageNumber) then
pBitmap.Draw(NonDoor.X ,NonDoor.Y,pImageList.Bitmap[16]);
end;
end;
end;
if (pDrawOptions and DRAWOPTENTRANCES) = DRAWOPTENTRANCES then
begin
for i := 0 to CurrLevel.Entrances.Count -1 do
begin
Entrance := CurrLevel.Entrances[i];
if TempScreen.MultiAreaBit = Entrance.MultiAreaBit then
begin
if (TempScreen.ScreenNumber = Entrance.ScreenID) and (Entrance.StageNumber = TempScreen.StageNumber) then
begin
pBitmap.Draw(Entrance.X ,Entrance.Y,pImageList.Bitmap[5]);
end;
end;
end;
end;
if (pDrawOptions and DRAWOPTBREAKABLEBLOCKS) = DRAWOPTBREAKABLEBLOCKS then
begin
if NumberOfBreakableBlocks > 0 then
begin
for i := 0 to CurrLevel.BreakableBlocks.Count - 1 do
begin
BrBlock := CurrLevel.BreakableBlocks[i];
if (BrBlock.StageNumber = TempScreen._StageNumber) and (BrBlock.ScreenNumber = TempScreen._ScreenNumber) then
if TempScreen.MultiAreaBit = BrBlock.MultiAreaBit then
begin
pBitmap.Draw(BrBlock.X,BrBlock.Y,pImageList.Bitmap[6+ BrBlock.ItemDropped]);
if BrBlock.AppearsSecondQuestOnly = True then
begin
pBitmap.Line(BrBlock.X,BrBlock.Y,BrBlock.X+16,BrBlock.Y+16,clRed32);
pBitmap.Line(BrBlock.X+16,BrBlock.Y,BrBlock.X,BrBlock.Y+16,clRed32);
end;
end;
end;
end;
end;
{ if NumberOfHiddenItems > 0 then
begin
for i := 0 to Levels[Levels.CurrentLevel].HiddenItems.Count - 1 do
begin
Hid := Levels[Levels.CurrentLevel].HiddenItems[i];
if (Hid.StageNumber = TempScreen._StageNumber) and (Hid.ScreenNumber = TempScreen._ScreenNumber) then
if TempScreen.MultiAreaBit = Hid.MultiAreaBit then
begin
pBitmap.Draw(Hid.X,Hid.Y,pImageList.Bitmap[17]);
end;
end;
end;}
if (pDrawOptions AND DRAWOPTSPIKECRUSHERS) = DRAWOPTSPIKECRUSHERS then
begin
if Assigned(CurrLevel.SpikeCrushers) = true then
begin
if CurrLevel._NumberOfSpikeCrushers > 0 then
begin
for i := 0 to CurrLevel.SpikeCrushers.Count - 1 do
begin
Spike := CurrLevel.SpikeCrushers[i];
// There currently does not seem to be a provision for
// multi-area screens in the data format. So just draw
// the crushers on screens without the multi-area bit
// set.
if (TempScreen.MultiAreaBit = False) and (TempScreen.StageNumber = CurrLevel._SpikeCrusherStage) and (TempScreen._ScreenNumber = Spike.Screen) then
begin
pBitmap.Draw(Spike.X,Spike.Y,pImageList.Bitmap[14]);
end;
end;
end;
end;
end;
if (pDrawOptions AND DRAWOPTFLOATINGPLATFORMS) = DRAWOPTFLOATINGPLATFORMS then
begin
if Assigned(CurrLevel.FloatingPlatforms) = True then
begin
for i := 0 to CurrLevel.FloatingPlatforms.Count - 1 do
begin
floaty := CurrLevel.FloatingPlatforms[i];
if TempScreen.StageNumber = floaty.Stage then
begin
if (TempScreen.MultiAreaBit = True) and (Floaty.MultiAreaBit = True) and (Floaty.Screen = TempScreen.ScreenNumber) then
begin
pBitmap.Draw(floaty.X,floaty.Y,pImageList.Bitmap[15]);
end
else if (TempScreen.MultiAreaBit = False) and (Floaty.MultiAreaBit = False) and (Floaty.Screen = TempScreen.ScreenNumber) then
begin
pBitmap.Draw(floaty.X,floaty.Y,pImageList.Bitmap[15]);
end;
end;
end;
end;
end;
end;
procedure TCVROM.DrawCVTile(pOffset: Integer; pBitmap: TBitmap32; pX, pY,
pIndex: Integer);
var
x,y : Integer;
curBit, curBit2 : Char;
TempBin : String;
Tile1 : Array [0..15] of Byte;
begin
For y := 0 To 15 do
Tile1[y] := _PatternTable[pOffset+y];
for y := 0 to 7 do
begin
for x := 0 to 7 do
begin
TempBin := ROM.ByteToBin(Tile1[y]);
CurBit := TempBin[x + 1];
TempBin := ROM.ByteToBin(Tile1[y + 8]);
CurBit2 := TempBin[x + 1];
TempBin := CurBit + CurBit2;
if TempBin = '00' Then
pBitmap.Pixel[pX + x,py+y] := ROM.NESPal[_Palette[pIndex,0]]
else if TempBin = '10' Then
pBitmap.Pixel[pX + x,py+y] := ROM.NESPal[_Palette[pIndex,1]]
else if TempBin = '01' Then
pBitmap.Pixel[pX + x,py+y] := ROM.NESPal[_Palette[pIndex,2]]
else if TempBin = '11' Then
pBitmap.Pixel[pX + x,py+y] := ROM.NESPal[_Palette[pIndex,3]];
end;
end;
end;
function TCVROM.GetScreen: Integer;
begin
result := _Screen;
end;
procedure TCVROM.SetScreen(const Value: Integer);
begin
if _Screen > -1 then
begin
SaveScreenData();
SaveEnemyData();
end;
_Screen := Value;
LoadScreenData();
LoadEnemyData();
end;
procedure TCVROM.LoadStairsData();
var
TempLevel : TLevel;
i,x,z : Integer;
Stair : TStair;
begin
for i := 0 to _NumberOfLevels - 1 do
begin
TempLevel := Levels[i];
if assigned(TempLevel.Stairs) = false then
TempLevel.Stairs := TStairList.Create(True)
else
exit;
for x := 0 to TempLevel._NumberOfStages -1 do
begin
z := ROM.PointerToOffset(TempLevel._StairPointers[x],$18010,$8000);
// Now we load in all the stairs.
while (ROM[z] > $00) do
begin
TempLevel.Stairs.Add(TStair.Create);
Stair := TStair(TempLevel.Stairs.Last);
Stair.Stage := x;
Stair.Y := (ROM[z] and 240) - 16;
Stair.UnknownBit1 := ROM[z] and 8;
Stair.MultiAreaBitRaw := ROM[z] and 4;
Stair.Direction := ROM[z] and 3;
Stair.X := (ROM[z+1] and 248);
Stair.ScreenNumber := ROM[z+1] and 7;
z := z + 2;
end;
end;
end;
end;
procedure TCVROM.LoadBreakableBlocksData();
var
TempLevel : TLevel;
i,x,z : Integer;
BreakableBlock : TBreakableBlock;
begin
for i := 0 to _NumberOfLevels - 1 do
begin
TempLevel := Levels[i];
if assigned(TempLevel.BreakableBlocks) = false then
TempLevel.BreakableBlocks := TBreakableBlockList.Create(True)
else
exit;
for x := 0 to TempLevel._NumberOfStages -1 do
begin
z := ROM.PointerToOffset(TempLevel._BreakableBlockPointers[x],$18010);
// Now we load in all the breakable blocks.
while (ROM[z] > $00) do
begin
TempLevel.BreakableBlocks.Add(TBreakableBlock.Create);
BreakableBlock := TempLevel.BreakableBlocks.Last;
BreakableBlock.StageNumber := x;
BreakableBlock.Y := (ROM[z] and $F0) -32;
BreakableBlock.ItemDropped := ROM[z] and 7;
BreakableBlock.X := (ROM[z+1] and $F0);
BreakableBlock.MultiAreaBitRaw := ROM[z] and 8;
BreakableBlock.AppearsSecondQuestOnlyRaw := ROM[z+1] and 8;
BreakableBlock.ScreenNumber := ROM[z+1] and $7;
z := z + 2;
end;
end;
end;
end;
procedure TCVROM.SaveStairsData();
var
TempLevel : TLevel;
i,x,z : Integer;
Stair : TStair;
CurrentStairPos : Integer;
StairPointer : String;
begin
CurrentStairPos := _StairsFreeSpace;
for i := 0 to _NumberOfLevels -1 do
begin
TempLevel := Levels[i];
for x := 0 to TempLevel._NumberOfStages -1 do
begin
// Update the stairs pointer.
// This assumes that the bank which the stair
// is stored in is the normal one.
StairPointer := IntToHex((CurrentStairPos - $18010) + $8000,4);
ROM[TempLevel._StairPointers[x]] := StrToInt('$' + StairPointer[3] + StairPointer[4]);
ROM[TempLevel._StairPointers[x]+1] := StrToInt('$' + StairPointer[1] + StairPointer[2]);
// showmessage(IntToHex(StairPointer,4));
if TempLevel.Stairs.Count > 0 then
begin
for z := 0 to TempLevel.Stairs.Count -1 do
begin
Stair := TStair(TempLevel.Stairs[z]);
if Stair.Stage = x then
begin
// if Stair._X >= 240 then
// Stair._X := 239;
ROM[CurrentStairPos] := ((Stair.Y + 16) and 240) +
(Stair.UnknownBit1 and 8) + (Stair.MultiAreaBitRaw and 4)
+ (Stair.Direction and 3);
ROM[CurrentStairPos + 1] := ((Stair.X) and 248) + (
Stair.ScreenNumber and 7);
inc(CurrentStairPos,2);
end; // if Stair._Stage = x
end; // z
end; // else if stairs.count > 0
ROM[CurrentStairPos] := 0;
inc(CurrentStairPos);
end; // x
end; // i
end;
procedure TCVROM.SaveBreakableBlocksData();
var
TempLevel : TLevel;
i,x,z : Integer;
BrBlock : TBreakableBlock;
CurrentBrBlockPos : Integer;
BrBlockPointer : String;
begin
CurrentBrBlockPos := _BreakableBlocksFreeSpace;
for i := 0 to _NumberOfLevels -1 do
begin
TempLevel := Levels[i];
for x := 0 to TempLevel._NumberOfStages -1 do
begin
// Update the stairs pointer.
// This assumes that the bank which the stair
// is stored in is the normal one.
BrBlockPointer := IntToHex((CurrentBrBlockPos - $18010) + $8000,4);
ROM[TempLevel._BreakableBlockPointers[x]] := StrToInt('$' + BrBlockPointer[3] + BrBlockPointer[4]);
ROM[TempLevel._BreakableBlockPointers[x]+1] := StrToInt('$' + BrBlockPointer[1] + BrBlockPointer[2]);
// showmessage(IntToHex(StairPointer,4));
if TempLevel.BreakableBlocks.Count > 0 then
begin
for z := 0 to TempLevel.BreakableBlocks.Count -1 do
begin
BrBlock := TempLevel.BreakableBlocks[z];
if BrBlock.StageNumber = x then
begin
ROM[CurrentBrBlockPos] := ((BrBlock.Y + 32) and $F0) +
(BrBlock.MultiAreaBitRaw and 8) + (BrBlock.ItemDropped and 7);
ROM[CurrentBrBlockPos + 1] := ((BrBlock.X) and $F0) +
(BrBlock.AppearsSecondQuestOnlyRaw and 8) + (BrBlock.ScreenNumber and 7);
inc(CurrentBrBlockPos,2);
end; // if Stair._Stage = x
end; // z
end; // else if stairs.count > 0
ROM[CurrentBrBlockPos] := 0;
inc(CurrentBrBlockPos);
end; // x
end; // i
end;
function TCVROM.DrawTileSelector(pIndex : Integer;pBitmap : TBitmap32): Boolean;
var
i : Integer;
begin
if assigned(_Tiles) = false then
begin
result := false;
end
else
begin
for i := 0 to 5 do
begin
if _DrawBlock[pindex + i] = False then
begin
if _tiles <> nil then DrawLevelTile(pindex + i);
_DrawBlock[pindex + i] := True;
end;
pBitmap.Draw(bounds(0,i * 32,32,32),bounds((pindex+i) * 32,0,32,32),_tiles);
end;
result := true;
end;
end;
function TCVROM.GetNumberOfTiles: Integer;
begin
result := Levels[Levels.CurrentLevel]._NumberOfTiles;
end;
procedure TCVROM.LoadScreenData;
var
i, x : Integer;
TempBlock : TCVScreen;
begin
TempBlock := Levels[Levels.CurrentLevel].Screens[_Screen];
For i := 0 To 7 do
begin
For x := 0 To 5 do
begin
_ScreenData[i, x] := ROM[TempBlock._Offset + (i * 6) + x];
if _DrawBlock[_ScreenData[i,x]] = False then
begin
if _tiles <> nil then DrawLevelTile(_screendata[i,x]);
_DrawBlock[_ScreenData[i, x]] := True;
end;
end;
end;
end;
function TCVROM.EditTSA(pBlock,pTileIndex1,pTileIndex2 : Integer; pNewTile : Byte): Integer;
begin
ROM[Levels[Levels.CurrentLevel]._TSAOffset+ (pBlock * 17+1) + (pTileIndex1 *4 + pTileIndex2)] := pNewTile;
DrawLevelTile(pBlock);
result := 1;
end;
function TCVROM.IncrementBlockAttributes(pBlock,pTileIndex1,pTileIndex2 : Integer): Integer;
var
TilePal : Array [0..1,0..1] Of Byte;
begin
TilePal[0,0] := (ROM[Levels[Levels.CurrentLevel]._TSAOffset +(pBlock*17)]) and 3;
tilepal[0,1] := (ROM[Levels[Levels.CurrentLevel]._TSAOffset +(pBlock*17)] shr 2) and 3;
tilepal[1,0] := (ROM[Levels[Levels.CurrentLevel]._TSAOffset +(pBlock*17)] shr 4) and 3;
tilepal[1,1] := (ROM[Levels[Levels.CurrentLevel]._TSAOffset +(pBlock*17)] shr 6) and 3;
if tilepal[pTileIndex1,pTileIndex2] = 3 then
tilepal[pTileIndex1,pTileIndex2] := 0
else
inc(tilepal[pTileIndex1,pTileIndex2]);
ROM[Levels[Levels.CurrentLevel]._TSAOffset+ (pBlock * 17)] := (TilePal[1,1] shl 6) + (TilePal[1,0] shl 4) + (TilePal[0,1] shl 2) + (TilePal[0,0]);
DrawLevelTile(pBlock);
result := 1;
end;
procedure TCVROM.RefreshOnScreenTiles(pTileSelectorValue : Byte);
var
i, x : integer;
begin
// Reset all the tiles back to the false drawing state.
for i := 0 to 255 do
_DrawBlock[i] := false;
for i := 0 to 7 do
for x := 0 to 5 do
if _DrawBlock[_ScreenData[i,x]] = false then
begin
DrawLevelTile(_screendata[i,x]);
_DrawBlock[_ScreenData[i,x]] := True;
end;
// Now scroll through the blocks displayed in the tile selector
for i := pTileSelectorValue to pTileSelectorValue + 5 do
if _DrawBlock[i] = false then
begin
DrawLevelTile(i);
_DrawBlock[i] := True;
end;
end;
procedure TCVROM.SaveCurrentPalette;
var
i,x : Integer;
begin
for i := 0 to 3 do
for x := 0 to 3 do
ROM[Levels[Levels.CurrentLevel]._BGPalOffset + (i*4)+x] := _Palette[i,x];
end;
function TCVROM.GetStairUnderMouse(pX,pY : Integer): Integer;
var
TempScreen : TCVScreen;
i : Integer;
Stair : TStair;
begin
TempScreen := Levels[Levels.CurrentLevel].Screens[_Screen];
result := -1;
if NumberOfStairs > 0 then
begin
for i := 0 to Levels[Levels.CurrentLevel].Stairs.Count - 1 do
begin
Stair := Levels[Levels.CurrentLevel].Stairs[i];
if (Stair.Stage = TempScreen.StageNumber) and (Stair.ScreenNumber = TempScreen.ScreenNumber) then
begin
if TempScreen.MultiAreaBit = Stair.MultiAreaBit then
begin
if ((pX >= Stair.X) and (pX <= Stair.X + 16)) and ((pY >= Stair.Y) and (pY <= Stair.Y + 16)) then
begin
result := i;
exit;
end
end;
end;
end;
end;
end;
procedure TCVROM.SetStairsXY(pStairID : Integer;pX,pY : Integer);
var
Stair : TStair;
begin
Stair := Levels[Levels.CurrentLevel].Stairs[pStairID];
if pX > -1 then
begin
if pX > 240 then
Stair.X := 240
else
Stair.X := pX;
end;
if pY > -1 then
Stair.Y := pY;
ROM.Changed := True;
end;
procedure TCVROM.IncrementStairDirection(pStairID : Integer);
var
Stair : TStair;
begin
Stair := Levels[Levels.CurrentLevel].Stairs[pStairID];
if Stair.Direction = 3 then
Stair.Direction := 0
else
Stair.Direction := Stair.Direction + 1;
ROM.Changed := True;
end;
function TCVROM.GetStairXY(pStairID: Integer; pXY: Byte): Integer;
var
Stair : TStair;
begin
Stair := Levels[Levels.CurrentLevel].Stairs[pStairID];
if pXY = 0 then
result := Stair.X
else
result := Stair.Y;
end;
function TCVROM.GetDoorUnderMouse(pX, pY: Integer): Integer;
var
Door : TDoor;
i : Integer;
begin
result := -1;
if assigned(Levels[Levels.CurrentLevel].Doors) = false then
exit;
if (Levels[Levels.CurrentLevel].Doors.Count = 0) then
exit;
for i := 0 to Levels[Levels.CurrentLevel].Doors.Count - 1 do
begin
Door := Levels[Levels.CurrentLevel].Doors[i];
if Door.ScreenNumber = ScreenID then
begin
if (pX >= Door.X) and (pX <= Door.X + 16) then
begin
if (pY >= Door.Y) and (pY <= Door.Y + 16) then
begin
result := i;
exit;
end;
end;
end;
end;
end;
function TCVROM.GetEntranceUnderMouse(pX, pY: integer): Integer;
var
Entrance : TEntrance;
TempScreen : TCVScreen;
i : Integer;
begin
TempScreen := Levels[Levels.CurrentLevel].Screens[_Screen];
result := -1;
if assigned(Levels[Levels.CurrentLevel].Entrances) = false then
exit;
if Levels[Levels.CurrentLevel].Entrances.count = 0 then
exit;
for i := 0 to Levels[Levels.CurrentLevel].Entrances.Count - 1 do
begin
Entrance := Levels[Levels.CurrentLevel].Entrances[i];
if (Entrance.MultiAreaBit = TempScreen.MultiAreaBit) and (Entrance.StageNumber = TempScreen.StageNumber) then
begin
if Entrance.ScreenID = TempScreen.ScreenNumber then
begin
if (pX >= Entrance.X) and (pX <= Entrance.X + 16) then
begin
if (pY >= Entrance.Y) and (pY <= Entrance.Y + 16) then
begin
result := i;
exit;
end;
end;
end;
end;
end;
end;
procedure TCVROM.SetDoorXY(pDoorID, pX,pY: Integer);
begin
if pX > -1 then
begin
if pX > 240 then
Levels[Levels.CurrentLevel].Doors[pDoorID].X := 240
else
Levels[Levels.CurrentLevel].Doors[pDoorID].X := pX;
end;
if pY > -1 then
Levels[Levels.CurrentLevel].Doors[pDoorID].Y := pY;
ROM.Changed := True;
end;
procedure TCVROM.SetEntranceXY(pX, pY, pEntranceID: Integer);
begin
if pX > -1 then
begin
if pX > 240 then
Levels[Levels.CurrentLevel].Entrances[pEntranceID].X := 240
else
Levels[Levels.CurrentLevel].Entrances[pEntranceID].X := pX;
end;
if pY > -1 then
begin
if pY > 176 then
Levels[Levels.CurrentLevel].Entrances[pEntranceID].Y := 176
else
Levels[Levels.CurrentLevel].Entrances[pEntranceID].Y := pY;
end;
ROM.Changed := True;
end;
function TCVROM.GetDoorXY(pXY,pDoorID: Integer): Integer;
begin
if pXY = 0 then
result := Levels[Levels.CurrentLevel].Doors[pDoorID].X
else
result := Levels[Levels.CurrentLevel].Doors[pDoorID].Y;
end;
function TCVROM.GetEntranceXY(pXY: Byte; pEntranceID : Integer): Integer;
begin
if pXY = 0 then
result := Levels[Levels.CurrentLevel].Entrances[pEntranceID].X
else
result := Levels[Levels.CurrentLevel].Entrances[pEntranceID].Y;
end;
procedure TCVROM.SaveDoorsData();
var
i,tempadd, temp : Integer;
Door : TDoor;
begin
if assigned(Levels[Levels.CurrentLevel].Doors) = false then exit;
for i := 0 to Levels[Levels.CurrentLevel].Doors.Count - 1 do
begin
Door := Levels[Levels.CurrentLevel].Doors[i];
ROM[Door.Offset] := ((Door.Y + 32) and 254) + (Door.MultiAreaBitSet and 1);
ROM[Door.Offset + 1] := ((Door.X + 8) and 254) + Door.UnknownBit1;
if Door.AnimationOffset > 0 then
ROM[Door.AnimationOffset] := (Door.Y and 240) + (Door.AnimUnknownBit1 and 14) + (Door.AnimationMultiArea and 1);
// ROM[Door._AnimOffset] := (Door._AnimationY and 2) + (Door._AnimationMultiArea and 1);
if Door.X and 128 = 128 then
tempadd := 16
else
tempadd := 0;
// Presumably, the point in the nametable where the door tiles disappear and the door
// appears over them.
temp := (((Door.Y) div 8)*32) + ((((Door.X) and 248) +tempadd) div 8) + Door.NameTable;
if Door.TileAnimationOffset > 0 then
begin
ROM[Door.TileAnimationOffset] := StrToInt('$' + copy(inttohex(temp,4),1,2));
ROM[Door.TileAnimationOffset + 1] := StrToInt('$' + copy(inttohex(temp,4),3,2));
end;
end;
end;
procedure TCVROM.LoadDoorsData();
var
i : Integer;
Door : TDoor;
begin
if assigned(Levels[Levels.CurrentLevel].Doors) = false then exit;
for i := 0 to Levels[Levels.CurrentLevel].Doors.Count - 1 do
begin
Door := Levels[Levels.CurrentLevel].Doors[i];
Door.Y := (ROM[Door.Offset] and 254)-32;
Door.X := ((ROM[Door.Offset +1]) and 254) -8;
Door.UnknownBit1 := ROM[Door.Offset +1] and 1;
Door.MultiAreaBitSet := ROM[Door.Offset] and 1;
Door.YAnimation := (ROM[Door.AnimationOffset] and 240);
Door.AnimUnknownBit1 := ROM[Door.AnimationOffset] and 14;
Door.AnimationMultiArea := (ROM[Door.AnimationOffset] and 1);
// Work out the name table address.
if (ROM[Door.TileAnimationOffset] >= $20) and (ROM[Door.TileAnimationOffset] <= $23) then
Door.NameTable := $2000
else if (ROM[Door.TileAnimationOffset] >= $24) and (ROM[Door.TileAnimationOffset] <= $27) then
Door.NameTable := $2400
else if (ROM[Door.TileAnimationOffset] >= $28) and (ROM[Door.TileAnimationOffset] <= $2B) then
Door.NameTable := $2800
else if (ROM[Door.TileAnimationOffset] >= $2C) and (ROM[Door.TileAnimationOffset] <= $29) then
Door.NameTable := $2C00;
end;
end;
procedure TCVROM.SaveEntranceData();
var
i : Integer;
Entrance : TEntrance;
begin
for i := 0 to Levels[Levels.CurrentLevel].Entrances.Count - 1 do
begin
Entrance := Levels[Levels.CurrentLevel].Entrances[i];
ROM[Entrance.Offset] := ((Entrance.Y + 48) and 248) + (Entrance.ScreenID and 7);
ROM[Entrance.Offset + 1] := ((Entrance.X + 8) and 254) + (Entrance.MultiAreaBitRaw and 1);
end;
end;
procedure TCVROM.LoadEntranceData();
var
i : Integer;
Entrance : TEntrance;
begin
for i := 0 to Levels[Levels.CurrentLevel].Entrances.Count - 1 do
begin
Entrance := Levels[Levels.CurrentLevel].Entrances[i];
Entrance.Y := (ROM[Entrance.Offset] and 248)-48;
Entrance.ScreenID := (ROM[Entrance.Offset] and 7);
Entrance.X := (ROM[Entrance.Offset +1] and 254)-8;
Entrance.MultiAreaBitRaw := (ROM[Entrance.Offset+1] and 1);
end;
end;
procedure TCVROM.TestTileDrawing();
var
i : Integer;
begin
LoadPatternTable();
LoadCurrentPalette();
for i := 0 to 100 do
self.DrawLevelTile(i);
_Tiles.SaveToFile('C:\test.bmp');
DumpPatternTable('C:\test.nes');
end;
function TCVROM.GetMapHeight: Integer;
begin
result := Levels[Levels.CurrentLevel]._Height;
end;
function TCVROM.GetMapWidth: Integer;
begin
result := Levels[Levels.CurrentLevel]._Length;
end;
procedure TCVROM.SetupMap;
var
TempScreen : TCVScreen;
i,x : Integer;
begin
SetLength(_Map,Levels[Levels.CurrentLevel]._Length, Levels[Levels.CurrentLevel]._Height);
for i := 0 to Levels[Levels.CurrentLevel]._Length -1 do
for x := 0 to Levels[Levels.CurrentLevel]._Height -1 do
_Map[i,x] := $FF;
for i := 0 to Levels[Levels.CurrentLevel]._NumberOfScreens - 1 do
begin
TempScreen := Levels[Levels.CurrentLevel].Screens[i];
if TempScreen._Enabled = True then
_Map[TempScreen._X,TempScreen._Y] := TempScreen._id;
end;
// showmessage('end');
end;
function TCVROM.Save() : Boolean;
begin
SaveScreenData();
SaveEnemyData();
SaveDoorsData();
SaveStairsData();
SaveBreakableBlocksData();
SaveEntranceData();
SaveFloatingPlatformData();
SaveNonDoors();
result := ROM.Save;
end;
function TCVROM.GetNumberOfStairs: Integer;
var
TempScreen : TCVScreen;
count, i : Integer;
begin
TempScreen := Levels[Levels.CurrentLevel].Screens[self._Screen];
count := 0;
if assigned(Levels[Levels.CurrentLevel].Stairs) = false then
begin
result := count;
exit;
end;
for i := 0 to Levels[Levels.CurrentLevel].Stairs.Count - 1 do
if Levels[Levels.CurrentLevel].Stairs[i].Stage = TempScreen._StageNumber then
inc(count);
result := count;
end;
function TCVROM.AddNewStair: Integer;
var
TempScreen : TCVScreen;
Stair : TStair;
begin
TempScreen := Levels[Levels.CurrentLevel].Screens[self._Screen];
if Levels[Levels.CurrentLevel].Stairs.Count < MAXSTAIRSINSTAGE then
begin
Levels[Levels.CurrentLevel].Stairs.Add(TStair.Create);
Stair := Levels[Levels.CurrentLevel].Stairs.Last;
Stair.Stage := TempScreen._StageNumber;
Stair.ScreenNumber := TempScreen._ScreenNumber;
Stair.MultiAreaBit := TempScreen.MultiAreaBit;
result := 1;
end
else
result := -1;
ROM.Changed := True;
end;
procedure TCVROM.DeleteStair(pID: Integer);
begin
if MessageDlg('Are you sure that you wish to delete this stair?',mtConfirmation,[mbYes, mbNo],0) = 6 then
Levels[Levels.CurrentLevel].Stairs.Delete(pID);
ROM.Changed := True;
end;
function TCVROM.GetLevelName: String;
begin
result := Levels[Levels.CurrentLevel]._Name;
end;
procedure TCVROM.GetScreenStairs(pStringList: TStringList; pStairID : Integer);
var
TempScreen : TCVScreen;
TempStair : TStair;
i : Integer;
begin
TempStair := Levels[Levels.CurrentLevel].Stairs.Items[pStairID];
for i := 0 to Levels[Levels.CurrentLevel].Screens.Count - 1 do
begin
TempScreen := Levels[Levels.CurrentLevel].Screens.Items[i];
if TempScreen._StageNumber = TempStair.Stage then
pStringList.Add(IntToHex(TempScreen._id,2));
end;
end;
function TCVROM.Export8x8Pat(pID: Integer) : T8x8Graphic;
var
x,y : Integer;
curBit, curBit2 : Char;
TempBin1,TempBin2, TempBin3 : String;
Tile1 : Array [0..15] of Byte;
p8x8 : T8x8Graphic;
begin
For y := 0 To 15 do
Tile1[y] := self._PatternTable[(pID * 16) +y];
for y := 0 to 7 do
begin
TempBin1 := ROM.ByteToBin(Tile1[y]);
TempBin2 := ROM.ByteToBin(Tile1[y + 8]);
for x := 0 to 7 do
begin
CurBit := TempBin1[x + 1];
CurBit2 := TempBin2[x + 1];
TempBin3 := CurBit + CurBit2;
if TempBin3 = '00' Then
p8x8.Pixels[y,x] := 0
else if TempBin3 = '10' Then
p8x8.Pixels[y,x] := 1
else if TempBin3 = '01' Then
p8x8.Pixels[y,x] := 2
else if TempBin3 = '11' Then
p8x8.Pixels[y,x] := 3;
end;
end;
result := p8x8;
end;
procedure TCVROM.Import8x8Pat(pID: Integer; p8x8: T8x8Graphic);
var
x,y : Integer;
TempBin1, TempBin2 : String;
Tile1 : Array [0..15] of Byte;
begin
For y := 0 To 15 do
Tile1[y] := self._PatternTable[(pID * 16) +y];
for y := 0 to 7 do
begin
for x := 0 to 7 do
begin
TempBin1 := IntToStr(p8x8.Pixels[y,x] and 1) + TempBin1;
TempBin2 := IntToStr(p8x8.Pixels[y,x] shr 1) + TempBin2;
end;
self._PatternTable[(pID * 16) +y] := ROM.BinToByte(TempBin1);
self._PatternTable[(pID * 16) +y + 8] := ROM.BinToByte(TempBin2);
// showmessage(TempBin2);
end;
end;
function TCVROM.GetCurrentScreenXYPos(pXY: Byte): Integer;
var
TempScreen : TCVScreen;
begin
TempScreen := Levels[Levels.CurrentLevel].Screens[self.ScreenID];
if pXY = 0 then
result := TempScreen._X
else
result := TempScreen._Y;
end;
function TCVROM.GetLevelStartX: Integer;
begin
result := Levels[Levels.CurrentLevel]._StartX;
end;
function TCVROM.GetLevelStartY: Integer;
begin
result := Levels[Levels.CurrentLevel]._StartY;
end;
function TCVROM.ReturnColor32NESPal(pElement: Integer): TColor32;
begin
result := ROM.NESPal[pElement];
end;
function TCVROM.IsCVROM: Boolean;
begin
if (ROM.MapperNumber = 2) and (ROM.PRGCount = 8) and (ROM.CHRCount = 0) then
result := true
else
result := False;
end;
procedure TCVROM.LoadDefaultPalette;
begin
ROM.LoadDefaultPalette;
end;
procedure TCVROM.LoadPaletteFile(pFilename: String);
begin
ROM.LoadPaletteFile(pFilename);
end;
function TCVROM.GetFilename: String;
begin
result := ROM.Filename;
end;
procedure TCVROM.LevelName(pStringList: TStringList);
var
i : Integer;
begin
for i := 0 to 6 do
pStringList.Add(self.Levels[i]._Name);
end;
procedure TCVROM.LoadSpritePalette;
var
i,x : Integer;
begin
for i := 0 to 3 do
for x := 0 to 3 do
_Palette[i+4,x] := ROM[self._SprPalOffset + (i*4)+x];
end;
procedure TCVROM.SaveSpritePalette;
var
i,x : Integer;
begin
for i := 0 to 3 do
for x := 0 to 3 do
ROM[self._SprPalOffset + (i*4)+x] := _Palette[i+4,x];
end;
function TCVROM.GetNumberOfBreakableBlocks: Integer;
var
TempScreen : TCVScreen;
count, i : Integer;
begin
TempScreen := Levels[Levels.CurrentLevel].Screens[self._Screen];
count := 0;
if assigned(Levels[Levels.CurrentLevel].BreakableBlocks) = false then
begin
result := count;
exit;
end;
if (Levels[Levels.CurrentLevel].BreakableBlocks.Count = 0) then
begin
result := count;
exit;
end;
for i := 0 to Levels[Levels.CurrentLevel].BreakableBlocks.Count - 1 do
if Levels[Levels.CurrentLevel].BreakableBlocks[i].StageNumber = TempScreen._StageNumber then
inc(count);
result := count;
end;
function TCVROM.GetBreakableBlockUnderMouse(pX, pY: Integer): Integer;
var
TempScreen : TCVScreen;
i : Integer;
BrBlock : TBreakableBlock;
begin
TempScreen := Levels[Levels.CurrentLevel].Screens[self._Screen];
result := -1;
if self.NumberOfBreakableBlocks > 0 then
begin
for i := 0 to Levels[Levels.CurrentLevel].BreakableBlocks.Count - 1 do
begin
BrBlock := Levels[Levels.CurrentLevel].BreakableBlocks[i];
if (BrBlock.StageNumber = TempScreen._StageNumber) and (BrBlock.ScreenNumber = TempScreen._ScreenNumber) then
begin
if TempScreen.MultiAreaBit = BrBlock.MultiAreaBit then
begin
if ((pX >= BrBlock.X) and (pX <= BrBlock.X + 16)) and ((pY >= BrBlock.Y) and (pY <= BrBlock.Y + 16)) then
begin
result := i;
exit;
end
end;
end;
end;
end;
end;
function TCVROM.GetBreakableBlockXY(pStairID: Integer; pXY: Byte): Integer;
begin
if pXY = 0 then
result := Levels[Levels.CurrentLevel].BreakableBlocks[pStairID].X
else
result := Levels[Levels.CurrentLevel].BreakableBlocks[pStairID].Y;
end;
procedure TCVROM.SetBreakableBlockXY(pStairID, pX, pY: Integer);
begin
if pStairID = -1 then exit;
if pX > -1 then
Levels[Levels.CurrentLevel].BreakableBlocks[pStairID].X := pX;
if pY > -1 then
Levels[Levels.CurrentLevel].BreakableBlocks[pStairID].Y := pY;
ROM.Changed := True;
end;
procedure TCVROM.GetScreenBrBlocks(pStringList: TStringList;
pBlockID: Integer);
var
TempScreen : TCVScreen;
TempBrBlock : TBreakableBlock;
i : Integer;
begin
TempBrBlock := Levels[Levels.CurrentLevel].BreakableBlocks.Items[pBlockID];
for i := 0 to Levels[Levels.CurrentLevel].Screens.Count - 1 do
begin
TempScreen := Levels[Levels.CurrentLevel].Screens.Items[i];
if TempScreen._StageNumber = TempBrBlock.StageNumber then
pStringList.Add(IntToHex(TempScreen._id,2));
end;
end;
procedure TCVROM.IncrementBrBlockItem(pBlockID: Integer);
var
BrBlock : TBreakableBlock;
begin
BrBlock := Levels[Levels.CurrentLevel].BreakableBlocks[pBlockID];
if BrBlock.ItemDropped = 7 then
BrBlock.ItemDropped := 0
else
BrBlock.ItemDropped := BrBlock.ItemDropped + 1;
ROM.Changed := True;
end;
procedure TCVROM.GetScreenSpikeCrushers(pStringList: TStringList;
pCrusherID: Integer);
var
TempScreen : TCVScreen;
i : Integer;
begin
if Assigned(levels[levels.currentlevel].SpikeCrushers) = True then
begin
for i :=0 to Levels[Levels.CurrentLevel].Screens.Count - 1 do
begin
TempScreen := Levels[Levels.CurrentLevel].Screens[i];
if (TempScreen._StageNumber = Levels[Levels.CurrentLevel]._SpikeCrusherStage) and (TempScreen.MultiAreaBit = False) then
begin
pStringList.Add(IntToHex(TempScreen._id,2));
end;
end;
end;
end;
function TCVROM.GetChanged: Boolean;
begin
result := ROM.Changed;
end;
function TCVROM.GetStageID : Integer;
begin
result := self.Levels[self._Level].Screens[self._Screen]._StageNumber;
end;
procedure TCVROM.GetStageScreenNumbers(pStringList: TStringList);
var
i : Integer;
begin
for i := 0 to self.Levels[self._Level].Screens.Count - 1 do
begin
if self.Levels[self._Level].Screens[i]._StageNumber = self.Levels[_Level].Screens[_Screen]._StageNumber then
begin
pStringList.Add(IntToHex(i,2));
end;
end;
end;
procedure TCVROM.DrawMap(pBitmap: TBitmap32);
var
i, x : Integer;
begin
for i := 0 to self.MapHeight-1 do
begin
for x := 0 to self.MapWidth -1 do
begin
if _Map[x,i] < $FF then
begin
// pBitmap.RenderText(x*16,i*16,IntToHex(_Map[i,x],1),0,clWhite32);
// pBitmap.FillRect(16+x*16,16+i*16,16+x*16+16,16+i*16+16,clFuchsia32);
// pBitmap.FrameRectS(16+x*16,16+i*16,16+x*16+16,16+i*16+16,clWhite32);
pBitmap.FillRect(x*16,i*16,x*16+16,i*16+16,StageColours[self.Levels[self.Level].Screens[self.Map[x,i]]._StageNumber] );
pBitmap.FrameRectS(x*16,i*16,x*16+16,i*16+16,clWhite32);
end;
end;
end;
end;
procedure TCVROM.LoadEnemyPosData;
var
i : Integer;
begin
if Assigned(Self.Enemies) = True then
FreeAndNil(self.Enemies);
self.Enemies := TEnemyList.Create(True);
for i := 0 to self._NumberOfEnemies - 1 do
begin
Enemies.Add(TEnemy.Create(self._EnemyPointer + (i * 2)));
end;
end;
procedure TCVROM.SaveEnemyPosData;
var
i : Integer;
begin
for i := 0 to Enemies.Count -1 do
begin
if ROM[Enemies[i].Offset] = 0 then
// Do nothing.
else
begin
if ROM[Enemies[i].Offset] = $FF then
begin
ROM[Enemies[i].Offset+1] := Enemies[i]._Type;
if ROM[Enemies[i].Offset+2] = $FE then
begin
ROM[Enemies[i].Offset+3] := Enemies[i].X;
ROM[Enemies[i].Offset+4] := Enemies[i].Y;
end
else
begin
ROM[Enemies[i].Offset+2] := Enemies[i].X;
ROM[Enemies[i].Offset+3] := Enemies[i].Y;
end;
end
else if ROM[Enemies[i].Offset] = $FE then
begin
ROM[Enemies[i].Offset+1] := Enemies[i].X;
ROM[Enemies[i].Offset+2] := Enemies[i].Y;
end
else if ROM[Enemies[i]._Offset] and $20 = $20 then
begin
ROM[Enemies[i].Offset] := Enemies[i].X;
ROM[Enemies[i].Offset+1] := Enemies[i].Y;
end
else
begin
ROM[Enemies[i].Offset] := Enemies[i].EnemyItem;
ROM[Enemies[i].Offset+1] := Enemies[i].X;
ROM[Enemies[i].Offset+2] := Enemies[i].Y;
end;
end;
end;
end;
function TCVROM.GetNumberOfBrBlocksInCurrentStage: Byte;
var
i : Integer;
StageNo : Integer;
count : Integer;
begin
StageNo := self.Levels[self._Level].Screens[self._Screen].StageNumber;
Count := 0;
for i := 0 to self.Levels[self._Level].BreakableBlocks.Count - 1 do
begin
if self.Levels[self._Level].BreakableBlocks[i].StageNumber = StageNo then
inc(Count);
end;
result := count;
end;
function TCVROM.AddNewBreakableBlock: Integer;
var
TempScreen : TCVScreen;
BreakableBlock : TBreakableBlock;
begin
TempScreen := Levels[Levels.CurrentLevel].Screens[self._Screen];
if self.GetNumberOfBrBlocksInCurrentStage < MAXBRBLOCKSINSTAGE then
begin
Levels[Levels.CurrentLevel].BreakableBlocks.Add(TBreakableBlock.Create);
BreakableBlock := Levels[Levels.CurrentLevel].BreakableBlocks.Last;
BreakableBlock.StageNumber := TempScreen._StageNumber;
BreakableBlock.ScreenNumber := TempScreen._ScreenNumber;
BreakableBlock.MultiAreaBit := TempScreen.MultiAreaBit;
result := 1;
end
else
result := -1;
ROM.Changed := True;
end;
procedure TCVROM.DeleteBreakableBlock(pID: Integer);
begin
if MessageDlg('Are you sure that you wish to delete this breakable block?',mtConfirmation,[mbYes, mbNo],0) = 6 then
Levels[Levels.CurrentLevel].BreakableBlocks.Delete(pID);
ROM.Changed := True;
end;
function TCVROM.GetEnemyArrData(index: Integer): Byte;
begin
result := self._EnemyData[index];
end;
procedure TCVROM.SetEnemyArrData(index: Integer; const Value: Byte);
begin
self._EnemyData[index] := Value;
ROM.Changed := True;
end;
procedure TCVROM.LoadEnemyData;
var
i : Integer;
EnemyOffset : Integer;
begin
SetLength(_EnemyData,Levels[Levels.CurrentLevel]._EnemyOffsets[Levels[Levels.CurrentLevel].Screens[self.ScreenID]._EnemyList].Count);
EnemyOffset := ROM.PointerToOffset(Levels[Levels.CurrentLevel]._EnemyOffsets[Levels[Levels.CurrentLevel].Screens[self.ScreenID]._EnemyList].PointerOffset,0,$C000);
for i := 0 to Levels[Levels.CurrentLevel]._EnemyOffsets[Levels[Levels.CurrentLevel].Screens[self.ScreenID]._EnemyList].Count -1 do
_EnemyData[i] := ROM[EnemyOffset+i];
end;
procedure TCVROM.SaveEnemyData;
var
i : Integer;
EnemyOffset : Integer;
begin
EnemyOffset := ROM.PointerToOffset(Levels[Levels.CurrentLevel]._EnemyOffsets[Levels[Levels.CurrentLevel].Screens[self.ScreenID]._EnemyList].PointerOffset,0,$C000);
for i := 0 to Levels[Levels.CurrentLevel]._EnemyOffsets[Levels[Levels.CurrentLevel].Screens[self.ScreenID]._EnemyList].Count -1 do
ROM[EnemyOffset+i] := _EnemyData[i];
end;
procedure TCVROM.DrawCandles(pBitmap: TBitmap32; pItemIndex,pIndex: Integer);
var
ArrPos, i,x, count, total : Integer;
NumbersBMP : TBitmap32;
begin
ArrPos := 2+ (self.Levels[self._level].screens[self._screen]._ScreenNumber*8);
// Draw the enemy
if FileExists(ExtractFileDir(Application.ExeName) + '\Data\numbers.bmp') = true then
begin
NumbersBMP := TBitmap32.Create;
try
NumbersBMP.Width := 136;
NumbersBMP.Height := 8;
NumbersBMP.LoadFromFile(ExtractFileDir(Application.ExeName) + '\Data\numbers.bmp');
NumbersBMP.DrawMode := dmBlend;
for i := 0 to 7 do
begin
if (i mod 2 = 1) and ((Enemies[_EnemyData[ArrPos+i]]._EnemyType = etCandle) or (Enemies[_EnemyData[ArrPos+i]]._EnemyType = etCandleNoXEditing) or (Enemies[_EnemyData[ArrPos+i]]._EnemyType = etNone)) then
begin
if _EnemyData[ArrPos+i] > 0 then
begin
NumbersBMP.MasterAlpha := 255;
if Enemies[_EnemyData[ArrPos+i]].Y > $D8 then
begin
pBitmap.Draw(bounds(self.Enemies[self._EnemyData[ArrPos+i]].X + ((i div 2) * 64)-8,$D0-$20,8,8),Bounds(StrToInt('$' + IntToHex(_EnemyData[ArrPos+i],2)[1])*8,0,8,8),NumbersBMP);
pBitmap.Draw(bounds((self.Enemies[self._EnemyData[ArrPos+i]].X + ((i div 2) * 64)-8) +8,$D0-$20,8,8),Bounds(StrToInt('$' + IntToHex(_EnemyData[ArrPos+i],2)[2])*8,0,8,8),NumbersBMP);
end
else
begin
pBitmap.Draw(bounds(self.Enemies[self._EnemyData[ArrPos+i]].X + ((i div 2) * 64)-8,self.Enemies[self._EnemyData[ArrPos+i]].Y-$20,8,8),Bounds(StrToInt('$' + IntToHex(_EnemyData[ArrPos+i],2)[1])*8,0,8,8),NumbersBMP);
pBitmap.Draw(bounds((self.Enemies[self._EnemyData[ArrPos+i]].X + ((i div 2) * 64)-8) +8,self.Enemies[self._EnemyData[ArrPos+i]].Y-$20,8,8),Bounds(StrToInt('$' + IntToHex(_EnemyData[ArrPos+i],2)[2])*8,0,8,8),NumbersBMP);
end;
end
else
begin
// Insert all drawing code here.
NumbersBMP.MasterAlpha := 170;
total := pIndex * 16;
count := 0;
for x := 0 to Enemies.Count -1 do
begin
if ((Enemies[x]._EnemyType = etCandle) or ((Enemies[x]._EnemyType = etCandleNoXEditing)))and (Enemies[x]._Type = pItemIndex) then
begin
if (count >= total - 16) then
begin
if self.Enemies[x].Y > $D8 then
begin
pBitmap.Draw(bounds(self.Enemies[x].X + ((i div 2) * 64)-8,$D0-$20,8,8),Bounds(StrToInt('$' + IntToHex(x,2)[1])*8,0,8,8),NumbersBMP);
pBitmap.Draw(bounds((self.Enemies[x].X + ((i div 2) * 64)-8) +8,$D0-$20,8,8),Bounds(StrToInt('$' + IntToHex(x,2)[2])*8,0,8,8),NumbersBMP);
end
else
begin
pBitmap.Draw(bounds(self.Enemies[x].X + ((i div 2) * 64)-8,self.Enemies[x].Y-$20,8,8),Bounds(StrToInt('$' + IntToHex(x,2)[1])*8,0,8,8),NumbersBMP);
pBitmap.Draw(bounds((self.Enemies[x].X + ((i div 2) * 64)-8) +8,self.Enemies[x].Y-$20,8,8),Bounds(StrToInt('$' + IntToHex(x,2)[2])*8,0,8,8),NumbersBMP);
end;
end;
inc(Count);
if Count = total then
break;
end;
end;
end;
end;
end;
finally
FreeAndNil(NumbersBMP);
end;
end;
end;
procedure TCVROM.DrawCandlestand(pBitmap: TBitmap32; pItemIndex,pIndex: Integer);
var
ArrPos, i,x, count, total : Integer;
NumbersBMP : TBitmap32;
begin
ArrPos := 2+ (self.Levels[self._level].screens[self._screen]._ScreenNumber*8);
// Draw the enemy
if FileExists(ExtractFileDir(Application.ExeName) + '\Data\numbers.bmp') = true then
begin
NumbersBMP := TBitmap32.Create;
try
NumbersBMP.Width := 136;
NumbersBMP.Height := 8;
NumbersBMP.LoadFromFile(ExtractFileDir(Application.ExeName) + '\Data\numbers.bmp');
NumbersBMP.DrawMode := dmBlend;
for i := 0 to 7 do
begin
if (i mod 2 = 1) and ((Enemies[_EnemyData[ArrPos+i]]._EnemyType = etCandleStand) or (Enemies[_EnemyData[ArrPos+i]]._EnemyType = etNone)) then
begin
if _EnemyData[ArrPos+i] > 0 then
begin
NumbersBMP.MasterAlpha := 255;
if Enemies[_EnemyData[ArrPos+i]].Y > $D8 then
begin
pBitmap.Draw(bounds(self.Enemies[self._EnemyData[ArrPos+i]].X + ((i div 2) * 64)-8,$D0-$20,8,8),Bounds(StrToInt('$' + IntToHex(_EnemyData[ArrPos+i],2)[1])*8,0,8,8),NumbersBMP);
pBitmap.Draw(bounds((self.Enemies[self._EnemyData[ArrPos+i]].X + ((i div 2) * 64)-8) +8,$D0-$20,8,8),Bounds(StrToInt('$' + IntToHex(_EnemyData[ArrPos+i],2)[2])*8,0,8,8),NumbersBMP);
end
else
begin
pBitmap.Draw(bounds(self.Enemies[self._EnemyData[ArrPos+i]].X + ((i div 2) * 64)-8,self.Enemies[self._EnemyData[ArrPos+i]].Y-$20,8,8),Bounds(StrToInt('$' + IntToHex(_EnemyData[ArrPos+i],2)[1])*8,0,8,8),NumbersBMP);
pBitmap.Draw(bounds((self.Enemies[self._EnemyData[ArrPos+i]].X + ((i div 2) * 64)-8) +8,self.Enemies[self._EnemyData[ArrPos+i]].Y-$20,8,8),Bounds(StrToInt('$' + IntToHex(_EnemyData[ArrPos+i],2)[2])*8,0,8,8),NumbersBMP);
end;
end
else if _EnemyData[ArrPos+i] = 0 then
begin
// Insert all drawing code here.
NumbersBMP.MasterAlpha := 200;
total := pIndex * 16;
count := 0;
for x := 0 to Enemies.Count -1 do
begin
if (Enemies[x]._EnemyType = etCandleStand)and (Enemies[x]._Type = pItemIndex) then
begin
if (count >= total - 16) then
begin
if self.Enemies[x].Y > $D8 then
begin
pBitmap.Draw(bounds(self.Enemies[x].X + ((i div 2) * 64)-8,$D0-$20,8,8),Bounds(StrToInt('$' + IntToHex(x,2)[1])*8,0,8,8),NumbersBMP);
pBitmap.Draw(bounds((self.Enemies[x].X + ((i div 2) * 64)-8) +8,$D0-$20,8,8),Bounds(StrToInt('$' + IntToHex(x,2)[2])*8,0,8,8),NumbersBMP);
end
else
begin
pBitmap.Draw(bounds(self.Enemies[x].X + ((i div 2) * 64)-8,self.Enemies[x].Y-$20,8,8),Bounds(StrToInt('$' + IntToHex(x,2)[1])*8,0,8,8),NumbersBMP);
pBitmap.Draw(bounds((self.Enemies[x].X + ((i div 2) * 64)-8) +8,self.Enemies[x].Y-$20,8,8),Bounds(StrToInt('$' + IntToHex(x,2)[2])*8,0,8,8),NumbersBMP);
end;
end;
inc(Count);
if Count = total then
break;
end;
end;
end;
end;
end;
finally
FreeAndNil(NumbersBMP);
end;
end;
end;
procedure TCVROM.DrawEnemies(pBitmap: TBitmap32; pItemIndex,pIndex: Integer);
var
ArrPos, i,x, count, total : Integer;
NumbersBMP : TBitmap32;
begin
ArrPos := 2+ (self.Levels[self._level].screens[self._screen]._ScreenNumber*8);
// Draw the enemy
if FileExists(ExtractFileDir(Application.ExeName) + '\Data\numbers.bmp') = true then
begin
NumbersBMP := TBitmap32.Create;
try
NumbersBMP.Width := 136;
NumbersBMP.Height := 8;
NumbersBMP.LoadFromFile(ExtractFileDir(Application.ExeName) + '\Data\numbers.bmp');
NumbersBMP.DrawMode := dmBlend;
NumbersBMP.MasterAlpha := 200;
for i := 0 to 7 do
begin
if i mod 2 = 0 then
begin
if _EnemyData[ArrPos+i] > 0 then
begin
NumbersBMP.MasterAlpha := 255;
if Enemies[_EnemyData[ArrPos+i]].Y > $D8 then
begin
pBitmap.Draw(bounds(self.Enemies[self._EnemyData[ArrPos+i]].X + ((i div 2) * 64)-8,$D0-$20,8,8),Bounds(StrToInt('$' + IntToHex(_EnemyData[ArrPos+i],2)[1])*8,0,8,8),NumbersBMP);
pBitmap.Draw(bounds((self.Enemies[self._EnemyData[ArrPos+i]].X + ((i div 2) * 64)-8) +8,$D0-$20,8,8),Bounds(StrToInt('$' + IntToHex(_EnemyData[ArrPos+i],2)[2])*8,0,8,8),NumbersBMP);
end
else
begin
pBitmap.Draw(bounds(self.Enemies[self._EnemyData[ArrPos+i]].X + ((i div 2) * 64)-8,self.Enemies[self._EnemyData[ArrPos+i]].Y-$20,8,8),Bounds(StrToInt('$' + IntToHex(_EnemyData[ArrPos+i],2)[1])*8,0,8,8),NumbersBMP);
pBitmap.Draw(bounds((self.Enemies[self._EnemyData[ArrPos+i]].X + ((i div 2) * 64)-8) +8,self.Enemies[self._EnemyData[ArrPos+i]].Y-$20,8,8),Bounds(StrToInt('$' + IntToHex(_EnemyData[ArrPos+i],2)[2])*8,0,8,8),NumbersBMP);
end;
end
else
begin
NumbersBMP.MasterAlpha := 170;
total := pIndex * 16;
count := 0;
for x := 0 to Enemies.Count -1 do
begin
if (Enemies[x]._EnemyType = etEnemy)and (Enemies[x]._Type = pItemIndex) then
begin
if (count >= total - 16) then
begin
if self.Enemies[x].Y > $D8 then
begin
pBitmap.Draw(bounds(self.Enemies[x].X + ((i div 2) * 64)-8,$D0-$20,8,8),Bounds(StrToInt('$' + IntToHex(x,2)[1])*8,0,8,8),NumbersBMP);
pBitmap.Draw(bounds((self.Enemies[x].X + ((i div 2) * 64)-8) +8,$D0-$20,8,8),Bounds(StrToInt('$' + IntToHex(x,2)[2])*8,0,8,8),NumbersBMP);
end
else
begin
pBitmap.Draw(bounds(self.Enemies[x].X + ((i div 2) * 64)-8,self.Enemies[x].Y-$20,8,8),Bounds(StrToInt('$' + IntToHex(x,2)[1])*8,0,8,8),NumbersBMP);
pBitmap.Draw(bounds((self.Enemies[x].X + ((i div 2) * 64)-8) +8,self.Enemies[x].Y-$20,8,8),Bounds(StrToInt('$' + IntToHex(x,2)[2])*8,0,8,8),NumbersBMP);
end;
end;
inc(Count);
if Count = total then
break;
end;
end;
end;
end;
end;
finally
FreeAndNil(NumbersBMP);
end;
end;
end;
function TCVROM.GetEnemyDataSize: Integer;
begin
result := length(_EnemyData);
end;
procedure TCVROM.ExportLevel(pFilename : String; pId: Integer;pAllow : Byte);
var
Mem : TMemoryStream;
TempString : String;
TempVar,TempVar2 : Integer;
TempByte : Byte;
i,x : Integer;
begin
Mem := TMemoryStream.Create;
try
// Write the header of the SPF file.
TempString := 'SPF1' + chr(0);
Mem.Write(TempString[1],4);
// Write the title of the SPF file.
TempString := self.Levels[pID]._Name + ' Exported Data';
TempVar :=Length(TempString);
Mem.Write(TempVar,1);
Mem.Write(TempString[1],TempVar);
// Write the description of the SPF file.
TempString := 'Exported By Stake v1.1';
TempVar := Length(TempString);
Mem.Write(TempVar,1);
Mem.Write(TempString[1],TempVar);
// Write the MAIN part.
TempString := 'MAIN';
Mem.Write(TempString[1],4);
if pAllow AND EXPORTGRAPHICS = EXPORTGRAPHICS then
begin
// Begin writing the graphics
Mem.Write(Levels[pID]._GFXOffset,4);
TempVar := 2304;
Mem.Write(TempVar,2);
// Mem.Write(ROM[Levels[pID]._GFXOffset],TempVar);
for i :=0 to 2303 do
begin
TempVar2 := ROM[Levels[pID]._GFXOffset + i];
Mem.Write(TempVar2,1);
end;
end;
if pAllow AND EXPORTTSA = EXPORTTSA then
begin
// Begin writing the TSA data
TempVar := Levels[pid].NumberOfLevelTiles * 17;
Mem.Write(Levels[pID]._TSAOffset,4);
Mem.Write(TempVar,2);
for i := 0 to TempVar - 1 do
begin
TempVar2 := ROM[Levels[pID].TSAOffset + i];
Mem.Write(TempVar2,1);
end;
end;
if pAllow AND EXPORTLEVELS = EXPORTLEVELS then
begin
// Begin writing the screen data
for x := 0 to Levels[pID].Screens.Count -1 do
begin
Mem.Write(Levels[pID].Screens[x]._Offset,4);
TempVar := 48;
Mem.Write(TempVar,2);
for i := 0 to 47 do
begin
TempVar2 := ROM[Levels[pID].Screens[x]._Offset + i];
Mem.Write(TempVar2,1);
end;
end;
end;
if pAllow AND EXPORTPALETTE = EXPORTPALETTE then
begin
// Write the palette
Mem.Write(Levels[pID]._BGPalOffset,4);
TempVar := 16;
Mem.Write(TempVar,2);
for i := 0 to 15 do
begin
TempVar2 := ROM[Levels[pID]._BGPalOffset + i];
Mem.Write(TempVar2,1);
end;
end;
if pAllow AND EXPORTENEMYDATA = EXPORTENEMYDATA then
begin
// Write the enemy data
for x := 0 to Levels[pID]._NumberOfEnemySets - 1 do
begin
// Write the enemy data pointer.
Mem.Write(Levels[pID]._EnemyOffsets[x].PointerOffset,4);
TempVar := 2;
Mem.Write(TempVar,2);
TempByte := ROM[Levels[pID]._EnemyOffsets[x].PointerOffset];
Mem.Write(TempByte,1);
TempByte := ROM[Levels[pID]._EnemyOffsets[x].PointerOffset + 1];
Mem.Write(TempByte,1);
TempVar := ROM.PointerToOffset(Levels[pID]._EnemyOffsets[x].PointerOffset,0,$C000);
Mem.Write(TempVar,4);
Mem.Write(Levels[pID]._EnemyOffsets[x].Count,2);
for i := 0 to Levels[pID]._EnemyOffsets[x].Count - 1 do
begin
TempVar2 := ROM[TempVar+i];
Mem.Write(TempVar2,1);
end;
end;
end;
// Write the EOF
TempString := 'EOF';
Mem.Write(TempString[1],3);
Mem.SaveToFile(pFilename);
finally
FreeAndNil(Mem);
end;
end;
procedure TCVROM.ImportLevel(pFilename: String);
var
PatchFile : TPatch;
begin
if FileExists(pFilename) = True then
begin
PatchFile := TPatch.Create(pFilename);
try
PatchFile.Execute;
LoadCurrentPalette();
LoadPatternTable();
LoadScreenData();
LoadEnemyData();
finally
FreeAndNil(PatchFile);
end;
end;
end;
procedure TCVROM.LoadSpikeCrushersData;
var
i : Integer;
TempSpike : TSpikeCrusher;
begin
if Levels[Levels.CurrentLevel]._NumberOfSpikeCrushers > 0 then
begin
if Assigned(Levels[Levels.CurrentLevel].SpikeCrushers) = True then
FreeAndNil(Levels[self._Level].SpikeCrushers);
Levels[Levels.CurrentLevel].SpikeCrushers := TSpikeCrusherList.Create(True);
for i := 0 to Levels[Levels.CurrentLevel]._NumberOfSpikeCrushers -1 do
begin
Levels[self._Level].SpikeCrushers.Add(TSpikeCrusher.Create);
TempSpike := Levels[Levels.CurrentLevel].SpikeCrushers.Last;
TempSpike.InitialDirection := ROM[Levels[Levels.CurrentLevel]._SpikeCrusherOffset + i];
TempSpike.Y := ROM[Levels[Levels.CurrentLevel]._SpikeCrusherOffset + i + (1*Levels[Levels.CurrentLevel]._NumberOfSpikeCrushers)] - $20;
TempSpike.X := ROM[Levels[Levels.CurrentLevel]._SpikeCrusherOffset + i + (2*Levels[Levels.CurrentLevel]._NumberOfSpikeCrushers)];
TempSpike.Screen := ROM[Levels[Levels.CurrentLevel]._SpikeCrusherOffset + i + (3*Levels[Levels.CurrentLevel]._NumberOfSpikeCrushers)];
TempSpike.Desc1 := ROM[Levels[Levels.CurrentLevel]._SpikeCrusherOffset + i + (4*Levels[Levels.CurrentLevel]._NumberOfSpikeCrushers)] and $F0;
TempSpike.Desc2 := ROM[Levels[Levels.CurrentLevel]._SpikeCrusherOffset + i + (4*Levels[Levels.CurrentLevel]._NumberOfSpikeCrushers)] and $0F;
end;
end;
end;
procedure TCVROM.SaveSpikeCrushersData;
var
i : Integer;
TempSpike : TSpikeCrusher;
begin
if (Levels[Levels.CurrentLevel]._NumberOfSpikeCrushers > 0) and (Assigned(Levels[Levels.CurrentLevel].SpikeCrushers) = True) then
begin
for i := 0 to Levels[Levels.CurrentLevel]._NumberOfSpikeCrushers -1 do
begin
TempSpike := Levels[Levels.CurrentLevel].SpikeCrushers[i];
ROM[Levels[Levels.CurrentLevel]._SpikeCrusherOffset + i] := TempSpike.InitialDirection;
ROM[Levels[Levels.CurrentLevel]._SpikeCrusherOffset + i + (1*Levels[Levels.CurrentLevel]._NumberOfSpikeCrushers)] := TempSpike.Y + $20;
ROM[Levels[Levels.CurrentLevel]._SpikeCrusherOffset + i + (2*Levels[Levels.CurrentLevel]._NumberOfSpikeCrushers)] := TempSpike.X;
ROM[Levels[Levels.CurrentLevel]._SpikeCrusherOffset + i + (3*Levels[Levels.CurrentLevel]._NumberOfSpikeCrushers)] := TempSpike.Screen;
ROM[Levels[Levels.CurrentLevel]._SpikeCrusherOffset + i + (4*Levels[Levels.CurrentLevel]._NumberOfSpikeCrushers)] := (TempSpike.Desc1 and $F0) + (TempSpike.Desc2 and $0F);
end;
end;
end;
function TCVROM.GetSpikeCrusherUnderMouse(pX, pY: Integer): Integer;
var
TempScreen : TCVScreen;
i : Integer;
Spike : TSpikeCrusher;
begin
TempScreen := Levels[Levels.CurrentLevel].Screens[self._Screen];
result := -1;
if self.Levels[levels.CurrentLevel]._NumberOfSpikeCrushers > 0 then
begin
for i := 0 to Levels[Levels.CurrentLevel].SpikeCrushers.Count - 1 do
begin
Spike := Levels[Levels.CurrentLevel].SpikeCrushers[i];
if (TempScreen.StageNumber = Levels[levels.CurrentLevel]._SpikeCrusherStage) and (Spike.Screen = TempScreen.ScreenNumber) then
begin
if TempScreen.MultiAreaBit = False Then
begin
if ((pX >= Spike.X) and (pX <= Spike.X + 16)) and ((pY >= Spike.Y) and (pY <= Spike.Y + 16)) then
begin
result := i;
exit;
end
end
end;
end;
end;
end;
function TCVROM.GetSpikeCrusherXY(pStairID: Integer; pXY: Byte): Integer;
begin
if pXY = 0 then
result := Levels[Levels.CurrentLevel].SpikeCrushers[pStairID].X
else
result := Levels[Levels.CurrentLevel].SpikeCrushers[pStairID].Y;
end;
procedure TCVROM.SetSpikeCrusherXY(pStairID, pX, pY: Integer);
begin
if pStairID = -1 then exit;
if pX > -1 then
begin
if pX > 240 then
Levels[Levels.CurrentLevel].SpikeCrushers[pStairID].X := 240
else
Levels[Levels.CurrentLevel].SpikeCrushers[pStairID].X := pX;;
end;
if pY > -1 then
begin
if pY > 176 then
Levels[Levels.CurrentLevel].SpikeCrushers[pStairID].Y := 176
else
Levels[Levels.CurrentLevel].SpikeCrushers[pStairID].Y := pY;
end;
ROM.Changed := True;
end;
procedure TCVROM.LoadFloatingPlatformData;
var
i : Integer;
begin
if Assigned(Levels[Levels.CurrentLevel].FloatingPlatforms) = True then
begin
for i := 0 to Levels[Levels.CurrentLevel].FloatingPlatforms.Count -1 do
begin
Levels[Levels.CurrentLevel].FloatingPlatforms[i].UnknownByte1 := ROM[Levels[Levels.CurrentLevel].FloatingPlatforms[i].Offset];
Levels[Levels.CurrentLevel].FloatingPlatforms[i].DistanceSpeed := ROM[Levels[Levels.CurrentLevel].FloatingPlatforms[i].Offset + 1];
Levels[Levels.CurrentLevel].FloatingPlatforms[i].UnknownByte2 := ROM[Levels[Levels.CurrentLevel].FloatingPlatforms[i].Offset + 2];
Levels[Levels.CurrentLevel].FloatingPlatforms[i].NumPixels := ROM[Levels[Levels.CurrentLevel].FloatingPlatforms[i].Offset + 3];
Levels[Levels.CurrentLevel].FloatingPlatforms[i].X := ROM[Levels[Levels.CurrentLevel].FloatingPlatforms[i].Offset + 4];
Levels[Levels.CurrentLevel].FloatingPlatforms[i].Screen := ROM[Levels[Levels.CurrentLevel].FloatingPlatforms[i].Offset + 5];
Levels[Levels.CurrentLevel].FloatingPlatforms[i].Y := (ROM[Levels[Levels.CurrentLevel].FloatingPlatforms[i].Offset + 6] and $FE) - $20;
Levels[Levels.CurrentLevel].FloatingPlatforms[i].MultiAreaBitRaw := ROM[Levels[Levels.CurrentLevel].FloatingPlatforms[i].Offset + 6] and 1;
Levels[Levels.CurrentLevel].FloatingPlatforms[i].Speed := ROM[Levels[Levels.CurrentLevel].FloatingPlatforms[i].Offset + 7];
end;
end;
end;
procedure TCVROM.SaveFloatingPlatformData;
var
i : Integer;
TempFloat : TFloatingPlatform;
begin
if Assigned(Levels[Levels.CurrentLevel].FloatingPlatforms) = True then
begin
for i := 0 to Levels[Levels.CurrentLevel].FloatingPlatforms.Count -1 do
begin
TempFloat := Levels[Levels.CurrentLevel].FloatingPlatforms[i];
ROM[TempFloat.Offset] := TempFloat.UnknownByte1;
ROM[TempFloat.Offset + 1] := TempFloat.DistanceSpeed;
ROM[TempFloat.Offset + 2] := TempFloat.UnknownByte2;
ROM[TempFloat.Offset + 3] := TempFloat.NumPixels;
ROM[TempFloat.Offset + 4] := TempFloat.X;
ROM[TempFloat.Offset + 5] := TempFloat.Screen;
ROM[TempFloat.Offset + 6] := ((TempFloat.Y + $20) and $FE) + (TempFloat.MultiAreaBitRaw and $1);
ROM[TempFloat.Offset + 7] := TempFloat.Speed;
end;
end;
end;
function TCVROM.GetFloatingPlatformUnderMouse(pX, pY: Integer): Integer;
var
TempScreen : TCVScreen;
i : Integer;
Floaty : TFloatingPlatform;
begin
TempScreen := Levels[Levels.CurrentLevel].Screens[self._Screen];
result := -1;
if Assigned(self.Levels[Levels.CurrentLevel].FloatingPlatforms) = True then
begin
for i := 0 to Levels[Levels.CurrentLevel].FloatingPlatforms.Count - 1 do
begin
Floaty := Levels[Levels.CurrentLevel].FloatingPlatforms[i];
if (Floaty.Stage = TempScreen.StageNumber) and (Floaty.Screen = TempScreen.ScreenNumber) then
begin
if TempScreen.MultiAreaBit = Floaty.MultiAreaBit then
begin
if ((pX >= Floaty.X) and (pX <= Floaty.X + 32)) and ((pY >= Floaty.Y) and (pY <= Floaty.Y + 16)) then
begin
result := i;
exit;
end
end;
end;
end;
end;
end;
function TCVROM.GetFloatingPlatformXY(pStairID: Integer;
pXY: Byte): Integer;
begin
if pXY = 0 then
result := Levels[Levels.CurrentLevel].FloatingPlatforms[pStairID].X
else
result := Levels[Levels.CurrentLevel].FloatingPlatforms[pStairID].Y;
end;
procedure TCVROM.SetFloatingPlatformXY(pPlatID, pX, pY: Integer);
begin
if pPlatID = -1 then exit;
if pX > -1 then
begin
if pX > 224 then
Levels[Levels.CurrentLevel].FloatingPlatforms[pPlatID].X := 224
else
Levels[Levels.CurrentLevel].FloatingPlatforms[pPlatID].X := pX;
end;
if pY > -1 then
begin
if pY > 176 then
Levels[Levels.CurrentLevel].FloatingPlatforms[pPlatID].Y := 176
else
Levels[Levels.CurrentLevel].FloatingPlatforms[pPlatID].Y := pY;
end;
ROM.Changed := True;
end;
procedure TCVROM.GetScreenFloatingPlatform(pStringList: TStringList;
pFloatID: Integer);
var
TempScreen : TCVScreen;
TempFloat : TFloatingPlatform;
i : Integer;
begin
TempFloat := Levels[Levels.CurrentLevel].FloatingPlatforms[pFloatID];
for i := 0 to Levels[Levels.CurrentLevel].Screens.Count - 1 do
begin
TempScreen := Levels[Levels.CurrentLevel].Screens[i];
if TempScreen.StageNumber = TempFloat.Stage then
pStringList.Add(IntToHex(TempScreen.ID,2));
end;
end;
destructor TCVROM.Destroy;
begin
FreeAndNil(self._Tiles);
FreeAndNil(Levels);
FreeAndNil(SoundEffects);
FreeAndNil(TitleScreen);
FreeAndNil(CastleIntro);
FreeAndNil(IntroExpansion);
FreeAndNil(Statistics);
FreeAndNil(MusicPointers);
FreeAndNil(MusicPointersTemplate);
FreeAndNil(Damage);
FreeAndNil(Enemies);
FreeAndNil(ending);
FreeAndNil(ROM);
inherited;
end;
procedure TCVROM.LoadNonDoors;
var
i : Integer;
begin
if Assigned(Levels[self._Level].NonStandardDoors) = True then
begin
for i := 0 to Levels[self._Level].NonStandardDoors.Count -1 do
begin
Levels[self._Level].NonStandardDoors[i].Y := ROM[Levels[self._Level].NonStandardDoors[i].Offset] - $20;
Levels[self._Level].NonStandardDoors[i].X := ROM[Levels[self._Level].NonStandardDoors[i].Offset+1] - $8;
Levels[self._Level].NonStandardDoors[i].ScreenNumber := ROM[Levels[self._Level].NonStandardDoors[i].Offset+2];
Levels[self._level].NonStandardDoors[i].WalkToX := ROM[Levels[self._Level].NonStandardDoors[i].WalkToXOffset];
end;
end;
end;
procedure TCVROM.SaveNonDoors;
var
i : Integer;
begin
if Assigned(Levels[self._Level].NonStandardDoors) = True then
begin
for i := 0 to Levels[self._Level].NonStandardDoors.Count -1 do
begin
ROM[Levels[self._Level].NonStandardDoors[i].Offset] := Levels[self._Level].NonStandardDoors[i].Y + $20;
ROM[Levels[self._Level].NonStandardDoors[i].Offset+1] := Levels[self._Level].NonStandardDoors[i].X + $8;
ROM[Levels[self._Level].NonStandardDoors[i].Offset+2] := Levels[self._Level].NonStandardDoors[i].ScreenNumber;
ROM[Levels[self._Level].NonStandardDoors[i].WalkToXOffset] := Levels[self._level].NonStandardDoors[i].WalkToX;
end;
end;
end;
function TCVROM.GetNonDoorUnderMouse(pX, pY: Integer): Integer;
var
NonDoor : TNonStandardDoor;
TempScreen : TCVScreen;
i : Integer;
begin
TempScreen := Levels[Levels.CurrentLevel].Screens[self._Screen];
result := -1;
if Assigned(Levels[_Level].NonStandardDoors) = True then
begin
if Levels[_Level].NonStandardDoors.Count > 0 then
begin
for i := 0 to Levels[_Level].NonStandardDoors.Count - 1 do
begin
NonDoor := Levels[_Level].NonStandardDoors[i];
if (NonDoor.Stage = TempScreen.StageNumber) then
begin
if NonDoor.ScreenNumber = TempScreen.ScreenNumber then
begin
if (pX >= NonDoor.X) and (pX <= NonDoor.X + 16) then
begin
if (pY >= NonDoor.Y) and (pY <= NonDoor.Y + 16) then
begin
result := i;
exit;
end;
end;
end;
end;
end;
end;
end;
end;
function TCVROM.GetNonDoorXY(pXY, pDoorID: Integer): Integer;
begin
if pXY = 0 then
result := Levels[Levels.CurrentLevel].NonStandardDoors[pDoorID].X
else
result := Levels[Levels.CurrentLevel].NonStandardDoors[pDoorID].Y;
end;
procedure TCVROM.SetNonDoorXY(pDoorID, pX, pY: Integer);
begin
if pX > -1 then
begin
if pX > 240 then
Levels[Levels.CurrentLevel].NonStandardDoors[pDoorID].X := 240
else
Levels[Levels.CurrentLevel].NonStandardDoors[pDoorID].X := pX;
end;
if pY > -1 then
begin
if pY > 176 then
Levels[Levels.CurrentLevel].NonStandardDoors[pDoorID].Y := 176
else
Levels[Levels.CurrentLevel].NonStandardDoors[pDoorID].Y := pY;
end;
end;
function TCVROM.GetPalVal(index1, index2: Integer): Byte;
begin
result := _palette[index1,index2];
end;
procedure TCVROM.SetPalVal(index1, index2: Integer; const Value: Byte);
begin
_palette[index1,index2] := Value;
end;
function TCVROM.GetMapVal(index1, index2: Integer): Byte;
begin
result := _Map[index1,index2];
end;
procedure TCVROM.SetMapVal(index1, index2: Integer; const Value: Byte);
begin
_Map[index1,index2] := Value;
end;
function TCVROM.GetScreenData(index1, index2: Integer): Byte;
begin
result := 0;
if (index1 <= 7) and (index2 <= 5) then
begin
result := _ScreenData[index1,index2];
end;
end;
procedure TCVROM.SetChanged(pChanged : Boolean);
begin
ROM.Changed := pChanged;
end;
procedure TCVROM.SetScreenData(index1, index2: Integer; const Value: Byte);
begin
// Check if the pX/pY aren't greater than the
// size of the array.
// Also check that the block number that is being
// passed is within the number of tiles limit for the level.
if (index1 <= 7) and (index2 <= 5) and (Value <= NumberOfTiles) then
begin
_ScreenData[index1,index2] := Value;
end;
ROM.Changed := True;
end;
function TCVROM.CHRCount: Byte;
begin
result := ROM.CHRCount;
end;
function TCVROM.FileSize: Integer;
begin
result := ROM.ROMSize;
end;
function TCVROM.MemoryMapper: Byte;
begin
result := ROM.MapperNumber;
end;
function TCVROM.MemoryMapperStr: String;
begin
result := ROM.MapperName;
end;
function TCVROM.PRGCount: Byte;
begin
result := ROM.PRGCount;
end;
procedure TCVROM.LoadHiddenItemsData;
var
TempLevel : TLevel;
i,x,z : Integer;
HiddenItem : THiddenItem;
begin
for i := 0 to _NumberOfLevels - 1 do
begin
TempLevel := Levels[i];
if assigned(TempLevel.HiddenItems) = false then
TempLevel.HiddenItems := THiddenItemList.Create(True)
else
exit;
for x := 0 to TempLevel._NumberOfStages -1 do
begin
z := ROM.PointerToOffset(TempLevel._HiddenItemPointers[x],$18010);
// Now we load in all the breakable blocks.
while (ROM[z] <> $FF) do
begin
TempLevel.HiddenItems.Add(THiddenItem.Create);
HiddenItem := TempLevel.HiddenItems.Last;
HiddenItem.StageNumber := x;
HiddenItem.Y := (ROM[z] and $F0) - $10;
HiddenItem.MultiAreaBitRaw := ROM[z] and $8;
HiddenItem.UnknownBit1 := ROM[z] and $7;
// False if he needs to crouch ^_^
HiddenItem.SimonMustCrouchRaw := ROM[z] and $1;
HiddenItem.ScreenNumber := ROM[z +1] and $7;
HiddenItem.X := ROM[z+1] and $F8;
HiddenItem.ItemType := ROM[z+3];
z := z + 4;
end;
end;
end;
end;
procedure TCVROM.SaveHiddenItemsData;
begin
end;
function TCVROM.GetNumberOfHiddenItems: Integer;
var
TempScreen : TCVScreen;
count, i : Integer;
begin
TempScreen := Levels[Levels.CurrentLevel].Screens[self._Screen];
count := 0;
if assigned(Levels[Levels.CurrentLevel].HiddenItems) = false then
begin
result := count;
exit;
end;
if (Levels[Levels.CurrentLevel].HiddenItems.Count = 0) then
begin
result := count;
exit;
end;
for i := 0 to Levels[Levels.CurrentLevel].HiddenItems.Count - 1 do
if Levels[Levels.CurrentLevel].HiddenItems[i].StageNumber = TempScreen._StageNumber then
inc(count);
result := count;
end;
{ TLevel }
destructor TLevel.Destroy;
begin
FreeAndNil(self.SpikeCrushers);
FreeAndNil(self.Stairs);
FreeAndNil(self.Entrances);
FreeAndNil(self.Doors);
FreeAndNil(self.BreakableBlocks);
FreeAndNil(self.Screens);
FreeAndNil(self.FloatingPlatforms);
FreeAndNil(self.NonStandardDoors);
FreeAndNil(HiddenItems);
inherited;
end;
function TLevel.GetBossVal(Index: Integer): Byte;
begin
result := ROM[self._BossOffsets[Index]];
end;
function TLevel.GetEnemyDataOffset(pScreenID : Integer): Integer;
begin
result := ROM.PointerToOffset(self._EnemyOffsets[self.Screens[pScreenID].EnemyList].PointerOffset,0,$C000);
end;
function TLevel.GetEnemyDataPointer(pScreenID : Integer): String;
var
TempStr : String;
begin
TempStr := IntToHex(ROM[self._EnemyOffsets[self.Screens[pScreenID].EnemyList].PointerOffset+1],2);
TempStr := TempStr + IntToHex(ROM[self._EnemyOffsets[self.Screens[pScreenID].EnemyList].PointerOffset],2);
result := TempStr;
end;
function TLevel.GetEnemyDataPointerOffset(pScreenID : Integer): Integer;
begin
result := self._EnemyOffsets[self.Screens[pScreenID].EnemyList].PointerOffset;
end;
function TLevel.GetTimeVal(Index: Integer): Byte;
begin
result := ROM[self._TimeOffsets[Index]];
end;
procedure TLevel.SetBossVal(Index: Integer; const Value: Byte);
begin
ROM[self._BossOffsets[Index]] := Value;
end;
procedure TLevel.SetTimeVal(Index: Integer; const Value: Byte);
begin
ROM[self._TimeOffsets[Index]] := Value;
end;
{ TEnemy }
constructor TEnemy.Create(pPointerOffset: Integer);
begin
self._Offset := ROM.PointerToOffset(pPointerOffset,0,$C000);
// Now we work out where the pointer leads to.
if ROM[self._Offset] = 0 then
self.EnemyType := etNone
else
begin
if ROM[self._Offset] = $FF then
begin
_Type := ROM[self._Offset+1];
if ROM[self._Offset+2] = $FE then
begin
self.EnemyType := etCandleStand;
self.X := ROM[self._Offset+3];
self.Y := ROM[self._Offset+4];
end
else
begin
self.EnemyType := etCandle;
self.X := ROM[self._Offset+2];
self.Y := ROM[self._Offset+3];
end;
end
else if ROM[self._Offset] = $FE then
begin
self.EnemyType := etCandleStand;
self.X := ROM[self._Offset+1];
self.Y := ROM[self._Offset+2];
end
else if ROM[self._Offset] and $20 = $20 then
begin
self.EnemyType := etCandleNoXEditing;
self.X := ROM[self._Offset];
self.Y := ROM[self._Offset+1];
end
else
begin
self._EnemyType := etEnemy;
self.EnemyItem := ROM[self._Offset];
self.X := ROM[self._Offset+1];
self.Y := ROM[self._Offset+2];
end;
end;
end;
{ TEnemyList }
function TEnemyList.Add(AObject: TEnemy): Integer;
begin
Result := inherited Add(AObject);
end;
function TEnemyList.GetEnemyItem(Index: Integer): TEnemy;
begin
Result := TEnemy(inherited Items[Index]);
end;
function TEnemyList.Last: TEnemy;
begin
Result := TEnemy(inherited Last);
end;
function TEnemyList.NumberOfCandles: Integer;
var
i : Integer;
countvar : Integer;
begin
countvar := 0;
for i := 0 to self.Count - 1 do
begin
if (self.Items[i]._EnemyType = etCandle) or (self.Items[i]._EnemyType = etCandleNoXEditing) then
begin
inc(countvar);
end;
end;
result := countvar;
end;
function TEnemyList.NumberOfCandlesFilter(pIndex: Integer): Integer;
var
i : Integer;
countvar : Integer;
begin
countvar := 0;
for i := 0 to self.Count - 1 do
begin
if (self.Items[i]._EnemyType = etCandle) or (self.Items[i]._EnemyType = etCandleNoXEditing) then
begin
if self.Items[i].EnemyItem = pIndex then
inc(countvar);
end;
end;
result := countvar;
end;
function TEnemyList.NumberOfCandleStands: Integer;
var
i : Integer;
countvar : Integer;
begin
countvar := 0;
for i := 0 to self.Count - 1 do
begin
if (self.Items[i]._EnemyType = etCandlestand) then
begin
inc(countvar);
end;
end;
result := countvar;
end;
function TEnemyList.NumberOfCandleStandsFilter(pIndex: Integer): Integer;
var
i : Integer;
countvar : Integer;
begin
countvar := 0;
for i := 0 to self.Count - 1 do
begin
if (self.Items[i]._EnemyType = etCandlestand) then
begin
if self.Items[i].EnemyItem = pIndex then
inc(countvar);
end;
end;
result := countvar;
end;
function TEnemyList.NumberOfEnemies: integer;
var
i : Integer;
countvar : Integer;
begin
countvar := 0;
for i := 0 to self.Count - 1 do
begin
if (self.Items[i]._EnemyType = etEnemy) then
begin
inc(countvar);
end;
end;
result := countvar;
end;
function TEnemyList.NumberOfEnemiesFilter(pIndex: Integer): integer;
var
i : Integer;
countvar : Integer;
begin
countvar := 0;
for i := 0 to self.Count - 1 do
begin
if (self.Items[i]._EnemyType = etEnemy) then
begin
if self.Items[i].EnemyItem = pIndex then
inc(countvar);
end;
end;
result := countvar;
end;
procedure TEnemyList.SetEnemyItem(Index: Integer; const Value: TEnemy);
begin
inherited Items[Index] := Value;
end;
{ TLevelList }
function TLevelList.Add(AObject: TLevel): Integer;
begin
Result := inherited Add(AObject);
end;
function TLevelList.GetCurrentLevel: Integer;
begin
result := self._CurrentLevel;
end;
function TLevelList.GetLevelItem(Index: Integer): TLevel;
begin
Result := TLevel(inherited Items[Index]);
end;
procedure TLevelList.SetCurrentLevel(const Value: Integer);
begin
self._CurrentLevel := Value;
end;
procedure TLevelList.SetLevelItem(Index: Integer; const Value: TLevel);
begin
inherited Items[Index] := Value;
end;
{ TScreenList }
function TScreenList.Add(AObject: TCVScreen): Integer;
begin
Result := inherited Add(AObject);
end;
function TScreenList.GetScreenItem(Index: Integer): TCVScreen;
begin
Result := TCVScreen(inherited Items[Index]);
end;
function TScreenList.Last: TCVScreen;
begin
Result := TCVScreen(inherited Last);
end;
procedure TScreenList.SetScreenItem(Index: Integer; const Value: TCVScreen);
begin
inherited Items[Index] := Value;
end;
end.
| 32.235952 | 233 | 0.673734 |
4734442ba82ad775a3be65e8eafb9cb06ba738bb | 7,339 | pas | Pascal | JCL/JclIniFiles.pas | tmcdos/VCL-explorer | 60e3774c4bfd14c833d79eb67051b6d52069d6c7 | [
"MIT"
]
| 13 | 2016-07-09T15:07:10.000Z | 2021-05-20T13:03:38.000Z | JCL/JclIniFiles.pas | tmcdos/VCL-explorer | 60e3774c4bfd14c833d79eb67051b6d52069d6c7 | [
"MIT"
]
| null | null | null | JCL/JclIniFiles.pas | tmcdos/VCL-explorer | 60e3774c4bfd14c833d79eb67051b6d52069d6c7 | [
"MIT"
]
| 11 | 2016-07-10T07:53:28.000Z | 2019-04-08T14:21:38.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 JclIniFiles.pas. }
{ }
{ The Initial Developer of the Original Code is John C Molyneux. }
{ Portions created by John C Molyneux are Copyright (C) John C Molyneux. }
{ }
{ Contributors: }
{ Eric S. Fisher }
{ John C Molyneux }
{ Petr Vones (pvones) }
{ Robert Marquardt (marquardt) }
{ Robert Rossmair (rrossmair) }
{ }
{**************************************************************************************************}
{ }
{ Last modified: $Date:: 2007-09-17 23:41:02 +0200 (lun., 17 sept. 2007) $ }
{ Revision: $Rev:: 2175 $ }
{ Author: $Author:: outchy $ }
{ }
{**************************************************************************************************}
unit JclIniFiles;
{$I jcl.inc}
interface
uses
{$IFDEF UNITVERSIONING}
JclUnitVersioning,
{$ENDIF UNITVERSIONING}
SysUtils, Classes, IniFiles;
// Initialization (ini) Files
function IniReadBool(const FileName, Section, Line: string): Boolean; // John C Molyneux
function IniReadInteger(const FileName, Section, Line: string): Integer; // John C Molyneux
function IniReadString(const FileName, Section, Line: string): string; // John C Molyneux
procedure IniWriteBool(const FileName, Section, Line: string; Value: Boolean); // John C Molyneux
procedure IniWriteInteger(const FileName, Section, Line: string; Value: Integer); // John C Molyneux
procedure IniWriteString(const FileName, Section, Line, Value: string); // John C Molyneux
// Initialization (ini) Files helper routines
procedure IniReadStrings(IniFile: TCustomIniFile; const Section: string; Strings: TStrings);
procedure IniWriteStrings(IniFile: TCustomIniFile; const Section: string; Strings: TStrings);
{$IFDEF UNITVERSIONING}
const
UnitVersioning: TUnitVersionInfo = (
RCSfile: '$URL: https://jcl.svn.sourceforge.net/svnroot/jcl/tags/JCL-1.102-Build3072/jcl/source/common/JclIniFiles.pas $';
Revision: '$Revision: 2175 $';
Date: '$Date: 2007-09-17 23:41:02 +0200 (lun., 17 sept. 2007) $';
LogPath: 'JCL\source\common'
);
{$ENDIF UNITVERSIONING}
implementation
{$IFDEF CLR}
type
TIniFile = TMemIniFile;
{$ENDIF CLR}
// Initialization Files
function IniReadBool(const FileName, Section, Line: string): Boolean;
var
Ini: TIniFile;
begin
Ini := TIniFile.Create(FileName);
try
Result := Ini.ReadBool(Section, Line, False);
finally
Ini.Free;
end;
end;
function IniReadInteger(const FileName, Section, Line: string): Integer;
var
Ini: TIniFile;
begin
Ini := TIniFile.Create(FileName);
try
Result := Ini.ReadInteger(Section, Line, 0);
finally
Ini.Free;
end;
end;
function IniReadString(const FileName, Section, Line: string): string;
var
Ini: TIniFile;
begin
Ini := TIniFile.Create(FileName);
try
Result := Ini.ReadString(Section, Line, '');
finally
Ini.Free;
end;
end;
procedure IniWriteBool(const FileName, Section, Line: string; Value: Boolean);
var
Ini: TIniFile;
begin
Ini := TIniFile.Create(FileName);
try
Ini.WriteBool(Section, Line, Value);
{$IFDEF CLR}
Ini.UpdateFile;
{$ENDIF CLR}
finally
Ini.Free;
end;
end;
procedure IniWriteInteger(const FileName, Section, Line: string; Value: Integer);
var
Ini: TIniFile;
begin
Ini := TIniFile.Create(FileName);
try
Ini.WriteInteger(Section, Line, Value);
{$IFDEF CLR}
Ini.UpdateFile;
{$ENDIF CLR}
finally
Ini.Free;
end;
end;
procedure IniWriteString(const FileName, Section, Line, Value: string);
var
Ini: TIniFile;
begin
Ini := TIniFile.Create(FileName);
try
Ini.WriteString(Section, Line, Value);
{$IFDEF CLR}
Ini.UpdateFile;
{$ENDIF CLR}
finally
Ini.Free;
end;
end;
// Initialization (ini) Files helper routines
const
ItemCountName = 'Count';
procedure IniReadStrings(IniFile: TCustomIniFile; const Section: string; Strings: TStrings);
var
Count, I: Integer;
begin
with IniFile do
begin
Strings.BeginUpdate;
try
Strings.Clear;
Count := ReadInteger(Section, ItemCountName, 0);
for I := 0 to Count - 1 do
Strings.Add(ReadString(Section, IntToStr(I), ''));
finally
Strings.EndUpdate;
end;
end;
end;
procedure IniWriteStrings(IniFile: TCustomIniFile; const Section: string; Strings: TStrings);
var
I: Integer;
begin
with IniFile do
begin
EraseSection(Section);
WriteInteger(Section, ItemCountName, Strings.Count);
for I := 0 to Strings.Count - 1 do
WriteString(Section, IntToStr(I), Strings[I]);
end;
end;
{$IFDEF UNITVERSIONING}
initialization
RegisterUnitVersion(HInstance, UnitVersioning);
finalization
UnregisterUnitVersion(HInstance);
{$ENDIF UNITVERSIONING}
end.
| 36.695 | 127 | 0.480174 |
83a9a4dc921a5a859a8108e3feb76d75ba8a792d | 2,576 | pas | Pascal | src/libraries/cryptolib4pascal/ClpISigner.pas | rabarbers/PascalCoin | 7a87031bc10a3e1d9461dfed3c61036047ce4fb0 | [
"MIT"
]
| 384 | 2016-07-16T10:07:28.000Z | 2021-12-29T11:22:56.000Z | src/libraries/cryptolib4pascal/ClpISigner.pas | rabarbers/PascalCoin | 7a87031bc10a3e1d9461dfed3c61036047ce4fb0 | [
"MIT"
]
| 165 | 2016-09-11T11:06:04.000Z | 2021-12-05T23:31:55.000Z | src/libraries/cryptolib4pascal/ClpISigner.pas | rabarbers/PascalCoin | 7a87031bc10a3e1d9461dfed3c61036047ce4fb0 | [
"MIT"
]
| 210 | 2016-08-26T14:49:47.000Z | 2022-02-22T18:06:33.000Z | { *********************************************************************************** }
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit ClpISigner;
{$I CryptoLib.inc}
interface
uses
ClpICipherParameters,
ClpCryptoLibTypes;
type
ISigner = interface(IInterface)
['{8D9ACCFE-AB70-4983-AE4C-A61F935C7DD5}']
// /**
// * Return the name of the algorithm the signer implements.
// *
// * @return the name of the algorithm the signer implements.
// */
function GetAlgorithmName: String;
property AlgorithmName: String read GetAlgorithmName;
// /**
// * Initialise the signer for signing or verification.
// *
// * @param forSigning true if for signing, false otherwise
// * @param param necessary parameters.
// */
procedure Init(forSigning: Boolean; const parameters: ICipherParameters);
// /**
// * update the internal digest with the byte b
// */
procedure Update(input: Byte);
// /**
// * update the internal digest with the byte array in
// */
procedure BlockUpdate(const input: TCryptoLibByteArray;
inOff, length: Int32);
// /**
// * Generate a signature for the message we've been loaded with using
// * the key we were initialised with.
// */
function GenerateSignature(): TCryptoLibByteArray;
// /**
// * return true if the internal state represents the signature described
// * in the passed in array.
// */
function VerifySignature(const signature: TCryptoLibByteArray): Boolean;
// /**
// * reset the internal state
// */
procedure Reset();
end;
implementation
end.
| 31.802469 | 87 | 0.492236 |
833c06cc004287ead460911078664efbce302d82 | 450 | pas | Pascal | Win10Session/Calendar/Unit1.pas | xchinjo/DelphiSessions | 0679d97a78ff232c6bbec1217c4f8c2104d58210 | [
"MIT"
]
| 44 | 2017-05-30T20:54:06.000Z | 2022-02-25T16:44:23.000Z | Win10Session/Calendar/Unit1.pas | jpluimers/DelphiSessions | 0679d97a78ff232c6bbec1217c4f8c2104d58210 | [
"MIT"
]
| null | null | null | Win10Session/Calendar/Unit1.pas | jpluimers/DelphiSessions | 0679d97a78ff232c6bbec1217c4f8c2104d58210 | [
"MIT"
]
| 19 | 2017-07-25T10:03:13.000Z | 2021-10-17T11:40:38.000Z | unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.WinXCalendars;
type
TForm1 = class(TForm)
CalendarView1: TCalendarView;
CalendarView2: TCalendarView;
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
end.
| 16.666667 | 99 | 0.68 |
859dd255255e389dd71dcf23ce308eb8e64b1d85 | 4,918 | pas | Pascal | windows/src/ext/jedi/jvcl/jvcl/examples/JvMouseGesture/uJvMouseGesture.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 219 | 2017-06-21T03:37:03.000Z | 2022-03-27T12:09:28.000Z | windows/src/ext/jedi/jvcl/jvcl/examples/JvMouseGesture/uJvMouseGesture.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 4,451 | 2017-05-29T02:52:06.000Z | 2022-03-31T23:53:23.000Z | windows/src/ext/jedi/jvcl/jvcl/examples/JvMouseGesture/uJvMouseGesture.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 72 | 2017-05-26T04:08:37.000Z | 2022-03-03T10:26:20.000Z | {******************************************************************
JEDI-VCL Demo
Copyright (C) 2002 Project JEDI
Original author:
Contributor(s):
You may retrieve the latest version of this file at the JEDI-JVCL
home page, located at http://jvcl.delphi-jedi.org
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_1Final.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.
******************************************************************}
unit uJvMouseGesture;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, JvMouseGesture, ExtCtrls, JvComponent, Menus,
JvExStdCtrls, JvCheckBox, JvRadioButton;
type
TJvMouseGestureDemoMainFrm = class(TForm)
Memo1: TMemo;
JvMouseGesture1: TJvMouseGesture;
JvMouseGestureHook1: TJvMouseGestureHook;
GroupBox1: TGroupBox;
rbFormOnly: TJvRadioButton;
rbAppEvents: TJvRadioButton;
Label1: TLabel;
cbMouseButton: TComboBox;
chkNoPopup: TJvCheckBox;
pnlGesture: TPanel;
Label2: TLabel;
procedure FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure FormMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormShow(Sender: TObject);
procedure cbMouseButtonChange(Sender: TObject);
procedure Memo1ContextPopup(Sender: TObject; MousePos: TPoint;
var Handled: Boolean);
procedure JvMouseGestureHook1MouseGestureCustomInterpretation(
Sender: TObject; const AGesture: String);
procedure FormCreate(Sender: TObject);
procedure rbFormOnlyClick(Sender: TObject);
private
procedure RefreshCaption;
end;
var
JvMouseGestureDemoMainFrm: TJvMouseGestureDemoMainFrm;
implementation
{$R *.dfm}
function BoolToStr(AValue:boolean):string;
const cBool:array[boolean] of PChar = ('false','true');
begin
Result := cBool[AValue];
end;
procedure TJvMouseGestureDemoMainFrm.FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if not rbFormOnly.Checked then
Exit;
if Button = mbRight then
JvMouseGesture1.StartMouseGesture(x,y);
end;
procedure TJvMouseGestureDemoMainFrm.FormMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
if JvMouseGesture1.TrailActive then
JvMouseGesture1.TrailMouseGesture(x,y);
end;
procedure TJvMouseGestureDemoMainFrm.FormMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if JvMouseGesture1.TrailActive then
begin
JvMouseGesture1.EndMouseGesture;
Memo1.Lines.Add('Gesture = ' + JvMouseGesture1.Gesture);
end;
end;
procedure TJvMouseGestureDemoMainFrm.FormShow(Sender: TObject);
begin
JvMouseGesture1.Active := True;
JvMouseGestureHook1.Active := False;
RefreshCaption;
end;
procedure TJvMouseGestureDemoMainFrm.RefreshCaption;
begin
Memo1.Clear;
Caption := 'Panel Hooked = ' + BoolToStr(JvMouseGesture1.Active) +
', Application Hooked = '+ BoolToStr(JvMouseGestureHook1.Active);
Memo1.Lines.Add(Caption);
end;
procedure TJvMouseGestureDemoMainFrm.cbMouseButtonChange(Sender: TObject);
begin
chkNoPopup.Enabled := false;
case cbMouseButton.ItemIndex of
0: JvMouseGestureHook1.MouseButton := mbLeft;
1: JvMouseGestureHook1.MouseButton := mbMiddle;
2:
begin
JvMouseGestureHook1.MouseButton := mbRight;
chkNoPopup.Enabled := true;
end;
end;
end;
procedure TJvMouseGestureDemoMainFrm.Memo1ContextPopup(Sender: TObject; MousePos: TPoint;
var Handled: Boolean);
begin
// if we have a gesture and the user wants to surpress the popup, return true
Handled := chkNoPopup.Checked and rbAppEvents.Checked and (JvMouseGestureHook1.MouseGesture.Gesture <> '');
end;
procedure TJvMouseGestureDemoMainFrm.JvMouseGestureHook1MouseGestureCustomInterpretation(
Sender: TObject; const AGesture: String);
begin
Memo1.Lines.Add('Gesture (via hook) = ' + AGesture);
end;
procedure TJvMouseGestureDemoMainFrm.FormCreate(Sender: TObject);
begin
cbMouseButton.ItemIndex := 2;
end;
procedure TJvMouseGestureDemoMainFrm.rbFormOnlyClick(Sender: TObject);
begin
if rbFormOnly.Checked then
begin
JvMouseGesture1.Active := true;
JvMouseGestureHook1.Active := false;
end
else
begin
JvMouseGesture1.Active := false;
JvMouseGestureHook1.Active := true;
end;
RefreshCaption;
end;
end. | 29.100592 | 109 | 0.735055 |
83d8c02e39836e90d062a984a996feecb28f0ac2 | 674 | pas | Pascal | Lab2 - Condicionales/domingopascua.pas | UCAB-arthurcanga/AyPI | 9fbdc1dfb53d49e92a4673de1982ebc98fa251cd | [
"MIT"
]
| null | null | null | Lab2 - Condicionales/domingopascua.pas | UCAB-arthurcanga/AyPI | 9fbdc1dfb53d49e92a4673de1982ebc98fa251cd | [
"MIT"
]
| null | null | null | Lab2 - Condicionales/domingopascua.pas | UCAB-arthurcanga/AyPI | 9fbdc1dfb53d49e92a4673de1982ebc98fa251cd | [
"MIT"
]
| null | null | null | program domingopascua;
uses crt;
var a,b,c,d,e,n,year:integer;
begin
writeln('Este programa indica que dia del mes de Marzo o Abril es el domingo de Pascua.');
writeln('Introduzca el ano al que quiere calcular el dia en que cae el domingo de Pascua');
readln(year);
a:=year mod 19;
b:=year mod 4;
c:=year mod 7;
d:=(19*a+24) mod 30;
e:=(2*b+4*c+6*d+5) mod 7;
n:=(22+d+e);
if (n<=31) then
writeln('El domingo de Pascua para el ano ',year,' caera el dia ',n,' de marzo')
else writeln('El domingo de Pascua para el ano ',year,' caera el dia ',n-31,' de abril');
writeln('Pulse cualquier tecla para salir...');
readkey();
end.
| 30.636364 | 94 | 0.635015 |
85890073f8330bec9ba66400915e59a462770204 | 6,968 | pas | Pascal | Source/ObjectSpace/IDE/BoldComponentValidatorIDE.pas | LenakeTech/BoldForDelphi | 3ef25517d5c92ebccc097c6bc2f2af62fc506c71 | [
"MIT"
]
| 121 | 2020-09-22T10:46:20.000Z | 2021-11-17T12:33:35.000Z | Source/ObjectSpace/IDE/BoldComponentValidatorIDE.pas | LenakeTech/BoldForDelphi | 3ef25517d5c92ebccc097c6bc2f2af62fc506c71 | [
"MIT"
]
| 8 | 2020-09-23T12:32:23.000Z | 2021-07-28T07:01:26.000Z | Source/ObjectSpace/IDE/BoldComponentValidatorIDE.pas | LenakeTech/BoldForDelphi | 3ef25517d5c92ebccc097c6bc2f2af62fc506c71 | [
"MIT"
]
| 42 | 2020-09-22T14:37:20.000Z | 2021-10-04T10:24:12.000Z | unit BoldComponentValidatorIDE;
interface
uses
Menus,
BoldComponentValidator,
ToolsApi;
type
{ forward declarations }
TBoldComponentValidatorIDE = class;
{ TBoldComponentValidatorIDE }
TBoldComponentValidatorIDE = class(TBoldComponentValidator)
private
fMenuItemAll: TMenuItem;
fMenuItemCurrent: TMenuItem;
procedure ChangeFocus;
public
constructor Create;
destructor Destroy; override;
procedure ValidateIOTAModule(Module: IOTAModule);
procedure ValidateFormEditor(FormEditor: IOTAFormEditor);
procedure ValidateIOTAModules;
Procedure ValidateIOTAComponent(Component: IOTAComponent; NamePrefix: String = '');
procedure ValidateAllMenuAction(Sender: TObject);
procedure ValidateCurrentMenuAction(Sender: TObject);
end;
procedure Register;
implementation
uses
Windows,
Classes,
SysUtils,
BoldLogHandler,
BoldGuard,
BoldIDEMenus,
BoldEnvironment,
BoldCoreConsts;
var
G_BoldComponentValidatorIDE: TBoldComponentValidatorIDE = nil;
procedure Register;
begin
G_BoldComponentValidatorIDE := TBoldComponentValidatorIDE.Create;
end;
{ TBoldComponentValidatorIDE }
constructor TBoldComponentValidatorIDE.create;
begin
fMenuItemAll := BoldMenuExpert.AddMenuItem('mnuValidateAllForms', // do not localize
sValidateAllForms,
ValidateAllMenuAction,
True);
fMenuItemCurrent := BoldMenuExpert.AddMenuItem('mnuValidateCurrentForm', // do not localize
sValidateCurrentForm,
ValidateCurrentMenuAction,
True);
end;
destructor TBoldComponentValidatorIDE.Destroy;
begin
if BoldMenuExpertAssigned then
begin
if assigned(fMenuItemAll) then
BoldMenuExpert.RemoveAndDestroyMenuItem(fMenuItemAll);
if assigned(fMenuItemCurrent) then
BoldMenuExpert.RemoveAndDestroyMenuItem(fMenuItemCurrent);
end;
inherited;
end;
procedure TBoldComponentValidatorIDE.ValidateIOTAModule(Module: IOTAModule);
var
i: integer;
Editor: IOTAEditor;
FormEditor: IOTAFormEditor;
HasEditor: boolean;
begin
if not Assigned(Module) then
Exit;
HasEditor := False;
try
for i := 0 to Module.GetModuleFileCount - 1 do
begin
Editor := Module.GetModuleFileEditor(i);
if Editor.QueryInterface(IOTAFormEditor, FormEditor) = S_OK then
begin
BoldLog.LogFmtIndent(sValidatingForm, [FormEditor.FileName]);
ValidateFormEditor(FormEditor);
HasEditor := True;
BoldLog.Dedent;
end;
end;
except
on e: Exception do
BoldLog.LogFmt(sFailedToValidate, [Module.FileName, e.Message]);
end;
if not HasEditor then
BoldLog.LogFmt(sNothingToValidate, [Module.FileName]);
end;
procedure TBoldComponentValidatorIDE.ValidateIOTAModules;
var
i: integer;
ModuleServices: IOTAModuleServices;
ProjectGroup: IOTAProjectGroup;
Project: IOTAProject;
Module: IOTAModule;
OTAModuleInfo: IOTAModuleInfo;
FileNames: TStringList;
Guard: IBoldGuard;
begin
// Filenames of open modules are stored and not revalidated later.
Guard := TBoldGuard.Create(FileNames);
FileNames := TStringList.Create;
ModuleServices := (BorlandIDEServices as IOTAModuleServices);
BoldLog.LogIndent(sValidatingAllOpenModules);
BoldLog.ProgressMax := ModuleServices.GetModuleCount;
ChangeFocus;
for i := 0 to ModuleServices.GetModuleCount - 1 do
begin
ValidateIOTAModule(ModuleServices.GetModule(i));
FileNames.Add(ModuleServices.Modules[i].FileName);
BoldLog.ProgressStep;
end;
BoldLog.Dedent;
ChangeFocus;
BoldLog.LogIndent(sLookingForDefaultProject);
for i := 0 to ModuleServices.GetModuleCount - 1 do
begin
if ModuleServices.GetModule(i).QueryInterface(IOTAProjectGroup, ProjectGroup) = S_OK then
begin
Project := ProjectGroup.ActiveProject;
BoldLog.LogFmt(sDefaultProject, [Project.FileName]);
Break;
end;
end;
BoldLog.Dedent;
ChangeFocus;
if not Assigned(Project) then
begin
BoldLog.LogIndent(sLookingForAnyProject);
for i := 0 to ModuleServices.GetModuleCount - 1 do
begin
if ModuleServices.GetModule(i).QueryInterface(IOTAProject, Project) = S_OK then
begin
BoldLog.LogFmt(sFoundProject, [Project.FileName]);
Break;
end;
end;
end;
BoldLog.Dedent;
ChangeFocus;
BoldLog.ProgressMax := Project.GetModuleCount - 1;
BoldLog.Progress := 0;
for i := 0 to Project.GetModuleCount - 1 do
begin
OTAModuleInfo := Project.GetModule(i);
try
Module := OTAModuleInfo.OpenModule;
if FileNames.IndexOf(Module.FileName) = - 1 then
begin
ValidateIOTAModule(Module);
Module.CloseModule(True);
end;
BoldLog.ProgressStep;
except
end;
end;
BoldLog.EndLog;
end;
procedure TBoldComponentValidatorIDE.ValidateFormEditor(FormEditor: IOTAFormEditor);
begin
if assigned(FormEditor) then
begin
FormEditor.Show;
if assigned(FormEditor.GetRootComponent) then
ValidateIOTAComponent(FormEditor.GetRootComponent);
end;
end;
procedure TBoldComponentValidatorIDE.ValidateIOTAComponent(Component: IOTAComponent; NamePrefix: String = '');
var
NTAComponent: INTAComponent;
RealComponent: TComponent;
i: integer;
ComponentName: string;
begin
RealComponent := nil;
ComponentName := '';
if Component.QueryInterface(INTAComponent, NTAComponent) = S_OK then
begin
RealComponent := NTAComponent.GetComponent;
if Assigned(RealComponent) then
ComponentName := RealComponent.Name;
end;
if assigned(RealComponent) then
ValidateComponent(RealComponent, NamePrefix);
//if not ValidateComponent(RealComponent, NamePrefix) then
// fLastFailedComponent := Component;
for i := 0 to Component.GetComponentCount - 1 do
ValidateIOTAComponent(Component.GetComponent(i),
NamePrefix + ComponentName + '.');
end;
procedure TBoldComponentValidatorIDE.ValidateAllMenuAction(Sender: TObject);
begin
InitializeLog;
ValidateIOTAModules;
CompleteLog;
{ if assigned(LastFailedComponent) then
LastFailedComponent.Select(false);
fLastFailedComponent := nil;
}
end;
procedure TBoldComponentValidatorIDE.ValidateCurrentMenuAction(Sender: TObject);
var
ModuleServices: IOTAModuleServices;
Module: IOTAModule;
begin
ModuleServices := (BorlandIDEServices as IOTAModuleServices);
Module := ModuleServices.CurrentModule;
if Assigned(Module) then
begin
InitializeLog;
ValidateIOTAModule(Module);
CompleteLog;
end
else
raise Exception.Create(sNoValidateableModuleAvailable);
end;
procedure TBoldComponentValidatorIDE.ChangeFocus;
begin
BoldEffectiveEnvironment.FocusMainform;
end;
initialization
finalization
FreeAndNil(G_BoldComponentValidatorIDE);
end.
| 26.8 | 110 | 0.723737 |
61977b72fff646fecacfdff5c6a0efa6629b005b | 412 | pas | Pascal | WebComponents/OLD-PreV3.0/demos/vui-signature-pad/VCL/VuiSignature.Dlg.pas | cybelesoft/virtualui | f0ba805563afc00546a1a1f9147721de45840ffb | [
"MIT"
]
| 11 | 2016-09-17T14:57:28.000Z | 2022-03-16T21:30:44.000Z | WebComponents/OLD-PreV3.0/demos/vui-signature-pad/VCL/VuiSignature.Dlg.pas | cybelesoft/virtualui | f0ba805563afc00546a1a1f9147721de45840ffb | [
"MIT"
]
| 3 | 2021-11-29T09:16:36.000Z | 2022-02-01T22:23:04.000Z | WebComponents/OLD-PreV3.0/demos/vui-signature-pad/VCL/VuiSignature.Dlg.pas | cybelesoft/virtualui | f0ba805563afc00546a1a1f9147721de45840ffb | [
"MIT"
]
| 10 | 2016-10-26T16:49:50.000Z | 2021-12-01T15:23:44.000Z | unit VuiSignature.Dlg;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls;
type
TfrmSignatureDlg = class(TForm)
Image1: TImage;
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmSignatureDlg: TfrmSignatureDlg;
implementation
{$R *.dfm}
end.
| 15.846154 | 98 | 0.730583 |
f1420ebe7fb87ced8182f9b42ad566fcb7aabe6e | 464 | pas | Pascal | Test/InterfacesPass/interface_inheritance_instance.pas | synapsea/DW-Script | b36c2e57f0285c217f8f0cae8e4e158d21127163 | [
"Condor-1.1"
]
| 1 | 2022-02-18T22:14:44.000Z | 2022-02-18T22:14:44.000Z | Test/InterfacesPass/interface_inheritance_instance.pas | synapsea/DW-Script | b36c2e57f0285c217f8f0cae8e4e158d21127163 | [
"Condor-1.1"
]
| null | null | null | Test/InterfacesPass/interface_inheritance_instance.pas | synapsea/DW-Script | b36c2e57f0285c217f8f0cae8e4e158d21127163 | [
"Condor-1.1"
]
| null | null | null | type
IBase = interface
procedure A;
end;
type
IDerived = interface(IBase)
procedure B;
end;
type
TImp = class(TObject, IDerived)
procedure A; begin PrintLn('A'); end;
procedure B; begin PrintLn('B'); end;
end;
var Imp: TImp;
var Base: IBase;
var Derived: IDerived;
Imp := TImp.Create;
Derived := Imp;
Derived.A;
Derived.B;
if not (Imp implements IBase) then PrintLn('Imp does not implement IBase');
Base := Derived;
Base.A; | 16 | 75 | 0.659483 |
47bc9546a2f6dae20b7ff3463af519d13915cbac | 803 | pas | Pascal | MultiPlug2/ULaunchManager.pas | danatela/MultiPlugger2 | 592e40740e453e231dc9bf8c3e75c730218ff45e | [
"CC0-1.0"
]
| null | null | null | MultiPlug2/ULaunchManager.pas | danatela/MultiPlugger2 | 592e40740e453e231dc9bf8c3e75c730218ff45e | [
"CC0-1.0"
]
| null | null | null | MultiPlug2/ULaunchManager.pas | danatela/MultiPlugger2 | 592e40740e453e231dc9bf8c3e75c730218ff45e | [
"CC0-1.0"
]
| null | null | null | unit ULaunchManager;
interface
uses
Classes, Contnrs, UPluginLauncher, Generics.Collections;
type
TLaunchManager = class (TList<TPluginLauncher>)
function GetLauncherByName(LauncherName: string): TPluginLauncher;
end;
function LaunchManager: TLaunchManager;
implementation
var
Manager: TLaunchManager;
function LaunchManager: TLaunchManager;
begin
Result := Manager;
end;
{ TLaunchManager }
function TLaunchManager.GetLauncherByName(LauncherName: string): TPluginLauncher;
var
I: Integer;
begin
Result := nil;
for I := 0 to Count - 1 do
if Items[I].ClassNameIs(LauncherName) then begin
Result := Items[I];
Break;
end;
end;
initialization
Manager := TLaunchManager.Create;
finalization
Manager.Free;
end.
| 17.085106 | 82 | 0.707347 |
83fc9bcffbe9fd78f11fad765bf9715031a3b4a8 | 4,656 | pas | Pascal | ProblemChecker/Source/ProblemChecker.Base.pas | ProHolz/ElementsDelphiTools | dca0c4d6171428ea2671ace6d3bc5f68e6f147af | [
"MIT"
]
| 5 | 2019-02-21T14:07:28.000Z | 2021-04-21T18:59:59.000Z | ProblemChecker/Source/ProblemChecker.Base.pas | ProHolz/ElementsDelphiTools | dca0c4d6171428ea2671ace6d3bc5f68e6f147af | [
"MIT"
]
| 1 | 2019-03-04T12:27:59.000Z | 2019-03-04T12:27:59.000Z | ProblemChecker/Source/ProblemChecker.Base.pas | ProHolz/ElementsDelphiTools | dca0c4d6171428ea2671ace6d3bc5f68e6f147af | [
"MIT"
]
| 4 | 2019-09-07T12:48:54.000Z | 2021-04-23T13:34:34.000Z | namespace ProHolz.SourceChecker;
interface
uses ProHolz.Ast;
type
TSyntaxNodeResolver = class(ISyntaxNodeSolver)
private
method InternGetTypes(const aNode: TSyntaxNode; const aInterface: Boolean; const aTypename: not nullable String; const amatchname: Boolean): TSyntaxNodeList; // ISyntaxNodeSolver
private // Interface ISyntaxNodeSolver
method GetNode(aNodetype: TSyntaxNodeType; const aNode: TSyntaxNode): TSyntaxNode;
method GetNodeArray(aNodetype: TSyntaxNodeType; const aNode: TSyntaxNode): TSyntaxNodeList;
method GetNodeArrayAll(aNodetypes: array of TSyntaxNodeType; const aNode: TSyntaxNode): TSyntaxNodeList;
method GetNodeGlobArray(aNodetype: TSyntaxNodeType; const aNode: TSyntaxNode): TSyntaxNodeList;
method GetPublicTypes(const aNode: TSyntaxNode; const aTypename : not nullable String; const amatchname : Boolean = false):TSyntaxNodeList;
method GetImplTypes(const aNode: TSyntaxNode; const aTypename : not nullable String; const amatchname : Boolean = false): TSyntaxNodeList;
method GetPublicClass(const aNode: TSyntaxNode): TSyntaxNodeList;
method GetPublicRecord(const aNode: TSyntaxNode): TSyntaxNodeList;
method GetImplClass(const aNode: TSyntaxNode): TSyntaxNodeList;
end;
implementation
method TSyntaxNodeResolver.InternGetTypes(const aNode: TSyntaxNode; const aInterface : Boolean; const aTypename : not nullable String; const amatchname : Boolean): TSyntaxNodeList;
begin
result := new TSyntaxNodeList();
var lClasses := GetNodeArrayAll(if aInterface then cPublicTypesInterface else cPublicTypesImplementation, aNode);
for lClass in lClasses do
begin
if String.EqualsIgnoringCase(
lClass.GetAttribute(if amatchname then TAttributeName.anName else TAttributeName.anType),
aTypename) then
result.Add(lClass);
if String.EqualsIgnoringCase(
lClass.FindNode(TSyntaxNodeType.ntName):GetAttribute(if amatchname then TAttributeName.anName else TAttributeName.anType),
aTypename) then
result.Add(lClass);
end;
ensure
result <> nil;
end;
method TSyntaxNodeResolver.GetPublicTypes(const aNode: TSyntaxNode; const aTypename : not nullable String; const amatchname : Boolean): TSyntaxNodeList;
begin
result := InternGetTypes(aNode, true, aTypename, amatchname);
ensure
result <> nil;
end;
method TSyntaxNodeResolver.GetImplTypes(const aNode: TSyntaxNode; const aTypename: not nullable String; const amatchname: Boolean): TSyntaxNodeList;
begin
result := InternGetTypes(aNode, false, aTypename, amatchname);
ensure
result <> nil;
end;
method TSyntaxNodeResolver.GetNode(aNodetype: TSyntaxNodeType; const aNode: TSyntaxNode): TSyntaxNode;
begin
Result := aNode:FindNode(aNodetype);
end;
method TSyntaxNodeResolver.GetNodeArray(aNodetype: TSyntaxNodeType; const aNode: TSyntaxNode): TSyntaxNodeList;
begin
result := new TSyntaxNodeList();
for lNode in aNode:ChildNodes do
if lNode.Typ = aNodetype then
result.Add(lNode);
ensure
result <> nil;
end;
method TSyntaxNodeResolver.GetNodeGlobArray(aNodetype: TSyntaxNodeType; const aNode: TSyntaxNode): TSyntaxNodeList;
begin
result := new TSyntaxNodeList();
for lNode in aNode:ChildNodes do
begin
if lNode.Typ = aNodetype then
result.Add(lNode);
for each ltemp in GetNodeGlobArray(aNodetype, lNode) do
result.Add(ltemp);
end;
ensure
result <> nil;
end;
method TSyntaxNodeResolver.GetNodeArrayAll(aNodetypes: array of TSyntaxNodeType; const aNode: TSyntaxNode): TSyntaxNodeList;
begin
result := new TSyntaxNodeList();
if length(aNodetypes) = 0 then exit(nil);
if length(aNodetypes) = 1 then
exit GetNodeArray(aNodetypes[0], aNode) else
begin
var temp := GetNodeArray(aNodetypes[0], aNode);
var ltemp := new List<TSyntaxNodeType>();
for i : Integer := 1 to high(aNodetypes) do
ltemp.Add(aNodetypes[i]);
for each node in temp do
begin
var linner := GetNodeArrayAll(ltemp.ToArray, node);
result.Add(linner.toArray);
end;
end;
ensure
result <> nil;
end;
method TSyntaxNodeResolver.GetPublicClass(const aNode: TSyntaxNode): TSyntaxNodeList;
begin
result := GetPublicTypes(aNode, 'class');
ensure
result <> nil;
end;
method TSyntaxNodeResolver.GetPublicRecord(const aNode: TSyntaxNode): TSyntaxNodeList;
begin
result := GetPublicTypes(aNode, 'record');
ensure
result <> nil;
end;
method TSyntaxNodeResolver.GetImplClass(const aNode: TSyntaxNode): TSyntaxNodeList;
begin
result := GetImplTypes(aNode, 'class');
ensure
result <> nil;
end;
end. | 32.788732 | 182 | 0.747208 |
856cd8b779b6babe015057025e1db55f82932575 | 3,951 | dfm | Pascal | GeneEdit/GeneEditForm.dfm | bmzat/GenNeuroNet | 7932fdbf48c8c9a49279cbc913749fa4a0fadbbe | [
"Unlicense"
]
| null | null | null | GeneEdit/GeneEditForm.dfm | bmzat/GenNeuroNet | 7932fdbf48c8c9a49279cbc913749fa4a0fadbbe | [
"Unlicense"
]
| null | null | null | GeneEdit/GeneEditForm.dfm | bmzat/GenNeuroNet | 7932fdbf48c8c9a49279cbc913749fa4a0fadbbe | [
"Unlicense"
]
| null | null | null | object Form1: TForm1
Left = 0
Top = 0
Caption = 'GenomeEdit'
ClientHeight = 675
ClientWidth = 1100
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
PixelsPerInch = 96
TextHeight = 13
object Label1: TLabel
Left = 128
Top = 19
Width = 24
Height = 13
Caption = 'From'
end
object Label2: TLabel
Left = 128
Top = 46
Width = 12
Height = 13
Caption = 'To'
end
object Label3: TLabel
Left = 128
Top = 78
Width = 26
Height = 13
Caption = 'Value'
end
object Label4: TLabel
Left = 128
Top = 124
Width = 46
Height = 13
Caption = 'Reserved'
end
object Axon: TCheckBox
Left = 8
Top = 8
Width = 97
Height = 17
Caption = 'Axon'
TabOrder = 0
end
object FromInput: TCheckBox
Left = 8
Top = 31
Width = 97
Height = 17
Caption = 'FromInput'
TabOrder = 1
end
object ToOutput: TCheckBox
Left = 8
Top = 54
Width = 97
Height = 17
Caption = 'ToOutput'
TabOrder = 2
end
object IsFeature: TCheckBox
Left = 8
Top = 77
Width = 97
Height = 17
Caption = 'IsFeature'
TabOrder = 3
end
object IsParam: TCheckBox
Left = 8
Top = 100
Width = 97
Height = 17
Caption = 'IsParam'
TabOrder = 4
end
object IsValue: TCheckBox
Left = 8
Top = 123
Width = 97
Height = 17
Caption = 'IsValue'
TabOrder = 5
end
object From: TEdit
Left = 176
Top = 16
Width = 121
Height = 21
TabOrder = 6
Text = '0'
end
object To: TEdit
Left = 176
Top = 43
Width = 121
Height = 21
TabOrder = 7
Text = '0'
end
object Reserved1: TCheckBox
Left = 8
Top = 146
Width = 97
Height = 17
Caption = 'Reserved1'
TabOrder = 8
end
object Reserved2: TCheckBox
Left = 8
Top = 169
Width = 97
Height = 17
Caption = 'Reserved2'
TabOrder = 9
end
object Value: TEdit
Left = 176
Top = 75
Width = 121
Height = 21
TabOrder = 10
Text = '0,0'
end
object Reserved: TEdit
Left = 180
Top = 121
Width = 117
Height = 19
TabOrder = 11
Text = '0'
end
object Button1: TButton
Left = 358
Top = 27
Width = 75
Height = 25
Caption = 'Random'
TabOrder = 12
OnClick = Button1Click
end
object Button2: TButton
Left = 254
Top = 169
Width = 75
Height = 25
Caption = 'Add'
TabOrder = 13
OnClick = Button2Click
end
object Memo1: TMemo
Left = 8
Top = 240
Width = 801
Height = 329
Lines.Strings = (
'Memo1')
TabOrder = 14
end
object ReverseInput: TEdit
Left = 776
Top = 29
Width = 121
Height = 21
TabOrder = 15
Text = 'ReverseInput'
end
object Button3: TButton
Left = 912
Top = 27
Width = 75
Height = 25
Caption = 'Reverse'
TabOrder = 16
OnClick = Button3Click
end
object Button4: TButton
Left = 358
Top = 112
Width = 75
Height = 25
Caption = 'Cook'
TabOrder = 17
OnClick = Button4Click
end
object Button5: TButton
Left = 216
Top = 200
Width = 113
Height = 25
Caption = 'Compile C-String'
TabOrder = 18
OnClick = Button5Click
end
object Button6: TButton
Left = 344
Top = 200
Width = 75
Height = 25
Caption = 'Button6'
TabOrder = 19
OnClick = Button6Click
end
object Button7: TButton
Left = 120
Top = 200
Width = 75
Height = 25
Caption = 'Compile HEX'
TabOrder = 20
OnClick = Button7Click
end
end
| 17.877828 | 33 | 0.535814 |
8368670b82e794cd93d37b71bf9b6b11f3b479fc | 229 | dpr | Pascal | Demos/Mega Demo/MegaDemo.dpr | JensBorrisholt/Print-and-Merge-Suite | 8ebbc09dc1ab10550e93e5a3bd07c60b295f8161 | [
"MIT"
]
| 8 | 2019-11-26T12:49:55.000Z | 2021-03-09T12:09:11.000Z | Demos/Mega Demo/MegaDemo.dpr | azrael11/Print-and-Merge-Suite | 8ebbc09dc1ab10550e93e5a3bd07c60b295f8161 | [
"MIT"
]
| null | null | null | Demos/Mega Demo/MegaDemo.dpr | azrael11/Print-and-Merge-Suite | 8ebbc09dc1ab10550e93e5a3bd07c60b295f8161 | [
"MIT"
]
| 5 | 2019-11-29T18:44:29.000Z | 2021-07-22T06:41:03.000Z | program MegaDemo;
uses
Vcl.Forms,
Mainu in 'Mainu.pas' {FormMain};
{$R *.res}
begin
Application.Initialize;
Application.MainFormOnTaskbar := True;
Application.CreateForm(TFormMain, FormMain);
Application.Run;
end.
| 15.266667 | 46 | 0.729258 |
47c802f2b52a75e2774bdb16af45d9974446c9ac | 4,333 | pas | Pascal | src/Common/KLUSolve.pas | PMeira/dss_capi | 8b80035730c9d470d057f6643db0a4d4623d70f4 | [
"BSD-3-Clause"
]
| 4 | 2017-12-18T15:23:43.000Z | 2019-02-05T18:22:53.000Z | src/Common/KLUSolve.pas | PMeira/dss_capi | 8b80035730c9d470d057f6643db0a4d4623d70f4 | [
"BSD-3-Clause"
]
| 28 | 2018-02-12T20:13:26.000Z | 2019-02-11T17:27:51.000Z | src/Common/KLUSolve.pas | PMeira/dss_capi | 8b80035730c9d470d057f6643db0a4d4623d70f4 | [
"BSD-3-Clause"
]
| 1 | 2018-07-30T22:57:42.000Z | 2018-07-30T22:57:42.000Z | unit KLUSolve;
{$MACRO ON}
{$IFDEF MSWINDOWS}
{$DEFINE KLUSOLVEX_CALL:=cdecl;external 'libklusolvex'}
{$ELSE} // Unix in general
{$DEFINE KLUSOLVEX_CALL:=cdecl;external}
{$ENDIF}
interface
uses
UComplex, DSSUcomplex;
{$IFDEF DSS_CAPI_MVMULT}
procedure mvmult(N: integer; b, A, x: pComplexArray);KLUSOLVEX_CALL;
{$ENDIF}
// in general, KLU arrays are 0-based
// function calls return 0 to indicate failure, 1 for success
// returns the non-zero handle of a new sparse matrix, if successful
// must call DeleteSparseSet on the valid handle when finished
FUNCTION NewSparseSet(nBus:LongWord):NativeUInt;KLUSOLVEX_CALL;
// return 1 for success, 0 for invalid handle
FUNCTION DeleteSparseSet(id:NativeUInt):LongWord;KLUSOLVEX_CALL;
// return 1 for success, 2 for singular, 0 for invalid handle
// factors matrix if needed
FUNCTION SolveSparseSet(id:NativeUInt; x,b:pComplexArray):LongWord;KLUSOLVEX_CALL;
// return 1 for success, 0 for invalid handle
FUNCTION ZeroSparseSet(id:NativeUInt):LongWord;KLUSOLVEX_CALL;
// return 1 for success, 2 for singular, 0 for invalid handle
// FactorSparseMatrix does no extra work if the factoring was done previously
FUNCTION FactorSparseMatrix(id:NativeUInt):LongWord;KLUSOLVEX_CALL;
// These "Get" functions for matrix information all return 1 for success, 0 for invalid handle
// Res is the matrix order (number of nodes)
FUNCTION GetSize(id:NativeUInt; Res: pLongWord):LongWord;KLUSOLVEX_CALL;
// the following function results are not known prior to factoring
// Res is the number of floating point operations to factor
FUNCTION GetFlops(id:NativeUInt; Res: pDouble):LongWord;KLUSOLVEX_CALL;
// Res is number of non-zero entries in the original matrix
FUNCTION GetNNZ(id:NativeUInt; Res: pLongWord):LongWord;KLUSOLVEX_CALL;
// Res is the number of non-zero entries in factored matrix
FUNCTION GetSparseNNZ(id:NativeUInt; Res: pLongWord):LongWord;KLUSOLVEX_CALL;
// Res is a column number corresponding to a singularity, or 0 if not singular
FUNCTION GetSingularCol(id:NativeUInt; Res: pLongWord):LongWord;KLUSOLVEX_CALL;
// Res is the pivot element growth factor
FUNCTION GetRGrowth(id:NativeUInt; Res: pDouble):LongWord;KLUSOLVEX_CALL;
// Res is aquick estimate of the reciprocal of condition number
FUNCTION GetRCond(id:NativeUInt; Res: pDouble):LongWord;KLUSOLVEX_CALL;
// Res is a more accurate estimate of condition number
FUNCTION GetCondEst(id:NativeUInt; Res: pDouble):LongWord;KLUSOLVEX_CALL;
// return 1 for success, 0 for invalid handle or a node number out of range
FUNCTION AddPrimitiveMatrix(id:NativeUInt; nOrder:LongWord; Nodes: pLongWord; Mat: pComplex):LongWord;KLUSOLVEX_CALL;
// Action = 0 (close), 1 (rewrite) or 2 (append)
FUNCTION SetLogFile(Path: pChar; Action:LongWord):LongWord;KLUSOLVEX_CALL;
// fill sparse matrix in compressed column form
// return 1 for success, 0 for invalid handle, 2 for invalid array sizes
// pColP must be of length nColP == nBus + 1
// pRowIdx and pMat of length nNZ, which
// must be at least the value returned by GetNNZ
FUNCTION GetCompressedMatrix(id:NativeUInt; nColP, nNZ:LongWord; pColP, pRowIdx: pLongWord; Mat: pComplex):LongWord;KLUSOLVEX_CALL;
// fill sparse matrix in triplet form
// return 1 for success, 0 for invalid handle, 2 for invalid array sizes
// pRows, pCols, and Mat must all be of length nNZ
FUNCTION GetTripletMatrix(id:NativeUInt; nNZ:LongWord; pRows, pCols: pLongWord; Mat: pComplex):LongWord;KLUSOLVEX_CALL;
// returns number of islands >= 1 by graph traversal
// pNodes contains the island number for each node
FUNCTION FindIslands(id:NativeUInt; nOrder:LongWord; pNodes: pLongWord):LongWord;KLUSOLVEX_CALL;
// AddMatrixElement is deprecated, use AddPrimitiveMatrix instead
FUNCTION AddMatrixElement(id:NativeUInt; i,j:LongWord; Value:pComplex):LongWord;KLUSOLVEX_CALL;
// GetMatrixElement is deprecated, use GetCompressedMatrix or GetTripletMatrix
FUNCTION GetMatrixElement(id:NativeUInt; i,j:LongWord; Value:pComplex):LongWord;KLUSOLVEX_CALL;
{$IFDEF DSS_CAPI_INCREMENTAL_Y}
FUNCTION IncrementMatrixElement(id:NativeUInt; i,j:LongWord; re: Double; im: Double):LongWord;KLUSOLVEX_CALL;
FUNCTION ZeroiseMatrixElement(id:NativeUInt; i,j:LongWord):LongWord;KLUSOLVEX_CALL;
FUNCTION SetOptions(id:NativeUInt; options: UInt64):LongWord;KLUSOLVEX_CALL;
{$ENDIF}
implementation
end.
| 45.135417 | 131 | 0.793676 |
83b7e5280db043c827af37ef0f55dc540940d5a3 | 44,388 | dfm | Pascal | Fontes/uFrmCadModelo.dfm | roneysousa/fpopular | d2f0f22cbab5a7e26540659ca7a6bf6811652c17 | [
"MIT"
]
| null | null | null | Fontes/uFrmCadModelo.dfm | roneysousa/fpopular | d2f0f22cbab5a7e26540659ca7a6bf6811652c17 | [
"MIT"
]
| null | null | null | Fontes/uFrmCadModelo.dfm | roneysousa/fpopular | d2f0f22cbab5a7e26540659ca7a6bf6811652c17 | [
"MIT"
]
| null | null | null | object FrmCadastro: TFrmCadastro
Left = 197
Top = 117
BorderIcons = [biSystemMenu]
BorderStyle = bsSingle
ClientHeight = 439
ClientWidth = 726
Color = clWhite
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
OldCreateOrder = False
Position = poScreenCenter
ShowHint = True
OnClose = FormClose
OnShow = FormShow
PixelsPerInch = 96
TextHeight = 13
object Panel1: TPanel
Left = 0
Top = 0
Width = 726
Height = 41
Align = alTop
TabOrder = 0
object Image1: TImage
Left = 1
Top = 1
Width = 724
Height = 39
Align = alClient
Stretch = True
end
end
object PageControl1: TPageControl
Left = 0
Top = 41
Width = 726
Height = 398
ActivePage = tsDados
Align = alClient
TabOrder = 1
object tsDados: TTabSheet
Caption = '&1 - Dados'
object lblCodigo: TLabel
Left = 20
Top = 16
Width = 33
Height = 13
Caption = 'C'#243'digo'
Transparent = True
end
object DBText1: TDBText
Left = 21
Top = 32
Width = 79
Height = 22
AutoSize = True
Color = clBtnFace
DataSource = dsCadastro
Font.Charset = ANSI_CHARSET
Font.Color = clBlue
Font.Height = -19
Font.Name = 'Arial'
Font.Style = [fsBold]
ParentColor = False
ParentFont = False
Transparent = True
end
object Panel2: TPanel
Left = 0
Top = 329
Width = 718
Height = 41
Align = alBottom
Color = clNavy
ParentBackground = False
TabOrder = 0
object BtAdicionar: TBitBtn
Left = 8
Top = 8
Width = 75
Height = 25
Hint = 'Adicionar novo registro'
Caption = '&Adicionar'
TabOrder = 0
OnClick = BtAdicionarClick
Glyph.Data = {
36050000424D3605000000000000360400002800000010000000100000000100
08000000000000010000220B0000220B00000001000000010000EFA54A00C684
6B00BD8C7300CE947300EFB57300FFC67300BD847B00C6947B00CE9C7B00B584
8400B58C8400CE9C8400B5948C00C6A59400EFCE9400F7CE9400C6A59C00EFCE
9C00F7CE9C00F7D69C00C6ADA500CEADA500F7D6A500CEB5AD00D6B5AD00C6BD
AD00F7D6AD00F7DEAD00D6BDB500DEBDB500DEC6B500E7C6B500EFC6B500EFCE
B500F7D6B500F7DEB500FFDEB500EFCEBD00F7DEBD00E7DEC600F7DEC600F7E7
C600E7CECE00E7D6CE00F7E7CE00E7D6D600F7E7D600FFE7D600FFEFD600FFEF
DE00FFEFE700FFF7E700FFF7EF00FFF7F700FFFFF700FF00FF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00373709090909
09090909090909090937373710302926231A16110E0E0E130937373710302C28
26221611110E0E110937373714322E2C2826221A11110E110937373714332E2C
292823221A11110E093737371736322E2E2C2826221A11110937373718383432
2E2C2928261A1616093737371C383534312E2C292826221A093737371C383835
34322E2C28262323093737371D3838383532312E2C282822093737371E383838
3835323131302719093737371F383838383834342E0D0C0A093737371F383838
383838362A0204000137373725383838383838382B070503373737371F353434
343434342A070B37373737371F212121211F1F211C0637373737}
end
object BtEditar: TBitBtn
Left = 88
Top = 8
Width = 75
Height = 25
Hint = 'Editar registro'
Caption = '&Editar'
TabOrder = 1
OnClick = BtEditarClick
Glyph.Data = {
36050000424D3605000000000000360400002800000010000000100000000100
08000000000000010000520B0000520B000000010000000100002D2D2D001855
6F004544420058534E005160610054777B007C707800B56D3E00C1713500C076
38008A5B5200947E7500AD7B7300BD847B00EFA65A00EDA75F00F0A85C00C694
7B0000009A000316AC0041749600477AA9000018C6001029D600106BFF00FF00
FF0035A8F5004A9EED006D8AFD00B5848400BD9494009891A200C6A59C00F1BC
8600C6ADA500C6ADAD00CEB5AD00D6B5AD00C6B5B500D6BDB500DEBDB500F8C2
8C00F9C48D00EFCE9400EFCE9C00F7D69C00DEC6B500D6C6BD00EFD6AD00F7D6
A500FBD3A900E7C6B500EFCEB500EFCEBD00F7DEB500F7DEBD00C6C6C600E7CE
CE00E7D6CE00F7E7C600FFEFD600FFEFE700FFF7E700FFF7EF00FFF7F700FFFF
F700FFFFFF000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000019191D1D1D1D
1D1D1D1D1D1D1D1D1D191919203C3B373630312C2B2B2B2D1D191919203C3838
383838383838382C1D191919223D00032F37302C2C2C2B2C1D191919223E0302
042F36302C2C2C2B1D1919192441380515010A263838382C1D19191925423F05
140B080A2F3030301D1919192742403F062110090A2F30301D19191927423838
0C322A0E090A262F1E19191928424242400C322A10080A2F231919192E424242
42400C32290F070A26191919334238383838380C321F1A131219191933424242
424242410C1B17171312191935424242424242423A161C181719191933403F3F
3F3F3F3F39111616191919193334343434333334270D19191919}
end
object BtExcluir: TBitBtn
Left = 168
Top = 8
Width = 75
Height = 25
Hint = 'Excluir registro'
Caption = '&Excluir'
TabOrder = 2
OnClick = BtExcluirClick
Glyph.Data = {
36050000424D3605000000000000360400002800000010000000100000000100
08000000000000010000220B0000220B000000010000000100000031DE000031
E7000031EF000031F700FF00FF000031FF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00040404040404
0404040404040404000004000004040404040404040404000004040000000404
0404040404040000040404000000000404040404040000040404040402000000
0404040400000404040404040404000000040000000404040404040404040400
0101010004040404040404040404040401010204040404040404040404040400
0201020304040404040404040404030201040403030404040404040404050203
0404040405030404040404040303050404040404040303040404040303030404
0404040404040403040403030304040404040404040404040404030304040404
0404040404040404040404040404040404040404040404040404}
end
object BtPesquisar: TBitBtn
Left = 248
Top = 8
Width = 75
Height = 25
Hint = 'Pesquisar Registros'
Caption = '&Pesquisar'
TabOrder = 3
OnClick = BtPesquisarClick
Glyph.Data = {
36050000424D3605000000000000360400002800000010000000100000000100
08000000000000010000320B0000320B000000010000000100005A6B7300AD7B
73004A637B00EFBD8400B58C8C00A5948C00C6948C00B59C8C00BD9C8C00F7BD
8C00BD949400C6949400CE949400C69C9400CEAD9400F7CE9400C6A59C00CEA5
9C00D6A59C00C6AD9C00CEAD9C00D6AD9C00F7CE9C00F7D69C004A7BA500CEAD
A500D6B5A500DEBDA500F7D6A500DEBDAD00DEC6AD00E7C6AD00FFDEAD00FFE7
AD00CEB5B500F7DEB500F7E7B500FFE7B500FFEFB500D6BDBD00DED6BD00E7DE
BD00FFE7BD006B9CC600EFDEC600FFEFC600FFF7C600F7E7CE00FFF7CE00F7EF
D600F7F7D600FFF7D600FFFFD6002184DE00F7F7DE00FFFFDE001884E700188C
E700FFFFE700188CEF00218CEF00B5D6EF00F7F7EF00FFF7EF00FFFFEF00FFFF
F700FF00FF004AB5FF0052B5FF0052BDFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF0042020A424242
424242424242424242422B39180B42424242424242424242424243443C180B42
4242424242424242424242444438180B42424242424242424242424244433918
0A424242424242424242424242444335004201101A114242424242424242453D
05072F343434291942424242424242221A2D34343437403E0442424242424206
231C303437404146284242424242421B210F30373A414140310D42424242421F
20032434373A3A37321342424242421D25030F2D37373737311042424242420D
2D2D1C162430333429424242424242421E463F0F0316252E0842424242424242
4227312D21252314424242424242424242420E141B1B42424242}
end
object BtCancelar: TBitBtn
Left = 400
Top = 8
Width = 75
Height = 25
Hint = 'Cancelar opera'#231#227'o'
Caption = '&Cancelar'
Enabled = False
TabOrder = 4
OnClick = BtCancelarClick
Glyph.Data = {
36050000424D3605000000000000360400002800000010000000100000000100
08000000000000010000D30E0000D30E00000001000000010000AD4A0000B54A
0000B5520000BD520000BD5A0000C65A0000C6630000CE630000CE6B0000D673
0000DE730000DE7B0000E77B0000E7840000F7940000CE6B0800FF9C0800A542
1000AD4A1000B5521000C6631000B55A2100CE732100B55A3100BD633100FFAD
3100CE7B3900BD6B4200C6734200CE844200CE844A00BD735200BD7B5200C67B
5200C6845A00C6846300FFBD6300C68C7300CE947B00CE9C8400FF00FF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00282828282828
2828281F05002828282828282828282828282817050713282828282828282828
2828282817060715282828282828282828282828281507062328280004040404
040404232828000701282802090807070707061B28282706062328040B090711
2727272828282800071328060D070A07232828282828281C070128070E13020B
082028282828281C0701280F101D28020D0818282828280107132816191E2828
140D0C03212513060623281A2421282828150C0D0B0908061228282622282828
282827140808041B282828282828282828282828282828282828282828282828
2828282828282828282828282828282828282828282828282828}
end
object BtGravar: TBitBtn
Left = 480
Top = 8
Width = 75
Height = 25
Hint = 'Gravar registro'
Caption = '&Gravar'
Enabled = False
TabOrder = 5
OnClick = BtGravarClick
Glyph.Data = {
36050000424D3605000000000000360400002800000010000000100000000100
08000000000000010000220B0000220B00000001000000010000942929009431
31009C3131009C393900A53939009C4242009C4A4A00A54A4A00B54A4A00AD52
4A00B5524A00A5525200AD525200B5525200B55A5200AD525A00AD5A5A00B55A
5A00BD5A5A00C65A5A00CE5A5A00CE636300CE6B6B00D66B6B00B5737300BD7B
73009C7B7B009C848400AD848400B5848400C6848400AD8C8C00B58C8C00C694
8C00AD949400C6949400A59C9C00B59C9C00D69C9C00BDA5A500D6A5A500D6AD
A500CEADAD00D6ADAD00DEADAD00CEB5B500D6B5B500CEBDBD00DEBDBD00E7BD
BD00E7C6C600C6CEC600CECEC600C6CECE00CECECE00D6CECE00E7CECE00E7D6
CE00D6D6D600DED6D600EFD6D600DEDED600D6DEDE00DEDEDE00E7DEDE00E7E7
E700EFEFEF00F7EFEF00F7F7EF00F7F7F700FFF7F700FFFFF700FF00FF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF004848100C0722
33343433332505050B4848191516111B27384647452D0002131048191515111A
05184046492E0102121048191515111C03032F42493200011210481915151120
0601243A493200011210481915151221231D1F27322C04041310481915151515
1515151313151515160F48190D111E282B292B2828292B26150C481909384544
4545454545454530130F48190A3C46434343434343434530130F48190A3C423A
3A3A3A3A3A3A4230130F48190A3C423B3F3F3F3F3F3B4230130F48190A3C4440
4040404040404230130F48190A3C423A3A3A3A3A3A3A4230130F48190A394643
4343434343434630130F4848092D3A363636363636363A2A0748}
end
object BtSair: TBitBtn
Left = 600
Top = 8
Width = 75
Height = 25
Hint = 'Fechar janela'
Caption = '&Sair'
TabOrder = 6
OnClick = BtSairClick
Glyph.Data = {
36050000424D3605000000000000360400002800000010000000100000000100
08000000000000010000220B0000220B00000001000000010000006400004242
42008C6363009A666600B9666600BB686800B0717200C3686900C66A6B00C76A
6D00CF6C6E00D2686900D16D6E00CC6E7100C0797A00D2707200D4707100D572
7300D0727500D3747600D9757600D8767700E37D7E000080000000960000DC7F
8000FF00FF00D7868700DA888800D8888A00DA888A00DF898A00E6808100E085
8500E9818200EE868700E3888900E78C8D00F0878800F18B8C00F28B8C00F18D
8E00F48C8D00F48E8F00EB8F9000EC969700E49A9800F3919200F7909100F791
9200F2939400F9909200F9949500FA949500F9969700F0999A00FC999A00FF9D
9E00F7B58400F5A7A500FACCAA00FBD6BB00FADCDC00FFFFFF00000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000001A1A1A1A1A1A
1A02011A1A1A1A1A1A1A1A1A1A1A02030405011A1A1A1A1A1A1A1A1A0203080B
0B07010303030303031A1A1A030C0C0C0A09010E1F323B3B031A1A1A030C0C10
0F0D01181818183B031A1A1A03111114151201181818183B031A1A1A03161616
201301181717173B031A1A1A0326222D3E1D01171700003B031A1A1A03262337
3F1E013C3A3A3A3B031A1A1A03272B282A19013C3D3D3D3B031A1A1A03273031
2921013C3D3D3D3B031A1A1A032734352F24013C3D3D3D3B031A1A1A03273338
3625013C3D3D3D3B031A1A1A03032E33392C013C3D3D3D3B031A1A1A1A1A0306
1B1C010303030303031A1A1A1A1A1A1A0303011A1A1A1A1A1A1A}
end
end
end
object tsPesquisa: TTabSheet
Caption = '&2 - Pesquisa'
ImageIndex = 1
OnShow = tsPesquisaShow
object grdConsultar: TJvDBUltimGrid
Left = 0
Top = 59
Width = 684
Height = 311
Align = alClient
DataSource = dsConsultar
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
Options = [dgTitles, dgIndicator, dgColLines, dgRowLines, dgTabs, dgRowSelect, dgConfirmDelete, dgCancelOnExit]
ParentFont = False
ReadOnly = True
TabOrder = 0
TitleFont.Charset = ANSI_CHARSET
TitleFont.Color = clBlack
TitleFont.Height = -11
TitleFont.Name = 'Verdana'
TitleFont.Style = [fsBold]
OnDblClick = grdConsultarDblClick
AlternateRowColor = clMenu
SelectColumnsDialogStrings.Caption = 'Select columns'
SelectColumnsDialogStrings.OK = '&OK'
SelectColumnsDialogStrings.NoSelectionWarning = 'At least one column must be visible!'
EditControls = <>
RowsHeight = 17
TitleRowHeight = 17
end
object Panel3: TPanel
Left = 0
Top = 0
Width = 718
Height = 59
Align = alTop
Color = clWhite
TabOrder = 1
object lblConsultar: TLabel
Left = 136
Top = 5
Width = 84
Height = 13
Caption = 'Nome/Descri'#231#227'o:'
end
object rgConsultar: TRadioGroup
Left = 4
Top = 1
Width = 127
Height = 55
Caption = 'Consultar por:'
Ctl3D = False
ItemIndex = 1
Items.Strings = (
'C'#243'digo'
'Nome/Descri'#231#227'o')
ParentCtl3D = False
TabOrder = 0
OnClick = rgConsultarClick
end
object edtConsultar: TEdit
Left = 135
Top = 21
Width = 465
Height = 19
CharCase = ecUpperCase
Ctl3D = False
ParentCtl3D = False
TabOrder = 1
OnChange = edtConsultarChange
OnKeyDown = edtConsultarKeyDown
OnKeyPress = edtConsultarKeyPress
end
object btnAlterar: TBitBtn
Left = 611
Top = 17
Width = 93
Height = 25
Hint = 'Alterar registro'
Caption = '&Ver Registro'
Enabled = False
ParentShowHint = False
ShowHint = True
TabOrder = 2
OnClick = btnAlterarClick
Glyph.Data = {
36050000424D3605000000000000360400002800000010000000100000000100
080000000000000100000000000000000000000100000000000000000000FFFF
FF005441B100614EBE00C0C0C000FCD7DA00ECC8CA00F0CCCE00EFCBCD00EECA
CC00FDD9DB00FBD7D900EAC5C700EEC9CB00F9D4D600FAD5D700E1BABB00ECC4
C500EDC6C700E6C0C100E4BEBF00E3BDBE00E9C3C400E7C2C300F4CECF00F8D3
D400F6D1D200FFCFCF00D6AEAE00D9B2B200D8B1B100E7BFBF00E8C1C100EAC3
C300F6D0D000CAA09F00CCA2A100D4AAA900E0B6B500DEB5B400DCB3B200D7B0
AF00E1B9B800C3999700CDA4A200D3AAA80046C6C50053D3D2004D8DB900ADAF
D900BABCE600F2F2F200C3C3C300B6B6B6008F8F8F008B8B8B00282828001B1B
1B000D0D0D000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000040404040404
0404040404040404040404040404040439010404040404040404040401330133
38390133013304040404043A003A003A392F3936330104040404040001070B16
382E0339013304040404043A330F07050C382E03390104040404040001170E08
0A392F02383304040404043A33121319090A392F0238330404040400011D1114
1A0D382E033901040404043A332A1E21152206382E03390104040400012C2629
201018392F3938330404043A332524271C1F003A3930023833040400012B2D23
28001B00383132390104043A330133013301000135383138330404003A003A00
3A003A3534393837010404040404040404040404040404040404}
end
end
object Panel4: TPanel
Left = 684
Top = 59
Width = 34
Height = 311
Align = alRight
Color = clWhite
TabOrder = 2
object sbProximo: TSpeedButton
Left = 5
Top = 83
Width = 25
Height = 35
Hint = 'Pr'#243'ximo registro'
Enabled = False
Flat = True
Glyph.Data = {
76060000424D7606000000000000360400002800000018000000180000000100
0800000000004002000000000000000000000001000000000000FFFFFF00FFE6
E600FEE5E500FCE3E300FBE1E100F9DFE000F7DDDE00F7DDDD00F5DBDB00F4DB
DB00F2D9D900E6D9D900F0D6D700EED4D400EBD2D200E9D0D000E9CFD000E7CD
CD00E5CBCB00E3C9C900E0C7C700DEC4C400DCC2C200CCC0C000D9C0BF00D7BE
BD00D4BBBB00D3B9B900D0B7B700CFB5B500CEB4B400CCB3B300C9B0B000C7AE
AE00C5ACAC00C3AAAA00C1A8A800C1A7A700BFA5A500BDA3A300BCA3A300BAA0
A100BAA1A000B89E9E00B59C9C00B39A9A00AF969600AD949400A88F8F00A68D
8D00A18888009F8686009B8382009A818100998080006633330000000000C0C0
C000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000393939393939
3939393939393939393939393939393939393939393939393939393939393939
3939393939393939393939393939393939393939393939393939393939393939
3939393939393939393939393939393939393939393939393939393939393939
3939393939393939393939393939393939393939393939393939393939003939
3939393939393939393939393939393939393939000037393939393939393939
39393939393939393939390000370D3839393939393939393939393939393939
39390000370D260D383939393939393939393939393939393900003706260D2E
1138393939393939393939393939393900003706260D2C112E15383939393939
3939393939393900003705210D2B112E15311938393939393939393939390000
3706210D261038143019331D383939393939393939000037012106260D383938
18331D331D38393939393939000037012106260D3839393938193321331D3839
393939393937011D05250C3839393939393821331D170B383939393939393801
25063839393939393939381D170B383939393939393939380638393939393939
393939380B383939393939393939393938393939393939393939393938393939
3939393939393939393939393939393939393939393939393939393939393939
3939393939393939393939393939393939393939393939393939393939393939
3939393939393939393939393939393939393939393939393939393939393939
3939393939393939393939393939393939393939393939393939}
ParentShowHint = False
ShowHint = True
OnClick = sbProximoClick
end
object sbUltimo: TSpeedButton
Left = 5
Top = 122
Width = 25
Height = 35
Hint = #218'ltimo registro'
Enabled = False
Flat = True
Glyph.Data = {
96010000424D9601000000000000760000002800000018000000180000000100
0400000000002001000000000000000000001000000000000000FFFFFF006130
30006E3D3D00916161009E6E6E00C2919100CF9E9E00C0C0C000000000000000
0000000000000000000000000000000000000000000000000000777777777777
7777777777777777777777777777777777777777777777777777777777777777
7777777777777777777777777777777077777777777777777777770027777777
7777777777777002327777777777777777770023432777777777777777700234
3432777777777777770023434343277777777777700234343434327777777777
0025656565656547777777700256565656565654777777772121212121212121
2777777777777777777777777777777000000000000000007777777034343434
3434343617777770456565656565656527777770365656565656565617777770
4565656565656565277777771212121212121212177777777777777777777777
7777777777777777777777777777777777777777777777777777}
ParentShowHint = False
ShowHint = True
OnClick = sbUltimoClick
end
object sbAnterior: TSpeedButton
Left = 5
Top = 44
Width = 25
Height = 35
Hint = 'Registro anterior'
Enabled = False
Flat = True
Glyph.Data = {
76060000424D7606000000000000360400002800000018000000180000000100
0800000000004002000000000000000000000001000000000000FFFFFF00FEE5
E400FDE3E300FBE1E100F9DFE000F7DEDD00F4DBDB00F2D9D900E6D9D900F0D7
D700EED4D400EBD2D200E9CFCF00E7CECD00E5CBCB00E3C9C900E0C6C700DEC4
C500DBC2C200D9C0C000CDC0C000CCC0C000D7BDBD00D5BBBB00D3B9B900D1B7
B700CFB6B500CFB5B500CDB4B400CCB3B300C7AEAE00C6ACAC00C1A8A800BFA6
A600BAA0A100B89E9E00B39A9A00B1989800AD949400AA919100A68D8D00A38A
8A009F8686009D8484009C8283009A818100998080006633330000000000C0C0
C000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000313131313131
3131313131313131313131313131313131313131313131313131313131313131
3131313131313131313131313131313131313131313131313131313131313131
3131313131313131313131313131313131313131313131313131313131313131
3131313131313131313131313131313131313131313131003131313131313131
313131003131313131313131313100002F31313131313131313100002F313131
313131313100002F01303131313131313100002F1A3031313131313100002F01
1E0530313131313100002F1A2A1A303131313131312F011E05210A3031313100
002F1E2A1A1408303131313131313004210A230D303100002F1E2A1A14083031
313131313131313005210D241130002F1A2A1A16083031313131313131313131
300A240D26162F1A2A1A140830313131313131313131313131300D2611281A2A
1A1408303131313131313131313131313131301128162A1A1408303131313131
313131313131313131313130162A1A1408303131313131313131313131313131
3131313130191408303131313131313131313131313131313131313131300830
3131313131313131313131313131313131313131313130313131313131313131
3131313131313131313131313131313131313131313131313131313131313131
3131313131313131313131313131313131313131313131313131313131313131
3131313131313131313131313131313131313131313131313131313131313131
3131313131313131313131313131313131313131313131313131}
ParentShowHint = False
ShowHint = True
OnClick = sbAnteriorClick
end
object sbPrimeiro: TSpeedButton
Left = 5
Top = 6
Width = 25
Height = 35
Hint = 'Primeiro registro'
Enabled = False
Flat = True
Glyph.Data = {
96010000424D9601000000000000760000002800000018000000180000000100
0400000000002001000000000000000000001000000000000000FFFFFF006130
30006E3D3D00916161009E6E6E00C2919100CF9E9E00C0C0C000000000000000
0000000000000000000000000000000000000000000000000000777777777777
7777777777777777777777777777777777777777777777777777777777777770
0000000000000000777777703434343434343436177777704565656565656565
2777777036565656565656561777777045656565656565652777777712121212
1212121217777777777777777777777777777777777777777777777777777770
0000000000000000777777771212121212121212177777777143434343434341
7777777777143434343656177777777777714343436561777777777777771434
3656177777777777777771436561777777777777777777165617777777777777
7777777161777777777777777777777717777777777777777777777777777777
7777777777777777777777777777777777777777777777777777}
ParentShowHint = False
ShowHint = True
OnClick = sbPrimeiroClick
end
end
end
end
object dsCadastro: TDataSource
AutoEdit = False
OnDataChange = dsCadastroDataChange
Left = 428
Top = 153
end
object dsConsultar: TDataSource
DataSet = cdsConsultar
OnDataChange = dsConsultarDataChange
Left = 164
Top = 194
end
object datasetConsultar: TSQLDataSet
Params = <>
Left = 244
Top = 194
end
object dspConsultar: TDataSetProvider
DataSet = datasetConsultar
Options = [poAllowCommandText]
Left = 324
Top = 194
end
object cdsConsultar: TClientDataSet
Aggregates = <>
Params = <>
ProviderName = 'dspConsultar'
Left = 396
Top = 194
end
end
| 54.530713 | 119 | 0.769037 |
4744e9c2265993650e8bbc302d3bb6373ed9a6b2 | 892 | dfm | Pascal | Source/Source/Tools/AnimationSeekBar/TDlgSourceTree.dfm | uvbs/FullSource | 07601c5f18d243fb478735b7bdcb8955598b9a90 | [
"MIT"
]
| 2 | 2018-07-26T07:58:14.000Z | 2019-05-31T14:32:18.000Z | Jx3Full/Source/Source/Tools/AnimationSeekBar/TDlgSourceTree.dfm | RivenZoo/FullSource | cfd7fd7ad422fd2dae5d657a18839c91ff9521fd | [
"MIT"
]
| null | null | null | Jx3Full/Source/Source/Tools/AnimationSeekBar/TDlgSourceTree.dfm | RivenZoo/FullSource | cfd7fd7ad422fd2dae5d657a18839c91ff9521fd | [
"MIT"
]
| 5 | 2021-02-03T10:25:39.000Z | 2022-02-23T07:08:37.000Z | object DlgSourceView: TDlgSourceView
Left = -560
Top = 78
Caption = #36164#28304#27983#35272#22120
ClientHeight = 613
ClientWidth = 421
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
object Button1: TButton
Left = 336
Top = 16
Width = 75
Height = 25
Caption = #21047#26032
TabOrder = 0
OnClick = Button1Click
end
object FileTree: TTreeView
Left = 16
Top = 16
Width = 305
Height = 585
Indent = 19
TabOrder = 1
OnChange = FileTreeChange
end
object Button_OK: TButton
Left = 336
Top = 48
Width = 75
Height = 25
Caption = #30830#23450
TabOrder = 2
OnClick = Button_OKClick
end
end
| 20.272727 | 43 | 0.608744 |
f1663e4aa1b695f8046a0421f98de09ea57ab861 | 22,852 | pas | Pascal | library/fhir/fhir_factory.pas | atkins126/fhirserver | b6c2527f449ba76ce7c06d6b1c03be86cf4235aa | [
"BSD-3-Clause"
]
| null | null | null | library/fhir/fhir_factory.pas | atkins126/fhirserver | b6c2527f449ba76ce7c06d6b1c03be86cf4235aa | [
"BSD-3-Clause"
]
| null | null | null | library/fhir/fhir_factory.pas | atkins126/fhirserver | b6c2527f449ba76ce7c06d6b1c03be86cf4235aa | [
"BSD-3-Clause"
]
| null | null | null | unit fhir_factory;
{
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, Classes,
fsl_base, fsl_utilities, fsl_collections, fsl_json, fsl_xml, fsl_stream, fsl_http, fsl_npm_cache,
fsl_ucum, fhir_objects, fhir_parser, fhir_narrative, fhir_pathengine, fhir_common, fhir_xhtml, fhir_elementmodel, fhir_client;
type
TFhirReferenceValidationPolicy = (rvpIGNORE, rvpCHECK_VALID);
const
TFhirReferenceValidationPolicyCheckExists = [rvpCHECK_VALID];
TFhirReferenceValidationPolicyCheckType = [];
TFhirReferenceValidationPolicyCheckValid = [];
type
TFHIRWorkerContextWithFactory = class;
TBestPracticeWarningLevel = (bpwlIgnore, bpwlHint, bpwlWarning, bpwlError);
TCheckDisplayOption = (cdoIgnore, cdopCheck, cdoCheckCaseAndSpace, cdoCheckCase, cdoCheckSpace);
TResourceIdStatus = (risOptional, risRequired, risProhibited);
TFHIRValidatorContext = class (TFslObject)
private
FCheckDisplay: TCheckDisplayOption;
FBPWarnings: TBestPracticeWarningLevel;
FSuppressLoincSnomedMessages: boolean;
FResourceIdRule: TResourceIdStatus;
FIsAnyExtensionsAllowed: boolean;
FIssues : TFslList<TFhirOperationOutcomeIssueW>;
Fowned : TFslList<TFslObject>;
FOperationDescription : String;
procedure SetIssues(const Value: TFslList<TFhirOperationOutcomeIssueW>);
protected
function sizeInBytesV : cardinal; override;
public
constructor Create; override;
destructor Destroy; override;
property CheckDisplay : TCheckDisplayOption read FCheckDisplay write FCheckDisplay;
property BPWarnings: TBestPracticeWarningLevel read FBPWarnings write FBPWarnings;
property SuppressLoincSnomedMessages: boolean read FSuppressLoincSnomedMessages write FSuppressLoincSnomedMessages;
property ResourceIdRule: TResourceIdStatus read FResourceIdRule write FResourceIdRule;
property IsAnyExtensionsAllowed: boolean read FIsAnyExtensionsAllowed write FIsAnyExtensionsAllowed;
property OperationDescription : String read FOperationDescription write FOperationDescription;
property owned : TFslList<TFslObject> read FOwned;
property Issues : TFslList<TFhirOperationOutcomeIssueW> read FIssues write SetIssues;
end;
TValidatorProgressEvent = procedure (sender : TObject; message : String) of object;
TFHIRValidatorV = class abstract(TFslObject)
private
FOnProgress : TValidatorProgressEvent;
FContext : TFHIRWorkerContextWithFactory;
protected
procedure doProgress(path : String);
public
constructor Create(context: TFHIRWorkerContextWithFactory); virtual;
destructor Destroy; override;
property Context : TFHIRWorkerContextWithFactory read FContext;
property OnProgress : TValidatorProgressEvent read FOnProgress write FOnProgress;
procedure validate(ctxt : TFHIRValidatorContext; obj: TJsonObject); overload; virtual; abstract;
procedure validate(ctxt : TFHIRValidatorContext; obj: TJsonObject; profile: String); overload; virtual; abstract;
procedure validate(ctxt : TFHIRValidatorContext; element: TMXmlElement); overload; virtual; abstract;
procedure validate(ctxt : TFHIRValidatorContext; element: TMXmlElement; profile: String); overload; virtual; abstract;
procedure validate(ctxt : TFHIRValidatorContext; document: TMXmlDocument); overload; virtual; abstract;
procedure validate(ctxt : TFHIRValidatorContext; document: TMXmlDocument; profile: String); overload; virtual; abstract;
procedure validate(ctxt : TFHIRValidatorContext; source : TFslBuffer; format : TFHIRFormat); overload; virtual; abstract;
procedure validate(ctxt : TFHIRValidatorContext; source : TFslBuffer; format : TFHIRFormat; profile : String); overload; virtual; abstract;
procedure validate(ctxt : TFHIRValidatorContext; resource : TFhirResourceV); overload; virtual; abstract;
procedure validate(ctxt : TFHIRValidatorContext; resource : TFhirResourceV; profile : string); overload; virtual; abstract;
function describe(ctxt : TFHIRValidatorContext): TFHIROperationOutcomeW; virtual; abstract;
end;
TFHIRValidatorClass = class of TFHIRValidatorV;
TFHIRFactory = class abstract (TFslObject)
public
function link : TFHIRFactory; overload;
function version : TFHIRVersion; virtual;
function versionString : String; virtual;
function versionName : String; virtual; abstract;
function corePackage : String; virtual; abstract;
function txPackage : String; virtual; abstract;
function txSupportPackage : String; virtual; abstract;
function specUrl : String; virtual; abstract;
function description : String; virtual;
function resourceNames : TArray<String>; virtual; abstract;
function canonicalResources : TArray<String>; virtual; abstract;
function isResourceName(name : String) : boolean; virtual;
function resCategory(name: String) : TTokenCategory; virtual; abstract;
function makeParser(worker : TFHIRWorkerContextV; format : TFHIRFormat; const lang : THTTPLanguages) : TFHIRParser; virtual; abstract;
function makeComposer(worker : TFHIRWorkerContextV; format : TFHIRFormat; const lang : THTTPLanguages; style: TFHIROutputStyle) : TFHIRComposer; virtual; abstract;
function makeValidator(worker : TFHIRWorkerContextV) : TFHIRValidatorV; virtual; abstract;
function makeGenerator(worker : TFHIRWorkerContextV) : TFHIRNarrativeGeneratorBase; virtual; abstract;
function makePathEngine(worker : TFHIRWorkerContextV; ucum : TUcumServiceInterface) : TFHIRPathEngineV; virtual; abstract;
function makeElementModelManager : TFHIRBaseMMManager; virtual; abstract;
function createFromProfile(worker : TFHIRWorkerContextV; profile : TFhirStructureDefinitionW) : TFHIRResourceV; virtual; abstract;
function createPropertyList(name : String; bPrimitiveValues : Boolean) : TFHIRPropertyList; Virtual;
function makeClient(worker : TFHIRWorkerContextV; url : String; fmt : TFHIRFormat) : TFhirClientV; overload;
function makeClient(worker : TFHIRWorkerContextV; url : String; kind : TFHIRClientType; fmt : TFHIRFormat) : TFhirClientV; overload;
function makeClient(worker : TFHIRWorkerContextV; url : String; kind : TFHIRClientType; fmt : TFHIRFormat; timeout : cardinal) : TFhirClientV; overload;
function makeClient(worker : TFHIRWorkerContextV; url : String; kind : TFHIRClientType; fmt : TFHIRFormat; timeout : cardinal; proxy : String) : TFhirClientV; overload; virtual; abstract;// because using indy is necessary if you're writing a server, or unixready code
function makeClientThreaded(worker : TFHIRWorkerContextV; internal : TFhirClientV; event : TThreadManagementEvent) : TFhirClientV; overload; virtual; abstract;
function makeClientInt(worker : TFHIRWorkerContextV; const lang : THTTPLanguages; comm : TFHIRClientCommunicator) : TFhirClientV; overload; virtual; abstract;
function getXhtml(res : TFHIRResourceV) : TFHIRXhtmlNode; virtual; abstract;
procedure setXhtml(res : TFHIRResourceV; x : TFHIRXhtmlNode); virtual; abstract;
function resetXhtml(r : TFHIRResourceV) : TFHIRXhtmlNode; virtual; abstract;
function getContained(r : TFHIRResourceV) : TFslList<TFHIRResourceV>; virtual; abstract;
procedure markWithTag(r : TFHIRResourceV; systemUri, code, display : String); virtual; abstract;
procedure checkNoModifiers(res : TFHIRObject; method, param : string; allowed : TArray<String> = nil); virtual; abstract;
function buildOperationOutcome(const lang : THTTPLanguages; e : exception; issueCode : TFhirIssueType = itNull) : TFhirResourceV; overload; virtual; abstract;
Function buildOperationOutcome(const lang : THTTPLanguages; message : String; issueCode : TFhirIssueType = itNull) : TFhirResourceV; overload; virtual; abstract;
function makeByName(const name : String) : TFHIRObject; virtual; abstract;
function makeResource(const name : String) : TFHIRResourceV;
function makeBoolean(b : boolean): TFHIRObject; virtual; abstract;
function makeCode(s : string) : TFHIRObject; virtual; abstract;
function makeCoding(systemUri, code : String) : TFHIRObject; overload;
function makeCoding(systemUri, code, display : String) : TFHIRObject; overload;
function makeCoding(systemUri, version, code, display : String) : TFHIRObject; overload; virtual; abstract;
function makeString(s : string) : TFHIRObject; virtual; abstract;
function makeInteger(s : string) : TFHIRObject; virtual; abstract;
function makeDecimal(s : string) : TFHIRObject; virtual; abstract;
function makeBase64Binary(s : string) : TFHIRObject; virtual; abstract;// must DecodeBase64
function makeBinary(content : TBytes; contentType : String) : TFHIRResourceV; virtual; abstract;
function makeParamsFromForm(s : TStream) : TFHIRResourceV; virtual; abstract;
function makeDateTime(dt : TFslDateTime) : TFHIRObject; virtual; abstract;
function makeDtFromForm(part : TMimePart; const lang : THTTPLanguages; name : String; type_ : string) : TFHIRXVersionElementWrapper; virtual; abstract;
function makeDuration(dt : TDateTime) : TFHIRObject; virtual; abstract;
function makeBundle(list : TFslList<TFHIRResourceV>) : TFHIRBundleW; virtual; abstract;
function makeParameters : TFHIRParametersW; virtual; abstract;
function makeTerminologyCapablities : TFhirTerminologyCapabilitiesW; virtual; abstract;
function makeIssue(level : TIssueSeverity; issue: TFhirIssueType; location, message: String) : TFhirOperationOutcomeIssueW; virtual; abstract;
function wrapCapabilityStatement(r : TFHIRResourceV) : TFHIRCapabilityStatementW; virtual; abstract;
function wrapStructureDefinition(r : TFHIRResourceV) : TFhirStructureDefinitionW; virtual; abstract;
function wrapValueSet(r : TFHIRResourceV) : TFhirValueSetW; virtual; abstract;
function wrapCodeSystem(r : TFHIRResourceV) : TFhirCodeSystemW; virtual; abstract;
function wrapConceptMap(r : TFHIRResourceV) : TFhirConceptMapW; virtual; abstract;
function wrapExtension(o : TFHIRObject) : TFhirExtensionW; virtual; abstract;
function wrapCoding(o : TFHIRObject) : TFhirCodingW; virtual; abstract;
function wrapCodeableConcept(o : TFHIRObject) : TFhirCodeableConceptW; virtual; abstract;
function wrapOperationOutcome(r : TFHIRResourceV) : TFhirOperationOutcomeW; virtual; abstract;
function wrapBundle(r : TFHIRResourceV) : TFhirBundleW; virtual; abstract;
function wrapParams(r : TFHIRResourceV) : TFHIRParametersW; virtual; abstract;
function wrapMeta(r : TFHIRResourceV) : TFhirMetaW; overload; virtual; abstract; // speecial: does not take ownership
function wrapMeta(r : TFHIRObject) : TFhirMetaW; overload; virtual; abstract;
function wrapBinary(r : TFHIRResourceV) : TFhirBinaryW; virtual; abstract;
function wrapAuditEvent(r : TFHIRResourceV) : TFhirAuditEventW; virtual; abstract;
function wrapSubscription(r : TFHIRResourceV) : TFhirSubscriptionW; virtual; abstract;
function wrapSubscriptionTopic(r : TFHIRResourceV) : TFhirSubscriptionTopicW; virtual; abstract;
function wrapObservation(r : TFHIRResourceV) : TFhirObservationW; virtual; abstract;
function wrapQuantity(r : TFHIRObject) : TFhirQuantityW; virtual; abstract;
function wrapPeriod(r : TFHIRObject) : TFhirPeriodW; virtual; abstract;
function wrapGroup(r : TFHIRResourceV) : TFhirGroupW; virtual; abstract;
function wrapPatient(r : TFHIRResourceV) : TFhirPatientW; virtual; abstract;
function wrapEncounter(r : TFHIRResourceV) : TFhirEncounterW; virtual; abstract;
function wrapBundleEntry(o : TFHIRObject) : TFhirBundleEntryW; virtual; abstract;
function wrapNamingSystem(o : TFHIRResourceV) : TFHIRNamingSystemW; virtual; abstract;
function wrapStructureMap(o : TFHIRResourceV) : TFHIRStructureMapW; virtual; abstract;
function wrapEventDefinition(o : TFHIRResourceV) : TFHIREventDefinitionW; virtual; abstract;
function wrapConsent(o : TFHIRResourceV) : TFHIRConsentW; virtual; abstract;
function wrapTestScript(o : TFHIRResourceV) : TFHIRTestScriptW; virtual; abstract;
function wrapProvenance(o : TFHIRResourceV) : TFhirProvenanceW; virtual; abstract;
function makeOpReqLookup : TFHIRLookupOpRequestW; virtual; abstract;
function makeOpRespLookup : TFHIRLookupOpResponseW; virtual; abstract;
function makeOpReqSubsumes : TFHIRSubsumesOpRequestW; virtual; abstract;
function makeOpRespSubsumes : TFHIRSubsumesOpResponseW; virtual; abstract;
function makeValueSetContains : TFhirValueSetExpansionContainsW; virtual; abstract;
function parseJson(worker : TFHIRWorkerContextV; bytes : TBytes) : TFHIRResourceV;
function parseXml(worker : TFHIRWorkerContextV; bytes : TBytes) : TFHIRResourceV;
end;
TFHIRVersionFactories = class (TFslObject)
private
FVersionArray : array [TFHIRVersion] of TFHIRFactory;
function getHasVersion(v: TFHIRVersion): boolean;
function getVersion(v: TFHIRVersion): TFHIRFactory;
procedure SetVersion(v: TFHIRVersion; const Value: TFHIRFactory);
public
constructor Create; override;
destructor Destroy; override;
function link : TFHIRVersionFactories; overload;
property version[v : TFHIRVersion] : TFHIRFactory read getVersion write SetVersion; default;
property hasVersion[v : TFHIRVersion] : boolean read getHasVersion;
end;
TExpansionOperationOption = (expOptLimited);
TExpansionOperationOptionSet = set of TExpansionOperationOption;
TFHIRWorkerContextWithFactory = class (TFHIRWorkerContextV)
private
FFactory : TFHIRFactory;
FLoadInfo : TPackageLoadingInformation;
protected
function sizeInBytesV : cardinal; override;
public
constructor Create(factory : TFHIRFactory); overload; virtual;
destructor Destroy; override;
function link : TFHIRWorkerContextWithFactory;
property Factory : TFHIRFactory read FFactory;
property LoadInfo : TPackageLoadingInformation read FLoadInfo;
procedure loadResourceJson(rType, id : String; json : TStream); override;
procedure seeResource(res : TFHIRResourceV); overload; virtual; abstract;
procedure dropResource(rtpe, id : String); overload; virtual; abstract;
procedure setNonSecureTypes(names : Array of String); virtual; abstract;
function getResourceNames : TFslStringSet; virtual; abstract;
function fetchResource(rType : String; url : String) : TFhirResourceV; overload; virtual; abstract;
function expand(vs : TFhirValueSetW; options : TExpansionOperationOptionSet = []) : TFHIRValueSetW; overload; virtual; abstract;
function supportsSystem(systemUri, version : string) : boolean; overload; virtual; abstract;
function validateCode(systemUri, version, code, display : String) : TValidationResult; overload; virtual; abstract;
function validateCode(systemUri, version, code : String; vs : TFhirValueSetW) : TValidationResult; overload; virtual; abstract;
function allResourceNames : TArray<String>; overload; virtual; abstract;
function nonSecureResourceNames : TArray<String>; overload; virtual; abstract;
procedure listStructures(list : TFslList<TFhirStructureDefinitionW>); overload; virtual; abstract;
function getProfileLinks(non_resources : boolean) : TFslStringMatch; virtual; abstract;
procedure LoadingFinished; virtual;
function getSearchParameter(resourceType, name : String) : TFHIRResourceV; virtual; abstract;
end;
implementation
{ TFHIRFactory }
function TFHIRFactory.description: String;
begin
result := 'Unknown version';
end;
function TFHIRFactory.isResourceName(name: String): boolean;
var
s : String;
begin
result := false;
for s in ResourceNames do
if s = name then
exit(true);
end;
function TFHIRFactory.link: TFHIRFactory;
begin
result := TFHIRFactory(inherited link);
end;
function TFHIRFactory.createPropertyList(name : String; bPrimitiveValues : Boolean) : TFHIRPropertyList;
var
o : TFHIRObject;
begin
o := makeByName(name);
try
result := o.createPropertyList(bPrimitiveValues);
finally
o.Free;
end;
end;
function TFHIRFactory.makeClient(worker : TFHIRWorkerContextV; url : String; fmt : TFHIRFormat) : TFhirClientV;
begin
result := makeClient(worker, url, fctCrossPlatform, fmt, 0, '');
end;
function TFHIRFactory.makeClient(worker : TFHIRWorkerContextV; url : String; kind : TFHIRClientType; fmt : TFHIRFormat) : TFhirClientV;
begin
result := makeClient(worker, url, kind, fmt, 0, '');
end;
function TFHIRFactory.makeClient(worker : TFHIRWorkerContextV; url : String; kind : TFHIRClientType; fmt : TFHIRFormat; timeout : cardinal) : TFhirClientV;
begin
result := makeClient(worker, url, kind, fmt, timeout, '');
end;
function TFHIRFactory.version: TFHIRVersion;
begin
result := fhirVersionUnknown;
end;
function TFHIRFactory.versionString: String;
begin
result := '??';
end;
function TFHIRFactory.makeResource(const name: String): TFHIRResourceV;
begin
result := makeByName(name) as TFHIRResourceV;
end;
function TFHIRFactory.parseJson(worker: TFHIRWorkerContextV; bytes : TBytes): TFHIRResourceV;
var
parser : TFHIRParser;
begin
parser := makeParser(worker, ffJson, THTTPlanguages.Create('en'));
try
result := parser.parseResource(bytes);
finally
parser.Free;
end;
end;
function TFHIRFactory.parseXml(worker: TFHIRWorkerContextV; bytes : TBytes): TFHIRResourceV;
var
parser : TFHIRParser;
begin
parser := makeParser(worker, ffXml, THTTPlanguages.Create('en'));
try
result := parser.parseResource(bytes);
finally
parser.Free;
end;
end;
function TFHIRFactory.makeCoding(systemUri, code, display: String): TFHIRObject;
begin
result := makeCoding(systemUri, '', code, display);
end;
function TFHIRFactory.makeCoding(systemUri, code: String): TFHIRObject;
begin
result := makeCoding(systemUri, '', code, '');
end;
{ TFHIRVersionFactories }
constructor TFHIRVersionFactories.Create;
var
v : TFHIRVersion;
begin
inherited;
for v in FHIR_ALL_VERSIONS do
FVersionArray[v] := nil;
end;
destructor TFHIRVersionFactories.Destroy;
var
v : TFHIRVersion;
begin
for v in FHIR_ALL_VERSIONS do
FVersionArray[v].free;
inherited;
end;
function TFHIRVersionFactories.getHasVersion(v: TFHIRVersion): boolean;
begin
result := FVersionArray[v] <> nil;
end;
function TFHIRVersionFactories.getVersion(v: TFHIRVersion): TFHIRFactory;
begin
result := FVersionArray[v];
end;
function TFHIRVersionFactories.link: TFHIRVersionFactories;
begin
result := TFHIRVersionFactories(inherited link);
end;
procedure TFHIRVersionFactories.SetVersion(v: TFHIRVersion; const Value: TFHIRFactory);
begin
FVersionArray[v].free;
FVersionArray[v] := value;
end;
{ TFHIRWorkerContextWithFactory }
constructor TFHIRWorkerContextWithFactory.Create(factory: TFHIRFactory);
begin
inherited Create;
FFactory := factory;
FLoadInfo := TPackageLoadingInformation.Create(FFactory.versionString);
FLoadInfo.OnLoadEvent := loadResourceJson;
end;
destructor TFHIRWorkerContextWithFactory.Destroy;
begin
FLoadInfo.Free;
FFactory.free;
inherited;
end;
function TFHIRWorkerContextWithFactory.link: TFHIRWorkerContextWithFactory;
begin
result := TFHIRWorkerContextWithFactory(inherited link);
end;
procedure TFHIRWorkerContextWithFactory.LoadingFinished;
begin
// nothing here
end;
procedure TFHIRWorkerContextWithFactory.loadResourceJson(rtype, id: String; json: TStream);
var
p : TFHIRParser;
begin
p := Factory.makeParser(self.link, ffJson, THTTPLanguages.create('en'));
try
p.source := json;
p.Parse;
SeeResource(p.resource);
finally
p.Free;
end;
end;
function TFHIRWorkerContextWithFactory.sizeInBytesV : cardinal;
begin
result := inherited sizeInBytesV;
inc(result, FFactory.sizeInBytes);
inc(result, FLoadInfo.sizeInBytes);
end;
{ TFHIRValidatorContext }
constructor TFHIRValidatorContext.create;
begin
inherited;
FOwned := TFslList<TFslObject>.create;
FIssues := TFslList<TFhirOperationOutcomeIssueW>.create;
end;
destructor TFHIRValidatorContext.destroy;
begin
FOwned.Free;
FIssues.Free;
inherited;
end;
procedure TFHIRValidatorContext.SetIssues(const Value: TFslList<TFhirOperationOutcomeIssueW>);
begin
FIssues.Free;
FIssues := Value;
end;
function TFHIRValidatorContext.sizeInBytesV : cardinal;
begin
result := inherited sizeInBytesV;
inc(result, FIssues.sizeInBytes);
inc(result, Fowned.sizeInBytes);
inc(result, (FOperationDescription.length * sizeof(char)) + 12);
end;
{ TFHIRValidatorV }
constructor TFHIRValidatorV.Create(context: TFHIRWorkerContextWithFactory);
begin
inherited create;
FContext := context;
end;
destructor TFHIRValidatorV.Destroy;
begin
FContext.Free;
inherited;
end;
procedure TFHIRValidatorV.doProgress(path: String);
begin
if assigned(FOnProgress) then
FOnProgress(self, path);
end;
end.
| 43.946154 | 273 | 0.760196 |
478636b23edc19d42f835dad673828190e09a7eb | 21,035 | pas | Pascal | windows/src/ext/jedi/jvcl/tests/archive/jvcl/Archive/ScheduleEditor.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 219 | 2017-06-21T03:37:03.000Z | 2022-03-27T12:09:28.000Z | windows/src/ext/jedi/jvcl/tests/archive/jvcl/Archive/ScheduleEditor.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 4,451 | 2017-05-29T02:52:06.000Z | 2022-03-31T23:53:23.000Z | windows/src/ext/jedi/jvcl/tests/archive/jvcl/Archive/ScheduleEditor.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 72 | 2017-05-26T04:08:37.000Z | 2022-03-03T10:26:20.000Z | {$I JEDI.INC}
unit ScheduleEditor;
interface
uses
SysUtils, Classes, Controls, Forms, StdCtrls, ComCtrls, ExtCtrls, AppEvnts,
JclSchedule;
type
TFrmScheduleEditor = class(TForm)
pnlStartInfo: TPanel;
lblStartDate: TLabel;
lblStartTime: TLabel;
lblStartCaption: TLabel;
dtpStartDate: TDateTimePicker;
dtpStartTime: TDateTimePicker;
pnlEndInfo: TPanel;
lblEndCaption: TLabel;
rbInfinite: TRadioButton;
rbTriggerCount: TRadioButton;
rbDayCount: TRadioButton;
rbDate: TRadioButton;
lblEndTime: TLabel;
dtpEndDate: TDateTimePicker;
dtpEndTime: TDateTimePicker;
edEventCount: TEdit;
edDayCount: TEdit;
pnlRecurringInfo: TPanel;
lblScheduleType: TLabel;
rbSingleShot: TRadioButton;
rbDaily: TRadioButton;
rbWeekly: TRadioButton;
rbMonthly: TRadioButton;
rbYearly: TRadioButton;
bvlSeparation: TBevel;
pnlDailySchedule: TPanel;
lblDailyCaption: TLabel;
rbDailyEveryWeekDay: TRadioButton;
rbDailyInterval: TRadioButton;
edDailyInterval: TEdit;
lblDailyIntervalUnit: TLabel;
pnlWeeklySchedule: TPanel;
lblWeeklyCaption: TLabel;
lblWeeklyInterval: TLabel;
edWeeklyInterval: TEdit;
lblWeeklyInterval2: TLabel;
cbWeeklyMon: TCheckBox;
cbWeeklyTue: TCheckBox;
cbWeeklyWed: TCheckBox;
cbWeeklyThu: TCheckBox;
cbWeeklyFri: TCheckBox;
cbWeeklySat: TCheckBox;
cbWeeklySun: TCheckBox;
pnlMonthlySchedule: TPanel;
lblMonthlyCaption: TLabel;
rbMonthlyDay: TRadioButton;
edMonthlyEveryMonth: TEdit;
lblMonthlyDayIntervalSuffix: TLabel;
rbMonthlyEveryIndex: TRadioButton;
cbMonthlyIndexValue: TComboBox;
cbMonthlyIndexType: TComboBox;
edMonthlyDay: TEdit;
lblMontlhyDayInterval: TLabel;
lblMonthlyIndexInterval: TLabel;
edMonthlyIndexInterval: TEdit;
lblMonthlyIndexIntervalSuffix: TLabel;
bvlScheduleType: TBevel;
pnlYearlySchedule: TPanel;
lblYearlyCaption: TLabel;
lblYearlyIntervalSuffix: TLabel;
lblYearlyDateOf: TLabel;
lblYearlyIndexInterval: TLabel;
lblYearlyIndexIntervalSuffix: TLabel;
rbYearlyDate: TRadioButton;
edYearlyDateInterval: TEdit;
rbYearlyIndex: TRadioButton;
cbYearlyIndexValue: TComboBox;
cbYearlyIndexKind: TComboBox;
edYearlyDateDay: TEdit;
edYearlyIndexInterval: TEdit;
cbYearlyDateMonth: TComboBox;
lblYearlyDateInterval: TLabel;
lblYearlyIndexMonth: TLabel;
cbYearlyIndexMonth: TComboBox;
bvlDailyFreq: TBevel;
pnlDailyFreq: TPanel;
lblDailyFreq: TLabel;
rbFreqOneshot: TRadioButton;
dtpDayFreqOneshot: TDateTimePicker;
rbFreqInterval: TRadioButton;
edFreqInterval: TEdit;
cbFreqIntervalUnit: TComboBox;
lblFreqFrom: TLabel;
dtpFreqFrom: TDateTimePicker;
lblFreqTo: TLabel;
dtpFreqTo: TDateTimePicker;
Bevel1: TBevel;
Bevel2: TBevel;
AppEvents: TApplicationEvents;
gbTestSettings: TGroupBox;
cxStartToday: TCheckBox;
cxCountMissedEvents: TCheckBox;
btnTest: TButton;
mmLog: TMemo;
btnOk: TButton;
btnCancel: TButton;
procedure FormCreate(Sender: TObject);
procedure btnTestClick(Sender: TObject);
procedure AppEventsIdle(Sender: TObject; var Done: Boolean);
procedure btnOkClick(Sender: TObject);
private
FTestSchedule: IJclSchedule;
FSchedule: IJclSchedule;
FBusy: Boolean;
procedure SetSchedule(Value: IJclSchedule);
procedure SelectRecurringInfoPage;
procedure UpdateDailyPageInfo;
procedure UpdateWeeklyPageInfo;
procedure UpdateMonthlyPageInfo;
procedure UpdateYearlyPageInfo;
procedure UpdateFrequencyPageInfo;
procedure UpdateEndPageInfo;
procedure UpdateTestSettings;
procedure InitSchedule(const ASchedule: IJclSchedule);
procedure ScheduleToUI(const ASchedule: IJclSchedule);
public
property Schedule: IJclSchedule read FSchedule write SetSchedule;
end;
var
FrmScheduleEditor: TFrmScheduleEditor;
implementation
{$R *.dfm}
uses
JclDateTime;
procedure DecodeTimeStampTime(const Stamp: TTimeStamp;
var ADays, AHour, AMinute, ASecond, AMSec: Word);
var
TempTime: Integer;
begin
TempTime := Stamp.Time;
AMSec := TempTime mod 1000;
TempTime := TempTime div 1000;
ASecond := TempTime mod 60;
TempTime := TempTime div 60;
AMinute := TempTime mod 60;
TempTime := TempTime div 60;
AHour := TempTime mod 24;
TempTime := TempTime div 24;
ADays := TempTime;
end;
function IndexOfRBChecked(const Controls: array of TRadioButton): Integer;
begin
Result := High(Controls);
while (Result >= 0) and not Controls[Result].Checked do
Dec(Result);
end;
procedure TFrmScheduleEditor.SetSchedule(Value: IJclSchedule);
begin
FSchedule := Value;
ScheduleToUI(FSchedule);
end;
procedure TFrmScheduleEditor.SelectRecurringInfoPage;
begin
pnlDailySchedule.Visible := rbDaily.Checked;
pnlWeeklySchedule.Visible := rbWeekly.Checked;
pnlMonthlySchedule.Visible := rbMonthly.Checked;
pnlYearlySchedule.Visible := rbYearly.Checked;
end;
procedure TFrmScheduleEditor.UpdateDailyPageInfo;
begin
edDailyInterval.Enabled := rbDailyInterval.Checked;
end;
procedure TFrmScheduleEditor.UpdateWeeklyPageInfo;
begin
end;
procedure TFrmScheduleEditor.UpdateMonthlyPageInfo;
begin
edMonthlyDay.Enabled := rbMonthlyDay.Checked;
edMonthlyEveryMonth.Enabled := rbMonthlyDay.Checked;
cbMonthlyIndexValue.Enabled := rbMonthlyEveryIndex.Checked;
cbMonthlyIndexType.Enabled := rbMonthlyEveryIndex.Checked;
edMonthlyIndexInterval.Enabled := rbMonthlyEveryIndex.Checked;
end;
procedure TFrmScheduleEditor.UpdateYearlyPageInfo;
begin
edYearlyDateDay.Enabled := rbYearlyDate.Checked;
cbYearlyDateMonth.Enabled := rbYearlyDate.Checked;
edYearlyDateInterval.Enabled := rbYearlyDate.Checked;
cbYearlyIndexValue.Enabled := rbYearlyIndex.Checked;
cbYearlyIndexKind.Enabled := rbYearlyIndex.Checked;
cbYearlyIndexMonth.Enabled := rbYearlyIndex.Checked;
edYearlyIndexInterval.Enabled := rbYearlyIndex.Checked;
end;
procedure TFrmScheduleEditor.UpdateFrequencyPageInfo;
begin
pnlDailyFreq.Visible := not rbSingleShot.Checked;
dtpDayFreqOneshot.Enabled := rbFreqOneshot.Checked;
edFreqInterval.Enabled := rbFreqInterval.Checked;
cbFreqIntervalUnit.Enabled := rbFreqInterval.Checked;
dtpFreqFrom.Enabled := rbFreqInterval.Checked;
dtpFreqTo.Enabled := rbFreqInterval.Checked;
end;
procedure TFrmScheduleEditor.UpdateEndPageInfo;
begin
pnlEndInfo.Visible := not rbSingleShot.Checked;
edEventCount.Enabled := rbTriggerCount.Checked;
edDayCount.Enabled := rbDayCount.Checked;
dtpEndDate.Enabled := rbDate.Checked;
dtpEndTime.Enabled := rbDate.Checked;
end;
procedure TFrmScheduleEditor.UpdateTestSettings;
begin
cxCountMissedEvents.Enabled := cxStartToday.Checked;
end;
procedure TFrmScheduleEditor.InitSchedule(const ASchedule: IJclSchedule);
var
TempDOW: TScheduleWeekDays;
begin
with ASchedule do
begin
RecurringType := TScheduleRecurringKind(IndexOfRBChecked([rbSingleShot, rbDaily, rbWeekly,
rbMonthly, rbYearly]));
StartDate := DateTimeToTimeStamp(Trunc(dtpStartDate.Date) + Frac(dtpStartTime.Time));
EndType := TScheduleEndKind(IndexOfRBChecked([rbInfinite, rbDate, rbTriggerCount, rbDayCount]));
if RecurringType = srkOneShot then
begin
EndType := sekDate;
EndDate := StartDate;
with ASchedule as IJclScheduleDayFrequency do
begin
StartTime := StartDate.Time;
EndTime := EndDate.Time;
Interval := 1;
end;
end
else
begin
case RecurringType of
srkDaily:
begin
with ASchedule as IJclDailySchedule do
begin
EveryWeekDay := rbDailyEveryWeekDay.Checked;
if not EveryWeekDay then
Interval := StrToInt64(edDailyInterval.Text);
end;
end;
srkWeekly:
begin
with ASchedule as IJclWeeklySchedule do
begin
TempDOW := [];
if cbWeeklyMon.Checked then
Include(TempDOW, swdMonday);
if cbWeeklyTue.Checked then
Include(TempDOW, swdTuesday);
if cbWeeklyWed.Checked then
Include(TempDOW, swdWednesday);
if cbWeeklyThu.Checked then
Include(TempDOW, swdThursday);
if cbWeeklyFri.Checked then
Include(TempDOW, swdFriday);
if cbWeeklySat.Checked then
Include(TempDOW, swdSaturday);
if cbWeeklySun.Checked then
Include(TempDOW, swdSunday);
DaysOfWeek := TempDOW;
Interval := StrToInt64(edWeeklyInterval.Text);
end;
end;
srkMonthly:
begin
with ASchedule as IJclMonthlySchedule do
begin
if rbMonthlyDay.Checked then
begin
IndexKind := sikNone;
Day := StrToInt64(edMonthlyDay.Text);
Interval := StrToInt64(edMonthlyEveryMonth.Text);
end
else
begin
IndexKind := TScheduleIndexKind(cbMonthlyIndexType.ItemIndex + 1);
if cbMonthlyIndexValue.ItemIndex > -1 then
begin
if cbMonthlyIndexValue.ItemIndex < 4 then
IndexValue := cbMonthlyIndexValue.ItemIndex + 1
else
IndexValue := sivLast;
end
else
IndexValue := StrToInt64(cbMonthlyIndexValue.Text);
Interval := StrToInt64(edMonthlyIndexInterval.Text);
end;
end;
end;
srkYearly:
begin
with ASchedule as IJclYearlySchedule do
begin
if rbYearlyDate.Checked then
begin
IndexKind := sikNone;
Day := StrToInt64(edYearlyDateDay.Text);
Month := cbYearlyDateMonth.ItemIndex + 1;
Interval := StrToInt64(edYearlyDateInterval.Text);
end
else
begin
IndexKind := TScheduleIndexKind(cbYearlyIndexKind.ItemIndex + 1);
if cbYearlyIndexValue.ItemIndex > -1 then
begin
if cbYearlyIndexValue.ItemIndex < 4 then
IndexValue := cbYearlyIndexValue.ItemIndex + 1
else
IndexValue := sivLast;
end
else
IndexValue := StrToInt64(cbYearlyIndexValue.Text);
Month := cbYearlyIndexMonth.ItemIndex + 1;
Interval := StrToInt64(edYearlyIndexInterval.Text);
end;
end;
end;
end;
with ASchedule as IJclScheduleDayFrequency do
begin
if rbFreqOneshot.Checked then
begin
StartTime := DateTimeToTimeStamp(dtpDayFreqOneshot.Time).Time;
EndTime := StartTime;
Interval := 1;
end
else
begin
StartTime := DateTimeToTimeStamp(dtpFreqFrom.Time).Time;
EndTime := DateTimeToTimeStamp(dtpFreqTo.Time).Time;
case cbFreqIntervalUnit.ItemIndex of
0: { Milliseconds }
Interval := StrToInt64(edFreqInterval.Text);
1: { Seconds }
Interval := 1000 * StrToInt64(edFreqInterval.Text);
2: { Minutes }
Interval := 60 * 1000 * StrToInt64(edFreqInterval.Text);
3: { Hours }
Interval := 60 * 60 * 1000 * StrToInt64(edFreqInterval.Text);
end;
end;
end;
case EndType of
sekDate:
EndDate := DateTimeToTimeStamp(Trunc(dtpEndDate.Date) + Frac(dtpEndTime.Time));
sekTriggerCount:
EndCount := StrToInt64(edEventCount.Text);
sekDayCount:
EndCount := StrToInt64(edDayCount.Text);
end;
end;
Reset;
end;
end;
procedure TFrmScheduleEditor.ScheduleToUI(const ASchedule: IJclSchedule);
var
TempStamp: TTimeStamp;
begin
with ASchedule do
begin
dtpStartDate.Date := Trunc(TimeStampToDateTime(StartDate));
dtpStartTime.Time := Frac(TimeStampToDateTime(StartDate));
case RecurringType of
srkOneShot:
rbSingleShot.Checked := True;
srkDaily:
begin
rbDaily.Checked := True;
with ASchedule as IJclDailySchedule do
begin
if EveryWeekDay then
rbDailyEveryWeekDay.Checked := True
else
begin
rbDailyInterval.Checked := True;
edDailyInterval.Text := IntToStr(Interval);
end;
end;
end;
srkWeekly:
begin
rbWeekly.Checked := True;
with ASchedule as IJclWeeklySchedule do
begin
cbWeeklyMon.Checked := swdMonday in DaysOfWeek;
cbWeeklyTue.Checked := swdTuesday in DaysOfWeek;
cbWeeklyWed.Checked := swdWednesday in DaysOfWeek;
cbWeeklyThu.Checked := swdThursday in DaysOfWeek;
cbWeeklyFri.Checked := swdFriday in DaysOfWeek;
cbWeeklySat.Checked := swdSaturday in DaysOfWeek;
cbWeeklySun.Checked := swdSunday in DaysOfWeek;
edWeeklyInterval.Text := IntToStr(Interval);
end
end;
srkMonthly:
begin
rbMonthly.Checked := True;
with ASchedule as IJclMonthlySchedule do
begin
case IndexKind of
sikNone:
begin
rbMonthlyDay.Checked := True;
edMonthlyDay.Text := IntToStr(Day);
edMonthlyEveryMonth.Text := IntToStr(Interval);
end;
sikDay, sikWeekDay, sikWeekendDay, sikMonday, sikTuesday,
sikWednesday, sikThursday, sikFriday, sikSaturday,
sikSunday:
begin
rbMonthlyEveryIndex.Checked := True;
if (IndexValue > 0) and (IndexValue < 5) then
cbMonthlyIndexValue.ItemIndex := IndexValue - 1
else
if IndexValue = sivLast then
cbMonthlyIndexValue.ItemIndex := 4
else
begin
cbMonthlyIndexValue.ItemIndex := -1;
cbMonthlyIndexValue.Text := IntToStr(IndexValue);
end;
cbMonthlyIndexType.ItemIndex := Ord(IndexKind) - 1;
edMonthlyIndexInterval.Text := IntToStr(Interval);
end;
else
raise ESchedule.Create('Invalid schedule settings found.');
end;
end;
end;
srkYearly:
begin
rbYearly.Checked := True;
with ASchedule as IJclYearlySchedule do
begin
case IndexKind of
sikNone:
begin
rbYearlyDate.Checked := True;
edYearlyDateDay.Text := IntToStr(Day);
cbYearlyDateMonth.ItemIndex := Month - 1;
edYearlyDateInterval.Text := IntToStr(Interval);
end;
sikDay, sikWeekDay, sikWeekendDay, sikMonday, sikTuesday,
sikWednesday, sikThursday, sikFriday, sikSaturday,
sikSunday:
begin
rbYearlyIndex.Checked := True;
if (IndexValue > 0) and (IndexValue < 5) then
cbYearlyIndexValue.ItemIndex := IndexValue - 1
else
if IndexValue = sivLast then
cbYearlyIndexValue.ItemIndex := 4
else
begin
cbYearlyIndexValue.ItemIndex := -1;
cbYearlyIndexValue.Text := IntToStr(IndexValue);
end;
cbYearlyIndexKind.ItemIndex := Ord(IndexKind) - 1;
cbYearlyIndexMonth.ItemIndex := Month - 1;
edYearlyIndexInterval.Text := IntToStr(Interval);
end;
else
raise ESchedule.Create('Invalid schedule settings found.');
end;
end;
end;
end;
case EndType of
sekNone:
rbInfinite.Checked := True;
sekDate:
begin
rbDate.Checked := True;
dtpEndDate.Date := Trunc(TimeStampToDateTime(EndDate));
dtpEndTime.Time := Frac(TimeStampToDateTime(EndDate));
end;
sekTriggerCount:
begin
rbTriggerCount.Checked := True;
edEventCount.Text := IntToStr(EndCount);
end;
sekDayCount:
begin
rbDayCount.Checked := True;
edDayCount.Text := IntToStr(EndCount);
end;
end;
if RecurringType <> srkOneShot then
begin
with ASchedule as IJclScheduleDayFrequency do
begin
rbFreqOneshot.Checked := StartTime = EndTime;
rbFreqInterval.Checked := StartTime <> EndTime;
if rbFreqOneshot.Checked then
begin
TempStamp := DateTimeToTimeStamp(Now);
TempStamp.Time := StartTime;
dtpDayFreqOneshot.Time := TimeStampToDateTime(TempStamp);
end
else
begin
TempStamp := DateTimeToTimeStamp(Now);
TempStamp.Time := StartTime;
dtpFreqFrom.Time := TimeStampToDateTime(TempStamp);
TempStamp.Time := EndTime;
dtpFreqTo.Time := TimeStampToDateTime(TempStamp);
if Interval mod (60 * 60 * 1000) = 0 then
begin
cbFreqIntervalUnit.ItemIndex := 3;
edFreqInterval.Text := IntToStr(Interval div (60 * 60 * 1000));
end
else
if Interval mod (60 * 1000) = 0 then
begin
cbFreqIntervalUnit.ItemIndex := 2;
edFreqInterval.Text := IntToStr(Interval div (60 * 1000));
end
else
if Interval mod 1000 = 0 then
begin
cbFreqIntervalUnit.ItemIndex := 1;
edFreqInterval.Text := IntToStr(Interval div 1000);
end
else
begin
cbFreqIntervalUnit.ItemIndex := 0;
edFreqInterval.Text := IntToStr(Interval);
end;
end;
end;
end;
end;
end;
procedure TFrmScheduleEditor.FormCreate(Sender: TObject);
begin
FTestSchedule := CreateSchedule;
{$IFNDEF COMPILER6_UP}
dtpStartDate.DateFormat := dfShort;
dtpEndDate.DateFormat := dfShort;
{$ELSE}
dtpStartDate.Format := 'dd-MM-yyyy';
dtpStartTime.Format := 'HH:mm:ss';
dtpEndDate.Format := 'dd-MM-yyyy';
dtpEndTime.Format := 'HH:mm:ss';
dtpDayFreqOneshot.Format := 'HH:mm:ss';
dtpFreqFrom.Format := 'HH:mm:ss';
dtpFreqTo.Format := 'HH:mm:ss';
{$ENDIF}
dtpStartDate.DateTime := Now;
dtpEndDate.DateTime := Now;
cbMonthlyIndexValue.ItemIndex := 0;
cbMonthlyIndexType.ItemIndex := 1;
cbYearlyIndexValue.ItemIndex := 0;
cbYearlyIndexKind.ItemIndex := 1;
cbYearlyDateMonth.ItemIndex := 0;
cbYearlyIndexMonth.ItemIndex := 0;
cbFreqIntervalUnit.ItemIndex := 2;
end;
procedure TFrmScheduleEditor.btnTestClick(Sender: TObject);
var
Stamp: TTimeStamp;
AYear, AMonth, ADay: Word;
ADays, AHour, AMinute, ASecond, AMSec: Word;
begin
if FBusy then
FBusy := False
else
begin
try
FBusy := True;
btnTest.Caption := 'Stop';
btnOk.Enabled := False;
btnCancel.Enabled := False;
InitSchedule(FTestSchedule);
mmLog.Lines.Clear;
if cxStartToday.Checked then
Stamp := FTestSchedule.NextEventFromNow(cxCountMissedEvents.Checked)
else
Stamp := FTestSchedule.NextEventFrom(FTestSchedule.StartDate, True);
while (Stamp.Date > 0) and FBusy do
begin
JclDateTime.DecodeDate(TimeStampToDateTime(Stamp), AYear, AMonth, ADay);
DecodeTimeStampTime(Stamp, ADays, AHour, AMinute, ASecond, AMSec);
mmLog.Lines.Add(Format('%.5d (%.4d): %.2d-%.2d-%.4d@%.2d:%.2d:%.2d.%.3d',
[FTestSchedule.TriggerCount, FTestSchedule.DayCount, ADay, AMonth,
AYear, AHour, AMinute, ASecond, AMSec]));
Application.ProcessMessages;
Stamp := FTestSchedule.NextEvent(True);
end;
finally
FBusy := False;
btnTest.Caption := 'Run';
btnOk.Enabled := True;
btnCancel.Enabled := True;
end;
end;
end;
procedure TFrmScheduleEditor.AppEventsIdle(Sender: TObject;
var Done: Boolean);
begin
SelectRecurringInfoPage;
if rbDaily.Checked then
UpdateDailyPageInfo
else
if rbWeekly.Checked then
UpdateWeeklyPageInfo
else
if rbMonthly.Checked then
UpdateMonthlyPageInfo
else
if rbYearly.Checked then
UpdateYearlyPageInfo;
UpdateFrequencyPageInfo;
UpdateEndPageInfo;
UpdateTestSettings;
end;
procedure TFrmScheduleEditor.btnOkClick(Sender: TObject);
begin
InitSchedule(Schedule);
end;
end.
| 31.536732 | 100 | 0.634609 |
8337941b608ba3d897a7870e8a1fd8a39c55105a | 151,523 | pas | Pascal | windows/src/ext/jedi/jvcl/help/tools/GenDtx/DelphiParser.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 219 | 2017-06-21T03:37:03.000Z | 2022-03-27T12:09:28.000Z | windows/src/ext/jedi/jvcl/help/tools/GenDtx/DelphiParser.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 4,451 | 2017-05-29T02:52:06.000Z | 2022-03-31T23:53:23.000Z | windows/src/ext/jedi/jvcl/help/tools/GenDtx/DelphiParser.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 72 | 2017-05-26T04:08:37.000Z | 2022-03-03T10:26:20.000Z | unit DelphiParser;
interface
uses
Classes, ParserTypes, Contnrs;
const
toComment = Char(6);
toSameLineComment = Char(7);
toCompilerDirective = Char(8);
toDotDot = Char(15);
toColon = Char(':'); // 58
toSemiColon = Char(';'); // 59
toLeftParens = Char('('); // 40
toLeftBracket = Char('['); // 91
toRightParens = Char(')'); // 41
toRightBracket = Char(']'); // 93
toEquals = Char('='); // 61
toComma = Char(','); // 44
toDot = Char('.'); // 46
type
THaakType = (htParens, htBracket);
TModuleType = (mtLibrary, mtUnit);
TDtxParseOption = (dpoLinks, dpoParameters, dpoDefaultText);
TDtxParseOptions = set of TDtxParseOption;
TBasicParser = class(TObject)
private
FStream: TStream;
FOrigin: Longint;
FBuffer: PChar;
FBufPtr: PChar;
FBufEnd: PChar;
FSourcePtr: PChar; // end of current token
FSourceEnd: PChar;
FTokenPtr: PChar; // start of current token
FSourceLine: Integer;
FSaveChar: Char;
FToken: Char;
FFloatType: Char;
FWideStr: WideString;
FRecordStr: string;
FRecording: Boolean;
FCompilerDirectives: TStringList;
FLastWasNewLine: Boolean;
FLowRecording: Boolean; { TODO : Use FLowRecordPtr }
FLowRecordPtr: PChar;
FLowRecordBuffer: PChar;
FLowRecordBufPtr: PChar;
FLowRecordBufEnd: PChar; { TODO : Use size ?? }
FLowOutputStream: TStream;
FSavedSourcePtr: PChar;
FSavedTokenPtr: PChar;
FSavedToken: Char;
FSavedSourceLine: Integer;
procedure ReadBuffer;
function ReadPortion(CheckPosition: Integer): Boolean;
procedure SkipBlanks;
procedure AddToLowRecording(StartPtr, EndPtr: PChar);
procedure AddTokenToRecordStr;
procedure SetRecording(const Value: Boolean);
function GetRecordStrWithCurrentToken: string;
procedure SetLowRecording(const Value: Boolean);
function GetLowRecordingStr: string;
protected
function ReadNextToken: Char; virtual; abstract;
procedure SaveRollBackPosition; virtual;
procedure RollBackToSavedPosition; virtual;
procedure ForgetRollBackPosition; virtual;
procedure Init; virtual;
public
constructor Create; virtual;
destructor Destroy; override;
procedure CheckToken(T: Char);
procedure CheckNotToken(T: Char);
procedure CheckTokenSymbol(const S: string);
function CheckTokenSymbolIn(const List: array of string): Integer;
procedure Error(const Ident: string);
procedure ErrorFmt(const Ident: string; const Args: array of const);
procedure ErrorStr(const Message: string);
function LowNextToken(SkipBlanks: Boolean = True): Char; virtual;
function SourcePos: Longint;
function TokenComponentIdent: string;
function TokenFloat: Extended;
function TokenInt: Int64;
function TokenString: string;
function TokenWideString: WideString;
function TokenSymbolIs(const S: string): Boolean;
function TokenSymbolIsExact(const S: string): Boolean;
function TokenSymbolIn(const List: array of string): Integer;
procedure BeginRecording;
procedure EndRecording;
procedure BeginLowRecording;
procedure EndLowRecording; // with current token
procedure EndLowRecordingWithoutCurrent; // but with white space etc.
procedure BeginOutputTo(AStream: TStream);
procedure EndOutputTo;
property FloatType: Char read FFloatType;
property SourceLine: Integer read FSourceLine;
property Token: Char read FToken;
property RecordStr: string read GetRecordStrWithCurrentToken;
property LowRecordingStr: string read GetLowRecordingStr;
property RecordStrWithoutCurrentToken: string read FRecordStr;
property Recording: Boolean read FRecording write SetRecording;
property LowRecording: Boolean read FLowRecording write SetLowRecording;
end;
TDelphiParser = class(TBasicParser)
private
FPasItems: TPasItems;
FErrorMsg: string;
FAcceptCompilerDirectives: TStrings;
FAcceptVisibilities: TClassVisibilities;
FLastCompilerDirectiveAccepted: Boolean;
FDEFList: TStrings;
FBlockDEFList: TStrings;
FSavedDEFList: TStrings;
FCopiedDEFList: TStrings;
FCapitalization: TStrings;
FRecapitalize: Boolean;
FHoldRecapitalize: Boolean;
FWantCompilerDirectives: Boolean;
FInterpretCompilerDirectives: Boolean;
procedure SetAcceptCompilerDirectives(const Value: TStrings);
function GetDoRecapitalize: Boolean;
protected
function ReadNextToken: Char; override;
function TokenSymbolInC(const List: array of string): Integer;
procedure CheckTokenSymbolC(const S: string);
function CheckTokenSymbolInC(const List: array of string): Integer;
function TokenSymbolIsC(const S: string): Boolean;
procedure SaveRollBackPosition; override;
procedure RollBackToSavedPosition; override;
procedure ForgetRollBackPosition; override;
procedure AddDefine(const S: string);
procedure AddNotDefine(const S: string);
procedure SwitchDefine;
procedure EndDefine;
procedure MakeCopyOfDEFList;
procedure BeginBlock;
procedure EndBlock(const AllowDoubleEnd: Boolean);
procedure RecapitalizeToken;
procedure RecapitalizeTokenWith(const S: string);
procedure StartCapitalization;
procedure StopCapitalization;
function ReadClass: TAbstractItem;
function ReadClass_ClassMethod(AClassItem: TClassItem; Position: TClassVisibility): TAbstractItem;
function ReadClass_Field(AClassItem: TClassItem; Position: TClassVisibility): TAbstractItem;
function ReadClass_Function(AClassItem: TClassItem; Position: TClassVisibility): TAbstractItem;
function ReadClass_Procedure(AClassItem: TClassItem; Position: TClassVisibility): TAbstractItem;
function ReadClass_Property(AClassItem: TClassItem; Position: TClassVisibility): TAbstractItem;
function ReadConst: TAbstractItem;
function ReadDispInterface: TAbstractItem;
function ReadEnumerator: TAbstractItem;
function ReadFunctionType: TAbstractItem;
function ReadInterfaceType: TAbstractItem;
function ReadProcedureType: TAbstractItem;
function ReadRecord: TAbstractItem;
function ReadResourceString: TAbstractItem;
function ReadSimpleType: TAbstractItem;
function ReadType(const DoReadDirectives: Boolean): TAbstractItem;
function ReadTypeDef: TAbstractItem;
function ReadVar: TAbstractItem;
function ReadThreadVar: TAbstractItem;
function SkipClass(const DoAdd: Boolean): TAbstractItem;
function SkipConst(const DoAdd: Boolean): TAbstractItem;
function SkipDispInterface(const DoAdd: Boolean): TAbstractItem;
function SkipEnumerator(const DoAdd: Boolean): TAbstractItem;
function SkipFunctionType(const DoAdd: Boolean): TAbstractItem;
function SkipInterfaceType(const DoAdd: Boolean): TAbstractItem;
function SkipProcedureType(const DoAdd: Boolean): TAbstractItem;
function SkipRecord(const DoAdd: Boolean): TAbstractItem;
function SkipResourceString(const DoAdd: Boolean): TAbstractItem;
function SkipSimpleType(const DoAdd: Boolean): TAbstractItem;
function SkipType(const DoAdd, DoReadDirectives: Boolean): TAbstractItem;
function SkipTypeDef(const DoAdd: Boolean): TAbstractItem;
function SkipVar(const DoAdd: Boolean): TAbstractItem;
procedure ReadClassMethods(AClassItem: TClassItem);
procedure ReadCommentBlock;
procedure ReadDirectives(const MaySkipSemiColon: Boolean; var Directives: TDirectives);
procedure ReadFunction;
procedure SkipFunction;
procedure ReadInterfaceBlock;
procedure ReadInterfaceMethods(AInterfaceItem: TInterfaceItem);
procedure ReadInterfaceStatement;
procedure ReadParamList(AParams, ATypes: TStrings; const HaakType: THaakType = htParens);
procedure ReadProcedure;
procedure SkipProcedure;
procedure ReadPropertySpecifiers(const MaySkipSemiColon: Boolean; var Specifiers: TPropertySpecifiers);
procedure ReadUnitBlock(out AModuleType: TModuleType);
function ReadUsesBlock(const DoAdd: Boolean): TAbstractItem;
procedure SkipUsesBlock;
procedure SkipClass_ClassMethod;
procedure SkipClass_Field;
procedure SkipClass_Function;
procedure SkipClass_Procedure;
procedure SkipClass_Property;
procedure SkipClassMethods;
procedure SkipConstantExpression(const ExpectDotDot: Boolean);
procedure SkipConstValue;
procedure SkipDirectives(const MaySkipSemiColon: Boolean);
procedure SkipInterfaceBlock;
procedure SkipInterfaceMethods;
procedure SkipParamList(const HaakType: THaakType = htParens);
procedure SkipPropertySpecifiers(const MaySkipSemiColon: Boolean);
{ implemenation }
function ReadClassProcedureFunctionImpl(const DoAdd: Boolean): TAbstractItem;
function ReadCompilerDirectiveImpl(const DoAdd: Boolean): TAbstractItem;
function ReadCommentImpl(const DoAdd: Boolean): TAbstractItem;
function ReadConstImpl(const DoAdd: Boolean): TAbstractItem;
function ReadFunctionHeader(const DoAdd: Boolean; out IsOnlyHeader: Boolean): TAbstractItem;
function ReadFunctionImpl(const DoAdd: Boolean): TAbstractItem;
function ReadProcedureHeader(const DoAdd: Boolean; out IsOnlyHeader: Boolean): TAbstractItem;
function ReadProcedureImpl(const DoAdd: Boolean): TAbstractItem;
function ReadResourceStringImpl(const DoAdd: Boolean): TAbstractItem;
function ReadTypeDefImpl(const DoAdd: Boolean): TAbstractItem;
function ReadVarImpl(const DoAdd: Boolean): TAbstractItem;
function ReadThreadVarImpl(const DoAdd: Boolean): TAbstractItem;
procedure ReadConstVarTypeSection;
procedure ReadFunctionProcedureBody;
procedure ReadImplementationBlock;
procedure ReadInitializationFinalization;
procedure SkipUntilToken(T: Char);
procedure SkipUntilSymbol(const Symbol: string);
procedure SkipUntilTokenInHaak(T: Char; const InitHaak: Integer = 0); overload;
procedure SkipUntilTokenInHaak(OpenSymbol, CloseSymbol: Char;
const InitialOpenCount: Integer = 0); overload;
procedure Init; override;
function Parse: Boolean; virtual;
public
constructor Create; override;
destructor Destroy; override;
function DoNextToken(SkipBlanks: Boolean = True): Char;
function TokenCompilerDirective: TCompilerDirective;
function TokenCompilerDirectiveArgument: string;
function TokenIsConditionalCompilation: Boolean;
function ExecuteFile(const AFileName: string): Boolean; virtual;
function Execute(AStream: TStream): Boolean; virtual;
property TypeList: TPasItems read FPasItems;
property AcceptCompilerDirectives: TStrings read FAcceptCompilerDirectives
write SetAcceptCompilerDirectives;
property AcceptVisibilities: TClassVisibilities read FAcceptVisibilities
write FAcceptVisibilities default [inPublic, inPublished];
property ErrorMsg: string read FErrorMsg;
property Recapitalize: Boolean read FRecapitalize write FRecapitalize;
property InterpretCompilerDirectives: Boolean read FInterpretCompilerDirectives write FInterpretCompilerDirectives;
property WantCompilerDirectives: Boolean read FWantCompilerDirectives write FWantCompilerDirectives;
property DEFList: TStrings read FDEFList;
property Capitalization: TStrings read FCapitalization write FCapitalization;
property DoRecapitalize: Boolean read GetDoRecapitalize;
end;
TDtxCompareErrorFlag = (defNoPackageTag, defPackageTagNotFilled,
defNoStatusTag, defEmptySeeAlso, defNoAuthor, defHasTocEntryError, defUnknownTag);
TDtxCompareErrorFlags = set of TDtxCompareErrorFlag;
TPasCheckErrorFlag = (pefNoLicense, pefUnitCase);
TPasCheckErrorFlags = set of TPasCheckErrorFlag;
TDefaultText = (dtWriteSummary, dtWriteDescription, dtTypeUsedBy,
dtListProperties, dtRemoveSeeAlso, dtDescribeReturns, dtOverridenMethod,
dtInheritedMethod, dtDescriptionFor, dtDescriptionForThisParameter);
TDefaultTexts = set of TDefaultText;
TDtxCompareTokenType = (ctHelpTag, ctText, ctParseTag, ctSeperator);
TJVCLInfoError = (jieGroupNotFilled, jieFlagNotFilled, jieOtherNotFilled, jieNoGroup, jieDoubles);
TJVCLInfoErrors = set of TJVCLInfoError;
TDtxBaseItem = class
private
FData: string;
procedure SetData(const Value: string);
public
procedure WriteToStream(AStream: TStream); virtual; abstract;
function CompareWith(AItem: TDtxBaseItem): Integer; virtual; abstract;
property Data: string read FData write SetData;
end;
TDtxStartSymbol = (dssPackage, dssStatus, dssSkip, dssOther);
TDtxItems = class(TObjectList)
private
FSkipList: TStrings;
public
constructor Create; virtual;
destructor Destroy; override;
procedure DtxSort;
procedure FillWithDtxHeaders(Dest: TStrings);
procedure CombineWithPasList(APasItems: TPasItems);
procedure ConstructSkipList;
function IndexOfReferenceName(ReferenceName: string): Integer;
procedure WriteToFile(const AFileName: string);
property SkipList: TStrings read FSkipList;
end;
TDtxStartItem = class(TDtxBaseItem)
private
FSymbolStr: string;
FSymbol: TDtxStartSymbol;
procedure SetSymbolStr(const Value: string);
procedure SetSymbol(const Value: TDtxStartSymbol);
public
function CompareWith(AItem: TDtxBaseItem): Integer; override;
procedure WriteToStream(AStream: TStream); override;
property SymbolStr: string read FSymbolStr write SetSymbolStr;
property Symbol: TDtxStartSymbol read FSymbol write SetSymbol;
end;
TDtxHelpItem = class(TDtxBaseItem)
private
FTag: string;
FParameters: TStrings;
FTitle: string;
FCombine: string;
FCombineWith: string;
FHasTocEntry: Boolean;
FTitleImg: string;
FHasJVCLInfo: Boolean;
FJVCLInfoErrors: TJVCLInfoErrors;
FIsRegisteredComponent: Boolean;
FIsFileInfo: Boolean;
FLinks: TStrings;
FPasObj: TAbstractItem;
FHasPasFileEntry: Boolean;
protected
procedure AddLink(const ALink: string);
procedure AddParam(const AParam: string);
procedure ClearLinks;
public
constructor Create(const ATag: string); virtual;
destructor Destroy; override;
function CompareWith(AItem: TDtxBaseItem): Integer; override;
procedure WriteToStream(AStream: TStream); override;
property IsFileInfo: Boolean read FIsFileInfo write FIsFileInfo;
property Tag: string read FTag write FTag;
property Parameters: TStrings read FParameters;
property Links: TStrings read FLinks;
property Title: string read FTitle write FTitle;
property Combine: string read FCombine write FCombine;
property CombineWith: string read FCombineWith write FCombineWith;
property HasTocEntry: Boolean read FHasTocEntry write FHasTocEntry;
property HasPasFileEntry: Boolean read FHasPasFileEntry write FHasPasFileEntry;
property TitleImg: string read FTitleImg write FTitleImg;
property HasJVCLInfo: Boolean read FHasJVCLInfo write FHasJVCLInfo;
property IsRegisteredComponent: Boolean read FIsRegisteredComponent write FIsRegisteredComponent;
property JVCLInfoErrors: TJVCLInfoErrors read FJVCLInfoErrors write FJVCLInfoErrors;
property PasObj: TAbstractItem read FPasObj write FPasObj;
end;
TDtxCompareParser = class(TBasicParser)
private
FList: TDtxItems;
FErrors: TDtxCompareErrorFlags;
FDefaultTexts: TDefaultTexts;
FPasFileNameWithoutPath: string;
FTags: TStrings;
FSkipList: TStrings;
FCollectData: Boolean;
FOptions: TDtxParseOptions;
function GetDtxCompareTokenType: TDtxCompareTokenType;
function GetPackage: string;
protected
function ReadNextToken: Char; override;
function Parse: Boolean;
procedure ReadAuthor;
function ReadLink(out Link: string): Boolean;
procedure ReadItem(Item: TDtxHelpItem);
procedure ReadFileInfo;
procedure ReadHasTocEntry(Item: TDtxHelpItem);
procedure ReadHelpTopic(Item: TDtxHelpItem);
procedure ReadJVCLINFO(Item: TDtxHelpItem);
procedure ReadPackage;
procedure ReadSkip;
procedure ReadParameters(Item: TDtxHelpItem);
procedure ReadRest;
procedure ReadSeeAlso(Item: TDtxHelpItem);
procedure ReadStartBlock;
procedure ReadStatus;
procedure ReadOther;
procedure ReadTitleImg(Item: TDtxHelpItem);
property CompareTokenType: TDtxCompareTokenType read GetDtxCompareTokenType;
public
constructor Create; override;
destructor Destroy; override;
property Package: string read GetPackage;
function Execute(const AFileName: string): Boolean;
property CollectData: Boolean read FCollectData write FCollectData;
property List: TDtxItems read FList;
property Tags: TStrings read FTags;
property Errors: TDtxCompareErrorFlags read FErrors;
property DefaultTexts: TDefaultTexts read FDefaultTexts;
property SkipList: TStrings read FSkipList write FSkipList;
property Options: TDtxParseOptions read FOptions write FOptions;
end;
TDpkParser = class(TDelphiParser)
private
FList: TStrings;
procedure ReadUntilContainsBlock;
function ReadFileReference: Boolean;
protected
function Parse: Boolean; override;
procedure Init; override;
public
constructor Create; override;
destructor Destroy; override;
property List: TStrings read FList;
end;
TRegisteredClassesParser = class(TDelphiParser)
private
FList: TStrings;
protected
function ReadUntilRegisterBlock: Boolean;
function ReadUntilRegisterComponentsBlock: Boolean;
function ReadRegisterComponentsBlock: Boolean;
function Parse: Boolean; override;
public
constructor Create; override;
destructor Destroy; override;
procedure Init; override;
property List: TStrings read FList;
end;
TPasCasingParser = class(TDelphiParser)
private
FList: TStrings;
FID: Integer;
FAllSymbols: Boolean;
FDoCount: Boolean;
protected
function Parse: Boolean; override;
public
constructor Create; override;
destructor Destroy; override;
property List: TStrings read FList;
property ID: Integer read FID write FID;
property AllSymbols: Boolean read FAllSymbols write FAllSymbols;
property DoCount: Boolean read FDoCount write FDoCount;
end;
TPasCheckParser = class(TDelphiParser)
private
FErrors: TPasCheckErrorFlags;
FFileName: string;
FUnitName: string;
protected
procedure ReadCommentBlock;
procedure ReadUnitName;
function Parse: Boolean; override;
public
function ExecuteFile(const AFileName: string): Boolean; override;
property Errors: TPasCheckErrorFlags read FErrors;
property FileName: string read FFileName;
property UnitName: string read FUnitName;
end;
TFunctionParser = class(TDelphiParser)
private
FFunctions: TStrings;
FSkipped: TStrings;
FFileName: string;
protected
procedure ReadUntilImplementationBlock;
function ReadUntilFunction: Boolean;
procedure ReadFunction;
procedure Init; override;
function Parse: Boolean; override;
public
constructor Create; override;
destructor Destroy; override;
function ExecuteFile(const AFileName: string): Boolean; override;
property Functions: TStrings read FFunctions;
property Skipped: TStrings read FSkipped;
end;
TImplementationParser = class(TDelphiParser)
private
FOutputStream: TStream;
FSortImplementation: Boolean;
protected
function Parse: Boolean; override;
public
property OutputStream: TStream read FOutputStream write FOutputStream;
property SortImplementation: Boolean read FSortImplementation write FSortImplementation;
end;
TRecapitalizeParser = class(TDelphiParser)
private
FOutputStream: TStream;
protected
function Parse: Boolean; override;
public
property OutputStream: TStream read FOutputStream write FOutputStream;
end;
implementation
uses
SysUtils, Dialogs, Windows, Math, DelphiParserUtils;
resourcestring
SCharExpected = '''''%s'''' expected';
SCompilerDirectiveExpected = 'Compiler directive expected';
SIdentifierExpected = 'Identifier expected';
SNumberExpected = 'Number expected';
SParseError = '%s on line %d';
SStringExpected = 'String expected';
SSymbolExpected = '%s expected';
type
TCheckTextResult = (ctPrefix, ctEqual, ctDifferent);
TPosition = (inConst, inType, inNull, inVar, inThreadVar, inResourceString);
const
CParseBufSize = 4096 * 16;
CAllowableSymbolsInTypeDef: array[0..4] of string = ('Low', 'High', 'Ord', 'Succ', 'Pred');
CDefaultText: array[TDefaultText] of string = (
'write here a summary (1 line)',
'write here a description',
'this type is used by (for reference):',
'list here other properties, methods',
'remove the ''see also'' section if there are no references',
'describe here what the function returns',
'this is an overridden method, you don''t have to describe these',
'if it does the same as the inherited method',
'Description for', // case sensitive
'description for this parameter'
);
SInvalidBinary = 'Invalid binary value';
SInvalidString = 'Invalid string constant';
SLineTooLong = 'Line too long';
SNotCharExpected = 'Not ''''%s'''' expected';
SNotEofExpected = 'Not EOF expected';
SNotIdentifierExpected = 'Not identifier expected';
SNotNumberExpected = 'Not number expected';
SNotStringExpected = 'Not string expected';
//=== Local procedures =======================================================
function CheckText(const Short, Long: string; const CaseSensitive: Boolean): TCheckTextResult;
var
AreEqual: Boolean;
begin
if CaseSensitive then
AreEqual := StrLComp(PChar(Short), PChar(Long), Length(Short)) = 0
else
AreEqual := StrLIComp(PChar(Short), PChar(Long), Length(Short)) = 0;
if not AreEqual then
Result := ctDifferent
else
if Length(Short) = Length(Long) then
Result := ctEqual
else
Result := ctPrefix;
end;
function RemoveEndChars(const S: string; const Chars: TSysCharSet): string;
begin
Result := S;
while (Length(Result) > 0) and (Result[Length(Result)] in Chars) do
Delete(Result, Length(Result), 1);
end;
function FirstChar(const S: string): Char;
begin
if S = '' then
Result := #0
else
Result := S[1];
end;
function DtxSortCompare(Item1, Item2: Pointer): Integer;
begin
Result := TDtxBaseItem(Item1).CompareWith(TDtxBaseItem(Item2));
end;
function AddLeading(const S: string): string;
begin
if (Length(S) < 2) or (S[1] <> '@') or (S[2] <> '@') then
Result := '@@' + S
else
Result := S;
end;
function RemoveSepLines(const S: string): string;
procedure AddString(StartPtr, EndPtr: PChar);
var
CurrentLength: Integer;
begin
if EndPtr <= StartPtr then
Exit;
CurrentLength := Length(Result);
SetLength(Result, CurrentLength + EndPtr - StartPtr);
Move(StartPtr^, (PChar(Result) + CurrentLength)^, EndPtr - StartPtr);
end;
var
P, Q, R: PChar;
begin
P := PChar(S);
R := P;
while P^ <> #0 do
begin
while not (P^ in ['-', #0]) do
Inc(P);
Q := P;
while P^ = '-' do
Inc(P);
if Q + 3 < P then { 3 = arbitrary }
begin
if P^ = #0 then
begin
AddString(R, Q);
R := P;
end
else
if P^ = #13 then
begin
Inc(P);
if P^ = #10 then
begin
AddString(R, Q);
Inc(P);
R := P;
Continue;
end;
end;
end;
while not (P^ in [#13, #10, #0]) do
Inc(P);
while P^ in [#13, #10] do
Inc(P);
end;
AddString(R, P);
end;
//=== TBasicParser ===========================================================
procedure TBasicParser.AddTokenToRecordStr;
begin
if FRecordStr > '' then
FRecordStr := FRecordStr + ' ' + TokenString
else
FRecordStr := TokenString;
end;
procedure TBasicParser.AddToLowRecording(StartPtr, EndPtr: PChar);
var
NeededSize: Integer;
PtrPos: Integer;
begin
Assert(FLowRecording, 'not recording');
if StartPtr >= EndPtr then
Exit;
{ copy size = FSourcePtr - FLowRecordPtr }
if FLowRecordBuffer = nil then
begin
GetMem(FLowRecordBuffer, $4000);
FLowRecordBufPtr := FLowRecordBuffer;
FLowRecordBufEnd := FLowRecordBuffer + $4000;
end;
NeededSize := (FLowRecordBufPtr - FLowRecordBuffer) + (EndPtr - StartPtr);
if FLowRecordBuffer + NeededSize > FLowRecordBufEnd then
begin
NeededSize := $4000 * ((NeededSize + $4000 - 1) div $4000);
PtrPos := FLowRecordBufPtr - FLowRecordBuffer;
ReallocMem(FLowRecordBuffer, NeededSize);
FLowRecordBufEnd := FLowRecordBuffer + NeededSize;
FLowRecordBufPtr := PtrPos + FLowRecordBuffer;
end;
Move(FLowRecordPtr^, FLowRecordBufPtr^, EndPtr - StartPtr);
Inc(FLowRecordBufPtr, EndPtr - StartPtr);
end;
procedure TBasicParser.BeginLowRecording;
begin
if not FLowRecording then
begin
FLowRecordPtr := FTokenPtr;
FLowRecordBufPtr := FLowRecordBuffer;
FLowRecording := True;
end;
end;
procedure TBasicParser.BeginOutputTo(AStream: TStream);
begin
FLowOutputStream := AStream;
end;
procedure TBasicParser.BeginRecording;
begin
FRecording := True;
FRecordStr := '';
end;
procedure TBasicParser.CheckNotToken(T: Char);
begin
if Token = T then
case T of
toSymbol:
Error(SNotIdentifierExpected);
toString, toWString:
Error(SNotStringExpected);
toInteger, toFloat:
Error(SNotNumberExpected);
toEof:
Error(SNotEofExpected);
else
ErrorFmt(SNotCharExpected, [T]);
end;
end;
procedure TBasicParser.CheckToken(T: Char);
begin
if Token <> T then
case T of
toSymbol:
Error(SIdentifierExpected);
toString, toWString:
Error(SStringExpected);
toInteger, toFloat:
Error(SNumberExpected);
toCompilerDirective:
Error(SCompilerDirectiveExpected);
else
ErrorFmt(SCharExpected, [T]);
end;
end;
procedure TBasicParser.CheckTokenSymbol(const S: string);
begin
if not TokenSymbolIs(S) then
ErrorFmt(SSymbolExpected, [S]);
end;
function TBasicParser.CheckTokenSymbolIn(const List: array of string): Integer;
var
I: Integer;
Msg: string;
begin
Result := TokenSymbolIn(List);
if Result < 0 then
begin
Msg := '';
for I := Low(List) to High(List) do
begin
Msg := Msg + List[I];
if I = High(List) - 1 then
Msg := Msg + ' or '
else
if I < High(List) - 1 then
Msg := Msg + ', ';
end;
Error(Msg + ' expected');
end;
end;
constructor TBasicParser.Create;
begin
inherited Create;
GetMem(FBuffer, CParseBufSize);
FCompilerDirectives := TStringList.Create;
end;
destructor TBasicParser.Destroy;
begin
FCompilerDirectives.Free;
if FBuffer <> nil then
begin
if Assigned(FStream) then
FStream.Seek(Longint(FTokenPtr) - Longint(FBufPtr), 1);
FreeMem(FBuffer, CParseBufSize);
end;
FreeMem(FLowRecordBuffer);
inherited Destroy;
end;
procedure TBasicParser.EndLowRecording;
begin
if FLowRecording then
begin
AddToLowRecording(FLowRecordPtr, FSourcePtr);
FLowRecording := False;
end;
end;
procedure TBasicParser.EndLowRecordingWithoutCurrent;
begin
if FLowRecording then
begin
AddToLowRecording(FLowRecordPtr, FTokenPtr);
FLowRecording := False;
end;
end;
procedure TBasicParser.EndOutputTo;
begin
FLowOutputStream.WriteBuffer(FBuffer^, FSourcePtr - FBuffer);
FLowOutputStream := nil;
end;
procedure TBasicParser.EndRecording;
begin
FRecording := False;
end;
procedure TBasicParser.Error(const Ident: string);
begin
ErrorStr(Ident);
end;
procedure TBasicParser.ErrorFmt(const Ident: string;
const Args: array of const);
begin
ErrorStr(Format(Ident, Args));
end;
procedure TBasicParser.ErrorStr(const Message: string);
begin
raise EParserError.CreateFmt(SParseError, [Message, FSourceLine]);
end;
procedure TBasicParser.ForgetRollBackPosition;
begin
FSavedSourcePtr := nil;
FSavedTokenPtr := nil;
FSavedSourceLine := -1;
FSavedToken := #0;
end;
function TBasicParser.GetLowRecordingStr: string;
begin
if Assigned(FLowRecordBuffer) then
SetString(Result, FLowRecordBuffer, FLowRecordBufPtr - FLowRecordBuffer)
else
Result := '';
end;
function TBasicParser.GetRecordStrWithCurrentToken: string;
begin
Result := FRecordStr + ' ' + TokenString;
end;
procedure TBasicParser.Init;
begin
FBuffer[0] := #0;
FBufPtr := FBuffer;
FBufEnd := FBuffer + CParseBufSize;
FSourcePtr := FBuffer;
FSourceEnd := FBuffer;
FTokenPtr := FBuffer;
FLowRecording := False;
FLowRecordPtr := nil;
FLowRecordBufPtr := FLowRecordBuffer;
FSavedSourcePtr := nil;
FSavedTokenPtr := nil;
FSourceLine := 1;
LowNextToken(False);
end;
function TBasicParser.LowNextToken(SkipBlanks: Boolean): Char;
const
CComments = [toComment, toSameLineComment];
CBlankTokens = CComments + [#10];
begin
if Recording and not (Token in CComments) then
AddTokenToRecordStr;
Result := ReadNextToken;
while SkipBlanks and (Token in CBlankTokens) do
Result := ReadNextToken;
end;
procedure TBasicParser.ReadBuffer;
var
Count: Integer;
Start: PChar;
SourcePtrDiff, SavedSourcePtrDiff: Integer;
begin
Inc(FOrigin, FSourcePtr - FBuffer);
if Assigned(FLowOutputStream) then
FLowOutputStream.Write(FBuffer^, FSourcePtr - FBuffer);
if LowRecording and (FSourcePtr > FLowRecordPtr) then
AddToLowRecording(FLowRecordPtr, FSourcePtr);
SourcePtrDiff := 0;
SavedSourcePtrDiff := 0;
if Assigned(FSavedSourcePtr) then
begin
Start := FSavedTokenPtr;
SourcePtrDiff := FSourcePtr - Start;
SavedSourcePtrDiff := FSavedSourcePtr - Start;
end
else
Start := FSourcePtr;
FSourceEnd[0] := FSaveChar;
Count := FBufPtr - Start;
if Count <> 0 then
Move(Start[0], FBuffer[0], Count);
FBufPtr := FBuffer + Count;
if FBufEnd = FBufPtr then
raise Exception.Create('ReadBuffer Error');
Inc(FBufPtr, FStream.Read(FBufPtr[0], FBufEnd - FBufPtr));
Start := FBuffer;
if Assigned(FSavedSourcePtr) then
begin
FSavedTokenPtr := Start;
FSavedSourcePtr := Start + SavedSourcePtrDiff;
end;
FSourcePtr := Start + SourcePtrDiff;
FLowRecordPtr := FBuffer;
FSourceEnd := FBufPtr;
if FSourceEnd = FBufEnd then
begin
FSourceEnd := LineStart(FBuffer, FSourceEnd - 1);
if FSourceEnd = FBuffer then
Error(SLineTooLong);
end;
FSaveChar := FSourceEnd[0];
FSourceEnd[0] := #0;
end;
function TBasicParser.ReadPortion(CheckPosition: Integer): Boolean;
begin
ReadBuffer;
Result := (FSourcePtr + CheckPosition)^ <> #0;
end;
procedure TBasicParser.RollBackToSavedPosition;
begin
FSourcePtr := FSavedSourcePtr;
FTokenPtr := FSavedTokenPtr;
FToken := FSavedToken;
FSourceLine := FSavedSourceLine;
ForgetRollBackPosition;
end;
procedure TBasicParser.SaveRollBackPosition;
begin
FSavedSourcePtr := FSourcePtr;
FSavedTokenPtr := FTokenPtr;
FSavedToken := FToken;
FSavedSourceLine := FSourceLine;
end;
procedure TBasicParser.SetLowRecording(const Value: Boolean);
begin
if Value then
BeginLowRecording
else
EndLowRecording;
end;
procedure TBasicParser.SetRecording(const Value: Boolean);
begin
if Value then
BeginRecording
else
EndRecording;
end;
procedure TBasicParser.SkipBlanks;
begin
FLastWasNewLine := False;
while True do
begin
case FSourcePtr^ of
#0:
begin
ReadBuffer;
if FSourcePtr^ = #0 then
Exit;
Continue;
end;
#10:
Inc(FSourceLine);
#33..#255:
Exit;
end;
FLastWasNewLine := (FSourcePtr^ = #10) or (FLastWasNewLine and (FSourcePtr^ in [#0..#32]));
Inc(FSourcePtr);
end;
end;
function TBasicParser.SourcePos: Longint;
begin
Result := FOrigin + (FTokenPtr - FBuffer);
end;
function TBasicParser.TokenComponentIdent: string;
var
P: PChar;
begin
CheckToken(toSymbol);
P := FSourcePtr;
while P^ = '.' do
begin
Inc(P);
if not (P^ in ['A'..'Z', 'a'..'z', '_']) then
Error(SIdentifierExpected);
repeat
Inc(P)
until not (P^ in ['A'..'Z', 'a'..'z', '0'..'9', '_']);
end;
FSourcePtr := P;
Result := TokenString;
end;
function TBasicParser.TokenFloat: Extended;
begin
if FFloatType <> #0 then
Dec(FSourcePtr);
Result := StrToFloat(TokenString);
if FFloatType <> #0 then
Inc(FSourcePtr);
end;
function TBasicParser.TokenInt: Int64;
begin
Result := StrToInt64(TokenString);
end;
function TBasicParser.TokenString: string;
var
L: Integer;
begin
L := FSourcePtr - FTokenPtr;
SetString(Result, FTokenPtr, L);
end;
function TBasicParser.TokenSymbolIn(const List: array of string): Integer;
var
S: string;
begin
if not (Token in [toSymbol, toCompilerDirective]) or (High(List) <= 0) then
begin
Result := -1;
Exit;
end;
S := TokenString;
Result := 0;
while (Result <= High(List)) and not SameText(S, List[Result]) do
Inc(Result);
if Result > High(List) then
Result := -1;
end;
function TBasicParser.TokenSymbolIs(const S: string): Boolean;
begin
Result := (Token = toSymbol) and SameText(S, TokenString);
end;
function TBasicParser.TokenSymbolIsExact(const S: string): Boolean;
begin
Result := (Token = toSymbol) and (CompareStr(S, TokenString) = 0);
end;
function TBasicParser.TokenWideString: WideString;
begin
if FToken = toString then
Result := TokenString
else
Result := FWideStr;
end;
//=== TDelphiParser ==========================================================
procedure TDelphiParser.AddDefine(const S: string);
begin
FDEFList.AddObject(S, TObject(dftIFDEF));
end;
procedure TDelphiParser.AddNotDefine(const S: string);
begin
FDEFList.AddObject(S, TObject(dftIFNDEF));
end;
procedure TDelphiParser.BeginBlock;
begin
if not Assigned(FBlockDEFList) then
begin
FBlockDEFList := TStringList.Create;
TStringList(FBlockDEFList).Sorted := True;
TStringList(FBlockDEFList).Duplicates := dupIgnore;
end;
FBlockDEFList.Clear;
FBlockDEFList.Assign(DEFList);
end;
procedure TDelphiParser.CheckTokenSymbolC(const S: string);
begin
CheckTokenSymbol(S);
RecapitalizeTokenWith(S);
end;
function TDelphiParser.CheckTokenSymbolInC(const List: array of string): Integer;
begin
Result := CheckTokenSymbolIn(List);
if Result >= 0 then
RecapitalizeTokenWith(List[Result]);
end;
constructor TDelphiParser.Create;
begin
inherited Create;
FPasItems := TPasItems.Create;
FAcceptCompilerDirectives := TStringList.Create;
TStringList(FAcceptCompilerDirectives).Sorted := True;
FAcceptVisibilities := [inPublic, inPublished];
FInterpretCompilerDirectives := True;
FWantCompilerDirectives := False;
FDEFList := TStringList.Create;
FSavedDEFList := TStringList.Create;
FCopiedDEFList := nil;
end;
destructor TDelphiParser.Destroy;
begin
FCopiedDEFList.Free;
FPasItems.Free;
FAcceptCompilerDirectives.Free;
FDEFList.Free;
FSavedDEFList.Free;
inherited Destroy;
end;
function TDelphiParser.DoNextToken(SkipBlanks: Boolean = True): Char;
var
IfDefCount: Integer;
SkipUntilIfDefCount0: Boolean;
procedure HandleIFDEF;
begin
if InterpretCompilerDirectives then
begin
if SkipUntilIfDefCount0 then
begin
Inc(IfDefCount);
Exit;
end;
end;
AddDefine(TokenCompilerDirectiveArgument);
if InterpretCompilerDirectives then
begin
FLastCompilerDirectiveAccepted :=
FAcceptCompilerDirectives.IndexOf(TokenCompilerDirectiveArgument) >= 0;
if not FLastCompilerDirectiveAccepted then
begin
IfDefCount := 1;
SkipUntilIfDefCount0 := True;
end;
end;
end;
procedure HandleIFNDEF;
begin
if InterpretCompilerDirectives then
begin
if SkipUntilIfDefCount0 then
begin
Inc(IfDefCount);
Exit;
end;
end;
AddNotDefine(TokenCompilerDirectiveArgument);
if InterpretCompilerDirectives then
begin
FLastCompilerDirectiveAccepted :=
FAcceptCompilerDirectives.IndexOf(TokenCompilerDirectiveArgument) < 0;
if not FLastCompilerDirectiveAccepted then
begin
IfDefCount := 1;
SkipUntilIfDefCount0 := True;
end;
end;
end;
procedure HandleENDIF;
begin
if InterpretCompilerDirectives then
begin
if SkipUntilIfDefCount0 then
begin
Dec(IfDefCount);
if IfDefCount > 0 then
{ Not yet done }
Exit;
SkipUntilIfDefCount0 := False;
end;
end;
EndDefine;
end;
procedure HandleELSE;
begin
if not SkipUntilIfDefCount0 or (IfDefCount = 1) then
SwitchDefine;
if InterpretCompilerDirectives then
begin
if SkipUntilIfDefCount0 then
begin
if IfDefCount = 1 then
Dec(IfDefCount);
if IfDefCount > 0 then
Exit;
SkipUntilIfDefCount0 := False;
Exit;
end;
if FLastCompilerDirectiveAccepted then
begin
IfDefCount := 1;
SkipUntilIfDefCount0 := True;
end;
end;
end;
begin
{ SkipBlanks - Do not return compiler directives; comments
InterpretCompilerDirectives - Do not return conditional directives
Jump over non-defined blocks
SkipUntilIfDefCount0 - Loop until $ENDIF encountered
WantCompilerDirectives - Return compiler directives
}
IfDefCount := 0;
SkipUntilIfDefCount0 := False;
while True do
begin
Result := LowNextToken(SkipBlanks);
if (Token = toSymbol) and DoRecapitalize then
RecapitalizeToken;
if not SkipUntilIfDefCount0 then
begin
if Token <> toCompilerDirective then
Exit;
{ Token = toCompilerDirective }
if not TokenIsConditionalCompilation then
begin
if SkipBlanks then
Continue
else
Exit;
end;
end
else
begin
while not (Token in [toCompilerDirective, toEof]) do
LowNextToken(True);
if Token = toEof then
begin
Result := toEof;
Exit;
end;
end;
{ Token = toCompilerDirective }
case TokenCompilerDirective of
cdIFDEF: HandleIFDEF;
cdIFNDEF: HandleIFNDEF;
cdENDIF: HandleENDIF;
cdELSE: HandleELSE;
end;
if WantCompilerDirectives and not InterpretCompilerDirectives then
Exit;
end;
end;
procedure TDelphiParser.EndBlock(const AllowDoubleEnd: Boolean);
function DoDefinesIndicateBlock(out ABlockDEFStr: string; out ABlockDEFType: TDefineType): Boolean;
var
Tmp: TStringList;
I: Integer;
Index: Integer;
begin
Tmp := TStringList.Create;
try
Tmp.Assign(FBlockDEFList);
FBlockDEFList.Assign(DEFList);
for I := 0 to Tmp.Count - 1 do
begin
Index := FBlockDEFList.IndexOf(Tmp[I]);
if (Index >= 0) and (FBlockDEFList.Objects[Index] = Tmp.Objects[I]) then
FBlockDEFList.Delete(Index);
end;
{ We can only skip a block if FBlockDEFList.Count = 1 }
if FBlockDEFList.Count = 1 then
begin
//uses <- BeginBlock
// A, B,
// {$IFDEF STANDALONE}
// C; <- EndBlock; return 'STANDALONE', ifdef
// {$ELSE} |
// D; |- Inverse of 'STANDALONE', ifdef
// {$ENDIF} |
ABlockDEFStr := FBlockDEFList[0];
ABlockDEFType := TDefineType(FBlockDEFList.Objects[0]);
FBlockDEFList.Assign(Tmp);
Result := True;
end
else
if (FBlockDEFList.Count = 0) and (Tmp.Count > 0) and AllowDoubleEnd then
begin
// {$IFNDEF A}
// procedure X(A: TA); <- BeginBlock, EndBlock, return 'A', 'ifndef'
// {$ELSE} |
// procedure X(A': TA'); |= inverse of 'A', 'ifndef'
// {$ENDIF} |
ABlockDEFStr := Tmp[Tmp.Count - 1];
ABlockDEFType := TDefineType(Tmp.Objects[Tmp.Count - 1]);
FBlockDEFList.Clear;
Result := True;
end
else
Result := False;
finally
Tmp.Free;
end;
end;
function DEFIndexOf(const S: string): Integer;
begin
if SameText(S, 'VisualCLX') then
Result := 0
else
if SameText(S, 'VCL') then
Result := 1
else
if SameText(S, 'MSWINDOWS') then
Result := 2
else
if SameText(S, 'LINUX') then
Result := 3
else
Result := -1;
end;
function IsInverse(
const S1: string; const Type1: TDefineType;
const S2: string; const Type2: TDefineType): Boolean;
var
Index1, Index2, Tmp: Integer;
begin
if SameText(S1, S2) then
Result := [Type1] + [Type2] = [dftIFDEF, dftIFNDEF]
else
begin
Result := Type1 = Type2;
if not Result then
Exit;
Index1 := DEFIndexOf(S1);
Index2 := DEFIndexOf(S2);
if Index1 > Index2 then
begin
Tmp := Index1;
Index1 := Index2;
Index2 := Tmp;
end;
Result :=
((Index1 = 0) and (Index2 = 1)) or
((Index1 = 2) and (Index2 = 3));
end;
end;
function IsInverseOf(const ABlockDEFStr: string; const ABlockDEFType: TDefineType): Boolean;
var
I: Integer;
begin
// Check whether FDEFList is the inverse of ABlock_
Result := FDEFList.Count > 0;
if not Result then
Exit;
for I := FDEFList.Count - 1 downto 0 do
begin
Result := IsInverse(
ABlockDEFStr, ABlockDEFType,
FDEFList[I], TDefineType(FDEFList.Objects[I]));
if Result then
Exit;
end;
Result := False;
end;
var
NewBlockDEFStr: string;
NewBlockDEFType: TDefineType;
begin
if not DoDefinesIndicateBlock(NewBlockDEFStr, NewBlockDEFType) then
Exit;
SaveRollBackPosition;
DoNextToken;
if not IsInverseOf(NewBlockDEFStr, NewBlockDEFType) then
begin
RollBackToSavedPosition;
Exit;
end;
ForgetRollBackPosition;
WantCompilerDirectives := True;
while IsInverseOf(NewBlockDEFStr, NewBlockDEFType) do
begin
CheckNotToken(toEof);
DoNextToken(False);
end;
WantCompilerDirectives := False;
end;
procedure TDelphiParser.EndDefine;
begin
if FDEFList.Count = 0 then
Error('Unexpected {$ENDIF}');
FDEFList.Delete(FDEFList.Count - 1);
end;
function TDelphiParser.Execute(AStream: TStream): Boolean;
begin
FStream := AStream;
Init;
try
Result := False;
try
Result := Parse;
except
on E: Exception do
FErrorMsg := E.Message;
end;
finally
FStream := nil;
end;
end;
function TDelphiParser.ExecuteFile(const AFileName: string): Boolean;
var
LStream: TFileStream;
begin
Result := FileExists(AFileName);
if not Result then
Exit;
FPasItems.FileName := AFileName;
LStream := TFileStream.Create(AFileName, fmOpenRead, fmShareDenyWrite);
try
Result := Execute(LStream);
finally
FreeAndNil(LStream);
end;
end;
procedure TDelphiParser.ForgetRollBackPosition;
begin
FSavedDEFList.Clear;
inherited ForgetRollBackPosition;
end;
function TDelphiParser.GetDoRecapitalize: Boolean;
begin
Result := Recapitalize and not FHoldRecapitalize and Assigned(FCapitalization);
end;
procedure TDelphiParser.Init;
begin
inherited Init;
FPasItems.Clear;
FLastCompilerDirectiveAccepted := False;
end;
procedure TDelphiParser.MakeCopyOfDEFList;
begin
if (FDEFList.Count > 0) and not Assigned(FCopiedDEFList) then
FCopiedDEFList := TStringList.Create;
if Assigned(FCopiedDEFList) then
FCopiedDEFList.Assign(FDEFList);
end;
function TDelphiParser.Parse: Boolean;
var
LModuleType: TModuleType;
begin
ReadCommentBlock;
ReadUnitBlock(LModuleType);
if LModuleType = mtLibrary then
begin
Result := True;
Exit;
end;
ReadInterfaceStatement;
SkipUsesBlock;
ReadInterfaceBlock;
FErrorMsg := '';
FPasItems.DtxSort;
FPasItems.CalculateCombines;
Result := True;
end;
function TDelphiParser.ReadClass: TAbstractItem;
var
LAncestor: string;
begin
{ Example:
Tx = class(Tx1) .. end;
Tx = class .. end;
Tx = class; -> Deze niet toevoegen, moet nog compleet
gedefinieerd worden
Tx = class(Tx1); -> Hack class
Tx = class of Tx1; -> Meta class
PRE : Token = 'class'
POST: Token = ;
}
DoNextToken;
if Token = toSemiColon then
begin
{ Class is nog niet compleet gedefinieerd; niet toevoegen }
Result := nil;
Exit;
end;
if Token = toLeftParens then
begin
DoNextToken;
CheckToken(toSymbol);
LAncestor := TokenString;
SkipUntilToken(toRightParens);
DoNextToken;
end;
{ Now add }
if TokenSymbolIs('of') then
begin
Result := TMetaClassItem.Create('');
FPasItems.Add(Result);
DoNextToken;
CheckToken(toSymbol);
TMetaClassItem(Result).Value := TokenString;
SkipUntilToken(toSemiColon);
end
else
begin
Result := TClassItem.Create('');
TClassItem(Result).Ancestor := LAncestor;
FPasItems.Add(Result);
if Token <> toSemiColon then
ReadClassMethods(TClassItem(Result)); { Token = ; or directive }
end;
end;
procedure TDelphiParser.ReadClassMethods(AClassItem: TClassItem);
var
Position: TClassVisibility;
begin
{ vb
public property P1; end;
PRE : Token = token after 'class'
POST: Token = ; (= first token after 'end')
}
Position := inPublic;
while True do
begin
CheckNotToken(toEof);
if Token = toSymbol then
case TokenSymbolInC(['end', 'private', 'protected', 'public', 'published',
'property', 'procedure', 'constructor', 'destructor', 'function', 'class']) of
0: { end }
begin
DoNextToken;
{ token = directive or ; }
Exit;
end;
1: { private }
begin
Position := inPrivate;
DoNextToken;
end;
2: { protected }
begin
Position := inProtected;
DoNextToken;
end;
3: { public }
begin
Position := inPublic;
DoNextToken;
end;
4: { published }
begin
Position := inPublished;
DoNextToken;
end;
5: { property }
if Position in AcceptVisibilities + [inProtected, inPublic, inPublished] then
ReadClass_Property(AClassItem, Position)
else
SkipClass_Property;
6, 7, 8: { procedure, constructor, destructor }
if Position in AcceptVisibilities then
ReadClass_Procedure(AClassItem, Position)
else
SkipClass_Procedure;
9: {function }
if Position in AcceptVisibilities then
ReadClass_Function(AClassItem, Position)
else
SkipClass_Function;
10: {class }
if Position in AcceptVisibilities then
ReadClass_ClassMethod(AClassItem, Position)
else
SkipClass_ClassMethod;
else { field }
if Position in AcceptVisibilities then
ReadClass_Field(AClassItem, Position)
else
SkipClass_Field;
end
else { not a symbol, probably ; }
DoNextToken;
end;
end;
function TDelphiParser.ReadClassProcedureFunctionImpl(const DoAdd: Boolean): TAbstractItem;
begin
Assert(FHoldRecapitalize, 'cap = true');
BeginLowRecording;
DoNextToken;
CheckToken(toSymbol);
case TokenSymbolInC(['function', 'procedure']) of
0: Result := ReadFunctionImpl(DoAdd);
1: Result := ReadProcedureImpl(DoAdd);
else
Result := nil;
Error('function or procedure expected');
end;
end;
function TDelphiParser.ReadClass_ClassMethod(AClassItem: TClassItem; Position: TClassVisibility): TAbstractItem;
begin
DoNextToken;
CheckToken(toSymbol);
case TokenSymbolInC(['function', 'procedure']) of
0: Result := ReadClass_Function(AClassItem, Position);
1: Result := ReadClass_Procedure(AClassItem, Position);
else
Result := nil;
Error('function or procedure expected');
end;
if Result is TParamClassMethodItem then
TParamClassMethodItem(Result).IsClassMethod := True;
end;
function TDelphiParser.ReadClass_Field(AClassItem: TClassItem; Position: TClassVisibility): TAbstractItem;
var
ClassField: TClassFieldItem;
begin
{ Example:
FErrorMsg: string;
Pre : Token = field name
POST: Token = ;
}
Result := TClassFieldItem.Create(TokenString);
FPasItems.Add(Result);
ClassField := Result as TClassFieldItem;
ClassField.OwnerClass := AClassItem;
ClassField.Position := Position;
{ TODO : Can be multiple fields ie:
FX, FY: Integer
}
SkipUntilToken(toColon);
DoNextToken;
BeginRecording;
SkipType(False, True);
//SkipUntilToken(toSemiColon);
EndRecording;
ClassField.TypeStr := RecordStrWithoutCurrentToken;
CheckToken(toSemiColon);
end;
function TDelphiParser.ReadClass_Function(AClassItem: TClassItem; Position: TClassVisibility): TAbstractItem;
var
MethodFunc: TMethodFuncItem;
LMethodName: string;
Directives: TDirectives;
begin
{ Example:
function F1(P1: T1; P2: T2);
function IMalloc.Alloc = Allocate;
PRE : Token = 'function'
POST: Token = ;
}
DoNextToken;
CheckToken(toSymbol);
LMethodName := TokenString;
DoNextToken;
if Token = '.' then
begin
{ Method resolution clause }
DoNextToken;
CheckToken(toSymbol);
DoNextToken;
CheckToken(toEquals);
DoNextToken;
CheckToken(toSymbol);
DoNextToken;
CheckToken(toSemiColon);
Result := nil;
Exit;
end;
Result := TMethodFuncItem.Create(LMethodName);
FPasItems.Add(Result);
MethodFunc := Result as TMethodFuncItem;
MethodFunc.OwnerClass := AClassItem;
MethodFunc.Position := Position;
{MethodFunc.IsClassMethod := IsClassMethod;}
if Token = toLeftParens then
ReadParamList(MethodFunc.Params, MethodFunc.ParamTypes);
CheckToken(toColon);
DoNextToken;
SkipType(False, False);
Directives := [];
ReadDirectives(True, Directives);
MethodFunc.Directives := Directives;
CheckToken(toSemiColon);
end;
function TDelphiParser.ReadClass_Procedure(AClassItem: TClassItem; Position: TClassVisibility): TAbstractItem;
var
MethodProc: TMethodProcItem;
MethodType: TMethodType;
Directives: TDirectives;
LMethodName: string;
begin
{ Example:
procedure P1(P1: T1; P2: T2);
PRE : Token = 'procedure' or 'constructor' or 'destructor'
POST: Token = ;
}
case TokenSymbolInC(['constructor', 'destructor']) of
0: MethodType := mtConstructor;
1: MethodType := mtDestructor;
else
MethodType := mtNormal;
end;
DoNextToken;
CheckToken(toSymbol);
LMethodName := TokenString;
DoNextToken;
if Token = toDot then
begin
{ Method resolution clause }
DoNextToken;
CheckToken(toSymbol);
DoNextToken;
CheckToken(toEquals);
DoNextToken;
CheckToken(toSymbol);
DoNextToken;
CheckToken(toSemiColon);
Result := nil;
Exit;
end;
Result := TMethodProcItem.Create(LMethodName);
FPasItems.Add(Result);
MethodProc := Result as TMethodProcItem;
MethodProc.OwnerClass := AClassItem;
MethodProc.MethodType := MethodType;
MethodProc.Position := Position;
{MethodProc.IsClassMethod := IsClassMethod;}
if Token = toLeftParens then
ReadParamList(MethodProc.Params, MethodProc.ParamTypes);
Directives := [];
ReadDirectives(True, Directives);
MethodProc.Directives := Directives;
CheckToken(toSemiColon);
end;
function TDelphiParser.ReadClass_Property(AClassItem: TClassItem; Position: TClassVisibility): TAbstractItem;
var
I: Integer;
Specifiers: TPropertySpecifiers;
ClassProperty: TClassPropertyItem;
begin
{ Bv:
propery P1: X1 read Get1 write Get2
property P1;
property P1 default X;
property Bold[Year, Month, Day: Word]: Boolean read IsBold write SetBold;
Pre : Token = 'property'
POST: Token = ;
}
DoNextToken;
CheckNotToken(toEof);
Result := TClassPropertyItem.Create(TokenString);
FPasItems.Add(Result);
ClassProperty := Result as TClassPropertyItem;
ClassProperty.OwnerClass := AClassItem;
ClassProperty.Position := Position;
DoNextToken;
if (Token = toSemiColon) or
((Token = toSymbol) and (TokenSymbolInC(['default', 'stored']) >= 0)) then
begin
ClassProperty.IsInherited := True;
SkipUntilToken(toSemiColon);
end
else
begin
ClassProperty.IsInherited := False;
ClassProperty.IsArray := Token = toLeftBracket;
if Token = toLeftBracket then
with ClassProperty do
ReadParamList(Params, ParamTypes, htBracket);
SkipUntilToken(toSymbol);
BeginRecording;
repeat
DoNextToken;
until
(Token in [toEof, toSemiColon]) or (TokenSymbolInC(CPropertySpecifiers) >= 0);
EndRecording;
ClassProperty.TypeStr := RecordStrWithoutCurrentToken;
while not (Token in [toSemiColon, toEof]) do
begin
I := TokenSymbolInC(CPropertySpecifiers);
if (I >= Integer(Low(TPropertySpecifier))) and (I <= Integer(High(TPropertySpecifier))) then
ClassProperty.Specifiers := ClassProperty.Specifiers + [TPropertySpecifier(I)];
DoNextToken;
end;
end;
CheckToken(toSemiColon);
Specifiers := [];
ReadPropertySpecifiers(True, Specifiers);
if Assigned(ClassProperty) then
ClassProperty.Specifiers := ClassProperty.Specifiers + Specifiers;
CheckToken(toSemiColon);
end;
procedure TDelphiParser.ReadCommentBlock;
const
CCopyRight1 = 'Initial Developer of the Original Code is';
CCopyRight2 = 'Initial Developers of the Original Code are:';
var
AuthorFound: Boolean;
S, T: string;
P: Integer;
Q, Q1, Q2, R: PChar;
SpacesFound: Integer;
begin
AuthorFound := False;
while (Token = toComment) or
((Token = toCompilerDirective) and (TokenCompilerDirective in CParamDirectives)) do
begin
if not AuthorFound then
begin
S := TokenString;
P := Pos(CCopyRight1, S);
Q := nil;
if P > 0 then
Q := PChar(S) + P + Length(CCopyRight1)
else
begin
P := Pos(CCopyRight2, S);
if P > 0 then
Q := PChar(S) + P + Length(CCopyRight2);
end;
AuthorFound := P > 0;
if AuthorFound then
begin
R := Q;
Q1 := AnsiStrPos(Q, 'Copyright');
Q2 := AnsiStrPos(Q, 'Portions');
if Q1 = nil then
Q := Q2
else
if (Q2 = nil) or (Q1 < Q2) then
Q := Q1
else
Q := Q2;
if Q = nil then
begin
SpacesFound := 0;
Q := R;
while (Q^ <> #0) and (SpacesFound < 2) do
begin
if Q^ = ' ' then
Inc(SpacesFound);
Inc(Q);
end;
end;
SetLength(T, Q - R);
Move(R^, PChar(T)^, Q - R);
{ Remove e-mail address }
if Pos(toLeftBracket, T) > 0 then
T := Copy(T, 1, Pos(toLeftBracket, T) - 1);
if Pos('<', T) > 0 then
T := Copy(T, 1, Pos('<', T) - 1);
FPasItems.Author := Trim(T);
end;
end;
DoNextToken(False);
end;
while Token <> toSymbol do
DoNextToken;
end;
function TDelphiParser.ReadCommentImpl(const DoAdd: Boolean): TAbstractItem;
begin
Assert(FHoldRecapitalize, 'cap = true');
if not (Token in [toComment, toSameLineComment]) then
Error('Internal error: Comment expected');
if DoAdd then
begin
Result := TCommentItem.Create(TokenString);
TCommentItem(Result).IsSameLineComment := Token = toSameLineComment;
FPasItems.Add(Result);
end
else
Result := nil;
DoNextToken(False);
end;
function TDelphiParser.ReadCompilerDirectiveImpl(
const DoAdd: Boolean): TAbstractItem;
begin
Assert(FHoldRecapitalize, 'cap = true');
CheckToken(toCompilerDirective);
if DoAdd then
begin
MakeCopyOfDEFList;
Result := TCompilerDirectiveItem.Create(TokenString);
Result.BeginDEFList := FCopiedDEFList;
Result.EndDEFList := FDEFList;
FPasItems.Add(Result);
end
else
Result := nil;
DoNextToken(False);
end;
function TDelphiParser.ReadConst: TAbstractItem;
var
ConstItem: TConstItem;
begin
{ Example:
C1 = V1;
C1: type = V1;
C1: array [xx] of TSpecialFolderInfo = ((), (), ());
C1: function (AOwner: TComponent; ActionClass: TBasicActionClass): TBasicAction = nil;
PRE : Token = identifier [C1]
POST: Token = ;
}
ConstItem := TConstItem.Create(TokenString);
FPasItems.Add(ConstItem);
Result := ConstItem;
BeginRecording;
DoNextToken;
case Token of
toEquals:
begin
DoNextToken;
SkipConstValue;
EndRecording;
if TokenSymbolInC(CDirectives) > 0 then
ConstItem.Value := RecordStrWithoutCurrentToken
else
ConstItem.Value := RecordStr;
SkipDirectives(False);
end;
toColon:
begin
DoNextToken;
SkipType(False, True);
CheckToken(toEquals);
DoNextToken;
SkipConstValue;
ConstItem.Value := RecordStr;
end;
else
Error('= or : expected');
end;
CheckToken(toSemiColon);
end;
function TDelphiParser.ReadConstImpl(const DoAdd: Boolean): TAbstractItem;
begin
if DoAdd then
begin
BeginLowRecording;
MakeCopyOfDEFList;
end;
Result := SkipConst(DoAdd);
CheckToken(toSemiColon);
if DoAdd then
begin
EndLowRecording;
if Assigned(Result) then
begin
Result.ImplementationStr := LowRecordingStr;
Result.BeginDEFList := FCopiedDEFList;
Result.EndDEFList := FDEFList;
end;
end;
DoNextToken(False);
end;
procedure TDelphiParser.ReadConstVarTypeSection;
var
Position: TPosition;
begin
Position := inNull;
while Token <> toEof do
begin
StopCapitalization;
case Token of
toSymbol:
case TokenSymbolInC([
'procedure', 'function', 'resourcestring',
'const', 'type', 'var', 'begin', 'end', 'asm', 'label']) of
0: ReadProcedureImpl(False);
1: ReadFunctionImpl(False);
2: { resourecestring }
begin
Position := inResourceString;
DoNextToken;
end;
3: { const }
begin
Position := inConst;
DoNextToken;
end;
4: { type }
begin
Position := inType;
DoNextToken;
end;
5: { var }
begin
Position := inVar;
DoNextToken;
end;
6, 8: { begin }
Exit;
7: { end }
CheckTokenSymbol('begin');
9: { label }
SkipUntilToken(toSemiColon);
else
case Position of
inConst: ReadConstImpl(False);
inType: ReadTypeDefImpl(False);
inVar: ReadVarImpl(False);
//inThreadVar: ReadThreadVarImpl(False); { can not be not here }
inResourceString: ReadResourceStringImpl(False);
else
Error('Not in Type, Const, Var');
end;
end;
else
DoNextToken(False);
end;
end;
while (Token <> toEof) and
((Token <> toSymbol) or not SameText(TokenString, 'implementation')) do
DoNextToken;
end;
procedure TDelphiParser.ReadDirectives(const MaySkipSemiColon: Boolean; var Directives: TDirectives);
var
Directive: Integer;
begin
{
Pre : Token = ; or some directive
Post : Token = ; or =
}
StopCapitalization;
if ((Token <> toSemiColon) or not MaySkipSemiColon) and
((Token <> toSymbol) or (TokenSymbolInC(CDirectives) < 0)) then
Exit;
while True do
begin
if Token = toSemiColon then
begin
SaveRollBackPosition;
DoNextToken;
if (Token <> toSymbol) or (TokenSymbolInC(CDirectives) < 0) then
begin
RollBackToSavedPosition;
Exit;
end;
ForgetRollBackPosition;
end;
while Token = toSymbol do
begin
Directive := TokenSymbolInC(CDirectives);
if Directive < 0 then
Error('Directive expected')
else
Include(Directives, TDirective(Directive));
case TDirective(Directive) of
diMessage, diExternal:
begin
{ message X ; }
DoNextToken;
StartCapitalization;
SkipUntilToken(toSemiColon);
StopCapitalization;
end;
else
DoNextToken;
end;
end;
if Token = toEquals then
Exit;
CheckToken(toSemiColon);
end;
end;
function TDelphiParser.ReadDispInterface: TAbstractItem;
begin
{ TODO: Implement }
SkipUntilSymbol('end');
SkipUntilToken(toSemiColon);
Result := nil;
end;
function TDelphiParser.ReadEnumerator: TAbstractItem;
var
EnumItem: TEnumItem;
NewValue: Boolean;
Haakjes: Integer;
begin
{ Example:
(E1, E2, E3);
();
(Small = 5, Medium = 10, Large = Small + Medium);
PRE : Token = (
POST: Token = ;
}
EnumItem := TEnumItem.Create('');
FPasItems.Add(EnumItem);
Result := EnumItem;
{ NewValue hebben we nodig om bv in '(Small = 5, ..' 5 niet mee te nemen }
NewValue := True;
Haakjes := 0;
while True do
begin
CheckNotToken(toEof);
case Token of
toSemiColon:
if Haakjes = 0 then
Exit;
toLeftParens:
Inc(Haakjes);
toRightParens:
begin
Dec(Haakjes);
if Haakjes = 0 then
begin
DoNextToken;
Exit;
end;
end;
toSymbol:
if NewValue then
begin
EnumItem.Items.Add(TokenString);
NewValue := False;
end;
toComma:
NewValue := True;
end;
DoNextToken;
end;
end;
procedure TDelphiParser.ReadFunction;
var
FunctionItem: TFunctionItem;
Directives: TDirectives;
begin
{ Example:
function F1(P1: T1; P2: T2);
PRE : Token = 'function'
POST: Token = ;
}
CheckTokenSymbol('function');
DoNextToken;
CheckToken(toSymbol);
FunctionItem := TFunctionItem.Create(TokenString);
FPasItems.Add(FunctionItem);
DoNextToken;
{ Token = toLeftParens or toColon }
if Token = toLeftParens then
ReadParamList(FunctionItem.Params, FunctionItem.ParamTypes);
CheckToken(toColon);
DoNextToken;
SkipType(False, False);
Directives := [];
ReadDirectives(True, Directives);
FunctionItem.Directives := Directives;
CheckToken(toSemiColon);
end;
function TDelphiParser.ReadFunctionHeader(const DoAdd: Boolean; out IsOnlyHeader: Boolean): TAbstractItem;
var
FirstToken: string;
Directives: TDirectives;
begin
CheckTokenSymbolC('function');
DoNextToken;
CheckToken(toSymbol);
StartCapitalization;
FirstToken := TokenString;
DoNextToken;
if Token = '.' then
begin
DoNextToken;
CheckToken(toSymbol);
if DoAdd then
begin
Result := TMethodFuncItem.Create(TokenString);
FPasItems.Add(Result);
TMethodFuncItem(Result).OwnerClassAsString := FirstToken;
end
else
Result := nil;
DoNextToken;
end
else
begin
if DoAdd then
begin
Result := TFunctionItem.Create(FirstToken);
FPasItems.Add(Result);
end
else
Result := nil;
end;
{ Token = toLeftParens or toColon }
if Token = toLeftParens then
SkipParamList;
{ Token may be ; (ie no result in the implementation) or : }
if Token <> ';' then
begin
CheckToken(toColon);
DoNextToken;
SkipType(False, False);
end;
Directives := [];
ReadDirectives(True, Directives);
IsOnlyHeader := [diExternal, diForward] * Directives <> [];
StopCapitalization;
CheckToken(toSemiColon);
end;
function TDelphiParser.ReadFunctionImpl(const DoAdd: Boolean): TAbstractItem;
var
OnlyHeader: Boolean;
begin
Assert(FHoldRecapitalize, 'cap = true');
if DoAdd then
begin
BeginLowRecording;
MakeCopyOfDEFList;
end;
BeginBlock;
Result := ReadFunctionHeader(DoAdd, OnlyHeader);
EndBlock(True);
if not OnlyHeader then
begin
BeginBlock;
ReadFunctionProcedureBody;
EndBlock(False);
end;
if DoAdd then
begin
EndLowRecording;
if Assigned(Result) then
begin
Result.ImplementationStr := LowRecordingStr;
Result.BeginDEFList := FCopiedDEFList;
Result.EndDEFList := FDEFList;
end;
end;
DoNextToken(False);
end;
procedure TDelphiParser.ReadFunctionProcedureBody;
var
BeginCount: Integer;
InASM: Boolean;
begin
ReadConstVarTypeSection;
InASM := CheckTokenSymbolInC(['asm', 'begin']) = 0;
if InASM then
StopCapitalization
else
StartCapitalization;
BeginCount := 0;
while True do
begin
CheckNotToken(toEof);
if Token = toSymbol then
case TokenSymbolInC(['begin', 'case', 'try', 'asm', 'end']) of
0, 1, 2: { begin/case/try }
Inc(BeginCount);
3:
begin
{ asm }
Inc(BeginCount);
InASM := True;
StopCapitalization;
end;
4: { end }
begin
Dec(BeginCount);
if BeginCount = 0 then
begin
DoNextToken;
Exit;
end;
if InASM then
begin
InASM := False;
StartCapitalization;
end;
end;
end;
DoNextToken;
end;
end;
function TDelphiParser.ReadFunctionType: TAbstractItem;
var
Directives: TDirectives;
begin
{ Example:
F1 = Function();
TODO : Deze gaat fout : dwz ReadType leest ook directives in
function(ctx: PSSL_CTX; const _file: PChar; _type: Integer):Integer cdecl = nil;
T17 : function(arg0: PSSL_CTX; str: PChar):Integer cdecl = nil;
__________________________________________________
PRE : Token = 'function'
POST: Token = ;
}
Result := TFunctionTypeItem.Create('');
FPasItems.Add(Result);
DoNextToken;
{ Token is toLeftParens or toSemiColon or 'of object' or ?? }
if Token = toLeftParens then
with TFunctionTypeItem(Result) do
ReadParamList(Params, ParamTypes);
CheckToken(toColon);
DoNextToken;
SkipType(False, False);
Directives := [];
ReadDirectives(True, Directives);
TFunctionTypeItem(Result).Directives := Directives;
if not (Token in [toSemiColon, toEquals]) then
Error('; or = expected');
end;
procedure TDelphiParser.ReadImplementationBlock;
var
Position: TPosition;
begin
Position := inNull;
while Token <> toEof do
begin
StopCapitalization;
case Token of
toCompilerDirective:
ReadCompilerDirectiveImpl(True);
toComment, toSameLineComment:
ReadCommentImpl(True);
toSymbol:
case TokenSymbolInC([
'class',
'procedure', 'constructor', 'destructor', 'function', 'resourcestring',
'const', 'type', 'var', 'threadvar', 'end', 'initialization', 'uses']) of
0: ReadClassProcedureFunctionImpl(True);
1, 2, 3: ReadProcedureImpl(True);
4: ReadFunctionImpl(True);
5: { resourcestring}
begin
Position := inResourceString;
DoNextToken(False);
end;
6: { const }
begin
Position := inConst;
DoNextToken(False);
end;
7: { type }
begin
Position := inType;
DoNextToken(False);
end;
8: { var }
begin
Position := inVar;
DoNextToken(False);
end;
9: { threadvar }
begin
Position := inThreadVar;
DoNextToken(False);
end;
10: { end }
begin
DoNextToken;
CheckToken('.');
Exit;
end;
11: { initialization }
ReadInitializationFinalization;
12: { uses }
ReadUsesBlock(True);
else
case Position of
inConst: ReadConstImpl(True);
inType: ReadTypeDefImpl(True);
inVar: ReadVarImpl(True);
inThreadVar: ReadThreadVarImpl(True);
inResourceString: ReadResourceStringImpl(True);
else
Error('Not in Type, Const, Var');
end;
end;
else
DoNextToken(False);
end;
end;
end;
procedure TDelphiParser.ReadInitializationFinalization;
var
BeginCount: Integer;
S: string;
begin
{ PRE: Token = 'initialization'
POST: Token = 'end'
}
BeginLowRecording;
BeginCount := 1;
while True do
begin
CheckNotToken(toEof);
if Token = toSymbol then
case TokenSymbolInC(['begin', 'case', 'try', 'asm', 'end']) of
0, 1, 2, 3: { begin/case/try/asm }
Inc(BeginCount);
4: { end }
begin
Dec(BeginCount);
if BeginCount = 0 then
begin
EndLowRecording;
{ Minus the 'end' }
S := LowRecordingStr;
FPasItems.Add(TInitializationFinaliziationItem.Create(
Copy(S, 1, Length(S) - 3)));
DoNextToken;
Exit;
end;
end;
end;
DoNextToken;
end;
end;
procedure TDelphiParser.ReadInterfaceBlock;
var
Position: TPosition;
begin
Position := inNull;
StopCapitalization;
while Token <> toEof do
case Token of
toSymbol:
case TokenSymbolInC([
{0}'implementation',
{1}'procedure',
{2}'function',
{3}'resourcestring',
{4}'const',
{5}'type',
{6}'var',
{7}'threadvar']) of
0: Exit;
1: ReadProcedure;
2: ReadFunction;
3:
begin
Position := inResourceString;
DoNextToken;
end;
4:
begin
Position := inConst;
DoNextToken;
end;
5:
begin
Position := inType;
DoNextToken;
end;
6: { var }
begin
Position := inVar;
DoNextToken;
end;
7: { threadvar }
begin
Position := inThreadVar;
DoNextToken;
end
else
case Position of
inConst: ReadConst;
inType: ReadTypeDef;
inVar: ReadVar;
inThreadVar: ReadThreadVar;
inResourceString: ReadResourceString;
else
Error('Not in Type, Const, Var');
end;
end;
else
DoNextToken;
end;
while (Token <> toEof) and
((Token <> toSymbol) or not SameText(TokenString, 'implementation')) do
DoNextToken;
end;
procedure TDelphiParser.ReadInterfaceMethods(AInterfaceItem: TInterfaceItem);
begin
while True do
begin
CheckNotToken(toEof);
case TokenSymbolInC(['end', 'property', 'procedure', 'function']) of
0: { end }
begin
DoNextToken;
CheckToken(toSemiColon);
Exit;
end;
1: { property }
ReadClass_Property(AInterfaceItem, inPublic);
2: { procedure }
ReadClass_Procedure(AInterfaceItem, inPublic);
3: { function }
ReadClass_Function(AInterfaceItem, inPublic);
else
DoNextToken;
end;
end;
end;
procedure TDelphiParser.ReadInterfaceStatement;
begin
CheckTokenSymbol('interface');
DoNextToken(False);
end;
function TDelphiParser.ReadInterfaceType: TAbstractItem;
var
InterfaceItem: TInterfaceItem;
begin
(* vb
IJvDataConsumer = interface;
IJvDataConsumer = interface
['{B2F18D03-F615-4AA2-A51A-74D330C05C0E}']
PRE : Token = 'interface'
POST: Token = ;
*)
DoNextToken;
if Token = toSemiColon then
begin
{ Class is nog niet compleet gedefinieerd; niet toevoegen }
Result := nil;
Exit;
end;
if Token = toLeftBracket then
SkipUntilToken(toRightBracket);
{ Nu pas toevoegen }
InterfaceItem := TInterfaceItem.Create('');
FPasItems.Add(InterfaceItem);
Result := InterfaceItem;
ReadInterfaceMethods(InterfaceItem);
CheckToken(toSemiColon);
end;
function TDelphiParser.ReadNextToken: Char;
var
I: Integer;
P: PChar;
LStartSourceLine: Integer;
function IsEndReached: Boolean;
var
Position: Integer;
begin
{ P^ = #0 -> Einde buffer }
Result := P^ = #0;
if not Result then
Exit;
{ Kan nog iets ingelezen worden? }
Position := P - FSourcePtr;
Result := ReadPortion(Position);
P := FSourcePtr + Position;
end;
procedure NextChar;
begin
Inc(P);
if P^ = #10 then
Inc(FSourceLine);
if P^ = #0 then
IsEndReached;
end;
begin
{ Let op: !!!!!!!!!!!!
geen multi-exit; FToken moet nog gezet worden }
LStartSourceLine := FSourceLine;
SkipBlanks;
P := FSourcePtr;
FTokenPtr := P;
case P^ of
'{':
begin
NextChar;
if P^ <> '$' then
begin
while P^ <> '}' do
NextChar;
if P^ = '}' then
NextChar;
if LStartSourceLine = FSourceLine then
Result := toSameLineComment
else
Result := toComment;
end
else
begin
{ A compiler directive starts with a $ as the first character after
the opening comment delimiter, immediately followed by a name (one
or more letters) }
NextChar;
while not (P^ in [#0, '}']) do
NextChar;
if P^ = '}' then
NextChar;
Result := toCompilerDirective;
end;
end;
'(':
begin
NextChar;
if P^ = '*' then
begin
NextChar;
repeat
while P^ <> '*' do
NextChar;
if P^ = '*' then
NextChar;
until P^ in [#0, ')'];
if P^ = ')' then
NextChar;
if LStartSourceLine = FSourceLine then
Result := toSameLineComment
else
Result := toComment;
end
else
Result := toLeftParens;
end;
'A'..'Z', 'a'..'z', '_':
begin
NextChar;
while P^ in ['A'..'Z', 'a'..'z', '0'..'9', '_'] do
NextChar;
Result := toSymbol;
end;
'#', '''':
begin
while True do
case P^ of
'#':
begin
NextChar;
I := 0;
while P^ in ['0'..'9'] do
begin
I := I * 10 + (Ord(P^) - Ord('0'));
NextChar;
end;
end;
'''':
begin
NextChar;
while True do
begin
case P^ of
#0, #10, #13:
Error(SInvalidString);
'''':
begin
NextChar;
if P^ <> '''' then
Break;
end;
end;
NextChar;
end;
end;
else
Break;
end;
Result := toString;
end;
'$':
begin
NextChar;
while P^ in ['0'..'9', 'A'..'F', 'a'..'f'] do
NextChar;
Result := toInteger;
end;
'-', '0'..'9':
begin
NextChar;
while P^ in ['0'..'9'] do
NextChar;
Result := toInteger;
if P^ = '.' then
begin
NextChar;
if P^ = '.' then
Dec(P)
else
Result := toFloat;
end;
while P^ in ['0'..'9', 'e', 'E', '+', '-'] do
begin
NextChar;
Result := toFloat;
end;
if P^ in ['c', 'C', 'd', 'D', 's', 'S'] then
begin
Result := toFloat;
FFloatType := P^;
NextChar;
end
else
FFloatType := #0;
end;
'.':
begin
NextChar;
if P^ = '.' then
begin
Result := toDotDot;
NextChar;
end
else
Result := toDot;
end;
'/':
begin
NextChar;
if P^ = '/' then
begin
if LStartSourceLine = FSourceLine then
Result := toSameLineComment
else
Result := toComment;
while not (P^ in [#13, #10, #0]) do
NextChar;
//while P^ in [#13, #10] do
// NextChar;
end
else
Result := '/';
end;
else
Result := P^;
if Result <> toEof then
NextChar;
end;
FSourcePtr := P;
FToken := Result;
end;
procedure TDelphiParser.ReadParamList(AParams, ATypes: TStrings; const HaakType: THaakType);
const
CLeftHaak: array[THaakType] of Char = (toLeftParens, toLeftBracket);
CRightHaak: array[THaakType] of Char = (toRightParens, toRightBracket);
procedure EndParamTypeRecording;
begin
if not Recording then
begin
if Assigned(ATypes) and Assigned(AParams) then
while ATypes.Count < AParams.Count do
ATypes.Add('');
Exit;
end;
if Assigned(ATypes) and Assigned(AParams) then
while ATypes.Count < AParams.Count do
ATypes.Add(Trim(RemoveEndChars(RecordStr, [' ', toSemiColon, toEquals, toRightParens])));
Recording := False;
end;
var
Haakjes: Integer;
NewParam: Boolean;
begin
{ Example:
(P1: T1);
(P1, P2: T1);
[Year, Month, Day: Word] // property
;
PRE : Token = toLeftParens or Token = toSemiColon (no param list)
AStrings might be nil
POST: Token is first symbol after ')'
}
Haakjes := 0;
NewParam := True;
try
while True do
begin
case Token of
toSemiColon:
begin
EndParamTypeRecording;
if Haakjes = 0 then
Exit;
NewParam := True;
end;
toEquals:
{ Do not add default values to the type }
EndParamTypeRecording;
toLeftParens, toLeftBracket:
if CLeftHaak[HaakType] = Token then
Inc(Haakjes);
toRightParens, toRightBracket:
if CRightHaak[HaakType] = Token then
begin
Dec(Haakjes);
if Haakjes = 0 then
begin
EndParamTypeRecording;
DoNextToken;
Exit;
end;
end;
toEof:
Exit;
toSymbol:
if (Haakjes > 0) and NewParam then
begin
if TokenSymbolInC(['const', 'var', 'out']) >= 0 then
begin
DoNextToken;
Continue;
end;
{ (var X) is ook mogelijk }
if Assigned(AParams) then
AParams.Add(TokenString);
DoNextToken;
{SkipComments;}
if Token <> toComma then
begin
NewParam := False;
{ Let op deze !! }
Continue;
end;
end
else
begin
if not Recording then
Recording := True;
end;
end;
DoNextToken;
end;
finally
Recording := False;
end;
end;
procedure TDelphiParser.ReadProcedure;
var
ProcedureItem: TProcedureItem;
Directives: TDirectives;
begin
{ Example:
procedure P1(P1: T1; P2: T2);
procedure P1;
procedure T20(Unicode: PWideChar; var S: WideString; Len: Integer); cdecl; export;
procedure PaintHook(p: QPainterH; R: PRect) cdecl;
PRE : Token = 'procedure'
POST: Token = ;
}
DoNextToken;
CheckToken(toSymbol);
ProcedureItem := TProcedureItem.Create(TokenString);
FPasItems.Add(ProcedureItem);
DoNextToken;
{ Token is ( or ; or some directive }
if Token = toLeftParens then
ReadParamList(ProcedureItem.Params, ProcedureItem.ParamTypes);
{ Token = ; or some directive }
Directives := [];
ReadDirectives(True, Directives);
ProcedureItem.Directives := Directives;
CheckToken(toSemiColon);
end;
function TDelphiParser.ReadProcedureHeader(const DoAdd: Boolean; out IsOnlyHeader: Boolean): TAbstractItem;
var
MethodType: TMethodType;
FirstToken: string;
Directives: TDirectives;
begin
if TokenSymbolIs('constructor') then
MethodType := mtConstructor
else
if TokenSymbolIs('destructor') then
MethodType := mtDestructor
else
MethodType := mtNormal;
DoNextToken;
CheckToken(toSymbol);
StartCapitalization;
FirstToken := TokenString;
DoNextToken;
if Token = toDot then
begin
DoNextToken;
CheckToken(toSymbol);
if DoAdd then
begin
Result := TMethodProcItem.Create(TokenString);
FPasItems.Add(Result);
TMethodProcItem(Result).MethodType := MethodType;
TMethodProcItem(Result).OwnerClassAsString := FirstToken;
end
else
Result := nil;
DoNextToken;
end
else
begin
if DoAdd then
begin
Result := TProcedureItem.Create(FirstToken);
FPasItems.Add(Result);
end
else
Result := nil;
end;
{ Token is toLeftParens or toSemiColon or some directive }
if Token = toLeftParens then
SkipParamList;
Directives := [];
ReadDirectives(True, Directives);
IsOnlyHeader := [diExternal, diForward] * Directives <> [];
StopCapitalization;
CheckToken(toSemiColon);
end;
function TDelphiParser.ReadProcedureImpl(const DoAdd: Boolean): TAbstractItem;
var
OnlyHeader: Boolean;
begin
Assert(FHoldRecapitalize, 'cap = true');
if DoAdd then
begin
BeginLowRecording;
MakeCopyOfDEFList;
end;
BeginBlock;
Result := ReadProcedureHeader(DoAdd, OnlyHeader);
EndBlock(True);
if not OnlyHeader then
begin
BeginBlock;
ReadFunctionProcedureBody;
EndBlock(False);
end;
if DoAdd then
begin
EndLowRecording;
if Assigned(Result) then
begin
Result.ImplementationStr := LowRecordingStr;
Result.BeginDEFList := FCopiedDEFList;
Result.EndDEFList := FDEFList;
end;
end;
DoNextToken(False);
end;
function TDelphiParser.ReadProcedureType: TAbstractItem;
var
Directives: TDirectives;
begin
{ Example:
TStrProc = procedure(const S: string);
TNotifyEvent = procedure(Sender: TObject) of object;
PRE : Token = 'procedure'
POST: Token = ; or =
}
Result := TProcedureTypeItem.Create('');
FPasItems.Add(Result);
DoNextToken;
{ Token is toLeftParens or toSemiColon or 'of object' or ?? }
if Token = toLeftParens then
with TProcedureTypeItem(Result) do
ReadParamList(Params, ParamTypes);
Directives := [];
ReadDirectives(True, Directives);
TProcedureTypeItem(Result).Directives := Directives;
if not (Token in [toSemiColon, toEquals]) then
Error('; or = expected');
end;
procedure TDelphiParser.ReadPropertySpecifiers(
const MaySkipSemiColon: Boolean; var Specifiers: TPropertySpecifiers);
var
Specifier: Integer;
begin
{
Pre : Token = ; or some specifier
Post : Token = ;
}
if ((Token <> toSemiColon) or not MaySkipSemiColon) and
((Token <> toSymbol) or (TokenSymbolInC(CPropertySpecifiers) < 0)) then
Exit;
while True do
begin
if Token = toSemiColon then
begin
SaveRollBackPosition;
DoNextToken;
if (Token <> toSymbol) or (TokenSymbolInC(CPropertySpecifiers) < 0) then
begin
RollBackToSavedPosition;
Exit;
end;
ForgetRollBackPosition;
end;
while Token = toSymbol do
begin
Specifier := TokenSymbolInC(CPropertySpecifiers);
if Specifier < 0 then
Error('Specifier expected')
else
Include(Specifiers, TPropertySpecifier(Specifier));
DoNextToken;
end;
CheckToken(toSemiColon);
end;
end;
function TDelphiParser.ReadRecord: TAbstractItem;
begin
{ Example:
R1 = record F1, F2: T1 end; <-- Let op ","
R1 = record F1: T1; F2: T2; end;
R1 = record case tag: ordinalType of
constantList1: (variant1);
...
constantListn: (variantn);
end;
variant1 = fieldList1: type1;
...
fieldListn: typen;
R1 = record
F1: T1; F2: T2;
F3: record case T3 of
constantList1: (F1': T1');
...
constantListn: (Fn': Tn');
end;
end;
PRE : Token is 'record'
POST: Token is token after 'end'
}
Result := TRecordItem.Create('');
FPasItems.Add(Result);
DoNextToken;
while True do
begin
case Token of
toSymbol:
if TokenSymbolIs('end') then
Break
else
if TokenSymbolIs('case') then
begin
SkipUntilSymbol('of');
DoNextToken;
SkipUntilToken(toLeftParens);
end
else
begin
{ Lees (identifier:type) paar in }
TRecordItem(Result).Items.Add(TokenString);
DoNextToken;
if Token <> toComma then
begin
CheckToken(toColon);
DoNextToken;
SkipType(False, True);
{ Note : Token = ; or end }
Continue;
end;
end;
toRightParens: { empty list or closing }
begin
DoNextToken;
while Token = toRightParens do
DoNextToken;
if Token = toSemiColon then
DoNextToken;
if TokenSymbolIs('end') then
Break
else
begin
SkipUntilToken(toColon);
DoNextToken;
CheckToken(toLeftParens);
end;
end;
toEof:
Exit;
end;
DoNextToken;
end;
CheckTokenSymbol('end');
DoNextToken;
end;
function TDelphiParser.ReadResourceString: TAbstractItem;
var
ResourceStringItem: TResourceStringItem;
begin
{ RS1 = V1;
PRE : Token = Identifier (RS1)
POST: Token = ;
}
StartCapitalization;
ResourceStringItem := TResourceStringItem.Create(TokenString);
FPasItems.Add(ResourceStringItem);
DoNextToken;
CheckToken(toEquals);
BeginRecording;
SkipUntilToken(toSemiColon);
EndRecording;
StopCapitalization;
ResourceStringItem.Value := RecordStr;
CheckToken(toSemiColon);
Result := ResourceStringItem;
end;
function TDelphiParser.ReadResourceStringImpl(const DoAdd: Boolean): TAbstractItem;
begin
if DoAdd then
begin
BeginLowRecording;
MakeCopyOfDEFList;
end;
Result := SkipResourceString(DoAdd);
CheckToken(toSemiColon);
if DoAdd then
begin
EndLowRecording;
if Assigned(Result) then
begin
Result.ImplementationStr := LowRecordingStr;
Result.BeginDEFList := FCopiedDEFList;
Result.EndDEFList := FDEFList;
end;
end;
DoNextToken(False);
end;
function TDelphiParser.ReadSimpleType: TAbstractItem;
begin
StartCapitalization;
BeginRecording;
Result := SkipSimpleType(True);
EndRecording;
StopCapitalization;
if Result is TTypeItem then
TTypeItem(Result).Value := RecordStr;
end;
function TDelphiParser.ReadThreadVar: TAbstractItem;
begin
Result := ReadVar;
if Result is TVarItem then
TVarItem(Result).IsThreadVar := True;
end;
function TDelphiParser.ReadThreadVarImpl(
const DoAdd: Boolean): TAbstractItem;
begin
Result := ReadVarImpl(DoAdd);
if Result is TVarItem then
TVarItem(Result).IsThreadVar := True;
end;
function TDelphiParser.ReadType(const DoReadDirectives: Boolean): TAbstractItem;
begin
{
PRE:
POST: Type including directives read
}
if Token = toLeftParens then
Result := ReadEnumerator
else
case TokenSymbolInC(['record', 'class', 'procedure', 'function', 'interface',
'dispinterface', 'packed']) of
0: { record }
Result := ReadRecord;
1: { class}
Result := ReadClass;
2: { procedure }
Result := ReadProcedureType;
3: { function }
Result := ReadFunctionType;
4: { interface }
Result := ReadInterfaceType;
5: { dispinterface }
Result := ReadDispInterface;
6: {packed }
begin
DoNextToken;
CheckToken(toSymbol);
if TokenSymbolIs('record') then
Result := ReadRecord
else
if TokenSymbolIs('array') then
Result := ReadSimpleType
else
begin
Result := nil;
Error('record or array expected');
end;
end
else
Result := ReadSimpleType;
end;
if DoReadDirectives then
SkipDirectives(False);
end;
function TDelphiParser.ReadTypeDef: TAbstractItem;
var
TypeName: string;
begin
{ Example:
T1 = record F1: T1; F2: T2; end;
T1 = class() [classdef] end;
T1 = sometype;
PRE : Token = identifier [T1]
POST: Token = ;
}
TypeName := TokenString;
DoNextToken;
CheckToken(toEquals);
DoNextToken;
Result := ReadType(False);
if Assigned(Result) then
Result.SimpleName := TypeName;
SkipDirectives(False); { 'deprecated', 'platform' }
CheckToken(toSemiColon);
end;
function TDelphiParser.ReadTypeDefImpl(const DoAdd: Boolean): TAbstractItem;
begin
if DoAdd then
begin
BeginLowRecording;
MakeCopyOfDEFList;
end;
Result := SkipTypeDef(DoAdd);
CheckToken(toSemiColon);
if DoAdd then
begin
EndLowRecording;
if Assigned(Result) then
begin
Result.ImplementationStr := LowRecordingStr;
Result.BeginDEFList := FCopiedDEFList;
Result.EndDEFList := FDEFList;
end;
end;
DoNextToken(False);
end;
procedure TDelphiParser.ReadUnitBlock(out AModuleType: TModuleType);
begin
CheckToken(toSymbol);
if TokenSymbolIs('library') then
AModuleType := mtLibrary
else
if TokenSymbolIs('unit') then
AModuleType := mtUnit
else
Error('''library'' or ''unit'' expected');
DoNextToken;
SkipUntilToken(toSemiColon);
DoNextToken;
end;
function TDelphiParser.ReadUsesBlock(const DoAdd: Boolean): TAbstractItem;
begin
Result := nil;
if Token in [toComment, toSameLineComment, toCompilerDirective] then
begin
SaveRollBackPosition;
DoNextToken;
if not TokenSymbolIsC('uses') then
begin
RollBackToSavedPosition;
Exit;
end;
ForgetRollBackPosition;
end;
if not TokenSymbolIsC('uses') then
Exit;
if DoAdd then
begin
MakeCopyOfDEFList;
Result := TUsesItem.Create('');
FPasItems.Add(Result);
BeginLowRecording;
end;
BeginBlock;
StartCapitalization;
SkipUntilToken(toSemiColon);
StopCapitalization;
EndBlock(True);
{ Token = ; or ENDIF directive }
if DoAdd then
begin
EndLowRecording;
if Assigned(Result) then
begin
Result.ImplementationStr := LowRecordingStr;
Result.BeginDEFList := FCopiedDEFList;
Result.EndDEFList := FDEFList;
end;
end;
DoNextToken(False);
end;
function TDelphiParser.ReadVar: TAbstractItem;
begin
{ Example:
V1: T1;
IdSslCtxFree : procedure(arg0: PSSL_CTX) cdecl = nil;
QBDRed, QBDBlue, QBDGreen: byte;
PRE: Token = var. identifier (V1 in example)
POST: Token = ;
}
Result := TVarItem.Create(TokenString);
FPasItems.Add(Result);
DoNextToken;
while Token = toComma do
begin
DoNextToken;
CheckToken(toSymbol);
FPasItems.Add(TVarItem.Create(TokenString));
DoNextToken;
end;
CheckToken(toColon);
DoNextToken;
SkipType(False, True);
if Token = toEquals then
begin
DoNextToken;
SkipConstValue;
end;
CheckToken(toSemiColon);
end;
function TDelphiParser.ReadVarImpl(const DoAdd: Boolean): TAbstractItem;
begin
if DoAdd then
begin
BeginLowRecording;
MakeCopyOfDEFList;
end;
Result := SkipVar(DoAdd);
CheckToken(toSemiColon);
if DoAdd then
begin
EndLowRecording;
if Assigned(Result) then
begin
Result.ImplementationStr := LowRecordingStr;
Result.BeginDEFList := FCopiedDEFList;
Result.EndDEFList := FDEFList;
end;
end;
DoNextToken(False);
end;
procedure TDelphiParser.RecapitalizeToken;
var
Index: Integer;
begin
if (Token <> toSymbol) or not Assigned(FCapitalization) then
Exit;
Index := FCapitalization.IndexOf(TokenString);
if Index >= 0 then
RecapitalizeTokenWith(FCapitalization[Index]);
end;
procedure TDelphiParser.RecapitalizeTokenWith(const S: string);
var
L: Integer;
begin
L := FSourcePtr - FTokenPtr;
if Length(S) = L then
Move(PChar(S)^, FTokenPtr^, L);
end;
procedure TDelphiParser.RollBackToSavedPosition;
begin
FDEFList.Assign(FSavedDEFList);
inherited RollBackToSavedPosition;
end;
procedure TDelphiParser.SaveRollBackPosition;
begin
FSavedDEFList.Assign(FDEFList);
inherited SaveRollBackPosition;
end;
procedure TDelphiParser.SetAcceptCompilerDirectives(const Value: TStrings);
begin
FAcceptCompilerDirectives.Assign(Value);
end;
function TDelphiParser.SkipClass(const DoAdd: Boolean): TAbstractItem;
begin
{ Example:
Tx = class(Tx1) .. end;
Tx = class .. end;
Tx = class; -> Deze niet toevoegen, moet nog compleet
gedefinieerd worden
Tx = class(Tx1); -> Hack class
Tx = class of Tx1; -> Meta class
PRE : Token = 'class'
POST: Token = ;
}
DoNextToken;
if Token = toSemiColon then
begin
{ Class is nog niet compleet gedefinieerd; niet toevoegen }
if DoAdd then
begin
Result := TTypeItem.Create('');
FPasItems.Add(Result);
end
else
Result := nil;
Exit;
end;
if Token = toLeftParens then
begin
DoNextToken;
CheckToken(toSymbol);
SkipUntilToken(toRightParens);
DoNextToken;
end;
{ Now add }
if DoAdd then
begin
if TokenSymbolIs('of') then
Result := TMetaClassItem.Create('')
else
Result := TClassItem.Create('');
FPasItems.Add(Result);
end
else
Result := nil;
if TokenSymbolIs('of') then
begin
DoNextToken;
CheckToken(toSymbol);
SkipUntilToken(toSemiColon);
end
else
if Token <> toSemiColon then
SkipClassMethods
end;
procedure TDelphiParser.SkipClassMethods;
begin
{ vb
public property P1; end;
PRE : Token = token after 'class'
POST: Token = ; (= first token after 'end')
}
while True do
begin
CheckNotToken(toEof);
if Token = toSymbol then
case TokenSymbolInC(['end', 'private', 'protected', 'public', 'published',
'property', 'procedure', 'constructor', 'destructor', 'function', 'class']) of
0: { end }
begin
DoNextToken;
{ token = directive or ; }
Exit;
end;
1, 2, 3, 4: { private, protected, public, published }
DoNextToken;
5: { property }
SkipClass_Property;
6, 7, 8: { procedure, constructor, destructor }
SkipClass_Procedure;
9: {function }
SkipClass_Function;
10: {class }
SkipClass_ClassMethod;
else { field }
SkipClass_Field;
end
else { not a symbol, probably ; }
DoNextToken;
end;
end;
procedure TDelphiParser.SkipClass_ClassMethod;
begin
DoNextToken;
CheckToken(toSymbol);
case CheckTokenSymbolInC(['function', 'procedure']) of
0: SkipClass_Function;
1: SkipClass_Procedure;
end;
end;
procedure TDelphiParser.SkipClass_Field;
begin
StartCapitalization;
SkipUntilToken(toColon);
DoNextToken;
SkipType(False, True);
//SkipUntilToken(toSemiColon);
StopCapitalization;
end;
procedure TDelphiParser.SkipClass_Function;
begin
{ Example:
function F1(P1: T1; P2: T2);
function IMalloc.Alloc = Allocate;
PRE : Token = 'function'
POST: Token = ;
}
DoNextToken;
StartCapitalization;
CheckToken(toSymbol);
DoNextToken;
if Token = '.' then
begin
{ Method resolution clause }
DoNextToken;
CheckToken(toSymbol);
DoNextToken;
CheckToken(toEquals);
DoNextToken;
CheckToken(toSymbol);
DoNextToken;
end
else
begin
if Token = toLeftParens then
SkipParamList;
CheckToken(toColon);
DoNextToken;
SkipType(False, False);
SkipDirectives(True);
end;
StopCapitalization;
CheckToken(toSemiColon);
end;
procedure TDelphiParser.SkipClass_Procedure;
begin
{ Example:
procedure P1(P1: T1; P2: T2);
PRE : Token = 'procedure' or 'constructor' or 'destructor'
POST: Token = ;
}
DoNextToken;
StartCapitalization;
CheckToken(toSymbol);
DoNextToken;
if Token = toDot then
begin
{ Method resolution clause }
DoNextToken;
CheckToken(toSymbol);
DoNextToken;
CheckToken(toEquals);
DoNextToken;
CheckToken(toSymbol);
DoNextToken;
end
else
begin
if Token = toLeftParens then
SkipParamList;
SkipDirectives(True);
end;
StopCapitalization;
CheckToken(toSemiColon);
end;
procedure TDelphiParser.SkipClass_Property;
begin
{ Bv:
propery P1: X1 read Get1 write Get2
property P1;
property P1 default X;
property Bold[Year, Month, Day: Word]: Boolean read IsBold write SetBold;
Pre : Token = 'property'
POST: Token = ;
}
DoNextToken;
StartCapitalization;
DoNextToken;
if (Token = toSemiColon) or
((Token = toSymbol) and (TokenSymbolInC(['default', 'stored']) >= 0)) then
begin
SkipUntilToken(toSemiColon);
end
else
begin
if Token = toLeftBracket then
SkipParamList(htBracket);
SkipUntilToken(toSymbol);
while not (Token in [toEof, toSemiColon]) and (TokenSymbolInC(CPropertySpecifiers) < 0) do
DoNextToken;
while not (Token in [toSemiColon, toEof]) do
begin
{ TODO : Anders }
TokenSymbolInC(CPropertySpecifiers);
DoNextToken;
end;
end;
CheckToken(toSemiColon);
SkipPropertySpecifiers(True);
StopCapitalization;
CheckToken(toSemiColon);
end;
function TDelphiParser.SkipConst(const DoAdd: Boolean): TAbstractItem;
begin
{ Example:
C1 = V1;
C1: type = V1;
C1: array [xx] of TSpecialFolderInfo = ((), (), ());
C1: function (AOwner: TComponent; ActionClass: TBasicActionClass): TBasicAction = nil;
PRE : Token = identifier [C1]
POST: Token = ;
}
StartCapitalization;
if DoAdd then
begin
Result := TConstItem.Create(TokenString);
FPasItems.Add(Result);
end
else
Result := nil;
DoNextToken;
case Token of
toEquals:
begin
DoNextToken;
SkipConstValue;
StopCapitalization;
SkipDirectives(False);
end;
toColon:
begin
DoNextToken;
SkipType(False, True);
CheckToken(toEquals);
DoNextToken;
SkipConstValue;
end;
else
Error('= or : expected');
end;
CheckToken(toSemiColon);
end;
procedure TDelphiParser.SkipConstantExpression(const ExpectDotDot: Boolean);
begin
{ Examples
const
DOW_WEEK : TTFDaysOfWeek = [dowSunday..dowSaturday];
_________________________
StIdSymbols = ['_', '0'..'9', 'A'..'Z', 'a'..'z'];
____________________________________
StdWordDelims = [#0..' ', ','] + Brackets;
__________________________
}
{ POST : Token = toSemiColon ';' or 'end' }
while True do
begin
if (Token = toSymbol) and (TokenSymbolInC(CDirectives) > 0) then
Exit;
CheckNotToken(toEof);
{ TODO : Nodig? }
if TokenSymbolInC(CAllowableSymbolsInTypeDef) >= 0 then
SkipUntilTokenInHaak(toLeftParens, toRightParens)
else
if TokenSymbolIs('end') then
Exit
else
case Token of
toRightParens:
Exit;
toLeftParens:
SkipUntilTokenInHaak(toLeftParens, toRightParens);
toLeftBracket:
SkipUntilTokenInHaak(toLeftBracket, toRightBracket);
toDotDot:
begin
DoNextToken;
CheckNotToken(toDot);
SkipConstantExpression(False);
Exit;
end;
toDot:
begin
DoNextToken;
CheckNotToken(toDot);
Continue;
end;
toSemiColon, '=':
Exit;
end;
DoNextToken;
end;
end;
procedure TDelphiParser.SkipConstValue;
begin
SkipConstantExpression(False);
end;
procedure TDelphiParser.SkipDirectives(const MaySkipSemiColon: Boolean);
var
Directive: Integer;
begin
{
Pre : Token = ; or some directive
Post : Token = ; or =
}
StopCapitalization;
if Token = toSemiColon then
begin
if not MaySkipSemiColon then
Exit;
Directive := 0;
end
else
begin
Directive := TokenSymbolInC(CDirectives);
if Directive < 0 then
Exit;
{ Directive is valid }
end;
{ Token = ; or Directive is valid }
while True do
begin
CheckNotToken(toEof);
if Token = toSemiColon then
begin
SaveRollBackPosition;
DoNextToken;
Directive := TokenSymbolInC(CDirectives);
if Directive < 0 then
begin
RollBackToSavedPosition;
Exit;
end;
{ Directive is valid }
ForgetRollBackPosition;
end;
repeat
if Directive < 0 then
Error('Directive expected');
case TDirective(Directive) of
diMessage, diExternal:
SkipUntilToken(toSemiColon);
else
DoNextToken;
end;
Directive := TokenSymbolInC(CDirectives);
until Token <> toSymbol;
if Token = toEquals then
Exit;
CheckToken(toSemiColon);
end;
end;
function TDelphiParser.SkipDispInterface(
const DoAdd: Boolean): TAbstractItem;
begin
{ TODO: Implement }
SkipUntilSymbol('end');
SkipUntilToken(toSemiColon);
Result := nil;
end;
function TDelphiParser.SkipEnumerator(const DoAdd: Boolean): TAbstractItem;
var
NewValue: Boolean;
Haakjes: Integer;
begin
{ Example:
(E1, E2, E3);
();
(Small = 5, Medium = 10, Large = Small + Medium);
PRE : Token = (
POST: Token = ;
}
if DoAdd then
begin
Result := TEnumItem.Create('');
FPasItems.Add(Result);
end
else
Result := nil;
{ NewValue hebben we nodig om bv in '(Small = 5, ..' 5 niet mee te nemen }
NewValue := True;
Haakjes := 0;
while True do
begin
CheckNotToken(toEof);
case Token of
toSemiColon:
if Haakjes = 0 then
Exit;
toLeftParens:
Inc(Haakjes);
toRightParens:
begin
Dec(Haakjes);
if Haakjes = 0 then
begin
DoNextToken;
Exit;
end;
end;
toSymbol:
if NewValue then
begin
NewValue := False;
end;
toComma:
NewValue := True;
end;
DoNextToken;
end;
end;
procedure TDelphiParser.SkipFunction;
begin
{ Example:
function F1(P1: T1; P2: T2);
PRE : Token = 'function'
POST: Token = ;
}
CheckTokenSymbol('function');
StartCapitalization;
DoNextToken;
CheckToken(toSymbol);
DoNextToken;
{ Token = toLeftParens or toColon }
if Token = toLeftParens then
SkipParamList;
CheckToken(toColon);
DoNextToken;
SkipType(False, False);
SkipDirectives(True);
StopCapitalization;
CheckToken(toSemiColon);
end;
function TDelphiParser.SkipFunctionType(const DoAdd: Boolean): TAbstractItem;
begin
{ Example:
F1 = Function();
TODO : Deze gaat fout : dwz ReadType leest ook directives in
function(ctx: PSSL_CTX; const _file: PChar; _type: Integer):Integer cdecl = nil;
T17 : function(arg0: PSSL_CTX; str: PChar):Integer cdecl = nil;
__________________________________________________
PRE : Token = 'function'
POST: Token = ;
}
if DoAdd then
begin
Result := TFunctionTypeItem.Create('');
FPasItems.Add(Result);
end
else
Result := nil;
DoNextToken;
{ Token is toLeftParens or toSemiColon or 'of object' or ?? }
if Token = toLeftParens then
SkipParamList;
CheckToken(toColon);
DoNextToken;
SkipType(False, False);
SkipDirectives(True);
if not (Token in [toSemiColon, toEquals]) then
Error('; or = expected');
end;
procedure TDelphiParser.SkipInterfaceBlock;
var
Position: TPosition;
begin
{ POST: Token = 'implementation' }
Position := inNull;
StopCapitalization;
while Token <> toEof do
case Token of
toSymbol:
case TokenSymbolInC([
{0}'implementation',
{1}'procedure',
{2}'function',
{3}'resourcestring',
{4}'const',
{5}'type',
{6}'var',
{7}'threadvar']) of
0: Exit;
1: ReadProcedure;
2: ReadFunction;
3:
begin
Position := inResourceString;
DoNextToken;
end;
4:
begin
Position := inConst;
DoNextToken;
end;
5:
begin
Position := inType;
DoNextToken;
end;
6, 7:
begin
Position := inVar;
DoNextToken;
end
else
case Position of
inConst: SkipConst(False);
inType: SkipTypeDef(False);
inVar: SkipVar(False);
//inThreadVar: SkipThreadVar(False); { not possible here }
inResourceString: SkipResourceString(False);
else
Error('Not in Type, Const, Var');
end;
end;
else
DoNextToken;
end;
{ TODO : Huh ?? }
while (Token <> toEof) and
((Token <> toSymbol) or not SameText(TokenString, 'implementation')) do
DoNextToken;
end;
procedure TDelphiParser.SkipInterfaceMethods;
begin
while True do
begin
CheckNotToken(toEof);
case TokenSymbolInC(['end', 'property', 'procedure', 'function']) of
0: { end }
begin
DoNextToken;
CheckToken(toSemiColon);
Exit;
end;
1: { property }
SkipClass_Property;
2: { procedure }
SkipClass_Procedure;
3: { function }
SkipClass_Function;
else
DoNextToken;
end;
end;
end;
function TDelphiParser.SkipInterfaceType(const DoAdd: Boolean): TAbstractItem;
begin
(* vb
IJvDataConsumer = interface;
IJvDataConsumer = interface
['{B2F18D03-F615-4AA2-A51A-74D330C05C0E}']
PRE : Token = 'interface'
POST: Token = ;
*)
DoNextToken;
if Token = toSemiColon then
begin
{ Class is nog niet compleet gedefinieerd; niet toevoegen }
Result := nil;
Exit;
end;
if Token = toLeftBracket then
SkipUntilToken(toRightBracket);
{ Nu pas toevoegen }
if DoAdd then
begin
Result := TInterfaceItem.Create('');
FPasItems.Add(Result);
end
else
Result := nil;
SkipInterfaceMethods;
CheckToken(toSemiColon);
end;
procedure TDelphiParser.SkipParamList(const HaakType: THaakType);
const
CLeftHaak: array[THaakType] of Char = (toLeftParens, toLeftBracket);
CRightHaak: array[THaakType] of Char = (toRightParens, toRightBracket);
var
Haakjes: Integer;
NewParam: Boolean;
begin
{ Example:
(P1: T1);
(P1, P2: T1);
[Year, Month, Day: Word] // property
;
PRE : Token = toLeftParens or Token = toSemiColon (no param list)
AStrings might be nil
POST: Token is first symbol after ')'
}
Haakjes := 0;
NewParam := True;
while True do
begin
case Token of
toSemiColon:
begin
if Haakjes = 0 then
Exit;
NewParam := True;
end;
toEquals:
{ Do not add default values to the type }
;
toLeftParens, toLeftBracket:
if CLeftHaak[HaakType] = Token then
Inc(Haakjes);
toRightParens, toRightBracket:
if CRightHaak[HaakType] = Token then
begin
Dec(Haakjes);
if Haakjes = 0 then
begin
DoNextToken;
Exit;
end;
end;
toEof:
Exit;
toSymbol:
if (Haakjes > 0) and NewParam then
begin
if TokenSymbolInC(['const', 'var', 'out']) >= 0 then
begin
DoNextToken;
Continue;
end;
DoNextToken;
if Token <> toComma then
begin
NewParam := False;
{ Let op deze !! }
Continue;
end;
end;
end;
DoNextToken;
end;
end;
procedure TDelphiParser.SkipProcedure;
begin
{ Example:
procedure P1(P1: T1; P2: T2);
procedure P1;
procedure T20(Unicode: PWideChar; var S: WideString; Len: Integer); cdecl; export;
procedure PaintHook(p: QPainterH; R: PRect) cdecl;
PRE : Token = 'procedure' or 'constructor' or 'destructor'
POST: Token = ;
}
DoNextToken;
StartCapitalization;
CheckToken(toSymbol);
DoNextToken;
{ Token is ( or ; or some directive }
if Token = toLeftParens then
SkipParamList;
{ Token = ; or some directive }
SkipDirectives(True);
StopCapitalization;
CheckToken(toSemiColon);
end;
function TDelphiParser.SkipProcedureType(const DoAdd: Boolean): TAbstractItem;
begin
{ Example:
TStrProc = procedure(const S: string);
TNotifyEvent = procedure(Sender: TObject) of object;
PRE : Token = 'procedure'
POST: Token = ; or =
}
if DoAdd then
begin
Result := TProcedureTypeItem.Create('');
FPasItems.Add(Result);
end
else
Result := nil;
DoNextToken;
{ Token is toLeftParens or toSemiColon or 'of object' or ?? }
if Token = toLeftParens then
SkipParamList;
SkipDirectives(True);
if not (Token in [toSemiColon, toEquals]) then
Error('; or = expected');
end;
procedure TDelphiParser.SkipPropertySpecifiers(const MaySkipSemiColon: Boolean);
begin
{
Pre : Token = ; or some specifier
Post : Token = ;
}
StopCapitalization;
if ((Token <> toSemiColon) or not MaySkipSemiColon) and
((Token <> toSymbol) or (TokenSymbolInC(CPropertySpecifiers) < 0)) then
Exit;
while True do
begin
if Token = toSemiColon then
begin
SaveRollBackPosition;
DoNextToken;
if (Token <> toSymbol) or (TokenSymbolInC(CPropertySpecifiers) < 0) then
begin
RollBackToSavedPosition;
Exit;
end;
ForgetRollBackPosition;
end;
while Token = toSymbol do
begin
if TokenSymbolInC(CPropertySpecifiers) < 0 then
Error('Specifier expected');
DoNextToken;
end;
CheckToken(toSemiColon);
end;
end;
function TDelphiParser.SkipRecord(const DoAdd: Boolean): TAbstractItem;
begin
{ Example:
R1 = record F1, F2: T1 end; <-- Let op ","
R1 = record F1: T1; F2: T2; end;
R1 = record case tag: ordinalType of
constantList1: (variant1);
...
constantListn: (variantn);
end;
variant1 = fieldList1: type1;
...
fieldListn: typen;
R1 = record
F1: T1; F2: T2;
F3: record case T3 of
constantList1: (F1': T1');
...
constantListn: (Fn': Tn');
end;
end;
PRE : Token is 'record'
POST: Token is token after 'end'
}
if DoAdd then
begin
Result := TRecordItem.Create('');
FPasItems.Add(Result);
end
else
Result := nil;
DoNextToken;
while True do
begin
case Token of
toSymbol:
if TokenSymbolIs('end') then
Break
else
if TokenSymbolIs('case') then
begin
SkipUntilSymbol('of');
DoNextToken;
SkipUntilToken(toLeftParens);
end
else
begin
{ Lees (identifier:type) paar in }
DoNextToken;
if Token <> toComma then
begin
CheckToken(toColon);
DoNextToken;
SkipType(False, True);
{ Note : Token = ; or end }
Continue;
end;
end;
toRightParens: { empty list or closing }
begin
DoNextToken;
while Token = toRightParens do
DoNextToken;
if Token = toSemiColon then
DoNextToken;
if TokenSymbolIs('end') then
Break
else
begin
SkipUntilToken(toColon);
DoNextToken;
CheckToken(toLeftParens);
end;
end;
toEof:
Exit;
end;
DoNextToken;
end;
CheckTokenSymbol('end');
DoNextToken;
end;
function TDelphiParser.SkipResourceString(const DoAdd: Boolean): TAbstractItem;
begin
{ RS1 = V1;
POST: Token = ;
}
if DoAdd then
begin
Result := TResourceStringItem.Create(TokenString);
FPasItems.Add(Result);
end
else
Result := nil;
DoNextToken;
CheckToken(toEquals);
SkipUntilToken(toSemiColon);
end;
function TDelphiParser.SkipSimpleType(const DoAdd: Boolean): TAbstractItem;
begin
{ Example:
T1 = array [..] of record F1: T1; F2: T2; end;
T1 = xx;
PRE: Token = xx/array
POST: Token = ;
}
if DoAdd then
begin
Result := TTypeItem.Create('');
FPasItems.Add(Result);
end
else
Result := nil;
if TokenSymbolIs('array') then
begin
SkipUntilSymbol('of');
DoNextToken;
SkipType(False, False);
end
else
if TokenSymbolIs('set') then
begin
{ same as array }
SkipUntilSymbol('of');
DoNextToken;
SkipType(False, False);
end
else
if Token = '^' then
begin
DoNextToken;
CheckToken(toSymbol);
DoNextToken;
end
else
if TokenSymbolIs('string') then
begin
DoNextToken;
if Token = toLeftBracket then
begin
SkipUntilTokenInHaak(toLeftBracket, toRightBracket);
CheckToken(toRightBracket);
DoNextToken;
end;
end
else
if TokenSymbolIs('file') then
begin
{ same as array }
DoNextToken;
if TokenSymbolIs('of') then
begin
DoNextToken;
SkipType(False, False);
end;
end
else
if TokenSymbolInC(CAllowableSymbolsInTypeDef) >= 0 then
SkipConstantExpression(True)
else
begin
{ We can't skip until ; }
if TokenSymbolIs('type') then
DoNextToken;
DoNextToken;
if Token = toDotDot then
begin
{ TSomeType = a..b; }
DoNextToken;
SkipConstantExpression(False);
end
else
if Token = '.' then
begin
DoNextToken;
CheckToken(toSymbol);
if TokenSymbolInC(CDirectives) > 0 then
Exit;
DoNextToken;
while Token = '.' do
begin
DoNextToken;
CheckToken(toSymbol);
if TokenSymbolIn(CDirectives) > 0 then
Exit;
DoNextToken;
end;
end
else
if not (Token in [toRightParens, toSemiColon, toEquals]) and not TokenSymbolIs('end') then
SkipConstantExpression(True);
end;
CheckNotToken(toEof);
end;
function TDelphiParser.SkipType(const DoAdd,
DoReadDirectives: Boolean): TAbstractItem;
begin
{
PRE:
POST: Type including directives read
}
if Token = toLeftParens then
Result := SkipEnumerator(DoAdd)
else
case TokenSymbolIn(['record', 'class', 'procedure', 'function', 'interface',
'dispinterface', 'packed']) of
0: { record }
Result := SkipRecord(DoAdd);
1: { class}
Result := SkipClass(DoAdd);
2: { procedure }
Result := SkipProcedureType(DoAdd);
3: { function }
Result := SkipFunctionType(DoAdd);
4: { interface }
Result := SkipInterfaceType(DoAdd);
5: { dispinterface }
Result := SkipDispInterface(DoAdd);
6: {packed }
begin
Result := nil; //Satisfy compiler
DoNextToken;
CheckToken(toSymbol);
case CheckTokenSymbolInC(['record', 'array']) of
0: Result := SkipRecord(DoAdd);
1: Result := SkipSimpleType(DoAdd);
end;
end
else
Result := SkipSimpleType(DoAdd);
end;
if DoReadDirectives then
SkipDirectives(False);
end;
function TDelphiParser.SkipTypeDef(const DoAdd: Boolean): TAbstractItem;
var
TypeName: string;
begin
{ Example:
T1 = record F1: T1; F2: T2; end;
T1 = class() [classdef] end;
T1 = sometype;
PRE : Token = identifier [T1]
POST: Token = ;
}
TypeName := TokenString;
DoNextToken;
CheckToken(toEquals);
DoNextToken;
Result := SkipType(DoAdd, False);
if Assigned(Result) then
Result.SimpleName := TypeName;
SkipDirectives(False); { 'deprecated', 'platform' }
CheckToken(toSemiColon);
end;
procedure TDelphiParser.SkipUntilSymbol(const Symbol: string);
begin
while (Token <> toEof) and not TokenSymbolIs(Symbol) do
DoNextToken;
end;
procedure TDelphiParser.SkipUntilToken(T: Char);
begin
{ PRE : -
POST: Token = T or Token = toEof
}
while not (Token in [T, toEof]) do
DoNextToken;
CheckToken(T);
end;
procedure TDelphiParser.SkipUntilTokenInHaak(OpenSymbol, CloseSymbol: Char;
const InitialOpenCount: Integer);
var
OpenCount: Integer;
begin
{ Post : Token on CloseHaak }
if OpenSymbol = CloseSymbol then
Error('Internal error: OpenHaak = CloseHaak');
OpenCount := InitialOpenCount;
while Token <> toEof do
begin
if Token = OpenSymbol then
Inc(OpenCount)
else
if Token = CloseSymbol then
begin
Dec(OpenCount);
if OpenCount = 0 then
Exit;
end;
DoNextToken;
end;
end;
procedure TDelphiParser.SkipUntilTokenInHaak(T: Char; const InitHaak: Integer);
var
Haakjes: Integer;
begin
{ PRE :
POST : Token = ;
}
Haakjes := InitHaak;
while True do
begin
case Token of
toLeftParens:
Inc(Haakjes);
toRightParens:
Dec(Haakjes);
toEof:
Exit;
end;
if Token = T then
if Haakjes <= 0 then
Exit;
DoNextToken;
end;
end;
procedure TDelphiParser.SkipUsesBlock;
begin
if Token in [toComment, toSameLineComment, toCompilerDirective] then
begin
SaveRollBackPosition;
DoNextToken;
if not TokenSymbolIsC('uses') then
begin
RollBackToSavedPosition;
Exit;
end;
ForgetRollBackPosition;
end;
if not TokenSymbolIsC('uses') then
Exit;
BeginBlock;
StartCapitalization;
SkipUntilToken(toSemiColon);
StopCapitalization;
EndBlock(True);
DoNextToken(False);
end;
function TDelphiParser.SkipVar(const DoAdd: Boolean): TAbstractItem;
begin
{ Example:
V1: T1;
IdSslCtxFree : procedure(arg0: PSSL_CTX) cdecl = nil;
QBDRed, QBDBlue, QBDGreen: byte;
PRE: Token = var. identifier (V1 in example)
POST: Token = ;
}
StartCapitalization;
if DoAdd then
begin
Result := TVarItem.Create(TokenString);
FPasItems.Add(Result);
end
else
Result := nil;
DoNextToken;
while Token = toComma do
begin
DoNextToken;
CheckToken(toSymbol);
if DoAdd then
FPasItems.Add(TVarItem.Create(TokenString));
DoNextToken;
end;
CheckToken(toColon);
DoNextToken;
{ Never add }
SkipType(False, True);
if Token = toEquals then
begin
DoNextToken;
SkipConstValue;
end;
CheckToken(toSemiColon);
StopCapitalization;
end;
procedure TDelphiParser.StartCapitalization;
begin
if not FHoldRecapitalize then
Exit;
FHoldRecapitalize := False;
RecapitalizeToken;
end;
procedure TDelphiParser.StopCapitalization;
begin
FHoldRecapitalize := True;
end;
procedure TDelphiParser.SwitchDefine;
var
Current: TDefineType;
begin
if FDEFList.Count = 0 then
Error('Unexpected {$ELSE}');
Current := TDefineType(FDEFList.Objects[FDEFList.Count - 1]);
if Current = dftIFDEF then
Current := dftIFNDEF
else
Current := dftIFDEF;
FDEFList.Objects[FDEFList.Count - 1] := TObject(Current);
end;
function TDelphiParser.TokenCompilerDirective: TCompilerDirective;
var
P: PChar;
S: string;
begin
CheckToken(toCompilerDirective);
P := FTokenPtr + 2;
while P^ in ['A'..'Z', 'a'..'z', '0'..'9'] do
Inc(P);
SetString(S, FTokenPtr + 2, P - FTokenPtr - 2);
Result := StrToCompilerDirective(S);
if (Length(S) = 1) and
(Result in [cdInputOutputChecking, cdLocalSymbolInformation, cdRTTI, cdRangeChecking]) and
not (FirstChar(TokenCompilerDirectiveArgument) in ['+', '-']) then
case Result of
cdInputOutputChecking: Result := cdIncludeFile;
cdLocalSymbolInformation: Result := cdLinkObjectFile;
cdRTTI: Result := cdMINSTACKSIZE;
cdRangeChecking: Result := cdResource;
end;
end;
function TDelphiParser.TokenCompilerDirectiveArgument: string;
var
P, Q: PChar;
begin
CheckToken(toCompilerDirective);
P := FTokenPtr + 2;
while P^ in ['A'..'Z', 'a'..'z', '0'..'9'] do
Inc(P);
while P^ = ' ' do
Inc(P);
Q := P;
while Q^ <> '}' do
Inc(Q);
Dec(Q);
while (Q > P) and (Q^ = ' ') do
Dec(Q);
Inc(Q);
SetString(Result, P, Q - P);
end;
function TDelphiParser.TokenIsConditionalCompilation: Boolean;
begin
Result := (Token = toCompilerDirective) and
(TokenCompilerDirective in [cdIFDEF, cdIFNDEF, cdELSE, cdENDIF]);
end;
function TDelphiParser.TokenSymbolInC(
const List: array of string): Integer;
begin
Result := TokenSymbolIn(List);
if (Result >= 0) and DoRecapitalize then
RecapitalizeTokenWith(List[Result]);
end;
function TDelphiParser.TokenSymbolIsC(const S: string): Boolean;
begin
Result := TokenSymbolIs(S);
if Result then
RecapitalizeTokenWith(S);
end;
//=== TDpkParser =============================================================
constructor TDpkParser.Create;
begin
inherited;
FList := TStringList.Create;
TStringList(FList).Sorted := True;
end;
destructor TDpkParser.Destroy;
begin
FList.Free;
inherited;
end;
procedure TDpkParser.Init;
begin
inherited Init;
FList.Clear;
end;
function TDpkParser.Parse: Boolean;
begin
ReadUntilContainsBlock;
while ReadFileReference do
;
{while ReadUntilFunction do
ReadFunction;}
Result := True;
end;
function TDpkParser.ReadFileReference: Boolean;
begin
DoNextToken;
Result := (Token = toSymbol) and not TokenSymbolIs('end');
if not Result then
Exit;
List.Add(TokenString);
ReadNextToken;
while not (Token in [toComma, toSemiColon, toEof]) do
ReadNextToken;
end;
procedure TDpkParser.ReadUntilContainsBlock;
begin
SkipUntilSymbol('contains');
end;
//=== TDtxBaseItem ===========================================================
procedure TDtxBaseItem.SetData(const Value: string);
begin
FData := RemoveSepLines(Value);
EnsureEndingCRLF(FData);
end;
//=== TDtxCompareParser ======================================================
constructor TDtxCompareParser.Create;
begin
inherited;
FList := TDtxItems.Create;
FTags := TStringList.Create;
FOptions := [dpoParameters, dpoDefaultText];
end;
destructor TDtxCompareParser.Destroy;
begin
FList.Free;
FTags.Free;
inherited;
end;
function TDtxCompareParser.Execute(const AFileName: string): Boolean;
begin
FErrors := [];
FDefaultTexts := [];
FTags.Clear;
Result := FileExists(AFileName);
if not Result then
Exit;
FPasFileNameWithoutPath := ChangeFileExt(ExtractFileName(AFileName), '.pas');
FStream := TFileStream.Create(AFileName, fmOpenRead, fmShareDenyWrite);
try
FList.Clear;
Init;
Result := Parse;
finally
FreeAndNil(FStream);
end;
end;
function TDtxCompareParser.GetDtxCompareTokenType: TDtxCompareTokenType;
var
S: string;
begin
S := TokenString;
if Length(S) > 2 then
begin
if (S[1] = '@') and (S[2] = '@') then
Result := ctHelpTag
else
if (S[1] = '#') and (S[2] = '#') then
Result := ctParseTag
else
if (S[1] = '-') and (S[2] = '-') then
Result := ctSeperator
else
Result := ctText;
end
else
Result := ctText;
end;
function TDtxCompareParser.GetPackage: string;
var
I: Integer;
begin
for I := 0 to FList.Count - 1 do
if (FList[I] is TDtxStartItem) and (TDtxStartItem(FList[I]).Symbol = dssPackage) then
begin
Result := RemoveStartEndCRLF(TDtxStartItem(FList[I]).Data);
Exit;
end;
Result := '';
end;
function TDtxCompareParser.Parse: Boolean;
begin
FErrors := [defNoPackageTag, defNoStatusTag, defNoAuthor];
FLastWasNewLine := True; { BOF }
ReadStartBlock;
ReadRest;
FList.ConstructSkipList;
Result := True;
end;
procedure TDtxCompareParser.ReadAuthor;
begin
LowNextToken;
if CompareTokenType = ctText then
Exclude(FErrors, defNoAuthor);
end;
procedure TDtxCompareParser.ReadFileInfo;
begin
{
PRE : Token = first token after @@Somepasfilename.pas
POST : Token = toEof or Token = @@SomeHelpTag }
{ We only determine whether an author is specified }
while (Token <> toEof) and (CompareTokenType <> ctHelpTag) do
if FLastWasNewLine and TokenSymbolIs('author') then
ReadAuthor
else
LowNextToken;
end;
procedure TDtxCompareParser.ReadHasTocEntry(Item: TDtxHelpItem);
var
S: string;
begin
if Item = nil then
ErrorStr('ReadCombineWith, Item = nil');
LowNextToken;
if CompareTokenType = ctText then
begin
S := TokenString;
{ Expect 'ON>' or 'OFF>' }
if (S > '') and (S[Length(S)] = '>') then
Delete(S, Length(S), 1);
if SameText(S, 'on') then
Item.HasTocEntry := True
else
if SameText(S, 'off') then
Item.HasTocEntry := False
else
Include(FErrors, defHasTocEntryError);
LowNextToken;
end;
end;
procedure TDtxCompareParser.ReadHelpTopic(Item: TDtxHelpItem);
procedure CheckDefaultText(var ACheck: string);
var
DefaultText: TDefaultText;
begin
for DefaultText := Low(TDefaultText) to High(TDefaultText) do
case CheckText(ACheck, CDefaultText[DefaultText], DefaultText = dtDescriptionFor) of
ctPrefix:
Exit;
ctEqual:
begin
ACheck := '';
Include(FDefaultTexts, DefaultText);
Exit;
end;
end;
ACheck := '';
end;
var
Check: string;
LTokenString: string;
LastWasSee, CurrentIsSee: Boolean;
Link: string;
begin
{ PRE : Token = first token after @@SomeHelpTag
POST : Token = toEof or Token = @@SomeHelpTag
}
Check := '';
CurrentIsSee := False;
while (Token <> toEof) and (CompareTokenType <> ctHelpTag) do
begin
LastWasSee := CurrentIsSee;
CurrentIsSee := FLastWasNewLine and (CompareTokenType = ctText) and TokenSymbolIsExact('See');
{ We use continue, otherwise the code becomes unreadable }
if CompareTokenType <> ctText then
begin
{ Token is not a text token, thus ------etc or ##something }
Check := '';
LowNextToken;
Continue;
end;
LTokenString := TokenString;
if dpoDefaultText in Options then
begin
{ check defaults }
if Check = '' then
Check := LTokenString
else
Check := Check + ' ' + LTokenString;
CheckDefaultText(Check);
if Check = '' then
Check := LTokenString;
end;
if LastWasSee and (CompareStr(LTokenString, 'Also') = 0) then
begin
ReadSeeAlso(Item);
Continue;
end;
if not FLastWasNewLine or (LTokenString = '') then
begin
{ Some text in the middle of a line }
LowNextToken;
Continue;
end;
{ Token is a text token that start on a new line }
if LTokenString[1] = '<' then
begin
{ Special tokens that start with a '<' }
if SameText(LTokenString, '<LINK') or SameText(LTokenString, '<ALIAS') then
begin
LowNextToken;
if dpoLinks in Options then
begin
if ReadLink(Link) then
Item.AddLink(Link);
LowNextToken;
end;
end
else
if SameText(LTokenString, '<COMBINE') then
begin
LowNextToken;
if ReadLink(Link) then
Item.Combine := Link;
LowNextToken;
end
else
if SameText(LTokenString, '<COMBINEWith') then
begin
LowNextToken;
if ReadLink(Link) then
Item.CombineWith := Link;
LowNextToken;
end
else
if SameText(LTokenString, '<HASTOCENTRY') then
ReadHasTocEntry(Item)
else
if SameText(LTokenString, '<TITLEIMG') then
ReadTitleImg(Item)
else
{ Token starts with < but not a known token }
LowNextToken;
end
else
begin
if CompareStr(LTokenString, 'Parameters') = 0 then
ReadParameters(Item)
else
if SameText(LTokenString, 'JVCLInfo') then
ReadJVCLINFO(Item)
else
{ Token start on new line but not a known token }
LowNextToken;
end;
end;
end;
procedure TDtxCompareParser.ReadItem(Item: TDtxHelpItem);
begin
end;
procedure TDtxCompareParser.ReadJVCLINFO(Item: TDtxHelpItem);
var
IsFlag, IsGroup: Boolean;
FlagFound, GroupFound: Boolean;
begin
LowNextToken;
Item.HasJVCLInfo := True;
FlagFound := False;
GroupFound := False;
while (Token <> toEof) and (Pos(toEquals, TokenString) > 0) do
begin
IsFlag := StrLComp(PChar(TokenString), 'FLAG=', 5) = 0;
IsGroup := not IsFlag and (StrLComp(PChar(TokenString), 'GROUP=', 6) = 0);
if (IsFlag and FlagFound) or (IsGroup and GroupFound) then
Include(Item.FJVCLInfoErrors, jieDoubles);
FlagFound := FlagFound or IsFlag;
GroupFound := GroupFound or IsGroup;
if Pos('?', TokenString) > 0 then
begin
if IsFlag then
Include(Item.FJVCLInfoErrors, jieFlagNotFilled)
else
if IsGroup then
Include(Item.FJVCLInfoErrors, jieGroupNotFilled)
else
Include(Item.FJVCLInfoErrors, jieOtherNotFilled)
end
else
if IsFlag then
Item.IsRegisteredComponent :=
SameText('component', Trim(Copy(TokenString, 6, MaxInt)));
{ Skip until new line }
repeat
LowNextToken
until (Token = toEof) or FLastWasNewLine;
end;
if not GroupFound then
Include(Item.FJVCLInfoErrors, jieNoGroup);
end;
function TDtxCompareParser.ReadLink(out Link: string): Boolean;
var
NewPart: string;
P: Integer;
begin
Link := '';
{ identifier can have spaces, such as
DSAMessageDlgEx@integer@string@string@TGraphic@array of string@array of integer@longint@TDlgCenterKind@integer@integer@integer@integer@TJvDynControlEngine
we just look if we have a '>' at the end, if not keep reading }
while CompareTokenType = ctText do
begin
{ 'SomeLink>,' is possible }
NewPart := TokenString;
P := Pos('>', NewPart);
if P > 0 then
begin
Link := Link + Copy(NewPart, 1, P - 1);
Result := True;
Exit;
end;
Link := Link + NewPart + ' ';
LowNextToken;
end;
Result := False;
end;
function TDtxCompareParser.ReadNextToken: Char;
var
P: PChar;
procedure NextChar;
begin
Inc(P);
if P^ = #10 then
Inc(FSourceLine);
end;
begin
SkipBlanks;
P := FSourcePtr;
FTokenPtr := P;
case P^ of
'@':
begin
Result := toSymbol;
NextChar;
if P^ = '@' then
begin
// read till eol
NextChar;
while P^ in [#32..#255] do
NextChar;
end
else
begin
// Same as #32..#255
NextChar;
while P^ in [#33..#255] do
NextChar;
end;
end;
{ TODO : Ugly }
#32..'?', 'A'..#255:
begin
NextChar;
while P^ in [#33..#255] do
NextChar;
Result := toSymbol;
end;
else
Result := P^;
if Result <> toEof then
NextChar;
end;
FSourcePtr := P;
FToken := Result;
end;
procedure TDtxCompareParser.ReadOther;
begin
Include(FErrors, defUnknownTag);
FTags.Add(TokenString);
LowNextToken;
end;
procedure TDtxCompareParser.ReadPackage;
var
DtxItem: TDtxStartItem;
begin
Exclude(FErrors, defNoPackageTag);
LowNextToken;
if CollectData then
BeginLowRecording;
while (Token <> toEof) and (CompareTokenType = ctText) do
begin
if Pos('?', TokenString) > 0 then
Include(FErrors, defPackageTagNotFilled);
LowNextToken;
end;
if CollectData then
begin
EndLowRecordingWithoutCurrent;
DtxItem := TDtxStartItem.Create;
FList.Add(DtxItem);
DtxItem.Symbol := dssPackage;
DtxItem.Data := LowRecordingStr;
end;
end;
procedure TDtxCompareParser.ReadParameters(Item: TDtxHelpItem);
var
Check: string;
procedure CheckDefaultText;
begin
if dtDescriptionForThisParameter in FDefaultTexts then
Exit;
if Check = '' then
Check := TokenString
else
Check := Check + ' ' + TokenString;
case CheckText(Check, CDefaultText[dtDescriptionForThisParameter], False) of
ctPrefix:
Exit;
ctEqual:
begin
Check := '';
Include(FDefaultTexts, dtDescriptionForThisParameter);
Exit;
end;
end;
Check := '';
end;
var
S: string;
begin
Check := '';
LowNextToken;
while True do
begin
while not FLastWasNewLine and (Token <> toEof) do
begin
if dpoDefaultText in Options then
CheckDefaultText;
LowNextToken;
end;
if Token = toEof then
Exit;
if CompareTokenType <> ctText then
Break;
S := TokenString;
LowNextToken;
if CompareTokenType <> ctText then
Break;
if SameText(S, 'See') and SameText(TokenString, 'Also') then
begin
ReadSeeAlso(Item);
Break;
end;
if (Token <> toSymbol) or (TokenSymbolIn(['-', toColon]) < 0) then
Continue;
if dpoParameters in Options then
Item.AddParam(S);
end;
end;
procedure TDtxCompareParser.ReadRest;
var
HelpToken: string;
DtxItem: TDtxHelpItem;
begin
while (Token <> toEof) and (CompareTokenType = ctHelpTag) do
begin
HelpToken := TokenString;
DtxItem := TDtxHelpItem.Create(HelpToken);
FList.Add(DtxItem);
LowNextToken;
if CollectData then
BeginLowRecording;
DtxItem.IsFileInfo := (Length(HelpToken) > 2) and
SameText(Copy(HelpToken, 3, MaxInt), FPasFileNameWithoutPath);
if DtxItem.IsFileInfo then
ReadFileInfo
else
ReadHelpTopic(DtxItem);
if CollectData then
begin
EndLowRecordingWithoutCurrent;
DtxItem.Data := LowRecordingStr;
end;
end;
end;
procedure TDtxCompareParser.ReadSeeAlso(Item: TDtxHelpItem);
const
CCheckWordCount = 3;
CCheckWords: array[0..CCheckWordCount - 1] of string = ('list', 'here', 'other');
var
Link: string;
State: Integer;
{ 0 = first
1 = first = 'List'
2 = second = 'here'
-1 = other
}
begin
LowNextToken;
if CompareTokenType <> ctText then
begin
Include(FErrors, defEmptySeeAlso);
Exit;
end;
if not (dpoLinks in Options) then
begin
{ skip }
while (Token <> toEof) and (CompareTokenType = ctText) do
LowNextToken;
end
else
begin
State := 0;
while (Token <> toEof) and (CompareTokenType = ctText) do
begin
if (State >= 0) and (State < CCheckWordCount) then
begin
if TokenSymbolIs(CCheckWords[State]) then
Inc(State)
else
State := -1;
if State = CCheckWordCount then
begin
Item.ClearLinks;
if dpoDefaultText in Options then
Include(FDefaultTexts, dtRemoveSeeAlso);
{ skip rest }
while (Token <> toEof) and (CompareTokenType = ctText) do
LowNextToken;
Exit;
end;
end;
if TokenSymbolIn(['<ALIAS', '<LINK']) >= 0 then
begin
State := -1;
LowNextToken;
if not ReadLink(Link) then
Exit;
Item.AddLink(Link);
end
else
Item.AddLink(TokenString);
LowNextToken;
end;
end;
end;
procedure TDtxCompareParser.ReadSkip;
var
DtxItem: TDtxStartItem;
begin
LowNextToken;
if CollectData then
BeginLowRecording;
if CompareTokenType = ctText then
begin
if Assigned(FSkipList) then
FSkipList.Add(TokenString);
LowNextToken;
end;
while (Token <> toEof) and (CompareTokenType = ctText) do
begin
if Pos('?', TokenString) > 0 then
Include(FErrors, defPackageTagNotFilled);
LowNextToken;
end;
if CollectData then
begin
EndLowRecordingWithoutCurrent;
DtxItem := TDtxStartItem.Create;
FList.Add(DtxItem);
DtxItem.Symbol := dssSkip;
DtxItem.Data := LowRecordingStr;
end;
end;
procedure TDtxCompareParser.ReadStartBlock;
begin
{ POST : Token = toEof or CompareTokenString = ctHelpTag }
while (Token <> toEof) and (CompareTokenType <> ctHelpTag) do
begin
if FLastWasNewLine and (CompareTokenType = ctParseTag) then
begin
if TokenSymbolIs('##package:') then
ReadPackage
else
if TokenSymbolIs('##status:') then
ReadStatus
else
if TokenSymbolIs('##skip:') then
ReadSkip
else
ReadOther;
end
else
LowNextToken;
end;
end;
procedure TDtxCompareParser.ReadStatus;
var
DtxItem: TDtxStartItem;
begin
Exclude(FErrors, defNoStatusTag);
LowNextToken;
if CollectData then
BeginLowRecording;
while (Token <> toEof) and (CompareTokenType = ctText) do
LowNextToken;
if CollectData then
begin
EndLowRecordingWithoutCurrent;
DtxItem := TDtxStartItem.Create;
FList.Add(DtxItem);
DtxItem.Symbol := dssStatus;
DtxItem.Data := LowRecordingStr;
end;
end;
procedure TDtxCompareParser.ReadTitleImg(Item: TDtxHelpItem);
var
S: string;
begin
if Item = nil then
ErrorStr('ReadCombineWith, Item = nil');
LowNextToken;
if CompareTokenType = ctText then
begin
S := TokenString;
if (S > '') and (S[Length(S)] = '>') then
Delete(S, Length(S), 1);
Item.TitleImg := S;
LowNextToken;
end;
end;
//=== TDtxHelpItem ===========================================================
procedure TDtxHelpItem.AddLink(const ALink: string);
var
P: Integer;
begin
if not Assigned(FLinks) then
FLinks := TStringList.Create;
P := Pos(',', ALink);
if P <= 0 then
P := Pos('>', ALink);
if P > 0 then
FLinks.Add(Copy(ALink, 1, P - 1))
else
FLinks.Add(ALink);
end;
procedure TDtxHelpItem.AddParam(const AParam: string);
begin
if not Assigned(FParameters) then
FParameters := TStringList.Create;
FParameters.Add(AParam);
end;
procedure TDtxHelpItem.ClearLinks;
begin
if Assigned(FLinks) then
FLinks.Clear;
end;
function TDtxHelpItem.CompareWith(AItem: TDtxBaseItem): Integer;
const
CBoolInt: array[Boolean] of Integer = (0, -1);
var
OtherItem: TDtxHelpItem;
begin
if AItem is TDtxHelpItem then
begin
OtherItem := TDtxHelpItem(AItem);
Result := CBoolInt[FIsFileInfo] - CBoolInt[OtherItem.FIsFileInfo];
if (Result = 0) and not FIsFileInfo then
Result := CompareText(FTag, OtherItem.FTag);
end
else
Result := 1;
end;
constructor TDtxHelpItem.Create(const ATag: string);
begin
FParameters := TStringList.Create;
FLinks := TStringList.Create;
FTag := ATag;
FHasTocEntry := True;
end;
destructor TDtxHelpItem.Destroy;
begin
FParameters.Free;
FLinks.Free;
inherited;
end;
procedure TDtxHelpItem.WriteToStream(AStream: TStream);
var
S: string;
begin
S := Tag + #13#10 + FData;
AStream.Write(PChar(S)^, Length(S));
end;
//=== TDtxItems ==============================================================
procedure TDtxItems.CombineWithPasList(APasItems: TPasItems);
var
I: Integer;
HelpItem: TDtxHelpItem;
Index: Integer;
begin
for I := 0 to Count - 1 do
if Items[I] is TDtxHelpItem then
begin
HelpItem := TDtxHelpItem(Items[I]);
Index := APasItems.IndexOfReferenceName(HelpItem.Tag);
if Index >= 0 then
HelpItem.PasObj := APasItems[Index];
end;
end;
procedure TDtxItems.ConstructSkipList;
var
I: Integer;
begin
FSkipList.Clear;
for I := 0 to Count - 1 do
if (Items[I] is TDtxStartItem) and (TDtxStartItem(Items[I]).Symbol = dssSkip) then
FSkipList.Add(
AddLeading(RemoveStartEndCRLF(TDtxStartItem(Items[I]).Data)));
end;
constructor TDtxItems.Create;
begin
inherited Create;
FSkipList := TStringList.Create;
with TStringList(FSkipList) do
begin
CaseSensitive := True;
Sorted := True;
Duplicates := dupIgnore;
end;
end;
destructor TDtxItems.Destroy;
begin
FSkipList.Free;
inherited Destroy;
end;
procedure TDtxItems.DtxSort;
begin
Sort(DtxSortCompare);
end;
procedure TDtxItems.FillWithDtxHeaders(Dest: TStrings);
var
I: Integer;
begin
for I := 0 to Count - 1 do
if Items[I] is TDtxHelpItem then
with TDtxHelpItem(Items[I]) do
if HasTocEntry then
Dest.Add(Tag);
end;
function TDtxItems.IndexOfReferenceName(ReferenceName: string): Integer;
begin
ReferenceName := AddLeading(ReferenceName);
Result := 0;
while (Result < Count) and
(not (Items[Result] is TDtxHelpItem) or
not SameText((Items[Result] as TDtxHelpItem).Tag, ReferenceName)) do
Inc(Result);
if Result >= Count then
Result := -1;
end;
procedure TDtxItems.WriteToFile(const AFileName: string);
const
cSepLength = 100;
var
Stream: TFileStream;
I: Integer;
Sep: string;
begin
SetLength(Sep, cSepLength + 2);
FillChar(PChar(Sep)^, cSepLength, '-');
Sep[cSepLength + 1] := #13;
Sep[cSepLength + 2] := #10;
Stream := TFileStream.Create(AFileName, fmCreate);
try
for I := 0 to Count - 1 do
begin
if Items[I] is TDtxHelpItem then
Stream.Write(PChar(Sep)^, cSepLength + 2);
(Items[I] as TDtxBaseItem).WriteToStream(Stream);
end;
finally
Stream.Free;
end;
end;
//=== TDtxStartItem ==========================================================
function TDtxStartItem.CompareWith(AItem: TDtxBaseItem): Integer;
begin
if AItem is TDtxStartItem then
begin
Result := Ord(FSymbol) - Ord(TDtxStartItem(AItem).FSymbol);
if (Result = 0) and (FSymbol in [dssOther, dssSkip]) then
Result := CompareText(FData, TDtxStartItem(AItem).FData);
end
else
Result := -1;
end;
procedure TDtxStartItem.SetSymbol(const Value: TDtxStartSymbol);
begin
FSymbol := Value;
case FSymbol of
dssPackage: FSymbolStr := '##Package:';
dssStatus: FSymbolStr := '##Status:';
dssSkip: FSymbolStr := '##Skip:';
end;
end;
procedure TDtxStartItem.SetSymbolStr(const Value: string);
begin
FSymbolStr := Value;
if SameText(FSymbolStr, '##package:') then
FSymbol := dssPackage
else
if SameText(FSymbolStr, '##status:') then
FSymbol := dssStatus
else
if SameText(FSymbolStr, '##skip:') then
FSymbol := dssSkip
else
FSymbol := dssOther;
end;
procedure TDtxStartItem.WriteToStream(AStream: TStream);
var
S: string;
begin
S := SymbolStr + ' ' + Data;
AStream.Write(PChar(S)^, Length(S));
end;
//=== TFunctionParser ========================================================
constructor TFunctionParser.Create;
begin
inherited;
FFunctions := TStringList.Create;
FSkipped := TStringList.Create;
end;
destructor TFunctionParser.Destroy;
begin
FFunctions.Free;
FSkipped.Free;
inherited;
end;
function TFunctionParser.ExecuteFile(const AFileName: string): Boolean;
begin
FFileName := ExtractFileName(AFileName);
Result := inherited ExecuteFile(AFileName);
end;
procedure TFunctionParser.Init;
begin
inherited Init;
FFunctions.Clear;
FSkipped.Clear;
end;
function TFunctionParser.Parse: Boolean;
begin
ReadUntilImplementationBlock;
while ReadUntilFunction do
ReadFunction;
Result := True;
end;
procedure TFunctionParser.ReadFunction;
function CheckAllChars(const S: string): Boolean;
var
I: Integer;
begin
Result := True;
I := 0;
while Result and (I < Length(S)) do
begin
Result := S[I + 1] in ['a'..'z', 'A'..'Z', '0'..'9', '_'];
Inc(I);
end;
end;
var
S: string;
begin
DoNextToken;
S := TokenString;
if not CheckAllChars(S) then
begin
FSkipped.Add(S);
Exit;
end;
DoNextToken;
if TokenString <> '.' then
begin
FFunctions.Add(Format('%s (%s)', [S, FFileName]));
end;
end;
function TFunctionParser.ReadUntilFunction: Boolean;
begin
while (Token <> toEof) and not TokenSymbolIs('function')
and not TokenSymbolIs('procedure') do
if TokenSymbolIs('class') then
SkipClass(False)
else
DoNextToken;
Result := Token <> toEof;
end;
procedure TFunctionParser.ReadUntilImplementationBlock;
begin
SkipUntilSymbol('implementation');
end;
//=== TImplementationParser ==================================================
function TImplementationParser.Parse: Boolean;
var
LModuleType: TModuleType;
GlobalProcedureNames: TStringList;
I: Integer;
begin
if Assigned(FOutputStream) then
BeginOutputTo(FOutputStream);
InterpretCompilerDirectives := False;
while Token <> toSymbol do
DoNextToken;
ReadUnitBlock(LModuleType);
if LModuleType = mtLibrary then
begin
Result := True;
Exit;
end;
ReadInterfaceStatement;
SkipUsesBlock;
SkipInterfaceBlock;
{ collect names of global procedures }
GlobalProcedureNames := TStringList.Create;
try
GlobalProcedureNames.Sorted := True;
GlobalProcedureNames.Duplicates := dupIgnore;
for I := 0 to FPasItems.Count - 1 do
if FPasItems[I].DelphiType in [dtFunction, dtProcedure] then
GlobalProcedureNames.Add(FPasItems[I].SimpleName);
FPasItems.Clear;
CheckTokenSymbolC('implementation');
if Assigned(FOutputStream) then
EndOutputTo;
DoNextToken(False);
ReadImplementationBlock;
for I := 0 to FPasItems.Count - 1 do
if FPasItems[I] is TBaseFuncItem then
with TBaseFuncItem(FPasItems[I]) do
IsLocal := GlobalProcedureNames.IndexOf(SimpleName) < 0;
if SortImplementation then
TypeList.SortImplementation
else
TypeList.OnlyCapitalization;
if Assigned(FOutputStream) then
TypeList.WriteImplementationToStream(FOutputStream);
Result := True;
finally
GlobalProcedureNames.Free;
end;
end;
//=== TPasCasingParser =======================================================
constructor TPasCasingParser.Create;
begin
inherited Create;
FList := TStringList.Create;
with FList as TStringList do
begin
Duplicates := dupIgnore;
CaseSensitive := True;
Sorted := True;
end;
end;
destructor TPasCasingParser.Destroy;
begin
FList.Free;
inherited Destroy;
end;
function TPasCasingParser.Parse: Boolean;
var
I: Integer;
Item: TAbstractItem;
Index: Integer;
begin
if AllSymbols then
begin
while Token <> toEof do
begin
if Token = toSymbol then
begin
if DoCount then
begin
Index := FList.Add(TokenString);
FList.Objects[Index] := TObject(Integer(FList.Objects[Index]) + 1);
end
else
FList.AddObject(TokenString, TObject(ID));
end;
DoNextToken;
end;
Result := True;
end
else
begin
Result := inherited Parse;
if not Result then
Exit;
for I := 0 to FPasItems.Count - 1 do
begin
Item := TAbstractItem(FPasItems[I]);
if DoCount then
begin
Index := FList.Add(Item.SimpleName);
FList.Objects[Index] := TObject(Integer(FList.Objects[Index]) + 1);
end
else
FList.AddObject(Item.SimpleName, TObject(ID));
if Item is TClassPropertyItem then
begin
if DoCount then
begin
Index := FList.Add(TClassPropertyItem(Item).TypeStr);
FList.Objects[Index] := TObject(Integer(FList.Objects[Index]) + 1);
end
else
FList.AddObject(TClassPropertyItem(Item).TypeStr, TObject(ID));
end;
end;
end;
end;
//=== TPasCheckParser ========================================================
function TPasCheckParser.ExecuteFile(const AFileName: string): Boolean;
var
FindData: TWin32FindData;
Handle: THandle;
begin
{ TODO : Naar init }
FErrors := [pefNoLicense];
Result := FileExists(AFileName);
if not Result then
Exit;
Handle := FindFirstFile(PChar(AFileName), FindData);
Result := Handle <> INVALID_HANDLE_VALUE;
if not Result then
Exit;
Windows.FindClose(Handle);
FFileName := ChangeFileExt(FindData.cFileName, '');
Result := inherited ExecuteFile(AFileName);
end;
function TPasCheckParser.Parse: Boolean;
begin
ReadCommentBlock;
ReadUnitName;
Result := True;
end;
procedure TPasCheckParser.ReadCommentBlock;
const
CLicenseText = 'The contents of this file are subject to the';
var
LicenseFound: Boolean;
begin
LicenseFound := False;
while Token = toComment do
begin
LicenseFound := LicenseFound or
(Pos(CLicenseText, TokenString) > 0);
DoNextToken(False);
end;
if LicenseFound then
Exclude(FErrors, pefNoLicense);
end;
procedure TPasCheckParser.ReadUnitName;
begin
while (Token <> toEof) and not TokenSymbolIs('unit') do
DoNextToken;
DoNextToken;
CheckToken(toSymbol);
FUnitName := TokenString;
if CompareStr(FUnitName, FFileName) <> 0 then
Include(FErrors, pefUnitCase);
end;
//=== TRecapitalizeParser ====================================================
function TRecapitalizeParser.Parse: Boolean;
var
Ch: Char;
begin
Result := Assigned(FOutputStream) and Assigned(FCapitalization);
if not Result then
Exit;
BeginOutputTo(FOutputStream);
while Token <> toEof do
DoNextToken;
EndOutputTo;
Ch := '.';
FOutputStream.WriteBuffer(Ch, 1);
end;
//=== TRegisteredClassesParser ===============================================
constructor TRegisteredClassesParser.Create;
begin
inherited Create;
FList := TStringList.Create;
TStringList(FList).Sorted := True;
WantCompilerDirectives := False;
InterpretCompilerDirectives := False;
end;
destructor TRegisteredClassesParser.Destroy;
begin
FList.Free;
inherited;
end;
procedure TRegisteredClassesParser.Init;
begin
inherited Init;
FList.Clear;
end;
function TRegisteredClassesParser.Parse: Boolean;
begin
if not ReadUntilRegisterBlock then
begin
Result := True;
Exit;
end;
while ReadUntilRegisterComponentsBlock and ReadRegisterComponentsBlock do
;
Result := True;
end;
function TRegisteredClassesParser.ReadRegisterComponentsBlock: Boolean;
begin
{ PRE : Token = 'RegisterComponents'
POST: Token = token after ; or )
Example:
RegisterComponents(x, [C1]);
RegisterComponents(x, [C1, C2, C3]);
}
DoNextToken;
CheckToken(toLeftParens);
SkipUntilToken(toComma);
DoNextToken;
CheckToken(toLeftBracket);
DoNextToken;
CheckToken(toSymbol);
List.Add(TokenString);
DoNextToken;
while Token = toComma do
begin
DoNextToken;
CheckToken(toSymbol);
List.Add(TokenString);
DoNextToken;
end;
CheckToken(toRightBracket);
DoNextToken;
CheckToken(toRightParens);
DoNextToken;
if Token = toSemiColon then
DoNextToken;
Result := Token <> toEof;
end;
function TRegisteredClassesParser.ReadUntilRegisterBlock: Boolean;
begin
while (Token <> toEof) and not TokenSymbolIsExact('Register') and not TokenSymbolIs('implementation') do
DoNextToken;
Result := TokenSymbolIsExact('Register');
end;
function TRegisteredClassesParser.ReadUntilRegisterComponentsBlock: Boolean;
begin
SkipUntilSymbol('RegisterComponents');
Result := TokenSymbolIs('RegisterComponents');
end;
end.
| 23.150955 | 158 | 0.645315 |
47362554d810338ae895d0e421b0d07390d693e3 | 272 | pas | Pascal | hardware/electronics/altium/20.2.6/scripts/UL_Form.pas | Semi-ATE/MCD | e5454235546a5033a8ae5bd6d49bd86e4faa54ca | [
"MIT"
]
| null | null | null | hardware/electronics/altium/20.2.6/scripts/UL_Form.pas | Semi-ATE/MCD | e5454235546a5033a8ae5bd6d49bd86e4faa54ca | [
"MIT"
]
| null | null | null | hardware/electronics/altium/20.2.6/scripts/UL_Form.pas | Semi-ATE/MCD | e5454235546a5033a8ae5bd6d49bd86e4faa54ca | [
"MIT"
]
| null | null | null |
procedure TUL_Form.BtnFileClick(Sender: TObject);
begin
If OpenDlg.Execute Then Begin
TxtFile.Text := OpenDlg.FileName;
End;
end;
procedure TUL_Form.BtnImportClick(Sender: TObject);
begin
ImportAscIIData(TxtFile.Text);
Close;
end;
| 18.133333 | 52 | 0.6875 |
f1aaa70a59023a9d4d904e0590f83a734306e275 | 387 | dpr | Pascal | HolaMundo.dpr | LeonardoRCruzL/UniGui_HolaMundo | cb20f4c975485c1cffeb4679b67b91f6aab21142 | [
"Apache-2.0"
]
| null | null | null | HolaMundo.dpr | LeonardoRCruzL/UniGui_HolaMundo | cb20f4c975485c1cffeb4679b67b91f6aab21142 | [
"Apache-2.0"
]
| null | null | null | HolaMundo.dpr | LeonardoRCruzL/UniGui_HolaMundo | cb20f4c975485c1cffeb4679b67b91f6aab21142 | [
"Apache-2.0"
]
| null | null | null | program HolaMundo;
uses
Forms,
ServerModule in 'ServerModule.pas' {UniServerModule: TUniGUIServerModule},
MainModule in 'MainModule.pas' {UniMainModule: TUniGUIMainModule},
Main in 'Main.pas' {MainForm: TUniForm};
{$R *.res}
begin
ReportMemoryLeaksOnShutdown := True;
Application.Initialize;
TUniServerModule.Create(Application);
Application.Run;
end.
| 22.764706 | 77 | 0.731266 |
479166423eb95e672341637a03b6855915741111 | 22,991 | dfm | Pascal | Libraries/SynEdit/Demos/SearchReplaceDemo/frmMain.dfm | jomael/Concepts | 82d18029e41d55e897d007f826c021cdf63e53f8 | [
"Apache-2.0"
]
| 62 | 2016-01-20T16:26:25.000Z | 2022-02-28T14:25:52.000Z | Libraries/SynEdit/Demos/SearchReplaceDemo/frmMain.dfm | jomael/Concepts | 82d18029e41d55e897d007f826c021cdf63e53f8 | [
"Apache-2.0"
]
| 16 | 2019-02-02T19:54:54.000Z | 2019-02-28T05:22:36.000Z | Libraries/SynEdit/Demos/SearchReplaceDemo/frmMain.dfm | jomael/Concepts | 82d18029e41d55e897d007f826c021cdf63e53f8 | [
"Apache-2.0"
]
| 20 | 2016-09-08T00:15:22.000Z | 2022-01-26T13:13:08.000Z | object SearchReplaceDemoForm: TSearchReplaceDemoForm
Left = 100
Top = 122
Caption = 'Search and replace demo'
ClientHeight = 345
ClientWidth = 554
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
OldCreateOrder = False
OnCreate = FormCreate
PixelsPerInch = 96
TextHeight = 13
object SynEditor: TSynEdit
Left = 0
Top = 26
Width = 554
Height = 300
Align = alClient
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -13
Font.Name = 'Courier New'
Font.Style = []
TabOrder = 0
Gutter.Font.Charset = DEFAULT_CHARSET
Gutter.Font.Color = clWindowText
Gutter.Font.Height = -11
Gutter.Font.Name = 'Terminal'
Gutter.Font.Style = []
OnReplaceText = SynEditorReplaceText
FontSmoothing = fsmNone
RemovedKeystrokes = <
item
Command = ecDeleteLastChar
ShortCut = 8200
end
item
Command = ecLineBreak
ShortCut = 8205
end
item
Command = ecContextHelp
ShortCut = 112
end>
AddedKeystrokes = <>
end
object ToolBarMain: TToolBar
Left = 0
Top = 0
Width = 554
Height = 26
AutoSize = True
BorderWidth = 1
Caption = 'Standard'
Images = ImageListMain
TabOrder = 1
object ToolButtonFileOpen: TToolButton
Left = 0
Top = 0
Action = ActionFileOpen
end
object ToolButtonSeparator1: TToolButton
Left = 23
Top = 0
Width = 8
ImageIndex = 1
Style = tbsSeparator
end
object ToolButtonSearch: TToolButton
Left = 31
Top = 0
Action = ActionSearch
end
object ToolButtonSearchNext: TToolButton
Left = 54
Top = 0
Action = ActionSearchNext
end
object ToolButtonSearchPrev: TToolButton
Left = 77
Top = 0
Action = ActionSearchPrev
end
object ToolButtonSeparator2: TToolButton
Left = 100
Top = 0
Width = 8
Caption = 'ToolButtonSeparator2'
ImageIndex = 4
Style = tbsSeparator
end
object ToolButtonSearchReplace: TToolButton
Left = 108
Top = 0
Action = ActionSearchReplace
end
end
object Statusbar: TStatusBar
Left = 0
Top = 326
Width = 554
Height = 19
Panels = <>
SimplePanel = True
end
object ImageListMain: TImageList
Left = 404
Top = 56
Bitmap = {
494C010105000900040010001000FFFFFFFFFF10FFFFFFFFFFFFFFFF424D3600
0000000000003600000028000000400000002000000001002000000000000020
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000848484008484840084848400000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000848484000000000000000000848484000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000848484000000000000000000848484000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000848484008484840084848400000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000848484000000000000000000848484000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000848484000000000000000000848484000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000848484008484840084848400000000000000000000000000000000000000
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
0000000000000000000000000000000000008484840000000000000000000000
0000848484000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000084848400000000008484
8400000000000000000000000000000000000000000000000000000000000000
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
000000000000000000000000000000000000000000000000000000000000FFFF
FF00000000000000000000000000000000000000000000000000FFFFFF000000
0000000000000000000000000000000000000000000000000000000000000000
0000FFFFFF00000000000000000000000000000000000000000000000000FFFF
FF00000000000000000000000000000000000000000000000000008484000084
8400008484000084840000848400008484000084840000848400008484000000
00000000000000000000000000000000000000000000FFFFFF00000000000000
000000000000000000000000000000000000000000000000000000000000FFFF
FF0000000000000000000000000000000000000000000000000000000000FFFF
FF00000000000000000000000000000000000000000000000000FFFFFF000000
0000000000000000000000000000000000000000000000000000000000000000
0000FFFFFF00000000000000000000000000000000000000000000000000FFFF
FF00000000000000000000000000000000000000000000FFFF00000000000084
8400008484000084840000848400008484000084840000848400008484000084
84000000000000000000000000000000000000000000FFFFFF00000000000000
000000000000000000000000000000000000000000000000000000000000FFFF
FF00000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000FFFFFF0000FFFF000000
0000008484000084840000848400008484000084840000848400008484000084
8400008484000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000FFFF
FF000000000000000000000000008484840000000000FFFFFF00000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000FFFFFF000000000000000000000000008484840000000000FFFFFF000000
0000000000000000000000000000000000000000000000FFFF00FFFFFF0000FF
FF00000000000084840000848400008484000084840000848400008484000084
8400008484000084840000000000000000000000000000000000FFFFFF000000
00000000000000000000000000000000000000000000FFFFFF00000000000000
000000000000000000000000000000000000000000000000000000000000FFFF
FF000000000000000000000000000000000000000000FFFFFF00000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000FFFFFF000000000000000000000000000000000000000000FFFFFF000000
00000000000000000000000000000000000000000000FFFFFF0000FFFF00FFFF
FF0000FFFF000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000FFFFFF000000
00000000000000000000C6C6C6000000000000000000FFFFFF00000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000084848400000000008484840000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000848484000000000084848400000000000000
0000000000000000000000000000000000000000000000FFFF00FFFFFF0000FF
FF00FFFFFF0000FFFF00FFFFFF0000FFFF00FFFFFF0000FFFF00000000000000
0000000000000000000000000000000000000000000000000000FFFFFF000000
00000000000000000000C6C6C6000000000000000000FFFFFF00000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000FFFFFF0000FFFF00FFFF
FF0000FFFF00FFFFFF0000FFFF00FFFFFF0000FFFF00FFFFFF00000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000FFFF00FFFFFF0000FF
FF00000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000FFFF
FF000000000000000000000000000000000000000000FFFFFF00000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000084848400840000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000008400000084848400000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000008484840084000000000000000000000000000000000000008400
0000840000008400000084000000000000000000000084000000840000008400
0000840000000000000000000000000000000000000084000000848484000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000008400000000000000000000000000000000000000000000000000
0000840000008400000084000000000000000000000084000000840000008400
0000000000000000000000000000000000000000000000000000840000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000FFFFFF000000000000000000000000000000000000000000FFFFFF000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000008400000000000000000000000000000000000000000000000000
0000840000008400000084000000000000000000000084000000840000008400
0000000000000000000000000000000000000000000000000000840000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000008484840084000000000000000000000000000000848484008400
0000000000000000000084000000000000000000000084000000000000000000
0000840000008484840000000000000000000000000084000000848484000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000084848400840000008400000084000000840000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000008400000084000000840000008400000084848400000000000000
000000000000000000000000000000000000424D3E000000000000003E000000
2800000040000000200000000100010000000000000100000000000000000000
000000000000000000000000FFFFFF00FFFF000000000000FF71000000000000
FF36000000000000F516000000000000DF31000000000000FF76000000000000
BFF6000000000000FFD1000000000000DFFF000000000000FFBF000000000000
77FF00000000000077BF00000000000007FF000000000000AFD7000000000000
8FE7000000000000DFC7000000000000FFFFFFFFFFFFFFFFFFFFFFFFC387E1C3
001F07C1C387E1C3000F07C1C387E1C3000707C1C007E00300030101C007E003
00010001C007E00300000001E10FF087001F0001F39FF9CF001F8003F39FF9CF
001FC107FCFFFF3F8FF1C107F9E1879FFFF9E38FFBF18FDFFF75E38FFBF18FDF
FF8FE38FF9CDB39FFFFFFFFFFC1FF83F00000000000000000000000000000000
000000000000}
end
object OpenDialogFile: TOpenDialog
Options = [ofPathMustExist, ofFileMustExist, ofEnableSizing]
Left = 460
Top = 56
end
object ActionListMain: TActionList
Images = ImageListMain
Left = 344
Top = 56
object ActionFileOpen: TAction
Caption = '&Open...'
ImageIndex = 0
ShortCut = 16463
OnExecute = ActionFileOpenExecute
end
object ActionSearch: TAction
Caption = '&Find...'
ImageIndex = 1
ShortCut = 16454
OnExecute = ActionSearchExecute
end
object ActionSearchNext: TAction
Caption = 'Find &next'
Enabled = False
ImageIndex = 2
ShortCut = 114
OnExecute = ActionSearchNextExecute
OnUpdate = actSearchUpdate
end
object ActionSearchPrev: TAction
Caption = 'Find &previous'
Enabled = False
ImageIndex = 3
ShortCut = 8306
OnExecute = ActionSearchPrevExecute
OnUpdate = actSearchUpdate
end
object ActionSearchReplace: TAction
Caption = '&Replace...'
Enabled = False
ImageIndex = 4
ShortCut = 16456
OnExecute = ActionSearchReplaceExecute
OnUpdate = ActionSearchReplaceUpdate
end
end
object SynEditSearch: TSynEditSearch
Left = 188
Top = 112
end
object SynEditRegexSearch: TSynEditRegexSearch
Left = 188
Top = 160
end
end
| 52.252273 | 70 | 0.855683 |
47c145e5cf2244d8e0a45dfd9f1be2b35872ac05 | 227,214 | pas | Pascal | library/wp/FHIR.WP.Control.pas | atkins126/fhirserver | b6c2527f449ba76ce7c06d6b1c03be86cf4235aa | [
"BSD-3-Clause"
]
| null | null | null | library/wp/FHIR.WP.Control.pas | atkins126/fhirserver | b6c2527f449ba76ce7c06d6b1c03be86cf4235aa | [
"BSD-3-Clause"
]
| null | null | null | library/wp/FHIR.WP.Control.pas | atkins126/fhirserver | b6c2527f449ba76ce7c06d6b1c03be86cf4235aa | [
"BSD-3-Clause"
]
| null | null | null | Unit FHIR.WP.Control;
{
Copyright (c) 2001+, Kestral Computing Pty Ltd (http://www.kestral.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.
}
Interface
uses
Windows, SysUtils, Classes, Controls, ExtCtrls, Forms, Graphics, Messages, Math, Contnrs, Vcl.Touch.GestureMgr,
DropBMPTarget, DropSource, DropTarget,
fsl_base, fsl_utilities, fsl_collections, fsl_stream, fsl_shell,
fsl_mapi,
fUi_vclx_Base, fUi_vclx_controls,
wp_graphics, wp_printing_win,
wp_types, wp_document, wp_format, wp_working, FHIR.WP.Settings,
FHIR.WP.Unicode,
FHIR.WP.Printing, FHIR.WP.Engine, wp_definers, FHIR.WP.Handler, wp_native,
FHIR.WP.Renderer, FHIR.WP.Menus, FHIR.WP.Spelling, FHIR.WP.Icons, FHIR.WP.Builder,
FHIR.WP.Dragon;
Type
TWPCapability = FHIR.WP.Engine.TWPCapability;
TWPCapabilities = FHIR.WP.Engine.TWPCapabilities;
Const
canInsert = FHIR.WP.Engine.canInsert;
canWrite = FHIR.WP.Engine.canWrite;
canDelete = FHIR.WP.Engine.canDelete;
canCut = FHIR.WP.Engine.canCut;
canUndo = FHIR.WP.Engine.canUndo;
canRedo = FHIR.WP.Engine.canRedo;
canInsertImage = FHIR.WP.Engine.canInsertImage;
canImageProps = FHIR.WP.Engine.canImageProps;
canLineProps = FHIR.WP.Engine.canLineProps;
canInsertField = FHIR.WP.Engine.canInsertField;
canFieldProps = FHIR.WP.Engine.canFieldProps;
canRemoveField = FHIR.WP.Engine.canRemoveField;
canSpliceField = FHIR.WP.Engine.canSpliceField;
canGotoField = FHIR.WP.Engine.canGotoField;
canFormat = FHIR.WP.Engine.canFormat;
canInsertTable = FHIR.WP.Engine.canInsertTable;
canConvertToTable = FHIR.WP.Engine.canConvertToTable;
canSelectTable = FHIR.WP.Engine.canSelectTable;
canTableProps = FHIR.WP.Engine.canTableProps;
canRemoveTable = FHIR.WP.Engine.canRemoveTable;
canInsertRowAbove = FHIR.WP.Engine.canInsertRowAbove;
canInsertRowBelow = FHIR.WP.Engine.canInsertRowBelow;
canSelectRow = FHIR.WP.Engine.canSelectRow;
canRowProps = FHIR.WP.Engine.canRowProps;
canRemoveRow = FHIR.WP.Engine.canRemoveRow;
canInsertColumn = FHIR.WP.Engine.canInsertColumn;
canRemoveColumn = FHIR.WP.Engine.canRemoveColumn;
canInsertLine = FHIR.WP.Engine.canInsertLine;
canInsertPageBreak = FHIR.WP.Engine.canInsertPageBreak;
SCROLLBAR_WIDTH = 16;
UM_CLOSE_TOUCH = WM_USER + 26;
Type
TWordProcessor = Class;
TWPHotspotInformation = Class (TFslObject)
Private
FBox : TRect;
FHotspot : TWPHotspot;
FMouseButton: TMouseButton;
FHandled: Boolean;
Procedure SetHotspot(Const Value: TWPHotspot);
Public
destructor Destroy; Override;
// the screen co-ordinates for the hotspot
Property Box : TRect Read FBox Write FBox;
// the hotspot itself
Property Hotspot : TWPHotspot Read FHotspot Write SetHotspot;
// the mousebutton
Property MouseButton : TMouseButton Read FMouseButton Write FMouseButton;
// whether the WP should act is if it's been handled
// (usually for right mouse button: should WP bring up it's normal popup?)
// default true
Property Handled : Boolean Read FHandled Write FHandled;
End;
TFieldUpdateStatus = (fusDeliberate, fusChange, fusLoading);
TWPInspector = Class (TUixPanel)
Protected
FHeader : TUixPanel;
FFooter : TUixPanel;
FFooterCaption : TUixLabel;
Function DesiredWidth : Integer; Virtual;
Function InspectorCaption : String; Virtual;
Procedure WantClose(oSender : TObject); Virtual;
Procedure Initialise; Override;
End;
TWPInspectorList = Class(TUixPanelList)
Private
Function GetPanelByIndex(Const iIndex : Integer) : TWPInspector;
Protected
Function ItemClass : TComponentClass; Overload; Override;
Public
Property InspectorByIndex[Const iIndex : Integer] : TWPInspector Read GetPanelByIndex; Default;
End;
// get's called constantly while user moves mouse over a hotspot, and then
// once with active = false when user leaves
TWPHotSpotHoverEvent = Procedure (oSender : TWordProcessor; bActive : Boolean; oInfo : TWPHotspotInformation) Of Object;
TWPHotSpotEvent = Procedure (oSender : TWordProcessor; oInfo : TWPHotspotInformation) Of Object;
TWPCodeCompletionEvent = Function (oSender : TObject; Const sText : String; oItems : TWPCompletionItems) : Boolean Of Object;
TWPTemplateEvent = Function (oSender : TObject) : TFslBuffer Of Object; // must return a native format buffer if any content is to be inserted
TWPNamedTemplateEvent = Function (oSender : TObject; Const iId : Integer; Const sName : String; Var aFormat : TWPFormat) : TFslBuffer Of Object; // must return a native format buffer if any content is to be inserted
TWPFieldUpdateEvent = Procedure (oSender : TObject; aState : TFieldUpdateStatus; oDefinitionProvider : TWPFieldDefinitionProvider; oField : TWPDocumentField; sContent : String; bValid : boolean) of Object;
TWordProcessCursorDetailsMode = (cdBlink, cdSelect, cdDrag);
TWordProcessorSelectionHot = (shNeither, shStart, shEnd);
TWordProcessCursorDetails = Class (TFslObject)
Private
FMode : TWordProcessCursorDetailsMode;
FShowing: Boolean;
FLeft: Integer;
FHeight: Integer;
FTop: Integer;
FColour: TColour;
FDragMarkTop : Integer;
FDragMarkLeft : Integer;
FDragMarkHeight : Integer;
FDragMarkColour: TColour;
FSelStartTop : Integer;
FSelStartLeft : Integer;
FSelStartHeight : Integer;
FSelStartColour: TColour;
FSelEndTop : Integer;
FSelEndLeft : Integer;
FSelEndHeight : Integer;
FSelEndColour: TColour;
FSelHot : TWordProcessorSelectionHot;
Procedure Clear;
Public
Property Showing : Boolean Read FShowing Write FShowing;
Property Left : Integer Read FLeft Write FLeft;
Property Top : Integer Read FTop Write FTop;
Property Height : Integer Read FHeight Write FHeight;
Property Colour : TColour Read FColour Write FColour;
End;
TWordProcessorDocumentHandler = Class (TWPDocumentHandler)
Private
FOwner : TWordProcessor;
Protected
Function GetHost : TObject; Override;
Function GetHostConfiguredStyles : TWPStyles; Override;
Function GetHostWorkingStyles : TWPStyles; Override;
Function GetHostDocument : TWPWorkingDocument; Override;
Procedure SetHostDocument(Const oDocument : TWPWorkingDocument; oStyles : TWPStyles); Override;
Public
constructor Create(oOwner : TWordProcessor); Overload; Virtual;
End;
TWordProcessorCheckor = Class (TFslObject)
Public
Function Invariants(Const sLocation : String; oObject : TFslObject; aClass : TClass; Const sObject : String) : Boolean; Overload;
End;
TWPMouseActor = Class (TFslObject)
Private
FWordProcessor : TWordProcessor;
Protected
FLastTop : Integer;
FLastBottom : Integer;
FLastLeft : Integer;
FLastRight : Integer;
FOffsetSquareforScroll : Boolean;
Procedure Square(iLeft, iTop, iRight, iBottom : Integer);
Public
constructor Create(oWordProcessor : TWordProcessor); Overload; Virtual;
destructor Destroy; Override;
Function Link : TWPMouseActor; Overload;
Procedure Disconnect; Overload; Virtual;
Function RequiresDown : Boolean; Overload; Virtual;
Function Cursor(oInfo : TWPMouseInfo; bDoing : Boolean) : TCursor; Overload; Virtual;
Procedure Down(aShift: TShiftState; iX, iY: Integer; oInfo : TWPMouseInfo; bDouble : Boolean); Overload; Virtual;
Procedure Move(iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo); Overload; Virtual;
Procedure Up(aShift: TShiftState; iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo); Overload; Virtual;
Procedure Close(oNewActor : TWPMouseActor); Overload; Virtual;
End;
TWPTouchManager = class (TFslObject)
private
FOwner : TWordProcessor;
FLoaded : boolean;
FGestures : TGestureManager;
FZoomStart : Integer;
FZoomBase : real;
FPanStart : Integer;
FPanBase : Integer;
procedure DoGesture(sender :TObject; const EventInfo: TGestureEventInfo; var Handled :boolean);
Function Zoom(EventInfo : TGestureEventInfo) : boolean;
Function Pan(EventInfo : TGestureEventInfo) : boolean;
Function TwoFingers(EventInfo : TGestureEventInfo) : boolean;
public
constructor Create(owner : TWordProcessor);
destructor Destroy; override;
procedure Load;
Procedure Unload;
end;
TWordProcessor = Class (TUixControl)
Private
FDefaultFieldDefinition: TWPFieldDefinitionProvider;
FInspectors: TWPInspectorList;
FSettings : TWPSettings;
FCheckor : TWordProcessorCheckor;
FDocument: TWPWorkingDocument;
FConfiguredStyles: TWPStyles;
FWorkingStyles: TWPStyles;
FOperator: TWPOperator;
FRangeManager : TWPRangeManager;
FPrimaryRange: TWPVisualRange;
FRenderer : TWPScreenRenderer;
FTimer : TUixTimer;
FCursorDetails : TWordProcessCursorDetails;
FMouseActor : TWPMouseActor;
FJustDoubleClicked : Boolean;
FOnContentChanged: TNotifyEvent;
FOnSelectionChanged: TNotifyEvent;
FPopup : TWPPopupMenu;
FObservers : TWPObservers;
FFontsAllowed: TFslStringList;
FOnCodeCompletion : TWPCodeCompletionEvent;
FSpeller: TWPSpeller;
FDocumentHandler : TWPDocumentHandler;
FVoiceActive : Boolean;
FExistingSearch : TWPSearchDetails;
FExistingReplace : TWPReplaceDetails;
FNextControl : TWinControl;
FPreviousControl : TWinControl;
FDropBMP : TDropBMPTarget;
FAltNum : String;
FWorkingWidthLimit : Integer;
FOnHotSpot : TWPHotSpotEvent;
FOnHotSpotHover : TWPHotSpotHoverEvent;
FResetMouseCursor : Boolean;
FTranslator : TWPDocumentTranslator;
FScrollPoint : TPoint; // Current scroll position.
FPropertyServer : TWPPropertyServer;
FPlaybackManager : TDragonPlaybackManager;
FCursorPersist : Boolean;
FCursorOutside : Boolean;
FModified : Boolean;
FLastSnapshot : Integer;
FScrollBarShowing : Boolean;
FNonVisibleMode : Boolean; // support for non-visual unit tests
FCodeCompletionListBox : TWPCodeCompletionListBox;
FTouchMenu : TUixPanel;
FSymbolFilter : String;
FSymbolBlock : TUnicodeBlock;
FTouch : TWPTouchManager;
// pagination support. These fields are only used to support page estimations.
// printers must be supplied to the print dialog etc for actual printing.
FPrinter : TFslPrinter;
FPageLayoutController : TWPPageLayoutController;
FPaginator : TWPPaginator;
FOnTemplate: TWPTemplateEvent;
FOnNamedTemplate: TWPNamedTemplateEvent;
FOnPageDesign : TNotifyEvent;
FOnPrint : TNotifyEvent;
FOnExport : TNotifyEvent;
FOnImport : TNotifyEvent;
FOnSave : TNotifyEvent;
FOnSaveAs : TNotifyEvent;
FOnOpen : TNotifyEvent;
FOnNew : TNotifyEvent;
FOnUpdateField : TWPFieldUpdateEvent;
// macros
FMacro : TWPMacro;
FOnSettingsChanged: TNotifyEvent;
FOnDocumentLoaded: TNotifyEvent;
Procedure SetDefaultFieldDefinition(Const Value: TWPFieldDefinitionProvider);
Procedure VoiceSelect(iTextStart, iTextLength : Integer; bDraw : Boolean);
Procedure DragDropFiles(Var VMsg: TMessage); Message wm_DropFiles;
Procedure SetFocusedControl(oControl : TWinControl);
Function GetDocumentHandler : TWPDocumentHandler;
Function GetOperator : TWPOperator;
Function GetSpeller : TWPSpeller;
Procedure SetSpeller(Const Value: TWPSpeller);
Function GetDocument : TWPWorkingDocument;
Function GetRenderer : TWPScreenRenderer;
Function GetSelection : TWPSelection;
Function GetConfiguredStyles : TWPStyles;
Procedure SetConfiguredStyles(Const Value: TWPStyles);
Function GetWorkingStyles : TWPStyles;
Procedure SetWorkingStyles(Const Value: TWPStyles);
Procedure SetWorkingWidthLimit(Const Value: Integer);
Function GetPageLayoutController : TWPPageLayoutController;
Procedure SetPageLayoutController(Const Value : TWPPageLayoutController);
Function GetPrinter : TFslPrinter;
Procedure SetPrinter(Const Value : TFslPrinter);
Function GetSettings : TWPSettings;
Procedure SetSettings(Const Value : TWPSettings);
Procedure SettingsChange(Const aProperties : TWPSettingsProperties);
Function GetNextControl : TWinControl;
Function GetPreviousControl : TWinControl;
Procedure Timer(oSender : TObject);
Procedure ToggleCursor;
Procedure DrawCursor(bShow : Boolean);
Procedure ActorContentChange(oSender : TObject);
Procedure ActorSelectionChange(oSender : TObject);
Procedure ActorInsertContent(oSender : TObject; iPoint : Integer; oPieces : TWPWorkingDocumentPieces);
Procedure ActorDeleteContent(oSender : TObject; iPoint : Integer; oPieces : TWPWorkingDocumentPieces);
Procedure LayoutDocumentHeightChange(oSender : TObject);
Function GetFontsAllowed : TFslStringList;
Procedure SetFontsAllowed(Const Value: TFslStringList);
Procedure InsertCompletionItem(oItem : TWPCompletionItem);
Function GetCursorEndPos : TPoint;
Function ActualWidth : Integer;
Procedure DragMarkCleared;
Procedure ClearDragMark;
Procedure DrawDragMark(iOffset : Integer);
Procedure InvokePopop;
Procedure WMEraseBkgnd(Var Message: TWmEraseBkgnd); Message WM_ERASEBKGND;
Procedure WMContextMenu(Var aMessage : TWMContextMenu); Message WM_CONTEXTMENU;
Function GetExistingSearch : TWPSearchDetails;
Procedure SetExistingSearch(Const Value : TWPSearchDetails);
Function GetExistingReplace : TWPReplaceDetails;
Procedure SetExistingReplace(Const Value : TWPReplaceDetails);
Procedure CheckDocument(oDocument : TWPWorkingDocument);
function BindToFields(oDocument : TWPWorkingDocument) : boolean;
Procedure CheckField(oErrors : TFslStringList; oPiece : TWPWorkingDocumentFieldStartPiece);
Function GetSelectionSummary : String; Overload; Virtual;
Function GetSelectionEnd: Integer;
Function GetSelectionStart: Integer;
Procedure CommitField;
Procedure ShowError(Const sTitle, sMessage : String; iDuration : Integer);
Procedure HandleError(Const sContext, sMessage : String);
Function IsAnnotationKey(iKey: Word; Const aShift: TWPShiftStates) : Boolean;
Function ProcessKey(iKey: Word; Const aShift: TWPShiftStates) : Boolean;
Procedure LoadNewDocument(Const oDocument : TWPWorkingDocument; oStyles : TWPStyles);
Function GetReadOnly : Boolean;
Procedure SetReadOnly(Const Value : Boolean);
Function GetPlaybackManager : TDragonPlaybackManager;
Procedure SetPlaybackManager(Const Value : TDragonPlaybackManager);
Function CheckForHotspot(ch : Char) : Boolean;
Procedure UpdateScrollBar;
Procedure ScrollbarPositionChanged;
Procedure Paginate;
Procedure FinishPagination;
Function MakeMouseActor(aAction : TWPMouseAction; iOffset : Integer) : TWPMouseActor;
Procedure CheckLostHotspot;
Function MouseIsOver : Boolean;
Function GetTopLine : Integer;
Procedure SetTopLine(Const iValue : Integer);
Function GetThumb : Integer;
Procedure SetThumb(iValue : Integer);
Procedure GetSelectedTableAsTextArray(Var aRows: Array Of TStringList);
Procedure SetOnTemplate(Const Value: TWPTemplateEvent);
Procedure ProduceSnapShot(Const sFilename, sCause: String);
Function FetchTemplateContent(Const iId : Integer; Const sCode : String; var aFormat : TWPFormat) : TFslStream;
Procedure ToggleMacro;
Procedure ExecuteMacro;
Procedure CheckForAllowedWord(Sender:TObject; Const Word:String; Var CheckType:TWordCheckType; Var Replacement:String);
Procedure AddAllowedWord(Sender:TObject; Const Word:String);
Function GetImageTool: TImageTool;
Procedure SetImageTool(Const Value: TImageTool);
Function WantDragSelection(x, y : integer; var oActor : TWPMouseActor) : Boolean;
Function DoNew : Boolean;
Function DoOpen : Boolean;
Function DoSave : Boolean;
// Function DoSaveAs : Boolean;
Function DoPrint : Boolean;
Protected
Procedure ApplyCursorState(Const aCursor : TCursor; bPersist : Boolean);
Procedure CloseTouchMenu(Var Message: TMessage); Message UM_CLOSE_TOUCH;
Procedure DoExit; Override;
Procedure WMVScroll(Var Message: TWMVScroll); Message WM_VSCROLL;
Procedure WMGetDlgCode(Var Msg: TWMGetDlgCode); Message WM_GETDLGCODE;
Procedure CreateWnd; Override;
Procedure Paint; Override;
Procedure Resize; Override;
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 DblClick; Override;
Procedure KeyDown(Var Key: Word; Shift: TShiftState); Override;
Procedure KeyUp(Var Key: Word; Shift: TShiftState); Override;
Procedure ShowPopup(iX, iY : Integer; oInfo : TWPMouseInfo);
Function DoMouseWheel(aShift: TShiftState; iWheelDelta: Integer; aMousePos: Windows.TPoint): Boolean; Override;
Procedure ScrollToTop;
Procedure DragOver(Source: TObject; X, Y: Integer; State: TDragState; Var Accept: Boolean); Override;
Procedure BMPDrop(oSender: TObject; aShiftState: TShiftState; aPoint: Windows.TPoint; Var iEffect: LongInt);
Procedure DoHotspotHover(bActive : Boolean; aBox : TRect; oHotspot : TWPHotspot);
Function DoHotspot(aBox : TRect; oHotspot : TWPHotspot; Const aMouseButton: TMouseButton) : Boolean;
Procedure DoButton(aBox : TRect; oButton : TFslObject; iOffset : Integer);
Procedure DoAnnotationClick(oAnnotation : TWPWorkingAnnotation);
Function NoUserResponse : Boolean; Virtual;
Function ShowCursorAlways : Boolean; Virtual;
Procedure NotifyObservers; Virtual;
Procedure NotifyObserversInsert(iPoint : Integer; oPieces : TWPWorkingDocumentPieces); Virtual;
Procedure NotifyObserversDelete(iPoint : Integer; oPieces : TWPWorkingDocumentPieces); Virtual;
Property CursorEndPos : TPoint Read GetCursorEndPos;
Procedure CMMouseLeave(Var Message: TMessage); Message CM_MOUSELEAVE;
Procedure CMMouseEnter(Var Message: TMessage); Message CM_MOUSEENTER;
Property TopLine : Integer Read GetTopLine Write SetTopLine;
Property Thumb : Integer Read GetThumb Write SetThumb;
Function GetPrimaryRange : TWPVisualRange;
Property Popup : TWPPopupMenu Read FPopup;
Procedure DoPaint; Virtual;
Procedure DoSnapshot(oWriter : TWPSnapshotWriter); Overload; Virtual;
Procedure ConfigureRange(oRange : TWPRange); Overload; Virtual;
Procedure CheckNotInMacro;
Procedure Ring(aColour : TColour);
Public
constructor Create(oOwner : TComponent); Override;
destructor Destroy; Override;
Procedure Clear; Overload; Virtual;
Function ClearFormatting : Boolean; Overload; Virtual; // will fail for tables, fields, images
Function Empty : Boolean; Overload; Virtual;
Function SelectedText : String; Overload; Virtual;
Function TextForLine(iLine : Integer) : String; Overload; Virtual;
Function HasDocument : Boolean; Overload; Virtual;
Function HasPlaybackManager : Boolean; Overload; Virtual;
Function InSpeechMode : Boolean; Virtual;
procedure CheckOkForSpeech; Virtual;
Procedure RegisterObserver(oObject : TObject; aEvent : TNotifyEvent); Overload; Virtual;
Procedure UnregisterObserver(oObject : TObject); Overload; Virtual;
Procedure DefineFieldProvider(oDefinition : TWPFieldDefinitionProvider; bDefault : Boolean);
Procedure DefineAnnotationProvider(oDefinition : TWPAnnotationDefinitionProvider);
Procedure RegisterInspector(oInspector : TWPInspector);
Procedure RemoveInspector(oInspector : TWPInspector);
Procedure FontDialog; Overload; Virtual;
Procedure ParaDialog; Overload; Virtual;
Procedure StyleDialog; Overload; Virtual;
Procedure ChangeCaseDialog; Overload; Virtual;
Procedure PasteSpecialDialog; Overload; Virtual;
Procedure InsertImageDialog; Overload; Virtual;
Procedure InsertPDFDialog; Overload; Virtual;
Procedure ImagePropertiesDialog; Overload; Virtual;
Procedure ImageMapsDialog; Overload; Virtual;
Procedure InsertSymbol; Overload; Virtual;
Procedure EditAnnotation; Overload; Virtual;
Procedure DeleteAnnotation; Overload; Virtual;
Procedure AddAnnotation(iStart, iEnd : Integer; Const sNamespace, sContent : String); Overload; Virtual;
Procedure InsertTemplate; Overload; Virtual;
Procedure InsertTableDialog; Overload; Virtual;
Procedure SortTableDialog; Overload; Virtual;
Procedure TablePropertiesDialog; Overload; Virtual;
Procedure LinePropertiesDialog; Overload; Virtual;
Procedure SearchDialog; Overload; Virtual;
Procedure ReplaceDialog; Overload; Virtual;
Function CheckFields(oErrors : TFslStringList): Boolean; Overload; Virtual;
Procedure CheckSpelling; Overload; Virtual;
Procedure CodeCompletePrompt; Overload; Virtual;
Procedure CodeCompletePromptList(oList : TWPCompletionItems); Overload; Virtual;
Procedure CompletionBoxKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
Procedure ReviewWordDialog; Overload; Virtual;
Procedure InsertField(oDefn : TWPFieldDefinitionProvider); Overload; Virtual;
Procedure FieldPropertiesDialog; Overload; Virtual;
Procedure FieldSectionPropertiesDialog; Overload; Virtual;
Procedure InsertAnnotation(oDefn : TWPAnnotationDefinitionProvider); Overload; Virtual;
Function AllFieldsValid(var sError : String) : boolean; Overload; Virtual;
function ListAllFields(Namespace : String) : TWPDocumentFields;
Function HasFields : Boolean;
function GetContentForField(oField : TWPDocumentField) : String;
Procedure ShowFieldError(Const sNamespace, sName, sTitle, sMessage : String; iDuration : Integer = 3000); Overload; Virtual;
Procedure ShowSectionError(Const sNamespace, sName, sTitle, sMessage : String; iDuration : Integer = 3000); Overload; Virtual;
function GetSourceLocation(var line, col : integer) : boolean;
Procedure VoiceSaveSession(Const sFilename : String); Overload; Virtual;
Procedure VoiceLoadSession(Const sFilename : String); Overload; Virtual;
Procedure VoiceActivate; Overload; Virtual;
Procedure VoiceDeactivate; Overload; Virtual;
Procedure VoicePlayback; Overload; Virtual;
Procedure VoiceAccelerate; Overload; Virtual;
Procedure VoiceDecelerate; Overload; Virtual;
Procedure VoiceStop; Overload; Virtual;
Procedure VoiceGetTextChanges(Var iTextStart, iTextLength : Integer; Var sText : String; Var iVisibleStart, iVisibleLength : Integer); Overload; Virtual;
Procedure VoiceMakeTextChanges(iTextStart, iTextLength : Integer; sText : String); Overload; Virtual;
Procedure VoiceGetSelectionRange(Var iSelectionStart, iSelectionLength : Integer); Overload; Virtual;
Procedure VoiceSetSelectionRange(iSelectionStart, iSelectionLength : Integer); Overload; Virtual;
// support tools
Procedure SaveImage(Const sFilename : String); Overload; Virtual;
Procedure SnapShot(Const sCause : String; Const DoMail : Boolean); Overload; Virtual;
Function DocumentHeight : Integer; Overload; Virtual;
Function MinimumRecommendedHeight : Integer;
Function MinimumRecommendedWidth : Integer;
Function HasNextControl : Boolean; Overload; Virtual;
Function HasPreviousControl : Boolean; Overload; Virtual;
Function HasSpeller : Boolean; Overload; Virtual;
Function HasWorkingStyles : Boolean; Overload; Virtual;
Function InTouchMode : boolean;
Function HasVoicePlayback : Boolean; Overload; Virtual;
Function CheckOffsetVisible(iIndex : Integer) : Boolean; Overload; Virtual;
Function HasImageArea(Const sURL: String; Out oImage: TWPWorkingDocumentImagePiece; Out oArea: TWPImageMapArea): Boolean; Overload; Virtual;
Procedure SelectImageArea(oImage: TWPWorkingDocumentImagePiece; oArea: TWPImageMapArea); Overload; Virtual;
Procedure Yield; Overload; Virtual;// call this when WP is no longer visible
Function ListAllFonts : TStringList;
Function ListSpecialFonts : TStringList;
Function GoToFieldByName(Const sNamespace, sName : String) : Boolean;
Function CheckOkForConsoleMode(Var sMessage : String) : Boolean;
Function CheckOkForNoParagraphs : Boolean;
// external redirectors
Function Capabilities : TWPCapabilities; Overload; Virtual;
Procedure Undo; Overload; Virtual;
Procedure Redo; Overload; Virtual;
Procedure Cut; Overload; Virtual;
Procedure Copy; Overload; Virtual;
Procedure CopyAllToClipboard; Overload; Virtual;
Function Paste(Var sError : String) : Boolean; Overload; Virtual;
Procedure ApplyStyle(Const sName : String); Overload; Virtual;
Procedure ApplyStyleToLine(Const sName : String); Overload; Virtual;
Procedure Insert(Const sText : String);
// not for public use
Function ProduceRange : TWPVisualRange;
Procedure ConsumeRange(oRange : TWPRange);
Procedure UpdateTextMetrics; Overload; Virtual;
Procedure DeactivateBMPDrop;
Procedure ShowPopupMenu;
Procedure ScrollTo(y : Integer);
// you can change the styles in this list, but it is only consulted when the document is cleared or changed
Property ConfiguredStyles : TWPStyles Read GetConfiguredStyles Write SetConfiguredStyles;
Property DocumentHandler : TWPDocumentHandler Read GetDocumentHandler;
Property Actor : TWPOperator Read GetOperator;
Property Speller : TWPSpeller Read GetSpeller Write SetSpeller;
Property SelectionSummary: String Read GetSelectionSummary;
Property SelectionStart: Integer Read GetSelectionStart;
Property SelectionEnd: Integer Read GetSelectionEnd;
Property PlaybackManager : TDragonPlaybackManager Read GetPlaybackManager Write SetPlaybackManager;
// published solely for internal use. DO NOT USE OUTSIDE WORD PROCESSOR
Procedure RefreshPopup;
Procedure ForceRender; // for automated testing only
Property WorkingStyles : TWPStyles Read GetWorkingStyles Write SetWorkingStyles;
Property Document : TWPWorkingDocument Read GetDocument;
Property PrimaryRange : TWPVisualRange Read GetPrimaryRange;
Property Renderer : TWPScreenRenderer Read GetRenderer;
Property Selection : TWPSelection Read GetSelection;
function BindToField(oDocument: TWPWorkingDocument; cursor : integer; oPiece : TWPWorkingDocumentFieldStartPiece) : boolean;
Procedure ReplaceFieldContent(oDocument: TWPWorkingDocument; cursor : integer; oPiece : TWPWorkingDocumentFieldStartPiece; txt : String);
function BindToSection(oPiece : TWPWorkingDocumentSectionStartPiece) : boolean;
Property ReadOnly : Boolean Read GetReadOnly Write SetReadOnly;
// pagination support
Property PageLayoutController : TWPPageLayoutController Read GetPageLayoutController Write SetPageLayoutController;
Property Printer : TFslPrinter Read GetPrinter Write SetPrinter;
// properties
Function GetProperties : TWPPropertyList; // returns a list of current properties and their values
Procedure SetProperty(oProperty : TWPProperty; Const sValue : String);
Property Modified : Boolean Read FModified Write FModified;
Property Settings : TWPSettings Read GetSettings Write SetSettings;
Property WorkingWidthLimit : Integer Read FWorkingWidthLimit Write SetWorkingWidthLimit;
Property FontsAllowed : TFslStringList Read GetFontsAllowed Write SetFontsAllowed;
Property OnSelectionChanged : TNotifyEvent Read FOnSelectionChanged Write FOnSelectionChanged; //physical selection point has changed (status bar shuld update)
Property OnSettingsChanged : TNotifyEvent Read FOnSettingsChanged write FOnSettingsChanged;
Property OnContentChanged : TNotifyEvent Read FOnContentChanged Write FOnContentChanged; //content of document has changed
Property OnCodeCompletion : TWPCodeCompletionEvent Read FOnCodeCompletion Write FOnCodeCompletion;
Property OnTemplate : TWPTemplateEvent Read FOnTemplate Write SetOnTemplate;
Property OnNamedTemplate : TWPNamedTemplateEvent Read FOnNamedTemplate Write FOnNamedTemplate;
Property OnHotSpot : TWPHotSpotEvent Read FOnHotSpot Write FOnHotSpot;
Property OnHotSpotHover : TWPHotSpotHoverEvent Read FOnHotSpotHover Write FOnHotSpotHover;
Property OnDocumentLoaded : TNotifyEvent read FOnDocumentLoaded write FOnDocumentLoaded;
Property NextControl : TWinControl Read GetNextControl Write FNextControl;
Property PreviousControl : TWinControl Read GetPreviousControl Write FPreviousControl;
Property Color;
Property NonVisibleMode : Boolean Read FNonVisibleMode Write FNonVisibleMode;
Property OnKeyDown;
// internal use only...
Property Inspectors : TWPInspectorList Read FInspectors;
Property VoiceActive : Boolean Read FVoiceActive;
Property ScrollPoint : TPoint Read FScrollPoint;
Property CursorPersist : Boolean Read FCursorPersist;
Property CursorOutside : Boolean Read FCursorOutside;
Property Observers : TWPObservers Read FObservers;
Property DefaultFieldDefinition: TWPFieldDefinitionProvider Read FDefaultFieldDefinition Write SetDefaultFieldDefinition;
Property ExistingSearch : TWPSearchDetails Read GetExistingSearch Write SetExistingSearch;
Property ExistingReplace : TWPReplaceDetails Read GetExistingReplace Write SetExistingReplace;
Property JustDoubleClicked : Boolean Read FJustDoubleClicked;
Property CursorDetails : TWordProcessCursorDetails Read FCursorDetails;
Property MouseActor : TWPMouseActor Read FMouseActor;
Property ResetMouseCursor : Boolean Read FResetMouseCursor;
Property AltNum : String Read FAltNum;
Function HasExistingSearch : Boolean;
Function HasExistingReplace : Boolean;
Property ImageTool : TImageTool Read GetImageTool Write SetImageTool;
Function CreateTouchMenu : TUixPanel;
Procedure WantCloseTouchMenu;
Procedure StartRecordingMacro;
Procedure StopRecordingMacro;
Property Macro : TWPMacro Read FMacro;
Property OnPageDesign : TNotifyEvent read FOnPageDesign write FOnPageDesign;
Property OnPrint : TNotifyEvent read FOnPrint write FOnPrint;
Property OnExport : TNotifyEvent read FOnExport write FOnExport;
Property OnImport : TNotifyEvent read FOnImport write FOnImport;
Property OnSave : TNotifyEvent read FOnSave write FOnSave;
Property OnSaveAs : TNotifyEvent read FOnSaveAs write FOnSaveAs;
Property OnOpen : TNotifyEvent read FOnOpen write FOnOpen;
Property OnNew : TNotifyEvent read FOnNew write FOnNew;
Property OnUpdateField : TWPFieldUpdateEvent read FOnUpdateField write FOnUpdateField;
End;
TRect = Windows.TRect;
TMouseButton = Controls.TMouseButton;
TWPCompletionItem = wp_types.TWPCompletionItem;
TWPCompletionItems = wp_types.TWPCompletionItems;
TWPDocumentEvent = FHIR.WP.Handler.TWPDocumentEvent;
TWPSaveImageEvent = FHIR.WP.Handler.TWPSaveImageEvent;
TWPLoadImageEvent = FHIR.WP.Handler.TWPLoadImageEvent;
TNotifyEvent = Classes.TNotifyEvent;
// TDragonPlaybackManager = DragonPlaybackManagers.TDragonPlaybackManager;
TWPLinkedInspector = Class(TWPInspector)
Private
FWordProcessor : TWordProcessor;
Protected
Procedure WantClose(oSender: TObject); Override;
Procedure WPChange(oSender : TObject); Virtual;
Procedure SetWordProcessor(Const Value: TWordProcessor); Virtual;
Public
Property WordProcessor : TWordProcessor Read FWordProcessor Write SetWordProcessor;
End;
TWPPropertyInspector = Class (TWPLinkedInspector)
Private
FDisplay : TWordProcessor;
FAllProperties : TFslStringObjectMatch;
Procedure SelectionChanged(oSender : TObject);
Procedure ProcessList(oBuilder : TWPDocumentBuilder; oProps : TWPPropertyList; oOwner : TWPDocumentTableRow);
Procedure CommitField(oField: TWPDocumentField; Const sContent: String);
Procedure SetUp;
Protected
Procedure WPChange(oSender : TObject); Override;
Function DesiredWidth : Integer; Override;
Function InspectorCaption : String; Override;
Public
Procedure Initialise; Override;
Procedure Finalise; Override;
End;
TWPSystemSnapshotWriter = class (TWPSnapshotWriter)
private
Procedure ProduceSelection(oSelection : TWPSelection);
Procedure ProduceOperation(oOperation : TWPOperation);
Procedure ProduceRange(oRange : TWPRange);
public
Procedure ProduceOperator(oOperator : TWPOperator);
Procedure ProduceRenderer(oRenderer : TWPScreenRenderer);
Procedure ProduceRanges(oRanges : TWPRangeManager; oPrimary : TWPVisualRange);
Procedure ProduceSettings(oSettings : TWPSettings);
end;
Const
mbLeft = Controls.mbLeft;
mbRight = Controls.mbRight;
mbMiddle = Controls.mbMiddle;
Implementation
Uses
ShellApi, Dialogs, FHIR.WP.Dialogs, FHIR.WP.FieldDefiners;
{ TWPMouseActor }
Constructor TWPMouseActor.Create(oWordProcessor: TWordProcessor);
Begin
Inherited Create;
FWordProcessor := oWordProcessor;
End;
Procedure TWPMouseActor.Close(oNewActor: TWPMouseActor);
Begin
End;
Function TWPMouseActor.Cursor(oInfo: TWPMouseInfo; bDoing: Boolean): TCursor;
Begin
Result := crArrow;
End;
Procedure TWPMouseActor.Down(aShift: TShiftState; iX, iY: Integer; oInfo: TWPMouseInfo; bDouble: Boolean);
Begin
End;
Function TWPMouseActor.Link: TWPMouseActor;
Begin
Result := TWPMouseActor(Inherited Link);
End;
Procedure TWPMouseActor.Move(iX, iY: Integer; bOk: Boolean; oInfo: TWPMouseInfo);
Begin
End;
Procedure TWPMouseActor.Up(aShift: TShiftState; iX, iY: Integer; bOk: Boolean; oInfo: TWPMouseInfo);
Begin
End;
Function TWPMouseActor.RequiresDown: Boolean;
Begin
Result := True;
End;
Type
TWPMouseImageActor = Class (TWPMouseActor)
Private
FImage : TWPWorkingDocumentImagePiece;
Protected
Procedure Restrict(Var iX, iY : Integer);
Function LocalX(iX: Integer):Integer;
Function LocalY(iY: Integer):Integer;
End;
Function TWPMouseImageActor.LocalX(iX: Integer): Integer;
Begin
Result := Trunc((iX - FImage.Map.Left) * (FImage.Image.Width / FImage.Width));
End;
Function TWPMouseImageActor.LocalY(iY: Integer): Integer;
Begin
Result := Trunc((iY - FImage.Map.Top) * (FImage.Image.Height / FImage.Height));
End;
Procedure TWPMouseImageActor.Restrict(Var iX, iY: Integer);
Begin
iX := Max(Min(iX, FImage.Map.Right), FImage.Map.Left);
iY := Max(Min(iY, FImage.Map.Bottom), FImage.Map.Top);
End;
Type
TWPActorDrawLine = Class (TWPMouseImageActor)
Private
FMark : TWPDocumentImageAdornment;
FLocals : TWPCoordinateList;
Procedure Update;
Public
Function Cursor(oInfo : TWPMouseInfo; bDoing : Boolean) : TCursor; Overload; Override;
Procedure Move(iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo); Overload; Override;
Procedure Down(aShift: TShiftState; iX, iY: Integer; oInfo : TWPMouseInfo; bDouble : Boolean); Overload; Override;
Procedure Up(aShift: TShiftState; iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo); Overload; Override;
End;
Procedure TWPActorDrawLine.Update;
Var
points : Array Of TPoint;
i : Integer;
oCanvas : TCanvas;
Begin
oCanvas := FWordProcessor.Canvas;
{$IFNDEF NO_VCL_CANVAS_LOCK}
oCanvas.Lock;
Try
{$ENDIF}
oCanvas.Pen.Style := ADVPENSTYLE_VCLVALUES[FMark.PenStyle];
oCanvas.Pen.Mode := pmCopy;
oCanvas.Pen.Color := FMark.PenColour;
oCanvas.Pen.Width := FMark.PenWidth;
SetLength(points, FLocals.Count);
For i := 0 To FLocals.Count - 1 Do
points[i] := FLocals[i].AsPoint;
oCanvas.Polyline(points);
{$IFNDEF NO_VCL_CANVAS_LOCK}
Finally
oCanvas.Unlock;
End;
{$ENDIF}
End;
Function TWPActorDrawLine.Cursor(oInfo : TWPMouseInfo; bDoing : Boolean) : TCursor;
Begin
Result := WPIconModule.CURSOR_PEN;
End;
Procedure TWPActorDrawLine.Move(iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo);
Begin
Restrict(iX, iY);
If (FMark <> Nil) And (Not FLocals.LastIs(iX, iY)) Then
Begin
FMark.Coordinates.Add(LocalX(iX), LocalY(iY));
FLocals.Add(iX, iY-FWordProcessor.FScrollPoint.Y);
Update;
End;
End;
Procedure TWPActorDrawLine.Down(aShift: TShiftState; iX, iY: Integer; oInfo : TWPMouseInfo; bDouble : Boolean);
Begin
FOffsetSquareforScroll := True;
FImage := oInfo.Subject As TWPWorkingDocumentImagePiece;
FMark := TWPDocumentImageAdornment.Create;
FMark.AdornmentType := iatLine;
FMark.PenColour := FImage.DefaultAdornmentColour;
FMark.Font.Foreground := FImage.DefaultAdornmentColour;
FMark.PenWidth := 1;
FMark.PenStyle := apsSolid;
FMark.Coordinates.Add(LocalX(iX), LocalY(iY));
FLocals := TWPCoordinateList.Create;
FLocals.Add(iX, iY-FWordProcessor.FScrollPoint.Y);
Update;
End;
Procedure TWPActorDrawLine.Up(aShift: TShiftState; iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo);
Begin
If FMark.Coordinates.Count > 1 Then
Begin
FWordProcessor.PrimaryRange.ApplyImageAdornment(FImage, FMark);
FWordProcessor.ImageTool := itSelect;
End;
FLocals.Free;
FMark.Free;
FMark := Nil;
FImage := Nil;
End;
Type
TWPActorDrawRectangle = Class (TWPMouseImageActor)
Private
FCircle : Boolean;
FMark : TWPDocumentImageAdornment;
FStart : TPoint;
FEnd : TPoint;
FStartLocal : TPoint;
FEndLocal : TPoint;
Procedure Update;
Public
Function Cursor(oInfo : TWPMouseInfo; bDoing : Boolean) : TCursor; Overload; Override;
Procedure Move(iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo); Overload; Override;
Procedure Down(aShift: TShiftState; iX, iY: Integer; oInfo : TWPMouseInfo; bDouble : Boolean); Overload; Override;
Procedure Up(aShift: TShiftState; iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo); Overload; Override;
End;
Procedure TWPActorDrawRectangle.Update;
Var
oCanvas : TCanvas;
Begin
oCanvas := FWordProcessor.Canvas;
{$IFNDEF NO_VCL_CANVAS_LOCK}
oCanvas.Lock;
Try
{$ENDIF}
oCanvas.Pen.Style := ADVPENSTYLE_VCLVALUES[FMark.PenStyle];
oCanvas.Pen.Mode := pmNot;
oCanvas.Pen.Color := FMark.PenColour;
oCanvas.Pen.Width := FMark.PenWidth;
oCanvas.Brush.Style := bsClear;
If FCircle Then
oCanvas.Ellipse(Fstart.x, FStart.y, FEnd.X, FEnd.y)
Else
oCanvas.Rectangle(Fstart.x, FStart.y, FEnd.X, FEnd.y);
{$IFNDEF NO_VCL_CANVAS_LOCK}
Finally
oCanvas.Unlock;
End;
{$ENDIF}
End;
Function TWPActorDrawRectangle.Cursor(oInfo : TWPMouseInfo; bDoing : Boolean) : TCursor;
Begin
If FCircle Then
Result := WPIconModule.CURSOR_CIRCLE
Else
Result := WPIconModule.CURSOR_BOX;
End;
Procedure TWPActorDrawRectangle.Move(iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo);
Begin
Restrict(iX, iY);
If (FMark <> Nil) Then
Begin
Update;
FEnd.X := iX;
FEnd.Y := iY-FWordProcessor.FScrollPoint.Y;
FEndLocal.X := LocalX(iX);
FEndLocal.Y := LocalY(iY);
Update;
End;
End;
Procedure TWPActorDrawRectangle.Down(aShift: TShiftState; iX, iY: Integer; oInfo : TWPMouseInfo; bDouble : Boolean);
Begin
FImage := oInfo.Subject As TWPWorkingDocumentImagePiece;
Restrict(iX, iY);
FMark := TWPDocumentImageAdornment.Create;
If FCircle Then
FMark.AdornmentType := iatCircle
Else
FMark.AdornmentType := iatRectangle;
FMark.PenColour := FImage.DefaultAdornmentColour;
FMark.Font.Foreground := FImage.DefaultAdornmentColour;
FMark.PenWidth := 1;
FMark.PenStyle := apsDot;
FStart.X := iX;
FStart.Y := iY-FWordProcessor.FScrollPoint.Y;
FStartLocal.X := LocalX(iX);
FStartLocal.Y := LocalY(iY);
FEnd := FStart;
Update;
End;
Procedure TWPActorDrawRectangle.Up(aShift: TShiftState; iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo);
Begin
If (FStart.x <> FEnd.x) Or (FStart.y <> FEnd.y) Then
Begin
FMark.Coordinates.Add(Min(FStartLocal.x, FEndLocal.x), Min(FStartLocal.y, FEndLocal.y));
FMark.Coordinates.Add(Max(FStartLocal.x, FEndLocal.x), Max(FStartLocal.y, FEndLocal.y));
FWordProcessor.PrimaryRange.ApplyImageAdornment(FImage, FMark);
FWordProcessor.ImageTool := itSelect;
End;
FMark.Free;
FMark := Nil;
FImage := Nil;
End;
Type
TWPActorDrawMark = Class (TWPMouseImageActor)
Private
FMark : TWPDocumentImageAdornment;
FStart : TPoint;
FEnd : TPoint;
FStartLocal : TPoint;
FEndLocal : TPoint;
Procedure Update;
Public
Function Cursor(oInfo : TWPMouseInfo; bDoing : Boolean) : TCursor; Overload; Override;
Procedure Move(iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo); Overload; Override;
Procedure Down(aShift: TShiftState; iX, iY: Integer; oInfo : TWPMouseInfo; bDouble : Boolean); Overload; Override;
Procedure Up(aShift: TShiftState; iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo); Overload; Override;
End;
Procedure TWPActorDrawMark.Update;
Var
oCanvas : TCanvas;
Begin
oCanvas := FWordProcessor.Canvas;
{$IFNDEF NO_VCL_CANVAS_LOCK}
oCanvas.Lock;
Try
{$ENDIF}
oCanvas.Pen.Style := ADVPENSTYLE_VCLVALUES[FMark.PenStyle];
oCanvas.Pen.Mode := pmNot;
oCanvas.Pen.Color := FMark.PenColour;
oCanvas.Pen.Width := FMark.PenWidth;
oCanvas.Brush.Style := bsClear;
oCanvas.MoveTo(FStart.X, FStart.Y);
oCanvas.LineTo(FEnd.X, FEnd.Y);
{$IFNDEF NO_VCL_CANVAS_LOCK}
Finally
oCanvas.Unlock;
End;
{$ENDIF}
End;
Function TWPActorDrawMark.Cursor(oInfo : TWPMouseInfo; bDoing : Boolean) : TCursor;
Begin
Result := WPIconModule.CURSOR_MARK;
End;
Procedure TWPActorDrawMark.Move(iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo);
Begin
Restrict(iX, iY);
If (FMark <> Nil) Then
Begin
Update;
FEnd.X := iX;
FEnd.Y := iY-FWordProcessor.FScrollPoint.Y;
FEndLocal.X := LocalX(iX);
FEndLocal.Y := LocalY(iY);
Update;
End;
End;
Procedure TWPActorDrawMark.Down(aShift: TShiftState; iX, iY: Integer; oInfo : TWPMouseInfo; bDouble : Boolean);
Begin
FImage := oInfo.Subject As TWPWorkingDocumentImagePiece;
FMark := TWPDocumentImageAdornment.Create;
FMark.AdornmentType := iatMark;
FMark.PenColour := FImage.DefaultAdornmentColour;
FMark.Font.Foreground := FImage.DefaultAdornmentColour;
FMark.PenWidth := 1;
FMark.PenStyle := apsDash;
FStart.X := iX;
FStart.Y := iY-FWordProcessor.FScrollPoint.Y;
FStartLocal.X := LocalX(iX);
FStartLocal.Y := LocalY(iY);
FEnd := FStart;
Update;
End;
Procedure TWPActorDrawMark.Up(aShift: TShiftState; iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo);
Var
oDialog : TWPAdornmentDialog;
oImage : TWPWorkingDocumentImagePiece;
Begin
If (FStart.x <> FEnd.x) Or (FStart.y <> FEnd.y) Then
Begin
Update;
FMark.Coordinates.Add(FStartLocal.x, FStartLocal.y);
FMark.CaptionPoint.X := FEndLocal.x;
FMark.CaptionPoint.Y := FEndLocal.Y;
oDialog := TWPAdornmentDialog.Create(FWordProcessor);
Try
// uh, self will likely disappear underneath us....
oDialog.Adornment := FMark.Clone;
FMark.Free;
FMark := Nil;
oImage := FImage;
FImage := Nil;
oDialog.FontsAllowed := FWordProcessor.FFontsAllowed.Link;
If oDialog.Execute Then
Begin
FWordProcessor.PrimaryRange.ApplyImageAdornment(oImage, oDialog.Adornment);
FWordProcessor.ImageTool := itSelect;
End;
Finally
oDialog.Free;
End;
End;
End;
Type
TWPActorDrawZoom = Class (TWPMouseImageActor)
Private
FCircle : Boolean;
FMark : TWPDocumentImageAdornment;
FStart : TPoint;
FEnd : TPoint;
FStartLocal : TPoint;
FEndLocal : TPoint;
Procedure Update;
Public
Function Cursor(oInfo : TWPMouseInfo; bDoing : Boolean) : TCursor; Overload; Override;
Procedure Move(iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo); Overload; Override;
Procedure Down(aShift: TShiftState; iX, iY: Integer; oInfo : TWPMouseInfo; bDouble : Boolean); Overload; Override;
Procedure Up(aShift: TShiftState; iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo); Overload; Override;
End;
Procedure TWPActorDrawZoom.Update;
Var
oCanvas : TCanvas;
Begin
oCanvas := FWordProcessor.Canvas;
{$IFNDEF NO_VCL_CANVAS_LOCK}
oCanvas.Lock;
Try
{$ENDIF}
oCanvas.Pen.Style := ADVPENSTYLE_VCLVALUES[FMark.PenStyle];
oCanvas.Pen.Mode := pmNot;
oCanvas.Pen.Color := FMark.PenColour;
oCanvas.Pen.Width := FMark.PenWidth;
oCanvas.Brush.Style := bsClear;
If FCircle Then
oCanvas.Ellipse(Fstart.x, FStart.y, FEnd.X, FEnd.y)
Else
oCanvas.Rectangle(Fstart.x, FStart.y, FEnd.X, FEnd.y);
{$IFNDEF NO_VCL_CANVAS_LOCK}
Finally
oCanvas.Unlock;
End;
{$ENDIF}
End;
Function TWPActorDrawZoom.Cursor(oInfo : TWPMouseInfo; bDoing : Boolean) : TCursor;
Begin
Result := WPIconModule.CURSOR_ZOOM;
End;
Procedure TWPActorDrawZoom.Move(iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo);
Begin
Restrict(iX, iY);
If (FMark <> Nil) Then
Begin
Update;
FEnd.X := iX;
FEnd.Y := iY-FWordProcessor.FScrollPoint.Y;
FEndLocal.X := LocalX(iX);
FEndLocal.Y := LocalY(iY);
Update;
End;
End;
Procedure TWPActorDrawZoom.Down(aShift: TShiftState; iX, iY: Integer; oInfo : TWPMouseInfo; bDouble : Boolean);
Begin
FImage := oInfo.Subject As TWPWorkingDocumentImagePiece;
Restrict(iX, iY);
FMark := TWPDocumentImageAdornment.Create;
FMark.AdornmentType := iatZoom;
FMark.PenColour := FImage.DefaultAdornmentColour;
FMark.Font.Foreground := FImage.DefaultAdornmentColour;
FMark.PenWidth := 1;
FMark.PenStyle := apsDot;
FStart.X := iX;
FStart.Y := iY-FWordProcessor.FScrollPoint.Y;
FStartLocal.X := LocalX(iX);
FStartLocal.Y := LocalY(iY);
FEnd := FStart;
Update;
End;
Function FitZoom(Const rImage, rFocus : TRect; iScale : Integer; Var rZoom : TRect) : Boolean;
Var
w,h : Integer;
Begin
w := (rFocus.Right - rFocus.Left) * iScale;
h := (rFocus.Bottom - rFocus.Top) * iScale;
// can we fit it on a diagonal?
// right, then left, bottom, then top
Result := True;
If (rFocus.Right + w + 40 < rImage.Right) And (rFocus.Bottom + h + 40 < rImage.Bottom) Then
Begin
rZoom.Left := rFocus.Right + 40;
rZoom.Top := rFocus.Bottom + 40;
End
Else If (rFocus.Left - (w + 40) > 0) And (rFocus.Bottom + h + 40 < rImage.Bottom) Then
Begin
rZoom.Left := rFocus.Left - (w + 40);
rZoom.Top := rFocus.Bottom + 40;
End
Else If (rFocus.Right + w + 40 < rImage.Right) And (rFocus.Top - (h + 40) > 0) Then
Begin
rZoom.Left := rFocus.Right + 40;
rZoom.Top := rFocus.Top - (h + 40);
End
Else If (rFocus.Left - (w + 40) > 0) And (rFocus.Top - (h + 40) > 0) Then
Begin
rZoom.Left := rFocus.Left - (w + 40);
rZoom.Top := rFocus.Top - (h + 40);
End
Else If (rFocus.Bottom + h + 20 < rImage.Bottom) And (w < rImage.Right) Then
Begin
rZoom.Left := (rImage.Right Div 2) - (w Div 2);
rZoom.Top := rFocus.Bottom + 20;
End
Else If (rFocus.Top - (h + 20) > 0) And (w < rImage.Right) Then
Begin
rZoom.Left := (rImage.Right Div 2) - (w Div 2);
rZoom.Top := rFocus.Top - (h + 20);
End
Else If (rFocus.Right + w + 20 < rImage.Right) And (h < rImage.Bottom) Then
Begin
rZoom.Left := rFocus.Right + 20;
rZoom.Top := (rImage.Bottom Div 2) - (h Div 2);
End
Else If (rFocus.Left - (w + 20) > 0) And (h < rImage.Bottom) Then
Begin
rZoom.Left := rFocus.Left - (w + 20);
rZoom.Top := (rImage.Bottom Div 2) - (h Div 2);
End
Else
Result := False;
rZoom.Right := rZoom.Left + w;
rZoom.Bottom := rZoom.Top + h;
If Result Then
Begin
Assert(rZoom.Left >= 0);
Assert(rZoom.Top >= 0);
Assert(rZoom.Bottom <= rImage.Bottom);
Assert(rZoom.right <= rImage.Right);
End;
End;
Procedure TWPActorDrawZoom.Up(aShift: TShiftState; iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo);
Var
rImage, rFocus, rZoom : TRect;
Begin
Update;
If (Abs(FStart.x - FEnd.x) > 10) And (Abs(FStart.y - FEnd.y) > 10) Then
Begin
rImage.Top := 0;
rImage.Left := 0;
rImage.Right := FImage.Image.Width;
rImage.Bottom := FImage.Image.Height;
rFocus.Top := Min(FStartLocal.y, FEndLocal.y);
rFocus.Left := Min(FStartLocal.x, FEndLocal.x);
rFocus.Bottom := Max(FStartLocal.y, FEndLocal.y);
rFocus.Right := Max(FStartLocal.x, FEndLocal.x);
// what we have to do is to determine where the expanded area is going to be.
If Not FitZoom(rImage, rFocus, 8, rZoom) And
Not FitZoom(rImage, rFocus, 4, rZoom) And
Not FitZoom(rImage, rFocus, 2, rZoom) Then
MessageDlg('Unable to zoom such a large area. Choose a smaller area', mterror, [mbok], 0)
Else
Begin
FMark.Coordinates.Add(rFocus.Left, rFocus.Top);
FMark.Coordinates.Add(rFocus.Right, rFocus.Bottom);
FMark.Coordinates.Add(rZoom.Left, rZoom.Top);
FMark.Coordinates.Add(rZoom.Right, rZoom.Bottom);
FWordProcessor.PrimaryRange.ApplyImageAdornment(FImage, FMark);
FWordProcessor.ImageTool := itSelect;
End;
End;
FMark.Free;
FMark := Nil;
FImage := Nil;
End;
Type
TWPActorNull = Class (TWPMouseImageActor)
Private
Public
End;
Type
TWPActorSelect = Class (TWPMouseImageActor)
Private
FDouble : Boolean;
FAdornment : TWPDocumentImageAdornment;
FAdornmentPart : TAdornmentPart;
FAdornmentAction : TAdornmentAction;
FStartX : Integer;
FStartY : Integer;
FCurrentX : Integer;
FCurrentY : Integer;
FMinX : Integer;
FMaxX : Integer;
FMinY : Integer;
FMaxY : Integer;
FPart : TRect;
Public
Function Cursor(oInfo : TWPMouseInfo; bDoing : Boolean) : TCursor; Overload; Override;
Procedure Move(iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo); Overload; Override;
Procedure Down(aShift: TShiftState; iX, iY: Integer; oInfo : TWPMouseInfo; bDouble : Boolean); Overload; Override;
Procedure Up(aShift: TShiftState; iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo); Overload; Override;
End;
Procedure TWPActorSelect.Down(aShift: TShiftState; iX, iY: Integer; oInfo : TWPMouseInfo; bDouble : Boolean);
Begin
If (Not FWordProcessor.NoUserResponse) Then
If oInfo.Adornment <> Nil Then
Begin
FOffsetSquareforScroll := True;
FDouble := bDouble;
FImage := TWPWorkingDocumentImagePiece(oInfo.Subject);
FStartX := iX;
FStartY := iY;
FCurrentX := FStartX;
FCurrentY := FStartY;
FAdornment := oInfo.Adornment;
FAdornmentPart := oInfo.AdornmentPart;
FAdornmentAction := oInfo.AdornmentAction;
FPart := FImage.GetExtant(FAdornment, FAdornmentPart, FAdornmentAction);
// scale extant for image scaling
FPart.Left := Trunc(FPart.Left * FImage.Width / FImage.Image.Width);
FPart.Right := Trunc(FPart.Right * FImage.Width / FImage.Image.Width);
FPart.Top := Trunc(FPart.Top * FImage.Height / FImage.Image.Height);
FPart.Bottom := Trunc(FPart.Bottom * FImage.Height / FImage.Image.Height);
FMinX := FCurrentX - FPart.Left;
FMinY := FCurrentY - FPart.Top;
FMaxX := FCurrentX + FImage.Width - FPart.Right - 1;
FMaxY := FCurrentY + FImage.Height - FPart.Bottom - 1;
// that's the absolute limits. There's also a limit when resizing - the adornment is not allowed to get smaller than 20*20
// todo: is that scaled pixels? Can an adornment get to small to handle?
Case FAdornmentAction Of
aaDragTop :
FMaxY := FImage.Map.Top + FPart.Bottom - 20;
aaDragBottom :
FMinY := FImage.Map.Top + FPart.Top + 20;
aaDragLeft :
FMaxX := FImage.Map.Left + FPart.Right - 20;
aaDragRight :
FMinX := FImage.Map.Left + FPart.Left + 20;
aaDragTopLeft :
Begin
FMaxX := FImage.Map.Left + FPart.Right - 20;
FMaxY := FImage.Map.Top + FPart.Bottom - 20;
End;
aaDragTopRight :
Begin
FMinX := FImage.Map.Left + FPart.Left + 20;
FMaxY := FImage.Map.Top + FPart.Bottom - 20;
End;
aaDragBottomLeft :
Begin
FMaxX := FImage.Map.Left + FPart.Right - 20;
FMinY := FImage.Map.Top + FPart.Top + 20;
End;
aaDragBottomRight :
Begin
FMinX := FImage.Map.Left + FPart.Left + 20;
FMinY := FImage.Map.Top + FPart.Top + 20;
End;
End;
FPart.Top := FPart.Top + (iY - Trunc(LocalY(iY) * FImage.Height / FImage.Image.Height));
FPart.Bottom := FPart.Bottom + (iY - Trunc(LocalY(iY) * FImage.Height / FImage.Image.Height));
FPart.Left := FPart.Left + (iX - Trunc(LocalX(iX) * FImage.Width / FImage.Image.Width));
FPart.Right := FPart.Right + (iX - Trunc(LocalX(iX) * FImage.Width / FImage.Image.Width));
Square(FPart.Left, FPart.Top, FPart.Right, FPart.Bottom);
End
Else If bDouble Then
Begin
FWordProcessor.PrimaryRange.SelectWord();
FDouble := True;
End
Else
Begin
FWordProcessor.PrimaryRange.MoveTo(oInfo.Offset);
End;
End;
Function TWPActorSelect.Cursor(oInfo : TWPMouseInfo; bDoing : Boolean) : TCursor;
Function CursorForAction(aAction : TAdornmentAction) : TCursor;
Begin
Case aAction Of
aaMove : Result := crHandPoint;
aaDragTop : Result := crSizeNS;
aaDragBottom : Result := crSizeNS;
aaDragLeft : Result := crSizeWE;
aaDragRight : Result := crSizeWE;
aaDragTopLeft : Result := crSizeNWSE;
aaDragTopRight : Result := crSizeNESW;
aaDragBottomLeft : Result := crSizeNESW;
aaDragBottomRight : Result := crSizeNWSE;
Else
Result := crDefault;
End;
End;
Begin
If (FAdornment <> Nil) Then
Result := CursorForAction(FAdornmentAction)
Else If (oInfo.Adornment <> Nil) Then
Result := CursorForAction(oInfo.AdornmentAction)
Else
Result := crIBeam;
End;
Procedure TWPActorSelect.Move(iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo);
Begin
If bOk And Not FDouble And Not FWordProcessor.NoUserResponse and ((FAdornment = Nil) or not FWordProcessor.Settings.ReadOnly) Then
Begin
If FAdornment <> Nil Then
Begin
Square(FLastLeft, FLastTop, FLastRight, FLastBottom);
FCurrentX := IntegerMin(IntegerMax(iX, FMinX), FMaxX);
FCurrentY := IntegerMin(IntegerMax(iY, FMinY), FMaxY);
Case FAdornmentAction Of
aaMove : Square(FPart.Left + (FCurrentX - FStartX), FPart.Top + (FCurrentY - FStartY), FPart.Right + (FCurrentX - FStartX), FPart.Bottom + (FCurrentY - FStartY));
aaDragTop : Square(FPart.Left, FPart.Top + (FCurrentY - FStartY), FPart.Right, FPart.Bottom);
aaDragBottom : Square(FPart.Left, FPart.Top, FPart.Right, FPart.Bottom + (FCurrentY - FStartY));
aaDragLeft : Square(FPart.Left + (FCurrentX - FStartX), FPart.Top, FPart.Right, FPart.Bottom);
aaDragRight : Square(FPart.Left, FPart.Top, FPart.Right + (FCurrentX - FStartX), FPart.Bottom);
aaDragTopLeft : Square(FPart.Left + (FCurrentX - FStartX), FPart.Top + (FCurrentY - FStartY), FPart.Right, FPart.Bottom);
aaDragTopRight : Square(FPart.Left, FPart.Top + (FCurrentY - FStartY), FPart.Right + (FCurrentX - FStartX), FPart.Bottom);
aaDragBottomLeft : Square(FPart.Left + (FCurrentX - FStartX), FPart.Top, FPart.Right, FPart.Bottom + (FCurrentY - FStartY));
aaDragBottomRight : Square(FPart.Left, FPart.Top, FPart.Right + (FCurrentX - FStartX), FPart.Bottom + (FCurrentY - FStartY));
End;
End
Else
FWordProcessor.PrimaryRange.SelectTo(oInfo.Offset);
End;
End;
Procedure TWPActorSelect.Up(aShift: TShiftState; iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo);
Var
oDialog : TWPAdornmentDialog;
bReadOnly : Boolean;
Begin
If FAdornment <> Nil Then
Begin
Square(FLastLeft, FLastTop, FLastRight, FLastBottom);
bReadOnly := FWordProcessor.Settings.ReadOnly or
not (oInfo.Subject Is TWPWorkingDocumentPiece) or
TWPWorkingDocumentPiece(oInfo.Subject).IsReadOnly;
If FDouble and not bReadOnly Then
Begin
oDialog := TWPAdornmentDialog.Create(FWordProcessor);
Try
oDialog.Adornment := oInfo.Adornment.Clone;
oDialog.FontsAllowed := FWordProcessor.FFontsAllowed.Link;
If oDialog.Execute Then
FWordProcessor.PrimaryRange.ApplyImageAdornment(TWPWorkingDocumentImagePiece(oInfo.Subject), oDialog.Adornment);
Finally
oDialog.Free;
End;
End
Else If (FCurrentX - FStartX <> 0) Or (FCurrentY - FStartY <> 0) Then
FWordProcessor.PrimaryRange.MoveImageAdornment(FImage, FAdornment, FAdornmentPart, FAdornmentAction, Trunc((FCurrentX - FStartX) * (FImage.Image.Width / FImage.Width)), Trunc((FCurrentY - FStartY) * (FImage.Image.Height / FImage.Height)));
FAdornment := Nil;
FImage := Nil;
End;
End;
Type
TWPActorDragSelection = Class (TWPMouseActor)
Private
Start : boolean;
XOffset, YOffset : integer;
Public
Function Cursor(oInfo : TWPMouseInfo; bDoing : Boolean) : TCursor; Overload; Override;
Procedure Down(aShift: TShiftState; iX, iY: Integer; oInfo : TWPMouseInfo; bDouble : Boolean); Overload; Override;
Procedure Move(iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo); Overload; Override;
Procedure Up(aShift: TShiftState; iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo); Overload; Override;
End;
Procedure TWPActorDragSelection.Down(aShift: TShiftState; iX, iY: Integer; oInfo : TWPMouseInfo; bDouble : Boolean);
Begin
if Start then
FWordProcessor.FCursorDetails.FSelHot := shStart
else
FWordProcessor.FCursorDetails.FSelHot := shEnd;
End;
Function TWPActorDragSelection.Cursor(oInfo : TWPMouseInfo; bDoing : Boolean) : TCursor;
Begin
Result := crSizeWE;
End;
Procedure TWPActorDragSelection.Move(iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo);
var
offs : integer;
Begin
if Start then
begin
inc(iX, XOffset);
inc(iY, YOffset);
FWordProcessor.Renderer.getMouseInfoForPoint(iX, iY, oInfo);
offs := Max(oInfo.Offset, 0);
if offs < FWordProcessor.PrimaryRange.Selection.SelEnd then
begin
FWordProcessor.PrimaryRange.MoveTo(FWordProcessor.PrimaryRange.Selection.SelEnd, false);
FWordProcessor.PrimaryRange.SelectTo(offs, true);
end;
end
else
begin
dec(iX, XOffset);
dec(iY, YOffset);
FWordProcessor.Renderer.getMouseInfoForPoint(iX, iY, oInfo);
offs := Min(oInfo.Offset, FWordProcessor.Document.CharCount);
if offs > FWordProcessor.PrimaryRange.Selection.SelStart then
begin
FWordProcessor.PrimaryRange.MoveTo(FWordProcessor.PrimaryRange.Selection.SelStart, false);
FWordProcessor.PrimaryRange.SelectTo(offs, true);
end;
end;
End;
Procedure TWPActorDragSelection.Up(aShift: TShiftState; iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo);
Begin
FWordProcessor.FCursorDetails.FSelHot := shNeither;
End;
Type
TWPActorDragBlock = Class (TWPMouseActor)
Public
Function Cursor(oInfo : TWPMouseInfo; bDoing : Boolean) : TCursor; Overload; Override;
Procedure Down(aShift: TShiftState; iX, iY: Integer; oInfo : TWPMouseInfo; bDouble : Boolean); Overload; Override;
Procedure Move(iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo); Overload; Override;
Procedure Up(aShift: TShiftState; iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo); Overload; Override;
End;
Procedure TWPActorDragBlock.Down(aShift: TShiftState; iX, iY: Integer; oInfo : TWPMouseInfo; bDouble : Boolean);
Begin
// nothing
End;
Function TWPActorDragBlock.Cursor(oInfo : TWPMouseInfo; bDoing : Boolean) : TCursor;
Begin
If bDoing Then
Result := crDrag
Else
Result := crArrow;
End;
Procedure TWPActorDragBlock.Move(iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo);
Begin
FWordProcessor.ClearDragMark;
If Not bOk Or FWordProcessor.PrimaryRange.Selection.InSelection(oInfo.Offset) Or FWordProcessor.NoUserResponse Then
FWordProcessor.ApplyCursorState(crNoDrop, True)
Else
Begin
FWordProcessor.ApplyCursorState(crDrag, True);
FWordProcessor.DrawDragMark(oInfo.Offset);
End;
End;
Procedure TWPActorDragBlock.Up(aShift: TShiftState; iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo);
Begin
FWordProcessor.ClearDragMark;
If bOk Then
Begin
If FWordProcessor.PrimaryRange.Selection.InSelection(oInfo.Offset) Then
FWordProcessor.PrimaryRange.MoveTo(oInfo.Offset)
Else
FWordProcessor.PrimaryRange.MoveSelection(oInfo.Offset);
End;
End;
Type
TWPActorDragEdge = Class (TWPMouseActor)
Private
FButton : TFslObject;
FEdgeAction : TEdgeAction;
iStartingLeft : Integer;
iStartingTop : Integer;
iStartingBottom : Integer;
iStartingRight : Integer;
Function WorkingLeft(iX, iY : Integer):Integer;
Function WorkingRight(iX, iY : Integer):Integer;
Function WorkingTop(iX, iY : Integer):Integer;
Function WorkingBottom(iX, iY : Integer):Integer;
Public
destructor Destroy; Override;
Function Cursor(oInfo : TWPMouseInfo; bDoing : Boolean) : TCursor; Overload; Override;
Procedure Down(aShift: TShiftState; iX, iY: Integer; oInfo : TWPMouseInfo; bDouble : Boolean); Overload; Override;
Procedure Move(iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo); Overload; Override;
Procedure Up(aShift: TShiftState; iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo); Overload; Override;
End;
Destructor TWPActorDragEdge.Destroy;
Begin
FButton.Free;
Inherited;
End;
Procedure TWPMouseActor.Square(iLeft, iTop, iRight, iBottom : Integer);
Var
iYOffs : Integer;
Begin
If FOffsetSquareforScroll Then
iYOffs := FWordProcessor.FScrollPoint.Y
Else
iYOffs := 0;
{$IFNDEF NO_VCL_CANVAS_LOCK}
FWordProcessor.Canvas.Lock;
Try
{$ENDIF}
FWordProcessor.Canvas.Pen.Style := psSolid;
FWordProcessor.Canvas.Pen.Mode := pmNot;
FWordProcessor.Canvas.Pen.Color := clNavy;
FWordProcessor.Canvas.MoveTo(iLeft, iTop - iYOffs);
FWordProcessor.Canvas.LineTo(iRight, iTop - iYOffs);
FWordProcessor.Canvas.LineTo(iRight, iBottom - iYOffs);
FWordProcessor.Canvas.LineTo(iLeft, iBottom - iYOffs);
FWordProcessor.Canvas.LineTo(iLeft, iTop - iYOffs);
{$IFNDEF NO_VCL_CANVAS_LOCK}
Finally
FWordProcessor.Canvas.Unlock;
End;
{$ENDIF}
FLastTop := iTop;
FLastBottom := iBottom;
FLastLeft := iLeft;
FLastRight := iRight;
End;
Function TWPActorDragEdge.WorkingLeft(iX, iY : Integer):Integer;
var
ratio : double;
Begin
If (FEdgeAction = eaLeft) Then
Result := IntegerMin(iX, iStartingRight - MIN_IMAGE_DRAG)
Else If (FEdgeAction = eaLeftTop) then
begin
// the working left is the average of the x/y changes in terms of the existing ratio of the image
ratio := (((iX - iStartingLeft) / (iStartingRight - iStartingLeft)) +
((iY - iStartingTop) / (iStartingBottom - iStartingTop))) / 2;
result := IntegerMin(iStartingLeft + trunc((iStartingRight - iStartingLeft) * ratio), iStartingRight - MIN_IMAGE_DRAG);
end
else If (FEdgeAction = eaLeftBottom) then
begin
ratio := (((iX - iStartingLeft) / (iStartingRight - iStartingLeft)) +
((iY - iStartingBottom) / (iStartingTop - iStartingBottom))) / 2;
result := IntegerMin(iStartingLeft + trunc((iStartingRight - iStartingLeft) * ratio), iStartingRight - MIN_IMAGE_DRAG);
end
else
Result := iStartingLeft;
End;
Function TWPActorDragEdge.WorkingRight(iX, iY : Integer):Integer;
var
ratio : double;
Begin
If (FEdgeAction In [eaRight]) Then
Result := IntegerMax(iX, iStartingLeft + MIN_IMAGE_DRAG)
else if FEdgeAction = eaRightBottom then
begin
ratio := (((iX - iStartingRight) / (iStartingLeft - iStartingRight)) +
((iY - iStartingBottom) / (iStartingTop - iStartingBottom))) / 2;
result := IntegerMax(iStartingRight - trunc((iStartingRight - iStartingLeft) * ratio), iStartingLeft + MIN_IMAGE_DRAG);
end
Else if FEdgeAction = eaRightTop then
begin
ratio := (((iX - iStartingRight) / (iStartingLeft - iStartingRight)) +
((iY - iStartingTop) / (iStartingBottom - iStartingTop))) / 2;
result := IntegerMax(iStartingRight - trunc((iStartingRight - iStartingLeft) * ratio), iStartingLeft + MIN_IMAGE_DRAG);
end
Else
Result := iStartingRight;
End;
Function TWPActorDragEdge.WorkingTop(iX, iY : Integer):Integer;
var
ratio : double;
Begin
If (FEdgeAction In [eaTop]) Then
Result := IntegerMin(iY, iStartingBottom - MIN_IMAGE_DRAG)
Else if FEdgeAction = eaRightTop then
begin
ratio := (((iX - iStartingRight) / (iStartingLeft - iStartingRight)) +
((iY - iStartingTop) / (iStartingBottom - iStartingTop))) / 2;
result := IntegerMin(iStartingTop + trunc((iStartingBottom - iStartingTop) * ratio), iStartingBottom - MIN_IMAGE_DRAG);
end
Else if FEdgeAction = eaLeftTop then
begin
ratio := (((iX - iStartingLeft) / (iStartingRight - iStartingLeft)) +
((iY - iStartingTop) / (iStartingBottom - iStartingTop))) / 2;
result := IntegerMin(iStartingTop + trunc((iStartingBottom - iStartingTop) * ratio), iStartingBottom - MIN_IMAGE_DRAG);
end
Else
Result := iStartingTop;
End;
Function TWPActorDragEdge.WorkingBottom(iX, iY : Integer):Integer;
var
ratio : double;
Begin
If (FEdgeAction In [eaBottom]) Then
Result := IntegerMax(iY, iStartingTop + MIN_IMAGE_DRAG)
Else If (FEdgeAction = eaRightBottom) then
begin
ratio := (((iX - iStartingRight) / (iStartingLeft - iStartingRight)) +
((iY - iStartingBottom) / (iStartingTop - iStartingBottom))) / 2;
result := IntegerMax(iStartingbottom - trunc((iStartingBottom - iStartingTop) * ratio), iStartingTop + MIN_IMAGE_DRAG);
end
Else If (FEdgeAction = eaLeftBottom) then
begin
ratio := (((iX - iStartingLeft) / (iStartingRight - iStartingLeft)) +
((iY - iStartingBottom) / (iStartingTop - iStartingBottom))) / 2;
result := IntegerMax(iStartingbottom - trunc((iStartingBottom - iStartingTop) * ratio), iStartingTop + MIN_IMAGE_DRAG);
end
Else
Result := iStartingBottom;
End;
Procedure TWPActorDragEdge.Down(aShift: TShiftState; iX, iY: Integer; oInfo : TWPMouseInfo; bDouble : Boolean);
Begin
FButton := oInfo.Subject.Link;
FEdgeAction := oInfo.EdgeAction;
If FButton Is TWPWorkingDocumentImagePiece Then
Begin
iStartingLeft := TWPWorkingDocumentImagePiece(FButton).Map.Left;
iStartingTop := TWPWorkingDocumentImagePiece(FButton).Map.Top;
iStartingRight := TWPWorkingDocumentImagePiece(FButton).Map.Right;
iStartingBottom := TWPWorkingDocumentImagePiece(FButton).Map.Bottom;
End
Else if FButton is TWPWorkingAnnotationList Then
Begin
iStartingLeft := FWordProcessor.Left + FWordProcessor.Width - FWordProcessor.Renderer.SpaceForAnnotations;
iStartingTop := FWordProcessor.Top;
iStartingRight := FWordProcessor.Left + FWordProcessor.Width;
iStartingBottom := FWordProcessor.Top+ + FWordProcessor.Height;
End;
Square(WorkingLeft(iX, iY), WorkingTop(iX, iY), WorkingRight(iX, iY), WorkingBottom(iX, iY));
End;
Function TWPActorDragEdge.Cursor(oInfo : TWPMouseInfo; bDoing : Boolean) : TCursor;
Begin
Case oInfo.EdgeAction Of
eaLeft: Result := crSizeWE;
eaRight: Result := crSizeWE;
eaTop: Result := crSizeNS;
eaBottom: Result := crSizeNS;
eaLeftTop: Result := crSizeNWSE;
eaRightTop: Result := crSizeNESW;
eaLeftBottom: Result := crSizeNESW;
eaRightBottom: Result := crSizeNWSE;
Else
Result := crNoDrop;
End;
End;
Procedure TWPActorDragEdge.Move(iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo);
Begin
Square(FLastLeft, FLastTop, FLastRight, FLastBottom);
Square(WorkingLeft(iX, iY), WorkingTop(iX, iY), WorkingRight(iX, iY), WorkingBottom(iX, iY));
End;
Procedure TWPActorDragEdge.Up(aShift: TShiftState; iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo);
Var
oImage : TWPWorkingDocumentImagePiece;
Begin
Square(FLastLeft, FLastTop, FLastRight, FLastBottom);
If FButton Is TWPWorkingDocumentImagePiece Then
Begin
FWordProcessor.PrimaryRange.MoveTo(TWPWorkingDocumentImagePiece(FButton).Metrics.Position, false);
FWordProcessor.PrimaryRange.SelectTo(TWPWorkingDocumentImagePiece(FButton).Metrics.Position+1, false);
oImage := TWPWorkingDocumentImagePiece(FButton.Clone);
Try
oImage.Width := WorkingRight(iX, iY) - WorkingLeft(iX, iY);
oImage.Height := WorkingBottom(iX, iY) - WorkingTop(iX, iY);
FWordProcessor.PrimaryRange.SetImageProperties(oImage);
Finally
oImage.Free;
End;
End
Else if FButton is TWPWorkingAnnotationList Then
Begin
FWordProcessor.Settings.AnnotationWidth := FWordProcessor.Width - iX;
End;
End;
Type
TWPActorButton = Class (TWPMouseActor)
Private
FButton : TFslObject;
FDouble : Boolean;
Public
destructor Destroy; Override;
Function Cursor(oInfo : TWPMouseInfo; bDoing : Boolean) : TCursor; Overload; Override;
Procedure Down(aShift: TShiftState; iX, iY: Integer; oInfo : TWPMouseInfo; bDouble : Boolean); Overload; Override;
Procedure Move(iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo); Overload; Override;
Procedure Up(aShift: TShiftState; iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo); Overload; Override;
End;
Destructor TWPActorButton.Destroy;
Begin
FButton.Free;
Inherited;
End;
Procedure TWPActorButton.Down(aShift: TShiftState; iX, iY: Integer; oInfo : TWPMouseInfo; bDouble : Boolean);
Begin
FButton := oInfo.Subject.Link;
FDouble := bDouble;
If (FWordProcessor.Renderer.CurrentButton <> oInfo.Subject) Then
Begin
FWordProcessor.Renderer.CurrentButton := oInfo.Subject.Link;
FWordProcessor.DoPaint;
End;
End;
Function TWPActorButton.Cursor(oInfo : TWPMouseInfo; bDoing : Boolean) : TCursor;
Begin
Result := crArrow;
End;
Procedure TWPActorButton.Move(iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo);
Begin
If (oInfo.Subject <> FButton) Or FDouble Or FWordProcessor.NoUserResponse and not FWordProcessor.Settings.ReadOnly Then
FWordProcessor.ApplyCursorState(crNoDrop, True)
Else
FWordProcessor.ApplyCursorState(crArrow, True);
End;
Procedure TWPActorButton.Up(aShift: TShiftState; iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo);
Begin
// we armour against everything disappearing - like if the document is reloaded under us in response
Link;
Try
If (oInfo.Subject = FButton) And Not FDouble Then
FWordProcessor.DoButton(FWordProcessor.FRenderer.GetScreenRectForOffset(oInfo.Offset), oInfo.Subject, oInfo.Offset);
If Assigned(FWordProcessor) Then
Begin
FWordProcessor.Renderer.CurrentButton := Nil;
FWordProcessor.DoPaint;
End;
Finally
Unlink;
End;
End;
Type
TWPActorHotspot = Class (TWPMouseActor)
Private
FHotspot : TWPHotspot;
FSubject : TFslObject;
FDouble : Boolean;
Public
destructor Destroy; Override;
Function Cursor(oInfo : TWPMouseInfo; bDoing : Boolean) : TCursor; Overload; Override;
Procedure Down(aShift: TShiftState; iX, iY: Integer; oInfo : TWPMouseInfo; bDouble : Boolean); Overload; Override;
Procedure Move(iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo); Overload; Override;
Procedure Up(aShift: TShiftState; iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo); Overload; Override;
End;
Destructor TWPActorHotspot.Destroy;
Begin
If Assigned(FWordProcessor) And (FWordProcessor.Renderer.CurrentHotspot <> Nil) Then
FWordProcessor.Renderer.CurrentHotspot := Nil;
FHotspot.Free;
FSubject.Free;
Inherited;
End;
Procedure TWPActorHotspot.Down(aShift: TShiftState; iX, iY: Integer; oInfo : TWPMouseInfo; bDouble : Boolean);
Begin
FHotspot := oInfo.Hotspot.Link;
FSubject := oInfo.Subject.Link;
FDouble := bDouble;
If (FWordProcessor.Renderer.CurrentHotspot <> oInfo.Hotspot) Then
Begin
FWordProcessor.Renderer.CurrentHotspot := oInfo.Hotspot.Link;
FWordProcessor.DoPaint;
End;
End;
Function TWPActorHotspot.Cursor(oInfo : TWPMouseInfo; bDoing : Boolean) : TCursor;
Begin
Result := crHandPoint;
End;
Procedure TWPActorHotspot.Move(iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo);
Begin
If (oInfo.Hotspot <> FHotspot) Or (oInfo.Subject <> FSubject) Or FDouble Then
FWordProcessor.ApplyCursorState(crNoDrop, True)
Else
FWordProcessor.ApplyCursorState(crHandPoint, True);
End;
Procedure TWPActorHotspot.Up(aShift: TShiftState; iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo);
Begin
If (oInfo.Hotspot = FHotspot) And (oInfo.Subject = FSubject) And Not FDouble Then
Begin
if oInfo.Hotspot <> nil Then
Begin
Link;
Try
FWordProcessor.DoHotspot(FWordProcessor.FRenderer.GetScreenRectForOffset(oInfo.Offset), oInfo.Hotspot, mbLeft);
Finally
Unlink;
End;
End
Else
Begin
FWordProcessor.DoAnnotationClick(oInfo.Subject as TWPWorkingAnnotation);
End;
End;
If Assigned(FWordProcessor) Then
Begin
Assert(Invariants('Up', FWordProcessor, TWordProcessor, 'FWordProcessor'));
FWordProcessor.Renderer.CurrentHotspot := Nil;
FWordProcessor.DoPaint;
End;
End;
Type
TWPActorHover = Class (TWPMouseActor)
Private
FHotspot : TWPHotspot;
FSubject : TFslObject;
FBox : TRect;
Public
destructor Destroy; Override;
Function RequiresDown : Boolean; Overload; Override;
Function Cursor(oInfo : TWPMouseInfo; bDoing : Boolean) : TCursor; Overload; Override;
Procedure Down(aShift: TShiftState; iX, iY: Integer; oInfo : TWPMouseInfo; bDouble : Boolean); Overload; Override;
Procedure Move(iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo); Overload; Override;
Procedure Close(oNewActor : TWPMouseActor); Overload; Override;
End;
Destructor TWPActorHover.Destroy;
Begin
FHotspot.Free;
FSubject.Free;
Inherited;
End;
Function TWPActorHover.RequiresDown : Boolean;
Begin
Result := False;
End;
Procedure TWPActorHover.Down(aShift: TShiftState; iX, iY: Integer; oInfo : TWPMouseInfo; bDouble : Boolean);
Begin
FHotspot := oInfo.Hotspot.Link;
FSubject := oInfo.Subject.Link;
FWordProcessor.Renderer.CurrentHotspot := oInfo.Hotspot.Link;
FWordProcessor.DoPaint;
FBox := FWordProcessor.FRenderer.GetScreenRectForOffset(oInfo.Offset);
FWordProcessor.DoHotspotHover(True, FBox, oInfo.Hotspot);
End;
Function TWPActorHover.Cursor(oInfo : TWPMouseInfo; bDoing : Boolean) : TCursor;
Begin
Result := crHandPoint;
End;
Procedure TWPActorHover.Move(iX, iY: Integer; bOk : Boolean; oInfo : TWPMouseInfo);
Begin
If oInfo.Hotspot <> FHotspot Then
Begin
If oInfo.Hotspot <> Nil Then
Begin
FWordProcessor.DoHotspotHover(False, FBox, FHotspot);
FHotspot.Free;
FHotspot := Nil;
FWordProcessor.Renderer.CurrentHotspot := oInfo.Hotspot.Link;
FHotspot := oInfo.Hotspot.Link;
FWordProcessor.DoPaint;
FBox := FWordProcessor.FRenderer.GetScreenRectForOffset(oInfo.Offset);
FWordProcessor.DoHotspotHover(True, FBox, oInfo.Hotspot);
End
Else
Begin
Close(Nil);
FWordProcessor.FMouseActor := Nil;
Free;
End;
End
Else if oInfo.Subject <> FSubject Then
Begin
Close(Nil);
FWordProcessor.FMouseActor := Nil;
Free;
End;
End;
Procedure TWPActorHover.Close(oNewActor : TWPMouseActor);
Begin
FWordProcessor.DoHotspotHover(False, FBox, FHotspot);
If (oNewActor = Nil) Or Not (oNewActor Is TWPActorHotspot) Then
Begin
FWordProcessor.Renderer.CurrentHotspot := Nil;
FWordProcessor.DoPaint;
End;
End;
Constructor TWordProcessor.Create(oOwner: TComponent);
Begin
Inherited Create(oOwner);
{$IFDEF UNICODE}
FTouch := TWPTouchManager.create(self);
{$ENDIF}
FMacro := TWPMacro.Create;
FSettings := TWPSettings.Create;
FCheckor := TWordProcessorCheckor.Create;
FTranslator := TWPDocumentTranslator.Create;
FCursorOutside := False;
FInspectors := TWPInspectorList.Create;
FInspectors.OwnsObjects := False;
FRangeManager := TWPRangeManager.Create;
FOperator := TWPOperator.Create;
FOperator.OnDo := FRangeManager.RangeDo;
FOperator.OnUndo := FRangeManager.RangeUndo;
FOperator.OnRedo := FRangeManager.RangeRedo;
FOperator.Settings := FSettings.Link;
FOperator.OnInsertContent := ActorInsertContent;
FOperator.OnDeleteContent := ActorDeleteContent;
FRenderer := TWPScreenRenderer.Create;
FRenderer.Settings := FSettings.Link;
FRenderer.Working := False;
FRenderer.Operator := FOperator.Link;
FRenderer.OnError := HandleError;
FDocumentHandler := TWordProcessorDocumentHandler.Create(Self);
FDocumentHandler.Settings := Settings.Link;
FFontsAllowed := TFslStringList.Create;
FRenderer.OnSetDocumentHeight := LayoutDocumentHeightChange;
FCursorDetails := TWordProcessCursorDetails.Create;
TabStop := True;
FConfiguredStyles := TWPStyles.Create;
FPopup := TWPPopupMenu.Create(Self);
FObservers := TWPObservers.Create;
Color := clWhite;
Constraints.MinHeight := 30;
Constraints.MinWidth := 50;
FDropBMP := TDropBMPTarget.Create(Self);
FDropBMP.Register(Self);
FDropBMP.OnDrop := BMPDrop;
FDropBMP.Dragtypes := [dtCopy];
FDropBMP.GetDataOnEnter := False;
FPlaybackManager := Nil;
FSettings.OnChange := SettingsChange;
FPropertyServer := TWPPropertyServer.Create;
FPropertyServer.Owner := Self;
FPrimaryRange := ProduceRange;
FDocumentHandler.OnLoadImage := FPrimaryRange.DefaultLoadImage;
FOperator.MasterRangeId := PrimaryRange.Id;
FRenderer.Selection := PrimaryRange.Selection.Link;
Clear;
FTimer := TUixTimer.Create(Self);
FTimer.Interval := 500;
FTimer.Enabled := True;
FTimer.OnTimer := Timer;
End;
function TWordProcessor.CreateTouchMenu: TUixPanel;
begin
if FTouchMenu <> nil then
begin
FTouchMenu.Free;
FTouchMenu := nil;
end;
FTouchMenu := TUixPanel.Create(self);
FTouchMenu.Parent := self;
FTouchMenu.Top := -1;
FTouchMenu.BringToFront;
FTouchMenu.Height := 100;
FTouchMenu.Width := 100;
FTouchMenu.Color := clWhite;
FTouchMenu.ParentColor := false;
FTouchMenu.BevelInnerRaised;
FtouchMenu.BevelOuterLowered;
{$IFDEF UNICODE}
FTouchMenu.ParentBackground := false;
{$ENDIF}
FTouchMenu.Transparent := false;
FTouchMenu.Show;
FTouchMenu.SetFocus;
result := FTouchmenu;
end;
Destructor TWordProcessor.Destroy;
Begin
If (FPaginator <> Nil) Then
Begin
FPaginator.Stop;
FPaginator.Wait;
FPaginator.Free;
End;
FMacro.Free;
ConsumeRange(PrimaryRange);
FPrimaryRange := Nil;
FRangeManager.Free;
If Assigned(FMouseActor) Then
FMouseActor.Disconnect;
FMouseActor.Free;
FPropertyServer.Free;
FPrinter.Free;
FPageLayoutController.Free;
Try
// NOTE: TWinControlProxy.DestroyWnd may raise EWPException.create('Failed to Unregister '+ Parent.name);
FDropBMP.UnregisterAll;
Except
// NOTE: suppressing is bad, but allowing an exception out of a destructor is worse [CH2011-11-28]
End;
FDropBMP.Free;
FExistingSearch.Free;
FExistingReplace.Free;
FSpeller.Free;
FObservers.Free;
FPopup.Free;
FTimer.Free;
FCursorDetails.Free;
FRenderer.Free;
FDocument.Free;
FConfiguredStyles.Free;
FWorkingStyles.Free;
FOperator.Free;
FFontsAllowed.Free;
FPlaybackManager.Free;
FDocumentHandler.Free;
FDefaultFieldDefinition.Free;
FTranslator.Free;
FCheckor.Free;
FSettings.Free;
FInspectors.Free;
{$IFDEF UNICODE}
FTouch.Free;
{$ENDIF}
Inherited;
End;
Procedure TWordProcessor.CreateWnd;
Begin
Inherited;
DragAcceptFiles(handle, True);
SettingsChange(WPSETTINGS_PROPERTIES_ALL);
End;
Function TWordProcessor.ProduceRange : TWPVisualRange;
Var
oRange : TWPVisualRange;
Begin
CheckNotInMacro;
oRange := TWPVisualRange.Create;
Try
oRange.Owner := Self;
oRange.Document := FDocument.Link;
oRange.Operator_ := FOperator.Link;
oRange.Renderer := FRenderer.Link;
If oRange.HasDocument Then
oRange.GoHome(False);
oRange.OnContentChange := ActorContentChange;
oRange.OnSelectionChange := ActorSelectionChange;
ConfigureRange(oRange);
FRangeManager.Add(oRange);
Result := oRange; // no link: the function result is not owned
Finally
oRange.Free;
End;
End;
Procedure TWordProcessor.ConfigureRange(oRange : TWPRange);
Begin
End;
Procedure TWordProcessor.ConsumeRange(oRange : TWPRange);
Begin
// cut off from the infrastructure - prevent use when inappropriate
oRange.CutOff;
FRangeManager.Remove(oRange);
End;
Function TWordProcessor.MakeMouseActor(aAction : TWPMouseAction; iOffset : Integer) : TWPMouseActor;
Begin
If (aAction = msSelect) And PrimaryRange.Selection.HasSelection And PrimaryRange.Selection.InSelection(iOffset) And (canCut In PrimaryRange.Capabilities) And Not NoUserResponse Then
aAction := msDragBlock;
Case aAction Of
msNull : Result := TWPActorNull.Create(Self);
msSelect : Result := TWPActorSelect.Create(Self);
msDragBlock : Result := TWPActorDragBlock.Create(Self);
msDragEdge : Result := TWPActorDragEdge.Create(Self);
msButton : Result := TWPActorButton.Create(Self);
msHotspot : Result := TWPActorHotspot.Create(Self);
msImageTool :
Case ImageTool Of
itSelect : Result := TWPActorSelect.Create(Self);
itLine : Result := TWPActorDrawLine.Create(Self);
itRectangle : Result := TWPActorDrawRectangle.Create(Self);
itCircle :
Begin
Result := TWPActorDrawRectangle.Create(Self);
TWPActorDrawRectangle(Result).FCircle := True;
End;
itMark : Result := TWPActorDrawMark.Create(Self);
itZoom : Result := TWPActorDrawZoom.Create(Self);
Else
Result := Nil;
End
Else
// action is Free or Hover. This is probably an error, but we will let it pass
Result := Nil;
End;
End;
function shiftToString(shiftstate: TShiftState):String;
begin
result := '';
if ssshift in shiftstate then
result := result + ':shift';
if ssalt in shiftstate then
result := result + ':alt';
if ssctrl in shiftstate then
result := result + ':ctrl';
if ssleft in shiftstate then
result := result + ':left';
if ssright in shiftstate then
result := result + ':right';
if ssmiddle in shiftstate then
result := result + ':middle';
if ssdouble in shiftstate then
result := result + ':double';
{$IFDEF UNICODE}
if sstouch in shiftstate then
result := result + ':touch';
if sspen in shiftstate then
result := result + ':pen';
if sscommand in shiftstate then
result := result + ':command';
{$ENDIF}
result := copy(result, 2, $ff);
end;
Function TWordProcessor.WantDragSelection(x, y : integer; var oActor : TWPMouseActor) : Boolean;
begin
result := false;
if FCursorDetails.FMode <> cdSelect then
result := false
else if (x >= FCursorDetails.FSelStartLeft - 35) and (x <= FCursorDetails.FSelStartLeft+5) and
(y >= FCursorDetails.FSelStartTop - 5) and (y <= FCursorDetails.FSelStartTop+ 35) then
begin
result := true;
oActor := TWPActorDragSelection.create(self);
TWPActorDragSelection(oActor).Start := true;
TWPActorDragSelection(oActor).XOffset := 30;
TWPActorDragSelection(oActor).YOffset := -30;
end
else if (x >= FCursorDetails.FSelEndLeft-5) and (x <= FCursorDetails.FSelEndLeft + 35) and
(y >= FCursorDetails.FSelEndTop-5) and (y <= FCursorDetails.FSelEndTop + 35) then
begin
result := true;
oActor := TWPActorDragSelection.create(self);
TWPActorDragSelection(oActor).Start := false;
TWPActorDragSelection(oActor).XOffset := 30;
TWPActorDragSelection(oActor).YOffset := 30;
end
end;
Procedure TWordProcessor.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
Var
oInfo : TWPMouseInfo;
oActor : TWPMouseActor;
bDbl : Boolean;
Begin
Inherited;
// writeln('mouse down: '+inttostr(x)+','+inttostr(y)+' ('+shiftToString(shift)+')');
If FCodeCompletionListBox <> nil Then
Begin
FCodeCompletionListBox.Free;
FCodeCompletionListBox := nil;
End;
if FTouchMenu <> nil then
Begin
FTouchMenu.Free;
FTouchMenu := nil;
End;
If Settings.Interactive And Not FMacro.Recording Then
Begin
If (Button = mbLeft) Then
Begin
bDbl := FJustDoubleClicked;
FJustDoubleClicked := False;
oInfo := TWPMouseInfo.Create;
Try
if Not WantDragSelection(X, Y + FScrollPoint.Y, oActor) then
If Not FRenderer.getMouseInfoForPoint(X, Y + FScrollPoint.Y, oInfo) Then
oActor := Nil
Else
oActor := MakeMouseActor(oInfo.ProposedAction, oInfo.Offset);
Hint := oInfo.HintText;
ShowHint := Hint <> '';
Try
// let the existing hover action decide how to terminate depending on the new value
If (FMouseActor <> Nil) Then
Begin
FMouseActor.Close(oActor);
FMouseActor.Free;
FMouseActor := Nil;
End;
If (oActor <> Nil) Then
Begin
ApplyCursorState(oActor.Cursor(oInfo, True), True);
oActor.Down(Shift, X, Y + FScrollPoint.Y, oInfo, bDbl);
End
Else
Begin
ApplyCursorState(crArrow, False);
SoundBeepExclamation;
End;
FMouseActor := oActor.Link;
SetCapture(Handle);
SetFocus;
Finally
oActor.Free;
End;
Finally
oInfo.Free;
End;
End
Else If (FMouseActor <> Nil) Then
Begin
FMouseActor.Close(Nil);
FMouseActor.Free;
FMouseActor := Nil;
End;
End;
End;
Procedure TWordProcessor.MouseMove(Shift: TShiftState; X, Y: Integer);
Var
oInfo : TWPMouseInfo;
oActor : TWPMouseActor;
bOk : Boolean;
Begin
Inherited;
// writeln('mouse move: '+inttostr(x)+','+inttostr(y)+' ('+shiftToString(shift)+')');
If Settings.Interactive And Not FMacro.Recording Then
Begin
If Not (ssLeft In Shift) And Assigned(FMouseActor) And FMouseActor.RequiresDown Then
Begin
FMouseActor.Free;
FMouseActor := Nil;
End;
oInfo := TWPMouseInfo.Create;
Try
bOk := FRenderer.getMouseInfoForPoint(X, Y + FScrollPoint.Y, oInfo);
Hint := oInfo.HintText;
ShowHint := Hint <> '';
If (FMouseActor <> Nil) Then
FMouseActor.Move(x,Y + FScrollPoint.Y, bOk, oInfo)
Else If Not bOk Then
ApplyCursorState(crArrow, False)
Else If (oInfo.ProposedAction = msHotspot) Then
Begin
FMouseActor := TWPActorHover.Create(Self);
ApplyCursorState(FMouseActor.Cursor(oInfo, False), False);
FMouseActor.Down(Shift, X, Y + FScrollPoint.Y, oInfo, False);
End
Else
Begin
oActor := MakeMouseActor(oInfo.ProposedAction, oInfo.Offset);
Try
ApplyCursorState(oActor.Cursor(oInfo, False), False);
Finally
oActor.Free;
End;
End
Finally
oInfo.Free;
End;
End;
End;
Procedure TWordProcessor.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
Var
oInfo : TWPMouseInfo;
bOk : Boolean;
bContinue : Boolean;
Begin
Inherited;
// writeln('mouse up: '+inttostr(x)+','+inttostr(y)+' ('+shiftToString(shift)+')');
If Settings.Interactive And Not FMacro.Recording Then
Begin
oInfo := TWPMouseInfo.Create;
Try
bOk := FRenderer.getMouseInfoForPoint(X, Y + FScrollPoint.Y, oInfo);
bContinue := True;
If bOk And (Button = mbRight) Then
Begin
If Not NoUserResponse Then
Begin
If Not PrimaryRange.Selection.HasSelection Or Not PrimaryRange.Selection.InSelection(oInfo.Offset) Then
PrimaryRange.MoveTo(oInfo.Offset);
If (oInfo.Hotspot = Nil) Or Not DoHotspot(Renderer.GetScreenRectForOffset(oInfo.Offset), oInfo.hotSpot, mbRight) Then
ShowPopup(X, Y, oInfo);
End;
End
Else If Assigned(FMouseActor) Then
Begin
FMouseActor.Up(Shift, X, Y + FScrollPoint.Y, bOk, oInfo);
bContinue := Assigned(FMouseActor) And Assigned(FMouseActor.FWordProcessor);
If bContinue Then
FMouseActor.Free;
FMouseActor := Nil;
End;
ReleaseCapture;
If bContinue Then
MouseMove(Shift, X, Y);
Cursor := Screen.Cursor;
Screen.Cursor := crDefault;
Finally
oInfo.Free;
End;
End;
End;
Procedure TWordProcessor.DblClick;
Begin
If Settings.Interactive And Not FMacro.Recording Then
FJustDoubleClicked := True;
End;
Procedure TWordProcessor.Paint;
Var
aMouse : TPoint;
oInfo : TWPMouseInfo;
oActor : TWPMouseActor;
Begin
Inherited;
FRenderer.Working := True;
DragMarkCleared;
If FCursorDetails.Showing Then
ToggleCursor;
DoPaint;
If FCursorDetails.Showing Then
ToggleCursor;
If FResetMouseCursor And GetCursorPos(Windows.TPoint(aMouse)) Then
Begin
FResetMouseCursor := False;
aMouse := TPoint(ScreenToClient(Windows.TPoint(aMouse)));
If RectHit(TRect(BoundsRect), aMouse) Then
Begin
oInfo := TWPMouseInfo.Create;
Try
If FRenderer.GetMouseInfoForPoint(aMouse.x, aMouse.y+FScrollPoint.Y, oInfo) Then
Begin
oActor := MakeMouseActor(oInfo.ProposedAction, oInfo.Offset);
Try
ApplyCursorState(oActor.Cursor(oInfo, False), False);
Finally
oActor.Free;
End;
End;
Finally
oInfo.Free;
End;
End;
End;
End;
Procedure TWordProcessor.ActorSelectionChange(oSender: TObject);
Begin
If FCursorDetails.Showing Then
ToggleCursor;
FCursorDetails.Clear;
CheckOffsetVisible(PrimaryRange.Selection.SelActive);
if FDocument.AllAnnotations.Select(Selection.WorkingSelStart, Selection.WorkingSelEnd) Then
FRenderer.PaintAnnotations(false);
If FRenderer.Working Then
Begin
If Assigned(parent) Then
Paint;
ToggleCursor;
End;
NotifyObservers;
If Assigned(FOnSelectionChanged) Then
FOnSelectionChanged(Self);
End;
Function TWordProcessor.CheckOffsetVisible(iIndex : Integer) : Boolean;
Var
iTop, iLeft, iHeight : Integer;
aColour : TColour;
Begin
Result := False;
If FRenderer.GetPointForOffset(iIndex, iLeft, iTop, iHeight, aColour) Then
Begin
If (iTop - FScrollPoint.Y <= 0) Then
Begin
FScrollPoint.Y := FScrollPoint.Y + (iTop - FScrollPoint.Y);
ScrollbarPositionChanged;
End
Else If (iTop + iHeight - FScrollPoint.Y > ClientHeight) Then
Begin
FScrollPoint.Y := FScrollPoint.Y + (iTop + iHeight - FScrollPoint.Y) - ClientHeight;
ScrollbarPositionChanged;
End;
Result := True;
End;
End;
Procedure TWordProcessor.DragMarkCleared;
Begin
FCursorDetails.Fmode := cdBlink;
End;
Procedure TWordProcessor.ClearDragMark;
Begin
FCursorDetails.Fmode := cdBlink;
{$IFNDEF NO_VCL_CANVAS_LOCK}
Canvas.Lock;
Try
{$ENDIF}
Canvas.Pen.Style := psSolid;
Canvas.Pen.Color := Renderer.Canvas.ApplyContrast(FCursorDetails.FDragMarkColour);
Canvas.Pen.Width := 2;
Canvas.MoveTo(FCursorDetails.FDragMarkLeft, FCursorDetails.FDragMarkTop - FScrollPoint.Y);
Canvas.LineTo(FCursorDetails.FDragMarkLeft, FCursorDetails.FDragMarkTop + FCursorDetails.FDragMarkHeight - FScrollPoint.Y - 1);
{$IFNDEF NO_VCL_CANVAS_LOCK}
Finally
Canvas.Unlock;
End;
{$ENDIF}
End;
Procedure TWordProcessor.DrawDragMark(iOffset : Integer);
Begin
If FRenderer.GetPointForOffset(iOffset, FCursorDetails.FDragMarkLeft, FCursorDetails.FDragMarkTop, FCursorDetails.FDragMarkHeight, FCursorDetails.FDragMarkColour) Then
Begin
FCursorDetails.FMode := cdDrag;
{$IFNDEF NO_VCL_CANVAS_LOCK}
Canvas.Lock;
Try
{$ENDIF}
Canvas.Pen.Style := psSolid;
Canvas.Pen.Color := Renderer.Canvas.ApplyContrast(clDkGray);
Canvas.Pen.Width := 2;
Canvas.MoveTo(FCursorDetails.FDragMarkLeft, FCursorDetails.FDragMarkTop - FScrollPoint.Y);
Canvas.LineTo(FCursorDetails.FDragMarkLeft, FCursorDetails.FDragMarkTop + FCursorDetails.FDragMarkHeight - FScrollPoint.Y - 1);
{$IFNDEF NO_VCL_CANVAS_LOCK}
Finally
Canvas.Unlock;
End;
{$ENDIF}
End;
End;
Procedure TWordProcessor.DrawCursor(bShow : Boolean);
Begin
{$IFNDEF NO_VCL_CANVAS_LOCK}
Canvas.Lock;
Try
{$ENDIF}
if InTouchMode and (FCursorDetails.FMode <> cdBlink) then
begin
Canvas.Pen.Style := psSolid;
Canvas.Pen.Color := Renderer.Canvas.ApplyContrast(clBlack);
Canvas.Pen.Width := 1;
Canvas.Brush.Style := bsSolid;
if FCursorDetails.FMode = cdDrag then
Canvas.Brush.Color := clGreen
else if FCursorDetails.FSelHot = shStart then
Canvas.Brush.Color := clRed
else
Canvas.Brush.Color := clBlue;
Canvas.Ellipse(
FCursorDetails.FSelStartLeft-20, FCursorDetails.FSelStartTop - FScrollPoint.Y,
FCursorDetails.FSelStartLeft, FCursorDetails.FSelStartTop - FScrollPoint.Y+20);
if FCursorDetails.FMode = cdDrag then
Canvas.Brush.Color := clGreen
else if FCursorDetails.FSelHot = shEnd then
Canvas.Brush.Color := clRed
else
Canvas.Brush.Color := clBlue;
Canvas.Ellipse(
FCursorDetails.FSelEndLeft, FCursorDetails.FSelEndTop - FScrollPoint.Y,
FCursorDetails.FSelEndLeft+20, FCursorDetails.FSelEndTop - FScrollPoint.Y+20);
end
else
begin
If Settings.Interactive And Settings.Blinking And bShow Then
Begin
Canvas.Pen.Style := psSolid;
Canvas.Pen.Color := Renderer.Canvas.ApplyContrast(clBlack);
End
Else
Begin
Canvas.Pen.Style := psSolid;
Canvas.Pen.Color := Renderer.Canvas.ApplyContrast(FCursorDetails.FColour);
End;
Canvas.Pen.Width := 2;
Canvas.MoveTo(FCursorDetails.Left, FCursorDetails.Top - FScrollPoint.Y);
Canvas.LineTo(FCursorDetails.Left, FCursorDetails.Top + FCursorDetails.Height - FScrollPoint.Y - 1);
end;
{$IFNDEF NO_VCL_CANVAS_LOCK}
Finally
Canvas.Unlock;
End;
{$ENDIF}
End;
Procedure TWordProcessor.ToggleCursor;
Var
iTop, iLeft, iHeight : Integer;
aColour : TColour;
Begin
If Settings.Blinking And Settings.Interactive And FCursorDetails.Showing Then
Begin
FCursorDetails.Showing := False;
DrawCursor(False);
End
Else If Settings.Blinking And Settings.Interactive And (Focused Or ShowCursorAlways) Then
begin
if not PrimaryRange.Selection.HasSelection Then
Begin
If FCursorDetails.Height = 0 Then
Begin
FRenderer.GetPointForOffset(PrimaryRange.Selection.Cursor, iLeft, iTop, iHeight, aColour);
FCursorDetails.Left := iLeft;
FCursorDetails.Top := iTop;
FCursorDetails.Height := iHeight;
FCursorDetails.Colour := aColour;
End;
FCursorDetails.Showing := True;
DrawCursor(FCursorDetails.Showing);
end
else if InTouchMode then
begin
If (FCursorDetails.Height = 0) Then
Begin
if FCursorDetails.FMode = cdBlink then
FCursorDetails.FMode := cdSelect;
FRenderer.GetPointForOffset(PrimaryRange.Selection.SelEnd, iLeft, iTop, iHeight, aColour);
FCursorDetails.FSelEndLeft := iLeft;
FCursorDetails.FSelEndTop := iTop + iHeight;
FCursorDetails.FSelEndHeight := iHeight;
FCursorDetails.FSelEndColour := aColour;
FRenderer.GetPointForOffset(PrimaryRange.Selection.SelStart, iLeft, iTop, iHeight, aColour);
FCursorDetails.FSelStartLeft := iLeft;
FCursorDetails.FSelStartTop := iTop + iHeight;
FCursorDetails.FSelStartHeight := iHeight;
FCursorDetails.FSelStartColour := aColour;
End;
FCursorDetails.Showing := True;
DrawCursor(FCursorDetails.Showing);
End;
End;
End;
Procedure TWordProcessor.Resize;
Var
iNewWidth : Integer;
iWidth : Integer;
bWorking : Boolean;
Begin
Inherited;
FOperator.MarkChange;
// actor's page height should always adjust to height change
If (PrimaryRange.PageHeight <> (Height - 2 * Settings.VerticalMargin)) Then
PrimaryRange.PageHeight := Height - 2 * Settings.VerticalMargin;
If Width <> 0 Then
Begin
iWidth := IntegerMin(ActualWidth, MAX_INTERNAL_WIDTH);
// Check if scroll bar will be visible
If (Settings.ShowVerticalScrollbar Or Settings.Interactive) And ((MinimumRecommendedHeight) > ClientHeight) Then
iNewWidth := IntegerMax(100, iWidth - VerticalScrollBarWidth)
Else
iNewWidth := IntegerMax(100, iWidth);
If FWorkingWidthLimit > 0 Then
iNewWidth := IntegerMin(iNewWidth, FWorkingWidthLimit);
If (iNewWidth > 0) And (FRenderer.Width <> iNewWidth) Then
Begin
ToggleCursor;
bWorking := FRenderer.Working;
Try
FRenderer.Working := False;
FRenderer.Width := iNewWidth;
FRenderer.NominalPageHeight := Height - 2 * Settings.VerticalMargin;
Finally
FRenderer.Working := bWorking;
End;
Repaint;
FCursorDetails.Clear;
End;
End;
If FRenderer.Working Then
Begin
UpdateScrollBar;
If Settings.Interactive And Settings.Blinking Then
DrawCursor(True);
End;
End;
Procedure TWordProcessor.SetWorkingWidthLimit(Const Value: Integer);
Begin
Assert(Condition((Value = 0) Or (Value > 100), 'SetWorkingWidthLimit', 'Value must be > 100'));
FWorkingWidthLimit := Value;
Resize;
End;
Function TWordProcessor.GetConfiguredStyles : TWPStyles;
Begin
Assert(FCheckor.Invariants('GetStyles', FConfiguredStyles, TWPStyles, 'Styles'));
Result := FConfiguredStyles;
End;
Procedure TWordProcessor.SetConfiguredStyles(Const Value: TWPStyles);
Begin
Assert(Value <> Nil, 'Cannot set nil styles');
FConfiguredStyles.Free;
FConfiguredStyles := Value;
End;
Function TWordProcessor.HasWorkingStyles : Boolean;
Begin
Result := Assigned(FWorkingStyles);
End;
Function TWordProcessor.GetWorkingStyles : TWPStyles;
Begin
Assert(FCheckor.Invariants('GetStyles', FWorkingStyles, TWPStyles, 'Styles'));
Result := FWorkingStyles;
End;
Procedure TWordProcessor.SetWorkingStyles(Const Value: TWPStyles);
Begin
Assert(Value <> Nil, 'Cannot set nil styles');
FWorkingStyles.Free;
FWorkingStyles := Value;
End;
Procedure TWordProcessor.Timer(oSender: TObject);
Var
iSystem : Cardinal;
iLast : Cardinal;
hnd : HWnd;
Begin
if Renderer.AltKeyDown and (GetAsyncKeyState(vkAlt) = 0) then
begin
Renderer.AltKeyDown := false;
Invalidate;
end;
if (FOperator.LastChange > 0) and (FOperator.LastChange < UniversalDateTime - (FASTDRAW_REDRAW * DATETIME_SECOND_ONE)) then
begin
FOperator.LastChange := 0;
FRenderer.PaintAll := true;
FRenderer.Update;
DoPaint;
end;
if FCodeCompletionListBox <> nil Then
Begin
hnd := GetFocus;
if (hnd <> self.Handle) And (hnd <> FCodeCompletionListBox.Handle) Then
begin
FCodeCompletionListBox.Free;
FCodeCompletionListBox := nil;
end;
End;
if FTouchMenu <> nil then
Begin
hnd := GetFocus;
if (hnd <> self.Handle) And (hnd <> FTouchMenu.Handle) Then
begin
FTouchMenu.Free;
FTouchMenu := nil;
end;
End;
ToggleCursor;
CheckLostHotspot;
If (Assigned(FPaginator)) Then
Begin
FinishPagination;
End
Else
Begin
iSystem := GetTickCount;
iLast := FOperator.LastAction;
If (iSystem < iLast) Then
// check for clock wrap
FOperator.LastAction := iSystem
Else If (iSystem - iLast > PAGINATION_DELAY) Then
Paginate;
End;
If FMacro.LastError And (FMacro.LastErrorTime < now - 2 * DATETIME_SECOND_ONE) Then
Begin
FMacro.LastError := False;
Invalidate;
End;
End;
Function ShiftState(aShift : TShiftState) : TWPShiftStates;
Begin
Result := [];
If ssShift In aShift Then
include(Result, wssShift);
If ssAlt In aShift Then
include(Result, wssAlt);
If ssCtrl In aShift Then
include(Result, wssCtrl);
If ssLeft In aShift Then
include(Result, wssLeft);
If ssRight In aShift Then
include(Result, wssRight);
If ssMiddle In aShift Then
include(Result, wssMiddle);
If ssDouble In aShift Then
include(Result, wssDouble);
End;
Procedure TWordProcessor.KeyUp(Var Key: Word; Shift: TShiftState);
var
value : integer;
Begin
Inherited;
if Key = vkAlt then
begin
Renderer.AltKeyDown := false;
Invalidate;
end;
If (Key = vkAlt) And (Shift = []) And (FAltNum <> '') Then
Begin
If StringIsInteger32(FAltNum) Then
begin
value := StringToInteger32(FAltNum);
if (value >= 32) and (value <= 255) then
PrimaryRange.Insert(chr(value));
end;
FAltNum := '';
End;
End;
Procedure TWordProcessor.KeyDown(Var Key: Word; Shift: TShiftState);
Begin
Inherited;
If FCodeCompletionListBox <> nil Then
Begin
FCodeCompletionListBox.Free;
FCodeCompletionListBox := nil;
End;
if FTouchMenu <> nil then
Begin
FTouchMenu.Free;
FTouchMenu := nil;
End;
if Key = vkAlt then
begin
Renderer.AltKeyDown := true;
Invalidate;
End;
If Settings.Interactive Then
Begin
If ProcessKey(Key, ShiftState(Shift)) Then
Key := 0;
End;
End;
Function TWordProcessor.CheckForHotspot(ch : Char) : Boolean;
Var
oHotspot : TWPHotspot;
oItem : TWPMapObject;
oOwner : TWPWorkingDocumentPiece;
Begin
oHotspot := Document.GetHotspot(ch, oItem, oOwner);
Result := Assigned(oHotspot);
If Result Then
Begin
If (oOwner <> Nil) And (oOwner Is TWPWorkingDocumentFieldStartPiece) And (oHotspot.URL = '') Then
Begin
PrimaryRange.MoveTo(oOwner.Metrics.Position+1);
While Not (oOwner.Next Is TWPWorkingDocumentFieldStopPiece) Do
Begin
PrimaryRange.SelectTo(oOwner.Next.Next.Metrics.Position);
oOwner := oOwner.Next;
End;
End
Else If (oOwner <> Nil) And (oOwner Is TWPWorkingDocumentSectionStartPiece) And (oHotspot.URL = '') Then
Begin
PrimaryRange.MoveTo(oOwner.Metrics.Position+1);
While (oOwner.Next Is TWPWorkingDocumentSectionStartPiece) Do
Begin
PrimaryRange.MoveTo(oOwner.Next.Metrics.Position+1);
oOwner := oOwner.Next;
End;
End
Else If Assigned(oItem) Then
DoHotspot(oItem.asRect, oHotspot, mbLeft)
Else
DoHotspot(Renderer.asRect, oHotspot, mbLeft);
End;
End;
Procedure StringToFile(Const sname, sContent : String);
Var
oFile : TFslFile;
aBytes : TBytes;
Begin
oFile := TFslFile.Create(sName, fmCreate);
Try
aBytes := TEncoding.UTF8.GetBytes(sContent);
oFile.Write(aBytes[0], Length(aBytes));
Finally
oFile.Free;
End;
End;
Function TWordProcessor.IsAnnotationKey(iKey: Word; Const aShift: TWPShiftStates) : Boolean;
var
i : integer;
Begin
result := false;
if canInsertAnnotation in PrimaryRange.Capabilities Then
For i := 0 to Settings.AnnotationDefinitions.Count - 1 Do
Begin
if Settings.AnnotationDefinitions[i].IsInsertKey(iKey, aShift, SelectedText) Then
Begin
result := true;
InsertAnnotation(Settings.AnnotationDefinitions[i]);
End;
End;
End;
Function TWordProcessor.ProcessKey(iKey: Word; Const aShift: TWPShiftStates) : Boolean;
Var
sError : String;
bRecord : Boolean;
Begin
If NoUserResponse Then
Begin
Result := False;
Exit;
End;
Try
bRecord := True;
Result := True;
if Selection.HasSelection and IsAnnotationKey(iKey, aShift) Then
Begin
result := true;
Exit;
End;
If aShift = [wssAlt] Then
Begin
Case iKey Of
vkAlt: FAltNum := '';
vkA..vkZ: Result := CheckForHotspot(chr(ord('0') + (iKey - vk0)));
vk0..vk9: Result := CheckForHotspot(chr(ord('A') + (iKey - vkA)));
vkNum0 : FAltNum := FAltNum + '0';
vkNum1 : FAltNum := FAltNum + '1';
vkNum2 : FAltNum := FAltNum + '2';
vkNum3 : FAltNum := FAltNum + '3';
vkNum4 : FAltNum := FAltNum + '4';
vkNum5 : FAltNum := FAltNum + '5';
vkNum6 : FAltNum := FAltNum + '6';
vkNum7 : FAltNum := FAltNum + '7';
vkNum8 : FAltNum := FAltNum + '8';
vkNum9 : FAltNum := FAltNum + '9';
vkBack : PrimaryRange.Undo;
vkMinus : result := PrimaryRange.ListStartDecrement;
vkEquals : result := PrimaryRange.ListStartReset;
Else
Result := False;
End;
End
Else If (aShift = [wssAlt, wssShift]) Then
Begin
Case iKey Of
vkBack : PrimaryRange.Redo;
vkEquals : result := PrimaryRange.ListStartIncrement;
Else
Result := False;
End;
End
Else If ((aShift = []) Or (aShift = [wssShift])) Then
Case iKey Of
vkHome : PrimaryRange.GoLineStart(wssShift In aShift);
vkEnd : PrimaryRange.GoLineEnd(wssShift In aShift);
vkLeft : PrimaryRange.Left(wssShift In aShift);
vkRight : PrimaryRange.Right(wssShift In aShift);
vkBack : PrimaryRange.DeleteLeft;
vkDel : If (aShift = []) Then
PrimaryRange.DeleteRight
Else
PrimaryRange.Cut;
vkSpace : PrimaryRange.Insert(' ');
vkInsert : If (aShift = []) Then
Result := False
Else If Not PrimaryRange.Paste(sError) Then
DialogError(sError, 0);
vkEnter : If Not PrimaryRange.Selection.HasSelection And PrimaryRange.HasCurrentFieldStart Then
CommitField
Else If aShift = [wssShift] Then
PrimaryRange.LineBreak
Else
PrimaryRange.NewParagraph;
vkPageUp : PrimaryRange.PageUp(wssShift In aShift);
vkPageDown : PrimaryRange.PageDown(wssShift In aShift);
vkUp : PrimaryRange.LineUp(wssShift In aShift);
vkDown : PrimaryRange.LineDown(wssShift In aShift);
vkTab :
Begin
If wssShift In aShift Then
Begin
CheckNotInMacro;
If Not PrimaryRange.PreviousField Then
If HasPreviousControl() Then
SetFocusedControl(PreviousControl)
Else
Result := False;
End
Else
Begin
If Not PrimaryRange.NextField Then
If HasNextControl() Then
SetFocusedControl(NextControl)
Else
Result := False;
End;
End;
vk0..vk9:
Begin
If wssShift In aShift Then
Begin
Case iKey Of
vk0:PrimaryRange.Insert(')');
vk1:PrimaryRange.Insert('!');
vk2:PrimaryRange.Insert('@');
vk3:PrimaryRange.Insert('#');
vk4:PrimaryRange.Insert('$');
vk5:PrimaryRange.Insert('%');
vk6:PrimaryRange.Insert('^');
vk7:PrimaryRange.Insert('&');
vk8:PrimaryRange.Insert('*');
vk9:PrimaryRange.Insert('(');
End;
End
Else
Begin
PrimaryRange.Insert(chr(ord('0')+(iKey - vk0)));
End;
End;
vkNum0..vkNum9 : PrimaryRange.Insert(chr(ord('0')+(iKey - vkNum0)));
vkSEMICOLON : If wssShift In aShift Then PrimaryRange.Insert(':') Else PrimaryRange.Insert(';');
vkCOMMA : If wssShift In aShift Then PrimaryRange.Insert('<') Else PrimaryRange.Insert(',');
vkFULLSTOP : If wssShift In aShift Then PrimaryRange.Insert('>') Else PrimaryRange.Insert('.');
vkSLASH : If wssShift In aShift Then PrimaryRange.Insert('?') Else PrimaryRange.Insert('/');
vkSINGLEQUOTE: If wssShift In aShift Then PrimaryRange.Insert('"') Else PrimaryRange.Insert('''');
vkSQUARELEFT : If wssShift In aShift Then PrimaryRange.Insert('{') Else PrimaryRange.Insert('[');
vkSQUARERIGHT: If wssShift In aShift Then PrimaryRange.Insert('}') Else PrimaryRange.Insert(']');
vkBACKSLASH : If wssShift In aShift Then PrimaryRange.Insert('|') Else PrimaryRange.Insert('\');
vkLEFTQUOTE : If wssShift In aShift Then PrimaryRange.Insert('~') Else PrimaryRange.Insert('`');
vkMINUS : If wssShift In aShift Then PrimaryRange.Insert('_') Else PrimaryRange.Insert('-');
vkEQUALS : If wssShift In aShift Then PrimaryRange.Insert('+') Else PrimaryRange.Insert('=');
vkNumDivide : PrimaryRange.Insert('/');
vkNumDecimal : PrimaryRange.Insert('.');
vkNumMultiply : PrimaryRange.Insert('*');
vkNumSubtract : PrimaryRange.Insert('-');
vkNumAdd : PrimaryRange.Insert('+');
vkF3 : If Settings.Search Then
If HasExistingSearch Then PrimaryRange.Search(ExistingSearch) Else SearchDialog
Else
Result := False;
vkF7 : CheckSpelling;
vkContextMenu : InvokePopop;
vkA..vkZ:
Begin
If (wssShift In aShift) <> IsCapitalKeyToggled Then
PrimaryRange.Insert(chr(ord('A') + (iKey - vkA)))
Else
PrimaryRange.Insert(chr(ord('a') + (iKey - vkA)));
End;
Else
Result := False;
End
Else If ((aShift = [wssCtrl]) Or (aShift = [wssCtrl, wssShift])) Then
Begin
Case iKey Of
vkHome : PrimaryRange.GoHome(wssShift In aShift);
vkEnd : PrimaryRange.GoEnd(wssShift In aShift);
vkLEFT : PrimaryRange.LeftWord(wssShift In aShift);
vkRIGHT : PrimaryRange.RightWord(wssShift In aShift);
vkBack : PrimaryRange.DeleteWordLeft;
vkDel : PrimaryRange.DeleteWordRight;
vkF1 : Settings.EditHints := Not Settings.EditHints;
vkEnter : PrimaryRange.InsertPageBreak;
vkEquals :
Begin
If wssShift In aShift Then
PrimaryRange.ApplySuperscript(True)
Else
PrimaryRange.ApplySubscript(True);
End;
vkSpace : CodeCompletePrompt;
vkTab :
Begin
If wssShift In aShift Then
Result := PrimaryRange.PreviousTableCell
Else
Result := PrimaryRange.NextTableCell;
End;
vkInsert :
Begin
If (aShift = [wssCtrl, wssShift]) Then
Result := False
Else
PrimaryRange.Copy;
End;
vkC : PrimaryRange.Copy;
vkA : PrimaryRange.SelectAll;
vkB : PrimaryRange.ApplyBold(Not PrimaryRange.IsBold);
vkE : PrimaryRange.AlignCentre;
vkF :
Begin
If Settings.Search Then
SearchDialog
Else
Result := False;
End;
vkM : InsertSymbol;
vkG : PrimaryRange.InsertColumnRight;
vkH : PrimaryRange.InsertRowBelow;
vkI : PrimaryRange.ApplyItalic(Not PrimaryRange.IsItalic);
vkL : PrimaryRange.AlignLeft;
vkN : result := DoNew;
vkO : result := DoOpen;
vkR : If (aShift = [wssCtrl, wssShift]) Then
Begin
bRecord := False;
ToggleMacro
End
Else
PrimaryRange.AlignRight;
vkP : If (aShift = [wssCtrl, wssShift]) Then
ExecuteMacro
Else
Result := DoPrint;
vkS: If (aShift = [wssCtrl, wssShift]) Then
SnapShot('ctrl-alt-shift-s', false)
Else
Result := DoSave;
vkT : PrimaryRange.ConvertTextToTable;
vkU : PrimaryRange.ApplyUnderline(Not PrimaryRange.IsUnderline);
vkV :
Begin
If Not PrimaryRange.Paste(sError) Then
DialogError(sError, 0);
End;
vkX : PrimaryRange.Cut;
vkY : PrimaryRange.Redo;
vkD :
If wssShift In aShift Then
Begin
SaveImage(SystemTemp + 'image.bmp');
ExecuteOpen(SystemTemp + 'image.bmp');
End
Else
Begin
StringToFile(SystemTemp + 'native.txt', DocumentHandler.AsNative);
ExecuteOpen(SystemTemp + 'native.txt');
End;
vkZ :
Begin
If wssShift In aShift Then
PrimaryRange.Redo
Else
PrimaryRange.Undo;
End;
Else
Result := False;
End
End
else
Begin
Result := False;
End;
If FMacro.Recording And bRecord And Result Then
FMacro.Actions.Add(TWPMacroKeyAction.Create(iKey, aShift));
Except
On e : ELibraryException Do
Begin
SoundBeepAsterisk;
FMacro.LastError := True;
Invalidate;
Result := False;
End;
On e:Exception Do
Raise;
End;
End;
Procedure TWordProcessor.WMGetDlgCode(Var Msg: TWMGetDlgCode);
Begin
Inherited;
Msg.Result := DLGC_WANTARROWS Or DLGC_WANTCHARS Or DLGC_WANTTAB;// Or DLGC_WANTALLKEYS;
End;
Procedure TWordProcessor.ActorContentChange(oSender: TObject);
Begin
FRenderer.ClearPaginations;
FModified := True;
If Assigned(FOnContentChanged) Then
FOnContentChanged(Self);
End;
Procedure TWordProcessor.ShowPopup(iX, iY: Integer; oInfo : TWPMouseInfo);
Var
aPoint : TPoint;
Begin
If Settings.AllowPopup And Not FMacro.Recording Then
Begin
aPoint.x := iX;
aPoint.y := iY;
aPoint := TPoint(ClientToScreen(Windows.TPoint(aPoint)));
FPopup.MouseInfo := oInfo.Link;
FPopup.Popup(aPoint.x, aPoint.y);
End;
End;
procedure TWordProcessor.ShowPopupMenu();
var
oInfo : TWPMouseInfo;
x, y, h : integer;
c : TColour;
bOk : boolean;
begin
if PrimaryRange.Selection.HasSelection then
FRenderer.GetPointForOffset(PrimaryRange.Selection.SelEnd, x, y, h, c)
else
FRenderer.GetPointForOffset(PrimaryRange.Selection.Cursor, x, y, h, c);
oInfo := TWPMouseInfo.Create;
try
bOk := FRenderer.getMouseInfoForPoint(X, Y + FScrollPoint.Y, oInfo);
if bOk then
begin
if not NoUserResponse then
Begin
if not PrimaryRange.Selection.HasSelection or not PrimaryRange.Selection.InSelection(oInfo.Offset) then
PrimaryRange.MoveTo(oInfo.Offset);
if (oInfo.Hotspot = nil) or not DoHotspot(Renderer.GetScreenRectForOffset(oInfo.Offset), oInfo.hotSpot, mbRight) then
ShowPopup(X, Y, oInfo);
end;
end
finally
oInfo.Free;
end;
end;
Procedure TWordProcessor.Clear;
Begin
CheckNotInMacro;
FDocumentHandler.NewDocument;
// Can't assert empty, as the application may override the definition of a cleared document.
End;
// TODO: use a dynamic range to clear everything
Function TWordProcessor.ClearFormatting : Boolean;
Begin
CheckNotInMacro;
Result := PrimaryRange.ClearFormatting;
End;
procedure TWordProcessor.CloseTouchMenu(var Message: TMessage);
begin
FTouchMenu.Free;
FTouchMenu := nil;
end;
procedure TWordProcessor.WantCloseTouchMenu;
begin
PostMessage(Handle, UM_CLOSE_TOUCH, 0, 0);
end;
Procedure TWordProcessor.NotifyObservers;
Begin
FObservers.Notify(Self);
End;
Procedure TWordProcessor.UnregisterObserver(oObject: TObject);
Begin
FObservers.Unregister(oObject);
End;
Procedure TWordProcessor.RegisterObserver(oObject: TObject; aEvent: TNotifyEvent);
Begin
FObservers.Register(oObject, aEvent);
End;
Function TWordProcessor.GetFontsAllowed : TFslStringList;
Begin
Assert(FCheckor.Invariants('GetFontsAllowed', FFontsAllowed, TFslStringList, 'FontsAllowed'));
Result := FFontsAllowed;
End;
Procedure TWordProcessor.SetFontsAllowed(Const Value: TFslStringList);
Begin
FFontsAllowed.Free;
FFontsAllowed := Value;
End;
Procedure TWordProcessor.LayoutDocumentHeightChange(oSender: TObject);
Begin
UpdateScrollBar;
End;
Procedure TWordProcessor.UpdateScrollBar;
Var
aScrollInfo : TScrollInfo;
iRequiredRendererHeight : Integer;
Begin
iRequiredRendererHeight := MinimumRecommendedHeight;
If (Settings.ShowVerticalScrollbar Or Settings.Interactive) And (iRequiredRendererHeight > ClientHeight) Then
Begin
ScrollbarPositionChanged;
FillChar(aScrollInfo, SizeOf(aScrollInfo), 0);
aScrollInfo.cbSize := SizeOf(aScrollInfo);
aScrollInfo.nPage := IntegerMax(0, ClientHeight - (2 * Settings.VerticalMargin));
aScrollInfo.nMin := 0;
aScrollInfo.nMax := iRequiredRendererHeight;
aScrollInfo.nPos := FScrollPoint.Y;
aScrollInfo.fMask := SIF_ALL;
If Settings.ShowVerticalScrollbar Then
aScrollInfo.fMask := aScrollInfo.fMask Or SIF_DISABLENOSCROLL;
If Not Settings.Interactive Then
aScrollInfo.nPage := aScrollInfo.nMax + 1; // disable the scrollbar if one is shown, or remove it if not
FScrollBarShowing := True;
ShowScrollBar(Handle, SB_VERT, True);
SetScrollInfo(Handle, SB_VERT, aScrollInfo, True);
End
Else
Begin
FScrollPoint.Y := 0;
ScrollbarPositionChanged;
SetScrollPos(Handle, SB_VERT, FScrollPoint.Y, False);
FScrollBarShowing := False;
ShowScrollbar(Handle, SB_VERT, False);
End;
End;
Function TWordProcessor.DoMouseWheel(aShift: TShiftState; iWheelDelta: Integer; aMousePos: Windows.TPoint): Boolean;
Var
iY : Integer;
Begin
If Settings.Interactive And Not FMacro.Recording And (aShift = []) And (MinimumRecommendedHeight > ClientHeight) Then
Begin
iY := FScrollPoint.Y;
FScrollPoint.Y := FScrollPoint.Y - iWheelDelta;
ScrollbarPositionChanged;
MouseMove(aShift, aMousePos.x, aMousePos.y);
If iY <> FScrollPoint.Y Then
DoPaint;
End;
Result := True;
End;
function TWordProcessor.DoNew: Boolean;
begin
result := assigned(FOnNew);
if result then
FOnNew(self);
end;
function TWordProcessor.DoOpen: Boolean;
begin
result := assigned(FOnOpen);
if result then
FOnOpen(self);
end;
Procedure TWordProcessor.WMVScroll(Var Message : TWMVScroll);
Var
aScroll : TScrollInfo;
iY : Integer;
Begin
iY := FScrollPoint.Y;
FillChar(aScroll, SizeOf(aScroll), 0);
aScroll.cbSize := SizeOf(aScroll);
aScroll.fMask := SIF_TRACKPOS Or SIF_POS;
GetScrollInfo(Handle, SB_VERT, aScroll);
Case Message.ScrollCode Of
SB_LINEDOWN : Inc(FScrollPoint.Y, 16);
SB_LINEUP : Dec(FScrollPoint.Y, 16);
SB_PAGEDOWN : Inc(FScrollPoint.Y, ClientHeight - (2 * Settings.VerticalMargin));
SB_PAGEUP : Dec(FScrollPoint.Y, ClientHeight - (2 * Settings.VerticalMargin));
SB_TOP : FScrollPoint.Y := 0;
SB_BOTTOM : FScrollPoint.Y := (MinimumRecommendedHeight + (2 * Settings.VerticalMargin));
SB_THUMBTRACK : FScrollPoint.Y := aScroll.nTrackPos;
End;
If (iY <> FScrollPoint.Y) Then
Begin
ScrollbarPositionChanged;
DoPaint;
End;
End;
Procedure TWordProcessor.ScrollbarPositionChanged;
Begin
FScrollPoint.Y := IntegerMax(0, IntegerMin(MinimumRecommendedHeight - ClientHeight + (2 * Settings.VerticalMargin), FScrollPoint.Y));
If FCursorDetails.Showing Then
ToggleCursor;
SetScrollPos(Handle, SB_VERT, FScrollPoint.Y, True);
ToggleCursor;
End;
Procedure TWordProcessor.FontDialog;
Var
oDialog : TWPFontDialog;
Begin
CheckNotInMacro;
oDialog := TWPFontDialog.Create(Owner);
Try
oDialog.Font.Assign(PrimaryRange.Font);
oDialog.Readonly := Settings.ReadOnly;
oDialog.FontsAllowed := FFontsAllowed.Link;
oDialog.ConsoleMode := Settings.ConsoleMode;
If oDialog.Execute Then
Begin
PrimaryRange.Font.Assign(oDialog.Font);
PrimaryRange.ApplyFont(oDialog.Font);
End;
Finally
oDialog.Free;
End;
End;
Procedure TWordProcessor.PasteSpecialDialog;
Var
oDialog : TWPPasteSpecialDialog;
sError : String;
Begin
CheckNotInMacro;
oDialog := TWPPasteSpecialDialog.Create(Self);
Try
oDialog.ReadOnly := Settings.ReadOnly;
If oDialog.Execute Then
If Not PrimaryRange.PasteSpecial(oDialog.Format, sError) Then
DialogError(sError);
Finally
oDialog.Free;
End;
End;
Procedure TWordProcessor.ParaDialog;
Var
oDialog : TWPParagraphDialog;
Begin
CheckNotInMacro;
oDialog := TWPParagraphDialog.Create(Owner);
Try
oDialog.ReadOnly := Settings.ReadOnly;
oDialog.Paragraph.Assign(PrimaryRange.Paragraph);
If oDialog.Execute Then
Begin
PrimaryRange.Paragraph.Assign(oDialog.Paragraph);
PrimaryRange.ApplyParagraph(PrimaryRange.Paragraph);
End;
Finally
oDialog.Free;
End;
End;
Procedure TWordProcessor.StyleDialog;
Var
oDialog : TWPStyleDialog;
Begin
CheckNotInMacro;
oDialog := TWPStyleDialog.Create(Owner);
Try
oDialog.ReadOnly := Settings.ReadOnly;
oDialog.Style.Assign(PrimaryRange.WorkingStyle);
If oDialog.Execute Then
PrimaryRange.WorkingStyle.Assign(oDialog.Style);
Finally
oDialog.Free;
End;
End;
Procedure TWordProcessor.ChangeCaseDialog;
Var
oDialog : TWPChangeCaseDialog;
Begin
CheckNotInMacro;
oDialog := TWPChangeCaseDialog.Create(Owner);
Try
If oDialog.Execute Then
Begin
PrimaryRange.ApplyChangeCase(oDialog.ChangeCaseType);
End;
Finally
oDialog.Free;
End;
End;
Procedure TWordProcessor.DragOver(Source: TObject; X, Y: Integer; State: TDragState; Var Accept: Boolean);
Begin
windows.Beep(800,20);
End;
Procedure TWordProcessor.DragDropFiles(Var VMsg: TMessage);
Var
iTotal : Integer;
iLoop : Integer;
a: Array [0..500] Of Char;
aPoint : TPoint;
oInfo : TWPMouseInfo;
Begin
Inherited;
CheckNotInMacro;
oInfo := TWPMouseInfo.Create;
Try
If Settings.Interactive And DragQueryPoint(VMsg.wParam, Windows.TPoint(aPoint)) And
FRenderer.GetMouseInfoForPoint(IntegerMin(IntegerMax(aPoint.x, 0), ActualWidth - Settings.HorizontalMargin * 2), aPoint.y + FScrollPoint.Y, oInfo) Then
Begin
iTotal := DragQueryFile(VMsg.wParam, $FFFFFFFF, Nil, 0);
For iLoop := 0 To iTotal - 1 Do
Begin
DragQueryFile(VMsg.wParam, iLoop, a, 500);
PrimaryRange.DropFile(oInfo.Offset, a);
End;
End;
Finally
oInfo.Free;
End;
End;
Procedure TWordProcessor.InsertImageDialog;
Var
oDialog : TOpenDialog;
Begin
CheckNotInMacro;
oDialog := TOpenDialog.Create(Self);
Try
oDialog.Filter := 'All Images (*.jpeg;*.jpg;*.gif;*.png;*.ico;*.bmp)|*.jpeg;*.jpg;*.gif;*.png;*.ico;*.bmp|JPEG Images (*.jpeg;*.jpg)|*.jpeg;*.jpg|PNG Images (*.png)|*.png|GIF Images (*.gif)|*.gif|Bitmaps (*.bmp)|*.bmp|All Files|*.*';
oDialog.Title := 'Open Image';
If oDialog.Execute Then
Begin
PrimaryRange.InsertImage(oDialog.FileName);
End;
Finally
oDialog.Free;
End;
End;
Procedure TWordProcessor.InsertPDFDialog;
Var
oDialog : TOpenDialog;
Begin
CheckNotInMacro;
oDialog := TOpenDialog.Create(Self);
Try
oDialog.Filter := 'PDF Documents (*.pdf)|*.pdf|All Files|*.*';
oDialog.Title := 'Open PDF Document';
If oDialog.Execute Then
Begin
PrimaryRange.InsertPDF(oDialog.FileName);
End;
Finally
oDialog.Free;
End;
End;
Procedure TWordProcessor.ImagePropertiesDialog;
Var
oImage : TWPWorkingDocumentImagePiece;
oDialog : TWPImageDialog;
Begin
CheckNotInMacro;
If Not PrimaryRange.HasCurrentImage Then
Error('ImagePropertiesDialog', 'No Image is in scope');
oImage := PrimaryRange.CurrentImage;
oDialog := TWPImageDialog.Create(Owner);
Try
oDialog.Image := oImage.Clone;
oDialog.ReadOnly := Settings.ReadOnly;
If oDialog.Execute Then
Begin
PrimaryRange.SetImageProperties( oDialog.Image);
End;
Finally
oDialog.Free;
End;
End;
Procedure TWordProcessor.ImageMapsDialog;
Var
oImage : TWPWorkingDocumentImagePiece;
oDialog : TWPImageMapDialog;
Begin
CheckNotInMacro;
If Not PrimaryRange.HasCurrentImage Then
Error('ImageMapsDialog', 'No Image is in scope');
oImage := PrimaryRange.CurrentImage;
oDialog := TWPImageMapDialog.Create(Owner);
Try
oDialog.Image := oImage.Clone;
oDialog.ReadOnly := Settings.ReadOnly;
If oDialog.Execute Then
Begin
PrimaryRange.SetImageProperties(oDialog.Image);
End;
Finally
oDialog.Free;
End;
End;
Procedure TWordProcessor.InsertCompletionItem(oItem : TWPCompletionItem);
Var
bOk : Boolean;
sMessage : String;
oStream : TFslStream;
aFormat : TWPFormat;
Begin
If oItem.Content <> '' Then
Begin
If PrimaryRange.HasCurrentFieldStart Then
Begin
PrimaryRange.SelectField(False);
bOk := PrimaryRange.Insert(oItem.Content);
End
Else
bOk := PrimaryRange.ReplaceCurrentWord(oItem.Content, sMessage);
End
Else
Begin
aFormat := wpfNative;
oStream := FetchTemplateContent(oItem.Id, oItem.Code, aFormat);
Try
bOk := PrimaryRange.ReplaceCurrentWord(oStream, aFormat, sMessage)
Finally
oStream.Free;
End;
End;
If Not bOk Then
Begin
FRenderer.Update;
DialogError(sMessage);
End Else If PrimaryRange.HasCurrentFieldStart Then
CommitField;
SetFocusedControl(self);
End;
Procedure TWordProcessor.CodeCompletePromptList(oList : TWPCompletionItems);
Begin
CheckNotInMacro;
If oList.Count = 1 Then
InsertCompletionItem(oList[0])
Else
Begin
If CheckOffsetVisible(PrimaryRange.Selection.Cursor) Then
Paint;
FCodeCompletionListBox := TWPCodeCompletionListBox.Create(self);
FCodeCompletionListBox.Parent := Self;
FCodeCompletionListBox.Left := CursorEndPos.X;
FCodeCompletionListBox.Top := CursorEndPos.Y;
FCodeCompletionListBox.List := oList.Link;
FCodeCompletionListBox.OnInsert := InsertCompletionItem;
FCodeCompletionListBox.SetFocus;
If FCodeCompletionListBox.Top + FCodeCompletionListBox.Height > ClientHeight Then
FCodeCompletionListBox.Top := Max(ClientHeight - FCodeCompletionListBox.Height, 0);
If FCodeCompletionListBox.Height > ClientHeight Then
FCodeCompletionListBox.Height := ClientHeight;
End;
End;
Procedure TWordProcessor.CodeCompletePrompt;
Var
sText : String;
oList : TWPCompletionItems;
bHandled : Boolean;
Begin
CheckNotInMacro;
If Not Settings.ReadOnly Then
Begin
bHandled := False;
If PrimaryRange.HasCurrentFieldStart And PrimaryRange.CurrentFieldStart.HasDefinitionProvider Then
bHandled := PrimaryRange.CurrentFieldStart.DefinitionProvider.CodeComplete(PrimaryRange.CurrentFieldStart.DocField, PrimaryRange.CurrentFieldContent);
If Not bHandled Then
Begin
oList := TWPCompletionItems.Create;
Try
If Assigned(FOnCodeCompletion) And PrimaryRange.CursorInWord(sText) And FOnCodeCompletion(Self, sText, oList) And (oList.Count > 0) Then
CodeCompletePromptList(oList)
Else
SoundBeepExclamation;
Finally
oList.Free;
End;
End;
End;
End;
Procedure TWordProcessor.DoPaint;
Var
iActualWidth : Integer;
iWidth : Integer;
aColor : TColour;
aRect : TRect;
Begin
{$IFNDEF NO_VCL_CANVAS_LOCK}
Canvas.Lock;
Try
{$ENDIF}
Settings.Background := Color;
iActualWidth := ActualWidth;
If FScrollBarShowing Then
iActualWidth := iActualWidth - SCROLLBAR_WIDTH;
If Not FNonVisibleMode Then
Begin
iWidth := FRenderer.PaintControl(Canvas.Handle, Height, iActualWidth, FScrollPoint.Y);
aColor := Renderer.Canvas.ApplyContrast(RandomColour(Color, False));
Canvas.Brush.Color := aColor;
Canvas.Brush.Style := bsSolid;
If (iWidth < iActualWidth) Then
Begin
aRect.Left := iWidth;
aRect.Top := 0;
aRect.Right := iActualWidth;
aRect.Bottom := Height;
Canvas.FillRect(aRect);
End;
If FRenderer.Height - FScrollPoint.Y < Height Then
Begin
aRect.Left := 0;
aRect.Top := FRenderer.Height - FScrollPoint.Y;
aRect.Right := iActualWidth;
aRect.Bottom := Height;
Canvas.FillRect(aRect);
End;
If FMacro.LastError Then
Ring(HTML_COLOUR_VALUES[hcCrimson])
Else If FMacro.State = msRecording Then
Ring(HTML_COLOUR_VALUES[hcForestgreen])
Else If FMacro.State = msPlaying Then
Ring(HTML_COLOUR_VALUES[hcDodgerblue])
Else If Renderer.AltKeyDown Then
Ring(HTML_COLOUR_VALUES[hcLinen]);
End;
{$IFNDEF NO_VCL_CANVAS_LOCK}
Finally
Canvas.Unlock;
End;
{$ENDIF}
End;
function TWordProcessor.DoPrint: Boolean;
begin
result := assigned(FOnPrint);
if result then
FOnPrint(self);
end;
Procedure TWordProcessor.InsertSymbol;
Var
oDialog : TWPSymbolDialog;
Begin
CheckNotInMacro;
If Not (canInsert In PrimaryRange.Capabilities) Then
Error('InsertSymbol', 'Cannot insert here');
oDialog := TWPSymbolDialog.Create(Owner);
Try
// oDialog.Filter := FSymbolFilter;
// oDialog.Block := FSymbolBlock;
oDialog.SpecifiedFont := PrimaryRange.Font.Link;
ODialog.FontsAllowed.Assign(FFontsAllowed);
oDIalog.AllowSpecialSymbols := Settings.AllowSpecialSymbols;
If oDialog.Execute Then
Begin
// FSymbolFilter := oDialog.Filter;
// FSymbolBlock := oDialog.Block;
PrimaryRange.InsertSymbol(oDialog.InsertChar, oDialog.DrawnFontName);
End;
Finally
oDialog.Free;
End;
End;
Function TWordProcessor.GetSpeller : TWPSpeller;
Begin
Assert(FCheckor.Invariants('GetSpeller', FSpeller, TWPSpeller, 'Speller'));
Result := FSpeller;
End;
Procedure TWordProcessor.SetSpeller(Const Value: TWPSpeller);
Begin
FSpeller.Free;
FSpeller := Value;
FOperator.Speller := FSpeller.Link;
FSpeller.Settings := FSettings.Link;
FSpeller.AllowedWords := FDocument.AllowedWords.Link;
End;
Function TWordProcessor.HasVoicePlayback : Boolean;
Begin
Result := HasPlaybackManager And FVoiceActive;
End;
Procedure TWordProcessor.VoicePlayback;
Begin
If HasVoicePlayback Then
PlaybackManager.Playback;
End;
Procedure TWordProcessor.VoiceStop;
Begin
If HasVoicePlayback Then
PlaybackManager.Stop;
End;
Procedure TWordProcessor.VoiceAccelerate;
Begin
If HasVoicePlayback Then
PlaybackManager.Accelerate;
End;
Procedure TWordProcessor.VoiceDecelerate;
Begin
If HasVoicePlayback Then
PlaybackManager.Deccelerate;
End;
Procedure StringAppendStart(Var VStr: String; Var VLen: Integer);
Begin
VLen := Length(VStr);
SetLength(VStr, Length(VStr) + 4096);
End;
Procedure StringAppend(Var VStr: String; AStrToAdd: String; Var VLen: Integer; ADivChar: Char = #0);
//procedure StringAppend(var s: String; ns: String; var len: Integer; divchar: Char = #0);
Var
LOffset: Integer;
Begin
If (AStrToAdd = '') And (ADivChar = #0) Then
Begin
Exit;
End;
If (ADivChar <> #0) And (VLen <> 0) Then
LOffset := 1
Else
LOffset := 0;
If VLen + LOffset + Length(AStrToAdd) > Length(VStr) Then
SetLength(VStr, Length(VStr) + Integermax(4096, LOffset + Length(AStrToAdd)));
If LOffset = 1 Then
VStr[VLen + 1] := ADivChar;
move(AStrToAdd[1], VStr[VLen + LOffset + 1], Length(AStrToAdd));
Inc(VLen, LOffset + Length(AStrToAdd));
End;
Procedure StringAppendClose(Var VStr: String; ALen: Integer);
Begin
SetLength(VStr, ALen);
End;
Procedure TWordProcessor.VoiceGetTextChanges(Var iTextStart, iTextLength : Integer; Var sText : String; Var iVisibleStart, iVisibleLength : Integer);
Var
iLen : Integer;
oPiece : TWPWorkingDocumentPiece;
Begin
iTextStart := 0;
iTextLength := FDocument.VoiceCharCount;
sText := '';
StringAppendStart(sText, iLen);
oPiece := FDocument.Pieces.First;
While Assigned(oPiece) Do
Begin
StringAppend(sText, oPiece.VoiceText, iLen);
If oPiece.HasNext Then
oPiece := oPiece.Next
Else
oPiece := Nil;
End;
StringAppendClose(sText, iLen);
iVisibleStart := iTextStart;
iVisibleLength := iTextLength;
End;
Procedure TWordProcessor.VoiceMakeTextChanges(iTextStart, iTextLength : Integer; sText : String);
Var
sWord : String;
bSplit : Boolean;
Begin
CheckNotInMacro;
VoiceSelect(iTextStart, iTextLength, False);
PrimaryRange.DeleteSelection;
While sText <> '' Do
Begin
bSplit := StringSplit(sText, #13#10, sWord, sText);
If sWord <> '' Then
PrimaryRange.Insert(sWord);
If bSplit Then
PrimaryRange.NewParagraph;
End;
End;
Procedure TWordProcessor.VoiceGetSelectionRange(Var iSelectionStart, iSelectionLength : Integer);
Begin
If PrimaryRange.Selection.HasSelection Then
Begin
iSelectionStart := FDocument.NormalPositionToVoicePosition(PrimaryRange.Selection.SelStart);
iSelectionLength := FDocument.NormalPositionToVoicePosition(PrimaryRange.Selection.SelEnd) - iSelectionStart;
End
Else
Begin
iSelectionStart := FDocument.NormalPositionToVoicePosition(PrimaryRange.Selection.Cursor);
iSelectionLength := 0;
End;
End;
Procedure TWordProcessor.VoiceSelect(iTextStart, iTextLength : Integer; bDraw : Boolean);
Begin
PrimaryRange.MoveTo(FDocument.VoicePositionToNormalPosition(iTextStart), bDraw);
If iTextLength <> 0 Then
PrimaryRange.SelectTo(FDocument.VoicePositionToNormalPosition(iTextStart + iTextLength), bDraw);
End;
Procedure TWordProcessor.VoiceSetSelectionRange(iSelectionStart, iSelectionLength : Integer);
Begin
VoiceSelect(iSelectionStart, iSelectionLength, True);
End;
Function TWordProcessor.GetCursorEndPos: TPoint;
Var
iCursor : Integer;
iLeft, iTop, iHeight : Integer;
aColour : TColour;
Begin
If FCursorDetails.FShowing Then
Begin
Result.x := FCursorDetails.Left;
Result.y := FCursorDetails.Top + FCursorDetails.Height;
End
Else
Begin
If PrimaryRange.Selection.HasSelection Then
iCursor := PrimaryRange.Selection.SelEnd
Else
iCursor := PrimaryRange.Selection.Cursor;
If FRenderer.GetPointForOffset(iCursor, iLeft, iTop, iHeight, aColour) Then
Begin
Result.x := iLeft;
Result.y := iTop + iHeight - FScrollPoint.Y;
End
Else
Begin
Result.x := FCursorDetails.Left;
Result.y := FCursorDetails.Top + FCursorDetails.Height - FScrollPoint.Y;
End;
End;
End;
Procedure TWordProcessor.InvokePopop;
Begin
If Settings.Interactive And (FCursorDetails.Left <> 0) Then
ShowPopup(FCursorDetails.FLeft, FCursorDetails.FTop + FCursorDetails.FHeight, Nil);
End;
Procedure TWordProcessor.InsertTableDialog;
Var
oDialog : TWPInsertTableDialog;
Begin
CheckNotInMacro;
oDialog := TWPInsertTableDialog.Create(Self);
Try
If oDialog.Execute Then
Begin
PrimaryRange.InsertTable(oDialog.Rows, oDialog.Columns);
End;
Finally
oDialog.Free;
End;
End;
Procedure TWordProcessor.TablePropertiesDialog;
Var
oDialog : TWPTablePropertiesDialog;
Begin
CheckNotInMacro;
If Not (PrimaryRange.HasCurrentTableStart Or PrimaryRange.HasSelectedTable) Then
Error('TablePropertiesDialog', 'No Table is in scope');
oDialog := TWPTablePropertiesDialog.Create(Owner);
Try
oDialog.SetRange(PrimaryRange);
oDialog.ReadOnly := Settings.ReadOnly;
If oDialog.Execute Then
Begin
{ TODO: Macro
MacroRecord(TWPMacroTableProperties.Create(oDialog.Table.Clone));
MacroRecord(TWPMacroTableRowProperties.Create(oDialog.TableRow.Clone));
}
PrimaryRange.SetTableProperties(oDialog.Table, oDialog.Row, oDialog.Cell);
End;
Finally
oDialog.Free;
End;
End;
Procedure TWordProcessor.LinePropertiesDialog;
Var
oBreak : TWPWorkingDocumentBreakPiece;
oDialog : TWPLineDialog;
Begin
CheckNotInMacro;
If Not PrimaryRange.HasCurrentLine Then
Error('RowPropertiesDialog', 'No Table Row is in scope');
oBreak := PrimaryRange.CurrentLine;
oDialog := TWPLineDialog.Create(Owner);
Try
oDialog.Line := oBreak.Clone;
oDialog.ReadOnly := Settings.ReadOnly;
If oDialog.Execute Then
Begin
PrimaryRange.SetLineProperties(oDialog.Line);
End;
Finally
oDialog.Free;
End;
End;
Procedure TWordProcessor.VoiceSaveSession(Const sFilename : String);
Begin
If HasPlaybackManager Then
PlaybackManager.SaveSession(sFilename);
End;
Procedure TWordProcessor.VoiceLoadSession(Const sFilename : String);
Begin
If HasPlaybackManager Then
PlaybackManager.LoadSession(sFilename);
End;
Procedure TWordProcessor.VoiceActivate;
Begin
If Not FVoiceActive Then
Begin
FVoiceActive := True;
If HasPlaybackManager Then
PlaybackManager.Open;
End;
End;
Procedure TWordProcessor.VoiceDeactivate;
Begin
If FVoiceActive Then
Begin
If HasPlaybackManager Then
PlaybackManager.Close;
FVoiceActive := False;
End;
End;
Function TWordProcessor.HasPlaybackManager: Boolean;
Begin
Result := Assigned(FPlaybackManager);
End;
Procedure TWPMouseActor.Disconnect;
Begin
FWordProcessor := Nil;
End;
Destructor TWPMouseActor.Destroy;
Begin
Disconnect;
Inherited;
End;
{ TWordProcessCursorDetails }
Procedure TWordProcessCursorDetails.Clear;
Begin
FLeft := 0;
FHeight := 0;
FTop := 0;
End;
Procedure TWordProcessor.WMEraseBkgnd(Var Message: TWmEraseBkgnd);
Begin
// no erase background
Message.Result := 1;
End;
Procedure TWordProcessor.SaveImage(Const sFilename : String);
Begin
FRenderer.SaveImage(sFilename);
End;
Function TWordProcessor.GetExistingSearch : TWPSearchDetails;
Begin
Assert(Condition(HasExistingSearch, 'GetExistingSearch', 'No ExistingSearch'));
Result := FExistingSearch;
End;
Procedure TWordProcessor.SetExistingSearch(Const Value : TWPSearchDetails);
Begin
FExistingSearch.Free;
FExistingSearch := Value;
End;
Function TWordProcessor.HasExistingSearch : Boolean;
Begin
Result := Assigned(FExistingSearch);
End;
function TWordProcessor.HasFields: Boolean;
var
oIter : TWPPieceIterator;
begin
result := False;
oIter := TWPPieceIterator.Create;
try
oIter.Document := Document.Link;
oIter.PieceTypes := [ptFieldStart];
oIter.First;
while oIter.More do
begin
result := true;
oIter.Next;
end;
finally
oIter.Free;
end;
end;
Procedure TWordProcessor.SearchDialog;
Var
oDialog : TWPSearchDialog;
Begin
CheckNotInMacro;
oDialog := TWPSearchDialog.Create(Self);
Try
If HasExistingSearch Then
oDialog.SearchDetails.Assign(ExistingSearch);
oDialog.Range := PrimaryRange.Link;
If oDialog.Execute Then
ExistingSearch := oDialog.SearchDetails.Link;
Finally
oDialog.Free;
End;
End;
Function TWordProcessor.GetExistingReplace : TWPReplaceDetails;
Begin
Assert(Condition(HasExistingReplace, 'GetExistingReplace', 'No ExistingReplace'));
Result := FExistingReplace;
End;
Procedure TWordProcessor.SetExistingReplace(Const Value : TWPReplaceDetails);
Begin
FExistingReplace.Free;
FExistingReplace := Value;
End;
Function TWordProcessor.HasExistingReplace : Boolean;
Begin
Result := Assigned(FExistingReplace);
End;
Procedure TWordProcessor.ReplaceDialog;
Var
oDialog : TWPReplaceDialog;
Begin
CheckNotInMacro;
oDialog := TWPReplaceDialog.Create(Self);
Try
If HasExistingReplace Then
oDialog.ReplaceDetails.Assign(ExistingReplace);
oDialog.Range := PrimaryRange.Link;
If oDialog.Execute Then
ExistingReplace := oDialog.ReplaceDetails.Link;
Finally
oDialog.Free;
End;
End;
procedure TWordProcessor.ReplaceFieldContent(oDocument: TWPWorkingDocument; cursor: integer; oPiece: TWPWorkingDocumentFieldStartPiece; txt: String);
var
iend : integer;
text : TWPWorkingDocumentTextPiece;
begin
inc(cursor);
iend := cursor;
while (iend < oDocument.Pieces.Count) and (oDocument.Pieces[iend].PieceType <> ptFieldStop) do
inc(iend);
if (iEnd = oDocument.Pieces.Count) then
raise EWPException.create('Unable to find end of field');
if (iEnd > cursor) then
oDocument.Pieces.DeleteRange(cursor, iEnd-1);
if (txt <> '') then
begin
text := TWPWorkingDocumentTextPiece.Create;
oDocument.Pieces.insert(cursor, text);
text.ApplyProperties(oPiece);
text.Content := txt;
end;
end;
Procedure TWordProcessor.CheckSpelling;
Begin
CheckNotInMacro;
If Not HasSpeller Then
Error('CheckSpelling', 'There is no spelling support');
Speller.Check(Self, CheckForAllowedWord, AddAllowedWord);
PrimaryRange.ResetSpelling;
Renderer.Valid := False;
Renderer.PaintAll := True;
Renderer.Update;
Invalidate;
End;
Procedure TWordProcessor.SetFocusedControl(oControl : TWinControl);
Var
oParent : TWinControl;
Begin
oParent := GetParentForm(Self);
If Assigned(oParent) Then
TForm(oParent).ActiveControl := oControl;
End;
Function TWordProcessor.GetNextControl : TWinControl;
Begin
Assert(Condition(HasNextControl, 'GetNextControl', 'No Next Control'));
Result := FNextControl;
End;
Function TWordProcessor.GetPreviousControl : TWinControl;
Begin
Assert(Condition(HasPreviousControl, 'GetPreviousControl', 'No Previous Control'));
Result := FPreviousControl;
End;
Function TWordProcessor.HasNextControl : Boolean;
Begin
Result := Assigned(FNextControl);
End;
Function TWordProcessor.HasPreviousControl : Boolean;
Begin
Result := Assigned(FPreviousControl);
End;
Function TWordProcessor.Empty : Boolean;
Begin
Result := Not HasDocument Or FDocument.IsEmpty;
End;
Function TWordProcessor.HasDocument : Boolean;
Begin
Result := Assigned(FDocument);
End;
Function TWordProcessor.HasSpeller : Boolean;
Begin
Result := Assigned(FSpeller);
End;
Procedure TWordProcessor.CheckDocument(oDocument : TWPWorkingDocument);
Begin
{$IFOPT C+}
TWPWorkingDocumentValidator.Validate(oDocument);
{$ENDIF}
If oDocument.Pieces.Count = 0 Then
Error('CheckDocument', 'Document is empty and cannot be loaded into the word processor');
End;
Function TWordProcessor.GetSelectionStart: Integer;
Begin
If PrimaryRange.Selection.HasSelection Then
Result := PrimaryRange.Selection.SelStart
Else
Result := PrimaryRange.Selection.Cursor;
End;
Function TWordProcessor.GetSelectionEnd: Integer;
Begin
If PrimaryRange.Selection.HasSelection Then
Result := PrimaryRange.Selection.SelEnd
Else
Result := PrimaryRange.Selection.Cursor;
End;
Procedure TWordProcessor.BMPDrop(oSender: TObject; aShiftState: TShiftState; aPoint: Windows.TPoint; Var iEffect: LongInt);
Var
oImage : TFslBitmapGraphic;
oInfo : TWPMouseInfo;
Begin
Inherited;
CheckNotInMacro;
oInfo := TWPMouseInfo.Create;
Try
If Settings.Interactive And FRenderer.GetMouseInfoForPoint(IntegerMin(IntegerMax(aPoint.x, 0), ActualWidth - Settings.HorizontalMargin * 2), aPoint.y + FScrollPoint.Y, oInfo) Then
Begin
oImage := TFslBitmapGraphic.Create;
Try
oImage.Handle.Assign(FDropBMP.Bitmap);
PrimaryRange.DropImage(oInfo.Offset, oImage);
Finally
oImage.Free;
End;
End;
Finally
oInfo.Free;
End;
End;
Procedure TWordProcessor.ShowError(Const sTitle, sMessage : String; iDuration : Integer);
Var
oBalloon : TUixBalloon;
aPoint : TPoint;
iCursor : Integer;
iTop, iLeft, iHeight : Integer;
aColour : TColour;
Begin
If PrimaryRange.Selection.HasSelection Then
iCursor := PrimaryRange.Selection.SelEnd
Else
iCursor := PrimaryRange.Selection.Cursor;
If Not FRenderer.GetPointForOffset(iCursor, iLeft, iTop, iHeight, aColour) Then
Begin
iLeft := 0;
iTop := 0;
End;
aPoint.x := IntegerMin(iLeft - Settings.HorizontalMargin, ActualWidth);
aPoint.y := IntegerMin(iTop + iHeight - FScrollPoint.Y, Height);
aPoint := TPoint(ClientToScreen(Windows.TPoint(aPoint)));
oBalloon := TUixBalloon.CreateNew(Self);
oBalloon.Parent := Self;
oBalloon.AbsoluteX := aPoint.x;
oBalloon.AbsoluteY := aPoint.y;
oBalloon.Title := sTitle;
oBalloon.Message := sMessage;
oBalloon.TimeoutDuration := iDuration;
oBalloon.ShowBalloon;
End;
Procedure TWordProcessor.ShowFieldError(Const sNamespace, sName, sTitle, sMessage : String; iDuration : Integer = 3000);
Begin
If PrimaryRange.SelectFieldByName(sNamespace, sName) Then
ShowError(sTitle, sMessage, iDuration)
Else
Error('ShowFieldError', 'Field "'+sNamespace+'::'+sName+'" not found');
End;
Procedure TWordProcessor.ShowSectionError(Const sNamespace, sName, sTitle, sMessage : String; iDuration : Integer = 3000);
Begin
If PrimaryRange.SelectSectionByName(sNamespace, sName) Then
ShowError(sTitle, sMessage, iDuration)
Else
Error('ShowSectionError', 'Section "'+sNamespace+'::'+sName+'" not found');
End;
Function PageNoToString(iPage : Integer) : String;
Begin
If iPage = -1 Then
Result := '?'
Else
Result := IntegerToString(iPage);
End;
Function TWordProcessor.GetSelectionSummary : String;
Var
iRow1 : Integer;
iCol1 : Integer;
iRow2 : Integer;
iCol2 : Integer;
Begin
If PrimaryRange.Selection.HasSelection Then
Begin
If FRenderer.GetLineCol(PrimaryRange.Selection.SelStart, iRow1, iCol1) And FRenderer.GetLineCol(PrimaryRange.Selection.SelEnd, iRow2, iCol2) Then
Begin
If iRow1 = iRow2 Then
Result := 'Line '+IntegerToString(iRow1+1)+' Columns '+IntegerToString(iCol1+1)+' to '+IntegerToString(iCol2+1)
Else
Result := 'Line '+IntegerToString(iRow1+1)+' Column '+IntegerToString(iCol1+1)+' to Line '+IntegerToString(iRow2+1)+' Column '+IntegerToString(iCol2+1)
End
Else
Begin
Result := StringFormat('Error: selection = %d/%d', [PrimaryRange.Selection.SelStart, PrimaryRange.Selection.SelEnd]);
End;
End
Else
Begin
If Not FRenderer.GetLineCol(PrimaryRange.Selection.Cursor, iRow1, iCol1) Then
Begin
If PrimaryRange.Selection.Cursor <= Document.FirstCursorPosition Then
Result := 'Line 1 Column 1' // this is always true, and sometimes we end up here before things are properly laid out, and don't come back
Else
Result := StringFormat('Error: selection = %d', [PrimaryRange.Selection.Cursor]);
End
Else
Begin
Result := 'Line '+IntegerToString(iRow1+1)+' Column '+IntegerToString(iCol1+1);
If Renderer.HasPaginations Then
Result := Result+' (Page '+PageNoToString(Renderer.GetPageForOffset(PrimaryRange.Selection.Cursor))+'/'+IntegerToString(Renderer.PageCount)+')';
End;
End;
End;
Function TWordProcessor.GetPrimaryRange : TWPVisualRange;
Begin
Assert(Condition(Assigned(FPrimaryRange), 'GetPrimaryRange', 'FPrimaryRange must be assigned.'));
Result := FPrimaryRange;
End;
Procedure TWordProcessor.DoHotspotHover(bActive : Boolean; aBox : TRect; oHotspot : TWPHotspot);
Var
oInfo : TWPHotspotInformation;
Begin
If Assigned(FOnHotSpotHover) Then
Begin
aBox.Top := aBox.Top - FScrollPoint.Y;
aBox.Bottom := aBox.Bottom - FScrollPoint.Y;
oInfo := TWPHotspotInformation.Create;
Try
oInfo.Hotspot := oHotspot.Link;
oInfo.Box := aBox;
oinfo.Handled := False;
FOnHotSpotHover(Self, bActive, oInfo);
Finally
oInfo.Free;
End;
End;
End;
Function TWordProcessor.DoHotspot(aBox : TRect; oHotspot : TWPHotspot; Const aMouseButton: TMouseButton) : Boolean;
Var
oInfo : TWPHotspotInformation;
Begin
If Assigned(FOnHotSpot) Then
Begin
aBox.Top := aBox.Top - FScrollPoint.Y;
aBox.Bottom := aBox.Bottom - FScrollPoint.Y;
oInfo := TWPHotspotInformation.Create;
Try
oInfo.Hotspot := oHotspot.Link;
oInfo.Box := aBox;
oinfo.MouseButton := aMouseButton;
oinfo.Handled := True;
FOnHotSpot(Self, oInfo);
Result := oInfo.Handled;
Finally
oInfo.Free;
End;
End
Else
Result := False;
End;
Function TWordProcessor.DocumentHeight : Integer;
Begin
Result := Renderer.Height;
End;
Function TWordProcessor.MinimumRecommendedHeight : Integer;
Begin
Result := DocumentHeight;
End;
// the minimum recommended width is the width of the largest single
// image or word + the margins
Function TWordProcessor.MinimumRecommendedWidth : Integer;
Begin
Result := Document.MinLength + Settings.HorizontalMargin * 2;
End;
Procedure TWordProcessor.Yield;
Begin
Renderer.Yield;
End;
Function TWordProcessor.GetOperator : TWPOperator;
Begin
Assert(FCheckor.Invariants('GetOperator', FOperator, TWPOperator, 'Actor'));
Result := FOperator;
End;
Function TWordProcessor.GetDocument : TWPWorkingDocument;
Begin
Assert(FCheckor.Invariants('GetDocument', FDocument, TWPWorkingDocument, 'Document'));
Result := FDocument;
End;
Function TWordProcessor.GetRenderer : TWPScreenRenderer;
Begin
Assert(FCheckor.Invariants('GetRenderer', FRenderer, TWPScreenRenderer, 'Renderer'));
Result := FRenderer;
End;
Function TWordProcessor.GetSelection : TWPSelection;
Begin
Assert(FCheckor.Invariants('GetSelection', PrimaryRange.Selection, TWPSelection, 'Selection'));
Result := PrimaryRange.Selection;
End;
Function TWordProcessor.GetDocumentHandler : TWPDocumentHandler;
Begin
Assert(FCheckor.Invariants('GetDocumentHandler', FDocumentHandler, TWPDocumentHandler, 'DocumentHandler'));
Result := FDocumentHandler;
End;
Function TWordProcessorCheckor.Invariants(Const sLocation : String; oObject : TFslObject; aClass : TClass; Const sObject : String) : Boolean;
Begin
Result := Inherited Invariants(sLocation, oObject, aClass, sObject);
End;
{ TWordProcessorDocumentHandler }
Constructor TWordProcessorDocumentHandler.Create(oOwner : TWordProcessor);
Begin
Create;
FOwner := oOwner;
End;
Function TWordProcessorDocumentHandler.GetHost : TObject;
Begin
Result := FOwner;
End;
Function TWordProcessorDocumentHandler.GetHostConfiguredStyles : TWPStyles;
Begin
Result := FOwner.ConfiguredStyles;
End;
Function TWordProcessorDocumentHandler.GetHostWorkingStyles : TWPStyles;
Begin
Result := FOwner.WorkingStyles;
End;
Function TWordProcessorDocumentHandler.GetHostDocument : TWPWorkingDocument;
Begin
Result := FOwner.FDocument;
End;
Procedure TWordProcessorDocumentHandler.SetHostDocument(Const oDocument : TWPWorkingDocument; oStyles : TWPStyles);
Begin
FOwner.LoadNewDocument(oDocument, oStyles);
End;
Procedure TWordProcessor.LoadNewDocument(Const oDocument : TWPWorkingDocument; oStyles : TWPStyles);
Begin
CheckDocument(oDocument);
oDocument.FieldDefinitionProviders := FSettings.FieldDefinitions.Link;
oDocument.AnnotationDefinitionProviders := FSettings.AnnotationDefinitions.Link;
oDocument.RegenerateMetrics(true, false);
if BindToFields(oDocument) then
oDocument.RegenerateMetrics(true, false);
If Assigned(FMouseActor) Then
FMouseActor.Disconnect;
FMouseActor.Free;
FMouseActor := Nil;
If Not oStyles.HasDefaultStyle Then
oStyles.UseSystemDefaultStyle;
Renderer.Working := False;
FDocument.Free;
FDocument := Nil;
FScrollPoint.y := 0;
FScrollPoint.x := 0;
FWorkingStyles.Free;
FWorkingStyles := oStyles.Link;
FOperator.Styles := FWorkingStyles.Link;
FRenderer.Styles := FWorkingStyles.Link;
{$IFDEF UNICODE}
if InTouchMode then
FTouch.Load;
{$ENDIF}
FDocument := oDocument.Link;
If FSpeller <> Nil Then
FSpeller.AllowedWords := FDocument.AllowedWords.Link;
ConsumeRange(PrimaryRange);
FPrimaryRange := Nil;
FRangeManager.Clear;
FPrimaryRange := ProduceRange;
FOperator.MasterRangeId := PrimaryRange.Id;
FRenderer.Selection := PrimaryRange.Selection.Link;
FRenderer.Document := FDocument.Link;
FOperator.Document := FDocument.Link;
FRenderer.Clear;
ActorContentChange(Self);
PrimaryRange.GoHome(False);
PrimaryRange.CheckSpelling;
FResetMouseCursor := True;
Renderer.Working := True;
if (assigned(OnDocumentLoaded)) then
OnDocumentLoaded(self);
Invalidate;
End;
Function TWordProcessor.GetSettings : TWPSettings;
Begin
Assert(Condition(Assigned(FSettings), 'GetSettings', 'FSettings must be assigned'));
Result := FSettings;
End;
function TWordProcessor.GetSourceLocation(var line, col: integer): boolean;
var
offset, index : integer;
piece : TWPWorkingDocumentPiece;
begin
if Selection.HasSelection then
result := Document.GetPieceByPosition(Selection.SelStart, piece, offset, index)
else
result := Document.GetPieceByPosition(Selection.Cursor, piece, offset, index);
if result then
begin
line := piece.SourceLine;
col := piece.SourceCol;
result := (line <> 0) and (col <> 0);
end;
end;
Procedure TWordProcessor.SetSettings(Const Value : TWPSettings);
Begin
FSettings.OnChange := Nil;
FSettings.Free;
FSettings := Value.Link;
FSettings.OnChange := SettingsChange;
If Settings.FieldWrappers = wpfpNone Then
Settings.FieldWrappers := wpfpSquareBrackets; // wpfpNone has consequences for cursor routines
SettingsChange(WPSETTINGS_PROPERTIES_ALL);
End;
Procedure TWordProcessor.SettingsChange(Const aProperties : TWPSettingsProperties);
Begin
FRenderer.ChangeSettings;
DoPaint;
PrimaryRange.ChangeState(False);
NotifyObservers;
if Assigned(FOnSettingsChanged) then
FOnSettingsChanged(self);
If Assigned(FOnSelectionChanged) Then
FOnSelectionChanged(Self);
End;
Function TWordProcessor.GetReadOnly : Boolean;
Begin
Result := Settings.ReadOnly;
End;
Procedure TWordProcessor.SetReadOnly(Const Value : Boolean);
Begin
If Value Then
Settings.ModeReadonly
Else
Settings.ModeWordProcessor;
End;
Function TWordProcessor.GetPlaybackManager : TDragonPlaybackManager;
Begin
Assert(FCheckor.Invariants('GetPlaybackManager', FPlaybackManager, TDragonPlaybackManager, 'FPlaybackManager'));
Result := FPlaybackManager;
End;
Procedure TWordProcessor.SetPlaybackManager(Const Value : TDragonPlaybackManager);
Begin
Assert(Not Assigned(Value) Or FCheckor.Invariants('SetPlaybackManager', Value, TDragonPlaybackManager, 'Value'));
FPlaybackManager.Free;
FPlaybackManager := Value;
End;
Function TWordProcessor.HasImageArea(Const sURL : String; Out oImage : TWPWorkingDocumentImagePiece; Out oArea : TWPImageMapArea) : Boolean;
Var
iLoop : Integer;
oWork : TWPWorkingDocumentPiece;
Begin
iLoop := 0;
Result := False;
While Not Result And (iLoop < FDocument.Pieces.Count) Do
Begin
oWork := FDocument.Pieces[iLoop];
If (oWork.PieceType = ptImage) Then
Begin
oImage := TWPWorkingDocumentImagePiece(oWork);
If (oImage.HasImageMap) Then
Begin
oArea := oImage.ImageMap.GetAreaByURL(sURL);
Result := oArea <> Nil;
End;
End;
Inc(iLoop);
End;
End;
Procedure TWordProcessor.SelectImageArea(oImage: TWPWorkingDocumentImagePiece; oArea: TWPImageMapArea);
Begin
CheckNotInMacro;
PrimaryRange.SelectImageArea(oImage, oArea);
End;
Procedure TWordProcessor.ApplyCursorState(Const aCursor : TCursor; bPersist : Boolean);
Begin
If FCursorPersist Or Not FCursorOutside Then
Begin
If (aCursor = crIBeam) And Not Settings.Selecting Then
Screen.Cursor := crArrow
Else
Screen.Cursor := aCursor
End
Else
Begin
Screen.Cursor := crDefault;
End;
FCursorPersist := bPersist;
End;
Function TWordProcessor.GetPageLayoutController : TWPPageLayoutController;
Begin
Result := FPageLayoutController;
End;
Procedure TWordProcessor.SetPageLayoutController(Const Value : TWPPageLayoutController);
Begin
FPageLayoutController.Free;
FPageLayoutController := Value;
End;
Function TWordProcessor.GetPrinter : TFslPrinter;
Begin
Result := FPrinter;
End;
Procedure TWordProcessor.SetPrinter(Const Value : TFslPrinter);
Begin
FPrinter.Free;
FPrinter := Value;
End;
Procedure TWordProcessor.Paginate;
Var
oPaginator : TWPPaginator;
Begin
// can we paginate?
If (Settings.Pagination And (Assigned(FPrinter) And Assigned(FPageLayoutController))) And
// do we need to paginate?
(Not FRenderer.HasPaginations And Not Assigned(FPaginator)) Then
Begin
oPaginator := TWPPaginator.Create;
Try
oPaginator.Operator := FOperator.Link;
oPaginator.Document := FDocument.Clone;
oPaginator.Styles := FWorkingStyles.Link;
oPaginator.Printer := FPrinter.Link;
oPaginator.PageLayoutController := FPageLayoutController.Link;
FPaginator := oPaginator.Link;
oPaginator.Start;
Finally
oPaginator.Free;
End;
End;
End;
Procedure TWordProcessor.FinishPagination;
Begin
If FPaginator.Terminated Then
Begin
If FPaginator.Completed Then
Begin
FRenderer.SetPaginations(FPaginator.Paginations);
If Assigned(FOnSelectionChanged) Then
FOnSelectionChanged(Self);
Invalidate;
End;
FPaginator.Free;
FPaginator := Nil;
End;
End;
Procedure TWordProcessor.CheckLostHotspot;
Begin
If Renderer.ShowHotspots(false) And (FRenderer.CurrentHotspot <> Nil) And Not MouseIsOver Then
Begin
MouseMove([], -1, -1);
End;
End;
Function TWordProcessor.MouseIsOver: Boolean;
Var
aMouse : TPoint;
Begin
If (GetCursorPos(Windows.TPoint(aMouse))) Then
Begin
aMouse := TPoint(ScreenToClient(Windows.TPoint(aMouse)));
Result := (aMouse.x > 0) And (aMouse.x < ActualWidth) And (aMouse.y > 0) And (aMouse.y < Height);
End
Else
Result := False;
End;
Function TWordProcessor.GetProperties: TWPPropertyList;
Begin
Result := FPropertyServer.GetProperties;
End;
Procedure TWordProcessor.SetProperty(oProperty: TWPProperty; Const sValue: String);
Begin
FPropertyServer.SetProperty(oProperty, sValue);
End;
Function EnumFontsProc(Var LogFont: TLogFont; Var TextMetric: TTextMetric; FontType: Integer; Data: Pointer): Integer; Stdcall;
Var
oList : TStringList;
Begin
Result := 1;
oList := TStringlist(Data);
If FontType And TRUETYPE_FONTTYPE > 0 Then
oList.Add(LogFont.lfFaceName);
End;
Function TWordProcessor.ListAllFonts: TStringList;
Var
iLoop : Integer;
Begin
Result := TStringList.Create;
{$IFNDEF NO_VCL_CANVAS_LOCK}
Canvas.Lock;
Try
{$ENDIF}
EnumFonts(Canvas.Handle, Nil, @EnumFontsProc, pointer(Result));
{$IFNDEF NO_VCL_CANVAS_LOCK}
Finally
Canvas.Unlock;
End;
{$ENDIF}
For iLoop := Result.Count - 1 DownTo 0 Do
Begin
If ((FontsAllowed.Count > 0) And Not FontsAllowed.ExistsByValue(Result[iLoop])) or (result[iLoop][1] = '@') Then
Result.Delete(iLoop);
End;
Result.Sort;
End;
Function EnumSpecialFontsProc(Var LogFont: TLogFont; Var TextMetric: TTextMetric; FontType: Integer; Data: Pointer): Integer; Stdcall;
Var
oList : TStringList;
Begin
Result := 1;
oList := TStringlist(Data);
If (FontType And TRUETYPE_FONTTYPE > 0) And (LogFont.lfCharSet = SYMBOL_CHARSET) Then
oList.Add(LogFont.lfFaceName);
End;
Function TWordProcessor.ListSpecialFonts: TStringList;
Var
iLoop : Integer;
Begin
Result := TStringList.Create;
{$IFNDEF NO_VCL_CANVAS_LOCK}
Canvas.Lock;
Try
{$ENDIF}
EnumFonts(Canvas.Handle, Nil, @EnumSpecialFontsProc, pointer(Result));
{$IFNDEF NO_VCL_CANVAS_LOCK}
Finally
Canvas.Unlock;
End;
{$ENDIF}
For iLoop := Result.Count - 1 DownTo 0 Do
Begin
If (FontsAllowed.Count > 0) And Not (FontsAllowed.ExistsByValue(Result[iLoop])) Then
Result.Delete(iLoop);
End;
Result.Sort;
End;
Procedure TWordProcessor.CommitField;
Begin
If PrimaryRange.HasCurrentFieldStart And PrimaryRange.CurrentFieldStart.HasDefinitionProvider Then
PrimaryRange.CurrentFieldStart.DefinitionProvider.Commit(PrimaryRange.CurrentFieldStart.DocField, PrimaryRange.CurrentFieldContent);
if PrimaryRange.HasCurrentFieldStart And Assigned(OnUpdateField) Then
begin
PrimaryRange.CurrentFieldStart.LastUpdateValue := PrimaryRange.CurrentFieldContent;
OnUpdateField(self, fusDeliberate, PrimaryRange.CurrentFieldStart.DefinitionProvider, PrimaryRange.CurrentFieldStart.DocField, PrimaryRange.CurrentFieldContent, not PrimaryRange.CurrentFieldStart.InError);
end;
End;
Function TWordProcessor.GoToFieldByName(Const sNamespace, sName : String) : Boolean;
Begin
CheckNotInMacro;
Result := PrimaryRange.GotoFieldByName(sNamespace, sName);
End;
Procedure TWordProcessor.DoButton(aBox : TRect; oButton : TFslObject; iOffset : Integer);
Begin
If (oButton Is TWPWorkingDocumentFieldStopPiece) And TWPWorkingDocumentFieldStopPiece(oButton).MatchingStart.HasDefinitionProvider And
TWPWorkingDocumentFieldStopPiece(oButton).MatchingStart.DefinitionProvider.HasUIAssistance(TWPWorkingDocumentFieldStopPiece(oButton).MatchingStart.DocField) Then
Begin
PrimaryRange.MoveTo(TWPWorkingDocumentFieldStopPiece(oButton).Metrics.Position, True);
CodeCompletePrompt;
End
Else If (oButton is TWPWorkingDocumentFieldStartPiece) And (TWPWorkingDocumentFieldStartPiece(oButton).Checkables.Count > 0) Then
Begin
PrimaryRange.MoveTo(TWPWorkingDocumentFieldStartPiece(oButton).Metrics.Position+TWPWorkingDocumentFieldStartPiece(oButton).Metrics.CharCount, True);
PrimaryRange.SetFieldCheckIndex(TWPWorkingDocumentFieldStartPiece(oButton), iOffset - TWPWorkingDocumentFieldStartPiece(oButton).Metrics.Position);
End
Else
MessageDlg('not done yet', mtInformation, [mbok], 0);
End;
Procedure TWordProcessor.CMMouseLeave(Var Message: TMessage);
Begin
Inherited;
If Not FCursorPersist Then
Screen.Cursor := crDefault;
FCursorOutside := True;
End;
Procedure TWordProcessor.CMMouseEnter(Var Message: TMessage);
Begin
Inherited;
FCursorOutside := False;
End;
{ TWPHotspotInformation }
Destructor TWPHotspotInformation.Destroy;
Begin
FHotspot.Free;
Inherited;
End;
Procedure TWPHotspotInformation.SetHotspot(Const Value: TWPHotspot);
Begin
FHotspot.Free;
FHotspot := Value;
End;
Function TWordProcessor.SelectedText: String;
Begin
Result := PrimaryRange.SelectedText;
End;
Function TWordProcessor.GetThumb: Integer;
Begin
Result := FScrollPoint.Y;
End;
Procedure TWordProcessor.SetThumb(iValue : Integer);
Begin
FScrollPoint.Y := iValue;
ScrollbarPositionChanged;
End;
Function TWordProcessor.GetTopLine: Integer;
Begin
Result := 0;
End;
Procedure TWordProcessor.SetTopLine(Const iValue: Integer);
Begin
End;
Function TWordProcessor.TextForLine(iLine: Integer): String;
Begin
// Result := Actor.TextForLine(iLine);
End;
Function TWordProcessor.Capabilities: TWPCapabilities;
Begin
Result := PrimaryRange.Capabilities;
End;
Procedure TWordProcessor.Copy;
Begin
CheckNotInMacro;
PrimaryRange.Copy;
End;
Procedure TWordProcessor.Cut;
Begin
CheckNotInMacro;
PrimaryRange.Cut;
End;
Procedure TWordProcessor.Redo;
Begin
CheckNotInMacro;
PrimaryRange.Redo;
End;
Procedure TWordProcessor.Undo;
Begin
CheckNotInMacro;
PrimaryRange.Undo;
End;
Function TWordProcessor.Paste(Var sError: String): Boolean;
Begin
CheckNotInMacro;
Result := PrimaryRange.Paste(sError);
End;
Procedure TWordProcessor.ApplyStyle(Const sName: String);
Begin
CheckNotInMacro;
PrimaryRange.Style := sName;
End;
Procedure TWordProcessor.ApplyStyleToLine(Const sName: String);
Begin
CheckNotInMacro;
PrimaryRange.GoLineEnd(False);
PrimaryRange.GoLineStart(True);
PrimaryRange.Style := sName;
PrimaryRange.GoLineEnd(False);
End;
Procedure TWordProcessor.CopyAllToClipboard;
Var
oRange : TWPVisualRange;
Begin
CheckNotInMacro;
oRange := ProduceRange;
Try
oRange.SelectAll;
oRange.Copy;
Finally
ConsumeRange(oRange);
End;
End;
Procedure TWordProcessor.Insert(Const sText: String);
Begin
CheckNotInMacro;
PrimaryRange.Insert(sText);
End;
Procedure TWordProcessor.SortTableDialog;
Var
oDialog: TWPSortTableDialog;
aRows: Array Of TStringList;
aSortedPos: Array Of Integer;
Begin
CheckNotInMacro;
If Not PrimaryRange.HasSelectedTable Then
Error('SortTableDialog', 'No Table is in scope');
If PrimaryRange.SelectedTable.Jagged Then
Error('SortTableDialog', 'Sort is not available for jagged Table');
oDialog := TWPSortTableDialog.Create(Owner);
Try
oDialog.Table := PrimaryRange.SelectedTable;
If oDialog.Execute Then
Begin
SetLength(aRows, oDialog.Table.Rows.Count);
GetSelectedTableAsTextArray(aRows);
SetLength(aSortedPos, Length(aRows));
SortTextArrays(oDialog.Sorts, aRows, aSortedPos);
PrimaryRange.ReorderTableRows(aSortedPos);
End;
Finally
oDialog.Free;
End;
End;
Procedure TWordProcessor.GetSelectedTableAsTextArray(Var aRows: Array Of TStringList);
Var
bInCell: Boolean;
sCellData: String;
iStart, iStop: Integer;
iLoop: Integer;
iRowIndex : Integer;
Begin
iRowIndex := 0;
bInCell := False;
iStart := Document.Pieces.IndexByReference(PrimaryRange.SelectedTable);
iStop := Document.Pieces.IndexByReference(PrimaryRange.SelectedTableStop);
For iLoop := iStart To iStop Do
Begin
Case Document.Pieces[iLoop].PieceType Of
ptRowStart: aRows[iRowIndex] := TStringList.Create;
ptRowStop: Inc(iRowIndex);
ptCellStart:
Begin
bInCell := True;
sCellData := '';
End;
ptCellStop:
Begin
bInCell := False;
aRows[iRowIndex].Add(sCellData);
End;
Else
If bInCell Then
sCellData := sCellData + Document.Pieces[iLoop].LogicalText;
End;
End;
End;
Procedure TWordProcessor.UpdateTextMetrics;
Begin
// nothing here.
End;
Procedure TWordProcessor.DeactivateBMPDrop;
Begin
FDropBMP.UnregisterAll;
End;
Procedure TWordProcessor.DoExit;
Begin
Inherited;
End;
Function TWordProcessor.NoUserResponse: Boolean;
Begin
Result := False;
End;
Function TWordProcessor.ShowCursorAlways: Boolean;
Begin
Result := False;
End;
Procedure TWordProcessor.NotifyObserversInsert(iPoint : Integer; oPieces : TWPWorkingDocumentPieces);
Begin
End;
Procedure TWordProcessor.NotifyObserversDelete(iPoint : Integer; oPieces : TWPWorkingDocumentPieces);
Begin
End;
Procedure TWordProcessor.ActorDeleteContent(oSender: TObject; iPoint: Integer; oPieces : TWPWorkingDocumentPieces);
Begin
NotifyObserversDelete(iPoint, oPieces);
End;
Procedure TWordProcessor.ActorInsertContent(oSender: TObject; iPoint: Integer; oPieces : TWPWorkingDocumentPieces);
Begin
If HasPlaybackManager Then
PlaybackManager.CloseCorrectionDialog;
NotifyObserversInsert(iPoint, oPieces);
End;
Procedure TWordProcessor.InsertTemplate;
Var
oBuffer : TFslBuffer;
Begin
CheckNotInMacro;
If Assigned(FOnTemplate) Then
Begin
oBuffer := FOnTemplate(Self);
Try
If Assigned(oBuffer) Then
PrimaryRange.InsertTemplate(oBuffer);
Finally
oBuffer.Free;
End;
End;
End;
Procedure TWordProcessor.SetOnTemplate(Const Value: TWPTemplateEvent);
Begin
FOnTemplate := Value;
Settings.InsertTemplates := Assigned(FOnTemplate);
End;
Function TWordProcessor.FetchTemplateContent(Const iId : Integer; Const sCode : String; var aFormat : TWPFormat) : TFslStream;
Var
oBuffer : TFslBuffer;
oStream : TFslMemoryStream;
Begin
If Not Assigned(FOnNamedTemplate) Then
Error('FetchTemplateContent', 'template content not provided');
oBuffer := FOnNamedTemplate(Self, iId, sCode, aFormat);
Try
oStream := TFslMemoryStream.Create;
Try
oStream.Buffer := oBuffer.Link;
Result := oStream.Link;
Finally
oStream.Free;
End;
Finally
oBuffer.Free;
End;
End;
Procedure TWordProcessor.InsertField(oDefn : TWPFieldDefinitionProvider);
Var
oField : TWPDocumentField;
oPiece : TWPWorkingDocumentFieldStartPiece;
oSection : TWPDocumentSection;
oPieceS : TWPWorkingDocumentSectionStartPiece;
bCanBeSection, bAcceptExistingContent : Boolean;
Begin
CheckNotInMacro;
If oDefn = Nil Then
oDefn := FDefaultFieldDefinition;
If oDefn = Nil Then
SoundBeepExclamation
Else
Begin
oField := TWPDocumentField.Create;
Try
oField.Style := PrimaryRange.Style;
oField.Font.Assign(PrimaryRange.Font);
bCanBeSection := canInsertFieldSection In Capabilities;
oSection := Nil;
If oDefn.NewField(oField, bCanBeSection, bAcceptExistingContent, oSection) Then
Begin
If (oSection <> Nil) Then
Begin
Try
If (Not bCanBeSection) Then
Error('InsertField', 'Cannot insert a section at this time');
oPieceS := FTranslator.CreateSection(oSection);
Try
oPieceS.Namespace := oDefn.GetNamespace;
PrimaryRange.InsertFieldSection(oPieceS, oSection.Blocks.AsText);
Finally
oPieceS.Free;
End;
Finally
oSection.Free;
End;
End
Else
Begin
oPiece := FTranslator.CreateField(oField);
Try
oPiece.Namespace := oDefn.GetNamespace;
PrimaryRange.InsertField(oPiece, True, bAcceptExistingContent, oField.Contents.AsText);
Finally
oPiece.Free;
End;
End;
End;
Finally
oField.Free;
End;
End;
End;
Procedure TWordProcessor.FieldPropertiesDialog;
Var
oField : TWPWorkingDocumentFieldStartPiece;
oTran : TWPDocumentTranslator;
Begin
CheckNotInMacro;
If Not PrimaryRange.HasCurrentFieldStart Then
Error('FieldPropertiesDialog', 'No Field is in scope');
If Not PrimaryRange.CurrentFieldStart.HasDefinitionProvider Then
Error('FieldPropertiesDialog', 'Current Field has no definition provider');
If PrimaryRange.CurrentFieldStart.DefinitionProvider.EditField(PrimaryRange.CurrentFieldStart.DocField) Then
Begin
oTran := TWPDocumentTranslator.Create;
Try
oField := oTran.CreateField(PrimaryRange.CurrentFieldStart.DocField);
Try
PrimaryRange.SetFieldProperties(oField);
Finally
oField.Free;
End;
Finally
oTran.Free;
End;
End;
End;
Procedure TWordProcessor.FieldSectionPropertiesDialog;
Var
oSection : TWPWorkingDocumentSectionStartPiece;
oTran : TWPDocumentTranslator;
Begin
CheckNotInMacro;
If Not PrimaryRange.HasCurrentSectionStart Then
Error('FieldSectionPropertiesDialog', 'No Section is in scope');
If Not PrimaryRange.CurrentSectionStart.HasDefinitionProvider Then
Error('FieldSectionPropertiesDialog', 'Current Section has no definition provider');
If PrimaryRange.CurrentSectionStart.DefinitionProvider.EditField(PrimaryRange.CurrentSectionStart.DocSection) Then
Begin
oTran := TWPDocumentTranslator.Create;
Try
oSection := oTran.CreateSection(PrimaryRange.CurrentSectionStart.DocSection);
Try
PrimaryRange.SetSectionProperties(oSection);
Finally
oSection.Free;
End;
Finally
oTran.Free;
End;
End;
End;
Procedure TWordProcessor.DefineFieldProvider(oDefinition: TWPFieldDefinitionProvider; bDefault : Boolean);
Begin
Settings.FieldDefinitions.Add(oDefinition);
If bDefault Then
DefaultFieldDefinition := oDefinition.Link;
End;
Procedure TWordProcessor.DefineAnnotationProvider(oDefinition: TWPAnnotationDefinitionProvider);
Begin
Settings.AnnotationDefinitions.Add(oDefinition);
End;
function TWordProcessor.BindToFields(oDocument: TWPWorkingDocument) : boolean;
Var
iLoop : Integer;
oPiece : TWPWorkingDocumentPiece;
Begin
result := false;
iLoop := 0;
while iLoop < oDocument.Pieces.Count do
Begin
oPiece := oDocument.Pieces[iLoop];
If oPiece.PieceType = ptFieldStart Then
result := BindToField(oDocument, iLoop, TWPWorkingDocumentFieldStartPiece(oPiece)) or result
Else If oPiece.PieceType = ptSectionStart Then
result := BindToSection(TWPWorkingDocumentSectionStartPiece(oPiece)) or result;
inc(iLoop);
End;
For iLoop := 0 to oDocument.AllAnnotations.Count - 1 Do
begin
oDocument.AllAnnotations[iLoop].DefinitionProvider := Settings.AnnotationDefinitions.GetByName(oDocument.AllAnnotations[iLoop].Owner, nil).Link;
if oDocument.AllAnnotations[iLoop].DefinitionProvider <> nil Then
oDocument.AllAnnotations[iLoop].Colour := oDocument.AllAnnotations[iLoop].DefinitionProvider.GetColour(oDocument.AllAnnotations[iLoop].Text);
End;
End;
function TWordProcessor.BindToField(oDocument: TWPWorkingDocument; cursor : integer; oPiece: TWPWorkingDocumentFieldStartPiece) : boolean;
var
s, txt : String;
p : TWPWorkingDocumentPiece;
Begin
result := false;
oPiece.BuildDocField;
oPiece.DefinitionProvider := Settings.FieldDefinitions.GetByName(oPiece.Namespace, DefaultFieldDefinition).Link;
if Assigned(OnUpdateField) or oPiece.HasDefinitionProvider Then
begin
s := '';
p := oPiece.Next;
while p.PieceType <> ptFieldStop do
begin
s := s + p.LogicalText;
p := p.Next;
end;
oPiece.LastUpdateValue := s;
if oPiece.HasDefinitionProvider and oPiece.DefinitionProvider.UpdateFieldOnLoad(oPiece.DocField, s, txt) then
begin
replaceFieldContent(oDocument, cursor, oPiece, txt);
result := true;
end
else if assigned(OnUpdateField) then
begin
if oPiece.HasDefinitionProvider then
OnUpdateField(self, fusLoading, oPiece.DefinitionProvider, oPiece.DocField, oPiece.DefinitionProvider.PreparePublicValue(oPiece.DocField, s), not oPiece.InError)
else
OnUpdateField(self, fusLoading, oPiece.DefinitionProvider, oPiece.DocField, s, not oPiece.InError);
end;
end;
if oPiece.HasDefinitionProvider And oPiece.DefinitionProvider.HasCheckables(oPiece.DocField) Then
Begin
oPiece.DefinitionProvider.GetCheckables(oPiece.DocField, oPiece.Checkables);
oPiece.BindToCheckables;
End;
End;
function TWordProcessor.BindToSection(oPiece: TWPWorkingDocumentSectionStartPiece) : boolean;
Begin
result := false;
If (oPiece.IsField) Then
Begin
oPiece.BuildDocSection;
oPiece.DefinitionProvider := Settings.FieldDefinitions.GetByName(oPiece.Namespace, DefaultFieldDefinition).Link;
End;
End;
Procedure TWordProcessor.SetDefaultFieldDefinition(Const Value: TWPFieldDefinitionProvider);
Begin
FDefaultFieldDefinition.Free;
FDefaultFieldDefinition := Value;
End;
Procedure TWordProcessor.RegisterInspector(oInspector : TWPInspector);
Begin
oInspector.Parent := Self;
oInspector.AlignRight;
FInspectors.Add(oInspector);
Resize;
Invalidate;
End;
Procedure TWordProcessor.RemoveInspector(oInspector : TWPInspector);
Begin
FInspectors.Remove(oInspector);
Resize;
Invalidate;
End;
Function TWordProcessor.ActualWidth: Integer;
Var
iLoop : Integer;
Begin
Result := Width;
For iLoop := 0 To FInspectors.Count - 1 Do
Dec(Result, FInspectors[iLoop].Width);
End;
Procedure TWordProcessor.SnapShot(Const sCause: String; Const DoMail : Boolean);
Var
sFilename : String;
oMapi : TFslMapi;
Begin
sFileName := IncludeTrailingBackslash(SystemTemp)+'wp'+DateTimeFormat(LocalDateTime, 'yyyymmddhhnnsszzz')+'.snapshot';
ProduceSnapShot(sFilename, sCause);
If (IsDebuggerPresent) Then
Begin
ExecuteOpen(sFileName+'.xml');
ExecuteOpen(sFileName+'.kdoc');
End
Else
Begin
oMapi := TFslMapi.Create;
Try
oMapi.Tos.Add(Settings.SnapshotEmail);
oMapi.Attachments.Add(sFileName+'.png');
oMapi.Attachments.Add(sFileName+'.xml');
oMapi.Preview := True;
oMapi.Send;
Finally
oMapi.Free;
End;
End;
End;
Procedure TWordProcessor.ProduceSnapShot(Const sFilename, sCause: String);
Var
oWriter : TWPSystemSnapshotWriter;
oFile : TFslFile;
Begin
Try
FRenderer.SavePNG(sFilename+'.png');
Except
On E:Exception Do
StringToFile(sFilename+'.png', e.Message);
End;
Try
oFile := TFslFile.Create(sFilename+'.xml', fmCreate);
Try
oWriter := TWPSystemSnapshotWriter.Create;
Try
oWriter.Filename := sFilename+'.xml';
oWriter.Stream := oFile.Link;
oWriter.Start(sCause);
oWriter.ProduceDocument(FDocument);
oWriter.ProduceOperator(FOperator);
oWriter.ProduceStyles('Configured', ConfiguredStyles);
oWriter.ProduceStyles('Working', WorkingStyles);
oWriter.ProduceSettings(FSettings);
oWriter.ProduceRanges(FRangeManager, PrimaryRange);
oWriter.ProduceRenderer(Renderer);
DoSnapShot(oWriter);
oWriter.Stop;
Finally
oWriter.Free;
End;
Finally
oFile.Free;
End;
Except
On E:Exception Do
StringToFile(sFilename+'.xml', e.Message);
End;
Try
FDocumentHandler.SaveNative(sFilename+'.kdoc');
Except
On E:Exception Do
StringToFile(sFilename+'.kdoc', e.Message);
End;
End;
Procedure TWordProcessor.RefreshPopup;
Begin
// nothing
End;
procedure TWordProcessor.ScrollTo(y: Integer);
begin
FScrollPoint.Y := IntegerMax(0, IntegerMin(MinimumRecommendedHeight - ClientHeight + (2 * Settings.VerticalMargin), Y));
ScrollbarPositionChanged;
DoPaint;
end;
Procedure TWordProcessor.ScrollToTop;
Begin
FScrollPoint.Y := 0;
ScrollbarPositionChanged;
DoPaint;
End;
Procedure TWordProcessor.HandleError(Const sContext, sMessage: String);
Begin
If FLastSnapshot <> FOperator.Version Then
Begin
SnapShot(sMessage, False);
FLastSnapshot := FOperator.Version;
End;
Error(sContext, sMessage);
End;
function TWordProcessor.DoSave: Boolean;
begin
result := assigned(FOnSave);
if result then
FOnSave(self);
end;
{
function TWordProcessor.DoSaveAs: Boolean;
begin
result := assigned(FOnSaveAs);
if result then
FOnSaveAs(self);
end;
}
Procedure TWordProcessor.DoSnapshot(oWriter: TWPSnapshotWriter);
Var
iLoop : Integer;
Begin
oWriter.ProduceOpen('status');
oWriter.ProduceText('Inspectors', IntegerToString(Inspectors.Count));
If FontsAllowed <> Nil Then
oWriter.ProduceText('FontsAllowed', FontsAllowed.AsCSV);
oWriter.ProduceText('VoiceActive', BooleanToString(VoiceActive));
If HasNextControl Then
oWriter.ProduceText('NextControl', 'True');
If HasPreviousControl Then
oWriter.ProduceText('PreviousControl', 'True');
oWriter.ProduceText('WorkingWidthLimit', IntegerToString(WorkingWidthLimit));
oWriter.ProduceText('ScrollPoint', IntegerToString(ScrollPoint.x)+':'+IntegerToString(ScrollPoint.y));
oWriter.ProduceText('CursorPersist', BooleanToString(CursorPersist));
oWriter.ProduceText('CursorOutside', BooleanToString(CursorOutside));
oWriter.ProduceText('Observers', IntegerToString(Observers.count));
If DefaultFieldDefinition <> Nil Then
oWriter.ProduceText('DefaultFieldDefinition', DefaultFieldDefinition.GetNamespace);
For iLoop := 0 To Settings.FieldDefinitions.Count - 1 Do
Begin
oWriter.Attributes.Match['namespace'] := Settings.FieldDefinitions[iLoop].GetNamespace;
oWriter.Attributes.Match['title'] := Settings.FieldDefinitions[iLoop].GetTitle;
oWriter.Attributes.Match['IconIndex'] := IntegerToString(Settings.FieldDefinitions[iLoop].GetStdIconIndex);
oWriter.Attributes.Match['TouchIconIndex'] := IntegerToString(Settings.FieldDefinitions[iLoop].GetTouchIconIndex);
oWriter.ProduceTag('FieldDefinition');
End;
If (HasExistingSearch) Then
Begin
oWriter.Attributes.Match['Text'] := ExistingSearch.Text;
oWriter.Attributes.Match['Direction'] := WPSEARCHDIRECTION_NAMES[ExistingSearch.Direction];
oWriter.Attributes.Match['WholeDocument'] := BooleanToString(ExistingSearch.WholeDocument);
oWriter.Attributes.Match['CaseSensitive'] := BooleanToString(ExistingSearch.CaseSensitive);
oWriter.Attributes.Match['WholeWords'] := BooleanToString(ExistingSearch.WholeWords);
oWriter.ProduceTag('ExistingSearch');
End;
If HasExistingReplace Then
Begin
oWriter.Attributes.Match['Replace'] := ExistingReplace.Replace;
oWriter.Attributes.Match['Selection'] := BooleanToString(ExistingReplace.Selection);
oWriter.Attributes.Match['Prompt'] := BooleanToString(ExistingReplace.Prompt);
oWriter.ProduceTag('ExistingReplace');
End;
If Printer <> Nil Then
Begin
oWriter.Attributes.Match['Port'] := Printer.Definition.Port;
oWriter.Attributes.Match['Driver'] := Printer.Definition.Driver;
oWriter.Attributes.Match['Name'] := Printer.Definition.Name;
oWriter.Attributes.Match['default'] := BooleanToString(Printer.Definition.IsDefault);
oWriter.ProduceTag('Printer');
End;
If PageLayoutController <> Nil Then
Begin
oWriter.Attributes.Match['SpanPolicy'] := NAMES_SPAN_POLICY[PageLayoutController.SpanPolicy];
oWriter.ProduceTag('PageController');
End;
oWriter.Attributes.Match['Modified'] := BooleanToString(Modified);
oWriter.Attributes.Match['JustDoubleClicked'] := BooleanToString(JustDoubleClicked);
oWriter.Attributes.Match['Cursor.Showing'] := BooleanToString(CursorDetails.Showing);
oWriter.Attributes.Match['Cursor.Left'] := IntegerToString(CursorDetails.Left);
oWriter.Attributes.Match['Cursor.Top'] := IntegerToString(CursorDetails.Top);
oWriter.Attributes.Match['Cursor.Height'] := IntegerToString(CursorDetails.Height);
oWriter.Attributes.Match['Cursor.Colour'] := ColourToString(CursorDetails.Colour);
If MouseActor <> Nil Then
oWriter.Attributes.Match['MouseActor'] := MouseActor.ClassName;
oWriter.Attributes.Match['ResetMouseCursor'] := BooleanToString(ResetMouseCursor);
oWriter.Attributes.Match['AltNum'] := AltNum;
oWriter.ProduceTag('cursor');
oWriter.ProduceClose('status');
End;
Procedure TWordProcessor.ForceRender;
Begin
Paint;
End;
Procedure TWordProcessor.WMContextMenu(Var aMessage : TWMContextMenu);
Begin
// http://qc.embarcadero.com/wc/qcmain.aspx?d=42752
aMessage.Result := 1;
End;
Type
TConsoleUnsuitableReason = (curFont, curParagraph, curBreak, curTable, curImage, curField);
TConsoleUnsuitableReasonSet = Set Of TConsoleUnsuitableReason;
Const
MSG_TConsoleUnsuitableReason : Array [TConsoleUnsuitableReason] Of String = ('Unsupported Font Formatting', 'Unsupported Paragraph Formatting', 'A Page or Break', 'A Table', 'An Image', 'A Field or Section');
Function TWordProcessor.CheckOkForConsoleMode(Var sMessage: String): Boolean;
Var
aFail : TConsoleUnsuitableReasonSet;
aLoop : TConsoleUnsuitableReason;
iLoop : Integer;
oDefault : TWPStyle;
oPiece : TWPWorkingDocumentPiece;
oStyle : TWPStyle;
Begin
aFail := [];
oDefault := WorkingStyles.DefaultStyle;
For iLoop := 0 To FDocument.Pieces.Count - 1 Do
Begin
oPiece := FDocument.Pieces[iLoop];
Case oPiece.PieceType Of
ptText :
Begin
oStyle := WorkingStyles.GetByNameOrDefault(oPiece.Style);
If oStyle.WorkingFontName(oPiece.Font) <> oDefault.Font.Name Then
Include(aFail, curFont);
If oStyle.WorkingFontSize(oPiece.Font) <> oDefault.Font.Size Then
Include(aFail, curFont);
If oStyle.WorkingFontStrikethrough(oPiece.Font) = tsTrue Then
Include(aFail, curFont);
If oStyle.WorkingFontState(oPiece.Font) In [fsSuperscript, fsSubscript] Then
Include(aFail, curFont);
If oStyle.WorkingFontForeground(oPiece.Font) <> DEFAULT_FOREGROUND Then
Include(aFail, curFont);
If oStyle.WorkingFontBackground(oPiece.Font, MAXINT) <> MAXINT Then
Include(aFail, curFont);
If oStyle.WorkingFontCapitalization(oPiece.Font) In [fcsAllCaps, fcsNoCaps, fcsSmallCaps] Then
Include(aFail, curFont);
End;
ptPara :
Begin
oStyle := WorkingStyles.GetByNameOrDefault(oPiece.Style);
If oStyle.WorkingFontName(oPiece.Font) <> oDefault.Font.Name Then
Include(aFail, curFont);
If oStyle.WorkingFontSize(oPiece.Font) <> oDefault.Font.Size Then
Include(aFail, curFont);
If oStyle.WorkingFontStrikethrough(oPiece.Font) = tsTrue Then
Include(aFail, curFont);
If oStyle.WorkingFontState(oPiece.Font) In [fsSuperscript, fsSubscript] Then
Include(aFail, curFont);
If oStyle.WorkingFontForeground(oPiece.Font) <> DEFAULT_FOREGROUND Then
Include(aFail, curFont);
If oStyle.WorkingFontBackground(oPiece.Font, MAXINT) <> MAXINT Then
Include(aFail, curFont);
If oStyle.WorkingFontCapitalization(oPiece.Font) In [fcsAllCaps, fcsNoCaps, fcsSmallCaps] Then
Include(aFail, curFont);
If oStyle.WorkingParagraphAlign(TWPWorkingDocumentParaPiece(oPiece).Format) In [WordProcessorParagraphAlignmentCentre, WordProcessorParagraphAlignmentRight, WordProcessorParagraphAlignmentJustify] Then
Include(aFail, curParagraph);
If oStyle.WorkingParagraphLeftIndent(TWPWorkingDocumentParaPiece(oPiece).Format) <> 0 Then
Include(aFail, curParagraph);
If oStyle.WorkingParagraphRightIndent(TWPWorkingDocumentParaPiece(oPiece).Format) <> 0 Then
Include(aFail, curParagraph);
If oStyle.WorkingParagraphListType(TWPWorkingDocumentParaPiece(oPiece).Format) In [WPSParagraphListTypeBullets, WPSParagraphListTypeNumbers] Then
Include(aFail, curParagraph);
End;
ptImage : Include(aFail, curImage);
ptFieldStart, ptFieldStop : Include(aFail, curField);
ptLineBreak, ptBreak : Include(aFail, curBreak);
ptTableStart, ptRowStart, ptCellStart, ptTableStop, ptRowStop, ptCellStop : Include(aFail, curTable);
ptSectionStart, ptSectionStop : Include(aFail, curField);
End;
End;
Result := True;
sMessage := '';
For aLoop := Low(TConsoleUnsuitableReason) To High(TConsoleUnsuitableReason) Do
If aLoop In aFail Then
Begin
Result := False;
sMessage := sMessage + ' '+MSG_TConsoleUnsuitableReason[aLoop] + #13#10;
End;
End;
Function TWordProcessor.CheckOkForNoParagraphs: Boolean;
Var
iLoop : Integer;
oPiece : TWPWorkingDocumentPiece;
Begin
Result := True;
For iLoop := 0 To FDocument.Pieces.Count - 1 Do
Begin
oPiece := FDocument.Pieces[iLoop];
If oPiece.PieceType = ptPara Then
Result := Result And (iLoop = FDocument.Pieces.Count - 1) // last one ok
Else
Result := Result And (oPiece.PieceType In [ptText, ptImage, ptLineBreak, ptFieldStart, ptFieldStop]);
End;
End;
Procedure TWordProcessor.CheckNotInMacro;
Begin
If FMacro.Recording Then
Raise ELibraryException.Create('Cannot perform this operation while a macro is being recorded');
End;
Procedure TWordProcessor.Ring(aColour: TColour);
Begin
Canvas.Pen.Style := psSolid;
Canvas.pen.Color := aColour;
Canvas.pen.Width := 4;
Canvas.MoveTo(0,0);
Canvas.LineTo(Width-1, 0);
Canvas.LineTo(Width-1, Height-1);
Canvas.LineTo(0, Height-1);
Canvas.LineTo(0,0);
End;
Procedure TWordProcessor.ToggleMacro;
Begin
Case FMacro.State Of
msIdle : FMacro.State := msRecording;
msRecording : FMacro.State := msIdle;
msPlaying : CheckNotInMacro;
End;
Invalidate;
End;
Procedure TWordProcessor.ExecuteMacro;
Var
i : Integer;
oAction : TWPMacroAction;
Begin
CheckNotInMacro;
NonVisibleMode := False;
FMacro.State := msPlaying;
Try
Try
For i := 0 To FMacro.Actions.Count - 1 Do
Begin
oAction := FMacro.Actions[i];
Case oAction.ActionType Of
matKey : If Not ProcessKey(TWPMacroKeyAction(oAction).Key, TWPMacroKeyAction(oAction).Shift) Then
Begin
SoundBeepExclamation;
Abort;
End;
Else
raise EWPException.create('Unknown action type '+FMacro.Actions[i].ClassName);
End;
End;
Except
FMacro.LastError := True;
Raise;
End;
Finally
FMacro.State := msIdle;
NonVisibleMode := False;
Invalidate;
End;
End;
Procedure TWordProcessor.StartRecordingMacro;
Begin
If FMacro.State <> msIdle Then
raise EWPException.create('Connect record a macro');
ToggleMacro;
End;
Procedure TWordProcessor.StopRecordingMacro;
Begin
If FMacro.State <> msRecording Then
raise EWPException.create('Not recording a macro');
ToggleMacro;
End;
Procedure TWordProcessor.CheckForAllowedWord(Sender: TObject; Const Word: String; Var CheckType: TWordCheckType; Var Replacement: String);
Begin
If FDocument.AllowedWords.ExistsByValue(lowercase(Word)) Then
CheckType := wcAccepted;
End;
Procedure TWordProcessor.ReviewWordDialog;
Var
oDlg : TWPAllowedWordsDialog;
iCount : Integer;
Begin
oDlg := TWPAllowedWordsDialog.Create(Self);
Try
oDlg.Words.Assign(Document.AllowedWords);
If oDlg.Execute Then
Begin
For iCount := 0 To oDlg.ToDictionary.Count - 1 Do
FSpeller.AddWord(oDlg.ToDictionary[iCount]);
Document.AllowedWords.Assign(oDlg.Words);
PrimaryRange.ResetSpelling;
Renderer.Valid := False;
Renderer.PaintAll := True;
Renderer.Update;
Invalidate;
End;
Finally
oDlg.Free;
End;
End;
Procedure TWordProcessor.AddAllowedWord(Sender: TObject; Const Word: String);
Begin
FDocument.AllowedWords.Add(Word);
End;
Function TWordProcessor.GetImageTool: TImageTool;
Begin
Result := FOperator.CurrentImageTool;
End;
Procedure TWordProcessor.SetImageTool(Const Value: TImageTool);
Begin
FOperator.CurrentImageTool := Value;
End;
procedure TWordProcessor.CompletionBoxKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if Key = vkEscape Then
FCodeCompletionListBox.Visible := false;
end;
function TWordProcessor.CheckFields(oErrors: TFslStringList): Boolean;
Var
iLoop : Integer;
oPiece : TWPWorkingDocumentPiece;
Begin
For iLoop := 0 To Document.Pieces.Count - 1 Do
Begin
oPiece := Document.Pieces[iLoop];
If oPiece.PieceType = ptFieldStart Then
CheckField(oErrors, TWPWorkingDocumentFieldStartPiece(oPiece));
End;
result := oErrors.Count = 0;
end;
procedure TWordProcessor.CheckField(oErrors: TFslStringList; oPiece: TWPWorkingDocumentFieldStartPiece);
begin
if oPiece.InError Then
if oPiece.FieldHint = '' Then
oErrors.Add('Field "'+oPiece.Name+'" content not acceptable')
Else
oErrors.Add('Field "'+oPiece.Name+'" should be : '+oPiece.FieldHint)
end;
procedure TWordProcessor.DoAnnotationClick(oAnnotation: TWPWorkingAnnotation);
begin
PrimaryRange.MoveTo(oAnnotation.OffsetStart, false);
PrimaryRange.SelectTo(oAnnotation.OffsetEnd, true);
EditAnnotation;
end;
procedure TWordProcessor.InsertAnnotation(oDefn: TWPAnnotationDefinitionProvider);
var
sContent : String;
action : TEditAnnotationResult;
Begin
CheckNotInMacro;
If Not (canInsertAnnotation In PrimaryRange.Capabilities) Then
Error('InsertAnnotation', 'Cannot insert annotation here');
sContent := '';
action := oDefn.EditAnnotation(PrimaryRange.SelectedText, sContent);
if action = earChanged then
PrimaryRange.InsertAnnotation(oDefn, sContent);
end;
procedure TWordProcessor.DeleteAnnotation;
Var
oAnnotation : TWPWorkingAnnotation;
Begin
If Not (canManageAnnotation In PrimaryRange.Capabilities) Then
Error('DeleteAnnotation', 'Cannot delete annotation');
oAnnotation := FDocument.AllAnnotations.GetBySelection(Selection.WorkingSelStart, Selection.WorkingSelEnd);
If (oAnnotation = nil) Then
Error('DeleteAnnotation', 'Cannot delete annotation - annotation not found');
PrimaryRange.DeleteAnnotation;
end;
procedure TWordProcessor.EditAnnotation;
Var
oAnnotation : TWPWorkingAnnotation;
oProvider : TWPAnnotationDefinitionProvider;
sText : String;
action : TEditAnnotationResult;
Begin
If Not (canManageAnnotation In PrimaryRange.Capabilities) Then
Error('EditAnnotation', 'Cannot edit annotation');
oAnnotation := FDocument.AllAnnotations.GetBySelection(Selection.WorkingSelStart, Selection.WorkingSelEnd);
If (oAnnotation = nil) Then
Error('EditAnnotation', 'Cannot edit annotation - annotation not found');
PrimaryRange.MoveTo(oAnnotation.OffsetStart, false);
PrimaryRange.SelectTo(oAnnotation.OffsetEnd, true);
oProvider := Settings.AnnotationDefinitions.GetByName(oAnnotation.Owner, nil);
if oProvider = nil then
raise EWPException.create('Unknown Annotation Type')
else
begin
sText := oAnnotation.Text;
action := oProvider.EditAnnotation(PrimaryRange.SelectedText, sText);
if action = earChanged Then
PrimaryRange.EditAnnotation(sText)
else if action = earDelete then
PrimaryRange.DeleteAnnotation;
end;
end;
procedure TWordProcessor.AddAnnotation(iStart, iEnd: Integer; const sNamespace, sContent: String);
var
oDefn : TWPAnnotationDefinitionProvider;
Begin
CheckNotInMacro;
oDefn := Settings.AnnotationDefinitions.GetByName(sNamespace, nil);
if oDefn = nil then
Error('AddAnnotation', 'Unknown Annotation Type');
PrimaryRange.MoveTo(iStart, false);
PrimaryRange.SelectTo(iEnd, true);
If Not (canInsertAnnotation In PrimaryRange.Capabilities) Then
Error('InsertAnnotation', 'Cannot insert annotation here');
PrimaryRange.InsertAnnotation(oDefn, sContent);
end;
function TWordProcessor.InSpeechMode: Boolean;
begin
result := false;
end;
function TWordProcessor.InTouchMode: boolean;
{$IFDEF UNICODE}
var
flags : uLONG;
{$ENDIF}
begin
result := {$IFDEF UNICODE}(Settings.TouchMode = wptmAlways) or
((Settings.TouchMode = wptmOnTouchDevice) and (IsTouchWindow(0, @flags))){$ELSE} false {$ENDIF};
end;
procedure TWordProcessor.CheckOkForSpeech;
var
iLoop : Integer;
oPiece : TWPWorkingDocumentPiece;
begin
for iLoop := 0 to FDocument.Pieces.Count - 1 Do
begin
oPiece := FDocument.Pieces[iLoop];
if (oPiece.PieceType = ptFieldStart) and (TWPWorkingDocumentFieldStartPiece(oPiece).Checkables.Count > 0) then
raise EWPException.create('Unable to start dicatation as the content includes a field with buttons - this is not supported in voice mode');
End;
end;
function TWordProcessor.AllFieldsValid(var sError : String): boolean;
var
oIter : TWPPieceIterator;
oField : TWPWorkingDocumentFieldStartPiece;
begin
oIter := TWPPieceIterator.Create;
try
oIter.Document := Document.Link;
oIter.PieceTypes := [ptFieldStart];
oIter.First;
result := true;
while oIter.More do
begin
oField := TWPWorkingDocumentFieldStartPiece(oIter.Current);
result := result and not oField.InError;
if not result and (sError = '') then
if oField.DefinitionProvider <> nil then
sError := oField.DefinitionProvider.HintForField(oField.DocField, fhmError)+' Error: '+TWPWorkingDocumentFieldStartPiece(oIter.Current).FieldError
else
sError := oField.FieldError;
oIter.Next;
end;
finally
oIter.Free;
end;
end;
function TWordProcessor.ListAllFields(Namespace: String): TWPDocumentFields;
var
oIter : TWPPieceIterator;
begin
result := TWPDocumentFields.create;
try
oIter := TWPPieceIterator.Create;
try
oIter.Document := Document.Link;
oIter.PieceTypes := [ptFieldStart];
oIter.First;
while oIter.More do
begin
if (Namespace = '') or (Namespace = TWPWorkingDocumentFieldStartPiece(oIter.Current).Namespace) then
result.add(TWPWorkingDocumentFieldStartPiece(oIter.Current).DocField.Link);
oIter.Next;
end;
finally
oIter.Free;
end;
result.link;
finally
result.free;
end;
end;
function TWordProcessor.GetContentForField(oField: TWPDocumentField): String;
var
oIter : TWPPieceIterator;
oPiece : TWPWorkingDocumentPiece;
found : boolean;
begin
oIter := TWPPieceIterator.Create;
try
oIter.Document := Document.Link;
oIter.PieceTypes := [ptFieldStart];
oIter.First;
found := false;
while oIter.More and not found do
begin
if (TWPWorkingDocumentFieldStartPiece(oIter.Current).DocField = oField) then
begin
found := true;
oPiece := oIter.Current.Next;
result := '';
while (oPiece.PieceType <> ptFieldStop) do
begin
result := result + oPiece.LogicalText;
oPiece := oPiece.Next;
end;
end;
oIter.Next;
end;
finally
oIter.Free;
end;
end;
{ TWPInspectorList }
function TWPInspectorList.GetPanelByIndex(const iIndex: Integer): TWPInspector;
begin
Result := TWPInspector(Items[iIndex]);
end;
function TWPInspectorList.ItemClass: TComponentClass;
begin
Result := TWPInspector;
end;
{ TWPInspector }
function TWPInspector.DesiredWidth: Integer;
begin
Result := 200;
end;
procedure TWPInspector.Initialise;
Var
oButton : TUixButton;
begin
inherited;
BorderWidth := 2;
AlignRight;
Width := DesiredWidth;
FHeader := TUixPanel.Create(Self);
FHeader.Parent := Self;
FHeader.Height := 20;
FHeader.Caption := InspectorCaption;
FHeader.Color := clActiveCaption;
FHeader.Font.Color := clCaptionText;
FHeader.Font.Style := [fsBold];
FHeader.AlignTop;
oButton := TUixButton.Create(FHeader);
oButton.Left := DesiredWidth - 70;
oButton.Height := 20;
oButton.Width := 66;
oButton.Top := 0;
oButton.Caption := 'Close';
oButton.OnClick := WantClose;
FFooter := TUixPanel.Create(Self);
FFooter.Parent := Self;
FFooter.Height := 20;
FFooter.Caption := '';
FFooter.Color := clBtnFace;
FFooter.AlignBottom;
FFooterCaption := TUixLabel.Create(self);
FFooterCaption.Parent := FFooter;
FFooterCaption.Top := 2;
FFooterCaption.Left := 2;
FFooterCaption.Font.Color := clBtnText;
FFooterCaption.Font.Style := [];
FFooterCaption.Caption := '--';
End;
function TWPInspector.InspectorCaption: String;
begin
Result := 'Caption';
end;
procedure TWPInspector.WantClose(oSender: TObject);
begin
end;
{ TWPPropertyInspector }
Procedure TWPPropertyInspector.Initialise;
Begin
Inherited;
FAllProperties := TFslStringObjectMatch.Create;
End;
Procedure TWPPropertyInspector.Setup;
Var
oDefn : TWPPropertyFieldDefinitionProvider;
Begin
FDisplay := TWordProcessor.Create(Self);
FDisplay.Parent := Self;
FDisplay.AlignClient;
oDefn := TWPPropertyFieldDefinitionProvider.Create(FDisplay);
Try
oDefn.OnCommit := CommitField;
FDisplay.DefineFieldProvider(oDefn.Link, False);
Finally
oDefn.Free;
End;
FDisplay.ShowHint := False;
FDisplay.Settings.Hold;
Try
FDisplay.Settings.AllowPopup := True;
FDisplay.Settings.Images := True;
FDisplay.Settings.Margin := 2;
FDisplay.Settings.TableBorders := False;
FDisplay.Settings.ShowDocumentInspector := False;
FDisplay.Settings.Background := clWhite; // $FFD5CF;
FDisplay.Settings.LinkColour := clAqua;
FDisplay.Settings.HoverColour := clLime;
FDisplay.Settings.Pagination := False;
FDisplay.Settings.FieldWrappers := wpfpInvisible;
FDisplay.Settings.NoSelectReadOnly := True;
Finally
FDisplay.Settings.Release;
End;
FDisplay.WorkingStyles.DefaultStyle.Font.Name := 'Verdana';
FDisplay.WorkingStyles.DefaultStyle.Font.Size := 8;
FDisplay.OnSelectionChanged := SelectionChanged;
End;
Procedure TWPPropertyInspector.ProcessList(oBuilder: TWPDocumentBuilder; oProps : TWPPropertyList; oOwner: TWPDocumentTableRow);
Var
iLoop : Integer;
oProp : TWPProperty;
oRow : TWPDocumentTableRow;
oCell : TWPDocumentTableCell;
oField : TWPDocumentField;
Begin
For iLoop := 0 To oProps.Count - 1 Do
Begin
oProp := oProps[iLoop];
If oProp.Kind = pkGroup Then
Begin
oRow := oBuilder.StartTableRow(oOwner, ReadOnlyTrue);
oRow.TopBorder.SimpleDot;
oCell := oBuilder.StartTableCell(2, ReadOnlyTrue);
oCell.Background := clGray;
oCell.MarginLeft := 4;
oCell.MarginTop := 1;
oCell.MarginBottom := 1;
oBuilder.StartParagraph;
oBuilder.AddText(oProp.Name, True, False, 8);
oBuilder.EndParagraph;
oBuilder.EndTableCell;
oBuilder.EndTableRow();
ProcessList(oBuilder, oProp.Children, oRow);
End
Else
Begin
oBuilder.StartTableRow(oOwner, ReadOnlyTrue);
oCell := oBuilder.StartTableCell(1, ReadOnlyTrue);
oCell.Width := 0.5;
oCell.MarginLeft := 4;
oCell.MarginTop := 1;
oCell.MarginBottom := 1;
If (iLoop > 0) Then
oCell.TopBorder.SimpleDot;
oBuilder.StartParagraph;
oBuilder.AddText(oProp.Name, False, False, 8);
oBuilder.EndParagraph;
oBuilder.EndTableCell;
oCell := oBuilder.StartTableCell(1, ReadOnlyTrue);
oCell.Width := 0.5;
If (iLoop > 0) Then
oCell.TopBorder.SimpleDot;
oCell.MarginLeft := 1;
oCell.MarginTop := 1;
oCell.MarginBottom := 1;
oBuilder.StartParagraph;
If oProp.Editable Then
Begin
oCell.Background := clWhite;
oField := oBuilder.StartField;
oField.ReadOnly := ReadOnlyFalse;
oField.Namespace := NS_FIELD_PROPERTY;
oField.Name := IntegerToString(oProp.Id);
FAllProperties.Add(oField.Name, oProp.Link);
oField.Font.Size := 8;
End;
oBuilder.AddText(oProp.Value, False, False, 8);
If oProp.Editable Then
oBuilder.EndField;
oBuilder.EndParagraph;
oBuilder.EndTableCell;
oBuilder.EndTableRow();
End;
End;
End;
Procedure TWPPropertyInspector.WPChange(oSender: TObject);
Var
oBuilder : TWPDocumentBuilder;
oTable : TWPDocumentTable;
oProps : TWPPropertyList;
sName : String;
Begin
If FDisplay = Nil Then
Setup;
If FDisplay.PrimaryRange.HasCurrentFieldStart And (FDisplay.PrimaryRange.CurrentFieldStart.Namespace = NS_FIELD_PROPERTY) Then
sName := FDisplay.PrimaryRange.CurrentFieldStart.Name;
oBuilder := TWPDocumentBuilder.Create;
Try
oBuilder.Document := TWPDocument.Create;
oBuilder.Document.Styles := FDisplay.WorkingStyles.Link;
oBuilder.Start;
oTable := oBuilder.StartTable(ReadOnlyTrue);
oTable.BorderPolicy := BorderPolicyCustom;
FAllProperties.clear;
oProps := WordProcessor.GetProperties;
Try
ProcessList(oBuilder, oProps, Nil);
Finally
oProps.Free;
End;
oBuilder.EndTable;
oBuilder.Stop;
FDisplay.DocumentHandler.LoadDocument(oBuilder.Document);
Finally
oBuilder.Free;
End;
If sName <> '' Then
FDisplay.GotoFieldByName(NS_FIELD_PROPERTY, sName);
End;
Procedure TWPPropertyInspector.SelectionChanged(oSender: TObject);
Begin
FFooterCaption.Caption := FDisplay.SelectionSummary + ' ['+FDisplay.Selection.Summary+']';
End;
Procedure TWPPropertyInspector.CommitField(oField: TWPDocumentField; Const sContent: String);
Var
oProp : TWPProperty;
Begin
If (oField.Namespace = NS_FIELD_PROPERTY) Then
Begin
oProp := TWPProperty(FAllProperties.GetValueByKey(oField.Name));
If oProp <> Nil Then
Begin
Try
WordProcessor.SetProperty(oProp, sContent);
Except
On E : Exception Do
MessageDlg('Error Setting '+oProp.Name+' value to "'+sContent+'": '+e.Message, mtError, [mbok], 0);
End;
End;
End;
WordProcessor.SetFocus;
End;
Procedure TWPPropertyInspector.Finalise;
Begin
FAllProperties.Free;
Inherited;
End;
Function TWPPropertyInspector.DesiredWidth: Integer;
Begin
Result := 220;
End;
Function TWPPropertyInspector.InspectorCaption: String;
Begin
Result := 'Document Properties';
End;
Procedure TWPLinkedInspector.SetWordProcessor(Const Value: TWordProcessor);
Begin
If FWordProcessor <> Nil Then
FWordProcessor.UnregisterObserver(Self);
FWordProcessor := Value;
If FWordProcessor <> Nil Then
Begin
FWordProcessor.RegisterObserver(Self, WPChange);
WPChange(FWordProcessor);
End;
End;
Procedure TWPLinkedInspector.WantClose(oSender: TObject);
Var
oWordProcessor : TWordProcessor;
Begin
oWordProcessor := WordProcessor;
WordProcessor := Nil;
oWordProcessor.RemoveInspector(Self);
Free;
End;
Procedure TWPLinkedInspector.WPChange(oSender: TObject);
Begin
End;
{ TWPTouchManager }
constructor TWPTouchManager.create(owner: TWordProcessor);
begin
inherited Create;
FLoaded := false;
FOwner := owner;
end;
destructor TWPTouchManager.destroy;
begin
Unload;
FGestures.Free;
inherited;
end;
Const
FLAGNAMES : array [TInteractiveGestureFlag] of string = ('begin', 'inertia', 'end');
function flagsToString(flags: TInteractiveGestureFlags):String;
var
a : TInteractiveGestureFlag;
begin
result:= '';
for a := Low(TInteractiveGestureFlag) to High(TInteractiveGestureFlag) do
if (a in flags)then
result := result + ',' + FLAGNAMES[a];
result := copy(result,2,100);
end;
function gesturetostr(i:integer):string;
begin
if i = igiZoom then
result := 'Zoom'
else if i=igiPan then
result := 'Pan'
else if i = igiRotate then
result := 'Rotate'
else if i = igiTwoFingerTap then
result := 'TwoFingerTap'
else if i = igiPressAndTap then
result := 'PressAndTap'
else
result := inttostr(i);
end;
procedure TWPTouchManager.DoGesture(sender: TObject; const EventInfo: TGestureEventInfo; var Handled: boolean);
begin
case EventInfo.GestureID of
igiZoom : handled := Zoom(EventInfo);
igiPan : handled := Pan(EventInfo);
igiTwoFingerTap : handled := TwoFingers(EventInfo);
else
Handled := false;
end;
end;
procedure TWPTouchManager.Load;
begin
if not FLoaded then
begin
FLoaded := true;
// FGestures := TGestureManager.create(FOwner);
FOwner.OnGesture := DoGesture;
// FOwner.Touch.GestureManager := FGestures;
//FGestures.StandardGestures[FOwner] := [sgLeft];
//FGestures.FindGesture(FOwner, sgiLeft).Action := FAction;
FOwner.Touch.InteractiveGestureOptions := [{igoPanSingleFingerHorizontal, }igoPanSingleFingerVertical, igoPanInertia{, igoPanGutter, igoParentPassthrough}];
FOwner.Touch.InteractiveGestures := [igZoom, igPan{, igRotate, }, igTwoFingerTap{, igPressAndTap}];
FOwner.Touch.TabletOptions := [toPressAndHold];
// FOwner.perform(CM_TABLETOPTIONSCHANGED, 0 ,0);
end;
end;
function TWPTouchManager.Pan(EventInfo: TGestureEventInfo): boolean;
begin
if gfBegin in EventInfo.Flags then
begin
FPanStart := EventInfo.Location.Y;
FPanBase := FOwner.ScrollPoint.Y;
end
else
begin
FOwner.ScrollTo(FPanBase-(EventInfo.Location.Y - FPanStart));
writeln('Pan: '+ inttostr(EventInfo.Location.Y - FPanStart));
end;
// FOwner.Settings.Scale := Min(Max(FZoomBase *(EventInfo.Distance / FZoomStart), 0.1), 10);
{
writeln('Loc = '+inttostr(EventInfo.Location.X)+', '+inttostr(EventInfo.Location.y)+
'. flags = '+Flagstostring(EventInfo.Flags)+'. angle = '+floatToStr(EventInfo.Angle)+
'. InertiaVector = '+inttostr(EventInfo.InertiaVector.X)+', '+inttostr(EventInfo.InertiaVector.y)+
'. Distance = '+inttostr(EventInfo.Distance)+
'. taplocation = '+inttostr(EventInfo.TapLocation.X)+', '+inttostr(EventInfo.TapLocation.y));
}
end;
function TWPTouchManager.TwoFingers(EventInfo: TGestureEventInfo): boolean;
begin
FOwner.ShowPopupMenu();
end;
procedure TWPTouchManager.Unload;
begin
if FLoaded then
begin
FLoaded := false;
FOwner.Touch.GestureManager := nil;
end;
end;
function TWPTouchManager.Zoom(EventInfo: TGestureEventInfo): boolean;
begin
if gfBegin in EventInfo.Flags then
begin
FZoomStart := EventInfo.Distance;
FZoomBase := FOwner.Settings.Scale;
end
else
FOwner.Settings.Scale := Min(Max(FZoomBase *(EventInfo.Distance / FZoomStart), 0.5), 10);
end;
{ TWPSystemSnapshotWriter }
Procedure TWPSystemSnapshotWriter.ProduceRenderer(oRenderer : TWPScreenRenderer);
Var
sText : String;
iLoop : Integer;
Begin
Attributes.Match['LastVersion'] := IntegerToString(oRenderer.LastVersion);
Attributes.Match['SomeSelected'] := BooleanToString(oRenderer.SomeSelected);
Attributes.Match['Width'] := IntegerToString(oRenderer.Width);
Attributes.Match['SectionHeaderHeight'] := IntegerToString(oRenderer.SectionHeaderHeight);
Attributes.Match['SectionFieldCharWidth'] := IntegerToString(oRenderer.SectionFieldCharWidth);
Attributes.Match['SectionFieldCharHeight'] := IntegerToString(oRenderer.SectionFieldCharHeight);
Attributes.Match['FieldFontSize'] := IntegerToString(oRenderer.FieldFontSize.cx)+':'+IntegerToString(oRenderer.FieldFontSize.cy);
Attributes.Match['FieldDescent'] := IntegerToString(oRenderer.FieldDescent);
Attributes.Match['MeasureAll'] := BooleanToString(oRenderer.MeasureAll);
Attributes.Match['PaintAll'] := BooleanToString(oRenderer.PaintAll);
Attributes.Match['Valid'] := BooleanToString(oRenderer.Valid);
Attributes.Match['Working'] := BooleanToString(oRenderer.Working);
Attributes.Match['AdjustTop'] := IntegerToString(oRenderer.AdjustTop);
Attributes.Match['AdjustOffset'] := IntegerToString(oRenderer.AdjustOffset);
Attributes.Match['CurrentHotspot'] := GetId(oRenderer.CurrentHotspot);
Attributes.Match['CurrentButton'] := GetId(oRenderer.CurrentButton);
Attributes.Match['canvas-StatedWidth'] := IntegerToString(oRenderer.Canvas.StatedWidth);
Attributes.Match['canvas-StatedHeight'] := IntegerToString(oRenderer.Canvas.StatedHeight);
Attributes.Match['canvas-InternalTop'] := IntegerToString(oRenderer.Canvas.InternalTop);
Attributes.Match['canvas-InternalBottom'] := IntegerToString(oRenderer.Canvas.InternalBottom);
Attributes.Match['canvas-HorizontalMargin'] := IntegerToString(oRenderer.Canvas.HorizontalMargin);
Attributes.Match['canvas-VerticalMargin'] := IntegerToString(oRenderer.Canvas.VerticalMargin);
Attributes.Match['canvas-Background'] := ColourToString(oRenderer.Canvas.Background);
Attributes.Match['canvas-Contrast'] := RealToString(oRenderer.Canvas.Contrast);
ProduceOpen('renderer');
ProduceBorder('defaultBorder', oRenderer.DefaultTableBorder);
ProduceContainer(oRenderer.Map);
sText := '';
For iLoop := Low(oRenderer.PageOffsets) To High(oRenderer.PageOffsets) Do
sText := sText + IntegerToString(oRenderer.PageOffsets[iLoop])+ ' ';
ProduceText('PageOffsets', sText);
sText := '';
For iLoop := Low(oRenderer.PagePositions) To High(oRenderer.PagePositions) Do
sText := sText + IntegerToString(oRenderer.PagePositions[iLoop])+ ' ';
ProduceText('PagePositions', sText);
ProduceClose('renderer');
End;
Procedure TWPSystemSnapshotWriter.ProduceRanges(oRanges: TWPRangeManager; oPrimary: TWPVisualRange);
Var
iLoop : Integer;
Begin
ProduceOpen('Ranges');
For iLoop := 0 To oRanges.List.Count - 1 Do
Begin
If oRanges.List[iLoop] = oPrimary Then
Begin
Attributes.Match['PageHeight'] := IntegerToString(oPrimary.PageHeight);
Attributes.Match['Primary'] := 'True';
End;
ProduceRange(oRanges.List[iLoop]);
End;
ProduceClose('Ranges');
ProduceOpen('Log');
for iLoop := 0 to oPrimary.Log.Count - 1 do
begin
Attributes.Match['Time'] := oPrimary.Log[iLoop].Time;
Attributes.Match['Action'] := oPrimary.Log[iLoop].Action;
Attributes.Match['Selection'] := oPrimary.Log[iLoop].Selection;
Attributes.Match['Details'] := oPrimary.Log[iLoop].Details;
Attributes.Match['Outcome'] := oPrimary.Log[iLoop].outcome;
ProduceTag('Action');
end;
ProduceClose('Log');
End;
Procedure TWPSystemSnapshotWriter.ProduceRange(oRange: TWPRange);
Var
aLoop : TWPCapability;
iLoop : Integer;
sText : String;
Begin
Attributes.Match['rangeId'] := IntegerToString(oRange.Id);
Attributes.Match['Style'] := oRange.Style;
ProduceOpen('Range');
sText := '';
For aLoop := Low(TWPCapability) To High(TWPCapability) Do
sText := sText + WPCAPABILITY_NAMES[aLoop]+' ';
ProduceText('Capabilities', sText);
ProduceFormat(oRange.Font);
ProduceParaFormat(oRange.Paragraph);
ProduceSelection(oRange.Selection);
If oRange.HasCurrentParagraph Then
Attributes.Match['CurrentParagraph'] := GetId(oRange.CurrentParagraph);
If oRange.HasCurrentImage Then
Attributes.Match['CurrentImage'] := GetId(oRange.CurrentImage);
If oRange.HasCurrentLine Then
Attributes.Match['CurrentLine'] := GetId(oRange.CurrentLine);
If oRange.HasCurrentSectionStart Then
Attributes.Match['CurrentSectionStart'] := GetId(oRange.CurrentSectionStart);
If oRange.HasCurrentSectionStop Then
Attributes.Match['CurrentSectionStop'] := GetId(oRange.CurrentSectionStop);
If oRange.HasCurrentFieldStart Then
Attributes.Match['CurrentFieldStart'] := GetId(oRange.CurrentFieldStart);
If oRange.HasCurrentFieldStop Then
Attributes.Match['CurrentFieldStop'] := GetId(oRange.CurrentFieldStop);
If oRange.HasCurrentTableStart Then
Attributes.Match['CurrentTableStart'] := GetId(oRange.CurrentTableStart);
If oRange.HasCurrentTableStop Then
Attributes.Match['CurrentTableStop'] := GetId(oRange.CurrentTableStop);
If oRange.HasCurrentTableRowStart Then
Attributes.Match['CurrentTableRowStart'] := GetId(oRange.CurrentTableRowStart);
If oRange.HasCurrentTableRowStop Then
Attributes.Match['CurrentTableRowStop'] := GetId(oRange.CurrentTableRowStop);
If oRange.HasCurrentTableCellStart Then
Attributes.Match['CurrentTableCellStart'] := GetId(oRange.CurrentTableCellStart);
If oRange.HasCurrentTableCellStop Then
Attributes.Match['CurrentTableCellStop'] := GetId(oRange.CurrentTableCellStop);
If oRange.HasSelectedTable Then
Attributes.Match['SelectedTable'] := GetId(oRange.SelectedTable);
sText := '';
For iLoop := 0 To oRange.SelectedRows.Count - 1 Do
sText := sText + GetId(oRange.SelectedRows[iLoop])+' ';
Attributes.Match['SelectedRows'] := sText;
sText := '';
For iLoop := 0 To oRange.SelectedCells.Count - 1 Do
sText := sText + GetId(oRange.SelectedCells[iLoop])+' ';
Attributes.Match['SelectedCells'] := sText;
ProduceTag('Current');
ProduceClose('Range');
End;
Procedure TWPSystemSnapshotWriter.ProduceSelection(oSelection: TWPSelection);
Begin
Attributes.Match['SelStart'] := IntegerToString(oSelection.SelStart);
Attributes.Match['Cursor'] := IntegerToString(oSelection.Cursor);
Attributes.Match['SelEnd'] := IntegerToString(oSelection.SelEnd);
Attributes.Match['Desired'] := IntegerToString(oSelection.Desired);
ProduceTag('Selection');
End;
Procedure TWPSystemSnapshotWriter.ProduceOperator(oOperator: TWPOperator);
Var
iLoop : Integer;
Begin
Attributes.Match['MasterRangeId'] := IntegerToString(oOperator.MasterRangeId);
Attributes.Match['Version'] := IntegerToString(oOperator.Version);
Attributes.Match['CurrentOp'] := BooleanToString(oOperator.CurrentOp <> Nil);
Attributes.Match['Status'] := NAMES_WPOPERATIONSTATUS[oOperator.Status];
Attributes.Match['RendererRange.Valid'] := BooleanToString(oOperator.RendererRange.Valid);
Attributes.Match['RendererRange.Start'] := IntegerToString(oOperator.RendererRange.Start);
Attributes.Match['RendererRange.Stop'] := IntegerToString(oOperator.RendererRange.Stop);
Attributes.Match['MaxUndoDepth'] := IntegerToString(oOperator.MaxUndoDepth);
Attributes.Match['DirectCount'] := IntegerToString(oOperator.DirectCount);
Attributes.Match['DirectText'] := oOperator.DirectText;
Attributes.Match['LastAction'] := IntegerToString(oOperator.LastAction);
ProduceOpen('operator');
ProduceOpen('Undo');
For iLoop := 0 To oOperator.UndoStack.Count - 1 Do
ProduceOperation(oOperator.UndoStack[iLoop]);
ProduceClose('Undo');
ProduceOpen('Redo');
For iLoop := 0 To oOperator.RedoStack.Count - 1 Do
ProduceOperation(oOperator.RedoStack[iLoop]);
ProduceClose('Redo');
ProduceClose('operator');
End;
Procedure TWPSystemSnapshotWriter.ProduceOperation(oOperation: TWPOperation);
Var
iLoop : Integer;
Begin
Attributes.Match['RangeId'] := IntegerToString(oOperation.RangeId);
Attributes.Match['Closed'] := BooleanToString(oOperation.Closed);
Attributes.Match['OpType'] := NAMES_WPOPERATIONTYPE[oOperation.OpType];
Attributes.Match['Start'] := IntegerToString(oOperation.Start);
Attributes.Match['CommencementFinish'] := IntegerToString(oOperation.CommencementFinish);
Attributes.Match['TerminationFinish'] := IntegerToString(oOperation.TerminationFinish);
Attributes.Match['MoveDestination'] := IntegerToString(oOperation.MoveDestination);
Attributes.Match['UndoCursor'] := oOperation.UndoCursor;
Attributes.Match['RedoCursor'] := oOperation.RedoCursor;
Attributes.Match['AddedAmount'] := IntegerToString(oOperation.AddedAmount);
Attributes.Match['AddedAmountThisIteration'] := IntegerToString(oOperation.AddedAmountThisIteration);
Attributes.Match['DeletedAmount'] := IntegerToString(oOperation.DeletedAmount);
Attributes.Match['Reiterating'] := BooleanToString(oOperation.Reiterating);
Attributes.Match['AddedText'] := oOperation.AddedText;
Attributes.Match['AddedTextThisIteration'] := oOperation.AddedTextThisIteration;
ProduceOpen('Operation');
ProduceOpen('OriginalPieces');
For iLoop := 0 To oOperation.OriginalPieces.Count - 1 Do
ProducePiece(oOperation.OriginalPieces[iLoop]);
ProduceClose('OriginalPieces');
ProduceOpen('ModifiedPieces');
For iLoop := 0 To oOperation.ModifiedPieces.Count - 1 Do
ProducePiece(oOperation.ModifiedPieces[iLoop]);
ProduceClose('ModifiedPieces');
ProduceOpen('UndoCursors');
For iLoop := 0 To oOperation.UndoCursors.Count - 1 Do
ProduceText(oOperation.UndoCursors.KeyByIndex[iLoop], IntegerToString(oOperation.UndoCursors.ValueByIndex[iLoop]));
ProduceClose('UndoCursors');
ProduceClose('Operation');
End;
Procedure TWPSystemSnapshotWriter.ProduceSettings(oSettings : TWPSettings);
Begin
ProduceOpen('settings');
ProduceText('Background', ColourToString(oSettings.Background));
ProduceText('LowLight', BooleanToString(oSettings.LowLight));
ProduceText('Margin', IntegerToString(oSettings.Margin));
ProduceText('HorizontalMargin', IntegerToString(oSettings.HorizontalMargin));
ProduceText('VerticalMargin', IntegerToString(oSettings.VerticalMargin));
ProduceText('Scale', RealToString(oSettings.Scale));
ProduceText('TableBorders', BooleanToString(oSettings.TableBorders));
ProduceText('NestingIndent', IntegerToString(oSettings.NestingIndent));
ProduceText('Pagination', BooleanToString(oSettings.Pagination));
ProduceText('LinkColour', ColourToString(oSettings.LinkColour));
ProduceText('HoverColour', ColourToString(oSettings.HoverColour));
ProduceText('Hotspots', NAMES_WPHotspotMode[oSettings.Hotspots]);
ProduceText('EditHints', BooleanToString(oSettings.EditHints));
ProduceText('SpellingErrors', BooleanToString(oSettings.SpellingErrors));
ProduceText('FieldWrappers', NAMES_WPFieldPresentation[oSettings.FieldWrappers]);
ProduceText('Interactive', BooleanToString(oSettings.Interactive));
ProduceText('ReadOnly', BooleanToString(oSettings.ReadOnly));
ProduceText('Images', BooleanToString(oSettings.Images));
ProduceText('ImageMapEditing', BooleanToString(oSettings.ImageMapEditing));
ProduceText('Format', BooleanToString(oSettings.Format));
ProduceText('Selecting', BooleanToString(oSettings.Selecting));
ProduceText('Blinking', BooleanToString(oSettings.Blinking));
ProduceText('ShowVerticalScrollbar', BooleanToString(oSettings.ShowVerticalScrollbar));
ProduceText('Search', BooleanToString(oSettings.Search));
ProduceText('AllowPopup', BooleanToString(oSettings.AllowPopup));
ProduceText('SnapshotEmail', oSettings.SnapshotEmail);
ProduceText('ShowDocumentInspector', BooleanToString(oSettings.ShowDocumentInspector));
ProduceText('NoSelectReadOnly', BooleanToString(oSettings.NoSelectReadOnly));
ProduceText('InsertTemplates', BooleanToString(oSettings.InsertTemplates));
ProduceText('AutosavePath', oSettings.AutosavePath);
ProduceText('AutosaveFrequency', IntegerToString(oSettings.AutosaveFrequency));
ProduceText('AutosaveId', oSettings.AutosaveId);
ProduceClose('settings');
End;
End.
| 31.921045 | 246 | 0.699283 |
47ca4b09d4c15b65352e1bd4c2d7675436326c6f | 17 | pas | Pascal | VERSION.pas | gitter-badger/puremvc-delphi-standard-framework-1 | 8c30be4c3d234d4d2883a4ef282c4080458aadc1 | [
"BSD-3-Clause"
]
| 12 | 2017-02-24T00:28:03.000Z | 2021-02-25T16:34:17.000Z | VERSION.pas | gitter-badger/puremvc-delphi-standard-framework-1 | 8c30be4c3d234d4d2883a4ef282c4080458aadc1 | [
"BSD-3-Clause"
]
| null | null | null | VERSION.pas | gitter-badger/puremvc-delphi-standard-framework-1 | 8c30be4c3d234d4d2883a4ef282c4080458aadc1 | [
"BSD-3-Clause"
]
| 10 | 2015-10-31T09:50:18.000Z | 2020-11-18T14:58:06.000Z | VERSION = '1.2.0' | 17 | 17 | 0.588235 |
834d54001b90be37991c280e6a8183ddc3d7823a | 28,732 | pas | Pascal | lib/sgImages.pas | jacobmilligan/deadfall-uni | 1bb9c7c8eb961b556bc0737783b840ebb0c5d6ab | [
"MIT",
"Unlicense"
]
| null | null | null | lib/sgImages.pas | jacobmilligan/deadfall-uni | 1bb9c7c8eb961b556bc0737783b840ebb0c5d6ab | [
"MIT",
"Unlicense"
]
| null | null | null | lib/sgImages.pas | jacobmilligan/deadfall-uni | 1bb9c7c8eb961b556bc0737783b840ebb0c5d6ab | [
"MIT",
"Unlicense"
]
| 1 | 2019-03-30T16:33:07.000Z | 2019-03-30T16:33:07.000Z | //=============================================================================
// sgImages.pas
//=============================================================================
//
// The Images unit contains the code related to manipulating and querying
// bitmap structures.
//
//=============================================================================
/// The Images module contains the code that relates to the manipulating and
/// querying of bitmap structures.
///
/// @module Images
/// @static
unit sgImages;
//=============================================================================
interface
uses sgTypes;
//=============================================================================
//----------------------------------------------------------------------------
// Bitmap loading routines
//----------------------------------------------------------------------------
/// Creates a bitmap in memory that is the specified width and height (in pixels).
/// The new bitmap is initially transparent and can be used as the target
/// for various drawing operations. Once you have drawn the desired image onto
/// the bitmap you can call OptimiseBitmap to optimise the surface.
///
/// @lib
/// @sn createBitmapWidth:%s height:%s
///
/// @class Bitmap
/// @constructor
/// @csn initWithWidth:%s andHeight:%s
function CreateBitmap(width, height: Longint): Bitmap; overload;
/// Creates a bitmap in memory that is the specified width and height (in pixels).
/// The new bitmap is initially transparent and can be used as the target
/// for various drawing operations. Once you have drawn the desired image onto
/// the bitmap you can call OptimiseBitmap to optimise the surface.
///
/// @lib CreateBitmapNamed
/// @sn createBitmapNamed:%s width:%s height:%s
///
/// @class Bitmap
/// @constructor
/// @csn initNamed:%s withWidth:%s andHeight:%s
function CreateBitmap(const name: String; width, height: Longint): Bitmap; overload;
/// Loads a bitmap from file into a Bitmap variable. This can then be drawn to
/// the screen. Bitmaps can be of bmp, jpeg, gif, png, etc. Images may also
/// contain alpha values, which will be drawn correctly by the API. All
/// bitmaps must be freed using the FreeBitmap once you are finished with
/// them.
///
/// @lib
/// @sn loadBitmapFile:%s
///
/// @class Bitmap
/// @constructor
/// @csn initWithPath:%s
function LoadBitmap(const filename : String): Bitmap; overload;
/// Frees a loaded bitmap. Use this when you will no longer be drawing the
/// bitmap (including within Sprites), and when the program exits.
///
/// @lib
///
/// @class Bitmap
/// @dispose
procedure FreeBitmap(bitmapToFree : Bitmap);
//----------------------------------------------------------------------------
// Bitmap mapping routines
//----------------------------------------------------------------------------
/// Loads and returns a bitmap. The supplied ``filename`` is used to
/// locate the Bitmap to load. The supplied ``name`` indicates the
/// name to use to refer to this Bitmap in SwinGame. The `Bitmap` can then be
/// retrieved by passing this ``name`` to the `BitmapNamed` function.
///
/// @lib
/// @sn loadBitmapNamed:%s fromFile:%s
///
/// @class Bitmap
/// @constructor
/// @csn initWithName:%s fromFile:%s
function LoadBitmapNamed(const name, filename: String): Bitmap;
/// Determines if SwinGame has a bitmap loaded for the supplied name.
/// This checks against all bitmaps loaded, those loaded without a name
/// are assigned the filename as a default.
///
/// @lib
function HasBitmap(const name: String): Boolean;
/// Returns the `Bitmap` that has been loaded with the specified name,
/// see `LoadBitmapNamed`.
///
/// @lib
function BitmapNamed(const name: String): Bitmap;
/// Releases the SwinGame resources associated with the bitmap of the
/// specified ``name``.
///
/// @lib
procedure ReleaseBitmap(const name: String);
/// Releases all of the bitmaps that have been loaded.
///
/// @lib
procedure ReleaseAllBitmaps();
//---------------------------------------------------------------------------
// Bitmap querying functions
//---------------------------------------------------------------------------
/// Returns the width of the entire bitmap.
///
/// @lib
///
/// @class Bitmap
/// @getter Width
function BitmapWidth(bmp: Bitmap): Longint; overload;
/// Returns the height of the entire bitmap.
///
/// @lib
///
/// @class Bitmap
/// @getter Height
function BitmapHeight(bmp: Bitmap): Longint; overload;
/// Returns the width of a cell within the bitmap.
///
/// @lib
///
/// @class Bitmap
/// @getter CellWidth
function BitmapCellWidth(bmp: Bitmap): Longint;
/// Returns the height of a cell within the bitmap.
///
/// @lib
///
/// @class Bitmap
/// @getter CellHeight
function BitmapCellHeight(bmp: Bitmap): Longint;
/// Checks if a pixel is drawn at the specified x,y location.
///
/// @lib
/// @sn pixelOf:%s drawnAtX:%s y:%s
///
/// @class Bitmap
/// @method PixelDrawnAtPoint
/// @csn pixelDrawnAtX:%s y:%s
function PixelDrawnAtPoint(bmp: Bitmap; x, y: Single): Boolean;
/// This is used to define the number of cells in a bitmap, and
/// their width and height. The cells are
/// traversed in rows so that the format would be [0 - 1 - 2]
/// [3 - 4 - 5] etc. The count can be used to restrict which of the
/// parts of the bitmap actually contain cells that can be drawn.
///
/// @lib
/// @sn bitmap:%s setCellWidth:%s height:%s columns:%s rows:%s count:%s
///
/// @class Bitmap
/// @method SetCellDetails
/// @csn setCellWidth:%s height:%s columns:%s rows:%s count:%s
procedure BitmapSetCellDetails(bmp: Bitmap; width, height, columns, rows, count: Longint);
/// Returns the number of cells in the specified bitmap.
///
/// @lib
///
/// @class Bitmap
/// @getter CellCount
function BitmapCellCount(bmp: Bitmap): Longint;
/// Returns the number of rows of cells in the specified bitmap.
///
/// @lib
///
/// @class Bitmap
/// @getter CellRows
function BitmapCellRows(bmp: Bitmap): Longint;
/// Returns the number of columns of cells in the specified bitmap.
///
/// @lib
///
/// @class Bitmap
/// @getter CellColumns
function BitmapCellColumns(bmp: Bitmap): Longint;
/// Are the two bitmaps of a similar format that they could be used in
/// place of each other. This returns true if they have the same cell
/// details (count, width, and height).
///
/// @lib
/// @sn bitmap: %s interchangableWith:%s
///
/// @class Bitmap
/// @method interchangableWith
function BitmapsInterchangable(bmp1, bmp2: Bitmap): Boolean;
/// Returns the name of the bitmap
///
/// @lib
///
/// @class Bitmap
/// @getter Name
function BitmapName(bmp:Bitmap): string;
/// Returns the Filename of the bitmap
///
/// @lib
///
/// @class Bitmap
/// @getter Filename
function BitmapFilename(bmp:Bitmap): string;
//----------------------------------------------------------------------------
// Bitmap -> Circle
//----------------------------------------------------------------------------
/// Creates a circle from within a bitmap, uses the larger of the width and
/// height.
///
/// @lib
/// @sn circleFrombitmap:%s atPt:%s
///
/// @class Bitmap
/// @method ToCircle
/// @csn circleAtPt:%s
function BitmapCircle(bmp: Bitmap; const pt: Point2D): Circle; overload;
/// Creates a circle from within a bitmap, uses the larger of the width and
/// height.
///
/// @lib BitmapCircleXY
/// @sn circleFromBitmap:%s atX:%s y:%s
///
/// @class Bitmap
/// @overload ToCircle ToCircleXY
/// @csn circleAtX:%s y:%s
function BitmapCircle(bmp: Bitmap; x, y: Single): Circle; overload;
/// Creates a circle from within a cell in a bitmap, uses the larger of the width and
/// height.
///
/// @lib
/// @sn circleFromBitmap:%s cellAtPt:%s
///
/// @class Bitmap
/// @method ToCellCircle
/// @csn circleCellAtPT:%s
function BitmapCellCircle(bmp: Bitmap; const pt: Point2D): Circle; overload;
/// Creates a circle that will encompass a cell of the passed in bitmap if it
/// were drawn at the indicated point, with the specified scale.
///
/// @lib BitmapCellCircleScale
/// @sn circleFromBitmapCell:%s atPt:%s scale:%s
///
/// @class Bitmap
/// @method ToCellCircle
/// @csn circleCellAtPT:%s scale:%s
function BitmapCellCircle(bmp: Bitmap; const pt: Point2D; scale: Single): Circle; overload;
/// Creates a circle from within a cell in a bitmap, uses the larger of the width and
/// height.
///
/// @lib BitmapCellCircleXY
/// @sn circleBitmap:%s cellAtX:%s y:%s
///
/// @class Bitmap
/// @overload ToCellCircle ToCellCircleXY
/// @csn circleCellAtX:%s y:%s
function BitmapCellCircle(bmp: Bitmap; x, y: Single): Circle; overload;
//---------------------------------------------------------------------------
// Collision Mask
//---------------------------------------------------------------------------
/// Setup the passed in bitmap for pixel level collisions.
///
/// @lib
/// @class Bitmap
/// @method SetupForCollisions
procedure SetupBitmapForCollisions(src: Bitmap);
//---------------------------------------------------------------------------
// Bitmap drawing routines - clearing
//---------------------------------------------------------------------------
/// Clear the drawing on the Bitmap to the passed in color.
///
/// @lib
/// @sn clearSurface:%s color:%s
///
/// @class Bitmap
/// @overload ClearSurface ClearSurfaceToColor
/// @csn clearSurfaceTo:%s
procedure ClearSurface(dest: Bitmap; toColor: Color); overload;
/// Clears the drawing on the Bitmap to black.
///
/// @lib ClearSurfaceToBlack
///
/// @class Bitmap
/// @method ClearSurface
procedure ClearSurface(dest: Bitmap); overload;
//---------------------------------------------------------------------------
// Bitmap -> Rectangle functions
//---------------------------------------------------------------------------
/// Returns a bounding rectangle for the bitmap.
///
/// @lib BitmapRectXY
/// @sn rectangleAtX:%s y:%s forBitmap:%s
///
/// @class Bitmap
/// @overload ToRectangle ToRectangleAtXY
/// @self 3
/// @csn toRectangleAtX:%s y:%s
function BitmapRectangle(x, y: Single; bmp: Bitmap): Rectangle; overload;
/// Returns a bounding rectangle for the bitmap, at the origin.
///
/// @lib BitmapRectAtOrigin
///
/// @class Bitmap
/// @overload ToRectangle ToRectangleAtOrigin
/// @csn toRectangleAtOrigin
function BitmapRectangle(bmp: Bitmap): Rectangle; overload;
/// Returns a bounding rectangle for a cell of the bitmap at the origin.
///
/// @lib BitmapCellRectangleAtOrigin
/// @sn rectangleForBitmapCellAtOrigin:%s
///
/// @class Bitmap
/// @overload ToCellRectangle ToCellRectangleAtOrigin
/// @csn toRectangleForCellAtOrigin
function BitmapCellRectangle(bmp: Bitmap): Rectangle; overload;
/// Returns a rectangle for a cell of the bitmap at the indicated point.
///
/// @lib BitmapCellRectangleXY
/// @sn rectangleForCellAtX:%s y:%s forBitmapCell:%s
///
/// @class Bitmap
/// @method ToCellRectangle
/// @self 3
/// @csn toRectangleForCellAtX:%s y:%s
function BitmapCellRectangle(x, y: Single; bmp: Bitmap): Rectangle; overload;
/// Returns a rectangle for the location of the indicated cell within the
/// bitmap.
///
/// @lib
/// @sn bitmap:%s rectangleOfCell:%s
///
/// @class Bitmap
/// @method CellRectangle
/// @csn rectangleCell:%s
function BitmapRectangleOfCell(src: Bitmap; cell: Longint): Rectangle;
//---------------------------------------------------------------------------
// Bitmap drawing routines - onto bitmap
//---------------------------------------------------------------------------
/// Draw the bitmap using the passed in options
///
/// @lib DrawBitmapWithOpts
/// @sn drawBitmap:%s atX:%s y:%s withOptions:%s
///
/// @class Bitmap
/// @method DrawWithOpts
/// @csn drawAtX:%s y:%s withOptions:%s
procedure DrawBitmap(src: Bitmap; x, y: Single; const opts: DrawingOptions); overload;
/// Draw the bitmap using the passed in options
///
/// @lib DrawBitmapNamedWithOpts
/// @sn drawBitmapNamed:%s atX:%s y:%s withOptions:%s
procedure DrawBitmap(const name: String; x, y: Single; const opts: DrawingOptions); overload;
//---------------------------------------------------------------------------
// Bitmap drawing routines - standard
//---------------------------------------------------------------------------
/// Draw the passed in bitmap onto the game.
///
/// @lib
/// @sn draw:%s x:%s y:%s
///
/// @class Bitmap
/// @method Draw
/// @csn drawAtX:%s y:%s
///
/// @doc_idx 0
procedure DrawBitmap(src : Bitmap; x, y : Single); overload;
/// Draw the named bitmap onto the game.
///
/// @lib DrawBitmapNamed
/// @sn drawBitmapNamed:%s x:%s y:%s
///
/// @doc_idx 1
procedure DrawBitmap(const name: String; x, y : Single); overload;
/// Draw a cell from a bitmap onto the game.
///
/// @lib DrawCellOpts
/// @sn bitmap:%s drawCell:%s atX:%s y:%s opts:%s
///
/// @class Bitmap
/// @method DrawCell
/// @csn drawCell:%s atX:%s y:%s opts:%s
procedure DrawCell(src: Bitmap; cell: Longint; x, y: Single; const opts : DrawingOptions); overload;
/// Draw a cell from a bitmap onto the game.
///
/// @lib DrawCell
/// @sn bitmap:%s drawCell:%s atX:%s y:%s
///
/// @class Bitmap
/// @method DrawCell
/// @csn drawCell:%s atX:%s y:%s
procedure DrawCell(src: Bitmap; cell: Longint; x, y: Single); overload;
//---------------------------------------------------------------------------
// Bitmap Saving
//---------------------------------------------------------------------------
/// Save Bitmap to specific directory.
///
/// @lib
/// @sn bitmap:%s saveToFile:%s
///
/// @class Bitmap
/// @method Save
/// @csn saveToFile:%s
procedure SaveBitmap(src: Bitmap; const filepath: String);
//=============================================================================
implementation
uses sgResources, sgCamera, sgGeometry, sgGraphics,
sgDriverImages, sgDriver, sgDrawingOptions,
stringhash, // libsrc
SysUtils,
sgShared, sgTrace, sgBackendTypes, sgDriverSDL2Types;
//=============================================================================
var
_Images: TStringHash;
//----------------------------------------------------------------------------
function CreateBitmap(width, height: Longint): Bitmap;
begin
result := CreateBitmap('Bitmap', width, height);
end;
function CreateBitmap(const name: String; width, height: Longint): Bitmap; overload;
var
realName: String;
idx: Longint;
obj: tResourceContainer;
begin
{$IFDEF TRACE}
TraceEnter('sgImages', 'CreateBitmap');
{$ENDIF}
result := nil;
if (width < 1) or (height < 1) then
begin
RaiseWarning('Bitmap width and height must be greater then 0');
exit;
end;
realName := name;
idx := 0;
while _Images.containsKey(realName) do
begin
realName := name + '_' + IntToStr(idx);
idx := idx + 1;
end;
result := Bitmap(sgDriverImages.CreateBitmap(realName, width, height));
if (not Assigned(result)) then
begin
RaiseWarning('Failed to create a bitmap: ' + Driver.GetError());
exit;
end;
//
// Place the bitmap in the _Images hashtable
//
obj := tResourceContainer.Create(result);
if not _Images.setValue(realName, obj) then
begin
FreeBitmap(result);
result := nil;
RaiseException('Error creating bitmap: ' + realName);
exit;
end;
{$IFDEF TRACE}
TraceExit('sgImages', 'CreateBitmap', realName + ' = ' + HexStr(result));
{$ENDIF}
end;
function CombineIntoGrid(const bitmaps: BitmapArray; cols: LongInt): Bitmap;
var
i, w, h, rows: Integer;
opts: DrawingOptions;
begin
result := nil;
w := 0;
h := 0;
for i := Low(bitmaps) to High(bitmaps) do
begin
if BitmapWidth(bitmaps[i]) > w then w := BitmapWidth(bitmaps[i]);
if BitmapHeight(bitmaps[i]) > h then h := BitmapWidth(bitmaps[i]);
end;
if Length(bitmaps) < 1 then exit;
if cols < 1 then exit;
if (w = 0) or (h = 0) then exit;
rows := Length(bitmaps) div cols;
if Length(bitmaps) mod cols > 0 then
rows += 1;
result := CreateBitmap(w * cols, h * rows);
opts := OptionDrawTo(result);
for i := Low(bitmaps) to High(bitmaps) do
begin
DrawBitmap(bitmaps[i], (i mod cols) * w, (i div cols) * h, opts);
end;
BitmapSetCellDetails(result, w, h, cols, rows, Length(bitmaps));
end;
function LoadBitmapNamed(const name, filename: String): Bitmap;
var
obj: tResourceContainer;
fn: String;
begin
if _Images.containsKey(name) then
begin
result := BitmapNamed(name);
exit;
end;
result := nil; //start at nil to exit cleanly on error
fn := filename;
// Check for file
if not FileExists(fn) then
begin
fn := PathToResource(fn, BitmapResource);
if not FileExists(fn) then
begin
RaiseWarning('Unable to locate bitmap ' + fn);
exit;
end;
end;
result := Bitmap(sgDriverImages.LoadBitmap(name, fn));
// if it failed to load then exit
if not Assigned(result) then
begin
RaiseWarning('Error loading image ' + fn);
exit;
end;
// Place the bitmap in the _Images hashtable
obj := tResourceContainer.Create(result);
if not _Images.setValue(name, obj) then
begin
FreeBitmap(result);
RaiseException('Error loaded Bitmap resource twice: ' + name + ' for file ' + fn);
exit;
end;
end;
function LoadBitmap(const filename: String): Bitmap;
begin
result := Bitmap(LoadBitmap(filename, filename));
end;
procedure FreeBitmap(bitmapToFree : Bitmap);
var
b: BitmapPtr;
begin
b := ToBitmapPtr(bitmapToFree);
if Assigned(b) then
begin
//Notify others that this is now gone!
CallFreeNotifier(bitmapToFree);
//Remove the image from the hashtable
_Images.remove(BitmapName(bitmapToFree)).Free();
sgDriverImages.FreeBitmap(b);
//Dispose the pointer
b^.id := NONE_PTR;
Dispose(b);
end;
end;
//----------------------------------------------------------------------------
function HasBitmap(const name: String): Boolean;
begin
result := _Images.containsKey(name);
end;
function BitmapNamed(const name: String): Bitmap;
var
tmp : TObject;
filename: String;
begin
{$IFDEF TRACE}
TraceEnter('sgImages', 'BitmapNamed', 'name = ' + name);
{$ENDIF}
tmp := _Images.values[name];
if assigned(tmp) then
result := Bitmap(tResourceContainer(tmp).Resource)
else
begin
filename := PathToResource(name, BitmapResource);
if FileExists(name) or FileExists(filename) then
begin
result := LoadBitmapNamed(name, name);
end
else
begin
RaiseWarning('Unable to find bitmap named: ' + name);
result := nil;
end;
end;
{$IFDEF TRACE}
TraceExit('sgImages', 'BitmapNamed = ' + HexStr(result));
{$ENDIF}
end;
procedure ReleaseBitmap(const name: String);
var
bmp: Bitmap;
begin
{$IFDEF TRACE}
TraceEnter('sgImages', 'ReleaseBitmap', 'name = ' + name);
{$ENDIF}
bmp := BitmapNamed(name);
if (assigned(bmp)) then
begin
FreeBitmap(bmp);
end;
{$IFDEF TRACE}
TraceExit('sgImages', 'ReleaseBitmap');
{$ENDIF}
end;
procedure ReleaseAllBitmaps();
begin
ReleaseAll(_Images, @ReleaseBitmap);
end;
//----------------------------------------------------------------------------
function PixelDrawnAtPoint(bmp: Bitmap; x, y: Single): Boolean;
var
b: BitmapPtr;
begin
b := ToBitmapPtr(bmp);
if not Assigned(b) then result := false
else result := (Length(b^.nonTransparentPixels) = b^.image.surface.width)
and ((x >= 0) and (x < b^.image.surface.width))
and ((y >= 0) and (y < b^.image.surface.height))
and b^.nonTransparentPixels[Round(x), Round(y)];
end;
procedure BitmapSetCellDetails(bmp: Bitmap; width, height, columns, rows, count: Longint);
var
b: BitmapPtr;
begin
b := ToBitmapPtr(bmp);
if not Assigned(b) then exit;
b^.cellW := width;
b^.cellH := height;
b^.cellCols := columns;
b^.cellRows := rows;
b^.cellCount := count;
end;
function BitmapCellCount(bmp: Bitmap): Longint;
var
b: BitmapPtr;
begin
b := ToBitmapPtr(bmp);
if not Assigned(b) then result := 0
else result := b^.cellCount;
end;
function BitmapCellRows(bmp: Bitmap): Longint;
var
b: BitmapPtr;
begin
b := ToBitmapPtr(bmp);
if not Assigned(b) then result := 0
else result := b^.cellRows;
end;
function BitmapCellColumns(bmp: Bitmap): Longint;
var
b: BitmapPtr;
begin
b := ToBitmapPtr(bmp);
if not Assigned(b) then result := 0
else result := b^.cellCols;
end;
function BitmapsInterchangable(bmp1, bmp2: Bitmap): Boolean;
var
b1, b2: BitmapPtr;
begin
b1 := ToBitmapPtr(bmp1);
b2 := ToBitmapPtr(bmp2);
if (not assigned(b1)) or (not assigned(b2)) then
result := false
else
result := (b1^.cellCount = b2^.cellCount) and
(b1^.cellW = b2^.cellW) and
(b1^.cellH = b2^.cellH);
end;
//---------------------------------------------------------------------------
procedure SetupBitmapForCollisions(src: Bitmap);
var
b: BitmapPtr;
begin
b := ToBitmapPtr(src);
if not assigned(b) then exit;
if Length(b^.nonTransparentPixels) <> 0 then exit;
sgDriverImages.SetupCollisionMask(b);
end;
//---------------------------------------------------------------------------
/// Draws one bitmap (src) onto another bitmap (dest).
///
/// @param dest: The destination bitmap - not optimised!
/// @param src: The bitmap to be drawn onto the destination
/// @param x,y: The x,y location to draw the bitmap to
///
/// Side Effects:
/// - Draws the src at the x,y location in the destination.
procedure DrawBitmap(src: Bitmap; x, y: Single; const opts: DrawingOptions); overload;
var
b: BitmapPtr;
begin
{$IFDEF TRACE}
TraceEnter('sgImages', 'DrawBitmap', 'src = ' + HexStr(src));
try
{$ENDIF}
b := ToBitmapPtr(src);
if (not Assigned(opts.dest)) or (not Assigned(b)) then exit;
sgDriverImages.DrawBitmap(b, x, y, opts)
{$IFDEF TRACE}
finally
TraceExit('sgImages', 'DrawBitmap');
end;
{$ENDIF}
end;
procedure DrawBitmap(src: Bitmap; x, y : Single); overload;
begin
DrawBitmap(src, x, y, OptionDefaults());
end;
procedure DrawBitmap(const name: String; x, y : Single; const opts: DrawingOptions); overload;
begin
DrawBitmap(BitmapNamed(name), x, y, opts);
end;
procedure DrawBitmap(const name: String; x, y : Single); overload;
begin
DrawBitmap(BitmapNamed(name), x, y, OptionDefaults());
end;
//---------------------------------------------------------------------------
procedure ClearSurface(dest: Bitmap; toColor: Color); overload;
var
surf: psg_drawing_surface;
begin
surf := ToSurfacePtr(dest);
if Assigned(surf) then
sgDriverImages.ClearSurface(surf, toColor);
end;
procedure ClearSurface(dest: Bitmap); overload;
begin
ClearSurface(dest, ColorBlack);
end;
//---------------------------------------------------------------------------
procedure DrawCell(src: Bitmap; cell: Longint; x, y: Single; const opts : DrawingOptions); overload;
begin
DrawBitmap(src, x, y, OptionPartBmp(BitmapRectangleOfCell(src, cell), opts));
end;
procedure DrawCell(src: Bitmap; cell: Longint; x, y: Single); overload;
begin
DrawCell(src, cell, x, y, OptionDefaults());
end;
//---------------------------------------------------------------------------
function BitmapRectangle(x, y: Single; bmp: Bitmap): Rectangle; overload;
var
b: BitmapPtr;
begin
b := ToBitmapPtr(bmp);
if not Assigned(b) then result := RectangleFrom(0,0,0,0)
else result := RectangleFrom(x, y, b^.image.surface.width, b^.image.surface.height);
end;
function BitmapRectangle(bmp: Bitmap): Rectangle; overload;
begin
result := BitmapRectangle(0,0,bmp);
end;
function BitmapCellRectangle(x, y: Single; bmp: Bitmap): Rectangle; overload;
var
b: BitmapPtr;
begin
b := ToBitmapPtr(bmp);
if not Assigned(b) then result := RectangleFrom(0,0,0,0)
else result := RectangleFrom(x, y, b^.cellW, b^.cellH);
end;
function BitmapCellRectangle(bmp: Bitmap): Rectangle; overload;
begin
result := BitmapCellRectangle(0, 0, bmp);
end;
function _BitmapRectangleOfCell(b: BitmapPtr; cell: Longint): Rectangle;
begin
if (not assigned(b)) or (cell >= b^.cellCount) then
result := RectangleFrom(0,0,0,0)
else if (cell < 0) then
begin
result := RectangleFrom(0,0,b^.image.surface.width,b^.image.surface.width);
end
else
begin
result.x := (cell mod b^.cellCols) * b^.cellW;
result.y := (cell - (cell mod b^.cellCols)) div b^.cellCols * b^.cellH;
result.width := b^.cellW;
result.height := b^.cellH;
end;
end;
function BitmapRectangleOfCell(src: Bitmap; cell: Longint): Rectangle;
begin
result := _BitmapRectangleOfCell(ToBitmapPtr(src), cell);
end;
function BitmapWidth(bmp: Bitmap): Longint; overload;
var
b: BitmapPtr;
begin
b := ToBitmapPtr(bmp);
if not assigned(b) then result := 0
else result := b^.image.surface.width;
end;
function BitmapHeight(bmp: Bitmap): Longint; overload;
var
b: BitmapPtr;
begin
b := ToBitmapPtr(bmp);
if not assigned(b) then result := 0
else result := b^.image.surface.height;
end;
function BitmapCellWidth(bmp: Bitmap): Longint;
var
b: BitmapPtr;
begin
b := ToBitmapPtr(bmp);
if not assigned(b) then result := 0
else result := b^.cellW;
end;
function BitmapCellHeight(bmp: Bitmap): Longint;
var
b: BitmapPtr;
begin
b := ToBitmapPtr(bmp);
if not assigned(b) then result := 0
else result := b^.cellH;
end;
function BitmapName(bmp:Bitmap): string;
var
b: BitmapPtr;
begin
b := ToBitmapPtr(bmp);
result:= '';
if not assigned(b) then exit;
result:=b^.name;
end;
function BitmapFilename(bmp:Bitmap): string;
var
b: BitmapPtr;
begin
b := ToBitmapPtr(bmp);
result:= '';
if not assigned(b) then exit;
result:=b^.filename;
end;
function BitmapCircle(bmp: Bitmap; x, y: Single): Circle; overload;
begin
result := BitmapCircle(bmp, PointAt(x, y));
end;
function BitmapCircle(bmp: Bitmap; const pt: Point2D): Circle; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgImages', 'BitmapCircle', '');
{$ENDIF}
result.center := pt;
if BitmapWidth(bmp) > BitmapHeight(bmp) then
result.radius := RoundInt(BitmapWidth(bmp) / 2.0)
else
result.radius := RoundInt(BitmapHeight(bmp) / 2.0);
{$IFDEF TRACE}
TraceExit('sgImages', 'BitmapCircle', '');
{$ENDIF}
end;
function BitmapCellCircle(bmp: Bitmap; x, y: Single): Circle; overload;
begin
result := BitmapCellCircle(bmp, PointAt(x, y), 1.0);
end;
function BitmapCellCircle(bmp: Bitmap; const pt: Point2D): Circle; overload;
begin
result := BitmapCellCircle(bmp, pt, 1.0);
end;
function BitmapCellCircle(bmp: Bitmap; const pt: Point2D; scale: Single): Circle; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgImages', 'BitmapCellCircle', '');
{$ENDIF}
result.center := pt;
if BitmapCellWidth(bmp) > BitmapCellHeight(bmp) then
result.radius := Abs(RoundInt(BitmapCellWidth(bmp) / 2.0) * scale)
else
result.radius := Abs(RoundInt(BitmapCellHeight(bmp) / 2.0) * scale);
{$IFDEF TRACE}
TraceExit('sgImages', 'BitmapCellCircle', '');
{$ENDIF}
end;
//---------------------------------------------------------------------------
procedure SaveBitmap(src: Bitmap; const filepath: String);
var
surface: psg_drawing_surface;
begin
surface := ToSurfacePtr(src);
if Assigned(surface) then
sgDriverImages.SaveSurface(surface, filepath);
end;
//=============================================================================
initialization
begin
{$IFDEF TRACE}
TraceEnter('sgImages', 'initialization');
{$ENDIF}
InitialiseSwinGame();
_Images := TStringHash.Create(False, 1024);
{$IFDEF TRACE}
TraceExit('sgImages', 'initialization');
{$ENDIF}
end;
finalization
begin
ReleaseAllBitmaps();
FreeAndNil(_Images);
end;
//=============================================================================
end.
//=============================================================================
| 26.677809 | 102 | 0.588925 |
f18e3b8c26af4c549d3853140a202f8b2c89366f | 5,123 | pas | Pascal | CryptoLib.Tests/src/Crypto/SHA1HMacTests.pas | MarkG55/CryptoLib4Pascal | 740f1e7ac86ac9cf009a8010d4384368e7abe6fb | [
"MIT"
]
| 148 | 2018-02-08T23:36:43.000Z | 2022-03-16T01:33:20.000Z | CryptoLib.Tests/src/Crypto/SHA1HMacTests.pas | tondrej/CryptoLib4Pascal | 33a540094aa24d22d84d502319e4d01f7c3e8163 | [
"MIT"
]
| 28 | 2018-08-09T04:14:18.000Z | 2022-03-31T05:23:51.000Z | CryptoLib.Tests/src/Crypto/SHA1HMacTests.pas | tondrej/CryptoLib4Pascal | 33a540094aa24d22d84d502319e4d01f7c3e8163 | [
"MIT"
]
| 46 | 2018-03-18T17:25:59.000Z | 2022-02-07T16:52:15.000Z | { *********************************************************************************** }
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit SHA1HMacTests;
interface
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF FPC}
uses
SysUtils,
{$IFDEF FPC}
fpcunit,
testregistry,
{$ELSE}
TestFramework,
{$ENDIF FPC}
ClpKeyParameter,
ClpHMac,
ClpIMac,
ClpDigestUtilities,
ClpStringUtils,
ClpConverters,
ClpCryptoLibTypes,
CryptoLibTestBase;
type
/// <summary>
/// SHA1 HMac Test, test vectors from RFC 2202
/// </summary>
TTestSHA1HMac = class(TCryptoLibAlgorithmTestCase)
private
var
Fkeys, Fdigests, Fmessages: TCryptoLibStringArray;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestSHA1HMac;
end;
implementation
{ TTestSHA1HMac }
procedure TTestSHA1HMac.SetUp;
begin
inherited;
Fkeys := TCryptoLibStringArray.Create
('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', '4a656665',
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'0102030405060708090a0b0c0d0e0f10111213141516171819',
'0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c',
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa');
Fdigests := TCryptoLibStringArray.Create
('b617318655057264e28bc0b6fb378c8ef146be00',
'effcdf6ae5eb2fa2d27416d5f184df9c259a7c79',
'125d7342b9ac11cd91a39af48aa17b4f63f175d3',
'4c9007f4026250c6bc8414f9bf50c86c2d7235da',
'4c1a03424b55e07fe7f27be1d58bb9324a9a5a04',
'aa4ae5e15272d00e95705637ce8a3b55ed402112',
'e8e99d0f45237d786d6bbaa7965c7808bbff1a91',
'4c1a03424b55e07fe7f27be1d58bb9324a9a5a04',
'aa4ae5e15272d00e95705637ce8a3b55ed402112',
'e8e99d0f45237d786d6bbaa7965c7808bbff1a91');
Fmessages := TCryptoLibStringArray.Create('Hi There',
'what do ya want for nothing?',
'0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd',
'0xcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd',
'Test With Truncation',
'Test Using Larger Than Block-Size Key - Hash Key First',
'Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data');
end;
procedure TTestSHA1HMac.TearDown;
begin
inherited;
end;
procedure TTestSHA1HMac.TestSHA1HMac;
var
hmac: IMac;
resBuf, m, m2: TBytes;
i, vector: Int32;
begin
hmac := THMac.Create(TDigestUtilities.GetDigest('SHA-1'));
System.SetLength(resBuf, hmac.GetMacSize());
for i := 0 to System.Pred(System.Length(Fmessages)) do
begin
m := TConverters.ConvertStringToBytes(Fmessages[i], TEncoding.ASCII);
if (TStringUtils.BeginsWith(Fmessages[i], '0x', True)) then
begin
m := DecodeHex(System.Copy(Fmessages[i], 3,
System.Length(Fmessages[i]) - 2));
end;
hmac.Init(TKeyParameter.Create(DecodeHex(Fkeys[i])));
hmac.BlockUpdate(m, 0, System.Length(m));
hmac.DoFinal(resBuf, 0);
if (not AreEqual(resBuf, DecodeHex(Fdigests[i]))) then
begin
Fail('Vector ' + IntToStr(i) + ' failed');
end;
end;
// test reset
vector := 0; // vector used for test
m2 := TConverters.ConvertStringToBytes(Fmessages[vector], TEncoding.ASCII);
if (TStringUtils.BeginsWith(Fmessages[vector], '0x', True)) then
begin
m2 := DecodeHex(System.Copy(Fmessages[vector], 3,
System.Length(Fmessages[vector]) - 2));
end;
hmac.Init(TKeyParameter.Create(DecodeHex(Fkeys[vector])));
hmac.BlockUpdate(m2, 0, System.Length(m2));
hmac.DoFinal(resBuf, 0);
hmac.Reset();
hmac.BlockUpdate(m2, 0, System.Length(m2));
hmac.DoFinal(resBuf, 0);
if (not AreEqual(resBuf, DecodeHex(Fdigests[vector]))) then
begin
Fail('Reset with vector ' + IntToStr(vector) + ' failed');
end;
end;
initialization
// Register any test cases with the test runner
{$IFDEF FPC}
RegisterTest(TTestSHA1HMac);
{$ELSE}
RegisterTest(TTestSHA1HMac.Suite);
{$ENDIF FPC}
end.
| 31.429448 | 168 | 0.655866 |
838d85a74365ca2ff63c235428e57e3b9a9e9b2a | 2,286 | dfm | Pascal | Filters/FilterSub.dfm | CrossProd/Aardbei_AardbeiTextureStudio | fe07d0c0d8a01492e11cd3f04ec152493ab02aa4 | [
"MIT"
]
| 1 | 2018-01-23T21:46:33.000Z | 2018-01-23T21:46:33.000Z | Filters/FilterSub.dfm | CrossProd/Aardbei_AardbeiTextureStudio | fe07d0c0d8a01492e11cd3f04ec152493ab02aa4 | [
"MIT"
]
| null | null | null | Filters/FilterSub.dfm | CrossProd/Aardbei_AardbeiTextureStudio | fe07d0c0d8a01492e11cd3f04ec152493ab02aa4 | [
"MIT"
]
| null | null | null | object frmSub: TfrmSub
Left = 175
Top = 113
BorderIcons = []
BorderStyle = bsDialog
Caption = 'frmSub'
ClientHeight = 161
ClientWidth = 362
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
OldCreateOrder = False
Position = poMainFormCenter
OnActivate = FormActivate
OnHide = FormHide
PixelsPerInch = 96
TextHeight = 13
object grbColor: TGroupBox
Left = 8
Top = 80
Width = 345
Height = 41
Caption = 'Channel Parameters'
TabOrder = 3
object rdbRed: TRadioButton
Left = 16
Top = 16
Width = 57
Height = 17
Caption = 'Red'
Checked = True
TabOrder = 0
TabStop = True
end
object rdbGreen: TRadioButton
Left = 107
Top = 16
Width = 57
Height = 17
Caption = 'Green'
TabOrder = 1
end
object rdbBlue: TRadioButton
Left = 197
Top = 16
Width = 57
Height = 17
Caption = 'Blue'
TabOrder = 2
end
object rdbAll: TRadioButton
Left = 288
Top = 16
Width = 49
Height = 17
Caption = 'All'
TabOrder = 3
end
end
object btnOk: TButton
Left = 16
Top = 129
Width = 75
Height = 25
Caption = 'Ok'
TabOrder = 0
OnClick = btnOkClick
end
object btnCancel: TButton
Left = 144
Top = 129
Width = 75
Height = 25
Caption = 'Cancel'
TabOrder = 1
OnClick = btnCancelClick
end
object btnPreview: TButton
Left = 271
Top = 129
Width = 75
Height = 25
Caption = 'Preview'
TabOrder = 2
OnClick = btnPreviewClick
end
object grbParameters: TGroupBox
Left = 8
Top = 8
Width = 345
Height = 65
Caption = 'Filter Parameters'
TabOrder = 4
object lblSlider1: TLabel
Left = 16
Top = 18
Width = 66
Height = 13
Caption = 'Source Layer:'
end
object cmbLayer: TComboBox
Left = 24
Top = 35
Width = 137
Height = 21
Style = csDropDownList
ItemHeight = 13
TabOrder = 0
end
end
end
| 19.878261 | 35 | 0.545057 |
f16342b031460bf63c5aaa4fcf96bd7293ecb729 | 40,862 | pas | Pascal | tools/logicEditor/src/LuaLib.pas | laggyluk/brick_engine | 1fc63d8186b4eb12cbfdb3a8b48a901089d3994c | [
"MIT"
]
| 1 | 2019-05-24T19:20:12.000Z | 2019-05-24T19:20:12.000Z | tools/logicEditor/src/LuaLib.pas | laggyluk/brick_engine | 1fc63d8186b4eb12cbfdb3a8b48a901089d3994c | [
"MIT"
]
| null | null | null | tools/logicEditor/src/LuaLib.pas | laggyluk/brick_engine | 1fc63d8186b4eb12cbfdb3a8b48a901089d3994c | [
"MIT"
]
| null | null | null | (******************************************************************************
* Original copyright for the lua source and headers:
* 1994-2004 Tecgraf, PUC-Rio.
* www.lua.org.
*
* Copyright for the Delphi adaptation:
* 2005 Rolf Meyerhoff
* www.matrix44.de
*
* Copyright for the Lua 5.1 adaptation:
* 2007 Marco Antonio Abreu
* www.marcoabreu.eti.br
*
* All rights reserved.
*
* 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 LuaLib;
interface
const
LUA_VERSION = 'Lua 5.1';
LUA_RELEASE = 'Lua 5.1.2';
LUA_COPYRIGHT = 'Copyright (C) 1994-2004 Tecgraf, PUC-Rio';
LUA_AUTHORS = 'R. Ierusalimschy, L. H. de Figueiredo & W. Celes';
LUA_PASCAL_51_AUTHOR = 'Marco Antonio Abreu';
LUA_PASCAL_51_COPYRIGHT = 'Copyright (C) 2007 Marco Antonio Abreu';
(* mark for precompiled code (`<esc>Lua') *)
LUA_SIGNATURE = #27'Lua';
(* option for multiple returns in `lua_pcall' and `lua_call' *)
LUA_MULTRET = -1;
(*
** pseudo-indices
*)
LUA_REGISTRYINDEX = -10000;
LUA_ENVIRONINDEX = -10001;
LUA_GLOBALSINDEX = -10002;
(* thread status; 0 is OK *)
LUA_TRD_YIELD = 1;
LUA_ERRRUN = 2;
LUA_ERRSYNTAX = 3;
LUA_ERRMEM = 4;
LUA_ERRERR = 5;
(* extra error code for `luaL_load' *)
LUA_ERRFILE = LUA_ERRERR + 1;
(*
** basic types
*)
LUA_TNONE = -1;
LUA_TNIL = 0;
LUA_TBOOLEAN = 1;
LUA_TLIGHTUSERDATA = 2;
LUA_TNUMBER = 3;
LUA_TSTRING = 4;
LUA_TTABLE = 5;
LUA_TFUNCTION = 6;
LUA_TUSERDATA = 7;
LUA_TTHREAD = 8;
(* minimum Lua stack available to a C function *)
LUA_MINSTACK = 20;
(*
** garbage-collection function and options
*)
LUA_GCSTOP = 0;
LUA_GCRESTART = 1;
LUA_GCCOLLECT = 2;
LUA_GCCOUNT = 3;
LUA_GCCOUNTB = 4;
LUA_GCSTEP = 5;
LUA_GCSETPAUSE = 6;
LUA_GCSETSTEPMUL = 7;
(*
** {======================================================================
** Debug API
** =======================================================================
*)
(*
** Event codes
*)
LUA_HOOKCALL = 0;
LUA_HOOKRET = 1;
LUA_HOOKLINE = 2;
LUA_HOOKCOUNT = 3;
LUA_HOOKTAILRET = 4;
(*
** Event masks
*)
LUA_MASKCALL = (1 shl LUA_HOOKCALL);
LUA_MASKRET = (1 shl LUA_HOOKRET);
LUA_MASKLINE = (1 shl LUA_HOOKLINE);
LUA_MASKCOUNT = (1 shl LUA_HOOKCOUNT);
(*
** {======================================================================
** useful definitions for Lua kernel and libraries
** =======================================================================
*)
(*
@@ LUA_NUMBER_SCAN is the format for reading numbers.
@@ LUA_NUMBER_FMT is the format for writing numbers.
@@ lua_number2str converts a number to a string.
@@ LUAI_MAXNUMBER2STR is maximum size of previous conversion.
@@ lua_str2number converts a string to a number.
*)
LUA_NUMBER_SCAN = '%lf';
LUA_NUMBER_FMT = '%.14g';
LUAI_MAXNUMBER2STR = 32; (* 16 digits, sign, point, and \0 *)
(* pre-defined references *)
LUA_NOREF = -2;
LUA_REFNIL = -1;
LUA_IDSIZE = 60;
(*
** package names
*)
LUA_COLIBNAME = 'coroutine';
LUA_TABLIBNAME = 'table';
LUA_IOLIBNAME = 'io';
LUA_OSLIBNAME = 'os';
LUA_STRLIBNAME = 'string';
LUA_MATHLIBNAME = 'math';
LUA_DBLIBNAME = 'debug';
LUA_LOADLIBNAME = 'package';
(*
** {======================================================
** Generic Buffer manipulation
** =======================================================
*)
BUFSIZ = 512; (* From stdio.h *)
LUAL_BUFFERSIZE = BUFSIZ;
type
lua_State = type Pointer;
lua_CFunction = function(L: lua_State): Integer; cdecl;
(*
** functions that read/write blocks when loading/dumping Lua chunks
*)
lua_Reader = function(L: lua_State; data: Pointer; var size: Cardinal): PAnsiChar; cdecl;
lua_Writer = function(L: lua_State; p: Pointer; sz: Cardinal; ud: Pointer): Integer; cdecl;
(*
** prototype for memory-allocation functions
*)
lua_Alloc = function(ud, ptr: Pointer; osize, nsize: Cardinal): Pointer; cdecl;
(* type of numbers in Lua *)
lua_Number = type double;
(* type for integer functions *)
lua_Integer = type integer;
lua_Debug = packed record
event: Integer;
name: PAnsiChar; (* (n) *)
namewhat: PAnsiChar; (* (n) `global', `local', `field', `method' *)
what: PAnsiChar; (* (S) `Lua', `C', `main', `tail' *)
source: PAnsiChar; (* (S) *)
currentline: Integer; (* (l) *)
nups: Integer; (* (u) number of upvalues *)
linedefined: Integer; (* (S) *)
lastlinedefine: Integer; (* (S) *)
short_src: array[0..LUA_IDSIZE - 1] of AnsiChar; (* (S) *)
(* private part *)
i_ci: Integer; (* active function *)
end;
(* Functions to be called by the debuger in specific events *)
lua_Hook = procedure(L: lua_State; var ar: lua_Debug); cdecl;
(* Lua Record *)
PluaL_reg = ^luaL_reg;
luaL_reg = packed record
name: PAnsiChar;
func: lua_CFunction;
end;
(*
** {======================================================
** Generic Buffer manipulation
** =======================================================
*)
luaL_Buffer = packed record
p: PAnsiChar; (* current position in buffer *)
lvl: Integer; (* number of strings in the stack (level) *)
L: lua_State;
buffer: array[0..LUAL_BUFFERSIZE - 1] of AnsiChar;
end;
var
(*
** state manipulation
*)
lua_newstate: function(f: lua_Alloc; ud: Pointer): lua_State; cdecl;
lua_close: procedure(L: lua_State); cdecl;
lua_newthread: function(L: lua_State): lua_State; cdecl;
lua_atpanic: function(L: lua_State; panicf: lua_CFunction): lua_CFunction; cdecl;
(*
** basic stack manipulation
*)
lua_gettop: function(L: lua_State): Integer; cdecl;
lua_settop: procedure(L: lua_State; idx: Integer); cdecl;
lua_pushvalue: procedure(L: lua_State; idx: Integer); cdecl;
lua_remove: procedure(L: lua_State; idx: Integer); cdecl;
lua_insert: procedure(L: lua_State; idx: Integer); cdecl;
lua_replace: procedure(L: lua_State; idx: Integer); cdecl;
lua_checkstack: function(L: lua_State; extra: Integer): LongBool; cdecl;
lua_xmove: procedure(from, dest: lua_State; n: Integer); cdecl;
(*
** access functions (stack -> C/Pascal)
*)
lua_isnumber: function(L: lua_State; idx: Integer): LongBool; cdecl;
lua_isstring: function(L: lua_State; idx: Integer): LongBool; cdecl;
lua_iscfunction: function(L: lua_State; idx: Integer): LongBool; cdecl;
lua_isuserdata: function(L: lua_State; idx: Integer): LongBool; cdecl;
lua_type: function(L: lua_State; idx: Integer): Integer; cdecl;
lua_typename: function(L: lua_State; tp: Integer): PAnsiChar; cdecl;
lua_equal: function(L: lua_State; idx1, idx2: Integer): LongBool; cdecl;
lua_rawequal: function(L: lua_State; idx1, idx2: Integer): LongBool; cdecl;
lua_lessthan: function(L: lua_State; idx1, idx2: Integer): LongBool; cdecl;
lua_tonumber: function(L: lua_State; idx: Integer): lua_Number; cdecl;
lua_tointeger: function(L: lua_State; idx: Integer): lua_Integer; cdecl;
lua_toboolean: function(L: lua_State; idx: Integer): LongBool; cdecl;
lua_tolstring: function(L: lua_State; idx: Integer; var len: Cardinal): PAnsiChar; cdecl;
lua_objlen: function(L: lua_State; idx: Integer): Cardinal; cdecl;
lua_tocfunction: function(L: lua_State; idx: Integer): lua_CFunction; cdecl;
lua_touserdata: function(L: lua_State; idx: Integer): Pointer; cdecl;
lua_tothread: function(L: lua_State; idx: Integer): lua_State; cdecl;
lua_topointer: function(L: lua_State; idx: Integer): Pointer; cdecl;
(*
** push functions (C/Pascal -> stack)
*)
lua_pushnil: procedure(L: lua_State); cdecl;
lua_pushnumber: procedure(L: lua_State; n: lua_Number); cdecl;
lua_pushinteger: procedure(L: lua_State; n: lua_Integer); cdecl;
lua_pushlstring: procedure(L: lua_State; s: PAnsiChar; len: Cardinal); cdecl;
lua_pushstring: procedure(L: lua_State; s: PAnsiChar); cdecl;
lua_pushvfstring: function(L: lua_State; fmt, argp: PAnsiChar): PAnsiChar; cdecl;
lua_pushfstring: function(L: lua_State; fmt: PAnsiChar; args: array of const): PAnsiChar; cdecl;
lua_pushcclosure: procedure(L: lua_State; fn: lua_CFunction; n: Integer); cdecl;
lua_pushboolean: procedure(L: lua_State; b: LongBool); cdecl;
lua_pushlightuserdata: procedure(L: lua_State; p: Pointer); cdecl;
lua_pushthread: function(L: lua_State): Integer; cdecl;
(*
** get functions (Lua -> stack)
*)
lua_gettable: procedure(L: lua_State; idx: Integer); cdecl;
lua_getfield: procedure(L: lua_State; idx: Integer; k: PAnsiChar); cdecl;
lua_rawget: procedure(L: lua_State; idx: Integer); cdecl;
lua_rawgeti: procedure(L: lua_State; idx, n: Integer); cdecl;
lua_createtable: procedure(L: lua_State; narr, nrec: Integer); cdecl;
lua_newuserdata: function(L: lua_State; size: Cardinal): Pointer; cdecl;
lua_getmetatable: function(L: lua_State; idx: Integer): LongBool; cdecl;
lua_getfenv: procedure(L: lua_State; idx: Integer); cdecl;
(*
** set functions (stack -> Lua)
*)
lua_settable: procedure(L: lua_State; idx: Integer); cdecl;
lua_setfield: procedure(L: lua_State; idx: Integer; k: PAnsiChar ); cdecl;
lua_rawset: procedure(L: lua_State; idx: Integer); cdecl;
lua_rawseti: procedure(L: lua_State; idx, n: Integer); cdecl;
lua_setmetatable: function(L: lua_State; idx: Integer): LongBool; cdecl;
lua_setfenv: function(L: lua_State; idx: Integer): LongBool; cdecl;
(*
** `load' and `call' functions (load and run Lua code)
*)
lua_call: procedure(L: lua_State; nargs, nresults: Integer); cdecl;
lua_pcall: function(L: lua_State; nargs, nresults, errfunc: Integer): Integer; cdecl;
lua_cpcall: function(L: lua_State; func: lua_CFunction; ud: Pointer): Integer; cdecl;
lua_load: function(L: lua_State; reader: lua_Reader; data: Pointer; chunkname: PAnsiChar): Integer; cdecl;
lua_dump: function(L: lua_State; writer: lua_Writer; data: Pointer): Integer; cdecl;
(*
** coroutine functions
*)
lua_yield: function(L: lua_State; nresults: Integer): Integer; cdecl;
lua_resume: function(L: lua_State; narg: Integer): Integer; cdecl;
lua_status: function(L: lua_State): Integer; cdecl;
(*
** garbage-collection functions
*)
lua_gc: function(L: lua_State; what, data: Integer): Integer; cdecl;
(*
** miscellaneous functions
*)
lua_error: function(L: lua_State): Integer; cdecl;
lua_next: function(L: lua_State; idx: Integer): Integer; cdecl;
lua_concat: procedure(L: lua_State; n: Integer); cdecl;
lua_getallocf: function(L: lua_State; ud: Pointer): lua_Alloc; cdecl;
lua_setallocf: procedure(L: lua_State; f: lua_Alloc; ud: Pointer); cdecl;
(*
** {======================================================================
** Debug API
** =======================================================================
*)
lua_getstack: function(L: lua_State; level: Integer; var ar: lua_Debug): Integer; cdecl;
lua_getinfo: function(L: lua_State; what: PAnsiChar; var ar: lua_Debug): Integer; cdecl;
lua_getlocal: function(L: lua_State; var ar: lua_Debug; n: Integer): PAnsiChar; cdecl;
lua_setlocal: function(L: lua_State; var ar: lua_Debug; n: Integer): PAnsiChar; cdecl;
lua_getupvalue: function(L: lua_State; funcindex, n: Integer): PAnsiChar; cdecl;
lua_setupvalue: function(L: lua_State; funcindex, n: Integer): PAnsiChar; cdecl;
lua_sethook: function(L: lua_State; func: lua_Hook; mask, count: Integer): Integer; cdecl;
lua_gethook: function(L: lua_State): lua_Hook; cdecl;
lua_gethookmask: function(L: lua_State): Integer; cdecl;
lua_gethookcount: function(L: lua_State): Integer; cdecl;
(* lua libraries *)
luaopen_base: function(L: lua_State): Integer; cdecl;
luaopen_debug: function(L: lua_State): Integer; cdecl;
luaopen_io: function(L: lua_State): Integer; cdecl;
luaopen_math: function(L: lua_State): Integer; cdecl;
luaopen_os: function(L: lua_State): Integer; cdecl;
luaopen_package: function(L: lua_State): Integer; cdecl;
luaopen_string: function(L: lua_State): Integer; cdecl;
luaopen_table: function(L: lua_State): Integer; cdecl;
(* open all previous libraries *)
luaL_openlibs: procedure(L: lua_State); cdecl;
luaL_register: procedure(L: lua_State; libname: PAnsiChar; lr: PluaL_reg); cdecl;
luaL_getmetafield: function(L: lua_State; obj: Integer; e: PAnsiChar): Integer; cdecl;
luaL_callmeta: function(L: lua_State; obj: Integer; e: PAnsiChar): Integer; cdecl;
luaL_typerror: function(L: lua_State; narg: Integer; tname: PAnsiChar): Integer; cdecl;
luaL_argerror: function(L: lua_State; narg: Integer; extramsg: PAnsiChar): Integer; cdecl;
luaL_checklstring: function(L: lua_State; narg: Integer; var len: Cardinal): PAnsiChar; cdecl;
luaL_optlstring: function(L: lua_State; narg: Integer; d: PAnsiChar; var len: Cardinal): PAnsiChar; cdecl;
luaL_checknumber: function(L: lua_State; narg: Integer): lua_Number; cdecl;
luaL_optnumber: function(L: lua_State; narg: Integer; d: lua_Number): lua_Number; cdecl;
luaL_checkinteger: function(L: lua_State; narg: Integer): lua_Integer; cdecl;
luaL_optinteger: function(L: lua_State; narg: Integer; d: lua_Integer): lua_Integer; cdecl;
luaL_checkstack: procedure(L: lua_State; sz: Integer; msg: PAnsiChar); cdecl;
luaL_checktype: procedure(L: lua_State; narg, t: Integer); cdecl;
luaL_checkany: procedure(L: lua_State; narg: Integer); cdecl;
luaL_newmetatable: function(L: lua_State; tname: PAnsiChar): Integer; cdecl;
luaL_checkudata: function(L: lua_State; narg: Integer; tname: PAnsiChar): Pointer; cdecl;
luaL_checkoption: function(L: lua_State; narg: Integer; def: PAnsiChar; lst: array of PAnsiChar): Integer; cdecl;
luaL_where: procedure(L: lua_State; lvl: Integer); cdecl;
luaL_error: function(L: lua_State; fmt: PAnsiChar; args: array of const): Integer; cdecl;
luaL_ref: function(L: lua_State; t: Integer): Integer; cdecl;
luaL_unref: procedure(L: lua_State; t, ref: Integer); cdecl;
{$ifdef LUA_COMPAT_GETN}
luaL_getn: function(L: lua_State; t: Integer): Integer; cdecl;
luaL_setn: procedure(L: lua_State; t, n: Integer); cdecl;
{$endif}
luaL_loadfile: function(L: lua_State; filename: PAnsiChar): Integer; cdecl;
luaL_loadbuffer: function(L: lua_State; buff: PAnsiChar; sz: Cardinal; name: PAnsiChar): Integer; cdecl;
luaL_loadstring: function(L: lua_State; s: PAnsiChar): Integer; cdecl;
luaL_newstate: function(): lua_State; cdecl;
luaL_gsub: function(L: lua_State; s, p, r: PAnsiChar): PAnsiChar; cdecl;
luaL_findtable: function(L: lua_State; idx: Integer; fname: PAnsiChar; szhint: Integer): PAnsiChar; cdecl;
luaL_buffinit: procedure(L: lua_State; var B: luaL_Buffer); cdecl;
luaL_prepbuffer: function(var B: luaL_Buffer): PAnsiChar; cdecl;
luaL_addlstring: procedure(var B: luaL_Buffer; s: PAnsiChar; l: Cardinal); cdecl;
luaL_addstring: procedure(var B: luaL_Buffer; s: PAnsiChar); cdecl;
luaL_addvalue: procedure(var B: luaL_Buffer); cdecl;
luaL_pushresult: procedure(var B: luaL_Buffer); cdecl;
(*
** ===============================================================
** some useful macros
** ===============================================================
*)
{$ifndef LUA_COMPAT_GETN}
function luaL_getn(L: lua_State; t: Integer): Integer;
procedure luaL_setn(L: lua_State; t, n: Integer);
{$endif}
(* pseudo-indices *)
function lua_upvalueindex(i: Integer): Integer;
(* to help testing the libraries *)
procedure lua_assert(c: Boolean);
function lua_number2str(s: Lua_Number; n: Integer): String;
function lua_str2number(s: String; p: integer): Lua_Number;
(* argument and parameters checks *)
function luaL_argcheck(L: lua_State; cond: Boolean; narg: Integer; extramsg: PAnsiChar): Integer;
function luaL_checkstring(L: lua_State; narg: Integer): PAnsiChar;
function luaL_optstring(L: lua_State; narg: Integer; d: PAnsiChar): PAnsiChar;
function luaL_checkint(L: lua_State; narg: Integer): Integer;
function luaL_optint(L: lua_State; narg, d: Integer): Integer;
function luaL_checklong(L: lua_State; narg: Integer): LongInt;
function luaL_optlong(L: lua_State; narg: Integer; d: LongInt): LongInt;
function luaL_typename(L: lua_State; idx: Integer): PAnsiChar;
function luaL_dofile(L: lua_State; filename: PAnsiChar): Integer;
function luaL_dostring(L: lua_State; str: PAnsiChar): Integer;
procedure luaL_getmetatable(L: lua_State; tname: PAnsiChar);
(* Generic Buffer manipulation *)
procedure luaL_addchar(var B: luaL_Buffer; c: AnsiChar);
procedure luaL_putchar(var B: luaL_Buffer; c: AnsiChar);
procedure luaL_addsize(var B: luaL_Buffer; n: Cardinal);
function luaL_check_lstr(L: lua_State; numArg: Integer; var ls: Cardinal): PAnsiChar;
function luaL_opt_lstr(L: lua_State; numArg: Integer; def: PAnsiChar; var ls: Cardinal): PAnsiChar;
function luaL_check_number(L: lua_State; numArg: Integer): lua_Number;
function luaL_opt_number(L: lua_State; nArg: Integer; def: lua_Number): lua_Number;
function luaL_arg_check(L: lua_State; cond: Boolean; numarg: Integer; extramsg: PAnsiChar): Integer;
function luaL_check_string(L: lua_State; n: Integer): PAnsiChar;
function luaL_opt_string(L: lua_State; n: Integer; d: PAnsiChar): PAnsiChar;
function luaL_check_int(L: lua_State; n: Integer): Integer;
function luaL_check_long(L: lua_State; n: LongInt): LongInt;
function luaL_opt_int(L: lua_State; n, d: Integer): Integer;
function luaL_opt_long(L: lua_State; n: Integer; d: LongInt): LongInt;
procedure lua_pop(L: lua_State; n: Integer);
procedure lua_newtable(L: lua_State);
procedure lua_register(L: lua_state; name: PAnsiChar; f: lua_CFunction);
procedure lua_pushcfunction(L: lua_State; f: lua_CFunction);
function lua_strlen(L: lua_State; i: Integer): Cardinal;
function lua_isfunction(L: lua_State; idx: Integer): Boolean;
function lua_istable(L: lua_State; idx: Integer): Boolean;
function lua_islightuserdata(L: lua_State; idx: Integer): Boolean;
function lua_isnil(L: lua_State; idx: Integer): Boolean;
function lua_isboolean(L: lua_State; idx: Integer): Boolean;
function lua_isthread(L: lua_State; idx: Integer): Boolean;
function lua_isnone(L: lua_State; idx: Integer): Boolean;
function lua_isnoneornil(L: lua_State; idx: Integer): Boolean;
procedure lua_pushliteral(L: lua_State; s: PAnsiChar);
procedure lua_setglobal(L: lua_State; name: PAnsiChar);
procedure lua_getglobal(L: lua_State; name: PAnsiChar);
function lua_tostring(L: lua_State; idx: Integer): PAnsiChar;
(*
** compatibility macros and functions
*)
function lua_open(): lua_State;
procedure lua_getregistry(L: lua_State);
function lua_getgccount(L: lua_State): Integer;
(* compatibility with ref system *)
function lua_ref(L: lua_State; lock: Boolean): Integer;
procedure lua_unref(L: lua_State; ref: Integer);
procedure lua_getref(L: lua_State; ref: Integer);
(*
** Dynamic library manipulation
*)
function GetProcAddr( fHandle: THandle; const methodName: String; bErrorIfNotExists: Boolean = True ): Pointer;
procedure SetLuaLibFileName( newLuaLibFileName: String );
function GetLuaLibFileName(): String;
function LoadLuaLib( newLuaLibFileName: String = '' ): Integer;
procedure FreeLuaLib();
function LuaLibLoaded: Boolean;
implementation
uses
SysUtils, Math,
{$ifdef MSWINDOWS}
Windows
{$endif}
;
var
fLibHandle: Integer = 0;
{$ifdef MSWINDOWS}
fLuaLibFileName: String = 'Lua5.1.dll';
{$endif}
{$ifdef LINUX}
fLuaLibFileName: String = 'liblua.so.5.1';
{$endif}
(*
** Dynamic library manipulation
*)
function GetProcAddr( fHandle: THandle; const methodName: String; bErrorIfNotExists: Boolean = True ): Pointer;
begin
Result := GetProcAddress( fHandle, PAnsiChar( AnsiString(methodName) ) );
if bErrorIfNotExists and ( Result = nil ) then
Raise Exception.Create( 'Cannot load method ' + QuotedStr( methodName ) + ' from dynamic library.' );
end;
procedure SetLuaLibFileName( newLuaLibFileName: String );
begin
fLuaLibFileName := newLuaLibFileName;
end;
function GetLuaLibFileName(): String;
begin
Result := fLuaLibFileName;
end;
function LuaLibLoaded: Boolean;
begin
Result := fLibHandle <> 0;
end;
function LoadLuaLib(newLuaLibFileName: String): Integer;
begin
FreeLuaLib();
if newLuaLibFileName <> '' then
SetLuaLibFileName( newLuaLibFileName );
if not FileExists( GetLuaLibFileName() ) then begin
Result := -1;
exit;
end;
fLibHandle := LoadLibrary(PWideChar( (GetLuaLibFileName() ) ));
if fLibHandle = 0 then begin
Result := -2;
exit;
end;
lua_newstate := GetProcAddr( fLibHandle, 'lua_newstate' );
lua_close := GetProcAddr( fLibHandle, 'lua_close' );
lua_newthread := GetProcAddr( fLibHandle, 'lua_newthread' );
lua_atpanic := GetProcAddr( fLibHandle, 'lua_atpanic' );
lua_gettop := GetProcAddr( fLibHandle, 'lua_gettop' );
lua_settop := GetProcAddr( fLibHandle, 'lua_settop' );
lua_pushvalue := GetProcAddr( fLibHandle, 'lua_pushvalue' );
lua_remove := GetProcAddr( fLibHandle, 'lua_remove' );
lua_insert := GetProcAddr( fLibHandle, 'lua_insert' );
lua_replace := GetProcAddr( fLibHandle, 'lua_replace' );
lua_checkstack := GetProcAddr( fLibHandle, 'lua_checkstack' );
lua_xmove := GetProcAddr( fLibHandle, 'lua_xmove' );
lua_isnumber := GetProcAddr( fLibHandle, 'lua_isnumber' );
lua_isstring := GetProcAddr( fLibHandle, 'lua_isstring' );
lua_iscfunction := GetProcAddr( fLibHandle, 'lua_iscfunction' );
lua_isuserdata := GetProcAddr( fLibHandle, 'lua_isuserdata' );
lua_type := GetProcAddr( fLibHandle, 'lua_type' );
lua_typename := GetProcAddr( fLibHandle, 'lua_typename' );
lua_equal := GetProcAddr( fLibHandle, 'lua_equal' );
lua_rawequal := GetProcAddr( fLibHandle, 'lua_rawequal' );
lua_lessthan := GetProcAddr( fLibHandle, 'lua_lessthan' );
lua_tonumber := GetProcAddr( fLibHandle, 'lua_tonumber' );
lua_tointeger := GetProcAddr( fLibHandle, 'lua_tointeger' );
lua_toboolean := GetProcAddr( fLibHandle, 'lua_toboolean' );
lua_tolstring := GetProcAddr( fLibHandle, 'lua_tolstring' );
lua_objlen := GetProcAddr( fLibHandle, 'lua_objlen' );
lua_tocfunction := GetProcAddr( fLibHandle, 'lua_tocfunction' );
lua_touserdata := GetProcAddr( fLibHandle, 'lua_touserdata' );
lua_tothread := GetProcAddr( fLibHandle, 'lua_tothread' );
lua_topointer := GetProcAddr( fLibHandle, 'lua_topointer' );
lua_pushnil := GetProcAddr( fLibHandle, 'lua_pushnil' );
lua_pushnumber := GetProcAddr( fLibHandle, 'lua_pushnumber' );
lua_pushinteger := GetProcAddr( fLibHandle, 'lua_pushinteger' );
lua_pushlstring := GetProcAddr( fLibHandle, 'lua_pushlstring' );
lua_pushstring := GetProcAddr( fLibHandle, 'lua_pushstring' );
lua_pushvfstring := GetProcAddr( fLibHandle, 'lua_pushvfstring' );
lua_pushfstring := GetProcAddr( fLibHandle, 'lua_pushfstring' );
lua_pushcclosure := GetProcAddr( fLibHandle, 'lua_pushcclosure' );
lua_pushboolean := GetProcAddr( fLibHandle, 'lua_pushboolean' );
lua_pushlightuserdata := GetProcAddr( fLibHandle, 'lua_pushlightuserdata' );
lua_pushthread := GetProcAddr( fLibHandle, 'lua_pushthread' );
lua_gettable := GetProcAddr( fLibHandle, 'lua_gettable' );
lua_getfield := GetProcAddr( fLibHandle, 'lua_getfield' );
lua_rawget := GetProcAddr( fLibHandle, 'lua_rawget' );
lua_rawgeti := GetProcAddr( fLibHandle, 'lua_rawgeti' );
lua_createtable := GetProcAddr( fLibHandle, 'lua_createtable' );
lua_newuserdata := GetProcAddr( fLibHandle, 'lua_newuserdata' );
lua_getmetatable := GetProcAddr( fLibHandle, 'lua_getmetatable' );
lua_getfenv := GetProcAddr( fLibHandle, 'lua_getfenv' );
lua_settable := GetProcAddr( fLibHandle, 'lua_settable' );
lua_setfield := GetProcAddr( fLibHandle, 'lua_setfield' );
lua_rawset := GetProcAddr( fLibHandle, 'lua_rawset' );
lua_rawseti := GetProcAddr( fLibHandle, 'lua_rawseti' );
lua_setmetatable := GetProcAddr( fLibHandle, 'lua_setmetatable' );
lua_setfenv := GetProcAddr( fLibHandle, 'lua_setfenv' );
lua_call := GetProcAddr( fLibHandle, 'lua_call' );
lua_pcall := GetProcAddr( fLibHandle, 'lua_pcall' );
lua_cpcall := GetProcAddr( fLibHandle, 'lua_cpcall' );
lua_load := GetProcAddr( fLibHandle, 'lua_load' );
lua_dump := GetProcAddr( fLibHandle, 'lua_dump' );
lua_yield := GetProcAddr( fLibHandle, 'lua_yield' );
lua_resume := GetProcAddr( fLibHandle, 'lua_resume' );
lua_status := GetProcAddr( fLibHandle, 'lua_status' );
lua_gc := GetProcAddr( fLibHandle, 'lua_gc' );
lua_error := GetProcAddr( fLibHandle, 'lua_error' );
lua_next := GetProcAddr( fLibHandle, 'lua_next' );
lua_concat := GetProcAddr( fLibHandle, 'lua_concat' );
lua_getallocf := GetProcAddr( fLibHandle, 'lua_getallocf' );
lua_setallocf := GetProcAddr( fLibHandle, 'lua_setallocf' );
lua_getstack := GetProcAddr( fLibHandle, 'lua_getstack' );
lua_getinfo := GetProcAddr( fLibHandle, 'lua_getinfo' );
lua_getlocal := GetProcAddr( fLibHandle, 'lua_getlocal' );
lua_setlocal := GetProcAddr( fLibHandle, 'lua_setlocal' );
lua_getupvalue := GetProcAddr( fLibHandle, 'lua_getupvalue' );
lua_setupvalue := GetProcAddr( fLibHandle, 'lua_setupvalue' );
lua_sethook := GetProcAddr( fLibHandle, 'lua_sethook' );
lua_gethook := GetProcAddr( fLibHandle, 'lua_gethook' );
lua_gethookmask := GetProcAddr( fLibHandle, 'lua_gethookmask' );
lua_gethookcount := GetProcAddr( fLibHandle, 'lua_gethookcount' );
luaopen_base := GetProcAddr( fLibHandle, 'luaopen_base' );
luaopen_table := GetProcAddr( fLibHandle, 'luaopen_table' );
luaopen_io := GetProcAddr( fLibHandle, 'luaopen_io' );
luaopen_os := GetProcAddr( fLibHandle, 'luaopen_os' );
luaopen_string := GetProcAddr( fLibHandle, 'luaopen_string' );
luaopen_math := GetProcAddr( fLibHandle, 'luaopen_math' );
luaopen_debug := GetProcAddr( fLibHandle, 'luaopen_debug' );
luaopen_package := GetProcAddr( fLibHandle, 'luaopen_package' );
luaL_openlibs := GetProcAddr( fLibHandle, 'luaL_openlibs' );
luaL_register := GetProcAddr( fLibHandle, 'luaL_register' );
luaL_getmetafield := GetProcAddr( fLibHandle, 'luaL_getmetafield' );
luaL_callmeta := GetProcAddr( fLibHandle, 'luaL_callmeta' );
luaL_typerror := GetProcAddr( fLibHandle, 'luaL_typerror' );
luaL_argerror := GetProcAddr( fLibHandle, 'luaL_argerror' );
luaL_checklstring := GetProcAddr( fLibHandle, 'luaL_checklstring' );
luaL_optlstring := GetProcAddr( fLibHandle, 'luaL_optlstring' );
luaL_checknumber := GetProcAddr( fLibHandle, 'luaL_checknumber' );
luaL_optnumber := GetProcAddr( fLibHandle, 'luaL_optnumber' );
luaL_checkinteger := GetProcAddr( fLibHandle, 'luaL_checkinteger' );
luaL_optinteger := GetProcAddr( fLibHandle, 'luaL_optinteger' );
luaL_checkstack := GetProcAddr( fLibHandle, 'luaL_checkstack' );
luaL_checktype := GetProcAddr( fLibHandle, 'luaL_checktype' );
luaL_checkany := GetProcAddr( fLibHandle, 'luaL_checkany' );
luaL_newmetatable := GetProcAddr( fLibHandle, 'luaL_newmetatable' );
luaL_checkudata := GetProcAddr( fLibHandle, 'luaL_checkudata' );
luaL_where := GetProcAddr( fLibHandle, 'luaL_where' );
luaL_error := GetProcAddr( fLibHandle, 'luaL_error' );
luaL_checkoption := GetProcAddr( fLibHandle, 'luaL_checkoption' );
luaL_ref := GetProcAddr( fLibHandle, 'luaL_ref' );
luaL_unref := GetProcAddr( fLibHandle, 'luaL_unref' );
{$ifdef LUA_COMPAT_GETN}
luaL_getn := GetProcAddr( fLibHandle, 'luaL_getn' );
luaL_setn := GetProcAddr( fLibHandle, 'luaL_setn' );
{$endif}
luaL_loadfile := GetProcAddr( fLibHandle, 'luaL_loadfile' );
luaL_loadbuffer := GetProcAddr( fLibHandle, 'luaL_loadbuffer' );
luaL_loadstring := GetProcAddr( fLibHandle, 'luaL_loadstring' );
luaL_newstate := GetProcAddr( fLibHandle, 'luaL_newstate' );
luaL_gsub := GetProcAddr( fLibHandle, 'luaL_gsub' );
luaL_findtable := GetProcAddr( fLibHandle, 'luaL_findtable' );
luaL_buffinit := GetProcAddr( fLibHandle, 'luaL_buffinit' );
luaL_prepbuffer := GetProcAddr( fLibHandle, 'luaL_prepbuffer' );
luaL_addlstring := GetProcAddr( fLibHandle, 'luaL_addlstring' );
luaL_addstring := GetProcAddr( fLibHandle, 'luaL_addstring' );
luaL_addvalue := GetProcAddr( fLibHandle, 'luaL_addvalue' );
luaL_pushresult := GetProcAddr( fLibHandle, 'luaL_pushresult' );
Result := fLibHandle;
end;
procedure FreeLuaLib();
begin
lua_newstate := nil;
lua_close := nil;
lua_newthread := nil;
lua_atpanic := nil;
lua_gettop := nil;
lua_settop := nil;
lua_pushvalue := nil;
lua_remove := nil;
lua_insert := nil;
lua_replace := nil;
lua_checkstack := nil;
lua_xmove := nil;
lua_isnumber := nil;
lua_isstring := nil;
lua_iscfunction := nil;
lua_isuserdata := nil;
lua_type := nil;
lua_typename := nil;
lua_equal := nil;
lua_rawequal := nil;
lua_lessthan := nil;
lua_tonumber := nil;
lua_tointeger := nil;
lua_toboolean := nil;
lua_tolstring := nil;
lua_objlen := nil;
lua_tocfunction := nil;
lua_touserdata := nil;
lua_tothread := nil;
lua_topointer := nil;
lua_pushnil := nil;
lua_pushnumber := nil;
lua_pushinteger := nil;
lua_pushlstring := nil;
lua_pushstring := nil;
lua_pushvfstring := nil;
lua_pushfstring := nil;
lua_pushcclosure := nil;
lua_pushboolean := nil;
lua_pushlightuserdata := nil;
lua_pushthread := nil;
lua_gettable := nil;
lua_getfield := nil;
lua_rawget := nil;
lua_rawgeti := nil;
lua_createtable := nil;
lua_newuserdata := nil;
lua_getmetatable := nil;
lua_getfenv := nil;
lua_settable := nil;
lua_setfield := nil;
lua_rawset := nil;
lua_rawseti := nil;
lua_setmetatable := nil;
lua_setfenv := nil;
lua_call := nil;
lua_pcall := nil;
lua_cpcall := nil;
lua_load := nil;
lua_dump := nil;
lua_yield := nil;
lua_resume := nil;
lua_status := nil;
lua_gc := nil;
lua_error := nil;
lua_next := nil;
lua_concat := nil;
lua_getallocf := nil;
lua_setallocf := nil;
lua_getstack := nil;
lua_getinfo := nil;
lua_getlocal := nil;
lua_setlocal := nil;
lua_getupvalue := nil;
lua_setupvalue := nil;
lua_sethook := nil;
lua_gethook := nil;
lua_gethookmask := nil;
lua_gethookcount := nil;
luaopen_base := nil;
luaopen_table := nil;
luaopen_io := nil;
luaopen_os := nil;
luaopen_string := nil;
luaopen_math := nil;
luaopen_debug := nil;
luaopen_package := nil;
luaL_openlibs := nil;
luaL_register := nil;
luaL_getmetafield := nil;
luaL_callmeta := nil;
luaL_typerror := nil;
luaL_argerror := nil;
luaL_checklstring := nil;
luaL_optlstring := nil;
luaL_checknumber := nil;
luaL_optnumber := nil;
luaL_checkinteger := nil;
luaL_optinteger := nil;
luaL_checkstack := nil;
luaL_checktype := nil;
luaL_checkany := nil;
luaL_newmetatable := nil;
luaL_checkudata := nil;
luaL_where := nil;
luaL_error := nil;
luaL_checkoption := nil;
luaL_ref := nil;
luaL_unref := nil;
{$ifdef LUA_COMPAT_GETN}
luaL_getn := nil;
luaL_setn := nil;
{$endif}
luaL_loadfile := nil;
luaL_loadbuffer := nil;
luaL_loadstring := nil;
luaL_newstate := nil;
luaL_gsub := nil;
luaL_findtable := nil;
luaL_buffinit := nil;
luaL_prepbuffer := nil;
luaL_addlstring := nil;
luaL_addstring := nil;
luaL_addvalue := nil;
luaL_pushresult := nil;
if fLibHandle <> 0 then begin
FreeLibrary( fLibHandle );
fLibHandle := 0;
end;
end;
{$ifndef LUA_COMPAT_GETN}
function luaL_getn(L: lua_State; t: Integer): Integer;
begin
Result := lua_objlen(L, t);
end;
procedure luaL_setn(L: lua_State; t, n: Integer);
begin
end;
{$endif}
function lua_upvalueindex(i: Integer): Integer;
begin
Result := LUA_GLOBALSINDEX - i;
end;
procedure lua_pop(L: lua_State; n: Integer);
begin
lua_settop(L, -(n) - 1);
end;
procedure lua_newtable(L: lua_State);
begin
lua_createtable(L, 0, 0);
end;
function lua_strlen(L: lua_State; i: Integer): Cardinal;
begin
result := lua_objlen(L, i);
end;
procedure lua_register(L: lua_state; name: PAnsiChar; f: lua_CFunction);
begin
lua_pushcfunction(L, f);
lua_setglobal(L, name);
end;
procedure lua_pushcfunction(L: lua_State; f: lua_CFunction);
begin
lua_pushcclosure(L, f, 0);
end;
function lua_isfunction(L: lua_State; idx: Integer): Boolean;
begin
Result := lua_type(L, idx) = LUA_TFUNCTION;
end;
function lua_istable(L: lua_State; idx: Integer): Boolean;
begin
Result := lua_type(L, idx) = LUA_TTABLE;
end;
function lua_islightuserdata(L: lua_State; idx: Integer): Boolean;
begin
Result := lua_type(L, idx) = LUA_TLIGHTUSERDATA;
end;
function lua_isnil(L: lua_State; idx: Integer): Boolean;
begin
Result := lua_type(L, idx) = LUA_TNIL;
end;
function lua_isboolean(L: lua_State; idx: Integer): Boolean;
begin
Result := lua_type(L, idx) = LUA_TBOOLEAN;
end;
function lua_isthread(L: lua_State; idx: Integer): Boolean;
begin
Result := lua_type(L, idx) = LUA_TTHREAD;
end;
function lua_isnone(L: lua_State; idx: Integer): Boolean;
begin
Result := lua_type(L, idx) = LUA_TNONE;
end;
function lua_isnoneornil(L: lua_State; idx: Integer): Boolean;
begin
Result := lua_type(L, idx) <= 0;
end;
procedure lua_pushliteral(L: lua_State; s: PAnsiChar);
begin
lua_pushlstring(L, s, StrLen(s));
end;
procedure lua_setglobal(L: lua_State; name: PAnsiChar);
begin
lua_setfield(L, LUA_GLOBALSINDEX, name);
end;
procedure lua_getglobal(L: lua_State; name: PAnsiChar);
begin
lua_getfield(L, LUA_GLOBALSINDEX, name);
end;
function lua_tostring(L: lua_State; idx: Integer): PAnsiChar;
var
len: Cardinal;
begin
Result := lua_tolstring(L, idx, len);
end;
function lua_getgccount(L: lua_State): Integer;
begin
Result := lua_gc(L, LUA_GCCOUNT, 0);
end;
function lua_open(): lua_State;
begin
Result := luaL_newstate();
end;
procedure lua_getregistry(L: lua_State);
begin
lua_pushvalue(L, LUA_REGISTRYINDEX);
end;
function lua_ref(L: lua_State; lock: Boolean): Integer;
begin
if lock then
Result := luaL_ref(L, LUA_REGISTRYINDEX)
else begin
lua_pushstring(L, 'unlocked references are obsolete');
Result := lua_error(L);
end;
end;
procedure lua_unref(L: lua_State; ref: Integer);
begin
luaL_unref(L, LUA_REGISTRYINDEX, ref);
end;
procedure lua_getref(L: lua_State; ref: Integer);
begin
lua_rawgeti(L, LUA_REGISTRYINDEX, ref);
end;
procedure lua_assert(c: Boolean);
begin
end;
function lua_number2str(s: Lua_Number; n: Integer): String;
begin
Result := FormatFloat( LUA_NUMBER_FMT, RoundTo( s, n ) );
end;
function lua_str2number(s: String; p: integer): Lua_Number;
begin
Result := RoundTo( StrToFloat( s ), p );
end;
function luaL_argcheck(L: lua_State; cond: Boolean; narg: Integer; extramsg: PAnsiChar): Integer;
begin
if cond then
Result := 0
else
Result := luaL_argerror(L, narg, extramsg);
end;
function luaL_checkstring(L: lua_State; narg: Integer): PAnsiChar;
var
ls: Cardinal;
begin
Result := luaL_checklstring(L, narg, ls);
end;
function luaL_optstring(L: lua_State; narg: Integer; d: PAnsiChar): PAnsiChar;
var
ls: Cardinal;
begin
Result := luaL_optlstring(L, narg, d, ls);
end;
function luaL_checkint(L: lua_State; narg: Integer): Integer;
begin
Result := Trunc(luaL_checkinteger(L, narg));
end;
function luaL_optint(L: lua_State; narg, d: Integer): Integer;
begin
Result := Trunc(luaL_optinteger(L, narg, d));
end;
function luaL_checklong(L: lua_State; narg: Integer): LongInt;
begin
Result := Trunc(luaL_checkinteger(L, narg));
end;
function luaL_optlong(L: lua_State; narg: Integer; d: LongInt): LongInt;
begin
Result := Trunc(luaL_optinteger(L, narg, d));
end;
function luaL_typename(L: lua_State; idx: Integer): PAnsiChar;
begin
Result := lua_typename(L, lua_type(L, idx));
end;
function luaL_dofile(L: lua_State; filename: PAnsiChar): Integer;
begin
Result := luaL_loadfile(L, filename);
If Result = 0 Then
Result := lua_pcall(L, 0, LUA_MULTRET, 0);
end;
function luaL_dostring(L: lua_State; str: PAnsiChar): Integer;
begin
Result := luaL_loadstring(L, str);
If Result = 0 Then
Result := lua_pcall(L, 0, LUA_MULTRET, 0);
end;
procedure luaL_getmetatable(L: lua_State; tname: PAnsiChar);
begin
lua_getfield(L, LUA_REGISTRYINDEX, tname);
end;
procedure luaL_addchar(var B: luaL_Buffer; c: AnsiChar);
begin
if Integer(B.p) < Integer(B.buffer + LUAL_BUFFERSIZE) then
luaL_prepbuffer(B);
B.p^ := c;
Inc(B.p);
{ // original C code
#define luaL_addchar(B,c) \
((void)((B)->p < ((B)->buffer+LUAL_BUFFERSIZE) || luaL_prepbuffer(B)), \
(*(B)->p++ = (char)(c)))
}
end;
procedure luaL_putchar(var B: luaL_Buffer; c: AnsiChar);
begin
luaL_addchar(B, c);
end;
procedure luaL_addsize(var B: luaL_Buffer; n: Cardinal);
begin
Inc(B.p, n);
end;
function luaL_check_lstr(L: lua_State; numArg: Integer; var ls: Cardinal): PAnsiChar;
begin
Result := luaL_checklstring(L, numArg, ls);
end;
function luaL_opt_lstr(L: lua_State; numArg: Integer; def: PAnsiChar; var ls: Cardinal): PAnsiChar;
begin
Result := luaL_optlstring(L, numArg, def, ls);
end;
function luaL_check_number(L: lua_State; numArg: Integer): lua_Number;
begin
Result := luaL_checknumber(L, numArg);
end;
function luaL_opt_number(L: lua_State; nArg: Integer; def: lua_Number): lua_Number;
begin
Result := luaL_optnumber(L, nArg, def);
end;
function luaL_arg_check(L: lua_State; cond: Boolean; numarg: Integer; extramsg: PAnsiChar): Integer;
begin
Result := luaL_argcheck(L, cond, numarg, extramsg);
end;
function luaL_check_string(L: lua_State; n: Integer): PAnsiChar;
begin
Result := luaL_checkstring(L, n);
end;
function luaL_opt_string(L: lua_State; n: Integer; d: PAnsiChar): PAnsiChar;
begin
Result := luaL_optstring(L, n, d);
end;
function luaL_check_int(L: lua_State; n: Integer): Integer;
begin
Result := luaL_checkint(L, n);
end;
function luaL_check_long(L: lua_State; n: LongInt): LongInt;
begin
Result := luaL_checklong(L, n);
end;
function luaL_opt_int(L: lua_State; n, d: Integer): Integer;
begin
Result := luaL_optint(L, n, d);
end;
function luaL_opt_long(L: lua_State; n: Integer; d: LongInt): LongInt;
begin
Result := luaL_optlong(L, n, d);
end;
end.
| 35.656195 | 115 | 0.670378 |
8373f25a9daface0bcbb01bf079f9b7750e37f0d | 4,866 | pas | Pascal | dependencies/Indy10/Protocols/IdTimeUDP.pas | 17-years-old/fhirserver | 9575a7358868619311a5d1169edde3ffe261e558 | [
"BSD-3-Clause"
]
| null | null | null | dependencies/Indy10/Protocols/IdTimeUDP.pas | 17-years-old/fhirserver | 9575a7358868619311a5d1169edde3ffe261e558 | [
"BSD-3-Clause"
]
| null | null | null | dependencies/Indy10/Protocols/IdTimeUDP.pas | 17-years-old/fhirserver | 9575a7358868619311a5d1169edde3ffe261e558 | [
"BSD-3-Clause"
]
| null | null | null | {
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
Rev 1.7 2/10/2005 2:24:38 PM JPMugaas
Minor Restructures for some new UnixTime Service components.
Rev 1.6 2004.02.03 5:44:36 PM czhower
Name changes
Rev 1.5 1/21/2004 4:21:00 PM JPMugaas
InitComponent
Rev 1.4 1/3/2004 1:00:06 PM JPMugaas
These should now compile with Kudzu's change in IdCoreGlobal.
Rev 1.3 10/26/2003 5:16:52 PM BGooijen
Works now, times in GetTickDiff were in wrong order
Rev 1.2 10/22/2003 04:54:26 PM JPMugaas
Attempted to get these to work.
Rev 1.1 2003.10.12 6:36:46 PM czhower
Now compiles.
Rev 1.0 11/13/2002 08:03:24 AM JPMugaas
}
unit IdTimeUDP;
interface
{$i IdCompilerDefines.inc}
uses
{$IFDEF WORKAROUND_INLINE_CONSTRUCTORS}
Classes,
{$ENDIF}
IdGlobal,
IdAssignedNumbers, IdUDPBase, IdGlobalProtocols, IdUDPClient;
type
TIdCustomTimeUDP = class(TIdUDPClient)
protected
FBaseDate: TDateTime;
FRoundTripDelay: UInt32;
//
function GetDateTimeCard: UInt32;
function GetDateTime: TDateTime;
procedure InitComponent; override;
public
{$IFDEF WORKAROUND_INLINE_CONSTRUCTORS}
constructor Create(AOwner: TComponent); reintroduce; overload;
{$ENDIF}
{This synchronizes the local clock with the Time Server}
function SyncTime: Boolean;
{This is the number of seconds since 12:00 AM, 1900 - Jan-1}
property DateTimeCard: UInt32 read GetDateTimeCard;
{This is the current time according to the server. TimeZone and Time used
to receive the data are accounted for}
property DateTime: TDateTime read GetDateTime;
{This is the time it took to receive the Time from the server. There is no
need to use this to calculate the current time when using DateTime property
as we have done that here}
property RoundTripDelay: UInt32 read FRoundTripDelay;
published
end;
TIdTimeUDP = class(TIdCustomTimeUDP)
published
{This property is used to set the Date that the Time server bases its
calculations from. If both the server and client are based from the same
date which is higher than the original date, you can extend it beyond the
year 2035}
property BaseDate: TDateTime read FBaseDate write FBaseDate;
property Port default IdPORT_TIME;
end;
implementation
uses
{$IFDEF USE_VCL_POSIX}
{$IFDEF DARWIN}
Macapi.CoreServices,
{$ENDIF}
Posix.SysTime,
{$ENDIF}
IdStack, SysUtils; //Sysutils added to facilitate inlining.
{ TIdCustomTimeUDP }
{$IFDEF WORKAROUND_INLINE_CONSTRUCTORS}
constructor TIdCustomTimeUDP.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
{$ENDIF}
procedure TIdCustomTimeUDP.InitComponent;
begin
inherited;
Port := IdPORT_TIME;
{This indicates that the default date is Jan 1, 1900 which was specified
by RFC 868.}
FBaseDate := TIME_BASEDATE;
end;
function TIdCustomTimeUDP.GetDateTime: TDateTime;
var
BufCard: UInt32;
begin
BufCard := GetDateTimeCard;
if BufCard <> 0 then begin
{The formula is The Time cardinal we receive divided by (24 * 60*60 for days + RoundTrip divided by one-thousand since this is based on seconds
- the Time Zone difference}
Result := ( ((BufCard + (FRoundTripDelay div 1000))/ (24 * 60 * 60) ) + Int(fBaseDate))
- TimeZoneBias;
end else begin
{ Somehow, I really doubt we are ever going to really get a time such as
12/30/1899 12:00 am so use that as a failure test}
Result := 0;
end;
end;
function TIdCustomTimeUDP.GetDateTimeCard: UInt32;
var
LTimeBeforeRetrieve: TIdTicks;
LBuffer : TIdBytes;
begin
//Important - This must send an empty UDP Datagram
Send(''); {Do not Localize}
LTimeBeforeRetrieve := Ticks64;
SetLength(LBuffer,4);
ReceiveBuffer(LBuffer);
Result := BytesToUInt32(LBuffer);
Result := GStack.NetworkToHost(Result);
{Theoritically, it should take about 1/2 of the time to receive the data
but in practice, it could be any portion depending upon network conditions. This is also
as per RFC standard}
{This is just in case the TickCount rolled back to zero}
FRoundTripDelay := GetElapsedTicks(LTimeBeforeRetrieve) div 2;
end;
function TIdCustomTimeUDP.SyncTime: Boolean;
var
LBufTime: TDateTime;
begin
LBufTime := DateTime;
Result := LBufTime <> 0;
if Result then begin
Result := IndySetLocalTime(LBufTime);
end;
end;
end.
| 28.45614 | 148 | 0.696054 |
f1654055a96ec9bf900280c7c2b365a85f761f97 | 14,606 | pas | Pascal | 2dBGI/docs/d3d/DirectSetup.pas | JazzMaster/LazGFX | e1d1bb0b698861651f28301b48abce774be5e1d1 | [
"Apache-2.0"
]
| 2 | 2021-10-15T12:00:45.000Z | 2022-01-17T20:38:17.000Z | 2dBGI/docs/d3d/DirectSetup.pas | JazzMaster/LazGFX | e1d1bb0b698861651f28301b48abce774be5e1d1 | [
"Apache-2.0"
]
| 21 | 2018-10-19T18:07:36.000Z | 2019-06-24T02:34:19.000Z | 2dBGI/docs/d3d/DirectSetup.pas | JazzMaster/LazGFX | e1d1bb0b698861651f28301b48abce774be5e1d1 | [
"Apache-2.0"
]
| 3 | 2019-07-03T06:22:43.000Z | 2022-01-17T20:38:19.000Z | {******************************************************************************}
{* *}
{* Copyright (C) 1995-1997 Microsoft Corporation. All Rights Reserved. *}
{* *}
{* Files: dsetup.h *}
{* Content: DirectXSetup, error codes and flags *}
{* *}
{* DirectX 9.0 Delphi / FreePascal adaptation by Alexey Barkovoy *}
{* E-Mail: directx@clootie.ru *}
{* *}
{* Latest version can be downloaded from: *}
{* http://www.clootie.ru *}
{* http://sourceforge.net/projects/delphi-dx9sdk *}
{* *}
{*----------------------------------------------------------------------------*}
{* $Id: DirectSetup.pas,v 1.1 2005/10/10 21:11:07 clootie Exp $ }
{******************************************************************************}
{ }
{ Obtained through: Joint Endeavour of Delphi Innovators (Project JEDI) }
{ }
{ 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 }
{ }
{******************************************************************************}
{$I DirectX.inc}
unit DirectSetup;
interface
uses
Windows;
////////////////////////////////////////////////////////////////////////
// Global level dynamic loading support
{$IFDEF DYNAMIC_LINK_ALL}
{$DEFINE DIRECTSETUP_DYNAMIC_LINK}
{$ENDIF}
{$IFDEF DYNAMIC_LINK_EXPLICIT_ALL}
{$DEFINE DIRECTSETUP_DYNAMIC_LINK_EXPLICIT}
{$ENDIF}
// Remove "dots" below to force some kind of dynamic linking
{.$DEFINE DIRECTSETUP_DYNAMIC_LINK}
{.$DEFINE DIRECTSETUP_DYNAMIC_LINK_EXPLICIT}
const
// FOURCC_VERS = mmioFOURCC('v','e','r','s')
FOURCC_VERS = Byte('v') or (Byte('e') shl 8) or (Byte('r') shl 16) or (Byte('s') shl 24);
// DSETUP Error Codes, must remain compatible with previous setup.
DSETUPERR_SUCCESS_RESTART = 1;
DSETUPERR_SUCCESS = 0;
DSETUPERR_BADWINDOWSVERSION = -1;
DSETUPERR_SOURCEFILENOTFOUND = -2;
DSETUPERR_NOCOPY = -5;
DSETUPERR_OUTOFDISKSPACE = -6;
DSETUPERR_CANTFINDINF = -7;
DSETUPERR_CANTFINDDIR = -8;
DSETUPERR_INTERNAL = -9;
DSETUPERR_UNKNOWNOS = -11;
DSETUPERR_NEWERVERSION = -14;
DSETUPERR_NOTADMIN = -15;
DSETUPERR_UNSUPPORTEDPROCESSOR = -16;
DSETUPERR_MISSINGCAB_MANAGEDDX = -17;
DSETUPERR_NODOTNETFRAMEWORKINSTALLED = -18;
DSETUPERR_CABDOWNLOADFAIL = -19;
DSETUPERR_DXCOMPONENTFILEINUSE = -20;
DSETUPERR_UNTRUSTEDCABINETFILE = -21;
// DSETUP flags. DirectX 5.0 apps should use these flags only.
DSETUP_DDRAWDRV = $00000008; (* install DirectDraw Drivers *)
DSETUP_DSOUNDDRV = $00000010; (* install DirectSound Drivers *)
DSETUP_DXCORE = $00010000; (* install DirectX runtime *)
DSETUP_DIRECTX = (DSETUP_DXCORE or DSETUP_DDRAWDRV or DSETUP_DSOUNDDRV);
DSETUP_MANAGEDDX = $00004000; (* OBSOLETE. install managed DirectX *)
DSETUP_TESTINSTALL = $00020000; (* just test install, don't do anything *)
// These OBSOLETE flags are here for compatibility with pre-DX5 apps only.
// They are present to allow DX3 apps to be recompiled with DX5 and still work.
// DO NOT USE THEM for DX5. They will go away in future DX releases.
DSETUP_DDRAW = $00000001; (* OBSOLETE. install DirectDraw *)
DSETUP_DSOUND = $00000002; (* OBSOLETE. install DirectSound *)
DSETUP_DPLAY = $00000004; (* OBSOLETE. install DirectPlay *)
DSETUP_DPLAYSP = $00000020; (* OBSOLETE. install DirectPlay Providers *)
DSETUP_DVIDEO = $00000040; (* OBSOLETE. install DirectVideo *)
DSETUP_D3D = $00000200; (* OBSOLETE. install Direct3D *)
DSETUP_DINPUT = $00000800; (* OBSOLETE. install DirectInput *)
DSETUP_DIRECTXSETUP = $00001000; (* OBSOLETE. install DirectXSetup DLL's *)
DSETUP_NOUI = $00002000; (* OBSOLETE. install DirectX with NO UI *)
DSETUP_PROMPTFORDRIVERS = $10000000; (* OBSOLETE. prompt when replacing display/audio drivers *)
DSETUP_RESTOREDRIVERS = $20000000; (* OBSOLETE. restore display/audio drivers *)
//******************************************************************
// DirectX Setup Callback mechanism
//******************************************************************
// DSETUP Message Info Codes, passed to callback as Reason parameter.
DSETUP_CB_MSG_NOMESSAGE = 0;
DSETUP_CB_MSG_INTERNAL_ERROR = 10;
DSETUP_CB_MSG_BEGIN_INSTALL = 13;
DSETUP_CB_MSG_BEGIN_INSTALL_RUNTIME = 14;
DSETUP_CB_MSG_PROGRESS = 18;
DSETUP_CB_MSG_WARNING_DISABLED_COMPONENT = 19;
type
PDSetupCBProgress = ^TDSetupCBProgress;
_DSETUP_CB_PROGRESS = record
dwPhase: DWORD;
dwInPhaseMaximum: DWORD;
dwInPhaseProgress: DWORD;
dwOverallMaximum: DWORD;
dwOverallProgress: DWORD;
end;
DSETUP_CB_PROGRESS = _DSETUP_CB_PROGRESS;
TDSetupCBProgress = _DSETUP_CB_PROGRESS;
_DSETUP_CB_PROGRESS_PHASE = (
DSETUP_INITIALIZING,
DSETUP_EXTRACTING,
DSETUP_COPYING,
DSETUP_FINALIZING
);
TDSetupCBProgressPhase = _DSETUP_CB_PROGRESS_PHASE;
//
// Data Structures
//
PDirectXRegisterAppA = ^TDirectXRegisterAppA;
_DIRECTXREGISTERAPPA = record
dwSize: DWORD;
dwFlags: DWORD;
lpszApplicationName: PAnsiChar;
lpGUID: PGUID;
lpszFilename: PAnsiChar;
lpszCommandLine: PAnsiChar;
lpszPath: PAnsiChar;
lpszCurrentDirectory: PAnsiChar;
end;
DIRECTXREGISTERAPPA = _DIRECTXREGISTERAPPA;
TDirectXRegisterAppA = _DIRECTXREGISTERAPPA;
PDirectXRegisterApp2A = ^TDirectXRegisterApp2A;
_DIRECTXREGISTERAPP2A = record
dwSize: DWORD;
dwFlags: DWORD;
lpszApplicationName: PAnsiChar;
lpGUID: PGUID;
lpszFilename: PAnsiChar;
lpszCommandLine: PAnsiChar;
lpszPath: PAnsiChar;
lpszCurrentDirectory: PAnsiChar;
lpszLauncherName: PAnsiChar;
end;
DIRECTXREGISTERAPP2A = _DIRECTXREGISTERAPP2A;
TDirectXRegisterApp2A = _DIRECTXREGISTERAPP2A;
PDirectXRegisterAppW = ^TDirectXRegisterAppW;
_DIRECTXREGISTERAPPW = record
dwSize: DWORD;
dwFlags: DWORD;
lpszApplicationName: PWideChar;
lpGUID: PGUID;
lpszFilename: PWideChar;
lpszCommandLine: PWideChar;
lpszPath: PWideChar;
lpszCurrentDirectory: PWideChar;
end;
DIRECTXREGISTERAPPW = _DIRECTXREGISTERAPPW;
TDirectXRegisterAppW = _DIRECTXREGISTERAPPW;
PDirectXRegisterApp2W = ^TDirectXRegisterApp2W;
_DIRECTXREGISTERAPP2W = record
dwSize: DWORD;
dwFlags: DWORD;
lpszApplicationName: PWideChar;
lpGUID: PGUID;
lpszFilename: PWideChar;
lpszCommandLine: PWideChar;
lpszPath: PWideChar;
lpszCurrentDirectory: PWideChar;
lpszLauncherName: PWideChar;
end;
DIRECTXREGISTERAPP2W = _DIRECTXREGISTERAPP2W;
TDirectXRegisterApp2W = _DIRECTXREGISTERAPP2W;
PDirectXRegisterApp = ^TDirectXRegisterApp;
PDirectXRegisterApp2 = ^TDirectXRegisterApp2;
{$IFDEF UNICODE}
TDirectXRegisterApp = TDirectXRegisterAppW;
TDirectXRegisterApp2 = TDirectXRegisterAppW2;
{$ELSE}
TDirectXRegisterApp = TDirectXRegisterAppA;
TDirectXRegisterApp2 = TDirectXRegisterApp2A;
{$ENDIF}
//
// API
//
var
DirectXSetupW: function (hWnd: HWND; lpszRootPath: PWideChar; dwFlags: DWORD): Integer; stdcall;
DirectXSetupA: function (hWnd: HWND; lpszRootPath: PAnsiChar; dwFlags: DWORD): Integer; stdcall;
DirectXSetup: function (hWnd: HWND; lpszRootPath: PChar; dwFlags: DWORD): Integer; stdcall;
DirectXRegisterApplicationW: function (hWnd: HWND; const lpDXRegApp: TDirectXRegisterAppW): Integer; stdcall;
DirectXRegisterApplicationA: function (hWnd: HWND; const lpDXRegApp: TDirectXRegisterAppA): Integer; stdcall;
DirectXRegisterApplication: function (hWnd: HWND; const lpDXRegApp: TDirectXRegisterApp): Integer; stdcall;
DirectXUnRegisterApplication: function (hWnd: HWND; const lpGUID: TGUID): Integer; stdcall;
type
TDSetupCallback = function (Reason: DWORD; MsgType: DWORD; (* Same as flags to MessageBox *)
szMessage: PChar; szName: PChar; pInfo: Pointer): DWORD; stdcall;
var
DirectXSetupSetCallback: function (Callback: TDSetupCallback): Integer; stdcall;
DirectXSetupGetVersion: function (out lpdwVersion, lpdwMinorVersion: DWORD): Integer; stdcall;
DirectXSetupShowEULA: function(hWndParent: HWND): Integer; stdcall;
DirectXSetupGetEULAA: function(lpszEULA: PAnsiChar; cchEULA: LongWord; LangID: Word): LongWord; stdcall;
DirectXSetupGetEULAW: function(lpszEULA: PWideChar; cchEULA: LongWord; LangID: Word): LongWord; stdcall;
DirectXSetupGetEULA: function(lpszEULA: PChar; cchEULA: LongWord; LangID: Word): LongWord; stdcall;
function DirectSetupLoaded: Boolean;
function UnLoadDirectSetup: Boolean;
function LoadDirectSetup: Boolean;
implementation
const
DirectSetupDll = 'dsetup.dll';
var
DirectSetupLib: THandle = 0;
function DirectSetupLoaded: Boolean;
begin
Result:= (DirectSetupLib <> 0);
end;
function UnLoadDirectSetup: Boolean;
begin
Result:= True;
if (DirectSetupLib <> 0) then
begin
Result:= Result and FreeLibrary(DirectSetupLib);
DirectXSetupA := nil;
DirectXSetupW := nil;
DirectXSetup := nil;
DirectXRegisterApplicationA := nil;
DirectXRegisterApplicationW := nil;
DirectXRegisterApplication := nil;
DirectXUnRegisterApplication := nil;
DirectXSetupSetCallback := nil;
DirectXSetupGetVersion := nil;
DirectXSetupShowEULA := nil;
DirectXSetupGetEULAA := nil;
DirectXSetupGetEULAW := nil;
DirectXSetupGetEULA := nil;
DirectSetupLib:= 0;
end;
end;
function LoadDirectSetup: Boolean;
begin
Result:= DirectSetupLoaded;
if (not Result) then
begin
DirectSetupLib:= LoadLibrary(DirectSetupDll);
if (DirectSetupLib <> 0) then
begin
DirectXSetupA := GetProcAddress(DirectSetupLib, 'DirectXSetupA');
DirectXSetupW := GetProcAddress(DirectSetupLib, 'DirectXSetupW');
{$IFDEF UNICODE}
DirectXSetup := DirectXSetupW;
{$ELSE}
DirectXSetup := DirectXSetupA;
{$ENDIF}
DirectXRegisterApplicationA := GetProcAddress(DirectSetupLib, 'DirectXRegisterApplicationA');
DirectXRegisterApplicationW := GetProcAddress(DirectSetupLib, 'DirectXRegisterApplicationW');
{$IFDEF UNICODE}
DirectXRegisterApplication := DirectXRegisterApplicationW;
{$ELSE}
DirectXRegisterApplication := DirectXRegisterApplicationA;
{$ENDIF}
DirectXUnRegisterApplication := GetProcAddress(DirectSetupLib, 'DirectXUnRegisterApplication');
DirectXSetupSetCallback := GetProcAddress(DirectSetupLib, 'DirectXSetupSetCallback');
DirectXSetupGetVersion := GetProcAddress(DirectSetupLib, 'DirectXSetupGetVersion');
DirectXSetupShowEULA := GetProcAddress(DirectSetupLib, 'DirectXSetupShowEULA');;
DirectXSetupGetEULAA := GetProcAddress(DirectSetupLib, 'DirectXSetupGetEULAA');;
DirectXSetupGetEULAW := GetProcAddress(DirectSetupLib, 'DirectXSetupGetEULAW');;
{$IFDEF UNICODE}
DirectXSetupGetEULA := DirectXSetupGetEULAW;
{$ELSE}
DirectXSetupGetEULA := DirectXSetupGetEULAA;
{$ENDIF}
end;
// At least basic procedure is found!
Result:= Assigned(DirectXSetup);
if not Result then UnLoadDirectSetup;
end;
end;
initialization
{$IFNDEF DIRECTSETUP_DYNAMIC_LINK_EXPLICIT}
LoadDirectSetup;
{$ENDIF}
finalization
UnLoadDirectSetup;
end.
| 41.259887 | 112 | 0.596741 |
83eb30ef1a805849eae551b6f4b1fa93603e59b7 | 2,543 | dfm | Pascal | src/misc/MuiltCheckBoxTest/Form.Main.dfm | bogdanpolak/internalBSC | 75f7f9be576de7af0f1748f602137cca4dc8bb84 | [
"MIT"
]
| 3 | 2019-01-13T08:41:55.000Z | 2020-11-11T03:00:56.000Z | src/misc/MuiltCheckBoxTest/Form.Main.dfm | bogdanpolak/internalBSC | 75f7f9be576de7af0f1748f602137cca4dc8bb84 | [
"MIT"
]
| 7 | 2018-09-27T15:27:35.000Z | 2019-08-13T15:30:23.000Z | src/misc/MuiltCheckBoxTest/Form.Main.dfm | bogdanpolak/internalBSC | 75f7f9be576de7af0f1748f602137cca4dc8bb84 | [
"MIT"
]
| 3 | 2019-01-13T08:41:57.000Z | 2020-11-11T03:01:00.000Z | object Form1: TForm1
Left = 0
Top = 0
Caption = 'Form1'
ClientHeight = 599
ClientWidth = 690
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
PixelsPerInch = 96
TextHeight = 13
object GroupBox1: TGroupBox
AlignWithMargins = True
Left = 3
Top = 3
Width = 684
Height = 54
Align = alTop
Caption = 'GroupBox1'
Padding.Top = 2
Padding.Bottom = 1
TabOrder = 0
object Label1: TLabel
AlignWithMargins = True
Left = 175
Top = 23
Width = 58
Height = 22
Margins.Top = 6
Margins.Bottom = 6
Align = alLeft
Caption = 'Liczba grup:'
Layout = tlCenter
ExplicitHeight = 13
end
object Bevel1: TBevel
AlignWithMargins = True
Left = 424
Top = 20
Width = 34
Height = 28
Align = alLeft
Shape = bsSpacer
ExplicitLeft = 287
end
object Label2: TLabel
AlignWithMargins = True
Left = 272
Top = 23
Width = 26
Height = 22
Margins.Top = 6
Margins.Bottom = 6
Align = alLeft
Caption = 'Tryb:'
Layout = tlCenter
ExplicitLeft = 268
ExplicitHeight = 13
end
object Button1: TButton
AlignWithMargins = True
Left = 5
Top = 20
Width = 164
Height = 28
Align = alLeft
Caption = 'Dodaj zestaw CheckBox-'#243'w'
TabOrder = 0
OnClick = Button1Click
ExplicitTop = 18
ExplicitHeight = 31
end
object Edit1: TEdit
AlignWithMargins = True
Left = 239
Top = 23
Width = 27
Height = 22
Margins.Top = 6
Margins.Bottom = 6
Align = alLeft
Alignment = taCenter
TabOrder = 1
Text = '6'
ExplicitLeft = 254
ExplicitHeight = 21
end
object btnClearAll: TButton
AlignWithMargins = True
Left = 464
Top = 20
Width = 138
Height = 28
Align = alLeft
Caption = 'btnClearAll'
TabOrder = 2
OnClick = btnClearAllClick
ExplicitLeft = 327
end
object ComboBox1: TComboBox
AlignWithMargins = True
Left = 304
Top = 23
Width = 114
Height = 21
Margins.Top = 6
Align = alLeft
Style = csDropDownList
ItemIndex = 0
TabOrder = 3
Text = 'Standardowy'
Items.Strings = (
'Standardowy'
'Szybki (No REDRAW)')
end
end
end
| 20.844262 | 47 | 0.562721 |
f1dfccece35cdc0ba31ab495d73af41bc993b7b2 | 185 | pas | Pascal | Auto-generated-tasks/Difficulty-2/Task-4/Solution.pas | Alexxx180/EasyTasks | 3661e062f0dc48e10d463816c4ab725d1eec6cc7 | [
"MIT"
]
| null | null | null | Auto-generated-tasks/Difficulty-2/Task-4/Solution.pas | Alexxx180/EasyTasks | 3661e062f0dc48e10d463816c4ab725d1eec6cc7 | [
"MIT"
]
| null | null | null | Auto-generated-tasks/Difficulty-2/Task-4/Solution.pas | Alexxx180/EasyTasks | 3661e062f0dc48e10d463816c4ab725d1eec6cc7 | [
"MIT"
]
| null | null | null | Var
Cnt:=5, k1, Rez:=0:integer;
T:Array[0..Cnt] of integer;
Begin
for k1:= 0 to Cnt do begin
if (T[k1] < 186) then begin
Rez := Rez + 1;
end;
end;
WriteLn("Rez=", Rez);
End. | 16.818182 | 29 | 0.583784 |
6ab456018b04f79d12e436c7fe9ae8393a243b36 | 175,928 | pas | Pascal | Projects/Main.pas | shortydoggg/issrc | 91b448a4b525f7db31eb9cdb421c2d57c8e95137 | [
"FSFAP"
]
| 2,613 | 2015-01-06T18:50:22.000Z | 2022-03-31T11:24:23.000Z | Projects/Main.pas | shortydoggg/issrc | 91b448a4b525f7db31eb9cdb421c2d57c8e95137 | [
"FSFAP"
]
| 249 | 2015-01-07T02:59:17.000Z | 2022-03-31T20:13:14.000Z | Projects/Main.pas | shortydoggg/issrc | 91b448a4b525f7db31eb9cdb421c2d57c8e95137 | [
"FSFAP"
]
| 802 | 2015-01-08T12:05:11.000Z | 2022-03-29T15:26:10.000Z | unit Main;
{
Inno Setup
Copyright (C) 1997-2021 Jordan Russell
Portions by Martijn Laan
For conditions of distribution and use, see LICENSE.TXT.
Background form
}
interface
{$I VERSION.INC}
uses
Windows, SysUtils, Messages, Classes, Graphics, Controls, Forms, Dialogs,
SetupForm, StdCtrls, Struct, DebugStruct, Int64Em, CmnFunc, CmnFunc2,
SetupTypes, ScriptRunner, BidiUtils, RestartManager;
type
TMainForm = class(TSetupForm)
procedure FormResize(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure FormPaint(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
IsMinimized, HideWizard: Boolean;
function MainWindowHook(var Message: TMessage): Boolean;
procedure UpdateWizardFormVisibility;
procedure WMSysCommand(var Message: TWMSysCommand); message WM_SYSCOMMAND;
procedure WMEraseBkgnd(var Message: TWMEraseBkgnd); message WM_ERASEBKGND;
procedure WMGetDlgCode(var Message: TWMGetDlgCode); message WM_GETDLGCODE;
procedure WMShowWindow(var Message: TWMShowWindow); message WM_SHOWWINDOW;
public
{ Public declarations }
CurStep: TSetupStep;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Finish(const FromPreparingPage: Boolean);
procedure InitializeWizard;
function Install: Boolean;
procedure SetStep(const AStep: TSetupStep; const HandleExceptions: Boolean);
class procedure ShowException(Sender: TObject; E: Exception);
class procedure ShowExceptionMsg(const S: String);
procedure ShowAboutBox;
end;
TEntryType = (seLanguage, seCustomMessage, sePermission, seType, seComponent,
seTask, seDir, seFile, seFileLocation, seIcon, seIni, seRegistry,
seInstallDelete, seUninstallDelete, seRun, seUninstallRun);
const
EntryStrings: array[TEntryType] of Integer = (SetupLanguageEntryStrings,
SetupCustomMessageEntryStrings, SetupPermissionEntryStrings,
SetupTypeEntryStrings, SetupComponentEntryStrings, SetupTaskEntryStrings,
SetupDirEntryStrings, SetupFileEntryStrings, SetupFileLocationEntryStrings,
SetupIconEntryStrings, SetupIniEntryStrings, SetupRegistryEntryStrings,
SetupDeleteEntryStrings, SetupDeleteEntryStrings, SetupRunEntryStrings,
SetupRunEntryStrings);
EntryAnsiStrings: array[TEntryType] of Integer = (SetupLanguageEntryAnsiStrings,
SetupCustomMessageEntryAnsiStrings, SetupPermissionEntryAnsiStrings,
SetupTypeEntryAnsiStrings, SetupComponentEntryAnsiStrings, SetupTaskEntryAnsiStrings,
SetupDirEntryAnsiStrings, SetupFileEntryAnsiStrings, SetupFileLocationEntryAnsiStrings,
SetupIconEntryAnsiStrings, SetupIniEntryAnsiStrings, SetupRegistryEntryAnsiStrings,
SetupDeleteEntryAnsiStrings, SetupDeleteEntryAnsiStrings, SetupRunEntryAnsiStrings,
SetupRunEntryAnsiStrings);
{ Exit codes that are assigned to the SetupExitCode variable.
Note: SetupLdr also returns exit codes with the same numbers. }
ecInitializationError = 1; { Setup failed to initialize. }
ecCancelledBeforeInstall = 2; { User clicked Cancel before the actual
installation started. }
ecNextStepError = 3; { A fatal exception occurred while moving to
the next step. }
ecInstallationError = 4; { A fatal exception occurred during
installation. }
ecInstallationCancelled = 5; { User clicked Cancel during installation,
or clicked Abort at an Abort-Retry-Ignore
dialog. }
ecKilledByDebugger = 6; { User killed the Setup process from within
the debugger. }
ecPrepareToInstallFailed = 7; { Stopped on Preparing to Install page;
restart not needed. }
ecPrepareToInstallFailedRestartNeeded = 8;
{ Stopped on Preparing to Install page;
restart needed. }
CodeRunnerNamingAttribute = 'Event';
var
MainForm: TMainForm;
{ Variables for command line parameters }
SetupLdrMode: Boolean;
SetupLdrOriginalFilename: String;
SetupLdrOffset0, SetupLdrOffset1: Longint;
SetupNotifyWndPresent: Boolean;
SetupNotifyWnd: HWND;
InitLang: String;
InitDir, InitProgramGroup: String;
InitLoadInf, InitSaveInf: String;
InitNoIcons, InitSilent, InitVerySilent, InitNoRestart, InitCloseApplications,
InitNoCloseApplications, InitForceCloseApplications, InitNoForceCloseApplications,
InitLogCloseApplications, InitRestartApplications, InitNoRestartApplications,
InitNoCancel: Boolean;
InitSetupType: String;
InitComponents, InitTasks: TStringList;
InitComponentsSpecified: Boolean;
InitDeselectAllTasks: Boolean;
InitPassword: String;
InitRestartExitCode: Integer;
InitPrivilegesRequired: TSetupPrivilegesRequired;
HasInitPrivilegesRequired: Boolean;
InitSuppressMsgBoxes: Boolean;
DetachedUninstMsgFile: Boolean;
NewParamsForCode: TStringList;
{ Debugger }
OriginalEntryIndexes: array[TEntryType] of TList;
{ 'Constants' }
SourceDir, TempInstallDir, WinDir, WinSystemDir, WinSysWow64Dir, WinSysNativeDir, SystemDrive,
ProgramFiles32Dir, CommonFiles32Dir, ProgramFiles64Dir, CommonFiles64Dir,
ProgramFilesUserDir, CommonFilesUserDir, SavedGamesUserDir, CmdFilename, SysUserInfoName,
SysUserInfoOrg, UninstallExeFilename: String;
{ Uninstall 'constants' }
UninstallExpandedAppId, UninstallExpandedApp, UninstallExpandedGroup,
UninstallExpandedGroupName, UninstallExpandedLanguage: String;
UninstallSilent: Boolean;
{ Variables read in from the SETUP.0 file }
SetupHeader: TSetupHeader;
LangOptions: TSetupLanguageEntry;
Entries: array[TEntryType] of TList;
WizardImages: TList;
WizardSmallImages: TList;
CloseApplicationsFilterList: TStringList;
{ User options }
ActiveLanguage: Integer = -1;
ActiveLicenseText, ActiveInfoBeforeText, ActiveInfoAfterText: AnsiString;
WizardUserInfoName, WizardUserInfoOrg, WizardUserInfoSerial, WizardDirValue, WizardGroupValue: String;
WizardNoIcons, WizardPreparingYesRadio: Boolean;
WizardSetupType: PSetupTypeEntry;
WizardComponents, WizardDeselectedComponents, WizardTasks, WizardDeselectedTasks: TStringList;
NeedToAbortInstall: Boolean;
{ Check/BeforeInstall/AfterInstall 'constants' }
CheckOrInstallCurrentFilename, CheckOrInstallCurrentSourceFilename: String;
{ RestartManager API state.
Note: the handle and key might change while running, see TWizardForm.QueryRestartManager. }
RmSessionStarted, RmFoundApplications, RmDoRestart: Boolean;
RmSessionHandle: DWORD;
RmSessionKey: array[0..CCH_RM_SESSION_KEY] of WideChar;
RmRegisteredFilesCount: Integer;
{ Other }
ShowLanguageDialog, MatchedLangParameter: Boolean;
InstallMode: (imNormal, imSilent, imVerySilent);
HasIcons, IsNT, IsWin64, Is64BitInstallMode, IsAdmin, IsPowerUserOrAdmin, IsAdminInstallMode,
NeedPassword, NeedSerial, NeedsRestart, RestartSystem,
IsUninstaller, AllowUninstallerShutdown, AcceptedQueryEndSessionInProgress: Boolean;
InstallDefaultDisableFsRedir, ScriptFuncDisableFsRedir: Boolean;
InstallDefaultRegView: TRegView = rvDefault;
HasCustomType, HasComponents, HasTasks: Boolean;
ProcessorArchitecture: TSetupProcessorArchitecture = paUnknown;
WindowsVersion: Cardinal;
NTServicePackLevel: Word;
WindowsProductType: Byte;
WindowsSuiteMask: Word;
MinimumSpace: Integer64;
DeleteFilesAfterInstallList, DeleteDirsAfterInstallList: TStringList;
ExpandedAppName, ExpandedAppVerName, ExpandedAppCopyright, ExpandedAppMutex: String;
DisableCodeConsts: Integer;
SetupExitCode: Integer;
CreatedIcon: Boolean;
RestartInitiatedByThisProcess, DownloadTemporaryFileProcessMessages: Boolean;
{$IFDEF IS_D12}
TaskbarButtonHidden: Boolean;
{$ENDIF}
InstallModeRootKey: HKEY;
CodeRunner: TScriptRunner;
procedure CodeRunnerOnLog(const S: String);
procedure CodeRunnerOnLogFmt(const S: String; const Args: array of const);
function CodeRunnerOnDebug(const Position: LongInt;
var ContinueStepOver: Boolean): Boolean;
function CodeRunnerOnDebugIntermediate(const Position: LongInt;
var ContinueStepOver: Boolean): Boolean;
procedure CodeRunnerOnDllImport(var DllName: String; var ForceDelayLoad: Boolean);
procedure CodeRunnerOnException(const Exception: AnsiString; const Position: LongInt);
procedure CreateTempInstallDir;
procedure DebugNotifyEntry(EntryType: TEntryType; Number: Integer);
procedure DeinitSetup(const AllowCustomSetupExitCode: Boolean);
function ExitSetupMsgBox: Boolean;
function ExpandConst(const S: String): String;
function ExpandConstEx(const S: String; const CustomConsts: array of String): String;
function ExpandConstEx2(const S: String; const CustomConsts: array of String;
const DoExpandIndividualConst: Boolean): String;
function ExpandConstIfPrefixed(const S: String): String;
function GetCustomMessageValue(const AName: String; var AValue: String): Boolean;
function GetShellFolder(const Common: Boolean; const ID: TShellFolderID;
ReadOnly: Boolean): String;
function GetShellFolderByCSIDL(Folder: Integer; const Create: Boolean): String;
function GetUninstallRegKeyBaseName(const ExpandedAppId: String): String;
function GetUninstallRegSubkeyName(const UninstallRegKeyBaseName: String): String;
function GetPreviousData(const ExpandedAppID, ValueName, DefaultValueData: String): String;
function GetPreviousLanguage(const ExpandedAppID: String): Integer;
procedure InitializeAdminInstallMode(const AAdminInstallMode: Boolean);
procedure Initialize64BitInstallMode(const A64BitInstallMode: Boolean);
procedure Log64BitInstallMode;
procedure InitializeCommonVars;
procedure InitializeSetup;
procedure InitMainNonSHFolderConsts;
function InstallOnThisVersion(const MinVersion: TSetupVersionData;
const OnlyBelowVersion: TSetupVersionData): TInstallOnThisVersionResult;
function IsRecurseableDirectory(const FindData: TWin32FindData): Boolean;
procedure LoadSHFolderDLL;
function LoggedAppMessageBox(const Text, Caption: PChar; const Flags: Longint;
const Suppressible: Boolean; const Default: Integer): Integer;
function LoggedMsgBox(const Text, Caption: String; const Typ: TMsgBoxType;
const Buttons: Cardinal; const Suppressible: Boolean; const Default: Integer): Integer;
function LoggedTaskDialogMsgBox(const Icon, Instruction, Text, Caption: String;
const Typ: TMsgBoxType; const Buttons: Cardinal; const ButtonLabels: array of String;
const ShieldButton: Integer; const Suppressible: Boolean; const Default: Integer;
const VerificationText: String = ''; const pfVerificationFlagChecked: PBOOL = nil): Integer;
procedure LogWindowsVersion;
procedure NotifyAfterInstallEntry(const AfterInstall: String);
procedure NotifyAfterInstallFileEntry(const FileEntry: PSetupFileEntry);
procedure NotifyBeforeInstallEntry(const BeforeInstall: String);
procedure NotifyBeforeInstallFileEntry(const FileEntry: PSetupFileEntry);
function PreviousInstallCompleted(const WizardComponents, WizardTasks: TStringList): Boolean;
function CodeRegisterExtraCloseApplicationsResource(const DisableFsRedir: Boolean; const AFilename: String): Boolean;
procedure RegisterResourcesWithRestartManager(const WizardComponents, WizardTasks: TStringList);
procedure RemoveTempInstallDir;
procedure SaveResourceToTempFile(const ResName, Filename: String);
procedure SetActiveLanguage(const I: Integer);
procedure SetTaskbarButtonVisibility(const AVisible: Boolean);
procedure ShellExecuteAsOriginalUser(hWnd: HWND; Operation, FileName, Parameters, Directory: LPWSTR; ShowCmd: Integer); stdcall;
function ShouldDisableFsRedirForFileEntry(const FileEntry: PSetupFileEntry): Boolean;
function ShouldDisableFsRedirForRunEntry(const RunEntry: PSetupRunEntry): Boolean;
function EvalDirectiveCheck(const Expression: String): Boolean;
function ShouldProcessEntry(const WizardComponents, WizardTasks: TStringList;
const Components, Tasks, Languages, Check: String): Boolean;
function ShouldProcessFileEntry(const WizardComponents, WizardTasks: TStringList;
const FileEntry: PSetupFileEntry; const IgnoreCheck: Boolean): Boolean;
function ShouldProcessIconEntry(const WizardComponents, WizardTasks: TStringList;
const WizardNoIcons: Boolean; const IconEntry: PSetupIconEntry): Boolean;
function ShouldProcessRunEntry(const WizardComponents, WizardTasks: TStringList;
const RunEntry: PSetupRunEntry): Boolean;
function TestPassword(const Password: String): Boolean;
procedure UnloadSHFolderDLL;
function WindowsVersionAtLeast(const AMajor, AMinor: Byte): Boolean;
implementation
uses
ShellAPI, ShlObj,
Msgs, MsgIDs, Install, InstFunc, InstFnc2, RedirFunc, PathFunc,
Compress, CompressZlib, bzlib, LZMADecomp, ArcFour, SetupEnt, SelLangForm,
Wizard, DebugClient, VerInfo, Extract, FileClass, Logging, MD5, SHA1,
{$IFNDEF Delphi3orHigher} OLE2, {$ELSE} ActiveX, {$ENDIF}
SimpleExpression, Helper, SpawnClient, SpawnServer, DotNet, BitmapImage,
TaskDialog;
{$R *.DFM}
var
ShellFolders: array[Boolean, TShellFolderID] of String;
ShellFoldersRead: array[Boolean, TShellFolderID] of Boolean;
SHFolderDLLHandle: HMODULE;
SHGetFolderPathFunc: function(hwndOwner: HWND; nFolder: Integer;
hToken: THandle; dwFlags: DWORD; pszPath: PChar): HRESULT; stdcall;
SHGetKnownFolderPathFunc: function(const rfid: TGUID; dwFlags: DWORD; hToken: THandle;
var ppszPath: PWideChar): HRESULT; stdcall;
DecompressorDLLHandle: HMODULE;
DecryptDLLHandle: HMODULE;
type
TDummyClass = class
public
class function ExpandCheckOrInstallConstant(Sender: TSimpleExpression;
const Constant: String): String;
class function EvalInstallIdentifier(Sender: TSimpleExpression;
const Name: String; const Parameters: array of const): Boolean;
class function EvalComponentOrTaskIdentifier(Sender: TSimpleExpression;
const Name: String; const Parameters: array of const): Boolean;
class function EvalLanguageIdentifier(Sender: TSimpleExpression;
const Name: String; const Parameters: array of const): Boolean;
class function EvalCheckIdentifier(Sender: TSimpleExpression;
const Name: String; const Parameters: array of const): Boolean;
end;
{ Misc. functions }
function WindowsVersionAtLeast(const AMajor, AMinor: Byte): Boolean;
begin
Result := (WindowsVersion >= Cardinal((AMajor shl 24) or (AMinor shl 16)));
end;
function GetUninstallRegKeyBaseName(const ExpandedAppId: String): String;
{$IFDEF UNICODE}
var
UseAnsiCRC32: Boolean;
S: AnsiString;
I: Integer;
{$ENDIF}
begin
{ Set uninstall registry key base name }
Result := ExpandedAppId;
{ Uninstall registry keys can only be up to 63 characters, otherwise Win95
ignores them. Limit to 57 since Setup will add _isXXX to the end later. }
if Length(Result) > 57 then begin
{ Only keep the first 48 characters, then add an tilde and the CRC
of the original string (to make the trimmed string unique). The
resulting string is 57 characters long. On Unicode, only do this if we
can get a CRC32 compatible with ANSI versions, else there's no point
in shortening since Unicode doesn't run on Win95. }
{$IFDEF UNICODE}
UseAnsiCRC32 := True;
for I := 1 to Length(Result) do begin
if Ord(Result[I]) > 126 then begin
UseAnsiCRC32 := False;
Break;
end;
end;
if UseAnsiCRC32 then begin
S := AnsiString(Result);
FmtStr(Result, '%.48s~%.8x', [Result, GetCRC32(S[1], Length(S)*SizeOf(S[1]))]);
end;
{$ELSE}
FmtStr(Result, '%.48s~%.8x', [Result, GetCRC32(Result[1], Length(Result)*SizeOf(Result[1]))]);
{$ENDIF}
end;
end;
function GetUninstallRegSubkeyName(const UninstallRegKeyBaseName: String): String;
begin
Result := Format('%s\%s_is1', [NEWREGSTR_PATH_UNINSTALL, UninstallRegKeyBaseName]);
end;
{ Based on FindPreviousData in Wizard.pas }
function GetPreviousData(const ExpandedAppID, ValueName, DefaultValueData: String): String;
var
H: HKEY;
begin
Result := DefaultValueData;
if ExpandedAppId <> '' then begin
if RegOpenKeyExView(InstallDefaultRegView, InstallModeRootKey,
PChar(GetUninstallRegSubkeyName(GetUninstallRegKeyBaseName(ExpandedAppId))),
0, KEY_QUERY_VALUE, H) = ERROR_SUCCESS then begin
try
RegQueryStringValue (H, PChar(ValueName), Result);
finally
RegCloseKey (H);
end;
end;
end;
end;
function GetPreviousLanguage(const ExpandedAppID: String): Integer;
var
PrevLang: String;
I: Integer;
begin
{ do not localize or change the following string }
PrevLang := GetPreviousData(ExpandConst(SetupHeader.AppId), 'Inno Setup: Language', '');
if PrevLang <> '' then begin
for I := 0 to Entries[seLanguage].Count-1 do begin
if CompareText(PrevLang, PSetupLanguageEntry(Entries[seLanguage][I]).Name) = 0 then begin
Result := I;
Exit;
end;
end;
end;
Result := -1;
end;
function TestPassword(const Password: String): Boolean;
var
Context: TSHA1Context;
Hash: TSHA1Digest;
begin
SHA1Init(Context);
SHA1Update(Context, PAnsiChar('PasswordCheckHash')^, Length('PasswordCheckHash'));
SHA1Update(Context, SetupHeader.PasswordSalt, SizeOf(SetupHeader.PasswordSalt));
SHA1Update(Context, Pointer(Password)^, Length(Password)*SizeOf(Password[1]));
Hash := SHA1Final(Context);
Result := SHA1DigestsEqual(Hash, SetupHeader.PasswordHash);
end;
class function TDummyClass.ExpandCheckOrInstallConstant(Sender: TSimpleExpression;
const Constant: String): String;
begin
Result := ExpandConst(Constant);
end;
class function TDummyClass.EvalInstallIdentifier(Sender: TSimpleExpression;
const Name: String; const Parameters: array of const): Boolean;
begin
CodeRunner.RunProcedure(AnsiString(Name), Parameters, True);
Result := True; { Result doesn't matter }
end;
procedure NotifyInstallEntry(const Install: String);
procedure EvalInstall(const Expression: String);
var
SimpleExpression: TSimpleExpression;
begin
try
SimpleExpression := TSimpleExpression.Create;
try
SimpleExpression.Expression := Expression;
SimpleExpression.OnEvalIdentifier := TDummyClass.EvalInstallIdentifier;
SimpleExpression.OnExpandConstant := TDummyClass.ExpandCheckOrInstallConstant;
SimpleExpression.ParametersAllowed := True;
SimpleExpression.SingleIdentifierMode := True;
SimpleExpression.Eval;
finally
SimpleExpression.Free;
end;
except
InternalError(Format('Expression error ''%s''', [GetExceptMessage]));
end;
end;
begin
if Install <> '' then begin
try
if CodeRunner = nil then
InternalError('"BeforeInstall" or "AfterInstall" parameter with no CodeRunner');
EvalInstall(Install);
except
{ Don't allow exceptions raised by Before/AfterInstall functions to be propagated out }
Application.HandleException(nil);
end;
end;
end;
procedure NotifyBeforeInstallEntry(const BeforeInstall: String);
begin
NotifyInstallEntry(BeforeInstall);
end;
procedure NotifyBeforeInstallFileEntry(const FileEntry: PSetupFileEntry);
begin
CheckOrInstallCurrentFilename := FileEntry.DestName;
CheckOrInstallCurrentSourceFilename := FileEntry.SourceFilename;
NotifyInstallEntry(FileEntry.BeforeInstall);
CheckOrInstallCurrentFilename := '';
CheckOrInstallCurrentSourceFilename := '';
end;
procedure NotifyAfterInstallEntry(const AfterInstall: String);
begin
NotifyInstallEntry(AfterInstall);
end;
procedure NotifyAfterInstallFileEntry(const FileEntry: PSetupFileEntry);
begin
CheckOrInstallCurrentFilename := FileEntry.DestName;
CheckOrInstallCurrentSourceFilename := FileEntry.SourceFilename;
NotifyInstallEntry(FileEntry.AfterInstall);
CheckOrInstallCurrentFilename := '';
CheckOrInstallCurrentSourceFilename := '';
end;
class function TDummyClass.EvalComponentOrTaskIdentifier(Sender: TSimpleExpression;
const Name: String; const Parameters: array of const): Boolean;
var
WizardItems: TStringList;
begin
WizardItems := TStringList(Sender.Tag);
Result := ListContains(WizardItems, Name);
end;
class function TDummyClass.EvalLanguageIdentifier(Sender: TSimpleExpression;
const Name: String; const Parameters: array of const): Boolean;
begin
Result := CompareText(PSetupLanguageEntry(Entries[seLanguage][ActiveLanguage]).Name, Name) = 0;
end;
class function TDummyClass.EvalCheckIdentifier(Sender: TSimpleExpression;
const Name: String; const Parameters: array of const): Boolean;
begin
Result := CodeRunner.RunBooleanFunction(AnsiString(Name), Parameters, True, False);
end;
function EvalCheck(const Expression: String): Boolean;
var
SimpleExpression: TSimpleExpression;
begin
try
SimpleExpression := TSimpleExpression.Create;
try
SimpleExpression.Lazy := True;
SimpleExpression.Expression := Expression;
SimpleExpression.OnEvalIdentifier := TDummyClass.EvalCheckIdentifier;
SimpleExpression.OnExpandConstant := TDummyClass.ExpandCheckOrInstallConstant;
SimpleExpression.ParametersAllowed := True;
SimpleExpression.SilentOrAllowed := False;
SimpleExpression.SingleIdentifierMode := False;
Result := SimpleExpression.Eval;
finally
SimpleExpression.Free;
end;
except
InternalError(Format('Expression error ''%s''', [GetExceptMessage]));
Result := False;
end;
end;
function EvalDirectiveCheck(const Expression: String): Boolean;
begin
if not TryStrToBoolean(Expression, Result) then
Result := EvalCheck(Expression);
end;
function ShouldProcessEntry(const WizardComponents, WizardTasks: TStringList;
const Components, Tasks, Languages, Check: String): Boolean;
function EvalExpression(const Expression: String;
OnEvalIdentifier: TSimpleExpressionOnEvalIdentifier; Tag: LongInt): Boolean;
var
SimpleExpression: TSimpleExpression;
begin
try
SimpleExpression := TSimpleExpression.Create;
try
SimpleExpression.Lazy := True;
SimpleExpression.Expression := Expression;
SimpleExpression.OnEvalIdentifier := OnEvalIdentifier;
SimpleExpression.ParametersAllowed := False;
SimpleExpression.SilentOrAllowed := True;
SimpleExpression.SingleIdentifierMode := False;
SimpleExpression.Tag := Tag;
Result := SimpleExpression.Eval;
finally
SimpleExpression.Free;
end;
except
InternalError(Format('Expression error ''%s''', [GetExceptMessage]));
Result := False;
end;
end;
var
ProcessComponent, ProcessTask, ProcessLanguage: Boolean;
begin
if (Components <> '') or (Tasks <> '') or (Languages <> '') or (Check <> '') then begin
if (Components <> '') and (WizardComponents <> nil) then
ProcessComponent := EvalExpression(Components, TDummyClass.EvalComponentOrTaskIdentifier, LongInt(WizardComponents))
else
ProcessComponent := True;
if (Tasks <> '') and (WizardTasks <> nil) then
ProcessTask := EvalExpression(Tasks, TDummyClass.EvalComponentOrTaskIdentifier, LongInt(WizardTasks))
else
ProcessTask := True;
if Languages <> '' then
ProcessLanguage := EvalExpression(Languages, TDummyClass.EvalLanguageIdentifier, 0)
else
ProcessLanguage := True;
Result := ProcessComponent and ProcessTask and ProcessLanguage;
if Result and (Check <> '') then begin
try
if CodeRunner = nil then
InternalError('"Check" parameter with no CodeRunner');
Result := EvalCheck(Check);
except
{ Don't allow exceptions raised by Check functions to be propagated out }
Application.HandleException(nil);
Result := False;
end;
end;
end else
Result := True;
end;
function ShouldProcessFileEntry(const WizardComponents, WizardTasks: TStringList;
const FileEntry: PSetupFileEntry; const IgnoreCheck: Boolean): Boolean;
begin
if foDontCopy in FileEntry.Options then begin
Result := False;
Exit;
end;
CheckOrInstallCurrentFilename := FileEntry.DestName;
CheckOrInstallCurrentSourceFilename := FileEntry.SourceFilename;
if IgnoreCheck then
Result := ShouldProcessEntry(WizardComponents, WizardTasks, FileEntry.Components, FileEntry.Tasks, FileEntry.Languages, '')
else
Result := ShouldProcessEntry(WizardComponents, WizardTasks, FileEntry.Components, FileEntry.Tasks, FileEntry.Languages, FileEntry.Check);
CheckOrInstallCurrentFilename := '';
CheckOrInstallCurrentSourceFilename := '';
end;
function ShouldProcessRunEntry(const WizardComponents, WizardTasks: TStringList;
const RunEntry: PSetupRunEntry): Boolean;
begin
if (InstallMode <> imNormal) and (roSkipIfSilent in RunEntry.Options) then
Result := False
else if (InstallMode = imNormal) and (roSkipIfNotSilent in RunEntry.Options) then
Result := False
else
Result := ShouldProcessEntry(WizardComponents, WizardTasks, RunEntry.Components, RunEntry.Tasks, RunEntry.Languages, RunEntry.Check);
end;
function ShouldProcessIconEntry(const WizardComponents, WizardTasks: TStringList;
const WizardNoIcons: Boolean; const IconEntry: PSetupIconEntry): Boolean;
begin
if WizardNoIcons and (IconEntry.Tasks = '') and
(Copy(IconEntry.IconName, 1, 8) = '{group}\') then
Result := False
else
Result := ShouldProcessEntry(WizardComponents, WizardTasks, IconEntry.Components, IconEntry.Tasks, IconEntry.Languages, IconEntry.Check);
end;
function ShouldDisableFsRedirForFileEntry(const FileEntry: PSetupFileEntry): Boolean;
begin
Result := InstallDefaultDisableFsRedir;
if fo32Bit in FileEntry.Options then
Result := False;
if fo64Bit in FileEntry.Options then begin
if not IsWin64 then
InternalError('Cannot install files to 64-bit locations on this version of Windows');
Result := True;
end;
end;
function SlashesToBackslashes(const S: String): String;
var
I: Integer;
begin
Result := S;
for I := 1 to Length(Result) do
if Result[I] = '/' then
Result[I] := '\';
end;
procedure LoadInf(const FileName: String; var WantToSuppressMsgBoxes: Boolean);
const
Section = 'Setup';
var
S: String;
begin
//saved infs
InitLang := GetIniString(Section, 'Lang', InitLang, FileName);
InitDir := GetIniString(Section, 'Dir', InitDir, FileName);
InitProgramGroup := GetIniString(Section, 'Group', InitProgramGroup, FileName);
InitNoIcons := GetIniBool(Section, 'NoIcons', InitNoIcons, FileName);
InitSetupType := GetIniString(Section, 'SetupType', InitSetupType, FileName);
S := GetIniString(Section, 'Components', '$', FileName);
if S <> '$' then begin
InitComponentsSpecified := True;
SetStringsFromCommaString(InitComponents, SlashesToBackslashes(S));
end;
S := GetIniString(Section, 'Tasks', '$', FileName);
if S <> '$' then begin
InitDeselectAllTasks := True;
SetStringsFromCommaString(InitTasks, SlashesToBackslashes(S));
end;
//non saved infs (=non user settable)
InitSilent := GetIniBool(Section, 'Silent', InitSilent, FileName);
InitVerySilent := GetIniBool(Section, 'VerySilent', InitVerySilent, FileName);
InitNoRestart := GetIniBool(Section, 'NoRestart', InitNoRestart, FileName);
InitCloseApplications := GetIniBool(Section, 'CloseApplications', InitCloseApplications, FileName);
InitNoCloseApplications := GetIniBool(Section, 'NoCloseApplications', InitNoCloseApplications, FileName);
InitForceCloseApplications := GetIniBool(Section, 'ForceCloseApplications', InitForceCloseApplications, FileName);
InitNoForceCloseApplications := GetIniBool(Section, 'NoForceCloseApplications', InitNoForceCloseApplications, FileName);
InitLogCloseApplications := GetIniBool(Section, 'LogCloseApplications', InitLogCloseApplications, FileName);
InitRestartApplications := GetIniBool(Section, 'RestartApplications', InitRestartApplications, FileName);
InitNoRestartApplications := GetIniBool(Section, 'NoRestartApplications', InitNoRestartApplications, FileName);
InitNoCancel := GetIniBool(Section, 'NoCancel', InitNoCancel, FileName);
InitPassword := GetIniString(Section, 'Password', InitPassword, FileName);
InitRestartExitCode := GetIniInt(Section, 'RestartExitCode', InitRestartExitCode, 0, 0, FileName);
WantToSuppressMsgBoxes := GetIniBool(Section, 'SuppressMsgBoxes', WantToSuppressMsgBoxes, FileName);
InitSaveInf := GetIniString(Section, 'SaveInf', InitSaveInf, FileName);
end;
procedure SaveInf(const FileName: String);
const
Section = 'Setup';
begin
SetIniString(Section, 'Lang',
PSetupLanguageEntry(Entries[seLanguage][ActiveLanguage]).Name, FileName);
SetIniString(Section, 'Dir', WizardDirValue, FileName);
SetIniString(Section, 'Group', WizardGroupValue, FileName);
SetIniBool(Section, 'NoIcons', WizardNoIcons, FileName);
if WizardSetupType <> nil then begin
SetIniString(Section, 'SetupType', WizardSetupType.Name, FileName);
SetIniString(Section, 'Components', StringsToCommaString(WizardComponents), FileName);
end
else begin
DeleteIniEntry(Section, 'SetupType', FileName);
DeleteIniEntry(Section, 'Components', FileName);
end;
SetIniString(Section, 'Tasks', StringsToCommaString(WizardTasks), FileName);
end;
function GetCustomMessageValue(const AName: String; var AValue: String): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 to Entries[seCustomMessage].Count-1 do begin
with PSetupCustomMessageEntry(Entries[seCustomMessage][I])^ do begin
if (CompareText(Name, AName) = 0) and
((LangIndex = -1) or (LangIndex = ActiveLanguage)) then begin
Result := True;
AValue := Value;
{ don't stop looping, last item counts }
end;
end;
end;
end;
function ExpandIndividualConst(Cnst: String;
const CustomConsts: array of String): String;
{ Cnst must be the name of a single constant, without the braces.
For example: app
IsPath is set to True if the result is a path which needs special trailing-
backslash handling. }
procedure HandleAutoConstants(var Cnst: String);
const
Actual: array [Boolean] of String = ('user', 'common');
begin
if Copy(Cnst, 1, 4) = 'auto' then begin
StringChange(Cnst, 'auto', Actual[IsAdminInstallMode]);
if (Cnst = 'userpf32') or (Cnst = 'userpf64') or
(Cnst = 'usercf32') or (Cnst = 'usercf64') then
Delete(Cnst, Length(Cnst)-1, 2);
end;
end;
procedure NoUninstallConstError(const C: String);
begin
InternalError(Format('Cannot evaluate "%s" constant during Uninstall', [C]));
end;
function ExpandEnvConst(C: String): String;
var
I: Integer;
VarName, Default: String;
begin
Delete(C, 1, 1);
I := ConstPos('|', C); { check for 'default' value }
if I = 0 then
I := Length(C)+1;
VarName := Copy(C, 1, I-1);
Default := Copy(C, I+1, Maxint);
Result := '';
if ConvertConstPercentStr(VarName) and ConvertConstPercentStr(Default) then begin
Result := GetEnv(ExpandConstEx(VarName, CustomConsts));
if Result = '' then
Result := ExpandConstEx(Default, CustomConsts);
end;
end;
function ExpandRegConst(C: String): String;
{ Expands a registry-value constant in the form:
reg:HKxx\SubkeyName,ValueName|DefaultValue }
type
TKeyNameConst = packed record
KeyName: String;
KeyConst: HKEY;
end;
const
KeyNameConsts: array[0..5] of TKeyNameConst = (
(KeyName: 'HKA'; KeyConst: HKEY_AUTO),
(KeyName: 'HKCR'; KeyConst: HKEY_CLASSES_ROOT),
(KeyName: 'HKCU'; KeyConst: HKEY_CURRENT_USER),
(KeyName: 'HKLM'; KeyConst: HKEY_LOCAL_MACHINE),
(KeyName: 'HKU'; KeyConst: HKEY_USERS),
(KeyName: 'HKCC'; KeyConst: HKEY_CURRENT_CONFIG));
var
Z, Subkey, Value, Default: String;
I, J, L: Integer;
RegView: TRegView;
RootKey: HKEY;
K: HKEY;
begin
Delete(C, 1, 4); { skip past 'reg:' }
I := ConstPos('\', C);
if I <> 0 then begin
Z := Copy(C, 1, I-1);
if Z <> '' then begin
RegView := InstallDefaultRegView;
L := Length(Z);
if L >= 2 then begin
{ Check for '32' or '64' suffix }
if (Z[L-1] = '3') and (Z[L] = '2') then begin
RegView := rv32Bit;
SetLength(Z, L-2);
end
else if (Z[L-1] = '6') and (Z[L] = '4') then begin
if not IsWin64 then
InternalError('Cannot access a 64-bit key in a "reg" constant on this version of Windows');
RegView := rv64Bit;
SetLength(Z, L-2);
end;
end;
RootKey := 0;
for J := Low(KeyNameConsts) to High(KeyNameConsts) do
if CompareText(KeyNameConsts[J].KeyName, Z) = 0 then begin
RootKey := KeyNameConsts[J].KeyConst;
if RootKey = HKEY_AUTO then
RootKey := InstallModeRootKey;
Break;
end;
if RootKey <> 0 then begin
Z := Copy(C, I+1, Maxint);
I := ConstPos('|', Z); { check for a 'default' data }
if I = 0 then
I := Length(Z)+1;
Default := Copy(Z, I+1, Maxint);
SetLength(Z, I-1);
I := ConstPos(',', Z); { comma separates subkey and value }
if I <> 0 then begin
Subkey := Copy(Z, 1, I-1);
Value := Copy(Z, I+1, Maxint);
if ConvertConstPercentStr(Subkey) and ConvertConstPercentStr(Value) and
ConvertConstPercentStr(Default) then begin
Result := ExpandConstEx(Default, CustomConsts);
if RegOpenKeyExView(RegView, RootKey,
PChar(ExpandConstEx(Subkey, CustomConsts)),
0, KEY_QUERY_VALUE, K) = ERROR_SUCCESS then begin
RegQueryStringValue(K, PChar(ExpandConstEx(Value, CustomConsts)),
Result);
RegCloseKey(K);
end;
Exit;
end;
end;
end;
end;
end;
{ it will only reach here if there was a parsing error }
InternalError('Failed to parse "reg" constant');
end;
function ExpandIniConst(C: String): String;
{ Expands an INI-value constant in the form:
filename,section,key|defaultvalue }
var
Z, Filename, Section, Key, Default: String;
I: Integer;
begin
Delete(C, 1, 4); { skip past 'ini:' }
I := ConstPos(',', C);
if I <> 0 then begin
Z := Copy(C, 1, I-1);
if Z <> '' then begin
Filename := Z;
Z := Copy(C, I+1, Maxint);
I := ConstPos('|', Z); { check for a 'default' data }
if I = 0 then
I := Length(Z)+1;
Default := Copy(Z, I+1, Maxint);
SetLength(Z, I-1);
I := ConstPos(',', Z); { comma separates section and key }
if I <> 0 then begin
Section := Copy(Z, 1, I-1);
Key := Copy(Z, I+1, Maxint);
if ConvertConstPercentStr(Filename) and ConvertConstPercentStr(Section) and ConvertConstPercentStr(Key) and
ConvertConstPercentStr(Default) then begin
Filename := ExpandConstEx(Filename, CustomConsts);
Section := ExpandConstEx(Section, CustomConsts);
Key := ExpandConstEx(Key, CustomConsts);
Default := ExpandConstEx(Default, CustomConsts);
Result := GetIniString(Section, Key, Default, Filename);
Exit;
end;
end;
end;
end;
{ it will only reach here if there was a parsing error }
InternalError('Failed to parse "ini" constant');
end;
function ExpandParamConst(C: String): String;
{ Expands an commandline-parameter-value constant in the form:
parametername|defaultvalue }
function GetParamString(const Param, Default: String): String;
var
I, PCount: Integer;
Z: String;
begin
PCount := NewParamCount();
for I := 1 to PCount do begin
Z := NewParamStr(I);
if StrLIComp(PChar(Z), PChar('/'+Param+'='), Length(Param)+2) = 0 then begin
Delete(Z, 1, Length(Param)+2);
Result := Z;
Exit;
end;
end;
Result := Default;
end;
var
Z, Param, Default: String;
I: Integer;
begin
Delete(C, 1, 6); { skip past 'param:' }
Z := C;
I := ConstPos('|', Z); { check for a 'default' data }
if I = 0 then
I := Length(Z)+1;
Default := Copy(Z, I+1, Maxint);
SetLength(Z, I-1);
Param := Z;
if ConvertConstPercentStr(Param) and ConvertConstPercentStr(Default) then begin
Param := ExpandConstEx(Param, CustomConsts);
Default := ExpandConstEx(Default, CustomConsts);
Result := GetParamString(Param, Default);
Exit;
end;
{ it will only reach here if there was a parsing error }
InternalError('Failed to parse "param" constant');
end;
function ExpandCodeConst(C: String): String;
{ Expands an Pascal-script-value constant in the form:
parametername|defaultvalue }
function GetCodeString(const ScriptFunc, Default: String): String;
begin
if (CodeRunner <> nil) then
Result := CodeRunner.RunStringFunction(AnsiString(ScriptFunc), [Default], True, Default)
else begin
InternalError('"code" constant with no CodeRunner');
Result := '';
end;
end;
var
Z, ScriptFunc, Default: String;
I: Integer;
begin
if DisableCodeConsts <> 0 then
raise Exception.Create('Cannot evaluate "code" constant because of possible side effects');
Delete(C, 1, 5); { skip past 'code:' }
Z := C;
I := ConstPos('|', Z); { check for a 'default' data }
if I = 0 then
I := Length(Z)+1;
Default := Copy(Z, I+1, Maxint);
SetLength(Z, I-1);
ScriptFunc := Z;
if ConvertConstPercentStr(ScriptFunc) and ConvertConstPercentStr(Default) then begin
Default := ExpandConstEx(Default, CustomConsts);
Result := GetCodeString(ScriptFunc, Default);
Exit;
end;
{ it will only reach here if there was a parsing error }
InternalError('Failed to parse "code" constant');
end;
function ExpandDriveConst(C: String): String;
begin
Delete(C, 1, 6); { skip past 'drive:' }
if ConvertConstPercentStr(C) then begin
Result := PathExtractDrive(ExpandConstEx(C, CustomConsts));
Exit;
end;
{ it will only reach here if there was a parsing error }
InternalError('Failed to parse "drive" constant');
end;
function ExpandCustomMessageConst(C: String): String;
var
I, ArgCount: Integer;
MsgName: String;
ArgValues: array[0..8] of String; { %1 through %9 }
begin
Delete(C, 1, 3); { skip past 'cm:' }
I := ConstPos(',', C);
if I = 0 then
MsgName := C
else
MsgName := Copy(C, 1, I-1);
{ Prepare arguments. Excess arguments are ignored. }
ArgCount := 0;
while (I > 0) and (ArgCount <= High(ArgValues)) do begin
Delete(C, 1, I);
I := ConstPos(',', C);
if I = 0 then
ArgValues[ArgCount] := C
else
ArgValues[ArgCount] := Copy(C, 1, I-1);
if not ConvertConstPercentStr(ArgValues[ArgCount]) then
InternalError('Failed to parse "cm" constant');
ArgValues[ArgCount] := ExpandConstEx(ArgValues[ArgCount], CustomConsts);
Inc(ArgCount);
end;
{ Look up the message value }
if not GetCustomMessageValue(MsgName, Result) then
InternalError(Format('Unknown custom message name "%s" in "cm" constant', [MsgName]));
{ Expand the message }
Result := FmtMessage(PChar(Result), Slice(ArgValues, ArgCount));
end;
const
FolderConsts: array[Boolean, TShellFolderID] of String =
(('userdesktop', 'userstartmenu', 'userprograms', 'userstartup',
'usersendto', 'commonfonts', 'userappdata', 'userdocs', 'usertemplates',
'userfavorites', 'localappdata'),
('commondesktop', 'commonstartmenu', 'commonprograms', 'commonstartup',
'usersendto', 'commonfonts', 'commonappdata', 'commondocs', 'commontemplates',
'commonfavorites' { not accepted anymore by the compiler }, 'localappdata'));
NoUninstallConsts: array[0..6] of String =
('src', 'srcexe', 'userinfoname', 'userinfoorg', 'userinfoserial', 'hwnd',
'wizardhwnd');
var
OriginalCnst, ShellFolder: String;
Common: Boolean;
ShellFolderID: TShellFolderID;
I: Integer;
begin
OriginalCnst := Cnst;
HandleRenamedConstants(Cnst, nil);
HandleAutoConstants(Cnst);
if IsUninstaller then
for I := Low(NoUninstallConsts) to High(NoUninstallConsts) do
if NoUninstallConsts[I] = Cnst then
NoUninstallConstError(NoUninstallConsts[I]);
if Cnst = '\' then Result := '\'
else if Cnst = 'app' then begin
if IsUninstaller then begin
if UninstallExpandedApp = '' then
InternalError('An attempt was made to expand the "' + OriginalCnst + '" constant but Setup didn''t create the "app" dir');
Result := UninstallExpandedApp;
end else begin
if WizardDirValue = '' then
InternalError('An attempt was made to expand the "' + OriginalCnst + '" constant before it was initialized');
Result := WizardDirValue;
end;
end
else if Cnst = 'win' then Result := WinDir
else if Cnst = 'sys' then Result := WinSystemDir
else if Cnst = 'syswow64' then begin
if WinSysWow64Dir <> '' then
Result := WinSysWow64Dir
else begin
if IsWin64 then { sanity check }
InternalError('Cannot expand "' + OriginalCnst + '" constant because there is no SysWOW64 directory');
Result := WinSystemDir;
end;
end
else if Cnst = 'sysnative' then begin
if WinSysNativeDir <> '' then
Result := WinSysNativeDir
else
Result := WinSystemDir;
end
else if Cnst = 'src' then Result := SourceDir
else if Cnst = 'srcexe' then Result := SetupLdrOriginalFilename
else if Cnst = 'tmp' then Result := TempInstallDir
else if Cnst = 'sd' then Result := SystemDrive
else if Cnst = 'userpf' then begin
if ProgramFilesUserDir <> '' then
Result := ProgramFilesUserDir
else
Result := ExpandConst('{localappdata}\Programs'); { supply default, same as Window 7 and newer }
end
else if Cnst = 'commonpf' then begin
if Is64BitInstallMode then
Result := ProgramFiles64Dir
else
Result := ProgramFiles32Dir;
end
else if Cnst = 'usercf' then begin
if CommonFilesUserDir <> '' then
Result := CommonFilesUserDir
else
Result := ExpandConst('{localappdata}\Programs\Common'); { supply default, same as Window 7 and newer }
end
else if Cnst = 'commoncf' then begin
if Is64BitInstallMode then
Result := CommonFiles64Dir
else
Result := CommonFiles32Dir;
end
else if Cnst = 'commonpf32' then Result := ProgramFiles32Dir
else if Cnst = 'commoncf32' then Result := CommonFiles32Dir
else if Cnst = 'commonpf64' then begin
if IsWin64 then
Result := ProgramFiles64Dir
else
InternalError('Cannot expand "' + OriginalCnst + '" constant on this version of Windows');
end
else if Cnst = 'commoncf64' then begin
if IsWin64 then
Result := CommonFiles64Dir
else
InternalError('Cannot expand "' + OriginalCnst + '" constant on this version of Windows');
end
else if Cnst = 'usersavedgames' then Result := SavedGamesUserDir
else if Cnst = 'userfonts' then Result := ExpandConst('{localappdata}\Microsoft\Windows\Fonts') { supported by Windows 10 Version 1803 and newer. doesn't have a KNOWNFOLDERID. }
else if Cnst = 'dao' then Result := ExpandConst('{cf}\Microsoft Shared\DAO')
else if Cnst = 'cmd' then Result := CmdFilename
else if Cnst = 'computername' then Result := GetComputerNameString
else if Cnst = 'username' then Result := GetUserNameString
else if Cnst = 'groupname' then begin
if IsUninstaller then begin
if UninstallExpandedGroupName = '' then
InternalError('Cannot expand "' + OriginalCnst + '" constant because it was not available at install time');
Result := UninstallExpandedGroupName;
end
else begin
if WizardGroupValue = '' then
InternalError('An attempt was made to expand the "' + OriginalCnst + '" constant before it was initialized');
Result := WizardGroupValue;
end;
end
else if Cnst = 'sysuserinfoname' then Result := SysUserInfoName
else if Cnst = 'sysuserinfoorg' then Result := SysUserInfoOrg
else if Cnst = 'userinfoname' then Result := WizardUserInfoName
else if Cnst = 'userinfoorg' then Result := WizardUserInfoOrg
else if Cnst = 'userinfoserial' then Result := WizardUserInfoSerial
else if Cnst = 'uninstallexe' then Result := UninstallExeFilename
else if Cnst = 'group' then begin
if IsUninstaller then begin
if UninstallExpandedGroup = '' then
InternalError('Cannot expand "' + OriginalCnst + '" constant because it was not available at install time');
Result := UninstallExpandedGroup;
end
else begin
if WizardGroupValue = '' then
InternalError('An attempt was made to expand the "' + OriginalCnst + '" constant before it was initialized');
ShellFolder := GetShellFolder(not(shAlwaysUsePersonalGroup in SetupHeader.Options) and IsAdminInstallMode,
sfPrograms, False);
if ShellFolder = '' then
InternalError('Failed to expand "' + OriginalCnst + '" constant');
Result := AddBackslash(ShellFolder) + WizardGroupValue;
end;
end
else if Cnst = 'language' then begin
if IsUninstaller then
Result := UninstallExpandedLanguage
else
Result := PSetupLanguageEntry(Entries[seLanguage][ActiveLanguage]).Name
end
else if Cnst = 'hwnd' then begin
if Assigned(MainForm) then
Result := IntToStr(MainForm.Handle)
else
Result := '0';
end
else if Cnst = 'wizardhwnd' then begin
if Assigned(WizardForm) then
Result := IntToStr(WizardForm.Handle)
else
Result := '0';
end
else if Cnst = 'log' then Result := GetLogFileName
else if Cnst = 'dotnet11' then Result := GetDotNetVersionInstallRoot(rv32Bit, netbase11)
else if Cnst = 'dotnet20' then Result := GetDotNetVersionInstallRoot(InstallDefaultRegView, netbase20)
else if Cnst = 'dotnet2032' then Result := GetDotNetVersionInstallRoot(rv32Bit, netbase20)
else if Cnst = 'dotnet2064' then begin
if IsWin64 then
Result := GetDotNetVersionInstallRoot(rv64Bit, netbase20)
else
InternalError('Cannot expand "' + OriginalCnst + '" constant on this version of Windows');
end
else if Cnst = 'dotnet40' then Result := GetDotNetVersionInstallRoot(InstallDefaultRegView, netbase40)
else if Cnst = 'dotnet4032' then Result := GetDotNetVersionInstallRoot(rv32Bit, netbase40)
else if Cnst = 'dotnet4064' then begin
if IsWin64 then
Result := GetDotNetVersionInstallRoot(rv64Bit, netbase40)
else
InternalError('Cannot expand "' + OriginalCnst + '" constant on this version of Windows');
end
else if (Cnst <> '') and (Cnst[1] = '%') then Result := ExpandEnvConst(Cnst)
else if StrLComp(PChar(Cnst), 'reg:', 4) = 0 then Result := ExpandRegConst(Cnst)
else if StrLComp(PChar(Cnst), 'ini:', 4) = 0 then Result := ExpandIniConst(Cnst)
else if StrLComp(PChar(Cnst), 'param:', 6) = 0 then Result := ExpandParamConst(Cnst)
else if StrLComp(PChar(Cnst), 'code:', 5) = 0 then Result := ExpandCodeConst(Cnst)
else if StrLComp(PChar(Cnst), 'drive:', 6) = 0 then Result := ExpandDriveConst(Cnst)
else if StrLComp(PChar(Cnst), 'cm:', 3) = 0 then Result := ExpandCustomMessageConst(Cnst)
else begin
{ Shell folder constants }
for Common := False to True do
for ShellFolderID := Low(ShellFolderID) to High(ShellFolderID) do
if Cnst = FolderConsts[Common, ShellFolderID] then begin
ShellFolder := GetShellFolder(Common, ShellFolderID, False);
if ShellFolder = '' then
InternalError(Format('Failed to expand shell folder constant "%s"', [OriginalCnst]));
Result := ShellFolder;
Exit;
end;
{ Custom constants }
if Cnst <> '' then begin
I := 0;
while I < High(CustomConsts) do begin
if Cnst = CustomConsts[I] then begin
Result := CustomConsts[I+1];
Exit;
end;
Inc(I, 2);
end;
end;
{ Unknown constant }
InternalError(Format('Unknown constant "%s"', [OriginalCnst]));
end;
end;
function ExpandConst(const S: String): String;
begin
Result := ExpandConstEx2(S, [''], True);
end;
function ExpandConstEx(const S: String; const CustomConsts: array of String): String;
begin
Result := ExpandConstEx2(S, CustomConsts, True);
end;
function ExpandConstEx2(const S: String; const CustomConsts: array of String;
const DoExpandIndividualConst: Boolean): String;
var
I, Start: Integer;
Cnst, ReplaceWith: String;
begin
Result := S;
I := 1;
while I <= Length(Result) do begin
if Result[I] = '{' then begin
if (I < Length(Result)) and (Result[I+1] = '{') then begin
{ Change '{{' to '{' if not in an embedded constant }
Inc(I);
Delete(Result, I, 1);
end
else begin
Start := I;
{ Find the closing brace, skipping over any embedded constants }
I := SkipPastConst(Result, I);
if I = 0 then { unclosed constant? }
InternalError('Unclosed constant');
Dec(I); { 'I' now points to the closing brace }
if DoExpandIndividualConst then begin
{ Now translate the constant }
Cnst := Copy(Result, Start+1, I-(Start+1));
ReplaceWith := ExpandIndividualConst(Cnst, CustomConsts);
Delete(Result, Start, (I+1)-Start);
Insert(ReplaceWith, Result, Start);
I := Start + Length(ReplaceWith);
if (ReplaceWith <> '') and (PathLastChar(ReplaceWith)^ = '\') and
(I <= Length(Result)) and (Result[I] = '\') then
Delete(Result, I, 1);
end else
Inc(I); { Skip closing brace }
end;
end
else begin
{$IFNDEF UNICODE}
if Result[I] in ConstLeadBytes^ then
Inc(I);
{$ENDIF}
Inc(I);
end;
end;
end;
function ExpandConstIfPrefixed(const S: String): String;
const
ExpandPrefix = 'expand:';
begin
if Pos(ExpandPrefix, S) = 1 then begin
Inc(DisableCodeConsts);
try
Result := ExpandConst(Copy(S, Length(ExpandPrefix)+1, Maxint));
finally
Dec(DisableCodeConsts);
end;
end
else
Result := S;
end;
procedure InitMainNonSHFolderConsts;
function GetPath(const RegView: TRegView; const Name: PChar): String;
var
H: HKEY;
begin
if RegOpenKeyExView(RegView, HKEY_LOCAL_MACHINE, NEWREGSTR_PATH_SETUP, 0,
KEY_QUERY_VALUE, H) = ERROR_SUCCESS then begin
if not RegQueryStringValue(H, Name, Result) then
Result := '';
RegCloseKey(H);
end
else
Result := '';
end;
procedure ReadSysUserInfo;
const
Paths: array[Boolean] of PChar = (NEWREGSTR_PATH_SETUP,
'SOFTWARE\Microsoft\Windows NT\CurrentVersion');
var
RegView: TRegView;
K: HKEY;
begin
{ Windows Vista and Server 2008 x64 are bugged: the owner and organization
are set to "Microsoft" on the 32-bit key. So on 64-bit Windows, read
from the 64-bit key. (The bug doesn't exist on 64-bit XP or Server 2003,
but it's safe to read the 64-bit key on those versions too.) }
if IsWin64 then
RegView := rv64Bit
else
RegView := rvDefault;
if RegOpenKeyExView(RegView, HKEY_LOCAL_MACHINE, Paths[IsNT], 0, KEY_QUERY_VALUE,
K) = ERROR_SUCCESS then begin
RegQueryStringValue(K, 'RegisteredOwner', SysUserInfoName);
RegQueryStringValue(K, 'RegisteredOrganization', SysUserInfoOrg);
RegCloseKey(K);
end;
end;
const
FOLDERID_UserProgramFiles: TGUID = (D1:$5CD7AEE2; D2:$2219; D3:$4A67; D4:($B8,$5D,$6C,$9C,$E1,$56,$60,$CB));
FOLDERID_UserProgramFilesCommon: TGUID = (D1:$BCBD3057; D2:$CA5C; D3:$4622; D4:($B4,$2D,$BC,$56,$DB,$0A,$E5,$16));
FOLDERID_SavedGames: TGUID = (D1:$4C5C32FF; D2:$BB9D; D3:$43B0; D4:($B5,$B4,$2D,$72,$E5,$4E,$AA,$A4));
KF_FLAG_CREATE = $00008000;
var
Path: PWideChar;
begin
{ Read Windows and Windows System dirs }
WinDir := GetWinDir;
WinSystemDir := GetSystemDir;
WinSysWow64Dir := GetSysWow64Dir;
WinSysNativeDir := GetSysNativeDir(IsWin64);
{ Get system drive }
if Win32Platform = VER_PLATFORM_WIN32_NT then
SystemDrive := GetEnv('SystemDrive') {don't localize}
else
SystemDrive := '';
if SystemDrive = '' then begin
SystemDrive := PathExtractDrive(WinDir);
if SystemDrive = '' then
{ In some rare case that PathExtractDrive failed, just default to C }
SystemDrive := 'C:';
end;
{ Get 32-bit Program Files and Common Files dirs }
ProgramFiles32Dir := GetPath(rv32Bit, 'ProgramFilesDir');
if ProgramFiles32Dir = '' then
ProgramFiles32Dir := SystemDrive + '\Program Files'; {don't localize}
CommonFiles32Dir := GetPath(rv32Bit, 'CommonFilesDir');
if CommonFiles32Dir = '' then
CommonFiles32Dir := AddBackslash(ProgramFiles32Dir) + 'Common Files'; {don't localize}
{ Get 64-bit Program Files and Common Files dirs }
if IsWin64 then begin
ProgramFiles64Dir := GetPath(rv64Bit, 'ProgramFilesDir');
if ProgramFiles64Dir = '' then
InternalError('Failed to get path of 64-bit Program Files directory');
CommonFiles64Dir := GetPath(rv64Bit, 'CommonFilesDir');
if CommonFiles64Dir = '' then
InternalError('Failed to get path of 64-bit Common Files directory');
end;
{ Get dirs which have no CSIDL equivalent and cannot be retrieved using SHGetFolderPath. }
if Assigned(SHGetKnownFolderPathFunc) and (WindowsVersion shr 16 >= $0600) then begin
if SHGetKnownFolderPathFunc(FOLDERID_UserProgramFiles {Windows 7+}, KF_FLAG_CREATE, 0, Path) = S_OK then begin
try
ProgramFilesUserDir := WideCharToString(Path);
finally
CoTaskMemFree(Path);
end;
end;
if SHGetKnownFolderPathFunc(FOLDERID_UserProgramFilesCommon {Windows 7+}, KF_FLAG_CREATE, 0, Path) = S_OK then begin
try
CommonFilesUserDir := WideCharToString(Path);
finally
CoTaskMemFree(Path);
end;
end;
if SHGetKnownFolderPathFunc(FOLDERID_SavedGames {Vista+}, KF_FLAG_CREATE, 0, Path) = S_OK then begin
try
SavedGamesUserDir := WideCharToString(Path);
finally
CoTaskMemFree(Path);
end;
end;
end;
{ Get path of command interpreter }
if IsNT then
CmdFilename := AddBackslash(WinSystemDir) + 'cmd.exe'
else
CmdFilename := AddBackslash(WinDir) + 'COMMAND.COM';
{ Get user info from system }
ReadSysUserInfo;
end;
procedure SaveStreamToTempFile(const Strm: TCustomMemoryStream;
const Filename: String);
var
ErrorCode: DWORD;
begin
try
Strm.SaveToFile(Filename);
except
{ Display more useful error message than 'Stream write error' etc. }
on EStreamError do begin
ErrorCode := GetLastError;
raise Exception.Create(FmtSetupMessage(msgLastErrorMessage,
[SetupMessages[msgLdrCannotCreateTemp], IntToStr(ErrorCode),
Win32ErrorString(ErrorCode)]));
end;
end;
end;
procedure SaveResourceToTempFile(const ResName, Filename: String);
var
ResStrm: TResourceStream;
begin
ResStrm := TResourceStream.Create(HInstance, ResName, RT_RCDATA);
try
SaveStreamToTempFile(ResStrm, Filename);
finally
ResStrm.Free;
end;
end;
procedure CreateTempInstallDir;
{ Initializes TempInstallDir and extracts the 64-bit helper into it if needed.
This is called by Setup, Uninstall, and RegSvr. }
var
Subdir, ResName, Filename: String;
ErrorCode: DWORD;
begin
TempInstallDir := CreateTempDir;
Log('Created temporary directory: ' + TempInstallDir);
if Debugging then
DebugNotifyTempDir(TempInstallDir);
{ Create _isetup subdirectory to hold our internally-used files to ensure
they won't use any DLLs the install creator might've dumped into
TempInstallDir }
Subdir := AddBackslash(TempInstallDir) + '_isetup';
if not CreateDirectory(PChar(Subdir), nil) then begin
ErrorCode := GetLastError;
raise Exception.Create(FmtSetupMessage(msgLastErrorMessage,
[FmtSetupMessage1(msgErrorCreatingDir, Subdir), IntToStr(ErrorCode),
Win32ErrorString(ErrorCode)]));
end;
{ Extract 64-bit helper EXE, if one is available for the current processor
architecture }
ResName := GetHelperResourceName;
if ResName <> '' then begin
Filename := Subdir + '\_setup64.tmp';
SaveResourceToTempFile(ResName, Filename);
SetHelperExeFilename(Filename);
end;
end;
function TempDeleteFileProc(const DisableFsRedir: Boolean;
const FileName: String; const Param: Pointer): Boolean;
var
Elapsed: DWORD;
label Retry;
begin
Retry:
Result := DeleteFileRedir(DisableFsRedir, FileName);
if not Result and
(GetLastError <> ERROR_FILE_NOT_FOUND) and
(GetLastError <> ERROR_PATH_NOT_FOUND) then begin
{ If we get here, the file is probably still in use. On an SMP machine,
it's possible for an EXE to remain locked by Windows for a short time
after it terminates, causing DeleteFile to fail with ERROR_ACCESS_DENIED.
(I'm not sure this issue can really be seen here in practice; I could
only reproduce it consistently by calling DeleteFile() *immediately*
after waiting on the process handle.)
Retry if fewer than 2 seconds have passed since DelTree started,
otherwise assume the error must be permanent and give up. 2 seconds
ought to be more than enough for the SMP case. }
Elapsed := GetTickCount - DWORD(Param);
if Cardinal(Elapsed) < Cardinal(2000) then begin
Sleep(50);
goto Retry;
end;
end;
end;
procedure RemoveTempInstallDir;
{ Removes TempInstallDir and all its contents. Stops the 64-bit helper first
if necessary. }
begin
{ Stop 64-bit helper if it's running }
StopHelper(False);
SetHelperExeFilename('');
if TempInstallDir <> '' then begin
if Debugging then
DebugNotifyTempDir('');
if not DelTree(False, TempInstallDir, True, True, True, False, nil,
TempDeleteFileProc, Pointer(GetTickCount())) then
Log('Failed to remove temporary directory: ' + TempInstallDir);
end;
end;
procedure LoadSHFolderDLL;
var
Filename: String;
const
shfolder = 'shfolder.dll';
begin
Filename := AddBackslash(GetSystemDir) + shfolder;
{ Ensure shell32.dll is pre-loaded so it isn't loaded/freed for each
individual SHGetFolderPath call }
SafeLoadLibrary(AddBackslash(GetSystemDir) + shell32, SEM_NOOPENFILEERRORBOX);
SHFolderDLLHandle := SafeLoadLibrary(Filename, SEM_NOOPENFILEERRORBOX);
if SHFolderDLLHandle = 0 then
InternalError(Format('Failed to load DLL "%s"', [Filename]));
@SHGetFolderPathFunc := GetProcAddress(SHFolderDLLHandle, {$IFDEF UNICODE}'SHGetFolderPathW'{$ELSE}'SHGetFolderPathA'{$ENDIF});
if @SHGetFolderPathFunc = nil then
InternalError('Failed to get address of SHGetFolderPath function');
end;
procedure UnloadSHFolderDLL;
begin
@SHGetFolderPathFunc := nil;
if SHFolderDLLHandle <> 0 then begin
FreeLibrary(SHFolderDLLHandle);
SHFolderDLLHandle := 0;
end;
end;
function GetShellFolderByCSIDL(Folder: Integer; const Create: Boolean): String;
const
CSIDL_FLAG_CREATE = $8000;
SHGFP_TYPE_CURRENT = 0;
var
Res: HRESULT;
Buf: array[0..MAX_PATH-1] of Char;
begin
if Create then
Folder := Folder or CSIDL_FLAG_CREATE;
{ Work around a nasty bug in Windows Vista (still present in SP1) and
Windows Server 2008: When a folder ID resolves to the root directory of a
drive ('X:\') and the CSIDL_FLAG_CREATE flag is passed, SHGetFolderPath
fails with code 0x80070005.
So on Vista only, first try calling the function without CSIDL_FLAG_CREATE.
If and only if that fails, call it again with the flag.
Note: The calls *must* be issued in this order; if it's called with the
flag first, it seems to permanently cache the failure code, causing future
calls that don't include the flag to fail as well. }
if (WindowsVersion shr 16 >= $0600) and
(Folder and CSIDL_FLAG_CREATE <> 0) then
Res := SHGetFolderPathFunc(0, Folder and not CSIDL_FLAG_CREATE, 0,
SHGFP_TYPE_CURRENT, Buf)
else
Res := E_FAIL; { always issue the call below }
if Res <> S_OK then
Res := SHGetFolderPathFunc(0, Folder, 0, SHGFP_TYPE_CURRENT, Buf);
if Res = S_OK then
Result := RemoveBackslashUnlessRoot(PathExpand(Buf))
else begin
Result := '';
LogFmt('Warning: SHGetFolderPath failed with code 0x%.8x on folder 0x%.4x',
[Res, Folder]);
end;
end;
function GetShellFolder(const Common: Boolean; const ID: TShellFolderID;
ReadOnly: Boolean): String;
const
CSIDL_COMMON_STARTMENU = $0016;
CSIDL_COMMON_PROGRAMS = $0017;
CSIDL_COMMON_STARTUP = $0018;
CSIDL_COMMON_DESKTOPDIRECTORY = $0019;
CSIDL_APPDATA = $001A;
CSIDL_LOCAL_APPDATA = $001C;
CSIDL_COMMON_FAVORITES = $001F;
CSIDL_COMMON_APPDATA = $0023;
CSIDL_COMMON_TEMPLATES = $002D;
CSIDL_COMMON_DOCUMENTS = $002E;
FolderIDs: array[Boolean, TShellFolderID] of Integer = (
{ User }
(CSIDL_DESKTOPDIRECTORY, CSIDL_STARTMENU, CSIDL_PROGRAMS, CSIDL_STARTUP,
CSIDL_SENDTO, CSIDL_FONTS, CSIDL_APPDATA, CSIDL_PERSONAL,
CSIDL_TEMPLATES, CSIDL_FAVORITES, CSIDL_LOCAL_APPDATA),
{ Common }
(CSIDL_COMMON_DESKTOPDIRECTORY, CSIDL_COMMON_STARTMENU, CSIDL_COMMON_PROGRAMS, CSIDL_COMMON_STARTUP,
CSIDL_SENDTO, CSIDL_FONTS, CSIDL_COMMON_APPDATA, CSIDL_COMMON_DOCUMENTS,
CSIDL_COMMON_TEMPLATES, CSIDL_COMMON_FAVORITES, CSIDL_LOCAL_APPDATA));
var
ShellFolder: String;
begin
if not ShellFoldersRead[Common, ID] then begin
{ Note: Must pass Create=True or else SHGetFolderPath fails if the
specified CSIDL is valid but doesn't currently exist. }
ShellFolder := GetShellFolderByCSIDL(FolderIDs[Common, ID], not ReadOnly);
ShellFolders[Common, ID] := ShellFolder;
if not ReadOnly or (ShellFolder <> '') then
ShellFoldersRead[Common, ID] := True;
end;
Result := ShellFolders[Common, ID];
end;
function InstallOnThisVersion(const MinVersion: TSetupVersionData;
const OnlyBelowVersion: TSetupVersionData): TInstallOnThisVersionResult;
var
Ver, Ver2, MinVer, OnlyBelowVer: Cardinal;
begin
Ver := WindowsVersion;
if IsNT then begin
MinVer := MinVersion.NTVersion;
OnlyBelowVer := OnlyBelowVersion.NTVersion;
end
else begin
MinVer := 0;
OnlyBelowVer := 0;
end;
Result := irInstall;
if MinVer = 0 then
Result := irNotOnThisPlatform
else begin
if Ver < MinVer then
Result := irVersionTooLow
else if (IsNT and (LongRec(Ver).Hi = LongRec(MinVer).Hi) and
(NTServicePackLevel < MinVersion.NTServicePack)) then
Result := irServicePackTooLow
else begin
if OnlyBelowVer <> 0 then begin
Ver2 := Ver;
{ A build number of 0 on OnlyBelowVersion means 'match any build' }
if LongRec(OnlyBelowVer).Lo = 0 then
Ver2 := Ver2 and $FFFF0000; { set build number to zero on Ver2 also }
if not IsNT then begin
if Ver2 >= OnlyBelowVer then
Result := irVerTooHigh;
end
else begin
{ Note: When OnlyBelowVersion includes a service pack level, the
version number test changes from a "<" to "<=" operation. Thus,
on Windows 2000 SP4, 5.0 and 5.0.2195 will fail, but 5.0sp5 and
5.0.2195sp5 will pass. }
if (Ver2 > OnlyBelowVer) or
((Ver2 = OnlyBelowVer) and
(OnlyBelowVersion.NTServicePack = 0)) or
((LongRec(Ver).Hi = LongRec(OnlyBelowVer).Hi) and
(OnlyBelowVersion.NTServicePack <> 0) and
(NTServicePackLevel >= OnlyBelowVersion.NTServicePack)) then
Result := irVerTooHigh;
end;
end;
end;
end;
end;
function GetSizeOfComponent(const ComponentName: String; const ExtraDiskSpaceRequired: Integer64): Integer64;
var
ComponentNameAsList: TStringList;
FileEntry: PSetupFileEntry;
I: Integer;
begin
Result := ExtraDiskSpaceRequired;
ComponentNameAsList := TStringList.Create();
try
ComponentNameAsList.Add(ComponentName);
for I := 0 to Entries[seFile].Count-1 do begin
FileEntry := PSetupFileEntry(Entries[seFile][I]);
with FileEntry^ do begin
if (Components <> '') and
((Tasks = '') and (Check = '')) then begin {don't count tasks or scripted entries}
if ShouldProcessFileEntry(ComponentNameAsList, nil, FileEntry, True) then begin
if LocationEntry <> -1 then
Inc6464(Result, PSetupFileLocationEntry(Entries[seFileLocation][LocationEntry])^.OriginalSize)
else
Inc6464(Result, ExternalSize);
end;
end;
end;
end;
finally
ComponentNameAsList.Free();
end;
end;
function GetSizeOfType(const TypeName: String; const IsCustom: Boolean): Integer64;
var
ComponentTypes: TStringList;
I: Integer;
begin
Result.Hi := 0;
Result.Lo := 0;
ComponentTypes := TStringList.Create();
for I := 0 to Entries[seComponent].Count-1 do begin
with PSetupComponentEntry(Entries[seComponent][I])^ do begin
SetStringsFromCommaString(ComponentTypes, Types);
{ For custom types, only count fixed components. Otherwise count all. }
if IsCustom then begin
if (coFixed in Options) and ListContains(ComponentTypes, TypeName) then
Inc6464(Result, Size);
end else begin
if ListContains(ComponentTypes, TypeName) then
Inc6464(Result, Size);
end;
end;
end;
ComponentTypes.Free();
end;
function IsRecurseableDirectory(const FindData: TWin32FindData): Boolean;
{ Returns True if FindData is a directory that may be recursed into.
Intended only for use when processing external+recursesubdirs file entries. }
begin
Result :=
(FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY <> 0) and
(FindData.dwFileAttributes and FILE_ATTRIBUTE_HIDDEN = 0) and
(StrComp(FindData.cFileName, '.') <> 0) and
(StrComp(FindData.cFileName, '..') <> 0);
end;
type
TEnumFilesProc = function(const DisableFsRedir: Boolean; const Filename: String;
const Param: Pointer): Boolean;
function DummyDeleteDirProc(const DisableFsRedir: Boolean; const Filename: String;
const Param: Pointer): Boolean;
begin
{ We don't actually want to delete the dir, so just return success. }
Result := True;
end;
{ Enumerates the files we're going to install and delete. Returns True on success.
Likewise EnumFilesProc should return True on success and return False
to break the enum and to cause EnumFiles to return False instead of True. }
function EnumFiles(const EnumFilesProc: TEnumFilesProc;
const WizardComponents, WizardTasks: TStringList; const Param: Pointer): Boolean;
function RecurseExternalFiles(const DisableFsRedir: Boolean;
const SearchBaseDir, SearchSubDir, SearchWildcard: String;
const SourceIsWildcard: Boolean; const CurFile: PSetupFileEntry): Boolean;
var
SearchFullPath, DestName: String;
H: THandle;
FindData: TWin32FindData;
begin
SearchFullPath := SearchBaseDir + SearchSubDir + SearchWildcard;
Result := True;
H := FindFirstFileRedir(DisableFsRedir, SearchFullPath, FindData);
if H <> INVALID_HANDLE_VALUE then begin
try
repeat
if FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY = 0 then begin
if SourceIsWildcard then
if FindData.dwFileAttributes and FILE_ATTRIBUTE_HIDDEN <> 0 then
Continue;
DestName := ExpandConst(CurFile^.DestName);
if not(foCustomDestName in CurFile^.Options) then
DestName := DestName + SearchSubDir + FindData.cFileName
else if SearchSubDir <> '' then
DestName := PathExtractPath(DestName) + SearchSubDir + PathExtractName(DestName);
if not EnumFilesProc(DisableFsRedir, DestName, Param) then begin
Result := False;
Exit;
end;
end;
until not FindNextFile(H, FindData);
finally
Windows.FindClose(H);
end;
end;
if foRecurseSubDirsExternal in CurFile^.Options then begin
H := FindFirstFileRedir(DisableFsRedir, SearchBaseDir + SearchSubDir + '*', FindData);
if H <> INVALID_HANDLE_VALUE then begin
try
repeat
if IsRecurseableDirectory(FindData) then
if not RecurseExternalFiles(DisableFsRedir, SearchBaseDir,
SearchSubDir + FindData.cFileName + '\', SearchWildcard,
SourceIsWildcard, CurFile) then begin
Result := False;
Exit;
end;
until not FindNextFile(H, FindData);
finally
Windows.FindClose(H);
end;
end;
end;
end;
var
I: Integer;
CurFile: PSetupFileEntry;
DisableFsRedir: Boolean;
SourceWildcard: String;
begin
Result := True;
{ [Files] }
for I := 0 to Entries[seFile].Count-1 do begin
CurFile := PSetupFileEntry(Entries[seFile][I]);
if (CurFile^.FileType = ftUserFile) and
ShouldProcessFileEntry(WizardComponents, WizardTasks, CurFile, False) then begin
DisableFsRedir := ShouldDisableFsRedirForFileEntry(CurFile);
if CurFile^.LocationEntry <> -1 then begin
{ Non-external file }
if not EnumFilesProc(DisableFsRedir, ExpandConst(CurFile^.DestName), Param) then begin
Result := False;
Exit;
end;
end
else begin
{ External file }
SourceWildcard := ExpandConst(CurFile^.SourceFilename);
if not RecurseExternalFiles(DisableFsRedir, PathExtractPath(SourceWildcard), '',
PathExtractName(SourceWildcard), IsWildcard(SourceWildcard), CurFile) then begin
Result := False;
Exit;
end;
end;
end;
end;
{ [InstallDelete] }
for I := 0 to Entries[seInstallDelete].Count-1 do
with PSetupDeleteEntry(Entries[seInstallDelete][I])^ do
if ShouldProcessEntry(WizardComponents, WizardTasks, Components, Tasks, Languages, Check) then begin
case DeleteType of
dfFiles, dfFilesAndOrSubdirs:
if not DelTree(InstallDefaultDisableFsRedir, ExpandConst(Name), False, True, DeleteType = dfFilesAndOrSubdirs, True,
DummyDeleteDirProc, EnumFilesProc, Param) then begin
Result := False;
Exit;
end;
dfDirIfEmpty:
if not DelTree(InstallDefaultDisableFsRedir, ExpandConst(Name), True, False, False, True,
DummyDeleteDirProc, EnumFilesProc, Param) then begin
Result := False;
Exit;
end;
end;
end;
end;
procedure EnumProc(const Filename: String; Param: Pointer);
begin
TStringList(Param).Add(PathLowercase(Filename));
end;
var
CheckForFileSL: TStringList;
function CheckForFile(const DisableFsRedir: Boolean; const AFilename: String;
const Param: Pointer): Boolean;
var
Filename: String;
J: Integer;
begin
Filename := AFilename;
if IsNT then begin
if not DisableFsRedir then
Filename := ReplaceSystemDirWithSysWow64(Filename);
end
else
Filename := GetShortName(Filename);
Filename := PathLowercase(Filename);
for J := 0 to CheckForFileSL.Count-1 do begin
if CheckForFileSL[J] = Filename then begin
LogFmt('Found pending rename or delete that matches one of our files: %s', [Filename]);
Result := False; { Break the enum, just need to know if any matches }
Exit;
end;
end;
Result := True; { Success! }
end;
{ Checks if no file we're going to install or delete has a pending rename or delete. }
function PreviousInstallCompleted(const WizardComponents, WizardTasks: TStringList): Boolean;
begin
Result := True;
if Entries[seFile].Count = 0 then
Exit;
CheckForFileSL := TStringList.Create;
try
EnumFileReplaceOperationsFilenames(EnumProc, CheckForFileSL);
if CheckForFileSL.Count = 0 then
Exit;
Result := EnumFiles(CheckForFile, WizardComponents, WizardTasks, nil);
finally
CheckForFileSL.Free;
end;
end;
type
TArrayOfPWideChar = array[0..(MaxInt div SizeOf(PWideChar))-1] of PWideChar;
PArrayOfPWideChar = ^TArrayOfPWideChar;
var
RegisterFileBatchFilenames: PArrayOfPWideChar;
RegisterFileFilenamesBatchMax, RegisterFileFilenamesBatchCount: Integer;
function RegisterFile(const DisableFsRedir: Boolean; const AFilename: String;
const Param: Pointer): Boolean;
var
Filename, Text: String;
I, Len: Integer;
CheckFilter, Match: Boolean;
begin
Filename := AFilename;
{ First: check filter and self. }
if Filename <> '' then begin
CheckFilter := Boolean(Param);
if CheckFilter then begin
Match := False;
Text := PathLowercase(PathExtractName(Filename));
for I := 0 to CloseApplicationsFilterList.Count-1 do begin
if WildcardMatch(PChar(Text), PChar(CloseApplicationsFilterList[I])) then begin
Match := True;
Break;
end;
end;
if not Match then begin
{ No match with filter so exit but don't return an error. }
Result := True;
Exit;
end;
end;
if PathCompare(Filename, SetupLdrOriginalFilename) = 0 then begin
{ Don't allow self to be registered but don't return an error. }
Result := True;
Exit;
end;
end;
{ Secondly: check if we need to register this batch, either because the batch is full
or because we're done scanning and have leftovers. }
if ((Filename <> '') and (RegisterFileFilenamesBatchCount = RegisterFileFilenamesBatchMax)) or
((Filename = '') and (RegisterFileFilenamesBatchCount > 0)) then begin
if RmRegisterResources(RmSessionHandle, RegisterFileFilenamesBatchCount, RegisterFileBatchFilenames, 0, nil, 0, nil) = ERROR_SUCCESS then begin
for I := 0 to RegisterFileFilenamesBatchCount-1 do
FreeMem(RegisterFileBatchFilenames[I]);
RegisterFileFilenamesBatchCount := 0;
end else begin
RmEndSession(RmSessionHandle);
RmSessionStarted := False;
end;
end;
{ Finally: add this file to the batch. }
if RmSessionStarted and (FileName <> '') then begin
{ From MSDN: "Installers should not disable file system redirection before calling
the Restart Manager API. This means that a 32-bit installer run on 64-bit Windows
is unable register a file in the %windir%\system32 directory." This is incorrect,
we can register such files by using the Sysnative alias. Note: the Sysnative alias
is only available on Windows Vista and newer, but so is Restart Manager. }
if DisableFsRedir then
Filename := ReplaceSystemDirWithSysNative(Filename, IsWin64);
if InitLogCloseApplications then
LogFmt('Found a file to register with RestartManager: %s', [Filename]);
Len := Length(Filename);
GetMem(RegisterFileBatchFilenames[RegisterFileFilenamesBatchCount], (Len + 1) * SizeOf(RegisterFileBatchFilenames[RegisterFileFilenamesBatchCount][0]));
{$IFNDEF UNICODE}
RegisterFileFilenames[RegisterFileFilenamesCount][MultiByteToWideChar(CP_ACP, 0, PChar(Filename), Len, RegisterFileFilenames[RegisterFileFilenamesCount], Len)] := #0;
{$ELSE}
StrPCopy(RegisterFileBatchFilenames[RegisterFileFilenamesBatchCount], Filename);
{$ENDIF}
Inc(RegisterFileFilenamesBatchCount);
Inc(RmRegisteredFilesCount);
end;
Result := RmSessionStarted; { Break the enum if there was an error, else continue. }
end;
{ Helper function for [Code] to register extra files. }
var
AllowCodeRegisterExtraCloseApplicationsResource: Boolean;
function CodeRegisterExtraCloseApplicationsResource(const DisableFsRedir: Boolean; const AFilename: String): Boolean;
begin
if AllowCodeRegisterExtraCloseApplicationsResource then
Result := RegisterFile(DisableFsRedir, AFilename, Pointer(False))
else begin
InternalError('Cannot call "RegisterExtraCloseApplicationsResource" function at this time');
Result := False;
end;
end;
{ Register all files we're going to install or delete. Ends RmSession on errors. }
procedure RegisterResourcesWithRestartManager(const WizardComponents, WizardTasks: TStringList);
var
I: Integer;
begin
{ Note: MSDN says we shouldn't call RmRegisterResources for each file because of speed, but calling
it once for all files adds extra memory usage, so calling it in batches. }
RegisterFileFilenamesBatchMax := 1000;
GetMem(RegisterFileBatchFilenames, RegisterFileFilenamesBatchMax * SizeOf(RegisterFileBatchFilenames[0]));
try
{ Register our files. }
RmRegisteredFilesCount := 0;
EnumFiles(RegisterFile, WizardComponents, WizardTasks, Pointer(True));
{ Ask [Code] for more files. }
if CodeRunner <> nil then begin
AllowCodeRegisterExtraCloseApplicationsResource := True;
try
try
CodeRunner.RunProcedures('RegisterExtraCloseApplicationsResources', [''], False);
except
Log('RegisterExtraCloseApplicationsResources raised an exception.');
Application.HandleException(nil);
end;
finally
AllowCodeRegisterExtraCloseApplicationsResource := False;
end;
end;
{ Don't forget to register leftovers. }
if RmSessionStarted then
RegisterFile(False, '', nil);
finally
for I := 0 to RegisterFileFilenamesBatchCount-1 do
FreeMem(RegisterFileBatchFilenames[I]);
FreeMem(RegisterFileBatchFilenames);
end;
end;
procedure DebugNotifyEntry(EntryType: TEntryType; Number: Integer);
var
Kind: TDebugEntryKind;
B: Boolean;
begin
if not Debugging then Exit;
case EntryType of
seDir: Kind := deDir;
seFile: Kind := deFile;
seIcon: Kind := deIcon;
seIni: Kind := deIni;
seRegistry: Kind := deRegistry;
seInstallDelete: Kind := deInstallDelete;
seUninstallDelete: Kind := deUninstallDelete;
seRun: Kind := deRun;
seUninstallRun: Kind := deUninstallRun;
else
Exit;
end;
DebugNotify(Kind, Integer(OriginalEntryIndexes[EntryType][Number]), B);
end;
procedure CodeRunnerOnLog(const S: String);
begin
Log(S);
end;
procedure CodeRunnerOnLogFmt(const S: String; const Args: array of const);
begin
LogFmt(S, Args);
end;
procedure CodeRunnerOnDllImport(var DllName: String; var ForceDelayLoad: Boolean);
var
S, BaseName, FullName: String;
FirstFile: Boolean;
P: Integer;
begin
while True do begin
if Pos('setup:', DllName) = 1 then begin
if IsUninstaller then begin
DllName := '';
ForceDelayLoad := True;
Exit;
end;
Delete(DllName, 1, Length('setup:'));
end
else if Pos('uninstall:', DllName) = 1 then begin
if not IsUninstaller then begin
DllName := '';
ForceDelayLoad := True;
Exit;
end;
Delete(DllName, 1, Length('uninstall:'));
end
else
Break;
end;
if Pos('files:', DllName) = 1 then begin
if IsUninstaller then begin
{ Uninstall doesn't do 'files:' }
DllName := '';
ForceDelayLoad := True;
end
else begin
S := Copy(DllName, Length('files:')+1, Maxint);
FirstFile := True;
repeat
P := ConstPos(',', S);
if P = 0 then
BaseName := S
else begin
BaseName := Copy(S, 1, P-1);
Delete(S, 1, P);
end;
BaseName := ExpandConst((BaseName));
FullName := AddBackslash(TempInstallDir) + BaseName;
if not NewFileExists(FullName) then
ExtractTemporaryFile(BaseName);
if FirstFile then begin
DllName := FullName;
FirstFile := False;
end;
until P = 0;
end;
end
else
DllName := ExpandConst(DllName);
end;
function CodeRunnerOnDebug(const Position: LongInt;
var ContinueStepOver: Boolean): Boolean;
begin
Result := DebugNotify(deCodeLine, Position, ContinueStepOver, CodeRunner.GetCallStack);
end;
function CodeRunnerOnDebugIntermediate(const Position: LongInt;
var ContinueStepOver: Boolean): Boolean;
begin
Result := DebugNotifyIntermediate(deCodeLine, Position, ContinueStepOver);
end;
procedure CodeRunnerOnException(const Exception: AnsiString; const Position: LongInt);
begin
if Debugging then
DebugNotifyException(String(Exception), deCodeLine, Position);
end;
procedure SetActiveLanguage(const I: Integer);
{ Activates the specified language }
const
{$IFDEF UNICODE}
{ UNICODE requires 2000+, so we can just use the English name }
SMSPGothic = 'MS PGothic';
{$ELSE}
{ "MS PGothic" in Japanese (CP 932) }
SMSPGothic = #$82'l'#$82'r '#$82'o'#$83'S'#$83'V'#$83'b'#$83'N';
{$ENDIF}
var
LangEntry: PSetupLanguageEntry;
J: Integer;
begin
if ActiveLanguage = I then
Exit;
LangEntry := Entries[seLanguage][I];
AssignSetupMessages(LangEntry.Data[1], Length(LangEntry.Data));
{ Remove outdated < and > markers from the Back and Next buttons. Done here for now to avoid a Default.isl change. }
StringChange(SetupMessages[msgButtonBack], '< ', '');
StringChange(SetupMessages[msgButtonNext], ' >', '');
ActiveLanguage := I;
Finalize(LangOptions); { prevent leak on D2 }
LangOptions := LangEntry^;
{ Hack for Japanese: Override the default fonts on older versions of Windows
that don't (fully) support font linking }
if (LangOptions.LanguageID = $0411) and
{$IFNDEF UNICODE}
(GetACP = 932) and
{$ENDIF}
(WindowsVersion < Cardinal($05010000)) and
FontExists(SMSPGothic) then begin
{ Windows <= 2000: Verdana can't display Japanese }
LangOptions.WelcomeFontName := SMSPGothic;
LangOptions.WelcomeFontSize := 12;
{$IFNDEF UNICODE}
if WindowsVersion < Cardinal($05000000) then begin
{ Windows 9x/Me/NT 4.0: MS Sans Serif can't display Japanese }
LangOptions.DialogFontName := SMSPGothic;
LangOptions.DialogFontSize := 9;
LangOptions.TitleFontName := SMSPGothic;
LangOptions.TitleFontSize := 29;
LangOptions.CopyrightFontName := SMSPGothic;
LangOptions.CopyrightFontSize := 9;
end;
{$ENDIF}
end;
if LangEntry.LicenseText <> '' then
ActiveLicenseText := LangEntry.LicenseText
else
ActiveLicenseText := SetupHeader.LicenseText;
if LangEntry.InfoBeforeText <> '' then
ActiveInfoBeforeText := LangEntry.InfoBeforeText
else
ActiveInfoBeforeText := SetupHeader.InfoBeforeText;
if LangEntry.InfoAfterText <> '' then
ActiveInfoAfterText := LangEntry.InfoAfterText
else
ActiveInfoAfterText := SetupHeader.InfoAfterText;
SetMessageBoxRightToLeft(LangOptions.RightToLeft);
SetMessageBoxCaption(mbInformation, PChar(SetupMessages[msgInformationTitle]));
SetMessageBoxCaption(mbConfirmation, PChar(SetupMessages[msgConfirmTitle]));
SetMessageBoxCaption(mbError, PChar(SetupMessages[msgErrorTitle]));
SetMessageBoxCaption(mbCriticalError, PChar(SetupMessages[msgErrorTitle]));
Application.Title := SetupMessages[msgSetupAppTitle];
for J := 0 to Entries[seType].Count-1 do begin
with PSetupTypeEntry(Entries[seType][J])^ do begin
case Typ of
ttDefaultFull: Description := SetupMessages[msgFullInstallation];
ttDefaultCompact: Description := SetupMessages[msgCompactInstallation];
ttDefaultCustom: Description := SetupMessages[msgCustomInstallation];
end;
end;
end;
{ Tell the first instance to change its language too. (It's possible for
the first instance to display messages after Setup terminates, e.g. if it
fails to restart the computer.) }
if SetupNotifyWndPresent then
SendNotifyMessage(SetupNotifyWnd, WM_USER + 150, 10001, I);
end;
function GetLanguageEntryProc(Index: Integer; var Entry: PSetupLanguageEntry): Boolean;
begin
Result := False;
if Index < Entries[seLanguage].Count then begin
Entry := Entries[seLanguage][Index];
Result := True;
end;
end;
procedure ActivateDefaultLanguage;
{ Auto-detects the most appropriate language and activates it.
Also initializes the ShowLanguageDialog and MatchedLangParameter variables.
Note: A like-named version of this function is also present in SetupLdr.dpr. }
var
I: Integer;
begin
MatchedLangParameter := False;
case DetermineDefaultLanguage(GetLanguageEntryProc,
SetupHeader.LanguageDetectionMethod, InitLang, I) of
ddNoMatch: ShowLanguageDialog := (SetupHeader.ShowLanguageDialog <> slNo);
ddMatch: ShowLanguageDialog := (SetupHeader.ShowLanguageDialog = slYes);
else
begin
{ ddMatchLangParameter }
ShowLanguageDialog := False;
MatchedLangParameter := True;
end;
end;
SetActiveLanguage(I);
end;
procedure SetTaskbarButtonVisibility(const AVisible: Boolean);
var
ExStyle: Longint;
begin
{ The taskbar button is hidden by setting the WS_EX_TOOLWINDOW style on the
application window. We can't simply hide the window because on D3+ the VCL
would just show it again in TApplication.UpdateVisible when the first form
is shown. }
{$IFDEF IS_D12}
TaskbarButtonHidden := not AVisible; { see WM_STYLECHANGING hook in Setup.dpr }
{$ENDIF}
if (GetWindowLong(Application.Handle, GWL_EXSTYLE) and WS_EX_TOOLWINDOW = 0) <> AVisible then begin
SetWindowPos(Application.Handle, 0, 0, 0, 0, 0, SWP_NOSIZE or
SWP_NOMOVE or SWP_NOZORDER or SWP_NOACTIVATE or SWP_HIDEWINDOW);
ExStyle := GetWindowLong(Application.Handle, GWL_EXSTYLE);
if AVisible then
ExStyle := ExStyle and not WS_EX_TOOLWINDOW
else
ExStyle := ExStyle or WS_EX_TOOLWINDOW;
SetWindowLong(Application.Handle, GWL_EXSTYLE, ExStyle);
if AVisible then
{ Show and activate when becoming visible }
ShowWindow(Application.Handle, SW_SHOW)
else
SetWindowPos(Application.Handle, 0, 0, 0, 0, 0, SWP_NOSIZE or
SWP_NOMOVE or SWP_NOZORDER or SWP_NOACTIVATE or SWP_SHOWWINDOW);
end;
end;
procedure LogCompatibilityMode;
var
S: String;
begin
S := GetEnv('__COMPAT_LAYER');
if S <> '' then
LogFmt('Compatibility mode: %s (%s)', [SYesNo[True], S]);
end;
procedure LogWindowsVersion;
var
SP: String;
begin
if NTServicePackLevel <> 0 then begin
SP := ' SP' + IntToStr(Hi(NTServicePackLevel));
if Lo(NTServicePackLevel) <> 0 then
SP := SP + '.' + IntToStr(Lo(NTServicePackLevel));
end;
LogFmt('Windows version: %u.%u.%u%s (NT platform: %s)', [WindowsVersion shr 24,
(WindowsVersion shr 16) and $FF, WindowsVersion and $FFFF, SP, SYesNo[IsNT]]);
LogFmt('64-bit Windows: %s', [SYesNo[IsWin64]]);
LogFmt('Processor architecture: %s', [SetupProcessorArchitectureNames[ProcessorArchitecture]]);
if IsNT then begin
if IsAdmin then
Log('User privileges: Administrative')
else if IsPowerUserOrAdmin then
Log('User privileges: Power User')
else
Log('User privileges: None');
end;
end;
function GetMessageBoxResultText(const AResult: Integer): String;
const
IDTRYAGAIN = 10;
IDCONTINUE = 11;
begin
case AResult of
IDOK: Result := 'OK';
IDCANCEL: Result := 'Cancel';
IDABORT: Result := 'Abort';
IDRETRY: Result := 'Retry';
IDIGNORE: Result := 'Ignore';
IDYES: Result := 'Yes';
IDNO: Result := 'No';
IDTRYAGAIN: Result := 'Try Again';
IDCONTINUE: Result := 'Continue';
else
Result := IntToStr(AResult);
end;
end;
function GetButtonsText(const Buttons: Cardinal): String;
const
{ We don't use this type, but end users are liable to in [Code] }
MB_CANCELTRYCONTINUE = $00000006;
begin
case Buttons and MB_TYPEMASK of
MB_OK: Result := 'OK';
MB_OKCANCEL: Result := 'OK/Cancel';
MB_ABORTRETRYIGNORE: Result := 'Abort/Retry/Ignore';
MB_YESNOCANCEL: Result := 'Yes/No/Cancel';
MB_YESNO: Result := 'Yes/No';
MB_RETRYCANCEL: Result := 'Retry/Cancel';
MB_CANCELTRYCONTINUE: Result := 'Cancel/Try Again/Continue';
else
Result := IntToStr(Buttons and MB_TYPEMASK);
end;
end;
procedure LogSuppressedMessageBox(const Text: PChar; const Buttons: Cardinal;
const Default: Integer);
begin
Log(Format('Defaulting to %s for suppressed message box (%s):' + SNewLine,
[GetMessageBoxResultText(Default), GetButtonsText(Buttons)]) + Text);
end;
procedure LogMessageBox(const Text: PChar; const Buttons: Cardinal);
begin
Log(Format('Message box (%s):' + SNewLine,
[GetButtonsText(Buttons)]) + Text);
end;
function LoggedAppMessageBox(const Text, Caption: PChar; const Flags: Longint;
const Suppressible: Boolean; const Default: Integer): Integer;
begin
if InitSuppressMsgBoxes and Suppressible then begin
LogSuppressedMessageBox(Text, Flags, Default);
Result := Default;
end else begin
LogMessageBox(Text, Flags);
Result := AppMessageBox(Text, Caption, Flags);
if Result <> 0 then
LogFmt('User chose %s.', [GetMessageBoxResultText(Result)])
else
Log('AppMessageBox failed.');
end;
end;
function LoggedMsgBox(const Text, Caption: String; const Typ: TMsgBoxType;
const Buttons: Cardinal; const Suppressible: Boolean; const Default: Integer): Integer;
begin
if InitSuppressMsgBoxes and Suppressible then begin
LogSuppressedMessageBox(PChar(Text), Buttons, Default);
Result := Default;
end else begin
LogMessageBox(PChar(Text), Buttons);
Result := MsgBox(Text, Caption, Typ, Buttons);
if Result <> 0 then
LogFmt('User chose %s.', [GetMessageBoxResultText(Result)])
else
Log('MsgBox failed.');
end;
end;
function LoggedTaskDialogMsgBox(const Icon, Instruction, Text, Caption: String;
const Typ: TMsgBoxType; const Buttons: Cardinal; const ButtonLabels: array of String;
const ShieldButton: Integer; const Suppressible: Boolean; const Default: Integer;
const VerificationText: String = ''; const pfVerificationFlagChecked: PBOOL = nil): Integer;
begin
if InitSuppressMsgBoxes and Suppressible then begin
LogSuppressedMessageBox(PChar(Text), Buttons, Default);
Result := Default;
end else begin
LogMessageBox(PChar(Text), Buttons);
Result := TaskDialogMsgBox(Icon, Instruction, Text,
Caption, Typ, Buttons, ButtonLabels, ShieldButton, VerificationText, pfVerificationFlagChecked);
if Result <> 0 then begin
LogFmt('User chose %s.', [GetMessageBoxResultText(Result)]);
if pfVerificationFlagChecked <> nil then
LogFmt('User chose %s for the verification.', [SYesNo[pfVerificationFlagChecked^]]);
end else
Log('TaskDialogMsgBox failed.');
end;
end;
procedure RestartComputerFromThisProcess;
begin
RestartInitiatedByThisProcess := True;
{ Note: Depending on the OS, RestartComputer may not return if successful }
if not RestartComputer then begin
{ Hack for when called from RespawnSetupElevated: re-show the
application's taskbar button }
ShowWindow(Application.Handle, SW_SHOW);
{ If another app denied the shutdown, we probably lost the foreground;
try to take it back. (Note: Application.BringToFront can't be used
because we have no visible forms, and MB_SETFOREGROUND doesn't make
the app's taskbar button blink.) }
SetForegroundWindow(Application.Handle);
LoggedMsgBox(SetupMessages[msgErrorRestartingComputer], '', mbError,
MB_OK, True, IDOK);
end;
end;
procedure RespawnSetupElevated(const AParams: String);
{ Starts a new, elevated Setup(Ldr) process and waits until it terminates.
Does not return; either calls Halt or raises an exception. }
var
Cancelled: Boolean;
Server: TSpawnServer;
ParamNotifyWnd: HWND;
RespawnResults: record
ExitCode: DWORD;
NotifyRestartRequested: Boolean;
NotifyNewLanguage: Integer;
end;
begin
{ Hide the taskbar button }
SetWindowPos(Application.Handle, 0, 0, 0, 0, 0, SWP_NOSIZE or
SWP_NOMOVE or SWP_NOZORDER or SWP_NOACTIVATE or SWP_HIDEWINDOW);
Cancelled := False;
try
Server := TSpawnServer.Create;
try
if SetupNotifyWndPresent then
ParamNotifyWnd := SetupNotifyWnd
else
ParamNotifyWnd := Server.Wnd;
RespawnSelfElevated(SetupLdrOriginalFilename,
Format('/SPAWNWND=$%x /NOTIFYWND=$%x ', [Server.Wnd, ParamNotifyWnd]) +
AParams, RespawnResults.ExitCode);
RespawnResults.NotifyRestartRequested := Server.NotifyRestartRequested;
RespawnResults.NotifyNewLanguage := Server.NotifyNewLanguage;
finally
Server.Free;
end;
except
{ If the user clicked Cancel on the dialog, halt with special exit code }
if ExceptObject is EAbort then
Cancelled := True
else begin
{ Otherwise, re-show the taskbar button and re-raise }
ShowWindow(Application.Handle, SW_SHOW);
raise;
end;
end;
if Cancelled then
Halt(ecCancelledBeforeInstall);
if not SetupNotifyWndPresent then begin
{ In the UseSetupLdr=no case, there is no notify window handle to pass to
RespawnSelfElevated, so it hosts one itself. Process the results. }
try
if (RespawnResults.NotifyNewLanguage >= 0) and
(RespawnResults.NotifyNewLanguage < Entries[seLanguage].Count) then
SetActiveLanguage(RespawnResults.NotifyNewLanguage);
if RespawnResults.NotifyRestartRequested then begin
{ Note: Depending on the OS, this may not return if successful }
RestartComputerFromThisProcess;
end;
except
{ In the unlikely event that something above raises an exception, handle
it here so the right exit code will still be returned below }
ShowWindow(Application.Handle, SW_SHOW);
Application.HandleException(nil);
end;
end;
Halt(RespawnResults.ExitCode);
end;
procedure InitializeCommonVars;
{ Initializes variables shared between Setup and Uninstall }
begin
IsAdmin := IsAdminLoggedOn;
IsPowerUserOrAdmin := IsAdmin or IsPowerUserLoggedOn;
Randomize;
end;
procedure InitializeAdminInstallMode(const AAdminInstallMode: Boolean);
{ Initializes IsAdminInstallMode and other global variables that depend on it }
const
RootKeys: array[Boolean] of HKEY = (HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE);
begin
LogFmt('Administrative install mode: %s', [SYesNo[AAdminInstallMode]]);
IsAdminInstallMode := AAdminInstallMode;
InstallModeRootKey := RootKeys[AAdminInstallMode];
LogFmt('Install mode root key: %s', [GetRegRootKeyName(InstallModeRootKey)]);
end;
procedure Initialize64BitInstallMode(const A64BitInstallMode: Boolean);
{ Initializes Is64BitInstallMode and other global variables that depend on it }
begin
Is64BitInstallMode := A64BitInstallMode;
InstallDefaultDisableFsRedir := A64BitInstallMode;
ScriptFuncDisableFsRedir := A64BitInstallMode;
if A64BitInstallMode then
InstallDefaultRegView := rv64Bit
else
InstallDefaultRegView := rv32Bit;
end;
procedure Log64BitInstallMode;
begin
LogFmt('64-bit install mode: %s', [SYesNo[Is64BitInstallMode]]);
end;
procedure InitializeSetup;
{ Initializes various vars used by the setup. This is called in the project
source. }
var
DecompressorDLL, DecryptDLL: TMemoryStream;
function ExtractLongWord(var S: String): LongWord;
var
P: Integer;
begin
P := PathPos(',', S);
if P = 0 then
raise Exception.Create('ExtractLongWord: Missing comma');
Result := LongWord(StrToInt(Copy(S, 1, P-1)));
Delete(S, 1, P);
end;
function ArchitecturesToStr(const Architectures: TSetupProcessorArchitectures): String;
procedure AppendLine(var S: String; const L: String);
begin
if S <> '' then
S := S + #13#10 + L
else
S := L;
end;
var
I: TSetupProcessorArchitecture;
begin
Result := '';
for I := Low(I) to High(I) do
if I in Architectures then
AppendLine(Result, SetupProcessorArchitectureNames[I]);
end;
procedure AbortInit(const Msg: TSetupMessageID);
begin
LoggedMsgBox(SetupMessages[Msg], '', mbCriticalError, MB_OK, True, IDOK);
Abort;
end;
procedure AbortInitFmt1(const Msg: TSetupMessageID; const Arg1: String);
begin
LoggedMsgBox(FmtSetupMessage(Msg, [Arg1]), '', mbCriticalError, MB_OK, True, IDOK);
Abort;
end;
procedure AbortInitServicePackRequired(const ServicePack: Word);
begin
LoggedMsgBox(FmtSetupMessage(msgWindowsServicePackRequired, ['Windows',
IntToStr(Hi(ServicePack))]), '', mbCriticalError, MB_OK, True, IDOK);
Abort;
end;
procedure ReadFileIntoStream(const Stream: TStream;
const R: TCompressedBlockReader);
type
PBuffer = ^TBuffer;
TBuffer = array[0..8191] of Byte;
var
Buf: PBuffer;
BytesLeft, Bytes: Longint;
begin
New(Buf);
try
R.Read(BytesLeft, SizeOf(BytesLeft));
while BytesLeft > 0 do begin
Bytes := BytesLeft;
if Bytes > SizeOf(Buf^) then Bytes := SizeOf(Buf^);
R.Read(Buf^, Bytes);
Stream.WriteBuffer(Buf^, Bytes);
Dec(BytesLeft, Bytes);
end;
finally
Dispose(Buf);
end;
end;
function ReadWizardImage(const R: TCompressedBlockReader): TBitmap;
var
MemStream: TMemoryStream;
begin
MemStream := TMemoryStream.Create;
try
ReadFileIntoStream(MemStream, R);
MemStream.Seek(0, soFromBeginning);
Result := TBitmap.Create;
Result.AlphaFormat := TAlphaFormat(SetupHeader.WizardImageAlphaFormat);
Result.LoadFromStream(MemStream);
finally
MemStream.Free;
end;
end;
procedure LoadDecompressorDLL;
var
Filename: String;
begin
Filename := AddBackslash(TempInstallDir) + '_isetup\_isdecmp.dll';
SaveStreamToTempFile(DecompressorDLL, Filename);
FreeAndNil(DecompressorDLL);
DecompressorDLLHandle := SafeLoadLibrary(Filename, SEM_NOOPENFILEERRORBOX);
if DecompressorDLLHandle = 0 then
InternalError(Format('Failed to load DLL "%s"', [Filename]));
case SetupHeader.CompressMethod of
cmZip:
if not ZlibInitDecompressFunctions(DecompressorDLLHandle) then
InternalError('ZlibInitDecompressFunctions failed');
cmBzip:
if not BZInitDecompressFunctions(DecompressorDLLHandle) then
InternalError('BZInitDecompressFunctions failed');
end;
end;
procedure LoadDecryptDLL;
var
Filename: String;
begin
Filename := AddBackslash(TempInstallDir) + '_isetup\_iscrypt.dll';
SaveStreamToTempFile(DecryptDLL, Filename);
FreeAndNil(DecryptDLL);
DecryptDLLHandle := SafeLoadLibrary(Filename, SEM_NOOPENFILEERRORBOX);
if DecryptDLLHandle = 0 then
InternalError(Format('Failed to load DLL "%s"', [Filename]));
if not ArcFourInitFunctions(DecryptDLLHandle) then
InternalError('ISCryptInitFunctions failed');
end;
var
Reader: TCompressedBlockReader;
procedure ReadEntriesWithoutVersion(const EntryType: TEntryType;
const Count: Integer; const Size: Integer);
var
I: Integer;
P: Pointer;
begin
Entries[EntryType].Capacity := Count;
for I := 0 to Count-1 do begin
P := AllocMem(Size);
SECompressedBlockRead(Reader, P^, Size, EntryStrings[EntryType],
EntryAnsiStrings[EntryType]);
Entries[EntryType].Add(P);
end;
end;
procedure ReadEntries(const EntryType: TEntryType; const Count: Integer;
const Size: Integer; const MinVersionOfs, OnlyBelowVersionOfs: Integer);
var
I: Integer;
P: Pointer;
begin
if Debugging then begin
OriginalEntryIndexes[EntryType] := TList.Create;
OriginalEntryIndexes[EntryType].Capacity := Count;
end;
Entries[EntryType].Capacity := Count;
for I := 0 to Count-1 do begin
P := AllocMem(Size);
SECompressedBlockRead(Reader, P^, Size, EntryStrings[EntryType],
EntryAnsiStrings[Entrytype]);
if (MinVersionOfs = -1) or
(InstallOnThisVersion(TSetupVersionData((@PByteArray(P)[MinVersionOfs])^),
TSetupVersionData((@PByteArray(P)[OnlyBelowVersionOfs])^)) = irInstall) then begin
Entries[EntryType].Add(P);
if Debugging then
OriginalEntryIndexes[EntryType].Add(Pointer(I));
end
else
SEFreeRec(P, EntryStrings[EntryType], EntryAnsiStrings[EntryType]);
end;
end;
function HandleInitPassword(const NeedPassword: Boolean): Boolean;
{ Handles InitPassword and returns the updated value of NeedPassword }
{ Also see Wizard.CheckPassword }
var
S: String;
PasswordOk: Boolean;
begin
Result := NeedPassword;
if NeedPassword and (InitPassword <> '') then begin
PasswordOk := False;
S := InitPassword;
if shPassword in SetupHeader.Options then
PasswordOk := TestPassword(S);
if not PasswordOk and (CodeRunner <> nil) then
PasswordOk := CodeRunner.RunBooleanFunctions('CheckPassword', [S], bcTrue, False, PasswordOk);
if PasswordOk then begin
Result := False;
if shEncryptionUsed in SetupHeader.Options then
FileExtractor.CryptKey := S;
end;
end;
end;
procedure SetupInstallMode;
begin
if InitVerySilent then
InstallMode := imVerySilent
else if InitSilent then
InstallMode := imSilent;
if InstallMode <> imNormal then begin
if InstallMode = imVerySilent then begin
Application.ShowMainForm := False;
SetTaskbarButtonVisibility(False);
end;
SetupHeader.Options := SetupHeader.Options - [shWindowVisible];
end;
end;
function RecurseExternalGetSizeOfFiles(const DisableFsRedir: Boolean;
const SearchBaseDir, SearchSubDir, SearchWildcard: String;
const SourceIsWildcard: Boolean; const RecurseSubDirs: Boolean): Integer64;
var
SearchFullPath: String;
H: THandle;
FindData: TWin32FindData;
I: Integer64;
begin
SearchFullPath := SearchBaseDir + SearchSubDir + SearchWildcard;
Result.Hi := 0;
Result.Lo := 0;
H := FindFirstFileRedir(DisableFsRedir, SearchFullPath, FindData);
if H <> INVALID_HANDLE_VALUE then begin
repeat
if FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY = 0 then begin
if SourceIsWildcard then
if FindData.dwFileAttributes and FILE_ATTRIBUTE_HIDDEN <> 0 then
Continue;
I.Hi := FindData.nFileSizeHigh;
I.Lo := FindData.nFileSizeLow;
Inc6464(Result, I);
end;
until not FindNextFile(H, FindData);
Windows.FindClose(H);
end;
if RecurseSubDirs then begin
H := FindFirstFileRedir(DisableFsRedir, SearchBaseDir + SearchSubDir + '*', FindData);
if H <> INVALID_HANDLE_VALUE then begin
try
repeat
if IsRecurseableDirectory(FindData) then begin
I := RecurseExternalGetSizeOfFiles(DisableFsRedir, SearchBaseDir,
SearchSubDir + FindData.cFileName + '\', SearchWildcard,
SourceIsWildcard, RecurseSubDirs);
Inc6464(Result, I);
end;
until not FindNextFile(H, FindData);
finally
Windows.FindClose(H);
end;
end;
end;
end;
{ Also see Install.pas }
function ExistingInstallationAt(const RootKey: HKEY; const SubkeyName: String): Boolean;
var
K: HKEY;
begin
if RegOpenKeyExView(InstallDefaultRegView, RootKey, PChar(SubkeyName), 0, KEY_QUERY_VALUE, K) = ERROR_SUCCESS then begin
Result := True;
RegCloseKey(K);
end else
Result := False;
end;
procedure HandlePrivilegesRequiredOverrides(var ExtraRespawnParam: String);
var
ExistingAtAdminInstallMode, ExistingAtNonAdminInstallMode, DesireAnInstallMode, DesireAdminInstallMode: Boolean;
SubkeyName, AppName: String;
begin
if HasInitPrivilegesRequired and (proCommandLine in SetupHeader.PrivilegesRequiredOverridesAllowed) then begin
SetupHeader.PrivilegesRequired := InitPrivilegesRequired;
{ We don't need to set ExtraRespawnParam since the existing command line
already contains the needed parameters and it will automatically be
passed on to any respawned Setup(Ldr). }
end else if proDialog in SetupHeader.PrivilegesRequiredOverridesAllowed then begin
if shUsePreviousPrivileges in SetupHeader.Options then begin
{ Note: if proDialog is used and UsePreviousPrivileges is set to "yes"
then the compiler does not allow AppId to include constants but we
should still call ExpandConst to handle any '{{'. }
SubkeyName := GetUninstallRegSubkeyName(GetUninstallRegKeyBaseName(ExpandConst(SetupHeader.AppID)));
ExistingAtAdminInstallMode := ExistingInstallationAt(HKEY_LOCAL_MACHINE, SubkeyName);
ExistingAtNonAdminInstallMode := ExistingInstallationAt(HKEY_CURRENT_USER, SubkeyName);
end else begin
ExistingAtAdminInstallMode := False;
ExistingAtNonAdminInstallMode := False;
end;
DesireAnInstallMode := True;
DesireAdminInstallMode := False; { Silence compiler }
if ExistingAtAdminInstallMode and not ExistingAtNonAdminInstallMode then
DesireAdminInstallMode := True
else if not ExistingAtAdminInstallMode and ExistingAtNonAdminInstallMode then
DesireAdminInstallMode := False
else if not InitSuppressMsgBoxes then begin
{ Ask user. Doesn't log since logging hasn't started yet. Also doesn't
use ExpandedAppName since it isn't set yet. Afterwards we need to tell
any respawned Setup(Ldr) about the user choice (and avoid asking again).
Will use the command line parameter for this. Allowing proDialog forces
allowing proCommandLine, so we can count on the parameter to work. }
if shAppNameHasConsts in SetupHeader.Options then
AppName := PathChangeExt(PathExtractName(SetupLdrOriginalFilename), '')
else
AppName := SetupHeader.AppName;
if SetupHeader.PrivilegesRequired = prLowest then begin
case TaskDialogMsgBox('MAINICON', SetupMessages[msgPrivilegesRequiredOverrideInstruction],
FmtSetupMessage(msgPrivilegesRequiredOverrideText2, [AppName]),
SetupMessages[msgPrivilegesRequiredOverrideTitle], mbInformation, MB_YESNOCANCEL,
[SetupMessages[msgPrivilegesRequiredOverrideCurrentUserRecommended], SetupMessages[msgPrivilegesRequiredOverrideAllUsers]], IDNO) of
IDYES: DesireAdminInstallMode := False;
IDNO: DesireAdminInstallMode := True;
IDCANCEL: Abort;
end;
end else begin
case TaskDialogMsgBox('MAINICON', SetupMessages[msgPrivilegesRequiredOverrideInstruction],
FmtSetupMessage(msgPrivilegesRequiredOverrideText1, [AppName]),
SetupMessages[msgPrivilegesRequiredOverrideTitle], mbInformation, MB_YESNOCANCEL,
[SetupMessages[msgPrivilegesRequiredOverrideAllUsersRecommended], SetupMessages[msgPrivilegesRequiredOverrideCurrentUser]], IDYES) of
IDYES: DesireAdminInstallMode := True;
IDNO: DesireAdminInstallMode := False;
IDCANCEL: Abort;
end;
end;
end else
DesireAnInstallMode := False; { No previous found and msgboxes are suppressed, just keep things as they are. }
if DesireAnInstallMode then begin
if DesireAdminInstallMode then begin
SetupHeader.PrivilegesRequired := prAdmin;
ExtraRespawnParam := '/ALLUSERS';
end else begin
SetupHeader.PrivilegesRequired := prLowest;
ExtraRespawnParam := '/CURRENTUSER';
end;
end;
end;
end;
var
ParamName, ParamValue: String;
ParamIsAutomaticInternal: Boolean;
StartParam: Integer;
I, N: Integer;
IsRespawnedProcess, EnableLogging, WantToSuppressMsgBoxes, Res: Boolean;
DebugWndValue: HWND;
LogFilename: String;
SetupFilename: String;
SetupFile: TFile;
TestID: TSetupID;
NameAndVersionMsg: String;
NextAllowedLevel: Integer;
LastShownComponentEntry, ComponentEntry: PSetupComponentEntry;
MinimumTypeSpace: Integer64;
SourceWildcard: String;
ExpandedSetupMutex, ExtraRespawnParam, RespawnParams: String;
begin
InitializeCommonVars;
{ NewParamsForCode will hold all params except automatic internal ones like /SL5= and /DEBUGWND=
Also see Uninstall.ProcessCommandLine }
NewParamsForCode.Add(NewParamStr(0));
{ Based on SetupLdr or not?
Parameters for launching SetupLdr-based installation are:
/SL5="<handle to SetupLdr's notify window>,<setup 0 data offset>,
<setup 1 data offset>,<original exe filename>"
}
SplitNewParamStr(1, ParamName, ParamValue);
if CompareText(ParamName, '/SL5=') = 0 then begin
StartParam := 2;
SetupLdrMode := True;
SetupNotifyWnd := ExtractLongWord(ParamValue);
SetupNotifyWndPresent := True;
SetupLdrOffset0 := ExtractLongWord(ParamValue);
SetupLdrOffset1 := ExtractLongWord(ParamValue);
SetupLdrOriginalFilename := ParamValue;
end
else begin
StartParam := 1;
SetupLdrOriginalFilename := NewParamStr(0);
end;
SourceDir := PathExtractDir(SetupLdrOriginalFilename);
IsRespawnedProcess := False;
EnableLogging := False;
WantToSuppressMsgBoxes := False;
DebugWndValue := 0;
for I := StartParam to NewParamCount do begin
SplitNewParamStr(I, ParamName, ParamValue);
ParamIsAutomaticInternal := False;
if CompareText(ParamName, '/Log') = 0 then begin
EnableLogging := True;
LogFilename := '';
end else if CompareText(ParamName, '/Log=') = 0 then begin
EnableLogging := True;
LogFilename := ParamValue;
end else if CompareText(ParamName, '/Silent') = 0 then
InitSilent := True
else if CompareText(ParamName, '/VerySilent') = 0 then
InitVerySilent := True
else if CompareText(ParamName, '/NoRestart') = 0 then
InitNoRestart := True
else if CompareText(ParamName, '/CloseApplications') = 0 then
InitCloseApplications := True
else if CompareText(ParamName, '/NoCloseApplications') = 0 then
InitNoCloseApplications := True
else if CompareText(ParamName, '/ForceCloseApplications') = 0 then
InitForceCloseApplications := True
else if CompareText(ParamName, '/NoForceCloseApplications') = 0 then
InitNoForceCloseApplications := True
else if CompareText(ParamName, '/LogCloseApplications') = 0 then
InitLogCloseApplications := True
else if CompareText(ParamName, '/RestartApplications') = 0 then
InitRestartApplications := True
else if CompareText(ParamName, '/NoRestartApplications') = 0 then
InitNoRestartApplications := True
else if CompareText(ParamName, '/NoIcons') = 0 then
InitNoIcons := True
else if CompareText(ParamName, '/NoCancel') = 0 then
InitNoCancel := True
else if CompareText(ParamName, '/Lang=') = 0 then
InitLang := ParamValue
else if CompareText(ParamName, '/Type=') = 0 then
InitSetupType := ParamValue
else if CompareText(ParamName, '/Components=') = 0 then begin
InitComponentsSpecified := True;
SetStringsFromCommaString(InitComponents, SlashesToBackslashes(ParamValue));
end else if CompareText(ParamName, '/Tasks=') = 0 then begin
InitDeselectAllTasks := True;
SetStringsFromCommaString(InitTasks, SlashesToBackslashes(ParamValue));
end else if CompareText(ParamName, '/MergeTasks=') = 0 then begin
InitDeselectAllTasks := False;
SetStringsFromCommaString(InitTasks, SlashesToBackslashes(ParamValue));
end else if CompareText(ParamName, '/LoadInf=') = 0 then
InitLoadInf := PathExpand(ParamValue)
else if CompareText(ParamName, '/SaveInf=') = 0 then
InitSaveInf := PathExpand(ParamValue)
else if CompareText(ParamName, '/DIR=') = 0 then
InitDir := ParamValue
else if CompareText(ParamName, '/GROUP=') = 0 then
InitProgramGroup := ParamValue
else if CompareText(ParamName, '/Password=') = 0 then
InitPassword := ParamValue
else if CompareText(ParamName, '/RestartExitCode=') = 0 then
InitRestartExitCode := StrToIntDef(ParamValue, 0)
else if CompareText(ParamName, '/SuppressMsgBoxes') = 0 then
WantToSuppressMsgBoxes := True
else if CompareText(ParamName, '/DETACHEDMSG') = 0 then { for debugging }
DetachedUninstMsgFile := True
else if CompareText(ParamName, '/SPAWNWND=') = 0 then begin
ParamIsAutomaticInternal := True; { sent by RespawnSetupElevated }
IsRespawnedProcess := True;
InitializeSpawnClient(StrToInt(ParamValue));
end else if CompareText(ParamName, '/NOTIFYWND=') = 0 then begin
ParamIsAutomaticInternal := True; { sent by RespawnSetupElevated }
{ /NOTIFYWND= takes precedence over any previously set SetupNotifyWnd }
SetupNotifyWnd := StrToInt(ParamValue);
SetupNotifyWndPresent := True;
end else if CompareText(ParamName, '/DebugSpawnServer') = 0 then { for debugging }
EnterSpawnServerDebugMode { does not return }
else if CompareText(ParamName, '/DEBUGWND=') = 0 then begin
ParamIsAutomaticInternal := True; { sent by TCompileForm.StartProcess }
DebugWndValue := StrToInt(ParamValue);
end else if CompareText(ParamName, '/ALLUSERS') = 0 then begin
InitPrivilegesRequired := prAdmin;
HasInitPrivilegesRequired := True;
end else if CompareText(ParamName, '/CURRENTUSER') = 0 then begin
InitPrivilegesRequired := prLowest;
HasInitPrivilegesRequired := True;
end;
if not ParamIsAutomaticInternal then
NewParamsForCode.Add(NewParamStr(I));
end;
if InitLoadInf <> '' then
LoadInf(InitLoadInf, WantToSuppressMsgBoxes);
if WantToSuppressMsgBoxes and (InitSilent or InitVerySilent) then
InitSuppressMsgBoxes := True;
{ Assign some default messages that may be used before the messages are read }
SetupMessages[msgSetupFileMissing] := SSetupFileMissing;
SetupMessages[msgSetupFileCorrupt] := SSetupFileCorrupt;
SetupMessages[msgSetupFileCorruptOrWrongVer] := SSetupFileCorruptOrWrongVer;
{ Read setup-0.bin, or from EXE }
if not SetupLdrMode then begin
SetupFilename := PathChangeExt(SetupLdrOriginalFilename, '') + '-0.bin';
if not NewFileExists(SetupFilename) then
AbortInitFmt1(msgSetupFileMissing, PathExtractName(SetupFilename));
end
else
SetupFilename := SetupLdrOriginalFilename;
SetupFile := TFile.Create(SetupFilename, fdOpenExisting, faRead, fsRead);
try
SetupFile.Seek(SetupLdrOffset0);
if SetupFile.Read(TestID, SizeOf(TestID)) <> SizeOf(TestID) then
AbortInit(msgSetupFileCorruptOrWrongVer);
if TestID <> SetupID then
AbortInit(msgSetupFileCorruptOrWrongVer);
try
Reader := TCompressedBlockReader.Create(SetupFile, TLZMA1Decompressor);
try
{ Header }
SECompressedBlockRead(Reader, SetupHeader, SizeOf(SetupHeader),
SetupHeaderStrings, SetupHeaderAnsiStrings);
{ Language entries }
ReadEntriesWithoutVersion(seLanguage, SetupHeader.NumLanguageEntries,
SizeOf(TSetupLanguageEntry));
{ CustomMessage entries }
ReadEntriesWithoutVersion(seCustomMessage, SetupHeader.NumCustomMessageEntries,
SizeOf(TSetupCustomMessageEntry));
{ Permission entries }
ReadEntriesWithoutVersion(sePermission, SetupHeader.NumPermissionEntries,
SizeOf(TSetupPermissionEntry));
{ Type entries }
ReadEntries(seType, SetupHeader.NumTypeEntries, SizeOf(TSetupTypeEntry),
Integer(@PSetupTypeEntry(nil).MinVersion),
Integer(@PSetupTypeEntry(nil).OnlyBelowVersion));
ActivateDefaultLanguage;
{ Set Is64BitInstallMode if we're on Win64 and the processor architecture is
one on which a "64-bit mode" install should be performed. Doing this early
so that UsePreviousPrivileges knows where to look. Will log later. }
if ProcessorArchitecture in SetupHeader.ArchitecturesInstallIn64BitMode then begin
if not IsWin64 then begin
{ A 64-bit processor was detected and 64-bit install mode was requested,
but IsWin64 is False, indicating required WOW64 APIs are not present }
AbortInit(msgWindowsVersionNotSupported);
end;
Initialize64BitInstallMode(True);
end
else
Initialize64BitInstallMode(False);
HandlePrivilegesRequiredOverrides(ExtraRespawnParam);
{ Start a new, elevated Setup(Ldr) process if needed }
if not IsRespawnedProcess and
NeedToRespawnSelfElevated(not (SetupHeader.PrivilegesRequired in [prNone, prLowest]),
SetupHeader.PrivilegesRequired <> prLowest) then begin
FreeAndNil(Reader);
FreeAndNil(SetupFile);
RespawnParams := GetCmdTailEx(StartParam);
if ExtraRespawnParam <> '' then
RespawnParams := RespawnParams + ' ' + ExtraRespawnParam;
RespawnSetupElevated(RespawnParams);
{ Note: RespawnSetupElevated does not return; it either calls Halt
or raises an exception. }
end;
{ Application.Handle is now known to be the main window. Set the shutdown block reason. }
ShutdownBlockReasonCreate(Application.Handle, SetupMessages[msgWizardInstalling]);
{ Initialize debug client }
if DebugWndValue <> 0 then
SetDebugWnd(DebugWndValue, False);
{ Initialize logging }
if EnableLogging or (shSetupLogging in SetupHeader.Options) then begin
try
if LogFilename = '' then
StartLogging('Setup')
else
StartLoggingWithFixedFilename(LogFilename);
except
on E: Exception do begin
E.Message := 'Error creating log file:' + SNewLine2 + E.Message;
raise;
end;
end;
end;
Log('Setup version: ' + SetupTitle + ' version ' + SetupVersion);
Log('Original Setup EXE: ' + SetupLdrOriginalFilename);
Log('Setup command line: ' + GetCmdTail);
LogCompatibilityMode;
LogWindowsVersion;
NeedPassword := shPassword in SetupHeader.Options;
NeedSerial := False;
NeedsRestart := shAlwaysRestart in SetupHeader.Options;
{ Component entries }
ReadEntries(seComponent, SetupHeader.NumComponentEntries, SizeOf(TSetupComponentEntry),
-1, -1);
{ Task entries }
ReadEntries(seTask, SetupHeader.NumTaskEntries, SizeOf(TSetupTaskEntry),
-1, -1);
{ Dir entries }
ReadEntries(seDir, SetupHeader.NumDirEntries, SizeOf(TSetupDirEntry),
Integer(@PSetupDirEntry(nil).MinVersion),
Integer(@PSetupDirEntry(nil).OnlyBelowVersion));
{ File entries }
ReadEntries(seFile, SetupHeader.NumFileEntries, SizeOf(TSetupFileEntry),
Integer(@PSetupFileEntry(nil).MinVersion),
Integer(@PSetupFileEntry(nil).OnlyBelowVersion));
{ Icon entries }
ReadEntries(seIcon, SetupHeader.NumIconEntries, SizeOf(TSetupIconEntry),
Integer(@PSetupIconEntry(nil).MinVersion),
Integer(@PSetupIconEntry(nil).OnlyBelowVersion));
{ INI entries }
ReadEntries(seIni, SetupHeader.NumIniEntries, SizeOf(TSetupIniEntry),
Integer(@PSetupIniEntry(nil).MinVersion),
Integer(@PSetupIniEntry(nil).OnlyBelowVersion));
{ Registry entries }
ReadEntries(seRegistry, SetupHeader.NumRegistryEntries, SizeOf(TSetupRegistryEntry),
Integer(@PSetupRegistryEntry(nil).MinVersion),
Integer(@PSetupRegistryEntry(nil).OnlyBelowVersion));
{ InstallDelete entries }
ReadEntries(seInstallDelete, SetupHeader.NumInstallDeleteEntries, SizeOf(TSetupDeleteEntry),
Integer(@PSetupDeleteEntry(nil).MinVersion),
Integer(@PSetupDeleteEntry(nil).OnlyBelowVersion));
{ UninstallDelete entries }
ReadEntries(seUninstallDelete, SetupHeader.NumUninstallDeleteEntries, SizeOf(TSetupDeleteEntry),
Integer(@PSetupDeleteEntry(nil).MinVersion),
Integer(@PSetupDeleteEntry(nil).OnlyBelowVersion));
{ Run entries }
ReadEntries(seRun, SetupHeader.NumRunEntries, SizeOf(TSetupRunEntry),
Integer(@PSetupRunEntry(nil).MinVersion),
Integer(@PSetupRunEntry(nil).OnlyBelowVersion));
{ UninstallRun entries }
ReadEntries(seUninstallRun, SetupHeader.NumUninstallRunEntries, SizeOf(TSetupRunEntry),
Integer(@PSetupRunEntry(nil).MinVersion),
Integer(@PSetupRunEntry(nil).OnlyBelowVersion));
{ Wizard image }
Reader.Read(N, SizeOf(LongInt));
for I := 0 to N-1 do
WizardImages.Add(ReadWizardImage(Reader));
Reader.Read(N, SizeOf(LongInt));
for I := 0 to N-1 do
WizardSmallImages.Add(ReadWizardImage(Reader));
{ Decompressor DLL }
DecompressorDLL := nil;
if SetupHeader.CompressMethod in [cmZip, cmBzip] then begin
DecompressorDLL := TMemoryStream.Create;
ReadFileIntoStream(DecompressorDLL, Reader);
end;
{ Decryption DLL }
DecryptDLL := nil;
if shEncryptionUsed in SetupHeader.Options then begin
DecryptDLL := TMemoryStream.Create;
ReadFileIntoStream(DecryptDLL, Reader);
end;
finally
Reader.Free;
end;
Reader := TCompressedBlockReader.Create(SetupFile, TLZMA1Decompressor);
try
{ File location entries }
ReadEntriesWithoutVersion(seFileLocation, SetupHeader.NumFileLocationEntries,
SizeOf(TSetupFileLocationEntry));
finally
Reader.Free;
end;
except
on ECompressDataError do
AbortInit(msgSetupFileCorrupt);
end;
finally
SetupFile.Free;
end;
InitializeAdminInstallMode(IsAdmin and (SetupHeader.PrivilegesRequired <> prLowest));
Log64BitInstallMode;
{ Show "Select Language" dialog if necessary - requires "64-bit mode" to be
initialized else it might query the previous language from the wrong registry
view }
if Entries[seLanguage].Count > 1 then begin
if ShowLanguageDialog and not InitSilent and not InitVerySilent then begin
if not AskForLanguage then
Abort;
end else if not MatchedLangParameter and (shUsePreviousLanguage in SetupHeader.Options) then begin
{ Replicate the dialog's UsePreviousLanguage functionality. }
{ Note: if UsePreviousLanguage is set to "yes" then the compiler does not
allow AppId to include constants but we should still call ExpandConst
to handle any '{{'. }
I := GetPreviousLanguage(ExpandConst(SetupHeader.AppId));
if I <> -1 then
SetActiveLanguage(I);
end;
end;
{ Check processor architecture }
if (SetupHeader.ArchitecturesAllowed <> []) and
not(ProcessorArchitecture in SetupHeader.ArchitecturesAllowed) then
AbortInitFmt1(msgOnlyOnTheseArchitectures, ArchitecturesToStr(SetupHeader.ArchitecturesAllowed));
{ Check Windows version }
case InstallOnThisVersion(SetupHeader.MinVersion, SetupHeader.OnlyBelowVersion) of
irInstall: ;
irServicePackTooLow:
AbortInitServicePackRequired(SetupHeader.MinVersion.NTServicePack);
else
AbortInit(msgWindowsVersionNotSupported);
end;
{ Check if the user lacks the required privileges }
case SetupHeader.PrivilegesRequired of
prPowerUser:
if not IsPowerUserOrAdmin then AbortInit(msgPowerUserPrivilegesRequired);
prAdmin:
if not IsAdmin then AbortInit(msgAdminPrivilegesRequired);
end;
{ Init main constants, not depending on shfolder.dll/_shfoldr.dll }
InitMainNonSHFolderConsts;
{ Create temporary directory and extract 64-bit helper EXE if necessary }
CreateTempInstallDir;
{ Load system's "shfolder.dll" or extract "_shfoldr.dll" to TempInstallDir, and load it }
LoadSHFolderDLL;
{ Extract "_isdecmp.dll" to TempInstallDir, and load it }
if SetupHeader.CompressMethod in [cmZip, cmBzip] then
LoadDecompressorDLL;
{ Extract "_iscrypt.dll" to TempInstallDir, and load it }
if shEncryptionUsed in SetupHeader.Options then
LoadDecryptDLL;
{ Start RestartManager session }
if InitCloseApplications or
((shCloseApplications in SetupHeader.Options) and not InitNoCloseApplications) then begin
InitRestartManagerLibrary;
{ Note from Old New Thing: "The RmStartSession function doesn't properly
null-terminate the session key <...>. To work around this bug, we pre-fill
the buffer with null characters <...>." Our key is pre-filled too since
it's global. }
if UseRestartManager and (RmStartSession(@RmSessionHandle, 0, RmSessionKey) = ERROR_SUCCESS) then begin
RmSessionStarted := True;
SetStringsFromCommaString(CloseApplicationsFilterList, SetupHeader.CloseApplicationsFilter);
end;
end;
{ Set install mode }
SetupInstallMode;
{ Load and initialize code }
if SetupHeader.CompiledCodeText <> '' then begin
CodeRunner := TScriptRunner.Create();
try
CodeRunner.NamingAttribute := CodeRunnerNamingAttribute;
CodeRunner.OnLog := CodeRunnerOnLog;
CodeRunner.OnLogFmt := CodeRunnerOnLogFmt;
CodeRunner.OnDllImport := CodeRunnerOnDllImport;
CodeRunner.OnDebug := CodeRunnerOnDebug;
CodeRunner.OnDebugIntermediate := CodeRunnerOnDebugIntermediate;
CodeRunner.OnException := CodeRunnerOnException;
CodeRunner.LoadScript(SetupHeader.CompiledCodeText, DebugClientCompiledCodeDebugInfo);
if not NeedPassword then
NeedPassword := CodeRunner.FunctionExists('CheckPassword', True);
NeedPassword := HandleInitPassword(NeedPassword);
if not NeedSerial then
NeedSerial := CodeRunner.FunctionExists('CheckSerial', True);
except
{ Don't let DeinitSetup see a partially-initialized CodeRunner }
FreeAndNil(CodeRunner);
raise;
end;
try
Res := CodeRunner.RunBooleanFunctions('InitializeSetup', [''], bcFalse, False, True);
except
Log('InitializeSetup raised an exception (fatal).');
raise;
end;
if not Res then begin
Log('InitializeSetup returned False; aborting.');
Abort;
end;
end
else
NeedPassword := HandleInitPassword(NeedPassword);
{ Expand AppName, AppVerName, and AppCopyright now since they're used often,
especially by the background window painting. }
ExpandedAppName := ExpandConst(SetupHeader.AppName);
if SetupHeader.AppVerName <> '' then
ExpandedAppVerName := ExpandConst(SetupHeader.AppVerName)
else begin
if not GetCustomMessageValue('NameAndVersion', NameAndVersionMsg) then
NameAndVersionMsg := '%1 %2'; { just in case }
ExpandedAppVerName := FmtMessage(PChar(NameAndVersionMsg),
[ExpandedAppName, ExpandConst(SetupHeader.AppVersion)]);
end;
ExpandedAppCopyright := ExpandConst(SetupHeader.AppCopyright);
ExpandedAppMutex := ExpandConst(SetupHeader.AppMutex);
ExpandedSetupMutex := ExpandConst(SetupHeader.SetupMutex);
{ Update the shutdown block reason now that we have ExpandedAppName. }
ShutdownBlockReasonCreate(Application.Handle,
FmtSetupMessage1(msgShutdownBlockReasonInstallingApp, ExpandedAppName));
{ Check if app is running }
while CheckForMutexes(ExpandedAppMutex) do
if LoggedMsgBox(FmtSetupMessage1(msgSetupAppRunningError, ExpandedAppName),
SetupMessages[msgSetupAppTitle], mbError, MB_OKCANCEL, True, IDCANCEL) <> IDOK then
Abort;
{ Check if Setup is running and if not create mutexes }
while CheckForMutexes(ExpandedSetupMutex) do
if LoggedMsgBox(FmtSetupMessage1(msgSetupAppRunningError, SetupMessages[msgSetupAppTitle]),
SetupMessages[msgSetupAppTitle], mbError, MB_OKCANCEL, True, IDCANCEL) <> IDOK then
Abort;
CreateMutexes(ExpandedSetupMutex);
{ Remove types that fail their 'languages' or 'check'. Can't do this earlier
because the InitializeSetup call above can't be done earlier. }
for I := 0 to Entries[seType].Count-1 do begin
if not ShouldProcessEntry(nil, nil, '', '', PSetupTypeEntry(Entries[seType][I]).Languages, PSetupTypeEntry(Entries[seType][I]).Check) then begin
SEFreeRec(Entries[seType][I], EntryStrings[seType], EntryAnsiStrings[seType]);
{ Don't delete it yet so that the entries can be processed sequentially }
Entries[seType][I] := nil;
end;
end;
{ Delete the nil-ed items now }
Entries[seType].Pack();
{ Remove components }
NextAllowedLevel := 0;
LastShownComponentEntry := nil;
for I := 0 to Entries[seComponent].Count-1 do begin
ComponentEntry := PSetupComponentEntry(Entries[seComponent][I]);
if (ComponentEntry.Level <= NextAllowedLevel) and
(InstallOnThisVersion(ComponentEntry.MinVersion, ComponentEntry.OnlyBelowVersion) = irInstall) and
ShouldProcessEntry(nil, nil, '', '', ComponentEntry.Languages, ComponentEntry.Check) then begin
NextAllowedLevel := ComponentEntry.Level + 1;
LastShownComponentEntry := ComponentEntry;
end
else begin
{ Not showing }
if Assigned(LastShownComponentEntry) and
(ComponentEntry.Level = LastShownComponentEntry.Level) and
(CompareText(ComponentEntry.Name, LastShownComponentEntry.Name) = 0) then begin
{ It's a duplicate of the last shown item. Leave NextAllowedLevel
alone, so that any child items that follow can attach to the last
shown item. }
end
else begin
{ Not a duplicate of the last shown item, so the next item must be
at the same level or less }
if NextAllowedLevel > ComponentEntry.Level then
NextAllowedLevel := ComponentEntry.Level;
{ Clear LastShownComponentEntry so that no subsequent item can be
considered a duplicate of it. Needed in this case:
foo (shown)
foo\childA (not shown)
foo (not shown)
foo\childB
"foo\childB" should be hidden, not made a child of "foo" #1. }
LastShownComponentEntry := nil;
end;
Entries[seComponent][I] := nil;
SEFreeRec(ComponentEntry, EntryStrings[seComponent], EntryAnsiStrings[seComponent]);
end;
end;
Entries[seComponent].Pack();
{ Set misc. variables }
HasCustomType := False;
for I := 0 to Entries[seType].Count-1 do begin
if toIsCustom in PSetupTypeEntry(Entries[seType][I]).Options then begin
HasCustomType := True;
Break;
end;
end;
HasComponents := Entries[seComponent].Count <> 0;
HasIcons := Entries[seIcon].Count <> 0;
HasTasks := Entries[seTask].Count <> 0;
{ Calculate minimum disk space. If there are setup types, find the smallest
type and add the size of all files that don't belong to any component. Otherwise
calculate minimum disk space by adding all of the file's sizes. Also for each
"external" file, check the file size now, and store it the ExternalSize field
of the TSetupFileEntry record, except if an ExternalSize was specified by the
script. }
MinimumSpace := SetupHeader.ExtraDiskSpaceRequired;
for I := 0 to Entries[seFile].Count-1 do begin
with PSetupFileEntry(Entries[seFile][I])^ do begin
if LocationEntry <> -1 then begin { not an "external" file }
if Components = '' then { no types or a file that doesn't belong to any component }
if (Tasks = '') and (Check = '') then {don't count tasks and scripted entries}
Inc6464(MinimumSpace, PSetupFileLocationEntry(Entries[seFileLocation][LocationEntry])^.OriginalSize)
end else begin
if not(foExternalSizePreset in Options) then begin
try
if FileType <> ftUserFile then
SourceWildcard := NewParamStr(0)
else
SourceWildcard := ExpandConst(SourceFilename);
ExternalSize := RecurseExternalGetSizeOfFiles(
ShouldDisableFsRedirForFileEntry(PSetupFileEntry(Entries[seFile][I])),
PathExtractPath(SourceWildcard),
'', PathExtractName(SourceWildcard), IsWildcard(SourceWildcard),
foRecurseSubDirsExternal in Options);
except
{ Ignore exceptions. One notable exception we want to ignore is
the one about "app" not being initialized. }
end;
end;
if Components = '' then { no types or a file that doesn't belong to any component }
if (Tasks = '') and (Check = '') then {don't count tasks or scripted entries}
Inc6464(MinimumSpace, ExternalSize);
end;
end;
end;
for I := 0 to Entries[seComponent].Count-1 do
with PSetupComponentEntry(Entries[seComponent][I])^ do
Size := GetSizeOfComponent(Name, ExtraDiskSpaceRequired);
if Entries[seType].Count > 0 then begin
for I := 0 to Entries[seType].Count-1 do begin
with PSetupTypeEntry(Entries[seType][I])^ do begin
Size := GetSizeOfType(Name, toIsCustom in Options);
if (I = 0) or (Compare64(Size, MinimumTypeSpace) < 0) then
MinimumTypeSpace := Size;
end;
end;
Inc6464(MinimumSpace, MinimumTypeSpace);
end;
end;
procedure DeinitSetup(const AllowCustomSetupExitCode: Boolean);
var
I: Integer;
begin
Log('Deinitializing Setup.');
if Assigned(CodeRunner) then begin
if AllowCustomSetupExitCode then begin
try
SetupExitCode := CodeRunner.RunIntegerFunctions('GetCustomSetupExitCode',
[''], bcNonZero, False, SetupExitCode);
except
Log('GetCustomSetupExitCode raised an exception.');
Application.HandleException(nil);
end;
end;
try
CodeRunner.RunProcedures('DeinitializeSetup', [''], False);
except
Log('DeinitializeSetup raised an exception.');
Application.HandleException(nil);
end;
FreeAndNil(CodeRunner);
end;
for I := 0 to DeleteFilesAfterInstallList.Count-1 do
DeleteFileRedir(DeleteFilesAfterInstallList.Objects[I] <> nil,
DeleteFilesAfterInstallList[I]);
DeleteFilesAfterInstallList.Clear;
for I := DeleteDirsAfterInstallList.Count-1 downto 0 do
RemoveDirectoryRedir(DeleteDirsAfterInstallList.Objects[I] <> nil,
DeleteDirsAfterInstallList[I]);
DeleteDirsAfterInstallList.Clear;
FreeFileExtractor;
{ End RestartManager session }
if RmSessionStarted then
RmEndSession(RmSessionHandle);
{ Free the _iscrypt.dll handle }
if DecryptDLLHandle <> 0 then
FreeLibrary(DecryptDLLHandle);
{ Free the _isdecmp.dll handle }
if DecompressorDLLHandle <> 0 then
FreeLibrary(DecompressorDLLHandle);
{ Free the shfolder.dll handles }
UnloadSHFolderDLL;
{ Remove TempInstallDir, stopping the 64-bit helper first if necessary }
RemoveTempInstallDir;
{ An attempt to restart while debugging is most likely an accident;
don't allow it }
if RestartSystem and Debugging then begin
Log('Not restarting Windows because Setup is being run from the debugger.');
RestartSystem := False;
end;
EndDebug;
ShutdownBlockReasonDestroy(Application.Handle);
if RestartSystem then begin
Log('Restarting Windows.');
if SetupNotifyWndPresent then begin
{ Send a special message back to the first instance telling it to
restart the system after Setup returns }
SendNotifyMessage(SetupNotifyWnd, WM_USER + 150, 10000, 0);
end
else begin
{ There is no other instance, so initiate the restart ourself.
Note: Depending on the OS, this may not return if successful. }
RestartComputerFromThisProcess;
end;
end;
end;
function BlendRGB(const Color1, Color2: TColor; const Blend: Integer): TColor;
{ Blends Color1 and Color2. Blend must be between 0 and 255; 0 = all Color1,
255 = all Color2. }
type
TColorBytes = array[0..3] of Byte;
var
I: Integer;
begin
Result := 0;
for I := 0 to 2 do
TColorBytes(Result)[I] := Integer(TColorBytes(Color1)[I] +
((TColorBytes(Color2)[I] - TColorBytes(Color1)[I]) * Blend) div 255);
end;
function ExitSetupMsgBox: Boolean;
begin
Result := LoggedMsgBox(SetupMessages[msgExitSetupMessage], SetupMessages[msgExitSetupTitle],
mbConfirmation, MB_YESNO or MB_DEFBUTTON2, False, 0) = IDYES;
end;
procedure TerminateApp;
begin
{ Work around shell32 bug: Don't use PostQuitMessage/Application.Terminate
here.
When ShellExecute is called with the name of a folder, it internally
creates a window used for DDE communication with Windows Explorer. After
ShellExecute returns, this window eventually receives a posted WM_DDE_ACK
message back from the DDE server (Windows Explorer), and in response, it
tries to flush the queue of DDE messages by using a PeekMessage loop.
Problem is, PeekMessage will return WM_QUIT messages posted with
PostQuitMessage regardless of the message range specified, and the loop was
not written with this in mind.
In previous IS versions, this was causing our WM_QUIT message to be eaten
if Application.Terminate was called very shortly after a shellexec [Run]
entry was processed (e.g. if DisableFinishedPage=yes).
A WM_QUIT message posted with PostMessage instead of PostQuitMessage will
not be returned by a GetMessage/PeekMessage call with a message range that
does not include WM_QUIT. }
PostMessage(0, WM_QUIT, 0, 0);
end;
{ TMainForm }
constructor TMainForm.Create(AOwner: TComponent);
var
SystemMenu: HMenu;
begin
inherited;
InitializeFont;
if shWindowVisible in SetupHeader.Options then begin
{ Should the main window not be sizable? }
if not(shWindowShowCaption in SetupHeader.Options) then
BorderStyle := bsNone
else
if not(shWindowResizable in SetupHeader.Options) then
BorderStyle := bsSingle;
{ Make the main window full-screen. If the window is resizable, limit it
to just the work area because on recent versions of Windows (e.g. 2000)
full-screen resizable windows don't cover over the taskbar. }
BoundsRect := GetRectOfPrimaryMonitor(BorderStyle = bsSizeable);
{ Before maximizing the window, ensure Handle is created now so the correct
'restored' position is saved properly }
HandleNeeded;
{ Maximize the window so that the taskbar is still accessible }
if shWindowStartMaximized in SetupHeader.Options then
WindowState := wsMaximized;
end
else begin
Application.ShowMainForm := False;
end;
if shDisableWelcomePage in SetupHeader.Options then
Caption := FmtSetupMessage1(msgSetupWindowTitle, ExpandedAppVerName)
else
Caption := FmtSetupMessage1(msgSetupWindowTitle, ExpandedAppName);
{ Append the 'About Setup' item to the system menu }
SystemMenu := GetSystemMenu(Handle, False);
AppendMenu(SystemMenu, MF_SEPARATOR, 0, nil);
AppendMenu(SystemMenu, MF_STRING, 9999, PChar(SetupMessages[msgAboutSetupMenuItem]));
Application.HookMainWindow(MainWindowHook);
if Application.ShowMainForm then
{ Show this form now, so that the focus stays on the wizard form that
InitializeWizard (called in the .dpr) shows }
Visible := True;
end;
destructor TMainForm.Destroy;
begin
Application.UnhookMainWindow(MainWindowHook);
inherited;
end;
procedure TMainForm.WMSysCommand(var Message: TWMSysCommand);
begin
if Message.CmdType = 9999 then
ShowAboutBox
else
inherited;
end;
procedure TMainForm.WMEraseBkgnd(var Message: TWMEraseBkgnd);
begin
{ Since the form paints its entire client area in FormPaint, there is
no need for the VCL to ever erase the client area with the brush color.
Doing so only slows it down, so this message handler disables that default
behavior. }
Message.Result := 0;
end;
procedure TMainForm.FormPaint(Sender: TObject);
var
C1, C2: TColor;
CS: TPoint;
Z: Integer;
DrawTextFlags: UINT;
R, R2: TRect;
begin
with Canvas do begin
{ Draw the blue background }
if SetupHeader.BackColor = SetupHeader.BackColor2 then begin
Brush.Color := SetupHeader.BackColor;
FillRect(ClientRect);
end
else begin
C1 := ColorToRGB(SetupHeader.BackColor);
C2 := ColorToRGB(SetupHeader.BackColor2);
CS := ClientRect.BottomRight;
for Z := 0 to 255 do begin
Brush.Color := BlendRGB(C1, C2, Z);
if not(shBackColorHorizontal in SetupHeader.Options) then
FillRect(Rect(0, MulDiv(CS.Y, Z, 255), CS.X, MulDiv(CS.Y, Z+1, 255)))
else
FillRect(Rect(MulDiv(CS.X, Z, 255), 0, MulDiv(CS.X, Z+1, 255), CS.Y));
end;
end;
{ Draw the application name and copyright }
SetBkMode(Handle, TRANSPARENT);
DrawTextFlags := DT_WORDBREAK or DT_NOPREFIX or DT_NOCLIP;
if RightToLeft then
DrawTextFlags := DrawTextFlags or (DT_RIGHT or DT_RTLREADING);
SetFontNameSize(Font, LangOptions.TitleFontName,
LangOptions.TitleFontSize, 'Arial', 29);
if IsMultiByteString(AnsiString(ExpandedAppName)) then
{ Don't use italics on Japanese characters }
Font.Style := [fsBold]
else
Font.Style := [fsBold, fsItalic];
R := ClientRect;
InflateRect(R, -8, -8);
R2 := R;
if RightToLeft then
OffsetRect(R2, -4, 4)
else
OffsetRect(R2, 4, 4);
Font.Color := clBlack;
DrawText(Handle, PChar(ExpandedAppName), -1, R2, DrawTextFlags);
Font.Color := clWhite;
DrawText(Handle, PChar(ExpandedAppName), -1, R, DrawTextFlags);
DrawTextFlags := DrawTextFlags xor DT_RIGHT;
SetFontNameSize(Font, LangOptions.CopyrightFontName,
LangOptions.CopyrightFontSize, 'Arial', 8);
Font.Style := [];
R := ClientRect;
InflateRect(R, -6, -6);
R2 := R;
DrawText(Handle, PChar(ExpandedAppCopyright), -1, R2, DrawTextFlags or
DT_CALCRECT);
R.Top := R.Bottom - (R2.Bottom - R2.Top);
R2 := R;
if RightToLeft then
OffsetRect(R2, -1, 1)
else
OffsetRect(R2, 1, 1);
Font.Color := clBlack;
DrawText(Handle, PChar(ExpandedAppCopyright), -1, R2, DrawTextFlags);
Font.Color := clWhite;
DrawText(Handle, PChar(ExpandedAppCopyright), -1, R, DrawTextFlags);
end;
end;
procedure TMainForm.FormResize(Sender: TObject);
begin
{ Needs to redraw the background whenever the form is resized }
Repaint;
end;
procedure TMainForm.ShowAboutBox;
var
S: String;
begin
{ Removing the About box or modifying any existing text inside it is a
violation of the Inno Setup license agreement; see LICENSE.TXT.
However, adding additional lines to the end of the About box is
permitted. }
S := SetupTitle + ' version ' + SetupVersion + SNewLine;
if SetupTitle <> 'Inno Setup' then
S := S + (SNewLine + 'Based on Inno Setup' + SNewLine);
S := S + ('Copyright (C) 1997-2021 Jordan Russell' + SNewLine +
'Portions Copyright (C) 2000-2021 Martijn Laan' + SNewLine +
'All rights reserved.' + SNewLine2 +
'Inno Setup home page:' + SNewLine +
'https://www.innosetup.com/');
S := S + SNewLine2 + 'RemObjects Pascal Script home page:' + SNewLine +
'https://www.remobjects.com/ps';
if SetupMessages[msgAboutSetupNote] <> '' then
S := S + SNewLine2 + SetupMessages[msgAboutSetupNote];
if SetupMessages[msgTranslatorNote] <> '' then
S := S + SNewLine2 + SetupMessages[msgTranslatorNote];
{$IFDEF UNICODE}
StringChangeEx(S, '(C)', #$00A9, True);
{$ENDIF}
LoggedMsgBox(S, SetupMessages[msgAboutSetupTitle], mbInformation, MB_OK, False, 0);
end;
class procedure TMainForm.ShowExceptionMsg(const S: String);
begin
Log('Exception message:');
LoggedAppMessageBox(PChar(S), PChar(Application.Title), MB_OK or MB_ICONSTOP, True, IDOK);
end;
class procedure TMainForm.ShowException(Sender: TObject; E: Exception);
begin
ShowExceptionMsg(AddPeriod(E.Message));
end;
procedure ProcessMessagesProc; far;
begin
Application.ProcessMessages;
end;
procedure TMainForm.SetStep(const AStep: TSetupStep; const HandleExceptions: Boolean);
begin
CurStep := AStep;
if CodeRunner <> nil then begin
try
CodeRunner.RunProcedures('CurStepChanged', [Ord(CurStep)], False);
except
if HandleExceptions then begin
Log('CurStepChanged raised an exception.');
Application.HandleException(Self);
end
else begin
Log('CurStepChanged raised an exception (fatal).');
raise;
end;
end;
end;
end;
procedure TMainForm.InitializeWizard;
begin
WizardForm := TWizardForm.Create(Application);
if CodeRunner <> nil then begin
try
CodeRunner.RunProcedures('InitializeWizard', [''], False);
except
Log('InitializeWizard raised an exception (fatal).');
raise;
end;
end;
WizardForm.FlipSizeAndCenterIfNeeded(shWindowVisible in SetupHeader.Options, MainForm, True);
WizardForm.SetCurPage(wpWelcome);
if InstallMode = imNormal then begin
WizardForm.ClickToStartPage; { this won't go past wpReady }
SetActiveWindow(Application.Handle); { ensure taskbar button is selected }
WizardForm.Show;
end
else
WizardForm.ClickThroughPages;
end;
function ShouldDisableFsRedirForRunEntry(const RunEntry: PSetupRunEntry): Boolean;
begin
Result := InstallDefaultDisableFsRedir;
if roRun32Bit in RunEntry.Options then
Result := False;
if roRun64Bit in RunEntry.Options then begin
if not IsWin64 then
InternalError('Cannot run files in 64-bit locations on this version of Windows');
Result := True;
end;
end;
procedure ProcessRunEntry(const RunEntry: PSetupRunEntry);
var
RunAsOriginalUser: Boolean;
ExpandedFilename, ExpandedParameters: String;
Wait: TExecWait;
DisableFsRedir: Boolean;
ErrorCode: Integer;
begin
try
Log('-- Run entry --');
RunAsOriginalUser := (roRunAsOriginalUser in RunEntry.Options);
if RunAsOriginalUser then
Log('Run as: Original user')
else
Log('Run as: Current user');
if not(roShellExec in RunEntry.Options) then
Log('Type: Exec')
else
Log('Type: ShellExec');
ExpandedFilename := ExpandConst(RunEntry.Name);
Log('Filename: ' + ExpandedFilename);
ExpandedParameters := ExpandConst(RunEntry.Parameters);
if not(roDontLogParameters in RunEntry.Options) and (ExpandedParameters <> '') then
Log('Parameters: ' + ExpandedParameters);
Wait := ewWaitUntilTerminated;
case RunEntry.Wait of
rwNoWait: Wait := ewNoWait;
rwWaitUntilIdle: Wait := ewWaitUntilIdle;
end;
if not(roShellExec in RunEntry.Options) then begin
DisableFsRedir := ShouldDisableFsRedirForRunEntry(RunEntry);
if not(roSkipIfDoesntExist in RunEntry.Options) or
NewFileExistsRedir(DisableFsRedir, ExpandedFilename) then begin
if not InstExecEx(RunAsOriginalUser, DisableFsRedir, ExpandedFilename,
ExpandedParameters, ExpandConst(RunEntry.WorkingDir),
Wait, RunEntry.ShowCmd, ProcessMessagesProc, ErrorCode) then
raise Exception.Create(FmtSetupMessage1(msgErrorExecutingProgram, ExpandedFilename) +
SNewLine2 + FmtSetupMessage(msgErrorFunctionFailedWithMessage,
['CreateProcess', IntToStr(ErrorCode), Win32ErrorString(ErrorCode)]));
if Wait = ewWaitUntilTerminated then
Log(Format('Process exit code: %u', [ErrorCode]));
end
else
Log('File doesn''t exist. Skipping.');
end
else begin
if not(roSkipIfDoesntExist in RunEntry.Options) or FileOrDirExists(ExpandedFilename) then begin
if not InstShellExecEx(RunAsOriginalUser, ExpandConst(RunEntry.Verb),
ExpandedFilename, ExpandedParameters, ExpandConst(RunEntry.WorkingDir),
Wait, RunEntry.ShowCmd, ProcessMessagesProc, ErrorCode) then
raise Exception.Create(FmtSetupMessage1(msgErrorExecutingProgram, ExpandedFilename) +
SNewLine2 + FmtSetupMessage(msgErrorFunctionFailedWithMessage,
['ShellExecuteEx', IntToStr(ErrorCode), Win32ErrorString(ErrorCode)]));
end
else
Log('File/directory doesn''t exist. Skipping.');
end;
except
Application.HandleException(nil);
end;
end;
procedure ShellExecuteAsOriginalUser(hWnd: HWND; Operation, FileName, Parameters, Directory: LPWSTR; ShowCmd: Integer); stdcall;
var
ErrorCode: Integer;
begin
InstShellExecEx(True, Operation, Filename, Parameters, Directory, ewNoWait, ShowCmd, ProcessMessagesProc, ErrorCode);
end;
function TMainForm.Install: Boolean;
procedure ProcessRunEntries;
var
CheckIfRestartNeeded: Boolean;
ChecksumBefore, ChecksumAfter: TMD5Digest;
WindowDisabler: TWindowDisabler;
I: Integer;
RunEntry: PSetupRunEntry;
begin
if Entries[seRun].Count <> 0 then begin
CheckIfRestartNeeded := (shRestartIfNeededByRun in SetupHeader.Options) and
not NeedsRestart;
if CheckIfRestartNeeded then
ChecksumBefore := MakePendingFileRenameOperationsChecksum;
WindowDisabler := nil;
try
for I := 0 to Entries[seRun].Count-1 do begin
RunEntry := PSetupRunEntry(Entries[seRun][I]);
if not(roPostInstall in RunEntry.Options) and
ShouldProcessRunEntry(WizardComponents, WizardTasks, RunEntry) then begin
{ Disable windows during execution of [Run] entries so that a nice
"beep" is produced if the user tries clicking on WizardForm }
if WindowDisabler = nil then
WindowDisabler := TWindowDisabler.Create;
if RunEntry.StatusMsg <> '' then begin
try
WizardForm.StatusLabel.Caption := ExpandConst(RunEntry.StatusMsg);
except
{ Don't die if the expansion fails with an exception. Just
display the exception message, and proceed with the default
status message. }
Application.HandleException(Self);
WizardForm.StatusLabel.Caption := SetupMessages[msgStatusRunProgram];
end;
end
else
WizardForm.StatusLabel.Caption := SetupMessages[msgStatusRunProgram];
WizardForm.StatusLabel.Update;
if roHideWizard in RunEntry.Options then begin
if WizardForm.Visible and not HideWizard then begin
HideWizard := True;
UpdateWizardFormVisibility;
end;
end
else begin
if HideWizard then begin
HideWizard := False;
UpdateWizardFormVisibility;
end;
end;
DebugNotifyEntry(seRun, I);
NotifyBeforeInstallEntry(RunEntry.BeforeInstall);
ProcessRunEntry(RunEntry);
NotifyAfterInstallEntry(RunEntry.AfterInstall);
end;
end;
finally
if HideWizard then begin
HideWizard := False;
UpdateWizardFormVisibility;
end;
WindowDisabler.Free;
if CheckIfRestartNeeded then begin
ChecksumAfter := MakePendingFileRenameOperationsChecksum;
if not MD5DigestsEqual(ChecksumBefore, ChecksumAfter) then
NeedsRestart := True;
end;
end;
Application.BringToFront;
end;
end;
procedure RestartApplications;
const
ERROR_FAIL_RESTART = 353;
var
Error: DWORD;
WindowDisabler: TWindowDisabler;
begin
if not NeedsRestart then begin
WizardForm.StatusLabel.Caption := SetupMessages[msgStatusRestartingApplications];
WizardForm.StatusLabel.Update;
Log('Attempting to restart applications.');
{ Disable windows during application restart so that a nice
"beep" is produced if the user tries clicking on WizardForm }
WindowDisabler := TWindowDisabler.Create;
try
Error := RmRestart(RmSessionHandle, 0, nil);
finally
WindowDisabler.Free;
end;
Application.BringToFront;
if Error = ERROR_FAIL_RESTART then
Log('One or more applications could not be restarted.')
else if Error <> ERROR_SUCCESS then begin
RmEndSession(RmSessionHandle);
RmSessionStarted := False;
LogFmt('RmRestart returned an error: %d', [Error]);
end;
end else
Log('Need to restart Windows, not attempting to restart applications');
end;
var
Succeeded, ChangesEnvironment, ChangesAssociations: Boolean;
S: String;
begin
Result := False;
try
if not WizardForm.ValidateDirEdit then
Abort;
WizardDirValue := WizardForm.DirEdit.Text;
if not WizardForm.ValidateGroupEdit then
Abort;
WizardGroupValue := WizardForm.GroupEdit.Text;
WizardNoIcons := WizardForm.NoIconsCheck.Checked;
WizardSetupType := WizardForm.GetSetupType();
WizardForm.GetComponents(WizardComponents, WizardDeselectedComponents);
WizardForm.GetTasks(WizardTasks, WizardDeselectedTasks);
WizardPreparingYesRadio := WizardForm.PreparingYesRadio.Checked;
if InitSaveInf <> '' then
SaveInf(InitSaveInf);
Application.Restore;
Update;
if InstallMode = imSilent then begin
SetActiveWindow(Application.Handle); { ensure taskbar button is selected }
WizardForm.Show;
end;
WizardForm.Update;
SetStep(ssInstall, False);
ChangesEnvironment := EvalDirectiveCheck(SetupHeader.ChangesEnvironment);
ChangesAssociations := EvalDirectiveCheck(SetupHeader.ChangesAssociations);
PerformInstall(Succeeded, ChangesEnvironment, ChangesAssociations);
if not Succeeded then begin
{ The user canceled the install or there was a fatal error }
TerminateApp;
Exit;
end;
{ Can't cancel at any point after PerformInstall, so disable the button }
WizardForm.CancelButton.Enabled := False;
ProcessRunEntries;
if RmDoRestart and
(InitRestartApplications or
((shRestartApplications in SetupHeader.Options) and not InitNoRestartApplications)) then
RestartApplications;
SetStep(ssPostInstall, True);
{ Notify Windows of assocations/environment changes *after* ssPostInstall
since user might set more stuff there }
if ChangesAssociations then
SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, nil, nil);
if ChangesEnvironment then
RefreshEnvironment;
if InstallMode <> imNormal then
WizardForm.Hide;
LogFmt('Need to restart Windows? %s', [SYesNo[NeedsRestart]]);
if NeedsRestart and not InitNoRestart then begin
with WizardForm do begin
ChangeFinishedLabel(ExpandSetupMessage(msgFinishedRestartLabel));
YesRadio.Visible := True;
NoRadio.Visible := True;
end;
end else begin
if CreatedIcon then
S := ExpandSetupMessage(msgFinishedLabel)
else
S := ExpandSetupMessage(msgFinishedLabelNoIcons);
with WizardForm do begin
ChangeFinishedLabel(S + SNewLine2 + SetupMessages[msgClickFinish]);
if not NeedsRestart then begin
UpdateRunList(WizardComponents, WizardTasks);
RunList.Visible := RunList.Items.Count > 0;
end;
end;
end;
if InstallMode = imNormal then begin
Application.Restore;
Update;
end;
Result := True;
except
{ If an exception was raised, display the message, then terminate }
Application.HandleException(Self);
SetupExitCode := ecNextStepError;
TerminateApp;
end;
end;
procedure TMainForm.Finish(const FromPreparingPage: Boolean);
procedure WaitForForegroundLoss;
function IsForegroundProcess: Boolean;
var
W: HWND;
PID: DWORD;
begin
W := GetForegroundWindow;
Result := False;
if (W <> 0) and (GetWindowThreadProcessId(W, @PID) <> 0) then
Result := (PID = GetCurrentProcessId);
end;
var
StartTick: DWORD;
begin
StartTick := GetTickCount;
while IsForegroundProcess do begin
{ Stop if it's taking too long (e.g. if the spawned process never
displays a window) }
if Cardinal(GetTickCount - StartTick) >= Cardinal(1000) then
Break;
ProcessMessagesProc;
WaitMessageWithTimeout(10);
ProcessMessagesProc;
end;
end;
procedure ProcessPostInstallRunEntries;
var
WindowDisabler: TWindowDisabler;
ProcessedNoWait: Boolean;
I: Integer;
RunEntry: PSetupRunEntry;
begin
WindowDisabler := nil;
try
ProcessedNoWait := False;
with WizardForm do begin
for I := 0 to RunList.Items.Count-1 do begin
if RunList.Checked[I] then begin
{ Disable windows before processing the first entry }
if WindowDisabler = nil then
WindowDisabler := TWindowDisabler.Create;
RunEntry := PSetupRunEntry(Entries[seRun][Integer(RunList.ItemObject[I])]);
DebugNotifyEntry(seRun, Integer(RunList.ItemObject[I]));
NotifyBeforeInstallEntry(RunEntry.BeforeInstall);
ProcessRunEntry(RunEntry);
NotifyAfterInstallEntry(RunEntry.AfterInstall);
if RunEntry.Wait = rwNoWait then
ProcessedNoWait := True;
end;
end;
end;
{ Give nowait processes some time to bring themselves to the
foreground before Setup exits. Without this delay, the application
underneath Setup can end up coming to the foreground instead.
(Note: Windows are already disabled at this point.) }
if ProcessedNoWait then
WaitForForegroundLoss;
finally
WindowDisabler.Free;
end;
end;
var
S: String;
begin
try
{ Deactivate WizardForm so another application doesn't come to the
foreground when Hide is called. (Needed by WaitForForegroundLoss.) }
if GetForegroundWindow = WizardForm.Handle then
SetActiveWindow(Application.Handle);
WizardForm.Hide;
if not FromPreparingPage and not NeedsRestart then begin
ProcessPostInstallRunEntries;
end else begin
if FromPreparingPage then
SetupExitCode := ecPrepareToInstallFailedRestartNeeded
else if InitRestartExitCode <> 0 then
SetupExitCode := InitRestartExitCode;
if InitNoRestart then
RestartSystem := False
else begin
case InstallMode of
imNormal:
if FromPreparingPage then
RestartSystem := WizardForm.PreparingYesRadio.Checked
else
RestartSystem := WizardForm.YesRadio.Checked;
imSilent:
begin
if FromPreparingPage then
S := WizardForm.PrepareToInstallFailureMessage + SNewLine +
SNewLine + SNewLine + ExpandSetupMessage(msgPrepareToInstallNeedsRestart)
else
S := ExpandSetupMessage(msgFinishedRestartMessage);
RestartSystem :=
LoggedMsgBox(S, '', mbConfirmation, MB_YESNO, True, IDYES) = IDYES;
end;
imVerySilent:
RestartSystem := True;
end;
end;
if not RestartSystem then
Log('Will not restart Windows automatically.');
end;
SetStep(ssDone, True);
except
Application.HandleException(Self);
SetupExitCode := ecNextStepError;
end;
TerminateApp;
end;
procedure TMainForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
function ConfirmCancel(const DefaultConfirm: Boolean): Boolean;
var
Cancel, Confirm: Boolean;
begin
Cancel := True;
Confirm := DefaultConfirm;
WizardForm.CallCancelButtonClick(Cancel, Confirm);
Result := Cancel and (not Confirm or ExitSetupMsgBox);
end;
begin
{ Note: Setting CanClose to True causes Application.Terminate to be called;
we don't want that. }
CanClose := False;
if Assigned(WizardForm) and WizardForm.HandleAllocated and
IsWindowVisible(WizardForm.Handle) and IsWindowEnabled(WizardForm.Handle) and
WizardForm.CancelButton.CanFocus then begin
case CurStep of
ssPreInstall:
if ConfirmCancel((WizardForm.CurPageID <> wpPreparing) or (WizardForm.PrepareToInstallFailureMessage = '')) then begin
if WizardForm.CurPageID = wpPreparing then
SetupExitCode := ecPrepareToInstallFailed
else
SetupExitCode := ecCancelledBeforeInstall;
TerminateApp;
end;
ssInstall:
if (shAllowCancelDuringInstall in SetupHeader.Options) and not InitNoCancel then
if ConfirmCancel(True) then
NeedToAbortInstall := True;
end;
end;
end;
procedure TMainForm.WMGetDlgCode(var Message: TWMGetDlgCode);
begin
Message.Result := Message.Result or DLGC_WANTTAB;
end;
function EWP(Wnd: HWND; Param: LPARAM): BOOL; stdcall;
begin
{ Note: GetParent is not used here because the other windows are not
actually child windows since they don't have WS_CHILD set. }
if GetWindowLong(Wnd, GWL_HWNDPARENT) <> Param then
Result := True
else begin
Result := False;
BringWindowToTop(Wnd);
end;
end;
procedure TMainForm.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
{ If, for some reason, the user doesn't have a mouse and the main form was
activated, there would normally be no way to reactivate the child form.
But this reactivates the form if the user hits a key on the keyboard }
if not(ssAlt in Shift) then begin
Key := 0;
EnumThreadWindows(GetCurrentThreadId, @EWP, Handle);
end;
end;
procedure TMainForm.UpdateWizardFormVisibility;
var
ShouldShow: Boolean;
begin
{ Note: We don't adjust WizardForm.Visible because on Delphi 3+, if all forms
have Visible set to False, the application taskbar button disappears. }
if Assigned(WizardForm) and WizardForm.HandleAllocated then begin
ShouldShow := WizardForm.Showing and not HideWizard and
not IsIconic(Application.Handle);
if (GetWindowLong(WizardForm.Handle, GWL_STYLE) and WS_VISIBLE <> 0) <> ShouldShow then begin
if ShouldShow then
ShowWindow(WizardForm.Handle, SW_SHOW)
else
ShowWindow(WizardForm.Handle, SW_HIDE);
end;
end;
end;
function TMainForm.MainWindowHook(var Message: TMessage): Boolean;
var
IsIcon: Boolean;
begin
Result := False;
case Message.Msg of
WM_WINDOWPOSCHANGED: begin
{ When the application window is minimized or restored, also hide or
show WizardForm.
Note: MainForm is hidden/shown automatically because its owner
window is Application.Handle. }
IsIcon := IsIconic(Application.Handle);
if IsMinimized <> IsIcon then begin
IsMinimized := IsIcon;
UpdateWizardFormVisibility;
end;
end;
end;
end;
procedure TMainForm.WMShowWindow(var Message: TWMShowWindow);
begin
inherited;
{ When showing, ensure WizardForm is the active window, not MainForm }
if Message.Show and (GetActiveWindow = Handle) and
Assigned(WizardForm) and WizardForm.HandleAllocated and
IsWindowVisible(WizardForm.Handle) then
SetActiveWindow(WizardForm.Handle);
end;
procedure InitIsWin64AndProcessorArchitecture;
const
PROCESSOR_ARCHITECTURE_INTEL = 0;
PROCESSOR_ARCHITECTURE_IA64 = 6;
PROCESSOR_ARCHITECTURE_AMD64 = 9;
PROCESSOR_ARCHITECTURE_ARM64 = 12;
IMAGE_FILE_MACHINE_I386 = $014c;
IMAGE_FILE_MACHINE_IA64 = $0200;
IMAGE_FILE_MACHINE_AMD64 = $8664;
IMAGE_FILE_MACHINE_ARM64 = $AA64;
var
KernelModule: HMODULE;
GetNativeSystemInfoFunc: procedure(var lpSystemInfo: TSystemInfo); stdcall;
IsWow64ProcessFunc: function(hProcess: THandle; var Wow64Process: BOOL): BOOL; stdcall;
IsWow64Process2Func: function(hProcess: THandle; var pProcessMachine, pNativeMachine: USHORT): BOOL; stdcall;
ProcessMachine, NativeMachine: USHORT;
Wow64Process: BOOL;
SysInfo: TSystemInfo;
begin
{ The system is considered a "Win64" system if all of the following
conditions are true:
1. One of the following two is true:
a. IsWow64Process2 is available, and returns True for the current process.
b. GetNativeSystemInfo is available +
IsWow64Process is available, and returns True for the current process.
2. Wow64DisableWow64FsRedirection is available.
3. Wow64RevertWow64FsRedirection is available.
4. GetSystemWow64DirectoryA is available.
5. RegDeleteKeyExA is available.
The system does not have to be one of the known 64-bit architectures
(AMD64, IA64, ARM64) to be considered a "Win64" system. }
IsWin64 := False;
KernelModule := GetModuleHandle(kernel32);
IsWow64Process2Func := GetProcAddress(KernelModule, 'IsWow64Process2');
if Assigned(IsWow64Process2Func) and
IsWow64Process2Func(GetCurrentProcess, ProcessMachine, NativeMachine) and
(ProcessMachine <> IMAGE_FILE_MACHINE_UNKNOWN) then begin
IsWin64 := True;
case NativeMachine of
IMAGE_FILE_MACHINE_I386: ProcessorArchitecture := paX86;
IMAGE_FILE_MACHINE_IA64: ProcessorArchitecture := paIA64;
IMAGE_FILE_MACHINE_AMD64: ProcessorArchitecture := paX64;
IMAGE_FILE_MACHINE_ARM64: ProcessorArchitecture := paARM64;
else
ProcessorArchitecture := paUnknown;
end;
end else begin
GetNativeSystemInfoFunc := GetProcAddress(KernelModule, 'GetNativeSystemInfo');
if Assigned(GetNativeSystemInfoFunc) then begin
GetNativeSystemInfoFunc(SysInfo);
IsWow64ProcessFunc := GetProcAddress(KernelModule, 'IsWow64Process');
if Assigned(IsWow64ProcessFunc) and
IsWow64ProcessFunc(GetCurrentProcess, Wow64Process) and
Wow64Process then
IsWin64 := True;
end else
GetSystemInfo(SysInfo);
case SysInfo.wProcessorArchitecture of
PROCESSOR_ARCHITECTURE_INTEL: ProcessorArchitecture := paX86;
PROCESSOR_ARCHITECTURE_IA64: ProcessorArchitecture := paIA64;
PROCESSOR_ARCHITECTURE_AMD64: ProcessorArchitecture := paX64;
PROCESSOR_ARCHITECTURE_ARM64: ProcessorArchitecture := paARM64;
else
ProcessorArchitecture := paUnknown;
end;
end;
if IsWin64 and
not (AreFsRedirectionFunctionsAvailable and
(GetProcAddress(KernelModule, 'GetSystemWow64DirectoryA') <> nil) and
(GetProcAddress(GetModuleHandle(advapi32), 'RegDeleteKeyExA') <> nil)) then
IsWin64 := False;
end;
procedure InitWindowsVersion;
procedure ReadServicePackFromRegistry;
var
K: HKEY;
Size, Typ, SP: DWORD;
begin
if RegOpenKeyExView(rvDefault, HKEY_LOCAL_MACHINE, 'System\CurrentControlSet\Control\Windows',
0, KEY_QUERY_VALUE, K) = ERROR_SUCCESS then begin
Size := SizeOf(SP);
if (RegQueryValueEx(K, 'CSDVersion', nil, @Typ, @SP, @Size) = ERROR_SUCCESS) and
(Typ = REG_DWORD) and (Size = SizeOf(SP)) then
NTServicePackLevel := Word(SP);
RegCloseKey(K);
end;
end;
procedure ReadProductTypeFromRegistry;
const
VER_NT_WORKSTATION = 1;
VER_NT_DOMAIN_CONTROLLER = 2;
VER_NT_SERVER = 3;
var
K: HKEY;
S: String;
begin
if RegOpenKeyExView(rvDefault, HKEY_LOCAL_MACHINE, 'System\CurrentControlSet\Control\ProductOptions',
0, KEY_QUERY_VALUE, K) = ERROR_SUCCESS then begin
{ See MS KB article 152078 for details on this key }
if RegQueryStringValue(K, 'ProductType', S) then begin
if CompareText(S, 'WinNT') = 0 then
WindowsProductType := VER_NT_WORKSTATION
else if CompareText(S, 'LanmanNT') = 0 then
WindowsProductType := VER_NT_DOMAIN_CONTROLLER
else if CompareText(S, 'ServerNT') = 0 then
WindowsProductType := VER_NT_SERVER;
end;
RegCloseKey(K);
end;
end;
type
TOSVersionInfoEx = packed record
dwOSVersionInfoSize: DWORD;
dwMajorVersion: DWORD;
dwMinorVersion: DWORD;
dwBuildNumber: DWORD;
dwPlatformId: DWORD;
szCSDVersion: array[0..127] of Char;
wServicePackMajor: Word;
wServicePackMinor: Word;
wSuiteMask: Word;
wProductType: Byte;
wReserved: Byte;
end;
var
OSVersionInfo: TOSVersionInfo;
OSVersionInfoEx: TOSVersionInfoEx;
begin
OSVersionInfo.dwOSVersionInfoSize := SizeOf(OSVersionInfo);
if GetVersionEx(OSVersionInfo) then begin
WindowsVersion := (Byte(OSVersionInfo.dwMajorVersion) shl 24) or
(Byte(OSVersionInfo.dwMinorVersion) shl 16) or
Word(OSVersionInfo.dwBuildNumber);
{ ^ Note: We MUST clip dwBuildNumber to 16 bits for Win9x compatibility }
if IsNT then begin
if OSVersionInfo.dwMajorVersion >= 5 then begin
{ OSVERSIONINFOEX is only available starting in Windows 2000 }
OSVersionInfoEx.dwOSVersionInfoSize := SizeOf(OSVersionInfoEx);
if GetVersionEx(POSVersionInfo(@OSVersionInfoEx)^) then begin
NTServicePackLevel := (Byte(OSVersionInfoEx.wServicePackMajor) shl 8) or
Byte(OSVersionInfoEx.wServicePackMinor);
WindowsProductType := OSVersionInfoEx.wProductType;
WindowsSuiteMask := OSVersionInfoEx.wSuiteMask;
end;
end
else if OSVersionInfo.dwMajorVersion = 4 then begin
{ Read from the registry on NT 4 }
ReadServicePackFromRegistry;
ReadProductTypeFromRegistry;
end;
end;
end;
end;
procedure CreateEntryLists;
var
I: TEntryType;
begin
for I := Low(I) to High(I) do
Entries[I] := TList.Create;
end;
procedure FreeEntryLists;
var
I: TEntryType;
List: TList;
J: Integer;
P: Pointer;
begin
for I := High(I) downto Low(I) do begin
List := Entries[I];
if Assigned(List) then begin
Entries[I] := nil;
for J := List.Count-1 downto 0 do begin
P := List[J];
if EntryStrings[I] <> 0 then
SEFreeRec(P, EntryStrings[I], EntryAnsiStrings[I])
else
FreeMem(P);
end;
List.Free;
end;
FreeAndNil(OriginalEntryIndexes[I]);
end;
end;
procedure FreeWizardImages;
var
I: Integer;
begin
for I := WizardImages.Count-1 downto 0 do
TBitmap(WizardImages[I]).Free;
FreeAndNil(WizardImages);
for I := WizardSmallImages.Count-1 downto 0 do
TBitmap(WizardSmallImages[I]).Free;
FreeAndNil(WizardSmallImages);
end;
initialization
IsNT := UsingWinNT;
InitIsWin64AndProcessorArchitecture;
InitWindowsVersion;
{$IFNDEF UNICODE}
ConstLeadBytes := @SetupHeader.LeadBytes;
{$ENDIF}
InitComponents := TStringList.Create();
InitTasks := TStringList.Create();
NewParamsForCode := TStringList.Create();
WizardComponents := TStringList.Create();
WizardDeselectedComponents := TStringList.Create();
WizardTasks := TStringList.Create();
WizardDeselectedTasks := TStringList.Create();
CreateEntryLists;
DeleteFilesAfterInstallList := TStringList.Create;
DeleteDirsAfterInstallList := TStringList.Create;
CloseApplicationsFilterList := TStringList.Create;
WizardImages := TList.Create;
WizardSmallImages := TList.Create;
SHGetKnownFolderPathFunc := GetProcAddress(SafeLoadLibrary(AddBackslash(GetSystemDir) + shell32,
SEM_NOOPENFILEERRORBOX), 'SHGetKnownFolderPath');
finalization
FreeWizardImages;
FreeAndNil(CloseApplicationsFilterList);
FreeAndNil(DeleteDirsAfterInstallList);
FreeAndNil(DeleteFilesAfterInstallList);
FreeEntryLists;
FreeAndNil(WizardDeselectedTasks);
FreeAndNil(WizardTasks);
FreeAndNil(WizardDeselectedComponents);
FreeAndNil(WizardComponents);
FreeAndNil(NewParamsForCode);
FreeAndNil(InitTasks);
FreeAndNil(InitComponents);
end.
| 37.833978 | 180 | 0.685474 |
475777b467ec28beadbbb81f96f2e82471d48918 | 1,111 | pas | Pascal | classes/UtilCommon.pas | DanScottNI/delphi-romhacklib | 8b8e18b32a156a20530f5d18f6acc015c0f2d004 | [
"MIT"
]
| 1 | 2020-08-15T22:53:43.000Z | 2020-08-15T22:53:43.000Z | classes/UtilCommon.pas | DanScottNI/delphi-romhacklib | 8b8e18b32a156a20530f5d18f6acc015c0f2d004 | [
"MIT"
]
| null | null | null | classes/UtilCommon.pas | DanScottNI/delphi-romhacklib | 8b8e18b32a156a20530f5d18f6acc015c0f2d004 | [
"MIT"
]
| null | null | null | unit UtilCommon;
interface
uses classes,ComCtrls;
procedure ListViewToCSV(var pListView : TListView;var pStringList : TStringList; pFilename : String);
implementation
procedure ListViewToCSV(var pListView : TListView;var pStringList : TStringList; pFilename : String);
var
i,x : Integer;
stroutput : String;
begin
// First row of the CSV file, should match the column headings of the listview.
if pListView.ViewStyle = vsReport then
begin
for i:= 0 to pListView.Columns.Count-1 do
begin
if i > 0 then stroutput := stroutput + ',';
stroutput := stroutput + pListView.Columns[i].Caption;
end;
pStringList.Add(strOutput);
for i := 0 to pListView.Items.Count-1 do
begin
stroutput := pListView.Items[i].Caption;
if pListView.Items[i].SubItems.Count > 0 then
begin
for x := 0 to pListView.Items[i].SubItems.Count-1 do
begin
strOutput := stroutput + ',' + pListView.Items[i].SubItems[x];
end;
end;
pStringList.Add(strOutput);
end;
pStringList.SaveToFile(pFilename);
end;
end;
end.
| 22.673469 | 101 | 0.668767 |
4748b540150718df9f29690421772c6baae1c323 | 164,438 | pas | Pascal | reference-platform/dstu3/FHIROperations.pas | novakjf2000/FHIRServer | a47873825e94cd6cdfa1a077f02e0960098bbefa | [
"BSD-3-Clause"
]
| 1 | 2018-01-08T06:40:02.000Z | 2018-01-08T06:40:02.000Z | reference-platform/dstu3/FHIROperations.pas | novakjf2000/FHIRServer | a47873825e94cd6cdfa1a077f02e0960098bbefa | [
"BSD-3-Clause"
]
| null | null | null | reference-platform/dstu3/FHIROperations.pas | novakjf2000/FHIRServer | a47873825e94cd6cdfa1a077f02e0960098bbefa | [
"BSD-3-Clause"
]
| null | null | null | {!Wrapper uses FHIRBase, FHIRBase_Wrapper, FHIRTypes, FHIRTypes_Wrapper, DateSupport, DateSupport_Wrapper}
unit FHIROperations;
{$I fhir.inc}
{
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 FHIR3}
This is the dstu3 version of the FHIR code
{$ENDIF}
interface
// FHIR v3.0.1 generated 2017-04-27T17:09:41+10:00
uses
SysUtils, Classes, Generics.Collections, StringSupport, DecimalSupport, AdvBuffers, AdvGenerics, ParseMap, DateSupport, FHIRBase, FHIRTypes, FHIRResources, FHIROpBase;
Type
//Operation apply (Apply)
TFHIRApplyOpRequest = class (TFHIROperationRequest)
private
FPatient : TFhirReference;
FEncounter : TFhirReference;
FPractitioner : TFhirReference;
FOrganization : TFhirReference;
FUserType : TFhirCodeableConcept;
FUserLanguage : TFhirCodeableConcept;
FUserTaskContext : TFhirCodeableConcept;
FSetting : TFhirCodeableConcept;
FSettingContext : TFhirCodeableConcept;
procedure SetPatient(value : TFhirReference);
procedure SetEncounter(value : TFhirReference);
procedure SetPractitioner(value : TFhirReference);
procedure SetOrganization(value : TFhirReference);
procedure SetUserType(value : TFhirCodeableConcept);
procedure SetUserLanguage(value : TFhirCodeableConcept);
procedure SetUserTaskContext(value : TFhirCodeableConcept);
procedure SetSetting(value : TFhirCodeableConcept);
procedure SetSettingContext(value : TFhirCodeableConcept);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property patient : TFhirReference read FPatient write SetPatient;
property encounter : TFhirReference read FEncounter write SetEncounter;
property practitioner : TFhirReference read FPractitioner write SetPractitioner;
property organization : TFhirReference read FOrganization write SetOrganization;
property userType : TFhirCodeableConcept read FUserType write SetUserType;
property userLanguage : TFhirCodeableConcept read FUserLanguage write SetUserLanguage;
property userTaskContext : TFhirCodeableConcept read FUserTaskContext write SetUserTaskContext;
property setting : TFhirCodeableConcept read FSetting write SetSetting;
property settingContext : TFhirCodeableConcept read FSettingContext write SetSettingContext;
end;
TFHIRApplyOpResponse = class (TFHIROperationResponse)
private
FReturn : TFhirResource;
procedure SetReturn(value : TFhirResource);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property return : TFhirResource read FReturn write SetReturn;
end;
//Operation data-requirements (Data Requirements)
TFHIRDataRequirementsOpRequest = class (TFHIROperationRequest)
private
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
end;
TFHIRDataRequirementsOpResponse = class (TFHIROperationResponse)
private
FReturn : TFhirLibrary;
procedure SetReturn(value : TFhirLibrary);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property return : TFhirLibrary read FReturn write SetReturn;
end;
//Operation conforms (Test if a server implements a client's required operations)
TFHIRConformsOpRequest = class (TFHIROperationRequest)
private
FLeft : String;
FRight : String;
FMode : String;
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property left : String read FLeft write FLeft;
property right : String read FRight write FRight;
property mode : String read FMode write FMode;
end;
TFHIRConformsOpResponse = class (TFHIROperationResponse)
private
FIssues : TFhirOperationOutcome;
FUnion : TFhirCapabilityStatement;
FIntersection : TFhirCapabilityStatement;
procedure SetIssues(value : TFhirOperationOutcome);
procedure SetUnion(value : TFhirCapabilityStatement);
procedure SetIntersection(value : TFhirCapabilityStatement);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property issues : TFhirOperationOutcome read FIssues write SetIssues;
property union : TFhirCapabilityStatement read FUnion write SetUnion;
property intersection : TFhirCapabilityStatement read FIntersection write SetIntersection;
end;
//Operation implements (Test if a server implements a client's required operations)
TFHIRImplementsOpRequest = class (TFHIROperationRequest)
private
FServer : String;
FClient : String;
FResource : TFhirCapabilityStatement;
procedure SetResource(value : TFhirCapabilityStatement);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property server : String read FServer write FServer;
property client : String read FClient write FClient;
property resource : TFhirCapabilityStatement read FResource write SetResource;
end;
TFHIRImplementsOpResponse = class (TFHIROperationResponse)
private
FReturn : TFhirOperationOutcome;
procedure SetReturn(value : TFhirOperationOutcome);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property return : TFhirOperationOutcome read FReturn write SetReturn;
end;
//Operation subset (Fetch a subset of the CapabilityStatement resource)
TFHIRSubsetOpRequest = class (TFHIROperationRequest)
private
FServer : String;
FResourceList : TList<String>;
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property server : String read FServer write FServer;
property resourceList : TList<String> read FResourceList;
end;
TFHIRSubsetOpResponse = class (TFHIROperationResponse)
private
FReturn : TFhirCapabilityStatement;
procedure SetReturn(value : TFhirCapabilityStatement);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property return : TFhirCapabilityStatement read FReturn write SetReturn;
end;
//Operation compose (Code Composition based on supplied properties)
TFHIRComposeOpReqSubproperty = class (TFHIROperationObject)
private
FCode : String;
FValue : String;
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
constructor Create(params : TFhirParametersParameter); overload; override;
destructor Destroy; override;
function asParams(name : String) : TFHIRParametersParameter; override;
property code : String read FCode write FCode;
property value : String read FValue write FValue;
end;
TFHIRComposeOpReqProperty_ = class (TFHIROperationObject)
private
FCode : String;
FValue : String;
FSubpropertyList : TAdvList<TFHIRComposeOpReqSubproperty>;
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
constructor Create(params : TFhirParametersParameter); overload; override;
destructor Destroy; override;
function asParams(name : String) : TFHIRParametersParameter; override;
property code : String read FCode write FCode;
property value : String read FValue write FValue;
property subpropertyList : TAdvList<TFHIRComposeOpReqSubproperty> read FSubpropertyList;
end;
TFHIRComposeOpRequest = class (TFHIROperationRequest)
private
FSystem : String;
FVersion : String;
FProperty_List : TAdvList<TFHIRComposeOpReqProperty_>;
FExact : Boolean;
FCompositional : Boolean;
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property system : String read FSystem write FSystem;
property version : String read FVersion write FVersion;
property property_List : TAdvList<TFHIRComposeOpReqProperty_> read FProperty_List;
property exact : Boolean read FExact write FExact;
property compositional : Boolean read FCompositional write FCompositional;
end;
TFHIRComposeOpRespProperty_ = class (TFHIROperationObject)
private
FCode : String;
FValue : String;
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
constructor Create(params : TFhirParametersParameter); overload; override;
destructor Destroy; override;
function asParams(name : String) : TFHIRParametersParameter; override;
property code : String read FCode write FCode;
property value : String read FValue write FValue;
end;
TFHIRComposeOpRespUnmatched = class (TFHIROperationObject)
private
FCode : String;
FValue : String;
FProperty_List : TAdvList<TFHIRComposeOpRespProperty_>;
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
constructor Create(params : TFhirParametersParameter); overload; override;
destructor Destroy; override;
function asParams(name : String) : TFHIRParametersParameter; override;
property code : String read FCode write FCode;
property value : String read FValue write FValue;
property property_List : TAdvList<TFHIRComposeOpRespProperty_> read FProperty_List;
end;
TFHIRComposeOpRespMatch = class (TFHIROperationObject)
private
FCode : TFhirCoding;
FUnmatchedList : TAdvList<TFHIRComposeOpRespUnmatched>;
FComment : String;
procedure SetCode(value : TFhirCoding);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
constructor Create(params : TFhirParametersParameter); overload; override;
destructor Destroy; override;
function asParams(name : String) : TFHIRParametersParameter; override;
property code : TFhirCoding read FCode write SetCode;
property unmatchedList : TAdvList<TFHIRComposeOpRespUnmatched> read FUnmatchedList;
property comment : String read FComment write FComment;
end;
TFHIRComposeOpResponse = class (TFHIROperationResponse)
private
FMatchList : TAdvList<TFHIRComposeOpRespMatch>;
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property matchList : TAdvList<TFHIRComposeOpRespMatch> read FMatchList;
end;
//Operation lookup (Concept Look Up & Decomposition)
TFHIRLookupOpRequest = class (TFHIROperationRequest)
private
FCode : String;
FSystem : String;
FVersion : String;
FCoding : TFhirCoding;
FDate : TDateTimeEx;
FDisplayLanguage : String;
FProperty_List : TList<String>;
procedure SetCoding(value : TFhirCoding);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property code : String read FCode write FCode;
property system : String read FSystem write FSystem;
property version : String read FVersion write FVersion;
property coding : TFhirCoding read FCoding write SetCoding;
property date : TDateTimeEx read FDate write FDate;
property displayLanguage : String read FDisplayLanguage write FDisplayLanguage;
property property_List : TList<String> read FProperty_List;
end;
TFHIRLookupOpRespDesignation = class (TFHIROperationObject)
private
FLanguage : String;
FUse : TFhirCoding;
FValue : String;
procedure SetUse(value : TFhirCoding);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
constructor Create(params : TFhirParametersParameter); overload; override;
destructor Destroy; override;
function asParams(name : String) : TFHIRParametersParameter; override;
property language : String read FLanguage write FLanguage;
property use : TFhirCoding read FUse write SetUse;
property value : String read FValue write FValue;
end;
TFHIRLookupOpRespSubproperty = class (TFHIROperationObject)
private
FCode : String;
FValue : String;
FDescription : String;
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
constructor Create(params : TFhirParametersParameter); overload; override;
destructor Destroy; override;
function asParams(name : String) : TFHIRParametersParameter; override;
property code : String read FCode write FCode;
property value : String read FValue write FValue;
property description : String read FDescription write FDescription;
end;
TFHIRLookupOpRespProperty_ = class (TFHIROperationObject)
private
FCode : String;
FValue : String;
FDescription : String;
FSubpropertyList : TAdvList<TFHIRLookupOpRespSubproperty>;
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
constructor Create(params : TFhirParametersParameter); overload; override;
destructor Destroy; override;
function asParams(name : String) : TFHIRParametersParameter; override;
property code : String read FCode write FCode;
property value : String read FValue write FValue;
property description : String read FDescription write FDescription;
property subpropertyList : TAdvList<TFHIRLookupOpRespSubproperty> read FSubpropertyList;
end;
TFHIRLookupOpResponse = class (TFHIROperationResponse)
private
FName : String;
FVersion : String;
FDisplay : String;
FDesignationList : TAdvList<TFHIRLookupOpRespDesignation>;
FProperty_List : TAdvList<TFHIRLookupOpRespProperty_>;
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property name : String read FName write FName;
property version : String read FVersion write FVersion;
property display : String read FDisplay write FDisplay;
property designationList : TAdvList<TFHIRLookupOpRespDesignation> read FDesignationList;
property property_List : TAdvList<TFHIRLookupOpRespProperty_> read FProperty_List;
end;
//Operation subsumes (Subsumption Testing)
TFHIRSubsumesOpRequest = class (TFHIROperationRequest)
private
FCodeA : String;
FCodeB : String;
FSystem : String;
FVersion : String;
FCodingA : TFhirCoding;
FCodingB : TFhirCoding;
procedure SetCodingA(value : TFhirCoding);
procedure SetCodingB(value : TFhirCoding);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property codeA : String read FCodeA write FCodeA;
property codeB : String read FCodeB write FCodeB;
property system : String read FSystem write FSystem;
property version : String read FVersion write FVersion;
property codingA : TFhirCoding read FCodingA write SetCodingA;
property codingB : TFhirCoding read FCodingB write SetCodingB;
end;
TFHIRSubsumesOpResponse = class (TFHIROperationResponse)
private
FOutcome : String;
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property outcome : String read FOutcome write FOutcome;
end;
//Operation document (Generate a Document)
TFHIRDocumentOpRequest = class (TFHIROperationRequest)
private
FPersist : Boolean;
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property persist : Boolean read FPersist write FPersist;
end;
TFHIRDocumentOpResponse = class (TFHIROperationResponse)
private
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
end;
//Operation closure (Closure Table Maintenance)
TFHIRClosureOpRequest = class (TFHIROperationRequest)
private
FName : String;
FConceptList : TAdvList<TFhirCoding>;
FVersion : String;
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property name : String read FName write FName;
property conceptList : TAdvList<TFhirCoding> read FConceptList;
property version : String read FVersion write FVersion;
end;
TFHIRClosureOpResponse = class (TFHIROperationResponse)
private
FReturn : TFhirConceptMap;
procedure SetReturn(value : TFhirConceptMap);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property return : TFhirConceptMap read FReturn write SetReturn;
end;
//Operation translate (Concept Translation)
TFHIRTranslateOpReqDependency = class (TFHIROperationObject)
private
FElement : String;
FConcept : TFhirCodeableConcept;
procedure SetConcept(value : TFhirCodeableConcept);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
constructor Create(params : TFhirParametersParameter); overload; override;
destructor Destroy; override;
function asParams(name : String) : TFHIRParametersParameter; override;
property element : String read FElement write FElement;
property concept : TFhirCodeableConcept read FConcept write SetConcept;
end;
TFHIRTranslateOpRequest = class (TFHIROperationRequest)
private
FCode : String;
FSystem : String;
FVersion : String;
FSource : String;
FCoding : TFhirCoding;
FCodeableConcept : TFhirCodeableConcept;
FTarget : String;
FTargetsystem : String;
FDependencyList : TAdvList<TFHIRTranslateOpReqDependency>;
FReverse : Boolean;
procedure SetCoding(value : TFhirCoding);
procedure SetCodeableConcept(value : TFhirCodeableConcept);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property code : String read FCode write FCode;
property system : String read FSystem write FSystem;
property version : String read FVersion write FVersion;
property source : String read FSource write FSource;
property coding : TFhirCoding read FCoding write SetCoding;
property codeableConcept : TFhirCodeableConcept read FCodeableConcept write SetCodeableConcept;
property target : String read FTarget write FTarget;
property targetsystem : String read FTargetsystem write FTargetsystem;
property dependencyList : TAdvList<TFHIRTranslateOpReqDependency> read FDependencyList;
property reverse : Boolean read FReverse write FReverse;
end;
TFHIRTranslateOpRespProduct = class (TFHIROperationObject)
private
FElement : String;
FConcept : TFhirCoding;
procedure SetConcept(value : TFhirCoding);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
constructor Create(params : TFhirParametersParameter); overload; override;
destructor Destroy; override;
function asParams(name : String) : TFHIRParametersParameter; override;
property element : String read FElement write FElement;
property concept : TFhirCoding read FConcept write SetConcept;
end;
TFHIRTranslateOpRespMatch = class (TFHIROperationObject)
private
FEquivalence : String;
FConcept : TFhirCoding;
FProductList : TAdvList<TFHIRTranslateOpRespProduct>;
FSource : String;
procedure SetConcept(value : TFhirCoding);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
constructor Create(params : TFhirParametersParameter); overload; override;
destructor Destroy; override;
function asParams(name : String) : TFHIRParametersParameter; override;
property equivalence : String read FEquivalence write FEquivalence;
property concept : TFhirCoding read FConcept write SetConcept;
property productList : TAdvList<TFHIRTranslateOpRespProduct> read FProductList;
property source : String read FSource write FSource;
end;
TFHIRTranslateOpResponse = class (TFHIROperationResponse)
private
FResult : Boolean;
FMessage : String;
FMatchList : TAdvList<TFHIRTranslateOpRespMatch>;
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property result : Boolean read FResult write FResult;
property message : String read FMessage write FMessage;
property matchList : TAdvList<TFHIRTranslateOpRespMatch> read FMatchList;
end;
//Operation everything (Fetch Encounter Record)
TFHIREverythingOpRequest = class (TFHIROperationRequest)
private
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
end;
TFHIREverythingOpResponse = class (TFHIROperationResponse)
private
FReturn : TFhirBundle;
procedure SetReturn(value : TFhirBundle);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property return : TFhirBundle read FReturn write SetReturn;
end;
//Operation find (Find a functional list)
TFHIRFindOpRequest = class (TFHIROperationRequest)
private
FPatient : String;
FName : String;
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property patient : String read FPatient write FPatient;
property name : String read FName write FName;
end;
TFHIRFindOpResponse = class (TFHIROperationResponse)
private
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
end;
//Operation evaluate-measure (Evaluate Measure)
TFHIREvaluateMeasureOpRequest = class (TFHIROperationRequest)
private
FPeriodStart : TDateTimeEx;
FPeriodEnd : TDateTimeEx;
FMeasure : TFhirReference;
FReportType : String;
FPatient : TFhirReference;
FPractitioner : TFhirReference;
FLastReceivedOn : TDateTimeEx;
procedure SetMeasure(value : TFhirReference);
procedure SetPatient(value : TFhirReference);
procedure SetPractitioner(value : TFhirReference);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property periodStart : TDateTimeEx read FPeriodStart write FPeriodStart;
property periodEnd : TDateTimeEx read FPeriodEnd write FPeriodEnd;
property measure : TFhirReference read FMeasure write SetMeasure;
property reportType : String read FReportType write FReportType;
property patient : TFhirReference read FPatient write SetPatient;
property practitioner : TFhirReference read FPractitioner write SetPractitioner;
property lastReceivedOn : TDateTimeEx read FLastReceivedOn write FLastReceivedOn;
end;
TFHIREvaluateMeasureOpResponse = class (TFHIROperationResponse)
private
FReturn : TFhirMeasureReport;
procedure SetReturn(value : TFhirMeasureReport);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property return : TFhirMeasureReport read FReturn write SetReturn;
end;
//Operation process-message (Process Message)
TFHIRProcessMessageOpRequest = class (TFHIROperationRequest)
private
FContent : TFhirBundle;
FAsync : Boolean;
FResponseUrl : String;
procedure SetContent(value : TFhirBundle);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property content : TFhirBundle read FContent write SetContent;
property async : Boolean read FAsync write FAsync;
property responseUrl : String read FResponseUrl write FResponseUrl;
end;
TFHIRProcessMessageOpResponse = class (TFHIROperationResponse)
private
FReturn : TFhirBundle;
procedure SetReturn(value : TFhirBundle);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property return : TFhirBundle read FReturn write SetReturn;
end;
//Operation lastn (Last N Observations Query)
TFHIRLastnOpRequest = class (TFHIROperationRequest)
private
FMax : String;
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property max : String read FMax write FMax;
end;
TFHIRLastnOpResponse = class (TFHIROperationResponse)
private
FReturn : TFhirBundle;
procedure SetReturn(value : TFhirBundle);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property return : TFhirBundle read FReturn write SetReturn;
end;
//Operation stats (Observation Statistics)
TFHIRStatsOpRequest = class (TFHIROperationRequest)
private
FSubject : String;
FCodeList : TList<String>;
FSystem : String;
FCodingList : TAdvList<TFhirCoding>;
FDuration : String;
FPeriod : TFhirPeriod;
FStatisticList : TList<String>;
FInclude : Boolean;
FLimit : String;
procedure SetPeriod(value : TFhirPeriod);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property subject : String read FSubject write FSubject;
property codeList : TList<String> read FCodeList;
property system : String read FSystem write FSystem;
property codingList : TAdvList<TFhirCoding> read FCodingList;
property duration : String read FDuration write FDuration;
property period : TFhirPeriod read FPeriod write SetPeriod;
property statisticList : TList<String> read FStatisticList;
property include : Boolean read FInclude write FInclude;
property limit : String read FLimit write FLimit;
end;
TFHIRStatsOpResponse = class (TFHIROperationResponse)
private
FReturnList : TAdvList<TFhirObservation>;
FSourceList : TAdvList<TFhirObservation>;
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property returnList : TAdvList<TFhirObservation> read FReturnList;
property sourceList : TAdvList<TFhirObservation> read FSourceList;
end;
//Operation match (Find patient matches using MPI based logic)
TFHIRMatchOpRequest = class (TFHIROperationRequest)
private
FResource : TFhirResource;
FOnlyCertainMatches : Boolean;
FCount : String;
procedure SetResource(value : TFhirResource);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property resource : TFhirResource read FResource write SetResource;
property onlyCertainMatches : Boolean read FOnlyCertainMatches write FOnlyCertainMatches;
property count : String read FCount write FCount;
end;
TFHIRMatchOpResponse = class (TFHIROperationResponse)
private
FReturn : TFhirBundle;
procedure SetReturn(value : TFhirBundle);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property return : TFhirBundle read FReturn write SetReturn;
end;
//Operation populate (Populate Questionnaire)
TFHIRPopulateOpRequest = class (TFHIROperationRequest)
private
FIdentifier : String;
FQuestionnaire : TFhirQuestionnaire;
FQuestionnaireRef : TFhirReference;
FSubject : TFhirReference;
FContentList : TAdvList<TFhirReference>;
FLocal : Boolean;
procedure SetQuestionnaire(value : TFhirQuestionnaire);
procedure SetQuestionnaireRef(value : TFhirReference);
procedure SetSubject(value : TFhirReference);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property identifier : String read FIdentifier write FIdentifier;
property questionnaire : TFhirQuestionnaire read FQuestionnaire write SetQuestionnaire;
property questionnaireRef : TFhirReference read FQuestionnaireRef write SetQuestionnaireRef;
property subject : TFhirReference read FSubject write SetSubject;
property contentList : TAdvList<TFhirReference> read FContentList;
property local : Boolean read FLocal write FLocal;
end;
TFHIRPopulateOpResponse = class (TFHIROperationResponse)
private
FQuestionnaire : TFhirQuestionnaireResponse;
FIssues : TFhirOperationOutcome;
procedure SetQuestionnaire(value : TFhirQuestionnaireResponse);
procedure SetIssues(value : TFhirOperationOutcome);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property questionnaire : TFhirQuestionnaireResponse read FQuestionnaire write SetQuestionnaire;
property issues : TFhirOperationOutcome read FIssues write SetIssues;
end;
//Operation populatehtml (Generate HTML for Questionnaire)
TFHIRPopulatehtmlOpRequest = class (TFHIROperationRequest)
private
FIdentifier : String;
FQuestionnaire : TFhirQuestionnaire;
FQuestionnaireRef : TFhirReference;
FContentList : TAdvList<TFhirReference>;
FLocal : Boolean;
procedure SetQuestionnaire(value : TFhirQuestionnaire);
procedure SetQuestionnaireRef(value : TFhirReference);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property identifier : String read FIdentifier write FIdentifier;
property questionnaire : TFhirQuestionnaire read FQuestionnaire write SetQuestionnaire;
property questionnaireRef : TFhirReference read FQuestionnaireRef write SetQuestionnaireRef;
property contentList : TAdvList<TFhirReference> read FContentList;
property local : Boolean read FLocal write FLocal;
end;
TFHIRPopulatehtmlOpResponse = class (TFHIROperationResponse)
private
FForm : TFhirBinary;
FIssues : TFhirOperationOutcome;
procedure SetForm(value : TFhirBinary);
procedure SetIssues(value : TFhirOperationOutcome);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property form : TFhirBinary read FForm write SetForm;
property issues : TFhirOperationOutcome read FIssues write SetIssues;
end;
//Operation populatelink (Generate a link to a Questionnaire completion webpage)
TFHIRPopulatelinkOpRequest = class (TFHIROperationRequest)
private
FIdentifier : String;
FQuestionnaire : TFhirQuestionnaire;
FQuestionnaireRef : TFhirReference;
FContentList : TAdvList<TFhirReference>;
FLocal : Boolean;
procedure SetQuestionnaire(value : TFhirQuestionnaire);
procedure SetQuestionnaireRef(value : TFhirReference);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property identifier : String read FIdentifier write FIdentifier;
property questionnaire : TFhirQuestionnaire read FQuestionnaire write SetQuestionnaire;
property questionnaireRef : TFhirReference read FQuestionnaireRef write SetQuestionnaireRef;
property contentList : TAdvList<TFhirReference> read FContentList;
property local : Boolean read FLocal write FLocal;
end;
TFHIRPopulatelinkOpResponse = class (TFHIROperationResponse)
private
FLink_ : String;
FIssues : TFhirOperationOutcome;
procedure SetIssues(value : TFhirOperationOutcome);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property link_ : String read FLink_ write FLink_;
property issues : TFhirOperationOutcome read FIssues write SetIssues;
end;
//Operation meta (Access a list of profiles, tags, and security labels)
TFHIRMetaOpRequest = class (TFHIROperationRequest)
private
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
end;
TFHIRMetaOpResponse = class (TFHIROperationResponse)
private
FReturn : TFhirMeta;
procedure SetReturn(value : TFhirMeta);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property return : TFhirMeta read FReturn write SetReturn;
end;
//Operation meta-add (Add profiles, tags, and security labels to a resource)
TFHIRMetaAddOpRequest = class (TFHIROperationRequest)
private
FMeta : TFhirMeta;
procedure SetMeta(value : TFhirMeta);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property meta : TFhirMeta read FMeta write SetMeta;
end;
TFHIRMetaAddOpResponse = class (TFHIROperationResponse)
private
FReturn : TFhirMeta;
procedure SetReturn(value : TFhirMeta);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property return : TFhirMeta read FReturn write SetReturn;
end;
//Operation meta-delete (Delete profiles, tags, and security labels for a resource)
TFHIRMetaDeleteOpRequest = class (TFHIROperationRequest)
private
FMeta : TFhirMeta;
procedure SetMeta(value : TFhirMeta);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property meta : TFhirMeta read FMeta write SetMeta;
end;
TFHIRMetaDeleteOpResponse = class (TFHIROperationResponse)
private
FReturn : TFhirMeta;
procedure SetReturn(value : TFhirMeta);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property return : TFhirMeta read FReturn write SetReturn;
end;
//Operation validate (Validate a resource)
TFHIRValidateOpRequest = class (TFHIROperationRequest)
private
FResource : TFhirResource;
FMode : String;
FProfile : String;
procedure SetResource(value : TFhirResource);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property resource : TFhirResource read FResource write SetResource;
property mode : String read FMode write FMode;
property profile : String read FProfile write FProfile;
end;
TFHIRValidateOpResponse = class (TFHIROperationResponse)
private
FReturn : TFhirOperationOutcome;
procedure SetReturn(value : TFhirOperationOutcome);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property return : TFhirOperationOutcome read FReturn write SetReturn;
end;
//Operation evaluate (Evaluate)
TFHIREvaluateOpRequest = class (TFHIROperationRequest)
private
FRequestId : String;
FEvaluateAtDateTime : TDateTimeEx;
FInputParameters : TFhirParameters;
FInputDataList : TAdvList<TFhirResource>;
FPatient : TFhirReference;
FEncounter : TFhirReference;
FInitiatingOrganization : TFhirReference;
FInitiatingPerson : TFhirReference;
FUserType : TFhirCodeableConcept;
FUserLanguage : TFhirCodeableConcept;
FUserTaskContext : TFhirCodeableConcept;
FReceivingOrganization : TFhirReference;
FReceivingPerson : TFhirReference;
FRecipientType : TFhirCodeableConcept;
FRecipientLanguage : TFhirCodeableConcept;
FSetting : TFhirCodeableConcept;
FSettingContext : TFhirCodeableConcept;
procedure SetInputParameters(value : TFhirParameters);
procedure SetPatient(value : TFhirReference);
procedure SetEncounter(value : TFhirReference);
procedure SetInitiatingOrganization(value : TFhirReference);
procedure SetInitiatingPerson(value : TFhirReference);
procedure SetUserType(value : TFhirCodeableConcept);
procedure SetUserLanguage(value : TFhirCodeableConcept);
procedure SetUserTaskContext(value : TFhirCodeableConcept);
procedure SetReceivingOrganization(value : TFhirReference);
procedure SetReceivingPerson(value : TFhirReference);
procedure SetRecipientType(value : TFhirCodeableConcept);
procedure SetRecipientLanguage(value : TFhirCodeableConcept);
procedure SetSetting(value : TFhirCodeableConcept);
procedure SetSettingContext(value : TFhirCodeableConcept);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property requestId : String read FRequestId write FRequestId;
property evaluateAtDateTime : TDateTimeEx read FEvaluateAtDateTime write FEvaluateAtDateTime;
property inputParameters : TFhirParameters read FInputParameters write SetInputParameters;
property inputDataList : TAdvList<TFhirResource> read FInputDataList;
property patient : TFhirReference read FPatient write SetPatient;
property encounter : TFhirReference read FEncounter write SetEncounter;
property initiatingOrganization : TFhirReference read FInitiatingOrganization write SetInitiatingOrganization;
property initiatingPerson : TFhirReference read FInitiatingPerson write SetInitiatingPerson;
property userType : TFhirCodeableConcept read FUserType write SetUserType;
property userLanguage : TFhirCodeableConcept read FUserLanguage write SetUserLanguage;
property userTaskContext : TFhirCodeableConcept read FUserTaskContext write SetUserTaskContext;
property receivingOrganization : TFhirReference read FReceivingOrganization write SetReceivingOrganization;
property receivingPerson : TFhirReference read FReceivingPerson write SetReceivingPerson;
property recipientType : TFhirCodeableConcept read FRecipientType write SetRecipientType;
property recipientLanguage : TFhirCodeableConcept read FRecipientLanguage write SetRecipientLanguage;
property setting : TFhirCodeableConcept read FSetting write SetSetting;
property settingContext : TFhirCodeableConcept read FSettingContext write SetSettingContext;
end;
TFHIREvaluateOpResponse = class (TFHIROperationResponse)
private
FReturn : TFhirGuidanceResponse;
procedure SetReturn(value : TFhirGuidanceResponse);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property return : TFhirGuidanceResponse read FReturn write SetReturn;
end;
//Operation questionnaire (Build Questionnaire)
TFHIRQuestionnaireOpRequest = class (TFHIROperationRequest)
private
FIdentifier : String;
FProfile : String;
FUrl : String;
FSupportedOnly : Boolean;
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property identifier : String read FIdentifier write FIdentifier;
property profile : String read FProfile write FProfile;
property url : String read FUrl write FUrl;
property supportedOnly : Boolean read FSupportedOnly write FSupportedOnly;
end;
TFHIRQuestionnaireOpResponse = class (TFHIROperationResponse)
private
FReturn : TFhirQuestionnaire;
procedure SetReturn(value : TFhirQuestionnaire);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property return : TFhirQuestionnaire read FReturn write SetReturn;
end;
//Operation transform (Model Instance Transformation)
TFHIRTransformOpRequest = class (TFHIROperationRequest)
private
FSource : String;
FContent : TFhirResource;
procedure SetContent(value : TFhirResource);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property source : String read FSource write FSource;
property content : TFhirResource read FContent write SetContent;
end;
TFHIRTransformOpResponse = class (TFHIROperationResponse)
private
FReturn : TFhirResource;
procedure SetReturn(value : TFhirResource);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property return : TFhirResource read FReturn write SetReturn;
end;
//Operation expand (Value Set Expansion)
TFHIRExpandOpRequest = class (TFHIROperationRequest)
private
FUrl : String;
FValueSet : TFhirValueSet;
FContext : String;
FFilter : String;
FProfile : String;
FDate : TDateTimeEx;
FOffset : String;
FCount : String;
FIncludeDesignations : Boolean;
FIncludeDefinition : Boolean;
FActiveOnly : Boolean;
FExcludeNested : Boolean;
FExcludeNotForUI : Boolean;
FExcludePostCoordinated : Boolean;
FDisplayLanguage : String;
FLimitedExpansion : Boolean;
procedure SetValueSet(value : TFhirValueSet);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property url : String read FUrl write FUrl;
property valueSet : TFhirValueSet read FValueSet write SetValueSet;
property context : String read FContext write FContext;
property filter : String read FFilter write FFilter;
property profile : String read FProfile write FProfile;
property date : TDateTimeEx read FDate write FDate;
property offset : String read FOffset write FOffset;
property count : String read FCount write FCount;
property includeDesignations : Boolean read FIncludeDesignations write FIncludeDesignations;
property includeDefinition : Boolean read FIncludeDefinition write FIncludeDefinition;
property activeOnly : Boolean read FActiveOnly write FActiveOnly;
property excludeNested : Boolean read FExcludeNested write FExcludeNested;
property excludeNotForUI : Boolean read FExcludeNotForUI write FExcludeNotForUI;
property excludePostCoordinated : Boolean read FExcludePostCoordinated write FExcludePostCoordinated;
property displayLanguage : String read FDisplayLanguage write FDisplayLanguage;
property limitedExpansion : Boolean read FLimitedExpansion write FLimitedExpansion;
end;
TFHIRExpandOpResponse = class (TFHIROperationResponse)
private
FReturn : TFhirValueSet;
procedure SetReturn(value : TFhirValueSet);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property return : TFhirValueSet read FReturn write SetReturn;
end;
//Operation validate-code (Value Set based Validation)
TFHIRValidateCodeOpRequest = class (TFHIROperationRequest)
private
FUrl : String;
FContext : String;
FValueSet : TFhirValueSet;
FCode : String;
FSystem : String;
FVersion : String;
FDisplay : String;
FCoding : TFhirCoding;
FCodeableConcept : TFhirCodeableConcept;
FDate : TDateTimeEx;
FAbstract : Boolean;
FDisplayLanguage : String;
procedure SetValueSet(value : TFhirValueSet);
procedure SetCoding(value : TFhirCoding);
procedure SetCodeableConcept(value : TFhirCodeableConcept);
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property url : String read FUrl write FUrl;
property context : String read FContext write FContext;
property valueSet : TFhirValueSet read FValueSet write SetValueSet;
property code : String read FCode write FCode;
property system : String read FSystem write FSystem;
property version : String read FVersion write FVersion;
property display : String read FDisplay write FDisplay;
property coding : TFhirCoding read FCoding write SetCoding;
property codeableConcept : TFhirCodeableConcept read FCodeableConcept write SetCodeableConcept;
property date : TDateTimeEx read FDate write FDate;
property abstract : Boolean read FAbstract write FAbstract;
property displayLanguage : String read FDisplayLanguage write FDisplayLanguage;
end;
TFHIRValidateCodeOpResponse = class (TFHIROperationResponse)
private
FResult : Boolean;
FMessage : String;
FDisplay : String;
protected
function isKnownName(name : String) : boolean; override;
public
constructor Create; overload; override;
destructor Destroy; override;
procedure load(params : TFHIRParameters); overload; override;
procedure load(params : TParseMap); overload; override;
function asParams : TFHIRParameters; override;
property result : Boolean read FResult write FResult;
property message : String read FMessage write FMessage;
property display : String read FDisplay write FDisplay;
end;
implementation
uses
FHIRUtilities;
procedure TFHIRApplyOpRequest.SetPatient(value : TFhirReference);
begin
FPatient.free;
FPatient := value;
end;
procedure TFHIRApplyOpRequest.SetEncounter(value : TFhirReference);
begin
FEncounter.free;
FEncounter := value;
end;
procedure TFHIRApplyOpRequest.SetPractitioner(value : TFhirReference);
begin
FPractitioner.free;
FPractitioner := value;
end;
procedure TFHIRApplyOpRequest.SetOrganization(value : TFhirReference);
begin
FOrganization.free;
FOrganization := value;
end;
procedure TFHIRApplyOpRequest.SetUserType(value : TFhirCodeableConcept);
begin
FUserType.free;
FUserType := value;
end;
procedure TFHIRApplyOpRequest.SetUserLanguage(value : TFhirCodeableConcept);
begin
FUserLanguage.free;
FUserLanguage := value;
end;
procedure TFHIRApplyOpRequest.SetUserTaskContext(value : TFhirCodeableConcept);
begin
FUserTaskContext.free;
FUserTaskContext := value;
end;
procedure TFHIRApplyOpRequest.SetSetting(value : TFhirCodeableConcept);
begin
FSetting.free;
FSetting := value;
end;
procedure TFHIRApplyOpRequest.SetSettingContext(value : TFhirCodeableConcept);
begin
FSettingContext.free;
FSettingContext := value;
end;
constructor TFHIRApplyOpRequest.create;
begin
inherited create();
end;
procedure TFHIRApplyOpRequest.load(params : TFHIRParameters);
begin
FPatient := (params.param['patient'].value as TFhirReference).Link; {ob.5d}
FEncounter := (params.param['encounter'].value as TFhirReference).Link; {ob.5d}
FPractitioner := (params.param['practitioner'].value as TFhirReference).Link; {ob.5d}
FOrganization := (params.param['organization'].value as TFhirReference).Link; {ob.5d}
FUserType := (params.param['userType'].value as TFhirCodeableConcept).Link; {ob.5d}
FUserLanguage := (params.param['userLanguage'].value as TFhirCodeableConcept).Link; {ob.5d}
FUserTaskContext := (params.param['userTaskContext'].value as TFhirCodeableConcept).Link; {ob.5d}
FSetting := (params.param['setting'].value as TFhirCodeableConcept).Link; {ob.5d}
FSettingContext := (params.param['settingContext'].value as TFhirCodeableConcept).Link; {ob.5d}
loadExtensions(params);
end;
procedure TFHIRApplyOpRequest.load(params : TParseMap);
begin
loadExtensions(params);
end;
destructor TFHIRApplyOpRequest.Destroy;
begin
FPatient.free;
FEncounter.free;
FPractitioner.free;
FOrganization.free;
FUserType.free;
FUserLanguage.free;
FUserTaskContext.free;
FSetting.free;
FSettingContext.free;
inherited;
end;
function TFHIRApplyOpRequest.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FPatient <> nil) then
result.addParameter('patient', FPatient.Link);{oz.5d}
if (FEncounter <> nil) then
result.addParameter('encounter', FEncounter.Link);{oz.5d}
if (FPractitioner <> nil) then
result.addParameter('practitioner', FPractitioner.Link);{oz.5d}
if (FOrganization <> nil) then
result.addParameter('organization', FOrganization.Link);{oz.5d}
if (FUserType <> nil) then
result.addParameter('userType', FUserType.Link);{oz.5d}
if (FUserLanguage <> nil) then
result.addParameter('userLanguage', FUserLanguage.Link);{oz.5d}
if (FUserTaskContext <> nil) then
result.addParameter('userTaskContext', FUserTaskContext.Link);{oz.5d}
if (FSetting <> nil) then
result.addParameter('setting', FSetting.Link);{oz.5d}
if (FSettingContext <> nil) then
result.addParameter('settingContext', FSettingContext.Link);{oz.5d}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRApplyOpRequest.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['patient', 'encounter', 'practitioner', 'organization', 'userType', 'userLanguage', 'userTaskContext', 'setting', 'settingContext'], name);
end;
procedure TFHIRApplyOpResponse.SetReturn(value : TFhirResource);
begin
FReturn.free;
FReturn := value;
end;
constructor TFHIRApplyOpResponse.create;
begin
inherited create();
end;
procedure TFHIRApplyOpResponse.load(params : TFHIRParameters);
begin
FReturn := (params.res['return'] as TFhirResource).Link;{ob.5a}
loadExtensions(params);
end;
procedure TFHIRApplyOpResponse.load(params : TParseMap);
begin
loadExtensions(params);
end;
destructor TFHIRApplyOpResponse.Destroy;
begin
FReturn.free;
inherited;
end;
function TFHIRApplyOpResponse.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FReturn <> nil) then
result.addParameter('return', FReturn.Link);{oz.5a}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRApplyOpResponse.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['return'], name);
end;
constructor TFHIRDataRequirementsOpRequest.create;
begin
inherited create();
end;
procedure TFHIRDataRequirementsOpRequest.load(params : TFHIRParameters);
begin
loadExtensions(params);
end;
procedure TFHIRDataRequirementsOpRequest.load(params : TParseMap);
begin
loadExtensions(params);
end;
destructor TFHIRDataRequirementsOpRequest.Destroy;
begin
inherited;
end;
function TFHIRDataRequirementsOpRequest.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRDataRequirementsOpRequest.isKnownName(name : String) : boolean;
begin
result := false;
end;
procedure TFHIRDataRequirementsOpResponse.SetReturn(value : TFhirLibrary);
begin
FReturn.free;
FReturn := value;
end;
constructor TFHIRDataRequirementsOpResponse.create;
begin
inherited create();
end;
procedure TFHIRDataRequirementsOpResponse.load(params : TFHIRParameters);
begin
FReturn := (params.res['return'] as TFhirLibrary).Link;{ob.5a}
loadExtensions(params);
end;
procedure TFHIRDataRequirementsOpResponse.load(params : TParseMap);
begin
loadExtensions(params);
end;
destructor TFHIRDataRequirementsOpResponse.Destroy;
begin
FReturn.free;
inherited;
end;
function TFHIRDataRequirementsOpResponse.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FReturn <> nil) then
result.addParameter('return', FReturn.Link);{oz.5a}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRDataRequirementsOpResponse.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['return'], name);
end;
constructor TFHIRConformsOpRequest.create;
begin
inherited create();
end;
procedure TFHIRConformsOpRequest.load(params : TFHIRParameters);
begin
FLeft := params.str['left'];
FRight := params.str['right'];
FMode := params.str['mode'];
loadExtensions(params);
end;
procedure TFHIRConformsOpRequest.load(params : TParseMap);
begin
FLeft := params.getVar('left');
FRight := params.getVar('right');
FMode := params.getVar('mode');
loadExtensions(params);
end;
destructor TFHIRConformsOpRequest.Destroy;
begin
inherited;
end;
function TFHIRConformsOpRequest.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FLeft <> '') then
result.addParameter('left', TFHIRUri.create(FLeft));{oz.5f}
if (FRight <> '') then
result.addParameter('right', TFHIRUri.create(FRight));{oz.5f}
if (FMode <> '') then
result.addParameter('mode', TFHIRCode.create(FMode));{oz.5f}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRConformsOpRequest.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['left', 'right', 'mode'], name);
end;
procedure TFHIRConformsOpResponse.SetIssues(value : TFhirOperationOutcome);
begin
FIssues.free;
FIssues := value;
end;
procedure TFHIRConformsOpResponse.SetUnion(value : TFhirCapabilityStatement);
begin
FUnion.free;
FUnion := value;
end;
procedure TFHIRConformsOpResponse.SetIntersection(value : TFhirCapabilityStatement);
begin
FIntersection.free;
FIntersection := value;
end;
constructor TFHIRConformsOpResponse.create;
begin
inherited create();
end;
procedure TFHIRConformsOpResponse.load(params : TFHIRParameters);
begin
FIssues := (params.res['issues'] as TFhirOperationOutcome).Link;{ob.5a}
FUnion := (params.res['union'] as TFhirCapabilityStatement).Link;{ob.5a}
FIntersection := (params.res['intersection'] as TFhirCapabilityStatement).Link;{ob.5a}
loadExtensions(params);
end;
procedure TFHIRConformsOpResponse.load(params : TParseMap);
begin
loadExtensions(params);
end;
destructor TFHIRConformsOpResponse.Destroy;
begin
FIssues.free;
FUnion.free;
FIntersection.free;
inherited;
end;
function TFHIRConformsOpResponse.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FIssues <> nil) then
result.addParameter('issues', FIssues.Link);{oz.5a}
if (FUnion <> nil) then
result.addParameter('union', FUnion.Link);{oz.5a}
if (FIntersection <> nil) then
result.addParameter('intersection', FIntersection.Link);{oz.5a}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRConformsOpResponse.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['issues', 'union', 'intersection'], name);
end;
procedure TFHIRImplementsOpRequest.SetResource(value : TFhirCapabilityStatement);
begin
FResource.free;
FResource := value;
end;
constructor TFHIRImplementsOpRequest.create;
begin
inherited create();
end;
procedure TFHIRImplementsOpRequest.load(params : TFHIRParameters);
begin
FServer := params.str['server'];
FClient := params.str['client'];
FResource := (params.res['resource'] as TFhirCapabilityStatement).Link;{ob.5a}
loadExtensions(params);
end;
procedure TFHIRImplementsOpRequest.load(params : TParseMap);
begin
FServer := params.getVar('server');
FClient := params.getVar('client');
loadExtensions(params);
end;
destructor TFHIRImplementsOpRequest.Destroy;
begin
FResource.free;
inherited;
end;
function TFHIRImplementsOpRequest.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FServer <> '') then
result.addParameter('server', TFHIRUri.create(FServer));{oz.5f}
if (FClient <> '') then
result.addParameter('client', TFHIRUri.create(FClient));{oz.5f}
if (FResource <> nil) then
result.addParameter('resource', FResource.Link);{oz.5a}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRImplementsOpRequest.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['server', 'client', 'resource'], name);
end;
procedure TFHIRImplementsOpResponse.SetReturn(value : TFhirOperationOutcome);
begin
FReturn.free;
FReturn := value;
end;
constructor TFHIRImplementsOpResponse.create;
begin
inherited create();
end;
procedure TFHIRImplementsOpResponse.load(params : TFHIRParameters);
begin
FReturn := (params.res['return'] as TFhirOperationOutcome).Link;{ob.5a}
loadExtensions(params);
end;
procedure TFHIRImplementsOpResponse.load(params : TParseMap);
begin
loadExtensions(params);
end;
destructor TFHIRImplementsOpResponse.Destroy;
begin
FReturn.free;
inherited;
end;
function TFHIRImplementsOpResponse.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FReturn <> nil) then
result.addParameter('return', FReturn.Link);{oz.5a}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRImplementsOpResponse.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['return'], name);
end;
constructor TFHIRSubsetOpRequest.create;
begin
inherited create();
FResourceList := TList<String>.create;
end;
procedure TFHIRSubsetOpRequest.load(params : TFHIRParameters);
var
p : TFhirParametersParameter;
begin
FServer := params.str['server'];
for p in params.parameterList do
if p.name = 'resource' then
FResourceList.Add((p.value as TFhirCode).value);{ob.1}
loadExtensions(params);
end;
procedure TFHIRSubsetOpRequest.load(params : TParseMap);
var
s : String;
begin
FServer := params.getVar('server');
for s in params.getVar('resource').Split([';']) do
FResourceList.add(s);
loadExtensions(params);
end;
destructor TFHIRSubsetOpRequest.Destroy;
begin
FResourceList.free;
inherited;
end;
function TFHIRSubsetOpRequest.asParams : TFhirParameters;
var
v1 : String;
begin
result := TFHIRParameters.create;
try
if (FServer <> '') then
result.addParameter('server', TFHIRUri.create(FServer));{oz.5f}
for v1 in FResourceList do
result.AddParameter('resource', TFhirCode.create(v1));
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRSubsetOpRequest.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['server', 'resource'], name);
end;
procedure TFHIRSubsetOpResponse.SetReturn(value : TFhirCapabilityStatement);
begin
FReturn.free;
FReturn := value;
end;
constructor TFHIRSubsetOpResponse.create;
begin
inherited create();
end;
procedure TFHIRSubsetOpResponse.load(params : TFHIRParameters);
begin
FReturn := (params.res['return'] as TFhirCapabilityStatement).Link;{ob.5a}
loadExtensions(params);
end;
procedure TFHIRSubsetOpResponse.load(params : TParseMap);
begin
loadExtensions(params);
end;
destructor TFHIRSubsetOpResponse.Destroy;
begin
FReturn.free;
inherited;
end;
function TFHIRSubsetOpResponse.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FReturn <> nil) then
result.addParameter('return', FReturn.Link);{oz.5a}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRSubsetOpResponse.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['return'], name);
end;
constructor TFHIRComposeOpReqSubproperty.create;
begin
inherited create();
end;
constructor TFHIRComposeOpReqSubproperty.create(params : TFhirParametersParameter);
begin
inherited create();
FCode := params.str['code'];
FValue := params.str['value'];
loadExtensions(params);
end;
destructor TFHIRComposeOpReqSubproperty.Destroy;
begin
inherited;
end;
function TFHIRComposeOpReqSubproperty.asParams(name : String) : TFhirParametersParameter;
begin
result := TFHIRParametersParameter.create;
try
result.name := name;
if (FCode <> '') then
result.addParameter('code', TFHIRCode.create(FCode));{oz.5f}
if (FValue <> '') then
result.addParameter('value', TFHIRCode.create(FValue));{oz.5f}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRComposeOpReqSubproperty.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['code', 'value'], name);
end;
constructor TFHIRComposeOpReqProperty_.create;
begin
inherited create();
FSubpropertyList := TAdvList<TFHIRComposeOpReqSubproperty>.create;
end;
constructor TFHIRComposeOpReqProperty_.create(params : TFhirParametersParameter);
var
p : TFhirParametersParameter;
begin
inherited create();
FSubpropertyList := TAdvList<TFHIRComposeOpReqSubproperty>.create;
FCode := params.str['code'];
FValue := params.str['value'];
for p in params.partList do
if p.name = 'subproperty' then
FSubpropertyList.Add(TFHIRComposeOpReqSubproperty.create(p));{a}
loadExtensions(params);
end;
destructor TFHIRComposeOpReqProperty_.Destroy;
begin
FSubpropertyList.free;
inherited;
end;
function TFHIRComposeOpReqProperty_.asParams(name : String) : TFhirParametersParameter;
var
v1 : TFHIRComposeOpReqSubproperty;
begin
result := TFHIRParametersParameter.create;
try
result.name := name;
if (FCode <> '') then
result.addParameter('code', TFHIRCode.create(FCode));{oz.5f}
if (FValue <> '') then
result.addParameter('value', TFHIRCode.create(FValue));{oz.5f}
for v1 in FSubpropertyList do
result.AddParameter(v1.asParams('subproperty'));
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRComposeOpReqProperty_.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['code', 'value', 'subproperty'], name);
end;
constructor TFHIRComposeOpRequest.create;
begin
inherited create();
FProperty_List := TAdvList<TFHIRComposeOpReqProperty_>.create;
end;
procedure TFHIRComposeOpRequest.load(params : TFHIRParameters);
var
p : TFhirParametersParameter;
begin
FSystem := params.str['system'];
FVersion := params.str['version'];
for p in params.parameterList do
if p.name = 'property' then
FProperty_List.Add(TFHIRComposeOpReqProperty_.create(p));{a}
FExact := params.bool['exact'];
FCompositional := params.bool['compositional'];
loadExtensions(params);
end;
procedure TFHIRComposeOpRequest.load(params : TParseMap);
begin
FSystem := params.getVar('system');
FVersion := params.getVar('version');
FExact := StrToBoolDef(params.getVar('exact'), false);
FCompositional := StrToBoolDef(params.getVar('compositional'), false);
loadExtensions(params);
end;
destructor TFHIRComposeOpRequest.Destroy;
begin
FProperty_List.free;
inherited;
end;
function TFHIRComposeOpRequest.asParams : TFhirParameters;
var
v1 : TFHIRComposeOpReqProperty_;
begin
result := TFHIRParameters.create;
try
if (FSystem <> '') then
result.addParameter('system', TFHIRUri.create(FSystem));{oz.5f}
if (FVersion <> '') then
result.addParameter('version', TFHIRString.create(FVersion));{oz.5f}
for v1 in FProperty_List do
result.AddParameter(v1.asParams('property'));
result.addParameter('exact', TFHIRBoolean.create(FExact));{oz.5f}
result.addParameter('compositional', TFHIRBoolean.create(FCompositional));{oz.5f}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRComposeOpRequest.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['system', 'version', 'property', 'exact', 'compositional'], name);
end;
procedure TFHIRComposeOpRespMatch.SetCode(value : TFhirCoding);
begin
FCode.free;
FCode := value;
end;
constructor TFHIRComposeOpRespProperty_.create;
begin
inherited create();
end;
constructor TFHIRComposeOpRespProperty_.create(params : TFhirParametersParameter);
begin
inherited create();
FCode := params.str['code'];
FValue := params.str['value'];
loadExtensions(params);
end;
destructor TFHIRComposeOpRespProperty_.Destroy;
begin
inherited;
end;
function TFHIRComposeOpRespProperty_.asParams(name : String) : TFhirParametersParameter;
begin
result := TFHIRParametersParameter.create;
try
result.name := name;
if (FCode <> '') then
result.addParameter('code', TFHIRCode.create(FCode));{oz.5f}
if (FValue <> '') then
result.addParameter('value', TFHIRCode.create(FValue));{oz.5f}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRComposeOpRespProperty_.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['code', 'value'], name);
end;
constructor TFHIRComposeOpRespUnmatched.create;
begin
inherited create();
FProperty_List := TAdvList<TFHIRComposeOpRespProperty_>.create;
end;
constructor TFHIRComposeOpRespUnmatched.create(params : TFhirParametersParameter);
var
p : TFhirParametersParameter;
begin
inherited create();
FProperty_List := TAdvList<TFHIRComposeOpRespProperty_>.create;
FCode := params.str['code'];
FValue := params.str['value'];
for p in params.partList do
if p.name = 'property' then
FProperty_List.Add(TFHIRComposeOpRespProperty_.create(p));{a}
loadExtensions(params);
end;
destructor TFHIRComposeOpRespUnmatched.Destroy;
begin
FProperty_List.free;
inherited;
end;
function TFHIRComposeOpRespUnmatched.asParams(name : String) : TFhirParametersParameter;
var
v1 : TFHIRComposeOpRespProperty_;
begin
result := TFHIRParametersParameter.create;
try
result.name := name;
if (FCode <> '') then
result.addParameter('code', TFHIRCode.create(FCode));{oz.5f}
if (FValue <> '') then
result.addParameter('value', TFHIRCode.create(FValue));{oz.5f}
for v1 in FProperty_List do
result.AddParameter(v1.asParams('property'));
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRComposeOpRespUnmatched.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['code', 'value', 'property'], name);
end;
constructor TFHIRComposeOpRespMatch.create;
begin
inherited create();
FUnmatchedList := TAdvList<TFHIRComposeOpRespUnmatched>.create;
end;
constructor TFHIRComposeOpRespMatch.create(params : TFhirParametersParameter);
var
p : TFhirParametersParameter;
begin
inherited create();
FUnmatchedList := TAdvList<TFHIRComposeOpRespUnmatched>.create;
FCode := (params.param['code'].value as TFhirCoding).Link; {ob.5d}
for p in params.partList do
if p.name = 'unmatched' then
FUnmatchedList.Add(TFHIRComposeOpRespUnmatched.create(p));{a}
FComment := params.str['comment'];
loadExtensions(params);
end;
destructor TFHIRComposeOpRespMatch.Destroy;
begin
FCode.free;
FUnmatchedList.free;
inherited;
end;
function TFHIRComposeOpRespMatch.asParams(name : String) : TFhirParametersParameter;
var
v1 : TFHIRComposeOpRespUnmatched;
begin
result := TFHIRParametersParameter.create;
try
result.name := name;
if (FCode <> nil) then
result.addParameter('code', FCode.Link);{oz.5d}
for v1 in FUnmatchedList do
result.AddParameter(v1.asParams('unmatched'));
if (FComment <> '') then
result.addParameter('comment', TFHIRString.create(FComment));{oz.5f}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRComposeOpRespMatch.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['code', 'unmatched', 'comment'], name);
end;
constructor TFHIRComposeOpResponse.create;
begin
inherited create();
FMatchList := TAdvList<TFHIRComposeOpRespMatch>.create;
end;
procedure TFHIRComposeOpResponse.load(params : TFHIRParameters);
var
p : TFhirParametersParameter;
begin
for p in params.parameterList do
if p.name = 'match' then
FMatchList.Add(TFHIRComposeOpRespMatch.create(p));{a}
loadExtensions(params);
end;
procedure TFHIRComposeOpResponse.load(params : TParseMap);
begin
loadExtensions(params);
end;
destructor TFHIRComposeOpResponse.Destroy;
begin
FMatchList.free;
inherited;
end;
function TFHIRComposeOpResponse.asParams : TFhirParameters;
var
v1 : TFHIRComposeOpRespMatch;
begin
result := TFHIRParameters.create;
try
for v1 in FMatchList do
result.AddParameter(v1.asParams('match'));
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRComposeOpResponse.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['match'], name);
end;
procedure TFHIRLookupOpRequest.SetCoding(value : TFhirCoding);
begin
FCoding.free;
FCoding := value;
end;
constructor TFHIRLookupOpRequest.create;
begin
inherited create();
FProperty_List := TList<String>.create;
end;
procedure TFHIRLookupOpRequest.load(params : TFHIRParameters);
var
p : TFhirParametersParameter;
begin
FCode := params.str['code'];
FSystem := params.str['system'];
FVersion := params.str['version'];
FCoding := (params.param['coding'].value as TFhirCoding).Link; {ob.5d}
FDate := TDateTimeEx.fromXml(params.str['date']);
FDisplayLanguage := params.str['displayLanguage'];
for p in params.parameterList do
if p.name = 'property' then
FProperty_List.Add((p.value as TFhirCode).value);{ob.1}
loadExtensions(params);
end;
procedure TFHIRLookupOpRequest.load(params : TParseMap);
var
s : String;
begin
FCode := params.getVar('code');
FSystem := params.getVar('system');
FVersion := params.getVar('version');
FDate := TDateTimeEx.fromXml(params.getVar('date'));
FDisplayLanguage := params.getVar('displayLanguage');
for s in params.getVar('property').Split([';']) do
FProperty_List.add(s);
loadExtensions(params);
end;
destructor TFHIRLookupOpRequest.Destroy;
begin
FCoding.free;
FProperty_List.free;
inherited;
end;
function TFHIRLookupOpRequest.asParams : TFhirParameters;
var
v1 : String;
begin
result := TFHIRParameters.create;
try
if (FCode <> '') then
result.addParameter('code', TFHIRCode.create(FCode));{oz.5f}
if (FSystem <> '') then
result.addParameter('system', TFHIRUri.create(FSystem));{oz.5f}
if (FVersion <> '') then
result.addParameter('version', TFHIRString.create(FVersion));{oz.5f}
if (FCoding <> nil) then
result.addParameter('coding', FCoding.Link);{oz.5d}
if (FDate.notNull) then
result.addParameter('date', TFHIRDateTime.create(FDate));{oz.5f}
if (FDisplayLanguage <> '') then
result.addParameter('displayLanguage', TFHIRCode.create(FDisplayLanguage));{oz.5f}
for v1 in FProperty_List do
result.AddParameter('property', TFhirCode.create(v1));
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRLookupOpRequest.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['code', 'system', 'version', 'coding', 'date', 'displayLanguage', 'property'], name);
end;
procedure TFHIRLookupOpRespDesignation.SetUse(value : TFhirCoding);
begin
FUse.free;
FUse := value;
end;
constructor TFHIRLookupOpRespDesignation.create;
begin
inherited create();
end;
constructor TFHIRLookupOpRespDesignation.create(params : TFhirParametersParameter);
begin
inherited create();
FLanguage := params.str['language'];
FUse := (params.param['use'].value as TFhirCoding).Link; {ob.5d}
FValue := params.str['value'];
loadExtensions(params);
end;
destructor TFHIRLookupOpRespDesignation.Destroy;
begin
FUse.free;
inherited;
end;
function TFHIRLookupOpRespDesignation.asParams(name : String) : TFhirParametersParameter;
begin
result := TFHIRParametersParameter.create;
try
result.name := name;
if (FLanguage <> '') then
result.addParameter('language', TFHIRCode.create(FLanguage));{oz.5f}
if (FUse <> nil) then
result.addParameter('use', FUse.Link);{oz.5d}
if (FValue <> '') then
result.addParameter('value', TFHIRString.create(FValue));{oz.5f}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRLookupOpRespDesignation.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['language', 'use', 'value'], name);
end;
constructor TFHIRLookupOpRespSubproperty.create;
begin
inherited create();
end;
constructor TFHIRLookupOpRespSubproperty.create(params : TFhirParametersParameter);
begin
inherited create();
FCode := params.str['code'];
FValue := params.str['value'];
FDescription := params.str['description'];
loadExtensions(params);
end;
destructor TFHIRLookupOpRespSubproperty.Destroy;
begin
inherited;
end;
function TFHIRLookupOpRespSubproperty.asParams(name : String) : TFhirParametersParameter;
begin
result := TFHIRParametersParameter.create;
try
result.name := name;
if (FCode <> '') then
result.addParameter('code', TFHIRCode.create(FCode));{oz.5f}
if (FValue <> '') then
result.addParameter('value', TFHIRCode.create(FValue));{oz.5f}
if (FDescription <> '') then
result.addParameter('description', TFHIRString.create(FDescription));{oz.5f}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRLookupOpRespSubproperty.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['code', 'value', 'description'], name);
end;
constructor TFHIRLookupOpRespProperty_.create;
begin
inherited create();
FSubpropertyList := TAdvList<TFHIRLookupOpRespSubproperty>.create;
end;
constructor TFHIRLookupOpRespProperty_.create(params : TFhirParametersParameter);
var
p : TFhirParametersParameter;
begin
inherited create();
FSubpropertyList := TAdvList<TFHIRLookupOpRespSubproperty>.create;
FCode := params.str['code'];
FValue := params.str['value'];
FDescription := params.str['description'];
for p in params.partList do
if p.name = 'subproperty' then
FSubpropertyList.Add(TFHIRLookupOpRespSubproperty.create(p));{a}
loadExtensions(params);
end;
destructor TFHIRLookupOpRespProperty_.Destroy;
begin
FSubpropertyList.free;
inherited;
end;
function TFHIRLookupOpRespProperty_.asParams(name : String) : TFhirParametersParameter;
var
v1 : TFHIRLookupOpRespSubproperty;
begin
result := TFHIRParametersParameter.create;
try
result.name := name;
if (FCode <> '') then
result.addParameter('code', TFHIRCode.create(FCode));{oz.5f}
if (FValue <> '') then
result.addParameter('value', TFHIRCode.create(FValue));{oz.5f}
if (FDescription <> '') then
result.addParameter('description', TFHIRString.create(FDescription));{oz.5f}
for v1 in FSubpropertyList do
result.AddParameter(v1.asParams('subproperty'));
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRLookupOpRespProperty_.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['code', 'value', 'description', 'subproperty'], name);
end;
constructor TFHIRLookupOpResponse.create;
begin
inherited create();
FDesignationList := TAdvList<TFHIRLookupOpRespDesignation>.create;
FProperty_List := TAdvList<TFHIRLookupOpRespProperty_>.create;
end;
procedure TFHIRLookupOpResponse.load(params : TFHIRParameters);
var
p : TFhirParametersParameter;
begin
FName := params.str['name'];
FVersion := params.str['version'];
FDisplay := params.str['display'];
for p in params.parameterList do
if p.name = 'designation' then
FDesignationList.Add(TFHIRLookupOpRespDesignation.create(p));{a}
for p in params.parameterList do
if p.name = 'property' then
FProperty_List.Add(TFHIRLookupOpRespProperty_.create(p));{a}
loadExtensions(params);
end;
procedure TFHIRLookupOpResponse.load(params : TParseMap);
begin
FName := params.getVar('name');
FVersion := params.getVar('version');
FDisplay := params.getVar('display');
loadExtensions(params);
end;
destructor TFHIRLookupOpResponse.Destroy;
begin
FDesignationList.free;
FProperty_List.free;
inherited;
end;
function TFHIRLookupOpResponse.asParams : TFhirParameters;
var
v1 : TFHIRLookupOpRespDesignation;
v2 : TFHIRLookupOpRespProperty_;
begin
result := TFHIRParameters.create;
try
if (FName <> '') then
result.addParameter('name', TFHIRString.create(FName));{oz.5f}
if (FVersion <> '') then
result.addParameter('version', TFHIRString.create(FVersion));{oz.5f}
if (FDisplay <> '') then
result.addParameter('display', TFHIRString.create(FDisplay));{oz.5f}
for v1 in FDesignationList do
result.AddParameter(v1.asParams('designation'));
for v2 in FProperty_List do
result.AddParameter(v2.asParams('property'));
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRLookupOpResponse.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['name', 'version', 'display', 'designation', 'property'], name);
end;
procedure TFHIRSubsumesOpRequest.SetCodingA(value : TFhirCoding);
begin
FCodingA.free;
FCodingA := value;
end;
procedure TFHIRSubsumesOpRequest.SetCodingB(value : TFhirCoding);
begin
FCodingB.free;
FCodingB := value;
end;
constructor TFHIRSubsumesOpRequest.create;
begin
inherited create();
end;
procedure TFHIRSubsumesOpRequest.load(params : TFHIRParameters);
begin
FCodeA := params.str['codeA'];
FCodeB := params.str['codeB'];
FSystem := params.str['system'];
FVersion := params.str['version'];
FCodingA := (params.param['codingA'].value as TFhirCoding).Link; {ob.5d}
FCodingB := (params.param['codingB'].value as TFhirCoding).Link; {ob.5d}
loadExtensions(params);
end;
procedure TFHIRSubsumesOpRequest.load(params : TParseMap);
begin
FCodeA := params.getVar('codeA');
FCodeB := params.getVar('codeB');
FSystem := params.getVar('system');
FVersion := params.getVar('version');
loadExtensions(params);
end;
destructor TFHIRSubsumesOpRequest.Destroy;
begin
FCodingA.free;
FCodingB.free;
inherited;
end;
function TFHIRSubsumesOpRequest.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FCodeA <> '') then
result.addParameter('codeA', TFHIRCode.create(FCodeA));{oz.5f}
if (FCodeB <> '') then
result.addParameter('codeB', TFHIRCode.create(FCodeB));{oz.5f}
if (FSystem <> '') then
result.addParameter('system', TFHIRUri.create(FSystem));{oz.5f}
if (FVersion <> '') then
result.addParameter('version', TFHIRString.create(FVersion));{oz.5f}
if (FCodingA <> nil) then
result.addParameter('codingA', FCodingA.Link);{oz.5d}
if (FCodingB <> nil) then
result.addParameter('codingB', FCodingB.Link);{oz.5d}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRSubsumesOpRequest.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['codeA', 'codeB', 'system', 'version', 'codingA', 'codingB'], name);
end;
constructor TFHIRSubsumesOpResponse.create;
begin
inherited create();
end;
procedure TFHIRSubsumesOpResponse.load(params : TFHIRParameters);
begin
FOutcome := params.str['outcome'];
loadExtensions(params);
end;
procedure TFHIRSubsumesOpResponse.load(params : TParseMap);
begin
FOutcome := params.getVar('outcome');
loadExtensions(params);
end;
destructor TFHIRSubsumesOpResponse.Destroy;
begin
inherited;
end;
function TFHIRSubsumesOpResponse.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FOutcome <> '') then
result.addParameter('outcome', TFHIRCode.create(FOutcome));{oz.5f}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRSubsumesOpResponse.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['outcome'], name);
end;
constructor TFHIRDocumentOpRequest.create;
begin
inherited create();
end;
procedure TFHIRDocumentOpRequest.load(params : TFHIRParameters);
begin
FPersist := params.bool['persist'];
loadExtensions(params);
end;
procedure TFHIRDocumentOpRequest.load(params : TParseMap);
begin
FPersist := StrToBoolDef(params.getVar('persist'), false);
loadExtensions(params);
end;
destructor TFHIRDocumentOpRequest.Destroy;
begin
inherited;
end;
function TFHIRDocumentOpRequest.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
result.addParameter('persist', TFHIRBoolean.create(FPersist));{oz.5f}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRDocumentOpRequest.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['persist'], name);
end;
constructor TFHIRDocumentOpResponse.create;
begin
inherited create();
end;
procedure TFHIRDocumentOpResponse.load(params : TFHIRParameters);
begin
loadExtensions(params);
end;
procedure TFHIRDocumentOpResponse.load(params : TParseMap);
begin
loadExtensions(params);
end;
destructor TFHIRDocumentOpResponse.Destroy;
begin
inherited;
end;
function TFHIRDocumentOpResponse.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRDocumentOpResponse.isKnownName(name : String) : boolean;
begin
result := false;
end;
constructor TFHIRClosureOpRequest.create;
begin
inherited create();
FConceptList := TAdvList<TFhirCoding>.create;
end;
procedure TFHIRClosureOpRequest.load(params : TFHIRParameters);
var
p : TFhirParametersParameter;
begin
FName := params.str['name'];
for p in params.parameterList do
if p.name = 'concept' then
FConceptList.Add((p.value as TFhirCoding).Link);{a}
FVersion := params.str['version'];
loadExtensions(params);
end;
procedure TFHIRClosureOpRequest.load(params : TParseMap);
begin
FName := params.getVar('name');
FVersion := params.getVar('version');
loadExtensions(params);
end;
destructor TFHIRClosureOpRequest.Destroy;
begin
FConceptList.free;
inherited;
end;
function TFHIRClosureOpRequest.asParams : TFhirParameters;
var
v1 : TFhirCoding;
begin
result := TFHIRParameters.create;
try
if (FName <> '') then
result.addParameter('name', TFHIRString.create(FName));{oz.5f}
for v1 in FConceptList do
result.AddParameter('concept', v1.Link);
if (FVersion <> '') then
result.addParameter('version', TFHIRId.create(FVersion));{oz.5f}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRClosureOpRequest.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['name', 'concept', 'version'], name);
end;
procedure TFHIRClosureOpResponse.SetReturn(value : TFhirConceptMap);
begin
FReturn.free;
FReturn := value;
end;
constructor TFHIRClosureOpResponse.create;
begin
inherited create();
end;
procedure TFHIRClosureOpResponse.load(params : TFHIRParameters);
begin
FReturn := (params.res['return'] as TFhirConceptMap).Link;{ob.5a}
loadExtensions(params);
end;
procedure TFHIRClosureOpResponse.load(params : TParseMap);
begin
loadExtensions(params);
end;
destructor TFHIRClosureOpResponse.Destroy;
begin
FReturn.free;
inherited;
end;
function TFHIRClosureOpResponse.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FReturn <> nil) then
result.addParameter('return', FReturn.Link);{oz.5a}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRClosureOpResponse.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['return'], name);
end;
procedure TFHIRTranslateOpRequest.SetCoding(value : TFhirCoding);
begin
FCoding.free;
FCoding := value;
end;
procedure TFHIRTranslateOpRequest.SetCodeableConcept(value : TFhirCodeableConcept);
begin
FCodeableConcept.free;
FCodeableConcept := value;
end;
procedure TFHIRTranslateOpReqDependency.SetConcept(value : TFhirCodeableConcept);
begin
FConcept.free;
FConcept := value;
end;
constructor TFHIRTranslateOpReqDependency.create;
begin
inherited create();
end;
constructor TFHIRTranslateOpReqDependency.create(params : TFhirParametersParameter);
begin
inherited create();
FElement := params.str['element'];
FConcept := (params.param['concept'].value as TFhirCodeableConcept).Link; {ob.5d}
loadExtensions(params);
end;
destructor TFHIRTranslateOpReqDependency.Destroy;
begin
FConcept.free;
inherited;
end;
function TFHIRTranslateOpReqDependency.asParams(name : String) : TFhirParametersParameter;
begin
result := TFHIRParametersParameter.create;
try
result.name := name;
if (FElement <> '') then
result.addParameter('element', TFHIRUri.create(FElement));{oz.5f}
if (FConcept <> nil) then
result.addParameter('concept', FConcept.Link);{oz.5d}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRTranslateOpReqDependency.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['element', 'concept'], name);
end;
constructor TFHIRTranslateOpRequest.create;
begin
inherited create();
FDependencyList := TAdvList<TFHIRTranslateOpReqDependency>.create;
end;
procedure TFHIRTranslateOpRequest.load(params : TFHIRParameters);
var
p : TFhirParametersParameter;
begin
FCode := params.str['code'];
FSystem := params.str['system'];
FVersion := params.str['version'];
FSource := params.str['source'];
FCoding := (params.param['coding'].value as TFhirCoding).Link; {ob.5d}
FCodeableConcept := (params.param['codeableConcept'].value as TFhirCodeableConcept).Link; {ob.5d}
FTarget := params.str['target'];
FTargetsystem := params.str['targetsystem'];
for p in params.parameterList do
if p.name = 'dependency' then
FDependencyList.Add(TFHIRTranslateOpReqDependency.create(p));{a}
FReverse := params.bool['reverse'];
loadExtensions(params);
end;
procedure TFHIRTranslateOpRequest.load(params : TParseMap);
begin
FCode := params.getVar('code');
FSystem := params.getVar('system');
FVersion := params.getVar('version');
FSource := params.getVar('source');
FTarget := params.getVar('target');
FTargetsystem := params.getVar('targetsystem');
FReverse := StrToBoolDef(params.getVar('reverse'), false);
loadExtensions(params);
end;
destructor TFHIRTranslateOpRequest.Destroy;
begin
FCoding.free;
FCodeableConcept.free;
FDependencyList.free;
inherited;
end;
function TFHIRTranslateOpRequest.asParams : TFhirParameters;
var
v1 : TFHIRTranslateOpReqDependency;
begin
result := TFHIRParameters.create;
try
if (FCode <> '') then
result.addParameter('code', TFHIRCode.create(FCode));{oz.5f}
if (FSystem <> '') then
result.addParameter('system', TFHIRUri.create(FSystem));{oz.5f}
if (FVersion <> '') then
result.addParameter('version', TFHIRString.create(FVersion));{oz.5f}
if (FSource <> '') then
result.addParameter('source', TFHIRUri.create(FSource));{oz.5f}
if (FCoding <> nil) then
result.addParameter('coding', FCoding.Link);{oz.5d}
if (FCodeableConcept <> nil) then
result.addParameter('codeableConcept', FCodeableConcept.Link);{oz.5d}
if (FTarget <> '') then
result.addParameter('target', TFHIRUri.create(FTarget));{oz.5f}
if (FTargetsystem <> '') then
result.addParameter('targetsystem', TFHIRUri.create(FTargetsystem));{oz.5f}
for v1 in FDependencyList do
result.AddParameter(v1.asParams('dependency'));
result.addParameter('reverse', TFHIRBoolean.create(FReverse));{oz.5f}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRTranslateOpRequest.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['code', 'system', 'version', 'source', 'coding', 'codeableConcept', 'target', 'targetsystem', 'dependency', 'reverse'], name);
end;
procedure TFHIRTranslateOpRespMatch.SetConcept(value : TFhirCoding);
begin
FConcept.free;
FConcept := value;
end;
procedure TFHIRTranslateOpRespProduct.SetConcept(value : TFhirCoding);
begin
FConcept.free;
FConcept := value;
end;
constructor TFHIRTranslateOpRespProduct.create;
begin
inherited create();
end;
constructor TFHIRTranslateOpRespProduct.create(params : TFhirParametersParameter);
begin
inherited create();
FElement := params.str['element'];
FConcept := (params.param['concept'].value as TFhirCoding).Link; {ob.5d}
loadExtensions(params);
end;
destructor TFHIRTranslateOpRespProduct.Destroy;
begin
FConcept.free;
inherited;
end;
function TFHIRTranslateOpRespProduct.asParams(name : String) : TFhirParametersParameter;
begin
result := TFHIRParametersParameter.create;
try
result.name := name;
if (FElement <> '') then
result.addParameter('element', TFHIRUri.create(FElement));{oz.5f}
if (FConcept <> nil) then
result.addParameter('concept', FConcept.Link);{oz.5d}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRTranslateOpRespProduct.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['element', 'concept'], name);
end;
constructor TFHIRTranslateOpRespMatch.create;
begin
inherited create();
FProductList := TAdvList<TFHIRTranslateOpRespProduct>.create;
end;
constructor TFHIRTranslateOpRespMatch.create(params : TFhirParametersParameter);
var
p : TFhirParametersParameter;
begin
inherited create();
FProductList := TAdvList<TFHIRTranslateOpRespProduct>.create;
FEquivalence := params.str['equivalence'];
FConcept := (params.param['concept'].value as TFhirCoding).Link; {ob.5d}
for p in params.partList do
if p.name = 'product' then
FProductList.Add(TFHIRTranslateOpRespProduct.create(p));{a}
FSource := params.str['source'];
loadExtensions(params);
end;
destructor TFHIRTranslateOpRespMatch.Destroy;
begin
FConcept.free;
FProductList.free;
inherited;
end;
function TFHIRTranslateOpRespMatch.asParams(name : String) : TFhirParametersParameter;
var
v1 : TFHIRTranslateOpRespProduct;
begin
result := TFHIRParametersParameter.create;
try
result.name := name;
if (FEquivalence <> '') then
result.addParameter('equivalence', TFHIRCode.create(FEquivalence));{oz.5f}
if (FConcept <> nil) then
result.addParameter('concept', FConcept.Link);{oz.5d}
for v1 in FProductList do
result.AddParameter(v1.asParams('product'));
if (FSource <> '') then
result.addParameter('source', TFHIRUri.create(FSource));{oz.5f}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRTranslateOpRespMatch.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['equivalence', 'concept', 'product', 'source'], name);
end;
constructor TFHIRTranslateOpResponse.create;
begin
inherited create();
FMatchList := TAdvList<TFHIRTranslateOpRespMatch>.create;
end;
procedure TFHIRTranslateOpResponse.load(params : TFHIRParameters);
var
p : TFhirParametersParameter;
begin
FResult := params.bool['result'];
FMessage := params.str['message'];
for p in params.parameterList do
if p.name = 'match' then
FMatchList.Add(TFHIRTranslateOpRespMatch.create(p));{a}
loadExtensions(params);
end;
procedure TFHIRTranslateOpResponse.load(params : TParseMap);
begin
FResult := StrToBoolDef(params.getVar('result'), false);
FMessage := params.getVar('message');
loadExtensions(params);
end;
destructor TFHIRTranslateOpResponse.Destroy;
begin
FMatchList.free;
inherited;
end;
function TFHIRTranslateOpResponse.asParams : TFhirParameters;
var
v1 : TFHIRTranslateOpRespMatch;
begin
result := TFHIRParameters.create;
try
result.addParameter('result', TFHIRBoolean.create(FResult));{oz.5f}
if (FMessage <> '') then
result.addParameter('message', TFHIRString.create(FMessage));{oz.5f}
for v1 in FMatchList do
result.AddParameter(v1.asParams('match'));
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRTranslateOpResponse.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['result', 'message', 'match'], name);
end;
constructor TFHIREverythingOpRequest.create;
begin
inherited create();
end;
procedure TFHIREverythingOpRequest.load(params : TFHIRParameters);
begin
loadExtensions(params);
end;
procedure TFHIREverythingOpRequest.load(params : TParseMap);
begin
loadExtensions(params);
end;
destructor TFHIREverythingOpRequest.Destroy;
begin
inherited;
end;
function TFHIREverythingOpRequest.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIREverythingOpRequest.isKnownName(name : String) : boolean;
begin
result := false;
end;
procedure TFHIREverythingOpResponse.SetReturn(value : TFhirBundle);
begin
FReturn.free;
FReturn := value;
end;
constructor TFHIREverythingOpResponse.create;
begin
inherited create();
end;
procedure TFHIREverythingOpResponse.load(params : TFHIRParameters);
begin
FReturn := (params.res['return'] as TFhirBundle).Link;{ob.5a}
loadExtensions(params);
end;
procedure TFHIREverythingOpResponse.load(params : TParseMap);
begin
loadExtensions(params);
end;
destructor TFHIREverythingOpResponse.Destroy;
begin
FReturn.free;
inherited;
end;
function TFHIREverythingOpResponse.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FReturn <> nil) then
result.addParameter('return', FReturn.Link);{oz.5a}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIREverythingOpResponse.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['return'], name);
end;
constructor TFHIRFindOpRequest.create;
begin
inherited create();
end;
procedure TFHIRFindOpRequest.load(params : TFHIRParameters);
begin
FPatient := params.str['patient'];
FName := params.str['name'];
loadExtensions(params);
end;
procedure TFHIRFindOpRequest.load(params : TParseMap);
begin
FPatient := params.getVar('patient');
FName := params.getVar('name');
loadExtensions(params);
end;
destructor TFHIRFindOpRequest.Destroy;
begin
inherited;
end;
function TFHIRFindOpRequest.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FPatient <> '') then
result.addParameter('patient', TFHIRId.create(FPatient));{oz.5f}
if (FName <> '') then
result.addParameter('name', TFHIRCode.create(FName));{oz.5f}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRFindOpRequest.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['patient', 'name'], name);
end;
constructor TFHIRFindOpResponse.create;
begin
inherited create();
end;
procedure TFHIRFindOpResponse.load(params : TFHIRParameters);
begin
loadExtensions(params);
end;
procedure TFHIRFindOpResponse.load(params : TParseMap);
begin
loadExtensions(params);
end;
destructor TFHIRFindOpResponse.Destroy;
begin
inherited;
end;
function TFHIRFindOpResponse.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRFindOpResponse.isKnownName(name : String) : boolean;
begin
result := false;
end;
procedure TFHIREvaluateMeasureOpRequest.SetMeasure(value : TFhirReference);
begin
FMeasure.free;
FMeasure := value;
end;
procedure TFHIREvaluateMeasureOpRequest.SetPatient(value : TFhirReference);
begin
FPatient.free;
FPatient := value;
end;
procedure TFHIREvaluateMeasureOpRequest.SetPractitioner(value : TFhirReference);
begin
FPractitioner.free;
FPractitioner := value;
end;
constructor TFHIREvaluateMeasureOpRequest.create;
begin
inherited create();
end;
procedure TFHIREvaluateMeasureOpRequest.load(params : TFHIRParameters);
begin
FPeriodStart := TDateTimeEx.fromXml(params.str['periodStart']);
FPeriodEnd := TDateTimeEx.fromXml(params.str['periodEnd']);
FMeasure := (params.param['measure'].value as TFhirReference).Link; {ob.5d}
FReportType := params.str['reportType'];
FPatient := (params.param['patient'].value as TFhirReference).Link; {ob.5d}
FPractitioner := (params.param['practitioner'].value as TFhirReference).Link; {ob.5d}
FLastReceivedOn := TDateTimeEx.fromXml(params.str['lastReceivedOn']);
loadExtensions(params);
end;
procedure TFHIREvaluateMeasureOpRequest.load(params : TParseMap);
begin
FPeriodStart := TDateTimeEx.fromXml(params.getVar('periodStart'));
FPeriodEnd := TDateTimeEx.fromXml(params.getVar('periodEnd'));
FReportType := params.getVar('reportType');
FLastReceivedOn := TDateTimeEx.fromXml(params.getVar('lastReceivedOn'));
loadExtensions(params);
end;
destructor TFHIREvaluateMeasureOpRequest.Destroy;
begin
FMeasure.free;
FPatient.free;
FPractitioner.free;
inherited;
end;
function TFHIREvaluateMeasureOpRequest.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FPeriodStart.notNull) then
result.addParameter('periodStart', TFHIRDate.create(FPeriodStart));{oz.5f}
if (FPeriodEnd.notNull) then
result.addParameter('periodEnd', TFHIRDate.create(FPeriodEnd));{oz.5f}
if (FMeasure <> nil) then
result.addParameter('measure', FMeasure.Link);{oz.5d}
if (FReportType <> '') then
result.addParameter('reportType', TFHIRCode.create(FReportType));{oz.5f}
if (FPatient <> nil) then
result.addParameter('patient', FPatient.Link);{oz.5d}
if (FPractitioner <> nil) then
result.addParameter('practitioner', FPractitioner.Link);{oz.5d}
if (FLastReceivedOn.notNull) then
result.addParameter('lastReceivedOn', TFHIRDateTime.create(FLastReceivedOn));{oz.5f}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIREvaluateMeasureOpRequest.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['periodStart', 'periodEnd', 'measure', 'reportType', 'patient', 'practitioner', 'lastReceivedOn'], name);
end;
procedure TFHIREvaluateMeasureOpResponse.SetReturn(value : TFhirMeasureReport);
begin
FReturn.free;
FReturn := value;
end;
constructor TFHIREvaluateMeasureOpResponse.create;
begin
inherited create();
end;
procedure TFHIREvaluateMeasureOpResponse.load(params : TFHIRParameters);
begin
FReturn := (params.res['return'] as TFhirMeasureReport).Link;{ob.5a}
loadExtensions(params);
end;
procedure TFHIREvaluateMeasureOpResponse.load(params : TParseMap);
begin
loadExtensions(params);
end;
destructor TFHIREvaluateMeasureOpResponse.Destroy;
begin
FReturn.free;
inherited;
end;
function TFHIREvaluateMeasureOpResponse.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FReturn <> nil) then
result.addParameter('return', FReturn.Link);{oz.5a}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIREvaluateMeasureOpResponse.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['return'], name);
end;
procedure TFHIRProcessMessageOpRequest.SetContent(value : TFhirBundle);
begin
FContent.free;
FContent := value;
end;
constructor TFHIRProcessMessageOpRequest.create;
begin
inherited create();
end;
procedure TFHIRProcessMessageOpRequest.load(params : TFHIRParameters);
begin
FContent := (params.res['content'] as TFhirBundle).Link;{ob.5a}
FAsync := params.bool['async'];
FResponseUrl := params.str['response-url'];
loadExtensions(params);
end;
procedure TFHIRProcessMessageOpRequest.load(params : TParseMap);
begin
FAsync := StrToBoolDef(params.getVar('async'), false);
FResponseUrl := params.getVar('response-url');
loadExtensions(params);
end;
destructor TFHIRProcessMessageOpRequest.Destroy;
begin
FContent.free;
inherited;
end;
function TFHIRProcessMessageOpRequest.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FContent <> nil) then
result.addParameter('content', FContent.Link);{oz.5a}
result.addParameter('async', TFHIRBoolean.create(FAsync));{oz.5f}
if (FResponseUrl <> '') then
result.addParameter('response-url', TFHIRUri.create(FResponseUrl));{oz.5f}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRProcessMessageOpRequest.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['content', 'async', 'response-url'], name);
end;
procedure TFHIRProcessMessageOpResponse.SetReturn(value : TFhirBundle);
begin
FReturn.free;
FReturn := value;
end;
constructor TFHIRProcessMessageOpResponse.create;
begin
inherited create();
end;
procedure TFHIRProcessMessageOpResponse.load(params : TFHIRParameters);
begin
FReturn := (params.res['return'] as TFhirBundle).Link;{ob.5a}
loadExtensions(params);
end;
procedure TFHIRProcessMessageOpResponse.load(params : TParseMap);
begin
loadExtensions(params);
end;
destructor TFHIRProcessMessageOpResponse.Destroy;
begin
FReturn.free;
inherited;
end;
function TFHIRProcessMessageOpResponse.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FReturn <> nil) then
result.addParameter('return', FReturn.Link);{oz.5a}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRProcessMessageOpResponse.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['return'], name);
end;
constructor TFHIRLastnOpRequest.create;
begin
inherited create();
end;
procedure TFHIRLastnOpRequest.load(params : TFHIRParameters);
begin
FMax := params.str['max'];
loadExtensions(params);
end;
procedure TFHIRLastnOpRequest.load(params : TParseMap);
begin
FMax := params.getVar('max');
loadExtensions(params);
end;
destructor TFHIRLastnOpRequest.Destroy;
begin
inherited;
end;
function TFHIRLastnOpRequest.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FMax <> '') then
result.addParameter('max', TFHIRPositiveInt.create(FMax));{oz.5f}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRLastnOpRequest.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['max'], name);
end;
procedure TFHIRLastnOpResponse.SetReturn(value : TFhirBundle);
begin
FReturn.free;
FReturn := value;
end;
constructor TFHIRLastnOpResponse.create;
begin
inherited create();
end;
procedure TFHIRLastnOpResponse.load(params : TFHIRParameters);
begin
FReturn := (params.res['return'] as TFhirBundle).Link;{ob.5a}
loadExtensions(params);
end;
procedure TFHIRLastnOpResponse.load(params : TParseMap);
begin
loadExtensions(params);
end;
destructor TFHIRLastnOpResponse.Destroy;
begin
FReturn.free;
inherited;
end;
function TFHIRLastnOpResponse.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FReturn <> nil) then
result.addParameter('return', FReturn.Link);{oz.5a}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRLastnOpResponse.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['return'], name);
end;
procedure TFHIRStatsOpRequest.SetPeriod(value : TFhirPeriod);
begin
FPeriod.free;
FPeriod := value;
end;
constructor TFHIRStatsOpRequest.create;
begin
inherited create();
FCodeList := TList<String>.create;
FCodingList := TAdvList<TFhirCoding>.create;
FStatisticList := TList<String>.create;
end;
procedure TFHIRStatsOpRequest.load(params : TFHIRParameters);
var
p : TFhirParametersParameter;
begin
FSubject := params.str['subject'];
for p in params.parameterList do
if p.name = 'code' then
FCodeList.Add((p.value as TFhirString).value);{ob.1}
FSystem := params.str['system'];
for p in params.parameterList do
if p.name = 'coding' then
FCodingList.Add((p.value as TFhirCoding).Link);{a}
FDuration := params.str['duration'];
FPeriod := (params.param['period'].value as TFhirPeriod).Link; {ob.5d}
for p in params.parameterList do
if p.name = 'statistic' then
FStatisticList.Add((p.value as TFhirCode).value);{ob.1}
FInclude := params.bool['include'];
FLimit := params.str['limit'];
loadExtensions(params);
end;
procedure TFHIRStatsOpRequest.load(params : TParseMap);
var
s : String;
begin
FSubject := params.getVar('subject');
for s in params.getVar('code').Split([';']) do
FCodeList.add(s);
FSystem := params.getVar('system');
FDuration := params.getVar('duration');
for s in params.getVar('statistic').Split([';']) do
FStatisticList.add(s);
FInclude := StrToBoolDef(params.getVar('include'), false);
FLimit := params.getVar('limit');
loadExtensions(params);
end;
destructor TFHIRStatsOpRequest.Destroy;
begin
FCodeList.free;
FCodingList.free;
FPeriod.free;
FStatisticList.free;
inherited;
end;
function TFHIRStatsOpRequest.asParams : TFhirParameters;
var
v1 : String;
v2 : TFhirCoding;
v3 : String;
begin
result := TFHIRParameters.create;
try
if (FSubject <> '') then
result.addParameter('subject', TFHIRUri.create(FSubject));{oz.5f}
for v1 in FCodeList do
result.AddParameter('code', TFhirString.create(v1));
if (FSystem <> '') then
result.addParameter('system', TFHIRUri.create(FSystem));{oz.5f}
for v2 in FCodingList do
result.AddParameter('coding', v2.Link);
if (FDuration <> '') then
result.addParameter('duration', TFHIRDecimal.create(FDuration));{oz.5f}
if (FPeriod <> nil) then
result.addParameter('period', FPeriod.Link);{oz.5d}
for v3 in FStatisticList do
result.AddParameter('statistic', TFhirCode.create(v3));
result.addParameter('include', TFHIRBoolean.create(FInclude));{oz.5f}
if (FLimit <> '') then
result.addParameter('limit', TFHIRPositiveInt.create(FLimit));{oz.5f}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRStatsOpRequest.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['subject', 'code', 'system', 'coding', 'duration', 'period', 'statistic', 'include', 'limit'], name);
end;
constructor TFHIRStatsOpResponse.create;
begin
inherited create();
FReturnList := TAdvList<TFhirObservation>.create;
FSourceList := TAdvList<TFhirObservation>.create;
end;
procedure TFHIRStatsOpResponse.load(params : TFHIRParameters);
var
p : TFhirParametersParameter;
begin
for p in params.parameterList do
if p.name = 'return' then
FReturnList.Add((p.resource as TFhirObservation).Link);{ob.2}
for p in params.parameterList do
if p.name = 'source' then
FSourceList.Add((p.resource as TFhirObservation).Link);{ob.2}
loadExtensions(params);
end;
procedure TFHIRStatsOpResponse.load(params : TParseMap);
begin
loadExtensions(params);
end;
destructor TFHIRStatsOpResponse.Destroy;
begin
FReturnList.free;
FSourceList.free;
inherited;
end;
function TFHIRStatsOpResponse.asParams : TFhirParameters;
var
v1 : TFhirObservation;
v2 : TFhirObservation;
begin
result := TFHIRParameters.create;
try
for v1 in FReturnList do
result.AddParameter('return', v1.Link);
for v2 in FSourceList do
result.AddParameter('source', v2.Link);
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRStatsOpResponse.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['return', 'source'], name);
end;
procedure TFHIRMatchOpRequest.SetResource(value : TFhirResource);
begin
FResource.free;
FResource := value;
end;
constructor TFHIRMatchOpRequest.create;
begin
inherited create();
end;
procedure TFHIRMatchOpRequest.load(params : TFHIRParameters);
begin
FResource := (params.res['resource'] as TFhirResource).Link;{ob.5a}
FOnlyCertainMatches := params.bool['onlyCertainMatches'];
FCount := params.str['count'];
loadExtensions(params);
end;
procedure TFHIRMatchOpRequest.load(params : TParseMap);
begin
FOnlyCertainMatches := StrToBoolDef(params.getVar('onlyCertainMatches'), false);
FCount := params.getVar('count');
loadExtensions(params);
end;
destructor TFHIRMatchOpRequest.Destroy;
begin
FResource.free;
inherited;
end;
function TFHIRMatchOpRequest.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FResource <> nil) then
result.addParameter('resource', FResource.Link);{oz.5a}
result.addParameter('onlyCertainMatches', TFHIRBoolean.create(FOnlyCertainMatches));{oz.5f}
if (FCount <> '') then
result.addParameter('count', TFHIRInteger.create(FCount));{oz.5f}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRMatchOpRequest.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['resource', 'onlyCertainMatches', 'count'], name);
end;
procedure TFHIRMatchOpResponse.SetReturn(value : TFhirBundle);
begin
FReturn.free;
FReturn := value;
end;
constructor TFHIRMatchOpResponse.create;
begin
inherited create();
end;
procedure TFHIRMatchOpResponse.load(params : TFHIRParameters);
begin
FReturn := (params.res['return'] as TFhirBundle).Link;{ob.5a}
loadExtensions(params);
end;
procedure TFHIRMatchOpResponse.load(params : TParseMap);
begin
loadExtensions(params);
end;
destructor TFHIRMatchOpResponse.Destroy;
begin
FReturn.free;
inherited;
end;
function TFHIRMatchOpResponse.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FReturn <> nil) then
result.addParameter('return', FReturn.Link);{oz.5a}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRMatchOpResponse.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['return'], name);
end;
procedure TFHIRPopulateOpRequest.SetQuestionnaire(value : TFhirQuestionnaire);
begin
FQuestionnaire.free;
FQuestionnaire := value;
end;
procedure TFHIRPopulateOpRequest.SetQuestionnaireRef(value : TFhirReference);
begin
FQuestionnaireRef.free;
FQuestionnaireRef := value;
end;
procedure TFHIRPopulateOpRequest.SetSubject(value : TFhirReference);
begin
FSubject.free;
FSubject := value;
end;
constructor TFHIRPopulateOpRequest.create;
begin
inherited create();
FContentList := TAdvList<TFhirReference>.create;
end;
procedure TFHIRPopulateOpRequest.load(params : TFHIRParameters);
var
p : TFhirParametersParameter;
begin
FIdentifier := params.str['identifier'];
FQuestionnaire := (params.res['questionnaire'] as TFhirQuestionnaire).Link;{ob.5a}
FQuestionnaireRef := (params.param['questionnaireRef'].value as TFhirReference).Link; {ob.5d}
FSubject := (params.param['subject'].value as TFhirReference).Link; {ob.5d}
for p in params.parameterList do
if p.name = 'content' then
FContentList.Add((p.value as TFhirReference).Link);{a}
FLocal := params.bool['local'];
loadExtensions(params);
end;
procedure TFHIRPopulateOpRequest.load(params : TParseMap);
begin
FIdentifier := params.getVar('identifier');
FLocal := StrToBoolDef(params.getVar('local'), false);
loadExtensions(params);
end;
destructor TFHIRPopulateOpRequest.Destroy;
begin
FQuestionnaire.free;
FQuestionnaireRef.free;
FSubject.free;
FContentList.free;
inherited;
end;
function TFHIRPopulateOpRequest.asParams : TFhirParameters;
var
v1 : TFhirReference;
begin
result := TFHIRParameters.create;
try
if (FIdentifier <> '') then
result.addParameter('identifier', TFHIRUri.create(FIdentifier));{oz.5f}
if (FQuestionnaire <> nil) then
result.addParameter('questionnaire', FQuestionnaire.Link);{oz.5a}
if (FQuestionnaireRef <> nil) then
result.addParameter('questionnaireRef', FQuestionnaireRef.Link);{oz.5d}
if (FSubject <> nil) then
result.addParameter('subject', FSubject.Link);{oz.5d}
for v1 in FContentList do
result.AddParameter('content', v1.Link);
result.addParameter('local', TFHIRBoolean.create(FLocal));{oz.5f}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRPopulateOpRequest.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['identifier', 'questionnaire', 'questionnaireRef', 'subject', 'content', 'local'], name);
end;
procedure TFHIRPopulateOpResponse.SetQuestionnaire(value : TFhirQuestionnaireResponse);
begin
FQuestionnaire.free;
FQuestionnaire := value;
end;
procedure TFHIRPopulateOpResponse.SetIssues(value : TFhirOperationOutcome);
begin
FIssues.free;
FIssues := value;
end;
constructor TFHIRPopulateOpResponse.create;
begin
inherited create();
end;
procedure TFHIRPopulateOpResponse.load(params : TFHIRParameters);
begin
FQuestionnaire := (params.res['questionnaire'] as TFhirQuestionnaireResponse).Link;{ob.5a}
FIssues := (params.res['issues'] as TFhirOperationOutcome).Link;{ob.5a}
loadExtensions(params);
end;
procedure TFHIRPopulateOpResponse.load(params : TParseMap);
begin
loadExtensions(params);
end;
destructor TFHIRPopulateOpResponse.Destroy;
begin
FQuestionnaire.free;
FIssues.free;
inherited;
end;
function TFHIRPopulateOpResponse.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FQuestionnaire <> nil) then
result.addParameter('questionnaire', FQuestionnaire.Link);{oz.5a}
if (FIssues <> nil) then
result.addParameter('issues', FIssues.Link);{oz.5a}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRPopulateOpResponse.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['questionnaire', 'issues'], name);
end;
procedure TFHIRPopulatehtmlOpRequest.SetQuestionnaire(value : TFhirQuestionnaire);
begin
FQuestionnaire.free;
FQuestionnaire := value;
end;
procedure TFHIRPopulatehtmlOpRequest.SetQuestionnaireRef(value : TFhirReference);
begin
FQuestionnaireRef.free;
FQuestionnaireRef := value;
end;
constructor TFHIRPopulatehtmlOpRequest.create;
begin
inherited create();
FContentList := TAdvList<TFhirReference>.create;
end;
procedure TFHIRPopulatehtmlOpRequest.load(params : TFHIRParameters);
var
p : TFhirParametersParameter;
begin
FIdentifier := params.str['identifier'];
FQuestionnaire := (params.res['questionnaire'] as TFhirQuestionnaire).Link;{ob.5a}
FQuestionnaireRef := (params.param['questionnaireRef'].value as TFhirReference).Link; {ob.5d}
for p in params.parameterList do
if p.name = 'content' then
FContentList.Add((p.value as TFhirReference).Link);{a}
FLocal := params.bool['local'];
loadExtensions(params);
end;
procedure TFHIRPopulatehtmlOpRequest.load(params : TParseMap);
begin
FIdentifier := params.getVar('identifier');
FLocal := StrToBoolDef(params.getVar('local'), false);
loadExtensions(params);
end;
destructor TFHIRPopulatehtmlOpRequest.Destroy;
begin
FQuestionnaire.free;
FQuestionnaireRef.free;
FContentList.free;
inherited;
end;
function TFHIRPopulatehtmlOpRequest.asParams : TFhirParameters;
var
v1 : TFhirReference;
begin
result := TFHIRParameters.create;
try
if (FIdentifier <> '') then
result.addParameter('identifier', TFHIRUri.create(FIdentifier));{oz.5f}
if (FQuestionnaire <> nil) then
result.addParameter('questionnaire', FQuestionnaire.Link);{oz.5a}
if (FQuestionnaireRef <> nil) then
result.addParameter('questionnaireRef', FQuestionnaireRef.Link);{oz.5d}
for v1 in FContentList do
result.AddParameter('content', v1.Link);
result.addParameter('local', TFHIRBoolean.create(FLocal));{oz.5f}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRPopulatehtmlOpRequest.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['identifier', 'questionnaire', 'questionnaireRef', 'content', 'local'], name);
end;
procedure TFHIRPopulatehtmlOpResponse.SetForm(value : TFhirBinary);
begin
FForm.free;
FForm := value;
end;
procedure TFHIRPopulatehtmlOpResponse.SetIssues(value : TFhirOperationOutcome);
begin
FIssues.free;
FIssues := value;
end;
constructor TFHIRPopulatehtmlOpResponse.create;
begin
inherited create();
end;
procedure TFHIRPopulatehtmlOpResponse.load(params : TFHIRParameters);
begin
FForm := (params.res['form'] as TFhirBinary).Link;{ob.5a}
FIssues := (params.res['issues'] as TFhirOperationOutcome).Link;{ob.5a}
loadExtensions(params);
end;
procedure TFHIRPopulatehtmlOpResponse.load(params : TParseMap);
begin
loadExtensions(params);
end;
destructor TFHIRPopulatehtmlOpResponse.Destroy;
begin
FForm.free;
FIssues.free;
inherited;
end;
function TFHIRPopulatehtmlOpResponse.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FForm <> nil) then
result.addParameter('form', FForm.Link);{oz.5a}
if (FIssues <> nil) then
result.addParameter('issues', FIssues.Link);{oz.5a}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRPopulatehtmlOpResponse.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['form', 'issues'], name);
end;
procedure TFHIRPopulatelinkOpRequest.SetQuestionnaire(value : TFhirQuestionnaire);
begin
FQuestionnaire.free;
FQuestionnaire := value;
end;
procedure TFHIRPopulatelinkOpRequest.SetQuestionnaireRef(value : TFhirReference);
begin
FQuestionnaireRef.free;
FQuestionnaireRef := value;
end;
constructor TFHIRPopulatelinkOpRequest.create;
begin
inherited create();
FContentList := TAdvList<TFhirReference>.create;
end;
procedure TFHIRPopulatelinkOpRequest.load(params : TFHIRParameters);
var
p : TFhirParametersParameter;
begin
FIdentifier := params.str['identifier'];
FQuestionnaire := (params.res['questionnaire'] as TFhirQuestionnaire).Link;{ob.5a}
FQuestionnaireRef := (params.param['questionnaireRef'].value as TFhirReference).Link; {ob.5d}
for p in params.parameterList do
if p.name = 'content' then
FContentList.Add((p.value as TFhirReference).Link);{a}
FLocal := params.bool['local'];
loadExtensions(params);
end;
procedure TFHIRPopulatelinkOpRequest.load(params : TParseMap);
begin
FIdentifier := params.getVar('identifier');
FLocal := StrToBoolDef(params.getVar('local'), false);
loadExtensions(params);
end;
destructor TFHIRPopulatelinkOpRequest.Destroy;
begin
FQuestionnaire.free;
FQuestionnaireRef.free;
FContentList.free;
inherited;
end;
function TFHIRPopulatelinkOpRequest.asParams : TFhirParameters;
var
v1 : TFhirReference;
begin
result := TFHIRParameters.create;
try
if (FIdentifier <> '') then
result.addParameter('identifier', TFHIRUri.create(FIdentifier));{oz.5f}
if (FQuestionnaire <> nil) then
result.addParameter('questionnaire', FQuestionnaire.Link);{oz.5a}
if (FQuestionnaireRef <> nil) then
result.addParameter('questionnaireRef', FQuestionnaireRef.Link);{oz.5d}
for v1 in FContentList do
result.AddParameter('content', v1.Link);
result.addParameter('local', TFHIRBoolean.create(FLocal));{oz.5f}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRPopulatelinkOpRequest.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['identifier', 'questionnaire', 'questionnaireRef', 'content', 'local'], name);
end;
procedure TFHIRPopulatelinkOpResponse.SetIssues(value : TFhirOperationOutcome);
begin
FIssues.free;
FIssues := value;
end;
constructor TFHIRPopulatelinkOpResponse.create;
begin
inherited create();
end;
procedure TFHIRPopulatelinkOpResponse.load(params : TFHIRParameters);
begin
FLink_ := params.str['link'];
FIssues := (params.res['issues'] as TFhirOperationOutcome).Link;{ob.5a}
loadExtensions(params);
end;
procedure TFHIRPopulatelinkOpResponse.load(params : TParseMap);
begin
FLink_ := params.getVar('link');
loadExtensions(params);
end;
destructor TFHIRPopulatelinkOpResponse.Destroy;
begin
FIssues.free;
inherited;
end;
function TFHIRPopulatelinkOpResponse.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FLink_ <> '') then
result.addParameter('link', TFHIRUri.create(FLink_));{oz.5f}
if (FIssues <> nil) then
result.addParameter('issues', FIssues.Link);{oz.5a}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRPopulatelinkOpResponse.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['link', 'issues'], name);
end;
constructor TFHIRMetaOpRequest.create;
begin
inherited create();
end;
procedure TFHIRMetaOpRequest.load(params : TFHIRParameters);
begin
loadExtensions(params);
end;
procedure TFHIRMetaOpRequest.load(params : TParseMap);
begin
loadExtensions(params);
end;
destructor TFHIRMetaOpRequest.Destroy;
begin
inherited;
end;
function TFHIRMetaOpRequest.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRMetaOpRequest.isKnownName(name : String) : boolean;
begin
result := false;
end;
procedure TFHIRMetaOpResponse.SetReturn(value : TFhirMeta);
begin
FReturn.free;
FReturn := value;
end;
constructor TFHIRMetaOpResponse.create;
begin
inherited create();
end;
procedure TFHIRMetaOpResponse.load(params : TFHIRParameters);
begin
FReturn := (params.param['return'].value as TFhirMeta).Link; {ob.5d}
loadExtensions(params);
end;
procedure TFHIRMetaOpResponse.load(params : TParseMap);
begin
loadExtensions(params);
end;
destructor TFHIRMetaOpResponse.Destroy;
begin
FReturn.free;
inherited;
end;
function TFHIRMetaOpResponse.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FReturn <> nil) then
result.addParameter('return', FReturn.Link);{oz.5d}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRMetaOpResponse.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['return'], name);
end;
procedure TFHIRMetaAddOpRequest.SetMeta(value : TFhirMeta);
begin
FMeta.free;
FMeta := value;
end;
constructor TFHIRMetaAddOpRequest.create;
begin
inherited create();
end;
procedure TFHIRMetaAddOpRequest.load(params : TFHIRParameters);
begin
FMeta := (params.param['meta'].value as TFhirMeta).Link; {ob.5d}
loadExtensions(params);
end;
procedure TFHIRMetaAddOpRequest.load(params : TParseMap);
begin
loadExtensions(params);
end;
destructor TFHIRMetaAddOpRequest.Destroy;
begin
FMeta.free;
inherited;
end;
function TFHIRMetaAddOpRequest.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FMeta <> nil) then
result.addParameter('meta', FMeta.Link);{oz.5d}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRMetaAddOpRequest.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['meta'], name);
end;
procedure TFHIRMetaAddOpResponse.SetReturn(value : TFhirMeta);
begin
FReturn.free;
FReturn := value;
end;
constructor TFHIRMetaAddOpResponse.create;
begin
inherited create();
end;
procedure TFHIRMetaAddOpResponse.load(params : TFHIRParameters);
begin
FReturn := (params.param['return'].value as TFhirMeta).Link; {ob.5d}
loadExtensions(params);
end;
procedure TFHIRMetaAddOpResponse.load(params : TParseMap);
begin
loadExtensions(params);
end;
destructor TFHIRMetaAddOpResponse.Destroy;
begin
FReturn.free;
inherited;
end;
function TFHIRMetaAddOpResponse.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FReturn <> nil) then
result.addParameter('return', FReturn.Link);{oz.5d}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRMetaAddOpResponse.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['return'], name);
end;
procedure TFHIRMetaDeleteOpRequest.SetMeta(value : TFhirMeta);
begin
FMeta.free;
FMeta := value;
end;
constructor TFHIRMetaDeleteOpRequest.create;
begin
inherited create();
end;
procedure TFHIRMetaDeleteOpRequest.load(params : TFHIRParameters);
begin
FMeta := (params.param['meta'].value as TFhirMeta).Link; {ob.5d}
loadExtensions(params);
end;
procedure TFHIRMetaDeleteOpRequest.load(params : TParseMap);
begin
loadExtensions(params);
end;
destructor TFHIRMetaDeleteOpRequest.Destroy;
begin
FMeta.free;
inherited;
end;
function TFHIRMetaDeleteOpRequest.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FMeta <> nil) then
result.addParameter('meta', FMeta.Link);{oz.5d}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRMetaDeleteOpRequest.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['meta'], name);
end;
procedure TFHIRMetaDeleteOpResponse.SetReturn(value : TFhirMeta);
begin
FReturn.free;
FReturn := value;
end;
constructor TFHIRMetaDeleteOpResponse.create;
begin
inherited create();
end;
procedure TFHIRMetaDeleteOpResponse.load(params : TFHIRParameters);
begin
FReturn := (params.param['return'].value as TFhirMeta).Link; {ob.5d}
loadExtensions(params);
end;
procedure TFHIRMetaDeleteOpResponse.load(params : TParseMap);
begin
loadExtensions(params);
end;
destructor TFHIRMetaDeleteOpResponse.Destroy;
begin
FReturn.free;
inherited;
end;
function TFHIRMetaDeleteOpResponse.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FReturn <> nil) then
result.addParameter('return', FReturn.Link);{oz.5d}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRMetaDeleteOpResponse.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['return'], name);
end;
procedure TFHIRValidateOpRequest.SetResource(value : TFhirResource);
begin
FResource.free;
FResource := value;
end;
constructor TFHIRValidateOpRequest.create;
begin
inherited create();
end;
procedure TFHIRValidateOpRequest.load(params : TFHIRParameters);
begin
FResource := (params.res['resource'] as TFhirResource).Link;{ob.5a}
FMode := params.str['mode'];
FProfile := params.str['profile'];
loadExtensions(params);
end;
procedure TFHIRValidateOpRequest.load(params : TParseMap);
begin
FMode := params.getVar('mode');
FProfile := params.getVar('profile');
loadExtensions(params);
end;
destructor TFHIRValidateOpRequest.Destroy;
begin
FResource.free;
inherited;
end;
function TFHIRValidateOpRequest.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FResource <> nil) then
result.addParameter('resource', FResource.Link);{oz.5a}
if (FMode <> '') then
result.addParameter('mode', TFHIRCode.create(FMode));{oz.5f}
if (FProfile <> '') then
result.addParameter('profile', TFHIRUri.create(FProfile));{oz.5f}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRValidateOpRequest.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['resource', 'mode', 'profile'], name);
end;
procedure TFHIRValidateOpResponse.SetReturn(value : TFhirOperationOutcome);
begin
FReturn.free;
FReturn := value;
end;
constructor TFHIRValidateOpResponse.create;
begin
inherited create();
end;
procedure TFHIRValidateOpResponse.load(params : TFHIRParameters);
begin
FReturn := (params.res['return'] as TFhirOperationOutcome).Link;{ob.5a}
loadExtensions(params);
end;
procedure TFHIRValidateOpResponse.load(params : TParseMap);
begin
loadExtensions(params);
end;
destructor TFHIRValidateOpResponse.Destroy;
begin
FReturn.free;
inherited;
end;
function TFHIRValidateOpResponse.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FReturn <> nil) then
result.addParameter('return', FReturn.Link);{oz.5a}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRValidateOpResponse.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['return'], name);
end;
procedure TFHIREvaluateOpRequest.SetInputParameters(value : TFhirParameters);
begin
FInputParameters.free;
FInputParameters := value;
end;
procedure TFHIREvaluateOpRequest.SetPatient(value : TFhirReference);
begin
FPatient.free;
FPatient := value;
end;
procedure TFHIREvaluateOpRequest.SetEncounter(value : TFhirReference);
begin
FEncounter.free;
FEncounter := value;
end;
procedure TFHIREvaluateOpRequest.SetInitiatingOrganization(value : TFhirReference);
begin
FInitiatingOrganization.free;
FInitiatingOrganization := value;
end;
procedure TFHIREvaluateOpRequest.SetInitiatingPerson(value : TFhirReference);
begin
FInitiatingPerson.free;
FInitiatingPerson := value;
end;
procedure TFHIREvaluateOpRequest.SetUserType(value : TFhirCodeableConcept);
begin
FUserType.free;
FUserType := value;
end;
procedure TFHIREvaluateOpRequest.SetUserLanguage(value : TFhirCodeableConcept);
begin
FUserLanguage.free;
FUserLanguage := value;
end;
procedure TFHIREvaluateOpRequest.SetUserTaskContext(value : TFhirCodeableConcept);
begin
FUserTaskContext.free;
FUserTaskContext := value;
end;
procedure TFHIREvaluateOpRequest.SetReceivingOrganization(value : TFhirReference);
begin
FReceivingOrganization.free;
FReceivingOrganization := value;
end;
procedure TFHIREvaluateOpRequest.SetReceivingPerson(value : TFhirReference);
begin
FReceivingPerson.free;
FReceivingPerson := value;
end;
procedure TFHIREvaluateOpRequest.SetRecipientType(value : TFhirCodeableConcept);
begin
FRecipientType.free;
FRecipientType := value;
end;
procedure TFHIREvaluateOpRequest.SetRecipientLanguage(value : TFhirCodeableConcept);
begin
FRecipientLanguage.free;
FRecipientLanguage := value;
end;
procedure TFHIREvaluateOpRequest.SetSetting(value : TFhirCodeableConcept);
begin
FSetting.free;
FSetting := value;
end;
procedure TFHIREvaluateOpRequest.SetSettingContext(value : TFhirCodeableConcept);
begin
FSettingContext.free;
FSettingContext := value;
end;
constructor TFHIREvaluateOpRequest.create;
begin
inherited create();
FInputDataList := TAdvList<TFhirResource>.create;
end;
procedure TFHIREvaluateOpRequest.load(params : TFHIRParameters);
var
p : TFhirParametersParameter;
begin
FRequestId := params.str['requestId'];
FEvaluateAtDateTime := TDateTimeEx.fromXml(params.str['evaluateAtDateTime']);
FInputParameters := (params.res['inputParameters'] as TFhirParameters).Link;{ob.5a}
for p in params.parameterList do
if p.name = 'inputData' then
FInputDataList.Add((p.resource as TFhirResource).Link);{ob.2}
FPatient := (params.param['patient'].value as TFhirReference).Link; {ob.5d}
FEncounter := (params.param['encounter'].value as TFhirReference).Link; {ob.5d}
FInitiatingOrganization := (params.param['initiatingOrganization'].value as TFhirReference).Link; {ob.5d}
FInitiatingPerson := (params.param['initiatingPerson'].value as TFhirReference).Link; {ob.5d}
FUserType := (params.param['userType'].value as TFhirCodeableConcept).Link; {ob.5d}
FUserLanguage := (params.param['userLanguage'].value as TFhirCodeableConcept).Link; {ob.5d}
FUserTaskContext := (params.param['userTaskContext'].value as TFhirCodeableConcept).Link; {ob.5d}
FReceivingOrganization := (params.param['receivingOrganization'].value as TFhirReference).Link; {ob.5d}
FReceivingPerson := (params.param['receivingPerson'].value as TFhirReference).Link; {ob.5d}
FRecipientType := (params.param['recipientType'].value as TFhirCodeableConcept).Link; {ob.5d}
FRecipientLanguage := (params.param['recipientLanguage'].value as TFhirCodeableConcept).Link; {ob.5d}
FSetting := (params.param['setting'].value as TFhirCodeableConcept).Link; {ob.5d}
FSettingContext := (params.param['settingContext'].value as TFhirCodeableConcept).Link; {ob.5d}
loadExtensions(params);
end;
procedure TFHIREvaluateOpRequest.load(params : TParseMap);
begin
FRequestId := params.getVar('requestId');
FEvaluateAtDateTime := TDateTimeEx.fromXml(params.getVar('evaluateAtDateTime'));
loadExtensions(params);
end;
destructor TFHIREvaluateOpRequest.Destroy;
begin
FInputParameters.free;
FInputDataList.free;
FPatient.free;
FEncounter.free;
FInitiatingOrganization.free;
FInitiatingPerson.free;
FUserType.free;
FUserLanguage.free;
FUserTaskContext.free;
FReceivingOrganization.free;
FReceivingPerson.free;
FRecipientType.free;
FRecipientLanguage.free;
FSetting.free;
FSettingContext.free;
inherited;
end;
function TFHIREvaluateOpRequest.asParams : TFhirParameters;
var
v1 : TFhirResource;
begin
result := TFHIRParameters.create;
try
if (FRequestId <> '') then
result.addParameter('requestId', TFHIRId.create(FRequestId));{oz.5f}
if (FEvaluateAtDateTime.notNull) then
result.addParameter('evaluateAtDateTime', TFHIRDateTime.create(FEvaluateAtDateTime));{oz.5f}
if (FInputParameters <> nil) then
result.addParameter('inputParameters', FInputParameters.Link);{oz.5a}
for v1 in FInputDataList do
result.AddParameter('inputData', v1.Link);
if (FPatient <> nil) then
result.addParameter('patient', FPatient.Link);{oz.5d}
if (FEncounter <> nil) then
result.addParameter('encounter', FEncounter.Link);{oz.5d}
if (FInitiatingOrganization <> nil) then
result.addParameter('initiatingOrganization', FInitiatingOrganization.Link);{oz.5d}
if (FInitiatingPerson <> nil) then
result.addParameter('initiatingPerson', FInitiatingPerson.Link);{oz.5d}
if (FUserType <> nil) then
result.addParameter('userType', FUserType.Link);{oz.5d}
if (FUserLanguage <> nil) then
result.addParameter('userLanguage', FUserLanguage.Link);{oz.5d}
if (FUserTaskContext <> nil) then
result.addParameter('userTaskContext', FUserTaskContext.Link);{oz.5d}
if (FReceivingOrganization <> nil) then
result.addParameter('receivingOrganization', FReceivingOrganization.Link);{oz.5d}
if (FReceivingPerson <> nil) then
result.addParameter('receivingPerson', FReceivingPerson.Link);{oz.5d}
if (FRecipientType <> nil) then
result.addParameter('recipientType', FRecipientType.Link);{oz.5d}
if (FRecipientLanguage <> nil) then
result.addParameter('recipientLanguage', FRecipientLanguage.Link);{oz.5d}
if (FSetting <> nil) then
result.addParameter('setting', FSetting.Link);{oz.5d}
if (FSettingContext <> nil) then
result.addParameter('settingContext', FSettingContext.Link);{oz.5d}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIREvaluateOpRequest.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['requestId', 'evaluateAtDateTime', 'inputParameters', 'inputData', 'patient', 'encounter', 'initiatingOrganization', 'initiatingPerson', 'userType', 'userLanguage', 'userTaskContext', 'receivingOrganization', 'receivingPerson', 'recipientType', 'recipientLanguage', 'setting', 'settingContext'], name);
end;
procedure TFHIREvaluateOpResponse.SetReturn(value : TFhirGuidanceResponse);
begin
FReturn.free;
FReturn := value;
end;
constructor TFHIREvaluateOpResponse.create;
begin
inherited create();
end;
procedure TFHIREvaluateOpResponse.load(params : TFHIRParameters);
begin
FReturn := (params.res['return'] as TFhirGuidanceResponse).Link;{ob.5a}
loadExtensions(params);
end;
procedure TFHIREvaluateOpResponse.load(params : TParseMap);
begin
loadExtensions(params);
end;
destructor TFHIREvaluateOpResponse.Destroy;
begin
FReturn.free;
inherited;
end;
function TFHIREvaluateOpResponse.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FReturn <> nil) then
result.addParameter('return', FReturn.Link);{oz.5a}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIREvaluateOpResponse.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['return'], name);
end;
constructor TFHIRQuestionnaireOpRequest.create;
begin
inherited create();
end;
procedure TFHIRQuestionnaireOpRequest.load(params : TFHIRParameters);
begin
FIdentifier := params.str['identifier'];
FProfile := params.str['profile'];
FUrl := params.str['url'];
FSupportedOnly := params.bool['supportedOnly'];
loadExtensions(params);
end;
procedure TFHIRQuestionnaireOpRequest.load(params : TParseMap);
begin
FIdentifier := params.getVar('identifier');
FProfile := params.getVar('profile');
FUrl := params.getVar('url');
FSupportedOnly := StrToBoolDef(params.getVar('supportedOnly'), false);
loadExtensions(params);
end;
destructor TFHIRQuestionnaireOpRequest.Destroy;
begin
inherited;
end;
function TFHIRQuestionnaireOpRequest.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FIdentifier <> '') then
result.addParameter('identifier', TFHIRUri.create(FIdentifier));{oz.5f}
if (FProfile <> '') then
result.addParameter('profile', TFHIRString.create(FProfile));{oz.5f}
if (FUrl <> '') then
result.addParameter('url', TFHIRUri.create(FUrl));{oz.5f}
result.addParameter('supportedOnly', TFHIRBoolean.create(FSupportedOnly));{oz.5f}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRQuestionnaireOpRequest.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['identifier', 'profile', 'url', 'supportedOnly'], name);
end;
procedure TFHIRQuestionnaireOpResponse.SetReturn(value : TFhirQuestionnaire);
begin
FReturn.free;
FReturn := value;
end;
constructor TFHIRQuestionnaireOpResponse.create;
begin
inherited create();
end;
procedure TFHIRQuestionnaireOpResponse.load(params : TFHIRParameters);
begin
FReturn := (params.res['return'] as TFhirQuestionnaire).Link;{ob.5a}
loadExtensions(params);
end;
procedure TFHIRQuestionnaireOpResponse.load(params : TParseMap);
begin
loadExtensions(params);
end;
destructor TFHIRQuestionnaireOpResponse.Destroy;
begin
FReturn.free;
inherited;
end;
function TFHIRQuestionnaireOpResponse.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FReturn <> nil) then
result.addParameter('return', FReturn.Link);{oz.5a}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRQuestionnaireOpResponse.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['return'], name);
end;
procedure TFHIRTransformOpRequest.SetContent(value : TFhirResource);
begin
FContent.free;
FContent := value;
end;
constructor TFHIRTransformOpRequest.create;
begin
inherited create();
end;
procedure TFHIRTransformOpRequest.load(params : TFHIRParameters);
begin
FSource := params.str['source'];
FContent := (params.res['content'] as TFhirResource).Link;{ob.5a}
loadExtensions(params);
end;
procedure TFHIRTransformOpRequest.load(params : TParseMap);
begin
FSource := params.getVar('source');
loadExtensions(params);
end;
destructor TFHIRTransformOpRequest.Destroy;
begin
FContent.free;
inherited;
end;
function TFHIRTransformOpRequest.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FSource <> '') then
result.addParameter('source', TFHIRUri.create(FSource));{oz.5f}
if (FContent <> nil) then
result.addParameter('content', FContent.Link);{oz.5a}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRTransformOpRequest.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['source', 'content'], name);
end;
procedure TFHIRTransformOpResponse.SetReturn(value : TFhirResource);
begin
FReturn.free;
FReturn := value;
end;
constructor TFHIRTransformOpResponse.create;
begin
inherited create();
end;
procedure TFHIRTransformOpResponse.load(params : TFHIRParameters);
begin
FReturn := (params.res['return'] as TFhirResource).Link;{ob.5a}
loadExtensions(params);
end;
procedure TFHIRTransformOpResponse.load(params : TParseMap);
begin
loadExtensions(params);
end;
destructor TFHIRTransformOpResponse.Destroy;
begin
FReturn.free;
inherited;
end;
function TFHIRTransformOpResponse.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FReturn <> nil) then
result.addParameter('return', FReturn.Link);{oz.5a}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRTransformOpResponse.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['return'], name);
end;
procedure TFHIRExpandOpRequest.SetValueSet(value : TFhirValueSet);
begin
FValueSet.free;
FValueSet := value;
end;
constructor TFHIRExpandOpRequest.create;
begin
inherited create();
end;
procedure TFHIRExpandOpRequest.load(params : TFHIRParameters);
begin
FUrl := params.str['url'];
FValueSet := (params.res['valueSet'] as TFhirValueSet).Link;{ob.5a}
FContext := params.str['context'];
FFilter := params.str['filter'];
FProfile := params.str['profile'];
FDate := TDateTimeEx.fromXml(params.str['date']);
FOffset := params.str['offset'];
FCount := params.str['count'];
FIncludeDesignations := params.bool['includeDesignations'];
FIncludeDefinition := params.bool['includeDefinition'];
FActiveOnly := params.bool['activeOnly'];
FExcludeNested := params.bool['excludeNested'];
FExcludeNotForUI := params.bool['excludeNotForUI'];
FExcludePostCoordinated := params.bool['excludePostCoordinated'];
FDisplayLanguage := params.str['displayLanguage'];
FLimitedExpansion := params.bool['limitedExpansion'];
loadExtensions(params);
end;
procedure TFHIRExpandOpRequest.load(params : TParseMap);
begin
FUrl := params.getVar('url');
FContext := params.getVar('context');
FFilter := params.getVar('filter');
FProfile := params.getVar('profile');
FDate := TDateTimeEx.fromXml(params.getVar('date'));
FOffset := params.getVar('offset');
FCount := params.getVar('count');
FIncludeDesignations := StrToBoolDef(params.getVar('includeDesignations'), false);
FIncludeDefinition := StrToBoolDef(params.getVar('includeDefinition'), false);
FActiveOnly := StrToBoolDef(params.getVar('activeOnly'), false);
FExcludeNested := StrToBoolDef(params.getVar('excludeNested'), false);
FExcludeNotForUI := StrToBoolDef(params.getVar('excludeNotForUI'), false);
FExcludePostCoordinated := StrToBoolDef(params.getVar('excludePostCoordinated'), false);
FDisplayLanguage := params.getVar('displayLanguage');
FLimitedExpansion := StrToBoolDef(params.getVar('limitedExpansion'), false);
loadExtensions(params);
end;
destructor TFHIRExpandOpRequest.Destroy;
begin
FValueSet.free;
inherited;
end;
function TFHIRExpandOpRequest.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FUrl <> '') then
result.addParameter('url', TFHIRUri.create(FUrl));{oz.5f}
if (FValueSet <> nil) then
result.addParameter('valueSet', FValueSet.Link);{oz.5a}
if (FContext <> '') then
result.addParameter('context', TFHIRUri.create(FContext));{oz.5f}
if (FFilter <> '') then
result.addParameter('filter', TFHIRString.create(FFilter));{oz.5f}
if (FProfile <> '') then
result.addParameter('profile', TFHIRUri.create(FProfile));{oz.5f}
if (FDate.notNull) then
result.addParameter('date', TFHIRDateTime.create(FDate));{oz.5f}
if (FOffset <> '') then
result.addParameter('offset', TFHIRInteger.create(FOffset));{oz.5f}
if (FCount <> '') then
result.addParameter('count', TFHIRInteger.create(FCount));{oz.5f}
result.addParameter('includeDesignations', TFHIRBoolean.create(FIncludeDesignations));{oz.5f}
result.addParameter('includeDefinition', TFHIRBoolean.create(FIncludeDefinition));{oz.5f}
result.addParameter('activeOnly', TFHIRBoolean.create(FActiveOnly));{oz.5f}
result.addParameter('excludeNested', TFHIRBoolean.create(FExcludeNested));{oz.5f}
result.addParameter('excludeNotForUI', TFHIRBoolean.create(FExcludeNotForUI));{oz.5f}
result.addParameter('excludePostCoordinated', TFHIRBoolean.create(FExcludePostCoordinated));{oz.5f}
if (FDisplayLanguage <> '') then
result.addParameter('displayLanguage', TFHIRCode.create(FDisplayLanguage));{oz.5f}
result.addParameter('limitedExpansion', TFHIRBoolean.create(FLimitedExpansion));{oz.5f}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRExpandOpRequest.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['url', 'valueSet', 'context', 'filter', 'profile', 'date', 'offset', 'count', 'includeDesignations', 'includeDefinition', 'activeOnly', 'excludeNested', 'excludeNotForUI', 'excludePostCoordinated', 'displayLanguage', 'limitedExpansion'], name);
end;
procedure TFHIRExpandOpResponse.SetReturn(value : TFhirValueSet);
begin
FReturn.free;
FReturn := value;
end;
constructor TFHIRExpandOpResponse.create;
begin
inherited create();
end;
procedure TFHIRExpandOpResponse.load(params : TFHIRParameters);
begin
FReturn := (params.res['return'] as TFhirValueSet).Link;{ob.5a}
loadExtensions(params);
end;
procedure TFHIRExpandOpResponse.load(params : TParseMap);
begin
loadExtensions(params);
end;
destructor TFHIRExpandOpResponse.Destroy;
begin
FReturn.free;
inherited;
end;
function TFHIRExpandOpResponse.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FReturn <> nil) then
result.addParameter('return', FReturn.Link);{oz.5a}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRExpandOpResponse.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['return'], name);
end;
procedure TFHIRValidateCodeOpRequest.SetValueSet(value : TFhirValueSet);
begin
FValueSet.free;
FValueSet := value;
end;
procedure TFHIRValidateCodeOpRequest.SetCoding(value : TFhirCoding);
begin
FCoding.free;
FCoding := value;
end;
procedure TFHIRValidateCodeOpRequest.SetCodeableConcept(value : TFhirCodeableConcept);
begin
FCodeableConcept.free;
FCodeableConcept := value;
end;
constructor TFHIRValidateCodeOpRequest.create;
begin
inherited create();
end;
procedure TFHIRValidateCodeOpRequest.load(params : TFHIRParameters);
begin
FUrl := params.str['url'];
FContext := params.str['context'];
FValueSet := (params.res['valueSet'] as TFhirValueSet).Link;{ob.5a}
FCode := params.str['code'];
FSystem := params.str['system'];
FVersion := params.str['version'];
FDisplay := params.str['display'];
FCoding := (params.param['coding'].value as TFhirCoding).Link; {ob.5d}
FCodeableConcept := (params.param['codeableConcept'].value as TFhirCodeableConcept).Link; {ob.5d}
FDate := TDateTimeEx.fromXml(params.str['date']);
FAbstract := params.bool['abstract'];
FDisplayLanguage := params.str['displayLanguage'];
loadExtensions(params);
end;
procedure TFHIRValidateCodeOpRequest.load(params : TParseMap);
begin
FUrl := params.getVar('url');
FContext := params.getVar('context');
FCode := params.getVar('code');
FSystem := params.getVar('system');
FVersion := params.getVar('version');
FDisplay := params.getVar('display');
FDate := TDateTimeEx.fromXml(params.getVar('date'));
FAbstract := StrToBoolDef(params.getVar('abstract'), false);
FDisplayLanguage := params.getVar('displayLanguage');
loadExtensions(params);
end;
destructor TFHIRValidateCodeOpRequest.Destroy;
begin
FValueSet.free;
FCoding.free;
FCodeableConcept.free;
inherited;
end;
function TFHIRValidateCodeOpRequest.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
if (FUrl <> '') then
result.addParameter('url', TFHIRUri.create(FUrl));{oz.5f}
if (FContext <> '') then
result.addParameter('context', TFHIRUri.create(FContext));{oz.5f}
if (FValueSet <> nil) then
result.addParameter('valueSet', FValueSet.Link);{oz.5a}
if (FCode <> '') then
result.addParameter('code', TFHIRCode.create(FCode));{oz.5f}
if (FSystem <> '') then
result.addParameter('system', TFHIRUri.create(FSystem));{oz.5f}
if (FVersion <> '') then
result.addParameter('version', TFHIRString.create(FVersion));{oz.5f}
if (FDisplay <> '') then
result.addParameter('display', TFHIRString.create(FDisplay));{oz.5f}
if (FCoding <> nil) then
result.addParameter('coding', FCoding.Link);{oz.5d}
if (FCodeableConcept <> nil) then
result.addParameter('codeableConcept', FCodeableConcept.Link);{oz.5d}
if (FDate.notNull) then
result.addParameter('date', TFHIRDateTime.create(FDate));{oz.5f}
result.addParameter('abstract', TFHIRBoolean.create(FAbstract));{oz.5f}
if (FDisplayLanguage <> '') then
result.addParameter('displayLanguage', TFHIRCode.create(FDisplayLanguage));{oz.5f}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRValidateCodeOpRequest.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['url', 'context', 'valueSet', 'code', 'system', 'version', 'display', 'coding', 'codeableConcept', 'date', 'abstract', 'displayLanguage'], name);
end;
constructor TFHIRValidateCodeOpResponse.create;
begin
inherited create();
end;
procedure TFHIRValidateCodeOpResponse.load(params : TFHIRParameters);
begin
FResult := params.bool['result'];
FMessage := params.str['message'];
FDisplay := params.str['display'];
loadExtensions(params);
end;
procedure TFHIRValidateCodeOpResponse.load(params : TParseMap);
begin
FResult := StrToBoolDef(params.getVar('result'), false);
FMessage := params.getVar('message');
FDisplay := params.getVar('display');
loadExtensions(params);
end;
destructor TFHIRValidateCodeOpResponse.Destroy;
begin
inherited;
end;
function TFHIRValidateCodeOpResponse.asParams : TFhirParameters;
begin
result := TFHIRParameters.create;
try
result.addParameter('result', TFHIRBoolean.create(FResult));{oz.5f}
if (FMessage <> '') then
result.addParameter('message', TFHIRString.create(FMessage));{oz.5f}
if (FDisplay <> '') then
result.addParameter('display', TFHIRString.create(FDisplay));{oz.5f}
writeExtensions(result);
result.link;
finally
result.free;
end;
end;
function TFHIRValidateCodeOpResponse.isKnownName(name : String) : boolean;
begin
result := StringArrayExists(['result', 'message', 'display'], name);
end;
end.
| 30.127886 | 333 | 0.748896 |
4719fd39f4bc9ca8bcb648b06a9f99fc20bb58f4 | 6,967 | pas | Pascal | src/CAPI/CAPI_Parser.pas | PMeira/dss_capi | 8b80035730c9d470d057f6643db0a4d4623d70f4 | [
"BSD-3-Clause"
]
| 4 | 2017-12-18T15:23:43.000Z | 2019-02-05T18:22:53.000Z | src/CAPI/CAPI_Parser.pas | PMeira/dss_capi | 8b80035730c9d470d057f6643db0a4d4623d70f4 | [
"BSD-3-Clause"
]
| 28 | 2018-02-12T20:13:26.000Z | 2019-02-11T17:27:51.000Z | src/CAPI/CAPI_Parser.pas | PMeira/dss_capi | 8b80035730c9d470d057f6643db0a4d4623d70f4 | [
"BSD-3-Clause"
]
| 1 | 2018-07-30T22:57:42.000Z | 2018-07-30T22:57:42.000Z | unit CAPI_Parser;
interface
uses
CAPI_Utils,
CAPI_Types;
function Parser_Get_CmdString(): PAnsiChar; CDECL;
procedure Parser_Set_CmdString(const Value: PAnsiChar); CDECL;
function Parser_Get_NextParam(): PAnsiChar; CDECL;
function Parser_Get_AutoIncrement(): TAPIBoolean; CDECL;
procedure Parser_Set_AutoIncrement(Value: TAPIBoolean); CDECL;
function Parser_Get_DblValue(): Double; CDECL;
function Parser_Get_IntValue(): Integer; CDECL;
function Parser_Get_StrValue(): PAnsiChar; CDECL;
function Parser_Get_WhiteSpace(): PAnsiChar; CDECL;
procedure Parser_Set_WhiteSpace(const Value: PAnsiChar); CDECL;
function Parser_Get_BeginQuote(): PAnsiChar; CDECL;
function Parser_Get_EndQuote(): PAnsiChar; CDECL;
procedure Parser_Set_BeginQuote(const Value: PAnsiChar); CDECL;
procedure Parser_Set_EndQuote(const Value: PAnsiChar); CDECL;
function Parser_Get_Delimiters(): PAnsiChar; CDECL;
procedure Parser_Set_Delimiters(const Value: PAnsiChar); CDECL;
procedure Parser_ResetDelimiters(); CDECL;
procedure Parser_Get_Vector(var ResultPtr: PDouble; ResultCount: PAPISize; ExpectedSize: Integer); CDECL;
procedure Parser_Get_Vector_GR(ExpectedSize: Integer); CDECL;
procedure Parser_Get_Matrix(var ResultPtr: PDouble; ResultCount: PAPISize; ExpectedOrder: Integer); CDECL;
procedure Parser_Get_Matrix_GR(ExpectedOrder: Integer); CDECL;
procedure Parser_Get_SymMatrix(var ResultPtr: PDouble; ResultCount: PAPISize; ExpectedOrder: Integer); CDECL;
procedure Parser_Get_SymMatrix_GR(ExpectedOrder: Integer); CDECL;
implementation
uses
CAPI_Constants,
ParserDel,
ArrayDef,
DSSClass;
//------------------------------------------------------------------------------
function Parser_Get_CmdString(): PAnsiChar; CDECL;
begin
Result := DSS_GetAsPAnsiChar(DSSPrime, DSSPrime.ComParser.CmdString);
end;
//------------------------------------------------------------------------------
procedure Parser_Set_CmdString(const Value: PAnsiChar); CDECL;
begin
DSSPrime.ComParser.CmdString := Value;
end;
//------------------------------------------------------------------------------
function Parser_Get_NextParam(): PAnsiChar; CDECL;
begin
Result := DSS_GetAsPAnsiChar(DSSPrime, DSSPrime.ComParser.NextParam);
end;
//------------------------------------------------------------------------------
function Parser_Get_AutoIncrement(): TAPIBoolean; CDECL;
begin
Result := DSSPrime.ComParser.AutoIncrement;
end;
//------------------------------------------------------------------------------
procedure Parser_Set_AutoIncrement(Value: TAPIBoolean); CDECL;
begin
DSSPrime.ComParser.AutoIncrement := Value;
end;
//------------------------------------------------------------------------------
function Parser_Get_DblValue(): Double; CDECL;
begin
Result := DSSPrime.ComParser.DblValue;
end;
//------------------------------------------------------------------------------
function Parser_Get_IntValue(): Integer; CDECL;
begin
Result := DSSPrime.ComParser.IntValue;
end;
//------------------------------------------------------------------------------
function Parser_Get_StrValue(): PAnsiChar; CDECL;
begin
Result := DSS_GetAsPAnsiChar(DSSPrime, DSSPrime.ComParser.StrValue);
end;
//------------------------------------------------------------------------------
function Parser_Get_WhiteSpace(): PAnsiChar; CDECL;
begin
Result := DSS_GetAsPAnsiChar(DSSPrime, DSSPrime.ComParser.Whitespace);
end;
//------------------------------------------------------------------------------
procedure Parser_Set_WhiteSpace(const Value: PAnsiChar); CDECL;
begin
DSSPrime.ComParser.Whitespace := Value;
end;
//------------------------------------------------------------------------------
function Parser_Get_BeginQuote(): PAnsiChar; CDECL;
begin
Result := DSS_GetAsPAnsiChar(DSSPrime, DSSPrime.ComParser.BeginQuoteChars);
end;
//------------------------------------------------------------------------------
function Parser_Get_EndQuote(): PAnsiChar; CDECL;
begin
Result := DSS_GetAsPAnsiChar(DSSPrime, DSSPrime.ComParser.EndQuoteChars);
end;
//------------------------------------------------------------------------------
procedure Parser_Set_BeginQuote(const Value: PAnsiChar); CDECL;
begin
DSSPrime.ComParser.BeginQuoteChars := Value;
end;
//------------------------------------------------------------------------------
procedure Parser_Set_EndQuote(const Value: PAnsiChar); CDECL;
begin
DSSPrime.ComParser.EndQuoteChars := Value;
end;
//------------------------------------------------------------------------------
function Parser_Get_Delimiters(): PAnsiChar; CDECL;
begin
Result := DSS_GetAsPAnsiChar(DSSPrime, DSSPrime.ComParser.Delimiters);
end;
//------------------------------------------------------------------------------
procedure Parser_Set_Delimiters(const Value: PAnsiChar); CDECL;
begin
DSSPrime.ComParser.Delimiters := Value;
end;
//------------------------------------------------------------------------------
procedure Parser_ResetDelimiters(); CDECL;
begin
DSSPrime.ComParser.ResetDelims;
end;
//------------------------------------------------------------------------------
procedure Parser_Get_Vector(var ResultPtr: PDouble; ResultCount: PAPISize; ExpectedSize: Integer); CDECL;
var
ActualSize: Integer;
begin
DSS_RecreateArray_PDouble(ResultPtr, ResultCount, ExpectedSize);
ActualSize := DSSPrime.ComParser.ParseAsVector(ResultCount^, ArrayDef.PDoubleArray(ResultPtr));
ResultCount^ := ActualSize;
end;
procedure Parser_Get_Vector_GR(ExpectedSize: Integer); CDECL;
// Same as Parser_Get_Vector but uses global result (GR) pointers
begin
Parser_Get_Vector(DSSPrime.GR_DataPtr_PDouble, DSSPrime.GR_Counts_PDouble, ExpectedSize)
end;
//------------------------------------------------------------------------------
procedure Parser_Get_Matrix(var ResultPtr: PDouble; ResultCount: PAPISize; ExpectedOrder: Integer); CDECL;
begin
DSS_RecreateArray_PDouble(ResultPtr, ResultCount, ExpectedOrder * ExpectedOrder);
DSSPrime.ComParser.ParseAsMatrix(ResultCount^, ArrayDef.PDoubleArray(ResultPtr));
end;
procedure Parser_Get_Matrix_GR(ExpectedOrder: Integer); CDECL;
// Same as Parser_Get_Matrix but uses global result (GR) pointers
begin
Parser_Get_Matrix(DSSPrime.GR_DataPtr_PDouble, DSSPrime.GR_Counts_PDouble, ExpectedOrder)
end;
//------------------------------------------------------------------------------
procedure Parser_Get_SymMatrix(var ResultPtr: PDouble; ResultCount: PAPISize; ExpectedOrder: Integer); CDECL;
begin
DSS_RecreateArray_PDouble(ResultPtr, ResultCount, ExpectedOrder * ExpectedOrder);
DSSPrime.ComParser.ParseAsSymMatrix(ResultCount^, ArrayDef.PDoubleArray(ResultPtr));
end;
procedure Parser_Get_SymMatrix_GR(ExpectedOrder: Integer); CDECL;
// Same as Parser_Get_SymMatrix but uses global result (GR) pointers
begin
Parser_Get_SymMatrix(DSSPrime.GR_DataPtr_PDouble, DSSPrime.GR_Counts_PDouble, ExpectedOrder)
end;
end.
| 41.224852 | 109 | 0.62064 |
8346e1b0c3b6e0658665d18c11f4491dc9973579 | 24,917 | dfm | Pascal | VCL_DELPHIX_D6/DxPathEdit.dfm | danielmarschall/spacemission | 28eaed68d11cd9c25f054b551949fb9187f654d2 | [
"Apache-2.0"
]
| null | null | null | VCL_DELPHIX_D6/DxPathEdit.dfm | danielmarschall/spacemission | 28eaed68d11cd9c25f054b551949fb9187f654d2 | [
"Apache-2.0"
]
| null | null | null | VCL_DELPHIX_D6/DxPathEdit.dfm | danielmarschall/spacemission | 28eaed68d11cd9c25f054b551949fb9187f654d2 | [
"Apache-2.0"
]
| 1 | 2021-01-28T02:19:19.000Z | 2021-01-28T02:19:19.000Z | object DelphiXPathsEditForm: TDelphiXPathsEditForm
Left = 292
Top = 187
Width = 610
Height = 508
Caption = 'Paths Editor'
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = True
Position = poScreenCenter
OnCreate = FormCreate
OnDestroy = FormDestroy
PixelsPerInch = 96
TextHeight = 13
object Panel2: TPanel
Left = 0
Top = 74
Width = 602
Height = 381
Align = alClient
BevelOuter = bvNone
BorderWidth = 5
Caption = 'Panel2'
TabOrder = 0
object ScrollBox1: TScrollBox
Left = 5
Top = 5
Width = 592
Height = 371
Align = alClient
TabOrder = 0
object Pane: TPanel
Left = 0
Top = 0
Width = 640
Height = 480
BevelOuter = bvNone
Color = clBlack
TabOrder = 0
OnResize = PaneResize
object Image1: TImage
Left = 0
Top = 0
Width = 640
Height = 480
Cursor = crCross
Align = alClient
end
object Shape1: TShape
Left = 16
Top = 16
Width = 16
Height = 16
Brush.Color = clYellow
Pen.Color = clRed
OnMouseDown = ShapeMouseDown
OnMouseMove = ShapeMouseMove
OnMouseUp = ShapeMouseUp
end
end
end
end
object Panel1: TPanel
Left = 0
Top = 0
Width = 602
Height = 74
Align = alTop
BevelOuter = bvNone
BorderStyle = bsSingle
TabOrder = 1
object Label1: TLabel
Left = 4
Top = 28
Width = 97
Height = 13
Caption = 'Active editing trace:'
FocusControl = cbListOfTraces
end
object LAmount: TLabel
Left = 124
Top = 28
Width = 41
Height = 13
Caption = 'Amount:'
FocusControl = eAmount
end
object Label2: TLabel
Left = 172
Top = 28
Width = 54
Height = 13
Caption = 'Show (ms):'
FocusControl = eShowOn
end
object Label3: TLabel
Left = 464
Top = 48
Width = 11
Height = 13
Caption = 'R:'
end
object cbListOfTraces: TComboBox
Left = 4
Top = 44
Width = 113
Height = 21
Style = csDropDownList
ItemHeight = 13
TabOrder = 1
OnChange = cbListOfTracesChange
end
object eAmount: TEdit
Left = 124
Top = 44
Width = 41
Height = 21
TabOrder = 2
Text = '32'
end
object btnNewTrace: TButton
Left = 312
Top = 40
Width = 65
Height = 25
Caption = 'New Trace'
TabOrder = 5
OnClick = btnNewTraceClick
end
object eShowOn: TEdit
Left = 172
Top = 44
Width = 41
Height = 21
TabOrder = 3
Text = '25'
end
object Panel12: TPanel
Left = 0
Top = 0
Width = 521
Height = 28
BevelOuter = bvLowered
TabOrder = 0
object btnSetTimming: TSpeedButton
Left = 2
Top = 2
Width = 24
Height = 24
Hint = 'Blit show time refresh.'
AllowAllUp = True
GroupIndex = 2
Flat = True
Glyph.Data = {
F6000000424DF600000000000000760000002800000010000000100000000100
0400000000008000000000000000000000001000000010000000000000000000
80000080000000808000800000008000800080800000C0C0C000808080000000
FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF00777777777777
7777777770000077777777700FBFBF007777770BFBFBFBFB077770BFBFBFBFBF
B07770FB0BFBFBFBF0770FBFB0BFBFBFBF070BFBFB0BFBFBFB070FBFBFB00000
0F070BFBFBFBFBFBFB070FBFBFBFBFBFBF0770FBFBFBFBFBF07770BFBFBFBFBF
B077770BFBF0FBFB077777700FBFBF0077777777700000777777}
ParentShowHint = False
ShowHint = True
OnClick = btnSetTimmingClick
end
object btnLine: TSpeedButton
Left = 32
Top = 2
Width = 24
Height = 24
Hint = 'Create line.'
AllowAllUp = True
GroupIndex = 3
Flat = True
Glyph.Data = {
F6000000424DF600000000000000760000002800000010000000100000000100
0400000000008000000000000000000000001000000010000000000000000000
8000008000000080800080000000800080008080000080808000C0C0C0000000
FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF00888888888888
8888888888888888888888888888888888888888888888880888888888888880
8888888888888808888888888888808888888888888808888888888888808888
8888888888088888888888888088888888888888088888888888888088888888
8888880888888888888888888888888888888888888888888888}
ParentShowHint = False
ShowHint = True
OnClick = btnLineClick
end
object btnCircle: TSpeedButton
Left = 56
Top = 2
Width = 24
Height = 24
Hint = 'Create ellipse/circle.'
AllowAllUp = True
GroupIndex = 3
Flat = True
Glyph.Data = {
F6000000424DF600000000000000760000002800000010000000100000000100
0400000000008000000000000000000000001000000010000000000000000000
8000008000000080800080000000800080008080000080808000C0C0C0000000
FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF00888888888888
8888888888888888888888888888888888888888888888888888888800000088
8888880088888800888880888888888808880888888888888088088888888888
8088088888888888808880888888888808888800888888008888888800000088
8888888888888888888888888888888888888888888888888888}
ParentShowHint = False
ShowHint = True
OnClick = btnLineClick
end
object btnSelectionArea: TSpeedButton
Left = 132
Top = 2
Width = 24
Height = 24
Hint = 'Selection.'
AllowAllUp = True
GroupIndex = 4
Flat = True
Glyph.Data = {
42010000424D4201000000000000760000002800000011000000110000000100
040000000000CC00000000000000000000001000000010000000000000000000
BF0000BF000000BFBF00BF000000BF00BF00BFBF0000C0C0C000808080000000
FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF00777777777777
7777700000007770777777777077700000007778777777777877700000007080
8080808080807000000077788888888888777000000077708888888880777000
0000777888888888887770000000777088888888807770000000777888888888
8877700000007770888888888077700000007778888888888877700000007770
8888888880777000000077788888888888777000000070808080808080807000
0000777877777777787770000000777077777777707770000000777777777777
777770000000}
ParentShowHint = False
ShowHint = True
OnClick = btnSelectionAreaClick
end
object btnSelectAll: TSpeedButton
Left = 180
Top = 2
Width = 24
Height = 24
Hint = 'Select single.'
Enabled = False
Flat = True
Glyph.Data = {
42010000424D4201000000000000760000002800000011000000110000000100
040000000000CC00000000000000000000001000000010000000000000000000
BF0000BF000000BFBF00BF000000BF00BF00BFBF0000C0C0C000808080000000
FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF00777777777777
7777700000007777000777777000700000007777000444444000700000007777
0007777770007000000077777477777777477000000000077477777777477000
0000000444777777774770000000000774777777774770000000747774777777
7747700000007477000777777000700000007477000444444000700000007477
0007747770007000000074777777747777777000000000077777000777777000
0000000444440007777770000000000777770007777770000000777777777777
777770000000}
ParentShowHint = False
ShowHint = True
end
object btnGrid: TSpeedButton
Left = 156
Top = 2
Width = 24
Height = 24
Hint = 'Show/hide grid...'
AllowAllUp = True
GroupIndex = 5
Flat = True
Glyph.Data = {
F6000000424DF600000000000000760000002800000010000000100000000100
0400000000008000000000000000000000001000000010000000000000000000
BF0000BF000000BFBF00BF000000BF00BF00BFBF0000C0C0C000808080000000
FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF00777777777777
7777777877877877877777787787787787777880880880880887777877877877
8777777877877877877778808808808808877778778778778777777877877877
8777788088088088088777787787787787777778778778778777788088088088
0887777877877877877777787787787787777777777777777777}
ParentShowHint = False
ShowHint = True
OnClick = btnGridClick
end
object brnSelectAsOne: TSpeedButton
Left = 204
Top = 2
Width = 24
Height = 24
Hint = 'SSelect one.'
Enabled = False
Flat = True
Glyph.Data = {
42010000424D4201000000000000760000002800000011000000110000000100
040000000000CC00000000000000000000001000000010000000000000000000
BF0000BF000000BFBF00BF000000BF00BF00BFBF0000C0C0C000808080000000
FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF00777777777777
7777700000007000777777777700000000007000774444444400000000007000
7747777777000000000077777747777777747000000077777747777777747000
0000774444477777777470000000774777477777777470000000774777477777
7774700000007747774777777774700000007747774444444444700000007747
7777774777777000000077477777774777777000000070007777774777000000
0000700044444447770000000000700077777777770000000000777777777777
777770000000}
ParentShowHint = False
ShowHint = True
end
object btnBringToFront: TSpeedButton
Left = 252
Top = 2
Width = 24
Height = 24
Hint = 'Bring to front.'
Flat = True
Glyph.Data = {
42010000424D4201000000000000760000002800000011000000110000000100
040000000000CC00000000000000000000001000000010000000000000000000
BF0000BF000000BFBF00BF000000BF00BF00BFBF0000C0C0C000808080000000
FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF00777777777777
7777700000007777777777777777700000007777770000000007700000007777
7708888888077000000077777708888888077000000070000000000088077000
000070FBFBFBFBF088077000000070BFBFBFBFB088077000000070FBFBFBFBF0
88077000000070BFBFBFBFB000077000000070FBFBFBFBF077777000000070BF
BFBFBFB077777000000070FBFBFBFBF077777000000070BFBFBFBFB077777000
0000700000000000777770000000777777777777777770000000777777777777
777770000000}
ParentShowHint = False
ShowHint = True
OnClick = btnBringToFrontClick
end
object btnMoveDown: TSpeedButton
Left = 308
Top = 2
Width = 24
Height = 24
Hint = 'Move down.'
AllowAllUp = True
Flat = True
Glyph.Data = {
DE000000424DDE0000000000000076000000280000000D0000000D0000000100
0400000000006800000000000000000000001000000010000000000000000000
BF0000BF000000BFBF00BF000000BF00BF00BFBF0000C0C0C000808080000000
FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF00777777777777
7000777777777777700077777707777770007777706077777000777706660777
7000777066666077700077066666660770007000066600007000777706660777
7000777706660777700077770666077770007777000007777000777777777777
7000}
ParentShowHint = False
ShowHint = True
OnClick = btnMoveDownClick
end
object btnSendToBack: TSpeedButton
Left = 228
Top = 2
Width = 24
Height = 24
Hint = 'Send to back.'
Flat = True
Glyph.Data = {
42010000424D4201000000000000760000002800000011000000110000000100
040000000000CC00000000000000000000001000000010000000000000000000
BF0000BF000000BFBF00BF000000BF00BF00BFBF0000C0C0C000808080000000
FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF00777777777777
7777700000007777777777777777700000007777770000000007700000007777
7708888888077000000077777708888888077000000070000008888888077000
000070FBFB08888888077000000070BFBF08888888077000000070FBFB088888
88077000000070BFBF00000000077000000070FBFBFBFBF077777000000070BF
BFBFBFB077777000000070FBFBFBFBF077777000000070BFBFBFBFB077777000
0000700000000000777770000000777777777777777770000000777777777777
777770000000}
ParentShowHint = False
ShowHint = True
OnClick = btnSendToBackClick
end
object btnMoveUp: TSpeedButton
Left = 284
Top = 2
Width = 24
Height = 24
Hint = 'Move up.'
AllowAllUp = True
Flat = True
Glyph.Data = {
DE000000424DDE0000000000000076000000280000000D0000000D0000000100
0400000000006800000000000000000000001000000010000000000000000000
BF0000BF000000BFBF00BF000000BF00BF00BFBF0000C0C0C000808080000000
FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF00777777777777
7000777777777777700077770000077770007777066607777000777706660777
7000777706660777700070000666000070007706666666077000777066666077
7000777706660777700077777060777770007777770777777000777777777777
7000}
ParentShowHint = False
ShowHint = True
OnClick = btnMoveUpClick
end
object btnMoveLeft: TSpeedButton
Left = 332
Top = 2
Width = 24
Height = 24
Hint = 'Move left.'
AllowAllUp = True
Flat = True
Glyph.Data = {
DE000000424DDE0000000000000076000000280000000D0000000D0000000100
0400000000006800000000000000000000001000000010000000000000000000
BF0000BF000000BFBF00BF000000BF00BF00BFBF0000C0C0C000808080000000
FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF00777777777777
7000777777077777700077777007777770007777060777777000777066000007
7000770666666607700070666666660770007706666666077000777066000007
7000777706077777700077777007777770007777770777777000777777777777
7000}
ParentShowHint = False
ShowHint = True
OnClick = btnMoveLeftClick
end
object btnMoveRight: TSpeedButton
Left = 356
Top = 2
Width = 24
Height = 24
Hint = 'Move right.'
AllowAllUp = True
Flat = True
Glyph.Data = {
DE000000424DDE0000000000000076000000280000000D0000000D0000000100
0400000000006800000000000000000000001000000010000000000000000000
BF0000BF000000BFBF00BF000000BF00BF00BFBF0000C0C0C000808080000000
FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF00777777777777
7000777777077777700077777700777770007777770607777000770000066077
7000770666666607700077066666666070007706666666077000770000066077
7000777777060777700077777700777770007777770777777000777777777777
7000}
ParentShowHint = False
ShowHint = True
OnClick = btnMoveRightClick
end
object btnCurve: TSpeedButton
Left = 104
Top = 2
Width = 24
Height = 24
Hint = 'Free style.'
AllowAllUp = True
GroupIndex = 3
Flat = True
Glyph.Data = {
F6000000424DF600000000000000760000002800000010000000100000000100
0400000000008000000000000000000000001000000010000000000000000000
8000008000000080800080000000800080008080000080808000C0C0C0000000
FF00C0C0C00000FFFF00FF000000C0C0C000FFFF0000FFFFFF00DADADADADADA
DADAADADADADAD0DADADDADADADAD0DADADAADADADAD000DADADDADADAD0D0D0
DADAADADADA0A0A0ADADDADADAD0DA00DADAADADADAD0DADADADDADADADAD0DA
DADAADAD00ADAD0DADADDAD0DA0ADA0ADADAADA0ADA0AD0DADADDADA0ADA00DA
DADAADADA0ADADADADADDADAD0DADADADADAADADA0ADADADADAD}
ParentShowHint = False
ShowHint = True
OnClick = btnLineClick
end
object btnProperties: TSpeedButton
Left = 488
Top = 2
Width = 24
Height = 24
Hint = 'Properties...'
GroupIndex = 11
Enabled = False
Flat = True
Glyph.Data = {
F6000000424DF600000000000000760000002800000010000000100000000100
0400000000008000000000000000000000001000000010000000000000000000
BF0000BF000000BFBF00BF000000BF00BF00BFBF0000C0C0C000808080000000
FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF00777777777777
7777777777777777777777B387777777777777BB387777777777777BB3877777
77777777BB387777777777777BB387777777777777BB387788777777777BB388
008777777777BB300007777777777B0008877777777770008077777777770008
0B77777777700080B77777777777777777777777777777777777}
ParentShowHint = False
ShowHint = True
end
object btnRect: TSpeedButton
Left = 80
Top = 2
Width = 24
Height = 24
Hint = 'Create rectangle.'
AllowAllUp = True
GroupIndex = 3
Flat = True
Glyph.Data = {
42010000424D4201000000000000760000002800000011000000110000000100
040000000000CC00000000000000000000001000000010000000000000000000
BF0000BF000000BFBF00BF000000BF00BF00BFBF0000C0C0C000808080000000
FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF00777777777777
7777700000007777777777777777700000007777777777777777700000007000
0000000000007000000070777777777777707000000070777777777777707000
0000707777777777777070000000707777777777777070000000707777777777
7770700000007077777777777770700000007077777777777770700000007077
7777777777707000000070777777777777707000000070777777777777707000
0000700000000000000070000000777777777777777770000000777777777777
777770000000}
ParentShowHint = False
ShowHint = True
OnClick = btnLineClick
end
object LDist: TLabel
Left = 384
Top = 7
Width = 26
Height = 13
Hint = 'Rotation distance 1..255'
Caption = 'Dist.:'
FocusControl = eDist
ParentShowHint = False
ShowHint = True
Transparent = True
end
object btnRotateLeft: TSpeedButton
Left = 440
Top = 2
Width = 24
Height = 24
Hint = 'Rotate left'
AllowAllUp = True
Flat = True
Glyph.Data = {
42010000424D4201000000000000760000002800000011000000110000000100
040000000000CC00000000000000000000001000000010000000000000000000
BF0000BF000000BFBF00BF000000BF00BF00BFBF0000C0C0C000808080000000
FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF00777777777777
777770000000777777555555777770000000777775FBFBFB5777700000007777
5FBFBFBFB577700000007775FBFBFBFBFB5770000000775FBFBFBFBFBF577000
0000775BFBFBFBFBFBB570000000775FBFBF00BFBFF570000000775BFBFB00FF
BFB570000000775FBFB9B9BBFBF570000000775BFB9BF9FBFB57700000007775
B91FB9BFBF577000000077779B1999FBF57770000000777975BFB9BF57777000
0000709777555955777770000000700777770977777770000000777777770077
777770000000}
ParentShowHint = False
ShowHint = True
OnClick = btnRotateLeftClick
end
object btnRotateRight: TSpeedButton
Left = 464
Top = 2
Width = 24
Height = 24
Hint = 'Rotate right'
AllowAllUp = True
Flat = True
Glyph.Data = {
42010000424D4201000000000000760000002800000011000000110000000100
040000000000CC00000000000000000000001000000010000000000000000000
BF0000BF000000BFBF00BF000000BF00BF00BFBF0000C0C0C000808080000000
FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF00777777777777
77777000000077777555555777777000000077775BFBFBF57777700000007775
BFBFBFBF577770000000775BFBFBFBFBF57770000000775FBFBFBFBFBF577000
000075BBFBFBFBFBFB577000000075FFBFB00FBFBF577000000075BFBFF00BFB
FB577000000075FBFBB9B9BFBF5770000000775BFBF9FB9BFB5770000000775F
BFB9BF19B577700000007775FBF9991B97777000000077775FB9BFB579777000
0000777775595557779070000000777777790777770070000000777777700777
777770000000}
ParentShowHint = False
ShowHint = True
OnClick = btnRotateRightClick
end
object eDist: TEdit
Left = 412
Top = 3
Width = 25
Height = 21
TabOrder = 0
Text = '1'
end
end
object Panel3: TPanel
Left = 518
Top = 0
Width = 80
Height = 70
Align = alRight
BevelOuter = bvNone
TabOrder = 7
object OKButton: TButton
Left = 4
Top = 8
Width = 73
Height = 25
Caption = 'OK'
Default = True
ModalResult = 1
TabOrder = 0
OnClick = OKButtonClick
end
object CancelButton: TButton
Left = 4
Top = 39
Width = 73
Height = 25
Cancel = True
Caption = 'Cancel'
ModalResult = 2
TabOrder = 1
end
end
object btnRefresh: TBitBtn
Left = 232
Top = 40
Width = 75
Height = 25
Caption = 'Refresh'
TabOrder = 4
OnClick = btnRefreshClick
Glyph.Data = {
76010000424D7601000000000000760000002800000020000000100000000100
0400000000000001000000000000000000001000000010000000000000000000
800000800000008080008000000080008000808000007F7F7F00BFBFBF000000
FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF00333333333333
3333333333FFFFF3333333333999993333333333F77777FFF333333999999999
3333333777333777FF33339993707399933333773337F3777FF3399933000339
9933377333777F3377F3399333707333993337733337333337FF993333333333
399377F33333F333377F993333303333399377F33337FF333373993333707333
333377F333777F333333993333101333333377F333777F3FFFFF993333000399
999377FF33777F77777F3993330003399993373FF3777F37777F399933000333
99933773FF777F3F777F339993707399999333773F373F77777F333999999999
3393333777333777337333333999993333333333377777333333}
NumGlyphs = 2
end
object Button1: TBitBtn
Left = 384
Top = 40
Width = 74
Height = 25
Caption = 'Reset Sel.'
TabOrder = 6
OnClick = Button1Click
Glyph.Data = {
76010000424D7601000000000000760000002800000020000000100000000100
0400000000000001000000000000000000001000000010000000000000000000
800000800000008080008000000080008000808000007F7F7F00BFBFBF000000
FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF00500005000555
555557777F777555F55500000000555055557777777755F75555005500055055
555577F5777F57555555005550055555555577FF577F5FF55555500550050055
5555577FF77577FF555555005050110555555577F757777FF555555505099910
555555FF75777777FF555005550999910555577F5F77777775F5500505509990
3055577F75F77777575F55005055090B030555775755777575755555555550B0
B03055555F555757575755550555550B0B335555755555757555555555555550
BBB35555F55555575F555550555555550BBB55575555555575F5555555555555
50BB555555555555575F555555555555550B5555555555555575}
NumGlyphs = 2
end
end
object StatusBar1: TStatusBar
Left = 0
Top = 455
Width = 602
Height = 19
Panels = <
item
Width = 50
end
item
Width = 100
end
item
Width = 50
end>
SimplePanel = False
end
object PopupMenu1: TPopupMenu
Left = 216
Top = 64
object Activate1: TMenuItem
Caption = 'Activate'
end
end
end
| 36.805022 | 75 | 0.679937 |
47c30fc1ad82566cda597ef9568173e3fb290bd6 | 7,979 | pas | Pascal | Composants/SynEdit-2_0_3/SynEdit/Source/SynEditPrinterInfo.pas | thewhiteninja/all4cod | 81bb997c23d93068c4ad09854fd0fd77d214f34a | [
"MIT"
]
| 5 | 2020-03-31T03:39:43.000Z | 2021-07-27T08:47:54.000Z | Composants/SynEdit-2_0_3/SynEdit/Source/SynEditPrinterInfo.pas | thewhiteninja/all4cod | 81bb997c23d93068c4ad09854fd0fd77d214f34a | [
"MIT"
]
| null | null | null | Composants/SynEdit-2_0_3/SynEdit/Source/SynEditPrinterInfo.pas | thewhiteninja/all4cod | 81bb997c23d93068c4ad09854fd0fd77d214f34a | [
"MIT"
]
| 4 | 2020-03-31T03:39:45.000Z | 2021-07-26T03:20:54.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 Original Code is: SynEditPrinterInfo.pas, released 2000-06-01.
The Initial Author of the Original Code is Morten J. Skovrup.
Portions written by Morten J. Skovrup are copyright 2000 Morten J. Skovrup.
All Rights Reserved.
Contributors to the SynEdit project are listed in the Contributors.txt file.
Alternatively, the contents of this file may be used under the terms of the
GNU General Public License Version 2 or later (the "GPL"), in which case
the provisions of the GPL are applicable instead of those above.
If you wish to allow use of your version of this file only under the terms
of the GPL 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 GPL.
If you do not delete the provisions above, a recipient may use your version
of this file under either the MPL or the GPL.
$Id: SynEditPrinterInfo.pas,v 1.5 2005/10/18 01:26:51 etrusco Exp $
You may retrieve the latest version of this file at the SynEdit home page,
located at http://SynEdit.SourceForge.net
Known Issues:
-------------------------------------------------------------------------------}
{-------------------------------------------------------------------------------
CONTENTS:
Class retrieving info about selected printer and paper size.
-------------------------------------------------------------------------------}
{$IFNDEF QSYNEDITPRINTERINFO}
unit SynEditPrinterInfo;
{$ENDIF}
{$I SynEdit.inc}
interface
uses
{$IFDEF SYN_CLX}
Qt,
QPrinters;
{$ELSE}
Windows,
Printers;
{$ENDIF}
type
//Printer info class - getting dimensions of paper
TSynEditPrinterInfo = class
private
FPhysicalWidth: Integer;
FPhysicalHeight: Integer;
FPrintableWidth: Integer;
FPrintableHeight: Integer;
FLeftGutter: Integer;
FRightGutter: Integer;
FTopGutter: Integer;
FBottomGutter: Integer;
FXPixPrInch: Integer;
FYPixPrInch: Integer;
FXPixPrmm: Single;
FYPixPrmm: Single;
FIsUpdated: Boolean;
procedure FillDefault;
function GetBottomGutter: Integer;
function GetLeftGutter: Integer;
function GetPhysicalHeight: Integer;
function GetPhysicalWidth: Integer;
function GetPrintableHeight: Integer;
function GetPrintableWidth: Integer;
function GetRightGutter: Integer;
function GetTopGutter: Integer;
function GetXPixPrInch: Integer;
function GetYPixPrInch: Integer;
function GetXPixPrmm: Single;
function GetYPixPrmm: Single;
public
procedure UpdatePrinter;
function PixFromLeft(mmValue: Double): Integer;
function PixFromRight(mmValue: Double): Integer;
function PixFromTop(mmValue: Double): Integer;
function PixFromBottom(mmValue: Double): Integer;
property PhysicalWidth: Integer read GetPhysicalWidth;
property PhysicalHeight: Integer read GetPhysicalHeight;
property PrintableWidth: Integer read GetPrintableWidth;
property PrintableHeight: Integer read GetPrintableHeight;
property LeftGutter: Integer read GetLeftGutter;
property RightGutter: Integer read GetRightGutter;
property TopGutter: Integer read GetTopGutter;
property BottomGutter: Integer read GetBottomGutter;
property XPixPrInch: Integer read GetXPixPrInch;
property YPixPrInch: Integer read GetYPixPrInch;
property XPixPrmm: Single read GetXPixPrmm;
property YPixPrmm: Single read GetYPixPrmm;
end;
implementation
{ TSynEditPrinterInfo }
function TSynEditPrinterInfo.PixFromBottom(mmValue: Double): Integer;
begin
if not FIsUpdated then
UpdatePrinter;
Result := Round(mmValue * FYPixPrmm - FBottomGutter);
end;
function TSynEditPrinterInfo.PixFromLeft(mmValue: Double): Integer;
begin
if not FIsUpdated then
UpdatePrinter;
Result := Round(mmValue * FXPixPrmm - FLeftGutter);
end;
function TSynEditPrinterInfo.PixFromRight(mmValue: Double): Integer;
begin
if not FIsUpdated then
UpdatePrinter;
Result := Round(mmValue * FXPixPrmm - FRightGutter);
end;
function TSynEditPrinterInfo.PixFromTop(mmValue: Double): Integer;
begin
if not FIsUpdated then
UpdatePrinter;
Result := Round(mmValue * FYPixPrmm - FTopGutter);
end;
procedure TSynEditPrinterInfo.FillDefault;
{In case of no printers installed this information is used
(I think it's taken from a HP LaserJet III with A4 paper)}
begin
FPhysicalWidth := 2481;
FPhysicalHeight := 3507;
FPrintableWidth := 2358;
FPrintableHeight := 3407;
FLeftGutter := 65;
FRightGutter := 58;
FTopGutter := 50;
FBottomGutter := 50;
FXPixPrInch := 300;
FYPixPrInch := 300;
FXPixPrmm := FXPixPrInch / 25.4;
FYPixPrmm := FYPixPrInch / 25.4;
end;
function TSynEditPrinterInfo.GetBottomGutter: Integer;
begin
if not FIsUpdated then
UpdatePrinter;
Result := FBottomGutter;
end;
function TSynEditPrinterInfo.GetLeftGutter: Integer;
begin
if not FIsUpdated then
UpdatePrinter;
Result := FLeftGutter;
end;
function TSynEditPrinterInfo.GetPhysicalHeight: Integer;
begin
if not FIsUpdated then
UpdatePrinter;
Result := FPhysicalHeight;
end;
function TSynEditPrinterInfo.GetPhysicalWidth: Integer;
begin
if not FIsUpdated then
UpdatePrinter;
Result := FPhysicalWidth;
end;
function TSynEditPrinterInfo.GetPrintableHeight: Integer;
begin
if not FIsUpdated then
UpdatePrinter;
Result := FPrintableHeight;
end;
function TSynEditPrinterInfo.GetPrintableWidth: Integer;
begin
if not FIsUpdated then
UpdatePrinter;
Result := FPrintableWidth;
end;
function TSynEditPrinterInfo.GetRightGutter: Integer;
begin
if not FIsUpdated then
UpdatePrinter;
Result := FRightGutter;
end;
function TSynEditPrinterInfo.GetTopGutter: Integer;
begin
if not FIsUpdated then
UpdatePrinter;
Result := FTopGutter;
end;
function TSynEditPrinterInfo.GetXPixPrInch: Integer;
begin
if not FIsUpdated then
UpdatePrinter;
Result := FXPixPrInch;
end;
function TSynEditPrinterInfo.GetXPixPrmm: Single;
begin
if not FIsUpdated then
UpdatePrinter;
Result := FXPixPrmm;
end;
function TSynEditPrinterInfo.GetYPixPrInch: Integer;
begin
if not FIsUpdated then
UpdatePrinter;
Result := FYPixPrInch;
end;
function TSynEditPrinterInfo.GetYPixPrmm: Single;
begin
if not FIsUpdated then
UpdatePrinter;
Result := FYPixPrmm;
end;
procedure TSynEditPrinterInfo.UpdatePrinter;
begin
FIsUpdated := True;
Printer.Refresh;
if Printer.Printers.Count <= 0 then
begin
FillDefault;
Exit;
end;
{************}
{$IFNDEF SYN_CLX}
FPhysicalWidth := GetDeviceCaps(Printer.Handle, Windows.PhysicalWidth);
FPhysicalHeight := GetDeviceCaps(Printer.Handle, Windows.PhysicalHeight);
{$ENDIF}
FPrintableWidth := Printer.PageWidth; {or GetDeviceCaps(Printer.Handle, HorzRes);}
FPrintableHeight := Printer.PageHeight; {or GetDeviceCaps(Printer.Handle, VertRes);}
{************}
{$IFNDEF SYN_CLX}
FLeftGutter := GetDeviceCaps(Printer.Handle, PhysicalOffsetX);
FTopGutter := GetDeviceCaps(Printer.Handle, PhysicalOffsetY);
{$ENDIF}
FRightGutter := FPhysicalWidth - FPrintableWidth - FLeftGutter;
FBottomGutter := FPhysicalHeight - FPrintableHeight - FTopGutter;
{************}
{$IFNDEF SYN_CLX}
FXPixPrInch := GetDeviceCaps(Printer.Handle, LogPixelsX);
FYPixPrInch := GetDeviceCaps(Printer.Handle, LogPixelsY);
{$ENDIF}
FXPixPrmm := FXPixPrInch / 25.4;
FYPixPrmm := FYPixPrInch / 25.4;
end;
end.
| 28.701439 | 86 | 0.731295 |
6af97b4695b4d611711145d3d965cf5a80a6699a | 5,073 | pas | Pascal | Server/src/daraja framework/djHTTPServer.pas | Ermesoml/Delphi-with-Vue.js | 1c9046e4ef9341f9592ac0e088e022cd50001eec | [
"MIT"
]
| 6 | 2018-09-10T14:37:57.000Z | 2022-02-27T11:55:29.000Z | Server/src/daraja framework/djHTTPServer.pas | Ermesoml/Delphi-with-Vue.js | 1c9046e4ef9341f9592ac0e088e022cd50001eec | [
"MIT"
]
| 1 | 2019-04-23T11:25:40.000Z | 2019-04-23T12:23:13.000Z | Server/src/daraja framework/djHTTPServer.pas | Ermesoml/Delphi-with-Vue.js | 1c9046e4ef9341f9592ac0e088e022cd50001eec | [
"MIT"
]
| 1 | 2018-09-10T14:38:03.000Z | 2018-09-10T14:38:03.000Z | (*
Daraja Framework
Copyright (C) 2016 Michael Justin
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the Daraja framework without
disclosing the source code of your own applications. These activities
include: offering paid services to customers as an ASP, shipping Daraja
with a closed source product.
*)
unit djHTTPServer;
interface
uses
{$IFDEF DARAJA_LOGGING}
djLogAPI, djLoggerFactory,
{$ENDIF DARAJA_LOGGING}
IdCustomHTTPServer, IdCustomTCPServer, IdIOHandler, IdContext,
SysUtils, Classes, IdSSLOpenSSL;
const
DEFAULT_SESSION_TIMEOUT = 10 * 60 * 1000;
type
(**
* HTTP Server.
*
* Inherits from Indy HTTP Server.
*)
{ TdjHTTPServer }
TdjHTTPServer = class(TIdCustomHTTPServer)
private
{$IFDEF DARAJA_LOGGING}
Logger: ILogger;
{$ENDIF DARAJA_LOGGING}
// Exceptions
procedure MyOnException(AContext: TIdContext; AException: Exception);
procedure MyOnListenException(AThread: TIdListenerThread; AException: Exception);
// Sessions
procedure MySessionStart(Sender: TIdHTTPSession);
procedure MySessionEnd(Sender: TIdHTTPSession);
procedure Trace(const S: string);
protected
(**
* If the server has a connection limit (MaxConnections) set,
* and a new request exceeds this limit, log as a warning message.
*)
procedure DoMaxConnectionsExceeded(AIOHandler: TIdIOHandler); override;
public
(**
* Create a HTTP Server.
*)
constructor Create;
(**
* Handler for HTTP requests.
*)
property OnCommandGet;
end;
implementation
uses
djServerContext,
IdException, IdExceptionCore;
{ TdjHTTPServer }
constructor TdjHTTPServer.Create;
begin
inherited Create;
{IOHandler := TIdServerIOHandlerSSLOpenSSL.Create(Self);
TIdServerIOHandlerSSLOpenSSL(IOHandler).SSLOptions.Method := sslvTLSv1_2;
TIdServerIOHandlerSSLOpenSSL(IOHandler).SSLOptions.SSLVersions := [sslvTLSv1_2];
TIdServerIOHandlerSSLOpenSSL(IOHandler).SSLOptions.Mode := sslmClient;}
// logging -----------------------------------------------------------------
{$IFDEF DARAJA_LOGGING}
Logger := TdjLoggerFactory.GetLogger('dj.' + TdjHTTPServer.ClassName);
{$ENDIF DARAJA_LOGGING}
Trace('Configuring HTTP server');
{$IFDEF DARAJA_LOGGING}
Logger.Info('Indy version: ' + GetIndyVersion);
{$ENDIF DARAJA_LOGGING}
// use HTTP 1.1 keep-alive by default
KeepAlive := True;
// session management
// workaround for AV on port already open
SessionList := TIdHTTPDefaultSessionList.Create(Self);
SessionState := True;
SessionTimeOut := DEFAULT_SESSION_TIMEOUT; // 10 minutes
Trace('On-demand HTTP sessions enabled');
OnException := MyOnException;
OnListenException:= MyOnListenException;
OnSessionStart := MySessionStart;
OnSessionEnd := MySessionEnd;
// register context class
ContextClass := TdjServerContext;
Trace('Context class: ' + TdjServerContext.ClassName);
end;
procedure TdjHTTPServer.Trace(const S: string);
begin
{$IFDEF DARAJA_LOGGING}
if Logger.IsTraceEnabled then
begin
Logger.Trace(S);
end;
{$ENDIF DARAJA_LOGGING}
end;
procedure TdjHTTPServer.MyOnException(AContext: TIdContext;
AException: Exception);
begin
if AException is EIdSilentException then Exit;
if AException is EIdNotConnected then Exit;
{$IFDEF DARAJA_LOGGING}
Logger.Warn(ClassName + ' (OnException): ' + AException.ClassName + ' '
+ AException.Message);
{$IFDEF LINUX}
// DumpExceptionBackTrace(StdOut);
// Halt;
{$ENDIF LINUX}
{$ENDIF DARAJA_LOGGING}
end;
procedure TdjHTTPServer.MyOnListenException(AThread: TIdListenerThread;
AException: Exception);
begin
{$IFDEF DARAJA_LOGGING}
Logger.Warn(ClassName + ' (OnListenException): ' + AException.ClassName + ' '
+ AException.Message);
{$ENDIF DARAJA_LOGGING}
end;
procedure TdjHTTPServer.MySessionStart(Sender: TIdHTTPSession);
begin
Trace('Session start ' + Sender.RemoteHost);
end;
procedure TdjHTTPServer.MySessionEnd(Sender: TIdHTTPSession);
begin
Trace('Session end ' + Sender.RemoteHost);
end;
procedure TdjHTTPServer.DoMaxConnectionsExceeded(AIOHandler: TIdIOHandler);
begin
{$IFDEF DARAJA_LOGGING}
Logger.Warn(ClassName + ': MaxConnections exceeded');
{$ENDIF DARAJA_LOGGING}
end;
end.
| 26.149485 | 85 | 0.734082 |
f1c051d46bf3da3a19dd2278fe0b5a9adfdb3953 | 221 | dpr | Pascal | windows/src/ext/jedi/jvcl/tests/p3/examples/JvRichEditParser/JvRichEditParserDemo.dpr | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 219 | 2017-06-21T03:37:03.000Z | 2022-03-27T12:09:28.000Z | windows/src/ext/jedi/jvcl/tests/p3/examples/JvRichEditParser/JvRichEditParserDemo.dpr | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 4,451 | 2017-05-29T02:52:06.000Z | 2022-03-31T23:53:23.000Z | windows/src/ext/jedi/jvcl/tests/p3/examples/JvRichEditParser/JvRichEditParserDemo.dpr | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 72 | 2017-05-26T04:08:37.000Z | 2022-03-03T10:26:20.000Z | program JvRichEditParserDemo;
uses
Forms,
JvRichEditParserFrm in 'JvRichEditParserFrm.pas' {frmMain};
{$R *.res}
begin
Application.Initialize;
Application.CreateForm(TfrmMain, frmMain);
Application.Run;
end.
| 15.785714 | 61 | 0.764706 |
833b1120e058a410e31d72f753b1633120630dbb | 17,183 | pas | Pascal | Quake_Delphi_Sources/src/cl_main.pas | delphi-pascal-archive/quake-delphi-sources | d7b90ca29ea43f9f7f11bb3646bee5050b100509 | [
"Unlicense"
]
| null | null | null | Quake_Delphi_Sources/src/cl_main.pas | delphi-pascal-archive/quake-delphi-sources | d7b90ca29ea43f9f7f11bb3646bee5050b100509 | [
"Unlicense"
]
| null | null | null | Quake_Delphi_Sources/src/cl_main.pas | delphi-pascal-archive/quake-delphi-sources | d7b90ca29ea43f9f7f11bb3646bee5050b100509 | [
"Unlicense"
]
| null | null | null | // ------------------------------------------------------------------------------
//
// Copyright (C) 1996-1997 Id Software, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// ------------------------------------------------------------------------------
// Roman Vereshagin
//
//
unit cl_main;
interface
uses
Unit_SysTools,
client;
type
TClientMain = class
procedure Init;
procedure NextDemo;
procedure AdjustPitch;
procedure ClearState;
procedure Disconnect;
procedure EstablishConnection(host: PChar);
procedure SignonReply;
function AllocDlight(key: integer): Pdlight_t;
procedure DecayLights;
function LerpPoint: single;
procedure RelinkEntities;
function ReadFromServer: integer;
procedure SendCmd;
end;
var
ClientMain: TClientMain;
procedure CL_Disconnect_f;
procedure CL_PrintEntities_f;
implementation
// cl_main.c -- client main loop
uses
cvar,
gl_model_h,
quakedef,
sv_main,
host,
cl_main_h,
common,
cl_tent,
snd_dma,
cl_demo,
console,
protocol,
net_main,
zone,
gl_screen,
cmd,
mathlib,
gl_refrag,
r_part,
chase,
host_h,
cl_parse,
cl_input,
in_win;
procedure CL_Disconnect_f;
begin
ClientMain.Disconnect;
if sv.active then
Host_ShutdownServer(false);
end;
procedure CL_PrintEntities_f;
var
ent: Pentity_t;
i: integer;
begin
ent := @cl_entities[0];
for i := 0 to cl.num_entities - 1 do
begin
Con_Printf('%3d:', [i]);
if ent.model = nil then
Con_Printf('EMPTY'#10)
else
Con_Printf('%s:%2d (%5.1f,%5.1f,%5.1f) [%5.1f %5.1f %5.1f]'#10,
[ent.model.name, ent.frame, ent.origin[0], ent.origin[1], ent.origin[2], ent.angles[0], ent.angles[1], ent.angles[2]]);
inc(ent);
end;
end;
(*
===============
SetPal
Debugging tool, just flashes the screen
===============
*)
procedure SetPal(i: integer);
begin
(*
#if 0
static int old;
byte pal[768];
int c;
if (i == old)
return;
old = i;
if (i==0)
VID_SetPalette (host_basepal);
else if (i==1)
{
for (c=0 ; c<768 ; c+=3)
{
pal[c] = 0;
pal[c+1] = 255;
pal[c+2] = 0;
}
VID_SetPalette (pal);
}
else
{
for (c=0 ; c<768 ; c+=3)
{
pal[c] = 0;
pal[c+1] = 0;
pal[c+2] = 255;
}
VID_SetPalette (pal);
}
#endif
*)
end;
{ TClientMain }
procedure TClientMain.AdjustPitch;
begin
if cl.viewangles[PITCH] > 80 then cl.viewangles[PITCH] := 80;
if cl.viewangles[PITCH] < -70 then cl.viewangles[PITCH] := -70;
end;
function TClientMain.AllocDlight(key: integer): Pdlight_t;
var
i: integer;
dl: Pdlight_t;
begin
// first look for an exact key match
if boolval(key) then
begin
dl := @cl_dlights;
for i := 0 to MAX_DLIGHTS - 1 do
begin
if dl.key = key then
begin
memset(dl, 0, SizeOf(dl^));
dl.key := key;
result := dl;
exit;
end;
inc(dl);
end;
end;
// then look for anything else
dl := @cl_dlights[0];
for i := 0 to MAX_DLIGHTS - 1 do
begin
if dl.die < cl.time then
begin
memset(dl, 0, SizeOf(dlight_t));
dl.key := key;
result := dl;
exit;
end;
inc(dl);
end;
dl := @cl_dlights[0];
memset(dl, 0, SizeOf(dlight_t));
dl.key := key;
result := dl;
end;
procedure TClientMain.ClearState;
var
i: integer;
begin
if not sv.active then
Host_ClearMemory;
// wipe the entire cl structure
ZeroMemory(@cl, SizeOf(cl));
SZ_Clear(@cls._message);
// clear other arrays
ZeroMemory(@cl_efrags, SizeOf(cl_efrags));
ZeroMemory(@cl_entities, SizeOf(cl_entities));
ZeroMemory(@cl_dlights, SizeOf(cl_dlights));
ZeroMemory(@cl_lightstyle, SizeOf(cl_lightstyle));
ClientEntity.Clear;
//
// allocate the efrags and chain together into a free list
//
cl.free_efrags := @cl_efrags;
for i := 0 to MAX_EFRAGS - 2 do
cl.free_efrags[i].entnext := @cl.free_efrags[i + 1];
cl.free_efrags[MAX_EFRAGS - 1].entnext := nil;
end;
procedure TClientMain.DecayLights;
var
i: integer;
dl: Pdlight_t;
time: single;
begin
time := cl.time - cl.oldtime;
dl := @cl_dlights[0];
for i := 0 to MAX_DLIGHTS - 1 do
begin
if (dl.die < cl.time) or (dl.radius = 0) then
else
begin
dl.radius := dl.radius - time * dl.decay;
if dl.radius < 0 then
dl.radius := 0;
end;
inc(dl);
end;
end;
procedure TClientMain.Disconnect;
begin
// stop sounds (especially looping!)
S_StopAllSounds(true);
// bring the console down and fade the colors back to normal
// SCR_BringDownConsole ();
// if running a local server, shut it down
if cls.demoplayback then
Demo.StopPlayback
else
if cls.state = ca_connected then
begin
if cls.demorecording then
CL_Stop_f;
Con_DPrintf('Sending clc_disconnect'#10);
SZ_Clear(@cls._message);
MSG_WriteByte(@cls._message, clc_disconnect);
NET_SendUnreliableMessage(cls.netcon, @cls._message);
SZ_Clear(@cls._message);
NET_Close(cls.netcon);
cls.state := ca_disconnected;
if sv.active then
Host_ShutdownServer(false);
end;
cls.demoplayback := false;
cls.timedemo := false;
cls.signon := 0;
end;
procedure TClientMain.EstablishConnection(host: PChar);
begin
if cls.state = ca_dedicated then
exit;
if cls.demoplayback then
exit;
Disconnect;
cls.netcon := NET_Connect(host);
if cls.netcon = nil then
Host_Error('CL_Connect: connect failed'#10);
Con_DPrintf('CL_EstablishConnection: connected to %s'#10, [host]);
cls.demonum := -1; // not in the demo loop now
cls.state := ca_connected;
cls.signon := 0; // need all the signon messages before playing
end;
procedure TClientMain.Init;
begin
SZ_Alloc(@cls._message, 1024);
CL_InitInput;
ClientEntity.Init;
//
// register our commands
//
ConsoleVars.RegisterVariable(@cl_name);
ConsoleVars.RegisterVariable(@cl_color);
ConsoleVars.RegisterVariable(@cl_upspeed);
ConsoleVars.RegisterVariable(@cl_forwardspeed);
ConsoleVars.RegisterVariable(@cl_backspeed);
ConsoleVars.RegisterVariable(@cl_sidespeed);
ConsoleVars.RegisterVariable(@cl_movespeedkey);
ConsoleVars.RegisterVariable(@cl_yawspeed);
ConsoleVars.RegisterVariable(@cl_pitchspeed);
ConsoleVars.RegisterVariable(@cl_anglespeedkey);
ConsoleVars.RegisterVariable(@cl_shownet);
ConsoleVars.RegisterVariable(@cl_nolerp);
ConsoleVars.RegisterVariable(@lookspring);
ConsoleVars.RegisterVariable(@lookstrafe);
ConsoleVars.RegisterVariable(@sensitivity);
ConsoleVars.RegisterVariable(@m_pitch);
ConsoleVars.RegisterVariable(@m_yaw);
ConsoleVars.RegisterVariable(@m_forward);
ConsoleVars.RegisterVariable(@m_side);
// Cvar_RegisterVariable (&cl_autofire);
Cmd_AddCommand('entities', CL_PrintEntities_f);
Cmd_AddCommand('disconnect', CL_Disconnect_f);
Cmd_AddCommand('record', CL_Record_f);
Cmd_AddCommand('stop', CL_Stop_f);
Cmd_AddCommand('playdemo', CL_PlayDemo_f);
Cmd_AddCommand('timedemo', CL_TimeDemo_f);
end;
function TClientMain.LerpPoint: single;
var
f, frac: single;
begin
f := cl.mtime[0] - cl.mtime[1];
if (f = 0) or (cl_nolerp.value <> 0) or cls.timedemo or sv.active then
begin
cl.time := cl.mtime[0];
result := 1;
exit;
end;
if f > 0.1 then
begin // dropped packet, or start of demo
cl.mtime[1] := cl.mtime[0] - 0.1;
f := 0.1;
end;
frac := (cl.time - cl.mtime[1]) / f;
//Con_Printf ("frac: %f\n",frac);
if frac < 0 then
begin
if frac < -0.01 then
begin
SetPal(1); // VJ
cl.time := cl.mtime[1];
// Con_Printf ("low frac\n");
end;
frac := 0;
end
else if frac > 1 then
begin
if frac > 1.01 then
begin
SetPal(2); // VJ
cl.time := cl.mtime[0];
// Con_Printf ("high frac\n");
end;
frac := 1;
end
else
SetPal(0);
result := frac;
end;
procedure TClientMain.NextDemo;
var
str: array[0..1023] of char;
begin
if cls.demonum = -1 then
exit; // don't play demos
SCR_BeginLoadingPlaque;
if (cls.demos[cls.demonum][0] = #0) or (cls.demonum = MAX_DEMOS) then
begin
cls.demonum := 0;
if not boolval(cls.demos[cls.demonum][0]) then
begin
Con_Printf('No demos listed with startdemos'#10);
cls.demonum := -1;
exit;
end;
end;
sprintf(str, 'playdemo %s'#10, [cls.demos[cls.demonum]]);
Cbuf_InsertText(str);
inc(cls.demonum);
end;
function TClientMain.ReadFromServer: integer;
var
ret: integer;
begin
cl.oldtime := cl.time;
cl.time := cl.time + host_frametime;
repeat
ret := Demo.GetMessage;
if ret = -1 then
Host_Error('CL_ReadFromServer: lost server connection');
if ret = 0 then
break;
cl.last_received_message := realtime;
Parser.ParseServerMessage;
until not ((ret <> 0) and (cls.state = ca_connected));
if cl_shownet.value <> 0 then
Con_Printf(#10);
RelinkEntities;
ClientEntity.Update;
//
// bring the links up to date
//
result := 0;
end;
procedure TClientMain.RelinkEntities;
var
ent: Pentity_t;
i, j: integer;
frac, f, d: single;
delta: TVector3f;
bobjrotate: single;
oldorg: TVector3f;
dl: Pdlight_t;
fv, rv, uv: TVector3f;
begin
// determine partial update time
frac := LerpPoint;
cl_numvisedicts := 0;
//
// interpolate player info
//
for i := 0 to 2 do
cl.velocity[i] := cl.mvelocity[1][i] +
frac * (cl.mvelocity[0][i] - cl.mvelocity[1][i]);
if cls.demoplayback then
begin
// interpolate the angles
for j := 0 to 2 do
begin
d := cl.mviewangles[0][j] - cl.mviewangles[1][j];
if d > 180 then
d := d - 360
else if d < -180 then
d := d + 360;
cl.viewangles[j] := cl.mviewangles[1][j] + frac * d;
end;
end;
bobjrotate := anglemod(100 * cl.time);
// start on the entity after the world
for i := 1 to cl.num_entities - 1 do
begin
ent := @cl_entities[i];
if ent.model = nil then
begin // empty slot
if ent.forcelink then
R_RemoveEfrags(ent); // just became empty
continue;
end;
// if the object wasn't included in the last packet, remove it
if ent.msgtime <> cl.mtime[0] then
begin
ent.model := nil;
continue;
end;
VectorCopy(@ent.origin, @oldorg);
if ent.forcelink then
begin // the entity was not updated in the last message
// so move to the final spot
VectorCopy(@ent.msg_origins[0], @ent.origin);
VectorCopy(@ent.msg_angles[0], @ent.angles);
end
else
begin // if the delta is large, assume a teleport and don't lerp
f := frac;
for j := 0 to 2 do
begin
delta[j] := ent.msg_origins[0][j] - ent.msg_origins[1][j];
if (delta[j] > 100) or (delta[j] < -100) then
f := 1; // assume a teleportation, not a motion
end;
// interpolate the origin and angles
for j := 0 to 2 do
begin
ent.origin[j] := ent.msg_origins[1][j] + f * delta[j];
d := ent.msg_angles[0][j] - ent.msg_angles[1][j];
if d > 180 then
d := d - 360
else if d < -180 then
d := d + 360;
ent.angles[j] := ent.msg_angles[1][j] + f * d;
end;
end;
// rotate binary objects locally
if ent.model.flags and EF_ROTATE <> 0 then
ent.angles[1] := bobjrotate;
if ent.effects and EF_BRIGHTFIELD <> 0 then
R_EntityParticles(ent);
(*
#ifdef QUAKE2
if (ent->effects & EF_DARKFIELD)
R_DarkFieldParticles (ent);
#endif
*)
if ent.effects and EF_MUZZLEFLASH <> 0 then
begin
dl := AllocDlight(i);
VectorCopy(@ent.origin, @dl.origin);
dl.origin[2] := dl.origin[2] + 16;
AngleVectors(@ent.angles, @fv, @rv, @uv);
VectorMA(@dl.origin, 18, @fv, @dl.origin);
dl.radius := 200 + (rand and 31);
dl.minlight := 32;
dl.die := cl.time + 0.1;
end;
if ent.effects and EF_BRIGHTLIGHT <> 0 then
begin
dl := AllocDlight(i);
VectorCopy(@ent.origin, @dl.origin);
dl.origin[2] := dl.origin[2] + 16;
dl.radius := 400 + (rand and 31);
dl.die := cl.time + 0.001;
end;
if ent.effects and EF_DIMLIGHT <> 0 then
begin
dl := AllocDlight(i);
VectorCopy(@ent.origin, @dl.origin);
dl.radius := 200 + (rand and 31);
dl.die := cl.time + 0.001;
end;
(*
#ifdef QUAKE2
if (ent->effects & EF_DARKLIGHT)
{
dl = CL_AllocDlight (i);
VectorCopy (ent->origin, dl->origin);
dl->radius = 200.0 + (rand()&31);
dl->die = cl.time + 0.001;
dl->dark = true;
}
if (ent->effects & EF_LIGHT)
{
dl = CL_AllocDlight (i);
VectorCopy (ent->origin, dl->origin);
dl->radius = 200;
dl->die = cl.time + 0.001;
}
#endif
*)
if ent.model.flags and EF_GIB <> 0 then
R_RocketTrail(@oldorg, @ent.origin, 2)
else if ent.model.flags and EF_ZOMGIB <> 0 then
R_RocketTrail(@oldorg, @ent.origin, 4)
else if ent.model.flags and EF_TRACER <> 0 then
R_RocketTrail(@oldorg, @ent.origin, 3)
else if ent.model.flags and EF_TRACER2 <> 0 then
R_RocketTrail(@oldorg, @ent.origin, 5)
else if ent.model.flags and EF_ROCKET <> 0 then
begin
R_RocketTrail(@oldorg, @ent.origin, 0);
dl := AllocDlight(i);
VectorCopy(@ent.origin, @dl.origin);
dl.radius := 200;
dl.die := cl.time + 0.01;
end
else if ent.model.flags and EF_GRENADE <> 0 then
R_RocketTrail(@oldorg, @ent.origin, 1)
else if ent.model.flags and EF_TRACER3 <> 0 then
R_RocketTrail(@oldorg, @ent.origin, 6);
ent.forcelink := false;
if (i = cl.viewentity) and (chase_active.value = 0) then
continue;
if cl_numvisedicts < MAX_VISEDICTS then
begin
cl_visedicts[cl_numvisedicts] := ent;
inc(cl_numvisedicts);
end;
end;
end;
procedure TClientMain.SendCmd;
var
cmd: usercmd_t;
begin
if cls.state <> ca_connected then
exit;
if cls.signon = SIGNONS then
begin
// get basic movement from keyboard
CL_BaseMove(@cmd);
// allow mice or other external controllers to add to the move
Input.Move(@cmd);
// send the unreliable message
CL_SendMove(@cmd);
end;
if cls.demoplayback then
begin
SZ_Clear(@cls._message);
exit;
end;
// send the reliable message
if cls._message.cursize = 0 then
exit; // no message at all
if not NET_CanSendMessage(cls.netcon) then
begin
Con_DPrintf('CL_WriteToServer: can''t send'#10);
exit;
end;
if NET_SendMessage(cls.netcon, @cls._message) = -1 then
Host_Error('CL_WriteToServer: lost server connection');
SZ_Clear(@cls._message);
end;
procedure TClientMain.SignonReply;
var
str: array[0..8191] of char;
begin
Con_DPrintf('CL_SignonReply: %d'#10, [cls.signon]);
case cls.signon of
1:
begin
MSG_WriteByte(@cls._message, clc_stringcmd);
MSG_WriteString(@cls._message, 'prespawn');
end;
2:
begin
MSG_WriteByte(@cls._message, clc_stringcmd);
MSG_WriteString(@cls._message, va('name "%s"'#10, [cl_name.text]));
MSG_WriteByte(@cls._message, clc_stringcmd);
MSG_WriteString(@cls._message, va('color %d %d'#10, [(int(cl_color.value) shr 4), int(cl_color.value) and 15]));
MSG_WriteByte(@cls._message, clc_stringcmd);
sprintf(str, 'spawn %s', [cls.spawnparms]);
MSG_WriteString(@cls._message, str);
end;
3:
begin
MSG_WriteByte(@cls._message, clc_stringcmd);
MSG_WriteString(@cls._message, 'begin');
Cache_Report; // print remaining memory
end;
4:
SCR_EndLoadingPlaque; // allow normal screen updates
end;
end;
initialization
ClientMain := TClientMain.Create;
finalization
ClientMain.Free;
end.
| 23.766252 | 128 | 0.603271 |
47a952c6a286e79314fa8270d9aa884beaf0ff5f | 18,298 | pas | Pascal | Import/Indy9/IdNetworkCalculator.pas | pavkam/wow-protocol | 2adc5df4cb15f29009dd6536fec18df5a8881ebb | [
"MIT"
]
| 2 | 2018-01-09T16:49:35.000Z | 2021-07-17T06:47:53.000Z | Import/Indy9/IdNetworkCalculator.pas | pavkam/wow-protocol | 2adc5df4cb15f29009dd6536fec18df5a8881ebb | [
"MIT"
]
| null | null | null | Import/Indy9/IdNetworkCalculator.pas | pavkam/wow-protocol | 2adc5df4cb15f29009dd6536fec18df5a8881ebb | [
"MIT"
]
| 2 | 2017-01-20T10:47:56.000Z | 2021-07-17T06:47:54.000Z | { $HDR$}
{**********************************************************************}
{ Unit archived using Team Coherence }
{ Team Coherence is Copyright 2002 by Quality Software Components }
{ }
{ For further information / comments, visit our WEB site at }
{ http://www.TeamCoherence.com }
{**********************************************************************}
{}
{ $Log: 10269: IdNetworkCalculator.pas
{
{ Rev 1.0 2002.11.12 10:47:10 PM czhower
}
unit IdNetworkCalculator;
interface
uses
SysUtils, Classes, IdBaseComponent;
type
TIpStruct = record
case integer of
0: (Byte4, Byte3, Byte2, Byte1: byte);
1: (FullAddr: Longword);
end;
TNetworkClass = (ID_NET_CLASS_A, ID_NET_CLASS_B, ID_NET_CLASS_C,
ID_NET_CLASS_D, ID_NET_CLASS_E);
const
ID_NC_MASK_LENGTH = 32;
ID_NETWORKCLASS = ID_NET_CLASS_A;
type
TIdIPAddressType = (IPLocalHost, IPLocalNetwork, IPReserved, IPInternetHost,
IPPrivateNetwork, IPLoopback, IPMulticast, IPFutureUse, IPGlobalBroadcast);
TIpProperty = Class(TPersistent)
protected
FReadOnly: boolean;
FOnChange: TNotifyEvent;
FByteArray: array[0..31] of boolean;
FDoubleWordValue: Longword;
FAsString: String;
FAsBinaryString: String;
FByte3: Byte;
FByte4: Byte;
FByte2: Byte;
FByte1: byte;
function GetAddressType: TIdIPAddressType;
procedure SetReadOnly(const Value: boolean);
procedure SetOnChange(const Value: TNotifyEvent);
function GetByteArray(Index: cardinal): boolean;
procedure SetAsBinaryString(const Value: String);
procedure SetAsDoubleWord(const Value: Longword);
procedure SetAsString(const Value: String);
procedure SetByteArray(Index: cardinal; const Value: boolean);
procedure SetByte4(const Value: Byte);
procedure SetByte1(const Value: byte);
procedure SetByte3(const Value: Byte);
procedure SetByte2(const Value: Byte);
//
property ReadOnly: boolean read FReadOnly write SetReadOnly default false;
public
procedure SetAll(One, Two, Three, Four: Byte); virtual;
procedure Assign(Source: Tpersistent); override;
//
property ByteArray[Index: cardinal]: boolean read GetByteArray write SetByteArray;
property AddressType: TIdIPAddressType read GetAddressType;
published
property Byte1: byte read FByte1 write SetByte1 stored false;
property Byte2: Byte read FByte2 write SetByte2 stored false;
property Byte3: Byte read FByte3 write SetByte3 stored false;
property Byte4: Byte read FByte4 write SetByte4 stored false;
property AsDoubleWord: Longword read FDoubleWordValue write SetAsDoubleWord stored false;
property AsBinaryString: String read FAsBinaryString write SetAsBinaryString stored false;
property AsString: String read FAsString write SetAsString;
property OnChange: TNotifyEvent read FOnChange write SetOnChange;
end;
TIdNetworkCalculator = class(TIdBaseComponent)
protected
FListIP: TStrings;
FNetworkMaskLength: cardinal;
FNetworkMask: TIpProperty;
FNetworkAddress: TIpProperty;
FNetworkClass: TNetworkClass;
FOnChange: TNotifyEvent;
FOnGenIPList: TNotifyEvent;
function GetNetworkClassAsString: String;
function GetIsAddressRoutable: Boolean;
procedure SetOnChange(const Value: TNotifyEvent);
procedure SetOnGenIPList(const Value: TNotifyEvent);
function GetListIP: TStrings;
procedure SetNetworkAddress(const Value: TIpProperty);
procedure SetNetworkMask(const Value: TIpProperty);
procedure SetNetworkMaskLength(const Value: cardinal);
procedure OnNetMaskChange(Sender: TObject);
procedure OnNetAddressChange(Sender: TObject);
public
function NumIP: integer;
function StartIP: String;
function EndIP: String;
procedure FillIPList;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
//
property ListIP: TStrings read GetListIP;
property NetworkClass: TNetworkClass read FNetworkClass;
property NetworkClassAsString: String read GetNetworkClassAsString;
property IsAddressRoutable: Boolean read GetIsAddressRoutable;
published
function IsAddressInNetwork(Address: String): Boolean;
property NetworkAddress: TIpProperty read FNetworkAddress write SetNetworkAddress;
property NetworkMask: TIpProperty read FNetworkMask write SetNetworkMask;
property NetworkMaskLength: cardinal read FNetworkMaskLength write SetNetworkMaskLength
default ID_NC_MASK_LENGTH;
property OnGenIPList: TNotifyEvent read FOnGenIPList write SetOnGenIPList;
property OnChange: TNotifyEvent read FOnChange write SetOnChange;
end;
implementation
uses
IdException, IdGlobal, IdResourceStrings;
{ TIdNetworkCalculator }
function IP(Byte1, Byte2, Byte3, Byte4: byte): TIpStruct;
begin
result.Byte1 := Byte1;
result.Byte2 := Byte2;
result.Byte3 := Byte3;
result.Byte4 := Byte4;
end;
function StrToIP(const value: string): TIPStruct;
var
strBuffers: Array [0..3] of String;
cardBuffers: Array[0..3] of cardinal;
StrWork: String;
begin
StrWork := Value;
// Separate the strings
strBuffers[0] := Fetch(StrWork, '.', true); {Do not Localize}
strBuffers[1] := Fetch(StrWork, '.', true); {Do not Localize}
strBuffers[2] := Fetch(StrWork, '.', true); {Do not Localize}
strBuffers[3] := StrWork;
try
cardBuffers[0] := StrToInt(strBuffers[0]);
cardBuffers[1] := StrToInt(strBuffers[1]);
cardBuffers[2] := StrToInt(strBuffers[2]);
cardBuffers[3] := StrToInt(strBuffers[3]);
except
on e: exception do
Raise exception.Create(Format( RSNETCALInvalidIPString, [Value]));
end;
// range check
if not(cardBuffers[0] in [0..255]) then
raise EIdException.Create(Format( RSNETCALInvalidIPString, [Value]));
if not(cardBuffers[1] in [0..255]) then
raise EIdException.Create(Format( RSNETCALInvalidIPString, [Value]));
if not(cardBuffers[2] in [0..255]) then
raise EIdException.Create(Format( RSNETCALInvalidIPString, [Value]));
if not(cardBuffers[3] in [0..255]) then
raise EIdException.Create(Format( RSNETCALInvalidIPString, [Value]));
result := IP(cardBuffers[0], cardBuffers[1], cardBuffers[2], cardBuffers[3]);
end;
constructor TIdNetworkCalculator.Create(AOwner: TComponent);
begin
inherited;
FNetworkMask := TIpProperty.Create;
FNetworkAddress := TIpProperty.Create;
FNetworkMask.OnChange := OnNetMaskChange;
FNetworkAddress.OnChange := OnNetAddressChange;
FListIP := TStringList.Create;
FNetworkClass := ID_NETWORKCLASS;
NetworkMaskLength := ID_NC_MASK_LENGTH;
end;
destructor TIdNetworkCalculator.Destroy;
begin
FNetworkMask.Free;
FNetworkAddress.Free;
FListIP.Free;
inherited;
end;
procedure TIdNetworkCalculator.FillIPList;
var
i: Cardinal;
BaseIP: TIpStruct;
begin
if FListIP.Count = 0 then
begin
// prevent to start a long loop in the IDE (will lock delphi)
if (csDesigning in ComponentState) and (NumIP > 1024) then
begin
FListIP.text := Format(RSNETCALConfirmLongIPList,[NumIP]);
end
else
begin
BaseIP.FullAddr := NetworkAddress.AsDoubleWord AND NetworkMask.AsDoubleWord;
// preallocate the memory for the list
FListIP.Capacity := NumIP;
// Lock the list so we won't be "repainting" the whole time... {Do not Localize}
FListIP.BeginUpdate;
try
for i := 1 to (NumIP - 1) do
begin
Inc(BaseIP.FullAddr);
FListIP.append(format('%d.%d.%d.%d', [BaseIP.Byte1, BaseIP.Byte2, BaseIP.Byte3, BaseIP.Byte4])); {Do not Localize}
end;
finally
FListIP.EndUpdate;
end;
end;
end;
end;
function TIdNetworkCalculator.GetListIP: TStrings;
begin
FillIPList;
result := FListIP;
end;
function TIdNetworkCalculator.IsAddressInNetwork(Address: String): Boolean;
var
IPStruct: TIPStruct;
begin
IPStruct := StrToIP(Address);
result := (IPStruct.FullAddr AND NetworkMask.FDoubleWordValue) = (NetworkAddress.FDoubleWordValue AND NetworkMask.FDoubleWordValue);
end;
procedure TIdNetworkCalculator.OnNetAddressChange(Sender: TObject);
begin
FListIP.Clear;
// RFC 1365
if IndyPos('0', NetworkAddress.AsBinaryString) = 1 then {Do not Localize}
begin
fNetworkClass := ID_NET_CLASS_A;
end;
if IndyPos('10', NetworkAddress.AsBinaryString) = 1 then {Do not Localize}
begin
fNetworkClass := ID_NET_CLASS_B;
end;
if IndyPos('110', NetworkAddress.AsBinaryString) = 1 then {Do not Localize}
begin
fNetworkClass := ID_NET_CLASS_C;
end;
// Network class D is reserved for multicast
if IndyPos('1110', NetworkAddress.AsBinaryString) = 1 then {Do not Localize}
begin
fNetworkClass := ID_NET_CLASS_D;
end;
// network class E is reserved and shouldn't be used {Do not Localize}
if IndyPos('1111', NetworkAddress.AsBinaryString) = 1 then {Do not Localize}
begin
fNetworkClass := ID_NET_CLASS_E;
end;
if assigned( FOnChange ) then
FOnChange(Self);
end;
procedure TIdNetworkCalculator.OnNetMaskChange(Sender: TObject);
var
sBuffer: string;
InitialMaskLength: Cardinal;
begin
FListIP.Clear;
InitialMaskLength := FNetworkMaskLength;
// A network mask MUST NOT contains holes.
sBuffer := FNetworkMask.AsBinaryString;
while (length(sBuffer) > 0) and (sBuffer[1] = '1') do {Do not Localize}
begin
Delete(sBuffer, 1, 1);
end; { while }
if IndyPos('1', sBuffer) > 0 then {Do not Localize}
begin
NetworkMaskLength := InitialMaskLength;
raise EIdexception.Create(RSNETCALCInvalidNetworkMask); // 'Invalid network mask' {Do not Localize}
end
else
begin
// set the net mask length
NetworkMaskLength := 32 - Length(sBuffer);
end;
if assigned( FOnChange ) then
FOnChange(Self);
end;
procedure TIdNetworkCalculator.SetNetworkAddress(const Value: TIpProperty);
begin
FNetworkAddress.Assign(Value);
end;
procedure TIdNetworkCalculator.SetNetworkMask(const Value: TIpProperty);
begin
FNetworkMask.Assign(Value);
end;
procedure TIdNetworkCalculator.SetNetworkMaskLength(const Value: cardinal);
var
LBuffer: Cardinal;
begin
FNetworkMaskLength := Value;
if Value > 0 then begin
LBuffer := High(Cardinal) shl (32 - Value);
end else begin
LBuffer := 0;
end;
FNetworkMask.AsDoubleWord := LBuffer;
end;
procedure TIdNetworkCalculator.SetOnGenIPList(const Value: TNotifyEvent);
begin
FOnGenIPList := Value;
end;
procedure TIdNetworkCalculator.SetOnChange(const Value: TNotifyEvent);
begin
FOnChange := Value;
end;
function TIdNetworkCalculator.GetNetworkClassAsString: String;
begin
Case FNetworkClass of
ID_NET_CLASS_A:
result := 'A'; {Do not Localize}
ID_NET_CLASS_B:
result := 'B'; {Do not Localize}
ID_NET_CLASS_C:
result := 'C'; {Do not Localize}
ID_NET_CLASS_D:
result := 'D'; {Do not Localize}
ID_NET_CLASS_E:
result := 'E'; {Do not Localize}
end; // case
end;
function TIdNetworkCalculator.GetIsAddressRoutable: Boolean;
begin
// RFC
result := (NetworkAddress.Byte1 = 10) or
((NetworkAddress.Byte1 = 172) and (NetworkAddress.Byte2 in [16..31])) or
((NetworkAddress.Byte1 = 192) and (NetworkAddress.Byte2 = 168));
end;
{ TIpProperty }
procedure TIpProperty.Assign(Source: Tpersistent);
begin
if Source is TIpProperty then
with source as TIpProperty do
begin
Self.SetAll(Byte1, Byte2, Byte3, Byte4);
end; { with }
if assigned( FOnChange ) then
FOnChange( Self );
inherited;
end;
function TIpProperty.GetByteArray(Index: cardinal): boolean;
begin
result := FByteArray[index]
end;
procedure TIpProperty.SetAll(One, Two, Three, Four: Byte);
var
i: Integer;
InitialIP, IpStruct: TIpStruct;
begin
// Set the individual bytes
InitialIP := IP(FByte1, FByte2, FByte3, FByte4);
FByte1 := One;
FByte2 := Two;
FByte3 := Three;
FByte4 := Four;
// Set the DWord Value
IpStruct.Byte1 := Byte1;
IpStruct.Byte2 := Byte2;
IpStruct.Byte3 := Byte3;
IpStruct.Byte4 := Byte4;
FDoubleWordValue := IpStruct.FullAddr;
// Set the bits array and the binary string
SetLength(FAsBinaryString, 32);
// Second, fill the array
for i := 1 to 32 do
begin
FByteArray[i - 1] := ((FDoubleWordValue shl (i-1)) shr 31) = 1;
if FByteArray[i - 1] then
FAsBinaryString[i] := '1' {Do not Localize}
else
FAsBinaryString[i] := '0'; {Do not Localize}
end;
// Set the string
FAsString := Format('%d.%d.%d.%d', [FByte1, FByte2, FByte3, FByte4]); {Do not Localize}
IpStruct := IP(FByte1, FByte2, FByte3, FByte4);
if IpStruct.FullAddr <> InitialIP.FullAddr then
begin
if assigned( FOnChange ) then
FOnChange( self );
end;
end;
procedure TIpProperty.SetAsBinaryString(const Value: String);
var
IPStruct: TIPStruct;
i: Integer;
begin
if ReadOnly then
exit;
if Length(Value) <> 32 then
raise EIdException.Create(RSNETCALCInvalidValueLength) // 'Invalid value length: Should be 32.' {Do not Localize}
else
begin
if not AnsiSameText( Value, FAsBinaryString) then
begin
IPStruct.FullAddr := 0;
for i := 1 to 32 do
begin
if Value[i] <> '0' then {Do not Localize}
IPStruct.FullAddr := IPStruct.FullAddr + (1 shl (32 - i));
SetAll(IPStruct.Byte1, IPStruct.Byte2, IPStruct.Byte3, IPStruct.Byte4);
end;
end;
end;
end;
procedure TIpProperty.SetAsDoubleWord(const Value: Cardinal);
var
IpStruct: TIpStruct;
begin
if ReadOnly then
exit;
IpStruct.FullAddr := value;
SetAll(IpStruct.Byte1, IpStruct.Byte2, IpStruct.Byte3, IpStruct.Byte4);
end;
procedure TIpProperty.SetAsString(const Value: String);
var
IPStruct: TIPStruct;
begin
if ReadOnly then
exit;
IPStruct := StrToIP(value);
SetAll(IPStruct.Byte1, IPStruct.Byte2, IPStruct.Byte3, IPStruct.Byte4);
end;
procedure TIpProperty.SetByteArray(Index: cardinal; const Value: boolean);
var
IPStruct: TIpStruct;
begin
if ReadOnly then
exit;
if FByteArray[Index] <> value then
begin
FByteArray[Index] := Value;
IPStruct.FullAddr := FDoubleWordValue;
if Value then
IPStruct.FullAddr := IPStruct.FullAddr + (1 shl index)
else
IPStruct.FullAddr := IPStruct.FullAddr - (1 shl index);
SetAll(IPStruct.Byte1, IPStruct.Byte2, IPStruct.Byte3, IPStruct.Byte4);
end;
end;
procedure TIpProperty.SetByte4(const Value: Byte);
begin
if ReadOnly then
exit;
if FByte4 <> value then
begin
FByte4 := Value;
SetAll(FByte1, FByte2, FByte3, FByte4);
end;
end;
procedure TIpProperty.SetByte1(const Value: byte);
begin
if FByte1 <> value then
begin
FByte1 := Value;
SetAll(FByte1, FByte2, FByte3, FByte4);
end;
end;
procedure TIpProperty.SetByte3(const Value: Byte);
begin
if FByte3 <> value then
begin
FByte3 := Value;
SetAll(FByte1, FByte2, FByte3, FByte4);
end;
end;
procedure TIpProperty.SetByte2(const Value: Byte);
begin
if ReadOnly then
exit;
if FByte2 <> value then
begin
FByte2 := Value;
SetAll(FByte1, FByte2, FByte3, FByte4);
end;
end;
procedure TIpProperty.SetOnChange(const Value: TNotifyEvent);
begin
FOnChange := Value;
end;
procedure TIpProperty.SetReadOnly(const Value: boolean);
begin
FReadOnly := Value;
end;
function TIdNetworkCalculator.EndIP: String;
var
IP: TIpStruct;
begin
IP.FullAddr := NetworkAddress.AsDoubleWord AND NetworkMask.AsDoubleWord;
Inc(IP.FullAddr, NumIP - 1);
result := Format('%d.%d.%d.%d', [IP.Byte1, IP.Byte2, IP.Byte3, IP.Byte4]); {Do not Localize}
end;
function TIdNetworkCalculator.NumIP: integer;
begin
NumIP := 1 shl (32 - NetworkMaskLength);
end;
function TIdNetworkCalculator.StartIP: String;
var
IP: TIpStruct;
begin
IP.FullAddr := NetworkAddress.AsDoubleWord AND NetworkMask.AsDoubleWord;
result := Format('%d.%d.%d.%d', [IP.Byte1, IP.Byte2, IP.Byte3, IP.Byte4]); {Do not Localize}
end;
function TIpProperty.GetAddressType: TIdIPAddressType;
// based on http://www.ora.com/reference/dictionary/terms/I/IP_Address.htm
begin
Result := IPInternetHost;
case FByte1 of
{localhost or local network}
0 : if AsDoubleWord = 0 then
begin
Result := IPLocalHost;
end
else
begin
Result := IPLocalNetwork;
end;
{Private network allocations}
10 : Result := IPPrivateNetwork;
172 : if Byte2 = 16 then
begin
Result := IPPrivateNetwork;
end;
192 : if Byte2 = 68 then
begin
Result := IPPrivateNetwork;
end
else
begin
if (Byte2 = 0) and (Byte3 = 0) then
begin
Result := IPReserved;
end;
end;
{loopback}
127 : Result := IPLoopback;
255 : if AsDoubleWord = $FFFFFFFF then
begin
Result := IPGlobalBroadcast;
end
else
begin
Result := IPFutureUse;
end;
{Reserved}
128 : if Byte2 = 0 then
begin
Result := IPReserved;
end;
191 : if (Byte2 = 255) and (Byte3 = 255) then
begin
Result := IPReserved;
end;
223 : if (Byte2 = 255) and (Byte3 = 255) then
begin
Result := IPReserved;
end;
end;
{Multicast}
if (Byte1 >= 224) and (Byte1 <= 239) then
begin
Result := IPMulticast;
end;
{Future Use}
if (Byte1 >= 240) and (Byte1 <= 254) then
begin
Result := IPFutureUse;
end;
end;
end.
| 29.656402 | 135 | 0.662477 |
4723d2e6d779a49bf72419a238a81cced9188729 | 17,442 | pas | Pascal | Components/JVCL/qrun/JvQWizardRouteMapList.pas | sabatex/Delphi | 0efbe6eb38bf8aa2bf269d1866741266e90b9cbf | [
"MIT"
]
| null | null | null | Components/JVCL/qrun/JvQWizardRouteMapList.pas | sabatex/Delphi | 0efbe6eb38bf8aa2bf269d1866741266e90b9cbf | [
"MIT"
]
| null | null | null | Components/JVCL/qrun/JvQWizardRouteMapList.pas | sabatex/Delphi | 0efbe6eb38bf8aa2bf269d1866741266e90b9cbf | [
"MIT"
]
| 1 | 2019-12-24T08:39:18.000Z | 2019-12-24T08:39:18.000Z | {******************************************************************************}
{* WARNING: JEDI VCL To CLX Converter generated unit. *}
{* Manual modifications will be lost on next release. *}
{******************************************************************************}
{-----------------------------------------------------------------------------
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: JvWizardRouteMapList.PAS, released on 2004-02-14.
The Initial Developer of the Original Code is Peter Thornqvist.
Portions created by Peter Thornqvist are Copyright (C) 2004 Peter Thornqvist
Contributor(s):
You may retrieve the latest version of this file at the Project JEDI's JVCL home page,
located at http://jvcl.sourceforge.net
Purpose:
Route map that displays pages as a list
History:
Known Issues:
-----------------------------------------------------------------------------}
// $Id: JvQWizardRouteMapList.pas,v 1.21 2005/04/16 19:33:44 asnepvangers Exp $
unit JvQWizardRouteMapList;
{$I jvcl.inc}
interface
uses
{$IFDEF UNITVERSIONING}
JclUnitVersioning,
{$ENDIF UNITVERSIONING}
SysUtils, Classes,
QWindows, QMessages, QGraphics, QControls, QForms,
QImgList,
JvQTypes, JvQConsts, JvQJVCLUtils,
JvQWizard;
type
TJvWizardDrawRouteMapListItem = procedure(Sender: TObject; ACanvas: TCanvas;
ARect: TRect; MousePos: TPoint; PageIndex: Integer; var DefaultDraw: Boolean) of object;
TRouteMapListItemText = (itNone, itCaption, itTitle, itSubtitle);
TJvWizardRouteMapList = class(TJvWizardRouteMapControl)
private
FItemHeight: Integer;
FVertOffset: Integer;
FHorzOffset: Integer;
FClickable: Boolean;
FIncludeDisabled: Boolean;
FHotTrackFont: TFont;
FActiveFont: TFont;
FHotTrackCursor, FOldCursor: TCursor;
FOnDrawItem: TJvWizardDrawRouteMapListItem;
FAlignment: TAlignment;
FTextOffset: Integer;
FShowImages: Boolean;
FItemColor: TColor;
FRounded: Boolean;
FItemText: TRouteMapListItemText;
FHotTrack: Boolean;
FCurvature: Integer;
FHotTrackBorder: Integer;
FBorderColor: TColor;
FTextOnly: Boolean;
FHotTrackFontOptions: TJvTrackFontOptions;
FActiveFontOptions: TJvTrackFontOptions;
procedure SetItemHeight(const Value: Integer);
procedure SetHorzOffset(const Value: Integer);
procedure SetVertOffset(const Value: Integer);
procedure SetIncludeDisabled(const Value: Boolean);
procedure SetActiveFont(const Value: TFont);
procedure SetHotTrackFont(const Value: TFont);
procedure DoFontChange(Sender: TObject);
procedure SetAlignment(const Value: TAlignment);
procedure SetTextOffset(const Value: Integer);
procedure SetShowImages(const Value: Boolean);
procedure SetItemColor(const Value: TColor);
procedure SetRounded(const Value: Boolean);
procedure SetItemText(const Value: TRouteMapListItemText);
procedure SetCurvature(const Value: Integer);
procedure SetTextOnly(const Value: Boolean);
procedure SetBorderColor(Value: TColor);
procedure SetActiveFontOptions(const Value: TJvTrackFontOptions);
procedure SetHotTrackFontOptions(const Value: TJvTrackFontOptions);
protected
procedure DrawPageItem(ACanvas: TCanvas; ARect: TRect; MousePos: TPoint; PageIndex: Integer); virtual;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
function PageAtPos(Pt: TPoint): TJvWizardCustomPage; override;
procedure Paint; override;
procedure Loaded; override;
procedure CursorChanged; override;
procedure FontChanged; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property ActiveFont: TFont read FActiveFont write SetActiveFont;
property ActiveFontOptions: TJvTrackFontOptions read FActiveFontOptions write SetActiveFontOptions default
DefaultTrackFontOptions;
property Alignment: TAlignment read FAlignment write SetAlignment default taCenter;
property Clickable: Boolean read FClickable write FClickable default True;
property Color default $00C08000;
property Curvature: Integer read FCurvature write SetCurvature default 9;
property Font;
property HorzOffset: Integer read FHorzOffset write SetHorzOffset default 8;
property HotTrackBorder: Integer read FHotTrackBorder write FHotTrackBorder default 2;
property HotTrackCursor: TCursor read FHotTrackCursor write FHotTrackCursor default crHandPoint;
property HotTrack: Boolean read FHotTrack write FHotTrack default True;
property HotTrackFont: TFont read FHotTrackFont write SetHotTrackFont;
property HotTrackFontOptions: TJvTrackFontOptions read FHotTrackFontOptions write SetHotTrackFontOptions default
DefaultTrackFontOptions;
property Image;
property TextOnly: Boolean read FTextOnly write SetTextOnly default False;
property IncludeDisabled: Boolean read FIncludeDisabled write SetIncludeDisabled default False;
property BorderColor: TColor read FBorderColor write SetBorderColor default clNavy;
property ItemColor: TColor read FItemColor write SetItemColor default clCream;
property ItemHeight: Integer read FItemHeight write SetItemHeight default 25;
property ItemText: TRouteMapListItemText read FItemText write SetItemText default itCaption;
property Rounded: Boolean read FRounded write SetRounded default False;
property ShowImages: Boolean read FShowImages write SetShowImages default False;
property TextOffset: Integer read FTextOffset write SetTextOffset default 8;
property VertOffset: Integer read FVertOffset write SetVertOffset default 8;
property OnDrawItem: TJvWizardDrawRouteMapListItem read FOnDrawItem write FOnDrawItem;
end;
{$IFDEF UNITVERSIONING}
const
UnitVersioning: TUnitVersionInfo = (
RCSfile: '$RCSfile: JvQWizardRouteMapList.pas,v $';
Revision: '$Revision: 1.21 $';
Date: '$Date: 2005/04/16 19:33:44 $';
LogPath: 'JVCL\run'
);
{$ENDIF UNITVERSIONING}
implementation
constructor TJvWizardRouteMapList.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FActiveFont := TFont.Create;
FActiveFont.Style := [fsBold];
FActiveFont.OnChange := DoFontChange;
FHotTrackFont := TFont.Create;
FHotTrackFont.Color := clNavy;
FHotTrackFont.Style := [fsUnderline];
FHotTrackFont.OnChange := DoFontChange;
FActiveFontOptions := DefaultTrackFontOptions;
FHotTrackFontOptions := DefaultTrackFontOptions;
Color := $00C08000;
FHotTrackCursor := crHandPoint;
FVertOffset := 8;
FHorzOffset := 8;
FItemHeight := 25;
FClickable := True;
FAlignment := taCenter;
FTextOffset := 8;
FBorderColor := clNavy;
FItemColor := clCream;
FItemText := itCaption;
FHotTrack := True;
FCurvature := 9;
FHotTrackBorder := 2;
FTextOnly := False;
end;
destructor TJvWizardRouteMapList.Destroy;
begin
FHotTrackFont.Free;
FActiveFont.Free;
inherited Destroy;
end;
procedure TJvWizardRouteMapList.Loaded;
begin
inherited Loaded;
FOldCursor := Cursor;
end;
procedure TJvWizardRouteMapList.MouseMove(Shift: TShiftState;
X, Y: Integer);
var
P: TJvWizardCustomPage;
begin
inherited MouseMove(Shift, X, Y);
if Clickable and HotTrack then
begin
P := PageAtPos(Point(X, Y));
if (P <> nil) and P.Enabled then
begin
if Cursor <> FHotTrackCursor then
FOldCursor := Cursor;
Cursor := FHotTrackCursor;
Refresh;
end
else
if Cursor <> FOldCursor then
begin
Cursor := FOldCursor;
Refresh;
end;
end;
end;
function TJvWizardRouteMapList.PageAtPos(Pt: TPoint): TJvWizardCustomPage;
var
R: TRect;
I: Integer;
begin
Result := nil;
if not Clickable then
Exit;
R := ClientRect;
InflateRect(R, -HorzOffset, -VertOffset);
R.Bottom := R.Top + ItemHeight;
for I := 0 to PageCount - 1 do
begin
if Pages[I].Enabled or IncludeDisabled then
begin
if PtInRect(R, Pt) then
begin
Result := Pages[I];
Exit;
end;
OffsetRect(R, 0, ItemHeight);
end;
end;
end;
procedure TJvWizardRouteMapList.Paint;
var
I: Integer;
R: TRect;
P: TPoint;
begin
Canvas.Brush.Style := bsSolid;
Canvas.Brush.Color := Color;
if BorderColor = clNone then
Canvas.Pen.Color := Color
else
Canvas.Pen.Color := BorderColor;
GetCursorPos(P);
P := ScreenToClient(P);
R := ClientRect;
if not HasPicture then
Canvas.Rectangle(R)
else
Image.PaintTo(Canvas, R);
if ItemHeight <= 0 then
Exit;
InflateRect(R, -HorzOffset, -VertOffset);
R.Bottom := R.Top + ItemHeight;
for I := 0 to PageCount - 1 do
if Pages[I].Enabled or IncludeDisabled then
begin
DrawPageItem(Canvas, R, P, I);
OffsetRect(R, 0, ItemHeight);
if R.Bottom >= ClientHeight - 2 then
Break;
end;
end;
procedure TJvWizardRouteMapList.DrawPageItem(ACanvas: TCanvas; ARect: TRect; MousePos: TPoint; PageIndex: Integer);
const
cAlignment: array [TAlignment] of Cardinal = (DT_LEFT, DT_RIGHT, DT_CENTER);
cWordWrap: array [Boolean] of Cardinal = (DT_SINGLELINE, DT_WORDBREAK);
var
DefaultDraw: Boolean;
ATop, ALeft: Integer;
AOrigRect: TRect;
BkColor: TColor;
S: string;
begin
ACanvas.Lock;
try
AOrigRect := ARect;
ACanvas.Font := Font;
if Assigned(Wizard) and (Pages[PageIndex] = Wizard.ActivePage) then
ACanvas.Font := ActiveFont
else
if PtInRect(ARect, MousePos) and Pages[PageIndex].Enabled and HotTrack and Clickable then
ACanvas.Font := HotTrackFont
else
if not Pages[PageIndex].Enabled then
ACanvas.Font.Color := clGrayText;
ACanvas.Brush.Color := ItemColor;
ACanvas.Pen.Color := Color;
DefaultDraw := True;
if Assigned(FOnDrawItem) then
FOnDrawItem(Self, ACanvas, ARect, MousePos, PageIndex, DefaultDraw);
if DefaultDraw then
begin
case ItemText of
itCaption:
S := Pages[PageIndex].Caption;
itTitle:
S := Pages[PageIndex].Title.Text;
itSubtitle:
S := Pages[PageIndex].Subtitle.Text;
end;
if not TextOnly then
begin
if ItemColor = clNone then
ACanvas.Brush.Style := bsClear;
if Rounded then
ACanvas.RoundRect(ARect.Left, ARect.Top, ARect.Right, ARect.Bottom, Curvature, Curvature)
else
ACanvas.Rectangle(ARect);
if ShowImages and Assigned(Wizard) and Assigned(Wizard.HeaderImages) then
begin
ATop := ((ARect.Bottom - ARect.Top) - Wizard.HeaderImages.Height) div 2;
BkColor := ACanvas.Brush.Color;
case Alignment of
taLeftJustify:
begin
Wizard.HeaderImages.Draw(ACanvas, ARect.Left + 4, ARect.Top + ATop, Pages[PageIndex].Header.ImageIndex, itImage, Pages[PageIndex].Enabled);
Inc(ARect.Left, Wizard.HeaderImages.Width + 4);
end;
taRightJustify:
begin
Wizard.HeaderImages.Draw(ACanvas, ARect.Right - Wizard.HeaderImages.Width - 4, ARect.Top + ATop,
Pages[PageIndex].Header.ImageIndex, itImage, Pages[PageIndex].Enabled);
Dec(ARect.Right, Wizard.HeaderImages.Width + 4);
end;
taCenter:
begin
ALeft := ((ARect.Right - ARect.Left) - Wizard.HeaderImages.Width) div 2;
Inc(ARect.Top, 4);
Wizard.HeaderImages.Draw(ACanvas, ARect.Left + ALeft, ARect.Top + 8,
Pages[PageIndex].Header.ImageIndex, itImage, Pages[PageIndex].Enabled);
Inc(ARect.Top, Wizard.HeaderImages.Height);
// if ItemText = itSubtitle then
// Inc(ARect.Top, 16);
end;
end;
if not Pages[PageIndex].Enabled then
begin
// (p3) TImageList changes the canvas colors when drawing disabled images, so we reset them explicitly
SetBkColor(ACanvas.Handle, BkColor);
SetTextColor(ACanvas.Handle, ColorToRGB(clGrayText));
end;
end;
end
else
ACanvas.Brush.Style := bsClear;
case Alignment of
taLeftJustify:
Inc(ARect.Left, TextOffset);
taRightJustify:
Dec(ARect.Right, TextOffset);
taCenter:
InflateRect(ARect, -TextOffset div 2, -TextOffset div 2);
end;
if ItemText = itSubtitle then
begin
Inc(ARect.Top, TextOffset);
InflateRect(ARect, -TextOffset, 0);
end;
if (ItemText <> itNone) and ((ARect.Bottom - ARect.Top) > abs(ACanvas.Font.Height)) then
DrawText(ACanvas.Handle, PChar(S), Length(S), ARect,
cAlignment[Alignment] or cWordWrap[ItemText = itSubtitle] or DT_VCENTER or DT_EDITCONTROL or DT_END_ELLIPSIS);
if not TextOnly and HotTrack and (HotTrackBorder > 0) and PtInRect(AOrigRect, MousePos) then
begin
ACanvas.Brush.Style := bsClear;
ACanvas.Pen.Color := HotTrackFont.Color;
ACanvas.Pen.Width := HotTrackBorder;
if Rounded then
with AOrigRect do
ACanvas.RoundRect(Left, Top, Right, Bottom, Curvature, Curvature)
else
ACanvas.Rectangle(AOrigRect);
ACanvas.Brush.Style := bsSolid;
ACanvas.Pen.Width := 1;
end;
end;
finally
ACanvas.Unlock;
end;
end;
procedure TJvWizardRouteMapList.SetHorzOffset(const Value: Integer);
begin
if FHorzOffset <> Value then
begin
FHorzOffset := Value;
Invalidate;
end;
end;
procedure TJvWizardRouteMapList.SetItemHeight(const Value: Integer);
begin
if FItemHeight <> Value then
begin
FItemHeight := Value;
Invalidate;
end;
end;
procedure TJvWizardRouteMapList.SetVertOffset(const Value: Integer);
begin
if FVertOffset <> Value then
begin
FVertOffset := Value;
Invalidate;
end;
end;
procedure TJvWizardRouteMapList.SetIncludeDisabled(const Value: Boolean);
begin
if FIncludeDisabled <> Value then
begin
FIncludeDisabled := Value;
Invalidate;
end;
end;
procedure TJvWizardRouteMapList.SetActiveFont(const Value: TFont);
begin
FActiveFont.Assign(Value);
end;
procedure TJvWizardRouteMapList.SetHotTrackFont(const Value: TFont);
begin
FHotTrackFont.Assign(Value);
end;
procedure TJvWizardRouteMapList.DoFontChange(Sender: TObject);
begin
Invalidate;
end;
procedure TJvWizardRouteMapList.SetAlignment(const Value: TAlignment);
begin
if FAlignment <> Value then
begin
FAlignment := Value;
Invalidate;
end;
end;
procedure TJvWizardRouteMapList.SetTextOffset(const Value: Integer);
begin
if FTextOffset <> Value then
begin
FTextOffset := Value;
Invalidate;
end;
end;
procedure TJvWizardRouteMapList.SetShowImages(const Value: Boolean);
begin
if FShowImages <> Value then
begin
FShowImages := Value;
Invalidate;
end;
end;
procedure TJvWizardRouteMapList.SetItemColor(const Value: TColor);
begin
if FItemColor <> Value then
begin
FItemColor := Value;
Invalidate;
end;
end;
procedure TJvWizardRouteMapList.SetRounded(const Value: Boolean);
begin
if FRounded <> Value then
begin
FRounded := Value;
Invalidate;
end;
end;
procedure TJvWizardRouteMapList.SetItemText(const Value: TRouteMapListItemText);
begin
if FItemText <> Value then
begin
FItemText := Value;
Invalidate;
end;
end;
procedure TJvWizardRouteMapList.SetCurvature(const Value: Integer);
begin
if FCurvature <> Value then
begin
FCurvature := Value;
Invalidate;
end;
end;
procedure TJvWizardRouteMapList.SetActiveFontOptions(const Value: TJvTrackFontOptions);
begin
if FActiveFontOptions <> Value then
begin
FActiveFontOptions := Value;
UpdateTrackFont(ActiveFont, Font, FActiveFontOptions);
end;
end;
procedure TJvWizardRouteMapList.SetHotTrackFontOptions(const Value: TJvTrackFontOptions);
begin
if FHotTrackFontOptions <> Value then
begin
FHotTrackFontOptions := Value;
UpdateTrackFont(HotTrackFont, Font, FHotTrackFontOptions);
end;
end;
procedure TJvWizardRouteMapList.SetBorderColor(Value: TColor);
begin
if Value <> FBorderColor then
begin
FBorderColor := Value;
Invalidate;
end;
end;
procedure TJvWizardRouteMapList.SetTextOnly(const Value: Boolean);
begin
if Value <> FTextOnly then
begin
FTextOnly := Value;
Invalidate;
end;
end;
procedure TJvWizardRouteMapList.CursorChanged;
begin
inherited CursorChanged;
if (Cursor <> FHotTrackCursor) and (Cursor <> FOldCursor) then
FOldCursor := Cursor;
end;
procedure TJvWizardRouteMapList.FontChanged;
begin
inherited FontChanged;
UpdateTrackFont(HotTrackFont, Font, FHotTrackFontOptions);
UpdateTrackFont(ActiveFont, Font, FActiveFontOptions);
end;
{$IFDEF UNITVERSIONING}
initialization
RegisterUnitVersion(HInstance, UnitVersioning);
finalization
UnregisterUnitVersion(HInstance);
{$ENDIF UNITVERSIONING}
end.
| 29.866438 | 157 | 0.697569 |
6acdebcbc8d9a781d25065742773fe444df9cc43 | 12,273 | pas | Pascal | PHPTypes.pas | bgarrels/PHP4Lazarus | 2ba45b156a5a590ea3aa049bb8e5e8bb2b86aea9 | [
"PHP-3.0"
]
| 11 | 2015-10-13T07:53:21.000Z | 2020-11-07T10:18:32.000Z | PHPTypes.pas | rnapoles/PHP4Lazarus | 2ba45b156a5a590ea3aa049bb8e5e8bb2b86aea9 | [
"PHP-3.0"
]
| null | null | null | PHPTypes.pas | rnapoles/PHP4Lazarus | 2ba45b156a5a590ea3aa049bb8e5e8bb2b86aea9 | [
"PHP-3.0"
]
| 5 | 2015-04-20T08:37:16.000Z | 2021-02-04T22:08:57.000Z | {*******************************************************}
{ PHP4Delphi }
{ PHP - Delphi interface }
{ }
{ Author: }
{ Serhiy Perevoznyk }
{ serge_perevoznyk@hotmail.com }
{ http://users.chello.be/ws36637 }
{*******************************************************}
{$I PHP.INC}
{ $Id: phpTypes.pas,v 7.2 10/2009 delphi32 Exp $ }
unit PHPTypes;
interface
uses
{$IFNDEF FPC} Windows, {$ELSE} LCLType,{$ENDIF} ZENDTypes;
{$IFDEF PHP4}
const
phpVersion = 4;
{$ELSE}
const
phpVersion = 5;
{$ENDIF}
const
TRequestName : array [0..3] of AnsiString =
('GET',
'PUT',
'POST',
'HEAD');
const
// connection status states
PHP_CONNECTION_NORMAL = 0;
PHP_CONNECTION_ABORTED = 1;
PHP_CONNECTION_TIMEOUT = 2;
PARSE_POST = 0;
PARSE_GET = 1;
PARSE_COOKIE = 2;
PARSE_STRING = 3;
const
SAPI_HEADER_ADD = (1 shl 0);
SAPI_HEADER_DELETE_ALL = (1 shl 1);
SAPI_HEADER_SEND_NOW = (1 shl 2);
SAPI_HEADER_SENT_SUCCESSFULLY = 1;
SAPI_HEADER_DO_SEND = 2;
SAPI_HEADER_SEND_FAILED = 3;
SAPI_DEFAULT_MIMETYPE = 'text/html';
SAPI_DEFAULT_CHARSET = '';
SAPI_PHP_VERSION_HEADER = 'X-Powered-By: PHP';
const
short_track_vars_names : array [0..5] of AnsiString =
('_POST',
'_GET',
'_COOKIE',
'_SERVER',
'_ENV',
'_FILES' );
const
PHP_ENTRY_NAME_COLOR = '#ccccff';
PHP_CONTENTS_COLOR = '#cccccc';
PHP_HEADER_COLOR = '#9999cc';
PHP_INFO_GENERAL = (1 shl 0);
PHP_INFO_CREDITS = (1 shl 1);
PHP_INFO_CONFIGURATION = (1 shl 2);
PHP_INFO_MODULES = (1 shl 3);
PHP_INFO_ENVIRONMENT = (1 shl 4);
PHP_INFO_VARIABLES = (1 shl 5);
PHP_INFO_LICENSE = (1 shl 6);
PHP_INFO_ALL = $FFFFFFFF;
PHP_CREDITS_GROUP = (1 shl 0);
PHP_CREDITS_GENERAL = (1 shl 1);
PHP_CREDITS_SAPI = (1 shl 2);
PHP_CREDITS_MODULES = (1 shl 3);
PHP_CREDITS_DOCS = (1 shl 4);
PHP_CREDITS_FULLPAGE = (1 shl 5);
PHP_CREDITS_QA = (1 shl 6);
PHP_CREDITS_WEB = (1 shl 7);
PHP_CREDITS_ALL = $FFFFFFFF;
PHP_LOGO_GUID = 'PHPE9568F34-D428-11d2-A769-00AA001ACF42';
PHP_EGG_LOGO_GUID = 'PHPE9568F36-D428-11d2-A769-00AA001ACF42';
ZEND_LOGO_GUID = 'PHPE9568F35-D428-11d2-A769-00AA001ACF42';
PHP_CREDITS_GUID = 'PHPB8B5F2A0-3C92-11d3-A3A9-4C7B08C10000';
const
ENT_HTML_QUOTE_NONE = 0;
ENT_HTML_QUOTE_SINGLE = 1;
ENT_HTML_QUOTE_DOUBLE = 2;
ENT_COMPAT = ENT_HTML_QUOTE_DOUBLE;
ENT_QUOTES = (ENT_HTML_QUOTE_DOUBLE or ENT_HTML_QUOTE_SINGLE);
ENT_NOQUOTES = ENT_HTML_QUOTE_NONE;
const
PHP_INI_USER = ZEND_INI_USER;
PHP_INI_PERDIR = ZEND_INI_PERDIR;
PHP_INI_SYSTEM = ZEND_INI_SYSTEM;
PHP_INI_ALL = ZEND_INI_ALL;
PHP_INI_DISPLAY_ORIG = ZEND_INI_DISPLAY_ORIG;
PHP_INI_DISPLAY_ACTIVE = ZEND_INI_DISPLAY_ACTIVE;
PHP_INI_STAGE_STARTUP = ZEND_INI_STAGE_STARTUP;
PHP_INI_STAGE_SHUTDOWN = ZEND_INI_STAGE_SHUTDOWN;
PHP_INI_STAGE_ACTIVATE = ZEND_INI_STAGE_ACTIVATE;
PHP_INI_STAGE_DEACTIVATE = ZEND_INI_STAGE_DEACTIVATE;
PHP_INI_STAGE_RUNTIME = ZEND_INI_STAGE_RUNTIME;
const
TRACK_VARS_POST = 0;
TRACK_VARS_GET = 1;
TRACK_VARS_COOKIE = 2;
TRACK_VARS_SERVER = 3;
TRACK_VARS_ENV = 4;
TRACK_VARS_FILES = 5;
type
error_handling_t = (EH_NORMAL, EH_SUPPRESS, EH_THROW);
type
TRequestType = (rtGet, rtPut, rtPost, rtHead);
TPHPRequestType = (prtGet, prtPost);
type
Psapi_header_struct = ^Tsapi_header_struct;
sapi_header_struct =
record
header : PAnsiChar;
header_len : uint;
{$IFNDEF PHP530}
replace : zend_bool;
{$ENDIF}
end;
Tsapi_header_struct = sapi_header_struct;
Psapi_headers_struct = ^Tsapi_headers_struct;
sapi_headers_struct =
record
headers : zend_llist;
http_response_code : Integer;
send_default_content_type : Byte;
mimetype : PAnsiChar;
http_status_line : PAnsiChar;
end;
Tsapi_headers_struct = sapi_headers_struct;
Psapi_post_entry = ^Tsapi_post_entry;
sapi_post_entry =
record
content_type : PAnsiChar;
content_type_len : uint;
post_reader : pointer; //void (*post_reader)(TSRMLS_D);
post_handler : pointer; //void (*post_handler)(char *content_type_dup, void *arg TSRMLS_DC);
end;
Tsapi_post_entry = sapi_post_entry;
{* Some values in this structure needs to be filled in before
* calling sapi_activate(). We WILL change the `char *' entries,
* so make sure that you allocate a separate buffer for them
* and that you free them after sapi_deactivate().
*}
Psapi_request_info = ^Tsapi_request_info;
sapi_request_info =
record
request_method : PAnsiChar;
query_string : PAnsiChar;
post_data : PAnsiChar;
raw_post_data : PAnsiChar;
cookie_data : PAnsiChar;
content_length : Longint;
post_data_length : uint;
raw_post_data_length : uint;
path_translated : PAnsiChar;
request_uri : PAnsiChar;
content_type : PAnsiChar;
headers_only : zend_bool;
no_headers : zend_bool;
{$IFDEF PHP5}
headers_read : zend_bool;
{$ENDIF}
post_entry : PSapi_post_entry;
content_type_dup : PAnsiChar;
//for HTTP authentication
auth_user : PAnsiChar;
auth_password : PAnsiChar;
{$IFDEF PHP510}
auth_digest : PAnsiChar;
{$ENDIF}
//this is necessary for the CGI SAPI module
argv0 : PAnsiChar;
//this is necessary for Safe Mode
current_user : PAnsiChar;
current_user_length : Integer;
//this is necessary for CLI module
argc : Integer;
argv : ^PAnsiChar;
{$IFDEF PHP510}
proto_num : integer;
{$ENDIF}
end;
Tsapi_request_info = sapi_request_info;
Psapi_header_line = ^Tsapi_header_line;
sapi_header_line =
record
line : PAnsiChar;
line_len : uint;
response_code : Longint;
end;
Tsapi_header_line = sapi_header_line;
Psapi_globals_struct = ^Tsapi_globals_struct;
_sapi_globals_struct =
record
server_context : Pointer;
request_info : sapi_request_info;
sapi_headers : sapi_headers_struct;
read_post_bytes : Integer;
headers_sent : Byte;
global_stat : stat;
default_mimetype : PAnsiChar;
default_charset : PAnsiChar;
rfc1867_uploaded_files : PHashTable;
post_max_size : Longint;
options : Integer;
{$IFDEF PHP5}
sapi_started : zend_bool;
{$IFDEF PHP510}
global_request_time : longint;
known_post_content_types : THashTable;
{$ENDIF}
{$ENDIF}
end;
Tsapi_globals_struct = _sapi_globals_struct;
Psapi_module_struct = ^Tsapi_module_struct;
TModuleShutdownFunc = function (globals : pointer) : Integer; cdecl;
TModuleStartupFunc = function (sapi_module : psapi_module_struct) : integer; cdecl;
sapi_module_struct =
record
name : PAnsiChar;
pretty_name : PAnsiChar;
startup : TModuleStartupFunc; //int (*startup)(struct _sapi_module_struct *sapi_module);
shutdown : TModuleShutdownFunc; //int (*shutdown)(struct _sapi_module_struct *sapi_module);
activate : pointer;
deactivate : pointer;
ub_write : pointer;
flush : pointer;
stat : pointer;
getenv : pointer;
sapi_error : pointer;
header_handler : pointer;
send_headers : pointer;
send_header : pointer;
read_post : pointer;
read_cookies : pointer;
register_server_variables : pointer;
log_message : pointer;
{$IFDEF PHP5}
{$IFDEF PHP510}
get_request_time : pointer;
{$ENDIF}
{$IFDEF PHP530}
terminate_process : pointer;
{$ENDIF}
{$ENDIF}
php_ini_path_override : PAnsiChar;
block_interruptions : pointer;
unblock_interruptions : pointer;
default_post_reader : pointer;
treat_data : pointer;
executable_location : PAnsiChar;
php_ini_ignore : Integer;
{******************************}
{IMPORTANT: }
{Please check your php version }
{******************************}
{$IFDEF PHP4}
{$IFDEF PHP433}
get_fd : pointer;
force_http_10 : pointer;
get_target_uid : pointer;
get_target_gid : pointer;
ini_defaults : pointer;
phpinfo_as_text : integer;
{$ENDIF}
{$ENDIF}
{$IFDEF PHP5}
get_fd : pointer;
force_http_10 : pointer;
get_target_uid : pointer;
get_target_gid : pointer;
input_filter : pointer;
ini_defaults : pointer;
phpinfo_as_text : integer;
{$IFDEF PHP520}
ini_entries : PAnsiChar;
{$ENDIF}
{$IFDEF PHP530}
additional_functions: Pointer;
input_filter_init : pointer;
{$ENDIF}
{$ENDIF}
end;
Tsapi_module_struct = sapi_module_struct;
type
PPHP_URL = ^TPHP_URL;
Tphp_url =
record
scheme : PAnsiChar;
user : PAnsiChar;
pass : PAnsiChar;
host : PAnsiChar;
port : Smallint;
path : PAnsiChar;
query : PAnsiChar;
fragment : PAnsiChar;
end;
type
arg_separators =
record
output : PAnsiChar;
input : PAnsiChar;
end;
type
Pphp_Core_Globals = ^TPHP_core_globals;
Tphp_core_globals =
record
magic_quotes_gpc : zend_bool;
magic_quotes_runtime : zend_bool;
magic_quotes_sybase : zend_bool;
safe_mode : zend_bool;
allow_call_time_pass_reference : boolean;
implicit_flush : boolean;
output_buffering : Integer;
safe_mode_include_dir : PAnsiChar;
safe_mode_gid : boolean;
sql_safe_mode : boolean;
enable_dl :boolean;
output_handler : PAnsiChar;
unserialize_callback_func : PAnsiChar;
safe_mode_exec_dir : PAnsiChar;
memory_limit : Longint;
max_input_time : Longint;
track_errors : boolean;
display_errors : boolean;
display_startup_errors : boolean;
log_errors : boolean;
log_errors_max_len : Longint;
ignore_repeated_errors : boolean;
ignore_repeated_source : boolean;
report_memleaks : boolean;
error_log : PAnsiChar;
doc_root : PAnsiChar;
user_dir : PAnsiChar;
include_path : PAnsiChar;
open_basedir : PAnsiChar;
extension_dir : PAnsiChar;
upload_tmp_dir : PAnsiChar;
upload_max_filesize : Longint;
error_append_string : PAnsiChar;
error_prepend_string : PAnsiChar;
auto_prepend_file : PAnsiChar;
auto_append_file : PAnsiChar;
arg_separator : arg_separators;
gpc_order : PAnsiChar;
variables_order : PAnsiChar;
rfc1867_protected_variables : THashTable;
connection_status : Smallint;
ignore_user_abort : Smallint;
header_is_being_sent : Byte;
tick_functions : zend_llist;
http_globals : array[0..5] of pzval;
expose_php : boolean;
register_globals : boolean;
register_argc_argv : boolean;
y2k_compliance : boolean;
docref_root : PAnsiChar;
docref_ext : PAnsiChar;
html_errors : boolean;
xmlrpc_errors : boolean;
xmlrpc_error_number : Longint;
modules_activated : boolean;
file_uploads : boolean;
during_request_startup : boolean;
allow_url_fopen : boolean;
always_populate_raw_post_data : boolean;
{$IFDEF PHP510}
report_zend_debug : boolean;
last_error_message : PAnsiChar;
last_error_file : PAnsiChar;
last_error_lineno : integer;
{$IFNDEF PHP530}
error_handling : error_handling_t;
exception_class : Pointer;
{$ENDIF}
disable_functions : PAnsiChar;
disable_classes : PAnsiChar;
{$ENDIF}
{$IFDEF PHP520}
allow_url_include : zend_bool;
com_initialized : zend_bool;
max_input_nesting_level : longint;
in_user_include : zend_bool;
{$ENDIF}
{$IFDEF PHP530}
user_ini_filename : PAnsiChar;
user_ini_cache_ttl : longint;
request_order : PAnsiChar;
mail_x_header : zend_bool;
mail_log : PAnsiChar;
{$ENDIF}
end;
implementation
end.
| 27.829932 | 99 | 0.646052 |
8533f81f1b64ab602f38a9e3d42a8decfdf4ba26 | 2,380 | pas | Pascal | test/code/ooObjectB.Entity.Mock.pas | VencejoSoftware/ooEntity | 0c49ad7c2420f8fe1fb57942fff27c55fdfd41bc | [
"BSD-3-Clause"
]
| 1 | 2022-01-04T02:17:53.000Z | 2022-01-04T02:17:53.000Z | test/code/ooObjectB.Entity.Mock.pas | VencejoSoftware/ooEntity | 0c49ad7c2420f8fe1fb57942fff27c55fdfd41bc | [
"BSD-3-Clause"
]
| null | null | null | test/code/ooObjectB.Entity.Mock.pas | VencejoSoftware/ooEntity | 0c49ad7c2420f8fe1fb57942fff27c55fdfd41bc | [
"BSD-3-Clause"
]
| 2 | 2019-11-21T02:57:52.000Z | 2021-01-26T04:45:05.000Z | {
Copyright (c) 2016, Vencejo Software
Distributed under the terms of the Modified BSD License
The full license is distributed with this software
}
unit ooObjectB.Entity.Mock;
interface
uses
SysUtils,
Generics.Collections,
ooKey,
ooDataInput.Intf, ooDataOutput.Intf,
ooEntity.Intf,
ooObjectA.Entity.Mock;
type
IObjectBEntityMock = interface(IEntity)
['{A5AB316E-A621-4C9E-9148-50B52CA636A7}']
function ID: Integer;
function Name: String;
function ObjectA: IObjectAEntityMock;
end;
TObjectBEntityMock = class sealed(TInterfacedObject, IObjectBEntityMock)
strict private
const
ID_KEY = 'ID';
NAME_KEY = 'Name';
OBJECTA_KEY = 'ObjectA';
strict private
_ID: Integer;
_Name: String;
_ObjectA: IObjectAEntityMock;
public
function ID: Integer;
function Name: String;
function ObjectA: IObjectAEntityMock;
function Marshal(const DataOutput: IDataOutput): Boolean;
function Unmarshal(const DataInput: IDataInput): Boolean;
constructor Create(const ID: Integer);
class function New(const ID: Integer): IObjectBEntityMock;
end;
implementation
function TObjectBEntityMock.ID: Integer;
begin
Result := _ID;
end;
function TObjectBEntityMock.Name: String;
begin
Result := _Name;
end;
function TObjectBEntityMock.ObjectA: IObjectAEntityMock;
begin
if not Assigned(_ObjectA) then
_ObjectA := TObjectAEntityMock.New(0);
Result := _ObjectA;
end;
function TObjectBEntityMock.Marshal(const DataOutput: IDataOutput): Boolean;
begin
DataOutput.WriteInteger(TTextKey.New(ID_KEY), ID);
DataOutput.WriteString(TTextKey.New(NAME_KEY), Name);
DataOutput.EnterSection(TTextKey.New(OBJECTA_KEY));
ObjectA.Marshal(DataOutput);
DataOutput.ExitSection(TTextKey.New(OBJECTA_KEY));
Result := True;
end;
function TObjectBEntityMock.Unmarshal(const DataInput: IDataInput): Boolean;
begin
_ID := DataInput.ReadInteger(TTextKey.New(ID_KEY));
_Name := DataInput.ReadString(TTextKey.New(NAME_KEY));
DataInput.EnterSection(TTextKey.New(OBJECTA_KEY));
ObjectA.Unmarshal(DataInput);
DataInput.ExitSection(TTextKey.New(OBJECTA_KEY));
Result := True;
end;
constructor TObjectBEntityMock.Create(const ID: Integer);
begin
_ID := ID;
end;
class function TObjectBEntityMock.New(const ID: Integer): IObjectBEntityMock;
begin
Result := TObjectBEntityMock.Create(ID);
end;
end.
| 24.791667 | 77 | 0.755882 |
47bae787eb94209279629359770aac5fadd9ec6f | 7,337 | pas | Pascal | Sources/XCTest.XCTestExpectation.pas | remobjects/RemObjects.Elements.EUnit | 3aedbd0a453a3464f518ffe819341cc369607d48 | [
"BSD-2-Clause"
]
| null | null | null | Sources/XCTest.XCTestExpectation.pas | remobjects/RemObjects.Elements.EUnit | 3aedbd0a453a3464f518ffe819341cc369607d48 | [
"BSD-2-Clause"
]
| null | null | null | Sources/XCTest.XCTestExpectation.pas | remobjects/RemObjects.Elements.EUnit | 3aedbd0a453a3464f518ffe819341cc369607d48 | [
"BSD-2-Clause"
]
| null | null | null | namespace RemObjects.Elements.EUnit.XCTest;
{$IF NOT WEBASSEMBLY}
type
{$IF DARWIN}[Cocoa]{$ENDIF}
XCTestExpectation = public class
constructor withDescription(aDescription: String);
begin
expectationDescription := aDescription;
end;
property expectationDescription: String; readonly;
property fulfillmentCount: Integer read private write;
property expectedFulfillmentCount: Integer := 1;
property assertForOverFulfill: Boolean := false;
//[SwiftName("isInverted")]
property inverted: Boolean := false;
public
method fulfill(aFile: String := currentFileName(); aLine: Integer := currentLineNumber(); aClass: String := currentClassName(); aMethod: String := currentMethodName()); virtual;
begin
dofulfill;
end;
assembly or protected
method waitFor(aTimeout: TimeInterval): Boolean; virtual;
begin
result := fFulfillmentTrigger.WaitFor(Int64(aTimeout)*1000); // Event.Timeout is in Miliseconds
end;
method dispose; virtual;
begin
//fFulfillmentTrigger.Dispose();
end;
property isFulfilled: Boolean read (fulfillmentCount = expectedFulfillmentCount) or (not assertForOverFulfill and (fulfillmentCount ≥ expectedFulfillmentCount)); virtual;
protected
method dofulfill(aFile: String := currentFileName(); aLine: Integer := currentLineNumber(); aClass: String := currentClassName(); aMethod: String := currentMethodName());
begin
if inverted then
XCTFail($"Expectation '{expectationDescription}' was not expected to be fulfilled", aFile, aLine, aClass, aMethod);
if assertForOverFulfill and (fulfillmentCount ≥ expectedFulfillmentCount) then
XCTFail($"Expectation '{expectationDescription}' was fulfilled for than {fulfillmentCount}x", aFile, aLine, aClass, aMethod);
inc(fulfillmentCount);
if fulfillmentCount ≥ expectedFulfillmentCount then
fFulfillmentTrigger.Set();
end;
private
var fFulfillmentTrigger := new &Event withState(false) Mode(EventMode.Manual); private;
end;
//XCTestManualExpectation = public class(XCTestExpectation)
//public
//method fulfill(aFile: String := currentFileName(); aLine: Integer := currentLineNumber(); aClass: String := currentClassName(); aMethod: String := currentMethodName()); override;
//begin
//dofulfill;
//end;
//end;
XCTNSNotificationExpectation = public class(XCTestExpectation)
assembly or protected
constructor withNotification(aNotificationName: String) object(aObject: nullable Object) handler(aHandler: Handler);
begin
inherited constructor withDescription($"Expectation for notification '{aNotificationName}'");
fNotificationName := aNotificationName;
fObject := aObject;
BroadcastManager.subscribe(self) toBroadcast(aNotificationName) &block( (n -> begin
if assigned(aHandler) then
dofulfill(nil, 0, nil, nil);
aHandler();
end))
end;
method dispose; override;
begin
BroadcastManager.unsubscribe(self) fromBroadcast(fNotificationName) object(fObject);
end;
private
var fNotificationName: String;
var fObject: Object;
end;
Handler nested in XCTNSNotificationExpectation = public block();
{$IF DARWIN}
XCTNSPredicateExpectation = public class(XCTestExpectation)
assembly or protected
constructor withPredicate(aPredicate: Foundation.NSPredicate) evaluatedWith(aEvaluatedWith: nullable Foundation.NSObject) handler(aHandler: Handler);
begin
inherited constructor withDescription($"Expectation with predicate '{aPredicate}'");
fPredicate := aPredicate;
fObject := aEvaluatedWith;
fHandler := aHandler;
async begin
loop begin
if fDone or check() then
break;
Thread.Sleep(500); // miliseconds
end;
end;
end;
method waitFor(aTimeout: TimeInterval): Boolean; override;
begin
if fFulfilled then exit;
inherited waitFor(aTimeout);
check();
fDone := true;
end;
property isFulfilled: Boolean read inherited isFulfilled or fPredicate.evaluateWithObject(fObject); override;
private
var fPredicate: Foundation.NSPredicate;
var fObject: nullable Object;
var fHandler: Handler;
var fFulfilled := false;
var fDone := false;
method check(): Boolean; locked on self;
begin
if fFulfilled then
exit true;
if fPredicate.evaluateWithObject(fObject) then begin
fFulfilled := true;
dofulfill(nil, 0, nil, nil);
if assigned(fHandler) then
fHandler();
result := true;
end;
end;
end;
Handler nested in XCTNSPredicateExpectation = public block();
XCTKVOExpectation = public class(XCTestExpectation)
assembly or protected
constructor withObject(aObject: not nullable Foundation.NSObject) keyPath(aKeyPath: String) expectedValue(aExpectedValue: nullable Object);
begin
inherited constructor withDescription($"Expectation for notificationkey path '{aKeyPath}'");
fObject := aObject;
fKeyPath := aKeyPath;
fExpectedValue := aExpectedValue;
fHasExpectedValue := true;
fFulfilled := false;
fObject.addObserver(self) forKeyPath(aKeyPath) options(0) context(nil);
end;
constructor withObject(aObject: not nullable Foundation.NSObject) keyPath(aKeyPath: String) handler(aHandler: XCTKVOExpectation.Handler);
begin
inherited constructor withDescription($"Expectation for notificationkey path '{aKeyPath}'");
fObject := aObject;
fKeyPath := aKeyPath;
fHandler := aHandler;
fFulfilled := false;
fObject.addObserver(self) forKeyPath(aKeyPath) options(0) context(nil);
end;
method waitFor(aTimeout: TimeInterval): Boolean; override;
begin
if fFulfilled then exit;
result := inherited waitFor(aTimeout);
end;
property isFulfilled: Boolean read inherited isFulfilled or (fHasExpectedValue and valueMatches); override;
private
method observeValueForKeyPath(keyPath: Foundation.NSString) ofObject(object: nullable id) change(aChanges: Foundation.NSDictionary<Foundation.NSString, id>) context(context: ^Void); override; public;
begin
check();
end;
var fExpectedValue: nullable Object;
var fHasExpectedValue := false;
var fObject: not nullable Foundation.NSObject;
var fKeyPath: String;
var fHandler: Handler;
var fFulfilled := false;
property valueMatches: Boolean read if assigned(fExpectedValue) then fExpectedValue.Equals(fObject.valueForKeyPath(fKeyPath)) else not assigned(fObject.valueForKeyPath(fKeyPath));
method check(): Boolean; locked on self;
begin
if fFulfilled then
exit true;
if not fHasExpectedValue or valueMatches then begin
fFulfilled := true;
dofulfill(nil, 0, nil, nil);
if assigned(fHandler) then
fHandler();
result := true;
end;
end;
end;
Handler nested in XCTKVOExpectation = public block();
{$ENDIF}
{$ENDIF}
end. | 32.608889 | 204 | 0.679978 |
47c657749633d539037be19cac34f8802abdc8b2 | 1,790 | pas | Pascal | Source/Services/Rekognition/Base/Model/AWS.Rekognition.Model.CoversBodyPart.pas | juliomar/aws-sdk-delphi | 995a0af808c7f66122fc6a04763d68203f8502eb | [
"Apache-2.0"
]
| 67 | 2021-07-28T23:47:09.000Z | 2022-03-15T11:48:35.000Z | Source/Services/Rekognition/Base/Model/AWS.Rekognition.Model.CoversBodyPart.pas | juliomar/aws-sdk-delphi | 995a0af808c7f66122fc6a04763d68203f8502eb | [
"Apache-2.0"
]
| 5 | 2021-09-01T09:31:16.000Z | 2022-03-16T18:19:21.000Z | Source/Services/Rekognition/Base/Model/AWS.Rekognition.Model.CoversBodyPart.pas | landgraf-dev/aws-sdk-delphi | 995a0af808c7f66122fc6a04763d68203f8502eb | [
"Apache-2.0"
]
| 13 | 2021-07-29T02:41:16.000Z | 2022-03-16T10:22:38.000Z | unit AWS.Rekognition.Model.CoversBodyPart;
interface
uses
Bcl.Types.Nullable;
type
TCoversBodyPart = class;
ICoversBodyPart = interface
function GetConfidence: Double;
procedure SetConfidence(const Value: Double);
function GetValue: Boolean;
procedure SetValue(const Value: Boolean);
function Obj: TCoversBodyPart;
function IsSetConfidence: Boolean;
function IsSetValue: Boolean;
property Confidence: Double read GetConfidence write SetConfidence;
property Value: Boolean read GetValue write SetValue;
end;
TCoversBodyPart = class
strict private
FConfidence: Nullable<Double>;
FValue: Nullable<Boolean>;
function GetConfidence: Double;
procedure SetConfidence(const Value: Double);
function GetValue: Boolean;
procedure SetValue(const Value: Boolean);
strict protected
function Obj: TCoversBodyPart;
public
function IsSetConfidence: Boolean;
function IsSetValue: Boolean;
property Confidence: Double read GetConfidence write SetConfidence;
property Value: Boolean read GetValue write SetValue;
end;
implementation
{ TCoversBodyPart }
function TCoversBodyPart.Obj: TCoversBodyPart;
begin
Result := Self;
end;
function TCoversBodyPart.GetConfidence: Double;
begin
Result := FConfidence.ValueOrDefault;
end;
procedure TCoversBodyPart.SetConfidence(const Value: Double);
begin
FConfidence := Value;
end;
function TCoversBodyPart.IsSetConfidence: Boolean;
begin
Result := FConfidence.HasValue;
end;
function TCoversBodyPart.GetValue: Boolean;
begin
Result := FValue.ValueOrDefault;
end;
procedure TCoversBodyPart.SetValue(const Value: Boolean);
begin
FValue := Value;
end;
function TCoversBodyPart.IsSetValue: Boolean;
begin
Result := FValue.HasValue;
end;
end.
| 22.375 | 71 | 0.764804 |
83d552b671ed390e08f9d3c159f9dc262f223f84 | 25,369 | pas | Pascal | contrib/mORMot/SynDBDataset/SynDBFireDAC.pas | Razor12911/bms2xtool | 0493cf895a9dbbd9f2316a3256202bcc41d9079c | [
"MIT"
]
| 4 | 2020-04-24T07:43:43.000Z | 2021-08-29T08:36:08.000Z | mORMot/SynDBDataset/SynDBFireDAC.pas | LongDirtyAnimAlf/AsphyrePXL | 9151ff88eca1fa01dce083b09e7ea20076f6d334 | [
"Apache-2.0"
]
| 1 | 2022-02-17T07:17:16.000Z | 2022-02-17T07:17:16.000Z | contrib/mORMot/SynDBDataset/SynDBFireDAC.pas | Razor12911/bms2xtool | 0493cf895a9dbbd9f2316a3256202bcc41d9079c | [
"MIT"
]
| 2 | 2020-08-18T09:42:33.000Z | 2021-04-22T08:15:27.000Z | /// FireDAC/AnyDAC-based classes for SynDB units
// - this unit is a part of the freeware Synopse framework,
// licensed under a MPL/GPL/LGPL tri-license; version 1.18
unit SynDBFireDAC;
{
This file is part of Synopse framework.
Synopse framework. Copyright (C) 2020 Arnaud Bouchez
Synopse Informatique - https://synopse.info
*** BEGIN LICENSE BLOCK *****
Version: MPL 1.1/GPL 2.0/LGPL 2.1
The contents of this file are subject to the Mozilla Public License Version
1.1 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the License.
The Original Code is Synopse mORMot framework.
The Initial Developer of the Original Code is Arnaud Bouchez.
Portions created by the Initial Developer are Copyright (C) 2020
the Initial Developer. All Rights Reserved.
Contributor(s):
- delphinium (louisyeow)
- Oleg Tretyakov
Alternatively, the contents of this file may be used under the terms of
either the GNU General Public License Version 2 or later (the "GPL"), or
the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
in which case the provisions of the GPL or the LGPL are applicable instead
of those above. If you wish to allow use of your version of this file only
under the terms of either the GPL or the LGPL, and not to allow others to
use your version of this file under the terms of the MPL, indicate your
decision by deleting the provisions above and replace them with the notice
and other provisions required by the GPL or the LGPL. If you do not delete
the provisions above, a recipient may use your version of this file under
the terms of any one of the MPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****
}
{$I Synopse.inc} // define HASINLINE CPU32 CPU64 OWNNORMTOUPPER
interface
uses
Windows, SysUtils,
{$IFNDEF DELPHI5OROLDER}
Variants,
{$ENDIF}
Classes, Contnrs,
SynCommons,
SynTable,
SynLog,
SynDB,
SynDBDataset,
{$ifdef ISDELPHIXE5}
FireDAC.Comp.Client, FireDAC.Stan.Param;
{$else}
uADCompClient, uADStanParam;
{$endif}
{ -------------- FireDAC/AnyDAC database access }
type
/// Exception type associated to FireDAC/AnyDAC database access
ESQLDBFireDAC = class(ESQLDBDataset);
/// connection properties definition using FireDAC/AnyDAC database access
TSQLDBFireDACConnectionProperties = class(TSQLDBDatasetConnectionProperties)
protected
fFireDACOptions: TStringList;
/// initialize fForeignKeys content with all foreign keys of this DB
// - do nothing by now (FireDAC metadata may be used in the future)
procedure GetForeignKeys; override;
public
/// initialize the properties to connect via FireDAC/AnyDAC database access
// - aServerName shall contain the FireDAC provider DriverID, e.g. 'Ora', and
// some optional parameters (e.g. remote server name if needed), after a '?'
// and separated by ';' - for instance:
// ! Create('Ora','TNSNAME','User','Password');
// ! Create('Ora?CharacterSet=cl8mswin1251','TNSNAME','User','Password');
// ! Create('MSSQL?Server=127.0.0.1\SQLEXPRESS','Northwind','User','Password');
// ! Create('MSSQL?Server=.\SQLEXPRESS;OSAuthent=Yes','','','');
// ! Create('MSAcc','c:\data\access.mdb','','');
// ! Create('MySQL?Server=127.0.0.1;Port=3306','MyDB','User','Password');
// ! Create('SQLite','c:\data\myapp.db3','','');
// ! Create('SQLite',SQLITE_MEMORY_DATABASE_NAME,'','');
// ! Create('IB','127.0.0.1:C:\ib\ADDEMO_IB2007.IB','User','Password');
// ! Create('IB?Server=my_host/3055','C:\ib\ADDEMO_IB2007.IB','User','Password');
// ! Create('IB?CreateDatabase=Yes','127.0.0.1:C:\ib\ADDEMO_IB2007.IB','User','Password');
// ! Create('DB2?Server=localhost;Port=50000','SAMPLE','db2admin','db2Password');
// ! Create('PG?Server=localhost;Port=5432','postgres','postgres','postgresPassword');
// ! Create('MySQL?Server=localhost;Port=3306','test','root','');
// - aDatabaseName shall contain the database server name
// - note that you need to link the FireDAC driver by including the
// expected uADPhys*.pas / FireDAC.Phy.*.pas units into a uses clause
// of your application, e.g. uADPhysOracle, uADPhysMSSQL, uADPhysMSAcc,
// uADPhysMySQL, uADPhysSQLite, uADPhysIB or uADPhysDB2 (depending on the
// expected provider) - or FireDAC.Phys.Oracle, FireDAC.Phys.MSAcc,
// FireDAC.Phys.MSSQL, FireDAC.Phys.SQLite, FireDAC.Phys.IB, FireDAC.Phys.PG
// or FireDAC.Phys.DB2 since Delphi XE5 namespace modifications
constructor Create(const aServerName, aDatabaseName, aUserID, aPassWord: RawUTF8); override;
/// release internal structures
destructor Destroy; override;
/// create a new connection
// - caller is responsible of freeing this instance
// - this overridden method will create an TSQLDBFireDACConnection instance
function NewConnection: TSQLDBConnection; override;
/// retrieve the column/field layout of a specified table
// - this overridden method will use FireDAC metadata to retrieve the information
procedure GetFields(const aTableName: RawUTF8; out Fields: TSQLDBColumnDefineDynArray); override;
/// get all table names
// - this overridden method will use FireDAC metadata to retrieve the information
procedure GetTableNames(out Tables: TRawUTF8DynArray); override;
/// retrieve the advanced indexed information of a specified Table
// - this overridden method will use FireDAC metadata to retrieve the information
procedure GetIndexes(const aTableName: RawUTF8; out Indexes: TSQLDBIndexDefineDynArray); override;
/// allow to set the options specific to a FireDAC driver
// - by default, ServerName, DatabaseName, UserID and Password are set by
// the Create() constructor according to the underlying FireDAC driver
// - you can add some additional options here
property Parameters: TStringList read fFireDACOptions;
end;
/// implements a direct connection via FireDAC/AnyDAC database access
TSQLDBFireDACConnection = class(TSQLDBConnectionThreadSafe)
protected
fDatabase: {$ifdef ISDELPHIXE5}TFDConnection{$else}TADConnection{$endif};
public
/// prepare a connection for a specified FireDAC/AnyDAC database access
constructor Create(aProperties: TSQLDBConnectionProperties); override;
/// release memory and connection
destructor Destroy; override;
/// connect to the specified database server using FireDAC
// - should raise an ESQLDBFireDAC on error
procedure Connect; override;
/// stop connection to the specified database server using FireDAC
// - should raise an ESQLDBFireDAC on error
procedure Disconnect; override;
/// return TRUE if Connect has been already successfully called
function IsConnected: boolean; override;
/// create a new statement instance
function NewStatement: TSQLDBStatement; override;
/// begin a Transaction for this connection
procedure StartTransaction; override;
/// commit changes of a Transaction for this connection
// - StartTransaction method must have been called before
procedure Commit; override;
/// discard changes of a Transaction for this connection
// - StartTransaction method must have been called before
procedure Rollback; override;
/// access to the associated FireDAC connection instance
property Database: {$ifdef ISDELPHIXE5}TFDConnection{$else}TADConnection{$endif} read fDatabase;
end;
/// implements a statement via a FireDAC connection
// - this specific version will handle the FireDAC specific parameter classes
// - it will also handle Array DML commands, if possible
TSQLDBFireDACStatement = class(TSQLDBDatasetStatementAbstract)
protected
fQueryParams: {$ifdef ISDELPHIXE5}TFDParams{$else}TADParams{$endif};
fPreparedUseArrayDML: boolean;
/// initialize and set fQuery: TUniQuery internal field as expected
procedure DatasetCreate; override;
/// set fQueryParams internal field as expected
function DatasetPrepare(const aSQL: string): boolean; override;
/// execute underlying TUniQuery.ExecSQL
procedure DatasetExecSQL; override;
/// bind SQLDBParam to TQuery-like param using fQueryParams: DB.TParams
procedure DataSetBindSQLParam(const aArrayIndex, aParamIndex: integer;
const aParam: TSQLDBParam); override;
/// set the returned parameter after a stored proc execution
procedure DataSetOutSQLParam(const aParamIndex: integer;
var aParam: TSQLDBParam); override;
public
/// Prepare an UTF-8 encoded SQL statement
// - parameters marked as ? will be bound later, before ExecutePrepared call
// - if ExpectResults is TRUE, then Step() and Column*() methods are available
// to retrieve the data rows
// - raise an ESQLDBFireDAC on any error
procedure Prepare(const aSQL: RawUTF8; ExpectResults: boolean = false); overload; override;
end;
const
/// FireDAC DriverID values corresponding to SynDB recognized SQL engines
{$ifdef ISDELPHIXE5}
FIREDAC_PROVIDER: array[dOracle..high(TSQLDBDefinition)] of RawUTF8 = (
'Ora','MSSQL','MSAcc','MySQL','SQLite','FB','','PG','DB2','Infx');
{$else}
FIREDAC_PROVIDER: array[dOracle..high(TSQLDBDefinition)] of RawUTF8 = (
'Ora','MSSQL','MSAcc','MySQL','SQLite','IB','','PG','DB2','Infx');
{$endif}
implementation
uses
{$ifdef ISDELPHIXE5}
FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.DApt, FireDAC.Stan.Async;
type
TADConnection = TFDConnection;
TADQuery = TFDQuery;
TADMetaInfoQuery = TFDMetaInfoQuery;
TADParam = TFDParam;
TADParams = TFDParams;
TADPhysMetaInfoKind = TFDPhysMetaInfoKind;
{$else}
uADPhysIntf, uADStanDef, uADDAptManager, uADStanAsync;
{$endif}
{ TSQLDBFireDACConnectionProperties }
constructor TSQLDBFireDACConnectionProperties.Create(const aServerName, aDatabaseName, aUserID, aPassWord: RawUTF8);
var p: TSQLDBDefinition;
server,options,namevalue: RawUTF8;
opt: PUTF8Char;
begin
Split(aServerName,'?',server,options);
if server<>'' then
for p := Low(FIREDAC_PROVIDER) to high(FIREDAC_PROVIDER) do
if SameTextU(FIREDAC_PROVIDER[p],server) then begin
fDBMS := p;
break;
end;
inherited Create(server,aDatabaseName,aUserID,aPassWord);
fOnBatchInsert := nil; // MultipleValuesInsert is slower than FireDAC ArrayDML
fFireDACOptions := TStringList.Create;
if ((fDBMS<low(FIREDAC_PROVIDER)) or (fDBMS>high(FIREDAC_PROVIDER))) and
(fDBMS<>dNexusDB) then
if SameTextU(server,'ASA') then
fDBMS := dMSSQL else begin
for p := Low(FIREDAC_PROVIDER) to high(FIREDAC_PROVIDER) do
namevalue := ' '+namevalue+FIREDAC_PROVIDER[p];
raise ESQLDBFireDAC.CreateUTF8('%.Create: unknown provider - available:%',
[self,namevalue]);
end;
if server='' then
server := FIREDAC_PROVIDER[fDBMS];
fFireDACOptions.Text := UTF8ToString(FormatUTF8(
'DriverID=%'#13#10'User_Name=%'#13#10'Password=%'#13#10'Database=%',
[server,fUserId,fPassWord,fDatabaseName]));
opt := pointer(options);
while opt<>nil do begin
GetNextItem(opt,';',namevalue);
if namevalue<>'' then
fFireDACOptions.Add(UTF8ToString(namevalue));
end;
case fDBMS of
dSQLite: begin
if fFireDACOptions.Values['CharacterSet']='' then // force UTF-8 for SynDB
fFireDACOptions.Values['CharacterSet'] := 'UTF8';
{$ifdef UNICODE} // CreateUTF16 is the default value for Delphi 2009+
if fFireDACOptions.Values['OpenMode']='' then // force UTF-8 for SynDB
fFireDACOptions.Values['OpenMode'] := 'CreateUTF8';
{$else}
ForceUseWideString := true; // as expected by FireDAC when UTF-8 is enabled
{$endif}
fSQLCreateField[ftInt64] := ' BIGINT'; // SQLite3 INTEGER = 32bit for FireDAC
end;
dFirebird, dMySQL, dPostgreSQL, dDB2: begin
if fFireDACOptions.Values['CharacterSet']='' then // force UTF-8 for SynDB
fFireDACOptions.Values['CharacterSet'] := 'UTF8';
{$ifndef UNICODE}
ForceUseWideString := true; // as expected by FireDAC when UTF-8 is enabled
{$endif}
end;
end;
end;
destructor TSQLDBFireDACConnectionProperties.Destroy;
begin
fFireDACOptions.Free;
inherited;
end;
procedure TSQLDBFireDACConnectionProperties.GetTableNames(
out Tables: TRawUTF8DynArray);
var List: TStringList;
begin
List := TStringList.Create;
try
(MainConnection as TSQLDBFireDACConnection).fDatabase.GetTableNames(
'','','',List,[osMy],[tkTable]);
StringListToRawUTF8DynArray(List,Tables);
exit;
finally
List.Free;
end;
inherited;
end;
procedure TSQLDBFireDACConnectionProperties.GetFields(
const aTableName: RawUTF8; out Fields: TSQLDBColumnDefineDynArray);
var meta: TADMetaInfoQuery;
n: integer;
F: TSQLDBColumnDefine;
FA: TDynArray;
begin
meta := TADMetaInfoQuery.Create(nil);
try
meta.Connection := (MainConnection as TSQLDBFireDACConnection).fDatabase;
FA.Init(TypeInfo(TSQLDBColumnDefineDynArray),Fields,@n);
FA.Compare := SortDynArrayAnsiStringI; // FA.Find() case insensitive
FillChar(F,sizeof(F),0);
meta.MetaInfoKind := mkTableFields;
meta.ObjectName := UTF8ToString(UpperCase(aTableName));
meta.Open;
while not meta.Eof do begin
F.ColumnName := StringToUTF8(meta.FieldByName('COLUMN_NAME').AsString);
F.ColumnTypeNative := StringToUTF8(meta.FieldByName('COLUMN_TYPENAME').AsString);
F.ColumnLength := meta.FieldByName('COLUMN_LENGTH').AsInteger;
F.ColumnScale := meta.FieldByName('COLUMN_SCALE').AsInteger;
F.ColumnPrecision := meta.FieldByName('COLUMN_PRECISION').AsInteger;
{ TODO : retrieve ColumnType from high-level FireDAC type information }
F.ColumnType := ColumnTypeNativeToDB(F.ColumnTypeNative,F.ColumnScale);
FA.Add(F);
meta.Next;
end;
Setlength(Fields,n);
GetIndexesAndSetFieldsColumnIndexed(aTableName,Fields);
finally
meta.Free;
end;
end;
procedure TSQLDBFireDACConnectionProperties.GetIndexes(
const aTableName: RawUTF8; out Indexes: TSQLDBIndexDefineDynArray);
var kind: boolean;
meta, indexs: TADMetaInfoQuery;
TableName: string;
ColName: RawUTF8;
F: TSQLDBIndexDefine;
FA: TDynArray;
n: integer;
const
MASTER: array[boolean] of TADPhysMetaInfoKind = (mkPrimaryKey,mkIndexes);
CHILD: array[boolean] of TADPhysMetaInfoKind = (mkPrimaryKeyFields,mkIndexFields);
begin
TableName := UTF8ToString(UpperCase(aTableName));
FA.Init(TypeInfo(TSQLDBIndexDefineDynArray),Indexes,@n);
fillchar(F,sizeof(F),0);
meta := TADMetaInfoQuery.Create(nil);
indexs := TADMetaInfoQuery.Create(nil);
try
meta.Connection := (MainConnection as TSQLDBFireDACConnection).fDatabase;
indexs.Connection := meta.Connection;
for kind := true to true do begin // primary keys may not be indexed
meta.MetaInfoKind := MASTER[kind];
meta.ObjectName := TableName;
meta.Open;
while not meta.Eof do begin
indexs.MetaInfoKind := CHILD[kind];
indexs.BaseObjectName := TableName;
indexs.ObjectName := meta.FieldByName('INDEX_NAME').AsString;
indexs.Open;
F.IndexName := StringToUTF8(indexs.ObjectName);
F.IsPrimaryKey := not kind;
F.KeyColumns := '';
while not indexs.Eof do begin
ColName := StringToUTF8(indexs.FieldByName('COLUMN_NAME').AsString);
if F.KeyColumns='' then
F.KeyColumns := ColName else
F.KeyColumns := F.KeyColumns+','+ColName;
indexs.Next;
end;
FA.Add(F);
indexs.Close;
meta.Next;
end;
meta.Close;
end;
SetLength(Indexes,n);
finally
indexs.Free;
meta.Free;
end;
end;
procedure TSQLDBFireDACConnectionProperties.GetForeignKeys;
begin
{ TODO : get FOREIGN KEYS from FireDAC metadata using mkForeignKeys }
end;
function TSQLDBFireDACConnectionProperties.NewConnection: TSQLDBConnection;
begin
result := TSQLDBFireDACConnection.Create(self);
end;
{ TSQLDBFireDACConnection }
procedure TSQLDBFireDACConnection.Commit;
begin
inherited Commit;
try
fDatabase.Commit;
except
inc(fTransactionCount); // the transaction is still active
raise;
end;
end;
constructor TSQLDBFireDACConnection.Create(aProperties: TSQLDBConnectionProperties);
begin
inherited Create(aProperties);
fDatabase := TADConnection.Create(nil);
fDatabase.ResourceOptions.SilentMode := True; // no need for wait cursor
fDatabase.Params.Text :=
(fProperties as TSQLDBFireDACConnectionProperties).fFireDACOptions.Text;
end;
procedure TSQLDBFireDACConnection.Connect;
var Log: ISynLog;
begin
if fDatabase=nil then
raise ESQLDBFireDAC.CreateUTF8('%.Connect(%): Database=nil',
[self,fProperties.ServerName]);
Log := SynDBLog.Enter('Connect to DriverID=% Database=%',
[FIREDAC_PROVIDER[fProperties.DBMS],fProperties.DatabaseName],self);
try
fDatabase.Open;
inherited Connect; // notify any re-connection
Log.Log(sllDB,'Connected to % (%)',
[fDatabase.DriverName,fProperties.DatabaseName]);
except
on E: Exception do begin
Log.Log(sllError,E);
Disconnect; // clean up on fail
raise;
end;
end;
end;
procedure TSQLDBFireDACConnection.Disconnect;
begin
try
inherited Disconnect; // flush any cached statement
finally
if fDatabase<>nil then
fDatabase.Close;
end;
end;
destructor TSQLDBFireDACConnection.Destroy;
begin
try
Disconnect;
except
on Exception do
end;
inherited;
FreeAndNil(fDatabase);
end;
function TSQLDBFireDACConnection.IsConnected: boolean;
begin
result := Assigned(fDatabase) and fDatabase.Connected;
end;
function TSQLDBFireDACConnection.NewStatement: TSQLDBStatement;
begin
result := TSQLDBFireDACStatement.Create(self);
end;
procedure TSQLDBFireDACConnection.Rollback;
begin
inherited Rollback;
fDatabase.Rollback;
end;
procedure TSQLDBFireDACConnection.StartTransaction;
begin
inherited StartTransaction;
fDatabase.StartTransaction;
end;
{ TSQLDBFireDACStatement }
procedure TSQLDBFireDACStatement.DatasetCreate;
begin
fQuery := TADQuery.Create(nil);
TADQuery(fQuery).Connection := (fConnection as TSQLDBFireDACConnection).Database;
fDatasetSupportBatchBinding := true;
end;
function TSQLDBFireDACStatement.DatasetPrepare(const aSQL: string): boolean;
begin
(fQuery as TADQuery).SQL.Text := aSQL;
fQueryParams := TADQuery(fQuery).Params;
result := fQueryParams<>nil;
end;
procedure TSQLDBFireDACStatement.Prepare(const aSQL: RawUTF8;
ExpectResults: boolean);
begin
inherited;
if fPreparedParamsCount<>fQueryParams.Count then
raise ESQLDBFireDAC.CreateUTF8(
'%.Prepare() expected % parameters in request, found % - [%]',
[self,fPreparedParamsCount,fQueryParams.Count,aSQL]);
end;
procedure TSQLDBFireDACStatement.DatasetExecSQL;
begin
if fPreparedUseArrayDML then
(fQuery as TADQuery).Execute(fParamsArrayCount) else
(fQuery as TADQuery).Execute;
end;
procedure TSQLDBFireDACStatement.DataSetBindSQLParam(const aArrayIndex,
aParamIndex: integer; const aParam: TSQLDBParam);
var P: TADParam;
i: integer;
tmp: RawUTF8;
StoreVoidStringAsNull: boolean;
begin
if fDatasetSupportBatchBinding then
fPreparedUseArrayDML := (aArrayIndex<0) and (fParamsArrayCount>0) else
fPreparedUseArrayDML := false;
if fPreparedUseArrayDML and (fQueryParams.ArraySize<>fParamsArrayCount) then
fQueryParams.ArraySize := fParamsArrayCount;
with aParam do begin
P := fQueryParams[aParamIndex];
P.ParamType := SQLParamTypeToDBParamType(VInOut);
if VinOut <> paramInOut then
case VType of
SynTable.ftNull:
if fPreparedUseArrayDML then
for i := 0 to fParamsArrayCount-1 do
P.Clear(i) else
P.Clear;
SynTable.ftInt64: begin
if fPreparedUseArrayDML then
for i := 0 to fParamsArrayCount-1 do
if VArray[i]='null' then
P.Clear(i) else
P.AsLargeInts[i] := GetInt64(pointer(VArray[i])) else
if aArrayIndex>=0 then
if VArray[aArrayIndex]='null' then
P.Clear else
P.AsLargeInt := GetInt64(pointer(VArray[aArrayIndex])) else
P.AsLargeInt := VInt64;
end;
SynTable.ftDouble:
if fPreparedUseArrayDML then
for i := 0 to fParamsArrayCount-1 do
if VArray[i]='null' then
P.Clear(i) else
P.AsFloats[i] := GetExtended(pointer(VArray[i])) else
if aArrayIndex>=0 then
if VArray[aArrayIndex]='null' then
P.Clear else
P.AsFloat := GetExtended(pointer(VArray[aArrayIndex])) else
P.AsFloat := PDouble(@VInt64)^;
SynTable.ftCurrency:
if fPreparedUseArrayDML then
for i := 0 to fParamsArrayCount-1 do
if VArray[i]='null' then
P.Clear(i) else
P.AsCurrencys[i] := StrToCurrency(pointer(VArray[i])) else
if aArrayIndex>=0 then
if VArray[aArrayIndex]='null' then
P.Clear else
P.AsCurrency := StrToCurrency(pointer(VArray[aArrayIndex])) else
P.AsCurrency := PCurrency(@VInt64)^;
SynTable.ftDate:
if fPreparedUseArrayDML then
for i := 0 to fParamsArrayCount-1 do
if VArray[i]='null' then
P.Clear(i) else begin
UnQuoteSQLStringVar(pointer(VArray[i]),tmp);
P.AsDateTimes[i] := Iso8601ToDateTime(tmp);
end else
if aArrayIndex>=0 then
if VArray[aArrayIndex]='null' then
P.Clear else begin
UnQuoteSQLStringVar(pointer(VArray[aArrayIndex]),tmp);
P.AsDateTime := Iso8601ToDateTime(tmp);
end else
P.AsDateTime := PDateTime(@VInt64)^;
SynTable.ftUTF8:
if fPreparedUseArrayDML then begin
StoreVoidStringAsNull := fConnection.Properties.StoreVoidStringAsNull;
for i := 0 to fParamsArrayCount-1 do
if (VArray[i]='null') or
(StoreVoidStringAsNull and (VArray[i]=#39#39)) then
P.Clear(i) else begin
UnQuoteSQLStringVar(pointer(VArray[i]),tmp);
{$ifdef UNICODE} // for FireDAC: TADWideString=UnicodeString
P.AsWideStrings[i] := UTF8ToString(tmp);
{$else}
if fForceUseWideString then
P.AsWideStrings[i] := UTF8ToWideString(tmp) else
P.AsStrings[i] := UTF8ToString(tmp);
{$endif}
end
end else
if aArrayIndex>=0 then
if (VArray[aArrayIndex]='null') or
(fConnection.Properties.StoreVoidStringAsNull and
(VArray[aArrayIndex]=#39#39)) then
P.Clear else begin
UnQuoteSQLStringVar(pointer(VArray[aArrayIndex]),tmp);
{$ifdef UNICODE}
P.AsWideString := UTF8ToString(tmp); // TADWideString=string
{$else}
if fForceUseWideString then
P.AsWideString := UTF8ToWideString(tmp) else
P.AsString := UTF8ToString(tmp);
{$endif}
end else
if (VData='') and fConnection.Properties.StoreVoidStringAsNull then
P.Clear else
{$ifdef UNICODE}
P.AsWideString := UTF8ToString(VData); // TADWideString=string
{$else}
if (not fForceUseWideString) {or IsAnsiCompatible(VData)} then
P.AsString := UTF8ToString(VData) else
P.AsWideString := UTF8ToWideString(VData);
{$endif}
SynTable.ftBlob:
if fPreparedUseArrayDML then
for i := 0 to fParamsArrayCount-1 do
if VArray[i]='null' then
P.Clear(i) else
P.AsBlobs[i] := VArray[i] else
if aArrayIndex>=0 then
if VArray[aArrayIndex]='null' then
P.Clear else
P.AsBlob := VArray[aArrayIndex] else
P.AsBlob := VData;
else
raise ESQLDBFireDAC.CreateUTF8(
'%.DataSetBindSQLParam: invalid type % on bound parameter #%',
[Self,ord(VType),aParamIndex+1]);
end;
end;
end;
procedure TSQLDBFireDACStatement.DataSetOutSQLParam(const aParamIndex: integer;
var aParam: TSQLDBParam);
var Par: TADParam;
begin
Par := fQueryParams[aParamIndex];
case aParam.VType of
SynTable.ftInt64: aParam.VInt64 := Par.AsLargeInt;
SynTable.ftDouble: PDouble(@aParam.VInt64)^ := Par.AsFloat;
SynTable.ftCurrency: PCurrency(@aParam.VInt64)^ := Par.AsCurrency;
SynTable.ftDate: PDateTime(@aParam.VInt64)^ := Par.AsDateTime;
SynTable.ftUTF8: aParam.VData := StringToUTF8(Par.AsString);
SynTable.ftBlob: aParam.VData := Par.AsBlob;
end;
end;
initialization
TSQLDBFireDACConnectionProperties.RegisterClassNameForDefinition;
end.
| 37.362297 | 116 | 0.692459 |
f1389f722712451360343576ba5cd68c78f168e9 | 7,532 | pas | Pascal | frmAdvanced.pas | dgrieser/winxcorners | c0e259106b1f2df07a04c76600ee6208b8dc3f67 | [
"MIT"
]
| 377 | 2019-06-12T19:12:38.000Z | 2022-03-31T16:30:52.000Z | frmAdvanced.pas | dgrieser/winxcorners | c0e259106b1f2df07a04c76600ee6208b8dc3f67 | [
"MIT"
]
| 32 | 2019-06-10T17:07:15.000Z | 2022-03-28T09:37:45.000Z | frmAdvanced.pas | dgrieser/winxcorners | c0e259106b1f2df07a04c76600ee6208b8dc3f67 | [
"MIT"
]
| 32 | 2019-09-22T01:17:15.000Z | 2022-03-28T09:35:39.000Z | unit frmAdvanced;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Samples.Spin,
Vcl.ExtCtrls, ShellApi, IniFiles, IPPeerClient, Data.Bind.Components,
Data.Bind.ObjectScope, REST.Client, Vcl.ComCtrls, UCL.Form, UCL.Classes,
UCL.QuickButton, UCL.CaptionBar, UCL.Button, Vcl.WinXPanels, Vcl.WinXCtrls,
UCL.ListButton, UCL.ScrollBox, UCL.Panel, Vcl.Imaging.pngimage
{, REST.Client, JSon};
const
VERSION = '1.2';
type
TfrmAdvSettings = class(TUForm)
GroupBox1: TGroupBox;
chkDelayGlobal: TCheckBox;
valDelayGlobal: TSpinEdit;
chkDelayTopLeft: TCheckBox;
valDelayTopLeft: TSpinEdit;
chkDelayTopRight: TCheckBox;
valDelayTopRight: TSpinEdit;
chkDelayBotLeft: TCheckBox;
valDelayBotLeft: TSpinEdit;
chkDelayBotRight: TCheckBox;
valDelayBotRight: TSpinEdit;
Label2: TLabel;
chkShowCount: TCheckBox;
GroupBox2: TGroupBox;
Label3: TLabel;
edCommand: TEdit;
chkCustom: TCheckBox;
Label4: TLabel;
chkHidden: TCheckBox;
edParams: TEdit;
Label1: TLabel;
Label5: TLabel;
GroupBox3: TGroupBox;
HotKey1: THotKey;
Label6: TLabel;
UCaptionBar1: TUCaptionBar;
UQuickButton1: TUQuickButton;
UButton1: TUButton;
UButton2: TUButton;
SplitView1: TSplitView;
CardPanel1: TCardPanel;
crdSettings: TCard;
crdAbout: TCard;
UListButton1: TUListButton;
UListButton2: TUListButton;
UScrollBox1: TUScrollBox;
StackPanel1: TStackPanel;
Panel1: TPanel;
UListButton3: TUListButton;
pnlContent: TUPanel;
Image1: TImage;
procedure FormCreate(Sender: TObject);
procedure Label4Click(Sender: TObject);
procedure chkDelayGlobalClick(Sender: TObject);
procedure Label5Click(Sender: TObject);
procedure UButton1Click(Sender: TObject);
procedure UButton2Click(Sender: TObject);
procedure UListButton1Click(Sender: TObject);
procedure UListButton2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure SaveAdvancedIni;
procedure ReadAdvancedIni;
end;
var
frmAdvSettings: TfrmAdvSettings;
implementation
{$R *.dfm}
uses frmSettings;
procedure TfrmAdvSettings.chkDelayGlobalClick(Sender: TObject);
begin
if chkDelayGlobal.Checked then
begin
valDelayGlobal.Enabled := True;
chkDelayTopLeft.Enabled := False;
valDelayTopLeft.Enabled := False;
chkDelayTopRight.Enabled := False;
valDelayTopRight.Enabled := False;
chkDelayBotLeft.Enabled := False;
valDelayBotLeft.Enabled := False;
chkDelayBotRight.Enabled := False;
valDelayBotRight.Enabled := False;
end
else
begin
valDelayGlobal.Enabled := False;
chkDelayTopLeft.Enabled := True;
valDelayTopLeft.Enabled := True;
chkDelayTopRight.Enabled := True;
valDelayTopRight.Enabled := True;
chkDelayBotLeft.Enabled := True;
valDelayBotLeft.Enabled := True;
chkDelayBotRight.Enabled := True;
valDelayBotRight.Enabled := True;
end;
end;
procedure TfrmAdvSettings.FormCreate(Sender: TObject);
begin
FormStyle := fsStayOnTop;
BorderStyle := bsSingle;
BorderIcons := [biSystemMenu, biMinimize];
Position := poScreenCenter;
valDelayGlobal.Enabled := False;
ReadAdvancedIni;
end;
procedure TfrmAdvSettings.Label4Click(Sender: TObject);
begin
ShellExecute(Handle, 'OPEN', 'http://apps.codigobit.info/p/support.html','','',SW_SHOWNORMAL);
end;
procedure TfrmAdvSettings.Label5Click(Sender: TObject);
var
// jValue: TJSonValue;
rversion: String;
begin
{ RESTClient1.BaseURL := 'https://updates.codigobit.net/app/winxcorners';
RESTRequest1.Execute;
try
jValue := RESTResponse1.JSONValue;
if Assigned(jValue) then
begin
rversion := jValue.GetValue('latestversion', '1.2');
if rversion = VERSION then
MessageDlg('You have the latest version.', mtInformation, [mbOK],0)
else
MessageDlg('', mtInformation, [mbOK],0);
end
else
MessageDlg('Couldn''t retrieve info. Please visit official page.', mtError, [mbOK],0);
except
MessageDlg('Error', mtInformation, [mbOK],0);
end;}
end;
procedure TfrmAdvSettings.ReadAdvancedIni;
var
ini: TIniFile;
begin
ini := TIniFile.Create(ExtractFilePath(ParamStr(0))+'settings.ini');
try
chkDelayGlobal.Checked := ini.ReadBool('Advanced','GlobalDelay',False);
valDelayGlobal.Text := ini.ReadString('Advanced','GlobalDelayVal', '3');
chkDelayTopLeft.Checked := ini.ReadBool('Advanced','TopLeftDelay', False);
valDelayTopLeft.Text := ini.ReadString('Advanced','TopLeftVal', '3');
chkDelayTopRight.Checked := ini.ReadBool('Advanced','TopRightDelay', False);
valDelayTopRight.Text := ini.ReadString('Advanced','TopRightDelayVal', '3');
chkDelayBotLeft.Checked := ini.ReadBool('Advanced','BotLeftDelay', False);
valDelayBotLeft.Text := ini.ReadString('Advanced','BotLeftDelayVal', '3');
chkDelayBotRight.Checked := ini.ReadBool('Advanced','BotRightDelay', False);
valDelayBotRight.Text := ini.ReadString('Advanced','BotRightDelayVal', '3');
chkShowCount.Checked := ini.ReadBool('Advanced', 'ShowCountDown', False);
chkCustom.Checked := ini.ReadBool('Advanced', 'CustomCommand', False);
frmTrayPopup.XPopupMenu.Items[5].Visible := chkCustom.Checked;
frmTrayPopup.UpdateXCombos;
edCommand.Text := ini.ReadString('Advanced', 'CustomCommandline', '');
edParams.Text := ini.ReadString('Advanced', 'CustomCommandparms', '');
chkHidden.Checked := ini.ReadBool('Advanced', 'CustomCommandHidden', False);
finally
ini.Free;
end;
end;
procedure TfrmAdvSettings.SaveAdvancedIni;
var
ini: TIniFile;
begin
ini := TIniFile.Create(ExtractFilePath(ParamStr(0))+'settings.ini');
try
ini.WriteBool('Advanced','GlobalDelay',chkDelayGlobal.Checked);
ini.WriteInteger('Advanced','GlobalDelayVal', StrToInt(valDelayGlobal.Text));
ini.WriteBool('Advanced','TopLeftDelay',chkDelayTopLeft.Checked);
ini.WriteInteger('Advanced','TopLeftVal', StrToInt(valDelayTopLeft.Text));
ini.WriteBool('Advanced','TopRightDelay',chkDelayTopRight.Checked);
ini.WriteInteger('Advanced','TopRightDelayVal', StrToInt(valDelayTopRight.Text));
ini.WriteBool('Advanced','BotLeftDelay',chkDelayBotLeft.Checked);
ini.WriteInteger('Advanced','BotLeftDelayVal', StrToInt(valDelayBotLeft.Text));
ini.WriteBool('Advanced','BotRightDelay',chkDelayBotRight.Checked);
ini.WriteInteger('Advanced','BotRightDelayVal', StrToInt(valDelayBotRight.Text));
ini.WriteBool('Advanced', 'ShowCountDown', chkShowCount.Checked);
ini.WriteBool('Advanced', 'CustomCommand', chkCustom.Checked);
frmTrayPopup.XPopupMenu.Items[5].Visible := chkCustom.Checked;
frmTrayPopup.UpdateXCombos;
ini.WriteString('Advanced', 'CustomCommandline', edCommand.Text);
ini.WriteString('Advanced', 'CustomCommandparms', edParams.Text);
ini.WriteBool('Advanced', 'CustomCommandHidden', chkHidden.Checked);
finally
ini.Free;
end;
end;
procedure TfrmAdvSettings.UButton1Click(Sender: TObject);
begin
SaveAdvancedIni;
Close
end;
procedure TfrmAdvSettings.UButton2Click(Sender: TObject);
begin
ReadAdvancedIni;
close
end;
procedure TfrmAdvSettings.UListButton1Click(Sender: TObject);
begin
CardPanel1.ActiveCard := crdSettings;
end;
procedure TfrmAdvSettings.UListButton2Click(Sender: TObject);
begin
CardPanel1.ActiveCard := crdAbout;
end;
end.
| 31.514644 | 98 | 0.731147 |
47c5d0ed615ccb5633c1e5fae9fcb5f25bc26ea9 | 113 | pas | Pascal | tests/compare/pointer.pas | tranleduy2000/JSPIIJ | 84103b491f16adf06e252298ff93a2dcb99c2bb1 | [
"Apache-2.0"
]
| 1 | 2021-07-31T03:46:22.000Z | 2021-07-31T03:46:22.000Z | tests/compare/pointer.pas | tranleduy2000/JSPIIJ | 84103b491f16adf06e252298ff93a2dcb99c2bb1 | [
"Apache-2.0"
]
| null | null | null | tests/compare/pointer.pas | tranleduy2000/JSPIIJ | 84103b491f16adf06e252298ff93a2dcb99c2bb1 | [
"Apache-2.0"
]
| null | null | null | procedure proc(a: ^integer);
begin
a^ := 2;
end;
var
x: integer;
begin
proc(@x);
writeln(x)
end. | 10.272727 | 28 | 0.557522 |
f1f7b2a13eaf87b653c54922506d62fd4a8f416f | 9,554 | pas | Pascal | Source/Apps/Messenger/MainFormU.pas | ronaldhoek/GroupMeLib | 9380ac524ed8c9ebe3a30dccf0dddc1a91ce5eb0 | [
"MIT"
]
| null | null | null | Source/Apps/Messenger/MainFormU.pas | ronaldhoek/GroupMeLib | 9380ac524ed8c9ebe3a30dccf0dddc1a91ce5eb0 | [
"MIT"
]
| null | null | null | Source/Apps/Messenger/MainFormU.pas | ronaldhoek/GroupMeLib | 9380ac524ed8c9ebe3a30dccf0dddc1a91ce5eb0 | [
"MIT"
]
| null | null | null | unit MainFormU;
(*
INFORMATION
This unit containts a basic test form for GroupMe to
- request available groups
- request group details
- request group messages
VERSION HISTORY
2016-11-28 -> initialversion bij Ronald Hoek
*)
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.Controls.Presentation, IdBaseComponent, IdComponent, IdTCPConnection,
IdTCPClient, IdHTTP, FMX.ScrollBox, FMX.Memo, FMX.Edit, FMX.EditBox,
FMX.NumberBox, GroupMeRequestManagerU, GroupMeObjectsU, FMX.ListView.Types,
FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.ListView,
GroupMeMessengerU, System.SyncObjs, FMX.Layouts, FMX.TreeView;
type
TfrmMain = class(TForm)
btnGetGroup: TButton;
btnLogin: TButton;
edtGroupListPageSize: TNumberBox;
IdHTTP1: TIdHTTP;
Label1: TLabel;
lvGroups: TListView;
TreeView1: TTreeView;
btnSend: TButton;
mmText: TMemo;
procedure btnGetGroupClick(Sender: TObject);
procedure btnLoginClick(Sender: TObject);
procedure btnSendClick(Sender: TObject);
procedure edtGroupListPageSizeChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
FHttpUseLock: TSynchroObject;
FMessenger: TGroupMeMessenger;
FRequestManager: TGroupMeRequestManager;
procedure AddTreeViewGroup(aGroup: TGroupMeGroup);
procedure AddTreeViewMessage(aParent: TTreeViewItem; aMessage: TGroupMeMessage);
function GetGroupID(out aGroupID: TGroupMeGroupID): Boolean;
function GetTreeViewGroup(aGroupID: TGroupMeGroupID): TTreeViewItem;
procedure InitMessengerGroups;
procedure TokenChanged;
procedure OnRequest(const aRequestID: TGUID; aType:
TGroupMeMessengerRequestType; const URL, RequestData: string; out
ResponseData: string);
protected
procedure OnNewMessages(aGroupID: TGroupMeGroupID; aMessages:
ArrayOf_TGroupMeMessage; aMessageOrder: TGroupMeMessageOrder; var
aEventHandlerOwnsMessages: boolean);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
var
frmMain: TfrmMain;
implementation
uses
LoginFormU, System.IniFiles, AppFuncU;
{$R *.fmx}
procedure TfrmMain.btnGetGroupClick(Sender: TObject);
var
aGroupID: TGroupMeGroupID;
_GroupInfo: TGroupMeResponseGroupInfo;
begin
if not GetGroupID(aGroupID) then Exit;
_GroupInfo := FRequestManager.GetGroupInfo(aGroupID);
try
ShowMessage(
_GroupInfo.response.id.ToString + ' - ' +
_GroupInfo.response.name + ' - ' +
_GroupInfo.response.messages.last_message_id.ToString()
);
finally
_GroupInfo.Free;
end;
end;
procedure TfrmMain.btnLoginClick(Sender: TObject);
var
ini: TCustomIniFile;
begin
with TfrmLogin.Create(Self) do
try
if ShowModal = mrOK then
begin
FRequestManager.Token := Token;
FMessenger.Token := Token;
ForceDirectories(AppUserDataPath);
ini := TMemIniFile.Create(AppUserConfigFile);
try
ini.WriteString('UserAccess', 'Token', Token);
TMemIniFile(ini).UpdateFile;
finally
ini.Free;
end;
TokenChanged;
end;
finally
Free;
end;
end;
constructor TfrmMain.Create(AOwner: TComponent);
begin
FHttpUseLock := TCriticalSection.Create;
FRequestManager := TGroupMeRequestManager.Create(Self);
FRequestManager.OnRequest := OnRequest;
FMessenger := TGroupMeMessenger.Create(Self);
FMessenger.OnRequest := OnRequest;
FMessenger.OnNewMessages := OnNewMessages;
FMessenger.Active := True;
inherited;
end;
destructor TfrmMain.Destroy;
begin
FHttpUseLock.Acquire;
FMessenger.Active := False;
FMessenger.WaitFor;
inherited;
FreeAndNil(FHttpUseLock);
end;
procedure TfrmMain.AddTreeViewGroup(aGroup: TGroupMeGroup);
var
tvi: TTreeViewItem;
begin
tvi := TTreeViewItem.Create(TreeView1);
tvi.Text := aGroup.name;
tvi.Tag := aGroup.group_id;
TreeView1.AddObject(tvi);
end;
procedure TfrmMain.AddTreeViewMessage(aParent: TTreeViewItem; aMessage:
TGroupMeMessage);
function AttData: string;
var
I: Integer;
begin
Result := '';
for I := 0 to Length(aMessage.attachments) - 1 do
Result := Result + ' ' + aMessage.attachments[I].type_ + ':' + aMessage.attachments[I].url;
end;
var
tvi: TTreeViewItem;
begin
tvi := TTreeViewItem.Create(aParent);
tvi.Text := aMessage.created_at.ToString() + ' - ' + aMessage.text + AttData();
tvi.Tag := aMessage.id;
aParent.AddObject(tvi);
end;
procedure TfrmMain.btnSendClick(Sender: TObject);
var
aGroupID: TGroupMeGroupID;
msg: TGroupMeSendMessage;
begin
if not GetGroupID(aGroupID) then Exit;
msg := TGroupMeSendMessage.Create;
msg.message.text := mmText.Lines.Text;
TThread.CreateAnonymousThread(
procedure
begin
FRequestManager.SendMessage(aGroupID, msg);
end).Start;
mmText.Lines.Clear;
end;
procedure TfrmMain.edtGroupListPageSizeChange(Sender: TObject);
begin
FRequestManager.PageSizeGroupList := Round(edtGroupListPageSize.Value);
// FRequestManager.PageSizeGroupList := Round(edtGroupListPageSize.Value);
end;
procedure TfrmMain.FormCreate(Sender: TObject);
var
ini: TCustomIniFile;
begin
ini := TMemIniFile.Create(AppUserConfigFile);
try
FRequestManager.Token := ini.ReadString('UserAccess', 'Token', '');
FMessenger.Token := FRequestManager.Token;
TokenChanged;
finally
ini.Free;
end;
end;
function TfrmMain.GetGroupID(out aGroupID: TGroupMeGroupID): Boolean;
var
item: TListViewItem;
begin
item := (lvGroups.Selected as TListViewItem);
if Assigned(item) then
begin
aGroupID := item.Tag;
Result := True;
end else
Result := False;
end;
function TfrmMain.GetTreeViewGroup(aGroupID: TGroupMeGroupID): TTreeViewItem;
var
I: Integer;
begin
for I := 0 to TreeView1.Count - 1 do
begin
Result := TreeView1.Items[I];
if Result.Tag = aGroupID then
Exit;
end;
Result := nil;
end;
procedure TfrmMain.InitMessengerGroups;
begin
TThread.CreateAnonymousThread(
procedure
var
aList: TGroupMeResponseGroupList;
iPage: Integer;
begin
iPage := 1;
try
repeat
aList := FRequestManager.GetGroupList(iPage);
try
if Length(aList.response) > 0 then
begin
TThread.Synchronize(nil,
procedure
var
I: Integer;
item: TListViewItem;
_GroupIDs: ArrayOf_TGroupMeGroupID;
begin
SetLength(_GroupIDs, Length(aList.response));
for I := 0 to Length(aList.response) - 1 do
begin
_GroupIDs[I] := aList.response[I].id;
// ListView
item := lvGroups.Items.Add;
item.Text := aList.response[I].name;
item.Tag := aList.response[I].id;
// TreeView
AddTreeViewGroup(aList.response[I]);
end;
FMessenger.GroupIDs := _GroupIDs;
end);
end else
Break;
finally
aList.Free;
end;
Inc(iPage);
until False;
except
on E: Exception do
TThread.Synchronize(nil,
procedure
begin
ShowMessage(E.ClassName + ' - ' + E.Message);
end);
end;
end).Start;
end;
procedure TfrmMain.OnNewMessages(aGroupID: TGroupMeGroupID; aMessages:
ArrayOf_TGroupMeMessage; aMessageOrder: TGroupMeMessageOrder; var
aEventHandlerOwnsMessages: boolean);
begin
TThread.Synchronize(nil,
procedure
var
tvi: TTreeViewItem;
I: Integer;
begin
tvi := GetTreeViewGroup(aGroupID);
// what's the order of the message list?
case aMessageOrder of
moCreatedDescending:
for I := Length(aMessages) - 1 downto 0 do
AddTreeViewMessage(tvi, aMessages[I]);
moCreatedAscending:
for I := 0 to Length(aMessages) - 1 do
AddTreeViewMessage(tvi, aMessages[I]);
end;
end);
end;
procedure TfrmMain.OnRequest(const aRequestID: TGUID; aType:
TGroupMeMessengerRequestType; const URL, RequestData: string; out
ResponseData: string);
var
str: TStream;
begin
if FHttpUseLock = nil then Exit;
FHttpUseLock.Acquire;
try
if FHttpUseLock = nil then Exit;
case aType of
grtGet:
ResponseData := IdHTTP1.Get(URL);
grtPost:
begin
str := TStringStream.Create(RequestData);
try
IdHTTP1.Request.ContentType := 'application/json; charset=UTF-8';
ResponseData := IdHTTP1.Post(URL, str);
finally
str.Free;
end;
end
else
ResponseData := '';
end;
finally
FHttpUseLock.Release;
end;
end;
procedure TfrmMain.TokenChanged;
begin
Caption := 'Token: ' + FRequestManager.Token;
if FRequestManager.Token > '' then
InitMessengerGroups;
end;
end.
| 27.065156 | 98 | 0.644861 |
f1b0b32417f1d97e53b6005771683248e6a0a204 | 659 | dpr | Pascal | DesingPrinciples.dpr | bernardbr/delphi-design-principles | 5860a78414347af62229441cfeab07d8f81e62f5 | [
"MIT"
]
| null | null | null | DesingPrinciples.dpr | bernardbr/delphi-design-principles | 5860a78414347af62229441cfeab07d8f81e62f5 | [
"MIT"
]
| null | null | null | DesingPrinciples.dpr | bernardbr/delphi-design-principles | 5860a78414347af62229441cfeab07d8f81e62f5 | [
"MIT"
]
| null | null | null | program DesingPrinciples;
uses
Vcl.Forms,
FormPrincipal in 'FormPrincipal.pas' {frmPrincipal},
FormPrincipalController in 'FormPrincipalController.pas',
InterfaceFuncionarioModel in 'InterfaceFuncionarioModel.pas',
FuncionarioDAO in 'FuncionarioDAO.pas',
FuncionarioComissionadoModel in 'FuncionarioComissionadoModel.pas',
FuncionarioAssalariadoModel in 'FuncionarioAssalariadoModel.pas',
FuncionarioAssalariadoComComissaoModel in 'FuncionarioAssalariadoComComissaoModel.pas';
{$R *.res}
begin
Application.Initialize;
Application.MainFormOnTaskbar := True;
Application.CreateForm(TfrmPrincipal, frmPrincipal);
Application.Run;
end.
| 31.380952 | 89 | 0.823976 |
f193f856a411de564fb297976e459248e5fa2e04 | 17,034 | pas | Pascal | test/TestArray.pas | alexeylisyutenko/jansson-delphi | 9faa3167fd6c9bb77849499776e10980339d8afc | [
"MIT"
]
| 5 | 2020-05-20T16:24:16.000Z | 2021-04-12T00:49:43.000Z | test/TestArray.pas | alexeylisyutenko/jansson-delphi | 9faa3167fd6c9bb77849499776e10980339d8afc | [
"MIT"
]
| null | null | null | test/TestArray.pas | alexeylisyutenko/jansson-delphi | 9faa3167fd6c9bb77849499776e10980339d8afc | [
"MIT"
]
| 1 | 2020-05-21T18:52:34.000Z | 2020-05-21T18:52:34.000Z | unit TestArray;
interface
uses
TestFramework;
type
TTestArray = class(TTestCase)
published
procedure TestMisc;
procedure TestInsert;
procedure TestRemove;
procedure TestClear;
procedure TestExtend;
procedure TestCircular;
procedure TestArrayForeach;
procedure TestBadArgs;
end;
implementation
uses
Jansson;
procedure TTestArray.TestArrayForeach;
var
LArray1: PJson;
LArray2: PJson;
LValue: PJson;
LIndex: Integer;
begin
LArray1 := json_pack('[sisisi]', 'foo', 1, 'bar', 2, 'baz', 3);
LArray2 := json_array();
// replacement loop for json_array_foreach macros
LIndex := 0;
while LIndex < json_array_size(LArray1) do begin
LValue := json_array_get(LArray1, LIndex);
if (LValue = nil) then begin
Break;
end;
// action
json_array_append(LArray2, LValue);
Inc(LIndex);
end;
if json_equal(LArray1, LArray2) = 0 then begin
Fail('json_array_foreach failed to iterate all elements');
end;
json_decref(LArray1);
json_decref(LArray2);
end;
procedure TTestArray.TestBadArgs;
var
LArr: PJson;
LNum: PJson;
begin
LArr := json_array();
LNum := json_integer(1);
if (LArr = nil) or (LNum = nil) then begin
Fail('failed to create required objects');
end;
if json_array_size(nil) <> 0 then begin
Fail('NULL array has nonzero size');
end;
if json_array_size(LNum) <> 0 then begin
Fail('non-array has nonzero array size');
end;
if json_array_get(nil, 0) <> nil then begin
Fail('json_array_get did not return NULL for non-array');
end;
if json_array_get(LNum, 0) <> nil then begin
Fail('json_array_get did not return NULL for non-array');
end;
if json_array_set_new(nil, 0, json_incref(LNum)) = 0 then begin
Fail('json_array_set_new did not return error for non-array');
end;
if json_array_set_new(LNum, 0, json_incref(LNum)) = 0 then begin
Fail('json_array_set_new did not return error for non-array');
end;
if json_array_set_new(LArr, 0, nil) = 0 then begin
Fail('json_array_set_new did not return error for NULL value');
end;
if json_array_set_new(LArr, 0, json_incref(LArr)) = 0 then begin
Fail('json_array_set_new did not return error for value == array');
end;
if json_array_remove(nil, 0) = 0 then begin
Fail('json_array_remove did not return error for non-array');
end;
if json_array_remove(LNum, 0) = 0 then begin
Fail('json_array_remove did not return error for non-array');
end;
if json_array_clear(nil) = 0 then begin
Fail('json_array_clear did not return error for non-array');
end;
if json_array_clear(LNum) = 0 then begin
Fail('json_array_clear did not return error for non-array');
end;
if json_array_append_new(nil, json_incref(LNum)) = 0 then begin
Fail('json_array_append_new did not return error for non-array');
end;
if json_array_append_new(LNum, json_incref(LNum)) = 0 then begin
Fail('json_array_append_new did not return error for non-array');
end;
if json_array_append_new(LArr, nil) = 0 then begin
Fail('json_array_append_new did not return error for NULL value');
end;
if json_array_append_new(LArr, json_incref(LArr)) = 0 then begin
Fail('json_array_append_new did not return error for value == array');
end;
if json_array_insert_new(nil, 0, json_incref(LNum)) = 0 then begin
Fail('json_array_insert_new did not return error for non-array');
end;
if json_array_insert_new(LNum, 0, json_incref(LNum)) = 0 then begin
Fail('json_array_insert_new did not return error for non-array');
end;
if json_array_insert_new(LArr, 0, nil) = 0 then begin
Fail('json_array_insert_new did not return error for NULL value');
end;
if json_array_insert_new(LArr, 0, json_incref(LArr)) = 0 then begin
Fail('json_array_insert_new did not return error for value == array');
end;
if json_array_extend(nil, LArr) = 0 then begin
Fail('json_array_extend did not return error for first argument '
+'non-array');
end;
if json_array_extend(LNum, LArr) = 0 then begin
Fail('json_array_extend did not return error for first argument '
+'non-array');
end;
if json_array_extend(LArr, nil) = 0 then begin
Fail('json_array_extend did not return error for second argument '
+'non-array');
end;
if json_array_extend(LArr, LNum) = 0 then begin
Fail('json_array_extend did not return error for second argument '
+'non-array');
end;
if LNum.refcount <> 1 then begin
Fail('unexpected reference count on num');
end;
if LArr.refcount <> 1 then begin
Fail('unexpected reference count on arr');
end;
json_decref(LNum);
json_decref(LArr);
end;
procedure TTestArray.TestCircular;
var
LArray1: PJson;
LArray2: PJson;
begin
(* the simple cases are checked *)
LArray1 := json_array();
if LArray1 = nil then begin
Fail('unable to create array');
end;
if json_array_append(LArray1, LArray1) = 0 then begin
Fail('able to append self');
end;
if json_array_insert(LArray1, 0, LArray1) = 0 then begin
Fail('able to insert self');
end;
if json_array_append_new(LArray1, json_true()) <> 0 then begin
Fail('failed to append true');
end;
if json_array_set(LArray1, 0, LArray1) = 0 then begin
Fail('able to set self');
end;
json_decref(LArray1);
(* create circular references *)
LArray1 := json_array();
LArray2 := json_array();
if (LArray1 = nil) or (LArray2 = nil) then begin
Fail('unable to create array');
end;
if (json_array_append(LArray1, LArray2) <> 0) or (json_array_append(LArray2, LArray1) <> 0) then begin
Fail('unable to append');
end;
(* circularity is detected when dumping *)
if json_dumps(LArray1, 0) <> nil then begin
Fail('able to dump circulars');
end;
(* decref twice to deal with the circular references *)
json_decref(LArray1);
json_decref(LArray2);
json_decref(LArray1);
end;
procedure TTestArray.TestClear;
var
LArray: PJson;
LFive: PJson;
LSeven: PJson;
I: Integer;
begin
LArray := json_array();
LFive := json_integer(5);
LSeven := json_integer(7);
if LArray = nil then begin
Fail('unable to create array');
end;
if (LFive = nil) or (LSeven = nil) then begin
Fail('unable to create integer');
end;
for I := 0 to 9 do begin
if json_array_append(LArray, LFive) <> 0 then begin
Fail('unable to append');
end;
end;
for I := 0 to 9 do begin
if json_array_append(LArray, LSeven) <> 0 then begin
Fail('unable to append');
end;
end;
if json_array_size(LArray) <> 20 then begin
Fail('array size is invalid after appending');
end;
if json_array_clear(LArray) <> 0 then begin
Fail('unable to clear');
end;
if json_array_size(LArray) <> 0 then begin
Fail('array size is invalid after clearing');
end;
json_decref(LFive);
json_decref(LSeven);
json_decref(LArray);
end;
procedure TTestArray.TestExtend;
var
LArray1: PJson;
LArray2: PJson;
LFive: PJson;
LSeven: PJson;
I: Integer;
begin
LArray1 := json_array();
LArray2 := json_array();
LFive := json_integer(5);
LSeven := json_integer(7);
if (LArray1 = nil) or (LArray2 = nil) then begin
Fail('unable to create array');
end;
if (LFive = nil) or (LSeven = nil) then begin
Fail('unable to create integer');
end;
for I := 0 to 9 do begin
if json_array_append(LArray1, LFive) <> 0 then begin
Fail('unable to append');
end;
end;
for I := 0 to 9 do begin
if json_array_append(LArray2, LSeven) <> 0 then begin
Fail('unable to append');
end;
end;
if (json_array_size(LArray1) <> 10) or (json_array_size(LArray2) <> 10) then begin
Fail('array size is invalid after appending');
end;
if json_array_extend(LArray1, LArray2) <> 0 then begin
Fail('unable to extend');
end;
for I := 0 to 9 do begin
if json_array_get(LArray1, i) <> LFive then begin
Fail('invalid array contents after extending');
end;
end;
for I := 10 to 19 do begin
if json_array_get(LArray1, i) <> LSeven then begin
Fail('invalid array contents after extending');
end;
end;
json_decref(LFive);
json_decref(LSeven);
json_decref(LArray1);
json_decref(LArray2);
end;
procedure TTestArray.TestInsert;
var
LArray: PJson;
LFive: PJson;
LSeven: PJson;
LEleven: PJson;
LValue: PJson;
I: Integer;
begin
LArray := json_array;
LFive := json_integer(5);
LSeven := json_integer(7);
LEleven := json_integer(11);
if LArray = nil then begin
Fail('unable to create array');
end;
if (LFive = nil) or (LSeven = nil) or (LEleven = nil) then begin
Fail('unable to create integer');
end;
if json_array_insert(LArray, 1, LFive) = 0 then begin
Fail('able to insert value out of bounds');
end;
if json_array_insert(LArray, 0, LFive) <> 0 then begin
Fail('unable to insert value in an empty array');
end;
if json_array_get(LArray, 0) <> LFive then begin
Fail('json_array_insert works incorrectly');
end;
if json_array_size(LArray) <> 1 then begin
Fail('array size is invalid after insertion');
end;
if json_array_insert(LArray, 1, LSeven) <> 0 then begin
Fail('unable to insert value at the end of an array');
end;
if json_array_get(LArray, 0) <> LFive then begin
Fail('json_array_insert works incorrectly');
end;
if json_array_get(LArray, 1) <> LSeven then begin
Fail('json_array_insert works incorrectly');
end;
if json_array_size(LArray) <> 2 then begin
Fail('array size is invalid after insertion');
end;
if json_array_insert(LArray, 1, LEleven) <> 0 then begin
Fail('unable to insert value in the middle of an array');
end;
if json_array_get(LArray, 0) <> LFive then begin
Fail('json_array_insert works incorrectly');
end;
if json_array_get(LArray, 1) <> LEleven then begin
Fail('json_array_insert works incorrectly');
end;
if json_array_get(LArray, 2) <> LSeven then begin
Fail('json_array_insert works incorrectly');
end;
if json_array_size(LArray) <> 3 then begin
Fail('array size is invalid after insertion');
end;
if json_array_insert_new(LArray, 2, json_integer(123)) <> 0 then begin
Fail('unable to insert value in the middle of an array');
end;
LValue := json_array_get(LArray, 2);
if (not json_is_integer(LValue)) or (json_integer_value(LValue) <> 123) then begin
Fail('json_array_insert_new works incorrectly');
end;
if json_array_size(LArray) <> 4 then begin
Fail('array size is invalid after insertion');
end;
for I := 0 to 19 do begin
if json_array_insert(LArray, 0, LSeven) <> 0 then begin
Fail('unable to insert value at the beginning of an array');
end
end;
for I := 0 to 19 do begin
if json_array_get(LArray, I) <> LSeven then begin
Fail('json_aray_insert works incorrectly');
end
end;
if json_array_size(LArray) <> 24 then begin
Fail('array size is invalid after loop insertion');
end;
json_decref(LFive);
json_decref(LSeven);
json_decref(LEleven);
json_decref(LArray);
end;
procedure TTestArray.TestMisc;
var
LArray: PJson;
LFive: PJson;
LSeven: PJson;
LValue: PJson;
I: Integer;
begin
LArray := json_array();
LFive := json_integer(5);
LSeven := json_integer(7);
if LArray = nil then begin
Fail('unable to create array');
end;
if (LFive = nil) or (LSeven = nil)then begin
Fail('unable to create integer');
end;
if json_array_size(LArray) <> 0 then begin
Fail('empty array has nonzero size');
end;
if json_array_append(LArray, nil) = 0 then begin
Fail('able to append NULL');
end;
if json_array_append(LArray, LFive) <> 0 then begin
Fail('unable to append');
end;
if json_array_size(LArray) <> 1 then begin
Fail('wrong array size');
end;
LValue := json_array_get(LArray, 0);
if LValue = nil then begin
Fail('unable to get item');
end;
if LValue <> LFive then begin
Fail('got wrong value');
end;
if json_array_append(LArray, LSeven) <> 0 then begin
Fail('unable to append value');
end;
if json_array_size(LArray) <> 2 then begin
Fail('wrong array size');
end;
LValue := json_array_get(LArray, 1);
if LValue = nil then begin
Fail('unable to get item');
end;
if LValue <> LSeven then begin
Fail('got wrong value');
end;
if json_array_set(LArray, 0, LSeven) <> 0 then begin
Fail('unable to set value');
end;
if json_array_set(LArray, 0, nil) = 0 then begin
Fail('able to set NULL');
end;
if json_array_size(LArray) <> 2 then begin
Fail('wrong array size');
end;
LValue := json_array_get(LArray, 0);
if LValue = nil then begin
Fail('unable to get item');
end;
if LValue <> LSeven then begin
Fail('got wrong value');
end;
if json_array_get(LArray, 2) <> nil then begin
Fail('able to get value out of bounds');
end;
if json_array_set(LArray, 2, LSeven) = 0 then begin
Fail('able to set value out of bounds');
end;
for I := 2 to 29 do begin
if json_array_append(LArray, LSeven) <> 0 then begin
Fail('unable to append value');
end;
if json_array_size(LArray) <> I + 1 then begin
Fail('wrong array size');
end;
end;
for I := 0 to 29 do begin
LValue := json_array_get(LArray, I);
if LValue = nil then begin
Fail('unable to get item');
end;
if LValue <> LSeven then begin
Fail('got wrong value');
end;
end;
if json_array_set_new(LArray, 15, json_integer(123)) <> 0 then begin
Fail('unable to set new value');
end;
LValue := json_array_get(LArray, 15);
if (not json_is_integer(LValue)) or (json_integer_value(LValue) <> 123) then begin
Fail('json_array_set_new works incorrectly');
end;
if json_array_set_new(LArray, 15, nil) = 0 then begin
Fail('able to set_new NULL value');
end;
if json_array_append_new(LArray, json_integer(321)) <> 0 then begin
Fail('unable to append new value');
end;
LValue := json_array_get(LArray, json_array_size(LArray) - 1);
if (not json_is_integer(LValue)) or (json_integer_value(LValue) <> 321) then begin
Fail('json_array_append_new works incorrectly');
end;
if json_array_append_new(LArray, nil) = 0 then begin
Fail('able to append_new NULL value');
end;
json_decref(LFive);
json_decref(LSeven);
json_decref(LArray);
end;
procedure TTestArray.TestRemove;
var
LArray: PJson;
LFive: PJson;
LSeven: PJson;
I: Integer;
begin
LArray := json_array;
LFive := json_integer(5);
LSeven := json_integer(7);
if LArray = nil then begin
Fail('unable to create array');
end;
if LFive = nil then begin
Fail('unable to create integer');
end;
if LSeven = nil then begin
Fail('unable to create integer');
end;
if json_array_remove(LArray, 0) = 0 then begin
Fail('able to remove an unexisting index');
end;
if json_array_append(LArray, LFive) <> 0 then begin
Fail('unable to append');
end;
if json_array_remove(LArray, 1) = 0 then begin
Fail('able to remove an unexisting index');
end;
if json_array_remove(LArray, 0) <> 0 then begin
Fail('unable to remove');
end;
if json_array_size(LArray) <> 0 then begin
Fail('array size is invalid after removing');
end;
if (json_array_append(LArray, LFive) <> 0) or (json_array_append(LArray, LSeven) <> 0) or
(json_array_append(LArray, LFive) <> 0) or (json_array_append(LArray, LSeven) <> 0) then begin
Fail('unable to append');
end;
if json_array_remove(LArray, 2) <> 0 then begin
Fail('unable to remove');
end;
if json_array_size(LArray) <> 3 then begin
Fail('array size is invalid after removing');
end;
if (json_array_get(LArray, 0) <> LFive) or (json_array_get(LArray, 1) <> LSeven) or
(json_array_get(LArray, 2) <> LSeven) then begin
Fail('remove works incorrectly');
end;
json_decref(LArray);
LArray := json_array();
for I := 0 to 3 do begin
json_array_append(LArray, LFive);
json_array_append(LArray, LSeven);
end;
if json_array_size(LArray) <> 8 then begin
Fail('unable to append 8 items to array');
end;
(* Remove an element from a "full" array. *)
json_array_remove(LArray, 5);
json_decref(LFive);
json_decref(LSeven);
json_decref(LArray);
end;
initialization
RegisterTest(TTestArray.Suite);
end.
| 26.287037 | 105 | 0.653869 |
478d59a1d2a21718d305fc599ed52e78ad1c7d69 | 7,417 | dfm | Pascal | DEMO/Demos/08_UserVars/CBuilder/Unit1.dfm | alexeysmorkalov/vtkTools.PReport | f07e1189ad0a4beaf00cdc3e4a4f5f29e000cf55 | [
"MIT"
]
| null | null | null | DEMO/Demos/08_UserVars/CBuilder/Unit1.dfm | alexeysmorkalov/vtkTools.PReport | f07e1189ad0a4beaf00cdc3e4a4f5f29e000cf55 | [
"MIT"
]
| null | null | null | DEMO/Demos/08_UserVars/CBuilder/Unit1.dfm | alexeysmorkalov/vtkTools.PReport | f07e1189ad0a4beaf00cdc3e4a4f5f29e000cf55 | [
"MIT"
]
| null | null | null | object Form1: TForm1
Left = 192
Top = 107
Width = 376
Height = 126
Caption = '8 - User vars'
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
OldCreateOrder = False
OnCreate = FormCreate
PixelsPerInch = 96
TextHeight = 13
object Label1: TLabel
Left = 8
Top = 12
Width = 90
Height = 13
Caption = 'Company contains:'
end
object Label2: TLabel
Left = 55
Top = 36
Width = 43
Height = 13
Caption = 'Order by:'
end
object Button1: TButton
Left = 16
Top = 64
Width = 257
Height = 25
Caption = 'Generate report'
TabOrder = 0
OnClick = Button1Click
end
object Edit1: TEdit
Left = 104
Top = 8
Width = 153
Height = 21
TabOrder = 1
end
object CheckBox1: TCheckBox
Left = 264
Top = 10
Width = 89
Height = 17
Caption = 'All customers'
Checked = True
State = cbChecked
TabOrder = 2
end
object ComboBox1: TComboBox
Left = 104
Top = 32
Width = 153
Height = 21
Style = csDropDownList
ItemHeight = 13
TabOrder = 3
Items.Strings = (
'Company'
'Country')
end
object prReport1: TprReport
Title = '8 - User vars'
ExportFromPage = 0
ExportToPage = 0
Values = <>
Variables = <>
PrinterName = 'Virtual printer'
OnUnknownVariable = prReport1UnknownVariable
OnUnknownObjFunction = prReport1UnknownObjFunction
Left = 312
Top = 56
SystemInfo = (
'OS: WIN32_NT 5.1.2600 Service Pack 1'
''
'PageSize: 4096'
'ActiveProcessorMask: $1000'
'NumberOfProcessors: 1'
'ProcessorType: 586'
''
'Compiler version: Builder5'
'PReport version: 1.9.7')
LOGPIXELSX = 96
LOGPIXELSY = 96
object prPage1: TprPage
Width = 2101
Height = 2969
PaperSize = 9
Orientation = poPortrait
lMargin = 7
rMargin = 7
tMargin = 5
bMargin = 5
object prHTitleBand1: TprHTitleBand
Height = 81
object prMemoObj1: TprMemoObj
dRec.Versions = <
item
Visible = True
Memo.Strings = (
'List of customers')
lBorder.Show = True
lBorder.Width = 1
rBorder.Show = True
rBorder.Width = 1
tBorder.Show = True
tBorder.Width = 1
bBorder.Show = True
bBorder.Width = 1
FillColor = clWhite
vAlign = prvTop
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -13
Font.Name = 'Arial Cyr'
Font.Style = []
FontSize = 10
end>
dRec.Left = 220
dRec.Top = 7
dRec.Right = 428
dRec.Bottom = 28
end
object prMemoObj4: TprMemoObj
dRec.Versions = <
item
Visible = True
Memo.Strings = (
'[FindValid]')
lBorder.Width = 1
rBorder.Width = 1
tBorder.Width = 1
bBorder.Width = 1
FillColor = 14933198
vAlign = prvTop
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -13
Font.Name = 'Arial Cyr'
Font.Style = []
CanResizeX = True
FontSize = 10
end>
dRec.Left = 7
dRec.Top = 33
dRec.Right = 726
dRec.Bottom = 52
end
object prMemoObj5: TprMemoObj
dRec.Versions = <
item
Visible = True
Memo.Strings = (
'Order by [Order]')
lBorder.Width = 1
rBorder.Width = 1
tBorder.Width = 1
bBorder.Width = 1
FillColor = 14933198
vAlign = prvTop
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -13
Font.Name = 'Arial Cyr'
Font.Style = []
CanResizeX = True
FontSize = 10
end>
dRec.Left = 7
dRec.Top = 58
dRec.Right = 726
dRec.Bottom = 77
end
end
object prHDetailBand1: TprHDetailBand
Height = 68
DataSetName = 'Query1'
ColCount = 1
object prMemoObj2: TprMemoObj
dRec.Versions = <
item
Visible = True
Memo.Strings = (
'[Query1.CustNo]')
lBorder.Show = True
lBorder.Width = 1
rBorder.Show = True
rBorder.Width = 1
tBorder.Show = True
tBorder.Width = 1
bBorder.Show = True
bBorder.Width = 1
FillColor = clWhite
vAlign = prvTop
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -13
Font.Name = 'Arial Cyr'
Font.Style = []
FontSize = 10
end>
dRec.Left = 8
dRec.Top = 4
dRec.Right = 78
dRec.Bottom = 24
end
object prMemoObj3: TprMemoObj
dRec.Versions = <
item
Visible = True
Memo.Strings = (
'[Query1.Company] (Country - [Query1.Country])')
lBorder.Show = True
lBorder.Width = 1
rBorder.Show = True
rBorder.Width = 1
tBorder.Show = True
tBorder.Width = 1
bBorder.Show = True
bBorder.Width = 1
FillColor = clWhite
vAlign = prvTop
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -13
Font.Name = 'Arial Cyr'
Font.Style = []
FontSize = 10
end>
dRec.Left = 98
dRec.Top = 4
dRec.Right = 450
dRec.Bottom = 24
end
object prMemoObj7: TprMemoObj
dRec.Versions = <
item
Visible = True
Memo.Strings = (
'Length of Company : [Query1.FieldLen("Company")]'
'First char of Company: [Query1.FieldSubString("Company", 1, 1)]')
lBorder.Show = True
lBorder.Width = 1
rBorder.Show = True
rBorder.Width = 1
tBorder.Show = True
tBorder.Width = 1
bBorder.Show = True
bBorder.Width = 1
FillColor = 14933198
vAlign = prvTop
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -13
Font.Name = 'Arial Cyr'
Font.Style = []
CanResizeY = True
FontSize = 10
end>
dRec.Left = 457
dRec.Top = 4
dRec.Right = 736
dRec.Bottom = 48
end
end
end
end
object Query1: TQuery
DatabaseName = 'DBDEMOS'
Left = 280
Top = 56
end
end
| 26.395018 | 82 | 0.479844 |
476f717f38bffaa8ccb4824e3ef543757520f210 | 53,979 | pas | Pascal | Grijjy.Http.pas | hkollmann/GrijjyFoundation | 8ff91c9f319d2c07a9b12dca8c481b96d47a2d23 | [
"BSD-2-Clause"
]
| 202 | 2017-01-09T19:30:32.000Z | 2022-03-09T09:53:47.000Z | Grijjy.Http.pas | hkollmann/GrijjyFoundation | 8ff91c9f319d2c07a9b12dca8c481b96d47a2d23 | [
"BSD-2-Clause"
]
| 40 | 2017-05-10T06:41:22.000Z | 2022-01-14T17:52:26.000Z | Grijjy.Http.pas | hkollmann/GrijjyFoundation | 8ff91c9f319d2c07a9b12dca8c481b96d47a2d23 | [
"BSD-2-Clause"
]
| 72 | 2017-01-17T00:52:24.000Z | 2022-03-24T09:14:56.000Z | unit Grijjy.Http;
{ Windows and Linux Cross-platform HTTP, HTTPS and HTTP/2 protocol
support class using scalable client sockets }
interface
{$I Grijjy.inc}
//{$DEFINE LOGGING}
{$DEFINE HTTP2}
uses
System.Classes,
System.SysUtils,
System.StrUtils,
System.SyncObjs,
System.DateUtils,
System.Messaging,
System.Net.URLClient,
System.Net.Socket,
System.Generics.Collections,
{$IFDEF MSWINDOWS}
Grijjy.SocketPool.Win,
Windows,
{$ENDIF}
{$IFDEF LINUX}
Grijjy.SocketPool.Linux,
Posix.Pthread,
{$ENDIF}
{$IFDEF HTTP2}
Nghttp2,
{$ENDIF}
Grijjy.BinaryCoding;
const
{ Socket buffer size }
BUFFER_SIZE = 32768;
{ Timeout for operations }
TIMEOUT_CONNECT = 20000;
TIMEOUT_RECV = 5000;
{ Strings }
S_CONTENT_LENGTH = 'content-length';
S_CONTENT_TYPE = 'content-type';
S_TRANSFER_ENCODING = 'transfer-encoding';
S_CHUNKED = 'chunked';
S_CHARSET = 'charset';
{ End of line }
CRLF = #13#10;
{ Ports }
DEFAULT_HTTP_PORT = 80;
DEFAULT_HTTPS_PORT = 443;
{ Cleanup }
INTERVAL_CLEANUP = 5000;
type
{ Http events }
TOnRedirect = procedure(Sender: TObject; var ALocation: String; const AFollow: Boolean) of object;
TOnPassword = procedure(Sender: TObject; var AAgain: Boolean) of object;
TOnRecv = procedure(Sender: TObject; const ABuffer: Pointer; const ASize: Integer; var ACreateResponse: Boolean) of object;
TOnSent = procedure(Sender: TObject; const ABuffer: Pointer; const ASize: Integer) of object;
{ ISO-8859-1 ASCII compatible string }
{$IFDEF MSWINDOWS}
ISO8859String = type AnsiString(28591);
{$ELSE}
ISO8859String = type RawByteString;
{$ENDIF}
type
{ Thread safe buffer }
TThreadSafeBuffer = class(TObject)
private
FLock: TCriticalSection;
FBuffer: TBytes;
FSize: Integer;
public
constructor Create(const ACapacity: Integer = BUFFER_SIZE);
destructor Destroy; override;
protected
function GetSize: Integer;
public
{ Write buffer }
procedure Write(const ABuffer: Pointer; const ASize: Integer);
{ Read entire buffer }
function Read(out ABytes: TBytes): Boolean; overload;
{ Read count number of bytes from the buffer }
function Read(out ABytes: TBytes; const ACount: Integer): Boolean; overload;
{ Read up to length number of bytes from the buffer, for nghttp2 }
function Read(const ABuffer: Pointer; var ALength: NativeInt): Boolean; overload;
{ Read all bytes up to and including substring match }
function ReadTo(const ASubStr: RawByteString; out ABytes: TBytes): Boolean;
{ Clear the buffer }
procedure Clear;
{$IFDEF LOGGING}
{ Outputs the buffer to log }
procedure Log(const AText: String);
{$ENDIF}
public
{ Current actual size of the buffer }
property Size: Integer read GetSize;
end;
type
{ Client activity state }
TgoHttpClientState = (None, Error, Sending, Receiving, Finished);
{ Http header }
TgoHttpHeader = record
Name: String;
Value: String;
{$IFDEF HTTP2}
NameAsISO8859: ISO8859String; { nghttp2 requires a pointer to a memory object we maintain }
ValueAsISO8859: ISO8859String;
{$ENDIF}
end;
{ Http headers class }
TgoHttpHeaders = class(TObject)
private
FHeaders: TArray<TgoHttpHeader>;
public
constructor Create;
destructor Destroy; override;
public
{ Add or set a header and value to a list of headers }
procedure AddOrSet(const AName, AValue: String); overload;
procedure AddOrSet(const AHeader: String); overload;
{ Get the value associated with the header }
function Value(const AName: String): String;
{ Returns the index of the associated header }
function IndexOf(const AName: String): Integer;
{ Reads headers as http compatible header string }
function AsString: String;
{ Reads headers as ngHttp2 compatible header array }
{$IFDEF HTTP2}
procedure AsNgHttp2Array(var AHeaders: TArray<nghttp2_nv>);
{$ENDIF}
public
property Headers: TArray<TgoHttpHeader> read FHeaders write FHeaders;
end;
{ Http client }
TgoHttpClient = class(TObject)
private
{$IFDEF HTTP2}
FHttp2: Boolean;
{$ENDIF}
FBlocking: Boolean;
FConnection: TgoSocketConnection;
FConnectionLock: TCriticalSection;
FState: TgoHttpClientState;
FConnectTimeout: Integer;
FRecvTimeout: Integer;
{ SSL }
FCertificate: TBytes;
FPrivateKey: TBytes;
{ Recv }
FRecvBuffer: TThreadSafeBuffer;
FRecvBuffer2: TThreadSafeBuffer;
FLastRecv: TDateTime;
FRecvAbort: Boolean;
FRecv: TEvent;
{ Send }
FSendBuffer: TThreadSafeBuffer;
FLastSent: TDateTime;
{ Http request }
FURL: String;
FMethod: String;
FURI: TURI;
FLastURI: TURI;
FContentLength: Int64;
FTransferEncoding: String;
FHttpVersion: String;
FFollowRedirects: Boolean;
FSentCookies: TStrings;
FCookies: TStrings;
FAuthorization: String;
FUserName: String;
FPassword: String;
FContentType: String;
FConnected: TEvent;
FInternalHeaders: TgoHttpHeaders;
FRequestStatusLine: String;
FRequestHeaders: TgoHttpHeaders;
FRequestBody: String;
FRequestData: TBytes;
FUserAgent: String;
FRange: String;
{ Http response }
FResponseHeader: Boolean;
FResponseHeaders: TgoHttpHeaders;
FResponseStatusCode: Integer;
FResponseContentType: String;
FResponseContentCharset: String;
FResponse: TBytes;
FResponseBytes: Integer;
FChunkSize: Integer;
{ ngHttp2 }
{$IFDEF HTTP2}
FStreamId2: Integer;
FResponseHeader2: Boolean;
FResponseContent2: Boolean;
FCallbacks_http2: pnghttp2_session_callbacks;
FSession_http2: pnghttp2_session;
{$ENDIF}
private
{ ngHttp2 callbacks }
{$IFDEF HTTP2}
function nghttp2_data_source_read_callback(session: pnghttp2_session;
stream_id: int32; buf: puint8; len: size_t; data_flags: puint32;
source: pnghttp2_data_source; user_data: Pointer): ssize_t; cdecl;
function nghttp2_on_data_chunk_recv_callback(session: pnghttp2_session;
flags: uint8; stream_id: int32; const data: puint8; len: size_t;
user_data: Pointer): Integer; cdecl;
function nghttp2_on_frame_recv_callback(session: pnghttp2_session;
const frame: pnghttp2_frame; user_data: Pointer): Integer; cdecl;
function nghttp2_on_header_callback(session: pnghttp2_session;
const frame: pnghttp2_frame; const name: puint8; namelen: size_t;
const value: puint8; valuelen: size_t; flags: uint8;
user_data: Pointer): Integer; cdecl;
function nghttp2_on_stream_close_callback(session: pnghttp2_session;
stream_id: int32; error_code: uint32; user_data: Pointer): Integer; cdecl;
function nghttp2_Send: Boolean;
function nghttp2_Recv: Boolean;
{$ENDIF}
protected
FOnPassword: TOnPassword;
FOnRedirect: TOnRedirect;
FOnSent: TOnSent;
FOnRecv: TOnRecv;
procedure SetCookies(const AValue: TStrings);
function GetIdleTime: Integer;
private
function GetCookies: TStrings;
private
procedure Reset;
procedure CreateRequest;
function SendRequest: Boolean;
function ResponseHeader: Boolean;
function ResponseContent: Boolean;
function WaitForRecv: Boolean;
function DoResponse(var AAgain: Boolean): TBytes;
function DoRequest(const AMethod, AURL: String;
out AResponse: TBytes; const AConnectTimeout, ARecvTimeout: Integer): Boolean;
protected
{ Socket routines }
procedure OnSocketConnected;
procedure OnSocketDisconnected;
procedure OnSocketSent(const ABuffer: Pointer; const ASize: Integer);
procedure OnSocketRecv(const ABuffer: Pointer; const ASize: Integer);
protected
procedure DoRecv(const ABuffer: Pointer; const ASize: Integer);
public
constructor Create(const AHttp2: Boolean = False; const ABlocking: Boolean = True);
destructor Destroy; override;
public
{ Get method }
function Get(const AURL: String; out AResponse: TBytes;
const AConnectTimeout: Integer = TIMEOUT_CONNECT;
const ARecvTimeout: Integer = TIMEOUT_RECV): Boolean; overload;
function Get(const AURL: String; out AResponse: String;
const AConnectTimeout: Integer = TIMEOUT_CONNECT;
const ARecvTimeout: Integer = TIMEOUT_RECV): Boolean; overload;
function Get(const AURL: String;
const AConnectTimeout: Integer = TIMEOUT_CONNECT;
const ARecvTimeout: Integer = TIMEOUT_RECV): String; overload;
{ Head method }
function Head(const AURL: String;
const AConnectTimeout: Integer = TIMEOUT_CONNECT;
const ARecvTimeout: Integer = TIMEOUT_RECV): Boolean;
{ Post method }
function Post(const AURL: String; out AResponse: TBytes;
const AConnectTimeout: Integer = TIMEOUT_CONNECT;
const ARecvTimeout: Integer = TIMEOUT_RECV): Boolean; overload;
function Post(const AURL: String; out AResponse: String;
const AConnectTimeout: Integer = TIMEOUT_CONNECT;
const ARecvTimeout: Integer = TIMEOUT_RECV): Boolean; overload;
function Post(const AURL: String;
const AConnectTimeout: Integer = TIMEOUT_CONNECT;
const ARecvTimeout: Integer = TIMEOUT_RECV): String; overload;
{ Put method }
function Put(const AURL: String; out AResponse: TBytes;
const AConnectTimeout: Integer = TIMEOUT_CONNECT;
const ARecvTimeout: Integer = TIMEOUT_RECV): Boolean; overload;
function Put(const AURL: String; out AResponse: String;
const AConnectTimeout: Integer = TIMEOUT_CONNECT;
const ARecvTimeout: Integer = TIMEOUT_RECV): Boolean; overload;
function Put(const AURL: String;
const AConnectTimeout: Integer = TIMEOUT_CONNECT;
const ARecvTimeout: Integer = TIMEOUT_RECV): String; overload;
{ Delete method }
function Delete(const AURL: String; out AResponse: TBytes;
const AConnectTimeout: Integer = TIMEOUT_CONNECT;
const ARecvTimeout: Integer = TIMEOUT_RECV): Boolean; overload;
function Delete(const AURL: String; out AResponse: String;
const AConnectTimeout: Integer = TIMEOUT_CONNECT;
const ARecvTimeout: Integer = TIMEOUT_RECV): Boolean; overload;
function Delete(const AURL: String;
const AConnectTimeout: Integer = TIMEOUT_CONNECT;
const ARecvTimeout: Integer = TIMEOUT_RECV): String; overload;
{ Options method }
function Options(const AURL: String; out AResponse: TBytes;
const AConnectTimeout: Integer = TIMEOUT_CONNECT;
const ARecvTimeout: Integer = TIMEOUT_RECV): Boolean; overload;
function Options(const AURL: String; out AResponse: String;
const AConnectTimeout: Integer = TIMEOUT_CONNECT;
const ARecvTimeout: Integer = TIMEOUT_RECV): Boolean; overload;
function Options(const AURL: String;
const AConnectTimeout: Integer = TIMEOUT_CONNECT;
const ARecvTimeout: Integer = TIMEOUT_RECV): String; overload;
{ Close connection }
procedure Close;
{ Convert bytes to string }
function BytesToString(const ABytes: TBytes; const ACharset: String): String;
public
{ State }
property State: TgoHttpClientState read FState;
{ Idle time in milliseconds }
property IdleTime: Integer read GetIdleTime;
{ Cookies sent to the server and received from the server }
property Cookies: TStrings read GetCookies write SetCookies;
{ Optional body for a request.
You can either use RequestBody or RequestData. If both are specified then
only RequestBody is used. }
property RequestBody: String read FRequestBody write FRequestBody;
{ Optional binary body data for a request.
You can either use RequestBody or RequestData. If both are specified then
only RequestBody is used. }
property RequestData: TBytes read FRequestData write FRequestData;
{ Request headers }
property RequestHeaders: TgoHttpHeaders read FRequestHeaders;
{ Response headers from the server }
property ResponseHeaders: TgoHttpHeaders read FResponseHeaders;
{ Response status code }
property ResponseStatusCode: Integer read FResponseStatusCode;
{ Response content type }
property ResponseContentType: String read FResponseContentType;
{ Response charset }
property ResponseContentCharset: String read FResponseContentCharset;
{ Response content length }
property ContentLength: Int64 read FContentLength;
{ Allow 301 and other redirects }
property FollowRedirects: Boolean read FFollowRedirects write FFollowRedirects;
{ Called when a redirect is requested }
property OnRedirect: TOnRedirect read FOnRedirect write FOnRedirect;
{ Called when a password is needed }
property OnPassword: TOnPassword read FOnPassword write FOnPassword;
{ Called when a buffer is received from the socket }
property OnRecv: TOnRecv read FOnRecv write FOnRecv;
{ Called when the data has been sent by the socket }
property OnSent: TOnSent read FOnSent write FOnSent;
{ Username and password for Basic Authentication }
property UserName: String read FUserName write FUserName;
property Password: String read FPassword write FPassword;
{ Content type }
property ContentType: String read FContentType write FContentType;
{ User agent }
property UserAgent: String read FUserAgent write FUserAgent;
{ Range }
property Range: String read FRange write FRange;
{ Authorization }
property Authorization: String read FAuthorization write FAuthorization;
{ Certificate in PEM format }
property Certificate: TBytes read FCertificate write FCertificate;
{ Private key in PEM format }
property PrivateKey: TBytes read FPrivateKey write FPrivateKey;
end;
{ Http response message }
TgoHttpResponseMessage = class(TMessage)
private
FHttpClient: TgoHttpClient;
FResponseHeaders: TgoHttpHeaders;
FResponseStatusCode: Integer;
FResponseContentType: String;
FResponseContentCharset: String;
FResponse: TBytes;
public
constructor Create(
const AHttpClient: TgoHttpClient;
const AResponseHeaders: TgoHttpHeaders;
const AResponseStatusCode: Integer;
const AResponseContentType: String;
const AResponseContentCharset: String;
const AResponse: TBytes);
public
property HttpClient: TgoHttpClient read FHttpClient;
property ResponseHeaders: TgoHttpHeaders read FResponseHeaders;
property ResponseStatusCode: Integer read FResponseStatusCode;
property ResponseContentType: String read FResponseContentType;
property ResponseContentCharset: String read FResponseContentCharset;
property Response: TBytes read FResponse;
end;
{ Http client manager }
TgoHttpClientManager = class(TThread)
private
FHttpClients: TList<TgoHttpClient>;
FLock: TCriticalSection;
procedure FreeClients(const AForce: Boolean = False);
protected
procedure Execute; override;
public
constructor Create;
destructor Destroy; override;
public
{ Queues the http client for release }
procedure Release(const AHttpClient: TgoHttpClient);
end;
var
HttpClientManager: TgoHttpClientManager;
implementation
uses
Grijjy.SysUtils;
var
_HttpClientSocketManager: TgoClientSocketManager;
{ ngHttp2 callback cdecl }
{$IFDEF HTTP2}
function data_source_read_callback(session: pnghttp2_session;
stream_id: int32; buf: puint8; len: size_t; data_flags: puint32;
source: pnghttp2_data_source; user_data: Pointer): ssize_t; cdecl;
var
Http: TgoHttpClient;
begin
Assert(Assigned(user_data));
Http := TgoHttpClient(user_data);
Result := Http.nghttp2_data_source_read_callback(session, stream_id, buf, len, data_flags, source, user_data);
end;
function on_header_callback(session: pnghttp2_session; const frame: pnghttp2_frame;
const name: puint8; namelen: size_t; const value: puint8; valuelen: size_t;
flags: uint8; user_data: Pointer): Integer; cdecl;
var
Http: TgoHttpClient;
begin
Assert(Assigned(user_data));
Http := TgoHttpClient(user_data);
Result := Http.nghttp2_on_header_callback(session, frame, name, namelen, value, valuelen, flags, user_data);
end;
function on_frame_recv_callback(session: pnghttp2_session;
const frame: pnghttp2_frame; user_data: Pointer): Integer; cdecl;
var
Http: TgoHttpClient;
begin
Assert(Assigned(user_data));
Http := TgoHttpClient(user_data);
Result := Http.nghttp2_on_frame_recv_callback(session, frame, user_data);
end;
function on_data_chunk_recv_callback(session: pnghttp2_session;
flags: uint8; stream_id: int32; const data: puint8; len: size_t;
user_data: Pointer): Integer; cdecl;
var
Http: TgoHttpClient;
begin
Assert(Assigned(user_data));
Http := TgoHttpClient(user_data);
Result := Http.nghttp2_on_data_chunk_recv_callback(session, flags, stream_id, data, len, user_data);
end;
function on_stream_close_callback(session: pnghttp2_session;
stream_id: int32; error_code: uint32; user_data: Pointer): Integer; cdecl;
var
Http: TgoHttpClient;
begin
Assert(Assigned(user_data));
Http := TgoHttpClient(user_data);
Result := Http.nghttp2_on_stream_close_callback(session, stream_id, error_code, user_data);
end;
{$ENDIF}
{ TThreadSafeBuffer }
constructor TThreadSafeBuffer.Create(const ACapacity: Integer);
begin
SetLength(FBuffer, ACapacity);
FSize := 0;
FLock := TCriticalSection.Create;
end;
destructor TThreadSafeBuffer.Destroy;
begin
FLock.Free;
inherited;
end;
function TThreadSafeBuffer.GetSize: Integer;
begin
FLock.Enter;
try
Result := FSize;
finally
FLock.Leave;
end;
end;
procedure TThreadSafeBuffer.Write(const ABuffer: Pointer; const ASize: Integer);
begin
FLock.Enter;
try
{ expand buffer }
if FSize + ASize >= Length(FBuffer) then
SetLength(FBuffer, (FSize + ASize) * 2);
{ append bytes }
Move(ABuffer^, FBuffer[FSize], ASize);
FSize := FSize + ASize;
finally
FLock.Leave;
end;
end;
function TThreadSafeBuffer.Read(out ABytes: TBytes): Boolean;
begin
FLock.Enter;
try
if FSize > 0 then
begin
{ read bytes into new buffer }
SetLength(ABytes, FSize);
Move(FBuffer[0], ABytes[0], FSize);
{ clear buffer }
FSize := 0;
Result := True;
end
else
Result := False;
finally
FLock.Leave;
end;
end;
function TThreadSafeBuffer.Read(out ABytes: TBytes; const ACount: Integer): Boolean;
var
Size: Integer;
begin
FLock.Enter;
try
if FSize > 0 then
begin
{ read bytes into new buffer }
if FSize >= ACount then
Size := ACount
else
Size := FSize;
SetLength(ABytes, Size);
Move(FBuffer[0], ABytes[0], Size);
{ delete buffer }
if FSize > Size then
begin
Move(FBuffer[Size], FBuffer[0], FSize - Size);
FSize := FSize - Size;
end
else
FSize := 0;
Result := True;
end
else
Result := False;
finally
FLock.Leave;
end;
end;
function TThreadSafeBuffer.Read(const ABuffer: Pointer;
var ALength: NativeInt): Boolean;
begin
FLock.Enter;
try
if FSize > 0 then
begin
{ read bytes into existing buffer }
if FSize < ALength then
ALength := FSize;
Move(FBuffer[0], ABuffer^, ALength);
{ delete buffer }
if FSize > ALength then
begin
Move(FBuffer[ALength], FBuffer[0], FSize - ALength);
FSize := FSize - ALength;
end
else
FSize := 0;
Result := True;
end
else
Result := False;
finally
FLock.Leave;
end;
end;
function TThreadSafeBuffer.ReadTo(const ASubStr: RawByteString; out ABytes: TBytes): Boolean;
var
Size, Index: Integer;
begin
Result := False;
Size := Length(ASubStr);
FLock.Enter;
try
if FSize > Size then
for Index := 0 to FSize - Size do
if CompareMem(@FBuffer[Index], @ASubStr[1], Size) then
begin
{ read bytes into new buffer }
SetLength(ABytes, Index + Size);
Move(FBuffer[0], ABytes[0], Index + Size);
{ delete buffer }
if FSize > (Index + Size) then
begin
Move(FBuffer[Index + Size], FBuffer[0], FSize - (Index + Size));
FSize := FSize - (Index + Size);
end
else
FSize := 0;
Result := True;
Break;
end;
finally
FLock.Leave;
end;
end;
procedure TThreadSafeBuffer.Clear;
begin
FLock.Enter;
try
FSize := 0;
finally
FLock.Leave;
end;
end;
{$IFDEF LOGGING}
procedure TThreadSafeBuffer.Log(const AText: String);
begin
//grLog(Format('RecvBuffer %s (Size=%d)', [AText, FSize]), @FBuffer[0], FSize);
end;
{$ENDIF}
{ THttpHeaders }
constructor TgoHttpHeaders.Create;
begin
end;
destructor TgoHttpHeaders.Destroy;
begin
FHeaders := nil;
inherited;
end;
procedure TgoHttpHeaders.AddOrSet(const AName, AValue: String);
var
Index: Integer;
Header: TgoHttpHeader;
begin
Index := IndexOf(AName);
if Index = -1 then
begin
Header.Name := AName;
Header.Value := AValue;
{$IFDEF HTTP2}
Header.NameAsISO8859 := ISO8859String(AName);
Header.ValueAsISO8859 := ISO8859String(AValue);
{$ENDIF}
FHeaders := FHeaders + [Header];
end
else
begin
FHeaders[Index].Name := AName;
FHeaders[Index].Value := AValue;
{$IFDEF HTTP2}
FHeaders[Index].NameAsISO8859 := ISO8859String(AName);
FHeaders[Index].ValueAsISO8859 := ISO8859String(AValue);
{$ENDIF}
end;
end;
procedure TgoHttpHeaders.AddOrSet(const AHeader: String);
var
Index: Integer;
Name: String;
Value: String;
begin
Index := AHeader.IndexOf(':');
if Index > -1 then
begin
Name := AHeader.Substring(0, Index);
Value := AHeader.Substring(Index + 1);
AddOrSet(Name, Value);
end;
end;
function TgoHttpHeaders.Value(const AName: String): String;
var
Header: TgoHttpHeader;
begin
Result := '';
for Header in FHeaders do
if Header.Name.ToLower = AName.ToLower then
begin
Result := String(Header.Value).TrimLeft;
Break;
end;
end;
function TgoHttpHeaders.IndexOf(const AName: String): Integer;
var
Index: Integer;
begin
Result := -1;
for Index := 0 to Length(FHeaders) - 1 do
if FHeaders[Index].Name.ToLower = AName.ToLower then
begin
Result := Index;
Break;
end;
end;
function TgoHttpHeaders.AsString: String;
var
Header: TgoHttpHeader;
begin
for Header in FHeaders do
Result := Result + Header.Name + ': ' + Header.Value + CRLF;
end;
{$IFDEF HTTP2}
procedure TgoHttpHeaders.AsNgHttp2Array(var AHeaders: TArray<nghttp2_nv>);
var
Header: TgoHttpHeader;
NgHttp2Header: nghttp2_nv;
begin
for Header in FHeaders do
begin
NgHttp2Header.name := MarshaledAString(Header.NameAsISO8859);
NgHttp2Header.value := MarshaledAString(Header.ValueAsISO8859);
NgHttp2Header.namelen := Length(Header.Name);
NgHttp2Header.valuelen := Length(Header.Value);
NgHttp2Header.flags := NGHTTP2_NV_FLAG_NONE;
AHeaders := AHeaders + [NgHttp2Header];
end;
end;
{$ENDIF}
{ TgoHttpResponseMessage }
constructor TgoHttpResponseMessage.Create(const AHttpClient: TgoHttpClient;
const AResponseHeaders: TgoHttpHeaders;
const AResponseStatusCode: Integer;
const AResponseContentType, AResponseContentCharset: String;
const AResponse: TBytes);
begin
inherited Create;
FHttpClient := AHttpClient;
FResponseHeaders := AResponseHeaders;
FResponseStatusCode := AResponseStatusCode;
FResponseContentType := AResponseContentType;
FResponseContentCharset := AResponseContentCharset;
FResponse := AResponse;
end;
{ TgoHttpClientManager }
constructor TgoHttpClientManager.Create;
begin
inherited Create;
FHttpClients := TList<TgoHttpClient>.Create;
FLock := TCriticalSection.Create;
end;
destructor TgoHttpClientManager.Destroy;
begin
FreeClients(True);
FLock.Free;
FHttpClients.Free;
inherited;
end;
procedure TgoHttpClientManager.FreeClients(const AForce: Boolean);
var
HttpClient: TgoHttpClient;
HttpClients: TArray<TgoHttpClient>;
ClientsToFree: TArray<TgoHttpClient>;
begin
FLock.Enter;
try
HttpClients := FHttpClients.ToArray;
for HttpClient in HttpClients do
begin
if (AForce) or
(HttpClient.IdleTime > HttpClient.FRecvTimeout) then
if (HttpClient.State = TgoHttpClientState.Sending) or
(HttpClient.State = TgoHttpClientState.Receiving) then
HttpClient.Close;
if (AForce) or
(HttpClient.IdleTime > HttpClient.FRecvTimeout) or
(HttpClient.State = TgoHttpClientState.Finished) or
(HttpClient.State = TgoHttpClientState.Error) or
(HttpClient.State = TgoHttpClientState.None) then
begin
ClientsToFree := ClientsToFree + [HttpClient];
FHttpClients.Remove(HttpClient);
end;
end;
finally
FLock.Leave;
end;
for HttpClient in ClientsToFree do
HttpClient.DisposeOf;
end;
procedure TgoHttpClientManager.Execute;
var
LastCleanup: TDateTime;
begin
LastCleanup := Now;
while not Terminated do
begin
if MillisecondsBetween(Now, LastCleanup) > INTERVAL_CLEANUP then
begin
FreeClients;
LastCleanup := Now;
end
else
Sleep(5); { waiting for interval }
end;
end;
procedure TgoHttpClientManager.Release(const AHttpClient: TgoHttpClient);
begin
FLock.Enter;
try
FHttpClients.Add(AHttpClient);
finally
FLock.Leave;
end;
end;
{ TgoHttpClient }
constructor TgoHttpClient.Create(const AHttp2: Boolean = False; const ABlocking: Boolean = True);
{$IFDEF HTTP2}
var
Settings: nghttp2_settings_entry;
Error: Integer;
{$ENDIF}
begin
inherited Create;
{ initialize nghttp2 library }
{$IFDEF HTTP2}
if nghttp2_session_callbacks_new(FCallbacks_http2) = 0 then
begin
nghttp2_session_callbacks_set_on_header_callback(FCallbacks_http2, on_header_callback);
nghttp2_session_callbacks_set_on_frame_recv_callback(FCallbacks_http2, on_frame_recv_callback);
nghttp2_session_callbacks_set_on_data_chunk_recv_callback(FCallbacks_http2, on_data_chunk_recv_callback);
nghttp2_session_callbacks_set_on_stream_close_callback(FCallbacks_http2, on_stream_close_callback);
if (nghttp2_session_client_new(FSession_http2, FCallbacks_http2, Self) = 0) then
begin
Settings.settings_id := NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS;
Settings.value := 100;
Error := nghttp2_submit_settings(FSession_http2, NGHTTP2_FLAG_NONE, @Settings, 1);
if (Error <> 0) then
raise Exception.Create('Unable to submit ngHttp2 settings');
end
else
raise Exception.Create('Unable to setup ngHttp2 session.');
end
else
raise Exception.Create('Unable to setup ngHttp2 callbacks.');
FHttp2 := AHttp2;
{$ENDIF}
FState := TgoHttpClientState.None;
FBlocking := ABlocking;
FHttpVersion := '1.1';
FAuthorization := '';
FContentType := '';
FUserAgent := '';
FRange := '';
FConnection := nil;
FConnectionLock := TCriticalSection.Create;
FConnected := TEvent.Create(nil, False, False, '');
FFollowRedirects := True;
FSendBuffer := TThreadSafeBuffer.Create;
FRecvBuffer := TThreadSafeBuffer.Create;
FRecvBuffer2 := TThreadSafeBuffer.Create;
FRecv := TEvent.Create(nil, False, False, '');
FRequestHeaders := TgoHttpHeaders.Create;
FInternalHeaders := TgoHttpHeaders.Create;
FResponseHeaders := TgoHttpHeaders.Create;
end;
destructor TgoHttpClient.Destroy;
var
Connection: TgoSocketConnection;
begin
{$IFDEF HTTP2}
nghttp2_session_callbacks_del(FCallbacks_http2);
nghttp2_session_terminate_session(FSession_http2, NGHTTP2_NO_ERROR);
{$ENDIF}
FConnectionLock.Enter;
try
Connection := FConnection;
FConnection := nil;
finally
FConnectionLock.Leave;
end;
if Connection <> nil then
_HttpClientSocketManager.Release(Connection);
FreeAndNil(FRequestHeaders);
FreeAndNil(FInternalHeaders);
FreeAndNil(FResponseHeaders);
FreeAndNil(FCookies);
FreeAndNil(FSentCookies);
FConnected.Free;
FConnectionLock.Free;
FSendBuffer.Free;
FRecvBuffer2.Free;
FRecvBuffer.Free;
FRecv.Free;
inherited Destroy;
end;
{$IFDEF HTTP2}
function TgoHttpClient.nghttp2_data_source_read_callback(session: pnghttp2_session;
stream_id: int32; buf: puint8; len: size_t; data_flags: puint32;
source: pnghttp2_data_source; user_data: Pointer): ssize_t;
begin
// Note: if you want request specific data you can use the API nghttp2_session_get_stream_user_data(session, stream_id);
if NativeUInt(FSendBuffer.Size) <= len then
begin
Result := FSendBuffer.Size;
FSendBuffer.Read(Buf, Result);
data_flags^ := data_flags^ or NGHTTP2_DATA_FLAG_EOF;
end
else
begin
Result := len;
FSendBuffer.Read(Buf, Result);
end;
end;
function TgoHttpClient.nghttp2_on_header_callback(session: pnghttp2_session; const frame: pnghttp2_frame;
const name: puint8; namelen: size_t; const value: puint8; valuelen: size_t;
flags: uint8; user_data: Pointer): Integer;
var
AName, AValue: String;
Index: Integer;
begin
{$IFDEF LOGGING}
//grLog('on_header_callback');
{$ENDIF}
if frame.hd.&type = _NGHTTP2_HEADERS then
if (frame.headers.cat = NGHTTP2_HCAT_RESPONSE) then
begin
AName := TEncoding.ASCII.GetString(BytesOf(name, namelen));
AValue := TEncoding.ASCII.GetString(BytesOf(value, valuelen));
FResponseHeaders.AddOrSet(AName, AValue);
{$IFDEF LOGGING}
//grLog(AName, AValue);
{$ENDIF}
{ response status code }
if AName = ':status' then
FResponseStatusCode := StrToInt64Def(AValue, -1);
{ content type }
if AName = 'content-type' then
begin
FResponseContentType := AValue;
{ charset }
Index := FResponseContentType.IndexOf(S_CHARSET + '=');
if Index >= 0 then
FResponseContentCharset := FResponseContentType.Substring(Index + Length(S_CHARSET) + 1, Length(FResponseContentType) - Index - Length(S_CHARSET)).ToLower;
end;
{ content length }
if AName = 'content-length' then
FContentLength := StrToInt64Def(AValue, -1);
end;
Result := 0;
end;
function TgoHttpClient.nghttp2_on_frame_recv_callback(session: pnghttp2_session;
const frame: pnghttp2_frame; user_data: Pointer): Integer;
begin
{$IFDEF LOGGING}
//grLog('on_frame_recv_callback');
{$ENDIF}
if frame.hd.&type = _NGHTTP2_HEADERS then
if (frame.headers.cat = NGHTTP2_HCAT_RESPONSE) then
begin
// all headers received
{$IFDEF LOGGING}
//grLog('All headers received');
{$ENDIF}
FResponseHeader2 := True;
end;
Result := 0;
end;
function TgoHttpClient.nghttp2_on_data_chunk_recv_callback(session: pnghttp2_session;
flags: uint8; stream_id: int32; const data: puint8; len: size_t;
user_data: Pointer): Integer;
begin
if stream_id = FStreamId2 then
begin
{$IFDEF LOGGING}
//grLog('on_data_chunk_recv_callback ' + stream_id.ToString, data, len);
{$ENDIF}
// response chunk
FRecvBuffer2.Write(data, len);
end;
Result := 0;
end;
function TgoHttpClient.nghttp2_on_stream_close_callback(session: pnghttp2_session;
stream_id: int32; error_code: uint32; user_data: Pointer): Integer;
begin
if stream_id = FStreamId2 then
begin
{$IFDEF LOGGING}
//grLog('on_stream_close_callback ' + stream_id.ToString);
{$ENDIF}
FResponseContent2 := True;
end;
Result := 0;
{ Note : connection is still open at this point unless you call
nghttp2_session_terminate_session(session, NGHTTP2_NO_ERROR) }
end;
function TgoHttpClient.nghttp2_Send: Boolean;
var
data: Pointer;
len: Integer;
Bytes: TBytes;
begin
Result := False;
while nghttp2_session_want_write(FSession_http2) > 0 do
begin
len := nghttp2_session_mem_send(FSession_http2, data);
if len > 0 then
begin
SetLength(Bytes, len);
Move(data^, Bytes[0], len);
Result := FConnection.Send(Bytes);
end;
end;
end;
function TgoHttpClient.nghttp2_Recv: Boolean;
var
Bytes: TBytes;
begin
Result := FRecvBuffer.Read(Bytes);
if Result then
nghttp2_session_mem_recv(FSession_http2, @Bytes[0], Length(Bytes));
end;
{$ENDIF}
function TgoHttpClient.GetIdleTime: Integer;
begin
Result := MillisecondsBetween(Now, FLastRecv);
end;
procedure TgoHttpClient.Close;
begin
FRecvAbort := True;
FRecv.SetEvent;
if FConnection <> nil then
FConnection.Disconnect;
end;
{ Cookies received from the server }
function TgoHttpClient.GetCookies: TStrings;
begin
if FCookies = nil then
FCookies := TStringList.Create;
Result := FCookies;
end;
{ Cookies sent to the server }
procedure TgoHttpClient.SetCookies(const AValue: TStrings);
begin
if GetCookies = AValue then
Exit;
GetCookies.Assign(AValue);
end;
procedure TgoHttpClient.Reset;
begin
FLastRecv := Now;
FInternalHeaders.Headers := nil;
FRequestStatusLine := '';
FResponseStatusCode := 0;
FResponseHeaders.Headers := nil;
FResponseHeader := False;
FChunkSize := -1;
FRecvAbort := False;
FResponse := nil;
FResponseBytes := 0;
FResponseHeaders.Headers := nil;
{$IFDEF HTTP2}
FResponseHeader2 := False;
FResponseContent2 := False;
{$ENDIF}
end;
procedure TgoHttpClient.CreateRequest;
var
_Username: String;
_Password: String;
Cookies: String;
Path: String;
Index: Integer;
begin
{ parse the URL into a URI }
FURI := TURI.Create(FURL);
{ http or https }
if (FURI.Port = 0) then
begin
if FURI.Scheme.ToLower = 'https' then
FURI.Port := DEFAULT_HTTPS_PORT
else
FURI.Port := DEFAULT_HTTP_PORT;
end;
{ use credentials in URI, if provided }
_Username := FURI.Username;
_Password := FURI.Password;
if (_Username = '') then
begin
{ credentials provided? }
_Username := FUserName;
_Password := FPassword;
end;
{$IFDEF HTTP2}
if FHttp2 then
begin
{ add method }
FInternalHeaders.AddOrSet(':method', FMethod.ToUpper);
{ add scheme }
FInternalHeaders.AddOrSet(':scheme', FURI.Scheme.ToLower);
{ add path }
FInternalHeaders.AddOrSet(':path', FURI.Path);
{ add host }
FInternalHeaders.AddOrSet('host', FURI.Host);
{ add authorization }
if (_Username <> '') then
begin
{ basic authentication }
FInternalHeaders.AddOrSet('authorization', 'Basic ' +
TEncoding.Utf8.GetString(goBase64Encode(TEncoding.Utf8.GetBytes(_Username + ':' + _Password))));
end
else
if (FAuthorization <> '') then
FInternalHeaders.AddOrSet('authorization', FAuthorization);
end
else
{$ENDIF}
begin
{ add header status line }
Path := FURI.Path;
if Length(FURI.Params) > 0 then
Path := Path + '?' + FURI.Query;
FRequestStatusLine := FMethod.ToUpper + ' ' + Path + ' ' + 'HTTP/' + FHttpVersion;
{ add host }
FInternalHeaders.AddOrSet('Host', FURI.Host);
{ add user-agent }
if (FUserAgent <> '') then
FInternalHeaders.AddOrSet('User-Agent', FUserAgent);
{ range request }
if (FRange <> '') then
FInternalHeaders.AddOrSet('Range', FRange);
{ add content type }
if (FContentType <> '') then
FInternalHeaders.AddOrSet('Content-Type', FContentType);
{ add content length }
if (FRequestBody <> '') then
FInternalHeaders.AddOrSet('Content-Length', Length(FRequestBody).ToString)
else
if (FRequestData <> nil) then
FInternalHeaders.AddOrSet('Content-Length', Length(FRequestData).ToString)
else
FInternalHeaders.AddOrSet('Content-Length', '0');
{ add authorization }
if (_Username <> '') then
begin
{ add basic authentication }
FInternalHeaders.AddOrSet('Authorization', 'Basic ' +
TEncoding.Utf8.GetString(goBase64Encode(TEncoding.Utf8.GetBytes(_Username + ':' + _Password))));
end
else
if (FAuthorization <> '') then
FInternalHeaders.AddOrSet('Authorization', FAuthorization);
{ add cookies, if any }
if Assigned(FCookies) then
begin
Cookies := '';
for Index := 0 to FCookies.Count-1 do
begin
if Index > 0 then
Cookies := Cookies + '; ';
Cookies := Cookies + FCookies[Index];
end;
FInternalHeaders.AddOrSet('Cookie', Cookies);
end;
FreeAndNil(FSentCookies);
FSentCookies := FCookies;
FCookies := nil;
end;
end;
function TgoHttpClient.SendRequest: Boolean;
var
Headers: String;
{$IFDEF HTTP2}
DataProvider: nghttp2_data_provider;
Data: TBytes;
FHeaders2: TArray<nghttp2_nv>;
{$ENDIF}
begin
{$IFDEF LOGGING}
//grLog('SendRequest Thread', GetCurrentThreadId);
{$ENDIF}
Result := False;
// FConnectionLock.Enter;
try
if (FConnection <> nil) then
begin
{$IFDEF HTTP2}
if FHttp2 then
begin
{ setup data callback }
DataProvider.source.ptr := nil;
DataProvider.read_callback := data_source_read_callback;
{ create nghttp2 compatible headers }
FInternalHeaders.AsNgHttp2Array(FHeaders2);
FRequestHeaders.AsNgHttp2Array(FHeaders2);
{ prepare send buffer for request body }
if (FRequestBody <> '') then
Data := TEncoding.Utf8.GetBytes(FRequestBody)
else
Data := FRequestData;
FSendBuffer.Write(@Data[0], Length(Data));
{ submit request }
FStreamId2 := nghttp2_submit_request(FSession_http2, Nil, @FHeaders2[0], Length(FHeaders2), @DataProvider, Self);
if FStreamId2 >= 0 then
Result := nghttp2_Send;
end
else
{$ENDIF}
begin
Headers :=
FRequestStatusLine + CRLF +
FInternalHeaders.AsString +
FRequestHeaders.AsString + CRLF;
{$IFDEF LOGGING}
//grLog('RequestHeader', TEncoding.ASCII.GetBytes(Headers));
{$ENDIF}
if (FRequestBody <> '') then
Result := FConnection.Send(TEncoding.ASCII.GetBytes(Headers) + TEncoding.Utf8.GetBytes(FRequestBody))
else
Result := FConnection.Send(TEncoding.ASCII.GetBytes(Headers) + FRequestData);
end;
end;
finally
// FConnectionLock.Leave;
end;
end;
function TgoHttpClient.WaitForRecv: Boolean;
begin
{$IFDEF LOGGING}
//grLog('WaitForRecv Thread', GetCurrentThreadId);
{$ENDIF}
Result := False;
FLastRecv := Now;
while ((FRecv.WaitFor(FRecvTimeout) <> wrTimeout) and (not FRecvAbort)) do
if ResponseHeader and ResponseContent then
begin
Result := True;
Break;
end;
{$IFDEF LOGGING}
//grLog('WaitForRecv ', Result);
{$ENDIF}
end;
function TgoHttpClient.DoResponse(var AAgain: Boolean): TBytes;
var
Location: String;
begin
Result := FResponse;
case FResponseStatusCode of
301,
302,
303,
307,
308,
808: { redirect? }
begin
if FFollowRedirects then
begin
Location := FResponseHeaders.Value('Location');
try
if not Assigned(FOnRedirect) then
begin
FURL := Location;
AAgain := True;
end
else
begin
AAgain := True;
FOnRedirect(Self, Location, AAgain);
if AAgain then
FURL := Location;
end;
if (FResponseStatusCode = 303) then
FMethod := 'GET';
finally
FreeAndNil(FCookies);
FCookies := FSentCookies;
FSentCookies := nil;
end;
end;
end;
401: { password required? }
begin
if Assigned(FOnPassword) then
FOnPassword(Self, AAgain);
end;
end;
end;
function TgoHttpClient.DoRequest(const AMethod, AURL: String;
out AResponse: TBytes; const AConnectTimeout, ARecvTimeout: Integer): Boolean;
var
Again: Boolean;
function Connect: Boolean;
begin
{$IFDEF LOGGING}
//grLog('ConnectToUrl', AUrl);
{$ENDIF}
FConnectionLock.Enter;
try
if (FConnection <> nil) and
((FURI.Scheme.ToLower <> FLastURI.Scheme) or
(FURI.Host <> FLastURI.Host ) or
(FURI.Port <> FLastURI.Port)) then
begin
_HttpClientSocketManager.Release(FConnection);
FConnection := nil;
end;
if FConnection = nil then
begin
FConnection := _HttpClientSocketManager.Request(FURI.Host, FURI.Port);
FConnection.OnConnected := OnSocketConnected;
FConnection.OnDisconnected := OnSocketDisconnected;
FConnection.OnSent := OnSocketSent;
FConnection.OnRecv := OnSocketRecv;
if FURI.Scheme.ToLower = 'https' then
begin
FConnection.SSL := True;
{$IFDEF HTTP2}
FConnection.ALPN := FHttp2;
{$ENDIF}
if FCertificate <> nil then
FConnection.Certificate := FCertificate;
if FPrivateKey <> nil then
FConnection.PrivateKey := FPrivateKey;
end
else
FConnection.SSL := False;
end;
Result := FConnection.State = TgoConnectionState.Connected;
if not Result then
begin
{$IFDEF LOGGING}
//grLog('Connecting');
{$ENDIF}
if FConnection.Connect then
Result := FConnected.WaitFor(FConnectTimeout) <> wrTimeout;
{$IFDEF LOGGING}
//grLog('Connected', Result);
{$ENDIF}
end;
finally
FConnectionLock.Leave;
end;
end;
begin
FState := TgoHttpClientState.None;
Result := False;
FURL := AURL;
FMethod := AMethod;
FConnectTimeout := AConnectTimeout;
FRecvTimeout := ARecvTimeout;
repeat
AResponse := nil;
Again := False;
Reset;
CreateRequest;
FState := TgoHttpClientState.Sending;
if Connect then
begin
if SendRequest then
begin
FState := TgoHttpClientState.Receiving;
if FBlocking then
begin
if WaitForRecv then
begin
AResponse := DoResponse(Again);
FState := TgoHttpClientState.Finished;
Result := True;
end;
end
else
Result := True;
end
else
FState := TgoHttpClientState.Error;
FLastURI := FURI;
end
else
FState := TgoHttpClientState.Error;
until not Again;
{$IFDEF LOGGING}
//grLog('ResponseLength', Length(AResponse));
{$ENDIF}
end;
procedure TgoHttpClient.OnSocketConnected;
begin
{$IFDEF LOGGING}
//grLog('OnSocketConnected');
{$ENDIF}
FConnected.SetEvent;
end;
procedure TgoHttpClient.OnSocketDisconnected;
begin
{$IFDEF LOGGING}
//grLog('OnSocketDisconnected');
{$ENDIF}
end;
procedure TgoHttpClient.OnSocketSent(const ABuffer: Pointer;
const ASize: Integer);
begin
FLastSent := Now;
if Assigned(FOnSent) then
FOnSent(Self, ABuffer, ASize);
end;
{ DoRecv is always called with a copy buffer and outside of the main buffer
lock so that we do not block any socket pooling threads with our own
worker logic }
procedure TgoHttpClient.DoRecv(const ABuffer: Pointer; const ASize: Integer);
var
Index: Integer;
CreateResponse: Boolean;
begin
{$IFDEF LOGGING}
//grLog(Format('DoRecv (Size=%d)', [ASize]), ABuffer, ASize);
{$ENDIF}
FResponseBytes := FResponseBytes + ASize;
CreateResponse := True;
if Assigned(FOnRecv) then
FOnRecv(Self, ABuffer, ASize, CreateResponse);
{ append response buffer, optional }
if CreateResponse then
begin
Index := Length(FResponse);
SetLength(FResponse, Length(FResponse) + ASize);
Move(ABuffer^, FResponse[Index], ASize);
end;
end;
function TgoHttpClient.ResponseHeader: Boolean;
var
Bytes: TBytes;
procedure ParseResponseHeader(const ABytes: TBytes);
var
Headers: TStringList;
Strings: TArray<String>;
Index: Integer;
begin
Headers := TStringList.Create;
try
Headers.Text := TEncoding.ASCII.GetString(ABytes, 0, Length(ABytes) - 4); // exclude CRLFCRLF
if Headers.Count > 0 then
begin
{ response status code }
Strings := Headers[0].ToLower.Substring(Headers[0].ToLower.LastIndexOf('http:/')).Split([#32]);
if Length(Strings) >= 2 then
FResponseStatusCode := StrToInt64Def(Strings[1], -1)
else
FResponseStatusCode := -1;
{ response headers }
if Headers.Count > 1 then
for Index := 1 to Headers.Count - 1 do
FResponseHeaders.AddOrSet(Headers[Index]);
{ content type }
FResponseContentType := FResponseHeaders.Value(S_CONTENT_TYPE);
{ charset }
Index := FResponseContentType.IndexOf(S_CHARSET + '=');
if Index >= 0 then
FResponseContentCharset := FResponseContentType.Substring(Index + Length(S_CHARSET) + 1, Length(FResponseContentType) - Index - Length(S_CHARSET)).ToLower;
{ content length or transfer encoding? }
FContentLength := StrToInt64Def(FResponseHeaders.Value(S_CONTENT_LENGTH), -1);
if FContentLength < 0 then
{ chunked encoding }
FTransferEncoding := FResponseHeaders.Value(S_TRANSFER_ENCODING);
end;
finally
Headers.Free;
end;
end;
begin
{$IFDEF HTTP2}
if FHttp2 then
Result := FResponseHeader2
else
{$ENDIF}
begin
Result := FResponseHeader;
if not FResponseHeader then
begin
if FRecvBuffer.ReadTo(CRLF + CRLF, Bytes) then
begin
ParseResponseHeader(Bytes);
FResponseHeader := True;
Result := True;
end;
end;
end;
{$IFDEF LOGGING}
//grLog('ResponseHeader', Result);
{$ENDIF}
end;
function TgoHttpClient.ResponseContent: Boolean;
var
S: RawByteString;
Index: Integer;
Bytes: TBytes;
begin
if FMethod.ToUpper = 'HEAD' then // no content expected
Result := True
else
begin
{$IFDEF HTTP2}
if FHttp2 then
begin
if FRecvBuffer2.Read(Bytes) then
DoRecv(@Bytes[0], Length(Bytes));
Result := FResponseContent2;
end
else
{$ENDIF}
begin
if FContentLength >= 0 then
begin
if FRecvBuffer.Read(Bytes) then
DoRecv(@Bytes[0], Length(Bytes));
Result := FResponseBytes >= FContentLength;
end
else
begin
Result := False;
{ chunked encoding }
if FTransferEncoding = S_CHUNKED then
begin
while True do
begin
{ calculate expected next chunk size, only once }
if FChunkSize = -1 then
if FRecvBuffer.ReadTo(CRLF, Bytes) then
begin
SetLength(S, Length(Bytes) - 2);
Move(Bytes[0], S[1], Length(Bytes) - 2);
Index := String(S).IndexOf(';'); { skip optional chunk parameters }
if Index >= 0 then
SetLength(S, Index);
FChunkSize := StrToInt64Def('$' + String(S), -1);
{$IFDEF LOGGING}
//grLog('ChunkSize', FChunkSize);
{$ENDIF}
end;
if FChunkSize > 0 then
begin
{ did we receive the chunk plus all padding bytes? }
if FRecvBuffer.Size > FChunkSize + 2 then
begin
if FRecvBuffer.Read(Bytes, FChunkSize + 2) then
DoRecv(@Bytes[0], Length(Bytes) - 2);
FChunkSize := -1;
end
else
Break; // need more data
end
else
if FChunkSize = 0 then // completed
begin
FRecvBuffer.Clear; // ignore chunking tail
Result := True;
Break;
end
else
Break; // need more data
end;
end;
end;
end;
end;
{$IFDEF LOGGING}
//grLog('ResponseContent', Result);
{$ENDIF}
end;
{ OnSocketRecv can be called by multiple threads from the socket pool in relation
to the same http request. These threads are always different from the main
thread. This can create issues with FIFO buffer ordering so we write the buffer
into our main buffer in a thread safe manner, and we do it as quickly as possible. }
procedure TgoHttpClient.OnSocketRecv(const ABuffer: Pointer; const ASize: Integer);
var
ResponseMessage: TgoHttpResponseMessage;
begin
{$IFDEF LOGGING}
//grLog(Format('OnSocketRecv (ThreadId=%d, Size=%d)', [GetCurrentThreadId, ASize]), ABuffer, ASize);
{$ENDIF}
FLastRecv := Now;
FRecvBuffer.Write(ABuffer, ASize);
{ http2 receive }
{$IFDEF HTTP2}
if FHttp2 then
nghttp2_Recv;
{$ENDIF}
if FState <> TgoHttpClientState.Finished then
begin
if FBlocking then
FRecv.SetEvent
else
begin
if ResponseHeader and ResponseContent then
begin
ResponseMessage := TgoHttpResponseMessage.Create(
Self,
FResponseHeaders,
FResponseStatusCode,
FResponseContentType,
FResponseContentCharset,
FResponse);
TMessageManager.DefaultManager.SendMessage(Self, ResponseMessage);
FState := TgoHttpClientState.Finished;
end;
end;
end;
end;
function TgoHttpClient.BytesToString(const ABytes: TBytes; const ACharset: String): String;
begin
if ACharset = 'iso-8859-1' then
Result := TEncoding.ANSI.GetString(ABytes)
else
if ACharset = 'utf-8' then
Result := TEncoding.UTF8.GetString(ABytes)
else
Result := TEncoding.ANSI.GetString(ABytes)
end;
function TgoHttpClient.Get(const AURL: String; out AResponse: TBytes;
const AConnectTimeout, ARecvTimeout: Integer): Boolean;
begin
Result := DoRequest('GET', AURL, AResponse, AConnectTimeout, ARecvTimeout);
end;
function TgoHttpClient.Get(const AURL: String; out AResponse: String;
const AConnectTimeout, ARecvTimeout: Integer): Boolean;
var
Response: TBytes;
begin
if Get(AURL, Response, AConnectTimeout, ARecvTimeout) then
begin
AResponse := BytesToString(Response, FResponseContentCharset);
Result := True;
end
else
Result := False;
end;
function TgoHttpClient.Get(const AURL: String; const AConnectTimeout, ARecvTimeout: Integer): String;
var
Response: TBytes;
begin
if Get(AURL, Response, AConnectTimeout, ARecvTimeout) then
Result := BytesToString(Response, FResponseContentCharset);
end;
function TgoHttpClient.Head(const AURL: String; const AConnectTimeout, ARecvTimeout: Integer): Boolean;
var
AResponse: TBytes;
begin
Result := DoRequest('HEAD', AURL, AResponse, AConnectTimeout, ARecvTimeout);
end;
function TgoHttpClient.Post(const AURL: String; out AResponse: TBytes;
const AConnectTimeout, ARecvTimeout: Integer): Boolean;
begin
Result := DoRequest('POST', AURL, AResponse, AConnectTimeout, ARecvTimeout);
end;
function TgoHttpClient.Post(const AURL: String; out AResponse: String;
const AConnectTimeout, ARecvTimeout: Integer): Boolean;
var
Response: TBytes;
begin
if Post(AURL, Response, AConnectTimeout, ARecvTimeout) then
begin
AResponse := BytesToString(Response, FResponseContentCharset);
Result := True;
end
else
Result := False;
end;
function TgoHttpClient.Post(const AURL: String; const AConnectTimeout, ARecvTimeout: Integer): String;
var
Response: TBytes;
begin
if Post(AURL, Response, AConnectTimeout, ARecvTimeout) then
Result := BytesToString(Response, FResponseContentCharset);
end;
function TgoHttpClient.Put(const AURL: String; out AResponse: TBytes;
const AConnectTimeout, ARecvTimeout: Integer): Boolean;
begin
Result := DoRequest('PUT', AURL, AResponse, AConnectTimeout, ARecvTimeout);
end;
function TgoHttpClient.Put(const AURL: String; out AResponse: String;
const AConnectTimeout, ARecvTimeout: Integer): Boolean;
var
Response: TBytes;
begin
if Put(AURL, Response, AConnectTimeout, ARecvTimeout) then
begin
AResponse := BytesToString(Response, FResponseContentCharset);
Result := True;
end
else
Result := False;
end;
function TgoHttpClient.Put(const AURL: String; const AConnectTimeout, ARecvTimeout: Integer): String;
var
Response: TBytes;
begin
if Put(AURL, Response, AConnectTimeout, ARecvTimeout) then
Result := BytesToString(Response, FResponseContentCharset);
end;
function TgoHttpClient.Delete(const AURL: String; out AResponse: TBytes;
const AConnectTimeout, ARecvTimeout: Integer): Boolean;
begin
Result := DoRequest('DELETE', AURL, AResponse, AConnectTimeout, ARecvTimeout);
end;
function TgoHttpClient.Delete(const AURL: String; out AResponse: String;
const AConnectTimeout, ARecvTimeout: Integer): Boolean;
var
Response: TBytes;
begin
if Delete(AURL, Response, AConnectTimeout, ARecvTimeout) then
begin
AResponse := BytesToString(Response, FResponseContentCharset);
Result := True;
end
else
Result := False;
end;
function TgoHttpClient.Delete(const AURL: String; const AConnectTimeout, ARecvTimeout: Integer): String;
var
Response: TBytes;
begin
if Delete(AURL, Response, AConnectTimeout, ARecvTimeout) then
Result := BytesToString(Response, FResponseContentCharset);
end;
function TgoHttpClient.Options(const AURL: String; out AResponse: TBytes;
const AConnectTimeout, ARecvTimeout: Integer): Boolean;
begin
Result := DoRequest('OPTIONS', AURL, AResponse, AConnectTimeout, ARecvTimeout);
end;
function TgoHttpClient.Options(const AURL: String; out AResponse: String;
const AConnectTimeout, ARecvTimeout: Integer): Boolean;
var
Response: TBytes;
begin
if Options(AURL, Response, AConnectTimeout, ARecvTimeout) then
begin
AResponse := BytesToString(Response, FResponseContentCharset);
Result := True;
end
else
Result := False;
end;
function TgoHttpClient.Options(const AURL: String; const AConnectTimeout, ARecvTimeout: Integer): String;
var
Response: TBytes;
begin
if Options(AURL, Response, AConnectTimeout, ARecvTimeout) then
Result := BytesToString(Response, FResponseContentCharset);
end;
initialization
_HttpClientSocketManager := TgoClientSocketManager.Create;
HttpClientManager := TgoHttpClientManager.Create;
finalization
HttpClientManager.Free;
_HttpClientSocketManager.Free;
end.
| 27.95391 | 165 | 0.690139 |
83e7adeb0c1b05a9cefa59271f68ad2fba695876 | 3,549 | dfm | Pascal | forecast.dfm | WangTimo/Power-Load-Forecasting-Software-with-Regression-Analysis- | abdadfa845c4f28c2857d30ba76c7c8d3c3ffe56 | [
"MIT"
]
| null | null | null | forecast.dfm | WangTimo/Power-Load-Forecasting-Software-with-Regression-Analysis- | abdadfa845c4f28c2857d30ba76c7c8d3c3ffe56 | [
"MIT"
]
| null | null | null | forecast.dfm | WangTimo/Power-Load-Forecasting-Software-with-Regression-Analysis- | abdadfa845c4f28c2857d30ba76c7c8d3c3ffe56 | [
"MIT"
]
| null | null | null | object Form4: TForm4
Left = 406
Top = 140
Width = 681
Height = 403
BorderStyle = bsSizeToolWin
Caption = #26681#25454#24180#20221#36827#34892#36127#33655#39044#27979
Color = clSkyBlue
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
OldCreateOrder = False
PixelsPerInch = 96
TextHeight = 13
object Label1: TLabel
Left = 201
Top = 51
Width = 121
Height = 25
AutoSize = False
Caption = #35831#36755#20837#39044#27979#24180#20221#65306
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -13
Font.Name = 'MS Sans Serif'
Font.Style = []
ParentFont = False
end
object Label6: TLabel
Left = 201
Top = 107
Width = 129
Height = 33
AutoSize = False
Caption = #36127#33655#39044#27979#32467#26524#20026#65306
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -13
Font.Name = 'MS Sans Serif'
Font.Style = []
ParentFont = False
end
object Edit1: TEdit
Left = 330
Top = 43
Width = 145
Height = 33
AutoSize = False
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -19
Font.Name = 'MS Sans Serif'
Font.Style = []
ParentFont = False
TabOrder = 0
end
object Button2: TButton
Left = 202
Top = 155
Width = 276
Height = 49
Caption = #24320#22987#39044#27979#20998#26512
TabOrder = 1
OnClick = Button2Click
end
object Button1: TButton
Left = 251
Top = 225
Width = 180
Height = 41
Caption = #36820#22238
Default = True
TabOrder = 2
OnClick = Button1Click
end
object Edit2: TEdit
Left = 330
Top = 99
Width = 145
Height = 33
AutoSize = False
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -19
Font.Name = 'MS Sans Serif'
Font.Style = []
ParentFont = False
ReadOnly = True
TabOrder = 3
end
object DataSource1: TDataSource
DataSet = ADOTable1
Left = 405
Top = 275
end
object ADOConnection1: TADOConnection
Connected = True
ConnectionString =
'Provider=Microsoft.Jet.OLEDB.4.0;User ID=Admin;Data Source=1.mdb' +
';Mode=Share Deny None;Persist Security Info=False;Jet OLEDB:Syst' +
'em database="";Jet OLEDB:Registry Path="";Jet OLEDB:Database Pas' +
'sword="";Jet OLEDB:Engine Type=5;Jet OLEDB:Database Locking Mode' +
'=1;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Global Bulk Tra' +
'nsactions=1;Jet OLEDB:New Database Password="";Jet OLEDB:Create ' +
'System Database=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB' +
':Don'#39't Copy Locale on Compact=False;Jet OLEDB:Compact Without Re' +
'plica Repair=False;Jet OLEDB:SFP=False'
LoginPrompt = False
Mode = cmShareDenyNone
Provider = 'Microsoft.Jet.OLEDB.4.0'
Left = 245
Top = 275
end
object ADOQuery1: TADOQuery
Active = True
Connection = ADOConnection1
CursorType = ctStatic
DataSource = DataSource1
Parameters = <>
SQL.Strings = (
'select '#36127#33655' from '#34920'1')
Left = 325
Top = 275
end
object ADOTable1: TADOTable
Active = True
Connection = ADOConnection1
CursorType = ctStatic
TableName = #34920'1'
Left = 285
Top = 275
end
end
| 26.095588 | 79 | 0.618484 |
f166badcc782d1446df9d9e21e04908ab64cbe7d | 718 | pas | Pascal | delphi/0040.pas | nickelsworth/swag | 7c21c0da2291fc249b9dc5cfe121a7672a4ffc08 | [
"BSD-2-Clause"
]
| 11 | 2015-12-12T05:13:15.000Z | 2020-10-14T13:32:08.000Z | delphi/0040.pas | nickelsworth/swag | 7c21c0da2291fc249b9dc5cfe121a7672a4ffc08 | [
"BSD-2-Clause"
]
| null | null | null | delphi/0040.pas | nickelsworth/swag | 7c21c0da2291fc249b9dc5cfe121a7672a4ffc08 | [
"BSD-2-Clause"
]
| 8 | 2017-05-05T05:24:01.000Z | 2021-07-03T20:30:09.000Z |
The following code demonstrates how to bring up the WinHelp "Search"
dialog for your application's help file. You can use TApplication's
HelpCommand method to send the Help_PartialKey command to the WinHelp
system. The parameter for this command should be a PChar (cast to a
longint to circumvent typechecking) that contains the string on
which you'd like to search. The example below uses an empty string,
which invokes "Search" dialog and leaves the edit control in the
dialog empty.
procedure TForm1.SearchHelp;
var
P: PChar;
begin
Application.HelpFile := 'c:\delphi\bin\delphi.hlp';
P := StrNew('');
Application.HelpCommand(Help_PartialKey, longint(P));
StrDispose(P);
end;
| 31.217391 | 70 | 0.747911 |
f18bce5bc8d131b90c992e8595ae537b2f76e789 | 232 | dpr | Pascal | Examples/VideoZip/demo_VideoZip.dpr | ryujt/ryulib-delphi | a59d308d6535de6a2fdb1ac49ded981849031c60 | [
"MIT"
]
| 12 | 2019-11-09T11:44:47.000Z | 2022-03-01T23:38:30.000Z | Examples/VideoZip/demo_VideoZip.dpr | ryujt/ryulib-delphi | a59d308d6535de6a2fdb1ac49ded981849031c60 | [
"MIT"
]
| 1 | 2019-11-08T08:27:34.000Z | 2019-11-08T08:43:51.000Z | Examples/VideoZip/demo_VideoZip.dpr | ryujt/ryulib-delphi | a59d308d6535de6a2fdb1ac49ded981849031c60 | [
"MIT"
]
| 15 | 2019-10-15T12:34:29.000Z | 2021-02-23T08:25:48.000Z | program demo_VideoZip;
uses
Vcl.Forms,
_fmMain in '_fmMain.pas' {fmMain};
{$R *.res}
begin
Application.Initialize;
Application.MainFormOnTaskbar := True;
Application.CreateForm(TfmMain, fmMain);
Application.Run;
end.
| 15.466667 | 42 | 0.732759 |
f19287f5302bd0bc6aedcca3f8db5f368012af3c | 2,292 | pas | Pascal | streams/0003.pas | nickelsworth/swag | 7c21c0da2291fc249b9dc5cfe121a7672a4ffc08 | [
"BSD-2-Clause"
]
| 11 | 2015-12-12T05:13:15.000Z | 2020-10-14T13:32:08.000Z | streams/0003.pas | nickelsworth/swag | 7c21c0da2291fc249b9dc5cfe121a7672a4ffc08 | [
"BSD-2-Clause"
]
| null | null | null | streams/0003.pas | nickelsworth/swag | 7c21c0da2291fc249b9dc5cfe121a7672a4ffc08 | [
"BSD-2-Clause"
]
| 8 | 2017-05-05T05:24:01.000Z | 2021-07-03T20:30:09.000Z | {
There's a bug in TEMSStream.Done. It leaves EMSCurHandle and EMSCurPage with
the last used values, even though it's releasing an EMS handle, which may
well be EMSCurHandle. This means that if you allocate a second EMSStream
after disposing of the first one, it can happen that it sees the page frame
as already valid, when in fact it should load it.
A workaround is to set EMSCurHandle := $FFFF after calling TEMSStream.Done.
Here's some sample code to demonstrate the bug. It was posted to Usenet's
comp.lang.pascal:
From: paf@fbit.msk.su (Alexander Petrosyan)
Subject: TEMSStream trouble (Bug?)
Date: Mon, 26 Sep 94 16:24:34 +0400
Try to compile and run this prog:
}
uses
Objects,
wincrt;
var
ES: TEMSStream;
A, B: array [0..$400-1] of Byte;
I, J: Integer;
procedure Error;
begin
WriteLn ('Error !');
ES.Done;
Halt (1);
end;
begin
FillChar (A, $400, 1);
ES.Init (18 * $400, 18 * $400); { Allocate 18K EMS }
for I := 1 to 18 do ES.Write (A, $400); { Fill with 1 }
ES.Seek (0);
for I := 1 to 10{*} do begin { Read 10K of 18K }
ES.Read (B, $400);
for J := Low (B) to High (B) do if B[J] <> 1 then { Verify }
Error;
end;
ES.Done; { Free allocated EMS }
{ Above code causes problem to below code }
(* emscurhandle := $ffff; *) { Uncomment this line to fix the bug }
FillChar (A, $400, 2);
ES.Init (79 * $400, 79 * $400); { Allocate 79K EMS }
for I := 1 to 79 do ES.Write (A, $400); { Fill with 2 }
ES.Seek (0);
for I := 1 to 79 do begin { Verify ALL }
ES.Read (B, $400);
for J := Low (B) to High (B) do if B[J] <> 2 then
Error; { I'm getting error at this point. Why? }
end;
ES.Done;
writeln('Done');
{
It seems that 1st page of this stream when being read are mapped not to the
right place but to some page of previous stream.
}
end.
(*
It seems to me that error occurs when stream position at dispose time not in
last 16K EMS page (stream must be readed before dispose).
In this example we are writing 18K but reading 10K leaving stream position
not in last page. When I change 10 to 18 at {*} all goes OK.
*)
| 30.157895 | 78 | 0.609075 |
47b5594fd25b1dad8aa2aef40e3fc4d47b7491c3 | 153 | pas | Pascal | CAT/tests/00. general/compiler options/pkg_opt_1.pas | SkliarOleksandr/NextPascal | 4dc26abba6613f64c0e6b5864b3348711eb9617a | [
"Apache-2.0"
]
| 19 | 2018-10-22T23:45:31.000Z | 2021-05-16T00:06:49.000Z | CAT/tests/00. general/compiler options/pkg_opt_1.pas | SkliarOleksandr/NextPascal | 4dc26abba6613f64c0e6b5864b3348711eb9617a | [
"Apache-2.0"
]
| 1 | 2019-06-01T06:17:08.000Z | 2019-12-28T10:27:42.000Z | CAT/tests/00. general/compiler options/pkg_opt_1.pas | SkliarOleksandr/NextPascal | 4dc26abba6613f64c0e6b5864b3348711eb9617a | [
"Apache-2.0"
]
| 6 | 2018-08-30T05:16:21.000Z | 2021-05-12T20:25:43.000Z | unit pkg_opt_1;
#set VariantExplicitConvert=False;
interface
implementation
procedure Test;
begin
end;
initialization
Test();
finalization
end. | 8.052632 | 34 | 0.784314 |
83bbf9e6e3ff2852a1c5605ad5e2fdefe0282d23 | 2,652 | pas | Pascal | src/gui-experimental/wizards/operations/UWIZChangeKey_EnterKey.pas | O1OOO111/PascalCoin | a1725b674c45ebf380c2fb132454439e58f7119a | [
"MIT"
]
| 1 | 2021-06-07T13:20:04.000Z | 2021-06-07T13:20:04.000Z | src/gui-experimental/wizards/operations/UWIZChangeKey_EnterKey.pas | O1OOO111/PascalCoin | a1725b674c45ebf380c2fb132454439e58f7119a | [
"MIT"
]
| null | null | null | src/gui-experimental/wizards/operations/UWIZChangeKey_EnterKey.pas | O1OOO111/PascalCoin | a1725b674c45ebf380c2fb132454439e58f7119a | [
"MIT"
]
| 1 | 2021-06-02T23:57:38.000Z | 2021-06-02T23:57:38.000Z | unit UWIZChangeKey_EnterKey;
{ Copyright (c) 2018 by Sphere 10 Software <http://www.sphere10.com/>
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 the PascalCoin Project, an infinitely scalable
cryptocurrency. Find us here:
Web: https://www.pascalcoin.org
Source: https://github.com/PascalCoin/PascalCoin
Acknowledgements:
- Ugochukwu Mmaduekwe - main developer
- Herman Schoenfeld - designer
THIS LICENSE HEADER MUST NOT BE REMOVED.
}
{$mode delphi}
{$modeswitch nestedprocvars}
interface
uses
SysUtils, StdCtrls, UWizard, UWIZOperation;
type
{ TWIZChangeKey_EnterKey }
TWIZChangeKey_EnterKey = class(TWizardForm<TWIZOperationsModel>)
chkChooseFee: TCheckBox;
chkAttachPayload: TCheckBox;
gbNewPublicKey: TGroupBox;
lblPublicKeyNotice: TLabel;
mmoNewPrivateKey: TMemo;
public
procedure OnPresent; override;
procedure OnNext; override;
function Validate(out message: ansistring): boolean; override;
end;
implementation
{$R *.lfm}
uses
UAccounts,
USettings,
UCoreObjects,
UWIZOperationFee_Custom,
UWIZOperationSigner_Select,
UWIZOperationPayload_Encryption;
{ TWIZChangeKey_EnterKey }
procedure TWIZChangeKey_EnterKey.OnPresent;
begin
if Model.Account.Count > 1 then
begin
chkChooseFee.Checked := True;
chkChooseFee.Enabled := False;
end;
mmoNewPrivateKey.Clear;
mmoNewPrivateKey.SetFocus;
end;
procedure TWIZChangeKey_EnterKey.OnNext;
begin
Model.Payload.HasPayload := chkAttachPayload.Checked;
if chkChooseFee.Checked then
UpdatePath(ptInject, [TWIZOperationFee_Custom])
else
begin
Model.Fee.SingleOperationFee := TSettings.DefaultFee;
if Model.Payload.HasPayload then
UpdatePath(ptInject, [TWIZOperationPayload_Encryption])
else
begin
UpdatePath(ptInject, [TWIZOperationSigner_Select]);
end;
end;
end;
function TWIZChangeKey_EnterKey.Validate(out message: ansistring): boolean;
var
LTempAccountKey: TAccountKey;
LIdx: integer;
begin
Result := True;
if not TAccountComp.AccountKeyFromImport(Trim(mmoNewPrivateKey.Lines.Text),
LTempAccountKey, message) then
begin
Exit(False);
end;
for LIdx := Low(Model.Account.SelectedAccounts) to High(Model.Account.SelectedAccounts) do
if TAccountComp.EqualAccountKeys(Model.Account.SelectedAccounts[LIdx].accountInfo.accountKey,
LTempAccountKey) then
begin
message := 'New Key Is Same As Current Key';
Exit(False);
end;
Model.TransferAccount.AccountKey := LTempAccountKey;
end;
end.
| 23.263158 | 97 | 0.755656 |
f17b3d5145210cef7ee61492a1d1b79daf7dfc8b | 660 | pas | Pascal | Source/VCL/ExtCtrls.Windows.pas | atkins126/DelphiRTL | f0ea29598025346577870cc9a27338592c4dac1b | [
"BSD-2-Clause"
]
| 40 | 2016-09-28T21:34:23.000Z | 2021-12-25T23:02:09.000Z | Source/VCL/ExtCtrls.Windows.pas | atkins126/DelphiRTL | f0ea29598025346577870cc9a27338592c4dac1b | [
"BSD-2-Clause"
]
| 11 | 2017-08-30T13:03:00.000Z | 2020-08-25T13:46:05.000Z | Source/VCL/ExtCtrls.Windows.pas | atkins126/DelphiRTL | f0ea29598025346577870cc9a27338592c4dac1b | [
"BSD-2-Clause"
]
| 15 | 2016-11-24T05:52:39.000Z | 2021-11-11T00:50:12.000Z | namespace RemObjects.Elements.RTL.Delphi.VCL;
{$IF ISLAND AND WINDOWS}
interface
uses
RemObjects.Elements.RTL.Delphi;
type
TPanel = public partial class(TCustomControl)
protected
method CreateParams(var aParams: TCreateParams); override;
end;
implementation
method TPanel.CreateParams(var aParams: TCreateParams);
begin
inherited(var aParams);
//aParams.Style := aParams.Style
aParams.WidgetClassName := PlatformString('WindowClassPanel').ToCharArray(true);
aParams.DefaultWndProc := true;
CreateClass(var aParams);
aParams.DefaultWndProc := true;
aParams.WindowClass.lpfnWndProc := @DefaultControlWndProc;
end;
{$ENDIF}
end. | 21.290323 | 82 | 0.769697 |
474480b84486a3a706091a1ec147095a844e861a | 17,601 | dfm | Pascal | AutoRun_USB_Agent/main.dfm | delphi-pascal-archive/autorun-usb-agent | b61499901a13a2c74cbe1a0b459d18d42dadf204 | [
"Unlicense"
]
| null | null | null | AutoRun_USB_Agent/main.dfm | delphi-pascal-archive/autorun-usb-agent | b61499901a13a2c74cbe1a0b459d18d42dadf204 | [
"Unlicense"
]
| null | null | null | AutoRun_USB_Agent/main.dfm | delphi-pascal-archive/autorun-usb-agent | b61499901a13a2c74cbe1a0b459d18d42dadf204 | [
"Unlicense"
]
| 1 | 2022-01-05T05:10:28.000Z | 2022-01-05T05:10:28.000Z | object MainForm: TMainForm
Left = 230
Top = 130
BorderIcons = []
BorderStyle = bsSingle
Caption = 'No AutoRun_USB Agent'
ClientHeight = 169
ClientWidth = 514
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -14
Font.Name = 'MS Sans Serif'
Font.Style = []
OldCreateOrder = False
Position = poOwnerFormCenter
OnActivate = FormActivate
OnCreate = FormCreate
OnDestroy = FormDestroy
OnHide = FormHide
PixelsPerInch = 120
TextHeight = 16
object box_config: TGroupBox
Left = 8
Top = 8
Width = 497
Height = 121
Caption = ' '#1053#1072#1089#1090#1088#1086#1081#1082#1072' '
TabOrder = 0
object Label1: TLabel
Left = 16
Top = 96
Width = 470
Height = 16
Caption =
#1042#1085#1080#1084#1072#1085#1080#1077': '#1087#1088#1080' '#1080#1079#1084#1077#1085#1077#1085#1080#1080' '#1076#1072#1085#1085#1086#1081' '#1086#1087#1094#1080#1080', '#1085#1091#1078#1085#1072' '#1087#1077#1088#1077#1079#1072#1075#1088#1091#1079#1082#1072' '#1089#1080#1089#1090#1077#1084#1099 +
'!'
Font.Charset = DEFAULT_CHARSET
Font.Color = clRed
Font.Height = -15
Font.Name = 'MS Sans Serif'
Font.Style = []
ParentFont = False
end
object box_autorun: TCheckBox
Left = 16
Top = 24
Width = 177
Height = 17
Caption = #1040#1074#1090#1086#1079#1072#1087#1091#1089#1082' '#1089' '#1089#1080#1089#1090#1077#1084#1086#1081
TabOrder = 0
OnClick = box_autorunClick
end
object box_view_event: TCheckBox
Left = 16
Top = 48
Width = 161
Height = 17
Caption = #1057#1086#1086#1073#1097#1072#1090#1100' '#1086' '#1089#1086#1073#1099#1090#1080#1103#1093
TabOrder = 1
end
object box_off_autorun_drives: TCheckBox
Left = 16
Top = 72
Width = 361
Height = 17
Caption = #1054#1090#1082#1083#1102#1095#1077#1085#1080#1077' '#1072#1074#1090#1086#1079#1072#1087#1091#1089#1082#1072' '#1076#1083#1103' '#1074#1089#1077#1093' '#1076#1080#1089#1082#1086#1074' '#1089#1080#1089#1090#1077#1084#1099
TabOrder = 2
OnClick = box_off_autorun_drivesClick
end
end
object bt_close: TButton
Left = 312
Top = 136
Width = 89
Height = 25
Caption = #1054#1090#1084#1077#1085#1072
TabOrder = 1
OnClick = bt_closeClick
end
object bt_OK: TButton
Left = 408
Top = 136
Width = 97
Height = 25
Caption = #1054'K'
TabOrder = 2
OnClick = bt_OKClick
end
object XPManifest: TXPManifest
Left = 288
Top = 32
end
object MainPopupMenu: TPopupMenu
Images = sImage
Left = 320
Top = 32
object bt_about: TMenuItem
Caption = #1054' '#1055#1088#1086#1075#1088#1072#1084#1084#1077' ...'
ImageIndex = 2
OnClick = bt_aboutClick
end
object bt_line_1: TMenuItem
Caption = '-'
end
object bt_config: TMenuItem
Caption = #1053#1072#1089#1090#1088#1086#1081#1082#1080
ImageIndex = 1
OnClick = bt_configClick
end
object bt_line_2: TMenuItem
Caption = '-'
end
object bt_exit: TMenuItem
Caption = #1042#1099#1093#1086#1076
ImageIndex = 0
OnClick = bt_exitClick
end
end
object sTimer: TTimer
Interval = 5000
OnTimer = sTimerTimer
Left = 352
Top = 32
end
object ida: TIdAntiFreeze
Left = 256
Top = 32
end
object sImage: TImageList
Height = 19
Width = 19
Left = 224
Top = 32
Bitmap = {
494C010103000400040013001300FFFFFFFFFF10FFFFFFFFFFFFFFFF424D3600
00000000000036000000280000004C0000001300000001002000000000009016
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000FEFEFE00DCDCDC00DADADA00909090007777770083838300D5D5D500DBDB
DB00DBDBDB00DBDBDB00DBDBDB00DBDBDB009F9F9F008181810084848400ADAD
AD00000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000627AC000F30B5001333B4001938B8001B3AB8001A3AB7001939
B9001739B9001337BC001237BD000D34C0000A31BE00082FBD00032CBF000029
BB000026B600001D940000000000F0F0F000EBA99000C7A69800AAAEB000E6E6
E600E7E7E700E4E4E40078747300F5C7B200F1C5B000F1C5B000F1C5B000B9A1
9500C9CACB00EBEBEB00CDCECE00716560008444340000000000000000000000
000000000000000000000000000000000000E5E5E50077777700898989008E8E
8E009191910083807E0000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000001037D4001F45D8002449
D9002C4FDB002F52DC002E51DB002C50DB002951DD002550DF00224FDF001B4B
E1001447E1001044E200093EE1000237DE000032D8000026B70000000000D785
5E00ECBCA500A2A5A700E2E2E20081766E00E7BEA600A5A5A400D8D8D800DBB4
9C00F3C8AE00F3C8AE00F3C8AE0098979800E1E1E100E8E8E800E1E1E1009495
9500EFB39C00EBECEC0000000000000000000000000000000000000000000000
0000B6B6B60084848400838383008282820088888800898989009C9B9C000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000143CDB00254ADF002B4FDF003356E0003658E1003558E1003358
E1002F57E2002A56E4002755E5002051E600184CE600144AE6000B43E600043B
E4000136DE000029BE0000000000D5835D00EEBBA100AFB1B300E2E2E2007162
5700F2C3A6009F9A9500D9D9DA00D2AB9100F4C7AB00F4C7AB00F5C7AB00A9AB
AD00E0E0E000E5E5E500E0E0E000AFB0B100EBB09600EAEAEA00000000000000
000000000000000000000000000000000000A5A09B00E3DCDA00E2DBDA00DFD8
D600DED6D500D8D1D000AEAFB100000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000001C43DF003155E1003759
E2004060E4004263E500889CEF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00809EF3001951EA00114AEA000841E700053BE100022BC10000000000D581
5A00EDB49400AEB0B200DDDDDD00D9D9D900CDCECE00DDDDDD00D5D6D600D1A5
8700F4C19F00F4C19F00F4C19F008F929400CECFCF00DDDDDD00CFD0D0008F92
9400ECA98B00EAEAEA0000000000000000000000000000000000000000000000
0000ACD8E300B7F9FF00C6FAFE00C6FBFE00C5FAFE00B4F9FF0086A7B0000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000254AE0003C5DE3004262E4004A69E500FFFFFF00FFFFFF004567
E6003F66E7003863E7003461E8002B5DEA00FFFFFF00FFFFFF00134CEA000D45
E7000A3FE2000730C20000000000D47E5400EBA88400A8ABAD00D7D7D700DDDD
DD00DDDDDD00DDDDDD00CFCFD000D19D7900F1B88F00F1B88F00F1B88F00F6BA
9000C39E8400D2D2D2007B675900E9A98400E69A7800EAEAEA00000000000000
0000000000000000000000000000C3DBE20076E7F900C7FCFF00C7FCFF00C7FC
FF00C7FCFF00C5FCFF0065E0F500C4AD9A000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000294EE0004160E4004665
E50090A2EF00FFFFFF008FA2EF004769E7004167E7003964E7003562E8002B5C
E9007496F100FFFFFF007B9AF3001046E7000E42E1000A32C20000000000D37B
5200E9A17B00A6AAAC00D5D5D500DBDBDB00DBDBDB00DBDBDB00CCCCCC00CF97
7300F2B38900F2B38900F2B38900F4B48900C29B8100CDCDCD007D675800E6A1
7B00E4947000EAEAEA000000000000000000000000000000000000000000C0DA
E2007DEBFA00BBFBFF00BCFAFF00BCFAFF00BCFAFF00BBFBFF006FE3F700C3AD
9C00000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000003255E2004967E5004E6BE600FFFFFF00516EE6004E6EE7004A6A
E6004367E700FFFFFF003661E7002C5CE8002457E9002054E900FFFFFF00174B
E6001647E1001037C30000000000D1794D00E6966900A1A5A700CFCFCF00D6D6
D600D6D6D600D6D6D600C5C6C600CF8F6400F0A97800F0A97800F0A97800F4AB
7900C4977900C8C8C8007D645400E79A6C00E1885E00EAEAEA00000000000000
0000000000000000000000000000BFD8DE0070EAFA00A3FAFF00A3FAFF00A3FA
FF00A3FAFF00A3FAFF0063E3F700C3A993000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000003D5DE400526EE6005470
E700FFFFFF00536FE700516DE6004969E6004266E600FFFFFF00355EE6002B59
E7002353E6002051E700FFFFFF001D4DE4001D4BE000163BC10000000000D074
4900E48A59009DA1A400CBCBCB00D0D0D000D0D0D000D0D0D000BEBFC000CD87
5800EDA06A00EDA06A00F5A266001D49C000336EE8003972E3003973E9001D51
CE00A0552D00EAEAEA00000000000000000000000000000000000000000058E8
FB0080F6FE0088F9FF0088F9FF0088F9FF0088F9FF0088F9FF0082F6FE006FF2
FE004077E3000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000004161E4005571E7005672E800FFFFFF00536FE700506CE6004968
E5004164E600FFFFFF00345CE5002B57E6002452E6002050E500FFFFFF00204E
E400214DDF00193CC10000000000D1724700E38553009CA0A300C9C9C900D0D0
D000D0D0D000D0D0D000BFC0C000CB825100EE9C6500EE9C6500A87775008AC6
FC0093CFFC0096D1FD0094CFFC008DC9FC002E2A6700EAEAEA00000000000000
00000000000000000000A4CED90071F5FE0077F7FF0078F8FF0078F8FF0078F8
FF0078F8FF0078F8FF0078F7FF0073F5FE003BC2EA0000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000004967E5005C76E8005D77
E800FFFFFF00546FE700516DE6004967E5004162E500FFFFFF00345AE4002B54
E4002550E400224EE400FFFFFF00244EE300264FDE001D3FC00000000000D071
4300E37C4400B0B3B500CACACA00CCCCCC00CCCCCC00CCCCCC00C4C4C4007048
2F00EE955A00ED935900195DE20076C7FE0078C9FF0078C9FF0078C9FF0077C8
FE00387EF100E9E9E900000000000000000000000000000000003CE6FB005DF6
FF005CF5FF005CF5FF005CF5FF005CF5FF005CF5FF005CF5FF005CF5FF005DF6
FF0051F1FE000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000516EE700647EE900637DE800FFFFFF00566FE700526CE6004966
E4004160E400FFFFFF003457E2002C52E200274EE200244DE200FFFFFF002950
E1002B50DD002141BF0000000000D06F410087878600C8C8C800CCCCCC00CCCC
CC00CDCDCD00CDCDCD00CCCCCC00AFB0B1009D5D3300EE9255000D58E4004BB7
FE004CB6FF004BB6FF004CB6FF004BB7FF002576EF00E9E9E900000000000000
000000000000CCCECE003CF1FE003DF4FF0043F4FF003DF4FF0040F4FF0041F5
FF0041F5FF0041F5FF0041F5FF0041F5FF003FF2FE0060C2F900000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000005974E8006F88EB006D86
EA00A8B6F300FFFFFF0096A5F0004D69E5004563E4003C5CE400385AE3003154
E2005371E700FFFFFF00879DEF002D52E1002E52DD002342BF0000000000CE6C
3F00BCBCBC00DCDCDC00E1E1E100E7E7E700E7E7E700E5E5E500DCDCDC00CDCD
CD0077726F00AF673900004FE30023A6FE0022A7FF0022A6FF0022A6FF0022A7
FF000F68ED00E9E9E900000000000000000000000000DCE3E50079F6FE0093F9
FF0092F8FF0092F9FF0096F9FF0025F3FF0028F4FF0028F4FF0028F4FF0028F4
FF0028F2FE0056BFF70000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000005D78E800748CEC00718AEB006780EA00FFFFFF00FFFFFF004F6A
E6004764E4003E5EE4003B5CE3003456E200FFFFFF00FFFFFF002E52E2002F52
E1002E51DE002443BF0000000000BC724F00E1E1E100E8E8E800E8E8E800E6E6
E600E7E7E700E7E7E700E8E8E800E8E8E800A0A4A60096603C00004AE20012A0
FE00129FFF00129FFF00129FFF0012A0FF000663ED00E9E9E900000000000000
000000000000E4E8E9009AF9FE009BFAFF009AFAFF0098FAFF009BFAFF0023F3
FF001CF2FF001DF2FF001DF2FF001DF2FF001DF1FE0046B8F800000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000006881EA00869BEE008398
ED00718AEB00657EE900A6B4F200FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF0091A4F0003A5BE3003759E2003356E1003053DD002140BD0000000000AE7A
6000E9E9E900EBEBEB00E9E9E9008F8B8A00BBA79900BABCBD00EBEBEB00EBEB
EB00C0C1C200938073003F72E10088CFFF0043B4FF000095FF000098FF000099
FF00005EEC00E9E9E9000000000000000000000000000000000066F1FE00AFFB
FF00AEFBFF00ADFBFF00AEFBFF00B2FBFF00A5F9FF0028F3FF0024F3FF0010F2
FF0009ECFE00059AFE0000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000007990EC009BACF10096A8F0008095ED00728BEB006E87EB006881
E900637DE800607AE9005E78E8005A75E8005370E6004F6CE6004766E500395B
E2003154DD001B3BBC0000000000C4846300ECECEC00EEEEEE00EDEDED00AB94
8500FBDDC600B5A69C00EDEDED00EDEDED00A3A5A500C0A796004474E200A9DC
FF00A9DDFF00ACDEFF0099D6FF005FBFFF002E7BF000E9E9E900000000000000
000000000000000000002CB6D400CDFBFF00C6FCFF00C6FCFF00C8FCFF00C7FC
FF00C8FCFF00C4FCFF00C7FCFF00CBFCFF0000CAEF0000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000007B92ED00A0B1F2009AAC
F1008398ED00748DEC00718AEB006B84EA006780E900657FE900637DE9005F79
E9005774E7005370E7004A68E500395BE2003153DD001839BA0000000000DF96
7400EDEDED00EFEFEF00EEEEEE00AD998B00FBDDCB00B6A89E00EEEEEE00EEEE
EE0086827E00ECD1BF004775E200B0DFFF00B0DEFF00B0DEFF00B1DFFF00B4E0
FF007FA9F700E9EAE90000000000000000000000000000000000ABA39900C1FB
FF00D8FCFF00D3FBFF00D5FDFF00D5FDFF00D5FDFF00D1FBFF00D5FCFF00E4FD
FF007ED2F4000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000004766E5007990EC00758DEC00627DE9005C76E8005974E800526E
E700506DE7004E6BE6004C6AE6004664E5004061E4003E5FE4003658E200284C
DF002246D9001030B20000000000C19079009C989600F1F1F100F0F0F000BEA9
9D00F9DECE00BAABA300EFEFEF00D7D8D900F5DACC00F6DCCD005770CC00C0E4
FD00BDE3FE00BDE3FE00BDE3FE00BEE2FD002F4FBF0000000000000000000000
0000000000000000000000000000DADCD5000BC0E500FAFFFE00EEFEFF00ECFE
FF00EDFEFF00F6FFFF0041D5F00073D0F1000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000BD958200B4826A00A9887800DD9B7B00DC9A7A00DF9B7A00AE988E00DE9D
7B00DC9A7A00DC9A7A00DD9A7A008C6882006F659C00746A9E0072699E007666
8C00FCFCFC000000000000000000000000000000000000000000000000000000
000000000000AF998F008CB6B90071C2CC0083B8BF00D8A18600000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000424D3E000000000000003E000000280000004C0000001300000001000100
00000000E40000000000000000000000000000000000000000000000FFFFFF00
FFFFF0000FFFFF80000000008000200007F03F80000000008000200003F01F80
000000008000200003F01F80000000008000200003F01F800000000080002000
03E00F80000000008000200003E00F80000000008000200003E00F8000000000
8000200003E00780000000008000200003C00780000000008000200003C00780
0000000080002000038003800000000080002000038003800000000080002000
03800380000000008000200003C00380000000008000200003C0078000000000
8000200003C00780000000008000200007E00F8000000000FFFFF00007F83F80
0000000000000000000000000000000000000000000000000000}
end
end
| 53.175227 | 309 | 0.829044 |
47a7e0ce85a9c2b91b6cd72aa5943136db9b917b | 9,734 | pas | Pascal | Examples/trunk/dockmanager/package/felasticsite.pas | joecare99/Public | 9eee060fbdd32bab33cf65044602976ac83f4b83 | [
"MIT"
]
| 11 | 2017-06-17T05:13:45.000Z | 2021-07-11T13:18:48.000Z | Examples/trunk/dockmanager/package/felasticsite.pas | joecare99/Public | 9eee060fbdd32bab33cf65044602976ac83f4b83 | [
"MIT"
]
| 2 | 2019-03-05T12:52:40.000Z | 2021-12-03T12:34:26.000Z | Examples/trunk/dockmanager/package/felasticsite.pas | joecare99/Public | 9eee060fbdd32bab33cf65044602976ac83f4b83 | [
"MIT"
]
| 6 | 2017-09-07T09:10:09.000Z | 2022-02-19T20:19:58.000Z | unit fElasticSite;
(* Demonstrate elastic dock sites.
This form has dock sites (panels) on its left, right and bottom.
Empty panels should be invisible, what's a bit tricky. They cannot have
Visible=False, because this would disallow to dock anything into them.
So the width/height of the panels is set to zero instead.
When a first control is docked, the dock site is enlarged.
Fine adjustment can be made with the splitters beneath the controls.
When the last control is undocked, the dock site is shrinked again.
*)
(* Observed problems:
Object Inspector says: the bottom panel's OnGetSiteInfo method is incompatible
with other OnGetSiteInfo methods.
ManualFloat does not properly align the client - should become alClient.
Undocked controls do not restore to their undocked size!
Hack: use ManualDock into created floating host.
Undocking controls from a FloatingDockHostSite will undock the control,
but it will become a child of the same site,
and the entire site is moved.
*)
(* AutoExpand by mouse position
Requires a flag in the DockSite, set on first dock.
Hack: use Site.Tag for AutoExpanded.
*)
{$mode objfpc}{$H+}
{.$DEFINE ExpandFlag} //using AutoExpand property?
{.$DEFINE sb} //have StatusBar?
interface
uses
Classes, SysUtils, FileUtil, LResources, Forms, Controls, Graphics, Dialogs,
ExtCtrls, ComCtrls,
EasyDockSite;
type
TDockingSite = class(TForm)
pnlBottom: TPanel;
pnlLeft: TPanel;
pnlRight: TPanel;
splitBottom: TSplitter;
splitLeft: TSplitter;
splitRight: TSplitter;
StatusBar1: TStatusBar;
procedure pnlLeftDockDrop(Sender: TObject; Source: TDragDockObject;
X, Y: Integer);
procedure pnlLeftDockOver(Sender: TObject; Source: TDragDockObject;
X, Y: Integer; State: TDragState; var Accept: Boolean);
procedure pnlLeftGetSiteInfo(Sender: TObject; DockClient: TControl;
var InfluenceRect: TRect; MousePos: TPoint; var CanDock: Boolean);
procedure pnlLeftUnDock(Sender: TObject; Client: TControl;
NewTarget: TWinControl; var Allow: Boolean);
protected
FAutoExpand: boolean;
function AutoExpanded(Site: TWinControl): boolean;
{$IFDEF ExpandFlag}
published
property AutoExpand: boolean read FAutoExpand write FAutoExpand default True;
{$ELSE}
//become property of the docksite (panel)
{$ENDIF}
end;
//var DockingSite: TDockingSite;
procedure Register;
implementation
{$R felasticsite.lfm}
uses
LCLIntf, LCLProc;
//uses fDockClient; //test only
procedure Register;
begin
RegisterComponents('DoDi', [TDockingSite]);
end;
{ TDockingSite }
function TDockingSite.AutoExpanded(Site: TWinControl): boolean;
begin
Result := Site.Tag <> 0;
end;
procedure TDockingSite.pnlLeftDockDrop(Sender: TObject;
Source: TDragDockObject; X, Y: Integer);
var
w: integer;
r: TRect;
Site: TWinControl absolute Sender;
begin
(* Adjust docksite extent, if required.
H/V depending on align LR/TB.
Take 1/3 of the form's extent for the dock site.
When changed, ensure that the form layout is updated.
*)
if (TWinControl(Source.DragTarget).DockClientCount > 1)
or ((Site.Width > 1) and (Site.Height > 1)) //NoteBook!
then
exit; //no adjustments of the dock site required
//this is the first drop - handle AutoExpand
(* Hack AutoExpand by mouse position:
Set Site.Tag to the FAutoExpand state determined in DockOver.
*)
Site.Tag := ord(FAutoExpand);
with Source do begin
if DragTarget.Align in [alLeft, alRight] then begin
w := self.Width div 3;
if DragTarget.Width < w then begin
//enlarge docksite
DisableAlign; //form(?)
DragTarget.Width := w;
if DragTarget.Align = alRight then begin
if FAutoExpand then begin
r := self.BoundsRect;
inc(r.Right, w);
BoundsRect := r;
end else begin
DragTarget.Left:=DragTarget.Left-w;
splitRight.Left:=splitRight.Left-w;
end;
end else if FAutoExpand then begin
//enlarge left
r := BoundsRect;
dec(r.Left, w);
BoundsRect := r;
end;
EnableAlign;
end;
end else begin //alBottom
w := self.Height div 3;
if DragTarget.Height < w then begin
//enlarge docksite
DisableAlign; //form(?)
DragTarget.Height := w;
if DragTarget.Align = alBottom then begin
if FAutoExpand then begin
//dec(self.Left, w);
r := self.BoundsRect;
inc(r.Bottom, w);
BoundsRect := r;
StatusBar1.Top:=StatusBar1.Top+w;
end else begin
splitBottom.Top:=splitBottom.Top-w;
DragTarget.Top:=DragTarget.Top-w;
end;
end;
EnableAlign;
end;
end;
end;
end;
procedure TDockingSite.pnlLeftDockOver(Sender: TObject;
Source: TDragDockObject; X, Y: Integer; State: TDragState;
var Accept: Boolean);
var
r: TRect;
procedure Adjust(dw, dh: integer);
begin
(* r.TopLeft in screen coords, r.BottomRight is W/H(?)
negative values mean expansion towards screen origin
*)
if dw <> 0 then begin
r.Right := r.Left;
inc(r.Bottom, r.Top);
if dw > 0 then
inc(r.Right, dw)
else
inc(r.Left, dw);
end else begin
r.Bottom := r.Top;
inc(r.Right, r.Left);
if dh > 0 then
inc(r.Bottom, dh)
else
inc(r.Top, dh);
end;
end;
var
Site: TWinControl; // absolute Sender;
dw, dh: integer;
const
d = 10; //shift mousepos with InfluenceRect
begin
(* This handler has to determine the intended DockRect,
and the alignment within this rectangle.
This is impossible when the mouse leaves the InfluenceRect,
i.e. when the site is not yet expanded :-(
For a shrinked site we only can display the intended DockRect,
and signal alClient.
On the first drop, AutoExpand can be determined from the mouse position,
inside or outside the form.
*)
if Source.DragTarget = nil then begin
//DragManager signals deny!
exit;
end;
if State = dsDragMove then begin
TObject(Site) := Source.DragTarget;
if Site.DockClientCount > 0 then
exit; //everything should be okay
//make DockRect reflect the docking area
r := Site.BoundsRect; //XYWH
r.TopLeft := Site.Parent.ClientToScreen(r.TopLeft);
dw := Width div 3; //r.Right := r.Left + dw;
dh := Height div 3; //r.Bottom := r.Top + dh;
//determine inside/outside
{$IFDEF ExpandFlag}
//using AutoExpand flag
case Site.Align of
alLeft: if AutoExpand then Adjust(-dw, 0) else Adjust(dw, 0);
alRight: if AutoExpand then Adjust(dw, 0) else Adjust(-dw, 0);
alBottom: if AutoExpand then Adjust(0, dh) else Adjust(0, -dh);
else exit;
end;
{$ELSE}
//dock inside/outside depending on mouse position
//set temporary FAutoExpand
case Site.Align of
alLeft:
begin
FAutoExpand := Source.DragPos.x + d < r.Left;
if FAutoExpand then Adjust(-dw, 0) else Adjust(dw, 0);
end;
alRight:
begin
FAutoExpand := Source.DragPos.x + d >= r.Left;
if FAutoExpand then Adjust(dw, 0) else Adjust(-dw, 0);
end;
alBottom:
begin
FAutoExpand := Source.DragPos.y + d > r.Top;
if FAutoExpand then Adjust(0, dh) else Adjust(0, -dh);
end
else
exit;
end;
{$ENDIF}
Source.DockRect := r;
Accept := True;
end;
end;
procedure TDockingSite.pnlLeftGetSiteInfo(Sender: TObject;
DockClient: TControl; var InfluenceRect: TRect; MousePos: TPoint;
var CanDock: Boolean);
begin
(* Signal acceptance.
Inflate InfluenceRect, for easier docking into a shrinked site.
*)
CanDock := True;
InflateRect(InfluenceRect, 10, 10);
//OffsetRect(InfluenceRect, 10, 10); //collides with other sites?
end;
procedure TDockingSite.pnlLeftUnDock(Sender: TObject; Client: TControl;
NewTarget: TWinControl; var Allow: Boolean);
var
Site: TWinControl absolute Sender;
wh: integer;
r: TRect;
begin
(* When the last client is undocked, shrink the dock site to zero extent.
Called *before* the dock client is removed.
*)
if Site.DockClientCount <= 1 then begin
//become empty, hide the dock site
DisableAlign;
case Site.Align of
alLeft:
begin
wh := Site.Width;
Site.Width := 0; //behaves as expected
if AutoExpanded(Site) then begin
r := BoundsRect;
inc(r.Left, wh);
BoundsRect := r;
end;
end;
alRight:
begin
wh := Site.Width;
Site.Width := 0;
if AutoExpanded(Site) then begin
r := BoundsRect;
dec(r.Right, wh);
BoundsRect := r;
end else begin
Site.Left:=Site.Left+wh;
splitRight.Left:=splitRight.Left+wh;
end;
end;
alBottom:
begin
wh := Site.Height;
Site.Height := 0;
if AutoExpanded(Site) then begin
r := BoundsRect;
dec(r.Bottom, wh);
BoundsRect := r;
splitBottom.Top:=splitBottom.Top-wh;
{$IFDEF sb}
StatusBar1.Top:=StatusBar1.Top-wh;
{$ELSE}
{$ENDIF}
end else begin
Site.Top:=Site.Top+wh;
splitBottom.Top := Site.Top - splitBottom.Height - 10;
end;
end;
end;
EnableAlign;
end;
end;
end.
| 28.545455 | 82 | 0.627697 |
830db87b77b8853fbefec728f30fd85e21852cec | 1,553 | dpr | Pascal | ScaleMM2/Challenge/MMUsageDll.dpr | thiekus/pascal-launcher | 4ba3b32339ed56851c6d53333c39231aa143af04 | [
"Unlicense"
]
| 2 | 2018-09-16T20:41:07.000Z | 2018-09-17T03:58:08.000Z | ScaleMM2/Challenge/MMUsageDll.dpr | thiekus/pascal-launcher | 4ba3b32339ed56851c6d53333c39231aa143af04 | [
"Unlicense"
]
| null | null | null | ScaleMM2/Challenge/MMUsageDll.dpr | thiekus/pascal-launcher | 4ba3b32339ed56851c6d53333c39231aa143af04 | [
"Unlicense"
]
| 1 | 2020-12-31T16:58:26.000Z | 2020-12-31T16:58:26.000Z | library MMUsageDll;
{$I FASTCODE_MM.INC}
uses
{$IFDEF MM_BUCKETMM}
{Robert Houdart's BucketMM}
BucketMem,
{$ENDIF}
{$IFDEF MM_BUCKETMM_ASM}
{Robert Houdart's BucketMM}
BucketMem_Asm,
{$ENDIF}
{$IFDEF MM_DKCIA32MM}
{Dennis Christensen slowcode entry version 0.16}
DKC_IA32_MM_Unit,
{$ENDIF}
{$IFDEF MM_EWCMM}
{Eric Carman's EWCMM}
EWCMM,
{$ENDIF}
{$IFDEF MM_FASTMM2}
{Pierre le Riche's Fastcode challenge entry v2.05}
FastMM,
{$ENDIF}
{$IFDEF MM_FASTMM3}
{Pierre le Riche's Fastcode challenge entry v3.01}
FastMM3,
{$ENDIF}
{$IFDEF MM_FASTMM4}
{Pierre le Riche's Fastcode challenge entry v4.xx}
FastMM4,
{$ENDIF}
{$IFDEF MM_FASTMM4_16}
{Pierre le Riche's Fastcode challenge entry v4.xx}
FastMM4_16,
{$ENDIF}
{$IFDEF MM_MULTIMM}
{Robert Lee's HPMM}
MultiMM,
{$ENDIF}
{$IFDEF MM_NEXUSMM}
{NexusDB Memory Manager}
nxReplacementMemoryManager,
{$ENDIF}
{$IFDEF MM_PSDMM}
{PSDMemoryManager v1.0}
PSDMemoryManager,
{$ENDIF}
{$IFDEF MM_QMEMORY}
{Andrew Driazgov's QMemory}
QMemory,
{$ENDIF}
{$IFDEF MM_RECYCLERMM}
{Eric Grange's RecyclerMM}
RecyclerMM,
{$ENDIF}
{$IFDEF MM_RTLMM}
{Borland Delphi RTL Memory Manager}
{$ENDIF}
{$IFDEF MM_TOPMM}
{Ivo Top's TopMM}
TopMemory,
{$ENDIF}
{$IFDEF MM_WINMEM}
{Mike Lischke's WinMem (Uses the windows heap)}
WinMem,
{$ENDIF}
MMUseMemory in 'MMUseMemory.pas';
{$R *.RES}
exports UseSomeMemory;
exports LeakSomeMemory;
begin
end.
| 19.658228 | 54 | 0.661945 |
618540c43ce5fbb61aaf011182e6bae5fb2c1cdb | 2,244 | pas | Pascal | src/LibraryEvents.pas | kmzbrnoI/mtb-lib | c172cb694d5d9212cd3bddea3d7ea84461499b8c | [
"Apache-2.0"
]
| 1 | 2018-09-03T01:36:13.000Z | 2018-09-03T01:36:13.000Z | src/LibraryEvents.pas | kmzbrnoI/mtb-lib | c172cb694d5d9212cd3bddea3d7ea84461499b8c | [
"Apache-2.0"
]
| 11 | 2016-05-09T14:12:30.000Z | 2021-05-06T11:50:36.000Z | src/LibraryEvents.pas | kmzbrnoI/mtb-lib | c172cb694d5d9212cd3bddea3d7ea84461499b8c | [
"Apache-2.0"
]
| 1 | 2018-09-03T01:36:14.000Z | 2018-09-03T01:36:14.000Z | ////////////////////////////////////////////////////////////////////////////////
// LibraryEvents.pas
// MTB communication library
// Library event definition
// (c) Jan Horacek (jan.horacek@kmz-brno.cz),
////////////////////////////////////////////////////////////////////////////////
{
LICENSE:
Copyright 2015-2019 Jan Horacek
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.
}
{
DESCRIPTION:
This file defines library callback events. Class TLibEvents holds library
events.
}
unit LibraryEvents;
interface
type
TStdNotifyEvent = procedure (Sender: TObject; data:Pointer); stdcall;
TStdLogEvent = procedure (Sender: TObject; data:Pointer; logLevel:Integer; msg:PChar); stdcall;
TStdErrorEvent = procedure (Sender: TObject; data:Pointer; errValue: word; errAddr: Cardinal; errMsg:PChar); stdcall;
TStdModuleChangeEvent = procedure (Sender: TObject; data:Pointer; module: Cardinal); stdcall;
TMyErrorEvent = record
event: TStdErrorEvent;
data: Pointer;
end;
TMyNotifyEvent = record
event: TStdNotifyEvent;
data: Pointer;
end;
TMyModuleChangeEvent = record
event: TStdModuleChangeEvent;
data:Pointer
end;
TMyLogEvent = record
event: TStdLogEvent;
data: Pointer;
end;
TLibEvents = record
BeforeOpen:TMyNotifyEvent;
AfterOpen:TMyNotifyEvent;
BeforeClose:TMyNotifyEvent;
AfterClose:TMyNotifyEvent;
BeforeStart:TMyNotifyEvent;
AfterStart:TMyNotifyEvent;
BeforeStop:TMyNotifyEvent;
AfterStop:TMyNotifyEvent;
OnScanned:TMyNotifyEvent;
OnError:TMyErrorEvent;
OnLog:TMyLogEvent;
OnInputChanged:TMyModuleChangeEvent;
OnOutputChanged:TMyModuleChangeEvent;
end;
var
LibEvents:TLibEvents;
implementation
end.
| 26.4 | 119 | 0.688948 |
473fc1100f2b2532abd4435036cc42182166f0ea | 45,543 | pas | Pascal | lazarus/lcl/interfaces/gtk3/gtk3bindings/lazgdkpixbuf2.pas | rarnu/golcl-liblcl | 6f238af742857921062365656a1b13b44b2330ce | [
"Apache-2.0"
]
| null | null | null | lazarus/lcl/interfaces/gtk3/gtk3bindings/lazgdkpixbuf2.pas | rarnu/golcl-liblcl | 6f238af742857921062365656a1b13b44b2330ce | [
"Apache-2.0"
]
| null | null | null | lazarus/lcl/interfaces/gtk3/gtk3bindings/lazgdkpixbuf2.pas | rarnu/golcl-liblcl | 6f238af742857921062365656a1b13b44b2330ce | [
"Apache-2.0"
]
| null | null | null | { This is an autogenerated unit using gobject introspection (gir2pascal). Do not Edit. }
unit LazGdkPixbuf2;
{$MODE OBJFPC}{$H+}
{$PACKRECORDS C}
{$MODESWITCH DUPLICATELOCALS+}
{$LINKLIB libgdk_pixbuf-2.0.so.0}
interface
uses
CTypes, LazGModule2, LazGio2, LazGLib2, LazGObject2;
const
GdkPixbuf2_library = 'libgdk_pixbuf-2.0.so.0';
GDK_PIXBUF_FEATURES_H = 1;
GDK_PIXBUF_MAGIC_NUMBER = 1197763408;
GDK_PIXBUF_MAJOR = 2;
GDK_PIXBUF_MICRO = 2;
GDK_PIXBUF_MINOR = 28;
GDK_PIXBUF_VERSION = '2.28.2';
GDK_PIXDATA_HEADER_LENGTH = 24;
type
TGdkColorspace = Integer;
const
{ GdkColorspace }
GDK_COLORSPACE_RGB: TGdkColorspace = 0;
type
TGdkInterpType = Integer;
const
{ GdkInterpType }
GDK_INTERP_NEAREST: TGdkInterpType = 0;
GDK_INTERP_TILES: TGdkInterpType = 1;
GDK_INTERP_BILINEAR: TGdkInterpType = 2;
GDK_INTERP_HYPER: TGdkInterpType = 3;
type
TGdkPixbufRotation = Integer;
const
{ GdkPixbufRotation }
GDK_PIXBUF_ROTATE_NONE: TGdkPixbufRotation = 0;
GDK_PIXBUF_ROTATE_COUNTERCLOCKWISE: TGdkPixbufRotation = 90;
GDK_PIXBUF_ROTATE_UPSIDEDOWN: TGdkPixbufRotation = 180;
GDK_PIXBUF_ROTATE_CLOCKWISE: TGdkPixbufRotation = 270;
type
TGdkPixdataDumpType = Integer;
const
{ GdkPixdataDumpType }
GDK_PIXDATA_DUMP_PIXDATA_STREAM: TGdkPixdataDumpType = 0;
GDK_PIXDATA_DUMP_PIXDATA_STRUCT: TGdkPixdataDumpType = 1;
GDK_PIXDATA_DUMP_MACROS: TGdkPixdataDumpType = 2;
GDK_PIXDATA_DUMP_GTYPES: TGdkPixdataDumpType = 0;
GDK_PIXDATA_DUMP_CTYPES: TGdkPixdataDumpType = 256;
GDK_PIXDATA_DUMP_STATIC: TGdkPixdataDumpType = 512;
GDK_PIXDATA_DUMP_CONST: TGdkPixdataDumpType = 1024;
GDK_PIXDATA_DUMP_RLE_DECODER: TGdkPixdataDumpType = 65536;
type
TGdkPixbufAlphaMode = Integer;
const
{ GdkPixbufAlphaMode }
GDK_PIXBUF_ALPHA_BILEVEL: TGdkPixbufAlphaMode = 0;
GDK_PIXBUF_ALPHA_FULL: TGdkPixbufAlphaMode = 1;
type
TGdkPixbufError = Integer;
const
{ GdkPixbufError }
GDK_PIXBUF_ERROR_CORRUPT_IMAGE: TGdkPixbufError = 0;
GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY: TGdkPixbufError = 1;
GDK_PIXBUF_ERROR_BAD_OPTION: TGdkPixbufError = 2;
GDK_PIXBUF_ERROR_UNKNOWN_TYPE: TGdkPixbufError = 3;
GDK_PIXBUF_ERROR_UNSUPPORTED_OPERATION: TGdkPixbufError = 4;
GDK_PIXBUF_ERROR_FAILED: TGdkPixbufError = 5;
type
TGdkPixdataType = Integer;
const
{ GdkPixdataType }
GDK_PIXDATA_COLOR_TYPE_RGB: TGdkPixdataType = 1;
GDK_PIXDATA_COLOR_TYPE_RGBA: TGdkPixdataType = 2;
GDK_PIXDATA_COLOR_TYPE_MASK: TGdkPixdataType = 255;
GDK_PIXDATA_SAMPLE_WIDTH_8: TGdkPixdataType = 65536;
GDK_PIXDATA_SAMPLE_WIDTH_MASK: TGdkPixdataType = 983040;
GDK_PIXDATA_ENCODING_RAW: TGdkPixdataType = 16777216;
GDK_PIXDATA_ENCODING_RLE: TGdkPixdataType = 33554432;
GDK_PIXDATA_ENCODING_MASK: TGdkPixdataType = 251658240;
type
PPGdkColorspace = ^PGdkColorspace;
PGdkColorspace = ^TGdkColorspace;
PPGdkInterpType = ^PGdkInterpType;
PGdkInterpType = ^TGdkInterpType;
PPGdkPixbuf = ^PGdkPixbuf;
PGdkPixbuf = ^TGdkPixbuf;
PPGdkPixbufDestroyNotify = ^PGdkPixbufDestroyNotify;
PGdkPixbufDestroyNotify = ^TGdkPixbufDestroyNotify;
TGdkPixbufDestroyNotify = procedure(pixels: Pguint8; data: gpointer); cdecl;
PPGdkPixdata = ^PGdkPixdata;
PGdkPixdata = ^TGdkPixdata;
PPGdkPixbufFormat = ^PGdkPixbufFormat;
PGdkPixbufFormat = ^TGdkPixbufFormat;
PPGdkPixbufRotation = ^PGdkPixbufRotation;
PGdkPixbufRotation = ^TGdkPixbufRotation;
PPGdkPixbufSaveFunc = ^PGdkPixbufSaveFunc;
PGdkPixbufSaveFunc = ^TGdkPixbufSaveFunc;
TGdkPixbufSaveFunc = function(buf: Pgchar; count: gsize; error: PPGError; data: gpointer): gboolean; cdecl;
TGdkPixbuf = object(TGObject)
function new(colorspace: TGdkColorspace; has_alpha: gboolean; bits_per_sample: gint; width: gint; height: gint): PGdkPixbuf; cdecl; inline; static;
function new_from_data(data: Pguint8; colorspace: TGdkColorspace; has_alpha: gboolean; bits_per_sample: gint; width: gint; height: gint; rowstride: gint; destroy_fn: TGdkPixbufDestroyNotify; destroy_fn_data: gpointer): PGdkPixbuf; cdecl; inline; static;
function new_from_file(filename: Pgchar; error: PPGError): PGdkPixbuf; cdecl; inline; static;
function new_from_file_at_scale(filename: Pgchar; width: gint; height: gint; preserve_aspect_ratio: gboolean; error: PPGError): PGdkPixbuf; cdecl; inline; static;
function new_from_file_at_size(filename: Pgchar; width: gint; height: gint; error: PPGError): PGdkPixbuf; cdecl; inline; static;
function new_from_inline(data_length: gint; data: Pguint8; copy_pixels: gboolean; error: PPGError): PGdkPixbuf; cdecl; inline; static;
function new_from_resource(resource_path: Pgchar; error: PPGError): PGdkPixbuf; cdecl; inline; static;
function new_from_resource_at_scale(resource_path: Pgchar; width: gint; height: gint; preserve_aspect_ratio: gboolean; error: PPGError): PGdkPixbuf; cdecl; inline; static;
function new_from_stream(stream: PGInputStream; cancellable: PGCancellable; error: PPGError): PGdkPixbuf; cdecl; inline; static;
function new_from_stream_at_scale(stream: PGInputStream; width: gint; height: gint; preserve_aspect_ratio: gboolean; cancellable: PGCancellable; error: PPGError): PGdkPixbuf; cdecl; inline; static;
function new_from_stream_finish(async_result: PGAsyncResult; error: PPGError): PGdkPixbuf; cdecl; inline; static;
function new_from_xpm_data(data: PPgchar): PGdkPixbuf; cdecl; inline; static;
function from_pixdata(pixdata: PGdkPixdata; copy_pixels: gboolean; error: PPGError): PGdkPixbuf; cdecl; inline; static;
function get_file_info(filename: Pgchar; width: Pgint; height: Pgint): PGdkPixbufFormat; cdecl; inline; static;
function get_formats: PGSList; cdecl; inline; static;
function gettext(msgid: Pgchar): Pgchar; cdecl; inline; static;
procedure new_from_stream_async(stream: PGInputStream; cancellable: PGCancellable; callback: TGAsyncReadyCallback; user_data: gpointer); cdecl; inline; static;
procedure new_from_stream_at_scale_async(stream: PGInputStream; width: gint; height: gint; preserve_aspect_ratio: gboolean; cancellable: PGCancellable; callback: TGAsyncReadyCallback; user_data: gpointer); cdecl; inline; static;
function save_to_stream_finish(async_result: PGAsyncResult; error: PPGError): gboolean; cdecl; inline; static;
function add_alpha(substitute_color: gboolean; r: guint8; g: guint8; b: guint8): PGdkPixbuf; cdecl; inline;
function apply_embedded_orientation: PGdkPixbuf; cdecl; inline;
procedure composite(dest: PGdkPixbuf; dest_x: gint; dest_y: gint; dest_width: gint; dest_height: gint; offset_x: gdouble; offset_y: gdouble; scale_x: gdouble; scale_y: gdouble; interp_type: TGdkInterpType; overall_alpha: gint); cdecl; inline;
procedure composite_color(dest: PGdkPixbuf; dest_x: gint; dest_y: gint; dest_width: gint; dest_height: gint; offset_x: gdouble; offset_y: gdouble; scale_x: gdouble; scale_y: gdouble; interp_type: TGdkInterpType; overall_alpha: gint; check_x: gint; check_y: gint; check_size: gint; color1: guint32; color2: guint32); cdecl; inline;
function composite_color_simple(dest_width: gint; dest_height: gint; interp_type: TGdkInterpType; overall_alpha: gint; check_size: gint; color1: guint32; color2: guint32): PGdkPixbuf; cdecl; inline;
function copy: PGdkPixbuf; cdecl; inline;
procedure copy_area(src_x: gint; src_y: gint; width: gint; height: gint; dest_pixbuf: PGdkPixbuf; dest_x: gint; dest_y: gint); cdecl; inline;
procedure fill(pixel: guint32); cdecl; inline;
function flip(horizontal: gboolean): PGdkPixbuf; cdecl; inline;
function get_bits_per_sample: gint; cdecl; inline;
function get_byte_length: gsize; cdecl; inline;
function get_colorspace: TGdkColorspace; cdecl; inline;
function get_has_alpha: gboolean; cdecl; inline;
function get_height: gint; cdecl; inline;
function get_n_channels: gint; cdecl; inline;
function get_option(key: Pgchar): Pgchar; cdecl; inline;
function get_pixels: Pguint8; cdecl; inline;
function get_pixels_with_length(length: Pguint): Pguint8; cdecl; inline;
function get_rowstride: gint; cdecl; inline;
function get_width: gint; cdecl; inline;
function new_subpixbuf(src_x: gint; src_y: gint; width: gint; height: gint): PGdkPixbuf; cdecl; inline;
function rotate_simple(angle: TGdkPixbufRotation): PGdkPixbuf; cdecl; inline;
procedure saturate_and_pixelate(dest: PGdkPixbuf; saturation: gfloat; pixelate: gboolean); cdecl; inline;
//function save(filename: Pgchar; type_: Pgchar; error: PPGError; args: array of const): gboolean; cdecl; inline;
//function save_to_buffer(buffer: PPgchar; buffer_size: Pgsize; type_: Pgchar; error: PPGError; args: array of const): gboolean; cdecl; inline;
function save_to_bufferv(buffer: PPgchar; buffer_size: Pgsize; type_: Pgchar; option_keys: PPgchar; option_values: PPgchar; error: PPGError): gboolean; cdecl; inline;
//function save_to_callback(save_func: TGdkPixbufSaveFunc; user_data: gpointer; type_: Pgchar; error: PPGError; args: array of const): gboolean; cdecl; inline;
function save_to_callbackv(save_func: TGdkPixbufSaveFunc; user_data: gpointer; type_: Pgchar; option_keys: PPgchar; option_values: PPgchar; error: PPGError): gboolean; cdecl; inline;
//function save_to_stream(stream: PGOutputStream; type_: Pgchar; cancellable: PGCancellable; error: PPGError; args: array of const): gboolean; cdecl; inline;
//procedure save_to_stream_async(stream: PGOutputStream; type_: Pgchar; cancellable: PGCancellable; callback: TGAsyncReadyCallback; user_data: gpointer; args: array of const); cdecl; inline;
function savev(filename: Pgchar; type_: Pgchar; option_keys: PPgchar; option_values: PPgchar; error: PPGError): gboolean; cdecl; inline;
procedure scale(dest: PGdkPixbuf; dest_x: gint; dest_y: gint; dest_width: gint; dest_height: gint; offset_x: gdouble; offset_y: gdouble; scale_x: gdouble; scale_y: gdouble; interp_type: TGdkInterpType); cdecl; inline;
function scale_simple(dest_width: gint; dest_height: gint; interp_type: TGdkInterpType): PGdkPixbuf; cdecl; inline;
property bits_per_sample: gint read get_bits_per_sample { property is writeable but setter not declared } ;
property colorspace: TGdkColorspace read get_colorspace { property is writeable but setter not declared } ;
property has_alpha: gboolean read get_has_alpha { property is writeable but setter not declared } ;
property height: gint read get_height { property is writeable but setter not declared } ;
property n_channels: gint read get_n_channels { property is writeable but setter not declared } ;
property pixels: Pguint8 read get_pixels { property is writeable but setter not declared } ;
property rowstride: gint read get_rowstride { property is writeable but setter not declared } ;
property width: gint read get_width { property is writeable but setter not declared } ;
end;
PPGdkPixdataDumpType = ^PGdkPixdataDumpType;
PGdkPixdataDumpType = ^TGdkPixdataDumpType;
TGdkPixdata = object
magic: guint32;
length: gint32;
pixdata_type: guint32;
rowstride: guint32;
width: guint32;
height: guint32;
pixel_data: guint8;
function deserialize(stream_length: guint; stream: Pguint8; error: PPGError): gboolean; cdecl; inline;
function from_pixbuf(pixbuf: PGdkPixbuf; use_rle: gboolean): gpointer; cdecl; inline;
function serialize(stream_length_p: Pguint): Pguint8; cdecl; inline;
function to_csource(name: Pgchar; dump_type: TGdkPixdataDumpType): PGString; cdecl; inline;
end;
TGdkPixbufFormat = object
function copy: PGdkPixbufFormat; cdecl; inline;
procedure free; cdecl; inline;
function get_description: Pgchar; cdecl; inline;
function get_extensions: PPgchar; cdecl; inline;
function get_license: Pgchar; cdecl; inline;
function get_mime_types: PPgchar; cdecl; inline;
function get_name: Pgchar; cdecl; inline;
function is_disabled: gboolean; cdecl; inline;
function is_scalable: gboolean; cdecl; inline;
function is_writable: gboolean; cdecl; inline;
procedure set_disabled(disabled: gboolean); cdecl; inline;
end;
PPGdkPixbufAlphaMode = ^PGdkPixbufAlphaMode;
PGdkPixbufAlphaMode = ^TGdkPixbufAlphaMode;
PPGdkPixbufAnimation = ^PGdkPixbufAnimation;
PGdkPixbufAnimation = ^TGdkPixbufAnimation;
PPGdkPixbufAnimationIter = ^PGdkPixbufAnimationIter;
PGdkPixbufAnimationIter = ^TGdkPixbufAnimationIter;
TGdkPixbufAnimation = object(TGObject)
function new_from_file(filename: Pgchar; error: PPGError): PGdkPixbufAnimation; cdecl; inline; static;
function new_from_resource(resource_path: Pgchar; error: PPGError): PGdkPixbufAnimation; cdecl; inline; static;
function new_from_stream(stream: PGInputStream; cancellable: PGCancellable; error: PPGError): PGdkPixbufAnimation; cdecl; inline; static;
function new_from_stream_finish(async_result: PGAsyncResult; error: PPGError): PGdkPixbufAnimation; cdecl; inline; static;
procedure new_from_stream_async(stream: PGInputStream; cancellable: PGCancellable; callback: TGAsyncReadyCallback; user_data: gpointer); cdecl; inline; static;
function get_height: gint; cdecl; inline;
function get_iter(start_time: PGTimeVal): PGdkPixbufAnimationIter; cdecl; inline;
function get_static_image: PGdkPixbuf; cdecl; inline;
function get_width: gint; cdecl; inline;
function is_static_image: gboolean; cdecl; inline;
end;
TGdkPixbufAnimationIter = object(TGObject)
function advance(current_time: PGTimeVal): gboolean; cdecl; inline;
function get_delay_time: gint; cdecl; inline;
function get_pixbuf: PGdkPixbuf; cdecl; inline;
function on_currently_loading_frame: gboolean; cdecl; inline;
end;
PPGdkPixbufError = ^PGdkPixbufError;
PGdkPixbufError = ^TGdkPixbufError;
PPGdkPixbufLoader = ^PGdkPixbufLoader;
PGdkPixbufLoader = ^TGdkPixbufLoader;
TGdkPixbufLoader = object(TGObject)
priv: gpointer;
function new: PGdkPixbufLoader; cdecl; inline; static;
function new_with_mime_type(mime_type: Pgchar; error: PPGError): PGdkPixbufLoader; cdecl; inline; static;
function new_with_type(image_type: Pgchar; error: PPGError): PGdkPixbufLoader; cdecl; inline; static;
function close(error: PPGError): gboolean; cdecl; inline;
function get_animation: PGdkPixbufAnimation; cdecl; inline;
function get_format: PGdkPixbufFormat; cdecl; inline;
function get_pixbuf: PGdkPixbuf; cdecl; inline;
procedure set_size(width: gint; height: gint); cdecl; inline;
function write(buf: Pguint8; count: gsize; error: PPGError): gboolean; cdecl; inline;
end;
PPGdkPixbufLoaderClass = ^PGdkPixbufLoaderClass;
PGdkPixbufLoaderClass = ^TGdkPixbufLoaderClass;
TGdkPixbufLoaderClass = object
parent_class: TGObjectClass;
size_prepared: procedure(loader: PGdkPixbufLoader; width: gint; height: gint); cdecl;
area_prepared: procedure(loader: PGdkPixbufLoader); cdecl;
area_updated: procedure(loader: PGdkPixbufLoader; x: gint; y: gint; width: gint; height: gint); cdecl;
closed: procedure(loader: PGdkPixbufLoader); cdecl;
end;
PPGdkPixbufSimpleAnim = ^PGdkPixbufSimpleAnim;
PGdkPixbufSimpleAnim = ^TGdkPixbufSimpleAnim;
TGdkPixbufSimpleAnim = object(TGdkPixbufAnimation)
function new(width: gint; height: gint; rate: gfloat): PGdkPixbufSimpleAnim; cdecl; inline; static;
procedure add_frame(pixbuf: PGdkPixbuf); cdecl; inline;
function get_loop: gboolean; cdecl; inline;
procedure set_loop(loop: gboolean); cdecl; inline;
property loop: gboolean read get_loop write set_loop;
end;
PPGdkPixbufSimpleAnimClass = ^PGdkPixbufSimpleAnimClass;
PGdkPixbufSimpleAnimClass = ^TGdkPixbufSimpleAnimClass;
TGdkPixbufSimpleAnimClass = object
end;
PPGdkPixbufSimpleAnimIter = ^PGdkPixbufSimpleAnimIter;
PGdkPixbufSimpleAnimIter = ^TGdkPixbufSimpleAnimIter;
TGdkPixbufSimpleAnimIter = object(TGdkPixbufAnimationIter)
end;
PPGdkPixdataType = ^PGdkPixdataType;
PGdkPixdataType = ^TGdkPixdataType;
function gdk_pixbuf_add_alpha(pixbuf: PGdkPixbuf; substitute_color: gboolean; r: guint8; g: guint8; b: guint8): PGdkPixbuf; cdecl; external;
function gdk_pixbuf_animation_get_height(animation: PGdkPixbufAnimation): gint; cdecl; external;
function gdk_pixbuf_animation_get_iter(animation: PGdkPixbufAnimation; start_time: PGTimeVal): PGdkPixbufAnimationIter; cdecl; external;
function gdk_pixbuf_animation_get_static_image(animation: PGdkPixbufAnimation): PGdkPixbuf; cdecl; external;
function gdk_pixbuf_animation_get_type: TGType; cdecl; external;
function gdk_pixbuf_animation_get_width(animation: PGdkPixbufAnimation): gint; cdecl; external;
function gdk_pixbuf_animation_is_static_image(animation: PGdkPixbufAnimation): gboolean; cdecl; external;
function gdk_pixbuf_animation_iter_advance(iter: PGdkPixbufAnimationIter; current_time: PGTimeVal): gboolean; cdecl; external;
function gdk_pixbuf_animation_iter_get_delay_time(iter: PGdkPixbufAnimationIter): gint; cdecl; external;
function gdk_pixbuf_animation_iter_get_pixbuf(iter: PGdkPixbufAnimationIter): PGdkPixbuf; cdecl; external;
function gdk_pixbuf_animation_iter_get_type: TGType; cdecl; external;
function gdk_pixbuf_animation_iter_on_currently_loading_frame(iter: PGdkPixbufAnimationIter): gboolean; cdecl; external;
function gdk_pixbuf_animation_new_from_file(filename: Pgchar; error: PPGError): PGdkPixbufAnimation; cdecl; external;
function gdk_pixbuf_animation_new_from_resource(resource_path: Pgchar; error: PPGError): PGdkPixbufAnimation; cdecl; external;
function gdk_pixbuf_animation_new_from_stream(stream: PGInputStream; cancellable: PGCancellable; error: PPGError): PGdkPixbufAnimation; cdecl; external;
function gdk_pixbuf_animation_new_from_stream_finish(async_result: PGAsyncResult; error: PPGError): PGdkPixbufAnimation; cdecl; external;
function gdk_pixbuf_apply_embedded_orientation(src: PGdkPixbuf): PGdkPixbuf; cdecl; external;
function gdk_pixbuf_composite_color_simple(src: PGdkPixbuf; dest_width: gint; dest_height: gint; interp_type: TGdkInterpType; overall_alpha: gint; check_size: gint; color1: guint32; color2: guint32): PGdkPixbuf; cdecl; external;
function gdk_pixbuf_copy(pixbuf: PGdkPixbuf): PGdkPixbuf; cdecl; external;
function gdk_pixbuf_error_quark: TGQuark; cdecl; external;
function gdk_pixbuf_flip(src: PGdkPixbuf; horizontal: gboolean): PGdkPixbuf; cdecl; external;
function gdk_pixbuf_format_copy(format: PGdkPixbufFormat): PGdkPixbufFormat; cdecl; external;
function gdk_pixbuf_format_get_description(format: PGdkPixbufFormat): Pgchar; cdecl; external;
function gdk_pixbuf_format_get_extensions(format: PGdkPixbufFormat): PPgchar; cdecl; external;
function gdk_pixbuf_format_get_license(format: PGdkPixbufFormat): Pgchar; cdecl; external;
function gdk_pixbuf_format_get_mime_types(format: PGdkPixbufFormat): PPgchar; cdecl; external;
function gdk_pixbuf_format_get_name(format: PGdkPixbufFormat): Pgchar; cdecl; external;
function gdk_pixbuf_format_get_type: TGType; cdecl; external;
function gdk_pixbuf_format_is_disabled(format: PGdkPixbufFormat): gboolean; cdecl; external;
function gdk_pixbuf_format_is_scalable(format: PGdkPixbufFormat): gboolean; cdecl; external;
function gdk_pixbuf_format_is_writable(format: PGdkPixbufFormat): gboolean; cdecl; external;
function gdk_pixbuf_from_pixdata(pixdata: PGdkPixdata; copy_pixels: gboolean; error: PPGError): PGdkPixbuf; cdecl; external;
function gdk_pixbuf_get_bits_per_sample(pixbuf: PGdkPixbuf): gint; cdecl; external;
function gdk_pixbuf_get_byte_length(pixbuf: PGdkPixbuf): gsize; cdecl; external;
function gdk_pixbuf_get_colorspace(pixbuf: PGdkPixbuf): TGdkColorspace; cdecl; external;
function gdk_pixbuf_get_file_info(filename: Pgchar; width: Pgint; height: Pgint): PGdkPixbufFormat; cdecl; external;
function gdk_pixbuf_get_formats: PGSList; cdecl; external;
function gdk_pixbuf_get_has_alpha(pixbuf: PGdkPixbuf): gboolean; cdecl; external;
function gdk_pixbuf_get_height(pixbuf: PGdkPixbuf): gint; cdecl; external;
function gdk_pixbuf_get_n_channels(pixbuf: PGdkPixbuf): gint; cdecl; external;
function gdk_pixbuf_get_option(pixbuf: PGdkPixbuf; key: Pgchar): Pgchar; cdecl; external;
function gdk_pixbuf_get_pixels(pixbuf: PGdkPixbuf): Pguint8; cdecl; external;
function gdk_pixbuf_get_pixels_with_length(pixbuf: PGdkPixbuf; length: Pguint): Pguint8; cdecl; external;
function gdk_pixbuf_get_rowstride(pixbuf: PGdkPixbuf): gint; cdecl; external;
function gdk_pixbuf_get_type: TGType; cdecl; external;
function gdk_pixbuf_get_width(pixbuf: PGdkPixbuf): gint; cdecl; external;
//does not exist anymore. issue #31677 function gdk_pixbuf_gettext(msgid: Pgchar): Pgchar; cdecl; external;
function gdk_pixbuf_loader_close(loader: PGdkPixbufLoader; error: PPGError): gboolean; cdecl; external;
function gdk_pixbuf_loader_get_animation(loader: PGdkPixbufLoader): PGdkPixbufAnimation; cdecl; external;
function gdk_pixbuf_loader_get_format(loader: PGdkPixbufLoader): PGdkPixbufFormat; cdecl; external;
function gdk_pixbuf_loader_get_pixbuf(loader: PGdkPixbufLoader): PGdkPixbuf; cdecl; external;
function gdk_pixbuf_loader_get_type: TGType; cdecl; external;
function gdk_pixbuf_loader_new: PGdkPixbufLoader; cdecl; external;
function gdk_pixbuf_loader_new_with_mime_type(mime_type: Pgchar; error: PPGError): PGdkPixbufLoader; cdecl; external;
function gdk_pixbuf_loader_new_with_type(image_type: Pgchar; error: PPGError): PGdkPixbufLoader; cdecl; external;
function gdk_pixbuf_loader_write(loader: PGdkPixbufLoader; buf: Pguint8; count: gsize; error: PPGError): gboolean; cdecl; external;
function gdk_pixbuf_new(colorspace: TGdkColorspace; has_alpha: gboolean; bits_per_sample: gint; width: gint; height: gint): PGdkPixbuf; cdecl; external;
function gdk_pixbuf_new_from_data(data: Pguint8; colorspace: TGdkColorspace; has_alpha: gboolean; bits_per_sample: gint; width: gint; height: gint; rowstride: gint; destroy_fn: TGdkPixbufDestroyNotify; destroy_fn_data: gpointer): PGdkPixbuf; cdecl; external;
function gdk_pixbuf_new_from_file(filename: Pgchar; error: PPGError): PGdkPixbuf; cdecl; external;
function gdk_pixbuf_new_from_file_at_scale(filename: Pgchar; width: gint; height: gint; preserve_aspect_ratio: gboolean; error: PPGError): PGdkPixbuf; cdecl; external;
function gdk_pixbuf_new_from_file_at_size(filename: Pgchar; width: gint; height: gint; error: PPGError): PGdkPixbuf; cdecl; external;
function gdk_pixbuf_new_from_inline(data_length: gint; data: Pguint8; copy_pixels: gboolean; error: PPGError): PGdkPixbuf; cdecl; external;
function gdk_pixbuf_new_from_resource(resource_path: Pgchar; error: PPGError): PGdkPixbuf; cdecl; external;
function gdk_pixbuf_new_from_resource_at_scale(resource_path: Pgchar; width: gint; height: gint; preserve_aspect_ratio: gboolean; error: PPGError): PGdkPixbuf; cdecl; external;
function gdk_pixbuf_new_from_stream(stream: PGInputStream; cancellable: PGCancellable; error: PPGError): PGdkPixbuf; cdecl; external;
function gdk_pixbuf_new_from_stream_at_scale(stream: PGInputStream; width: gint; height: gint; preserve_aspect_ratio: gboolean; cancellable: PGCancellable; error: PPGError): PGdkPixbuf; cdecl; external;
function gdk_pixbuf_new_from_stream_finish(async_result: PGAsyncResult; error: PPGError): PGdkPixbuf; cdecl; external;
function gdk_pixbuf_new_from_xpm_data(data: PPgchar): PGdkPixbuf; cdecl; external;
function gdk_pixbuf_new_subpixbuf(src_pixbuf: PGdkPixbuf; src_x: gint; src_y: gint; width: gint; height: gint): PGdkPixbuf; cdecl; external;
function gdk_pixbuf_rotate_simple(src: PGdkPixbuf; angle: TGdkPixbufRotation): PGdkPixbuf; cdecl; external;
function gdk_pixbuf_save(pixbuf: PGdkPixbuf; filename: Pgchar; type_: Pgchar; error: PPGError; args: array of const): gboolean; cdecl; external;
function gdk_pixbuf_save_to_buffer(pixbuf: PGdkPixbuf; buffer: PPgchar; buffer_size: Pgsize; type_: Pgchar; error: PPGError; args: array of const): gboolean; cdecl; external;
function gdk_pixbuf_save_to_bufferv(pixbuf: PGdkPixbuf; buffer: PPgchar; buffer_size: Pgsize; type_: Pgchar; option_keys: PPgchar; option_values: PPgchar; error: PPGError): gboolean; cdecl; external;
function gdk_pixbuf_save_to_callback(pixbuf: PGdkPixbuf; save_func: TGdkPixbufSaveFunc; user_data: gpointer; type_: Pgchar; error: PPGError; args: array of const): gboolean; cdecl; external;
function gdk_pixbuf_save_to_callbackv(pixbuf: PGdkPixbuf; save_func: TGdkPixbufSaveFunc; user_data: gpointer; type_: Pgchar; option_keys: PPgchar; option_values: PPgchar; error: PPGError): gboolean; cdecl; external;
function gdk_pixbuf_save_to_stream(pixbuf: PGdkPixbuf; stream: PGOutputStream; type_: Pgchar; cancellable: PGCancellable; error: PPGError; args: array of const): gboolean; cdecl; external;
function gdk_pixbuf_save_to_stream_finish(async_result: PGAsyncResult; error: PPGError): gboolean; cdecl; external;
function gdk_pixbuf_savev(pixbuf: PGdkPixbuf; filename: Pgchar; type_: Pgchar; option_keys: PPgchar; option_values: PPgchar; error: PPGError): gboolean; cdecl; external;
function gdk_pixbuf_scale_simple(src: PGdkPixbuf; dest_width: gint; dest_height: gint; interp_type: TGdkInterpType): PGdkPixbuf; cdecl; external;
function gdk_pixbuf_simple_anim_get_loop(animation: PGdkPixbufSimpleAnim): gboolean; cdecl; external;
function gdk_pixbuf_simple_anim_get_type: TGType; cdecl; external;
function gdk_pixbuf_simple_anim_iter_get_type: TGType; cdecl; external;
function gdk_pixbuf_simple_anim_new(width: gint; height: gint; rate: gfloat): PGdkPixbufSimpleAnim; cdecl; external;
function gdk_pixdata_deserialize(pixdata: PGdkPixdata; stream_length: guint; stream: Pguint8; error: PPGError): gboolean; cdecl; external;
function gdk_pixdata_from_pixbuf(pixdata: PGdkPixdata; pixbuf: PGdkPixbuf; use_rle: gboolean): gpointer; cdecl; external;
function gdk_pixdata_serialize(pixdata: PGdkPixdata; stream_length_p: Pguint): Pguint8; cdecl; external;
function gdk_pixdata_to_csource(pixdata: PGdkPixdata; name: Pgchar; dump_type: TGdkPixdataDumpType): PGString; cdecl; external;
procedure gdk_pixbuf_animation_new_from_stream_async(stream: PGInputStream; cancellable: PGCancellable; callback: TGAsyncReadyCallback; user_data: gpointer); cdecl; external;
procedure gdk_pixbuf_composite(src: PGdkPixbuf; dest: PGdkPixbuf; dest_x: gint; dest_y: gint; dest_width: gint; dest_height: gint; offset_x: gdouble; offset_y: gdouble; scale_x: gdouble; scale_y: gdouble; interp_type: TGdkInterpType; overall_alpha: gint); cdecl; external;
procedure gdk_pixbuf_composite_color(src: PGdkPixbuf; dest: PGdkPixbuf; dest_x: gint; dest_y: gint; dest_width: gint; dest_height: gint; offset_x: gdouble; offset_y: gdouble; scale_x: gdouble; scale_y: gdouble; interp_type: TGdkInterpType; overall_alpha: gint; check_x: gint; check_y: gint; check_size: gint; color1: guint32; color2: guint32); cdecl; external;
procedure gdk_pixbuf_copy_area(src_pixbuf: PGdkPixbuf; src_x: gint; src_y: gint; width: gint; height: gint; dest_pixbuf: PGdkPixbuf; dest_x: gint; dest_y: gint); cdecl; external;
procedure gdk_pixbuf_fill(pixbuf: PGdkPixbuf; pixel: guint32); cdecl; external;
procedure gdk_pixbuf_format_free(format: PGdkPixbufFormat); cdecl; external;
procedure gdk_pixbuf_format_set_disabled(format: PGdkPixbufFormat; disabled: gboolean); cdecl; external;
procedure gdk_pixbuf_loader_set_size(loader: PGdkPixbufLoader; width: gint; height: gint); cdecl; external;
procedure gdk_pixbuf_new_from_stream_async(stream: PGInputStream; cancellable: PGCancellable; callback: TGAsyncReadyCallback; user_data: gpointer); cdecl; external;
procedure gdk_pixbuf_new_from_stream_at_scale_async(stream: PGInputStream; width: gint; height: gint; preserve_aspect_ratio: gboolean; cancellable: PGCancellable; callback: TGAsyncReadyCallback; user_data: gpointer); cdecl; external;
procedure gdk_pixbuf_saturate_and_pixelate(src: PGdkPixbuf; dest: PGdkPixbuf; saturation: gfloat; pixelate: gboolean); cdecl; external;
procedure gdk_pixbuf_save_to_stream_async(pixbuf: PGdkPixbuf; stream: PGOutputStream; type_: Pgchar; cancellable: PGCancellable; callback: TGAsyncReadyCallback; user_data: gpointer; args: array of const); cdecl; external;
procedure gdk_pixbuf_scale(src: PGdkPixbuf; dest: PGdkPixbuf; dest_x: gint; dest_y: gint; dest_width: gint; dest_height: gint; offset_x: gdouble; offset_y: gdouble; scale_x: gdouble; scale_y: gdouble; interp_type: TGdkInterpType); cdecl; external;
procedure gdk_pixbuf_simple_anim_add_frame(animation: PGdkPixbufSimpleAnim; pixbuf: PGdkPixbuf); cdecl; external;
procedure gdk_pixbuf_simple_anim_set_loop(animation: PGdkPixbufSimpleAnim; loop: gboolean); cdecl; external;
implementation
function TGdkPixbuf.new(colorspace: TGdkColorspace; has_alpha: gboolean; bits_per_sample: gint; width: gint; height: gint): PGdkPixbuf; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_new(colorspace, has_alpha, bits_per_sample, width, height);
end;
function TGdkPixbuf.new_from_data(data: Pguint8; colorspace: TGdkColorspace; has_alpha: gboolean; bits_per_sample: gint; width: gint; height: gint; rowstride: gint; destroy_fn: TGdkPixbufDestroyNotify; destroy_fn_data: gpointer): PGdkPixbuf; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_new_from_data(data, colorspace, has_alpha, bits_per_sample, width, height, rowstride, destroy_fn, destroy_fn_data);
end;
function TGdkPixbuf.new_from_file(filename: Pgchar; error: PPGError): PGdkPixbuf; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_new_from_file(filename, error);
end;
function TGdkPixbuf.new_from_file_at_scale(filename: Pgchar; width: gint; height: gint; preserve_aspect_ratio: gboolean; error: PPGError): PGdkPixbuf; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_new_from_file_at_scale(filename, width, height, preserve_aspect_ratio, error);
end;
function TGdkPixbuf.new_from_file_at_size(filename: Pgchar; width: gint; height: gint; error: PPGError): PGdkPixbuf; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_new_from_file_at_size(filename, width, height, error);
end;
function TGdkPixbuf.new_from_inline(data_length: gint; data: Pguint8; copy_pixels: gboolean; error: PPGError): PGdkPixbuf; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_new_from_inline(data_length, data, copy_pixels, error);
end;
function TGdkPixbuf.new_from_resource(resource_path: Pgchar; error: PPGError): PGdkPixbuf; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_new_from_resource(resource_path, error);
end;
function TGdkPixbuf.new_from_resource_at_scale(resource_path: Pgchar; width: gint; height: gint; preserve_aspect_ratio: gboolean; error: PPGError): PGdkPixbuf; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_new_from_resource_at_scale(resource_path, width, height, preserve_aspect_ratio, error);
end;
function TGdkPixbuf.new_from_stream(stream: PGInputStream; cancellable: PGCancellable; error: PPGError): PGdkPixbuf; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_new_from_stream(stream, cancellable, error);
end;
function TGdkPixbuf.new_from_stream_at_scale(stream: PGInputStream; width: gint; height: gint; preserve_aspect_ratio: gboolean; cancellable: PGCancellable; error: PPGError): PGdkPixbuf; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_new_from_stream_at_scale(stream, width, height, preserve_aspect_ratio, cancellable, error);
end;
function TGdkPixbuf.new_from_stream_finish(async_result: PGAsyncResult; error: PPGError): PGdkPixbuf; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_new_from_stream_finish(async_result, error);
end;
function TGdkPixbuf.new_from_xpm_data(data: PPgchar): PGdkPixbuf; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_new_from_xpm_data(data);
end;
function TGdkPixbuf.from_pixdata(pixdata: PGdkPixdata; copy_pixels: gboolean; error: PPGError): PGdkPixbuf; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_from_pixdata(pixdata, copy_pixels, error);
end;
function TGdkPixbuf.get_file_info(filename: Pgchar; width: Pgint; height: Pgint): PGdkPixbufFormat; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_get_file_info(filename, width, height);
end;
function TGdkPixbuf.get_formats: PGSList; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_get_formats();
end;
function TGdkPixbuf.gettext(msgid: Pgchar): Pgchar; cdecl;
begin
Result := nil; //issue #31677 LazGdkPixbuf2.gdk_pixbuf_gettext(msgid);
end;
procedure TGdkPixbuf.new_from_stream_async(stream: PGInputStream; cancellable: PGCancellable; callback: TGAsyncReadyCallback; user_data: gpointer); cdecl;
begin
LazGdkPixbuf2.gdk_pixbuf_new_from_stream_async(stream, cancellable, callback, user_data);
end;
procedure TGdkPixbuf.new_from_stream_at_scale_async(stream: PGInputStream; width: gint; height: gint; preserve_aspect_ratio: gboolean; cancellable: PGCancellable; callback: TGAsyncReadyCallback; user_data: gpointer); cdecl;
begin
LazGdkPixbuf2.gdk_pixbuf_new_from_stream_at_scale_async(stream, width, height, preserve_aspect_ratio, cancellable, callback, user_data);
end;
function TGdkPixbuf.save_to_stream_finish(async_result: PGAsyncResult; error: PPGError): gboolean; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_save_to_stream_finish(async_result, error);
end;
function TGdkPixbuf.add_alpha(substitute_color: gboolean; r: guint8; g: guint8; b: guint8): PGdkPixbuf; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_add_alpha(@self, substitute_color, r, g, b);
end;
function TGdkPixbuf.apply_embedded_orientation: PGdkPixbuf; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_apply_embedded_orientation(@self);
end;
procedure TGdkPixbuf.composite(dest: PGdkPixbuf; dest_x: gint; dest_y: gint; dest_width: gint; dest_height: gint; offset_x: gdouble; offset_y: gdouble; scale_x: gdouble; scale_y: gdouble; interp_type: TGdkInterpType; overall_alpha: gint); cdecl;
begin
LazGdkPixbuf2.gdk_pixbuf_composite(@self, dest, dest_x, dest_y, dest_width, dest_height, offset_x, offset_y, scale_x, scale_y, interp_type, overall_alpha);
end;
procedure TGdkPixbuf.composite_color(dest: PGdkPixbuf; dest_x: gint; dest_y: gint; dest_width: gint; dest_height: gint; offset_x: gdouble; offset_y: gdouble; scale_x: gdouble; scale_y: gdouble; interp_type: TGdkInterpType; overall_alpha: gint; check_x: gint; check_y: gint; check_size: gint; color1: guint32; color2: guint32); cdecl;
begin
LazGdkPixbuf2.gdk_pixbuf_composite_color(@self, dest, dest_x, dest_y, dest_width, dest_height, offset_x, offset_y, scale_x, scale_y, interp_type, overall_alpha, check_x, check_y, check_size, color1, color2);
end;
function TGdkPixbuf.composite_color_simple(dest_width: gint; dest_height: gint; interp_type: TGdkInterpType; overall_alpha: gint; check_size: gint; color1: guint32; color2: guint32): PGdkPixbuf; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_composite_color_simple(@self, dest_width, dest_height, interp_type, overall_alpha, check_size, color1, color2);
end;
function TGdkPixbuf.copy: PGdkPixbuf; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_copy(@self);
end;
procedure TGdkPixbuf.copy_area(src_x: gint; src_y: gint; width: gint; height: gint; dest_pixbuf: PGdkPixbuf; dest_x: gint; dest_y: gint); cdecl;
begin
LazGdkPixbuf2.gdk_pixbuf_copy_area(@self, src_x, src_y, width, height, dest_pixbuf, dest_x, dest_y);
end;
procedure TGdkPixbuf.fill(pixel: guint32); cdecl;
begin
LazGdkPixbuf2.gdk_pixbuf_fill(@self, pixel);
end;
function TGdkPixbuf.flip(horizontal: gboolean): PGdkPixbuf; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_flip(@self, horizontal);
end;
function TGdkPixbuf.get_bits_per_sample: gint; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_get_bits_per_sample(@self);
end;
function TGdkPixbuf.get_byte_length: gsize; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_get_byte_length(@self);
end;
function TGdkPixbuf.get_colorspace: TGdkColorspace; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_get_colorspace(@self);
end;
function TGdkPixbuf.get_has_alpha: gboolean; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_get_has_alpha(@self);
end;
function TGdkPixbuf.get_height: gint; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_get_height(@self);
end;
function TGdkPixbuf.get_n_channels: gint; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_get_n_channels(@self);
end;
function TGdkPixbuf.get_option(key: Pgchar): Pgchar; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_get_option(@self, key);
end;
function TGdkPixbuf.get_pixels: Pguint8; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_get_pixels(@self);
end;
function TGdkPixbuf.get_pixels_with_length(length: Pguint): Pguint8; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_get_pixels_with_length(@self, length);
end;
function TGdkPixbuf.get_rowstride: gint; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_get_rowstride(@self);
end;
function TGdkPixbuf.get_width: gint; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_get_width(@self);
end;
function TGdkPixbuf.new_subpixbuf(src_x: gint; src_y: gint; width: gint; height: gint): PGdkPixbuf; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_new_subpixbuf(@self, src_x, src_y, width, height);
end;
function TGdkPixbuf.rotate_simple(angle: TGdkPixbufRotation): PGdkPixbuf; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_rotate_simple(@self, angle);
end;
procedure TGdkPixbuf.saturate_and_pixelate(dest: PGdkPixbuf; saturation: gfloat; pixelate: gboolean); cdecl;
begin
LazGdkPixbuf2.gdk_pixbuf_saturate_and_pixelate(@self, dest, saturation, pixelate);
end;
function TGdkPixbuf.save_to_bufferv(buffer: PPgchar; buffer_size: Pgsize; type_: Pgchar; option_keys: PPgchar; option_values: PPgchar; error: PPGError): gboolean; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_save_to_bufferv(@self, buffer, buffer_size, type_, option_keys, option_values, error);
end;
function TGdkPixbuf.save_to_callbackv(save_func: TGdkPixbufSaveFunc; user_data: gpointer; type_: Pgchar; option_keys: PPgchar; option_values: PPgchar; error: PPGError): gboolean; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_save_to_callbackv(@self, save_func, user_data, type_, option_keys, option_values, error);
end;
function TGdkPixbuf.savev(filename: Pgchar; type_: Pgchar; option_keys: PPgchar; option_values: PPgchar; error: PPGError): gboolean; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_savev(@self, filename, type_, option_keys, option_values, error);
end;
procedure TGdkPixbuf.scale(dest: PGdkPixbuf; dest_x: gint; dest_y: gint; dest_width: gint; dest_height: gint; offset_x: gdouble; offset_y: gdouble; scale_x: gdouble; scale_y: gdouble; interp_type: TGdkInterpType); cdecl;
begin
LazGdkPixbuf2.gdk_pixbuf_scale(@self, dest, dest_x, dest_y, dest_width, dest_height, offset_x, offset_y, scale_x, scale_y, interp_type);
end;
function TGdkPixbuf.scale_simple(dest_width: gint; dest_height: gint; interp_type: TGdkInterpType): PGdkPixbuf; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_scale_simple(@self, dest_width, dest_height, interp_type);
end;
function TGdkPixdata.deserialize(stream_length: guint; stream: Pguint8; error: PPGError): gboolean; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixdata_deserialize(@self, stream_length, stream, error);
end;
function TGdkPixdata.from_pixbuf(pixbuf: PGdkPixbuf; use_rle: gboolean): gpointer; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixdata_from_pixbuf(@self, pixbuf, use_rle);
end;
function TGdkPixdata.serialize(stream_length_p: Pguint): Pguint8; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixdata_serialize(@self, stream_length_p);
end;
function TGdkPixdata.to_csource(name: Pgchar; dump_type: TGdkPixdataDumpType): PGString; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixdata_to_csource(@self, name, dump_type);
end;
function TGdkPixbufFormat.copy: PGdkPixbufFormat; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_format_copy(@self);
end;
procedure TGdkPixbufFormat.free; cdecl;
begin
LazGdkPixbuf2.gdk_pixbuf_format_free(@self);
end;
function TGdkPixbufFormat.get_description: Pgchar; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_format_get_description(@self);
end;
function TGdkPixbufFormat.get_extensions: PPgchar; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_format_get_extensions(@self);
end;
function TGdkPixbufFormat.get_license: Pgchar; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_format_get_license(@self);
end;
function TGdkPixbufFormat.get_mime_types: PPgchar; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_format_get_mime_types(@self);
end;
function TGdkPixbufFormat.get_name: Pgchar; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_format_get_name(@self);
end;
function TGdkPixbufFormat.is_disabled: gboolean; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_format_is_disabled(@self);
end;
function TGdkPixbufFormat.is_scalable: gboolean; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_format_is_scalable(@self);
end;
function TGdkPixbufFormat.is_writable: gboolean; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_format_is_writable(@self);
end;
procedure TGdkPixbufFormat.set_disabled(disabled: gboolean); cdecl;
begin
LazGdkPixbuf2.gdk_pixbuf_format_set_disabled(@self, disabled);
end;
function TGdkPixbufAnimation.new_from_file(filename: Pgchar; error: PPGError): PGdkPixbufAnimation; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_animation_new_from_file(filename, error);
end;
function TGdkPixbufAnimation.new_from_resource(resource_path: Pgchar; error: PPGError): PGdkPixbufAnimation; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_animation_new_from_resource(resource_path, error);
end;
function TGdkPixbufAnimation.new_from_stream(stream: PGInputStream; cancellable: PGCancellable; error: PPGError): PGdkPixbufAnimation; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_animation_new_from_stream(stream, cancellable, error);
end;
function TGdkPixbufAnimation.new_from_stream_finish(async_result: PGAsyncResult; error: PPGError): PGdkPixbufAnimation; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_animation_new_from_stream_finish(async_result, error);
end;
procedure TGdkPixbufAnimation.new_from_stream_async(stream: PGInputStream; cancellable: PGCancellable; callback: TGAsyncReadyCallback; user_data: gpointer); cdecl;
begin
LazGdkPixbuf2.gdk_pixbuf_animation_new_from_stream_async(stream, cancellable, callback, user_data);
end;
function TGdkPixbufAnimation.get_height: gint; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_animation_get_height(@self);
end;
function TGdkPixbufAnimation.get_iter(start_time: PGTimeVal): PGdkPixbufAnimationIter; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_animation_get_iter(@self, start_time);
end;
function TGdkPixbufAnimation.get_static_image: PGdkPixbuf; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_animation_get_static_image(@self);
end;
function TGdkPixbufAnimation.get_width: gint; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_animation_get_width(@self);
end;
function TGdkPixbufAnimation.is_static_image: gboolean; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_animation_is_static_image(@self);
end;
function TGdkPixbufAnimationIter.advance(current_time: PGTimeVal): gboolean; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_animation_iter_advance(@self, current_time);
end;
function TGdkPixbufAnimationIter.get_delay_time: gint; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_animation_iter_get_delay_time(@self);
end;
function TGdkPixbufAnimationIter.get_pixbuf: PGdkPixbuf; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_animation_iter_get_pixbuf(@self);
end;
function TGdkPixbufAnimationIter.on_currently_loading_frame: gboolean; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_animation_iter_on_currently_loading_frame(@self);
end;
function TGdkPixbufLoader.new: PGdkPixbufLoader; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_loader_new();
end;
function TGdkPixbufLoader.new_with_mime_type(mime_type: Pgchar; error: PPGError): PGdkPixbufLoader; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_loader_new_with_mime_type(mime_type, error);
end;
function TGdkPixbufLoader.new_with_type(image_type: Pgchar; error: PPGError): PGdkPixbufLoader; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_loader_new_with_type(image_type, error);
end;
function TGdkPixbufLoader.close(error: PPGError): gboolean; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_loader_close(@self, error);
end;
function TGdkPixbufLoader.get_animation: PGdkPixbufAnimation; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_loader_get_animation(@self);
end;
function TGdkPixbufLoader.get_format: PGdkPixbufFormat; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_loader_get_format(@self);
end;
function TGdkPixbufLoader.get_pixbuf: PGdkPixbuf; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_loader_get_pixbuf(@self);
end;
procedure TGdkPixbufLoader.set_size(width: gint; height: gint); cdecl;
begin
LazGdkPixbuf2.gdk_pixbuf_loader_set_size(@self, width, height);
end;
function TGdkPixbufLoader.write(buf: Pguint8; count: gsize; error: PPGError): gboolean; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_loader_write(@self, buf, count, error);
end;
function TGdkPixbufSimpleAnim.new(width: gint; height: gint; rate: gfloat): PGdkPixbufSimpleAnim; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_simple_anim_new(width, height, rate);
end;
procedure TGdkPixbufSimpleAnim.add_frame(pixbuf: PGdkPixbuf); cdecl;
begin
LazGdkPixbuf2.gdk_pixbuf_simple_anim_add_frame(@self, pixbuf);
end;
function TGdkPixbufSimpleAnim.get_loop: gboolean; cdecl;
begin
Result := LazGdkPixbuf2.gdk_pixbuf_simple_anim_get_loop(@self);
end;
procedure TGdkPixbufSimpleAnim.set_loop(loop: gboolean); cdecl;
begin
LazGdkPixbuf2.gdk_pixbuf_simple_anim_set_loop(@self, loop);
end;
end.
| 54.347255 | 360 | 0.808313 |
85e11ece6afb7fe819ba1867cbb91e30cb863b9d | 1,155 | pas | Pascal | src/forms/fSplash.pas | kmzbrnoI/hJOPpanel | 17752ed3da5cf423375250113ce2df6b96c019a2 | [
"Apache-2.0"
]
| 3 | 2016-02-17T20:15:23.000Z | 2018-05-24T20:12:38.000Z | src/forms/fSplash.pas | kmzbrnoI/hJOPpanel | 17752ed3da5cf423375250113ce2df6b96c019a2 | [
"Apache-2.0"
]
| 45 | 2016-04-15T18:21:06.000Z | 2021-09-22T09:54:20.000Z | src/forms/fSplash.pas | kmzbrnoI/hJOPpanel | 17752ed3da5cf423375250113ce2df6b96c019a2 | [
"Apache-2.0"
]
| 1 | 2021-11-16T14:15:33.000Z | 2021-11-16T14:15:33.000Z | unit fSplash;
{
Splash window shown when starting the application.
}
interface
uses
Windows, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, ExtCtrls;
type
TF_splash = class(TForm)
ST_name: TStaticText;
ST_Version: TStaticText;
L_Created: TLabel;
L_BuildTime: TLabel;
I_Horasystems: TImage;
PB_Progress: TProgressBar;
L_1: TLabel;
L_Load: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
procedure ShowState(Text: String);
end;
var
F_splash: TF_splash;
implementation
{$R *.dfm}
uses Verze;
procedure TF_splash.FormCreate(Sender: TObject);
begin
Self.Show();
Application.ProcessMessages();
end;
procedure TF_splash.FormShow(Sender: TObject);
begin
ST_Version.Caption := 'Verze ' + NactiVerzi(Application.ExeName);
L_BuildTime.Caption := GetLastBuildDate + ' ' + GetLastBuildTime;
end;
procedure TF_splash.ShowState(Text: String);
begin
Self.L_Load.Caption := Text;
Self.PB_Progress.Position := F_splash.PB_Progress.Position + 1;
Self.Refresh();
end;
end.// unit
| 19.25 | 68 | 0.722944 |
47211177dc0cb09e202702cde7532e7807422ea1 | 935 | pas | Pascal | src/Horse.Query.pas | dliocode/horse-query | 188e4a63baaca666c634f7f6b7485f10fd878941 | [
"MIT"
]
| 8 | 2020-10-22T11:02:33.000Z | 2021-06-24T11:39:00.000Z | src/Horse.Query.pas | dliocode/horse-query | 188e4a63baaca666c634f7f6b7485f10fd878941 | [
"MIT"
]
| 1 | 2021-01-20T23:10:17.000Z | 2021-01-20T23:16:13.000Z | src/Horse.Query.pas | dliocode/horse-query | 188e4a63baaca666c634f7f6b7485f10fd878941 | [
"MIT"
]
| 5 | 2020-10-30T14:40:23.000Z | 2021-06-26T02:09:42.000Z | unit Horse.Query;
interface
uses
Horse,
DataSet.Serialize,
Data.DB,
System.JSON, System.SysUtils;
procedure Query(Req: THorseRequest; Res: THorseResponse; Next: TProc);
implementation
procedure Query(Req: THorseRequest; Res: THorseResponse; Next: TProc);
var
LContent: TObject;
LJA: TJSONArray;
LOldCaseName: TCaseNameDefinition;
begin
Next;
LContent := Res.Content;
if Assigned(LContent) and LContent.InheritsFrom(TDataSet) then
begin
LOldCaseName := TDataSetSerializeConfig.GetInstance.CaseNameDefinition;
TDataSetSerializeConfig.GetInstance.CaseNameDefinition := TCaseNameDefinition.cndLower;
try
LJA := TDataSet(LContent).ToJSONArray;
finally
TDataSetSerializeConfig.GetInstance.CaseNameDefinition := LOldCaseName;
end;
end
else
Exit;
if Assigned(LJA) then
begin
Res.Send(LJA.ToString);
FreeAndNil(LJA);
end
else
Res.Send('[]');
end;
end.
| 19.081633 | 91 | 0.73262 |
f19f893df71e8b2a01c37426e5fb874bd51d2b43 | 368 | pas | Pascal | Test/SimpleScripts/const_block.pas | skolkman/dwscript | b9f99d4b8187defac3f3713e2ae0f7b83b63d516 | [
"Condor-1.1"
]
| 79 | 2015-03-18T10:46:13.000Z | 2022-03-17T18:05:11.000Z | Test/SimpleScripts/const_block.pas | skolkman/dwscript | b9f99d4b8187defac3f3713e2ae0f7b83b63d516 | [
"Condor-1.1"
]
| 6 | 2016-03-29T14:39:00.000Z | 2020-09-14T10:04:14.000Z | Test/SimpleScripts/const_block.pas | skolkman/dwscript | b9f99d4b8187defac3f3713e2ae0f7b83b63d516 | [
"Condor-1.1"
]
| 25 | 2016-05-04T13:11:38.000Z | 2021-09-29T13:34:31.000Z | procedure Stuff1;
const
a = 1;
b = 2;
var
c : Integer;
d : Integer;
begin
c:=d;
end;
procedure Stuff2;
var
c : Integer;
d : Integer;
const
a = 1;
b = 2;
begin
c:=d;
end;
procedure Stuff3;
var
c : Integer;
d : Integer;
begin
c:=d;
end;
procedure Stuff4;
const
a = 1;
b = 2;
begin
end;
| 9.945946 | 18 | 0.494565 |
47974eaaddb5690e25f01714eb4b52e60357ce5f | 419 | dfm | Pascal | screen/uUsuarioAcessoScreen.dfm | RickMao/mvcdelphi | 9f2b7ca714aba25e6918964975acba91298c998e | [
"Unlicense"
]
| null | null | null | screen/uUsuarioAcessoScreen.dfm | RickMao/mvcdelphi | 9f2b7ca714aba25e6918964975acba91298c998e | [
"Unlicense"
]
| null | null | null | screen/uUsuarioAcessoScreen.dfm | RickMao/mvcdelphi | 9f2b7ca714aba25e6918964975acba91298c998e | [
"Unlicense"
]
| 1 | 2019-10-31T17:41:00.000Z | 2019-10-31T17:41:00.000Z | object UsuarioAcessoScreen: TUsuarioAcessoScreen
Left = 0
Top = 0
BorderStyle = bsSingle
Caption = 'Sistema de Login MVC'
ClientHeight = 571
ClientWidth = 794
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
KeyPreview = True
OldCreateOrder = False
PixelsPerInch = 96
TextHeight = 13
end
| 22.052632 | 49 | 0.680191 |
f1e571f314ce0d849d0b3902a72b10ce25f6ffa4 | 91,443 | pas | Pascal | Cairo/cairo.pas | bittencourtthulio/SVGIconImageList | e62c4d900ec72d1b5c065b8648ff594494276fd0 | [
"Apache-2.0"
]
| 4 | 2021-05-06T17:36:32.000Z | 2022-01-17T21:33:25.000Z | Cairo/cairo.pas | bittencourtthulio/SVGIconImageList | e62c4d900ec72d1b5c065b8648ff594494276fd0 | [
"Apache-2.0"
]
| null | null | null | Cairo/cairo.pas | bittencourtthulio/SVGIconImageList | e62c4d900ec72d1b5c065b8648ff594494276fd0 | [
"Apache-2.0"
]
| 1 | 2021-04-12T19:31:49.000Z | 2021-04-12T19:31:49.000Z | (* cairo delphi & freepascal binding
*
* This library is free software; you can redistribute it and/or
* modify it either under the terms of the GNU Lesser General Public
* License version 2.1 as published by the Free Software Foundation
* (the "LGPL") or, at your option, under the terms of the Mozilla
* Public License Version 1.1 (the "MPL"). If you do not alter this
* notice, a recipient may use your version of this file under either
* the MPL or the LGPL.
*
* You should have received a copy of the LGPL along with this library
* in the file COPYING-LGPL-2.1; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* You should have received a copy of the MPL along with this library
* in the file COPYING-MPL-1.1
*
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY
* OF ANY KIND, either express or implied. See the LGPL or the MPL for
* the specific language governing rights and limitations.
*
* Author(s):
* Henri Gourvest <hgourvest@progdigy.com>
*)
unit cairo;
{$IFDEF FPC}
{$MODE OBJFPC}{$H+}
{$ENDIF}
{$I cairo.inc}
interface
uses sysutils, classes, cairolib
{$IFDEF MSWINDOWS}
, windows
{$ENDIF}
{$IFDEF CAIRO_HAS_RSVG_FUNCTIONS}
,rsvg
{$ENDIF}
;
type
ECairoException = class(Exception)
private
FStatus: TCairoStatus;
public
constructor Create(AStatus: TCairoStatus); virtual;
property Status: TCairoStatus read FStatus;
end;
ICairoFontFace = interface
['{67C6474B-3B01-4330-976F-E0F3A6A5F287}']
function GetUserData(key: Pointer): Pointer;
procedure SetUserData(key: Pointer; userData: Pointer; destroyFunc: TCairoDestroyFunc);
function GetStatus: TCairoStatus;
function GetType: TCairoFontType;
property Status: TCairoStatus read GetStatus;
property FontType: TCairoFontType read GetType;
end;
TCairoFontFace = class(TInterfacedObject, ICairoFontFace)
private
FFontFace: PCairoFontFace;
class function init(fontface: PCairoFontFace): TCairoFontFace;
constructor CreateInternal(fontface: PCairoFontFace);
protected
function GetUserData(key: Pointer): Pointer;
procedure SetUserData(key: Pointer; userData: Pointer; destroyFunc: TCairoDestroyFunc);
function GetStatus: TCairoStatus;
function GetType: TCairoFontType;
public
destructor Destroy; override;
property FontFace: PCairoFontFace read FFontFace;
end;
ICairoToyFontFace = interface(ICairoFontFace)
['{1A1EF26C-EA53-4151-A8B6-FED2BA11FBC2}']
function GetFamily: AnsiString;
function GetSlant: TCairoFontSlant;
function GetWeight: TCairoFontWeight;
property Family: AnsiString read GetFamily;
property Slant: TCairoFontSlant read GetSlant;
property Weight: TCairoFontWeight read GetWeight;
end;
TCairoToyFontFace = class(TCairoFontFace, ICairoToyFontFace)
protected
function GetFamily: AnsiString;
function GetSlant: TCairoFontSlant;
function GetWeight: TCairoFontWeight;
public
constructor Create(const family: AnsiString; slant: TCairoFontSlant; weight: TCairoFontWeight);
end;
{$ifdef CAIRO_HAS_WIN32_FONT}
TCairoWin32FontFace = class(TCairoFontFace)
public
constructor CreateForLogfontw(logfont: PLOGFONTW);
constructor CreateForHfont(font: HFONT);
constructor CreateForLogfontwHfont(logfont: PLOGFONTW; font: HFONT);
end;
{$endif}
ICairoFontOptions = interface
['{103D190B-93AB-492C-A144-CAD73CC21135}']
function GetUserData: Pointer;
function Copy: ICairoFontOptions;
function GetStatus: TCairoStatus;
procedure Merge(other: ICairoFontOptions);
function Equal(other: ICairoFontOptions): Boolean;
function GetHash: Cardinal;
procedure SetAntialias(antialias: TCairoAntialias);
function GetAntialias: TCairoAntialias;
procedure SetSubpixelOrder(subpixelOrder: TCairoSubpixelOrder);
function GetSubpixelOrder: TCairoSubpixelOrder;
procedure SetHintStyle(hintStyle: TCairoHintStyle);
function GetHintStyle: TCairoHintStyle;
procedure SetHintMetrics(hintMetrics: TCairoHintMetrics);
function GetHintMetrics: TCairoHintMetrics;
property Antialias: TCairoAntialias read GetAntialias write SetAntialias;
property SubpixelOrder: TCairoSubpixelOrder read GetSubpixelOrder write SetSubpixelOrder;
property HintStyle: TCairoHintStyle read GetHintStyle write SetHintStyle;
property HintMetrics: TCairoHintMetrics read GetHintMetrics write SetHintMetrics;
end;
TCairoUserFontFace = class(TCairoFontFace)
public
constructor Create; virtual;
end;
TCairoFontOptions = class(TInterfacedObject, ICairoFontOptions)
private
FFontOptions: PCairoFontOptions;
constructor CreateInternal(options: PCairoFontOptions);
protected
function GetUserData: Pointer;
function Copy: ICairoFontOptions;
function GetStatus: TCairoStatus;
procedure Merge(other: ICairoFontOptions);
function Equal(other: ICairoFontOptions): Boolean;
function GetHash: Cardinal;
procedure SetAntialias(antialias: TCairoAntialias);
function GetAntialias: TCairoAntialias;
procedure SetSubpixelOrder(subpixelOrder: TCairoSubpixelOrder);
function GetSubpixelOrder: TCairoSubpixelOrder;
procedure SetHintStyle(hintStyle: TCairoHintStyle);
function GetHintStyle: TCairoHintStyle;
procedure SetHintMetrics(hintMetrics: TCairoHintMetrics);
function GetHintMetrics: TCairoHintMetrics;
public
constructor Create; virtual;
destructor Destroy; override;
property FontOptions: PCairoFontOptions read FFontOptions;
end;
ICairoScaledFont = interface(ICairoFontFace)
['{EA646BC8-2E6A-4288-BBA2-C68AE29795EB}']
function GetStatus: TCairoStatus;
function GetType: TCairoFontType;
procedure Extents(extent: TCairoFontExtents);
procedure TextExtents(utf8: UTF8String; extent: TCairoTextExtents);
procedure GlyphExtents(glyphs: PCairoGlyph; numGlyphs: Integer; extent: TCairoTextExtents);
procedure TextToGlyphs(x, y: Double; utf8: UTF8String = '';
glyphs: PPCairoGlyph = nil; numGlyphs: Integer = 0;
clusters: PPCairoTextCluster = nil; numClusters: Integer = 0;
clusterFlags: PCairoTextClusterFlags = nil);
function GetFontFace: ICairoFontFace;
procedure GetFontMatrix(var fontMatrix: TCairoMatrix);
procedure GetCtm(var ctm: TCairoMatrix);
procedure GetScaleMatrix(var scaleMatrix: TCairoMatrix);
procedure GetFontOptions(options: ICairoFontOptions);
end;
TCairoScaledFont = class(TInterfacedObject, ICairoScaledFont)
private
FScaledFont: PCairoScaledFont;
class function init(scaledfont: PCairoScaledFont): TCairoScaledFont;
protected
function GetUserData(key: Pointer): Pointer;
procedure SetUserData(key: Pointer; userData: Pointer; destroyFunc: TCairoDestroyFunc);
function GetStatus: TCairoStatus;
function GetType: TCairoFontType;
procedure Extents(extent: TCairoFontExtents);
procedure TextExtents(utf8: UTF8String; extent: TCairoTextExtents);
procedure GlyphExtents(glyphs: PCairoGlyph; numGlyphs: Integer; extent: TCairoTextExtents);
procedure TextToGlyphs(x, y: Double; utf8: UTF8String = '';
glyphs: PPCairoGlyph = nil; numGlyphs: Integer = 0;
clusters: PPCairoTextCluster = nil; numClusters: Integer = 0;
clusterFlags: PCairoTextClusterFlags = nil);
function GetFontFace: ICairoFontFace;
procedure GetFontMatrix(var fontMatrix: TCairoMatrix);
procedure GetCtm(var ctm: TCairoMatrix);
procedure GetScaleMatrix(var scaleMatrix: TCairoMatrix);
procedure GetFontOptions(options: ICairoFontOptions);
public
constructor CreateInternal(scaledfont: PCairoScaledFont);
constructor Create(fontFace: ICairoFontFace; fontMatrix, ctm: TCairoMatrix; options: ICairoFontOptions); virtual;
destructor Destroy; override;
property ScaledFont: PCairoScaledFont read FScaledFont;
end;
TUserScaledFont = class(TCairoScaledFont)
protected
function UserTextToGlyphs(utf8: PAnsiChar; utf8Len: Integer; glyphs: PPCairoGlyph; numGlyphs: PInteger; clusters: PPCairoTextCluster; numClusters: PInteger; clusterFlags: PCairoTextClusterFlags): TCairoStatus; virtual; abstract;
function UserInit(cr: PCairo; extent: PCairoFontExtents): TCairoStatus; virtual; abstract;
function UserRenderGlyph(glyph: Cardinal; cr: PCairo; extent: PCairoTextExtents): TCairoStatus; virtual; abstract;
function UserUnicodeToGlyph(unicode: Cardinal; glyphIndex: PCardinal): TCairoStatus; virtual; abstract;
public
constructor Create(fontFace: ICairoFontFace; fontMatrix, ctm: TCairoMatrix; options: ICairoFontOptions); override;
end;
{$ifdef CAIRO_HAS_WIN32_FONT}
ICairoWin32ScaledFont = interface(ICairoScaledFont)
['{E456AD11-E68D-46BE-BB5E-455184F75B68}']
procedure SelectFont(hdc: HDC);
procedure DoneFont;
function GetMetricsFactor: Double;
procedure GetLogicalToDevice(var logicalToDevice: TCairoMatrix);
procedure GetDeviceToLogical(var deviceToLogical: TCairoMatrix);
end;
{$endif}
{$ifdef CAIRO_HAS_WIN32_FONT}
TCairoWin32ScaledFont = class(TCairoScaledFont, ICairoWin32ScaledFont)
protected
procedure SelectFont(hdc: HDC);
procedure DoneFont;
function GetMetricsFactor: Double;
procedure GetLogicalToDevice(var logicalToDevice: TCairoMatrix);
procedure GetDeviceToLogical(var deviceToLogical: TCairoMatrix);
end;
{$endif}
ICairoDevice = interface
['{F7FCAD08-427E-4772-BFF7-7A0543280DC5}']
function GetType: TCairoDeviceType;
function GetStatus: TCairoStatus;
function Acquire: TCairoStatus;
procedure Release;
procedure Flush;
procedure Finish;
end;
TCairoDevice = class(TInterfacedObject, ICairoDevice)
private
FDevice: PCairoDevice;
class function init(device: PCairoDevice): TCairoDevice;
constructor CreateInternal(device: PCairoDevice);
protected
function GetType: TCairoDeviceType;
function GetStatus: TCairoStatus;
function Acquire: TCairoStatus;
procedure Release;
procedure Flush;
procedure Finish;
public
destructor Destroy; override;
end;
ICairoSurface = interface
['{CE917E0C-97B2-434E-8C72-CD7930C4BB67}']
function GetUserData(key: Pointer): Pointer;
procedure SetUserData(key: Pointer; userData: Pointer; destroyFunc: TCairoDestroyFunc);
function CreateSimilar(content: TCairoContent; width, height: Integer): ICairoSurface;
function CreateForRectangle(x, y, width, height: Double): ICairoSurface;
procedure Finish;
function GetStatus: TCairoStatus;
function GetType: TCairoSurfaceType;
function GetContent: TCairoContent;
{$ifdef CAIRO_HAS_PNG_FUNCTIONS}
procedure WriteToPNG(const filename: string);
procedure WriteToPNGStream(stream: TStream);
{$endif}
procedure GetFontOptions(options: ICairoFontOptions);
procedure Flush;
procedure MarkDirty;
procedure MarkDirtyRectangle(x, y, width, height: Integer);
procedure SetDeviceOffset(xOffset, yOffset: Double);
procedure GetDeviceOffset(var xOffset, yOffset: Double);
procedure SetFallbackResolution(xPixelsPerInch, yPixelsPerInch: Double);
procedure GetFallbackResolution(var xPixelsPerInch, yPixelsPerInch: Double);
procedure CopyPage;
procedure ShowPage;
function HasShowTextGlyphs: Boolean;
function GetDevice: ICairoDevice;
procedure GetMimeData(const mime_type: PAnsiChar; out data: Pointer; out length: Cardinal);
function SetMimeData(const mime_type: PAnsiChar; const data : Pointer; length: Cardinal; destroy: TCairoDestroyFunc; closure: Pointer): TCairoStatus;
property Status: TCairoStatus read GetStatus;
property SurfaceType: TCairoSurfaceType read GetType;
property Content: TCairoContent read GetContent;
property Device: ICairoDevice read GetDevice;
end;
TCairoSurface = class(TInterfacedObject, ICairoSurface)
private
FSurface: PCairoSurface;
class function init(surface: PCairoSurface): TCairoSurface;
constructor CreateInternal(surface: PCairoSurface);
protected
function GetUserData(key: Pointer): Pointer;
procedure SetUserData(key: Pointer; userData: Pointer; destroyFunc: TCairoDestroyFunc);
function CreateSimilar(content: TCairoContent; width, height: Integer): ICairoSurface;
function CreateForRectangle(x, y, width, height: Double): ICairoSurface;
procedure Finish;
function GetStatus: TCairoStatus;
function GetType: TCairoSurfaceType;
function GetContent: TCairoContent;
{$ifdef CAIRO_HAS_PNG_FUNCTIONS}
procedure WriteToPNG(const filename: string);
procedure WriteToPNGStream(stream: TStream);
{$endif}
procedure GetFontOptions(options: ICairoFontOptions);
procedure Flush;
procedure MarkDirty;
procedure MarkDirtyRectangle(x, y, width, height: Integer);
procedure SetDeviceOffset(xOffset, yOffset: Double);
procedure GetDeviceOffset(var xOffset, yOffset: Double);
procedure SetFallbackResolution(xPixelsPerInch, yPixelsPerInch: Double);
procedure GetFallbackResolution(var xPixelsPerInch, yPixelsPerInch: Double);
procedure CopyPage;
procedure ShowPage;
function HasShowTextGlyphs: Boolean;
function GetDevice: ICairoDevice;
procedure GetMimeData(const mimeType: PAnsiChar; out data: Pointer; out length: Cardinal);
function SetMimeData(const mimeType: PAnsiChar; const data : Pointer; length: Cardinal; destroy: TCairoDestroyFunc; closure: Pointer): TCairoStatus;
public
constructor CreateRecording(content: TCairoContent; const extents: PCairoRectangle);
//function cairo_recording_surface_create(content: TCairoContent; const extents: PCairoRectangle): PCairoSurface; cdecl;
//procedure cairo_recording_surface_ink_extents(surface: PCairoSurface; x0, y0, width, height: PDouble); cdecl;
destructor Destroy; override;
property Surface: PCairoSurface read FSurface;
end;
ICairoPattern = interface
['{F93A9DAE-6E01-4B92-A13F-3CCCFA6B0EEA}']
function GetStatus: TCairoStatus;
function GetUserData(key: Pointer): Pointer;
procedure SetUserData(key: Pointer; userData: Pointer; destroyFunc: TCairoDestroyFunc);
function GetType: TCairoPatternType;
procedure AddColorStopRGB(offset, red, green, blue: Double);
procedure AddColorStopRGBA(offset, red, green, blue, alpha: Double);
procedure AddColorStop(offset: Double; color: Cardinal);
procedure SetMatrix(matrix: TCairoMatrix);
procedure GetMatrix(var matrix: TCairoMatrix);
procedure SetExtend(extend: TCairoExtend);
function GetExtend: TCairoExtend;
procedure SetFilter(filter: TCairoFilter);
function GetFilter: TCairoFilter;
procedure GetRGBA(red, green, blue, alpha: PDouble);
function GetSurface: ICairoSurface;
procedure GetColorStopRGBA(index: Integer; offset, red, green, blue, alpha: PDouble);
function GetColorStopCount: Integer;
procedure GetLinearPoints(x0, y0, x1, y1: PDouble);
procedure GetRadialCircles(x0, y0, r0, x1, y1, r1: PDouble);
property Extend: TCairoExtend read GetExtend write SetExtend;
property Status: TCairoStatus read GetStatus;
property Filter: TCairoFilter read GetFilter write SetFilter;
property Surface: ICairoSurface read GetSurface;
end;
TCairoPattern = class(TInterfacedObject, ICairoPattern)
private
FPattern: PCairoPattern;
class function init(pattern: PCairoPattern): TCairoPattern;
constructor CreateInternal(pattern: PCairoPattern);
protected
function GetStatus: TCairoStatus;
function GetUserData(key: Pointer): Pointer;
procedure SetUserData(key: Pointer; userData: Pointer; destroyFunc: TCairoDestroyFunc);
function GetType: TCairoPatternType;
procedure AddColorStopRGB(offset, red, green, blue: Double);
procedure AddColorStopRGBA(offset, red, green, blue, alpha: Double);
procedure AddColorStop(offset: Double; color: Cardinal);
procedure SetMatrix(matrix: TCairoMatrix);
procedure GetMatrix(var matrix: TCairoMatrix);
procedure SetExtend(extend: TCairoExtend);
function GetExtend: TCairoExtend;
procedure SetFilter(filter: TCairoFilter);
function GetFilter: TCairoFilter;
procedure GetRGBA(red, green, blue, alpha: PDouble);
function GetSurface: ICairoSurface;
procedure GetColorStopRGBA(index: Integer; offset, red, green, blue, alpha: PDouble);
function GetColorStopCount: Integer;
procedure GetLinearPoints(x0, y0, x1, y1: PDouble);
procedure GetRadialCircles(x0, y0, r0, x1, y1, r1: PDouble);
public
constructor CreateRGB(red, green, blue: Double);
constructor CreateRGBA(red, green, blue, alpha: Double);
constructor CreateForSurface(surface: ICairoSurface);
constructor CreateLinear(x0, y0, x1, y1: Double);
constructor CreateRadial(cx0, cy0, radius0, cx1, cy1, radius1: Double);
destructor Destroy; override;
property Pattern: PCairoPattern read FPattern;
end;
{$ifdef CAIRO_HAS_WIN32_SURFACE}
IWin32Surface = interface(ICairoSurface)
['{94C8B7E7-4AD4-4EA2-90BE-D9E2FC59725E}']
function GetDC: HDC;
function GetImage: ICairoSurface;
end;
{$endif}
{$ifdef CAIRO_HAS_WIN32_SURFACE}
TWin32Surface = class(TCairoSurface, IWin32Surface)
protected
function GetDC: HDC;
function GetImage: ICairoSurface;
public
constructor CreateHDC(hdc: HDC); virtual;
constructor CreatePrinting(hdc: HDC); virtual;
constructor CreateWithDDB(hdc: HDC; format: TCairoFormat; width, height: Integer); virtual;
constructor CreateWithDIB(format: TCairoFormat; width: Integer; height: Integer); virtual;
end;
{$ENDIF}
IImageSurface = interface(ICairoSurface)
['{4D4E061E-D4D5-4DBB-9A09-036724AB15F0}']
function GetData: Pointer;
function GetFormat: TCairoFormat;
function GetWidth: Integer;
function GetHeight: Integer;
function GetStride: Integer;
property Data: Pointer read GetData;
property Format: TCairoFormat read GetFormat;
property Width: Integer read GetWidth;
property Height: Integer read GetHeight;
property Stride: Integer read GetStride;
end;
TImageSurface = class(TCairoSurface, IImageSurface)
protected
function GetData: Pointer;
function GetFormat: TCairoFormat;
function GetWidth: Integer;
function GetHeight: Integer;
function GetStride: Integer;
public
constructor Create(format: TCairoFormat; width, height: Integer);
constructor CreateForData(data: Pointer; format: TCairoFormat; width, height, stride: Integer);
{$ifdef CAIRO_HAS_PNG_FUNCTIONS}
constructor CreateFromPNG(const filename: string); overload;
constructor CreateFromPNG(stream: TStream); overload;
{$endif}
{$ifdef CAIRO_HAS_RSVG_FUNCTIONS}
constructor CreateFromSVG(const filename: string; format: TCairoFormat; scale: double); overload;
constructor CreateFromSVG(stream: TStream; format: TCairoFormat; scale: double); overload;
{$endif}
end;
{$ifdef CAIRO_HAS_SVG_SURFACE}
ISVGSurface = interface(ICairoSurface)
['{8A00FEC6-0C3D-4F0B-A781-BA764731FC71}']
procedure RestrictToVersion(version: TCairoSVGVersion);
end;
{$endif}
{$ifdef CAIRO_HAS_SVG_SURFACE}
TSVGSurface = class(TCairoSurface, ISVGSurface)
private
FStream: TStream;
protected
procedure RestrictToVersion(version: TCairoSVGVersion);
public
constructor Create(stream: TStream; widthInPoints, heightInPoints: Double; owned: boolean = false); overload;
constructor Create(filename: TFileName; widthInPoints, heightInPoints: Double); overload;
destructor Destroy; override;
end;
{$endif}
{$ifdef CAIRO_HAS_PDF_SURFACE}
IPDFSurface = interface(ICairoSurface)
['{AEFBC266-74E8-418A-9908-C3C118157C28}']
procedure SetSize(widthInPoints, heightInPoints: Double);
procedure RestrictToVersion(version: TCairoPdfVersion);
end;
{$endif}
{$ifdef CAIRO_HAS_PDF_SURFACE}
TPDFSurface = class(TCairoSurface, IPDFSurface)
private
FStream: TStream;
protected
procedure SetSize(widthInPoints, heightInPoints: Double);
procedure RestrictToVersion(version: TCairoPdfVersion);
public
constructor Create(stream: TStream; widthInPoints, heightInPoints: Double; owned: boolean = false); overload;
constructor Create(filename: TFileName; widthInPoints, heightInPoints: Double); overload;
destructor Destroy; override;
end;
{$endif}
{$ifdef CAIRO_HAS_PS_SURFACE}
IPostScriptSurface = interface(ICairoSurface)
['{F763BE75-E19C-4F48-8C5B-AC220D9FE3F4}']
procedure RestrictToLevel(level: TCairoPSLevel);
procedure SetEPS(eps: Boolean);
function GetEPS: Boolean;
procedure SetSize(widthInPoints, heightInPoints: Double);
procedure DscComment(const comment: AnsiString);
procedure DscBeginSetup;
procedure DscBeginPageSetup;
property EPS: Boolean read GetEPS write SetEPS;
end;
{$endif}
{$ifdef CAIRO_HAS_PS_SURFACE}
TPostScriptSurface = class(TCairoSurface, IPostScriptSurface)
private
FStream: TStream;
protected
procedure RestrictToLevel(level: TCairoPSLevel);
procedure SetEPS(eps: Boolean);
function GetEPS: Boolean;
procedure SetSize(widthInPoints, heightInPoints: Double);
procedure DscComment(const comment: AnsiString);
procedure DscBeginSetup;
procedure DscBeginPageSetup;
public
constructor Create(stream: TStream; widthInPoints, heightInPoints: Double; owned: boolean = false); overload;
constructor Create(const filename: string; widthInPoints, heightInPoints: Double); overload;
destructor Destroy; override;
end;
{$endif}
ICairoContext = interface
['{CDF9B3F9-ED80-4300-9D2C-4F0B233A9912}']
function GetStatus: TCairoStatus;
(* Functions for manipulating state objects *)
function GetUserData(key: Pointer): Pointer;
procedure SetUserData(key: Pointer; userData: Pointer; destroyFunc: TCairoDestroyFunc);
procedure Save;
procedure Restore;
procedure PushGroup;
procedure PushGroupWithContent(content: TCairoContent);
function PopGroup: ICairoPattern;
procedure PopGroupToSource;
(* Modify state *)
procedure SetOperator(op: TCairoOperator);
procedure SetSource(source: ICairoPattern);
procedure SetSourceColor(color: Cardinal);
procedure SetSourceRGB(red, green, blue: Double);
procedure SetSourceRGBA(red, green, blue, alpha: Double);
procedure SetSourceSurface(surface: ICairoSurface; x, y: Double);
procedure SetTolerance(tolerance: Double);
procedure SetAntialias(antialias: TCairoAntialias);
procedure SetFillRule(fillRule: TCairoFillRule);
procedure SetLineWidth(width: Double);
procedure SetLineCap(lineCap: TCairoLineCap);
procedure SetLineJoin(lineJoin: TCairoLineJoin);
procedure SetDash(dashes: PDouble; numDashes: Integer; offset: Double);
procedure SetMiterLimit(limit: Double);
procedure Translate(tx, ty: Double);
procedure Scale(sx, sy: Double);
procedure Rotate(angle: Double);
procedure Transform(matrix: TCairoMatrix);
procedure SetMatrix(matrix: TCairoMatrix);
procedure IdentityMatrix;
procedure UserToDevice(var x, y: Double);
procedure UserToDeviceDistance(var dx, dy: Double);
procedure DeviceToUser(var x, y: Double);
procedure DeviceToUserDistance(var dx, dy: Double);
(* Path creation functions *)
procedure NewPath;
procedure MoveTo(x, y: Double);
procedure NewSubPath;
procedure LineTo(x, y: Double);
procedure CurveTo(x1, y1, x2, y2, x3, y3: Double);
procedure Arc(xc, yc, radius, angle1, angle2: Double);
procedure ArcNegative(xc, yc, radius, angle1, angle2: Double);
procedure RelMoveTo(dx, dy: Double);
procedure RelLineTo(dx, dy: Double);
procedure RelCurveTo(dx1, dy1, dx2, dy2, dx3, dy3: Double);
procedure Rectangle(x, y, width, height: Double);
procedure ClosePath;
procedure PathExtents(x1, y1, x2, y2: PDouble);
(* Painting functions *)
procedure Paint;
procedure PaintWithAlpha(alpha: Double);
procedure Mask(pattern: ICairoPattern);
procedure MaskSurface(surface: ICairoSurface; surfaceX, surfaceY: Double);
procedure Stroke;
procedure StrokePreserve;
procedure Fill;
procedure FillPreserve;
procedure CopyPage;
procedure ShowPage;
(* Insideness testing *)
function InStroke(x, y: Double): Boolean;
function InFill(x, y: Double): Boolean;
function InClip(x, y: Double): Boolean;
(* Rectangular extents *)
procedure StrokeExtents(x1, y1, x2, y2: PDouble);
procedure FillExtents(x1, y1, x2, y2: PDouble);
(* Clipping *)
procedure ResetClip;
procedure Clip;
procedure ClipPreserve;
procedure ClipExtents(x1, y1, x2, y2: PDouble);
function CopyClipRectangleList: PCairoRectangleList; // destroy it !
(* Font/Text functions *)
procedure SelectFontFace(const family: AnsiString; slant: TCairoFontSlant; weight: TCairoFontWeight);
procedure SetFontSize(size: Double);
procedure SetFontMatrix(matrix: TCairoMatrix);
procedure GetFontMatrix(var matrix: TCairoMatrix);
procedure SetFontOptions(options: ICairoFontOptions);
function GetFontOptions: ICairoFontOptions;
procedure SetFontFace(fontFace: ICairoFontFace);
function GetFontFace: ICairoFontFace;
procedure SetScaledFont(scaledFont: ICairoScaledFont);
function GetScaledFont: ICairoScaledFont;
procedure ShowText(utf8: UTF8String);
procedure ShowGlyphs(glyphs: PCairoGlyph; numGlyphs: Integer);
procedure ShowTextGlyphs(utf8: UTF8String; glyphs: PCairoGlyph;
numGlyphs: Integer; clusters: PCairoTextCluster; numClusters: Integer;
clusterFlags: TCairoTextClusterFlags);
procedure TextPath(utf8: UTF8String);
procedure GlyphPath(glyphs: PCairoGlyph; numGlyphs: Integer);
procedure TextExtents(utf8: UTF8String; extent: PCairoTextExtents);
procedure GlyphExtents(glyphs: PCairoGlyph; numGlyphs: Integer; extent: PCairoTextExtents);
procedure FontExtents(extents: PCairoFontExtents);
(* Query functions *)
function GetOperator: TCairoOperator;
function GetSource: ICairoPattern;
function GetTolerance: Double;
function GetAntialias: TCairoAntialias;
function HasCurrentPoint: Boolean;
procedure GetCurrentPoint(x: PDouble; y: PDouble);
function GetFillRule: TCairoFillRule;
function GetLineWidth: Double;
function GetLineCap: TCairoLineCap;
function GetLineJoin: TCairoLineJoin;
function GetMiterLimit: Double;
function GetDashCount: Integer;
procedure GetDash(dashes: PDouble; offset: PDouble);
procedure GetMatrix(var matrix: TCairoMatrix);
function GetTarget: ICairoSurface;
function GetGroupTarget: ICairoSurface;
(* path *)
function CopyPath: PCairoPath; // destroy it !
function CopyPathFlat: PCairoPath; // destroy it !
procedure AppendPath(path: PCairoPath);
(* SVG *)
{$IFDEF CAIRO_HAS_RSVG_FUNCTIONS}
function RenderSVG(svg: IRSVGObject; id: RawByteString = ''): Boolean;
{$ENDIF}
property Op: TCairoOperator read GetOperator write SetOperator;
property Source: ICairoPattern read GetSource write SetSource;
property Tolerance: Double read GetTolerance write SetTolerance;
property Antialias: TCairoAntialias read GetAntialias write SetAntialias;
property FillRule: TCairoFillRule read GetFillRule write SetFillRule;
property LineWidth: Double read GetLineWidth write SetLineWidth;
property LineCap: TCairoLineCap read GetLineCap write SetLineCap;
property LineJoin: TCairoLineJoin read GetLineJoin write SetLineJoin;
property MiterLimit: Double read GetMiterLimit write SetMiterLimit;
property DashCount: Integer read GetDashCount;
property Target: ICairoSurface read GetTarget;
property GroupTarget: ICairoSurface read GetGroupTarget;
property Status: TCairoStatus read GetStatus;
property FontFace: ICairoFontFace read GetFontFace write SetFontFace;
end;
TCairoContext = class(TInterfacedObject, ICairoContext)
private
FContext: PCairo;
//class function init(context: PCairo): TCairoContext;
constructor CreateInternal(context: PCairo);
protected
function GetStatus: TCairoStatus;
(* Functions for manipulating state objects *)
function GetUserData(key: Pointer): Pointer;
procedure SetUserData(key: Pointer; userData: Pointer; destroyFunc: TCairoDestroyFunc);
procedure Save;
procedure Restore;
procedure PushGroup;
procedure PushGroupWithContent(content: TCairoContent);
function PopGroup: ICairoPattern;
procedure PopGroupToSource;
(* Modify state *)
procedure SetOperator(op: TCairoOperator);
procedure SetSource(source: ICairoPattern);
procedure SetSourceColor(color: Cardinal);
procedure SetSourceRGB(red, green, blue: Double);
procedure SetSourceRGBA(red, green, blue, alpha: Double);
procedure SetSourceSurface(surface: ICairoSurface; x, y: Double);
procedure SetTolerance(tolerance: Double);
procedure SetAntialias(antialias: TCairoAntialias);
procedure SetFillRule(fillRule: TCairoFillRule);
procedure SetLineWidth(width: Double);
procedure SetLineCap(lineCap: TCairoLineCap);
procedure SetLineJoin(lineJoin: TCairoLineJoin);
procedure SetDash(dashes: PDouble; numDashes: Integer; offset: Double);
procedure SetMiterLimit(limit: Double);
procedure Translate(tx, ty: Double);
procedure Scale(sx, sy: Double);
procedure Rotate(angle: Double);
procedure Transform(matrix: TCairoMatrix);
procedure SetMatrix(matrix: TCairoMatrix);
procedure IdentityMatrix;
procedure UserToDevice(var x, y: Double);
procedure UserToDeviceDistance(var dx, dy: Double);
procedure DeviceToUser(var x, y: Double);
procedure DeviceToUserDistance(var dx, dy: Double);
(* Path creation functions *)
procedure NewPath;
procedure MoveTo(x, y: Double);
procedure NewSubPath;
procedure LineTo(x, y: Double);
procedure CurveTo(x1, y1, x2, y2, x3, y3: Double);
procedure Arc(xc, yc, radius, angle1, angle2: Double);
procedure ArcNegative(xc, yc, radius, angle1, angle2: Double);
procedure RelMoveTo(dx, dy: Double);
procedure RelLineTo(dx, dy: Double);
procedure RelCurveTo(dx1, dy1, dx2, dy2, dx3, dy3: Double);
procedure Rectangle(x, y, width, height: Double);
procedure ClosePath;
procedure PathExtents(x1, y1, x2, y2: PDouble);
(* Painting functions *)
procedure Paint;
procedure PaintWithAlpha(alpha: Double);
procedure Mask(pattern: ICairoPattern);
procedure MaskSurface(surface: ICairoSurface; surfaceX, surfaceY: Double);
procedure Stroke;
procedure StrokePreserve;
procedure Fill;
procedure FillPreserve;
procedure CopyPage;
procedure ShowPage;
(* Insideness testing *)
function InStroke(x, y: Double): Boolean;
function InFill(x, y: Double): Boolean;
function InClip(x, y: Double): Boolean;
(* Rectangular extents *)
procedure StrokeExtents(x1, y1, x2, y2: PDouble);
procedure FillExtents(x1, y1, x2, y2: PDouble);
(* Clipping *)
procedure ResetClip;
procedure Clip;
procedure ClipPreserve;
procedure ClipExtents(x1, y1, x2, y2: PDouble);
function CopyClipRectangleList: PCairoRectangleList; // destroy it !
(* Font/Text functions *)
procedure SelectFontFace(const family: AnsiString; slant: TCairoFontSlant; weight: TCairoFontWeight);
procedure SetFontSize(size: Double);
procedure SetFontMatrix(matrix: TCairoMatrix);
procedure GetFontMatrix(var matrix: TCairoMatrix);
procedure SetFontOptions(options: ICairoFontOptions);
function GetFontOptions: ICairoFontOptions;
procedure SetFontFace(fontFace: ICairoFontFace);
function GetFontFace: ICairoFontFace;
procedure SetScaledFont(scaledFont: ICairoScaledFont);
function GetScaledFont: ICairoScaledFont;
procedure ShowText(utf8: UTF8String);
procedure ShowGlyphs(glyphs: PCairoGlyph; numGlyphs: Integer);
procedure ShowTextGlyphs(utf8: UTF8String; glyphs: PCairoGlyph;
numGlyphs: Integer; clusters: PCairoTextCluster; numClusters: Integer;
clusterFlags: TCairoTextClusterFlags);
procedure TextPath(utf8: UTF8String);
procedure GlyphPath(glyphs: PCairoGlyph; numGlyphs: Integer);
procedure TextExtents(utf8: UTF8String; extent: PCairoTextExtents);
procedure GlyphExtents(glyphs: PCairoGlyph; numGlyphs: Integer; extent: PCairoTextExtents);
procedure FontExtents(extents: PCairoFontExtents);
(* Query functions *)
function GetOperator: TCairoOperator;
function GetSource: ICairoPattern;
function GetTolerance: Double;
function GetAntialias: TCairoAntialias;
function HasCurrentPoint: Boolean;
procedure GetCurrentPoint(x: PDouble; y: PDouble);
function GetFillRule: TCairoFillRule;
function GetLineWidth: Double;
function GetLineCap: TCairoLineCap;
function GetLineJoin: TCairoLineJoin;
function GetMiterLimit: Double;
function GetDashCount: Integer;
procedure GetDash(dashes: PDouble; offset: PDouble);
procedure GetMatrix(var matrix: TCairoMatrix);
function GetTarget: ICairoSurface;
function GetGroupTarget: ICairoSurface;
(* path *)
function CopyPath: PCairoPath; // destroy it !
function CopyPathFlat: PCairoPath; // destroy it !
procedure AppendPath(path: PCairoPath);
(* SVG *)
{$IFDEF CAIRO_HAS_RSVG_FUNCTIONS}
function RenderSVG(svg: IRSVGObject; id: RawByteString = ''): Boolean;
{$ENDIF}
public
constructor Create(surface: ICairoSurface);
destructor Destroy; override;
property Context: PCairo read FContext;
end;
ICairoRegion = interface
['{B9EF38A7-452F-492F-8B3C-CFE69A355DC3}']
function GetUserData: Pointer;
function Copy: ICairoRegion;
function Equal(r: ICairoRegion): Boolean;
function Status: TCairoStatus;
procedure GetExtents(extents: PCairoRectangleInt);
function NumRectangles: Integer;
procedure GetRectangle(nth: Integer; rectangle: PCairoRectangleInt);
function IsEmpty: Boolean;
function ContainsRectangle(const rectangle: PCairoRectangleInt): TCairoRegionOverlap;
function ContainsPoint(x, y: Integer): Boolean;
procedure Translate(dx, dy: Integer);
function Subtract(other: ICairoRegion): TCairoStatus;
function SubtractRectangle(const rectangle: PCairoRectangleInt): TCairoStatus;
function Intersect(other: ICairoRegion): TCairoStatus;
function IntersectRectangle(const rectangle: PCairoRectangleInt): TCairoStatus;
function Union(other: ICairoRegion): TCairoStatus;
function UnionRectangle(const rectangle: PCairoRectangleInt): TCairoStatus;
function XorRegion(other: ICairoRegion): TCairoStatus;
function XorRectangle(const rectangle: PCairoRectangleInt): TCairoStatus;
end;
TCairoRegion = class(TInterfacedObject, ICairoRegion)
private
FRegion: PCairoRegion;
constructor CreateInternal(region: PCairoRegion);
protected
function GetUserData: Pointer;
function Copy: ICairoRegion;
function Equal(r: ICairoRegion): Boolean;
function Status: TCairoStatus;
procedure GetExtents(extents: PCairoRectangleInt);
function NumRectangles: Integer;
procedure GetRectangle(nth: Integer; rectangle: PCairoRectangleInt);
function IsEmpty: Boolean;
function ContainsRectangle(const rectangle: PCairoRectangleInt): TCairoRegionOverlap;
function ContainsPoint(x, y: Integer): Boolean;
procedure Translate(dx, dy: Integer);
function Subtract(other: ICairoRegion): TCairoStatus;
function SubtractRectangle(const rectangle: PCairoRectangleInt): TCairoStatus;
function Intersect(other: ICairoRegion): TCairoStatus;
function IntersectRectangle(const rectangle: PCairoRectangleInt): TCairoStatus;
function Union(other: ICairoRegion): TCairoStatus;
function UnionRectangle(const rectangle: PCairoRectangleInt): TCairoStatus;
function XorRegion(other: ICairoRegion): TCairoStatus;
function XorRectangle(const rectangle: PCairoRectangleInt): TCairoStatus;
public
constructor Create;
constructor CreateRectangle(const rectangle: PCairoRectangleInt);
constructor CreateRectangles(const rects: PCairoRectangleInt; count: Integer);
destructor Destroy; override;
end;
function CairoFormatStrideForWidth(format: TCairoFormat; width: Integer): Integer;
procedure CairoCheck(AStatus: TCairoStatus);
const
aclAliceBlue = $FFF0F8FF;
aclAntiqueWhite = $FFFAEBD7;
aclAqua = $FF00FFFF;
aclAquamarine = $FF7FFFD4;
aclAzure = $FFF0FFFF;
aclBeige = $FFF5F5DC;
aclBisque = $FFFFE4C4;
aclBlack = $FF000000;
aclBlanchedAlmond = $FFFFEBCD;
aclBlue = $FF0000FF;
aclBlueViolet = $FF8A2BE2;
aclBrown = $FFA52A2A;
aclBurlyWood = $FFDEB887;
aclCadetBlue = $FF5F9EA0;
aclChartreuse = $FF7FFF00;
aclChocolate = $FFD2691E;
aclCoral = $FFFF7F50;
aclCornflowerBlue = $FF6495ED;
aclCornsilk = $FFFFF8DC;
aclCrimson = $FFDC143C;
aclCyan = $FF00FFFF;
aclDarkBlue = $FF00008B;
aclDarkCyan = $FF008B8B;
aclDarkGoldenrod = $FFB8860B;
aclDarkGray = $FFA9A9A9;
aclDarkGreen = $FF006400;
aclDarkKhaki = $FFBDB76B;
aclDarkMagenta = $FF8B008B;
aclDarkOliveGreen = $FF556B2F;
aclDarkOrange = $FFFF8C00;
aclDarkOrchid = $FF9932CC;
aclDarkRed = $FF8B0000;
aclDarkSalmon = $FFE9967A;
aclDarkSeaGreen = $FF8FBC8B;
aclDarkSlateBlue = $FF483D8B;
aclDarkSlateGray = $FF2F4F4F;
aclDarkTurquoise = $FF00CED1;
aclDarkViolet = $FF9400D3;
aclDeepPink = $FFFF1493;
aclDeepSkyBlue = $FF00BFFF;
aclDimGray = $FF696969;
aclDodgerBlue = $FF1E90FF;
aclFirebrick = $FFB22222;
aclFloralWhite = $FFFFFAF0;
aclForestGreen = $FF228B22;
aclFuchsia = $FFFF00FF;
aclGainsboro = $FFDCDCDC;
aclGhostWhite = $FFF8F8FF;
aclGold = $FFFFD700;
aclGoldenrod = $FFDAA520;
aclGray = $FF808080;
aclGreen = $FF008000;
aclGreenYellow = $FFADFF2F;
aclHoneydew = $FFF0FFF0;
aclHotPink = $FFFF69B4;
aclIndianRed = $FFCD5C5C;
aclIndigo = $FF4B0082;
aclIvory = $FFFFFFF0;
aclKhaki = $FFF0E68C;
aclLavender = $FFE6E6FA;
aclLavenderBlush = $FFFFF0F5;
aclLawnGreen = $FF7CFC00;
aclLemonChiffon = $FFFFFACD;
aclLightBlue = $FFADD8E6;
aclLightCoral = $FFF08080;
aclLightCyan = $FFE0FFFF;
aclLightGoldenrodYellow = $FFFAFAD2;
aclLightGray = $FFD3D3D3;
aclLightGreen = $FF90EE90;
aclLightPink = $FFFFB6C1;
aclLightSalmon = $FFFFA07A;
aclLightSeaGreen = $FF20B2AA;
aclLightSkyBlue = $FF87CEFA;
aclLightSlateGray = $FF778899;
aclLightSteelBlue = $FFB0C4DE;
aclLightYellow = $FFFFFFE0;
aclLime = $FF00FF00;
aclLimeGreen = $FF32CD32;
aclLinen = $FFFAF0E6;
aclMagenta = $FFFF00FF;
aclMaroon = $FF800000;
aclMediumAquamarine = $FF66CDAA;
aclMediumBlue = $FF0000CD;
aclMediumOrchid = $FFBA55D3;
aclMediumPurple = $FF9370DB;
aclMediumSeaGreen = $FF3CB371;
aclMediumSlateBlue = $FF7B68EE;
aclMediumSpringGreen = $FF00FA9A;
aclMediumTurquoise = $FF48D1CC;
aclMediumVioletRed = $FFC71585;
aclMidnightBlue = $FF191970;
aclMintCream = $FFF5FFFA;
aclMistyRose = $FFFFE4E1;
aclMoccasin = $FFFFE4B5;
aclNavajoWhite = $FFFFDEAD;
aclNavy = $FF000080;
aclOldLace = $FFFDF5E6;
aclOlive = $FF808000;
aclOliveDrab = $FF6B8E23;
aclOrange = $FFFFA500;
aclOrangeRed = $FFFF4500;
aclOrchid = $FFDA70D6;
aclPaleGoldenrod = $FFEEE8AA;
aclPaleGreen = $FF98FB98;
aclPaleTurquoise = $FFAFEEEE;
aclPaleVioletRed = $FFDB7093;
aclPapayaWhip = $FFFFEFD5;
aclPeachPuff = $FFFFDAB9;
aclPeru = $FFCD853F;
aclPink = $FFFFC0CB;
aclPlum = $FFDDA0DD;
aclPowderBlue = $FFB0E0E6;
aclPurple = $FF800080;
aclRed = $FFFF0000;
aclRosyBrown = $FFBC8F8F;
aclRoyalBlue = $FF4169E1;
aclSaddleBrown = $FF8B4513;
aclSalmon = $FFFA8072;
aclSandyBrown = $FFF4A460;
aclSeaGreen = $FF2E8B57;
aclSeaShell = $FFFFF5EE;
aclSienna = $FFA0522D;
aclSilver = $FFC0C0C0;
aclSkyBlue = $FF87CEEB;
aclSlateBlue = $FF6A5ACD;
aclSlateGray = $FF708090;
aclSnow = $FFFFFAFA;
aclSpringGreen = $FF00FF7F;
aclSteelBlue = $FF4682B4;
aclTan = $FFD2B48C;
aclTeal = $FF008080;
aclThistle = $FFD8BFD8;
aclTomato = $FFFF6347;
aclTransparent = $00FFFFFF;
aclTurquoise = $FF40E0D0;
aclViolet = $FFEE82EE;
aclWheat = $FFF5DEB3;
aclWhite = $FFFFFFFF;
aclWhiteSmoke = $FFF5F5F5;
aclYellow = $FFFFFF00;
aclYellowGreen = $FF9ACD32;
implementation
{$IFDEF CAIRO_HAS_RSVG_FUNCTIONS}
uses rsvglib, math;
{$ENDIF}
procedure CairoCheck(AStatus: TCairoStatus);
begin
if AStatus <> CAIRO_STATUS_SUCCESS then
raise ECairoException.Create(AStatus);
end;
function WriteStream(stream: TStream; data: Pointer; length: Cardinal): TCairoStatus; cdecl;
begin
if stream.Write(data^, length) = Integer(length) then
Result := CAIRO_STATUS_SUCCESS else
Result := CAIRO_STATUS_WRITE_ERROR;
end;
function ReadStream(stream: TStream; data: Pointer; length: Cardinal): TCairoStatus; cdecl;
begin
if stream.Read(data^, length) = Integer(length) then
Result := CAIRO_STATUS_SUCCESS else
Result := CAIRO_STATUS_READ_ERROR;
end;
function CairoFormatStrideForWidth(format: TCairoFormat; width: Integer): Integer;
begin
Result := cairo_format_stride_for_width(format, width)
end;
{ TWin32Surface }
{$ifdef CAIRO_HAS_WIN32_SURFACE}
constructor TWin32Surface.CreateHDC(hdc: HDC);
begin
inherited CreateInternal(cairo_win32_surface_create(hdc));
end;
{$endif}
{$ifdef CAIRO_HAS_WIN32_SURFACE}
constructor TWin32Surface.CreatePrinting(hdc: HDC);
begin
inherited CreateInternal(cairo_win32_printing_surface_create(hdc));
end;
{$endif}
{$ifdef CAIRO_HAS_WIN32_SURFACE}
constructor TWin32Surface.CreateWithDDB(hdc: HDC; format: TCairoFormat; width,
height: Integer);
begin
inherited CreateInternal(cairo_win32_surface_create_with_ddb(hdc, format, width, height));
end;
{$endif}
{$ifdef CAIRO_HAS_WIN32_SURFACE}
constructor TWin32Surface.CreateWithDIB(format: TCairoFormat; width,
height: Integer);
begin
inherited CreateInternal(cairo_win32_surface_create_with_dib(format, width, height));
end;
{$endif}
{$ifdef CAIRO_HAS_WIN32_SURFACE}
function TWin32Surface.GetDC: HDC;
begin
Result := cairo_win32_surface_get_dc(FSurface);
end;
{$endif}
{$ifdef CAIRO_HAS_WIN32_SURFACE}
function TWin32Surface.GetImage: ICairoSurface;
begin
Result := init(cairo_win32_surface_get_image(FSurface))
end;
{$endif}
{ TCairoSurface }
procedure TCairoSurface.CopyPage;
begin
cairo_surface_copy_page(FSurface);
end;
function TCairoSurface.CreateForRectangle(x, y, width,
height: Double): ICairoSurface;
begin
Result := init(cairo_surface_create_for_rectangle(FSurface, x, y, width, height))
end;
constructor TCairoSurface.CreateInternal(surface: PCairoSurface);
begin
FSurface := surface;
cairo_surface_set_user_data(FSurface, nil, Self, nil);
end;
constructor TCairoSurface.CreateRecording(content: TCairoContent;
const extents: PCairoRectangle);
begin
CreateInternal(cairo_recording_surface_create(content, extents));
end;
function TCairoSurface.CreateSimilar(content: TCairoContent; width,
height: Integer): ICairoSurface;
begin
Result := init(cairo_surface_create_similar(FSurface, content, width, height));
end;
destructor TCairoSurface.Destroy;
begin
cairo_surface_set_user_data(FSurface, nil, nil, nil);
cairo_surface_destroy(FSurface);
inherited;
end;
procedure TCairoSurface.Finish;
begin
cairo_surface_finish(FSurface);
end;
procedure TCairoSurface.Flush;
begin
cairo_surface_flush(FSurface);
end;
function TCairoSurface.GetContent: TCairoContent;
begin
Result := cairo_surface_get_content(FSurface)
end;
function TCairoSurface.GetDevice: ICairoDevice;
begin
Result := TCairoDevice.init(cairo_surface_get_device(FSurface));
end;
procedure TCairoSurface.GetDeviceOffset(var xOffset, yOffset: Double);
begin
cairo_surface_get_device_offset(FSurface, @xOffset, @yOffset);
end;
procedure TCairoSurface.GetFallbackResolution(var xPixelsPerInch,
yPixelsPerInch: Double);
begin
cairo_surface_get_fallback_resolution(FSurface, @xPixelsPerInch, @yPixelsPerInch);
end;
procedure TCairoSurface.GetFontOptions(options: ICairoFontOptions);
begin
cairo_surface_get_font_options(FSurface, TCairoFontOptions(options.GetUserData).FFontOptions);
end;
procedure TCairoSurface.GetMimeData(const mimeType: PAnsiChar;
out data: Pointer; out length: Cardinal);
begin
cairo_surface_get_mime_data(FSurface, mimeType, data, length);
end;
function TCairoSurface.GetType: TCairoSurfaceType;
begin
Result := cairo_surface_get_type(FSurface);
end;
function TCairoSurface.GetUserData(key: Pointer): Pointer;
begin
Result := cairo_surface_get_user_data(FSurface, key);
end;
function TCairoSurface.HasShowTextGlyphs: Boolean;
begin
Result := cairo_surface_has_show_text_glyphs(FSurface) <> 0;
end;
class function TCairoSurface.init(surface: PCairoSurface): TCairoSurface;
begin
Result := TCairoSurface(cairo_surface_get_user_data(surface, nil));
if Result = nil then
begin
cairo_surface_reference(surface);
Result := TCairoSurface.CreateInternal(surface);
end;
end;
procedure TCairoSurface.MarkDirty;
begin
cairo_surface_mark_dirty(FSurface);
end;
procedure TCairoSurface.MarkDirtyRectangle(x, y, width, height: Integer);
begin
cairo_surface_mark_dirty_rectangle(FSurface, x, y, width, height);
end;
procedure TCairoSurface.SetDeviceOffset(xOffset, yOffset: double);
begin
cairo_surface_set_device_offset(FSurface, xOffset, yOffset);
end;
procedure TCairoSurface.SetFallbackResolution(xPixelsPerInch,
yPixelsPerInch: double);
begin
cairo_surface_set_fallback_resolution(FSurface, xPixelsPerInch, yPixelsPerInch);
end;
function TCairoSurface.SetMimeData(const mimeType: PAnsiChar;
const data: Pointer; length: Cardinal; destroy: TCairoDestroyFunc;
closure: Pointer): TCairoStatus;
begin
Result := cairo_surface_set_mime_data(FSurface, mimeType, data, length, destroy, closure)
end;
procedure TCairoSurface.SetUserData(key, userData: Pointer;
destroyFunc: TCairoDestroyFunc);
begin
Assert(key <> nil, 'null key is reserved');
CairoCheck(cairo_surface_set_user_data(FSurface, key, userData, destroyFunc));
end;
procedure TCairoSurface.ShowPage;
begin
cairo_surface_show_page(FSurface);
end;
function TCairoSurface.GetStatus: TCairoStatus;
begin
result := cairo_surface_status(FSurface)
end;
{$ifdef CAIRO_HAS_PNG_FUNCTIONS}
procedure TCairoSurface.WriteToPNGStream(stream: TStream);
begin
CairoCheck(cairo_surface_write_to_png_stream(FSurface, TCairoWriteFunc(@writestream), stream));
end;
{$endif}
{$ifdef CAIRO_HAS_PNG_FUNCTIONS}
procedure TCairoSurface.WriteToPNG(const filename: string);
var
stream: TFileStream;
begin
stream := TFileStream.Create(filename, fmCreate, fmShareExclusive);
try
WriteToPNGStream(stream);
finally
stream.Free;
end;
end;
{$endif}
{ ECairoException }
constructor ECairoException.Create(AStatus: TCairoStatus);
begin
FStatus := AStatus;
inherited Create(string(cairo_status_to_string(AStatus)));
end;
{ TCairoImageSurface }
constructor TImageSurface.Create(format: TCairoFormat; width, height: Integer);
begin
inherited CreateInternal(cairo_image_surface_create(format, width, height));
end;
constructor TImageSurface.CreateForData(data: Pointer; format: TCairoFormat;
width, height, stride: Integer);
begin
inherited CreateInternal(cairo_image_surface_create_for_data(data, format, width, height, stride));
end;
{$ifdef CAIRO_HAS_PNG_FUNCTIONS}
constructor TImageSurface.CreateFromPNG(const filename: string);
var
stream: TFileStream;
begin
stream := TFileStream.Create(filename, fmOpenRead, fmShareDenyWrite);
try
CreateFromPNG(stream);
finally
stream.Free;
end;
end;
{$endif}
{$ifdef CAIRO_HAS_PNG_FUNCTIONS}
constructor TImageSurface.CreateFromPNG(stream: TStream);
begin
inherited CreateInternal(cairo_image_surface_create_from_png_stream(TCairoReadFunc(@ReadStream), stream));
end;
{$endif}
{$ifdef CAIRO_HAS_RSVG_FUNCTIONS}
constructor TImageSurface.CreateFromSVG(const filename: string; format: TCairoFormat; scale: double);
var
stream: TFileStream;
begin
stream := TFileStream.Create(filename, fmOpenRead, fmShareDenyWrite);
try
CreateFromSVG(stream, format, scale);
finally
stream.Free;
end;
end;
constructor TImageSurface.CreateFromSVG(stream: TStream; format: TCairoFormat; scale: double);
var
handle: PRsvgHandle;
dim: TRsvgDimensionData;
newctx: PCairo;
buffer: Pointer;
begin
if stream is TCustomMemoryStream then
handle := rsvg_handle_new_from_data(TCustomMemoryStream(stream).Memory, stream.Size, nil) else
begin
GetMem(buffer, stream.Size);
try
stream.Read(buffer^, stream.Size);
handle := rsvg_handle_new_from_data(buffer, stream.Size, nil);
finally
FreeMem(buffer);
end;
end;
try
Assert(handle <> nil);
rsvg_handle_get_dimensions(handle, @dim);
inherited CreateInternal(cairo_image_surface_create(format, round(dim.width * scale), round(dim.height * scale)));
newctx := cairo_create(FSurface);
try
cairo_scale(newctx, scale, scale);
rsvg_handle_render_cairo(handle, newctx);
finally
cairo_destroy(newctx);
end;
finally
rsvg_handle_free(handle);
end;
end;
{$endif}
function TImageSurface.GetData: Pointer;
begin
Result := cairo_image_surface_get_data(FSurface);
end;
function TImageSurface.GetFormat: TCairoFormat;
begin
Result := cairo_image_surface_get_format(FSurface);
end;
function TImageSurface.GetHeight: Integer;
begin
Result := cairo_image_surface_get_height(FSurface);
end;
function TImageSurface.GetStride: Integer;
begin
Result := cairo_image_surface_get_stride(FSurface);
end;
function TImageSurface.GetWidth: Integer;
begin
Result := cairo_image_surface_get_width(FSurface);
end;
{ TSVGSurface }
{$ifdef CAIRO_HAS_SVG_SURFACE}
constructor TSVGSurface.Create(stream: TStream; widthInPoints, heightInPoints: Double; owned: boolean);
begin
inherited CreateInternal(cairo_svg_surface_create_for_stream(TCairoWriteFunc(@WriteStream), stream, widthInPoints, heightInPoints));
if owned then
FStream := stream else
FStream := nil;
end;
{$endif}
{$ifdef CAIRO_HAS_SVG_SURFACE}
constructor TSVGSurface.Create(filename: TFileName; widthInPoints, heightInPoints: Double);
begin
Create(TFileStream.Create(filename, fmCreate, fmShareExclusive), widthInPoints, heightInPoints, True);
end;
{$endif}
{$ifdef CAIRO_HAS_SVG_SURFACE}
destructor TSVGSurface.Destroy;
begin
inherited;
if FStream <> nil then
FStream.Free;
end;
{$endif}
{$ifdef CAIRO_HAS_SVG_SURFACE}
procedure TSVGSurface.RestrictToVersion(version: TCairoSVGVersion);
begin
cairo_svg_surface_restrict_to_version(FSurface, version);
end;
{$endif}
{ TPDFSurface }
{$ifdef CAIRO_HAS_PDF_SURFACE}
constructor TPDFSurface.Create(stream: TStream; widthInPoints,
heightInPoints: Double; owned: boolean);
begin
inherited CreateInternal(cairo_pdf_surface_create_for_stream(TCairoWriteFunc(@WriteStream), stream, widthInPoints, heightInPoints));
if owned then
FStream := stream else
FStream := nil;
end;
{$endif}
{$ifdef CAIRO_HAS_PDF_SURFACE}
constructor TPDFSurface.Create(filename: TFileName; widthInPoints,
heightInPoints: Double);
begin
Create(TFileStream.Create(filename, fmCreate, fmShareExclusive), widthInPoints, heightInPoints, True);
end;
{$endif}
{$ifdef CAIRO_HAS_PDF_SURFACE}
destructor TPDFSurface.Destroy;
begin
inherited;
if FStream <> nil then
FStream.Free;
end;
{$endif}
{$ifdef CAIRO_HAS_PDF_SURFACE}
procedure TPDFSurface.SetSize(widthInPoints, heightInPoints: Double);
begin
cairo_pdf_surface_set_size(FSurface, widthInPoints, heightInPoints);
end;
{$endif}
{$ifdef CAIRO_HAS_PDF_SURFACE}
procedure TPDFSurface.RestrictToVersion(version: TCairoPdfVersion);
begin
cairo_pdf_surface_restrict_to_version(FSurface, version);
end;
{$endif}
{ TPostScriptSurface }
{$ifdef CAIRO_HAS_PS_SURFACE}
constructor TPostScriptSurface.Create(stream: TStream; widthInPoints,
heightInPoints: Double; owned: boolean);
begin
inherited CreateInternal(cairo_ps_surface_create_for_stream(TCairoWriteFunc(@WriteStream), stream, widthInPoints, heightInPoints));
if owned then
FStream := stream else
FStream := nil;
end;
{$endif}
{$ifdef CAIRO_HAS_PS_SURFACE}
constructor TPostScriptSurface.Create(const filename: string; widthInPoints,
heightInPoints: Double);
begin
Create(TFileStream.Create(filename, fmCreate, fmShareExclusive), widthInPoints, heightInPoints, True);
end;
{$endif}
{$ifdef CAIRO_HAS_PS_SURFACE}
destructor TPostScriptSurface.Destroy;
begin
inherited;
if FStream <> nil then
FStream.Free;
end;
{$endif}
{$ifdef CAIRO_HAS_PS_SURFACE}
procedure TPostScriptSurface.DscBeginPageSetup;
begin
cairo_ps_surface_dsc_begin_page_setup(FSurface);
end;
{$endif}
{$ifdef CAIRO_HAS_PS_SURFACE}
procedure TPostScriptSurface.DscBeginSetup;
begin
cairo_ps_surface_dsc_begin_setup(FSurface);
end;
{$endif}
{$ifdef CAIRO_HAS_PS_SURFACE}
procedure TPostScriptSurface.DscComment(const comment: AnsiString);
begin
cairo_ps_surface_dsc_comment(FSurface, PAnsiChar(comment));
end;
{$endif}
{$ifdef CAIRO_HAS_PS_SURFACE}
function TPostScriptSurface.GetEPS: Boolean;
begin
Result := cairo_ps_surface_get_eps(FSurface) <> 0;
end;
{$endif}
{$ifdef CAIRO_HAS_PS_SURFACE}
procedure TPostScriptSurface.RestrictToLevel(level: TCairoPSLevel);
begin
cairo_ps_surface_restrict_to_level(FSurface, level);
end;
{$endif}
{$ifdef CAIRO_HAS_PS_SURFACE}
procedure TPostScriptSurface.SetEPS(eps: Boolean);
begin
cairo_ps_surface_set_eps(FSurface, ord(eps));
end;
{$endif}
{$ifdef CAIRO_HAS_PS_SURFACE}
procedure TPostScriptSurface.SetSize(widthInPoints, heightInPoints: Double);
begin
cairo_ps_surface_set_size(FSurface, widthInPoints, heightInPoints);
end;
{$endif}
{ TCairoContext }
procedure TCairoContext.AppendPath(path: PCairoPath);
begin
cairo_append_path(FContext, path)
end;
{$IFDEF CAIRO_HAS_RSVG_FUNCTIONS}
function TCairoContext.RenderSVG(svg: IRSVGObject; id: RawByteString): Boolean;
begin
if id <> '' then
Result := rsvg_handle_render_cairo_sub(svg.Handle, FContext, PAnsiChar(id)) else
Result := rsvg_handle_render_cairo(svg.Handle, FContext);
end;
{$ENDIF}
procedure TCairoContext.Arc(xc, yc, radius, angle1, angle2: Double);
begin
cairo_arc(FContext, xc, yc, radius, angle1, angle2);
end;
procedure TCairoContext.ArcNegative(xc, yc, radius, angle1, angle2: Double);
begin
cairo_arc_negative(FContext, xc, yc, radius, angle1, angle2);
end;
procedure TCairoContext.Clip;
begin
cairo_clip(FContext);
end;
procedure TCairoContext.ClipExtents(x1, y1, x2, y2: PDouble);
begin
cairo_clip_extents(FContext, x1, y1, x2, y2);
end;
procedure TCairoContext.ClipPreserve;
begin
cairo_clip_preserve(FContext);
end;
procedure TCairoContext.ClosePath;
begin
cairo_close_path(FContext);
end;
function TCairoContext.CopyClipRectangleList: PCairoRectangleList;
begin
Result := cairo_copy_clip_rectangle_list(FContext);
end;
procedure TCairoContext.CopyPage;
begin
cairo_copy_page(FContext);
end;
function TCairoContext.CopyPath: PCairoPath;
begin
Result := cairo_copy_path(FContext);
end;
function TCairoContext.CopyPathFlat: PCairoPath;
begin
Result := cairo_copy_path_flat(FContext);
end;
constructor TCairoContext.Create(surface: ICairoSurface);
begin
CreateInternal(cairo_create(TCairoSurface(surface.GetUserData(nil)).FSurface));
end;
constructor TCairoContext.CreateInternal(context: PCairo);
begin
FContext := context;
cairo_set_user_data(FContext, nil, Self, nil);
end;
procedure TCairoContext.CurveTo(x1, y1, x2, y2, x3, y3: Double);
begin
cairo_curve_to(FContext, x1, y1, x2, y2, x3, y3);
end;
destructor TCairoContext.Destroy;
begin
cairo_set_user_data(FContext, nil, nil, nil);
cairo_destroy(FContext);
inherited;
end;
procedure TCairoContext.DeviceToUser(var x, y: Double);
begin
cairo_device_to_user(FContext, @x, @y);
end;
procedure TCairoContext.DeviceToUserDistance(var dx, dy: Double);
begin
cairo_device_to_user_distance(FContext, @dx, @dy);
end;
procedure TCairoContext.Fill;
begin
cairo_fill(FContext);
end;
procedure TCairoContext.FillExtents(x1, y1, x2, y2: PDouble);
begin
cairo_fill_extents(FContext, x1, y1, x2, y2);
end;
procedure TCairoContext.FillPreserve;
begin
cairo_fill_preserve(FContext);
end;
procedure TCairoContext.FontExtents(extents: PCairoFontExtents);
begin
cairo_font_extents(FContext, extents);
end;
function TCairoContext.GetAntialias: TCairoAntialias;
begin
Result := cairo_get_antialias(FContext);
end;
procedure TCairoContext.GetCurrentPoint(x, y: PDouble);
begin
cairo_get_current_point(FContext, x, y);
end;
procedure TCairoContext.GetDash(dashes, offset: PDouble);
begin
cairo_get_dash(FContext, dashes, offset);
end;
function TCairoContext.GetDashCount: Integer;
begin
Result := cairo_get_dash_count(FContext);
end;
function TCairoContext.GetFillRule: TCairoFillRule;
begin
Result := cairo_get_fill_rule(FContext);
end;
function TCairoContext.GetFontFace: ICairoFontFace;
begin
Result := TCairoFontFace.init(cairo_get_font_face(FContext));
end;
procedure TCairoContext.GetFontMatrix(var matrix: TCairoMatrix);
begin
cairo_get_font_matrix(FContext, @matrix);
end;
function TCairoContext.GetFontOptions: ICairoFontOptions;
var
fontoptions: PCairoFontOptions;
begin
fontoptions := cairo_font_options_create;
cairo_get_font_options(FContext, fontoptions);
Result := TCairoFontOptions.CreateInternal(fontoptions);
end;
function TCairoContext.GetGroupTarget: ICairoSurface;
begin
Result := TcairoSurface.init(cairo_get_group_target(FContext));
end;
function TCairoContext.GetLineCap: TCairoLineCap;
begin
Result := cairo_get_line_cap(FContext);
end;
function TCairoContext.GetLineJoin: TCairoLineJoin;
begin
Result := cairo_get_line_join(FContext);
end;
function TCairoContext.GetLineWidth: Double;
begin
Result := cairo_get_line_width(FContext);
end;
procedure TCairoContext.GetMatrix(var matrix: TCairoMatrix);
begin
cairo_get_matrix(FContext, @matrix);
end;
function TCairoContext.GetMiterLimit: Double;
begin
Result := cairo_get_miter_limit(FContext);
end;
function TCairoContext.GetOperator: TCairoOperator;
begin
Result := cairo_get_operator(FContext)
end;
function TCairoContext.GetScaledFont: ICairoScaledFont;
begin
Result := TCairoScaledFont.init(cairo_get_scaled_font(FContext))
end;
function TCairoContext.GetSource: ICairoPattern;
begin
Result := TCairoPattern.init(cairo_get_source(FContext));
end;
function TCairoContext.GetStatus: TCairoStatus;
begin
Result := cairo_status(FContext);
end;
function TCairoContext.GetTarget: ICairoSurface;
begin
Result := TCairoSurface.init(cairo_get_target(FContext))
end;
function TCairoContext.GetTolerance: Double;
begin
Result := cairo_get_tolerance(FContext);
end;
function TCairoContext.GetUserData(key: Pointer): Pointer;
begin
Result := cairo_get_user_data(FContext, key);
end;
procedure TCairoContext.GlyphExtents(glyphs: PCairoGlyph;
numGlyphs: Integer; extent: PCairoTextExtents);
begin
cairo_glyph_extents(FContext, glyphs, numGlyphs, extent);
end;
procedure TCairoContext.GlyphPath(glyphs: PCairoGlyph;
numGlyphs: Integer);
begin
cairo_glyph_path(FContext, glyphs, numGlyphs);
end;
function TCairoContext.HasCurrentPoint: Boolean;
begin
Result := cairo_has_current_point(FContext) <> 0;
end;
procedure TCairoContext.IdentityMatrix;
begin
cairo_identity_matrix(FContext);
end;
function TCairoContext.InClip(x, y: Double): Boolean;
begin
Result := cairo_in_clip(FContext, x, y) <> 0;
end;
function TCairoContext.InFill(x, y: Double): Boolean;
begin
Result := cairo_in_fill(FContext, x, y) <> 0;
end;
//class function TCairoContext.init(context: PCairo): TCairoContext;
//begin
// Result := cairo_get_user_data(context, nil);
// if Result = nil then
// Result := TCairoContext.CreateInternal(context);
//end;
function TCairoContext.InStroke(x, y: Double): Boolean;
begin
Result := cairo_in_stroke(FContext, x, y) <> 0;
end;
procedure TCairoContext.LineTo(x, y: Double);
begin
cairo_line_to(FContext, x, y);
end;
procedure TCairoContext.Mask(pattern: ICairoPattern);
begin
cairo_mask(FContext, TCairoPattern(pattern.GetUserData(nil)).FPattern);
end;
procedure TCairoContext.MaskSurface(surface: ICairoSurface; surfaceX,
surfaceY: Double);
begin
cairo_mask_surface(FContext, TCairoSurface(surface.GetUserData(nil)).FSurface, surfaceX, surfaceY);
end;
procedure TCairoContext.MoveTo(x, y: Double);
begin
cairo_move_to(FContext, x, y);
end;
procedure TCairoContext.NewPath;
begin
cairo_new_path(FContext);
end;
procedure TCairoContext.NewSubPath;
begin
cairo_new_sub_path(FContext);
end;
procedure TCairoContext.Paint;
begin
cairo_paint(FContext);
end;
procedure TCairoContext.PaintWithAlpha(alpha: Double);
begin
cairo_paint_with_alpha(FContext, alpha);
end;
procedure TCairoContext.PathExtents(x1, y1, x2, y2: PDouble);
begin
cairo_path_extents(FContext, x1, y1, x2, y2);
end;
function TCairoContext.PopGroup: ICairoPattern;
begin
Result := TCairoPattern.init(cairo_pop_group(FContext));
end;
procedure TCairoContext.PopGroupToSource;
begin
cairo_pop_group_to_source(FContext)
end;
procedure TCairoContext.PushGroup;
begin
cairo_push_group(FContext);
end;
procedure TCairoContext.PushGroupWithContent(content: TCairoContent);
begin
cairo_push_group_with_content(FContext, content);
end;
procedure TCairoContext.Rectangle(x, y, width, height: Double);
begin
cairo_rectangle(FContext, x, y, width, height);
end;
procedure TCairoContext.RelCurveTo(dx1, dy1, dx2, dy2, dx3, dy3: Double);
begin
cairo_rel_curve_to(FContext, dx1, dy1, dx2, dy2, dx3, dy3);
end;
procedure TCairoContext.RelLineTo(dx, dy: Double);
begin
cairo_rel_line_to(FContext, dx, dy);
end;
procedure TCairoContext.RelMoveTo(dx, dy: Double);
begin
cairo_rel_move_to(FContext, dx, dy);
end;
procedure TCairoContext.ResetClip;
begin
cairo_reset_clip(FContext);
end;
procedure TCairoContext.Restore;
begin
cairo_restore(FContext);
end;
procedure TCairoContext.Rotate(angle: Double);
begin
cairo_rotate(FContext, angle);
end;
procedure TCairoContext.Save;
begin
cairo_save(FContext);
end;
procedure TCairoContext.Scale(sx, sy: Double);
begin
cairo_scale(FContext, sx, sy);
end;
procedure TCairoContext.SelectFontFace(const family: AnsiString;
slant: TCairoFontSlant; weight: TCairoFontWeight);
begin
cairo_select_font_face(FContext, PAnsiChar(family), slant, weight);
end;
procedure TCairoContext.SetAntialias(antialias: TCairoAntialias);
begin
cairo_set_antialias(FContext, antialias);
end;
procedure TCairoContext.SetDash(dashes: PDouble; numDashes: Integer;
offset: Double);
begin
cairo_set_dash(FContext, dashes, numDashes, offset);
end;
procedure TCairoContext.SetFillRule(fillRule: TCairoFillRule);
begin
cairo_set_fill_rule(FContext, fillRule);
end;
procedure TCairoContext.SetFontFace(fontFace: ICairoFontFace);
begin
cairo_set_font_face(FContext, TCairoFontFace(fontface.GetUserData(nil)).FFontFace);
end;
procedure TCairoContext.SetFontMatrix(matrix: TCairoMatrix);
begin
cairo_set_font_matrix(FContext, @matrix);
end;
procedure TCairoContext.SetFontOptions(options: ICairoFontOptions);
begin
cairo_set_font_options(FContext, TCairoFontOptions(options.GetUserData).FFontOptions);
end;
procedure TCairoContext.SetFontSize(size: Double);
begin
cairo_set_font_size(FContext, size)
end;
procedure TCairoContext.SetLineCap(lineCap: TCairoLineCap);
begin
cairo_set_line_cap(FContext, lineCap);
end;
procedure TCairoContext.SetLineJoin(lineJoin: TCairoLineJoin);
begin
cairo_set_line_join(FContext, lineJoin);
end;
procedure TCairoContext.SetLineWidth(width: Double);
begin
cairo_set_line_width(FContext, width);
end;
procedure TCairoContext.SetMatrix(matrix: TCairoMatrix);
begin
cairo_set_matrix(FContext, @matrix);
end;
procedure TCairoContext.SetMiterLimit(limit: Double);
begin
cairo_set_miter_limit(FContext, limit);
end;
procedure TCairoContext.SetOperator(op: TCairoOperator);
begin
cairo_set_operator(FContext, op);
end;
procedure TCairoContext.SetScaledFont(scaledFont: ICairoScaledFont);
begin
cairo_set_scaled_font(FContext, TCairoScaledFont(scaledFont.GetUserData(nil)).FScaledFont);
end;
procedure TCairoContext.SetSource(source: ICairoPattern);
begin
cairo_set_source(FContext, TCairoPattern(source.GetUserData(nil)).FPattern);
end;
procedure TCairoContext.SetSourceColor(color: Cardinal);
var
alpha, red, green, blue: byte;
begin
alpha := (color shr 24) and $FF;
red := (color shr 16) and $FF;
green := (color shr 8) and $FF;
blue := color and $FF;
if alpha = $ff then
SetSourceRGB(red/255, green/255, blue/255) else
SetSourceRGBA(red/255, green/255, blue/255, alpha/255);
end;
procedure TCairoContext.SetSourceRGB(red, green, blue: Double);
begin
cairo_set_source_rgb(FContext, red, green, blue);
end;
procedure TCairoContext.SetSourceRGBA(red, green, blue, alpha: Double);
begin
cairo_set_source_rgba(FContext, red, green, blue, alpha);
end;
procedure TCairoContext.SetSourceSurface(surface: ICairoSurface; x, y: Double);
begin
cairo_set_source_surface(FContext, TCairoSurface(surface.GetUserData(nil)).FSurface, x, y);
end;
procedure TCairoContext.SetTolerance(tolerance: Double);
begin
cairo_set_tolerance(FContext, tolerance);
end;
procedure TCairoContext.SetUserData(key, userData: Pointer;
destroyFunc: TCairoDestroyFunc);
begin
Assert(key <> nil, 'null key is reserved');
CairoCheck(cairo_set_user_data(FContext, key, userData, destroyFunc));
end;
procedure TCairoContext.ShowGlyphs(glyphs: PCairoGlyph; numGlyphs: Integer);
begin
cairo_show_glyphs(FContext, glyphs, numGlyphs);
end;
procedure TCairoContext.ShowPage;
begin
cairo_show_page(FContext);
end;
procedure TCairoContext.ShowText(utf8: UTF8String);
begin
cairo_show_text(FContext, PAnsiChar(utf8));
end;
procedure TCairoContext.ShowTextGlyphs(utf8: UTF8String;
glyphs: PCairoGlyph; numGlyphs: Integer; clusters: PCairoTextCluster;
numClusters: Integer; clusterFlags: TCairoTextClusterFlags);
begin
cairo_show_text_glyphs(FContext, PAnsiChar(utf8), Length(utf8), glyphs,
numGlyphs, clusters, numClusters, clusterFlags);
end;
procedure TCairoContext.Stroke;
begin
cairo_stroke(FContext);
end;
procedure TCairoContext.StrokeExtents(x1, y1, x2, y2: PDouble);
begin
cairo_stroke_extents(FContext, x1, y1, x2, y2);
end;
procedure TCairoContext.StrokePreserve;
begin
cairo_stroke_preserve(FContext);
end;
procedure TCairoContext.TextExtents(utf8: UTF8String;
extent: PCairoTextExtents);
begin
cairo_text_extents(FContext, PAnsiChar(utf8), extent);
end;
procedure TCairoContext.TextPath(utf8: UTF8String);
begin
cairo_text_path(FContext, PAnsiChar(utf8));
end;
procedure TCairoContext.Transform(matrix: TCairoMatrix);
begin
cairo_transform(FContext, @matrix)
end;
procedure TCairoContext.Translate(tx, ty: Double);
begin
cairo_translate(FContext, tx, ty);
end;
procedure TCairoContext.UserToDevice(var x, y: Double);
begin
cairo_user_to_device(FContext, @x, @y);
end;
procedure TCairoContext.UserToDeviceDistance(var dx, dy: Double);
begin
cairo_user_to_device_distance(FContext, @dx, @dy);
end;
{ TCairoFontOptions }
function TCairoFontOptions.Copy: ICairoFontOptions;
begin
Result := TCairoFontOptions.CreateInternal(cairo_font_options_copy(FFontOptions));
end;
constructor TCairoFontOptions.Create;
begin
CreateInternal(cairo_font_options_create);
end;
constructor TCairoFontOptions.CreateInternal(options: PCairoFontOptions);
begin
FFontOptions := options;
end;
destructor TCairoFontOptions.Destroy;
begin
cairo_font_options_destroy(FFontOptions);
inherited;
end;
function TCairoFontOptions.Equal(other: ICairoFontOptions): Boolean;
begin
Result := cairo_font_options_equal(FFontOptions, TCairoFontOptions(other.GetUserData).FFontOptions) <> 0;
end;
function TCairoFontOptions.GetAntialias: TCairoAntialias;
begin
Result := cairo_font_options_get_antialias(FFontOptions);
end;
function TCairoFontOptions.GetHash: Cardinal;
begin
Result := cairo_font_options_hash(FFontOptions);
end;
function TCairoFontOptions.GetHintMetrics: TCairoHintMetrics;
begin
Result := cairo_font_options_get_hint_metrics(FFontOptions);
end;
function TCairoFontOptions.GetHintStyle: TCairoHintStyle;
begin
Result := cairo_font_options_get_hint_style(FFontOptions);
end;
function TCairoFontOptions.GetStatus: TCairoStatus;
begin
Result := cairo_font_options_status(FFontOptions);
end;
function TCairoFontOptions.GetSubpixelOrder: TCairoSubpixelOrder;
begin
Result := cairo_font_options_get_subpixel_order(FFontOptions);
end;
function TCairoFontOptions.GetUserData: Pointer;
begin
Result := Self;
end;
procedure TCairoFontOptions.Merge(other: ICairoFontOptions);
begin
cairo_font_options_merge(FFontOptions, TCairoFontOptions(other.GetUserData).FFontOptions);
end;
procedure TCairoFontOptions.SetAntialias(antialias: TCairoAntialias);
begin
cairo_font_options_set_antialias(FFontOptions, antialias);
end;
procedure TCairoFontOptions.SetHintMetrics(hintMetrics: TCairoHintMetrics);
begin
cairo_font_options_set_hint_metrics(FFontOptions, hintMetrics);
end;
procedure TCairoFontOptions.SetHintStyle(hintStyle: TCairoHintStyle);
begin
cairo_font_options_set_hint_style(FFontOptions, hintStyle);
end;
procedure TCairoFontOptions.SetSubpixelOrder(
subpixelOrder: TCairoSubpixelOrder);
begin
cairo_font_options_set_subpixel_order(FFontOptions, subpixelOrder);
end;
{ TCairoPattern }
procedure TCairoPattern.AddColorStop(offset: Double; color: Cardinal);
var
r, g, b, a: Byte;
begin
a := color shr 24;
r := color shr 16;
g := color shr 8;
b := color;
if a = $ff then
cairo_pattern_add_color_stop_rgb(FPattern, offset, r/255, g/255, b/255);
cairo_pattern_add_color_stop_rgba(FPattern, offset, r/255, g/255, b/255, a/255);
end;
procedure TCairoPattern.AddColorStopRGB(offset, red, green, blue: Double);
begin
cairo_pattern_add_color_stop_rgb(FPattern, offset, red, green, blue);
end;
procedure TCairoPattern.AddColorStopRGBA(offset, red, green, blue,
alpha: Double);
begin
cairo_pattern_add_color_stop_rgba(FPattern, offset, red, green, blue, alpha);
end;
constructor TCairoPattern.CreateForSurface(surface: ICairoSurface);
begin
CreateInternal(cairo_pattern_create_for_surface(TCairoSurface(surface.GetUserData(nil)).FSurface));
end;
constructor TCairoPattern.CreateInternal(pattern: PCairoPattern);
begin
FPattern := pattern;
cairo_pattern_set_user_data(FPattern, nil, Self, nil);
end;
constructor TCairoPattern.CreateLinear(x0, y0, x1, y1: Double);
begin
CreateInternal(cairo_pattern_create_linear(x0, y0, x1, y1));
end;
constructor TCairoPattern.CreateRadial(cx0, cy0, radius0, cx1, cy1,
radius1: Double);
begin
CreateInternal(cairo_pattern_create_radial(cx0, cy0, radius0, cx1, cy1, radius1));
end;
constructor TCairoPattern.CreateRGB(red, green, blue: Double);
begin
CreateInternal(cairo_pattern_create_rgb(red, green, blue));
end;
constructor TCairoPattern.CreateRGBA(red, green, blue, alpha: Double);
begin
CreateInternal(cairo_pattern_create_rgba(red, green, blue, alpha));
end;
destructor TCairoPattern.Destroy;
begin
cairo_pattern_set_user_data(FPattern, nil, nil, nil);
cairo_pattern_destroy(FPattern);
inherited;
end;
function TCairoPattern.GetColorStopCount: Integer;
begin
CairoCheck(cairo_pattern_get_color_stop_count(FPattern, @Result));
end;
procedure TCairoPattern.GetColorStopRGBA(index: Integer; offset, red, green,
blue, alpha: PDouble);
begin
CairoCheck(cairo_pattern_get_color_stop_rgba(FPattern, index, offset, red, green, blue, alpha));
end;
function TCairoPattern.GetExtend: TCairoExtend;
begin
Result := cairo_pattern_get_extend(FPattern);
end;
function TCairoPattern.GetFilter: TCairoFilter;
begin
Result := cairo_pattern_get_filter(FPattern);
end;
procedure TCairoPattern.GetLinearPoints(x0, y0, x1, y1: PDouble);
begin
CairoCheck(cairo_pattern_get_linear_points(FPattern, x0, y0, x1, y1));
end;
procedure TCairoPattern.GetMatrix(var matrix: TCairoMatrix);
begin
cairo_pattern_get_matrix(FPattern, @matrix);
end;
procedure TCairoPattern.GetRadialCircles(x0, y0, r0, x1, y1, r1: PDouble);
begin
CairoCheck(cairo_pattern_get_radial_circles(FPattern, x0, y0, r0, x1, y1, r1));
end;
procedure TCairoPattern.GetRGBA(red, green, blue, alpha: PDouble);
begin
CairoCheck(cairo_pattern_get_rgba(FPattern, red, green, blue, alpha));
end;
function TCairoPattern.GetStatus: TCairoStatus;
begin
Result := cairo_pattern_status(FPattern);
end;
function TCairoPattern.GetSurface: ICairoSurface;
var
psurface: PCairoSurface;
begin
CairoCheck(cairo_pattern_get_surface(FPattern, psurface));
Result := TCairoSurface.init(psurface);
end;
function TCairoPattern.GetType: TCairoPatternType;
begin
Result := cairo_pattern_get_type(FPattern);
end;
function TCairoPattern.GetUserData(key: Pointer): Pointer;
begin
Result := cairo_pattern_get_user_data(FPattern, key);
end;
procedure TCairoPattern.SetExtend(extend: TCairoExtend);
begin
cairo_pattern_set_extend(FPattern, extend);
end;
procedure TCairoPattern.SetFilter(filter: TCairoFilter);
begin
cairo_pattern_set_filter(FPattern, filter);
end;
procedure TCairoPattern.SetMatrix(matrix: TCairoMatrix);
begin
cairo_pattern_set_matrix(FPattern, @matrix);
end;
procedure TCairoPattern.SetUserData(key, userData: Pointer;
destroyFunc: TCairoDestroyFunc);
begin
Assert(key <> nil, 'null key is reserved');
CairoCheck(cairo_pattern_set_user_data(FPattern, key, userData, destroyFunc));
end;
class function TCairoPattern.init(pattern: PCairoPattern): TCairoPattern;
begin
Result := TCairoPattern(cairo_pattern_get_user_data(pattern, nil));
if Result = nil then
begin
cairo_pattern_reference(pattern);
Result := TCairoPattern.CreateInternal(pattern);
end;
end;
{ TCairoFontFace }
constructor TCairoFontFace.CreateInternal(fontface: PCairoFontFace);
begin
FFontFace := fontface;
cairo_font_face_set_user_data(FFontFace, nil, Self, nil);
end;
destructor TCairoFontFace.Destroy;
begin
cairo_font_face_set_user_data(FFontFace, nil, nil, nil);
cairo_font_face_destroy(FFontFace);
inherited;
end;
function TCairoFontFace.GetStatus: TCairoStatus;
begin
Result := cairo_font_face_status(FFontFace);
end;
function TCairoFontFace.GetType: TCairoFontType;
begin
Result := cairo_font_face_get_type(FFontFace);
end;
function TCairoFontFace.GetUserData(key: Pointer): Pointer;
begin
Result := cairo_font_face_get_user_data(FFontFace, key);
end;
class function TCairoFontFace.init(
fontface: PCairoFontFace): TCairoFontFace;
begin
Result := TCairoFontFace(cairo_font_face_get_user_data(fontface, nil));
if Result = nil then
begin
cairo_font_face_reference(fontface);
Result := TCairoFontFace.CreateInternal(fontface);
end;
end;
procedure TCairoFontFace.SetUserData(key, userData: Pointer;
destroyFunc: TCairoDestroyFunc);
begin
Assert(key <> nil, 'null key is reserved');
CairoCheck(cairo_font_face_set_user_data(FFontFace, key, userData, destroyFunc));
end;
{ TCairoScaledFont }
constructor TCairoScaledFont.Create(fontFace: ICairoFontFace; fontMatrix, ctm: TCairoMatrix; options: ICairoFontOptions);
begin
CreateInternal(
cairo_scaled_font_create(
TCairoFontFace(fontFace.GetUserData(nil)).FFontFace,
@fontMatrix, @ctm,
TCairoFontOptions(options.GetUserData).FFontOptions
));
end;
constructor TCairoScaledFont.CreateInternal(scaledfont: PCairoScaledFont);
begin
FScaledFont := scaledfont;
cairo_scaled_font_set_user_data(FScaledFont, nil, Self, nil);
end;
destructor TCairoScaledFont.Destroy;
begin
cairo_scaled_font_set_user_data(FScaledFont, nil, nil, nil);
cairo_scaled_font_destroy(FScaledFont);
inherited;
end;
procedure TCairoScaledFont.Extents(extent: TCairoFontExtents);
begin
cairo_scaled_font_extents(FScaledFont, @extent);
end;
procedure TCairoScaledFont.GetCtm(var ctm: TCairoMatrix);
begin
cairo_scaled_font_get_ctm(FScaledFont, @ctm);
end;
function TCairoScaledFont.GetFontFace: ICairoFontFace;
begin
Result := TCairoFontFace.init(cairo_scaled_font_get_font_face(FScaledFont));
end;
procedure TCairoScaledFont.GetFontMatrix(var fontMatrix: TCairoMatrix);
begin
cairo_scaled_font_get_font_matrix(FScaledFont, @fontMatrix);
end;
procedure TCairoScaledFont.GetFontOptions(options: ICairoFontOptions);
begin
cairo_scaled_font_get_font_options(FScaledFont, TCairoFontOptions(options.GetUserData).FFontOptions);
end;
procedure TCairoScaledFont.GetScaleMatrix(var scaleMatrix: TCairoMatrix);
begin
cairo_scaled_font_get_scale_matrix(FScaledFont, @scaleMatrix);
end;
function TCairoScaledFont.GetStatus: TCairoStatus;
begin
Result := cairo_scaled_font_status(FScaledFont);
end;
function TCairoScaledFont.GetType: TCairoFontType;
begin
Result := cairo_scaled_font_get_type(FScaledFont);
end;
function TCairoScaledFont.GetUserData(key: Pointer): Pointer;
begin
Result := cairo_scaled_font_get_user_data(FScaledFont, key);
end;
procedure TCairoScaledFont.GlyphExtents(glyphs: PCairoGlyph; numGlyphs: Integer;
extent: TCairoTextExtents);
begin
cairo_scaled_font_glyph_extents(FScaledFont, glyphs, numGlyphs, @extent);
end;
class function TCairoScaledFont.init(
scaledfont: PCairoScaledFont): TCairoScaledFont;
begin
Result := TCairoScaledFont(cairo_scaled_font_get_user_data(scaledfont, nil));
if Result = nil then
begin
cairo_scaled_font_reference(scaledfont);
Result := TCairoScaledFont.CreateInternal(scaledfont);
end;
end;
procedure TCairoScaledFont.SetUserData(key, userData: Pointer;
destroyFunc: TCairoDestroyFunc);
begin
Assert(key <> nil, 'null key is reserved');
CairoCheck(cairo_scaled_font_set_user_data(FScaledFont, key, userData, destroyFunc));
end;
procedure TCairoScaledFont.TextExtents(utf8: UTF8String;
extent: TCairoTextExtents);
begin
cairo_scaled_font_text_extents(FScaledFont, PAnsiChar(utf8), @extent);
end;
procedure TCairoScaledFont.TextToGlyphs(x, y: Double; utf8: UTF8String;
glyphs: PPCairoGlyph; numGlyphs: Integer;
clusters: PPCairoTextCluster; numClusters: Integer;
clusterFlags: PCairoTextClusterFlags);
begin
CairoCheck(cairo_scaled_font_text_to_glyphs(FScaledFont, x, y, PAnsiChar(utf8),
Length(utf8), glyphs, @numGlyphs, clusters, @numClusters, clusterFlags));
end;
{ TCairoToyFont }
constructor TCairoToyFontFace.Create(const family: AnsiString;
slant: TCairoFontSlant; weight: TCairoFontWeight);
begin
inherited CreateInternal(cairo_toy_font_face_create(PAnsiChar(family), slant, weight));
end;
function TCairoToyFontFace.GetFamily: AnsiString;
begin
Result := cairo_toy_font_face_get_family(FFontFace);
end;
function TCairoToyFontFace.GetSlant: TCairoFontSlant;
begin
Result := cairo_toy_font_face_get_slant(FFontFace);
end;
function TCairoToyFontFace.GetWeight: TCairoFontWeight;
begin
Result := cairo_toy_font_face_get_weight(FFontFace);
end;
{ TCairoWin32FontFace }
{$ifdef CAIRO_HAS_WIN32_FONT}
constructor TCairoWin32FontFace.CreateForHfont(font: HFONT);
begin
inherited CreateInternal(cairo_win32_font_face_create_for_hfont(font));
end;
{$endif}
{$ifdef CAIRO_HAS_WIN32_FONT}
constructor TCairoWin32FontFace.CreateForLogfontw(logfont: PLOGFONTW);
begin
inherited CreateInternal(cairo_win32_font_face_create_for_logfontw(logfont));
end;
{$endif}
{$ifdef CAIRO_HAS_WIN32_FONT}
constructor TCairoWin32FontFace.CreateForLogfontwHfont(logfont: PLOGFONTW;
font: HFONT);
begin
inherited CreateInternal(cairo_win32_font_face_create_for_logfontw_hfont(logfont, font));
end;
{$endif}
{ TCairoWin32ScaledFont }
{$ifdef CAIRO_HAS_WIN32_FONT}
procedure TCairoWin32ScaledFont.DoneFont;
begin
cairo_win32_scaled_font_done_font(FScaledFont);
end;
{$endif}
{$ifdef CAIRO_HAS_WIN32_FONT}
procedure TCairoWin32ScaledFont.GetDeviceToLogical(
var deviceToLogical: TCairoMatrix);
begin
cairo_win32_scaled_font_get_device_to_logical(FScaledFont, @deviceToLogical);
end;
{$endif}
{$ifdef CAIRO_HAS_WIN32_FONT}
procedure TCairoWin32ScaledFont.GetLogicalToDevice(
var logicalToDevice: TCairoMatrix);
begin
cairo_win32_scaled_font_get_logical_to_device(FScaledFont, @logicalToDevice);
end;
{$endif}
{$ifdef CAIRO_HAS_WIN32_FONT}
function TCairoWin32ScaledFont.GetMetricsFactor: Double;
begin
Result := cairo_win32_scaled_font_get_metrics_factor(FScaledFont);
end;
{$endif}
{$ifdef CAIRO_HAS_WIN32_FONT}
procedure TCairoWin32ScaledFont.SelectFont(hdc: HDC);
begin
CairoCheck(cairo_win32_scaled_font_select_font(FScaledFont, hdc));
end;
{$endif}
{ TCairoUserFontFace }
constructor TCairoUserFontFace.Create;
begin
inherited CreateInternal(cairo_user_font_face_create);
end;
{ TUserScaledFont }
function cairoUserScaledFontInit(scaledFont: PCairoScaledFont; cr: PCairo; extent: PCairoFontExtents): TCairoStatus; cdecl;
begin
Result := TUserScaledFont(cairo_scaled_font_get_user_data(scaledFont, nil)).UserInit(cr, extent);
end;
function cairoUserScaledFontRenderGlyph(scaledFont: PCairoScaledFont; glyph: Cardinal; cr: PCairo; extent: PCairoTextExtents): TCairoStatus; cdecl;
begin
Result := TUserScaledFont(cairo_scaled_font_get_user_data(scaledFont, nil)).UserRenderGlyph(glyph, cr, extent);
end;
function cairoUserScaledFontTextToGlyphs(scaledFont: PCairoScaledFont; utf8: PAnsiChar; utf8Len: Integer; glyphs: PPCairoGlyph; numGlyphs: PInteger; clusters: PPCairoTextCluster; numClusters: PInteger; clusterFlags: PCairoTextClusterFlags): TCairoStatus; cdecl;
begin
Result := TUserScaledFont(cairo_scaled_font_get_user_data(scaledFont, nil)).UserTextToGlyphs(utf8, utf8Len, glyphs, numGlyphs, clusters, numClusters, clusterFlags);
end;
function cairoUserScaledFontUnicodeToGlyph(scaledFont: PCairoScaledFont; unicode: Cardinal; glyphIndex: PCardinal): TCairoStatus; cdecl;
begin
Result := TUserScaledFont(cairo_scaled_font_get_user_data(scaledFont, nil)).UserUnicodeToGlyph(unicode, glyphIndex);
end;
{ TUserScaledFont }
constructor TUserScaledFont.Create(fontFace: ICairoFontFace; fontMatrix,
ctm: TCairoMatrix; options: ICairoFontOptions);
begin
inherited;
with TCairoFontFace(fontFace.GetUserData(nil)) do
begin
cairo_user_font_face_set_init_func(FFontFace, @cairoUserScaledFontInit);
cairo_user_font_face_set_render_glyph_func(FFontFace, @cairoUserScaledFontRenderGlyph);
cairo_user_font_face_set_text_to_glyphs_func(FFontFace, @cairoUserScaledFontTextToGlyphs);
cairo_user_font_face_set_unicode_to_glyph_func(FFontFace, @cairoUserScaledFontUnicodeToGlyph);
end;
end;
{ TCairoDevice }
function TCairoDevice.Acquire: TCairoStatus;
begin
Result := cairo_device_acquire(FDevice);
end;
constructor TCairoDevice.CreateInternal(device: PCairoDevice);
begin
FDevice := device;
cairo_device_set_user_data(device, nil, Self, nil);
end;
destructor TCairoDevice.Destroy;
begin
cairo_device_set_user_data(FDevice, nil, nil, nil);
cairo_device_destroy(FDevice);
inherited;
end;
procedure TCairoDevice.Finish;
begin
cairo_device_finish(FDevice);
end;
procedure TCairoDevice.Flush;
begin
cairo_device_flush(FDevice);
end;
function TCairoDevice.GetStatus: TCairoStatus;
begin
Result := cairo_device_status(FDevice);
end;
function TCairoDevice.GetType: TCairoDeviceType;
begin
Result := cairo_device_get_type(FDevice);
end;
class function TCairoDevice.init(device: PCairoDevice): TCairoDevice;
begin
if device <> nil then
begin
Result := TCairoDevice(cairo_device_get_user_data(device, nil));
if Result = nil then
begin
cairo_device_reference(device);
Result := TCairoDevice.CreateInternal(device);
end;
end else
Result := nil;
end;
procedure TCairoDevice.Release;
begin
cairo_device_release(FDevice);
end;
{ TCairoRegion }
function TCairoRegion.ContainsPoint(x, y: Integer): Boolean;
begin
Result := cairo_region_contains_point(FRegion, x, y) <> 0;
end;
function TCairoRegion.ContainsRectangle(
const rectangle: PCairoRectangleInt): TCairoRegionOverlap;
begin
Result := cairo_region_contains_rectangle(FRegion, rectangle)
end;
function TCairoRegion.Copy: ICairoRegion;
begin
// Result := CreateInternal(cairo_region_copy(FRegion))
end;
constructor TCairoRegion.Create;
begin
CreateInternal(cairo_region_create);
end;
constructor TCairoRegion.CreateInternal(region: PCairoRegion);
begin
FRegion := region;
end;
constructor TCairoRegion.CreateRectangle(const rectangle: PCairoRectangleInt);
begin
CreateInternal(cairo_region_create_rectangle(rectangle));
end;
constructor TCairoRegion.CreateRectangles(const rects: PCairoRectangleInt;
count: Integer);
begin
CreateInternal(cairo_region_create_rectangles(rects, count));
end;
destructor TCairoRegion.Destroy;
begin
cairo_region_destroy(FRegion);
inherited;
end;
function TCairoRegion.Equal(r: ICairoRegion): Boolean;
begin
Result := cairo_region_equal(FRegion, r.GetUserData) <> 0
end;
procedure TCairoRegion.GetExtents(extents: PCairoRectangleInt);
begin
cairo_region_get_extents(FRegion, extents);
end;
procedure TCairoRegion.GetRectangle(nth: Integer;
rectangle: PCairoRectangleInt);
begin
cairo_region_get_rectangle(FRegion, nth, rectangle);
end;
function TCairoRegion.GetUserData: Pointer;
begin
Result := FRegion;
end;
function TCairoRegion.Intersect(other: ICairoRegion): TCairoStatus;
begin
Result := cairo_region_intersect(FRegion, other.GetUserData);
end;
function TCairoRegion.IntersectRectangle(
const rectangle: PCairoRectangleInt): TCairoStatus;
begin
Result := cairo_region_intersect_rectangle(FRegion, rectangle);
end;
function TCairoRegion.IsEmpty: Boolean;
begin
Result := cairo_region_is_empty(FRegion) <> 0;
end;
function TCairoRegion.NumRectangles: Integer;
begin
Result := cairo_region_num_rectangles(FRegion);
end;
function TCairoRegion.Status: TCairoStatus;
begin
Result := cairo_region_status(FRegion);
end;
function TCairoRegion.Subtract(other: ICairoRegion): TCairoStatus;
begin
Result := cairo_region_subtract(FRegion, other.GetUserData);
end;
function TCairoRegion.SubtractRectangle(
const rectangle: PCairoRectangleInt): TCairoStatus;
begin
Result := cairo_region_subtract_rectangle(FRegion, rectangle);
end;
procedure TCairoRegion.Translate(dx, dy: Integer);
begin
cairo_region_translate(FRegion, dx, dy);
end;
function TCairoRegion.Union(other: ICairoRegion): TCairoStatus;
begin
Result := cairo_region_union(FRegion, other.GetUserData);
end;
function TCairoRegion.UnionRectangle(
const rectangle: PCairoRectangleInt): TCairoStatus;
begin
Result := cairo_region_union_rectangle(FRegion, rectangle);
end;
function TCairoRegion.XorRectangle(
const rectangle: PCairoRectangleInt): TCairoStatus;
begin
Result := cairo_region_xor_rectangle(FRegion, rectangle);
end;
function TCairoRegion.XorRegion(other: ICairoRegion): TCairoStatus;
begin
Result := cairo_region_xor(FRegion, other.GetUserData)
end;
end.
| 31.928422 | 262 | 0.74243 |
Subsets and Splits
HTML Code Excluding Scripts
The query retrieves a limited set of HTML content entries that are longer than 8 characters and do not contain script tags, offering only basic filtering with minimal analytical value.