text stringlengths 14 6.51M |
|---|
unit speechtotext;
{$mode delphi}
interface
uses
Classes, SysUtils, And_jni, AndroidWidget;
type
{Draft Component code by "Lazarus Android Module Wizard" [5/12/2017 22:51:37]}
{https://github.com/jmpessoa/lazandroidmodulewizard}
{jControl template}
jSpeechToText = class(jControl)
private
FRequestCode: integer;
FPromptMessage: string;
FSpeechLanguage: TSpeechLanguage;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Init; override;
function SpeakIn() : boolean; overload;
function SpeakIn(_promptMessage: string) : boolean; overload;
procedure SetPromptMessage(_promptMessage: string);
procedure SetRequestCode(_requestCode: integer);
function GetRequestCode(): integer;
function SpeakOut(_intentData: jObject): string;
procedure SetLanguage(_language: TSpeechLanguage);
published
property RequestCode: integer read GetRequestCode write SetRequestCode;
property PromptMessage: string read FPromptMessage write SetPromptMessage;
property SpeechLanguage: TSpeechLanguage read FSpeechLanguage write SetLanguage;
end;
function jSpeechToText_jCreate(env: PJNIEnv; _Self: int64; this: jObject): jObject;
implementation
{--------- jSpeechToText --------------}
constructor jSpeechToText.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
//your code here....
FPromptMessage:= 'Speech a message to write...';
FRequestCode:= 1234;
FSpeechLanguage:= slDefault;
end;
destructor jSpeechToText.Destroy;
begin
if not (csDesigning in ComponentState) then
begin
if FjObject <> nil then
begin
jni_proc(gApp.jni.jEnv, FjObject, 'jFree');
FjObject:= nil;
end;
end;
//you others free code here...'
inherited Destroy;
end;
procedure jSpeechToText.Init;
begin
if FInitialized then Exit;
inherited Init; //set default ViewParent/FjPRLayout as jForm.View!
//your code here: set/initialize create params....
FjObject := jSpeechToText_jCreate(gApp.jni.jEnv, int64(Self), gApp.jni.jThis);
if FjObject = nil then exit;
FInitialized:= True;
if FRequestCode <> 1234 then
SetRequestCode(FRequestCode);
if FPromptMessage <> '' then
SetPromptMessage(FPromptMessage);
if FSpeechLanguage <> slDefault then
SetLanguage(FSpeechLanguage);
end;
function jSpeechToText.SpeakIn() : boolean;
begin
result := false;
//in designing component state: set value here...
if FInitialized then
result := jni_func_out_z(gApp.jni.jEnv, FjObject, 'SpeakIn');
end;
procedure jSpeechToText.SetPromptMessage(_promptMessage: string);
begin
//in designing component state: set value here...
FPromptMessage:= _promptMessage;
if FInitialized then
jni_proc_t(gApp.jni.jEnv, FjObject, 'SetPromptMessage', _promptMessage);
end;
function jSpeechToText.SpeakIn(_promptMessage: string) : boolean;
begin
result := false;
//in designing component state: set value here...
FPromptMessage:= _promptMessage;
if FInitialized then
result := jni_func_t_out_z(gApp.jni.jEnv, FjObject, 'SpeakIn', FPromptMessage);
end;
procedure jSpeechToText.SetRequestCode(_requestCode: integer);
begin
//in designing component state: set value here...
FRequestCode:= _requestCode;
if FInitialized then
jni_proc_i(gApp.jni.jEnv, FjObject, 'SetRequestCode', _requestCode);
end;
function jSpeechToText.GetRequestCode(): integer;
begin
//in designing component state: result value here...
Result:= FRequestCode;
if FInitialized then
Result:= jni_func_out_i(gApp.jni.jEnv, FjObject, 'GetRequestCode');
end;
function jSpeechToText.SpeakOut(_intentData: jObject): string;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jni_func_int_out_t(gApp.jni.jEnv, FjObject, 'SpeakOut', _intentData);
end;
procedure jSpeechToText.SetLanguage(_language: TSpeechLanguage);
begin
//in designing component state: set value here...
FSpeechLanguage:= _language;
if FInitialized then
jni_proc_i(gApp.jni.jEnv, FjObject, 'SetLanguage', Ord(_language));
end;
{-------- jSpeechToText_JNI_Bridge ----------}
function jSpeechToText_jCreate(env: PJNIEnv; _Self: int64; this: jObject): jObject;
var
jParams: array[0..0] of jValue;
jMethod: jMethodID = nil;
jCls: jClass = nil;
label
_exceptionOcurred;
begin
result := nil;
jCls := Get_gjClass(env);
if jCls = nil then goto _exceptionOcurred;
jMethod := env^.GetMethodID(env, jCls, 'jSpeechToText_jCreate', '(J)Ljava/lang/Object;');
if jMethod = nil then goto _exceptionOcurred;
jParams[0].j := _Self;
Result := env^.CallObjectMethodA(env, this, jMethod, @jParams);
Result := env^.NewGlobalRef(env, Result);
_exceptionOcurred: if jni_ExceptionOccurred(env) then result := nil;
end;
end.
|
unit KM_GUIMapEdTerrainHeights;
{$I KaM_Remake.inc}
interface
uses
Math, SysUtils,
KM_Controls, KM_Defaults;
type
//Terrain height editing
TKMMapEdTerrainHeights = class
private
procedure HeightChange(Sender: TObject);
procedure HeightRefresh;
protected
Panel_Heights: TKMPanel;
HeightSize: TKMTrackBar;
HeightSlope: TKMTrackBar;
HeightSpeed: TKMTrackBar;
HeightShapeLabel: TKMLabel;
HeightCircle: TKMButtonFlat;
HeightSquare: TKMButtonFlat;
HeightElevate: TKMButtonFlat;
HeightUnequalize: TKMButtonFlat;
public
constructor Create(aParent: TKMPanel);
procedure Show;
procedure Hide;
function Visible: Boolean;
end;
implementation
uses
KM_ResFonts, KM_ResTexts, KM_GameCursor, KM_RenderUI,
KM_InterfaceGame;
{ TKMMapEdTerrainHeights }
constructor TKMMapEdTerrainHeights.Create(aParent: TKMPanel);
begin
inherited Create;
Panel_Heights := TKMPanel.Create(aParent, 0, 28, TB_WIDTH, 400);
TKMLabel.Create(Panel_Heights, 0, PAGE_TITLE_Y, TB_WIDTH, 0, gResTexts[TX_MAPED_TERRAIN_HEIGHTS], fnt_Outline, taCenter);
HeightShapeLabel := TKMLabel.Create(Panel_Heights, 0, 34, TB_WIDTH, 0, gResTexts[TX_MAPED_TERRAIN_HEIGHTS_SHAPE], fnt_Metal, taLeft);
HeightCircle := TKMButtonFlat.Create(Panel_Heights, 120, 30, 24, 24, 592);
HeightCircle.Hint := gResTexts[TX_MAPED_TERRAIN_HEIGHTS_CIRCLE];
HeightCircle.OnClick := HeightChange;
HeightSquare := TKMButtonFlat.Create(Panel_Heights, 150, 30, 24, 24, 593);
HeightSquare.Hint := gResTexts[TX_MAPED_TERRAIN_HEIGHTS_SQUARE];
HeightSquare.OnClick := HeightChange;
HeightSize := TKMTrackBar.Create(Panel_Heights, 0, 60, TB_WIDTH, 1, 15); //1..15(4bit) for size
HeightSize.Caption := gResTexts[TX_MAPED_TERRAIN_HEIGHTS_SIZE];
HeightSize.Hint := gResTexts[TX_MAPED_TERRAIN_HEIGHTS_SIZE_HINT];
HeightSize.OnChange := HeightChange;
HeightSlope := TKMTrackBar.Create(Panel_Heights, 0, 115, TB_WIDTH, 1, 15); //1..15(4bit) for slope shape
HeightSlope.Caption := gResTexts[TX_MAPED_TERRAIN_HEIGHTS_SLOPE];
HeightSlope.Hint := gResTexts[TX_MAPED_TERRAIN_HEIGHTS_SLOPE_HINT];
HeightSlope.OnChange := HeightChange;
HeightSpeed := TKMTrackBar.Create(Panel_Heights, 0, 170, TB_WIDTH, 1, 15); //1..15(4bit) for speed
HeightSpeed.Caption := gResTexts[TX_MAPED_TERRAIN_HEIGHTS_SPEED];
HeightSpeed.Hint := gResTexts[TX_MAPED_TERRAIN_HEIGHTS_SPEED_HINT];
HeightSpeed.OnChange := HeightChange;
HeightElevate := TKMButtonFlat.Create(Panel_Heights, 0, 225, TB_WIDTH, 20, 0);
HeightElevate.OnClick := HeightChange;
HeightElevate.Down := True;
HeightElevate.Caption := gResTexts[TX_MAPED_TERRAIN_HEIGHTS_ELEVATE];
HeightElevate.CapOffsetY := -12;
HeightElevate.Hint := gResTexts[TX_MAPED_TERRAIN_HEIGHTS_ELEVATE_HINT];
HeightUnequalize := TKMButtonFlat.Create(Panel_Heights, 0, 255, TB_WIDTH, 20, 0);
HeightUnequalize.OnClick := HeightChange;
HeightUnequalize.Caption := gResTexts[TX_MAPED_TERRAIN_HEIGHTS_UNEQUALIZE];
HeightUnequalize.CapOffsetY := -12;
HeightUnequalize.Hint := gResTexts[TX_MAPED_TERRAIN_HEIGHTS_UNEQUALIZE_HINT];
end;
procedure TKMMapEdTerrainHeights.HeightChange(Sender: TObject);
begin
GameCursor.MapEdSize := HeightSize.Position;
GameCursor.MapEdSlope := HeightSlope.Position;
GameCursor.MapEdSpeed := HeightSpeed.Position;
//Shape
if Sender = HeightCircle then
GameCursor.MapEdShape := hsCircle
else
if Sender = HeightSquare then
GameCursor.MapEdShape := hsSquare;
//Kind
if Sender = HeightElevate then
GameCursor.Mode := cmElevate
else
if Sender = HeightUnequalize then
GameCursor.Mode := cmEqualize;
HeightRefresh;
end;
procedure TKMMapEdTerrainHeights.HeightRefresh;
begin
HeightCircle.Down := (GameCursor.MapEdShape = hsCircle);
HeightSquare.Down := (GameCursor.MapEdShape = hsSquare);
HeightElevate.Down := (GameCursor.Mode = cmElevate);
HeightUnequalize.Down := (GameCursor.Mode = cmEqualize);
end;
procedure TKMMapEdTerrainHeights.Show;
begin
HeightChange(HeightCircle);
HeightChange(HeightElevate);
Panel_Heights.Show;
end;
function TKMMapEdTerrainHeights.Visible: Boolean;
begin
Result := Panel_Heights.Visible;
end;
procedure TKMMapEdTerrainHeights.Hide;
begin
Panel_Heights.Hide;
end;
end.
|
unit FindUnit.FormSettings;
interface
uses
Data.DB,
Datasnap.DBClient,
FindUnit.Settings,
System.IniFiles,
System.SyncObjs,
System.SysUtils,
Vcl.DBCtrls,
Vcl.DBGrids,
Vcl.ExtCtrls,
Vcl.Grids,
Vcl.Mask,
Vcl.StdCtrls,
Winapi.ShellAPI, FindUnit.OTAUtils, ToolsAPI, Vcl.Controls, Vcl.ComCtrls,
System.Classes, Vcl.Forms;
type
TfrmSettings = class(TForm)
pgcMain: TPageControl;
tsAutoImport: TTabSheet;
chkAutoEnabled: TCheckBox;
grdAutoImport: TDBGrid;
dtsAutoImport: TDataSource;
grpAutoSettings: TGroupBox;
nvgAutoImport: TDBNavigator;
tsGeneral: TTabSheet;
grpGeneralSettings: TGroupBox;
btn1: TButton;
grpSearchAlgorithm: TRadioGroup;
grpShotCuts: TGroupBox;
chkMemorize: TCheckBox;
chkOrganizeUses: TCheckBox;
grpUsesOrganization: TGroupBox;
chkAlwaysImportToInterfaceSection: TCheckBox;
chkSortAfterAdding: TCheckBox;
chkBreakline: TCheckBox;
chkBlankLineBtwNamespace: TCheckBox;
lblLink: TLabel;
chbOrganizeUsesAfterInsertingNewUsesUnit: TCheckBox;
medtBreakUsesLineAtPosition: TMaskEdit;
lblBreakLineAt: TLabel;
chbGroupNonNameSpaceUnits: TCheckBox;
cdsAutoImport: TClientDataSet;
cdsAutoImportIDENTIFIER: TStringField;
cdsAutoImportUNIT: TStringField;
btnCreateProjectConfiguration: TButton;
tsUnusedUses: TTabSheet;
mmoIgnoreUses: TMemo;
Label1: TLabel;
chbFeatureUnusedUses: TCheckBox;
chbDontBreakLineForNonNameSpaceUnits: TCheckBox;
shpUnused: TShape;
Shape2: TShape;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btn1Click(Sender: TObject);
procedure chkBreaklineClick(Sender: TObject);
procedure chkSortAfterAddingClick(Sender: TObject);
procedure lblLinkClick(Sender: TObject);
procedure pgcMainChange(Sender: TObject);
procedure btnCreateProjectConfigurationClick(Sender: TObject);
private
FSettings: TSettings;
FMemorizedOpened: Boolean;
procedure InsertAutoImportInDataSet;
procedure InsertDataSetInAutoImport;
procedure CreateIniFile;
procedure SaveSettings;
procedure ConfigureAutoImportPage;
procedure ConfigurePages;
procedure ToggleEnableItems;
function IsThereProjectOpen: Boolean;
end;
implementation
uses
Winapi.Windows, Vcl.Dialogs;
{$R *.dfm}
procedure TfrmSettings.SaveSettings;
begin
FSettings.AutoImportEnabled := chkAutoEnabled.Checked;
FSettings.AlwaysUseInterfaceSection := chkAlwaysImportToInterfaceSection.Checked;
FSettings.OrganizeUses := chkOrganizeUses.Checked;
FSettings.StoreChoices := chkMemorize.Checked;
FSettings.BreakLine := chkBreakline.Checked;
FSettings.SortUsesAfterAdding := chkSortAfterAdding.Checked;
FSettings.BlankLineBtwNameScapes := chkBlankLineBtwNamespace.Checked;
FSettings.UseDefaultSearchMatch := grpSearchAlgorithm.ItemIndex = 0;
FSettings.OrganizeUsesAfterAddingNewUsesUnit := chbOrganizeUsesAfterInsertingNewUsesUnit.Checked;
FSettings.BreakUsesLineAtPosition := StrToInt(Trim(medtBreakUsesLineAtPosition.Text));
FSettings.GroupNonNamespaceUnits := chbGroupNonNameSpaceUnits.Checked;
FSettings.IgnoreUsesUnused := mmoIgnoreUses.Lines.CommaText;
FSettings.EnableExperimentalFindUnusedUses := chbFeatureUnusedUses.Checked;
FSettings.BreakLineForNonDomainUses := not chbDontBreakLineForNonNameSpaceUnits.Checked;
InsertDataSetInAutoImport;
end;
procedure TfrmSettings.btn1Click(Sender: TObject);
begin
ShellExecute(Handle, nil, PChar(TSettings.SettingsFilePath), nil, nil, SW_SHOWNORMAL)
end;
procedure TfrmSettings.btnCreateProjectConfigurationClick(Sender: TObject);
begin
ShowMessage(GetCurrentProject.FileName);
end;
procedure TfrmSettings.chkBreaklineClick(Sender: TObject);
begin
ToggleEnableItems;
end;
procedure TfrmSettings.chkSortAfterAddingClick(Sender: TObject);
begin
ToggleEnableItems;
end;
procedure TfrmSettings.ToggleEnableItems;
begin
chkBlankLineBtwNamespace.Enabled := chkBreakline.Checked and chkSortAfterAdding.Checked;
chbGroupNonNameSpaceUnits.Enabled := chkBreakline.Checked and chkSortAfterAdding.Checked;
end;
procedure TfrmSettings.ConfigureAutoImportPage;
begin
chkAutoEnabled.Checked := FSettings.AutoImportEnabled;
chkAlwaysImportToInterfaceSection.Checked := FSettings.AlwaysUseInterfaceSection;
chkMemorize.Checked := FSettings.StoreChoices;
chkBreakline.Checked := FSettings.BreakLine;
chkSortAfterAdding.Checked := FSettings.SortUsesAfterAdding;
chkBlankLineBtwNamespace.Checked := FSettings.BlankLineBtwNameScapes;
chkOrganizeUses.Checked := FSettings.OrganizeUses;
medtBreakUsesLineAtPosition.Text := IntToStr(FSettings.BreakUsesLineAtPosition);
chbOrganizeUsesAfterInsertingNewUsesUnit.Checked := FSettings.OrganizeUsesAfterAddingNewUsesUnit;
chbGroupNonNameSpaceUnits.Checked := FSettings.GroupNonNamespaceUnits;
mmoIgnoreUses.Lines.CommaText := FSettings.IgnoreUsesUnused;
chbFeatureUnusedUses.Checked := FSettings.EnableExperimentalFindUnusedUses;
chbDontBreakLineForNonNameSpaceUnits.Checked := not FSettings.BreakLineForNonDomainUses;
if FSettings.UseDefaultSearchMatch then
grpSearchAlgorithm.ItemIndex := 0
else
grpSearchAlgorithm.ItemIndex := 1;
ToggleEnableItems;
end;
procedure TfrmSettings.ConfigurePages;
begin
ConfigureAutoImportPage;
end;
procedure TfrmSettings.CreateIniFile;
begin
FSettings := TSettings.Create;
end;
procedure TfrmSettings.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TfrmSettings.FormCreate(Sender: TObject);
begin
CreateIniFile;
ConfigurePages;
end;
procedure TfrmSettings.FormDestroy(Sender: TObject);
begin
SaveSettings;
TSettings.ReloadSettings;
FSettings.Free;
end;
procedure TfrmSettings.InsertAutoImportInDataSet;
var
Values: TStrings;
I: Integer;
begin
FMemorizedOpened := True;
Values := FSettings.AutoImportValue;
try
if Values = nil then
Exit;
if not cdsAutoImport.Active then
cdsAutoImport.CreateDataSet;
for I := 0 to Values.Count -1 do
begin
cdsAutoImport.Append;
cdsAutoImportIDENTIFIER.Value := Values.Names[i];
cdsAutoImportUNIT.Value := Values.ValueFromIndex[i];
cdsAutoImport.Post;
end;
with cdsAutoImport.IndexDefs.AddIndexDef do
begin
Name := cdsAutoImportIDENTIFIER.FieldName + 'Idx';
Fields := cdsAutoImportIDENTIFIER.FieldName;
Options := [ixCaseInsensitive];
end;
cdsAutoImport.IndexName := cdsAutoImportIDENTIFIER.FieldName + 'Idx';
finally
Values.Free;
end;
end;
procedure TfrmSettings.InsertDataSetInAutoImport;
var
Values: TStrings;
begin
if not FMemorizedOpened then
Exit;
Values := TStringList.Create;
cdsAutoImport.DisableControls;
try
cdsAutoImport.First;
while not cdsAutoImport.Eof do
begin
Values.Values[UpperCase(cdsAutoImportIDENTIFIER.Value)] := cdsAutoImportUNIT.Value;
cdsAutoImport.Next;
end;
FSettings.AutoImportValue := Values;
finally
Values.Free;
end;
end;
function TfrmSettings.IsThereProjectOpen: Boolean;
begin
Result := GetCurrentProject <> nil;
end;
procedure TfrmSettings.lblLinkClick(Sender: TObject);
var
Link: string;
begin
Link := 'https://github.com/rfrezino/RFindUnit';
ShellExecute(Application.Handle, PChar('open'), PChar(Link), nil, nil, SW_SHOW);
end;
procedure TfrmSettings.pgcMainChange(Sender: TObject);
begin
if not FMemorizedOpened then
InsertAutoImportInDataSet;
end;
end.
|
{ Invokable interface IPulseWS }
unit PulseWSIntf;
interface
uses InvokeRegistry, Types, XSBuiltIns, Advantech, CommunicationObj;
type
IPulseWS = interface(IInvokable)
['{5E79B470-2680-410A-96CC-685BAF238D95}']
// IPulse
function Get_N1CH1: Integer; safecall;
function Get_N2: Integer; safecall;
function Get_N3: Integer; safecall;
function Get_N4: Integer; safecall;
function Get_N5: Integer; safecall;
function Get_N6: Integer; safecall;
function Get_N1CH2: Integer; safecall;
function Get_Frecuencia: Integer; safecall;
function Get_TxRxPulso: TxPulseEnum; safecall;
// IPulseControl
procedure Set_N1CH1(Value: Integer); safecall;
procedure Set_N2(Value: Integer); safecall;
procedure Set_N3(Value: Integer); safecall;
procedure Set_N4(Value: Integer); safecall;
procedure Set_N5(Value: Integer); safecall;
procedure Set_N6(Value: Integer); safecall;
procedure Set_N1CH2(Value: Integer); safecall;
procedure Set_Frecuencia(Value: Integer); safecall;
end;
implementation
initialization
InvRegistry.RegisterInterface(TypeInfo(IPulseWS));
end.
|
{$ifdef license}
(*
Copyright 2020 ChapmanWorld LLC ( https://chapmanworld.com )
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be
used to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*)
{$endif}
unit testcase.cwIO.Buffers;
{$ifdef fpc} {$mode delphiunicode} {$M+} {$endif}
interface
uses
cwTest
;
type
TTest_IBuffer_Standard = class(TTestCase)
private
published
procedure FillMem;
procedure LoadFromStream;
procedure SaveToStream;
procedure Assign;
procedure InsertData;
procedure AppendData;
procedure AppendDataASCIIZ;
procedure ExtractData;
procedure getDataPointer;
procedure getSize;
procedure getByte;
procedure setByte;
procedure setSize;
end;
implementation
uses
cwTest.Standard
, cwIO
, cwIO.Standard
;
const
cTestBufferSize = 512;
procedure TTest_IBuffer_Standard.FillMem;
var
idx: nativeuint;
CUT: IBuffer;
begin
// Arrange:
CUT := TBuffer.Create( cTestBufferSize );
// Act:
CUT.FillMem($FF);
// Assert:
for idx := 0 to pred( cTestBufferSize ) do begin
TTest.Expect( $FF, CUT.getByte(idx) );
end;
end;
procedure TTest_IBuffer_Standard.LoadFromStream;
var
MS: IStream;
CUT: IBuffer;
B: uint8;
idx: nativeuint;
begin
// Arrange:
B := $FE;
MS := TMemoryStream.Create;
for idx := 0 to pred(cTestBufferSize) do begin
MS.Write(@B,1);
end;
MS.Position := 0;
CUT := TBuffer.Create(cTestBufferSize);
// Act:
CUT.LoadFromStream(MS,MS.Size);
// Assert:
for idx := 0 to pred( cTestBufferSize ) do begin
TTest.Expect( $FE, CUT.getByte(idx) );
end;
end;
procedure TTest_IBuffer_Standard.SaveToStream;
var
MS: IStream;
CUT: IBuffer;
B: uint8;
idx: nativeuint;
begin
// Arrange:
CUT := TBuffer.Create(cTestBufferSize);
CUT.FillMem($FD);
MS := TMemoryStream.Create;
// Act:
CUT.SaveToStream(MS,cTestBufferSize);
// Assert:
MS.Position := 0;
for idx := 0 to pred( cTestBufferSize ) do begin
B := 0;
MS.Read(@B,1);
TTest.Expect( $FD, B );
end;
end;
procedure TTest_IBuffer_Standard.Assign;
var
idx: nativeuint;
B: IBuffer;
CUT: IBuffer;
begin
// Arrange:
B := TBuffer.Create(cTestBufferSize);
B.FillMem($FB);
CUT := TBuffer.Create;
// Act:
CUT.Assign(B);
// Assert:
for idx := 0 to pred( cTestBufferSize ) do begin
TTest.Expect( $FB, CUT.getByte(idx) );
end;
end;
procedure TTest_IBuffer_Standard.InsertData;
var
idx: uint8;
CUT: IBuffer;
begin
// Arrange:
CUT := TBuffer.Create($FF);
// Act:
for idx := 0 to $FE do begin
CUT.InsertData(@idx,idx,1);
end;
// Assert:
for idx := 0 to $FE do begin
TTest.Expect( idx, CUT.getByte(idx) );
end;
end;
procedure TTest_IBuffer_Standard.AppendData;
var
idx: nativeuint;
CUT: IBuffer;
B: IBuffer;
begin
// Arrange:
CUT := TBuffer.Create(cTestBufferSize div 2);
CUT.FillMem($FF);
B := TBuffer.Create(cTestBufferSize div 2 );
B.FillMem($FE);
// Act:
CUT.AppendData(B.getDataPointer,B.size);
// Assert:
TTest.Expect( CUT.Size, nativeuint(((cTestBufferSize div 2)*2)) );
for idx := 0 to pred(cTestBufferSize) do begin
if (idx<(cTestBuffersize div 2)) then begin
TTest.Expect($FF,CUT.getByte(idx));
end else begin
TTest.Expect($FE,CUT.getByte(idx));
end;
end;
end;
procedure TTest_IBuffer_Standard.AppendDataASCIIZ;
var
Data: array[0..5] of uint8;
CUT: IBuffer;
begin
// Arrange:
CUT := TBuffer.Create(2);
CUT.FillMem($FF);
Data[0] := 67;
Data[1] := 82;
Data[2] := 65;
Data[3] := 73;
Data[4] := 71;
Data[5] := 0;
// Act:
CUT.AppendData(@Data[0]);
// Assert:
TTest.Expect( nativeuint(8), CUT.Size );
TTest.Expect( $FF, CUT.getByte(0) );
TTest.Expect( $FF, CUT.getByte(1) );
TTest.Expect( 67, CUT.getByte(2) );
TTest.Expect( 82, CUT.getByte(3) );
TTest.Expect( 65, CUT.getByte(4) );
TTest.Expect( 73, CUT.getByte(5) );
TTest.Expect( 71, CUT.getByte(6) );
TTest.Expect( 0, CUT.getByte(7) );
end;
procedure TTest_IBuffer_Standard.ExtractData;
var
CUT: IBuffer;
Two: array[0..1] of uint8;
begin
// Arrange:
CUT := TBuffer.Create(5);
CUT.setByte(0,67);
CUT.setByte(1,82);
CUT.setByte(2,65);
CUT.setByte(3,73);
CUT.setByte(4,71);
Two[0] := 0;
Two[1] := 0;
// Act:
CUT.ExtractData(@Two[0],2,2);
// Assert:
TTest.Expect( 65, Two[0] );
TTest.Expect( 73, Two[1] );
end;
procedure TTest_IBuffer_Standard.getDataPointer;
begin
// Arrange:
// Act:
// Assert:
TTest.Fail('Test not implemented yet.');
end;
procedure TTest_IBuffer_Standard.getSize;
begin
// Arrange:
// Act:
// Assert:
TTest.Fail('Test not implemented yet.');
end;
procedure TTest_IBuffer_Standard.getByte;
begin
// Arrange:
// Act:
// Assert:
TTest.Fail('Test not implemented yet.');
end;
procedure TTest_IBuffer_Standard.setByte;
begin
// Arrange:
// Act:
// Assert:
TTest.Fail('Test not implemented yet.');
end;
procedure TTest_IBuffer_Standard.setSize;
begin
// Arrange:
// Act:
// Assert:
TTest.Fail('Test not implemented yet.');
end;
initialization
TestSuite.RegisterTestCase(TTest_IBuffer_Standard);
end.
|
// ******************************************************************
//
// Program Name : $ProgramName$
// Platform(s) : $Platforms$
// Framework : VCL
//
// Filename : AT.$ShortName$.DM.Services.Dialogs.pas/.dfm
// File Version : 1.00
// Date Created : $CreateDate$
// Author : Matthew Vesperman
//
// Description:
//
// $ProgramName$'s global dialog services data module.
//
// Revision History:
//
// v1.00 : Initial version
//
// ******************************************************************
//
// COPYRIGHT © $Year$ - PRESENT Angelic Technology
// ALL RIGHTS RESERVED WORLDWIDE
//
// ******************************************************************
{$WARN SYMBOL_PLATFORM OFF}
/// <summary>
/// $ProgramName$'s global dialog services data module.
/// </summary>
unit AT.ShortName.DM.Services.Dialogs;
interface
uses
System.SysUtils, System.Classes, Vcl.Controls, Vcl.Dialogs;
type
/// <summary>
/// Type to define a reference to a procedure to execute
/// before/after a open dialog is displayed.
/// </summary>
TATOpenDialogExecProc = reference to procedure(
var ADialog: TOpenDialog);
/// <summary>
/// Type to define a reference to a procedure to execute
/// before/after a save dialog is displayed.
/// </summary>
TATSaveDialogExecProc = reference to procedure(
var ADialog: TSaveDialog);
/// <summary>
/// Type to define a reference to a procedure to execute
/// before/after a task dialog is displayed.
/// </summary>
TATTaskDialogExecProc = reference to procedure(
var ATaskDialog: TTaskDialog);
/// <summary>
/// Global dialog services data module.
/// </summary>
/// <remarks>
/// Several methods in this class require Enable Runtime Themes
/// to be enabled in the project options.
/// </remarks>
TDlgServices = class(TDataModule)
dlgOpen: TOpenDialog;
dlgSave: TSaveDialog;
tskdlg1: TTaskDialog;
/// <summary>
/// Data module's OnCreate event handler.
/// </summary>
/// <remarks>
/// Initializes the DlgServices data module.
/// </remarks>
procedure DataModuleCreate(Sender: TObject);
public
/// <summary>
/// Displays an Open File Dialog.
/// </summary>
/// <param name="AFileName">
/// Receives the name of the selected file if the Open (Ok)
/// button was clicked, otherwise it receives an empty string.
/// </param>
/// <param name="AFilter">
/// (Optional) File type filter string.
/// </param>
/// <param name="ACaption">
/// (Optional) Title for the open dialog.
/// </param>
/// <param name="ABeforeExecute">
/// (Optional) Reference to a procedure to call before the
/// dialog box is displayed.
/// </param>
/// <param name="AAfterExecute">
/// (Optional) Reference to a procedure to call after the
/// dialog box is displayed.
/// </param>
/// <returns>
/// TRUE if the dialog's Open (Ok) button was clicked, FALSE
/// otherwise.
/// </returns>
function OpenFile(out AFileName: String;
const AFilter: String = 'All Files (*.*)|*.*';
const ACaption: String = '';
ABeforeExecute: TATOpenDialogExecProc = NIL;
AAfterExecute: TATOpenDialogExecProc = NIL): Boolean;
/// <summary>
/// Displays a Save File Dialog.
/// </summary>
/// <param name="AFileName">
/// Receives the name of the selected file if the Save (Ok)
/// button was clicked, otherwise it receives an empty string.
/// </param>
/// <param name="AFilter">
/// (Optional) File type filter string.
/// </param>
/// <param name="ACaption">
/// (Optional) Title for the save dialog.
/// </param>
/// <param name="ABeforeExecute">
/// (Optional) Reference to a procedure to call before the
/// dialog box is displayed.
/// </param>
/// <param name="AAfterExecute">
/// (Optional) Reference to a procedure to call after the
/// dialog box is displayed.
/// </param>
/// <returns>
/// TRUE if the dialog's Save (Ok) button was clicked, FALSE
/// otherwise.
/// </returns>
function SaveFile(out AFileName: String;
const AFilter: String = 'All Files (*.*)|*.*';
const ACaption: String = '';
ABeforeExecute: TATSaveDialogExecProc = NIL;
AAfterExecute: TATSaveDialogExecProc = NIL): Boolean;
/// <summary>
/// Displays an error message dialog.
/// </summary>
/// <param name="AInstruct">
/// Instruction text for the error message dialog.
/// </param>
/// <param name="AContent">
/// Descriptive text for the error message dialog.
/// </param>
/// <param name="ACaption">
/// The caption for the error message dialog.
/// </param>
/// <param name="AExpText">
/// Detail text for the error message dialog.<br />If this
/// parameter is an empty string the Show Details button is
/// hidden.
/// </param>
/// <remarks>
/// This method requires Enable Runtime Themes to be
/// enabled in the project options.
/// </remarks>
class procedure ShowErrorDlg(const AInstruct: String = '';
const AContent: String = ''; const ACaption: String = 'Error';
const AExpText: String = '');
/// <summary>
/// Displays an information message dialog.
/// </summary>
/// <param name="AInstruct">
/// Instruction text for the info message dialog.
/// </param>
/// <param name="AContent">
/// Descriptive text for the info message dialog.
/// </param>
/// <param name="ACaption">
/// The caption for the info message dialog.
/// </param>
/// <param name="AExpText">
/// Detail text for the info message dialog.<br />If this
/// parameter is an empty string the Show Details button is
/// hidden.
/// </param>
/// <remarks>
/// This method requires Enable Runtime Themes to be
/// enabled in the project options.
/// </remarks>
class procedure ShowInfoDlg(const AInstruct: String = '';
const AContent: String = ''; const ACaption: String = '';
const AExpText: String = '');
/// <summary>
/// Displays a simple message box with an OK button. The
/// application's main window caption appears as the caption of
/// the message box.
/// </summary>
/// <param name="AMessage">
/// The message string that appears in the message box.
/// </param>
class procedure ShowMessage(const AMessage: String);
/// <summary>
/// Displays a simple message box with a formatted message and
/// an OK button. The application's main window caption appears
/// as the caption of the message box.
/// </summary>
/// <param name="AMessage">
/// A format string for the message that appears in the message
/// box.
/// </param>
/// <param name="AParams">
/// Provides the parameters that are assembled into the message
/// </param>
class procedure ShowMessageFmt(const AMessage: String;
AParams: Array of TVarRec);
/// <summary>
/// Displays a simple message box with an OK button at a
/// specified location. The application's main window caption
/// appears as the caption of the message box.
/// </summary>
/// <param name="AMessage">
/// The message string that appears in the message box.
/// </param>
/// <param name="X">
/// The horizontal screen coordinate where the message box
/// should appear. A value of –1 means that the message box can
/// appear anywhere in the specified dimension.
/// </param>
/// <param name="Y">
/// The vertical screen coordinate where the message box should
/// appear. A value of –1 means that the message box can appear
/// anywhere in the specified dimension.
/// </param>
class procedure ShowMessagePos(const AMessage: String;
X, Y: Integer);
/// <summary>
/// Displays a message dialog to ask the user a Yes or No
/// question.
/// </summary>
/// <param name="AModalResult">
/// Receives the modal result of the query dialog.
/// </param>
/// <param name="AInstruct">
/// Instruction text for the query dialog.
/// </param>
/// <param name="AContent">
/// Descriptive text for the query dialog.
/// </param>
/// <param name="ACaption">
/// The caption for the query dialog.
/// </param>
/// <param name="AExpText">
/// Detail text for the query dialog.<br />If this parameter
/// is an empty string the Show Details button is hidden.
/// </param>
/// <param name="AMainIcon">
/// Indicates which standard main icon to display in the Task
/// Dialog.<br />Legal values include tdiNone, tdiWarning,
/// tdiError, tdiInformation, and tdiShield.
/// </param>
/// <param name="ABeforeExecute">
/// (Optional) Reference to a procedure to call before the
/// dialog box is displayed.
/// </param>
/// <param name="AAfterExecute">
/// (Optional) Reference to a procedure to call after the
/// dialog box is displayed.
/// </param>
/// <returns>
/// TRUE if the Yes button was clicked, FALSE otherwise.
/// </returns>
/// <remarks>
/// This method requires Enable Runtime Themes to be
/// enabled in the project options.
/// </remarks>
class function ShowQueryDlg(out AModalResult: TModalResult;
const AInstruct: String = ''; const AContent: String = '';
const ACaption: String = 'Query'; const AExpText: String = '';
AMainIcon: TTaskDialogIcon = tdiInformation;
ABeforeExecute: TATTaskDialogExecProc = NIL;
AAfterExecute: TATTaskDialogExecProc = NIL): Boolean;
/// <summary>
/// Displays a security (shield) message dialog.
/// </summary>
/// <param name="AInstruct">
/// Instruction text for the security message dialog.
/// </param>
/// <param name="AContent">
/// Descriptive text for the security message dialog.
/// </param>
/// <param name="ACaption">
/// The caption for the security message dialog.
/// </param>
/// <param name="AExpText">
/// Detail text for the security message dialog.<br />If this
/// parameter is an empty string the Show Details button is
/// hidden.
/// </param>
/// <remarks>
/// This method requires Enable Runtime Themes to be
/// enabled in the project options.
/// </remarks>
class procedure ShowShieldDlg(const AInstruct: String = '';
const AContent: String = ''; const ACaption: String = '';
const AExpText: String = '');
/// <summary>
/// Displays a task message dialog with an OK button.
/// </summary>
/// <param name="AInstruct">
/// Instruction text for the message dialog.
/// </param>
/// <param name="AContent">
/// Descriptive text for the message dialog.
/// </param>
/// <param name="ACaption">
/// The caption for the message dialog.
/// </param>
/// <param name="AExpText">
/// Detail text for the message dialog.<br />If this parameter
/// is an empty string the Show Details button is hidden.
/// </param>
/// <param name="AMainIcon">
/// Indicates which standard main icon to display in the Task
/// Dialog.<br />Legal values include tdiNone, tdiWarning,
/// tdiError, tdiInformation, and tdiShield.
/// </param>
/// <param name="ABeforeExecute">
/// (Optional) Reference to a procedure to call before the
/// dialog box is displayed.
/// </param>
/// <param name="AAfterExecute">
/// (Optional) Reference to a procedure to call after the
/// dialog box is displayed.
/// </param>
/// <param name="AModalResult">
/// Receives the modal result of the message dialog.
/// </param>
/// <remarks>
/// This method requires Enable Runtime Themes to be
/// enabled in the project options.
/// </remarks>
class procedure ShowTaskMessageDlg(const AInstruct: String = '';
const AContent: String = ''; const ACaption: String = '';
const AExpText: String = '';
const AMainIcon: TTaskDialogIcon = tdiNone;
ABeforeExecute: TATTaskDialogExecProc = NIL;
AAfterExecute: TATTaskDialogExecProc = NIL); overload;
/// <summary>
/// Displays a task message dialog with an OK button.
/// </summary>
/// <param name="AModalResult">
/// Receives the modal result of the message dialog.
/// </param>
/// <param name="AInstruct">
/// Instruction text for the message dialog.
/// </param>
/// <param name="AContent">
/// Descriptive text for the message dialog.
/// </param>
/// <param name="ACaption">
/// The caption for the message dialog.
/// </param>
/// <param name="AExpText">
/// Detail text for the message dialog.<br />If this parameter
/// is an empty string the Show Details button is hidden.
/// </param>
/// <param name="AMainIcon">
/// Indicates which standard main icon to display in the Task
/// Dialog.<br />Legal values include tdiNone, tdiWarning,
/// tdiError, tdiInformation, and tdiShield.
/// </param>
/// <param name="ABeforeExecute">
/// (Optional) Reference to a procedure to call before the
/// dialog box is displayed.
/// </param>
/// <param name="AAfterExecute">
/// (Optional) Reference to a procedure to call after the
/// dialog box is displayed.
/// </param>
/// <returns>
/// TRUE if the OK button was clicked, FALSE otherwise.
/// </returns>
/// <remarks>
/// This method requires Enable Runtime Themes to be
/// enabled in the project options.
/// </remarks>
class function ShowTaskMessageDlg(out AModalResult: TModalResult;
const AInstruct: String = ''; const AContent: String = '';
const ACaption: String = ''; const AExpText: String = '';
const AMainIcon: TTaskDialogIcon = tdiNone;
ABeforeExecute: TATTaskDialogExecProc = NIL;
AAfterExecute: TATTaskDialogExecProc = NIL): Boolean; overload;
/// <summary>
/// Displays a warning message dialog.
/// </summary>
/// <param name="AInstruct">
/// Instruction text for the warning message dialog.
/// </param>
/// <param name="AContent">
/// Descriptive text for the warning message dialog.
/// </param>
/// <param name="ACaption">
/// The caption for the warning message dialog.
/// </param>
/// <param name="AExpText">
/// Detail text for the warning message dialog. <br />If this
/// parameter is an empty string the Show Details button is
/// hidden.
/// </param>
/// <remarks>
/// This method requires Enable Runtime Themes to be
/// enabled in the project options.
/// </remarks>
class procedure ShowWarningDlg(const AInstruct: String = '';
const AContent: String = '';
const ACaption: String = 'Warning';
const AExpText: String = '');
end;
/// <summary>
/// Returns a reference to the global DlgServices data module.
/// </summary>
function DlgServices: TDlgServices;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
uses
AT.GarbageCollector, Vcl.Forms, AT.ShortName.Vcl.Dialogs.SplashDX,
AT.ShortName.ResourceStrings;
{$R *.dfm}
var
/// <summary>
/// Module level garbage collector object.
/// </summary>
MGC: IATGarbageCollector;
/// <summary>
/// Holds a reference to the global DlgServices data module.
/// </summary>
dmDlgServices: TDlgServices;
function DlgServices: TDlgServices;
begin
if (NOT Assigned(dmDlgServices)) then
begin
dmDlgServices := TATGC.Collect(TDlgServices.Create(NIL), MGC);
end;
Result := dmDlgServices;
end;
procedure TDlgServices.DataModuleCreate(Sender: TObject);
begin
TdlgSplashDX.ChangeStartMessage(rstrStartInitDlgSvc, 500);
end;
function TDlgServices.OpenFile(out AFileName: String; const AFilter:
String = 'All Files (*.*)|*.*'; const ACaption: String = '';
ABeforeExecute: TATOpenDialogExecProc = NIL; AAfterExecute:
TATOpenDialogExecProc = NIL): Boolean;
begin
dlgOpen.Filter := AFilter;
dlgOpen.Title := ACaption;
if (Assigned(ABeforeExecute)) then
ABeforeExecute(dlgOpen);
Result := dlgOpen.Execute(Application.MainFormHandle);
if (Assigned(AAfterExecute)) then
AAfterExecute(dlgOpen);
if (Result) then
AFileName := dlgOpen.FileName
else
AFileName := EmptyStr;
end;
function TDlgServices.SaveFile(out AFileName: String; const AFilter:
String = 'All Files (*.*)|*.*'; const ACaption: String = '';
ABeforeExecute: TATSaveDialogExecProc = NIL; AAfterExecute:
TATSaveDialogExecProc = NIL): Boolean;
begin
dlgSave.Filter := AFilter;
dlgSave.Title := ACaption;
if (Assigned(ABeforeExecute)) then
ABeforeExecute(dlgSave);
Result := dlgSave.Execute(Application.MainFormHandle);
if (Assigned(AAfterExecute)) then
AAfterExecute(dlgSave);
if (Result) then
AFileName := dlgOpen.FileName
else
AFileName := EmptyStr;
end;
class procedure TDlgServices.ShowErrorDlg(const AInstruct: String =
''; const AContent: String = ''; const ACaption: String =
'Error'; const AExpText: String = '');
begin
TDlgServices.ShowTaskMessageDlg(AInstruct, AContent, ACaption,
AExpText, tdiError);
end;
class procedure TDlgServices.ShowInfoDlg(const AInstruct: String =
''; const AContent: String = ''; const ACaption: String = '';
const AExpText: String = '');
begin
TDlgServices.ShowTaskMessageDlg(AInstruct, AContent, ACaption,
AExpText, tdiInformation);
end;
class procedure TDlgServices.ShowMessage(const AMessage: String);
begin
Vcl.Dialogs.ShowMessage(AMessage);
end;
class procedure TDlgServices.ShowMessageFmt(const AMessage: String;
AParams: Array of TVarRec);
begin
Vcl.Dialogs.ShowMessageFmt(AMessage, AParams);
end;
class procedure TDlgServices.ShowMessagePos(const AMessage: String;
X, Y: Integer);
begin
Vcl.Dialogs.ShowMessagePos(AMessage, X, Y);
end;
class function TDlgServices.ShowQueryDlg(out AModalResult:
TModalResult; const AInstruct: String = ''; const AContent:
String = ''; const ACaption: String = 'Query'; const AExpText:
String = ''; AMainIcon: TTaskDialogIcon = tdiInformation;
ABeforeExecute: TATTaskDialogExecProc = NIL; AAfterExecute:
TATTaskDialogExecProc = NIL): Boolean;
var
AGC: IATGarbageCollector;
ADlg: TTaskDialog;
ACap: String;
begin
ADlg := TATGC.Collect(TTaskDialog.Create(NIL), AGC);
if (ACaption.IsEmpty) then
ACap := 'Query'
else
ACap := ACaption;
ADlg.CommonButtons := [tcbYes, tcbNo];
ADlg.DefaultButton := tcbYes;
ADlg.Flags := [tfUseHiconMain, tfAllowDialogCancellation];
ADlg.Title := AInstruct;
ADlg.Text := AContent;
ADlg.Caption := ACap;
ADlg.ExpandedText := AExpText;
ADlg.MainIcon := AMainIcon;
if (Assigned(ABeforeExecute)) then
ABeforeExecute(ADlg);
if (ADlg.Execute) then
Result := (ADlg.ModalResult = mrYes)
else
Result := False;
AModalResult := ADlg.ModalResult;
if (Assigned(AAfterExecute)) then
AAfterExecute(ADlg);
end;
class procedure TDlgServices.ShowShieldDlg(const AInstruct: String =
''; const AContent: String = ''; const ACaption: String = '';
const AExpText: String = '');
begin
TDlgServices.ShowTaskMessageDlg(AInstruct, AContent, ACaption,
AExpText, tdiShield);
end;
class procedure TDlgServices.ShowTaskMessageDlg(const AInstruct:
String = ''; const AContent: String = ''; const ACaption: String
= ''; const AExpText: String = ''; const AMainIcon:
TTaskDialogIcon = tdiNone; ABeforeExecute: TATTaskDialogExecProc
= NIL; AAfterExecute: TATTaskDialogExecProc = NIL);
var
AJunk: TModalResult;
begin
TDlgServices.ShowTaskMessageDlg(AJunk, AInstruct, AContent,
ACaption, AExpText, AMainIcon, ABeforeExecute, AAfterExecute);
end;
class function TDlgServices.ShowTaskMessageDlg(
out AModalResult: TModalResult; const AInstruct: String = '';
const AContent: String = ''; const ACaption: String = '';
const AExpText: String = '';
const AMainIcon: TTaskDialogIcon = tdiNone;
ABeforeExecute: TATTaskDialogExecProc = NIL;
AAfterExecute: TATTaskDialogExecProc = NIL): Boolean;
var
AGC: IATGarbageCollector;
ADlg: TTaskDialog;
ACap: String;
begin
ADlg := TATGC.Collect(TTaskDialog.Create(NIL), AGC);
if (ACaption.IsEmpty) then
ACap := Application.Title
else
ACap := ACaption;
ADlg.CommonButtons := [tcbOk];
ADlg.DefaultButton := tcbOk;
ADlg.Flags := [tfAllowDialogCancellation];
ADlg.Title := AInstruct;
ADlg.Text := AContent;
ADlg.Caption := ACap;
ADlg.ExpandedText := AExpText;
ADlg.MainIcon := AMainIcon;
if (Assigned(ABeforeExecute)) then
ABeforeExecute(ADlg);
Result := ADlg.Execute;
AModalResult := ADlg.ModalResult;
if (Assigned(AAfterExecute)) then
AAfterExecute(ADlg);
end;
class procedure TDlgServices.ShowWarningDlg(const AInstruct: String =
''; const AContent: String = ''; const ACaption: String =
'Warning'; const AExpText: String = '');
begin
TDlgServices.ShowTaskMessageDlg(AInstruct, AContent, ACaption,
AExpText, tdiWarning);
end;
{$WARN SYMBOL_PLATFORM ON}
end.
|
unit dinamic_fifo;
{* implementação de estrutura de dados fila utilizando ponteiros *}
interface
{* definição de tipos *}
type data = integer;
type node = record
item : data;
next : ^node;
end;
type pointer = ^node;
type fifo = record
last : pointer;
first : pointer;
size : integer;
end;
{* definição de métodos para manipulação da fila *}
procedure init(var mFifo:fifo);
function isEmpty(var mFifo:fifo):boolean;
procedure add(var mFifo:fifo; item:data);
function remove(var mFifo:fifo; var item:data):boolean;
function size(var mFifo:fifo):integer;
implementation
procedure init(var mFifo:fifo);
begin
new(mFifo.first);
mFifo.last := mFifo.first;
mFifo.first^.next := NIL;
mFifo.size := 0;
end;
function isEmpty(var mFifo:fifo):boolean;
begin
isEmpty := (mFifo.last = mFifo.first);
end;
procedure add(var mFifo:fifo; item:data);
begin
new(mFifo.last^.next);
mFifo.last := mFifo.last^.next;
mFifo.last^.item := item;
mFifo.last^.next := NIL;
mFifo.size := mFifo.size + 1;
end;
function remove(var mFifo:fifo; var item:data):boolean;
var auxFifo:pointer;
begin
if isEmpty(mFifo) then
remove := false
else begin
auxFifo := mFifo.first;
mFifo.first := mFifo.first^.next;
item := mFifo.first^.item;
dispose(auxFifo);
mFifo.size := mFifo.size - 1;
remove := true;
end;
end;
function size(var mFifo:fifo):integer;
begin
size := mFifo.size;
end;
end. |
unit DUnitX.Tests.TestDataProvider;
interface
uses
System.Generics.Collections,
DUnitX.Types,
DUnitX.InternalDataProvider,
DUnitX.TestDataProvider,
DUnitX.TestFramework;
type
TSampleData = Record
v1,v2 : integer; //simple 2 integer values
AddEx : integer; //Expected value for Add
Equal : boolean; //Expected value for Equal-Compare
End;
TSampleProvider = Class(TTestDataProvider)
private
flist : TList<TSampleData>;
Procedure InitTestData;
public
Constructor Create;Override;
function GetCaseCount(const methodName : string) : Integer; override;
function GetCaseName(const methodName : string; const caseNumber : integer) : string; override;
function GetCaseParams(const methodName : string ; const caseNumber : integer) : TValuearray; override;
Destructor Destroy;override;
End;
[TestFixture]
TestFixtureProviderTest = class(TObject)
public
[Test]
[TestCaseProvider('Sampleprovider')]
Procedure spTstAdd(const value1,Value2:integer;expected:integer);
[Test]
[TestCaseProvider('Sampleprovider')]
Procedure spTstEqual(const value1,Value2:integer;expected:boolean);
end;
implementation
{ TSampleProvider }
constructor TSampleProvider.Create;
begin
inherited;
flist := TList<TSampleData>.create;
InitTestData;
end;
destructor TSampleProvider.Destroy;
begin
flist.free;
inherited;
end;
function TSampleProvider.GetCaseCount(const methodName : string) : Integer;
begin
result := flist.count;
end;
function TSampleProvider.GetCaseName(const methodName : string; const caseNumber : integer) : string;
begin
result := '';
if (Methodname = 'spTstAdd') then
result := 'Addtest'
else
result := 'Comparetest';
end;
function TSampleProvider.GetCaseParams(const methodName : string ; const caseNumber : integer) : TValuearray;
begin
SetLength(result,0);
if (caseNumber >=0) and (caseNumber < flist.count) then
begin
SetLength(result,3);
result[0] := flist[caseNumber].v1;
result[1] := flist[caseNumber].v2;
if (Methodname = 'spTstAdd') then
result[2] := flist[caseNumber].AddEx
else
result[2] := flist[caseNumber].Equal;
end;
end;
procedure TSampleProvider.InitTestData;
var
item : TSampleData;
begin
item.v1 := 1;
item.v2 := 1;
item.AddEx := 2;
item.Equal := true;
flist.add(item);
item.v1 := 1;
item.v2 := 2;
item.AddEx := 3;
item.Equal := false;
flist.add(item);
item.v1 := 2;
item.v2 := 3;
item.AddEx := 5;
item.Equal := false;
flist.add(item);
item.v1 := 2;
item.v2 := 2;
item.AddEx := 4;
item.Equal := true;
flist.add(item);
item.v1 := 3;
item.v2 := 3;
item.AddEx := 6;
item.Equal := true;
flist.add(item);
end;
{ TestFixtureProviderTest }
procedure TestFixtureProviderTest.spTstAdd(const value1, Value2: integer;
expected: integer);
begin
Assert.AreEqual(expected,(value1+value2),'Ok');
end;
procedure TestFixtureProviderTest.spTstEqual(const value1, Value2: integer;
expected: boolean);
begin
Assert.AreEqual(expected,(value1=value2),'Ok');
end;
initialization
TestDataProviderManager.RegisterProvider('Sampleprovider',TSampleProvider);
TDUnitX.RegisterTestFixture(TestFixtureProviderTest);
end.
|
unit LoggerUnit;
//------------------------------------------------------------------------------
// Модуль журналирования
//------------------------------------------------------------------------------
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, syncobjs;
type
{ TLogger }
TLogger = class(TObject)
private
cs: TCriticalSection;
local_log: boolean;
public
constructor Create;
destructor Destroy; override;
procedure LogText(const st:string; const force_log:boolean = false);
procedure LogError(const err_code:integer; const log:string);
procedure startLog;
procedure pauseLog;
end;
var MyLogger: TLogger;
implementation
{ TLogger }
constructor TLogger.Create;
begin
inherited Create;
local_log := false;
cs := TCriticalSection.Create;
end;
destructor TLogger.Destroy;
begin
cs.Free;
inherited Destroy;
end;
procedure TLogger.LogText(const st: string; const force_log: boolean);
var f: textfile;
tmp,fnm: string;
begin
if local_log or force_log
then
begin
cs.Enter;
try
fnm := ExtractFilePath(ParamStr(0))+'log.txt';
AssignFile(f,fnm);
if FileExists(fnm)
then Append(f)
else Rewrite(f);
try
tmp := FormatDateTime('yyyy.mm.dd hh":"nn":"ss',now)+#9+st;
Writeln(f,tmp);
finally
CloseFile(f);
end;
finally
cs.Leave;
end;
end;
end;
procedure TLogger.LogError(const err_code: integer; const log: string);
begin
LogText('Код ошибки: '+IntToStr(err_code), false);
LogText(log, false);
end;
procedure TLogger.startLog;
begin
local_log := true;
end;
procedure TLogger.pauseLog;
begin
local_log := false;
end;
initialization
finalization
end.
|
(*
* "THE BEER-WARE LICENSE" (Revision 42):
* d0p1 <d0p1@yahoo.com> wrote this file. As long as you retain this notice you
* can do whatever you want with this stuff. If we meet some day, and you think
* this stuff is worth it, you can buy me a beer in return.
*)
UNIT base58;
{$mode objfpc}{$H+}
INTERFACE
USES
strutils,
gmp,
sysutils;
FUNCTION Base58Encode(const data: pchar): string;
FUNCTION Base58Decode(const data: string): pchar;
CONST
B58_ALPHABET: shortstring = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
IMPLEMENTATION
FUNCTION RawToHexString(const data: pchar): string;
BEGIN
SetLength(Result, 64);
BinToHex(@data[0], @Result[1], 32);
END;
FUNCTION HexStringToRaw(const data: string): pchar;
BEGIN
result := StrAlloc(32);
HexToBin(@data[1], @result[0], 64);
END;
FUNCTION Base58Encode(const data: pchar): string;
VAR
hexstring: string;
num: mpz_t;
tmp: mpz_t;
divisor: mpz_t;
i: LongInt;
res: shortstring;
BEGIN
mpz_init(tmp);
mpz_init(num);
mpz_init_set_ui(divisor, 58);
hexstring := RawToHexString(data);
res := '';
mpz_set_str(num, pchar(hexstring), 16);
WHILE (mpz_cmp_ui(num, 0) > 0) DO
BEGIN
mpz_mod(tmp, num, divisor);
i := mpz_get_ui(tmp);
res := Copy(B58_ALPHABET, i + 1, 1) + res;
mpz_fdiv_q(num, num, divisor);
END;
FOR i := 0 TO 31 DO
BEGIN
IF data[i] = #0
THEN res := Copy(B58_ALPHABET, 0, 1) + res
ELSE BREAK;
END;
mpz_clear(tmp);
mpz_clear(num);
mpz_clear(divisor);
result := res;
END;
FUNCTION Base58Decode(const data: string): pchar;
VAR
num: mpz_t;
hexstring: string;
c: char;
reversed: string;
BEGIN
mpz_init_set_ui(num, 0);
FOR c IN data DO
BEGIN
mpz_mul_ui(num, num, 58);
mpz_add_ui(num, num, pos(c, B58_ALPHABET) - 1);
END;
hexstring := mpz_get_str(NIL, 16, num);
mpz_clear(num);
reversed := ReverseString(data);
FOR c IN reversed DO
BEGIN
IF c = B58_ALPHABET[1]
THEN hexstring := '00' + hexstring
ELSE BREAK;
END;
result := HexStringToRaw(hexstring);
END;
END.
|
unit VarSYS;
interface
uses
DB, StdCtrls, sysutils;
Const
MensagemLookUp='Não Encontrado';
Var
UsuarioCorrente,
EmpresaCorrente,
TerminalCorrente, TimeOutIntegrador, TimeOutIntegradorInicial : Integer;
Retaguarda,
Exporta,
UsuarioMaster, TranspVeiculo, EsperaParaPerguntar : Boolean;
FieldLookup : TField;
MatrizFilial,
FieldOrigem, TimeOutIntegradorSTR : String;
DataSetLookup : TDataSet;
EditLookup : TEdit;
DSMasterSys : TDataSource;
ClienteCadastro, UsaPrecoVenda, ProdutoDescricao, ProdutoReferencia, IntegracaoAutomatica, ObsCliente : String;
ValorVenda : Double;
function TabelaNaLista(Tabela : string) : boolean;
function TabelaNaListaExportaCadastro(Tabela : String) : Boolean;
implementation
function TabelaNaLista(Tabela : string) : boolean ;
begin
// Lista de tabelas que nao devem ser importadas ou exportadas, qdo uma Filial esta Exportando
Result := False;
Tabela := UpperCase(Tabela);
if (Tabela = 'ALINEA') or
(Tabela = 'BANCO') or
(Tabela = 'CARTAAVISOCOBRANCA') or
(Tabela = 'CARTAAVISOSPC') or
(Tabela = 'CARTAPRIMEIROAVISO') or
(Tabela = 'CARTASEGUNDOAVISO') or
(Tabela = 'CFOP') or
(Tabela = 'CLASSE') or
(Tabela = 'CLASSEMODULO') or
(Tabela = 'CLASSETABELA') or
(Tabela = 'CLASSEUSUARIO') or
(Tabela = 'CLASSIFICACAOFISCAL') or
(Tabela = 'COBRADOR') or
(Tabela = 'CONFIGCOMPRAS') or
(Tabela = 'CONFIGCONTA') or
(Tabela = 'CONFIGCREDIARIO') or
(Tabela = 'CONFIGETIQUETACODIGOBARRA') or
(Tabela = 'CONFIGGERAL') or
(Tabela = 'CONFIGVENDA') or
(Tabela = 'CONVENIO') or
(Tabela = 'COR') or
(Tabela = 'DECRETO') or
(Tabela = 'ECFALIQUOTAICMS') or
(Tabela = 'EMPRESA') or
(Tabela = 'EMPRESASERIE') or
(Tabela = 'FECHAMENTOCAIXA') or
(Tabela = 'FORNECEDOR') or
(Tabela = 'GRADE') or
(Tabela = 'GRADETAMANHO') or
(Tabela = 'GRUPO') or
(Tabela = 'HISTORICOPADRAO') or
(Tabela = 'ICMS') or
(Tabela = 'ICMSUF') or
(Tabela = 'MARCA') or
(Tabela = 'MOTIVOBLOQUEIO') or
(Tabela = 'NUMERARIO') or
(Tabela = 'NUMERARIOTOTALIZADOR') or
(Tabela = 'NUMERARIOTOTALIZADORECF') or
(Tabela = 'OPERACAOBANCO') or
(Tabela = 'OPERACAOCAIXA') or
(Tabela = 'OPERACAOCAIXATOTALIZADOR') or
(Tabela = 'OPERACAOESTOQUE') or
(Tabela = 'OPERACAOTESOURARIA') or
(Tabela = 'PLANODECONTAS') or
(Tabela = 'PLANOPAGAMENTO') or
(Tabela = 'PLANOPAGAMENTOPARCELA') or
(Tabela = 'PLANORECEBIMENTO') or
(Tabela = 'PLANORECEBIMENTOPARCELA') or
(Tabela = 'PORTADOR') or
(Tabela = 'PRODUTO') or
(Tabela = 'PRODUTOREAJUSTE') or
(Tabela = 'PROFISSAO') or
(Tabela = 'PROVEDORCARTAO') or
(Tabela = 'SERIE') or
(Tabela = 'SITUACAOOS') or
(Tabela = 'SUBGRUPO') or
(Tabela = 'TIPOCLIENTE') or
(Tabela = 'TIPOCUSTO') or
(Tabela = 'TIPODOCUMENTO') or
(Tabela = 'TIPOFORNECEDOR') or
(Tabela = 'TIPOMOVIMENTOBANCO') or
(Tabela = 'TIPOOS') or
(Tabela = 'TIPOSERVICOOS') or
(Tabela = 'TIPOVENDA') or
(Tabela = 'TOTALIZADORCAIXA') or
(Tabela = 'TRANSPORTADORA') or
(Tabela = 'UNIDADE') or
(Tabela = 'USUARIO') or
(Tabela = 'VARIACAO') or
(Tabela = 'VENDEDOR') or
(Tabela = 'LOTE') or
(Tabela = 'VENDEDORCOMISSAO') then
Result := True;
end ;
function TabelaNaListaExportaCadastro(Tabela : String) : Boolean;
begin
Result := False;
Tabela := UpperCase(Tabela);
if (Tabela = 'ALINEA') or
(Tabela = 'BANCO') or
(Tabela = 'CFOP') or
(Tabela = 'CLASSIFICACAOFISCAL') or
(Tabela = 'CLIENTE') or
(Tabela = 'CLIENTEAUTORIZACOMPRA') or
(Tabela = 'CLIENTECONTATO') or
(Tabela = 'CLIENTEDEPENDENTE') or
(Tabela = 'CLIENTEENDERECOCOBRANCA') or
(Tabela = 'CLIENTEENDERECOCOMERCIAL') or
(Tabela = 'CLIENTEENDERECOENTREGA') or
(Tabela = 'CLIENTEHISTORICO') or
(Tabela = 'CLIENTERECEITUARIO') or
(Tabela = 'CLIENTEREFERENCIA') or
(Tabela = 'COBRADOR') or
(Tabela = 'CONVENIO') or
(Tabela = 'COR') or
(Tabela = 'DECRETO') or
(Tabela = 'ECF') or
(Tabela = 'ECFALIQUOTAICMS') or
(Tabela = 'EMPRESA') or
(Tabela = 'FORNECEDOR') or
(Tabela = 'GRADE') or
(Tabela = 'GRADETAMANHO') or
(Tabela = 'GRUPO') or
(Tabela = 'HISTORICOPADRAO') or
(Tabela = 'ICMS') or
(Tabela = 'ICMSUF') or
(Tabela = 'INTEGRACAO') or
(Tabela = 'MARCA') or
(Tabela = 'MOTIVOBLOQUEIO') or
(Tabela = 'NUMERARIO') or
(Tabela = 'NUMERARIOTOTALIZADOR') or
(Tabela = 'NUMERARIOTOTALIZADORECF') or
(Tabela = 'LOTE') or
(Tabela = 'MARCA') or
(Tabela = 'MOTIVOBLOQUEIO') or
(Tabela = 'OPERACAOBANCO') or
(Tabela = 'OPERACAOCAIXA') or
(Tabela = 'OPERACAOCAIXATOTALIZADOR') or
(Tabela = 'OPERACAOESTOQUE') or
(Tabela = 'OPERACAOTESOURARIA') or
(Tabela = 'PLANODECONTAS') or
(Tabela = 'PLANOPAGAMENTO') or
(Tabela = 'PLANOPAGAMENTOPARCELA') or
(Tabela = 'PLANORECEBIMENTO') or
(Tabela = 'PLANORECEBIMENTOPARCELA') or
(Tabela = 'PORTADOR') or
(Tabela = 'PRODUTO') or
(Tabela = 'PRODUTOCOMPOSICAO') or
(Tabela = 'PRODUTOFORNECEDOR') or
(Tabela = 'PRODUTOREAJUSTE') or
(Tabela = 'PRODUTOSALDO') or
(Tabela = 'PROFISSAO') or
(Tabela = 'PROVEDORCARTAO') or
(Tabela = 'SERIE') or
(Tabela = 'SITUACAOOS') or
(Tabela = 'SUBGRUPO') or
(Tabela = 'TABELAPRECO') or
(Tabela = 'TABELAPRECOPRODUTO') or
(Tabela = 'TERMINAL') or
(Tabela = 'TIPOCLIENTE') or
(Tabela = 'TIPOCUSTO') or
(Tabela = 'TIPODOCUMENTO') or
(Tabela = 'TIPOFORNECEDOR') or
(Tabela = 'TIPOMOVIMENTOBANCO') or
(Tabela = 'TIPOOS') or
(Tabela = 'TIPOSERVICOOS') or
(Tabela = 'TIPOVENDA') or
(Tabela = 'TOTALIZADORCAIXA') or
(Tabela = 'TRANSPORTADORA') or
(Tabela = 'UNIDADE') or
(Tabela = 'USUARIO') or
(Tabela = 'VARIACAO') or
(Tabela = 'VENDEDOR') or
(Tabela = 'VENDEDORCOMISSAO') then
Result := True;
end;
end.
|
unit TelegaPi.Types.Enums;
interface
type
{$SCOPEDENUMS ON}
/// <summary>
/// Type of action to broadcast.
/// </summary>
/// <remarks>
/// We only recommend using this method when a response from the bot will
/// take a noticeable amount of time to arrive.
/// </remarks>
/// <example>
/// Example: The ImageBot needs some time to process a request and upload
/// the image. Instead of sending a text message along the lines of
/// “Retrieving image, please wait…”, the bot may use sendChatAction with
/// action = upload_photo. The user will see a “sending photo” status for
/// the bot.
/// </example>
TtgSendChatAction = (
/// <summary>
/// for text messages
/// </summary>
Typing,
/// <summary>
/// for photos
/// </summary>
UploadPhoto,
/// <summary>
/// for videos
/// </summary>
Record_video,
/// <summary>
/// for videos
/// </summary>
UploadVideo,
/// <summary>
/// for audio files
/// </summary>
Record_audio,
/// <summary>
/// for audio files
/// </summary>
Upload_audio,
/// <summary>
/// for general files
/// </summary>
Upload_document,
/// <summary>
/// for location data
/// </summary>
Find_location,
/// <summary>
/// for video notes
/// </summary>
Record_video_note,
/// <summary>
/// for video notes
/// </summary>
Upload_video_note);
/// <summary>
/// ChatMember status
/// </summary>
TtgChatMemberStatus = (
/// <summary>
/// Creator of the <see cref="Chat" />
/// </summary>
Creator,
/// <summary>
/// Administrator of the <see cref="Chat" />
/// </summary>
Administrator,
/// <summary>
/// Normal member of the <see cref="Chat" />
/// </summary>
Member, Restricted,
/// <summary>
/// A <see cref="User" /> who left the <see cref="Chat" />
/// </summary>
Left,
/// <summary>
/// A <see cref="User" /> who was kicked from the <see cref="Chat" />
/// </summary>
Kicked);
/// <summary>
/// Type of a <see cref="Chat" />
/// </summary>
TtgChatType = (
/// <summary>
/// Normal one to one <see cref="Chat" />
/// </summary>
private,
/// <summary>
/// Normal groupchat
/// </summary>
Group,
/// <summary>
/// A channel
/// </summary>
Channel,
/// <summary>
/// A supergroup
/// </summary>
Supergroup);
/// <summary>
/// Type of a <see cref="FileToSend" />
/// </summary>
TtgFileType = (
/// <summary>
/// Unknown FileType
/// </summary>
Unknown,
/// <summary>
/// FileStream
/// </summary>
Stream,
/// <summary>
/// FileId
/// </summary>
Id,
/// <summary>
/// File Url
/// </summary>
Url);
/// <summary>
/// The type of a Message
/// </summary>
TtgMessageType = (UnknownMessage = 0, TextMessage, PhotoMessage, AudioMessage,
VideoMessage, VideoNoteMessage, VoiceMessage, DocumentMessage,
StickerMessage, GameMessage, LocationMessage, ContactMessage, ServiceMessage,
VenueMessage);
/// <summary>
/// Text parsing mode
/// </summary>
/// <example>
/// <para>
/// Markdown style
/// </para>
/// <para>
/// *bold text* <br />_italic text_ <br />
/// [text](http://www.example.com/) <br />`inline fixed-width code` <br />
/// ```text <br />pre-formatted fixed-width code block <br />```
/// </para>
/// <para>
/// Html:
/// </para>
/// <para>
/// <b>bold</b>, <strong>bold</strong> <br />
/// <i>italic</i>, <em>italic</em> <br /><a
/// href="http://www.example.com/">inline URL</a> <br />
/// <code>inline fixed-width code</code> <br />
/// <pre>pre-formatted fixed-width code block</pre> <br /><br />
/// </para>
/// </example>
TtgParseMode = (default = 0,
/// <summary>
/// To use this mode, pass Markdown in the parse_mode field when using
/// sendMessage
/// </summary>
Markdown,
/// <summary>
/// To use this mode, pass HTML in the parse_mode field when using
/// sendMessage
/// </summary>
Html);
/// <summary>
/// The type of an Update
/// </summary>
TtgUpdateType = (
/// <summary>
/// Update Type is unknown
/// </summary>
UnknownUpdate = 0,
/// <summary>
/// The <see cref="Update" /> contains a <see cref="Message" />.
/// </summary>
MessageUpdate,
/// <summary>
/// The <see cref="Update" /> contains an <see cref="InlineQuery" />.
/// </summary>
InlineQueryUpdate,
/// <summary>
/// The <see cref="Update" /> contains a <see cref="ChosenInlineResult" />
/// .
/// </summary>
ChosenInlineResultUpdate,
/// <summary>
/// The <see cref="Update" /> contins a <see cref="CallbackQuery" />
/// </summary>
CallbackQueryUpdate,
/// <summary>
/// The <see cref="Update" /> contains an edited <see cref="Message" />
/// </summary>
EditedMessage,
/// <summary>
/// The <see cref="Update" /> contains a channel post <see cref="Message" />
/// </summary>
ChannelPost,
/// <summary>
/// The <see cref="Update" /> contains an edited channel post <see cref="Message" />
/// </summary>
EditedChannelPost,
/// <summary>
/// The <see cref="Update" /> contains an <see cref="ShippingQueryUpdate" />
/// </summary>
ShippingQueryUpdate,
/// <summary>
/// The <see cref="Update" /> contains an <see cref="PreCheckoutQueryUpdate" />
/// </summary>
PreCheckoutQueryUpdate,
/// <summary>
/// Receive all <see cref="Update" /> Types
/// </summary>
All = 255);
/// <summary>
/// Type of a <see cref="MessageEntity" />
/// </summary>
TtgMessageEntityType = (
/// <summary>
/// A mentioned <see cref="User" />
/// </summary>
mention,
/// <summary>
/// A searchable Hashtag
/// </summary>
hashtag,
/// <summary>
/// A Bot command
/// </summary>
bot_command,
/// <summary>
/// An url
/// </summary>
url,
/// <summary>
/// An email
/// </summary>
email,
/// <summary>
/// Bold text
/// </summary>
bold,
/// <summary>
/// Italic text
/// </summary>
italic,
/// <summary>
/// Monowidth string
/// </summary>
code,
/// <summary>
/// Monowidth block
/// </summary>
pre,
/// <summary>
/// Clickable text urls
/// </summary>
text_link,
/// <summary>
/// Mentions for a <see cref="User" /> without <see cref="User.Username" />
/// </summary>
text_mention, N_A);
/// <summary>
/// The part of the face relative to which the mask should be placed. One
/// of “forehead”, “eyes”, “mouth”, or “chin”.
/// </summary>
TtgMaskPositionPoint = (
/// <summary>
/// The forehead
/// </summary>
forehead,
/// <summary>
/// The eyes
/// </summary>
eyes,
/// <summary>
/// The mouth
/// </summary>
mouth,
/// <summary>
/// The chin
chin);
TtgGender = (Male, Female);
TtgPassportAvaibleData = (PersonalDetails, Passport, InternalPassport,
DriverLicense, IdentityCard, IdDocument, IdSelfie, Address, UtilityBill,
BankStatement, RentalAgreement, PassportRegistration, TemporaryRegistration,
AdressDocument, PhoneNumber, Email);
TAllowedUpdate = (message, Edited_message, Channel_post, Edited_channel_post,
Inline_query, Chosen_inline_result, Callback_query);
TAllowedUpdates = set of TAllowedUpdate;
const
UPDATES_ALLOWED_ALL =[Low(TAllowedUpdate)..High(TAllowedUpdate)];
implementation
end.
|
unit uMain;
{$IFDEF FPC}
{$mode objfpc}
{$H+}
//{$modeswitch typehelpers}
{$ENDIF}
interface
uses
{$IFDEF DARWIN}
{$IFDEF UseCThreads}
cthreads,
{$ENDIF}
{$ENDIF}
{$IFDEF DARWIN}
cwstring,
{$ENDIF}
sysutils,
Classes,
uUtil,
uOptions,
uHTMLResEmb;
function ProcessFile: Integer;
implementation
function ProcessFile: Integer;
var
ProcessingMessage: string;
DocPath: string;
sl: TStringList;
msStdIn: TMemoryStream;
HTMLProcessor: THTMLProcessor;
begin
ProcessingMessage := '';
DocPath := ExtractFilePath(Opts.InputFile);
sl := TStringList.Create;
HTMLProcessor := nil;
msStdIn := nil;
try
try
if (Opts.StdIn) then
begin
msStdin := StdInToMemoryStream;
msStdIn.Position := 0; // !!
sl.LoadFromStream(msStdIn);
end
else
sl.LoadFromFile(Opts.InputFile);
HTMLProcessor := THTMLProcessor.Create(DocPath, Opts.EmbedCSS, Opts.EmbedJavaScript, Opts.EmbedImages);
if not(HTMLProcessor.ProcessHTML(sl, ProcessingMessage)) then
Result := ERR_PROCESS
else
begin
if (Opts.StdOut) then
Write(sl.Text)
else
sl.SaveToFile(Opts.OutputFile);
Result := SUCCESS;
end;
if (Result = ERR_PROCESS) then
WriteLn(StdErr, 'Processing failed.');
if (ProcessingMessage <> '') then
WriteLn(StdErr, '(Warning) messages from HTML processing:', NL, ProcessingMessage);
except
Result := ERR_PROCESS;
WriteLn(StdErr, 'Processing error: ', NL, Exception(ExceptObject).Message);
end;
finally
msStdIn.Free;
HTMLProcessor.Free;
sl.Free;
end;
end;
end.
|
unit SMS.ServiceU;
interface
type
ISMSService = interface
['{C44D7371-6E5B-427D-A017-2163DFC6DA34}']
procedure SendSMS(const Number: string; Text: string);
procedure SendNextSMS;
end;
function GetSMSService: ISMSService;
implementation
uses
Androidapi.Helpers, Androidapi.JNI.JavaTypes, Androidapi.JNI.Telephony,
SMS.RESTAPI.ServiceU, System.Rtti, SmsBO, System.Threading, System.SysUtils,
System.UITypes;
type
TSMSService = class(TInterfacedObject, ISMSService)
public
procedure SendSMS(const Number: string; Text: string);
procedure SendNextSMS;
end;
{ TSMSService }
procedure TSMSService.SendNextSMS;
var
LRESTApi: ISMSRESTAPIService;
begin
TTask.Run(
procedure
var
ASMS: TSMS;
begin
LRESTApi := BuildSMSRESTApiService;
ASMS := LRESTApi.PopSMS;
if not Assigned(ASMS) then
exit;
try
SendSMS(ASMS.DESTINATION, ASMS.Text);
finally
ASMS.Free;
end;
end);
end;
procedure TSMSService.SendSMS(const Number: string; Text: string);
var
LSmsManager: JSmsManager;
LSmsTo, LSmsFrom, LText: JString;
begin
LSmsManager := TJSmsManager.JavaClass.getDefault;
// destination number
LSmsTo := StringToJString(Number);
LSmsFrom := nil;
// sms text
LText := StringToJString(Text);
LSmsManager.sendTextMessage(LSmsTo, LSmsFrom, LText, nil, nil);
end;
function GetSMSService: ISMSService;
begin
Result := TSMSService.Create;
end;
end.
|
unit fmFormPatterns2;
{ Masked input plugin
http://forums.unigui.com/index.php?/topic/4523-masked-input-plugin/?hl=format#entry22465
}
interface
uses
KrUtil,
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs,
uniGUITypes, uniGUIAbstractClasses, uniGUIClasses, uniGUIForm, uniDBEdit,
uniGUIBaseClasses, uniEdit, uniDBLookupComboBox, uniDBDateTimePicker,
UniDateTimePicker ;
type
TfrmFormPatterns2 = class(TUniForm)
procedure UniFormCreate(Sender: TObject);
procedure UniFormKeyPress(Sender: TObject; var Key: Char);
procedure UniFormShow(Sender: TObject);
private
function GetDataNula: String;
procedure AddEditLookpCombobox;
{ Private declarations }
public
Const
MaskFone :String='(99)9999-9999'; // Fone
MaskDate :String='99/99/9999'; // Data
MaskTime :String='99:99'; // Hora
MaskCPF :String='999.999.999-99'; // CPF
MaskPlaca :String='aaa-9999'; // Placa de Autovóvel
MaskIPol :String='999-9999/9999'; // inquérito Policial
MaskIP :String='9999.9999.9999.9999';// IP de computador
MaskCNPJ :String='99.999.999/9999-99'; // CNPJ
ResultCPF:String='___.___.___-__' ;
function DelCharEspeciais(Str:String):string;
function Idade(DataNasc:String):string; Overload;
function Idade(DataNasc:String; dtAtual:TDate):string; Overload;
procedure OpenURL(URL:String);
procedure OpenURLWindow(URL:String);
procedure AddMask(Edit: TUniDBEdit; Mask: String); Overload; // Adiciona mascara
procedure AddMask(Edit: TUniEdit; Mask: String); Overload; // Adiciona mascara
procedure AddMask(Edit: TUniDBDateTimePicker; Mask:String); Overload; // Adiciona mascara
procedure AddMask(Edit: TUniDateTimePicker; Mask:String); Overload; // Adiciona mascara
procedure AddMaskDate;
function Confirm(msg: String): Boolean;
function Soundex(S: String): String;
procedure Warning(msg: String);
procedure DisplayError(Msg:string); // Mensagem de dialog de erro
Procedure AddFeriados(Data:String);
function Criptografar(wStri: String): String;
function GeraSenha(n: integer): String;
function GerarNomeArquivo:String;
//
// Validação
function IsEMail(eMail: String): boolean;
function isKeyValid(Value:Char):Boolean;
function IsCnpj(const aCode:string):boolean; //Retorna verdadeiro se aCode for um CNPJ válido
function IsCpf(const aCode:string):boolean; //Retorna verdadeiro se aCode for um CPF válido
function IsCpfCnpj(const aCode:string):boolean;//Retorna verdadeiro se aCode for um CPF ou CNPJ válido
function IsDate(fDate:String):Boolean; // verifica se uma determinada data é válida ou não
function IsPlaca(Value:String):Boolean; // Faz a validação de uma placa de automóvel
function IsTitulo(numero: String): Boolean; // Validação de titulo de eleitor
function IsIP(IP: string): Boolean; // Verifica se o IP inofmado é válido
function IsIE(UF, IE: string): boolean;
function BoolToStr2(Bool:Boolean):String; overload;// Converte o valor de uma variável booleana em String
function BoolToStr2(Bool:Integer):String; overload;
property DataNula :String read GetDataNula;
function IsTituloEleitor(NumTitulo: string): Boolean; // Valida Título de Eleitor
// Date e Time
function Dias_Uteis(DT_Ini, DT_Fin:TDateTime):Integer;
{ Public declarations }
Function GetWhere(Value:TStrings):String;
function StrToBool1(Str:string):boolean;
end;
function frmFormPatterns2: TfrmFormPatterns2;
implementation
{$R *.dfm}
uses
MainModule, uniGUIApplication;
function frmFormPatterns2: TfrmFormPatterns2;
begin
Result := TfrmFormPatterns2(UniMainModule.GetFormInstance(TfrmFormPatterns2));
end;
procedure TfrmFormPatterns2.OpenURLWindow(URL:String);
Begin
if Trim(URL) <> '' then
UniSession.AddJS('window.open("'+URL+'", "janela", "directories=no, resizable=no, scrollbars=no, status=no, location=no, toolbar=no, menubar=no, scrollbars=yes, resizable=no, fullscreen=no")');
End; //http://www.guj.com.br/10470-esconder-urllink-da-barra-do-navegador-ou-a-propria-barra-de-nagegacao
procedure TfrmFormPatterns2.OpenURL(URL:String);
Begin
if Trim(URL) <> '' then
UniSession.AddJS('window.open("'+URL+'")');
End;
function TfrmFormPatterns2.DelCharEspeciais(Str: String): string;
begin
Result := KrUtil.DelCharEspeciais(Str);
end;
function TfrmFormPatterns2.Dias_Uteis(DT_Ini, DT_Fin: TDateTime): Integer;
begin
Result := KrUtil.Dias_Uteis(DT_Ini, DT_Fin);
end;
procedure TfrmFormPatterns2.DisplayError(Msg: string);
begin
MessageDlg(Msg, mtError, [mbOk]);
end;
function TfrmFormPatterns2.GerarNomeArquivo: String;
begin
Result:=krUtil.GerarNomeArquivo;
end;
function TfrmFormPatterns2.GeraSenha(n: integer): String;
begin
Result:=krUtil.GeraSenha(n);
end;
function TfrmFormPatterns2.GetDataNula: String;
begin
Result:=krUtil.DataNula;
end;
function TfrmFormPatterns2.GetWhere(Value: TStrings): String;
begin
Result:=KrUtil.GetWhere(Value);
end;
function TfrmFormPatterns2.Soundex(S: String): String;
begin
Result:=KrUtil.Soundex(S);
end;
function TfrmFormPatterns2.StrToBool1(Str: string): boolean;
begin
Result:=KrUtil.StrToBool1(Str);
end;
procedure TfrmFormPatterns2.UniFormCreate(Sender: TObject);
begin
KrUtil.Create;
end;
procedure TfrmFormPatterns2.UniFormKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #27 then
Close;
end;
procedure TfrmFormPatterns2.UniFormShow(Sender: TObject);
begin
AddMaskDate;
AddEditLookpCombobox;
end;
function TfrmFormPatterns2.BoolToStr2(Bool:Boolean):String;
Begin
Result:=KrUtil.BoolToStr2(Bool);
End;
function TfrmFormPatterns2.Idade(DataNasc: String): string;
begin
Result:=KrUtil.Idade(DataNasc);
end;
function TfrmFormPatterns2.Idade(DataNasc: String; dtAtual: TDate): string;
begin
Result:=KrUtil.Idade(DataNasc, dtAtual);
end;
function TfrmFormPatterns2.IsCnpj(const aCode: string): boolean;
begin
Result:=KrUtil.IsCnpj(aCode);
end;
function TfrmFormPatterns2.IsCpf(const aCode: string): boolean;
begin
Result:=KrUtil.IsCpf(aCode);
end;
function TfrmFormPatterns2.IsCpfCnpj(const aCode: string): boolean;
begin
Result:=KrUtil.IsCpfCnpj(aCode);
end;
function TfrmFormPatterns2.IsDate(fDate: String): Boolean;
begin
Result:=KrUtil.IsDate(fDate);
end;
function TfrmFormPatterns2.IsEMail(eMail: String): boolean;
begin
Result:=KrUtil.IsEMail(eMail);
end;
function TfrmFormPatterns2.IsIE(UF, IE: string): boolean;
begin
Result:=KrUtil.IsIE(UF, IE);
end;
function TfrmFormPatterns2.IsIP(IP: string): Boolean;
begin
Result:=KrUtil.IsIP(IP);
end;
function TfrmFormPatterns2.isKeyValid(Value: Char): Boolean;
begin
Result:=KrUtil.isKeyValid(Value);
end;
function TfrmFormPatterns2.IsPlaca(Value: String): Boolean;
begin
Result:=KrUtil.IsPlaca(Value);
end;
function TfrmFormPatterns2.IsTitulo(numero: String): Boolean;
begin
Result:=KrUtil.IsTitulo(numero);
end;
function TfrmFormPatterns2.IsTituloEleitor(NumTitulo: string): Boolean;
begin
Result := KrUtil.IsTituloEleitor(NumTitulo);
end;
procedure TfrmFormPatterns2.AddMaskDate;
Var
I:Integer;
begin // Adiciona mascara do componente informado
For I:=0 to ComponentCount - 1 do
if lowercase(Components[I].ClassName) = 'tunidbdatetimepicker' then
AddMask(TUniDBDateTimePicker(Components[I]), MaskDate);
end;
procedure TfrmFormPatterns2.AddMask(Edit: TUniDBDateTimePicker; Mask:String);
begin // Uses uniDBDateTimePicker
Edit.ClientEvents.ExtEvents.Add
('Onfocus=function function focus(sender, the, eOpts)'+
' { $("#"+sender.id+"-inputEl").mask("'+Mask+'"); }');
end;
procedure TfrmFormPatterns2.AddMask(Edit: TUniDateTimePicker; Mask:String);
begin // Uses uniDBDateTimePicker
Edit.ClientEvents.ExtEvents.Add
('Onfocus=function function focus(sender, the, eOpts)'+
' { $("#"+sender.id+"-inputEl").mask("'+Mask+'"); }');
end;
procedure TfrmFormPatterns2.AddMask(Edit: TUniDBEdit; Mask:String);
begin
Edit.ClientEvents.ExtEvents.Add
('Onfocus=function function focus(sender, the, eOpts)'+
' { $("#"+sender.id+"-inputEl").mask("'+Mask+'"); }');
end;
procedure TfrmFormPatterns2.AddMask(Edit: TUniEdit; Mask:String);
begin
Edit.ClientEvents.ExtEvents.Add
('Onfocus=function function focus(sender, the, eOpts)'+
' { $("#"+sender.id+"-inputEl").mask("'+Mask+'"); }');
end;
procedure TfrmFormPatterns2.AddEditLookpCombobox;
Var
I:Integer;
begin // Uses uniDBLookupComboBox
For I:=0 to ComponentCount - 1 do
if lowercase(Components[I].ClassName) = 'tunidblookupcombobox' then
TUniDBLookupComboBox(Components[I]).ClientEvents.ExtEvents.Add
('OnAfterrender=function afterrender(sender, eOpts)'+
' { sender.allowBlank=true; sender.editable = true;}');
end;
function TfrmFormPatterns2.Confirm(msg:String):Boolean;
Begin
MessageDlg(Msg, mtConfirmation, mbYesNo);
End;
procedure TfrmFormPatterns2.Warning(msg:String);
Begin
MessageDlg(Msg, mtWarning, [mbOk]);
End;
procedure TfrmFormPatterns2.AddFeriados(Data: String);
begin
KrUtil.AddFeriados(Data);
end;
function TfrmFormPatterns2.BoolToStr2(Bool: Integer): String;
begin
Result:=KrUtil.BoolToStr2(Bool);
end;
function TfrmFormPatterns2.Criptografar(wStri: String): String;
begin
Result := krUtil.Criptografar(wStri);
end;
end.
|
unit ConfigurationWSIntf;
interface
uses InvokeRegistry, Types, XSBuiltIns, CommunicationObj, DRX_WS;
type
IConfigurationWS = interface(IInvokable)
['{712FF90D-6010-4692-BB7B-55889DD01519}']
// IConfiguration
function Get_Filter(Index: Integer) : TDataFilter;
function Get_FilterCount: Integer; safecall;
function Get_DefaultFilter: Integer; safecall;
function Get_FilterAngle: Double; safecall;
function Get_FilterHeigh: Integer; safecall;
function Get_FilterDistance: Integer; safecall;
function Get_FilterSQI: WordBool; safecall;
function Get_FilterCI: WordBool; safecall;
function Get_FilterSIG: WordBool; safecall;
function Get_FilterLOG: WordBool; safecall;
function Get_FilterCCOR: WordBool; safecall;
function Get_AIGains: TWordDynArray; safecall;
function Get_AIFactors : TDoubleDynArray; safecall;
function Get_Radar_ID: Integer; safecall;
function Get_Obs_Directory: string; safecall;
function Get_Beam_Ch1: Single; safecall;
function Get_Beam_Ch2: Single; safecall;
function Get_Speed_Accuracy: Integer; safecall;
function Get_Angle_Accuracy: Integer; safecall;
function Get_Pack_Method: Integer; safecall;
function Get_Timeout_TxRx: Integer; safecall;
function Get_Speckle_Remove: boolean; safecall;
function Get_Save_Variance: boolean; safecall;
function Get_AngleCodeRate: Integer; safecall;
function Get_AngleClockwiseRotationX: boolean; safecall;
function Get_AngleClockwiseRotationY: boolean; safecall;
function Get_AngleClockwiseRotationZ: boolean; safecall;
function Get_SpeckleUmbral: Integer; safecall;
function Get_RadarName(RadarId: Integer): string; safecall;
function Get_RadarOwner(RadarId: Integer): string; safecall;
function Get_RadarRange(RadarId: Integer): Integer; safecall;
function Get_RadarLatitude(RadarId: Integer): Single; safecall;
function Get_RadarLongitude(RadarId: Integer): Single; safecall;
function Get_RadarAltitude(RadarId: Integer): Single; safecall;
function Get_RadarBrand(RadarId: Integer): RadarBrandsEnum; safecall;
function Get_SendMsgOnError: boolean; safecall;
function Get_TargetAddress: string; safecall;
function Get_SMTPServer: string; safecall;
function Get_SMTPUser: string; safecall;
function Get_SMTPPassword: string; safecall;
function Get_SMTPPort: Integer; safecall;
function Get_SMTPFromAddress: string; safecall;
function Get_ContinuosRegime: boolean; safecall;
procedure Set_ContinuosRegime(Value: boolean); safecall;
function Get_Timeout_Radar: Integer; safecall;
procedure Set_Timeout_Radar(Value: Integer); safecall;
function Get_Automatic_Obs: boolean; safecall;
procedure Set_Automatic_Obs(Value: boolean); safecall;
function Get_Auto_Power_Off: boolean; safecall;
procedure Set_Auto_Power_Off(Value: boolean); safecall;
function Get_WarmTime_Radar: Integer; safecall;
procedure Set_WarmTime_Radar(Value: Integer); safecall;
function Get_RestTime_Radar: Integer; safecall;
procedure Set_RestTime_Radar(Value: Integer); safecall;
function Get_RadarTemperature: Double; safecall;
function Get_RadarPressure: Double; safecall;
function Get_CheckPPIParam: boolean; safecall;
// IConfigurationControl
procedure SaveConfig; safecall;
procedure SaveAllConfig; safecall;
procedure Set_AIGains(Gains: TWordDynArray); safecall;
procedure Set_AIFactors(Factors: TDoubleDynArray); safecall;
procedure Set_Radar_ID(value: Integer); safecall;
procedure Set_Obs_Directory(const value: string); safecall;
procedure Set_Beam_Ch1(value: Single); safecall;
procedure Set_Beam_Ch2(value: Single); safecall;
procedure Set_Speed_Accuracy(value: Integer); safecall;
procedure Set_Angle_Accuracy(value: Integer); safecall;
procedure Set_Pack_Method(value: Integer); safecall;
procedure Set_Timeout_TxRx(value: Integer); safecall;
procedure Set_Speckle_Remove(value: boolean); safecall;
procedure Set_Save_Variance(value: boolean); safecall;
procedure Set_AngleCodeRate(value: Integer); safecall;
procedure Set_AngleClockwiseRotationX(value: boolean); safecall;
procedure Set_AngleClockwiseRotationY(value: boolean); safecall;
procedure Set_AngleClockwiseRotationZ(value: boolean); safecall;
procedure Set_SpeckleUmbral(value: Integer); safecall;
procedure Set_SMTPPort(value: Integer); safecall;
procedure Set_SMTPUser(const value: string); safecall;
procedure Set_SMTPPassword(const value: string); safecall;
procedure Set_SendMsgOnError(value: boolean); safecall;
procedure Set_TargetAddress(const value: string); safecall;
procedure Set_SMTPServer(const value: string); safecall;
function TestSMTPConfig: boolean; safecall;
function SendTestEMail: boolean; safecall;
procedure Set_SMTPFromAddress(const value: string); safecall;
procedure Set_RadarTemperature(value: Double); safecall;
procedure Set_RadarPressure(value: Double); safecall;
procedure Set_CheckPPIParam(value: boolean); safecall;
procedure SetFilter(Index: Integer; Filter : TDataFilter);
procedure Set_FilterCount(Value: Integer); safecall;
procedure Set_DefaultFilter(Value: Integer); safecall;
procedure Set_FilterAngle(Value: Double); safecall;
procedure Set_FilterHeigh(Value: Integer); safecall;
procedure Set_FilterDistance(Value: Integer); safecall;
procedure Set_FilterSQI(Value: WordBool); safecall;
procedure Set_FilterCI(Value: WordBool); safecall;
procedure Set_FilterSIG(Value: WordBool); safecall;
procedure Set_FilterLOG(Value: WordBool); safecall;
procedure Set_FilterCCOR(Value: WordBool); safecall;
property Radar_ID: Integer read Get_Radar_ID write Set_Radar_ID;
property Obs_Directory: string read Get_Obs_Directory write Set_Obs_Directory;
property Beam_Ch1: Single read Get_Beam_Ch1 write Set_Beam_Ch1;
property Beam_Ch2: Single read Get_Beam_Ch2 write Set_Beam_Ch2;
property Speed_Accuracy: Integer read Get_Speed_Accuracy write Set_Speed_Accuracy;
property Angle_Accuracy: Integer read Get_Angle_Accuracy write Set_Angle_Accuracy;
property Pack_Method: Integer read Get_Pack_Method write Set_Pack_Method;
property Timeout_TxRx: Integer read Get_Timeout_TxRx write Set_Timeout_TxRx;
property Speckle_Remove: boolean read Get_Speckle_Remove write Set_Speckle_Remove;
property Save_Variance: boolean read Get_Save_Variance write Set_Save_Variance;
property AngleCodeRate: Integer read Get_AngleCodeRate write Set_AngleCodeRate;
property AngleClockwiseRotationX: boolean read Get_AngleClockwiseRotationX write Set_AngleClockwiseRotationX;
property AngleClockwiseRotationY: boolean read Get_AngleClockwiseRotationY write Set_AngleClockwiseRotationY;
property AngleClockwiseRotationZ: boolean read Get_AngleClockwiseRotationZ write Set_AngleClockwiseRotationZ;
property SpeckleUmbral: Integer read Get_SpeckleUmbral write Set_SpeckleUmbral;
property ContinuosRegime: boolean read Get_ContinuosRegime write Set_ContinuosRegime;
property Timeout_Radar: Integer read Get_Timeout_Radar write Set_Timeout_Radar;
property Automatic_Obs: boolean read Get_Automatic_Obs write Set_Automatic_Obs;
property Auto_Power_Off: boolean read Get_Auto_Power_Off write Set_Auto_Power_Off;
property WarmTime_Radar: Integer read Get_WarmTime_Radar write Set_WarmTime_Radar;
property RestTime_Radar: Integer read Get_RestTime_Radar write Set_RestTime_Radar;
property RadarTemperature: Double read Get_RadarTemperature write Set_RadarTemperature;
property RadarPressure: Double read Get_RadarPressure write Set_RadarPressure;
property CheckPPIParam: boolean read Get_CheckPPIParam write Set_CheckPPIParam;
property SendMsgOnError: boolean read Get_SendMsgOnError write Set_SendMsgOnError;
property TargetAddress: string read Get_TargetAddress write Set_TargetAddress;
property SMTPServer: string read Get_SMTPServer write Set_SMTPServer;
property SMTPUser: string read Get_SMTPUser write Set_SMTPUser;
property SMTPPassword: string read Get_SMTPPassword write Set_SMTPPassword;
property SMTPPort: Integer read Get_SMTPPort write Set_SMTPPort;
property SMTPFromAddress: string read Get_SMTPFromAddress write Set_SMTPFromAddress;
property RadarName[RadarId: Integer]: string read Get_RadarName;
property RadarOwner[RadarId: Integer]: string read Get_RadarOwner;
property RadarRange[RadarId: Integer]: Integer read Get_RadarRange;
property RadarLatitude[RadarId: Integer]: Single read Get_RadarLatitude;
property RadarLongitude[RadarId: Integer]: Single read Get_RadarLongitude;
property RadarAltitude[RadarId: Integer]: Single read Get_RadarAltitude;
property RadarBrand[RadarId: Integer]: RadarBrandsEnum read Get_RadarBrand;
property FilterCount: Integer read Get_FilterCount write Set_FilterCount;
property DefaultFilter: Integer read Get_DefaultFilter write Set_DefaultFilter;
property FilterAngle: Double read Get_FilterAngle write Set_FilterAngle;
property FilterHeigh: Integer read Get_FilterHeigh write Set_FilterHeigh;
property FilterDistance: Integer read Get_FilterDistance write Set_FilterDistance;
property FilterSQI: WordBool read Get_FilterSQI write Set_FilterSQI;
property FilterCI: WordBool read Get_FilterCI write Set_FilterCI;
property FilterSIG: WordBool read Get_FilterSIG write Set_FilterSIG;
property FilterLOG: WordBool read Get_FilterLOG write Set_FilterLOG;
property FilterCCOR: WordBool read Get_FilterCCOR write Set_FilterCCOR;
end;
implementation
initialization
InvRegistry.RegisterInterface(TypeInfo(IConfigurationWS));
end.
|
unit stackLib;
interface
type
TInfo = integer;
TStack = ^ElemStack;
ElemStack = record
Info: TInfo;
Next: TStack;
end;
procedure InitStack(var s: TStack); // инициализация стека
function StackIsEmpty(s: TStack): Boolean;// проверка на пустоту
function PopStack(var s: TStack): TInfo; // взять из стека
procedure PushStack(var s: TStack; x:TInfo); // положить в стек
implementation
procedure InitStack(var s: TStack);
begin
s:=Nil;
end;
function StackIsEmpty(s: TStack): Boolean;
begin
Result:=s=Nil;
end;
function PopStack(var s: TStack): TInfo;
var
p:TStack;
begin
Result:=s^.Info;
p:=s; s:=s^.Next;
dispose(p);
end;
procedure PushStack(var s: TStack; x:TInfo);
var p:TStack;
begin
new(p);
with p^ do
begin
Info:=x;
Next:=s;
end;
s:=p;
end;
end.
|
unit uAssembler;
// Developed using Delphi for Windows and Mac platforms.
// *** Ths source is distributed under Apache 2.0 ***
// Copyright (C) 2019-2020 Herbert M Sauro
// Author Contact Information:
// email: hsauro@gmail.com
interface
Uses Classes, System.SysUtils, System.StrUtils, System.Types, IOUtils, uSymbolTable, uOpCodes;
function assembleCode (const srcCode : string) : TProgram;
function dissassemble (myProgram : TProgram) : string;
implementation
Uses uConstantTable;
var labels : TStringList;
// From stackoverflow (35158485) Alex James
function RemoveDupSpaces(const Input : String) : String;
var
P : Integer;
begin
Result := Input;
repeat
P := Pos(' ', Result); // that's two spaces
if P > 0 then
Delete(Result, P + 1, 1);
until P = 0;
end;
procedure collectLabels (srcCode : string);
var sl : TStringList;
i : integer;
s, alabel : string;
splitted: TArray<string>;
instCounter : integer;
begin
labels := TStringList.Create;
sl := TStringList.Create;
sl.text := srcCode;
instCounter := 0;
for i := 0 to sl.Count - 1 do
begin
s := sl[i].TrimLeft;
// Ignore comment lines and empty lines
if (s <> '') then
if (s[1] <> '#') then
begin
s := RemoveDupSpaces(s);
splitted := s.Split([' ']);
if rightStr(splitted[0], 1) = ':' then
begin
// get label
alabel := leftStr (splitted[0], length (splitted[0])-1);
labels.AddObject(alabel, TObject (instCounter));
end;
inc (instCounter);
end;
end;
end;
procedure tokenize (srcStr : string; var dest1, dest2, dest3 : string);
var index : integer;
begin
dest1 := ''; dest2 := ''; dest3 := '';
index := pos (':', srcStr);
if index <> 0 then
begin
dest1 := leftstr (srcStr, index-1);
srcStr := trim (rightStr (srcStr, length (srcStr) - index ));
end;
index := pos (' ', srcStr);
if index <> 0 then
begin
dest2 := leftStr (srcStr, index-1);
dest3 := rightStr (srcStr, length (srcStr) - index);
end
else
dest2 := srcStr;
dest1 := trim (dest1);
dest2 := trim (dest2);
dest3 := trim (dest3);
end;
function assembleCode (const srcCode : string) : TProgram;
var sl : TStringList;
i : integer;
s, alabel, astr : string;
instCounter, labelInt, index : integer;
opCodeStr, opCodeArgument : string;
begin
collectLabels (srcCode);
result := TProgram.Create;
sl := TStringList.Create;
try
sl.text := srcCode;
instCounter := 0;
for i := 0 to sl.Count - 1 do
begin
s := sl[i].TrimLeft;
// Ignore comment lines and empty lines
if (s <> '') then
if (s[1] <> '#') then
begin
s := RemoveDupSpaces(s);
tokenize(s, alabel, opcodeStr, opCodeArgument);
if opCodeStr = opCodeNames[oNop] then begin result.addByteCode (oNop); inc (instCounter); continue end;
if opCodeStr = opCodeNames[oAdd] then begin result.addByteCode (oAdd); inc (instCounter); continue end;
if opCodeStr = opCodeNames[oSub] then begin result.addByteCode (oSub); inc (instCounter); continue end;
if opCodeStr = opcodeNames[oMult] then begin result.addByteCode (oMult); inc (instCounter); continue end;
if opCodeStr = opCodeNames[oDivide] then begin result.addByteCode (oDivide); inc (instCounter); continue end;
if opCodeStr = opCodeNames[oMod] then begin result.addByteCode (oMod); inc (instCounter); continue end;
if opCodeStr = opCodeNames[oDivi] then begin result.addByteCode (oDivi); inc (instCounter); continue end;
if opCodeStr = opCodeNames[oInc] then begin result.addByteCode (oInc); inc (instCounter); continue end;
if opCodeStr = opCodeNames[oDec] then begin result.addByteCode (oDec); inc (instCounter); continue end;
if opCodeStr = opCodeNames[oLocalInc] then begin result.addByteCode (oLocalInc); inc (instCounter); continue end;
if opCodeStr = opCodeNames[oLocalDec] then begin result.addByteCode (oLocalDec); inc (instCounter); continue end;
if opCodeStr = opCodeNames[oNot] then begin result.addByteCode (oNot); inc (instCounter); continue end;
if opCodeStr = opCodeNames[oAnd] then begin result.addByteCode (oAnd); inc (instCounter); continue end;
if opCodeStr = opCodeNames[oOr] then begin result.addByteCode (oOr); inc (instCounter); continue end;
if opCodeStr = opCodeNames[oXor] then begin result.addByteCode (oXor); inc (instCounter); continue end;
if opCodeStr = opCodeNames[oPop] then begin result.addByteCode (oPop); inc (instCounter); continue end;
if opCodeStr = opCodeNames[oIsGt] then begin result.addByteCode (oIsGt); inc (instCounter); continue end;
if opCodeStr = opCodeNames[oIsGte] then begin result.addByteCode (oIsGte); inc (instCounter); continue end;
if opCodeStr = opCodeNames[oIsLt] then begin result.addByteCode (oIsLt); inc (instCounter); continue end;
if opCodeStr = opCodeNames[oIsLte] then begin result.addByteCode (oIsLte); inc (instCounter); continue end;
if opCodeStr = opCodeNames[oIsEq] then begin result.addByteCode (oIsEq); inc (instCounter); continue end;
if opCodeStr = opCodeNames[oIsNotEq] then begin result.addByteCode (oIsNotEq); inc (instCounter); continue end;
if opCodeStr = opCodeNames[oPrint] then begin result.addByteCode (oPrint); inc (instCounter); continue end;
if opCodeStr = opCodeNames[oPrintln] then begin result.addByteCode (oPrintln); inc (instCounter); continue end;
if opCodeStr = opCodeNames[oHalt] then begin result.addByteCode (oHalt); inc (instCounter); continue end;
if opCodeStr = opCodeNames[oRet] then begin result.addByteCode (oRet); inc (instCounter); continue end;
if opCodeStr = opCodeNames[oLvecIdx] then begin result.addByteCode (oLvecIdx); inc (instCounter); continue end;
if opCodeStr = opCodeNames[oSvecIdx] then begin result.addByteCode (oSvecIdx); inc (instCounter); continue end;
if opCodeStr = opCodeNames[oLocalLvecIdx] then begin result.addByteCode (oLocalLvecIdx); inc (instCounter); continue end;
if opCodeStr = opCodeNames[oLocalSvecIdx] then begin result.addByteCode (oLocalSvecIdx); inc (instCounter); continue end;
if opCodeStr = opCodeNames[oCall] then begin result.addByteCode (oCall); inc (instCounter); continue end;
if opCodeStr = opCodeNames[oBuiltin] then begin result.addByteCode (oBuiltin); inc (instCounter); continue end;
if opCodeStr = opCodeNames[oLoad] then
begin
result.addByteCode (oLoad, strtoint (opCodeArgument));
inc (instCounter);
continue;
end;
if opCodeStr = opCodeNames[oStore] then begin
result.addByteCode (oStore, strtoint (opCodeArgument));
inc (instCounter);
continue;
end;
if opCodeStr = opCodeNames[oCreateList] then
begin
result.addByteCode (oCreateList, strtoint (opCodeArgument));
inc (instCounter);
continue
end;
if opCodeStr = opCodeNames[oPushi] then
begin
result.addByteCode (oPushi, strtoint (opCodeArgument));
inc (instCounter);
continue;
end;
if opCodeStr = opCodeNames[oPushd] then
begin
result.addByteCode (oPushd, strtofloat (opCodeArgument));
inc (instCounter);
continue;
end;
if opCodeStr = opCodeNames[oPushb] then
begin
if opCodeArgument = 'true' then
result.addByteCode (oPushb, true);
if opCodeArgument = 'false' then
result.addByteCode (oPushb, false);
if (opCodeArgument <> 'false') and (opCodeArgument <> 'true') then
raise Exception.Create('Expecting boolean true or false in pushb');
inc (instCounter);
continue;
end;
if opCodeStr = opCodeNames[oPushs] then
begin
astr := opCodeArgument;
// Check for double quotes at start and end of string
if (astr[1] = '"') and (astr[length (astr)] = '"') then
begin
// Strip double quotes from the string
astr := astr.Substring (0, astr.Length - 1);
delete (astr, 1, 1);
result.addByteCode (oPUSHs, astr);
inc (instCounter);
continue;
end
else
raise Exception.Create('Expecting string as argument to pushs');
end;
if opCodeStr = opCodeNames[oJmp] then
begin
index := labels.IndexOf (opCodeArgument);
if index <> -1 then
begin
labelInt := integer (labels.Objects[index]);
result.addByteCode (oJMP, labelInt - instCounter);
end
else
raise Exception.Create ('Unable to locate label specificed in jmp opcode');
inc (instCounter);
continue;
end;
if opCodeStr = opCodeNames[oJmpIfTrue] then
begin
index := labels.IndexOf (opCodeArgument);
if index <> -1 then
begin
labelInt := integer (labels.Objects[index]);
result.addByteCode (oJmpIfTrue, labelInt - instCounter);
end
else
raise Exception.Create ('Unable to locate label specificed in jmpIfTrue opcode');
inc (instCounter);
continue;
end;
if opCodeStr = opCodeNames[oJmpIfFalse] then
begin
index := labels.IndexOf (opCodeArgument);
if index <> -1 then
begin
labelInt := integer (labels.Objects[index]);
result.addByteCode (oJmpIfFalse, labelInt - instCounter);
end
else
raise Exception.Create ('Unable to locate label specificed in jmpIfFalse opcode');
inc (instCounter);
continue;
end;
raise Exception.Create ('Error: Unknown op code in program: ' + opCodeStr);
end;
end;
finally
sl.Free;
labels.Free;
end;
end;
function dissassemble (myProgram : TProgram) : string;
var i : integer;
begin
result := '';
for i := 0 to myProgram.count - 1 do
begin
result := result + format ('%3d', [i]);
case myProgram.code[i].opCode of
oNop : result := result + ' ' + opCodeNames[oNop] + ' ' + sLineBreak;
oHalt : result := result + ' ' + opCodeNames[oHalt] + sLineBreak;
oPushi : result := result + ' ' + opCodeNames[oPushi] + ' ' + inttostr (myProgram.code[i].index) + sLineBreak;
oPushb : result := result + ' ' + opCodeNames[oPushb] + ' ' + inttostr (myProgram.code[i].index) + sLineBreak;
oPushd : result := result + ' ' + opCodeNames[oPushd] + ' ' + floattostr (constantValueTable[myProgram.code[i].index].dValue) + sLineBreak;
oPushs : result := result + ' ' + opCodeNames[oPushs] + ' "' + constantValueTable[myProgram.code[i].index].sValue.value + '"' + sLineBreak;
oPushNone : result := result + ' ' + opCodeNames[oPushNone] + sLineBreak;
oAdd : result := result + ' ' + opCodeNames[oAdd] + sLineBreak;
oSub : result := result + ' ' + opCodeNames[oSub] + sLineBreak;
oMult : result := result + ' ' + opCodeNames[oMult] + sLineBreak;
oDivide : result := result + ' ' + opCodeNames[oDivide] + sLineBreak;
oDivi : result := result + ' ' + opCodeNames[oDivI] + sLineBreak;
oMod : result := result + ' ' + opCodeNames[oMod] + sLineBreak;
oPower : result := result + ' ' + opCodeNames[oPower] + sLineBreak;
oUmi : result := result + ' ' + opCodeNames[oUmi] + sLineBreak;
oInc : result := result + ' ' + opCodeNames[oInc] + ' ' + inttostr (myProgram.code[i].index) + sLineBreak;
oDec : result := result + ' ' + opCodeNames[oDec] + sLineBreak;
oLocalInc : result := result + ' ' + opCodeNames[oLocalInc] + sLineBreak;
oLocalDec : result := result + ' ' + opCodeNames[oLocalDec] + sLineBreak;
oOr : result := result + ' ' + opCodeNames[oOr] + sLineBreak;
oAnd : result := result + ' ' + opCodeNames[oAnd] + sLineBreak;
oXor : result := result + ' ' + opCodeNames[oXor] + sLineBreak;
oNot : result := result + ' ' + opCodeNames[oNot] + sLineBreak;
oPop : result := result + ' ' + opCodeNames[oPop] + sLineBreak;
oIsGt : result := result + ' ' + opCodeNames[oIsGt] + sLineBreak;
oIsLt : result := result + ' ' + opCodeNames[oIsLt] + sLineBreak;
oIsGte : result := result + ' ' + opCodeNames[oIsGte] + sLineBreak;
oIsLte : result := result + ' ' + opCodeNames[oIsLte] + sLineBreak;
oIsEq : result := result + ' ' + opCodeNames[oIsEq] + sLineBreak;
oIsNotEq : result := result + ' ' + opCodeNames[oIsNotEq] + sLineBreak;
oPrint : result := result + ' ' + opCodeNames[oPrint] + sLineBreak;
oPrintln : result := result + ' ' + opCodeNames[oPrintln] + sLineBreak;
oAssertTrue : result := result + ' ' + opCodeNames[oAssertTrue] + sLineBreak;
oAssertFalse: result := result + ' ' + opCodeNames[oAssertFalse] + sLineBreak;
oJmp : result := result + ' ' + opCodeNames[oJmp] + ' ' + inttostr (myProgram.code[i].index) + sLineBreak;
oJmpIfTrue : result := result + ' ' + opCodeNames[ojmpIfTrue] + ' ' + inttostr (myProgram.code[i].index) + sLineBreak;
oJmpIfFalse : result := result + ' ' + opCodeNames[oJmpIfFalse] + ' ' + inttostr (myProgram.code[i].index) + sLineBreak;
oStore : result := result + ' ' + opCodeNAmes[oStore] + ' ' + inttostr (myProgram.code[i].index) + sLineBreak;
oLoad : result := result + ' ' + opCodeNames[oLoad] + ' ' + inttostr (myProgram.code[i].index) + sLineBreak;
oStoreLocal : result := result + ' ' + opCodeNAmes[oStoreLocal] + ' ' + inttostr (myProgram.code[i].index) + sLineBreak;
oLoadLocal : result := result + ' ' + opCodeNames[oLoadLocal] + ' ' + inttostr (myProgram.code[i].index) + sLineBreak;
oCall : result := result + ' ' + opCodeNames[oCall] + sLineBreak;
oBuiltin : result := result + ' ' + opCodeNames[oBuiltin] + ' ' + inttostr (myProgram.code[i].index) + sLineBreak;
oRet : result := result + ' ' + opCodeNames[oRet] + ' ' + sLineBreak;
oLvecIdx : result := result + ' ' + opCodeNames[oLvecIdx] + sLineBreak;
oSvecIdx : result := result + ' ' + opCodeNames[oSvecIdx] + sLineBreak;
oLocalLvecIdx : result := result + ' ' + opCodeNames[oLocalLvecIdx] + ' ' + inttostr (myProgram.code[i].index) + sLineBreak;
oLocalSvecIdx : result := result + ' ' + opCodeNames[oLocalSvecIdx] + ' ' + inttostr (myProgram.code[i].index) + sLineBreak;
oCreateList : result := result + ' ' + opCodeNames[oCreateList] + ' ' + inttostr (myProgram.code[i].index) + sLineBreak;
else
writeln ('Unknown opcode during dissassembly: ', myProgram.code[i].opCode);
end;
end;
end;
end.
|
unit runqueue;
{$mode fpc}
interface
uses threads;
function PopThread: PThread;
procedure EnqueueThread(var t: TThread);
procedure RemoveThread(var t: TThread);
implementation
uses config;
var
First, Last: array[TThreadPriority] of PThread;
function PopThread: PThread;
var
t: PThread;
tp: TThreadPriority;
begin
for tp:=high(TThreadPriority) downto low(TThreadPriority) do
begin
if First[tp] = nil then
continue;
t := First[tp];
if t = last[tp] then
begin
First[tp] := nil;
Last[tp] := nil;
end
else
First[tp] := t^.Next;
t^.next := nil;
exit(t);
end;
exit(nil);
end;
procedure EnqueueThread(var t: TThread);
var
tp: TThreadPriority;
LastTmp: PThread;
begin
tp:=t.Priority;
LastTmp:=last[tp];
if LastTmp = nil then
First[tp] := @t
else
LastTmp^.Next := @t;
Last[tp] := @t;
t.Next:=nil;
end;
procedure RemoveThread(var t: TThread);
var
tp: TThreadPriority;
ft: PThread;
begin
tp:=t.Priority;
ft:=first[tp];
if @t = ft then
begin
if ft = last[tp] then
begin
first[tp] := nil;
last[tp] := nil;
end
else
first[tp] := ft^.Next;
end
else
begin
while assigned(ft) do
begin
if ft^.Next = @t then
begin
ft^.Next := t.Next;
if last[tp] = @t then
last[tp] := ft;
exit;
end;
ft := ft^.Next;
end;
end;
end;
end.
|
unit u_CadastroPadraoPessoas;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, u_CadastroPadrao, Data.DB,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client,
Vcl.StdCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.ComCtrls, Vcl.ExtCtrls, Vcl.DBCtrls,
Vcl.Mask, Vcl.Buttons, IPPeerClient, REST.Response.Adapter, REST.Client,
Data.Bind.Components, Data.Bind.ObjectScope, System.UITypes;
type
Tfrm_CadastroPadraoPessoas = class(Tfrm_CadastroPadrao)
Label3: TLabel;
edit_razao_nome: TDBEdit;
Label4: TLabel;
edit_fantasia_apelido: TDBEdit;
rg_tipo: TDBRadioGroup;
Label2: TLabel;
edit_cnpj_cpf: TDBEdit;
Label5: TLabel;
edit_ie_rg: TDBEdit;
Label6: TLabel;
edit_nascimento: TDBEdit;
Label8: TLabel;
edit_cod_cidade: TDBEdit;
b_pequisa_cidade: TBitBtn;
edit_nome_cidade: TEdit;
edit_cep: TDBEdit;
Label9: TLabel;
Label7: TLabel;
edit_endereco: TDBEdit;
Label10: TLabel;
edit_numero: TDBEdit;
Label11: TLabel;
edit_bairro: TDBEdit;
Label12: TLabel;
edit_contato: TDBEdit;
rg_sexo: TDBRadioGroup;
Label14: TLabel;
edit_email: TDBEdit;
btn_cnpj: TBitBtn;
RESTClient1: TRESTClient;
RESTRequest1: TRESTRequest;
RESTResponse1: TRESTResponse;
RESTResponseDataSetAdapter1: TRESTResponseDataSetAdapter;
FDMemTable1: TFDMemTable;
FDMemTable1nome: TWideStringField;
FDMemTable1telefone: TWideStringField;
FDMemTable1email: TWideStringField;
FDMemTable1bairro: TWideStringField;
FDMemTable1logradouro: TWideStringField;
FDMemTable1numero: TWideStringField;
FDMemTable1cep: TWideStringField;
FDMemTable1fantasia: TWideStringField;
FDMemTable1cnpj: TWideStringField;
q_dadoscod_pessoa: TFDAutoIncField;
q_dadostipo: TStringField;
q_dadosrazao_nome: TStringField;
q_dadosfantasia_apelido: TStringField;
q_dadoscnpj_cpf: TStringField;
q_dadosie_rg: TStringField;
q_dadosdata_nascimento: TDateField;
q_dadossexo: TStringField;
q_dadoscod_cidade: TIntegerField;
q_dadosendereco: TStringField;
q_dadosbairro: TStringField;
q_dadoscep: TStringField;
q_dadosemail: TStringField;
q_dadoscontato: TStringField;
q_dadosnumero: TStringField;
procedure B_fecharClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure b_pequisa_cidadeClick(Sender: TObject);
procedure edit_cod_cidadeChange(Sender: TObject);
procedure btn_cnpjClick(Sender: TObject);
procedure rg_tipoClick(Sender: TObject);
procedure B_incluirClick(Sender: TObject);
procedure B_alterarClick(Sender: TObject);
protected
{ Public declarations }
function pode_excluir : string; override;
function validar : boolean; override;
private
{ Private declarations }
public
{ Public declarations }
end;
var
frm_CadastroPadraoPessoas: Tfrm_CadastroPadraoPessoas;
implementation
{$R *.dfm}
uses u_dm, u_pesquisa, funcoes;
procedure Tfrm_CadastroPadraoPessoas.btn_cnpjClick(Sender: TObject);
begin
inherited;
RESTRequest1.Params.ParameterByName('cnpj').Value := edit_cnpj_cpf.Field.Text;
RESTRequest1.Execute;
edit_razao_nome.Field.Text := FDMemTable1.FieldByName('nome').Text;
edit_fantasia_apelido.Field.Text := FDMemTable1.FieldByName('fantasia').Text;
edit_cnpj_cpf.Field.Text := Remove(FDMemTable1.FieldByName('cnpj').Text);
edit_contato.Field.Text := FDMemTable1.FieldByName('telefone').Text;
edit_cep.Field.Text := Remove(FDMemTable1.FieldByName('cep').Text);
edit_endereco.Field.Text := FDMemTable1.FieldByName('logradouro').Text;
edit_numero.Field.Text := FDMemTable1.FieldByName('numero').Text;
edit_bairro.Field.Text := FDMemTable1.FieldByName('bairro').Text;
edit_email.Field.Text:= FDMemTable1.FieldByName('email').Text;
end;
procedure Tfrm_CadastroPadraoPessoas.B_alterarClick(Sender: TObject);
begin
inherited;
// PESSOA JURIDICA
if rg_tipo.ItemIndex = 0 then
begin
btn_cnpj.Enabled:= true;
edit_cnpj_cpf.Field.EditMask:= '00\.000\.000\/0000\-00;0;_';
edit_nascimento.Enabled:= false;
rg_sexo.Enabled:= false;
end
// PESSOA FISICA
else
begin
btn_cnpj.Enabled:= false;
edit_cnpj_cpf.Field.EditMask:= '000\.000\.000\-00;0;_';
edit_nascimento.Enabled:= true;
rg_sexo.Enabled:= true;
end;
end;
procedure Tfrm_CadastroPadraoPessoas.B_fecharClick(Sender: TObject);
begin
inherited;
close;
end;
procedure Tfrm_CadastroPadraoPessoas.B_incluirClick(Sender: TObject);
begin
inherited;
rg_tipo.ItemIndex:= 0;
end;
procedure Tfrm_CadastroPadraoPessoas.b_pequisa_cidadeClick(Sender: TObject);
begin
inherited;
frm_pesquisa:= Tfrm_pesquisa.create(application);
frm_pesquisa.tabela:= 'cidades';
frm_pesquisa.codigo:= 'cod_cidade';
frm_pesquisa.campo1:= 'localidade';
frm_pesquisa.campo2:= 'cep';
frm_pesquisa.rotulo_codigo:= 'Código';
frm_pesquisa.rotulo_c1:= 'Nome';
frm_pesquisa.rotulo_c2:= 'CEP';
frm_pesquisa.largura_codigo:= 0.10; // 10% da largura do dbgrid
frm_pesquisa.largura_c1:= 0.45;
frm_pesquisa.largura_c2:= 0.25;
frm_pesquisa.ShowModal;
if frm_pesquisa.ModalResult = mrOk then
begin
edit_cod_cidade.Text:= frm_pesquisa.q_dados.fieldbyname(frm_pesquisa.codigo).AsString;
end;
// retira o objeto da memória
frm_pesquisa.Free;
end;
procedure Tfrm_CadastroPadraoPessoas.edit_cod_cidadeChange(Sender: TObject);
begin
inherited;
edit_nome_cidade.Text:= '';
dm.q_geral.SQL.Clear;
dm.q_geral.SQL.add(' select * from cidades where cod_cidade = ' + QuotedStr(edit_cod_cidade.Text));
dm.q_geral.open;
if not dm.q_geral.IsEmpty
then edit_nome_cidade.Text:= dm.q_geral.FieldByName('localidade').AsString;
edit_cep.Text:= dm.q_geral.FieldByName('cep').AsString;
end;
procedure Tfrm_CadastroPadraoPessoas.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action:= caFree;
Frm_CadastroPadraoPessoas:= nil;
end;
function Tfrm_CadastroPadraoPessoas.pode_excluir: string;
begin
dm.Q_Geral.SQL.Clear;
dm.Q_Geral.SQL.Add('select count(*) as total from certificados where cod_pessoa = ' + q_dados.FieldByName('cod_pessoa').AsString);
dm.Q_Geral.Open;
if dm.Q_Geral.FieldByName('total').AsInteger > 0 then
begin
Result := 'A Pessoa esta Relacionada com um Certificado, e não pode ser excluida!';
exit;
end;
end;
procedure Tfrm_CadastroPadraoPessoas.rg_tipoClick(Sender: TObject);
begin
inherited;
// PESSOA JURIDICA
if rg_tipo.ItemIndex = 0 then
begin
btn_cnpj.Enabled:= true;
edit_cnpj_cpf.Field.EditMask:= '00\.000\.000\/0000\-00;0;_';
edit_cnpj_cpf.Field.Text:= '';
edit_nascimento.Enabled:= false;
rg_sexo.Enabled:= false;
end
// PESSOA FISICA
else
begin
btn_cnpj.Enabled:= false;
edit_cnpj_cpf.Field.EditMask:= '000\.000\.000\-00;0;_';
edit_cnpj_cpf.Field.Text:= '';
edit_nascimento.Enabled:= true;
rg_sexo.Enabled:= true;
end;
end;
function Tfrm_CadastroPadraoPessoas.validar: boolean;
begin
if trim(edit_razao_nome.Text) = '' then
begin
MessageDlg('A Razão Social / Nome, é de preenchimento obrigatorio !',mtError,[mbOk],0);
edit_razao_nome.SetFocus;
exit;
end;
if trim(edit_cnpj_cpf.Text) = '' then
begin
MessageDlg('O CNPJ / CPF deve ser preenchido !',mtError,[mbOk],0);
edit_cnpj_cpf.SetFocus;
exit;
end;
// PESSOA JURIDICA
if rg_tipo.ItemIndex = 0 then
begin
if not isCNPJ(edit_cnpj_cpf.Text) then
begin
MessageDlg('O CNPJ deve ser valido !',mtError,[mbOk],0);
edit_cnpj_cpf.SetFocus;
exit;
end;
end
// PESSOA FISICA
else
begin
if not valida_cpf(edit_cnpj_cpf.Text) then
begin
MessageDlg('O CPF deve ser valido !',mtError,[mbOk],0);
edit_cnpj_cpf.SetFocus;
exit;
end;
end;
result:= True;
end;
end.
|
unit FileSub;
(* ファイル関連のサブルーチン *)
(* Copyright (c) 2001,2002 Twiddle <hetareprog@hotmail.com> *)
(* 1.5, Sun Oct 10 04:57:28 2004 UTC *)
interface
uses
SysUtils, Classes;
type
(*-------------------------------------------------------*)
TTmpFile = class(TStringList)
public
destructor Destroy; override;
procedure Clear; override;
procedure Delete(index: integer); override;
end;
(* 再帰的にディレクトリを作成する *)
procedure RecursiveCreateDir(path: string);
function HogeExtractFileDir(const path: string): string;
function Convert2FName(const fname: string): string;
(*=======================================================*)
implementation
(*=======================================================*)
(* *)
destructor TTmpFile.Destroy;
begin
Clear;
inherited;
end;
(* *)
procedure TTmpFile.Clear;
var
i: integer;
begin
for i := 0 to Count -1 do begin
DeleteFile(Strings[i]);
end;
inherited;
end;
(* *)
procedure TTmpFile.Delete(index: integer);
begin
DeleteFile(Strings[index]);
inherited;
end;
(*=======================================================*)
(* 'ニュース速報+' を含むパス名をExtractFileDirに渡すと *)
(* +までとられた・・・(´Д`) *)
(* UpdatePack1では起きない。Delphi 6 Personal無印固有かも *)
function HogeExtractFileDir(const path: string): string;
var
w: WideString;
i: integer;
begin
w := path;
result := '';
for i := length(w) -1 downto 1 do
begin
if (w[i] = '\') or (w[i] = '/') then
begin
if (i = 1) or (w[i-1] = ':') then
result := Copy(w, 1, i)
else
result := Copy(w, 1, i -1);
break;
end;
end;
end;
(* 再帰的にディレクトリを作成する *)
procedure RecursiveCreateDir(path: string);
begin
if (length(path) <= 0) then
exit;
if AnsiLastChar(path) = '\' then
exit;
if DirectoryExists(path) then
exit;
RecursiveCreateDir(HogeExtractFileDir(path));
CreateDir(path);
end;
function Convert2FName(const fname: string): string;
var
wstr: WideString;
i: integer;
begin
if AnsiSameText(fname, 'CON') then
result := '$CON'
else if AnsiSameText(fname, 'AUX') then
result := '$AUX'
else if AnsiSameText(fname, 'NUL') then
result := '$NUL'
else begin
wstr := fname;
result := '';
for i := 1 to length(wstr) do
begin
case wstr[i] of
'\': result := result + '$Backslash';
'/': result := result + '$Slash';
':': result := result + '$Colon';
'*': result := result + '$Asterisk';
'?': result := result + '$Question';
'"': result := result + 'Quote';
'<': result := result + 'LT';
'>': result := result + 'GT';
'|': result := result + 'Bar';
else
result := result + wstr[i];
end;
end;
end;
// ▼ Nightly Sun Oct 10 04:57:28 2004 UTC by view
//名前の末尾に空白が含まれる板でスレが保存されない不具合を修正
if Length(Result) > 0 then
begin
Result := Trim(Result);
if Length(Result) = 0 then
Result := '$SPACE';
end;
// ▲ Nightly Sun Oct 10 04:57:28 2004 UTC by view
end;
end.
|
unit Model.Helpers.Edit;
interface
uses
vcl.stdCtrls, SysUtils;
type
TEditHelper = class helper for TEdit
procedure TextCurrency(aValue:String);overload;
procedure TextCurrency(aValue:Currency);overload;
procedure TextInteger(aValue:integer);
function IsEmpty:Boolean;
function ToInteger:Integer;
function ToCurrency:Currency;
end;
implementation
{ TEditHelper }
procedure TEditHelper.TextCurrency(aValue: String);
begin
TextCurrency(StrToCurrDef(aValue,0));
end;
function TEditHelper.IsEmpty: Boolean;
begin
Result := False;
if (Trim(Self.Text) = '') then
Result := True;
end;
procedure TEditHelper.TextCurrency(aValue: Currency);
begin
Self.Text := FormatFloat('#,##0.00',aValue)
end;
procedure TEditHelper.TextInteger(aValue: integer);
begin
Self.Text := IntToStr(aValue);
end;
function TEditHelper.ToCurrency: Currency;
begin
Result := StrToCurrDef(Self.Text,0);
end;
function TEditHelper.ToInteger: Integer;
begin
Result := StrToIntDef(Self.Text,0);
end;
end.
|
unit SORM.Model.Conexao.Interfaces;
interface
uses
Data.DB, FireDAC.Comp.Client;
type
iModelConexao = interface
['{EA2113CF-7092-48E2-8D45-21D1B9A34B8B}']
function Connection: TCustomConnection;
function Firedac : TFDConnection;
end;
iModelQuery = interface
['{82240D22-F80E-41AE-9C80-0BA1F3D25A52}']
function Query: TObject;
function OpenTable(Table: string): iModelQuery;
end;
iModelConexaoFactory = interface
['{F0A27B3C-C783-415D-9E9B-D2B6DD599C5E}']
function Conexao : iModelConexao;
function Query : iModelQuery;
end;
implementation
end.
|
{******************************************************************************}
{ }
{ Indy (Internet Direct) - Internet Protocols Simplified }
{ }
{ https://www.indyproject.org/ }
{ https://gitter.im/IndySockets/Indy }
{ }
{******************************************************************************}
{ }
{ This file is part of the Indy (Internet Direct) project, and is offered }
{ under the dual-licensing agreement described on the Indy website. }
{ (https://www.indyproject.org/license/) }
{ }
{ Copyright: }
{ (c) 1993-2020, Chad Z. Hower and the Indy Pit Crew. All rights reserved. }
{ }
{******************************************************************************}
{ }
{ Originally written by: Fabian S. Biehn }
{ fbiehn@aagon.com (German & English) }
{ }
{ Contributers: }
{ Here could be your name }
{ }
{******************************************************************************}
// This File is auto generated!
// Any change to this file should be made in the
// corresponding unit in the folder "intermediate"!
// Generation date: 28.10.2020 15:24:13
unit IdOpenSSLHeaders_whrlpool;
interface
// Headers for OpenSSL 1.1.1
// whrlpool.h
{$i IdCompilerDefines.inc}
uses
Classes,
IdCTypes,
IdGlobal,
IdOpenSSLConsts;
const
WHIRLPOOL_DIGEST_LENGTH = 512 div 8;
WHIRLPOOL_BBLOCK = 512;
WHIRLPOOL_COUNTER = 256 div 8;
type
WHIRLPOOL_CTX_union = record
case Byte of
0: (c: array[0 .. WHIRLPOOL_DIGEST_LENGTH -1] of Byte);
(* double q is here to ensure 64-bit alignment *)
1: (q: array[0 .. (WHIRLPOOL_DIGEST_LENGTH div SizeOf(TIdC_DOUBLE)) -1] of TIdC_DOUBLE);
end;
WHIRLPOOL_CTX = record
H: WHIRLPOOL_CTX_union;
data: array[0 .. (WHIRLPOOL_BBLOCK div 8) -1] of Byte;
bitoff: TIdC_UINT;
bitlen: array[0 .. (WHIRLPOOL_COUNTER div SizeOf(TIdC_SIZET)) -1] of TIdC_SIZET;
end;
PWHIRLPOOL_CTX = ^WHIRLPOOL_CTX;
procedure Load(const ADllHandle: TIdLibHandle; const AFailed: TStringList);
procedure UnLoad;
var
WHIRLPOOL_Init: function(c: PWHIRLPOOL_CTX): TIdC_INT cdecl = nil;
WHIRLPOOL_Update: function(c: PWHIRLPOOL_CTX; inp: Pointer; bytes: TIdC_SIZET): TIdC_INT cdecl = nil;
WHIRLPOOL_BitUpdate: procedure(c: PWHIRLPOOL_CTX; inp: Pointer; bits: TIdC_SIZET) cdecl = nil;
WHIRLPOOL_Final: function(md: PByte; c: PWHIRLPOOL_CTX): TIdC_INT cdecl = nil;
WHIRLPOOL: function(inp: Pointer; bytes: TIdC_SIZET; md: PByte): PByte cdecl = nil;
implementation
procedure Load(const ADllHandle: TIdLibHandle; const AFailed: TStringList);
function LoadFunction(const AMethodName: string; const AFailed: TStringList): Pointer;
begin
Result := LoadLibFunction(ADllHandle, AMethodName);
if not Assigned(Result) then
AFailed.Add(AMethodName);
end;
begin
WHIRLPOOL_Init := LoadFunction('WHIRLPOOL_Init', AFailed);
WHIRLPOOL_Update := LoadFunction('WHIRLPOOL_Update', AFailed);
WHIRLPOOL_BitUpdate := LoadFunction('WHIRLPOOL_BitUpdate', AFailed);
WHIRLPOOL_Final := LoadFunction('WHIRLPOOL_Final', AFailed);
WHIRLPOOL := LoadFunction('WHIRLPOOL', AFailed);
end;
procedure UnLoad;
begin
WHIRLPOOL_Init := nil;
WHIRLPOOL_Update := nil;
WHIRLPOOL_BitUpdate := nil;
WHIRLPOOL_Final := nil;
WHIRLPOOL := nil;
end;
end.
|
unit UUADConfiguration;
{ ClickForms Application }
{ Bradford Technologies, Inc. }
{ All Rights Reserved }
{ Source Code Copyrighted © 1998-2011 by Bradford Technologies, Inc. }
{ Purpose: Configuration settings for the Uniform Appraisal DataSet}
interface
uses
MSXML6_TLB,
UGlobals;
type
/// summary: Configuration settings for the Uniform Appraisal DataSet.
/// remarks: Developed to meet the Uniform Appraisal Dataset (UAD) requirements of the GSEs.
TUADConfiguration = class
class function Cell(const XID: Integer; const UID: CellUID): IXMLDOMElement;
class function Database: IXMLDOMDocument2;
class function Dialog(const DialogID: String): IXMLDOMElement;
class function Mismo(const Cell: IXMLDOMElement; const UADEnabled: Boolean): IXMLDOMElement;
end;
implementation
uses
SysUtils,
UDebugTools,
UPaths;
var
/// summary: The configuraion database as an XML document.
GDatabase: IXMLDOMDocument2;
// --- TUADConfiguration -------------------------------------
// summary: Gets the xml element from the database for the specified cell.
class function TUADConfiguration.Cell(const XID: Integer; const UID: CellUID): IXMLDOMElement;
function FindMatchingNode(const XPath: String; const NodeList: IXMLDOMNodeList): IXMLDOMNode;
var
Index: Integer;
begin
Result := nil;
for Index := 0 to NodeList.length - 1 do
begin
Result := NodeList.item[Index].selectSingleNode(XPath);
if Assigned(Result) then
Break;
end;
end;
const
CXPathBase = '/UniformAppraisalDataSet/Cells/Cell[@XID="%d"]';
CXPathMatch1 = '.[@FormID="%d" and @Page="%d" and @Cell="%d"]';
CXPathMatch2 = '.[@FormID="%d" and @Page="%d" and not(@Cell)]';
CXPathMatch3 = '.[@FormID="%d" and not(@Page) and not(@Cell)]';
CXPathMatch4 = '.[not(@FormID) and not(@Page) and not(@Cell)]';
var
Document: IXMLDOMDocument2;
Node: IXMLDOMNode;
NodeList: IXMLDOMNodeList;
XPath: String;
begin
Document := Database;
XPath := Format(CXPathBase, [XID]);
NodeList := Document.selectNodes(XPath);
XPath := Format(CXPathMatch1, [UID.FormID, UID.Pg, UID.Num]);
Node := FindMatchingNode(XPath, NodeList);
if not Assigned(Node) then
begin
XPath := Format(CXPathMatch2, [UID.FormID, UID.Pg]);
Node := FindMatchingNode(XPath, NodeList);
end;
if not Assigned(Node) then
begin
XPath := Format(CXPathMatch3, [UID.FormID]);
Node := FindMatchingNode(XPath, NodeList);
end;
if not Assigned(Node) then
begin
XPath := CXPathMatch4;
Node := FindMatchingNode(XPath, NodeList);
end;
Supports(Node, IID_IXMLDOMElement, Result);
end;
/// summary: Gets the configuration database as an interface to an XML document.
class function TUADConfiguration.Database: IXMLDOMDocument2;
const
CDatabaseFileName = 'UAD.DAT';
CXPath_DatabaseVersion = '/UniformAppraisalDataSet[@Version="2"]';
var
FileName: String;
OK: Boolean;
begin
if not Assigned(GDatabase) then
begin
FileName := TCFFilePaths.MISMO + CDatabaseFileName;
GDatabase := CoDomDocument.Create;
GDatabase.async := False;
OK := GDatabase.load(FileName);
if not OK then
begin
TDebugTools.WriteLine('UADConfiguration: ' + GDatabase.parseError.reason);
GDatabase := nil;
end
else if not Assigned(GDatabase.selectSingleNode(CXPath_DatabaseVersion)) then
begin
TDebugTools.WriteLine('UADConfiguration: Incompatible database version.');
GDatabase := nil;
end;
end;
Result := GDatabase;
end;
// summary: Gets the xml element from the database for the specified dialog.
class function TUADConfiguration.Dialog(const DialogID: String): IXMLDOMElement;
const
CXPath = '/UniformAppraisalDataSet/Dialogs/Dialog[@DialogID="%s"]';
var
Document: IXMLDOMDocument2;
Node: IXMLDOMNode;
XPath: String;
begin
Document := Database;
XPath := Format(CXPath, [DialogID]);
Node := Document.selectSingleNode(XPath);
Supports(Node, IID_IXMLDOMElement, Result);
end;
/// summary: Gets the mismo xml element from the database for the specified cell.
class function TUADConfiguration.Mismo(const Cell: IXMLDOMElement; const UADEnabled: Boolean): IXMLDOMElement;
const
CXPathMismo26 = 'Mismo26';
CXPathMismo26GSE = 'Mismo26GSE';
var
Node: IXMLDOMNode;
begin
Node := nil;
if Assigned(Cell) then
begin
if UADEnabled then
Node := Cell.selectSingleNode(CXPathMismo26GSE)
else
Node := Cell.selectSingleNode(CXPathMismo26);
end;
Supports(Node, IID_IXMLDOMElement, Result);
end;
end.
|
program zy (inout, output) ;
type
tRefListe = ^tListe;
tListe = record
info : integer;
next : tRefListe
end;
var
mylist : tRefListe;
procedure einfuegen ( inInfo: integer; inEinfuegenAmAnfang: Boolean;
var ioRefAnfang: tRefListe);
var
Zeiger, Element: tRefListe;
begin
Zeiger := ioRefAnfang;
new(Element);
Element^.info := inInfo;
while Zeiger^.next <> ioRefAnfang do
Zeiger := Zeiger^.next;
if not inEinfuegenAmAnfang then
begin
Element^.next := ioRefAnfang;
Zeiger^.next := Element;
ioRefAnfang := Element
end
else
begin
Zeiger^.next := Element;
Element^.next := ioRefAnfang
end
end;
procedure LiesListe(var outListe : tRefListe);
{ Liest eine (evtl. leere) Liste ein und gibt deren Anfangszeiger outListe zurueck. }
var
Anzahl : integer;
i : integer;
neueZahl : integer;
Listenanfang,
Listenende : tRefListe;
begin
Listenanfang := nil;
repeat
write ('Wie viele Zahlen wollen Sie eingeben? ');
readln (Anzahl);
until Anzahl >= 0;
write ('Bitte geben Sie ', Anzahl, ' Zahlen ein: ');
{ Liste aufbauen }
for i := 1 to Anzahl do
begin
read (neueZahl);
if Listenanfang = nil then
begin
new (Listenanfang);
Listenanfang^.next := nil;
Listenanfang^.info := neueZahl;
Listenende := Listenanfang;
end
else
begin
new (Listenende^.next);
Listenende := Listenende^.next;
Listenende^.next := nil;
Listenende^.info := neueZahl
end { if Liste = nil }
end; { for }
outListe := Listenanfang;
writeln
end; { LiesListe }
procedure gibListeAus (inListe : tRefListe);
{ gibt die Liste mit Anfangszeiger inListe aus }
var
ListenElement : tRefListe;
begin
ListenElement := inListe;
while ListenElement <> nil do
begin
write(ListenElement^.info, ' ');
ListenElement := ListenElement^.next;
end;
writeln;
end; { gibListeAus }
begin
LiesListe(mylist);
einfuegen(8, true, mylist);
gibListeAus(mylist)
end.
|
unit ConfigIdentificacion;
interface
type
TConfigIdentificacion = class
private
function GetAlEntrar: boolean;
function GetContrasenaBloquear: string;
function GetRellenoAutomatico: boolean;
function GetUsuario: string;
procedure SetAlEntrar(const Value: boolean);
procedure SetRellenoAutomatico(const Value: boolean);
procedure SetUsuario(const Value: string);
procedure SetContrasenaBloquear(const Value: string);
function GetUsuarioBloquear: string;
procedure SetUsuarioBloquear(const Value: string);
function GetBloquear: boolean;
procedure SetBloquear(const Value: boolean);
public
property Usuario: string read GetUsuario write SetUsuario;
property UsuarioBloquear: string read GetUsuarioBloquear write SetUsuarioBloquear;
property ContrasenaBloquear: string read GetContrasenaBloquear write SetContrasenaBloquear;
property Bloquear: boolean read GetBloquear write SetBloquear;
property AlEntrar: boolean read GetAlEntrar write SetAlEntrar;
property RellenoAutomatico: boolean read GetRellenoAutomatico write SetRellenoAutomatico;
end;
implementation
uses dmConfiguracion;
const
SECCION: string = 'Configuracion.Identificacion';
{ TConfigIdentificacion }
function TConfigIdentificacion.GetAlEntrar: boolean;
begin
result := Configuracion.ReadBoolean(SECCION, 'AlEntrar', false);
end;
function TConfigIdentificacion.GetBloquear: boolean;
begin
result := Configuracion.ReadBoolean(SECCION, 'Bloquear', false);
end;
function TConfigIdentificacion.GetContrasenaBloquear: string;
begin
result := Configuracion.ReadString(SECCION, 'ContrasenaBloquear', '');
end;
function TConfigIdentificacion.GetRellenoAutomatico: boolean;
begin
result := Configuracion.ReadBoolean(SECCION, 'RellenoAutomatico', false);
end;
function TConfigIdentificacion.GetUsuario: string;
begin
result := Configuracion.ReadString(SECCION, 'Usuario', '');
end;
function TConfigIdentificacion.GetUsuarioBloquear: string;
begin
Result := Configuracion.ReadString(SECCION, 'UsuarioBloquear', '');
end;
procedure TConfigIdentificacion.SetAlEntrar(const Value: boolean);
begin
Configuracion.WriteBoolean(SECCION, 'AlEntrar', Value);
end;
procedure TConfigIdentificacion.SetBloquear(const Value: boolean);
begin
Configuracion.WriteBoolean(SECCION, 'Bloquear', Value);
end;
procedure TConfigIdentificacion.SetContrasenaBloquear(const Value: string);
begin
Configuracion.WriteString(SECCION, 'ContrasenaBloquear', Value);
end;
procedure TConfigIdentificacion.SetRellenoAutomatico(const Value: boolean);
begin
Configuracion.WriteBoolean(SECCION, 'RellenoAutomatico', Value);
end;
procedure TConfigIdentificacion.SetUsuario(const Value: string);
begin
Configuracion.WriteString(SECCION, 'Usuario', Value);
end;
procedure TConfigIdentificacion.SetUsuarioBloquear(const Value: string);
begin
Configuracion.WriteString(SECCION, 'UsuarioBloquear', Value);
end;
end.
|
unit NtUtils.Files.Operations;
{
The module provides support for various file operations using Native API.
}
interface
uses
Ntapi.WinNt, Ntapi.ntioapi,DelphiApi.Reflection, DelphiUtils.AutoObjects,
DelphiUtils.Async, NtUtils, NtUtils.Files;
type
TFileStreamInfo = record
[Bytes] StreamSize: Int64;
[Bytes] StreamAllocationSize: Int64;
StreamName: String;
end;
TFileHardlinkLinkInfo = record
ParentFileID: TFileId;
FileName: String;
end;
{ Operations }
// Synchronously wait for a completion of an operation on an asynchronous handle
procedure AwaitFileOperation(
var Result: TNtxStatus;
[Access(SYNCHRONIZE)] hFile: THandle;
const xIoStatusBlock: IMemory<PIoStatusBlock>
);
// Read from a file into a buffer
function NtxReadFile(
[Access(FILE_READ_DATA)] hFile: THandle;
[out] Buffer: Pointer;
BufferSize: Cardinal;
const Offset: UInt64 = FILE_USE_FILE_POINTER_POSITION;
[opt] const AsyncCallback: TAnonymousApcCallback = nil
): TNtxStatus;
// Write to a file from a buffer
function NtxWriteFile(
[Access(FILE_WRITE_DATA)] hFile: THandle;
[in] Buffer: Pointer;
BufferSize: Cardinal;
const Offset: UInt64 = FILE_USE_FILE_POINTER_POSITION;
[opt] const AsyncCallback: TAnonymousApcCallback = nil
): TNtxStatus;
// Delete a file
function NtxDeleteFile(
const Name: String;
[opt] const ObjectAttributes: IObjectAttributes = nil
): TNtxStatus;
// Rename a file
function NtxRenameFile(
[Access(_DELETE)] hFile: THandle;
const NewName: String;
Flags: TFileRenameFlags = 0;
[opt] RootDirectory: THandle = 0;
InfoClass: TFileInformationClass = FileRenameInformation
): TNtxStatus;
// Creare a hardlink for a file
function NtxHardlinkFile(
[Access(0)] hFile: THandle;
const NewName: String;
Flags: TFileLinkFlags = 0;
[opt] RootDirectory: THandle = 0;
InfoClass: TFileInformationClass = FileLinkInformation
): TNtxStatus;
{ Information }
// Query variable-length information
function NtxQueryFile(
hFile: THandle;
InfoClass: TFileInformationClass;
out xMemory: IMemory;
InitialBuffer: Cardinal = 0;
[opt] GrowthMethod: TBufferGrowthMethod = nil
): TNtxStatus;
// Query basic information by file name
function NtxQueryAttributesFile(
[Access(FILE_READ_ATTRIBUTES)] const ObjectAttributes: IObjectAttributes;
out BasicInfo: TFileBasicInformation
): TNtxStatus;
// Query extended information by file name
function NtxQueryFullAttributesFile(
[Access(FILE_READ_ATTRIBUTES)] const ObjectAttributes: IObjectAttributes;
out NetworkInfo: TFileNetworkOpenInformation
): TNtxStatus;
// Set variable-length information
function NtxSetFile(
hFile: THandle;
InfoClass: TFileInformationClass;
[in] Buffer: Pointer;
BufferSize: Cardinal
): TNtxStatus;
type
NtxFile = class abstract
// Query fixed-size information
class function Query<T>(
hFile: THandle;
InfoClass: TFileInformationClass;
out Buffer: T
): TNtxStatus; static;
// Query fixed-size information by name
class function QueryByName<T>(
const FileName: String;
InfoClass: TFileInformationClass;
out Buffer: T;
[opt] const ObjectAttributes: IObjectAttributes = nil
): TNtxStatus; static;
// Set fixed-size information
class function &Set<T>(
hFile: THandle;
InfoClass: TFileInformationClass;
const Buffer: T
): TNtxStatus; static;
end;
// Query a name of a file without the device name
function NtxQueryNameFile(
[Access(0)] hFile: THandle;
out Name: String;
InfoClass: TFileInformationClass = FileNameInformation
): TNtxStatus;
// Modify a short (alternative) name of a file
function NtxSetShortNameFile(
[Access(_DELETE)] hFile: THandle;
const ShortName: String
): TNtxStatus;
// Determine the maximum access we can open a file for without failing
function NtxQueryMaximumAccessFile(
[in] OpenParameters: IFileOpenParameters;
out MaximumAccess: TFileAccessMask
): TNtxStatus;
{ Enumeration }
// Enumerate file streams
function NtxEnumerateStreamsFile(
[Access(0)] hFile: THandle;
out Streams: TArray<TFileStreamInfo>
): TNtxStatus;
// Enumerate hardlinks pointing to the file
function NtxEnumerateHardLinksFile(
[Access(0)] hFile: THandle;
out Links: TArray<TFileHardlinkLinkInfo>
): TNtxStatus;
// Enumerate processes that use this file. Requires FILE_READ_ATTRIBUTES.
function NtxEnumerateUsingProcessesFile(
[Access(FILE_READ_ATTRIBUTES)] hFile: THandle;
out PIDs: TArray<TProcessId>
): TNtxStatus;
implementation
uses
Ntapi.ntstatus, Ntapi.ntrtl, Ntapi.Versions, NtUtils.SysUtils, NtUtils.Ldr,
NtUtils.Objects, NtUtils.Files.Open, NtUtils.Synchronization;
{$BOOLEVAL OFF}
{$IFOPT R+}{$DEFINE R+}{$ENDIF}
{$IFOPT Q+}{$DEFINE Q+}{$ENDIF}
{ Operations }
procedure AwaitFileOperation;
begin
// When performing a synchronous operation on an asynchronous handle, we
// must wait for completion ourselves.
if Result.Status = STATUS_PENDING then
begin
Result := NtxWaitForSingleObject(hFile);
// On success, extract the status. On failure, the only option we
// have is to prolong the lifetime of the I/O status block indefinitely
// because we never know when the system will write to its memory.
if Result.IsSuccess then
Result.Status := xIoStatusBlock.Data.Status
else
xIoStatusBlock.AutoRelease := False;
end;
end;
function NtxReadFile;
var
ApcContext: IAnonymousIoApcContext;
xIsb: IMemory<PIoStatusBlock>;
begin
Result.Location := 'NtReadFile';
Result.LastCall.Expects<TIoFileAccessMask>(FILE_READ_DATA);
Result.Status := NtReadFile(hFile, 0, GetApcRoutine(AsyncCallback),
Pointer(ApcContext), PrepareApcIsbEx(ApcContext, AsyncCallback, xIsb),
Buffer, BufferSize, @Offset, nil);
// Keep the context alive until the callback executes
if Assigned(ApcContext) and Result.IsSuccess then
ApcContext._AddRef;
// Wait on asynchronous handles if no callback is available
if not Assigned(AsyncCallback) then
AwaitFileOperation(Result, hFile, xIsb);
end;
function NtxWriteFile;
var
ApcContext: IAnonymousIoApcContext;
xIsb: IMemory<PIoStatusBlock>;
begin
Result.Location := 'NtWriteFile';
Result.LastCall.Expects<TIoFileAccessMask>(FILE_WRITE_DATA);
Result.Status := NtWriteFile(hFile, 0, GetApcRoutine(AsyncCallback),
Pointer(ApcContext), PrepareApcIsbEx(ApcContext, AsyncCallback, xIsb),
Buffer, BufferSize, @Offset, nil);
// Keep the context alive until the callback executes
if Assigned(ApcContext) and Result.IsSuccess then
ApcContext._AddRef;
// Wait on asynchronous handles if no callback is available
if not Assigned(AsyncCallback) then
AwaitFileOperation(Result, hFile, xIsb);
end;
function NtxDeleteFile;
begin
Result.Location := 'NtDeleteFile';
Result.Status := NtDeleteFile(AttributeBuilder(ObjectAttributes)
.UseName(Name).ToNative^);
end;
function NtxpSetRenameInfoFile(
hFile: THandle;
TargetName: String;
Flags: Cardinal;
RootDirectory: THandle;
InfoClass: TFileInformationClass
): TNtxStatus;
var
xMemory: IMemory<PFileRenameInformationEx>; // aka PFileLinkInformationEx
begin
IMemory(xMemory) := Auto.AllocateDynamic(SizeOf(TFileRenameInformation) +
Length(TargetName) * SizeOf(WideChar));
// Prepare a variable-length buffer for rename or hardlink operations
xMemory.Data.Flags := Flags;
xMemory.Data.RootDirectory := RootDirectory;
xMemory.Data.FileNameLength := Length(TargetName) * SizeOf(WideChar);
Move(PWideChar(TargetName)^, xMemory.Data.FileName,
xMemory.Data.FileNameLength);
Result := NtxSetFile(hFile, InfoClass, xMemory.Data, xMemory.Size);
end;
function NtxRenameFile;
begin
// Note: if you get sharing violation when using RootDirectory, open it with
// FILE_TRAVERSE | FILE_READ_ATTRIBUTES access.
Result := NtxpSetRenameInfoFile(hFile, NewName, Flags,
RootDirectory, InfoClass);
Result.LastCall.Expects<TFileAccessMask>(_DELETE);
end;
function NtxHardlinkFile;
begin
Result := NtxpSetRenameInfoFile(hFile, NewName, Flags,
RootDirectory, InfoClass);
end;
{ Information }
function GrowFileDefault(
const Memory: IMemory;
Required: NativeUInt
): NativeUInt;
begin
Result := Memory.Size shl 1 + 256; // x2 + 256 B
end;
function NtxQueryFile;
var
Isb: TIoStatusBlock;
begin
Result.Location := 'NtQueryInformationFile';
Result.LastCall.UsesInfoClass(InfoClass, icQuery);
// NtQueryInformationFile does not return the required size. We either need
// to know how to grow the buffer, or we should guess.
if not Assigned(GrowthMethod) then
GrowthMethod := GrowFileDefault;
xMemory := Auto.AllocateDynamic(InitialBuffer);
repeat
Isb.Information := 0;
Result.Status := NtQueryInformationFile(hFile, Isb, xMemory.Data,
xMemory.Size, InfoClass);
until not NtxExpandBufferEx(Result, xMemory, Isb.Information, GrowthMethod);
end;
function NtxQueryAttributesFile;
begin
Result.Location := 'NtQueryAttributesFile';
Result.LastCall.Expects<TFileAccessMask>(FILE_READ_ATTRIBUTES);
Result.Status := NtQueryAttributesFile(ObjectAttributes.ToNative^, BasicInfo);
end;
function NtxQueryFullAttributesFile;
begin
Result.Location := 'NtQueryFullAttributesFile';
Result.LastCall.Expects<TFileAccessMask>(FILE_READ_ATTRIBUTES);
Result.Status := NtQueryFullAttributesFile(ObjectAttributes.ToNative^,
NetworkInfo);
end;
function NtxSetFile;
var
Isb: TIoStatusBlock;
begin
Result.Location := 'NtSetInformationFile';
Result.LastCall.UsesInfoClass(InfoClass, icSet);
Result.Status := NtSetInformationFile(hFile, Isb, Buffer,
BufferSize, InfoClass);
end;
class function NtxFile.Query<T>;
var
Isb: TIoStatusBlock;
begin
Result.Location := 'NtQueryInformationFile';
Result.LastCall.UsesInfoClass(InfoClass, icQuery);
Result.Status := NtQueryInformationFile(hFile, Isb, @Buffer,
SizeOf(Buffer), InfoClass);
end;
class function NtxFile.QueryByName<T>;
var
Isb: TIoStatusBlock;
hxFile: IHandle;
begin
if LdrxCheckNtDelayedImport('NtQueryInformationByName').IsSuccess then
begin
Result.Location := 'NtQueryInformationByName';
Result.LastCall.UsesInfoClass(InfoClass, icQuery);
Result.LastCall.Expects<TFileAccessMask>(FILE_READ_ATTRIBUTES);
Result.Status := NtQueryInformationByName(
AttributeBuilder(ObjectAttributes).UseName(FileName).ToNative^,
Isb,
@Buffer,
SizeOf(Buffer),
InfoClass
);
end
else
begin
// Fallback to opening the file manually on older versions
Result := NtxOpenFile(hxFile, FileOpenParameters
.UseFileName(FileName)
.UseRoot(AttributeBuilder(ObjectAttributes).Root)
.UseAccess(FILE_READ_ATTRIBUTES)
);
if Result.IsSuccess then
Result := Query(hxFile.Handle, InfoClass, Buffer);
end;
end;
class function NtxFile.&Set<T>;
begin
Result := NtxSetFile(hFile, InfoClass, @Buffer, SizeOf(Buffer));
end;
function GrowFileName(
const Memory: IMemory;
BufferSize: NativeUInt
): NativeUInt;
begin
Result := SizeOf(Cardinal) + PFileNameInformation(Memory.Data).FileNameLength;
end;
function NtxQueryNameFile;
var
xMemory: IMemory<PFileNameInformation>;
begin
Result := NtxQueryFile(hFile, InfoClass, IMemory(xMemory),
SizeOf(TFileNameInformation), GrowFileName);
if Result.IsSuccess then
SetString(Name, xMemory.Data.FileName, xMemory.Data.FileNameLength div
SizeOf(WideChar));
end;
function NtxSetShortNameFile;
var
Buffer: IMemory<PFileNameInformation>;
begin
IMemory(Buffer) := Auto.AllocateDynamic(SizeOf(TFileNameInformation) +
Length(ShortName) * SizeOf(WideChar));
Buffer.Data.FileNameLength := Length(ShortName) * SizeOf(WideChar);
Move(PWideChar(ShortName)^, Buffer.Data.FileName, Buffer.Data.FileNameLength);
Result := NtxSetFile(hFile, FileShortNameInformation, Buffer.Data,
Buffer.Size);
end;
function NtxQueryMaximumAccessFile;
var
hxFile: IHandle;
BitsToTest, AccessMask: TFileAccessMask;
Bit: Byte;
Stats: TFileStatInformation;
begin
MaximumAccess := 0;
// Avoid getting stuck on oplocks
OpenParameters := OpenParameters.UseOpenOptions(OpenParameters.OpenOptions
or FILE_COMPLETE_IF_OPLOCKED);
// Don't recall data since we are not interested in it
if not BitTest(OpenParameters.OpenOptions and FILE_DIRECTORY_FILE) then
OpenParameters := OpenParameters.UseOpenOptions(OpenParameters.OpenOptions
or FILE_OPEN_NO_RECALL);
// Prefer opening reparse points but let the caller overwrite this
// behavior by using names ending with "\"
if (OpenParameters.FileName <> '') and
(OpenParameters.FileName[High(OpenParameters.FileName)] <> '\') then
OpenParameters := OpenParameters.UseOpenOptions(OpenParameters.OpenOptions
or FILE_OPEN_REPARSE_POINT);
// Try maximum access first
OpenParameters := OpenParameters.UseAccess(MAXIMUM_ALLOWED);
Result := NtxOpenFile(hxFile, OpenParameters);
if not Result.IsSuccess and
(Result.Status <> STATUS_ACCESS_DENIED) and
(Result.Status <> STATUS_SHARING_VIOLATION) then
Exit;
if Result.IsSuccess then
begin
// We got a maximum-allowed handle; determine what it means
Result := NtxFile.Query(hxFile.Handle, FileAccessInformation, MaximumAccess);
Exit;
end;
// Looks like we need to guess the access mask
BitsToTest := FILE_ALL_ACCESS and not SYNCHRONIZE;
// On RS2+ we can lower the threshold by querying the effective access
if RtlOsVersionAtLeast(OsWin10RS2) then
begin
OpenParameters := OpenParameters.UseAccess(FILE_READ_ATTRIBUTES);
Result := NtxOpenFile(hxFile, OpenParameters);
if Result.IsSuccess then
begin
Result := NtxFile.Query(hxFile.Handle, FileStatInformation, Stats);
if Result.IsSuccess then
BitsToTest := BitsToTest and Stats.EffectiveAccess;
end;
end;
// Test read-only rights at once first
if HasAny(BitsToTest and FILE_GENERIC_READ) then
begin
OpenParameters := OpenParameters.UseAccess(BitsToTest and FILE_GENERIC_READ);
Result := NtxOpenFile(hxFile, OpenParameters);
if Result.IsSuccess then
begin
Result := NtxFile.Query(hxFile.Handle, FileAccessInformation, AccessMask);
if Result.IsSuccess then
begin
MaximumAccess := MaximumAccess or AccessMask;
BitsToTest := BitsToTest and not AccessMask;
end;
end;
end;
// Test the remaining bits one-by-one
for Bit := 0 to 19 do
if BitTest(BitsToTest and (1 shl Bit)) then
begin
OpenParameters := OpenParameters.UseAccess(1 shl Bit);
Result := NtxOpenFile(hxFile, OpenParameters);
if Result.IsSuccess then
begin
Result := NtxFile.Query(hxFile.Handle, FileAccessInformation,
AccessMask);
if Result.IsSuccess then
begin
MaximumAccess := MaximumAccess or AccessMask;
BitsToTest := BitsToTest and not AccessMask;
end;
end;
end;
if MaximumAccess <> 0 then
Result.Status := STATUS_SUCCESS;
end;
{ Enumeration }
function NtxEnumerateStreamsFile;
var
xMemory: IMemory;
pStream: PFileStreamInformation;
begin
Result := NtxQueryFile(hFile, FileStreamInformation, xMemory,
SizeOf(TFileStreamInformation));
if not Result.IsSuccess then
Exit;
SetLength(Streams, 0);
pStream := xMemory.Data;
repeat
SetLength(Streams, Length(Streams) + 1);
Streams[High(Streams)].StreamSize := pStream.StreamSize;
Streams[High(Streams)].StreamAllocationSize := pStream.StreamAllocationSize;
SetString(Streams[High(Streams)].StreamName, pStream.StreamName,
pStream.StreamNameLength div SizeOf(WideChar));
if pStream.NextEntryOffset <> 0 then
pStream := Pointer(UIntPtr(pStream) + pStream.NextEntryOffset)
else
Break;
until False;
end;
function GrowFileLinks(
const Memory: IMemory;
Required: NativeUInt
): NativeUInt;
begin
Result := PFileLinksInformation(Memory.Data).BytesNeeded;
end;
function NtxEnumerateHardLinksFile;
var
xMemory: IMemory<PFileLinksInformation>;
pLink: PFileLinkEntryInformation;
i: Integer;
begin
Result := NtxQueryFile(hFile, FileHardLinkInformation, IMemory(xMemory),
SizeOf(TFileLinksInformation), GrowFileLinks);
if not Result.IsSuccess then
Exit;
SetLength(Links, xMemory.Data.EntriesReturned);
pLink := Pointer(@xMemory.Data.Entry);
i := 0;
repeat
if i > High(Links) then
Break;
// Note: we have only the filename and the ID of the parent directory
Links[i].ParentFileId := pLink.ParentFileId;
SetString(Links[i].FileName, pLink.FileName, pLink.FileNameLength);
if pLink.NextEntryOffset <> 0 then
pLink := Pointer(UIntPtr(pLink) + pLink.NextEntryOffset)
else
Break;
Inc(i);
until False;
end;
function NtxEnumerateUsingProcessesFile;
var
xMemory: IMemory<PFileProcessIdsUsingFileInformation>;
i: Integer;
begin
Result := NtxQueryFile(hFile, FileProcessIdsUsingFileInformation,
IMemory(xMemory), SizeOf(TFileProcessIdsUsingFileInformation));
Result.LastCall.Expects<TFileAccessMask>(FILE_READ_ATTRIBUTES);
if not Result.IsSuccess then
Exit;
SetLength(PIDs, xMemory.Data.NumberOfProcessIdsInList);
for i := 0 to High(PIDs) do
PIDs[i] := xMemory.Data.ProcessIdList{$R-}[i]{$IFDEF R+}{$R+}{$ENDIF};
end;
end.
|
unit USketch_JSonToXML;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics,msxmldom,Math,
uLKJSON, XMLDoc, Dialogs,XMLIntf,xmldom;
function ParseSketchLines(joSketch: TlkJSonBase): String;
function ParseSketchAreas(joSketch: TlkJSonBase): String;
function ParseSketchTexts(joSketch: TlkJSonBase): String;
function ConvertJSONToXML(joSketch: TlkJSonBase; pageNo: Integer; AreaList:TStringList):String;
var
FLog: TStringList;
implementation
uses
UUtil1,uUtil2, uStatus, uGlobals;
const
cSketchFileName = 'TempSketch.xml'; //this is file AS looks for on startup, if from previous sketch
var
FSketchDir:String;
function GetJsonString(aFieldName:String; js: TlkJsonObject):String;
begin
result := '';
if not (js.Field[aFieldName] is TLKJSONnull) then
if js.Field[aFieldname] is TlkJSONString then
result := js.GetString(aFieldName);
end;
function GetJsonInt0(aFieldName:String; js: TlkJsonObject):Integer;
begin
result := 0;
if not (js.Field[aFieldName] is TLKJSONnull) then
if js.Field[aFieldname] is TlkJSONnumber then
result := js.GetInt(aFieldName);
end;
function GetJsonBool(aFieldName:String; js:TlkJsonObject):Boolean;
var
aBool: Boolean;
begin
result := False;
if not (js.Field[aFieldName] is TLKJSONnull) then
if js.Field[aFieldname] is TlkJSONboolean then
begin
aBool := js.getBoolean(aFieldname);
result := aBool;
end;
end;
function GetJsonDouble(aFieldName:String; js: TlkJsonObject):Double;
begin
result := 0;
if not (js.Field[aFieldName] is TLKJSONnull) then
if js.Field[aFieldname] is TlkJSONnumber then
result := js.getDouble(aFieldName);
end;
function GetJsonCoordinate(aFieldName:String; js: TlkJsonObject; var X,Y:Double):Boolean;
var
jCoord: TlkJSonBase;
begin
result := True;
jCoord := js.Field[aFieldName];
if (not (jCoord.Field['X'] is TLKJSONnull)) and (not (jCoord.Field['Y'] is TLKJSONnull)) then
begin
if jCoord.Field['X'] <> nil then
X := jCoord.Field['X'].Value;
if jCoord.Field['Y'] <> nil then
Y := jCoord.Field['Y'].Value;
end;
end;
function BoolToStr(aBool:Boolean):String;
begin
if aBool then
result := 'True'
else
result := 'False';
end;
function ParseSketchLines(joSketch: TlkJSonBase): String;
var
jSketch, jLines, jLine: TlkJSonBase;
joLine: TlkJSonObject;
i,j: Integer;
SketchData, LinesData:String;
X,Y: Double;
sl:TStringList;
jCoord: TlkJSonBase;
aInt: Integer;
aBool: Boolean;
aBoolStr, aStr: String;
aDouble: Double;
begin
if joSketch.Field['Sketcher_Definition_Data'] <> nil then
jSketch := joSketch.Field['Sketcher_Definition_Data'];
sl := TStringList.create;
try
for i:= 0 to jSketch.Count -1 do
begin
joSketch := jSketch.Child[i] as TlkJSONObject; //get each comp
if joSketch = nil then continue;
jLines := joSketch.Field['Lines'];
if jLines <> nil then
for j:= 0 to jLines.Count -1 do
begin
jLine := jLines.Child[j];
joLine := jLine as TlkJSONObject; //get each comp
aStr := GetJsonString('Id', joLine);
sl.Add('ID = '+aStr);
aStr := GetJsonString('DimensionTextId', joLine);
sl.Add('DimensionTextID = '+ aStr);
//For Start X, Y
GetJsonCoordinate('Start', joLine, X, Y);
sl.Add(Format('Start: X=%8.2f,Y=%8.2f',[X,Y]));
//For End X, Y
GetJsonCoordinate('End', joLine, X, Y);
sl.Add(Format('End: X=%8.2f,Y=%8.2f',[X,Y]));
//For InitialStart X, Y
GetJsonCoordinate('InitialStart', joLine, X, Y);
sl.Add(Format('InitialStart: X=%8.2f,Y=%8.2f',[X,Y]));
//For InitialEnd X, Y
GetJsonCoordinate('InitialEnd', joLine, X, Y);
sl.Add(Format('InitialEnd: X=%8.2f,Y=%8.2f',[X,Y]));
//For values
aBoolStr := BoolToStr(GetJsonBool('IsUsed', joLine));
sl.Add('IsUsed = '+aBoolStr);
aBoolStr := BoolToStr(GetJsonBool('IsArc', joLine));
sl.Add('IsArc = '+aBoolStr);
aDouble := GetJsonDouble('LengthFt', joLine);
sl.Add(Format('LengthFt = %8.2f',[aDouble]));
aDouble := GetJsonDouble('HeightFt', joLine);
sl.Add(Format('HeightFt = %8.2f',[aDouble]));
aDouble := GetJsonDouble('RadiusFt', joLine);
sl.Add(Format('RadiusFt = %8.2f',[aDouble]));
aBoolStr := BoolToStr(GetJsonBool('IsArcRotated', joLine));
sl.Add('IsArcRotated = '+aBoolStr);
aInt := GetJsonint0('ArcAngle', joLine);
sl.Add(Format('ArcAngle = %d',[aInt]));
aInt := GetJsonint0('LineAngle', joLine);
sl.Add(Format('LineAngle = %d',[aInt]));
aBoolStr := BoolToStr(GetJsonBool('InverseRotation', joLine));
sl.Add('InverseRotation = '+aBoolStr);
aBoolStr := BoolToStr(GetJsonBool('IsHorizontal', joLine));
sl.Add('IsHorizontal = '+aBoolStr);
aBoolStr := BoolToStr(GetJsonBool('IsVertical', joLine));
sl.Add('IsVertical = '+aBoolStr);
sl.add(' ');
end;
end;
finally
result := sl.Text;
sl.Free;
end;
end;
function ParseSketchAreas(joSketch: TlkJSonBase): String;
var
jSketch, jAreas, jEdgeIds, jEdges, js: TlkJSonBase;
joEdgeIds,joEdges: TlkJSonObject;
i,j,k,l: Integer;
SketchData, LinesData:String;
X,Y: Double;
sl:TStringList;
jCoord: TlkJSonBase;
aInt: Integer;
aBool: Boolean;
aBoolStr, aStr: String;
aDouble: Double;
aCount: Integer;
begin
if joSketch.Field['Sketcher_Definition_Data'] <> nil then
jSketch := joSketch.Field['Sketcher_Definition_Data'];
sl := TStringList.create;
try
for i:= 0 to jSketch.Count -1 do
begin
joSketch := jSketch.Child[i] as TlkJSONObject; //get each comp
if joSketch = nil then continue;
jAreas := joSketch.Field['Areas'];
if jAreas <> nil then
for j:= 0 to jAreas.Count -1 do
begin
jEdges := jAreas.Child[j].Field['Edges'];
if jEdges <> nil then
for k:= 0 to jEdges.Count - 1 do
begin //handle EdgeIds
joEdges := jEdges.Child[k] as TlkJSonObject;
aStr := GetJsonString('Id', joEdges);
sl.Add('ID = '+aStr);
aStr := GetJsonString('DimensionTextId', joEdges);
sl.Add('DimensionTextID = '+ aStr);
//For Start X, Y
GetJsonCoordinate('Start', joEdges, X, Y);
sl.Add(Format('Start: X=%8.2f,Y=%8.2f',[X,Y]));
//For End X, Y
GetJsonCoordinate('End', joEdges, X, Y);
sl.Add(Format('End: X=%8.2f,Y=%8.2f',[X,Y]));
//For InitialStart X, Y
GetJsonCoordinate('InitialStart', joEdges, X, Y);
sl.Add(Format('InitialStart: X=%8.2f,Y=%8.2f',[X,Y]));
//For InitialEnd X, Y
GetJsonCoordinate('InitialEnd', joEdges, X, Y);
sl.Add(Format('InitialEnd: X=%8.2f,Y=%8.2f',[X,Y]));
//For values
aBoolStr := BoolToStr(GetJsonBool('IsUsed', joEdges));
sl.Add('IsUsed = '+aBoolStr);
aBoolStr := BoolToStr(GetJsonBool('IsArc', joEdges));
sl.Add('IsArc = '+aBoolStr);
aDouble := GetJsonDouble('LengthFt', joEdges);
sl.Add(Format('LengthFt = %8.2f',[aDouble]));
aDouble := GetJsonDouble('HeightFt', joEdges);
sl.Add(Format('HeightFt = %8.2f',[aDouble]));
aDouble := GetJsonDouble('RadiusFt', joEdges);
sl.Add(Format('RadiusFt = %8.2f',[aDouble]));
aBoolStr := BoolToStr(GetJsonBool('IsArcRotated', joEdges));
sl.Add('IsArcRotated = '+aBoolStr);
aInt := GetJsonint0('ArcAngle', joEdges);
sl.Add(Format('ArcAngle = %d',[aInt]));
aInt := GetJsonint0('LineAngle', joEdges);
sl.Add(Format('LineAngle = %d',[aInt]));
aBoolStr := BoolToStr(GetJsonBool('InverseRotation', joEdges));
sl.Add('InverseRotation = '+aBoolStr);
aBoolStr := BoolToStr(GetJsonBool('IsHorizontal', joEdges));
sl.Add('IsHorizontal = '+aBoolStr);
aBoolStr := BoolToStr(GetJsonBool('IsVertical', joEdges));
sl.Add('IsVertical = '+aBoolStr);
sl.add(' ');
end;
jEdges := jAreas.Field['Edges'];
if jEdges <> nil then
begin//handle Edges
end;
sl.add(' ');
end;
end;
finally
result := sl.Text;
sl.Free;
end;
end;
function ParseSketchTexts(joSketch: TlkJSonBase): String;
var
jSketch, jTexts : TlkJSonBase;
joText: TlkJSonObject;
i,j,k,l: Integer;
SketchData, LinesData:String;
X,Y: Double;
sl:TStringList;
jCoord: TlkJSonBase;
aInt: Integer;
aBool: Boolean;
aBoolStr, aStr: String;
aDouble: Double;
aCount: Integer;
isDimension: Boolean;
Content: String;
begin
if joSketch.Field['Sketcher_Definition_Data'] <> nil then
jSketch := joSketch.Field['Sketcher_Definition_Data'];
sl := TStringList.create;
try
for i:= 0 to jSketch.Count -1 do
begin
joSketch := jSketch.Child[i] as TlkJSONObject; //get each comp
if joSketch = nil then continue;
jTexts := joSketch.Field['Texts'];
if jTexts <> nil then
for j:= 0 to jTexts.Count -1 do
begin
joText := jTexts.Child[j] as TlkJSonObject;
aStr := GetJsonString('Id', joText);
sl.Add('ID = '+aStr);
isDimension := GetJsonBool('IsDimension', joText);
Content := GetJSonString('Content', joText);
sl.Add('Content = '+Content);
sl.add(' ');
end;
end;
finally
result := sl.Text;
sl.Free;
end;
end;
function GetDirection(jEdges:TlkJSonBase; i: Integer; isArc:Boolean):String;
var
joEdges:TlkJSonObject;
Xs, Ys:Double;
Xe, Ye: Double;
X0, y0: Double;
begin
try
result := '';
if jEdges = nil then exit;
if i = -1 then exit;
joEdges := jEdges.Child[i] as TlkJSonObject;
if joEdges.Field['Start'] <> nil then
GetJsonCoordinate('Start', joEdges, Xs, Ys);
if joEdges.Field['End'] <> nil then
GetJsonCoordinate('End', joEdges, Xe, Ye);
if Xe - Xs = 0 then //this is horizontal
begin
if Ye > Ys then //this is South
begin
result := 'S';
end
else
begin
result := 'N'; //not south so must be N
end;
end
else if Ye - Ys = 0 then //this is Vertical either E/W
begin
if Xe > Xs then
begin
result := 'E'; //this is E
end
else if i = jEdges.Count -1 then //this is the last point
begin
//look for the first start point
joEdges := jEdges.Child[0] as TlkJSonObject;
if joEdges.Field['Start'] <> nil then
GetJsonCoordinate('Start', joEdges, X0, Y0);
if x0 = xs then //this is E for the last point
result := 'E';
end
else
result := 'W';
end
else //not horizontal and not vertical, has to be in diagonal
begin
if Xe > Xs then //this is E
begin
if Ye > Ys then //this is S
result := 'SE'
else
result := 'NE';
end
else if Xe < Xs then //this is W
begin
if Ye > Ys then
result := 'SW'
else
result := 'NW';
end;
end;
except on E:Exception do
ShowNotice('Error in calculating direction. '+e.message);
end;
end;
function calcDegree(x1,y1,x2,y2: Double):Double;
var
aLog: String;
begin
result := 0;
if x2 <> x1 then
result := 90 - RadToDeg(arcTan(abs((y2-y1)/(x2-x1))));
aLog := Format('(%f,%f), (%f,%f), degree:%f ',
[X1, Y1, X2, Y2, result]);
FLog.Add(aLog);
end;
function GetPerimeter(jEdges:TlkJSonBase): Double;
var
i,k: Integer;
joEdges: TlkJSonObject;
LengthFt: Double;
begin
result := 0;
LengthFt := 0;
for k:= 0 to jEdges.Count - 1 do
begin //handle EdgeIds
joEdges := jEdges.Child[k] as TlkJSonObject;
if joEdges <> nil then
LengthFt := GetJsonDouble('LengthFt', joEdges);
result := result + LengthFt;
end;
end;
function getCurve(dir: String; Height:Double):String;
begin
if (Height > 0) then
begin
result := 'R'; //this is top (N)
end
else
begin
result := 'L';
end;
FLog.Add('curve ='+result);
end;
procedure translateLines(joEdges:TlkJsonObject; dir: String; var xml:TStringList);
var
dim: string;
aLog: String;
LengthFt: Double;
X1, Y1, X2, Y2: Double;
degree: Double;
deg: String;
begin
try
xml.add('<line>');
xml.add('<segment>');
LengthFt := GetJsonDouble('LengthFt', joEdges);
dim := trim(Format('%f',[LengthFt]));
xml.add(Format('<dim>%s</dim>',[dim]));
xml.add(Format('<dir>%s</dir>',[dir]));
GetJsonCoordinate('Start', joEdges, X1, Y1);
aLog := Format('Start(X1=%f, Y1=%f)',[X1,Y1]);
FLog.Add(aLog);
GetJsonCoordinate('End', joEdges, X2, Y2);
aLog := Format('End(X2=%f, Y2=%f)',[X2,Y2]);
FLog.Add(aLog);
aLog := Format('dim/dir = %s/%s ',[dim, dir]);
FLog.Add(aLog);
FLog.Add('');
if length(dir) > 1 then
begin
GetJsonCoordinate('Start', joEdges, X1, Y1);
GetJsonCoordinate('End', joEdges, X2, Y2);
aLog := Format('Start(X1=%f, Y1=%f)',[X1,Y1]);
FLog.Add(aLog);
aLog := Format('End(X2=%f, Y2=%f)',[X2,Y2]);
FLog.Add(aLog);
degree := calcDegree(x1,y1,x2,y2);
deg := Format('%f',[degree]);
if deg <> '' then
xml.add(Format('<degree>%s</degree>',[deg]));
end;
xml.Add('</segment>');
xml.Add('</line>');
except on E:Exception do
ShowNotice('Error in calculating Line dimension. '+e.message);
end;
end;
procedure translateArc(joEdges:TlkJsonObject; dir: String; var xml:TStringList);
var
dim: string;
aLog: String;
LengthFt, Height: Double;
X1, Y1, X2, Y2: Double;
degree, arcAngle: Double;
deg, curve: String;
begin
try
FLog.Add('IsArc = TRUE');
xml.add('<arc>');
Height := GetJsonDouble('HeightFt', joEdges);
FLog.Add(Format('HeightFt = %f',[Height]));
LengthFt := GetJsonDouble('LengthFt', joEdges);
Flog.Add(Format('LengthFt = %f',[LengthFt]));
curve := getCurve(dir,Height);
xml.add(Format('<curve>%s</curve>',[curve]));
xml.add('<cord>');
xml.add('<segment>');
dim := trim(Format('%8.2f',[LengthFt]));
xml.add(Format('<dim>%s</dim>',[dim]));
xml.add(Format('<dir>%s</dir>',[dir]));
Flog.Add(Format('dim = %s',[dim]));
Flog.Add(Format('dir = %s',[dir]));
xml.add('</segment>');
xml.add('</cord>');
arcAngle := getJsonDouble('ArcAngle', joEdges);
if arcAngle > 90 then
arcAngle := (180 - arcAngle) + arcAngle;
deg := Format('%f',[arcAngle]);
if deg <> '' then
xml.add(Format('<degree>%s</degree>',[deg]));
Flog.Add(Format('degree = %s',[deg]));
xml.add('</arc>');
except on E:Exception do
ShowNotice('Error in calculating arc dimension. '+e.message);
end;
end;
procedure GetOriginalPoint(jEdges: TlkJSonBase; var X1, Y1, X2, Y2, LengthFT: Double);
var
joEdges: TlkJSonObject;
begin
if jEdges = nil then exit;
joEdges := jEdges.Child[0] as TlkJSonObject; //always get the first point
if jEdges.Field['Start'] <> nil then
GetJsonCoordinate('Start', joEdges, X1, Y1); //get the first coordinate of the next area
if jEdges.Field['End'] <> nil then
GetJsonCoordinate('End', joEdges, X2, Y2); //get the first coordinate of the next area
LengthFt := GetJsonDouble('LengthFt', joEdges);
end;
procedure TranslateMoveLines(jAreas,jEdges: TlkJSonBase; j: Integer; var xml: TStringList);
var
L, LengthFT:Double;
jo, joEdges: TlkJSonObject;
X1,Y1: Double; //This is the starting point X1 = 466, Y1 = 499.5
X2,Y2: Double; //This is the end point of the first line X2 = 751.84, Y2 = 499.5
X,Y: Double; //this is the point that we need to move to X = 751.84, Y = 352.61
D1,D2,D3: Double; //This is the distance between X1 to X2
Dir, aMsg: String;
i: Integer;
begin
L := 0;
for i := 0 to jAreas.Count -1 do //look for the next area
begin
if i = 0 then
begin
jEdges := jAreas.Child[i].Field['Edges'];
GetOriginalPoint(jEdges, X1, Y1, X2, Y2, LengthFT);
(*
jEdges := jAreas.Child[i].Field['Edges'];
joEdges := jEdges.Child[0] as TlkJSonObject; //always get the first point
if jEdges.Field['Start'] <> nil then
GetJsonCoordinate('Start', joEdges, X1, Y1); //get the first coordinate of the next area
if jEdges.Field['End'] <> nil then
GetJsonCoordinate('End', joEdges, X2, Y2); //get the first coordinate of the next area
LengthFt := GetJsonDouble('LengthFt', joEdges);
*)
end;
if i < j then continue;
jEdges := jAreas.Child[i].Field['Edges'];
joEdges := jEdges.Child[0] as TlkJSonObject; //always get the first point
if jEdges.Field['Start'] <> nil then
begin
GetJsonCoordinate('Start', joEdges, X, Y); //get the first coordinate of the next area
break;
end;
end;
//use the coordinate to calculate the length
if X2 <> X1 then
begin //calculate length of Y
D1 := abs(X2 - X1); // 751.84 - 466 = 285.84 and D1 = LengthFT(36)
//LengthFT * L = D1 * Y;
if D1 <> 0 then
begin
//get the move for Y first
D2 := abs(Y - Y1);
L := (LengthFT * D2)/D1;
xml.Add('<move> <segment>');
xml.add(Format('<dim>%f</dim>',[L]));
if Y > Y1 then //this is S
Dir := 'S'
else
Dir := 'N';
xml.Add(Format('<dir>%s</dir>',[Dir]));
xml.Add('</segment> </move>');
//Now, get the move for X
D3 := abs(X - X1);
//now, get the move for X
L := (LengthFT * D3)/D1;
xml.Add('<move> <segment>');
xml.add(Format('<dim>%f</dim>',[L]));
if X > X1 then //this is S
Dir := 'E'
else
Dir := 'W';
xml.Add(Format('<dir>%s</dir>',[Dir]));
xml.Add('</segment> </move>');
end;
end;
end;
function GetSurface(joSketch:TlkJsonBase; sList:TStringList; cur:Integer):String;
var
i,j,k:Integer;
jAreas, jTexts: TlkJSonbase;
aTitle,aItem, aValue:String;
begin
result := '0';
jAreas := joSketch.Field['Areas'];
if jAreas <> nil then
begin
for i:= 0 to jAreas.Count -1 do
begin
if i <> cur then continue;
if jAreas.child[i].Field['TextId'] <> nil then
begin
jTexts := joSketch.Field['Texts'];
if jTexts <> nil then
begin
for j:= 0 to jTexts.Count -1 do
begin
if jTexts.Child[j].Field['Id'] <> nil then
if varToStr(jTexts.Child[j].Field['Id'].Value) = varToStr(jAreas.child[i].Field['TextId'].Value) then
begin
for k:=0 to slist.count -1 do
begin
aItem := slist[k];
aTitle := popStr(aItem,'=');
if jTexts.child[j].Field['Content'] <> nil then
if compareText(aTitle, varToStr(jTexts.child[j].Field['Content'].Value)) = 0 then
begin
result := aItem;
break;
end;
end;
end;
end;
end;
end;
end;
end;
end;
function ConvertJSONToXML(joSketch: TlkJSonBase; pageNo: Integer; AreaList:TStringList):String;
var
jSketch, jTexts, jText, jEdges, jAreas, jAreaName: TlkJSonBase;
joEdges, joText,jo: TlkJSonObject;
xml: TStringList;
aXMLData:String;
i,j,k,n: Integer;
aLine: String;
ID,dir: String;
LengthFt: Double;
aStr: String;
isVertical, IsHorizontal, isArc :Boolean;
perimeter:Double;
isDimension: Boolean;
Content: String;
X,Y:Double;
degree:Double;
dim, deg: String;
aMsg: String;
x1,x2,y1,y2: Double;
arcAngle, Height:Double;
curve: String;
aLog: String;
areaName: String;
xmlFileName: String;
MoveDim:Double;
MoveDir: String;
sCount, TotCount,aCount: Integer;
surface: String;
aDebugPath, aDebugFileName: String;
IsAreaTitle: Boolean;
D1, D2, D3, L: Double;
begin
try
FSketchDir := IncludeTrailingPathDelimiter(GetTempFolderPath); //ClickForms Temp folder stores the files
xml := TStringList.Create;
try
xml.Clear;
if joSketch.Field['Sketcher_Definition_Data'] <> nil then
jSketch := joSketch.Field['Sketcher_Definition_Data'];
//set up XML header
xml.Add('<?xml version="1.0" encoding="UTF-8"?>');
xml.add('<sketch xmlns="http://www.areasketch.com/namespace" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.areasketch.com/namespace areasketch.xsd">');
case PageNo of
1: begin
sCount := 0;
totCount := 1;
end;
else
begin
//sCount := 1;
sCount := PageNo - 1;
totCount := PageNo;
end;
end;
for i:= sCount to totCount -1 do
begin
joSketch := jSketch.Child[i] as TlkJSONObject; //get each comp
if joSketch = nil then continue;
jAreas := joSketch.Field['Areas'];
if jAreas <> nil then
for j:= 0 to jAreas.Count -1 do
begin
xml.add('<id/>'); //needs to have this
xml.add('<status>new</status>'); //needs to have this
jEdges := jAreas.Child[j].Field['Edges'];
jAreaName := jAreas.Child[j].Field['Name'];
xml.add('<area style="solid" width="2" color="0x000000" showDimensionText="1" flipDimensionTextPos="0" showAreaCalc="1" showPerimeterCalc="1" autoLabel="full" fillPattern="none" fillColor="0xff0000" >');
if jEdges.Field['Id'] <> nil then
Id := varToStr(jEdges.Field['Id'].Value);
xml.add(Format('<id>%s</id>',[Id]));
areaName := VarToStr(jAreaName.Value);
xml.add(Format('<name>%s</name>',[areaName]));
xml.add('<status>new</status>');
surface := getSurface(joSketch, AreaList,j);
xml.add(Format('<surface>%s</surface>',[surface]));
perimeter := GetPerimeter(jEdges);
aStr := Format('%8.2f',[perimeter]);
xml.add(Format('<perimeter>%s</perimeter>',[aStr]));
if jEdges = nil then continue;
xml.add('<vectors>');
for k:= 0 to jEdges.Count - 1 do
begin //handle EdgeIds
joEdges := jEdges.Child[k] as TlkJSonObject;
ID := GetJsonString('Id', joEdges);
if ID <> '' then
begin
LengthFt := GetJsonDouble('LengthFt', joEdges);
if LengthFt > 0 then
begin
if (k = 0) and (j>0) then
TranslateMoveLines(jAreas, jEdges, j, xml);
isArc := GetJsonBool('IsArc', joEdges);
dir := GetDirection(jEdges,k, isArc);
if not isArc then
begin
translateLines(joEdges, dir, xml);
end
else //isArc
begin
translateArc(joEdges, dir, xml);
end;
end;
end;
end;
xml.add('</vectors>');
if jAreaName <> nil then
begin
areaName := VarToStr(jAreaName.Value);
xml.add('<areaDefs>');
xml.add('<areaDef>');
xml.add(Format('<name>%s</name>',[areaName]));
xml.add(Format('<type>%s</type>',[areaName]));
xml.add('<sign>1</sign>');
xml.add('<modifier>1</modifier>');
xml.add('<partof/>');
xml.add('<partofSign>1</partofSign>');
xml.add('</areaDef>');
xml.add('</areaDefs>');
end;
xml.add('</area>');
end;
end;
//Handle labels
jTexts := joSketch.Field['Texts'];
if jTexts <> nil then
begin
for j:= 0 to jTexts.Count -1 do
begin
joText := jTexts.Child[j] as TlkJSonObject;
Content := GetJSonString('Content', joText);
IsDimension := GetJsonBool('IsDimension', joText);
isAreaTitle := GetJsonBool('IsAreaTitle', joText);
if (Content <> '') and not IsDimension and not IsAreaTitle then
begin
if joText.Field['TapPoint'] <> nil then
begin
GetJsonCoordinate('TapPoint', joText, X, Y);
jEdges := jAreas.Child[0].Field['Edges'];
if jEdges <> nil then
GetOriginalPoint(jEdges, X1, Y1, X2, Y2, LengthFT);
//use the coordinate to calculate the length
if X2 <> X1 then
begin //calculate length of Y
D1 := abs(X2 - X1); // 751.84 - 466 = 285.84 and D1 = LengthFT(36)
//LengthFT * L = D1 * Y;
if D1 <> 0 then
begin
xml.add('<label>');
xml.add('<position>');
D3 := X - X1;
L := (LengthFT * D3)/D1;
if L <> 0 then
aStr := FloatToStr(L);
aStr := Format('<X>%s</X>',[aStr]);
xml.add(aStr);
//get the move for Y first
D2 := Y - Y1;
L := (LengthFT * D2)/D1;
if L <> 0 then
aStr := FloatToStr(L);
aStr := Format('<Y>%s</Y>',[aStr]);
xml.add(aStr);
xml.add('</position>');
aStr := Format('<text>%s</text>',[Content]);
xml.add(aStr);
xml.add('<alignHorz>center</alignHorz>');
xml.add('</label>');
end;
end;
end;
end;
end;
end;
xml.add('</sketch>');
finally
XMLFileName := FSketchDir + cSketchFileName;
xml.SaveToFile(xmlFileName);
aDebugPath := IncludeTrailingPathDelimiter(appPref_DirInspection+'\Debug');
aDebugFileName := aDebugPath + '\ASSketch.xml';
xml.SaveToFile(aDebugFileName);
result := xmlFileName;
FLog.SaveToFile(aDebugPath+ '\ASSketch_Log.txt');
xml.Free;
end;
except on E:Exception do
end;
end;
end.
|
//---------------------------------------------------------------------------
// This software is Copyright (c) 2011 Embarcadero Technologies, Inc.
// You may only use this software if you are an authorized licensee
// of Delphi, C++Builder or RAD Studio (Embarcadero Products).
// This software is considered a Redistributable as defined under
// the software license agreement that comes with the Embarcadero Products
// and is subject to that software license agreement.
//---------------------------------------------------------------------------
unit Unit1;
interface
uses
SysUtils, Types, UITypes, Classes, Variants, FMX_Types, FMX_Controls, FMX_Forms,
FMX_Dialogs, FMX_Objects, FMX_Effects, FMX_Types3D, FMX_Layers3D, Location;
type
TForm1 = class(TForm)
Latitude: TLabel;
Longitude: TLabel;
Altitude: TLabel;
Compass: TCircle;
SelectionPoint1: TSelectionPoint;
CompassLabel: TLabel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
iOSLocation1: TiOSLocation;
procedure iOSLocation1UpdateHeading(HeadingData: THeadingData);
procedure iOSLocation1UpdateLocation(LocationData: TLocationData);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
// 37 3'45.88'' N 122 0'26.66'' W (my office)
function CoordPartToStr(CoordPart: Double) : String;
var
Degrees, Minutes, Seconds : Double;
begin
CoordPart := Abs(CoordPart);
Degrees := Trunc(CoordPart);
CoordPart := 60*(CoordPart-Degrees);
Minutes := Trunc(CoordPart);
CoordPart := 60*(CoordPart-Minutes);
Seconds := Trunc(CoordPart*100)/100;
Result := FloatToStr(Degrees)+' '+FloatToStr(Minutes)+''''+FloatToStr(Seconds)+''''' ';
end;
function LatitudeToStr(Latitude: Double) : String;
begin
if Latitude < 0 then
Result := CoordPartToStr(Latitude)+'S'
else
Result := CoordPartToStr(Latitude)+'N';
end;
function LongitudeToStr(Longitude: Double) : String;
begin
if Longitude < 0 then
Result := CoordPartToStr(Longitude)+'W'
else
Result := CoordPartToStr(Longitude)+'E';
end;
procedure TForm1.iOSLocation1UpdateHeading(HeadingData: THeadingData);
begin
Form1.CompassLabel.Text := IntToStr(Round(HeadingData.MagneticHeading));
Form1.Compass.RotationAngle := -HeadingData.MagneticHeading;
end;
procedure TForm1.iOSLocation1UpdateLocation(LocationData: TLocationData);
begin
Form1.Latitude.Text := LatitudeToStr(LocationData.Latitude);
Form1.Longitude.Text := LongitudeToStr(LocationData.Longitude);
Form1.Altitude.Text := IntToStr(Round(LocationData.Altitude/0.3048))+' ft';
end;
end.
|
unit UMZDepartmentUnit;
interface
uses DomainObjectUnit;
type
TUMZDepartment = class(TDomainObject)
strict private
FCode: String;
FShortName: String;
FFullName: String;
FBeginUsingDate: TDateTime;
FEndUsingDate: TDateTime;
public
destructor Destroy; override;
constructor Create; overload; override;
constructor Create(
const AID: Variant;
const ACode, AShortName, AFullName: String;
const ABeginUsingDate, AEndUsingDate: TDateTime
); overload;
procedure CopyFrom(Copyable: TObject);
procedure DeepCopyFrom(Copyable: TObject);
function Equals(Equatable: TObject): Boolean;
function Clone: TObject;
published
property Code: String read FCode write FCode;
property ShortName: String read FShortName write FShortName;
property FullName: String read FFullName write FFullName;
property BeginUsingDate: TDateTime
read FBeginUsingDate write FBeginUsingDate;
property EndUsingDate: TDateTime
read FEndUsingDate write FEndUsingDate;
end;
implementation
{ TOMODepartament }
constructor TUMZDepartment.Create;
begin
inherited;
end;
function TUMZDepartment.Clone: TObject;
var Clonee : TUMZDepartment;
begin
Result := inherited Clone;
end;
constructor TUMZDepartment.Create(
const AID: Variant; const ACode,
AShortName, AFullName: String;
const ABeginUsingDate, AEndUsingDate: TDateTime
);
begin
inherited Create(AID);
FCode := ACode;
FShortName := AShortName;
FFullName := AFullName;
FBeginUsingDate := ABeginUsingDate;
FEndUsingDate := AEndUsingDate;
end;
procedure TUMZDepartment.DeepCopyFrom(Copyable: TObject);
begin
inherited;
end;
destructor TUMZDepartment.Destroy;
begin
inherited;
end;
procedure TUMZDepartment.CopyFrom(Copyable: TObject);
var Other: TUMZDepartment;
begin
inherited;
end;
function TUMZDepartment.Equals(Equatable: TObject): Boolean;
var Other: TUMZDepartment;
begin
Result := inherited Equals(Equatable);
end;
end.
|
unit Event;
{$mode objfpc}{$H+}
interface
uses
Windows, Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls,
StdCtrls, Buttons, DbCtrls, DBGrids, Calendar, EditBtn,
Databases, Settings, sqldb;
type
{ TEventForm }
TEventForm = class(TForm)
CancelButton: TBitBtn;
EventDateEdit: TDateEdit;
EventWindowDBGrid: TDBGrid;
InfoMemo2: TMemo;
ActionLabel: TLabel;
Label1: TLabel;
SelectedRowInfoLabel1: TLabel;
SelectedRowInfoLabel2: TLabel;
EventDateLabel: TLabel;
SearchEdit: TLabeledEdit;
InfoMemo1: TMemo;
EventRadioGroup: TRadioGroup;
SaveButton: TBitBtn;
procedure CancelButtonClick(Sender: TObject);
procedure EventWindowDBGridMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure SearchEditKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure LabelsUpdateCaption(Sender: TObject);
procedure EventWindowDBGridKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure EventWindowDBGridDblClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure ShowTable(Sender: TObject);
procedure EventRadioGroupClick(Sender: TObject);
procedure SaveButtonClick(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
EventForm: TEventForm;
SelectedID:Integer;
SelectedComplect_ID:Integer;
SelectedClient_ID:Integer;
SelectedType:Integer;
SelectedDeviceSummary:string;
implementation
{$R *.lfm}
{ TEventForm }
procedure TEventForm.FormCreate(Sender: TObject);
begin
end;
procedure TEventForm.FormShow(Sender: TObject);
begin
EventRadioGroup.Items.Clear;
EventRadioGroup.Items.AddStrings(['Информация','Продажа','Аренда','Подарок', 'Временно',
'Возврат','Утеря','Поломка','Ремонт','Уточнение','Другое']);
EventRadioGroup.ItemIndex:=0;
EventRadioGroupClick(nil);
ShowTable(nil);
end;
procedure TEventForm.ShowTable(Sender: TObject);
begin
with Database.EventwindowSQLQuery do
begin
if Active then Close;
SQL.Sorted:=False;
SQL.Text:='select * from CLIENT_COMPLECTS_SMALL_VIEW '+
'where USER_CARDNUM containing :SearchStr or '+
'NAME containing :SearchStr '+
'order by NAME ';
Params.ParamByName('SearchStr').AsString :=SearchEdit.Text;
if not Active then Open;
Last;
First;
end;
end;
procedure TEventForm.EventRadioGroupClick(Sender: TObject);
var complect_id:integer;
client_id:Integer;
begin
InfoMemo1.Clear;
InfoMemo2.Clear;
if SelectedType in [2,5] then
with Database.FlashQuery do
begin
complect_id:=0;
InfoMemo1.Append('Информация о носителе:');
Close;
SQL.Text := 'select * from CLIENT_DEVICES where ID='+IntToStr(SelectedID);
Open;
while not Eof do
begin
InfoMemo1.Append('Носитель: '+FieldByName('SHORTNUMBER').AsString);
InfoMemo1.Append('Полный номер: '+FieldByName('FULLNUMBER').AsString);
InfoMemo1.Append('Размер: '+FieldByName('MEDIASIZE').AsString+'GB');
InfoMemo1.Append('Производитель: '+FieldByName('VENDOR').AsString);
InfoMemo1.Append('Модель: '+FieldByName('MODEL').AsString);
InfoMemo1.Append('Название: '+FieldByName('NAME').AsString);
InfoMemo1.Append('Серийный номер: '+FieldByName('SERIAL').AsString);
complect_id:=FieldByName('UC_ID').AsInteger;
client_id:=FieldByName('ID_CLIENT').AsInteger;
Next;
end;
SelectedDeviceSummary:=FieldByName('VENDOR').AsString+' '+FieldByName('MODEL').AsString+' '+
FieldByName('MEDIASIZE').AsString+'GB, номер '+FieldByName('SHORTNUMBER').AsString;
InfoMemo2.Append('Информация о клиенте:');
Close;
SQL.Text := 'select * from CLIENT_COMPLECTS_SMALL_VIEW where UC_ID='+IntToStr(complect_id);
Open;
while not Eof do
begin
InfoMemo2.Append('Регномер: '+FieldByName('USER_CARDNUM').AsString);
InfoMemo2.Append('Клиент: '+FieldByName('NAME').AsString);
//InfoMemo2.Append('Статус клиента: '+FieldByName('DELETED').AsString);
InfoMemo2.Append('');
InfoMemo2.Append('ID комплекта: '+FieldByName('UC_ID').AsString);
InfoMemo2.Append('Название: '+FieldByName('UC_NAME').AsString);
InfoMemo2.Append('Тип комплекта: '+FieldByName('NETDESCR').AsString);
InfoMemo2.Append('Способ обновления: '+FieldByName('NM_MDTYPE').AsString);
InfoMemo2.Append('Регулярность: '+FieldByName('DELETED').AsString);
InfoMemo2.Append('Руководитель: '+FieldByName('FIO_HEADGROUP').AsString);
InfoMemo2.Append('Сотрудник: '+FieldByName('FIO_EMPGROUP').AsString);
Next;
end;
end;
Case EventRadioGroup.ItemIndex of
0: begin
ActionLabel.Caption:='';
EventWindowDBGrid.Hide;
SearchEdit.Hide;
SaveButton.Enabled:=False;
end;
1,2,3,4,5: begin
ActionLabel.Caption:='Укажите организацию и комплект:';
EventWindowDBGrid.Show;
SearchEdit.Show;
SaveButton.Enabled:=True;
LabelsUpdateCaption(nil);
end;
6: begin
SelectedComplect_ID:=0;
ActionLabel.Caption:='';
EventWindowDBGrid.Hide;
SearchEdit.Hide;
SaveButton.Enabled:=True;
end;
7,8,9,10,11,12,13: begin
ActionLabel.Caption:='Укажите носитель:';
ActionLabel.Caption:='Данная функция не реализована в этой версии программы';
EventWindowDBGrid.Hide;
SearchEdit.Hide;
SaveButton.Enabled:=True;
LabelsUpdateCaption(nil);
end;
end;
end;
procedure TEventForm.SaveButtonClick(Sender: TObject);
begin
if (Application.MessageBox(PChar('Действие: '''+EventRadioGroup.Items[EventRadioGroup.ItemIndex]+''' '+IntToStr(SelectedComplect_ID)+sLineBreak+
'для носителя '+SelectedDeviceSummary+sLineBreak+
SelectedRowInfoLabel1.Caption+sLineBreak+
SelectedRowInfoLabel2.Caption),
'Подтвердите действие',
MB_ICONQUESTION+MB_YESNO)=IDYES) then
begin
// log transaction
Database.FlashQuery.Close;
Database.FlashQuery.SQL.Text := 'execute procedure ADD_EVENT_DEVICES( '+
':EVENTDATE,:EVENTTYPE,:DEVICE_ID,:ID_CLIENT,:UC_ID, '+
':ID_HEADGROUP,:ID_EMPLOYEE,:ID_EMPL_ADDED_EVENT,:COMMENT_FOR_EVENT, '+
':VENDOR,:MODEL,:NAME,:MEDIASIZE,:BYTES,:SERIAL, '+
':FULLNUMBER,:SHORTNUMBER,:PNPDEVICEID,:PURCHASEDATE,:FIRM,:COMMENT )';
Database.FlashQuery.Params.ParamByName('EVENTDATE').AsDate := EventDateEdit.Date;
Database.FlashQuery.Params.ParamByName('EVENTTYPE').AsInteger := EventRadioGroup.ItemIndex;
Database.FlashQuery.Params.ParamByName('DEVICE_ID').AsInteger := SelectedID;
Database.FlashQuery.Params.ParamByName('ID_CLIENT').AsInteger := SelectedClient_ID;
Database.FlashQuery.Params.ParamByName('UC_ID').AsInteger := SelectedComplect_ID;
Database.FlashQuery.Params.ParamByName('ID_HEADGROUP').AsInteger := 0;
Database.FlashQuery.Params.ParamByName('ID_EMPLOYEE').AsInteger := 0;
Database.FlashQuery.Params.ParamByName('ID_EMPL_ADDED_EVENT').AsInteger := 0;
{Database.FlashQuery.Params.ParamByName('COMMENT_FOR_EVENT').AsString := CommentEdit.Text;
Database.FlashQuery.Params.ParamByName('VENDOR').AsString := VendorEdit.Text;
Database.FlashQuery.Params.ParamByName('MODEL').AsString := ModelNameEdit.Text;
Database.FlashQuery.Params.ParamByName('NAME').AsString := ModelNameEdit.Text;
Database.FlashQuery.Params.ParamByName('MEDIASIZE').AsInteger := StrToInt(SizeEdit.Text);
Database.FlashQuery.Params.ParamByName('BYTES').AsLargeInt := StrToInt64(BytesEdit.Text);
Database.FlashQuery.Params.ParamByName('SERIAL').AsString := SerialNumberEdit.Text;
Database.FlashQuery.Params.ParamByName('FULLNUMBER').AsString := FullNumberEdit.Text;
Database.FlashQuery.Params.ParamByName('SHORTNUMBER').AsString := ShortNumberEdit.Text;
Database.FlashQuery.Params.ParamByName('PNPDEVICEID').AsString := PNPDeviceIDEdit.Text;
Database.FlashQuery.Params.ParamByName('PURCHASEDATE').AsString := DateToStr(PurchaseDateEdit.Date);
Database.FlashQuery.Params.ParamByName('FIRM').AsInteger := AgentComboBox.ItemIndex+1;
Database.FlashQuery.Params.ParamByName('COMMENT').AsString := CommentEdit.Text;
} Database.FlashQuery.ExecSQL;
Database.FlashTransaction.Commit;
Database.FlashTransaction.EndTransaction;
{Database.FlashQuery.SQL.Text := 'insert into EVENTS ('+
'EVENTDATE,EVENTTYPE,DEVICE_ID,REGNUM,COMPLECT_ID,MANAGER_ID,EMPLOYEE_ID,SNAPSHOT,COMMENT )'+
Database.FlashQuery.Params.ParamByName('EVENTDATE').AsDate := EventDateEdit.Date;
Database.FlashQuery.Params.ParamByName('EVENTTYPE').AsInteger := EventRadioGroup.ItemIndex;
Database.FlashQuery.Params.ParamByName('DEVICE_ID').AsInteger := SelectedID;
Database.FlashQuery.Params.ParamByName('REGNUM').AsString := EventWindowDBGrid.DataSource.DataSet.FieldByName('REGNUM').AsString;;
Database.FlashQuery.Params.ParamByName('COMPLECT_ID').AsInteger := SelectedComplect_ID;
// set device-client association
Database.FlashQuery.SQL.Text:='update DEVICES set COMPLECT_ID=:COMPLECT_ID where ID=:ID';
}
MessageDlg('Информация','Действие '''+EventRadioGroup.Items[EventRadioGroup.ItemIndex]+''' выполнено',mtInformation,[mbOK],0);
EventForm.Close;
end;
end;
procedure TEventForm.CancelButtonClick(Sender: TObject);
begin
EventForm.Close;
end;
procedure TEventForm.LabelsUpdateCaption(Sender: TObject);
begin
SelectedRowInfoLabel1.Caption:='Клиент: '+
EventWindowDBGrid.DataSource.DataSet.FieldByName('USER_CARDNUM').AsString+', '+
EventWindowDBGrid.DataSource.DataSet.FieldByName('NAME').AsString;
SelectedRowInfoLabel2.Caption:='Комплект: '+
EventWindowDBGrid.DataSource.DataSet.FieldByName('UC_ID').AsString+', '+
EventWindowDBGrid.DataSource.DataSet.FieldByName('UC_NAME').AsString;
SelectedComplect_ID:=EventWindowDBGrid.DataSource.DataSet.FieldByName('UC_ID').AsInteger;
SelectedClient_ID:=EventWindowDBGrid.DataSource.DataSet.FieldByName('ID_CLIENT').AsInteger;
end;
procedure TEventForm.EventWindowDBGridKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
LabelsUpdateCaption(nil);
if Key=13 then
SaveButtonClick(nil);
end;
procedure TEventForm.EventWindowDBGridMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
LabelsUpdateCaption(nil);
end;
procedure TEventForm.SearchEditKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
ShowTable(nil);
end;
procedure TEventForm.EventWindowDBGridDblClick(Sender: TObject);
begin
SaveButtonClick(nil);
end;
end.
|
{
Copyright (C) 2012 Matthias Bolte <matthias@tinkerforge.com>
Redistribution and use in source and binary forms of this file,
with or without modification, are permitted. See the Creative
Commons Zero (CC0 1.0) License for more details.
}
unit BlockingQueue;
{$ifdef FPC}{$mode OBJFPC}{$H+}{$endif}
interface
uses
Contnrs, SyncObjs, LEConverter, TimedSemaphore;
type
TBlockingQueue = class
private
mutex: TCriticalSection;
semaphore: TTimedSemaphore;
kinds: TQueue;
items: TQueue;
public
constructor Create;
destructor Destroy; override;
procedure Enqueue(const kind: byte; const item: TByteArray);
function Dequeue(out kind: byte; out item: TByteArray; const timeout: longint): boolean;
end;
implementation
constructor TBlockingQueue.Create;
begin
mutex := TCriticalSection.Create;
semaphore := TTimedSemaphore.Create;
kinds := TQueue.Create;
items := TQueue.Create;
end;
destructor TBlockingQueue.Destroy;
var pkind: PByte; pitem: PByteArray;
begin
mutex.Acquire;
try
while (kinds.Count > 0) do begin
pkind := kinds.Pop;
Dispose(pkind);
end;
while (items.Count > 0) do begin
pitem := items.Pop;
Dispose(pitem);
end;
finally
mutex.Release;
end;
mutex.Destroy;
semaphore.Destroy;
kinds.Destroy;
items.Destroy;
inherited Destroy;
end;
procedure TBlockingQueue.Enqueue(const kind: byte; const item: TByteArray);
var pkind: PByte; pitem: PByteArray;
begin
mutex.Acquire;
try
New(pkind);
pkind^ := kind;
kinds.Push(pkind);
New(pitem);
pitem^ := item;
items.Push(pitem);
semaphore.Release;
finally
mutex.Release;
end;
end;
function TBlockingQueue.Dequeue(out kind: byte; out item: TByteArray; const timeout: longint): boolean;
var pkind: PByte; pitem: PByteArray;
begin
result := false;
if (semaphore.Acquire(timeout)) then begin
mutex.Acquire;
try
pkind := kinds.Pop;
kind := pkind^;
Dispose(pkind);
pitem := items.Pop;
item := pitem^;
Dispose(pitem);
result := true;
finally
mutex.Release;
end;
end;
end;
end.
|
unit UUtil2;
{ ClickForms Application }
{ Bradford Technologies, Inc. }
{ All Rights Reserved }
{ Source Code Copyrighted © 1998-2011 by Bradford Technologies, Inc. }
{$WARN SYMBOL_PLATFORM OFF}
{$WARN UNIT_PLATFORM OFF}
interface
uses
Graphics, UGlobals, Forms,Jpeg, Variants;
const
cmdGetCity = 1;
cmdGetState = 2;
cmdGetZip = 3;
cmdGetUnit = 4;
function ValidEmailAddress(eAddress: String): Boolean;
function TrimNumbersLeft(const S: String): String;
function TrimInterior(const Name: String): String;
function PosRScan(C: char; S: string): Integer;
Function NotNil(obj: TObject): Boolean;
procedure ReplaceCRwithSpace(var S: String);
function IsProcessRunning(const processName: String): Boolean;
function ParseStreetAddress(const Address: String; Cmd, Opt: Integer): String;
function ParseCityStateZip(const addstr : string; cmd : integer): string;
function ParseCityStateZip2(const addstr : string; cmd : integer): string;
function ParseCityStateZip3(const addstr : string; cmd : integer): string;
procedure ParseFullAddress(const fullAddress: String; var Address, CityStZip: String);
function GetFirstLastName(const fullName: String): String;
function GetNamePart(const fullName: String; Part: Integer): String;
function GetGoodUserName(const userName, defaultName: String): String;
function GetLastDigits(const Str: String): String;
procedure UpperCaseChar(var Key: Char);
function WrapTextAdv(text: String; canv: TCanvas; width: Integer; var LineLengths: IntegerArray): Boolean;
function URLEncode(const DecodedStr: String): String;
function FormatPhone(const phone: String): String;
function GetZipCodePart(const zip: String; part: Integer): String;
function IsStringZipCode(const str: String): Boolean;
function IsStringState(const str: String): Boolean;
function TrimTokens(const AString : string) : string; overload; // default to trim quotes
function TrimTokens(const AString : string; const Delimiters : array of string) : string; overload;
function StrToDateEx(strDate: String; strDateFrmt: String; chDateSepar: Char): TdateTime;
//commands in the import/export files
// function ParseCommand(Const Str: String; var CmdID, FrmID, InsID, ActionID: Integer): Boolean;
function ParseCommand(Const Str: String; var CmdID, FrmID, InsID, ActionID, OvrID: Integer): Boolean;
function PopStr(var sList : string; Seperator: String): string;
function GetAppName:String;
//Based on the format: Unit#, City, State Zip or City, State Zip
procedure GetUnitCityStateZip(var unitNo, City, State,Zip: String; citystZip:String);
function ConvertSalesDateMDY(aDateStr:String;Sep:String):String;//aDateStr = smm/yy;cmm/yy
procedure LoadJPEGFromByteArray(const dataArray: String; var JPGImg: TJPEGImage);
function convertStrToDateStr(aStrDate: String): String; //Pam 07/01/2015 Return U.S. Date format when we have European DateTime Format String
function convertStrToTimeStr(aStrDate: String): String; //Pam 07/01/2015 Return U.S. Date format when we have European DateTime Format String
function EncodeDigit2Char(N: Integer): String;
function DecodeChar2Digit(C: String): Integer;
function GetMainAddressChars(const address: String): String;
function GetStreetNameOnly(const streetAddress: String): String;
function ForceLotSizeToSqFt(lotSize: String): String;
implementation
uses
Windows,SysUtils,Registry,Math,Classes,UGridMgr,
UStatus;
function ValidEmailAddress(eAddress: String): Boolean;
begin
result := (POS('@',eAddress)>1) and (POS('.',eAddress)>1);
end;
Function TrimNumbersLeft(const S: String): String;
var
I, L: Integer;
begin
L := Length(S);
I := 1;
while (I <= L) and (Pos(S[i],' 0123456789') > 0) do Inc(I);
Result := Copy(S, I, Maxint);
end;
//trims multi spaces in the interior of a string
function TrimInterior(const Name: String): String;
var
i,j, L: Integer;
prevWasSpace: Boolean;
begin
L := Length(Name);
SetLength(result, L);
j := 1;
prevWasSpace := False;
for i := 1 to L do
begin
if Name[i] = ' ' then
if not prevWasSpace then
begin
result[j] := name[i];
prevWasSpace := True;
inc(j);
end
else
else
begin
result[j] := name[i];
prevWasSpace := False;
inc(j);
end;
end;
Setlength(result, j-1);
end;
function PosRScan(C: char; S: string): Integer;
var
i: Integer;
begin
i := length(S);
while i > 0 do
if S[i]=C then
break
else
dec(i);
result := i;
end;
Function NotNil(obj: TObject): Boolean;
begin
result := obj <> nil;
end;
procedure ReplaceCRwithSpace(var S: String);
var
k: Integer;
begin
repeat
k := Pos(char(#13), S);
if K > 0 then
begin
Delete(S, k, 1); //delete CR
Insert(' ', S, k); //insert Space
end;
until k = 0;
end;
function IsProcessRunning(const processName: String): Boolean;
begin
result := (0 <> GetModuleHandle(PChar(processName)));
end;
function ParseStreetAddress(const Address: String; Cmd, Opt: Integer): String;
const
cmdStrNo = 1;
cmdStrName = 2;
cmdStrSte = 3;
optNone = 0;
optTrmRt = 1;
var
psn : integer;
ststr : string;
function AptTest(str : string) : boolean;
begin // AptTest
if (Pos(Char($23), str) > 0) or (Pos('APT', UpperCase(str)) > 0)
or (Pos('#', UpperCase(str))>0) or (POS(', #', UpperCase(str))>0)
or (Pos('STE', UpperCase(str)) > 0) or (Pos('SUITE', UpperCase(str)) > 0) then begin
Result := true;
end // then
else begin
Result := false;
end; // if
end; // AptTest
begin // StreetParse
ststr := Address;
ststr := Trim(ststr);
psn := Pos(' ', ststr);
case cmd of
cmdStrNo : begin
ststr := Copy(ststr, 1, psn - 1);
end; // cmdStrNo
cmdStrName : begin
Delete(ststr, 1, psn);
ststr := TrimLeft(ststr);
if opt = optTrmRt then begin
psn := min(LastDelimiter(' ', ststr), POS(', #', ststr));
if AptTest(Copy(ststr, psn + 1, Length(ststr) - psn)) then begin
Delete(ststr, psn, Length(ststr) - psn + 1);
end; // if
end; // if
end; // cmdStrName
cmdStrSte : begin
psn := LastDelimiter(' ', ststr);
if AptTest(Copy(ststr, psn + 1, Length(ststr) - psn)) then begin
Delete(ststr, 1, psn);
end // then
else begin
ststr := '';
end; // if
end; // cmdStrSte
else
ststr := '';
end; // case
Result := ststr;
end; // StreetParse
//Cleans up a name to remove middle initials pre/post suffixes, etc
function NameClean(istr : string) : string;
var
psn : integer;
gstr, ostr : string;
begin // NameClean
istr := Trim(istr);
ostr := '';
while Length(istr) > 0 do begin
psn := Pos(' ', istr);
if psn > 0 then begin
gstr := Copy(istr, 1, psn - 1);
end // then
else begin
gstr := istr;
psn := Length(istr);
end; // if
if (Pos('.', gstr) > 0)
or (Length(gstr) = 1)
or ((Length(gstr) = 2) and (
(Pos('mr', LowerCase(gstr)) > 0)
or (Pos('ms', LowerCase(gstr)) > 0)
or (Pos('md', LowerCase(gstr)) > 0)
or (Pos('jr', LowerCase(gstr)) > 0)
or (Pos('sr', LowerCase(gstr)) > 0)
or (Pos('ii', LowerCase(gstr)) > 0)
))
or ((Length(gstr) = 3) and (
(Pos('mrs', LowerCase(gstr)) > 0)
or (Pos('phd', LowerCase(gstr)) > 0)
or (Pos('dds', LowerCase(gstr)) > 0)
or (Pos('iii', LowerCase(gstr)) > 0)
)) then begin
; // Let it be deleted
end // then
else begin
if Length(ostr) > 0 then begin
ostr := ostr + ' ';
end; // if
ostr := ostr + gstr;
end; // if
Delete(istr, 1, psn);
TrimLeft(istr);
end; // while
Result := ostr;
end; // NameClean
//scans a string and gets first two groups of chars separated by spaces
function GetFirstLastName(const fullName: String): String;
var
name: String;
i,L,spaces: integer;
begin
//trim multiple space, left, interior and right
name := Trim(fullName); //eliminate spaces
name := NameClean(Name); //eliminate middle initials, etc
name := Trim(name); //get rid of dangling stuff
i := 1;
L := Length(name);
//use only chars
while i <= L do
begin
if not (name[i] in ['a'..'z','A'..'Z']) then
name[i] := ' ';
inc(i);
end;
name := TrimInterior(Name); //eliminate multiple spaces within name
//now get two groups
i := 1;
L := Length(name);
spaces := 0;
while (i <= L) and (spaces < 2) do
begin
if (name[i] = ' ') then inc(spaces);
if spaces > 1 then break;
inc(i);
end;
result := Copy(name, 1, i-1);
end;
function GetNamePart(const fullName: String; Part: Integer): String;
var
twoPartName: String;
n: Integer;
begin
twoPartName := GetFirstLastName(fullName);
case Part of
1:
begin
n := pos(' ',twoPartName);
result := copy(twoPartName, 1, n-1);
end;
2:
begin
n := pos(' ',twoPartName);
result := copy(twoPartName, n+1, length(twoPartName)-n);
end
end;
end;
function GetGoodUserName(const userName, defaultName: String): String;
begin
result := GetFirstLastName(UserName);
if length(result) = 0 then
result := defaultName;
end;
function GetLastDigits(const Str: String): String;
var
i,j: Integer;
begin
j := Length(Str);
for i := Length(Str) downto 1 do
if Str[i] in ['0'..'9'] then
j := i
else
break; //break as soon as we hit alpha characters
result := Copy(Str, j, length(Str)-j+1);
end;
//function ParseCommand(Const Str: String; var CmdID, FrmID, InsID, ActionID: Integer): Boolean;
function ParseCommand(Const Str: String; var CmdID, FrmID, InsID, ActionID, OvrID: Integer): Boolean; //add overwrite id
var
i,N: Integer;
UpStr: String;
begin
UpStr := Uppercase(Str);
CmdID := 0;
FrmID := 0;
InsID := 0;
OvrID := 0;
If POS('CMD', UpStr)> 0 then //this is a command
try
//get the command
if Pos('UPLOAD', UpStr) > 0 then
CmdID := 5
else if POS('LOAD',UpStr)> 0 then
CmdID := 1 {cLoadCmd}
else if POS('MERGE',UpStr)> 0 then
CmdID := 2 {cMergeCmd}
else if POS('POPIN', UpStr)> 0 then
CmdID := 3 {cImportCmd}
else if Pos('ORDER', UpStr) > 0 then
CmdID := 4;
//F stands for Form. This identifies the unique form ID
N := POS('.F', UpStr);
if N > 0 then
begin
N := N+2;
i := N;
while UpStr[i] in ['0'..'9'] do inc(i); //count digits
FrmID := StrToInt(Copy(UpStr, N, i-N));
end;
//I stands for Instance of the form (So we can load the same form twice)
N := POS('.I', UpStr);
if N > 0 then
begin
N := N+2;
i := N;
while UpStr[i] in ['0'..'9'] do inc(i); //count digits
InsID := StrToInt(Copy(UpStr, N, i-N));
end;
if POS('BROADCAST', UpStr) > 0 then
ActionID := 1;
if POS('BROADCASTALL', UpStr) > 0 then
ActionID := 2;
if POS('OVERWRITE', UpStr) > 0 then
OvrID := 1; //1 = Overwrite 0 = Not Overwrite
except
ShowNotice('The import command "' + Str + '" is not valid.');
end;
result := (CmdID > 0) and (FrmID > 0);
end;
procedure UpperCaseChar(var Key: Char);
begin
if (Key >= 'a') and (Key <= 'z') then Dec(Key, 32);
end;
//Now we have 3 different functions ParseCityStateZip
//We have to replace ParseCityStateZip and ParseCityStateZip2 with ParseCityStateZip3
function ParseCityStateZip(const addstr : string; cmd : integer) : string;
var
iscity, isstate, iszip : boolean;
psn, ind : integer;
ststr : string;
begin // ParseCity
iscity := true;
isstate := true;
iszip := true;
ststr := Trim(addstr);
psn := Pos(',', ststr);
if psn = 0 then begin
isState := false;
psn := LastDelimiter(' ', ststr);
if psn = 0 then begin
for ind := 1 to Length(ststr) do begin
if not (ststr[ind] in ['0'..'9', '-']) then begin
isZip := false;
break;
end; // if
end; // for
if isZip then
isCity := false
else
psn := Length(ststr) + 1;
end // then
else begin
for ind := (psn + 1) to Length(ststr) do begin
if not (ststr[ind] in ['0'..'9', '-']) then begin
isZip := false;
break;
end; // if
end; // for
if not isZip then begin
psn := Length(ststr) + 1;
end; // if
end; // if
end; // if
case cmd of
cmdGetCity : begin
if isCity then begin
ststr := Copy(ststr, 1, psn - 1);
end // then
else begin
ststr := '';
end; // if
end; // cmdCity
cmdGetState : begin
if isState then begin
Delete(ststr, 1, psn);
ststr := TrimLeft(ststr);
ststr := Copy(ststr, 1, 2);
for ind := 1 to Length(ststr) do begin
if not (ststr[ind] in ['a'..'z', 'A'..'Z']) then begin
isstate := false;
break;
end; // if
end; // for
end; // if
if not isState then begin
ststr := '';
end; // if
end; // cmdState
cmdGetZip : begin
if isZip then begin
psn := LastDelimiter(' ', ststr);
ststr := Copy(ststr, psn + 1, Length(ststr) - psn);
for ind := 1 to Length(ststr) do begin
if not (ststr[ind] in ['0'..'9', '-']) then begin
isZip := false;
break;
end; // if
end; // for
end; // if
if not isZip then begin
ststr := '';
end; // if
end; // cmdZip
else
ststr := '';
end; // case
Result := ststr;
end; // ParseCity
function ParseCityStateZip2(const addstr : string; cmd : integer) : string;
const
delimSpace = ' ';
delimComa = ',';
zipChars: Set of Char = ['0'..'9', '-'];
var
strCity,strState,strZip: String;
delimPos: Integer;
curStr: String;
indx: Integer;
begin
strCity := '';
strState := '';
strZip := '';
curStr := addstr;
delimPos := Pos(delimComa,curStr);
if delimPos = 0 then
strCity := curStr
else
begin
strCity := Trim(Copy(curStr,1,delimPos - 1));
curStr := Trim(copy(curStr,delimPos + 1,length(curStr)));
delimPos := Pos(delimSpace,curStr);
if DelimPos = 0 then
strState := curStr
else
begin
strState := Trim(Copy(curStr,1,delimPos - 1));
curStr := Trim(Copy(curStr,delimPos + 1,length(curStr)));
for indx := 1 to length(curStr) do
if not (curStr[indx] in zipChars) then
break;
if indx > length(curStr)
then strZip := curStr;
end;
end;
case cmd of
cmdGetCity: result := strCity;
cmdGetState: result := strState;
cmdGetZip: result := strZip;
else
result := '';
end;
end;
procedure ParseFullAddress(const fullAddress: String; var Address, CityStZip: String);
var
n: Integer;
begin
cityStZip := '';
n := POS(';',fullAddress); //go to first semicolon
if n = 0 then //if not one..
n := POS(',',fullAddress); //..check for comma
if n > 0 then //if found divider
begin
Address := Trim(Copy(fullAddress,1,n-1));
CityStZip := Trim(Copy(fullAddress,n+1,length(fullAddress)));
end
else
Address := fullAddress;
end;
function WrapTextAdv(text: String; canv: TCanvas; width: Integer; var LineLengths: IntegerArray): Boolean;
var
remainText,curLineText: String;
curLine: Integer;
LastChar,lastWordEndPos,CRPos: Integer;
sz: TSize;
begin
SetLength(LineLengths,0);
remainText := text;
curLine := 0;
while length(remainText) > 0 do
begin
GetTextExtentExPoint(canv.Handle,PChar(remainText),length(remainText),width,@LastChar,nil,sz);
curLineText := Copy(remainText,1,LastChar);
CRPos := Pos(#13,curLineText);
if CRPos <> 0 then
begin
if curLineText[CRPos] = #10 then //LF
inc(CRPos);
lastChar := min(lastChar,CRPos);
end
else
if (length(remainText) > lastChar) and not isDelimiter(' ',remainText,lastChar + 1) then
begin
lastWordEndPos := LastDelimiter(' ',curLineText);
if lastWordEndPos > 0 then
LastChar := lastWordEndPos;
end;
SetLength(LineLengths,curLine + 1);
LineLengths[curLine] := lastChar;
remainText := Copy(remainText,lastChar + 1,length(remainText));
inc(curLine);
end;
result := True;
end;
// This will change string to a Browser friendly string.
function UrlEncode(const DecodedStr: String): String;
var
I: Integer;
begin
Result := '';
if Length(DecodedStr) > 0 then
begin
for I := 1 to Length(DecodedStr) do
begin
if not (DecodedStr[I] in ['0'..'9', 'a'..'z',
'A'..'Z', ' ']) then
Result := Result + '%' + IntToHex(Ord(DecodedStr[I]), 2)
else if not (DecodedStr[I] = ' ') then
Result := Result + DecodedStr[I]
else
begin
Result := Result + '+';
end;
end;
end;
end;
function FormatPhone(const phone: String): String;
var
i, j: Integer;
digits, phoneNo: String;
begin
digits := ' '; //10 spaces
j:= 1;
for i := 1 to length(phone) do
if (phone[i] in ['0'..'9']) then
if j <= 10 then
begin
digits[j] := phone[i];
inc(j);
end
else
break;
if (pos(' ', digits) > 0) then
result := ''
else
begin
PhoneNo := '???-???-????';
phoneNo[1] := digits[1];
phoneNo[2] := digits[2];
phoneNo[3] := digits[3];
// phoneNo[4] := '-';
phoneNo[5] := digits[4];
phoneNo[6] := digits[5];
phoneNo[7] := digits[6];
// phoneNo[8] := '-';
phoneNo[9] := digits[7];
phoneNo[10] := digits[8];
phoneNo[11] := digits[9];
phoneNo[12] := digits[10];
result := PhoneNo;
end;
end;
function GetZipCodePart(const zip: String; part: Integer): String;
var
i,j,k: Integer;
zip5: String[5];
zip4: String[4];
begin
zip5 := '';
zip4 := '';
j := 1;
k := 1;
for i := 1 to length(zip) do
if (zip[i] in ['0'..'9']) then //will not work for non-US codes
if j <= 5 then
begin
zip5[j] := zip[i];
zip5[0] := chr(j);
inc(j);
end
else if k <= 4 then
begin
zip4[k] := zip[i];
zip4[0] := chr(k);
inc(k);
end
else
break;
case part of
0:
begin
result := Zip5;
if length(zip4) = 4 then
result := result + '-' + zip4;
end;
1:
begin
result := zip5;
end;
2:
begin
result := zip4;
end;
end;
end;
function IsStringZipCode(const str: String): Boolean;
const
digits: TSysCharSet = ['0'..'9'];
dash: Char = '-';
var
ind: Integer;
bOK: Boolean;
begin
result := False;
//str has to be trimmed
if (length(str) <> 5) and (length(str) <> 10) then
exit;
bOK := True;
for ind := 1 to 5 do
if not (str[ind] in digits) then
begin
bOK := False;
break;
end;
if not bOK then
exit;
if length(str) = 5 then
begin
result := True;
exit;
end;
if str[6] <> dash then
exit;
for ind := 7 to 10 do
if not (str[ind] in digits) then
exit;
result := True;
end;
function IsStringState(const str: String): Boolean;
const
stateAbbr = 'AL,AK,AS,AZ,AR,CA,CO,CT,DE,DC,FM,FL,GA,GU,HI,ID,IL,IN,IA,KS,KY,' +
'LA,ME,MH,MD,MA,MI,MN,MS,MO,MT,NE,NV,NH,NJ,NM,NY,NC,ND,MP,OH,OK,' +
'OR,PW,PA,PR,RI,SC,SD,TN,TX,UT,VT,VI,VA,WA,WV,WI,WY';
stateFull = 'ALABAMA, ALASKA, ARIZONA, ARKANSAS, CALIFORNIA, COLORADO, CONNECTICUT,'+
'DELAWARE, FLORIDA, GEORGIA, HAWAII, IDAHO, ILLINOIS, INDIANA, IOWA, KANSAS,'+
'KENTUCKY, LOUISIANA, MAINE, MARYLAND, MASSACHUSETTS, MICHIGAN, MINNESOTA,'+
'MISSISSIPPI, MISSOURI, MONTAANA, NEBRASKA, NEVADA, NEW HAMPSHIRE, NEW JERSEY,'+
'NEW MEXICO, NEW YORK, NORTH CAROLINA, NORTH DAKOTA, OHIO, OKLAHOMA, OREGON, PENNSYLVANIA,'+
'RHODE ISLAND, SOUTH CAROLINA, SOUTH DAKOTA, TENNESSEE, TEXAS, UTAH, VERMONT,'+
'VIRGINIA, WASHINGTON, WEST VIRGINIA, WISCONSIN, WYOMING';
var
aState, aStr: String;
begin
if (length(str) = 2) and ((Pos(UpperCase(str),stateAbbr) mod 3) = 1) then
result := True
else
begin
aStr := upperCase(str);
aState := copy(aStr, 1, 5); //use the first 5 to compare
if pos(aState, stateFull) > 0 then //github #439: for full state name, use the full state name list to compare
result := True;
end;
end;
function StripCommas(S: String): String;
var
k: Integer;
begin
repeat
k := Pos(',', S);
if K > 0 then
Delete(S, k, 1);
until k = 0;
result := S;
end;
//We need another parsing function because of the existing ones assume presence a comma
// in the string. Some properties data providers (Win2Data, Realquest) used format
//without comma: 'City State Zip', just spaces. The new function handles a space
//as well as a comma so we can replace old ones.
//This function should replace
function ParseCityStateZip3(const addstr : string; cmd : integer) : string;
const
delims = ', ';
var
delimPos: Integer;
strCity, strState, strZip: String;
curStr1, curStr2: string;
begin
strCity := '';
strState := '';
strZip := '';
curStr1 := Trim(addStr);
delimPos := LastDelimiter(delims,curstr1);
try
if delimPos = 0 then
begin
strCity := curStr1;
exit;
end;
curStr2 := Trim(Copy(curstr1,delimPos + 1,length(curStr1)));
if not isStringZipCode(curStr2) then
begin
if isStringState(curStr2) then
begin
strState := curStr2;
strCity := Trim(Copy(curStr1,1,delimPos - 1));
end
else
strCity := curStr1;
exit;
end;
strZip := CurStr2;
curStr1 := Trim(Copy(curStr1,1,delimPos - 1));
delimPos := LastDelimiter(delims,curStr1);
if delimPos = 0 then
begin
strCity := curStr1;
exit;
end;
curStr2 := Trim(Copy(curStr1,delimPos + 1,length(curStr1)));
if isStringState(curStr2) then
begin
strState := curStr2;
strCity := Trim(Copy(curStr1,1,delimPos - 1));
end
else
strCity := curstr1;
finally
case cmd of
cmdGetCity: result := StripCommas(strCity);
cmdGetState: result := strState;
cmdGetZip: result := strZip;
end;
end;
end;
function TrimTokens(const AString : string) : string;
begin
Result := TrimTokens(AString, ['''', '"']);
end;
function TrimTokens(const AString : string; const Delimiters : array of string) : string;
var
Counter, Index : System.Integer;
StillSearching : Boolean;
begin
Result := AString;
StillSearching := True;
while StillSearching do
begin
StillSearching := False;
for Counter := Low(Delimiters) to High(Delimiters) do
begin
if Copy(Result, 1, Length(Delimiters[Counter])) = Delimiters[Counter] then
begin
Delete(Result, 1, Length(Delimiters[Counter]));
StillSearching := True;
Break;
end;
end;
end;
StillSearching := True;
while StillSearching do
begin
StillSearching := False;
for Counter := Low(Delimiters) to High(Delimiters) do
begin
Index := (Length(Result) - Length(Delimiters[Counter])) + 1;
if Copy(Result, Index, Length(Delimiters[Counter])) = Delimiters[Counter] then
begin
Delete(Result, Index, Length(Delimiters[Counter]));
StillSearching := True;
Break;
end;
end;
end;
end;
function StrToDateEx(strDate: String; strDateFrmt: String; chDateSepar: Char): TDateTime;
var
systDateFrmt: String;
systDateSepar: Char;
begin
//get system setting
systDateFrmt := ShortDateFormat;
systDateSepar := DateSeparator;
//set system setting
ShortDateFormat := strDateFrmt;
DateSeparator := chDateSepar;
try
result := StrToDate(strDate);
except
result := 0;
end;
//restore system settings
ShortDateFormat := systDateFrmt;
DateSeparator := systDateSepar;
end;
function PopStr(var sList : string; Seperator: String): string;
var
iPos : integer;
begin
Result := '';
if (sList = '') then
begin
Result:='';
Exit;
end;
iPos := Pos(Seperator,sList);
if (iPos > 0) then
begin
Result := Copy(sList,1,iPos-1);
Delete(sList,1,iPos-1+Length(Seperator));
end
else
begin
Result := sList;
sList := ''
end;
end;
function ParseUnitCityStateZip(const addstr : string; cmd : integer) : string;
var
isUnit, iscity, isstate, iszip : boolean;
psn, ind : integer;
ststr : string;
begin // ParseUnit
isUnit := true;
iscity := true;
isstate := true;
iszip := true;
ststr := Trim(addstr);
psn := Pos(',', ststr); //first comma
if psn > 0 then begin
psn := Pos(',', stStr);
if psn = 0 then // we don't have unit #
isUnit := false
end;
psn := Pos(',', ststr);
if psn = 0 then begin
isState := false;
psn := LastDelimiter(' ', ststr);
if psn = 0 then begin
for ind := 1 to Length(ststr) do begin
if not (ststr[ind] in ['0'..'9', '-']) then begin
isZip := false;
break;
end; // if
end; // for
if isZip then
isCity := false
else
psn := Length(ststr) + 1;
end // then
else begin
for ind := (psn + 1) to Length(ststr) do begin
if not (ststr[ind] in ['0'..'9', '-']) then begin
isZip := false;
break;
end; // if
end; // for
if not isZip then begin
psn := Length(ststr) + 1;
end; // if
end; // if
end; // if
case cmd of
cmdGetUnit : begin
if isUnit then begin
ststr := Copy(ststr, 1, psn - 1);
end; //then
end; //cmdUnit
cmdGetCity : begin
if isCity then begin
ststr := popStr(ststr,',');
//ststr := Copy(ststr, 1, psn - 1);
end // then
else begin
ststr := '';
end; // if
end; // cmdCity
cmdGetState : begin
if isState then begin
Delete(ststr, 1, psn);
ststr := TrimLeft(ststr);
ststr := Copy(ststr, 1, 2);
for ind := 1 to Length(ststr) do begin
if not (ststr[ind] in ['a'..'z', 'A'..'Z']) then begin
isstate := false;
break;
end; // if
end; // for
end; // if
if not isState then begin
ststr := '';
end; // if
end; // cmdState
cmdGetZip : begin
if isZip then begin
psn := LastDelimiter(' ', ststr);
ststr := Copy(ststr, psn + 1, Length(ststr) - psn);
for ind := 1 to Length(ststr) do begin
if not (ststr[ind] in ['0'..'9', '-']) then begin
isZip := false;
break;
end; // if
end; // for
end; // if
if not isZip then begin
ststr := '';
end; // if
end; // cmdZip
else
ststr := '';
end; // case
Result := ststr;
end; // ParseCity
function GetAppName:String;
begin
if AppIsClickForms then
result := AppTitleClickFORMS;
end;
//This routine will give us the Unit#, City, State, Zip out of the CityStZip string
//If CityStZip includes unit#, parse unit # before parse city
//Based on the format: Unit#, City, State Zip or City, State Zip
procedure GetUnitCityStateZip(var unitNo, City, State,Zip: String; citystZip:String);
var
aStr: String;
hasUnitNo:Boolean;
begin
aStr := trim(CityStZip);
popStr(aStr, ','); //pop the first comma
hasUnitNo := pos(',',aStr) > 0; //still have more comma, means we have unit # in CityStZip
if hasUnitNo then //we know we have unit #
begin
aStr := trim(CityStZip);
UnitNo := popStr(aStr, ',');
aStr := trim(aStr); //get rid of space in front
City := popStr(aStr, ',');
City := trim(City);
aStr := trim(aStr); //get rid of space in front
if pos(' ', aStr) > 0 then
begin
state := popStr(aStr, ' ');
state := trim(state);
end;
zip := trim(aStr);
end
else
begin
aStr := trim(CityStZip);
City := popStr(aStr, ',');
City := Trim(City);
aStr := trim(aStr); //get rid of space in front
if pos(' ', aStr) > 0 then
begin
state := popStr(aStr, ' ');
state := trim(state);
end;
zip := trim(aStr);
end;
end;
//this routine deal with sales date UAD in this format: smm/yy;cmm/yy
//the Sep can be s or c
function ConvertSalesDateMDY(aDateStr:String;Sep:String):String;//aDateStr = smm/yy;cmm/yy
var
aMonth, aYear, aStr:String;
begin
result := '';
if (POS(';',aDateStr) > 0) and (POS(Sep,aDateStr)>0) then
begin
aStr := popStr(aDateStr, ';');
if (aStr <> '') and (pos('/',aStr) > 0) then
aMonth := popStr(aStr, '/');
if POS('s',aMonth) > 0 then
aMonth := copy(aMonth, 2, 2); //copy the last 2
aYear := aStr;
result := Format('%s/01/%s',[aMonth, aYear]); //put back date format and add 01 for the day
end;
end;
//Insert a data array of bytes that represent an image and put it into a JPEG
procedure LoadJPEGFromByteArray(const dataArray: String; var JPGImg: TJPEGImage);
var
msByte: TMemoryStream;
iSize: Integer;
begin
msByte := TMemoryStream.Create;
try
iSize := Length(DataArray);
msByte.WriteBuffer(PChar(DataArray)^, iSize);
msByte.Position:=0;
if not assigned(JPGImg) then
JPGImg := TJPEGImage.Create;
JPGImg.LoadFromStream(msByte);
finally
msByte.Free;
end;
end;
//XML date format - its in other places,by other names
function convertStrToDateStr(aStrDate: String): String; //Pam 07/01/2015 Return U.S. Date format when we have European DateTime Format String
var
aDate: TDateTime;
begin
result := '';
if aStrDate <> '' then
begin
if pos('0000', aStrDate) > 0 then exit; //not a valid date
//Use VarToDateTime to convert European Date or any date time string to U.S DateTime string
//This will work when we have yyyy-mm-dd hh:mm:ss
aDate := VarToDateTime(aStrDate);
if aDate > 0 then
result := FormatDateTime('mm/dd/yyyy', aDate);
end;
end;
function convertStrToTimeStr(aStrDate: String): String; //Pam 07/01/2015 Return U.S. Date format when we have European DateTime Format String
var
aDate: TDateTime;
aDateTimeStr: String;
begin
result := '';
if aStrDate <> '' then
begin
if pos('0000', aStrDate) > 0 then exit; //not a valid date
//Use VarToDateTime to convert European Date or any date time string to U.S DateTime string
//This will work when we have yyyy-mm-dd hh:mm:ss
aDate := VarToDateTime(aStrDate);
if aDate > 0 then
begin
aDateTimeStr := FormatDateTime('mm/dd/yyyy hh:mm', aDate);
popStr(aDateTimeStr, ' ');
result := aDateTimeStr;
end;
end;
end;
function EncodeDigit2Char(N: Integer): String;
begin
result := '?';
case N of
1: result := 'B';
2: result := 'R';
3: result := 'A';
4: result := 'D';
5: result := 'T';
6: result := 'E';
7: result := 'C';
8: result := 'H';
9: result := '#';
10: result := '1';
end;
end;
function DecodeChar2Digit(C: String): Integer;
var
aChar: Char;
begin
result := 0;
if C = '' then
exit;
aChar := C[1];
case aChar of
'B': result := 1;
'R': result := 2;
'A': result := 3;
'D': result := 4;
'T': result := 5;
'E': result := 6;
'C': result := 7;
'H': result := 8;
'#': result := 9;
'1': result := 10;
else
result := 999;
end;
end;
function GetMainAddressChars(const address: String): String;
begin
result := StringReplace(address,' ','',[rfReplaceAll]); //remove spaces
result := StringReplace(result,',','',[rfReplaceAll]); //remove commas
result := StringReplace(result,'.','',[rfReplaceAll]); //remove periods
end;
function GetStreetNameOnly(const streetAddress: String): String;
begin
result := TrimNumbersLeft(streetAddress);
//do other street name processing/parsing here
end;
function ForceLotSizeToSqFt(lotSize: String): String;
var
siteArea: Double;
begin
result := lotSize; //assumme its already in sqft
siteArea := StrToFloatDef(lotSize, 0);
if (siteArea < 250) and (siteArea > 0) then
result := IntToStr(Round(siteArea * 43560.0));
end;
end.
|
// Fit4Delphi Copyright (C) 2008. Sabre Inc.
// This program is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software Foundation;
// either version 2 of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with this program;
// if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
// Derived from Fixture.java by Martin Chernenkoff, CHI Software Design
// Ported to Delphi by Michal Wojcik.
//
unit Display;
interface
uses
Classes,
RowFixture;
type
TDisplay = class(TRowFixture)
public
function query : TList; override;
function getTargetClass() : TClass; override;
end;
implementation
uses
MusicLibrary,
Music;
function TDisplay.getTargetClass : TClass;
begin
Result := TMusic;
end;
function TDisplay.query : TList;
begin
Result := TList.Create;
MusicLibrary.DisplayContents(result);
end;
initialization
RegisterClass(TDisplay);
finalization
UnRegisterClass(TDisplay);
end.
|
unit QApplication.Window;
interface
uses
Windows,
Messages,
QCore.Types,
Strope.Math;
type
TWindow = class sealed
strict private
FOwner: TComponent;
FHandle: THandle;
FCaption: string;
FCaptionSize, FBorderSizeX, FBorderSizeY: Word;
procedure SetCaption(ACaption: string);
class procedure RegisterWindowClass;
private
function WndProc(Msg: Cardinal; WParam, LParam: Integer): Boolean;
public
class constructor CreateClass;
class destructor DestroyClass;
constructor Create(AOwner: TComponent);
destructor Destroy; override;
procedure CreateWindow(const AWindowCaption: string;
AClientWidth, AClientHeight: Word);
property Handle: THandle read FHandle;
property Caption: string read FCaption write SetCaption;
end;
implementation
uses
SysUtils,
QCore.Input,
QApplication.Application;
{$REGION ' TWindow '}
function WindowProcess(
HWnd: HWND; Msg: Cardinal;
WParam, LParam: Integer): Integer; stdcall;
var
AWindow: TWindow;
begin
AWindow := TWindow(GetWindowLongA(HWnd, GWL_USERDATA));
if Assigned(AWindow) then
if AWindow.WndProc(Msg, WParam, LParam) then
Exit(0);
Result := DefWindowProcA(HWnd, Msg, WParam, LParam);
end;
class constructor TWindow.CreateClass;
begin
RegisterWindowClass;
end;
class destructor TWindow.DestroyClass;
begin
UnregisterClassA(PAnsiChar('QApplication Window'), HInstance);
end;
constructor TWindow.Create(AOwner: TComponent);
begin
if Assigned(AOwner) then
FOwner := AOwner
else
raise EArgumentException.Create(
'Не указан владелец окна. ' +
'{A12D5AE0-0629-40A4-9DFC-5699104EAF75}');
end;
destructor TWindow.Destroy;
begin
FOwner := nil;
if FHandle > 0 then
DestroyWindow(FHandle);
inherited;
end;
class procedure TWindow.RegisterWindowClass;
var
AWndClass: WNDCLASSEXA;
begin
FillChar(AWndClass, SizeOf(AWndClass), 0);
with AWndClass do
begin
cbSize := SizeOf(AWndClass);
style := CS_HREDRAW or CS_VREDRAW;
lpfnWndProc := @WindowProcess;
hCursor := LoadCursorA(0, PAnsiChar(IDC_ARROW));
hIcon := LoadIconA(0, PAnsiChar(IDI_APPLICATION));
hbrBackground := HBRUSH(GetStockObject(BLACK_BRUSH));
lpszClassName := PAnsiChar('QApplication Window');
end;
AWndClass.hInstance := HInstance;
if RegisterClassExA(AWndClass) = 0 then
raise Exception.Create(
'Window class register fail. ' +
'{6393A518-7353-41A1-9468-61B83F854164}');
end;
function TWindow.WndProc(Msg: Cardinal; WParam, LParam: Integer): Boolean;
var
APosition: TPoint;
begin
Result := False;
case Msg of
{$REGION ' Focus '}
WM_SETFOCUS:
begin
FOwner.OnActivate(True);
Exit(True);
end;
WM_KILLFOCUS:
begin
FOwner.OnActivate(False);
Exit(True);
end;
{$ENDREGION}
{$REGION ' Keyboard input '}
WM_KEYDOWN:
begin
FOwner.OnKeyDown(WParam);
Exit(True);
end;
WM_KEYUP:
begin
FOwner.OnKeyUp(WParam);
Exit(True);
end;
WM_SYSKEYDOWN:
begin
FOwner.OnKeyDown(WParam);
Exit(True);
end;
WM_SYSKEYUP:
begin
FOwner.OnKeyUp(WParam);
Exit(True);
end;
{$ENDREGION}
{$REGION ' Mouse input '}
WM_MOUSEMOVE:
begin
GetCursorPos(APosition);
ScreenToClient(Handle, APosition);
//Бред, но почему так вечно?!!
if TheApplication.IsFullscreen then
begin
APosition.X := APosition.X + FBorderSizeX;
APosition.Y := APosition.Y + FCaptionSize + FBorderSizeY;
end;
FOwner.OnMouseMove(Vec2F(APosition.X, APosition.Y));
Exit(True);
end;
WM_LBUTTONDOWN:
begin
GetCursorPos(APosition);
ScreenToClient(Handle, APosition);
//Бред, но почему так вечно?!!
if TheApplication.IsFullscreen then
begin
APosition.X := APosition.X + FBorderSizeX;
APosition.Y := APosition.Y + FCaptionSize + FBorderSizeY;
end;
FOwner.OnMouseButtonDown(mbLeft, Vec2F(APosition.X, APosition.Y));
Exit(True);
end;
WM_LBUTTONUP:
begin
GetCursorPos(APosition);
ScreenToClient(Handle, APosition);
//Бред, но почему так вечно?!!
if TheApplication.IsFullscreen then
begin
APosition.X := APosition.X + FBorderSizeX;
APosition.Y := APosition.Y + FCaptionSize + FBorderSizeY;
end;
FOwner.OnMouseButtonUp(mbLeft, Vec2F(APosition.X, APosition.Y));
Exit(True);
end;
WM_RBUTTONDOWN:
begin
GetCursorPos(APosition);
ScreenToClient(Handle, APosition);
//Бред, но почему так вечно?!!
if TheApplication.IsFullscreen then
begin
APosition.X := APosition.X + FBorderSizeX;
APosition.Y := APosition.Y + FCaptionSize + FBorderSizeY;
end;
FOwner.OnMouseButtonDown(mbRight, Vec2F(APosition.X, APosition.Y));
Exit(True);
end;
WM_RBUTTONUP:
begin
GetCursorPos(APosition);
ScreenToClient(Handle, APosition);
//Бред, но почему так вечно?!!
if TheApplication.IsFullscreen then
begin
APosition.X := APosition.X + FBorderSizeX;
APosition.Y := APosition.Y + FCaptionSize + FBorderSizeY;
end;
FOwner.OnMouseButtonUp(mbRight, Vec2F(APosition.X, APosition.Y));
Exit(True);
end;
WM_MBUTTONDOWN:
begin
GetCursorPos(APosition);
ScreenToClient(Handle, APosition);
//Бред, но почему так вечно?!!
if TheApplication.IsFullscreen then
begin
APosition.X := APosition.X + FBorderSizeX;
APosition.Y := APosition.Y + FCaptionSize + FBorderSizeY;
end;
FOwner.OnMouseButtonDown(mbMiddle, Vec2F(APosition.X, APosition.Y));
Exit(True);
end;
WM_MBUTTONUP:
begin
GetCursorPos(APosition);
ScreenToClient(Handle, APosition);
//Бред, но почему так вечно?!!
if TheApplication.IsFullscreen then
begin
APosition.X := APosition.X + FBorderSizeX;
APosition.Y := APosition.Y + FCaptionSize + FBorderSizeY;
end;
FOwner.OnMouseButtonUp(mbMiddle, Vec2F(APosition.X, APosition.Y));
Exit(True);
end;
WM_MOUSEWHEEL:
begin
if WParam > 0 then
FOwner.OnMouseWheel(1)
else
FOwner.OnMouseWheel(-1);
Exit(True);
end;
{$ENDREGION}
WM_CLOSE:
begin
DestroyWindow(Handle);
Exit(True);
end;
WM_DESTROY:
begin
FOwner.OnDestroy;
PostQuitMessage(0);
Exit(True);
end;
end;
end;
procedure TWindow.SetCaption(ACaption: string);
begin
FCaption := ACaption;
SetWindowText(FHandle, ACaption);
end;
procedure TWindow.CreateWindow(
const AWindowCaption: string;
AClientWidth, AClientHeight: Word);
var
AWindowWidth, AWindowHeight: Word;
begin
if FHandle <> 0 then
raise Exception.Create(
'Window already created! ' +
'{7C6D90CE-6214-4650-B210-23463687980E}');
FCaptionSize := GetSystemMetrics(SM_CYCAPTION );
FBorderSizeX := GetSystemMetrics(SM_CXDLGFRAME);
FBorderSizeY := GetSystemMetrics(SM_CYDLGFRAME);
AWindowWidth := AClientWidth + 2 * FBorderSizeX;
AWindowHeight := AClientHeight + 2 * FBorderSizeY + FCaptionSize;
FHandle := CreateWindowExA(
WS_EX_APPWINDOW or WS_EX_WINDOWEDGE,
PAnsiChar('QApplication Window'),
PAnsiChar(AnsiString(AWindowCaption)),
WS_CAPTION or WS_BORDER or WS_SYSMENU or WS_MINIMIZEBOX,
Round((GetSystemMetrics(SM_CXSCREEN) - AWindowWidth) * 0.5),
Round((GetSystemMetrics(SM_CYSCREEN) - AWindowHeight) * 0.5),
AWindowWidth, AWindowHeight,
0, 0, HInstance, nil);
if FHandle = 0 then
raise Exception.Create(
'Window create fail. ' +
'{4B351846-BBAA-4D0C-A572-D52D09F8B14D}');
FCaption := AWindowCaption;
ShowCursor(True);
SetForegroundWindow(FHandle);
ShowWindow(FHandle, SW_SHOW);
SetFocus(FHandle);
UpdateWindow(FHandle);
SetWindowLongA(FHandle, GWL_USERDATA, Cardinal(Self));
end;
{$ENDREGION}
end.
|
unit uPacienteModel;
interface
uses uTipos, Data.Win.ADODB, Data.DB;
type
TPacienteModel = class
private
FAcao: TAcao;
FCPF: String;
FDtNasc: TDateTime;
FSexo: String;
FNome: String;
procedure SetAcao(const Value: TAcao);
procedure SetCPF(const Value: String);
procedure SetDtNasc(const Value: TDateTime);
procedure SetNome(const Value: String);
procedure SetSexo(const Value: String);
public
function GetPaciente: TADOQuery;
function Salvar: Boolean;
property CPF : String read FCPF write SetCPF;
property Nome : String read FNome write SetNome;
property DtNasc : TDateTime read FDtNasc write SetDtNasc;
property Sexo : String read FSexo write SetSexo;
property Acao : TAcao read FAcao write SetAcao;
end;
implementation
{ TPaciente }
uses uPacienteDao;
function TPacienteModel.GetPaciente: TADOQuery;
var
VPacienteDao: TPacienteDao;
begin
VPacienteDao := TPacienteDao.Create;
try
Result := VPacienteDao.GetPacientes;
finally
VPacienteDao.Free;
end;
end;
function TPacienteModel.Salvar: Boolean;
var
VPacienteDao: TPacienteDao;
begin
Result := False;
VPacienteDao := TPacienteDao.Create;
try
case FAcao of
uTipos.tacIncluir: Result := VPacienteDao.Incluir(Self);
uTipos.tacAlterar: Result := VPacienteDao.Alterar(Self);
uTipos.tacExcluir: Result := VPacienteDao.Excluir(Self);
end;
finally
VPacienteDao.Free;
end;
end;
procedure TPacienteModel.SetAcao(const Value: TAcao);
begin
FAcao := Value;
end;
procedure TPacienteModel.SetCPF(const Value: String);
begin
FCPF := Value;
end;
procedure TPacienteModel.SetDtNasc(const Value: TDateTime);
begin
FDtNasc := Value;
end;
procedure TPacienteModel.SetNome(const Value: String);
begin
FNome := Value;
end;
procedure TPacienteModel.SetSexo(const Value: String);
begin
FSexo := Value;
end;
end.
|
unit DIOTA.Dto.Request.InterruptAttachingToTangleRequest;
interface
uses
DIOTA.IotaAPIClasses;
type
TInterruptAttachingToTangleRequest = class(TIotaAPIRequest)
protected
function GetCommand: String; override;
end;
implementation
{ TInterruptAttachingToTangleRequest }
function TInterruptAttachingToTangleRequest.GetCommand: String;
begin
Result := 'interruptAttachingToTangle';
end;
end.
|
unit ufrmMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdActns, ImgList, ActnList, Menus, StdCtrls, ComCtrls, ToolWin,
uHYModuleManager, uHYIntf, ExtCtrls;
type
TfrmVCLApp = class(TForm)
MainMenu1: TMainMenu;
mnuFile: TMenuItem;
itmFileExit: TMenuItem;
mnuHelp: TMenuItem;
itmHelpAbout: TMenuItem;
ActionList1: TActionList;
ImageList1: TImageList;
actFileExit: TFileExit;
actHelpAbout: TAction;
ToolBar1: TToolBar;
ToolButton1: TToolButton;
ToolButton4: TToolButton;
ToolButton5: TToolButton;
HYModuleManager1: THYModuleManager;
mnuPlugins: TMenuItem;
actLoadPlugins: TAction;
actUnloadPlugins: TAction;
actShowPlugins: TAction;
LoadPlugins1: TMenuItem;
UnloadPlugins1: TMenuItem;
N1: TMenuItem;
ShowPlugins1: TMenuItem;
dlgPluginList: TTaskDialog;
actHelpAboutPluginModal: TAction;
AboutfromPlugin1: TMenuItem;
pnlPlugins: TPanel;
actHelpAboutPluginNonModal: TAction;
Aboutfromapluginnonmodal1: TMenuItem;
actHelpAboutVersionedPluginModal: TAction;
VersionedAboutfromaplugin1: TMenuItem;
procedure actHelpAboutExecute(Sender: TObject);
procedure actLoadPluginsExecute(Sender: TObject);
procedure actUnloadPluginsExecute(Sender: TObject);
procedure actShowPluginsExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure HYModuleManager1AfterLoadModule(Sender: THYModuleManager;
aModule: THYModule);
procedure actHelpAboutPluginModalExecute(Sender: TObject);
procedure actHelpAboutPluginNonModalExecute(Sender: TObject);
procedure HYModuleManager1BeforeUnloadModule(Sender: THYModuleManager;
aModule: THYModule);
procedure actHelpAboutVersionedPluginModalExecute(Sender: TObject);
private
FSimpleAboutPlugin: IHYVisualPlugin;
FVersionedAboutPlugin: IHYVisualPlugin;
end;
var
frmVCLApp: TfrmVCLApp;
implementation
{$R *.dfm}
uses
uHYPluginDescriptors, uVersionedAboutIntf;
procedure TfrmVCLApp.actHelpAboutExecute(Sender: TObject);
begin
ShowMessage('Standard VCL Demo App');
end;
procedure TfrmVCLApp.actHelpAboutPluginModalExecute(Sender: TObject);
begin
if Assigned(FSimpleAboutPlugin) then
FSimpleAboutPlugin.ShowWindowed
else
ShowMessage('About plugin not loaded.');
end;
procedure TfrmVCLApp.actHelpAboutPluginNonModalExecute(Sender: TObject);
begin
if Assigned(FSimpleAboutPlugin) then
FSimpleAboutPlugin.ShowParented(pnlPlugins)
else
ShowMessage('About plugin not loaded.');
end;
procedure TfrmVCLApp.actHelpAboutVersionedPluginModalExecute(Sender: TObject);
begin
if Assigned(FVersionedAboutPlugin) then begin
(FVersionedAboutPlugin as IVersionedAboutInterface).ApplicationName := Application.Title;
(FVersionedAboutPlugin as IVersionedAboutInterface).MajorVersion := 1;
(FVersionedAboutPlugin as IVersionedAboutInterface).MinorVersion := 2;
(FVersionedAboutPlugin as IVersionedAboutInterface).Copyright := 'Copyright 2015';
FVersionedAboutPlugin.ShowWindowed;
end else
ShowMessage('Versioned About plugin not loaded.');
end;
procedure TfrmVCLApp.actLoadPluginsExecute(Sender: TObject);
begin
HYModuleManager1.LoadModules(ExtractFilePath(Application.ExeName) + '*.dll');
end;
procedure TfrmVCLApp.actUnloadPluginsExecute(Sender: TObject);
begin
HYModuleManager1.UnloadModules;
end;
procedure TfrmVCLApp.FormCreate(Sender: TObject);
begin
FSimpleAboutPlugin := nil;
FVersionedAboutPlugin := nil;
end;
procedure TfrmVCLApp.HYModuleManager1AfterLoadModule(Sender: THYModuleManager; aModule: THYModule);
var
i: Integer;
PluginName: string;
begin
for i := 0 to aModule.ModuleController.FactoryCount - 1 do begin
PluginName := aModule.ModuleController.Factories[i].Descriptor.Name;
if (aModule.ModuleController.Factories[i].Descriptor.PluginType = ptVisual) and
SameText('SimpleAboutPlugin', PluginName) then
HYModuleManager1.CreateVisualPlugin(PluginName, FSimpleAboutPlugin)
else if SameText('VersionedAboutPlugin', PluginName) then
HYModuleManager1.CreateVisualPlugin(PluginName, FVersionedAboutPlugin);
end;
end;
procedure TfrmVCLApp.HYModuleManager1BeforeUnloadModule(
Sender: THYModuleManager; aModule: THYModule);
var
i: Integer;
begin
for i := 0 to aModule.ModuleController.FactoryCount - 1 do
if (aModule.ModuleController.Factories[i].Descriptor.PluginType = ptVisual) then
if SameText('SimpleAboutPlugin', aModule.ModuleController.Factories[i].Descriptor.Name) and
Assigned(FSimpleAboutPlugin) then
FSimpleAboutPlugin := nil
else if SameText('VersionedAboutPlugin', aModule.ModuleController.Factories[i].Descriptor.Name) and
Assigned(FVersionedAboutPlugin) then
FVersionedAboutPlugin := nil;
end;
procedure TfrmVCLApp.actShowPluginsExecute(Sender: TObject);
function PluginTypeToStr(const PluginType: THYPluginType): string;
begin
case PluginType of
ptNonVisual:
Result := 'Non-Visual';
ptVisual:
Result := 'Visual';
ptService:
Result := 'Service';
ptUnknown:
Result := 'Unknown';
end;
end;
var
i: Integer;
PluginList: TStringList;
ModuleList: TStringList;
begin
PluginList := TStringList.Create;
ModuleList := TStringList.Create;
try
// build displayable list of module names (DLLs)
for i := 0 to HYModuleManager1.ModuleCount - 1 do
ModuleList.Add(ExtractFileName(HYModuleManager1.Modules[i].FileName));
// build displayable list of plugins
for i := 0 to HYModuleManager1.PluginDescriptorCount - 1 do begin
PluginList.Add(Format('Name: %s - Version %d.%d (%s)', [HYModuleManager1.PluginDescriptors[i].Name,
HYModuleManager1.PluginDescriptors[i].MajorVersion,
HYModuleManager1.PluginDescriptors[i].MinorVersion,
PluginTypeToStr(HYModuleManager1.PluginDescriptors[i].PluginType)]));
PluginList.Add('Description: ' + HYModuleManager1.PluginDescriptors[i].Description);
PluginList.Add(EmptyStr);
end;
dlgPluginList.Title := Format('There are %d plugin(s) in %d module(s) loaded.',
[HYModuleManager1.PluginDescriptorCount, ModuleList.Count]);
dlgPluginList.Text := PluginList.GetText;
dlgPluginList.ExpandedText := ModuleList.GetText;
dlgPluginList.Execute;
finally
ModuleList.Free;
PluginList.Free;
end;
end;
end.
|
unit ufrmInput;
interface
uses
System.SysUtils, System.Variants, System.Classes,
Winapi.Windows, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TfrmInput = class(TForm)
btnOk: TButton;
edtValue: TEdit;
mmoPrompt: TMemo;
procedure btnOkClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure edtValueKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormShow(Sender: TObject);
private
FVarType: TVarType;
public
end;
var
frmInput: TfrmInput;
function Input(const ACaption, APrompt: string; var ADefault: string; AType: TVarType = varString): Boolean; overload;
function Input(const ACaption, APrompt: string; var ADefault: Integer): Boolean; overload;
function Input(const ACaption, APrompt: string; var ADefault: Double): Boolean; overload;
implementation
{$R *.dfm}
function Input(const ACaption, APrompt: string; var ADefault: string; AType: TVarType = varString): Boolean;
begin
Result := False;
if not Assigned(frmInput) then frmInput := TfrmInput.Create(Application);
frmInput.Caption := ACaption;
frmInput.mmoPrompt.Text := APrompt;
frmInput.edtValue.Text := ADefault;
frmInput.edtValue.SelectAll;
frmInput.FVarType := AType;
frmInput.ShowModal;
Result := frmInput.ModalResult = mrOk;
if Result then ADefault := Trim(frmInput.edtValue.Text);
end;
function Input(const ACaption, APrompt: string; var ADefault: Integer): Boolean;
var
s: string;
begin
s := IntToStr(ADefault);
Result := Input(ACaption, APrompt, s, varInteger);
if Result then ADefault := StrToInt(s);
end;
function Input(const ACaption, APrompt: string; var ADefault: Double): Boolean;
var
s: string;
begin
s := FloatToStr(ADefault);
Result := Input(ACaption, APrompt, s, varDouble);
if Result then ADefault := StrToFloat(s);
end;
procedure TfrmInput.btnOkClick(Sender: TObject);
var
i: Integer;
d: Double;
s: string;
begin
s := Trim(edtValue.Text);
case FVarType of
varInteger:
begin
if not TryStrToInt(s, i) then
raise Exception.Create('请输入有效整数');
end;
varDouble:
begin
if not TryStrToFloat(s, d) then
raise Exception.Create('请输入有效数值');
end;
end;
ModalResult := mrOk;
end;
procedure TfrmInput.edtValueKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = 13 then btnOkClick(btnOk);
end;
procedure TfrmInput.FormCreate(Sender: TObject);
begin
ActiveControl := edtValue;
end;
procedure TfrmInput.FormShow(Sender: TObject);
begin
if Caption = '' then Caption := '提示';
end;
end.
|
unit UUADSiteView;
{ ClickForms Application }
{ Bradford Technologies, Inc. }
{ All Rights Reserved }
{ Source Code Copyrighted © 1998-2011 by Bradford Technologies, Inc. }
interface
uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls,
Buttons, Dialogs, StrUtils, UCell, UContainer, UEditor, UGlobals, UStatus, CheckLst,
UForms, UUADUtils;
type
TdlgUADSiteView = class(TAdvancedForm)
bbtnCancel: TBitBtn;
bbtnOK: TBitBtn;
edtOtherDesc: TEdit;
lblOtherDesc: TLabel;
lblViewAppeal: TLabel;
lbViewAppeal: TListBox;
clbViewFeatures: TCheckListBox;
bbtnHelp: TBitBtn;
bbtnClear: TBitBtn;
lblInstruction1: TLabel;
lblInstruction2: TLabel;
stFactors: TStaticText;
procedure FormShow(Sender: TObject);
procedure bbtnHelpClick(Sender: TObject);
procedure bbtnOKClick(Sender: TObject);
procedure SetOtherDescState(IsEnabled: Boolean);
function CountFeatures: Integer;
procedure bbtnClearClick(Sender: TObject);
procedure SetFactorTitle;
procedure clbViewFeaturesKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure clbViewFeaturesMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
private
FClearData : Boolean;
function GetDescriptionText: String;
public
FCell: TBaseCell;
Constructor Create(AOwner: TComponent); Override;
procedure Clear;
procedure LoadForm;
procedure SaveToCell;
end;
const
OtherFeatureIdx = 12;
MaxFeatures = 2;
FactorOK = 'Select up to two View Factors';
FactorOKColor = clBtnFace;
FactorErr = 'Warning - More than two View Factors are selected';
FactorErrColor = clYellow;
var
dlgUADSiteView: TdlgUADSiteView;
AppealTitle: array[0..2] of String = ('N','B','A');
FeatureTitle: array[0..OtherFeatureIdx] of String = ('Res','Wtr','Glfvw','Prk','Pstrl','Woods','CtySky','Mtn',
'CtyStr','Ind','PwrLn','LtdSght','Other');
FeatureDesc: array[0..OtherFeatureIdx] of String = ('ResidentialView','WaterView','GolfCourseView','ParkView',
'PastoralView','WoodsView', 'CityViewSkylineView','MountainView',
'CityStreetView','IndustrialView','PowerLines','LimitedSight','Other');
FeatureID: array[0..1] of String = ('4413','4414');
implementation
{$R *.dfm}
uses
UStrings;
constructor TdlgUADSiteView.Create(AOwner: TComponent);
begin
inherited;
end;
procedure TdlgUADSiteView.FormShow(Sender: TObject);
begin
LoadForm;
SetFactorTitle;
SetOtherDescState(clbViewFeatures.Checked[OtherFeatureIdx]); //set Other state
lbViewAppeal.SetFocus;
end;
procedure TdlgUADSiteView.bbtnHelpClick(Sender: TObject);
begin
ShowUADHelp('FILE_HELP_UAD_SITE_VIEW', Caption);
end;
procedure TdlgUADSiteView.bbtnOKClick(Sender: TObject);
var
Cntr, SelCnt: Integer;
begin
if lbViewAppeal.ItemIndex < 0 then
begin
ShowAlert(atWarnAlert, 'A view appeal must be selected.');
lbViewAppeal.SetFocus;
Exit;
end;
if (CountFeatures < 1) or (CountFeatures > 2) then
begin
ShowAlert(atWarnAlert, 'At least one but no more than 2 view factors must be selected.');
clbViewFeatures.SetFocus;
Exit;
end;
if clbViewFeatures.Checked[OtherFeatureIdx] then
if (Trim(edtOtherDesc.Text) = '') then
begin
ShowAlert(atWarnAlert, 'You must enter a description for "Other".');
edtOtherDesc.SetFocus;
Exit;
end
else
begin
Cntr := -1;
SelCnt := 0;
repeat
Cntr := Succ(Cntr);
if clbViewFeatures.Checked[Cntr] then
SelCnt := Succ(SelCnt);
until (Cntr = OtherFeatureIDx);
if (SelCnt > 1) and (Pos(';', edtOtherDesc.Text) > 0) then
begin
ShowAlert(atWarnAlert, 'Only two view factors are allowed. A semicolon (;) ' +
'in the description indicates multiple "Other" ' +
'features. Remove all the semicolons or uncheck ' +
'the first factor you selected.');
edtOtherDesc.SetFocus;
Exit;
end
else
begin
Cntr := 0;
SelCnt := 0;
repeat
Cntr := Succ(Cntr);
if edtOtherDesc.Text[Cntr] = ';' then
SelCnt := Succ(SelCnt);
until (Cntr = Length(edtOtherDesc.Text));
if SelCnt > 1 then
begin
ShowAlert(atWarnAlert, 'More than one semicolon (;) in the description indicates ' +
'more than two "Other" factors. Remove any of the ' +
'semicolons so the description contains no more than one.');
edtOtherDesc.SetFocus;
Exit;
end;
end;
end;
SaveToCell;
ModalResult := mrOK;
end;
function TdlgUADSiteView.CountFeatures: Integer;
var
Cntr: Integer;
begin
Cntr := -1;
Result := 0;
repeat
Cntr := Succ(Cntr);
if clbViewFeatures.Checked[Cntr] then
Result := Succ(Result);
until (Result > MaxFeatures) or (Cntr = OtherFeatureIdx);
end;
procedure TdlgUADSiteView.SetOtherDescState(IsEnabled: Boolean);
begin
lblOtherDesc.Enabled := IsEnabled;
edtOtherDesc.Enabled := IsEnabled;
if IsEnabled then
edtOtherDesc.SetFocus;
if not IsEnabled then
edtOtherDesc.Text := '';
end;
function TdlgUADSiteView.GetDescriptionText: String;
var
Cntr, Factors: Integer;
begin
if lbViewAppeal.ItemIndex > -1 then
begin
Result := AppealTitle[lbViewAppeal.ItemIndex];
Factors := 0;
for Cntr := 0 to OtherFeatureIDx do
begin
if clbViewFeatures.Checked[Cntr] then
begin
Factors := Succ(Factors);
if Cntr <> OtherFeatureIDx then
Result := Result + ';' + FeatureTitle[Cntr]
else
begin
if Pos(';', edtOtherDesc.Text) > 0 then
Factors := Succ(Factors);
Result := Result + ';' + Trim(edtOtherDesc.Text);
end;
end;
end;
// if only one factor was selected then add a terminating semicolon
if Factors = 1 then
Result := Result + ';';
end
else
Result := '';
end;
procedure TdlgUADSiteView.Clear;
var
Index: Integer;
begin
edtOtherDesc.Text := '';
lbViewAppeal.ClearSelection;
clbViewFeatures.MultiSelect := True;
clbViewFeatures.ClearSelection;
for Index := 0 to clbViewFeatures.Count - 1 do
clbViewFeatures.Checked[Index] := False;
SetFactorTitle;
end;
procedure TdlgUADSiteView.LoadForm;
var
FeatureIdx, PosItem: Integer;
RatingText, FeatureText: String;
function GetFeatureIdx(FeatureTxt: String): Integer;
var
FeatureCntr, FeatureIdx: Integer;
begin
Result := -1;
if FeatureTxt <> '' then
begin
FeatureCntr := -1;
FeatureIDx := -1;
repeat
FeatureCntr := Succ(FeatureCntr);
if FeatureTxt = FeatureDesc[FeatureCntr] then
FeatureIDx := FeatureCntr;
until (FeatureIDx >= 0) or (FeatureCntr = OtherFeatureIDx);
Result := FeatureIDx;
end;
end;
begin
Clear;
FClearData := False;
RatingText := FCell.Text;
PosItem := Pos(';', RatingText);
if PosItem = 2 then
begin
lbViewAppeal.ItemIndex := AnsiIndexStr(RatingText[1], AppealTitle);
RatingText := Copy(RatingText, 3, Length(RatingText));
end;
//get first checked
if Length(RatingText) > 0 then
begin
PosItem := Pos(';', RatingText);
if PosItem > 0 then
begin
FeatureText := Copy(RatingText, 1, Pred(PosItem));
RatingText := Copy(RatingText, Succ(PosItem), Length(RatingText));
end
else
begin
FeatureText := RatingText;
RatingText := '';
end;
if Length(FeatureText) > 0 then
FeatureIdx := AnsiIndexStr(FeatureText, FeatureTitle)
else
FeatureIdx := -1;
if FeatureIdx > -1 then
clbViewFeatures.Checked[FeatureIdx] := True
else
begin
clbViewFeatures.Checked[OtherFeatureIdx] := True;
edtOtherDesc.Text := FeatureText;
end;
end;
//get second checked
if Length(RatingText) > 0 then
begin
FeatureIdx := AnsiIndexStr(RatingText, FeatureTitle);
if FeatureIdx > -1 then
clbViewFeatures.Checked[FeatureIdx] := True
else
begin
clbViewFeatures.Checked[OtherFeatureIdx] := True;
if Trim(edtOtherDesc.Text) <> '' then
edtOtherDesc.Text := edtOtherDesc.Text + ';' + RatingText
else
edtOtherDesc.Text := RatingText;
end;
end;
end;
procedure TdlgUADSiteView.SaveToCell;
begin
// Remove any legacy data - no longer used
FCell.GSEData := '';
// Save the cleared or formatted text
if FClearData then // clear ALL GSE data and blank the cell
FCell.SetText('')
else
FCell.SetText(GetDescriptionText);
end;
procedure TdlgUADSiteView.bbtnClearClick(Sender: TObject);
begin
if WarnOK2Continue(msgUAGClearDialog) then
begin
Clear;
FClearData := True;
SaveToCell;
ModalResult := mrOK;
end;
end;
procedure TdlgUADSiteView.SetFactorTitle;
var
Cntr, Count: Integer;
begin
Count := 0;
for Cntr := 0 to Pred(clbViewFeatures.Count) do
if clbViewFeatures.Checked[Cntr] then
Count := Succ(Count);
if Count <= 2 then
begin
stFactors.Caption := FactorOK;
stFactors.Color := FactorOKColor;
end
else
begin
stFactors.Caption := FactorErr;
stFactors.Color := FactorErrColor;
end;
stFactors.Refresh;
end;
procedure TdlgUADSiteView.clbViewFeaturesKeyUp(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
SetOtherDescState(clbViewFeatures.Checked[OtherFeatureIdx]); //set Other state
SetFactorTitle;
end;
procedure TdlgUADSiteView.clbViewFeaturesMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
SetOtherDescState(clbViewFeatures.Checked[OtherFeatureIdx]); //set Other state
SetFactorTitle;
end;
end.
|
{***************************************************************************}
{ }
{ DUnitX }
{ }
{ Copyright (C) 2015 Vincent Parrett & Contributors }
{ }
{ vincent@finalbuilder.com }
{ http://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DUnitX.InternalInterfaces;
interface
{$I DUnitX.inc}
uses
{$IFDEF USE_NS}
System.TimeSpan,
{$ELSE}
TimeSpan,
{$ENDIF}
DUnitX.Types,
DUnitX.Generics,
DUnitX.Extensibility,
DUnitX.TestFrameWork;
type
//These interfaces mirror the Info classes in the framework but expose stuff we need for runtime.
ISetTestResult = interface
['{B50D50E9-3609-40BF-847D-53B5BF19B5C7}']
procedure SetResult(const value : ITestResult);
end;
//Used by the TestExecute method.
ITestExecuteContext = interface
['{DE4ADB3F-3B5B-4B90-8659-0BFA578977CC}']
procedure RecordFixture(const fixtureResult : IFixtureResult);
procedure RecordResult(const fixtureResult : IFixtureResult; const testResult : ITestResult);
procedure RollupResults;
end;
ITestFixtureContext = interface
['{C3B85C73-1FE8-4558-8AB0-7E8075821D35}']
end;
ITestExecute = interface
['{C59443A9-8C7D-46CE-83A1-E40309A1B384}']
procedure Execute(const context : ITestExecuteContext);
procedure UpdateInstance(const fixtureInstance : TObject);
end;
ITestCaseExecute = interface(ITestExecute)
['{49781E22-C127-4BED-A9D5-84F9AAACE96C}']
function GetCaseName : string;
end;
IFixtureResultBuilder = interface
['{2604E655-349D-4379-9796-1C708CAD7307}']
procedure AddTestResult(const AResult : ITestResult);
procedure AddChild(const AFixtureResult : IFixtureResult);
procedure RollUpResults;
// function Combine(const AFixtureResult : IFixtureResult) : IFixtureResult;
// function AreEqual(const AFixtureResult : IFixtureResult) : boolean;
end;
implementation
end.
|
unit uAulasDadasAluno;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, JvExControls, JvXPCore, JvXPButtons, DB, kbmMemTable, Grids, DBGrids, uFramePeriodo, uFrameAluno, StdCtrls, ExtCtrls, ZAbstractRODataset,
ZAbstractDataset, ZDataset;
type
TfrmAulasDadasAluno = class(TForm)
Panel1: TPanel;
btConfirmar: TJvXPButton;
btCancelar: TJvXPButton;
btFechar: TJvXPButton;
Panel2: TPanel;
btCarregar: TJvXPButton;
fraPeriodo: TframePeriodo;
dbgAulas: TDBGrid;
tblAulasDadas: TkbmMemTable;
tblAulasDadasCodDisciplina: TStringField;
tblAulasDadasNomeDisciplina: TStringField;
tblAulasDadasFaltas: TIntegerField;
tblAulasDadasAulasDadas: TIntegerField;
dsAulasDadas: TDataSource;
sqlDisciplina1: TZQuery;
sqlDisciplina1Codigo: TStringField;
sqlDisciplina1Nome: TStringField;
sqlDisciplina1Tipo: TStringField;
sqlDisciplina1Suple: TSmallintField;
sqlDisciplina1Sigla: TStringField;
sqlDisciplina1Reprova: TSmallintField;
sqlDisciplina1Historico: TSmallintField;
sqlDisciplina1AnoLetivo: TStringField;
sqlDisciplina1TipoComposicao: TStringField;
sqlDisciplina1DisciplinaPai: TStringField;
sqlDisciplina1CalculoComp: TStringField;
sqlDisciplina1Cor: TStringField;
fraAluno: TframeAluno;
procedure fraAlunobtBuscaAlunoClick(Sender: TObject);
procedure tblAulasDadasBeforeDelete(DataSet: TDataSet);
procedure tblAulasDadasBeforeInsert(DataSet: TDataSet);
procedure btCancelarClick(Sender: TObject);
procedure btFecharClick(Sender: TObject);
procedure btConfirmarClick(Sender: TObject);
procedure btCarregarClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
FEditando: Boolean;
BloqueiaInclusao : Boolean;
procedure SetEditando(const Value: Boolean);
procedure CarregarAulas(Matricula: String; Bimestre : Integer);
procedure GravarAulas(Matricula: String; Bimestre : Integer);
{ Private declarations }
public
{ Public declarations }
property Editando : Boolean read FEditando write SetEditando;
end;
var
frmAulasDadasAluno: TfrmAulasDadasAluno;
implementation
uses uDMPrincipal, Processo;
{$R *.dfm}
{ TForm1 }
procedure TfrmAulasDadasAluno.btCancelarClick(Sender: TObject);
begin
Editando := False;
end;
procedure TfrmAulasDadasAluno.btCarregarClick(Sender: TObject);
begin
if not fraAluno.CodigoValido then
begin
MessageBox(handle, 'Informe um aluno válido', 'Atenção!', MB_ICONERROR);
fraAluno.edMatricula.SetFocus;
end
else if fraPeriodo.Periodo <= 0 then
begin
MessageBox(handle, PAnsiChar('Escolha um ' + DMPrincipal.Letivo.NomePeriodo), 'Atenção!', MB_ICONERROR);
fraPeriodo.cbPeriodo.SetFocus;
end
else
begin
CarregarAulas(fraAluno.Matricula, fraPeriodo.Periodo);
Editando := True;
end;
end;
procedure TfrmAulasDadasAluno.btConfirmarClick(Sender: TObject);
begin
GravarAulas(fraAluno.Matricula, fraPeriodo.Periodo);
Editando := False;
DMPrincipal.Espiao.RegistraLog(frmAulasDadasAluno.caption, 'Altera','Aluno: '+fraAluno.Matricula );
end;
procedure TfrmAulasDadasAluno.btFecharClick(Sender: TObject);
begin
Close;
end;
procedure TfrmAulasDadasAluno.CarregarAulas(Matricula: String; Bimestre: Integer);
var
CodClasse : String;
begin
CriaProcesso('Carregando Aulas e faltas');
try
with DMPrincipal do
begin
CodClasse := ClasseAtual(vUser.AnoLetivo, Matricula);
OpenSQL(sqlClasses, 'SELECT * '+
'FROM Classe1 '+
'WHERE idClasse1 = ' + QuotedStr(CodClasse) +
' AND AnoLetivo = ' + QuotedStr(vUser.AnoLetivo) );
OpenSQL(Self.sqlDisciplina1, 'SELECT * '+
'FROM Disciplina1 '+
'WHERE AnoLetivo = ' + QuotedStr(vUser.AnoLetivo) +
'AND Codigo IN ( SELECT Disciplina '+
' FROM Disciplina2 '+
' WHERE AnoLetivo = ' + QuotedStr(vUser.AnoLetivo) +
' AND Curso = ' + QuotedStr(sqlClassesidCursos.Value) +
' AND Serie = ' + QuotedStr(sqlClassesSerie.Value) +
' ) '+
'ORDER BY Nome ');
OpenSQL(sqlNotasFaltas, 'SELECT * '+
'FROM NotasFaltas '+
'WHERE AnoLetivo = ' + QuotedStr(vUser.AnoLetivo) +
' AND Mat = ' + QuotedStr(Matricula) +
' AND Bim = ' + QuotedStr(IntToStr(Bimestre)) );
OpenSQL(sqlAulasDadasAluno, 'SELECT * '+
'FROM AulasDadasAluno '+
'WHERE AnoLetivo = ' + QuotedStr(vUser.AnoLetivo) +
' AND Mat = ' + QuotedStr(Matricula) +
' AND Bimestre = ' + QuotedStr(IntToStr(Bimestre)) );
BloqueiaInclusao := False;
tblAulasDadas.Close;
tblAulasDadas.Open;
while not Self.sqlDisciplina1.Eof do
begin
tblAulasDadas.Append;
tblAulasDadasCodDisciplina.Value := Self.sqlDisciplina1Codigo.Value;
tblAulasDadasNomeDisciplina.Value := Self.sqlDisciplina1Nome.Value;
if sqlNotasFaltas.Locate('Disc', Self.sqlDisciplina1Codigo.Value, []) then
tblAulasDadasFaltas.Assign(sqlNotasFaltasFalta);
if sqlAulasDadasAluno.Locate('Disciplina', Self.sqlDisciplina1Codigo.Value, []) then
tblAulasDadasAulasDadas.Assign(sqlAulasDadasAlunoAulasDadas);
tblAulasDadas.Post;
Self.sqlDisciplina1.Next;
end;
BloqueiaInclusao := True;
end;
finally
FechaProcesso;
end;
end;
procedure TfrmAulasDadasAluno.FormCreate(Sender: TObject);
begin
Editando := False;
BloqueiaInclusao := True;
end;
procedure TfrmAulasDadasAluno.FormShow(Sender: TObject);
begin
fraAluno.edMatricula.SetFocus;
end;
procedure TfrmAulasDadasAluno.fraAlunobtBuscaAlunoClick(Sender: TObject);
begin
fraAluno.btBuscaAlunoClick(Sender);
fraPeriodo.CarregaPeriodos;
end;
procedure TfrmAulasDadasAluno.GravarAulas(Matricula: String; Bimestre: Integer);
var
CodClasse, disc : String;
begin
CriaProcesso('Carregando Aulas e faltas');
try
with DMPrincipal do
begin
CodClasse := ClasseAtual(vUser.AnoLetivo, Matricula);
OpenSQL(sqlClasses, 'SELECT * FROM Classe1 WHERE idClasse1 = ' + QuotedStr(CodClasse) );
OpenSQL(sqlNotasFaltas, 'SELECT * '+
'FROM NotasFaltas '+
'WHERE AnoLetivo = ' + QuotedStr(vUser.AnoLetivo) +
' AND Mat = ' + QuotedStr(Matricula) +
' AND Bim = ' + QuotedStr(IntToStr(Bimestre)) );
OpenSQL(sqlAulasDadasAluno, 'SELECT * '+
'FROM AulasDadasAluno '+
'WHERE AnoLetivo = ' + QuotedStr(vUser.AnoLetivo) +
' AND Mat = ' + QuotedStr(Matricula) +
' AND Bimestre = ' + QuotedStr(IntToStr(Bimestre)) );
tblAulasDadas.First;
while not tblAulasDadas.Eof do
begin
Disc := tblAulasDadasCodDisciplina.Value;
// Atualiza as faltas
if not sqlNotasFaltas.Locate('Disc', Disc, []) then
begin
sqlNotasFaltas.Insert;
sqlNotasFaltasAnoLetivo.Value := vUser.AnoLetivo;
sqlNotasFaltasMat.Value := Matricula;
sqlNotasFaltasBim.Value := IntToStr(Bimestre);
sqlNotasFaltasDisc.Value := Disc;
end
else
sqlNotasFaltas.Edit;
if tblAulasDadasFaltas.Value = 0 then
sqlNotasFaltasFalta.Clear
else
sqlNotasFaltasFalta.Value := tblAulasDadasFaltas.Value;
sqlNotasFaltas.Post;
// Atualiza as aulas dadas
if tblAulasDadasAulasDadas.IsNull then
begin
if sqlAulasDadasAluno.Locate('Disciplina', Disc, []) then
sqlAulasDadasAluno.Delete;
end
else
begin
if sqlAulasDadasAluno.Locate('Disciplina', Disc, []) then
sqlAulasDadasAluno.Edit
else
begin
sqlAulasDadasAluno.Insert;
sqlAulasDadasAlunoAnoLetivo.Value := vUser.AnoLetivo;
sqlAulasDadasAlunoMat.Value := Matricula;
sqlAulasDadasAlunobimestre.Value := IntToStr(Bimestre);
sqlAulasDadasAlunodisciplina.Value := disc;
end;
sqlAulasDadasAlunoAulasDadas.Value := tblAulasDadasAulasDadas.Value;
sqlAulasDadasAluno.Post;
end;
tblAulasDadas.Next;
end;
end;
finally
DMPrincipal.sqlAulasDadas.Close;
DMPrincipal.sqlNotasFaltas.Close;
FechaProcesso;
end;
end;
procedure TfrmAulasDadasAluno.SetEditando(const Value: Boolean);
begin
FEditando := Value;
fraAluno.Ativo := not FEditando;
fraPeriodo.Enabled := not FEditando;
btCarregar.Enabled := not FEditando;
dbgAulas.Enabled := FEditando;
if not FEditando then
tblAulasDadas.Close;
btConfirmar.Enabled := FEditando;
btCancelar.Enabled := FEditando;
btFechar.Enabled := not FEditando;
end;
procedure TfrmAulasDadasAluno.tblAulasDadasBeforeDelete(DataSet: TDataSet);
begin
if BloqueiaInclusao then
Abort;
end;
procedure TfrmAulasDadasAluno.tblAulasDadasBeforeInsert(DataSet: TDataSet);
begin
if BloqueiaInclusao then
Abort;
end;
end.
|
PROGRAM StudentSearch;
TYPE DateType = RECORD
day: 1..31;
month: 1..12;
year: WORD;
END;
TYPE StudentType = RECORD
first_name: STRING[30];
last_name: STRING[50];
matriculation_number: LONGINT;
date_of_birth: DateType;
END;
FUNCTION CreateStudent(firstName, lastName: STRING; matrNumber: LONGINT;
VAR sList: ARRAY OF StudentType;
VAR sc: WORD): BOOLEAN;
BEGIN
IF sc <= High(sList) THEN BEGIN
WITH sList[sc] DO BEGIN
first_name := firstName;
last_name := lastName;
matriculation_number := matrNumber;
END;
sc := sc + 1;
CreateStudent := TRUE;
END
ELSE BEGIN
CreateStudent := FALSE;
END;
END;
PROCEDURE WriteStudent(VAR student_to_print: StudentType);
BEGIN
WriteLn('Name: ', student_to_print.first_name, ' ', student_to_print.last_name);
WriteLn('M#: ', student_to_print.matriculation_number);
WriteLn('Date of birth: ', student_to_print.date_of_birth.day, '.', student_to_print.date_of_birth.month, '.', student_to_print.date_of_birth.year);
END;
PROCEDURE WriteStudents(VAR students: ARRAY OF StudentType; length : INTEGER);
VAR i: INTEGER;
BEGIN
WriteLn('BEGIN STUDENT LIST');
WriteLn('---');
FOR i := Low(students) TO (length - 1) DO BEGIN
WriteStudent(students[i]);
WriteLn('---');
END;
WriteLn('END STUDENT LIST');
WriteLn('');
END;
FUNCTION ExistsStudent(VAR students: ARRAY OF StudentType; matrNumber: INTEGER; length: INTEGER): BOOLEAN;
VAR i: INTEGER;
BEGIN
i := 0;
WHILE (i < length) AND (students[i].matriculation_number <> matrNumber) DO BEGIN
i := i + 1;
END;
IF i < length THEN BEGIN
ExistsStudent := TRUE;
END
ELSE BEGIN
ExistsStudent := FALSE;
END;
END;
VAR estudiante, estudiante_b: StudentType;
estudiantes: ARRAY [0..2] OF StudentType;
listCount: INTEGER;
BEGIN
estudiante.first_name := 'Johannes';
estudiante.last_name := 'Huber';
estudiante.matriculation_number := 1610307103;
estudiante.date_of_birth.day := 4;
estudiante.date_of_birth.month := 3;
estudiante.date_of_birth.year := 1994;
WITH estudiante_b DO BEGIN
first_name := 'Ricarda';
last_name := 'Mayr';
matriculation_number := 1610307104;
WITH date_of_birth DO BEGIN
day := 18;
month := 6;
year := 1995;
END;
END;
estudiantes[0] := estudiante;
estudiantes[1] := estudiante_b;
listCount := 2;
WriteStudents(estudiantes, listCount);
WriteLn(CreateStudent('Thomas', 'Müller', 85, estudiantes, listCount));
WriteStudents(estudiantes, listCount);
WriteLn(CreateStudent('Heribert', 'Müller', 84, estudiantes, listCount));
WriteStudents(estudiantes, listCount);
WriteLn(ExistsStudent(estudiantes, 85, listCount));
WriteLn(ExistsStudent(estudiantes, 185, listCount));
END. |
Unit WdIUnit;
Interface
type
PRec = ^TRec;
TRec = packed record
Next, Prev: PRec;
case Integer of
0: (I: Int64);
1: (F: Extended);
2: (S: ShortString);
end;
TTab = array of TRec;
TType = Integer;
const
tInt = 0;
tFloat = 1;
tString = 2;
cNotExists : TRec = (Next: nil; Prev: nil; I: -1; F: -1; S: '');
{
Tab -> SetLength(x);
Stack -> Wsk := nil;
Queue -> WskRead := nil; New(WskAdd);
BST -> Wsk := nil;
}
procedure Swap(var A, B: TRec; T: TType);
procedure Losuj(var Tab: TTab; T: TType; Range: Integer; Start: Integer);
procedure Pokaz(var Tab: TTab; T: TType; L: Integer);
procedure QuickSort(var Tab: TTab; T: TType; S, E: Integer); //S -> Start; E -> End;
function Szukaj(var Tab: TTab; V: TRec; T: TType):Integer;
function Min(var Tab: TTab; T: TType): TRec;
function Max(var Tab: TTab; T: TType): TRec;
function NWD(A, B: Integer): Integer;
function Palindrom(S: String): Boolean;
function Odwroc(X: String): String;
function Prefix(S: String; L: Integer): String;
function Surfix(S: String; L: Integer): String;
function X2Str(Rec: TRec; T: TType; L: Integer): TRec;
function Str2X(Rec: TRec; T: TType): TRec;
procedure StackPush(var Wsk: PRec; V: TRec);
function StackPop(var Wsk: PRec): TRec;
procedure QueueAdd(var WskAdd, WskRead: PRec; V: TRec);
function QueueRead(var WskRead: PRec): TRec;
procedure BSTAdd(var Wsk: PRec; V: TRec; T: TType);
procedure BSTInOrder(const Wsk: PRec; T: TType);
procedure BSTPreOrder(const Wsk: PRec; T: TType);
procedure BSTPostOrder(const Wsk: PRec; T: TType);
procedure BSTSearch(var Wsk, Found: PRec; V: TRec; T: TType);
procedure BSTFree(var Wsk: PRec);
implementation
procedure Swap(var A, B: TRec; T: TType);
var
Tmp: TRec;
begin
case T of
tInt:
begin
Tmp.I := A.I;
A.I := B.I;
B.I := Tmp.I;
end;
tFloat:
begin
Tmp.F := A.F;
A.F := B.F;
B.F := Tmp.F;
end;
tString:
begin
Tmp.S := A.S;
A.S := B.S;
B.S := Tmp.S;
end;
end;
end;
procedure Losuj(var Tab: TTab; T: TType; Range: Integer; Start: Integer);
var
i: Integer;
begin
Randomize;
for i := 0 to Length(Tab) - 1 do
begin
case T of
tInt: Tab[i].I := Random(Range) + Start;
tFloat: Tab[i].F := Random * (Range - Start) + Start;
end;
end;
end;
procedure Pokaz(var Tab: TTab; T: TType; L: Integer);
var
i: Integer;
begin
for i := 0 to Length(Tab) - 1 do
case T of
tInt: Writeln(Tab[i].I);
tFloat: Writeln(Tab[i].F:0:L);
tString: Writeln(Tab[i].S);
end;
end;
procedure QuickSort(var Tab: TTab; T: TType; S, E: Integer); //S -> Start; E -> End;
var
i, j: Integer;
X: TRec;
begin
i := S;
j := E;
X := Tab[ (S + E) div 2];
repeat
case T of
tInt:
begin
while Tab[i].I < X.I do Inc(i);
while Tab[j].I > X.I do Dec(j);
end;
tFloat:
begin
while Tab[i].F < X.F do Inc(i);
while Tab[j].F > X.F do Dec(j);
end;
tString:
begin
while Tab[i].S < X.S do Inc(i);
while Tab[j].S > X.S do Dec(j);
end;
end;
if i <= j then
begin
Swap(Tab[i], Tab[j], T);
Inc(i);
Dec(j);
end;
until i > j;
if S < j then
QuickSort(Tab, T, S, j);
if i < E then
QuickSort(Tab, T, i, E);
end;
function Szukaj(var Tab: TTab; V: TRec; T: TType):Integer;
var
S, E, M, W: Integer;
begin
S := -1;
E := Length(Tab) - 1;
W := -1;
while E > S + 1 do
begin
M := (S + E) div 2;
case T of
tInt:
begin
if Tab[M].I <> V.I then
begin
if Tab[M].I < V.I then
S := M
else
E := M;
end
else
begin
W := M;
break;
end;
end;
tFloat:
begin
if Tab[M].F <> V.F then
begin
if Tab[M].F < V.F then
S := M
else
E := M;
end
else
begin
W := M;
break;
end;
end;
end;
end;
Szukaj := W;
end;
function Min(var Tab: TTab; T: TType): TRec;
var
Wynik: TRec;
i: Integer;
begin
case T of
tInt: Wynik.I := High(Int64);
tFloat: Wynik.F := High(Int64);
end;
for i := 0 to Length(Tab) - 1 do
case T of
tInt:
if Tab[i].I < Wynik.I then
Wynik.I := Tab[i].I;
tFloat:
if Tab[i].F < Wynik.F then
Wynik.F := Tab[i].F;
end;
Min := Wynik;
end;
function Max(var Tab: TTab; T: TType): TRec;
var
Wynik: TRec;
i: Integer;
begin
case T of
tInt: Wynik.I := Low(Int64);
tFloat: Wynik.F := Low(Int64);
end;
for i := 0 to Length(Tab) - 1 do
case T of
tInt:
if Tab[i].I > Wynik.I then
Wynik.I := Tab[i].I;
tFloat:
if Tab[i].F > Wynik.F then
Wynik.F := Tab[i].F;
end;
Max := Wynik;
end;
function NWD(A, B: Integer): Integer;
begin
while A <> B do
if A > B then A := A - B
else B := B - A;
NWD := A;
end;
function Palindrom(S: String): Boolean;
var
i: Integer;
Wynik: Boolean;
begin
Wynik := true;
for i := 1 to Length(S) div 2 do
if s[i] <> S[Length(S) - i + 1] then
Wynik := false;
Palindrom := Wynik;
end;
function Odwroc(X: String): String;
var
i: Integer;
c: Char;
begin
for i := 1 to Length(X) div 2 do
begin
c := X[i];
X[i] := X[Length(X) - i + 1];
X[Length(X) - i + 1] := c;
end;
Odwroc := X;
end;
function Prefix(S: String; L: Integer): String;
begin
Prefix := Copy(S, 1, L);
end;
function Surfix(S: String; L: Integer): String;
begin
Surfix := Copy(S, Length(S) - L + 1, L);
end;
function X2Str(Rec: TRec; T: TType; L: Integer): TRec;
var
Wynik: TRec;
begin
case T of
tInt: Str(Rec.I, Wynik.S);
tFloat: Str(Rec.F:0:L, Wynik.S);
end;
X2Str := Wynik;
end;
function Str2X(Rec: TRec; T: TType): TRec;
var
Wynik: TRec;
Code: Integer;
begin
case T of
tInt: Val(Rec.S, Wynik.I, Code);
tFloat: Val(Rec.S, Wynik.F, Code);
end;
if Code = 0 then
Str2X := Wynik;
end;
procedure StackPush(var Wsk: PRec; V: TRec);
var
Nowy: PRec;
begin
New(Nowy);
Nowy^ := V;
Nowy^.Next := Wsk;
Wsk := Nowy;
end;
function StackPop(var Wsk: PRec): TRec;
var
Buf: PRec;
begin
if Wsk <> nil then
begin
StackPop := Wsk^;
Buf := Wsk;
Wsk := Wsk^.Next;
Dispose(Buf);
end
else
StackPop := cNotExists;
end;
procedure QueueAdd(var WskAdd, WskRead: PRec; V: TRec);
var
Nowy: PRec;
begin
New(Nowy);
Nowy^ := V;
WskAdd^.Next := Nowy;
WskAdd := Nowy;
if WskRead = nil then
WskRead := WskAdd;
end;
function QueueRead(var WskRead: PRec): TRec;
var
Buf: PRec;
begin
if WskRead <> nil then
begin
QueueRead := WskRead^;
Buf := WskRead;
WskRead := WskRead^.Next;
Dispose(Buf);
end
else
QueueRead := cNotExists;
end;
procedure BSTAdd(var Wsk: PRec; V: TRec; T: TType);
begin
if Wsk = nil then
begin
New(Wsk);
Wsk^ := V;
Wsk^.Prev := nil;
Wsk^.Next := nil;
end
else
begin
case T of
tInt:
if V.I > Wsk^.I then
BSTAdd(Wsk^.Next, V, T)
else
BSTAdd(Wsk^.Prev, V, T);
tFloat:
if V.F > Wsk^.F then
BSTAdd(Wsk^.Next, V, T)
else
BSTAdd(Wsk^.Prev, V, T);
end;
end;
end;
procedure BSTInOrder(const Wsk: PRec; T: TType);
begin
if Wsk <> nil then
begin
BSTInOrder(Wsk^.Prev, T);
case T of
tInt: Write(Wsk^.I, ' ');
tFloat: Write(Wsk^.F, ' ');
end;
BSTInOrder(Wsk^.Next, T);
end;
end;
procedure BSTPreOrder(const Wsk: PRec; T: TType);
begin
if Wsk <> nil then
begin
case T of
tInt: Write(Wsk^.I, ' ');
tFloat: Write(Wsk^.F, ' ');
end;
BSTPreOrder(Wsk^.Prev, T);
BSTPreOrder(Wsk^.Next, T);
end;
end;
procedure BSTPostOrder(const Wsk: PRec; T: TType);
begin
if Wsk <> nil then
begin
BSTPostOrder(Wsk^.Prev, T);
BSTPostOrder(Wsk^.Next, T);
case T of
tInt: Write(Wsk^.I, ' ');
tFloat: Write(Wsk^.F, ' ');
end;
end;
end;
procedure BSTSearch(var Wsk, Found: PRec; V: TRec; T: TType);
begin
if Wsk <> nil then
begin
case T of
tInt:
begin
if Wsk^.I <> V.I then
begin
if V.I < Wsk^.I then
BSTSearch(Wsk^.Prev, Found, V, T)
else
BSTSearch(Wsk^.Next, Found, V, T);
end
else
Found := Wsk;
end;
tFloat:
begin
if Wsk^.F <> V.F then
begin
if V.F < Wsk^.F then
BSTSearch(Wsk^.Prev, Found, V, T)
else
BSTSearch(Wsk^.Next, Found, V, T);
end
else
Found := Wsk;
end;
end;
end
else
Found := nil;
end;
procedure BSTFree(var Wsk: PRec);
begin
if Wsk <> nil then
begin
BSTFree(Wsk^.Prev);
BSTFree(Wsk^.Next);
Dispose(Wsk);
Wsk := nil;
end;
end;
end. |
unit Tasks;
interface
function KillTask(ExeFileName: string): integer;
implementation
uses Tlhelp32, Windows, SysUtils, Forms;
function KillTask(ExeFileName: string): integer;
const
PROCESS_TERMINATE=$0001;
var
ContinueLoop: BOOL;
FSnapshotHandle: THandle;
FProcessEntry32: TProcessEntry32;
begin
result := 0;
FSnapshotHandle := CreateToolhelp32Snapshot
(TH32CS_SNAPPROCESS, 0);
FProcessEntry32.dwSize := Sizeof(FProcessEntry32);
ContinueLoop := Process32First(FSnapshotHandle,
FProcessEntry32);
while integer(ContinueLoop) <> 0 do
begin
if ((UpperCase(ExtractFileName(FProcessEntry32.szExeFile)) =
UpperCase(ExeFileName))
or (UpperCase(FProcessEntry32.szExeFile) =
UpperCase(ExeFileName))) then
Result := Integer(TerminateProcess(OpenProcess(
PROCESS_TERMINATE, BOOL(0),
FProcessEntry32.th32ProcessID), 0));
ContinueLoop := Process32Next(FSnapshotHandle,
FProcessEntry32);
end;
CloseHandle(FSnapshotHandle);
end;
end.
|
unit UCRMLicSelectOptions;
{ ClickForms Application }
{ Bradford Technologies, Inc. }
{ All Rights Reserved }
{ Source Code Copyrighted © 2018 by Bradford Technologies, Inc. }
{ This unit displays a dialog to allow the user to Register, Evaluate or }
{ Cancel out of the software. This unit is what calls the Registration unit }
{ with the option to register as PaidLicensee or Evaluator }
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, jpeg,
UStrings, UForms;
const
{Messages to display to user when setting license}
cMsgWelcome = 0; //display when undefined lic
cMsgEvalLic = 1;
cMsgEvalExpired = 2;
cMsgSubcrpEnded = 3;
cMsgGeneralExpired = 4;
cMsgCannotValidate = 5;
type
TCRMSelectWorkOption = class(TAdvancedForm)
btnEvaluate: TButton;
Memo: TMemo;
Background: TImage;
lblCompCopy: TLabel;
btnCancel: TButton;
btnRegister: TButton;
procedure btnRegisterClick(Sender: TObject);
procedure btnEvaluateClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
FInfoNeeded: Boolean;
FCanUse: Boolean;
public
constructor Create(InfoNeeded: Boolean); reintroduce;
procedure SetupMsg(Greeting: String; MsgType, DaysLeft: Integer);
function CanUseSoftware: Boolean;
end;
function SelectHowToWorkOption(Greeting: String; msgTyp, daysLeft: Integer; infoNeeded: Boolean): Boolean;
implementation
uses
UGlobals, UCRMLicUser, UCRMLicRegistration;
{$R *.DFM}
function SelectHowToWorkOption(Greeting: String; msgTyp, daysLeft: Integer; infoNeeded: Boolean): Boolean;
var
SelectMode: TCRMSelectWorkOption;
begin
SelectMode := TCRMSelectWorkOption.Create(InfoNeeded);
try
SelectMode.SetupMsg(Greeting, msgTyp, daysLeft);
SelectMode.ShowModal;
result := SelectMode.CanUseSoftware; //what was result
finally
SelectMode.Free;
end;
end;
{ TSelectWorkOption }
constructor TCRMSelectWorkOption.Create(InfoNeeded: Boolean);
begin
inherited Create(nil);
FInfoNeeded := InfoNeeded;
FCanUse := False;
end;
function TCRMSelectWorkOption.CanUseSoftware: Boolean;
begin
result := FCanUse;
end;
procedure TCRMSelectWorkOption.btnRegisterClick(Sender: TObject);
begin
if RegisterClickFORMSSoftware(Self, CurrentUser, rtPaidLicMode) then
FCanUse := True;
if FCanUse then ModalResult := mrOK;
end;
procedure TCRMSelectWorkOption.btnEvaluateClick(Sender: TObject);
begin
if not FInfoNeeded then //don't ask for name anymore
FCanUse := True
else if RegisterClickFORMSSoftware(Self, CurrentUser, rtEvalLicMode) then
FCanUse := True;
if FCanUse then ModalResult := mrOK;
end;
procedure TCRMSelectWorkOption.btnCancelClick(Sender: TObject);
begin
FCanUse := False;
ModalResult := mrCancel;
end;
procedure TCRMSelectWorkOption.SetupMsg(Greeting: String; MsgType, DaysLeft: Integer);
var
msgStr: String;
begin
//case is for handling other types - ClickForms webbased
if Length(Greeting)>0 then
Caption := 'Welcome to ClickFORMS '+ Greeting
else
Caption := 'Welcome to ClickFORMS';
case MsgType of
cMsgWelcome: //displayed when user license is UNDEFINED
begin
lblCompCopy.Caption := msgClickFORMSInitialWelcome; //'Welcome to ClickFORMS';
memo.lines.Text := msgClickFORMSInitialMeno; // chr(13) + chr(13)
end;
cMsgEvalLic:
begin
if DaysLeft > 1 then
msgStr := 'Evalution Period Expires in '+ IntToStr(DaysLeft) + ' Days'
else if DaysLeft = 1 then
msgStr := 'Evalution Period Expires in '+ IntToStr(DaysLeft) + ' Day';
lblCompCopy.Caption := msgStr;
Memo.Lines.Text := msgSoftwareInEvalMode;
// Memo.Lines.Text := msgClickFORMSThx4Evaluating; // + chr(13)+ chr(13)
end;
cMsgEvalExpired:
begin
lblCompCopy.Caption := msgClickFORMSEvalExpiredTitle;
Memo.Lines.Text := msgClickFORMSEvalExpired;
btnEvaluate.Enabled := False;
AppForceQuit:= true;
end;
cMsgSubcrpEnded: //subscription ended
begin
lblCompCopy.Caption := 'Your ClickFORMS Subscription Has Expired';
Memo.Lines.Text := msgClickFORMSSubcripExpired;
btnEvaluate.Enabled := False;
end;
cMsgGeneralExpired: //we may not use this
begin
lblCompCopy.Caption := 'Your ClickFORMS License Has Expired';
Memo.Lines.Text := msgClickFORMSGeneralExpired;
btnEvaluate.Enabled := False;
end;
cMsgCannotValidate: //cannot Validate subscription because connection
begin
lblCompCopy.Caption := 'ClickForms cannot validate your Subscription';
Memo.Lines.Text := msgClickFORMSCanntValidate;
btnEvaluate.Enabled := False;
end;
end;
end;
procedure TCRMSelectWorkOption.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Key = VK_F4)then Key := 0; // Cancel Alt + F4 to close the from.
end;
end.
|
unit u_TimeZoneDiffByLonLatStuped;
interface
uses
Classes,
t_GeoTypes,
i_VectorItemLonLat,
i_VectorItmesFactory,
i_DoublePointsAggregator,
i_TimeZoneList,
i_TimeZoneDiffByLonLat;
type
PSmallIntPoint = ^TSmallIntPoint;
TSmallIntPoint = packed record
X: Smallint;
Y: Smallint;
end;
ITimeZonePointCheck = interface(ITimeZone)
['{8C51B27B-1257-4A55-AA03-C8041027A090}']
function IsPointFromThis(const ALonLat: TDoublePoint): Boolean;
end;
TTimeZone = class(TInterfacedObject, ITimeZone, ITimeZonePointCheck)
private
FDiff: TDateTime;
FPolygon: ILonLatPolygon;
function IsPointFromPolygonLine(
const ALine: ILonLatPolygonLine;
const ALonLat: TDoublePoint
): Boolean;
protected
function GetDiff: TDateTime;
function GetPolygon: ILonLatPolygon;
protected
function IsPointFromThis(const ALonLat: TDoublePoint): Boolean;
public
constructor Create(
const ADiffInHour: Double;
const APolygon: ILonLatPolygon
);
end;
TTimeZoneDiffByLonLatStuped = class(TInterfacedObject, ITimeZoneList, ITimeZoneDiffByLonLat)
private
FTimeZoneList: IInterfaceList;
procedure AddFromSmallIntArray(
const AAggregator: IDoublePointsAggregator;
ASmallIntPolygon: PSmallIntPoint;
ALength: Integer
);
protected
function GetCount: Integer;
function GetItem(AIndex: Integer): ITimeZone;
protected
function GetTimeDiff(const ALonLat: TDoublePoint): TDateTime;
public
constructor Create(const AVectorFactory: IVectorItmesFactory);
end;
implementation
uses
c_TimeZones,
i_EnumDoublePoint,
u_GeoFun,
u_DoublePointsAggregator;
{ TTimeZone }
constructor TTimeZone.Create(
const ADiffInHour: Double;
const APolygon: ILonLatPolygon
);
begin
inherited Create;
FDiff := ADiffInHour / 24;
FPolygon := APolygon;
end;
function TTimeZone.GetDiff: TDateTime;
begin
Result := FDiff;
end;
function TTimeZone.GetPolygon: ILonLatPolygon;
begin
Result := FPolygon;
end;
function TTimeZone.IsPointFromPolygonLine(
const ALine: ILonLatPolygonLine;
const ALonLat: TDoublePoint
): Boolean;
var
VEnum: IEnumDoublePoint;
VPrevPoint: TDoublePoint;
VCurrPoint: TDoublePoint;
begin
result := false;
if ALine.Bounds.IsPointInRect(ALonLat) then begin
VEnum := ALine.GetEnum;
if VEnum.Next(VPrevPoint) then begin
while VEnum.Next(VCurrPoint) do begin
if (((VCurrPoint.y <= ALonLat.y) and (ALonLat.y < VPrevPoint.y)) or
((VPrevPoint.y <= ALonLat.y) and (ALonLat.y < VCurrPoint.y))) and
(ALonLat.x > (VPrevPoint.x - VCurrPoint.x) * (ALonLat.y - VCurrPoint.y) / (VPrevPoint.y - VCurrPoint.y) + VCurrPoint.x) then begin
Result := not (Result);
end;
VPrevPoint := VCurrPoint;
end;
end;
end;
end;
function TTimeZone.IsPointFromThis(const ALonLat: TDoublePoint): Boolean;
var
i: Integer;
VArea: ILonLatPolygonLine;
begin
Result := False;
if FPolygon.Bounds.IsPointInRect(ALonLat) then begin
for i := 0 to FPolygon.Count - 1 do begin
VArea := FPolygon.Item[i];
if IsPointFromPolygonLine(VArea, ALonLat) then begin
Result := True;
Break;
end;
end;
end;
end;
{ TTimeZoneDiffByLonLatStuped }
constructor TTimeZoneDiffByLonLatStuped.Create(const AVectorFactory: IVectorItmesFactory);
var
VZone: ITimeZonePointCheck;
VAggregator: IDoublePointsAggregator;
VPolygon: ILonLatPolygon;
begin
inherited Create;
FTimeZoneList := TInterfaceList.Create;
VAggregator := TDoublePointsAggregator.Create;
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_m12, length(timezone_m12));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_m12_1, length(timezone_m12_1));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(-12, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_m11, length(timezone_m11));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_m11_1, length(timezone_m11_1));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_m11_2, length(timezone_m11_2));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(-11, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_m10, length(timezone_m10));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_m10_1, length(timezone_m10_1));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_m10_2, length(timezone_m10_2));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_m10_3, length(timezone_m10_3));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(-10, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_m9d5, length(timezone_m9d5));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(-9.5, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_m9, length(timezone_m9));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_m9_1, length(timezone_m9_1));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(-9, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_m8d5, length(timezone_m8d5));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(-8.5, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_m8, length(timezone_m8));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_m8_1, length(timezone_m8_1));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(-8, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_m7, length(timezone_m7));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(-7, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_m6, length(timezone_m6));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(-6, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_m5, length(timezone_m5));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(-5, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_m3d5, length(timezone_m3d5));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(-3.5, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_m3, length(timezone_m3));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_m3_1, length(timezone_m3_1));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(-3, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_m4, length(timezone_m4));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_m4_1, length(timezone_m4_1));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(-4, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_m2, length(timezone_m2));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_m2_1, length(timezone_m2_1));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(-2, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_m1, length(timezone_m1));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_m1_1, length(timezone_m1_1));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_m1_2, length(timezone_m1_2));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(-1, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_0, length(timezone_0));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_0_1, length(timezone_0_1));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_0_2, length(timezone_0_2));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(0, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_1, length(timezone_1));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(1, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_2, length(timezone_2));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_2_1, length(timezone_2_1));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(2, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_3, length(timezone_3));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_3_1, length(timezone_3_1));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(3, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_3d5, length(timezone_3d5));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(3.5, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_4, length(timezone_4));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_4_1, length(timezone_4_1));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_4_2, length(timezone_4_2));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_4_3, length(timezone_4_3));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_4_4, length(timezone_4_4));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(4, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_4d5, length(timezone_4d5));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(4.5, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_6, length(timezone_6));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_6_1, length(timezone_6_1));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_6_2, length(timezone_6_2));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_6_3, length(timezone_6_3));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_6_4, length(timezone_6_4));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(6, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_5, length(timezone_5));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_5_1, length(timezone_5_1));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(5, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_5d5, length(timezone_5d5));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_5d5_1, length(timezone_5d5_1));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_5d5_2, length(timezone_5d5_2));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(5.5, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_5d75, length(timezone_5d75));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(5.75, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_6d5, length(timezone_6d5));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_6d5_1, length(timezone_6d5_1));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(6.5, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_7, length(timezone_7));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_7_1, length(timezone_7_1));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(7, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_8, length(timezone_8));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_8_1, length(timezone_8_1));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(8, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_9, length(timezone_9));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_9_1, length(timezone_9_1));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_9_2, length(timezone_9_2));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(9, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_9d5, length(timezone_9d5));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_9d5_1, length(timezone_9d5_1));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(9.5, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_10, length(timezone_10));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_10_1, length(timezone_10_1));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_10_2, length(timezone_10_2));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_10_3, length(timezone_10_3));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_10_4, length(timezone_10_4));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_10_5, length(timezone_10_5));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(10, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_10d5, length(timezone_10d5));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_10d5_1, length(timezone_10d5_1));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(10.5, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_11, length(timezone_11));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_11_1, length(timezone_11_1));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_11_2, length(timezone_11_2));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_11_3, length(timezone_11_3));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(11, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_11d5, length(timezone_11d5));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_11d5_1, length(timezone_11d5_1));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(11.5, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_12, length(timezone_12));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_12_1, length(timezone_12_1));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_12_2, length(timezone_12_2));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_12_3, length(timezone_12_3));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_12_4, length(timezone_12_4));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_12_5, length(timezone_12_5));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_12_6, length(timezone_12_6));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(12, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_12d75, length(timezone_12d75));
VAggregator.Add(CEmptyDoublePoint);
AddFromSmallIntArray(VAggregator, @timezone_12d75_1, length(timezone_12d75_1));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(12.75, VPolygon);
FTimeZoneList.Add(VZone);
VAggregator.Clear;
AddFromSmallIntArray(VAggregator, @timezone_13, length(timezone_13));
VPolygon := AVectorFactory.CreateLonLatPolygon(VAggregator.Points, VAggregator.Count);
VZone := TTimeZone.Create(13, VPolygon);
FTimeZoneList.Add(VZone);
end;
procedure TTimeZoneDiffByLonLatStuped.AddFromSmallIntArray(
const AAggregator: IDoublePointsAggregator;
ASmallIntPolygon: PSmallIntPoint;
ALength: Integer
);
var
i: Integer;
VSmallIntPoint: PSmallIntPoint;
VPoint: TDoublePoint;
begin
VSmallIntPoint := ASmallIntPolygon;
for i := 0 to ALength - 1 do begin
VPoint.X := VSmallIntPoint.X / 100;
VPoint.Y := VSmallIntPoint.Y / 100;
AAggregator.Add(VPoint);
Inc(VSmallIntPoint);
end;
end;
function TTimeZoneDiffByLonLatStuped.GetCount: Integer;
begin
Result := FTimeZoneList.Count;
end;
function TTimeZoneDiffByLonLatStuped.GetItem(AIndex: Integer): ITimeZone;
begin
Result := ITimeZone(FTimeZoneList.Items[AIndex]);
end;
function TTimeZoneDiffByLonLatStuped.GetTimeDiff(
const ALonLat: TDoublePoint): TDateTime;
var
i: Integer;
VZone: ITimeZonePointCheck;
begin
Result := 0;
for i := 0 to FTimeZoneList.Count - 1 do begin
VZone := ITimeZonePointCheck(FTimeZoneList.Items[i]);
if VZone.IsPointFromThis(ALonLat) then begin
Result := VZone.Diff;
Break;
end;
end;
end;
end.
|
//WinDu.DirectoryEntry
//
//MIT License
//
//Copyright (c) 2020 ottigeda
//
//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 WinDu.DirectoryEntry;
interface
uses
Generics.Collections,
FMX.Controls,
FMX.Objects,
FMX.Types,
System.SysUtils;
type
////////////////////////////////////////////////////////////////////////////////
TDirectoryEntry = class(TObject)
private
FTotalFileSize: Int64;
FPath: string;
FSubDirs: TObjectList<TDirectoryEntry>;
FParentDir : TDirectoryEntry;
FLevel: Integer;
FNumberOfFiles: Int64;
FPie: TPie;
FOtherControls: TObjectList<TControl>;
FLineControls: TObjectList<TControl>;
function GetTotalSize: Int64;
function GetTotalFiles: Int64;
function GetTotalSizeText: string;
function GetIsLeft: Boolean;
function GetIsRight: Boolean;
function GetDirectory: string;
function GetTotalFolders: Int64;
function GetAngle: Extended;
public
constructor Create(ADirectory : string);
destructor Destroy; override;
property Path : string read FPath write FPath;
property Directory : string read GetDirectory;
property TotalFileSize : Int64 read FTotalFileSize write FTotalFileSize;
property NumberOfFiles : Int64 read FNumberOfFiles write FNumberOfFiles;
property ParentDir : TDirectoryEntry read FParentDir write FParentDir;
property SubDirs : TObjectList<TDirectoryEntry> read FSubDirs;
property TotalSize : Int64 read GetTotalSize;
property TotalSizeText : string read GetTotalSizeText;
property TotalFiles : Int64 read GetTotalFiles;
property TotalFolders : Int64 read GetTotalFolders;
property Level : Integer read FLevel write FLevel;
property Angle : Extended read GetAngle;
property Pie : TPie read FPie write FPie;
property OtherControls : TObjectList<TControl> read FOtherControls;
property LineControls : TObjectList<TControl> read FLineControls;
property IsLeft : Boolean read GetIsLeft;
property IsRight : Boolean read GetIsRight;
end;
////////////////////////////////////////////////////////////////////////////////
implementation
{ TDirectoryEntry }
////////////////////////////////////////////////////////////////////////////////
constructor TDirectoryEntry.Create(ADirectory: string);
begin
FSubDirs := TObjectList<TDirectoryEntry>.Create;
FOtherControls := TObjectList<TControl>.Create;
FLineControls := TObjectList<TControl>.Create;
FPath := ADirectory;
FTotalFileSize := 0;
FNumberOfFiles := 0;
FLevel := 0;
FPie := nil;
end;
////////////////////////////////////////////////////////////////////////////////
destructor TDirectoryEntry.Destroy;
begin
FreeAndNil(FSubDirs);
FreeAndNil(FOtherControls);
FreeAndNil(FLineControls);
FreeAndNil(FPie);
inherited;
end;
////////////////////////////////////////////////////////////////////////////////
function TDirectoryEntry.GetTotalSize: Int64;
var
entry : TDirectoryEntry;
begin
Result := 0;
for entry in FSubDirs do begin
Result := Result + entry.TotalSize;
end;
Result := Result + TotalFileSize;
end;
////////////////////////////////////////////////////////////////////////////////
function TDirectoryEntry.GetTotalSizeText: string;
const
SIZE_CLASS : array[0..6] of string = ('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB');
var
size : Extended;
i : Integer;
begin
size := TotalSize;
i := 0;
while (i < Length(SIZE_CLASS)-1) and (size > 1024) do begin
size := size / 1024;
i := i + 1;
end;
Result := Format('%.2f %s' ,[size, SIZE_CLASS[i]]);
end;
////////////////////////////////////////////////////////////////////////////////
function TDirectoryEntry.GetTotalFiles: Int64;
var
entry : TDirectoryEntry;
begin
Result := 0;
for entry in FSubDirs do begin
Result := Result + entry.TotalFiles;
end;
Result := Result + NumberOfFiles;
end;
////////////////////////////////////////////////////////////////////////////////
function TDirectoryEntry.GetTotalFolders: Int64;
var
entry : TDirectoryEntry;
begin
Result := 0;
for entry in FSubDirs do begin
Result := Result + entry.TotalFolders;
end;
Result := Result + 1;
end;
////////////////////////////////////////////////////////////////////////////////
function TDirectoryEntry.GetAngle: Extended;
begin
Result := 0;
if Assigned(FPie) then begin
Result := FPie.EndAngle - FPie.StartAngle;
end;
end;
////////////////////////////////////////////////////////////////////////////////
function TDirectoryEntry.GetDirectory: string;
var
p : Integer;
begin
Result := ExcludeTrailingPathDelimiter(FPath);
p := Pos(PathDelim, Result);
while p > 0 do begin
Result := Copy(Result, p+1, Length(Result));
p := Pos(PathDelim, Result);
end;
end;
////////////////////////////////////////////////////////////////////////////////
function TDirectoryEntry.GetIsLeft: Boolean;
var
angle : Extended;
begin
Result := False;
if Assigned(FPie) then begin
angle := FPie.StartAngle + (FPie.EndAngle - FPie.StartAngle) / 2;
Result := Cos(angle/180*Pi) <= 0;
end;
end;
////////////////////////////////////////////////////////////////////////////////
function TDirectoryEntry.GetIsRight: Boolean;
var
angle : Extended;
begin
Result := False;
if Assigned(FPie) then begin
angle := (FPie.EndAngle - FPie.StartAngle) / 2;
Result := Cos(angle/180*Pi) >= 0;
end;
end;
////////////////////////////////////////////////////////////////////////////////
end.
|
unit mnDialog;
interface
uses mnSystem, Classes, Dialogs, Windows, Graphics, mnGraphics;
{$IFDEF MN_NODIALOG}
type
{--------------------------------
当项目的预编译定义包含MN_NODIALOG时,mnDialog单元内,除M打头的函数外(表示Mandatory),所有函数都不会弹出对话框,
而是把应弹出的对话框信息存在一个mnTDialogInfo结构里,包括对话框种类和消息。
一般用于单元测试中,在与界面进行交互时,不再需要让用户手工处理对话框。
--------------------------------}
mnTDialogInfo = record
Kind: string;
Msg: string;
end;
var
{--------------------------------
上次弹出的对话框信息,可在单元测试里检验。
--------------------------------}
mnLastDialogInfo: mnTDialogInfo;
{$ENDIF}
{--------------------------------
显示一个提示框,内容为Msg,标题为Title。
若未指定标题,则缺省为应用程序的标题。
Tested in TestUnit and TestApp.
--------------------------------}
procedure mnInfoBox(const Msg: string; const Title: string = ''); overload;
procedure mnInfoBox(const Msg: Integer; const Title: string = ''); overload;
procedure mnInfoBox(const Msg: Extended; const Title: string = ''); overload;
procedure mnInfoBox(const Msg: Boolean; const Title: string = ''); overload;
procedure mnInfoBoxDT(const Msg: TDateTime; const Title: string = '');
procedure mnInfoBoxVar(const Msg: Variant; const Title: string = '');
{--------------------------------
强制性地显示一个提示框,内容为Msg,标题为Title。
若未指定标题,则缺省为应用程序的标题。
和mnInfoBox系列函数的功能相同,但不受预编译定义MN_NODIALOG的影响。
Tested in TestApp.
--------------------------------}
procedure mnMInfoBox(const Msg: string; const Title: string = ''); overload;
procedure mnMInfoBox(const Msg: Integer; const Title: string = ''); overload;
procedure mnMInfoBox(const Msg: Extended; const Title: string = ''); overload;
procedure mnMInfoBox(const Msg: Boolean; const Title: string = ''); overload;
procedure mnMInfoBoxDT(const Msg: TDateTime; const Title: string = '');
procedure mnMInfoBoxVar(const Msg: Variant; const Title: string = '');
{--------------------------------
显示一个错误框,内容为Msg,标题为Title。
若未指定标题,则缺省为应用程序的标题。
Tested in TestUnit and TestApp.
--------------------------------}
procedure mnErrorBox(const Msg: string; const Title: string = '');
{--------------------------------
显示一个警告框,内容为Msg,标题为Title。
若未指定标题,则缺省为应用程序的标题。
Tested in TestUnit and TestApp.
--------------------------------}
procedure mnWarningBox(const Msg: string; const Title: string = '');
{--------------------------------
显示一个带Yes和No两个按钮的警告框,内容为Msg,标题为Title。
用户点击Yes返回True,点击No返回False。
若未指定标题,则缺省为应用程序的标题。
Tested in TestUnit and TestApp.
--------------------------------}
function mnWarningBoxEx(const Msg: string; const Title: string = ''): Boolean;
{--------------------------------
显示一个带Yes和No两个按钮的确认框,内容为Msg,标题为Title。
用户点击Yes返回True,点击No返回False。
若未指定标题,则缺省为应用程序的标题。
Tested in TestUnit and TestApp.
--------------------------------}
function mnConfirmBox(const Msg: string; const Title: string = ''): Boolean;
{--------------------------------
显示一个带Yes、No和Cancel三个按钮的确认框,内容为Msg,标题为Title。
用户点击Yes返回IDYES,点击No返回IDNO,点击Cancel返回IDCANCEL。
若未指定标题,则缺省为应用程序的标题。
Tested in TestUnit and TestApp.
--------------------------------}
function mnConfirmBoxEx(const Msg: string; const Title: string = ''): Integer;
{--------------------------------
根据实际值和期望值是否一致,显示提示框或错误框。
若未指定标题,则缺省为应用程序的标题。
Tested in TestUnit and TestApp.
--------------------------------}
procedure mnShouldBeBox(const Actual, Expected: string; const Title: string = ''); overload;
procedure mnShouldBeBox(const Actual, Expected: Integer; const Title: string = ''); overload;
procedure mnShouldBeBox(const Actual, Expected: Extended; const Title: string = ''); overload;
procedure mnShouldBeBox(const Actual, Expected: Boolean; const Title: string = ''); overload;
procedure mnShouldBeBoxDT(const Actual, Expected: TDateTime; const Title: string = '');
{--------------------------------
显示一个多行文本框,内容为Msg,标题为Title。
若未指定标题,则缺省为应用程序的标题。
CanSave表示是否有保存按钮,可以将文本框内容保存到文件。
Tested in TestUnit and TestApp.
--------------------------------}
procedure mnMemoBox(const Msg: string; const Title: string = ''; const CanSave: Boolean = False);
{--------------------------------
强制性地显示一个多行文本框,内容为Msg,标题为Title。
若未指定标题,则缺省为应用程序的标题。
CanSave表示是否有保存按钮,可以将文本框内容保存到文件。
和mnMemoBox函数的功能相同,但不受预编译定义MN_NODIALOG的影响。
Tested in TestApp.
--------------------------------}
procedure mnMMemoBox(const Msg: string; const Title: string = ''; const CanSave: Boolean = False);
{--------------------------------
显示一个图片对话框,内容为BMP或PixeledImage,标题为Title。
若未指定标题,则缺省为应用程序的标题。
另有确定和取消按钮。
返回用户是否确认了对话框,即对话框是否返回mrOK。
Tested in TestApp.
--------------------------------}
function mnImageBox(BMP: TBitmap; const Title: string = ''): Boolean; overload;
function mnImageBox(PixeledImage: mnTPixeledImage; const Title: string = ''): Boolean; overload;
{--------------------------------
显示一个对话框,上面有一个编辑框供用户输入。
Title是对话框的标题,Prompt是对话框上提示用户输入的内容,Default是编辑框初始的缺省值。
返回用户是否确认了对话框,即对话框是否返回mrOK。如果是,Value将存储编辑框的值。
可以指定对用户输入的约束,和未满足约束时的错误信息。
Tested in TestUnit and TestApp.
--------------------------------}
function mnEditDialog(const Title, Prompt, Default: string; var Value: string;
const EditConstraint: mnTStrConstraint = scAny; const ErrorMsg: string = ''): Boolean;
{--------------------------------
显示一个对话框,上面有一个ComboBox供用户选择。
Title是对话框的标题,Prompt是对话框上提示用户选择的内容,ComboItems是ComboBox的选项。
返回用户是否确认了对话框,即对话框是否返回mrOK。如果是,SelectedIndex将存储ComboBox的被选项索引。
可以通过预先对SelectedIndex赋值,来决定ComboBox缺省选中的项目。如果SelectedIndex越界,则缺省选中第0项。
Tested in TestUnit and TestApp.
--------------------------------}
function mnComboBoxDialog(const Title, Prompt: string; ComboItems: TStrings; var SelectedIndex: Integer): Boolean;
{--------------------------------
显示一个对话框,上面有一个CheckListBox供用户勾选。
Title是对话框的标题,Prompt是对话框上提示用户勾选的内容,CheckItems是CheckListBox的选项。
返回用户是否确认了对话框,即对话框是否返回mrOK。如果是,CheckedResult将存储CheckListBox的每一项是否被勾选的结果。
注意:可以通过预先对CheckedResult赋值,来决定CheckListBox中缺省勾选上的项目。
这时,CheckedResult的个数,必须不小于CheckItems的个数。
如果CheckedResult个数为0,表示所有项缺省都未勾选上。
Tested in TestUnit and TestApp.
--------------------------------}
function mnCheckListBoxDialog(const Title, Prompt: string; CheckItems: TStrings; CheckedResult: mnTBoolList): Boolean;
type
{--------------------------------
标准OpenDialog和SaveDialog的预定义的各种文件类型的Filter,可以快捷设置。
--------------------------------}
mnTDialogFilter = (dfAll, dfText, dfExcel, dfWord, dfXML);
{--------------------------------
快捷设置OpenDialog和SaveDialog的Filter。
Tested in TestApp.
--------------------------------}
procedure mnSetOpenDialogFilter(OpenDialog: TOpenDialog; const DialogFilter: mnTDialogFilter);
procedure mnSetSaveDialogFilter(SaveDialog: TSaveDialog; const DialogFilter: mnTDialogFilter);
implementation
uses SysUtils, Variants, Forms, mnResStrsU, StdCtrls, mnWindows,
cxTextEdit, cxButtons, mnForm, Controls, cxDropDownEdit, mnControl,
cxCheckListBox, mnFile, ExtCtrls;
procedure mnInfoBox(const Msg: string; const Title: string = ''); overload;
begin
{$IFDEF MN_NODIALOG}
mnLastDialogInfo.Kind := 'mnInfoBox';
mnLastDialogInfo.Msg := Msg;
{$ELSE}
mnMInfoBox(Msg, Title);
{$ENDIF}
end;
procedure mnInfoBox(const Msg: Integer; const Title: string = ''); overload;
begin
mnInfoBox(IntToStr(Msg), Title);
end;
procedure mnInfoBox(const Msg: Extended; const Title: string = ''); overload;
begin
mnInfoBox(FloatToStr(Msg), Title);
end;
procedure mnInfoBox(const Msg: Boolean; const Title: string = ''); overload;
begin
mnInfoBox(mnBoolToStr(Msg), Title);
end;
procedure mnInfoBoxDT(const Msg: TDateTime; const Title: string = '');
begin
mnInfoBox(DateTimeToStr(Msg), Title);
end;
procedure mnInfoBoxVar(const Msg: Variant; const Title: string = '');
begin
mnInfoBox(VarToStr(Msg), Title);
end;
procedure mnMInfoBox(const Msg: string; const Title: string = ''); overload;
begin
Application.MessageBox(PChar(Msg), PChar(mnChooseStr(Title = '', Application.Title, Title)), MB_ICONINFORMATION);
end;
procedure mnMInfoBox(const Msg: Integer; const Title: string = ''); overload;
begin
mnMInfoBox(IntToStr(Msg), Title);
end;
procedure mnMInfoBox(const Msg: Extended; const Title: string = ''); overload;
begin
mnMInfoBox(FloatToStr(Msg), Title);
end;
procedure mnMInfoBox(const Msg: Boolean; const Title: string = ''); overload;
begin
mnMInfoBox(BoolToStr(Msg, True), Title);
end;
procedure mnMInfoBoxDT(const Msg: TDateTime; const Title: string = '');
begin
mnMInfoBox(DateTimeToStr(Msg), Title);
end;
procedure mnMInfoBoxVar(const Msg: Variant; const Title: string = '');
begin
mnMInfoBox(VarToStr(Msg), Title);
end;
procedure mnErrorBox(const Msg: string; const Title: string = '');
begin
{$IFDEF MN_NODIALOG}
mnLastDialogInfo.Kind := 'mnErrorBox';
mnLastDialogInfo.Msg := Msg;
{$ELSE}
Application.MessageBox(PChar(Msg), PChar(mnChooseStr(Title = '', Application.Title, Title)), MB_ICONERROR);
{$ENDIF}
end;
procedure mnWarningBox(const Msg: string; const Title: string = '');
begin
{$IFDEF MN_NODIALOG}
mnLastDialogInfo.Kind := 'mnWarningBox';
mnLastDialogInfo.Msg := Msg;
{$ELSE}
Application.MessageBox(PChar(Msg), PChar(mnChooseStr(Title = '', Application.Title, Title)), MB_ICONWARNING);
{$ENDIF}
end;
function mnWarningBoxEx(const Msg: string; const Title: string = ''): Boolean;
begin
{$IFDEF MN_NODIALOG}
mnLastDialogInfo.Kind := 'mnWarningBoxEx';
mnLastDialogInfo.Msg := Msg;
Result := True;
{$ELSE}
Result := Application.MessageBox(PChar(Msg), PChar(mnChooseStr(Title = '', Application.Title, Title)), MB_ICONWARNING or MB_YESNO) = IDYES;
{$ENDIF}
end;
function mnConfirmBox(const Msg: string; const Title: string = ''): Boolean;
begin
{$IFDEF MN_NODIALOG}
mnLastDialogInfo.Kind := 'mnConfirmBox';
mnLastDialogInfo.Msg := Msg;
Result := True;
{$ELSE}
Result := Application.MessageBox(PChar(Msg), PChar(mnChooseStr(Title = '', Application.Title, Title)), MB_ICONQUESTION or MB_YESNO) = IDYES;
{$ENDIF}
end;
function mnConfirmBoxEx(const Msg: string; const Title: string = ''): Integer;
begin
{$IFDEF MN_NODIALOG}
mnLastDialogInfo.Kind := 'mnConfirmBoxEx';
mnLastDialogInfo.Msg := Msg;
Result := IDYES;
{$ELSE}
Result := Application.MessageBox(PChar(Msg), PChar(mnChooseStr(Title = '', Application.Title, Title)), MB_ICONQUESTION or MB_YESNOCANCEL);
{$ENDIF}
end;
procedure mnShouldBeBox(const Actual, Expected: string; const Title: string = ''); overload;
begin
if Actual = Expected then
mnInfoBox(Format(SShouldBeCorrect, [Actual]), Title)
else
mnErrorBox(Format(SShouldBeWrong, [Actual, Expected]), Title);
end;
procedure mnShouldBeBox(const Actual, Expected: Integer; const Title: string = ''); overload;
begin
if Actual = Expected then
mnInfoBox(Format(SShouldBeCorrect, [IntToStr(Actual)]), Title)
else
mnErrorBox(Format(SShouldBeWrong, [IntToStr(Actual), IntToStr(Expected)]), Title);
end;
procedure mnShouldBeBox(const Actual, Expected: Extended; const Title: string = ''); overload;
begin
if Actual = Expected then
mnInfoBox(Format(SShouldBeCorrect, [FloatToStr(Actual)]), Title)
else
mnErrorBox(Format(SShouldBeWrong, [FloatToStr(Actual), FloatToStr(Expected)]), Title);
end;
procedure mnShouldBeBox(const Actual, Expected: Boolean; const Title: string = ''); overload;
begin
if Actual = Expected then
mnInfoBox(Format(SShouldBeCorrect, [mnBoolToStr(Actual)]), Title)
else
mnErrorBox(Format(SShouldBeWrong, [mnBoolToStr(Actual), mnBoolToStr(Expected)]), Title);
end;
procedure mnShouldBeBoxDT(const Actual, Expected: TDateTime; const Title: string = '');
begin
if Actual = Expected then
mnInfoBox(Format(SShouldBeCorrect, [DateTimeToStr(Actual)]), Title)
else
mnErrorBox(Format(SShouldBeWrong, [DateTimeToStr(Actual), DateTimeToStr(Expected)]), Title);
end;
type
TShortcutMemo = class(TMemo)
private
procedure WhenMemoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
end;
{ TShortcutMemo }
procedure TShortcutMemo.WhenMemoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if Key = VK_ESCAPE then (Parent as TForm).Close
else if (Key = Ord('A')) and mnIsVKeyHold(VK_CONTROL) then SelectAll;
end;
type
TShortcutSaveBtn = class(TcxButton)
private
StrToBeSaved: string;
procedure WhenButtonClick(Sender: TObject);
end;
{ TShortcutSaveBtn }
procedure TShortcutSaveBtn.WhenButtonClick(Sender: TObject);
var
SaveDialog: TSaveDialog;
begin
SaveDialog := TSaveDialog.Create(nil);
try
mnSetSaveDialogFilter(SaveDialog, dfAll);
if SaveDialog.Execute then
begin
mnSaveStrToFile(StrToBeSaved, SaveDialog.FileName);
mnInfoBox(SSaveSuccessfully);
end;
finally
SaveDialog.Free;
end;
end;
procedure mnMemoBox(const Msg: string; const Title: string = ''; const CanSave: Boolean = False);
begin
{$IFDEF MN_NODIALOG}
mnLastDialogInfo.Kind := 'mnMemoBox';
mnLastDialogInfo.Msg := Msg;
{$ELSE}
mnMMemoBox(Msg, Title, CanSave);
{$ENDIF}
end;
procedure mnMMemoBox(const Msg: string; const Title: string = ''; const CanSave: Boolean = False);
var
MemoDialog: TForm;
begin
MemoDialog := TForm.Create(nil);
try
mnSetStandardFont(MemoDialog);
with MemoDialog do
begin
Caption := mnChooseStr(Title = '', Application.Title, Title);
BorderStyle := bsDialog;
Position := poScreenCenter;
Width := Screen.WorkAreaWidth * 2 div 3;
Height := Screen.WorkAreaHeight * 2 div 3;
end;
with TShortcutMemo.Create(MemoDialog) do
begin
Parent := MemoDialog;
if CanSave then
begin
Align := alTop;
Height := MemoDialog.ClientHeight - 45;
end
else
begin
Align := alClient;
end;
Text := Msg;
ScrollBars := ssBoth;
ReadOnly := True;
OnKeyDown := WhenMemoKeyDown;
end;
if CanSave then
begin
with TShortcutSaveBtn.Create(MemoDialog) do
begin
Parent := MemoDialog;
Caption := SSave;
Left := (MemoDialog.ClientWidth - Width) div 2;
Top := MemoDialog.ClientHeight - 10 - Height;
StrToBeSaved := Msg;
OnClick := WhenButtonClick;
end;
end;
MemoDialog.ShowModal;
finally
MemoDialog.Free;
end;
end;
function mnImageBox(BMP: TBitmap; const Title: string = ''): Boolean; overload;
{$IFDEF MN_NODIALOG}
begin
mnLastDialogInfo.Kind := 'mnImageBox';
mnLastDialogInfo.Msg := '';
Result := True;
end;
{$ELSE}
var
ImageDialog: TForm;
Panel: TPanel;
begin
ImageDialog := TForm.Create(nil);
try
mnSetStandardFont(ImageDialog);
with ImageDialog do
begin
Caption := mnChooseStr(Title = '', Application.Title, Title);
BorderStyle := bsDialog;
Position := poScreenCenter;
Width := Screen.WorkAreaWidth * 2 div 3;
Height := Screen.WorkAreaHeight * 2 div 3;
end;
Panel := TPanel.Create(ImageDialog);
with Panel do
begin
Parent := ImageDialog;
Align := alTop;
Height := ImageDialog.ClientHeight - 45;
BevelOuter := bvLowered;
end;
with TImage.Create(ImageDialog) do
begin
Parent := Panel;
Align := alClient;
Picture.Bitmap.Assign(BMP);
end;
with TcxButton.Create(ImageDialog) do
begin
Parent := ImageDialog;
Caption := SOK;
Left := ImageDialog.ClientWidth div 2 - 10 - Width;
Top := ImageDialog.ClientHeight - 10 - Height;
ModalResult := mrOK;
Default := True;
end;
with TcxButton.Create(ImageDialog) do
begin
Parent := ImageDialog;
Caption := SCancel;
Left := ImageDialog.ClientWidth div 2 + 10;
Top := ImageDialog.ClientHeight - 10 - Height;
ModalResult := mrCancel;
Cancel := True;
end;
Result := ImageDialog.ShowModal = mrOK;
finally
ImageDialog.Free;
end;
end;
{$ENDIF}
function mnImageBox(PixeledImage: mnTPixeledImage; const Title: string = ''): Boolean; overload;
var
BMP: TBitmap;
begin
BMP := TBitmap.Create;
try
PixeledImage.SaveToBMP(BMP);
Result := mnImageBox(BMP, Title);
finally
BMP.Free;
end;
end;
{$IFNDEF MN_NODIALOG}
type
TEditForm = class(TForm)
private
FEdit: TcxTextEdit;
FEditConstraint: mnTStrConstraint;
FErrorMsg: string;
procedure WhenFormClose(Sender: TObject; var Action: TCloseAction);
end;
{ TEditForm }
procedure TEditForm.WhenFormClose(Sender: TObject; var Action: TCloseAction);
begin
if ModalResult = mrOK then mnValidateControlText(FEdit, FEditConstraint, '', FErrorMsg);
end;
{$ENDIF}
function mnEditDialog(const Title, Prompt, Default: string; var Value: string;
const EditConstraint: mnTStrConstraint = scAny; const ErrorMsg: string = ''): Boolean;
{$IFDEF MN_NODIALOG}
begin
mnLastDialogInfo.Kind := 'mnEditDialog';
mnLastDialogInfo.Msg := '';
Value := Default;
Result := True;
end;
{$ELSE}
var
EditDialog: TEditForm;
Edit: TcxTextEdit;
begin
EditDialog := TEditForm.CreateNew(nil);
try
mnSetStandardFont(EditDialog);
with EditDialog do
begin
Caption := Title;
BorderStyle := bsDialog;
Position := poScreenCenter;
Width := 298;
Height := 135;
FEditConstraint := EditConstraint;
FErrorMsg := ErrorMsg;
OnClose := WhenFormClose;
end;
with TLabel.Create(EditDialog) do
begin
Parent := EditDialog;
Caption := Prompt;
Left := 20;
Top := 20;
end;
Edit := TcxTextEdit.Create(EditDialog);
with Edit do
begin
Parent := EditDialog;
Left := 20;
Top := 40;
Width := 250;
Text := Default;
end;
EditDialog.FEdit := Edit;
with TcxButton.Create(EditDialog) do
begin
Parent := EditDialog;
Caption := SOK;
Left := 140 - Width;
Top := 72;
ModalResult := mrOK;
Default := True;
end;
with TcxButton.Create(EditDialog) do
begin
Parent := EditDialog;
Caption := SCancel;
Left := 150;
Top := 72;
ModalResult := mrCancel;
Cancel := True;
end;
Result := EditDialog.ShowModal = mrOK;
if Result then Value := Edit.Text;
finally
EditDialog.Free;
end;
end;
{$ENDIF}
function mnComboBoxDialog(const Title, Prompt: string; ComboItems: TStrings; var SelectedIndex: Integer): Boolean;
{$IFDEF MN_NODIALOG}
begin
mnLastDialogInfo.Kind := 'mnComboBoxDialog';
mnLastDialogInfo.Msg := '';
Result := True;
end;
{$ELSE}
var
ComboBoxDialog: TForm;
ComboBox: TcxComboBox;
begin
if not mnBetweenIE(SelectedIndex, 0, ComboItems.Count) then
SelectedIndex := 0;
ComboBoxDialog := TForm.Create(nil);
try
mnSetStandardFont(ComboBoxDialog);
with ComboBoxDialog do
begin
Caption := Title;
BorderStyle := bsDialog;
Position := poScreenCenter;
Width := 298;
Height := 135;
end;
with TLabel.Create(ComboBoxDialog) do
begin
Parent := ComboBoxDialog;
Caption := Prompt;
Left := 20;
Top := 20;
end;
ComboBox := TcxComboBox.Create(ComboBoxDialog);
with ComboBox do
begin
Parent := ComboBoxDialog;
Left := 20;
Top := 40;
Width := 250;
Properties.DropDownListStyle := lsFixedList;
Properties.Items.Assign(ComboItems);
ItemIndex := SelectedIndex;
end;
with TcxButton.Create(ComboBoxDialog) do
begin
Parent := ComboBoxDialog;
Caption := SOK;
Left := 140 - Width;
Top := 72;
ModalResult := mrOK;
Default := True;
end;
with TcxButton.Create(ComboBoxDialog) do
begin
Parent := ComboBoxDialog;
Caption := SCancel;
Left := 150;
Top := 72;
ModalResult := mrCancel;
Cancel := True;
end;
Result := ComboBoxDialog.ShowModal = mrOK;
if Result then SelectedIndex := ComboBox.ItemIndex;
finally
ComboBoxDialog.Free;
end;
end;
{$ENDIF}
type
TEventContainer = class
procedure WhenCheckAllBtnClick(Sender: TObject);
procedure WhenCheckNoneBtnClick(Sender: TObject);
end;
{ TEventContainer }
procedure TEventContainer.WhenCheckAllBtnClick(Sender: TObject);
var
CheckListBox: TcxCheckListBox;
i: Integer;
begin
CheckListBox := TcxCheckListBox((Sender as TcxButton).Tag);
for i := 0 to CheckListBox.Items.Count-1 do
CheckListBox.Items[i].Checked := True;
end;
procedure TEventContainer.WhenCheckNoneBtnClick(Sender: TObject);
var
CheckListBox: TcxCheckListBox;
i: Integer;
begin
CheckListBox := TcxCheckListBox((Sender as TcxButton).Tag);
for i := 0 to CheckListBox.Items.Count-1 do
CheckListBox.Items[i].Checked := False;
end;
function mnCheckListBoxDialog(const Title, Prompt: string; CheckItems: TStrings; CheckedResult: mnTBoolList): Boolean;
{$IFDEF MN_NODIALOG}
begin
mnLastDialogInfo.Kind := 'mnCheckListBoxDialog';
mnLastDialogInfo.Msg := '';
Result := True;
end;
{$ELSE}
var
CheckListBoxDialog: TForm;
CheckListBox: TcxCheckListBox;
EventContainer: TEventContainer;
i: Integer;
begin
CheckListBoxDialog := TForm.Create(nil);
EventContainer := TEventContainer.Create;
try
mnSetStandardFont(CheckListBoxDialog);
with CheckListBoxDialog do
begin
Caption := Title;
BorderStyle := bsDialog;
Position := poScreenCenter;
Width := 298;
Height := 397;
end;
with TLabel.Create(CheckListBoxDialog) do
begin
Parent := CheckListBoxDialog;
Caption := Prompt;
Left := 20;
Top := 20;
end;
CheckListBox := TcxCheckListBox.Create(CheckListBoxDialog);
with CheckListBox do
begin
Parent := CheckListBoxDialog;
Left := 20;
Top := 40;
Width := 250;
Height := 250;
for i := 0 to CheckItems.Count-1 do
with Items.Add do
begin
Text := CheckItems[i];
if CheckedResult.Count > 0 then
Checked := CheckedResult[i];
end;
end;
with TcxButton.Create(CheckListBoxDialog) do
begin
Parent := CheckListBoxDialog;
Caption := SOK;
Left := 140 - Width;
Top := 335;
ModalResult := mrOK;
Default := True;
end;
with TcxButton.Create(CheckListBoxDialog) do
begin
Parent := CheckListBoxDialog;
Caption := SCancel;
Left := 150;
Top := 335;
ModalResult := mrCancel;
Cancel := True;
end;
with TcxButton.Create(CheckListBoxDialog) do
begin
Parent := CheckListBoxDialog;
Caption := SCheckAll;
Left := 110 - Width;
Top := 302;
Tag := Integer(CheckListBox);
OnClick := EventContainer.WhenCheckAllBtnClick;
end;
with TcxButton.Create(CheckListBoxDialog) do
begin
Parent := CheckListBoxDialog;
Caption := SCheckNone;
Left := 180;
Top := 302;
Tag := Integer(CheckListBox);
OnClick := EventContainer.WhenCheckNoneBtnClick;
end;
Result := CheckListBoxDialog.ShowModal = mrOK;
if Result then
begin
CheckedResult.Clear;
for i := 0 to CheckListBox.Items.Count-1 do
CheckedResult.Add(CheckListBox.Items[i].Checked);
end;
finally
EventContainer.Free;
CheckListBoxDialog.Free;
end;
end;
{$ENDIF}
procedure mnSetOpenDialogFilter(OpenDialog: TOpenDialog; const DialogFilter: mnTDialogFilter);
begin
case DialogFilter of
dfAll: OpenDialog.Filter := SDialogFilterAll;
dfText: OpenDialog.Filter := SDialogFilterText;
dfExcel: OpenDialog.Filter := SDialogFilterExcel;
dfWord: OpenDialog.Filter := SDialogFilterWord;
dfXML: OpenDialog.Filter := SDialogFilterXML;
end;
case DialogFilter of
dfText: OpenDialog.DefaultExt := 'txt';
dfExcel: OpenDialog.DefaultExt := 'xlsx';
dfWord: OpenDialog.DefaultExt := 'docx';
dfXML: OpenDialog.DefaultExt := 'xml';
end;
end;
procedure mnSetSaveDialogFilter(SaveDialog: TSaveDialog; const DialogFilter: mnTDialogFilter);
begin
case DialogFilter of
dfAll: SaveDialog.Filter := SDialogFilterAll;
dfText: SaveDialog.Filter := SDialogFilterText;
dfExcel: SaveDialog.Filter := SDialogFilterExcel;
dfWord: SaveDialog.Filter := SDialogFilterWord;
dfXML: SaveDialog.Filter := SDialogFilterXML;
end;
case DialogFilter of
dfText: SaveDialog.DefaultExt := 'txt';
dfExcel: SaveDialog.DefaultExt := 'xlsx';
dfWord: SaveDialog.DefaultExt := 'docx';
dfXML: SaveDialog.DefaultExt := 'xml';
end;
end;
end.
|
unit Utils.MD5;
interface
uses IdHashMessageDigest, idHash;
type
TMD5 = class
public
class function Hash(AValue: string): string;
end;
implementation
{ TMD5 }
class function TMD5.Hash(AValue: string): string;
var
idmd5: TIdHashMessageDigest5;
hash : T4x4LongWordRecord;
begin
Result := '';
idmd5 := TIdHashMessageDigest5.Create;
try
Result := idmd5.HashStringAsHex(AValue);
finally
idmd5.Free;
end;
end;
end.
|
unit AndroidThemes;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Laz2_DOM, Graphics;
type
TAndroidThemes = class;
{ TAndroidTheme }
TAndroidTheme = class
private
FOwner: TAndroidThemes;
FMinAPI: Integer;
FName: string; // full dotted name like "Theme.Holo.Light"
FLoaded: Boolean;
FParent: TAndroidTheme;
FContent: TDOMElement;
FCache: TStringList; // x>y>z -> TColorCacheItem
function PathToKey(const APath: array of string; const attribs: string): string; { TODO: inline }
function FindColorInCache(const APath: array of string; attribs: string;
out WasFound: Boolean; out ARed, AGreen, ABlue, AAlpha: Byte): Boolean;
function FindColorInCache(const APathStr: string;
out WasFound: Boolean; out ARed, AGreen, ABlue, AAlpha: Byte): Boolean;
function FindDrawableInCache(const APathKey: string;
out WasFound: Boolean; out Drawable: string): Boolean;
function FindPath(const Path: array of string): TDOMNode;
procedure AddColorToCache(const APath: array of string;
WasFound: Boolean; attribs: string; ARed, AGreen, ABlue, AAlpha: Byte);
procedure AddDrawableToCache(const APathKey: string; WasFound: Boolean; Drawable: string);
function Loaded: Boolean; // FContent = node from themes.xml
function TryResolve(n: TDOMNode): TDOMNode;
function Selector(AParent: TDOMNode; const attribs, aname: string): string;
public
constructor Create(const AName: string);
destructor Destroy; override;
procedure ClearCache;
function ShortName: string;
function GetColor(const colorName: string): TColor;
function TryGetColor(const colorName: string; attribs: string;
out Red, Green, Blue, Alpha: Byte): Boolean;
function TryGetColor(const Path: array of string; attribs: string;
out Red, Green, Blue, Alpha: Byte): Boolean;
function TryGetColor(const Path: array of string; attribs: string;
out Color: TColor): Boolean;
function GetColorDef(const colorName: string; DefValue: TColor): TColor;
function Find(const tagName, attrName, attrVal: string): TDOMElement;
function FindDrawable(const Path: array of string; const attribs: string): string;
property MinAPI: Integer read FMinAPI;
property Name: string read FName;
end;
{ TAndroidThemes }
TAndroidThemes = class
private
FInited: Boolean;
FAPI: Integer;
FThemes: TStringList;
FXMLs: TStringList; // objects are TXMLDocument
FBasePath: string; // %{sdk}/platforms/android-XX/data/res/values/
function AddTheme(const ThemeName: string; MinAPI: Integer): TAndroidTheme;
procedure Clear;
function LoadXML(FileName: string; ForceReload: Boolean = False): TXMLDocument;
function FindNodeAttribInFiles(const BaseFileName, ATag, AAttr, AVal: string): TDOMElement;
procedure ClearXMLCache(const ProjRoot: string);
function Resolve(link: string; const PathToProjRoot: string = '';
TargetAPI: Integer = 0): TDOMNode;
public
constructor Create;
destructor Destroy; override;
procedure Init(API: Integer);
function GetTheme(const AndroidManifestFileName: string): TAndroidTheme;
function Count: Integer;
function FindTheme(const ThemeName: string): TAndroidTheme;
procedure ReInit(API: Integer); // reloading available themes from SDK
end;
var
Themes: TAndroidThemes;
implementation
uses LamwSettings, strutils, laz2_XMLRead, FileUtil;
type
TColorCacheItem = class
public
Red, Green, Blue, Alpha: Byte;
end;
TDrawableCacheItem = class
public
fname: string;
end;
function FindNodeAttrib(root: TDOMElement; const ATag, AAttr, AVal: string): TDOMElement;
var
n: TDOMNode;
begin
if not root.HasChildNodes then Exit(nil);
n := root.FirstChild;
while n <> nil do
begin
if n is TDOMElement then
with TDOMElement(n) do
if (TagName = ATag) and (AttribStrings[AAttr] = AVal) then
begin
Result := TDOMElement(n);
Exit;
end;
n := n.NextSibling;
end;
Result := nil;
end;
{ TAndroidThemes }
function TAndroidThemes.AddTheme(const ThemeName: string;
MinAPI: Integer): TAndroidTheme;
begin
Result := TAndroidTheme.Create(ThemeName);
Result.FMinAPI := MinAPI;
Result.FOwner := Self;
FThemes.AddObject(ThemeName, Result);
end;
procedure TAndroidThemes.Clear;
begin
FThemes.Clear;
FXMLs.Clear;
end;
function TAndroidThemes.LoadXML(FileName: string; ForceReload: Boolean): TXMLDocument;
var
i: Integer;
begin
if Pos(PathDelim, FileName) = 0 then
FileName := FBasePath + FileName;
FileName := ExpandFileName(FileName);
if not FileExists(FileName) then Exit(nil);
i := FXMLs.IndexOf(FileName);
if ForceReload and (i >= 0) then
begin
FXMLs.Delete(i);
i := -1;
end;
if i >= 0 then
Result := TXMLDocument(FXMLs.Objects[i])
else begin
ReadXMLFile(Result, FileName);
FXMLs.AddObject(FileName, Result);
end
end;
function TAndroidThemes.FindNodeAttribInFiles(const BaseFileName, ATag, AAttr, AVal: string): TDOMElement;
var
xml: TXMLDocument;
files: TStringList;
i: Integer;
begin
Result := nil;
xml := LoadXML(BaseFileName + '.xml');
if xml <> nil then
begin
Result := FindNodeAttrib(xml.DocumentElement, ATag, AAttr, AVal);
if Result <> nil then Exit;
end;
files := FindAllFiles(FBasePath, BaseFileName + '_*.xml', False);
try
for i := 0 to files.Count - 1 do
begin
xml := LoadXML(files[i]);
if xml <> nil then
begin
Result := FindNodeAttrib(xml.DocumentElement, ATag, AAttr, AVal);
if Result <> nil then Exit;
end;
end;
finally
files.Free
end;
end;
procedure TAndroidThemes.ClearXMLCache(const ProjRoot: string);
function Starts(const s1, s2: string): Boolean;
var
i: Integer;
begin
Result := False;
if Length(s1) > Length(s2) then Exit;
for i := 1 to Length(s1) do
if s1[i] <> s2[i] then Exit;
Result := True;
end;
var
i: Integer;
begin
for i := FXMLs.Count - 1 downto 0 do
if Starts(ProjRoot, FXMLs[i]) then
FXMLs.Delete(i);
end;
function TAndroidThemes.FindTheme(const ThemeName: string): TAndroidTheme;
var
n: Integer;
begin
Result := nil;
n := FThemes.IndexOf(ThemeName);
if n >= 0 then
Result := TAndroidTheme(FThemes.Objects[n])
end;
constructor TAndroidThemes.Create;
begin
FThemes := TStringList.Create;
FThemes.Sorted := True;
FThemes.OwnsObjects := True;
FXMLs := TStringList.Create;
FXMLs.CaseSensitive := True;
FXMLs.OwnsObjects := True;
FXMLs.Sorted := True;
end;
destructor TAndroidThemes.Destroy;
begin
Clear;
FThemes.Free;
FXMLs.Free;
inherited Destroy;
end;
procedure TAndroidThemes.Init(API: Integer);
var
xml: TXMLDocument;
n, p: TDOMNode;
FCurAPI: Integer;
str: DOMString;
i: SizeInt;
begin
if FInited and (FAPI >= API) then Exit;
if FInited then ClearXMLCache('');
FInited := False;
FBasePath := LamwGlobalSettings.PathToAndroidSDK + 'platforms/android-' + IntToStr(API)
+ '/data/res/values/';
DoDirSeparators(FBasePath);
if not FileExists(FBasePath + 'public.xml') then Exit;
ReadXMLFile(xml, FBasePath + 'public.xml');
try
Clear;
FAPI := API;
FCurAPI := 0;
p := nil;
n := xml.DocumentElement.FirstChild;
while n <> nil do
begin
if n is TDOMElement then
with TDOMElement(n) do
if (TagName = 'eat-comment') and (p is TDOMComment) then
begin
str := TDOMComment(p).TextContent;
i := Pos('version ', str);
if i > 0 then
begin
Delete(str, 1, i + 6);
str := TrimLeft(str);
i := 1;
while (i < Length(str)) and (str[i] in ['0'..'9']) do Inc(i);
if (i > 1) then
FCurAPI := StrToInt(Copy(str, 1, i - 1));
end;
end else
if (TagName = 'public') and (AttribStrings['type'] = 'style') then
begin
str := AttribStrings['name'];
if Copy(str, 1, 5) = 'Theme' then
AddTheme(str, FCurAPI);
end;
p := n;
n := n.NextSibling;
end;
finally
xml.Free;
end;
FInited := True;
end;
function TAndroidThemes.Resolve(link: string; const PathToProjRoot: string;
TargetAPI: Integer): TDOMNode;
function ResolveStyle(const search: string): TDOMElement;
var
i: Integer;
s: string;
xml: TXMLDocument;
n: TDOMElement;
Found: Boolean;
begin
Result := nil;
i := TargetAPI;
repeat
s := PathToProjRoot + 'res' + PathDelim + 'values-v' + IntToStr(i)
+ PathDelim + 'styles.xml';
Found := FileExists(s);
Dec(i);
until (i <= 0) or Found;
if not Found then Exit;
xml := LoadXML(s);
if xml = nil then Exit;
n := FindNodeAttrib(xml.DocumentElement, 'style', 'name', search);
if n <> nil then Exit(n);
s := PathToProjRoot + 'res' + PathDelim + 'values' + PathDelim + 'styles.xml';
xml := LoadXML(s);
if xml = nil then Exit;
n := FindNodeAttrib(xml.DocumentElement, 'style', 'name', search);
if n <> nil then Exit(n);
Result := FindNodeAttribInFiles('styles', 'style', 'name', search);
end;
function ResolveAndroidStyle(const search: string): TDOMNode;
var
xml: TXMLDocument;
begin
Result := nil;
xml := LoadXML('styles.xml');
if xml = nil then Exit;
Result := FindNodeAttrib(xml.DocumentElement, 'style', 'name', search);
if Result = nil then
begin
xml := LoadXML('styles_device_defaults.xml');
if xml = nil then Exit;
Result := FindNodeAttrib(xml.DocumentElement, 'style', 'name', search);
end;
end;
function ResolveAndroidDrawable(const search: string): TDOMNode;
var
xml: TXMLDocument;
begin
Result := nil;
xml := LoadXML(FBasePath + '../drawable/' + search + '.xml');
if xml = nil then Exit;
Result := xml.DocumentElement;
end;
function ResolveAndroidColor(const search: string): TDOMNode;
var
fn: string;
begin
fn := ExpandFileName(FBasePath + '../color/' + search + '.xml');
if FileExists(fn) then
Result := LoadXML(fn).DocumentElement
else
Result := FindNodeAttribInFiles('colors', 'color', 'name', search);
end;
var
LinkType: string;
i: Integer;
begin
i := Pos('/', link);
LinkType := Copy(link, 2, i - 2);
Delete(link, 1, i);
if LinkType = 'style' then
Result := ResolveStyle(link)
else
if LinkType = 'android:style' then
Result := ResolveAndroidStyle(link)
else
if LinkType = 'android:drawable' then
Result := ResolveAndroidDrawable(link)
else
if (LinkType = 'android:color') or (LinkType = 'color') then
Result := ResolveAndroidColor(link)
else
Result := nil;
end;
function TAndroidThemes.GetTheme(const AndroidManifestFileName: string): TAndroidTheme;
var
TargetAPI: Integer;
xml: TXMLDocument;
n: TDOMNode;
s, pp: string;
begin
Result := nil;
if not FileExists(AndroidManifestFileName) then Exit;
xml := LoadXML(AndroidManifestFileName, True);
n := xml.DocumentElement.FindNode('uses-sdk');
if n = nil then Exit;
s := TDOMElement(n).AttribStrings['android:targetSdkVersion'];
if not TryStrToInt(s, TargetAPI) then Exit;
n := xml.DocumentElement.FindNode('application');
if n = nil then Exit;
s := TDOMElement(n).AttribStrings['android:theme'];
if s = '' then Exit;
Init(TargetAPI);
if not FInited then Exit;
pp := ExtractFilePath(AndroidManifestFileName);
ClearXMLCache(pp);
while s[1] = '@' do
begin
n := Resolve(s, pp, TargetAPI);
if not (n is TDOMElement) then Exit;
s := TDOMElement(n).AttribStrings['parent'];
if s = '' then Exit;
if Pos(':', s) = 0 then
s := '@style/' + s;
end;
if Copy(s, 1, 8) = 'android:' then
Delete(s, 1, 8);
Result := FindTheme(s);
end;
function TAndroidThemes.Count: Integer;
begin
Result := FThemes.Count;
end;
procedure TAndroidThemes.ReInit(API: Integer);
begin
FThemes.Clear;
FInited := False;
Init(API);
end;
{ TAndroidTheme }
function TAndroidTheme.PathToKey(const APath: array of string;
const attribs: string): string;
var
i: Integer;
begin
Result := APath[0];
for i := 1 to High(APath) do
Result := Result + '>' + APath[i];
Result := Result + '|' + attribs;
end;
function TAndroidTheme.FindColorInCache(const APath: array of string;
attribs: string; out WasFound: Boolean;
out ARed, AGreen, ABlue, AAlpha: Byte): Boolean;
begin
Result := FindColorInCache(PathToKey(APath, attribs), WasFound, ARed, AGreen, ABlue, AAlpha);
end;
function TAndroidTheme.FindColorInCache(const APathStr: string;
out WasFound: Boolean; out ARed, AGreen, ABlue, AAlpha: Byte): Boolean;
var
i: Integer;
begin
i := FCache.IndexOf(APathStr);
Result := i >= 0;
if Result then
begin
WasFound := FCache.Objects[i] is TColorCacheItem;
if WasFound then
with TColorCacheItem(FCache.Objects[i]) do
begin
ARed := Red;
AGreen := Green;
ABlue := Blue;
AAlpha := Alpha;
end;
end;
end;
function TAndroidTheme.FindDrawableInCache(const APathKey: string; out
WasFound: Boolean; out Drawable: string): Boolean;
var
i: Integer;
begin
i := FCache.IndexOf(APathKey);
Result := i >= 0;
if Result then
begin
WasFound := FCache.Objects[i] is TDrawableCacheItem;
if WasFound then
Drawable := TDrawableCacheItem(FCache.Objects[i]).fname;
end;
end;
function TAndroidTheme.FindPath(const Path: array of string): TDOMNode;
function FindNodeUsingParent(root: TDOMElement; const tag, attr, val: string): TDOMNode;
begin
Result := FindNodeAttrib(root, tag, attr, val);
if (Result = nil) and (root.AttribStrings['parent'] <> '') then
begin
root := FOwner.Resolve('@android:' + root.TagName + '/' + root.AttribStrings['parent']) as TDOMElement;
if root <> nil then
Result := FindNodeUsingParent(root, tag, attr, val);
end;
Result := TryResolve(Result);
end;
var
n: TDOMNode;
i: Integer;
begin
Result := nil;
if not Loaded then Exit;
n := TryResolve(Find('item', 'name', Path[0]));
if n = nil then Exit;
for i := 1 to High(Path) do
begin
n := FindNodeUsingParent(TDOMElement(n), 'item', 'name', Path[i]);
if n = nil then Exit;
end;
Result := n;
end;
procedure TAndroidTheme.AddColorToCache(const APath: array of string;
WasFound: Boolean; attribs: string; ARed, AGreen, ABlue, AAlpha: Byte);
var
i: Integer;
key: string;
it: TColorCacheItem;
begin
key := PathToKey(APath, attribs);
i := FCache.IndexOf(key);
if i >= 0 then Exit;
i := FCache.Add(key);
if WasFound then
begin
it := TColorCacheItem.Create;
it.Red := ARed;
it.Green := AGreen;
it.Blue := ABlue;
it.Alpha := AAlpha;
FCache.Objects[i] := it;
end;
end;
procedure TAndroidTheme.AddDrawableToCache(const APathKey: string;
WasFound: Boolean; Drawable: string);
var
i: Integer;
it: TDrawableCacheItem;
begin
i := FCache.IndexOf(APathKey);
if i >= 0 then Exit;
i := FCache.Add(APathKey);
if WasFound then
begin
it := TDrawableCacheItem.Create;
it.fname := Drawable;
FCache.Objects[i] := it;
end;
end;
function TAndroidTheme.Loaded: Boolean;
function FindIn(XmlFileName: string): TDOMElement;
var
n: TDOMNode;
xml: TXMLDocument;
begin
Result := nil;
xml := FOwner.LoadXML(XmlFileName);
if xml = nil then Exit;
n := xml.DocumentElement.FirstChild;
while n <> nil do
begin
if (n is TDOMElement) then
with TDOMElement(n) do
if (TagName = 'style') and (AttribStrings['name'] = FName) then
begin
Result := TDOMElement(n);
Break;
end;
n := n.NextSibling;
end;
end;
var
parent: string;
begin
if FLoaded then Exit(True);
FContent := FOwner.FindNodeAttribInFiles('themes', 'style', 'name', FName);
if FContent = nil then Exit(False);
parent := FContent.AttribStrings['parent'];
if parent <> '' then
begin
FParent := FOwner.FindTheme(parent);
if FParent = nil then // not all themes are listed in res\values\piblic.xml
FParent := FOwner.AddTheme(parent, FMinAPI);
end;
FLoaded := True;
Result := True;
end;
function TAndroidTheme.TryResolve(n: TDOMNode): TDOMNode;
var
s: string;
begin
Result := n;
if n is TDOMElement then
begin
s := TDOMElement(n).TextContent;
if (s <> '') and (s[1] = '@') then
begin
n := FOwner.Resolve(s);
end else
if Copy(s, 1, 14) = '?android:attr/' then
begin
Delete(s, 1, Pos('/', s));
n := Find('item', 'name', s);
end;
if (n <> nil) and (n <> Result) then
Result := TryResolve(n);
end;
end;
function TAndroidTheme.Selector(AParent: TDOMNode; const attribs, aname: string): string;
var
attrT, attrF: TStringList;
n1: TDOMNode;
lc: TDOMElement;
v: string;
i: Integer;
match: Boolean;
begin
Result := '';
lc := nil;
attrT := TStringList.Create;
attrF := TStringList.Create;
try
attrT.Delimiter := ';';
attrT.DelimitedText := attribs;
for i := attrT.Count - 1 downto 0 do
begin
v := attrT.ValueFromIndex[i];
if (v <> '') and (v[1] = '!') then
begin
Delete(v, 1, 1);
attrF.Values[attrT.Names[i]] := v;
attrT.Delete(i);
end;
end;
n1 := AParent.FirstChild;
while n1 <> nil do
begin
if (n1 is TDOMElement) and TDOMElement(n1).hasAttribute(aname) then //fixed, thanks to Coldzer0
with TDOMElement(n1) do
begin
lc := TDOMElement(n1);
match := True;
for i := 0 to attrT.Count - 1 do
begin
if AttribStrings[attrT.Names[i]] <> attrT.ValueFromIndex[i] then
begin
match := False;
Break;
end;
end;
if match then
for i := 0 to attrF.Count - 1 do
begin
if AttribStrings[attrF.Names[i]] = attrF.ValueFromIndex[i] then
begin
match := False;
Break;
end;
end;
if match then Break;
end;
n1 := n1.NextSibling;
end;
if n1 <> nil then
Result := TDOMElement(n1).AttribStrings[aname]
else
if lc <> nil then
Result := lc.AttribStrings[aname];
finally
attrT.Free;
attrF.Free;
end;
end;
constructor TAndroidTheme.Create(const AName: string);
begin
FName := AName;
FCache := TStringList.Create;
FCache.Sorted := True;
FCache.OwnsObjects := True;
FCache.CaseSensitive := True;
end;
destructor TAndroidTheme.Destroy;
begin
FCache.Free;
inherited Destroy;
end;
procedure TAndroidTheme.ClearCache;
begin
FCache.Clear;
end;
function TAndroidTheme.ShortName: string;
var
i: Integer;
begin
Result := FName;
i := RPos('.', Result);
if i > 0 then
Delete(Result, 1, i);
end;
function TAndroidTheme.GetColor(const colorName: string): TColor;
begin
Result := GetColorDef(colorName, clNone);
end;
function TAndroidTheme.TryGetColor(const colorName: string; attribs: string;
out Red, Green, Blue, Alpha: Byte): Boolean;
var
i: Integer;
t: TAndroidTheme;
s: string;
n: TDOMNode;
begin
if FindColorInCache([colorName], attribs, Result, Red, Green, Blue, Alpha) then Exit;
Result := False;
if not Loaded then Exit;
try
s := colorName;
while s <> '' do
case s[1] of
'#':
begin
Result := True;
Delete(s, 1, 1);
if Length(s) > 8 then
s := RightStr(s, 8);
while Length(s) < 6 do s := '0' + s;
case Length(s) of
6: s := 'ff' + s;
7: s := '0' + s;
end;
Alpha := StrToInt('$' + Copy(s, 1, 2));
Red := StrToInt('$' + Copy(s, 3, 2));
Green := StrToInt('$' + Copy(s, 5, 2));
Blue := StrToInt('$' + Copy(s, 7, 2));
Exit;
end;
'?':
begin
i := Pos('/', s);
if i = 0 then i := 1;
Delete(s, 1, i);
end;
'@':
begin
n := FOwner.Resolve(s);
if n = nil then Break;
if n.NodeName = 'selector' then
s := Selector(n, attribs, 'android:color')
else
s := n.TextContent;
end;
else
n := FindNodeAttrib(FContent, 'item', 'name', s);
if n = nil then Break;
s := n.TextContent;
end;
if FParent <> nil then
Result := FParent.TryGetColor(colorName, attribs, Red, Green, Blue, Alpha);
if not Result then
begin
i := RPos('.', Name);
if i > 0 then
begin
t := FOwner.FindTheme(Copy(Name, 1, i - 1));
if t <> nil then
Result := t.TryGetColor(colorName, attribs, Red, Green, Blue, Alpha);
end;
end;
finally
AddColorToCache([colorName], Result, attribs, Red, Green, Blue, Alpha);
end;
end;
function TAndroidTheme.TryGetColor(const Path: array of string; attribs: string;
out Red, Green, Blue, Alpha: Byte): Boolean;
var
s: string;
n: TDOMNode;
begin
if FindColorInCache(Path, attribs, Result, Red, Green, Blue, Alpha) then Exit;
Result := False;
if not Loaded then Exit;
try
n := FindPath(Path);
if (n <> nil) and (n.NodeName = 'selector') then
s := Selector(n, attribs, 'android:color')
else
if n is TDOMElement then
s := TDOMElement(n).TextContent
else
Exit;
if s = '' then Exit;
Result := TryGetColor(s, attribs, Red, Green, Blue, Alpha);
finally
AddColorToCache(Path, Result, attribs, Red, Green, Blue, Alpha);
end;
end;
function TAndroidTheme.TryGetColor(const Path: array of string;
attribs: string; out Color: TColor): Boolean;
var
r, g, b, a: Byte;
begin
Result := TryGetColor(Path, attribs, r, g, b, a);
if Result then
Color := RGBToColor(r, g, b);
end;
function TAndroidTheme.GetColorDef(const colorName: string;
DefValue: TColor): TColor;
var
r, g, b, a: Byte;
begin
if not TryGetColor(colorName, 'android:state_enabled=!false', r, g, b, a) then
Result := DefValue
else
Result := RGBToColor(r, g, b);
end;
function TAndroidTheme.Find(const tagName, attrName, attrVal: string): TDOMElement;
var
i: Integer;
t: TAndroidTheme;
begin
Result := nil;
if not Loaded then Exit;
Result := FindNodeAttrib(FContent, tagName, attrName, attrVal);
if Result = nil then
begin
if FParent <> nil then
Result := FParent.Find(tagName, attrName, attrVal)
else
begin
i := RPos('.', Name);
if i > 0 then
begin
t := FOwner.FindTheme(Copy(Name, 1, i - 1));
if t <> nil then
Result := t.Find(tagName, attrName, attrVal);
end;
end;
end;
end;
function TAndroidTheme.FindDrawable(const Path: array of string;
const attribs: string): string;
var
n: TDOMNode;
s: string;
found: Boolean;
begin
Result := '';
if FindDrawableInCache(PathToKey(Path, attribs), found, Result) then Exit;
try
if not Loaded then Exit;
n := TryResolve(FindPath(Path));
if n = nil then Exit;
if (n.NodeName = 'selector') then
s := Selector(n, attribs, 'android:drawable')
else
if n is TDOMElement then
s := TDOMElement(n).TextContent
else
Exit;
if Copy(s, 1, 10) = '@drawable/' then
begin
Delete(s, 1, 10);
s := ExpandFileName(FOwner.FBasePath + '../drawable-mdpi/' + s);
if FileExists(s + '.9.png') then
Result := s + '.9.png'
else
if FileExists(s + '.png') then
Result := s + '.png';
end;
finally
AddDrawableToCache(PathToKey(Path, attribs), Result <> '', Result);
end;
end;
initialization
Themes := TAndroidThemes.Create;
finalization
Themes.Free;
end.
|
unit UGameVariables;
interface
uses
W3System;
const
GRAVITY = 1.5;
FLYING_SPEED_CHANGE = 0.1;
FLYING_SPEED_MAX = 3;
ARROW_FREEZE_DURATION_RANGE = 2000;
var
MaxPower : float;
ArrowDamage : integer;
ArrowsFreeze : boolean;
ArrowFreezeDuration : integer;
TimeBetweenShots : integer;
PauseButtonCoordinates : array [0 .. 3] of integer;
RestartButtonCoordinates : array [0 .. 3] of integer;
RestartClicked : boolean;
Paused : boolean;
Lives : integer;
Money : integer;
function FloatMod(a, b : float) : integer; // A function to perform modulus operations on floats
function PauseButtonRect() : TRect;
function RestartButtonRect() : TRect;
implementation
function FloatMod(a, b : float) : integer;
begin
exit(Trunc(a - b * Trunc(a / b)));
end;
function PauseButtonRect() : TRect;
begin
exit(TRect.Create(PauseButtonCoordinates[0], PauseButtonCoordinates[1], PauseButtonCoordinates[2], PauseButtonCoordinates[3]));
end;
function RestartButtonRect() : TRect;
begin
exit(TRect.Create(RestartButtonCoordinates[0], RestartButtonCoordinates[1], RestartButtonCoordinates[2], RestartButtonCoordinates[3]));
end;
end. |
unit UEmitter;
{
Copyright (c) 2014 George Wright
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License, as described at
http://www.apache.org/licenses/ and http://www.pp4s.co.uk/licenses/
}
interface
uses
SmartCL.System, SmartCL.Graphics, UParticle, UColourShifter;
type TParticleEmitter = class(TObject)
Particles : array of TParticle; // Contains all the particles and their data
EmitterX : float; // The starting X of all particles, the X origin point
EmitterY : float; // The starting Y of all particles, the Y origin point
LeftToSpawn : float; // Particles waiting to be spawned
CurrentCol : array [0 .. 2] of integer;
ColourToEdit : integer;
IncrementCol : boolean;
ColourShifter : TColourShifter; // The colour changer
constructor Create(newx, newy : float);
procedure Update(updateX, updateY : float; howManyToSpawn : float = 1); // Updates all the particles and makes any new ones
procedure DrawStars(Canvas : TW3Canvas); // Draws all the stars
function GenerateNewParticle : TParticle; // Will generate a new particle
end;
implementation
constructor TParticleEmitter.Create(newx, newy : float);
begin
EmitterX := newx;
EmitterY := newy;
LeftToSpawn := 0;
ColourShifter := TColourShifter.Create(0, 0, 0);
end;
procedure TParticleEmitter.Update(updateX, updateY : float; howManyToSpawn : float = 1);
begin
// Set the x and y
EmitterX := updateX;
EmitterY := updateY;
// Iterate over the particles
for var i := 0 to High(Particles) do
begin
// Update the particle
Particles[i].Update();
// If the particle is meant to be dead kill it
if (Particles[i].TTL <= 0) then
begin
// Respawn the particle
Particles[i] := GenerateNewParticle();
LeftToSpawn -= 1;
end;
end;
LeftToSpawn += howManyToSpawn;
for var i := 0 to trunc(LeftToSpawn) do
begin
// Generate a new particle
Particles[High(Particles) + 1] := GenerateNewParticle();
// Store that a particle was created
LeftToSpawn -= 1
end;
end;
procedure TParticleEmitter.DrawStars(Canvas: TW3Canvas);
begin
// Iterate over each particle
for var i := 0 to High(Particles) do
// Draw the particle
Particles[i].Draw(Canvas);
end;
function TParticleEmitter.GenerateNewParticle() : TParticle;
var
pX, pY, pXvol, pYvol, pAngle, pSpin, pSize : float;
pColour : array [0..2] of integer;
pTTL : integer;
returnP : TParticle;
begin
// Set the new particle's X and Y
pX := EmitterX;
pY := EmitterY;
// Set the new particle's x-velocity and y-velocity
pXvol := randomint(10) - 5;
pYvol := randomint(4) - 2;
// Set the new particle's angle and spin
pAngle := randomint(360);
pSpin := randomint(60)- 30;
// Set the new particle's colour
pColour := ColourShifter.Colour;
// Shift the colour
ColourShifter.ShiftColour();
// Set the new particle's size
pSize := randomint(200) / 100;
// Set the new particle's TTL
pTTL := randomint(5) + 25;
// Create the new particle
returnP := TParticle.Create(pX, pY, pXvol, pYvol, pAngle, pSpin, pSize, pColour, pTTL);
// Return the new particle
exit(returnP);
end;
end. |
{ ***************************************************************************
Copyright (c) 2016-2019 Kike P�rez
Unit : Quick.ORM.DataBase
Description : Rest ORM Database config & connection
Author : Kike P�rez
Version : 1.2
Created : 20/06/2017
Modified : 27/02/2019
This file is part of QuickORM: https://github.com/exilon/QuickORM
Uses Synopse mORMot framework. Copyright (C) 2017 Arnaud Bouchez
Synopse Informatique - https://synopse.info
***************************************************************************
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 Quick.ORM.DataBase;
{$i QuickORM.inc}
interface
uses
Classes,
SysUtils,
SynCommons,
mORMot,
mORMotDB,
SynDB,
{$IFNDEF FPC}
System.IOUtils,
{$ELSE}
Quick.Files,
{$ENDIF}
Quick.Commons,
Quick.ORM.Engine;
type
TORMDataBase = class
private
fSQLProperties : TSQLDBConnectionProperties;
fDBFileName : RawUTF8;
fDBType : TDBType;
fDBIndexes : TDBIndexArray;
fDBMappingFields : TDBMappingArray;
fFullMemoryMode : Boolean;
fModel : TSQLModel;
faRootURI : RawUTF8;
fIncludedClasses : TSQLRecordClassArray;
fSQLConnection : TSQLConnection;
fLockMode : TSQLiteLockMode;
procedure SetDBFileName(const dbfname : RawUTF8);
public
property DBType : TDBType read fDBType write fDBType;
property DBFileName : RawUTF8 read fDBFileName write SetDBFileName;
property DBIndexes : TDBIndexArray read fDBIndexes write fDBIndexes;
property DBMappingFields : TDBMappingArray read fDBMappingFields write fDBMappingFields;
property Model : TSQLModel read fModel write fModel;
property FullMemoryMode : Boolean read fFullMemoryMode write fFullMemoryMode;
property LockMode : TSQLiteLockMode read fLockMode write fLockMode;
property aRootURI : RawUTF8 read faRootURI write faRootURI;
property IncludedClasses : TSQLRecordClassArray read fIncludedClasses write fIncludedClasses;
property SQLProperties : TSQLDBConnectionProperties read fSQLProperties write fSQLProperties;
property SQLConnection : TSQLConnection read fSQLConnection write fSQLConnection;
constructor Create;
destructor Destroy; override;
end;
implementation
{TORMDataBase Class}
constructor TORMDataBase.Create;
begin
fDBType := dtSQLite;
fModel := nil;
faRootURI := 'root';
fDBFileName := '.\default.db3';
fSQLConnection := TSQLConnection.Create;
fSQLConnection.Provider := TDBProvider.dbMSSQL;
fLockMode := TSQLiteLockMode.lmNormal;
end;
destructor TORMDataBase.Destroy;
begin
if Assigned(fModel) then fModel.Free;
if Assigned(fSQLConnection) then fSQLConnection.Free;
inherited;
end;
procedure TORMDataBase.SetDBFileName(const dbfname : RawUTF8);
begin
//if dbfile not found, sets as current app dir
if (CompareText(dbfname,'SQLITE_MEMORY_DATABASE_NAME') = 0) or TFile.Exists(dbfname) then fDBFileName := dbfname
else fDBFileName := Format('%s\%s',[path.EXEPATH,TPath.GetFileName(dbfname)]);
end;
end.
|
unit Car;
interface
type
TCar = class(TObject)
public
constructor Create(make:String);
function getGreeting() : String;
private
greeting : String;
end;
implementation
constructor TCar.Create(make:String);
begin
Self.greeting := 'I am an ' + make;
end;
function TCar.getGreeting() : String;
begin
Result := Self.greeting;
end;
end.
|
unit FProgress;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, StdCtrls, Buttons;
type
TFormProgress = class(TForm)
memoLog: TMemo;
PB: TProgressBar;
bbCancel: TBitBtn;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure bbCancelClick(Sender: TObject);
procedure FormResize(Sender: TObject);
private
FThread: TThread;
{ Private declarations }
public
procedure Log( const pMessage : string; pAppendToPrevRow: boolean ) ;
procedure UpdateProgress( piMax, piPos : integer ) ;
property Thread : TThread read FThread write FThread ;
end;
implementation
uses
tiUtils
,tiINI
,tiDialogs
,tiFileSync_Mgr
;
{$R *.DFM}
{ TFormProgress }
procedure TFormProgress.Log(const pMessage: string; pAppendToPrevRow: boolean);
var
lIndex: Integer ;
lLine: string;
begin
if pAppendToPrevRow and ( MemoLog.Lines.Count > 0 ) then
begin
lIndex := memoLog.Lines.Count-1 ;
lLine := MemoLog.Lines[lIndex] + ' ' + pMessage;
MemoLog.Lines[lIndex] := lLine;
end else
MemoLog.Lines.Add(pMessage)
end;
procedure TFormProgress.FormCreate(Sender: TObject);
begin
gReg.ReadFormState( self ) ;
end;
procedure TFormProgress.FormDestroy(Sender: TObject);
begin
gReg.WriteFormState( self ) ;
end;
procedure TFormProgress.bbCancelClick(Sender: TObject);
begin
Assert( Assigned( FThread ), 'FThread not assigned' ) ;
Assert( FThread is TthrdFileSyncMgr, 'FThread not a TthrdFileSyncMgr' ) ;
if tiAppConfirmation(
'Are you sure you want to terminate this process?' ) then
begin
bbCancel.Enabled := false ;
TthrdFileSyncMgr(FThread).CustomTerminate ;
end ;
end;
procedure TFormProgress.FormResize(Sender: TObject);
begin
bbCancel.Left := ( ClientWidth - bbCancel.Width ) div 2 ;
end;
procedure TFormProgress.UpdateProgress(piMax, piPos: integer);
begin
if PB.Max <> piMax then
PB.Max := piMax ;
if PB.Position <> piPos then
PB.Position := piPos ;
end;
end.
|
unit PayloadEndpoint;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Payload;
type
IPayloadEndpoint = interface(IInterface) ['{DBDD30FF-4F98-4DBC-9827-0B77FC95D82B}']
function All: IPayloadList;
function One(const Id: string): IPayload;
end;
function NewPayloadEndpoint: IPayloadEndpoint;
implementation
uses
Endpoint_Helper;
const
Endpoint = 'payloads/';
type
{ IPayloadEndpoint }
TPayloadEndpoint = class(TInterfacedObject, IPayloadEndpoint)
function All: IPayloadList;
function One(const Id: string): IPayload;
end;
function NewPayloadEndpoint: IPayloadEndpoint;
begin
Result := TPayloadEndpoint.Create;
end;
{ IPayloadEndpoint }
function TPayloadEndpoint.All: IPayloadList;
begin
Result := NewPayloadList;
EndpointToModel(Endpoint, Result);
end;
function TPayloadEndpoint.One(const Id: string): IPayload;
begin
Result := NewPayload;
EndpointToModel(SysUtils.ConcatPaths([Endpoint, Id]), Result);
end;
end.
|
unit PrinterInterface;
interface
type
IPrinter = interface
function PrintText(const AText : WideString): boolean;
function SerialNumber:String;
function LengNoFiscalText : integer;
end;
implementation
end.
|
unit uEmployee;
interface
uses
uPerson;
type
TEmployee = class(TPerson)
private
FDepartment: Integer;
FSurename: string;
FfirstName: string;
procedure SetDepartment(const Value: Integer);
procedure SetfirstName(const Value: string);
procedure SetSurename(const Value: string);
published
property department: Integer read FDepartment write SetDepartment;
property firstName: string read FfirstName write SetfirstName;
property surename : string read FSurename write SetSurename ;
end;
implementation
{ TEmployee }
procedure TEmployee.SetDepartment(const Value: Integer);
begin
FDepartment := Value;
end;
procedure TEmployee.SetfirstName(const Value: string);
begin
FfirstName := Value;
end;
procedure TEmployee.SetSurename(const Value: string);
begin
FSurename := Value;
end;
end.
|
unit u_DoublePointsAggregator;
interface
uses
t_GeoTypes,
i_DoublePointsAggregator;
type
TDoublePointsAggregator = class(TInterfacedObject, IDoublePointsAggregator)
private
FPoints: array of TDoublePoint;
FCount: Integer;
FCapacity: Integer;
private
procedure Add(const APoint: TDoublePoint);
procedure AddPoints(
const APoints: PDoublePointArray;
ACount: Integer
);
procedure Clear;
function GetCount: Integer;
function GetPoints: PDoublePointArray;
public
constructor Create;
destructor Destroy; override;
end;
implementation
{ TDoublePointsAggregator }
constructor TDoublePointsAggregator.Create;
begin
inherited Create;
FCount := 0;
end;
destructor TDoublePointsAggregator.Destroy;
begin
FPoints := nil;
FCount := 0;
FCapacity := 0;
inherited;
end;
procedure TDoublePointsAggregator.Add(const APoint: TDoublePoint);
var
VSize: Integer;
begin
if FCount >= FCapacity then begin
if FCapacity < 256 then begin
VSize := 256;
end else if FCapacity < 4 * 1024 then begin
VSize := FCapacity * 2;
end else begin
VSize := FCapacity + 4 * 1024;
end;
SetLength(FPoints, VSize);
FCapacity := VSize;
end;
FPoints[FCount] := APoint;
Inc(FCount);
end;
procedure TDoublePointsAggregator.AddPoints(
const APoints: PDoublePointArray;
ACount: Integer
);
var
VNewCount: Integer;
VSize: Integer;
begin
if ACount > 0 then begin
VNewCount := FCount + ACount;
if VNewCount > FCapacity then begin
VSize := FCapacity;
while VNewCount > VSize do begin
if VSize < 256 then begin
VSize := 256;
end else if VSize < 4 * 1024 then begin
VSize := VSize * 2;
end else begin
VSize := VSize + 4 * 1024;
end;
end;
SetLength(FPoints, VSize);
FCapacity := VSize;
end;
Move(APoints[0], FPoints[FCount], ACount * SizeOf(TDoublePoint));
FCount := VNewCount;
end;
end;
procedure TDoublePointsAggregator.Clear;
begin
FCount := 0;
end;
function TDoublePointsAggregator.GetCount: Integer;
begin
Result := FCount;
end;
function TDoublePointsAggregator.GetPoints: PDoublePointArray;
begin
Result := @FPoints[0];
end;
end.
|
{-------------------------------------------------------------------------------
The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
the specific language governing rights and limitations under the License.
The Original Code is: SynEditHighlighter.pas, released 2000-04-07.
The Original Code is based on mwHighlighter.pas by Martin Waldenburg, part of
the mwEdit component suite.
Portions created by Martin Waldenburg are Copyright (C) 1998 Martin Waldenburg.
All Rights Reserved.
Contributors to the SynEdit and mwEdit projects are listed in the
Contributors.txt file.
$Id: synedithighlighter.pp 19051 2009-03-21 00:47:33Z martin $
You may retrieve the latest version of this file at the SynEdit home page,
located at http://SynEdit.SourceForge.net
-------------------------------------------------------------------------------}
(* Naming Conventions:
- FoldBlock:
A continuous range of lines, that can (optional) be folded.
Which Foldblocks can be folded is decided by the Highlighter. It may be
configurable.
A Foldblock can contain other Foldbloccks (nested), but two Foldblocks can
not overlap.
- FoldBlockLevel (FoldBlockNestLevel):
The amount of FoldBlocks in which a line (or a point of text) is.
- FoldGroup:
An independent set of FoldBlocks. FoldBlocks in different Groups may overlap.
(e.g. IFDEF/REGION in the SynPasSyn allow for overlaps, rather than strict nesting)
Some older code use "FoldType" instead
- FoldNode
Start or End of a FoldBlock
*)
(* TODO : Workaround for bug #20850
Remove when FPC 2.6.2 is out
*)
{$IFDEF CPU64}
{$IF (FPC_FULLVERSION = 20600) or (FPC_FULLVERSION = 20501)}
{$DEFINE ISSUE_20850 }
{$ENDIF}
{$ENDIF}
unit SynEditHighlighterFoldBase;
{$I synedit.inc}
interface
uses
SysUtils, Classes, math, LCLProc, SynEditHighlighter, SynEditTypes,
AvgLvlTree, LazClasses;
const
NullRange = TSynEditRange(nil);
type
TSynFoldAction = ( sfaOpen, // Any Opening node
sfaClose, // Any Closing node
sfaFold, // Part of a fold- or hide-able block (FoldConf.Enabled = True) - excludes one=liners for FoldFold, as they can not fold
sfaFoldFold, // Part of a fold-able block (FoldConf.Enabled = True / smFold in Modes) - excludes one=liners / only opening node, except ifdef/region (todo: maybe both?)
sfaFoldHide, // Part of a hide-able block (FoldConf.Enabled = True / smHide in Modes) - includes one=liners / only opening node, except ifdef/region (todo: maybe both?)
sfaMultiLine, // The closing node is on an other line
sfaSingleLine, // The closing node is on the same line (though the keyword may be on the next)
// //sfaSingleLineClosedByNext
sfaCloseForNextLine, // Fold closes this line, but keyword is on the next (e.g. "var" block)
sfaLastLineClose, // Fold is incomplete, and closed at last line of file
sfaDefaultCollapsed,
sfaMarkup, // This node can be highlighted, by the matching Word-Pair Markup
sfaOutline, // This node will be higlighted by nested color replacing the token color
sfaOutlineKeepLevel, // Direct children should not increase color dept. (But grandchild can.) e.g. "if","then" any "procedure"
sfaOutlineMergeParent,// This node want to decrease current color depth. (But Previous sibling increased) e.g. "except", "finally"
sfaOutlineForceIndent, // Node will temporary ignore sfaOutlineKeep. (Next sibling can.) e.g in NESTED "procedure"
sfaOutlineNoColor, // Node will not painted by nested-coloring, but may increase color (e.g. any "procedure")
sfaOutlineNoLine, // Node doesn't want to have vertical line. (e.g. "then")
sfaInvalid, // Wrong Index
// TODO: deprecate
sfaOpenFold, // At this node a new Fold can start // Actually, includes all,any multiline node too.
sfaCloseFold, // At this node a fold ends
sfaOneLineOpen, // Open, but closes on same line; *only* if hide-able has [sfaOpenFold, sfaFold]; always has [sfaFoldFold, sfaFoldHide]
sfaOneLineClose // Open, but closes on same line;
);
TSynFoldActions = set of TSynFoldAction;
(* TSynFoldBlockFilter
used to specify which folds to include for:
- FoldOpenCount, FoldCloseCount, FoldNestCount
- maybe in future TLazSynFoldNodeInfoList
TLazSynFoldNodeInfoList has additional filters
TLazSynFoldNodeInfoList always uses the full set (sfbIncludeDisabled)
A Highlighter is not required to implement this, or can choose to implement
a subset only. For any field/value a Highlighter may simple assume default.
- Highlighter that have only one "FoldGroup" do not require this.
- Highlighter that do not store foldblocks that are unavailable (e.g. off by
config) always return the same set
Using a record, as argument is the virtual methods, allows one to add further
fields/values, without breaking inheritance.
New fields values are expected to be ignored (handled as default) by existing
highlighter.
Callers of the method can:
- use InitFoldBlockFilter to make sure all fields are set to default
- use (none virtual) wrapper methods
*)
TSynFoldBlockFilterFlag = (
sfbIncludeDisabled // Foldable by config = off
);
TSynFoldBlockFilterFlags = set of TSynFoldBlockFilterFlag;
TSynFoldBlockFilter = record
FoldGroup: integer;
Flags: TSynFoldBlockFilterFlags;
end;
procedure InitFoldBlockFilter(out AFilter: TSynFoldBlockFilter;
AFoldGroup: Integer = 0; AFlag: TSynFoldBlockFilterFlags = []);
type
TSynCustomFoldHighlighter = class;
TSynFoldNodeInfo = record
LineIndex: Integer;
NodeIndex: Integer; // Indicates the position within the list of info nodes (depends on search-Filter)
AllNodeIndex: Integer; // Indicates the position within the unfiltered list of info nodes
LogXStart, LogXEnd: Integer; // -1 previous line ( 0-based)
FoldLvlStart, FoldLvlEnd: Integer; // FoldLvl within each FoldGroup
NestLvlStart, NestLvlEnd: Integer; // include disabled nodes, e.g markup (within each FoldGroup)
FoldAction: TSynFoldActions;
FoldType: Pointer; // e.g.cfbtBeginEnd, cfbtProcedure ...
FoldTypeCompatible: Pointer; // map outer and inner begin, and other exchangeable types
FoldGroup: Integer; // independend/overlapping folds, e.g begin/end; ifdef, region
end;
PSynFoldNodeInfo = ^TSynFoldNodeInfo;
{ TLazSynFoldNodeInfoList }
TLazSynFoldNodeInfoList = class(TRefCountedObject)
private
FHighLighter: TSynCustomFoldHighlighter;
FValid: Boolean;
FActionFilter: TSynFoldActions;
FGroupFilter: Integer;
FLine: TLineIdx;
FNodeCount: Integer;
FFilteredCount, FFilteredProgress: Integer;
FNodeInfoList: Array of TSynFoldNodeInfo;
FFilteredList: Array of TSynFoldNodeInfo;
function GetItem(Index: Integer): TSynFoldNodeInfo;
procedure SetActionFilter(AValue: TSynFoldActions);
procedure SetGroupFilter(AValue: Integer);
function GetItemPointer(AnIndex: Integer): PSynFoldNodeInfo;
function GetLastItemPointer: PSynFoldNodeInfo;
protected
procedure Invalidate;
procedure Clear;
procedure ClearData;
procedure ClearFilteredList;
procedure DoFilter(MinIndex: Integer = -1);
procedure SetLine(ALine: TLineIdx); // Does not clear anything, if line has not changed.
procedure SetLineClean(ALine: TLineIdx); // Does not clear anything, if line has not changed.
property HighLighter: TSynCustomFoldHighlighter read FHighLighter write FHighLighter;
public
// used by HighLighters to add data
procedure Add(const AnInfo: TSynFoldNodeInfo);
procedure Delete(AnIndex: Integer = -1);
function CountAll: Integer;
property ItemPointer[AnIndex: Integer]: PSynFoldNodeInfo read GetItemPointer;
property LastItemPointer: PSynFoldNodeInfo read GetLastItemPointer;
protected
function DefaultGroup: Integer; virtual;
function MinCapacity: Integer; virtual;
procedure InvalidateNode(out AnInfo: TSynFoldNodeInfo);
function Match(const AnInfo: TSynFoldNodeInfo;
AnActionFilter: TSynFoldActions; AGroupFilter: Integer = 0): Boolean; virtual;
public
// filtered items
procedure ClearFilter;
function Count: Integer;
property Item[Index: Integer]: TSynFoldNodeInfo read GetItem; default;
property ActionFilter: TSynFoldActions read FActionFilter write SetActionFilter;
property GroupFilter: Integer read FGroupFilter write SetGroupFilter;
public
// all items / filtered on the fly
function CountEx (AnActionFilter: TSynFoldActions; AGroupFilter: Integer = 0): Integer;
function NodeInfoEx(Index: Integer; AnActionFilter: TSynFoldActions; AGroupFilter: Integer = 0): TSynFoldNodeInfo; virtual;
public
// Only allowed to be set, if highlighter has CurrentLines (and is scanned)
property Line: TLineIdx read FLine write SetLine;
end;
TSynCustomFoldConfigMode = (fmFold, fmHide, fmMarkup, fmOutline);
TSynCustomFoldConfigModes = set of TSynCustomFoldConfigMode;
{ TSynCustomFoldConfig }
TSynCustomFoldConfig = class(TPersistent)
private
FEnabled: Boolean;
FFoldActions: TSynFoldActions;
FModes: TSynCustomFoldConfigModes;
FOnChange: TNotifyEvent;
FSupportedModes: TSynCustomFoldConfigModes;
procedure SetEnabled(const AValue: Boolean);
procedure SetModes(AValue: TSynCustomFoldConfigModes);
procedure SetSupportedModes(AValue: TSynCustomFoldConfigModes);
protected
procedure DoOnChange;
public
constructor Create;
procedure Assign(Src: TSynCustomFoldConfig); reintroduce; virtual;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
property SupportedModes: TSynCustomFoldConfigModes
read FSupportedModes write SetSupportedModes;
// Actions representing the modes
property FoldActions: TSynFoldActions read FFoldActions;
published
property Enabled: Boolean read FEnabled write SetEnabled;
property Modes: TSynCustomFoldConfigModes read FModes write SetModes default [fmFold];
end;
{ TSynCustomCodeFoldBlock }
TSynCustomCodeFoldBlock = class
private
FBlockType: Pointer;
FFoldable: boolean;
FParent, FChildren: TSynCustomCodeFoldBlock;
FRight, FLeft: TSynCustomCodeFoldBlock;
FBalance: Integer;
function GetChild(ABlockType: Pointer): TSynCustomCodeFoldBlock;
protected
function GetOrCreateSibling(ABlockType: Pointer): TSynCustomCodeFoldBlock;
property Right: TSynCustomCodeFoldBlock read FRight;
property Left: TSynCustomCodeFoldBlock read FLeft;
property Children: TSynCustomCodeFoldBlock read FChildren;
public
destructor Destroy; override;
procedure WriteDebugReport;
public
procedure InitRootBlockType(AType: Pointer);
property BlockType: Pointer read FBlockType;
property Foldable : boolean read FFoldable write FFoldable;
property Parent: TSynCustomCodeFoldBlock read FParent;
property Child[ABlockType: Pointer]: TSynCustomCodeFoldBlock read GetChild;
end;
{ TSynCustomHighlighterRange }
TSynCustomHighlighterRange = class
private
FCodeFoldStackSize: integer; // EndLevel
FNestFoldStackSize: integer; // EndLevel
FMinimumCodeFoldBlockLevel: integer;
FMinimumNestFoldBlockLevel: integer;
FRangeType: Pointer;
FTop: TSynCustomCodeFoldBlock;
public
constructor Create(Template: TSynCustomHighlighterRange); virtual;
destructor Destroy; override;
function Compare(Range: TSynCustomHighlighterRange): integer; virtual;
function Add(ABlockType: Pointer = nil; IncreaseLevel: Boolean = True):
TSynCustomCodeFoldBlock; virtual;
procedure Pop(DecreaseLevel: Boolean = True); virtual;
function MaxFoldLevel: Integer; virtual;
procedure Clear; virtual;
procedure Assign(Src: TSynCustomHighlighterRange); virtual;
procedure WriteDebugReport;
property FoldRoot: TSynCustomCodeFoldBlock read FTop write FTop;
public
property RangeType: Pointer read FRangeType write FRangeType;
property CodeFoldStackSize: integer read FCodeFoldStackSize; // excl disabled, only IncreaseLevel
property MinimumCodeFoldBlockLevel: integer
read FMinimumCodeFoldBlockLevel write FMinimumCodeFoldBlockLevel;
property NestFoldStackSize: integer read FNestFoldStackSize; // all, incl disabled (not IncreaseLevel)
property MinimumNestFoldBlockLevel: integer
read FMinimumNestFoldBlockLevel; // write FMinimumNestFoldBlockLevel;
property Top: TSynCustomCodeFoldBlock read FTop;
end;
TSynCustomHighlighterRangeClass = class of TSynCustomHighlighterRange;
TSynCustomHighlighterRanges = class;
{ TSynCustomFoldHighlighter }
TSynCustomFoldHighlighter = class(TSynCustomHighlighter)
protected
// Fold Config
FFoldConfig: Array of TSynCustomFoldConfig;
function GetFoldConfig(Index: Integer): TSynCustomFoldConfig; virtual;
procedure SetFoldConfig(Index: Integer; const AValue: TSynCustomFoldConfig); virtual;
function GetFoldConfigCount: Integer; virtual;
function GetFoldConfigInternalCount: Integer; virtual;
function GetFoldConfigInstance(Index: Integer): TSynCustomFoldConfig; virtual;
procedure InitFoldConfig;
procedure DestroyFoldConfig;
procedure DoFoldConfigChanged(Sender: TObject); virtual;
private
FCodeFoldRange: TSynCustomHighlighterRange;
FIsCollectingNodeInfo: boolean;
fRanges: TSynCustomHighlighterRanges;
FRootCodeFoldBlock: TSynCustomCodeFoldBlock;
FFoldNodeInfoList: TLazSynFoldNodeInfoList;
FCollectingNodeInfoList: TLazSynFoldNodeInfoList;
procedure ClearFoldNodeList;
protected
// "Range"
function GetRangeClass: TSynCustomHighlighterRangeClass; virtual;
procedure CreateRootCodeFoldBlock; virtual; // set RootCodeFoldBlock
property CodeFoldRange: TSynCustomHighlighterRange read FCodeFoldRange;
function TopCodeFoldBlockType(DownIndex: Integer = 0): Pointer;
property RootCodeFoldBlock: TSynCustomCodeFoldBlock read FRootCodeFoldBlock
write FRootCodeFoldBlock;
// Open/Close Folds
function StartCodeFoldBlock(ABlockType: Pointer = nil;
IncreaseLevel: Boolean = true): TSynCustomCodeFoldBlock; virtual;
procedure EndCodeFoldBlock(DecreaseLevel: Boolean = True); virtual;
procedure CollectNodeInfo(FinishingABlock : Boolean; ABlockType: Pointer;
LevelChanged: Boolean); virtual;
procedure DoInitNode(out Node: TSynFoldNodeInfo;
FinishingABlock: Boolean;
ABlockType: Pointer; aActions: TSynFoldActions;
AIsFold: Boolean); virtual;
procedure RepairSingleLineNode(var Node: TSynFoldNodeInfo); virtual;
procedure GetTokenBounds(out LogX1,LogX2: Integer); virtual;
// Info about Folds
function CreateFoldNodeInfoList: TLazSynFoldNodeInfoList; virtual;
function GetFoldNodeInfo(Line: TLineIdx): TLazSynFoldNodeInfoList;
procedure InitFoldNodeInfo(AList: TLazSynFoldNodeInfoList; Line: TLineIdx); virtual;
// Info about Folds, on currently set line/range (simply forwarding to range
function MinimumCodeFoldBlockLevel: integer; virtual;
function CurrentCodeFoldBlockLevel: integer; virtual;
property IsCollectingNodeInfo : boolean read FIsCollectingNodeInfo write FIsCollectingNodeInfo;
property CollectingNodeInfoList : TLazSynFoldNodeInfoList read FCollectingNodeInfoList;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
class function GetCapabilities: TSynHighlighterCapabilities; override;
function GetRange: Pointer; override;
// Info about Folds
function FoldBlockOpeningCount(ALineIndex: TLineIdx;
const AFilter: TSynFoldBlockFilter): integer; virtual; overload;
function FoldBlockClosingCount(ALineIndex: TLineIdx;
const AFilter: TSynFoldBlockFilter): integer; virtual; overload;
function FoldBlockEndLevel(ALineIndex: TLineIdx;
const AFilter: TSynFoldBlockFilter): integer; virtual; overload;
function FoldBlockMinLevel(ALineIndex: TLineIdx;
const AFilter: TSynFoldBlockFilter): integer; virtual; overload;
(* All nested FoldType (cfbtBegin) if available. Similar to TopCodeFoldBlockType
- Index=0 is most outer / Index=FoldBlockEndLevel is most inner (TopCodeFoldBlockType 0=inner)
- False, if it can not be determined for the filter settings
*)
function FoldBlockNestedTypes(ALineIndex: TLineIdx; ANestIndex: Integer; out AType: Pointer;
const AFilter: TSynFoldBlockFilter): boolean; virtual; overload;
function FoldBlockOpeningCount(ALineIndex: TLineIdx; AFoldGroup: integer = 0;
AFlags: TSynFoldBlockFilterFlags = []): integer; overload;
function FoldBlockClosingCount(ALineIndex: TLineIdx; AFoldGroup: integer = 0;
AFlags: TSynFoldBlockFilterFlags = []): integer; overload;
function FoldBlockEndLevel(ALineIndex: TLineIdx; AFoldGroup: integer = 0;
AFlags: TSynFoldBlockFilterFlags = []): integer; overload;
function FoldBlockMinLevel(ALineIndex: TLineIdx; AFoldGroup: integer = 0;
AFlags: TSynFoldBlockFilterFlags = []): integer; overload;
function FoldBlockNestedTypes(ALineIndex: TLineIdx; ANestIndex: Integer; out AType: Pointer;
AFoldGroup: integer = 0;
AFlags: TSynFoldBlockFilterFlags = []): boolean; virtual; overload;
function FoldOpenCount(ALineIndex: Integer; AType: Integer = 0): integer; deprecated;
function FoldCloseCount(ALineIndex: Integer; AType: Integer = 0): integer; deprecated;
function FoldNestCount(ALineIndex: Integer; AType: Integer = 0): integer; deprecated;
function FoldTypeCount: integer; virtual;
function FoldTypeAtNodeIndex(ALineIndex, FoldIndex: Integer;
UseCloseNodes: boolean = false): integer; virtual; // TODO: could be deprecated ./ only child-classes
function FoldLineLength(ALineIndex, FoldIndex: Integer): integer; virtual;
function FoldEndLine(ALineIndex, FoldIndex: Integer): integer; virtual; // FoldEndLine, can be more than given by FoldLineLength, since Length my cut off early
// All fold-nodes
// FoldNodeInfo: Returns a shared object
// Adding RefCount, will prevent others from getting further copies, but not from using copies they already have.
// If not adding refcount, the object should not be stored/re-used
// Not adding ref-count, should only be done for CountEx, NodeInfoEx
property FoldNodeInfo[Line: TLineIdx]: TLazSynFoldNodeInfoList read GetFoldNodeInfo;
procedure SetRange(Value: Pointer); override;
procedure ResetRange; override;
procedure SetLine(const NewValue: String;
LineNumber:Integer // 0 based
); override;
procedure DoCurrentLinesChanged; override;
function PerformScan(StartIndex, EndIndex: Integer; ForceEndIndex: Boolean =
False): Integer; override;
public
property FoldConfig[Index: Integer]: TSynCustomFoldConfig
read GetFoldConfig write SetFoldConfig;
property FoldConfigCount: Integer read GetFoldConfigCount;
end;
{ TSynCustomHighlighterRanges }
TSynCustomHighlighterRanges = class
private
FAllocatedCount: integer;
FHighlighterClass: TSynCustomHighlighterClass;
FItems: TAvgLvlTree;
public
constructor Create(TheHighlighterClass: TSynCustomHighlighterClass);
destructor Destroy; override;
function GetEqual(Range: TSynCustomHighlighterRange
): TSynCustomHighlighterRange;
procedure Allocate;
procedure Release;
property HighlighterClass: TSynCustomHighlighterClass read FHighlighterClass;
property AllocatedCount: integer read FAllocatedCount;
end;
function CompareSynHighlighterRanges(Data1, Data2: Pointer): integer;
function AllocateHighlighterRanges(
HighlighterClass: TSynCustomHighlighterClass): TSynCustomHighlighterRanges;
function dbgs(AFoldActions: TSynFoldActions): String; overload;
function dbgs(ANode: TSynFoldNodeInfo):string; overload;
implementation
procedure InitFoldBlockFilter(out AFilter: TSynFoldBlockFilter; AFoldGroup: Integer;
AFlag: TSynFoldBlockFilterFlags = []);
begin
AFilter.FoldGroup := AFoldGroup;
AFilter.Flags := AFlag;
end;
function CompareSynHighlighterRanges(Data1, Data2: Pointer): integer;
var
Range1: TSynCustomHighlighterRange;
Range2: TSynCustomHighlighterRange;
begin
Range1:=TSynCustomHighlighterRange(Data1);
Range2:=TSynCustomHighlighterRange(Data2);
Result:=Range1.Compare(Range2);
end;
var
HighlighterRanges: TFPList = nil;
function IndexOfHighlighterRanges(
HighlighterClass: TSynCustomHighlighterClass): integer;
begin
if HighlighterRanges=nil then
Result:=-1
else begin
Result:=HighlighterRanges.Count-1;
while (Result>=0)
and (TSynCustomHighlighterRanges(HighlighterRanges[Result]).HighlighterClass
<>HighlighterClass)
do
dec(Result);
end;
end;
function AllocateHighlighterRanges(
HighlighterClass: TSynCustomHighlighterClass): TSynCustomHighlighterRanges;
var
i: LongInt;
begin
if HighlighterRanges=nil then HighlighterRanges:=TFPList.Create;
i:=IndexOfHighlighterRanges(HighlighterClass);
if i>=0 then begin
Result:=TSynCustomHighlighterRanges(HighlighterRanges[i]);
Result.Allocate;
end else begin
Result:=TSynCustomHighlighterRanges.Create(HighlighterClass);
HighlighterRanges.Add(Result);
end;
end;
function dbgs(AFoldActions: TSynFoldActions): String;
var
i: TSynFoldAction;
s: string;
begin
Result:='';
for i := low(TSynFoldAction) to high(TSynFoldAction) do
if i in AFoldActions then begin
WriteStr(s{%H-}, i);
Result := Result + s + ',';
end;
if Result <> '' then Result := '[' + copy(Result, 1, Length(Result)-1) + ']';
end;
function dbgs(ANode: TSynFoldNodeInfo): string;
begin
with ANode do
if sfaInvalid in FoldAction then
Result := Format('L=%3d I=%d X=%2d-%2d Fld=%d-%d Nst=%d-%d FT=%d FTC=%d Grp=%d A=%s',
[LineIndex, NodeIndex, 0, 0, 0, 0, 0, 0, 0, 0, 0, dbgs(FoldAction)])
else
Result := Format('L=%3d I=%d X=%2d-%2d Fld=%d-%d Nst=%d-%d FT=%d FTC=%d Grp=%d A=%s',
[LineIndex, NodeIndex, LogXStart, LogXEnd,
FoldLvlStart, FoldLvlEnd, NestLvlStart, NestLvlEnd,
PtrUInt(FoldType), PtrUInt(FoldTypeCompatible), FoldGroup,
dbgs(FoldAction)]);
end;
{ TLazSynFoldNodeInfoList }
function TLazSynFoldNodeInfoList.GetItem(Index: Integer): TSynFoldNodeInfo;
begin
DoFilter(Index);
if (Index >= FFilteredCount) or (Index < 0) or (not FValid) then
InvalidateNode(Result)
else begin
Result := FFilteredList[Index];
Result.NodeIndex := Index; // only set copy on result
end;
end;
procedure TLazSynFoldNodeInfoList.SetActionFilter(AValue: TSynFoldActions);
begin
if FActionFilter=AValue then Exit;
FActionFilter:=AValue;
ClearFilteredList;
end;
procedure TLazSynFoldNodeInfoList.SetGroupFilter(AValue: Integer);
begin
if FGroupFilter=AValue then Exit;
FGroupFilter:=AValue;
ClearFilteredList;
end;
procedure TLazSynFoldNodeInfoList.Clear;
begin
ClearFilter;
ClearData;
end;
procedure TLazSynFoldNodeInfoList.ClearData;
var
c: Integer;
begin
FValid := True;
ClearFilteredList;
FLine := -1;
c := MinCapacity;
FNodeCount := 0;
if Length(FNodeInfoList) > c then
SetLength(FNodeInfoList, c);
end;
procedure TLazSynFoldNodeInfoList.ClearFilteredList;
begin
SetLength(FFilteredList, 0);
FFilteredCount := 0;
FFilteredProgress := 0; // next to be filtered
end;
procedure TLazSynFoldNodeInfoList.ClearFilter;
begin
ClearFilteredList;
FGroupFilter := 0;
FActionFilter := [];
end;
procedure TLazSynFoldNodeInfoList.DoFilter(MinIndex: Integer = -1);
begin
if FFilteredProgress = FNodeCount then exit;
if (MinIndex >= 0) and (FFilteredCount > MinIndex) or (not FValid) then exit;
if (FActionFilter = []) and (FGroupFilter = DefaultGroup) then begin
FFilteredList := FNodeInfoList;
FFilteredCount := FNodeCount;
FFilteredProgress := FNodeCount;
exit;
end;
if Length(FFilteredList) < Length(FNodeInfoList) then
SetLength(FFilteredList, Length(FNodeInfoList));
while FFilteredProgress < FNodeCount do begin
if Match(FNodeInfoList[FFilteredProgress], FActionFilter, FGroupFilter)
then begin
FFilteredList[FFilteredCount] := FNodeInfoList[FFilteredProgress];
inc(FFilteredCount);
end;
inc(FFilteredProgress);
if (MinIndex >= 0) and (FFilteredCount > MinIndex) then break;
end;
end;
procedure TLazSynFoldNodeInfoList.SetLine(ALine: TLineIdx);
begin
if (FLine = ALine) or (ALine < 0) then exit;
ClearData;
FLine := ALine;
FHighLighter.InitFoldNodeInfo(Self, FLine);
end;
procedure TLazSynFoldNodeInfoList.SetLineClean(ALine: TLineIdx);
begin
if (FLine = ALine) or (ALine < 0) then exit;
Clear;
FLine := ALine;
FHighLighter.InitFoldNodeInfo(Self, FLine);
end;
function TLazSynFoldNodeInfoList.MinCapacity: Integer;
begin
Result := 8;
end;
procedure TLazSynFoldNodeInfoList.InvalidateNode(out AnInfo: TSynFoldNodeInfo);
begin
AnInfo.FoldAction := [sfaInvalid];
AnInfo.LineIndex := Line;
AnInfo.NodeIndex := -1;
end;
procedure TLazSynFoldNodeInfoList.Add(const AnInfo: TSynFoldNodeInfo);
var
c: Integer;
begin
if FNodeCount >= Length(FNodeInfoList) - 1 then begin
c := MinCapacity;
if c <= 0 then c := 8;
SetLength(FNodeInfoList, Max(Length(FNodeInfoList) * 2, c));
end;
FNodeInfoList[FNodeCount] := AnInfo;
FNodeInfoList[FNodeCount].AllNodeIndex := FNodeCount;
inc(FNodeCount);
end;
procedure TLazSynFoldNodeInfoList.Delete(AnIndex: Integer = -1);
begin
if AnIndex > 0 then begin
while (AnIndex < FNodeCount) do begin
FNodeInfoList[AnIndex] := FNodeInfoList[AnIndex + 1];
FNodeInfoList[AnIndex].AllNodeIndex := AnIndex;
inc(AnIndex);
end;
end;
if FNodeCount > 0 then
dec(FNodeCount);
end;
function TLazSynFoldNodeInfoList.CountAll: Integer;
begin
if FValid then
Result := FNodeCount
else
Result := -1;
end;
function TLazSynFoldNodeInfoList.GetItemPointer(AnIndex: Integer
): PSynFoldNodeInfo;
begin
if (AnIndex >= FNodeCount) or (AnIndex < 0) then
Result := nil
else
Result := @FNodeInfoList[AnIndex];
end;
function TLazSynFoldNodeInfoList.GetLastItemPointer: PSynFoldNodeInfo;
begin
if FNodeCount < 0 then
Result := nil
else
Result := @FNodeInfoList[FNodeCount-1];
end;
procedure TLazSynFoldNodeInfoList.Invalidate;
begin
Clear;
FValid := False;
end;
function TLazSynFoldNodeInfoList.Match(const AnInfo: TSynFoldNodeInfo;
AnActionFilter: TSynFoldActions; AGroupFilter: Integer): Boolean;
begin
Result := (AnInfo.FoldAction * AnActionFilter = AnActionFilter) and
( (AGroupFilter = 0) or (AnInfo.FoldGroup = AGroupFilter) );
end;
function TLazSynFoldNodeInfoList.DefaultGroup: Integer;
begin
Result := 0;
end;
function TLazSynFoldNodeInfoList.Count: Integer;
begin
if not FValid then exit(-1);
DoFilter(-1);
Result := FFilteredCount;
end;
function TLazSynFoldNodeInfoList.CountEx(AnActionFilter: TSynFoldActions;
AGroupFilter: Integer): Integer;
var
i: Integer;
begin
if not FValid then exit(-1);
if (AnActionFilter = []) and (AGroupFilter = DefaultGroup) then begin
Result := FNodeCount;
exit;
end;
Result := 0;
for i := 0 to FNodeCount - 1 do
if Match(FNodeInfoList[i], AnActionFilter, AGroupFilter) then inc(Result);
end;
function TLazSynFoldNodeInfoList.NodeInfoEx(Index: Integer;
AnActionFilter: TSynFoldActions; AGroupFilter: Integer): TSynFoldNodeInfo;
var
i, j: Integer;
begin
if (Index < 0) or (not FValid) then begin
InvalidateNode(Result);
exit;
end;
if (AnActionFilter = []) and (AGroupFilter = DefaultGroup) then begin
if (Index >= FNodeCount) then
InvalidateNode(Result)
else
Result := FNodeInfoList[Index];
Result.NodeIndex := Index; // only set copy on result
exit;
end;
i := 0;
j := Index;
while i < FNodeCount do begin
if Match(FNodeInfoList[i], AnActionFilter, AGroupFilter) then dec(j);
if j < 0 then begin;
Result := FNodeInfoList[i];
Result.NodeIndex := Index; // only set copy on result
exit;
end;
inc(i);
end;
InvalidateNode(Result);
end;
{ TSynCustomFoldHighlighter }
constructor TSynCustomFoldHighlighter.Create(AOwner: TComponent);
begin
SetLength(FFoldConfig, GetFoldConfigInternalCount);
InitFoldConfig;
fRanges:=AllocateHighlighterRanges(TSynCustomHighlighterClass(ClassType));
CreateRootCodeFoldBlock;
inherited Create(AOwner);
FCodeFoldRange:=GetRangeClass.Create(nil);
FCodeFoldRange.FoldRoot := FRootCodeFoldBlock;
FFoldNodeInfoList := nil;;
end;
destructor TSynCustomFoldHighlighter.Destroy;
begin
inherited Destroy;
DestroyFoldConfig;
FreeAndNil(FCodeFoldRange);
FreeAndNil(FRootCodeFoldBlock);
ReleaseRefAndNil(FFoldNodeInfoList);
fRanges.Release;
FFoldConfig := nil;
end;
class function TSynCustomFoldHighlighter.GetCapabilities: TSynHighlighterCapabilities;
begin
Result := inherited GetCapabilities + [hcCodeFolding];
end;
function TSynCustomFoldHighlighter.GetRange: Pointer;
begin
// FCodeFoldRange is the working range and changed steadily
// => return a fixed copy of the current CodeFoldRange instance,
// that can be stored by other classes (e.g. TSynEdit)
Result:=fRanges.GetEqual(FCodeFoldRange);
end;
function TSynCustomFoldHighlighter.FoldBlockOpeningCount(ALineIndex: TLineIdx;
const AFilter: TSynFoldBlockFilter): integer;
{$IFDEF ISSUE_20850}
var x : integer;
{$ENDIF}
begin
if (ALineIndex < 0) or (ALineIndex >= CurrentLines.Count) then
exit(0);
{$IFDEF ISSUE_20850}
x := FoldBlockEndLevel(ALineIndex, AFilter);
Result := FoldBlockMinLevel(ALineIndex, AFilter);
Result := x - Result;
{$ELSE}
Result := FoldBlockEndLevel(ALineIndex, AFilter) - FoldBlockMinLevel(ALineIndex, AFilter);
{$ENDIF}
end;
function TSynCustomFoldHighlighter.FoldBlockClosingCount(ALineIndex: TLineIdx;
const AFilter: TSynFoldBlockFilter): integer;
{$IFDEF ISSUE_20850}
var x : integer;
{$ENDIF}
begin
if (ALineIndex < 0) or (ALineIndex >= CurrentLines.Count) then
exit(0);
{$IFDEF ISSUE_20850}
x := FoldBlockEndLevel(ALineIndex - 1, AFilter);
Result := FoldBlockMinLevel(ALineIndex, AFilter);
Result := x - Result;
{$ELSE}
Result := FoldBlockEndLevel(ALineIndex - 1, AFilter) - FoldBlockMinLevel(ALineIndex, AFilter);
{$ENDIF}
end;
function TSynCustomFoldHighlighter.FoldBlockEndLevel(ALineIndex: TLineIdx;
const AFilter: TSynFoldBlockFilter): integer;
var
r: Pointer;
begin
Assert(CurrentRanges <> nil, 'TSynCustomFoldHighlighter.FoldBlockEndLevel requires CurrentRanges');
if (ALineIndex < 0) or (ALineIndex >= CurrentLines.Count - 1) then
exit(0);
r := CurrentRanges[ALineIndex];
if (r <> nil) and (r <> NullRange) then
Result := TSynCustomHighlighterRange(r).CodeFoldStackSize
else
Result:=0;
end;
function TSynCustomFoldHighlighter.FoldBlockMinLevel(ALineIndex: TLineIdx;
const AFilter: TSynFoldBlockFilter): integer;
var
r: Pointer;
begin
Assert(CurrentRanges <> nil, 'TSynCustomFoldHighlighter.FoldBlockMinLevelrequires CurrentRanges');
if (ALineIndex < 0) or (ALineIndex >= CurrentLines.Count - 1) then
exit(0);
r := CurrentRanges[ALineIndex];
if (r <> nil) and (r <> NullRange) then
Result := TSynCustomHighlighterRange(r).MinimumCodeFoldBlockLevel
else
Result:=0;
end;
function TSynCustomFoldHighlighter.FoldBlockNestedTypes(ALineIndex: TLineIdx;
ANestIndex: Integer; out AType: Pointer; const AFilter: TSynFoldBlockFilter): boolean;
begin
Result := False;
end;
function TSynCustomFoldHighlighter.FoldBlockOpeningCount(ALineIndex: TLineIdx;
AFoldGroup: integer; AFlags: TSynFoldBlockFilterFlags): integer;
var
Filter: TSynFoldBlockFilter;
begin
Filter.FoldGroup := AFoldGroup;
Filter.Flags := AFlags;
Result := FoldBlockOpeningCount(ALineIndex, Filter);
end;
function TSynCustomFoldHighlighter.FoldBlockClosingCount(ALineIndex: TLineIdx;
AFoldGroup: integer; AFlags: TSynFoldBlockFilterFlags): integer;
var
Filter: TSynFoldBlockFilter;
begin
Filter.FoldGroup := AFoldGroup;
Filter.Flags := AFlags;
Result := FoldBlockClosingCount(ALineIndex, Filter);
end;
function TSynCustomFoldHighlighter.FoldBlockEndLevel(ALineIndex: TLineIdx;
AFoldGroup: integer; AFlags: TSynFoldBlockFilterFlags): integer;
var
Filter: TSynFoldBlockFilter;
begin
Filter.FoldGroup := AFoldGroup;
Filter.Flags := AFlags;
Result := FoldBlockEndLevel(ALineIndex, Filter);
end;
function TSynCustomFoldHighlighter.FoldBlockMinLevel(ALineIndex: TLineIdx;
AFoldGroup: integer; AFlags: TSynFoldBlockFilterFlags): integer;
var
Filter: TSynFoldBlockFilter;
begin
Filter.FoldGroup := AFoldGroup;
Filter.Flags := AFlags;
Result := FoldBlockMinLevel(ALineIndex, Filter);
end;
function TSynCustomFoldHighlighter.FoldBlockNestedTypes(ALineIndex: TLineIdx;
ANestIndex: Integer; out AType: Pointer; AFoldGroup: integer;
AFlags: TSynFoldBlockFilterFlags): boolean;
var
Filter: TSynFoldBlockFilter;
begin
Filter.FoldGroup := AFoldGroup;
Filter.Flags := AFlags;
Result := FoldBlockNestedTypes(ALineIndex, ANestIndex, AType, Filter);
end;
procedure TSynCustomFoldHighlighter.ResetRange;
begin
FCodeFoldRange.Clear;
FCodeFoldRange.FoldRoot := FRootCodeFoldBlock;
end;
function TSynCustomFoldHighlighter.MinimumCodeFoldBlockLevel: integer;
begin
assert(FCodeFoldRange <> nil, 'MinimumCodeFoldBlockLevel requires FCodeFoldRange');
Result := FCodeFoldRange.MinimumCodeFoldBlockLevel;
end;
procedure TSynCustomFoldHighlighter.SetRange(Value: Pointer);
begin
FCodeFoldRange.Assign(TSynCustomHighlighterRange(Value));
// in case we asigned a null range
if not assigned(FCodeFoldRange.FoldRoot) then
FCodeFoldRange.FoldRoot := FRootCodeFoldBlock;
end;
procedure TSynCustomFoldHighlighter.SetLine(const NewValue: String;
LineNumber: Integer);
begin
inherited;
FCodeFoldRange.MinimumCodeFoldBlockLevel := FCodeFoldRange.FCodeFoldStackSize;
FCodeFoldRange.FMinimumNestFoldBlockLevel := FCodeFoldRange.NestFoldStackSize;
end;
procedure TSynCustomFoldHighlighter.DoCurrentLinesChanged;
begin
inherited DoCurrentLinesChanged;
ClearFoldNodeList;
end;
function TSynCustomFoldHighlighter.PerformScan(StartIndex, EndIndex: Integer;
ForceEndIndex: Boolean): Integer;
begin
ClearFoldNodeList;
Result := inherited PerformScan(StartIndex, EndIndex, ForceEndIndex);
end;
function TSynCustomFoldHighlighter.CurrentCodeFoldBlockLevel: integer;
begin
assert(FCodeFoldRange <> nil, 'MinimumCodeFoldBlockLevel requires FCodeFoldRange');
Result := FCodeFoldRange.CodeFoldStackSize;
end;
function TSynCustomFoldHighlighter.FoldOpenCount(ALineIndex: Integer; AType: Integer = 0): integer;
begin
result := FoldBlockOpeningCount(ALineIndex, AType);
end;
function TSynCustomFoldHighlighter.FoldCloseCount(ALineIndex: Integer; AType: Integer = 0): integer;
begin
result := FoldBlockClosingCount(ALineIndex, AType);
end;
function TSynCustomFoldHighlighter.FoldNestCount(ALineIndex: Integer; AType: Integer = 0): integer;
begin
Result := FoldBlockEndLevel(ALineIndex, AType);
end;
function TSynCustomFoldHighlighter.FoldTypeCount: integer;
begin
Result := 1;
end;
function TSynCustomFoldHighlighter.FoldTypeAtNodeIndex(ALineIndex, FoldIndex: Integer;
UseCloseNodes: boolean): integer;
begin
Result := 0;
end;
function TSynCustomFoldHighlighter.FoldLineLength(ALineIndex, FoldIndex: Integer): integer;
begin
Result := FoldEndLine(ALineIndex, FoldIndex);
// check if fold last line of block (not mixed "end begin")
if (FoldBlockEndLevel(Result) > FoldBlockMinLevel(Result)) then
dec(Result);
// Amount of lines, that will become invisible (excludes the cfCollapsed line)
Result := Result - ALineIndex;
end;
function TSynCustomFoldHighlighter.FoldEndLine(ALineIndex, FoldIndex: Integer): integer;
var
lvl, cnt: Integer;
e, m: Integer;
begin
cnt := CurrentLines.Count;
e := FoldBlockEndLevel(ALineIndex);
m := FoldBlockMinLevel(ALineIndex);
lvl := Min(m+1+FoldIndex, e);
Result := ALineIndex + 1;
while (Result < cnt) and (FoldBlockMinLevel(Result) >= lvl) do inc(Result);
if (Result = cnt) then
dec(Result);
end;
function TSynCustomFoldHighlighter.GetFoldConfig(Index: Integer): TSynCustomFoldConfig;
begin
Result := FFoldConfig[Index];
end;
procedure TSynCustomFoldHighlighter.SetFoldConfig(Index: Integer; const AValue: TSynCustomFoldConfig);
begin
BeginUpdate;
FFoldConfig[Index].Assign(AValue);
EndUpdate;
end;
function TSynCustomFoldHighlighter.GetFoldConfigCount: Integer;
begin
Result := 0;
end;
function TSynCustomFoldHighlighter.GetFoldConfigInternalCount: Integer;
begin
Result := 0;
end;
function TSynCustomFoldHighlighter.GetFoldConfigInstance(Index: Integer): TSynCustomFoldConfig;
begin
Result := TSynCustomFoldConfig.Create;
Result.OnChange := @DoFoldConfigChanged;
Result.Enabled := False;
end;
procedure TSynCustomFoldHighlighter.InitFoldConfig;
var
i: Integer;
begin
for i := 0 to high(FFoldConfig) do
FFoldConfig[i] := GetFoldConfigInstance(i);
end;
procedure TSynCustomFoldHighlighter.DestroyFoldConfig;
var
i: Integer;
begin
for i := 0 to high(FFoldConfig) do
FFoldConfig[i].Free;
end;
procedure TSynCustomFoldHighlighter.DoFoldConfigChanged(Sender: TObject);
begin
FAttributeChangeNeedScan := True;
DefHighlightChange(self);
end;
procedure TSynCustomFoldHighlighter.ClearFoldNodeList;
begin
if FFoldNodeInfoList <> nil then begin
if (FFoldNodeInfoList.RefCount > 1) then
ReleaseRefAndNil(FFoldNodeInfoList)
else
FFoldNodeInfoList.Clear;
end;
end;
function TSynCustomFoldHighlighter.GetFoldNodeInfo(Line: TLineIdx
): TLazSynFoldNodeInfoList;
begin
if (FFoldNodeInfoList <> nil) and (FFoldNodeInfoList.RefCount > 1) then
ReleaseRefAndNil(FFoldNodeInfoList);
if FFoldNodeInfoList = nil then begin
FFoldNodeInfoList := CreateFoldNodeInfoList;
FFoldNodeInfoList.AddReference;
FFoldNodeInfoList.HighLighter := Self;
end
else
if (CurrentRanges <> nil) and (CurrentRanges.NeedsReScanStartIndex >= 0) then
ClearFoldNodeList;
Result := FFoldNodeInfoList;
Result.SetLineClean(Line);
end;
procedure TSynCustomFoldHighlighter.InitFoldNodeInfo(AList: TLazSynFoldNodeInfoList; Line: TLineIdx);
begin
FIsCollectingNodeInfo := True;
try
FCollectingNodeInfoList := TLazSynFoldNodeInfoList(AList);
StartAtLineIndex(Line);
NextToEol;
finally
FIsCollectingNodeInfo := False;
end;
end;
function TSynCustomFoldHighlighter.CreateFoldNodeInfoList: TLazSynFoldNodeInfoList;
begin
Result := TLazSynFoldNodeInfoList.Create;
end;
function TSynCustomFoldHighlighter.GetRangeClass: TSynCustomHighlighterRangeClass;
begin
Result:=TSynCustomHighlighterRange;
end;
function TSynCustomFoldHighlighter.TopCodeFoldBlockType(DownIndex: Integer = 0): Pointer;
var
Fold: TSynCustomCodeFoldBlock;
begin
Result:=nil;
if (CodeFoldRange<>nil) then begin
Fold := CodeFoldRange.Top;
while (Fold <> nil) and (DownIndex > 0) do begin
Fold := Fold.Parent;
dec(DownIndex);
end;
if Fold <> nil then
Result := Fold.BlockType
end;
end;
procedure TSynCustomFoldHighlighter.GetTokenBounds(out LogX1, LogX2: Integer);
var p : pchar; L : integer;
begin
GetTokenEx(p,L);
LogX1 := GetTokenPos;
LogX2 := LogX1 + L ;
end;
function TSynCustomFoldHighlighter.StartCodeFoldBlock(ABlockType: Pointer;
IncreaseLevel: Boolean = True): TSynCustomCodeFoldBlock;
begin
if FIsCollectingNodeInfo then
CollectNodeInfo(False, ABlockType, IncreaseLevel);
Result:=CodeFoldRange.Add(ABlockType, IncreaseLevel);
end;
procedure TSynCustomFoldHighlighter.EndCodeFoldBlock(DecreaseLevel: Boolean = True);
var
BlockType: Pointer;
begin
//ABlockType required for detect whether singleline /multiline is being paired
BlockType := TopCodeFoldBlockType;
if FIsCollectingNodeInfo then
CollectNodeInfo(True, BlockType, DecreaseLevel);
CodeFoldRange.Pop(DecreaseLevel);
end;
procedure TSynCustomFoldHighlighter.CollectNodeInfo(FinishingABlock: Boolean;
ABlockType: Pointer; LevelChanged: Boolean);
var
//DecreaseLevel,
BlockTypeEnabled, BlockConfExists: Boolean;
act: TSynFoldActions;
nd: TSynFoldNodeInfo;
begin
if not IsCollectingNodeInfo then exit;
BlockConfExists := (PtrUInt(ABlockType) < FoldConfigCount); // how about pascal that has blocktype > foldconfigcount?
//BlockConfExists := HasFoldConfig(PtrUInt(ABlockType));
BlockTypeEnabled := False;
if BlockConfExists then
BlockTypeEnabled := FoldConfig[PtrUInt(ABlockType)].Enabled;
//Start
if not FinishingABlock then
begin
act := [sfaOpen, sfaOpenFold]; // todo deprecate sfaOpenFold
if BlockTypeEnabled then
act := act + FoldConfig[PtrUInt(ABlockType)].FoldActions
else
if not BlockConfExists then
act := act + [sfaFold,sfaFoldFold, sfaMarkup, sfaOutline];
end
else
//Finish
begin
act := [sfaClose, sfaCloseFold]; // todo deprecate sfaCloseFold
if BlockTypeEnabled then
act := act + FoldConfig[PtrUInt(ABlockType)].FoldActions
else
if not BlockConfExists then
act := act + [sfaFold, sfaFoldFold, sfaMarkup, sfaOutline];
act := act - [sfaFoldFold, sfaFoldHide]; // it is closing tag
end;
DoInitNode(nd, FinishingABlock, ABlockType, act, LevelChanged);
FCollectingNodeInfoList.Add(nd);
end;
procedure TSynCustomFoldHighlighter.DoInitNode(var Node: TSynFoldNodeInfo;
FinishingABlock: Boolean; ABlockType: Pointer;
aActions: TSynFoldActions; AIsFold: Boolean);
var
OneLine: Boolean;
EndOffs: Integer;
LogX1, LogX2: Integer;
begin
GetTokenBounds(LogX1, LogX2);
aActions := aActions + [sfaMultiLine];
if FinishingABlock then
EndOffs := -1
else
EndOffs := +1;
Node.LineIndex := LineIndex;
Node.LogXStart := LogX1;
Node.LogXEnd := LogX2;
Node.FoldType := ABlockType;
Node.FoldTypeCompatible := ABlockType;
Node.FoldAction := aActions;
node.FoldGroup := 1;//FOLDGROUP_PASCAL;
Node.FoldLvlStart := CodeFoldRange.CodeFoldStackSize; // If "not AIsFold" then the node has no foldlevel of its own
Node.NestLvlStart := CodeFoldRange.NestFoldStackSize;
OneLine := FinishingABlock and (Node.FoldLvlStart > CodeFoldRange.MinimumCodeFoldBlockLevel);
Node.NestLvlEnd := Node.NestLvlStart + EndOffs;
if not (sfaFold in aActions) then
EndOffs := 0;
Node.FoldLvlEnd := Node.FoldLvlStart + EndOffs;
if OneLine then // find opening node
RepairSingleLineNode(Node);
end;
procedure TSynCustomFoldHighlighter.RepairSingleLineNode(var Node: TSynFoldNodeInfo);
var
nd: PSynFoldNodeInfo;
i : integer;
begin
i := FCollectingNodeInfoList.CountAll - 1;
nd := FCollectingNodeInfoList.ItemPointer[i];
while (i >= 0) and
( (nd^.FoldType <> node.FoldType) or
(nd^.FoldGroup <> node.FoldGroup) or
(not (sfaOpenFold in nd^.FoldAction))
or (nd^.FoldLvlEnd <> Node.FoldLvlStart)
)
do begin
dec(i);
nd := FCollectingNodeInfoList.ItemPointer[i];
end;
if i >= 0 then begin
nd^.FoldAction := nd^.FoldAction + [sfaOneLineOpen, sfaSingleLine] - [sfaMultiLine];
Node.FoldAction := Node.FoldAction + [sfaOneLineClose, sfaSingleLine] - [sfaMultiLine];
if (sfaFoldHide in nd^.FoldAction) then begin
assert(sfaFold in nd^.FoldAction, 'sfaFoldHide without sfaFold');
// one liner: hide-able / not fold-able
nd^.FoldAction := nd^.FoldAction - [sfaFoldFold];
Node.FoldAction := Node.FoldAction - [sfaFoldFold];
end else begin
// one liner: nether hide-able nore fold-able
nd^.FoldAction := nd^.FoldAction - [sfaOpenFold, sfaFold, sfaFoldFold];
Node.FoldAction := Node.FoldAction - [sfaCloseFold, sfaFold, sfaFoldFold];
end;
end;
end;
procedure TSynCustomFoldHighlighter.CreateRootCodeFoldBlock;
begin
FRootCodeFoldBlock := TSynCustomCodeFoldBlock.Create;
end;
{ TSynCustomCodeFoldBlock }
function TSynCustomCodeFoldBlock.GetChild(ABlockType: Pointer): TSynCustomCodeFoldBlock;
begin
if assigned(FChildren) then
Result := FChildren.GetOrCreateSibling(ABlockType)
else begin
Result := TSynCustomCodeFoldBlock(self.ClassType.Create);
Result.FBlockType := ABlockType;
Result.FParent := self;
FChildren := Result;
end;
end;
var
CreateSiblingBalanceList: Array of TSynCustomCodeFoldBlock;
function TSynCustomCodeFoldBlock.GetOrCreateSibling(ABlockType: Pointer): TSynCustomCodeFoldBlock;
procedure BalanceNode(TheNode: TSynCustomCodeFoldBlock);
var
i, l: Integer;
t: Pointer;
N, P, C: TSynCustomCodeFoldBlock;
begin
l := length(CreateSiblingBalanceList);
i := 0;
t := TheNode.FBlockType;
N := self;
while N.FBlockType <> t do begin
if i >= l then begin
inc(l, 20);
SetLength(CreateSiblingBalanceList, l);
end;
CreateSiblingBalanceList[i] := N; // Record all parents
inc(i);
if t < N.FBlockType
then N := N.FLeft
else N := N.FRight;
end;
if i >= l then begin
inc(l, 20);
SetLength(CreateSiblingBalanceList, l);
end;
CreateSiblingBalanceList[i] := TheNode;
while i >= 0 do begin
if CreateSiblingBalanceList[i].FBalance = 0
then exit;
if (CreateSiblingBalanceList[i].FBalance = -1) or
(CreateSiblingBalanceList[i].FBalance = 1) then begin
if i = 0 then
exit;
dec(i);
if CreateSiblingBalanceList[i+1] = CreateSiblingBalanceList[i].FLeft
then dec(CreateSiblingBalanceList[i].FBalance)
else inc(CreateSiblingBalanceList[i].FBalance);
continue;
end;
// rotate
P := CreateSiblingBalanceList[i];
if P.FBalance = -2 then begin
N := P.FLeft;
if N.FBalance < 0 then begin
(* ** single rotate ** *)
(* []\[]_ _C []_ C_ _[]
N(-1)_ _[] => []_ _P(0)
P(-2) N(0) *)
C := N.FRight;
N.FRight := P;
P.FLeft := C;
N.FBalance := 0;
P.FBalance := 0;
end else begin
(* ** double rotate ** *)
(* x1 x2
[]_ _C x1 x2
N(+1)_ _[] => N _ _ P
P(-2) C *)
C := N.FRight;
N.FRight := C.FLeft;
P.FLeft := C.FRight;
C.FLeft := N;
C.FRight := P;
// balance
if (C.FBalance <= 0)
then N.FBalance := 0
else N.FBalance := -1;
if (C.FBalance = -1)
then P.FBalance := 1
else P.FBalance := 0;
C.FBalance := 0;
N := C;
end;
end else begin // *******************
N := P.FRight;
if N.FBalance > 0 then begin
(* ** single rotate ** *)
C := N.FLeft;
N.FLeft := P;
P.FRight := C;
N.FBalance := 0;
P.FBalance := 0;
end else begin
(* ** double rotate ** *)
C := N.FLeft;
N.FLeft := C.FRight;
P.FRight := C.FLeft;
C.FRight := N;
C.FLeft := P;
// balance
if (C.FBalance >= 0)
then N.FBalance := 0
else N.FBalance := +1;
if (C.FBalance = +1)
then P.FBalance := -1
else P.FBalance := 0;
C.FBalance := 0;
N := C;
end;
end;
// update parent
dec(i);
if i < 0 then begin
if assigned(self.FParent) then
self.FParent.FChildren := N
end else
if CreateSiblingBalanceList[i].FLeft = P
then CreateSiblingBalanceList[i].FLeft := N
else CreateSiblingBalanceList[i].FRight := N;
break;
end
end;
var
P: TSynCustomCodeFoldBlock;
begin
Result := self;
while (assigned(Result)) do begin
if Result.FBlockType = ABlockType then
exit;
P := Result;
if ABlockType < Result.FBlockType
then Result := Result.FLeft
else Result := Result.FRight;
end;
// Not Found
Result := TSynCustomCodeFoldBlock(self.ClassType.Create);
Result.FBlockType := ABlockType;
Result.FParent := self.FParent;
if ABlockType < P.FBlockType then begin
P.FLeft := Result;
dec(P.FBalance);
end else begin
P.FRight := Result;
inc(P.FBalance);
end;
// Balance
if P.FBalance <> 0 then
BalanceNode(P);
end;
destructor TSynCustomCodeFoldBlock.Destroy;
begin
FreeAndNil(FRight);
FreeAndNil(FLeft);
FreeAndNil(FChildren);
inherited Destroy;
end;
procedure TSynCustomCodeFoldBlock.WriteDebugReport;
procedure debugout(n: TSynCustomCodeFoldBlock; s1, s: String; p: TSynCustomCodeFoldBlock);
begin
if n = nil then exit;
if n.FParent <> p then
DebugLn([s1, 'Wrong Parent for', ' (', PtrInt(n), ')']);
DebugLn([s1, PtrUInt(n.BlockType), ' (', PtrInt(n), ')']);
debugout(n.FLeft, s+'L: ', s+' ', p);
debugout(n.FRight, s+'R: ', s+' ', p);
debugout(n.FChildren, s+'C: ', s+' ', n);
end;
begin
debugout(self, '', '', nil);
end;
procedure TSynCustomCodeFoldBlock.InitRootBlockType(AType: Pointer);
begin
if assigned(FParent) then
raise Exception.Create('Attempt to modify a FoldBlock');
FBlockType := AType;
end;
{ TSynCustomHighlighterRange }
constructor TSynCustomHighlighterRange.Create(
Template: TSynCustomHighlighterRange);
begin
if (Template<>nil) and (ClassType<>Template.ClassType) then
RaiseGDBException('');
if Template<>nil then
Assign(Template);
end;
destructor TSynCustomHighlighterRange.Destroy;
begin
Clear;
inherited Destroy;
end;
function TSynCustomHighlighterRange.Compare(Range: TSynCustomHighlighterRange
): integer;
begin
if RangeType < Range.RangeType then
Result:=1
else if RangeType > Range.RangeType then
Result:=-1
else if Pointer(FTop) < Pointer(Range.FTop) then
Result:= -1
else if Pointer(FTop) > Pointer(Range.FTop) then
Result:= 1
else
Result := FMinimumNestFoldBlockLevel - Range.FMinimumNestFoldBlockLevel;
if Result <> 0 then
exit;
Result := FNestFoldStackSize - Range.FNestFoldStackSize;
if Result <> 0 then
exit;
Result := FMinimumCodeFoldBlockLevel - Range.FMinimumCodeFoldBlockLevel;
if Result <> 0 then
exit;
Result := FCodeFoldStackSize - Range.FCodeFoldStackSize;
end;
function TSynCustomHighlighterRange.Add(ABlockType: Pointer;
IncreaseLevel: Boolean = True): TSynCustomCodeFoldBlock;
var
i: LongInt;
begin
i := MaxFoldLevel;
if (i > 0) and (FCodeFoldStackSize >= i) then begin
//debugln('Reached MaxFoldLevel, ignoring folds');
exit(nil);
end;
Result := FTop.Child[ABlockType];
Result.Foldable := IncreaseLevel;
inc(FNestFoldStackSize);
if IncreaseLevel then
inc(FCodeFoldStackSize);
FTop:=Result;
end;
procedure TSynCustomHighlighterRange.Pop(DecreaseLevel: Boolean = True);
// can be called, even if there is no stack
// because it's normal that sources under development have unclosed blocks
begin
//debugln('TSynCustomHighlighterRange.Pop');
if assigned(FTop.Parent) then begin
FTop := FTop.Parent;
dec(FNestFoldStackSize);
if FMinimumNestFoldBlockLevel > FNestFoldStackSize then
FMinimumNestFoldBlockLevel := FNestFoldStackSize;
if DecreaseLevel then begin
dec(FCodeFoldStackSize);
if FMinimumCodeFoldBlockLevel > FCodeFoldStackSize then
FMinimumCodeFoldBlockLevel := FCodeFoldStackSize;
end;
end;
end;
function TSynCustomHighlighterRange.MaxFoldLevel: Integer;
begin
Result := -1;
end;
procedure TSynCustomHighlighterRange.Clear;
begin
FRangeType:=nil;
FCodeFoldStackSize := 0;
FNestFoldStackSize := 0;
FMinimumCodeFoldBlockLevel := 0;
FMinimumNestFoldBlockLevel:= 0;
FTop:=nil;
end;
procedure TSynCustomHighlighterRange.Assign(Src: TSynCustomHighlighterRange);
begin
if (Src<>nil) and (Src<>TSynCustomHighlighterRange(NullRange)) then begin
FTop := Src.FTop;
FCodeFoldStackSize := Src.FCodeFoldStackSize;
FMinimumCodeFoldBlockLevel := Src.FMinimumCodeFoldBlockLevel;
FNestFoldStackSize := Src.FNestFoldStackSize;
FMinimumNestFoldBlockLevel := Src.FMinimumNestFoldBlockLevel;
FRangeType := Src.FRangeType;
end
else begin
FTop := nil;
FCodeFoldStackSize := 0;
FNestFoldStackSize := 0;
FMinimumCodeFoldBlockLevel := 0;
FMinimumNestFoldBlockLevel := 0;
FRangeType := nil;
end;
end;
procedure TSynCustomHighlighterRange.WriteDebugReport;
begin
debugln('TSynCustomHighlighterRange.WriteDebugReport ',DbgSName(Self),
' RangeType=',dbgs(RangeType),' StackSize=',dbgs(CodeFoldStackSize));
debugln(' Block=',dbgs(PtrInt(FTop)));
FTop.WriteDebugReport;
end;
{ TSynCustomHighlighterRanges }
constructor TSynCustomHighlighterRanges.Create(
TheHighlighterClass: TSynCustomHighlighterClass);
begin
Allocate;
FItems:=TAvgLvlTree.Create(@CompareSynHighlighterRanges);
end;
destructor TSynCustomHighlighterRanges.Destroy;
begin
if HighlighterRanges<>nil then begin
HighlighterRanges.Remove(Self);
if HighlighterRanges.Count=0 then
FreeAndNil(HighlighterRanges);
end;
FItems.FreeAndClear;
FreeAndNil(FItems);
inherited Destroy;
end;
function TSynCustomHighlighterRanges.GetEqual(Range: TSynCustomHighlighterRange
): TSynCustomHighlighterRange;
var
Node: TAvgLvlTreeNode;
begin
if Range=nil then exit(nil);
Node:=FItems.Find(Range);
if Node<>nil then begin
Result:=TSynCustomHighlighterRange(Node.Data);
end else begin
// add a copy
Result:=TSynCustomHighlighterRangeClass(Range.ClassType).Create(Range);
FItems.Add(Result);
//if FItems.Count mod 32 = 0 then debugln(['FOLDRANGE Count=', FItems.Count]);
end;
//debugln('TSynCustomHighlighterRanges.GetEqual A ',dbgs(Node),' ',dbgs(Result.Compare(Range)),' ',dbgs(Result.CodeFoldStackSize));
end;
procedure TSynCustomHighlighterRanges.Allocate;
begin
inc(FAllocatedCount);
end;
procedure TSynCustomHighlighterRanges.Release;
begin
dec(FAllocatedCount);
if FAllocatedCount=0 then Free;
end;
{ TSynCustomFoldConfig }
procedure TSynCustomFoldConfig.SetEnabled(const AValue: Boolean);
begin
if FEnabled = AValue then exit;
FEnabled := AValue;
DoOnChange;
end;
procedure TSynCustomFoldConfig.SetModes(AValue: TSynCustomFoldConfigModes);
begin
AValue := AValue * FSupportedModes;
if FModes = AValue then exit;
FModes := AValue;
FFoldActions := [];
if fmFold in AValue then FFoldActions := FFoldActions + [sfaFold, sfaFoldFold];
if fmHide in AValue then FFoldActions := FFoldActions + [sfaFold, sfaFoldHide];
if fmMarkup in AValue then FFoldActions := FFoldActions + [sfaMarkup];
if fmOutline in AValue then FFoldActions := FFoldActions + [sfaOutline];
DoOnChange;
end;
procedure TSynCustomFoldConfig.SetSupportedModes(AValue: TSynCustomFoldConfigModes);
begin
if FSupportedModes = AValue then Exit;
FSupportedModes := AValue;
Modes := Modes * FSupportedModes;
end;
procedure TSynCustomFoldConfig.DoOnChange;
begin
if assigned(FOnChange) then
FOnChange(self);
end;
constructor TSynCustomFoldConfig.Create;
begin
Inherited;
FSupportedModes := [fmFold];
Modes := [fmFold];
end;
procedure TSynCustomFoldConfig.Assign(Src: TSynCustomFoldConfig);
begin
Enabled := Src.Enabled;
SupportedModes := Src.SupportedModes;
Modes := Src.Modes;
end;
end.
|
unit gPickableItems;
interface
uses
gWorld, gTypes,
UPhysics2D, UPhysics2DTypes, B2Utils,
mutils, avRes, gUnits,
avContnrs,
intfUtils;
type
TPickItem = class(TGameSingleBody)
private
protected
FPicked: Boolean;
FAllowRotate: Boolean;
function CreateFixutreDefForShape(const AShape: Tb2Shape): Tb2FixtureDef; override;
function CreateBodyDef(const APos: TVector2; const AAngle: Double): Tb2BodyDef; override;
protected
FOnHitLeave : IWeakedInterface;
procedure OnHit(const AFixture: Tb2Fixture; const ThisFixture: Tb2Fixture; const AManifold: Tb2WorldManifold); virtual;
procedure OnLeave(const AFixture: Tb2Fixture; const ThisFixture: Tb2Fixture); virtual;
procedure DoSetResource(const ARes: TGameResource); override;
procedure OnTankHit(const AUnit: TTowerTank); virtual; abstract;
procedure GetResource(out ASprite: ISpriteIndex; out AllowRotate: Boolean; out AScale: Single); virtual; abstract;
public
function GetTransform(): TMat3; override;
procedure AfterConstruction; override;
end;
TPickItem_HP = class(TPickItem)
private
protected
procedure OnTankHit(const AUnit: TTowerTank); override;
procedure GetResource(out ASprite: ISpriteIndex; out AllowRotate: Boolean; out AScale: Single); override;
public
end;
TPickItem_Speed = class(TPickItem)
private
protected
procedure OnTankHit(const AUnit: TTowerTank); override;
procedure GetResource(out ASprite: ISpriteIndex; out AllowRotate: Boolean; out AScale: Single); override;
public
end;
TPickItem_FireRate = class(TPickItem)
private
protected
procedure OnTankHit(const AUnit: TTowerTank); override;
procedure GetResource(out ASprite: ISpriteIndex; out AllowRotate: Boolean; out AScale: Single); override;
public
end;
TPickItem_Canon_RocketMini = class(TPickItem)
private
protected
procedure OnTankHit(const AUnit: TTowerTank); override;
procedure GetResource(out ASprite: ISpriteIndex; out AllowRotate: Boolean; out AScale: Single); override;
public
end;
TPickItem_Canon_Rocket = class(TPickItem)
private
protected
procedure OnTankHit(const AUnit: TTowerTank); override;
procedure GetResource(out ASprite: ISpriteIndex; out AllowRotate: Boolean; out AScale: Single); override;
public
end;
TPickItem_Canon_Tesla = class(TPickItem)
private
protected
procedure OnTankHit(const AUnit: TTowerTank); override;
procedure GetResource(out ASprite: ISpriteIndex; out AllowRotate: Boolean; out AScale: Single); override;
public
end;
TPickItem_Canon_Grenade = class(TPickItem)
private
protected
procedure OnTankHit(const AUnit: TTowerTank); override;
procedure GetResource(out ASprite: ISpriteIndex; out AllowRotate: Boolean; out AScale: Single); override;
public
end;
implementation
uses
Math;
{ TPickItem }
procedure TPickItem.AfterConstruction;
var
res : TGameResource;
lsize: TVec2;
s: Single;
begin
inherited;
res.Clear;
SetLength(res.images, 1);
GetResource(res.images[0], FAllowRotate, s);
lsize := Vec(res.images[0].Data.Width, res.images[0].Data.Height) / 80;
lsize := lsize * s;
res.tris := TSpineExVertices.Create;
Draw_Sprite(res.tris, Vec(0,0), Vec(1,0), lsize, res.images[0]);
SetLength(res.fixtures_cir, 1);
res.fixtures_cir[0] := Vec(0,0,(lsize.y+lsize.x)*0.25);
SetResource(res);
Layer := glGame;
ZIndex := 0;
end;
function TPickItem.CreateBodyDef(const APos: TVector2; const AAngle: Double): Tb2BodyDef;
begin
Result := Tb2BodyDef.Create;
Result.bodyType := b2_staticBody;
Result.userData := Self;
Result.position := APos;
Result.angle := AAngle;
end;
function TPickItem.CreateFixutreDefForShape(const AShape: Tb2Shape): Tb2FixtureDef;
begin
Result := Tb2FixtureDef.Create;
Result.shape := AShape;
Result.isSensor := True;
end;
procedure TPickItem.DoSetResource(const ARes: TGameResource);
begin
inherited;
FOnHitLeave := TOnHitSubscriber.Create(MainBody, {$IfDef FPC}@{$EndIf}OnHit, {$IfDef FPC}@{$EndIf}OnLeave);
World.b2ContactListener.Subscribe(FOnHitLeave);
end;
function TPickItem.GetTransform: TMat3;
var m: TMat3;
s: Single;
rot: Single;
begin
s := 1 + sin(World.Time*0.004)*0.2;
if FAllowRotate then
rot := World.Time*0.001
else
rot := 0;
Result := Mat3(Vec(s, s), rot, Vec(0,0)) * inherited GetTransform();
end;
procedure TPickItem.OnHit(const AFixture, ThisFixture: Tb2Fixture; const AManifold: Tb2WorldManifold);
var b: Tb2Body;
o: TGameObject;
begin
if FPicked then Exit;
b := AFixture.GetBody;
if b = nil then Exit;
o := TGameObject(b.UserData);
if not (o is TTowerTank) then Exit;
OnTankHit(o as TTowerTank);
end;
procedure TPickItem.OnLeave(const AFixture, ThisFixture: Tb2Fixture);
begin
end;
{ TPickItem_HP }
procedure TPickItem_HP.GetResource(out ASprite: ISpriteIndex; out AllowRotate: Boolean; out AScale: Single);
begin
ASprite := World.GetCommonTextures^.hp;
AllowRotate := False;
AScale := 1.5;
end;
procedure TPickItem_HP.OnTankHit(const AUnit: TTowerTank);
begin
if AUnit.HP < AUnit.MaxHP then
begin
AUnit.HP := Min(AUnit.HP + 150, AUnit.MaxHP);
World.SafeDestroy(Self);
World.PlaySound('pick_aidkid', Pos, Vec(0,0));
FPicked := True;
end;
end;
{ TPickItem_Speed }
procedure TPickItem_Speed.GetResource(out ASprite: ISpriteIndex; out AllowRotate: Boolean; out AScale: Single);
begin
ASprite := World.GetCommonTextures^.speed;
AllowRotate := False;
AScale := 1.5;
end;
procedure TPickItem_Speed.OnTankHit(const AUnit: TTowerTank);
var t: Int64;
begin
t := Max(AUnit.SpeedBoost, World.Time);
t := t + 7000;
AUnit.SpeedBoost := t;
World.SafeDestroy(Self);
FPicked := True;
World.PlaySound('pkup', Pos, Vec(0,0));
end;
{ TPickItem_FireRate }
procedure TPickItem_FireRate.GetResource(out ASprite: ISpriteIndex; out AllowRotate: Boolean; out AScale: Single);
begin
ASprite := World.GetCommonTextures^.firerate;
AllowRotate := False;
AScale := 1.5;
end;
procedure TPickItem_FireRate.OnTankHit(const AUnit: TTowerTank);
var t: Int64;
begin
t := Max(AUnit.FireRateBoost, World.Time);
t := t + 7000;
AUnit.FireRateBoost := t;
World.SafeDestroy(Self);
FPicked := True;
World.PlaySound('pkup', Pos, Vec(0,0));
end;
{ TPcikItem_Canon_RocketMini }
procedure TPickItem_Canon_RocketMini.GetResource(out ASprite: ISpriteIndex; out AllowRotate: Boolean; out AScale: Single);
begin
ASprite := World.GetCommonTextures^.canon_rocket_mini;
AllowRotate := True;
AScale := 1;
end;
procedure TPickItem_Canon_RocketMini.OnTankHit(const AUnit: TTowerTank);
begin
if not (AUnit is TPlayer) then Exit;
TPlayer(AUnit).Ammo_MiniRocket := TPlayer(AUnit).Ammo_MiniRocket + 15;
World.SafeDestroy(Self);
FPicked := True;
World.PlaySound('pick_ammo', Pos, Vec(0,0));
end;
{ TPickItem_Canon_Rocket }
procedure TPickItem_Canon_Rocket.GetResource(out ASprite: ISpriteIndex; out AllowRotate: Boolean; out AScale: Single);
begin
ASprite := World.GetCommonTextures^.canon_rocket;
AllowRotate := True;
AScale := 1;
end;
procedure TPickItem_Canon_Rocket.OnTankHit(const AUnit: TTowerTank);
begin
if not (AUnit is TPlayer) then Exit;
TPlayer(AUnit).Ammo_Rocket := TPlayer(AUnit).Ammo_Rocket + 15;
World.SafeDestroy(Self);
FPicked := True;
World.PlaySound('pick_ammo', Pos, Vec(0,0));
end;
{ TPickItem_Canon_Tesla }
procedure TPickItem_Canon_Tesla.GetResource(out ASprite: ISpriteIndex; out AllowRotate: Boolean; out AScale: Single);
begin
ASprite := World.GetCommonTextures^.canon_tesla;
AllowRotate := True;
AScale := 1;
end;
procedure TPickItem_Canon_Tesla.OnTankHit(const AUnit: TTowerTank);
begin
if not (AUnit is TPlayer) then Exit;
TPlayer(AUnit).Ammo_Tesla := TPlayer(AUnit).Ammo_Tesla + 100;
World.SafeDestroy(Self);
FPicked := True;
World.PlaySound('pick_ammo', Pos, Vec(0,0));
end;
{ TPickItem_Canon_Grenade }
procedure TPickItem_Canon_Grenade.GetResource(out ASprite: ISpriteIndex; out AllowRotate: Boolean; out AScale: Single);
begin
ASprite := World.GetCommonTextures^.canon_grenades;
AllowRotate := True;
AScale := 1;
end;
procedure TPickItem_Canon_Grenade.OnTankHit(const AUnit: TTowerTank);
begin
if not (AUnit is TPlayer) then Exit;
TPlayer(AUnit).Ammo_Grenade := TPlayer(AUnit).Ammo_Grenade + 20;
World.SafeDestroy(Self);
FPicked := True;
World.PlaySound('pick_ammo', Pos, Vec(0,0));
end;
end.
|
unit uToolbarGrafico;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uPanelNotificaciones, Grafico, TB2Item, SpTBXItem, ImgList, TB2Dock,
TB2Toolbar, ActnList, Menus, SpTBXFormPopupMenu, IncrustedItems,
dmToolbarGrafico, Contnrs, GraficoPositionLayer, GraficoBolsa, UtilFS;
type
TBotonItem = class(TSpTBXSubmenuItem)
public
Grafico: TGraficoItem;
Titulo: string;
VerGrafico: boolean;
OID: integer;
end;
TfrToolbarGrafico = class(TfrPanelNotificaciones)
ActionList: TActionList;
Administrar: TAction;
Toolbar: TSpTBXToolbar;
ImageList: TImageList;
MenuGeneral: TSpTBXSubmenuItem;
ColorPalette: TSpTBXColorPalette;
Ver: TAction;
SpTBXItem2: TSpTBXItem;
SpTBXSeparatorItem1: TSpTBXSeparatorItem;
Quitar: TAction;
mgQuitar: TSpTBXItem;
MenuAnadir: TSpTBXSubmenuItem;
SpTBXItem1: TSpTBXItem;
SpTBXSeparatorItem2: TSpTBXSeparatorItem;
MenuOsciladores: TSpTBXSubmenuItem;
SpTBXItem4: TSpTBXItem;
aAnadirValor: TAction;
procedure AdministrarExecute(Sender: TObject);
procedure ColorPaletteChange(Sender: TObject);
procedure VerExecute(Sender: TObject);
procedure MenuGeneralPopup(Sender: TTBCustomItem; FromLink: Boolean);
procedure QuitarExecute(Sender: TObject);
procedure MenuOsciladoresPopup(Sender: TTBCustomItem; FromLink: Boolean);
procedure aAnadirValorExecute(Sender: TObject);
private
botones: TObjectList;
MenuCreated: boolean;
ToolbarGrafico: TToolbarGrafico;
FGraficoBolsa: TGraficoBolsa;
procedure OnCalculated(Sender: TGraficoItem; itemToNotify: TTBCustomItem;
stopped: boolean);
procedure OnAdministrarOsciladorChangeColor(const OID: Integer; const color: TColor);
procedure OnAdministrarOsciladorDeleted(const OID: integer);
procedure OnAdministrarOsciladorChangeName(const OID: integer; const name: string);
procedure AnadirOscilador(Sender: TObject);
procedure AnadirOsciladorItem(const osciladorItem: TMenuFSItem);
procedure AnadirValor(const OIDValor: integer);
function GetGrafico: TGrafico;
function GetColor: TColor;
procedure SetColor(const Value: TColor);
procedure OnShowParent(Sender: TObject);
protected
procedure SaveConfigVisual;
procedure LoadConfigVisual;
procedure OnCotizacionCambiada; override;
property Grafico: TGrafico read GetGrafico;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
class function GetNombre: string; override;
procedure AnadirGrafico(const item: TBotonItem; const graficoItem: TGraficoItem;
const color: TColor);
procedure QuitarBoton(boton: TSpTBXSubmenuItem);
property GraficoBolsa: TGraficoBolsa read FGraficoBolsa write FGraficoBolsa;
property Color: TColor read GetColor write SetColor;
end;
implementation
uses UtilDock, fmOsciladores, dmOsciladores, UtilForms, dmFS, frFS,
dmData, fmBaseBuscar, dmDataComun, GraficoValor, GraficoOscilador,
DatosGrafico, GraficoLineas, BusCommunication, uAccionesVer, ConfigVisual;
{$R *.dfm}
const
INDEX_CALCULATING = 2;
type
TBotonOsciladorItem = class;
TMenuOsciladorItem = class(TMenuFSItem)
private
Color: TColor;
BotonOscilador: TBotonOsciladorItem;
CodigoCompiled: string;
OID: integer;
end;
TBotonOsciladorItem = class(TBotonItem)
private
MenuItem: TMenuOsciladorItem;
end;
function CrearMenuItem(const AOwner: TComponent; const FS: TFS;
const data: TBasicNodeData): TSpTBXItem;
var i, OID: Integer;
botones: TObjectList;
botonItem: TBotonOsciladorItem;
begin
OID := data.OID;
TOsciladores(FS).Load(OID);
if TOsciladores(FS).HasCodigoCompiled then begin
result := TMenuOsciladorItem.Create(AOwner);
result.Caption := data.Caption;
TMenuOsciladorItem(result).OID := OID;
TMenuOsciladorItem(result).BotonOscilador := nil;
TMenuOsciladorItem(result).Color := TOsciladores(FS).Color;
TMenuOsciladorItem(result).CodigoCompiled := TOsciladores(FS).CodigoCompiled;
botones := TfrToolbarGrafico(AOwner).botones;
for i := botones.Count - 1 downto 0 do begin
botonItem := TBotonOsciladorItem(botones[i]);
if botonItem.OID = OID then begin
botonItem.MenuItem := TMenuOsciladorItem(result);
TMenuOsciladorItem(result).BotonOscilador := botonItem;
TMenuOsciladorItem(result).Checked := true;
exit;
end;
end;
end
else
result := nil;
end;
{ TfrPanelNotificaciones1 }
procedure TfrToolbarGrafico.AnadirGrafico(const item: TBotonItem;
const graficoItem: TGraficoItem; const color: TColor);
begin
item.Images := ImageList;
item.DisplayMode := nbdmImageAndText;
item.Caption := item.Titulo;
item.Options := [tboDropdownArrow];
item.LinkSubitems := MenuGeneral;
item.FontSettings.Color := color;
item.VerGrafico := true;
item.Grafico := graficoItem;
graficoItem.Color := color;
graficoItem.Visible := True;
graficoItem.ItemImageIndexCalculating := INDEX_CALCULATING;
graficoItem.OnCalculated := OnCalculated;
Toolbar.Items.Add(item);
botones.Add(item);
graficoItem.Run;
end;
procedure TfrToolbarGrafico.AnadirOscilador(Sender: TObject);
var osciladorItem: TMenuOsciladorItem;
begin
if Sender is TMenuOsciladorItem then begin
osciladorItem := TMenuOsciladorItem(Sender);
if osciladorItem.Checked then begin
QuitarBoton(osciladorItem.BotonOscilador);
end
else
AnadirOsciladorItem(osciladorItem);
end;
end;
procedure TfrToolbarGrafico.AnadirOsciladorItem(const osciladorItem: TMenuFSItem);
var item: TBotonOsciladorItem;
Oscilador: TGraficoOscilador;
begin
osciladorItem.Checked := true;
item := TBotonOsciladorItem.Create(Self);
item.OID := osciladorItem.OID;
// item.Images := ImageList;
// item.DisplayMode := nbdmImageAndText;
item.Titulo := osciladorItem.Caption;
// item.Caption := item.Titulo;
// item.Options := [tboDropdownArrow];
// item.LinkSubitems := MenuGeneral;
// item.FontSettings.Color := TMenuOsciladorItem(osciladorItem).Color;
item.MenuItem := TMenuOsciladorItem(osciladorItem);
// item.VerGrafico := true;
// Toolbar.Items.Add(item);
// botones.Add(item);
TMenuOsciladorItem(osciladorItem).BotonOscilador := item;
Oscilador := TGraficoOscilador.Create(Grafico,
TMenuOsciladorItem(osciladorItem).CodigoCompiled, item);
// Oscilador.ItemImageIndexCalculating := INDEX_CALCULATING;
// Oscilador.OnCalculated := OnCalculated;
// Oscilador.Visible := true;
// Oscilador.Color := TMenuOsciladorItem(osciladorItem).Color;
// item.Grafico := Oscilador;
// Oscilador.Run;
AnadirGrafico(item, Oscilador, TMenuOsciladorItem(osciladorItem).Color);
end;
procedure TfrToolbarGrafico.AnadirValor(const OIDValor: integer);
var item: TBotonItem;
ValorItem: TGraficoValor;
begin
item := TBotonItem.Create(Self);
item.OID := OIDValor;
item.Titulo := DataComun.FindValor(OIDValor)^.Simbolo;
// item.Images := ImageList;
// item.DisplayMode := nbdmImageAndText;
// item.Caption := item.Titulo;
// item.Options := [tboDropdownArrow];
// item.LinkSubitems := MenuGeneral;
// item.FontSettings.Color := clWhite;
// item.VerGrafico := true;
ValorItem := TGraficoValor.Create(Grafico, item, OIDValor);
// ValorItem.ItemImageIndexCalculating := INDEX_CALCULATING;
// ValorItem.Visible := true;
ValorItem.Color := clWhite;
// ValorItem.OnCalculated := OnCalculated;
// item.Grafico := ValorItem;
// Toolbar.Items.Add(item);
// botones.Add(item);
// ValorItem.Run;
AnadirGrafico(item, ValorItem, clWhite);
end;
procedure TfrToolbarGrafico.aAnadirValorExecute(Sender: TObject);
var BuscarValor: TfBaseBuscar;
OIDValor: integer;
begin
inherited;
BuscarValor := TfBaseBuscar.Create(Self);
try
BuscarValor.ShowModal;
OIDValor := BuscarValor.OID_VALOR;
finally
BuscarValor.Free;
end;
if OIDValor <> VALOR_NO_SELECTED then
AnadirValor(OIDValor);
end;
procedure TfrToolbarGrafico.AdministrarExecute(Sender: TObject);
var osciladores: TfOsciladores;
begin
osciladores := TfOsciladores.Create(nil);
try
osciladores.OnChangeColor := OnAdministrarOsciladorChangeColor;
osciladores.OnDeleteItem := OnAdministrarOsciladorDeleted;
osciladores.OnChangeName := OnAdministrarOsciladorChangeName;
osciladores.ShowModal;
finally
osciladores.Free;
end;
while MenuOsciladores.Count > 2 do
MenuOsciladores.Delete(2);
MenuCreated := false;
end;
procedure TfrToolbarGrafico.ColorPaletteChange(Sender: TObject);
var color: TColor;
item: TBotonItem;
begin
inherited;
item := TBotonItem((Sender as TSpTBXColorPalette).Tag);
color := ColorPalette.Color;
item.FontSettings.Color := color;
item.Grafico.Color := color;
if item is TBotonOsciladorItem then begin
TBotonOsciladorItem(item).MenuItem.Color := Color;
ToolbarGrafico.ModificarColor(TBotonOsciladorItem(item).MenuItem.OID, color);
end;
end;
constructor TfrToolbarGrafico.Create(AOwner: TComponent);
var defaultDock: TDefaultDock;
begin
defaultDock.Position := dpArribaCentro;
inherited CreatePanelNotificaciones(AOwner, defaultDock, [pnCotizacionCambiada]);
MenuCreated := false;
ToolbarGrafico := TToolbarGrafico.Create(Self);
botones := TObjectList.Create(False);
(AOwner as TForm).OnShow := OnShowParent;
Bus.RegisterEvent(MessageVistaGuardando, SaveConfigVisual);
Bus.RegisterEvent(MessageVistaCargando, LoadConfigVisual);
end;
destructor TfrToolbarGrafico.Destroy;
begin
Bus.UnregisterEvent(MessageVistaGuardando, SaveConfigVisual);
Bus.UnregisterEvent(MessageVistaCargando, LoadConfigVisual);
SaveConfigVisual;
while botones.Count > 0 do
QuitarBoton(TBotonItem(botones[0]));
botones.Free;
inherited;
end;
function TfrToolbarGrafico.GetColor: TColor;
begin
Result := inherited Color;
end;
function TfrToolbarGrafico.GetGrafico: TGrafico;
begin
Result := FGraficoBolsa.GetGrafico(tgbLineas);
end;
class function TfrToolbarGrafico.GetNombre: string;
begin
result := '';
end;
procedure TfrToolbarGrafico.LoadConfigVisual;
var i, num, OID: integer;
sI, clase: string;
menu: TMenuFSItem;
begin
while botones.Count > 0 do
QuitarBoton(TBotonItem(botones[0]));
num := ConfiguracionVisual.ReadInteger(ClassName, 'Num', 0);
for i := 0 to num do begin
sI := IntToStr(i);
clase := ConfiguracionVisual.ReadString(ClassName, 'ClassName.' + sI, '');
OID := ConfiguracionVisual.ReadInteger(ClassName, 'OID.' + sI, -1);
if clase = 'TBotonOsciladorItem' then begin
menu := GetMenuItem(MenuOsciladores, OID);
AnadirOsciladorItem(menu);
end
else begin
if clase = 'TBotonItem' then begin
AnadirValor(OID);
end;
end;
end;
end;
procedure TfrToolbarGrafico.MenuGeneralPopup(Sender: TTBCustomItem;
FromLink: Boolean);
var item: TBotonItem;
begin
inherited;
item := Sender as TBotonItem;
Ver.Checked := item.VerGrafico;
Ver.Tag := integer(item);
Quitar.Tag := integer(item);
ColorPalette.Tag := integer(item);
ColorPalette.OnChange := nil;
if item is TBotonOsciladorItem then
ColorPalette.Color := TBotonOsciladorItem(item).MenuItem.Color
else
ColorPalette.Color := clWhite;
ColorPalette.OnChange := ColorPaletteChange;
end;
procedure TfrToolbarGrafico.MenuOsciladoresPopup(Sender: TTBCustomItem;
FromLink: Boolean);
begin
inherited;
if not MenuCreated then begin
CreateMenuFormFS(Self, MenuOsciladores, TOsciladores, AnadirOscilador, CrearMenuItem);
MenuCreated := true;
end;
end;
procedure TfrToolbarGrafico.OnAdministrarOsciladorChangeColor(const OID: Integer;
const color: TColor);
var menu: TMenuFSItem;
begin
menu := GetMenuItem(MenuOsciladores, OID);
if menu <> nil then begin
assert(menu.ClassType = TMenuOsciladorItem);
TMenuOsciladorItem(menu).Color := color;
if TMenuOsciladorItem(menu).BotonOscilador <> nil then
TMenuOsciladorItem(menu).BotonOscilador.FontSettings.Color := color;
end;
end;
procedure TfrToolbarGrafico.OnAdministrarOsciladorChangeName(const OID: integer;
const name: string);
var menu: TMenuFSItem;
begin
menu := GetMenuItem(MenuOsciladores, OID);
if menu <> nil then begin
assert(menu.ClassType = TMenuOsciladorItem);
if TMenuOsciladorItem(menu).BotonOscilador <> nil then
TMenuOsciladorItem(menu).BotonOscilador.Caption := name;
end;
end;
procedure TfrToolbarGrafico.OnAdministrarOsciladorDeleted(const OID: integer);
var menu: TMenuFSItem;
begin
menu := GetMenuItem(MenuOsciladores, OID);
if menu <> nil then begin
assert(menu.ClassType = TMenuOsciladorItem);
if TMenuOsciladorItem(menu).BotonOscilador <> nil then
QuitarBoton(TMenuOsciladorItem(menu).BotonOscilador);
end;
end;
procedure TfrToolbarGrafico.OnCotizacionCambiada;
var i, position: integer;
graficoItem: TGraficoItem;
boton: TBotonItem;
caption: string;
cambio: currency;
PositionLayer: TGraficoPositionLayer;
begin
if Toolbar.Visible then begin
for i := botones.Count - 1 downto 0 do begin
boton := TBotonItem(botones.Items[i]);
graficoItem := boton.Grafico;
if graficoItem.Calculated then begin
caption := boton.Titulo;
PositionLayer := Grafico.GetLayerByType(TGraficoPositionLayer) as TGraficoPositionLayer;
if PositionLayer <> nil then begin
position := PositionLayer.Position;
if position <> POSICION_INDEFINIDA then begin
cambio := graficoItem.PDatos^[position];
if cambio <> SIN_CAMBIO then
caption := caption + sLineBreak + CurrToStr(cambio);
end;
end;
boton.Caption := caption;
end;
end;
end;
end;
procedure TfrToolbarGrafico.OnShowParent(Sender: TObject);
begin
TForm(Owner).OnShow := nil;
MenuOsciladoresPopup(nil, false);
LoadConfigVisual;
end;
procedure TfrToolbarGrafico.OnCalculated(Sender: TGraficoItem;
itemToNotify: TTBCustomItem; stopped: boolean);
begin
if stopped then begin
QuitarBoton(TBotonItem(itemToNotify));
end
else begin
itemToNotify.Images := nil;
itemToNotify.ImageIndex := -1;
ToolBar.Invalidate;
OnCotizacionCambiada;
end;
end;
procedure TfrToolbarGrafico.QuitarBoton(boton: TSpTBXSubmenuItem);
var item: TBotonItem;
i: integer;
menuItem: TMenuOsciladorItem;
begin
item := TBotonItem(boton);
i := botones.IndexOf(item);
if i <> -1 then
botones.Delete(i);
if item.Grafico <> nil then begin
item.Grafico.Free;
item.Grafico := nil;
end;
if item is TBotonOsciladorItem then begin
menuItem := TBotonOsciladorItem(item).MenuItem;
TMenuOsciladorItem(menuItem).BotonOscilador := nil;
menuItem.Checked := false;
end;
item.Free;
Grafico.InvalidateGrafico;
end;
procedure TfrToolbarGrafico.QuitarExecute(Sender: TObject);
begin
inherited;
QuitarBoton(TBotonOsciladorItem((Sender as TAction).Tag));
end;
procedure TfrToolbarGrafico.SaveConfigVisual;
var i, num: integer;
sI: string;
boton: TBotonItem;
begin
ConfiguracionVisual.DeleteSeccion(ClassName);
num := botones.Count;
ConfiguracionVisual.WriteInteger(ClassName, 'Num', num);
Dec(num);
for i := 0 to num do begin
sI := IntToStr(i);
boton := TBotonItem(botones[i]);
ConfiguracionVisual.WriteString(ClassName, 'ClassName.' + sI, boton.ClassName);
ConfiguracionVisual.WriteInteger(ClassName, 'OID.' + sI, boton.OID);
end;
end;
procedure TfrToolbarGrafico.SetColor(const Value: TColor);
begin
inherited Color := Value;
Toolbar.Color := Value;
end;
procedure TfrToolbarGrafico.VerExecute(Sender: TObject);
var item: TBotonItem;
begin
inherited;
Ver.Checked := not Ver.Checked;
item := TBotonItem((Sender as TAction).Tag);
item.VerGrafico := Ver.Checked;
if Ver.Checked then
item.FontSettings.Style := item.FontSettings.Style - [fsStrikeOut]
else
item.FontSettings.Style := item.FontSettings.Style + [fsStrikeOut];
item.Grafico.Visible := Ver.Checked;
end;
end.
|
unit HCEmrViewLite;
interface
uses
Classes, SysUtils, HCView, HCStyle, HCCustomData, HCCustomFloatItem,
HCItem, HCTextItem, HCRectItem, HCSectionData;
type
THCImportAsTextEvent = procedure (const AText: string) of object;
THCEmrViewLite = class(THCView)
protected
/// <summary> 当有新Item创建时触发 </summary>
/// <param name="AData">创建Item的Data</param>
/// <param name="AStyleNo">要创建的Item样式</param>
/// <returns>创建好的Item</returns>
function DoSectionCreateStyleItem(const AData: THCCustomData;
const AStyleNo: Integer): THCCustomItem; override;
public
constructor Create(AOwner: TComponent); override;
end;
implementation
uses
HCEmrElementItem, HCEmrGroupItem, HCEmrYueJingItem, HCEmrFangJiaoItem, HCEmrToothItem;
{ THCEmrViewLite }
constructor THCEmrViewLite.Create(AOwner: TComponent);
begin
HCDefaultTextItemClass := TDeItem;
HCDefaultDomainItemClass := TDeGroup;
inherited Create(AOwner);
end;
function THCEmrViewLite.DoSectionCreateStyleItem(const AData: THCCustomData;
const AStyleNo: Integer): THCCustomItem;
begin
Result := CreateEmrStyleItem(aData, aStyleNo);
end;
end.
|
(*
Copyright (c) 2011-2014, Stefan Glienke
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 this library nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*)
unit DSharp.Core.XmlSerialization;
interface
uses
SysUtils,
Rtti;
type
XmlAttributeAttribute = class(TCustomAttribute)
private
fAttributeName: string;
public
constructor Create(const attributeName: string);
property AttributeName: string read fAttributeName;
end;
XmlElementAttribute = class(TCustomAttribute)
private
fElementName: string;
public
constructor Create(const elementName: string);
property ElementName: string read fElementName;
end;
XmlIgnoreAttribute = class(TCustomAttribute);
XmlRootAttribute = class(TCustomAttribute)
private
fElementName: string;
public
constructor Create(const elementName: string);
property ElementName: string read fElementName;
end;
IXmlReader = interface
function GetXml: string;
procedure SetXml(const Value: string);
function IsStartElement: Boolean; overload;
function IsStartElement(const name: string): Boolean; overload;
function MoveToElement: Boolean;
function MoveToFirstAttribute: Boolean;
function MoveToNextAttribute: Boolean;
procedure ReadEndElement; overload;
procedure ReadStartElement; overload;
procedure ReadStartElement(const name: string); overload;
procedure ReadValue(var value: TValue);
property Xml: string read GetXml write SetXml;
end;
IXmlWriter = interface
function GetXml: string;
procedure WriteAttribute(const name: string; const value: TValue);
procedure WriteEndElement(const name: string);
procedure WriteStartElement(const name: string);
procedure WriteValue(const value: TValue);
property Xml: string read GetXml;
end;
IXmlSerializer = interface
function Deserialize(reader: IXmlReader): TObject;
procedure Serialize(instance: TObject; writer: IXmlWriter);
end;
IXmlSerializable = interface
procedure ReadXml(reader: IXmlReader);
procedure WriteXml(writer: IXmlWriter);
end;
EXmlException = class(Exception)
end;
var
XmlFormatSettings: TFormatSettings;
implementation
{ XmlAttributeAttribute }
constructor XmlAttributeAttribute.Create(const attributeName: string);
begin
inherited Create;
fAttributeName := attributeName;
end;
{ XmlElementAttribute }
constructor XmlElementAttribute.Create(const elementName: string);
begin
inherited Create;
fElementName := elementName;
end;
{ XmlRootAttribute }
constructor XmlRootAttribute.Create(const elementName: string);
begin
inherited Create;
fElementName := elementName;
end;
initialization
{$IF CompilerVersion > 21}
XmlFormatSettings := TFormatSettings.Create;
{$IFEND}
XmlFormatSettings.DateSeparator := '-';
XmlFormatSettings.DecimalSeparator := '.';
XmlFormatSettings.ShortTimeFormat := 'hh:nn:ss.zzz';
XmlFormatSettings.ShortDateFormat := 'yyyy-mm-dd';
end.
|
unit uModuleForm;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs,
VirtualTrees, uLibraryData,
uModuleData;
type
{ TModuleForm }
TModuleForm = class(TEditingForm)
procedure FormCreate(Sender: TObject);
private
fModuleEditor: TModuleEditor;
public
procedure Load(const aLibraryData: TLibraryData); override;
procedure Unload; override;
end;
implementation
{$R *.lfm}
{ TModuleForm }
procedure TModuleForm.FormCreate(Sender: TObject);
begin
fModuleEditor := TModuleEditor.Create(Self);
fModuleEditor.Parent := Self;
fModuleEditor.Align := alClient;
end;
procedure TModuleForm.Load(const aLibraryData: TLibraryData);
begin
if aLibraryData is uLibraryData.TModuleData then
fModuleEditor.Module := uLibraryData.TModuleData(aLibraryData).Module;
end;
procedure TModuleForm.Unload;
begin
fModuleEditor.Clear;
end;
end.
|
{*!
* Fano Web Framework (https://fanoframework.github.io)
*
* @link https://github.com/fanoframework/fano
* @copyright Copyright (c) 2018 Zamrony P. Juhara
* @license https://github.com/fanoframework/fano/blob/master/LICENSE (MIT)
*}
unit ClamAvImpl;
interface
{$MODE OBJFPC}
{$H+}
uses
AntivirusIntf,
ScanResultIntf;
type
(*!-----------------------------------------------
* Interface for any class having capability to build
* FastCGI Frame Parser
*
* @author Zamrony P. Juhara <zamronypj@yahoo.com>
*-----------------------------------------------*)
TClamAv = class(TInterfacedObject, IAntivirus, IScanResult)
private
fVirusName : PAnsiChar;
fCleaned : boolean;
fEngineCreated : boolean;
fEngine : pointer;
procedure loadAntivirusDb(const engine : pointer);
procedure compileEngine(var engine : pointer);
procedure raiseExceptionIfFailed(const errCode : integer; const msg : string);
procedure createEngine(var engine : pointer);
procedure freeEngine(var engine : pointer);
public
constructor create();
destructor destroy(); override;
(*!------------------------------------------------
* setup antivirus engine
*-----------------------------------------------
* @return current instance
*-----------------------------------------------*)
function beginScan() : IAntivirus;
(*!------------------------------------------------
* scan file for virus
*-----------------------------------------------
* @return scan result
*-----------------------------------------------*)
function scanFile(const filePath : string) : IScanResult;
(*!------------------------------------------------
* free antivirus engine resources
*-----------------------------------------------
* @return current instance
*-----------------------------------------------*)
function endScan() : IAntivirus;
(*!------------------------------------------------
* test if the last scan is cleaned
*-----------------------------------------------
* @return true if cleaned
*-----------------------------------------------*)
function isCleaned() : boolean;
(*!------------------------------------------------
* return name of virus if virus detected
*------------------------------------------------
* @return name of virus or empty string if clean
*-----------------------------------------------*)
function virusName() : string;
end;
implementation
uses
clamav3,
EClamAvImpl;
procedure TClamAv.raiseExceptionIfFailed(const errCode : integer; const msg : string);
begin
if (errCode <> CL_SUCCESS) then
begin
freeEngine(fEngine);
raise EClamAv.create(msg + AnsiString(cl_strerror(errCode)));
end;
end;
constructor TClamAv.create();
var ret : integer;
begin
fCleaned := false;
fVirusName := nil;
fEngineCreated := false;
fEngine := nil;
ret := cl_init(CL_INIT_DEFAULT);
raiseExceptionIfFailed(ret, 'ClamAV initialization fails. ');
end;
destructor TClamAv.destroy();
begin
endScan();
inherited destroy();
end;
procedure TClamAv.loadAntivirusDb(const engine : pointer);
var ret : integer;
sigs : cardinal;
begin
ret := cl_load(cl_retdbdir(), cl_engine(engine^), sigs, CL_DB_STDOPT);
raiseExceptionIfFailed(ret, 'Load antivirus database fails. ');
end;
procedure TClamAv.createEngine(var engine : pointer);
begin
engine := cl_engine_new();
if (engine <> nil) then
begin
raise EClamAv.create('Engine creation failed.');
end;
end;
procedure TClamAv.freeEngine(var engine : pointer);
begin
if fEngineCreated then
begin
cl_engine_free(cl_engine(engine^));
engine := nil;
fEngineCreated := false;
end;
end;
procedure TClamAv.compileEngine(var engine : pointer);
var ret : integer;
begin
ret := cl_engine_compile(cl_engine(engine^));
raiseExceptionIfFailed(ret, 'Compile engine failed. ');
end;
(*!------------------------------------------------
* setup antivirus engine
*-----------------------------------------------
* @return current instance
*-----------------------------------------------*)
function TClamAv.beginScan() : IAntivirus;
begin
if (not fEngineCreated) then
begin
createEngine(fEngine);
loadAntivirusDb(fEngine);
compileEngine(fEngine);
fEngineCreated := (fEngine <> nil);
end;
result := self;
end;
(*!------------------------------------------------
* free antivirus engine resources
*-----------------------------------------------
* @return current instance
*-----------------------------------------------*)
function TClamAv.endScan() : IAntivirus;
begin
freeEngine(fEngine);
result := self;
end;
(*!------------------------------------------------
* scan file for virus
*-----------------------------------------------
* @return scan result
*-----------------------------------------------*)
function TClamAv.scanFile(const filePath : string) : IScanResult;
var ret : longint;
scanned : dword;
begin
scanned := 0;
ret := cl_scanfile(
PChar(filePath),
@fVirusName,
scanned,
cl_engine(fEngine^),
CL_SCAN_STDOPT
);
fCleaned := (ret = CL_CLEAN) or (ret = CL_SUCCESS);
result := self;
end;
(*!------------------------------------------------
* test if the last scan is cleaned
*-----------------------------------------------
* @return true if cleaned
*-----------------------------------------------*)
function TClamAv.isCleaned() : boolean;
begin
result := fCleaned;
end;
(*!------------------------------------------------
* return name of virus if virus detected
*------------------------------------------------
* @return name of virus or empty string if clean
*-----------------------------------------------*)
function TClamAv.virusName() : string;
begin
result := AnsiString(fVirusName);
end;
end.
|
unit Funkcje;
interface
uses
SysUtils, Stale, Math, Windows, Types, Classes, StrUtils, ShellApi, SHFolder, ShlObj, ActiveX, WinSvc, Forms, Dialogs, Grids, DataBase;
function PodajPathSystem: string;
function PodajPathIniFile: string;
function GetGuid: string;
function PodajNazweSystemu: string;
function PodajWersjeSystemu: string;
function PodajNazweBazy: string;
function PodajWersjeBazy: string;
procedure WyczyscStringGrida(AStringGrid: TStringGrid);
function PodajListePlikowWKatalogu(Akatalog: string; var Alista: TStringList): integer;
function IsDirNotation(ADirName: string): Boolean;
function PodajNazwePlikuKataloguZeSciezki(ANapis: string): string;
//Funkcja podaje nazwę stacji roboczej
function PodajZWersionRC(AString: string): string;
function DateTimeToSql(Avalue: TDateTime): string;
function PodajWartosc(Astring: string): string;
function PodajkatalogMojeDokumenty(AHandle: HWND): string;
function UruchamiajProgramy(APlikExe: string; AParametry: string = '';
ASciezkaDomyslna: string = ''; APoprzezProces: Boolean = False;
ACzekajNaKoniec: Boolean = True;
AChowajZrodlo: Boolean = True): Integer;
type
//Obiekt tej klasy będzie odpowiedzialny za wyświetlanie komunikatów. Komunikaty będą trzymane w bazie danych
TKomunikat = class
public
procedure WyswietlKomunikat(AKomunikat: string; ANaglowek: string; Anapisydodatkowe: TArrayOfStrings); overload;
//Wyświetla komunikat z przyciskami Tak anuluj
function WyswietlKomunikatF(AKomunikat: string; ANaglowek: string; Anapisydodatkowe: TArrayOfStrings): integer;
procedure WyswietlKomunikat(AKomunikat: string; ANaglowek: string); overload;
end;
Tid = class
public
Fid: integer;
Findex: integer;
end;
var
GKomunikat: TKomunikat;
implementation
//####################################################################################################################
function PodajPathSystem: string;
begin
result := ExpandUNCFileName(IncludeTrailingPathDelimiter (ExtractFilePath(ParamStr(0))));
end;
//####################################################################################################################
function PodajPathIniFile: string;
begin
result := ExpandUNCFileName(IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0)))) + CNazwaPlikuIni;
end;
//####################################################################################################################
function GetGuid: string;
var
Guid: TGUID;
begin
Result := '';
if CreateGUID(Guid) = S_OK then begin
Result := GUIDToString(Guid);
end;
end;
//####################################################################################################################
function PodajWersjeBazy: string;
begin
result := copy(PodajWersjeSystemu, 1, 4);
end;
//####################################################################################################################
function PodajNazweBazy: string;
var
xNazwaSystemu: string;
xWersja: string;
begin
xNazwaSystemu := PodajNazweSystemu;
xWersja := copy(PodajWersjeSystemu, 1, 4);
while Pos('.', xWersja) <> 0 do begin
Delete(xWersja, Pos('.', xWersja), 1);
end;
result := xNazwaSystemu + '_' + xWersja;
end;
//####################################################################################################################
//####################################################################################################################
function PodajNazweSystemu: string;
begin
result := PodajZWersionRC(CRCNazwaWewnetrzna)
end;
//####################################################################################################################
function PodajWersjeSystemu: string;
begin
result := PodajZWersionRC(CRCWersjaProduktu)
end;
//####################################################################################################################
procedure WyczyscStringGrida(AStringGrid: TStringGrid);
var
i: integer;
begin
for i := 0 to AStringGrid.RowCount - 1 do begin
AStringGrid.Rows[i].Clear;
end;
AStringGrid.RowCount := 2;
AStringGrid.FixedRows := 1;
end;
//####################################################################################################################
{ TKomunikat }
procedure TKomunikat.WyswietlKomunikat(AKomunikat: string; ANaglowek: string; Anapisydodatkowe: TArrayOfStrings);
var
xTresc: string;
i: integer;
begin
xTresc := AKomunikat;
for i := 1 to length(Anapisydodatkowe) do begin
xTresc := SysUtils.format(xTresc, [Anapisydodatkowe[i - 1]]);
end;
with Application do begin
MessageBox(PChar(xTresc), PChar(ANaglowek), mb_OK or mb_IconInformation or mb_ApplModal);
end;
end;
//####################################################################################################################
procedure TKomunikat.WyswietlKomunikat(AKomunikat, ANaglowek: string);
begin
with Application do begin
MessageBox(PChar(AKomunikat), PChar(ANaglowek), mb_OK or mb_IconInformation or mb_ApplModal);
end;
end;
function TKomunikat.WyswietlKomunikatF(AKomunikat: string; ANaglowek: string; Anapisydodatkowe: TArrayOfStrings): integer;
var
xTresc: string;
i: integer;
begin
result := -1;
xTresc := AKomunikat;
for i := 1 to length(Anapisydodatkowe) do begin
xTresc := SysUtils.format(xTresc, [Anapisydodatkowe[i - 1]]);
end;
with Application do begin
if MessageBox(Pchar(xTresc), PChar(ANaglowek), MB_YESNO or MB_ICONWARNING)
= id_Yes then
result := 1;
end;
end;
//####################################################################################################################
function PodajListePlikowWKatalogu(Akatalog: string; var Alista: TStringList): integer;
var
c: TsearchRec;
begin
result := 1;
if SysUtils.FindFirst(Akatalog + '\*.*', FaAnyFile, c) = 0 then begin
if not IsDirNotation(c.Name) then begin
if SysUtils.fileExists(Akatalog + '\' + c.name) then
Alista.Add(Akatalog + '\' + c.name);
end;
while SysUtils.FindNext(c) = 0 do
if not IsDirNotation(c.Name) then begin
if SysUtils.fileExists(Akatalog + '\' + c.name) then
ALista.Add(Akatalog + '\' + c.name);
end;
end;
SysUtils.FindClose(c);
end;
//####################################################################################################################
function IsDirNotation(ADirName: string): Boolean;
begin
Result := (ADirName = '.') or (ADirName = '..');
end;
//####################################################################################################################
function PodajNazwePlikuKataloguZeSciezki(ANapis: string): string;
begin
while pos('\', Anapis) <> 0 do
delete(Anapis, 1, pos('\', Anapis));
result := ANapis;
end;
//####################################################################################################################
//####################################################################################################################
function DateTimeToSql(Avalue: TDateTime): string;
var
OldDecimalSeparator: char;
begin
OldDecimalSeparator := DecimalSeparator;
DecimalSeparator := '.';
result := FloatToStrF(AValue - 2, ffFixed, 15, 8);
DecimalSeparator := OldDecimalSeparator;
end;
//####################################################################################################################
function PodajWartosc(Astring: string): string;
var
xResult: string;
begin
xResult := StringReplace(Astring, '''', '', [rfReplaceAll]);
result := trim(xResult);
end;
//####################################################################################################################
function PodajZWersionRC(AString: string): string;
var
InfoSize, Wnd, VerSize: DWORD;
VerBuf: Pointer;
FI: PVSFixedFileInfo;
p: array[byte] of char;
begin
Result := '';
if (trim(AString) <> '') then begin
InfoSize := GetFileVersionInfoSize(PChar(ParamStr(0)), Wnd);
if (InfoSize <> 0) then begin
GetMem(VerBuf, InfoSize);
try
if GetFileVersionInfo(PChar(ParamStr(0)), Wnd, InfoSize, VerBuf) then
if VerQueryValue(VerBuf, PAnsiChar('\\StringFileInfo\\041504E2\\' + Trim(AString)), Pointer(FI), VerSize) then begin
strCopy(PChar(@p[0]), PChar(FI));
Result := StrPas(p);
end;
finally
FreeMem(VerBuf);
end;
end;
end;
end;
function PodajkatalogMojeDokumenty(AHandle: HWND): string;
var
Allocator: IMalloc;
SpecialDir: PItemIdList;
FBuf: array[0..MAX_PATH] of Char;
begin
if SHGetMalloc(Allocator) = NOERROR then
begin
SHGetSpecialFolderLocation(AHandle
, CSIDL_PERSONAL, SpecialDir);
SHGetPathFromIDList(SpecialDir, @FBuf[0]);
Allocator.Free(SpecialDir);
result := string(FBuf);
end;
end;
function UruchamiajProgramy(APlikExe: string; AParametry: string = ''; ASciezkaDomyslna: string = ''; APoprzezProces: Boolean = False; ACzekajNaKoniec: Boolean = True; AChowajZrodlo: Boolean = True): Integer;
var STARTUPINFO: TStartupInfo;
ProcessInfo: TProcessInformation;
begin
Result:=0;
case APoprzezProces of
False: Result := ShellExecute(0, 'open', PChar(APlikExe), PChar(AParametry), PChar(ASciezkaDomyslna), SW_SHOW);
True: begin
FillChar(STARTUPINFO, SizeOf(TStartupInfo), #0);
STARTUPINFO.cb := SizeOf(STARTUPINFO);
if AChowajZrodlo then begin
with Application do begin
Minimize;
ShowWindow(Handle, SW_HIDE);
end;
end;
Result := Integer(CreateProcess(nil, PChar(APlikExe + ' ' + AParametry), nil, nil, False, 0, nil, PChar(ExtractFilePath(ASciezkaDomyslna)), StartupInfo, ProcessInfo));
if Result <> 0 then begin
if ACzekajNaKoniec then WaitForSingleObject(ProcessInfo.hProcess, INFINITE);
end else begin
ShowMessage(SysErrorMessage(GetLastError));
end;
if AChowajZrodlo then begin
with Application do begin
ShowWindow(Handle, SW_SHOW);
Restore;
end;
end;
end;
end;
end;
end.
|
unit renderable_object_types;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,dglOpenGL,VectorGeometry,core_types,core_camera,
core_material_library,core_matrixStack,core_renderable,core_texture, fgl,
core_actor_definitions;
type
{ TModel }
//do trzymania voxelowych modeli
//to gowno jest jak miniaturowy terrain chunk +rotation Matrix
TModel = class (TRenderable)
mvp,rotationM:tmatrix;
name:string;
itemType:eItemTypes;
pivot:TAffineVector;
constructor create(buffer:PDataBuffer;count:integer);
destructor destroy;
procedure render(leMvp, leTransform: pMatrix);
end;
{ TTerrainChunk }
TTerrainChunk = class(TRenderable)
mvp:tmatrix;
constructor create(buffer:PDataBuffer;byteCount:integer);
destructor destroy;
procedure render;override;
procedure updateVBO(buffer:PDataBuffer;byteCount:integer);
end;
{ TSelectionCube }
TSelectionCube = class (TRenderable)
private
fcolor:tvector4f;
procedure setColor(AValue: TVector4f);
public
property color:TVector4f read fcolor write setColor;
procedure render;override;
constructor create;
destructor destroy;override;
end;
{ TPointLightCube }
//cube light gizmo for deferred renderrer
TPointLightCube = class (TRenderable)
procedure render(nullPass:boolean);
constructor create;
destructor destroy;override;
end;
{ TQuad }
TQuad = class (TRenderable)
procedure render;override;
constructor create;
destructor destroy;override;
end;
{ TTexturedQuad }
// quad is not scaled to texture texture is
//for flat ppl maybe
TTexturedQuad = class (TQuad)
protected
//remember rotation from 'set' commands to avoid costly calculations when getting. and im stupid
angles:TAffinevector;
public
mvp,rotationM:tmatrix;
//texutre indexes in units atlas
texFront,texSide,texBack:integer;
mvpLocation,worldMatricLocation:glint;
procedure render;override;
//rotates around y axis
procedure setRotationY(const angle:single);
procedure setRotationX(const angle:single);
procedure setRotationZ(const angle:single);
procedure setRotationXYZ(const ax,ay,az:single;heightOffset:single = 0);
function getRotation:TAffineVector;
function getYAngle:single;
constructor create(textureInAtlasIndex:integer);
end;
//texture quad that is not square like parent class but conforms to sprite size
{ TUIQuad }
TUIQuad = class(TTexturedQuad)
procedure render;override;
constructor create(atlas:TTextureAtlas;textureInAtlasIndex:integer);
end;
//since modules are separated by messaging sysyem then each interested modelue needs
//coresponding class to represent values needed by it
{ TFlatUnitRenderable }
{ TODO -copti : te sprity uzywaja uniformow zamiast uv w vbo, powinny byc jak uiquad }
TFlatUnitRenderable = class(TTexturedQuad)
actorID:integer;
//flags if crate should be drawn over the actor. and servs as it's id
crateActorID:integer;
assetID:integer;
common:rActorDefinition;
procedure update(angleY: single; sideView: boolean);
constructor create;
end;
//maps actorID to unit
TFlatUnitRenderableMap = specialize TFPgMap<integer,TFlatUnitRenderable>;
implementation
const
cubeVerts :array [0..63] of GLfloat =
( //front face
-0.51, 0.51, 0.51,1, //top left
//colors
1,0,0,0,
0.51, -0.51, 0.51,1, //bottom right
1,0,0,0,
-0.51, -0.51, 0.51,1, //left bottom
1,0,0,0,
0.51, 0.51, 0.51,1, //right top
1,0,0,0,
//back face
-0.51, 0.51, -0.51,1, //top left
0,0,1,0,
0.51, -0.51, -0.51,1, //bottom right
0,0,1,0,
-0.51, -0.51, -0.51,1, //left bottom
0,0,1,0,
0.51, 0.51, -0.51,1, //right top
0,0,1,0
);
cubeIndices: array [0..35] of GLuByte =
(
0,2,1, //front
0,1,3,
3,1,7, //r side
1,5,7,
4,5,6, //back
4,7,5,
0,6,2, //l side
6,0,4,
0,3,4, //top
4,3,7,
2,5,1, //bottom
2,6,5
);
cubeNoColor :array [0..31] of GLfloat =
( //front face
-0.51, 0.51, 0.51,1, //top left
//colors
0.51, -0.51, 0.51,1, //bottom right
-0.51, -0.51, 0.51,1, //left bottom
0.51, 0.51, 0.51,1, //right top
//back face
-0.51, 0.51, -0.51,1, //top left
0.51, -0.51, -0.51,1, //bottom right
-0.51, -0.51, -0.51,1, //left bottom
0.51, 0.51, -0.51,1 //right top
);
quadVerts: array [0..17] of GLfloat =
(
-1,1,0,
-1,-1,0,
1,-1,0,
-1,1,0,
1,-1,0,
1,1,0
);
texQuadVerts: array [0..17] of GLfloat =
(
-0.5,1,0,
-0.5,0,0,
0.5,0,0,
-0.5,1,0,
0.5,0,0,
0.5,1,0
);
{ TUIQuad }
procedure TUIQuad.render;
begin
//no need to set those on each quad render?
glUniformMatrix4fv(mvpLocation, 1, bytebool(GL_FALSE), @mvp);
glUniformMatrix4fv(worldMatricLocation, 1, bytebool(GL_FALSE), @transformM);
glBindVertexArray(vao);
glDrawArrays(GL_TRIANGLEs, 0,6);
glBindVertexArray(0);
end;
constructor TUIQuad.create(atlas: TTextureAtlas; textureInAtlasIndex: integer);
var
buf:array [0..29] of GLfloat;
begin
shaderDesc:='ui quad';
//create quad from atlas params
with atlas.data[textureInAtlasIndex] do begin
//xyz
buf[0]:=0;
buf[1]:=h;
buf[2]:=0;
buf[3]:=(x) / atlas.width;
buf[4]:=(y)/ atlas.height;
buf[5]:=0;
buf[6]:=0;
buf[7]:=0;
buf[8]:=x / atlas.width;
buf[9]:=(y+h)/ atlas.height;
buf[10]:=w;
buf[11]:=h;
buf[12]:=0;
buf[13]:=(x+w) / atlas.width;
buf[14]:=(y)/ atlas.height;
buf[15]:=0;
buf[16]:=0;
buf[17]:=0;
buf[18]:=x / atlas.width;
buf[19]:=(y+h)/ atlas.height;
buf[20]:=w;
buf[21]:=0;
buf[22]:=0;
buf[23]:=(x+w) / atlas.width;
buf[24]:=(y+h)/ atlas.height;
buf[25]:=w;
buf[26]:=h;
buf[27]:=0;
buf[28]:=(x+w) / atlas.width;
buf[29]:=(y)/ atlas.height;
end;
glGenBuffers(1,@vbo);
glGenVertexArrays(1, @vao);
glBindBuffer(GL_ARRAY_BUFFER,vbo);
glBufferData(GL_ARRAY_BUFFER,sizeof(buf),@buf[0],GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER,0);
//setup vao
glBindVertexArray(vao);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER,vbo);
glVertexAttribPointer(0, 3, GL_FLOAT, bytebool(GL_FALSE),5*sizeof(single), nil);
//tutaj stride byc moglby
glVertexAttribPointer(1, 2, GL_FLOAT, bytebool(GL_FALSE), 5*sizeof(single), pointer(3*sizeof(single)));
glBindVertexArray(0);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER,0);
translateM:=IdentityHmgMatrix;
scaleM:=IdentityHmgMatrix;
rotationM:=IdentityHmgMatrix;
setVector(angles,0,0,0);
texFront:=textureInAtlasIndex;
end;
{ TFlatUnitRenderable }
procedure TFlatUnitRenderable.update(angleY: single;sideView:boolean);
begin
// if sideView then begin
//setRotationY(angles[1]+degtorad(45));
//rotationM:=CreateRotationMatrixY(angleY);
//if sideView then scaleM[0,0]:=common.depth else scaleM[0,0]:=common.width;
// dirty:=true;
// end;
if dirty then begin
MatrixMultiply(scaleM,rotationM,transformM);
MatrixMultiply(transformM,translateM,transformM);
dirty:=false;
//chuj
end;
// end;
MatrixMultiply(transformM,worldCameraMatrix,mvp);
end;
constructor TFlatUnitRenderable.create;
begin
translateM:=IdentityHmgMatrix;
scaleM:=IdentityHmgMatrix;
rotationM:=IdentityHmgMatrix;
texFront:=0;
crateActorID:=-1;
end;
{ TTexturedQuad }
procedure TTexturedQuad.render;
begin
//no need to set those on each quad render?
glUniformMatrix4fv(mvpLocation, 1, bytebool(GL_FALSE), @mvp);
glUniformMatrix4fv(worldMatricLocation, 1, bytebool(GL_FALSE), @transformM);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER,vbo);
glVertexAttribPointer(0, 3, GL_FLOAT, bytebool(GL_FALSE), 0, nil);
glDrawArrays(GL_TRIANGLES, 0,6);
glDisableVertexAttribArray(0);
end;
procedure TTexturedQuad.setRotationY(const angle: single);
begin
angles[1]:=angle;
rotationM:=CreateRotationMatrixY(angle);
dirty:=true;
end;
procedure TTexturedQuad.setRotationX(const angle: single);
begin
angles[0]:=angle;
rotationM:=CreateRotationMatrixX(angle);
dirty:=true;
end;
procedure TTexturedQuad.setRotationZ(const angle: single);
begin
angles[2]:=angle;
rotationM:=CreateRotationMatrixZ(angle);
dirty:=true;
end;
procedure TTexturedQuad.setRotationXYZ(const ax, ay, az: single;
heightOffset: single);
begin
//ef wtf
angles[0]:=ax;
angles[1]:=ay;
angles[2]:=az;
rotationM:=IdentityHmgMatrix;
//rotationM:=translateM;
TranslateMatrix(rotationM,vector3fmake(0,-heightOffset,0));
//QuaternionFromRollPitchYaw();
rotationM:=turn(rotationM,-ay);
rotationM:=pitch(rotationM,-ax);
rotationM:=roll(rotationM,-az);
TranslateMatrix(rotationM,vector3fmake(0,+heightOffset,0));
dirty:=true;
end;
function TTexturedQuad.getRotation: TAffineVector;
begin
result:=angles;
end;
function TTexturedQuad.getYAngle: single;
begin
result:=angles[1];
end;
constructor TTexturedQuad.create(textureInAtlasIndex:integer);
begin
shaderDesc:='flat quad';
glGenBuffers(1,@vbo);
glBindBuffer(GL_ARRAY_BUFFER,vbo);
glBufferData(GL_ARRAY_BUFFER,sizeof(texquadVerts),@texquadVerts[0],GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER,0);
translateM:=IdentityHmgMatrix;
scaleM:=IdentityHmgMatrix;
rotationM:=IdentityHmgMatrix;
setVector(angles,0,0,0);
texFront:=textureInAtlasIndex;
end;
{ TPointLightCube }
procedure TPointLightCube.render(nullPass:boolean);
var
t:tmatrix;
g:glint;
begin
// inherited;
// matrixStack.push(@transformM);
//translate or transform?
// t:=cameraToClipMatrix * worldToCameraMatrix * modelToWorldMatrix
//MatrixMultiply(transformM,camera.worldToCameraMatrix,t);
//MatrixMultiply(t,camera.projectionMatrix,t);
//t:=IdentityHmgMatrix;
//MatrixMultiply(translateM,scaleM,transformM);
if nullPass then glUniformMatrix4fv(matlib.shaderNullDS.gWVP, 1, bytebool(GL_FALSE), @transformM)
else glUniformMatrix4fv(matlib.shaderCubeLightDS.unifMvp, 1, bytebool(GL_FALSE), @transformM);
glBindVertexArray(vao);
glDrawElements(GL_TRIANGLES, sizeof(cubeIndices), GL_UNSIGNED_BYTE, nil);
glBindVertexArray(0);
// matrixStack.pop;
end;
constructor TPointLightCube.create;
var
s:string;
begin
inherited;
shaderDesc:='cubic light';
glGenVertexArrays(1, @vao);
glGenBuffers(1,@vbo);
glGenBuffers(1, @ibo);
glBindBuffer(GL_ARRAY_BUFFER,vbo);
glBufferData(GL_ARRAY_BUFFER,sizeof(cubeNoColor),@cubeNoColor[0],GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(cubeIndices), @cubeIndices[0], GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER,0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
//setup cube vao
glBindVertexArray(vao);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER,vbo);
//stride to rozmiar calej paczki czyli vert+color dlatego 8
glVertexAttribPointer(0, 4, GL_FLOAT, bytebool(GL_FALSE), 0, nil);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER,0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glDisableVertexAttribArray(0);
//getMaterial('simple');
//s:=gluErrorString(glGetError());
end;
destructor TPointLightCube.destroy;
begin
inherited destroy;
end;
{ TQuad }
procedure TQuad.render;
var
s:string;
t:tmatrix;
begin
//t:=IdentityHmgMatrix;
//matrixStack.push(@t); //move camera instead of world -style
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER,vbo);
glVertexAttribPointer(0, 3, GL_FLOAT, bytebool(GL_FALSE), 0, nil);
glDrawArrays(GL_TRIANGLES, 0,6);
glDisableVertexAttribArray(0);
// glBindBuffer(GL_ARRAY_BUFFER,0);
end;
constructor TQuad.create;
var
s:string;
begin
inherited;
shaderDesc:='flat quad';
translateM:=IdentityHmgMatrix;
glGenBuffers(1,@vbo);
glBindBuffer(GL_ARRAY_BUFFER,vbo);
glBufferData(GL_ARRAY_BUFFER,sizeof(quadVerts),@quadVerts[0],GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER,0);
//s:=gluErrorString(glGetError());
end;
destructor TQuad.destroy;
begin
inherited destroy;
end;
{ TTerrainChunk }
procedure TTerrainChunk.render;
var
kid:TRenderable;
s:string;
begin
// inherited;
//for some reason matrix transformation order needs to be reveresed interrain chunk..
//byc moze dlatego musialem odwracac wszystko w pickingu breshanma
if dirty then begin
//there been a transformation or camera moved so recalculate stuff
MatrixMultiply(translateM,scaleM,transformM);
// mvp:=cameraToClipMatrix * worldToCameraMatrix * modelToWorldMatrix
MatrixMultiply(transformM,worldCameraMatrix,mvp);
dirty:=false;
end;
//matrixStack.push(@transformM);
glUniformMatrix4fv(matlib.shaderChunkDS.unifMVP, 1, bytebool(GL_FALSE), @mvp);
glUniformMatrix4fv(matlib.shaderChunkDS.m_WorldMatrixLocation, 1, bytebool(GL_FALSE), @translateM);
glBindVertexArray(vao);
//if wtf=2 then
glDrawArrays(GL_TRIANGLEs, 0,verticesCount);
glBindVertexArray(0);
// matrixStack.pop;
end;
//count to ilosc single *(vertex + kolor) ale jeszcze trzeba pomozyc przez rozmiar single
constructor TTerrainChunk.create(buffer:PDataBuffer;byteCount:integer);
var
s:string;
u:glint;
begin
inherited Create();
mvp:=IdentityHmgMatrix;
shaderDesc:='geom terrain chunk';
translateM:=IdentityHmgMatrix;
verticesCount:=(byteCount div 2) div 3; //div 2 because color and position, div3 cause triangle is made of 3
glGenVertexArrays(1, @vao);
glGenBuffers(1,@vbo);
// glGenBuffers(1, @ibo);
glBindBuffer(GL_ARRAY_BUFFER,vbo);
glBufferData(GL_ARRAY_BUFFER,byteCount,@buffer^[0],GL_DYNAMIC_DRAW );
glBindBuffer(GL_ARRAY_BUFFER,0);
//setup vao
glBindVertexArray(vao);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER,vbo);
glVertexAttribPointer(0, 4, GL_FLOAT, bytebool(GL_FALSE),8*sizeof(single), nil);
//tutaj stride byc moglby
glVertexAttribPointer(1, 4, GL_FLOAT, bytebool(GL_FALSE), 8*sizeof(single), pointer(4*sizeof(single)));
glBindVertexArray(0);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER,0);
//getMaterial('geom');
//s:=gluErrorString(glGetError());
end;
procedure TTerrainChunk.updateVBO(buffer:PDataBuffer;byteCount:integer);
begin
//glDeleteBuffers(1, @vbo);
//glGenBuffers(1,@vbo);
verticesCount:=(byteCount div sizeOf(rBufferDataBit));
glBindBuffer(GL_ARRAY_BUFFER,vbo);
glBufferData(GL_ARRAY_BUFFER,byteCount,@buffer^[0],GL_DYNAMIC_DRAW );
glBindBuffer(GL_ARRAY_BUFFER,0);
end;
destructor TTerrainChunk.destroy;
begin
inherited;
glDeleteBuffers(1, @vbo);
glDeleteVertexArrays (1, @vao);
end;
procedure TSelectionCube.setColor(AValue: TVector4f);
begin
//if fcolor=AValue then Exit;
fcolor:=AValue;
glUniform4f(matlib.shaderSelectionCube.unifColor,AValue[0],AValue[1],AValue[2],AValue[3]);
end;
procedure TSelectionCube.render;
var
t:tmatrix;
begin
inherited;
//matrixStack.push(@transformM);
//glUniformMatrix4fv(uniformMvp, 1, bytebool(GL_FALSE), @mvpMatrix);
glUniformMatrix4fv(matlib.shaderSelectionCube.unifModelToWorldMatrix, 1, bytebool(GL_FALSE), @transformM);
glBindVertexArray(vao);
glDrawElements(GL_TRIANGLES, sizeof(cubeIndices), GL_UNSIGNED_BYTE, nil);
glBindVertexArray(0);
// for kid in kids do kid.render;
// matrixStack.pop;
end;
constructor TSelectionCube.create;
var
s:string;
begin
inherited;
shaderDesc:='colored cube';
fcolor:=vector4fmake(0.1,0.1,0.3,0.5);
translateM:=IdentityHmgMatrix;
glGenVertexArrays(1, @vao);
glGenBuffers(1,@vbo);
glGenBuffers(1, @ibo);
glBindBuffer(GL_ARRAY_BUFFER,vbo);
glBufferData(GL_ARRAY_BUFFER,sizeof(cubeNoColor),@cubeNoColor[0],GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(cubeIndices), @cubeIndices[0], GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER,0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
//setup cube vao
glBindVertexArray(vao);
glEnableVertexAttribArray(0);
//glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER,vbo);
//stride to rozmiar calej paczki czyli vert+color dlatego 8
glVertexAttribPointer(0, 4, GL_FLOAT, bytebool(GL_FALSE),0, nil);
//verts interleaved with colour
//glVertexAttribPointer(1, 4, GL_FLOAT, bytebool(GL_FALSE), 8*sizeof(single), pointer(4*sizeof(single)));
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER,0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glDisableVertexAttribArray(0);
//glDisableVertexAttribArray(1);
//getMaterial('simple');
//s:=gluErrorString(glGetError());
end;
destructor TSelectionCube.destroy;
begin
inherited destroy;
glDeleteBuffers(1, @vbo);
glDeleteVertexArrays (1, @vao);
glDeleteBuffers(1, @ibo);
end;
{ TModel }
constructor TModel.create(buffer: PDataBuffer; count: integer);
var
s:string;
u:glint;
i:integer;
r:rBufferDataBit;
begin
inherited Create();
mvp:=IdentityHmgMatrix;
rotationM:=IdentityHmgMatrix;
scaleM:=IdentityHmgMatrix;
shaderDesc:='geom terrain chunk';
translateM:=IdentityHmgMatrix;
//find the pivot point
for i:=0 to count-1 do
verticesCount:=(Count div sizeOf(rBufferDataBit));
glGenVertexArrays(1, @vao);
glGenBuffers(1,@vbo);
// glGenBuffers(1, @ibo);
glBindBuffer(GL_ARRAY_BUFFER,vbo);
glBufferData(GL_ARRAY_BUFFER,count,@buffer^[0],GL_DYNAMIC_DRAW );
glBindBuffer(GL_ARRAY_BUFFER,0);
//setup vao
glBindVertexArray(vao);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER,vbo);
glVertexAttribPointer(0, 4, GL_FLOAT, bytebool(GL_FALSE),8*sizeof(single), nil);
//tutaj stride byc moglby
glVertexAttribPointer(1, 4, GL_FLOAT, bytebool(GL_FALSE), 8*sizeof(single), pointer(4*sizeof(single)));
glBindVertexArray(0);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER,0);
//getMaterial('geom');
//s:=gluErrorString(glGetError());
end;
destructor TModel.destroy;
begin
inherited;
glDeleteBuffers(1, @vbo);
glDeleteVertexArrays (1, @vao);
end;
procedure TModel.render(leMvp, leTransform: pMatrix);
var
kid:TRenderable;
s:string;
begin
//glUniform1i(matlib.shaderChunkDS.ghostUnif,integer(ghost));
glUniformMatrix4fv(matlib.shaderChunkDS.unifMVP, 1, bytebool(GL_FALSE), leMvp[0,0]);
glUniformMatrix4fv(matlib.shaderChunkDS.m_WorldMatrixLocation, 1, bytebool(GL_FALSE), leTransform[0,0]);
glBindVertexArray(vao);
glDrawArrays(GL_TRIANGLEs, 0,verticesCount);
glBindVertexArray(0);
end;
end.
|
unit sedittextfloatinglabel;
{$mode delphi}
interface
uses
Classes, SysUtils, And_jni, And_jni_Bridge, AndroidWidget, Laz_And_Controls;
type
{Draft Component code by "Lazarus Android Module Wizard" [12/30/2017 0:18:06]}
{https://github.com/jmpessoa/lazandroidmodulewizard}
{jVisualControl template}
jsEditTextFloatingLabel = class(jVisualControl)
private
procedure SetVisible(Value: Boolean);
procedure SetColor(Value: TARGBColorBridge); //background
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Init; override;
procedure Refresh;
procedure UpdateLayout; override;
procedure GenEvent_OnClick(Obj: TObject);
function jCreate(): jObject;
procedure jFree();
procedure SetViewParent(_viewgroup: jObject);
function GetParent(): jObject;
procedure RemoveFromViewParent();
function GetView(): jObject;
procedure SetLParamWidth(_w: integer);
procedure SetLParamHeight(_h: integer);
function GetLParamWidth(): integer;
function GetLParamHeight(): integer;
procedure SetLGravity(_g: integer);
procedure SetLWeight(_w: single);
procedure SetLeftTopRightBottomWidthHeight(_left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer);
procedure AddLParamsAnchorRule(_rule: integer);
procedure AddLParamsParentRule(_rule: integer);
procedure SetLayoutAll(_idAnchor: integer);
procedure ClearLayout();
published
property BackgroundColor: TARGBColorBridge read FColor write SetColor;
property OnClick: TOnNotify read FOnClick write FOnClick;
end;
function jsEditTextFloatingLabel_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject;
procedure jsEditTextFloatingLabel_jFree(env: PJNIEnv; _jsedittextfloatinglabel: JObject);
procedure jsEditTextFloatingLabel_SetViewParent(env: PJNIEnv; _jsedittextfloatinglabel: JObject; _viewgroup: jObject);
function jsEditTextFloatingLabel_GetParent(env: PJNIEnv; _jsedittextfloatinglabel: JObject): jObject;
procedure jsEditTextFloatingLabel_RemoveFromViewParent(env: PJNIEnv; _jsedittextfloatinglabel: JObject);
function jsEditTextFloatingLabel_GetView(env: PJNIEnv; _jsedittextfloatinglabel: JObject): jObject;
procedure jsEditTextFloatingLabel_SetLParamWidth(env: PJNIEnv; _jsedittextfloatinglabel: JObject; _w: integer);
procedure jsEditTextFloatingLabel_SetLParamHeight(env: PJNIEnv; _jsedittextfloatinglabel: JObject; _h: integer);
function jsEditTextFloatingLabel_GetLParamWidth(env: PJNIEnv; _jsedittextfloatinglabel: JObject): integer;
function jsEditTextFloatingLabel_GetLParamHeight(env: PJNIEnv; _jsedittextfloatinglabel: JObject): integer;
procedure jsEditTextFloatingLabel_SetLGravity(env: PJNIEnv; _jsedittextfloatinglabel: JObject; _g: integer);
procedure jsEditTextFloatingLabel_SetLWeight(env: PJNIEnv; _jsedittextfloatinglabel: JObject; _w: single);
procedure jsEditTextFloatingLabel_SetLeftTopRightBottomWidthHeight(env: PJNIEnv; _jsedittextfloatinglabel: JObject; _left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer);
procedure jsEditTextFloatingLabel_AddLParamsAnchorRule(env: PJNIEnv; _jsedittextfloatinglabel: JObject; _rule: integer);
procedure jsEditTextFloatingLabel_AddLParamsParentRule(env: PJNIEnv; _jsedittextfloatinglabel: JObject; _rule: integer);
procedure jsEditTextFloatingLabel_SetLayoutAll(env: PJNIEnv; _jsedittextfloatinglabel: JObject; _idAnchor: integer);
procedure jsEditTextFloatingLabel_ClearLayoutAll(env: PJNIEnv; _jsedittextfloatinglabel: JObject);
procedure jsEditTextFloatingLabel_SetId(env: PJNIEnv; _jsedittextfloatinglabel: JObject; _id: integer);
implementation
{--------- jsEditTextFloatingLabel --------------}
constructor jsEditTextFloatingLabel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
if gapp <> nil then FId := gapp.GetNewId();
FMarginLeft := 10;
FMarginTop := 10;
FMarginBottom := 10;
FMarginRight := 10;
FHeight := 96; //??
FWidth := 96; //??
FLParamWidth := lpMatchParent; //lpWrapContent
FLParamHeight := lpWrapContent; //lpMatchParent
FAcceptChildrenAtDesignTime:= False;
//your code here....
end;
destructor jsEditTextFloatingLabel.Destroy;
begin
if not (csDesigning in ComponentState) then
begin
if FjObject <> nil then
begin
jFree();
FjObject:= nil;
end;
end;
//you others free code here...'
inherited Destroy;
end;
procedure jsEditTextFloatingLabel.Init;
var
rToP: TPositionRelativeToParent;
rToA: TPositionRelativeToAnchorID;
begin
if not FInitialized then
begin
inherited Init; //set default ViewParent/FjPRLayout as jForm.View!
//your code here: set/initialize create params....
FjObject := jCreate(); if FjObject = nil then exit;
if FParent <> nil then
sysTryNewParent( FjPRLayout, FParent);
jsEditTextFloatingLabel_SetViewParent(gApp.jni.jEnv, FjObject, FjPRLayout);
jsEditTextFloatingLabel_SetId(gApp.jni.jEnv, FjObject, Self.Id);
end;
jsEditTextFloatingLabel_setLeftTopRightBottomWidthHeight(gApp.jni.jEnv, FjObject ,
FMarginLeft,FMarginTop,FMarginRight,FMarginBottom,
sysGetLayoutParams( FWidth, FLParamWidth, Self.Parent, sdW, fmarginLeft + fmarginRight ),
sysGetLayoutParams( FHeight, FLParamHeight, Self.Parent, sdH, fMargintop + fMarginbottom ));
for rToA := raAbove to raAlignRight do
begin
if rToA in FPositionRelativeToAnchor then
begin
jsEditTextFloatingLabel_AddLParamsAnchorRule(gApp.jni.jEnv, FjObject, GetPositionRelativeToAnchor(rToA));
end;
end;
for rToP := rpBottom to rpCenterVertical do
begin
if rToP in FPositionRelativeToParent then
begin
jsEditTextFloatingLabel_AddLParamsParentRule(gApp.jni.jEnv, FjObject, GetPositionRelativeToParent(rToP));
end;
end;
if Self.Anchor <> nil then Self.AnchorId:= Self.Anchor.Id
else Self.AnchorId:= -1; //dummy
jsEditTextFloatingLabel_SetLayoutAll(gApp.jni.jEnv, FjObject, Self.AnchorId);
if not FInitialized then
begin
FInitialized:= True;
if FColor <> colbrDefault then
View_SetBackGroundColor(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, FColor));
View_SetVisible(gApp.jni.jEnv, FjObject, FVisible);
end;
end;
procedure jsEditTextFloatingLabel.SetColor(Value: TARGBColorBridge);
begin
FColor:= Value;
if (FInitialized = True) and (FColor <> colbrDefault) then
View_SetBackGroundColor(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, FColor));
end;
procedure jsEditTextFloatingLabel.SetVisible(Value : Boolean);
begin
FVisible:= Value;
if FInitialized then
View_SetVisible(gApp.jni.jEnv, FjObject, FVisible);
end;
procedure jsEditTextFloatingLabel.UpdateLayout;
begin
if not FInitialized then exit;
ClearLayout();
inherited UpdateLayout;
init;
end;
procedure jsEditTextFloatingLabel.Refresh;
begin
if FInitialized then
View_Invalidate(gApp.jni.jEnv, FjObject);
end;
//Event : Java -> Pascal
procedure jsEditTextFloatingLabel.GenEvent_OnClick(Obj: TObject);
begin
if Assigned(FOnClick) then FOnClick(Obj);
end;
function jsEditTextFloatingLabel.jCreate(): jObject;
begin
Result:= jsEditTextFloatingLabel_jCreate(gApp.jni.jEnv, int64(Self), gApp.jni.jThis);
end;
procedure jsEditTextFloatingLabel.jFree();
begin
//in designing component state: set value here...
if FInitialized then
jsEditTextFloatingLabel_jFree(gApp.jni.jEnv, FjObject);
end;
procedure jsEditTextFloatingLabel.SetViewParent(_viewgroup: jObject);
begin
//in designing component state: set value here...
if FInitialized then
jsEditTextFloatingLabel_SetViewParent(gApp.jni.jEnv, FjObject, _viewgroup);
end;
function jsEditTextFloatingLabel.GetParent(): jObject;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jsEditTextFloatingLabel_GetParent(gApp.jni.jEnv, FjObject);
end;
procedure jsEditTextFloatingLabel.RemoveFromViewParent();
begin
//in designing component state: set value here...
if FInitialized then
jsEditTextFloatingLabel_RemoveFromViewParent(gApp.jni.jEnv, FjObject);
end;
function jsEditTextFloatingLabel.GetView(): jObject;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jsEditTextFloatingLabel_GetView(gApp.jni.jEnv, FjObject);
end;
procedure jsEditTextFloatingLabel.SetLParamWidth(_w: integer);
begin
//in designing component state: set value here...
if FInitialized then
jsEditTextFloatingLabel_SetLParamWidth(gApp.jni.jEnv, FjObject, _w);
end;
procedure jsEditTextFloatingLabel.SetLParamHeight(_h: integer);
begin
//in designing component state: set value here...
if FInitialized then
jsEditTextFloatingLabel_SetLParamHeight(gApp.jni.jEnv, FjObject, _h);
end;
function jsEditTextFloatingLabel.GetLParamWidth(): integer;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jsEditTextFloatingLabel_GetLParamWidth(gApp.jni.jEnv, FjObject);
end;
function jsEditTextFloatingLabel.GetLParamHeight(): integer;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jsEditTextFloatingLabel_GetLParamHeight(gApp.jni.jEnv, FjObject);
end;
procedure jsEditTextFloatingLabel.SetLGravity(_g: integer);
begin
//in designing component state: set value here...
if FInitialized then
jsEditTextFloatingLabel_SetLGravity(gApp.jni.jEnv, FjObject, _g);
end;
procedure jsEditTextFloatingLabel.SetLWeight(_w: single);
begin
//in designing component state: set value here...
if FInitialized then
jsEditTextFloatingLabel_SetLWeight(gApp.jni.jEnv, FjObject, _w);
end;
procedure jsEditTextFloatingLabel.SetLeftTopRightBottomWidthHeight(_left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer);
begin
//in designing component state: set value here...
if FInitialized then
jsEditTextFloatingLabel_SetLeftTopRightBottomWidthHeight(gApp.jni.jEnv, FjObject, _left ,_top ,_right ,_bottom ,_w ,_h);
end;
procedure jsEditTextFloatingLabel.AddLParamsAnchorRule(_rule: integer);
begin
//in designing component state: set value here...
if FInitialized then
jsEditTextFloatingLabel_AddLParamsAnchorRule(gApp.jni.jEnv, FjObject, _rule);
end;
procedure jsEditTextFloatingLabel.AddLParamsParentRule(_rule: integer);
begin
//in designing component state: set value here...
if FInitialized then
jsEditTextFloatingLabel_AddLParamsParentRule(gApp.jni.jEnv, FjObject, _rule);
end;
procedure jsEditTextFloatingLabel.SetLayoutAll(_idAnchor: integer);
begin
//in designing component state: set value here...
if FInitialized then
jsEditTextFloatingLabel_SetLayoutAll(gApp.jni.jEnv, FjObject, _idAnchor);
end;
procedure jsEditTextFloatingLabel.ClearLayout();
var
rToP: TPositionRelativeToParent;
rToA: TPositionRelativeToAnchorID;
begin
//in designing component state: set value here...
if FInitialized then
begin
jsEditTextFloatingLabel_clearLayoutAll(gApp.jni.jEnv, FjObject);
for rToP := rpBottom to rpCenterVertical do
if rToP in FPositionRelativeToParent then
jsEditTextFloatingLabel_addlParamsParentRule(gApp.jni.jEnv, FjObject , GetPositionRelativeToParent(rToP));
for rToA := raAbove to raAlignRight do
if rToA in FPositionRelativeToAnchor then
jsEditTextFloatingLabel_addlParamsAnchorRule(gApp.jni.jEnv, FjObject , GetPositionRelativeToAnchor(rToA));
end;
end;
{-------- jsEditTextFloatingLabel_JNI_Bridge ----------}
function jsEditTextFloatingLabel_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject;
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].j:= _Self;
jCls:= Get_gjClass(env);
jMethod:= env^.GetMethodID(env, jCls, 'jsEditTextFloatingLabel_jCreate', '(J)Ljava/lang/Object;');
Result:= env^.CallObjectMethodA(env, this, jMethod, @jParams);
Result:= env^.NewGlobalRef(env, Result);
end;
procedure jsEditTextFloatingLabel_jFree(env: PJNIEnv; _jsedittextfloatinglabel: JObject);
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jsedittextfloatinglabel);
jMethod:= env^.GetMethodID(env, jCls, 'jFree', '()V');
env^.CallVoidMethod(env, _jsedittextfloatinglabel, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
procedure jsEditTextFloatingLabel_SetViewParent(env: PJNIEnv; _jsedittextfloatinglabel: JObject; _viewgroup: jObject);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= _viewgroup;
jCls:= env^.GetObjectClass(env, _jsedittextfloatinglabel);
jMethod:= env^.GetMethodID(env, jCls, 'SetViewParent', '(Landroid/view/ViewGroup;)V');
env^.CallVoidMethodA(env, _jsedittextfloatinglabel, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
function jsEditTextFloatingLabel_GetParent(env: PJNIEnv; _jsedittextfloatinglabel: JObject): jObject;
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jsedittextfloatinglabel);
jMethod:= env^.GetMethodID(env, jCls, 'GetParent', '()Landroid/view/ViewGroup;');
Result:= env^.CallObjectMethod(env, _jsedittextfloatinglabel, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
procedure jsEditTextFloatingLabel_RemoveFromViewParent(env: PJNIEnv; _jsedittextfloatinglabel: JObject);
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jsedittextfloatinglabel);
jMethod:= env^.GetMethodID(env, jCls, 'RemoveFromViewParent', '()V');
env^.CallVoidMethod(env, _jsedittextfloatinglabel, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
function jsEditTextFloatingLabel_GetView(env: PJNIEnv; _jsedittextfloatinglabel: JObject): jObject;
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jsedittextfloatinglabel);
jMethod:= env^.GetMethodID(env, jCls, 'GetView', '()Landroid/view/View;');
Result:= env^.CallObjectMethod(env, _jsedittextfloatinglabel, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
procedure jsEditTextFloatingLabel_SetLParamWidth(env: PJNIEnv; _jsedittextfloatinglabel: JObject; _w: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _w;
jCls:= env^.GetObjectClass(env, _jsedittextfloatinglabel);
jMethod:= env^.GetMethodID(env, jCls, 'SetLParamWidth', '(I)V');
env^.CallVoidMethodA(env, _jsedittextfloatinglabel, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jsEditTextFloatingLabel_SetLParamHeight(env: PJNIEnv; _jsedittextfloatinglabel: JObject; _h: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _h;
jCls:= env^.GetObjectClass(env, _jsedittextfloatinglabel);
jMethod:= env^.GetMethodID(env, jCls, 'SetLParamHeight', '(I)V');
env^.CallVoidMethodA(env, _jsedittextfloatinglabel, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
function jsEditTextFloatingLabel_GetLParamWidth(env: PJNIEnv; _jsedittextfloatinglabel: JObject): integer;
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jsedittextfloatinglabel);
jMethod:= env^.GetMethodID(env, jCls, 'GetLParamWidth', '()I');
Result:= env^.CallIntMethod(env, _jsedittextfloatinglabel, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
function jsEditTextFloatingLabel_GetLParamHeight(env: PJNIEnv; _jsedittextfloatinglabel: JObject): integer;
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jsedittextfloatinglabel);
jMethod:= env^.GetMethodID(env, jCls, 'GetLParamHeight', '()I');
Result:= env^.CallIntMethod(env, _jsedittextfloatinglabel, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
procedure jsEditTextFloatingLabel_SetLGravity(env: PJNIEnv; _jsedittextfloatinglabel: JObject; _g: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _g;
jCls:= env^.GetObjectClass(env, _jsedittextfloatinglabel);
jMethod:= env^.GetMethodID(env, jCls, 'SetLGravity', '(I)V');
env^.CallVoidMethodA(env, _jsedittextfloatinglabel, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jsEditTextFloatingLabel_SetLWeight(env: PJNIEnv; _jsedittextfloatinglabel: JObject; _w: single);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].f:= _w;
jCls:= env^.GetObjectClass(env, _jsedittextfloatinglabel);
jMethod:= env^.GetMethodID(env, jCls, 'SetLWeight', '(F)V');
env^.CallVoidMethodA(env, _jsedittextfloatinglabel, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jsEditTextFloatingLabel_SetLeftTopRightBottomWidthHeight(env: PJNIEnv; _jsedittextfloatinglabel: JObject; _left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer);
var
jParams: array[0..5] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _left;
jParams[1].i:= _top;
jParams[2].i:= _right;
jParams[3].i:= _bottom;
jParams[4].i:= _w;
jParams[5].i:= _h;
jCls:= env^.GetObjectClass(env, _jsedittextfloatinglabel);
jMethod:= env^.GetMethodID(env, jCls, 'SetLeftTopRightBottomWidthHeight', '(IIIIII)V');
env^.CallVoidMethodA(env, _jsedittextfloatinglabel, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jsEditTextFloatingLabel_AddLParamsAnchorRule(env: PJNIEnv; _jsedittextfloatinglabel: JObject; _rule: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _rule;
jCls:= env^.GetObjectClass(env, _jsedittextfloatinglabel);
jMethod:= env^.GetMethodID(env, jCls, 'AddLParamsAnchorRule', '(I)V');
env^.CallVoidMethodA(env, _jsedittextfloatinglabel, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jsEditTextFloatingLabel_AddLParamsParentRule(env: PJNIEnv; _jsedittextfloatinglabel: JObject; _rule: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _rule;
jCls:= env^.GetObjectClass(env, _jsedittextfloatinglabel);
jMethod:= env^.GetMethodID(env, jCls, 'AddLParamsParentRule', '(I)V');
env^.CallVoidMethodA(env, _jsedittextfloatinglabel, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jsEditTextFloatingLabel_SetLayoutAll(env: PJNIEnv; _jsedittextfloatinglabel: JObject; _idAnchor: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _idAnchor;
jCls:= env^.GetObjectClass(env, _jsedittextfloatinglabel);
jMethod:= env^.GetMethodID(env, jCls, 'SetLayoutAll', '(I)V');
env^.CallVoidMethodA(env, _jsedittextfloatinglabel, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jsEditTextFloatingLabel_ClearLayoutAll(env: PJNIEnv; _jsedittextfloatinglabel: JObject);
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jsedittextfloatinglabel);
jMethod:= env^.GetMethodID(env, jCls, 'ClearLayoutAll', '()V');
env^.CallVoidMethod(env, _jsedittextfloatinglabel, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
procedure jsEditTextFloatingLabel_SetId(env: PJNIEnv; _jsedittextfloatinglabel: JObject; _id: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _id;
jCls:= env^.GetObjectClass(env, _jsedittextfloatinglabel);
jMethod:= env^.GetMethodID(env, jCls, 'setId', '(I)V');
env^.CallVoidMethodA(env, _jsedittextfloatinglabel, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
end.
|
unit RecalcMCSSheduler;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, AncestorDBGrid, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, cxPCdxBarPopupMenu, cxStyles, cxCustomData, cxFilter,
cxData, cxDataStorage, cxEdit, Data.DB, cxDBData,
Vcl.Menus, dsdAddOn, dxBarExtItems, dxBar, cxClasses, dsdDB,
Datasnap.DBClient, dsdAction, Vcl.ActnList, cxPropertiesStore, cxGridLevel,
cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView,
cxGrid, cxPC, cxButtonEdit, Vcl.ExtCtrls, cxSplitter, cxDropDownEdit,
dxSkinsCore, dxSkinsDefaultPainters, dxSkinscxPCPainter, dxSkinsdxBarPainter,
dxBarBuiltInMenu, cxNavigator, cxContainer, Vcl.ComCtrls, dxCore, cxDateUtils,
cxLabel, cxTextEdit, cxMaskEdit, cxCalendar, dsdGuides;
type
TRecalcMCSShedulerForm = class(TAncestorDBGridForm)
bbSetErased: TdxBarButton;
bbUnErased: TdxBarButton;
bbSetErasedChild: TdxBarButton;
bbUnErasedChild: TdxBarButton;
bbdsdChoiceGuides: TdxBarButton;
cxSplitter1: TcxSplitter;
Ord: TcxGridDBColumn;
actInsert: TdsdInsertUpdateAction;
actUpdate: TdsdInsertUpdateAction;
dxBarButton1: TdxBarButton;
dxBarButton2: TdxBarButton;
Color_cal: TcxGridDBColumn;
dxBarButton3: TdxBarButton;
dxBarButton4: TdxBarButton;
dxBarButton5: TdxBarButton;
actOpenUnitTree: TOpenChoiceForm;
actAddUnit: TMultiAction;
actOpenRecalcMCSShedulerEdit: TdsdOpenForm;
FormParams: TdsdFormParams;
Panel1: TPanel;
edBeginHolidays: TcxDateEdit;
cxLabel2: TcxLabel;
edEndHolidays: TcxDateEdit;
cxLabel1: TcxLabel;
spGetHolidays: TdsdStoredProc;
spUpdateHolidays: TdsdStoredProc;
HeaderSaver: THeaderSaver;
spInsertUpdateMovement: TdsdExecStoredProc;
bbInsertUpdateMovement: TdxBarButton;
AllRetail: TcxGridDBColumn;
RetailName: TcxGridDBColumn;
DateRun: TcxGridDBColumn;
actRecalcMCSSheduler: TdsdExecStoredProc;
spRecalcMCSSheduler: TdsdStoredProc;
dxBarButton6: TdxBarButton;
UserRun: TcxGridDBColumn;
SelectRun: TcxGridDBColumn;
actRecalcMCSShedulerSelect: TdsdExecStoredProc;
actUpdateDataSet: TdsdUpdateDataSet;
spRecalcMCSShedulerSelect: TdsdStoredProc;
spUpdate_SelectRun: TdsdStoredProc;
dxBarButton7: TdxBarButton;
DateRunSun: TcxGridDBColumn;
dsdSetUnErased: TdsdUpdateErased;
dsdSetErased: TdsdUpdateErased;
dxBarButton8: TdxBarButton;
dxBarButton9: TdxBarButton;
spErasedUnErased: TdsdStoredProc;
Period: TcxGridDBColumn;
Period1: TcxGridDBColumn;
Period2: TcxGridDBColumn;
Period3: TcxGridDBColumn;
Period4: TcxGridDBColumn;
Period5: TcxGridDBColumn;
Period6: TcxGridDBColumn;
Period7: TcxGridDBColumn;
PeriodSun1: TcxGridDBColumn;
PeriodSun2: TcxGridDBColumn;
PeriodSun3: TcxGridDBColumn;
PeriodSun4: TcxGridDBColumn;
PeriodSun5: TcxGridDBColumn;
PeriodSun6: TcxGridDBColumn;
PeriodSun7: TcxGridDBColumn;
actExecuteSunDialog: TExecuteDialog;
actUpdateSun: TMultiAction;
actExecSPUpdateactSun: TdsdExecStoredProc;
spUpdateactSun: TdsdStoredProc;
dxBarButton10: TdxBarButton;
actShowErased: TBooleanStoredProcAction;
bbShowErased: TdxBarButton;
Comment: TcxGridDBColumn;
actExecuteDialogMain: TExecuteDialog;
actUpdateMain: TMultiAction;
actExecSPUpdateactMain: TdsdExecStoredProc;
spUpdateactMain: TdsdStoredProc;
dxBarButton11: TdxBarButton;
actReport_RecalcMCS: TdsdOpenForm;
bbReport_RecalcMCS: TdxBarButton;
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
{$R *.dfm}
initialization
RegisterClass(TRecalcMCSShedulerForm);
end.
|
unit uprojectoptions;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
const
ETContinuousName='Continuous';
ETDottedName='Dotted';
ETUCDottedName='DOTTED';
type
{$Z1}
TPasPaths=packed record
_File:String;
_Paths:String;
end;
TParser=packed record
_CompilerOptions:String;
TargetOS,TargetCPU:String;
end;
TCircularGraphOptions=packed record
CalcEdgesWeight:Boolean;
end;
TClustersOptions=packed record
PathClusters:Boolean;
CollapseClusters:string;
ExpandClusters:string;
LabelClustersEdges:Boolean;
end;
TFullGraphOptions=packed record
ClustersOptions:TClustersOptions;
IncludeNotFoundedUnits:Boolean;
IncludeInterfaceUses:Boolean;
IncludeImplementationUses:Boolean;
IncludeOnlyCircularLoops:Boolean;
IncludeToGraph:string;
ExcludeFromGraph:string;
OnlyDirectlyUses:Boolean;
DstUnit:string;
SrcUnit:string;
end;
TEdgeType=(ETContinuous,ETDotted);
TGraphBulding=packed record
CircularGraphOptions:TCircularGraphOptions;
FullGraphOptions:TFullGraphOptions;
InterfaceUsesEdgeType:TEdgeType;
ImplementationUsesEdgeType:TEdgeType;
end;
PTProjectOptions=^TProjectOptions;
TProjectOptions=packed record
Paths:TPasPaths;
ParserOptions:TParser;
GraphBulding:TGraphBulding;
end;
TLogDir=(LD_Clear,LD_Report,LD_FullGraph,LD_CircGraph,LD_Explorer);
TLogOpt=set of TLogDir;
TLogWriter=procedure(msg:string; const LogOpt:TLogOpt) of object;
function DefaultProjectOptions:TProjectOptions;
function GetCompilerDefs:String;
function EdgeType2String(ET:TEdgeType):String;
function String2EdgeType(ETn:String):TEdgeType;
implementation
function EdgeType2String(ET:TEdgeType):String;
begin
case ET of
ETContinuous:result:=ETContinuousName;
ETDotted:result:=ETDottedName;
end;
end;
function String2EdgeType(ETn:String):TEdgeType;
begin
if UpperCase(ETn)=ETUCDottedName then
result:=ETDotted
else
result:=ETContinuous;
end;
function GetCompilerDefs:String;
procedure adddef(def:string);
begin
if result='' then
result:=format('-d%s',[def])
else
result:=result+format(' -d%s',[def]);
end;
begin
result:='';
{$ifdef LINUX}adddef('LINUX');{$endif}
{$ifdef WINDOWS}adddef('WINDOWS');{$endif}
{$ifdef MSWINDOWS}adddef('MSWINDOWS');{$endif}
{$ifdef WIN32}adddef('WIN32');{$endif}
{$ifdef LCLWIN32}adddef('LCLWIN32');{$endif}
{$ifdef FPC}adddef('FPC');{$endif}
{$ifdef CPU64}adddef('CPU64');{$endif}
{$ifdef CPU32}adddef('CPU32');{$endif}
{$ifdef LCLWIN32}adddef('LCLWIN32');{$endif}
{$ifdef LCLQT}adddef('LCLQT');{$endif}
{$ifdef LCLQT5}adddef('LCLQT5');{$endif}
{$ifdef LCLGTK2}adddef('LCLGTK2');{$endif}
end;
function DefaultProjectOptions:TProjectOptions;
begin
result.Paths._File:=ExtractFileDir(ParamStr(0))+pathdelim+'passrcerrors.pas';
result.Paths._Paths:=ExtractFileDir(ParamStr(0));
result.ParserOptions._CompilerOptions:='-Sc '+GetCompilerDefs;
result.ParserOptions.TargetOS:={$I %FPCTARGETOS%};
result.ParserOptions.TargetCPU:={$I %FPCTARGETCPU%};
result.GraphBulding.FullGraphOptions.IncludeToGraph:='';
result.GraphBulding.FullGraphOptions.ExcludeFromGraph:='';
result.GraphBulding.FullGraphOptions.IncludeNotFoundedUnits:=false;
result.GraphBulding.FullGraphOptions.IncludeInterfaceUses:=true;
result.GraphBulding.InterfaceUsesEdgeType:=ETContinuous;
result.GraphBulding.FullGraphOptions.IncludeImplementationUses:=true;
result.GraphBulding.ImplementationUsesEdgeType:=ETDotted;
result.GraphBulding.FullGraphOptions.ClustersOptions.PathClusters:=true;
result.GraphBulding.FullGraphOptions.ClustersOptions.CollapseClusters:='';
result.GraphBulding.FullGraphOptions.ClustersOptions.ExpandClusters:='';
result.GraphBulding.FullGraphOptions.ClustersOptions.LabelClustersEdges:=false;
result.GraphBulding.FullGraphOptions.IncludeOnlyCircularLoops:=false;
result.GraphBulding.FullGraphOptions.OnlyDirectlyUses:=false;
result.GraphBulding.CircularGraphOptions.CalcEdgesWeight:=false;
end;
end.
|
unit mcsAVRcpu;
interface
uses
Windows, sysUtils, Classes, Graphics, Forms, Controls, Menus,
Dialogs, StdCtrls, Buttons, ExtCtrls, ComCtrls, ImgList, StdActns,
ActnList, ToolWin, Grids, DBGrids, DB, Math, MMSystem,
mcsRutinas,
ACG_MBS_TYPES, ACG_MBS_TYPES_DINAMIC,
mcsAVR;
const
CAPACIDAD_MEMORIA_DE_DATOS=$20;//$60; WFS 2020
nZ=1; nC=0; nN=2; nV=3; nH=5; nT=6;
type
Npuerto=(A,B,C,D,E,F,G,H,I,J,K,L);
registrosAVR=array[0..CAPACIDAD_MEMORIA_DE_DATOS-1] of Byte;
TmcsAVR=class
r:registrosAVR;
SREG:Byte;
PORT:array[A..L] of Byte;
DDR:array[A..L] of Byte;
PIN:array[A..L] of Byte;
public
function ejecutarInstruccion(var instruccion:vectorInstruccion;nTec:Byte):Boolean;
procedure mostrarRegistros(var memo:Tmemo);
procedure ejecutarPrograma(var programa:Tseq;var memo:tmemo);
end;
var
AVRcpu:TmcsAVR;
implementation
uses
ACG_MBS_KEYPAD;
procedure TmcsAVR.ejecutarPrograma(var programa:Tseq;var memo:tmemo);
var
i,tamano:Integer;
nTec:Byte;
begin
tamano:=Length(programa);
for i:=0 to tamano do
begin
ejecutarInstruccion(programa[i],nTec);
memo.Lines.Add(IntToStr(i)+' oc: '+inttostr(programa[i][0]));
end;
end;
procedure TmcsAVR.mostrarRegistros(var memo:Tmemo);
var
cadena:string;
begin
cadena:='R0='+ByteAStringHexadecimal(r[0])+' '+
'R1='+ByteAStringHexadecimal(r[1])+' '+
'R20='+ByteAStringHexadecimal(r[20])+' '+
'SREG='+ByteAStringBinario(SREG)+' '+
'PORTD='+inttostr(PORT[D])+' '+
'DDRD='+inttostr(DDR[D])+' '+
'PIND='+inttostr(PIN[D])+' '+
'PORTA='+inttostr(PORT[A])+' '+
'DDRA='+inttostr(DDR[A])+' '+
'PINA='+inttostr(PIN[A]);
memo.Lines.Add(cadena);
end;
function TmcsAVR.ejecutarInstruccion(var instruccion:vectorInstruccion;nTec:Byte):Boolean;
function determinarN(entrada:byte):byte;
begin
Result:=(entrada shr 7)and 1;
end;
function determinarZ(entrada:byte):byte;
begin
if entrada = 0 then Result:=1
else Result:=0;
end;
function determinarZword(entrada:word):byte;
begin
if entrada = 0 then Result:=1
else Result:=0;
end;
function determinarH(entrada1,entrada2,acarreo:word):byte;
begin
if (entrada1 and $0F)+(entrada2 and $0F)+acarreo > $0F then
Result:=1
else
Result:=0;
end;
function determinarV(entrada1,entrada2,acarreo:word):byte;
var
w:word;
begin
w:=entrada1+entrada2+acarreo;
Result:=( (w and $80) shr 7)xor( (w and $100) shr 8);
end;
function determinarC(entrada1,entrada2,acarreo:word):byte;
var
w:word;
begin
w:=entrada1+entrada2+acarreo;
if w > $FF then Result:=1 else Result:=0;
end;
var
OC,bK,tipo,fue,des:Byte;
vC,des7,fue7:Byte;
bitC,bitX:Byte;
operandoW,desWord,fueWord:Word;
begin
Result:=True;
OC:=instruccion[0];
bK:=instruccion[1];
tipo:=instruccion[2];
des:=instruccion[3];
fue:=instruccion[4];
case OC of
0: { 0 NOP 1 1 No operation None }
begin
end;
1,2,3,4,5,6: { 1 ADD Rd,Rr 1 1 Add two Registers Rd <-- Rd + Rr Z,C,N,V,H }
begin
escribirBit(determinarZ(r[des]+r[fue]),SREG,nZ);
escribirBit(determinarC(r[des],r[fue],0),SREG,nC);
escribirBit(determinarN(r[des]+r[fue]),SREG,nN);
escribirBit(determinarV(r[des],r[fue],0),SREG,nV);
escribirBit(determinarH(r[des],r[fue],0),SREG,nH);
r[des]:=r[des]+r[fue];
end;
7,8,9,10,11,12: { 7 ADC R0,R1 1 1 Add with Carry two Registers Rd <-- Rd + Rr + C Z,C,N,V,H }
begin
vC:=leerBit(SREG,nC);
escribirBit(determinarZ(r[des]+r[fue]+vC),SREG,nZ);
escribirBit(determinarC(r[des],r[fue],+vC),SREG,nC);
escribirBit(determinarN(r[des]+r[fue]+vC),SREG,nN);
escribirBit(determinarV(r[des],r[fue],+vC),SREG,nV);
escribirBit(determinarH(r[des],r[fue],+vC),SREG,nH);
r[des]:=r[des]+r[fue]+vC;
end;
13,14,15,16,17,18: { 13 SUB R0,R1 1 1 Subtract two Registers Rd <-- Rd - Rr Z,C,N,V,H }
begin
escribirBit(determinarZ(r[des]-r[fue]),SREG,nZ);
escribirBit(determinarC(r[des],-r[fue],0),SREG,nC);
escribirBit(determinarN(r[des]-r[fue]),SREG,nN);
escribirBit(determinarV(r[des],-r[fue],0),SREG,nV);
escribirBit(determinarH(r[des],-r[fue],0),SREG,nH);
r[des]:=r[des]-r[fue];
end;
19,20,21: { 19 SUBI R0,K 2 1 Subtract Constant from Register Rd <-- Rd - K Z,C,N,V,H }
begin
escribirBit(determinarZ(r[des]-bK),SREG,nZ);
escribirBit(determinarC(r[des],-bK,0),SREG,nC);
escribirBit(determinarN(r[des]-bK),SREG,nN);
escribirBit(determinarV(r[des],-bK,0),SREG,nV);
escribirBit(determinarH(r[des],-bK,0),SREG,nH);
r[des]:=r[des]-bK;
end;
22,23,24,25,26,27: { 22 SBC R0,R1 1 1 Subtract with Carry two Registers Rd <-- Rd - Rr - C Z,C,N,V,H }
begin
vC:=leerBit(SREG,nC);
escribirBit(determinarZ(r[des]-r[fue]-vC),SREG,nZ);
escribirBit(determinarC(r[des],-r[fue],-vC),SREG,nC);
escribirBit(determinarN(r[des]-r[fue]-vC),SREG,nN);
escribirBit(determinarV(r[des],-r[fue],-vC),SREG,nV);
escribirBit(determinarH(r[des],-r[fue],-vC),SREG,nH);
r[des]:=r[des]-r[fue]-vC;
end;
28,29,30: { 28 SBCI R0,K 2 1 Subtract with Carry Constant from Reg Rd <-- Rd - K - C Z,C,N,V,H }
begin
vC:=leerBit(SREG,nC);
escribirBit(determinarZ(r[des]-bK-vC),SREG,nZ);
escribirBit(determinarC(r[des],-bK,-vC),SREG,nC);
escribirBit(determinarN(r[des]-bK-vC),SREG,nN);
escribirBit(determinarV(r[des],-bK,-vC),SREG,nV);
escribirBit(determinarH(r[des],-bK,-vC),SREG,nH);
r[des]:=r[des]-bK-vC;
end;
31,32,33,34,35,36: { 31 AND R0,R1 1 1 Logical AND Registers Rd <-- Rd and Rr Z,N,V=0 }
begin
escribirBit(determinarZ(r[des] and r[fue]),SREG,nZ);
escribirBit(determinarN(r[des] and r[fue]),SREG,nN);
escribirBit(0,SREG,nV);
r[des]:=r[des] and r[fue];
end;
37,38,39: { 37 ANDI R0,K 2 1 Logical AND Register and Constant Rd <-- Rd and K Z,N,V=0 }
begin
escribirBit(determinarZ(r[des] and bK),SREG,nZ);
escribirBit(determinarN(r[des] and bK),SREG,nN);
escribirBit(0,SREG,nV);
r[des]:=r[des] and bK;
end;
40,41,42,43,44,45: { 40 OR R0,R1 1 1 Logical OR Registers Rd <-- Rd v Rr Z,N,V=0 }
begin
escribirBit(determinarZ(r[des] or r[fue]),SREG,nZ);
escribirBit(determinarN(r[des] or r[fue]),SREG,nN);
escribirBit(0,SREG,nV);
r[des]:=r[des] or r[fue];
end;
46,47,48: { 46 ORI R0,K 2 1 Logical OR Register and Constant Rd <-- Rd v K Z,N,V=0 }
begin
escribirBit(determinarZ(r[des] or bK),SREG,nZ);
escribirBit(determinarN(r[des] or bK),SREG,nN);
escribirBit(0,SREG,nV);
r[des]:=r[des] or bK;
end;
49,50,51,52,53,54: { 49 EOR R0,R1 1 1 Exclusive OR Registers Rd <-- Rd xor Rr Z,N,V=0 }
begin
escribirBit(determinarZ(r[des] xor r[fue]),SREG,nZ);
escribirBit(determinarN(r[des] xor r[fue]),SREG,nN);
escribirBit(0,SREG,nV);
r[des]:=r[des] xor r[fue];
end;
55,56,57: { 55 COM R0 1 1 One’s Complement Rd <-- 0xFF - Rd Z,C=1,N,V=0 }
begin
escribirBit(determinarZ(255-r[des]),SREG,nZ);
escribirBit(1,SREG,nC);
escribirBit(determinarN(255-r[des]),SREG,nN);
escribirBit(0,SREG,nV);
r[des]:=255-r[des];
end;
58,59,60: { 58 NEG R0 1 1 Two’s Complement Rd <-- 0x00 - Rd Z,C,N,V,H }
begin
escribirBit(determinarZ(-r[des]),SREG,nZ);
escribirBit(determinarC(0,-r[des],0),SREG,nC);
escribirBit(determinarN(-r[des]),SREG,nN);
escribirBit(determinarV(0,-r[des],0),SREG,nV);
escribirBit(determinarH(0,-r[des],0),SREG,nH);
r[des]:=0-r[des];
end;
64,65,66: { 64 CBR R0,K 2 1 Clear Bit(s) in Register Rd <-- Rd and (0xFF - K) Z,N,V=0 }
begin
escribirBit(determinarZ(r[des] and (255-bK)),SREG,nZ);
escribirBit(determinarN(r[des] and (255-bK)),SREG,nN);
escribirBit(0,SREG,nV);
r[des]:=r[des] and (255-bK);
end;
67,68,69: { 67 INC R0 1 1 Increment Rd <-- Rd + 1 Z,N,V }
begin
escribirBit(determinarZ(r[des]+1),SREG,nZ);
escribirBit(determinarN(r[des]+1),SREG,nN);
escribirBit(determinarV(r[des],1,0),SREG,nV);
r[des]:=r[des] + 1;
end;
70,71,72: { 70 DEC R0 1 1 Decrement Rd <-- Rd <-- 1 Z,N,V }
begin
operandoW:=65535;{-1 en 16 bits}
escribirBit(determinarZ(r[des]-1),SREG,nZ);
escribirBit(determinarN(r[des]-1),SREG,nN);
escribirBit(determinarV(r[des],operandoW,0),SREG,nV);
r[des]:=r[des] - 1;
end;
73,74,75: { 73 TST R0 1 1 Test for Zero or Minus Rd <-- Rd and Rd Z,N,V=0 }
begin
escribirBit(determinarZ(r[des] and r[des]),SREG,nZ);
escribirBit(determinarN(r[des] and r[des]),SREG,nN);
escribirBit(0,SREG,nV);
r[des]:=r[des] and r[des];
end;
76,77,78: { 76 CLR R0 1 1 Clear Register Rd <-- Rd xor Rd Z=1,N=0,V=0 }
begin
escribirBit(1,SREG,nZ);
escribirBit(0,SREG,nN);
escribirBit(0,SREG,nV);
r[des]:=r[des] xor r[des];
end;
79,80,81: { 79 SER R0 1 1 Set Register Rd <-- 0xFF None }
begin
r[des]:=255;
end;
82,83,84: { 82 MUL R0,R1 1 2 Multiply Unsigned R1:R0 <-- Rd x Rr Z,C }
begin
operandoW:=r[des] * r[fue];
r[1]:=operandoW shr 8;
r[0]:=operandoW and $00FF;
escribirBit(determinarZword(operandoW),SREG,nZ);
escribirBit(leerBit(r[1],7),SREG,nC);
end;
85,86,87: { 85 MULS R0,R1 1 2 Multiply Signed R1:R0 <-- Rd x Rr Z,C }
begin
//operandoW:=r[des] * r[fue];
des7:=leerBit(r[des],7);
fue7:=leerBit(r[fue],7);
if des7=1 then desWord:=1+not(r[des]) else desWord:=r[des];
if fue7=1 then fueWord:=1+not(r[fue]) else fueWord:=r[fue];
operandoW:=desWord*fueWord;
if ((des7=1)and(fue7=0)) or ((des7=0)and(fue7=1)) then
begin
operandoW:=1+not(operandoW)
end;
r[1]:=operandoW shr 8;
r[0]:=operandoW and $00FF;
escribirBit(determinarZword(operandoW),SREG,nZ);
escribirBit(leerBit(r[1],7),SREG,nC);
end;
92,93,94: { 92 LSL R0 1 1 0 0 Logical Shift Left Rd(n+1) <-- Rd(n), Rd(0) <-- 0 Z,C,N,V }
begin {Equivale a ADD Rd,Rd}
escribirBit(determinarZ(r[des]+r[des]),SREG,nZ);
escribirBit(determinarC(r[des],r[des],0),SREG,nC);
escribirBit(determinarN(r[des]+r[des]),SREG,nN);
escribirBit(determinarV(r[des],r[des],0),SREG,nV);
//escribirBit(determinarH(),SREG,nH);
r[des]:=r[des]+r[des];
end;
95,96,97: { 95 LSR R0 1 1 0 0 Logical Shift Right Rd(n) <-- Rd(n+1), Rd(7) <-- 0 Z,C,N,V }
begin
escribirBit(leerBit(r[des],0),SREG,nC);{Bit 0 pasa a C}
r[des]:=(r[des] shr 1) and $7F; {Bit 7 es igual a 0 (N=0)}
escribirBit(determinarZ(r[des]),SREG,nZ);
escribirBit(0,SREG,nN);
{V=N xor C, for N and C after the shift.}
escribirBit(leerBit(SREG,nN) xor leerBit(SREG,nC),SREG,nV);
end;
98,99,100: { 98 ROL R0 1 1 0 0 Rotate Left Through Carry Rd(0)<--C,Rd(n+1)<-- Rd(n),C<--Rd(7) Z,C,N,V }
begin
bitC:=leerBit(SREG,nC);
escribirBit(leerBit(r[des],7),SREG,nC);{Bit 7 pasa a C}
r[des]:=(r[des] shl 1);
escribirBit(bitC,r[des],0);{C pasa a Bit 0}
escribirBit(determinarZ(r[des]),SREG,nZ);
escribirBit(determinarN(r[des]),SREG,nN);
{V=N xor C, for N and C after the shift.}
escribirBit(leerBit(SREG,nN) xor leerBit(SREG,nC),SREG,nV);
end;
101,102,103: { 101 ROR R0 1 1 0 0 Rotate Right Through Carry Rd(7)<--C,Rd(n)<-- Rd(n+1),C<--Rd(0) Z,C,N,V }
begin
bitC:=leerBit(SREG,nC);
escribirBit(leerBit(r[des],0),SREG,nC);{Bit 0 pasa a C}
r[des]:=(r[des] shr 1);
escribirBit(bitC,r[des],7);{C pasa a Bit 7}
escribirBit(determinarZ(r[des]),SREG,nZ);
escribirBit(determinarN(r[des]),SREG,nN);
{V=N xor C, for N and C after the shift.}
escribirBit(leerBit(SREG,nN) xor leerBit(SREG,nC),SREG,nV);
end;
104,105,106: { 104 ASR R0 1 1 0 0 Arithmetic Shift Right Rd(n) <-- Rd(n+1), n=0..6 Z,C,N,V }
begin
bitX:=leerBit(r[des],7);
escribirBit(leerBit(r[des],0),SREG,nC);{Bit 0 pasa a C}
r[des]:=(r[des] shr 1);
escribirBit(bitX,r[des],7);{Bit 7 se conserva}
escribirBit(determinarZ(r[des]),SREG,nZ);
escribirBit(determinarN(r[des]),SREG,nN);
{V=N xor C, for N and C after the shift.}
escribirBit(leerBit(SREG,nN) xor leerBit(SREG,nC),SREG,nV);
end;
107,108,109: { 107 SWAP R0 1 1 0 0 Swap Nibbles Rd(3:0)<--Rd(7:4),Rd(7:4)<--Rd(3:0) None }
begin
r[des]:= (r[des] shr 4) or (r[des] shl 4);
end;
110,111,112: { 110 BST R0,b 3 1 0 0 Bit Store from Register to T T <-- Rr(b) T }
begin
escribirBit(leerBit(r[fue],bK),SREG,nT);
end;
113,114,115: { 113 BLD R0,b 3 1 0 0 Bit load from T to Register Rd(b) <-- T None }
begin
escribirBit(leerBit(SREG,nT),r[des],bK);
end;
116: { 116 SEC 1 1 0 0 Set Carry C <-- 1 C }
begin
escribirBit(1,SREG,nC);
end;
117: { 117 CLC 1 1 0 0 Clear Carry C <-- 0 C }
begin
escribirBit(0,SREG,nC);
end;
118: { 118 SEN 1 1 0 0 0 0 1 0 0 Set Negative Flag N <-- 1 N }
begin
escribirBit(1,SREG,nN);
end;
119: { 119 CLN 1 1 0 0 0 0 1 0 0 Clear Negative Flag N <-- 0 N }
begin
escribirBit(0,SREG,nN);
end;
120: { 120 SET 1 1 0 0 0 0 0 0 0 Set T in SREG T <-- 1 T }
begin
escribirBit(1,SREG,nT);
end;
121: { 121 CLT 1 1 0 0 0 0 0 0 0 Clear T in SREG T <-- 0 T }
begin
escribirBit(0,SREG,nT);
end;
122: { 122 SEH 1 1 0 0 0 0 0 0 1 Set Half Carry Flag in SREG H <-- 1 H }
begin
escribirBit(1,SREG,nH);
end;
123: { 123 CLH 1 1 0 0 0 0 0 0 1 Clear Half Carry Flag in SREG H <-- 0 H }
begin
escribirBit(0,SREG,nH);
end;
124,125,126,127,128,129: { 124 MOV R0,R1 1 1 0 1 Move Between Registers Rd <-- Rr None }
begin
r[des]:=r[fue];
end;
130,131,132: { 130 LDI R0,K 2 1 0 0 Load Immediate Rd <-- K None }
begin
r[des]:=bK;
end;
61,62,63: { 61 IN R0,PIND 1 1 0 0 In Port Rd <-- P None }
begin
if valoresDePinesEnConexionConTecladoValidos(AVRcpu,nTec) then
begin
r[des]:=PIN[D];
end
else
begin
Result:=False;
end;
end;
133,134,135: { 133 OUT PORTD,R0 1 1 0 0 Out Port P <-- Rr None }
begin
PORT[D]:=r[fue];
end;
136,137,138: { 136 OUT DDRD,R0 1 1 0 0 Out Port P <-- Rr None }
begin
DDR[D]:=r[fue];
end;
88: { 88 SBI PORTD,b 3 2 Set Bit in I/O Register I/O(P,b) <-- 1 None }
begin
escribirBit(1,PORT[D],bK);
end;
89: { 89 SBI DDRD,b 3 2 Set Bit in I/O Register I/O(P,b) <-- 1 None }
begin
escribirBit(1,DDR[D],bK);
end;
90: { 90 CBI PORTD,b 3 2 Clear Bit in I/O Register I/O(P,b) <-- 0 None }
begin
escribirBit(0,PORT[D],bK);
end;
91: { 91 CBI DDRD,b 3 2 Clear Bit in I/O Register I/O(P,b) <-- 0 None }
begin
escribirBit(0,DDR[D],bK);
end;
139,140,141: { 61 IN R0,PINA 1 1 0 0 In Port Rd <-- P None }
begin
if valoresDePinesEnConexionConTecladoValidos(AVRcpu,nTec) then
begin
r[des]:=PIN[A];
end
else
begin
Result:=False;
end;
end;
142,143,144: { 133 OUT PORTA,R0 1 1 0 0 Out Port P <-- Rr None }
begin
PORT[A]:=r[fue];
end;
145,146,147: { 136 OUT DDRA,R0 1 1 0 0 Out Port P <-- Rr None }
begin
DDR[A]:=r[fue];
end;
148: { 88 SBI PORTA,b 3 2 Set Bit in I/O Register I/O(P,b) <-- 1 None }
begin
escribirBit(1,PORT[A],bK);
end;
149: { 89 SBI DDRA,b 3 2 Set Bit in I/O Register I/O(P,b) <-- 1 None }
begin
escribirBit(1,DDR[A],bK);
end;
150: { 90 CBI PORTA,b 3 2 Clear Bit in I/O Register I/O(P,b) <-- 0 None }
begin
escribirBit(0,PORT[A],bK);
end;
151: { 91 CBI DDRA,b 3 2 Clear Bit in I/O Register I/O(P,b) <-- 0 None }
begin
escribirBit(0,DDR[A],bK);
end;
156: { 156 MOV Rd,Rr 1 1 0 1 Move Between Registers Rd <-- Rr None }
begin
r[des]:=r[fue];
end;
157: { 157 BST Rd,b 3 1 0 0 Bit Store from Register to T T <-- Rr(b) T }
begin
escribirBit(leerBit(r[fue],bK),SREG,nT);
end;
159,160,161: { 61 IN R0,PINC 1 1 0 0 In Port Rd <-- P None }
begin {El LCD se conecata al puerto L}
r[des]:=PIN[C];
end;
162,163,164: { 133 OUT PORTC,R0 1 1 0 0 Out Port P <-- Rr None }
begin
PORT[C]:=r[fue];
end;
165,166,167: { 136 OUT DDRC,R0 1 1 0 0 Out Port P <-- Rr None }
begin
DDR[C]:=r[fue];
end;
168: { 88 SBI PORTC,b 3 2 Set Bit in I/O Register I/O(P,b) <-- 1 None }
begin
escribirBit(1,PORT[C],bK);
end;
169: { 89 SBI DDRC,b 3 2 Set Bit in I/O Register I/O(P,b) <-- 1 None }
begin
escribirBit(1,DDR[C],bK);
end;
170: { 90 CBI PORTC,b 3 2 Clear Bit in I/O Register I/O(P,b) <-- 0 None }
begin
escribirBit(0,PORT[C],bK);
end;
171: { 91 CBI DDRC,b 3 2 Clear Bit in I/O Register I/O(P,b) <-- 0 None }
begin
escribirBit(0,DDR[C],bK);
end;
end;
end;
end.
|
// see ISC_license.txt
{$I genLL.inc}
unit SimpleLexer;
interface
uses
Sysutils, Runtime;
const
LEX_ID = 1;
LEX_INT = 2;
LEX_WS = 3;
LEX_LCURLY = 4;
LEX_RCURLY = 5;
LEX_COMMENT = 6;
LEX_JAVADOC = 7;
LEX_LPAREN = 8;
LEX_RPAREN = 9;
LEX_SEMI = 10;
LEX_ASSIGN = 11;
LEX_KEY_INT = 12;
LEX_KEY_METHOD = 13;
LEX_KEY_RETURN = 14;
type
TSimpleLexer = class(TLexer)
protected
procedure Tokens(); override;
procedure KeyWords();
function GetTokenName(tokenType: integer): string; override;
function fENDL(): boolean;
function fLETTER(): boolean;
function fDIGIT(): boolean;
procedure mWS();
procedure mCOMMENT();
procedure mJAVADOC();
procedure mID();
procedure mINT();
procedure mKEY_INT();
procedure mKEY_METHOD();
procedure mKEY_RETURN();
end;
implementation
uses
Tokens;
procedure TSimpleLexer.Tokens;
var
LA1: integer;
lextype: integer;
begin
LA1 := LA(1);
if LA1 = LEX_EOF then
begin
ApproveTokenBuf(LEX_EOF, ceDefault);
exit;
end;
case LA1 of
9 .. 10, 13, ord(' '): mWS();
ord('A') .. ord('Z'), ord('a') .. ord('z'): KeyWords();
ord('0') .. ord('9'): mINT();
ord('/'): if LA(2) = ord('*') then
begin
if LA(3) = ord('*') then
mJAVADOC()
else
mCOMMENT()
end
else
raise ENoViableAltException.Create('');
ord('{'), ord('}'), ord('('), ord(')'), ord(';'), ord('='):
begin
case LA1 of
ord('{'): lextype := LEX_LCURLY;
ord('}'): lextype := LEX_RCURLY;
ord('('): lextype := LEX_LPAREN;
ord(')'): lextype := LEX_RPAREN;
ord(';'): lextype := LEX_SEMI;
ord('='): lextype := LEX_ASSIGN;
end;
Consume;
ApproveTokenBuf(lextype, ceDefault);
end;
end;
end;
function TSimpleLexer.GetTokenName(tokenType: integer): string;
begin
case tokenType of
LEX_ID: result := 'ID';
LEX_INT: result := 'int';
LEX_WS: result := 'whitespace';
LEX_LCURLY: result := '{';
LEX_RCURLY: result := '}';
LEX_COMMENT: result := 'comment';
LEX_JAVADOC: result := 'javadoc';
LEX_LPAREN: result := '(';
LEX_RPAREN: result := ')';
LEX_SEMI: result := ';';
LEX_ASSIGN: result := '=';
LEX_KEY_INT: result := 'key int';
LEX_KEY_METHOD: result := 'key method';
LEX_KEY_RETURN: result := 'key return';
end;
end;
procedure TSimpleLexer.KeyWords;
begin
case LA(1) of
ord('i'):
begin
if CompareLatin('int') then
mKEY_INT()
else
mID();
end;
ord('m'):
begin
if CompareLatin('method') then
mKEY_METHOD()
else
mID();
end;
ord('r'):
begin
if CompareLatin('return') then
mKEY_RETURN()
else
mID();
end;
else
mID();
end;
end;
function TSimpleLexer.fENDL(): boolean;
begin
result := (LA(1) = 13) and (LA(2) = 10) or (LA(1) = 10);
end;
function TSimpleLexer.fLETTER(): boolean;
var
ch: integer;
begin
ch := LA(1);
result := (ch >= ord('A')) and (ch <= ord('Z'))
or (ch >= ord('a')) and (ch <= ord('z'))
end;
function TSimpleLexer.fDIGIT(): boolean;
var
ch: integer;
begin
ch := LA(1);
result := (ch >= ord('0')) and (ch <= ord('9'));
end;
procedure TSimpleLexer.mWS();
var
LA1: integer;
begin
repeat
LA1 := LA(1);
if (LA1 = 9) or fENDL() or (LA1 = ord(' '))
then
Consume()
else
break;
until false;
ApproveTokenBuf(LEX_WS, ceHidden);
end;
procedure TSimpleLexer.mCOMMENT;
var
LA1: integer;
begin
MatchLatin('/*');
repeat
LA1 := LA(1);
if LA1 = -1 then
raise ETokenEOFException.Create('');
if LA1 <> ord('*') then
Consume()
else
begin
if LA(2) = ord('/') then
break
else
Consume(2);
end;
until false;
ApproveTokenBuf(LEX_COMMENT, ceHidden);
end;
procedure TSimpleLexer.mJAVADOC;
var
LA1: integer;
begin
MatchLatin('/**');
repeat
LA1 := LA(1);
if (LA1 <> -1) and (LA1 <> ord('*')) then
Consume()
else
begin
Consume();
if LA(1) = ord('/') then
begin
Consume();
break
end;
end;
until false;
ApproveTokenBuf(LEX_COMMENT, ceHidden);
end;
procedure TSimpleLexer.mID();
var
LA1: integer;
begin
if fLETTER() or (LA(1) = ord('_')) then
Consume;
repeat
LA1 := LA(1);
if fLETTER() or (LA(1) = ord('_')) or fDIGIT() then
Consume()
else
break;
until false;
ApproveTokenBuf(LEX_ID, ceDefault);
end;
procedure TSimpleLexer.mINT();
var
LA1: integer;
begin
if LA(1) = ord('0') then
Consume()
else
begin
Consume(); // 1..9
while fDIGIT() do
Consume();
end;
ApproveTokenBuf(LEX_INT, ceDefault);
end;
procedure TSimpleLexer.mKEY_INT;
begin
MatchLatin('int');
ApproveTokenBuf(LEX_KEY_INT, ceDefault);
end;
procedure TSimpleLexer.mKEY_METHOD;
begin
MatchLatin('method');
ApproveTokenBuf(LEX_KEY_METHOD, ceDefault);
end;
procedure TSimpleLexer.mKEY_RETURN;
begin
MatchLatin('return');
ApproveTokenBuf(LEX_KEY_RETURN, ceDefault);
end;
end.
|
unit uEvent;
interface
uses
System.Classes;
type
TBrowserEvent = class(TComponent, IDispatch)
private
{ Private declarations }
FOnEvent : TNotifyEvent;
FRefCount : integer;
function QueryInterface( const IID : TGUID; out Obj) : Integer; stdcall;
function _AddRef : Integer; stdcall;
function _Release : Integer; stdcall;
function Invoke( DispID : Integer; const IID : TGUID; LocaleID : Integer; Flags : Word; var Params; VarResult, ExcepInfo, ArgErr : Pointer) : HResult; stdcall;
public
{ Public declarations }
property OnEvent : TNotifyEvent read FOnEvent write FOnEvent;
end;
implementation
{ TBrowserEvent }
function TBrowserEvent.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
if GetInterface(IID, Obj) then
Result := S_OK
else
Result := E_NOINTERFACE;
end;
function TBrowserEvent._AddRef: integer;
begin
Inc(FRefCount);
Result := FRefCount;
end;
function TBrowserEvent._Release: integer;
begin
Dec(FRefCount);
Result := FRefCount;
end;
function TBrowserEvent.Invoke(DispID: integer; const IID: TGUID; LocaleID: integer; Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult;
begin
if Assigned(OnEvent) then
OnEvent(Self);
Result := S_OK;
end;
end.
|
unit SimThyrTypes;
{ SimThyr Project }
{ A numerical simulator of thyrotropic feedback control }
{ Version 3.3.2 }
{ (c) J. W. Dietrich, 1994 - 2014 }
{ (c) Ludwig Maximilian University of Munich 1995 - 2002 }
{ (c) Ruhr University of Bochum 2005 - 2014 }
{ This unit provides types and global variables for other SimThyr units }
{ Source code released under the BSD License }
{ See http://simthyr.sourceforge.net for details }
{$mode objfpc}
interface
uses
Classes, SysUtils, Forms, Graphics, TAGraph, UnitConverter;
const
kNUL = char(0); {Special ASCII characters}
kENTER = char(3);
kTAB = char(9);
kLF = char(10);
kRETURN = char(13);
kESCAPE = char(27);
kPERIOD = '.';
kSPACE = ' ';
kSLASH = '/';
kCOLON = ':';
kOMIT = '•';
kCRLF = #13#10;
RES_MAX_COLS = 10; {number of columns of table in log window}
RES_BLANK_ROWS = 26; {number of blank rows for empty window}
DEC_POINT = '.';
DEC_COMMA = ',';
i_pos = 0; {positions of simulated variables in}
t_pos = 1; {several arrays and in result matrix}
TRH_pos = 2;
pTSH_pos = 3;
TSH_pos = 4;
TT4_pos = 5;
FT4_pos = 6;
TT3_pos = 7;
FT3_pos = 8;
cT3_pos = 9;
T4_MOLAR_MASS = 776.87; {molar mass of T4}
T3_MOLAR_MASS = 650.97; {molar mass of T3}
UTRH = 2.76E-12; {Conversion factor ng/l -> mol/l (TRH; MW=362) [Jackson 1987]}
UTSH = 1e-3; {Dummy conversion factor for TSH}
TWS_RESOLUTION = 91; {Resolution for two-way sensitivity analysis}
type
TableCell = TPoint;
Str3 = string[3];
Str13 = string[13];
Str255 = string[255];
tResultMatrix = array of array of real; {matrix with simulated values}
tResultContent = array[0..RES_MAX_COLS-1] of Str255;
tmode = (integerMode, realMode);
var
nmax_old, tmax, tt, gridrows: integer;
nmax: longint;
T4UnitFactor, T3UnitFactor: array[0..MAXFACTORS - 1] of real;
gLabel: array[1..3] of Str255;
gMessage: array[1..3] of Str255;
gStartup: boolean;
delt: real;
testflag, tbgflag, signalflag, previewflag, noiseflag, circadianflag: boolean;
haltsim, runcommand, simready, splashflag, showSettingsAtStartup: boolean;
TRHs, TRH1, TSH1, TSH2, TSH3, FT41, FT42, FT43: real;
T3z1, T3z2, T3z3, T3n1, T3n2, T3n3, FT31, FT32, FT33: real;
T41, T42, T43, T31, T32, T33: real;
TSHz1, TSHz2, TSHz3, T3R1, T3R2, T3R3: real;
G3, t1, x1, x2, x3, x4, x5, x6, xe, ya, t: real;
a, b, c, d, e, xd, a1, b1, c1, d1, r1, s1, p1, q1, u, v, u1, u2, Det, y1, y2, y3: real;
dTRH, TRH, TRHi, TRHe, dTSH, TSH, TSHz, dT4, T4, FT4: real;
dT3z, T3z, T3n, T3R, dT3p, T3p, FT3, Albumin, TBG, TBPA, IBS: real;
alphaR, betaR, gH, alphaS, betaS, alphaS2, betaS2, kDH, dH, LS, SS, dS, GT, alphaT, betaT, dT: real;
GD1, GD2, GR, alpha31, beta31, alpha32, beta32, kM1, kM2, dR, D3, AC1, AC2, MI, MH: real;
Tt1, Tt2, Tt22, Tt3, Tt4, tpt11, tpt12, tpt13, tpt14, tpt15, tpt16, vpt10: real;
t121, t122, t123, t124, t125, t126: real;
k1, k2, k21, k22, k3, k30, k31, k41, k42, k5, k51, k7, dTSH1, dTSH2: real;
phi, chi, omega, f, dTSH3, gH0: real;
k6, k11, k8, k9, k61: real;
gResultMatrix: tResultMatrix;
gParameterLabel: array[0..RES_MAX_COLS - 1] of Str255;
gParameterUnit: array[0..RES_MAX_COLS -1] of String;
gParameterFactor: array[0..RES_MAX_COLS -1] of real;
gDefaultColors: array[0..RES_MAX_COLS -1] of TColor;
gSelectedChart: tChart;
tmax_text, tmax_unit, i1_text, i1_unit: str255;
gNumberFormat, gDateTimeFormat: String;
gLastActiveCustomForm: TForm;
implementation
end.
|
unit REST.Hermes.Params;
interface
uses
System.Generics.Collections, System.Rtti, System.Classes;
type
THermesParams = class(TPersistent)
private
FHeaders: TDictionary<string, TValue>;
FParams: TDictionary<string, TValue>;
FQuery: TDictionary<string, TValue>;
function GetHeaders(AKey: String): TValue;
function GetParams(AKey: String): TValue;
function GetQueries(AKey: String): TValue;
procedure SetHeaders(AKey: String; const Value: TValue);
procedure SetParams(AKey: String; const Value: TValue);
procedure SetQueries(AKey: String; const Value: TValue);
public
constructor Create;
function SetHeader(AKey: string; AValue: TValue): THermesParams;
function SetParam(AKey: string; AValue: TValue): THermesParams;
function SetQuery(AKey: string; AValue: TValue): THermesParams;
destructor Destroy; override;
property Params[AKey: String]: TValue read GetParams write SetParams;
property Queries[AKey: String]: TValue read GetQueries write SetQueries;
property Headers[AKey: String]: TValue read GetHeaders write SetHeaders;
end;
THermesParamsExposed = class(THermesParams)
function GetHeaders: TDictionary<string, TValue>;
function GetParams: TDictionary<string, TValue>;
function GetQueries: TDictionary<string, TValue>;
end;
implementation
uses
System.SysUtils, REST.Hermes.Core;
{ THermesParams }
constructor THermesParams.Create;
begin
FHeaders := TDictionary<string, TValue>.Create;
FParams := TDictionary<string, TValue>.Create;
FQuery := TDictionary<string, TValue>.Create;
end;
destructor THermesParams.Destroy;
begin
FHeaders.DisposeOf;
FParams.DisposeOf;
FQuery.DisposeOf;
inherited;
end;
function THermesParams.GetHeaders(AKey: String): TValue;
begin
Result := FHeaders.Items[AKey];
end;
function THermesParams.GetParams(AKey: String): TValue;
begin
Result := FParams.Items[AKey];
end;
function THermesParams.GetQueries(AKey: String): TValue;
begin
Result := FQuery.Items[AKey];
end;
function THermesParams.SetHeader(AKey: string; AValue: TValue): THermesParams;
begin
FHeaders.AddOrSetValue(AKey, AValue);
Result := Self;
end;
procedure THermesParams.SetHeaders(AKey: String; const Value: TValue);
begin
FHeaders.AddOrSetValue(AKey, Value);
end;
function THermesParams.SetParam(AKey: string; AValue: TValue): THermesParams;
begin
FParams.AddOrSetValue(AKey, AValue);
Result := Self;
end;
procedure THermesParams.SetParams(AKey: String; const Value: TValue);
begin
FParams.AddOrSetValue(AKey, Value);
end;
function THermesParams.SetQuery(AKey: string; AValue: TValue): THermesParams;
begin
FQuery.AddOrSetValue(AKey, AValue);
Result := Self;
end;
procedure THermesParams.SetQueries(AKey: String; const Value: TValue);
begin
FQuery.AddOrSetValue(AKey, Value);
end;
{ THermesParamsExposed }
function THermesParamsExposed.GetHeaders: TDictionary<string, TValue>;
begin
Result := FHeaders;
end;
function THermesParamsExposed.GetParams: TDictionary<string, TValue>;
begin
Result := FParams;
end;
function THermesParamsExposed.GetQueries: TDictionary<string, TValue>;
begin
Result := FQuery;
end;
end.
|
{***************************************************************************}
{ }
{ DUnitX }
{ }
{ Copyright (C) 2015 Vincent Parrett & Contributors }
{ }
{ vincent@finalbuilder.com }
{ http://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DUnitX.MemoryLeakMonitor.FastMM4;
interface
{$I DUnitX.inc}
uses
{$IFDEF USE_NS}
System.Classes,
{$ELSE}
Classes,
{$ENDIF}
DUnitX.TestFramework;
implementation
uses
DUnitX.MemoryLeakMonitor.Default,
DUnitX.IoC;
type
TDUnitXFastMM4MemoryLeakMonitor = class(TInterfacedObject,IMemoryLeakMonitor)
private
FPreSetupAllocation : Int64;
FPostSetupAllocation : Int64;
FPreTestAllocation : Int64;
FPostTestAllocation : Int64;
FPreTearDownAllocation : Int64;
FPostTearDownAllocation : Int64;
function GetMemoryAllocated() : Int64;
public
procedure PreSetup;
procedure PostSetUp;
procedure PreTest;
procedure PostTest;
procedure PreTearDown;
procedure PostTearDown;
function SetUpMemoryAllocated: Int64;
function TearDownMemoryAllocated: Int64;
function TestMemoryAllocated: Int64;
end;
{ TDUnitXFastMM4MemoryLeakMonitor }
function TDUnitXFastMM4MemoryLeakMonitor.GetMemoryAllocated: Int64;
var
st: TMemoryManagerState;
sb: TSmallBlockTypeState;
begin
GetMemoryManagerState(st);
Result := st.TotalAllocatedMediumBlockSize + st.TotalAllocatedLargeBlockSize;
for sb in st.SmallBlockTypeStates do
begin
Result := Result + Int64(sb.UseableBlockSize * sb.AllocatedBlockCount);
end;
end;
procedure TDUnitXFastMM4MemoryLeakMonitor.PostSetUp;
begin
FPostSetupAllocation := GetMemoryAllocated();
end;
procedure TDUnitXFastMM4MemoryLeakMonitor.PostTearDown;
begin
FPostTearDownAllocation := GetMemoryAllocated();
end;
procedure TDUnitXFastMM4MemoryLeakMonitor.PostTest;
begin
FPostTestAllocation := GetMemoryAllocated();
end;
procedure TDUnitXFastMM4MemoryLeakMonitor.PreSetup;
begin
FPreSetupAllocation := GetMemoryAllocated();
end;
procedure TDUnitXFastMM4MemoryLeakMonitor.PreTearDown;
begin
FPreTearDownAllocation := GetMemoryAllocated();
end;
procedure TDUnitXFastMM4MemoryLeakMonitor.PreTest;
begin
FPreTestAllocation := GetMemoryAllocated();
end;
function TDUnitXFastMM4MemoryLeakMonitor.SetUpMemoryAllocated: Int64;
begin
Result := FPostSetupAllocation - FPreSetupAllocation;
end;
function TDUnitXFastMM4MemoryLeakMonitor.TearDownMemoryAllocated: Int64;
begin
Result := FPostTearDownAllocation - FPreTearDownAllocation;
end;
function TDUnitXFastMM4MemoryLeakMonitor.TestMemoryAllocated: Int64;
begin
Result := FPostTestAllocation - FPreTestAllocation;
end;
initialization
{$IFDEF USE_FASTMM4_LEAK_MONITOR}
TDUnitXIoC.DefaultContainer.RegisterType<IMemoryLeakMonitor>(
function : IMemoryLeakMonitor
begin
result := TDUnitXFastMM4MemoryLeakMonitor.Create;
end);
{$ENDIF}
end.
|
unit UCRMLicSerial;
{ ClickForms Application }
{ Bradford Technologies, Inc. }
{ All Rights Reserved }
{ Source Code Copyrighted © 1998-2019 by Bradford Technologies, Inc. }
{ This unit will take a number (integer) and return a 20 character }
{ string composed of digits and alpha characters. This will become }
{ a customers serial number and will be used to identify them. }
{$WARN SYMBOL_PLATFORM OFF}
{$WARN UNIT_PLATFORM OFF}
interface
procedure GenerateSerialNumber(CustID: Integer; GroupFlag: Boolean; var SerialA, SerialB, SerialC, SerialD: String);
function ExtractCustomerID(SerialA, SerialB, SerialC, SerialD: String): Integer;
function IsPartOfUserGroup(SerialA: String): Boolean;
function ValidSerialNumbers(const SerialA, SerialB, SerialC, SerialD: String): Boolean;
function LeadingZeroDigitStr(Str: String; digits: Integer): String;
function GetUniqueID: Int64;
function EncodeDigit(N: Integer): Char;
function DecodeChar(C: Char): Integer;
implementation
uses
SysUtils,DateUtils,Math,Dialogs,
UStatus;
function AllowedDigits(ASCVal: Integer): char;
begin
case ASCVal of
58: result := 'J';
59: result := 'E';
60: result := 'F';
61: result := 'F';
62: result := 'E';
63: result := 'R';
64: result := 'Y';
73: result := 'M'; //73 = I
76: result := 'A'; //76 = L
79: result := 'R'; //79 = O
81: result := 'K'; //81 = Q
else
result := Char(ASCVal);
end;
end;
function Random5Digits: String;
var
Digits: ShortString;
begin
Digits[0] := char(5);
Digits[1] := AllowedDigits(RandomRange(50,90));
Digits[2] := AllowedDigits(RandomRange(50,90));
Digits[3] := AllowedDigits(RandomRange(50,90));
Digits[4] := AllowedDigits(RandomRange(50,90));
Digits[5] := AllowedDigits(RandomRange(50,90));
result := digits;
end;
function EncodeDigit(N: Integer): Char;
begin
result := '?';
case N of
0: result := 'A';
1: result := '2';
2: result := '5';
3: result := 'Z';
4: result := 'T';
5: result := '7';
6: result := 'C';
7: result := '4';
8: result := 'K';
9: result := 'B';
else
showNotice('Non-valid value passed to encoder.');
end;
end;
function DecodeChar(C: Char): Integer;
begin
case C of
'A': result := 0;
'2': result := 1;
'5': result := 2;
'Z': result := 3;
'T': result := 4;
'7': result := 5;
'C': result := 6;
'4': result := 7;
'K': result := 8;
'B': result := 9;
else
result := -1;
// ShowNotice('Non-valid char passed to decoder.');
end;
end;
{ To identify if a person belong to a group SerialA[3] is used }
{ to conveny this status. if Serial[3] = 'A' then the user is }
{ NOT a part of a group, if the value in SerialA[3] is anything}
{ else, the user is part of a group and we will lock the Co Name}
function GroupingIdentifier(groupFlag: Boolean): Char;
begin
if groupFlag then
begin
result := AllowedDigits(RandomRange(50,90));
if result = 'A' then result := 'B';
end
else
result := 'A';
end;
{ This grnerator can handle up to 999,999 customer serial numbers }
{ SerialA represents the customer ID number}
{ SerialB is a random sequence of chars }
procedure GenerateSerialNumber(CustID: Integer; GroupFlag: Boolean; var SerialA, SerialB, SerialC,SerialD: String);
var
X, D6,D5,D4,D3,D2,D1, K1,K2, XS,X1,X2: Integer;
begin
If not (CustID > 0) then
begin
ShowNotice('The customer ID was not a valid number.');
end;
SerialA := Random5Digits;
SerialB := Random5Digits;
SerialC := Random5Digits;
SerialD := Random5Digits;
//get the individual digits of the Customer ID
//can handle up to 999,999 customers
X := CustID;
D6 := X div 100000; //6th digit
X := X - (D6 * 100000);
D5 := X div 10000; //5th place
X := X - (D5 * 10000);
D4 := X div 1000; //4th place
X := X - (D4 * 1000);
D3 := X div 100; //3th place
X := X - (D3 * 100);
D2 := X div 10; //2th place
D1 := X - (D2 * 10); //1st place
SerialA[4] := EncodeDigit(D1); //digit 1 of CustID
SerialB[2] := EncodeDigit(D2); //digit 2 of CustID
SerialC[2] := EncodeDigit(D3); //digit 3 of CustID
SerialD[2] := EncodeDigit(D4); //digit 4 of CustID
SerialC[4] := EncodeDigit(D5); //digit 5 of CustID
SerialD[4] := EncodeDigit(D6); //digit 6 of CustID
//install verification keys
K1 := D1 + D2;
if K1 > 9 then K1 := K1 - 10;
K2 := D3 + D4;
if K2 > 9 then K2 := K2 - 10;
SerialD[3] := EncodeDigit(K1); //SA4 + SB2 -> SD3
SerialB[4] := EncodeDigit(K2); //SC2 + SD2 -> SB4
//install random key
XS := RandomRange(2,9);
SerialC[1] := EncodeDigit(XS);
X1 := XS div 2;
SerialA[1] := EncodeDigit(X1);
X2 := XS - X1;
SerialB[1] := EncodeDigit(X2);
//grouping identifier
SerialA[3] := GroupingIdentifier(groupFlag);
end;
function ExtractCustomerID(SerialA, SerialB, SerialC, SerialD: String): Integer;
var
X, D6,D5,D4,D3,D2,D1: Integer;
begin
D1 := DecodeChar(SerialA[4]); //digit 1 of CustID
D2 := DecodeChar(SerialB[2]); //digit 2 of CustID
D3 := DecodeChar(SerialC[2]); //digit 3 of CustID
D4 := DecodeChar(SerialD[2]); //digit 4 of CustID
D5 := DecodeChar(SerialC[4]); //digit 5 of CustID
D6 := DecodeChar(SerialD[4]); //digit 6 of CustID
X := D6 * 100000;
X := X + D5 * 10000;
X := X + D4 * 1000;
X := X + D3 * 100;
X := X + D2 * 10;
X := X + D1;
result := X;
end;
function IsPartOfUserGroup(SerialA: String): Boolean;
begin
result := false;
if length(SerialA) >= 3 then
result := SerialA[3] = 'A';
end;
function ValidSerialNumbers(const SerialA, SerialB, SerialC, SerialD: String): Boolean;
var
K1,K2, D1,D2,D3,D4, D5,D6, X1,X2, KR, R1,R2: Integer;
function Has5Ch(const S: String): Boolean;
begin
result := length(S)=5;
end;
begin
result := False;
if Has5Ch(SerialA) and Has5Ch(SerialB) and Has5Ch(SerialC) and Has5Ch(SerialD) then
begin
//verification of customer ID
K1 := DecodeChar(SerialD[3]); //verification key 1
K2 := DecodeChar(SerialB[4]); //verification key 2
D1 := DecodeChar(SerialA[4]); //digit 1 of CustID
D2 := DecodeChar(SerialB[2]); //digit 2 of CustID
D3 := DecodeChar(SerialC[2]); //digit 3 of CustID
D4 := DecodeChar(SerialD[2]); //digit 4 of CustID
D5 := DecodeChar(SerialC[4]); //digit 5 of CustID
D6 := DecodeChar(SerialD[4]); //digit 6 of CustID
X1 := D1 + D2;
if X1 > 9 then X1 := X1 - 10;
X2 := D3 + D4;
if X2 > 9 then X2 := X2 - 10;
//verification of random key
KR := DecodeChar(SerialC[1]);
R1 := DecodeChar(SerialA[1]);
R2 := DecodeChar(SerialB[1]);
result := (K1 >= 0) and (K2 >= 0) and
(D1 >= 0) and (D2 >= 0) and (D3 >= 0) and (D4 >= 0) and (D5 >= 0) and (D6 >= 0) and
(KR >= 0) and (R1 >= 0) and (R2 >= 0) and
(K1 = X1) and (K2 = X2) and (KR = (R1+R2));
end;
end;
function GetUniqueID: Int64;
begin
// result := MinutesBetween(Now,0);
result := SecondOfTheMonth(Date);
result := result shl 32;
result := result or RandomRange(0, High(Integer));
end;
function LeadingZeroDigitStr(Str: String; digits: Integer): String;
var
i,j: Integer;
begin
//this is a short string
SetString(result, PChar('00000000000'), digits);
j := digits;
for i := length(Str) downto 1 do
begin
result[j] := Str[i];
dec(j);
end;
end;
end.
|
unit FindUnit.Worker;
interface
uses
System.Classes, FindUnit.IncluderHandlerInc, FindUnit.PasParser, System.Generics.Collections,
Log4Pascal, SimpleParser.Lexer.Types, System.SysUtils, FindUnit.DcuDecompiler,
FindUnit.Utils, System.Threading, FindUnit.FileCache, System.DateUtils,
FindUnit.Header;
type
TOnFinished = procedure(FindUnits: TUnits) of object;
TParserWorker = class(TObject)
private
FDirectoriesPath: TStringList;
FPasFiles: TDictionary<string, TFileInfo>;
FFindUnits: TUnits;
FIncluder: IIncludeHandler;
FParsedItems: Integer;
FCacheFiles: TUnits;
FDcuFiles: TStringList;
FParseDcuFile: Boolean;
FCallBack: TOnFinished;
procedure ListPasFiles;
procedure ListDcuFiles;
procedure RemoveDcuFromExistingPasFiles;
procedure GeneratePasFromDcus;
procedure ParseFilesParallel;
procedure ParseFiles;
function GetItemsToParse: Integer;
procedure RunTasks;
procedure FreeGeneratedPas;
function MustContinue: Boolean;
public
constructor Create(var DirectoriesPath: TStringList; var Files: TDictionary<string, TFileInfo>; Chache: TUnits);
destructor Destroy; override;
procedure Start(CallBack: TOnFinished); overload;
function Start: TUnits; overload;
property ItemsToParse: Integer read GetItemsToParse;
property ParsedItems: Integer read FParsedItems;
property ParseDcuFile: Boolean read FParseDcuFile write FParseDcuFile;
procedure RemoveCallBack;
end;
implementation
uses
Winapi.Windows;
{ TParserWorker }
constructor TParserWorker.Create(var DirectoriesPath: TStringList; var Files: TDictionary<string, TFileInfo>;
Chache: TUnits);
var
InfoFiles: TFileInfo;
begin
FCacheFiles := Chache;
FDirectoriesPath := TStringList.Create;
if DirectoriesPath <> nil then
FDirectoriesPath.Text := TPathConverter.ConvertPathsToFullPath(DirectoriesPath.Text);
FreeAndNil(DirectoriesPath);
FPasFiles := TDictionary<string, TFileInfo>.Create;
if Files <> nil then
for InfoFiles in Files.Values do
FPasFiles.Add(InfoFiles.Path, InfoFiles);
Files.Free;
FDcuFiles := TStringList.Create;
FDcuFiles.Sorted := True;
FDcuFiles.Duplicates := dupIgnore;
FFindUnits := TUnits.Create;
FIncluder := TIncludeHandlerInc.Create(FDirectoriesPath.Text) as IIncludeHandler;
end;
destructor TParserWorker.Destroy;
var
Step: string;
Files: TObject;
begin
try
Step := 'FPasFiles';
FPasFiles.Free;
Step := 'FDirectoriesPath';
FDirectoriesPath.Free;
Step := 'FOldItems';
if Assigned(FCacheFiles) then
for Files in FCacheFiles.Values do
Files.Free;
FCacheFiles.Free;
Step := 'FDcuFiles';
// FIncluder.Free; //Weak reference
FDcuFiles.Free;
except
on E: exception do
begin
Logger.Error('TParserWorker.Destroy ' + Step);
end;
end;
inherited;
end;
procedure TParserWorker.FreeGeneratedPas;
var
Files: TPasFile;
begin
if Assigned(FFindUnits) then
for Files in FFindUnits.Values do
Files.Free;
end;
function TParserWorker.GetItemsToParse: Integer;
begin
Result := 0;
if (FPasFiles <> nil) then
Result := FPasFiles.Count;
end;
procedure TParserWorker.GeneratePasFromDcus;
var
DcuDecompiler: TDcuDecompiler;
begin
if not FParseDcuFile then
Exit;
DcuDecompiler := TDcuDecompiler.Create;
try
DcuDecompiler.ProcessFiles(FDcuFiles);
finally
DcuDecompiler.Free;
end;
end;
procedure TParserWorker.ListDcuFiles;
var
ResultList: TThreadList<string>;
DcuFile: string;
begin
if not FParseDcuFile then
Exit;
FDirectoriesPath.Add(DirRealeaseWin32);
ResultList := TThreadList<string>.Create;
TParallel.&For(0, FDirectoriesPath.Count -1,
procedure (index: Integer)
var
DcuFiles: TDictionary<string, TFileInfo>;
DcuFile: TFileInfo;
begin
try
DcuFiles := GetAllDcuFilesFromPath(FDirectoriesPath[index]);
try
for DcuFile in DcuFiles.Values do
ResultList.Add(Trim(DcuFile.Path));
finally
DcuFiles.Free;
end;
except
on E: exception do
begin
Logger.Error('TParserWorker.ListDcuFiles: ' + e.Message);
{$IFDEF RAISEMAD} raise; {$ENDIF}
end;
end;
end);
for DcuFile in ResultList.LockList do
FDcuFiles.Add(DcuFile);
ResultList.Free;
end;
procedure TParserWorker.ListPasFiles;
var
ResultList: TThreadList<TFileInfo>;
PasValue: TFileInfo;
begin
//DEBUG
// FPasFiles.Add('C:\Program Files (x86)\Embarcadero\RAD Studio\8.0\source\rtl\common\Classes.pas');
// Exit;
if FPasFiles.Count > 0 then
Exit;
ResultList := TThreadList<TFileInfo>.Create;
TParallel.&For(0, FDirectoriesPath.Count -1,
procedure (index: Integer)
var
PasFiles: TDictionary<string, TFileInfo>;
PasFile: TFileInfo;
begin
try
if not DirectoryExists(FDirectoriesPath[index]) then
Exit;
PasFiles := GetAllPasFilesFromPath(FDirectoriesPath[index]);
try
for PasFile in PasFiles.Values do
ResultList.Add(PasFile);
finally
PasFiles.Free;
end;
except
on E: exception do
begin
Logger.Error('TParserWorker.ListPasFiles: ' + e.Message);
{$IFDEF RAISEMAD} raise; {$ENDIF}
end;
end;
end
);
for PasValue in ResultList.LockList do
FPasFiles.AddOrSetValue(PasValue.Path, PasValue);
ResultList.Free;
end;
function TParserWorker.MustContinue: Boolean;
begin
Result := Assigned(FCallBack);
end;
procedure TParserWorker.ParseFiles;
var
Parser: TPasFileParser;
Item: TPasFile;
Step: string;
OldParsedFile: TPasFile;
CurFileInfo: TFileInfo;
MilliBtw: Int64;
begin
for CurFileInfo in FPasFiles.Values do
begin
Parser := nil;
if not MustContinue then
Exit;
if FCacheFiles <> nil then
begin
if FCacheFiles.TryGetValue(CurFileInfo.Path, OldParsedFile) then
begin
MilliBtw := MilliSecondsBetween(CurFileInfo.LastAccess, OldParsedFile.LastModification);
if MilliBtw <= 1 then
begin
Item := FCacheFiles.ExtractPair(CurFileInfo.Path).Value;
FFindUnits.Add(Item.FilePath, Item);
Logger.Debug('TParserWorker.ParseFiles[%s]: Cached files', [CurFileInfo.Path]);
Continue;
end
else
Logger.Debug('TParserWorker.ParseFiles[%s]: %d millis btw', [CurFileInfo.Path, MilliBtw]);
end
else
Logger.Debug('TParserWorker.ParseFiles[%s]: no fount path', [CurFileInfo.Path]);
end;
Parser := TPasFileParser.Create(CurFileInfo.Path);
try
try
Step := 'Parser.SetIncluder(FIncluder)';
Parser.SetIncluder(FIncluder);
Step := 'InterlockedIncrement(FParsedItems);';
InterlockedIncrement(FParsedItems);
Step := 'Parser.Process';
Item := Parser.Process;
if Item <> nil then
begin
Item.LastModification := CurFileInfo.LastAccess;
Item.FilePath := CurFileInfo.Path;
FFindUnits.Add(Item.FilePath, Item);
end;
except
on e: exception do
begin
Logger.Error('TParserWorker.ParseFiles[%s]: %s', [Step, e.Message]);
{$IFDEF RAISEMAD} raise; {$ENDIF}
end;
end;
finally
if Parser <> nil then //Thread issues
Parser.Free;
end;
end;
end;
procedure TParserWorker.ParseFilesParallel;
var
ResultList: TThreadList<TPasFile>;
PasValue: TPasFile;
ItemsToParser: TList<TFileInfo>;
CurFileInfo: TFileInfo;
MilliBtw: Int64;
OldParsedFile: TPasFile;
Item: TPasFile;
begin
ResultList := TThreadList<TPasFile>.Create;
FParsedItems := 0;
Logger.Debug('TParserWorker.ParseFiles: Starting parseing files.');
if FCacheFiles = nil then
Logger.Debug('TParserWorker.ParseFiles: no cache files')
else
Logger.Debug('TParserWorker.ParseFiles: found cache files');
ItemsToParser := TList<TFileInfo>.Create;
try
if FCacheFiles <> nil then
begin
for CurFileInfo in FPasFiles.Values do
begin
if FCacheFiles.TryGetValue(CurFileInfo.Path, OldParsedFile) then
begin
MilliBtw := MilliSecondsBetween(CurFileInfo.LastAccess, OldParsedFile.LastModification);
if MilliBtw <= 1 then
begin
Item := FCacheFiles.ExtractPair(CurFileInfo.Path).Value;
FFindUnits.Add(Item.FilePath, Item);
Continue;
end
else
begin
Logger.Debug('TParserWorker.ParseFiles[Out of date]: %d millis btw | %s', [MilliBtw, CurFileInfo.Path]);
ItemsToParser.Add(CurFileInfo);
end;
end
else
begin
Logger.Debug('TParserWorker.ParseFiles[New file]: %s', [CurFileInfo.Path]);
ItemsToParser.Add(CurFileInfo);
end;
end;
end
else
begin
for CurFileInfo in FPasFiles.Values do
ItemsToParser.Add(CurFileInfo);
end;
TParallel.&For(0, ItemsToParser.Count -1,
procedure (index: Integer)
var
Parser: TPasFileParser;
Item: TPasFile;
Step: string;
begin
try
if (not vSystemRunning) or (not MustContinue) then
Exit;
Step := 'InterlockedIncrement(FParsedItems);';
InterlockedIncrement(FParsedItems);
Step := 'Create';
Parser := TPasFileParser.Create(ItemsToParser[index].Path);
try
Step := 'Parser.SetIncluder(FIncluder)';
Parser.SetIncluder(FIncluder);
Step := 'Parser.Process';
Item := Parser.Process;
finally
Parser.Free;
end;
if Item <> nil then
begin
Item.LastModification := ItemsToParser[index].LastAccess;
Item.FilePath := ItemsToParser[index].Path;
ResultList.Add(Item);
end;
except
on e: exception do
begin
Logger.Error('TParserWorker.ParseFiles[%s]: %s', [Step, e.Message]);
{$IFDEF RAISEMAD} raise; {$ENDIF}
end;
end;
end
);
Logger.Debug('TParserWorker.ParseFiles: Put results together.');
for PasValue in ResultList.LockList do
begin
FFindUnits.Add(PasValue.FilePath, PasValue);
end;
Logger.Debug('TParserWorker.ParseFiles: Finished.');
ResultList.Free;
finally
ItemsToParser.Free;
end;
end;
procedure TParserWorker.RemoveCallBack;
begin
FCallBack := nil;
end;
procedure TParserWorker.RemoveDcuFromExistingPasFiles;
var
PasFilesName: TStringList;
I: Integer;
PasFile: string;
DcuFile: string;
PasFileIn: TFileInfo;
begin
if FDcuFiles.Count = 0 then
Exit;
PasFilesName := TStringList.Create;
PasFilesName.Sorted := True;
PasFilesName.Duplicates := dupIgnore;
try
for PasFileIn in FPasFiles.Values do
begin
PasFile := PasFileIn.Path;
PasFile := UpperCase(ExtractFileName(PasFile));
PasFile := StringReplace(PasFile, '.PAS', '', [rfReplaceAll]);
PasFilesName.Add(PasFile);
end;
for I := FDcuFiles.Count -1 downto 0 do
begin
DcuFile := FDcuFiles[i];
DcuFile:= UpperCase(ExtractFileName(DcuFile));
DcuFile := StringReplace(DcuFile, '.DCU', '', [rfReplaceAll]);
if PasFilesName.IndexOf(DcuFile) > -1 then
FDcuFiles.Delete(I);
end;
finally
PasFilesName.Free;
end;
end;
function TParserWorker.Start: TUnits;
begin
RunTasks;
Result := FFindUnits;
end;
procedure TParserWorker.RunTasks;
var
Step: string;
procedure OutPutStep(CurStep: string);
begin
Step := CurStep;
Logger.Debug('TParserWorker.RunTasks: ' + CurStep);
end;
begin
try
OutPutStep('FIncluder.Process');
TIncludeHandlerInc(FIncluder).Process;
OutPutStep('ListPasFiles');
ListPasFiles;
OutPutStep('ListDcuFiles');
ListDcuFiles;
OutPutStep('RemoveDcuFromExistingPasFiles');
RemoveDcuFromExistingPasFiles;
OutPutStep('GeneratePasFromDcus');
GeneratePasFromDcus;
OutPutStep('ParseFiles');
ParseFilesParallel;
OutPutStep('Finished');
except
on E: exception do
begin
Logger.Error('TParserWorker.RunTasks[%s]: %s ',[Step, e.Message]);
{$IFDEF RAISEMAD} raise; {$ENDIF}
end;
end;
end;
procedure TParserWorker.Start(CallBack: TOnFinished);
begin
FCallBack := CallBack;
RunTasks;
//Must check because of threads
if Assigned(FCallBack) then
FCallBack(FFindUnits)
else
FreeGeneratedPas;
end;
end.
|
{
Sobre o autor:
Guinther Pauli
Delphi Certified Professional - 3,5,6,7,2005,2006,Delphi Web,Kylix,XE
Microsoft Certified Professional - MCP,MCAD,MCSD.NET,MCTS,MCPD (C#, ASP.NET, Arquitetura)
Colaborador Editorial Revistas .net Magazine e ClubeDelphi
MVP (Most Valuable Professional) - Embarcadero Technologies - US
http://gpauli.com
http://www.facebook.com/guintherpauli
http://www.twitter.com/guintherpauli
http://br.linkedin.com/in/guintherpauli
}
unit uFramework;
interface
type
// Command
Command = class abstract
public procedure Execute(); virtual; abstract;
end;
// Invoker
Formulario = class
private _command: Command;
public procedure setCommand(command: Command);
public procedure ClickValidate();
end;
// Receiver
Server = class
public procedure ValidateUser();
end;
// ConcreteCommand
ServerCommand = class(Command)
private _server: Server;
public constructor Create(server: Server);
public procedure Execute(); override;
end;
implementation
{ Formulario }
procedure Formulario.ClickValidate();
begin
Writeln('Formulário - Iniciando validação do usuário');
_command.Execute();
end;
procedure Formulario.setCommand(command: Command);
begin
self._command := command;
end;
{ ServerCommand }
constructor ServerCommand.Create(server: Server);
begin
self._server := server;
end;
procedure ServerCommand.Execute();
begin
// delegando chamada a receiver
_server.ValidateUser();
end;
{ Server }
procedure Server.ValidateUser();
begin
Writeln('Servidor - Validando usuário');
end;
end.
|
unit RocketFairing;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, SizeInfo, BaseModel;
type
IBaseRocketFairing = interface(IBaseModel) ['{01AFDD2C-BF7A-4C3A-A8B4-02E70A29B369}']
function GetDiameter: ISizeInfo;
function GetHeight: ISizeInfo;
procedure SetDiameter(AValue: ISizeInfo);
procedure SetHeight(AValue: ISizeInfo);
end;
IRocketFairing = interface(IBaseRocketFairing) ['{A032C6D9-88D2-4550-8EF0-D2FB14FDA435}']
property Diameter: ISizeInfo read GetDiameter write SetDiameter;
property Height: ISizeInfo read GetHeight write SetHeight;
end;
function NewRocketFairing: IRocketFairing;
implementation
uses
JSON_Helper;
type
{ TRocketFairing }
TRocketFairing = class(TBaseModel, IRocketFairing)
private
FDiameter: ISizeInfo;
FHeight: ISizeInfo;
function GetDiameter: ISizeInfo;
function GetHeight: ISizeInfo;
procedure SetDiameter(AValue: ISizeInfo);
procedure SetHeight(AValue: ISizeInfo);
public
function ToString: string; override;
procedure BuildSubObjects(const JSONData: IJSONData); override;
end;
function NewRocketFairing: IRocketFairing;
begin
Result := TRocketFairing.Create;
end;
{ TRocketFairing }
function TRocketFairing.GetDiameter: ISizeInfo;
begin
Result := FDiameter;
end;
function TRocketFairing.GetHeight: ISizeInfo;
begin
Result := FHeight;
end;
procedure TRocketFairing.SetDiameter(AValue: ISizeInfo);
begin
FDiameter := AValue;
end;
procedure TRocketFairing.SetHeight(AValue: ISizeInfo);
begin
FHeight := AValue;
end;
function TRocketFairing.ToString: string;
begin
Result := Format(''
+ 'Diameter: %s' + LineEnding
+ 'Height: %s'
, [
GetDiameter.ToString,
GetHeight.ToString
]);
end;
procedure TRocketFairing.BuildSubObjects(const JSONData: IJSONData);
var
SubJSONData: IJSONData;
Diameter, Height: ISizeInfo;
begin
inherited BuildSubObjects(JSONData);
SubJSONData := JSONData.GetPath('diameter');
Diameter := NewSizeInfo;
JSONToModel(SubJSONData.GetJSONData, Diameter);
Self.FDiameter := Diameter;
SubJSONData := JSONData.GetPath('height');
Height := NewSizeInfo;
JSONToModel(SubJSONData.GetJSONData, Height);
Self.FHeight := Height;
end;
end.
|
{
Процедура вывода окна сообщения
}
procedure UI_ShowMessageBox(title, message : pChar);
var
form : newtComponent;
begin
newtOpenWindow(10, 5, 41, 7, title);
form := newtForm(nil, nil, 0);
newtFormAddComponents(
form,
newtLabel(1, 1, message),
newtButton(18, 3, 'ОК'),
nil
);
newtRunForm(form);
newtFormDestroy(form);
newtPopWindow;
end;
|
unit ubasepath;
interface
function _basepath: string;
const
_wintedversion = '0.2.3';
_atomname='wintedatom';
var
debug: boolean;
implementation
uses sysutils;
function _basepath: string;
begin
result := IncludeTrailingBackslash(ExtractFileDir(paramstr(0)));
end;
initialization
debug := (paramstr(1) = 'DEBUG');
end.
|
unit History;
interface
uses sysutils,classes,ComWriUtils,SafeCode;
type
TAfterProcMethod = procedure (Sender : TObject; Successful : boolean) of object;
THistory = class
private
protected
FPosition: integer;
function GetCount: integer; virtual; abstract;
procedure SetPosition(const Value: integer); virtual; abstract;
public
property count : integer read GetCount;
property Position : integer read FPosition write SetPosition;
// return if successful
function Back:boolean;
function Foreward:boolean;
procedure Clear; virtual; abstract;
procedure GetCurrentValue(var Value); virtual; abstract;
procedure Add(const Value); virtual; abstract;
function Bof:boolean ;
function Eof:boolean ;
end;
TStringHistory = class(THistory)
private
FStrings : TStringList;
FMaxCount: integer;
function GetCurValue: string;
protected
function GetCount: integer; override;
procedure SetPosition(const Value: integer); override;
public
constructor Create(AMaxCount : integer);
destructor destroy; override;
property MaxCount : integer read FMaxCount;
procedure Clear; override;
procedure GetCurrentValue(var Value); override;
procedure Add(const Value); override;
property Items : TStringList read FStrings;
property CurValue : string read GetCurValue;
end;
TFileOpenHistory = class(TStringHistory)
private
FAfterFileOpen: TAfterProcMethod;
public
FileOpen : IFileView;
function OpenFile(const Filename:string):boolean;
// if now is first , return false
// if file open error return false
function Back:boolean;
// if now is last , return false
// if file open error return false
function Foreward:boolean;
property AfterFileOpen : TAfterProcMethod read FAfterFileOpen write FAfterFileOpen;
end;
implementation
{ THistory }
function THistory.Back: boolean;
begin
result := not bof;
if result then position := position -1;
end;
function THistory.Bof: boolean;
begin
result := Position<=0;
end;
function THistory.Eof: boolean;
begin
result := (Position>=count-1) or (Position<0);
end;
function THistory.Foreward: boolean;
begin
result := not eof;
if result then position := position+1;
end;
{ TStringHistory }
constructor TStringHistory.Create(AMaxCount : integer);
begin
inherited Create;
FStrings := TStringList.Create;
FPosition := -1;
FMaxCount := AMaxCount;
end;
destructor TStringHistory.destroy;
begin
FStrings.free;
inherited destroy;
end;
procedure TStringHistory.Add(const Value);
var
AddStr : string;
begin
inc(FPosition);
if FPosition=count then
begin
AddStr := String(value);
FStrings.Add(String(value));
if count>FMaxCount then
begin
FStrings.Delete(0);
FPosition:=count-1;
end;
end
else
FStrings[FPosition]:=String(value);
end;
procedure TStringHistory.Clear;
begin
FStrings.Clear;
FPosition := -1;
end;
function TStringHistory.GetCount: integer;
begin
result := FStrings.count;
end;
procedure TStringHistory.GetCurrentValue(var Value);
begin
String(Value):=FStrings[FPosition];
end;
procedure TStringHistory.SetPosition(const Value: integer);
begin
if (value<0) or (value>=count) then
RaiseIndexOutOfRange
else
FPosition := value;
end;
function TStringHistory.GetCurValue: string;
begin
GetCurrentValue(result);
end;
{ TFileOpenHistory }
function TFileOpenHistory.Back: boolean;
begin
result := inherited Back;
if result and assigned(FileOpen) then
begin
result := FileOpen.LoadFromFile(CurValue);
if Assigned(FAfterFileOpen) then
FAfterFileOpen(self,result);
end;
end;
function TFileOpenHistory.Foreward: boolean;
begin
result := inherited Foreward;
if result and assigned(FileOpen) then
begin
result := FileOpen.LoadFromFile(CurValue);
if Assigned(FAfterFileOpen) then
FAfterFileOpen(self,result);
end;
end;
function TFileOpenHistory.OpenFile(const Filename:string):boolean;
var
RealFileName : string;
begin
RealFileName :=ExpandFileName(FileName);
//RealFileName :=FileName;
result := FileOpen.LoadFromFile(RealFilename);
if result then Add(RealFileName);
if Assigned(FAfterFileOpen) then
FAfterFileOpen(self,result);
end;
end.
|
unit RTConfiguration;
interface
uses
Graphics, Measure, RTDisplay;
type
TConfig = class
public
constructor Create( const RegistryKey : string );
destructor Destroy; override;
private
fRegistryKey : string;
fRange : cardinal;
fCellCount : cardinal;
fServerCellCount : cardinal;
fCellSize : word;
fSpeckleRemove : boolean;
fSpeckleThreshold : cardinal;
fShowRings : boolean;
fRingColor : TColor;
fRingsDistance : cardinal;
fShowMap : boolean;
fColorMap : TColor;
fShowRadar : boolean;
fShowOutlines : boolean;
fPPI : boolean;
fDataFormat : TDataType;
fDBZScalePath : string;
fDBScalePath : string;
fVScalePath : string;
fWScalePath : string;
fZoom : word;
fRTServer : string;
fMeasure : TMeasure;
public
property Range : cardinal read fRange write fRange;
property CellCount : cardinal read fCellCount write fCellCount;
property ServerCellCount : cardinal read fServerCellCount write fServerCellCount;
property CellSize : word read fCellSize write fCellSize;
property SpeckleRemove : boolean read fSpeckleRemove write fSpeckleRemove;
property PPI : boolean read fPPI write fPPI;
property Measure : TMeasure read fMeasure write fMeasure;
property SpeckleThreshold : cardinal read fSpeckleThreshold write fSpeckleThreshold;
property ShowRings : boolean read fShowRings write fShowRings;
property RingColor : TColor read fRingColor write fRingColor ;
property RingsDistance : cardinal read fRingsDistance write fRingsDistance;
property ShowMap : boolean read fShowMap write fShowMap;
property ColorMap : TColor read fColorMap write fColorMap;
property ShowRadar : boolean read fShowRadar write fShowRadar;
property ShowOutlines : boolean read fShowOutlines write fShowOutlines;
property DataFormat : TDataType read fDataFormat write fDataFormat;
property DBZScalePath : string read fDBZScalePath write fDBZScalePath;
property DBScalePath : string read fDBScalePath write fDBScalePath;
property VScalePath : string read fVScalePath write fVScalePath;
property WScalePath : string read fWScalePath write fWScalePath;
property Zoom : word read fZoom write fZoom;
property RTServer : string read fRTServer write fRTServer;
private
function LoadConfig : boolean;
public
procedure SaveConfig;
end;
implementation
uses
Registry;
const
//Values
RangeValue = 'Range';
CellCountValue = 'CellCount';
ServerCellCountValue = 'ServerCellCount';
CellSizeValue = 'CellSize';
SpeckleRemoveValue = 'SpeckleRemove';
SpeckleThresholdValue = 'SpeckleThreshold';
ShowRingsValue = 'ShowRings';
RingColorValue = 'RingColor';
RingsDistanceValue = 'RingsDistance';
ShowMapValue = 'ShowMap';
ColorMapValue = 'ColorMap';
ShowRadarValue = 'ShowRadar';
ShowOutlinesValue = 'ShowOutlines';
DBScalePathValue = 'DBScalePath';
VScalePathValue = 'VScalePath';
WScalePathValue = 'WScalePath';
DBZScalePathValue = 'DBZScalePath';
ZoomValue = 'Zoom';
RTServerValue = 'RTServer';
PPIValue = 'PPI';
DataTypeValue = 'DataType';
//Defaults
DefaultPPI = true;
DefaultDataType = 0;
DefaultRange = 450000; //meters
DefaultCellCount = 1000;
DefaultServerCellCount = 1000;
DefaultCellSize = 150; //meters
DefaultSpeckleRemove = true;
DefaultSpeckleThreshold = 500;
DefaultShowRings = false;
DefaultRingColor = clWhite;
DefaultRingsDistance = 100000; //meters
DefaultShowMap = true;
DefaultColorMap = clBlack;
DefaultShowRadar = true;
DefaultShowOutlines = false;
DefaultDBScalePath = '';
DefaultDBZScalePath = '';
DefaultVScalePath = '';
DefaultWScalePath = '';
DefaultZoom = 100;
DefaultRTServer = '127.0.0.1';
{ TConfig }
constructor TConfig.Create( const RegistryKey : string );
begin
inherited Create;
fRegistryKey := RegistryKey;
LoadConfig;
end;
destructor TConfig.Destroy;
begin
SaveConfig;
inherited;
end;
function TConfig.LoadConfig: boolean;
begin
with TRegistry.Create do
try
if OpenKey(fRegistryKey, false)
then
begin
if ValueExists( RangeValue )
then fRange := ReadInteger( RangeValue )
else fRange := DefaultRange;
if ValueExists( CellCountValue )
then fCellCount := ReadInteger( CellCountValue )
else fCellCount := DefaultCellCount;
if ValueExists( ServerCellCountValue )
then fServerCellCount := ReadInteger( ServerCellCountValue )
else fServerCellCount := DefaultServerCellCount;
if ValueExists( CellSizeValue )
then fCellSize := ReadInteger( CellSizeValue )
else fCellSize := DefaultCellSize;
if ValueExists( SpeckleRemoveValue )
then fSpeckleRemove := ReadBool( SpeckleRemoveValue )
else fSpeckleRemove := DefaultSpeckleRemove;
if ValueExists( SpeckleThresholdValue )
then fSpeckleThreshold := ReadInteger( SpeckleThresholdValue )
else fSpeckleThreshold := DefaultSpeckleThreshold;
if ValueExists( ShowRingsValue )
then fShowRings := ReadBool( ShowRingsValue )
else fShowRings := DefaultShowRings;
if ValueExists( ShowMapValue )
then fShowMap := ReadBool( ShowMapValue )
else fShowMap := DefaultShowMap;
if ValueExists( ShowRadarValue )
then fShowRadar := ReadBool( ShowRadarValue )
else fShowRadar := DefaultShowRadar;
if ValueExists( ShowOutlinesValue )
then fShowOutlines := ReadBool( ShowOutlinesValue )
else fShowOutlines := DefaultShowOutlines;
if ValueExists( RingsDistanceValue )
then fRingsDistance := ReadInteger( RingsDistanceValue )
else fRingsDistance := DefaultRingsDistance;
if ValueExists( RingColorValue )
then fRingColor := ReadInteger( RingColorValue )
else fRingColor := DefaultRingColor;
if ValueExists( ColorMapValue )
then fColorMap := ReadInteger( ColorMapValue )
else fColorMap := DefaultColorMap;
if ValueExists( ZoomValue )
then fZoom := ReadInteger( ZoomValue )
else fZoom := DefaultZoom;
if ValueExists( DBZScalePathValue )
then fDBZScalePath := ReadString( DBZScalePathValue )
else fDBZScalePath := DefaultDBZScalePath;
if ValueExists( DBScalePathValue )
then fDBScalePath := ReadString( DBScalePathValue )
else fDBScalePath := DefaultDBScalePath;
if ValueExists(VScalePathValue )
then fVScalePath := ReadString( VScalePathValue )
else fVScalePath := DefaultVScalePath;
if ValueExists(WScalePathValue )
then fWScalePath := ReadString( WScalePathValue )
else fWScalePath := DefaultWScalePath;
if ValueExists( RTServerValue )
then fRTServer := ReadString( RTServerValue )
else fRTServer := DefaultRTServer;
if ValueExists( PPIValue )
then fPPI := ReadBool( PPIValue )
else fPPI := DefaultPPI;
if ValueExists( DataTypeValue )
then fDataFormat := TDataType(ReadInteger(DataTypeValue))
else fDataFormat := dtDBZ;
end
else
begin
fPPI := DefaultPPI;
fMeasure := unDBZ;
fRange := DefaultRange;
fCellCount := DefaultCellCount;
fServerCellCount := DefaultServerCellCount;
fCellSize := DefaultCellSize;
fSpeckleRemove := DefaultSpeckleRemove;
fSpeckleThreshold := DefaultSpeckleThreshold;
fShowRings := DefaultShowRings;
fShowMap := DefaultShowMap;
fShowRadar := DefaultShowRadar;
fShowOutlines := DefaultShowOutlines;
fRingsDistance := DefaultRingsDistance;
fRingColor := DefaultRingColor;
fColorMap := DefaultColorMap;
fZoom := DefaultZoom;
fDBZScalePath := DefaultDBZScalePath;
fRTServer := DefaultRTServer;
end;
finally
free;
end;
end;
procedure TConfig.SaveConfig;
begin
with TRegistry.Create do
try
if OpenKey( fRegistryKey, true )
then
begin
WriteInteger( RangeValue, fRange );
WriteInteger( CellCountValue, fCellCount );
WriteInteger( ServerCellCountValue, fServerCellCount );
WriteInteger( CellSizeValue, fCellSize );
WriteInteger( SpeckleThresholdValue, fSpeckleThreshold );
WriteInteger( RingsDistanceValue, fRingsDistance );
WriteInteger( RingColorValue, fRingColor );
WriteInteger( ColorMapValue, fColorMap );
WriteInteger( ZoomValue, fZoom );
WriteString( DBZScalePathValue, fDBZScalePath );
WriteString( DBScalePathValue, fDBScalePath );
WriteString( VScalePathValue, fVScalePath );
WriteString( WScalePathValue, fWScalePath );
WriteString( RTServerValue, fRTServer );
WriteBool( SpeckleRemoveValue, fSpeckleRemove );
WriteBool( ShowRingsValue, fShowRings );
WriteBool( ShowMapValue, fShowMap );
WriteBool( ShowRadarValue, fShowRadar );
WriteBool( ShowOutlinesValue, fShowOutlines );
WriteBool( PPIValue, fPPI );
WriteInteger(DataTypeValue, Ord(fDataFormat) );
end;
finally
Free;
end;
end;
end.
|
unit Defaults;
interface
uses Classes, dsdDB;
type
TDefaultType = (dtGuides, dtText, dtDate);
// Возвращает ключ для дефолтных значений
TDefaultKey = class(TComponent)
private
FParams: TdsdParams;
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
function Key: string;
function JSONKey: string;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Params: TdsdParams read FParams write FParams;
end;
//
function GetDefaultJSON(DefaultType: TDefaultType; DefaultValue: Variant): string;
procedure Register;
implementation
uses SysUtils, utilConvert;
procedure Register;
begin
RegisterComponents('DSDComponent', [TDefaultKey]);
end;
function GetDefaultJSON(DefaultType: TDefaultType; DefaultValue: Variant): string;
begin
result := '{"DefaultType":"dtGuides", "Value":"' + DefaultValue + '"}';
end;
{ TDefaultKey }
constructor TDefaultKey.Create(AOwner: TComponent);
begin
inherited;
FParams := TdsdParams.Create(Self, TdsdParam);
end;
destructor TDefaultKey.Destroy;
begin
FreeAndNil(FParams);
inherited;
end;
function TDefaultKey.JSONKey: string;
var Param: TCollectionItem;
begin
result := '';
for Param in Params do
with TdsdParam(Param) do
if Value <> '' then begin
if result <> '' then result := result + ',';
result := result + '"' + Name + '":"' + Value +'"';
end;
result := '{' + result + '}';
result := gfStrToXmlStr (result);
end;
function TDefaultKey.Key: string;
var Param: TCollectionItem;
begin
result := '';
for Param in Params do
with TdsdParam(Param) do
if Value <> '' then begin
if result <> '' then result := result + ';';
result := result + Value
end;
end;
procedure TDefaultKey.Notification(AComponent: TComponent;
Operation: TOperation);
var i: integer;
begin
inherited;
if csDestroying in ComponentState then
exit;
if csDesigning in ComponentState then
if (Operation = opRemove) and Assigned(Params) then
for I := 0 to Params.Count - 1 do
if Params[i].Component = AComponent then
Params[i].Component := nil;
end;
initialization
RegisterClass(TDefaultKey)
end.
|
{$mode objfpc}
{$modeswitch objectivec2}
unit AppDelegate;
interface
uses
FGL, CocoaUtils, CocoaAll;
type
TDataNode = class;
TDataNodeList = specialize TFPGList<TDataNode>;
TDataNode = class
path: ansistring;
children: TDataNodeList;
parent: TDataNode;
ref: TCocoaObject;
constructor Create(_path: ansistring);
destructor Destroy; override;
function ChildCount: integer;
function ItemAt(index: integer): id;
procedure AddChild(child: TDataNode);
procedure InsertChild(child: TDataNode; index: integer);
procedure RemoveFromParent;
function FileName: string;
function IsFolder: boolean;
procedure Reload;
end;
type
TAppDelegate = objcclass(NSObject, NSApplicationDelegateProtocol, NSOutlineViewDataSourceProtocol, NSOutlineViewDelegateProtocol)
private
window: NSWindow;
dataOutlineView: NSOutlineView;
root: TDataNode;
public
procedure loadData; message 'loadData';
procedure applicationDidFinishLaunching(notification: NSNotification); message 'applicationDidFinishLaunching:';
{ NSOutlineViewDataSourceProtocol }
function outlineView_numberOfChildrenOfItem (outlineView: NSOutlineView; item: id): NSInteger; message 'outlineView:numberOfChildrenOfItem:';
function outlineView_child_ofItem (outlineView: NSOutlineView; index: NSInteger; item: id): id; message 'outlineView:child:ofItem:';
function outlineView_isItemExpandable (outlineView: NSOutlineView; item: id): boolean; message 'outlineView:isItemExpandable:';
function outlineView_objectValueForTableColumn_byItem (outlineView: NSOutlineView; tableColumn: NSTableColumn; item: id): id; message 'outlineView:objectValueForTableColumn:byItem:';
function outlineView_writeItems_toPasteboard(outlineView: NSOutlineView; writeItems: NSArray; pasteboard: NSPasteboard): Boolean; message 'outlineView:writeItems:toPasteboard:';
function outlineView_validateDrop_proposedItem_proposedChildIndex(outlineView: NSOutlineView; info: id; item: id; index: NSInteger): NSDragOperation; message 'outlineView:validateDrop:proposedItem:proposedChildIndex:';
function outlineView_acceptDrop_item_childIndex(outlineView: NSOutlineView; info: NSDraggingInfoProtocol; item: id; index: NSInteger): Boolean; message 'outlineView:acceptDrop:item:childIndex:';
{ NSOutlineViewDelegateProtocol }
procedure outlineViewItemWillExpand (notification: NSNotification); message 'outlineViewItemWillExpand:';
procedure outlineViewItemDidCollapse (notification: NSNotification); message 'outlineViewItemDidCollapse:';
end;
implementation
uses
BaseUnix, SysUtils, MacOSAll;
var
DataNodeTag: NSString;
constructor TDataNode.Create(_path: ansistring);
begin
path := _path;
ref := TCocoaObject.alloc.initWithObject(self);
end;
destructor TDataNode.Destroy;
begin
FreeAndNil(children);
ref.release;
end;
function TDataNode.ChildCount: integer;
begin
if assigned(children) then
result := children.Count
else
result := 0;
end;
function TDataNode.FileName: string;
begin
result := ExtractFileName(path);
end;
function TDataNode.IsFolder: boolean;
var
info : stat;
begin
if fpstat(path, info) = 0 then
result := fpS_ISDIR(info.st_mode)
else
result := false;
end;
function TDataNode.ItemAt(index: integer): id;
begin
result := children[index].ref;
end;
procedure TDataNode.RemoveFromParent;
begin
if assigned(parent) then
begin
parent.children.Remove(self);
parent := nil;
end;
end;
procedure TDataNode.AddChild(child: TDataNode);
begin
child.RemoveFromParent;
if children = nil then
Reload;
children.Add(child);
child.parent := self;
end;
procedure TDataNode.InsertChild(child: TDataNode; index: integer);
begin
child.RemoveFromParent;
if children = nil then
Reload;
children.Insert(index, child);
child.parent := self;
end;
procedure TDataNode.Reload;
var
handle: PDir;
entry: PDirent;
name: pchar;
begin
children := TDataNodeList.Create;
handle := fpOpenDir(path);
if assigned(handle) then
begin
while true do
begin
entry := fpReadDir(handle);
if assigned(entry) then
begin
name := pchar(@entry^.d_name[0]);
if name[0] = '.' then
continue;
AddChild(TDataNode.Create(path+'/'+name));
end
else
break;
end;
fpCloseDir(handle);
end;
end;
function TAppDelegate.outlineView_numberOfChildrenOfItem (outlineView: NSOutlineView; item: id): NSInteger;
begin
if item = nil then
begin
if root = nil then
loadData;
result := root.ChildCount;
end
else
result := TDataNode(item.obj).ChildCount;
end;
function TAppDelegate.outlineView_child_ofItem (outlineView: NSOutlineView; index: NSInteger; item: id): id;
begin
if item = nil then
result := root.ItemAt(index)
else
result := TDataNode(item.obj).ItemAt(index);
end;
function TAppDelegate.outlineView_isItemExpandable (outlineView: NSOutlineView; item: id): boolean;
begin
if item = nil then
result := false
else
result := TDataNode(item.obj).IsFolder;
end;
function TAppDelegate.outlineView_objectValueForTableColumn_byItem (outlineView: NSOutlineView; tableColumn: NSTableColumn; item: id): id;
begin
if tableColumn.title = 'Name' then
result := NSSTR(TDataNode(item.obj).FileName)
else if tableColumn.title = 'Children' then
begin
if TDataNode(item.obj).IsFolder then
result := NSSTR(IntToStr(TDataNode(item.obj).ChildCount))
else
result := nil;
end
else
result := nil;
end;
function TAppDelegate.outlineView_writeItems_toPasteboard(outlineView: NSOutlineView; writeItems: NSArray; pasteboard: NSPasteboard): Boolean;
var
data: NSData;
pasteboardItems: NSMutableArray;
pasteboardItem: NSPasteboardItem;
item: id;
begin
pasteboardItems := NSMutableArray.array_;
for item in writeItems do
begin
pasteboardItem := NSPasteboardItem.alloc.init;
pasteboardItem.setData_forType(NSKeyedArchiver.archivedDataWithRootObject(item), DataNodeTag);
pasteboardItems.addObject(pasteboardItem);
pasteboardItem.release;
end;
pasteboard.writeObjects(pasteboardItems);
result := true;
end;
function TAppDelegate.outlineView_validateDrop_proposedItem_proposedChildIndex(outlineView: NSOutlineView; info: id; item: id; index: NSInteger): NSDragOperation;
var
target: TDataNode;
begin
result := NSDragOperationNone;
if item <> nil then
target := TDataNode(item.obj)
else
target := root;
if target.IsFolder then
result := NSDragOperationGeneric;
end;
function TAppDelegate.outlineView_acceptDrop_item_childIndex(outlineView: NSOutlineView; info: NSDraggingInfoProtocol; item: id; index: NSInteger): Boolean;
var
pasteboard: NSPasteboard;
pasteboardItem: NSPasteboardItem;
data: NSData;
source,
target: TDataNode;
begin
pasteboard := info.draggingPasteboard;
result := false;
if item <> nil then
target := TDataNode(item.obj)
else
target := root;
for pasteboardItem in info.draggingPasteboard.pasteboardItems do
begin
data := pasteboardItem.dataForType(DataNodeTag);
if data <> nil then
begin
source := NSKeyedUnarchiver.unarchiveObjectWithData(data).obj as TDataNode;
if info.draggingSource = outlineView then
begin
if index = -1 then
begin
if target.IsFolder then
begin
target.AddChild(source);
result := true;
end
end
else
begin
target.InsertChild(source, index);
result := true;
end;
if result then
outlineView.reloadData;
end;
continue;
end;
end;
end;
procedure TAppDelegate.outlineViewItemWillExpand (notification: NSNotification);
var
node: TDataNode;
begin
node := notification.userInfo.objectForKey(NSSTR('NSObject')).obj as TDataNode;
if node.children = nil then
node.Reload;
end;
procedure TAppDelegate.outlineViewItemDidCollapse (notification: NSNotification);
var
node: TDataNode;
begin
node := notification.userInfo.objectForKey(NSSTR('NSObject')).obj as TDataNode;
end;
procedure TAppDelegate.loadData;
var
node: TDataNode;
begin
root := TDataNode.Create(NSSTR('~/Desktop').stringByExpandingTildeInPath.UTF8String);
root.Reload;
end;
procedure TAppDelegate.applicationDidFinishLaunching(notification : NSNotification);
begin
DataNodeTag := NSString.alloc.initWithUTF8String('data.TDataNode');
dataOutlineView.registerForDraggedTypes(NSArray.arrayWithObject(DataNodeTag));
end;
end. |
unit Unit2;
interface
uses
System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf,
FireDAC.DApt.Intf, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client,
FireDAC.Stan.StorageBin, FireDAC.UI.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool,
FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef,
FireDAC.Stan.ExprFuncs, FireDAC.Phys.SQLiteWrapper.Stat, FireDAC.FMXUI.Wait,
FireDAC.Phys.SQLiteVDataSet, FireDAC.VCLUI.Wait, FMX.Forms;
type
TDataModule2 = class(TDataModule)
FDMemTable1: TFDMemTable;
FDStanStorageBinLink1: TFDStanStorageBinLink;
procedure DataModuleCreate(Sender: TObject);
private
{ Déclarations privées }
public
{ Déclarations publiques }
end;
function _(id, DefaultText: string): string;
function ChangeLangue(Langue: string): boolean;
function GetLangue: string;
var
DataModule2: TDataModule2;
implementation
{%CLASSGROUP 'FMX.Controls.TControl'}
{$R *.dfm}
uses
System.IOUtils, Unit1;
var
LangueSelectionnee: string;
procedure TDataModule2.DataModuleCreate(Sender: TObject);
begin
FDMemTable1.LoadFromFile(tpath.Combine(tpath.GetDocumentsPath,
'MesTextesTraduits.bin'));
end;
function _(id, DefaultText: string): string;
begin
result := '';
if assigned(DataModule2) and DataModule2.FDMemTable1.Active then
if DataModule2.FDMemTable1.Locate('id', id) then
result := DataModule2.FDMemTable1.fieldbyname(LangueSelectionnee)
.AsString;
if result.IsEmpty then
result := DefaultText;
end;
function ChangeLangue(Langue: string): boolean;
var
i: integer;
begin
result := assigned(DataModule2) and DataModule2.FDMemTable1.Active and
assigned(DataModule2.FDMemTable1.Fields.fieldbyname(Langue));
if result then
begin
LangueSelectionnee := Langue;
for i := 0 to Screen.FormCount - 1 do
if (Screen.Forms[i] is TFormTraduite) then
(Screen.Forms[i] as TFormTraduite).TraduireTextes;
end;
end;
function GetLangue: string;
begin
result := LangueSelectionnee;
end;
initialization
LangueSelectionnee := 'fr';
end.
|
{*!
* Fano Web Framework (https://fanoframework.github.io)
*
* @link https://github.com/fanoframework/fano
* @copyright Copyright (c) 2018 Zamrony P. Juhara
* @license https://github.com/fanoframework/fano/blob/master/LICENSE (MIT)
*}
unit ServiceContainerIntf;
interface
{$MODE OBJFPC}
{$H+}
uses
DependencyIntf,
DependencyContainerIntf,
ServiceIntf,
ServiceFactoryIntf;
type
{------------------------------------------------
interface for any class having capability to manage
dependency
@author Zamrony P. Juhara <zamronypj@yahoo.com>
-----------------------------------------------}
IServiceContainer = interface
['{BC4A8D34-FE8E-4EA3-A7EB-51A92889DA66}']
(*!--------------------------------------------------------
* register factory instance to service registration as
* single instance
*---------------------------------------------------------
* @param service service to be register
* @param serviceFactory factory instance
* @return current dependency container instance
*---------------------------------------------------------*)
function register(const service : IInterface; const serviceFactory : IServiceFactory) : IServiceContainer;
(*!--------------------------------------------------------
* register factory instance to service registration as
* multiple instance
*---------------------------------------------------------
* @param service service to be registered
* @param serviceFactory factory instance
* @return current dependency container instance
*---------------------------------------------------------*)
function registerMultiple(const service : IInterface; const serviceFactory : IServiceFactory) : IServiceContainer;
(*!--------------------------------------------------------
* register alias to existing service
*---------------------------------------------------------
* @param aliasService alias of service
* @param serviceName actual service
* @return current dependency container instance
*---------------------------------------------------------*)
function registerAlias(const aliasService: IInterface; const service : IInterface) : IServiceContainer;
(*!--------------------------------------------------------
* resolve instance from service registration using its name.
*---------------------------------------------------------
* @param serviceName name of service
* @return dependency instance
* @throws EDependencyNotFoundImpl exception when name is not registered
*---------------------------------------------------------
* if serviceName is registered with add(), then this method
* will always return same instance. If serviceName is
* registered using factory(), this method will return
* different instance everytim get() is called.
*---------------------------------------------------------*)
function resolve(const service : IInterface) : IService;
(*!--------------------------------------------------------
* test if service is already registered or not.
*---------------------------------------------------------
* @param serviceName name of service
* @return boolean true if service is registered otherwise false
*---------------------------------------------------------*)
function isRegistered(const service : IInterface) : boolean;
end;
implementation
end.
|
uses dos,crt;
Type
ST3 = string[3];
ST80 = string[80];
ST5 = string[5];
Registers = record
case integer of
1: (AX,BX,CX,DX,BP,SI,DI,DS,ES,FLAGS: Integer);
2: (AL,AH,BL,BH,CL,CH,DL,DH : Byte);
end;
Const
EMM_INT = $67;
DOS_Int = $21;
GET_PAGE_FRAME = $41;
GET_UNALLOCATED_PAGE_COUNT = $42;
ALLOCATE_PAGES = $43;
MAP_PAGES = $44;
DEALLOCATE_PAGES = $45;
GET_VERSION = $46;
STATUS_OK = 0;
{------------------------------------------------------------}
{ Assume the application needs one EMM page. }
{------------------------------------------------------------}
APPLICATION_PAGE_COUNT = 1;
Var
Regs: Registers;
Emm_handle,
Page_Frame_Base_Address,
Pages_Needed,
Physical_Page,
Logical_Page,
Offset,
Error_Code,
Pages_EMM_Available,
Total_EMM_Pages,
Available_EMM_Pages: Integer;
Version_Number,
Pages_Number_String: ST3;
Verify: Boolean;
{------------------------------------------------------------}
{ The function Hex_String converts an integer into a four }
{ character hexadecimal number (string) with leading zeros. }
{------------------------------------------------------------}
Function Hex_String (Number: Integer): ST5;
Function Hex_Char (Number: Integer): Char;
Begin
If Number < 10 then
Hex_Char := Char (Number + 48)
else
Hex_Char := Char (Number + 55);
end; { Function Hex_char }
Var
S: ST5;
Begin
S := '';
S := Hex_Char ((Number shr 1) div 2048);
Number := (((Number shr 1) mod 2048) shl 1) + (Number and 1);
S := S + Hex_Char (Number div 256);
Number := Number mod 256;
S := S + Hex_Char (Number div 16);
Number := Number mod 16;
S := S + Hex_Char (Number);
Hex_String := S + 'h';
end; { Function Hex_String }
{------------------------------------------------------------}
{ The function Emm_Installed checks to see if the }
{ EMM is loaded in memory. It does this by looking }
{ for the string 'EMMXXXX0', which should be located }
{ at 10 bytes from the beginning of the code segment the }
{ EMM interrupt, 67h, points to. }
{------------------------------------------------------------}
Function Emm_Installed: Boolean;
Var
Emm_Device_Name : string[8];
Int_67_Device_Name: string[8];
Position : integer;
Regs : registers;
Begin
Int_67_Device_Name := '';
Emm_Device_Name := 'EMMXXXX0';
with Regs do
Begin
{----------------------------------------------------}
{ Get the code segment interrupt 67h points to }
{ the EMM interrupt by using DOS function 35h. }
{ (get interrupt vector) }
{----------------------------------------------------}
AH := $35;
AL := EMM_INT;
Intr (DOS_Int, Regs);
{----------------------------------------------------}
{ The ES pseudo-register contains the segment }
{ address pointed to by interrupt 67h. Create an }
{ eight character string from the eight successive }
{ bytes at address ES:$000A (10 bytes from ES) }
{----------------------------------------------------}
For Position := 0 to 7 do
Int_67_Device_Name :=
Int_67_Device_Name + Chr (mem[ES:Position + $0A]);
Emm_Installed := True;
{----------------------------------------------------}
{ If the string is the EMM manager signature, }
{ 'EMMXXXX0', then EMM is installed and ready for }
{ use. If not, then EMM is not present. }
{----------------------------------------------------}
If Int_67_Device_Name <> Emm_Device_Name
then Emm_Installed := False;
end; { with Regs do }
end; { Function Emm_Installed }
{------------------------------------------------------------}
{ This function returns the total number of EMM pages }
{ present in the system, and the number of EMM pages that }
{ are available. }
{------------------------------------------------------------}
Function EMM_Pages_Available
(Var Total_EMM_Pages, Pages_Available: Integer): Integer;
Var
Regs: Registers;
Begin
with Regs do
Begin
{----------------------------------------------------}
{ Get the number of currently unallocated pages and }
{ the total number of pages in the system from EMM. }
{ Load pseudo-registers prior to invoking EMM. }
{ AH = get unallocated page count function }
{----------------------------------------------------}
AH := GET_UNALLOCATED_PAGE_COUNT;
Intr (EMM_INT, Regs);
{----------------------------------------------------}
{ Unload the pseudo-registers after invoking EMM. }
{ BX = currently unallocated pages }
{ DX = total pages in the system }
{ AH = status }
{----------------------------------------------------}
Pages_Available := BX;
Total_EMM_Pages := DX;
EMM_Pages_Available := AH;
end;
end; { Function EMM_Pages_Available }
{------------------------------------------------------------}
{ This function requests the specified number of pages }
{ from the EMM. }
{------------------------------------------------------------}
Function Allocate_Expanded_Memory_Pages
(Pages_Needed: Integer; Var Handle: Integer): Integer;
Var
Regs: Registers;
Begin
with Regs do
Begin
{----------------------------------------------------}
{ Allocate the specified number of pages from EMM. }
{ Load pseudo-registers prior to invoking EMM. }
{ AH = allocate pages function. }
{ BX = number of pages to allocate. }
{----------------------------------------------------}
AH := ALLOCATE_PAGES;
BX := Pages_Needed;
Intr (EMM_INT, Regs);
{----------------------------------------------------}
{ Unload the pseudo-registers after invoking EMM. }
{ DX = EMM handle }
{ AH = status }
{----------------------------------------------------}
Handle := DX;
Allocate_Expanded_Memory_Pages := AH;
end;
end; { Function Allocate_Expanded_Memory_Pages }
{------------------------------------------------------------}
{ This function maps a logical page allocated by the }
{ Allocate_Expanded_Memory_Pages function into one of the }
{ four physical pages. }
{------------------------------------------------------------}
Function Map_Expanded_Memory_Pages
(Handle, Logical_Page, Physical_Page: Integer): Integer;
Var
Regs: Registers;
Begin
with Regs do
Begin
{----------------------------------------------------}
{ Map a logical page at a physical page. }
{ Load pseudo-registers prior to invoking EMM. }
{ AH = map page function }
{ DX = handle }
{ BX = logical page number }
{ AL = physical page number }
{----------------------------------------------------}
AH := MAP_PAGES;
DX := Handle;
BX := Logical_Page;
AL := Physical_Page;
Intr (EMM_INT, Regs);
{----------------------------------------------------}
{ Unload the pseudo-registers after invoking EMM. }
{ AH = status }
{----------------------------------------------------}
Map_Expanded_Memory_Pages := AH;
end; { with Regs do }
end; { Function Map_Expanded_Memory_Pages }
{------------------------------------------------------------}
{ This function gets the physical address of the EMM page }
{ frame we are using. The address returned is the segment }
{ of the page frame. }
{------------------------------------------------------------}
Function Get_Page_Frame_Base_Address
(Var Page_Frame_Address: Integer): Integer;
Var
Regs: Registers;
Begin
with Regs do
Begin
{----------------------------------------------------}
{ Get the page frame segment address from EMM. }
{ Load pseudo-registers prior to invoking EMM. }
{ AH = get page frame segment function }
{----------------------------------------------------}
AH := GET_PAGE_FRAME;
Intr (EMM_INT, Regs);
{----------------------------------------------------}
{ Unload the pseudo-registers after invoking EMM. }
{ BX = page frame segment address }
{ AH = status }
{----------------------------------------------------}
Page_Frame_Address := BX;
Get_Page_Frame_Base_Address := AH;
end; { with Regs do }
end; { Function Get_Page_Frame_Base_Address }
{------------------------------------------------------------}
{ This function releases the EMM memory pages allocated to }
{ us, back to the EMM memory pool. }
{------------------------------------------------------------}
Function Deallocate_Expanded_Memory_Pages
(Handle: Integer): Integer;
Var
Regs: Registers;
Begin
with Regs do
Begin
{----------------------------------------------------}
{ Deallocate the pages allocated to an EMM handle. }
{ Load pseudo-registers prior to invoking EMM. }
{ AH = deallocate pages function }
{ DX = EMM handle }
{----------------------------------------------------}
AH := DEALLOCATE_PAGES;
DX := Handle;
Intr (EMM_INT, Regs);
{----------------------------------------------------}
{ Unload the pseudo-registers after invoking EMM. }
{ AH = status }
{----------------------------------------------------}
Deallocate_Expanded_Memory_Pages := AH;
end; { with Regs do }
end; { Function Deallocate_Expanded_Memory_Pages }
{------------------------------------------------------------}
{ This function returns the version number of the EMM as }
{ a three-character string. }
{------------------------------------------------------------}
Function Get_Version_Number (Var Version_String: ST3): Integer;
Var
Regs: Registers;
Integer_Part, Fractional_Part: Char;
Begin
with Regs do
Begin
{----------------------------------------------------}
{ Get the version of EMM. }
{ Load pseudo-registers prior to invoking EMM. }
{ AH = get EMM version function }
{----------------------------------------------------}
AH := GET_VERSION;
Intr (EMM_INT, Regs);
{----------------------------------------------------}
{ If the version number returned was OK, then }
{ convert it to a three-character string. }
{----------------------------------------------------}
If AH=STATUS_OK then
Begin
{------------------------------------------------}
{ The upper four bits of AH are the integer }
{ portion of the version number, the lower four }
{ bits are the fractional portion. Convert the }
{ integer value to ASCII by adding 48. }
{------------------------------------------------}
Integer_Part := Char (AL shr 4 + 48);
Fractional_Part := Char (AL and $F + 48);
Version_String := Integer_Part + '.' +
Fractional_Part;
end; { If AH=STATUS_OK }
{----------------------------------------------------}
{ Unload the pseudo-registers after invoking EMM. }
{ AH = status }
{----------------------------------------------------}
Get_Version_Number := AH;
end; { with Regs do }
end; { Function Get_Version_Number }
{------------------------------------------------------------}
{ This procedure prints an error message passed by the }
{ caller, prints the error code passed by the caller in hex, }
{ and then terminates the program with an error level of 1. }
{------------------------------------------------------------}
Procedure Error (Error_Message: ST80; Error_Number: Integer);
Begin
Writeln (Error_Message);
Writeln (' Error_Number = ', Hex_String (Error_Number));
Writeln ('EMM test program aborting.');
Halt (1);
end; { Procedure Error }
{--------------------------------------------------------------}
{ This program is an example of the basic EMM functions that }
{ you need in order to use EMM memory with Turbo Pascal. }
{--------------------------------------------------------------}
Begin
ClrScr;
Window (5,2,77,22);
{------------------------------------------------------------}
{ Determine if the Expanded Memory Manager is installed. If }
{ not, then terminate 'main' with an ErrorLevel code of 1. }
{------------------------------------------------------------}
If not (Emm_Installed) then
Begin
Writeln ('The LIM EMM is not installed.');
Halt (1);
end
else
Begin
{ Get the version number and display it }
Error_Code := Get_Version_Number (Version_Number);
If Error_Code <> STATUS_OK then
Error ('Error getting EMM version number.', Error_Code)
else
Writeln ('LIM Expanded Memory Manager, version ',
Version_Number, ' is ready for use.');
end;
Writeln;
{------------------------------------------------------------}
{ Determine if there are enough expanded memory pages for }
{ this application. }
{------------------------------------------------------------}
Pages_Needed := APPLICATION_PAGE_COUNT;
Error_Code := EMM_Pages_Available (Total_EMM_Pages,
Available_EMM_Pages);
If Error_Code <> STATUS_OK then
Error ('Error determining number of EMM pages available.',
Error_Code);
Writeln ('There are a total of ', Total_EMM_Pages,
' expanded memory pages present in this system.');
Writeln (' ', Available_EMM_Pages,
' of those pages are available for use.');
Writeln;
{------------------------------------------------------------}
{ If there is an insufficient number of pages for the }
{ application, then report the error and terminate the EMM }
{ example program. }
{------------------------------------------------------------}
If Pages_Needed > Available_EMM_Pages then
Begin
Str (Pages_Needed, Pages_Number_String);
Error ('We need ' + Pages_Number_String +
' EMM pages. There are not that many available.',
Error_Code);
end; { Pages_Needed > Available_EMM_Pages }
{------------------------------------------------------------}
{ Allocate expanded memory pages for our use. }
{------------------------------------------------------------}
Error_Code :=
Allocate_Expanded_Memory_Pages (Pages_Needed, Emm_Handle);
Str (Pages_Needed, Pages_Number_String);
If Error_Code <> STATUS_OK then
Error ('EMM test program failed trying to allocate '
+ Pages_Number_String
+ ' pages for usage.', Error_Code);
Writeln (APPLICATION_PAGE_COUNT,
' EMM page(s) allocated for the EMM test program.');
Writeln;
{------------------------------------------------------------}
{ Map in the required logical pages to the physical pages }
{ given to us, in this case just one page. }
{------------------------------------------------------------}
Logical_Page := 0;
Physical_Page := 0;
Error_Code := Map_Expanded_Memory_Pages (Emm_Handle,
Logical_Page,
Physical_Page);
If Error_Code <> STATUS_OK then
Error ('EMM test program failed trying to map '
+ 'logical pages into physical pages.',
Error_Code);
Writeln ('Logical Page ',
Logical_Page,
' successfully mapped into Physical Page ',
Physical_Page);
Writeln;
{------------------------------------------------------------}
{ Get the expanded memory page frame address. }
{------------------------------------------------------------}
Error_Code := Get_Page_Frame_Base_Address
(Page_Frame_Base_Address);
If Error_Code <> STATUS_OK then
Error ('EMM test program unable to get the base Page'
+ ' Frame Address.',
Error_Code);
Writeln ('The base address of the EMM page frame is = '
+ Hex_String (Page_Frame_Base_Address));
Writeln;
{------------------------------------------------------------}
{ Write a test pattern to expanded memory. }
{------------------------------------------------------------}
For Offset := 0 to 16382 do
Begin
Mem[Page_Frame_Base_Address:Offset] := Offset mod 256;
end;
{------------------------------------------------------------}
{ Make sure that what is in EMM memory is what was just }
{ written. }
{------------------------------------------------------------}
Writeln ('Testing EMM memory.');
Offset := 1;
Verify := True;
while (Offset <= 16382) and (Verify = True) do
Begin
If Mem[Page_Frame_Base_Address:Offset] <> Offset mod 256
then Verify := False;
Offset := Succ (Offset);
end; { while (Offset <= 16382) and (Verify = True) }
{------------------------------------------------------------}
{ If what is read does not match what was written, }
{ an error occurred. }
{------------------------------------------------------------}
If not Verify then
Error ('What was written to EMM memory was not found during'
+ ' memory verification test.',
0);
Writeln ('EMM memory test successful.');
Writeln;
{------------------------------------------------------------}
{ Return the expanded memory pages given to us back to the }
{ EMM memory pool before terminating our test program. }
{------------------------------------------------------------}
Error_Code := Deallocate_Expanded_Memory_Pages (Emm_Handle);
If Error_Code <> STATUS_OK then
Error ('EMM test program was unable to deallocate '
+ 'the EMM pages in use.',
Error_Code);
Writeln (APPLICATION_PAGE_COUNT,
' pages(s) deallocated.');
Writeln;
Writeln ('EMM test program completed.');
end.
|
unit ThrddCF;
{**********************************************
Kingstar Delphi Library
Copyright (C) Kingstar Corporation
<Unit> ThrddCF
<What> Threaded Class Factory
<Written By> Huang YanLai
<History>
**********************************************}
// base on delphi's ThrddCF.pas
{*******************************************************}
{ }
{ Threaded Class Factory Demo }
{ }
{*******************************************************}
{
This unit provides some custom class factories that implement threading for
out of process servers. The TThreadedAutoObjectFactory is for any TAutoObject
and the TThreadedClassFactory is for and TComponentFactory. To use them,
replace the line in the initialization section of your automation object to
use the appropriate threaded class factory instead of the non-threaded version.
}
interface
uses messages,sysUtils,ComObj, ActiveX, Classes, Windows, VCLCom, Forms;
type
TCreateInstanceProc = function(const UnkOuter: IUnknown;
const IID: TGUID; out Obj): HResult of object; stdcall;
{ TThreadedAutoObjectFactory }
TThreadedAutoObjectFactory = class(TAutoObjectFactory, IClassFactory)
protected
function CreateInstance(const UnkOuter: IUnknown; const IID: TGUID;
out Obj): HResult; stdcall;
function DoCreateInstance(const UnkOuter: IUnknown; const IID: TGUID;
out Obj): HResult; stdcall;
end;
{ TThreadedClassFactory }
TThreadedClassFactory = class(TComponentFactory, IClassFactory)
protected
function CreateInstance(const UnkOuter: IUnknown; const IID: TGUID;
out Obj): HResult; stdcall;
function DoCreateInstance(const UnkOuter: IUnknown; const IID: TGUID;
out Obj): HResult; stdcall;
end;
{ TApartmentThread }
TApartmentThread = class(TThread)
private
FCreateInstanceProc: TCreateInstanceProc;
FUnkOuter: IUnknown;
FIID: TGuid;
FSemaphore: THandle;
FStream: Pointer;
FCreateResult: HResult;
protected
procedure Execute; override;
public
constructor Create(CreateInstanceProc: TCreateInstanceProc; UnkOuter: IUnknown; IID: TGuid);
destructor Destroy; override;
property Semaphore: THandle read FSemaphore;
property CreateResult: HResult read FCreateResult;
property ObjStream: Pointer read FStream;
end;
TCOMServerThread = class(TThread)
private
FCreateResult: boolean;
FTimeOut : integer;
FTimeOutDateTime : TDateTime;
FKeepStay: boolean;
procedure SetTimeOut(const Value: integer);
protected
FServerObject : TObject;
// set FStream : Pointer to avoid delphi's counting
FStream: Pointer;
FSemaphore: THandle;
FServerInterface : IUnknown;
FLastAccessTime: TDateTime;
FTimer : THandle;
procedure Execute; override;
// return whether success
function CreateServer(out Unk: IUnknown):boolean; virtual;abstract;
procedure InitServer; virtual;
function CanTimeout : boolean; virtual;
function UnMarshalInterface(out Unk: IUnknown):HResult;
function MarshalInterface:HResult;
function MarshalInterfaceEx(const IID : TGUID):HResult;
function UnMarshalInterfaceEx(const IID : TGUID; out Unk):HResult;
public
constructor Create;
destructor Destroy; override;
procedure ReleaseSemaphore;
// called out of this thread
procedure Wait;
function WaitForCreate:boolean;
procedure Release; virtual;
function GetServerInterface: IUnknown;
property CreateResult : boolean read FCreateResult;
property Semaphore: THandle read FSemaphore;
property ObjStream: Pointer read FStream;
property ServerObject : TObject read FServerObject;
property ServerInterface : IUnknown read GetServerInterface;
property LastAccessTime : TDateTime read FLastAccessTime;
// TimeOut is in minutes
// if TimeOut<=0 , no TimeOut
property TimeOut : integer read FTimeOut write SetTimeOut;
function GetServerInterfaceEx(const IID : TGUID; out obj): HResult;
property KeepStay : boolean read FKeepStay write FKeepStay default true;
end;
const
ServerThreadMsg_MarshalInterface = WM_User + $1000;
ServerThreadMsg_MarshalInterfaceEx = WM_User + $1001;
implementation
uses SafeCode;
{ TThreadedAutoObjectFactory }
function TThreadedAutoObjectFactory.DoCreateInstance(const UnkOuter: IUnknown;
const IID: TGUID; out Obj): HResult; stdcall;
begin
Result := inherited CreateInstance(UnkOuter, IID, Obj);
end;
function TThreadedAutoObjectFactory.CreateInstance(const UnkOuter: IUnknown;
const IID: TGUID; out Obj): HResult; stdcall;
begin
with TApartmentThread.Create(DoCreateInstance, UnkOuter, IID) do
begin
if WaitForSingleObject(Semaphore, INFINITE) = WAIT_OBJECT_0 then
begin
Result := CreateResult;
if Result <> S_OK then Exit;
Result := CoGetInterfaceAndReleaseStream(IStream(ObjStream), IID, Obj);
end else
Result := E_FAIL
end;
end;
{ TThreadedClassFactory }
function TThreadedClassFactory.DoCreateInstance(const UnkOuter: IUnknown;
const IID: TGUID; out Obj): HResult; stdcall;
begin
Result := inherited CreateInstance(UnkOuter, IID, Obj);
end;
function TThreadedClassFactory.CreateInstance(const UnkOuter: IUnknown;
const IID: TGUID; out Obj): HResult; stdcall;
begin
with TApartmentThread.Create(DoCreateInstance, UnkOuter, IID) do
begin
if WaitForSingleObject(Semaphore, INFINITE) = WAIT_OBJECT_0 then
begin
Result := CreateResult;
if Result <> S_OK then Exit;
Result := CoGetInterfaceAndReleaseStream(IStream(ObjStream), IID, Obj);
end else
Result := E_FAIL
end;
end;
{ TApartmentThread }
constructor TApartmentThread.Create(CreateInstanceProc: TCreateInstanceProc;
UnkOuter: IUnknown; IID: TGuid);
begin
FCreateInstanceProc := CreateInstanceProc;
FUnkOuter := UnkOuter;
FIID := IID;
FSemaphore := CreateSemaphore(nil, 0, 1, nil);
FreeOnTerminate := True;
inherited Create(False);
end;
destructor TApartmentThread.Destroy;
begin
FUnkOuter := nil;
CloseHandle(FSemaphore);
inherited Destroy;
Application.ProcessMessages;
end;
procedure TApartmentThread.Execute;
var
msg: TMsg;
Unk: IUnknown;
begin
CoInitialize(nil);
FCreateResult := FCreateInstanceProc(FUnkOuter, FIID, Unk);
if FCreateResult = S_OK then
CoMarshalInterThreadInterfaceInStream(FIID, Unk, IStream(FStream));
ReleaseSemaphore(FSemaphore, 1, nil);
if FCreateResult = S_OK then
while GetMessage(msg, 0, 0, 0) do
begin
DispatchMessage(msg);
Unk._AddRef;
if Unk._Release = 1 then break;
end;
Unk := nil;
CoUninitialize;
end;
{ TCOMServerThread }
constructor TCOMServerThread.Create;
begin
FTimeOut := -1;
FSemaphore := CreateSemaphore(nil, 0, 1, nil);
FreeOnTerminate := True;
FKeepStay := true;
inherited Create(False);
end;
destructor TCOMServerThread.Destroy;
begin
FServerInterface := nil;
// FServerObject is freed by FServerInterface
//FServerObject.free;
CloseHandle(FSemaphore);
inherited Destroy;
Application.ProcessMessages;
end;
procedure TCOMServerThread.Release;
begin
FServerInterface := nil;
end;
procedure TCOMServerThread.Execute;
var
msg: TMsg;
Unk: IUnknown;
FCurTime : TDateTime;
RefCount : integer;
begin
CoInitialize(nil);
FCreateResult := CreateServer(Unk);
if FCreateResult then
begin
FServerInterface := Unk;
//CoMarshalInterThreadInterfaceInStream(IUnknown, Unk, IStream(FStream));
end;
// force the system to create the message queue
PeekMessage(msg, 0, WM_USER, WM_USER, PM_NOREMOVE);
ReleaseSemaphore;
// Init Server;
InitServer;
if FCreateResult then
begin
FTimer := SetTimer(0,0,1000*30,nil);
while GetMessage(msg, 0, 0, 0) do
begin
DispatchMessage(msg);
outPutDebugString('AddRef and Release For Count Testing');
Unk._AddRef;
RefCount := Unk._Release;
outPutDebugString(pchar('Count Testing : '+IntToStr(RefCount)));
if RefCount=1 then break
else if (RefCount=2) and not KeepStay then
begin
Release;
break;
end;
FCurTime := Now;
//if (msg.message=WM_Timer) and (msg.hwnd=0) then
// avoid OLEChanel Window's WM_Timer
if (msg.message=WM_Timer) then
begin
// check time out
if CanTimeout and (FLastAccessTime+FTimeOutDateTime<FCurTime) then
begin
OutputDebugString('Time out!');
break;
end
else
begin
OutputDebugString(pchar(
' now : '+ formatDateTime('hh:nn:ss',FCurTime)+
' last : '+ formatDateTime('hh:nn:ss',FLastAccessTime)
));
end;
end
else if (msg.hwnd=0) and
(msg.message=ServerThreadMsg_MarshalInterface) and
(msg.wParam=ServerThreadMsg_MarshalInterface) and
(msg.lParam=ServerThreadMsg_MarshalInterface) then
begin
MarshalInterface;
ReleaseSemaphore;
end
else if (msg.hwnd=0) and
(msg.message=ServerThreadMsg_MarshalInterfaceEx) and
(msg.wParam=ServerThreadMsg_MarshalInterfaceEx)then
begin
MarshalInterfaceEx(PGUID(msg.LParam)^);
ReleaseSemaphore;
end
else
begin
FLastAccessTime := FCurTime;
OutputDebugString(pchar(
' now : '+ formatDateTime('hh:nn:ss',FCurTime)+
' msg : '+ IntToHex(msg.message,8)+
' wnd : '+ IntToHex(msg.hwnd,8)
));
end;
end; // end while
KillTimer(0,FTimer);
end;
Unk := nil;
CoUninitialize;
end;
procedure TCOMServerThread.Wait;
begin
CheckTrue(WaitForSingleObject(FSemaphore, INFINITE) = WAIT_OBJECT_0);
end;
procedure TCOMServerThread.ReleaseSemaphore;
begin
windows.ReleaseSemaphore(FSemaphore, 1, nil);
end;
function TCOMServerThread.MarshalInterface:HResult;
begin
// must set FStream=nil to avoid delphi's counting
FStream:=nil;
result := CoMarshalInterThreadInterfaceInStream(IUnknown, FServerInterface, IStream(FStream));
end;
function TCOMServerThread.UnMarshalInterface(out Unk: IUnknown):HResult;
begin
Result := CoGetInterfaceAndReleaseStream(IStream(FStream), IUnknown, Unk);
// must set FStream=nil to avoid delphi's counting
FStream:=nil;
end;
function TCOMServerThread.WaitForCreate: boolean;
begin
wait;
Result := FCreateResult;
if result then
begin
//result := CoGetInterfaceAndReleaseStream(IStream(ObjStream), IUnknown, FServerInterface)=S_OK;
//Synchronize(MarshalInterface);
end;
//ReleaseSemaphore;
end;
procedure TCOMServerThread.SetTimeOut(const Value: integer);
begin
FTimeOut := Value;
FTimeOutDateTime := FTimeOut * ( 1 / 24 / 60);
OutputDebugString(pchar(
formatDateTime('hh:nn:ss',FTimeOutDateTime)
));
end;
function TCOMServerThread.CanTimeout: boolean;
begin
result := FTimeOut>0;
end;
function TCOMServerThread.GetServerInterface: IUnknown;
begin
if GetCurrentThreadId=ThreadId then
result := FServerInterface else
begin
if PostThreadMessage(ThreadId,
ServerThreadMsg_MarshalInterface,
ServerThreadMsg_MarshalInterface,
ServerThreadMsg_MarshalInterface) then
begin
wait;
{if UnMarshalInterface(result)<>S_OK then
result:=nil;}
CheckTrue(UnMarshalInterface(result)=S_OK,'Error : UnMarshalInterface');
end
else result:=nil;
end;
end;
function TCOMServerThread.GetServerInterfaceEx(const IID: TGUID;
out obj): HResult;
begin
try
if GetCurrentThreadId=ThreadId then
result:=FServerInterface.QueryInterface(IID,Obj) else
begin
if PostThreadMessage(ThreadId,
ServerThreadMsg_MarshalInterfaceEx,
ServerThreadMsg_MarshalInterfaceEx,
integer(@IID)) then
begin
wait;
result := UnMarshalInterfaceEx(IID,Obj);
end
else
begin
Pointer(obj) := nil;
result:=S_FALSE;
end;
end;
except
pointer(obj) := nil;
result := S_FALSE;
end;
end;
function TCOMServerThread.MarshalInterfaceEx(const IID: TGUID): HResult;
{var
Intf : IUnknown;}
begin
// must set FStream=nil to avoid delphi's counting
FStream:=nil;
{result := FServerInterface.QueryInterface(IID,Intf);
if result=S_OK then
result := CoMarshalInterThreadInterfaceInStream(IID, Intf, IStream(FStream));}
result := CoMarshalInterThreadInterfaceInStream(IID, FServerInterface, IStream(FStream));
end;
function TCOMServerThread.UnMarshalInterfaceEx(const IID: TGUID;
out Unk): HResult;
begin
Result := CoGetInterfaceAndReleaseStream(IStream(FStream), IID, Unk);
// must set FStream=nil to avoid delphi's counting
FStream:=nil;
end;
procedure TCOMServerThread.InitServer;
begin
// do nothing
end;
end.
|
{ Форма просмотра и проверки документов по вывозу отходов }
unit UFrmCheckingWasteDoc;
interface
uses
udmWASTE_DOC, udmWasteLimit, udmWASTE_PROTOKOL, udmMain, udmReports,
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ActnList, ExtCtrls, ComCtrls,
DBGridEhGrouping, ToolCtrlsEh,
DBGridEhToolCtrls, DynVarsEh, EhLibVCL, GridsEh, DBAxisGridsEh, DBGridEh,
DB, Contnrs, OleCtrls, SHDocVw, Ora, System.Actions;
type
{Событие для обновления даных на форме контроля документов}
TUpdateLimitEvt = procedure (fkko_code: string; fkko_name: string; dlt_limit: string) of Object;
TFrmCheckingWasteDoc = class(TForm)
pagDataView: TPageControl;
pnlButtons: TPanel;
btnExit: TButton;
ActionList1: TActionList;
actFindDoc: TAction;
actExit: TAction;
tbshNoFoundDoc: TTabSheet;
lblNotFoundText: TLabel;
btnFindAgain: TButton;
actFindDocAgain: TAction;
actEndProcess: TAction;
tbshFindDoc: TTabSheet;
edtDocNum: TEdit;
calDocDate: TDateTimePicker;
lblStepName: TLabel;
lblDocName: TLabel;
lblDocDate: TLabel;
btnFindDoc: TButton;
tbshViewShipDoc: TTabSheet;
grdListDocs: TDBGridEh;
lblReviewDoc: TStaticText;
Button1: TButton;
actReviewDocument: TAction;
btnApprove: TButton;
btnErrorToPtocol: TButton;
actApproveDoc: TAction;
actSendErrorToProtocol: TAction;
tbshProtocol: TTabSheet;
memMessage: TMemo;
lblMessageCaption: TLabel;
btnSaveToProtocol: TButton;
actSaveMessage: TAction;
btnReturn: TButton;
actReturnToCheckScreen: TAction;
actPrintTP: TAction;
btnPrintTP: TButton;
actPrintAndSaveTp: TAction;
tbsh_limit_control: TTabSheet;
lbl_limit_control: TStaticText;
btn_senf_email: TButton;
act_send_email: TAction;
web_view_report: TWebBrowser;
procedure act_send_emailExecute(Sender: TObject);
procedure actReturnToCheckScreenExecute(Sender: TObject);
procedure actPrintAndSaveTpExecute(Sender: TObject);
procedure actPrintTPExecute(Sender: TObject);
procedure actSaveMessageExecute(Sender: TObject);
procedure actSendErrorToProtocolExecute(Sender: TObject);
procedure actApproveDocExecute(Sender: TObject);
procedure actReviewDocumentExecute(Sender: TObject);
procedure actEndProcessExecute(Sender: TObject);
procedure actFindDocAgainExecute(Sender: TObject);
procedure actExitExecute(Sender: TObject);
procedure actFindDocExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
FdmWASTE_DOC : TdmWASTE_DOC;
// FRptPlaceShipDoc : TRptPlaceShipDoc;
// FTrepFullNakl : TrepFullNakl;
// FFrmTalonPassportReport : TFrmTalonPassportReport;
FdmWasteLimit: TdmWasteLimit;
{Выбрать страницу перехода при контроле лимита
@param (is_controlled результат контроля лимитов отходов
@return (ссылка на страницу перехода))}
function choice_page(is_controlled: boolean): TTabSheet;
public
{ Public declarations }
function GetDataModel : TdmWASTE_DOC;
{Обновить сообшение о превышении лимита
@param (fkko_code код фкко)
@param (fkko_name наименование фкко)
@param (dlt_limit превышение веса в тоннах)
}
procedure update_limit_state(const fkko_code{, fkko_name, dlt_limit}: string);
end;
TControlLimit = (inLmt, notLmt); //< Значение для определения выполнения лимита inLimit- лимит выполняется
TControlLimitSet = set of TControlLimit;
{ Класс для расчета и контроля лимитов }
TOverLimitWasteControl = class
private
fWaste: TDmWASTE_DOC;
fProtocol: TdmWASTE_PROTOKOL;
fCalc_limit: TdmWasteLimit;
Fupdate_limit_evt: TUpdateLimitEvt;
procedure Setupdate_limit_evt(const Value: TUpdateLimitEvt);
{Выдать номер ТП
@param (data набор данных по ТП)
@return (номер ТП)}
function get_tp_num(data: TDataSet): string;
{Выдать дату ТП
@param (data набор данных по ТП)
@return (дату ТП)}
function get_tp_dt(data: TDataSet): string;
{Выдать номер а/т
@param (data набор данных по ТП)
@return (номер а/т)}
function get_tp_car_num(data: TDataSet): string;
{Выдать наименование подразделения
@param (data набор данных по ТП)
@return (наименование подразделения)}
function get_tp_unit_name(data: TDataSet): string;
{Выдать наименование в строке ТП
@param (data набор данных по ТП)
@return (наименование в строке ТП)}
function get_tp_wst_name(data: TDataSet): string;
{Выдать вес по строке ТП
@param (data набор данных по ТП)
@return (вес в строке ТП тонна)}
function get_item_wt(data: TDataSet): string;
{Выдать код ФККО
@param (data набор данных по ТП)
@return (код ФККО)}
function get_fkko_code(data: TDataSet): string;
{Выдать наименование ФККО
@param (data набор данных по ТП)
@return (наименование ФККО)}
function get_fkko_name(data: TDataSet): string;
{Выдать вес по ФККО текущей строки ТП
@param (data набор данных по ТП)
@return (вес по ФККО)}
function get_fkko_wt(data: TDataSet): string;
{Выдать лимит по ФККО
@param (data набор данных по ТП)
@return (лимит по ФККО)}
function get_fkko_lmt(data: TDataSet): string;
{Выдать факт по ФККО с начала года
@param (data набор данных по ТП)
@return (факт по ФККО)}
function get_fkko_fct(data: TDataSet): string;
{Выдать лимит - факт по ФККО с начала года исполненние лимита
@param (data набор данных по ТП)
@return (лимит - факт)}
function get_fkko_dlt(data: TDataSet): string;
function is_not_in_limit(data: TDataSet): TControlLimit;
public
constructor create_limit_waste_control(waste: TdmWASTE_DOC; protocol: TdmWASTE_PROTOKOL; calc_limit: TdmWasteLimit);
destructor destroy;override;
{Выполнить контроль лимита для найденного документа
@return (true- нет превышения false- есть превышение лимита)}
function control_limit: boolean;virtual;
{Сформировать текст сообщения для e-mail
@return (сообщение о превышении лимита отходов для e-mail)}
// function get_message_email(): string;
property update_limit_evt: TUpdateLimitEvt read Fupdate_limit_evt write Setupdate_limit_evt;
end;
{Обертка для расчета веса в строках ТПю Использует процедуру VOXR.WASTE_CALC_ITEMS_WEIGHT}
TTPWtCalculator = class(TComponent)
private
fOra_sql: TOraQuery;
public
constructor create_calulator(owner: TComponent; session: TOraSession);
{Рассчитать вес в ТП для каждой строки
@param (docid ид талона-паспорта)}
procedure calc_item_wt(const docid: string);
end;
var
FrmCheckingWasteDoc: TFrmCheckingWasteDoc;
resourcestring
LPT_CAPTION = 'Печать талона паспорта на принтер';
LPT_DOC_IS_PRINTED = 'Талон паспорт № %s от %s распечатан правильно?';
implementation
uses uhtmlComponents, StrUtils, DateUtils, UDmOracleSMTP;
const
NOT_FOUND_MSG = 'Разрешение на погрузку № %s от %s не найдено';
MAIL_FROM = 'arm_voxr@arconic.com';
{$R *.dfm}
procedure TFrmCheckingWasteDoc.FormCreate(Sender: TObject);
begin
FdmWASTE_DOC := TdmWASTE_DOC.Create(self);
FdmWASTE_DOC.SetSession(dmMain.oraSS);
pagDataView.ActivePageIndex := 1;
grdListDocs.DataSource := FdmWASTE_DOC.srcTblConnect;
FdmWASTE_DOC.OnPrintTpReady := actPrintTPExecute;
TdmWASTE_PROTOKOL.GetInstance().Init(dmMain.oraSS);
with TdmWASTE_PROTOKOL.GetInstance() do
begin
AppName := AppCaption;
Autor := dmMain.UserFIO + ', ' + dmMain.kpp_name;
end;
pagDataView.ActivePage := tbshFindDoc;
calDocDate.DateTime := Now();
FdmWasteLimit := TDmWasteLimit.Create(self);
FdmWasteLimit.qry_calc_limit_year.Session := dmMain.oraSS;
end;
procedure TFrmCheckingWasteDoc.actFindDocExecute(Sender: TObject);
var
limit_control: TOverLimitWasteControl;
wt_calculator: TTPWtCalculator;
begin
limit_control := TOverLimitWasteControl.create_limit_waste_control(FdmWASTE_DOC,
TdmWASTE_PROTOKOL.GetInstance(), self.FdmWasteLimit);
limit_control.update_limit_evt := self.update_limit_state;
wt_calculator := TTPWtCalculator.create_calulator(self, dmMain.oraSS);
try
FdmWASTE_DOC.FindDocument(self.edtDocNum.Text, self.calDocDate.Date);
self.btnPrintTP.Enabled := false;
if FdmWASTE_DOC.GetDocId() = 0 then
begin
self.pagDataView.ActivePage := self.tbshNoFoundDoc;
self.lblNotFoundText.Caption := Format(NOT_FOUND_MSG, [self.edtDocNum.Text, DateToStr(self.calDocDate.Date)]);
end
else
begin
wt_calculator.calc_item_wt(IntToStr(self.FdmWASTE_DOC.GetDocId()));
self.pagDataView.ActivePage := self.choice_page(limit_control.control_limit());
self.FdmWASTE_DOC.CollectShipDocs();
end;
finally
limit_control.Free();
wt_calculator.Free();
end;
end;
procedure TFrmCheckingWasteDoc.actExitExecute(Sender: TObject);
begin
ModalResult := mrCancel;
Close;
end;
procedure TFrmCheckingWasteDoc.actFindDocAgainExecute(Sender: TObject);
begin
self.pagDataView.ActivePage := self.tbshFindDoc;
end;
procedure TFrmCheckingWasteDoc.actEndProcessExecute(Sender: TObject);
begin
self.Close;
end;
procedure TFrmCheckingWasteDoc.actReviewDocumentExecute(Sender: TObject);
begin
if SameText(self.FdmWASTE_DOC.GetWasteShipDocType(), WT_DOC_TYPE) then
TdmReports.CallReport_WeighingDoc(dmMain.oraSS, pmPre_View, AppNum, WD_TemplateId,
FdmWASTE_DOC.GetReviewedDocId() )
else
if SameText(self.FdmWASTE_DOC.GetWasteShipDocType(), TP_DOC_TYPE) then
TdmReports.CallReport_LoadPermit(dmMain.oraSS, pmPre_View, PoligonCode, LP_TemplateId,
FdmWASTE_DOC.GetDocId, FdmWASTE_DOC.GetPlaceDoc(), LP_rollback_status );
end;
procedure TFrmCheckingWasteDoc.actApproveDocExecute(Sender: TObject);
begin
TdmWASTE_PROTOKOL.GetInstance().AddMessage(self.FdmWASTE_DOC.GetDocId,
UdmWASTE_PROTOKOL.STATUS_NORM,
TdmWASTE_PROTOKOL.GetInstance().AppName,
TdmWASTE_PROTOKOL.GetInstance().Autor,
self.FdmWASTE_DOC.GetDocumentName());
FdmWASTE_DOC.ApproveDocument();
end;
procedure TFrmCheckingWasteDoc.actSendErrorToProtocolExecute(Sender: TObject);
begin
self.pagDataView.ActivePage := self.tbshProtocol;
end;
procedure TFrmCheckingWasteDoc.actSaveMessageExecute(Sender: TObject);
begin
TdmWASTE_PROTOKOL.GetInstance().AddMessage(self.FdmWASTE_DOC.GetDocId,
UdmWASTE_PROTOKOL.STATUS_WARNING,
TdmWASTE_PROTOKOL.GetInstance().AppName,
TdmWASTE_PROTOKOL.GetInstance().Autor,
self.memMessage.Lines.Text);
MessageBox(self.Handle, 'Сообщение сохранено', 'Сообщение', MB_OK);
end;
procedure TFrmCheckingWasteDoc.actPrintTPExecute(Sender: TObject);
begin
if (Sender as TdmWASTE_DOC).IsDocsApproved then
self.btnPrintTP.Enabled := true
else
self.btnPrintTP.Enabled := false;
end;
procedure TFrmCheckingWasteDoc.actPrintAndSaveTpExecute(Sender: TObject);
var
msgboxID : integer;
begin
if TdmReports.CallReport_TalonPass(dmMain.oraSS, pmOriginal, AppNum, TALON_PASS_ID,FdmWASTE_DOC.GetDocId()) then
begin
msgboxID := MessageBox(self.Handle,
PChar(Format(LPT_DOC_IS_PRINTED, [self.edtDocNum.Text, FormatDateTime('dd.mm.yyyy', self.calDocDate.Date)])),
PChar(LPT_CAPTION),
MB_ICONWARNING or MB_YESNO or MB_DEFBUTTON1);
if msgboxID = IDYES then
begin
FdmWASTE_DOC.SetPrintFlag;
Close;
ModalResult := mrOK;
end;
end;
end;
function TFrmCheckingWasteDoc.GetDataModel: TdmWASTE_DOC;
begin
Result := self.FdmWASTE_DOC;
end;
procedure TFrmCheckingWasteDoc.actReturnToCheckScreenExecute(Sender: TObject);
begin
self.pagDataView.ActivePage := self.tbshViewShipDoc;
end;
{ TOverLimitWasteControl }
function TOverLimitWasteControl.control_limit: boolean;
var
data: TDataSet;
d, m, y: WORD;
html_block: TStringList;
tempFolder: array[0..MAX_PATH] of Char;
temp_file: array[0..MAX_PATH] of Char;
// ret_code: cardinal;
temp_html_block: string;
temp_control_set: TControlLimitSet;
begin
result := false;
temp_control_set := [];
if not fWaste.is_weighting() then
begin
result := true;
exit;
end;
if fWaste.is_printed() then
begin
result := true;
exit;
end;
if self.fProtocol.get_last_status_code(fWaste.qryFindDoc.FieldByName('waste_doc_id').AsString) = udmWASTE_PROTOKOL.STATUS_OVER_LIMITS_WASTE_APPROVED then
begin
result := true;
exit;
end;
html_block := TStringList.Create();
try
DecodeDate(fWaste.qryFindDoc.FieldByName('doc_date').AsDateTime, y, m, d);
data := self.fCalc_limit.select_limit_by_doc(fWaste.qryFindDoc.FieldByName('waste_doc_id').AsString, IntToStr(y));
temp_html_block := html_header;
temp_html_block := ReplaceStr(temp_html_block, '99tp', self.get_tp_num(data));
temp_html_block := ReplaceStr(temp_html_block, '99dt', self.get_tp_dt(data));
temp_html_block := ReplaceStr(temp_html_block, '99car', self.get_tp_car_num(data));
temp_html_block := ReplaceStr(temp_html_block, '99unit', self.get_tp_unit_name(data));
html_block.Add(temp_html_block);
data.First();
while not data.Eof do
begin
case data.FieldByName('abc').AsInteger of
0: begin
temp_html_block := html_fkko;
temp_html_block := ReplaceStr(temp_html_block, '99fkkocode', self.get_fkko_code(data));
temp_html_block := ReplaceStr(temp_html_block, '99fkkoname', self.get_fkko_name(data));
temp_html_block := ReplaceStr(temp_html_block, '99fkkowt', self.get_fkko_wt(data));
temp_html_block := ReplaceStr(temp_html_block, '99lmt', self.get_fkko_lmt(data));
temp_html_block := ReplaceStr(temp_html_block, '99fkkofct', self.get_fkko_fct(data));
temp_html_block := ReplaceStr(temp_html_block, '99fkkodlt', self.get_fkko_dlt(data));
temp_control_set := temp_control_set + [self.is_not_in_limit(data)];
html_block.Add(temp_html_block);
end;
1: begin
temp_html_block := html_tp_str;
temp_html_block := ReplaceStr(temp_html_block, '99wstname', self.get_tp_wst_name(data));
temp_html_block := ReplaceStr(temp_html_block, '99wsttpwt', self.get_item_wt(data));
html_block.Add(temp_html_block);
end;
end;
data.Next();
end;
html_block.Add(html_footer);
GetTempPath(MAX_PATH, @tempFolder);
{ ret_code := 0;
ret_code := GetTempFileName(tempFolder, // directory for tmp files
'LIMIT_', // temp file name prefix
0, // create unique name
temp_file); }
html_block.SaveToFile(temp_file);
result := not (notLmt in temp_control_set);
if not result then
begin
self.fProtocol.AddMessage(fWaste.qryFindDoc.FieldByName('waste_doc_id').AsInteger, STATUS_OVER_LIMITS_WASTE_DISPOSAL,
TdmWASTE_PROTOKOL.GetInstance().AppName, TdmWASTE_PROTOKOL.GetInstance().Autor, 'Превышение лимита');
if Assigned(self.Fupdate_limit_evt) then
self.Fupdate_limit_evt(StrPas(temp_file), '', '');
end;
finally
html_block.Free();
end;
end;
constructor TOverLimitWasteControl.create_limit_waste_control(
waste: TdmWASTE_DOC; protocol: TdmWASTE_PROTOKOL; calc_limit: TdmWasteLimit);
begin
inherited Create;
self.fWaste := waste;
self.fProtocol := protocol;
self.fCalc_limit := calc_limit;
self.update_limit_evt := nil;
end;
function TFrmCheckingWasteDoc.choice_page(is_controlled: boolean): TTabSheet;
begin
if is_controlled then
result := self.tbshViewShipDoc
else
result := self.tbsh_limit_control;
end;
destructor TOverLimitWasteControl.destroy;
begin
inherited;
end;
function TOverLimitWasteControl.get_fkko_code(data: TDataSet): string;
begin
result := data.FieldByName('waste_code').AsString;
end;
function TOverLimitWasteControl.get_fkko_lmt(data: TDataSet): string;
begin
result := data.FieldByName('lmt_total').AsString;
end;
function TOverLimitWasteControl.get_fkko_dlt(data: TDataSet): string;
begin
result := data.FieldByName('dlt').AsString;
end;
function TOverLimitWasteControl.get_fkko_fct(data: TDataSet): string;
begin
result := data.FieldByName('fact_total').AsString;
end;
function TOverLimitWasteControl.get_fkko_name(data: TDataSet): string;
begin
result := data.FieldByName('w_name').AsString;
end;
function TOverLimitWasteControl.get_fkko_wt(data: TDataSet): string;
begin
result := data.FieldByName('doc_wt').AsString;
end;
function TOverLimitWasteControl.get_item_wt(data: TDataSet): string;
begin
result := data.FieldByName('doc_wt').AsString;
end;
//function TOverLimitWasteControl.get_message_email: string;
//begin
//
//end;
function TOverLimitWasteControl.get_tp_car_num(data: TDataSet): string;
begin
data.First;
if data.Locate('abc', VarArrayOf([2]), []) then
result := data.FieldByName('car_num').AsString
else
result := ' ';
end;
function TOverLimitWasteControl.get_tp_dt(data: TDataSet): string;
begin
data.First;
if data.Locate('abc', VarArrayOf([2]), []) then
result := FormatDateTime('dd.mm.yyyy', data.FieldByName('doc_date').AsDateTime)
else
result := ' ';
end;
function TOverLimitWasteControl.get_tp_num(data: TDataSet): string;
begin
data.First;
if data.Locate('abc', VarArrayOf([2]), []) then
result := data.FieldByName('doc_num').AsString
else
result := ' ';
end;
function TOverLimitWasteControl.get_tp_unit_name(data: TDataSet): string;
begin
data.First;
if data.Locate('abc', VarArrayOf([2]), []) then
result := data.FieldByName('name_unit').AsString
else
result := ' ';
end;
function TOverLimitWasteControl.get_tp_wst_name(data: TDataSet): string;
begin
result := data.FieldByName('svi_name').AsString;
end;
procedure TOverLimitWasteControl.Setupdate_limit_evt(
const Value: TUpdateLimitEvt);
begin
Fupdate_limit_evt := Value;
end;
procedure TFrmCheckingWasteDoc.update_limit_state(const fkko_code{, fkko_name,
dlt_limit}: string);
begin
// self.mem_tp_text.Lines.Add(Format('Превышение лимита для %s %s на %s', [fkko_code, fkko_name, dlt_limit]));
self.web_view_report.Navigate(fkko_code);
end;
function TOverLimitWasteControl.is_not_in_limit(data: TDataSet): TControlLimit;
begin
if data.FieldByName('dlt').AsFloat < 0 then
result := notLmt
else
result := inLmt;
end;
procedure TFrmCheckingWasteDoc.act_send_emailExecute(Sender: TObject);
var
mail_list: string;
smtp: TdmOracleSMTP;
body: TStringList;
s: string;
begin
smtp := TdmOracleSMTP.create_smtp(self, dmMain.oraSS);
body := TStringList.Create();
try
mail_list := smtp.get_email_adr(POLIGON_APP_CODE, '1, 2');
s := web_view_report.LocationURL;
s := ReplaceStr(s, 'file:///', '');
body.LoadFromFile(s);
smtp.send_email(mail_list, MAIL_FROM, 'Превышение лимита отходов', body.Text);
smtp.Free();
body.Free();
MessageBox(self.Handle, 'Сообщение отправлено', 'Внимание', MB_OK);
except on e: Exception do
begin
smtp.Free();
body.Free();
MessageBox(self.Handle, PChar('При отправке сообщения возникла ошибка: ' + e.Message), 'Ошибка', MB_OK);
end;
end;
end;
{ TTPWtCalculator }
procedure TTPWtCalculator.calc_item_wt(const docid: string);
var
wt_tp_tonn: extended;
is_printed: boolean;
begin
self.fOra_sql.Close();
self.fOra_sql.SQL.Text := sql_wt_by_doc;
self.fOra_sql.ParamByName('docid').AsString := docid;
self.fOra_sql.Open();
wt_tp_tonn := self.fOra_sql.FieldByName('weight').AsFloat;
is_printed := self.fOra_sql.FieldByName('is_printed').AsInteger = 1;
self.fOra_sql.Close();
if is_printed then
exit;
self.fOra_sql.SQL.Text := sql_calc_wt;
self.fOra_sql.ParamByName('docid').AsString := docid;
self.fOra_sql.ParamByName('wt').AsFloat := wt_tp_tonn;
if not self.fOra_sql.Session.InTransaction then
self.fOra_sql.Session.StartTransaction;
try
self.fOra_sql.Execute;
self.fOra_sql.Session.Commit;
except
on e: Exception do
begin
self.fOra_sql.Session.Rollback;
raise Exception.Create(e.Message);
end;
end;
end;
constructor TTPWtCalculator.create_calulator(owner: TComponent;
session: TOraSession);
begin
inherited Create(owner);
fOra_sql := TOraQuery.Create(self);
fOra_sql.Session := session;
end;
end.
|
program fodP3E1;
uses
crt;
const
corte = 'fin';
max = 70;
type
empleado = record
nro: integer;
apellido: string[15];
nombre: string[15];
edad: integer;
dni: integer;
end;
archivoDeEmpleados = file of empleado;
procedure leer(var e: empleado);
begin
with e do begin
write('* Apellido: '); readln(apellido);
if (apellido <> corte) then begin
write('* Nombre: '); readln(nombre);
write('* Edad: '); readln(edad);
write('* Dni: '); readln(dni);
write('* Núm de empleado: '); readln(nro);
writeln('');
end;
end;
End;
procedure cargarArchivo(var emp: archivoDeEmpleados);
var
e: empleado;
nombreFisico: string[15];
begin
writeln();
write('* Nombre físico del archivo: '); readln(nombreFisico);
assign(emp, nombreFisico);
writeln('----------------------------------------------------------');
writeln(' Comenzando la carga del archivo ', nombreFisico);
writeln('----------------------------------------------------------');
rewrite(emp);
leer(e);
while (e.apellido <> corte) do begin
write(emp,e);
leer(e);
end;
close(emp);
Clrscr;
End;
procedure mostrar(e: empleado);
begin
writeln('* Nombre: ',e.nombre,' ',e.apellido,', DNI: ',e.dni,', edad: ',e.edad,', Nro: ',e.nro);
End;
//i. Listar en pantalla los datos de empleados que tengan un nombre o apellido determinado.
procedure mostrarXNomAp(var emp: archivoDeEmpleados);
var
e: empleado;
nombre: string;
begin
writeln('');
write('* Nombre a buscar: ');readln(nombre);
writeln();
writeln('------ EMPLEADOS CON EL NOMBRE / APELLIDO ', nombre,' ------');
writeln();
reset(emp);
while (not eof(emp)) do begin
read(emp, e);
if (e.apellido = nombre) or (e.nombre = nombre) then
mostrar(e);
end;
close(emp);
End;
//Listar en pantalla los empleados de a uno por línea.
procedure mostrarEmplados(var emp: archivoDeEmpleados);
var
e: empleado;
begin
writeln();
writeln('------------ LISTA DE EMPLEADOS -------------');
writeln();
reset(emp);
while(not eof(emp)) do begin
read(emp,e);
mostrar(e);
end;
close(emp);
End;
procedure mostrarProxAJubilarse(var emp: archivoDeEmpleados);
var
e: empleado;
begin
writeln();
writeln('----------- EMPLEADOS PRÓXIMOS A JUBILARSE -----------');
writeln();
reset(emp);
while(not eof(emp)) do begin
read(emp,e);
if (e.edad >= max) then
mostrar(e);
end;
close(emp);
End;
//a. Añadir una o más empleados al final del archivo con sus datos ingresados por teclado.
procedure agregarInformacion(var ade: archivoDeEmpleados);
var
emp: empleado;
begin
reset(ade);
seek(ade , filesize(ade));
leer(emp);
while(emp.apellido <> corte) do begin
write(ade, emp);
leer(emp);
end;
close(ade);
End;
//b. Modificar edad a una o más empleados.
procedure modificarEdad(var ade: archivoDeEmpleados);
var
emp: empleado;
num: integer;
age: integer;
ok: boolean;
begin
ok:= false;
write('* Numero del empleado: '); readln(num);
reset(ade);
while (num <> -1) do begin
while (not eof(ade)) and (not ok) do begin
read(ade, emp);
if(emp.nro = num) then begin
ok := true;
write('* Actualizar Edad con: '); readln(age);
emp.edad := age;
end;
seek(ade, filepos(ade)-1);
write(ade,emp);
end;
write('* Número del empleado al que desea modificar edad: '); readln(num);
write('* Actualizar edad con: '); readln(age);
end;
close(ade);
End;
//c. Exportar el contenido del archivo a un archivo de texto llamado “todos_empleados.txt”.
procedure exportarATxt(var ade: archivoDeEmpleados);
var
archTxt: string;
cargaTxt: Text;
emp: empleado;
begin
archTxt:='todos_empleados.txt';
assign(cargaTxt, archTxt);
rewrite(cargaTxt);
reset(ade);
while(not eof(ade)) do begin
read(ade, emp);
with emp do
writeln(nro:5, apellido:5, nombre:5, edad:5, dni:5);
with emp do
writeln(cargaTxt,nro, '', apellido, '', nombre,'', edad, '', dni); //archivo de txt + campos
end;
close(cargaTxt);
close(ade);
End;
//Exportar a un archivo de texto llamado: “faltaDNIEmpleado.txt”, los empleados que no tengan cargado el DNI (DNI en 00).
procedure exportarFaltaDni(var ade: archivoDeEmpleados);
var
archTxt: string;
cargaTxt: Text;
emp: empleado;
begin
archTxt:='faltaDNIEmpleado.txt';
assign(cargaTxt, archTxt);
rewrite(cargaTxt);
reset(ade);
while(not eof(ade)) do begin
read(ade, emp);
if (emp.dni = 00) then begin
with emp do
writeln(nro:5, apellido:5, nombre:5, edad:5, dni:5);
with emp do
writeln(cargaTxt,nro, '', apellido, '', nombre,'', edad, '', dni);
end;
end;
close(cargaTxt);
close(ade);
End;
//----------------------------------------------------------------------
procedure leerArchivo(var a: archivoDeEmpleados; var e: empleado);
begin
if (not eof(a)) then
read(a,e)
else
e.nombre := 'zzz';
End;
//----------------------------------------------------------------------
procedure bajas(var a: archivoDeEmpleados);
var
nombreFisico: string[15];
r, aux: empleado;
codigo: integer;
begin
reset(a);
write('* Código del empleado que quiere dar de baja: '); readln(codigo);
read(a,r);
if (r.nro <> codigo) then begin
seek(a,0);
leerArchivo(a, aux);
end;
while(aux.nro <> valorAlto) and (aux.nro <> codigo) do
leerArchivo(a,e);
leerArchivo(a,e);
if(aux.nro = codigo) then begin
seek(a, filepos(a) -1);
write(a,r);
seek(a, filesize(a)-1);
truncate(a);
end
else begin
seek(a, filesize(a)-1);
truncate(a);
end;
close(a);
End;
//----------------------------------------------------------------------
procedure menu(var boton: integer);
begin
writeln('------------------------------');
writeln(' MENÚ ');
writeln('------------------------------');
writeln();
Writeln(' - Ingrese la opción que desea - ');
writeln();
writeln('* 1_ Crear un nuevo Archivo de Empleados.');
writeln();
writeln('* 2_ Mostrar los datos de un Empleado.');
writeln();
writeln('* 3_ Mostrar la lista de todos los Empleados.');
writeln();
writeln('* 4_ Mostrar los empelados mayores de 70 años próximos a jubilarse.');
writeln();
writeln('* 5_ Agregar 1 o más empleados al archivo. Ingrese - fin - para finalizar la carga.');
writeln();
writeln('* 6_ Modificar la edad de uno o más empleados. Ingrese - fin - para finalizar.');
writeln();
writeln('* 7_ Exportar un archivo a texto.');
writeln();
writeln('* 8_ Exportar archivos de empleados con DNI 00 (DNI inexistente)');
writeln();
writeln('* 9_ Dar de baja a un empelado.');
writeln();
writeln('* 0_ Salir del menú.');
readln(boton);
ClrScr;
End;
VAR
empleados: archivoDeEmpleados;
boton: integer;
BEGIN
write('* Nombre físico del archivo: '); readln(nombreFisico);
assign(empleados, nombreFisico);
cargarArchivo(empleados);
menu(boton);
while (boton <> 0) do begin
case boton of
1: cargarArchivo(empleados);
2: mostrarXNomAp(empleados);
3: mostrarEmplados(empleados);
4: mostrarProxAJubilarse(empleados);
5: agregarInformacion(empleados);
6: modificarEdad(empleados);
7: exportarATxt(empleados);
8: exportarFaltaDni(empleados);
9: bajas(empleados);
else
writeln('*** OPCIÓN INVÁLIDA ****');
end;
menu(boton);
end;
END.
|
unit Base64Tests;
interface
uses
System.NetEncoding, System.SysUtils, DunitX.TestFramework, BaseTests, uBase64;
type
IBase64Tests = interface
['{0CCE92C0-A9CD-46B3-8181-40FF57149B36}']
end;
[TestFixture]
TBase64Tests = class(TBaseNcodingTests, IBase64Tests)
strict private
class function Helper(const InString: String): String; static;
public
[TestCase('Base64SampleStringTestCalcAgainstDefault',
TBaseNcodingTests.Base64SampleString)]
[TestCase('RusStringSampleStringTestCalcAgainstDefault',
TBaseNcodingTests.RusString)]
[TestCase('GreekStringSampleStringTestCalcAgainstDefault',
TBaseNcodingTests.GreekString)]
procedure Base64CompareToStandard(const str: String);
[Setup]
procedure Setup;
end;
implementation
procedure TBase64Tests.Setup;
begin
FConverter := TBase64.Create();
end;
procedure TBase64Tests.Base64CompareToStandard(const str: String);
var
encoded, base64standard: String;
begin
encoded := FConverter.EncodeString(str);
base64standard := Helper(str);
base64standard := StringReplace(base64standard, sLineBreak, '',
[rfReplaceAll]);
Assert.AreEqual(base64standard, encoded);
end;
class function TBase64Tests.Helper(const InString: String): String;
var
temp: TArray<Byte>;
begin
temp := TEncoding.UTF8.GetBytes(InString);
result := TNetEncoding.Base64.EncodeBytesToString(temp);
end;
initialization
TDUnitX.RegisterTestFixture(TBase64Tests);
end.
|
{ *********************************************************** }
{ * ksTools Library * }
{ * Copyright (c) Sergey Kasandrov 1997, 2010 * }
{ * ----------------------------------------- * }
{ * http://sergworks.wordpress.com/kstools * }
{ *********************************************************** }
unit ksZCrypt;
interface
uses
SysUtils, Windows, Classes, ksUtils, ksClasses;
type
TksZipCrypto = record
public type
THeader = packed array[0..11] of Byte;
private
FKeys: packed array [0..2] of LongWord;
function CryptoByte: Byte;
procedure UpdateKeys(B: Byte);
public
function DecodeByte(B: Byte): Byte;
function EncodeByte(B: Byte): Byte;
procedure Decode(var Data; Count: Integer);
procedure Encode(var Data; Count: Integer);
procedure Init(const Password: TBytes);
function CheckHeader(const Header: TksZipCrypto.THeader;
const Password: TBytes; CRC: LongWord; CheckSize: Byte): Boolean;
procedure InitHeader(var Header: TksZipCrypto.THeader;
const Password: TBytes; CRC: LongWord; CheckSize: Byte);
end;
implementation
{
TksZipCrypto implements traditional PKWARE encryption algorithm;
to encrypt data according to PKZIP 2.0 specification:
- calculate CRC32 of data to be encrypted;
- initialize 12-byte encryption header using Password and
calculated CRC32 value by calling TksZipCrypto.InitHeader;
this method also initializes keys needed for encryption;
- encrypt data by calling TksZipCrypto.Encode;
to decrypt data according to PKZIP 2.0 specification:
- make sure encryption header corresponds to Password and CRC32
by calling TksZipCrypto.CheckHeader;
this method also initializes keys needed for decryption;
- decrypt data by calling TksZipCrypto.Decode;
A test version of encryption/decryption (without using
encryption header and CRC32) can be implemented as follows:
to encrypt data you must:
- initialize keys by password (call TksZipCrypto.Init);
- encrypt data by calling TksZipCrypto.Encode;
to decrypt data you must:
- initialize keys by password (call TksZipCrypto.Init);
- decrypt data by calling TksZipCrypto.Decode;
see also ZipEncryptStream/ZipDecryptStream code as example
}
{ FROM APPNOTE.TXT Version 6.2.0:
XII. Traditional PKWARE Encryption
----------------------------------
The following information discusses the decryption steps
required to support traditional PKWARE encryption. This
form of encryption is considered weak by today's standards
and its use is recommended only for situations with
low security needs or for compatibility with older .ZIP
applications.
XIII. Decryption
----------------
The encryption used in PKZIP was generously supplied by Roger
Schlafly. PKWARE is grateful to Mr. Schlafly for his expert
help and advice in the field of data encryption.
PKZIP encrypts the compressed data stream. Encrypted files must
be decrypted before they can be extracted.
Each encrypted file has an extra 12 bytes stored at the start of
the data area defining the encryption header for that file. The
encryption header is originally set to random values, and then
itself encrypted, using three, 32-bit keys. The key values are
initialized using the supplied encryption password. After each byte
is encrypted, the keys are then updated using pseudo-random number
generation techniques in combination with the same CRC-32 algorithm
used in PKZIP and described elsewhere in this document.
The following is the basic steps required to decrypt a file:
1) Initialize the three 32-bit keys with the password.
2) Read and decrypt the 12-byte encryption header, further
initializing the encryption keys.
3) Read and decrypt the compressed data stream using the
encryption keys.
Step 1 - Initializing the encryption keys
-----------------------------------------
Key(0) <- 305419896
Key(1) <- 591751049
Key(2) <- 878082192
loop for i <- 0 to length(password)-1
update_keys(password(i))
end loop
Where update_keys() is defined as:
update_keys(char):
Key(0) <- crc32(key(0),char)
Key(1) <- Key(1) + (Key(0) & 000000ffH)
Key(1) <- Key(1) * 134775813 + 1
Key(2) <- crc32(key(2),key(1) >> 24)
end update_keys
Where crc32(old_crc,char) is a routine that given a CRC value and a
character, returns an updated CRC value after applying the CRC-32
algorithm described elsewhere in this document.
Step 2 - Decrypting the encryption header
-----------------------------------------
The purpose of this step is to further initialize the encryption
keys, based on random data, to render a plaintext attack on the
data ineffective.
Read the 12-byte encryption header into Buffer, in locations
Buffer(0) thru Buffer(11).
loop for i <- 0 to 11
C <- buffer(i) ^ decrypt_byte()
update_keys(C)
buffer(i) <- C
end loop
Where decrypt_byte() is defined as:
unsigned char decrypt_byte()
local unsigned short temp
temp <- Key(2) | 2
decrypt_byte <- (temp * (temp ^ 1)) >> 8
end decrypt_byte
After the header is decrypted, the last 1 or 2 bytes in Buffer
should be the high-order word/byte of the CRC for the file being
decrypted, stored in Intel low-byte/high-byte order, or the high-order
byte of the file time if bit 3 of the general purpose bit flag is set.
Versions of PKZIP prior to 2.0 used a 2 byte CRC check; a 1 byte CRC check is
used on versions after 2.0. This can be used to test if the password
supplied is correct or not.
Step 3 - Decrypting the compressed data stream
----------------------------------------------
The compressed data stream can be decrypted as follows:
loop until done
read a character into C
Temp <- C ^ decrypt_byte()
update_keys(temp)
output Temp
end loop
}
const
ZipKey0 = 305419896;
ZipKey1 = 591751049;
ZipKey2 = 878082192;
ZipMagicNumber = 134775813;
type
TByteArray = packed array [0..$3FFFFFFF] of Byte;
TBytes4 = packed array [0..3] of Byte;
function TksZipCrypto.CryptoByte: Byte;
var
Temp: Word;
begin
Temp:= Word(FKeys[2]) or 2;
Result:= (Temp * (Temp xor 1)) shr 8;
end;
function TksZipCrypto.DecodeByte(B: Byte): Byte;
begin
Result:= B xor CryptoByte;
UpdateKeys(Result);
end;
procedure TksZipCrypto.Decode(var Data; Count: Integer);
var
I: Integer;
begin
for I:= 0 to Pred(Count) do begin
TByteArray(Data)[I]:= TByteArray(Data)[I] xor CryptoByte;
UpdateKeys(TByteArray(Data)[I]);
end;
end;
function TksZipCrypto.EncodeByte(B: Byte): Byte;
begin
Result:= B xor CryptoByte;
UpdateKeys(B);
end;
procedure TksZipCrypto.Encode(var Data; Count: Integer);
var
I: Integer;
J: Byte;
begin
for I:= 0 to Pred(Count) do begin
J:= CryptoByte;
UpdateKeys(TByteArray(Data)[I]);
TByteArray(Data)[I]:= TByteArray(Data)[I] xor J;
end;
end;
procedure TksZipCrypto.Init(const Password: TBytes);
var
I: Integer;
begin
FKeys[0]:= ZipKey0;
FKeys[1]:= ZipKey1;
FKeys[2]:= ZipKey2;
for I:= 0 to Length(Password) - 1 do UpdateKeys(Ord(Password[I]));
end;
procedure TksZipCrypto.UpdateKeys(B: Byte);
begin
FKeys[0]:= Crc32OfByte(B, FKeys[0]);
FKeys[1]:= FKeys[1] + (FKeys[0] and $FF);
FKeys[1]:= (FKeys[1] * ZipMagicNumber) + 1;
FKeys[2]:= Crc32OfByte(FKeys[1] shr 24, FKeys[2]);
end;
function TksZipCrypto.CheckHeader(const Header: TksZipCrypto.THeader;
const Password: TBytes; CRC: LongWord; CheckSize: Byte): Boolean;
var
LHeader: TksZipCrypto.THeader;
begin
Init(Password);
LHeader:= Header;
Decode(LHeader, 12);
if CheckSize = 1 then // version 2.0 or better
Result:= (LHeader[11] = TBytes4(CRC)[3])
else if CheckSize = 2 then // prior to version 2.0
Result:= (LHeader[11] = TBytes4(CRC)[3]) and
(LHeader[10] = TBytes4(CRC)[2])
else begin // not used by zip archive
Result:= True;
Exit;
end;
end;
procedure TksZipCrypto.InitHeader(var Header: TksZipCrypto.THeader;
const Password: TBytes; CRC: LongWord; CheckSize: Byte);
var
N: Integer;
B: Byte;
T: Word;
begin
Init(Password); // initialize Header[0..9]
for N:= 0 to 9 do begin // with random values
B:= Random(256);
T:= CryptoByte;
UpdateKeys(B);
Header[N]:= T xor B;
end;
// Header[10..11] = CRC32 higher word
if CheckSize = 2 then begin
Header[10]:= TBytes4(CRC)[2];
end
else begin
Header[10]:= Random(256);
end;
Header[11]:= TBytes4(CRC)[3];
Init(Password); // encrypt Header
Encode(Header, 12)
end;
initialization
Randomize;
end.
|
unit ShtDwnU;
interface
uses
Windows;
procedure DoRestart;
procedure DoShutdown;
implementation
type
TRestartMode = (rmRestart, rmShutdown);
procedure RestartProcedure(const ARestartMode : TRestartMode); forward;
procedure RestartProcedure(const ARestartMode : TRestartMode);
function ExWindows(AFlag : LongInt) : Boolean;
var
Number : LongWord;
TokenPrivileges : TTokenPrivileges;
VersionInfo : TOSVersionInfo;
WindowsHandle : THandle;
begin
Result := false;
VersionInfo.dwOSVersionInfoSize := SizeOf(VersionInfo);
GetVersionEx(VersionInfo);
if (VersionInfo.dwPlatformId = VER_PLATFORM_WIN32_NT) then
begin
// Windows NT
OpenProcessToken(GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES, WindowsHandle);
LookupPrivilegeValue(nil, 'SeShutdownPrivilege', TokenPrivileges.Privileges[0].Luid);
TokenPrivileges.PrivilegeCount := 1;
TokenPrivileges.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;
Number := 0;
AdjustTokenPrivileges(WindowsHandle, false, TokenPrivileges, 0, PTokenPrivileges(nil)^, Number);
CloseHandle(WindowsHandle);
Result := ExitWindowsEx(AFlag, 0);
end
else
begin // Windows 95
Result := ExitWindowsEx(AFlag, 0);
end;
end;
begin
if (ARestartMode = rmRestart) then
ExWindows(EWX_REBOOT + EWX_FORCEIFHUNG)
else
begin
if (ARestartMode = rmShutdown) then
ExWindows(EWX_SHUTDOWN + EWX_FORCEIFHUNG + EWX_POWEROFF);
end;
end;
procedure DoRestart;
begin
RestartProcedure(rmRestart);
end;
procedure DoShutdown;
begin
RestartProcedure(rmShutdown);
end;
end.
|
// ************************************************************************ //
// The types declared in this file were generated from data read from the
// WSDL File described below:
// WSDL : http://localhost:8888/wsdl/ITxRxCh1WS
// Encoding : utf-8
// Version : 1.0
// (3/30/2012 11:44:04 AM - 1.33.2.5)
// ************************************************************************ //
unit ITxRxCh1Proxy;
interface
uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns;
type
// ************************************************************************ //
// The following types, referred to in the WSDL document are not being represented
// in this file. They are either aliases[@] of other types represented or were referred
// to but never[!] declared in the document. The types from the latter category
// typically map to predefined/known XML or Borland types; however, they could also
// indicate incorrect WSDL documents that failed to declare or import a schema type.
// ************************************************************************ //
// !:boolean - "http://www.w3.org/2001/XMLSchema"
// !:double - "http://www.w3.org/2001/XMLSchema"
// !:long - "http://www.w3.org/2001/XMLSchema"
// !:int - "http://www.w3.org/2001/XMLSchema"
{ "urn:CommunicationObj" }
RadarStatusEnum = (rsOff, rsFailure, rsOk);
{ "urn:CommunicationObj" }
TxPulseEnum = (tx_Pulse_Long, tx_Pulse_Short, tx_Pulse_None, tx_Pulse_Dual);
{ "urn:CommunicationObj" }
TWaveLengthEnum = (wl_3cm, wl_10cm);
// ************************************************************************ //
// Namespace : urn:TxRxCh1WSIntf-ITxRxCh1WS
// soapAction: urn:TxRxCh1WSIntf-ITxRxCh1WS#%operationName%
// transport : http://schemas.xmlsoap.org/soap/http
// style : rpc
// binding : ITxRxCh1WSbinding
// service : ITxRxCh1WSservice
// port : ITxRxCh1WSPort
// URL : http://localhost:8888/soap/ITxRxCh1WS
// ************************************************************************ //
ITxRxCh1WS = interface(IInvokable)
['{4CEDA6BD-6D98-EE7A-4EBF-F07F6854CEA0}']
function Get_Tx_Status: RadarStatusEnum; stdcall;
function Get_Encendido: Boolean; stdcall;
function Get_HV: Boolean; stdcall;
function Get_Listo: Boolean; stdcall;
function Get_Inter_Lock: Boolean; stdcall;
function Get_Ventilacion: Boolean; stdcall;
function Get_Averia: Boolean; stdcall;
function Get_Averia_MPS: Boolean; stdcall;
function Get_Averia_Ventilador: Boolean; stdcall;
function Get_Averia_Fuente_Filamento: Boolean; stdcall;
function Get_Local: Boolean; stdcall;
function Get_Fuente_5V_N: Boolean; stdcall;
function Get_Fuente_5V_P: Boolean; stdcall;
function Get_Fuente_15V_N: Boolean; stdcall;
function Get_Fuente_15V_P: Boolean; stdcall;
function Get_Stalo_Locked: Boolean; stdcall;
function Get_Rx_Status: RadarStatusEnum; stdcall;
function Get_DRX_Ready: Boolean; stdcall;
function Get_Stalo_Temperature: Double; stdcall;
function Get_Stalo_Power: Double; stdcall;
function Get_Stalo_Frequency: Int64; stdcall;
function Get_Stalo_ExtRef: Boolean; stdcall;
function Get_Stalo_Ref_Unlocked: Boolean; stdcall;
function Get_Stalo_RF_Unlocked: Boolean; stdcall;
function Get_Stalo_RF_Output: Boolean; stdcall;
function Get_Stalo_VoltageError: Boolean; stdcall;
function Get_Stalo_Ref_Output: Boolean; stdcall;
function Get_Stalo_Blanking: Boolean; stdcall;
function Get_Stalo_LockRecovery: Boolean; stdcall;
function Get_AFC_Status: Boolean; stdcall;
function Get_Tx_Frequency: Int64; stdcall;
function Get_Tx_IF: Int64; stdcall;
function Get_Tx_PulsePower: Double; stdcall;
function Get_NCO_Frequency: Int64; stdcall;
procedure StartAcquiring; stdcall;
function Get_Potencia_Code: Integer; stdcall;
function Get_Potencia_Unit: Double; stdcall;
function Get_MPS_Volt_Code: Integer; stdcall;
function Get_MPS_Volt_Unit: Double; stdcall;
function Get_MPS_Corr_Code: Integer; stdcall;
function Get_MPS_Corr_Unit: Double; stdcall;
function Get_Fuente_24VN_Code: Integer; stdcall;
function Get_Fuente_24VN_Unit: Double; stdcall;
function Get_Fuente_24VP_Code: Integer; stdcall;
function Get_Fuente_24VP_Unit: Double; stdcall;
function Get_Fuente_50V_Code: Integer; stdcall;
function Get_Fuente_50V_Unit: Double; stdcall;
function Get_Fuente_100V_Code: Integer; stdcall;
function Get_Fuente_100V_Unit: Double; stdcall;
function Get_Fuente_400V_Code: Integer; stdcall;
function Get_Fuente_400V_Unit: Double; stdcall;
function Get_Fuente_Filamento_Code: Integer; stdcall;
function Get_Fuente_Filamento_Unit: Double; stdcall;
function Get_Tx_Pulso: TxPulseEnum; stdcall;
function Get_Numero: Integer; stdcall;
function Get_Longitud_Onda: TWaveLengthEnum; stdcall;
procedure Tx_Encender; stdcall;
procedure Tx_Apagar; stdcall;
procedure Set_HV(const Value: Boolean); stdcall;
procedure Rx_Encender; stdcall;
procedure Rx_Apagar; stdcall;
procedure Set_Stalo_Freq(const Value: Int64); stdcall;
procedure Set_Stalo_Power(const Value: Double); stdcall;
procedure Stalo_Reset; stdcall;
procedure Set_AFC_Status(const Value: Boolean); stdcall;
procedure Set_Stalo_Output(const Value: Boolean); stdcall;
procedure Stalo_Update; stdcall;
procedure Set_NCO_Frequency(const Value: Int64); stdcall;
function Get_Rango_Tx_Potencia: Integer; stdcall;
function Get_Sector_Tx_Potencia: Integer; stdcall;
function Get_Rango_Tx_MPS_Volt: Integer; stdcall;
function Get_Rango_Tx_MPS_Corr: Integer; stdcall;
function Get_Rango_Tx_Fuente24V_N: Integer; stdcall;
function Get_Rango_Tx_Fuente24V_P: Integer; stdcall;
function Get_Rango_Tx_Fuente50V: Integer; stdcall;
function Get_Rango_Tx_Fuente400V: Integer; stdcall;
function Get_Rango_Tx_Fuente_Filamento: Integer; stdcall;
function Get_Rango_Tx_Fuente100V: Integer; stdcall;
function Get_Sector_Tx_MPS_Volt: Integer; stdcall;
function Get_Sector_Tx_MPS_Corr: Integer; stdcall;
function Get_Sector_Tx_Fuente24V_N: Integer; stdcall;
function Get_Sector_Tx_Fuente24V_P: Integer; stdcall;
function Get_Sector_Tx_Fuente50V: Integer; stdcall;
function Get_Sector_Tx_Fuente100V: Integer; stdcall;
function Get_Sector_Tx_Fuente400V: Integer; stdcall;
function Get_Sector_Tx_Fuente_Filamento: Integer; stdcall;
procedure Set_Rango_Tx_Potencia(const Value: Integer); stdcall;
procedure Set_Sector_Tx_Potencia(const Value: Integer); stdcall;
procedure Set_Rango_Tx_MPS_Volt(const Value: Integer); stdcall;
procedure Set_Rango_Tx_MPS_Corr(const Value: Integer); stdcall;
procedure Set_Rango_Tx_Fuente24V_N(const Value: Integer); stdcall;
procedure Set_Rango_Tx_Fuente24V_P(const Value: Integer); stdcall;
procedure Set_Rango_Tx_Fuente50V(const Value: Integer); stdcall;
procedure Set_Rango_Tx_Fuente100V(const Value: Integer); stdcall;
procedure Set_Rango_Tx_Fuente400V(const Value: Integer); stdcall;
procedure Set_Rango_Tx_Fuente_Filamento(const Value: Integer); stdcall;
procedure Set_Sector_Tx_MPS_Volt(const Value: Integer); stdcall;
procedure Set_Sector_Tx_MPS_Corr(const Value: Integer); stdcall;
procedure Set_Sector_Tx_Fuente24V_N(const Value: Integer); stdcall;
procedure Set_Sector_Tx_Fuente24V_P(const Value: Integer); stdcall;
procedure Set_Sector_Tx_Fuente50V(const Value: Integer); stdcall;
procedure Set_Sector_Tx_Fuente100V(const Value: Integer); stdcall;
procedure Set_Sector_Tx_Fuente400V(const Value: Integer); stdcall;
procedure Set_Sector_Tx_Fuente_Filamento(const Value: Integer); stdcall;
end;
function GetITxRxCh1WS(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): ITxRxCh1WS;
implementation
function GetITxRxCh1WS(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): ITxRxCh1WS;
const
defWSDL = 'http://localhost:8888/wsdl/ITxRxCh1WS';
defURL = 'http://localhost:8888/soap/ITxRxCh1WS';
defSvc = 'ITxRxCh1WSservice';
defPrt = 'ITxRxCh1WSPort';
var
RIO: THTTPRIO;
begin
Result := nil;
if (Addr = '') then
begin
if UseWSDL then
Addr := defWSDL
else
Addr := defURL;
end;
if HTTPRIO = nil then
RIO := THTTPRIO.Create(nil)
else
RIO := HTTPRIO;
try
Result := (RIO as ITxRxCh1WS);
if UseWSDL then
begin
RIO.WSDLLocation := Addr;
RIO.Service := defSvc;
RIO.Port := defPrt;
end else
RIO.URL := Addr;
finally
if (Result = nil) and (HTTPRIO = nil) then
RIO.Free;
end;
end;
initialization
InvRegistry.RegisterInterface(TypeInfo(ITxRxCh1WS), 'urn:TxRxCh1WSIntf-ITxRxCh1WS', 'utf-8');
InvRegistry.RegisterDefaultSOAPAction(TypeInfo(ITxRxCh1WS), 'urn:TxRxCh1WSIntf-ITxRxCh1WS#%operationName%');
RemClassRegistry.RegisterXSInfo(TypeInfo(RadarStatusEnum), 'urn:CommunicationObj', 'RadarStatusEnum');
RemClassRegistry.RegisterXSInfo(TypeInfo(TxPulseEnum), 'urn:CommunicationObj', 'TxPulseEnum');
RemClassRegistry.RegisterXSInfo(TypeInfo(TWaveLengthEnum), 'urn:CommunicationObj', 'TWaveLengthEnum');
end. |
//************************************************************************
//
// Program Name : AT Library
// Platform(s) : Android, iOS, Linux, MacOS, Windows
// Framework : Console, FMX, VCL
//
// Filename : AT.Config.Storage.Custom.pas
// Date Created : 01-AUG-2014
// Author : Matthew Vesperman
//
// Description:
//
// Custom config storage class.
//
// Revision History:
//
// v1.00 : Initial version
// v1.10 : Added DeleteSection method
// v1.20 : Changed base class to TInterfacedPersistent (08-Apr-2018)
//
//************************************************************************
//
// COPYRIGHT © 2014 Angelic Technology
// ALL RIGHTS RESERVED WORLDWIDE
//
//************************************************************************
/// <summary>
/// Custom configuration storage class.
/// </summary>
unit AT.Config.Storage.Custom;
interface
uses
System.Classes;
type
TATCustomConfigStorage = class(TInterfacedPersistent)
strict private
FCanCreateSection: Boolean;
FDefaultBoolean: Boolean;
FDefaultCurrency: Currency;
FDefaultDate: TDateTime;
FDefaultDateTime: TDateTime;
FDefaultDouble: Double;
FDefaultInteger: Integer;
FDefaultSection: string;
FDefaultString: string;
FDefaultTime: TDateTime;
FUpdating: Boolean;
strict protected
procedure BeginUpdate; virtual;
procedure EndUpdate; virtual;
function GetBooleanValues(Entry: String): Boolean; virtual;
function GetCurrencyValues(Entry: String): Currency; virtual;
function GetDates(Entry: String): TDateTime; virtual;
function GetDateTimeValues(Entry: String): TDateTime; virtual;
function GetDoubles(Entry: String): Double; virtual;
function GetIntegers(Entry: String): Integer; virtual;
function GetStrings(Entry: String): string; virtual;
function GetTimes(Entry: String): TDateTime; virtual;
procedure SetBooleanValues(Entry: String; Value: Boolean); virtual;
procedure SetCurrencyValues(Entry: String; Value: Currency); virtual;
procedure SetDates(Entry: String; Value: TDateTime); virtual;
procedure SetDateTimeValues(Entry: String; Value: TDateTime); virtual;
procedure SetDoubles(Entry: String; Value: Double); virtual;
procedure SetIntegers(Entry: String; Value: Integer); virtual;
procedure SetStrings(Entry: String; Value: string); virtual;
procedure SetTimes(Entry: String; Value: TDateTime); virtual;
property Updating: Boolean read FUpdating;
public
constructor Create; overload; virtual;
destructor Destroy; override;
procedure DeleteEntry(const sSection: String; const sEntry: String);
virtual; abstract;
procedure DeleteSection(const sSection: String); virtual; abstract;
function ReadBoolean(const sSection: String; const sEntry: String; const
bDefault: Boolean): Boolean; virtual; abstract;
function ReadCurrency(const sSection: String; const sEntry: String; const
cDefault: Currency): Currency; virtual; abstract;
function ReadDate(const sSection: String; const sEntry: String; const
dtDefault: TDateTime): TDateTime; virtual; abstract;
function ReadDateTime(const sSection: String; const sEntry: String; const
dtDefault: TDateTime): TDateTime; virtual; abstract;
function ReadDouble(const sSection: String; const sEntry: String; const
rDefault: Double): Double; virtual; abstract;
function ReadInteger(const sSection: String; const sEntry: String; const
iDefault: Integer): Integer; virtual; abstract;
function ReadString(const sSection, sEntry, sDefault: String): string; virtual;
abstract;
function ReadTime(const sSection: String; const sEntry: String; const
dtDefault: TDateTime): TDateTime; virtual; abstract;
procedure WriteBoolean(const sSection: String; const sEntry: String; const
bValue: Boolean); virtual; abstract;
procedure WriteCurrency(const sSection: String; const sEntry: String; const
cValue: Currency); virtual; abstract;
procedure WriteDate(const sSection: String; const sEntry: String; const
dtValue: TDateTime); virtual; abstract;
procedure WriteDateTime(const sSection: String; const sEntry: String; const
dtValue: TDateTime); virtual; abstract;
procedure WriteDouble(const sSection: String; const sEntry: String; const
rValue: Double); virtual; abstract;
procedure WriteInteger(const sSection: String; const sEntry: String; const
iValue: Integer); virtual; abstract;
procedure WriteString(const sSection: String; const sEntry: String; const
sValue: String); virtual; abstract;
procedure WriteTime(const sSection: String; const sEntry: String; const
dtValue: TDateTime); virtual; abstract;
property BooleanValues[Entry: String]: Boolean read GetBooleanValues write
SetBooleanValues;
property CurrencyValues[Entry: String]: Currency read GetCurrencyValues
write SetCurrencyValues;
property Dates[Entry: String]: TDateTime read GetDates write SetDates;
property DateTimeValues[Entry: String]: TDateTime read GetDateTimeValues
write SetDateTimeValues;
property Doubles[Entry: String]: Double read GetDoubles write SetDoubles;
property Integers[Entry: String]: Integer read GetIntegers write
SetIntegers;
property Strings[Entry: String]: string read GetStrings write SetStrings;
property Times[Entry: String]: TDateTime read GetTimes write SetTimes;
published
property CanCreateSection: Boolean read FCanCreateSection write
FCanCreateSection default True;
property DefaultBoolean: Boolean read FDefaultBoolean write FDefaultBoolean
default False;
property DefaultCurrency: Currency read FDefaultCurrency write
FDefaultCurrency;
property DefaultDate: TDateTime read FDefaultDate write FDefaultDate;
property DefaultDateTime: TDateTime read FDefaultDateTime write
FDefaultDateTime;
property DefaultDouble: Double read FDefaultDouble write FDefaultDouble;
property DefaultInteger: Integer read FDefaultInteger write FDefaultInteger
default 0;
property DefaultSection: string read FDefaultSection write FDefaultSection;
property DefaultString: string read FDefaultString write FDefaultString;
property DefaultTime: TDateTime read FDefaultTime write FDefaultTime;
end;
implementation
uses System.SysUtils;
{
**************************** TATCustomConfigStorage ****************************
}
constructor TATCustomConfigStorage.Create;
begin
inherited Create;
FCanCreateSection := True;
FDefaultBoolean := False;
FDefaultCurrency := 0.0;
FDefaultDate := Date;
FDefaultDateTime := Now;
FDefaultDouble := 0.0;
FDefaultInteger := 0;
FDefaultSection := '';
FDefaultString := '';
FDefaultTime := Time;
end;
destructor TATCustomConfigStorage.Destroy;
begin
inherited Destroy;
end;
procedure TATCustomConfigStorage.BeginUpdate;
begin
FUpdating := True;
end;
procedure TATCustomConfigStorage.EndUpdate;
begin
FUpdating := False;
end;
function TATCustomConfigStorage.GetBooleanValues(Entry: String): Boolean;
begin
Result := ReadBoolean(DefaultSection, Entry, DefaultBoolean);
end;
function TATCustomConfigStorage.GetCurrencyValues(Entry: String): Currency;
begin
Result := ReadCurrency(DefaultSection, Entry, DefaultCurrency);
end;
function TATCustomConfigStorage.GetDates(Entry: String): TDateTime;
begin
Result := ReadDate(DefaultSection, Entry, DefaultDate);
end;
function TATCustomConfigStorage.GetDateTimeValues(Entry: String): TDateTime;
begin
Result := ReadDateTime(DefaultSection, Entry, DefaultDateTime);
end;
function TATCustomConfigStorage.GetDoubles(Entry: String): Double;
begin
Result := ReadDouble(DefaultSection, Entry, DefaultDouble);
end;
function TATCustomConfigStorage.GetIntegers(Entry: String): Integer;
begin
Result := ReadInteger(DefaultSection, Entry, DefaultInteger);
end;
function TATCustomConfigStorage.GetStrings(Entry: String): string;
begin
Result := ReadString(DefaultSection, Entry, DefaultString);
end;
function TATCustomConfigStorage.GetTimes(Entry: String): TDateTime;
begin
Result := ReadTime(DefaultSection, Entry, DefaultTime);
end;
procedure TATCustomConfigStorage.SetBooleanValues(Entry: String; Value:
Boolean);
begin
WriteBoolean(DefaultSection, Entry, Value);
end;
procedure TATCustomConfigStorage.SetCurrencyValues(Entry: String; Value:
Currency);
begin
WriteCurrency(DefaultSection, Entry, Value);
end;
procedure TATCustomConfigStorage.SetDates(Entry: String; Value: TDateTime);
begin
WriteDate(DefaultSection, Entry, Value);
end;
procedure TATCustomConfigStorage.SetDateTimeValues(Entry: String; Value:
TDateTime);
begin
WriteDateTime(DefaultSection, Entry, Value);
end;
procedure TATCustomConfigStorage.SetDoubles(Entry: String; Value: Double);
begin
WriteDouble(DefaultSection, Entry, Value);
end;
procedure TATCustomConfigStorage.SetIntegers(Entry: String; Value: Integer);
begin
WriteInteger(DefaultSection, Entry, Value);
end;
procedure TATCustomConfigStorage.SetStrings(Entry: String; Value: string);
begin
WriteString(DefaultSection, Entry, Value);
end;
procedure TATCustomConfigStorage.SetTimes(Entry: String; Value: TDateTime);
begin
WriteTime(DefaultSection, Entry, Value);
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.