text stringlengths 14 6.51M |
|---|
//---------------------------------------------------------------------------
// This software is Copyright (c) 2015 Embarcadero Technologies, Inc.
// You may only use this software if you are an authorized licensee
// of an Embarcadero developer tools product.
// 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 fMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.StdCtrls,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf,
FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async,
FireDAC.Phys, FireDAC.Comp.Client, FireDAC.Stan.Param, FireDAC.DatS,
FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.VCLUI.Error,
FireDAC.Comp.UI, FireDAC.Moni.Base, FireDAC.Moni.FlatFile, FireDAC.VCLUI.Wait,
FireDAC.Phys.MongoDBCli, FireDAC.Phys.MongoDBWrapper, FireDAC.Phys.MongoDB,
FireDAC.Phys.MongoDBDef,
System.JSON.Types, System.JSON.BSON, System.JSON.Builders, System.Rtti,
System.JSON.Readers;
type
TfrmMain = class(TForm)
Memo1: TMemo;
btnInsert: TButton;
btnPing: TButton;
btnAggProj: TButton;
btnAggRedact: TButton;
btnInsFind: TButton;
btnListCols: TButton;
btnUpdInc: TButton;
btnUpdPush: TButton;
Button9: TButton;
btnIterate: TButton;
FDGUIxErrorDialog1: TFDGUIxErrorDialog;
FDConnection1: TFDConnection;
FDPhysMongoDriverLink1: TFDPhysMongoDriverLink;
btnCurrentOp: TButton;
FDMoniFlatFileClientLink1: TFDMoniFlatFileClientLink;
FDGUIxWaitCursor1: TFDGUIxWaitCursor;
procedure FormCreate(Sender: TObject);
procedure btnInsertClick(Sender: TObject);
procedure btnPingClick(Sender: TObject);
procedure btnAggProjClick(Sender: TObject);
procedure btnAggRedactClick(Sender: TObject);
procedure btnInsFindClick(Sender: TObject);
procedure btnListColsClick(Sender: TObject);
procedure btnUpdIncClick(Sender: TObject);
procedure btnUpdPushClick(Sender: TObject);
procedure Button9Click(Sender: TObject);
procedure btnIterateClick(Sender: TObject);
procedure btnCurrentOpClick(Sender: TObject);
private
FEnv: TMongoEnv;
FCon: TMongoConnection;
{ Private declarations }
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
procedure TfrmMain.FormCreate(Sender: TObject);
begin
// Connect to MongoDB and get CLI wrapping objects
FDConnection1.Connected := True;
FCon := TMongoConnection(FDConnection1.CliObj);
FEnv := FCon.Env;
end;
procedure TfrmMain.btnInsertClick(Sender: TObject);
var
oDoc: TMongoDocument;
oCrs: IMongoCursor;
begin
// For details see:
// https://docs.mongodb.org/getting-started/shell/insert/
oDoc := FEnv.NewDoc;
try
// Remove all documents from "restaurants" collection in "test" database
FCon['test']['restaurants'].RemoveAll;
// Build new document
oDoc
.BeginObject('address')
.Add('street', '2 Avenue')
.Add('zipcode', '10075')
.Add('building', '1480')
.BeginArray('coord')
.Add('0', -73.9557413)
.Add('1', 40.7720266)
.EndArray
.EndObject
.Add('borough', 'Manhattan')
.Add('cuisine', 'Italian')
.BeginArray('grades')
.BeginObject('0')
.Add('date', EncodeDate(2000, 5, 25))
.Add('grade', 'Add')
.Add('score', 11)
.EndObject
.BeginObject('1')
.Add('date', EncodeDate(2005, 6, 2))
.Add('grade', 'B')
.Add('score', 17)
.EndObject
.EndArray
.Add('name', 'Vella')
.Add('restaurant_id', '41704620');
// Insert new document into "restaurants" collection in "test" database.
// This may be done using "fluent" style.
FCon['test']['restaurants'].Insert(oDoc);
// Find, retrieve and show all documents
// The query condition may be build using "fluent" style.
oCrs := FCon['test']['restaurants'].Find();
while oCrs.Next do
Memo1.Text := Memo1.Text + #13#10 + oCrs.Doc.AsJSON;
// Get number of documents in the collection
Memo1.Text := Memo1.Text + #13#10'Record count ' +
FCon['test']['restaurants'].Count().Value().ToString();
finally
oDoc.Free;
end;
end;
procedure TfrmMain.btnPingClick(Sender: TObject);
begin
// Ping server and get server version
FCon.Ping;
Memo1.Text := IntToStr(FCon.ServerVersion);
end;
procedure TfrmMain.btnAggProjClick(Sender: TObject);
var
oDoc: TMongoDocument;
oCrs: IMongoCursor;
begin
// For details see:
// http://docs.mongodb.org/manual/reference/operator/aggregation/project/#include-computed-fields
oDoc := FEnv.NewDoc;
try
FCon['test']['books'].RemoveAll;
oDoc
.Add('_id', 1)
.Add('title', 'abc123')
.Add('isbn', '0001122223334')
.BeginObject('author')
.Add('last', 'zzz')
.Add('first', 'aaa')
.EndObject
.Add('copies', 5);
FCon['test']['books'].Insert(oDoc);
oCrs := FCon['test']['books']
.Aggregate()
.Project
.Field('title')
.FieldBegin('isbn')
.Exp('prefix', '{ "$substr": [ "$isbn", 0, 3 ] }')
.Exp('group', '{ "$substr": [ "$isbn", 3, 2 ] }')
.Exp('publisher', '{ "$substr": [ "$isbn", 5, 4 ] }')
.Exp('title', '{ "$substr": [ "$isbn", 9, 3 ] }')
.Exp('checkDigit', '{ "$substr": [ "$isbn", 12, 1] }')
.FieldEnd
.Exp('lastName', '"$author.last"')
.Exp('copiesSold', '"$copies"')
.&End
.Match
.Exp('copiesSold', '{ "$gt" : 4, "$lte" : 6 }')
.&End;
while oCrs.Next do
Memo1.Text := Memo1.Text + #13#10 + oCrs.Doc.AsJSON;
finally
oDoc.Free;
end;
end;
procedure TfrmMain.btnAggRedactClick(Sender: TObject);
var
oDoc: TMongoDocument;
oCrs: IMongoCursor;
begin
// For details see:
// http://docs.mongodb.org/manual/reference/operator/aggregation/redact/
oDoc := FEnv.NewDoc;
try
FCon['test']['forecasts'].RemoveAll;
oDoc
.Add('_id', 1)
.Add('title', '123 Department Report')
.BeginArray('tags')
.Add('0', 'G')
.Add('1', 'STLW')
.EndArray
.Add('year', 2014)
.BeginArray('subsections')
.BeginObject('0')
.Add('subtitle', 'Section 1: Overview')
.BeginArray('tags')
.Add('0', 'SI')
.Add('1', 'G')
.EndArray
.Add('content', 'Section 1: This is the content of section 1.')
.EndObject
.BeginObject('1')
.Add('subtitle', 'Section 2: Analysis')
.BeginArray('tags')
.Add('0', 'STLW')
.EndArray
.Add('content', 'Section 2: This is the content of section 2.')
.EndObject
.BeginObject('2')
.Add('subtitle', 'Section 3: Budgeting')
.BeginArray('tags')
.Add('0', 'TK')
.EndArray
.BeginObject('content')
.Add('text', 'Section 3: This is the content of section3.')
.BeginArray('tags')
.Add('0', 'HCS')
.EndArray
.EndObject
.EndObject
.EndArray;
FCon['test']['forecasts'].Insert(oDoc);
oCrs := FCon['test']['forecasts']
.Aggregate()
.Match
.Exp('year', '2014')
.&End
.Redact
.BeginObject('$cond')
.BeginObject('if')
.BeginArray('$gt')
.BeginObject('0')
.BeginObject('$size')
.BeginArray('$setIntersection')
.Add('0', '$tags')
.BeginArray('1')
.Add('0', 'STLW')
.Add('1', 'G')
.EndArray
.EndArray
.EndObject
.EndObject
.Add('1', 0)
.EndArray
.EndObject
.Add('then', '$$DESCEND')
.Add('else', '$$PRUNE')
.EndObject
.&End;
while oCrs.Next do
Memo1.Text := Memo1.Text + #13#10 + oCrs.Doc.AsJSON;
finally
oDoc.Free;
end;
end;
procedure TfrmMain.btnInsFindClick(Sender: TObject);
var
oDoc: TMongoDocument;
oCrs: IMongoCursor;
i: Integer;
begin
// For details see:
// http://docs.mongodb.org/manual/reference/operator/query/
// http://docs.mongodb.org/manual/reference/operator/query-modifier/
oDoc := FEnv.NewDoc;
try
FCon['test']['perf_test'].RemoveAll;
for i := 1 to 100 do begin
oDoc
.Clear
.Add('f1', i div 10)
.Add('f2', i mod 10)
.Add('f3', 'str' + IntToStr(i));
FCon['test']['perf_test'].Insert(oDoc);
end;
oCrs := FCon['test']['perf_test']
.Find()
.Match
.BeginObject('f1')
.Add('$gt', 5)
.EndObject
.&End
.Sort
.Field('f1', False)
.Field('f2', True)
.&End
.Limit(5);
while oCrs.Next do
Memo1.Text := Memo1.Text + #13#10 + oCrs.Doc.AsJSON;
finally
oDoc.Free;
end;
end;
procedure TfrmMain.btnListColsClick(Sender: TObject);
var
oCrs: IMongoCursor;
begin
// For details see:
// http://docs.mongodb.org/manual/reference/command/listCollections/
oCrs := FCon['test'].ListCollections();
while oCrs.Next do
Memo1.Text := Memo1.Text + #13#10 + oCrs.Doc.AsJSON;
end;
procedure TfrmMain.btnUpdIncClick(Sender: TObject);
var
oDoc: TMongoDocument;
oCrs: IMongoCursor;
begin
// For details see:
// http://docs.mongodb.org/manual/reference/operator/update/inc/
oDoc := FEnv.NewDoc;
try
FCon['test']['products'].RemoveAll;
oDoc
.Add('_id', 1)
.Add('sku', 'abc123')
.Add('quantity', 10)
.BeginObject('metrics')
.Add('orders', 2)
.Add('ratings', 3.5)
.EndObject;
FCon['test']['products'].Insert(oDoc);
FCon['test']['products']
.Update()
.Match
.Add('sku', 'abc123')
.&End
.Modify
.Inc
.Field('quantity', -2)
.Field('metrics.orders', 1)
.&End
.Mul
.Field('metrics.ratings', 1.01)
.&End
.&End
.Exec;
oCrs := FCon['test']['products'].Find();
while oCrs.Next do
Memo1.Text := Memo1.Text + #13#10 + oCrs.Doc.AsJSON;
finally
oDoc.Free;
end;
end;
procedure TfrmMain.btnUpdPushClick(Sender: TObject);
var
oDoc: TMongoDocument;
oCrs: IMongoCursor;
begin
// For details see:
// http://docs.mongodb.org/manual/reference/operator/update/push/
oDoc := FEnv.NewDoc;
try
FCon['test']['students'].RemoveAll;
oDoc
.Add('_id', 5)
.BeginArray('quizzes')
.BeginObject('0')
.Add('wk', 1)
.Add('score', 10)
.EndObject
.BeginObject('1')
.Add('wk', 2)
.Add('score', 8)
.EndObject
.BeginObject('2')
.Add('wk', 3)
.Add('score', 5)
.EndObject
.BeginObject('3')
.Add('wk', 4)
.Add('score', 6)
.EndObject
.EndArray;
FCon['test']['students'].Insert(oDoc);
FCon['test']['students']
.Update()
.Match
.Add('_id', 5)
.&End
.Modify
.Push
.Field('quizzes', ['{', 'wk', 5, 'score', 8, '}',
'{', 'wk', 6, 'score', 7, '}',
'{', 'wk', 7, 'score', 6, '}'],
True, 3, '"score": -1')
.&End
.&End
.Exec;
oCrs := FCon['test']['students'].Find();
while oCrs.Next do
Memo1.Text := Memo1.Text + #13#10 + oCrs.Doc.AsJSON;
finally
oDoc.Free;
end;
end;
procedure TfrmMain.Button9Click(Sender: TObject);
var
oDoc: TMongoDocument;
oCol: TMongoCollection;
i: Integer;
oCrs: IMongoCursor;
begin
// For details see:
// http://docs.mongodb.org/manual/reference/method/Bulk/
oDoc := FEnv.NewDoc;
try
oCol := FCon['test']['testbulk'];
oCol.RemoveAll;
try
oCol.BeginBulk(False);
for i := 1 to 10 do begin
oDoc
.Clear
.Add('_id', i div 2)
.Add('name', 'rec' + IntToStr(i));
oCol.Insert(oDoc);
end;
oCol.EndBulk;
except
ApplicationHandleException(nil);
end;
oCrs := oCol.Find();
while oCrs.Next do
Memo1.Text := Memo1.Text + #13#10 + oCrs.Doc.AsJSON;
finally
oDoc.Free;
end;
end;
procedure TfrmMain.btnIterateClick(Sender: TObject);
var
oDoc: TMongoDocument;
oIter: TJSONIterator;
sIdent: String;
begin
oDoc := FEnv.NewDoc;
try
oDoc
.BeginObject('address')
.Add('street', '2 Avenue')
.Add('zipcode', '10075')
.Add('building', '1480')
.BeginArray('coord')
.Add('0', -73.9557413)
.Add('1', 40.7720266)
.EndArray
.EndObject
.Add('borough', 'Manhattan')
.Add('cuisine', 'Italian')
.BeginArray('grades')
.BeginObject('0')
.Add('date', EncodeDate(2000, 5, 25))
.Add('grade', 'Add')
.Add('score', 11)
.EndObject
.BeginObject('1')
.Add('date', EncodeDate(2005, 6, 2))
.Add('grade', 'B')
.Add('score', 17)
.EndObject
.EndArray
.Add('name', 'Vella')
.Add('restaurant_id', '41704620');
oIter := oDoc.Iterator;
sIdent := '';
try
while True do begin
while oIter.Next do begin
Memo1.Lines.Add(sIdent + oIter.Key);
if oIter.&Type in [TJsonToken.StartObject, TJsonToken.StartArray] then begin
sIdent := sIdent + ' ';
oIter.Recurse;
end;
end;
if oIter.InRecurse then begin
oIter.Return;
sIdent := Copy(sIdent, 1, Length(sIdent) - 2);
end
else
Break;
end;
if oIter.Find('grades[0].score') then
Memo1.Lines.Add('found')
else
Memo1.Lines.Add('NOT found');
finally
oIter.Free;
end;
finally
oDoc.Free;
end;
end;
procedure TfrmMain.btnCurrentOpClick(Sender: TObject);
var
oCrs: IMongoCursor;
begin
// For details see:
// http://docs.mongodb.org/manual/reference/method/db.currentOp/
oCrs := FCon['admin']['$cmd.sys.inprog'].Command('{"query": {"$all": [true]}}');
while oCrs.Next do
Memo1.Text := Memo1.Text + #13#10 + oCrs.Doc.AsJSON;
end;
end.
|
unit mnAboutDialogWizard;
interface
uses ToolsAPI;
type
mnTAboutDialogWizard = class(TNotifierObject,
IOTAWizard, IOTARepositoryWizard, IOTAFormWizard, IOTACreator, IOTAModuleCreator)
private
FModuleName: string;
FUnitName: string;
FFormName: string;
protected
// IOTAWizard methods
function GetIDString: string;
function GetName: string;
function GetState: TWizardState;
procedure Execute;
// IOTARepositoryWizard methods
function GetAuthor: string;
function GetComment: string;
function GetPage: string;
function GetGlyph: Cardinal;
// IOTACreator methods
function GetCreatorType: string;
function GetExisting: Boolean;
function GetFileSystem: string;
function GetOwner: IOTAModule;
function GetUnnamed: Boolean;
// IOTAModuleCreator methods
function GetAncestorName: string;
function GetImplFileName: string;
function GetIntfFileName: string;
function GetFormName: string;
function GetMainForm: Boolean;
function GetShowForm: Boolean;
function GetShowSource: Boolean;
function NewFormFile(const FormIdent, AncestorIdent: string): IOTAFile;
function NewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile;
function NewIntfSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile;
procedure FormCreated(const FormEditor: IOTAFormEditor);
end;
implementation
uses Windows, SysUtils, Dialogs, mnWindows, mnDialog, mnSystem, mnString;
{$R ..\..\..\files\Strings\IOTA\mnAboutDialogWizard\mnAboutDialogWizard.res}
{$R ..\..\..\files\Icons\IOTA\mnAboutDialogWizard.res}
type
TBaseFile = class(TInterfacedObject)
private
FModuleName: string;
FFormName: string;
FAncestorName: string;
public
constructor Create(const ModuleName, FormName, AncestorName: string);
end;
TUnitFile = class(TBaseFile, IOTAFile)
protected
function GetSource: string;
function GetAge: TDateTime;
end;
TFormFile = class(TBaseFile, IOTAFile)
protected
function GetSource: string;
function GetAge: TDateTime;
end;
{ TBaseFile }
constructor TBaseFile.Create(const ModuleName, FormName, AncestorName: string);
begin
inherited Create;
FModuleName := ModuleName;
FFormName := FormName;
FAncestorName := AncestorName;
end;
{ TUnitFile }
function TUnitFile.GetSource: string;
begin
Result := mnLoadResAsStr(HInstance, 'AboutDialog');
end;
function TUnitFile.GetAge: TDateTime;
begin
Result := -1;
end;
{ TFormFile }
function TFormFile.GetSource: string;
begin
Result := mnLoadResAsStr(HInstance, 'AboutDialogDFM');
end;
function TFormFile.GetAge: TDateTime;
begin
Result := -1;
end;
{ mnTAboutDialogWizard }
function mnTAboutDialogWizard.GetIDString: string;
begin
Result := 'Moon.mnTAboutDialogWizard';
end;
function mnTAboutDialogWizard.GetName: string;
begin
Result := 'About Dialog';
end;
function mnTAboutDialogWizard.GetState: TWizardState;
begin
Result := [wsEnabled];
end;
procedure mnTAboutDialogWizard.Execute;
begin
FModuleName := 'About';
FUnitName := 'Dlg' + FModuleName;
FFormName := FModuleName + 'Dialog';
(BorlandIDEServices as IOTAModuleServices).CreateModule(Self);
end;
function mnTAboutDialogWizard.GetAuthor: string;
begin
Result := 'Milan Qiu';
end;
function mnTAboutDialogWizard.GetComment: string;
begin
Result := 'Creates a new about dialog.';
end;
function mnTAboutDialogWizard.GetPage: string;
begin
Result := 'Moon';
end;
function mnTAboutDialogWizard.GetGlyph: Cardinal;
begin
Result := LoadImage(hInstance, 'mnTAboutDialogWizard', IMAGE_ICON, 0, 0, LR_DEFAULTSIZE);
end;
function mnTAboutDialogWizard.GetCreatorType: string;
begin
Result := '';
end;
function mnTAboutDialogWizard.GetExisting: Boolean;
begin
Result := False;
end;
function mnTAboutDialogWizard.GetFileSystem: string;
begin
Result := '';
end;
function mnTAboutDialogWizard.GetOwner: IOTAModule;
var
i: Integer;
ModServ: IOTAModuleServices;
Module: IOTAModule;
ProjGrp: IOTAProjectGroup;
begin
Result := nil;
ModServ := BorlandIDEServices as IOTAModuleServices;
for i := 0 to ModServ.ModuleCount - 1 do
begin
Module := ModSErv.Modules[i];
// find current project group
if CompareText(ExtractFileExt(Module.FileName), '.bdsgroup') = 0 then
if Module.QueryInterface(IOTAProjectGroup, ProjGrp) = S_OK then
begin
// return active project of group
Result := ProjGrp.GetActiveProject;
Exit;
end;
end;
end;
function mnTAboutDialogWizard.GetUnnamed: Boolean;
begin
Result := True;
end;
function mnTAboutDialogWizard.GetAncestorName: string;
begin
Result := '';
end;
function mnTAboutDialogWizard.GetImplFileName: string;
begin
// Note: full path name required!
Result := Format('%s%s.pas', [ExtractFilePath(GetOwner.FileName), FUnitName]);
end;
function mnTAboutDialogWizard.GetIntfFileName: string;
begin
Result := '';
end;
function mnTAboutDialogWizard.GetFormName: string;
begin
Result := FFormName;
end;
function mnTAboutDialogWizard.GetMainForm: Boolean;
begin
Result := False;
end;
function mnTAboutDialogWizard.GetShowForm: Boolean;
begin
Result := True;
end;
function mnTAboutDialogWizard.GetShowSource: Boolean;
begin
Result := True;
end;
function mnTAboutDialogWizard.NewFormFile(const FormIdent, AncestorIdent: string): IOTAFile;
begin
Result := TFormFile.Create(FModuleName, '', AncestorIdent);
end;
function mnTAboutDialogWizard.NewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile;
begin
Result := TUnitFile.Create(FModuleName, '', AncestorIdent);
end;
function mnTAboutDialogWizard.NewIntfSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile;
begin
Result := nil;
end;
procedure mnTAboutDialogWizard.FormCreated(const FormEditor: IOTAFormEditor);
begin
// do nothing
end;
initialization
RegisterPackageWizard(mnTAboutDialogWizard.Create);
end.
|
unit OTPcipher;
{$mode objfpc}{$H+}
interface
uses
SysUtils, uspybeauty;
type
CipherException = class(Exception);
procedure changeEncType();
function isEncByAddition(): boolean;
procedure setEncByAdditionTo(val: boolean);
function Cipher(src: ansistring; key: ansistring; encipher: boolean): ansistring;
implementation
var
encipherByAddition: boolean = False;
resourcestring
ssBadKeyLength = 'Unsufficient key length.';
ssNonDigit = 'Non-digit symbol in input. Please check.';
procedure changeEncType();
begin
encipherByAddition := not encipherByAddition;
end;
procedure setEncByAdditionTo(val: boolean);
begin
encipherByAddition := val;
end;
function isEncByAddition(): boolean;
begin
isEncByAddition := encipherByAddition;
end;
function mod10minus(a: integer; b: integer): integer; //a-b: it was harder, than expected
begin
if b > a then
a := 10 + a; //very problem specific
mod10minus := (a - b) mod 10;
end;
function Cipher(src: ansistring; key: ansistring; encipher: boolean): ansistring;
var
i: integer; //loop counter
sn: integer; //current source text digit
kn: integer; //current key digit
r: ansistring = ''; //result
eflag: boolean; //substraction flag
begin
eflag := encipher xor encipherByAddition;
src := extractNums(src);
key := extractNums(key);
if length(utf8decode(src)) > length(key) then
begin
Cipher := '(⊙︿⊙)';
raise CipherException.create(ssBadKeyLength);
exit;
end;
for i := 1 to (length(src)) do
begin
try
sn := StrToInt(src[i]);
kn := StrToInt(key[i]);
except
On E: EConvertError do
begin
raise CipherException.create(ssNonDigit);
//Newer shown?
Cipher := '(''o'')';
exit;
end;
end;
if eflag then
begin
//ShowMessage('Minus');
r := r + IntToStr(mod10minus(sn, kn));
end
else
begin
//ShowMessage('Plus');
r := r + IntToStr((sn + kn) mod 10);
end;
end;
Cipher := r;
end;
end.
|
{***************************************************************************}
{ }
{ DelphiUIAutomation }
{ }
{ Copyright 2015-17 JHC Systems Limited }
{ }
{***************************************************************************}
{ }
{ 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 AutomatedStringGrid;
interface
uses
AutomatedStringGridItem,
UIAutomationCore_TLB,
windows,
messages,
classes,
ActiveX,
grids;
type
TAutomatedStringGrid = class(TStringGrid,
ISelectionProvider,
IGridProvider,
ITableProvider,
IInvokeProvider,
IValueProvider,
IRawElementProviderSimple,
IRawElementProviderSimple2)
private
FRawElementProviderSimple : IRawElementProviderSimple;
procedure WMGetObject(var Message: TMessage); message WM_GETOBJECT;
protected
function GetCol: Integer; virtual;
function GetRow: Integer; virtual;
function GetColumnCount: integer; virtual;
function GetRowCount: integer; virtual;
function GetCell(column: integer; row: integer) : String; virtual;
function GetCanMultipleSelect: Integer; virtual;
function CreateCell(ACount, ARow: integer; AValue: String; ARect: TRect) : IAutomatedStringGridItem; virtual;
public
// IRawElementProviderSimple
function Get_ProviderOptions(out pRetVal: ProviderOptions): HResult; stdcall;
function GetPatternProvider(patternId: SYSINT; out pRetVal: IUnknown): HResult; stdcall;
function GetPropertyValue(propertyId: SYSINT; out pRetVal: OleVariant): HResult; stdcall;
function Get_HostRawElementProvider(out pRetVal: IRawElementProviderSimple): HResult; stdcall;
// ISelectionProvider
///<remarks>
/// Will return the selected row (if possible)
///</remarks>
function GetSelection(out pRetVal: PSafeArray): HResult; virtual; stdcall;
function Get_CanSelectMultiple(out pRetVal: Integer): HResult; stdcall;
function Get_IsSelectionRequired(out pRetVal: Integer): HResult; stdcall;
// IInvokeProvider
function Invoke: HResult; stdcall;
// IRawElementProviderSimple2
function ShowContextMenu: HResult; virtual; stdcall;
// IValueProvider
function SetValue(val: PWideChar): HResult; stdcall;
function Get_Value(out pRetVal: WideString): HResult; stdcall;
function Get_IsReadOnly(out pRetVal: Integer): HResult; stdcall;
// IGridProvider
function GetItem(row: SYSINT; column: SYSINT; out pRetVal: IRawElementProviderSimple): HResult; stdcall;
function Get_RowCount(out pRetVal: SYSINT): HResult; stdcall;
function Get_ColumnCount(out pRetVal: SYSINT): HResult; stdcall;
// ITableProvider
function GetRowHeaders(out pRetVal: PSafeArray): HResult; stdcall;
function GetColumnHeaders(out pRetVal: PSafeArray): HResult; stdcall;
function Get_RowOrColumnMajor(out pRetVal: RowOrColumnMajor): HResult; stdcall;
end;
procedure Register;
implementation
uses
dialogs,
sysutils,
Variants;
procedure Register;
begin
RegisterComponents('Automation', [TAutomatedStringGrid]);
end;
{ TAutomationStringGrid }
function TAutomatedStringGrid.GetColumnHeaders(
out pRetVal: PSafeArray): HResult;
var
intf : IAutomatedStringGridItem;
outBuffer : PSafeArray;
unk : IUnknown;
Bounds : array [0..0] of TSafeArrayBound;
count : integer;
begin
pRetVal := nil;
// is a cell selected?
if (self.FixedRows <> 0) then
begin
bounds[0].lLbound := 0;
bounds[0].cElements := self.getColumnCount;
outBuffer := SafeArrayCreate(VT_UNKNOWN, 1, @Bounds);
for count := 0 to self.getColumnCount -1 do
begin
intf := self.CreateCell(count, 0, self.getCell(count, 0), self.CellRect(count, 0));
if intf <> nil then
begin
unk := intf as IUnknown;
Result := SafeArrayPutElement(&outBuffer, count, Pointer(unk)^);
if Result <> S_OK then
begin
SafeArrayDestroy(outBuffer);
pRetVal := nil;
result := E_OUTOFMEMORY;
exit;
end
end;
end;
pRetVal := outBuffer;
result := S_OK;
end
else
begin
pRetVal := nil;
result := S_FALSE;
end;
end;
function TAutomatedStringGrid.getCell(column: integer; row: integer) : String;
begin
result := self.Cells[column, row];
end;
function TAutomatedStringGrid.GetItem(row, column: SYSINT;
out pRetVal: IRawElementProviderSimple): HResult;
var
intf : IRawElementProviderSimple;
begin
result := S_OK;
intf := self.CreateCell(column, row, self.getCell(column, row), self.CellRect(column, row)).asIRawElementProviderSimple;
pRetVal := intf;
end;
function TAutomatedStringGrid.GetPatternProvider(patternId: SYSINT;
out pRetVal: IInterface): HResult;
begin
result := S_OK;
pRetval := nil;
if ((patternID = UIA_InvokePatternId) or
(patternID = UIA_ValuePatternId) or
(patternID = UIA_TablePatternId) or
(patternID = UIA_GridPatternId) or
(patternID = UIA_SelectionPatternId)) then
begin
pRetVal := self;
end;
end;
function TAutomatedStringGrid.GetPropertyValue(propertyId: SYSINT;
out pRetVal: OleVariant): HResult;
begin
if(propertyId = UIA_ClassNamePropertyId) then
begin
TVarData(pRetVal).VType := varOleStr;
TVarData(pRetVal).VOleStr := pWideChar(self.ClassName);
result := S_OK;
end
else if(propertyId = UIA_NamePropertyId) then
begin
TVarData(pRetVal).VType := varOleStr;
TVarData(pRetVal).VOleStr := pWideChar(self.Name);
result := S_OK;
end
else if (propertyId = UIA_ControlTypePropertyId) then
begin
TVarData(pRetVal).VType := varInteger;
TVarData(pRetVal).VInteger := UIA_DataGridControlTypeId;
result := S_OK;
end
else
result := S_FALSE;
end;
function TAutomatedStringGrid.GetRowHeaders(out pRetVal: PSafeArray): HResult;
begin
pRetVal := nil;
result := S_FALSE;
end;
function TAutomatedStringGrid.CreateCell(ACount, ARow: integer; AValue: String; ARect: TRect) : IAutomatedStringGridItem;
begin
result := TAutomatedStringGridItem.create(self, ACount, ARow, AValue, ARect);
end;
function TAutomatedStringGrid.GetSelection(out pRetVal: PSafeArray): HResult;
var
intf : IAutomatedStringGridItem;
outBuffer : PSafeArray;
unk : IUnknown;
Bounds : array [0..0] of TSafeArrayBound;
count : integer;
iRow : integer;
begin
pRetVal := nil;
iRow := Self.Row;
// is a cell selected?
if (iRow > -1) then
begin
bounds[0].lLbound := 0;
bounds[0].cElements := self.getColumnCount;
outBuffer := SafeArrayCreate(VT_UNKNOWN, 1, @Bounds);
for count := 0 to self.getColumnCount -1 do
begin
intf := self.CreateCell(count, iRow, self.getCell(count, iRow), self.CellRect(count, iRow));
if intf <> nil then
begin
unk := intf as IUnknown;
Result := SafeArrayPutElement(&outBuffer, count, Pointer(unk)^);
if Result <> S_OK then
begin
SafeArrayDestroy(outBuffer);
pRetVal := nil;
result := E_OUTOFMEMORY;
exit;
end
end;
end;
pRetVal := outBuffer;
result := S_OK;
end
else
begin
pRetVal := nil;
result := S_FALSE;
end;
end;
function TAutomatedStringGrid.getCanMultipleSelect: Integer;
begin
result := 0;
end;
function TAutomatedStringGrid.Get_CanSelectMultiple(out pRetVal: Integer): HResult;
begin
pRetVal := self.getCanMultipleSelect;
result := S_OK;
end;
function TAutomatedStringGrid.Get_ColumnCount(out pRetVal: SYSINT): HResult;
begin
pRetVal := self.getColumnCount;
result := S_OK;
end;
function TAutomatedStringGrid.Get_HostRawElementProvider(
out pRetVal: IRawElementProviderSimple): HResult;
begin
result := UiaHostProviderFromHwnd (self.Handle, pRetVal);
end;
function TAutomatedStringGrid.Get_IsSelectionRequired(out pRetVal: Integer): HResult;
begin
pRetVal := 0;
result := S_OK;
end;
function TAutomatedStringGrid.Get_ProviderOptions(out pRetVal: ProviderOptions): HResult;
begin
pRetVal:= ProviderOptions_ServerSideProvider;
Result := S_OK;
end;
function TAutomatedStringGrid.Get_RowCount(out pRetVal: SYSINT): HResult;
begin
pretVal := self.getRowCount;
result := S_OK;
end;
function TAutomatedStringGrid.getRowCount: integer;
begin
result := self.rowCount;
end;
function TAutomatedStringGrid.getColumnCount: integer;
begin
result := self.colCount;
end;
function TAutomatedStringGrid.Get_RowOrColumnMajor(
out pRetVal: RowOrColumnMajor): HResult;
begin
pRetVal := RowOrColumnMajor_RowMajor;
result := S_OK;
end;
function TAutomatedStringGrid.Invoke: HResult;
begin
PostMessage(self.Handle, WM_LBUTTONDBLCLK, Integer(self),0);
result := S_OK;
end;
function TAutomatedStringGrid.SetValue(val: PWideChar): HResult;
begin
self.Cells[self.Col, self.Row] := val;
result := S_OK;
end;
function TAutomatedStringGrid.Get_Value(out pRetVal: WideString): HResult;
begin
pRetVal := self.getCell(self.Col, self.Row);
result := S_OK;
end;
function TAutomatedStringGrid.getCol: Integer;
begin
result := self.Col;
end;
function TAutomatedStringGrid.getRow: Integer;
begin
result := self.Row;
end;
function TAutomatedStringGrid.ShowContextMenu: HResult;
begin
// Descendant classes can implement this
result := S_OK;
end;
function TAutomatedStringGrid.Get_IsReadOnly(out pRetVal: Integer): HResult;
begin
// pRetVal := self
pRetVal := 0;
result := S_OK;
end;
procedure TAutomatedStringGrid.WMGetObject(var Message: TMessage);
begin
if (Message.Msg = WM_GETOBJECT) then
begin
QueryInterface(IID_IRawElementProviderSimple, FRawElementProviderSimple);
message.Result := UiaReturnRawElementProvider(self.Handle, Message.WParam, Message.LParam, FRawElementProviderSimple);
end
else
Message.Result := DefWindowProc(self.Handle, Message.Msg, Message.WParam, Message.LParam);
end;
end.
|
unit unitBase;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.WinXCtrls,
Vcl.Imaging.pngimage, Vcl.CategoryButtons, System.ImageList, Vcl.ImgList,
Vcl.StdCtrls, System.Actions, Vcl.ActnList, 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,
Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client;
type
TExecutar = (Navegacao, sentencaSQL, exibePanels, desabilitaBotoes, habilitaBotoes, exibeBotoes);
TformBasico = class(TForm)
header: TImage;
footer: TImage;
SplitView1: TSplitView;
PNLFicha: TPanel;
imgMenu: TImage;
CategoryButtons1: TCategoryButtons;
ILMenuPrincipal: TImageList;
ILMenuPrincipalNegativo: TImageList;
ActionList1: TActionList;
actIncluir: TAction;
FDTabela: TFDTable;
DataSource1: TDataSource;
actCancelar: TAction;
actAlterar: TAction;
actSalvar: TAction;
actExcluir: TAction;
actPesquisar: TAction;
actSair: TAction;
GroupBox1: TGroupBox;
procedure imgMenuClick(Sender: TObject);
procedure actIncluirExecute(Sender: TObject);
procedure actAlterarExecute(Sender: TObject);
procedure actExcluirExecute(Sender: TObject);
procedure actCancelarExecute(Sender: TObject);
procedure actSalvarExecute(Sender: TObject);
procedure actSairExecute(Sender: TObject);
private
FExecutar: TExecutar;
procedure SetExecutar(const Value: TExecutar);
public
property Executar: TExecutar read FExecutar write SetExecutar;
{ Public declarations }
end;
var
formBasico: TformBasico;
tipoID: integer;
nomeTabela: String;
nomeJanela: String;
mensagem: String;
operacaoIncluir: Integer;
implementation
{$R *.dfm}
uses unitDM;
procedure TformBasico.actAlterarExecute(Sender: TObject);
begin
FDTabela.Edit;
end;
procedure TformBasico.actCancelarExecute(Sender: TObject);
begin
FDTabela.Cancel;
mensagem := 'As alterações foram canceladas. ';
Application.MessageBox(PChar(mensagem), 'Informação', MB_OK+MB_ICONINFORMATION);
end;
procedure TformBasico.actExcluirExecute(Sender: TObject);
begin
mensagem := 'Tem certeza que deseja excluir o registro?';
if Application.MessageBox(PChar(mensagem), 'Atenção', MB_YESNO+MB_ICONQUESTION) = ID_YES then
begin
FDTabela.Delete;
mensagem := 'O registro foi excluído com sucesso.';
Application.MessageBox(PChar(mensagem), 'Informação', MB_OK+MB_ICONINFORMATION);
end
else
begin
mensagem := 'A operação foi abortada.';
Application.MessageBox(PChar(mensagem), 'Informação', MB_OK+MB_ICONINFORMATION);
end;
end;
procedure TformBasico.actIncluirExecute(Sender: TObject);
begin
if FDTabela.Active = False then
begin
FDTabela.Open;
end;
FDTabela.Insert;
FDTabela.FieldByName('DATA_INC').AsDateTime := Date;
end;
procedure TformBasico.actSairExecute(Sender: TObject);
begin
self.Close;
end;
procedure TformBasico.actSalvarExecute(Sender: TObject);
begin
FDTabela.Post;
mensagem := 'O registro foi incluído ou alterado com sucesso. ';
Application.MessageBox(PChar(mensagem), 'Informação', MB_OK+MB_ICONINFORMATION);
end;
procedure TformBasico.imgMenuClick(Sender: TObject);
begin
if (SplitView1.Opened) then
begin
SplitView1.Close;
end
else
begin
SplitView1.Open;
end;
end;
procedure TformBasico.SetExecutar(const Value: TExecutar);
begin
end;
end.
|
unit C2Delphi.Forms.Main;
interface
{.$DEFINE USE_DELPHIAST}
{.$DEFINE USE_DWS}
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
System.Actions,
Vcl.Forms,
Vcl.Dialogs,
Vcl.Graphics,
Vcl.Controls,
Vcl.ExtCtrls,
Vcl.StdCtrls,
Vcl.WinXCtrls,
Vcl.ComCtrls,
Vcl.ActnList,
Vcl.PlatformDefaultStyleActnCtrls,
Vcl.ActnMan,
Vcl.Menus,
Vcl.Styles.Hooks,
Threading,
SynEditKeyCmds,
{$IFDEF USE_DELPHIAST}
DelphiAST,
DelphiAST.Consts,
DelphiAST.Classes,
{$ENDIF}
{$IFDEF USE_DWS}
dwsComp,
dwsExprs,
dwsStringResult,
{$ENDIF}
WvN.Pascal.Model,
WvN.Pascal.CReader, Vcl.AppEvnts,
SynHighlighterPas, SynEditHighlighter, SynHighlighterCpp, SynEdit,
Vcl.Themes
;
const
AppName='C to Delphi';
type
TfrmMain = class(TForm)
Splitter1: TSplitter;
SearchBox1: TSearchBox;
TreeView1: TTreeView;
Splitter2: TSplitter;
ActionManager1: TActionManager;
Action1: TAction;
actRun: TAction;
Splitter3: TSplitter;
ListBox1: TListBox;
StatusBar1: TStatusBar;
PopupMenu1: TPopupMenu;
Run1: TMenuItem;
ProgressBar1: TProgressBar;
ApplicationEvents1: TApplicationEvents;
Panel1: TPanel;
Panel2: TPanel;
StatusBar2: TStatusBar;
StatusBar3: TStatusBar;
edCCode: TSynEdit;
edPascalCode: TSynEdit;
SynCppSyn1: TSynCppSyn;
SynPasSyn1: TSynPasSyn;
procedure FormCreate(Sender: TObject);
procedure edCCodeSelectionChanged(Sender: TObject);
procedure edCCodeChange(Sender:TObject);
procedure SearchBox1Change(Sender: TObject);
procedure TreeView1Change(Sender: TObject; Node: TTreeNode);
procedure Action1Execute(Sender: TObject);
procedure actRunExecute(Sender: TObject);
procedure edPascalCodeCaretChanged(ASender: TObject; X, Y: Integer);
procedure edCCodeCaretChanged(ASender: TObject; X, Y: Integer);
procedure ListBox1DblClick(Sender: TObject);
procedure edPascalCodeChange(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ApplicationEvents1Hint(Sender: TObject);
procedure ApplicationEvents1Exception(Sender: TObject; E: Exception);
procedure FormDestroy(Sender: TObject);
procedure edPascalCodeClick(Sender: TObject);
procedure edCCodeSpecialLineColors(Sender: TObject; Line: Integer;
var Special: Boolean; var FG, BG: TColor);
procedure edPascalCodeSpecialLineColors(Sender: TObject; Line: Integer;
var Special: Boolean; var FG, BG: TColor);
procedure TreeView1CustomDrawItem(Sender: TCustomTreeView;
Node: TTreeNode; State: TCustomDrawState; var DefaultDraw: Boolean);
private
procedure WMDROPFILES(var msg : TWMDropFiles) ; message WM_DROPFILES;
procedure UpdateTree;
procedure ShowElement(Sender:TObject; el: TPascalElement);
function ReadCCodeFromFile(cfn: string):string;
procedure GetRangeSource(const sl: TStrings; e: TPascalElement; out p1,p2: TBufferCoord);
procedure GetRangeRender(const sl: TStrings; e: TPascalElement; out p1,p2: TBufferCoord);
procedure FindParent(var e: TPascalElement);
public
e:TPascalElement;
CFileName:string;
Pas:WvN.Pascal.Model.TPascalUnit;
{$IFDEF USE_DWS}
dws : TDelphiWebScript;
prog : IdwsProgram;
exec : IdwsProgramExecution;
{$ENDIF}
{$IFDEF USE_DELPHIAST}
ex : ESyntaxTreeException;
{$ENDIF}
task:ITask;
procedure Run;
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
uses ShellAPI, Math, System.IOUtils, dwsErrors,
System.Diagnostics,
RegularExpressions
;
{$IFDEF USE_DELPHIAST}
function Parse(const FileName: string;var ex:ESyntaxTreeException): string;
var
SyntaxTree: TSyntaxNode;
begin
try
ex := nil;
SyntaxTree := TPasSyntaxTreeBuilder.Run(FileName, False);
SyntaxTree.Free;
Result := 'Pascal syntax OK';
except
on E: ESyntaxTreeException do
begin
Result := Format('[%d, %d] %s', [E.Line, E.Col, E.Message]);
ex := E;
end;
end;
end;
{$ENDIF}
function getPosition(const sl:TStrings; Offset:Integer):TBufferCoord;
var
I,n: Integer;
const lineEndSize=length(sLineBreak);
begin
n := 0;
for I := 0 to sl.Count-1 do
begin
if (n + sl[I].Length + lineEndSize) > offset then
begin
Result.Line := I;
Result.Char := Offset - n;
Exit;
end;
n := n + sl[I].Length + lineEndSize;
end;
Result.Line := 0;
Result.Char := 0;
end;
procedure TfrmMain.edCCodeSelectionChanged(Sender: TObject);
var c,t:string;
begin
if edCCode.SelLength=0 then
begin
edCCodeCaretChanged(edCCode, edCCode.CaretX, edCCode.CaretY);
Exit;
end;
c := edCCode.SelText;
pas := TPascalUnit.Create(nil);
c_to_pas(c,t,pas.Name,
procedure(progress:double;const text:string)
begin
TThread.Synchronize(TThread.CurrentThread,
procedure
begin
ProgressBar1.Position := round(Progress * 100);
Statusbar1.Panels[2].Text := round(Progress * 100).toString+'% '+ Text;
if ListBox1.Count>0 then
ListBox1.Perform(lb_SetTopIndex,ListBox1.Count-1,0);
end);
end,
Pas);
UpdateTree;
edPascalCode.Text := pas.toPascal;
end;
procedure TfrmMain.edCCodeSpecialLineColors(Sender: TObject; Line: Integer;
var Special: Boolean; var FG, BG: TColor);
var p1,p2:TBufferCoord;
begin
if e=nil then
Exit;
if e.Sourceinfo.Position>edCCode.Text.Length then
Exit;
if e.Sourceinfo.Position<0 then
Exit;
p1 := getPosition( edCCode.Lines, e.Sourceinfo.Position);
p2 := getPosition( edCCode.Lines, e.Sourceinfo.Position + e.Sourceinfo.Length );
if InRange(Line, p1.Line, p2.Line) then
begin
Special := False;
BG := edCCode.Color + $111111;
end;
end;
procedure TfrmMain.GetRangeSource(const sl: TStrings; e: TPascalElement; out p1,p2: TBufferCoord);
begin
p1 := getPosition(sl, e.Sourceinfo.Position);
p2 := getPosition(sl, e.Sourceinfo.Position + e.Sourceinfo.Length);
end;
procedure TfrmMain.GetRangeRender(const sl: TStrings; e: TPascalElement; out p1,p2: TBufferCoord);
begin
p1 := getPosition(sl, e.Renderinfo.Position);
p2 := getPosition(sl, e.Renderinfo.Position + e.Renderinfo.Length);
end;
procedure TfrmMain.edPascalCodeCaretChanged(ASender: TObject; X, Y: Integer);
var c:TClassdef;e:TPascalElement;
p1,p2:TBufferCoord;
begin
StatusBar2.Panels[0].Text := Format('[Line:%d,Col%d]', [Y,X]);
if pas=nil then
Exit;
for c in pas.Classes do
for e in c.FMethods do
begin
GetRangeRender(edPascalCode.Lines, e, p1, p2);
if InRange(Y,p1.Line, p2.Line) then
begin
ShowElement(ASender,e);
edCCode.Refresh;
Exit;
end;
end;
for e in pas.GlobalArrays1D do
begin
GetRangeRender(edPascalCode.Lines, e, p1, p2);
if InRange(Y,p1.Line, p2.Line) then
begin
ShowElement(ASender,e);
edCCode.Refresh;
Exit;
end;
end;
for e in pas.GlobalArrays2D do
begin
GetRangeRender(edPascalCode.Lines, e, p1, p2);
if InRange(Y,p1.Line, p2.Line) then
begin
ShowElement(ASender,e);
edCCode.Refresh;
Exit;
end;
end;
for e in pas.Classes do
begin
GetRangeRender(edPascalCode.Lines, e, p1, p2);
if InRange(Y,p1.Line, p2.Line) then
begin
ShowElement(ASender,e);
edCCode.Refresh;
Exit;
end;
end;
end;
procedure TfrmMain.edPascalCodeChange(Sender: TObject);
{$IFDEF USE_DELPHIAST}
var fn,t:string;
{$ENDIF}
begin
{$IFDEF USE_DELPHIAST}
fn := TPath.Combine(TPath.GetTempPath, Pas.Name+'_tmp.pas');
edPascalCode.Lines.SaveToFile(fn);
t := Parse(fn,ex);
ListBox1.Items.Add(t);
TFile.Delete(fn);
{$ENDIF}
end;
procedure TfrmMain.edPascalCodeClick(Sender: TObject);
begin
edPascalCodeCaretChanged(edPascalCode, edPascalCode.CaretX, edPascalCode.CaretY);
end;
procedure TfrmMain.edPascalCodeSpecialLineColors(Sender: TObject;
Line: Integer; var Special: Boolean; var FG, BG: TColor);
var p1,p2:TBufferCoord;
begin
if e=nil then
Exit;
p1 := getPosition( edPascalCode.Lines, e.Renderinfo.Position);
p2 := getPosition( edPascalCode.Lines, e.Renderinfo.Position + e.Renderinfo.Length );
if InRange(Line, p1.Line, p2.Line) then
begin
Special := False;
BG := edPascalCode.Color + $111111;
end;
end;
procedure TfrmMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if Assigned(Task) then
Task.Cancel;
Task.Wait(1);
end;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
TStyleManager.Engine.RegisterStyleHook(TCustomSynEdit, TScrollingStyleHook);
{$IFDEF USE_DWS}
dws:=TDelphiWebScript.Create(nil);
{$ENDIF}
CFileName := '';
edCCode.Color := $00222827;
edCCode.Text :=
'void hello(int x){'+sLineBreak+
' printf("Hello world %d\n",x);'+sLineBreak+
'}'+sLineBreak+
''+sLineBreak+
'/* '+sLineBreak+
' Multiline'+sLineBreak+
' Comment'+sLineBreak+
'*/ '+sLineBreak+
'int main(){'+sLineBreak+
' for(int i=0;i<=10;i++){'+sLineBreak+
' hello(i);'+sLineBreak+
' } '+sLineBreak+
'}'
;
DragAcceptFiles( Handle, True ) ;
edCCodeChange(nil);
end;
procedure TfrmMain.FormDestroy(Sender: TObject);
begin
{$IFDEF USE_DWS}
dws.Free;
{$ENDIF}
{$IFDEF USE_DELPHIAST}
ex.Free;
{$ENDIF}
pas.Free;
end;
procedure TfrmMain.ListBox1DblClick(Sender: TObject);
var line,Col:integer;m:TMatch; pos:TBufferCoord;
begin
if ListBox1.ItemIndex<0 then Exit;
m := TRegEx.Match(ListBox1.Items[ListBox1.ItemIndex], '\[(?<Line>\d+)\,\s*(?<Col>\d+)\]\s*(?<Message>.*)');
if not m.Success then
Exit;
Line := StrToInt(m.Groups['Line'].Value)-1;
Col := StrToInt(m.Groups['Col'].Value);
pos.Char := Col;
pos.Line := Line;
edPascalCode.SelStart := edPascalCode.RowColToCharIndex(Pos);
Pos.Char := Pos.Char + 1;
edPascalCode.SelEnd := edPascalCode.RowColToCharIndex(Pos);
edPascalCode.TopLine := Line - 3;
edPascalCode.SetFocus;
FocusControl(edPascalCode);
end;
{$IFDEF USE_DWS}
procedure TfrmMain.Run;
var s,code:string;
begin
code := edPascalCode.Text;
// fix some common problems.
// Somehow DWS uses PintLn instead of WriteLn
code := code.Replace('WriteLn','PrintLn',[ rfIgnoreCase, rfReplaceAll ]);
code := code.Replace('Write','Print',[ rfIgnoreCase, rfReplaceAll ]);
// compile
prog:=dws.Compile(code);
ListBox1.Clear;
ListBox1.Items.Add('Output:');
if prog.Msgs.Count=0 then
begin
try
// run
exec := prog.Execute;
// show program output in listbox
for s in exec.Result.ToString.Split([sLineBreak]) do
ListBox1.Items.Add(s);
except
on E: Exception do
ListBox1.Items.Add(E.ClassName+': '+E.Message);
end;
end
else
begin
ListBox1.Items.Add(prog.Msgs.AsInfo);
end;
end;
{$ELSE}
procedure TfrmMain.Run;
begin
// include DWS to run the generated code
end;
{$ENDIF}
function TfrmMain.ReadCCodeFromFile(cfn: string): string;
var
hfn: string;
begin
// try to open the header file too...
Result := TFile.ReadAllText(cfn);
if not SameText(ExtractFileExt(cfn), '.h') then
begin
hfn := ChangeFileExt(cfn, '.h');
if TFile.Exists(hfn) then
Result := TFile.ReadAllText(hfn) + sLineBreak + Result;
end;
end;
procedure TfrmMain.FindParent(var e: TPascalElement);
begin
repeat
if e.Renderinfo.Length > 1 then
break
else
e := e.Owner;
until (e = nil) or (e.Owner = nil);
end;
procedure TfrmMain.ShowElement(Sender:TObject; el: TPascalElement);
var
p1,p3: TBufferCoord;
begin
StatusBar1.Panels[4].Text := Format('%s (%s)',[el.Name,el.Name.TrimLeft(['T'])]);
e := el;
FindParent(e);
if e <> nil then
begin
p1 := getPosition(edCCode.Lines, e.Sourceinfo.Position);
while edCCode.Lines[p1.Line].Trim = '' do
begin
p1.Line := p1.Line + 1;
if p1.Line > edCCode.Lines.Count then
Break;
end;
if Sender<>edCCode then
begin
edCCode.TopLine := p1.Line;
edCCode.Refresh;
end;
end;
e := el;
FindParent(e);
if e<>nil then
begin
p3 := getPosition(edPascalCode.Lines, e.Renderinfo.Position);
if Sender<>edPascalCode then
begin
edPascalCode.TopLine := p3.Line - (p1.Line - edCCode.TopLine + 1);
edPascalCode.Refresh;
end;
end;
end;
procedure TfrmMain.SearchBox1Change(Sender: TObject);
begin
edCCode.SearchEngine.FindAll(SearchBox1.Text);
Caption := Format('Matches:%d', [edCCode.SearchEngine.ResultCount]);;
end;
procedure TfrmMain.TreeView1Change(Sender: TObject; Node: TTreeNode);
var el:TPascalElement;
begin
if Node.Data=nil then
Exit;
el := Node.Data;
if el=nil then
Exit;
ShowElement(Sender,el);
end;
procedure TfrmMain.TreeView1CustomDrawItem(Sender: TCustomTreeView;
Node: TTreeNode; State: TCustomDrawState; var DefaultDraw: Boolean);
var el:TPascalElement;
begin
el := TPascalElement(Node.Data);
if el is TClassDef then Sender.Canvas.Font.Color := $FF9999;
if el is TVariableList then Sender.Canvas.Font.Color := $99CC99;
if el is TVariable then Sender.Canvas.Font.Color := $999999;
if el is TPascalUnit then Sender.Canvas.Font.Color := $888888;
if el is TRoutine then Sender.Canvas.Font.Color := $6666FF;
if el is TUsesList then Sender.Canvas.Font.Color := $669999;
if el is TUsesListItem then Sender.Canvas.Font.Color := $66cccc;
if el is TEnumDef then Sender.Canvas.Font.Color := $66ffcc;
if el is TArrayDef1D then Sender.Canvas.Font.Color := $ffffcc;
if el is TArrayDef2D then Sender.Canvas.Font.Color := $ffccff;
DefaultDraw := True;
end;
procedure TfrmMain.WMDROPFILES(var msg: TWMDropFiles);
const
MAXFILENAME = 255;
var
cnt, fileCount: integer;
code,cfn,t:string;
fileName : array [0 .. MAXFILENAME] of char;
p:TPascalUnit;
begin
fileCount := DragQueryFile(msg.Drop, $FFFFFFFF, fileName, MAXFILENAME);
for cnt := 0 to fileCount -1 do
begin
DragQueryFile(msg.Drop, cnt, fileName, MAXFILENAME);
cfn := fileName;
if fileCount>1 then
begin
p := TPascalUnit.Create(nil);
try
c_to_pas(ReadCCodeFromFile(cfn),t,changefileext(ExtractFilename(cfn),''),
procedure(progress:double;const text:string)
begin
ProgressBar1.Position := round(Progress * 100);
Statusbar1.Panels[2].Text := round(Progress * 100).toString+'% '+ Text;
if ListBox1.Count>0 then
ListBox1.Perform(lb_SetTopIndex,ListBox1.Count-1,0);
end,
p
);
TFile.WriteAllText( ChangeFileExt(fileName,'.pas'), p.toPascal);
finally
p.Free;
end;
end;
end;
if fileCount>0 then
begin
code := ReadCCodeFromFile(cfn);
if length(code)>1024*150 then
begin
edCCode.Highlighter := nil;
end
else
begin
edCCode.Highlighter := SynCppSyn1;
edCCode.Color := $00222827;
end;
edCCode.Clear;
edCCode.Text := code;
edCCode.Hint := ChangeFileExt(ExtractFileName(cfn),'');
CFileName := fileName;
pas.Name := changefileext(ExtractFilename(cfn),'');
edCCodeChange(nil);
end;
DragFinish(msg.Drop);
end;
procedure TfrmMain.UpdateTree;
procedure AddNode(p:TPascalElement;t:TTreeNode);
var i:integer;tn:TTreeNode;
begin
tn := TreeView1.Items.AddChild(t, p.ToString );
tn.Data := p;
for I := 0 to p.Count-1 do
if p.Children[I].Visible then
begin
AddNode(p.Children[I],tn);
end;
if (p is TRoutine) or (p is TVariableList) then
tn.Collapse(True)
else
tn.Expand(false);
end;
begin
TreeView1.Items.BeginUpdate;
TreeView1.Items.Clear;
AddNode(pas,nil);
TreeView1.Items.EndUpdate;
end;
procedure TfrmMain.Action1Execute(Sender: TObject);
begin
edCCode.Lines.SaveToFile(ChangeFileExt(cFileName,'_prep_.c'));
edPascalCode.Lines.SaveToFile(ChangeFileExt(cFileName,'.pas'));
end;
procedure TfrmMain.actRunExecute(Sender: TObject);
begin
Run;
end;
procedure TfrmMain.ApplicationEvents1Exception(Sender: TObject; E: Exception);
begin
ListBox1.Items.Add(E.Message)
end;
procedure TfrmMain.ApplicationEvents1Hint(Sender: TObject);
begin
StatusBar1.Panels[3].Text := Application.Hint;
end;
procedure TfrmMain.edCCodeCaretChanged(ASender: TObject; X, Y: Integer);
var text:string; c:TClassDef;
e:TPascalElement; p1,p2:TBufferCoord;
begin
if pas=nil then
Exit;
text := edCCode.Text;
StatusBar3.Panels[0].Text := Format('[Line:%d,Col%d]', [Y,X]);
for c in pas.Classes do
for e in c.FMethods do
begin
GetRangeSource(edCCode.Lines, e, p1, p2);
if InRange(Y,p1.Line, p2.Line) then
begin
ShowElement(ASender,e);
Exit;
end;
end;
for e in pas.GlobalArrays1D do
begin
GetRangeSource(edCCode.Lines, e, p1, p2);
if InRange(Y,p1.Line, p2.Line) then
begin
ShowElement(ASender,e);
Exit;
end;
end;
for e in pas.GlobalArrays2D do
begin
GetRangeSource(edCCode.Lines, e, p1, p2);
if InRange(Y,p1.Line, p2.Line) then
begin
ShowElement(ASender,e);
Exit;
end;
end;
for e in pas.Classes do
begin
GetRangeSource(edCCode.Lines, e, p1, p2);
if InRange(Y,p1.Line, p2.Line) then
begin
ShowElement(ASender,e);
Exit;
end;
end;
end;
procedure TfrmMain.edCCodeChange(Sender:TObjecT);
var
tl: Integer;t:string;
c:string;
begin
tl := edPascalCode.TopLine;
c := edCCode.Text;
if task<>nil then
if task.Status in [TTaskStatus.Running,TTaskStatus.WaitingToRun] then
begin
task.Cancel;
task.Wait(300);
end;
ProgressBar1.Position := 0;
ProgressBar1.Min := 0;
ProgressBar1.Max := 100;
StatusBar1.Panels[1].Text := 'Converting...';
edPascalCode.Enabled := False;
edPascalCode.Color := $000033;
ListBox1.Clear;
task := TTask.Create(
procedure
var p:TPascalUnit; n:string;
begin
if pas<>nil then
n:= pas.Name
else
n := 'tmp';
p := TPascalUnit.Create(nil);
c_to_pas(c,t,n,
// callback to report progress
procedure(progress:double;const text:string)
begin
TThread.Synchronize(TThread.CurrentThread,
procedure
begin
if progress < 1 then
begin
ProgressBar1.Position := round(Progress * 100);
Statusbar1.Panels[2].Text := round(Progress * 100).toString+'% '+ Text
end
else
begin
ProgressBar1.Position := 0;
Statusbar1.Panels[2].Text := '';
end;
if ListBox1.Count>0 then
ListBox1.Perform(lb_SetTopIndex,ListBox1.Count-1,0);
end);
end,
p);
TThread.Synchronize(TThread.CurrentThread,
procedure
begin
Pas.Free;
pas := p;
frmMain.Caption := Application.Title;
if pas.Name <> '' then
frmMain.Caption := p.Name + ' - ' + Caption;
UpdateTree;
edPascalCode.Text := pas.toPascal;
edPascalCode.TopLine := tl;
edPascalCode.Enabled := True;
//@@@ edPascalCode.OnChange(sender);
edPascalCode.Color := $00222827;
StatusBar1.Panels[1].Text := '';
p := nil;
end);
end);
task.Start;
end;
end.
|
unit KM_PathFindingAStarNew;
{$I KaM_Remake.inc}
interface
uses SysUtils, Math, KromUtils, KM_PathFinding,
KM_CommonClasses, KM_Defaults, KM_Terrain, KM_Points, BinaryHeap;
type
TANode = class
X,Y: SmallInt;
CostTo: Word;
Estim: Word;
Parent: TANode;
end;
//This is a helper class for TTerrain
//Here should be pathfinding and all associated stuff
//I think we should refactor this unit and move some TTerrain methods here
TPathFindingAStarNew = class(TPathFinding)
private
fHeap: TBinaryHeap;
fMinN: TANode;
fOpenRef: array of array of TANode; //References to OpenList, Sized as map
fUsedNodes: array of TANode; //Used to make Reset more efficient
fUsedNodeCount: Integer;
function HeapCmp(A,B: Pointer): Boolean;
function GetNodeAt(X,Y: SmallInt): TANode;
procedure Flush;
protected
function MakeRoute: Boolean; override;
procedure ReturnRoute(NodeList: TKMPointList); override;
public
constructor Create;
destructor Destroy; override;
end;
implementation
{ TPathFindingAStarNew }
constructor TPathFindingAStarNew.Create;
begin
inherited;
fHeap := TBinaryHeap.Create(High(Word));
fHeap.Cmp := HeapCmp;
end;
destructor TPathFindingAStarNew.Destroy;
begin
Flush;
fHeap.Free;
inherited;
end;
function TPathFindingAStarNew.HeapCmp(A, B: Pointer): Boolean;
begin
if A = nil then
Result := True
else
Result := (B = nil) or (TANode(A).Estim + TANode(A).CostTo < TANode(B).Estim + TANode(B).CostTo);
end;
function TPathFindingAStarNew.GetNodeAt(X,Y: SmallInt): TANode;
begin
//Cell is new
if fOpenRef[Y,X] = nil then
begin
fOpenRef[Y,X] := TANode.Create;
fOpenRef[Y,X].X := X;
fOpenRef[Y,X].Y := Y;
if Length(fUsedNodes) <= fUsedNodeCount then
SetLength(fUsedNodes, fUsedNodeCount + 64);
fUsedNodes[fUsedNodeCount] := fOpenRef[Y,X];
Inc(fUsedNodeCount);
end;
Result := fOpenRef[Y,X];
end;
procedure TPathFindingAStarNew.Flush;
var
I: Integer;
begin
//Reverse seems to work ~10% faster (cos of cache access probably)
for I := fUsedNodeCount - 1 downto 0 do
begin
fOpenRef[fUsedNodes[I].Y, fUsedNodes[I].X] := nil;
fUsedNodes[I].Free;
end;
fUsedNodeCount := 0;
end;
function TPathFindingAStarNew.MakeRoute: Boolean;
const c_closed = 65535;
var
N: TANode;
X, Y: Word;
NewCost: Word;
begin
//Clear previous data
Flush;
//Check that fOpenRef has been initialised (running SetLength when it's already correct size
//is inefficient with such a large array, SetLength doesn't seem to test for that condition
//because the CPU debugger runs through all of SetLength anyway on both dimensions)
if (Length(fOpenRef) <> gTerrain.MapY+1) or (Length(fOpenRef[0]) <> gTerrain.MapX+1) then
SetLength(fOpenRef, gTerrain.MapY+1, gTerrain.MapX+1);
//Initialize first element
N := GetNodeAt(fLocA.X, fLocA.Y);
N.Estim := EstimateToFinish(fLocA.X, fLocA.Y);
N.Parent := nil;
//Seed
fMinN := N;
while (fMinN <> nil) and not DestinationReached(fMinN.X, fMinN.Y) do
begin
fMinN.Estim := c_closed;
//Check all surrounding cells and issue costs to them
for Y := Math.max(fMinN.Y-1,1) to Math.min(fMinN.Y+1, gTerrain.MapY-1) do
for X := Math.max(fMinN.X-1,1) to Math.min(fMinN.X+1, gTerrain.MapX-1) do
if fOpenRef[Y,X] = nil then //Cell is new
begin
if CanWalkTo(KMPoint(fMinN.X, fMinN.Y), X, Y) then
begin
N := GetNodeAt(X, Y);
N.Parent := fMinN;
if IsWalkableTile(X, Y) then
begin
N.CostTo := fMinN.CostTo + MovementCost(fMinN.X, fMinN.Y, X, Y);
N.Estim := EstimateToFinish(X,Y);
fHeap.Push(N);
end
else //If cell doen't meets Passability then mark it as Closed
N.Estim := c_closed;
end;
end
else //Else cell is old
begin
//If route through new cell is shorter than ORef[Y,X] then
if fOpenRef[Y,X].Estim <> c_closed then
if CanWalkTo(KMPoint(fMinN.X, fMinN.Y), X, Y) then
begin
NewCost := MovementCost(fMinN.X, fMinN.Y, X, Y);
if fMinN.CostTo + NewCost < fOpenRef[Y,X].CostTo then
begin
fOpenRef[Y,X].Parent := fMinN;
fOpenRef[Y,X].CostTo := fMinN.CostTo + NewCost;
end;
end;
end;
//Find next cell with least (Estim+CostTo)
if fHeap.IsEmpty then
Break;
fMinN := fHeap.Pop;
end;
//Route found, no longer need the lookups
fHeap.Clear;
Result := DestinationReached(fMinN.X, fMinN.Y);
end;
procedure TPathFindingAStarNew.ReturnRoute(NodeList: TKMPointList);
var
N: TANode;
begin
NodeList.Clear;
//Assemble the route
N := fMinN;
while N <> nil do
begin
NodeList.Add(KMPoint(N.X, N.Y));
N := N.Parent;
end;
//Reverse the list, since path is assembled LocB > LocA
NodeList.Inverse;
//Cache long paths
if CACHE_PATHFINDING and (NodeList.Count > 20) then
AddToCache(NodeList);
end;
end.
|
UNIT MyFrxPDFPage;
INTERFACE
uses
Windows, Messages, SysUtils, Classes, Graphics, Menus, Controls, Variants,
frxClass, frxDsgnIntf, fs_iinterpreter, frxXML, frxXMLSerializer,
MyPDFRender, MyChromePDFRender;
type
TMyFrxPDFSource =
(
srcFileFromDisk,
srcEmbeddedFile,
srcFileFromDB
);
TMyFrxPDFPageView = class(TfrxView)
private
FPDFSource : TMyFrxPDFSource;
FPDFRender : TCustomMyPDFRender;
FVisiblePDFPage : integer;
FFileFromDisk : string;
FEmbeddedFile : TCustomMyPDFRender;
FVectorDrawing : boolean;
FAutoRotate : boolean;
FCenterInBounds : boolean;
function GetSourceIsEmbeddedFile(): boolean;
function GetSourceIsFileFromDB(): boolean;
function GetSourceIsFileFromDisk(): boolean;
procedure SetSourceIsEmbeddedFile(const Value: boolean);
procedure SetSourceIsFileFromDB(const Value: boolean);
procedure SetSourceIsFileFromDisk(const Value: boolean);
procedure SetPDFSource(ANewSource: TMyFrxPDFSource);
procedure SetEmbeddedFile(const Value: TCustomMyPDFRender);
function GetTotalPDFPages(): integer;
procedure SetVisiblePDFPage(const Value: integer);
procedure LoadPDFFromSource();
procedure SetFileFromDisk(const Value: string);
procedure SetVectorDrawing(const Value: boolean);
procedure SetAutoRotate(const Value: boolean);
procedure SetCenterInBounds(const Value: boolean);
(*
function CreateMetafile(): TMetafile;
*)
protected
procedure AssignTo(Dest: TPersistent); override;
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToStream(Stream: TStream;
SaveChildren: Boolean;
SaveDefaultValues: Boolean); override;
public
class function GetDescription(): String; override;
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
procedure GetData(); override;
procedure Draw(Canvas: TCanvas; ScaleX, ScaleY, OffsetX, OffsetY: Extended); override;
published
property SourceIsFileFromDisk: boolean read GetSourceIsFileFromDisk write SetSourceIsFileFromDisk;
property SourceIsEmbeddedFile: boolean read GetSourceIsEmbeddedFile write SetSourceIsEmbeddedFile;
property SourceIsFileFromDB: boolean read GetSourceIsFileFromDB write SetSourceIsFileFromDB;
property FileFromDisk: string read FFileFromDisk write SetFileFromDisk;
property EmbeddedFile: TCustomMyPDFRender read FEmbeddedFile write SetEmbeddedFile;
property TotalPDFPages: integer read GetTotalPDFPages;
property VisiblePDFPage: integer read FVisiblePDFPage write SetVisiblePDFPage;
property VectorDrawing: boolean read FVectorDrawing write SetVectorDrawing;
property AutoRotate: boolean read FAutoRotate write SetAutoRotate;
property CenterInBounds: boolean read FCenterInBounds write SetCenterInBounds;
published
property Frame;
property TagStr;
property Cursor;
property DataField;
property DataSet;
property DataSetName;
end;
TMyFrxPDFPageViewObject = class(TComponent) // fake component for Delphi's Components-Palette
end;
TMyFrxPDFPageViewRTTI = class(TfsRTTIModule)
public
constructor Create(AScript : TfsScript); override;
end;
TfrxCustomMyPDFRenderProperty=class(TfrxClassProperty)
public
function GetValue(): string; override;
function GetAttributes: TfrxPropertyAttributes; override;
function Edit(): boolean; override;
end;
IMPLEMENTATION
uses Dialogs, fqbUtils, frxPrinter;
VAR
_LogoForFRDesigner : TBitmap;
//##############################################################################
{ TMyFrxPDFPageView }
//##############################################################################
constructor TMyFrxPDFPageView.Create(AOwner: TComponent);
begin
inherited;
FVisiblePDFPage:=1;
FVectorDrawing:=true;
FAutoRotate:=true;
FCenterInBounds:=false;
FPDFRender:=TMyChromePDFRender.Create();
FEmbeddedFile:=TMyChromePDFRender.Create();
SetPDFSource(srcFileFromDisk);
Width:=100;
Height:=140;
end;
//------------------------------------------------------------------------------
destructor TMyFrxPDFPageView.Destroy();
begin
FPDFRender.Free();
FEmbeddedFile.Free();
inherited;
end;
////////////////////////////////////////////////////////////////////////////////
class function TMyFrxPDFPageView.GetDescription(): String;
begin
Result:='MyFrxPDFPageView';
end;
//------------------------------------------------------------------------------
procedure TMyFrxPDFPageView.AssignTo(Dest: TPersistent);
begin
inherited;
if Dest is TMyFrxPDFPageView then
TMyFrxPDFPageView(Dest).FEmbeddedFile.Assign(FEmbeddedFile);
end;
//------------------------------------------------------------------------------
procedure TMyFrxPDFPageView.SetEmbeddedFile(const Value: TCustomMyPDFRender);
begin
FEmbeddedFile.Assign(Value);
end;
//------------------------------------------------------------------------------
procedure TMyFrxPDFPageView.LoadFromStream(Stream: TStream);
begin
inherited;
//...
end;
//------------------------------------------------------------------------------
procedure TMyFrxPDFPageView.SaveToStream(Stream: TStream;
SaveChildren: Boolean; SaveDefaultValues: Boolean);
begin
inherited;
//...
end;
////////////////////////////////////////////////////////////////////////////////
procedure TMyFrxPDFPageView.SetPDFSource(ANewSource: TMyFrxPDFSource);
begin
FPDFSource:=ANewSource;
end;
//------------------------------------------------------------------------------
function TMyFrxPDFPageView.GetSourceIsFileFromDisk(): boolean;
begin
Result:=(FPDFSource=srcFileFromDisk);
end;
//------------------------------------------------------------------------------
procedure TMyFrxPDFPageView.SetSourceIsFileFromDisk(const Value: boolean);
begin
if Value then SetPDFSource(srcFileFromDisk);
end;
//------------------------------------------------------------------------------
function TMyFrxPDFPageView.GetSourceIsEmbeddedFile(): boolean;
begin
Result:=(FPDFSource=srcEmbeddedFile);
end;
//------------------------------------------------------------------------------
procedure TMyFrxPDFPageView.SetSourceIsEmbeddedFile(const Value: boolean);
begin
if Value then SetPDFSource(srcEmbeddedFile);
end;
//------------------------------------------------------------------------------
function TMyFrxPDFPageView.GetSourceIsFileFromDB(): boolean;
begin
Result:=(FPDFSource=srcFileFromDB);
end;
//------------------------------------------------------------------------------
procedure TMyFrxPDFPageView.SetSourceIsFileFromDB(const Value: boolean);
begin
if Value then SetPDFSource(srcFileFromDB);
end;
////////////////////////////////////////////////////////////////////////////////
procedure TMyFrxPDFPageView.SetFileFromDisk(const Value: string);
begin
FFileFromDisk:=Value;
end;
//------------------------------------------------------------------------------
function TMyFrxPDFPageView.GetTotalPDFPages(): integer;
begin
Result:=FPDFRender.PagesCount;
end;
//------------------------------------------------------------------------------
procedure TMyFrxPDFPageView.SetVisiblePDFPage(const Value: integer);
begin
FVisiblePDFPage:=Value;
end;
//------------------------------------------------------------------------------
procedure TMyFrxPDFPageView.SetVectorDrawing(const Value: boolean);
begin
FVectorDrawing:=Value;
end;
//------------------------------------------------------------------------------
procedure TMyFrxPDFPageView.SetAutoRotate(const Value: boolean);
begin
FAutoRotate := Value;
end;
//------------------------------------------------------------------------------
procedure TMyFrxPDFPageView.SetCenterInBounds(const Value: boolean);
begin
FCenterInBounds := Value;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TMyFrxPDFPageView.LoadPDFFromSource();
var
mem : TMemoryStream;
begin
FPDFRender.Clear();
case FPDFSource of
srcFileFromDisk: FPDFRender.LoadPDFFromFile(FFileFromDisk);
srcEmbeddedFile: FPDFRender.Assign(FEmbeddedFile);
srcFileFromDB:
begin
FPDFRender.Clear();
if IsDataField and DataSet.IsBlobField(DataField) then
begin
mem:=TMemoryStream.Create();
try
DataSet.AssignBlobTo(DataField, mem);
mem.Position:=0;
FPDFRender.LoadPDFFromStream(mem);
finally
FreeAndNil(mem);
end;
end;
end;
else raise EMyPDFRendererError.Create('PDFSourceType = ?????');
end;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TMyFrxPDFPageView.GetData();
begin
inherited;
LoadPDFFromSource();
end;
//------------------------------------------------------------------------------
(*
function TMyFrxPDFPageView.CreateMetafile(): TMetafile;
var
hPrinterCanvas : THandle;
EMFCanvas : TMetafileCanvas;
R : TRect;
begin
if frxPrinters.HasPhysicalPrinters then
hPrinterCanvas := frxPrinters.Printer.Canvas.Handle
else
hPrinterCanvas := GetDC(0);
Result:=TMetafile.Create();
Result.Width := Round(Width * GetDeviceCaps(hPrinterCanvas, LOGPIXELSX) / 96);
Result.Height := Round(Height * GetDeviceCaps(hPrinterCanvas, LOGPIXELSY) / 96);
EMFCanvas := TMetafileCanvas.Create(Result, hPrinterCanvas);
try
//R:=Rect(0, 0, Result.Width, Result.Height);
R:=Rect(0, 0, Round(Width * 1440 / 96), Round(Height * 1440 / 96));
FPDFRender.RenderPDFToCanvas(EMFCanvas, R, FVisiblePDFPage, 600, 600,
FAutoRotate, FCenterInBounds)
finally
FreeAndNil(EMFCanvas);
end;
if not frxPrinters.HasPhysicalPrinters then
ReleaseDC(0, hPrinterCanvas);
end;
*)
//------------------------------------------------------------------------------
procedure GetPrinterDPI(out ADPIX: integer; out ADPIY: integer);
var
hPrinterCanvas : THandle;
begin
if frxPrinters.HasPhysicalPrinters then
begin
hPrinterCanvas := frxPrinters.Printer.Canvas.Handle;
ADPIX:=GetDeviceCaps(hPrinterCanvas, LOGPIXELSX);
ADPIY:=GetDeviceCaps(hPrinterCanvas, LOGPIXELSY);
end
else
begin
ADPIX := 600;
ADPIY := 600;
end;
end;
//------------------------------------------------------------------------------
procedure TMyFrxPDFPageView.Draw(Canvas: TCanvas; ScaleX, ScaleY, OffsetX,
OffsetY: Extended);
var
R : TRect;
bmp : Graphics.TBitmap;
(*
EMF : TMetafile;
*)
iDPIX : integer;
iDPIY : integer;
begin
BeginDraw(Canvas, ScaleX, ScaleY, OffsetX, OffsetY);
GetPrinterDPI(iDPIX, iDPIY);
DrawBackground();
try
try
LoadPDFFromSource();
if not FPDFRender.IsEmpty() then
begin
R:=Rect(FX, FY, FX1, FY1);
if FVectorDrawing then
begin
FPDFRender.RenderPDFToCanvas(Canvas, R, FVisiblePDFPage, iDPIX, iDPIY,
FAutoRotate, FCenterInBounds)
end
else
begin
bmp:=TBitmap.Create();
try
bmp.Width:=FDX;
bmp.Height:=FDY;
FPDFRender.RenderPDFToBitmap(bmp, FVisiblePDFPage, iDPIX, iDPIY,
FAutoRotate, FCenterInBounds,
false);
Canvas.Draw(FX, FY, bmp);
finally
FreeAndNil(bmp);
end;
(*
EMF:= CreateMetafile();
try
Canvas.StretchDraw(Rect(FX, FY, FX1, FY1), EMF);
finally
FreeAndNil(EMF);
end;
*)
end;
end
else
if IsDesigning then
begin
Canvas.Draw(FX, FY, _LogoForFRDesigner);
end;
except
on E: Exception do
begin
//Draw an Exception-Text
Canvas.Font.Color:=clRed;
Canvas.TextOut(FX, FY, E.Message);
end;
end;
finally
DrawFrame();
end;
end;
//##############################################################################
{ TMyFrxPDFPageViewRTTI }
//##############################################################################
constructor TMyFrxPDFPageViewRTTI.Create(AScript: TfsScript);
begin
inherited;
AScript.AddClass(TMyFrxPDFPageView, 'TMyFrxPDFPageView');
end;
//##############################################################################
{ TfrxCustomMyPDFRenderProperty }
//##############################################################################
function TfrxCustomMyPDFRenderProperty.GetValue(): string;
var
Render : TCustomMyPDFRender;
begin
Render:=TCustomMyPDFRender(GetOrdValue());
if Render.IsEmpty() then
Result:='< empty >'
else
Result:='PDF: '+IntToStr(Render.SizeInBytes div 1024)+' kB';
end;
//------------------------------------------------------------------------------
function TfrxCustomMyPDFRenderProperty.GetAttributes(): TfrxPropertyAttributes;
begin
Result:=[paDialog, paReadOnly];
end;
//------------------------------------------------------------------------------
function YesNoDialog(const AMessage, ACaption: string;
ADefaultVal:boolean):boolean;
var
iButtonDef : integer;
begin
if ADefaultVal then
iButtonDef:=MB_DEFBUTTON1
else
iButtonDef:=MB_DEFBUTTON2;
//Result:=Application.MessageBox(PChar(sMessage),PChar(sCaption),
Result:=Windows.MessageBox(0,PChar(AMessage),PChar(ACaption),
iButtonDef or MB_YESNO or MB_ICONQUESTION
)=IDYES;
end;
//------------------------------------------------------------------------------
function TfrxCustomMyPDFRenderProperty.Edit(): boolean;
var
dlg : TOpenDialog;
Render : TCustomMyPDFRender;
bDoSearch : boolean;
begin
Render:=TCustomMyPDFRender(GetOrdValue());
bDoSearch:=true;
if not Render.IsEmpty() then
begin
if YesNoDialog('Do you want to clear embedded-file?','Clear',false) then
begin
Render.Clear();
bDoSearch:=false;
end;
end;
if bDoSearch then
begin
dlg:=TOpenDialog.Create(nil);
try
dlg.Filter:='PDF files (*.pdf)|*.pdf';
dlg.FileName:='';
Result:=dlg.Execute();
Render.LoadPDFFromFile(dlg.FileName);
if Component is TMyFrxPDFPageView then
TMyFrxPDFPageView(Component).SourceIsEmbeddedFile:=true;
finally
dlg.Free();
end;
end;
end;
//##############################################################################
procedure LoadLogoForFRDesigner(); //better as from Resource
const
LOGO_BMP_FR_DESIGNER_BASE64 =
'Qk32AAAAAAAAAHYAAAAoAAAAEAAAABAAAAABAAQAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAA'+
'AAAAAAAAAAgAAAgAAAAICAAIAAAACAAIAAgIAAAICAgADAwMAAAAD/AAD/AAAA//8A/wAA'+
'AP8A/wD//wAA////ADM4iIiIiIiDMwAAAAAAAIMzD//////wgzMP//////CDMw//////8I'+
'MzD//////wgzMP//////CDMw//////8IMzD//////wg5mZmZmZ//CDmZmZmZn/8IOZmZmZ'+
'mf/wg5mZmZmZAAAzmZmZmZkPAzMzD////wAzMzMAAAAAAzMz';
var
mem : TMemoryStream;
sDecoded : string;
begin
mem:=TMemoryStream.Create();
try
sDecoded:=fqbBase64Decode(LOGO_BMP_FR_DESIGNER_BASE64);
mem.Write(PChar(sDecoded)^, Length(sDecoded));
mem.Position:=0;
_LogoForFRDesigner.LoadFromStream(mem);
finally
FreeAndNil(mem);
end;
_LogoForFRDesigner.Transparent:=true;
_LogoForFRDesigner.TransparentColor:=
_LogoForFRDesigner.Canvas.Pixels[0,_LogoForFRDesigner.Height-1];
end;
//------------------------------------------------------------------------------
INITIALIZATION
_LogoForFRDesigner:=TBitmap.Create();
LoadLogoForFRDesigner();
frxObjects.RegisterObject1(TMyFrxPDFPageView, _LogoForFRDesigner);
fsRTTIModules.Add(TMyFrxPDFPageViewRTTI);
//--- maybe: frxHideProperties(TMyFrxPDFPageView, 'TotalPDFPages');
frxPropertyEditors.Register(
TypeInfo(TCustomMyPDFRender),
nil,
'',
TfrxCustomMyPDFRenderProperty
);
FINALIZATION
frxObjects.Unregister(TMyFrxPDFPageView);
_LogoForFRDesigner.Free;
END.
|
unit PSLExportKind;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, AncestorEnum, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, cxStyles, cxCustomData, cxFilter,
cxData, cxDataStorage, cxEdit, Data.DB, cxDBData, dsdAddOn, dsdDB, dsdAction,
Vcl.ActnList, dxBarExtItems, dxBar, cxClasses, cxPropertiesStore,
Datasnap.DBClient, cxGridLevel, cxGridCustomView, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxGrid, cxPCdxBarPopupMenu, cxPC,
dxSkinsCore, dxSkinsDefaultPainters, dxSkinscxPCPainter, dxSkinsdxBarPainter,
Vcl.Menus, dxSkinBlack, dxSkinBlue, dxSkinBlueprint, dxSkinCaramel,
dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinDevExpressDarkStyle,
dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast,
dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky,
dxSkinMcSkin, dxSkinMoneyTwins, dxSkinOffice2007Black, dxSkinOffice2007Blue,
dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver,
dxSkinOffice2010Black, dxSkinOffice2010Blue, dxSkinOffice2010Silver,
dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus,
dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008,
dxSkinTheAsphaltWorld, dxSkinValentine, dxSkinVS2010, dxSkinWhiteprint,
dxSkinXmas2008Blue;
type
TPSLExportKindForm = class(TAncestorEnumForm)
Name: TcxGridDBColumn;
Code: TcxGridDBColumn;
EnumName: TcxGridDBColumn;
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
{$R *.dfm}
initialization
RegisterClass(TPSLExportKindForm);
end.
|
unit Favorite_u;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ImgList, IniFiles, StdCtrls, Buttons, ComCtrls, Advanced;
type
TdlgFavorite = class(TForm)
imgListExt: TImageList;
btnOk: TBitBtn;
btnCancel: TBitBtn;
lvFavorites: TListView;
btnAdd: TSpeedButton;
btnDelete: TSpeedButton;
btnClear: TSpeedButton;
DlgOpen: TOpenDialog;
procedure FormCreate(Sender: TObject);
procedure btnClearClick(Sender: TObject);
procedure btnAddClick(Sender: TObject);
procedure btnDeleteClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
dlgFavorite: TdlgFavorite;
implementation
{$R *.dfm}
procedure DeleteFormFav(Index:LongWord);
var Fav:TIniFile;
Count:Integer;
Begin
Fav:=TIniFile.Create(ExtractFileDir(Application.Exename)+'\Fav.ini');
Count:=Fav.ReadInteger('Main','Count',0);
Dec(Count);
Fav.WriteInteger('Main','Count',Count);
Fav.DeleteKey('Favorite'+IntToStr(Index),'Caption');
Fav.DeleteKey('Favorite'+IntToStr(Index),'ImageIndex');
Fav.DeleteKey('Favorite'+IntToStr(Index),'Size');
Fav.DeleteKey('Favorite'+IntToStr(Index),'Pach');
Fav.Free;
End;
procedure AddToFavorite(FileName:String);
var Fav:TIniFile;
Count:Integer;
FileStream:TFileStream;
Size:LongWord;
Pach:String;
Begin
FileSetAttr(ExtractFileDir(Application.Exename)+'\Fav.ini',faArchive);
FileStream:=TFileStream.Create(FileName,fmOpenRead);
Size:=FileStream.Size;
FileStream.Free;
Fav:=TIniFile.Create(ExtractFileDir(Application.Exename)+'\Fav.ini');
Count:=Fav.ReadInteger('Main','Count',0);
Inc(Count);
Fav.WriteInteger('Main','Count',Count);
Fav.WriteString('Favorite'+IntToStr(Count-1),'Caption',ExtractFileName(FileName));
Fav.WriteInteger('Favorite'+IntToStr(Count-1),'ImageIndex',GetImgIndexByExt(ExtractFileExt(FileName)));
Fav.WriteInteger('Favorite'+IntToStr(Count-1),'Size',Size);
Pach:=ExtractFileDir(FileName);
If Pach[Length(Pach)]<>'\' Then Pach:=Pach+'\';
Fav.WriteString('Favorite'+IntToStr(Count-1),'Pach',Pach);
Fav.Free;
Size:=0;
End;
procedure AddToFavoriteValuesOnly(FName,FSize,Pach:String;ImgIndex:Byte);
var Fav:TIniFile;
Count:Integer;
Begin
Fav:=TIniFile.Create(ExtractFileDir(Application.Exename)+'\Fav.ini');
Count:=Fav.ReadInteger('Main','Count',0);
Inc(Count);
Fav.WriteInteger('Main','Count',Count);
Fav.WriteString('Favorite'+IntToStr(Count-1),'Caption',FName);
Fav.WriteInteger('Favorite'+IntToStr(Count-1),'ImageIndex',ImgIndex);
Fav.WriteString('Favorite'+IntToStr(Count-1),'Size',FSize);
Fav.WriteString('Favorite'+IntToStr(Count-1),'Pach',Pach);
Fav.Free;
End;
procedure ReadFavorites;
Var Fav:TIniFile;
Count:Integer;
Index:Integer;
Item:TListItem;
Begin
Fav:=TIniFile.Create(ExtractFileDir(Application.Exename)+'\Fav.ini');
Count:=Fav.ReadInteger('Main','Count',0);
If Count>0 Then
For Index:=0 To Count-1 Do
Begin
Item:=dlgFavorite.lvFavorites.Items.Add;
Item.Caption:=Fav.ReadString('Favorite'+IntToStr(Index),'Caption','');
Item.ImageIndex:=Fav.ReadInteger('Favorite'+IntToStr(Index),'ImageIndex',0);
Item.SubItems.Add(IntToStr(Fav.ReadInteger('Favorite'+IntToStr(Index),'Size',0)));
Item.SubItems.Add(Fav.ReadString('Favorite'+IntToStr(Index),'Pach',''));
End;
Fav.Free;
End;
procedure TdlgFavorite.FormCreate(Sender: TObject);
begin
ReadFavorites;
imgListExt.BkColor:=lvFavorites.Color;
imgListExt.BlendColor:=lvFavorites.Color;
Caption:=ReadFromLanguage('Windows','wndFavorites',Caption);
btnAdd.Caption:=ReadFromLanguage('Buttons','btnAdd',btnAdd.Caption);
btnDelete.Caption:=ReadFromLanguage('Buttons','btnDelete',btnDelete.Caption);
btnClear.Caption:=ReadFromLanguage('Buttons','btnClear',btnClear.Caption);
btnCancel.Caption:=ReadFromLanguage('Buttons','btnCancel',btnCancel.Caption);
lvFavorites.Columns[0].Caption:=ReadFromLanguage('ListItems','liFile',lvFavorites.Columns[0].Caption);
lvFavorites.Columns[1].Caption:=ReadFromLanguage('ListItems','liSize',lvFavorites.Columns[1].Caption);
lvFavorites.Columns[2].Caption:=ReadFromLanguage('ListItems','liPath',lvFavorites.Columns[2].Caption);
DlgOpen.Title:=ReadFromLanguage('Dialogs','dlgOpen',DlgOpen.Title);
end;
procedure TdlgFavorite.btnClearClick(Sender: TObject);
begin
lvFavorites.Clear;
FileSetAttr(ExtractFileDir(Application.Exename)+'\Fav.ini',faArchive);
DeleteFile(ExtractFileDir(Application.Exename)+'\Fav.ini');
end;
procedure TdlgFavorite.btnAddClick(Sender: TObject);
begin
If DlgOpen.Execute(Handle) Then
Begin
AddToFavorite(DlgOpen.FileName);
lvFavorites.Clear;
ReadFavorites;
End;
end;
procedure TdlgFavorite.btnDeleteClick(Sender: TObject);
Var Index:LongWord;
begin
If lvFavorites.SelCount<>0 Then
If MessageBox(Handle,Pchar(ReadFromLanguage('Messages','Shure','Are you shure?')),'WinMZF',MB_YESNO+MB_ICONQUESTION)=IDYES Then
Begin
FileSetAttr(ExtractFileDir(Application.Exename)+'\Fav.ini',faArchive);
DeleteFile(ExtractFileDir(Application.Exename)+'\Fav.ini');
lvFavorites.DeleteSelected;
For Index:=0 To lvFavorites.Items.Count-1 Do
AddToFavoriteValuesOnly(lvFavorites.Items[Index].Caption,
lvFavorites.Items[Index].SubItems[0],
lvFavorites.Items[Index].SubItems[1],
lvFavorites.Items[Index].ImageIndex);
End;
end;
end.
|
unit Language;
{ Cluster: Language
}
{ Explanation:
Zusammenstellung der Buchstaben einer Sprache.
Das Programm wird z.B. zur Bibelanalyse Urtext eingesetzt.
- Klasse Language
- Klasse German
- Klasse Greek
- Klasse Hebrew
}
{ Indexing:
Keywords: Sprache, Bibel
Author : Dr. P.G. Zint
Street : Holzheimer Str. 96
City : 57299 Burbach
Phone : 02736-3378
Created : 21.08.1995
Revised : 27.04.2002
Compile : Delphi 5
}
{ Changing:
03.10.1995 Neue Features: Order_of.
26.10.1997 Eingerichtet für Delphi 2.0
28.10.1997 Read_Code neu
15.11.1997 Hebrew.Read_Code neu
16.11.1997 Font_Code neu
22.11.1997 Class-Header neu
28.03.2002 Anpassungen für Windows XP und neue Fonts.
27.04.2002 Code_of_OLB neu
}
interface
const
Code_Zeichen = '_'; // Zeichen zwischen 2 Code-Zahlen im Urtext.
type
TLanguage = class
constructor Create;
function Get_Letter_max: Byte;
// Anzahl der Buchstaben der Sprache.
function Get_Lower (i: Byte): string; virtual; abstract;
// Liefert den Namen des i. Kleinbuchstabens.
function Get_Upper (i: Byte): string; virtual;
// Liefert den Namen des i. Großbuchstabens.
function Get_Random_Word (l: Byte): string;
{ Liefert einen zufälligen Wortstring der Länge l.
Der Wordstring besteht aus den Nummern der Buchstaben. }
{ Features des durch Latin_Letter
in der Online Bible definierten Buchstaben: }
function Order (Latin_Letter: Char): Integer; virtual; abstract;
// Ordnungszahl: z.B. a = 1, b = 2 etc.
function Code (Latin_Letter: Char): Integer; virtual;
// Zahlencode der Sprache.
function Name (Latin_Letter: Char): string; virtual;
// Name des Buchstaben.
function Read_Code (Latin_Letter: Char): Char; virtual;
// Normaler Lese-Code des Buchstaben.
function Font_Code (Latin_Letter: Char): Char; virtual;
// Code des Buchstaben zur Darstellung im WINWORD-Font.
// Urtext features:
function Code_of_OLB (s: string): string;
// Liefert Zahlencode xxx-yyy-... zum OLB-Wort s.
function Total_of_OLB (s: string): Integer;
// Liefert Totalwerte des Zahlencodes zum OLB-Wort s.
private
Letter_max: Byte; // Anzahl der Buchstaben.
end;
TGerman = class (TLanguage)
constructor Create;
function Get_Lower (i: Byte): string; override;
function Order (Latin_Letter: Char): Integer; override;
end;
TGreek = class (TLanguage)
constructor Create;
function Get_Lower (i: Byte): string; override;
function Order (Latin_Letter: Char): Integer; override;
function Code (Latin_Letter: Char): Integer; override;
function Name (Latin_Letter: Char): string; override;
function Read_Code (Latin_Letter: Char): Char; override;
function Font_Code (Latin_Letter: Char): Char; override;
function OLB_to_Symbol (Latin_Letter: Char): Char;
// Liefert Symbol-Font-Zeichen zum OLB-Zeichen Latin_Letter.
function OLB_to_TITUS (Latin_Letter: Char): Char;
// Liefert TITUS-Font-Zeichen zum OLB-Zeichen Latin_Letter.
function German_to_TITUS (Latin_Letter: Char): Char;
// Liefert TITUS-Font-Zeichen zum deutschen Zeichen Latin_Letter.
end;
THebrew = class (TLanguage)
constructor Create;
function Get_Lower (i: Byte): string; override;
function Order (Latin_Letter: Char): Integer; override;
function Code (Latin_Letter: Char): Integer; override;
function Name (Latin_Letter: Char): string; override;
function Read_Code (Latin_Letter: Char): Char; override;
function OLB_to_David (Latin_Letter: Char): Char;
// Liefert David-Font-Zeichen zum OLB-Zeichen Latin_Letter.
end;
implementation
uses SysUtils, Zeichen;
// TLanguage: -------------------------------------------------------
constructor TLanguage.Create;
begin
Letter_max := 1
end;
function TLanguage.Get_Letter_max: Byte;
begin
Result := Letter_max
end;
function TLanguage.Get_Upper (i: Byte): string;
begin
Result := First_Capital (Get_Lower (i))
end;
function TLanguage.Get_Random_Word (l: Byte): string;
var i: Byte; s: string;
begin
s := '';
for i := 1 to l do s := s + Chr (Succ (Random (Letter_max)));
Result := s
end;
function TLanguage.Code (Latin_Letter: Char): Integer;
begin
Result := Ord (Latin_Letter)
end;
function TLanguage.Name (Latin_Letter: Char): string;
begin
Result := Latin_Letter
end;
function TLanguage.Read_Code (Latin_Letter: Char): Char;
begin
Result := Latin_Letter
end;
function TLanguage.Font_Code (Latin_Letter: Char): Char;
begin
Result := Latin_Letter
end;
function TLanguage.Code_of_OLB (s: string): string;
var Len, i: Integer;
begin
Len := Length (s);
Result := '';
for i := 1 to Len do
begin
Result := Result + IntToStr (Code (s [i]));
if i < Len then Result := Result + Code_Zeichen
end
end;
function TLanguage.Total_of_OLB (s: string): Integer;
var i: Integer;
begin
Result := 0;
for i := 1 to Length (s) do Result := Result + Code (s [i])
end;
// TGerman: ---------------------------------------------------------
constructor TGerman.Create;
begin
Letter_max := 26
end;
function TGerman.Get_Lower (i: Byte): string;
begin
case i of
1: Result := 'a';
2: Result := 'b';
3: Result := 'c';
4: Result := 'd';
5: Result := 'e';
6: Result := 'f';
7: Result := 'g';
8: Result := 'h';
9: Result := 'i';
10: Result := 'j';
11: Result := 'k';
12: Result := 'l';
13: Result := 'm';
14: Result := 'n';
15: Result := 'o';
16: Result := 'p';
17: Result := 'q';
18: Result := 'r';
19: Result := 's';
20: Result := 't';
21: Result := 'u';
22: Result := 'v';
23: Result := 'w';
24: Result := 'x';
25: Result := 'y';
26: Result := 'z';
else Result := ''
end
end;
function TGerman.Order (Latin_Letter: Char): Integer;
begin
if Latin_Letter >= 'a'
then Result := Ord (Latin_Letter) - Ord ('a') + 1
else Result := Ord (Latin_Letter) - Ord ('A') + 1
end;
// TGreek: ----------------------------------------------------------
constructor TGreek.Create;
begin
Letter_max := 24
end;
function TGreek.Get_Lower (i: Byte): string;
begin // Nach K. Breest:
case i of {OnLine: Lies:}
1: Result := 'alpha'; {a a}
2: Result := 'beta'; {b b}
3: Result := 'gamma'; {g g}
4: Result := 'delta'; {d d}
5: Result := 'epsilon'; {e e}
6: Result := 'zeta'; {z z}
7: Result := 'eta'; {h e}
8: Result := 'theta'; {y t}
9: Result := 'jota'; {i i}
10: Result := 'kappa'; {k k}
11: Result := 'lambda'; {l l}
12: Result := 'my'; {m m}
13: Result := 'ny'; {n n}
14: Result := 'xi'; {x x}
15: Result := 'omicron'; {o o}
16: Result := 'pi'; {p p}
17: Result := 'rho'; {r r}
18: Result := 'sigma'; {s s}
19: Result := 'tau'; {t t}
20: Result := 'ypsilon'; {u u}
21: Result := 'phi'; {f f}
22: Result := 'chi'; {c c}
23: Result := 'psi'; {q p}
24: Result := 'omega'; {w o}
else Result := ''
end
end;
function TGreek.Order (Latin_Letter: Char): Integer;
begin
case Latin_Letter of
'a': Result := 1;
'b': Result := 2;
'g': Result := 3;
'd': Result := 4;
'e': Result := 5;
'z': Result := 6;
'h': Result := 7;
'y': Result := 8;
'i': Result := 9;
'k': Result := 10;
'l': Result := 11;
'm': Result := 12;
'n': Result := 13;
'x': Result := 14;
'o': Result := 15;
'p': Result := 16;
'r': Result := 17;
's',
'v': Result := 18;
't': Result := 19;
'u': Result := 20;
'f': Result := 21;
'c': Result := 22;
'q': Result := 23;
'w': Result := 24;
else Result := 0
end
end;
function TGreek.Code (Latin_Letter: Char): Integer;
begin
case Latin_Letter of
'a': Result := 1; // Alpha
'b': Result := 2; // Beta
'g': Result := 3; // Gamma
'd': Result := 4; // Delta
'e': Result := 5; // Epsilon
'z': Result := 7; // Zeta
'h': Result := 8; // Eta !
'y': Result := 9; // Theta !
'i': Result := 10; // Jota
'k': Result := 20; // Kappa
'l': Result := 30; // Lambda
'm': Result := 40; // My
'n': Result := 50; // Ny
'x': Result := 60; // Xi
'o': Result := 70; // Omicron
'p': Result := 80; // Pi
'r': Result := 100; // Rho
's',
'v': Result := 200; // Sigma !
't': Result := 300; // Tau
'u': Result := 400; // Ypsilon !
'f': Result := 500; // Phi
'c': Result := 600; // Chi
'q': Result := 700; // Psi !
'w': Result := 800; // Omega !
else Result := 0
end
end;
function TGreek.Name (Latin_Letter: Char): string;
begin
case Latin_Letter of
'a': Result := Get_Lower (1);
'b': Result := Get_Lower (2);
'g': Result := Get_Lower (3);
'd': Result := Get_Lower (4);
'e': Result := Get_Lower (5);
'z': Result := Get_Lower (6);
'h': Result := Get_Lower (7);
'y': Result := Get_Lower (8);
'i': Result := Get_Lower (9);
'k': Result := Get_Lower (10);
'l': Result := Get_Lower (11);
'm': Result := Get_Lower (12);
'n': Result := Get_Lower (13);
'x': Result := Get_Lower (14);
'o': Result := Get_Lower (15);
'p': Result := Get_Lower (16);
'r': Result := Get_Lower (17);
's',
'v': Result := Get_Lower (18);
't': Result := Get_Lower (19);
'u': Result := Get_Lower (20);
'f': Result := Get_Lower (21);
'c': Result := Get_Lower (22);
'q': Result := Get_Lower (23);
'w': Result := Get_Lower (24);
else Result := Blank
end
end;
function TGreek.Read_Code (Latin_Letter: Char): Char;
begin
case Latin_Letter of
'h': Result := 'e'; // OLB h -> Eta
'q': Result := 'p'; // OLB q -> Psi
'v': Result := 's'; // OLB v -> Schuß s = Sigma
'w': Result := 'o'; // OLB w -> Omega
// eigentlich: 'u': Result := 'y'; // OLB u -> Ypsilon
'y': Result := 't'; // OLB y -> Theta
else Result := Latin_Letter
end
end;
function TGreek.Font_Code (Latin_Letter: Char): Char;
begin
case Latin_Letter of
'q': Result := 'y';
'v': Result := 'j';
'y': Result := 'q';
else Result := Latin_Letter
end
end;
function TGreek.OLB_to_Symbol (Latin_Letter: Char): Char;
begin
case Latin_Letter of
'\': Result := #35;
'$': Result := #42;
#121: Result := #74;
#102: Result := #106;
#113: Result := #121;
else Result := Latin_Letter
end
end;
function TGreek.OLB_to_TITUS (Latin_Letter: Char): Char;
begin
case Latin_Letter of
'a': Result := Chr (215);
'b': Result := Chr (225);
'g': Result := Chr (217);
'd': Result := Chr (218);
'e': Result := Chr (219);
'z': Result := Chr (220);
'h': Result := Chr (221);
'y': Result := Chr (222);
'i': Result := Chr (223);
'k': Result := Chr (224);
'l': Result := Chr (226);
'm': Result := Chr (227);
'n': Result := Chr (228);
'x': Result := Chr (229);
'o': Result := 'o';
'p': Result := Chr (231);
'r': Result := Chr (232);
's': Result := Chr (233);
't': Result := Chr (234);
'u': Result := Chr (235);
'f': Result := Chr (236);
'c': Result := Chr (237);
'q': Result := Chr (238);
'w': Result := Chr (239);
'\': Result := Chr (47);
'$': Result := Chr (42);
else Result := Latin_Letter
end
end;
function TGreek.German_to_TITUS (Latin_Letter: Char): Char;
begin
case Latin_Letter of
'ä': Result := Chr (155);
'ü': Result := Chr (145);
'ö': Result := Chr (144);
'ß': Result := Chr (225);
'\': Result := Chr (47);
'$': Result := Chr (42);
else Result := Latin_Letter
end
end;
// THebrew: ---------------------------------------------------------
constructor THebrew.Create;
begin
Letter_max := 22
end;
function THebrew.Get_Lower (i: Byte): string;
begin
case i of {OnLine: Lies:}
1: Result := 'aleph'; {a a}
2: Result := 'beth'; {b b}
3: Result := 'gimel'; {g g}
4: Result := 'daleth'; {d d}
5: Result := 'he'; {h h}
6: Result := 'waw'; {w w}
7: Result := 'zayin'; {z z}
8: Result := 'cheth'; {x c}
9: Result := 'teth'; {j t}
10: Result := 'yod'; {y y}
11: Result := 'kaph'; {k k}
12: Result := 'lamedh'; {l l}
13: Result := 'mem'; {m m}
14: Result := 'nun'; {n n}
15: Result := 'samekh'; {o s}
16: Result := 'ayin'; {e a}
17: Result := 'peh'; {p p}
18: Result := 'tsadhe'; {u t}
19: Result := 'qoph'; {q q}
20: Result := 'resh'; {r r}
21: Result := 's(h)in'; {v s}
22: Result := 'tau'; {t t}
else Result := ''
end
end;
function THebrew.Order (Latin_Letter: Char): Integer;
begin
case Latin_Letter of
'a': Result := 1;
'b': Result := 2;
'g': Result := 3;
'd': Result := 4;
'h': Result := 5;
'w': Result := 6;
'z': Result := 7;
'x': Result := 8;
'j': Result := 9;
'y': Result := 10;
'k',
'K': Result := 11;
'l': Result := 12;
'm',
'M': Result := 13;
'n',
'N': Result := 14;
'o': Result := 15;
'e': Result := 16;
'p',
'P': Result := 17;
'u',
'U': Result := 18;
'q': Result := 19;
'r': Result := 20;
'v',
's': Result := 21;
't': Result := 22;
else Result := 0
end
end;
function THebrew.Code (Latin_Letter: Char): Integer;
begin
case Latin_Letter of
'a': Result := 1;
'b': Result := 2;
'g': Result := 3;
'd': Result := 4;
'h': Result := 5;
'w': Result := 6;
'z': Result := 7;
'x': Result := 8;
'j': Result := 9;
'y': Result := 10;
'k',
'K': Result := 20;
'l': Result := 30;
'm',
'M': Result := 40;
'n',
'N': Result := 50;
'o': Result := 60;
'e': Result := 70;
'p',
'P': Result := 80;
'u',
'U': Result := 90;
'q': Result := 100;
'r': Result := 200;
'v',
's': Result := 300;
't': Result := 400;
else Result := 0
end
end;
function THebrew.Name (Latin_Letter: Char): string;
begin
case Latin_Letter of
'a': Result := Get_Lower (1);
'b': Result := Get_Lower (2);
'g': Result := Get_Lower (3);
'd': Result := Get_Lower (4);
'h': Result := Get_Lower (5);
'w': Result := Get_Lower (6);
'z': Result := Get_Lower (7);
'x': Result := Get_Lower (8);
'j': Result := Get_Lower (9);
'y': Result := Get_Lower (10);
'k',
'K': Result := Get_Lower (11);
'l': Result := Get_Lower (12);
'm',
'M': Result := Get_Lower (13);
'n',
'N': Result := Get_Lower (14);
'o': Result := Get_Lower (15);
'e': Result := Get_Lower (16);
'p',
'P': Result := Get_Lower (17);
'u',
'U': Result := Get_Lower (18);
'q': Result := Get_Lower (19);
'r': Result := Get_Lower (20);
'v',
's': Result := Get_Lower (21);
't': Result := Get_Lower (22);
else Result := Blank
end
end;
function THebrew.Read_Code (Latin_Letter: Char): Char;
begin
case Latin_Letter of
'e': Result := 'a';
'o': Result := 's';
'U': Result := 'T';
'u': Result := 't';
'v': Result := 's';
'x': Result := 'c';
else Result := Latin_Letter
end
end;
function THebrew.OLB_to_David (Latin_Letter: Char): Char;
begin
case Latin_Letter of
'a': Result := Chr (224);
'b': Result := Chr (225);
'g': Result := Chr (226);
'd': Result := Chr (227);
'h': Result := Chr (228);
'w': Result := Chr (229);
'z': Result := Chr (230);
'x': Result := Chr (231);
'j': Result := Chr (232);
'y': Result := Chr (233);
'K': Result := Chr (234); // am Wortende.
'k': Result := Chr (235);
'l': Result := Chr (236);
'M': Result := Chr (237); // am Wortende.
'm': Result := Chr (238);
'N': Result := Chr (239); // am Wortende.
'n': Result := Chr (240);
'o': Result := Chr (241);
'e': Result := Chr (242);
'P': Result := Chr (243); // am Wortende.
'p': Result := Chr (244);
'U': Result := Chr (245); // am Wortende.
'u': Result := Chr (246);
'q': Result := Chr (247);
'r': Result := Chr (248);
'v',
's': Result := Chr (249);
't': Result := Chr (250);
else Result := Latin_Letter
end
end;
end.
|
{ @abstract(This file is part of the KControls component suite for Delphi and Lazarus.)
@author(Tomas Krysl)
Copyright (c) 2020 Tomas Krysl<BR><BR>
<B>License:</B><BR>
This code is licensed under BSD 3-Clause Clear License, see file License.txt or https://spdx.org/licenses/BSD-3-Clause-Clear.html.
}
unit klabels; // lowercase name because of Lazarus/Linux
{$include kcontrols.inc}
{$WEAKPACKAGEUNIT ON}
interface
uses
{$IFDEF FPC}
LCLType, LCLIntf, LMessages, LCLProc, LResources,
{$ELSE}
Windows, Messages,
{$ENDIF}
Classes, Controls, Forms, Graphics, StdCtrls, KFunctions, KControls
{$IFDEF USE_THEMES}
, Themes
{$IFNDEF FPC}
, UxTheme
{$ENDIF}
{$ENDIF}
;
type
TKGradientLabel = class(TKCustomControl)
private
BM: TBitmap;
FLeftColor,
FRightColor,
FDividerColor: TColor;
FDividerWidth: Integer;
FColorStep: Integer;
FCaptionWidth: Integer;
procedure SetLeftColor(Value: TColor);
procedure SetRightColor(Value: TColor);
procedure SetDividerColor(Value: TColor);
procedure SetDividerWidth(Value: Integer);
procedure SetColorStep(Value: Integer);
procedure SetCaptionWidth(Value: Integer);
procedure WMEraseBkGnd(var Msg: TLMessage); message LM_ERASEBKGND;
procedure CMTextChanged(var Msg: TLMessage); message CM_TEXTCHANGED;
protected
procedure Paint; override;
procedure Resize; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Align;
property Anchors;
property Caption;
property CaptionWidth: Integer read FCaptionWidth write SetCaptionWidth default 50;
property ColorStep: Integer read FColorStep write SetColorStep default 50;
property Constraints;
property DividerColor: TColor read FDividerColor write SetDividerColor default clBlack;
property DividerWidth: Integer read FDividerWidth write SetDividerWidth default 2;
property Font;
property LeftColor: TColor read FLeftColor write SetLeftColor default clNavy;
property RightColor: TColor read FRightColor write SetRightColor default clBlue;
end;
{ TKLinkLabel }
TKLinkLabel = class(TLabel)
private
FHotColor: TColor;
FLinkColor: TColor;
FShowURLAsHint: Boolean;
FURL: string;
procedure CMMouseEnter(var Message: TLMessage); message CM_MOUSEENTER;
procedure CMMouseLeave(var Message: TLMessage); message CM_MOUSELEAVE;
procedure CMFontChanged(var Message: TLMessage); message CM_FONTCHANGED;
procedure SetHotColor(Value: TColor);
procedure SetLinkColor(const Value: TColor);
protected
FActiveColor: TColor;
FMouseInControl: Boolean;
procedure Loaded; override;
procedure Paint; override;
public
constructor Create(AOwner: TComponent); override;
procedure Click; override;
published
property HotColor: TColor read FHotColor write SetHotColor default clRed;
property LinkColor: TColor read FLinkColor write SetLinkColor default clBlue;
property ShowURLAsHint: Boolean read FShowURLAsHint write FShowURLAsHint;
property URL: string read FURL write FURL;
end;
implementation
uses
Math, SysUtils, KGraphics;
{ TKGradientLabel }
constructor TKGradientLabel.Create(AOwner: TComponent);
begin
inherited;
BM := TBitmap.Create;
{$IFNDEF FPC}
BM.IgnorePalette := True;
{$ENDIF}
Caption := '';
FLeftColor := clNavy;
FRightColor := clBlue;
FDividerColor := clBlack;
FDividerWidth := 2;
Font.Color := clWhite;
Font.Name := 'Arial';
Font.Height := 20;
Font.Style := [fsBold];
FColorStep := 50;
Width := 50;
Height := 30;
FCaptionWidth := 50;
end;
destructor TKGradientLabel.Destroy;
begin
inherited;
BM.Free;
end;
procedure TKGradientLabel.Resize;
begin
FCaptionWidth := Width;
Invalidate;
inherited;
end;
procedure TKGradientLabel.SetDividerColor(Value: TColor);
begin
if Value <> FDividerColor then
begin
FDividerColor := Value;
Invalidate;
end;
end;
procedure TKGradientLabel.SetDividerWidth(Value: Integer);
begin
if Value <> FDividerWidth then
begin
FDividerWidth := Value;
Invalidate;
end;
end;
procedure TKGradientLabel.SetLeftColor(Value: TColor);
begin
if Value <> FLeftColor then
begin
FLeftColor := Value;
Invalidate;
end;
end;
procedure TKGradientLabel.SetRightColor(Value: TColor);
begin
if Value <> FRightColor then
begin
FRightColor := Value;
Invalidate;
end;
end;
procedure TKGradientLabel.SetCaptionWidth(Value: Integer);
begin
if Value <> FCaptionWidth then
begin
FCaptionWidth := Value;
Invalidate;
end;
end;
procedure TKGradientLabel.SetColorStep(Value: Integer);
begin
Value := Max(Value, 1);
Value := Min(Value, 255);
if Value <> FColorStep then
begin
FColorStep := Value;
Invalidate;
end;
end;
procedure TKGradientLabel.WMEraseBkGnd(var Msg: TLMessage);
begin
Msg.Result := 1;
end;
procedure TKGradientLabel.Paint;
begin
if Width > 0 then
begin
BM.Width := Width;
BM.Height := Max(Height - FDividerWidth, 1);
with BM.Canvas do
begin
if FLeftColor <> FRightColor then
begin
DrawGradientRect(BM.Canvas, Rect(0, 0, BM.Width, BM.Height), FLeftColor, FRightColor, FColorStep, True);
end else
begin
Brush.Color := FLeftColor;
FillRect(Rect(0, 0, BM.Width, BM.Height));
end;
Font := Self.Font;
SetBkMode(Handle, TRANSPARENT);
TextOut(Max((FCaptionWidth - TextWidth(Caption)) div 2, 10),
(Height - Font.Height) div 2, Caption);
end;
with Canvas do
begin
Draw(0,0, BM);
if FDividerWidth > 0 then
begin
Pen.Color := FDividerColor;
Brush.Color := FDividerColor;
Rectangle(0, Max(Height - FDividerWidth, 0), Width, Height);
end;
end;
end;
end;
procedure TKGradientLabel.CMTextChanged(var Msg: TLMessage);
begin
inherited;
Invalidate;
end;
{ TKLinkLabel }
constructor TKLinkLabel.Create(AOwner: TComponent);
begin
inherited;
FMouseInControl := False;
FShowURLAsHint := True;
ShowHint := True;
FHotColor := clRed;
FLinkColor := clBlue;
FActiveColor := FLinkColor;
FURL := 'http://example.com';
Caption := FURL;
Cursor := crHandPoint;
end;
procedure TKLinkLabel.Paint;
begin
if csDesigning in ComponentState then
Font.Color := FLinkColor
else
Font.Color := FActiveColor;
inherited;
end;
procedure TKLinkLabel.Click;
begin
inherited;
OpenURLWithShell(FURL);
end;
procedure TKLinkLabel.SetHotColor(Value: TColor);
begin
if Value <> FHotColor then
begin
FHotColor := Value;
if FMouseInControl then
Invalidate;
end;
end;
procedure TKLinkLabel.SetLinkColor(const Value: TColor);
begin
if Value <> FLinkColor then
begin
FLinkColor := Value;
if not FMouseInControl then
Invalidate;
end;
end;
procedure TKLinkLabel.Loaded;
begin
inherited Loaded;
FActiveColor := FLinkColor;
end;
procedure TKLinkLabel.CMMouseEnter(var Message: TLMessage);
begin
inherited;
{ Don't draw a border if DragMode <> dmAutomatic since this button is meant to
be used as a dock client. }
if not (csDesigning in ComponentState) and not FMouseInControl
and Enabled and (DragMode <> dmAutomatic) and (GetCapture = 0) then
begin
FMouseInControl := True;
FActiveColor := FHotColor;
if FShowURLAsHint then
Hint := FURL;
Invalidate;
end;
end;
procedure TKLinkLabel.CMMouseLeave(var Message: TLMessage);
begin
inherited;
if not (csDesigning in ComponentState) and FMouseInControl and Enabled then
begin
FMouseInControl := False;
FActiveColor := FLinkColor;
if FShowURLAsHint then
Hint := '';
Invalidate;
end;
end;
procedure TKLinkLabel.CMFontChanged(var Message: TLMessage);
begin
Invalidate;
end;
end.
|
unit ReturnOutMovementItemTest;
interface
uses dbMovementItemTest, dbTest, ObjectTest;
type
TReturnOutMovementItemTest = class(TdbTest)
protected
procedure SetUp; override;
published
// загрузка процедура из определенной директории
procedure ProcedureLoad; override;
procedure Test; override;
end;
TReturnOutMovementItem = class(TMovementItemTest)
protected
function InsertDefault: integer; override;
public
function InsertUpdateReturnOutMovementItem
(Id, MovementId, GoodsId: Integer;
Amount, AmountPartner,
Price, CountForPrice, HeadCount: double;
PartionGoods:String; GoodsKindId, AssetId: Integer): integer;
constructor Create; override;
end;
implementation
uses UtilConst, Db, SysUtils, PersonalTest, dbMovementTest, UnitsTest,
Storage, Authentication, TestFramework, CommonData, dbObjectTest,
Variants, dbObjectMeatTest, ReturnOutTest, GoodsTest;
{ TReturnOutMovementItemTest }
procedure TReturnOutMovementItemTest.ProcedureLoad;
begin
ScriptDirectory := ProcedurePath + 'MovementItem\ReturnOut\';
inherited;
ScriptDirectory := ProcedurePath + 'Movement\ReturnOut\';
inherited;
end;
procedure TReturnOutMovementItemTest.SetUp;
begin
inherited;
TAuthentication.CheckLogin(TStorageFactory.GetStorage, 'Админ', 'Админ', gc_User);
end;
function TReturnOutMovementItem.InsertDefault: integer;
var Id, MovementId, GoodsId: Integer;
Amount, AmountPartner, Price, CountForPrice,
HeadCount: double;
PartionGoods:String;
GoodsKindId, AssetId: Integer;
begin
Id:=0;
MovementId:= TReturnOut.Create.GetDefault;
GoodsId := TGoods.Create.GetDefault;
Amount:=10;
AmountPartner:=11;
Price:=2.34;
CountForPrice:=1;
HeadCount:=5;
PartionGoods:='';
GoodsKindId:=0;
AssetId:=0;
//
result := InsertUpdateReturnOutMovementItem(Id, MovementId, GoodsId,
Amount, AmountPartner,
Price, CountForPrice, HeadCount,
PartionGoods, GoodsKindId, AssetId);
end;
procedure TReturnOutMovementItemTest.Test;
var ReturnOutMovementItem: TReturnOutMovementItem;
Id: Integer;
begin
inherited;
// Создаем документ
ReturnOutMovementItem := TReturnOutMovementItem.Create;
Id := ReturnOutMovementItem.InsertDefault;
// создание документа
try
// редактирование
finally
ReturnOutMovementItem.Delete(Id);
end;
end;
{ TReturnOutMovementItem }
constructor TReturnOutMovementItem.Create;
begin
inherited;
spInsertUpdate := 'gpInsertUpdate_MovementItem_ReturnOut';
end;
function TReturnOutMovementItem.InsertUpdateReturnOutMovementItem(
Id, MovementId, GoodsId: Integer;
Amount, AmountPartner, Price,
CountForPrice, HeadCount: double;
PartionGoods:String; GoodsKindId, AssetId: Integer): integer;
begin
FParams.Clear;
FParams.AddParam('ioId', ftInteger, ptInputOutput, Id);
FParams.AddParam('inMovementId', ftInteger, ptInput, MovementId);
FParams.AddParam('inGoodsId', ftInteger, ptInput, GoodsId);
FParams.AddParam('inAmount', ftFloat, ptInput, Amount);
FParams.AddParam('inAmountPartner', ftFloat, ptInput, AmountPartner);
// FParams.AddParam('inAmountChangePercent', ftFloat, ptInput, AmountChangePercent);
// FParams.AddParam('inChangePercentAmount', ftFloat, ptInput, ChangePercentAmount);
FParams.AddParam('inPrice', ftFloat, ptInput, Price);
FParams.AddParam('ioCountForPrice', ftFloat, ptInputOutput, CountForPrice);
// FParams.AddParam('outAmountSumm', ftFloat, ptOutput, AmountSumm);
FParams.AddParam('inHeadCount', ftFloat, ptInput, HeadCount);
FParams.AddParam('inPartionGoods', ftString, ptInput, PartionGoods);
FParams.AddParam('inGoodsKindId', ftInteger, ptInput, GoodsKindId);
FParams.AddParam('inAssetId', ftInteger, ptInput, AssetId);
result := InsertUpdate(FParams);
end;
initialization
// TestFramework.RegisterTest('Строки Документов', TReturnOutMovementItemTest.Suite);
end.
|
program CrapWindows;
Uses Graph, Crt, GrafBits, Mary;
type
TButton = object
XPos, YPos,
Height, Width,
CaptionX, CaptionY: integer;
Caption: string;
CaptionColour,
Colour, BackColour,
HighLightColour, ShadowColour: Word;
ShortCutKey: string[2];
Enabled: Boolean;
procedure Init(X, Y, Wid, Ht: integer;
Col, BkCol, HltCol, ShadCol, TxtCol: Word;
Capt: string;
Enable: Boolean);
procedure Draw;
procedure PressedIn;
end;
TWindow = object
FrameWidth,
XPos, YPos,
Height, Width,
CaptionX, CaptionY: integer;
TitleCaption: string;
FrameFillColour, FrameColour,
TitleColour, TitleCaptionColour,
Colour, TextColour: Word;
cmdButton: TButton;
procedure Init(X, Y, Wid, Ht: integer;
FrmCol, TitleCol, TitleCapCol,
Col, TxtCol: Word;
Caption: string);
procedure Draw;
end;
Var
winWindow: TWindow;
cmdButton: TButton;
Ch: Char;
procedure TButton.Init;
var
Ca: integer;
begin
XPos:= X;
YPos:= Y;
Height:= Ht;
Width:= Wid;
Caption:= Capt;
Colour:= Col;
BackColour:= BkCol;
HighLightColour:= HltCol;
ShadowColour:= ShadCol;
CaptionColour:= TxtCol;
Enabled:= Enable;
ShortCutKey:= #0;
For Ca:= 1 to Length(Caption) do
if ShortCutKey <> #0 then
if Caption[Ca] in ['A'..'Z'] then ShortCutKey:= Caption[Ca];
end;
procedure TButton.Draw;
begin
SetFillStyle(1, Colour);
Bar(XPos, YPos, XPos + Width, YPos + Height);
SetColor(Black);
Rectangle(XPos, YPos, XPos + Width, YPos + Height);
PutPixel(XPos, YPos, Yellow);
PutPixel(XPos + Width, YPos, BackColour);
PutPixel(XPos + Width, YPos + Height, BackColour);
PutPixel(XPos, YPos + Height, BackColour);
SetColor(HighLightColour);
{Left Highlight Edge}
Line(XPos + 1, YPos + 1, XPos + 1, YPos + (Height - 1));
Line(XPos + 2, YPos + 1, XPos + 2, YPos + (Height - 2));
{Top Highlight Edge }
Line(XPos + 1, YPos + 1, XPos + (Width - 1), YPos + 1);
Line(XPos + 1, YPos + 1, XPos + (Width - 2), YPos + 1);
SetColor(ShadowColour);
{ Right hand edge shadow }
Line(XPos + (Width - 1), YPos + (Height - 1), XPos + (Width - 1), YPos + 1);
Line(XPos + (Width - 2), YPos + (Height - 2), XPos + (Width - 2), YPos + 2);
{ Bottom edge shadow }
Line(XPos + (Width - 1), YPos + (Height - 1), XPos + 1, YPos + (Height - 1));
Line(XPos + (Width - 2), YPos + (Height - 2), XPos + 2, YPos + (Height - 2)); {Top Highlight Edge }
SetTextStyle(0, 0, 1);
SetTextJustify(1, 1);
SetColor(CaptionColour);
CaptionX:= XPos + (Width div 2);
CaptionY:= YPos + (Height div 2);
if TextWidth(Caption) < Width - 5 then OutTextXY(CaptionX, CaptionY, Caption);
end;
procedure TButton.PressedIn;
begin
end;
procedure TWindow.Init;
begin
XPos:= X;
YPos:= Y;
Height:= Ht;
Width:= Wid;
TitleCaption:= Caption;
TitleColour:= TitleCol;
TitleCaptionColour:= TitleCapCol;
FrameColour:= FrmCol;
Colour:= Col;
TextColour:= TxtCol;
CaptionX:= (Width div 2) + XPos;
CaptionY:= YPos + 10;
end;
procedure TWindow.Draw;
begin
SetFillStyle(1, Colour);
Bar(XPos, YPos, XPos + Width, YPos + Height);
SetLineStyle(0, 0, 3);
SetColor(FrameColour);
Rectangle(XPos, YPos, XPos + Width, YPos + Height);
SetFillStyle(1, TitleColour);
Bar(XPos, YPos, XPos + Width, YPos + 20);
SetLineStyle(0, 0, 1);
Line(XPos, YPos + 20, XPos + Width, YPos + 20);
SetColor(TitleCaptionColour);
SetTextStyle(0, 0, 1);
SetTextJustify(1, 1);
if (Width - 10) > TextWidth(TitleCaption) then
OutTextXY(CaptionX, CaptionY, TitleCaption);
SetViewPort(XPos + 2, YPos + 22, XPos + (Width - 2), YPos + (Height - 2), ClipOn);
cmdButton.Init(10, 10, 300, 20, LightGray, White, White, DarkGray, Black, 'eXit Now Man', True);
cmdButton.Draw;
end;
begin
GraphicsScreen;
winWindow.Init(0, 0, MaxX, MaxY,
Yellow, Blue, White, White, Black,
'The Window.');
winWindow.Draw;
ReadKey;
CloseGraph;
end.
|
unit SAPMB51Reader2;
interface
uses
Classes, SysUtils, ComObj, CommUtils, ADODB;
type
TSAPMB51Record = packed record
sbillno: string; //物料凭证
sentryid: string; //物料凭证项目
fbilldate: TDateTime; //凭证日期
fstockno: string; //库存地点
fstockname: string; //仓储地点的描述
fnote: string; //凭证抬头文本 用于存储 代工厂单号
smovingtype: string; //移动类型
smovingtypeText: string; //移动类型文本
snumber: string; //物料
sname: string; //物料描述
dqty: Double; //以录入单位表示的数量
fdate: TDateTime; //过账日期
finputdate: TDateTime; //输入日期
finputtime: TDateTime; //输入时间
spo: string; //订单
sbillno_po: string; //采购订单
snote_entry: string; // 文本
bCalc: Boolean;
sMatchType: string;
end;
PSAPMB51Record= ^TSAPMB51Record;
TSAPMB51Reader2 = class
private
FList: TStringList;
FFile: string;
ExcelApp, WorkBook: Variant;
FLogEvent: TLogEvent;
FWinBCount: Integer;
procedure Open;
procedure Log(const str: string);
function GetCount: Integer;
function GetItems(i: Integer): PSAPMB51Record;
public
constructor Create(const sfile: string; aLogEvent: TLogEvent = nil);
destructor Destroy; override;
procedure Clear;
function GetMB51Qty101(aSAPMB51RecordPtr: PSAPMB51Record): Double;
procedure SetCalcFlag(aSAPMB51RecordPtr: PSAPMB51Record; const sMatchType: string);
property Count: Integer read GetCount;
property Items[i: Integer]: PSAPMB51Record read GetItems;
property WinBCount: Integer read FWinBCount;
end;
TSAPMB51RecordFox = packed record
sbillno: string; //物料凭证
snumber: string; //物料
sname: string; //物料描述
dqty: Double; //以录入单位表示的数量
smovingtype: string; //移动类型
splnt: string;
fstockno: string; //库存地点
fstockname: string; //仓储地点的描述
stext: string; //凭证抬头文本 用于存储 代工厂单号
sorder: string; //订单
sref: string;
fdate: TDateTime; //过账日期
finputdate: TDateTime; //输入日期
finputtime: TDateTime; //输入时间
sheadtext: string;
susername: string;
splnt_name: string;
smovingtypeText: string; //移动类型文本
sitem: string;
bCalc: Boolean;
sMatchType: string;
end;
PSAPMB51RecordFox = ^TSAPMB51RecordFox;
TSAPMB51ReaderFox = class
private
FList: TStringList;
FFile: string;
ExcelApp, WorkBook: Variant;
FLogEvent: TLogEvent;
FWinBCount: Integer;
procedure Open;
procedure Log(const str: string);
function GetCount: Integer;
function GetItems(i: Integer): PSAPMB51RecordFox;
public
constructor Create(const sfile: string; aLogEvent: TLogEvent = nil);
destructor Destroy; override;
procedure Clear;
property Count: Integer read GetCount;
property Items[i: Integer]: PSAPMB51RecordFox read GetItems;
property WinBCount: Integer read FWinBCount;
end;
implementation
{ TSAPMB51Reader2 }
constructor TSAPMB51Reader2.Create(const sfile: string;
aLogEvent: TLogEvent = nil);
begin
FFile := sfile;
FLogEvent := aLogEvent;
FList := TStringList.Create;
Open;
end;
destructor TSAPMB51Reader2.Destroy;
begin
Clear;
FList.Free;
inherited;
end;
procedure TSAPMB51Reader2.Clear;
var
i: Integer;
p: PSAPMB51Record;
begin
for i := 0 to FList.Count - 1 do
begin
p := PSAPMB51Record(FList.Objects[i]);
Dispose(p);
end;
FList.Clear;
end;
function TSAPMB51Reader2.GetMB51Qty101(aSAPMB51RecordPtr: PSAPMB51Record): Double;
var
i: Integer;
p: PSAPMB51Record;
begin
Result := 0;
for i := 0 to self.Count - 1 do
begin
p := self.Items[i];
if p^.bCalc then Continue;
if (p^.fnote = aSAPMB51RecordPtr^.fnote) and
(p^.snumber = aSAPMB51RecordPtr^.snumber) and
(p^.sbillno_po = aSAPMB51RecordPtr^.sbillno_po) then
begin
Result := Result + p^.dqty;
end;
end;
end;
procedure TSAPMB51Reader2.SetCalcFlag(aSAPMB51RecordPtr: PSAPMB51Record;
const sMatchType: string);
var
i: Integer;
p: PSAPMB51Record;
begin
for i := 0 to self.Count - 1 do
begin
p := self.Items[i];
if (p^.fnote = aSAPMB51RecordPtr^.fnote) and
(p^.snumber = aSAPMB51RecordPtr^.snumber) and
(p^.sbillno_po = aSAPMB51RecordPtr^.sbillno_po) then
begin
p^.bCalc := True;
p^.sMatchType := sMatchType;
end;
end;
end;
function TSAPMB51Reader2.GetCount: Integer;
begin
Result := FList.Count;
end;
function TSAPMB51Reader2.GetItems(i: Integer): PSAPMB51Record;
begin
Result := PSAPMB51Record(FList.Objects[i]);
end;
procedure TSAPMB51Reader2.Log(const str: string);
begin
savelogtoexe(str);
if Assigned(FLogEvent) then
begin
FLogEvent(str);
end;
end;
procedure TSAPMB51Reader2.Open;
var
iSheetCount, iSheet: Integer;
stitle: string;
irow: Integer;
snumber: string;
aSAPOPOAllocPtr: PSAPMB51Record;
Conn: TADOConnection;
ADOTabXLS: TADOTable;
begin
Clear;
if not FileExists(FFile) then Exit;
ADOTabXLS := TADOTable.Create(nil);
Conn:=TADOConnection.Create(nil);
Conn.ConnectionString:='Provider=Microsoft.ACE.OLEDB.12.0;Data Source="' + FFile + '";Extended Properties=excel 8.0;Persist Security Info=False';
Conn.LoginPrompt:=false;
try
Conn.Connected:=true;
ADOTabXLS.Connection:=Conn;
ADOTabXLS.TableName:='['+'Sheet1'+'$]';
ADOTabXLS.Active:=true;
FWinBCount := 0;
ADOTabXLS.First;
while not ADOTabXLS.Eof do
begin
snumber := ADOTabXLS.FieldByName('物料').AsString; // ExcelApp.Cells[irow, iColNumber].Value;
if snumber = '' then Break;
aSAPOPOAllocPtr := New(PSAPMB51Record);
aSAPOPOAllocPtr^.bCalc := False;
aSAPOPOAllocPtr^.sbillno := ADOTabXLS.FieldByName('物料凭证').AsString;
//aSAPOPOAllocPtr^.sentryid := ADOTabXLS.FieldByName('物料凭证项目').AsString;
aSAPOPOAllocPtr^.fbilldate := ADOTabXLS.FieldByName('凭证日期').AsDateTime;
if ADOTabXLS.FindField('库位') <> nil then
begin
aSAPOPOAllocPtr^.fstockno := ADOTabXLS.FieldByName('库位').AsString;
end
else
begin
aSAPOPOAllocPtr^.fstockno := ADOTabXLS.FieldByName('库存地点').AsString;
end;
aSAPOPOAllocPtr^.fstockname := ADOTabXLS.FieldByName('仓储地点的描述').AsString;
aSAPOPOAllocPtr^.fnote := ADOTabXLS.FieldByName('凭证抬头文本').AsString; // 用于存储 代工厂单号
if ADOTabXLS.FindField('MvT') <> nil then
begin
aSAPOPOAllocPtr^.smovingtype := ADOTabXLS.FieldByName('MvT').AsString;
end
else
begin
aSAPOPOAllocPtr^.smovingtype := ADOTabXLS.FieldByName('移动类型').AsString;
end;
// aSAPOPOAllocPtr^.smovingtypeText := ADOTabXLS.FieldByName('移动类型文本').AsString;
aSAPOPOAllocPtr^.snumber := snumber;
aSAPOPOAllocPtr^.sname := ADOTabXLS.FieldByName('物料描述').AsString;
if ADOTabXLS.FindField('数量') <> nil then
begin
aSAPOPOAllocPtr^.dqty := ADOTabXLS.FieldByName('数量').AsFloat;
end
else if ADOTabXLS.FindField('数量(录入单位)') <> nil then
begin
aSAPOPOAllocPtr^.dqty := ADOTabXLS.FieldByName('数量(录入单位)').AsFloat;
end
else
begin
aSAPOPOAllocPtr^.dqty := ADOTabXLS.FieldByName('以录入单位表示的数量').AsFloat;
end;
aSAPOPOAllocPtr^.fdate := ADOTabXLS.FieldByName('过账日期').AsDateTime;
aSAPOPOAllocPtr^.finputdate := ADOTabXLS.FieldByName('输入日期').AsDateTime;
aSAPOPOAllocPtr^.finputtime := ADOTabXLS.FieldByName('输入时间').AsDateTime;
aSAPOPOAllocPtr^.spo := ADOTabXLS.FieldByName('订单').AsString;
aSAPOPOAllocPtr^.sbillno_po := ADOTabXLS.FieldByName('采购订单').AsString;
aSAPOPOAllocPtr^.snote_entry := ADOTabXLS.FieldByName('文本').AsString;
if aSAPOPOAllocPtr^.smovingtype = '101' then
begin
FWinBCount := FWinBCount + 1;
end;
FList.AddObject(snumber, TObject(aSAPOPOAllocPtr));
irow := irow + 1;
snumber := ADOTabXLS.FieldByName('物料').AsString; // ExcelApp.Cells[irow, iColNumber].Value;
ADOTabXLS.Next;
end;
ADOTabXLS.Close;
Conn.Connected := False;
finally
FreeAndNil(Conn);
FreeAndNil(ADOTabXLS);
end;
end;
////////////////////////////////////////////////////////////////////////////////
{ TSAPMB51ReaderFox }
constructor TSAPMB51ReaderFox.Create(const sfile: string;
aLogEvent: TLogEvent = nil);
begin
FFile := sfile;
FLogEvent := aLogEvent;
FList := TStringList.Create;
Open;
end;
destructor TSAPMB51ReaderFox.Destroy;
begin
Clear;
FList.Free;
inherited;
end;
procedure TSAPMB51ReaderFox.Clear;
var
i: Integer;
p: PSAPMB51RecordFox;
begin
for i := 0 to FList.Count - 1 do
begin
p := PSAPMB51RecordFox(FList.Objects[i]);
Dispose(p);
end;
FList.Clear;
end;
function TSAPMB51ReaderFox.GetCount: Integer;
begin
Result := FList.Count;
end;
function TSAPMB51ReaderFox.GetItems(i: Integer): PSAPMB51RecordFox;
begin
Result := PSAPMB51RecordFox(FList.Objects[i]);
end;
procedure TSAPMB51ReaderFox.Log(const str: string);
begin
savelogtoexe(str);
if Assigned(FLogEvent) then
begin
FLogEvent(str);
end;
end;
procedure TSAPMB51ReaderFox.Open;
var
iSheetCount, iSheet: Integer;
stitle: string;
irow: Integer;
aSAPOPOAllocPtr: PSAPMB51RecordFox;
Conn: TADOConnection;
ADOTabXLS: TADOTable;
snumber: string;
sdt: string;
begin
Clear;
if not FileExists(FFile) then Exit;
ADOTabXLS := TADOTable.Create(nil);
Conn:=TADOConnection.Create(nil);
Conn.ConnectionString:='Provider=Microsoft.ACE.OLEDB.12.0;Data Source="' + FFile + '";Extended Properties=excel 8.0;Persist Security Info=False';
Conn.LoginPrompt:=false;
try
Conn.Connected:=true;
ADOTabXLS.Connection:=Conn;
ADOTabXLS.TableName:='['+'Sheet1'+'$]';
ADOTabXLS.Active:=true;
FWinBCount := 0;
ADOTabXLS.First;
while not ADOTabXLS.Eof do
begin
snumber := ADOTabXLS.FieldByName('Material').AsString; // ExcelApp.Cells[irow, iColNumber].Value;
if snumber = '' then
begin
Continue;
end;
aSAPOPOAllocPtr := New(PSAPMB51RecordFox);
aSAPOPOAllocPtr^.bCalc := False;
FList.AddObject(snumber, TObject(aSAPOPOAllocPtr));
aSAPOPOAllocPtr^.sbillno := ADOTabXLS.FieldByName('Mat. doc.').AsString;
aSAPOPOAllocPtr^.snumber := ADOTabXLS.FieldByName('Material').AsString;
aSAPOPOAllocPtr^.sname := ADOTabXLS.FieldByName('Material description').AsString;
aSAPOPOAllocPtr^.dqty := ADOTabXLS.FieldByName(' Quantity').AsFloat;
aSAPOPOAllocPtr^.smovingtype := ADOTabXLS.FieldByName('MvT').AsString;
aSAPOPOAllocPtr^.splnt := ADOTabXLS.FieldByName('Plnt').AsString;
aSAPOPOAllocPtr^.fstockno := ADOTabXLS.FieldByName('SLoc').AsString;
aSAPOPOAllocPtr^.fstockname := ADOTabXLS.FieldByName('富士康仓位').AsString;
aSAPOPOAllocPtr^.stext := ADOTabXLS.FieldByName('Text').AsString;
aSAPOPOAllocPtr^.sorder := ADOTabXLS.FieldByName('Order').AsString;
aSAPOPOAllocPtr^.sref := ADOTabXLS.FieldByName('Reference').AsString;
sdt := ADOTabXLS.FieldByName('Entry date').AsString;
aSAPOPOAllocPtr^.fdate := myStrToDateTime(sdt);
sdt := ADOTabXLS.FieldByName('Pstg date').AsString;
aSAPOPOAllocPtr^.finputdate := myStrToDateTime(sdt);
aSAPOPOAllocPtr^.finputtime := ADOTabXLS.FieldByName('Time').AsDateTime;
aSAPOPOAllocPtr^.sheadtext := ADOTabXLS.FieldByName('HeadText').AsString;
aSAPOPOAllocPtr^.susername := ADOTabXLS.FieldByName('User name').AsString;
aSAPOPOAllocPtr^.splnt_name := ADOTabXLS.FieldByName('Name 1').AsString;
aSAPOPOAllocPtr^.smovingtypeText := ADOTabXLS.FieldByName('MvtTypeTxt').AsString;
aSAPOPOAllocPtr^.sitem := ADOTabXLS.FieldByName('Item').AsString;
ADOTabXLS.Next;
end;
ADOTabXLS.Close;
Conn.Connected := False;
finally
FreeAndNil(Conn);
FreeAndNil(ADOTabXLS);
end;
end;
end.
|
{Hint: save all files to location: C:\adt32\eclipse\workspace\AppCameraDemo\jni }
unit unit1;
{$mode delphi}
interface
uses
Classes, SysUtils, And_jni, And_jni_Bridge, Laz_And_Controls,
Laz_And_Controls_Events, AndroidWidget;
type
{ TAndroidModule1 }
TAndroidModule1 = class(jForm)
jBitmap1: jBitmap;
jButton1: jButton;
jCamera1: jCamera;
jCanvas1: jCanvas;
jEditText1: jEditText;
jImageView1: jImageView;
jPanel1: jPanel;
jPanel2: jPanel;
jPanel3: jPanel;
jPanel4: jPanel;
jPanel5: jPanel;
jTextView1: jTextView;
jTextView2: jTextView;
jView1: jView;
procedure AndroidModule1ActivityResult(Sender: TObject;
requestCode: integer; resultCode: TAndroidResult; intentData: jObject);
procedure AndroidModule1Create(Sender: TObject);
procedure AndroidModule1JNIPrompt(Sender: TObject);
procedure AndroidModule1PrepareOptionsMenu(Sender: TObject;
jObjMenu: jObject; menuSize: integer; out prepareItems: boolean);
procedure AndroidModule1RequestPermissionResult(Sender: TObject;
requestCode: integer; manifestPermission: string;
grantResult: TManifestPermissionResult);
procedure AndroidModule1Rotate(Sender: TObject; rotate: TScreenStyle);
procedure jButton1Click(Sender: TObject);
procedure jView1Draw(Sender: TObject; Canvas: jCanvas);
private
{private declarations}
FPhotoExist: boolean;
FSaveRotate: TScreenStyle;
public
{public declarations}
end;
var
AndroidModule1: TAndroidModule1;
implementation
{$R *.lfm}
{ TAndroidModule1 }
procedure TAndroidModule1.jButton1Click(Sender: TObject);
begin
if IsRuntimePermissionGranted('android.permission.CAMERA') and
IsRuntimePermissionGranted('android.permission.WRITE_EXTERNAL_STORAGE') then
begin
jCamera1.RequestCode := 12345;
//jCamera1.AddToGallery:= False;
jCamera1.TakePhoto;
end
else ShowMessage('Sorry... Some Runtime Permission NOT Granted ...');
end;
procedure TAndroidModule1.jView1Draw(Sender: TObject; Canvas: jCanvas);
begin
if FPhotoExist then
begin
jView1.Canvas.DrawBitmap(jBitmap1.GetImage, jView1.Width, jView1.Height);
//just to ilustration.... you can draw and write over....
jView1.Canvas.PaintColor := colbrRed;
jView1.Canvas.drawLine(0, 0, Trunc(jView1.Width / 2), Trunc(jView1.Height / 2));
jView1.Canvas.drawText('Hello People!', 30, 30);
end;
end;
procedure TAndroidModule1.AndroidModule1Create(Sender: TObject);
begin
FPhotoExist := False;
FSaveRotate := ssPortrait; //default: Vertical
end;
procedure TAndroidModule1.AndroidModule1ActivityResult(Sender: TObject;
requestCode: integer; resultCode: TAndroidResult; intentData: jObject);
begin
if resultCode = RESULT_CANCELED then
begin
ShowMessage('Photo Canceled!')
end
else if resultCode = RESULT_OK then //ok...
begin
if requestCode = jCamera1.RequestCode then
begin
jBitmap1.LoadFromFile(jCamera1.FullPathToBitmapFile);
jImageView1.SetImageBitmap(jBitmap1.GetImage, jImageView1.Width, jImageView1.Height);
FPhotoExist:= True;
jView1.Refresh; //dispatch OnDraw!
end;
end
else
ShowMessage('Photo Fail!');
end;
procedure TAndroidModule1.AndroidModule1JNIPrompt(Sender: TObject);
var
manifestPermissions: TDynArrayOfString;
begin
if Self.GetScreenOrientationStyle = ssLandscape then // device is on horizontal...
begin //reconfigure....
FSaveRotate := ssLandscape;
jPanel1.LayoutParamHeight := lpMatchParent;
jPanel1.LayoutParamWidth := lpOneQuarterOfParent;
jPanel1.PosRelativeToParent := [rpLeft];
jPanel2.LayoutParamHeight := lpMatchParent;
jPanel2.LayoutParamWidth := lpOneThirdOfParent;
jPanel2.PosRelativeToAnchor := [raToRightOf, raAlignBaseline];
jPanel3.LayoutParamHeight := lpMatchParent;
jPanel3.LayoutParamWidth := lpOneThirdOfParent;
jPanel3.PosRelativeToAnchor := [raToRightOf, raAlignBaseline];
end
else
begin
jPanel1.LayoutParamHeight := lpOneThirdOfParent;
jPanel1.LayoutParamWidth := lpMatchParent;
jPanel1.PosRelativeToParent := [rpTop];
jPanel2.LayoutParamHeight := lpOneThirdOfParent;
jPanel2.LayoutParamWidth := lpMatchParent;
jPanel2.PosRelativeToAnchor := [raBelow];
jPanel3.LayoutParamHeight := lpOneThirdOfParent;
jPanel3.LayoutParamWidth := lpMatchParent;
jPanel3.PosRelativeToAnchor := [raBelow];
;
end;
jPanel1.ClearLayout;
jPanel2.ClearLayout;
jPanel3.ClearLayout;
Self.UpdateLayout;
jEditText1.SetFocus;
//https://www.captechconsulting.com/blogs/runtime-permissions-best-practices-and-how-to-gracefully-handle-permission-removal
//https://developer.android.com/guide/topics/security/permissions#normal-dangerous
if IsRuntimePermissionNeed() then // that is, target API >= 23
begin
ShowMessage('warning: Requesting Runtime Permission.... please, wait..');
SetLength(manifestPermissions, 2);
manifestPermissions[0]:= 'android.permission.CAMERA'; //from AndroodManifest.xml
manifestPermissions[1]:= 'android.permission.WRITE_EXTERNAL_STORAGE'; //from AndroodManifest.xml
Self.RequestRuntimePermission(manifestPermissions, 1001);
SetLength(manifestPermissions, 0);
end;
end;
procedure TAndroidModule1.AndroidModule1PrepareOptionsMenu(Sender: TObject;
jObjMenu: jObject; menuSize: integer; out prepareItems: boolean);
begin
self.UpdateLayout;
end;
procedure TAndroidModule1.AndroidModule1RequestPermissionResult(
Sender: TObject; requestCode: integer; manifestPermission: string;
grantResult: TManifestPermissionResult);
begin
case requestCode of
1001:begin
if grantResult = PERMISSION_GRANTED then
ShowMessage('Success! ['+manifestPermission+'] Permission grant!!! ' )
else //PERMISSION_DENIED
ShowMessage('Sorry... ['+manifestPermission+'] Permission not grant... ' );
end;
end;
end;
procedure TAndroidModule1.AndroidModule1Rotate(Sender: TObject; rotate: TScreenStyle);
begin
FSaveRotate := rotate;
if rotate = ssLandscape then
begin
//after rotation device is on horizontal
jPanel1.LayoutParamHeight := lpMatchParent;
jPanel1.LayoutParamWidth := lpOneThirdOfParent;
jPanel1.PosRelativeToParent := [rpLeft];
jPanel2.LayoutParamHeight := lpMatchParent;
jPanel2.LayoutParamWidth := lpOneThirdOfParent;
jPanel2.PosRelativeToAnchor := [raToRightOf, raAlignBaseline];
jPanel3.LayoutParamHeight := lpMatchParent;
jPanel3.LayoutParamWidth := lpOneThirdOfParent;
jPanel3.PosRelativeToAnchor := [raToRightOf, raAlignBaseline];
end;
if rotate = ssPortrait then
begin
//after rotation device is in vertical :: default
jPanel1.LayoutParamHeight := lpOneThirdOfParent;
jPanel1.LayoutParamWidth := lpMatchParent;
jPanel1.PosRelativeToParent := [rpTop];
jPanel2.LayoutParamHeight := lpOneThirdOfParent;
jPanel2.LayoutParamWidth := lpMatchParent;
jPanel2.PosRelativeToAnchor := [raBelow];
jPanel3.LayoutParamHeight := lpOneThirdOfParent;
jPanel3.LayoutParamWidth := lpMatchParent;
jPanel3.PosRelativeToAnchor := [raBelow];
end;
if rotate in [ssLandscape, ssPortrait] then
begin
jPanel1.ClearLayout;
jPanel2.ClearLayout;
jPanel3.ClearLayout;
jPanel5.ClearLayout;
Self.UpdateLayout;
end;
end;
end.
|
unit dll_httpapi;
interface
uses
atmcmbaseconst;
const
httpapi = 'httpapi.dll';
type
HTTP_URL_GROUP_ID = Pointer;
HTTP_URL_CONTEXT = Pointer;
HTTP_SERVER_SESSION_ID = Pointer;
PHTTP_SERVER_SESSION_ID = ^HTTP_SERVER_SESSION_ID;
HTTPAPI_VERSION = Pointer;
THTTP_DATA_CHUNK = Pointer;
PHTTP_DATA_CHUNK = ^THTTP_DATA_CHUNK;
THTTP_CACHE_POLICY = Pointer;
PHTTP_CACHE_POLICY = ^THTTP_CACHE_POLICY;
THTTP_BYTE_RANGE = Pointer;
PHTTP_BYTE_RANGE = ^THTTP_BYTE_RANGE;
{ HTTP Server API Version 1.0 Functions }
{ General }
function HttpCreateHttpHandle( pReqQueueHandle: PHANDLE; Reserved: ULONG): DWORD; stdcall; external Httpapi name 'HttpCreateHttpHandle';
function HttpInitialize(Version: HTTPAPI_VERSION; Flags: ULONG; pReserved: PVOID): DWORD; stdcall; external Httpapi name 'HttpInitialize';
{ flag : HTTP_INITIALIZE_CONFIG / HTTP_INITIALIZE_SERVER }
function HttpTerminate(Flags: ULONG; pReserved: PVOID): DWORD; stdcall; external Httpapi name 'HttpTerminate';
{ Cache Management }
function HttpAddFragmentToCache(ReqQueueHandle: THANDLE; pUrlPrefix: PWideChar;
pDataChunk: PHTTP_DATA_CHUNK; pCachePolicy: PHTTP_CACHE_POLICY; pOverlapped: POVERLAPPED): DWORD; stdcall; external Httpapi name 'HttpAddFragmentToCache';
function HttpFlushResponseCache(ReqQueueHandle: THANDLE; pUrlPrefix: PWideChar; Flags: ULONG; pOverlapped: POVERLAPPED): DWORD; stdcall; external Httpapi name 'HttpFlushResponseCache';
function HttpReadFragmentFromCache(ReqQueueHandle: THANDLE; pUrlPrefix: PWideChar;
pByteRange: PHTTP_BYTE_RANGE; pBuffer: PVOID; BufferLength: ULONG;
pBytesRead: PULONG; pOverlapped: POVERLAPPED): DWORD; stdcall; external Httpapi name 'HttpReadFragmentFromCache';
{ Configuration }
function HttpDeleteServiceConfiguration: DWORD; stdcall; external Httpapi name 'HttpDeleteServiceConfiguration';
function HttpQueryServiceConfiguration: DWORD; stdcall; external Httpapi name 'HttpQueryServiceConfiguration';
function HttpSetServiceConfiguration: DWORD; stdcall; external Httpapi name 'HttpSetServiceConfiguration';
{ Input and Output }
function HttpReceiveHttpRequest: DWORD; stdcall; external Httpapi name 'HttpReceiveHttpRequest';
function HttpReceiveRequestEntityBody: DWORD; stdcall; external Httpapi name 'HttpReceiveRequestEntityBody';
function HttpSendHttpResponse: DWORD; stdcall; external Httpapi name 'HttpSendHttpResponse';
function HttpSendResponseEntityBody: DWORD; stdcall; external Httpapi name 'HttpSendResponseEntityBody';
function HttpWaitForDisconnect: DWORD; stdcall; external Httpapi name 'HttpWaitForDisconnect';
{ ssl }
function HttpReceiveClientCertificate: DWORD; stdcall; external Httpapi name 'HttpReceiveClientCertificate';
{ URL Registration }
function HttpAddUrl: DWORD; stdcall; external Httpapi name 'HttpAddUrl';
function HttpRemoveUrl: DWORD; stdcall; external Httpapi name 'HttpRemoveUrl';
{ HTTP Server API Version 2.0 Functions }
{ Server Session }
function HttpCloseServerSession(ServerSessionId: HTTP_SERVER_SESSION_ID): DWORD; stdcall; external Httpapi name 'HttpCloseServerSession';
function HttpCreateServerSession(Version: HTTPAPI_VERSION; pServerSessionId: PHTTP_SERVER_SESSION_ID; Reserved: DWORD): DWORD; stdcall; external Httpapi name 'HttpCreateServerSession';
function HttpQueryServerSessionProperty: DWORD; stdcall; external Httpapi name 'HttpQueryServerSessionProperty';
function HttpSetServerSessionProperty: DWORD; stdcall; external Httpapi name 'HttpSetServerSessionProperty';
{ URL Groups }
function HttpAddUrlToUrlGroup(UrlGroupId: HTTP_URL_GROUP_ID;
pFullyQualifiedUrl: PWideChar; UrlContext: HTTP_URL_CONTEXT; Reserved: DWORD): DWORD; stdcall; external Httpapi name 'HttpAddUrlToUrlGroup';
function HttpCreateUrlGroup: DWORD; stdcall; external Httpapi name 'HttpCreateUrlGroup';
function HttpCloseUrlGroup: DWORD; stdcall; external Httpapi name 'HttpCloseUrlGroup';
function HttpQueryUrlGroupProperty: DWORD; stdcall; external Httpapi name 'HttpQueryUrlGroupProperty';
function HttpRemoveUrlFromUrlGroup: DWORD; stdcall; external Httpapi name 'HttpRemoveUrlFromUrlGroup';
function HttpSetUrlGroupProperty: DWORD; stdcall; external Httpapi name 'HttpSetUrlGroupProperty';
{ Request Queue }
function HttpCancelHttpRequest: DWORD; stdcall; external Httpapi name 'HttpCancelHttpRequest';
function HttpCloseRequestQueue: DWORD; stdcall; external Httpapi name 'HttpCloseRequestQueue';
function HttpCreateRequestQueue: DWORD; stdcall; external Httpapi name 'HttpCreateRequestQueue';
function HttpQueryRequestQueueProperty: DWORD; stdcall; external Httpapi name 'HttpQueryRequestQueueProperty';
function HttpSetRequestQueueProperty: DWORD; stdcall; external Httpapi name 'HttpSetRequestQueueProperty';
function HttpShutdownRequestQueue: DWORD; stdcall; external Httpapi name 'HttpShutdownRequestQueue';
function HttpWaitForDemandStart: DWORD; stdcall; external Httpapi name 'HttpWaitForDemandStart';
implementation
end. |
unit uHelper;
interface
uses IdHTTP, System.JSON, SysUtils, Variants, Classes;
const
FCard = ['J', 'Q', 'K', 'A'];
srvUrl = 'http://durakgame.s3.amazonaws.com/public/servers.json';
type
TServer = record
name: String;
host: String;
port: Integer;
end;
TServers = array [0..6] of TServer;
TCard = record
cType: char;
cVal: String;
use: boolean;
end;
THandCards = array of TCard;
function getHttp(url: String): String;
function getCommand(data: String): String;
function getJson(json: String): TJsonValue;
function getJsonParam(param: String; default: Variant; field: TJSONObject): Variant;
function getCard(value: String): TCard;
function getCards(hand: TJSONArray): THandCards;
function getRelevantCard(hand: THandCards; card: TCard; vc: TCard): TCard;
function getAnyCard(hand: THandCards; card: TCard): TCard;
function getNextCard(hand: THandCards; card: TCard): TCard;
function getMyCards(hand: THandCards): String;
procedure splitCard(var hand: THandCards; card: TCard);
procedure setUsesCard(var hand: THandCards; c: TCard; value: boolean = true);
procedure setUnUsesCard(var hand: THandCards);
implementation
procedure splitCard(var hand: THandCards; card: TCard);
begin
SetLength(hand, Length(hand));
hand[Length(hand) - 1].use := false;
end;
function getMyCards(hand: THandCards): String;
var
i: integer;
begin
Result := '';
for i := 0 to Length(hand) - 1 do
if NOT hand[i].use then
Result := Result + hand[i].cType + hand[i].cVal + ' | ';
end;
procedure setUnUsesCard(var hand: THandCards);
var
i: integer;
begin
for i := 0 to Length(hand) - 1 do
hand[i].use := false;
end;
procedure setUsesCard(var hand: THandCards; c: TCard; value: boolean = true);
var
i: integer;
begin
for i := 0 to Length(hand) - 1 do
if (hand[i].cType = c.cType) AND (hand[i].cVal = c.cVal) then begin
hand[i].use := value;
break;
end;
end;
function getCardIndex(v: String): Integer;
begin
result := 0;
if v = 'J' then result := 1;
if v = 'Q' then result := 2;
if v = 'K' then result := 3;
if v = 'A' then result := 4;
end;
function canSetCard(a, b, c: TCard; cuse: boolean = false): boolean;
begin
Result := false;
if (b.use) then Exit;
if (a.cType <> b.cType) AND (b.cType <> c.cType) then Exit;
if (cuse) AND (b.cType = c.cType) AND (a.cType <> c.cType) then begin
Result := true;
Exit;
end;
if (a.cVal[1] in FCard) AND (NOT (b.cVal[1] in FCard)) then Exit;
if (NOT (a.cVal[1] in FCard)) AND (b.cVal[1] in FCard) then Result := true;
if (a.cVal[1] in FCard) AND (b.cVal[1] in FCard) then
if getCardIndex(a.cVal) < getCardIndex(b.cVal) then
Result := true;
end;
function getRelevantCard(hand: THandCards; card: TCard; vc: TCard): TCard;
var
i: integer;
begin
Result.cType := card.cType;
// Norm
for i := 0 to length(hand) - 1 do begin
if canSetCard(card, hand[i], vc) then begin
Result := hand[i];
Exit;
end;
end;
// Max
for i := 0 to length(hand) - 1 do begin
if canSetCard(card, hand[i], vc, true) then begin
Result := hand[i];
Exit;
end;
end;
end;
function getMinCard(hand: THandCards): TCard;
var
i: integer;
c: TCard;
begin
for i := 0 to length(hand) - 1 do begin
if hand[i].use then continue;
if (c.cVal = '') then begin
c := hand[i];
continue;
end;
if (c.cVal[1] in FCard) AND (hand[i].cVal[1] in FCard) then
if getCardIndex(c.cVal) > getCardIndex(hand[i].cVal) then begin
c := hand[i];
continue;
end;
if NOT (hand[i].cVal[1] in FCard) AND (c.cVal[1] in FCard) then begin
c := hand[i];
continue;
end;
if NOT (hand[i].cVal[1] in FCard) AND NOT (c.cVal[1] in FCard) then
if (StrToInt(c.cVal) > StrToInt(hand[i].cVal)) then begin
c := hand[i];
continue;
end;
end;
c.cVal := Trim(c.cVal);
Result := c;
end;
function getAnyCard(hand: THandCards; card: TCard): TCard;
begin
Result := getMinCard(hand);
end;
function getNextCard(hand: THandCards; card: TCard): TCard;
var
i,j: Integer;
c: TCard;
begin
Result.cVal := '';
for i := 0 to length(hand) - 1 do begin
if (hand[i].use) then begin
for j := 0 to length(hand) - 1 do begin
if (i = j) then continue;
if (hand[j].cVal = hand[i].cVal) AND (NOT hand[i].use) then begin
Result := hand[i];
Exit;
end;
end;
end;
if (hand[i].cVal = card.cVal) AND (NOT hand[i].use) then begin
Result := hand[i];
Exit;
end;
end;
Result.cVal := Trim(Result.cVal);
end;
function getCard(value: String): TCard;
begin
if (value = '') then exit;
Result.cType := value[1];
value[1] := ' ';
Result.cVal := trim(value);
Result.use := false;
end;
function getCards(hand: TJSONArray): THandCards;
var
i: integer;
begin
SetLength(Result, hand.Count);
for i := 0 to hand.Count - 1 do
Result[i] := getCard(hand.Items[i].Value);
i := 0;
end;
function getHttp(url: String): String;
var
lHTTP: TIdHTTP;
begin
lHTTP := TIdHTTP.Create(nil);
try
try
Result := lHTTP.Get(url);
except end;
finally
lHTTP.Free;
end;
end;
function getCommand(data: String): String;
var
s: string;
i: integer;
begin
for i := 1 to Length(data) do begin
if data[i] = '{' then break;
s := s + data[i];
end;
result := s;
end;
function getJson(json: String): TJsonValue;
var
data: string;
jps, aps: integer;
begin
data := json;
if ((data[1] <> '{') or (data[1] <> '[')) then begin
jps := pos('{', data);
aps := pos('[', data);
if ((aps <> 0) and (aps < jps)) then
jps := aps;
data := Copy(data, jps, length(data));
end;
try
if data <> '' then
result := TJSONObject.ParseJSONValue(data);
except
result := nil;
end;
end;
function getJsonParam(param: String; default: Variant; field: TJSONObject): Variant;
begin
try
if (field.Values[param] <> nil) then Result := field.Values[param].Value else Result := default;
except
Result := default;
end;
end;
end.
|
program programaRecursion2;
{--------------------------------------
DIGITOMAXIMO. Calcula el digito maximo de n}
procedure digitoMaximo(n: integer; var max: integer);
var
dig: integer;
begin
dig:= n mod 10;
if(dig > max) then
max:= dig;
n:= n div 10;
if (n <> 0) then // EL CASO BASE EN ESTE EJERCICIO ES CUANDO YA SE
digitoMaximo(n, max); // DESCOMPUSO POR COMPLETO EL NUMERO N (n mod 10 = 0).
// Se aproxima al caso base descomponiendo el número
writeln ('max: ', max); // dígito por dígito hasta que se descompuso por
// completo: : n div 10 = 0
end;
var
max, num: integer;
{programa principal}
Begin
max:= -1;
writeln( 'Ingrese un valor entero:');
readln(num);
digitoMaximo(num, max);
writeln();
writeln('El maximo digito de ',num,' es ', max);
readln;
End.
|
unit uOSVersionUtils;
interface
uses
System.SysUtils;
function OSArchitectureToStr(const a: TOSVersion.TArchitecture): string;
function OSPlatformToStr(const p: TOSVersion.TPlatform): string;
implementation
function OSArchitectureToStr(const a: TOSVersion.TArchitecture): string;
begin
case a of
arIntelX86:
Result := 'IntelX86';
arIntelX64:
Result := 'IntelX64';
else
Result := 'UNKNOWN OS architecture';
end;
end;
function OSPlatformToStr(const p: TOSVersion.TPlatform): string;
begin
case p of
pfWindows:
Result := 'Windows';
pfMacOS:
Result := 'MacOS';
else
Result := 'UNKNOWN OS Platform';
end;
end;
end.
|
unit uAddHora;
interface
uses SysUtils, DateUtils;
type
TTipoCalculo = (tcSoma, tcSubtrai, tcSomaHoraUtil);
TInterlado = record
HoraIni: TTime;
HoraFim: TTime;
end;
TIntervalos = Array of TInterlado;
TDiasSemana = set of AnsiChar;
THoraUtil = class
private
FIntervalo: TIntervalos;
FDiasSemana: TDiasSemana;
public
constructor Create(atHoraIni, atHoraFim: TTime; aiDiasSemana: TDiasSemana); overload;
procedure AddIntervalo(atHoraIni, atHoraFim: TTime);
property GetIntervalo: TIntervalos read FIntervalo;
function GetMaxHora: TTime;
function GetMinHora: TTime;
function GetProximatHora(adData: TDateTime): TTime;
property DiasSemana: TDiasSemana read FDiasSemana;
end;
TDateUtils = class
public
class function AddHora(adDataHoraInicio: TDateTime; aiHH, aiMM: Word; atTipoCalculo: TTipoCalculo; aoHoraUtil: THoraUtil = nil)
: TDateTime;
end;
implementation
{ THoraUtil }
constructor THoraUtil.Create(atHoraIni, atHoraFim: TTime; aiDiasSemana: TDiasSemana);
begin
inherited Create;
AddIntervalo(atHoraIni, atHoraFim);
FDiasSemana := aiDiasSemana;
end;
procedure THoraUtil.AddIntervalo(atHoraIni, atHoraFim: TTime);
var
i: Integer;
// vloListOrder : TList;
begin
if atHoraIni > atHoraFim then
raise Exception.Create('A Hora inicial não pode ser maior que a Hora Final. O Intervalo não foi Criado.')
else
begin
for i := Low(Self.GetIntervalo) to High(Self.GetIntervalo) do
if ((Self.GetIntervalo[i].HoraIni >= atHoraIni) and (Self.GetIntervalo[i].HoraFim <= atHoraIni)) or
((Self.GetIntervalo[i].HoraIni >= atHoraFim) and (Self.GetIntervalo[i].HoraFim <= atHoraFim)) or
((Self.GetIntervalo[i].HoraIni >= atHoraIni) and (Self.GetIntervalo[i].HoraFim <= atHoraFim)) then
raise Exception.Create('Intervalo com Horários concorrentes. O Intervalo não foi Criado.');
//
SetLength(FIntervalo, High(FIntervalo) + 2);
FIntervalo[ High(FIntervalo)].HoraIni := atHoraIni;
FIntervalo[ High(FIntervalo)].HoraFim := atHoraFim;
end;
end;
function THoraUtil.GetMaxHora: TTime;
var
i: Integer;
begin
Result := StrToTime('00:00');
for i := Low(Self.GetIntervalo) to High(Self.GetIntervalo) do
begin
if Self.GetIntervalo[i].HoraFim > Result then
Result := Self.GetIntervalo[i].HoraFim;
end;
end;
function THoraUtil.GetMinHora: TTime;
var
i: Integer;
begin
Result := Self.GetIntervalo[0].HoraIni;
for i := Low(Self.GetIntervalo) to High(Self.GetIntervalo) do
begin
if Self.GetIntervalo[i].HoraIni < Result then
Result := Self.GetIntervalo[i].HoraIni;
end;
end;
function THoraUtil.GetProximatHora(adData: TDateTime): TTime;
var
i: Integer;
vlbPegaMinHora : Boolean;
vlbHoraAux : TTime;
begin
Result := StrToTime('23:59');
vlbPegaMinHora := True;
if TimeOf(adData) = Self.GetMaxHora then
vlbHoraAux := StrToTime('00:00')
else
vlbHoraAux := TimeOf(adData);
for i := Low(Self.GetIntervalo) to High(Self.GetIntervalo) do
begin
if (Self.GetIntervalo[i].HoraIni > vlbHoraAux) and (Self.GetIntervalo[i].HoraIni < Result) then
begin
Result := Self.GetIntervalo[i].HoraIni;
vlbPegaMinHora := False;
end;
end;
if vlbPegaMinHora then
Result := Self.GetMinHora;
end;
{ TDateUtils }
class function TDateUtils.AddHora(adDataHoraInicio: TDateTime; aiHH, aiMM: Word; atTipoCalculo: TTipoCalculo; aoHoraUtil: THoraUtil)
: TDateTime;
var
vldDataHoraFim: TDateTime;
vldSaldoMinuto, vliMinuto: Word;
vliIncDay : Integer;
i: Integer;
begin
// -> Converte Horas para Minutos
vldSaldoMinuto := aiMM + (aiHH * 60);
// -> Segundos serão desconsiderados
vldDataHoraFim := DateOf(adDataHoraInicio) + StrToTime(FormatDateTime('hh:mm', adDataHoraInicio));
//
if atTipoCalculo = tcSoma then
vldDataHoraFim := IncMinute(vldDataHoraFim, vldSaldoMinuto)
else if atTipoCalculo = tcSubtrai then
vldDataHoraFim := IncMinute(vldDataHoraFim, vldSaldoMinuto * -1)
else if atTipoCalculo = tcSomaHoraUtil then
begin
if not Assigned(aoHoraUtil) then
aoHoraUtil := THoraUtil.Create(StrToTime('08:00'), StrToTime('18:00'), ['2' .. '6']);
if TimeOf(adDataHoraInicio) < aoHoraUtil.GetProximatHora(adDataHoraInicio) then
vldDataHoraFim := TDate(adDataHoraInicio) + aoHoraUtil.GetProximatHora(vldDataHoraFim)
else if TimeOf(adDataHoraInicio) >= aoHoraUtil.GetMaxHora then
vldDataHoraFim := IncDay(DateOf(adDataHoraInicio), 1) + aoHoraUtil.GetMinHora;
while vldSaldoMinuto > 0 do
begin
for i := Low(aoHoraUtil.GetIntervalo) to High(aoHoraUtil.GetIntervalo) do
begin
if TimeOf(vldDataHoraFim) < aoHoraUtil.GetIntervalo[i].HoraFim then
begin
if (vldSaldoMinuto <= MinutesBetween(vldDataHoraFim, DateOf(vldDataHoraFim) + aoHoraUtil.GetIntervalo[i].HoraFim)) then
begin
vldDataHoraFim := IncMinute(vldDataHoraFim, vldSaldoMinuto);
vldSaldoMinuto := 0;
end
else
begin
vliMinuto := MinutesBetween(vldDataHoraFim, DateOf(vldDataHoraFim) + aoHoraUtil.GetIntervalo[i].HoraFim);
vldDataHoraFim := IncMinute(vldDataHoraFim, vliMinuto);
vldSaldoMinuto := vldSaldoMinuto - vliMinuto;
if (DateOf(vldDataHoraFim) + aoHoraUtil.GetProximatHora(vldDataHoraFim) > vldDataHoraFim) and (vldSaldoMinuto > 0) then
vldDataHoraFim := DateOf(vldDataHoraFim) + aoHoraUtil.GetProximatHora(vldDataHoraFim)
else if (vldDataHoraFim >= DateOf(vldDataHoraFim) + aoHoraUtil.GetMaxHora) and (vldSaldoMinuto > 0) then
begin
vliIncDay := 1;
while not (IntToStr(DayOfWeek(IncDay(vldDataHoraFim, vliIncDay)))[1] in aoHoraUtil.DiasSemana) do
Inc(vliIncDay);
vldDataHoraFim := IncDay(DateOf(vldDataHoraFim), vliIncDay) + aoHoraUtil.GetMinHora;
end;
end;
end;
end;
end;
end;
Result := vldDataHoraFim;
end;
end.
|
unit SimpleDateRangePanelUnit;
interface
uses SysUtils, Classes, Controls, ComCtrls, ExtCtrls, Cloneable;
type
TDateTimeRange = class;
TSimpleDateRangePanel = class (TPanel)
private
FLeftDateTimePicker, FRightDateTimePicker: TDateTimePicker;
function GetLeftDateTime: TDateTime;
function GetRightDateTime: TDateTime;
procedure SetLeftDateTime(const LeftDateTime: TDateTime);
procedure SetRightDateTime(const RightDateTime: TDateTime);
public
constructor Create(AOwner: TComponent); overload; override;
constructor Create(
LeftDateTimePicker, RightDateTimePicker: TDateTimePicker;
AOwner: TComponent
); overload;
function GetCurrentDateTimeRange: TDateTimeRange;
procedure AssignFromDateTimeRange(
const DateTimeRange: TDateTimeRange
);
property LeftDateTime: TDateTime
read GetLeftDateTime write SetLeftDateTime;
property RightDateTime: TDateTime
read GetRightDateTime write SetRightDateTime;
property LeftDateTimePicker: TDateTimePicker
read FLeftDateTimePicker write FLeftDateTimePicker;
property RightDateTimePicker: TDateTimePicker
read FRightDateTimePicker write FRightDateTimePicker;
function GetLeftFormattedDateTimeString(const Format: String): String;
function GetRightFormattedDateTimeString(const Format: String): String;
end;
TDateTimeRange = class (TCloneable)
public
LeftDateTime: TDateTime;
RightDateTime: TDateTime;
constructor Create; overload;
constructor Create(const ALeftDateTime, ARightDateTime: TDateTime); overload;
function Clone: TObject; override;
end;
implementation
{ TSimpleDateRangePanel }
constructor TSimpleDateRangePanel.Create(AOwner: TComponent);
begin
inherited;
end;
procedure TSimpleDateRangePanel.AssignFromDateTimeRange(
const DateTimeRange: TDateTimeRange);
begin
LeftDateTime := DateTimeRange.LeftDateTime;
RightDateTime := DateTimeRange.RightDateTime;
end;
constructor TSimpleDateRangePanel.Create(LeftDateTimePicker,
RightDateTimePicker: TDateTimePicker; AOwner: TComponent);
begin
inherited Create(AOwner);
Self.LeftDateTimePicker := LeftDateTimePicker;
Self.RightDateTimePicker := RightDateTimePicker;
end;
function TSimpleDateRangePanel.GetCurrentDateTimeRange: TDateTimeRange;
begin
Result := TDateTimeRange.Create(LeftDateTime, RightDateTime);
end;
function TSimpleDateRangePanel.GetLeftDateTime: TDateTime;
begin
Result := FLeftDateTimePicker.DateTime;
end;
function TSimpleDateRangePanel.GetRightDateTime: TDateTime;
begin
Result := FRightDateTimePicker.DateTime;
end;
procedure TSimpleDateRangePanel.SetLeftDateTime(const LeftDateTime: TDateTime);
begin
FLeftDateTimePicker.DateTime := LeftDateTime;
end;
procedure TSimpleDateRangePanel.SetRightDateTime(const RightDateTime: TDateTime);
begin
FRightDateTimePicker.DateTime := RightDateTime;
end;
function TSimpleDateRangePanel.GetLeftFormattedDateTimeString(const Format: String): String;
begin
Result :=
FormatDateTime(
Format,
FLeftDateTimePicker.DateTime
);
end;
function TSimpleDateRangePanel.GetRightFormattedDateTimeString(const Format: String): String;
begin
Result :=
FormatDateTime(
Format,
FRightDateTimePicker.DateTime
);
end;
{ TDateTimeRange }
constructor TDateTimeRange.Create;
begin
inherited;
end;
function TDateTimeRange.Clone: TObject;
begin
Result := TDateTimeRange.Create(LeftDateTime, RightDateTime);
end;
constructor TDateTimeRange.Create(const ALeftDateTime,
ARightDateTime: TDateTime);
begin
inherited Create;
LeftDateTime := ALeftDateTime;
RightDateTime := ARightDateTime;
end;
end.
|
{ Invokable interface IAntennaWS }
unit AntennaWSIntf;
interface
uses InvokeRegistry, Types, XSBuiltIns, ElbrusTypes, Elbrus;
type
{ Invokable interfaces must derive from IInvokable }
IAntennaWS = interface(IInvokable)
['{E5342DDF-910D-4454-AE9B-B270C4865639}']
//Status
function Get_Estado: LongWord; safecall;
function Get_Antena_Listo: WordBool; safecall;
function Get_Averia_Excitacion: WordBool; safecall;
function Get_Limite_N: WordBool; safecall;
function Get_Limite_P: WordBool; safecall;
function Get_Acc_Listo: WordBool; safecall;
function Get_Cupula_Abierta: WordBool; safecall;
function Get_Acc_On: WordBool; safecall;
//Control
procedure Encender_Acc; safecall;
procedure Apagar_Acc; safecall;
procedure Alarma_Sonora(Tiempo: Integer); safecall;
property Estado: LongWord read Get_Estado;
property Antena_Listo: WordBool read Get_Antena_Listo;
property Averia_Excitacion: WordBool read Get_Averia_Excitacion;
property Limite_N: WordBool read Get_Limite_N;
property Limite_P: WordBool read Get_Limite_P;
property Acc_Listo: WordBool read Get_Acc_Listo;
property Cupula_Abierta: WordBool read Get_Cupula_Abierta;
property Acc_On: WordBool read Get_Acc_On;
end;
implementation
uses CommunicationObj;
initialization
{ Invokable interfaces must be registered }
InvRegistry.RegisterInterface(TypeInfo(IAntennaWS));
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:33
unit IdOpenSSLHeaders_dherr;
interface
// Headers for OpenSSL 1.1.1
// dherr.h
{$i IdCompilerDefines.inc}
uses
IdCTypes,
IdGlobal,
IdOpenSSLConsts;
const
// DH function codes
DH_F_COMPUTE_KEY = 102;
DH_F_DHPARAMS_PRINT_FP = 101;
DH_F_DH_BUILTIN_GENPARAMS = 106;
DH_F_DH_CHECK_EX = 121;
DH_F_DH_CHECK_PARAMS_EX = 122;
DH_F_DH_CHECK_PUB_KEY_EX = 123;
DH_F_DH_CMS_DECRYPT = 114;
DH_F_DH_CMS_SET_PEERKEY = 115;
DH_F_DH_CMS_SET_SHARED_INFO = 116;
DH_F_DH_METH_DUP = 117;
DH_F_DH_METH_NEW = 118;
DH_F_DH_METH_SET1_NAME = 119;
DH_F_DH_NEW_BY_NID = 104;
DH_F_DH_NEW_METHOD = 105;
DH_F_DH_PARAM_DECODE = 107;
DH_F_DH_PKEY_PUBLIC_CHECK = 124;
DH_F_DH_PRIV_DECODE = 110;
DH_F_DH_PRIV_ENCODE = 111;
DH_F_DH_PUB_DECODE = 108;
DH_F_DH_PUB_ENCODE = 109;
DH_F_DO_DH_PRINT = 100;
DH_F_GENERATE_KEY = 103;
DH_F_PKEY_DH_CTRL_STR = 120;
DH_F_PKEY_DH_DERIVE = 112;
DH_F_PKEY_DH_INIT = 125;
DH_F_PKEY_DH_KEYGEN = 113;
// DH reason codes
DH_R_BAD_GENERATOR = 101;
DH_R_BN_DECODE_ERROR = 109;
DH_R_BN_ERROR = 106;
DH_R_CHECK_INVALID_J_VALUE = 115;
DH_R_CHECK_INVALID_Q_VALUE = 116;
DH_R_CHECK_PUBKEY_INVALID = 122;
DH_R_CHECK_PUBKEY_TOO_LARGE = 123;
DH_R_CHECK_PUBKEY_TOO_SMALL = 124;
DH_R_CHECK_P_NOT_PRIME = 117;
DH_R_CHECK_P_NOT_SAFE_PRIME = 118;
DH_R_CHECK_Q_NOT_PRIME = 119;
DH_R_DECODE_ERROR = 104;
DH_R_INVALID_PARAMETER_NAME = 110;
DH_R_INVALID_PARAMETER_NID = 114;
DH_R_INVALID_PUBKEY = 102;
DH_R_KDF_PARAMETER_ERROR = 112;
DH_R_KEYS_NOT_SET = 108;
DH_R_MISSING_PUBKEY = 125;
DH_R_MODULUS_TOO_LARGE = 103;
DH_R_NOT_SUITABLE_GENERATOR = 120;
DH_R_NO_PARAMETERS_SET = 107;
DH_R_NO_PRIVATE_VALUE = 100;
DH_R_PARAMETER_ENCODING_ERROR = 105;
DH_R_PEER_KEY_ERROR = 111;
DH_R_SHARED_INFO_ERROR = 113;
DH_R_UNABLE_TO_CHECK_GENERATOR = 121;
function ERR_load_DH_strings: TIdC_INT cdecl; external CLibCrypto;
implementation
end.
|
unit uModelPessoa;
interface
type
TStatusCliente = (scTodos, scAtivo, scInativo);
type
TPessoa = class
private
FCodigo : Double;
FTipoPessoa : String;
FDataCadastro : TDate;
FRG_IE : String;
FCPF_CNPJ : String;
FNomeFantasia : String;
FRazaoSocial : String;
FEmail : String;
FCEP : String;
FEndereco : String;
FNumero : String;
FBairro : String;
FCidade : String;
FUF : String;
FTelefone : String;
FCelular : String;
FTipoCadastro : String;
FObservacao : String;
FInativo : TStatusCliente;
public
property Codigo : Double read FCodigo write FCodigo;
property TipoPessoa : String read FTipoPessoa write FTipoPessoa;
property DataCadastro : TDate read FDataCadastro write FDataCadastro;
property RG_IE : String read FRG_IE write FRG_IE;
property CPF_CNPJ : String read FCPF_CNPJ write FCPF_CNPJ;
property NomeFantasia : String read FNomeFantasia write FNomeFantasia;
property RazaoSocial : String read FRazaoSocial write FRazaoSocial;
property Email : String read FEmail write FEmail;
property CEP : String read FCEP write FCEP;
property Endereco : String read FEndereco write FEndereco;
property Numero : String read FNumero write FNumero;
property Bairro : String read FBairro write FBairro;
property Cidade : String read FCidade write FCidade;
property UF : String read FUF write FUF;
property Telefone : String read FTelefone write FTelefone;
property Celular : String read FCelular write FCelular;
property TipoCadastro : String read FTipoCadastro write FTipoCadastro;
property Observacao : String read FObservacao write FObservacao;
property Inativo : TStatusCliente read FInativo write FInativo;
end;
implementation
end.
|
unit CampoIncluidoAuditoria;
interface
uses
Auditoria;
type
TCampoIncluidoAuditoria = class
private
FCodigo :Integer;
FNomeCampo :String;
FValorCampo :String;
FCodigoAuditoria :Integer;
FAuditoria :TAuditoria;
procedure SetCodigo (const Value: Integer);
procedure SetNomeCampo (const Value: String);
procedure SetValorCampo (const Value: String);
procedure SetAuditoria (const Value: TAuditoria);
procedure SetCodigoAuditoria(const Value: Integer);
public
property Codigo :Integer read FCodigo write SetCodigo;
property NomeCampo :String read FNomeCampo write SetNomeCampo;
property ValorCampo :String read FValorCampo write SetValorCampo;
property Auditoria :TAuditoria read FAuditoria write SetAuditoria;
property CodigoAuditoria :Integer read FCodigoAuditoria write SetCodigoAuditoria;
end;
implementation
{ TCampoIncluidoAuditoria }
procedure TCampoIncluidoAuditoria.SetAuditoria(const Value: TAuditoria);
begin
FAuditoria := Value;
end;
procedure TCampoIncluidoAuditoria.SetCodigo(const Value: Integer);
begin
FCodigo := Value;
end;
procedure TCampoIncluidoAuditoria.SetCodigoAuditoria(const Value: Integer);
begin
FCodigoAuditoria := Value;
end;
procedure TCampoIncluidoAuditoria.SetNomeCampo(const Value: String);
begin
FNomeCampo := Value;
end;
procedure TCampoIncluidoAuditoria.SetValorCampo(const Value: String);
begin
FValorCampo := Value;
end;
end.
|
unit jclass_constants;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
jclass_common,
jclass_enum,
jclass_common_types,
fgl;
type
TJClassConstant = class;
TJClassConstants = class;
TJClassConstantClass = class of TJClassConstant;
{ TJClassConstant }
TJClassConstant = class(TJClassLoadable)
protected
FConstants: TJClassConstants;
public
procedure BuildDebugInfo(AIndent: string; AOutput: TStrings); override;
constructor Create(AConstants: TJClassConstants; out ADoubleSize: boolean); virtual;
end;
{ TJClassEmptyConstant }
TJClassEmptyConstant = class(TJClassConstant)
public
procedure BuildDebugInfo(AIndent: string; AOutput: TStrings); override;
procedure LoadFromStream(AStream: TStream); override;
end;
{ TJClassUtf8Constant }
TJClassUtf8Constant = class(TJClassConstant)
private
FUtf8String: UTF8String;
public
procedure BuildDebugInfo(AIndent: string; AOutput: TStrings); override;
procedure LoadFromStream(AStream: TStream); override;
function AsString: string;
end;
{ TJClassIntegerConstant }
TJClassIntegerConstant = class(TJClassConstant)
private
FInteger: Int32;
public
procedure BuildDebugInfo(AIndent: string; AOutput: TStrings); override;
procedure LoadFromStream(AStream: TStream); override;
property AsInteger: Int32 read FInteger;
end;
{ TJClassFloatConstant }
TJClassFloatConstant = class(TJClassConstant)
private
FFloat: single;
public
procedure BuildDebugInfo(AIndent: string; AOutput: TStrings); override;
procedure LoadFromStream(AStream: TStream); override;
property AsFloat: single read FFloat;
end;
{ TJClassLongConstant }
TJClassLongConstant = class(TJClassConstant)
private
FLong: int64;
public
procedure BuildDebugInfo(AIndent: string; AOutput: TStrings); override;
constructor Create(AConstants: TJClassConstants; out ADoubleSize: boolean); override;
procedure LoadFromStream(AStream: TStream); override;
property AsLong: int64 read FLong;
end;
{ TJClassDoubleConstant }
TJClassDoubleConstant = class(TJClassConstant)
private
FDouble: double;
public
procedure BuildDebugInfo(AIndent: string; AOutput: TStrings); override;
constructor Create(AConstants: TJClassConstants; out ADoubleSize: boolean); override;
procedure LoadFromStream(AStream: TStream); override;
property AsDouble: double read FDouble;
end;
{ TJClassNamedConstant }
TJClassNamedConstant = class(TJClassConstant)
private
FNameIndex: UInt16;
protected
function GetTypeName: string; virtual; abstract;
public
procedure BuildDebugInfo(AIndent: string; AOutput: TStrings); override;
procedure LoadFromStream(AStream: TStream); override;
property NameIndex: UInt16 read FNameIndex;
end;
{ TJClassClassConstant }
TJClassClassConstant = class(TJClassNamedConstant)
protected
function GetTypeName: string; override;
end;
{ TJClassModuleConstant }
TJClassModuleConstant = class(TJClassNamedConstant)
protected
function GetTypeName: string; override;
end;
{ TJClassPackageConstant }
TJClassPackageConstant = class(TJClassNamedConstant)
protected
function GetTypeName: string; override;
end;
{ TJClassStringConstant }
TJClassStringConstant = class(TJClassConstant)
private
FStringIndex: UInt16;
public
procedure LoadFromStream(AStream: TStream); override;
procedure BuildDebugInfo(AIndent: string; AOutput: TStrings); override;
property StringIndex: UInt16 read FStringIndex;
end;
{ TJClassRefConstant }
TJClassRefConstant = class(TJClassConstant)
private
FRefIndex: UInt16;
FNameAndTypeIndex: UInt16;
protected
function GetRefName: string; virtual; abstract;
public
procedure BuildDebugInfo(AIndent: string; AOutput: TStrings); override;
procedure LoadFromStream(AStream: TStream); override;
property RefIndex: UInt16 read FRefIndex;
end;
{ TJClassFieldrefConstant }
TJClassFieldrefConstant = class(TJClassRefConstant)
protected
function GetRefName: string; override;
end;
{ TJClassMethodrefConstant }
TJClassMethodrefConstant = class(TJClassRefConstant)
protected
function GetRefName: string; override;
end;
{ TJClassInterfaceMethodrefConstant }
TJClassInterfaceMethodrefConstant = class(TJClassRefConstant)
protected
function GetRefName: string; override;
end;
{ TJClassNameAndTypeConstant }
TJClassNameAndTypeConstant = class(TJClassConstant)
private
FNameIndex: UInt16;
FDescriptorIndex: UInt16;
public
procedure BuildDebugInfo(AIndent: string; AOutput: TStrings); override;
procedure LoadFromStream(AStream: TStream); override;
property NameIndex: UInt16 read FNameIndex;
property DescriptorIndex: UInt16 read FDescriptorIndex;
end;
{ TJClassMethodHandleConstant }
TJClassMethodHandleConstant = class(TJClassConstant)
private
FReferenceKind: UInt8;
FReferenceIndex: UInt16;
public
procedure LoadFromStream(AStream: TStream); override;
property ReferenceKind: UInt8 read FReferenceKind;
property ReferenceIndex: UInt16 read FReferenceIndex;
end;
{ TJClassMethodTypeConstant }
TJClassMethodTypeConstant = class(TJClassConstant)
private
FDescriptorIndex: UInt16;
public
procedure LoadFromStream(AStream: TStream); override;
property DescriptorIndex: UInt16 read FDescriptorIndex;
end;
{ TJClassDynamicGeneralConstant }
TJClassDynamicGeneralConstant = class(TJClassConstant)
private
FBootstrapMethodAttrIndex: UInt16;
FNameAndTypeIndex: UInt16;
public
procedure LoadFromStream(AStream: TStream); override;
property BootstrapMethodAttrIndex: UInt16 read FBootstrapMethodAttrIndex;
property NameAndTypeIndex: UInt16 read FNameAndTypeIndex;
end;
TJClassDynamicConstant = class(TJClassDynamicGeneralConstant);
TJClassInvokeDynamicConstant = class(TJClassDynamicGeneralConstant);
{ TJClassConstants }
TJClassConstants = class(specialize TFPGObjectList<TJClassConstant>)
public
procedure BuildDebugInfo(AIndent: string; AOutput: TStrings);
procedure LoadFromStream(AStream: TStream);
function CreateNewConst(ATag: TJConstantType; out ADoubleSize: boolean): TJClassConstant;
function FindConstant(AIndex: TConstIndex): TJClassConstant;
function FindConstantSafe(AIndex: TConstIndex; AClass: TJClassConstantClass): TJClassConstant;
function FindUtf8Constant(AIndex: TConstIndex): string;
end;
const
JConstantTypeNames: array[1..20] of string = (
'Utf8',
'ERROR',
'Integer',
'Float',
'Long',
'Double',
'Class',
'String',
'Fieldref',
'Methodref',
'InterfaceMethodref',
'NameAndType',
'ERROR',
'ERROR',
'MethodHandle',
'MethodType',
'Dynamic',
'InvokeDynamic',
'Module',
'Package'
);
JConstantTypes: array[1..20] of TJClassConstantClass = (
TJClassUtf8Constant,
nil,
TJClassIntegerConstant,
TJClassFloatConstant,
TJClassLongConstant,
TJClassDoubleConstant,
TJClassClassConstant,
TJClassStringConstant,
TJClassFieldrefConstant,
TJClassMethodrefConstant,
TJClassInterfaceMethodrefConstant,
TJClassNameAndTypeConstant,
nil,
nil,
TJClassMethodHandleConstant,
TJClassMethodTypeConstant,
TJClassDynamicConstant,
TJClassInvokeDynamicConstant,
TJClassModuleConstant,
TJClassPackageConstant
);
implementation
{ TJClassEmptyConstant }
procedure TJClassEmptyConstant.BuildDebugInfo(AIndent: string; AOutput: TStrings);
begin
AOutput.Add(AIndent + 'Empty slot after 8-byte constant');
end;
procedure TJClassEmptyConstant.LoadFromStream(AStream: TStream);
begin
end;
{ TJClassConstants }
procedure TJClassConstants.BuildDebugInfo(AIndent: string; AOutput: TStrings);
var
i: integer;
begin
AOutput.Add('%sCount: %d', [AIndent, Count]);
for i := 0 to Count - 1 do
Items[i].BuildDebugInfo(AIndent + ' ', AOutput);
end;
procedure TJClassConstants.LoadFromStream(AStream: TStream);
var
constant: TJClassConstant;
constantCount: UInt16;
tag: UInt8;
i: integer;
doubleSize: boolean;
begin
constantCount := TJClassConstant.ReadWord(AStream) - 1;
i := 0;
while i < constantCount do
begin
tag := TJClassConstant.ReadByte(AStream);
constant := JConstantTypes[tag].Create(self, doubleSize);
try
constant.LoadFromStream(AStream);
Add(constant);
except
constant.Free;
raise;
end;
if doubleSize then
begin
Add(TJClassEmptyConstant.Create(Self, doubleSize));
Inc(i);
end;
Inc(i);
end;
end;
function TJClassConstants.CreateNewConst(ATag: TJConstantType;
out ADoubleSize: boolean): TJClassConstant;
begin
if (Ord(ATag) < 1) or (Ord(ATag) > 20) then
raise Exception.Create('Constant type index out of bounds');
if not Assigned(JConstantTypes[Ord(ATag)]) then
raise Exception.Create('Constant type not found');
Result := JConstantTypes[Ord(ATag)].Create(Self, ADoubleSize);
end;
function TJClassConstants.FindConstant(AIndex: TConstIndex): TJClassConstant;
begin
Result := Items[AIndex - 1];
end;
function TJClassConstants.FindConstantSafe(AIndex: TConstIndex;
AClass: TJClassConstantClass): TJClassConstant;
begin
Result := FindConstant(AIndex);
if not (Result is AClass) then
raise Exception.CreateFmt('Wrong constant type "%s", expected "%s" at %d',
[Result.ClassName, AClass.ClassName, AIndex - 1]);
end;
function TJClassConstants.FindUtf8Constant(AIndex: TConstIndex): string;
begin
Result := TJClassUtf8Constant(FindConstantSafe(AIndex, TJClassUtf8Constant)).AsString;
end;
{ TJClassInterfaceMethodrefConstant }
function TJClassInterfaceMethodrefConstant.GetRefName: string;
begin
Result := 'InterfaceMethod';
end;
{ TJClassMethodrefConstant }
function TJClassMethodrefConstant.GetRefName: string;
begin
Result := 'Method';
end;
{ TJClassFieldrefConstant }
function TJClassFieldrefConstant.GetRefName: string;
begin
Result := 'Field';
end;
{ TJClassPackageConstant }
function TJClassPackageConstant.GetTypeName: string;
begin
Result := 'Package';
end;
{ TJClassModuleConstant }
function TJClassModuleConstant.GetTypeName: string;
begin
Result := 'Module';
end;
{ TJClassClassConstant }
function TJClassClassConstant.GetTypeName: string;
begin
Result := 'Class';
end;
{ TJClassConstant }
procedure TJClassConstant.BuildDebugInfo(AIndent: string; AOutput: TStrings);
begin
AOutput.Add(AIndent + ClassName);
end;
constructor TJClassConstant.Create(AConstants: TJClassConstants; out ADoubleSize: boolean);
begin
FConstants := AConstants;
ADoubleSize := False;
end;
{ TJClassNameAndTypeConstant }
procedure TJClassNameAndTypeConstant.BuildDebugInfo(AIndent: string; AOutput: TStrings);
begin
AOutput.Add('%sName and type: name "%s", type "%s"',
[AIndent, FConstants.FindUtf8Constant(FNameIndex),
FConstants.FindUtf8Constant(FDescriptorIndex)]);
end;
procedure TJClassNameAndTypeConstant.LoadFromStream(AStream: TStream);
begin
FNameIndex := ReadWord(AStream);
FDescriptorIndex := ReadWord(AStream);
end;
{ TJClassDynamicGeneralConstant }
procedure TJClassDynamicGeneralConstant.LoadFromStream(AStream: TStream);
begin
FBootstrapMethodAttrIndex := ReadWord(AStream);
FNameAndTypeIndex := ReadWord(AStream);
end;
{ TJClassMethodTypeConstant }
procedure TJClassMethodTypeConstant.LoadFromStream(AStream: TStream);
begin
FDescriptorIndex := ReadWord(AStream);
end;
{ TJClassMethodHandleConstant }
procedure TJClassMethodHandleConstant.LoadFromStream(AStream: TStream);
begin
FReferenceKind := ReadByte(AStream);
FReferenceIndex := ReadWord(AStream);
end;
{ TJClassRefConstant }
procedure TJClassRefConstant.BuildDebugInfo(AIndent: string; AOutput: TStrings);
begin
AOutput.Add('%s%sref: target (%d), name and type (%d)',
[AIndent, GetRefName, FRefIndex, FNameAndTypeIndex]);
end;
procedure TJClassRefConstant.LoadFromStream(AStream: TStream);
begin
FRefIndex := ReadWord(AStream);
FNameAndTypeIndex := ReadWord(AStream);
end;
{ TJClassStringConstant }
procedure TJClassStringConstant.LoadFromStream(AStream: TStream);
begin
FStringIndex := ReadWord(AStream);
end;
procedure TJClassStringConstant.BuildDebugInfo(AIndent: string; AOutput: TStrings);
begin
AOutput.Add('%sString: "%s"', [AIndent, FConstants.FindUtf8Constant(FStringIndex)]);
end;
{ TJClassNamedConstant }
procedure TJClassNamedConstant.BuildDebugInfo(AIndent: string; AOutput: TStrings);
begin
AOutput.Add('%s%s: %s', [AIndent, GetTypeName, FConstants.FindUtf8Constant(FNameIndex)]);
end;
procedure TJClassNamedConstant.LoadFromStream(AStream: TStream);
begin
FNameIndex := ReadWord(AStream);
end;
{ TJClassDoubleConstant }
procedure TJClassDoubleConstant.BuildDebugInfo(AIndent: string; AOutput: TStrings);
begin
AOutput.Add('%sDouble: %f', [AIndent, FDouble]);
end;
constructor TJClassDoubleConstant.Create(AConstants: TJClassConstants; out ADoubleSize: boolean);
begin
inherited Create(AConstants, ADoubleSize);
ADoubleSize := True;
end;
procedure TJClassDoubleConstant.LoadFromStream(AStream: TStream);
var
doubleBuf: double;
valueBuf: array[0..1] of UInt32 absolute doubleBuf;
begin
valueBuf[1] := ReadDWord(AStream);
valueBuf[0] := ReadDWord(AStream);
FDouble := doubleBuf;
end;
{ TJClassLongConstant }
procedure TJClassLongConstant.BuildDebugInfo(AIndent: string; AOutput: TStrings);
begin
AOutput.Add('%sLong: %d', [AIndent, FLong]);
end;
constructor TJClassLongConstant.Create(AConstants: TJClassConstants; out ADoubleSize: boolean);
begin
inherited Create(AConstants, ADoubleSize);
ADoubleSize := True;
end;
procedure TJClassLongConstant.LoadFromStream(AStream: TStream);
var
longBuf: UInt64;
valueBuf: array[0..1] of UInt32 absolute longBuf;
begin
valueBuf[1] := ReadDWord(AStream);
valueBuf[0] := ReadDWord(AStream);
FLong := longBuf;
end;
{ TJClassFloatConstant }
procedure TJClassFloatConstant.BuildDebugInfo(AIndent: string; AOutput: TStrings);
begin
AOutput.Add('%sFloat: %f', [AIndent, FFloat]);
end;
procedure TJClassFloatConstant.LoadFromStream(AStream: TStream);
begin
FFloat := ReadDWord(AStream);
end;
{ TJClassIntegerConstant }
procedure TJClassIntegerConstant.BuildDebugInfo(AIndent: string; AOutput: TStrings);
begin
AOutput.Add('%sInt: %d', [AIndent, FInteger]);
end;
procedure TJClassIntegerConstant.LoadFromStream(AStream: TStream);
begin
FInteger := ReadDWord(AStream);
end;
{ TJClassUtf8Constant }
procedure TJClassUtf8Constant.BuildDebugInfo(AIndent: string; AOutput: TStrings);
begin
AOutput.Add('%sUTF8: "%s"', [AIndent, FUtf8String]);
end;
procedure TJClassUtf8Constant.LoadFromStream(AStream: TStream);
begin
SetLength(FUtf8String, ReadWord(AStream));
if Length(FUtf8String) > 0 then
AStream.Read(FUtf8String[1], Length(FUtf8String));
end;
function TJClassUtf8Constant.AsString: string;
begin
Result := FUtf8String;
end;
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 }
{ }
{******************************************************************************}
unit IdOpenSSLHeaders_dh;
interface
// Headers for OpenSSL 1.1.1
// dh.h
{$i IdCompilerDefines.inc}
uses
IdCTypes,
IdGlobal,
IdOpenSSLConsts,
IdOpenSSLHeaders_ossl_typ,
IdOpenSSLHeaders_evp;
const
OPENSSL_DH_MAX_MODULUS_BITS = 10000;
OPENSSL_DH_FIPS_MIN_MODULUS_BITS = 1024;
DH_FLAG_CACHE_MONT_P = $01;
DH_FLAG_FIPS_METHOD = $0400;
DH_FLAG_NON_FIPS_ALLOW = $0400;
DH_GENERATOR_2 = 2;
DH_GENERATOR_5 = 5;
DH_CHECK_P_NOT_PRIME = $01;
DH_CHECK_P_NOT_SAFE_PRIME = $02;
DH_UNABLE_TO_CHECK_GENERATOR = $04;
DH_NOT_SUITABLE_GENERATOR = $08;
DH_CHECK_Q_NOT_PRIME = $10;
DH_CHECK_INVALID_Q_VALUE = $20;
DH_CHECK_INVALID_J_VALUE = $40;
DH_CHECK_PUBKEY_TOO_SMALL = $01;
DH_CHECK_PUBKEY_TOO_LARGE = $02;
DH_CHECK_PUBKEY_INVALID = $04;
DH_CHECK_P_NOT_STRONG_PRIME = DH_CHECK_P_NOT_SAFE_PRIME;
EVP_PKEY_DH_KDF_NONE = 1;
EVP_PKEY_DH_KDF_X9_42 = 2;
EVP_PKEY_CTRL_DH_PARAMGEN_PRIME_LEN = (EVP_PKEY_ALG_CTRL + 1);
EVP_PKEY_CTRL_DH_PARAMGEN_GENERATOR = (EVP_PKEY_ALG_CTRL + 2);
EVP_PKEY_CTRL_DH_RFC5114 = (EVP_PKEY_ALG_CTRL + 3);
EVP_PKEY_CTRL_DH_PARAMGEN_SUBPRIME_LEN = (EVP_PKEY_ALG_CTRL + 4);
EVP_PKEY_CTRL_DH_PARAMGEN_TYPE = (EVP_PKEY_ALG_CTRL + 5);
EVP_PKEY_CTRL_DH_KDF_TYPE = (EVP_PKEY_ALG_CTRL + 6);
EVP_PKEY_CTRL_DH_KDF_MD = (EVP_PKEY_ALG_CTRL + 7);
EVP_PKEY_CTRL_GET_DH_KDF_MD = (EVP_PKEY_ALG_CTRL + 8);
EVP_PKEY_CTRL_DH_KDF_OUTLEN = (EVP_PKEY_ALG_CTRL + 9);
EVP_PKEY_CTRL_GET_DH_KDF_OUTLEN = (EVP_PKEY_ALG_CTRL + 10);
EVP_PKEY_CTRL_DH_KDF_UKM = (EVP_PKEY_ALG_CTRL + 11);
EVP_PKEY_CTRL_GET_DH_KDF_UKM = (EVP_PKEY_ALG_CTRL + 12);
EVP_PKEY_CTRL_DH_KDF_OID = (EVP_PKEY_ALG_CTRL + 13);
EVP_PKEY_CTRL_GET_DH_KDF_OID = (EVP_PKEY_ALG_CTRL + 14);
EVP_PKEY_CTRL_DH_NID = (EVP_PKEY_ALG_CTRL + 15);
EVP_PKEY_CTRL_DH_PAD = (EVP_PKEY_ALG_CTRL + 16);
type
DH_meth_generate_key_cb = function(dh: PDH): TIdC_INT cdecl;
DH_meth_compute_key_cb = function(key: PByte; const pub_key: PBIGNUM; dh: PDH): TIdC_INT cdecl;
DH_meth_bn_mod_exp_cb = function(
const dh: PDH; r: PBIGNUM; const a: PBIGNUM;
const p: PBIGNUM; const m: PBIGNUM;
ctx: PBN_CTX; m_ctx: PBN_MONT_CTX): TIdC_INT cdecl;
DH_meth_init_cb = function(dh: PDH): TIdC_INT cdecl;
DH_meth_finish_cb = function(dh: PDH): TIdC_INT cdecl;
DH_meth_generate_params_cb = function(dh: PDH; prime_len: TIdC_INT; generator: TIdC_INT; cb: PBN_GENCB): TIdC_INT cdecl;
var
{
# define DH_CHECK_P_NOT_STRONG_PRIME DH_CHECK_P_NOT_SAFE_PRIME
# define d2i_DHparams_fp(fp,x) \
(DH *)ASN1_d2i_fp((char *(*)())DH_new, \
(char *(*)())d2i_DHparams, \
(fp), \
(unsigned char **)(x))
# define i2d_DHparams_fp(fp,x) \
ASN1_i2d_fp(i2d_DHparams,(fp), (unsigned char *)(x))
# define d2i_DHparams_bio(bp,x) \
ASN1_d2i_bio_of(DH, DH_new, d2i_DHparams, bp, x)
# define i2d_DHparams_bio(bp,x) \
ASN1_i2d_bio_of_const(DH,i2d_DHparams,bp,x)
# define d2i_DHxparams_fp(fp,x) \
(DH *)ASN1_d2i_fp((char *(*)())DH_new, \
(char *(*)())d2i_DHxparams, \
(fp), \
(unsigned char **)(x))
# define i2d_DHxparams_fp(fp,x) \
ASN1_i2d_fp(i2d_DHxparams,(fp), (unsigned char *)(x))
# define d2i_DHxparams_bio(bp,x) \
ASN1_d2i_bio_of(DH, DH_new, d2i_DHxparams, bp, x)
# define i2d_DHxparams_bio(bp,x) \
ASN1_i2d_bio_of_const(DH, i2d_DHxparams, bp, x)
}
function DHparams_dup(dh: PDH): PDH;
function DH_OpenSSL: PDH_Method;
procedure DH_set_default_method(const meth: PDH_Method);
function DH_get_default_method: PDH_Method;
function DH_set_method(dh: PDH; const meth: PDH_Method): TIdC_INT;
function DH_new_method(engine: PENGINE): PDH;
function DH_new: PDH;
procedure DH_free(dh: PDH);
function DH_up_ref(dh: PDH): TIdC_INT;
function DH_bits(const dh: PDH): TIdC_INT;
function DH_size(const dh: PDH): TIdC_INT;
function DH_security_bits(const dh: PDH): TIdC_INT;
function DH_set_ex_data(d: PDH; idx: TIdC_INT; arg: Pointer): TIdC_INT;
function DH_get_ex_data(d: PDH; idx: TIdC_INT): Pointer;
function DH_generate_parameters_ex(dh: PDH; prime_len: TIdC_INT; generator: TIdC_INT; cb: PBN_GENCB): TIdC_INT;
function DH_check_params_ex(const dh: PDH): TIdC_INT;
function DH_check_ex(const dh: PDH): TIdC_INT;
function DH_check_pub_key_ex(const dh: PDH; const pub_key: PBIGNUM): TIdC_INT;
function DH_check_params(const dh: PDH; ret: PIdC_INT): TIdC_INT;
function DH_check(const dh: PDH; codes: PIdC_INT): TIdC_INT;
function DH_check_pub_key(const dh: PDH; const pub_key: PBIGNUM; codes: PIdC_INT): TIdC_INT;
function DH_generate_key(dh: PDH): TIdC_INT;
function DH_compute_key(key: PByte; const pub_key: PBIGNUM; dh: PDH): TIdC_INT;
function DH_compute_key_padded(key: PByte; const pub_key: PBIGNUM; dh: PDH): TIdC_INT;
function d2i_DHparams(a: PPDH; const pp: PPByte; length: TIdC_LONG): PDH;
function i2d_DHparams(const a: PDH; pp: PPByte): TIdC_INT;
function d2i_DHxparams(a: PPDH; const pp: PPByte; length: TIdC_LONG): PDH;
function i2d_DHxparams(const a: PDH; pp: PPByte): TIdC_INT;
function DHparams_print(bp: PBIO; const x: PDH): TIdC_INT;
function DH_get_1024_160: PDH;
function DH_get_2048_224: PDH;
function DH_get_2048_256: PDH;
function DH_new_by_nid(nid: TIdC_INT): PDH;
function DH_get_nid(const dh: PDH): TIdC_INT;
function DH_KDF_X9_42( out_: PByte; outlen: TIdC_SIZET; const Z: PByte; Zlen: TIdC_SIZET; key_oid: PASN1_OBJECT; const ukm: PByte; ukmlen: TIdC_SIZET; const md: PEVP_MD): TIdC_INT;
procedure DH_get0_pqg(const dh: PDH; const p: PPBIGNUM; const q: PPBIGNUM; const g: PPBIGNUM);
function DH_set0_pqg(dh: PDH; p: PBIGNUM; q: PBIGNUM; g: PBIGNUM): TIdC_INT;
procedure DH_get0_key(const dh: PDH; const pub_key: PPBIGNUM; const priv_key: PPBIGNUM);
function DH_set0_key(dh: PDH; pub_key: PBIGNUM; priv_key: PBIGNUM): TIdC_INT;
function DH_get0_p(const dh: PDH): PBIGNUM;
function DH_get0_q(const dh: PDH): PBIGNUM;
function DH_get0_g(const dh: PDH): PBIGNUM;
function DH_get0_priv_key(const dh: PDH): PBIGNUM;
function DH_get0_pub_key(const dh: PDH): PBIGNUM;
procedure DH_clear_flags(dh: PDH; flags: TIdC_INT);
function DH_test_flags(const dh: PDH; flags: TIdC_INT): TIdC_INT;
procedure DH_set_flags(dh: PDH; flags: TIdC_INT);
function DH_get0_engine(d: PDH): PENGINE;
function DH_get_length(const dh: PDH): TIdC_LONG;
function DH_set_length(dh: PDH; length: TIdC_LONG): TIdC_INT;
function DH_meth_new(const name: PIdAnsiChar; flags: TIdC_INT): PDH_Method;
procedure DH_meth_free(dhm: PDH_Method);
function DH_meth_dup(const dhm: PDH_Method): PDH_Method;
function DH_meth_get0_name(const dhm: PDH_Method): PIdAnsiChar;
function DH_meth_set1_name(dhm: PDH_Method; const name: PIdAnsiChar): TIdC_INT;
function DH_meth_get_flags(const dhm: PDH_Method): TIdC_INT;
function DH_meth_set_flags(const dhm: PDH_Method; flags: TIdC_INT): TIdC_INT;
function DH_meth_get0_app_data(const dhm: PDH_Method): Pointer;
function DH_meth_set0_app_data(const dhm: PDH_Method; app_data: Pointer): TIdC_INT;
function DH_meth_get_generate_key(const dhm: PDH_Method): DH_meth_generate_key_cb;
function DH_meth_set_generate_key(const dhm: PDH_Method; generate_key: DH_meth_generate_key_cb): TIdC_INT;
function DH_meth_get_compute_key(const dhm: PDH_Method): DH_meth_compute_key_cb;
function DH_meth_set_compute_key(const dhm: PDH_Method; compute_key: DH_meth_compute_key_cb): TIdC_INT;
function DH_meth_get_bn_mod_exp(const dhm: PDH_Method): DH_meth_bn_mod_exp_cb;
function DH_meth_set_bn_mod_exp(const dhm: PDH_Method; bn_mod_expr: DH_meth_bn_mod_exp_cb): TIdC_INT;
function DH_meth_get_init(const dhm: PDH_Method): DH_meth_init_cb;
function DH_meth_set_init(const dhm: PDH_Method; init: DH_meth_init_cb): TIdC_INT;
function DH_meth_get_finish(const dhm: PDH_Method): DH_meth_finish_cb;
function DH_meth_set_finish(const dhm: PDH_Method; finish: DH_meth_finish_cb): TIdC_INT;
function DH_meth_get_generate_params(const dhm: PDH_Method): DH_meth_generate_params_cb;
function DH_meth_set_generate_params(const dhm: PDH_Method; generate_params: DH_meth_generate_params_cb): TIdC_INT;
{
# define EVP_PKEY_CTX_set_dh_paramgen_prime_len(ctx, len) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DH, EVP_PKEY_OP_PARAMGEN, \
EVP_PKEY_CTRL_DH_PARAMGEN_PRIME_LEN, len, NULL)
# define EVP_PKEY_CTX_set_dh_paramgen_subprime_len(ctx, len) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DH, EVP_PKEY_OP_PARAMGEN, \
EVP_PKEY_CTRL_DH_PARAMGEN_SUBPRIME_LEN, len, NULL)
# define EVP_PKEY_CTX_set_dh_paramgen_type(ctx, typ) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DH, EVP_PKEY_OP_PARAMGEN, \
EVP_PKEY_CTRL_DH_PARAMGEN_TYPE, typ, NULL)
# define EVP_PKEY_CTX_set_dh_paramgen_generator(ctx, gen) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DH, EVP_PKEY_OP_PARAMGEN, \
EVP_PKEY_CTRL_DH_PARAMGEN_GENERATOR, gen, NULL)
# define EVP_PKEY_CTX_set_dh_rfc5114(ctx, gen) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, EVP_PKEY_OP_PARAMGEN, \
EVP_PKEY_CTRL_DH_RFC5114, gen, NULL)
# define EVP_PKEY_CTX_set_dhx_rfc5114(ctx, gen) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, EVP_PKEY_OP_PARAMGEN, \
EVP_PKEY_CTRL_DH_RFC5114, gen, NULL)
# define EVP_PKEY_CTX_set_dh_nid(ctx, nid) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DH, \
EVP_PKEY_OP_PARAMGEN | EVP_PKEY_OP_KEYGEN, \
EVP_PKEY_CTRL_DH_NID, nid, NULL)
# define EVP_PKEY_CTX_set_dh_pad(ctx, pad) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DH, EVP_PKEY_OP_DERIVE, \
EVP_PKEY_CTRL_DH_PAD, pad, NULL)
# define EVP_PKEY_CTX_set_dh_kdf_type(ctx, kdf) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \
EVP_PKEY_OP_DERIVE, \
EVP_PKEY_CTRL_DH_KDF_TYPE, kdf, NULL)
# define EVP_PKEY_CTX_get_dh_kdf_type(ctx) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \
EVP_PKEY_OP_DERIVE, \
EVP_PKEY_CTRL_DH_KDF_TYPE, -2, NULL)
# define EVP_PKEY_CTX_set0_dh_kdf_oid(ctx, oid) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \
EVP_PKEY_OP_DERIVE, \
EVP_PKEY_CTRL_DH_KDF_OID, 0, (void *)(oid))
# define EVP_PKEY_CTX_get0_dh_kdf_oid(ctx, poid) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \
EVP_PKEY_OP_DERIVE, \
EVP_PKEY_CTRL_GET_DH_KDF_OID, 0, (void *)(poid))
# define EVP_PKEY_CTX_set_dh_kdf_md(ctx, md) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \
EVP_PKEY_OP_DERIVE, \
EVP_PKEY_CTRL_DH_KDF_MD, 0, (void *)(md))
# define EVP_PKEY_CTX_get_dh_kdf_md(ctx, pmd) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \
EVP_PKEY_OP_DERIVE, \
EVP_PKEY_CTRL_GET_DH_KDF_MD, 0, (void *)(pmd))
# define EVP_PKEY_CTX_set_dh_kdf_outlen(ctx, len) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \
EVP_PKEY_OP_DERIVE, \
EVP_PKEY_CTRL_DH_KDF_OUTLEN, len, NULL)
# define EVP_PKEY_CTX_get_dh_kdf_outlen(ctx, plen) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \
EVP_PKEY_OP_DERIVE, \
EVP_PKEY_CTRL_GET_DH_KDF_OUTLEN, 0, (void *)(plen))
# define EVP_PKEY_CTX_set0_dh_kdf_ukm(ctx, p, plen) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \
EVP_PKEY_OP_DERIVE, \
EVP_PKEY_CTRL_DH_KDF_UKM, plen, (void *)(p))
# define EVP_PKEY_CTX_get0_dh_kdf_ukm(ctx, p) \
EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \
EVP_PKEY_OP_DERIVE, \
EVP_PKEY_CTRL_GET_DH_KDF_UKM, 0, (void *)(p))
}
implementation
end.
|
unit Facturacion.GeneradorSelloV33;
interface
uses Facturacion.Comprobante,
Facturacion.GeneradorSello,
Facturacion.OpenSSL;
type
TGeneradorSelloV33 = class(TInterfacedObject, IGeneradorSello)
private
fInstanciaOpenSSL: IOpenSSL;
public
procedure Configurar(const aOpenSSL: IOpenSSL);
function GenerarSelloDeFactura(const aCadenaOriginal: TCadenaUTF8): TCadenaUTF8;
// function GenerarSello(const aCadenaOriginal: TCadenaUTF8): TCadenaUTF8;
End;
implementation
{ TGeneradorSelloV33 }
procedure TGeneradorSelloV33.Configurar(const aOpenSSL: IOpenSSL);
begin
fInstanciaOpenSSL := aOpenSSL;
end;
//function TGeneradorSelloV33.GenerarSello(
// const aCadenaOriginal: TCadenaUTF8): TCadenaUTF8;
//begin
// fInstanciaOpenSSL := TOpenSSL.Create;
// Result:= GenerarSelloDeFactura(aCadenaOriginal);
//end;
function TGeneradorSelloV33.GenerarSelloDeFactura(const aCadenaOriginal:
TCadenaUTF8): TCadenaUTF8;
begin
Assert(fInstanciaOpenSSL <> nil, 'La instancia fInstanciaOpenSSL no debio ser nula. Favor de mandar la instancia en el metodo Configurar');
// CFDI v3.3 utiliza SHA256
Result := fInstanciaOpenSSL.HacerDigestion(aCadenaOriginal, tdSHA256)
end;
end.
|
unit Produto;
interface
type
TProduto = class
private
FId: Integer;
FDescricao: String;
FPreco: Double;
protected
function GetId: Integer;
procedure SetId(Value: Integer);
function GetDescricao: String;
procedure SetDescricao(Value: String);
function GetPreco: Double;
procedure SetPreco(Value: Double);
public
property Id: Integer read FId write FId;
property Descricao: String read FDescricao write FDescricao;
property Preco: Double read FPreco write FPreco;
end;
implementation
{ TProduto }
function TProduto.GetDescricao: String;
begin
Result := FDescricao;
end;
function TProduto.GetId: Integer;
begin
Result := FId;
end;
function TProduto.GetPreco: Double;
begin
Result := FPreco;
end;
procedure TProduto.SetDescricao(Value: String);
begin
FDescricao := Value;
end;
procedure TProduto.SetId(Value: Integer);
begin
FId := Value;
end;
procedure TProduto.SetPreco(Value: Double);
begin
FPreco := Value;
end;
end.
|
{
@abstract(Formulario padrao.)
@author(Analista / Programador : Jairo dos Santos Gurgel <jsgurgel@hotmail.com>)
@created(2014)
@lastmod(17/02/2017)
}
unit fmFormPatterns;
{ Masked input plugin
http://forums.unigui.com/index.php?/topic/4523-masked-input-plugin/?hl=format#entry22465
}
interface
uses
KrUtil, uniKrUtil, krVar,
uniDBGrid, ZAbstractDataset, ZAbstractRODataset,
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs,
uniGUITypes, uniGUIAbstractClasses, uniGUIClasses, uniGUIForm, uniDBEdit,
uniGUIBaseClasses, uniEdit, uniDBLookupComboBox, uniDBDateTimePicker,
UniDateTimePicker;
type
TfrmFormPatterns = class(TUniForm)
procedure UniFormCreate(Sender: TObject);
procedure UniFormKeyPress(Sender: TObject; var Key: Char);
procedure UniFormShow(Sender: TObject);
procedure UniFormActivate(Sender: TObject);
private
fCallBackConfirm:Boolean;
function GetDataNula: String;
procedure AddEditLookpCombobox;
procedure CallBackConfirm(Sender: TComponent; AResult: Integer);
procedure OnColumnSort(Column: TUniDBGridColumn; Direction: Boolean);
procedure SortedBy;
{ Private declarations }
public
Const
MaskFone :String = '(99)9999-9999'; // Fone
MaskCelular :String = '(99)9 9999-9999'; // Celular com 9 digitos
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
MaskIP :String = '9999.9999.9999.9999'; // IP de computador
MaskCNPJ :String = '99.999.999/9999-99'; // CNPJ
MaskVIPROC :String = '9999999/9999'; // VIPROC
MaskIPol :String = '999-9999/9999'; // Inquérito Policial
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(Value: 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;
function IsTituloEleitor(NumTitulo: string): Boolean; // Valida Título de Eleitor
function IsNum(Value:String):Boolean;
// Date e Time
function Dias_Uteis(DT_Ini, DT_Fin:TDateTime):Integer;
{ Public declarations }
Function GetWhere(Value:TStrings):String;
function StrToBool1(Str:string):boolean;
//
property DataNula :String read GetDataNula;
end;
function frmFormPatterns: TfrmFormPatterns;
implementation
{$R *.dfm}
uses
MainModule, uniGUIApplication;
procedure TfrmFormPatterns.CallBackConfirm(Sender: TComponent; AResult: Integer);
begin
fCallBackConfirm := AResult = mrYes;
end;
function frmFormPatterns: TfrmFormPatterns;
begin
Result := TfrmFormPatterns(UniMainModule.GetFormInstance(TfrmFormPatterns));
end;
procedure TfrmFormPatterns.OpenURLWindow(URL:String);
Begin
uniKrUtil.OpenURLWindow(URL);
End;
procedure TfrmFormPatterns.OpenURL(URL:String);
Begin
uniKrUtil.OpenURL(URL);
End;
function TfrmFormPatterns.DelCharEspeciais(Str: String): string;
begin
Result := KrUtil.DelCharEspeciais(Str);
end;
function TfrmFormPatterns.Dias_Uteis(DT_Ini, DT_Fin: TDateTime): Integer;
begin
Result := KrUtil.Dias_Uteis(DT_Ini, DT_Fin);
end;
procedure TfrmFormPatterns.DisplayError(Msg: string);
begin
uniKrUtil.DisplayError(Msg);
end;
function TfrmFormPatterns.GerarNomeArquivo: String;
begin
Result:=krUtil.GerarNomeArquivo;
end;
function TfrmFormPatterns.GeraSenha(n: integer): String;
begin
Result:=krUtil.GeraSenha(n);
end;
function TfrmFormPatterns.GetDataNula: String;
begin
Result:=krVar.DataNula;
end;
function TfrmFormPatterns.GetWhere(Value: TStrings): String;
begin
Result:=KrUtil.GetWhere(Value);
end;
function TfrmFormPatterns.Soundex(S: String): String;
begin
Result:=KrUtil.Soundex(S);
end;
function TfrmFormPatterns.StrToBool1(Str: string): boolean;
begin
Result:=KrUtil.StrToBool1(Str);
end;
procedure TfrmFormPatterns.UniFormActivate(Sender: TObject);
begin
inherited;
SortedBy;
end;
procedure TfrmFormPatterns.UniFormCreate(Sender: TObject);
begin
KrUtil.Create;
end;
procedure TfrmFormPatterns.OnColumnSort(Column: TUniDBGridColumn; Direction: Boolean);
begin // Uses uniDBGrid, ZAbstractDataset, ZAbstractRODataset
inherited; // Ordena as informações pelo campo da coluna que foi clicada
if TZAbstractDataSet(Column.Field.DataSet).Active then
Begin
if Column.FieldName <> TZAbstractDataSet(Column.Field.DataSet).SortedFields then
Begin
TZAbstractDataSet(Column.Field.DataSet).SortedFields := Column.FieldName;
TZAbstractDataSet(Column.Field.DataSet).SortType := stAscending;
End
else
Begin
case TZAbstractDataSet(Column.Field.DataSet).SortType of
stAscending : TZAbstractDataSet(Column.Field.DataSet).SortType := stDescending;
stDescending: TZAbstractDataSet(Column.Field.DataSet).SortType := stAscending;
end;
End;
End;
end;
procedure TfrmFormPatterns.SortedBy;
Var
I, J :Integer;
begin
inherited;
For I:=0 To Self.ComponentCount - 1 do
Begin
if (LowerCase(self.Components[I].ClassName) = 'tunidbgrid') and
(TUniDBGrid(self.Components[I]).Tag = 0) then
Begin
TUniDBGrid(self.Components[I]).OnColumnSort := OnColumnSort;
TUniDBGrid(self.Components[I]).Tag := 1;
//
{ if TUniDBGrid(self.Components[I]).DataSource.DataSet.Active then
For J:= 0 to TUniDBGrid(self.Components[I]).Columns.Count - 1 do
if not TUniDBGrid(self.Components[I]).Columns[J].Sortable then
TUniDBGrid(self.Components[I]).Columns[J].Sortable := True;}
End;
end;
end;
procedure TfrmFormPatterns.UniFormKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #27 then
Close;
end;
procedure TfrmFormPatterns.UniFormShow(Sender: TObject);
begin
AddMaskDate;
AddEditLookpCombobox;
end;
function TfrmFormPatterns.BoolToStr2(Bool:Boolean):String;
Begin
Result:=KrUtil.BoolToStr2(Bool);
End;
function TfrmFormPatterns.Idade(DataNasc: String): string;
begin
Result:=KrUtil.Idade(DataNasc);
end;
function TfrmFormPatterns.Idade(DataNasc: String; dtAtual: TDate): string;
begin
Result:=KrUtil.Idade(DataNasc, dtAtual);
end;
function TfrmFormPatterns.IsCnpj(const aCode: string): boolean;
begin
Result:=KrUtil.IsCnpj(aCode);
end;
function TfrmFormPatterns.IsCpf(const aCode: string): boolean;
begin
Result:=KrUtil.IsCpf(aCode);
end;
function TfrmFormPatterns.IsCpfCnpj(const aCode: string): boolean;
begin
Result:=KrUtil.IsCpfCnpj(aCode);
end;
function TfrmFormPatterns.IsDate(fDate: String): Boolean;
begin
Result:=KrUtil.IsDate(fDate);
end;
function TfrmFormPatterns.IsEMail(Value: String):Boolean;
begin
Result:=KrUtil.IsEMail(Value);
end;
function TfrmFormPatterns.IsIE(UF, IE: string): boolean;
begin
Result:=KrUtil.IsIE(UF, IE);
end;
function TfrmFormPatterns.IsIP(IP: string): Boolean;
begin
Result:=KrUtil.IsIP(IP);
end;
function TfrmFormPatterns.isKeyValid(Value: Char): Boolean;
begin
Result:=KrUtil.isKeyValid(Value);
end;
function TfrmFormPatterns.IsNum(Value: String): Boolean;
begin
Result:=KrUtil.IsNum(Value);
end;
function TfrmFormPatterns.IsPlaca(Value: String): Boolean;
begin
Result:=KrUtil.IsPlaca(Value);
end;
function TfrmFormPatterns.IsTitulo(numero: String): Boolean;
begin
Result:=KrUtil.IsTitulo(numero);
end;
function TfrmFormPatterns.IsTituloEleitor(NumTitulo: string): Boolean;
begin
Result := KrUtil.IsTituloEleitor(NumTitulo);
end;
procedure TfrmFormPatterns.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 TfrmFormPatterns.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 TfrmFormPatterns.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 TfrmFormPatterns.AddMask(Edit: TUniDBEdit; Mask:String);
begin
Edit.ClientEvents.ExtEvents.Add
('Onfocus=function function focus(sender, the, eOpts)'+
' { $("#"+sender.id+"-inputEl").mask("'+Mask+'"); }');
end;
procedure TfrmFormPatterns.AddMask(Edit: TUniEdit; Mask:String);
begin
Edit.ClientEvents.ExtEvents.Add
('Onfocus=function function focus(sender, the, eOpts)'+
' { $("#"+sender.id+"-inputEl").mask("'+Mask+'"); }');
end;
procedure TfrmFormPatterns.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;}'); // sender.allowBlank=true; sender.editable = true;
end;
function TfrmFormPatterns.Confirm(msg:String):Boolean;
Begin
MessageDlg(Msg, mtConfirmation, mbYesNo,CallBackConfirm);
Result := fCallBackConfirm;
End;
procedure TfrmFormPatterns.Warning(msg:String);
Begin
uniKrUtil.Warning(msg);
End;
procedure TfrmFormPatterns.AddFeriados(Data: String);
begin
KrUtil.AddFeriados(Data);
end;
function TfrmFormPatterns.BoolToStr2(Bool: Integer): String;
begin
Result:=KrUtil.BoolToStr2(Bool);
end;
function TfrmFormPatterns.Criptografar(wStri: String): String;
begin
Result := krUtil.Criptografar(wStri);
end;
end.
|
(*
8. Conditional construct
9. Iterative construct
10. Array
11. Relational operators
12. Boolean operators
*)
program secondTest;
{
7. Conditional construct
8. Relational operators
}
procedure conditionalRelation;
var
x, y : integer;
begin
writeln('Check Conditional and Relation Operators');
write('Input two integers (x and y): ');
readln(x, y);
if x = y then
writeln('1. x = y')
else
writeln('1. x <> y');
if x <> y then
writeln('2. x <> y')
else
writeln('2. x = y');
if x > y then
writeln('3. x > y')
else
writeln('3. !(x > y)');
if x < y then
writeln('4. x < y')
else
writeln('4. !(x < y)');
if (x >= y) then
writeln('5. x >= y')
else
writeln('5. !(x >= y)');
if (x <= y) then
writeln('6. x <= y')
else
writeln('6. !(x <= y)');
writeln;
end;
{
7. Conditional construct
9. Boolean operators
}
procedure conditionalBoolean;
var
s : string;
begin
writeln('Check Conditional and Boolean Operators');
writeln('Which is a heavier a kilogram of steel or a kilogram of feathers?');
readln(s);
if not (s = 'both') then
writeln('judging you')
else
writeln('that is right');
if (s = 'steel') or (s = 'feathers') then
writeln('seriously judging you')
else
writeln('hmmm');
writeln;
writeln('Next question');
writeln('Who is the strongest avenger?');
readln(s);
if not (s = 'hulk') and (s = 'idk') then
writeln('okay lang yan')
else
writeln('weh sure ka ba');
writeln;
end;
{
9. Iterative Construct
10. Array
}
procedure iteration;
var
a : array [1..3] of integer;
i : integer;
begin
writeln('Check for Iterative Construct and Array');
for i := 1 to 3 do
a[i] := i + 1;
for i := 1 to 3 do
writeln('a[', i, ']: ', a[i]);
writeln;
end;
procedure combination;
var
c : array [1..5] of integer;
i : integer;
j : integer;
b : boolean;
begin
writeln('Check for Conditional and Iteration');
for i := 1 to 5 do
c[i] := i;
j := 12;
b := false;
for i := 1 to 5 do
if c[i] = j then
begin
writeln('j here');
b := true;
end
else
writeln('j not here');
writeln('found a ', j, '?');
if b = false then
writeln('sad')
else
writeln('yay!');
if b = true and not (j >= 2) then
writeln('False and False or True and True')
else
writeln('At least 1 True');
writeln(b = true);
writeln(not (j >= 2));
writeln;
end;
begin
conditionalRelation;
conditionalBoolean;
iteration;
combination;
end. |
// ************************************************************************ //
// The types declared in this file were generated from data read from the
// WSDL File described below:
// WSDL : https://webservices.appraisalworld.com/ws/awsi/FloodInsightsServer.php?wsdl
// >Import : https://webservices.appraisalworld.com/ws/awsi/FloodInsightsServer.php?wsdl:0
// Encoding : ISO-8859-1
// Version : 1.0
// (9/26/2017 4:29:47 PM - - $Rev: 10138 $)
// ************************************************************************ //
unit AWSI_Server_FloodInsights;
interface
uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns;
const
IS_OPTN = $0001;
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.
// ************************************************************************ //
// !:string - "http://www.w3.org/2001/XMLSchema"[Gbl]
// !:int - "http://www.w3.org/2001/XMLSchema"[Gbl]
// !:float - "http://www.w3.org/2001/XMLSchema"[Gbl]
// !:boolean - "http://www.w3.org/2001/XMLSchema"[Gbl]
clsUserCredentials = class; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
clsMapRequest = class; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
clsRmMapInfo = class; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
clsResults = class; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
clsRmLocationArrayItem = class; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
clsRmTestResultArrayItem = class; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
clsRmTestResult2ArrayItem = class; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
clsRmFeature2ArrayItem = class; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
clsRmFeatureArrayItem = class; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
clsAcknowledgement = class; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
clsGetGeocodeRequest = class; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
clsFloodInsightsGetMapRequest = class; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
clsGetRespottedMapRequest = class; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
clsUsageAccessCredentials = class; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
clsAcknowledgementResponse = class; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
clsAcknowledgementResponseData = class; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
clsGetGeocodeResponse = class; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
clsCDGeoResults = class; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
clsCdCandidateArrayItem = class; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
clsCDGeneral = class; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
clsFloodInsightsGetMapResponse = class; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
clsGetMapResponse = class; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
clsFloodInsightsGetMap2Response = class; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
clsGetMap2Response = class; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
clsFloodInsightsGetMap3Response = class; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
clsGetMap3Response = class; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
clsGetRespottedMapResponse = class; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
clsGetUsageAvailabilityData = class; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
clsGetUsageAvailabilityResponse = class; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
// ************************************************************************ //
// XML : clsUserCredentials, global, <complexType>
// Namespace : http://webservices.appraisalworld.com/secure/ws/WSDL
// ************************************************************************ //
clsUserCredentials = class(TRemotable)
private
FUsername: WideString;
FPassword: WideString;
FCompanyKey: WideString;
FOrderNumberKey: WideString;
FPurchase: Integer;
FCustomerOrderNumber: WideString;
FCustomerOrderNumber_Specified: boolean;
procedure SetCustomerOrderNumber(Index: Integer; const AWideString: WideString);
function CustomerOrderNumber_Specified(Index: Integer): boolean;
published
property Username: WideString read FUsername write FUsername;
property Password: WideString read FPassword write FPassword;
property CompanyKey: WideString read FCompanyKey write FCompanyKey;
property OrderNumberKey: WideString read FOrderNumberKey write FOrderNumberKey;
property Purchase: Integer read FPurchase write FPurchase;
property CustomerOrderNumber: WideString Index (IS_OPTN) read FCustomerOrderNumber write SetCustomerOrderNumber stored CustomerOrderNumber_Specified;
end;
// ************************************************************************ //
// XML : clsMapRequest, global, <complexType>
// Namespace : http://webservices.appraisalworld.com/secure/ws/WSDL
// ************************************************************************ //
clsMapRequest = class(TRemotable)
private
FStreet: WideString;
FCity: WideString;
FState: WideString;
FZip: WideString;
FPlus4: WideString;
FLongitude: Single;
FLatitude: Single;
FGeoResult: WideString;
FCensusBlockId: WideString;
FMapHeight: Integer;
FMapWidth: Integer;
FMapZoom: Single;
FLocationLabel: WideString;
published
property Street: WideString read FStreet write FStreet;
property City: WideString read FCity write FCity;
property State: WideString read FState write FState;
property Zip: WideString read FZip write FZip;
property Plus4: WideString read FPlus4 write FPlus4;
property Longitude: Single read FLongitude write FLongitude;
property Latitude: Single read FLatitude write FLatitude;
property GeoResult: WideString read FGeoResult write FGeoResult;
property CensusBlockId: WideString read FCensusBlockId write FCensusBlockId;
property MapHeight: Integer read FMapHeight write FMapHeight;
property MapWidth: Integer read FMapWidth write FMapWidth;
property MapZoom: Single read FMapZoom write FMapZoom;
property LocationLabel: WideString read FLocationLabel write FLocationLabel;
end;
// ************************************************************************ //
// XML : clsRmMapInfo, global, <complexType>
// Namespace : http://webservices.appraisalworld.com/secure/ws/WSDL
// ************************************************************************ //
clsRmMapInfo = class(TRemotable)
private
FLocPtX: Single;
FLocPtY: Single;
FCenterX: Single;
FCenterY: Single;
FZoom: Single;
FImageID: WideString;
FImageURL: WideString;
published
property LocPtX: Single read FLocPtX write FLocPtX;
property LocPtY: Single read FLocPtY write FLocPtY;
property CenterX: Single read FCenterX write FCenterX;
property CenterY: Single read FCenterY write FCenterY;
property Zoom: Single read FZoom write FZoom;
property ImageID: WideString read FImageID write FImageID;
property ImageURL: WideString read FImageURL write FImageURL;
end;
// ************************************************************************ //
// XML : clsResults, global, <complexType>
// Namespace : http://webservices.appraisalworld.com/secure/ws/WSDL
// ************************************************************************ //
clsResults = class(TRemotable)
private
FCode: Integer;
FType_: WideString;
FDescription: WideString;
published
property Code: Integer read FCode write FCode;
property Type_: WideString read FType_ write FType_;
property Description: WideString read FDescription write FDescription;
end;
// ************************************************************************ //
// XML : clsRmLocationArrayItem, global, <complexType>
// Namespace : http://webservices.appraisalworld.com/secure/ws/WSDL
// ************************************************************************ //
clsRmLocationArrayItem = class(TRemotable)
private
FMapLabel: WideString;
FStreet: WideString;
FCity: WideString;
FState: WideString;
FZip: WideString;
FPlus4: WideString;
FCensusBlock: WideString;
published
property MapLabel: WideString read FMapLabel write FMapLabel;
property Street: WideString read FStreet write FStreet;
property City: WideString read FCity write FCity;
property State: WideString read FState write FState;
property Zip: WideString read FZip write FZip;
property Plus4: WideString read FPlus4 write FPlus4;
property CensusBlock: WideString read FCensusBlock write FCensusBlock;
end;
clsRmLocationArray = array of clsRmLocationArrayItem; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
// ************************************************************************ //
// XML : clsRmTestResultArrayItem, global, <complexType>
// Namespace : http://webservices.appraisalworld.com/secure/ws/WSDL
// ************************************************************************ //
clsRmTestResultArrayItem = class(TRemotable)
private
FName_: WideString;
FType_: Integer;
FSHFA: WideString;
FNearby: WideString;
FFzDdPhrase: WideString;
FCensusTrack: WideString;
published
property Name_: WideString read FName_ write FName_;
property Type_: Integer read FType_ write FType_;
property SHFA: WideString read FSHFA write FSHFA;
property Nearby: WideString read FNearby write FNearby;
property FzDdPhrase: WideString read FFzDdPhrase write FFzDdPhrase;
property CensusTrack: WideString read FCensusTrack write FCensusTrack;
end;
clsRmTestResultArray = array of clsRmTestResultArrayItem; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
// ************************************************************************ //
// XML : clsRmTestResult2ArrayItem, global, <complexType>
// Namespace : http://webservices.appraisalworld.com/secure/ws/WSDL
// ************************************************************************ //
clsRmTestResult2ArrayItem = class(TRemotable)
private
FName_: WideString;
FType_: Integer;
FSHFA: WideString;
FNearby: WideString;
FFzDdPhrase: WideString;
FCensusTrack: WideString;
FMapNumber: WideString;
published
property Name_: WideString read FName_ write FName_;
property Type_: Integer read FType_ write FType_;
property SHFA: WideString read FSHFA write FSHFA;
property Nearby: WideString read FNearby write FNearby;
property FzDdPhrase: WideString read FFzDdPhrase write FFzDdPhrase;
property CensusTrack: WideString read FCensusTrack write FCensusTrack;
property MapNumber: WideString read FMapNumber write FMapNumber;
end;
clsRmTestResult2Array = array of clsRmTestResult2ArrayItem; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
// ************************************************************************ //
// XML : clsRmFeature2ArrayItem, global, <complexType>
// Namespace : http://webservices.appraisalworld.com/secure/ws/WSDL
// ************************************************************************ //
clsRmFeature2ArrayItem = class(TRemotable)
private
FCommunity: WideString;
FCommunityName: WideString;
FZone: WideString;
FPanel: WideString;
FPanelDate: WideString;
FFIPS: WideString;
FCOBRA: WideString;
published
property Community: WideString read FCommunity write FCommunity;
property CommunityName: WideString read FCommunityName write FCommunityName;
property Zone: WideString read FZone write FZone;
property Panel: WideString read FPanel write FPanel;
property PanelDate: WideString read FPanelDate write FPanelDate;
property FIPS: WideString read FFIPS write FFIPS;
property COBRA: WideString read FCOBRA write FCOBRA;
end;
clsRmFeature2Array = array of clsRmFeature2ArrayItem; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
// ************************************************************************ //
// XML : clsRmFeatureArrayItem, global, <complexType>
// Namespace : http://webservices.appraisalworld.com/secure/ws/WSDL
// ************************************************************************ //
clsRmFeatureArrayItem = class(TRemotable)
private
FCommunity: WideString;
FCommunityName: WideString;
FZone: WideString;
FPanel: WideString;
FPanelDate: WideString;
FFIPS: WideString;
published
property Community: WideString read FCommunity write FCommunity;
property CommunityName: WideString read FCommunityName write FCommunityName;
property Zone: WideString read FZone write FZone;
property Panel: WideString read FPanel write FPanel;
property PanelDate: WideString read FPanelDate write FPanelDate;
property FIPS: WideString read FFIPS write FFIPS;
end;
clsRmFeatureArray = array of clsRmFeatureArrayItem; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
clsRmMapInfoArray = array of clsRmMapInfo; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
// ************************************************************************ //
// XML : clsAcknowledgement, global, <complexType>
// Namespace : http://webservices.appraisalworld.com/secure/ws/WSDL
// ************************************************************************ //
clsAcknowledgement = class(TRemotable)
private
FReceived: Integer;
FServiceAcknowledgement: WideString;
published
property Received: Integer read FReceived write FReceived;
property ServiceAcknowledgement: WideString read FServiceAcknowledgement write FServiceAcknowledgement;
end;
// ************************************************************************ //
// XML : clsGetGeocodeRequest, global, <complexType>
// Namespace : http://webservices.appraisalworld.com/secure/ws/WSDL
// ************************************************************************ //
clsGetGeocodeRequest = class(TRemotable)
private
FStreetAddress: WideString;
FCity: WideString;
FState: WideString;
FZip: WideString;
FPlus4: WideString;
published
property StreetAddress: WideString read FStreetAddress write FStreetAddress;
property City: WideString read FCity write FCity;
property State: WideString read FState write FState;
property Zip: WideString read FZip write FZip;
property Plus4: WideString read FPlus4 write FPlus4;
end;
// ************************************************************************ //
// XML : clsFloodInsightsGetMapRequest, global, <complexType>
// Namespace : http://webservices.appraisalworld.com/secure/ws/WSDL
// ************************************************************************ //
clsFloodInsightsGetMapRequest = class(TRemotable)
private
FStreetAddress: WideString;
FCity: WideString;
FState: WideString;
FZip: WideString;
FPlus4: WideString;
FLatitude: Single;
FLongitude: Single;
FGeoResult: WideString;
FCensusBlockId: WideString;
FMapHeight: Integer;
FMapWidth: Integer;
FMapZoom: Single;
FLocationLabel: WideString;
published
property StreetAddress: WideString read FStreetAddress write FStreetAddress;
property City: WideString read FCity write FCity;
property State: WideString read FState write FState;
property Zip: WideString read FZip write FZip;
property Plus4: WideString read FPlus4 write FPlus4;
property Latitude: Single read FLatitude write FLatitude;
property Longitude: Single read FLongitude write FLongitude;
property GeoResult: WideString read FGeoResult write FGeoResult;
property CensusBlockId: WideString read FCensusBlockId write FCensusBlockId;
property MapHeight: Integer read FMapHeight write FMapHeight;
property MapWidth: Integer read FMapWidth write FMapWidth;
property MapZoom: Single read FMapZoom write FMapZoom;
property LocationLabel: WideString read FLocationLabel write FLocationLabel;
end;
// ************************************************************************ //
// XML : clsGetRespottedMapRequest, global, <complexType>
// Namespace : http://webservices.appraisalworld.com/secure/ws/WSDL
// ************************************************************************ //
clsGetRespottedMapRequest = class(TRemotable)
private
FMapRequest: clsMapRequest;
FMapInfo: clsRmMapInfo;
public
destructor Destroy; override;
published
property MapRequest: clsMapRequest read FMapRequest write FMapRequest;
property MapInfo: clsRmMapInfo read FMapInfo write FMapInfo;
end;
// ************************************************************************ //
// XML : clsUsageAccessCredentials, global, <complexType>
// Namespace : http://webservices.appraisalworld.com/secure/ws/WSDL
// ************************************************************************ //
clsUsageAccessCredentials = class(TRemotable)
private
FCustomerId: Integer;
FServiceId: WideString;
published
property CustomerId: Integer read FCustomerId write FCustomerId;
property ServiceId: WideString read FServiceId write FServiceId;
end;
// ************************************************************************ //
// XML : clsAcknowledgementResponse, global, <complexType>
// Namespace : http://webservices.appraisalworld.com/secure/ws/WSDL
// ************************************************************************ //
clsAcknowledgementResponse = class(TRemotable)
private
FResults: clsResults;
FResponseData: clsAcknowledgementResponseData;
public
destructor Destroy; override;
published
property Results: clsResults read FResults write FResults;
property ResponseData: clsAcknowledgementResponseData read FResponseData write FResponseData;
end;
// ************************************************************************ //
// XML : clsAcknowledgementResponseData, global, <complexType>
// Namespace : http://webservices.appraisalworld.com/secure/ws/WSDL
// ************************************************************************ //
clsAcknowledgementResponseData = class(TRemotable)
private
FReceived: Integer;
published
property Received: Integer read FReceived write FReceived;
end;
// ************************************************************************ //
// XML : clsGetGeocodeResponse, global, <complexType>
// Namespace : http://webservices.appraisalworld.com/secure/ws/WSDL
// ************************************************************************ //
clsGetGeocodeResponse = class(TRemotable)
private
FResults: clsResults;
FResponseData: clsCDGeoResults;
public
destructor Destroy; override;
published
property Results: clsResults read FResults write FResults;
property ResponseData: clsCDGeoResults read FResponseData write FResponseData;
end;
clsCdCandidateArray = array of clsCdCandidateArrayItem; { "http://webservices.appraisalworld.com/secure/ws/WSDL"[GblCplx] }
// ************************************************************************ //
// XML : clsCDGeoResults, global, <complexType>
// Namespace : http://webservices.appraisalworld.com/secure/ws/WSDL
// ************************************************************************ //
clsCDGeoResults = class(TRemotable)
private
FCdCandidates: clsCdCandidateArray;
FMatchInfo: clsCDGeneral;
public
destructor Destroy; override;
published
property CdCandidates: clsCdCandidateArray read FCdCandidates write FCdCandidates;
property MatchInfo: clsCDGeneral read FMatchInfo write FMatchInfo;
end;
// ************************************************************************ //
// XML : clsCdCandidateArrayItem, global, <complexType>
// Namespace : http://webservices.appraisalworld.com/secure/ws/WSDL
// ************************************************************************ //
clsCdCandidateArrayItem = class(TRemotable)
private
FStreet: WideString;
FCity: WideString;
FState: WideString;
FZip: WideString;
FPlus4: WideString;
FLongitude: Single;
FLatitude: Single;
FGeoResult: WideString;
FFirm: WideString;
FCensusBlockId: WideString;
FPrecision: Integer;
published
property Street: WideString read FStreet write FStreet;
property City: WideString read FCity write FCity;
property State: WideString read FState write FState;
property Zip: WideString read FZip write FZip;
property Plus4: WideString read FPlus4 write FPlus4;
property Longitude: Single read FLongitude write FLongitude;
property Latitude: Single read FLatitude write FLatitude;
property GeoResult: WideString read FGeoResult write FGeoResult;
property Firm: WideString read FFirm write FFirm;
property CensusBlockId: WideString read FCensusBlockId write FCensusBlockId;
property Precision: Integer read FPrecision write FPrecision;
end;
// ************************************************************************ //
// XML : clsCDGeneral, global, <complexType>
// Namespace : http://webservices.appraisalworld.com/secure/ws/WSDL
// ************************************************************************ //
clsCDGeneral = class(TRemotable)
private
FNumCandidates: Integer;
FNumCloseCandidates: Integer;
FStatus: WideString;
FGeoSource: WideString;
FGoodCandidate: Boolean;
published
property NumCandidates: Integer read FNumCandidates write FNumCandidates;
property NumCloseCandidates: Integer read FNumCloseCandidates write FNumCloseCandidates;
property Status: WideString read FStatus write FStatus;
property GeoSource: WideString read FGeoSource write FGeoSource;
property GoodCandidate: Boolean read FGoodCandidate write FGoodCandidate;
end;
// ************************************************************************ //
// XML : clsFloodInsightsGetMapResponse, global, <complexType>
// Namespace : http://webservices.appraisalworld.com/secure/ws/WSDL
// ************************************************************************ //
clsFloodInsightsGetMapResponse = class(TRemotable)
private
FLocation: clsRmLocationArray;
FTestResult: clsRmTestResultArray;
FFeature: clsRmFeatureArray;
FMapInfo: clsRmMapInfoArray;
FMapImage: WideString;
FServiceAcknowledgement: WideString;
public
destructor Destroy; override;
published
property Location: clsRmLocationArray read FLocation write FLocation;
property TestResult: clsRmTestResultArray read FTestResult write FTestResult;
property Feature: clsRmFeatureArray read FFeature write FFeature;
property MapInfo: clsRmMapInfoArray read FMapInfo write FMapInfo;
property MapImage: WideString read FMapImage write FMapImage;
property ServiceAcknowledgement: WideString read FServiceAcknowledgement write FServiceAcknowledgement;
end;
// ************************************************************************ //
// XML : clsGetMapResponse, global, <complexType>
// Namespace : http://webservices.appraisalworld.com/secure/ws/WSDL
// ************************************************************************ //
clsGetMapResponse = class(TRemotable)
private
FResults: clsResults;
FResponseData: clsFloodInsightsGetMapResponse;
public
destructor Destroy; override;
published
property Results: clsResults read FResults write FResults;
property ResponseData: clsFloodInsightsGetMapResponse read FResponseData write FResponseData;
end;
// ************************************************************************ //
// XML : clsFloodInsightsGetMap2Response, global, <complexType>
// Namespace : http://webservices.appraisalworld.com/secure/ws/WSDL
// ************************************************************************ //
clsFloodInsightsGetMap2Response = class(TRemotable)
private
FLocation: clsRmLocationArray;
FTestResult: clsRmTestResultArray;
FFeature: clsRmFeature2Array;
FMapInfo: clsRmMapInfoArray;
FMapImage: WideString;
FServiceAcknowledgement: WideString;
public
destructor Destroy; override;
published
property Location: clsRmLocationArray read FLocation write FLocation;
property TestResult: clsRmTestResultArray read FTestResult write FTestResult;
property Feature: clsRmFeature2Array read FFeature write FFeature;
property MapInfo: clsRmMapInfoArray read FMapInfo write FMapInfo;
property MapImage: WideString read FMapImage write FMapImage;
property ServiceAcknowledgement: WideString read FServiceAcknowledgement write FServiceAcknowledgement;
end;
// ************************************************************************ //
// XML : clsGetMap2Response, global, <complexType>
// Namespace : http://webservices.appraisalworld.com/secure/ws/WSDL
// ************************************************************************ //
clsGetMap2Response = class(TRemotable)
private
FResults: clsResults;
FResponseData: clsFloodInsightsGetMap2Response;
public
destructor Destroy; override;
published
property Results: clsResults read FResults write FResults;
property ResponseData: clsFloodInsightsGetMap2Response read FResponseData write FResponseData;
end;
// ************************************************************************ //
// XML : clsFloodInsightsGetMap3Response, global, <complexType>
// Namespace : http://webservices.appraisalworld.com/secure/ws/WSDL
// ************************************************************************ //
clsFloodInsightsGetMap3Response = class(TRemotable)
private
FLocation: clsRmLocationArray;
FTestResult: clsRmTestResult2Array;
FFeature: clsRmFeature2Array;
FMapInfo: clsRmMapInfoArray;
FMapImage: WideString;
FServiceAcknowledgement: WideString;
public
destructor Destroy; override;
published
property Location: clsRmLocationArray read FLocation write FLocation;
property TestResult: clsRmTestResult2Array read FTestResult write FTestResult;
property Feature: clsRmFeature2Array read FFeature write FFeature;
property MapInfo: clsRmMapInfoArray read FMapInfo write FMapInfo;
property MapImage: WideString read FMapImage write FMapImage;
property ServiceAcknowledgement: WideString read FServiceAcknowledgement write FServiceAcknowledgement;
end;
// ************************************************************************ //
// XML : clsGetMap3Response, global, <complexType>
// Namespace : http://webservices.appraisalworld.com/secure/ws/WSDL
// ************************************************************************ //
clsGetMap3Response = class(TRemotable)
private
FResults: clsResults;
FResponseData: clsFloodInsightsGetMap3Response;
public
destructor Destroy; override;
published
property Results: clsResults read FResults write FResults;
property ResponseData: clsFloodInsightsGetMap3Response read FResponseData write FResponseData;
end;
// ************************************************************************ //
// XML : clsGetRespottedMapResponse, global, <complexType>
// Namespace : http://webservices.appraisalworld.com/secure/ws/WSDL
// ************************************************************************ //
clsGetRespottedMapResponse = class(TRemotable)
private
FResults: clsResults;
FResponseData: clsFloodInsightsGetMapResponse;
public
destructor Destroy; override;
published
property Results: clsResults read FResults write FResults;
property ResponseData: clsFloodInsightsGetMapResponse read FResponseData write FResponseData;
end;
// ************************************************************************ //
// XML : clsGetUsageAvailabilityData, global, <complexType>
// Namespace : http://webservices.appraisalworld.com/secure/ws/WSDL
// ************************************************************************ //
clsGetUsageAvailabilityData = class(TRemotable)
private
FServiceName: WideString;
FWebServiceId: Integer;
FProductAvailable: WideString;
FMessage_: WideString;
FExpirationDate: WideString;
FAppraiserQuantity: Integer;
FOwnerQuantity: Integer;
FOwnerQuantity_Specified: boolean;
procedure SetOwnerQuantity(Index: Integer; const AInteger: Integer);
function OwnerQuantity_Specified(Index: Integer): boolean;
published
property ServiceName: WideString read FServiceName write FServiceName;
property WebServiceId: Integer read FWebServiceId write FWebServiceId;
property ProductAvailable: WideString read FProductAvailable write FProductAvailable;
property Message_: WideString read FMessage_ write FMessage_;
property ExpirationDate: WideString read FExpirationDate write FExpirationDate;
property AppraiserQuantity: Integer read FAppraiserQuantity write FAppraiserQuantity;
property OwnerQuantity: Integer Index (IS_OPTN) read FOwnerQuantity write SetOwnerQuantity stored OwnerQuantity_Specified;
end;
// ************************************************************************ //
// XML : clsGetUsageAvailabilityResponse, global, <complexType>
// Namespace : http://webservices.appraisalworld.com/secure/ws/WSDL
// ************************************************************************ //
clsGetUsageAvailabilityResponse = class(TRemotable)
private
FResults: clsResults;
FResponseData: clsGetUsageAvailabilityData;
public
destructor Destroy; override;
published
property Results: clsResults read FResults write FResults;
property ResponseData: clsGetUsageAvailabilityData read FResponseData write FResponseData;
end;
// ************************************************************************ //
// Namespace : FloodInsightsServerClass
// soapAction: FloodInsightsServerClass#%operationName%
// transport : http://schemas.xmlsoap.org/soap/http
// style : rpc
// binding : FloodInsightsServerBinding
// service : FloodInsightsServer
// port : FloodInsightsServerPort
// URL : https://webservices.appraisalworld.com:443/ws/awsi/FloodInsightsServer.php
// ************************************************************************ //
FloodInsightsServerPortType = interface(IInvokable)
['{13FD2445-0533-571A-388F-100B0F0634D6}']
function FloodInsightsService_GetUsageAvailability(const UsageAccessCredentials: clsUsageAccessCredentials): clsGetUsageAvailabilityResponse; stdcall;
function FloodInsightsService_GetGeocode(const UserCredentials: clsUserCredentials; const FIGeocodeRequestRec: clsGetGeocodeRequest): clsGetGeocodeResponse; stdcall;
function FloodInsightsService_GetMap(const UserCredentials: clsUserCredentials; const FIGetMapRequestRec: clsFloodInsightsGetMapRequest): clsGetMapResponse; stdcall;
function FloodInsightsService_GetMap2(const UserCredentials: clsUserCredentials; const FIGetMapRequestRec: clsFloodInsightsGetMapRequest): clsGetMap2Response; stdcall;
function FloodInsightsService_GetMap3(const UserCredentials: clsUserCredentials; const FIGetMapRequestRec: clsFloodInsightsGetMapRequest): clsGetMap3Response; stdcall;
function FloodInsightsService_GetRespottedMap(const UserCredentials: clsUserCredentials; const FloodInsightsGetRespottedMap: clsGetRespottedMapRequest): clsGetRespottedMapResponse; stdcall;
function FloodInsightsService_Acknowledgement(const UserCredentials: clsUserCredentials; const Acknowledgement: clsAcknowledgement): clsAcknowledgementResponse; stdcall;
end;
function GetFloodInsightsServerPortType(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): FloodInsightsServerPortType;
implementation
uses SysUtils;
function GetFloodInsightsServerPortType(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): FloodInsightsServerPortType;
const
defWSDL = 'https://webservices.appraisalworld.com/ws/awsi/FloodInsightsServer.php?wsdl';
defURL = 'https://webservices.appraisalworld.com:443/ws/awsi/FloodInsightsServer.php';
defSvc = 'FloodInsightsServer';
defPrt = 'FloodInsightsServerPort';
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 FloodInsightsServerPortType);
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;
procedure clsUserCredentials.SetCustomerOrderNumber(Index: Integer; const AWideString: WideString);
begin
FCustomerOrderNumber := AWideString;
FCustomerOrderNumber_Specified := True;
end;
function clsUserCredentials.CustomerOrderNumber_Specified(Index: Integer): boolean;
begin
Result := FCustomerOrderNumber_Specified;
end;
destructor clsGetRespottedMapRequest.Destroy;
begin
FreeAndNil(FMapRequest);
FreeAndNil(FMapInfo);
inherited Destroy;
end;
destructor clsAcknowledgementResponse.Destroy;
begin
FreeAndNil(FResults);
FreeAndNil(FResponseData);
inherited Destroy;
end;
destructor clsGetGeocodeResponse.Destroy;
begin
FreeAndNil(FResults);
FreeAndNil(FResponseData);
inherited Destroy;
end;
destructor clsCDGeoResults.Destroy;
var
I: Integer;
begin
for I := 0 to Length(FCdCandidates)-1 do
FreeAndNil(FCdCandidates[I]);
SetLength(FCdCandidates, 0);
FreeAndNil(FMatchInfo);
inherited Destroy;
end;
destructor clsFloodInsightsGetMapResponse.Destroy;
var
I: Integer;
begin
for I := 0 to Length(FLocation)-1 do
FreeAndNil(FLocation[I]);
SetLength(FLocation, 0);
for I := 0 to Length(FTestResult)-1 do
FreeAndNil(FTestResult[I]);
SetLength(FTestResult, 0);
for I := 0 to Length(FFeature)-1 do
FreeAndNil(FFeature[I]);
SetLength(FFeature, 0);
for I := 0 to Length(FMapInfo)-1 do
FreeAndNil(FMapInfo[I]);
SetLength(FMapInfo, 0);
inherited Destroy;
end;
destructor clsGetMapResponse.Destroy;
begin
FreeAndNil(FResults);
FreeAndNil(FResponseData);
inherited Destroy;
end;
destructor clsFloodInsightsGetMap2Response.Destroy;
var
I: Integer;
begin
for I := 0 to Length(FLocation)-1 do
FreeAndNil(FLocation[I]);
SetLength(FLocation, 0);
for I := 0 to Length(FTestResult)-1 do
FreeAndNil(FTestResult[I]);
SetLength(FTestResult, 0);
for I := 0 to Length(FFeature)-1 do
FreeAndNil(FFeature[I]);
SetLength(FFeature, 0);
for I := 0 to Length(FMapInfo)-1 do
FreeAndNil(FMapInfo[I]);
SetLength(FMapInfo, 0);
inherited Destroy;
end;
destructor clsGetMap2Response.Destroy;
begin
FreeAndNil(FResults);
FreeAndNil(FResponseData);
inherited Destroy;
end;
destructor clsFloodInsightsGetMap3Response.Destroy;
var
I: Integer;
begin
for I := 0 to Length(FLocation)-1 do
FreeAndNil(FLocation[I]);
SetLength(FLocation, 0);
for I := 0 to Length(FTestResult)-1 do
FreeAndNil(FTestResult[I]);
SetLength(FTestResult, 0);
for I := 0 to Length(FFeature)-1 do
FreeAndNil(FFeature[I]);
SetLength(FFeature, 0);
for I := 0 to Length(FMapInfo)-1 do
FreeAndNil(FMapInfo[I]);
SetLength(FMapInfo, 0);
inherited Destroy;
end;
destructor clsGetMap3Response.Destroy;
begin
FreeAndNil(FResults);
FreeAndNil(FResponseData);
inherited Destroy;
end;
destructor clsGetRespottedMapResponse.Destroy;
begin
FreeAndNil(FResults);
FreeAndNil(FResponseData);
inherited Destroy;
end;
procedure clsGetUsageAvailabilityData.SetOwnerQuantity(Index: Integer; const AInteger: Integer);
begin
FOwnerQuantity := AInteger;
FOwnerQuantity_Specified := True;
end;
function clsGetUsageAvailabilityData.OwnerQuantity_Specified(Index: Integer): boolean;
begin
Result := FOwnerQuantity_Specified;
end;
destructor clsGetUsageAvailabilityResponse.Destroy;
begin
FreeAndNil(FResults);
FreeAndNil(FResponseData);
inherited Destroy;
end;
initialization
InvRegistry.RegisterInterface(TypeInfo(FloodInsightsServerPortType), 'FloodInsightsServerClass', 'ISO-8859-1');
InvRegistry.RegisterDefaultSOAPAction(TypeInfo(FloodInsightsServerPortType), 'FloodInsightsServerClass#%operationName%');
InvRegistry.RegisterExternalMethName(TypeInfo(FloodInsightsServerPortType), 'FloodInsightsService_GetUsageAvailability', 'FloodInsightsService.GetUsageAvailability');
InvRegistry.RegisterExternalMethName(TypeInfo(FloodInsightsServerPortType), 'FloodInsightsService_GetGeocode', 'FloodInsightsService.GetGeocode');
InvRegistry.RegisterExternalMethName(TypeInfo(FloodInsightsServerPortType), 'FloodInsightsService_GetMap', 'FloodInsightsService.GetMap');
InvRegistry.RegisterExternalMethName(TypeInfo(FloodInsightsServerPortType), 'FloodInsightsService_GetMap2', 'FloodInsightsService.GetMap2');
InvRegistry.RegisterExternalMethName(TypeInfo(FloodInsightsServerPortType), 'FloodInsightsService_GetMap3', 'FloodInsightsService.GetMap3');
InvRegistry.RegisterExternalMethName(TypeInfo(FloodInsightsServerPortType), 'FloodInsightsService_GetRespottedMap', 'FloodInsightsService.GetRespottedMap');
InvRegistry.RegisterExternalMethName(TypeInfo(FloodInsightsServerPortType), 'FloodInsightsService_Acknowledgement', 'FloodInsightsService.Acknowledgement');
RemClassRegistry.RegisterXSClass(clsUserCredentials, 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsUserCredentials');
RemClassRegistry.RegisterXSClass(clsMapRequest, 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsMapRequest');
RemClassRegistry.RegisterXSClass(clsRmMapInfo, 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsRmMapInfo');
RemClassRegistry.RegisterXSClass(clsResults, 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsResults');
RemClassRegistry.RegisterExternalPropName(TypeInfo(clsResults), 'Type_', 'Type');
RemClassRegistry.RegisterXSClass(clsRmLocationArrayItem, 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsRmLocationArrayItem');
RemClassRegistry.RegisterXSInfo(TypeInfo(clsRmLocationArray), 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsRmLocationArray');
RemClassRegistry.RegisterXSClass(clsRmTestResultArrayItem, 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsRmTestResultArrayItem');
RemClassRegistry.RegisterExternalPropName(TypeInfo(clsRmTestResultArrayItem), 'Name_', 'Name');
RemClassRegistry.RegisterExternalPropName(TypeInfo(clsRmTestResultArrayItem), 'Type_', 'Type');
RemClassRegistry.RegisterXSInfo(TypeInfo(clsRmTestResultArray), 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsRmTestResultArray');
RemClassRegistry.RegisterXSClass(clsRmTestResult2ArrayItem, 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsRmTestResult2ArrayItem');
RemClassRegistry.RegisterExternalPropName(TypeInfo(clsRmTestResult2ArrayItem), 'Name_', 'Name');
RemClassRegistry.RegisterExternalPropName(TypeInfo(clsRmTestResult2ArrayItem), 'Type_', 'Type');
RemClassRegistry.RegisterXSInfo(TypeInfo(clsRmTestResult2Array), 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsRmTestResult2Array');
RemClassRegistry.RegisterXSClass(clsRmFeature2ArrayItem, 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsRmFeature2ArrayItem');
RemClassRegistry.RegisterXSInfo(TypeInfo(clsRmFeature2Array), 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsRmFeature2Array');
RemClassRegistry.RegisterXSClass(clsRmFeatureArrayItem, 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsRmFeatureArrayItem');
RemClassRegistry.RegisterXSInfo(TypeInfo(clsRmFeatureArray), 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsRmFeatureArray');
RemClassRegistry.RegisterXSInfo(TypeInfo(clsRmMapInfoArray), 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsRmMapInfoArray');
RemClassRegistry.RegisterXSClass(clsAcknowledgement, 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsAcknowledgement');
RemClassRegistry.RegisterXSClass(clsGetGeocodeRequest, 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsGetGeocodeRequest');
RemClassRegistry.RegisterXSClass(clsFloodInsightsGetMapRequest, 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsFloodInsightsGetMapRequest');
RemClassRegistry.RegisterXSClass(clsGetRespottedMapRequest, 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsGetRespottedMapRequest');
RemClassRegistry.RegisterXSClass(clsUsageAccessCredentials, 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsUsageAccessCredentials');
RemClassRegistry.RegisterXSClass(clsAcknowledgementResponse, 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsAcknowledgementResponse');
RemClassRegistry.RegisterXSClass(clsAcknowledgementResponseData, 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsAcknowledgementResponseData');
RemClassRegistry.RegisterXSClass(clsGetGeocodeResponse, 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsGetGeocodeResponse');
RemClassRegistry.RegisterXSInfo(TypeInfo(clsCdCandidateArray), 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsCdCandidateArray');
RemClassRegistry.RegisterXSClass(clsCDGeoResults, 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsCDGeoResults');
RemClassRegistry.RegisterXSClass(clsCdCandidateArrayItem, 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsCdCandidateArrayItem');
RemClassRegistry.RegisterXSClass(clsCDGeneral, 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsCDGeneral');
RemClassRegistry.RegisterXSClass(clsFloodInsightsGetMapResponse, 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsFloodInsightsGetMapResponse');
RemClassRegistry.RegisterXSClass(clsGetMapResponse, 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsGetMapResponse');
RemClassRegistry.RegisterXSClass(clsFloodInsightsGetMap2Response, 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsFloodInsightsGetMap2Response');
RemClassRegistry.RegisterXSClass(clsGetMap2Response, 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsGetMap2Response');
RemClassRegistry.RegisterXSClass(clsFloodInsightsGetMap3Response, 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsFloodInsightsGetMap3Response');
RemClassRegistry.RegisterXSClass(clsGetMap3Response, 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsGetMap3Response');
RemClassRegistry.RegisterXSClass(clsGetRespottedMapResponse, 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsGetRespottedMapResponse');
RemClassRegistry.RegisterXSClass(clsGetUsageAvailabilityData, 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsGetUsageAvailabilityData');
RemClassRegistry.RegisterExternalPropName(TypeInfo(clsGetUsageAvailabilityData), 'Message_', 'Message');
RemClassRegistry.RegisterXSClass(clsGetUsageAvailabilityResponse, 'http://webservices.appraisalworld.com/secure/ws/WSDL', 'clsGetUsageAvailabilityResponse');
end. |
unit ORMDemo.Model;
interface
uses
{$IFDEF NEXTGEN}
SynCrossPlatformJSON,
SynCrossPlatformRest,
{$ELSE}
mORMot,
SynCommons,
{$ENDIF}
Quick.ORM.Engine;
type
TLogin = class
private
fUsername : RawUTF8;
fUserPass : RawUTF8;
fLastLogin : TDateTime;
published
property Username : RawUTF8 read fUsername write fUsername;
property UserPass : RawUTF8 read fUserPass write fUserPass;
property LastLogin : TDateTime read fLastLogin write fLastLogin;
end;
{ TAUser }
TAUser = class(TSQLRecordTimeStamped)
private
fName : RawUTF8;
fSurname : RawUTF8;
fAge : Integer;
fLogin : TLogin;
public
constructor Create; override;
published
property Name : RawUTF8 read fName write fName;
property Surname : RawUTF8 read fSurname write fSurname;
property Age : Integer read fAge write fAge;
property Login : TLogin read fLogin write fLogin;
end;
TAGroup = class(TSQLRecord)
private
fName : RawUTF8;
fAllowNewUsers : Boolean;
published
property Name : RawUTF8 read fName write fName;
property AllowNewUsers : Boolean read fAllowNewUsers write fAllowNewUsers;
end;
implementation
{ TAUser }
constructor TAUser.Create;
begin
inherited;
fLogin := TLogin.Create;
end;
end.
|
{Hint: save all files to location: C:\Documents\lazarus\Essais\AppGridViewDemo2\jni }
unit unit1;
{$mode delphi}
interface
uses
Classes, SysUtils, AndroidWidget, gridview, Laz_And_Controls;
type
TCell = record
Item, ImgIdentifier: string;
end;
TCells = array of TCell;
{ TAndroidModule1 }
TAndroidModule1 = class(jForm)
BtnAddRow: jButton;
BtnDelRow: jButton;
BtnReset: jButton;
EditCol: jEditText;
EditValue: jEditText;
EditRow: jEditText;
BtnIncVal: jButton;
BtnAddCol: jButton;
BtnDelCol: jButton;
jGridView1: jGridView;
PanelActionButtons: jPanel;
LabelCol: jTextView;
LabelValue: jTextView;
LabelRow: jTextView;
PanelBottom: jPanel;
PanelEdits: jPanel;
PanelInfo: jTextView;
PanelTop: jPanel;
procedure AndroidModule1JNIPrompt(Sender: TObject);
procedure BtnAddColClick(Sender: TObject);
procedure BtnAddRowClick(Sender: TObject);
procedure BtnIncValClick(Sender: TObject);
procedure BtnDelColClick(Sender: TObject);
procedure BtnDelRowClick(Sender: TObject);
procedure BtnResetClick(Sender: TObject);
procedure EditColChange(Sender: TObject; txt: string; count: integer);
procedure EditRowChange(Sender: TObject; txt: string; count: integer);
procedure jGridView1ClickItem(Sender: TObject; ItemIndex: integer;
itemCaption: string);
private
procedure DisplayCellCoords;
procedure DisplayEdits(Col, Row: integer);
procedure ShowInfo;
procedure ShowItem(const Col, Row: integer; const Item: string);
procedure UpdateButtons;
procedure UpdateEdits;
{private declarations}
public
{public declarations}
end;
var
AndroidModule1: TAndroidModule1;
implementation
{$R *.lfm}
function GridView_PrintCoord(const col, row: integer): string;
begin
Result := IntToStr(Col) + 'x' + IntToStr(Row);
end;
{ TAndroidModule1 }
procedure TAndroidModule1.ShowItem(const Col, Row: integer; const Item: string);
begin
EditCol.Text := IntToStr(Col);
EditRow.Text := IntToStr(Row);
end;
procedure TAndroidModule1.UpdateButtons ;
var
Row, Col : integer;
begin
if trystrtoint(EditRow.Text,Row) and (Row >= 0) then
begin
BtnAddRow.Text := 'Add 1 row after '+Inttostr(Row);
BtnDelRow.Text := 'Del row '+Inttostr(Row);
BtnDelRow.Enabled:= true;
BtnDelRow.Visible := true;
end
else
begin
BtnAddRow.Text := 'Ins 1 top row';
BtnDelRow.Text := '';
BtnDelRow.Enabled:= false;
BtnDelRow.Visible := false;
end;
if trystrtoint(EditCol.Text,Col) and (col >= 0) then
begin
BtnAddCol.Text := 'Add 1 Col after '+Inttostr(Col);
BtnDelCol.Text := 'Del Col '+Inttostr(Col);
BtnDelCol.Enabled:= true;
BtnDelCol.Visible:= true;
end
else
begin
BtnAddCol.Text := 'Ins 1 left col';
BtnDelCol.Text := '';
BtnDelCol.Enabled:= false;
BtnDelCol.Visible:= false;
end;
end;
procedure TAndroidModule1.DisplayCellCoords;
var
row, col, P: integer;
Item : string ;
begin
// display all
for Col := 0 to jGridView1.ColCount - 1 do
for Row := 0 to jGridView1.RowCount - 1 do
begin
Item := jGridView1.Cells[Col,Row];
P := pos('=', Item );
jGridView1.Cells[Col, Row] := GridView_PrintCoord(Col, Row)+'='+copy(Item,P+1, Length(Item)-P ); ;
end;
end;
procedure TAndroidModule1.DisplayEdits ( Col, Row : integer );
begin
try
EditCol.OnChange := nil ;
EditRow.OnChange:= nil;
if (Col >=0) and (Col < jGridView1.ColCount) and (Row >=0) and (Row < jGridView1.RowCount) then
// valid col and row
ShowItem(Col, Row, jGridView1.Cells[Col, Row])
else
begin
// invalid col or row
EditValue.Clear ;
if (Row >= jGridView1.RowCount) or (Row < 0) then
EditRow.Clear
else
EditRow.Text := inttostr(Row);
if (Col >= jGridView1.ColCount) or (Col < 0) then
EditCol.Clear
else
EditCol.Text := IntToStr(Col);
end ;
finally
EditCol.OnChange := EditColChange ;
EditRow.OnChange:= EditRowChange;
end;
end;
procedure TAndroidModule1.UpdateEdits ;
var
row, col: integer;
begin
Row := StrToIntDef(EditRow.Text,-1);
Col := StrToIntDef(EditCol.Text,-1);
// try to set max possible values
if (Row >= jGridView1.RowCount) or (Row < 0) then
Row := jGridView1.Rowcount-1;
if (Col >= jGridView1.ColCount) or (Col < 0) then
Col := jGridView1.ColCount-1;
DisplayEdits( Col, Row);
end;
procedure TAndroidModule1.ShowInfo;
begin
DisplayCellCoords;
UpdateEdits ;
UpdateButtons ;
end;
procedure TAndroidModule1.BtnAddRowClick(Sender: TObject);
var
row, col: integer;
begin
Row := StrToIntDef(EditRow.Text, -1);
jGridView1.AddRow ( Row );
// set value into new cells
inc(Row);
for Col := 0 to jGridView1.ColCount - 1 do
jGridView1.Cells[Col, Row] := GridView_PrintCoord(Col, Row)+'='+EditValue.Text;
ShowMessage ( 'Added '+copy(BtnAddRow.Text,4,maxint) );
ShowInfo;
end;
procedure TAndroidModule1.BtnIncValClick(Sender: TObject);
var
Item : string ;
begin
Item := EditValue.Text;
if (Length(Item) <> 1) or (Item[1] = 'Z') then
EditValue.Text := 'A'
else
EditValue.Text := Chr( Ord(Item[1])+1 );
UpdateButtons;
end;
procedure TAndroidModule1.BtnDelColClick(Sender: TObject);
var
Col: integer;
begin
Col := strtointdef(EditCol.Text, -1);
jGridView1.DeleteCol(Col);
ShowMessage ( 'Deleted '+copy(BtnAddCol.Text,7,maxint) );
ShowInfo;
end;
procedure TAndroidModule1.BtnDelRowClick(Sender: TObject);
var
Row: integer;
begin
Row := strtointdef(EditRow.Text, -1);
jGridView1.DeleteRow(Row);
ShowMessage ( 'Deleted '+copy(BtnAddRow.Text,7,maxint) );
ShowInfo;
end;
procedure TAndroidModule1.BtnResetClick(Sender: TObject);
var
row, col: integer;
begin
// display all
for Col := 0 to jGridView1.ColCount - 1 do
for Row := 0 to jGridView1.RowCount - 1 do
jGridView1.Cells[Col, Row] := GridView_PrintCoord(Col, Row)+'='+GridView_PrintCoord(Col, Row);
EditCol.Clear;
EditRow.Clear;
EditValue.Clear;
UpdateButtons;
end;
procedure TAndroidModule1.EditColChange(Sender: TObject; txt: string;
count: integer);
begin
//ShowInfo ;
end;
procedure TAndroidModule1.EditRowChange(Sender: TObject; txt: string;
count: integer);
begin
//ShowInfo ;
end;
procedure TAndroidModule1.jGridView1ClickItem(Sender: TObject;
ItemIndex: integer; itemCaption: string);
var
col, row: integer;
begin
jGridView1.IndexToCoord(ItemIndex, Col, Row);
DisplayEdits ( Col, Row );
UpdateButtons;
end;
procedure TAndroidModule1.AndroidModule1JNIPrompt(Sender: TObject);
begin
jGridView1.Clear;
EditValue.Clear;
ShowInfo;
end;
procedure TAndroidModule1.BtnAddColClick(Sender: TObject);
var
row, col: integer;
begin
col := StrToIntDef( EditCol.Text, -1 );
jGridView1.AddCol (Col);
// show coordinates into new cells
inc(Col);
for Row := 0 to jGridView1.Rowcount - 1 do
jGridView1.Cells[Col, Row] := GridView_PrintCoord(col, row)+'='+EditValue.Text;
ShowMessage ( 'Added '+copy(BtnAddCol.Text,4,maxint) );
ShowInfo;
end;
end.
|
unit Pedido;
interface
uses
SysUtils,
Contnrs,
Usuario, Cliente, Endereco;
type
TPedido = class
private
Fcodigo_comanda: integer;
Fcodigo: integer;
Fcodigo_mesa: integer;
Fvalor_total: Real;
Fobservacoes: String;
Fcouvert: Real;
Fdata: TDateTime;
Fdesconto: Real;
Facrescimo: Real;
Fsituacao: String;
FItens :TObjectList;
FCriouListaItens :Boolean;
FTaxa_servico :Real;
FTipo_moeda :String;
FImprime_apos_salvar :Boolean;
FNome_cliente :String;
FTelefone :String;
FCpf_cliente :String;
FCLiente :TCliente;
FCodigo_endereco :integer;
FEndereco :TEndereco;
FValor_pago: Real;
FAgrupadas :String;
FTaxa_entrega: Real;
FSts_recebimento: String;
function GetItens: TObjectList;
function GetTotal_produtos: Real;
function GetTotal_servicos: Real;
function GetCliente: TCliente;
function GetEndereco: TEndereco;
public
property codigo :integer read Fcodigo write Fcodigo;
property codigo_comanda :integer read Fcodigo_comanda write Fcodigo_comanda;
property codigo_mesa :integer read Fcodigo_mesa write Fcodigo_mesa;
property data :TDateTime read Fdata write Fdata;
property observacoes :String read Fobservacoes write Fobservacoes;
property situacao :String read Fsituacao write Fsituacao;
property couvert :Real read Fcouvert write Fcouvert;
property desconto :Real read Fdesconto write Fdesconto;
property acrescimo :Real read Facrescimo write Facrescimo;
property valor_total :Real read Fvalor_total write Fvalor_total;
property taxa_servico :Real read FTaxa_servico write FTaxa_servico;
property tipo_moeda :String read FTipo_moeda write FTipo_moeda;
property nome_cliente :String read FNome_cliente write FNome_cliente;
property telefone :String read FTelefone write FTelefone;
property cpf_cliente :String read FCpf_cliente write FCpf_cliente;
property Cliente :TCliente read GetCliente;
property Codigo_endereco :Integer read Fcodigo_endereco write FCodigo_endereco;
property valor_pago :Real read FValor_pago write FValor_pago;
property Agrupadas :String read FAgrupadas write FAgrupadas;
property taxa_entrega :Real read Ftaxa_entrega write Ftaxa_entrega;
property sts_recebimento :String read FSts_recebimento write FSts_recebimento;
public
property Itens :TObjectList read GetItens write FItens;
property Total_produtos :Real read GetTotal_produtos;
property Total_servicos :Real read GetTotal_servicos;
property Endereco :TEndereco read GetEndereco;
public
constructor Create;
destructor Destroy; override;
end;
implementation
uses repositorio, fabricaRepositorio, EspecificacaoClientePorCpfCnpj, EspecificacaoItensDoPedido, Item,
Classes, Math;
{ TPedido }
constructor TPedido.Create;
begin
inherited create;
self.FCriouListaItens := false;
self.FItens := nil;
FImprime_apos_salvar := false;
end;
destructor TPedido.Destroy;
begin
if self.FCriouListaItens and Assigned(self.FItens) then
FreeAndNil(self.FItens);
inherited;
end;
function TPedido.GetCliente: TCliente;
var
Repositorio :TRepositorio;
Especificacao :TEspecificacaoClientePorCpfCnpj;
begin
Repositorio := nil;
Especificacao := nil;
try
if not Assigned(self.FCliente) then begin
Especificacao := TEspecificacaoClientePorCpfCnpj.Create(self.cpf_cliente);
Repositorio := TFabricaRepositorio.GetRepositorio(TCliente.ClassName);
self.FCLiente := TCliente(Repositorio.GetPorEspecificacao(Especificacao));
end;
result := self.FCLiente;
finally
FreeAndNil(Especificacao);
FreeAndNil(Repositorio);
end;
end;
function TPedido.GetEndereco: TEndereco;
var repositorio :TRepositorio;
begin
if not assigned(FEndereco) then begin
repositorio := TFabricaRepositorio.GetRepositorio(TEndereco.ClassName);
FEndereco := TEndereco( repositorio.Get( self.FCodigo_endereco ) );
end;
result := FEndereco;
end;
function TPedido.GetItens: TObjectList;
var
Repositorio :TRepositorio;
Especificacao :TEspecificacaoItensDoPedido;
begin
Repositorio := nil;
Especificacao := nil;
try
if not Assigned(self.FItens) then begin
Especificacao := TEspecificacaoItensDoPedido.Create(self);
Repositorio := TFabricaRepositorio.GetRepositorio(TItem.ClassName);
self.FItens := Repositorio.GetListaPorEspecificacao(Especificacao, 'CODIGO_PEDIDO ='+IntToStr(self.Codigo));
FCriouListaItens := true;
end;
result := self.FItens;
finally
FreeAndNil(Especificacao);
FreeAndNil(Repositorio);
end;
end;
function TPedido.GetTotal_produtos: Real;
var i :integer;
begin
result := 0;
for i := 0 to self.Itens.Count - 1 do
if TItem(Itens.Items[i]).Produto.tipo = 'P' then
result := result + (TItem(Itens.Items[i]).valor_Unitario * TItem(Itens.Items[i]).quantidade);
end;
function TPedido.GetTotal_servicos: Real;
var i :integer;
begin
result := 0;
for i := 0 to self.Itens.Count - 1 do
if TItem(Itens.Items[i]).Produto.tipo = 'S' then
result := result + (TItem(Itens.Items[i]).valor_Unitario * IfThen(TItem(Itens.Items[i]).quantidade > 599, 1, TItem(Itens.Items[i]).quantidade));
end;
end.
|
unit EV04;
{===============================================================================
File: ULEV04.MAK
Library Call Demonstrated: cbEnableEvent - ON_SCAN_ERROR
- ON_END_OF_AO_SCAN
cbDisableEvent()
Purpose: Paces a waveform out channel 0 using cbAOutScan.
At scan start, it sets the digital output high,
and upon scan completion, it sets the digital
output low. Fatal errors such as UNDERRUN
errors, cause the scan to be aborted.
Demonstration: Shows how to enable and respond to events.
Other Library Calls: cbAOutScan()
cbErrHandling()
cbDOut()
Special Requirements: Board 0 must support event handling, paced
analog outputs, and cbDOut.
(c) Copyright 2001-2002, Measurement Computing Corp.
All rights reserved.
===============================================================================}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Cbw;
type
TfrmEventDisplay = class(TForm)
cmdEnableEvents: TButton;
cmdDisableEvents: TButton;
cmdStart: TButton;
cmdStop: TButton;
Label1: TLabel;
Label2: TLabel;
txtStatus: TEdit;
txtTotalCount: TEdit;
chkAutoRestart: TCheckBox;
procedure cmdStopClick(Sender: TObject);
procedure cmdStartClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure cmdDisableEventsClick(Sender: TObject);
procedure cmdEnableEventsClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
DataPtr:PWordArray;
end;
PWord = ^Word;
var
frmEventDisplay: TfrmEventDisplay;
implementation
var
Rate:LongInt;
const
BoardNum = 0;
Channel = 0;
TotalCount = 2000;
SampleRate = 1000;
Range = BIP5VOLTS;
Options = BACKGROUND;
PortNum = FIRSTPORTA;
PortDir = DIGITALOUT;
SIGNAL_ON = $FF;
SIGNAL_OFF = $00;
PI = 3.1415926536;
{$R *.DFM}
{
This gets called upon ON_END_OF_AO_SCAN events.
For these event types, the EventData supplied curresponds
to the number of samples output since the start of cbAOutScan.
}
procedure MyCallback(Bd:LongInt; EventType:LongInt;
SampleCount:LongInt; UserData: Pointer);stdcall;
var
Display: TfrmEventDisplay;
ULStat: Integer;
begin
Display := UserData;
//give the library a chance to cleanup
cbStopBackground(Bd, AOFUNCTION);
//signal external device that scan is complete
cbDOut(Bd, PortNum, SIGNAL_OFF);
//update the display
Display.txtTotalCount.Text := IntToStr(SampleCount);
Display.txtStatus.Text := 'IDLE';
if (Display.chkAutoRestart.Checked) then
begin
//start a new scan
Rate := SampleRate;
ULStat := cbAOutScan( Bd, Channel, Channel, TotalCount, Rate,
Range, LongInt(Display.DataPtr), Options);
if (ULStat = NOERRORS) then
//signal external device that there's an active scan in progress
cbDOut(Bd, PortNum, SIGNAL_ON);
Display.txtTotalCount.Text := '0';
Display.txtStatus.Text := 'RUNNING';
end;
end;
//A scan error occurred; abort and reset the controls.
procedure OnErrCallback(Bd:LongInt; EventType:LongInt;
ErrNo:LongInt; UserData: Pointer);stdcall;
var
Display: TfrmEventDisplay;
begin
Display := UserData;
cbStopBackground(Bd, AOFUNCTION);
// Reset the bAutoRestart such that the ON_END_OF_AO_SCAN event does
// not automatically start a new scan
Display.chkAutoRestart.Checked := False;
end;
procedure TfrmEventDisplay.cmdEnableEventsClick(Sender: TObject);
var
ULStat : Integer;
EventType: LongInt;
EventSize: LongInt;
begin
{
Enable and connect one or more event types to a single user callback
function using cbEnableEvent().
Parameters:
BoardNum :the number used by CB.CFG to describe this board
EventType :the condition that will cause an event to fire
EventSize :only used for ON_DATA_AVAILABLE to determine how
many samples to collect before firing an event
@MyCallback :the address of the user function to call when above event
type occurs. Note that this function cannot be a member
function. So, send self-reference to handle instance specific
data.
Self :provide reference to this instance of the form so that
handler accesses this form's data, not some other's.
}
EventType := ON_END_OF_AO_SCAN;
EventSize := 0;
ULStat := cbEnableEvent(BoardNum, EventType, EventSize, @MyCallback, Self);
if ULStat <> NOERRORS then exit;
{
Since ON_SCAN_ERROR event doesn't use the EventSize, we can set it to anything
we choose without affecting the ON_DATA_AVAILABLE setting.
}
EventType := ON_SCAN_ERROR;
cbEnableEvent(BoardNum, EventType, EventSize, @OnErrCallback, Self);
end;
procedure TfrmEventDisplay.cmdDisableEventsClick(Sender: TObject);
begin
{
Disable and disconnect all event types with cbDisableEvent()
Since disabling events that were never enabled is harmless,
we can disable all the events at once.
Parameters:
BoardNum :the number used by CB.CFG to describe this board
ALL_EVENT_TYPES :all event types will be disabled
}
cbDisableEvent(BoardNum, ALL_EVENT_TYPES);
end;
procedure TfrmEventDisplay.cmdStartClick(Sender: TObject);
var
ULStat:Integer;
begin
//start a new scan
Rate := SampleRate;
ULStat := cbAOutScan(BoardNum, Channel, Channel, TotalCount,
Rate, Range, LongInt(DataPtr),Options);
if ULStat = NOERRORS then
begin
txtStatus.Text := 'RUNNING';
txtTotalCount.Text := '0';
end;
end;
procedure TfrmEventDisplay.cmdStopClick(Sender: TObject);
begin
//make sure we don't restart the scan ON_END_OF_AI_SCAN
chkAutoRestart.Checked := False;
cbStopBackground(BoardNum, AOFUNCTION);
txtStatus.Text := 'IDLE';
end;
procedure TfrmEventDisplay.FormCreate(Sender: TObject);
var
Phase: Double;
val: Single;
i:Integer;
begin
{
Initiate error handling
activating error handling will trap errors like
bad channel numbers and non-configured conditions.
Parameters:
PRINTALL :all warnings and errors encountered will be printed
DONTSTOP :if an error is encountered, the program will not stop,
errors must be handled locally
}
cbErrHandling(PRINTALL, DONTSTOP);
//prepare digital port for signalling external device
cbDConfigPort(BoardNum, PortNum, PortDir);
//allocate the data buffer and store the waveform
DataPtr := PWordArray(cbWinBufAlloc(TotalCount));
for i:=0 to TotalCount-1 do
begin
Phase := 2*PI*i/TotalCount;
val := 2040*(1+sin(Phase));
DataPtr^[0] := Trunc(val);
end;
end;
procedure TfrmEventDisplay.FormDestroy(Sender: TObject);
begin
// make sure to shut down
cbStopBackground(BoardNum, AOFUNCTION);
// disable any active events
cbDisableEvent(BoardNum, ALL_EVENT_TYPES);
// and free the data buffer
cbWinBufFree(LongInt(DataPtr));
end;
end.
|
program hash_table_string;
uses crt;
const
MAX_SIZE = 30;
BUCKET_MAX_SIZE = 4;
p = 0; // change the point value!
type
key_t = string;
bucket_t = array[1..BUCKET_MAX_SIZE] of key_t;
hashtable_t = array[1..MAX_SIZE] of bucket_t;
list_t = array[1..MAX_SIZE*BUCKET_MAX_SIZE] of key_t;
var
hashtable: hashtable_t;
bsizes: array[1..MAX_SIZE] of integer;
size: integer;
function Hash(key: key_t): integer;
begin
Hash := 1;
end;
function Find(key: key_t): boolean;
begin
Find := false;
end;
function Add(key: key_t): boolean;
begin
Add := false;
end;
function Delete(key: key_t): boolean;
begin
Delete := false;
end;
function GetSize(): integer;
begin
GetSize := -1;
end;
procedure MakePPrint();
begin
end;
procedure Clear();
begin
end;
function test(): boolean;
var TEST_NAME: string; KEEP_RUNNING: boolean;
procedure cprint(text: string; c: integer);
begin
textcolor(c);
writeln(text);
normvideo
end;
function ASSERT_EQ(got, expected: integer) : boolean;
begin
ASSERT_EQ := got = expected;
if not (ASSERT_EQ) then begin
cprint(TEST_NAME + ' failed with assertion error:', red);
writeln('got: ', got);
writeln('expected: ', expected);
KEEP_RUNNING := false
end
end;
function ASSERT_TRUE(got: boolean): boolean;
begin
ASSERT_TRUE := got;
if not(ASSERT_TRUE) then begin
cprint(TEST_NAME + ' failed with assertion error:', red);
writeln('got: false');
writeln('expected: true');
KEEP_RUNNING := false
end
end;
function ASSERT_FALSE(got: boolean): boolean;
begin
ASSERT_FALSE := not(got);
if not(ASSERT_FALSE) then begin
cprint(TEST_NAME + ' failed with assertion error:', red);
writeln('got: true');
writeln('expected: false');
KEEP_RUNNING := false
end
end;
procedure test_run();
begin
KEEP_RUNNING := true;
// add your test procedures here
end;
begin
test_run();
if (KEEP_RUNNING) then cprint('Job succed.', green)
else cprint('Testing failed.', red);
test := KEEP_RUNNING
end;
BEGIN
test()
END.
|
unit IdTestSMTPServer;
//odd: TIdCommandHandler.DoCommand: Response.Assign(Self.Response);
interface
uses
IdGlobal,
IdReplySMTP,
IdTCPClient,
IdSMTPServer,
IdMessage,
IdObjs,
IdSMTP,
IdSys,
IdLogDebug,
IdTest;
type
TIdTestSMTPServer = class(TIdTest)
private
FReceivedMsg:TIdMessage;
FServer:TIdSMTPServer;
FClient:TIdSMTP;
FDebug:TIdLogDebug;
//replace setup/teardown with virtuals
procedure mySetup;
procedure myTearDown;
procedure CallbackRcptTo(ASender: TIdSMTPServerContext; const AAddress : string;
var VAction : TIdRCPToReply; var VForward : string);
procedure CallbackMsgReceive(ASender: TIdSMTPServerContext; AMsg : TIdStream;var LAction : TIdDataReply);
procedure CallbackMailFrom(ASender: TIdSMTPServerContext; const AAddress : string;
var VAction : TIdMailFromReply);
published
procedure TestGreeting;
procedure TestReceive;
procedure TestReject;
end;
implementation
const
cTestPort=20202;
cSpammerAddress='spammer@example.com';
procedure TIdTestSMTPServer.mySetup;
begin
Assert(FReceivedMsg=nil);
FReceivedMsg:=TIdMessage.Create(nil);
Assert(FServer=nil);
FServer:=TIdSMTPServer.Create(nil);
FServer.OnMsgReceive:=CallbackMsgReceive;
FServer.OnRcptTo:=CallbackRcptTo;
FServer.OnMailFrom:=CallbackMailFrom;
FServer.DefaultPort:=cTestPort;
FDebug:=TIdLogDebug.Create;
Assert(FClient=nil);
FClient:=TIdSMTP.Create(nil);
FClient.ReadTimeout:=5000;
FClient.Port:=cTestPort;
FClient.Host:='127.0.0.1';
FClient.CreateIOHandler;
FClient.IOHandler.Intercept := FDebug;
FDebug.Active := True;
end;
procedure TIdTestSMTPServer.myTearDown;
begin
FDebug.Active := False;
Sys.FreeAndNil(FDebug);
Sys.FreeAndNil(FClient);
Sys.FreeAndNil(FServer);
Sys.FreeAndNil(FReceivedMsg);
end;
procedure TIdTestSMTPServer.CallbackMailFrom(ASender: TIdSMTPServerContext;
const AAddress: string; var VAction: TIdMailFromReply);
begin
if AAddress=cSpammerAddress then
begin
VAction:=mReject;
end;
end;
procedure TIdTestSMTPServer.CallbackMsgReceive(
ASender: TIdSMTPServerContext; AMsg: TIdStream;
var LAction: TIdDataReply);
var
aList:TIdStringList;
begin
//do a precheck here.
aList:=TIdStringList.Create;
try
AMsg.Position:=0;
aList.Text:=ReadStringFromStream(AMsg);
//should be at least headers for: received from subject to date
//if this fails, then client hasn't written correctly, or server hasn't read
Assert(aList.Count>=5);
finally
sys.FreeAndNil(aList);
end;
AMsg.Position:=0;
FReceivedMsg.LoadFromStream(AMsg);
end;
procedure TIdTestSMTPServer.CallbackRcptTo(ASender: TIdSMTPServerContext;
const AAddress: string; var VAction: TIdRCPToReply;
var VForward: string);
begin
VAction:=rAddressOk;
end;
procedure TIdTestSMTPServer.TestGreeting;
//checks that the server returns a correct greeting
//uses tcpclient to check directly
var
s:string;
aClient:TIdTCPClient;
const
cGreeting='HELLO';
begin
aClient:=TIdTCPClient.Create(nil);
try
mySetup;
//Set a specific greeting, makes easy to test
(FServer.Greeting as TIdReplySMTP).SetEnhReply(220, '' ,cGreeting);
FServer.Active:=True;
aClient.Port:=cTestPort;
aClient.Host:='127.0.0.1';
aClient.ReadTimeout:=5000;
aClient.Connect;
s:=aClient.IOHandler.Readln;
//real example '220 mail.example.com ESMTP'
Assert(s='220 '+cGreeting);
aClient.Disconnect;
finally
Sys.FreeAndNil(aClient);
myTearDown;
end;
end;
procedure TIdTestSMTPServer.TestReceive;
//do a round-trip message send using smtp client and server
//repeat with/without client pipelining?
var
aMessage:TIdMessage;
const
cFrom='bob@example.com';
cSubject='mysubject';
cBody='1,2,3';
cAddress='mary@example.com';
cPriority:TIdMessagePriority=mpHigh;
begin
try
mySetup;
FServer.Active:=True;
FClient.Connect;
aMessage := TIdMessage.Create(nil);
try
aMessage.From.Address := cFrom;
aMessage.Subject := cSubject;
aMessage.Body.CommaText := cBody;
//test with multiple recipients
aMessage.Recipients.Add.Address := cAddress;
aMessage.Priority :=cPriority;
aMessage.Encoding := mePlaintext;
FClient.Send(aMessage);
finally
Sys.FreeAndNil(aMessage);
end;
Assert(FClient.LastCmdResult.NumericCode =250, 'Code:' + Sys.IntToStr(FClient.LastCmdResult.NumericCode));
//check that what the server received is same as sent
Assert(FReceivedMsg.From.Address = cFrom, 'From:' + FReceivedMsg.From.Address);
Assert(FReceivedMsg.Subject = cSubject, 'Subject:' + FReceivedMsg.Subject);
Assert(FReceivedMsg.Body.CommaText = cBody, 'Body:' + FReceivedMsg.Body.CommaText);
Assert(FReceivedMsg.Recipients.EMailAddresses = cAddress, 'To:' + FReceivedMsg.Recipients.EMailAddresses);
Assert(FReceivedMsg.Priority = cPriority, 'Priority');
//also check the "Received:" header
//also check attachments
//currently breaks due to ioHandler rev26
finally
myTearDown;
end;
end;
procedure TIdTestSMTPServer.TestReject;
//check that if a message is rejected by server, (here using OnMailFrom)
//the correct status is returned.
var
aMessage:TIdMessage;
begin
try
mySetup;
FServer.Active:=True;
FClient.Connect;
aMessage:=TIdMessage.Create(nil);
try
aMessage.From.Address:=cSpammerAddress;
aMessage.Subject:='spam';
aMessage.Body.CommaText:='spam';
aMessage.Recipients.Add.Address:='bob@example.com';
try
FClient.Send(aMessage);
except
//want to ignore the exception here
//EIdSMTPReplyError
//check class,content
on E : Exception do
begin
//You can NOT do:
//
//Assert(FClient.LastCmdResult.NumericCode = 550, FClient.LastCmdResult.FormattedReply.Text);
//
//because the exception may be from a line in a pipelined sequence and
//LastCmdResult probably contains the result from the last command in the pipelined
//sequence
if E is EIdSMTPReplyError then
begin
with (E as EIdSMTPReplyError) do
begin
Assert( (E as EIdSMTPReplyError).ErrorCode = 550, (E as EIdSMTPReplyError).Message);
end;
end;
end;
end;
finally
Sys.FreeAndNil(aMessage);
end;
finally
myTearDown;
end;
end;
initialization
TIdTest.RegisterTest(TIdTestSMTPServer);
end.
|
unit FileSelector;
interface
uses
System.Classes;
type
TFileSelector = class
private
FilePath: string;
Component: TComponent;
public
function getFilePath: string;
constructor Create(Component: TComponent);
procedure save(const Content: string);
procedure Load;
end;
implementation
uses
Vcl.Dialogs;
{ TFileSelector }
constructor TFileSelector.Create(Component: TComponent);
var
OpenDialog: TOpenDialog;
begin
Self.Component := Component;
end;
function TFileSelector.getFilePath: string;
begin
Result := FilePath;
end;
procedure TFileSelector.Load;
var
OpenDialog: TOpenDialog;
begin
OpenDialog := TOpenDialog.Create(Component);
OpenDialog.Options := [ofFileMustExist];
if OpenDialog.Execute then
FilePath := OpenDialog.FileName;
OpenDialog.Free;
end;
procedure TFileSelector.save(const Content: string);
var
saveDialog: TSaveDialog;
Data: TStringList;
begin
saveDialog := TSaveDialog.Create(Component);
// Give the dialog a title
saveDialog.Title := 'Save your text or word file';
// Allow only .txt and .doc file types to be saved
// saveDialog.Filter := 'Text file|*.txt|Word file|*.doc';
// Set the default extension
// saveDialog.DefaultExt := 'txt';
// Select text files as the starting filter type
// saveDialog.FilterIndex := 1;
// Display the open file dialog
if not(saveDialog.Execute) then
begin
ShowMessage('Save file was cancelled');
Exit;
end;
ShowMessage('File : ' + saveDialog.FileName);
Data := TStringList.Create;
Data.Add(Content);
Data.SaveToFile(saveDialog.FileName);
// Free up the dialog
saveDialog.Free;
end;
end.
|
unit ufonctionDiv;
// |===========================================================================|
// | unit ufonctionDiv |
// | 2010 F.BASSO |
// |___________________________________________________________________________|
// | unité permettant d'avoir les informations de version de copyrigth d'un |
// | programme |
// |___________________________________________________________________________|
// | Ce programme est libre, vous pouvez le redistribuer et ou le modifier |
// | selon les termes de la Licence Publique Générale GNU publiée par la |
// | Free Software Foundation . |
// | Ce programme est distribué car potentiellement utile, |
// | mais SANS AUCUNE GARANTIE, ni explicite ni implicite, |
// | y compris les garanties de commercialisation ou d'adaptation |
// | dans un but spécifique. |
// | Reportez-vous à la Licence Publique Générale GNU pour plus de détails. |
// | |
// | anbasso@wanadoo.fr |
// |___________________________________________________________________________|
// | Versions |
// | 1.0.0.0 Création de l'unité |
// |===========================================================================|
interface
Function StrLectureVersion : String;
Function StrLectureNomProduit : String;
Function StrLectureCopyright : String;
implementation
uses forms,types,windows,sysutils;
function GetInformation (strinfo : string):string;
Var
S : String;
Taille : DWord;
Buffer : PChar;
VersionPC : PChar;
VersionL : DWord;
Begin
Result:='';
// On demande la taille des informations sur l'application
S := Application.ExeName;
Taille := GetFileVersionInfoSize(PChar(S), Taille);
If Taille>0
Then Try
// Réservation en mémoire d'une zone de la taille voulue
Buffer := AllocMem(Taille);
// Copie dans le buffer des informations
GetFileVersionInfo(PChar(S), 0, Taille, Buffer);
// Recherche de l'information de version
If VerQueryValue(Buffer, PChar('\StringFileInfo\040C04E4\'+strinfo), Pointer(VersionPC), VersionL)
Then Result:=VersionPC;
Finally
FreeMem(Buffer, Taille);
End;
end;
Function StrLectureVersion : String;
// ___________________________________________________________________________
// | function StrLectureVersion |
// | _________________________________________________________________________ |
// || Permet d'avoir le numero de version de l'appli ||
// ||_________________________________________________________________________||
// || Sorties | String ||
// || | Version de l'appli ||
// ||_________|_______________________________________________________________||
// |___________________________________________________________________________|
begin
result := GetInformation('FileVersion');
End;
Function StrLectureNomProduit : String;
// ___________________________________________________________________________
// | function StrLectureNomProduit |
// | _________________________________________________________________________ |
// || Permet d'avoir le nom de l'appli ||
// ||_________________________________________________________________________||
// || Sorties | String ||
// || | Nom de l'appli ||
// ||_________|_______________________________________________________________||
// |___________________________________________________________________________|
begin
result := GetInformation('InternalName');
End;
Function StrLectureCopyright : String;
// ___________________________________________________________________________
// | function StrLectureCopyright |
// | _________________________________________________________________________ |
// || Permet d'avoir le Copyright de l'appli ||
// ||_________________________________________________________________________||
// || Sorties | String ||
// || | Copyright de l'appli ||
// ||_________|_______________________________________________________________||
// |___________________________________________________________________________|
begin
result := GetInformation('LegalCopyright');
End;
end.
|
unit uCrMain;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, IniFiles;
type
TForm1 = class(TForm)
Label1: TLabel;
edInFile: TEdit;
Bevel1: TBevel;
btnBrowseInFile: TButton;
opndlg: TOpenDialog;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
lbLangName: TLabel;
lbTranslator: TLabel;
lbComment: TLabel;
Label5: TLabel;
edOutFile: TEdit;
btnBrowseOut: TButton;
btnCompile: TButton;
Button1: TButton;
procedure btnBrowseInFileClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnBrowseOutClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure btnCompileClick(Sender: TObject);
private
{ Private-Deklarationen }
Curr:TMemIniFile;
procedure OpenFile(FN:String);
function GetStr(Sect,Key,Def:String):string;
public
{ Public-Deklarationen }
end;
var
Form1: TForm1;
implementation
uses DUGetText, DUStrings, CRC32;
{$R *.DFM}
resourcestring
InFilter = 'LangRaw(*.lraw)|*.lraw|Alle Dateien(*.*)|*.*';
OutFilter = 'Lang(*.lang)|*.lang|Alle Dateien(*.*)|*.*';
AllWritten= 'Datei erzeugt!';
const
Sig = '## DUGETTEXT LRAW FILE ##';
Info = 'Info';
procedure TForm1.FormCreate(Sender: TObject);
begin
Curr:= TMemIniFile.Create('');
if ParamCount>0 then begin
edInFile.Text:= ParamStr(1);
edOutFile.Text:= ChangeFileExt(edInFile.Text,'.lang');
OpenFile(edInFile.Text);
end;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
Curr.Free;
end;
function TForm1.GetStr(Sect, Key, Def: String): string;
begin
Result:= Curr.ReadString(Sect,Key,Def);
Result:= ExtractQuotedString(Result,'"');
end;
procedure TForm1.OpenFile(FN: String);
var l:TStringList;
begin
if not FileExists(Fn) then exit;
Curr.Clear;
l:= TStringList.Create;
try
l.LoadFromFile(FN);
if L.Count<2 then exit;
if l[0]<>Sig then exit;
l.Delete(0);
Curr.SetStrings(l);
lbLangName.Caption:= GetStr(Info,'LangName','');
lbTranslator.Caption:= GetStr(Info,'Translator','');
lbComment.Caption:= GetStr(Info,'Comments','');
finally
l.Free;
end;
end;
procedure TForm1.btnBrowseInFileClick(Sender: TObject);
begin
opndlg.Filter:= InFilter;
opndlg.FileName:= edInFile.Text;
if opndlg.Execute then
edInFile.Text:= opndlg.FileName;
lbLangName.Caption:='';
lbTranslator.Caption:= '';
lbComment.Caption:= '';
OpenFile(edInFile.Text);
end;
procedure TForm1.btnBrowseOutClick(Sender: TObject);
begin
opndlg.Filter:= OutFilter;
opndlg.FileName:= edOutFile.Text;
if opndlg.Execute then
edOutFile.Text:= opndlg.FileName;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
Close;
end;
procedure TForm1.btnCompileClick(Sender: TObject);
var tbl:TTranslationTable;
l:TStringList;
i:integer;
s:string;
st:TFileStream;
begin
FillChar(tbl.Header,sizeof(tbl.Header),0);
tbl.Header.ProgramID:= Curr.ReadInteger(Info,'ProgramID',0);
tbl.Header.LangID:= Curr.ReadInteger(Info,'LangID',LANG_NEUTRAL);
tbl.Header.SubLangID:= Curr.ReadInteger(Info,'SubLangID',SUBLANG_NEUTRAL);
tbl.Header.LangName:= GetStr(Info,'LangName','');
tbl.Header.Translator:= GetStr(Info,'Translator','');
tbl.Header.Comments:= GetStr(Info,'Comments','');
l:= TStringList.Create;
try
Curr.ReadSection('Items',l);
tbl.Header.ItemCount:= l.Count;
SetLength(Tbl.Items,tbl.Header.ItemCount);
for i:= 0 to l.Count-1 do begin
FillChar(Tbl.Items[i],sizeof(Tbl.Items[i]),0);
Tbl.Items[i].Head.StringID:= ToStrID(l[i]);
s:= GetStr('Items',l[i],'');
ConvertSpecials(S);
Tbl.Items[i].Head.Length:= length(s);
tbl.Items[i].Data:= s;
end;
st:= TFileStream.Create(edOutFile.Text,fmCreate);
try
WriteLanguage(tbl,st);
finally
st.Free;
end;
finally
l.Free;
end;
MessageDlg(AllWritten,mtInformation,[mbOk],0);
end;
end.
|
unit FDisplay;
interface
uses
Windows, FOpenGl, FStructure, FMath3d;
type
int2 = array[0..1] of integer;
TCoords3c = record
X : currency;
Y : currency;
Z : currency;
end;
MatrixSaveType = record
Time : Integer;
Matrix : PGLFLoat;
end;
TModel = class
private
_angle : Currency;
procedure setAngle(a : Currency);
public
ModelPath : string;
ModelID : integer;
_ModelScale : Integer;
MatrixSave : array of MatrixSaveType;
RealPos : TCoords3c;
InterfacePos : TPoint;
Animated : Boolean;
AnimRepeat : Boolean;
AnimID : Integer;
AnimTime : Integer;
AnimPlayAfter : string;
AnimDoAfter : string;
AnimCurrent : string;
TeamColor : TCoords3c;
procedure set_ModelScale(effect : integer);
property ModelScale : integer read _ModelScale write set_ModelScale;
property Angle : Currency read _angle write setAngle;
procedure SetAnim(name : string; AnimRepeat : boolean = true; forceUpdate : boolean = false);
procedure SetPath(path : string);
procedure UpdateAnim(time : integer = -1);
procedure Display(select : boolean = false);
procedure ApplyTexture(i : integer);
function ApplyTransformation(i, j : integer) : Float3;
function inFrustum() : boolean;
function GetGeosetAlpha(GeosetID : integer; select: boolean) : Float;
function GetTransformation(ObjectId, time : integer) : PGLFloat;
procedure ClearSavedMatrix();
constructor Create();
end;
const
NOPARENT = 4294967295;
implementation
uses
FBase, FTextures, FFrustum, Flogs, SysUtils, FFPS, Math, FLoader, FInterfaceDraw;
constructor TModel.Create();
begin
self.AnimPlayAfter := '';
self.AnimDoAfter := 'Ready';
end;
procedure TModel.ClearSavedMatrix();
var
i : integer;
begin
for i := 0 to Length(self.MatrixSave) - 1 do
self.MatrixSave[i].Time := -1;
end;
function TModel.inFrustum() : boolean;
begin
Result := ModelInFrustum(@LoadedModels[self.ModelID], self.AnimID, self.RealPos.X, self.RealPos.Y, self.RealPos.Z);
end;
procedure TModel.SetPath(path: string);
begin
self.ModelPath := path;
Self.ModelID := GetModel(path);
SetLength(self.MatrixSave, LoadedModels[self.ModelID].ObjectMaxId + 1);
self.ClearSavedMatrix();
end;
procedure TModel.setAngle(a : Currency);
begin
self._angle := a;
// if self._angle < 0 then
// self._angle := 2*PI + self._angle
// else if self._angle > 2*PI then
// self._angle := -2*PI + self._angle;
end;
procedure TModel.SetAnim(name : string; AnimRepeat : boolean = true; forceUpdate : boolean = false);
var
i, k, len : integer;
Model : PMdxModel;
begin
name := LowerCase(name);
if (self.AnimCurrent = name) and not forceUpdate then
exit;
if name = '' then begin
self.Animated := False;
exit;
end else
self.Animated := True;
Model := @LoadedModels[self.ModelID];
len := Length(Model^.Sequence);
i := 0;
while (i < len) and (LowerCase(Model^.Sequence[i].Name) <> name) do
Inc(i);
if (i = len) then begin
AddLine('Animation `' + name + '` not found on `' + Model^.Model.Name + '`');
exit;
end;
k := 0;
while (i + k + 1 < len) and (Model^.Sequence[i + k + 1].Rarity > 0)
and (Random() > 1 / Model^.Sequence[i + k + 1].Rarity) do
Inc(k);
if (i + k + 1 = len) or (Model^.Sequence[i + k + 1].Rarity = 0) then
k := -1;
self.AnimID := i + k + 1;
self.AnimTime := Model^.Sequence[self.AnimID].IntervalStart;
self.AnimCurrent := name;
self.AnimRepeat := AnimRepeat;
self.ClearSavedMatrix();
end;
procedure TModel.UpdateAnim(time : integer = -1);
var
Model : PMdxModel;
begin
if not Self.Animated then
exit;
Model := @LoadedModels[self.ModelID];
if time = -1 then
if (self.AnimTime + Count.Elapsed > Integer(Model^.Sequence[self.AnimID].IntervalEnd)) then
if self.AnimRepeat then begin
if self.AnimPlayAfter <> '' then begin
self.AnimCurrent := self.AnimPlayAfter;
self.AnimPlayAfter := '';
end;
if self.AnimDoAfter = '' then
self.AnimDoAfter := 'Ready';
self.SetAnim(self.AnimCurrent, true, true);
end else begin
self.AnimTime := Model^.Sequence[self.AnimID].IntervalEnd;
self.SetAnim('');
end
else
self.AnimTime := (self.AnimTime
+ Count.Elapsed
- Integer(Model^.Sequence[self.AnimID].IntervalStart))
mod
(Integer(Model^.Sequence[self.AnimID].IntervalEnd)
- Integer(Model^.Sequence[self.AnimID].IntervalStart))
+ Integer(Model^.Sequence[self.AnimID].IntervalStart)
else
self.AnimTime := Integer(Model^.Sequence[self.AnimID].IntervalStart) + time;
end;
function FindKey(Transfo : Transformation1; t : Cardinal; Sequence : PSequenceChunk; var k : int2) : integer; overload;
var
i, len : integer;
begin
len := Length(Transfo.Scaling);
k[0] := -1;
i := 0;
while (i < len) and (Transfo.Scaling[i].Time <= t) and (Transfo.Scaling[i].Time <= Sequence^.IntervalEnd) do begin
k[0] := i;
Inc(i);
end;
if (k[0] = -1) or (k[0] >= len) or (Transfo.Scaling[k[0]].Time < Sequence^.IntervalStart)
or (Transfo.Scaling[k[0]].Time > Sequence.IntervalEnd) then
Result := 0
else begin
k[1] := k[0] + 1;
if (k[1] >= len) or (Transfo.Scaling[k[1]].Time < Sequence.IntervalStart) then
Result := 1
else
Result := 2;
end;
end;
function FindKey(Transfo : Transformation3; t : Cardinal; Sequence : PSequenceChunk; var k : int2) : integer; overload;
var
i, len : integer;
begin
len := Length(Transfo.Scaling);
k[0] := -1;
i := 0;
while (i < len) and (Transfo.Scaling[i].Time <= t) and (Transfo.Scaling[i].Time <= Sequence^.IntervalEnd) do begin
k[0] := i;
Inc(i);
end;
if (k[0] = -1) or (k[0] >= len) or (Transfo.Scaling[k[0]].Time < Sequence^.IntervalStart)
or (Transfo.Scaling[k[0]].Time > Sequence.IntervalEnd) then
Result := 0
else begin
k[1] := k[0] + 1;
if (k[1] >= len) or (Transfo.Scaling[k[1]].Time < Sequence.IntervalStart) then
Result := 1
else
Result := 2;
end;
end;
function FindKey(Transfo : Transformation4; t : Cardinal; Sequence : PSequenceChunk; var k : int2) : integer; overload;
var
i, len : integer;
begin
len := Length(Transfo.Scaling);
k[0] := -1;
i := 0;
while (i < len) and (Transfo.Scaling[i].Time <= t) and (Transfo.Scaling[i].Time <= Sequence^.IntervalEnd) do begin
k[0] := i;
Inc(i);
end;
if (k[0] = -1) or (k[0] >= len) or (Transfo.Scaling[k[0]].Time < Sequence^.IntervalStart)
or (Transfo.Scaling[k[0]].Time > Sequence.IntervalEnd) then
Result := 0
else begin
k[1] := k[0] + 1;
if (k[1] >= len) or (Transfo.Scaling[k[1]].Time < Sequence.IntervalStart) then
Result := 1
else
Result := 2;
end;
end;
function CalculatePos(Transfo : Transformation1; time: integer; Sequence : PSequenceChunk; Default : Float; var IsChanged : Boolean) : Float; overload;
var
k : int2;
found : integer;
begin
found := FindKey(Transfo, time, Sequence, k);
if (found = 0) or ((found = 1) and (Transfo.InterpolationType > 0)) then begin
Result := Default;
IsChanged := false;
end else begin
IsChanged := true;
if Transfo.InterpolationType = 0 then
Result := Transfo.Scaling[k[0]].Value
else
Result :=
Interpolate(time,
Transfo.Scaling[k[0]].Time,
Transfo.Scaling[k[1]].Time,
Transfo.Scaling[k[0]].Value,
Transfo.Scaling[k[1]].Value,
Transfo.InterpolationType
);
end;
end;
function CalculatePos(Transfo : Transformation3; time: integer; Sequence : PSequenceChunk; Default : Float3; var IsChanged : Boolean) : Float3; overload;
var
k : int2;
found : integer;
begin
found := FindKey(Transfo, time, Sequence, k);
if (found = 0) or ((found = 1) and (Transfo.InterpolationType > 0)) then begin
Result := Default;
IsChanged := false;
end else begin
IsChanged := true;
if Transfo.InterpolationType = 0 then
Result := Transfo.Scaling[k[0]].Value
else begin
Result[0] :=
Interpolate(time,
Transfo.Scaling[k[0]].Time,
Transfo.Scaling[k[1]].Time,
Transfo.Scaling[k[0]].Value[0],
Transfo.Scaling[k[1]].Value[0],
Transfo.InterpolationType
);
Result[1] :=
Interpolate(time,
Transfo.Scaling[k[0]].Time,
Transfo.Scaling[k[1]].Time,
Transfo.Scaling[k[0]].Value[1],
Transfo.Scaling[k[1]].Value[1],
Transfo.InterpolationType
);
Result[2] :=
Interpolate(time,
Transfo.Scaling[k[0]].Time,
Transfo.Scaling[k[1]].Time,
Transfo.Scaling[k[0]].Value[2],
Transfo.Scaling[k[1]].Value[2],
Transfo.InterpolationType
);
end;
end;
end;
function CalculatePos(Transfo : Transformation4; time: integer; Sequence : PSequenceChunk; Default : Float4; var IsChanged : Boolean) : Float4; overload;
var
k : int2;
found : integer;
begin
found := FindKey(Transfo, time, Sequence, k);
if (found = 0) or ((found = 1) and (Transfo.InterpolationType > 0)) then begin
Result := Default;
IsChanged := false;
end else begin
IsChanged := true;
if Transfo.InterpolationType = 0 then
Result := Transfo.Scaling[k[0]].Value
else
Result :=
QuaternionSlerp(
Transfo.Scaling[k[0]].Value,
Transfo.Scaling[k[1]].Value,
(Cardinal(time) - Transfo.Scaling[k[0]].Time) / (Transfo.Scaling[k[1]].Time - Transfo.Scaling[k[0]].Time)
);
end;
end;
function TModel.GetGeosetAlpha(GeosetID : integer; select: boolean) : Float;
var
i, len : integer;
Model : pMdxModel;
t : boolean;
begin
Model := @LoadedModels[self.ModelID];
i := 0;
len := Length(Model^.GeosetAnimation);
if select and (Model^.Geoset[GeosetID].SelectionFlags = 4) then begin
Result := 0;
exit;
end;
// Hack
if (Length(Model^.Material[Model^.Geoset[GeosetID].MaterialId].Layer) > 0)
and (Model^.Texture[Model^.Material[Model^.Geoset[GeosetID].MaterialId].Layer[0].TextureId].ReplaceableId = 2) then begin
Result := 0;
exit;
end;
if len = 0 then begin
Result := 1;
exit;
end;
while (i < len - 1) and (Integer(Model^.GeosetAnimation[i].GeosetId) <> GeosetID) do
Inc(i);
if (Integer(Model^.GeosetAnimation[i].GeosetId) <> GeosetID) then
Result := 1
else begin
Result := CalculatePos(
Model^.GeosetAnimation[i].GeosetAlpha,
self.AnimTime, @Model^.Sequence[self.AnimID], 1, t
);
end;
end;
function FindNode(Model : pMDXModel; ObjectId : integer) : PNodeChunk;
var
i : integer;
begin
// Search the good node
i := 0;
while (i < Length(Model^.Bone)) and (Integer(Model^.Bone[i].Node.ObjectId) <> ObjectId) do
Inc(i);
if (i = Length(Model^.Bone)) then begin
i := 0;
while (i < Length(Model^.Helper)) and (Integer(Model^.Helper[i].ObjectId) <> ObjectId) do
Inc(i);
if (i = Length(Model^.Helper)) then begin
Result := nil;
Log('Model Error: ' + Model^.Model.Name + ' can''t find the Node ' + IntToStr(ObjectId));
exit;
end else
Result := @Model^.Helper[i];
end else
Result := @Model^.Bone[i].Node;
end;
function TModel.GetTransformation(ObjectId, time : integer) : PGLFloat;
var
Node : PNodeChunk;
Translation, Pivot, Scaling : Float3;
Rotation : Float4;
isTranslation, isRotation, isScaling : Boolean;
Model : pMDXModel;
begin
Model := @LoadedModels[self.ModelID];
// Find the node
Node := FindNode(Model, ObjectId);
if Node = nil then begin
Result := IdentityMatrix;
exit;
end;
// if already calculated
if time = self.MatrixSave[ObjectId].Time then begin
Result := self.MatrixSave[ObjectId].Matrix;
exit;
end;
// Calculate
glPushMatrix();
// Base Matrix
if Node^.ParentId <> NOPARENT then begin
glLoadMatrixf(self.GetTransformation(Node^.ParentId, time));
end else
glLoadIdentity();
// Getting transformations
Translation := CalculatePos(Node^.NodeTranslation, time, @Model^.Sequence[self.AnimID], DefaultTranslation, isTranslation);
Rotation := CalculatePos(Node^.NodeRotation, time, @Model^.Sequence[self.AnimID], DefaultQuaternion, isRotation);
Scaling := CalculatePos(Node^.NodeScaling, time, @Model^.Sequence[self.AnimID], DefaultScaling, isScaling);
Pivot := Model^.PivotPoint[ObjectId];
// Apply transformations
if isTranslation and (isRotation or isScaling) then
glTranslatef(Translation[0] + Pivot[0], Translation[1] + Pivot[1], Translation[2] + Pivot[2])
else if isTranslation then
glTranslatef(Translation[0], Translation[1], Translation[2])
else if isRotation or isScaling then
glTranslatef(Pivot[0], Pivot[1], Pivot[2]);
if isRotation then
glMultMatrixf(QuaternionToMatrix(Rotation));
if isScaling then
glScalef(Scaling[0], Scaling[1], Scaling[2]);
if isRotation or isScaling then
glTranslatef(-Pivot[0], -Pivot[1], -Pivot[2]);
glGetFloatv(GL_MODELVIEW_MATRIX, Result);
// Storing it
self.MatrixSave[ObjectId].Matrix := Result;
self.MatrixSave[ObjectId].Time := time;
glPopMatrix();
end;
function TModel.ApplyTransformation(i, j : integer) : Float3;
var
l, len : integer;
Matrix : PGLFloat;
Model : pMDXModel;
begin
Model := @LoadedModels[self.ModelID];
len := Length(Model^.Geoset[i].Matrix[Model^.Geoset[i].VertexGroup[j]]);
Matrix := NullMatrix;
for l := 0 to len - 1 do
AddMatrix(Matrix, self.GetTransformation(Model^.Geoset[i].Matrix[Model^.Geoset[i].VertexGroup[j]][l], self.AnimTime));
MultMatrix(Matrix, 0.1 * self.ModelScale / len);
Result := TransformVector(Model^.Geoset[i].VertexPosition[j], Matrix);
end;
procedure TModel.ApplyTexture(i : integer);
var
j : integer;
Model : pMdxModel;
Layer : ^LayerChunk;
Texture : ^TextureChunk;
begin
Model := @LoadedModels[self.ModelID];
for j := 0 to Length(Model^.Material[Model^.Geoset[i].MaterialId].Layer) - 1 do begin
glClientActiveTexture(GL_TEXTURE0_ARB + j);
glActiveTexture(GL_TEXTURE0_ARB + j);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnable(GL_TEXTURE_2D);
Layer := @Model^.Material[Model^.Geoset[i].MaterialId].Layer[j];
Texture := @Model^.Texture[Layer^.TextureId];
case Layer^.FilterMode of
0 : begin
end;
1 : begin // transparent
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_ALPHA_TEST);
glAlphaFunc(GL_GREATER, 0.8);
end;
2 : begin // blend
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
if j > 0 then
glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL );
end;
3 : begin // additive
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE);
end;
end;
case Texture^.ReplaceableId of
0 : begin // Texture
BindTexture(Texture^.GLID);
end;
1 : begin // Team Color
glColor3f(self.TeamColor.X, self.TeamColor.Y, self.TeamColor.Z);
BindTexture(BlankGLID);
end;
2 : begin // Team Glow
BindTexture(TransparentGLID); // Hack en attendant le vrai code !
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
AddLine(inttoStr(Length(Model^.Material[Model^.Geoset[i].MaterialId].Layer)));
end;
end;
glTexCoordPointer(2, GL_FLOAT, 0, Model^.Geoset[i].TexturePosition)
end;
end;
procedure TModel.Display(select : boolean=false);
var
i, j, k : integer;
geo : array of Float3;
Model : pMDXModel;
begin
Model := @LoadedModels[self.ModelID];
for i := 0 to length(Model^.Geoset) - 1 do begin
if GeosetInFrustum(@Model^.Geoset[i], self.RealPos) and (self.GetGeosetAlpha(i, select) > 0) then begin
glEnableClientState(GL_VERTEX_ARRAY);
// Texture
if not select then
self.ApplyTexture(i);
// Vertex
SetLength(geo, Length(Model^.Geoset[i].VertexPosition));
for j := 0 to Length(geo) - 1 do
geo[j] := self.ApplyTransformation(i, j);
glVertexPointer(3, GL_FLOAT, 0, geo);
// Draw
glDrawElements(GL_TRIANGLES, Length(Model^.Geoset[i].Face) * 3, GL_UNSIGNED_SHORT, Model^.Geoset[i].Face);
// Cleaning Up
if not select then begin
glColor3f(1, 1, 1);
glDisable(GL_ALPHA_TEST);
glDisable(GL_BLEND);
for k := Length(Model^.Material[Model^.Geoset[i].MaterialId].Layer) - 1 downto 0 do begin
glClientActiveTexture(GL_TEXTURE0_ARB + k);
glActiveTexture(GL_TEXTURE0_ARB + k);
glDisable(GL_TEXTURE_2D);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE );
end;
end;
end;
end;
end;
procedure TModel.set_ModelScale(effect : integer);
begin
self._ModelScale := effect;
end;
end.
|
unit MotorAz;
{$WARN SYMBOL_PLATFORM OFF}
interface
uses
ComObj, RDAObj, Rda_TLB;
type
TMotor_Az =
class( TRDAObject, IMotorStatus, IMotorControl )
protected //IMotorStatus
function Get_Posicion: Integer; safecall;
function Get_Velocidad: Integer; safecall;
function Get_SP_Posicion: Integer; safecall;
function Get_SP_Velocidad: Integer; safecall;
function Get_Lazo_Posicion: WordBool; safecall;
function Get_Acc_Listo: WordBool; safecall;
function Get_Marca_Posicion: Integer; safecall;
function Get_Lazo_Sector: WordBool; safecall;
function Get_Taco_Code: Integer; safecall;
function Get_Taco_Unit: Double; safecall;
function Get_Range_Taco: Integer; safecall;
function Get_Sector_Taco: Integer; safecall;
function Get_Status: RadarStatus; safecall;
protected //IMotorControl
procedure Set_SP_Posicion(Value: Integer); safecall;
procedure Set_SP_Velocidad(Value: Integer); safecall;
procedure Set_Lazo_Posicion(Value: WordBool); safecall;
function Get_Lazo_Posicion_K: Single; safecall;
procedure Set_Lazo_Posicion_K(Value: Single); safecall;
function Get_Lazo_Velocidad_K: Single; safecall;
procedure Set_Lazo_Velocidad_K(Value: Single); safecall;
procedure Set_Marca_Posicion(Value: Integer); safecall;
procedure Set_Lazo_Sector(Value: WordBool); safecall;
procedure Set_Range_Taco(Value: Integer); safecall;
procedure Set_Sector_Taco(Value: Integer); safecall;
end;
const
Class_Motor_Az: TGUID = '{FC95A152-24B2-4753-B3CE-5A01037508C7}';
implementation
uses
ComServ,
ElbrusTypes, Elbrus;
function TMotor_Az.Get_Posicion: Integer;
begin
Result := Snapshot.Position_Az;
end;
function TMotor_Az.Get_Velocidad: Integer;
begin
Result := Snapshot.Velocity_Az;
end;
function TMotor_Az.Get_Lazo_Posicion: WordBool;
begin
Result := Snapshot.Position_Loop_Az;
end;
function TMotor_Az.Get_SP_Posicion: Integer;
begin
Result := Snapshot.SP_Position_Az;
end;
function TMotor_Az.Get_SP_Velocidad: Integer;
begin
Result := Snapshot.SP_Velocity_Az;
end;
procedure TMotor_Az.Set_Lazo_Posicion(Value: WordBool);
begin
if InControl
then Elbrus.Set_Lazo_Posicion_Az(Value);
end;
procedure TMotor_Az.Set_SP_Posicion(Value: Integer);
begin
if InControl
then Elbrus.Set_SP_Posicion_Az(Value);
end;
procedure TMotor_Az.Set_SP_Velocidad(Value: Integer);
begin
if InControl
then Elbrus.Set_SP_Velocidad_Az(Value);
end;
function TMotor_Az.Get_Lazo_Posicion_K: Single;
begin
Result := Snapshot.Position_Loop_Az_K;
end;
procedure TMotor_Az.Set_Lazo_Posicion_K(Value: Single);
begin
if InControl
then Elbrus.Set_Lazo_K_Pos_Az(Value);
end;
function TMotor_Az.Get_Acc_Listo: WordBool;
begin
Result := (SnapShot.Digital_Input and di_Acc_Listo_Az) <> 0;
end;
function TMotor_Az.Get_Lazo_Velocidad_K: Single;
begin
Result := Snapshot.Velocity_Loop_Az_K;
end;
procedure TMotor_Az.Set_Lazo_Velocidad_K(Value: Single);
begin
if InControl
then Elbrus.Set_Lazo_K_Vel_Az(Value);
end;
procedure TMotor_Az.Set_Lazo_Sector(Value: WordBool);
begin
if InControl
then Elbrus.Set_Lazo_Sector_Az(Value);
end;
procedure TMotor_Az.Set_Marca_Posicion(Value: Integer);
begin
if InControl
then Elbrus.Set_Mark_Posicion_Az(Value);
end;
function TMotor_Az.Get_Marca_Posicion: Integer;
begin
Result := Snapshot.Mark_Position_Az;
end;
function TMotor_Az.Get_Lazo_Sector: WordBool;
begin
Result := Snapshot.Sector_Loop_Az;
end;
function TMotor_Az.Get_Status: RadarStatus;
begin
if Snapshot.MotorAz_ON
then if Snapshot.MotorAz_Ok
then result := rsOk
else result := rsFailure
else result := rsOff;
end;
function TMotor_Az.Get_Range_Taco: Integer;
begin
Result := integer(Snapshot.AI_Range[ai_Taco_Az]);
end;
function TMotor_Az.Get_Sector_Taco: Integer;
begin
Result := integer(Snapshot.AI_Sector[ai_Taco_Az]);
end;
function TMotor_Az.Get_Taco_Code: Integer;
begin
Result := Snapshot.Analog_Input[ai_Taco_Az];
end;
function TMotor_Az.Get_Taco_Unit: Double;
begin
Result := Snapshot.Analog_Input_Voltage[ai_Taco_Az];
end;
procedure TMotor_Az.Set_Range_Taco(Value: Integer);
begin
if InControl
then Elbrus.Set_AI_Range(ai_Taco_Az, TAIRange(Value));
end;
procedure TMotor_Az.Set_Sector_Taco(Value: Integer);
begin
if InControl
then Elbrus.Set_AI_Sector(ai_Taco_Az, TAIRange(Value));
end;
initialization
TComObjectFactory.Create(ComServer, TMotor_Az, Class_Motor_Az,
'Motor_Az', '', ciMultiInstance, tmApartment);
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_ecerr;
interface
// Headers for OpenSSL 1.1.1
// ecerr.h
{$i IdCompilerDefines.inc}
uses
Classes,
IdCTypes,
IdGlobal,
IdOpenSSLConsts;
const
(*
* EC function codes.
*)
EC_F_BN_TO_FELEM = 224;
EC_F_D2I_ECPARAMETERS = 144;
EC_F_D2I_ECPKPARAMETERS = 145;
EC_F_D2I_ECPRIVATEKEY = 146;
EC_F_DO_EC_KEY_PRINT = 221;
EC_F_ECDH_CMS_DECRYPT = 238;
EC_F_ECDH_CMS_SET_SHARED_INFO = 239;
EC_F_ECDH_COMPUTE_KEY = 246;
EC_F_ECDH_SIMPLE_COMPUTE_KEY = 257;
EC_F_ECDSA_DO_SIGN_EX = 251;
EC_F_ECDSA_DO_VERIFY = 252;
EC_F_ECDSA_SIGN_EX = 254;
EC_F_ECDSA_SIGN_SETUP = 248;
EC_F_ECDSA_SIG_NEW = 265;
EC_F_ECDSA_VERIFY = 253;
EC_F_ECD_ITEM_VERIFY = 270;
EC_F_ECKEY_PARAM2TYPE = 223;
EC_F_ECKEY_PARAM_DECODE = 212;
EC_F_ECKEY_PRIV_DECODE = 213;
EC_F_ECKEY_PRIV_ENCODE = 214;
EC_F_ECKEY_PUB_DECODE = 215;
EC_F_ECKEY_PUB_ENCODE = 216;
EC_F_ECKEY_TYPE2PARAM = 220;
EC_F_ECPARAMETERS_PRINT = 147;
EC_F_ECPARAMETERS_PRINT_FP = 148;
EC_F_ECPKPARAMETERS_PRINT = 149;
EC_F_ECPKPARAMETERS_PRINT_FP = 150;
EC_F_ECP_NISTZ256_GET_AFFINE = 240;
EC_F_ECP_NISTZ256_INV_MOD_ORD = 275;
EC_F_ECP_NISTZ256_MULT_PRECOMPUTE = 243;
EC_F_ECP_NISTZ256_POINTS_MUL = 241;
EC_F_ECP_NISTZ256_PRE_COMP_NEW = 244;
EC_F_ECP_NISTZ256_WINDOWED_MUL = 242;
EC_F_ECX_KEY_OP = 266;
EC_F_ECX_PRIV_ENCODE = 267;
EC_F_ECX_PUB_ENCODE = 268;
EC_F_EC_ASN1_GROUP2CURVE = 153;
EC_F_EC_ASN1_GROUP2FIELDID = 154;
EC_F_EC_GF2M_MONTGOMERY_POINT_MULTIPLY = 208;
EC_F_EC_GF2M_SIMPLE_FIELD_INV = 296;
EC_F_EC_GF2M_SIMPLE_GROUP_CHECK_DISCRIMINANT = 159;
EC_F_EC_GF2M_SIMPLE_GROUP_SET_CURVE = 195;
EC_F_EC_GF2M_SIMPLE_LADDER_POST = 285;
EC_F_EC_GF2M_SIMPLE_LADDER_PRE = 288;
EC_F_EC_GF2M_SIMPLE_OCT2POINT = 160;
EC_F_EC_GF2M_SIMPLE_POINT2OCT = 161;
EC_F_EC_GF2M_SIMPLE_POINTS_MUL = 289;
EC_F_EC_GF2M_SIMPLE_POINT_GET_AFFINE_COORDINATES = 162;
EC_F_EC_GF2M_SIMPLE_POINT_SET_AFFINE_COORDINATES = 163;
EC_F_EC_GF2M_SIMPLE_SET_COMPRESSED_COORDINATES = 164;
EC_F_EC_GFP_MONT_FIELD_DECODE = 133;
EC_F_EC_GFP_MONT_FIELD_ENCODE = 134;
EC_F_EC_GFP_MONT_FIELD_INV = 297;
EC_F_EC_GFP_MONT_FIELD_MUL = 131;
EC_F_EC_GFP_MONT_FIELD_SET_TO_ONE = 209;
EC_F_EC_GFP_MONT_FIELD_SQR = 132;
EC_F_EC_GFP_MONT_GROUP_SET_CURVE = 189;
EC_F_EC_GFP_NISTP224_GROUP_SET_CURVE = 225;
EC_F_EC_GFP_NISTP224_POINTS_MUL = 228;
EC_F_EC_GFP_NISTP224_POINT_GET_AFFINE_COORDINATES = 226;
EC_F_EC_GFP_NISTP256_GROUP_SET_CURVE = 230;
EC_F_EC_GFP_NISTP256_POINTS_MUL = 231;
EC_F_EC_GFP_NISTP256_POINT_GET_AFFINE_COORDINATES = 232;
EC_F_EC_GFP_NISTP521_GROUP_SET_CURVE = 233;
EC_F_EC_GFP_NISTP521_POINTS_MUL = 234;
EC_F_EC_GFP_NISTP521_POINT_GET_AFFINE_COORDINATES = 235;
EC_F_EC_GFP_NIST_FIELD_MUL = 200;
EC_F_EC_GFP_NIST_FIELD_SQR = 201;
EC_F_EC_GFP_NIST_GROUP_SET_CURVE = 202;
EC_F_EC_GFP_SIMPLE_BLIND_COORDINATES = 287;
EC_F_EC_GFP_SIMPLE_FIELD_INV = 298;
EC_F_EC_GFP_SIMPLE_GROUP_CHECK_DISCRIMINANT = 165;
EC_F_EC_GFP_SIMPLE_GROUP_SET_CURVE = 166;
EC_F_EC_GFP_SIMPLE_MAKE_AFFINE = 102;
EC_F_EC_GFP_SIMPLE_OCT2POINT = 103;
EC_F_EC_GFP_SIMPLE_POINT2OCT = 104;
EC_F_EC_GFP_SIMPLE_POINTS_MAKE_AFFINE = 137;
EC_F_EC_GFP_SIMPLE_POINT_GET_AFFINE_COORDINATES = 167;
EC_F_EC_GFP_SIMPLE_POINT_SET_AFFINE_COORDINATES = 168;
EC_F_EC_GFP_SIMPLE_SET_COMPRESSED_COORDINATES = 169;
EC_F_EC_GROUP_CHECK = 170;
EC_F_EC_GROUP_CHECK_DISCRIMINANT = 171;
EC_F_EC_GROUP_COPY = 106;
EC_F_EC_GROUP_GET_CURVE = 291;
EC_F_EC_GROUP_GET_CURVE_GF2M = 172;
EC_F_EC_GROUP_GET_CURVE_GFP = 130;
EC_F_EC_GROUP_GET_DEGREE = 173;
EC_F_EC_GROUP_GET_ECPARAMETERS = 261;
EC_F_EC_GROUP_GET_ECPKPARAMETERS = 262;
EC_F_EC_GROUP_GET_PENTANOMIAL_BASIS = 193;
EC_F_EC_GROUP_GET_TRINOMIAL_BASIS = 194;
EC_F_EC_GROUP_NEW = 108;
EC_F_EC_GROUP_NEW_BY_CURVE_NAME = 174;
EC_F_EC_GROUP_NEW_FROM_DATA = 175;
EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS = 263;
EC_F_EC_GROUP_NEW_FROM_ECPKPARAMETERS = 264;
EC_F_EC_GROUP_SET_CURVE = 292;
EC_F_EC_GROUP_SET_CURVE_GF2M = 176;
EC_F_EC_GROUP_SET_CURVE_GFP = 109;
EC_F_EC_GROUP_SET_GENERATOR = 111;
EC_F_EC_GROUP_SET_SEED = 286;
EC_F_EC_KEY_CHECK_KEY = 177;
EC_F_EC_KEY_COPY = 178;
EC_F_EC_KEY_GENERATE_KEY = 179;
EC_F_EC_KEY_NEW = 182;
EC_F_EC_KEY_NEW_METHOD = 245;
EC_F_EC_KEY_OCT2PRIV = 255;
EC_F_EC_KEY_PRINT = 180;
EC_F_EC_KEY_PRINT_FP = 181;
EC_F_EC_KEY_PRIV2BUF = 279;
EC_F_EC_KEY_PRIV2OCT = 256;
EC_F_EC_KEY_SET_PUBLIC_KEY_AFFINE_COORDINATES = 229;
EC_F_EC_KEY_SIMPLE_CHECK_KEY = 258;
EC_F_EC_KEY_SIMPLE_OCT2PRIV = 259;
EC_F_EC_KEY_SIMPLE_PRIV2OCT = 260;
EC_F_EC_PKEY_CHECK = 273;
EC_F_EC_PKEY_PARAM_CHECK = 274;
EC_F_EC_POINTS_MAKE_AFFINE = 136;
EC_F_EC_POINTS_MUL = 290;
EC_F_EC_POINT_ADD = 112;
EC_F_EC_POINT_BN2POINT = 280;
EC_F_EC_POINT_CMP = 113;
EC_F_EC_POINT_COPY = 114;
EC_F_EC_POINT_DBL = 115;
EC_F_EC_POINT_GET_AFFINE_COORDINATES = 293;
EC_F_EC_POINT_GET_AFFINE_COORDINATES_GF2M = 183;
EC_F_EC_POINT_GET_AFFINE_COORDINATES_GFP = 116;
EC_F_EC_POINT_GET_JPROJECTIVE_COORDINATES_GFP = 117;
EC_F_EC_POINT_INVERT = 210;
EC_F_EC_POINT_IS_AT_INFINITY = 118;
EC_F_EC_POINT_IS_ON_CURVE = 119;
EC_F_EC_POINT_MAKE_AFFINE = 120;
EC_F_EC_POINT_NEW = 121;
EC_F_EC_POINT_OCT2POINT = 122;
EC_F_EC_POINT_POINT2BUF = 281;
EC_F_EC_POINT_POINT2OCT = 123;
EC_F_EC_POINT_SET_AFFINE_COORDINATES = 294;
EC_F_EC_POINT_SET_AFFINE_COORDINATES_GF2M = 185;
EC_F_EC_POINT_SET_AFFINE_COORDINATES_GFP = 124;
EC_F_EC_POINT_SET_COMPRESSED_COORDINATES = 295;
EC_F_EC_POINT_SET_COMPRESSED_COORDINATES_GF2M = 186;
EC_F_EC_POINT_SET_COMPRESSED_COORDINATES_GFP = 125;
EC_F_EC_POINT_SET_JPROJECTIVE_COORDINATES_GFP = 126;
EC_F_EC_POINT_SET_TO_INFINITY = 127;
EC_F_EC_PRE_COMP_NEW = 196;
EC_F_EC_SCALAR_MUL_LADDER = 284;
EC_F_EC_WNAF_MUL = 187;
EC_F_EC_WNAF_PRECOMPUTE_MULT = 188;
EC_F_I2D_ECPARAMETERS = 190;
EC_F_I2D_ECPKPARAMETERS = 191;
EC_F_I2D_ECPRIVATEKEY = 192;
EC_F_I2O_ECPUBLICKEY = 151;
EC_F_NISTP224_PRE_COMP_NEW = 227;
EC_F_NISTP256_PRE_COMP_NEW = 236;
EC_F_NISTP521_PRE_COMP_NEW = 237;
EC_F_O2I_ECPUBLICKEY = 152;
EC_F_OLD_EC_PRIV_DECODE = 222;
EC_F_OSSL_ECDH_COMPUTE_KEY = 247;
EC_F_OSSL_ECDSA_SIGN_SIG = 249;
EC_F_OSSL_ECDSA_VERIFY_SIG = 250;
EC_F_PKEY_ECD_CTRL = 271;
EC_F_PKEY_ECD_DIGESTSIGN = 272;
EC_F_PKEY_ECD_DIGESTSIGN25519 = 276;
EC_F_PKEY_ECD_DIGESTSIGN448 = 277;
EC_F_PKEY_ECX_DERIVE = 269;
EC_F_PKEY_EC_CTRL = 197;
EC_F_PKEY_EC_CTRL_STR = 198;
EC_F_PKEY_EC_DERIVE = 217;
EC_F_PKEY_EC_INIT = 282;
EC_F_PKEY_EC_KDF_DERIVE = 283;
EC_F_PKEY_EC_KEYGEN = 199;
EC_F_PKEY_EC_PARAMGEN = 219;
EC_F_PKEY_EC_SIGN = 218;
EC_F_VALIDATE_ECX_DERIVE = 278;
(*
* EC reason codes.
*)
EC_R_ASN1_ERROR = 115;
EC_R_BAD_SIGNATURE = 156;
EC_R_BIGNUM_OUT_OF_RANGE = 144;
EC_R_BUFFER_TOO_SMALL = 100;
EC_R_CANNOT_INVERT = 165;
EC_R_COORDINATES_OUT_OF_RANGE = 146;
EC_R_CURVE_DOES_NOT_SUPPORT_ECDH = 160;
EC_R_CURVE_DOES_NOT_SUPPORT_SIGNING = 159;
EC_R_D2I_ECPKPARAMETERS_FAILURE = 117;
EC_R_DECODE_ERROR = 142;
EC_R_DISCRIMINANT_IS_ZERO = 118;
EC_R_EC_GROUP_NEW_BY_NAME_FAILURE = 119;
EC_R_FIELD_TOO_LARGE = 143;
EC_R_GF2M_NOT_SUPPORTED = 147;
EC_R_GROUP2PKPARAMETERS_FAILURE = 120;
EC_R_I2D_ECPKPARAMETERS_FAILURE = 121;
EC_R_INCOMPATIBLE_OBJECTS = 101;
EC_R_INVALID_ARGUMENT = 112;
EC_R_INVALID_COMPRESSED_POINT = 110;
EC_R_INVALID_COMPRESSION_BIT = 109;
EC_R_INVALID_CURVE = 141;
EC_R_INVALID_DIGEST = 151;
EC_R_INVALID_DIGEST_TYPE = 138;
EC_R_INVALID_ENCODING = 102;
EC_R_INVALID_FIELD = 103;
EC_R_INVALID_FORM = 104;
EC_R_INVALID_GROUP_ORDER = 122;
EC_R_INVALID_KEY = 116;
EC_R_INVALID_OUTPUT_LENGTH = 161;
EC_R_INVALID_PEER_KEY = 133;
EC_R_INVALID_PENTANOMIAL_BASIS = 132;
EC_R_INVALID_PRIVATE_KEY = 123;
EC_R_INVALID_TRINOMIAL_BASIS = 137;
EC_R_KDF_PARAMETER_ERROR = 148;
EC_R_KEYS_NOT_SET = 140;
EC_R_LADDER_POST_FAILURE = 136;
EC_R_LADDER_PRE_FAILURE = 153;
EC_R_LADDER_STEP_FAILURE = 162;
EC_R_MISSING_PARAMETERS = 124;
EC_R_MISSING_PRIVATE_KEY = 125;
EC_R_NEED_NEW_SETUP_VALUES = 157;
EC_R_NOT_A_NIST_PRIME = 135;
EC_R_NOT_IMPLEMENTED = 126;
EC_R_NOT_INITIALIZED = 111;
EC_R_NO_PARAMETERS_SET = 139;
EC_R_NO_PRIVATE_VALUE = 154;
EC_R_OPERATION_NOT_SUPPORTED = 152;
EC_R_PASSED_NULL_PARAMETER = 134;
EC_R_PEER_KEY_ERROR = 149;
EC_R_PKPARAMETERS2GROUP_FAILURE = 127;
EC_R_POINT_ARITHMETIC_FAILURE = 155;
EC_R_POINT_AT_INFINITY = 106;
EC_R_POINT_COORDINATES_BLIND_FAILURE = 163;
EC_R_POINT_IS_NOT_ON_CURVE = 107;
EC_R_RANDOM_NUMBER_GENERATION_FAILED = 158;
EC_R_SHARED_INFO_ERROR = 150;
EC_R_SLOT_FULL = 108;
EC_R_UNDEFINED_GENERATOR = 113;
EC_R_UNDEFINED_ORDER = 128;
EC_R_UNKNOWN_COFACTOR = 164;
EC_R_UNKNOWN_GROUP = 129;
EC_R_UNKNOWN_ORDER = 114;
EC_R_UNSUPPORTED_FIELD = 131;
EC_R_WRONG_CURVE_PARAMETERS = 145;
EC_R_WRONG_ORDER = 130;
procedure Load(const ADllHandle: TIdLibHandle; const AFailed: TStringList);
procedure UnLoad;
var
ERR_load_EC_strings: function: TIdC_INT 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
ERR_load_EC_strings := LoadFunction('ERR_load_EC_strings', AFailed);
end;
procedure UnLoad;
begin
ERR_load_EC_strings := nil;
end;
end.
|
unit UAMC_Login;
{ ClickForms Application }
{ Bradford Technologies, Inc. }
{ All Rights Reserved }
{ Source Code Copyrighted © 1998-2007 by Bradford Technologies, Inc. }
{ This unit is used to get the appraisers credentials (vendor id and
the appraiser id and password. It will be stored in the registry
and can be edited by the "Login" preferences.}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UWinUtils, StdCtrls, UForms;
type
AMCUserUID = record //Unique identifier for user
VendorID: String; //this is historical user ID
UserId: String; //this is user id (currently same as vendorID)
UserPSW: String; //this is user passowrd
end;
TAMCCredentialsForm = class(TAdvancedForm)
VendorIdLabel: TLabel;
Label1: TLabel;
Label2: TLabel;
editVendorId: TEdit;
editUserID: TEdit;
editUserPassword: TEdit;
btnRecord: TButton;
btnCancel: TButton;
procedure btnRecordClick(Sender: TObject);
private
{ Private declarations }
public
procedure RecordAMCUserCredentials;
{ Public declarations }
end;
procedure LaunchRegistryForm;
procedure ChangeRegistry;
function GetAMCCredentials: Boolean;
function GetAMCUserRegistryInfo(AppraiserID: String; var AUser: AMCUserUID): Boolean;
procedure SetAMCUserRegistryInfo(AppraiserID: String; AUser: AMCUserUID);
function GetAMCUserCredentials(var AUser: AMCUserUID; DlgCaption: String='Service'): Boolean;
var
AMCCredentialsForm: TAMCCredentialsForm;
AMCCredentials: AMCUserUID;
implementation
uses
Registry,
UGlobals, UStatus, UAMC_RELSPort, UUtil3, ULicUser;
{$R *.dfm}
const
AMCRegKey = '\AMC';
regVendorID = 'VendorID';
regUserID = 'UserID';
regUserPassword = 'UserPassword';
function GetAMCUserRegistryInfo(AppraiserID: String; var AUser: AMCUserUID): Boolean;
var
reg: TRegistry;
begin
result := False; //assume we did not find user in registry
AUser.VendorID := '';
AUser.UserId := '';
AUser.UserPSW := '';
//NOTE: Users will be registered by AMC\AppraiserID. AppraiserID is their unique identifier
//NOTE: AppraiserID is NOT the same as VendorID
reg := TRegistry.Create;
try
Reg.RootKey := HKEY_CURRENT_USER;
if reg.OpenKey(LocMachClickFormBaseSection + AMCRegKey + '\' + AppraiserID, False) then
begin
AUser.VendorID := DecryptString(reg.ReadString(regVendorID), wEncryptKey );
AUser.UserId := DecryptString(reg.ReadString(regUserID), wEncryptKey );
AUser.UserPSW := DecryptString(reg.ReadString(regUserPassword), wEncryptKey);
result := (length(AUser.VendorID) > 0) and (length(AUser.UserId) > 0)and (length(AUser.UserPSW) > 0);
end;
finally
reg.Free;
end;
end;
procedure SetAMCUserRegistryInfo(AppraiserID: String; AUser: AMCUserUID);
var
reg: TRegistry;
begin
//NOTE: Users will be registered by AMC\AppraiserID. AppraiserID is their unique identifier
//NOTE: AppraiserID is NOT the same as VendorID
reg := TRegistry.Create;
try
Reg.RootKey := HKEY_CURRENT_USER;
if reg.OpenKey(LocMachClickFormBaseSection + AMCRegKey + '\' + AppraiserID, True) then
begin
reg.WriteString(regVendorID, EncryptString(AUser.VendorID, wEncryptKey));
reg.WriteString(regUserID, EncryptString(AUser.UserId, wEncryptKey));
reg.WriteString(regUserPassword, EncryptString(AUser.UserPSW, wEncryptKey));
end;
finally
reg.Free;
end;
end;
function GetAMCUserCredentials(var AUser: AMCUserUID; DlgCaption: String='Service'): Boolean;
var
LoginForm: TAMCCredentialsForm;
begin
LoginForm := TAMCCredentialsForm.Create(Application.MainForm);
try
//load in existing info to display
LoginForm.editVendorId.Text := AUser.VendorID;
LoginForm.editUserID.Text := AUser.UserId;
LoginForm.editUserPassword.Text := AUser.UserPSW;
LoginForm.Caption := 'Enter Your ' + DlgCaption + ' Authentication Information';
LoginForm.ShowModal;
result := LoginForm.modalResult = mrCancel; //did the user cancel out???
//send back new info
AUser.VendorID := LoginForm.editVendorId.Text;
AUser.UserId := LoginForm.editUserID.Text;
AUser.UserPSW := LoginForm.editUserPassword.Text;
finally
LoginForm.Free;
end;
end;
function GetAMCCredentials: Boolean;
var
reg: TRegistry;
licFileName: String;
begin
reg := TRegistry.Create;
AMCCredentials.VendorID := '';
AMCCredentials.UserId := '';
AMCCredentials.UserPSW := '';
licFileName := ChangeFileExt(CurrentUser.UserFileName,'');
result := False;
try
Reg.RootKey := HKEY_CURRENT_USER;
if reg.OpenKey(LocMachAMCOrderSection + '\' + licFileName, False) then
begin
AMCCredentials.VendorID := DecryptString(reg.ReadString(regVendorID),wEncryptKey );
AMCCredentials.UserId := DecryptString(reg.ReadString(regUserID),wEncryptKey );
AMCCredentials.UserPSW := DecryptString(reg.ReadString(regUserPassword),wEncryptKey);
result := (length(AMCCredentials.VendorID) > 0) and (length(AMCCredentials.UserId) > 0)and (length(AMCCredentials.UserPSW) > 0);
end;
finally
reg.Free;
end;
end;
procedure ChangeRegistry;
begin
GetAMCCredentials;
LaunchRegistryForm;
end;
procedure LaunchRegistryForm;
var
regForm: TAMCCredentialsForm;
begin
regForm := TAMCCredentialsForm.Create(Application.MainForm);
try
regForm.editVendorId.Text := AMCCredentials.VendorID;
regForm.editUserID.Text := AMCCredentials.UserId;
regForm.editUserPassword.Text := AMCCredentials.UserPSW;
regForm.ShowModal;
finally
regForm.Free;
end;
end;
procedure TAMCCredentialsForm.RecordAMCUserCredentials;
var
reg: TRegistry;
licFileName: String;
begin
licFileName := ChangeFileExt(CurrentUser.UserFileName,'');
reg := TRegistry.Create;
Reg.RootKey := HKEY_CURRENT_USER;
try
if reg.OpenKey(LocMachAMCOrderSection + '\' + licFileName, True) then
begin
reg.WriteString(regVendorID,EncryptString(editVendorId.Text,wEncryptKey));
reg.WriteString(regUserID,EncryptString(editUserID.Text,wEncryptKey));
reg.WriteString(regUserPassword,EncryptString(editUserPassword.Text,wEncryptKey));
end;
finally
begin
reg.Free;
AMCCredentials.VendorID := editVendorId.Text;
AMCCredentials.UserId := editUserID.Text;
AMCCredentials.UserPSW := editUserPassword.Text;
end;
end;
end;
procedure TAMCCredentialsForm.btnRecordClick(Sender: TObject);
begin
if ((length(editVendorId.Text) = 0) or
(length(editUserID.Text) = 0)or
(length(editUserPassword.Text) = 0)) then
ShowAlert(atWarnAlert, 'You must fill in all the fields for proper authentication.')
else
modalResult := mrOK;
end;
end.
|
unit dsdExportToXMLAction;
interface
uses Forms, Data.DB, System.Classes, System.SysUtils, System.Win.ComObj, Vcl.Graphics,
Vcl.ActnList, System.Variants, DBClient, Dialogs, dsdAction, dsdDB;
type
TdsdEncodingType = (etWindows1251, etUtf8);
TdsdExportToXML = class(TdsdCustomAction)
private
FParams: TdsdParams;
FStoredProc: TdsdStoredProc;
FRootName: String;
FTagName: String;
FEncodingType : TdsdEncodingType;
FSaveFile: TSaveDialog;
procedure SetStoredProc(const Value: TdsdStoredProc);
protected
function LocalExecute: Boolean; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property RootParams: TdsdParams read FParams write FParams;
property StoredProc: TdsdStoredProc read FStoredProc write SetStoredProc;
property RootName: String read FRootName write FRootName;
property TagName : String read FTagName write FTagName;
property EncodingType : TdsdEncodingType read FEncodingType write FEncodingType default etWindows1251;
property Caption;
property Hint;
property ImageIndex;
property ShortCut;
property SecondaryShortCuts;
end;
implementation
{TdsdExportToXML}
constructor TdsdExportToXML.Create(AOwner: TComponent);
begin
inherited;
FSaveFile := TSaveDialog.Create(Application);
FSaveFile.DefaultExt := '.xml';
FSaveFile.Filter := 'Файл XML|*.xml|Все файлы|*.*';
FSaveFile.Title := 'Укажите файл для сохранения';
FSaveFile.Options := [ofFileMustExist, ofOverwritePrompt];
FParams := TdsdParams.Create(Self, TdsdParam);
end;
destructor TdsdExportToXML.Destroy;
begin
FreeAndNil(FParams);
FSaveFile := Nil;
inherited;
end;
procedure TdsdExportToXML.SetStoredProc(const Value: TdsdStoredProc);
begin
FStoredProc := Value;
end;
function TdsdExportToXML.LocalExecute: Boolean;
var
F: TextFile;
FiteText, cRoot, cTeg: string;
I : integer;
DST : TClientDataSet;
sl : TStringList;
function CodeTextParam(AParam : TdsdParam) : string;
begin
if AParam.Value <> Null then
begin
case AParam.DataType of
ftFloat : Result := CurrToStr(AParam.AsFloat);
ftDate, ftTime, ftDateTime : Result := StringReplace(AParam.Value, FormatSettings.DateSeparator, '/', [rfReplaceAll]);
else Result := AParam.Value;
end;
Result := StringReplace(Result, '<', '<', [rfReplaceAll, rfIgnoreCase]);
Result := StringReplace(Result, '>', '>', [rfReplaceAll, rfIgnoreCase]);
Result := StringReplace(Result, '&', '&', [rfReplaceAll, rfIgnoreCase]);
Result := StringReplace(Result, '''', ''', [rfReplaceAll, rfIgnoreCase]);
Result := StringReplace(Result, '"', '"', [rfReplaceAll, rfIgnoreCase]);
end else Result := '';
end;
function CodeTextField(AField : TField) : string;
begin
if not AField.IsNull then
begin
case AField.DataType of
ftFloat, ftCurrency, ftBCD : Result := StringReplace(AField.AsString, FormatSettings.DecimalSeparator, '.', [rfReplaceAll]);
ftDate, ftTime, ftDateTime : Result := StringReplace(AField.AsString, FormatSettings.DateSeparator, '/', [rfReplaceAll]);
else Result := AField.AsString;
end;
Result := StringReplace(Result, '<', '<', [rfReplaceAll, rfIgnoreCase]);
Result := StringReplace(Result, '>', '>', [rfReplaceAll, rfIgnoreCase]);
Result := StringReplace(Result, '&', '&', [rfReplaceAll, rfIgnoreCase]);
Result := StringReplace(Result, '''', ''', [rfReplaceAll, rfIgnoreCase]);
Result := StringReplace(Result, '"', '"', [rfReplaceAll, rfIgnoreCase]);
end else Result := '';
end;
begin
inherited;
Result := False;
DST := Nil;
cRoot := FRootName;
if cRoot = '' then cRoot := 'Root';
cTeg := FTagName;
if cTeg = '' then cTeg := 'Tag';
if FStoredProc = Nil then
begin
raise Exception.Create('Не определен TagStoredProc..');
Exit;
end;
if FSaveFile.Execute then
try
AssignFile(F, FSaveFile.FileName);
Rewrite(F); // переписываем файл
case FEncodingType of
etWindows1251 : FiteText := '<?xml version="1.0" encoding="windows-1251"?>'#13+#10;
etUtf8 : FiteText := '<?xml version="1.0" encoding="utf-8"?>'#13+#10;
end;
FiteText := FiteText + '<' + cRoot;
if FParams.Count > 0 then
begin
for I := 0 to FParams.Count - 1 do
begin
FiteText := FiteText + ' ' + FParams.Items[I].Name + '="' +
CodeTextParam(FParams.Items[I]) + '"';
end;
end;
FiteText := FiteText + '>'#13+#10;
if FStoredProc.DataSet = Nil then
begin
DST := TClientDataSet.Create(Nil);
FStoredProc.DataSet := DST;
end;
FStoredProc.Execute;
FStoredProc.DataSet.First;
while not FStoredProc.DataSet.Eof do
begin
FiteText := FiteText + '<' + cTeg;
for I := 0 to FStoredProc.DataSet.FieldCount - 1 do
begin
FiteText := FiteText + ' ' + FStoredProc.DataSet.Fields.Fields[I].FieldName + '="' +
CodeTextField(FStoredProc.DataSet.Fields.Fields[I]) + '"';
end;
FiteText := FiteText + '/>'#13+#10;
FStoredProc.DataSet.Next;
end;
FiteText := FiteText + '</' + cRoot + '>';
Writeln(F, FiteText);
Result := True;
finally
CloseFile(F);
if Assigned(DST) then
begin
FStoredProc.DataSet := Nil;
DST.Free;
end;
if Result and (FEncodingType = etUtf8) then
begin
sl := TStringList.Create;
try
sl.LoadFromFile(FSaveFile.FileName);
sl.SaveToFile(FSaveFile.FileName, TEncoding.UTF8)
finally
sl.Free;
end;
end;
end;
end;
end.
|
// ****************************************************************************
//
// Program Name : - AT Library -
// Program Version: 1.00
// Filenames : AT.Windows.System.pas
// File Version : 1.00
// Date Created : 26-JAN-2014
// Author : Matthew S. Vesperman
//
// Description:
//
// Angelic Tech system functions... (Migrated from SSSysUtils.pas)
//
// Revision History:
//
// v1.00 : Initial version for Delphi XE5.
//
// ****************************************************************************
//
// COPYRIGHT © 2013-Present Angelic Technology
// ALL RIGHTS RESERVED WORLDWIDE
//
// ****************************************************************************
unit AT.Windows.System;
interface
uses
System.Classes, System.Types;
/// <summary>
/// Retrieves the date/time AFilename was last modified.
/// </summary>
/// <param name="AFilename">
/// The name of the file to inspect.
/// </param>
/// <returns>
/// Returns the date/time that AFilename was last modified.
/// </returns>
function FileLastModified(const AFilename: String): TDateTime;
/// <summary>
/// Retrieves the location of the AppData folder. If ACommon is TRUE then
/// return the AppData folder for all users. The value of AAppPath is
/// appended to the value and the directory tree is forced to exist.
/// </summary>
/// <param name="AAppPath">
/// The sub-folder location within AppData to use.
/// </param>
/// <param name="ACommon">
/// If TRUE then then we use the All Users app data folder, otherwise we use
/// the user's roaming app data location.
/// </param>
/// <returns>
/// Returns a string containing the path to the app data location.
/// </returns>
function GetAppDataPath(const AAppPath: String = '';
ACommon: Boolean = False): String;
function GetAppDataDirectory(const AAppPath: String = '';
ACommon: Boolean = False): String;
/// <summary>
/// Retrieves the location of the Documents folder. If ACommon is TRUE then
/// return the Documents folder for all users. The value of ADocPath is
/// appended to the value and the directory tree is forced to exist.
/// </summary>
/// <param name="ADocPath">
/// The sub-folder location within Documents to use.
/// </param>
/// <param name="ACommon">
/// If TRUE then then we use the All Users document folder, otherwise we use
/// the user's document location.
/// </param>
/// <returns>
/// Returns a string containing the path to the document location.
/// </returns>
function GetDocumentPath(const ADocPath: String = '';
ACommon: Boolean = False): String;
function GetProgramFilesPath: String;
/// <summary>
/// Converts APoint to a string.
/// </summary>
/// <param name="APoint">
/// The point to convert.
/// </param>
/// <returns>
/// Returns a string formatted as 'APoint.X,APoint.Y'
/// </returns>
function PointToStr(const APoint: TPoint): String;
/// <summary>
/// Generates a "random" component name.
/// </summary>
/// <param name="APrefix">
/// The prefix to prepend to the component name. If no prefix is specified
/// then the prefix is 'Component'.
/// </param>
/// <returns>
/// Returns the component name as a string.
/// </returns>
/// <remarks>
/// Actually returns a string where the name is the prefix + the current
/// date/time formatted as 'yyyymmdd_hhnnsszzz'.
/// </remarks>
function RandomComponentName(const APrefix: String = ''): String;
/// <summary>
/// Splits AString into a stringlist of values.
/// </summary>
/// <param name="AString">
/// The string to tokenize.
/// </param>
/// <param name="ADelim">
/// The character to split at.
/// </param>
/// <param name="ATokens">
/// A variable pointing to a stringlist to receive the results.
/// </param>
procedure StrTokens(const AString: String; const ADelim: Char;
var ATokens: TStrings);
/// <summary>
/// Converts AStr to a point value.
/// </summary>
/// <param name="AStr">
/// The string to convert.
/// </param>
/// <returns>
/// Returns a point value. If the string cannot be converted an exception of
/// EConvertError is raised.
/// </returns>
function StrToPoint(const AStr: String): TPoint;
implementation
uses
System.SysUtils, Winapi.SHFolder, Winapi.Windows, System.RegularExpressions;
function FileLastModified(const AFilename: String): TDateTime;
begin
if (NOT FileAge(AFilename, Result)) then
Result := 0;
end;
function GetAppDataPath(const AAppPath: String = '';
ACommon: Boolean = False): String;
var
iFolderID: Integer;
AFolder : array [0 .. MAX_PATH] of Char;
begin
AFolder := '';
if (ACommon) then
iFolderID := CSIDL_COMMON_APPDATA
else
iFolderID := CSIDL_APPDATA;
if (Succeeded(SHGetFolderPath(0, iFolderID, 0, SHGFP_TYPE_CURRENT,
@AFolder[0]))) then
begin
Result := AFolder;
Result := IncludeTrailingPathDelimiter(Result);
Result := Format('%s%s', [Result, AAppPath]);
ForceDirectories(Result);
end
else
begin
Result := '';
end;
end;
function GetAppDataDirectory(const AAppPath: String = '';
ACommon: Boolean = False): String;
begin
Result := GetAppDataPath(AAppPath, ACommon);
end;
function GetDocumentPath(const ADocPath: String = '';
ACommon: Boolean = False): String;
var
iFolderID: Integer;
AFolder : array [0 .. MAX_PATH] of Char;
begin
AFolder := '';
if (ACommon) then
iFolderID := CSIDL_COMMON_DOCUMENTS
else
iFolderID := CSIDL_PERSONAL;
if (Succeeded(SHGetFolderPath(0, iFolderID, 0, SHGFP_TYPE_CURRENT,
@AFolder[0]))) then
begin
Result := AFolder;
Result := IncludeTrailingPathDelimiter(Result);
Result := Format('%s%s', [Result, ADocPath]);
ForceDirectories(Result);
end
else
begin
Result := '';
end;
end;
function GetProgramFilesPath: String;
var
iFolderID: Integer;
AFolder : array [0 .. MAX_PATH] of Char;
begin
AFolder := '';
iFolderID := CSIDL_PROGRAM_FILES;
if (Succeeded(SHGetFolderPath(0, iFolderID, 0, SHGFP_TYPE_CURRENT,
@AFolder[0]))) then
begin
Result := AFolder;
end
else
begin
Result := EmptyStr;
end;
end;
function PointToStr(const APoint: TPoint): String;
begin
Result := Format('%d,%d', [APoint.X, APoint.Y]);
end;
function RandomComponentName(const APrefix: String = ''): String;
const
sFmt = 'yyyymmdd_hhnnsszzz';
var
sVal: String;
begin
DateTimeToString(sVal, sFmt, Now);
if (APrefix <> '') then
sVal := APrefix + sVal
else
sVal := 'Component' + sVal;
Result := sVal;
end;
procedure StrTokens(const AString: String; const ADelim: Char;
var ATokens: TStrings);
var
ATokStr: String;
APos : Integer;
AToken : String;
begin
ATokStr := AString;
ATokens.Clear;
APos := Pos(ADelim, ATokStr);
while (APos > 0) do
begin
AToken := Copy(ATokStr, 1, APos - 1);
Delete(ATokStr, 1, APos);
ATokens.Add(AToken);
APos := Pos(ADelim, ATokStr);
end;
if (Length(ATokStr) > 0) then
ATokens.Add(ATokStr);
end;
function StrToPoint(const AStr: String): TPoint;
var
Idx : Integer;
AXStr, AYStr: String;
AX, AY : Integer;
begin
Idx := Pos(',', AStr);
if (Idx > 0) then
begin
AXStr := Copy(AStr, 1, Idx - 1);
AYStr := Copy(AStr, Idx + 1, Length(AStr));
try
AX := StrToInt(AXStr);
AY := StrToInt(AYStr);
Result := Point(AX, AY);
except
raise EConvertError.Create('Invalid Point string');
end;
end
else
begin
raise EConvertError.Create('Invalid Point string');
end;
end;
end.
|
unit uLog;
interface
uses
DataSnap.DBClient, DB;
type
TTipoLog = (tlInfo, tlAviso, tlErro);
TTipoLogHelper = record helper for TTipoLog
function AsByte: Byte;
end;
ILog = Interface(IInterface)
procedure AdicionarMensagem(const Tipo: TTipoLog; const Mensagem: string);
function PegarDataSetLog: TDataSet;
end;
TLog = class(TInterfacedObject, ILog)
private
FcdsLog: TClientDataSet;
FTipoMensagem: TField;
FMensagem: TField;
procedure ConfigurarCdsLog;
public
constructor Create;
destructor Destroy; override;
procedure AdicionarMensagem(const Tipo: TTipoLog; const Mensagem: string);
function PegarDataSetLog: TDataSet;
end;
implementation
constructor TLog.Create;
begin
FcdsLog := TClientDataSet.Create(nil);
ConfigurarCdsLog;
end;
destructor TLog.Destroy;
begin
FcdsLog.Close;
FcdsLog.Free;
inherited;
end;
function TLog.PegarDataSetLog: TDataSet;
begin
Result := FcdsLog;
end;
procedure TLog.ConfigurarCdsLog;
const
OBRIGATORIO = true;
SEM_TAMANHO_DEFINIDO = 0;
CAMPO_TAMANHO_STRING = 500;
begin
FcdsLog.FieldDefs.Add('id', ftAutoInc, SEM_TAMANHO_DEFINIDO, not OBRIGATORIO);
FcdsLog.FieldDefs.Add('TipoMensagem', ftInteger, SEM_TAMANHO_DEFINIDO, OBRIGATORIO);
FcdsLog.FieldDefs.Add('Mensagem', ftString, CAMPO_TAMANHO_STRING, OBRIGATORIO);
FcdsLog.CreateDataSet;
FTipoMensagem := FcdsLog.FieldByName('TipoMensagem');
FMensagem := FcdsLog.FieldByName('Mensagem');
end;
procedure TLog.AdicionarMensagem(const Tipo: TTipoLog; const Mensagem: string);
begin
FcdsLog.Insert;
FTipoMensagem.AsInteger := Tipo.AsByte;
FMensagem.AsString := Mensagem;
FcdsLog.Post;
end;
{ TTipoLogHelper }
function TTipoLogHelper.AsByte: Byte;
begin
result := ord(Self);
end;
end.
|
unit Search;
{$include kcontrols.inc}
interface
uses
{$IFDEF FPC}
LCLType, LCLIntf, LResources,
{$ELSE}
Windows, Messages,
{$ENDIF}
SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, KEditCommon;
type
TSearchForm = class(TForm)
CBTextToFind: TComboBox;
GBOptions: TGroupBox;
LBFindText: TLabel;
BUFind: TButton;
BUCancel: TButton;
CBMatchCase: TCheckBox;
CBHexaSearch: TCheckBox;
GBDirection: TGroupBox;
RBForward: TRadioButton;
RBBackward: TRadioButton;
GBScope: TGroupBox;
RBGlobal: TRadioButton;
RBSelectedOnly: TRadioButton;
GBOrigin: TGroupBox;
RBFromCursor: TRadioButton;
RBEntireScope: TRadioButton;
procedure BUFindClick(Sender: TObject);
procedure CBTextToFindChange(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure GetData(var Data: TKEditSearchData); virtual;
procedure SetData(const Data: TKEditSearchData; SelAvail: Boolean); virtual;
end;
var
SearchForm: TSearchForm;
function TrimToSize(const Text: string; Size: Integer): string;
implementation
{$IFDEF FPC}
{$R *.lfm}
{$ELSE}
{$R *.dfm}
{$ENDIF}
uses Options;
function TrimToSize(const Text: string; Size: Integer): string;
begin
Result := Text;
if (Size > 0) and (Length(Result) > Size) then
begin
SetLength(Result, Size);
Result := Format('%s...', [Result]);
end;
end;
procedure TSearchForm.BUFindClick(Sender: TObject);
begin
if CBTextToFind.Items.IndexOf(CBTextToFind.Text) < 0 then
CBTextToFind.Items.Insert(0, CBTextToFind.Text);
end;
procedure TSearchForm.CBTextToFindChange(Sender: TObject);
begin
BUFind.Enabled := CBTextToFind.Text <> '';
end;
procedure TSearchForm.FormShow(Sender: TObject);
begin
CBTextToFindChange(Sender);
end;
procedure TSearchForm.GetData(var Data: TKEditSearchData);
begin
with Data do
begin
Options := [];
if CBMatchCase.Checked then Include(Options, esoMatchCase);
if CBHexaSearch.Checked then Include(Options, esoTreatAsDigits);
if RBBackward.Checked then Include(Options, esoBackwards);
if RBEntireScope.Checked then Include(Options, esoEntireScope);
if RBSelectedOnly.Checked then Include(Options, esoSelectedOnly);
TextToFind := CBTextToFind.Text;
end;
end;
procedure TSearchForm.SetData(const Data: TKEditSearchData; SelAvail: Boolean);
begin
ActiveControl := CBTextToFind;
with Data do
begin
CBMatchCase.Checked := esoMatchCase in Options;
CBHexaSearch.Checked := esoTreatAsDigits in Options;
if esoBackwards in Options then
RBBackward.Checked := True
else
RBForward.Checked := True;
if esoEntireScope in Options then
RBEntireScope.Checked := True
else
RBFromCursor.Checked := True;
if SelAvail then
begin
RBSelectedOnly.Enabled := True;
if esoSelectedOnly in Options then
RBSelectedOnly.Checked := True
else
RBGlobal.Checked := True
end else
begin
RBGlobal.Checked := True;
RBSelectedOnly.Enabled := False;
end;
end;
end;
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.cwvectors.evector4;
{$ifdef fpc} {$mode delphiunicode} {$endif}
{$M+}
interface
uses
cwTest
, cwVectors
;
type
TTestVector4Extended = class(TTestCase)
published
/// <summary>
/// Tests addition in which the left term is a vector and the right
/// term is an array of float. (Returns result as a vector)
/// </summary>
procedure AddVA;
/// <summary>
/// Tests addition in which the left term is an array of float and the
/// right term is a vector. (Returns result as a vector)
/// </summary>
procedure AddAV;
/// <summary>
/// Tests addition in which the left term is a vector and the right
/// term is an array of float. (Returns result as a vector)
/// </summary>
procedure SubtractVA;
/// <summary>
/// Tests addition in which the left term is an array of float and the
/// right term is a vector. (Returns result as a vector)
/// </summary>
procedure SubtractAV;
/// <summary>
/// Tests addition in which the left term is a vector and the right
/// term is an array of float. (Returns result as a vector)
/// </summary>
procedure MultiplyVA;
/// <summary>
/// Tests addition in which the left term is an array of float and the
/// right term is a vector. (Returns result as a vector)
/// </summary>
procedure MultiplyAV;
/// <summary>
/// Tests addition in which the left term is a vector and the right
/// term is an array of float. (Returns result as a vector)
/// </summary>
procedure DivideVA;
/// <summary>
/// Tests addition in which the left term is an array of float and the
/// right term is a vector. (Returns result as a vector)
/// </summary>
procedure DivideAV;
/// <summary>
/// Tests the assignment of an array of floats to a vector.
/// </summary>
procedure ArrayAssign;
/// <summary>
/// Test the addition of one TVector4 to another TVector4
/// </summary>
procedure Add;
/// <summary>
/// Test the addition of a float to a TVector4 (element-wise)
/// </summary>
procedure AddF;
/// <summary>
/// Test the subtraction of a TVector4 from another TVector4.
/// </summary>
procedure Subtract;
/// <summary>
/// Test the subtraction of a float from a TVector4 (element-wise).
/// </summary>
procedure SubtractF;
/// <summary>
/// Test the multiplication of a TVector4 with another TVector4.
/// (Hadamard, element-wise)
/// </summary>
procedure Multiply;
/// <summary>
/// Test the multiplication of a float with a TVector4
/// (element-wise, scale)
/// </summary>
procedure MultiplyF;
/// <summary>
/// Test the division of a TVector4 by another TVector4.
/// (element-wise)
/// </summary>
procedure Divide;
/// <summary>
/// Test the division of a TVector4 by a float.
/// (element-wise)
/// </summary>
procedure DivideF;
/// <summary>
/// Test the implicit assignment of a TVector3 to a TVector4 where the
/// fourth element of the TVector4 is set to 1.0
/// </summary>
procedure ImplicitV3V4;
/// <summary>
/// Test the explicit assignment of a TVector3 to a TVector4 where the
/// fourth element of the TVector4 is set to 1.0
/// </summary>
procedure ExplicitV3V4;
/// <summary>
/// Test the implicit assignment of a TVector2 to a TVector4 where the
/// third element of the TVector4 is set to 0.0 and the fourth is set to
/// 1.0.
/// </summary>
procedure ImplicitV2V4;
/// <summary>
/// Test the explicit assignment of a TVector2 to a TVector4 where the
/// third element of the TVector4 is set to 0.0 and the fourth is set
/// to 1.0.
/// </summary>
procedure ExplicitV2V4;
/// <summary>
/// Test the implicit assignment of a TVector4 to a TVector3 where the
/// fourth element of the TVector4 is dropped.
/// </summary>
procedure ImplicitV4V3;
/// <summary>
/// Test the explicit assignment of a TVector4 to a TVector3 where the
/// fourth element of the TVector4 is dropped.
/// </summary>
procedure ExplicitV4V3;
/// <summary>
/// Test the implicit assignment of a TVector4 to a TVector2 where the
/// third and fourth elements ot the TVector4 are dropped.
/// </summary>
procedure ImplicitV4V2;
/// <summary>
/// Test the explicit assignment of a TVector4 to a TVector2 where the
/// third and fourth elements of the TVector4 are dropped.
/// </summary>
procedure ExplicitV4V2;
/// <summary>
/// Test the creation of a TVector4 from four discreet float parameters.
/// </summary>
procedure CreateXYZW;
/// <summary>
/// Test the dot product calculation of a TVector4 with another
/// TVector4.
/// </summary>
procedure dot;
/// <summary>
/// Test the normalized calculation of a TVector4.
/// </summary>
procedure normalized;
/// <summary>
/// Test the magnitude calculation of a TVector4.
/// </summary>
procedure magnitude;
end;
implementation
uses
cwTest.Standard
;
procedure TTestVector4Extended.Add;
var
V1, V2, V3: eVector4;
begin
// Arrange:
V1 := eVector4.Create( 2, 4, 6, 8 );
V2 := eVector4.Create( 3, 6, 9, 12 );
// Act:
V3 := V1 + V2;
// Assert:
TTest.IsTrue((V3.X > 4.99) and (V3.X < 5.01));
TTest.IsTrue((V3.Y > 9.99) and (V3.Y < 10.01));
TTest.IsTrue((V3.Z > 14.99) and (V3.Z < 15.01));
TTest.IsTrue((V3.W > 19.99) and (V3.W < 20.01));
end;
procedure TTestVector4Extended.AddAV;
var
V: eVector4;
R: eVector4;
begin
// Arrange:
V := [ 1, 2, 3, 4 ]; // FPC Bug [0035061] https://bugs.freepascal.org/view.php?id=35061 RESOLVED
// Act:
R := [ 4, 3, 2, 1 ];
R := R + V; // FPC Bug [0035061] https://bugs.freepascal.org/view.php?id=35061 RESOLVED
// Assert:
TTest.IsTrue( ((R.X > 4.99 ) and (R.X < 5.01)) );
TTest.IsTrue( ((R.Y > 4.99 ) and (R.Y < 5.01)) );
TTest.IsTrue( ((R.Z > 4.99 ) and (R.Y < 5.01)) );
TTest.IsTrue( ((R.W > 4.99 ) and (R.W < 5.01)) );
end;
procedure TTestVector4Extended.AddF;
var
V1, V2: eVector4;
begin
// Arrange:
V1 := eVector4.Create( 2, 4, 6, 8 );
// Act:
V2 := V1 + 3;
// Assert:
TTest.IsTrue((V2.X > 4.99) and (V2.X < 5.01));
TTest.IsTrue((V2.Y > 6.99) and (V2.Y < 7.01));
TTest.IsTrue((V2.Z > 8.99) and (V2.Z < 9.01));
TTest.IsTrue((V2.W > 10.99) and (V2.W < 11.01));
end;
procedure TTestVector4Extended.AddVA;
var
V: eVector4;
R: eVector4;
begin
// Arrange:
V := [ 1, 2, 3, 4 ]; // FPC Bug [0035061] https://bugs.freepascal.org/view.php?id=35061 RESOLVED
// Act:
R := [ 4, 3, 2, 1 ];
R := V + R; // FPC Bug [0035061] https://bugs.freepascal.org/view.php?id=35061 RESOLVED
// Assert:
TTest.IsTrue( ((R.X > 4.99 ) and (R.X < 5.01)) );
TTest.IsTrue( ((R.Y > 4.99 ) and (R.Y < 5.01)) );
TTest.IsTrue( ((R.Z > 4.99 ) and (R.Y < 5.01)) );
TTest.IsTrue( ((R.W > 4.99 ) and (R.W < 5.01)) );
end;
procedure TTestVector4Extended.ArrayAssign;
var
V: eVector4;
begin
// Arrange:
// Act:
V := [1,2,3,4]; // FPC Bug [0035061] https://bugs.freepascal.org/view.php?id=35061 RESOLVED
// Assert:
TTest.IsTrue( ((V.X > 0.99 ) and (V.X < 1.01)) );
TTest.IsTrue( ((V.Y > 1.99 ) and (V.Y < 2.01)) );
TTest.IsTrue( ((V.Z > 2.99 ) and (V.Y < 3.01)) );
TTest.IsTrue( ((V.W > 3.99 ) and (V.W < 4.01)) );
end;
procedure TTestVector4Extended.CreateXYZW;
var
V1: eVector4;
begin
// Arrange:
// Act:
V1 := eVector4.Create( 2, 4, 6, 8 );
// Assert:
TTest.IsTrue((V1.X > 1.99) and (V1.X < 2.01));
TTest.IsTrue((V1.Y > 3.99) and (V1.Y < 4.01));
TTest.IsTrue((V1.Z > 5.99) and (V1.Z < 6.01));
TTest.IsTrue((V1.W > 7.99) and (V1.W < 8.01));
end;
procedure TTestVector4Extended.Divide;
var
V1, V2, V3: eVector4;
begin
// Arrange:
V1 := eVector4.Create( 3, 6, 9, 12 );
V2 := eVector4.Create( 2, 4, 6, 8 );
// Act:
V3 := V1 / V2;
// Assert:
TTest.IsTrue((V3.X > 1.49) and (V3.X < 1.51));
TTest.IsTrue((V3.Y > 1.49) and (V3.Y < 1.51));
TTest.IsTrue((V3.Z > 1.49) and (V3.Z < 1.51));
TTest.IsTrue((V3.W > 1.49) and (V3.W < 1.51));
end;
procedure TTestVector4Extended.DivideAV;
var
V: eVector4;
R: eVector4;
begin
// Arrange:
V := [ 1, 2, 2, 1 ]; // FPC Bug [0035061] https://bugs.freepascal.org/view.php?id=35061 RESOLVED
// Act:
R := [ 4, 3, 3, 4 ];
R := R / V; // FPC Bug [0035061] https://bugs.freepascal.org/view.php?id=35061 RESOLVED
// Assert:
TTest.IsTrue( ((R.X > 3.99 ) and (R.X < 4.01)) );
TTest.IsTrue( ((R.Y > 1.49 ) and (R.Y < 1.51)) );
TTest.IsTrue( ((R.Z > 1.49 ) and (R.Y < 1.51)) );
TTest.IsTrue( ((R.W > 3.99 ) and (R.W < 4.01)) );
end;
procedure TTestVector4Extended.DivideF;
var
V1, V2: eVector4;
begin
// Arrange:
V1 := eVector4.Create( 2, 4, 6, 8 );
// Act:
V2 := V1 / 2;
// Assert:
TTest.IsTrue((V2.X > 0.99) and (V2.X < 1.01));
TTest.IsTrue((V2.Y > 1.99) and (V2.Y < 2.01));
TTest.IsTrue((V2.Z > 2.99) and (V2.Z < 3.01));
TTest.IsTrue((V2.W > 3.99) and (V2.W < 4.01));
end;
procedure TTestVector4Extended.DivideVA;
var
V: eVector4;
R: eVector4;
begin
// Arrange:
V := [ 4, 3, 3, 4 ]; // FPC Bug [0035061] https://bugs.freepascal.org/view.php?id=35061 RESOLVED
// Act:
R := [ 1, 2, 2, 1 ];
R := V / R; // FPC Bug [0035061] https://bugs.freepascal.org/view.php?id=35061 RESOLVED
// Assert:
TTest.IsTrue( ((R.X > 3.99 ) and (R.X < 4.01)) );
TTest.IsTrue( ((R.Y > 1.49 ) and (R.Y < 1.51)) );
TTest.IsTrue( ((R.Z > 1.49 ) and (R.Y < 1.51)) );
TTest.IsTrue( ((R.W > 3.99 ) and (R.W < 4.01)) );
end;
procedure TTestVector4Extended.dot;
var
V1, V2: eVector4;
F: extended;
begin
// Arrange:
V1 := eVector4.Create(5,6,3,8);
V2 := eVector4.Create(2,3,5,4);
// Act:
F := V1.dot(V2);
// Assert:
TTest.IsTrue( ((F > 74.99 ) and (F < 75.01)) );
end;
procedure TTestVector4Extended.ExplicitV2V4;
var
V2: eVector2;
V4: eVector4;
begin
// Arrange:
V2 := eVector2.Create( 2, 8 );
// Act:
V4 := eVector4( V2 );
// Assert:
TTest.IsTrue( ((V4.X > 1.99 ) and (V4.X < 2.01)) );
TTest.IsTrue( ((V4.Y > 7.99 ) and (V4.Y < 8.01)) );
TTest.IsTrue( ((V4.Z > -0.01 ) and (V4.Z < 0.01)) );
TTest.IsTrue( ((V4.W > 0.99 ) and (V4.W < 1.01)) );
end;
procedure TTestVector4Extended.ExplicitV3V4;
var
V3: eVector3;
V4: eVector4;
begin
// Arrange:
V3 := eVector3.Create( 2, 4, 6 );
// Act:
V4 := eVector4( V3 );
// Assert:
TTest.IsTrue( ((V4.X > 1.99 ) and (V4.X < 2.01)) );
TTest.IsTrue( ((V4.Y > 3.99 ) and (V4.Y < 4.01)) );
TTest.IsTrue( ((V4.Z > 5.99 ) and (V4.Z < 6.01)) );
TTest.IsTrue( ((V4.W > 0.99 ) and (V4.W < 1.01)) );
end;
procedure TTestVector4Extended.ExplicitV4V2;
var
V4: eVector4;
V2: eVector2;
begin
// Arrange:
V4 := eVector4.Create( 2, 4, 6, 8 );
// Act:
V2 := eVector2( V4 );
// Assert:
TTest.IsTrue( ((V2.X > 1.99 ) and (V2.X < 2.01)) );
TTest.IsTrue( ((V2.Y > 3.99 ) and (V2.Y < 4.01)) );
end;
procedure TTestVector4Extended.ExplicitV4V3;
var
V4: eVector4;
V3: eVector3;
begin
// Arrange:
V4 := eVector4.Create( 2, 4, 6, 8 );
// Act:
V3 := eVector3( V4 );
// Assert:
TTest.IsTrue( ((V3.X > 1.99 ) and (V3.X < 2.01)) );
TTest.IsTrue( ((V3.Y > 3.99 ) and (V3.Y < 4.01)) );
TTest.IsTrue( ((V3.Z > 5.99 ) and (V3.Z < 6.01)) );
end;
procedure TTestVector4Extended.ImplicitV2V4;
var
V2: eVector2;
V4: eVector4;
begin
// Arrange:
V2 := eVector2.Create( 2, 8 );
// Act:
V4 := V2;
// Assert:
TTest.IsTrue( ((V4.X > 1.99 ) and (V4.X < 2.01)) );
TTest.IsTrue( ((V4.Y > 7.99 ) and (V4.Y < 8.01)) );
TTest.IsTrue( ((V4.Z > -0.01 ) and (V4.Z < 0.01)) );
TTest.IsTrue( ((V4.W > 0.99 ) and (V4.W < 1.01)) );
end;
procedure TTestVector4Extended.ImplicitV3V4;
var
V3: eVector3;
V4: eVector4;
begin
// Arrange:
V3 := eVector3.Create( 2, 4, 6 );
// Act:
V4 := V3;
// Assert:
TTest.IsTrue( ((V4.X > 1.99 ) and (V4.X < 2.01)) );
TTest.IsTrue( ((V4.Y > 3.99 ) and (V4.Y < 4.01)) );
TTest.IsTrue( ((V4.Z > 5.99 ) and (V4.Z < 6.01)) );
TTest.IsTrue( ((V4.W > 0.99 ) and (V4.W < 1.01)) );
end;
procedure TTestVector4Extended.ImplicitV4V2;
var
V4: eVector4;
V2: eVector2;
begin
// Arrange:
V4 := eVector4.Create( 2, 4, 6, 8 );
// Act:
V2 := V4;
// Assert:
TTest.IsTrue( ((V2.X > 1.99 ) and (V2.X < 2.01)) );
TTest.IsTrue( ((V2.Y > 3.99 ) and (V2.Y < 4.01)) );
end;
procedure TTestVector4Extended.ImplicitV4V3;
var
V4: eVector4;
V3: eVector3;
begin
// Arrange:
V4 := eVector4.Create( 2, 4, 6, 8 );
// Act:
V3 := V4;
// Assert:
TTest.IsTrue( ((V3.X > 1.99 ) and (V3.X < 2.01)) );
TTest.IsTrue( ((V3.Y > 3.99 ) and (V3.Y < 4.01)) );
TTest.IsTrue( ((V3.Z > 5.99 ) and (V3.Z < 6.01)) );
end;
procedure TTestVector4Extended.magnitude;
var
V1: eVector4;
F: single;
begin
// Arrange:
V1 := eVector4.Create( 2, 4, 6, 9 );
// Act:
F := V1.magnitude; // 11.704699910
// Assert:
TTest.IsTrue( (F > 11.699 ) and (F < 11.705) );
end;
procedure TTestVector4Extended.Multiply;
var
V1, V2, V3: eVector4;
begin
// Arrange:
V1 := eVector4.Create( 2, 4, 6, 8 );
V2 := eVector4.Create( 3, 6, 9, 12 );
// Act:
V3 := V1 * V2;
// Assert:
TTest.IsTrue((V3.X > 5.99) and (V3.X < 6.01));
TTest.IsTrue((V3.Y > 23.99) and (V3.Y < 24.01));
TTest.IsTrue((V3.Z > 53.99) and (V3.Z < 54.01));
TTest.IsTrue((V3.W > 95.99) and (V3.W < 96.01));
end;
procedure TTestVector4Extended.MultiplyAV;
var
V: eVector4;
R: eVector4;
begin
// Arrange:
V := [ 1, 2, 2, 1 ]; // FPC Bug [0035061] https://bugs.freepascal.org/view.php?id=35061 RESOLVED
// Act:
R := [ 4, 3, 3, 4 ];
R := R * V; // FPC Bug [0035061] https://bugs.freepascal.org/view.php?id=35061 RESOLVED
// Assert:
TTest.IsTrue( ((R.X > 3.99 ) and (R.X < 4.01)) );
TTest.IsTrue( ((R.Y > 5.99 ) and (R.Y < 6.01)) );
TTest.IsTrue( ((R.Z > 5.99 ) and (R.Y < 6.01)) );
TTest.IsTrue( ((R.W > 3.99 ) and (R.W < 4.01)) );
end;
procedure TTestVector4Extended.MultiplyF;
var
V1, V2: eVector4;
begin
// Arrange:
V1 := eVector4.Create( 2, 4, 6, 8 );
// Act:
V2 := V1 * 3;
// Assert:
TTest.IsTrue((V2.X > 5.99) and (V2.X < 6.01));
TTest.IsTrue((V2.Y > 11.99) and (V2.Y < 12.01));
TTest.IsTrue((V2.Z > 17.99) and (V2.Z < 18.01));
TTest.IsTrue((V2.W > 23.99) and (V2.W < 24.01));
end;
procedure TTestVector4Extended.MultiplyVA;
var
V: eVector4;
R: eVector4;
begin
// Arrange:
V := [ 1, 2, 2, 1 ]; // FPC Bug [0035061] https://bugs.freepascal.org/view.php?id=35061 RESOLVED
// Act:
R := [ 4, 3, 3, 4 ];
R := V * R; // FPC Bug [0035061] https://bugs.freepascal.org/view.php?id=35061 RESOLVED
// Assert:
TTest.IsTrue( ((R.X > 3.99 ) and (R.X < 4.01)) );
TTest.IsTrue( ((R.Y > 5.99 ) and (R.Y < 6.01)) );
TTest.IsTrue( ((R.Z > 5.99 ) and (R.Y < 6.01)) );
TTest.IsTrue( ((R.W > 3.99 ) and (R.W < 4.01)) );
end;
procedure TTestVector4Extended.normalized;
var
V1, V2: eVector4;
begin
// Arrange:
V1 := eVector4.Create( 2, 4, 6, 9 );
// Act:
V2 := V1.normalized; //- Magnitude = // 11.704699910
// Assert:
TTest.IsTrue((V2.X > 0.1707) and (V2.X < 0.1709));
TTest.IsTrue((V2.Y > 0.3416) and (V2.Y < 0.3418));
TTest.IsTrue((V2.Z > 0.5125) and (V2.Z < 0.5127));
TTest.IsTrue((V2.W > 0.7688) and (V2.W < 0.7690));
end;
procedure TTestVector4Extended.Subtract;
var
V1, V2, V3: eVector4;
begin
// Arrange:
V1 := eVector4.Create( 3, 6, 9, 12 );
V2 := eVector4.Create( 2, 4, 6, 8 );
// Act:
V3 := V1 - V2;
// Assert:
TTest.IsTrue((V3.X > 0.99) and (V3.X < 1.01));
TTest.IsTrue((V3.Y > 1.99) and (V3.Y < 2.01));
TTest.IsTrue((V3.Z > 2.99) and (V3.Z < 3.01));
TTest.IsTrue((V3.W > 3.99) and (V3.W < 4.01));
end;
procedure TTestVector4Extended.SubtractAV;
var
V: eVector4;
R: eVector4;
begin
// Arrange:
V := [ 1, 2, 2, 1 ]; // FPC Bug [0035061] https://bugs.freepascal.org/view.php?id=35061 RESOLVED
// Act:
R := [ 4, 3, 3, 4 ];
R := R - V; // FPC Bug [0035061] https://bugs.freepascal.org/view.php?id=35061 RESOLVED
// Assert:
TTest.IsTrue( ((R.X > 2.99 ) and (R.X < 3.01)) );
TTest.IsTrue( ((R.Y > 0.99 ) and (R.Y < 1.01)) );
TTest.IsTrue( ((R.Z > 0.99 ) and (R.Y < 1.01)) );
TTest.IsTrue( ((R.W > 2.99 ) and (R.W < 3.01)) );
end;
procedure TTestVector4Extended.SubtractF;
var
V1, V2: eVector4;
begin
// Arrange:
V1 := eVector4.Create( 2, 4, 6, 8 );
// Act:
V2 := V1 - 3;
// Assert:
TTest.IsTrue((V2.X > -1.01) and (V2.X < -0.99));
TTest.IsTrue((V2.Y > 0.99) and (V2.Y < 1.01));
TTest.IsTrue((V2.Z > 2.99) and (V2.Z < 3.01));
TTest.IsTrue((V2.W > 4.99) and (V2.W < 5.01));
end;
procedure TTestVector4Extended.SubtractVA;
var
V: eVector4;
R: eVector4;
begin
// Arrange:
V := [ 4, 3, 3, 4 ]; // FPC Bug [0035061] https://bugs.freepascal.org/view.php?id=35061 RESOLVED
// Act:
R := [ 1, 2, 2, 1 ];
R := V - R; // FPC Bug [0035061] https://bugs.freepascal.org/view.php?id=35061 RESOLVED
// Assert:
TTest.IsTrue( ((R.X > 2.99 ) and (R.X < 3.01)) );
TTest.IsTrue( ((R.Y > 0.99 ) and (R.Y < 1.01)) );
TTest.IsTrue( ((R.Z > 0.99 ) and (R.Y < 1.01)) );
TTest.IsTrue( ((R.W > 2.99 ) and (R.W < 3.01)) );
end;
initialization
TestSuite.RegisterTestCase(TTestVector4Extended);
end.
|
unit Account;
interface
type
TAccount = class
private
FCurrency: string;
FNumber: string;
FBalance: Currency;
public
constructor Create(ANumber, Acurrency: string);
procedure Withdraw(AAmount: Currency);
procedure Deposit(AAmount: Currency);
property Number: string read FNumber write FNumber;
property Currency: string read FCurrency write FCurrency;
property Balance: Currency read FBalance;
end;
implementation
{ TAccount }
constructor TAccount.Create(ANumber, ACurrency: string);
begin
FNumber := ANumber;
FCurrency := ACurrency;
end;
procedure TAccount.Deposit(AAmount: Currency);
begin
FBalance := FBalance + AAmount;
end;
procedure TAccount.Withdraw(AAmount: Currency);
begin
FBalance := FBalance - AAmount;
end;
end.
|
unit LinePainter;
interface
uses DatosGrafico, GR32;
type
TLinePainter = class
private
FDatos: TDatosGrafico;
FColor: TColor32;
public
procedure Paint(const Bitmap: TBitmap32; const iFrom, iTo: integer);
property Datos: TDatosGrafico read FDatos write FDatos;
property Color: TColor32 read FColor write FColor;
end;
implementation
uses Tipos, Types;
{ TLinePainter }
procedure TLinePainter.Paint(const Bitmap: TBitmap32; const iFrom,
iTo: integer);
var auxTo, i, num: integer;
lastX, lastY: integer;
lastConCambio: boolean;
begin
num := Datos.DataCount - 1;
if num > 0 then begin
auxTo := iTo;
if auxTo < num then
inc(auxTo);
if Datos.IsCambio[iFrom] then begin
lastX := Datos.XTransformados[iFrom];
lastY := Datos.YTransformados[iFrom];
lastConCambio := true;
end
else
lastConCambio := false;
i := iFrom + 1;
while i <= auxTo do begin
if Datos.IsCambio[i] then begin
if lastConCambio then
Bitmap.LineAS(lastX, lastY, Datos.XTransformados[i], Datos.YTransformados[i], FColor, true)
else
lastConCambio := true;
lastX := Datos.XTransformados[i];
lastY := Datos.YTransformados[i];
end
else begin
lastConCambio := false;
end;
inc(i);
end;
end;
end;
end.
|
unit HelperUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, ComCtrls, ShellApi, psAPI, WinInet, Tlhelp32, registry,
shlobj, axCtrls, ActiveX, ImageHlp, Mapi, Winsock, TypInfo, Clipbrd, jpeg;
type
TTypeLib=class
Win32, FileName, Name :string;
GUID :TGUID;
end;
TFindWindowRec=record
ModuleToFind :string;
FoundHWnd :hwnd;
end;
PRegistryEntryStruct=^TRegistryEntryStruct;
TRegistryEntryStruct=record
Name,Server,TypName,DisplayName,Info:string;
end;
FLASHWINFO = record
cbSize: UINT;
hWnd: HWND;
dwFlags: DWORD;
uCount: UINT;
dwTimeOut: DWORD;
end;
TFlashWInfo = FLASHWINFO;
PComPort=^TComPort;
TComPort = record
ID:integer;
Name:string;
Info:Pointer;
end;
TComPorts=array of TComport;
PHICON = ^HICON;
PIMAGE_NT_HEADERS = ^IMAGE_NT_HEADERS;
PIMAGE_EXPORT_DIRECTORY = ^IMAGE_EXPORT_DIRECTORY;
TSearchEvent = procedure(var FileName :string);
TSearchInFileEvent = function (var AFile :string) :integer of object;stdcall;
TBorder = (bsNone, bsDialog, bsSingle, bsSizeable, bsSizeToolWindow, bsToolWindow);
TCliping=(clChild,clSiblings);
TStyle=(stNormal,stStayOnTop);
TPoints=array of TPoint;
TDllRegisterServer = function: HResult; stdcall;
procedure FindFilesEx(FilesList: TStrings; StartDir, FileMask: string);
procedure FindFiles(FilesList: TStrings; StartDir, FileMask: string);
function GetCPUSpeed: Double;
function GetCPUVendor: string;
function GetCurrentUserName: string;
function GetMemory :string;
procedure GetOSVersion(var APlatform: string ; var AMajorVersion,AMinorVersion,ABuild: DWORD);
function GetProcessMemorySize(_sProcessName: string; var _nMemSize: Cardinal): Boolean;
function IsAdmin: Boolean;
procedure ListDLLExports(const FileName: string; List: TStrings; complete:boolean=false);
function GetClassName(Handle: THandle): String;
function IsFileTypeRegistered(ProgId :string): boolean;
function RegisterFileTypeCommand(fileExtension, menuItemText, target: string) : boolean;
function UnRegisterFileTypeCommand(fileExtension, menuItemText: string) : boolean;
procedure ImageLoad(AFile :string; Image :TImage);
procedure ListFileDir(Path: string; Proc :TSearchInFileEvent; Filter :string='*.*');overload;
procedure ListFileDir(Path: string; FileList: TStrings; Filter :string='*.*'); overload;
procedure ListFileInDir(const AStartDir : string; AList :TStrings; Filter :string = '*.*'; ARecurse :boolean = true);
function BrowseForFolder(var Foldr: string; Title:string): Boolean;
function GetFileNameFromOLEClass(const OLEClassName: string): string;
function GetWin32TypeLibList(Lines: TStrings): Boolean;
function GetSpecialDir(v:string):string;
function GetSpecialFolderPath(CSIDLFolder: Integer): string;
procedure Bmp2Jpeg(const BmpFileName, JpgFileName: string); // helloacm.com
procedure Jpeg2Bmp(const BmpFileName, JpgFileName: string); // helloacm.com
function GetCapture(Image :TImage; fDlg :TForm=nil; Jpg :boolean = false):string;
function SearchTree(const AStartDir, AFileToFind : string; ARecurse :boolean = true) : string;
procedure ExtractResourceIDToFile(Instance:THandle; ResID:Integer; ResType, FileName:String; Overriden :boolean = true);
procedure ExtractResourceNameToFile(Instance:THandle; ResName, ResType, FileName:String; Overriden :boolean = true);
procedure ExtractResource(Module :HMODULE; ResName, ResType, ResFile :string);
procedure LoadResourceName(instance :HMODULe; ResName, ResFile, ResType :string; ALines :TStrings);
procedure GetPropertyList(value :TObject; Results :TStrings);
procedure DUI2PIX(FWindow :hwnd; var P :TPoint);
procedure PIX2DUI(FWindow :hwnd; var P :TPoint) ;
procedure Win2DUI(Dlg :integer; var lx, ly, cx, cy :integer);
procedure DUI2Win(Dlg :integer; var lx, ly, cx, cy :integer);
function twips2pix(v :integer):integer;
function pix2twips(v :integer):integer;
function CurrentProcessMemory: Cardinal;
function ReplaceString(s, swhat, swith :string; all :boolean=true):string;
function ClassExists(v :string):boolean;
function tally(s,v :string):integer;
function IsWindowOpen(v:string): Boolean;
function IsWindowHandleOpen(v:string): hwnd;
function NormalizeName(value :string) :string;
function GetFilterByIndex(id:integer;filter:string):string;
function GetWindowsFromThread(ti:cardinal;var L:TStrings):integer;
procedure LoadImage(v:string; img:TImage);
function ExecuteProcess(FileName: string; Visibility: Integer; BitMask: Integer; Synch: Boolean): Longword;
function LastInput: DWord;
procedure EnumExtensions(Lines:TStrings);
function SetGlobalEnvironment(const Name, Value: string; const User: Boolean = True): Boolean;
function FlashWindowEx(var pfwi: FLASHWINFO): BOOL; stdcall;
procedure FlashsWindow(dlg:hwnd;longflash:integer=5);
procedure ExtractIcons(limg:TImage=nil;simg:TImage=nil);
procedure GetAssociatedIcon(FileName: TFilename; PLargeIcon, PSmallIcon: PHICON);
function ComPortAvailable(Port: PChar): Boolean;
function GetOpenComPort(searchfor:integer=30):tcomports;
procedure RegisterFileType(ext: string; exe: string);
function GetSerialPortNames: string;
procedure EnumComPorts(const Ports: TStringList);
function GetUserName: String;
function ComputerName:String;
function SkipBlanks(v:string):string;
const
RT_HTML = MAKEINTRESOURCE(23);
RT_MANIFEST = MAKEINTRESOURCE(24);
SECURITY_NT_AUTHORITY: TSIDIdentifierAuthority = (Value: (0, 0, 0, 0, 0, 5));
SECURITY_BUILTIN_DOMAIN_RID = $00000020;
DOMAIN_ALIAS_RID_ADMINS = $00000220;
FLASHW_STOP = 0;
FLASHW_CAPTION = 1;
FLASHW_TRAY = 2;
FLASHW_ALL = FLASHW_CAPTION or FLASHW_TRAY;
FLASHW_TIMER = 4;
FLASHW_TIMERNOFG = 12;
CSIDL_DESKTOP = $0000; { <desktop> }
CSIDL_INTERNET = $0001; { Internet Explorer (icon on desktop) }
CSIDL_PROGRAMS = $0002; { Start Menu\Programs }
CSIDL_CONTROLS = $0003; { My Computer\Control Panel }
CSIDL_PRINTERS = $0004; { My Computer\Printers }
CSIDL_PERSONAL = $0005; { My Documents. This is equivalent to
CSIDL_MYDOCUMENTS in XP and above }
CSIDL_FAVORITES = $0006; { <user name>\Favorites }
CSIDL_STARTUP = $0007; { Start Menu\Programs\Startup }
CSIDL_RECENT = $0008; { <user name>\Recent }
CSIDL_SENDTO = $0009; { <user name>\SendTo }
CSIDL_BITBUCKET = $000a; { <desktop>\Recycle Bin }
CSIDL_STARTMENU = $000b; { <user name>\Start Menu }
CSIDL_MYDOCUMENTS = $000c; { logical "My Documents" desktop icon }
CSIDL_MYMUSIC = $000d; { "My Music" folder }
CSIDL_MYVIDEO = $000e; { "My Video" folder }
CSIDL_DESKTOPDIRECTORY = $0010; { <user name>\Desktop }
CSIDL_DRIVES = $0011; { My Computer }
CSIDL_NETWORK = $0012; { Network Neighborhood (My Network Places) }
CSIDL_NETHOOD = $0013; { <user name>\nethood }
CSIDL_FONTS = $0014; { windows\fonts }
CSIDL_TEMPLATES = $0015; { <user name>\appdata\roaming\template folder }
CSIDL_COMMON_STARTMENU = $0016; { All Users\Start Menu }
CSIDL_COMMON_PROGRAMS = $0017; { All Users\Start Menu\Programs }
CSIDL_COMMON_STARTUP = $0018; { All Users\Startup }
CSIDL_COMMON_DESKTOPDIRECTORY = $0019; { All Users\Desktop }
CSIDL_APPDATA = $001a; { <user name>\Application Data }
CSIDL_PRINTHOOD = $001b; { <user name>\PrintHood }
CSIDL_LOCAL_APPDATA = $001c; { <user name>\Local Settings\Application Data
(non roaming) }
CSIDL_ALTSTARTUP = $001d; { non localized startup }
CSIDL_COMMON_ALTSTARTUP= $001e; { non localized common startup }
CSIDL_COMMON_FAVORITES = $001f; { User favourites }
CSIDL_INTERNET_CACHE = $0020; { temporary inter files }
CSIDL_COOKIES = $0021; { <user name>\Local Settings\Application Data\
..\cookies }
CSIDL_HISTORY = $0022; { <user name>\Local Settings\
Application Data\..\history}
CSIDL_COMMON_APPDATA = $0023; { All Users\Application Data }
CSIDL_WINDOWS = $0024; { GetWindowsDirectory() }
CSIDL_SYSTEM = $0025; { GetSystemDirectory() }
CSIDL_PROGRAM_FILES = $0026; { C:\Program Files }
CSIDL_MYPICTURES = $0027; { C:\Program Files\My Pictures }
CSIDL_PROFILE = $0028; { USERPROFILE }
CSIDL_SYSTEMX86 = $0029; { x86 system directory on RISC }
CSIDL_PROGRAM_FILESX86 = $002a; { x86 C:\Program Files on RISC }
CSIDL_PROGRAM_FILES_COMMON = $002b; { C:\Program Files\Common }
CSIDL_PROGRAM_FILES_COMMONX86 = $002c; { x86 C:\Program Files\Common on RISC }
CSIDL_COMMON_TEMPLATES = $002d; { All Users\Templates }
CSIDL_COMMON_DOCUMENTS = $002e; { All Users\Documents }
CSIDL_COMMON_ADMINTOOLS = $002f; { All Users\Start Menu\Programs\
Administrative Tools }
CSIDL_ADMINTOOLS = $0030; { <user name>\Start Menu\Programs\
Administrative Tools }
CSIDL_CONNECTIONS = $0031; { Network and Dial-up Connections }
CSIDL_COMMON_MUSIC = $0035; { All Users\My Music }
CSIDL_COMMON_PICTURES = $0036; { All Users\My Pictures }
CSIDL_COMMON_VIDEO = $0037; { All Users\My Video }
CSIDL_RESOURCES = $0038; { Resource Directory }
CSIDL_RESOURCES_LOCALIZED = $0039; { Localized Resource Directory }
CSIDL_CDBURN_AREA = $003b; { USERPROFILE\Local Settings\
Application Data\Microsoft\CD Burning }
CS_DROPSHADOW = $00020000;
function SHGetFolderPath(hwnd: HWND; csidl: Integer; hToken: THandle; dwFlags: DWORD; pszPath: PChar): HResult; stdcall; external 'shfolder.dll' name 'SHGetFolderPathA';
var
FindWindowRec: TFindWindowRec;
FWInfo: TFlashWInfo;
PLargeIcon, PSmallIcon: phicon;
implementation
function FlashWindowEx; external user32 Name 'FlashWindowEx';
function SkipBlanks(v:string):string;
var
i:integer;
L:TStrings;
begin
result:=v;
if v='' then exit;
L:=TStringList.Create;
L.Text:=stringreplace(v,#32,#10,[rfreplaceall]);
result:='';
for i:=0 to L.Count-1 do
if L[i]<>'' then
result:=trim(result+#32+L[i]);
L.Free
end;
function getUserName: String;
const
UNLEN = 256;
var
BufSize: DWord;
Buffer: array[0..UNLEN] of Char;
begin
BufSize := Length(Buffer);
if Windows.GetUserName(Buffer, BufSize) then
SetString(Result, Buffer, BufSize-1)
else
RaiseLastOSError;
end;
procedure FlashsWindow(dlg:hwnd;longflash:integer=5);
begin
with FWInfo do begin
cbSize := SizeOf(FWInfo);
hWnd := dlg;
dwFlags := FLASHW_ALL;
uCount := longflash;
dwTimeOut := 100;
end;
FlashWindowEx(FWInfo)
end;
procedure LoadImage(v:string; img:TImage);
var
OleGraphic: TOleGraphic;
fs: TFileStream;
begin
if not FileExists(v) then exit;
if img=nil then exit;
OleGraphic:= TOleGraphic.Create;
fs:= TFileStream.Create(v, fmOpenRead or fmSharedenyNone);
try
OleGraphic.LoadFromStream(fs);
img.Picture.Assign(OleGraphic);
finally
fs.Free;
OleGraphic.Free
end;
end;
function EnumThreadWndProc(dlg,lparam :integer):boolean;stdcall;
begin
if lparam>0 then
TStrings(lparam).AddObject(GetClassName(dlg),TObject(Dlg));
result:=true;
end;
function GetWindowsFromThread(ti:cardinal;var L:TStrings):integer;
begin
if ti=0 then ti:=GetCurrentThreadId;
EnumThreadWindows(ti,@EnumThreadWndProc,integer(L));
result:=L.Count;
end;
function GetFilterByIndex(id:integer;filter:string):string;
var
i,x,y :integer;
s :string;
begin
result:=filter;
if id=0 then exit;
if filter='' then begin result:=filter; exit; end; x:=0; y:=0;
for i:=1 to length(filter) do begin
s :=s+filter[i];
if (filter[i]='|') or (i=length(filter)) then begin
inc(x);
if x=2 then begin
inc(y);
if i<length(filter) then s:=copy(s,1,length(s)-1);
if y=id then
if pos('*.*',s)=0 then result:=s else result:='';
x:=0;
s:='';
end;
end;
end;
end;
function NormalizeName(value :string) :string;
var
i :integer;
s :string;
begin
result:=value;
if value='' then exit;
s:='';
for i:=1 to length(value) do begin
if value[i]in ['a'..'z','A'..'Z','0'..'9','-','_'] then s :=s + value[i];
Result:=s;
end;
end;
function EnumWindowsCallBack(Handle: hWnd; var FindWindowRec: TFindWindowRec): BOOL; stdcall;
const
C_FileNameLength = 256;
var
WinFileName: string;
PID, hProcess: DWORD;
Len: Byte;
begin
Result := True;
SetLength(WinFileName, C_FileNameLength);
GetWindowThreadProcessId(Handle, PID);
hProcess := OpenProcess(PROCESS_ALL_ACCESS, False, PID);
Len := GetModuleFileNameEx(hProcess, 0, PChar(WinFileName), C_FileNameLength);
if Len > 0 then
begin
SetLength(WinFileName, Len);
if SameText(WinFileName, FindWindowRec.ModuleToFind) then
begin
Result := False;
FindWindowRec.FoundHWnd := Handle;
end;
end;
end;
function IsWindowOpen(v:string): Boolean;
begin
FindWindowRec.ModuleToFind := v;
FindWindowRec.FoundHWnd := 0;
EnumWindows(@EnumWindowsCallback, integer(@FindWindowRec));
Result := FindWindowRec.FoundHWnd <> 0;
end;
function IsWindowHandleOpen(v:string): hwnd;
begin
FindWindowRec.ModuleToFind := v;
FindWindowRec.FoundHWnd := 0;
EnumWindows(@EnumWindowsCallback, integer(@FindWindowRec));
Result := FindWindowRec.FoundHWnd;
end;
function tally(s,v :string):integer;
label
reload;
begin
result:=0;
if (v='') or (s='') then exit;
if pos(v,s)>0 then begin
reload:
s := copy(s,pos(v,s)+length(v),length(s));
if pos(v,s)>0 then goto reload;
end
end;
function ClassExists(v :string):boolean;
var
cls :TWndClassEx;
begin
cls.cbSize:=Sizeof(cls);
result :=(GetClassInfoEx(0,PChar(v),cls)) or (GetClassInfoEx(hinstance,PChar(v),cls));
end;
function ReplaceString(s, swhat, swith :string; all :boolean=true):string; overload;
var
i,x :integer;
t :string;
begin
result:=s; t:='';
if (s='') or (swhat='') then exit;
for i :=1 to length(s) do begin
x :=pos(s[i],swhat);
if x=0 then
t :=t +s[i];
end;
result:=t;
end;
function twips2pix(v :integer):integer;
begin
result:=v div 15;
end;
function pix2twips(v :integer):integer;
begin
result:=v * 15;
end;
procedure DUI2Win(Dlg:integer; var lx, ly, cx, cy :integer) ;
var
avgWidth, avgHeight :integer;
size :TSize;
tm : TTextMetric;
{Font,} FontOld, SysFont :hfont;
dc :hdc;
LF :TLogFont;
begin
dc := GetDC(Dlg);
SysFont := GetStockObject(DEFAULT_GUI_FONT);
GetObject(SysFont, SizeOf( LF), @LF);
//Font := SendMessage( Dlg, WM_GETFONT, 0,0);
FontOld := SelectObject(dc, SysFont);
GetTextMetrics(dc,tm);
GetTextExtentPoint32(dc,'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',52,size);
avgWidth := ((size.cx div 26)+1) div 2;
avgHeight := tm.tmHeight;
lx := (lx * avgWidth) div 4;
cx := (cx * avgWidth) div 4;
ly := (ly * avgHeight) div 8;
cy := (cy * avgHeight) div 8;
ReleaseDC(Dlg, dc);
DeleteObject(FontOld);
end;
procedure Win2DUI(Dlg :integer; var lx, ly, cx, cy :integer);
var
avgWidth, avgHeight :integer;
size :TSize;
tm : TTextMetric;
{Font,} FontOld, SysFont :hfont;
dc :hdc;
LF :TLogFont;
begin
dc := GetDC(Dlg);
SysFont := GetStockObject(DEFAULT_GUI_FONT);
GetObject(SysFont, SizeOf( LF), @LF);
//Font := SendMessage( Dlg, WM_GETFONT, 0,0);
FontOld := SelectObject(dc, SysFont);
GetTextMetrics(dc,tm);
GetTextExtentPoint32(dc,'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',52,size);
avgWidth := ((size.cx div 26)+1) div 2;
avgHeight := tm.tmHeight;
lx := (4 * lx) div avgWidth;
cx := (4 * cx) div avgWidth;
ly := (8 * ly) div avgHeight;
cy := (8 * cy) div avgHeight;
ReleaseDC(Dlg, dc);
DeleteObject(FontOld);
end;
procedure GetPropertyList(value :TObject; Results :TStrings);
var
plist: PPropList;
i, n: integer;
v :string;
d :double;
begin
if value=nil then exit;
n:= GetPropList (value, plist);
try
for i:= 0 to n-1 do begin
if plist^[i]^.PropType^.Kind<>tkFloat then
v := GetPropValue(value,plist^[i]^.Name)
else begin
d :=GetPropValue(value,plist^[i]^.Name,false);
v := floattostr(d);
end;
Results.AddObject(plist^[i]^.Name+'='+v,TObject(plist^[i]));
//AddLog (plist^[i]^.Name+'='+v);
end;
finally
FreeMem (plist);
end ;
end;
procedure DUI2PIX(FWindow :hwnd; var P :TPoint);
var
Dc: hdc ;
AWidth,AHeight :integer;
Font, FontOld :hfont;
s :string;
TM :TEXTMETRIC;
Sz : SIZE;
begin
Dc := GetDC(FWindow);
Font := SendMessage(FWindow,wm_getfont,0,0);
FontOld := SelectObject(Dc,Font);
s := 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
GetTextMetrics(Dc,TM);
GetTextExtentPoint32(Dc,PChar(s),Length(s),Sz);
SelectObject(DC,FontOld);
ReleaseDc(FWindow,Dc) ;
AWidth := sz.cx div Length(s) ;
AHeight := TM.tmHeight ;
P.x := (P.x*AWidth) div 4;
P.y := (P.y*AHeight) div 8;
end;
procedure PIX2DUI(FWindow :hwnd; var P :TPoint) ;
var
Dc: hdc ;
AWidth,AHeight :integer;
Font, FontOld :hfont;
s :string;
TM :TEXTMETRIC;
Sz : SIZE;
begin
Dc := GetDC(FWindow) ;
Font := SendMessage(FWindow,wm_getfont,0,0);
FontOld := SelectObject(Dc,Font);
s := 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
GetTextMetrics(Dc,TM);
GetTextExtentPoint32(Dc,PChar(s),Length(s),Sz);
SelectObject(DC,FontOld);
ReleaseDc(FWindow,Dc) ;
AWidth := sz.cx div Length(s) ;
AHeight := TM.tmHeight ;
P.x := (P.x*4) div AWidth ;
P.y := (P.y*8) div AHeight ;
end;
function BrowseForFolder(var Foldr: string; Title:string): Boolean;
var
BrowseInfo: TBrowseInfo;
ItemIDList: PItemIDList;
DisplayName: array[0..MAX_PATH] of Char;
begin
Result := False;
CopyMemory(@BrowseInfo.pidlRoot,@Foldr,Length(Foldr));
CopyMemory(@DisplayName[0],@Foldr,Length(Foldr));
FillChar(BrowseInfo, SizeOf(BrowseInfo), #0);
with BrowseInfo do begin
hwndOwner := Application.Handle;
pszDisplayName := @DisplayName[0];
lpszTitle := PChar(Title);
ulFlags := BIF_RETURNONLYFSDIRS;
end;
ItemIDList := SHBrowseForFolder(BrowseInfo);
if Assigned(ItemIDList) then
if SHGetPathFromIDList(ItemIDList, DisplayName) then begin
Foldr := DisplayName;
Result := True;
end;
end;
function SearchTree(const AStartDir, AFileToFind : string; ARecurse :boolean = true) : string;
var
sResult : string;
// Recursive Dir Search
procedure _SearchDir(const ADirPath : string);
var rDirInfo : TSearchRec;
sDirPath : string;
begin
sDirPath := IncludeTrailingPathDelimiter(ADirPath);
if FindFirst(sDirPath + '*.*',faAnyFile,rDirInfo) = 0 then begin
// First find is a match ?
if SameText(rDirInfo.Name,AFileToFind) then
sResult := sDirPath + rDirInfo.Name;
// Traverse Starting Path
while {}(sResult = '') and (FindNext(rDirInfo) = 0) do begin
if SameText(rDirInfo.Name,AFileToFind) then
sResult := sDirPath + rDirInfo.Name
else
// Recurse Directorty ?
if ARecurse then
if (rDirInfo.Name = '.') or (rDirInfo.Name = '..') and
((rDirInfo.Attr and faDirectory) = faDirectory) then
_SearchDir(sDirPath + rDirInfo.Name);
end;
FindClose(rDirInfo);
end;
end;
// SearchTree
begin
Result := '';
Screen.Cursor := crHourGlass;
sResult := '';
_SearchDir(AStartDir);
Screen.Cursor := crDefault;
Result := sResult;
end;
procedure ListFileinDir(const AStartDir : string; AList :TStrings; Filter :string = '*.*'; ARecurse :boolean = true) ;
var
sResult : string;
// Recursive Dir Search
procedure _SearchDir(const ADirPath : string);
var rDirInfo : TSearchRec;
sDirPath : string;
begin
Application.ProcessMessages;
sDirPath := IncludeTrailingPathDelimiter(ADirPath);
if FindFirst(sDirPath + '\'+Filter,faAnyFile,rDirInfo) = 0 then begin
// First find is a match ?
sResult := sDirPath + rDirInfo.Name;
Alist.Add(sResult) ;
// Traverse Starting Path
while (sResult = '') and (FindNext(rDirInfo) = 0) do begin
sResult := sDirPath + rDirInfo.Name;
Alist.Add(sResult) ;
// Recurse Directorty ?
if ARecurse then
if (rDirInfo.Name = '.') or (rDirInfo.Name = '..') and
((rDirInfo.Attr and faDirectory) = faDirectory) then
_SearchDir(sDirPath + rDirInfo.Name);
end;
FindClose(rDirInfo);
end;
end;
// SearchTree
begin
Screen.Cursor := crHourGlass;
sResult := '';
_SearchDir(AStartDir);
Screen.Cursor := crDefault;
end;
procedure ListFileDir(Path: string; FileList: TStrings; Filter :string='*.*');
var
DOSerr: Integer;
fsrch: TsearchRec;
begin
Doserr := FindFirst(Path+'\'+Filter, faAnyFile, fsrch);
if (DOSerr = 0) then
begin
while (DOSerr = 0) do
begin
if (fsrch.attr and faDirectory) = 0 then
FileList.Add(Path+'\'+fsrch.Name);
Doserr := findnext(fsrch);
end;
findClose(fsrch);
end;
end;
procedure ListFileDir(Path: string; Proc :TSearchInFileEvent; Filter :string='*.*');
var
DOSerr: Integer;
fsrch: TsearchRec;
s :string;
begin
s:=Path+fsrch.Name;
if Proc(s)=-1 then exit;
doserr := FindFirst(Path+'\'+Filter, faAnyFile, fsrch);
if (DOSerr = 0) then
begin
while (DOSerr = 0) do
begin
Application.ProcessMessages;
if (fsrch.attr and faDirectory) = 0 then
if Assigned(Proc) then begin
s := Path+fsrch.Name;
Proc(s);
end ;
DOSerr := findnext(fsrch);
end;
findClose(fsrch);
end;
end;
function IsAdmin: Boolean;
var
hAccessToken: THandle;
ptgGroups: PTokenGroups;
dwInfoBufferSize: DWORD;
psidAdministrators: PSID;
x: Integer;
bSuccess: BOOL;
begin
Result := False;
bSuccess := OpenThreadToken(GetCurrentThread, TOKEN_QUERY, True,
hAccessToken);
if not bSuccess then
begin
if GetLastError = ERROR_NO_TOKEN then
bSuccess := OpenProcessToken(GetCurrentProcess, TOKEN_QUERY,
hAccessToken);
end;
if bSuccess then
begin
GetMem(ptgGroups, 1024);
bSuccess := GetTokenInformation(hAccessToken, TokenGroups,
ptgGroups, 1024, dwInfoBufferSize);
CloseHandle(hAccessToken);
if bSuccess then
begin
AllocateAndInitializeSid(SECURITY_NT_AUTHORITY, 2,
SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS,
0, 0, 0, 0, 0, 0, psidAdministrators);
{$R-}
for x := 0 to ptgGroups.GroupCount - 1 do
if EqualSid(psidAdministrators, ptgGroups.Groups[x].Sid) then
begin
Result := True;
Break;
end;
{$R+}
FreeSid(psidAdministrators);
end;
FreeMem(ptgGroups);
end;
end;
function GetProcessMemorySize(_sProcessName: string; var _nMemSize: Cardinal): Boolean;
var
l_nWndHandle, l_nProcID, l_nTmpHandle: HWND;
l_pPMC: PPROCESS_MEMORY_COUNTERS;
l_pPMCSize: Cardinal;
begin
l_nWndHandle := FindWindow(nil, PChar(_sProcessName));
if l_nWndHandle = 0 then
begin
Result := False;
Exit;
end;
l_pPMCSize := SizeOf(PROCESS_MEMORY_COUNTERS);
GetMem(l_pPMC, l_pPMCSize);
l_pPMC^.cb := l_pPMCSize;
GetWindowThreadProcessId(l_nWndHandle, @l_nProcID);
l_nTmpHandle := OpenProcess(PROCESS_ALL_ACCESS, False, l_nProcID);
if (GetProcessMemoryInfo(l_nTmpHandle, l_pPMC, l_pPMCSize)) then
_nMemSize := l_pPMC^.WorkingSetSize
else
_nMemSize := 0;
FreeMem(l_pPMC);
Result := True;
end;
procedure GetOSVersion(var APlatform: string ; var AMajorVersion,AMinorVersion,ABuild: DWORD);
var
VersionInfo: TOSVersionInfo;
begin
VersionInfo.dwOSVersionInfoSize := SizeOf(VersionInfo);
GetVersionEx(VersionInfo);
with VersionInfo do
begin
case dwPlatformId of
VER_PLATFORM_WIN32s: APlatform := 'Windows 3x';
VER_PLATFORM_WIN32_WINDOWS: APlatform := 'Windows 95';
VER_PLATFORM_WIN32_NT: APlatform := 'Windows NT';
end;
AMajorVersion := dwMajorVersion;
AMinorVersion := dwMinorVersion;
ABuild := dwBuildNumber;
end;
end;
function GetMemory :string;
var
memory: TMemoryStatus;
begin
memory.dwLength := SizeOf(memory);
GlobalMemoryStatus(memory);
Result := ('Total memory: ' +
IntToStr(memory.dwTotalPhys) + ' Bytes')+chr(10)+
('Available memory: ' +
IntToStr(memory.dwAvailPhys) + ' Bytes');
end;
function CurrentProcessMemory: Cardinal;
var
MemCounters: TProcessMemoryCounters;
begin
Result := 0;
MemCounters.cb := SizeOf(MemCounters);
if GetProcessMemoryInfo(GetCurrentProcess,
@MemCounters,
SizeOf(MemCounters)) then
Result := MemCounters.WorkingSetSize
else
RaiseLastOSError;
end;
function GetCurrentUserName: string;
const
cnMaxUserNameLen = 254;
var
sUserName: string;
dwUserNameLen: DWORD;
begin
dwUserNameLen := cnMaxUserNameLen - 1;
SetLength(sUserName, cnMaxUserNameLen);
Windows.GetUserName(PChar(sUserName), dwUserNameLen);
SetLength(sUserName, dwUserNameLen);
Result := sUserName;
end;
function ComputerName:String;
var
ComputerName: Array [0 .. 256] of char;
Size: DWORD;
begin
Size := 256;
GetComputerName(ComputerName, Size);
Result := ComputerName;
end;
function GetCPUVendor: string;
var
aVendor: array [0 .. 2] of LongWord;
iI, iJ: Integer;
begin
asm
push ebx
xor eax, eax
dw $A20F // CPUID instruction
mov LongWord ptr aVendor, ebx
mov LongWord ptr aVendor[+4], edx
mov LongWord ptr aVendor[+8], ecx
pop ebx
end;
for iI := 0 to 2 do
for iJ := 0 to 3 do
Result := Result +
Chr((aVendor[iI] and ($000000ff shl(iJ * 8))) shr(iJ * 8));
end;
function GetCPUSpeed: Double;
const
DelayTime = 500;
var
TimerHi, TimerLo: DWORD;
PriorityClass, Priority: Integer;
begin
PriorityClass := GetPriorityClass(GetCurrentProcess);
Priority := GetThreadPriority(GetCurrentThread);
SetPriorityClass(GetCurrentProcess, REALTIME_PRIORITY_CLASS);
SetThreadPriority(GetCurrentThread, THREAD_PRIORITY_TIME_CRITICAL);
Sleep(10);
asm
dw 310Fh
mov TimerLo, eax
mov TimerHi, edx
end;
Sleep(DelayTime);
asm
dw 310Fh
sub eax, TimerLo
sbb edx, TimerHi
mov TimerLo, eax
mov TimerHi, edx
end;
SetThreadPriority(GetCurrentThread, Priority);
SetPriorityClass(GetCurrentProcess, PriorityClass);
Result := TimerLo / (1000 * DelayTime);
end;
procedure FindFilesEx(FilesList: TStrings; StartDir, FileMask: string);
var
SR: TSearchRec;
DirList, Masks: TStringList;
IsFound: Boolean;
i: integer;
begin
if StartDir='' then exit;//avoid rangecheck error , StartDir:='c:\';
if StartDir[length(StartDir)] <> '\' then
StartDir := StartDir + '\';
{ Build a list of the files in directory StartDir
(not the directories!) }
Masks:=TStringList.Create;
Masks.Text:=StringReplace(FileMask,',',#10,[rfreplaceall]);
Application.ProcessMessages;
IsFound :=FindFirst(StartDir+'*.*', faAnyFile-faDirectory, SR) = 0;
while IsFound do begin
if Masks.IndexOf(ExtractFileExt(SR.Name))>-1 then
FilesList.Add(StartDir + SR.Name);
IsFound := FindNext(SR) = 0;
end;
FindClose(SR);
// Build a list of subdirectories
DirList := TStringList.Create;
IsFound := FindFirst(StartDir+'*.*', faAnyFile, SR) = 0;
while IsFound do begin
if ((SR.Attr and faDirectory) <> 0) and
(SR.Name[1] <> '.') then
DirList.Add(StartDir + SR.Name);
IsFound := FindNext(SR) = 0;
end;
FindClose(SR);
// Scan the list of subdirectories
for i := 0 to DirList.Count - 1 do
FindFiles(FilesList, DirList[i], FileMask);
DirList.Free;
Masks.Free;
end;
procedure FindFiles(FilesList: TStrings; StartDir, FileMask: string);
var
SR: TSearchRec;
DirList, Masks: TStringList;
IsFound: Boolean;
i: integer;
begin
if StartDir='' then exit;//avoid rangecheck error , StartDir:='c:\';
if StartDir[length(StartDir)] <> '\' then
StartDir := StartDir + '\';
{ Build a list of the files in directory StartDir
(not the directories!) }
Masks:=TStringList.Create;
Masks.Text:=StringReplace(FileMask,',',#10,[rfreplaceall]);
Application.ProcessMessages;
IsFound :=FindFirst(StartDir+'*.*', faAnyFile-faDirectory, SR) = 0;
while IsFound do begin
if Masks.IndexOf(ExtractFileExt(SR.Name))>-1 then
FilesList.Add(StartDir + SR.Name);
IsFound := FindNext(SR) = 0;
end;
FindClose(SR);
// Build a list of subdirectories
DirList := TStringList.Create;
IsFound := FindFirst(StartDir+'*.*', faAnyFile, SR) = 0;
while IsFound do begin
if ((SR.Attr and faDirectory) <> 0) and
(SR.Name[1] <> '.') then
DirList.Add(StartDir + SR.Name);
IsFound := FindNext(SR) = 0;
end;
FindClose(SR);
// Scan the list of subdirectories
for i := 0 to DirList.Count - 1 do
FindFiles(FilesList, DirList[i], FileMask);
DirList.Free;
Masks.Free;
end;
function GetClassName(Handle: THandle): String;
var
Buffer: array[0..MAX_PATH] of Char;
begin
Windows.GetClassName(Handle, @Buffer, MAX_PATH);
Result := String(Buffer);
end;
procedure ListDLLExports(const FileName: string; List: TStrings; complete:boolean=false);
type
TDWordArray = array [0..$FFFFF] of DWORD;
var
imageinfo: LoadedImage;
pExportDirectory: PImageExportDirectory;
dirsize: Cardinal;
pDummy: PImageSectionHeader;
i: Cardinal;
pNameRVAs: ^TDWordArray;
Name: string;
begin
List.Clear; pDummy:= nil;
if MapAndLoad(PChar(FileName), nil, @imageinfo, True, True) then
begin
try
pExportDirectory := ImageDirectoryEntryToData(imageinfo.MappedAddress,
False, IMAGE_DIRECTORY_ENTRY_EXPORT, dirsize);
if (pExportDirectory <> nil) then
begin
pNameRVAs := ImageRvaToVa(imageinfo.FileHeader, imageinfo.MappedAddress,
DWORD(pExportDirectory^.AddressOfNames), pDummy);
for i := 0 to pExportDirectory^.NumberOfNames - 1 do
begin
Name := PChar(ImageRvaToVa(imageinfo.FileHeader, imageinfo.MappedAddress,
pNameRVAs^[i], pDummy));
if complete then
List.AddObject(Name,TObject(integer(pExportDirectory)))
else
List.Add(Name);
end;
end;
finally
UnMapAndLoad(@imageinfo);
end;
end;
end;
function GetCapture(Image :TImage; fDlg :TForm=nil; Jpg :boolean = false):string;
var
B :TBitmap;
R :TRect;
P :TPoint;
cx, cy :integer;
c:string;
Dlg :hwnd;
begin
result:='';
if fdlg=nil then begin
dlg:=0;
c:='deskop';
end else begin
dlg:=fdlg.Handle;
SetWindowLong(dlg,gwl_style,GetWindowLong(dlg,gwl_style) and not CS_DROPSHADOW);
c:=fdlg.Name;
end;
Screen.Cursor := crHandPoint;
if not IsWindow(Dlg) then begin
GetCursorPos(P);
Dlg := WindowFromPoint(P);
end;
GetWindowRect(Dlg, R);
cx := R.Right - R.Left;
cy := R.Bottom -R.Top;
Image.Width := cx;
Image.Height := cy;
B := TBitmap.Create;
B.Canvas.Handle := GetDCEx(Dlg,0,dcx_parentclip or dcx_window or dcx_cache or dcx_clipsiblings or DCX_LOCKWINDOWUPDATE);
BitBlt(Image.Canvas.Handle, 0, 0, cx, cy, B.Canvas.Handle, 0, 0, srccopy);
ReleaseDC(Dlg, B.Canvas.Handle);
Screen.Cursor:=crArrow;
if pos('*',c)>0 then c:=stringreplace(c,'*','',[]);
if jpg then begin
image.Picture.SaveToFile(ExtractFilePath(ParamStr(0))+c+'.bmp');
bmp2jpeg(ExtractFilePath(ParamStr(0))+c+'.bmp',ExtractFilePath(ParamStr(0))+c+'.jpg');
result:=ExtractFilePath(ParamStr(0))+c+'.jpg'
end else begin
image.Picture.SaveToFile(ExtractFilePath(ParamStr(0))+c+'.bmp');
result:=ExtractFilePath(ParamStr(0))+c+'.bmp'
end
end;
procedure Jpeg2Bmp(const BmpFileName, JpgFileName: string); // helloacm.com
var
Bmp: TBitmap;
Jpg: TJPEGImage;
begin
Bmp := TBitmap.Create;
Bmp.PixelFormat := pf32bit;
Jpg := TJPEGImage.Create;
try
Jpg.LoadFromFile(JpgFileName);
Bmp.Assign(Jpg);
Bmp.SaveToFile(BmpFileName);
finally
Jpg.Free;
Bmp.Free;
end;
end;
procedure Bmp2Jpeg(const BmpFileName, JpgFileName: string); // helloacm.com
var
Bmp: TBitmap;
Jpg: TJPEGImage;
begin
Bmp := TBitmap.Create;
Bmp.PixelFormat := pf32bit;
Jpg := TJPEGImage.Create;
try
Bmp.LoadFromFile(BmpFileName);
Jpg.Assign(Bmp);
Jpg.SaveToFile(JpgFileName);
finally
Jpg.Free;
Bmp.Free;
end;
end;
function IsFileTypeRegistered(ProgId :string): boolean;
var
hkeyProgid : HKEY;
begin
Result := false;
if (SUCCEEDED(HResultFromWin32(RegOpenKey(HKEY_CLASSES_ROOT, PChar(ProgID), hkeyProgid)))) then
begin
Result := true;
RegCloseKey(hkeyProgid);
end;
end;
function RegisterFileTypeCommand(fileExtension, menuItemText, target: string) : boolean;
var
reg: TRegistry;
fileType: string;
begin
result := false;
reg := TRegistry.Create;
with reg do
try
RootKey := HKEY_CLASSES_ROOT;
if OpenKey('.' + fileExtension, True) then
begin
fileType := ReadString('') ;
if fileType = '' then
begin
fileType := fileExtension + 'file';
WriteString('', fileType) ;
end;
CloseKey;
if OpenKey(fileType + '\shell\' + menuItemText + '\command', True) then
begin
WriteString('', target + ' "%1"') ;
CloseKey;
result := true;
end;
end;
finally
Free;
end;
end;
function UnRegisterFileTypeCommand(fileExtension, menuItemText: string) : boolean;
var
reg: TRegistry;
fileType: string;
begin
result := false;
reg := TRegistry.Create;
with reg do
try
RootKey := HKEY_CLASSES_ROOT;
if OpenKey('.' + fileExtension, True) then
begin
fileType := ReadString('') ;
CloseKey;
end;
if OpenKey(fileType + '\shell', True) then
begin
DeleteKey(menuItemText) ;
CloseKey;
result := true;
end;
finally
Free;
end;
end;
procedure ImageLoad(AFile :string; Image :TImage);
var
OleGraphic: TOleGraphic;
fs: TFileStream;
begin
OleGraphic := TOleGraphic.Create;
fs := TFileStream.Create(AFile, fmOpenRead or fmSharedenyNone);
try
OleGraphic.LoadFromStream(fs);
Image.Picture.Assign(OleGraphic);
finally
fs.Free;
OleGraphic.Free
end;
end;
function GetFileNameFromOLEClass(const OLEClassName: string): string;
var
strCLSID: string;
IsFound: Boolean;
begin
with TRegistry.Create do
try
RootKey := HKEY_CLASSES_ROOT;
if KeyExists(OLEClassName + '\CLSID') then
begin
if OpenKeyReadOnly(OLEClassName + '\CLSID') then begin
strCLSID := ReadString('');
CloseKey;
end;
if OpenKey('CLSID\' + strCLSID + '\InprocServer32', False) then
IsFound := True
else
if OpenKey('CLSID\' + strCLSID + '\LocalServer32', False) then
IsFound := True
else
IsFound := False;
if IsFound then
begin
Result := ReadString('');
CloseKey;
end
else
Result := '';
end {else messageDlg('Not found.',mtInformation,[mbok],0)};
finally
Free
end
end;
function RecurseWin32(const R: TRegistry; const ThePath: string;
const TheKey: string): string;
var
TheList: TStringList;
i: Integer;
LP: string;
OnceUponATime: string;
begin
Result := '-';
TheList := TStringList.Create;
try
R.OpenKey(ThePath, False);
R.GetKeyNames(TheList);
R.CloseKey;
if TheList.Count = 0 then Exit;
for i := 0 to TheList.Count - 1 do with TheList do
begin
LP := ThePath + '\' + TheList[i];
if CompareText(Strings[i], TheKey) = 0 then
begin
Result := LP;
Break;
end;
OnceUponATime := RecurseWin32(R, LP, TheKey);
if OnceUponATime <> '-' then
begin
Result := OnceUponATime;
Break;
end;
end;
finally
TheList.Clear;
TheList.Free;
end;
end;
function GetWin32TypeLibList(Lines: TStrings): Boolean;
var
R: TRegistry;
W32: string;
i, j, TheIntValue, TheSizeOfTheIntValue{}: Integer;
TheSearchedValue, TheSearchedValueString: string;
TheVersionList, TheKeyList: TStringList;
TheBasisKey: string;
TL:TTypeLib;
begin
Result := True; TheVersionList := nil; TheKeyList := nil;
try
try
R := TRegistry.Create;
TheVersionList := TStringList.Create;
TheKeyList := TStringList.Create;
R.RootKey := HKEY_CLASSES_ROOT;
R.OpenKey('TypeLib', False);
TheBasisKey := R.CurrentPath;
(* Basis Informations *)
case R.GetDataType('') of
rdUnknown: ShowMessage('Nothing ???');
rdExpandString, rdString: TheSearchedValueString := R.ReadString('');
rdInteger: TheIntValue := R.ReadInteger('');
rdBinary: TheSizeOfTheIntValue := R.GetDataSize('');{}
end;
(* Build the List of Keys *)
R.GetKeyNames(TheKeyList);
R.CloseKey;
for i := 0 to TheKeyList.Count - 1 do
(* Loop around the typelib entries)
(* Schleife um die TypeLib Einträge *)
with TheKeyList do
if Length(Strings[i]) > 0 then
begin
R.OpenKey(TheBasisKey + '\' + Strings[i], False);
TheVersionList.Clear;
R.GetKeyNames(TheVersionList);
R.CloseKey;
(* Find "Win32" for each version *)
(* Finde der "win32" für jede VersionVersion:*)
for j := 0 to TheVersionList.Count - 1 do
if Length(TheVersionList.Strings[j]) > 0 then
begin
W32 := RecurseWin32(R, TheBasisKey + '\' +
Strings[i] + '\' +
TheVersionList.Strings[j],
'Win32');
if W32 <> '-' then
begin
TL :=TTypeLib.Create;
TL.Win32:= W32;
//TL.GUID:=StringToGUID(Copy(W32,pos('[',W32),pos(']',W32)-pos('[',W32)));
//Lines.Add(W32);
R.OpenKey(W32, False);
case R.GetDataType('') of
rdExpandString,
rdString: TheSearchedValue := R.ReadString('');
else
TheSearchedValue := 'Nothing !!!';
end;
R.CloseKey;
TL.FileName:=TheSearchedValue;
TL.Name:=ChangeFileExt(ExtractFileName(TL.FileName),'');
//Lines.Add('-----> ' + TheSearchedValue);
Lines.AddObject(TL.Name,TL);
end;
end;
end;
finally
TheVersionList.Free;
TheKeyList.Free;
end;
except
Result := False;
end;
end;
function GetSpecialDir(v:string):string;
(*
ALLUSERSPROFILE
APPDATA
CLIENTNAME
COMMONPROGRAMFILES
COMPUTERNAME
COMSPEC
HOMEDRIVE
HOMEPATH
LOGONSERVER
NUMBER_OF_PROCESSORS
OS
PATH
PATHEXT
PCTOOLSDIR
PROCESSOR_ARCHITECTURE
PROCESSOR_IDENTIFIER
PROCESSOR_LEVEL
PROCESSOR_REVISION
PROGRAMFILES
SESSIONNAME
SYSTEMDRIVE
SYSTEMROOT
TEMP
TMP
USERDOMAIN
USERNAME
USERPROFILE
WINDIR
*)
begin
result:=GetEnvironmentVariable(v);
end;
function GetSpecialFolderPath(CSIDLFolder: Integer): string;
var
FilePath: array [0..MAX_PATH] of char;
begin
SHGetFolderPath(0, CSIDLFolder, 0, 0, FilePath);
Result := FilePath;
end;
procedure ExtractResourceIDToFile(Instance:THandle; ResID:Integer; ResType, FileName:String; Overriden :boolean = true);
var
ResStream: TResourceStream;
FileStream: TFileStream;
begin
try
ResStream := TResourceStream.CreateFromID(Instance, ResID, pChar(ResType));
try
if Overriden then
if FileExists(FileName) then
DeleteFile(pChar(FileName));
FileStream := TFileStream.Create(FileName, fmCreate);
try
FileStream.CopyFrom(ResStream, 0);
finally
FileStream.Free;
end;
finally
ResStream.Free;
end;
except
on E:Exception do
begin
DeleteFile(FileName);
raise;
end;
end;
end;
procedure ExtractResourceNameToFile(Instance:THandle; ResName, ResType, FileName:String; Overriden :boolean = true);
var
ResStream: TResourceStream;
FileStream: TFileStream;
begin
try
ResStream := TResourceStream.Create(Instance, ResName, pChar(ResType));
try
if Overriden then
if FileExists(FileName) then
DeleteFile(pChar(FileName));
FileStream := TFileStream.Create(FileName, fmCreate);
try
FileStream.CopyFrom(ResStream, 0);
finally
FileStream.Free;
end;
finally
ResStream.Free;
end;
except
on E:Exception do
begin
DeleteFile(FileName);
raise;
end;
end;
end;
procedure ExtractResource(Module :HMODULE; ResName, ResType, ResFile :string);
var
i, Size :integer;
F :TextFile;
A :array of Char;
hLock :Pointer;
hRes, hGlb :Cardinal;
begin
hRes := findResource(Module,PChar(ResName),PChar(ResType));
if hRes <> 0 then begin
hGlb := LoadResource(Module,hRes);
if hGlb <> 0 then begin
hLock := LockResource(hRes);
if hLock <> nil then begin
size := SizeofResource(Module, hRes);
SetLength(A, size);
CopyMemory(@A[0], hLock, Size);
AssignFile(F,ResFile);
Rewrite(F);
for i := Low(A) to High(A) do
Write(F,A[i]);
CloseFile(F);
end;
end;
end;
end;
procedure LoadResourceName(instance :HMODULe; ResName, ResFile, ResType :string; ALines :TStrings);
var
tmpStream: TResourceStream;
begin
tmpStream := TResourceStream.Create( Instance, PChar(ResName), PChar(ResType) );
try
ALines.LoadFromStream( tmpStream );
ALines.SaveToFile(ResFile);
finally
tmpStream.Free;
end;
end;
function ExecuteProcess(FileName: string; Visibility: Integer; BitMask: Integer; Synch: Boolean): Longword;
//valori di Visibility:
{
Value Meaning
SW_HIDE :Hides the window and activates another window.
SW_MAXIMIZE :Maximizes the specified window.
SW_MINIMIZE :Minimizes the specified window and activates the next top-level window in the Z order.
SW_RESTORE :Activates and displays the window. If the window is minimized or maximized,
Windows restores it to its original size and position. An application should
specify this flag when restoring a minimized window.
SW_SHOW :Activates the window and displays it in its current size and position.
SW_SHOWDEFAULT :Sets the show state based on the SW_ flag specified in the STARTUPINFO
structure passed to the CreateProcess function by the program that started the application.
SW_SHOWMAXIMIZED :Activates the window and displays it as a maximized window.
SW_SHOWMINIMIZED :Activates the window and displays it as a minimized window.
SW_SHOWMINNOACTIVE :Displays the window as a minimized window. The active window remains active.
SW_SHOWNA :Displays the window in its current state. The active window remains active.
SW_SHOWNOACTIVATE :Displays a window in its most recent size and position. The active window remains active.
SW_SHOWNORMAL :Activates and displays a window. If the window is minimized or maximized,
Windows restores it to its original size and position. An application should specify this
flag when displaying the window for the first time.
}
//FileName: the name of the program I want to launch
//Bitmask: specifies the set of CPUs on wich I want to run the program
//the BitMask is built in the following manner:
//I have a bit sequence: every bit is associated to a CPU (from right to left)
//I set the bit to 1 if I want to use the corrisponding CPU, 0 otherwise
//for example: I have 4 processor and I want to run the specified process on the CPU 2 and 4:
//the corresponding bitmask will be 1010 -->2^0 * 0 + 2^1 * 1 + 2^2 * 0 + 2^3 * 1 = 2 + 8 = 10
//hence BitMask = 10
//Synch: Boolean --> True if I want a Synchronous Execution (I cannot close
//my application before the launched process is terminated)
var
zAppName: array[0..512] of Char;
zCurDir: array[0..255] of Char;
WorkDir: string;
StartupInfo: TStartupInfo;
ProcessInfo: TProcessInformation;
Closed: Boolean;
begin
//Closed := True;
StrPCopy(zAppName, FileName);
GetDir(0, WorkDir);
StrPCopy(zCurDir, WorkDir);
FillChar(StartupInfo, SizeOf(StartupInfo), #0);
StartupInfo.cb := SizeOf(StartupInfo);
StartupInfo.dwFlags := STARTF_USESHOWWINDOW;
StartupInfo.wShowWindow := Visibility;
if not CreateProcess(nil,
zAppName, // pointer to command line string
nil, // pointer to process security attributes
nil, // pointer to thread security attributes
False, // handle inheritance flag
CREATE_NEW_CONSOLE or // creation flags
NORMAL_PRIORITY_CLASS,
nil, //pointer to new environment block
nil, // pointer to current directory name
StartupInfo, // pointer to STARTUPINFO
ProcessInfo) // pointer to PROCESS_INF
then Result := WAIT_FAILED
else
begin
//running the process on the set of CPUs specified by BitMask
SetProcessAffinityMask(ProcessInfo.hProcess, BitMask);
/////
if (Synch = True) then //if I want a Synchronous execution (I cannot close my
// application before this process is terminated)
begin
Closed:= False;
repeat
case WaitForSingleObject(
ProcessInfo.hProcess, 100) of
WAIT_OBJECT_0 : Closed:= True;
WAIT_FAILED : RaiseLastWin32Error;
end;
Application.ProcessMessages;
until (Closed);
GetExitCodeProcess(ProcessInfo.hProcess, Result);
//exit code of the launched process (0 if the process returned no error )
CloseHandle(ProcessInfo.hProcess);
CloseHandle(ProcessInfo.hThread);
end
else
begin
Result := 0;
end;
end;
end; {ExecuteProcess}
// Open Taskmanager, select the launched process, right click,
// "Set affinity", you will see a check on the CPUs you selected
function LastInput: DWord;
var
LInput: TLastInputInfo;
begin
LInput.cbSize := SizeOf(TLastInputInfo);
GetLastInputInfo(LInput);
Result := GetTickCount - LInput.dwTime;
end;
(*Example:
procedure TForm1.Timer1Timer(Sender: TObject);
begin
Label1.Caption := Format('System Idle since %d ms', [LastInput]);
end;*)
procedure EnumExtensions(Lines:TStrings);
var
reg: TRegistry;
keys: TStringList;
i: Integer;
typename, displayname, server: string;
rii:PRegistryEntryStruct;
begin
lines.Clear;
reg := TRegistry.Create;
try
reg.rootkey := HKEY_CLASSES_ROOT;
if reg.OpenKey('', False) then
begin
keys := TStringList.Create;
try
reg.GetKeyNames(keys);
reg.CloseKey;
//lines.addstrings(keys);
for i := 0 to keys.Count - 1 do
begin
if keys[i][1] = '.' then
begin
{this is an extension, get its typename}
if reg.OpenKey(keys[i], False) then
begin
typename := reg.ReadString('');
reg.CloseKey;
if typename <> '' then
begin
if reg.OpenKey(typename, False) then
begin
displayname := reg.ReadString('');
reg.CloseKey;
end;
if reg.OpenKey(typename + '\shell\open\command', False) then
begin
server := reg.ReadString('');
New(rii);
rii^.Name:=keys[i];
rii^.Server:=server;
rii^.TypName:=typename;
rii^.DisplayName:=displayname;
rii^.Info:=Format('Extension: "%s", Typename: "%s", Displayname:"%s"' +
#13#10' Server: %s',
[keys[i], typename, displayname, server]);
Lines.AddObject(rii^.Name,TObject(rii));
reg.CloseKey;
end;
end;
end;
end;
end;
finally
keys.Free;
end;
end;
finally
reg.Free
end;
end;
function SetGlobalEnvironment(const Name, Value: string; const User: Boolean = True): Boolean;
resourcestring
REG_MACHINE_LOCATION = 'System\CurrentControlSet\Control\Session Manager\Environment';
REG_USER_LOCATION = 'Environment';
begin
with TRegistry.Create do
try
if User then { User Environment Variable }
Result := OpenKey(REG_USER_LOCATION, True)
else { System Environment Variable }
begin
RootKey := HKEY_LOCAL_MACHINE;
Result := OpenKey(REG_MACHINE_LOCATION, True);
end;
if Result then
begin
WriteString(Name, Value); { Write Registry for Global Environment }
{ Update Current Process Environment Variable }
SetEnvironmentVariable(PChar(Name), PChar(Value));
{ Send Message To All Top Window for Refresh }
SendMessage(HWND_BROADCAST, WM_SETTINGCHANGE, 0, Integer(PChar('Environment')));
end;
finally
Free;
end;
end;
procedure GetAssociatedIcon(FileName: TFilename; PLargeIcon, PSmallIcon: PHICON);
var
IconIndex: SmallInt; // Position of the icon in the file
Icono: PHICON; // The LargeIcon parameter of ExtractIconEx
FileExt, FileType: string;
Reg: TRegistry;
p: Integer;
p1, p2: PChar;
buffer: array [0..255] of Char;
Label
noassoc, NoSHELL; // ugly! but I use it, to not modify to much the original code :(
begin
IconIndex := 0;
Icono := nil;
// ;Get the extension of the file
FileExt := UpperCase(ExtractFileExt(FileName));
if ((FileExt ='.EXE') and (FileExt ='.ICO')) or not FileExists(FileName) then
begin
// If the file is an EXE or ICO and exists, then we can
// extract the icon from that file. Otherwise here we try
// to find the icon in the Windows Registry.
Reg := nil;
try
Reg := TRegistry.Create;
Reg.RootKey := HKEY_CLASSES_ROOT;
if FileExt = '.EXE' then FileExt := '.COM';
if Reg.OpenKeyReadOnly(FileExt) then
try
FileType := Reg.ReadString('');
finally
Reg.CloseKey;
end;
if (FileType <> '') and Reg.OpenKeyReadOnly(FileType + '\DefaultIcon') then
try
FileName := Reg.ReadString('');
finally
Reg.CloseKey;
end;
finally
Reg.Free;
end;
// If there is not association then lets try to
// get the default icon
if FileName = '' then goto noassoc;
// Get file name and icon index from the association
// ('"File\Name",IconIndex')
p1 := PChar(FileName);
p2 := StrRScan(p1, ',');
if p2<>nil then
begin
p := p2 - p1 + 1; // Position de la coma
IconIndex := StrToInt(Copy(FileName, p + 1, Length(FileName) - p));
SetLength(FileName, p - 1);
end;
end; //if ((FileExt '.EX ...
// Try to extract the small icon
if ExtractIconEx(PChar(FileName), IconIndex, Icono^, PSmallIcon^, 1) <> 1 then
begin
noassoc:
// That code is executed only if the ExtractIconEx return a value but 1
// There is not associated icon
// try to get the default icon from SHELL32.DLL
FileName := 'C:\Windows\System\SHELL32.DLL';
if not FileExists(FileName) then
begin //If SHELL32.DLL is not in Windows\System then
GetWindowsDirectory(buffer, SizeOf(buffer));
//Search in the current directory and in the windows directory
FileName := FileSearch('SHELL32.DLL', GetCurrentDir + ';' + buffer);
if FileName = '' then
goto NoSHELL; //the file SHELL32.DLL is not in the system
end;
// Determine the default icon for the file extension
if (FileExt = '.DOC') then IconIndex := 1
else if (FileExt = '.EXE') or (FileExt = '.COM') then IconIndex := 2
else if (FileExt = '.HLP') then IconIndex := 23
else if (FileExt = '.INI') or (FileExt = '.INF') then IconIndex := 63
else if (FileExt = '.TXT') then IconIndex := 64
else if (FileExt = '.BAT') then IconIndex := 65
else if (FileExt = '.DLL') or (FileExt = '.SYS') or (FileExt = '.VBX') or
(FileExt = '.OCX') or (FileExt = '.VXD') then IconIndex := 66
else if (FileExt = '.FON') then IconIndex := 67
else if (FileExt = '.TTF') then IconIndex := 68
else if (FileExt = '.FOT') then IconIndex := 69
else
IconIndex := 0;
// Try to extract the small icon
if ExtractIconEx(PChar(FileName), IconIndex, Icono^, PSmallIcon^, 1) <> 1 then
begin
//That code is executed only if the ExtractIconEx return a value but 1
// Fallo encontrar el icono. Solo "regresar" ceros.
NoSHELL:
if PLargeIcon=nil then PLargeIcon^ := 0;
if PSmallIcon=nil then PSmallIcon^ := 0;
end;
end; //if ExtractIconEx
if PSmallIcon^>0 then
begin //If there is an small icon then extract the large icon.
PLargeIcon^ := ExtractIcon(Application.Handle, PChar(FileName), IconIndex);
if PLargeIcon^ = Null then
PLargeIcon^ := 0;
end;
end;
procedure ExtractIcons(limg:TImage=nil;simg:TImage=nil);
var
SmallIcon, LargeIcon: HIcon;
Icon: TIcon;
begin
with (TOpenDialog.Create(nil)) do begin
Icon := TIcon.Create;
try
GetAssociatedIcon(FileName, @LargeIcon, @SmallIcon);
if LargeIcon <> 0 then
begin
Icon.Handle := LargeIcon;
Icon.SaveToFile(ChangeFileExt(FileName,'')+'-large.ico');
if limg<>nil then
limg.Picture.Icon:=icon;
end;
if SmallIcon <> 0 then
begin
Icon.Handle := SmallIcon;
Icon.SaveToFile(ChangeFileExt(FileName,'')+'-small.ico');
if simg<>nil then
simg.Picture.Icon:=icon;
end;
finally
Icon.Destroy;
end;
end;
end;
function ComPortAvailable(Port: PChar): Boolean;
var
DeviceName: array[0..80] of Char;
ComFile: THandle;
begin
StrPCopy(DeviceName, Port);
ComFile := CreateFile(DeviceName, GENERIC_READ or GENERIC_WRITE, 0, nil,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, 0);
Result := ComFile <> INVALID_HANDLE_VALUE;
CloseHandle(ComFile);
end;
function GetOpenComPort(searchfor:integer=30):tcomports;
var
i:integer;
begin
SetLength(result,0);
for i:=0 to searchfor-1 do begin
if ComPortAvailable(PChar(format('COM%d:',[i]))) then begin
SetLength(result,i+1);
result[i].name:=format('COM%d:',[i]);
result[i].id:=i;
end
end
end;
procedure RegisterFileType(ext: string; exe: string);
var
reg: TRegistry;
begin
reg := TRegistry.Create;
try
reg.RootKey := HKEY_CLASSES_ROOT;
//create a new key --> .pci
reg.OpenKey('.' + ext, True);
try
//create a new value for this key --> pcifile
reg.Writestring('', ext + 'file');
finally
reg.CloseKey;
end;
//create a new key --> pcifile
reg.CreateKey(ext + 'file');
//create a new key pcifile\DefaultIcon
reg.OpenKey(ext + 'file\DefaultIcon', True);
//and create a value where the icon is stored --> c:\project1.exe,0
try
reg.Writestring('', exe + ',0');
finally
reg.CloseKey;
end;
reg.OpenKey(ext + 'file\shell\open\command', True);
//create value where exefile is stored --> c:\project1.exe "%1"
try
reg.Writestring('', exe + ' "%1"');
finally
reg.CloseKey;
end;
finally
reg.Free;
end;
SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, nil, nil);
end;
{procedure TForm1.Button1Click(Sender: TObject);
begin
RegisterFileType('pci', 'c:\project1.exe');
end;}
function GetSerialPortNames: string;
var
Index: Integer;
Data: string;
TmpPorts: String;
sr : TSearchRec;
begin
try
TmpPorts := '';
if FindFirst('/dev/ttyS*', $FFFFFF{FF}, sr) = 0 then
begin
repeat
if (sr.Attr and $FFFFFF{FF}) = Sr.Attr then
begin
data := sr.Name;
index := length(data);
while (index > 1) and (data[index] <> '/') do
index := index - 1;
TmpPorts := TmpPorts + ' ' + copy(data, 1, index + 1);
end;
until FindNext(sr) <> 0;
end;
FindClose(sr);
finally
Result:=TmpPorts;
end;
end;
function RegisterOCX(FileName: string): Boolean;
var
OCXHand: THandle;
RegFunc: TDllRegisterServer;
begin
OCXHand := LoadLibrary(PChar(FileName));
RegFunc := GetProcAddress(OCXHand, 'DllRegisterServer');
if @RegFunc <> nil then
Result := RegFunc = S_OK
else
Result := False;
FreeLibrary(OCXHand);
end;
function UnRegisterOCX(FileName: string): Boolean;
var
OCXHand: THandle;
RegFunc: TDllRegisterServer;
begin
OCXHand := LoadLibrary(PChar(FileName));
RegFunc := GetProcAddress(OCXHand, 'DllUnregisterServer');
if @RegFunc <> nil then
Result := RegFunc = S_OK
else
Result := False;
FreeLibrary(OCXHand);
end;
procedure EnumComPorts(const Ports: TStringList);
var
nInd: Integer;
begin { EnumComPorts }
with TRegistry.Create(KEY_READ) do
try
RootKey := HKEY_LOCAL_MACHINE;
if OpenKey('hardware\devicemap\serialcomm', False) then
try
Ports.BeginUpdate();
try
GetValueNames(Ports);
for nInd := Ports.Count - 1 downto 0 do
Ports.Strings[nInd] := ReadString(Ports.Strings[nInd]);
Ports.Sort()
finally
Ports.EndUpdate()
end { try-finally }
finally
CloseKey()
end { try-finally }
else
Ports.Clear()
finally
Free()
end { try-finally }
end { EnumComPorts };
end.
|
unit Lib.Android.Account;
interface
uses
Androidapi.Helpers,
Androidapi.Jni,
Androidapi.JNI.Accounts,
Androidapi.JNIBridge,
Androidapi.JNI.App,
Androidapi.JNI.GraphicsContentViewText,
Androidapi.JNI.JavaTypes,
Androidapi.JNI.Os,
System.Classes;
procedure FillAccountEmails(const AccountType: String; AList: TStrings);
function GetAccountEmails(const AccountType: String): TArray<String>;
function GetFirstAccountEmail(const AccountType: string): string;
implementation
procedure FillAccountEmails(const AccountType: String; AList: TStrings);
var
AccountManager: JAccountManager;
Accounts: TJavaObjectArray<JAccount>;
Account: JAccount;
AccountLoopCounter: Integer;
begin
AccountManager := TJAccountManager.JavaClass.get(TAndroidHelper.Context);
if AccountManager <> nil then
begin
Accounts:= AccountManager.getAccountsByType(StringToJString(AccountType));
if Accounts <> nil then
begin
for AccountLoopCounter := 0 to Pred(Accounts.Length) do
begin
Account:= TJAccount.Wrap(Accounts.GetRawItem(AccountLoopCounter));
AList.Add(JStringtoString(Account.name));
end
end;
end;
end;
function GetAccountEmails(const AccountType: String): TArray<String>;
var
AccountManager: JAccountManager;
Accounts: TJavaObjectArray<JAccount>;
Account: JAccount;
AccountLoopCounter: Integer;
begin
AccountManager := TJAccountManager.JavaClass.get(TAndroidHelper.Context);
if AccountManager <> nil then
begin
Accounts:= AccountManager.getAccountsByType(StringToJString(AccountType));
if Accounts <> nil then
begin
SetLength(Result, Accounts.Length);
for AccountLoopCounter := 0 to Pred(Accounts.Length) do
begin
Account:= TJAccount.Wrap(Accounts.GetRawItem(AccountLoopCounter));
Result[AccountLoopCounter] := JStringtoString(Account.name);
end
end;
end;
end;
function GetFirstAccountEmail(const AccountType: string): string;
var
AccountManager: JAccountManager;
Accounts: TJavaObjectArray<JAccount>;
Account: JAccount;
begin
AccountManager := TJAccountManager.JavaClass.get(TAndroidHelper.Context);
if AccountManager <> nil then
begin
Accounts := AccountManager.getAccountsByType(StringToJString(AccountType));
if Accounts <> nil then
begin
Account:= TJAccount.Wrap(Accounts.GetRawItem(0));
Result:= JStringtoString(Account.name);
end;
end;
end;
end.
|
unit View.Main;
interface
uses
System.SysUtils, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts, FMX.ListBox,
View.Frame.CustomerDetails, System.ImageList, FMX.ImgList, ViewModel.Main.Types,
System.Generics.Collections;
type
TFormMain = class(TForm)
ListBoxCustomers: TListBox;
LabelTitle: TLabel;
LabelTotalCustomers: TLabel;
ButtonAdd: TButton;
ButtonEdit: TButton;
ButtonDelete: TButton;
TFrameCustomerDetails1: TFrameCustomerDetails;
ImageList1: TImageList;
procedure FormCreate(Sender: TObject);
procedure ButtonDeleteClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure ListBoxCustomersChange(Sender: TObject);
procedure ButtonEditClick(Sender: TObject);
procedure ButtonAddClick(Sender: TObject);
private
fViewModel: IViewModelMain;
fIndexID: TDictionary<Integer, Integer>;
procedure updateGUI;
procedure updateList;
procedure updateCustomer (const aID: Integer);
public
procedure setViewModel (const aViewModel: IViewModelMain);
end;
implementation
uses
System.StrUtils, System.Types,
Model.Main.Types, Model.Main, Model.Database, ViewModel.Types, ViewModel.AddEditCustomer,
ViewModel.AddEditCustomer.Types, View.AddEditCustomer;
{$R *.fmx}
procedure TFormMain.ButtonAddClick(Sender: TObject);
var
newModel: IModelMain;
newEdit: TFormAddEditCustomer;
newViewModel: IViewModelAddEditCustomer;
begin
newModel:=createModelMain (database);
newViewModel:=createViewModelAddEditCustomer(newModel);
newViewModel.setCustomer(0);
newEdit:=TFormAddEditCustomer.Create(self);
newEdit.Parent:=Self;
newEdit.setViewModel(newViewModel);
newEdit.ShowModal;
updateList;
if ListBoxCustomers.Count>0 then
ListBoxCustomers.ItemIndex:=0;
end;
procedure TFormMain.ButtonDeleteClick(Sender: TObject);
begin
if ListBoxCustomers.ItemIndex>-1 then
if MessageDlg('Are you sure you want to delete the selected customer?',
TMsgDlgType.mtConfirmation,[TMsgDlgBtn.mbYes, TMsgDlgBtn.mbNo],0)=mrYes then
begin
fViewModel.deleteCustomer(fIndexID.Items[ListBoxCustomers.ItemIndex]);
updateList;
updateGUI;
if ListBoxCustomers.Count>-1 then
ListBoxCustomers.ItemIndex:=0;
end;
end;
procedure TFormMain.ButtonEditClick(Sender: TObject);
var
editModel: IModelMain;
editEdit: TFormAddEditCustomer;
editViewModel: IViewModelAddEditCustomer;
begin
if not ListBoxCustomers.ItemIndex>-1 then
Exit;
editModel:=createModelMain (database);
editViewModel:=createViewModelAddEditCustomer(editModel);
editViewModel.setCustomer(fIndexID.Items[ListBoxCustomers.ItemIndex]);
editEdit:=TFormAddEditCustomer.Create(self);
editEdit.Parent:=Self;
editEdit.setViewModel(editViewModel);
editEdit.ShowModal;
updateList;
if ListBoxCustomers.Count>0 then
ListBoxCustomers.ItemIndex:=0;
end;
procedure TFormMain.FormCreate(Sender: TObject);
begin
TFrameCustomerDetails1.ImagePhoto.Bitmap:=ImageList1.Source[0].MultiResBitmap.Bitmaps[1];
fIndexID:=TDictionary<Integer, Integer>.Create;
end;
procedure TFormMain.FormDestroy(Sender: TObject);
begin
fIndexID.Free;
end;
procedure TFormMain.ListBoxCustomersChange(Sender: TObject);
begin
if (ListBoxCustomers.ItemIndex>-1) and
(fIndexID.ContainsKey(ListBoxCustomers.ItemIndex)) then
updateCustomer(fIndexID.Items[ListBoxCustomers.ItemIndex]);
end;
procedure TFormMain.setViewModel(const aViewModel: IViewModelMain);
begin
if not Assigned(aViewModel) then
raise Exception.Create('The ViewModel is nil')
else
begin
fViewModel:=aViewModel;
updateGUI;
updateList;
end;
end;
procedure TFormMain.updateCustomer (const aID: Integer);
var
tmpCustomer: TCustomerTransientRecord;
begin
fViewModel.getCustomer(aID, tmpCustomer);
updateGUI;
TFrameCustomerDetails1.ImagePhoto.Visible:=true;
if assigned(tmpCustomer.PhotoBitmap) then
TFrameCustomerDetails1.ImagePhoto.Bitmap:=tmpCustomer.PhotoBitmap
else
TFrameCustomerDetails1.ImagePhoto.Bitmap:=ImageList1.Source[0].MultiResBitmap.Bitmaps[1];
end;
procedure TFormMain.updateGUI;
begin
LabelTotalCustomers.Text:=fViewModel.ComponentsRecord.TotalLabel;
ButtonAdd.Enabled:=fViewModel.ComponentsRecord.AddButtonEnabled;
ButtonDelete.Enabled:=fViewModel.ComponentsRecord.DeleteButtonEnabled;
ButtonEdit.Enabled:=fViewModel.ComponentsRecord.EditButtonEnabled;
TFrameCustomerDetails1.ButtonLoadImage.Visible:=fViewModel.ComponentsRecord.PanelLoadButtonVisile;
TFrameCustomerDetails1.ButtonSave.Visible:=fViewModel.ComponentsRecord.PanelSaveButtonVisible;
TFrameCustomerDetails1.ButtonCancel.Visible:=fViewModel.ComponentsRecord.PanelCancelButtonVisible;
TFrameCustomerDetails1.LabelFirstName.Visible:=fViewModel.ComponentsRecord.PanelLabel1Visible;
TFrameCustomerDetails1.LabelFirstName.Text:=fViewModel.ComponentsRecord.PanelLabel1Text;
TFrameCustomerDetails1.LabelLastName.Visible:=fViewModel.ComponentsRecord.PanelLabel2Visible;
TFrameCustomerDetails1.LabelLastName.Text:=fViewModel.ComponentsRecord.PanelLabel2Text;
TFrameCustomerDetails1.EditFirstName.Visible:=fViewModel.ComponentsRecord.PanelEdit1Visible;
TFrameCustomerDetails1.EditFirstName.Text:=fViewModel.ComponentsRecord.PanelEdit1Text;
TFrameCustomerDetails1.EditLastName.Visible:=fViewModel.ComponentsRecord.PanelEdit2Visible;
TFrameCustomerDetails1.EditLastName.Text:=fViewModel.ComponentsRecord.PanelEdit2Text;
TFrameCustomerDetails1.ImagePhoto.Visible:=False;
end;
procedure TFormMain.updateList;
var
tmpList: TStringList;
tmpListItem: TListBoxItem;
tmpStr: string;
i: integer;
begin
ListBoxCustomers.Clear;
fIndexID.Clear;
tmpList:=fViewModel.CustomerList;
for i := 0 to tmpList.Count-1 do
begin
tmpStr:=tmpList.Strings[i];
tmpListItem:=TListBoxItem.Create(ListBoxCustomers);
tmpListItem.Parent:=ListBoxCustomers;
tmpListItem.Text:=SplitString(tmpStr,'|')[0];
fIndexID.Add(i, SplitString(tmpStr,'|')[1].ToInteger);
end;
LabelTotalCustomers.Text:=fViewModel.ComponentsRecord.TotalLabel;
end;
end.
|
unit LTPCMSConfirmReader;
interface
uses
Classes, ComObj, ActiveX, SysUtils, Windows, CommUtils, DateUtils, Variants,
SAPStockReader, SBomReader;
type
TLTPCMSConfirmRecord = packed record
dtCreateDate: TDateTime; //单据创建日期
sNumber: string; //物料编码
sName: string; //物料名称
sUnit: string; //单位
dQtyNeed: Double; //需求数量
dtDateNeed: TDateTime; //计划到料日期
sBuyerNo: string; //采购员代码
sBuyerName: string; //采购员名称
dQtyConfirm: Double; //回复数量
dtConfirm: TDateTime; //回复到料日期
end;
PLTPCMSConfirmRecord = ^TLTPCMSConfirmRecord;
TTPCMSConfirmReader = class
private
FFile: string;
ExcelApp, WorkBook: Variant;
procedure Open;
procedure Log(const str: string);
public
FList: TList;
constructor Create(const sfile: string);
destructor Destroy; override;
procedure Clear;
procedure GetNumberList(slNumbers: TStringList; var dt1, dt2: TDateTime);
function GetQtyDemand(sNumber: string; dt: TDateTime): Double;
function GetQtyConfirm(sNumber: string; dt: TDateTime): Double;
procedure Save(aSAPStockReader: TSAPStockReader; aSBomReader: TSBomReader;
const sfile: string);
end;
implementation
const
CICreateDate = 1; //单据创建日期
CINumber = 2; //物料编码
CIName = 3; //物料名称
CIUnit = 4; //单位
CIQtyNeed = 5; //需求数量
CIDateNeed = 6; //计划到料日期
CIBuyerNo = 7; //采购员代码
CIBuyerName = 8; //采购员名称
CIQtyConfirm = 12; //回复数量
CIDateConfirm = 13; //回复到料日期
{ TTPCMSConfirmReader }
constructor TTPCMSConfirmReader.Create(const sfile: string);
begin
FFile := sfile;
FList := TList.Create;
Open;
end;
destructor TTPCMSConfirmReader.Destroy;
begin
Clear;
FList.Free;
inherited;
end;
procedure TTPCMSConfirmReader.Clear;
var
i: Integer;
p: PLTPCMSConfirmRecord;
begin
for i := 0 to FList.Count - 1 do
begin
p := PLTPCMSConfirmRecord(FList[i]);
Dispose(p);
end;
FList.Clear;
end;
procedure TTPCMSConfirmReader.GetNumberList(slNumbers: TStringList;
var dt1, dt2: TDateTime);
var
i: Integer;
p: PLTPCMSConfirmRecord;
begin
dt2 := myStrToDateTime('1900-01-01');
dt1 := myStrToDateTime('2100-01-01');
slNumbers.Clear;
for i := 0 to FList.Count - 1 do
begin
p := PLTPCMSConfirmRecord(FList[i]);
if p^.dQtyConfirm > 0 then
begin
if dt1 > p^.dtConfirm then
begin
dt1 := p^.dtConfirm;
end;
if dt2 < p^.dtConfirm then
begin
dt2 := p^.dtConfirm;
end;
end;
if slNumbers.IndexOf(p^.sNumber) < 0 then
begin
slNumbers.AddObject(p^.sNumber, TObject(p));
end;
end;
end;
function TTPCMSConfirmReader.GetQtyDemand(sNumber: string; dt: TDateTime): Double;
var
i: Integer;
p: PLTPCMSConfirmRecord;
begin
Result := 0;
for i := 0 to FList.Count - 1 do
begin
p := PLTPCMSConfirmRecord(FList[i]);
if p^.dtConfirm <> dt then Continue;
if p^.sNumber <> sNumber then Continue;
Result := Result + p^.dQtyNeed;
end;
end;
function TTPCMSConfirmReader.GetQtyConfirm(sNumber: string; dt: TDateTime): Double;
var
i: Integer;
p: PLTPCMSConfirmRecord;
begin
Result := 0;
for i := 0 to FList.Count - 1 do
begin
p := PLTPCMSConfirmRecord(FList[i]);
if p^.dtConfirm <> dt then Continue;
if p^.sNumber <> sNumber then Continue;
Result := Result + p^.dQtyConfirm;
end;
end;
procedure TTPCMSConfirmReader.Log(const str: string);
begin
end;
procedure TTPCMSConfirmReader.Open;
var
iSheetCount, iSheet: Integer;
sSheet: string;
stitle1, stitle2, stitle3, stitle4: string;
stitle: string;
irow: Integer;
snumber: string;
p: PLTPCMSConfirmRecord;
sdate: string;
v: Variant;
s: string;
begin
Clear;
ExcelApp := CreateOleObject('Excel.Application' );
ExcelApp.Visible := False;
ExcelApp.Caption := '应用程序调用 Microsoft Excel';
try
WorkBook := ExcelApp.WorkBooks.Open(FFile);
try
iSheetCount := ExcelApp.Sheets.Count;
for iSheet := 1 to iSheetCount do
begin
if not ExcelApp.Sheets[iSheet].Visible then Continue;
ExcelApp.Sheets[iSheet].Activate;
sSheet := ExcelApp.Sheets[iSheet].Name;
Log(sSheet);
irow := 1;
stitle1 := ExcelApp.Cells[irow, 1].Value;
stitle2 := ExcelApp.Cells[irow, 2].Value;
stitle3 := ExcelApp.Cells[irow, 3].Value;
stitle4 := ExcelApp.Cells[irow, 4].Value;
stitle := stitle1 + stitle2 + stitle3 + stitle4;
if stitle <> '单据创建日期物料编码物料名称单位' then
begin
Log(sSheet +' 不是SAP导出BOM格式');
Continue;
end;
irow := 2;
snumber := ExcelApp.Cells[irow, CINumber].Value;
while snumber <> '' do
begin
p := New(PLTPCMSConfirmRecord);
FList.Add(p);
sdate := ExcelApp.Cells[irow, CICreateDate].Value;
sdate := StringReplace(sdate, '/', '-', [rfReplaceAll]);
p^.dtCreateDate := myStrToDateTime(sdate);
p^.sNumber := snumber;
p^.sName := ExcelApp.Cells[irow, CIName].Value;
p^.sUnit := ExcelApp.Cells[irow, CIUnit].Value;
p^.dQtyNeed := ExcelApp.Cells[irow, CIQtyNeed].Value;
sdate := ExcelApp.Cells[irow, CIDateNeed].Value;
sdate := StringReplace(sdate, '/', '-', [rfReplaceAll]);
p^.dtDateNeed := myStrToDateTime(sdate);
p^.sBuyerNo := ExcelApp.Cells[irow, CIBuyerNo].Value;
p^.sBuyerName := ExcelApp.Cells[irow, CIBuyerName].Value;
v := ExcelApp.Cells[irow, CIQtyConfirm].Value;
if VarIsNumeric(v) then
begin
p^.dQtyConfirm := v;
end
else if VarIsStr(v) then
begin
s := v;
p^.dQtyConfirm := StrToFloatDef(s, 0);
end;
if p^.dQtyConfirm > 0 then
begin
sdate := ExcelApp.Cells[irow, CIDateConfirm].Value;
sdate := StringReplace(sdate, '/', '-', [rfReplaceAll]);
p^.dtConfirm := myStrToDateTime(sdate);
end;
irow := irow + 1;
snumber := ExcelApp.Cells[irow, CINumber].Value;
end;
end;
finally
ExcelApp.ActiveWorkBook.Saved := True; //新加的,设置已经保存
WorkBook.Close;
end;
finally
ExcelApp.Visible := True;
ExcelApp.Quit;
end;
end;
procedure TTPCMSConfirmReader.Save(aSAPStockReader: TSAPStockReader;
aSBomReader: TSBomReader; const sfile: string);
var
ExcelApp, WorkBook: Variant;
irow: Integer;
i: Integer;
p: PLTPCMSConfirmRecord;
slNumbers: TStringList;
dt1, dt2: TDateTime;
col1: Integer;
col: Integer;
idate: Integer;
dc: Integer;
dt: TDateTime;
begin
// 开始保存 Excel
try
ExcelApp := CreateOleObject('Excel.Application' );
ExcelApp.Visible := False;
ExcelApp.Caption := '应用程序调用 Microsoft Excel';
except
on e: Exception do
begin
MessageBox(0, PChar(e.Message), '金蝶提示', 0);
Exit;
end;
end;
WorkBook := ExcelApp.WorkBooks.Add;
while ExcelApp.Sheets.Count > 1 do
begin
ExcelApp.Sheets[2].Delete;
end;
slNumbers := TStringList.Create;
GetNumberList(slNumbers, dt1, dt2);
if dt1 > dt2 then
begin
dc := 0;
end
else
begin
dc := DaysBetween(dt2, dt1);
end;
ExcelApp.Sheets[1].Activate;
ExcelApp.Sheets[1].Name := '采购交期回复';
try
irow := 3;
ExcelApp.Cells[irow, 1].Value := '物料类别';
ExcelApp.Cells[irow, 2].Value := '物料编码';
ExcelApp.Cells[irow, 3].Value := '物料名称';
ExcelApp.Cells[irow, 4].Value := '子料名称';
ExcelApp.Cells[irow, 5].Value := '所用项目';
ExcelApp.Cells[irow, 6].Value := '半成品库存';
ExcelApp.Cells[irow, 7].Value := '可用库存';
ExcelApp.Cells[irow, 8].Value := '新外购入库';
ExcelApp.Cells[irow, 9].Value := 'MRP当天外购入库';
ExcelApp.Cells[irow, 10].Value := 'Commitment';
ExcelApp.Columns[2].ColumnWidth := 16;
ExcelApp.Columns[3].ColumnWidth := 20;
ExcelApp.Columns[10].ColumnWidth := 18;
col1 := 11;
for idate := 0 to dc - 1 do
begin
col := col1 + idate;
ExcelApp.Cells[irow - 1, col].Value := 'WK' + IntToStr(WeekOf(dt1 + idate));
dt := dt1 + idate;
ExcelApp.Cells[irow, col].Value := dt;
end;
AddColor(ExcelApp, irow - 1, col1 - 1, irow - 1, col1 + dc - 1, $E8DEB7);
AddColor(ExcelApp, irow, 1, irow, col1 + dc - 1, $E8DEB7);
irow := 4;
for i := 0 to slNumbers.Count - 1 do
begin
p := PLTPCMSConfirmRecord(slNumbers.Objects[i]);
ExcelApp.Cells[irow, 1].Value := '';
ExcelApp.Cells[irow, 2].Value := p^.sNumber;
ExcelApp.Cells[irow, 3].Value := p^.sName;
ExcelApp.Cells[irow, 4].Value := '';
ExcelApp.Cells[irow, 5].Value := '';
ExcelApp.Cells[irow, 6].Value := aSBomReader.GetAvailStockSemi(p^.sNumber);
ExcelApp.Cells[irow, 7].Value := aSAPStockReader.GetAvailStock(p^.sNumber);
ExcelApp.Cells[irow, 8].Value := '';
ExcelApp.Cells[irow, 9].Value := '';
ExcelApp.Cells[irow, 10].Value := 'Demand By MPS';
ExcelApp.Cells[irow + 1, 10].Value := 'Demand By 要货计划';
ExcelApp.Cells[irow + 2, 10].Value := 'Delta MPS';
ExcelApp.Cells[irow + 3, 10].Value := 'Confirm supply';
MergeCells(ExcelApp, irow, 1, irow + 3, 1);
MergeCells(ExcelApp, irow, 2, irow + 3, 2);
MergeCells(ExcelApp, irow, 3, irow + 3, 3);
MergeCells(ExcelApp, irow, 4, irow + 3, 4);
MergeCells(ExcelApp, irow, 5, irow + 3, 5);
MergeCells(ExcelApp, irow, 6, irow + 3, 6);
MergeCells(ExcelApp, irow, 7, irow + 3, 7);
MergeCells(ExcelApp, irow, 8, irow + 3, 8);
col1 := 11;
for idate := 0 to dc - 1 do
begin
col := col1 + idate;
//ExcelApp.Cells[irow, col].Value := 'Demand By MPS';
ExcelApp.Cells[irow + 1, col].Value := GetQtyDemand(p^.sNumber, dt1 + idate);
ExcelApp.Cells[irow + 2, col].Value := '=' + GetRef(col) + IntToStr(irow + 1) + '-' + GetRef(col) + IntToStr(irow);
ExcelApp.Cells[irow + 3, col].Value := GetQtyConfirm(p^.sNumber, dt1 + idate);
end;
AddColor(ExcelApp, irow + 2, col1 - 1, irow + 2, col1 + dc - 1, $E4DCD6);
AddColor(ExcelApp, irow + 3, col1 - 1, irow + 3, col1 + dc - 1, $D6E4FC);
irow := irow + 4;
end;
col1 := 10;
AddBorder(ExcelApp, 1, 1, irow - 1, col1 + dc);
WorkBook.SaveAs(sfile);
ExcelApp.ActiveWorkBook.Saved := True; //新加的,设置已经保存
finally
WorkBook.Close;
ExcelApp.Quit;
slNumbers.Free;
end;
end;
end.
|
unit Laz_And_Controls_Events; //by jmpessoa
{$mode delphi}
interface
uses
Classes, SysUtils, And_jni;
// AdMob Events
procedure Java_Event_pOnAdMobLoaded(env: PJNIEnv; this: jobject; Obj: TObject; admobType : integer);
procedure Java_Event_pOnAdMobFailedToLoad(env: PJNIEnv; this: jobject; Obj: TObject; admobType, errorCode: integer);
procedure Java_Event_pOnAdMobOpened(env: PJNIEnv; this: jobject; Obj: TObject; admobType : integer);
procedure Java_Event_pOnAdMobClosed(env: PJNIEnv; this: jobject; Obj: TObject; admobType : integer);
procedure Java_Event_pOnAdMobClicked(env: PJNIEnv; this: jobject; Obj: TObject; admobType : integer);
procedure Java_Event_pOnAdMobInitializationComplete(env: PJNIEnv; this: jobject; Obj: TObject);
procedure Java_Event_pOnAdMobFailedToShow(env: PJNIEnv; this: jobject; Obj: TObject; admobType, errorCode: integer);
procedure Java_Event_pOnAdMobRewardedUserEarned(env: PJNIEnv; this: jobject; Obj: TObject);
procedure Java_Event_pOnBluetoothEnabled(env: PJNIEnv; this: jobject; Obj: TObject);
procedure Java_Event_pOnBluetoothDisabled(env: PJNIEnv; this: jobject; Obj: TObject);
procedure Java_Event_pOnBluetoothDeviceFound(env: PJNIEnv; this: jobject; Obj: TObject; deviceName: JString; deviceAddress: JString );
procedure Java_Event_pOnBluetoothDiscoveryStarted(env: PJNIEnv; this: jobject; Obj: TObject);
procedure Java_Event_pOnBluetoothDiscoveryFinished(env: PJNIEnv; this: jobject; Obj: TObject; countFoundedDevices: integer; countPairedDevices: integer);
procedure Java_Event_pOnBluetoothDeviceBondStateChanged(env: PJNIEnv; this: jobject; Obj: TObject; state: integer; deviceName: JString; deviceAddress: JString);
procedure Java_Event_pOnBluetoothClientSocketConnected(env: PJNIEnv; this: jobject; Obj: TObject; deviceName: JString; deviceAddress: JString);
procedure Java_Event_pOnBluetoothClientSocketIncomingData(env: PJNIEnv; this: jobject; Obj: TObject; byteArrayData: JByteArray; byteArrayHeader: JByteArray);
procedure Java_Event_pOnBluetoothClientSocketDisconnected(env: PJNIEnv; this: jobject; Obj: TObject);
function Java_Event_pOnBluetoothServerSocketConnected(env: PJNIEnv; this: jobject; Obj: TObject; deviceName: JString; deviceAddress: JString): JBoolean;
function Java_Event_pOnBluetoothServerSocketIncomingData(env: PJNIEnv; this: jobject; Obj: TObject; byteArrayData: JByteArray; byteArrayHeader: JByteArray): JBoolean;
procedure Java_Event_pOnBluetoothServerSocketListen(env: PJNIEnv; this: jobject; Obj: TObject; serverName: JString; strUUID: JString);
procedure Java_Event_pOnBluetoothServerSocketAcceptTimeout(env: PJNIEnv; this: jobject; Obj: TObject);
procedure Java_Event_pOnSpinnerItemSelected(env: PJNIEnv; this: jobject; Obj: TObject; position: integer; caption: JString);
procedure Java_Event_pOnLocationChanged(env: PJNIEnv; this: jobject; Obj: TObject; latitude: JDouble; longitude: JDouble; altitude: JDouble; address: JString);
procedure Java_Event_pOnLocationStatusChanged(env: PJNIEnv; this: jobject; Obj: TObject; status: integer; provider: JString; msgStatus: JString);
procedure Java_Event_pOnLocationProviderEnabled(env: PJNIEnv; this: jobject; Obj: TObject; provider:JString);
procedure Java_Event_pOnLocationProviderDisabled(env: PJNIEnv; this: jobject; Obj: TObject; provider: JString);
procedure Java_Event_pOnGpsStatusChanged(env: PJNIEnv; this: jobject; Obj: TObject; countSatellites: integer; gpsStatusEvent: integer);
Procedure Java_Event_pOnActionBarTabSelected(env: PJNIEnv; this: jobject; Obj: TObject; view: jObject; title: jString);
Procedure Java_Event_pOnActionBarTabUnSelected(env: PJNIEnv; this: jobject; Obj: TObject; view:jObject; title: jString);
Procedure Java_Event_pOnCustomDialogShow(env: PJNIEnv; this: jobject; Obj: TObject; dialog:jObject; title: jString);
Procedure Java_Event_pOnCustomDialogBackKeyPressed(env: PJNIEnv; this: jobject; Obj: TObject; title: jString);
Procedure Java_Event_pOnClickToggleButton(env: PJNIEnv; this: jobject; Obj: TObject; state: jboolean); overload;
Procedure Java_Event_pOnClickToggleButton(env: PJNIEnv; this: jobject; Obj: TObject; state: boolean); overload; //deprecated
procedure Java_Event_pOnLongClickToggleButton(env:PJNIEnv;this:JObject;Sender:TObject;state:jBoolean);
Procedure Java_Event_pOnChangeSwitchButton(env: PJNIEnv; this: jobject; Obj: TObject; state: jboolean); overload;
Procedure Java_Event_pOnChangeSwitchButton(env: PJNIEnv; this: jobject; Obj: TObject; state: boolean); overload; //deprecated
Procedure Java_Event_pOnClickGridItem(env: PJNIEnv; this: jobject; Obj: TObject; position: integer; caption: JString);
Procedure Java_Event_pOnLongClickGridItem(env: PJNIEnv; this: jobject; Obj: TObject; position: integer; caption: JString);
Procedure Java_Event_pOnChangedSensor(env: PJNIEnv; this: jobject; Obj: TObject; sensor: JObject; sensorType: integer; values: JObject; timestamp: jLong);
Procedure Java_Event_pOnListeningSensor(env: PJNIEnv; this: jobject; Obj: TObject; sensor: jObject; sensorType: integer);
Procedure Java_Event_pOnUnregisterListeningSensor(env: PJNIEnv; this: jobject; Obj: TObject; sensorType: integer; sensorName: JString);
Procedure Java_Event_pOnBroadcastReceiver(env: PJNIEnv; this: jobject; Obj: TObject; intent:jObject);
Procedure Java_Event_pOnTimePicker(env: PJNIEnv; this: jobject; Obj: TObject; hourOfDay: integer; minute: integer);
Procedure Java_Event_pOnDatePicker(env: PJNIEnv; this: jobject; Obj: TObject; year: integer; monthOfYear: integer; dayOfMonth: integer);
Procedure Java_Event_pOnShellCommandExecuted(env: PJNIEnv; this: jobject; Obj: TObject; cmdResult: JString);
procedure Java_Event_pOnTCPSocketClientMessageReceived(env: PJNIEnv; this: jobject; Obj: TObject; messageReceived: JString);
procedure Java_Event_pOnTCPSocketClientBytesReceived(env: PJNIEnv; this: jobject; Obj: TObject; byteArrayReceived: JByteArray);
procedure Java_Event_pOnTCPSocketClientConnected(env: PJNIEnv; this: jobject; Obj: TObject);
procedure Java_Event_pOnTCPSocketClientFileSendProgress(env: PJNIEnv; this: jobject; Obj: TObject; filename: JString; sendFileSize: integer; filesize: integer);
procedure Java_Event_pOnTCPSocketClientFileSendFinished(env: PJNIEnv; this: jobject; Obj: TObject; filename: JString; filesize: integer);
procedure Java_Event_pOnTCPSocketClientFileGetProgress(env: PJNIEnv; this: jobject; Obj: TObject; filename: JString; remainingFileSize: integer; filesize: integer);
procedure Java_Event_pOnTCPSocketClientFileGetFinished(env: PJNIEnv; this: jobject; Obj: TObject; filename: JString; filesize: integer);
procedure Java_Event_pOnTCPSocketClientDisConnected(env:PJNIEnv;this:JObject;Sender:TObject);
Procedure Java_Event_pOnMediaPlayerVideoSizeChanged(env: PJNIEnv; this: jobject; Obj: TObject; videoWidth: integer; videoHeight: integer);
Procedure Java_Event_pOnMediaPlayerCompletion(env: PJNIEnv; this: jobject; Obj: TObject);
Procedure Java_Event_pOnMediaPlayerPrepared(env: PJNIEnv; this: jobject; Obj: TObject; videoWidth: integer; videoHeigh: integer);
Procedure Java_Event_pOnMediaPlayerTimedText(env: PJNIEnv; this: jobject; Obj: TObject; timedText: JString);
Procedure Java_Event_pOnSoundPoolLoadComplete(env: PJNIEnv; this: jobject; Obj: TObject; soundId : integer; status: integer);
Procedure Java_Event_pOnSurfaceViewCreated(env: PJNIEnv; this: jobject; Obj: TObject;
surfaceHolder: jObject);
Procedure Java_Event_pOnSurfaceViewDraw (env: PJNIEnv; this: jobject; Obj: TObject; canvas: jObject);
Procedure Java_Event_pOnSurfaceViewChanged(env: PJNIEnv; this: jobject; Obj: TObject; width: integer; height: integer);
procedure Java_Event_pOnSurfaceViewTouch(env: PJNIEnv; this: jobject;
Obj: TObject;
act,cnt: integer; x1,y1,x2,y2 : single);
function Java_Event_pOnSurfaceViewDrawingInBackground(env: PJNIEnv; this: jobject; Obj: TObject; progress: single): JBoolean;
procedure Java_Event_pOnSurfaceViewDrawingPostExecute(env: PJNIEnv; this: jobject; Obj: TObject; progress: single);
procedure Java_Event_pOnDrawingViewTouch(env: PJNIEnv; this: jobject; Obj: TObject; action, countPoints: integer;
arrayX: jObject; arrayY: jObject; flingGesture: integer; pinchZoomGestureState: integer; zoomScaleFactor: single);
procedure Java_Event_pOnDrawingViewDraw(env: PJNIEnv; this: jobject; Obj: TObject; action, countPoints: integer;
arrayX: jObject; arrayY: jObject; flingGesture: integer; pinchZoomGestureState: integer; zoomScaleFactor: single);
procedure Java_Event_pOnDrawingViewSizeChanged(env: PJNIEnv; this: jobject; Obj: TObject;
width: integer; height: integer; oldWidth: integer; oldHeight: integer);
Procedure Java_Event_pOnContactManagerContactsExecuted(env: PJNIEnv; this: jobject; Obj: TObject; count: integer);
function Java_Event_pOnContactManagerContactsProgress(env: PJNIEnv; this: jobject; Obj: TObject; contactInfo: JString;
contactShortInfo: JString;
contactPhotoUriAsString: JString;
contactPhoto: jObject;
progress: integer): jBoolean;
function Java_Event_pOnGridDrawItemCaptionColor(env: PJNIEnv; this: jobject; Obj: TObject; index: integer; caption: JString): JInt;
function Java_Event_pOnGridDrawItemBitmap(env: PJNIEnv; this: jobject; Obj: TObject; index: integer; caption: JString): JObject;
procedure Java_Event_pOnSeekBarProgressChanged(env: PJNIEnv; this: jobject; Obj: TObject; progress: integer; fromUser: jboolean); overload;
procedure Java_Event_pOnSeekBarProgressChanged(env: PJNIEnv; this: jobject; Obj: TObject; progress: integer; fromUser: boolean); overload; //deprecated
procedure Java_Event_pOnSeekBarStartTrackingTouch(env: PJNIEnv; this: jobject; Obj: TObject; progress: integer);
procedure Java_Event_pOnSeekBarStopTrackingTouch(env: PJNIEnv; this: jobject; Obj: TObject; progress: integer);
procedure Java_Event_pOnRatingBarChanged(env: PJNIEnv; this: jobject; Obj: TObject; rating: single);
procedure Java_Event_pRadioGroupCheckedChanged(env: PJNIEnv; this: jobject; Obj: TObject; checkedIndex: integer; checkedCaption: JString);
Procedure Java_Event_pOnClickGeneric(env: PJNIEnv; this: jobject; Obj: TObject);
Procedure Java_Event_pOnClickAutoDropDownItem(env: PJNIEnv; this: jobject; Obj: TObject;index: integer; caption: JString);
procedure Java_Event_pOnChronometerTick(env: PJNIEnv; this: jobject; Obj: TObject; elapsedTimeMillis: JLong);
Procedure Java_Event_pOnNumberPicker(env: PJNIEnv; this: jobject; Obj: TObject; oldValue: integer; newValue: integer);
function Java_Event_pOnUDPSocketReceived(env: PJNIEnv; this: jobject; Obj: TObject;
content: JString; fromIP: JString; fromPort: integer): JBoolean;
procedure Java_Event_pOnFileSelected(env: PJNIEnv; this: jobject; Obj: TObject; path: JString; fileName: JString);
procedure Java_Event_pOnMikrotikAsyncReceive(env: PJNIEnv; this: jobject; Obj: TObject; delimitedContent: JString; delimiter: JString );
Procedure Java_Event_pOnClickComboDropDownItem(env: PJNIEnv; this: jobject; Obj: TObject;
index: integer; caption: JString);
Procedure Java_Event_pOnExpandableListViewChildClick(env: PJNIEnv; this: jobject; Obj: TObject;
groupPosition: integer; groupHeader:JString;
childItemPosition: integer;
childItemCaption: JString);
Procedure Java_Event_pOnExpandableListViewGroupExpand(env: PJNIEnv; this: jobject; Obj: TObject;
groupPosition: integer; groupHeader: JString);
Procedure Java_Event_pOnExpandableListViewGroupCollapse(env: PJNIEnv; this: jobject; Obj: TObject;
groupPosition: integer; groupHeader: JString);
Procedure Java_Event_pOnGL2SurfaceCreate(env: PJNIEnv; this: jobject; Obj: TObject);
Procedure Java_Event_pOnGL2SurfaceChanged(env: PJNIEnv; this: jobject; Obj: TObject; width: integer; height: integer);
Procedure Java_Event_pOnGL2SurfaceDrawFrame(env: PJNIEnv; this: jobject; Obj: TObject);
Procedure Java_Event_pOnGL2SurfaceTouch(env: PJNIEnv; this: jobject; Obj: TObject;
action, countPoints: integer;
arrayX: jObject; arrayY: jObject;
flingGesture: integer; pinchZoomGestureState: integer;
zoomScaleFactor: single);
Procedure Java_Event_pOnGL2SurfaceDestroyed(env: PJNIEnv; this: jobject; Obj: TObject);
Procedure Java_Event_pOnRecyclerViewItemClick(env: PJNIEnv; this: jobject; Obj: TObject; itemIndex: integer);
Procedure Java_Event_pOnRecyclerViewItemLongClick(env: PJNIEnv; this: jobject; Obj: TObject; itemIndex: integer);
Procedure Java_Event_pOnRecyclerViewItemTouchUp(env: PJNIEnv; this: jobject; Obj: TObject; itemIndex: integer);
Procedure Java_Event_pOnRecyclerViewItemTouchDown(env: PJNIEnv; this: jobject; Obj: TObject; itemIndex: integer);
Procedure Java_Event_pOnClickNavigationViewItem(env: PJNIEnv; this: jobject; Obj: TObject; itemIndex: integer; itemCaption: JString);
Procedure Java_Event_pOnClickBottomNavigationViewItem(env: PJNIEnv; this: jobject; Obj: TObject; itemIndex: integer; itemCaption: JString);
Procedure Java_Event_pOnClickTreeViewItem(env: PJNIEnv; this: jobject; Obj: TObject; itemIndex: integer; itemCaption: JString);
Procedure Java_Event_pOnLongClickTreeViewItem(env: PJNIEnv; this: jobject; Obj: TObject; itemIndex: integer; itemCaption: JString);
Procedure Java_Event_pOnSTabSelected(env: PJNIEnv; this: jobject; Obj: TObject; position: integer; title: JString);
Procedure Java_Event_pOnCustomCameraSurfaceChanged(env: PJNIEnv; this: jobject; Obj: TObject; width: integer; height: integer);
Procedure Java_Event_pOnCustomCameraPictureTaken(env: PJNIEnv; this: jobject; Obj: TObject; picture: JObject; fullPath: JString);
Procedure Java_Event_pOnCalendarSelectedDayChange(env: PJNIEnv; this: jobject; Obj: TObject; year: integer; monthOfYear: integer; dayOfMonth: integer);
Procedure Java_Event_pOnSearchViewFocusChange(env: PJNIEnv; this: jobject; Obj: TObject; hasFocus: jBoolean);
Procedure Java_Event_pOnSearchViewQueryTextSubmit(env: PJNIEnv; this: jobject; Obj: TObject; query: JString);
Procedure Java_Event_pOnSearchViewQueryTextChange(env: PJNIEnv; this: jobject; Obj: TObject; newText: JString );
procedure Java_Event_pOnClickX(env:PJNIEnv;this:JObject;Sender:TObject);
Procedure Java_Event_pOnTelephonyCallStateChanged(env: PJNIEnv; this: jobject; Obj: TObject; state: integer; phoneNumber: JString );
Procedure Java_Event_pOnGetUidTotalMobileBytesFinished(env: PJNIEnv; this: jobject; Obj: TObject; bytesResult: jLong; uid:integer );
Procedure Java_Event_pOnGetUidTotalWifiBytesFinished(env: PJNIEnv; this: jobject; Obj: TObject; bytesResult: jLong; uid:integer );
Procedure Java_Event_pOnRecyclerViewItemWidgetClick(env: PJNIEnv; this: jobject; Obj: TObject;
itemIndex: integer; widgetClass: integer;
widgetId: integer; status: integer);
Procedure Java_Event_pOnRecyclerViewItemWidgetLongClick(env: PJNIEnv; this: jobject; Obj: TObject;
itemIndex: integer; widgetClass: integer;
widgetId: integer);
Procedure Java_Event_pOnRecyclerViewItemWidgetTouchUp(env: PJNIEnv; this: jobject; Obj: TObject;
itemIndex: integer; widgetClass: integer;
widgetId: integer);
Procedure Java_Event_pOnRecyclerViewItemWidgetTouchDown(env: PJNIEnv; this: jobject; Obj: TObject;
itemIndex: integer; widgetClass: integer;
widgetId: integer);
Procedure Java_Event_pOnZBarcodeScannerViewResult(env: PJNIEnv; this: jobject; Obj: TObject;
codedata: JString; codetype: integer);
//Procedure Java_Event_pOnZBarcodeScannerViewPictureTaken(env: PJNIEnv; this: jobject; Obj: TObject;
// picture: JObject; fullPath: JString);
//Procedure Java_Event_pOnZBarcodeScannerViewPictureMake(env: PJNIEnv; this: jobject; Obj: TObject);
procedure Java_Event_pOnMidiManagerDeviceAdded(env:PJNIEnv;this:JObject;Sender:TObject;deviceId:integer;deviceName:jString;productId:jString;manufacture:jString);
procedure Java_Event_pOnMidiManagerDeviceRemoved(env:PJNIEnv;this:JObject;Sender:TObject;deviceId:integer;deviceName:jString;productId:jString;manufacture:jString);
function Java_Event_pOnOpenMapViewRoadDraw(env:PJNIEnv;this:JObject;Sender:TObject;roadCode:integer;roadStatus:integer;roadDuration:double;roadDistance:double):jintArray;
procedure Java_Event_pOnOpenMapViewClick(env:PJNIEnv;this:JObject;Sender:TObject;latitude:double;longitude:double);
procedure Java_Event_pOnOpenMapViewLongClick(env:PJNIEnv;this:JObject;Sender:TObject;latitude:double;longitude:double);
procedure Java_Event_pOnOpenMapViewMarkerClick(env:PJNIEnv;this:JObject;Sender:TObject;title:jString;latitude:double;longitude:double);
procedure Java_Event_pOnSignaturePadStartSigning(env:PJNIEnv;this:JObject;Sender:TObject);
procedure Java_Event_pOnSignaturePadSigned(env:PJNIEnv;this:JObject;Sender:TObject);
procedure Java_Event_pOnSignaturePadClear(env:PJNIEnv;this:JObject;Sender:TObject);
procedure Java_Event_pOnGDXFormShow(env:PJNIEnv;this:JObject;Sender:TObject);
procedure Java_Event_pOnGDXFormResize(env:PJNIEnv;this:JObject;Sender:TObject;width:integer;height:integer);
procedure Java_Event_pOnGDXFormRender(env:PJNIEnv;this:JObject;Sender:TObject;deltaTime:single);
procedure Java_Event_pOnGDXFormClose(env:PJNIEnv;this:JObject;Sender:TObject);
procedure Java_Event_pOnGDXFormTouchDown(env:PJNIEnv;this:JObject;Sender:TObject;screenX:integer;screenY:integer;pointer:integer;button:integer);
procedure Java_Event_pOnGDXFormTouchUp(env:PJNIEnv;this:JObject;Sender:TObject;screenX:integer;screenY:integer;pointer:integer;button:integer);
function Java_Event_pOnGDXFormKeyPressed(env:PJNIEnv;this:JObject;Sender:TObject;keyCode:integer):integer;
procedure Java_Event_pOnGDXFormResume(env:PJNIEnv;this:JObject;Sender:TObject);
procedure Java_Event_pOnGDXFormPause(env:PJNIEnv;this:JObject;Sender:TObject);
procedure Java_Event_pOnGDXFormHide(env:PJNIEnv;this:JObject;Sender:TObject);
procedure Java_Event_pOnMailMessagesCount(env:PJNIEnv;this:JObject;Sender:TObject;count:integer);
procedure Java_Event_pOnMailMessageRead(env:PJNIEnv;this:JObject;Sender:TObject;position:integer;Header:jString;Date:jString;Subject:jString;ContentType:jString;ContentText:jString;Attachments:jString);
procedure Java_Event_pOnSFTPClientTryConnect(env:PJNIEnv;this:JObject;Sender:TObject;success:jBoolean);
procedure Java_Event_pOnSFTPClientDownloadFinished(env:PJNIEnv;this:JObject;Sender:TObject;destination:jString;success:jBoolean);
procedure Java_Event_pOnSFTPClientUploadFinished(env:PJNIEnv;this:JObject;Sender:TObject;destination:jString;success:jBoolean);
procedure Java_Event_pOnSFTPClientListing(env:PJNIEnv;this:JObject;Sender:TObject;remotePath:jString;fileName:jString;fileSize:integer);
procedure Java_Event_pOnSFTPClientListed(env:PJNIEnv;this:JObject;Sender:TObject;count:integer);
procedure Java_Event_pOnFTPClientTryConnect(env:PJNIEnv;this:JObject;Sender:TObject;success:jBoolean);
procedure Java_Event_pOnFTPClientDownloadFinished(env:PJNIEnv;this:JObject;Sender:TObject;destination:jString;success:jBoolean);
procedure Java_Event_pOnFTPClientUploadFinished(env:PJNIEnv;this:JObject;Sender:TObject;destination:jString;success:jBoolean);
procedure Java_Event_pOnFTPClientListing(env:PJNIEnv;this:JObject;Sender:TObject;remotePath:jString;fileName:jString;fileSize:integer);
procedure Java_Event_pOnFTPClientListed(env:PJNIEnv;this:JObject;Sender:TObject;count:integer);
procedure Java_Event_pOnBluetoothSPPDataReceived(env:PJNIEnv;this:JObject;Sender:TObject;jbyteArrayData:jbyteArray;messageData:jString);
procedure Java_Event_pOnBluetoothSPPDeviceConnected(env:PJNIEnv;this:JObject;Sender:TObject;deviceName:jString;deviceAddress:jString);
procedure Java_Event_pOnBluetoothSPPDeviceDisconnected(env:PJNIEnv;this:JObject;Sender:TObject);
procedure Java_Event_pOnBluetoothSPPDeviceConnectionFailed(env:PJNIEnv;this:JObject;Sender:TObject);
procedure Java_Event_pOnBluetoothSPPServiceStateChanged(env:PJNIEnv;this:JObject;Sender:TObject;serviceState:integer);
procedure Java_Event_pOnBluetoothSPPListeningNewAutoConnection(env:PJNIEnv;this:JObject;Sender:TObject;deviceName:jString;deviceAddress:jString);
procedure Java_Event_pOnBluetoothSPPAutoConnectionStarted(env:PJNIEnv;this:JObject;Sender:TObject);
procedure Java_Event_pOnDirectorySelected(env:PJNIEnv;this:JObject;Sender:TObject;path:jString);
procedure Java_Event_pOnMsSqlJDBCConnectionExecuteQueryAsync(env:PJNIEnv;this:JObject;Sender:TObject;messageStatus:jString);
procedure Java_Event_pOnMsSqlJDBCConnectionOpenAsync(env:PJNIEnv;this:JObject;Sender:TObject;messageStatus:jString);
procedure Java_Event_pOnMsSqlJDBCConnectionExecuteUpdateAsync(env:PJNIEnv;this:JObject;Sender:TObject;messageStatus:jString);
procedure Java_Event_pOnBeginOfSpeech(env:PJNIEnv;this:JObject;Sender:TObject);
procedure Java_Event_pOnSpeechBufferReceived(env:PJNIEnv;this:JObject;Sender:TObject;txtBytes:jbyteArray);
procedure Java_Event_pOnEndOfSpeech(env:PJNIEnv;this:JObject;Sender:TObject);
procedure Java_Event_pOnSpeechResults(env:PJNIEnv;this:JObject;Sender:TObject;txt:jString);
//by Marco Bramardi
procedure Java_Event_pOnBillingClientEvent(env:PJNIEnv; this:JObject; Obj: TObject; xml: JString);
//jcToyTimerService
procedure Java_Event_pOnToyTimerServicePullElapsedTime(env:PJNIEnv;this:JObject;Sender:TObject;elapsedTime:int64);
procedure Java_Event_pOnBluetoothLEConnected(env:PJNIEnv;this:JObject;Sender:TObject;deviceName:jString;deviceAddress:jString;bondState:integer);
procedure Java_Event_pOnBluetoothLEScanCompleted(env:PJNIEnv;this:JObject;Sender:TObject;deviceNameArray:jstringArray;deviceAddressArray:jstringArray);
procedure Java_Event_pOnBluetoothLEServiceDiscovered(env:PJNIEnv;this:JObject;Sender:TObject;serviceIndex:integer;serviceUUID:jString;characteristicUUIDArray:jstringArray);
procedure Java_Event_pOnBluetoothLECharacteristicChanged(env:PJNIEnv;this:JObject;Sender:TObject;strValue:jString;strCharacteristic:jString);
procedure Java_Event_pOnBluetoothLECharacteristicRead(env:PJNIEnv;this:JObject;Sender:TObject;strValue:jString;strCharacteristic:jString);
//jsFirebasePushNotificationListener
procedure Java_Event_pOnGetTokenComplete(env:PJNIEnv;this:JObject;Sender:TObject;token:jString;isSuccessful:jBoolean;statusMessage:jString);
//jBatteryManager
procedure Java_Event_pOnBatteryCharging(env:PJNIEnv;this:JObject;Sender:TObject;batteryAtPercentLevel:integer;pluggedBy:integer);
procedure Java_Event_pOnBatteryDisCharging(env:PJNIEnv;this:JObject;Sender:TObject;batteryAtPercentLevel:integer);
procedure Java_Event_pOnBatteryFull(env:PJNIEnv;this:JObject;Sender:TObject;batteryAtPercentLevel:integer);
procedure Java_Event_pOnBatteryUnknown(env:PJNIEnv;this:JObject;Sender:TObject;batteryAtPercentLevel:integer);
procedure Java_Event_pOnBatteryNotCharging(env:PJNIEnv;this:JObject;Sender:TObject;batteryAtPercentLevel:integer);
//jModbus
procedure Java_Event_pOnModbusConnect(env:PJNIEnv;this:JObject;Sender:TObject;success:jBoolean;msg:jString);
// jcWebSocketClient
procedure Java_Event_pWebSocketClientOnOpen(env:PJNIEnv;this:JObject;Sender:TObject);
procedure Java_Event_pWebSocketClientOnTextReceived(env:PJNIEnv;this:JObject;Sender:TObject;msgContent:jString);
procedure Java_Event_pWebSocketClientOnBinaryReceived(env:PJNIEnv;this:JObject;Sender:TObject;data:jbyteArray);
procedure Java_Event_pWebSocketClientOnPingReceived(env:PJNIEnv;this:JObject;Sender:TObject;data:jbyteArray);
procedure Java_Event_pWebSocketClientOnPongReceived(env:PJNIEnv;this:JObject;Sender:TObject;data:jbyteArray);
procedure Java_Event_pWebSocketClientOnException(env:PJNIEnv;this:JObject;Sender:TObject;exceptionMessage:jString);
procedure Java_Event_pWebSocketClientOnCloseReceived(env:PJNIEnv;this:JObject;Sender:TObject);
implementation
uses
AndroidWidget, bluetooth, bluetoothclientsocket, bluetoothserversocket,
spinner, location, actionbartab, customdialog, togglebutton, switchbutton, gridview,
sensormanager, broadcastreceiver, datepickerdialog, timepickerdialog, shellcommand,
tcpsocketclient, surfaceview, mediaplayer, contactmanager, seekbar, ratingbar,
radiogroup, drawingview, autocompletetextview, chronometer, numberpicker,
udpsocket, opendialog, comboedittext,toolbar, expandablelistview, gl2surfaceview,
sfloatingbutton, framelayout,stoolbar, snavigationview, srecyclerview, sbottomnavigationview,
stablayout, treelistview, customcamera, calendarview, searchview, telephonymanager,
sadmob, zbarcodescannerview, cmikrotikrouteros, scontinuousscrollableimageview,
midimanager, copenmapview, csignaturepad, soundpool, gdxform, cmail, sftpclient,
ftpclient, cbluetoothspp, selectdirectorydialog, mssqljdbcconnection, customspeechtotext,
cbillingclient, ctoytimerservice, bluetoothlowenergy,
sfirebasepushnotificationlistener, batterymanager, modbus, cwebsocketclient;
function GetString(env: PJNIEnv; jstr: JString): string;
var
_jBoolean: JBoolean;
begin
Result := '';
if jstr <> nil then
begin
_jBoolean:= JNI_False;
Result:= string(env^.GetStringUTFChars(env,jstr,@_jBoolean) );
end;
end;
function GetJString(env: PJNIEnv; str: string): JString;
begin
Result:= env^.NewStringUTF(env, PChar(str));
end;
function GetDynArrayOfString(env: PJNIEnv; stringArrayData: jstringArray): TDynArrayOfString;
var
jstr: JString;
jBoo: JBoolean;
sizeArray: integer;
i: integer;
begin
Result := nil;
sizeArray:= env^.GetArrayLength(env, stringArrayData);
SetLength(Result, sizeArray);
for i:= 0 to sizeArray - 1 do
begin
jstr:= env^.GetObjectArrayElement(env, stringArrayData, i);
case jstr = nil of
True : Result[i]:= '';
False: begin
jBoo:= JNI_False;
Result[i]:= string(env^.GetStringUTFChars(env,jstr, @jBoo));
end;
end;
end;
end;
function GetDynArrayOfSingle(env: PJNIEnv; floatArrayData: jfloatArray): TDynArrayOfSingle;
var
sizeArray: integer;
begin
Result := nil;
sizeArray:= env^.GetArrayLength(env, floatArrayData);
SetLength(Result, sizeArray);
env^.GetFloatArrayRegion(env, floatArrayData, 0, sizeArray, @Result[0] {target});
end;
function GetDynArrayOfDouble(env: PJNIEnv; doubleArrayData: jfloatArray): TDynArrayOfDouble;
var
sizeArray: integer;
begin
Result := nil;
sizeArray:= env^.GetArrayLength(env, doubleArrayData);
SetLength(Result, sizeArray);
env^.GetDoubleArrayRegion(env, doubleArrayData, 0, sizeArray, @Result[0] {target});
end;
function GetDynArrayOfInteger(env: PJNIEnv; intArrayData: jintArray): TDynArrayOfInteger;
var
sizeArray: integer;
begin
Result := nil;
sizeArray:= env^.GetArrayLength(env, intArrayData);
SetLength(Result, sizeArray);
env^.GetIntArrayRegion(env, intArrayData, 0, sizeArray, @Result[0] {target});
end;
function GetDynArrayOfJByte(env: PJNIEnv; byteArrayData: jbytearray): TDynArrayOfJByte;
var
sizeArray: integer;
begin
Result := nil;
sizeArray:= env^.GetArrayLength(env, byteArrayData);
SetLength(Result, sizeArray);
env^.GetByteArrayRegion(env, byteArrayData, 0, sizeArray, @Result[0] {target});
end;
//-------------
function GetJObjectOfDynArrayOfJByte(env: PJNIEnv; var dataContent: TDynArrayOfJByte):jbyteArray; //jObject;
var
newSize0: integer;
begin
Result:= nil;
newSize0:= Length(dataContent);
Result:= env^.NewByteArray(env, newSize0); // allocate
env^.SetByteArrayRegion(env, Result, 0 , newSize0, @dataContent[0] {source});
end;
function GetJObjectOfDynArrayOfSingle(env: PJNIEnv; var dataContent: TDynArrayOfSingle):jfloatArray; // jObject;
var
newSize0: integer;
begin
Result:= nil;
newSize0:= Length(dataContent);
Result:= env^.NewFloatArray(env, newSize0); // allocate
env^.SetFloatArrayRegion(env, Result, 0 , newSize0, @dataContent[0] {source});
end;
function GetJObjectOfDynArrayOfDouble(env: PJNIEnv; var dataContent: TDynArrayOfDouble):jdoubleArray; // jObject;
var
newSize0: integer;
begin
Result:= nil;
newSize0:= Length(dataContent);
Result:= env^.NewDoubleArray(env, newSize0); // allocate
env^.SetDoubleArrayRegion(env, Result, 0 , newSize0, @dataContent[0] {source});
end;
function GetJObjectOfDynArrayOfInteger(env: PJNIEnv; var dataContent: TDynArrayOfInteger):jintArray; // jObject;
var
newSize0: integer;
begin
Result:= nil;
newSize0:= Length(dataContent);
Result:= env^.NewIntArray(env, newSize0); // allocate
env^.SetIntArrayRegion(env, Result, 0 , newSize0, @dataContent[0] {source});
end;
function GetJObjectOfDynArrayOfString(env: PJNIEnv; var dataContent: TDynArrayOfString): jstringArray; // jObject;
var
newSize0: integer;
i: integer;
begin
Result:= nil;
newSize0:= Length(dataContent);
Result:= env^.NewObjectArray(env, newSize0, env^.FindClass(env,'java/lang/String'),env^.NewStringUTF(env, PChar('')));
for i:= 0 to newSize0 - 1 do
begin
env^.SetObjectArrayElement(env,Result,i,env^.NewStringUTF(env, PChar(dataContent[i])));
end;
end;
//--------
procedure Java_Event_pOnBluetoothEnabled(env: PJNIEnv; this: jobject; Obj: TObject);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jBluetooth then
begin
jBluetooth(Obj).GenEvent_OnBluetoothEnabled(Obj);
end;
end;
procedure Java_Event_pOnBluetoothDisabled(env: PJNIEnv; this: jobject; Obj: TObject);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jBluetooth then
begin
jBluetooth(Obj).GenEvent_OnBluetoothDisabled(Obj);
end;
end;
Procedure Java_Event_pOnBluetoothDeviceFound(env: PJNIEnv; this: jobject; Obj: TObject; deviceName: JString; deviceAddress: JString );
var
pasStrName, pasStrAddress: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jBluetooth then
begin
pasStrName := '';
if deviceName <> nil then
begin
_jBoolean:= JNI_False;
pasStrName:= string( env^.GetStringUTFChars(Env,deviceName,@_jBoolean) );
end;
pasStrAddress := '';
if deviceAddress <> nil then
begin
_jBoolean := JNI_False;
pasStrAddress:= string( env^.GetStringUTFChars(Env,deviceAddress,@_jBoolean) );
end;
jBluetooth(Obj).GenEvent_OnBluetoothDeviceFound(Obj, pasStrName, pasStrAddress);
end;
end;
procedure Java_Event_pOnBluetoothDiscoveryStarted(env: PJNIEnv; this: jobject; Obj: TObject);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jBluetooth then
begin
jBluetooth(Obj).GenEvent_OnBluetoothDiscoveryStarted(Obj);
end;
end;
procedure Java_Event_pOnBluetoothDiscoveryFinished(env: PJNIEnv; this: jobject; Obj: TObject; countFoundedDevices: integer; countPairedDevices: integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jBluetooth then
begin
jBluetooth(Obj).GenEvent_OnBluetoothDiscoveryFinished(Obj, countFoundedDevices, countPairedDevices);
end;
end;
procedure Java_Event_pOnBluetoothDeviceBondStateChanged(env: PJNIEnv; this: jobject; Obj: TObject; state: integer; deviceName: JString; deviceAddress: JString);
var
pasStrName, pasStrAddress: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jBluetooth then
begin
pasStrName := '';
if deviceName <> nil then
begin
_jBoolean:= JNI_False;
pasStrName:= string( env^.GetStringUTFChars(Env,deviceName,@_jBoolean) );
end;
pasStrAddress := '';
if deviceAddress <> nil then
begin
_jBoolean := JNI_False;
pasStrAddress:= string( env^.GetStringUTFChars(Env,deviceAddress,@_jBoolean) );
end;
jBluetooth(Obj).GenEvent_OnBluetoothDeviceBondStateChanged(Obj, state, pasStrName, pasStrAddress);
end;
end;
procedure Java_Event_pOnBluetoothClientSocketIncomingData(env: PJNIEnv; this: jobject; Obj: TObject; byteArrayData: JByteArray; byteArrayHeader: JByteArray);
var
sizeArray: integer;
arrayResult: TDynArrayOfJByte; //array of jByte; //shortint
sizeArrayHeader: integer;
arrayResultHeader: TDynArrayOfJByte; //array of jByte; //shortint
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
arrayResult := nil;
arrayResultHeader := nil;
if byteArrayData <> nil then
begin
sizeArray:= env^.GetArrayLength(env, byteArrayData);
SetLength(arrayResult, sizeArray);
env^.GetByteArrayRegion(env, byteArrayData, 0, sizeArray, @arrayResult[0] {target});
end;
if byteArrayHeader <> nil then
begin
sizeArrayHeader:= env^.GetArrayLength(env, byteArrayHeader);
SetLength(arrayResultHeader, sizeArrayHeader);
env^.GetByteArrayRegion(env, byteArrayHeader, 0, sizeArrayHeader, @arrayResultHeader[0] {target});
end;
if Obj is jBluetoothClientSocket then
begin
jBluetoothClientSocket(Obj).GenEvent_OnBluetoothClientSocketIncomingData(Obj, arrayResult, arrayResultHeader);
end;
end;
procedure Java_Event_pOnBluetoothClientSocketConnected(env: PJNIEnv; this: jobject; Obj: TObject; deviceName: JString; deviceAddress: JString);
var
pasStrName, pasStrAddress: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jBluetoothClientSocket then
begin
pasStrName := '';
if deviceName <> nil then
begin
_jBoolean:= JNI_False;
pasStrName:= string( env^.GetStringUTFChars(Env,deviceName,@_jBoolean) );
end;
pasStrAddress := '';
if deviceAddress <> nil then
begin
_jBoolean := JNI_False;
pasStrAddress:= string( env^.GetStringUTFChars(Env,deviceAddress,@_jBoolean) );
end;
jBluetoothClientSocket(Obj).GenEvent_OnBluetoothClientSocketConnected(Obj, pasStrName, pasStrAddress);
end;
end;
procedure Java_Event_pOnBluetoothClientSocketDisconnected(env: PJNIEnv; this: jobject; Obj: TObject);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jBluetoothClientSocket then
begin
jBluetoothClientSocket(Obj).GenEvent_OnBluetoothClientSocketDisconnected(Obj);
end;
end;
function Java_Event_pOnBluetoothServerSocketConnected(env: PJNIEnv; this: jobject; Obj: TObject; deviceName: JString; deviceAddress: JString): JBoolean;
var
pasStrName, pasStrAddress: string;
_jBoolean: JBoolean;
keepConnected: boolean;
begin
keepConnected := true;
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jBluetoothServerSocket then
begin
pasStrName := '';
if deviceName <> nil then
begin
_jBoolean:= JNI_False;
pasStrName:= string( env^.GetStringUTFChars(Env,deviceName,@_jBoolean) );
end;
pasStrAddress := '';
if deviceAddress <> nil then
begin
_jBoolean := JNI_False;
pasStrAddress:= string( env^.GetStringUTFChars(Env,deviceAddress,@_jBoolean) );
end;
jBluetoothServerSocket(Obj).GenEvent_OnBluetoothServerSocketConnected(Obj, pasStrName, pasStrAddress, keepConnected);
end;
Result:= JBool(keepConnected);
end;
function Java_Event_pOnBluetoothServerSocketIncomingData(env: PJNIEnv; this: jobject; Obj: TObject; byteArrayData: JByteArray; byteArrayHeader: JByteArray): JBoolean;
var
sizeArray: integer;
sizeArrayHeader: integer;
arrayResult: TDynArrayOfJByte; //array of jByte; //shortint
arrayResultHeader: TDynArrayOfJByte; //array of jByte; //shortint
keepConnected: boolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
keepConnected := true;
arrayResult := nil;
arrayResultHeader := nil;
if byteArrayData <> nil then
begin
sizeArray:= env^.GetArrayLength(env, byteArrayData);
SetLength(arrayResult, sizeArray);
env^.GetByteArrayRegion(env, byteArrayData, 0, sizeArray, @arrayResult[0] {target});
end;
if byteArrayHeader <> nil then
begin
sizeArrayHeader:= env^.GetArrayLength(env, byteArrayHeader);
SetLength(arrayResultHeader, sizeArrayHeader);
env^.GetByteArrayRegion(env, byteArrayHeader, 0, sizeArrayHeader, @arrayResultHeader[0] {target});
end;
if Obj is jBluetoothServerSocket then
begin
jBluetoothServerSocket(Obj).GenEvent_OnBluetoothServerSocketIncomingData(Obj, arrayResult, arrayResultHeader, keepConnected);
end;
Result:= JBool(keepConnected);
end;
procedure Java_Event_pOnBluetoothServerSocketListen(env: PJNIEnv; this: jobject; Obj: TObject; serverName: JString; strUUID: JString);
var
pasStrName, pasStrAddress: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jBluetoothServerSocket then
begin
pasStrName := '';
if serverName <> nil then
begin
_jBoolean:= JNI_False;
pasStrName:= string( env^.GetStringUTFChars(Env,serverName,@_jBoolean) );
end;
pasStrAddress := '';
if strUUID <> nil then
begin
_jBoolean := JNI_False;
pasStrAddress:= string( env^.GetStringUTFChars(Env,strUUID,@_jBoolean) );
end;
jBluetoothServerSocket(Obj).GenEvent_OnBluetoothServerSocketListen(Obj, pasStrName, pasStrAddress);
end;
end;
procedure Java_Event_pOnBluetoothServerSocketAcceptTimeout(env: PJNIEnv; this: jobject; Obj: TObject);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jBluetoothServerSocket then
begin
jBluetoothServerSocket(Obj).GenEvent_OnBluetoothServerSocketAcceptTimeout(Obj);
end;
end;
procedure Java_Event_pOnAdMobLoaded(env: PJNIEnv; this: jobject; Obj: TObject; admobType: integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if not Assigned(Obj) then Exit;
if Obj is jsAdMob then
begin
jsAdMob(Obj).GenEvent_OnAdMobLoaded(Obj, admobType);
end;
end;
procedure Java_Event_pOnAdMobInitializationComplete(env: PJNIEnv; this: jobject; Obj: TObject);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if not Assigned(Obj) then Exit;
if Obj is jsAdMob then
begin
jsAdMob(Obj).GenEvent_OnAdMobInitializationComplete(Obj);
end;
end;
procedure Java_Event_pOnAdMobClicked(env: PJNIEnv; this: jobject; Obj: TObject; admobType: integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if not Assigned(Obj) then Exit;
if Obj is jsAdMob then
begin
jsAdMob(Obj).GenEvent_OnAdMobClicked(Obj, admobType);
end;
end;
procedure Java_Event_pOnAdMobFailedToLoad(env: PJNIEnv; this: jobject; Obj: TObject; admobType, errorCode: integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if not Assigned(Obj) then Exit;
if Obj is jsAdMob then
begin
jsAdMob(Obj).GenEvent_OnAdMobFailedToLoad(Obj, admobType, errorCode);
end;
end;
procedure Java_Event_pOnAdMobOpened(env: PJNIEnv; this: jobject; Obj: TObject; admobType: integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if not Assigned(Obj) then Exit;
if Obj is jsAdMob then
begin
jsAdMob(Obj).GenEvent_OnAdMobOpened(Obj, admobType);
end;
end;
procedure Java_Event_pOnAdMobClosed(env: PJNIEnv; this: jobject; Obj: TObject; admobType: integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if not Assigned(Obj) then Exit;
if Obj is jsAdMob then
begin
jsAdMob(Obj).GenEvent_OnAdMobClosed(Obj, admobType);
end;
end;
procedure Java_Event_pOnAdMobRewardedUserEarned(env: PJNIEnv; this: jobject; Obj: TObject);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if not Assigned(Obj) then Exit;
if Obj is jsAdMob then
begin
jsAdMob(Obj).GenEvent_OnAdMobRewardedUserEarned(Obj);
end;
end;
procedure Java_Event_pOnAdMobFailedToShow(env: PJNIEnv; this: jobject; Obj: TObject; admobType, errorCode: integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if not Assigned(Obj) then Exit;
if Obj is jsAdMob then
begin
jsAdMob(Obj).GenEvent_OnAdMobFailedToShow(Obj, admobType, errorCode);
end;
end;
procedure Java_Event_pOnSpinnerItemSelected(env: PJNIEnv; this: jobject; Obj: TObject; position: integer; caption: JString);
var
pasCaption: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jSpinner then
begin
pasCaption := '';
if caption <> nil then
begin
_jBoolean:= JNI_False;
pasCaption:= string( env^.GetStringUTFChars(Env,caption,@_jBoolean) );
end;
jSpinner(Obj).GenEvent_OnSpinnerItemSelected(Obj, pasCaption, position);
end;
end;
procedure Java_Event_pOnLocationChanged(env: PJNIEnv; this: jobject; Obj: TObject; latitude: JDouble; longitude: JDouble; altitude: JDouble; address: JString);
var
pasaddress: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jLocation then
begin
pasaddress:='';
if address <> nil then
begin
_jBoolean:= JNI_False;
pasaddress:= string( env^.GetStringUTFChars(Env,address,@_jBoolean) );
end;
jLocation(Obj).GenEvent_OnLocationChanged(Obj, latitude, longitude, altitude, pasaddress);
end;
end;
procedure Java_Event_pOnLocationStatusChanged(env: PJNIEnv; this: jobject; Obj: TObject; status: integer; provider: JString; msgStatus: JString);
var
pasmsgStatus, pasprovider: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jLocation then
begin
pasmsgStatus:= '';
pasprovider:= '';
if provider <> nil then
begin
_jBoolean:= JNI_False;
pasprovider:= string( env^.GetStringUTFChars(Env,provider,@_jBoolean) );
end;
if msgStatus <> nil then
begin
_jBoolean:= JNI_False;
pasmsgStatus:= string( env^.GetStringUTFChars(Env,msgStatus,@_jBoolean) );
end;
jLocation(Obj).GenEvent_OnLocationStatusChanged(Obj, status, pasprovider, pasmsgStatus);
end;
end;
procedure Java_Event_pOnLocationProviderEnabled(env: PJNIEnv; this: jobject; Obj: TObject; provider:JString);
var
pasprovider: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jLocation then
begin
pasprovider := '';
if provider <> nil then
begin
_jBoolean:= JNI_False;
pasprovider:= string( env^.GetStringUTFChars(Env,provider,@_jBoolean) );
end;
jLocation(Obj).GenEvent_OnLocationProviderEnabled(Obj, pasprovider);
end;
end;
procedure Java_Event_pOnLocationProviderDisabled(env: PJNIEnv; this: jobject; Obj: TObject; provider: JString);
var
pasprovider: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jLocation then
begin
pasprovider := '';
if provider <> nil then
begin
_jBoolean:= JNI_False;
pasprovider:= string( env^.GetStringUTFChars(Env,provider,@_jBoolean) );
end;
jLocation(Obj).GenEvent_OnLocationProviderDisabled(Obj, pasprovider);
end;
end;
procedure Java_Event_pOnGpsStatusChanged(env: PJNIEnv; this: jobject; Obj: TObject; countSatellites: integer; gpsStatusEvent: integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jLocation then
begin
jLocation(Obj).GenEvent_OnGpsStatusChanged(Obj, countSatellites, gpsStatusEvent);
end;
end;
Procedure Java_Event_pOnActionBarTabSelected(env: PJNIEnv; this: jobject; Obj: TObject; view: jObject; title: jString);
var
pastitle: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jActionBarTab then
begin
pastitle:= '';
if title <> nil then
begin
_jBoolean:= JNI_False;
pastitle:= string( env^.GetStringUTFChars(Env, title,@_jBoolean) );
end;
jActionBarTab(Obj).GenEvent_OnActionBarTabSelected(Obj, view, pastitle);
end;
end;
Procedure Java_Event_pOnActionBarTabUnSelected(env: PJNIEnv; this: jobject; Obj: TObject; view:jObject; title: jString);
var
pastitle: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jActionBarTab then
begin
pastitle:= '';
if title <> nil then
begin
_jBoolean:= JNI_False;
pastitle:= string(env^.GetStringUTFChars(Env, title,@_jBoolean) );
end;
jActionBarTab(Obj).GenEvent_OnActionBarTabUnSelected(Obj, view, pastitle);
end;
end;
Procedure Java_Event_pOnCustomDialogShow(env: PJNIEnv; this: jobject; Obj: TObject; dialog:jObject; title: jString);
var
pastitle: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jCustomDialog then
begin
pastitle:= '';
if title <> nil then
begin
_jBoolean:= JNI_False;
pastitle:= string(env^.GetStringUTFChars(Env, title,@_jBoolean) );
end;
jCustomDialog(Obj).GenEvent_OnCustomDialogShow(Obj, dialog, pastitle);
end;
end;
Procedure Java_Event_pOnCustomDialogBackKeyPressed(env: PJNIEnv; this: jobject; Obj: TObject; title: jString);
var
pastitle: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jCustomDialog then
begin
pastitle:= '';
if title <> nil then
begin
_jBoolean:= JNI_False;
pastitle:= string(env^.GetStringUTFChars(Env, title,@_jBoolean) );
end;
jCustomDialog(Obj).GenEvent_OnCustomDialogBackKeyPressed(Obj, pastitle);
end;
end;
Procedure Java_Event_pOnClickToggleButton(env: PJNIEnv; this: jobject; Obj: TObject; state: boolean); //deprecated
begin
Java_Event_pOnClickToggleButton(env,this,Obj,JBoolean(state));
end;
Procedure Java_Event_pOnClickToggleButton(env: PJNIEnv; this: jobject; Obj: TObject; state: jboolean);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jToggleButton then
begin
jToggleButton(Obj).GenEvent_OnClickToggleButton(Obj, Boolean(state));
end;
end;
procedure Java_Event_pOnLongClickToggleButton(env:PJNIEnv;this:JObject;Sender:TObject;state:jBoolean);
begin
gApp.Jni.jEnv:= env;
if this <> nil then gApp.Jni.jThis:= this;
if Sender is jToggleButton then
begin
jToggleButton(Sender).GenEvent_OnLongClickToggleButton(Sender,boolean(state));
end;
end;
Procedure Java_Event_pOnChangeSwitchButton(env: PJNIEnv; this: jobject; Obj: TObject; state: boolean); //deprecated
begin
Java_Event_pOnChangeSwitchButton(env,this,Obj,JBoolean(state));
end;
Procedure Java_Event_pOnChangeSwitchButton(env: PJNIEnv; this: jobject; Obj: TObject; state: jboolean);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jSwitchButton then
begin
jSwitchButton(Obj).GenEvent_OnChangeSwitchButton(Obj, Boolean(state));
end;
end;
Procedure Java_Event_pOnClickGridItem(env: PJNIEnv; this: jobject; Obj: TObject; position: integer; caption: JString);
var
pasCaption: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jGridView then
begin
pasCaption:= '';
if caption <> nil then
begin
_jBoolean:= JNI_False;
pasCaption:= string(env^.GetStringUTFChars(Env, caption,@_jBoolean) );
end;
jGridView(Obj).GenEvent_OnClickGridItem(Obj, position, pasCaption);
end;
end;
Procedure Java_Event_pOnLongClickGridItem(env: PJNIEnv; this: jobject; Obj: TObject; position: integer; caption: JString);
var
pasCaption: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jGridView then
begin
pasCaption:= '';
if caption <> nil then
begin
_jBoolean:= JNI_False;
pasCaption:= string(env^.GetStringUTFChars(Env, caption,@_jBoolean) );
end;
jGridView(Obj).GenEvent_OnLongClickGridItem(Obj, position, pasCaption);
end;
end;
Procedure Java_Event_pOnChangedSensor(env: PJNIEnv; this: jobject; Obj: TObject; sensor: JObject; sensorType: integer; values: JObject; timestamp: jLong);
var
sizeArray: integer;
arrayResult: array of single;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
arrayResult := nil;
if values <> nil then
begin
sizeArray:= env^.GetArrayLength(env, values);
SetLength(arrayResult, sizeArray);
env^.GetFloatArrayRegion(env, values, 0, sizeArray, @arrayResult[0] {target});
end;
if Obj is jSensorManager then
begin
jSensorManager(Obj).GenEvent_OnChangedSensor(Obj, sensor, sensorType, arrayResult, timestamp{sizeArray});
end;
end;
Procedure Java_Event_pOnListeningSensor(env: PJNIEnv; this: jobject; Obj: TObject; sensor: jObject; sensorType: integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jSensorManager then
begin
jSensorManager(Obj).GenEvent_OnListeningSensor(Obj, sensor, sensorType);
end;
end;
Procedure Java_Event_pOnUnregisterListeningSensor(env: PJNIEnv; this: jobject; Obj: TObject; sensorType: integer; sensorName: JString);
var
pasSensorName: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jSensorManager then
begin
pasSensorName:= '';
if sensorName <> nil then
begin
_jBoolean:= JNI_False;
pasSensorName:= string(env^.GetStringUTFChars(Env, sensorName,@_jBoolean) );
end;
jSensorManager(Obj).GenEvent_OnUnregisterListeningSensor(Obj, sensorType, pasSensorName);
end;
end;
Procedure Java_Event_pOnBroadcastReceiver(env: PJNIEnv; this: jobject; Obj: TObject; intent:jObject);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jBroadcastReceiver then
begin
jBroadcastReceiver(Obj).GenEvent_OnBroadcastReceiver(Obj, intent);
end;
end;
Procedure Java_Event_pOnTimePicker(env: PJNIEnv; this: jobject; Obj: TObject; hourOfDay: integer; minute: integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jTimePickerDialog then
begin
jTimePickerDialog(Obj).GenEvent_OnTimePicker(Obj, hourOfDay, minute);
end;
end;
Procedure Java_Event_pOnDatePicker(env: PJNIEnv; this: jobject; Obj: TObject; year: integer; monthOfYear: integer; dayOfMonth: integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jDatePickerDialog then
begin
jDatePickerDialog(Obj).GenEvent_OnDatePicker(Obj, year, monthOfYear, dayOfMonth);
end;
end;
Procedure Java_Event_pOnCalendarSelectedDayChange(env: PJNIEnv; this: jobject; Obj: TObject; year: integer; monthOfYear: integer; dayOfMonth: integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jCalendarView then
begin
jCalendarView(Obj).GenEvent_OnSelectedDayChange(Obj, year, monthOfYear, dayOfMonth);
end;
end;
Procedure Java_Event_pOnShellCommandExecuted(env: PJNIEnv; this: jobject; Obj: TObject; cmdResult: JString);
var
pascmdResult: string;
jBoo: jBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jShellCommand then
begin
pascmdResult := '';
if cmdResult <> nil then
begin
jBoo := JNI_False;
pascmdResult:= string( env^.GetStringUTFChars(Env,cmdResult,@jBoo) );
end;
jShellCommand(Obj).GenEvent_OnShellCommandExecuted(Obj, pascmdResult);
end;
end;
Procedure Java_Event_pOnTCPSocketClientMessageReceived(env: PJNIEnv; this: jobject; Obj: TObject; messageReceived: JString);
var
pasMessageReceived: string;
jBoo: jBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jTCPSocketClient then
begin
pasMessageReceived := '';
if messageReceived <> nil then
begin
jBoo := JNI_False;
pasMessageReceived:= string( env^.GetStringUTFChars(Env,messageReceived,@jBoo) );
end;
jTCPSocketClient(Obj).GenEvent_OnTCPSocketClientMessagesReceived(Obj, pasMessageReceived);
end;
end;
Procedure Java_Event_pOnTCPSocketClientBytesReceived(env: PJNIEnv; this: jobject; Obj: TObject; byteArrayReceived: JByteArray);
var
sizeArray: integer;
arrayResult: TDynArrayOfJByte; //array of jByte; //shortint
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
arrayResult := nil;
if byteArrayReceived <> nil then
begin
sizeArray:= env^.GetArrayLength(env, byteArrayReceived);
SetLength(arrayResult, sizeArray);
env^.GetByteArrayRegion(env, byteArrayReceived, 0, sizeArray, @arrayResult[0] {target});
end;
if Obj is jTCPSocketClient then
begin
jTCPSocketClient(Obj).GenEvent_OnTCPSocketClientBytesReceived(Obj, arrayResult);
end;
end;
Procedure Java_Event_pOnTCPSocketClientConnected(env: PJNIEnv; this: jobject; Obj: TObject);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jTCPSocketClient then
begin
jTCPSocketClient(Obj).GenEvent_OnTCPSocketClientConnected(Obj);
end;
end;
Procedure Java_Event_pOnTCPSocketClientFileSendProgress(env: PJNIEnv; this: jobject; Obj: TObject; filename: JString; sendFileSize: integer; filesize: integer);
var
pasfilename: string;
jBoo: jBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jTCPSocketClient then
begin
pasfilename := '';
if filename <> nil then
begin
jBoo := JNI_False;
pasfilename:= string( env^.GetStringUTFChars(Env,filename,@jBoo) );
end;
jTCPSocketClient(Obj).GenEvent_OnTCPSocketClientFileSendProgress(Obj, pasfilename, sendFileSize, filesize);
end;
end;
Procedure Java_Event_pOnTCPSocketClientFileSendFinished(env: PJNIEnv; this: jobject; Obj: TObject; filename: JString; filesize: integer);
var
pasfilename: string;
jBoo: jBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jTCPSocketClient then
begin
pasfilename := '';
if filename <> nil then
begin
jBoo := JNI_False;
pasfilename:= string( env^.GetStringUTFChars(Env,filename,@jBoo) );
end;
jTCPSocketClient(Obj).GenEvent_pOnTCPSocketClientFileSendFinished(Obj, pasfilename, filesize);
end;
end;
procedure Java_Event_pOnTCPSocketClientFileGetProgress(env: PJNIEnv; this: jobject; Obj: TObject; filename: JString; remainingFileSize: integer; filesize: integer);
var
pasfilename: string;
jBoo: jBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jTCPSocketClient then
begin
pasfilename := '';
if filename <> nil then
begin
jBoo := JNI_False;
pasfilename:= string( env^.GetStringUTFChars(Env,filename,@jBoo) );
end;
jTCPSocketClient(Obj).GenEvent_OnTCPSocketClientFileGetProgress(Obj, pasfilename, remainingFileSize, filesize);
end;
end;
procedure Java_Event_pOnTCPSocketClientFileGetFinished(env: PJNIEnv; this: jobject; Obj: TObject; filename: JString; filesize: integer);
var
pasfilename: string;
jBoo: jBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jTCPSocketClient then
begin
pasfilename := '';
if filename <> nil then
begin
jBoo := JNI_False;
pasfilename:= string( env^.GetStringUTFChars(Env,filename,@jBoo) );
end;
jTCPSocketClient(Obj).GenEvent_pOnTCPSocketClientFileGetFinished(Obj, pasfilename, filesize);
end;
end;
procedure Java_Event_pOnTCPSocketClientDisConnected(env:PJNIEnv;this:JObject;Sender:TObject);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jTCPSocketClient then
begin
jTCPSocketClient(Sender).GenEvent_OnTCPSocketClientDisConnected(Sender);
end;
end;
Procedure Java_Event_pOnSurfaceViewCreated(env: PJNIEnv; this: jobject; Obj: TObject;
surfaceHolder: jObject);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jSurfaceView then
begin
jSurfaceView(Obj).GenEvent_OnSurfaceViewCreated(Obj,surfaceHolder);
end;
end;
Procedure Java_Event_pOnSurfaceViewDraw (env: PJNIEnv; this: jobject; Obj: TObject; canvas: jObject);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jSurfaceView then
begin
jSurfaceView(Obj).GenEvent_OnSurfaceViewDraw(Obj, canvas);
end;
end;
Procedure Java_Event_pOnMediaPlayerPrepared(env: PJNIEnv; this: jobject; Obj: TObject; videoWidth: integer; videoHeigh: integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jMediaPlayer then
begin
jMediaPlayer(Obj).GenEvent_OnPrepared(Obj, videoWidth, videoHeigh);
end;
end;
Procedure Java_Event_pOnMediaPlayerVideoSizeChanged(env: PJNIEnv; this: jobject; Obj: TObject; videoWidth: integer; videoHeight: integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jMediaPlayer then
begin
jMediaPlayer(Obj).GenEvent_OnVideoSizeChanged(Obj, videoWidth, videoHeight);
end;
end;
Procedure Java_Event_pOnMediaPlayerCompletion(env: PJNIEnv; this: jobject; Obj: TObject);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jMediaPlayer then
begin
jMediaPlayer(Obj).GenEvent_OnCompletion(Obj);
end;
end;
Procedure Java_Event_pOnMediaPlayerTimedText(env: PJNIEnv; this: jobject; Obj: TObject; timedText: JString);
var
pastimedText: string;
jBoo: jBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jMediaPlayer then
begin
pastimedText := '';
if timedText <> nil then
begin
jBoo := JNI_False;
pastimedText:= string( env^.GetStringUTFChars(Env,timedText,@jBoo) );
end;
jMediaPlayer(Obj).GenEvent_pOnMediaPlayerTimedText(Obj, pastimedText);
end;
end;
Procedure Java_Event_pOnSoundPoolLoadComplete(env: PJNIEnv; this: jobject; Obj: TObject; soundId : integer; status: integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jSoundPool then
begin
jSoundPool(Obj).GenEvent_OnLoadComplete(Obj, soundId, status);
end;
end;
procedure Java_Event_pOnSurfaceViewTouch(env: PJNIEnv; this: jobject;
Obj: TObject;
act,cnt: integer; x1,y1,x2,y2 : single);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if not Assigned(Obj) then Exit;
if Obj is jSurfaceView then
begin
jSurfaceView(Obj).GenEvent_OnSurfaceViewTouch(Obj,act,cnt,x1,y1,x2,y2);
end;
end;
Procedure Java_Event_pOnSurfaceViewChanged(env: PJNIEnv; this: jobject;
Obj: TObject; width: integer; height: integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jSurfaceView then
begin
jSurfaceView(Obj).GenEvent_OnSurfaceViewChanged(Obj, width, height);
end;
end;
function Java_Event_pOnSurfaceViewDrawingInBackground(env: PJNIEnv; this: jobject; Obj: TObject; progress: single): JBoolean;
var
running: boolean;
begin
running:= True;
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if not Assigned(Obj) then Exit;
if Obj is jSurfaceView then
begin
jSurfaceView(Obj).GenEvent_OnSurfaceViewDrawingInBackground(Obj,progress,running);
end;
Result:= JBool(running);
end;
procedure Java_Event_pOnSurfaceViewDrawingPostExecute(env: PJNIEnv; this: jobject; Obj: TObject; progress: single);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if not Assigned(Obj) then Exit;
if Obj is jSurfaceView then
begin
jSurfaceView(Obj).GenEvent_OnSurfaceViewDrawingPostExecute(Obj,progress);
end;
end;
procedure Java_Event_pOnDrawingViewTouch(env: PJNIEnv; this: jobject; Obj: TObject; action, countPoints: integer;
arrayX: jObject; arrayY: jObject; flingGesture: integer; pinchZoomGestureState: integer; zoomScaleFactor: single);
var
sizeArray: integer;
arrayResultX: array of single;
arrayResultY: array of single;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
arrayResultX := nil;
arrayResultY := nil;
if not Assigned(Obj) then Exit;
if Obj is jDrawingView then
begin
sizeArray:= countPoints;
if arrayX <> nil then
begin
//sizeArray:= env^.GetArrayLength(env, arrayX);
SetLength(arrayResultX, sizeArray);
env^.GetFloatArrayRegion(env, arrayX, 0, sizeArray, @arrayResultX[0] {target});
end;
if arrayY <> nil then
begin
//sizeArray:= env^.GetArrayLength(env, arrayX);
SetLength(arrayResultY, sizeArray);
env^.GetFloatArrayRegion(env, arrayY, 0, sizeArray, @arrayResultY[0] {target});
end;
jDrawingView(Obj).GenEvent_OnDrawingViewTouch(Obj,action,countPoints,
arrayResultX,arrayResultY,
flingGesture,pinchZoomGestureState, zoomScaleFactor);
end;
end;
procedure Java_Event_pOnDrawingViewDraw(env: PJNIEnv; this: jobject; Obj: TObject; action, countPoints: integer;
arrayX: jObject; arrayY: jObject; flingGesture: integer; pinchZoomGestureState: integer; zoomScaleFactor: single);
var
sizeArray: integer;
arrayResultX: array of single;
arrayResultY: array of single;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
arrayResultX := nil;
arrayResultY := nil;
if not Assigned(Obj) then Exit;
if Obj is jDrawingView then
begin
sizeArray:= countPoints;
if arrayX <> nil then
begin
//sizeArray:= env^.GetArrayLength(env, arrayX);
SetLength(arrayResultX, sizeArray);
env^.GetFloatArrayRegion(env, arrayX, 0, sizeArray, @arrayResultX[0] {target});
end;
if arrayY <> nil then
begin
//sizeArray:= env^.GetArrayLength(env, arrayX);
SetLength(arrayResultY, sizeArray);
env^.GetFloatArrayRegion(env, arrayY, 0, sizeArray, @arrayResultY[0] {target});
end;
jDrawingView(Obj).GenEvent_OnDrawingViewDraw(Obj,action,countPoints,
arrayResultX,arrayResultY,
flingGesture,pinchZoomGestureState, zoomScaleFactor);
end;
end;
procedure Java_Event_pOnDrawingViewSizeChanged(env: PJNIEnv; this: jobject; Obj: TObject;
width: integer; height: integer; oldWidth: integer; oldHeight: integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if not Assigned(Obj) then Exit;
if Obj is jDrawingView then
begin
jDrawingView(Obj).GenEvent_OnDrawingViewSizeChanged(Obj,width, height, oldWidth, oldHeight);
end;
end;
procedure Java_Event_pOnRatingBarChanged(env: PJNIEnv; this: jobject; Obj: TObject; rating: single);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if not Assigned(Obj) then Exit;
if Obj is jRatingBar then
begin
jRatingBar(Obj).GenEvent_OnRatingBarChanged(Obj,rating);
end;
end;
Procedure Java_Event_pOnContactManagerContactsExecuted(env: PJNIEnv; this: jobject; Obj: TObject; count: integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if not Assigned(Obj) then Exit;
if Obj is jContactManager then
begin
jContactManager(Obj).GenEvent_OnContactManagerContactsExecuted(Obj, count);
end;
end;
function Java_Event_pOnContactManagerContactsProgress(env: PJNIEnv; this: jobject; Obj: TObject; contactInfo: JString;
contactShortInfo: JString;
contactPhotoUriAsString: JString;
contactPhoto: jObject;
progress: integer): jBoolean;
var
pascontact, pascontactShortInfo, pascontactPhotoUriAsString: string;
jBoo: jBoolean;
continueListing: boolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
continueListing:= True;
if Obj is jContactManager then
begin
pascontact := '';
if contactInfo <> nil then
begin
jBoo := JNI_False;
pascontact:= string( env^.GetStringUTFChars(Env,contactInfo,@jBoo) );
end;
pascontactShortInfo := '';
if contactShortInfo <> nil then
begin
jBoo := JNI_False;
pascontactShortInfo:= string( env^.GetStringUTFChars(Env,contactShortInfo,@jBoo) );
end;
pascontactPhotoUriAsString := '';
if contactPhotoUriAsString <> nil then
begin
jBoo := JNI_False;
pascontactPhotoUriAsString:= string( env^.GetStringUTFChars(Env,contactPhotoUriAsString,@jBoo) );
end;
jContactManager(Obj).GenEvent_OnContactManagerContactsProgress(Obj, pascontact, pascontactShortInfo, pascontactPhotoUriAsString, contactPhoto, progress, continueListing);
end;
Result:= JBool(continueListing);
end;
function Java_Event_pOnGridDrawItemCaptionColor(env: PJNIEnv; this: jobject; Obj: TObject; index: integer; caption: JString): JInt;
var
pasCaption: string;
_jBoolean: JBoolean;
outColor: dword;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
outColor:= 0;
if Obj is jGridVIew then
begin
pasCaption := '';
if caption <> nil then
begin
_jBoolean:= JNI_False;
pasCaption:= string( env^.GetStringUTFChars(env,caption,@_jBoolean) );
end;
jGridVIew(Obj).GenEvent_OnDrawItemCaptionColor(Obj, index, pasCaption, outColor);
end;
Result:= outColor;
end;
procedure Java_Event_pRadioGroupCheckedChanged(env: PJNIEnv; this: jobject; Obj: TObject; checkedIndex: integer; checkedCaption: JString);
var
pascheckedCaption: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jRadioGroup then
begin
pascheckedCaption := '';
if checkedCaption <> nil then
begin
_jBoolean:= JNI_False;
pascheckedCaption:= string( env^.GetStringUTFChars(env,checkedCaption,@_jBoolean) );
end;
jRadioGroup(Obj).GenEvent_CheckedChanged(Obj, checkedIndex, pascheckedCaption);
end;
end;
function Java_Event_pOnGridDrawItemBitmap(env: PJNIEnv; this: jobject; Obj: TObject; index: integer; caption: JString): JObject;
var
pasCaption: string;
_jBoolean: JBoolean;
outBitmap: jObject;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
outBitmap:= nil;
if Obj is jGridVIew then
begin
pasCaption := '';
if caption <> nil then
begin
_jBoolean:= JNI_False;
pasCaption:= string( env^.GetStringUTFChars(env,caption,@_jBoolean) );
end;
jGridVIew(Obj).GenEvent_OnDrawItemBitmap(Obj, index, pasCaption, outBitmap);
end;
Result:= outBitmap;
end;
procedure Java_Event_pOnSeekBarProgressChanged(env: PJNIEnv; this: jobject; Obj: TObject; progress: integer; fromUser: boolean); //deprecated
begin
Java_Event_pOnSeekBarProgressChanged(env,this,Obj,progress, JBoolean(fromUser));
end;
procedure Java_Event_pOnSeekBarProgressChanged(env: PJNIEnv; this: jobject; Obj: TObject; progress: integer; fromUser: jboolean);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if not Assigned(Obj) then Exit;
if Obj is jSeekBar then
begin
jSeekBar(Obj).GenEvent_OnSeekBarProgressChanged(Obj, progress, Boolean(fromUser));
end;
end;
procedure Java_Event_pOnSeekBarStartTrackingTouch(env: PJNIEnv; this: jobject; Obj: TObject; progress: integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if not Assigned(Obj) then Exit;
if Obj is jSeekBar then
begin
jSeekBar(Obj).GenEvent_OnSeekBarStartTrackingTouch(Obj, progress);
end;
end;
procedure Java_Event_pOnSeekBarStopTrackingTouch(env: PJNIEnv; this: jobject; Obj: TObject; progress: integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if not Assigned(Obj) then Exit;
if Obj is jSeekBar then
begin
jSeekBar(Obj).GenEvent_OnSeekBarStopTrackingTouch(Obj, progress);
end;
end;
Procedure Java_Event_pOnClickAutoDropDownItem(env: PJNIEnv; this: jobject; Obj: TObject;index: integer; caption: JString);
var
pasCaption: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jAutoTextView then
begin
pasCaption := '';
if caption <> nil then
begin
_jBoolean:= JNI_False;
pasCaption:= string( env^.GetStringUTFChars(env,caption,@_jBoolean) );
end;
jAutoTextView(Obj).GenEvent_OnClickAutoDropDownItem(Obj, index, pasCaption);
end;
end;
Procedure Java_Event_pOnClickComboDropDownItem(env: PJNIEnv; this: jobject; Obj: TObject;index: integer; caption: JString);
var
pasCaption: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jComboEditText then
begin
pasCaption := '';
if caption <> nil then
begin
_jBoolean:= JNI_False;
pasCaption:= string( env^.GetStringUTFChars(env,caption,@_jBoolean) );
end;
jComboEditText(Obj).GenEvent_OnClickComboDropDownItem(Obj, index, pasCaption);
end;
end;
Procedure Java_Event_pOnClickGeneric(env: PJNIEnv; this: jobject; Obj: TObject);
begin
//----update global "gApp": to whom it may concern------
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
//------------------------------------------------------
if not (Assigned(Obj)) then Exit;
if Obj is jAutoTextView then
begin
jAutoTextView(Obj).GenEvent_OnClick(Obj);
Exit;
end;
if Obj is jChronometer then
begin
jChronometer(Obj).GenEvent_OnClick(Obj);
Exit;
end;
if Obj is jComboEditText then
begin
jComboEditText(Obj).GenEvent_OnClick(Obj);
Exit;
end;
if Obj is jToolbar then
begin
jToolbar(Obj).GenEvent_OnClick(Obj);
Exit;
end;
if Obj is jsToolbar then //android support library...
begin
jsToolbar(Obj).GenEvent_OnClick(Obj);
Exit;
end;
if Obj is jsFloatingButton then //android support library...
begin
jsFloatingButton(Obj).GenEvent_OnClick(Obj);
Exit;
end;
if Obj is jFrameLayout then
begin
jFrameLayout(Obj).GenEvent_OnClick(Obj);
Exit;
end;
if Obj is jSearchView then
begin
jSearchView(Obj).GenEvent_OnClick(Obj);
Exit;
end;
if Obj is jZBarcodeScannerView then
begin
jZBarcodeScannerView(Obj).GenEvent_OnClick(Obj);
Exit;
end;
if Obj is jsContinuousScrollableImageView then
begin
jsContinuousScrollableImageView(Obj).GenEvent_OnClick(Obj);
Exit;
end;
end;
procedure Java_Event_pOnChronometerTick(env: PJNIEnv; this: jobject; Obj: TObject; elapsedTimeMillis: JLong);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jChronometer then
begin
jChronometer(Obj).GenEvent_OnChronometerTick(Obj, int64(elapsedTimeMillis));
end;
end;
Procedure Java_Event_pOnNumberPicker(env: PJNIEnv; this: jobject; Obj: TObject; oldValue: integer; newValue: integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jNumberPickerDialog then
begin
jNumberPickerDialog(Obj).GenEvent_OnNumberPicker(Obj, oldValue, newValue);
end;
end;
function Java_Event_pOnUDPSocketReceived(env: PJNIEnv; this: jobject; Obj: TObject;
content: JString; fromIP: JString; fromPort: integer): JBoolean;
var
pascontent, pasfromIP: string;
jBoo: jBoolean;
outListening: boolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
outListening:= True; //continue listening
if Obj is jUDPSocket then
begin
pascontent := '';
if content <> nil then
begin
jBoo := JNI_False;
pascontent:= string( env^.GetStringUTFChars(Env,content,@jBoo) );
end;
pasfromIP:= '';
if fromIP <> nil then
begin
jBoo := JNI_False;
pasfromIP:= string( env^.GetStringUTFChars(Env,fromIP,@jBoo) );
end;
jUDPSocket(Obj).GenEvent_OnUDPSocketReceived(Obj, pascontent, pasfromIP, fromPort, outListening);
end;
Result:= JBool(outListening);
end;
procedure Java_Event_pOnFileSelected(env: PJNIEnv; this: jobject; Obj: TObject; path: JString; fileName: JString);
var
pasFileName: string;
pasPath: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jOpenDialog then
begin
pasFileName := '';
if fileName <> nil then
begin
_jBoolean:= JNI_False;
pasFileName:= string( env^.GetStringUTFChars(env,fileName,@_jBoolean) );
end;
pasPath := '';
if path <> nil then
begin
_jBoolean:= JNI_False;
pasPath:= string( env^.GetStringUTFChars(env,path,@_jBoolean) );
end;
jOpenDialog(Obj).GenEvent_OnFileSelected(Obj, pasPath, pasFileName);
end;
end;
procedure Java_Event_pOnMikrotikAsyncReceive(env: PJNIEnv; this: jobject; Obj: TObject; delimitedContent: JString; delimiter: JString );
var
pasdelimitedContent: string;
pasdelimiter: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jcMikrotikRouterOS then
begin
pasdelimitedContent:= '';
if delimitedContent <> nil then
begin
_jBoolean:= JNI_False;
pasdelimitedContent:= string( env^.GetStringUTFChars(env,delimitedContent,@_jBoolean) );
end;
pasdelimiter := '';
if delimiter <> nil then
begin
_jBoolean:= JNI_False;
pasdelimiter:= string( env^.GetStringUTFChars(env,delimiter,@_jBoolean) );
end;
jcMikrotikRouterOS(Obj).GenEvent_OnMikrotikAsyncReceive(Obj, pasdelimitedContent, pasdelimiter);
end;
end;
Procedure Java_Event_pOnExpandableListViewGroupExpand(env: PJNIEnv; this: jobject; Obj: TObject;
groupPosition: integer; groupHeader: JString);
var
pasgroupHeader: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jExpandableListView then
begin
pasgroupHeader := '';
if groupHeader <> nil then
begin
_jBoolean:= JNI_False;
pasgroupHeader:= string( env^.GetStringUTFChars(env,groupHeader,@_jBoolean) );
end;
jExpandableListView(Obj).GenEvent_OnGroupExpand(Obj, groupPosition, pasgroupHeader);
end;
end;
Procedure Java_Event_pOnClickNavigationViewItem(env: PJNIEnv; this: jobject; Obj: TObject; itemIndex: integer; itemCaption: JString);
var
pasitemCaption: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jsNavigationView then
begin
pasitemCaption := '';
if itemCaption <> nil then
begin
_jBoolean:= JNI_False;
pasitemCaption:= string( env^.GetStringUTFChars(env,itemCaption,@_jBoolean) );
end;
jsNavigationView(Obj).GenEvent_OnClickNavigationViewItem(Obj, itemIndex, pasitemCaption);
end;
end;
Procedure Java_Event_pOnClickBottomNavigationViewItem(env: PJNIEnv; this: jobject; Obj: TObject; itemIndex: integer; itemCaption: JString);
var
pasitemCaption: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jsBottomNavigationView then
begin
pasitemCaption := '';
if itemCaption <> nil then
begin
_jBoolean:= JNI_False;
pasitemCaption:= string( env^.GetStringUTFChars(env,itemCaption,@_jBoolean) );
end;
jsBottomNavigationView(Obj).GenEvent_OnClickNavigationViewItem(Obj, itemIndex, pasitemCaption);
end;
end;
Procedure Java_Event_pOnClickTreeViewItem(env: PJNIEnv; this: jobject; Obj: TObject; itemIndex: integer; itemCaption: JString);
var
pasitemCaption: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jTreeListView then
begin
pasitemCaption := '';
if itemCaption <> nil then
begin
_jBoolean:= JNI_False;
pasitemCaption:= string( env^.GetStringUTFChars(env,itemCaption,@_jBoolean) );
end;
jTreeListView(Obj).GenEvent_OnClickTreeViewItem(Obj, itemIndex, pasitemCaption);
end;
end;
Procedure Java_Event_pOnLongClickTreeViewItem(env: PJNIEnv; this: jobject; Obj: TObject; itemIndex: integer; itemCaption: JString);
var
pasitemCaption: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jTreeListView then
begin
pasitemCaption := '';
if itemCaption <> nil then
begin
_jBoolean:= JNI_False;
pasitemCaption:= string( env^.GetStringUTFChars(env,itemCaption,@_jBoolean) );
end;
jTreeListView(Obj).GenEvent_OnLongClickTreeViewItem(Obj, itemIndex, pasitemCaption);
end;
end;
Procedure Java_Event_pOnExpandableListViewGroupCollapse(env: PJNIEnv; this: jobject; Obj: TObject;
groupPosition: integer; groupHeader: JString);
var
pasgroupHeader: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jExpandableListView then
begin
pasgroupHeader := '';
if groupHeader <> nil then
begin
_jBoolean:= JNI_False;
pasgroupHeader:= string( env^.GetStringUTFChars(env,groupHeader,@_jBoolean) );
end;
jExpandableListView(Obj).GenEvent_OnGroupCollapse(Obj, groupPosition, pasgroupHeader);
end;
end;
Procedure Java_Event_pOnExpandableListViewChildClick(env: PJNIEnv; this: jobject; Obj: TObject;
groupPosition: integer; groupHeader:JString;
childItemPosition: integer;
childItemCaption: JString);
var
pasgroupHeader: string;
paschildItemCaption: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jExpandableListView then
begin
pasgroupHeader := '';
if groupHeader <> nil then
begin
_jBoolean:= JNI_False;
pasgroupHeader:= string( env^.GetStringUTFChars(env,groupHeader,@_jBoolean) );
end;
paschildItemCaption := '';
if childItemCaption <> nil then
begin
_jBoolean:= JNI_False;
paschildItemCaption:= string( env^.GetStringUTFChars(env,childItemCaption,@_jBoolean) );
end;
jExpandableListView(Obj).GenEvent_OnChildClick(Obj, groupPosition, pasgroupHeader, childItemPosition, paschildItemCaption);
end;
end;
Procedure Java_Event_pOnGL2SurfaceCreate(env: PJNIEnv; this: jobject; Obj: TObject);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jGL2SurfaceView then
begin
jGL2SurfaceView(Obj).GenEvent_OnGL2SurfaceCreate(Obj);
end;
end;
Procedure Java_Event_pOnGL2SurfaceDestroyed(env: PJNIEnv; this: jobject; Obj: TObject);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jGL2SurfaceView then
begin
jGL2SurfaceView(Obj).GenEvent_OnGL2SurfaceDestroyed(Obj);
end;
end;
Procedure Java_Event_pOnGL2SurfaceChanged(env: PJNIEnv; this: jobject; Obj: TObject; width: integer; height: integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jGL2SurfaceView then
begin
jGL2SurfaceView(Obj).GenEvent_OnGL2SurfaceChanged(Obj, width, height);
end;
end;
Procedure Java_Event_pOnGL2SurfaceDrawFrame(env: PJNIEnv; this: jobject; Obj: TObject);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jGL2SurfaceView then
begin
jGL2SurfaceView(Obj).GenEvent_OnGL2SurfaceDrawFrame(Obj);
end;
end;
Procedure Java_Event_pOnGL2SurfaceTouch(env: PJNIEnv; this: jobject; Obj: TObject;
action, countPoints: integer;
arrayX: jObject; arrayY: jObject;
flingGesture: integer; pinchZoomGestureState: integer;
zoomScaleFactor: single);
var
sizeArray: integer;
arrayResultX: array of single;
arrayResultY: array of single;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
arrayResultX := nil;
arrayResultY := nil;
if not Assigned(Obj) then Exit;
if Obj is jGL2SurfaceView then
begin
sizeArray:= countPoints;
if arrayX <> nil then
begin
//sizeArray:= env^.GetArrayLength(env, arrayX);
SetLength(arrayResultX, sizeArray);
env^.GetFloatArrayRegion(env, arrayX, 0, sizeArray, @arrayResultX[0] {target});
end;
if arrayY <> nil then
begin
//sizeArray:= env^.GetArrayLength(env, arrayX);
SetLength(arrayResultY, sizeArray);
env^.GetFloatArrayRegion(env, arrayY, 0, sizeArray, @arrayResultY[0] {target});
end;
jGL2SurfaceView(Obj).GenEvent_OnGL2SurfaceTouch(Obj,action,countPoints,
arrayResultX,arrayResultY,
flingGesture,pinchZoomGestureState, zoomScaleFactor);
end;
end;
//Updated by ADiV
Procedure Java_Event_pOnRecyclerViewItemClick(env: PJNIEnv; this: jobject; Obj: TObject; itemIndex: integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jsRecyclerView then
begin
jsRecyclerView(Obj).GenEvent_OnRecyclerViewItemClick(Obj, itemIndex);
end;
end;
// By ADiV
Procedure Java_Event_pOnRecyclerViewItemLongClick(env: PJNIEnv; this: jobject; Obj: TObject; itemIndex: integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jsRecyclerView then
begin
jsRecyclerView(Obj).GenEvent_OnRecyclerViewItemLongClick(Obj, itemIndex);
end;
end;
// By ADiV
Procedure Java_Event_pOnRecyclerViewItemTouchUp(env: PJNIEnv; this: jobject; Obj: TObject; itemIndex: integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jsRecyclerView then
begin
jsRecyclerView(Obj).GenEvent_OnRecyclerViewItemTouchUp(Obj, itemIndex);
end;
end;
// By ADiV
Procedure Java_Event_pOnRecyclerViewItemTouchDown(env: PJNIEnv; this: jobject; Obj: TObject; itemIndex: integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jsRecyclerView then
begin
jsRecyclerView(Obj).GenEvent_OnRecyclerViewItemTouchDown(Obj, itemIndex);
end;
end;
Procedure Java_Event_pOnSTabSelected(env: PJNIEnv; this: jobject; Obj: TObject; position: integer; title: JString);
var
pastitle: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jsTabLayout then
begin
pastitle := '';
if title <> nil then
begin
_jBoolean:= JNI_False;
pastitle:= string( env^.GetStringUTFChars(env,title,@_jBoolean) );
end;
jsTabLayout(Obj).GenEvent_OnSTabSelected(Obj, position, pastitle);
end;
end;
procedure Java_Event_pOnCustomCameraSurfaceChanged(env: PJNIEnv; this: jobject; Obj: TObject; width: integer; height: integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jCustomCamera then
begin
jCustomCamera(Obj).GenEvent_OnCustomCameraSurfaceChanged(Obj, width, height);
end;
end;
Procedure Java_Event_pOnCustomCameraPictureTaken(env: PJNIEnv; this: jobject; Obj: TObject; picture: JObject; fullPath: JString);
var
pasfullPath: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jCustomCamera then
begin
pasfullPath := '';
if fullPath <> nil then
begin
_jBoolean:= JNI_False;
pasfullPath:= string( env^.GetStringUTFChars(env,fullPath,@_jBoolean) );
end;
jCustomCamera(Obj).GenEvent_OnCustomCameraPictureTaken(Obj, picture, pasfullPath);
end;
end;
Procedure Java_Event_pOnSearchViewFocusChange(env: PJNIEnv; this: jobject; Obj: TObject; hasFocus: jBoolean);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jSearchView then
begin
jSearchView(Obj).GenEvent_OnSearchViewFocusChange(Obj, Boolean(hasFocus));
end;
end;
Procedure Java_Event_pOnSearchViewQueryTextSubmit(env: PJNIEnv; this: jobject; Obj: TObject; query: JString);
var
pasquery: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jSearchView then
begin
pasquery := '';
if query <> nil then
begin
_jBoolean:= JNI_False;
pasquery:= string( env^.GetStringUTFChars(env,query,@_jBoolean) );
end;
jSearchView(Obj).GenEvent_OnSearchViewQueryTextSubmit(Obj, pasquery);
end;
end;
Procedure Java_Event_pOnSearchViewQueryTextChange(env: PJNIEnv; this: jobject; Obj: TObject; newText: JString );
var
pasnewText: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jSearchView then
begin
pasnewText := '';
if newText <> nil then
begin
_jBoolean:= JNI_False;
pasnewText:= string( env^.GetStringUTFChars(env,newText,@_jBoolean) );
end;
jSearchView(Obj).GenEvent_OnSearchViewQueryTextChange(Obj, pasnewText);
end;
end;
procedure Java_Event_pOnClickX(env:PJNIEnv;this:JObject;Sender:TObject);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jSearchView then
begin
jSearchView(Sender).GenEvent_OnClickX(Sender);
end;
end;
Procedure Java_Event_pOnTelephonyCallStateChanged(env: PJNIEnv; this: jobject; Obj: TObject; state: integer; phoneNumber: JString );
var
pasPhoneNumber: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jTelephonyManager then
begin
pasPhoneNumber := '';
if phoneNumber <> nil then
begin
_jBoolean:= JNI_False;
pasPhoneNumber:= string( env^.GetStringUTFChars(env,phoneNumber,@_jBoolean) );
end;
jTelephonyManager(Obj).GenEvent_OnTelephonyCallStateChanged(Obj, TTelephonyCallState(state), pasPhoneNumber);
end;
end;
Procedure Java_Event_pOnGetUidTotalMobileBytesFinished(env: PJNIEnv; this: jobject; Obj: TObject; bytesResult: JLong; uid: integer);
begin
gApp.Jni.jEnv:= env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jTelephonyManager then
begin
jTelephonyManager(Obj).GenEvent_OnGetUidTotalMobileBytesFinished(Obj, int64(bytesResult), uid);
end;
end;
Procedure Java_Event_pOnGetUidTotalWifiBytesFinished(env: PJNIEnv; this: jobject; Obj: TObject; bytesResult: JLong; uid: integer);
begin
gApp.Jni.jEnv:= env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jTelephonyManager then
begin
jTelephonyManager(Obj).GenEvent_OnGetUidTotalWifiBytesFinished(Obj, int64(bytesResult), uid);
end;
end;
// UPDATED by [ADiV]
Procedure Java_Event_pOnRecyclerViewItemWidgetClick(env: PJNIEnv; this: jobject; Obj: TObject;
itemIndex: integer; widgetClass: integer;
widgetId: integer; status: integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jsRecyclerView then
begin
jsRecyclerView(Obj).GenEvent_OnRecyclerViewItemWidgetClick(Obj,itemIndex, TItemContentFormat(widgetClass),widgetId, TItemWidgetStatus(status));
end;
end;
// By [ADiV]
Procedure Java_Event_pOnRecyclerViewItemWidgetLongClick(env: PJNIEnv; this: jobject; Obj: TObject;
itemIndex: integer; widgetClass: integer;
widgetId: integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jsRecyclerView then
begin
jsRecyclerView(Obj).GenEvent_OnRecyclerViewItemWidgetLongClick(Obj,itemIndex, TItemContentFormat(widgetClass),widgetId);
end;
end;
// By [ADiV]
Procedure Java_Event_pOnRecyclerViewItemWidgetTouchUp(env: PJNIEnv; this: jobject; Obj: TObject;
itemIndex: integer; widgetClass: integer;
widgetId: integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jsRecyclerView then
begin
jsRecyclerView(Obj).GenEvent_OnRecyclerViewItemWidgetTouchUp(Obj,itemIndex, TItemContentFormat(widgetClass),widgetId);
end;
end;
// By [ADiV]
Procedure Java_Event_pOnRecyclerViewItemWidgetTouchDown(env: PJNIEnv; this: jobject; Obj: TObject;
itemIndex: integer; widgetClass: integer;
widgetId: integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jsRecyclerView then
begin
jsRecyclerView(Obj).GenEvent_OnRecyclerViewItemWidgetTouchDown(Obj,itemIndex, TItemContentFormat(widgetClass),widgetId);
end;
end;
Procedure Java_Event_pOnZBarcodeScannerViewResult(env: PJNIEnv; this: jobject; Obj: TObject;
codedata: JString; codetype: integer);
var
_jBoolean: JBoolean;
pascodedata: string;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Obj is jZBarcodeScannerView then
begin
pascodedata := '';
if codedata <> nil then
begin
_jBoolean:= JNI_False;
pascodedata:= string( env^.GetStringUTFChars(env,codedata,@_jBoolean) );
end;
jZBarcodeScannerView(Obj).GenEvent_OnZBarcodeScannerViewResult(Obj,pascodedata, codetype);
end;
end;
procedure Java_Event_pOnMidiManagerDeviceAdded(env:PJNIEnv;this:JObject;Sender:TObject;deviceId:integer;deviceName:jString;productId:jString;manufacture:jString);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jMidiManager then
begin
jMidiManager(Sender).GenEvent_OnMidiManagerDeviceAdded(Sender,deviceId,GetString(env,deviceName),GetString(env,productId),GetString(env,manufacture));
end;
end;
procedure Java_Event_pOnMidiManagerDeviceRemoved(env:PJNIEnv;this:JObject;Sender:TObject;deviceId:integer;deviceName:jString;productId:jString;manufacture:jString);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jMidiManager then
begin
jMidiManager(Sender).GenEvent_OnMidiManagerDeviceRemoved(Sender,deviceId,GetString(env,deviceName),GetString(env,productId),GetString(env,manufacture));
end;
end;
function Java_Event_pOnOpenMapViewRoadDraw(env:PJNIEnv;this:JObject;Sender:TObject;roadCode:integer;roadStatus:integer; roadDuration:double;roadDistance:double):jintArray;
var
outReturn: TDynArrayOfInteger;
outReturnColor: dword;
outReturnWidth: integer;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
outReturn:=nil;
if Sender is jcOpenMapView then
begin
jcOpenMapView(Sender).GenEvent_OnOpenMapViewRoadDraw(Sender,roadCode,roadStatus,roadDuration,roadDistance,outReturnColor,outReturnWidth);
end;
SetLength(outReturn, 2);
outReturn[0]:= outReturnColor;
outReturn[1]:= outReturnWidth;
Result:=GetJObjectOfDynArrayOfInteger(env,outReturn);
SetLength(outReturn, 0);
end;
procedure Java_Event_pOnOpenMapViewClick(env:PJNIEnv;this:JObject;Sender:TObject;latitude:double;longitude:double);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jcOpenMapView then
begin
jcOpenMapView(Sender).GenEvent_OnOpenMapViewClick(Sender,latitude,longitude);
end;
end;
procedure Java_Event_pOnOpenMapViewLongClick(env:PJNIEnv;this:JObject;Sender:TObject;latitude:double;longitude:double);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jcOpenMapView then
begin
jcOpenMapView(Sender).GenEvent_OnOpenMapViewLongClick(Sender,latitude,longitude);
end;
end;
procedure Java_Event_pOnOpenMapViewMarkerClick(env:PJNIEnv;this:JObject;Sender:TObject;title:jString;latitude:double;longitude:double);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jcOpenMapView then
begin
jcOpenMapView(Sender).GenEvent_OnOpenMapViewMarkerClick(Sender,GetString(env,title),latitude,longitude);
end;
end;
procedure Java_Event_pOnSignaturePadStartSigning(env:PJNIEnv;this:JObject;Sender:TObject);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jcSignaturePad then
begin
jcSignaturePad(Sender).GenEvent_OnSignaturePadStartSigning(Sender);
end;
end;
procedure Java_Event_pOnSignaturePadSigned(env:PJNIEnv;this:JObject;Sender:TObject);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jcSignaturePad then
begin
jcSignaturePad(Sender).GenEvent_OnSignaturePadSigned(Sender);
end;
end;
procedure Java_Event_pOnSignaturePadClear(env:PJNIEnv;this:JObject;Sender:TObject);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jcSignaturePad then
begin
jcSignaturePad(Sender).GenEvent_OnSignaturePadClear(Sender);
end;
end;
procedure Java_Event_pOnGDXFormRender(env:PJNIEnv;this:JObject;Sender:TObject;deltaTime:single);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jGdxForm then
begin
jGdxForm(Sender).GenEvent_OnGDXFormRender(Sender,deltaTime);
end;
end;
procedure Java_Event_pOnGDXFormShow(env:PJNIEnv;this:JObject;Sender:TObject);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jGdxForm then
begin
jGdxForm(Sender).GenEvent_OnGDXFormShow(Sender);
end;
end;
procedure Java_Event_pOnGDXFormResize(env:PJNIEnv;this:JObject;Sender:TObject;width:integer;height:integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jGdxForm then
begin
jGdxForm(Sender).GenEvent_OnGDXFormResize(Sender,width,height);
end;
end;
procedure Java_Event_pOnGDXFormClose(env:PJNIEnv;this:JObject;Sender:TObject);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jGdxForm then
begin
jGdxForm(Sender).GenEvent_OnGDXFormClose(Sender);
end;
end;
procedure Java_Event_pOnGDXFormTouchDown(env:PJNIEnv;this:JObject;Sender:TObject;screenX:integer;screenY:integer;pointer:integer;button:integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jGdxForm then
begin
jGdxForm(Sender).GenEvent_OnGDXFormTouchDown(Sender,screenX,screenY,pointer,button);
end;
end;
procedure Java_Event_pOnGDXFormTouchUp(env:PJNIEnv;this:JObject;Sender:TObject;screenX:integer;screenY:integer;pointer:integer;button:integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jGdxForm then
begin
jGdxForm(Sender).GenEvent_OnGDXFormTouchUp(Sender,screenX,screenY,pointer,button);
end;
end;
function Java_Event_pOnGDXFormKeyPressed(env:PJNIEnv;this:JObject;Sender:TObject;keyCode:integer):integer;
var
outReturn: integer;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
outReturn:=0;
if Sender is jGdxForm then
begin
jGdxForm(Sender).GenEvent_OnGDXFormKeyPressed(Sender,keyCode{,outReturn});
end;
Result:=outReturn;
end;
procedure Java_Event_pOnGDXFormResume(env:PJNIEnv;this:JObject;Sender:TObject);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jGdxForm then
begin
jGdxForm(Sender).GenEvent_OnGDXFormResume(Sender);
end;
end;
procedure Java_Event_pOnGDXFormPause(env:PJNIEnv;this:JObject;Sender:TObject);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jGdxForm then
begin
jGdxForm(Sender).GenEvent_OnGDXFormPause(Sender);
end;
end;
procedure Java_Event_pOnGDXFormHide(env:PJNIEnv;this:JObject;Sender:TObject);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jGdxForm then
begin
jGdxForm(Sender).GenEvent_OnGDXFormHide(Sender);
end;
end;
procedure Java_Event_pOnMailMessageRead(env:PJNIEnv;this:JObject;Sender:TObject;position:integer;Header:jString;Date:jString;Subject:jString;ContentType:jString;ContentText:jString;Attachments:jString);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jcMail then
begin
jcMail(Sender).GenEvent_OnMailMessageRead(Sender,position,GetString(env,Header),GetString(env,Date),GetString(env,Subject),GetString(env,ContentType),GetString(env,ContentText),GetString(env,Attachments));
end;
end;
procedure Java_Event_pOnMailMessagesCount(env:PJNIEnv;this:JObject;Sender:TObject;count:integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jcMail then
begin
jcMail(Sender).GenEvent_OnMailMessagesCount(Sender,count);
end;
end;
procedure Java_Event_pOnSFTPClientTryConnect(env:PJNIEnv;this:JObject;Sender:TObject;success:jBoolean);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jSFTPClient then
begin
jSFTPClient(Sender).GenEvent_OnSFTPClientTryConnect(Sender,boolean(success));
end;
end;
procedure Java_Event_pOnSFTPClientDownloadFinished(env:PJNIEnv;this:JObject;Sender:TObject;destination:jString;success:jBoolean);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jSFTPClient then
begin
jSFTPClient(Sender).GenEvent_OnSFTPClientDownloadFinished(Sender,GetString(env,destination),boolean(success));
end;
end;
procedure Java_Event_pOnSFTPClientUploadFinished(env:PJNIEnv;this:JObject;Sender:TObject;destination:jString;success:jBoolean);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jSFTPClient then
begin
jSFTPClient(Sender).GenEvent_OnSFTPClientUploadFinished(Sender,GetString(env,destination),boolean(success));
end;
end;
procedure Java_Event_pOnSFTPClientListing(env:PJNIEnv;this:JObject;Sender:TObject;remotePath:jString;fileName:jString;fileSize:integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jSFTPClient then
begin
jSFTPClient(Sender).GenEvent_OnSFTPClientListing(Sender,GetString(env,remotePath),GetString(env,fileName),fileSize);
end;
end;
procedure Java_Event_pOnSFTPClientListed(env:PJNIEnv;this:JObject;Sender:TObject;count:integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jSFTPClient then
begin
jSFTPClient(Sender).GenEvent_OnSFTPClientListed(Sender,count);
end;
end;
procedure Java_Event_pOnFTPClientTryConnect(env:PJNIEnv;this:JObject;Sender:TObject;success:jBoolean);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jFTPClient then
begin
jFTPClient(Sender).GenEvent_OnFTPClientTryConnect(Sender,boolean(success));
end;
end;
procedure Java_Event_pOnFTPClientDownloadFinished(env:PJNIEnv;this:JObject;Sender:TObject;destination:jString;success:jBoolean);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jFTPClient then
begin
jFTPClient(Sender).GenEvent_OnFTPClientDownloadFinished(Sender,GetString(env,destination),boolean(success));
end;
end;
procedure Java_Event_pOnFTPClientUploadFinished(env:PJNIEnv;this:JObject;Sender:TObject;destination:jString;success:jBoolean);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jFTPClient then
begin
jFTPClient(Sender).GenEvent_OnFTPClientUploadFinished(Sender,GetString(env,destination),boolean(success));
end;
end;
procedure Java_Event_pOnFTPClientListing(env:PJNIEnv;this:JObject;Sender:TObject;remotePath:jString;fileName:jString;fileSize:integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jFTPClient then
begin
jFTPClient(Sender).GenEvent_OnFTPClientListing(Sender,GetString(env,remotePath),GetString(env,fileName),fileSize);
end;
end;
procedure Java_Event_pOnFTPClientListed(env:PJNIEnv;this:JObject;Sender:TObject;count:integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jFTPClient then
begin
jFTPClient(Sender).GenEvent_OnFTPClientListed(Sender,count);
end;
end;
procedure Java_Event_pOnBluetoothSPPDataReceived(env:PJNIEnv;this:JObject;Sender:TObject;jbyteArrayData:jbyteArray;messageData:jString);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jcBluetoothSPP then
begin
jcBluetoothSPP(Sender).GenEvent_OnBluetoothSPPDataReceived(Sender,GetDynArrayOfJByte(env,jbyteArrayData),GetString(env,messageData));
end;
end;
procedure Java_Event_pOnBluetoothSPPDeviceConnected(env:PJNIEnv;this:JObject;Sender:TObject;deviceName:jString;deviceAddress:jString);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jcBluetoothSPP then
begin
jcBluetoothSPP(Sender).GenEvent_OnBluetoothSPPDeviceConnected(Sender,GetString(env,deviceName),GetString(env,deviceAddress));
end;
end;
procedure Java_Event_pOnBluetoothSPPDeviceDisconnected(env:PJNIEnv;this:JObject;Sender:TObject);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jcBluetoothSPP then
begin
jcBluetoothSPP(Sender).GenEvent_OnBluetoothSPPDeviceDisconnected(Sender);
end;
end;
procedure Java_Event_pOnBluetoothSPPDeviceConnectionFailed(env:PJNIEnv;this:JObject;Sender:TObject);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jcBluetoothSPP then
begin
jcBluetoothSPP(Sender).GenEvent_OnBluetoothSPPDeviceConnectionFailed(Sender);
end;
end;
procedure Java_Event_pOnBluetoothSPPServiceStateChanged(env:PJNIEnv;this:JObject;Sender:TObject;serviceState:integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jcBluetoothSPP then
begin
jcBluetoothSPP(Sender).GenEvent_OnBluetoothSPPServiceStateChanged(Sender, serviceState);
end;
end;
procedure Java_Event_pOnBluetoothSPPListeningNewAutoConnection(env:PJNIEnv;this:JObject;Sender:TObject;deviceName:jString;deviceAddress:jString);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jcBluetoothSPP then
begin
jcBluetoothSPP(Sender).GenEvent_OnBluetoothSPPListeningNewAutoConnection(Sender,GetString(env,deviceName),GetString(env,deviceAddress));
end;
end;
procedure Java_Event_pOnBluetoothSPPAutoConnectionStarted(env:PJNIEnv;this:JObject;Sender:TObject);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jcBluetoothSPP then
begin
jcBluetoothSPP(Sender).GenEvent_OnBluetoothSPPAutoConnectionStarted(Sender);
end;
end;
procedure Java_Event_pOnDirectorySelected(env:PJNIEnv;this:JObject;Sender:TObject;path:jString);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jSelectDirectoryDialog then
begin
jSelectDirectoryDialog(Sender).GenEvent_OnDirectorySelected(Sender,GetString(env,path));
end;
end;
procedure Java_Event_pOnMsSqlJDBCConnectionExecuteQueryAsync(env:PJNIEnv;this:JObject;Sender:TObject;messageStatus:jString);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jMsSqlJDBCConnection then
begin
jMsSqlJDBCConnection(Sender).GenEvent_OnMsSqlJDBCConnectionExecuteQueryAsync(Sender,GetString(env,messageStatus));
end;
end;
procedure Java_Event_pOnMsSqlJDBCConnectionOpenAsync(env:PJNIEnv;this:JObject;Sender:TObject;messageStatus:jString);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jMsSqlJDBCConnection then
begin
jMsSqlJDBCConnection(Sender).GenEvent_OnMsSqlJDBCConnectionOpenAsync(Sender,GetString(env,messageStatus));
end;
end;
procedure Java_Event_pOnMsSqlJDBCConnectionExecuteUpdateAsync(env:PJNIEnv;this:JObject;Sender:TObject;messageStatus:jString);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jMsSqlJDBCConnection then
begin
jMsSqlJDBCConnection(Sender).GenEvent_OnMsSqlJDBCConnectionExecuteUpdateAsync(Sender,GetString(env,messageStatus));
end;
end;
//jCustomSpeechToText
procedure Java_Event_pOnBeginOfSpeech(env:PJNIEnv;this:JObject;Sender:TObject);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jCustomSpeechToText then
begin
jCustomSpeechToText(Sender).GenEvent_OnBeginOfSpeech(Sender);
end;
end;
procedure Java_Event_pOnSpeechBufferReceived(env:PJNIEnv;this:JObject;Sender:TObject;txtBytes:jbyteArray);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jCustomSpeechToText then
begin
jCustomSpeechToText(Sender).GenEvent_OnSpeechBufferReceived(Sender,GetDynArrayOfJByte(env,txtBytes));
end;
end;
procedure Java_Event_pOnEndOfSpeech(env:PJNIEnv;this:JObject;Sender:TObject);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jCustomSpeechToText then
begin
jCustomSpeechToText(Sender).GenEvent_OnEndOfSpeech(Sender);
end;
end;
procedure Java_Event_pOnSpeechResults(env:PJNIEnv;this:JObject;Sender:TObject;txt:jString);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jCustomSpeechToText then
begin
jCustomSpeechToText(Sender).GenEvent_OnSpeechResults(Sender,GetString(env,txt));
end;
end;
procedure Java_Event_pOnBillingClientEvent(env:PJNIEnv; this:JObject; Obj: TObject; xml: JString);
var
pasStr: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
pasStr := '';
if xml <> nil then begin
_jBoolean := JNI_False;
pasStr := String( env^.GetStringUTFChars(Env,xml,@_jBoolean) );
end;
jcBillingClient(Obj).GenEvent_OnBillingClientEvent(pasStr);
end;
//jcToyTimerService
procedure Java_Event_pOnToyTimerServicePullElapsedTime(env:PJNIEnv;this:JObject;Sender:TObject;elapsedTime:int64);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jcToyTimerService then
begin
jcToyTimerService(Sender).GenEvent_OnToyTimerServicePullElapsedTime(Sender,elapsedTime);
end;
end;
//jBluetoothLowEnergy
procedure Java_Event_pOnBluetoothLEConnected(env:PJNIEnv;this:JObject;Sender:TObject;deviceName:jString;deviceAddress:jString;bondState:integer);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jBluetoothLowEnergy then
begin
jBluetoothLowEnergy(Sender).GenEvent_OnBluetoothLEConnected(Sender,GetString(env,deviceName),GetString(env,deviceAddress),bondState);
end;
end;
procedure Java_Event_pOnBluetoothLEScanCompleted(env:PJNIEnv;this:JObject;Sender:TObject;deviceNameArray:jstringArray;deviceAddressArray:jstringArray);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jBluetoothLowEnergy then
begin
jBluetoothLowEnergy(Sender).GenEvent_OnBluetoothLEScanCompleted(Sender,GetDynArrayOfString(env,deviceNameArray),GetDynArrayOfString(env,deviceAddressArray));
end;
end;
procedure Java_Event_pOnBluetoothLEServiceDiscovered(env:PJNIEnv;this:JObject;Sender:TObject;serviceIndex:integer;serviceUUID:jString;characteristicUUIDArray:jstringArray);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jBluetoothLowEnergy then
begin
jBluetoothLowEnergy(Sender).GenEvent_OnBluetoothLEServiceDiscovered(Sender,serviceIndex,GetString(env,serviceUUID),GetDynArrayOfString(env,characteristicUUIDArray));
end;
end;
procedure Java_Event_pOnBluetoothLECharacteristicChanged(env:PJNIEnv;this:JObject;Sender:TObject;strValue:jString;strCharacteristic:jString);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jBluetoothLowEnergy then
begin
jBluetoothLowEnergy(Sender).GenEvent_OnBluetoothLECharacteristicChanged(Sender,GetString(env,strValue),GetString(env,strCharacteristic));
end;
end;
procedure Java_Event_pOnBluetoothLECharacteristicRead(env:PJNIEnv;this:JObject;Sender:TObject;strValue:jString;strCharacteristic:jString);
begin
gApp.Jni.jEnv := env;
if this <> nil then gApp.Jni.jThis := this;
if Sender is jBluetoothLowEnergy then
begin
jBluetoothLowEnergy(Sender).GenEvent_OnBluetoothLECharacteristicRead(Sender,GetString(env,strValue),GetString(env,strCharacteristic));
end;
end;
//jsFirebasePushNotificationListener
procedure Java_Event_pOnGetTokenComplete(env:PJNIEnv;this:JObject;Sender:TObject;token:jString;isSuccessful:jBoolean;statusMessage:jString);
begin
gApp.Jni.jEnv:= env;
if this <> nil then gApp.Jni.jThis:= this;
if Sender is jsFirebasePushNotificationListener then
begin
jsFirebasePushNotificationListener(Sender).GenEvent_OnGetTokenComplete(Sender,GetString(env,token),boolean(isSuccessful),GetString(env,statusMessage));
end;
end;
//jBatteryManager
procedure Java_Event_pOnBatteryCharging(env:PJNIEnv;this:JObject;Sender:TObject;batteryAtPercentLevel:integer;pluggedBy:integer);
begin
gApp.Jni.jEnv:= env;
if this <> nil then gApp.Jni.jThis:= this;
if Sender is jBatteryManager then
begin
jBatteryManager(Sender).GenEvent_OnBatteryCharging(Sender,batteryAtPercentLevel,pluggedBy);
end;
end;
procedure Java_Event_pOnBatteryDisCharging(env:PJNIEnv;this:JObject;Sender:TObject;batteryAtPercentLevel:integer);
begin
gApp.Jni.jEnv:= env;
if this <> nil then gApp.Jni.jThis:= this;
if Sender is jBatteryManager then
begin
jBatteryManager(Sender).GenEvent_OnBatteryDisCharging(Sender,batteryAtPercentLevel);
end;
end;
procedure Java_Event_pOnBatteryFull(env:PJNIEnv;this:JObject;Sender:TObject;batteryAtPercentLevel:integer);
begin
gApp.Jni.jEnv:= env;
if this <> nil then gApp.Jni.jThis:= this;
if Sender is jBatteryManager then
begin
jBatteryManager(Sender).GenEvent_OnBatteryFull(Sender,batteryAtPercentLevel);
end;
end;
procedure Java_Event_pOnBatteryUnknown(env:PJNIEnv;this:JObject;Sender:TObject;batteryAtPercentLevel:integer);
begin
gApp.Jni.jEnv:= env;
if this <> nil then gApp.Jni.jThis:= this;
if Sender is jBatteryManager then
begin
jBatteryManager(Sender).GenEvent_OnBatteryUnknown(Sender,batteryAtPercentLevel);
end;
end;
procedure Java_Event_pOnBatteryNotCharging(env:PJNIEnv;this:JObject;Sender:TObject;batteryAtPercentLevel:integer);
begin
gApp.Jni.jEnv:= env;
if this <> nil then gApp.Jni.jThis:= this;
if Sender is jBatteryManager then
begin
jBatteryManager(Sender).GenEvent_OnBatteryNotCharging(Sender,batteryAtPercentLevel);
end;
end;
procedure Java_Event_pOnModbusConnect(env:PJNIEnv;this:JObject;Sender:TObject;success:jBoolean;msg:jString);
begin
gApp.Jni.jEnv:= env;
if this <> nil then gApp.Jni.jThis:= this;
if Sender is jModbus then
begin
jModbus(Sender).GenEvent_OnModbusConnect(Sender,boolean(success),GetString(env,msg));
end;
end;
procedure Java_Event_pWebSocketClientOnOpen(env:PJNIEnv;this:JObject;Sender:TObject);
begin
gApp.Jni.jEnv:= env;
if this <> nil then gApp.Jni.jThis:= this;
if Sender is jcWebSocketClient then
begin
jcWebSocketClient(Sender).GenEvent_WebSocketClientOnOpen(Sender);
end;
end;
procedure Java_Event_pWebSocketClientOnTextReceived(env:PJNIEnv;this:JObject;Sender:TObject;msgContent:jString);
begin
gApp.Jni.jEnv:= env;
if this <> nil then gApp.Jni.jThis:= this;
if Sender is jcWebSocketClient then
begin
jcWebSocketClient(Sender).GenEvent_WebSocketClientOnTextReceived(Sender,GetString(env,msgContent));
end;
end;
procedure Java_Event_pWebSocketClientOnBinaryReceived(env:PJNIEnv;this:JObject;Sender:TObject;data:jbyteArray);
begin
gApp.Jni.jEnv:= env;
if this <> nil then gApp.Jni.jThis:= this;
if Sender is jcWebSocketClient then
begin
jcWebSocketClient(Sender).GenEvent_WebSocketClientOnBinaryReceived(Sender,GetDynArrayOfJByte(env,data));
end;
end;
procedure Java_Event_pWebSocketClientOnPingReceived(env:PJNIEnv;this:JObject;Sender:TObject;data:jbyteArray);
begin
gApp.Jni.jEnv:= env;
if this <> nil then gApp.Jni.jThis:= this;
if Sender is jcWebSocketClient then
begin
jcWebSocketClient(Sender).GenEvent_WebSocketClientOnPingReceived(Sender,GetDynArrayOfJByte(env,data));
end;
end;
procedure Java_Event_pWebSocketClientOnPongReceived(env:PJNIEnv;this:JObject;Sender:TObject;data:jbyteArray);
begin
gApp.Jni.jEnv:= env;
if this <> nil then gApp.Jni.jThis:= this;
if Sender is jcWebSocketClient then
begin
jcWebSocketClient(Sender).GenEvent_WebSocketClientOnPongReceived(Sender,GetDynArrayOfJByte(env,data));
end;
end;
procedure Java_Event_pWebSocketClientOnException(env:PJNIEnv;this:JObject;Sender:TObject;exceptionMessage:jString);
begin
gApp.Jni.jEnv:= env;
if this <> nil then gApp.Jni.jThis:= this;
if Sender is jcWebSocketClient then
begin
jcWebSocketClient(Sender).GenEvent_WebSocketClientOnException(Sender,GetString(env,exceptionMessage));
end;
end;
procedure Java_Event_pWebSocketClientOnCloseReceived(env:PJNIEnv;this:JObject;Sender:TObject);
begin
gApp.Jni.jEnv:= env;
if this <> nil then gApp.Jni.jThis:= this;
if Sender is jcWebSocketClient then
begin
jcWebSocketClient(Sender).GenEvent_WebSocketClientOnCloseReceived(Sender);
end;
end;
end.
|
unit RWinVerEx;
interface
uses
Windows, Classes;
type
TWinVersionInfo = packed record
PlatformId: Longword;
LanguageId: Longword;
MajorVersion: Longword;
MinorVersion: Longword;
BuildNumber: Longword;
ExtendedData: Boolean;
ServicePackMajor: Word;
ServicePackMinor: Word;
SuiteMask: Word;
ProductType: Byte;
CSDVersion: string[128];
end;
const
VER_NT_WORKSTATION = $00000001;
// The operating system is Windows Vista, Windows XP Professional,
// Windows XP Home Edition, or Windows 2000 Professional.
VER_NT_DOMAIN_CONTROLLER = $00000002;
// The system is a domain controller and the operating system is
// Windows Server 2008, Windows Server 2003, or Windows 2000 Server.
VER_NT_SERVER = $00000003;
// The operating system is Windows Server 2008, Windows Server 2003, or Windows 2000 Server.
// Note that a server that is also a domain controller is reported as VER_NT_DOMAIN_CONTROLLER, not VER_NT_SERVER.
VER_SUITE_SMALLBUSINESS = $00000001;
// Microsoft Small Business Server was once installed on the system,
// but may have been upgraded to another version of Windows.
// Refer to the Remarks section for more information about this bit flag.
VER_SUITE_ENTERPRISE = $00000002;
// Windows Server 2008 Enterprise, Windows Server 2003, Enterprise Edition,
// or Windows 2000 Advanced Server is installed.
// Refer to the Remarks section for more information about this bit flag.
VER_SUITE_BACKOFFICE = $00000004;
// Microsoft BackOffice components are installed.
VER_SUITE_TERMINAL = $00000010;
// Terminal Services is installed. This value is always set.
// If VER_SUITE_TERMINAL is set but VER_SUITE_SINGLEUSERTS is not set,
// the system is running in application server mode.
VER_SUITE_SMALLBUSINESS_RESTRICTED = $00000020;
// Microsoft Small Business Server is installed with the restrictive
// client license in force. Refer to the Remarks section for more information
// about this bit flag.
VER_SUITE_EMBEDDEDNT = $00000040;
// Windows XP Embedded is installed.
VER_SUITE_DATACENTER = $00000080;
// Windows Server 2008 Datacenter, Windows Server 2003, Datacenter Edition,
// or Windows 2000 Datacenter Server is installed.
VER_SUITE_SINGLEUSERTS = $00000100;
// Remote Desktop is supported, but only one interactive session is supported.
// This value is set unless the system is running in application server mode.
VER_SUITE_PERSONAL = $00000200;
// Windows Vista Home Premium, Windows Vista Home Basic,
// or Windows XP Home Edition is installed.
VER_SUITE_BLADE = $00000400;
// Windows Server 2003, Web Edition is installed.
VER_SUITE_STORAGE_SERVER = $00002000;
// Windows Storage Server 2003 R2 or Windows Storage Server 2003 is installed.
VER_SUITE_COMPUTE_SERVER = $00004000;
// Windows Server 2003, Compute Cluster Edition is installed.
VER_SUITE_WH_SERVER = $00008000;
// Windows Home Server is installed.
function GetLangAbbrLCID(const LocaleLCID: LCID): string;
function GetLangNameLCID(const LocaleLCID: LCID): string;
function GetLanguageName(const LangId: Cardinal): string;
function GetWindowsVersionInfo: TWinVersionInfo;
function GetWindowsVersionType(const VerInfo: TWinVersionInfo; const VersionFormat: string): string; overload;
function GetWindowsVersionType(const VerInfo: TWinVersionInfo): string; overload;
function GetWindowsVersionAbbr(const VerInfo: TWinVersionInfo; const VersionFormat: string): string; overload;
function GetWindowsVersionAbbr(const VerInfo: TWinVersionInfo): string; overload;
function GetWindowsVersionName(const VerInfo: TWinVersionInfo; const VersionFormat: string): string; overload;
function GetWindowsVersionName(const VerInfo: TWinVersionInfo): string; overload;
function GetWindowsVersionNameLng(const VerInfo: TWinVersionInfo): string;
function GetWindowsVersionNameExt(const VerInfo: TWinVersionInfo): string;
function GetWindowsVersionNumber(const VerInfo: TWinVersionInfo): string;
function GetWindowsVersionProductType(const VerInfo: TWinVersionInfo): string;
function GetWindowsSuiteText(const VerInfo: TWinVersionInfo): string;
procedure GetWindowsDescription(const VerInfo: TWinVersionInfo; TxtInfo: TStrings);
const
SWindowsUnknown = '???';
SWindowsWS = 'Workstation';
SWindowsWSS = 'Wst %d.%d';
SWindowsSRV = 'Server';
SWindowsVer = '%d.%d';
SWindows32S = 'Win32s';
SWindows95 = '95';
SwindowsOSR2 = 'OSR2';
SwindowsSE = 'SE';
SWindows98 = '98';
SWindowsME = 'ME';
SWindowsNT = 'NT';
SWindowsXP = 'XP';
SWindows2K0 = '2000';
SWindows2K3 = '2003';
SWindows6x_WS = 'Vista';
SWindows6x_SRV = '%d.%d';
SWindows7x_WS = '%d';
SWindows7x_SRV = '2008';
SWindowsNx_WS = '%d.%d';
SWindowsNx_SRV = '%d.%d';
SWinExtSP = 'SP';
SWinExtSPF = 'SERVICE PACK';
SWinExtED = '%s, %s Edition';
SWinExtHE = 'Home Edition';
SWinExtHES = 'Home';
SWinExtPRO = 'Professional';
SWinExtPROS = 'Pro';
SWinExtEMB = 'Embedded';
SWinExtEMBS = 'Emb';
SWinExtADV = 'Advanced';
SWinExtENT = 'Enterprise';
SWinExtWEB = 'Web';
SWinExtSBS = 'Small Business';
SWinExtSBSR = 'Small Business Restricted';
SWinExtBO = 'Back Office';
SWinExtRD = 'Remote Desktop';
SWinExtTS = 'Terminal Service';
SWinExtSS = 'Storage Server';
SWinExtHS = 'Home Server';
SWinExtDC = 'Datacenter';
SWinExtCC = 'Compute Cluster';
SFmtWindowsVersionAbbr = 'Windows %0:s %1:s %2:s';
SFmtWindowsVersionType = 'Microsoft Windows %0:s';
SFmtWindowsVersionName = 'Microsoft Windows %0:s %2:s';
SFmtWindowsVersionNameLng = 'Microsoft Windows %0:s %1:s %2:s';
SFmtWindowsVersionNameExt = 'Microsoft Windows %0:s %1:s %2:s [%3:d.%4:.2d.%5:.3d]';
resourcestring
SOsName = '%s';
SOsVersion = 'Версия: %d.%.2d.%.3d';
SOsLanguage = 'Язык GUI: %s (%s), id: %d (0x%4.4x)';
SOsComponents = 'Установленные компоненты: %s';
implementation
uses
SysUtils;
function GetSystemDefaultUILanguage: UINT; stdcall; external kernel32 name 'GetSystemDefaultUILanguage';
type
TOsVersionInfoEx = packed record
Base: TOsVersionInfoA;
wServicePackMajor: Word;
wServicePackMinor: Word;
wSuiteMask: Word;
wProductType: Byte;
wReserved: Byte;
end;
function AddDelimStrEx(const BaseStr, AddStr, DelimStr: string): string;
begin
if AddStr <> '' then begin
if BaseStr = '' then
Result := AddStr
else
Result := BaseStr + DelimStr + AddStr;
end
else
Result := BaseStr;
end;
function DelDoubleSpaces(const S: string): string;
var
i: Integer;
begin
Result := S;
for i := Length(Result) downto 2 do
begin
if (Result[i] = ' ') and (Result[i - 1] = ' ') then
Delete(Result, i, 1);
end;
Result := Trim(Result);
end;
function GetLangAbbrLCID(const LocaleLCID: LCID): string;
var
LangAbbr: array [0..2] of Char;
begin
try
GetLocaleInfo(LocaleLCID, LOCALE_SABBREVLANGNAME, LangAbbr, SizeOf(LangAbbr));
Result := LangAbbr;
except
Result := EmptyStr;
end;
end;
function GetLangNameLCID(const LocaleLCID: LCID): string;
var
LangName: array [0..127] of Char;
begin
try
GetLocaleInfo(LocaleLCID, LOCALE_SLANGUAGE, LangName, SizeOf(LangName));
Result := LangName;
except
Result := EmptyStr;
end;
end;
function GetLanguageName(const LangId: Cardinal): string;
var
LangName: array[0..127] of Char;
begin
try
VerLanguageName(LangId, LangName, SizeOf(LangName));
Result := LangName;
except
Result := EmptyStr;
end;
end;
function GetWindowsVersionInfo: TWinVersionInfo;
var
VerInfo: TOsVersionInfoEx;
ResBool: Boolean;
begin
FillChar(VerInfo, SizeOf(VerInfo), 0);
VerInfo.Base.dwOSVersionInfoSize := SizeOf(TOsVersionInfoEx);
ResBool := GetVersionExA(VerInfo.Base);
Result.ExtendedData := ResBool;
if not Result.ExtendedData then
begin
VerInfo.Base.dwOSVersionInfoSize := SizeOf(TOsVersionInfo);
ResBool := GetVersionExA(VerInfo.Base);
end;
if ResBool then
begin
Result.PlatformId := VerInfo.Base.dwPlatformId;
Result.MajorVersion := VerInfo.Base.dwMajorVersion;
Result.MinorVersion := VerInfo.Base.dwMinorVersion;
Result.BuildNumber := VerInfo.Base.dwBuildNumber;
Result.ServicePackMajor := VerInfo.wServicePackMajor;
Result.ServicePackMinor := VerInfo.wServicePackMinor;
Result.SuiteMask := VerInfo.wSuiteMask;
Result.ProductType := VerInfo.wProductType;
Result.CSDVersion := Trim(ShortString(VerInfo.Base.szCSDVersion));
Result.LanguageId := GetSystemDefaultUILanguage;
// GetSystemDefaultLCID; // GetSystemDefaultLangID
end
else
raise Exception.Create(SysErrorMessage(GetLastError));
end;
function GetWindowsVersionType(const VerInfo: TWinVersionInfo; const VersionFormat: string): string;
var
VersionName: string;
begin
VersionName := SWindowsUnknown;
with VerInfo do
case PlatformId of
VER_PLATFORM_WIN32S: VersionName := SWindows32S;
VER_PLATFORM_WIN32_WINDOWS:
begin
if (MajorVersion = 4) and (MinorVersion = 0) then
VersionName := SWindows95;
if (MajorVersion = 4) and (MinorVersion = 10) then
VersionName := SWindows98;
if (MajorVersion = 4) and (MinorVersion = 90) then
VersionName := SWindowsME;
end;
VER_PLATFORM_WIN32_NT:
begin
if (MajorVersion <= 4) then
begin
if ExtendedData then
begin
if ProductType <> VER_NT_WORKSTATION
then VersionName := Format(SWindowsNT + #32 + SWindowsSRV + #32 + SWindowsVer,
[MajorVersion, MinorVersion])
else VersionName := Format(SWindowsNT + #32 + SWindowsWS + #32 + SWindowsVer,
[MajorVersion, MinorVersion]);
end
else VersionName := Format(SWindowsNT + #32 + SWindowsVer,
[MajorVersion, MinorVersion]);
end;
if (MajorVersion = 5) and (MinorVersion = 0) then
begin
if ExtendedData and (ProductType <> VER_NT_WORKSTATION)
then VersionName := SWindows2K0 + #32 + SWindowsSRV
else VersionName := SWindows2K0;
end;
if (MajorVersion = 5) and (MinorVersion = 1) then
VersionName := SWindowsXP;
if (MajorVersion = 5) and (MinorVersion = 2) then
VersionName := SWindowsSRV + #32 + SWindows2K3;
if (MajorVersion = 6) and (MinorVersion = 0) then
begin
if ExtendedData and (ProductType <> VER_NT_WORKSTATION)
then VersionName := SWindowsSRV + #32 + Format(SWindows6x_SRV, [MajorVersion, MinorVersion])
else VersionName := SWindows6x_WS;
end;
if (MajorVersion = 7) then
begin
if ExtendedData and (ProductType <> VER_NT_WORKSTATION)
then VersionName := SWindowsSRV + #32 + SWindows7x_SRV
else VersionName := Format(SWindows7x_WS, [MajorVersion]);
end;
if (MajorVersion > 7) then
begin
if ExtendedData and (ProductType <> VER_NT_WORKSTATION)
then VersionName := SWindowsSRV + #32 + Format(SWindowsNx_SRV, [MajorVersion, MinorVersion])
else VersionName := Format(SWindowsNx_WS, [MajorVersion]);
end;
end;
end;
Result := Format(VersionFormat, [VersionName]);
end;
function GetWindowsVersionType(const VerInfo: TWinVersionInfo): string;
begin
Result := GetWindowsVersionType(VerInfo, SFmtWindowsVersionType);
end;
function GetWindowsVersionAbbr(const VerInfo: TWinVersionInfo; const VersionFormat: string): string;
var
VersionName, TypeName, LanguageName, ServicePackName: string;
begin
with VerInfo do
begin
VersionName := SWindowsUnknown;
TypeName := EmptyStr;
ServicePackName := EmptyStr;
case PlatformId of
VER_PLATFORM_WIN32S:
VersionName := SWindows32S;
VER_PLATFORM_WIN32_WINDOWS:
begin
if (MajorVersion = 4) and (MinorVersion = 0) then
begin
VersionName := SWindows95;
if (Length(CSDVersion) > 0) and (CSDVersion[1] in ['B', 'C']) then
TypeName := SWindowsOSR2
end;
if (MajorVersion = 4) and (MinorVersion = 10) then
begin
VersionName := SWindows98;
if (Length(CSDVersion) > 0) and (CSDVersion[1] in ['A']) then
TypeName := SWindowsSE
end;
if (MajorVersion = 4) and (MinorVersion = 90) then
VersionName := SWindowsME;
VersionName := VersionName + TypeName;
end;
VER_PLATFORM_WIN32_NT:
begin
if ExtendedData then
begin
if ProductType = VER_NT_WORKSTATION then
begin
if (MajorVersion <= 4)
then TypeName := Format(SWindowsWSS, [MajorVersion, MinorVersion])
else begin
if (SuiteMask and VER_SUITE_EMBEDDEDNT) > 0
then TypeName := SWinExtEMBS
else if (SuiteMask and VER_SUITE_PERSONAL) > 0
then TypeName := SWinExtHES
else TypeName := SWinExtPROS;
end;
end
else begin
if (ProductType = VER_NT_SERVER)
or (ProductType = VER_NT_DOMAIN_CONTROLLER) then
begin
if (MajorVersion <= 4)
then TypeName := Format(SWindowsSRV + #32 + SWindowsVer,
[MajorVersion, MinorVersion])
else TypeName := SWindowsSRV;
end;
end;
end;
if (MajorVersion <= 4) then
VersionName := AddDelimStrEx(SWindowsNT, TypeName, #32);
if (MajorVersion = 5) and (MinorVersion = 0) then
VersionName := AddDelimStrEx(SWindows2K0, TypeName, #32);
if (MajorVersion = 5) and (MinorVersion = 1) then
VersionName := AddDelimStrEx(SWindowsXP, TypeName, #32);
if (MajorVersion = 5) and (MinorVersion = 2) then
VersionName := AddDelimStrEx(TypeName, SWindows2K3, #32);
if (MajorVersion = 6) and (MinorVersion = 0) then
begin
if ExtendedData and (ProductType <> VER_NT_WORKSTATION)
then VersionName := AddDelimStrEx(TypeName, Format(SWindows6x_SRV, [MajorVersion, MinorVersion]), #32)
else VersionName := AddDelimStrEx(SWindows6x_WS, TypeName, #32);
end;
if (MajorVersion = 7) then
begin
if ExtendedData and (ProductType <> VER_NT_WORKSTATION)
then VersionName := AddDelimStrEx(TypeName, SWindows7x_SRV, #32)
else VersionName := AddDelimStrEx(Format(SWindows7x_WS, [MajorVersion]), TypeName, #32);
end;
if (MajorVersion > 7) then
begin
if ExtendedData and (ProductType <> VER_NT_WORKSTATION)
then VersionName := AddDelimStrEx(TypeName, Format(SWindowsNx_SRV, [MajorVersion, MinorVersion]), #32)
else VersionName := AddDelimStrEx(Format(SWindowsNx_WS, [MajorVersion]), TypeName, #32);
end;
if Pos(SWinExtSPF, AnsiUpperCase(CSDVersion)) = 1
then ServicePackName := SWinExtSP + Trim(Copy(CSDVersion, 13, Length(CSDVersion) - 12))
else ServicePackName := Trim(CSDVersion);
end;
end;
LanguageName := GetLangAbbrLCID(LanguageId);
Result := DelDoubleSpaces(Format(VersionFormat,
[VersionName, LanguageName, ServicePackName,
MajorVersion, MinorVersion, (BuildNumber and $FFFF),
LanguageId]));
end;
end;
function GetWindowsVersionAbbr(const VerInfo: TWinVersionInfo): string;
begin
Result := GetWindowsVersionAbbr(VerInfo, SFmtWindowsVersionAbbr);
end;
function GetWindowsVersionName(const VerInfo: TWinVersionInfo; const VersionFormat: string): string;
var
VersionName, TypeName, ServerName, LanguageName, ServicePackName: string;
begin
with VerInfo do
begin
VersionName := SWindowsUnknown;
TypeName := EmptyStr;
ServerName := EmptyStr;
ServicePackName := EmptyStr;
case PlatformId of
VER_PLATFORM_WIN32S:
VersionName := SWindows32S;
VER_PLATFORM_WIN32_WINDOWS:
begin
if (MajorVersion = 4) and (MinorVersion = 0) then
begin
VersionName := SWindows95;
if (Length(CSDVersion) > 0) and (CSDVersion[1] in ['B', 'C']) then
TypeName := SWindowsOSR2
end;
if (MajorVersion = 4) and (MinorVersion = 10) then
begin
VersionName := SWindows98;
if (Length(CSDVersion) > 0) and (CSDVersion[1] in ['A']) then
TypeName := SWindowsSE
end;
if (MajorVersion = 4) and (MinorVersion = 90) then
VersionName := SWindowsME;
VersionName := VersionName + TypeName;
end;
VER_PLATFORM_WIN32_NT:
begin
if ExtendedData then
begin
if ProductType = VER_NT_WORKSTATION then
begin
if (MajorVersion <= 4)
then TypeName := Format(SWindowsWS + #32 + SWindowsVer,
[MajorVersion, MinorVersion])
else begin
if (SuiteMask and VER_SUITE_EMBEDDEDNT) > 0
then TypeName := SWinExtEMB
else if (SuiteMask and VER_SUITE_PERSONAL) > 0
then TypeName := SWinExtHE
else TypeName := SWinExtPRO;
end;
end
else begin
if (ProductType = VER_NT_SERVER)
or (ProductType = VER_NT_DOMAIN_CONTROLLER) then
begin
if (MajorVersion <= 4)
then TypeName := Format(SWindowsSRV + #32 + SWindowsVer,
[MajorVersion, MinorVersion])
else TypeName := SWindowsSRV;
if (SuiteMask and VER_SUITE_SMALLBUSINESS) > 0 then
ServerName := SWinExtSBS;
if (SuiteMask and VER_SUITE_SMALLBUSINESS_RESTRICTED) > 0 then
ServerName := SWinExtSBSR;
if (SuiteMask and VER_SUITE_DATACENTER) > 0 then
ServerName := SWinExtDC;
if (SuiteMask and VER_SUITE_ENTERPRISE) > 0 then
begin
if (MajorVersion = 5) and (MinorVersion = 0)
then ServerName := SWinExtADV
else ServerName := SWinExtENT;
end;
if (SuiteMask and VER_SUITE_BLADE) > 0 then
ServerName := SWinExtWEB;
if (SuiteMask and VER_SUITE_STORAGE_SERVER) > 0 then
TypeName := SWinExtSS;
if (SuiteMask and VER_SUITE_COMPUTE_SERVER) > 0 then
ServerName := SWinExtCC;
if (SuiteMask and VER_SUITE_WH_SERVER) > 0 then
TypeName := SWinExtHS;
end;
end;
end;
if (MajorVersion <= 4) then
VersionName := AddDelimStrEx(SWindowsNT, AddDelimStrEx(ServerName, TypeName, #32), #32);
if (MajorVersion = 5) and (MinorVersion = 0) then
VersionName := AddDelimStrEx(SWindows2K0, AddDelimStrEx(ServerName, TypeName, #32), #32);
if (MajorVersion = 5) and (MinorVersion = 1) then
VersionName := AddDelimStrEx(SWindowsXP, TypeName, #32);
if (MajorVersion = 5) and (MinorVersion = 2) then
begin
VersionName := AddDelimStrEx(TypeName, SWindows2K3, #32);
if ServerName <> EmptyStr then
VersionName := Format(SWinExtED, [VersionName, ServerName]);
end;
if (MajorVersion = 6) then
begin
if ExtendedData and (ProductType <> VER_NT_WORKSTATION)
then VersionName := AddDelimStrEx(AddDelimStrEx(TypeName, Format(SWindows6x_SRV, [MajorVersion, MinorVersion]), #32), ServerName, #32)
else VersionName := AddDelimStrEx(SWindows6x_WS, TypeName, #32);
end;
if (MajorVersion = 7) then
begin
if ExtendedData and (ProductType <> VER_NT_WORKSTATION)
then VersionName := AddDelimStrEx(AddDelimStrEx(TypeName, SWindows7x_SRV, #32), ServerName, #32)
else VersionName := AddDelimStrEx(Format(SWindows7x_WS, [MajorVersion]), TypeName, #32);
end;
if (MajorVersion > 7) then
begin
if ExtendedData and (ProductType <> VER_NT_WORKSTATION)
then VersionName := AddDelimStrEx(AddDelimStrEx(TypeName, Format(SWindowsNx_SRV, [MajorVersion, MinorVersion]), #32), ServerName, #32)
else VersionName := AddDelimStrEx(Format(SWindowsNx_WS, [MajorVersion]), TypeName, #32);
end;
ServicePackName := Trim(CSDVersion);
end;
end;
LanguageName := GetLangAbbrLCID(LanguageId);
Result := DelDoubleSpaces(Format(VersionFormat,
[VersionName, LanguageName, ServicePackName,
MajorVersion, MinorVersion, (BuildNumber and $FFFF),
LanguageId]));
end;
end;
function GetWindowsVersionName(const VerInfo: TWinVersionInfo): string;
begin
Result := GetWindowsVersionName(VerInfo, SFmtWindowsVersionName);
end;
function GetWindowsVersionNameLng(const VerInfo: TWinVersionInfo): string;
begin
Result := GetWindowsVersionName(VerInfo, SFmtWindowsVersionNameLng);
end;
function GetWindowsVersionNameExt(const VerInfo: TWinVersionInfo): string;
begin
Result := GetWindowsVersionName(VerInfo, SFmtWindowsVersionNameExt);
end;
function GetWindowsVersionNumber(const VerInfo: TWinVersionInfo): string;
begin
Result := Format(SWindowsVer, [VerInfo.MajorVersion, VerInfo.MinorVersion]);
end;
function GetWindowsVersionProductType(const VerInfo: TWinVersionInfo): string;
begin
if VerInfo.ExtendedData and (VerInfo.ProductType <> VER_NT_WORKSTATION)
then Result := SWindowsSRV
else Result := SWindowsWS;
end;
function GetWindowsSuiteText(const VerInfo: TWinVersionInfo): string;
begin
Result := EmptyStr;
if VerInfo.ExtendedData then
begin
if (VerInfo.SuiteMask and VER_SUITE_SMALLBUSINESS) > 0
then Result := AddDelimStrEx(Result, SWinExtSBS + #32 + SWindowsSRV, ', ');
if (VerInfo.SuiteMask and VER_SUITE_SMALLBUSINESS_RESTRICTED) > 0
then Result := AddDelimStrEx(Result, SWinExtSBSR + #32 + SWindowsSRV, ', ');
if (VerInfo.SuiteMask and VER_SUITE_BACKOFFICE) > 0
then Result := AddDelimStrEx(Result, SWinExtBO, ', ');
if (VerInfo.SuiteMask and VER_SUITE_WH_SERVER) > 0
then Result := AddDelimStrEx(Result, SWinExtHS, ', ');
if (VerInfo.SuiteMask and VER_SUITE_SINGLEUSERTS) > 0
then Result := AddDelimStrEx(Result, SWinExtRD, ', ');
if (VerInfo.SuiteMask and VER_SUITE_TERMINAL) > 0 then
begin
if (VerInfo.SuiteMask and VER_SUITE_SINGLEUSERTS) > 0
then Result := AddDelimStrEx(Result, SWinExtRD, ', ')
else Result := AddDelimStrEx(Result, SWinExtTS, ', ');
end;
end;
end;
procedure GetWindowsDescription(const VerInfo: TWinVersionInfo; TxtInfo: TStrings);
var
ExtComp: string;
begin
if (VerInfo.PlatformId > 0) and (VerInfo.MajorVersion > 0) then
begin
TxtInfo.BeginUpdate;
try
TxtInfo.Clear;
TxtInfo.Add(Format(SOsName, [GetWindowsVersionName(VerInfo)]));
TxtInfo.Add(Format(SOsVersion, [VerInfo.MajorVersion,
VerInfo.MinorVersion, VerInfo.BuildNumber]));
TxtInfo.Add(Format(SOsLanguage, [GetLangNameLCID(VerInfo.LanguageId),
GetLangAbbrLCID(VerInfo.LanguageId), VerInfo.LanguageId, VerInfo.LanguageId]));
ExtComp := GetWindowsSuiteText(VerInfo);
if ExtComp <> EmptyStr then TxtInfo.Add(Format(SOsComponents, [ExtComp]));
finally
TxtInfo.EndUpdate;
end;
end;
end;
end.
|
unit soundpool;
{$mode delphi}
interface
uses
Classes, SysUtils, And_jni, {And_jni_Bridge,} AndroidWidget;
type
TOnLoadComplete = procedure(Sender: TObject; soundId: integer; status: integer) of Object;
{Draft Component code by "LAMW: Lazarus Android Module Wizard" [12/08/2019 9:44:33]}
{https://github.com/jmpessoa/lazandroidmodulewizard}
{jControl template}
jSoundPool = class(jControl)
private
FOnLoadComplete: TOnLoadComplete;
FMaxStreams : integer;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Init; override;
function SoundLoad(_path: string; _filename: string): integer; overload;
function SoundLoad(_path: string): integer; overload;
procedure SoundUnload(soundId: integer);
function SoundPlay(soundId: integer; _leftVolume: single; _rightVolume: single; _priority: integer; _loop: integer; _rate: single): integer;
procedure StreamSetVolume(streamId: integer; _leftVolume: single; _rightVolume: single);
procedure StreamSetPriority(streamId: integer; _priority: integer);
procedure StreamSetLoop(streamId: integer; _loop: integer);
procedure StreamSetRate(streamId: integer; _rate: single);
procedure StreamPause(streamId: integer);
procedure StreamResume(streamId: integer);
procedure StreamStop(streamId: integer);
procedure PauseAll();
procedure ResumeAll();
procedure GenEvent_OnLoadComplete(Obj: jObject; soundId: integer; status: integer);
published
property MaxStreams : integer read FMaxStreams write FMaxStreams;
property OnLoadComplete: TOnLoadComplete read FOnLoadComplete write FOnLoadComplete;
end;
function jSoundPool_jCreate(env: PJNIEnv;_Self: int64; _maxstreams : integer; this: jObject): jObject;
function jSoundPool_SoundPlay(env: PJNIEnv; _jsoundpool: JObject; soundId: integer; _leftVolume: single; _rightVolume: single; _priority: integer; _loop: integer; _rate: single): integer;
implementation
{--------- jSoundPool --------------}
constructor jSoundPool.Create(AOwner: TComponent);
begin
FMaxStreams := 5;
inherited Create(AOwner);
//your code here....
end;
destructor jSoundPool.Destroy;
begin
if not (csDesigning in ComponentState) then
begin
if FjObject <> nil then
begin
jni_free(gApp.jni.jEnv, FjObject);
FjObject:= nil;
end;
end;
//you others free code here...'
inherited Destroy;
end;
procedure jSoundPool.Init;
begin
if FInitialized then Exit;
inherited Init; //set default ViewParent/FjPRLayout as jForm.View!
//your code here: set/initialize create params....
FjObject := jSoundPool_jCreate(gApp.jni.jEnv, int64(Self), FMaxStreams, gApp.jni.jThis);
if FjObject = nil then exit;
FInitialized:= True;
end;
function jSoundPool.SoundLoad(_path: string; _filename: string): integer;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jni_func_tt_out_i(gApp.jni.jEnv, FjObject, 'SoundLoad', _path ,_filename);
end;
function jSoundPool.SoundLoad(_path: string): integer;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jni_func_t_out_i(gApp.jni.jEnv, FjObject, 'SoundLoad', _path);
end;
procedure jSoundPool.SoundUnload(soundId: integer);
begin
//in designing component state: set value here...
if FInitialized then
jni_proc_i(gApp.jni.jEnv, FjObject, 'SoundUnload', soundId);
end;
(*
* priority : Example: 1 has less priority than 10,
* it will stop those with lower priority.
* If you reach the maximum number of sounds allowed
*
* loop : -1 Infinite loop should call the soundStop function to stop the sound.
* : 0 Without loop
* : Any other non-zero value will cause the sound to repeat the specified
* number of times, e.g. a value of 3 causes the sound to play a total of 4 times
*
* rate : The playback rate can also be changed
* : 1.0 causes the sound to play at its original
* : The playback rate range is 0.5 to 2.0
*
* return streamId of sound;
* *)
function jSoundPool.SoundPlay(soundId: integer; _leftVolume: single; _rightVolume: single; _priority: integer; _loop: integer; _rate: single): integer;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jSoundPool_SoundPlay(gApp.jni.jEnv, FjObject, soundId ,_leftVolume ,_rightVolume ,_priority ,_loop ,_rate);
end;
procedure jSoundPool.StreamSetVolume(streamId: integer; _leftVolume: single; _rightVolume: single);
begin
//in designing component state: set value here...
if FInitialized then
jni_proc_iff(gApp.jni.jEnv, FjObject, 'StreamSetVolume', streamId ,_leftVolume ,_rightVolume);
end;
procedure jSoundPool.StreamSetPriority(streamId: integer; _priority: integer);
begin
//in designing component state: set value here...
if FInitialized then
jni_proc_ii(gApp.jni.jEnv, FjObject, 'StreamSetPriority', streamId ,_priority);
end;
procedure jSoundPool.StreamSetLoop(streamId: integer; _loop: integer);
begin
//in designing component state: set value here...
if FInitialized then
jni_proc_ii(gApp.jni.jEnv, FjObject, 'StreamSetLoop', streamId ,_loop);
end;
procedure jSoundPool.StreamSetRate(streamId: integer; _rate: single);
begin
//in designing component state: set value here...
if FInitialized then
jni_proc_if(gApp.jni.jEnv, FjObject, 'StreamSetRate', streamId ,_rate);
end;
procedure jSoundPool.StreamPause(streamId: integer);
begin
//in designing component state: set value here...
if FInitialized then
jni_proc_i(gApp.jni.jEnv, FjObject, 'StreamPause', streamId);
end;
procedure jSoundPool.StreamResume(streamId: integer);
begin
//in designing component state: set value here...
if FInitialized then
jni_proc_i(gApp.jni.jEnv, FjObject, 'StreamResume', streamId);
end;
procedure jSoundPool.StreamStop(streamId: integer);
begin
//in designing component state: set value here...
if FInitialized then
jni_proc_i(gApp.jni.jEnv, FjObject, 'StreamStop', streamId);
end;
procedure jSoundPool.PauseAll();
begin
//in designing component state: set value here...
if FInitialized then
jni_proc(gApp.jni.jEnv, FjObject, 'PauseAll');
end;
procedure jSoundPool.ResumeAll();
begin
//in designing component state: set value here...
if FInitialized then
jni_proc(gApp.jni.jEnv, FjObject, 'ResumeAll');
end;
procedure jSoundPool.GenEvent_OnLoadComplete(Obj: jObject; soundId: integer; status: integer);
begin
if Assigned(FOnLoadComplete) then FOnLoadComplete(Obj, soundId, status);
end;
{-------- jSoundPool_JNI_Bridge ----------}
function jSoundPool_jCreate(env: PJNIEnv;_Self: int64; _maxstreams : integer; this: jObject): jObject;
var
jParams: array[0..1] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
label
_exceptionOcurred;
begin
Result := nil;
if (env = nil) or (this = nil) then exit;
jCls:= Get_gjClass(env);
if jCls = nil then goto _exceptionOcurred;
jMethod:= env^.GetMethodID(env, jCls, 'jSoundPool_jCreate', '(JI)Ljava/lang/Object;');
if jMethod = nil then goto _exceptionOcurred;
jParams[0].j:= _Self;
jParams[1].i:= _maxstreams;
Result:= env^.CallObjectMethodA(env, this, jMethod, @jParams);
Result:= env^.NewGlobalRef(env, Result);
_exceptionOcurred: if jni_ExceptionOccurred(env) then Result := nil;
end;
function jSoundPool_SoundPlay(env: PJNIEnv; _jsoundpool: JObject; soundId: integer; _leftVolume: single; _rightVolume: single; _priority: integer; _loop: integer; _rate: single): integer;
var
jParams: array[0..5] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
label
_exceptionOcurred;
begin
Result := 0;
if (env = nil) or (_jsoundpool = nil) then exit;
jCls:= env^.GetObjectClass(env, _jsoundpool);
if jCls = nil then goto _exceptionOcurred;
jMethod:= env^.GetMethodID(env, jCls, 'SoundPlay', '(IFFIIF)I');
if jMethod = nil then begin env^.DeleteLocalRef(env, jCls); goto _exceptionOcurred; end;
jParams[0].i:= soundId;
jParams[1].f:= _leftVolume;
jParams[2].f:= _rightVolume;
jParams[3].i:= _priority;
jParams[4].i:= _loop;
jParams[5].f:= _rate;
Result:= env^.CallIntMethodA(env, _jsoundpool, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
_exceptionOcurred: if jni_ExceptionOccurred(env) then result := 0;
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireMonkey Platform }
{ }
{ Copyright(c) 2011-2013 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit FMX.Forms3D;
interface
uses
System.TypInfo, System.Math, System.Classes, System.SysUtils, System.Types,
System.UITypes, FMX.Types, FMX.Types3D, System.Generics.Collections,
FMX.ActnList, FMX.Messages, FMX.Controls3D, FMX.Objects3D, FMX.Forms,
FMX.Graphics, FMX.Effects;
{$SCOPEDENUMS ON}
type
{ TCustomForm3D }
TCustomForm3D = class(TCommonCustomForm, IContextObject, IViewport3D)
private
FCamera: TCamera;
FDesignCamera: TCamera;
FDesignCameraZ: TDummy;
FDesignCameraX: TDummy;
FFill: TAlphaColor;
FMultisample: TMultisample;
FUsingDesignCamera: Boolean;
FDrawing: Boolean;
FOnRender: TRenderEvent;
FEffectBitmap: TBitmap;
FContext: TContext3D;
FRenderingList: TList<TControl3D>;
FLights: TList<TLight>;
procedure SetFill(const Value: TAlphaColor);
procedure SetMultisample(const Value: TMultisample);
function GetFill: TAlphaColor;
procedure RebuildRenderingList;
procedure SetUsingDesignCamera(const Value: Boolean);
procedure SkipTransparency(Reader: TReader);
{ IViewport3D }
function GetObject: TFmxObject;
function GetContext: TContext3D;
function GetCamera: TCamera;
function GetUsingDesignCamera: Boolean;
function GetViewportScale: Single;
function GetLightCount: Integer;
function GetLight(Index: Integer): TLight;
procedure SetCamera(const ACamera: TCamera);
procedure AddLight(const ALight: TLight);
procedure RemoveLight(const ALight: TLight);
procedure NeedRender;
function GetCurrentCamera: TCamera;
protected
procedure DoAddObject(const AObject: TFmxObject); override;
procedure DoRemoveObject(const AObject: TFmxObject); override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure DefineProperties(Filer: TFiler); override;
{ Context }
procedure CreateContext; virtual;
procedure DestroyContext; virtual;
{ Handle }
procedure CreateHandle; override;
procedure DestroyHandle; override;
procedure ResizeHandle; override;
procedure PaintRects(const UpdateRects: array of TRectF); override;
{ Preload }
procedure AddPreloadPropertyNames(const PropertyNames: TList<string>); override;
procedure SetPreloadProperties(const PropertyStore: TDictionary<string, Variant>); override;
{ inherited }
procedure Realign; override;
function FindTarget(P: TPointF; const Data: TDragObject): IControl; override;
procedure SetTransparency(const Value: Boolean); override;
procedure DoScaleChanged; override;
{ }
function ScreenToLocal(P: TPointF): TPointF;
function LocalToScreen(P: TPointF): TPointF;
{ Window style }
function GetWindowStyle: TWindowStyles; override;
public
constructor Create(AOwner: TComponent); override;
constructor CreateNew(AOwner: TComponent; Dummy: NativeInt = 0); override;
destructor Destroy; override;
procedure EndUpdate; override;
procedure InitializeNewForm; override;
property Context: TContext3D read FContext;
property Multisample: TMultisample read FMultisample write SetMultisample default TMultisample.ms4Samples;
property Color: TAlphaColor read GetFill write SetFill default TAlphaColors.White;
property Camera: TCamera read FCamera write SetCamera;
property UsingDesignCamera: Boolean read FUsingDesignCamera write SetUsingDesignCamera default True;
function ObjectAtPoint(P: TPointF): IControl; override;
property OnRender: TRenderEvent read FOnRender write FOnRender;
end;
TForm3D = class(TCustomForm3D)
published
property BiDiMode;
property Camera;
property Caption;
property Color default TAlphaColors.White;
property Cursor default crDefault;
property Border;
property BorderIcons default [TBorderIcon.biSystemMenu, TBorderIcon.biMinimize, TBorderIcon.biMaximize];
property BorderStyle default TFmxFormBorderStyle.bsSizeable;
property ClientHeight;
property ClientWidth;
property Height;
property Left;
property Padding;
property Multisample default TMultisample.ms4Samples;
property Position default TFormPosition.poDefaultPosOnly;
property StyleBook;
property Top;
property FormStyle default TFormStyle.fsNormal;
property UsingDesignCamera default True;
property Visible;
property Width;
property WindowState default TWindowState.wsNormal;
property FormFactor;
property FormFamily;
{events}
property OnActivate;
property OnCreate;
property OnClose;
property OnCloseQuery;
property OnDeactivate;
property OnDestroy;
property OnKeyDown;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
property OnRender;
property OnResize;
property OnShow;
property OnHide;
property OnVirtualKeyboardShown;
property OnVirtualKeyboardHidden;
end;
implementation
uses
System.Variants,
System.Generics.Defaults,
System.RTLConsts,
System.Rtti, System.Actions,
FMX.Consts,
FMX.Dialogs,
FMX.Controls,
FMX.Platform, FMX.Menus, FMX.Styles,
FMX.Filter, FMX.Materials, FMX.TextLayout, FMX.Objects, FMX.Text;
type
TOpenFmxObject = class (TFmxObject)
end;
TOpenControl = class (TControl)
end;
{ TCustomForm3D }
type
TOpenContext = class(TContext3D);
TOpenControl3D = class(TControl3D);
// Required to force Delphi-style initialization when used from C++.
constructor TCustomForm3D.Create(AOwner: TComponent);
begin
inherited;
end;
constructor TCustomForm3D.CreateNew(AOwner: TComponent; Dummy: NativeInt);
begin
inherited;
end;
procedure TCustomForm3D.InitializeNewForm;
begin
inherited;
FUsingDesignCamera := True;
FFill := TAlphaColors.White;
FLights := TList<TLight>.Create;
FDesignCameraZ := TDummy.Create(nil);
FDesignCameraZ.Tag := $FFFE;
FDesignCameraZ.Locked := True;
FDesignCameraZ.Stored := False;
AddObject(FDesignCameraZ);
FDesignCameraX := TDummy.Create(nil);
FDesignCameraX.Tag := $FFFE;
FDesignCameraX.Parent := FDesignCameraZ;
FDesignCameraX.Locked := True;
FDesignCameraX.Stored := False;
FDesignCameraX.RotationAngle.X := -20;
FDesignCamera := TCamera.Create(nil);
FDesignCamera.Tag := $FFFE;
FDesignCamera.Parent := FDesignCameraX;
FDesignCamera.Locked := True;
FDesignCamera.Stored := False;
FDesignCamera.Position.Point := Point3D(0, 0, -20);
end;
destructor TCustomForm3D.Destroy;
begin
if Assigned(FRenderingList) then
FreeAndNil(FRenderingList);
if Assigned(FEffectBitmap) then
FreeAndNil(FEffectBitmap);
DeleteChildren;
if Assigned(FContext) then
FreeAndNil(FContext);
// if Assigned(FChildren) then
// FreeAndNil(FChildren);
FreeAndNil(FLights);
inherited;
end;
procedure TCustomForm3D.AddPreloadPropertyNames(const PropertyNames: TList<string>);
begin
inherited ;
PropertyNames.Add('Multisample');
end;
procedure TCustomForm3D.SetPreloadProperties(const PropertyStore: TDictionary<string, Variant>);
var
Val: Variant;
begin
inherited ;
// Default
FMultisample := TMultisample.ms4Samples;
// Preload
PropertyStore.TryGetValue('Multisample', Val);
if (Val <> Unassigned) and (Val <> Null) then
FMultisample := TMultisample(GetEnumValue(TypeInfo(TMultisample), Val));
end;
procedure TCustomForm3D.CreateHandle;
begin
inherited;
CreateContext;
end;
procedure TCustomForm3D.ResizeHandle;
begin
inherited;
if Assigned(Context) and (ClientWidth > 0) and (ClientHeight > 0) then
begin
Context.SetSize(ClientWidth, ClientHeight);
Context.SetCameraMatrix(GetCurrentCamera.CameraMatrix);
Realign;
end;
end;
procedure TCustomForm3D.DestroyHandle;
begin
DestroyContext;
inherited;
end;
procedure TCustomForm3D.CreateContext;
begin
FContext := TContextManager.CreateFromWindow(Handle, ClientWidth, ClientHeight, FMultisample, True);
end;
procedure TCustomForm3D.DestroyContext;
begin
FreeAndNil(FContext);
end;
procedure TCustomForm3D.DefineProperties(Filer: TFiler);
begin
inherited;
// Only for backward compatibility with XE2
Filer.DefineProperty('Transparency', SkipTransparency, nil, False);
end;
procedure TCustomForm3D.SkipTransparency(Reader: TReader);
begin
Reader.ReadBoolean; // skip this
end;
procedure TCustomForm3D.DoScaleChanged;
begin
inherited;
DestroyContext;
CreateContext;
end;
procedure TCustomForm3D.EndUpdate;
begin
inherited;
if FUpdating = 0 then
RebuildRenderingList;
end;
procedure TCustomForm3D.RebuildRenderingList;
var
I: Integer;
CompareFunc: TRenderingCompare;
begin
if Assigned(Children) and (Children.Count > 0) and (FUpdating = 0) then
begin
if Not Assigned(FRenderingList) then
FRenderingList := TList<TControl3D>.Create;
FRenderingList.Clear;
for I := 0 to Children.Count - 1 do
if (Children[i] is TControl3D) then
FRenderingList.Add(Children[I] as TControl3D);
CompareFunc := TRenderingCompare.Create;
try
FRenderingList.Sort(CompareFunc);
finally
CompareFunc.Free;
end;
end;
end;
procedure TCustomForm3D.AddLight(const ALight: TLight);
begin
FLights.Add(ALight);
end;
procedure TCustomForm3D.RemoveLight(const ALight: TLight);
begin
FLights.Remove(ALight);
end;
procedure TCustomForm3D.PaintRects(const UpdateRects: array of TRectF);
var
I: Integer;
Ver: TVertexBuffer;
Ind: TIndexBuffer;
Mat: TTextureMaterial;
Control: TOpenControl3D;
P: TPointF;
begin
if Not Assigned(Context) then
Exit;
if FDrawing then
Exit;
FDrawing := True;
try
if Context.BeginScene then
try
Context.Clear([TClearTarget.ctColor, TClearTarget.ctDepth], FFill, 1.0, 0);
Context.SetCameraMatrix(GetCurrentCamera.CameraMatrix);
Context.Lights.Clear;
for I := 0 to FLights.Count - 1 do
Context.Lights.Add(FLights[I].LightDescription);
if Assigned(FOnRender) then
FOnRender(Self, Context);
if Assigned(FRenderingList) and (FRenderingList.Count > 0) then
begin
for I := 0 to FRenderingList.Count - 1 do
if FRenderingList[i].Visible or (not FRenderingList[i].Visible and
(csDesigning in ComponentState) and not FRenderingList[i].Locked) then
begin
Control := TOpenControl3D(FRenderingList[i]);
if (csDesigning in Control.ComponentState) and not Control.DesignVisible then
Continue;
Control.RenderInternal;
end;
end;
{ post-processing }
if Assigned(Children) then
begin
for i := 0 to Children.Count - 1 do
if (TFmxObject(Children[i]) is TEffect) and (TEffect(Children[i]).Enabled) then
begin
if Not Assigned(FEffectBitmap) then
FEffectBitmap := TBitmap.Create(FContext.Width, FContext.Height);
FEffectBitmap.Assign(Context);
TEffect(Children[i]).ProcessEffect(nil, FEffectBitmap, 1);
// create quad
Ver := TVertexBuffer.Create([TVertexFormat.vfVertex, TVertexFormat.vfTexCoord0], 4);
P := Context.PixelToPixelPolygonOffset;
Ver.Vertices[0] := Point3D(P.X, P.Y, 0);
Ver.TexCoord0[0] := PointF(0.0, 0.0);
Ver.Vertices[1] := Point3D(FEffectBitmap.Width + P.X, P.Y, 0);
Ver.TexCoord0[1] := PointF(1.0, 0.0);
Ver.Vertices[2] := Point3D(FEffectBitmap.Width + P.X, FEffectBitmap.Height + P.Y, 0);
Ver.TexCoord0[2] := PointF(1.0, 1.0);
Ver.Vertices[3] := Point3D(P.X, FEffectBitmap.Height + P.Y, 0);
Ver.TexCoord0[3] := PointF(0.0, 1.0);
Ind := TIndexBuffer.Create(6);
Ind[0] := 0;
Ind[1] := 1;
Ind[2] := 3;
Ind[3] := 3;
Ind[4] := 1;
Ind[5] := 2;
// params
Context.SetMatrix(TMatrix3D.Identity);
Context.SetContextState(TContextState.cs2DScene);
Context.SetContextState(TContextState.csAllFace);
Context.SetContextState(TContextState.csAlphaBlendOff);
Context.SetContextState(TContextState.csZWriteOff);
Context.SetContextState(TContextState.csZTestOff);
// texture
Mat := TTextureMaterial.Create;
Mat.Texture := FEffectBitmap.Texture;
// render quad
Context.DrawTriangles(Ver, Ind, Mat, 1);
if Assigned(Mat) then
Mat.Free;
if Assigned(Ind) then
Ind.Free;
if Assigned(Ver) then
Ver.Free;
end;
end;
finally
{ buffer }
Context.EndScene;
end;
finally
{ off flag }
FDrawing := False;
end;
end;
procedure TCustomForm3D.DoAddObject(const AObject: TFmxObject);
begin
inherited;
if AObject is TControl3D then
begin
TOpenControl3D(AObject).SetNewViewport(Self);
RebuildRenderingList;
end;
if (csDesigning in ComponentState) and (AObject is TCamera) and (AObject.Tag <> $FFFE) then
Camera := TCamera(AObject);
end;
procedure TCustomForm3D.DoRemoveObject(const AObject: TFmxObject);
begin
inherited;
if AObject is TControl3D then
begin
TOpenControl3D(AObject).SetNewViewport(nil);
RebuildRenderingList;
end;
end;
procedure TCustomForm3D.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if (Operation = opRemove) and (AComponent = FCamera) then
FCamera := nil;
end;
function TCustomForm3D.ObjectAtPoint(P: TPointF): IControl;
var
i: Integer;
Obj: TFmxObject;
NewObj: IControl;
begin
Result := nil;
// first screen projection
GlobalDistance := $FFFF;
GlobalProjection := TProjection.pjScreen;
for i := ChildrenCount - 1 downto 0 do
begin
Obj := Children[i];
if IInterface(Obj).QueryInterface(IControl, NewObj) <> 0 then
Continue;
if not NewObj.GetVisible and not(csDesigning in ComponentState) then
Continue;
NewObj := NewObj.ObjectAtPoint(P);
if Assigned(NewObj) then
Result := NewObj;
end;
if Not Assigned(Result) then
begin
// second camera projection
GlobalDistance := $FFFF;
GlobalProjection := TProjection.pjCamera;
for i := ChildrenCount - 1 downto 0 do
begin
Obj := Children[i];
if IInterface(Obj).QueryInterface(IControl, NewObj) <> 0 then
Continue;
if not NewObj.GetVisible and not(csDesigning in ComponentState) then
Continue;
NewObj := NewObj.ObjectAtPoint(P);
if Assigned(NewObj) then
Result := NewObj;
end;
end;
end;
function TCustomForm3D.FindTarget(P: TPointF; const Data: TDragObject): IControl;
var
i: Integer;
Obj: TFmxObject;
NewObj: IControl;
begin
Result := nil;
// first screen projection
GlobalDistance := $FFFF;
GlobalProjection := TProjection.pjScreen;
for i := ChildrenCount - 1 downto 0 do
begin
Obj := Children[i];
if IInterface(Obj).QueryInterface(IControl, NewObj) <> 0 then
Continue;
if not NewObj.Visible then Continue;
NewObj := NewObj.FindTarget(P, Data);
if Assigned(NewObj) then
Result := NewObj;
end;
if Not Assigned(Result) then
begin
// second camera projection
GlobalDistance := $FFFF;
GlobalProjection := TProjection.pjCamera;
for i := ChildrenCount - 1 downto 0 do
begin
Obj := Children[i];
if IInterface(Obj).QueryInterface(IControl, NewObj) <> 0 then
Continue;
if not NewObj.Visible then Continue;
NewObj := NewObj.FindTarget(P, Data);
if Assigned(NewObj) then
Result := NewObj;
end;
end;
end;
function TCustomForm3D.GetFill: TAlphaColor;
begin
Result := FFill;
end;
function TCustomForm3D.GetLight(Index: Integer): TLight;
begin
Result := FLights[Index];
end;
function TCustomForm3D.GetLightCount: Integer;
begin
Result := FLights.Count;
end;
procedure TCustomForm3D.SetFill(const Value: TAlphaColor);
begin
if FFill <> Value then
begin
FFill := Value;
NeedRender;
end;
end;
function TCustomForm3D.ScreenToLocal(P: TPointF): TPointF;
begin
Result := ScreenToClient(P);
end;
function TCustomForm3D.LocalToScreen(P: TPointF): TPointF;
begin
Result := ClientToScreen(P);
end;
procedure TCustomForm3D.SetMultisample(const Value: TMultisample);
begin
if FMultisample <> Value then
begin
FMultisample := Value;
Recreate;
end;
end;
procedure TCustomForm3D.SetTransparency(const Value: Boolean);
begin
Transparency := False;
end;
procedure TCustomForm3D.SetUsingDesignCamera(const Value: Boolean);
begin
if FUsingDesignCamera <> Value then
begin
FUsingDesignCamera := Value;
if Assigned(FContext) then
NeedRender;
end;
end;
{ IViewport3D }
function TCustomForm3D.GetObject: TFmxObject;
begin
Result := Self;
end;
function TCustomForm3D.GetCamera: TCamera;
begin
Result := FCamera;
end;
function TCustomForm3D.GetCurrentCamera: TCamera;
begin
if Assigned(FCamera) and not (FUsingDesignCamera) and not (csDesigning in ComponentState) then
Result := FCamera
else
Result := FDesignCamera;
end;
function TCustomForm3D.GetContext: TContext3D;
begin
Result := FContext;
end;
function TCustomForm3D.GetUsingDesignCamera: Boolean;
begin
Result := FUsingDesignCamera;
end;
function TCustomForm3D.GetViewportScale: Single;
begin
Result := FWinService.GetWindowScale(Self);
end;
function TCustomForm3D.GetWindowStyle: TWindowStyles;
begin
Result := [TWindowStyle.wsGPUSurface];
end;
procedure TCustomForm3D.SetCamera(const ACamera: TCamera);
begin
if FCamera <> ACamera then
begin
FCamera := ACamera;
if Assigned(FContext) and not (FUsingDesignCamera) and not (csDesigning in ComponentState) then
NeedRender;
end;
end;
procedure TCustomForm3D.NeedRender;
begin
InvalidateRect(RectF(0, 0, FContext.Width, FContext.Height)); // because is a HW context
end;
procedure TCustomForm3D.Realign;
begin
AlignObjects(Self, Padding, FContext.Width, FContext.Height, FLastWidth, FLastHeight, FDisableAlign);
InvalidateRect(ClientRect);
end;
end.
|
unit RMPacket;
{$mode objfpc}{$H+}
interface
uses
SysUtils, Classes, syncobjs;
type
{ TRMPacket }
TRMPacket = class
private
Raw1: ansistring;
LastAppended1: ansistring;
TerminatorString1: string;
function GetReady: boolean;
function GetCount: integer;
function GetPacket: ansistring;
public
property Packet: ansistring read GetPacket;
property Raw: ansistring read Raw1;
property TerminatorString: string read TerminatorString1 write TerminatorString1;
function Extract(del: boolean = True): ansistring;
property Ready: boolean read GetReady;
property Count: integer read GetCount;
procedure Append(part: ansistring);
procedure Clear;
property LastAppended: ansistring read LastAppended1;
constructor Create(Delimeter: string = '');
destructor Destroy; override;
end;
implementation
{ TRMPacket }
procedure TRMPacket.Append(part: ansistring);
begin
LastAppended1 := Part;
Raw1 := Raw1 + part;
end;
procedure TRMPacket.Clear;
begin
Raw1 := '';
end;
constructor TRMPacket.Create(Delimeter: string);
begin
Raw1 := '';
LastAppended1 := '';
if (Delimeter = '') then
TerminatorString1 := #0
else
TerminatorString1 := Delimeter;
end;
destructor TRMPacket.Destroy;
begin
inherited Destroy;
end;
function TRMPacket.Extract(del: boolean): ansistring;
begin
if Ready then
begin
Result := Copy(Raw1, 1, Pos(TerminatorString, Raw1) - 1);
if del then
Delete(Raw1, 1, Pos(TerminatorString, Raw1) + 1);
end;
end;
function TRMPacket.GetReady: boolean;
var
i: integer;
st: ansistring;
begin
if (Pos(TerminatorString, Raw) > 0) then
Result := True
else
Result := False;
end;
function TRMPacket.GetCount: integer;
begin
Result := -1;
end;
function TRMPacket.GetPacket: ansistring;
begin
if Ready then
Result := Copy(Raw, 1, Pos(TerminatorString, Raw) - 1);
end;
end.
|
unit UVerlauf;
{
Verlaufsanalyse:
Betrachtet die aneinanderhängenden Treffertage als Sitzungen und berechnet anhand ihrer
Verlaufseigenschaften (wann wurde abgebrochen oder fortgefahren) eine Wahrscheinlichkeit
für das angegebene Datum.
}
{$mode objfpc}{$H+}
interface
uses
fgl, DateUtils
{ Eigen },
UAspekt;
Type
TIntegerListe = specialize TFPGList<Integer>;
type
TVerlauf = class (TAspekt)
private
Verlauf: TIntegerListe;
Verlaufswerte: Array of Integer;
ErsterTag: TDate;
public
constructor Create;
destructor Destroy; override;
procedure Durchlauf(Datum: TDate); override;
procedure Treffer; override;
function Wert (Datum: TDate): Double; override;
published
end;
implementation
constructor TVerlauf.Create;
begin
inherited;
FGewichtung := 1;
Verlauf := TIntegerListe.Create;
SetLength(Verlaufswerte, 1);
end;
destructor TVerlauf.Destroy;
begin
Verlauf.Free;
inherited;
end;
procedure TVerlauf.Durchlauf(Datum: TDate);
begin
if Verlauf.Count = 0 then
ErsterTag := Datum;
Verlauf.Add(0);
Verlaufswerte[0] += 1;
end;
procedure TVerlauf.Treffer;
var
Tag: Integer;
begin
if Verlauf.Count = 1 then
Tag := 1
else
Tag := Verlauf.Items[Verlauf.Count - 2] + 1;
Verlauf.Last := Tag;
if Tag > High(Verlaufswerte) then
SetLength(Verlaufswerte, Tag + 1);
Verlaufswerte[0] -= 1;
Verlaufswerte[Tag] += 1;
end;
function TVerlauf.Wert (Datum: TDate): Double;
var
i, Tag: Integer;
WahrscheinlichkeitTag: Double; //Wahrscheinlichkeit dafür, dass auf den gestrigen Tag ein Treffer folgt.
WahrscheinlichkeitSitzung: Double; //Wahrscheinlichkeit dafür, dass eine Sitzung so lange dauert.
begin
Tag := Verlauf[DaysBetween(Datum, ErsterTag) - 1];
if Tag = High(Verlaufswerte) then
WahrscheinlichkeitTag := 0
else
WahrscheinlichkeitTag := Verlaufswerte[Tag + 1] / Verlaufswerte[Tag];
if High(Verlaufswerte) = 0 then
WahrscheinlichkeitSitzung := 0
else
WahrscheinlichkeitSitzung := Verlaufswerte[Tag + 1] / Verlaufswerte[1];
Result := WahrscheinlichkeitTag * 2/3 + WahrscheinlichkeitSitzung * 1/3;
end;
end.
|
unit xEmailSender_UT;
interface
uses
DUnitX.TestFramework, xEmailSender_I, xEmailSenderMAPI_U, xEmail_I, delphi.mocks;
type
TIEmailMock_Blank = class (TInterfacedObject, IEmail)
end;
[TestFixture]
xEmailSenderUT = class(TObject)
public
FemSend : TEmailSenderMAPI;
[Setup]
procedure Setup;
[TearDown]
procedure TearDown;
[Test]
procedure TestMockSend;
end;
implementation
uses typInfo;
procedure xEmailSenderUT.Setup;
begin
FemSend := TEmailSenderMAPI.create;
end;
procedure xEmailSenderUT.TearDown;
begin
FemSend.Free;
end;
procedure xEmailSenderUT.TestMockSend;
var MockEmail : IEmail;
res : TEmailSendResult;
begin
MockEmail := TIEmailMock_Blank.create;
Assert.WillRaise(procedure begin FemSend.SendEmail( MockEmail );end, Exception_EmailSender_NoRecipients);
end;
initialization
TDUnitX.RegisterTestFixture(xEmailSenderUT);
end.
|
unit AudioSettings;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.ExtCtrls,
Vcl.Buttons, GraphicsSpeedButton, MediaPlayTrackBar,
GraphicsButton, Vcl.StdCtrls, Vcl.Menus, Vcl.Samples.Spin,
VideoConverterInt, VideoEffectInt;
type
TfrmAudioSettings = class(TForm)
palRender: TPanel;
palConsole: TPanel;
tbSeek: TMediaPlayTrackBar;
PageControl1: TPageControl;
btnPlay: TGraphicsSpeedButton;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
TabSheet3: TTabSheet;
lblVolumeStream: TLabel;
tbVolumeStream: TTrackBar;
Label1: TLabel;
edMusic: TEdit;
Label2: TLabel;
tbVolumeMusic: TTrackBar;
Label3: TLabel;
tbVolumeRecord: TTrackBar;
Button1: TButton;
lblRecord: TLabel;
btnImport: TButton;
btnRemove: TButton;
btnRemoveRecord: TButton;
btnClip: TButton;
lblTime: TLabel;
procedure FormCreate(Sender: TObject);
procedure palRenderResize(Sender: TObject);
procedure btnPlayClick(Sender: TObject);
procedure tbSeekChange(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Button1Click(Sender: TObject);
procedure tbVolumeStreamChange(Sender: TObject);
procedure tbVolumeMusicChange(Sender: TObject);
procedure tbVolumeRecordChange(Sender: TObject);
private
{ Private declarations }
FItem : PVCItem;
FMediaInfo: PMediaInfo;
FPlayer : Pointer;
FPlaying : Boolean;
FDuration : Integer;
FChanging : Boolean;
procedure Pause();
procedure OnPause();
procedure SetTimeInfo(sec: Integer);
private
procedure OnProgress(var msg: TMessage); message VC_VIDEO_RENDER_PROGRESS;
procedure OnPlayEnd(var msg: TMessage); message VC_VIDEO_RENDER_END;
protected
{ protected declarations }
procedure CreateParams(var Params: TCreateParams); override;
public
{ Public declarations }
procedure InitForm(Item: PVCItem);
end;
implementation
{$R *.dfm}
uses ImageResource, Functions, Profile, Main, Recording;
procedure TfrmAudioSettings.Button1Click(Sender: TObject);
var
frmRecording: TfrmRecording;
begin
end;
procedure TfrmAudioSettings.CreateParams(var Params: TCreateParams);
begin
inherited;
Params.WndParent := 0;
Params.ExStyle := Params.ExStyle or WS_EX_APPWINDOW;
end;
procedure TfrmAudioSettings.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if FPlayer <> nil then
begin
vcVideoPlayerDestroy(FPlayer);
FPlayer := nil;
end;
frmMain.Show();
Action := caFree;
end;
procedure TfrmAudioSettings.FormCreate(Sender: TObject);
begin
btnPlay.SetImage(imagePlay);
PageControl1.ActivePageIndex := 0;
end;
procedure TfrmAudioSettings.palRenderResize(Sender: TObject);
begin
if FPlayer <> nil then
begin
vcVideoPlayerResize(FPlayer);
end;
end;
procedure TfrmAudioSettings.tbSeekChange(Sender: TObject);
var
Pos: Integer;
begin
Pos := tbSeek.Position;
SetTimeInfo(Pos);
vcVideoPlayerSeekTo(FPlayer, Pos * AV_TIME_BASE_LL);
OnPause();
end;
procedure TfrmAudioSettings.tbVolumeMusicChange(Sender: TObject);
begin
if FChanging then Exit;
vcVideoPlayerSetVolume(FPlayer, 1, tbVolumeStream.Position);
end;
procedure TfrmAudioSettings.tbVolumeRecordChange(Sender: TObject);
begin
if FChanging then Exit;
vcVideoPlayerSetVolume(FPlayer, 2, tbVolumeStream.Position);
end;
procedure TfrmAudioSettings.tbVolumeStreamChange(Sender: TObject);
begin
if FChanging then Exit;
vcVideoPlayerSetVolume(FPlayer, 0, tbVolumeStream.Position);
end;
procedure TfrmAudioSettings.Pause();
begin
if FPlaying then
begin
vcVideoPlayerPause(FPlayer);
FPlaying := FALSE;
btnPlay.SetImage(imagePlay);
end;
end;
procedure TfrmAudioSettings.OnPause();
begin
if FPlaying then
begin
FPlaying := FALSE;
btnPlay.SetImage(imagePlay);
end;
end;
procedure TfrmAudioSettings.btnPlayClick(Sender: TObject);
begin
if FPlaying then
begin
vcVideoPlayerPause(FPlayer);
FPlaying := FALSE;
btnPlay.SetImage(imagePlay);
end else
begin
vcVideoPlayerResume(FPlayer);
FPlaying := TRUE;
btnPlay.SetImage(imagePause);
end;
end;
procedure TfrmAudioSettings.InitForm(Item: PVCItem);
var
Duration: Int64;
begin
FChanging := TRUE;
FItem := Item;
FMediaInfo := Item.m_MediaInfo;
Self.HandleNeeded;
Self.Caption := FMediaInfo.m_szFileName;
FPlayer := vcCreateVideoPlayer(palRender.Handle, Self.Handle, FItem, VC_VIDEO_RENDER_MODE_DEST);
if FItem.m_ClipStop <> 0 then
begin
Duration := FItem.m_ClipStop - FItem.m_ClipStart;
end else
begin
Duration := FMediaInfo.m_Duration - FItem.m_ClipStart;
end;
FDuration := (Duration + AV_TIME_BASE_LL - 1) div AV_TIME_BASE_LL;
tbSeek.Max := FDuration;
lblTime.Caption := '';
// Page 1
tbVolumeStream.Enabled := FMediaInfo.m_bAudioStream <> 0;
tbVolumeStream.Position := FItem.m_AudioTrack[0].m_Volume;
// Page 2
if Item.m_AudioTrack[1].m_Media <> nil then
begin
edMusic.Text := ExtractFileName(FItem.m_AudioTrack[1].m_Media.m_szFileName);
tbVolumeMusic.Position := FItem.m_AudioTrack[1].m_Volume;
end else begin
edMusic.Text := '';
btnRemove.Enabled := FALSE;
btnClip.Enabled := FALSE;
tbVolumeMusic.Enabled := FALSE;
tbVolumeMusic.Position := 0;
end;
// Page 3
if Item.m_AudioTrack[2].m_Media <> nil then
begin
lblRecord.Caption := 'Recording duration:' + GetAVTimeString(FItem.m_AudioTrack[2].m_Media.m_Duration);
tbVolumeRecord.Position := FItem.m_AudioTrack[2].m_Volume;
end else begin
lblRecord.Caption := 'No recording';
btnRemoveRecord.Enabled := FALSE;
tbVolumeRecord.Enabled := FALSE;
tbVolumeRecord.Position := 0;;
end;
FChanging := FALSE;
end;
procedure TfrmAudioSettings.OnProgress(var msg: TMessage);
begin
SetTimeInfo(msg.LParam);
end;
procedure TfrmAudioSettings.OnPlayEnd(var msg: TMessage);
begin
FPlaying := FALSE;
btnPlay.SetImage(imagePlay);
end;
procedure TfrmAudioSettings.SetTimeInfo(sec: Integer);
begin
tbSeek.Position := sec;
lblTime.Caption := GetDurationProcString(sec, FDuration);
end;
end.
|
unit CommParser;
(***** Code Written By Huang YanLai *****)
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Scanner,RepInfoIntf, LXScanner;
type
TCommonParser = class(TDataModule)
Scanner: TLXScanner;
private
protected
{ Private declarations }
FReporter : IReport;
FTokenSeq : integer;
token : TLXToken;
procedure doParse; virtual;
procedure goBackAToken;
function nextToken: TLXToken;
procedure reportInfo; virtual;
procedure beforeAnalyse; virtual;
procedure afterAnalyse; virtual;
procedure analyseToken; virtual;
procedure beforeExecute; virtual;
public
{ Public declarations }
function Execute(s : TStream; Reporter : IReport):boolean;
end;
var
CommonParser: TCommonParser;
const
feedBackCount = 50;
function inList(const s: string;const list: array of string): integer;
function isKeyword(token:TLXToken; const keyword:string):boolean;
function getIdentifier(token:TLXToken):string;
function isSymbol(token:TLXToken; symbol:char):boolean;
function getString(token:TLXToken; var s:string):boolean;
implementation
uses ProgDlg2;
{$R *.DFM}
{ help procedures/functions }
function inList(const s: string;
const list: array of string): integer;
var
i : integer;
begin
result := -1;
for i:=low(list) to high(list) do
if CompareText(list[i],s)=0 then
begin
result := i;
break;
end;
end;
function isKeyword(token:TLXToken; const keyword:string):boolean;
begin
result := (token<>nil) and (token.Token=ttKeyword)
and (compareText(token.text,keyword)=0);
end;
function getIdentifier(token:TLXToken):string;
begin
if (token<>nil) and (token.Token=ttIdentifier) then
result := token.text else
result := '';
end;
function isSymbol(token:TLXToken; symbol:char):boolean;
begin
result := (token<>nil) and (token.Token=ttSpecialChar)
and (token.text=symbol);
end;
function getString(token:TLXToken; var s:string):boolean;
begin
result := (token<>nil) and (token.Token=ttString);
if result then s:=token.text;
end;
{ TCommonParser }
procedure TCommonParser.afterAnalyse;
begin
end;
procedure TCommonParser.analyseToken;
begin
end;
procedure TCommonParser.beforeAnalyse;
begin
end;
procedure TCommonParser.beforeExecute;
begin
end;
procedure TCommonParser.doParse;
begin
dlgProgress.lbInfo.Caption:='Analyse Tokens...';
dlgProgress.ProgressBar.Min:=0;
dlgProgress.ProgressBar.max:=Scanner.Count;
FTokenSeq:=0;
beforeAnalyse;
token := nextToken;
while token<>nil do
begin
analyseToken;
token := nextToken;
end;
afterAnalyse;
end;
function TCommonParser.Execute(s : TStream; Reporter : IReport):boolean;
begin
FReporter := Reporter;
beforeExecute;
dlgProgress.execute;
try
dlgProgress.setInfo('Read Tokens...');
dlgProgress.checkCanceled;
Scanner.Analyze(s);
doParse;
if not dlgProgress.canceled then
reportInfo;
finally
result := not dlgProgress.canceled;
FReporter := nil;
dlgProgress.close;
end;
end;
procedure TCommonParser.goBackAToken;
begin
if (FTokenSeq>0) and (token<>nil) then
begin
dec(FTokenSeq);
//outputDebugString(':back');
end;
end;
function TCommonParser.nextToken: TLXToken;
begin
if (FTokenSeq mod feedBackCount)=0 then
begin
dlgProgress.ProgressBar.Position:=FTokenSeq;
Application.ProcessMessages;
if dlgProgress.canceled then abort;
end;
// filter out comments
while FTokenSeq<Scanner.count do
begin
result := Scanner.Token[FTokenSeq];
inc(FTokenSeq);
//outputDebugString(pchar(result.text));
if result.Token<>ttComment then exit;
end;
result := nil;
end;
procedure TCommonParser.reportInfo;
begin
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireMonkey Platform }
{ }
{ Copyright(c) 2012-2013 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit FMX.Media.Android;
interface
uses
Androidapi.JNI.Media, System.Types, FMX.Media, Androidapi.JNI.VideoView,
Androidapi.JNI.App, Androidapi.JNI.Widget, FMX.Messages;
type
TAndroidCaptureDeviceManager = class(TCaptureDeviceManager)
public
constructor Create; override;
end;
TAndroidMedia = class(TMedia)
private
FPlayer: JMediaPlayer;
FVolume: Single;
protected
procedure SeekToBegin;
function GetDuration: TMediaTime; override;
function GetCurrent: TMediaTime; override;
procedure SetCurrent(const Value: TMediaTime); override;
function GetVideoSize: TPointF; override;
function GetMediaState: TMediaState; override;
function GetVolume: Single; override;
procedure SetVolume(const Value: Single); override;
procedure UpdateMediaFromControl; override;
procedure DoPlay; override;
procedure DoStop; override;
public
constructor Create(const AFileName: string); override;
destructor Destroy; override;
end;
TAndroidMediaCodec = class(TCustomMediaCodec)
public
function CreateFromFile(const AFileName: string): TMedia; override;
end;
TAndroidVideo = class(TMedia)
private
FVideoPlayer: JVideoView;
FLayout: JLinearLayout;
FDialog : JDialog;
FVideoSize: TSize;
FOrientationChangedId: Integer;
function AllAssigned : Boolean;
procedure RealignView;
procedure RetreiveVideoSize;
procedure OrientationChangedHandler(const Sender: TObject; const Msg : TMessage);
protected
procedure SeekToBegin;
function GetDuration: TMediaTime; override;
function GetCurrent: TMediaTime; override;
procedure SetCurrent(const Value: TMediaTime); override;
function GetVideoSize: TPointF; override;
function GetMediaState: TMediaState; override;
function GetVolume: Single; override;
procedure SetVolume(const Value: Single); override;
procedure UpdateMediaFromControl; override;
procedure DoPlay; override;
procedure DoStop; override;
public
constructor Create(const AFileName: string); override;
destructor Destroy; override;
end;
TAndroidVideoCodec = class(TCustomMediaCodec)
public
function CreateFromFile(const AFileName: string): TMedia; override;
end;
implementation
uses
Androidapi.Bitmap, Androidapi.JNIBridge, Androidapi.JNI.JavaTypes, Androidapi.JNI.GraphicsContentViewText,
Androidapi.JNI.Hardware, System.RTLConsts, System.Math, System.SysUtils, System.SyncObjs, FMX.Consts, FMX.Types,
FMX.PixelFormats, FMX.Surfaces, FMX.Graphics, FMX.Helpers.Android, FMX.Forms;
{$REGION 'Local Class Declarations'}
type
TAndroidAudioCaptureDevice = class(TAudioCaptureDevice)
private
FRecorder: JMediaRecorder;
protected
procedure DoStartCapture; override;
procedure DoStopCapture; override;
function GetDeviceState: TCaptureDeviceState; override;
public
destructor Destroy; override;
end;
TAndroidVideoCaptureDevice = class;
TAndroidVideoCaptureCallback = class(TJavaLocal, JCamera_PreviewCallback)
private
[weak] FCaptureDevice: TAndroidVideoCaptureDevice;
public
procedure onPreviewFrame(P1: TJavaArray<Byte>; P2: JCamera); cdecl;
end;
TAndroidVideoCaptureDevice = class(TVideoCaptureDevice)
private const
CaptureTimerInterval = 33;
VideoConversionJPEGQuality = 75;
private
SurfaceSection: TCriticalSection;
UpdatedSection: TCriticalSection;
QueueSection: TCriticalSection;
FCameraId: Integer;
FCamera: JCamera;
FCapturing: Boolean;
FQuality: TVideoCaptureQuality;
FCallback: TAndroidVideoCaptureCallback;
SharedBuffer: TJavaArray<Byte>;
SharedBufferSize: TPoint;
SharedBufferBytes: Integer;
QueuedBufferCount: Integer;
SharedBufferFormat: Integer;
SharedSurface: TBitmapSurface;
SharedSurfaceUpdated: Boolean;
CapturePollingTimer: TTimer;
procedure CopyBufferToSurface;
function GetCamera: JCamera;
procedure AddQueueBuffer;
procedure RemoveQueueBuffer;
procedure OnCaptureTimer(Sender: TObject);
protected
procedure DoStartCapture; override;
procedure DoStopCapture; override;
procedure DoSampleBufferToBitmap(const ABitmap: TBitmap; const ASetSize: Boolean); override;
function GetDeviceProperty(const Prop: TCaptureDevice.TProperty): string; override;
function GetDeviceState: TCaptureDeviceState; override;
function GetPosition: TDevicePosition; override;
function GetQuality: TVideoCaptureQuality; override;
procedure SetQuality(const Value: TVideoCaptureQuality); override;
function GetHasFlash: Boolean; override;
function GetFlashMode: TFlashMode; override;
procedure SetFlashMode(const Value: TFlashMode); override;
function GetHasTorch: Boolean; override;
function GetTorchMode: TTorchMode; override;
procedure SetTorchMode(const Value: TTorchMode); override;
function GetFocusMode: TFocusMode; override;
procedure SetFocusMode(const Value: TFocusMode); override;
public
property CameraId: Integer read FCameraId;
property Camera: JCamera read GetCamera;
constructor Create(const AManager: TCaptureDeviceManager; const ADefault: Boolean); override;
destructor Destroy; override;
end;
{$ENDREGION}
{$REGION 'TAndroidCaptureDeviceManager'}
constructor TAndroidCaptureDeviceManager.Create;
var
I: Integer;
CameraDevice: TAndroidVideoCaptureDevice;
begin
inherited;
TAndroidAudioCaptureDevice.Create(Self, True);
for I := 0 to TJCamera.JavaClass.getNumberOfCameras - 1 do
begin
CameraDevice := TAndroidVideoCaptureDevice.Create(Self, I = 0);
CameraDevice.FCameraId := I;
end;
end;
{$ENDREGION}
{$REGION 'TAndroidAudioCaptureDevice'}
destructor TAndroidAudioCaptureDevice.Destroy;
begin
if Assigned(FRecorder) then
FRecorder := nil;
inherited;
end;
procedure TAndroidAudioCaptureDevice.DoStartCapture;
begin
FRecorder := TJMediaRecorder.JavaClass.init;
FRecorder.setAudioSource(TJMediaRecorder_AudioSource.JavaClass.MIC);
FRecorder.setOutputFormat(TJMediaRecorder_OutputFormat.JavaClass.THREE_GPP);
FRecorder.setAudioEncoder(TJMediaRecorder_AudioEncoder.JavaClass.AMR_NB);
FRecorder.setOutputFile(StringToJString(FileName));
FRecorder.prepare;
FRecorder.start;
end;
procedure TAndroidAudioCaptureDevice.DoStopCapture;
begin
if Assigned(FRecorder) then
begin
FRecorder.stop;
FRecorder := nil;
end;
end;
function TAndroidAudioCaptureDevice.GetDeviceState: TCaptureDeviceState;
begin
if Assigned(FRecorder) then
Result := TCaptureDeviceState.Capturing
else
Result := TCaptureDeviceState.Stopped;
end;
{$ENDREGION}
{$REGION 'TAndroidVideoCaptureDevice'}
procedure TAndroidVideoCaptureCallback.onPreviewFrame(P1: TJavaArray<Byte>; P2: JCamera);
begin
if Assigned(FCaptureDevice) then
begin
if FCaptureDevice.FCapturing then
FCaptureDevice.CopyBufferToSurface;
FCaptureDevice.RemoveQueueBuffer;
end;
end;
constructor TAndroidVideoCaptureDevice.Create(const AManager: TCaptureDeviceManager; const ADefault: Boolean);
begin
inherited;
SurfaceSection:= TCriticalSection.Create;
UpdatedSection:= TCriticalSection.Create;
QueueSection:= TCriticalSection.Create;
FCapturing := False;
end;
destructor TAndroidVideoCaptureDevice.Destroy;
begin
if FCapturing then
Self.DoStopCapture;
if Assigned(FCamera) then
begin
FCamera.setPreviewCallbackWithBuffer(nil);
FCamera := nil;
end;
if Assigned(FCallback) then
FCallback := nil;
QueueSection.Free;
UpdatedSection.Free;
SurfaceSection.Free;
inherited;
end;
function TAndroidVideoCaptureDevice.GetCamera: JCamera;
begin
if not Assigned(FCamera) then
FCamera := TJCamera.JavaClass.open(FCameraId);
Result := FCamera;
end;
function TAndroidVideoCaptureDevice.GetDeviceProperty(const Prop: TCaptureDevice.TProperty): string;
begin
case Prop of
TCaptureDevice.TProperty.UniqueID:
Result := FCameraId.ToString;
else
Result := '';
end;
end;
function TAndroidVideoCaptureDevice.GetDeviceState: TCaptureDeviceState;
begin
if FCapturing then
Result := TCaptureDeviceState.Capturing
else
Result := TCaptureDeviceState.Stopped;
end;
function TAndroidVideoCaptureDevice.GetQuality: TVideoCaptureQuality;
begin
Result := FQuality;
end;
procedure TAndroidVideoCaptureDevice.SetQuality(const Value: TVideoCaptureQuality);
begin
FQuality := Value;
case FQuality of
TVideoCaptureQuality.vcPhotoQuality: ;
TVideoCaptureQuality.vcHighQuality: ;
TVideoCaptureQuality.vcMediumQuality: ;
TVideoCaptureQuality.vcLowQuality: ;
end;
end;
function TAndroidVideoCaptureDevice.GetPosition: TDevicePosition;
begin
Result := TDevicePosition.dpUnspecified;
end;
function TAndroidVideoCaptureDevice.GetHasFlash: Boolean;
var
Params: JCamera_Parameters;
ModeList: JList;
begin
Params := Camera.getParameters;
if not Assigned(Params) then
Exit(False);
ModeList := Params.getSupportedFlashModes;
if not Assigned(ModeList) then
Exit(False);
Result := ModeList.contains(TJCamera_Parameters.JavaClass.FLASH_MODE_ON) or
ModeList.contains(TJCamera_Parameters.JavaClass.FLASH_MODE_AUTO);
end;
function TAndroidVideoCaptureDevice.GetHasTorch: Boolean;
var
Params: JCamera_Parameters;
ModeList: JList;
begin
Params := Camera.getParameters;
if not Assigned(Params) then
Exit(False);
ModeList := Params.getSupportedFlashModes;
if not Assigned(ModeList) then
Exit(False);
Result := ModeList.contains(TJCamera_Parameters.JavaClass.FLASH_MODE_TORCH);
end;
function TAndroidVideoCaptureDevice.GetFlashMode: TFlashMode;
var
Params: JCamera_Parameters;
FlashMode: JString;
FlashModeText: string;
begin
Params := Camera.getParameters;
if not Assigned(Params) then
Exit(inherited);
FlashMode := Params.getFlashMode;
if not Assigned(FlashMode) then
Exit(inherited);
FlashModeText := JStringToString(FlashMode);
if SameText(FlashModeText, JStringToString(TJCamera_Parameters.JavaClass.FLASH_MODE_ON)) then
Result := TFlashMode.fmFlashOn
else if SameText(FlashModeText, JStringToString(TJCamera_Parameters.JavaClass.FLASH_MODE_AUTO)) then
Result := TFlashMode.fmAutoFlash
else
Result := TFlashMode.fmFlashOff;
end;
procedure TAndroidVideoCaptureDevice.SetFlashMode(const Value: TFlashMode);
var
Params: JCamera_Parameters;
begin
Params := Camera.getParameters;
if not Assigned(Params) then
Exit;
case Value of
TFlashMode.fmAutoFlash:
Params.setFlashMode(TJCamera_Parameters.JavaClass.FLASH_MODE_AUTO);
TFlashMode.fmFlashOff:
Params.setFlashMode(TJCamera_Parameters.JavaClass.FLASH_MODE_OFF);
TFlashMode.fmFlashOn:
Params.setFlashMode(TJCamera_Parameters.JavaClass.FLASH_MODE_ON);
end;
Camera.setParameters(Params);
end;
function TAndroidVideoCaptureDevice.GetFocusMode: TFocusMode;
var
Params: JCamera_Parameters;
FocusMode: JString;
FocusModeText: string;
begin
Params := Camera.getParameters;
if not Assigned(Params) then
Exit(inherited);
FocusMode := Params.getFocusMode;
if not Assigned(FocusMode) then
Exit(inherited);
FocusModeText := JStringToString(FocusMode);
if SameText(FocusModeText, JStringToString(TJCamera_Parameters.JavaClass.FOCUS_MODE_AUTO)) then
Result := TFocusMode.fmAutoFocus
else if SameText(FocusModeText, JStringToString(TJCamera_Parameters.JavaClass.FOCUS_MODE_CONTINUOUS_VIDEO)) then
Result := TFocusMode.fmContinuousAutoFocus
else if SameText(FocusModeText, JStringToString(TJCamera_Parameters.JavaClass.FOCUS_MODE_CONTINUOUS_PICTURE)) then
Result := TFocusMode.fmContinuousAutoFocus
else
Result := TFocusMode.fmLocked;
end;
procedure TAndroidVideoCaptureDevice.SetFocusMode(const Value: TFocusMode);
var
Params: JCamera_Parameters;
begin
Params := Camera.getParameters;
if not Assigned(Params) then
Exit;
case Value of
TFocusMode.fmAutoFocus:
Params.setFocusMode(TJCamera_Parameters.JavaClass.FOCUS_MODE_AUTO);
TFocusMode.fmContinuousAutoFocus:
Params.setFocusMode(TJCamera_Parameters.JavaClass.FOCUS_MODE_CONTINUOUS_PICTURE);
TFocusMode.fmLocked:
Params.setFocusMode(TJCamera_Parameters.JavaClass.FOCUS_MODE_FIXED);
end;
Camera.setParameters(Params);
end;
function TAndroidVideoCaptureDevice.GetTorchMode: TTorchMode;
var
Params: JCamera_Parameters;
FlashMode: JString;
begin
Params := Camera.getParameters;
if not Assigned(Params) then
Exit(inherited);
FlashMode := Params.getFlashMode;
if not Assigned(FlashMode) then
Exit(inherited);
if SameText(JStringToString(FlashMode), JStringToString(TJCamera_Parameters.JavaClass.FLASH_MODE_TORCH)) then
Result := TTorchMode.tmModeOn
else
Result := TTorchMode.tmModeOff
end;
procedure TAndroidVideoCaptureDevice.SetTorchMode(const Value: TTorchMode);
var
Params: JCamera_Parameters;
begin
Params := Camera.getParameters;
if not Assigned(Params) then
Exit;
case Value of
TTorchMode.tmModeOff:
if GetTorchMode = TTorchMode.tmModeOn then
begin
Params.setFlashMode(TJCamera_Parameters.JavaClass.FLASH_MODE_OFF);
Camera.setParameters(Params);
end;
TTorchMode.tmModeOn:
if GetTorchMode = TTorchMode.tmModeOff then
begin
Params.setFlashMode(TJCamera_Parameters.JavaClass.FLASH_MODE_TORCH);
Camera.setParameters(Params);
end;
end;
end;
procedure TAndroidVideoCaptureDevice.AddQueueBuffer;
begin
QueueSection.Acquire;
try
if QueuedBufferCount < 1 then
begin
if Assigned(SharedBuffer) then
FreeAndNil(SharedBuffer);
SharedBuffer := TJavaArray<Byte>.Create(SharedBufferBytes);
Camera.addCallbackBuffer(SharedBuffer);
Inc(QueuedBufferCount);
end;
finally
QueueSection.Release;
end;
end;
procedure TAndroidVideoCaptureDevice.RemoveQueueBuffer;
begin
QueueSection.Acquire;
try
QueuedBufferCount := Max(QueuedBufferCount - 1, 0);
finally
QueueSection.Release;
end;
end;
procedure TAndroidVideoCaptureDevice.DoStartCapture;
var
Params: JCamera_Parameters;
PreviewSize: JCamera_Size;
begin
if FCapturing then
Exit;
Params := Camera.getParameters;
if not Assigned(Params) then
Exit;
PreviewSize := Params.getPreviewSize;
SharedBufferSize := TPoint.Create(PreviewSize.width, PreviewSize.height);
SharedBufferFormat := Params.getPreviewFormat;
SharedBufferBytes := SharedBufferSize.X * SharedBufferSize.Y *
(TJImageFormat.JavaClass.getBitsPerPixel(SharedBufferFormat) div 8);
FCallback := TAndroidVideoCaptureCallback.Create;
FCallback.FCaptureDevice := Self;
SharedSurface := TBitmapSurface.Create;
SharedSurface.SetSize(SharedBufferSize.X, SharedBufferSize.Y, pfA8B8G8R8);
SharedSurfaceUpdated := False;
AddQueueBuffer;
Camera.setPreviewCallbackWithBuffer(FCallback);
Camera.startPreview;
FCapturing := True;
CapturePollingTimer := TTimer.Create(nil);
CapturePollingTimer.Interval := CaptureTimerInterval;
CapturePollingTimer.OnTimer := OnCaptureTimer;
CapturePollingTimer.Enabled := True;
end;
procedure TAndroidVideoCaptureDevice.DoStopCapture;
begin
if FCapturing then
begin
if Assigned(CapturePollingTimer) then
FreeAndNil(CapturePollingTimer);
Camera.stopPreview;
Camera.setPreviewCallbackWithBuffer(nil);
if Assigned(FCallback) then
FCallback := nil;
if Assigned(SharedSurface) then
FreeAndNil(SharedSurface);
FCapturing := False;
end;
end;
procedure TAndroidVideoCaptureDevice.CopyBufferToSurface;
var
Image: JYuvImage;
Rect: JRect;
Stream: JByteArrayOutputStream;
LoadOptions: JBitmapFactory_Options;
Bitmap: JBitmap;
begin
if Assigned(SharedBuffer) and Assigned(SharedSurface) then
begin
SurfaceSection.Acquire;
try
Image := TJYuvImage.JavaClass.init(SharedBuffer, SharedBufferFormat, SharedBufferSize.X, SharedBufferSize.Y, nil);
finally
SurfaceSection.Release;
end;
Rect := TJRect.JavaClass.init(0, 0, SharedBufferSize.X, SharedBufferSize.Y);
Stream := TJByteArrayOutputStream.JavaClass.init(0);
Image.compressToJpeg(Rect, VideoConversionJPEGQuality, Stream);
// Some resources are freed as early as possible to reduce impact on working memory.
Rect := nil;
Image := nil;
LoadOptions := TJBitmapFactory_Options.JavaClass.init;
Bitmap := TJBitmapFactory.JavaClass.decodeByteArray(Stream.toByteArray, 0, Stream.Size, LoadOptions);
Stream := nil;
JBitmapToSurface(Bitmap, SharedSurface);
Bitmap := nil;
UpdatedSection.Acquire;
try
SharedSurfaceUpdated := True;
finally
UpdatedSection.Release;
end;
end;
end;
procedure TAndroidVideoCaptureDevice.OnCaptureTimer(Sender: TObject);
var
UpdatePending: Boolean;
begin
UpdatedSection.Acquire;
try
UpdatePending := SharedSurfaceUpdated;
SharedSurfaceUpdated := False;
finally
UpdatedSection.Release;
end;
if UpdatePending then
begin
if Assigned(OnSampleBufferReady) then
OnSampleBufferReady(Self, 0);
end;
AddQueueBuffer;
end;
procedure TAndroidVideoCaptureDevice.DoSampleBufferToBitmap(const ABitmap: TBitmap; const ASetSize: Boolean);
var
BiData: TBitmapData;
I: Integer;
begin
if (not FCapturing) or (not Assigned(SharedSurface)) then
Exit;
if ASetSize then
ABitmap.SetSize(SharedBufferSize.X, SharedBufferSize.Y);
SurfaceSection.Acquire;
try
if ABitmap.Map(TMapAccess.maWrite, BiData) then
try
for I := 0 to SharedBufferSize.Y - 1 do
Move(SharedSurface.Scanline[I]^, BiData.GetScanline(I)^, SharedBufferSize.X * SharedSurface.BytesPerPixel);
finally
ABitmap.Unmap(BiData);
end;
finally
SurfaceSection.Release;
end;
end;
{$ENDREGION}
{$REGION 'TAndroidMedia'}
constructor TAndroidMedia.Create(const AFileName: string);
var
AudioService: JObject;
AudioManager: JAudioManager;
MaxVolume : Integer;
begin
inherited Create(AFileName);
FPlayer := TJMediaPlayer.JavaClass.init;
FPlayer.setDataSource(StringToJString(FileName));
FPlayer.prepare;
AudioService := SharedActivity.getSystemService(TJContext.JavaClass.AUDIO_SERVICE);
if Assigned(AudioService) then
AudioManager := TJAudioManager.Wrap((AudioService as ILocalObject).GetObjectID);
if Assigned(AudioManager) then
begin
MaxVolume := AudioManager.getStreamMaxVolume(TJAudioManager.JavaClass.STREAM_MUSIC);
FVolume := AudioManager.getStreamVolume(TJAudioManager.JavaClass.STREAM_MUSIC);
if MaxVolume > 0 then
FVolume := FVolume / MaxVolume ;
if FVolume > 1 then
FVolume := 1 ;
end;
end;
destructor TAndroidMedia.Destroy;
begin
FPlayer.release;
FPlayer := nil;
inherited Destroy;
end;
function TAndroidMedia.GetCurrent: TMediaTime;
begin
if Assigned(FPlayer) then
Result := FPlayer.getCurrentPosition
else
Result := 0;
end;
function TAndroidMedia.GetDuration: TMediaTime;
begin
Result := FPlayer.getDuration;
end;
function TAndroidMedia.GetMediaState: TMediaState;
begin
if Assigned(FPlayer) then
begin
if FPlayer.isPlaying then
Result := TMediaState.Playing
else
Result := TMediaState.Stopped;
end
else
Result := TMediaState.Unavailable;
end;
function TAndroidMedia.GetVideoSize: TPointF;
begin
if Assigned(FPlayer) then
Result := TPointF.Create(FPlayer.getVideoWidth, FPlayer.getVideoHeight)
else
Result := TPointF.Create(0, 0);
end;
function TAndroidMedia.GetVolume: Single;
begin
if Assigned(FPlayer) then
Result := FVolume
else
Result := 0;
end;
procedure TAndroidMedia.SeekToBegin;
begin
FPlayer.seekTo(0);
end;
procedure TAndroidMedia.SetCurrent(const Value: TMediaTime);
var
NewPos : Integer;
begin
if Assigned(FPlayer) then
begin
NewPos := Value;
if NewPos < 0 then
NewPos := 0;
FPlayer.seekTo(NewPos);
end;
end;
procedure TAndroidMedia.SetVolume(const Value: Single);
begin
FVolume := Value;
if FVolume < 0 then
FVolume := 0
else if FVolume > 1 then
FVolume := 1;
if Assigned(FPlayer) then
FPlayer.setVolume(FVolume, FVolume);
end;
procedure TAndroidMedia.UpdateMediaFromControl;
begin
end;
procedure TAndroidMedia.DoStop;
begin
FPlayer.stop;
end;
procedure TAndroidMedia.DoPlay;
begin
FPlayer.start;
end;
{$ENDREGION}
{$REGION 'TAndroidMediaCodec'}
function TAndroidMediaCodec.CreateFromFile(const AFileName: string): TMedia;
begin
Result := TAndroidMedia.Create(AFileName);
end;
{$ENDREGION}
{$REGION 'TAndroidVideoCodec'}
function TAndroidVideoCodec.CreateFromFile(const AFileName: string): TMedia;
begin
Result := TAndroidVideo.Create(AFileName);
end;
{$ENDREGION}
{$REGION 'TAndroidVideo'}
function TAndroidVideo.AllAssigned: Boolean;
begin
Result := Assigned(FVideoPlayer) and Assigned(FDialog);
end;
constructor TAndroidVideo.Create(const AFileName: string);
begin
inherited Create(AFileName);
RetreiveVideoSize;
CallInUIThread(
procedure
begin
FDialog := TJDialog.JavaClass.init(SharedActivity,-1);
FDialog.setCancelable(True);
FVideoPlayer := TJVideoView.JavaClass.init(SharedActivity);
FVideoPlayer.setVideoPath(StringToJString(FileName));
FVideoPlayer.setMediaController(TJMediaController.JavaClass.init(SharedActivity));
FVideoPlayer.requestFocus(0);
FLayout := TJLinearLayout.JavaClass.init(SharedActivity);
FLayout.addView(FVideoPlayer);
RealignView;
FDialog.setContentView(FLayout);
end);
FOrientationChangedId := TMessageManager.DefaultManager.SubscribeToMessage(TOrientationChangedMessage, OrientationChangedHandler);
end;
procedure TAndroidVideo.OrientationChangedHandler(const Sender: TObject; const Msg: TMessage);
begin
CallInUIThread(
procedure
begin
RealignView;
end
);
end;
procedure TAndroidVideo.RealignView;
const
GreatThatScreen = 100; // To be sure that destination rect will fit to fullscreen
var
VideoRect: TRectF;
begin
if Assigned(FLayout) then
begin
VideoRect := TRectF.Create(0, 0, FVideoSize.Width * GreatThatScreen, FVideoSize.Height * GreatThatScreen);
VideoRect.Fit(TRectF.Create(0, 0, Screen.Size.Width, Screen.Size.Height));
FLayout.setPadding(VideoRect.Round.Left, VideoRect.Round.Top, Screen.Size.Width - VideoRect.Round.Right,
Screen.Size.Height - VideoRect.Round.Bottom);
end;
end;
procedure TAndroidVideo.RetreiveVideoSize;
var
MediaPlayer: JMediaPlayer;
begin
MediaPlayer := TJMediaPlayer.JavaClass.init;
MediaPlayer.setDataSource(StringToJString(FileName));
MediaPlayer.prepare;
FVideoSize := TSize.Create(MediaPlayer.getVideoWidth, MediaPlayer.getVideoHeight);
MediaPlayer := nil;
end;
destructor TAndroidVideo.Destroy;
begin
TMessageManager.DefaultManager.Unsubscribe(TOrientationChangedMessage, FOrientationChangedId);
if Assigned(FVideoPlayer) then
FVideoPlayer := nil;
inherited Destroy;
end;
procedure TAndroidVideo.DoPlay;
begin
inherited;
CallInUIThread(
procedure
begin
if not FDialog.isShowing then
FDialog.show;
if not FVideoPlayer.isPlaying then
FVideoPlayer.start;
end);
end;
procedure TAndroidVideo.DoStop;
begin
inherited;
CallInUIThread(
procedure
begin
if FDialog.isShowing then
FDialog.hide;
if FVideoPlayer.isPlaying then
FVideoPlayer.stopPlayback;
end);
end;
function TAndroidVideo.GetCurrent: TMediaTime;
begin
Result := 0;
if AllAssigned then
Result := FVideoPlayer.getCurrentPosition;
end;
function TAndroidVideo.GetDuration: TMediaTime;
begin
Result := 0;
if AllAssigned then
Result := FVideoPlayer.getDuration;
end;
function TAndroidVideo.GetMediaState: TMediaState;
begin
if Assigned(FVideoPlayer) then
begin
if FVideoPlayer.isPlaying then
Result := TMediaState.Playing
else
Result := TMediaState.Stopped;
end
else
Result := TMediaState.Unavailable;
end;
function TAndroidVideo.GetVideoSize: TPointF;
begin
Result := PointF(FVideoSize.Width, FVideoSize.Height);
end;
function TAndroidVideo.GetVolume: Single;
begin
Result := NaN;
end;
procedure TAndroidVideo.SeekToBegin;
begin
if AllAssigned then
CallInUIThread(
procedure
begin
if FVideoPlayer.isPlaying then
FVideoPlayer.stopPlayback;
FVideoPlayer.seekTo(0);
end);
end;
procedure TAndroidVideo.SetCurrent(const Value: TMediaTime);
begin
inherited;
if AllAssigned then
CallInUIThread(
procedure
begin
FVideoPlayer.seekTo(Value);
end);
end;
procedure TAndroidVideo.SetVolume(const Value: Single);
begin
inherited;
end;
procedure TAndroidVideo.UpdateMediaFromControl;
begin
inherited;
end;
{$ENDREGION}
initialization
TMediaCodecManager.RegisterMediaCodecClass('.mov', SVMOVFiles, TMediaType.Video, TAndroidVideoCodec);
TMediaCodecManager.RegisterMediaCodecClass('.m4v', SVM4VFiles, TMediaType.Video, TAndroidVideoCodec);
TMediaCodecManager.RegisterMediaCodecClass('.mp4', SVMP4Files, TMediaType.Video, TAndroidVideoCodec);
TMediaCodecManager.RegisterMediaCodecClass('.mp3', SVMP3Files, TMediaType.Audio, TAndroidMediaCodec);
TMediaCodecManager.RegisterMediaCodecClass('.caf', SVCAFFiles, TMediaType.Audio, TAndroidMediaCodec);
TMediaCodecManager.RegisterMediaCodecClass('.3gp', SV3GPFiles, TMediaType.Audio, TAndroidMediaCodec);
end.
|
unit Utils;
interface
function Confirm(Msg: string): Boolean;
implementation
uses
Dialogs, UITypes;
function Confirm(Msg: string): Boolean;
begin
Result := MessageDlg(Msg, mtConfirmation, mbYesNoCancel, 0) = mrYes;
end;
end.
|
unit SAPCMSPushErrorReader2;
interface
uses
Classes, SysUtils, ComObj, CommUtils, ADODB;
type
TCMSPushError = packed record
sbillno: string; //单据编号
sbilltype: string; //单据类型
dt: TDateTime; //日期
dtCreate: TDateTime; //创建日期
sfac: string; //代工厂名称
serrtype: string; //错误类型
serreason: string; //错误原因
smsg1: string; //信息1
smsg2: string; //信息2
smsg3: string; //信息3
smsg4: string; //信息4
scount: string; //次数
end;
PCMSPushError = ^TCMSPushError;
TSAPCMSPushErrorReader2 = class
private
FList: TList;
FFile: string;
ExcelApp, WorkBook: Variant;
FLogEvent: TLogEvent;
procedure Open;
procedure Log(const str: string);
function GetCount: Integer;
function GetItems(i: Integer): PCMSPushError;
public
constructor Create(const sfile: string; aLogEvent: TLogEvent = nil);
destructor Destroy; override;
procedure Clear;
property Count: Integer read GetCount;
property Items[i: Integer]: PCMSPushError read GetItems;
end;
implementation
{ TSAPCMSPushErrorReader2 }
constructor TSAPCMSPushErrorReader2.Create(const sfile: string;
aLogEvent: TLogEvent = nil);
begin
FFile := sfile;
FLogEvent := aLogEvent;
FList := TList.Create;
Open;
end;
destructor TSAPCMSPushErrorReader2.Destroy;
begin
Clear;
FList.Free;
inherited;
end;
procedure TSAPCMSPushErrorReader2.Clear;
var
i: Integer;
p: PCMSPushError;
begin
for i := 0 to FList.Count - 1 do
begin
p := PCMSPushError(FList[i]);
Dispose(p);
end;
FList.Clear;
end;
function TSAPCMSPushErrorReader2.GetCount: Integer;
begin
Result := FList.Count;
end;
function TSAPCMSPushErrorReader2.GetItems(i: Integer): PCMSPushError;
begin
Result := PCMSPushError(FList[i]);
end;
procedure TSAPCMSPushErrorReader2.Log(const str: string);
begin
savelogtoexe(str);
if Assigned(FLogEvent) then
begin
FLogEvent(str);
end;
end;
procedure TSAPCMSPushErrorReader2.Open;
var
iSheetCount, iSheet: Integer;
stitle: string;
irow: Integer;
snumber: string;
aSAPOPOAllocPtr: PCMSPushError;
Conn: TADOConnection;
ADOTabXLS: TADOTable;
begin
Clear;
if not FileExists(FFile) then Exit;
ADOTabXLS := TADOTable.Create(nil);
Conn:=TADOConnection.Create(nil);
Conn.ConnectionString:='Provider=Microsoft.ACE.OLEDB.12.0;Data Source="' + FFile + '";Extended Properties=excel 8.0;Persist Security Info=False';
Conn.LoginPrompt:=false;
try
Conn.Connected:=true;
ADOTabXLS.Connection:=Conn;
ADOTabXLS.TableName:='['+'推送错误列表'+'$]';
ADOTabXLS.Active:=true;
ADOTabXLS.First;
while not ADOTabXLS.Eof do
begin
aSAPOPOAllocPtr := New(PCMSPushError);
FList.Add(aSAPOPOAllocPtr);
aSAPOPOAllocPtr^.sbillno := ADOTabXLS.FieldByName('单据编号').AsString;
aSAPOPOAllocPtr^.sbilltype := ADOTabXLS.FieldByName('单据类型').AsString;
aSAPOPOAllocPtr^.dt := ADOTabXLS.FieldByName('日期').AsDateTime;
aSAPOPOAllocPtr^.dtCreate := ADOTabXLS.FieldByName('创建日期').AsDateTime;
aSAPOPOAllocPtr^.sfac := ADOTabXLS.FieldByName('代工厂名称').AsString;
aSAPOPOAllocPtr^.serrtype := ADOTabXLS.FieldByName('错误类型').AsString;
aSAPOPOAllocPtr^.serreason := ADOTabXLS.FieldByName('错误原因').AsString;
aSAPOPOAllocPtr^.smsg1 := ADOTabXLS.FieldByName('信息1').AsString;
aSAPOPOAllocPtr^.smsg2 := ADOTabXLS.FieldByName('信息2').AsString;
aSAPOPOAllocPtr^.smsg3 := ADOTabXLS.FieldByName('信息3').AsString;
aSAPOPOAllocPtr^.smsg4 := ADOTabXLS.FieldByName('信息4').AsString;
aSAPOPOAllocPtr^.scount := ADOTabXLS.FieldByName('次数').AsString;
ADOTabXLS.Next;
end;
ADOTabXLS.Close;
Conn.Connected := False;
finally
FreeAndNil(Conn);
FreeAndNil(ADOTabXLS);
end;
end;
end.
|
unit WinUtils;
interface
uses Windows,winObjs,classes,Messages,forms;
type
{ TMessageComponent is a unvisible Component,
that creates a FUtilWindow to handle messages
such as timer messages, DDE messeges and all
you want. The style of the FUtilWindow is WS_Popup,
Size is 0. TMessageComponent.Wndroc only call
DefWindowProc.
}
TMessageComponent = class(TComponent)
protected
FUtilWindow : WWindow;
procedure WndProc(var MyMsg : TMessage); virtual;
public
constructor create(Aowner : TComponent); override;
destructor destroy; override;
end;
{ TFindWindow is module , that help you use mouse
to find window in the screen.
How to use;
1. set OnFinish = yourform.method
in yourform.method, FoundWindow indicate the found
window.
2. call start to begin find window
if you set ownerform ( if its owner is Tform, will
automaticly set ownerform = owner), the form will
hide. After you clicked a mouse button, ( call BeforeRestire
then ) the form will show again, then call yourform.method.
Note:
1. The property GetChild indicate you want find child window
or toplevel window(Popup or Overlapped)
2. The Event BeforeRestore likes OnFinish, but it will be
called before ownerform restore.
}
TFindWindow = class(TMessageComponent)
protected
procedure WndProc(var MyMsg : TMessage); override;
private
FOwnerForm : TForm;
FOwnerWindow : WWindow;
FFoundWindow : WWindow;
FOnFinish : TNotifyEvent;
FBeforeRestore : TNotifyEvent;
FGetChild : boolean;
FFindMode : boolean;
procedure SetOwnerForm(value : TForm);
procedure SetOwnerWindow(value : WWindow);
procedure Finish;
procedure Failure;
public
property OwnerWindow : WWindow read FOwnerWindow write SetOwnerWindow;
property FoundWindow : WWindow read FFoundWindow;
constructor create(Aowner : TComponent); override;
procedure Start;
destructor destroy; override;
published
property GetChild : boolean read FGetChild write FGetChild;
property OwnerForm : TForm read FOwnerForm write SetOwnerForm;
property OnFinish : TNotifyEvent read FOnFinish write FOnFinish;
property BeforeRestore : TNotifyEvent
read FBeforeRestore write FBeforeRestore;
end;
{ TSubClassWindow is a class that subClass from a window.
Create method needs a window handle.
Override the WndProc method, you can do something useful.
TSubClassWindow.WndProc only call previous Wndproc.
}
TSubClassWindow = class
private
procedure ReleaseWndProc;
protected
hWnd : THandle;
PreWndproc : Pointer;
FWindow : WWindow;
ObjInst : Pointer;
procedure WndProc(var MyMsg : TMessage); virtual;
public
Enabled : boolean;
constructor create(hw : THandle); virtual;
destructor Destroy; override;
procedure DefaultHandler(var Message); override;
end;
TSubClassWindowClass = class of TSubClassWindow;
TSubClasssNotifyMsg = record
Msg : Cardinal;
NotifyID : Longint;
TheClass : TSubClassWindowClass;
Result : Longint;
end;
var
SubClasssNotify : UINT;
const
SubClasssNotifyName = 'SubClasssNotify';
// subclass notify id (WParam)
scn_enabled = 1;
scn_disabled = 2;
scn_release = 3;
function SubClass(Wnd : HWnd;
TheClass:TSubClassWindowClass ):TSubClassWindow ;
function NotifySubClass(Wnd : HWnd; NotifyID : longint;
TheClass:TSubClassWindowClass):longint;
function ReleaseSubClass(Wnd : HWnd;
TheClass:TSubClassWindowClass):longint;
function EnableSubClass(Wnd : HWnd; TheClass:TSubClassWindowClass;
Enabled : boolean):longint;
(*
{ TDirectDrag makes a window movable-by-mouse
by handling WM_NCHitTest, and replacing
the result HTClient to HTCaption.
}
TDirectDrag = class(TSubClassWindow)
protected
procedure WndProc(var MyMsg : TMessage); override;
end;
{ TPassMessage send messages from a window
to another window, when method pass return true.
}
TPassMessage = class(TSubClassWindow)
protected
FReceiveWindow : WWindow;
// if pass return true, messges will be passed to Receive Window
function Pass(var MyMsg:TMessage):boolean; virtual; abstract;
procedure WndProc(var MyMsg : TMessage); override;
public
// source is the subclassed window handle
// receiver is the handle of the window witch receive message
// message from source to receiver
constructor Create(source,reciever : THandle);
destructor destroy; override;
end;
{ TPassMouseMsg inherites form TPassMessage.
It passes Mouse messages(contains NoneClient)
to another window.
}
const
WM_NCMouseFirst = WM_NCMouseMove;
WM_NCMouseLast = WM_NCMButtonDblClk;
type
TPassMouseMsg = class(TPassMessage)
protected
function Pass(var MyMsg:TMessage):boolean; override;
public
// if reverse is true , will reverse mouse (X,y)
Reverse : boolean;
end;
{ TDirectMoveSize makes a window sizable and movable-
by-mouse , by handling WM_NCHitTest
}
TDirectMoveSize = class(TSubClassWindow)
protected
procedure WndProc(var MyMsg : TMessage); override;
public
canMove : boolean;
canSize : boolean;
BorderWidth : integer;
constructor Create(hw : THandle);
end;
*)
implementation
// TMessageComponent
constructor TMessageComponent.create(Aowner : TComponent);
begin
inherited Create(AOwner);
FUtilWindow := WWindow.CreateBy(AllocateHWnd(WndProc));
FUtilWindow.style := longint(WS_Popup);
FUtilWindow.rect := Rect(0,0,0,0);
end;
destructor TMessageComponent.destroy;
begin
DeallocateHWnd(FUtilWindow.handle);
FUtilWindow.free;
inherited destroy;
end;
procedure TMessageComponent.WndProc(var MyMsg : TMessage);
begin
with MyMsg do
Result := DefWindowProc(FUtilWindow.Handle,Msg,wParam,lParam);
end;
// TFindWindow
constructor TFindWindow.create(Aowner : TComponent);
begin
inherited Create(AOwner);
FOwnerWindow := WWindow.Create;
if AOwner is TForm
then OwnerForm := TForm(AOwner)
else OwnerForm := nil;
FFoundWindow := WWindow.Create;
end;
destructor TFindWindow.destroy;
begin
FOwnerWindow.free;
FFoundWindow.free;
inherited destroy;
end;
procedure TFindWindow.Start;
begin
if FOwnerWindow.Isvalid
then FOwnerWindow.hide;
FUtilWindow.BringToForeGround;
FUtilWindow.SetCapture;
FFindmode:=FUtilWindow.captured;
if not FFindmode then Failure;
end;
procedure TFindWindow.finish;
begin
if Assigned(BeforeRestore)
then BeforeRestore(self);
if FOwnerWindow.Isvalid
then FOwnerWindow.BringToForeGround;
if Assigned(OnFinish)
then OnFinish(self);
end;
procedure TFindWindow.SetOwnerForm(value : TForm);
begin
if value=nil
then FOwnerWindow.handle := 0
else FOwnerWindow.handle := value.handle;
FOwnerForm := value;
end;
procedure TFindWindow.SetOwnerWindow(value : WWindow);
begin
FOwnerWindow.handle := value.handle;
end;
procedure TFindWindow.Failure;
begin
FFoundWindow.handle := Invalidhandle;
finish;
end;
procedure TFindWindow.WndProc(var MyMsg : TMessage);
var
p : TPoint;
begin
with TWMMouse(MyMsg) do
if FFindmode and
((msg=WM_LButtonDown) or (msg=WM_MButtonDown)
or (msg=WM_RButtonDown))
then begin
p := FUtilWindow.ClientToScreen(Point(xpos,ypos));
if GetChild
then FFoundWindow.GetFrom(p)
else FFoundWindow.GetPopOverFrom(p);
FFindmode := false;
FUtilWindow.releaseCapture;
finish;
end
else inherited WndProc(MyMsg);
end;
// TSubClassWindow
constructor TSubClassWindow.create(hw : THandle);
begin
FWindow := WWindow.Createby(hw);
PreWndproc := Pointer(Fwindow.Wndproc);
ObjInst := MakeObjectInstance(Wndproc);
Fwindow.Wndproc := longint(ObjInst);
Enabled := true;
end;
destructor TSubClassWindow.Destroy;
begin
ReleaseWndProc;
FreeObjectInstance(ObjInst);
FWindow.free;
end;
procedure TSubClassWindow.WndProc(var MyMsg : TMessage);
begin
if (MyMsg.msg=SubClasssNotify) then
with TSubClasssNotifyMsg(MyMsg) do
begin
if NotifyID=scn_release then
begin
if self is TheClass then
begin
result := longint(PreWndProc);
//PreWndProc := nil;
free;
end
else
begin
DefaultHandler(MyMsg);
if MyMsg.result<>longint(nil) then
begin
PreWndProc:=pointer(MyMsg.result);
MyMsg.result := longint(nil);
end;
end;
exit;
end;
if (self is TheClass) then
case NotifyID of
scn_disabled : enabled := false;
scn_enabled : enabled := true;
end;
end;
if MyMsg.msg=WM_Destroy then
ReleaseWndProc;
if enabled then
dispatch(MyMsg)
else
DefaultHandler(MyMsg);
if MyMsg.msg=WM_Destroy then
free;
end;
procedure TSubClassWindow.DefaultHandler(var Message);
begin
with TMessage(Message) do
result := callWindowProc(PreWndProc,FWindow.handle,
msg,WParam,LParam);
end;
function SubClass(Wnd : HWnd;
TheClass:TSubClassWindowClass ):TSubClassWindow ;
begin
assert(assigned(TheClass));
result := TheClass.Create(Wnd);
end;
function NotifySubClass(Wnd : HWnd; NotifyID : longint;
TheClass:TSubClassWindowClass):longint;
begin
result := SendMessage(Wnd,SubClasssNotify,
NotifyID,longint(TheClass));
end;
function ReleaseSubClass(Wnd : HWnd;
TheClass:TSubClassWindowClass):longint;
begin
result:=NotifySubClass(Wnd,scn_release,theClass);
end;
function EnableSubClass(Wnd : HWnd; TheClass:TSubClassWindowClass;
Enabled : boolean):longint;
var
Notify : longint;
begin
if enabled then
Notify:=scn_enabled
else
Notify:=scn_disabled;
result:=NotifySubClass(Wnd,Notify,theClass);
end;
(*
// TDirectDrag
procedure TDirectDrag.WndProc(var MyMsg : TMessage);
begin
inherited Wndproc(MyMsg);
with MyMsg do
if (msg=WM_NCHITTEST) and (result=HTClient)
then result := HTCaption;
end;
// TPassMessage
constructor TPassMessage.Create(source,reciever : THandle);
begin
inherited Create(source);
FReceiveWindow := WWindow.createby(reciever);
end;
destructor TPassMessage.destroy;
begin
FReceiveWindow.free;
inherited destroy;
end;
procedure TPassMessage.WndProc(var MyMsg : TMessage);
begin
with MyMsg do
if pass(MyMsg)
then result := sendMessage(FReceiveWindow.handle,
msg,WParam,LParam)
else inherited WndProc(MyMsg);
end;
// TPassMouseMsg
function TPassMouseMsg.Pass(var MyMsg:TMessage):boolean;
var
p : TPoint;
begin
with MyMsg do
pass := ((Msg>=WM_MouseFirst) and (Msg<=WM_MouseLast))
or (Msg=WM_NCHitTest)
or ((Msg>=WM_NCMouseFirst) and (Msg<=WM_NCMouseLast));
if result and Reverse and (MyMsg.msg<>WM_NCHitTest)
then with TWMMouse(MyMsg) do
begin
p := Point(xpos,ypos);
p := FWindow.ClientToScreen(p);
p := FReceiveWindow.ScreenToClient(p);
xpos := p.x;
ypos := p.y;
end;
end;
// TDirectMoveSize
constructor TDirectMoveSize.Create(hw : THandle);
begin
inherited Create(hw);
BorderWidth := 2;
CanMove := true;
CanSize := true;
end;
procedure TDirectMoveSize.WndProc(var MyMsg : TMessage);
var
left,right,top,bottom : boolean;
rect : TRect;
begin
if MyMsg.msg=wm_NCHitTest
then with TWMMouse(MyMsg) do
begin
if CanMove
then result := HTCaption
else result := HTClient;
if canSize
then begin
rect := FWindow.Rect;
left := (xpos>=rect.left) and (xpos<=rect.left+borderWidth);
right := (xpos<=rect.right) and (xpos>=rect.right-borderWidth);
top := (ypos>=rect.top) and (ypos<=rect.top+borderWidth);
bottom:= (ypos<=rect.bottom) and (ypos>=rect.bottom-borderWidth);
if left
then result := HTLeft
else if right
then result := HTRight;
if bottom
then
if left
then result := HTBottomLeft
else if right
then result := HTBottomRight
else result := HTBottom
else
if top
then if left
then result := HTTopLeft
else if right
then result := HTTopRight
else result := HTTop;
end; // border > 0
end // WM_NCHitTest
else inherited WndProc(MyMsg);
end;
*)
procedure TSubClassWindow.ReleaseWndProc;
begin
if (FWindow.WndProc=longint(ObjInst)) then
FWindow.WndProc := longint(PreWndproc);
end;
initialization
SubClasssNotify:=RegisterWindowMessage
(SubClasssNotifyName);
end.
|
unit uConexao;
interface
uses
System.SysUtils, System.Classes,Data.Win.ADODB, Data.DB;
type
TConexao = class
private
ADOConnection: TADOConnection;
procedure ConfigurarConexao;
public
{ Public declarations }
constructor Create;
destructor Destroy; override;
function getConexao: TADOConnection;
function CriarQry: TADOQuery;
end;
const
CONECT_FILE : string = 'C:\Projetos\ProjetosDelphi\AppAtend\DAO\conexao.udl';
CONECT_STRING : string = 'FILE NAME=C:\Projetos\ProjetosDelphi\AppAtend\DAO\conexao.udl';
implementation
procedure TConexao.ConfigurarConexao;
begin
ADOConnection.ConnectionString := CONECT_STRING;
ADOConnection.Provider := CONECT_FILE;
ADOConnection.KeepConnection := True;
ADOConnection.LoginPrompt := False;
ADOConnection.Connected := True;
end;
constructor TConexao.Create;
begin
ADOConnection := TADOConnection.Create(nil);
self.ConfigurarConexao();
end;
function TConexao.CriarQry: TADOQuery;
var
VQry : TADOQuery;
begin
VQry := TADOQuery.Create(nil);
VQry.Connection := ADOConnection;
result := VQry;
end;
destructor TConexao.Destroy;
begin
ADOConnection.Free;
inherited;
end;
function TConexao.getConexao: TADOConnection;
begin
result := ADOConnection;
end;
end.
|
unit DataTargetVoucha4;
interface
uses
Customers, Settings, DataSourceIntf, ImportDialogs, Winapi.Windows,
System.StrUtils,
System.SysUtils, System.Classes, ZAbstractConnection, ZConnection, Data.DB,
ZAbstractRODataset, ZAbstractDataset, ZDataset, ZSqlProcessor;
type
TTargetVoucha4 = class(TDataModule, IImportDataTarget)
Connection: TZConnection;
ZQuery: TZQuery;
ZSql: TZSQLProcessor;
procedure ConnectionBeforeConnect(Sender: TObject);
procedure DataModuleCreate(Sender: TObject);
private
{ Private declarations }
Setting: TPostgreSQLSetting;
public
{ Public declarations }
{IImportDataTarget}
function showConnectionSetting(ParentHandle: HWND): Boolean;
procedure Connect;
procedure Disconnnect;
procedure emptyTable;
function addCustomer(var Data:TCustomerRecord):Boolean;
function addMsisdn(Data:TCustomerRecord):Boolean;
function setCustomerBalance(Data: TCustomerRecord):Boolean;
function getCustomerByID(const ID: LongInt;
var Data:TCustomerRecord):Boolean;
function getCustomerByMsisdn(const MSISDN: string;
var Data:TCustomerRecord):Boolean;
function generateUsername(Data: TCustomerRecord):string;
function generateRandomPassword:string;
function generateMetaPath(var Data:TCustomerRecord):Boolean;
function updateMetaPath(Data:TCustomerRecord):Boolean;
end;
var
TargetVoucha4: TTargetVoucha4;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
{ TTargetVoucha4 }
function TTargetVoucha4.addCustomer(var Data: TCustomerRecord): Boolean;
var
Query: TZQuery;
Success: Boolean;
begin
Success:=False;
try
Query:=TZQuery.Create(nil);
Query.Connection:=Connection;
Query.SQL.Text:='INSERT INTO customer ("name", username, "password", ' +
'balance, credit, parentid, parentrebate, metapath, metalevel) VALUES (:name, ' +
':username, md5(:password), :balance, :credit,:parentid, :parentrebate, :metapath, ' +
':metalevel) RETURNING customerid;';
Query.ParamByName('name').AsString:=Data.Name;
Query.ParamByName('username').AsString:=Data.Username;
Query.ParamByName('password').AsString:=Data.PIN;
Query.ParamByName('balance').AsCurrency:=Data.Balance;
Query.ParamByName('credit').AsCurrency:=Data.Credit;
Query.ParamByName('parentid').AsInteger:=Data.ParentID;
Query.ParamByName('parentrebate').AsCurrency:=Data.ParentRebate;
Query.ParamByName('metapath').AsString:=Data.MetaPath;
Query.ParamByName('metalevel').AsInteger:=Data.MetaLevel;
Query.Open;
if Query.RecordCount > 0 then
begin
Data.CustomerID:=Query.FieldByName('customerid').AsInteger;
generateMetaPath(Data);
updateMetaPath(Data);
Success:=True;
end;
Query.Close;
finally
FreeAndNil(Query);
Result:=Success;
end;
end;
function TTargetVoucha4.addMsisdn(Data: TCustomerRecord): Boolean;
var
P:TZSQLProcessor;
Success:Boolean;
MSISDN: string;
begin
Success:=False;
Assert(Data.CustomerID <> 0, 'addMsisdn: Nilai customerid tidak valid!');
MSISDN:=fixMsisdn(Data.MSISDN);
if Trim(MSISDN) = '' then Exit;
try
P:=TZSQLProcessor.Create(nil);
P.Connection:=Connection;
P.Script.Text:='INSERT INTO sender (sendertype, senderid, "password", ' +
'customerid, status, isdefault) VALUES (1, :msisdn, md5(:password), :customerid, 1, 1);';
P.ParamByName('msisdn').AsString:=Data.MSISDN;
P.ParamByName('password').AsString:=Data.PIN;
P.ParamByName('customerid').AsInteger:=Data.CustomerID;
P.Execute;
Success:=True;
finally
FreeAndNil(P);
Result:=Success;
end;
end;
procedure TTargetVoucha4.Connect;
begin
Connection.Connect;
end;
procedure TTargetVoucha4.ConnectionBeforeConnect(Sender: TObject);
begin
Connection.HostName:=Setting.Hostname;
Connection.Database:=Setting.Database;
Connection.User:=Setting.Username;
Connection.Password:=Setting.Password;
Connection.Port:=Setting.Port;
Connection.Protocol:='postgresql';
end;
procedure TTargetVoucha4.DataModuleCreate(Sender: TObject);
begin
SetDefaultPostgreSQLSetting(Setting);
Setting.Database:='voucha4';
Setting.Username:='voucha4';
end;
procedure TTargetVoucha4.Disconnnect;
begin
Connection.Disconnect;
end;
procedure TTargetVoucha4.emptyTable;
var
P:TZSQLProcessor;
begin
try
P:=TZSQLProcessor.Create(nil);
P.Connection:=Connection;
P.Script.Text:='DELETE FROM customer;';
P.Script.Add('DELETE FROM sender;');
P.Script.Add('SELECT setval(''customer_customerid_seq'', 1, false);');
P.Execute;
finally
FreeAndNil(P);
end;
end;
function TTargetVoucha4.generateMetaPath(var Data: TCustomerRecord): Boolean;
var
Parent: TCustomerRecord;
begin
if Data.ParentID = 0 then
begin
Data.MetaPath:=Format('-%d',[Data.CustomerID]);
Data.MetaLevel:=1;
Result:=True;
end
else
begin
if getCustomerByID(Data.ParentID, Parent) then
begin
Data.MetaPath:=Format('%s-%d',[Parent.MetaPath, Data.CustomerID]);
Data.MetaLevel:=Parent.MetaLevel+1;
Result:=True;
end
else Result:=False;
end;
end;
function TTargetVoucha4.generateRandomPassword: string;
begin
Result:=Format('%d',[Random(10000)]);
end;
function TTargetVoucha4.generateUsername(Data: TCustomerRecord): string;
var
Username: string;
begin
Username:=LowerCase(Data.Name);
Username:=StringReplace(Username, ' ', '', [rfReplaceAll]);
Username:=StringReplace(Username, '/', '', [rfReplaceAll]);
Username:=LeftStr(Username, 8)+RightStr(Data.MSISDN, 4);
Result:=Username;
end;
function TTargetVoucha4.getCustomerByID(const ID: Integer;
var Data: TCustomerRecord): Boolean;
var
Exists: Boolean;
Query: TZQuery;
begin
Exists:=False;
InitCustomerRecord(Data);
try
Query:=TZQuery.Create(nil);
Query.Connection:=Connection;
Query.SQL.Text:='SELECT * FROM customer WHERE customerid=:customerid;';
Query.ParamByName('customerid').AsInteger:=ID;
Query.Open;
if Query.RecordCount > 0 then
begin
Exists:=True;
Query.First;
Data.Name:=Query.FieldByName('name').AsString;
Data.Balance:=Query.FieldByName('balance').AsCurrency;
Data.CustomerID:=Query.FieldByName('customerid').AsInteger;
Data.ParentID:=Query.FieldByName('parentid').AsInteger;
Data.ParentRebate:=Query.FieldByName('parentrebate').AsCurrency;
Data.TimeRegister:=Query.FieldByName('dateregistered').AsDateTime;
Data.MetaPath:=Query.FieldByName('metapath').AsString;
Data.MetaLevel:=Query.FieldByName('metalevel').AsInteger;
end;
Query.Close;
finally
FreeAndNil(Query);
Result:=Exists;
end;
end;
function TTargetVoucha4.getCustomerByMsisdn(const MSISDN: string;
var Data: TCustomerRecord): Boolean;
var
CustomerID: Integer;
Query: TZQuery;
begin
CustomerID:=0;
InitCustomerRecord(Data);
try
Query:=TZQuery.Create(nil);
Query.Connection:=Connection;
Query.SQL.Text:='SELECT customerid FROM customermsisdn WHERE msisdn=' +
':msisdn;';
Query.ParamByName('msisdn').AsString:=MSISDN;
Query.Open;
if Query.RecordCount > 0 then
begin
Query.First;
CustomerID:=Query.FieldByName('customerid').AsInteger;
end;
Query.Close;
finally
FreeAndNil(Query);
Data.CustomerID:=CustomerID;
end;
end;
function TTargetVoucha4.setCustomerBalance(Data: TCustomerRecord): Boolean;
begin
end;
function TTargetVoucha4.showConnectionSetting(ParentHandle: HWND): Boolean;
begin
Result:=ImportDialogs.ShowSettingPostgreSQL(ParentHandle, Setting);
end;
function TTargetVoucha4.updateMetaPath(Data: TCustomerRecord): Boolean;
var
P:TZSQLProcessor;
begin
try
P:=TZSQLProcessor.Create(nil);
P.Connection:=Connection;
P.Script.Text:='UPDATE customer SET metapath=:metapath, metalevel=' +
':metalevel WHERE customerid=:customerid;';
P.ParamByName('metapath').AsString:=Data.MetaPath;
P.ParamByName('metalevel').AsInteger:=Data.MetaLevel;
P.ParamByName('customerid').AsInteger:=Data.CustomerID;
P.Execute;
Result:=True;
finally
FreeAndNil(P);
end;
end;
end.
|
unit zAVZDriverBC;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, winsvc, StdCtrls, ntdll, AclAPI, AccCtrl, zSharedFunctions, zAntivirus,
registry;
type
TAVZDriverBC = class
private
FDriverPath, FDriverName: string;
ServiceAPILoaded : boolean;
procedure SetDriverPath(const Value: string);
public
KMBase : TKMBase;
LastStatus : DWORD;
DriverSvcName, DriverLinkName : string;
// Конструктор
constructor Create; virtual;
// Инсталляция драйвера и его настройка
function InstallDriver(AFiles, AKeys, ASvcReg, ASvc, ADisableSvc, AQrFiles, AQrSvc, ACpFiles : TStrings; ALogFile : string) : boolean; virtual;
// Загрузка драйвера
function LoadDriver : boolean; virtual;
// Деинсталляция драйвера
function UnInstallDriver : boolean; virtual;
published
Property DriverPath : string read FDriverPath write SetDriverPath;
end;
TAVZDriverBCKIS = class(TAVZDriverBC)
// Конструктор
constructor Create; override;
// Инсталляция драйвера и его настройка
function InstallDriver(AFiles, AKeys, ASvcReg, ASvc, ADisableSvc, AQrFiles, AQrSvc, ACpFiles : TStrings; ALogFile : string) : boolean; override;
// Загрузка драйвера
function LoadDriver : boolean; override;
// Деинсталляция драйвера
function UnInstallDriver : boolean; override;
end;
implementation
uses zAVKernel, zutil;
{ TAVZDriverN }
constructor TAVZDriverBC.Create;
begin
ServiceAPILoaded := LoadServiceManagerAPI;
// Имя файла
FDriverName := 'AVZBC.sys';
FDriverName := GenerateRandomName(8, 4) + '.sys';
// Имя службы
DriverSvcName := 'AVZBC';
DriverSvcName := GenerateRandomName(8, 4);
end;
function TAVZDriverBC.InstallDriver(AFiles, AKeys, ASvcReg, ASvc, ADisableSvc, AQrFiles, AQrSvc, ACpFiles : TStrings; ALogFile : string): boolean;
var
Reg : TRegistry;
KeyName, Group : String;
i : integer;
begin
if KMBase <> nil then
KMBase.CreateDriverFile('AVZBC', DriverPath+FDriverName, 0, DriverLinkName); //#DNL
LastStatus := zSharedFunctions.InstallDriver(DriverPath+FDriverName,
DriverSvcName, 'AVZ-BC Kernel Driver', 1); //#DNL
Result := LastStatus = STATUS_SUCCESS;
if Result then begin
Group := '';
Reg := TRegistry.Create;
Reg.RootKey := HKEY_LOCAL_MACHINE;
// Определение группы
if Reg.OpenKey('SYSTEM\CurrentControlSet\Control\ServiceGroupOrder', false) then begin
try
SetLength(Group, 4096);
i := Reg.ReadBinaryData('List', Group[1], Length(Group));
SetLength(Group, i);
Delete(Group, 1, pos(#0, Group));
Group := Trim(copy(Group, 1, pos(#0, Group)-1));
except
Group := '';
end;
end;
KeyName := 'SYSTEM\CurrentControlSet\Services\'+DriverSvcName; //#DNL
Reg.CloseKey;
if Reg.OpenKey(KeyName, false) then begin
if Group <> '' then
Reg.WriteString('Group', Group); //#DNL
Reg.WriteInteger('Tag', 1); //#DNL
if Trim(ALogFile) <> '' then
Reg.WriteString('LogFile', '\??\'+Trim(ALogFile)); //#DNL
for i := 0 to AFiles.Count-1 do
Reg.WriteString('DelFile'+IntToStr(i+1), '\??\'+AFiles[i]); //#DNL
for i := 0 to AQrFiles.Count-1 do
Reg.WriteString('QrFile'+IntToStr(i+1), '\??\'+AQrFiles[i]); //#DNL
for i := 0 to ACpFiles.Count-1 do begin
Reg.WriteString('CpFileF'+IntToStr(i+1), '\??\'+copy(ACpFiles[i], 1, pos('||', ACpFiles[i])-1)); //#DNL
Reg.WriteString('CpFileT'+IntToStr(i+1), '\??\'+copy(ACpFiles[i], pos('||', ACpFiles[i])+2, maxint)); //#DNL
end;
for i := 0 to AKeys.Count-1 do
Reg.WriteString('DelRegKey'+IntToStr(i+1), RegKeyToSystemRegKey(AKeys[i])); //#DNL
for i := 0 to ASvcReg.Count-1 do
Reg.WriteString('DelSvcReg'+IntToStr(i+1), ASvcReg[i]); //#DNL
for i := 0 to ASvc.Count-1 do
Reg.WriteString('DelSvc'+IntToStr(i+1), ASvc[i]); //#DNL
for i := 0 to AQrSvc.Count-1 do
Reg.WriteString('QrSvc'+IntToStr(i+1), AQrSvc[i]); //#DNL
for i := 0 to ADisableSvc.Count-1 do
Reg.WriteString('DisableSvc'+IntToStr(i+1), ADisableSvc[i]); //#DNL
// Создание пути для сохранения файлов, внесенных в карантин
if (AQrSvc.Count > 0) or (AQrFiles.Count > 0) then begin
Reg.WriteString('QrPath', '\??\'+GetQuarantineDirName('Quarantine')); //#DNL
zForceDirectories(GetQuarantineDirName('Quarantine')); //#DNL
end;
end;
Reg.CloseKey;
Reg.Free;
end;
end;
function TAVZDriverBC.LoadDriver: boolean;
begin
Result := false;
LastStatus := zSharedFunctions.LoadDriver(DriverSvcName);
Result := (LastStatus = STATUS_SUCCESS) or (LastStatus = STATUS_IMAGE_ALREADY_LOADED);
end;
procedure TAVZDriverBC.SetDriverPath(const Value: string);
begin
FDriverPath := Value;
end;
function TAVZDriverBC.UnInstallDriver: boolean;
begin
LastStatus := zSharedFunctions.UnInstallDriver(DriverSvcName);
DeleteFile(FDriverPath+FDriverName);
Result := LastStatus = STATUS_SUCCESS;
end;
{ TAVZDriverBCKIS }
constructor TAVZDriverBCKIS.Create;
begin
ServiceAPILoaded := LoadServiceManagerAPI;
// Имя файла
FDriverName := 'AVZBC.sys';
// Имя службы
DriverSvcName := 'AVZBC';
end;
function TAVZDriverBCKIS.InstallDriver(AFiles, AKeys, ASvcReg, ASvc,
ADisableSvc, AQrFiles, AQrSvc, ACpFiles: TStrings;
ALogFile: string): boolean;
begin
end;
function TAVZDriverBCKIS.LoadDriver: boolean;
begin
end;
function TAVZDriverBCKIS.UnInstallDriver: boolean;
begin
end;
initialization
finalization
end.
|
unit uMain;
interface
uses
System.Types, SmartCL.System, SmartCL.Components, SmartCL.Application,
SmartCL.Game, SmartCL.GameApp, SmartCL.Graphics, SmartCL.Controls.Button, SmartCL.Touch,
UMakeMaze;
type
TApplication=class(TW3CustomGameApplication)
private
{ Private methods }
FMaze : TMaze;
FMazeOffset : TPoint;
FMazeCellWidth : Integer;
FSolvePos : array [0..1] of TPoint;
FSolveIndex : Integer;
FGenTimeMSec : Float;
protected
{ protected methods }
procedure ApplicationStarting;override;
procedure ApplicationClosing;override;
Procedure PaintView(Canvas:TW3Canvas);override;
procedure ShowMaze ( c : TW3Canvas; maze : TMaze; rows, cols, w, stepWidth, endsWidth, ox, oy : integer );
procedure DoMouseDown(Sender:TObject;Button:TMouseButton; Shift: TShiftState; X,Y:Integer);
end;
Implementation
const mazeSize = 64;
//############################################################################
// TApplication
//############################################################################
procedure TApplication.DoMouseDown(Sender:TObject;Button:TMouseButton; Shift: TShiftState; X,Y:Integer);
var
maze : TMaze;
solLength, visited : Integer;
begin
x:=(x-FMazeOffset.X) div FMazeCellWidth;
y:=(y-FMazeOffset.Y) div FMazeCellWidth;
FSolvePos[FSolveIndex].X:=ClampInt(x, 0, mazeSize-1);
FSolvePos[FSolveIndex].Y:=ClampInt(y, 0, mazeSize-1);
FSolveIndex:=1-FSolveIndex;
maze:=FMaze;
InvalidateMazeSolution(maze, mazeSize, mazeSize);
SolveMaze(maze, mazeSize, mazeSize,
FSolvePos[0].Y, FSolvePos[0].X,
FSolvePos[1].Y, FSolvePos[1].X,
solLength, visited);
FMaze:=maze;
end;
procedure TApplication.ApplicationStarting;
var
maze : TMaze;
Begin
inherited;
//Initialize refresh interval, set this to 1 for optimal speed
GameView.Delay:=20;
FGenTimeMSec:=Now;
MakeMaze(maze, mazeSize, mazeSize);
FGenTimeMSec:=(Now-FGenTimeMSec)*86400*1000;
FMaze:=maze;
GameView.OnMouseDown:= DoMouseDown;
//Start the redraw-cycle with framecounter active
//Note: the framecounter impacts rendering speed. Disable
//the framerate for maximum speed (false)
GameView.StartSession(true);
End;
procedure TApplication.ApplicationClosing;
Begin
GameView.EndSession;
inherited;
End;
// Note: In a real live game you would try to cache as much
// info as you can. Typical tricks are:
// 1: Only get the width/height when resized
// 2: Pre-calculate strings, especially RGB/RGBA values
// 3: Only redraw what has changed, avoid a full repaint
// The code below is just to get you started
procedure TApplication.PaintView(Canvas:TW3Canvas);
var
s, w : Integer;
txt : String;
Begin
// Clear background
canvas.fillstyle:='rgb(0,0,99)';
canvas.fillrectF(0,0,gameview.width,gameview.height);
s:=Min(gameview.width, gameView.Height);
w:=s div (mazeSize+mazeSize shr 1);
FMazeCellWidth:=w;
FMazeOffset.X:=(gameview.width-w*mazeSize) div 2;
FMazeOffset.Y:=(gameview.Height-w*mazeSize) div 2;
ShowMaze(canvas, FMaze, mazeSize, mazeSize,
w, w div 2, 1, FMazeOffset.X, FMazeOffset.Y);
// Draw our framerate on the screen
txt:=Format('Gen: %d ms FPS: %d', [Round(FGenTimeMSec), GameView.FrameRate]);
canvas.font:='20pt verdana';
canvas.FillStyle:='white';
canvas.FillTextF(txt,12,22,MAX_INT);
canvas.FillStyle:='blue';
canvas.FillTextF(txt,10,20,MAX_INT);
End;
procedure TApplication.ShowMaze (c : TW3Canvas; maze : TMaze; rows, cols, w, stepWidth, endsWidth, ox, oy : integer );
var
i,j : integer;
stepOffset : integer;
begin
stepOffset := (w-stepWidth+1) div 2;
// normal color
c.FillStyle:='white';
c.StrokeStyle:='black';
c.FillRectF(ox, oy, (cols)*w, (rows)*w);
c.LineWidth:=1;
// backgrounds for solution and start/end cells
for i := 0 to cols-1 do
for j := 0 to rows-1 do
begin
// if this is a solution cell
if (maze[j,i] and CELL_VISITED = CELL_VISITED) then
begin
c.FillStyle:='#E0E0E0';
c.FillRectF(ox + i*w + stepOffset, oy + j*w + stepOffset,
stepWidth, stepWidth);
end;
if maze[j,i] and CELL_SOLUTION = CELL_SOLUTION then
begin
c.FillStyle:='#8080FF';
c.FillRectF(ox + i*w + stepOffset, oy + j*w + stepOffset,
stepWidth, stepWidth);
end;
// paint Start and End Cell
if (j = FSolvePos[0].Y) and (i = FSolvePos[0].X) then
begin
c.FillStyle:='#FF8000';
c.FillRectF(ox + i*w , oy + j*w ,
w, w);
end;
if (j = FSolvePos[1].Y) and (i = FSolvePos[1].X) then
begin
c.FillStyle:='#8080FF';
c.FillRectF(ox + i*w , oy + j*w ,
w, w);
end;
end;
// lines
c.BeginPath;
for i := 0 to cols-1 do
for j := 0 to rows-1 do
begin
if maze[j,i] and EXIT_EAST = $00 then // if there is NO exit EAST
begin
c.LineF (ox + (i+1)*w, oy + j*w,
ox + (i+1)*w, oy + (j+1)*w + 1);
end;
if maze[j,i] and EXIT_NORTH = $00 then // if there is NO exit NORTH
begin
c.LineF (ox + i*w, oy + j*w,
ox + (i+1)*w + 1, oy + j*w);
end;
if maze[j,i] and EXIT_WEST = $00 then // if there is NO exit WEST
begin
c.LineF (ox + i*w, oy + j*w,
ox + i*w, oy + (j+1)*w + 1);
end;
if maze[j,i] and EXIT_SOUTH = $00 then // if there is NO exit SOUTH
begin
c.LineF (ox + i*w, oy + (j+1)*w,
ox + (i+1)*w + 1, oy + (j+1)*w);
end;
end;
c.Stroke;
end;
end.
|
unit frm_main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Webdriver4D,
System.Actions, Vcl.ActnList, Vcl.ComCtrls, System.IniFiles, WD_httpDelphi;
type
TForm1 = class(TForm)
rgWebDriver: TRadioGroup;
memLog: TMemo;
Label1: TLabel;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
txtGetURL: TEdit;
Label2: TLabel;
Button1: TButton;
ActionList1: TActionList;
actCmdGetURL: TAction;
Label3: TLabel;
txtWebDriverPath: TEdit;
Action1: TAction;
actStartWebDriver: TAction;
Button2: TButton;
Label4: TLabel;
txtSession: TEdit;
txtFindName: TEdit;
actFindElementByTag: TAction;
Button3: TButton;
txtPropName: TEdit;
actSwitchFrame: TAction;
actGetPropValue: TAction;
Button4: TButton;
actClickCurrentElement: TAction;
Button5: TButton;
procedure actClickCurrentElementExecute(Sender: TObject);
procedure actCmdGetURLExecute(Sender: TObject);
procedure actFindElementByTagExecute(Sender: TObject);
procedure actGetPropValueExecute(Sender: TObject);
procedure actStartWebDriverExecute(Sender: TObject);
procedure actSwitchFrameExecute(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
function CreateWebDriver: TWebDriver;
procedure FormShow(Sender: TObject);
procedure txtFindNameChange(Sender: TObject);
procedure txtGetURLChange(Sender: TObject);
procedure txtWebDriverPathChange(Sender: TObject);
private
FCMD: TDelphiCommand;
FcurElement: TWebElement;
FIni: TIniFile;
FWD: TWebDriver;
function GetAppPath: string;
function GetElementXPath: string;
function GetPropName: string;
function GetURL: string;
function GetWebdriverPath: string;
procedure SetElementXPath(const Value: string);
procedure SetPropName(const Value: string);
procedure SetURL(const Value: string);
procedure SetWebdriverPath(const Value: string);
property ElementXPath: string read GetElementXPath write SetElementXPath;
property PropName: string read GetPropName write SetPropName;
property URL: string read GetURL write SetURL;
{ Private declarations }
public
property AppPath: string read GetAppPath;
property WebdriverPath: string read GetWebdriverPath write SetWebdriverPath;
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses
System.WideStrUtils, System.StrUtils;
{$R *.dfm}
procedure TForm1.actClickCurrentElementExecute(Sender: TObject);
begin
if not FcurElement.IsEmpty then
begin
FcurElement.Click;
end;
end;
procedure TForm1.actCmdGetURLExecute(Sender: TObject);
begin
FWD.GetURL(txtGetURL.Text);
end;
procedure TForm1.actFindElementByTagExecute(Sender: TObject);
begin
FcurElement := FWd.FindElementByXPath(txtFindName.Text);
memLog.Lines.Add(FcurElement.Text);
end;
procedure TForm1.actGetPropValueExecute(Sender: TObject);
var
Element:TWebElement;
begin
Element :=FcurElement;
memLog.Lines.Add(FcurElement.PropertyValue(txtPropName.Text));
end;
procedure TForm1.actStartWebDriverExecute(Sender: TObject);
begin
FWD :=CreateWebDriver;
end;
procedure TForm1.actSwitchFrameExecute(Sender: TObject);
begin
FWD.SwitchToFrame(txtFindName.Text);
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
if Assigned(FWD) then FreeAndNil(FWD);
FreeAndNil(FCMD);
FreeAndNil(FIni);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
FIni :=TIniFile.Create(AppPath+'Set.ini');
FCMD :=TDelphiCommand.Create(self);
WebdriverPath :=FIni.ReadString('Path','webdriverpath',AppPath+'webdriver\');
txtGetURL.Text :=FIni.ReadString('Value','URL','')
end;
function TForm1.CreateWebDriver: TWebDriver;
var
WD:TWebDriver;
IE:TIEDriver absolute WD;
FFox:TFireFoxDriver absolute WD;
Chrome:TChromeDriver absolute WD;
Edge:TEdgeDriver absolute WD;
Phantomjs:TPhantomjs absolute WD;
begin
if Assigned(FWD) then FreeAndNil(FWD);
case rgWebDriver.ItemIndex of
0: //IE
begin
IE :=TIEDriver.Create(nil);
IE.StartDriver(WebdriverPath+'IEDriverServer_X86.exe');
IE.Cmd :=FCMD;
txtSession.Text :=IE.NewSession;
result :=IE;
end;
1: //FireFox
begin
FFox := TFireFoxDriver.Create(nil);
FFox.BrowserFileName :='C:\Program Files\Mozilla Firefox\firefox.exe';
FFox.newVersion :=true;
FFox.StartDriver(WebdriverPath+'geckodriver_x64.exe');
FFox.Cmd :=FCMD;
txtSession.Text :=FFox.NewSession;
result :=FFox;
end;
2: //chrome
begin
Chrome :=TChromeDriver.Create(nil);
Chrome.StartDriver(WebdriverPath+'chromedriver.exe');
txtSession.Text :=Chrome.NewSession;
result :=Chrome;
end;
3: //Edge
begin
Edge :=TEdgeDriver.Create(nil);
Edge.StartDriver(WebdriverPath+'MicrosoftWebDriver.exe');
Edge.Cmd :=FCMD;
txtSession.Text :=Edge.NewSession;
result :=Edge;
end;
4: //Phantomjs
begin
Phantomjs :=TPhantomjs.Create(nil);
Phantomjs.StartDriver(WebdriverPath+'Phantomjs.exe');
Phantomjs.Cmd :=FCMD;
txtSession.Text :=Phantomjs.NewSession;
result :=Phantomjs;
end;
end;
end;
procedure TForm1.FormShow(Sender: TObject);
begin
txtWebDriverPath.Text :=WebdriverPath;
txtFindName.Text :=ElementXPath;
txtGetURL.Text :=URL;
txtPropName.Text :=PropName;
end;
function TForm1.GetAppPath: string;
begin
// TODO -cMM: TForm1.GetAppPath default body inserted
Result :=ExtractFilePath(Application.ExeName) ;
end;
function TForm1.GetElementXPath: string;
begin
// TODO -cMM: TForm1.GetElementXPath default body inserted
Result :=FIni.ReadString('Value','ElementXPath','') ;
end;
function TForm1.GetPropName: string;
begin
Result :=FIni.ReadString('Value','PropName','') ;
end;
function TForm1.GetURL: string;
begin
Result :=FIni.ReadString('Value','URL','');
end;
function TForm1.GetWebdriverPath: string;
begin
if RightStr(txtWebDriverPath.Text,1)<>'\' then
Result :=txtWebDriverPath.Text+'\'
else
Result :=txtWebDriverPath.Text;
end;
procedure TForm1.SetElementXPath(const Value: string);
begin
FIni.WriteString('Value','ElementXPath',Value);
end;
procedure TForm1.SetPropName(const Value: string);
begin
FIni.WriteString('Value','PropName',Value)
end;
procedure TForm1.SetURL(const Value: string);
begin
FIni.WriteString('Value','URL',Value);
end;
procedure TForm1.SetWebdriverPath(const Value: string);
begin
txtWebDriverPath.Text :=Value;
end;
procedure TForm1.txtFindNameChange(Sender: TObject);
begin
ElementXPath :=txtFindName.Text;
end;
procedure TForm1.txtGetURLChange(Sender: TObject);
begin
FIni.WriteString('Value','URL',txtGetURL.Text);
end;
procedure TForm1.txtWebDriverPathChange(Sender: TObject);
begin
FIni.WriteString('Path','webdriverpath',WebdriverPath);
end;
end.
|
//
// Made from firebase-messaging 10.2.0
//
unit Alcinoe.iOSApi.FirebaseMessaging;
interface
{$I Alcinoe.inc}
{$IFNDEF ALCompilerVersionSupported}
//Pleast update <Alcinoe>\Libraries\ios\firebase\ to the last one and then run
//<Alcinoe>\Tools\NativeBridgeFileGenerator\NativeBridgeFileGeneratorIOS.bat
//and gave the path to <Alcinoe>\Source\Alcinoe.iOSApi.FirebaseMessaging.pas to build
//the compare source file. Then make a diff compare between the new generated
//Alcinoe.iOSApi.FirebaseMessaging.pas and this one to see if the api signature is
//still the same
{$MESSAGE WARN 'Check if the api signature of the last version of Firebase Messaging (ios) is still the same'}
{$ENDIF}
uses
Macapi.ObjectiveC,
iOSapi.CocoaTypes,
iOSapi.Foundation;
{$M+}
type
{***********************}
FIRMessaging = interface;
{******************************************************************************************************************}
//https://firebase.google.com/docs/reference/ios/firebasemessaging/api/reference/Protocols/FIRMessagingDelegate.html
FIRMessagingDelegate = interface(IObjectiveC)
['{9784786A-515F-41F0-84C3-8F298623275E}']
procedure messaging(messaging: FIRMessaging; fcmToken: NSString); cdecl;
end;
{*********************************************************************************************}
TFIRMessagingTokenWithCompletionHandler = procedure(token: NSString; error: NSError) of object;
TFIRMessagingDeleteTokenWithCompletionHandler = procedure(error: NSError) of object;
{***************************************************************************************************}
//https://firebase.google.com/docs/reference/ios/firebasemessaging/api/reference/Classes/FIRMessaging
FIRMessagingClass = interface(NSObjectClass)
['{FC9DDBCE-4C91-4DE4-B2FC-80289562D9F5}']
{class} function messaging : Pointer{instancetype}; cdecl;
end;
FIRMessaging = interface(NSObject)
['{FCF96F2C-513B-409C-87D7-3FFE504EA79D}']
procedure setDelegate(delegate: FIRMessagingDelegate); cdecl;
function delegate : FIRMessagingDelegate; cdecl;
procedure tokenWithCompletion(completion: TFIRMessagingTokenWithCompletionHandler); cdecl;
procedure deleteTokenWithCompletion(completion: TFIRMessagingDeleteTokenWithCompletionHandler); cdecl;
end;
TFIRMessaging = class(TOCGenericImport<FIRMessagingClass, FIRMessaging>) end;
implementation
uses
Alcinoe.iOSApi.FirebaseCore; // [MANDATORY] Because we need it's initialization/finalization section
{*******************************************************************************}
procedure FirebaseMessagingLoader; cdecl; external framework 'FirebaseMessaging';
end.
|
{
ID:because3
PROG:transform
LANG:PASCAL
}
type date=array[1..10,1..10] of char;
var x,y,xx,yy,s:date;
a,n,i,j:integer;
finish:boolean;
procedure init;
var i,j:integer;
begin
readln(n);
for i:=1 to n do begin
for j:=1 to n do
read(x[i,j]);
readln;
end;
for i:=1 to n do begin
for j:=1 to n do
read(s[i,j]);
readln;
end;
end;
function xd(a,b:date):boolean;
var i,j:integer;
begin
for i:=1 to n do
for j:=1 to n do
if a[i,j]<>b[i,j] then
exit(false);
exit(true);
end;
procedure d1;
var j,k:integer;
begin
for j:=1 to n do
for k:=1 to n do
xx[k,n-j+1]:=x[j,k];
end;
procedure d2;
var j,k:integer;
begin
for j:=1 to n do
for k:=1 to n do
xx[n-j+1,n-k+1]:=x[j,k];
end;
procedure d3;
var j,k:integer;
begin
for j:=1 to n do
for k:=1 to n do
xx[n-k+1,j]:=x[j,k];
end;
procedure d4;
var j,k:integer;
begin
for j:=1 to n do
for k:=1 to n do
xx[j,n-k+1]:=x[j,k];
end;
BEGIN
assign(input,'transform.in');
reset(input);
assign(output,'transform.out');
rewrite(output);
init;
close(input);
a:=0;
i:=1;
finish:=true;
while (i<=6) and finish do begin
case i of
1:begin d1;if xd(xx,s) then begin finish:=false;a:=1; end;end;
2:begin d2;if xd(xx,s) then begin finish:=false;a:=2; end;end;
3:begin d3;if xd(xx,s) then begin finish:=false;a:=3; end;end;
4:begin d4;if xd(xx,s) then begin finish:=false;a:=4; end;end;
5:begin d4;y:=x;yy:=xx;x:=xx; for j:=1 to 3 do
case j of
1:begin d1;if xd(xx,s) then begin finish:=false;a:=5; end else x:=yy;end;
2:begin d2;if xd(xx,s) then begin finish:=false;a:=5; end else x:=yy;end;
3:begin d3;if xd(xx,s) then begin finish:=false;a:=5; end else x:=y;end;
end;
end;
6:if xd(x,s) then a:=6;
end;
inc(i);
end;
if a=0 then writeln(7) else writeln(a);
close(output);
END.
|
unit ArticleInMemoryRepository;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, ArticleRepository, ArticleModel;
type
{ TArticleInMemoryRepository }
TArticleInMemoryRepository = class(TInterfacedObject, IArticleRepository)
private
Storage: TArticles;
function InStringArray(Element: string; StringsArray: array of string): boolean;
public
constructor Create;
destructor Destroy; override;
procedure Add(Article: TArticle);
function Build(Title, Description, Body: string;
const Tags: array of string): TArticle;
function GetAll: TArticles;
function GetAllTags: TTags;
function GetByAuthorSlug(Slug: string): TArticles;
function GetByTag(Tag: string): TArticles;
end;
implementation
function TArticleInMemoryRepository.InStringArray(Element: string;
StringsArray: array of string): boolean;
var
I: integer;
begin
for I := Low(StringsArray) to High(StringsArray) do
begin
Result := False;
if StringsArray[I] = Element then
begin
Result := True;
Exit;
end;
end;
end;
constructor TArticleInMemoryRepository.Create;
begin
inherited Create;
end;
destructor TArticleInMemoryRepository.Destroy;
begin
inherited Destroy;
end;
procedure TArticleInMemoryRepository.Add(Article: TArticle);
begin
SetLength(Storage, Length(Storage) + 1);
Storage[High(Storage)] := Article;
end;
function TArticleInMemoryRepository.Build(Title, Description, Body: string;
const Tags: array of string): TArticle;
var
I: integer;
begin
Result.Title := Title;
Result.Description := Description;
Result.Body := Body;
SetLength(Result.Tags, Length(Tags));
for I := Low(Tags) to High(Tags) do
Result.Tags[I] := Tags[I];
end;
function TArticleInMemoryRepository.GetAll: TArticles;
begin
Result := Storage;
end;
function TArticleInMemoryRepository.GetAllTags: TTags;
var
I, J: integer;
begin
SetLength(Result, 0);
for I := Low(Storage) to High(Storage) do
begin
for J := Low(Storage[I].Tags) to High(Storage[I].Tags) do
begin
if not InStringArray(Storage[I].Tags[J], Result) then
begin
SetLength(Result, Length(Result) + 1);
Result[High(Result)] := Storage[I].Tags[J];
end;
end;
end;
end;
function TArticleInMemoryRepository.GetByAuthorSlug(Slug: string): TArticles;
var
I: integer;
Article: TArticle;
begin
SetLength(Result, 0);
for I := Low(Storage) to High(Storage) do
begin
Article := Storage[I];
if Article.Author.Slug <> Slug then
Continue;
SetLength(Result, Length(Result) + 1);
Result[High(Result)] := Article;
end;
end;
function TArticleInMemoryRepository.GetByTag(Tag: string): TArticles;
var
I: integer;
Article: TArticle;
begin
SetLength(Result, 0);
for I := Low(Storage) to High(Storage) do
begin
Article := Storage[I];
if InStringArray(Tag, Article.Tags) then
begin
SetLength(Result, Length(Result) + 1);
Result[High(Result)] := Article;
end;
end;
end;
end.
|
unit DIOTA.Dto.Response.GetTipsResponse;
interface
uses
DIOTA.IotaAPIClasses;
type
TGetTipsResponse = class(TIotaAPIResponse)
private
FHashes: TArray<String>;
function GetHashes(Index: Integer): String;
function GetHashesCount: Integer;
public
constructor Create(AHashes: TArray<String>); reintroduce; virtual;
property HashesCount: Integer read GetHashesCount;
property Hashes[Index: Integer]: String read GetHashes;
end;
implementation
{ TGetTipsResponse }
constructor TGetTipsResponse.Create(AHashes: TArray<String>);
begin
inherited Create;
FHashes := AHashes;
end;
function TGetTipsResponse.GetHashes(Index: Integer): String;
begin
Result := FHashes[Index];
end;
function TGetTipsResponse.GetHashesCount: Integer;
begin
Result := Length(FHashes);
end;
end.
|
unit DIOTA.Model.Transfer;
interface
type
ITransfer = interface
['{1E8AE714-FEE1-4A68-8DDD-854B7E7B53E8}']
function GetAddress: String;
function GetValue: Int64;
function GetMessage: String;
function GetTag: String;
procedure SetAddress(AAddress: String);
property Address: String read GetAddress write SetAddress;
property Value: Int64 read GetValue;
property Message: String read GetMessage;
property Tag: String read GetTag;
end;
TTransferBuilder = class
private
FAddress: String;
FValue: Int64;
FMessage: String;
FTag: String;
public
{
* Initializes a new instance of the Transfer class.
*
* @param timestamp
* @param address, must contain checksums
* @param hash
* @param persistence
* @param value
* @param message
* @param tag
}
class function CreateTransfer(AAddress: String; AValue: Int64; AMessage: String; ATag: String): ITransfer;
function SetAddress(AAddress: String): TTransferBuilder;
function SetValue(AValue: Int64): TTransferBuilder;
function SetMessage(AMessage: String): TTransferBuilder;
function SetTag(ATag: String): TTransferBuilder;
function Build: ITransfer;
end;
implementation
type
TTransfer = class(TInterfacedObject, ITransfer)
private
FAddress: String;
FValue: Int64;
FMessage: String;
FTag: String;
function GetAddress: String;
function GetValue: Int64;
function GetMessage: String;
function GetTag: String;
procedure SetAddress(AAddress: String);
public
constructor Create(AAddress: String; AValue: Int64; AMessage: String; ATag: String);
end;
{ TTransferBuilder }
class function TTransferBuilder.CreateTransfer(AAddress: String; AValue: Int64; AMessage: String; ATag: String): ITransfer;
begin
Result := TTransfer.Create(AAddress, AValue, AMessage, ATag);
end;
function TTransferBuilder.Build: ITransfer;
begin
Result := TTransfer.Create(FAddress, FValue, FMessage, FTag);
end;
function TTransferBuilder.SetAddress(AAddress: String): TTransferBuilder;
begin
FAddress := AAddress;
Result := Self;
end;
function TTransferBuilder.SetMessage(AMessage: String): TTransferBuilder;
begin
FMessage := AMessage;
Result := Self;
end;
function TTransferBuilder.SetTag(ATag: String): TTransferBuilder;
begin
FTag := ATag;
Result := Self;
end;
function TTransferBuilder.SetValue(AValue: Int64): TTransferBuilder;
begin
FValue := AValue;
Result := Self;
end;
{ TTransfer }
constructor TTransfer.Create(AAddress: String; AValue: Int64; AMessage: String; ATag: String);
begin
FAddress := AAddress;
FValue := AValue;
FMessage := AMessage;
FTag := ATag;
end;
function TTransfer.GetAddress: String;
begin
Result := FAddress;
end;
function TTransfer.GetMessage: String;
begin
Result := FMessage;
end;
function TTransfer.GetTag: String;
begin
Result := FTag;
end;
function TTransfer.GetValue: Int64;
begin
Result := FValue;
end;
procedure TTransfer.SetAddress(AAddress: String);
begin
FAddress := AAddress;
end;
end.
|
unit Aspect4D.UnitTest.Logging;
interface
uses
Aspect4D,
System.Rtti,
System.SysUtils,
System.Classes;
type
ELoggingException = class(Exception);
LoggingAttribute = class(AspectAttribute);
TLoggingAspect = class(TAspect, IAspect)
private
{ private declarations }
protected
function GetName: string;
procedure DoBefore(instance: TObject; method: TRttiMethod;
const args: TArray<TValue>; out invoke: Boolean; out result: TValue);
procedure DoAfter(instance: TObject; method: TRttiMethod;
const args: TArray<TValue>; var result: TValue);
procedure DoException(instance: TObject; method: TRttiMethod;
const args: TArray<TValue>; out raiseException: Boolean;
theException: Exception; out result: TValue);
public
{ public declarations }
end;
function GlobalLoggingList: TStringList;
implementation
var
_LoggingList: TStringList;
function GlobalLoggingList: TStringList;
begin
Result := _LoggingList;
end;
{ TLoggingAspect }
procedure TLoggingAspect.DoAfter(instance: TObject; method: TRttiMethod; const args: TArray<TValue>; var result: TValue);
var
att: TCustomAttribute;
begin
for att in method.GetAttributes do
if att is LoggingAttribute then
GlobalLoggingList.Add('After ' + instance.QualifiedClassName + ' - ' + method.Name);
end;
procedure TLoggingAspect.DoBefore(instance: TObject; method: TRttiMethod; const args: TArray<TValue>; out invoke: Boolean;
out result: TValue);
var
att: TCustomAttribute;
begin
for att in method.GetAttributes do
if att is LoggingAttribute then
GlobalLoggingList.Add('Before ' + instance.QualifiedClassName + ' - ' + method.Name);
end;
procedure TLoggingAspect.DoException(instance: TObject; method: TRttiMethod; const args: TArray<TValue>; out raiseException: Boolean;
theException: Exception; out result: TValue);
var
att: TCustomAttribute;
begin
for att in method.GetAttributes do
if att is LoggingAttribute then
GlobalLoggingList.Add('Exception ' + instance.QualifiedClassName + ' - ' + method.Name + ' - ' + theException.Message);
end;
function TLoggingAspect.GetName: string;
begin
Result := Self.QualifiedClassName;
end;
initialization
_LoggingList := TStringList.Create;
finalization
_LoggingList.Free;
end.
|
unit uBase64;
{$ZEROBASEDSTRINGS ON}
interface
uses
System.SysUtils,
uBase,
uUtils;
type
IBase64 = interface
['{E57BB251-9048-4287-9782-F22B12602B12}']
function Encode(data: TArray<Byte>): String;
function Decode(const data: String): TArray<Byte>;
function EncodeString(const data: String): String;
function DecodeToString(const data: String): String;
function GetBitsPerChars: Double;
property BitsPerChars: Double read GetBitsPerChars;
function GetCharsCount: UInt32;
property CharsCount: UInt32 read GetCharsCount;
function GetBlockBitsCount: Integer;
property BlockBitsCount: Integer read GetBlockBitsCount;
function GetBlockCharsCount: Integer;
property BlockCharsCount: Integer read GetBlockCharsCount;
function GetAlphabet: String;
property Alphabet: String read GetAlphabet;
function GetSpecial: Char;
property Special: Char read GetSpecial;
function GetHaveSpecial: Boolean;
property HaveSpecial: Boolean read GetHaveSpecial;
function GetEncoding: TEncoding;
procedure SetEncoding(value: TEncoding);
property Encoding: TEncoding read GetEncoding write SetEncoding;
end;
TBase64 = class(TBase, IBase64)
public
const
DefaultAlphabet =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
DefaultSpecial = '=';
constructor Create(const _Alphabet: String = DefaultAlphabet;
_Special: Char = DefaultSpecial; _textEncoding: TEncoding = Nil);
function Encode(data: TArray<Byte>): String; override;
function Decode(const data: String): TArray<Byte>; override;
strict private
procedure EncodeBlock(src: TArray<Byte>; dst: TArray<Char>;
beginInd, endInd: Integer);
procedure DecodeBlock(const src: String; dst: TArray<Byte>;
beginInd, endInd: Integer);
end;
implementation
constructor TBase64.Create(const _Alphabet: String = DefaultAlphabet;
_Special: Char = DefaultSpecial; _textEncoding: TEncoding = Nil);
begin
Inherited Create(64, _Alphabet, _Special, _textEncoding);
FHaveSpecial := True;
end;
function TBase64.Encode(data: TArray<Byte>): String;
var
resultLength, dataLength, tempInt, length3, ind, x1, x2, srcInd,
dstInd: Integer;
tempResult: TArray<Char>;
begin
if ((data = Nil) or (Length(data) = 0)) then
begin
Exit('');
end;
dataLength := Length(data);
resultLength := (dataLength + 2) div 3 * 4;
SetLength(tempResult, resultLength);
length3 := Length(data) div 3;
EncodeBlock(data, tempResult, 0, length3);
tempInt := (dataLength - length3 * 3);
case tempInt of
1:
begin
ind := length3;
srcInd := ind * 3;
dstInd := ind * 4;
x1 := data[srcInd];
tempResult[dstInd] := Alphabet[x1 shr 2];
tempResult[dstInd + 1] := Alphabet[(x1 shl 4) and $30];
tempResult[dstInd + 2] := Special;
tempResult[dstInd + 3] := Special;
end;
2:
begin
ind := length3;
srcInd := ind * 3;
dstInd := ind * 4;
x1 := data[srcInd];
x2 := data[srcInd + 1];
tempResult[dstInd] := Alphabet[x1 shr 2];
tempResult[dstInd + 1] := Alphabet[((x1 shl 4) and $30) or (x2 shr 4)];
tempResult[dstInd + 2] := Alphabet[(x2 shl 2) and $3C];
tempResult[dstInd + 3] := Special;
end;
end;
result := TUtils.ArraytoString(tempResult);
end;
procedure TBase64.EncodeBlock(src: TArray<Byte>; dst: TArray<Char>;
beginInd, endInd: Integer);
var
ind, srcInd, dstInd: Integer;
x1, x2, x3: Byte;
begin
for ind := beginInd to Pred(endInd) do
begin
srcInd := ind * 3;
dstInd := ind * 4;
x1 := src[srcInd];
x2 := src[srcInd + 1];
x3 := src[srcInd + 2];
dst[dstInd] := Alphabet[x1 shr 2];
dst[dstInd + 1] := Alphabet[((x1 shl 4) and $30) or (x2 shr 4)];
dst[dstInd + 2] := Alphabet[((x2 shl 2) and $3C) or (x3 shr 6)];
dst[dstInd + 3] := Alphabet[x3 and $3F];
end;
end;
function TBase64.Decode(const data: String): TArray<Byte>;
var
lastSpecialInd, tailLength, resultLength, length4, ind, x1, x2, x3, srcInd,
dstInd: Integer;
tempResult: TArray<Byte>;
begin
if TUtils.isNullOrEmpty(data) then
begin
SetLength(result, 1);
result := Nil;
Exit;
end;
lastSpecialInd := Length(data);
while (data[lastSpecialInd - 1] = Special) do
begin
dec(lastSpecialInd);
end;
tailLength := Length(data) - lastSpecialInd;
resultLength := (Length(data) + 3) div 4 * 3 - tailLength;
SetLength(tempResult, resultLength);
length4 := (Length(data) - tailLength) div 4;
DecodeBlock(data, tempResult, 0, length4);
Case tailLength of
2:
begin
ind := length4;
srcInd := ind * 4;
dstInd := ind * 3;
x1 := FInvAlphabet[Ord(data[srcInd])];
x2 := FInvAlphabet[Ord(data[srcInd + 1])];
tempResult[dstInd] := Byte((x1 shl 2) or ((x2 shr 4) and $3));
end;
1:
begin
ind := length4;
srcInd := ind * 4;
dstInd := ind * 3;
x1 := FInvAlphabet[Ord(data[srcInd])];
x2 := FInvAlphabet[Ord(data[srcInd + 1])];
x3 := FInvAlphabet[Ord(data[srcInd + 2])];
tempResult[dstInd] := Byte((x1 shl 2) or ((x2 shr 4) and $3));
tempResult[dstInd + 1] := Byte((x2 shl 4) or ((x3 shr 2) and $F));
end;
end;
result := tempResult;
end;
{$OVERFLOWCHECKS OFF}
procedure TBase64.DecodeBlock(const src: String; dst: TArray<Byte>;
beginInd, endInd: Integer);
var
ind, srcInd, dstInd, x1, x2, x3, x4: Integer;
begin
for ind := beginInd to Pred(endInd) do
begin
srcInd := ind * 4;
dstInd := ind * 3;
x1 := FInvAlphabet[Ord(src[srcInd])];
x2 := FInvAlphabet[Ord(src[srcInd + 1])];
x3 := FInvAlphabet[Ord(src[srcInd + 2])];
x4 := FInvAlphabet[Ord(src[srcInd + 3])];
dst[dstInd] := Byte((x1 shl 2) or ((x2 shr 4) and $3));
dst[dstInd + 1] := Byte((x2 shl 4) or ((x3 shr 2) and $F));
dst[dstInd + 2] := Byte((x3 shl 6) or (x4 and $3F));
end;
end;
end.
|
unit Alcinoe.Files;
interface
{$I Alcinoe.inc}
uses
Alcinoe.Common;
Function AlEmptyDirectoryA(
Directory: ansiString;
SubDirectory: Boolean;
const IgnoreFiles: Array of AnsiString;
Const RemoveEmptySubDirectory: Boolean = True;
Const FileNameMask: ansiString = '*';
Const MinFileAge: TdateTime = ALNullDate): Boolean; overload;
Function AlEmptyDirectoryW(
Directory: String;
SubDirectory: Boolean;
const IgnoreFiles: Array of String;
Const RemoveEmptySubDirectory: Boolean = True;
Const FileNameMask: String = '*';
Const MinFileAge: TdateTime = ALNullDate): Boolean; overload;
Function AlEmptyDirectoryA(
const Directory: ansiString;
SubDirectory: Boolean;
Const RemoveEmptySubDirectory: Boolean = True;
Const FileNameMask: ansiString = '*';
Const MinFileAge: TdateTime = ALNullDate): Boolean; overload;
Function AlEmptyDirectoryW(
const Directory: String;
SubDirectory: Boolean;
Const RemoveEmptySubDirectory: Boolean = True;
Const FileNameMask: String = '*';
Const MinFileAge: TdateTime = ALNullDate): Boolean; overload;
{$IF defined(MSWINDOWS)}
Function AlCopyDirectoryA(
SrcDirectory,
DestDirectory: ansiString;
SubDirectory: Boolean;
Const FileNameMask: ansiString = '*';
Const FailIfExists: Boolean = True;
Const SkipIfExists: Boolean = False): Boolean;
Function AlCopyDirectoryW(
SrcDirectory,
DestDirectory: String;
SubDirectory: Boolean;
Const FileNameMask: String = '*';
Const FailIfExists: Boolean = True;
Const SkipIfExists: Boolean = False): Boolean;
function ALGetModuleFileNameA(const AWithoutExtension: boolean = True): ansistring;
function ALGetModuleFileNameW(const AWithoutExtension: boolean = True): String;
function ALGetModuleNameA: ansistring;
function ALGetModuleNameW: String;
function ALGetModulePathA: ansiString;
function ALGetModulePathW: String;
Function AlGetFileSize(const AFileName: ansistring): int64; overload; deprecated 'Use Tfile.GetSize Instead';
function ALGetFileSize(const FileName : string): Int64; overload; deprecated 'Use Tfile.GetSize Instead';
Function AlGetFileVersion(const AFileName: ansistring): ansiString;
function ALGetFileCreationDateTime(const aFileName: Ansistring): TDateTime; overload; deprecated 'Use Tfile.GetCreationTime/Tfile.GetCreationTimeUtc Instead';
function ALGetFileCreationDateTime(const aFileName: String): TDateTime; overload; deprecated 'Use Tfile.GetCreationTime/Tfile.GetCreationTimeUtc Instead';
function ALGetFileLastWriteDateTime(const aFileName: Ansistring): TDateTime; overload; deprecated 'Use Tfile.GetLastWriteTime/Tfile.GetLastWriteTimeUtc Instead';
function ALGetFileLastWriteDateTime(const aFileName: String): TDateTime; overload; deprecated 'Use Tfile.GetLastWriteTime/Tfile.GetLastWriteTimeUtc Instead';
function ALGetFileLastAccessDateTime(const aFileName: Ansistring): TDateTime; overload; deprecated 'Use Tfile.GetLastAccessTime/Tfile.GetLastAccessTimeUtc Instead';
function ALGetFileLastAccessDateTime(const aFileName: String): TDateTime; overload; deprecated 'Use Tfile.GetLastAccessTime/Tfile.GetLastAccessTimeUtc Instead';
Procedure ALSetFileCreationDateTime(Const aFileName: Ansistring; Const aCreationDateTime: TDateTime); overload; deprecated 'Use Tfile.SetCreationTime/Tfile.SetCreationTimeUtc Instead';
Procedure ALSetFileCreationDateTime(Const aFileName: String; Const aCreationDateTime: TDateTime); overload; deprecated 'Use Tfile.SetCreationTime/Tfile.SetCreationTimeUtc Instead';
Procedure ALSetFileLastWriteDateTime(Const aFileName: Ansistring; Const aLastWriteDateTime: TDateTime); overload; deprecated 'Use Tfile.SetLastWriteTime/Tfile.SetLastWriteTimeUtc Instead';
Procedure ALSetFileLastWriteDateTime(Const aFileName: String; Const aLastWriteDateTime: TDateTime); overload; deprecated 'Use Tfile.SetLastWriteTime/Tfile.SetLastWriteTimeUtc Instead';
Procedure ALSetFileLastAccessDateTime(Const aFileName: Ansistring; Const aLastAccessDateTime: TDateTime); overload; deprecated 'Use Tfile.LastAccessTime/Tfile.LastAccessTimeUtc Instead';
Procedure ALSetFileLastAccessDateTime(Const aFileName: String; Const aLastAccessDateTime: TDateTime); overload; deprecated 'Use Tfile.LastAccessTime/Tfile.LastAccessTimeUtc Instead';
function ALIsDirectoryEmpty(const directory: ansiString): boolean; overload; deprecated 'Use Tdirectory.IsEmpty Instead';
function ALIsDirectoryEmpty(const directory: String): boolean; overload; deprecated 'Use Tdirectory.IsEmpty Instead';
function ALFileExists(const Path: ansiString): boolean; overload; deprecated 'Use Tfile.Exists Instead';
function ALFileExists(const Path: String): boolean; overload; deprecated 'Use Tfile.Exists Instead';
function ALDirectoryExists(const Directory: Ansistring): Boolean; overload; deprecated 'Use Tdirectory.Exists Instead';
function ALDirectoryExists(const Directory: string): Boolean; overload; deprecated 'Use Tdirectory.Exists Instead';
function ALCreateDir(const Dir: Ansistring): Boolean; overload; deprecated 'Use Tdirectory.CreateDirectory Instead';
function ALCreateDir(const Dir: string): Boolean; overload; deprecated 'Use Tdirectory.CreateDirectory Instead';
function ALRemoveDir(const Dir: Ansistring): Boolean; overload; deprecated 'Use Tdirectory.Delete Instead';
function ALRemoveDir(const Dir: string): Boolean; overload; deprecated 'Use Tdirectory.Delete Instead';
function ALDeleteFile(const FileName: Ansistring): Boolean; overload; deprecated 'Use Tfile.Delete Instead';
function ALDeleteFile(const FileName: string): Boolean; overload; deprecated 'Use Tfile.Delete Instead';
function ALRenameFileA(const OldName, NewName: ansistring): Boolean; deprecated 'Use Tfile.Move Instead';
function ALRenameFileW(const OldName, NewName: string): Boolean; deprecated 'Use Tfile.Move Instead';
{$ENDIF}
implementation
uses
System.Classes,
System.sysutils,
System.IOUtils,
System.Masks,
{$IF defined(MSWINDOWS)}
System.AnsiStrings,
Winapi.Windows,
Winapi.ShLwApi,
{$ELSE}
Posix.Unistd,
{$ENDIF}
Alcinoe.StringUtils,
Alcinoe.StringList;
{**************************}
Function AlEmptyDirectoryA(
Directory: ansiString;
SubDirectory: Boolean;
const IgnoreFiles: Array of AnsiString;
const RemoveEmptySubDirectory: Boolean = True;
const FileNameMask: ansiString = '*';
const MinFileAge: TdateTime = ALNullDate): Boolean;
var LIgnoreFilesW: Array of String;
begin
setlength(LIgnoreFilesW, length(IgnoreFiles));
for var I := Low(IgnoreFiles) to High(IgnoreFiles) do
LIgnoreFilesW[i] := String(IgnoreFiles[i]);
result := AlEmptyDirectoryW(
String(Directory),
SubDirectory,
LIgnoreFilesW,
RemoveEmptySubDirectory,
String(FileNameMask),
MinFileAge);
end;
{**************************}
Function AlEmptyDirectoryW(
Directory: String;
SubDirectory: Boolean;
const IgnoreFiles: Array of String;
const RemoveEmptySubDirectory: Boolean = True;
const FileNameMask: String = '*';
const MinFileAge: TdateTime = ALNullDate): Boolean;
var LSR: TSearchRec;
LIgnoreFilesLst: TALStringListW;
I: integer;
begin
if (Directory = '') or
(Directory = '.') or
(Directory = '..') then raise EALException.CreateFmt('Wrong directory ("%s")', [Directory]);
Result := True;
Directory := ALIncludeTrailingPathDelimiterW(Directory);
LIgnoreFilesLst := TALStringListW.Create;
try
for I := 0 to length(IgnoreFiles) - 1 do LIgnoreFilesLst.Add(ALExcludeTrailingPathDelimiterW(IgnoreFiles[I]));
LIgnoreFilesLst.Duplicates := DupIgnore;
LIgnoreFilesLst.Sorted := True;
if System.sysutils.FindFirst(Directory + '*', faAnyFile , LSR) = 0 then begin
Try
repeat
If (LSR.Name <> '.') and
(LSR.Name <> '..') and
(LIgnoreFilesLst.IndexOf(Directory + LSR.Name) < 0) Then Begin
If ((LSR.Attr and faDirectory) <> 0) then begin
If SubDirectory then begin
Result := AlEmptyDirectoryW(
Directory + LSR.Name,
True,
IgnoreFiles,
RemoveEmptySubDirectory,
fileNameMask,
MinFileAge);
If result and RemoveEmptySubDirectory then
result := RemoveDir(Directory + LSR.Name);
end;
end
else If ((FileNameMask = '*') or
ALMatchesMaskW(LSR.Name, FileNameMask))
and
((MinFileAge=ALNullDate) or
(LSR.TimeStamp < MinFileAge))
then Result := System.sysutils.Deletefile(Directory + LSR.Name);
end;
until (not result) or (FindNext(LSR) <> 0);
finally
System.sysutils.FindClose(LSR);
end;
end;
finally
LIgnoreFilesLst.Free;
end;
end;
{*************************}
Function AlEmptyDirectoryA(
const Directory: ansiString;
SubDirectory: Boolean;
Const RemoveEmptySubDirectory: Boolean = True;
Const FileNameMask: ansiString = '*';
Const MinFileAge: TdateTime = ALNullDate): Boolean;
begin
result := AlEmptyDirectoryA(
Directory,
SubDirectory,
[],
RemoveEmptySubDirectory,
FileNameMask,
MinFileAge);
end;
{*************************}
Function AlEmptyDirectoryW(
const Directory: String;
SubDirectory: Boolean;
Const RemoveEmptySubDirectory: Boolean = True;
Const FileNameMask: String = '*';
Const MinFileAge: TdateTime = 0): Boolean;
begin
result := AlEmptyDirectoryW(
Directory,
SubDirectory,
[],
RemoveEmptySubDirectory,
FileNameMask,
MinFileAge);
end;
{**********************}
{$IF defined(MSWINDOWS)}
Function AlCopyDirectoryA(
SrcDirectory,
DestDirectory: ansiString;
SubDirectory: Boolean;
Const FileNameMask: ansiString = '*';
Const FailIfExists: Boolean = True;
Const SkipIfExists: Boolean = False): Boolean;
begin
result := AlCopyDirectoryW(
String(SrcDirectory),
String(DestDirectory),
SubDirectory,
String(FileNameMask),
FailIfExists,
SkipIfExists);
end;
{$ENDIF}
{**********************}
{$IF defined(MSWINDOWS)}
Function AlCopyDirectoryW(
SrcDirectory,
DestDirectory: String;
SubDirectory: Boolean;
Const FileNameMask: String = '*';
Const FailIfExists: Boolean = True;
Const SkipIfExists: Boolean = False): Boolean;
var sr: TSearchRec;
begin
Result := True;
SrcDirectory := ALIncludeTrailingPathDelimiterW(SrcDirectory);
DestDirectory := ALIncludeTrailingPathDelimiterW(DestDirectory);
If not DirectoryExists(DestDirectory) and (not Createdir(DestDirectory)) then begin
result := False;
exit;
end;
if System.sysutils.FindFirst(SrcDirectory + '*', faAnyFile, sr) = 0 then begin
Try
repeat
If (sr.Name <> '.') and (sr.Name <> '..') Then Begin
If ((sr.Attr and faDirectory) <> 0) then begin
If SubDirectory then Result := AlCopyDirectoryW(
SrcDirectory + sr.Name,
DestDirectory + sr.Name,
SubDirectory,
FileNameMask,
FailIfExists,
SkipIfExists);
end
else If (FileNameMask = '*') or
(ALMatchesMaskW(sr.Name, FileNameMask)) then begin
if SkipIfExists then begin
if not Tfile.Exists(DestDirectory + sr.Name) then
Result := CopyfileW(
PChar(SrcDirectory + sr.Name),
PChar(DestDirectory + sr.Name),
True{FailIfExists});
end
else begin
result := CopyfileW(
PChar(SrcDirectory + sr.Name),
PChar(DestDirectory + sr.Name),
FailIfExists);
end;
end;
end;
until (not result) or (FindNext(sr) <> 0);
finally
System.sysutils.FindClose(sr);
end;
end
end;
{$ENDIF}
{**********************}
{$IF defined(MSWINDOWS)}
function ALGetModuleFileNameA(const AWithoutExtension: boolean = True): ansiString;
Var Ln: Integer;
begin
result := ALExtractFileName(ALGetModuleNameA);
if AWithoutExtension then begin
ln := Length(ALExtractFileExt(Result));
if Ln > 0 then delete(Result,length(Result)-ln+1,ln);
end;
end;
{$ENDIF}
{**********************}
{$IF defined(MSWINDOWS)}
function ALGetModuleFileNameW(const AWithoutExtension: boolean = True): String;
Var Ln: Integer;
begin
result := ALExtractFileName(ALGetModuleNameW);
if AWithoutExtension then begin
ln := Length(ALExtractFileExt(Result));
if Ln > 0 then delete(Result,length(Result)-ln+1,ln);
end;
end;
{$ENDIF}
{**********************}
{$IF defined(MSWINDOWS)}
function ALGetModuleNameA: ansiString;
var ModName: array[0..MAX_PATH] of AnsiChar;
begin
SetString(Result, ModName, Winapi.Windows.GetModuleFileNameA(HInstance, ModName, SizeOf(ModName)));
If ALPosA('\\?\',result) = 1 then delete(Result,1,4);
end;
{$ENDIF}
{**********************}
{$IF defined(MSWINDOWS)}
function ALGetModuleNameW: String;
var ModName: array[0..MAX_PATH] of Char;
begin
SetString(Result, ModName, Winapi.Windows.GetModuleFileNameW(HInstance, ModName, SizeOf(ModName)));
If ALPosW('\\?\',result) = 1 then delete(Result,1,4);
end;
{$ENDIF}
{**********************}
{$IF defined(MSWINDOWS)}
function ALGetModulePathA: ansiString;
begin
Result:=ALExtractFilePath(ALGetModuleNameA);
If (length(result) > 0) and (result[length(result)] <> '\') then result := result + '\';
end;
{$ENDIF}
{**********************}
{$IF defined(MSWINDOWS)}
function ALGetModulePathW: String;
begin
Result:=ALExtractFilePath(ALGetModuleNameW);
If (length(result) > 0) and (result[length(result)] <> '\') then result := result + '\';
end;
{$ENDIF}
{**********************}
{$IF defined(MSWINDOWS)}
Function AlGetFileSize(const AFileName: ansistring): int64;
var
Handle: THandle;
FindData: TWin32FindDataA;
begin
Handle := FindFirstFileA(PAnsiChar(AFileName), FindData);
if Handle <> INVALID_HANDLE_VALUE then
begin
Winapi.Windows.FindClose(Handle);
if (FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) = 0 then
begin
Int64Rec(Result).Lo := FindData.nFileSizeLow;
Int64Rec(Result).Hi := FindData.nFileSizeHigh;
Exit;
end;
end;
Result := -1;
end;
{$ENDIF}
{******************************************************}
function ALGetFileSize(const FileName : string) : Int64;
begin
Result := Tfile.GetSize(FileName);
end;
{**********************}
{$IF defined(MSWINDOWS)}
Function AlGetFileVersion(const AFileName: ansiString): ansiString;
var
FileName: ansiString;
InfoSize, Wnd: DWORD;
VerBuf: Pointer;
FI: PVSFixedFileInfo;
VerSize: DWORD;
begin
Result := '';
FileName := AFileName;
UniqueString(FileName);
InfoSize := GetFileVersionInfoSizeA(PAnsiChar(FileName), Wnd);
if InfoSize <> 0 then begin
GetMem(VerBuf, InfoSize);
try
if GetFileVersionInfoA(PAnsiChar(FileName), Wnd, InfoSize, VerBuf) then
if VerQueryValue(VerBuf, '\', Pointer(FI), VerSize) then
Result := ALIntToStrA(HiWord(FI.dwFileVersionMS)) +'.'+ ALIntToStrA(LoWord(FI.dwFileVersionMS)) +'.'+ ALIntToStrA(HiWord(FI.dwFileVersionLS)) +'.'+ ALIntToStrA(LoWord(FI.dwFileVersionLS));
finally
FreeMem(VerBuf);
end;
end;
end;
{$ENDIF}
{**********************}
{$IF defined(MSWINDOWS)}
function ALGetFileCreationDateTime(const aFileName: Ansistring): TDateTime;
var LHandle: THandle;
LFindData: TWin32FindDataA;
LLocalFileTime: TFileTime;
begin
LHandle := FindFirstFileA(PAnsiChar(aFileName), LFindData);
if (LHandle = INVALID_HANDLE_VALUE) or
(not Winapi.Windows.FindClose(LHandle)) or
(not FileTimeToLocalFileTime(LFindData.ftCreationTime, LLocalFileTime)) then raiselastOsError;
Result := ALFileTimeToDateTime(LLocalFileTime);
end;
{$ENDIF}
{**********************}
{$IF defined(MSWINDOWS)}
function ALGetFileCreationDateTime(const aFileName: String): TDateTime;
var LHandle: THandle;
LFindData: TWin32FindData;
LLocalFileTime: TFileTime;
begin
LHandle := FindFirstFileW(PChar(aFileName), LFindData);
if (LHandle = INVALID_HANDLE_VALUE) or
(not Winapi.Windows.FindClose(LHandle)) or
(not FileTimeToLocalFileTime(LFindData.ftCreationTime, LLocalFileTime)) then raiselastOsError;
Result := ALFileTimeToDateTime(LLocalFileTime);
end;
{$ENDIF}
{**********************}
{$IF defined(MSWINDOWS)}
function ALGetFileLastWriteDateTime(const aFileName: Ansistring): TDateTime;
var LHandle: THandle;
LFindData: TWin32FindDataA;
LLocalFileTime: TFileTime;
begin
LHandle := FindFirstFileA(PAnsiChar(aFileName), LFindData);
if (LHandle = INVALID_HANDLE_VALUE) or
(not Winapi.Windows.FindClose(LHandle)) or
(not FileTimeToLocalFileTime(LFindData.ftLastWriteTime, LLocalFileTime)) then raiselastOsError;
Result := ALFileTimeToDateTime(LLocalFileTime);
end;
{$ENDIF}
{**********************}
{$IF defined(MSWINDOWS)}
function ALGetFileLastWriteDateTime(const aFileName: String): TDateTime;
var LHandle: THandle;
LFindData: TWin32FindData;
LLocalFileTime: TFileTime;
begin
LHandle := FindFirstFileW(PChar(aFileName), LFindData);
if (LHandle = INVALID_HANDLE_VALUE) or
(not Winapi.Windows.FindClose(LHandle)) or
(not FileTimeToLocalFileTime(LFindData.ftLastWriteTime, LLocalFileTime)) then raiselastOsError;
Result := ALFileTimeToDateTime(LLocalFileTime);
end;
{$ENDIF}
{**********************}
{$IF defined(MSWINDOWS)}
function ALGetFileLastAccessDateTime(const aFileName: Ansistring): TDateTime;
var LHandle: THandle;
LFindData: TWin32FindDataA;
LLocalFileTime: TFileTime;
begin
LHandle := FindFirstFileA(PAnsiChar(aFileName), LFindData);
if (LHandle = INVALID_HANDLE_VALUE) or
(not Winapi.Windows.FindClose(LHandle)) or
(not FileTimeToLocalFileTime(LFindData.ftLastAccessTime, LLocalFileTime)) then raiselastOsError;
Result := ALFileTimeToDateTime(LLocalFileTime);
end;
{$ENDIF}
{**********************}
{$IF defined(MSWINDOWS)}
function ALGetFileLastAccessDateTime(const aFileName: String): TDateTime;
var LHandle: THandle;
LFindData: TWin32FindData;
LLocalFileTime: TFileTime;
begin
LHandle := FindFirstFileW(PChar(aFileName), LFindData);
if (LHandle = INVALID_HANDLE_VALUE) or
(not Winapi.Windows.FindClose(LHandle)) or
(not FileTimeToLocalFileTime(LFindData.ftLastAccessTime, LLocalFileTime)) then raiselastOsError;
Result := ALFileTimeToDateTime(LLocalFileTime);
end;
{$ENDIF}
{**********************}
{$IF defined(MSWINDOWS)}
Procedure ALSetFileCreationDateTime(Const aFileName: Ansistring; Const aCreationDateTime: TDateTime);
Var LHandle: Thandle;
LSystemTime: TsystemTime;
LFiletime: TfileTime;
Begin
LHandle := System.sysUtils.fileOpen(String(aFileName), fmOpenWrite or fmShareDenyNone);
if LHandle = INVALID_HANDLE_VALUE then raiseLastOsError;
Try
dateTimeToSystemTime(aCreationDateTime, LSystemTime);
if (not SystemTimeToFileTime(LSystemTime, LFiletime)) or
(not LocalFileTimeToFileTime(LFiletime, LFiletime)) or
(not setFileTime(LHandle, @LFiletime, nil, nil)) then raiselastOsError;
finally
fileClose(LHandle);
end;
End;
{$ENDIF}
{**********************}
{$IF defined(MSWINDOWS)}
Procedure ALSetFileCreationDateTime(Const aFileName: String; Const aCreationDateTime: TDateTime);
Var LHandle: Thandle;
LSystemTime: TsystemTime;
LFiletime: TfileTime;
Begin
LHandle := System.sysUtils.fileOpen(aFileName, fmOpenWrite or fmShareDenyNone);
if LHandle = INVALID_HANDLE_VALUE then raiseLastOsError;
Try
dateTimeToSystemTime(aCreationDateTime, LSystemTime);
if (not SystemTimeToFileTime(LSystemTime, LFiletime)) or
(not LocalFileTimeToFileTime(LFiletime, LFiletime)) or
(not setFileTime(LHandle, @LFiletime, nil, nil)) then raiselastOsError;
finally
fileClose(LHandle);
end;
End;
{$ENDIF}
{**********************}
{$IF defined(MSWINDOWS)}
Procedure ALSetFileLastWriteDateTime(Const aFileName: Ansistring; Const aLastWriteDateTime: TDateTime);
Var LHandle: Thandle;
LSystemTime: TsystemTime;
LFiletime: TfileTime;
Begin
LHandle := System.sysUtils.fileOpen(String(aFileName), fmOpenWrite or fmShareDenyNone);
if LHandle = INVALID_HANDLE_VALUE then raiseLastOsError;
Try
dateTimeToSystemTime(aLastWriteDateTime, LSystemTime);
if (not SystemTimeToFileTime(LSystemTime, LFiletime)) or
(not LocalFileTimeToFileTime(LFiletime, LFiletime)) or
(not setFileTime(LHandle, nil, nil, @LFiletime)) then raiselastOsError;
finally
fileClose(LHandle);
end;
End;
{$ENDIF}
{**********************}
{$IF defined(MSWINDOWS)}
Procedure ALSetFileLastWriteDateTime(Const aFileName: String; Const aLastWriteDateTime: TDateTime);
Var LHandle: Thandle;
LSystemTime: TsystemTime;
LFiletime: TfileTime;
Begin
LHandle := System.sysUtils.fileOpen(aFileName, fmOpenWrite or fmShareDenyNone);
if LHandle = INVALID_HANDLE_VALUE then raiseLastOsError;
Try
dateTimeToSystemTime(aLastWriteDateTime, LSystemTime);
if (not SystemTimeToFileTime(LSystemTime, LFiletime)) or
(not LocalFileTimeToFileTime(LFiletime, LFiletime)) or
(not setFileTime(LHandle, nil, nil, @LFiletime)) then raiselastOsError;
finally
fileClose(LHandle);
end;
End;
{$ENDIF}
{**********************}
{$IF defined(MSWINDOWS)}
Procedure ALSetFileLastAccessDateTime(Const aFileName: Ansistring; Const aLastAccessDateTime: TDateTime);
Var LHandle: Thandle;
LSystemTime: TsystemTime;
LFiletime: TfileTime;
Begin
LHandle := System.sysUtils.fileOpen(String(aFileName), fmOpenWrite or fmShareDenyNone);
if LHandle = INVALID_HANDLE_VALUE then raiseLastOsError;
Try
dateTimeToSystemTime(aLastAccessDateTime, LSystemTime);
if (not SystemTimeToFileTime(LSystemTime, LFiletime)) or
(not LocalFileTimeToFileTime(LFiletime, LFiletime)) or
(not setFileTime(LHandle, nil, @LFiletime, nil)) then raiselastOsError;
finally
fileClose(LHandle);
end;
End;
{$ENDIF}
{**********************}
{$IF defined(MSWINDOWS)}
Procedure ALSetFileLastAccessDateTime(Const aFileName: String; Const aLastAccessDateTime: TDateTime);
Var LHandle: Thandle;
LSystemTime: TsystemTime;
LFiletime: TfileTime;
Begin
LHandle := System.sysUtils.fileOpen(aFileName, fmOpenWrite or fmShareDenyNone);
if LHandle = INVALID_HANDLE_VALUE then raiseLastOsError;
Try
dateTimeToSystemTime(aLastAccessDateTime, LSystemTime);
if (not SystemTimeToFileTime(LSystemTime, LFiletime)) or
(not LocalFileTimeToFileTime(LFiletime, LFiletime)) or
(not setFileTime(LHandle, nil, @LFiletime, nil)) then raiselastOsError;
finally
fileClose(LHandle);
end;
End;
{$ENDIF}
{**********************}
{$IF defined(MSWINDOWS)}
function ALIsDirectoryEmpty(const directory: ansiString): boolean;
begin
Result := PathIsDirectoryEmptyA(PansiChar(directory));
end;
{$ENDIF}
{**********************}
{$IF defined(MSWINDOWS)}
function ALIsDirectoryEmpty(const directory: String): boolean;
begin
Result := PathIsDirectoryEmptyW(PChar(directory));
end;
{$ENDIF}
{**********************}
{$IF defined(MSWINDOWS)}
function ALFileExists(const Path: ansiString): boolean;
begin
result := PathFileExistsA(PansiChar(Path)) and (not PathIsDirectoryA(PansiChar(Path)));
end;
{$ENDIF}
{**********************}
{$IF defined(MSWINDOWS)}
function ALFileExists(const Path: String): boolean;
begin
result := PathFileExistsW(PChar(Path)) and (not PathIsDirectoryW(PChar(Path)));
end;
{$ENDIF}
{**********************}
{$IF defined(MSWINDOWS)}
function ALDirectoryExists(const Directory: Ansistring): Boolean;
begin
result := PathFileExistsA(PansiChar(Directory)) and (PathIsDirectoryA(PansiChar(Directory)));
end;
{$ENDIF}
{**********************}
{$IF defined(MSWINDOWS)}
function ALDirectoryExists(const Directory: string): Boolean;
begin
result := PathFileExistsW(PChar(Directory)) and (PathIsDirectoryW(PChar(Directory)));
end;
{$ENDIF}
{**********************}
{$IF defined(MSWINDOWS)}
function ALCreateDir(const Dir: Ansistring): Boolean;
begin
Result := CreateDirectoryA(PAnsiChar(Dir), nil);
end;
{$ENDIF}
{**********************}
{$IF defined(MSWINDOWS)}
function ALCreateDir(const Dir: string): Boolean;
begin
Result := CreateDirectoryW(PChar(Dir), nil);
end;
{$ENDIF}
{**********************}
{$IF defined(MSWINDOWS)}
function ALRemoveDir(const Dir: Ansistring): Boolean;
begin
Result := RemoveDirectoryA(PansiChar(Dir));
end;
{$ENDIF}
{**********************}
{$IF defined(MSWINDOWS)}
function ALRemoveDir(const Dir: string): Boolean;
begin
Result := RemoveDirectoryW(PChar(Dir));
end;
{$ENDIF}
{**********************}
{$IF defined(MSWINDOWS)}
function ALDeleteFile(const FileName: Ansistring): Boolean;
begin
Result := DeleteFileA(PAnsiChar(FileName));
end;
{$ENDIF}
{**********************}
{$IF defined(MSWINDOWS)}
function ALDeleteFile(const FileName: String): Boolean;
begin
Result := DeleteFileW(PChar(FileName));
end;
{$ENDIF}
{**********************}
{$IF defined(MSWINDOWS)}
function ALRenameFileA(const OldName, NewName: ansistring): Boolean;
begin
Result := MoveFileA(PansiChar(OldName), PansiChar(NewName));
end;
{$ENDIF}
{**********************}
{$IF defined(MSWINDOWS)}
function ALRenameFileW(const OldName, NewName: String): Boolean;
begin
Result := MoveFileW(PChar(OldName), PChar(NewName));
end;
{$ENDIF}
end.
|
unit UImage1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls,ImgLibObjs, NewDlgs;
type
TForm1 = class(TForm)
Panel1: TPanel;
Label1: TLabel;
edFile: TEdit;
btnBrowse: TButton;
btnOpen: TButton;
btnSave: TButton;
btnSaveStream: TButton;
btnLoadStream: TButton;
btnLoadData: TButton;
btnSaveData: TButton;
btnRotate90: TButton;
btnRotate180: TButton;
btnFlip: TButton;
ILImage1: TILImage;
OpenDialog1: TOpenDialogEx;
Label2: TLabel;
lbResolution: TLabel;
procedure btnOpenClick(Sender: TObject);
procedure btnBrowseClick(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure btnSaveStreamClick(Sender: TObject);
procedure btnLoadStreamClick(Sender: TObject);
procedure btnLoadDataClick(Sender: TObject);
procedure btnSaveDataClick(Sender: TObject);
procedure btnRotate90Click(Sender: TObject);
procedure btnRotate180Click(Sender: TObject);
procedure btnFlipClick(Sender: TObject);
procedure ILImage1Progress(Sender: TObject; Stage: TProgressStage;
PercentDone: Byte; RedrawNow: Boolean; const R: TRect;
const Msg: String);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses ImageLibX, UProgress;
{$R *.DFM}
procedure TForm1.btnBrowseClick(Sender: TObject);
begin
if OpenDialog1.Execute then
begin
edFile.Text := OpenDialog1.FileName;
//btnOpenClick(sender);
end;
end;
procedure TForm1.btnOpenClick(Sender: TObject);
begin
if edFile.text<>'' then
begin
dlgProgress.Start;
try
ILImage1.ImageObj.LoadFromFile(edFile.text);
finally
dlgProgress.Done;
end;
lbResolution.caption :=
IntToStr(ILImage1.ImageObj.LoadResolution);
end;
end;
procedure TForm1.btnSaveClick(Sender: TObject);
begin
if edFile.text<>'' then
begin
// add code here.
ILImage1.ImageObj.SaveToFile(edFile.text);
end;
end;
type
TImgLibObjAccess = class(TImgLibObj);
procedure TForm1.btnSaveStreamClick(Sender: TObject);
var
f : TFileStream;
begin
if edFile.text<>'' then
begin
// add code here.
f := TFileStream.Create(edFile.text,fmCreate);
ILImage1.ImageObj.ImageType := GetImageTypeFromFileExt(edFile.text);
try
ILImage1.ImageObj.SaveToStream(f);
finally
f.free;
end;
end;
end;
procedure TForm1.btnLoadStreamClick(Sender: TObject);
var
f : TFileStream;
begin
if edFile.text<>'' then
begin
// add code here.
f := TFileStream.Create(edFile.text,fmOpenRead);
try
ILImage1.ImageObj.LoadFromStream(f);
finally
f.free;
end;
lbResolution.caption :=
IntToStr(ILImage1.ImageObj.LoadResolution);
end;
end;
procedure TForm1.btnLoadDataClick(Sender: TObject);
var
f : TFileStream;
begin
if edFile.text<>'' then
begin
// add code here.
f := TFileStream.Create(edFile.text,fmOpenRead);
try
TImgLibObjAccess(ILImage1.ImageObj).ReadData(f);
finally
f.free;
end;
lbResolution.caption :=
IntToStr(ILImage1.ImageObj.LoadResolution);
end;
end;
procedure TForm1.btnSaveDataClick(Sender: TObject);
var
f : TFileStream;
begin
if edFile.text<>'' then
begin
// add code here.
f := TFileStream.Create(edFile.text,fmCreate);
ILImage1.ImageObj.ImageType := GetImageTypeFromFileExt(edFile.text);
try
TImgLibObjAccess(ILImage1.ImageObj).WriteData(f);
finally
f.free;
end;
end;
end;
(*
//Vesrion 1 : OK!
// Notes :
//ROTATEDDB90 will change the handle
procedure TForm1.btnRotate90Click(Sender: TObject);
var
hBMP1,hBMP2 : HBitmap;
hPAL1,hPAL2 : HPalette;
begin
ILImage1.ImageObj.Bitmap.FreeImage;
hBMP1:=ILImage1.ImageObj.Bitmap.Handle;
HPAL1:=ILImage1.ImageObj.Bitmap.Palette;
hBmp2 := hBmp1;
HPAL2 := HPAL1;
//HPAL2 := 0;
ILImage1.ImageObj.Bitmap.ReleaseHandle;
ILImage1.ImageObj.Bitmap.ReleasePalette;
CheckImgLibCallError(ROTATEDDB90(ILImage1.ImageObj.LoadResolution,hBMP2,HPAL2,0));
ILImage1.ImageObj.Bitmap.Palette :=HPAL2;
ILImage1.ImageObj.Bitmap.Handle :=hBMP2;
if hBmp1<>hBmp2 then
begin
deleteObject(hBmp1);
OutputDebugString(pchar(format('Bmp:New=%d,Old=%d',[hBmp2,hBmp1])));
end;
if hPal1<>hPal2 then
begin
deleteObject(hPal1);
OutputDebugString(pchar(format('Pal:New=%d,Old=%d',[hPal2,hPal1])));
end;
ILImage1.Invalidate;
end;
*)
(*
//version2 OK
procedure TForm1.btnRotate90Click(Sender: TObject);
var
hBMP : HBitmap;
hPAL : HPalette;
begin
hBMP:=ILImage1.ImageObj.Bitmap.Handle;
HPAL:=ILImage1.ImageObj.Bitmap.Palette;
CheckImgLibCallError(ROTATEDDB90(ILImage1.ImageObj.LoadResolution,hBMP,HPAL,0));
ILImage1.ImageObj.Bitmap.Palette :=HPAL;
ILImage1.ImageObj.Bitmap.Handle :=hBMP;
ILImage1.Invalidate;
end;
*)
procedure TForm1.btnRotate90Click(Sender: TObject);
begin
ILImage1.ImageObj.Rotate90;
end;
procedure TForm1.btnRotate180Click(Sender: TObject);
begin
ILImage1.ImageObj.Rotate180;
end;
procedure TForm1.btnFlipClick(Sender: TObject);
begin
ILImage1.ImageObj.Flip;
end;
procedure TForm1.ILImage1Progress(Sender: TObject; Stage: TProgressStage;
PercentDone: Byte; RedrawNow: Boolean; const R: TRect;
const Msg: String);
begin
dlgProgress.Progress(PercentDone);
if dlgProgress.isCancel then ILImage1.ImageObj.IsCancel := true;
end;
end.
|
unit DatabaseConnection;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs,
DatabaseConfig, DataSet, Query, Statement, DB;
type
IDatabaseConnection = interface
['{3110F532-BEBB-4D3A-9FA1-2EDD1DDF9D42}']
procedure open;
procedure close;
procedure configure(const config: IDatabaseConfig);
function connected: Boolean;
function createQuery: IQuery;
function inTransaction: Boolean;
procedure StartTransaction;
procedure CommitTransaction;
procedure RollbackTransaction;
function realConnection: TObject;
function Execute(const AStatement: IStatement): Integer;
function getFields(ATableName: String): TFieldListMetadata;
procedure getTableNames(AList: TStrings);
end;
IDatabaseConnectionProvider = interface
['{520470FC-0111-47EB-9806-BC12CA5FB319}']
end;
implementation
end.
|
unit NetReaderProtelTango;
interface
uses NetReader, ExceptSafe;
// Low level access to Protel Netlist files.
type ESafeProtelTangoReader = class( ESafe );
type TProtelNetReader = class( TveNetReader )
protected
CurrentNet : string;
HaveNet : boolean;
function GetNetlistDescriptor : string; override;
procedure ParseNetLine(
LineIndex : integer; const Line : string;
var Designator, PinName : string ); virtual;
public
function CheckCompatibility : boolean; override;
procedure ToFirstComponent; override;
function GetNextComponent( var Designator, Value, Outline : string ) : boolean;
override;
procedure ToFirstConnection; override;
function GetNextConnection( var NetName, Designator, PinName : string )
: boolean; override;
end;
// Low level access to Tango Netlist files.
type TTangoNetReader = class( TProtelNetReader )
protected
function GetNetlistDescriptor : string; override;
{
procedure ParseNetLine(
LineIndex : integer; const Line : string;
var Designator : string; var PinNo : Integer ); override;
}
end;
implementation
uses SysUtils;
// **********************************************
// TProtelNetReader
// **********************************************
// safe to scan each code unit (16 bit char) because both bytes of a surrogate
// are guaranteed never to match any single unit char.
function DeComma( const S : string ) : string;
var
i : integer;
begin
result := S;
for i := 1 to Length(S) do begin
if result[i] = ',' then begin
result[i] := '_';
end;
end;
end;
(*
A Net line is of form "U1-14" ie pin 14 of U1 is assigned to current net.
A component name can also include a '-', e.g. "U1--14" means pin 14 of U1- ,
so have to scan from the right when looking for separator '-'.
Code now accepts ',' as separator. First '-' or ',' from right is taken to be
separator.
*)
procedure TProtelNetReader.ParseNetLine(
LineIndex : integer; const Line : string; var Designator, PinName : string );
var
found : boolean;
i : integer;
c : char;
LineLength : integer;
begin
// scan from right until '-' found
found := False;
i := Length( Line );
while i > 0 do begin
c := Line[i];
if (c = '-') or (c = ',') then begin // Protel '-', Tango ','
// if Line[i] = '-' then begin // Protel
// if Line[i] = ',' then begin // Tango
found := True;
break;
end;
dec( i );
end;
if not Found then begin
raise ESafeProtelTangoReader.CreateFmt(
'Missing "-" or "," in Pin to Net assignment on line %d', // Protel, Tango
// 'Missing "-" in Pin to Net assignment on line %d', // Protel
// 'Missing "," in Pin to Net assignment on line %d', // Tango
[LineIndex + 1]
);
end;
Designator := DeComma(Copy( Line, 1, i-1 ));
//.. designator is Trimmed - to match Trim when reading when Designators in
//.. component section
Designator := Trim( Designator );
PinName := Trim(Copy( Line, i+1, 255 ));
// if PinName is blank, we might have encountered a line like
// R1,- or R1-- , which is ambiguous, but which we define as a special case
// of a pin name of '-'
LineLength := Length(Line);
if (PinName = '') and (LineLength > 2) then begin
// c is 2nd last char
c := Line[LineLength -1];
// if last char is '-' and char before is '-' or ','
if (Line[LineLength] = '-') and ((c = '-') or (c = ',')) then begin
Designator := Trim( Copy( Line, 1, LineLength-2 ));
PinName := '-';
end;
end;
end;
function TProtelNetReader.GetNetlistDescriptor : string;
begin
result := 'Protel';
end;
function TProtelNetReader.CheckCompatibility : boolean;
begin
result := True;
end;
procedure TProtelNetReader.ToFirstComponent;
begin
LineIndex := 0;
end;
function TProtelNetReader.GetNextComponent( var Designator, Value, Outline : string ) : boolean;
procedure LoadComponent;
const MinimumComponentLines = 5;
begin
// to next line
Inc( LineIndex );
// need at least 6 data lines plus ']' to complete component
if LineIndex >= LineLimit - MinimumComponentLines then begin
raise ESafeProtelTangoReader.CreateFmt(
'Component on lne %d has insufficient data lines',
[LineIndex + 1]
);
end;
// next 3 lines contain component info we want
//.. designator is Trimmed - when reading connection section of netlist
//.. must also Trim to avoid mismatches.
Designator := DeComma(Trim( Lines[ LineIndex ] ));
Inc( LineIndex );
Outline := DeComma(Trim( Lines[ LineIndex ] ));
Inc( LineIndex );
Value := DeComma(Trim( Lines[ LineIndex ] ));
// find the ']' which terminates the component
while LineIndex < LineLimit do begin
Line := Trim( Lines[LineIndex] );
if Line = ']' then begin
break;
end
else if Line = '[' then begin
raise ESafeTveNetReader.CreateFmt(
'"[" on line %d before end of component definition',
[LineIndex + 1]
);
end
else if Line = '(' then begin
raise ESafeProtelTangoReader.CreateFmt(
'"(" on line %d before end of component definition',
[LineIndex + 1]
);
end;
Inc( LineIndex )
end;
// must have designator (eg 'C1', 'Q2') - other fields can be blank
// OR could give a dummy designator or no designator ??
// OR raise an exception.
if (Designator = '') then begin
exit;
end;
end;
begin
// search for next component
while LineIndex < LineLimit do begin
Line := Lines[LineIndex];
if '[' = Line then begin
FCurrentLine := LineIndex + 2;
LoadComponent;
Inc( LineIndex );
result := True;
exit;
end;
Inc( LineIndex );
end;
// no component loaded - at end of file
result := False;
end;
procedure TProtelNetReader.ToFirstConnection;
begin
LineIndex := 0;
HaveNet := False;
end;
function TProtelNetReader.GetNextConnection( var NetName, Designator, PinName : string )
: boolean;
procedure ToNextNet;
begin
while LineIndex < LineLimit do begin
// find opening '(' of net definition group of lines
Line := Trim(Lines[LineIndex]);
if (Length(Line) > 0) and (Line[1] = '(') then begin
// Windraft has opening bracket and net name on same line..
// (N0025
// so net name is rest of this line
if Length(Line) > 1 then begin
CurrentNet := Trim( Copy( Line, 2, 255 ));
end
// Normal Protel has bracket and net name on separate lines..
// (
// N0025
else begin
// read net name on next line
Inc(LineIndex);
if LineIndex >= LineLimit then begin
exit;
end;
CurrentNet := Trim(Lines[LineIndex]);
end;
// successfully entered new net
Inc( LineIndex );
HaveNet := True;
exit;
end;
inc( LineIndex );
end;
// fell through loop and did not find net : leave HaveNet = False;
// HaveNet := False;
end;
begin
while LineIndex < LineLimit do begin
// must be inside a net definition
if not HaveNet then begin
ToNextNet;
// no net definition found
if not HaveNet then begin
result := False;
exit;
end;
end;
// read line
Line := Lines[ LineIndex ];
// find end of net definition
if Line = ')' then begin
HaveNet := False;
Inc( LineIndex );
continue;
end;
// find pin to net assignment , eg line is "U1-3"
// separate net line into Designator & PinNo
ParseNetLine( LineIndex, Line, Designator, PinName );
NetName := CurrentNet;
Inc( LineIndex );
FCurrentLine := LineIndex;
result := True;
exit;
end;
// fell through loop - end of netlist file
result := False;
end;
// **********************************************
// TTangoNetReader
// **********************************************
{
TANGO uses ',' separator in component pin descriptors
PROTEL uses '-' separator in component pin descriptors
Otherwise these two formats are handled by the same code
Tango
(
GND
U15,7
U15,13
)
Protel
(
GND
U15-7
U15-13
)
}
function TTangoNetReader.GetNetlistDescriptor : string;
begin
result := 'Tango';
end;
(*
A Net line is of form "U1,14" ie pin 14 of U1 is assigned to current net.
A component name can also include a ',', e.g. "U1,,14" means pin 14 of "U1,"
so have to scan from the right when looking for separator ','.
*)
(*
procedure TTangoNetReader.ParseNetLine(
LineIndex : integer; const Line : string;
var Designator : string; var PinNo : Integer );
var
found : boolean;
i : integer;
PinNoString : string;
begin
// scan from right until '-' found
found := False;
i := Length( Line );
while i > 0 do begin
// if Line[i] = '-' then begin // Protel
if Line[i] = ',' then begin // Tango
found := True;
break;
end;
dec( i );
end;
if not Found then begin
raise ETveNetReader.CreateFmt(
// 'Missing "-" in Pin to Net assignment on line %d', // Protel
'Missing "," in Pin to Net assignment on line %d', // Tango
[LineIndex + 1]
);
end;
Designator := DeComma(Copy( Line, 1, i-1 ));
PinNoString := Trim(Copy( Line, i+1, 255 ));
try
PinNo := StrToInt( PinNoString );
except
raise ETveNetReader.CreateFmt(
'Invalid pin number "%s" in Pin to Net assignment on line %d',
[PinNoString, LineIndex + 1]
);
end;
end;
*)
end.
|
unit uLogOptions;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, GnuGettext, uTools, uMain,
Vcl.Buttons;
type
TfLogOptions = class(TForm)
FontDialog: TFontDialog;
lblLogFont: TLabel;
tLogFont: TEdit;
lblLogFontSize: TLabel;
bSelect: TButton;
tLogFontSize: TEdit;
bSave: TBitBtn;
bCancel: TBitBtn;
procedure bSelectClick(Sender: TObject);
procedure FontDialogApply(Sender: TObject; Wnd: HWND);
procedure FontDialogClose(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure bCancelClick(Sender: TObject);
procedure bSaveClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
fLogOptions: TfLogOptions;
implementation
{$R *.dfm}
procedure TfLogOptions.bCancelClick(Sender: TObject);
begin
Close;
end;
procedure TfLogOptions.bSaveClick(Sender: TObject);
begin
Config.LogSettings.Font := FontDialog.Font.Name;
Config.LogSettings.FontSize := FontDialog.Font.Size;
fMain.AdjustLogFont(FontDialog.Font.Name, FontDialog.Font.Size);
SaveSettings;
Close;
end;
procedure TfLogOptions.bSelectClick(Sender: TObject);
begin
FontDialog.Execute();
end;
procedure TfLogOptions.FontDialogApply(Sender: TObject; Wnd: HWND);
begin
tLogFont.Text := FontDialog.Font.Name;
tLogFontSize.Text := IntToStr(FontDialog.Font.Size);
end;
procedure TfLogOptions.FontDialogClose(Sender: TObject);
begin
tLogFont.Text := FontDialog.Font.Name;
tLogFontSize.Text := IntToStr(FontDialog.Font.Size);
end;
procedure TfLogOptions.FormCreate(Sender: TObject);
begin
TranslateComponent(Self);
end;
procedure TfLogOptions.FormShow(Sender: TObject);
begin
tLogFont.Text := Config.LogSettings.Font;
tLogFontSize.Text := IntToStr(Config.LogSettings.FontSize);
FontDialog.Font.Name := Config.LogSettings.Font;
FontDialog.Font.Size := Config.LogSettings.FontSize;
end;
end.
|
unit ULicSubscription;
{ ClickForms Application }
{ Bradford Technologies, Inc. }
{ All Rights Reserved }
{ Source Code Copyrighted © 1998-2008 by Bradford Technologies, Inc. }
{This unit makes a webservice call to check a users subscription status}
interface
function GetUserHasValidSubscription(CustID: Integer; var serverDate: TDateTime): Boolean;
implementation
uses
SysUtils, Classes, XSBuiltIns, DateUtils,
UGlobals, ULicUser, UUtil3, UStatus, UWebUtils, UWebConfig, RegistrationService;
const
defaultInt = 0;
dateFormat = 'mm/dd/yyyy';
function GetUserHasValidSubscription(CustID: Integer; var serverDate: TDateTime): Boolean;
var
xsUpdDate: TXSDateTime;
resCode: Integer;
begin
result := false;
try
xsUpdDate := TXSDateTime.Create;
try
if custID = defaultInt then //this should never show, since only valid licenses are checked
raise Exception.Create('You need to register ClickFORMS before you can use it.');
with GetRegistrationServiceSoap(True,GetURLForServiceReg) do
IsClickFormSubscriptionValid(CustID, WSServiceReg_Password, resCode, xsUpdDate);
serverDate := xsUpdDate.AsDateTime; //our real date
result := (resCode = 1); //they are on subscription
finally
xsUpdDate.Free;
end;
except
on E:Exception do
begin
ShowNotice(E.Message);
end;
end;
end;
end.
|
unit debug;
{$mode fpc}
interface
type
TDebugOutProc = procedure(ch: char);
var DebugOutput: TDebugOutProc = nil;
procedure DebugStr(const s: shortstring);
procedure DebugLn(const s: shortstring);
procedure DebugLn;
procedure DebugChar(ch: char);
procedure DebugInt(v: longint);
procedure DebugHex(v: longword);
procedure DebugHexWord(v: word);
procedure DebugHexChar(v: byte);
implementation
procedure DebugChar(ch: char);
begin
if DebugOutput = nil then exit;
DebugOutput(ch);
end;
procedure DebugStr(const s: shortstring);
var i: longint;
begin
if DebugOutput = nil then exit;
for i := 1 to length(s) do
DebugOutput(s[i]);
end;
procedure DebugLn(const s: shortstring);
begin
debugstr(s);
debugln;
end;
procedure DebugLn;
begin
if DebugOutput = nil then exit;
DebugOutput(#13);
DebugOutput(#10);
end;
procedure DebugInt(v: longint);
var buffer: array[0..11] of char;
i: longint;
begin
if DebugOutput = nil then exit;
if v < 0 then
begin
DebugOutput('-');
v := -v;
end;
if v = 0 then
DebugOutput('0')
else
begin
i := 11;
while v > 0 do
begin
buffer[i] := char(byte('0')+(v mod 10));
v := v div 10;
dec(i);
end;
repeat
inc(i);
DebugOutput(buffer[i]);
until i >= 11;
end;
end;
procedure DebugHex(v: longword);
var i,t: longint;
begin
if DebugOutput = nil then exit;
for i := 7 downto 0 do
begin
t := (v shr (i*4)) and $F;
if t > 9 then
DebugOutput(char(byte('A')+t-10))
else
DebugOutput(char(byte('0')+t));
end;
end;
procedure DebugHexWord(v: word);
var i,t: longint;
begin
if DebugOutput = nil then exit;
for i := 3 downto 0 do
begin
t := (v shr (i*4)) and $F;
if t > 9 then
DebugOutput(char(byte('A')+t-10))
else
DebugOutput(char(byte('0')+t));
end;
end;
procedure DebugHexChar(v: byte);
var i,t: longint;
begin
if DebugOutput = nil then exit;
for i := 1 downto 0 do
begin
t := (v shr (i*4)) and $F;
if t > 9 then
DebugOutput(char(byte('A')+t-10))
else
DebugOutput(char(byte('0')+t));
end;
end;
end.
|
unit Alcinoe.Mime;
interface
uses
System.Types,
Alcinoe.StringList;
//From indy
Function ALGetDefaultFileExtFromMimeContentType(aContentType: AnsiString): AnsiString;
Function ALGetDefaultMIMEContentTypeFromExt(const aExt: AnsiString): AnsiString;
Var
AlMimeContentTypeByExtList: TALStringsA; {.htm=text/html}
AlExtbyMimeContentTypeList: TALStringsA; {text/html=.htm}
implementation
uses
System.AnsiStrings,
Alcinoe.StringUtils,
Alcinoe.Common;
{************************************************************************************}
Function ALGetDefaultFileExtFromMimeContentType(aContentType: AnsiString): AnsiString;
Var P: integer;
Index : Integer;
Begin
Result := '';
aContentType := ALLowerCase(aContentType);
P := ALPosA(';',aContentType);
if (P > 0) then delete(aContentType,P,MaxInt);
aContentType := ALTrim(AContentType);
Index := AlExtbyMimeContentTypeList.IndexOfName(aContentType);
if Index <> -1 then Result := AlExtbyMimeContentTypeList.ValueFromIndex[Index];
end;
{******************************************************************************}
Function ALGetDefaultMIMEContentTypeFromExt(const aExt: AnsiString): AnsiString;
var Index : Integer;
LExt: AnsiString;
begin
LExt := AlLowerCase(aExt);
If (LExt = '') or (LExt[low(AnsiString)] <> '.') then LExt := '.' + LExt;
Index := AlMimeContentTypeByExtList.IndexOfName(LExt);
if Index <> -1 then Result := AlMimeContentTypeByExtList.ValueFromIndex[Index]
else Result := 'application/octet-stream';
end;
{************************}
procedure ALFillMimeTable;
var I: integer;
begin
{NOTE: All of these strings should never be translated
because they are protocol specific and are important for some
web-browsers}
{ Animation }
AlMimeContentTypeByExtList.Add('.nml=animation/narrative'); {Do not Localize}
{ Audio }
AlMimeContentTypeByExtList.Add('.aac=audio/mp4');
AlMimeContentTypeByExtList.Add('.aif=audio/x-aiff'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.aifc=audio/x-aiff'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.aiff=audio/x-aiff'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.au=audio/basic'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.gsm=audio/x-gsm'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.kar=audio/midi'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.m3u=audio/mpegurl'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.m4a=audio/x-mpg'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.mid=audio/midi'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.midi=audio/midi'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.mpega=audio/x-mpg'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.mp2=audio/x-mpg'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.mp3=audio/x-mpg'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.mpga=audio/x-mpg'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.m3u=audio/x-mpegurl'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.pls=audio/x-scpls'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.qcp=audio/vnd.qcelp'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.ra=audio/x-realaudio'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.ram=audio/x-pn-realaudio'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.rm=audio/x-pn-realaudio'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.sd2=audio/x-sd2'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.sid=audio/prs.sid'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.snd=audio/basic'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.wav=audio/x-wav'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.wax=audio/x-ms-wax'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.wma=audio/x-ms-wma'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.mjf=audio/x-vnd.AudioExplosion.MjuiceMediaFile'); {Do not Localize}
{ Image }
AlMimeContentTypeByExtList.Add('.art=image/x-jg'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.bmp=image/bmp'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.cdr=image/x-coreldraw'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.cdt=image/x-coreldrawtemplate'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.cpt=image/x-corelphotopaint'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.djv=image/vnd.djvu'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.djvu=image/vnd.djvu'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.gif=image/gif'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.ief=image/ief'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.ico=image/x-icon'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.jng=image/x-jng'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.jpg=image/jpeg'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.jpeg=image/jpeg'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.jpe=image/jpeg'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.pat=image/x-coreldrawpattern'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.pcx=image/pcx'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.pbm=image/x-portable-bitmap'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.pgm=image/x-portable-graymap'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.pict=image/x-pict'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.png=image/x-png'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.pnm=image/x-portable-anymap'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.pntg=image/x-macpaint'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.ppm=image/x-portable-pixmap'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.psd=image/x-psd'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.qtif=image/x-quicktime'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.ras=image/x-cmu-raster'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.rf=image/vnd.rn-realflash'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.rgb=image/x-rgb'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.rp=image/vnd.rn-realpix'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.sgi=image/x-sgi'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.svg=image/svg+xml'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.svgz=image/svg+xml'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.targa=image/x-targa'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.tif=image/x-tiff'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.wbmp=image/vnd.wap.wbmp'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.webp=image/webp'); {Do not localize}
AlMimeContentTypeByExtList.Add('.xbm=image/xbm'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.xbm=image/x-xbitmap'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.xpm=image/x-xpixmap'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.xwd=image/x-xwindowdump'); {Do not Localize}
{ Text }
AlMimeContentTypeByExtList.Add('.323=text/h323'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.xml=text/xml'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.uls=text/iuls'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.txt=text/plain'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.rtx=text/richtext'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.wsc=text/scriptlet'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.rt=text/vnd.rn-realtext'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.htt=text/webviewhtml'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.htc=text/x-component'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.vcf=text/x-vcard'); {Do not Localize}
{ Video }
AlMimeContentTypeByExtList.Add('.asf=video/x-ms-asf'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.asx=video/x-ms-asf'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.avi=video/x-msvideo'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.dl=video/dl'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.dv=video/dv'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.flc=video/flc'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.fli=video/fli'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.gl=video/gl'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.lsf=video/x-la-asf'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.lsx=video/x-la-asf'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.mng=video/x-mng'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.mp2=video/mpeg'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.mp3=video/mpeg'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.mp4=video/mpeg'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.mpeg=video/x-mpeg2a'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.mpa=video/mpeg'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.mpe=video/mpeg'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.mpg=video/mpeg'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.ogv=video/ogg'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.moov=video/quicktime'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.mov=video/quicktime'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.mxu=video/vnd.mpegurl'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.qt=video/quicktime'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.qtc=video/x-qtc'); {Do not loccalize}
AlMimeContentTypeByExtList.Add('.rv=video/vnd.rn-realvideo'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.ivf=video/x-ivf'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.webm=video/webm'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.wm=video/x-ms-wm'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.wmp=video/x-ms-wmp'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.wmv=video/x-ms-wmv'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.wmx=video/x-ms-wmx'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.wvx=video/x-ms-wvx'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.rms=video/vnd.rn-realvideo-secure'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.asx=video/x-ms-asf-plugin'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.movie=video/x-sgi-movie'); {Do not Localize}
{ Application }
AlMimeContentTypeByExtList.Add('.7z=application/x-7z-compressed'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.a=application/x-archive'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.aab=application/x-authorware-bin'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.aam=application/x-authorware-map'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.aas=application/x-authorware-seg'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.abw=application/x-abiword'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.ace=application/x-ace-compressed'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.ai=application/postscript'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.alz=application/x-alz-compressed'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.ani=application/x-navi-animation'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.arj=application/x-arj'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.asf=application/vnd.ms-asf'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.bat=application/x-msdos-program'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.bcpio=application/x-bcpio'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.boz=application/x-bzip2'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.bz=application/x-bzip');
AlMimeContentTypeByExtList.Add('.bz2=application/x-bzip2'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.cab=application/vnd.ms-cab-compressed'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.cat=application/vnd.ms-pki.seccat'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.ccn=application/x-cnc'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.cco=application/x-cocoa'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.cdf=application/x-cdf'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.cer=application/x-x509-ca-cert'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.chm=application/vnd.ms-htmlhelp'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.chrt=application/vnd.kde.kchart'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.cil=application/vnd.ms-artgalry'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.class=application/java-vm'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.com=application/x-msdos-program'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.clp=application/x-msclip'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.cpio=application/x-cpio'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.cpt=application/mac-compactpro'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.cqk=application/x-calquick'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.crd=application/x-mscardfile'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.crl=application/pkix-crl'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.csh=application/x-csh'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.dar=application/x-dar'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.dbf=application/x-dbase'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.dcr=application/x-director'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.deb=application/x-debian-package'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.dir=application/x-director'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.dist=vnd.apple.installer+xml'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.distz=vnd.apple.installer+xml'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.dll=application/x-msdos-program'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.dmg=application/x-apple-diskimage'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.doc=application/msword'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.dot=application/msword'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.dvi=application/x-dvi'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.dxr=application/x-director'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.ebk=application/x-expandedbook'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.eps=application/postscript'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.evy=application/envoy'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.exe=application/x-msdos-program'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.fdf=application/vnd.fdf'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.fif=application/fractals'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.flm=application/vnd.kde.kivio'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.fml=application/x-file-mirror-list'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.gzip=application/x-gzip'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.gnumeric=application/x-gnumeric'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.gtar=application/x-gtar'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.gz=application/x-gzip'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.hdf=application/x-hdf'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.hlp=application/winhlp'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.hpf=application/x-icq-hpf'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.hqx=application/mac-binhex40'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.hta=application/hta'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.ims=application/vnd.ms-ims'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.ins=application/x-internet-signup'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.iii=application/x-iphone'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.iso=application/x-iso9660-image'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.jar=application/java-archive'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.karbon=application/vnd.kde.karbon'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.kfo=application/vnd.kde.kformula'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.kon=application/vnd.kde.kontour'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.kpr=application/vnd.kde.kpresenter'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.kpt=application/vnd.kde.kpresenter'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.kwd=application/vnd.kde.kword'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.kwt=application/vnd.kde.kword'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.latex=application/x-latex'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.lha=application/x-lzh'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.lcc=application/fastman'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.lrm=application/vnd.ms-lrm'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.lz=application/x-lzip'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.lzh=application/x-lzh'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.lzma=application/x-lzma'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.lzo=application/x-lzop'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.lzx=application/x-lzx');
AlMimeContentTypeByExtList.Add('.m13=application/x-msmediaview'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.m14=application/x-msmediaview'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.mpp=application/vnd.ms-project'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.mvb=application/x-msmediaview'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.man=application/x-troff-man'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.mdb=application/x-msaccess'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.me=application/x-troff-me'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.ms=application/x-troff-ms'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.msi=application/x-msi'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.mpkg=vnd.apple.installer+xml'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.mny=application/x-msmoney'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.nix=application/x-mix-transfer'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.o=application/x-object'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.oda=application/oda'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.odb=application/vnd.oasis.opendocument.database'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.odc=application/vnd.oasis.opendocument.chart'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.odf=application/vnd.oasis.opendocument.formula'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.odg=application/vnd.oasis.opendocument.graphics'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.odi=application/vnd.oasis.opendocument.image'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.odm=application/vnd.oasis.opendocument.text-master'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.odp=application/vnd.oasis.opendocument.presentation'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.ods=application/vnd.oasis.opendocument.spreadsheet'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.ogg=application/ogg'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.odt=application/vnd.oasis.opendocument.text'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.otg=application/vnd.oasis.opendocument.graphics-template'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.oth=application/vnd.oasis.opendocument.text-web'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.otp=application/vnd.oasis.opendocument.presentation-template'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.ots=application/vnd.oasis.opendocument.spreadsheet-template'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.ott=application/vnd.oasis.opendocument.text-template'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.p10=application/pkcs10'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.p12=application/x-pkcs12'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.p7b=application/x-pkcs7-certificates'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.p7m=application/pkcs7-mime'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.p7r=application/x-pkcs7-certreqresp'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.p7s=application/pkcs7-signature'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.package=application/vnd.autopackage'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.pfr=application/font-tdpfr'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.pkg=vnd.apple.installer+xml'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.pdf=application/pdf'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.pko=application/vnd.ms-pki.pko'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.pl=application/x-perl'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.pnq=application/x-icq-pnq'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.pot=application/mspowerpoint'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.pps=application/mspowerpoint'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.ppt=application/mspowerpoint'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.ppz=application/mspowerpoint'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.ps=application/postscript'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.pub=application/x-mspublisher'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.qpw=application/x-quattropro'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.qtl=application/x-quicktimeplayer'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.rar=application/rar'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.rdf=application/rdf+xml'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.rjs=application/vnd.rn-realsystem-rjs'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.rm=application/vnd.rn-realmedia'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.rmf=application/vnd.rmf'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.rmp=application/vnd.rn-rn_music_package'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.rmx=application/vnd.rn-realsystem-rmx'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.rnx=application/vnd.rn-realplayer'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.rpm=application/x-redhat-package-manager');
AlMimeContentTypeByExtList.Add('.rsml=application/vnd.rn-rsml'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.rtsp=application/x-rtsp'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.rss=application/rss+xml'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.scm=application/x-icq-scm'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.ser=application/java-serialized-object'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.scd=application/x-msschedule'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.sda=application/vnd.stardivision.draw'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.sdc=application/vnd.stardivision.calc'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.sdd=application/vnd.stardivision.impress'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.sdp=application/x-sdp'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.setpay=application/set-payment-initiation'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.setreg=application/set-registration-initiation'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.sh=application/x-sh'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.shar=application/x-shar'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.shw=application/presentations'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.sit=application/x-stuffit'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.sitx=application/x-stuffitx'); {Do not localize}
AlMimeContentTypeByExtList.Add('.skd=application/x-koan'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.skm=application/x-koan'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.skp=application/x-koan'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.skt=application/x-koan'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.smf=application/vnd.stardivision.math'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.smi=application/smil'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.smil=application/smil'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.spl=application/futuresplash'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.ssm=application/streamingmedia'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.sst=application/vnd.ms-pki.certstore'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.stc=application/vnd.sun.xml.calc.template'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.std=application/vnd.sun.xml.draw.template'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.sti=application/vnd.sun.xml.impress.template'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.stl=application/vnd.ms-pki.stl'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.stw=application/vnd.sun.xml.writer.template'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.svi=application/softvision'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.sv4cpio=application/x-sv4cpio'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.sv4crc=application/x-sv4crc'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.swf=application/x-shockwave-flash'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.swf1=application/x-shockwave-flash'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.sxc=application/vnd.sun.xml.calc'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.sxi=application/vnd.sun.xml.impress'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.sxm=application/vnd.sun.xml.math'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.sxw=application/vnd.sun.xml.writer'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.sxg=application/vnd.sun.xml.writer.global'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.t=application/x-troff'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.tar=application/x-tar'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.tcl=application/x-tcl'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.tex=application/x-tex'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.texi=application/x-texinfo'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.texinfo=application/x-texinfo'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.tbz=application/x-bzip-compressed-tar'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.tbz2=application/x-bzip-compressed-tar'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.tgz=application/x-compressed-tar'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.tlz=application/x-lzma-compressed-tar'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.tr=application/x-troff'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.trm=application/x-msterminal'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.troff=application/x-troff'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.tsp=application/dsptype'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.torrent=application/x-bittorrent'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.ttz=application/t-time'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.txz=application/x-xz-compressed-tar'); {Do not localize}
AlMimeContentTypeByExtList.Add('.udeb=application/x-debian-package'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.uin=application/x-icq'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.urls=application/x-url-list'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.ustar=application/x-ustar'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.vcd=application/x-cdlink'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.vor=application/vnd.stardivision.writer'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.vsl=application/x-cnet-vsl'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.wcm=application/vnd.ms-works'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.wb1=application/x-quattropro'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.wb2=application/x-quattropro'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.wb3=application/x-quattropro'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.wdb=application/vnd.ms-works'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.wks=application/vnd.ms-works'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.wmd=application/x-ms-wmd'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.wms=application/x-ms-wms'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.wmz=application/x-ms-wmz'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.wp5=application/wordperfect5.1'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.wpd=application/wordperfect'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.wpl=application/vnd.ms-wpl'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.wps=application/vnd.ms-works'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.wri=application/x-mswrite'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.xfdf=application/vnd.adobe.xfdf'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.xls=application/x-msexcel'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.xlb=application/x-msexcel'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.xpi=application/x-xpinstall'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.xps=application/vnd.ms-xpsdocument'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.xsd=application/vnd.sun.xml.draw'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.xul=application/vnd.mozilla.xul+xml'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.z=application/x-compress'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.zoo=application/x-zoo'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.zip=application/x-zip-compressed'); {Do not Localize}
{ WAP }
AlMimeContentTypeByExtList.Add('.wbmp=image/vnd.wap.wbmp'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.wml=text/vnd.wap.wml'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.wmlc=application/vnd.wap.wmlc'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.wmls=text/vnd.wap.wmlscript'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.wmlsc=application/vnd.wap.wmlscriptc'); {Do not Localize}
{ Non-web text}
{
IMPORTANT!!
You should not use a text MIME type definition unless you are
extremely certain that the file will NOT be a binary. Some browsers
will display the text instead of saving to disk and it looks ugly
if a web-browser shows all of the 8bit charactors.
}
//of course, we have to add this :-).
AlMimeContentTypeByExtList.Add('.asm=text/x-asm'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.p=text/x-pascal'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.pas=text/x-pascal'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.cs=text/x-csharp'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.c=text/x-csrc'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.c++=text/x-c++src'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.cpp=text/x-c++src'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.cxx=text/x-c++src'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.cc=text/x-c++src'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.h=text/x-chdr'); {Do not localize}
AlMimeContentTypeByExtList.Add('.h++=text/x-c++hdr'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.hpp=text/x-c++hdr'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.hxx=text/x-c++hdr'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.hh=text/x-c++hdr'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.java=text/x-java'); {Do not Localize}
{ WEB }
AlMimeContentTypeByExtList.Add('.css=text/css'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.js=text/javascript'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.htm=text/html'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.html=text/html'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.xhtml=application/xhtml+xml'); {Do not localize}
AlMimeContentTypeByExtList.Add('.xht=application/xhtml+xml'); {Do not localize}
AlMimeContentTypeByExtList.Add('.rdf=application/rdf+xml'); {Do not localize}
AlMimeContentTypeByExtList.Add('.rss=application/rss+xml'); {Do not localize}
AlMimeContentTypeByExtList.Add('.ls=text/javascript'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.mocha=text/javascript'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.shtml=server-parsed-html'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.xml=text/xml'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.sgm=text/sgml'); {Do not Localize}
AlMimeContentTypeByExtList.Add('.sgml=text/sgml'); {Do not Localize}
{ Message }
AlMimeContentTypeByExtList.Add('.mht=message/rfc822'); {Do not Localize}
for I := 0 to AlMimeContentTypeByExtList.Count - 1 do
AlExtbyMimeContentTypeList.Add(AlMimeContentTypeByExtList.ValueFromIndex[I] + '=' + AlMimeContentTypeByExtList.Names[I]);
end;
Initialization
AlMimeContentTypeByExtList := TALNVStringListA.Create;
AlExtbyMimeContentTypeList := TALNVStringListA.Create;
ALFillMimeTable;
TALNVStringListA(AlMimeContentTypeByExtList).Duplicates := dupAccept;
TALNVStringListA(AlMimeContentTypeByExtList).Sorted := true;
TALNVStringListA(AlExtbyMimeContentTypeList).Duplicates := dupAccept;
TALNVStringListA(AlExtbyMimeContentTypeList).Sorted := true;
finalization
AlFreeandNil(AlMimeContentTypeByExtList);
AlFreeandNil(AlExtbyMimeContentTypeList);
end.
|
unit tiBOMExploration;
{
These classes describe and manage the information required by the
BOM Explorer (BOME) to explore a tree of BOM objects.
The BOMEDictionary is a singleton containing a list of registered ExplorableBOMs.
An ExplorableBOM is a name associated with one or more 'Aliases', 'Registrars',
'Views' and 'ViewPoints'.
An Alias is the set of information required to connect to a database.
A BOMRegistrar is responsible for registering automaps or visitors.
A BOMEView is a set of all the class-related information required to explore
a tree of objects instantiated from a particular BOM.
A BOMEViewPoint is a named root to start exploring from.
}
interface
uses
Classes
, tiObject
, tiVTTreeView;
type
TtiRegistrarKind = (rkNone, rkAutoMap, rkDBIndependant, rkHardCode, rkOther);
TtiBOMEViewPoint = class;
TtiBOMEViewPointList = class;
TtiBOMEView = class;
TtiBOMEViewList = class;
TtiBOMERegistrar = class;
TtiBOMERegistrarList = class;
TtiAlias = class;
TtiAliasList = class;
TtiExplorableBOM = class;
TtiExplorableBOMList = class;
TtiBOMEDictionary = class(TtiObject)
private
FBOMs: TtiExplorableBOMList;
public
constructor Create; override;
destructor Destroy; override;
published
property BOMs: TtiExplorableBOMList read FBOMs;
end;
TtiExplorableBOMList = class(TtiObjectList)
private
protected
function GetItems(I: Integer): TtiExplorableBOM; reintroduce;
procedure SetItems(I: Integer; const AValue: TtiExplorableBOM); reintroduce;
function GetOwner: TtiBOMEDictionary; reintroduce;
procedure SetOwner(const AValue: TtiBOMEDictionary); reintroduce;
public
property Items[I: Integer]: TtiExplorableBOM read GetItems write SetItems; default;
procedure Add(const AObject: TtiExplorableBOM); reintroduce; overload;
function Add: TtiExplorableBOM; overload;
property Owner: TtiBOMEDictionary read GetOwner write SetOwner;
published
end;
TtiExplorableBOM = class(TtiObject)
private
FAliases: TtiAliasList;
FRegistrars: TtiBOMERegistrarList;
FViews: TtiBOMEViewList;
FName: String;
FViewPoints: TtiBOMEViewPointList;
public
function AddAlias(const AName, APerLayerName, ADatabaseName: String;
const AUserName: String = ''; const APassword: String = '';
AParams: String = ''): TtiAlias;
constructor Create; override;
destructor Destroy; override;
published
property Aliases: TtiAliasList read FAliases;
property Registrars: TtiBOMERegistrarList read FRegistrars;
property Views: TtiBOMEViewList read FViews;
property ViewPoints: TtiBOMEViewPointList read FViewPoints;
property Name: String read FName write FName;
end;
TtiAliasList = class(TtiObjectList)
private
protected
function GetItems(I: Integer): TtiAlias; reintroduce;
procedure SetItems(I: Integer; const AValue: TtiAlias); reintroduce;
function GetOwner: TtiExplorableBOM; reintroduce;
procedure SetOwner(const AValue: TtiExplorableBOM); reintroduce;
public
property Items[I: Integer]: TtiAlias read GetItems write SetItems; default;
procedure Add(const AObject: TtiAlias); reintroduce; overload;
function Add: TtiAlias; overload;
property Owner: TtiExplorableBOM read GetOwner write SetOwner;
published
end;
TtiAlias = class(TtiObject)
private
FName: String;
FPerLayerName: String;
FDatabaseName: String;
FPassword: String;
FUserName: String;
FParams: String;
protected
function GetOwner: TtiAliasList; reintroduce;
procedure SetOwner(const AValue: TtiAliasList); reintroduce;
public
constructor Create; override;
property Owner: TtiAliasList read GetOwner write SetOwner;
published
property Name: String read FName write FName;
property DatabaseName: String read FDatabaseName write FDatabaseName;
property PerLayerName: String read FPerLayerName write FPerLayerName;
property UserName: String read FUserName write FUserName;
property Password: String read FPassword write FPassword;
property Params: String read FParams write FParams;
end;
TtiBOMERegistrarList = class(TtiObjectList)
private
protected
function GetItems(I: Integer): TtiBOMERegistrar; reintroduce;
procedure SetItems(I: Integer; const AValue: TtiBOMERegistrar); reintroduce;
function GetOwner: TtiExplorableBOM; reintroduce;
procedure SetOwner(const AValue: TtiExplorableBOM); reintroduce;
public
property Items[I: Integer]: TtiBOMERegistrar read GetItems write SetItems; default;
procedure Add(const AObject: TtiBOMERegistrar); reintroduce; overload;
function Add: TtiBOMERegistrar; overload;
property Owner: TtiExplorableBOM read GetOwner write SetOwner;
published
end;
TtiBOMERegistrar = class(TtiObject)
private
FName: String;
FKind: TtiRegistrarKind;
FRegistered: Boolean;
protected
function GetOwner: TtiBOMERegistrarList; reintroduce;
procedure SetOwner(const AValue: TtiBOMERegistrarList); reintroduce;
procedure DoRegisterItems; virtual;
procedure DoUnregisterItems; virtual;
public
constructor Create; override;
procedure RegisterItems;
procedure UnregisterItems;
property Owner: TtiBOMERegistrarList read GetOwner write SetOwner;
published
property Kind: TtiRegistrarKind read FKind write FKind default rkNone;
property Name: String read FName write FName;
property Registered: Boolean read FRegistered;
end;
TtiBOMEAutomapRegistrar = class(TtiBOMERegistrar)
protected
procedure DoUnregisterItems; override;
public
constructor Create; override;
end;
TtiBOMEVisitorRegistrar = class(TtiBOMERegistrar)
protected
procedure DoUnregisterItems; override;
end;
TtiBOMEDBIndependantRegistrar = class(TtiBOMEVisitorRegistrar)
public
constructor Create; override;
end;
TtiBOMEHardCodeRegistrar = class(TtiBOMEVisitorRegistrar)
public
constructor Create; override;
end;
TtiBOMEViewList = class(TtiObjectList)
private
protected
function GetItems(I: Integer): TtiBOMEView; reintroduce;
procedure SetItems(I: Integer; const AValue: TtiBOMEView); reintroduce;
function GetOwner: TtiExplorableBOM; reintroduce;
procedure SetOwner(const AValue: TtiExplorableBOM); reintroduce;
public
property Items[I: Integer]: TtiBOMEView read GetItems write SetItems; default;
procedure Add(const AObject: TtiBOMEView); reintroduce; overload;
function Add: TtiBOMEView; overload;
property Owner: TtiExplorableBOM read GetOwner write SetOwner;
published
end;
TtiBOMEView = class(TtiObject)
private
FName: String;
FTreeMappings: TtiVTTVDataMappings;
protected
function GetOwner: TtiBOMEViewList; reintroduce;
procedure SetOwner(const AValue: TtiBOMEViewList); reintroduce;
public
function AddTreeMapping(AClass: TtiClass;
ACanEdit: Boolean = False;
AOnInsert: TtiVTTVNodeEvent = nil;
AOnDelete: TtiVTTVNodeEvent = nil;
const APropertyName: String = 'Caption'): TtiVTTVDataMapping;
constructor Create; override;
destructor Destroy; override;
property Owner: TtiBOMEViewList read GetOwner write SetOwner;
published
property TreeMappings: TtiVTTVDataMappings read FTreeMappings;
property Name: String read FName write FName;
end;
TtiBOMEViewPointList = class(TtiObjectList)
private
protected
function GetItems(I: Integer): TtiBOMEViewPoint; reintroduce;
procedure SetItems(I: Integer; const AValue: TtiBOMEViewPoint); reintroduce;
function GetOwner: TtiBOMEView; reintroduce;
procedure SetOwner(const AValue: TtiBOMEView); reintroduce;
public
property Items[I: Integer]: TtiBOMEViewPoint read GetItems write SetItems; default;
procedure Add(const AObject: TtiBOMEViewPoint); reintroduce; overload;
function Add: TtiBOMEViewPoint; overload;
function Add(const AName: String; ARoot: TtiObject): TtiBOMEViewPoint; overload;
property Owner: TtiBOMEView read GetOwner write SetOwner;
published
end;
TtiBOMEViewPoint = class(TtiObject)
private
FName: String;
FRoot: TtiObject;
public
constructor Create; override;
published
property Name: String read FName write FName;
property Root: TtiObject read FRoot write FRoot;
end;
function BOMEDictionary: TtiBOMEDictionary;
implementation
uses
tiOPFManager;
var
uBOMEDictionary: TtiBOMEDictionary;
function BOMEDictionary: TtiBOMEDictionary;
begin
Result := uBOMEDictionary;
end;
{ TtiBOMEDictionary }
constructor TtiBOMEDictionary.Create;
begin
inherited;
FBOMs := TtiExplorableBOMList.Create;
end;
destructor TtiBOMEDictionary.Destroy;
begin
FBOMs.Free;
inherited;
end;
{ TtiExplorableBOMList }
procedure TtiExplorableBOMList.Add(const AObject: TtiExplorableBOM);
begin
inherited Add(AObject);
end;
function TtiExplorableBOMList.Add: TtiExplorableBOM;
begin
Result := TtiExplorableBOM.Create;
Add(Result);
end;
function TtiExplorableBOMList.GetItems(I: Integer): TtiExplorableBOM;
begin
Result := TtiExplorableBOM(inherited GetItems(I));
end;
function TtiExplorableBOMList.GetOwner: TtiBOMEDictionary;
begin
Result := TtiBOMEDictionary(inherited GetOwner);
end;
procedure TtiExplorableBOMList.SetItems(I: Integer; const AValue: TtiExplorableBOM);
begin
inherited SetItems(I, AValue);
end;
procedure TtiExplorableBOMList.SetOwner(const AValue: TtiBOMEDictionary);
begin
inherited SetOwner(AValue);
end;
{ TtiExploreableBOM }
function TtiExplorableBOM.AddAlias(const AName, APerLayerName,
ADatabaseName, AUserName, APassword: String; AParams: String): TtiAlias;
begin
Result := Aliases.Add;
Result.Name := AName;
Result.PerLayerName := APerLayerName;
Result.DatabaseName := ADatabaseName;
Result.UserName := AUserName;
Result.Password := APassword;
Result.Params := AParams;
end;
constructor TtiExplorableBOM.Create;
begin
inherited;
FAliases := TtiAliasList.Create;
FRegistrars := TtiBOMERegistrarList.Create;
FViews := TtiBOMEViewList.Create;
FViewPoints := TtiBOMEViewPointList.Create;
FName := '';
end;
destructor TtiExplorableBOM.Destroy;
begin
FAliases.Free;
FRegistrars.Free;
FViews.Free;
FViewPoints.Free;
inherited;
end;
{ TtiAliasList }
procedure TtiAliasList.Add(const AObject: TtiAlias);
begin
inherited Add(AObject);
end;
function TtiAliasList.Add: TtiAlias;
begin
Result := TtiAlias.Create;
Add(Result);
end;
function TtiAliasList.GetItems(I: Integer): TtiAlias;
begin
Result := TtiAlias(inherited GetItems(I));
end;
function TtiAliasList.GetOwner: TtiExplorableBOM;
begin
Result := TtiExplorableBOM(inherited GetOwner);
end;
procedure TtiAliasList.SetItems(I: Integer; const AValue: TtiAlias);
begin
inherited SetItems(I, AValue);
end;
procedure TtiAliasList.SetOwner(const AValue: TtiExplorableBOM);
begin
inherited SetOwner(AValue);
end;
{ TtiAlias }
constructor TtiAlias.Create;
begin
inherited;
FParams := '';
FName := '';
FPerLayerName := '';
FDatabaseName := '';
FPassword := '';
FUserName := '';
end;
function TtiAlias.GetOwner: TtiAliasList;
begin
Result := TtiAliasList(inherited GetOwner);
end;
procedure TtiAlias.SetOwner(const AValue: TtiAliasList);
begin
inherited SetOwner(AValue);
end;
{ TiBOMERegistrarList }
procedure TtiBOMERegistrarList.Add(const AObject: TtiBOMERegistrar);
begin
inherited Add(AObject);
end;
function TtiBOMERegistrarList.Add: TtiBOMERegistrar;
begin
Result := TtiBOMERegistrar.Create;
Add(Result);
end;
function TtiBOMERegistrarList.GetItems(I: Integer): TtiBOMERegistrar;
begin
Result := TtiBOMERegistrar(inherited GetItems(I));
end;
function TtiBOMERegistrarList.GetOwner: TtiExplorableBOM;
begin
Result := TtiExplorableBOM(inherited GetOwner);
end;
procedure TtiBOMERegistrarList.SetItems(I: Integer; const AValue: TtiBOMERegistrar);
begin
inherited SetItems(I, AValue);
end;
procedure TtiBOMERegistrarList.SetOwner(const AValue: TtiExplorableBOM);
begin
inherited SetOwner(AValue);
end;
{ TtiBOMERegistrar }
constructor TtiBOMERegistrar.Create;
begin
inherited;
FName := '';
FKind := rkNone;
FRegistered := False;
end;
procedure TtiBOMERegistrar.DoRegisterItems;
begin
FRegistered := True;
end;
procedure TtiBOMERegistrar.DoUnregisterItems;
begin
FRegistered := False;
end;
function TtiBOMERegistrar.GetOwner: TtiBOMERegistrarList;
begin
Result := TtiBOMERegistrarList(inherited GetOwner);
end;
procedure TtiBOMERegistrar.RegisterItems;
begin
if Registered then
Exit;
DoRegisterItems;
end;
procedure TtiBOMERegistrar.SetOwner(const AValue: TtiBOMERegistrarList);
begin
inherited SetOwner(AValue);
end;
procedure TtiBOMERegistrar.UnregisterItems;
begin
if not Registered then
Exit;
DoUnregisterItems;
end;
{ TtiAutomapRegistrar }
constructor TtiBOMEAutomapRegistrar.Create;
begin
inherited;
FKind := rkAutomap;
end;
{ TtiDBIndependent }
constructor TtiBOMEDBIndependantRegistrar.Create;
begin
inherited;
FKind := rkDBIndependant;
end;
procedure TtiBOMEAutomapRegistrar.DoUnregisterItems;
begin
FRegistered := True; //remains true since AutoMaps can't be unregistered in tiOPF
end;
{ TtiHardCodeRegistrar }
constructor TtiBOMEHardCodeRegistrar.Create;
begin
inherited;
FKind := rkHardCode;
end;
{ TtiBOMEViewList }
procedure TtiBOMEViewList.Add(const AObject: TtiBOMEView);
begin
inherited Add(AObject);
end;
function TtiBOMEViewList.Add: TtiBOMEView;
begin
Result := TtiBOMEView.Create;
Add(Result);
end;
function TtiBOMEViewList.GetItems(I: Integer): TtiBOMEView;
begin
Result := TtiBOMEView(inherited GetItems(I));
end;
function TtiBOMEViewList.GetOwner: TtiExplorableBOM;
begin
Result := TtiExplorableBOM(inherited GetOwner);
end;
procedure TtiBOMEViewList.SetItems(I: Integer; const AValue: TtiBOMEView);
begin
inherited SetItems(I, AValue);
end;
procedure TtiBOMEViewList.SetOwner(const AValue: TtiExplorableBOM);
begin
inherited SetOwner(AValue);
end;
{ TtiBOMEView }
function TtiBOMEView.AddTreeMapping(AClass: TtiClass;
ACanEdit: Boolean;
AOnInsert, AOnDelete: TtiVTTVNodeEvent;
const APropertyName: String): TtiVTTVDataMapping;
begin
Result := FTreeMappings.Add;
Result.DataClass := AClass;
Result.DisplayPropName := APropertyName;
Result.CanInsert := Assigned(AOnInsert);
Result.CanDelete := Assigned(AOnDelete);
Result.OnInsert := AOnInsert;
Result.OnDelete := AOnDelete;
Result.CanView := True;
Result.CanEdit := ACanEdit;
end;
constructor TtiBOMEView.Create;
begin
inherited;
FTreeMappings := TtiVTTVDataMappings.Create(nil);
FName := '';
end;
destructor TtiBOMEView.Destroy;
begin
FTreeMappings.Free;
inherited;
end;
function TtiBOMEView.GetOwner: TtiBOMEViewList;
begin
Result := TtiBOMEViewList(inherited GetOwner);
end;
procedure TtiBOMEView.SetOwner(const AValue: TtiBOMEViewList);
begin
inherited SetOwner(AValue);
end;
{ TtiBOMEViewPointList }
procedure TtiBOMEViewPointList.Add(const AObject: TtiBOMEViewPoint);
begin
inherited Add(AObject);
end;
function TtiBOMEViewPointList.Add: TtiBOMEViewPoint;
begin
Result := TtiBOMEViewPoint.Create;
Add(Result);
end;
function TtiBOMEViewPointList.Add(const AName: String;
ARoot: TtiObject): TtiBOMEViewPoint;
begin
Result := Add;
Result.Name := AName;
Result.Root := ARoot;
end;
function TtiBOMEViewPointList.GetItems(I: Integer): TtiBOMEViewPoint;
begin
Result := TtiBOMEViewPoint(inherited GetItems(I));
end;
function TtiBOMEViewPointList.GetOwner: TtiBOMEView;
begin
Result := TtiBOMEView(inherited GetOwner);
end;
procedure TtiBOMEViewPointList.SetItems(I: Integer; const AValue: TtiBOMEViewPoint);
begin
inherited SetItems(I, AValue);
end;
procedure TtiBOMEViewPointList.SetOwner(const AValue: TtiBOMEView);
begin
inherited SetOwner(AValue);
end;
{ TtiBOMEViewPoint }
constructor TtiBOMEViewPoint.Create;
begin
inherited;
FName := '';
end;
{ TtiVisitorRegistrar }
procedure TtiBOMEVisitorRegistrar.DoUnregisterItems;
begin
inherited;
{GOTCHA: tiOPF doesn't allow us to UnRegister individual visitors,
only groups of visitors. Thus, we will unregister all 'read' and 'save'
visitors, which should achieve the same results}
{PH: Reasonable to add this functionality if required.}
gTIOPFManager.VisitorManager.UnregisterVisitors(cuStandardTask_Read);
gTIOPFManager.VisitorManager.UnregisterVisitors(cuStandardTask_Save);
end;
initialization
uBOMEDictionary := TtiBOMEDictionary.Create;
finalization
uBOMEDictionary.Free;
end.
|
unit uMaquina;
interface
uses
uIMaquina, Classes, uTroco;
type
TMaquina = class(TInterfacedObject, IMaquina)
public
function MontarTroco(aTroco: Double): TList;
end;
implementation
function TMaquina.MontarTroco(aTroco: Double): TList;
var
FCedulas: TList;
FCedula: TCedula;
aQuantidade: Integer;
begin
FCedulas := TList.Create;
for FCedula := Low(CValorCedula) to High(CValorCedula) do
begin
if aTroco >= CValorCedula[FCedula] then
begin
aQuantidade := Trunc(aTroco / CValorCedula[FCedula]);
aTroco := aTroco - (CValorCedula[FCedula] * aQuantidade);
FCedulas.Add(TTroco.Create(FCedula, aQuantidade));
end;
end;
Result := FCedulas;
end;
end.
|
unit SimpleGauge;
interface
uses
{$IFDEF MSWINDOWS}
VCL.Controls, VCL.Forms, Vcl.ComCtrls,
{$ELSE}
FMX.Controls, FMX.Forms, FMX.StdCtrls, System.UITypes,
{$ENDIF}
System.Classes;
type
IGauge = interface(IDispatch)
procedure IncProgress(IncValue: integer = 1);
procedure Start;
procedure Finish;
end;
TGaugeFactory = class
class function GetGauge(in_stCaption: string; AMinValue, AMaxValue: integer): IGauge;
end;
TSimpleGaugeForm = class(TForm, IGauge)
Gauge: TProgressBar;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
protected
procedure Start;
procedure Finish;
procedure IncProgress(IncValue: integer = 1);
public
constructor Create(AOwner: TForm; ACaption: string; AMinValue, AMaxValue: integer); reintroduce; virtual;
end;
implementation
{$R *.DFM}
constructor TSimpleGaugeForm.Create(AOwner: TForm; ACaption: string; AMinValue, AMaxValue: integer);
begin
inherited Create(AOwner);
Caption := ACaption;
with Gauge do
begin
{$IFDEF MSWINDOWS}
Position := AMinValue;
{$ELSE}
Value := AMinValue;
{$ENDIF}
Min := AMinValue;
if AMaxValue < AMinValue then
Max := AMinValue
else
Max := AMaxValue;
end;
end;
procedure TSimpleGaugeForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
inherited;
Action := TCloseAction.caFree;
end;
procedure TSimpleGaugeForm.Finish;
begin
Close;
end;
procedure TSimpleGaugeForm.Start;
begin
Show;
{$IFDEF MSWINDOWS}
Gauge.Position := Gauge.Min;
{$ELSE}
Gauge.Value := Gauge.Min;
{$ENDIF}
end;
{ TGaugeFactory }
class function TGaugeFactory.GetGauge(in_stCaption: string; AMinValue, AMaxValue: integer): IGauge;
begin
result := TSimpleGaugeForm.Create(nil, in_stCaption, AMinValue, AMaxValue);
end;
procedure TSimpleGaugeForm.IncProgress(IncValue: integer);
begin
{$IFDEF MSWINDOWS}
Gauge.Position := Gauge.Position + IncValue;
{$ELSE}
Gauge.Value := Gauge.Value + IncValue;
{$ENDIF}
Application.ProcessMessages;
end;
end.
|
{$IFDEF FREEPASCAL}
{$MODE DELPHI}
{$ENDIF}
unit dll_winmm_joy;
interface
uses
atmcmbaseconst, winconst, wintype, dll_winmm;
type
PJoyCapsA = ^TJoyCapsA;
PJoyCaps = PJoyCapsA;
TJoyCapsA = record
wMid: Word; { manufacturer ID }
wPid: Word; { product ID }
szPname: array[0..MAXPNAMELEN-1] of AnsiChar; { product name (NULL terminated AnsiString) }
wXmin: UINT; { minimum x position value }
wXmax: UINT; { maximum x position value }
wYmin: UINT; { minimum y position value }
wYmax: UINT; { maximum y position value }
wZmin: UINT; { minimum z position value }
wZmax: UINT; { maximum z position value }
wNumButtons: UINT; { number of buttons }
wPeriodMin: UINT; { minimum message period when captured }
wPeriodMax: UINT; { maximum message period when captured }
wRmin: UINT; { minimum r position value }
wRmax: UINT; { maximum r position value }
wUmin: UINT; { minimum u (5th axis) position value }
wUmax: UINT; { maximum u (5th axis) position value }
wVmin: UINT; { minimum v (6th axis) position value }
wVmax: UINT; { maximum v (6th axis) position value }
wCaps: UINT; { joystick capabilites }
wMaxAxes: UINT; { maximum number of axes supported }
wNumAxes: UINT; { number of axes in use }
wMaxButtons: UINT; { maximum number of buttons supported }
szRegKey: array[0..MAXPNAMELEN - 1] of AnsiChar; { registry key }
szOEMVxD: array[0..MAX_JOYSTICKOEMVXDNAME - 1] of AnsiChar; { OEM VxD in use }
end;
TJoyCaps = TJoyCapsA;
PJoyInfo = ^TJoyInfo;
TJoyInfo = record
wXpos: UINT; { x position }
wYpos: UINT; { y position }
wZpos: UINT; { z position }
wButtons: UINT; { button states }
end;
PJoyInfoEx = ^TJoyInfoEx;
TJoyInfoEx = record
dwSize: DWORD; { size of structure }
dwFlags: DWORD; { flags to indicate what to return }
wXpos: UINT; { x position }
wYpos: UINT; { y position }
wZpos: UINT; { z position }
dwRpos: DWORD; { rudder/4th axis position }
dwUpos: DWORD; { 5th axis position }
dwVpos: DWORD; { 6th axis position }
wButtons: UINT; { button states }
dwButtonNumber: DWORD; { current button number pressed }
dwPOV: DWORD; { point of view state }
dwReserved1: DWORD; { reserved for communication between winmm & driver }
dwReserved2: DWORD; { reserved for future expansion }
end;
function joyGetDevCaps(uJoyID: UINT; lpCaps: PJoyCaps; uSize: UINT): MMRESULT; stdcall; external winmm name 'joyGetDevCapsA';
function joyGetNumDevs: UINT; stdcall; external winmm name 'joyGetNumDevs';
function joyGetPos(uJoyID: UINT; lpInfo: PJoyInfo): MMRESULT; stdcall; external winmm name 'joyGetPos';
function joyGetPosEx(uJoyID: UINT; lpInfo: PJoyInfoEx): MMRESULT; stdcall; external winmm name 'joyGetPosEx';
function joyGetThreshold(uJoyID: UINT; lpuThreshold: PUINT): MMRESULT; stdcall; external winmm name 'joyGetThreshold';
function joyReleaseCapture(uJoyID: UINT): MMRESULT; stdcall; external winmm name 'joyReleaseCapture';
function joySetCapture(Handle: HWND; uJoyID, uPeriod: UINT; bChanged: BOOL): MMRESULT; stdcall; external winmm name 'joySetCapture';
function joySetThreshold(uJoyID, uThreshold: UINT): MMRESULT; stdcall; external winmm name 'joySetThreshold';
function joyConfigChanged(dwFlags : LongWord) : MMRESULT; external winmm;
implementation
end.
|
unit DIOTA.Dto.Response.AttachToTangleResponse;
interface
uses
System.Classes,
DIOTA.IotaAPIClasses;
type
TAttachToTangleResponse = class(TIotaAPIResponse)
private
FTrytes: TArray<String>;
function GetTrytes(Index: Integer): String;
function GetTrytesCount: Integer;
public
constructor Create(ATrytes: TArray<String>); reintroduce; virtual;
function TrytesList: TStringList;
property TrytesCount: Integer read GetTrytesCount;
property Trytes[Index: Integer]: String read GetTrytes;
end;
implementation
{ TAttachToTangleResponse }
constructor TAttachToTangleResponse.Create(ATrytes: TArray<String>);
begin
inherited Create;
FTrytes := ATrytes;
end;
function TAttachToTangleResponse.GetTrytes(Index: Integer): String;
begin
Result := FTrytes[Index];
end;
function TAttachToTangleResponse.GetTrytesCount: Integer;
begin
Result := Length(FTrytes);
end;
function TAttachToTangleResponse.TrytesList: TStringList;
var
ATryte: String;
begin
Result := TStringList.Create;
for ATryte in FTrytes do
Result.Add(ATryte);
end;
end.
|
{*****************************************************************************
* The contents of this file are used with permission, subject to
* the Mozilla Public License Version 1.1 (the "License"); you may
* not use this file except in compliance with the License. You may
* obtain a copy of the License at
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* Software distributed under the License is distributed on an
* "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
*****************************************************************************
*
* This file was created by Mason Wheeler. He can be reached for support at
* tech.turbu-rpg.com.
*****************************************************************************}
unit rsImport;
interface
uses
RTTI, TypInfo,
rsDefs, rsDefsBackend;
type
TTypeLookupFunc = reference to function(base: TRttiType): TTypeSymbol;
TTypeRegisterProc = reference to procedure(value: TRttiType);
TParseHeaderFunc = reference to function(const header: string;
parent: TUnitSymbol; add: boolean): TProcSymbol;
NoImportAttribute = rsDefsBackend.NoImportAttribute;
IExternalType = interface
['{D1A64764-87B2-48EF-B2FC-641D31C3856A}']
function GetInfo: TRttiType;
end;
TExternalType = class(TTypeSymbol, IExternalType)
private
FInfo: TRttiType;
function GetInfo: TRttiType;
protected
function GetTypeInfo: PTypeInfo; override;
public
constructor Create(info: TRttiType);
end;
TExternalArrayType = class(TArrayTypeSymbol, IExternalType)
private
FInfo: TRttiType;
function GetInfo: TRttiType;
protected
function GetTypeInfo: PTypeInfo; override;
public
constructor Create(info: TRttiType);
function CanDerefArray: boolean; override;
end;
TExternalClassType = class(TClassTypeSymbol, IExternalType)
private
FInfo: TRttiType;
function GetInfo: TRttiType;
protected
function GetTypeInfo: PTypeInfo; override;
public
constructor Create(info: TRttiInstanceType); overload;
constructor Create(info: TRttiInstanceType; LookupType: TTypeLookupFunc;
ParseHeader: TParseHeaderFunc; AddType: TTypeRegisterProc; parent: TUnitSymbol;
baseType: TClassTypeSymbol); overload;
procedure AddArrayProp(const name, indexType, propType: string;
canRead, canWrite: boolean; default: boolean = false);
end;
implementation
uses
SysUtils;
{ TExternalType }
constructor TExternalType.Create(info: TRttiType);
begin
assert(assigned(info));
inherited Create(info.Name);
FInfo := info;
end;
function TExternalType.GetInfo: TRttiType;
begin
result := FInfo;
end;
function TExternalType.GetTypeInfo: PTypeInfo;
begin
result := FInfo.Handle;
end;
{ TExternalClassType }
constructor TExternalClassType.Create(info: TRttiInstanceType);
var
base: TClassTypeSymbol;
begin
assert(assigned(info));
inherited Create(info.Name);
self.metaclass := info.MetaclassType;
FInfo := info;
FFieldCount := (length(info.GetFields));
if NativeTypeDefined(info.BaseType) then
begin
base := TypeOfRttiType(info.BaseType) as TClassTypeSymbol;
FMethodCount := base.methodCount;
FPropCount := base.propCount;
end;
end;
procedure TExternalClassType.AddArrayProp(const name, indexType, propType: string;
canRead, canWrite, default: boolean);
var
list: IParamList;
propTypeSym, indexTypeSym: TTypeSymbol;
readSpec, writeSpec: TSymbol;
begin
if not (canRead or canWrite) then
raise EParseError.CreateFmt('Array property "%s.%s%" must be readable or writable.', [self.name, name]);
if default and assigned(FDefaultProperty) then
raise EParseError.CreateFmt('Class %s already has a default property.', [self.name]);
propTypeSym := FindNativeType(propType);
indexTypeSym := FindNativeType(indexType);
if canRead then
begin
list := EmptyParamList;
list.Add(TParamSymbol.Create('index', indexTypeSym, [pfConst]));
AddMethod(format('Get*%s', [name]), propTypeSym, mvPrivate, false, list);
readSpec := self.SymbolLookup(UpperCase(format('Get*%s', [name])));
end
else readSPec := nil;
if canWrite then
begin
list := EmptyParamList;
list.Add(TParamSymbol.Create('index', indexTypeSym, [pfConst]));
list.Add(TParamSymbol.Create('value', propTypeSym, [pfConst]));
AddMethod(format('Set*%s', [name]), nil, mvPrivate, false, list);
writeSpec := self.SymbolLookup(UpperCase(format('Set*%s', [name])));
end
else writeSpec := nil;
list := EmptyParamList;
list.Add(TParamSymbol.Create('index', indexTypeSym, [pfConst]));
propTypeSym := MakeArrayPropType(propTypeSym);
AddProp(name, propTypeSym, mvPublic, false, list, readSpec, writeSpec);
if default then
FDefaultProperty := self.SymbolLookup(UpperCase(name)) as TPropSymbol;
end;
constructor TExternalClassType.Create(info: TRttiInstanceType; LookupType: TTypeLookupFunc;
ParseHeader: TParseHeaderFunc; AddType: TTypeRegisterProc; parent: TUnitSymbol;
baseType: TClassTypeSymbol);
procedure EnsureType(val: TRttiType);
begin
if not NativeTypeDefined(val) then
AddType(val);
end;
function NoImport(obj: TRttiObject): boolean;
var
attr: TCustomAttribute;
begin
for attr in obj.GetAttributes do
if attr is NoImportAttribute then
exit(true);
result := false;
end;
var
method: TRttiMethod;
prop: TRttiProperty;
proc: TProcSymbol;
retval: TTypeSymbol;
paramList: IParamList;
param: TRttiParameter;
begin
Create(info);
if assigned(baseType) then
begin
self.AddField('*PARENT', baseType, mvProtected);
self.parent := baseType;
end;
for method in info.GetDeclaredMethods do
begin
if method.Visibility in [mvPrivate, mvProtected] then
Continue;
if method.IsDestructor then
Continue;
if NoImport(method) then
Continue;
if assigned(method.ReturnType) then
begin
EnsureType(method.ReturnType);
retval := LookupType(method.ReturnType)
end
else retval := nil;
for param in method.GetParameters do
EnsureType(param.ParamType);
proc := ParseHeader(method.ToString, parent, false);
paramList := proc.paramList;
proc.Free;
self.AddMethod(UpperCase(method.Name), retval, mvPublic, method.IsClassMethod, paramList);
end;
for prop in info.GetDeclaredProperties do
begin
if NoImport(prop) then
Continue;
EnsureType(prop.PropertyType);
self.AddProp(prop as TRttiInstanceProperty);
end;
end;
function TExternalClassType.GetInfo: TRttiType;
begin
result := FInfo;
end;
function TExternalClassType.GetTypeInfo: PTypeInfo;
begin
result := FInfo.Handle;
end;
{ TExternalArrayType }
constructor TExternalArrayType.Create(info: TRttiType);
begin
if info is TRttiArrayType then
inherited Create(1, TRttiArrayType(info).TotalElementCount, TypeOfRttiType(TRttiArrayType(info).ElementType))
else if info is TRttiDynamicArrayType then
inherited Create(0, 0, TypeOfRttiType(TRttiDynamicArrayType(info).ElementType))
else raise Exception.Create('TExternalArrayType can only represent array types');
FInfo := info;
// FTypeInfo := info.handle;
end;
function TExternalArrayType.CanDerefArray: boolean;
begin
result := true;
end;
function TExternalArrayType.GetInfo: TRttiType;
begin
result := FInfo;
end;
function TExternalArrayType.GetTypeInfo: PTypeInfo;
begin
result := FInfo.Handle;
end;
end.
|
unit AbstractCardFormControllerEvents;
interface
uses
CardFormViewModel,
Disposable,
Event,
SysUtils,
Classes;
type
TCardStateChangedEvent = class (TEvent)
private
FViewModel: TCardFormViewModel;
FFreeViewModel: IDisposable;
procedure SetViewModel(const Value: TCardFormViewModel);
public
constructor Create(
ViewModel: TCardFormViewModel
);
property CardFormViewModel: TCardFormViewModel
read FViewModel write SetViewModel;
end;
TCardStateChangedEventClass = class of TCardStateChangedEvent;
TCardCreatedEvent = class (TCardStateChangedEvent)
end;
TCardCreatedEventClass = class of TCardCreatedEvent;
TCardModifiedEvent = class (TCardStateChangedEvent)
end;
TCardModifiedEventClass = class of TCardModifiedEvent;
TCardRemovedEvent = class (TCardStateChangedEvent)
end;
TCardRemovedEventClass = class of TCardRemovedEvent;
implementation
{ TCardStateChangedEvent }
constructor TCardStateChangedEvent.Create(ViewModel: TCardFormViewModel);
begin
inherited Create;
CardFormViewModel := ViewModel;
end;
procedure TCardStateChangedEvent.SetViewModel(const Value: TCardFormViewModel);
begin
if FViewModel = Value then
Exit;
FViewModel := Value;
FFreeViewModel := FViewModel;
end;
end.
|
unit Sample5.Contact.Template;
interface
uses
DSharp.Core.DataTemplates;
type
TContactTemplate = class(TDataTemplate)
public
function GetText(const Item: TObject; const ColumnIndex: Integer): string; override;
function GetTemplateDataClass: TClass; override;
procedure SetText(const Item: TObject; const ColumnIndex: Integer;
const Value: string); override;
end;
implementation
uses
Sample5.Contact;
{ TContactTemplate }
function TContactTemplate.GetTemplateDataClass: TClass;
begin
Result := TContact;
end;
function TContactTemplate.GetText(const Item: TObject;
const ColumnIndex: Integer): string;
var
LItem: TContact;
begin
LItem := Item as TContact;
case ColumnIndex of
-1: Result := LItem.Lastname + ', ' + LItem.Firstname;
0: Result := LItem.Lastname;
1: Result := LItem.Firstname;
end;
end;
procedure TContactTemplate.SetText(const Item: TObject;
const ColumnIndex: Integer; const Value: string);
var
LItem: TContact;
begin
LItem := Item as TContact;
case ColumnIndex of
0: LItem.Lastname := Value;
1: LItem.Firstname := Value;
end;
end;
end.
|
unit DW.VirtualKeyboard.Android;
{*******************************************************}
{ }
{ Kastri Free }
{ }
{ DelphiWorlds Cross-Platform Library }
{ }
{*******************************************************}
{$I DW.GlobalDefines.inc}
interface
uses
// RTL
System.Types;
type
TPlatformVirtualKeyboard = record
public
class function GetBounds: TRect; static;
end;
implementation
uses
// Android
Androidapi.JNI.GraphicsContentViewText,
// FMX
{$IF CompilerVersion > 32}
FMX.Platform.UI.Android,
{$ENDIF}
FMX.Platform.Android;
class function TPlatformVirtualKeyboard.GetBounds: TRect;
var
ContentRect, TotalRect: JRect;
begin
ContentRect := TJRect.Create;
TotalRect := TJRect.Create;
MainActivity.getWindow.getDecorView.getWindowVisibleDisplayFrame(ContentRect);
MainActivity.getWindow.getDecorView.getDrawingRect(TotalRect);
Result := TRectF.Create(ConvertPixelToPoint(TPointF.Create(TotalRect.left, TotalRect.top + ContentRect.height)),
ConvertPixelToPoint(TPointF.Create(TotalRect.right, TotalRect.bottom))).Truncate;
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.
//
// Ported to Delphi by Michal Wojcik.
//
// Copyright (C) 2003,2004,2005 by Object Mentor, Inc. All rights reserved.
// Released under the terms of the GNU General Public License version 2 or later.
{$H+}
unit FormattingOption;
interface
uses
classes,
RequestBuilder,
OutputStream,
InputStream;
type
TFormattingOption = class
private
status : Integer;
resultFilename : string;
procedure args(args : TStringList);
procedure usage();
function buildRequest(inputStream : TInputStream; size : Integer) : TRequestBuilder;
procedure setOutput(stdout : TOutputStream);
public
format : string;
usingStdout : boolean;
output : TOutputStream;
host : string;
port : Integer;
rootPath : string;
filename : string;
constructor Create(); overload;
constructor Create(format : string; filename : string; stdout : TOutputStream; host : string; port : Integer;
rootPath : string); overload;
class procedure main(args : TStringList);
procedure process(inputStream : TInputStream; size : Integer);
function wasSuccessful : Boolean;
end;
implementation
uses
CommandLine,
ResponseParser,
FileUnit,
FileInputStream,
FileOutputStream,
FileUtil,
sysUtils;
constructor TFormattingOption.Create;
begin
end;
class procedure TFormattingOption.main(args : TStringList);
var
option : TFormattingOption;
inputFile : TFile;
input : TFileInputStream;
byteCount : Integer;
begin
option := TFormattingOption.Create();
option.args(args);
inputFile := TFile.Create(option.resultFilename);
input := TFileInputStream.Create(inputFile);
byteCount := inputFile.length();
option.process(input, byteCount);
option.Free;
end;
procedure TFormattingOption.args(args : TStringList);
var
commandLine : TCommandLine;
begin
commandLine := TCommandLine.Create('resultFilename format outputFilename host port rootPath');
if (not commandLine.parse(args)) then
usage();
resultFilename := commandLine.getArgument('resultFilename');
format := commandLine.getArgument('format');
filename := commandLine.getArgument('outputFilename');
host := commandLine.getArgument('host');
port := StrToInt(commandLine.getArgument('port'));
rootPath := commandLine.getArgument('rootPath');
//TODO setOutput(System.out);
end;
procedure TFormattingOption.usage();
const
c : Integer = -1;
begin
WriteLn('java fitnesse.runner.FormattingOption resultFilename format outputFilename host port rootPath');
WriteLn(#9'resultFilename:'#9'the name of the file containing test results');
WriteLn(#9'format: '#9'raw|html|xml|...');
WriteLn(#9'outputfilename:'#9'stdout|a filename where the formatted results are to be stored');
WriteLn(#9'host: '#9'the domain name of the hosting FitNesse server');
WriteLn(#9'port: '#9'the port on which the hosting FitNesse server is running');
WriteLn(#9'rootPath: '#9'name of the test page or suite page');
System.Halt(c);
end;
constructor TFormattingOption.Create(format : string; filename : string; stdout : TOutputStream; host : string; port :
Integer; rootPath : string);
begin
self.format := format;
self.filename := filename;
setOutput(stdout);
self.host := host;
self.port := port;
self.rootPath := rootPath;
end;
procedure TFormattingOption.setOutput(stdout : TOutputStream);
begin
if ('stdout' = filename) then
begin
self.output := stdout;
self.usingStdout := true;
end
else
self.output := TFileOutputStream.Create(filename);
end;
procedure TFormattingOption.process(inputStream : TInputStream; size : Integer);
var
request : TRequestBuilder;
response : TResponseParser;
begin
if ('raw' = format) then
TFileUtil.copyBytes(inputStream, output)
else
begin
request := buildRequest(inputStream, size);
response := TResponseParser.performHttpRequest(host, port, request);
status := response.getStatus();
output.write(response.getBody() {.getBytes('UTF-8')});
end;
if (not usingStdout) then
output.close();
inputStream.Free;
end;
function TFormattingOption.wasSuccessful() : Boolean;
begin
Result := status = 200;
end;
function TFormattingOption.buildRequest(inputStream : TInputStream; size : Integer) : TRequestBuilder;
var
request : TRequestBuilder;
begin
request := TRequestBuilder.Create('/' + rootPath);
request.setMethod('POST');
request.setHostAndPort(host, port);
request.addInput('responder', 'format');
request.addInput('format', format);
request.addInputAsPart('results', inputStream, size, 'text/plain');
Result := request;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.