text stringlengths 14 6.51M |
|---|
unit uDemoForm;
interface
{$R uDemoForm.res}
uses
Windows, apiGUI, apiObjects, apiWrappersGUI, uDataProvider;
const
NullRect: TRect = (Left: 0; Top: 0; Right: 0; Bottom: 0);
type
TAIMPUITreeListNodeValueEvent = procedure (Sender: IAIMPUITreeList; NodeValue: IAIMPString) of object;
{ TAIMPUITreeListNodeSelectedEventAdapter }
TAIMPUITreeListNodeSelectedEventAdapter = class(TInterfacedObject,
IAIMPUITreeListEvents)
strict private
FEvent: TAIMPUITreeListNodeValueEvent;
public
constructor Create(AEvent: TAIMPUITreeListNodeValueEvent);
// IAIMPUITreeListEvents
procedure OnColumnClick(Sender: IAIMPUITreeList; ColumnIndex: Integer); stdcall;
procedure OnFocusedColumnChanged(Sender: IAIMPUITreeList); stdcall;
procedure OnFocusedNodeChanged(Sender: IAIMPUITreeList); stdcall;
procedure OnNodeChecked(Sender: IAIMPUITreeList; Node: IAIMPUITreeListNode); stdcall;
procedure OnNodeDblClicked(Sender: IAIMPUITreeList; Node: IAIMPUITreeListNode); stdcall;
procedure OnSelectionChanged(Sender: IAIMPUITreeList); stdcall;
procedure OnSorted(Sender: IAIMPUITreeList); stdcall;
procedure OnStructChanged(Sender: IAIMPUITreeList); stdcall;
end;
{ TDemoForm }
TDemoForm = class(TInterfacedObject,
IAIMPUIPlacementEvents,
IAIMPUIFormEvents)
strict private
// IAIMPUIPlacementEvents
procedure OnBoundsChanged(Sender: IInterface); stdcall;
// IAIMPUIFormEvents
procedure OnActivated(Sender: IAIMPUIForm); stdcall;
procedure OnDeactivated(Sender: IAIMPUIForm); stdcall;
procedure OnCreated(Sender: IAIMPUIForm); stdcall;
procedure OnDestroyed(Sender: IAIMPUIForm); stdcall;
procedure OnCloseQuery(Sender: IAIMPUIForm; var CanClose: LongBool); stdcall;
procedure OnLocalize(Sender: IAIMPUIForm); stdcall;
procedure OnShortCut(Sender: IAIMPUIForm; Key, Modifiers: Word; var Handled: LongBool); stdcall;
// TAIMPUITreeListNodeSelectedEventAdapter
procedure OnSelectAlbum(Sender: IAIMPUITreeList; NodeValue: IAIMPString);
procedure OnSelectArtist(Sender: IAIMPUITreeList; NodeValue: IAIMPString);
protected
FControlAlbumList: IAIMPUITreeList;
FControlArtistList: IAIMPUITreeList;
FControlTopPanel: IAIMPUIWinControl;
FControlTrackList: IAIMPUITreeList;
FDataProvider: TMLDataProvider;
FForm: IAIMPUIForm;
FService: IAIMPServiceUI;
FSelectedAlbum: IAIMPString;
FSelectedArtist: IAIMPString;
procedure CreateControls;
procedure FetchAlbums;
procedure FetchArtists;
procedure FetchTracks;
procedure PopulateTreeList(ATreeList: IAIMPUITreeList; AData: THashSet<string>);
public
constructor Create(AService: IAIMPServiceUI; ADataProvider: TMLDataProvider);
function ShowModal: Integer;
end;
implementation
uses
apiWrappers;
function CenterRect(const ABounds: TRect; AWidth, AHeight: Integer): TRect;
begin
Result.Left := (ABounds.Left + ABounds.Right - AWidth) div 2;
Result.Top := (ABounds.Top + ABounds.Bottom - AHeight) div 2;
Result.Right := Result.Left + AWidth;
Result.Bottom := Result.Top + AHeight;
end;
{ TAIMPUITreeListNodeSelectedEventAdapter }
constructor TAIMPUITreeListNodeSelectedEventAdapter.Create(AEvent: TAIMPUITreeListNodeValueEvent);
begin
FEvent := AEvent;
end;
procedure TAIMPUITreeListNodeSelectedEventAdapter.OnFocusedColumnChanged(Sender: IAIMPUITreeList);
begin
// do nothing
end;
procedure TAIMPUITreeListNodeSelectedEventAdapter.OnFocusedNodeChanged(Sender: IAIMPUITreeList);
var
ANode: IAIMPUITreeListNode;
AValue: IAIMPString;
begin
if Succeeded(Sender.GetFocused(IAIMPUITreeListNode, ANode)) then
begin
if Succeeded(ANode.GetValue(0, AValue)) then
FEvent(Sender, AValue);
end;
end;
procedure TAIMPUITreeListNodeSelectedEventAdapter.OnColumnClick(Sender: IAIMPUITreeList; ColumnIndex: Integer);
begin
// do nothing
end;
procedure TAIMPUITreeListNodeSelectedEventAdapter.OnNodeChecked(Sender: IAIMPUITreeList; Node: IAIMPUITreeListNode);
begin
// do nothing
end;
procedure TAIMPUITreeListNodeSelectedEventAdapter.OnNodeDblClicked(Sender: IAIMPUITreeList; Node: IAIMPUITreeListNode);
begin
// do nothing
end;
procedure TAIMPUITreeListNodeSelectedEventAdapter.OnSelectionChanged(Sender: IAIMPUITreeList);
begin
// do nothing
end;
procedure TAIMPUITreeListNodeSelectedEventAdapter.OnSorted(Sender: IAIMPUITreeList);
begin
// do nothing
end;
procedure TAIMPUITreeListNodeSelectedEventAdapter.OnStructChanged(Sender: IAIMPUITreeList);
begin
// do nothing
end;
{ TDemoForm }
constructor TDemoForm.Create(AService: IAIMPServiceUI; ADataProvider: TMLDataProvider);
var
ABounds: TRect;
begin
FService := AService;
FDataProvider := ADataProvider;
CheckResult(AService.CreateForm(0, 0, MakeString('DemoForm'), Self, FForm));
// Center the Form on screen
SystemParametersInfo(SPI_GETWORKAREA, 0, ABounds, 0);
CheckResult(FForm.SetPlacement(TAIMPUIControlPlacement.Create(CenterRect(ABounds, 1024, 600))));
// Create children controls
CreateControls;
// Show the data
FetchArtists;
end;
procedure TDemoForm.CreateControls;
var
AColumn: IAIMPUITreeListColumn;
begin
// Create a top panel
CheckResult(FService.CreateControl(FForm, FForm, nil, nil, IID_IAIMPUIPanel, FControlTopPanel));
CheckResult(FControlTopPanel.SetPlacement(TAIMPUIControlPlacement.Create(ualTop, 200)));
CheckResult(FControlTopPanel.SetValueAsInt32(AIMPUI_PANEL_PROPID_BORDERS, 0));
// Create an artist view
CheckResult(FService.CreateControl(FForm, FControlTopPanel, nil,
TAIMPUITreeListNodeSelectedEventAdapter.Create(OnSelectArtist), IID_IAIMPUITreeList, FControlArtistList));
CheckResult(FControlArtistList.SetPlacement(TAIMPUIControlPlacement.Create(ualNone, NullRect)));
CheckResult(FControlArtistList.AddColumn(IID_IAIMPUITreeListColumn, AColumn));
PropListSetStr(AColumn, AIMPUI_TL_COLUMN_PROPID_CAPTION, 'Artists');
// Create an album view
CheckResult(FService.CreateControl(FForm, FControlTopPanel, nil,
TAIMPUITreeListNodeSelectedEventAdapter.Create(OnSelectAlbum), IID_IAIMPUITreeList, FControlAlbumList));
CheckResult(FControlAlbumList.SetPlacement(TAIMPUIControlPlacement.Create(ualClient, NullRect)));
CheckResult(FControlAlbumList.AddColumn(IID_IAIMPUITreeListColumn, AColumn));
PropListSetStr(AColumn, AIMPUI_TL_COLUMN_PROPID_CAPTION, 'Albums');
// Create a tracks view
CheckResult(FService.CreateControl(FForm, FForm, nil, nil, IID_IAIMPUITreeList, FControlTrackList));
CheckResult(FControlTrackList.SetPlacement(TAIMPUIControlPlacement.Create(ualClient, NullRect)));
end;
procedure TDemoForm.FetchAlbums;
begin
FDataProvider.FetchAlbums(FSelectedArtist,
procedure (AStringSet: THashSet<string>)
begin
PopulateTreeList(FControlAlbumList, AStringSet);
end);
end;
procedure TDemoForm.FetchArtists;
begin
FDataProvider.FetchArtists(
procedure (AStringSet: THashSet<string>)
begin
PopulateTreeList(FControlArtistList, AStringSet);
end);
end;
procedure TDemoForm.FetchTracks;
begin
FDataProvider.FetchTracks(FSelectedArtist, FSelectedAlbum,
procedure (AStringSet: THashSet<string>)
begin
PopulateTreeList(FControlTrackList, AStringSet);
end);
end;
procedure TDemoForm.PopulateTreeList(ATreeList: IAIMPUITreeList; AData: THashSet<string>);
var
ARootNode: IAIMPUITreeListNode;
ANode: IAIMPUITreeListNode;
AValue: string;
begin
ATreeList.BeginUpdate;
try
CheckResult(ATreeList.GetRootNode(IID_IAIMPUITreeListNode, ARootNode));
CheckResult(ARootNode.ClearChildren);
for AValue in AData do
begin
CheckResult(ARootNode.Add(ANode));
CheckResult(ANode.SetValue(0, MakeString(AValue)));
end;
finally
ATreeList.EndUpdate;
end;
end;
function TDemoForm.ShowModal: Integer;
begin
Result := FForm.ShowModal;
end;
// IAIMPUIPlacementEvents
procedure TDemoForm.OnBoundsChanged(Sender: IInterface);
var
APlacement: TAIMPUIControlPlacement;
begin
CheckResult(FControlTopPanel.GetPlacement(APlacement));
CheckResult(FControlArtistList.SetPlacement(TAIMPUIControlPlacement.Create(ualLeft, APlacement.Bounds.Width div 2)));
end;
// IAIMPUIFormEvents
procedure TDemoForm.OnActivated(Sender: IAIMPUIForm);
begin
// do nothing
end;
procedure TDemoForm.OnDeactivated(Sender: IAIMPUIForm); stdcall;
begin
// do nothing
end;
procedure TDemoForm.OnCreated(Sender: IAIMPUIForm); stdcall;
begin
// do nothing
end;
procedure TDemoForm.OnDestroyed(Sender: IAIMPUIForm); stdcall;
begin
{$MESSAGE 'TODO - stop all requests in FDataProvider'}
// Release all variables
FControlTopPanel := nil;
FControlArtistList := nil;
FControlAlbumList := nil;
FControlTrackList := nil;
FForm := nil;
end;
procedure TDemoForm.OnCloseQuery(Sender: IAIMPUIForm; var CanClose: LongBool); stdcall;
begin
// do nothing
end;
procedure TDemoForm.OnLocalize(Sender: IAIMPUIForm); stdcall;
begin
// do nothing
end;
procedure TDemoForm.OnShortCut(Sender: IAIMPUIForm; Key, Modifiers: Word; var Handled: LongBool); stdcall;
begin
// do nothing
end;
procedure TDemoForm.OnSelectAlbum(Sender: IAIMPUITreeList; NodeValue: IAIMPString);
begin
FControlTrackList.Clear;
FSelectedAlbum := NodeValue;
FetchTracks;
end;
procedure TDemoForm.OnSelectArtist(Sender: IAIMPUITreeList; NodeValue: IAIMPString);
begin
FControlAlbumList.Clear;
FControlTrackList.Clear;
FSelectedArtist := NodeValue;
FSelectedAlbum := nil;
FetchAlbums;
end;
end.
|
unit fre_basecli_app;
{
(§LIC)
(c) Autor,Copyright
Dipl.Ing.- Helmut Hartl, Dipl.Ing.- Franz Schober, Dipl.Ing.- Christian Koch
FirmOS Business Solutions GmbH
www.openfirmos.org
New Style BSD Licence (OSI)
Copyright (c) 2001-2009, FirmOS Business Solutions GmbH
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the <FirmOS Business Solutions GmbH> 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.
(§LIC_END)
}
{$mode objfpc}
{$codepage utf8}
{$H+}
{$modeswitch nestedprocvars}
interface
uses
Classes, SysUtils, CustApp,
fre_system,fos_default_implementation,fos_tool_interfaces,fos_fcom_types,fre_aps_interface,fre_db_interface,
fre_db_core,
fre_dbbase,fre_openssl_cmd,
fre_aps_comm_impl,
fre_net_pl_client, { network ps layer}
fre_db_persistance_fs_simple, { filesystem ps layer}
fre_configuration,fre_base_server,
fre_db_core_transdata
;
type
{ TFRE_CLISRV_APP }
TFRE_CLISRV_APP = class(TCustomApplication)
private
FAvailExtensionList : IFOS_STRINGS;
FChosenExtensionList : IFOS_STRINGS;
FCustomExtensionSet : boolean;
FDeployed : boolean;
FShortOpts : IFOS_STRINGS;
FLongOpts : IFOS_STRINGS;
FHelpOpts : IFOS_STRINGS;
FDefaultStyle : String;
procedure SetDefaultStyle (AValue: String);
protected
fapplication : string;
FDBName : string;
FOnlyInitDB : boolean;
FBaseServer : TFRE_BASE_SERVER;
FLimittransfer : integer;
FSystemConnection : TFRE_DB_SYSTEM_CONNECTION;
procedure AddCheckOption (const short_option,long_option,helpentry : string);
procedure AddHelpOutLine (const msg:String='');
function GetShortCheckOptions : String; virtual; { Setup of cmd line options short }
function GetLongCheckOptions : TStrings; virtual; { Setup of cmd line options long }
procedure _CheckDBNameSupplied;
procedure _CheckAdminUserSupplied;
procedure _CheckAdminPassSupplied;
procedure _CheckPLAdminUserSupplied;
procedure _CheckPLAdminPassSupplied;
procedure _CheckUserSupplied;
procedure _CheckPassSupplied;
procedure _CheckNoCustomextensionsSet;
procedure DoRun ; override ;
procedure OrderedShutDown ;
procedure DebugTestProcedure ; { copy startup test code here}
function PreStartupTerminatingCommands: boolean ; virtual; { cmd's that should be executed without db(ple), they terminate }
function AfterConfigStartupTerminatingCommands:boolean ; virtual; { cmd's that should be executed after the reading of cfg file, but before db core init }
function AfterStartupTerminatingCommands:boolean ; virtual; { cmd's that should be executed with db core init, they terminate }
function AfterInitDBTerminatingCommands:boolean ; virtual; { cmd's that should be executed with full db init, they terminate }
function AfterSysDBConnectTerminatingCommands:boolean ; virtual; { cmd's that should be executed after the connection to the system db is done, FSystemConnection is available (Proxy) }
procedure ParseSetSystemFlags ; virtual; { Setting of global flags before startup go here }
procedure AddCommandLineOptions ; virtual; { override for custom options/flags/commands }
procedure WriteHelp ; virtual;
procedure WriteVersion ; virtual;
public
function GetActiveDatabaseConnection : IFRE_DB_CONNECTION;
function ListFromString (const str :string) : IFOS_STRINGS;
procedure EnableDisableFeature (const feature: TFRE_DB_NameType; const enable: boolean);
procedure ShowFeatures ;
procedure ConvertDbo (const file_name:string ; const to_json:boolean);
procedure CalcSHA1 (pw : string);
procedure DumpDBO (const uid_hex : string);
procedure PrintTimeZones ;
procedure ReCreateDB ;
procedure ReCreateSysDB ;
procedure BackupDB (const adb, sdb: boolean; const dir: string);
procedure RestoreDB (const adb, sdb: boolean; const dir: string ; const override_with_live_scheme : boolean);
procedure AddUser (const userencoding : string);
procedure GenerateTestdata ; virtual;
procedure DoUnitTest ;
procedure InitExtensions ;
procedure ShowVersions ;
procedure ShowRights ;
procedure ShowApps ;
procedure ShowDeploy ;
procedure DumpScheme (const scheme:shortstring);
procedure RemoveExtensions ;
procedure RegisterExtensions ;
procedure DeployDatabaseScheme (deploy_revision : string);
procedure VerifyExtensions ;
procedure ListExtensions ;
procedure PrepareStartup ;
procedure CfgTestLog ; virtual;
procedure EndlessLogTest ;
procedure SchemeDump (const filename:string;const classfile:string);
procedure DumpAll (const filterstring: string);
procedure OverviewDump ;
procedure ExpandReferences (const input:string);
constructor Create (TheOwner: TComponent); override;
destructor Destroy ; override;
property DefaultStyle : String read FDefaultStyle write SetDefaultStyle;
end;
implementation
{$I fos_version_helper.inc}
{ TFRE_CLISRV_APP }
function TFRE_CLISRV_APP.ListFromString(const str: string): IFOS_STRINGS;
begin
result := GFRE_TF.Get_FOS_Strings;
result.SetCommatext(str);
end;
procedure TFRE_CLISRV_APP.EnableDisableFeature(const feature: TFRE_DB_NameType; const enable: boolean);
var conn : IFRE_DB_CONNECTION;
begin
_CheckDBNameSupplied;
_CheckAdminUserSupplied;
_CheckAdminPassSupplied;
_CheckNoCustomextensionsSet;
CONN := GFRE_DBI.NewConnection;
if cG_OVERRIDE_USER='' then
cG_OVERRIDE_USER:=cFRE_ADMIN_USER;
if cG_OVERRIDE_PASS='' then
cG_OVERRIDE_PASS:=cFRE_ADMIN_PASS;
CheckDbResult(CONN.Connect(FDBName,cG_OVERRIDE_USER,cG_OVERRIDE_PASS),'cannot connect db');
CheckDbResult(conn.SetFeatureStatus(feature,enable));
end;
procedure TFRE_CLISRV_APP.ShowFeatures;
var conn : IFRE_DB_CONNECTION;
begin
_CheckDBNameSupplied;
_CheckAdminUserSupplied;
_CheckAdminPassSupplied;
_CheckNoCustomextensionsSet;
CONN := GFRE_DBI.NewConnection;
if cG_OVERRIDE_USER='' then
cG_OVERRIDE_USER:=cFRE_ADMIN_USER;
if cG_OVERRIDE_PASS='' then
cG_OVERRIDE_PASS:=cFRE_ADMIN_PASS;
CheckDbResult(CONN.Connect(FDBName,cG_OVERRIDE_USER,cG_OVERRIDE_PASS),'cannot connect db');
writeln('Possible Features : ',GFRE_DBI.GetFeatureList.Commatext);
writeln('Enabled Features : ',conn.GetAllEnabledDBFeatures.Commatext);
end;
procedure TFRE_CLISRV_APP.ConvertDbo(const file_name: string; const to_json: boolean);
var dbo : TFRE_DB_Object;
fp,fn : string;
res : string;
begin
if not FileExists(file_name) then
begin
writeln('the given file [',file_name,'] does not exist!');
terminate;
halt(1);
end;
if to_json then
begin
fp := ExtractFilePath(file_name);
fn := ExtractFileName(file_name);
fn := copy(fn,1,Length(fn)-Length(ExtractFileExt(fn)));
fn := fp+DirectorySeparator+fn+'.frejson';
if FileExists(fn) and
not DeleteFile(fn) then
raise EFRE_DB_Exception.Create(edb_INTERNAL,'could not delete convert file : '+fn);
dbo := TFRE_DB_Object.CreateFromFile(file_name);
res := dbo.GetAsJSONString(false,true,nil);
GFRE_BT.StringToFile(fn,res);
dbo.Finalize;
end
else
begin
fp := ExtractFilePath(file_name);
fn := ExtractFileName(file_name);
fn := copy(fn,1,Length(fn)-Length(ExtractFileExt(fn)));
fn := fp+DirectorySeparator+fn+'.fdbo';
if FileExists(fn) and
not DeleteFile(fn) then
raise EFRE_DB_Exception.Create(edb_INTERNAL,'could not delete convert file : '+fn);
res := GFRE_BT.StringFromFile(file_name);
dbo := TFRE_DB_Object.CreateFromJSONString(res);
dbo.SaveToFile(fn);
dbo.Finalize;
end;
end;
procedure TFRE_CLISRV_APP.CalcSHA1(pw: string);
var len : NativeInt;
begin
Randomize;
len:=StrToIntDef(pw,-1);
if pw='' then
pw := FREDB_GetRandomChars(10)
else
if (len>0) and (len<65) then
pw := FREDB_GetRandomChars(len);
writeln('Calculating Salted SHA1 SCHEME for ['+pw+'] = ['+GFRE_BT.CalcSaltedSH1Password(pw,FREDB_GetRandomChars(8))+']');
end;
procedure TFRE_CLISRV_APP.DumpDBO(const uid_hex: string);
var conn : IFRE_DB_CONNECTION;
uid : TFRE_DB_GUID;
dbo : IFRE_DB_Object;
refs : TFRE_DB_ObjectReferences;
i : NativeInt;
begin
uid := FREDB_H2G(uid_hex);
_CheckDBNameSupplied;
_CheckAdminUserSupplied;
_CheckAdminPassSupplied;
_CheckNoCustomextensionsSet;
CONN := GFRE_DBI.NewConnection;
if cG_OVERRIDE_USER='' then
cG_OVERRIDE_USER:=cFRE_ADMIN_USER;
if cG_OVERRIDE_PASS='' then
cG_OVERRIDE_PASS:=cFRE_ADMIN_PASS;
CheckDbResult(CONN.Connect(FDBName,cG_OVERRIDE_USER,cG_OVERRIDE_PASS),'cannot connect system db');
CheckDbResult(conn.fetch(uid,dbo));
refs := conn.GetReferencesDetailed(uid,false);
writeln('');
writeln(dbo.DumpToString(2));
writeln('');
writeln('REFERENCES INBOUND ');
for i:=0 to high(refs) do
begin
writeln(' <- ',refs[i].schemename,'.',refs[i].fieldname,'(',refs[i].linked_uid.AsHexString,')');
end;
writeln('');
writeln('REFERENCES OUTBOUND');
SetLength(refs,0);
refs := conn.GetReferencesDetailed(uid,true);
for i:=0 to high(refs) do
begin
writeln(' ',refs[i].fieldname,' -> ',refs[i].schemename,'(',refs[i].linked_uid.AsHexString,')');
end;
conn.Finalize;
end;
procedure TFRE_CLISRV_APP.ParseSetSystemFlags;
procedure SetDatetimeTag;
var y,m,d,hh,mm,ss,mmm : LongInt;
begin
GFRE_DT.DecodeTime(GFRE_DT.Now_UTC,y,m,d,hh,mm,ss,mmm);
cFRE_DB_CACHETAG := Format('%2.2d%2.2d%2.2d%2.2d%2.2d%2.2d',[hh,mm,ss,d,m,y-2000]);
end;
begin
SetDatetimeTag;
if HasOption('*','tryrecovery') then
begin
GDBPS_SKIP_STARTUP_CHECKS := true;
end;
FLimittransfer := 0;
if HasOption('*','limittransfer') then
begin
FLimittransfer:=StrToIntDef(GetOptionValue('*','limittransfer'),-1);
if FLimittransfer=-1 then
begin
writeln('TRANSFER LIMITING FAILED, SYNTAX');
FLimittransfer:=0;
end;
end;
if HasOption('*','cleanzip') then
cFRE_FORCE_CLEAN_ZIP_HTTP_FILES := true;
if HasOption('*','nozip') then
cFRE_BUILD_ZIP_HTTP_FILES := false;
if HasOption('*','nocache') then
cFRE_USE_STATIC_CACHE := false;
if HasOption('s','style') then
cFRE_WEB_STYLE := GetOptionValue('s','style')
else
cFRE_WEB_STYLE := FDefaultStyle;
if HasOption('*','jsdebug') then
cFRE_JS_DEBUG := true
else
cFRE_JS_DEBUG := false;
if HasOption('*','webdev') then
begin
cFRE_JS_DEBUG := true;
cFRE_USE_STATIC_CACHE := false;
cFRE_BUILD_ZIP_HTTP_FILES := false;
cFRE_FORCE_CLEAN_ZIP_HTTP_FILES := true;
end;
if HasOption('*','cmddebug') then
cFRE_CMDLINE_DEBUG := GetOptionValue('*','cmddebug');
if HasOption('*','filterapps') then
cFRE_DB_ALLOWED_APPS := GetOptionValue('*','filterapps');
if HasOption('*','basedir') then
CFRE_OVERRIDE_DEFAULT_DIR := GetOptionValue('*','basedir');
if GDBPS_SKIP_STARTUP_CHECKS then
writeln('>>> !!!! WARNING : SKIPPING STARTUP CHECKS (only possible on embedded) !!!! ');
end;
function TFRE_CLISRV_APP.GetShortCheckOptions: String;
var
i: NativeInt;
begin
result := '';
for i:=0 to FShortOpts.Count-1 do
result := result+FShortOpts[i];
end;
function TFRE_CLISRV_APP.GetLongCheckOptions: TStrings;
begin
result := FLongOpts.AsTStrings;
end;
procedure TFRE_CLISRV_APP.AddCheckOption(const short_option, long_option, helpentry: string);
begin
FShortOpts.Add(short_option);
FLongOpts.Add(long_option);
FHelpOpts.Add(helpentry);
end;
procedure TFRE_CLISRV_APP.AddHelpOutLine(const msg: String);
begin
FHelpOpts.Add(msg);
end;
procedure TFRE_CLISRV_APP.AddCommandLineOptions;
begin
AddCheckOption('v' ,'version' ,' -v | --version : print version information');
AddCheckOption('h' ,'help' ,' -h | --help : print this help');
AddCheckOption('e:' ,'extensions:' ,' -e <ext,..> | --extensions=<ext,..> : load database extensions');
AddCheckOption('l' ,'list' ,' -l | --list : list available extensions');
AddCheckOption('s:' ,'style:' ,' -s <style> | --style <style> : use the given css style (default: firmos)');
AddCheckOption('d:' ,'database:' ,' -d <database> | --database=<database> : specify database, default is "ADMIN_DB"');
AddCheckOption('x' ,'forcedb' ,' -x | --forcedb : recreates specified database (CAUTION)');
AddCheckOption('y' ,'forcesysdb' ,' -y | --forcesysdb : recreates system database (CAUTION)');
AddCheckOption('i::','init::' ,' -i [fast] | --init [fast] : init a new database with the chosen extensions, fast enables write back mode');
AddCheckOption('r' ,'remove' ,' -r | --remove : remove extensions from system database (CAUTION)');
AddCheckOption('t' ,'testdata' ,' -t | --testdata : creates test data for extensions');
AddCheckOption('u:' ,'user:' ,' -u <user> | --user=<user> : specify autologin (debug) user');
AddCheckOption('p:' ,'pass:' ,' -p <password> | --pass=<password> : specify autologin (debug) password');
AddCheckOption('U:' ,'remoteuser:' ,' -U | --remoteuser=<user> : user for remote commands');
AddCheckOption('H:' ,'remotehost:' ,' -H | --remotehost=<pass> : host for remote commands');
AddCheckOption('g:' ,'graph:' ,' -g <filename> | --graph=<filename> : graphical dump (system without extensions)');
AddCheckOption('*' ,'classfile:' ,' | --classfile=<filename> : filter graphical dump to classes listed in classfile and related');
AddCheckOption('z' ,'testdump:' ,' -z [Scheme,..]| --testdump=[Scheme,..] : dump class and uid of all objects');
AddHelpOutLine;
AddCheckOption('*' ,'basedir:' ,' | --basedir=<basedir> : override server base directory');
AddCheckOption('*' ,'ple' ,' | --ple : use embedded persistence layer');
AddCheckOption('*' ,'plhost:' ,' | --plhost=<dnsname> : use dns host for pl net connection');
AddCheckOption('*' ,'plip:' ,' | --plip=<numeric ip> : use ip host for pl net connection');
AddCheckOption('*' ,'plport:' ,' | --plport=<portnum> : use port for pl net connection');
AddHelpOutLine;
AddCheckOption('*' ,'unittest' ,' | --unittest : perform the unit test function for extensions');
AddCheckOption('*' ,'printtz' ,' | --printtz : print debug timezone information / known timezones');
AddCheckOption('*' ,'cleanzip' ,' | --cleanzip : force delete all prezipped webroot files');
AddCheckOption('*' ,'nozip' ,' | --nozip : don''t zip webroot files, the server still uses files that are availlable');
AddCheckOption('*' ,'nocache' ,' | --nocache : disable memory caching of whole webroot on startup');
AddCheckOption('*' ,'jsdebug' ,' | --jsdebug : enable javascript debug/develop mode');
AddCheckOption('*' ,'webdev' ,' | --webdev : shortcut: cleanzip,nozip,jsdebug,nocache');
AddCheckOption('*' ,'dbo2json:' ,' | --dbo2json=/path2/dbo : convert a dbo to json representation');
AddCheckOption('*' ,'json2dbo:' ,' | --json2dbo=/path2/json : convert a json to dbo representation');
AddCheckOption('*' ,'dumpdbo:' ,' | --dumpdbo=uid_hex : direct dump of a dbo');
AddCheckOption('*' ,'expandrefs:' ,' | --expandrefs=uid_hex,[..]/RL,..: expand referenceslist');
AddCheckOption('*' ,'tryrecovery' ,' | --tryrecovery : try recovery of a bad db by skipping checks / start with option / make backup / have luck');
AddCheckOption('*' ,'showinstalled' ,' | --showinstalled : show installed versions of all database objects');
AddCheckOption('*' ,'showrights' ,' | --showrights : show rights of specified user & and check login');
AddCheckOption('*' ,'showapps' ,' | --showapps : show the actual available (filtered) app classes');
AddCheckOption('*' ,'showdeploy' ,' | --showdeploy : show the deployment information');
AddCheckOption('*' ,'showfeatures' ,' | --showfeatures : show the feature information');
AddCheckOption('*' ,'enablefeature:',' | --enablefeature : enable a feature');
AddCheckOption('*' ,'disablefeature:',' | --disablefeature : disable a feature');
AddCheckOption('*' ,'filterapps:' ,' | --filterapps=class,class : allow only the specified apps');
AddCheckOption('A' ,'adduser:' ,' | --adduser=name@dom,pass,class : add a user with a specified class (WEBUSER,FEEDER),password and domain (SYSTEM)');
AddCheckOption('*' ,'showscheme::' ,' | --showscheme [CLASS] : dump the whole database scheme definition, or a specific schemeclass');
AddCheckOption('*' ,'backupdb:' ,' | --backupdb=</path2/dir> : backup database interactive');
AddCheckOption('*' ,'restoredb:' ,' | --restoredb=</path2/dir> : restore database interactive');
AddCheckOption('*' ,'restoredbsch:' ,' | --restoredbsch=</path2/dir> : restore database interactive, but ignore backup schemes and use live schemes');
AddCheckOption('*' ,'backupsys:' ,' | --backupsys=</path2/dir> : backup only sys database interactive');
AddCheckOption('*' ,'restoresys:' ,' | --restoresys=</path2/dir> : restore only sys database interactive');
AddCheckOption('*' ,'backupapp:' ,' | --backupapp=</path2/dir> : backup only app database interactive');
AddCheckOption('*' ,'restoreapp:' ,' | --restoreapp=</path2/dir> : restore only app database interactive');
AddCheckOption('D::','deploy::' ,' -D [revision] | --deploy[=revision] : build and deploy databasescheme for the chosen extensions to persistence layer, optional tag with revision');
AddCheckOption('*' ,'limittransfer:',' | --limittransfer=<10> : sleep <x ms> during backup and restore, to limit bandwidth');
AddCheckOption('*' ,'adminuser:' ,' | --adminuser=<user> : specify user for db admin options');
AddCheckOption('*' ,'adminpass:' ,' | --adminpass=<password> : specify password for db admin options');
AddCheckOption('*' ,'pladmin:' ,' | --pladmin=<user> : specify user for pl admin options');
AddCheckOption('*' ,'plpass:' ,' | --plpass=<password> : specify password for pl admin options');
AddCheckOption('*' ,'testlog' ,' | --testlog : enable fixed (debug-cfg) logging to console');
AddCheckOption('*' ,'testlogcfg' ,' | --testlogcfg : do an endless logging test');
AddHelpOutLine;
AddCheckOption('c' ,'config' ,' -c | --config : enable config mode');
AddCheckOption('*' ,'datacenter:' ,' | --datacenter : default datacenter name for config');
AddCheckOption('*' ,'machine:' ,' | --machine : default machine name for config');
//AddCheckOption('*' ,'machineuid:' ,' | --machineuid : default machine uid for config (standalone)');
AddCheckOption('*' ,'mac:' ,' | --mac : mac for config');
AddCheckOption('*' ,'ip:' ,' | --ip : ip for config');
AddHelpOutLine;
AddCheckOption('*' ,'resetadmin' ,' | --resetadmin : reset the admin@system and the guest@system accounts to default. => (admin and "")');
AddCheckOption('*' ,'cmddebug:' ,' | --cmddebug=<param> : set an arbitrary cmd line debug option');
AddCheckOption('o' ,'overviewdump' ,' -o | --overviewdump : do a overview dump of the database');
AddCheckOption('Z::','calcsha::' ,' -Z | --calcsha[=<password>] : generate/calc a safe salted sha1 password');
end;
procedure TFRE_CLISRV_APP.SetDefaultStyle(AValue: String);
begin
FDefaultStyle:=AValue;
end;
procedure TFRE_CLISRV_APP._CheckDBNameSupplied;
begin
if (FDBName='') then begin
writeln('no database name supplied for extension initialization');
Terminate;
halt(1);
end;
end;
procedure TFRE_CLISRV_APP._CheckAdminUserSupplied;
begin
if (cFRE_ADMIN_USER='') then begin
writeln('no admin username supplied');
Terminate;
halt(1);
end;
end;
procedure TFRE_CLISRV_APP._CheckAdminPassSupplied;
begin
if (cFRE_ADMIN_PASS='') then begin
writeln('no admin password supplied');
Terminate;
halt(1);
end;
end;
procedure TFRE_CLISRV_APP._CheckPLAdminUserSupplied;
begin
if (cFRE_PL_ADMIN_USER='') then begin
writeln('no admin username supplied');
Terminate;
halt(1);
end;
end;
procedure TFRE_CLISRV_APP._CheckPLAdminPassSupplied;
begin
if (cFRE_PL_ADMIN_PASS='') then begin
writeln('no pl admin username supplied');
Terminate;
halt(1);
end;
end;
procedure TFRE_CLISRV_APP._CheckUserSupplied;
begin
if (cG_OVERRIDE_USER='') then begin
writeln('no pl admin password supplied');
Terminate;
halt(1);
end;
end;
procedure TFRE_CLISRV_APP._CheckPassSupplied;
begin
if (cG_OVERRIDE_PASS='') then begin
writeln('no override/login password supplied');
Terminate;
halt(1);
end;
end;
procedure TFRE_CLISRV_APP._CheckNoCustomextensionsSet;
begin
if FCustomExtensionSet then begin
writeln('the custom extensions option is only allowed in conjunction with --deploy option.');
Terminate;
halt(1);
end;
end;
procedure TFRE_CLISRV_APP.DoRun;
var ErrorMsg : String;
procedure ParsePersistanceLayerParams;
begin
if cFRE_CONFIG_MODE then
begin
cFRE_PS_LAYER_USE_EMBEDDED := true;
end
else
begin
if HasOption('*','plhost') then begin
cFRE_PS_LAYER_HOST := GetOptionValue('*','plhost');
end;
if HasOption('*','plip') then begin
cFRE_PS_LAYER_IP := GetOptionValue('*','plip');
end;
if HasOption('*','plport') then begin
cFRE_PS_LAYER_PORT := GetOptionValue('*','plport');
end;
if HasOption('*','ple') then begin
cFRE_PS_LAYER_USE_EMBEDDED := true;
end;
end;
end;
procedure ParseExtensionsUserPassDB;
begin
if HasOption('e','extensions') then begin // has to be after possible recreate db
FChosenExtensionList := ListFromString(GetOptionValue('e','extensions'));
FCustomExtensionSet := True;
VerifyExtensions;
end;
if HasOption('u','user') then begin
cG_OVERRIDE_USER := GetOptionValue('u','user');
end;
if HasOption('p','pass') then begin
cG_OVERRIDE_PASS := GetOptionValue('p','pass');
end;
if HasOption('*','adminuser') then begin
cFRE_ADMIN_USER := GetOptionValue('*','adminuser');
end;
if HasOption('*','adminpass') then begin
cFRE_ADMIN_PASS := GetOptionValue('*','adminpass');
end;
if HasOption('*','pladmin') then begin
cFRE_PL_ADMIN_USER := GetOptionValue('*','pladmin');
end;
if HasOption('*','plpass') then begin
cFRE_PL_ADMIN_PASS := GetOptionValue('*','plpass');
end;
if HasOption('U','remoteuser') then begin
cFRE_REMOTE_USER := GetOptionValue('U','remoteuser');
end;
if HasOption('H','remotehost') then begin
cFRE_REMOTE_HOST:= GetOptionValue('H','remotehost');
end else begin
cFRE_REMOTE_HOST:= '127.0.0.1';
end;
if HasOption('d','database') then begin
FDBName := GetOptionValue('d','database');
end else begin
FDBName := 'ADMIN_DB';
end;
end;
procedure CheckTestLogging;
begin
if HasOption('*','testlog') then
CfgTestLog;
end;
procedure ParseSetConfigmode;
begin
if HasOption('c','config') then
begin
cFRE_CONFIG_MODE:=true;
if HasOption('*','datacenter') then
cFRE_DC_NAME := GetOptionValue('*','datacenter');
if HasOption('*','machine') then
cFRE_MACHINE_NAME := GetOptionValue('*','machine'); { for the config dialog }
//if HasOption('*','mac') then
// cFRE_MACHINE_MAC := GetOptionValue('*','mac');
if HasOption('*','ip') then { for the config dialog }
cFRE_MACHINE_IP := GetOptionValue('*','ip');
end;
end;
procedure ProcessInitRecreateOptions;
begin
if cFRE_CONFIG_MODE then
begin
cG_OVERRIDE_USER := 'admin@system';
cG_OVERRIDE_PASS := 'admin';
if not FCustomExtensionSet then
raise EFRE_DB_Exception.Create(edb_ERROR,'using config mode requires the use of an EXTENSION, use -e option!');
GDBPS_TRANS_WRITE_THROUGH := FALSE;
GDISABLE_SYNC := TRUE;
GDBPS_SKIP_STARTUP_CHECKS := FALSE;
ReCreateSysDB;
ReCreateDB;
DeployDatabaseScheme('CONFIG');
//GDBPS_TRANS_WRITE_THROUGH := false;
//GDISABLE_SYNC := false;
writeln('INIT EXTENSIONS');
InitExtensions;
writeln('INIT EXTENSIONS DONE');
end
else
begin
GFRE_DB_PS_LAYER.ForceRestoreIfNeeded;
if HasOption('y','forcesysdb') then
begin
FOnlyInitDB:=true;
ReCreateSysDB;
end;
if HasOption('x','forcedb') then
begin
FOnlyInitDB:=true;
ReCreateDB;
end;
if HasOption('D','deploy') then
begin
FOnlyInitDB := true;
DeployDatabaseScheme(GetOptionValue('D','deploy'));
end;
if HasOption('i','init') then
begin
if GetOptionValue('i','init')='fast' then
begin
writeln('WRITE BACK MODE ACTIVATED');
GDBPS_TRANS_WRITE_THROUGH := false;
GDISABLE_SYNC := false;
end;
FOnlyInitDB:=true;
InitExtensions;
GFRE_DB_PS_LAYER.SyncSnapshot;
end;
if HasOption('t','testdata') then
begin
FOnlyInitDB:=true;
GenerateTestdata;
end;
if HasOption('r','remove') then
begin
FOnlyInitDB:=true;
RemoveExtensions;
Terminate;
Exit;
end;
if HasOption('*','unittests') then
begin
FOnlyInitDB:=true;
DoUnitTest;
Terminate;
exit;
end;
end;
end;
procedure SetupDBSchemeAndExtensions;
var fdbs : IFRE_DB_Object;
res : TFRE_DB_Errortype;
begin
res := GFRE_DB_PS_LAYER.GetDatabaseScheme(fdbs);
if res = edb_OK then
begin
GFRE_DB.SetDatabasescheme(fdbs);
FChosenExtensionList := ListFromString(GFRE_DB.GetDeployedExtensionlist);
RegisterExtensions;
GFRE_DB.InstantiateApplicationObjectsAndRecordModules;
GFRE_DB.LogInfo(dblc_SERVER,'SERVING SYSTEM DATABASE : [%s]',[GFRE_DB.GetDeploymentInfo]);
writeln(format('SERVING SYSTEM DATABASE : [%s]',[GFRE_DB.GetDeploymentInfo]));
if FCustomExtensionSet and (not cFRE_CONFIG_MODE) then
writeln('WARNING: ignoring specified extensions from commandline, they are only used for the deploy case');
end
else
raise EFRE_DB_Exception.Create(edb_ERROR,'could not fetch the database scheme [%s] ',[res.Msg]);
end;
procedure SetupSystemConnection;
var res : TFRE_DB_Errortype;
begin
FSystemConnection := GFRE_DB.NewDirectSysConnection;
res := FSystemConnection.Connect(cFRE_ADMIN_USER,cFRE_ADMIN_PASS,true);
if res<>edb_OK then begin
FSystemConnection.Free;
FSystemConnection := nil;
GFRE_DB.LogError(dblc_SERVER,'SERVING SYSTEM DATABASE failed due to [%s]',[CFRE_DB_Errortype[res]]);
GFRE_BT.CriticalAbort('CANNOT SERVE SYSTEM DB [%s]',[CFRE_DB_Errortype[res]]);
end;
end;
begin
AddCommandLineOptions;
ErrorMsg:=CheckOptions(GetShortCheckOptions,FLongOpts.AsTStrings);
if ErrorMsg<>'' then begin
writeln(ErrorMsg);
WriteHelp;
Terminate;
Exit;
end;
GDBPS_TRANS_WRITE_THROUGH := TRUE;
GDISABLE_SYNC := TRUE;
GDBPS_SKIP_STARTUP_CHECKS := FALSE;
ParseSetConfigmode;
ParsePersistanceLayerParams;
if PreStartupTerminatingCommands then
halt(0);
ParseSetSystemFlags;
ParseExtensionsUserPassDB;
Initialize_Read_FRE_CFG_Parameter(true);
writeln('SERVER DB DIR : ',cFRE_SERVER_DEFAULT_DIR);
writeln('SERVER WWW ROOT : ',cFRE_SERVER_WWW_ROOT_DIR);
if AfterConfigStartupTerminatingCommands then
halt(0);
PrepareStartup; { The initial startup is done (connections can be made, but no extensions initialized }
CheckTestLogging; { CFG File reading done}
DebugTestProcedure;
if AfterStartupTerminatingCommands then
begin
OrderedShutDown;
exit;
end;
ProcessInitRecreateOptions;
SetupDBSchemeAndExtensions;
if AfterInitDBTerminatingCommands then
begin
Terminate;
exit;
end;
if not FOnlyInitDB then
SetupSystemConnection;
if AfterSysDBConnectTerminatingCommands then
begin
Terminate;
exit;
end;
if HasOption('*','dontstart')
or FOnlyInitDB then
begin
Terminate;
exit;
end;
FBaseServer := TFRE_BASE_SERVER.create(FDBName);
FBaseServer.Setup(FSystemConnection);
if not Terminated then
GFRE_SC.RunUntilTerminate;
OrderedShutDown;
end;
procedure TFRE_CLISRV_APP.OrderedShutDown;
begin
Teardown_APS_Comm;
Terminate;
FBaseServer.Free;
GFRE_DB_PS_LAYER.Finalize;
Cleanup_SSL_CMD_CA_Interface;
FinalizeTransformManager;
GFRE_BT.DeactivateJack;
end;
procedure TFRE_CLISRV_APP.DebugTestProcedure;
begin
//RangeManager_TestSuite;
//sleep(2000);
//halt;
end;
function TFRE_CLISRV_APP.PreStartupTerminatingCommands:boolean;
begin
result := false;
if cFRE_CONFIG_MODE then
exit;
if HasOption('Z','calcsha') then
begin
result := true;
CalcSHA1(GetOptionValue('Z','calcsha'));
end;
if HasOption('*','printtz') then
begin
result := true;
PrintTimeZones;
end;
if HasOption('h','help') then
begin
result := true;
WriteHelp;
end;
if HasOption('v','version') then
begin
result := true;
WriteVersion;
end;
if HasOption('l','list') then
begin
result := true;
ListExtensions;
end;
end;
function TFRE_CLISRV_APP.AfterConfigStartupTerminatingCommands: boolean;
begin
result := false;
if cFRE_CONFIG_MODE then
exit;
if HasOption('*','testlogcfg') then
EndlessLogTest;
if HasOption('*','resetadmin') then
cFRE_DB_RESET_ADMIN:=true;
end;
function TFRE_CLISRV_APP.AfterStartupTerminatingCommands: boolean; { if true then shutdown, don't start }
begin
result := false;
if HasOption('*','dbo2json') then
begin
result := true;
ConvertDbo(GetOptionValue('*','dbo2json'),true);
end;
if HasOption('*','json2dbo') then
begin
result := true;
ConvertDbo(GetOptionValue('*','json2dbo'),false);
end;
if HasOption('*','restoredb') then
begin
result := true;
RestoreDB(true,true,GetOptionValue('*','restoredb'),false);
end;
if HasOption('*','restoredbsch') then
begin
result := true;
RestoreDB(true,true,GetOptionValue('*','restoredbsch'),true);
end;
end;
function TFRE_CLISRV_APP.AfterInitDBTerminatingCommands: boolean;
begin
result := false;
if HasOption('A','adduser') then
begin
result:=true;
AddUser(GetOptionValue('A','adduser'));
end;
if HasOption('*','showinstalled') then
begin
result := true;
ShowVersions;
end;
if HasOption('*','showrights') then
begin
result := true;
ShowRights;
end;
if HasOption('g','graph') then
begin
result := true;
SchemeDump(GetOptionValue('g','graph'),GetOptionValue('*','classfile'));
end;
if HasOption('z','testdump') then
begin
result := true;
DumpAll(GetOptionValue('z','testdump'));
end;
if HasOption('o','overviewdump') then
begin
result := true;
OverviewDump;
end;
if HasOption('*','backupdb') then
begin
result := true;
BackupDB(true,true,GetOptionValue('*','backupdb'));
end;
if HasOption('*','backupsys') then
begin
result := true;
BackupDB(false,true,GetOptionValue('*','backupsys'));
end;
if HasOption('*','backupapp') then
begin
result := true;
BackupDB(true,false,GetOptionValue('*','backupapp'));
end;
if HasOption('*','dumpdbo') then
begin
result := true;
DumpDBO(GetOptionValue('*','dumpdbo'));
end;
if HasOption('*','expandrefs') then
begin
result := true;
ExpandReferences(GetOptionValue('*','expandrefs'));
end;
end;
function TFRE_CLISRV_APP.AfterSysDBConnectTerminatingCommands: boolean;
begin
result := false;
if HasOption('*','showapps') then
begin
result := true;
ShowApps;
end;
if HasOption('*','showscheme') then
begin
result := true;
DumpScheme(GetOptionValue('*','showscheme'));
end;
if HasOption('*','showdeploy') then
begin
result := true;
ShowDeploy;
end;
if HasOption('*','showfeatures') then
begin
result := true;
ShowFeatures;
end;
if HasOption('*','enablefeature') then
begin
result := true;
EnableDisableFeature(GetOptionValue('enablefeature'),true);
end;
if HasOption('*','disablefeature') then
begin
result := true;
EnableDisableFeature(GetOptionValue('disablefeature'),false);
end;
end;
procedure TFRE_CLISRV_APP.PrintTimeZones;
var cnt : NativeInt;
sl : TStringlist;
procedure PrintTZ(const zonename, timezoneletters : String ; const sec_offset,fixed_offset : integer ; const valid_to_year,valid_to_month,valid_to_day,valid_to_secs_in_day:Integer ; const valid_until_gmt : boolean);
begin
inc(cnt);
writeln(cnt:3,':',zonename:12,' ',timezoneletters:12,' offset ',sec_offset,' fixed ',fixed_offset,' valid until ',valid_to_year,':',valid_to_month,':',valid_to_day,':',valid_to_secs_in_day,' until GMT ',valid_until_gmt);
end;
begin
cnt:=0;
GFRE_DT.ForAllTimeZones(@PrintTZ,true);
writeln('----');
sl:=TStringList.Create;
try
GFRE_DT.GetTimeZoneNames(sl);
writeln(sl.Text);
finally
sl.free;
end;
end;
procedure TFRE_CLISRV_APP.WriteHelp;
var
i: NativeInt;
begin
WriteVersion;
writeln('Usage: ',ExtractFileName(ExeName),' [OPTIONS]');
writeln(' OPTIONS');
for i := 0 to FHelpOpts.Count-1 do
writeln(FHelpOpts[i]);
end;
procedure TFRE_CLISRV_APP.WriteVersion;
begin
writeln('');
writeln('---');
writeln(GFOS_VHELP_GET_VERSION_STRING);
writeln('---');
writeln('Default style : ',FDefaultStyle);
writeln('---');
writeln('');
end;
function TFRE_CLISRV_APP.GetActiveDatabaseConnection: IFRE_DB_CONNECTION;
begin
_CheckDBNameSupplied;
_CheckAdminUserSupplied;
_CheckAdminPassSupplied;
if cG_OVERRIDE_USER='' then
cG_OVERRIDE_USER:=cFRE_ADMIN_USER;
if cG_OVERRIDE_PASS='' then
cG_OVERRIDE_PASS:=cFRE_ADMIN_PASS;
result := GFRE_DBI.NewConnection;
CheckDbResult(result.Connect(FDBName,cG_OVERRIDE_USER,cG_OVERRIDE_PASS),'cannot connect db');
end;
procedure TFRE_CLISRV_APP.ReCreateDB;
var conn : IFRE_DB_CONNECTION;
begin
_CheckDBNameSupplied;
_CheckAdminUserSupplied;
_CheckAdminPassSupplied;
if GFRE_DB_PS_LAYER.DatabaseExists(FDBName) then
begin
writeln('>DROP USER DB '+FDBName);
CheckDbResult(GFRE_DB_PS_LAYER.DeleteDatabase(FDBName,cFRE_PL_ADMIN_USER,cFRE_PL_ADMIN_PASS),'DELETE DB FAILED : '+FDBName);
writeln('>USER DB '+FDBName+' DROPPED');
end;
writeln('>CREATE USER DB '+FDBName);
CheckDbResult(GFRE_DB_PS_LAYER.CreateDatabase(FDBName,cFRE_PL_ADMIN_USER,cFRE_PL_ADMIN_PASS),'CREATE DB FAILED : '+FDBName);
writeln('>USER DB '+FDBName+' CREATED');
writeln('>CONNECT USER DB '+FDBName);
CONN := GFRE_DBI.NewConnection;
CheckDbResult(CONN.Connect(FDBName,cG_OVERRIDE_USER,cG_OVERRIDE_PASS),'cannot connect user db'); { initial admin (!) }
writeln('>USER DB '+FDBName+' CONNECTED,DEFAULT COLLECTION INITIALIZED,DONE');
end;
procedure TFRE_CLISRV_APP.ReCreateSysDB;
var conn : IFRE_DB_SYS_CONNECTION;
begin
_CheckAdminUserSupplied;
_CheckAdminPassSupplied;
if GFRE_DB_PS_LAYER.DatabaseExists('SYSTEM') then
begin
writeln('>DROP SYSTEM DB');
CheckDbResult(GFRE_DB_PS_LAYER.DeleteDatabase('SYSTEM',cFRE_PL_ADMIN_USER,cFRE_PL_ADMIN_PASS),'DELETE SYSTEM DB FAILED');
writeln('>SYSTEM DB DROPPED');
end;
writeln('>CREATE SYSTEM DB');
CheckDbResult(GFRE_DB_PS_LAYER.CreateDatabase('SYSTEM',cFRE_PL_ADMIN_USER,cFRE_PL_ADMIN_PASS),'CREATE SYSTEM DB FAILED');
writeln('>SYSTEM DB CREATED');
writeln('>CONNECT SYSTEM DB');
GFRE_DB.Initialize_Extension_ObjectsBuild;
CONN := GFRE_DBI.NewSysOnlyConnection;
CheckDbResult(CONN.Connect('admin@system','admin'),'cannot connect system db'); { initial admin (!) }
conn.Finalize;
cG_OVERRIDE_USER:='admin@system';
cG_OVERRIDE_PASS:='admin';
writeln('>SYSTEM CONNECTED, DEFAULT COLLECTIONS INITIALIZED, DONE');
end;
procedure TFRE_CLISRV_APP.BackupDB(const adb,sdb:boolean ; const dir: string);
var s : string;
conn : IFRE_DB_CONNECTION;
scon : IFRE_DB_SYS_CONNECTION;
res : TFRE_DB_Errortype;
sfs : TFileStream;
dbfs : TFileStream;
sysfn : String;
dbfn : String;
schfn : String;
fdbs : IFRE_DB_Object;
procedure ProgressCB(const phase,detail,header : ShortString ; const cnt,max: integer);
var outs :string;
begin
if header<>'' then
begin
writeln(header);
exit;
end;
WriteStr(outs,' > ',phase,' [',detail,'] : ',cnt,'/',max,' Items',' ');
write(outs);
if cnt<>max then
begin
write(StringOfChar(#8,length(outs)));
end
else
begin
writeln;
end;
if FLimittransfer>0 then
sleep(FLimittransfer);
end;
procedure SaveScheme;
var sch : TFRE_DB_String;
f : TFileStream;
begin
write('FETCHING SERVER DATABASE SCHEME ');
res := GFRE_DB_PS_LAYER.GetDatabaseScheme(fdbs);
if res<>edb_OK then
begin
writeln(' ['+CFRE_DB_Errortype[res]+']');
abort;
end;
write('DONE');
sch := fdbs.GetAsJSONString(false,true);
f := TFileStream.Create(schfn,fmCreate+fmOpenWrite);
try
FREDB_StringWrite2Stream(sch,f);
finally
f.Free;
end;
end;
begin
_CheckDBNameSupplied;
_CheckAdminUserSupplied;
_CheckAdminPassSupplied;
ForceDirectories(dir);
if not DirectoryExists(dir) then
begin
writeln('cannot backup / could not create directory ['+dir+'] !');
abort;
end;
if adb and not sdb then
writeln('Backup of Database ['+FDBName+'] into ['+dir+'] (y/N)');
if sdb and not adb then
writeln('Backup of SYSTEM DB into ['+dir+'] (y/N)');
if adb and sdb then
writeln('Backup of Database ['+FDBName+'] + [SYSTEM DB] into ['+dir+'] (y/N)');
ReadLn(s);
//s:='y';
if s='y' then
begin
sysfn := dir+DirectorySeparator+'sys.fdbb';
dbfn := dir+DirectorySeparator+'usr.fdbb';
schfn := dir+DirectorySeparator+'sch.fdbb';
write('CONNECTING ['+FDBName+'] ');
if adb then
begin
conn := GFRE_DBI.NewConnection;
res := conn.Connect(FDBName,cFRE_ADMIN_USER,cFRE_ADMIN_PASS);
end
else
begin
scon := GFRE_DBI.NewSysOnlyConnection;
res := scon.Connect(cFRE_ADMIN_USER,cFRE_ADMIN_PASS);
end;
if res<>edb_OK then
begin
writeln(res.AsString);
abort;
end;
writeln('OK');
SaveScheme;
if sdb then
begin
write('Opening file :'+sysfn);
try
sfs := TFileStream.Create(sysfn,fmCreate+fmShareExclusive);
except
writeln('FAILED');
abort;
end;
writeln(' OK');
end
else
sfs := nil;
if adb then
begin
write('Opening file :'+dbfn);
try
dbfs := TFileStream.Create(dbfn,fmCreate+fmShareExclusive);
except
writeln('FAILED');
abort;
end;
writeln(' OK');
end
else
dbfs := nil;
if adb then
conn.SYS.BackupDatabaseReadable(sfs,dbfs,@ProgressCB,cFRE_PL_ADMIN_USER,cFRE_PL_ADMIN_PASS)
else
scon.BackupDatabaseReadable(sfs,nil,@ProgressCB,cFRE_PL_ADMIN_USER,cFRE_PL_ADMIN_PASS);
end
else
begin
writeln('ABORTED');
end;
end;
procedure TFRE_CLISRV_APP.RestoreDB(const adb, sdb: boolean; const dir: string; const override_with_live_scheme: boolean);
var s : string;
conn : IFRE_DB_CONNECTION;
scon : IFRE_DB_SYS_CONNECTION;
res : TFRE_DB_Errortype;
sfs : TFileStream;
dbfs : TFileStream;
sysfn : String;
dbfn : String;
schfn : string;
procedure ProgressCB(const phase,detail,header : ShortString ; const cnt,max: integer);
var outs :string;
begin
if header<>'' then
begin
writeln(header);
exit;
end;
WriteStr(outs,' > ',phase,' [',detail,'] : ',cnt,'/',max,' Items',' ');
write(outs);
if cnt<>max then
begin
write(StringOfChar(#8,length(outs)));
end
else
begin
writeln;
end;
if FLimittransfer>0 then
sleep(FLimittransfer);
end;
procedure CheckExistUserDB;
begin
if not FileExists(dbfn) then
begin
writeln('the user databasefile does not exist['+dbfn+'] !');
abort;
end;
end;
procedure CheckExistSysDB;
begin
if not FileExists(sysfn) then
begin
writeln('the system databasefile does not exist['+sysfn+'] !');
abort;
end;
end;
procedure CheckScheme;
begin
if override_with_live_scheme then
exit;
if not FileExists(schfn) then
begin
writeln('the scheme databasefile does not exist['+schfn+'] !');
abort;
end;
end;
procedure LoadScheme;
var fdbs : IFRE_DB_Object;
f : TFileStream;
//function ReadElement : TFRE_DB_Object;
//var line : TFRE_DB_String;
// elem : Byte;
// count : Integer;
// pos : integer;
//begin
// pos := 1;
// repeat
// elem := f.ReadByte;
// inc(pos);
// if char(elem)<>'C' then begin
// line := line + char(elem);
// end else break;
// until false;
// count := StrToInt(line);
// SetLength(line,count-2);
// f.ReadBuffer(line[1],count-2);
// f.ReadByte;f.ReadByte;
// result := TFRE_DB_Object.CreateFromJSONString(line);
//end;
function ReadElement : TFRE_DB_Object;
begin
result := FREDB_ReadJSONEncodedObject(f).Implementor as TFRE_DB_Object;
end;
begin
f := TFileStream.Create(schfn,fmOpenRead);
try
fdbs := ReadElement;
finally
f.Free;
end;
writeln('SETTING SCHEME');
GFRE_DB.SetDatabasescheme(fdbs);
writeln('REGISTER EXTENSIONS : ',GFRE_DB.GetDeployedExtensionlist);
FChosenExtensionList := ListFromString(GFRE_DB.GetDeployedExtensionlist);
writeln('REGISTER EXTENSIONS DONE');
RegisterExtensions;
writeln('SETTING SCHEME DONE');
end;
begin
_CheckDBNameSupplied;
_CheckAdminUserSupplied;
_CheckAdminPassSupplied;
sysfn := dir+DirectorySeparator+'sys.fdbb';
dbfn := dir+DirectorySeparator+'usr.fdbb';
schfn := dir+DirectorySeparator+'sch.fdbb';
if not DirectoryExists(dir) then
begin
writeln('the backup directory does not exist['+dir+'] !');
abort;
end;
if adb and not sdb then
begin
CheckExistUserDB;
CheckScheme;
writeln('Restore of database ['+FDBName+'] (y/N)');
end;
if sdb and not adb then
begin
CheckExistSysDB;
CheckScheme;
writeln('Restore of SYSTEM DB (y/N)');
end;
if adb and sdb then
begin
CheckExistUserDB;
CheckExistSysDB;
CheckScheme;
writeln('Restore backup as database ['+FDBName+'] + [SYSTEM DB] (y/N)');
end;
ReadLn(s);
//s:='y'; // ignore force lazarusdebug
if s='y' then
begin
if override_with_live_scheme then
begin
writeln('INTERNAL BUILDING SCHEMES');
GFRE_DB.Initialize_Extension_ObjectsBuild;
end
else
begin
writeln('LOADING DB METADATA SCHEMES');
LoadScheme;
end;
write('RECREATING / CONNECTING ['+FDBName+'] ');
if adb then
begin
GFRE_DB_PS_LAYER.DeleteDatabase('SYSTEM',cFRE_PL_ADMIN_USER,cFRE_PL_ADMIN_PASS);
GFRE_DB_PS_LAYER.DeleteDatabase(FDBName,cFRE_PL_ADMIN_USER,cFRE_PL_ADMIN_PASS);
CheckDbResult(GFRE_DB_PS_LAYER.CreateDatabase('SYSTEM',cFRE_PL_ADMIN_USER,cFRE_PL_ADMIN_PASS));
CheckDbResult(GFRE_DB_PS_LAYER.CreateDatabase(FDBName,cFRE_PL_ADMIN_USER,cFRE_PL_ADMIN_PASS));
conn := GFRE_DBI.NewConnection;
res := conn.Connect(FDBName,'admin@system','admin');
end
else
begin
scon := GFRE_DBI.NewSysOnlyConnection;
res := scon.Connect('admin@system','admin');
end;
if res<>edb_OK then
begin
writeln(res.AsString);
abort;
end;
writeln('OK');
if sdb then
begin
write('Opening file :'+sysfn);
try
sfs := TFileStream.Create(sysfn,fmOpenRead+fmShareExclusive);
except
writeln('FAILED');
abort;
end;
writeln(' OK');
end
else
sfs := nil;
if adb then
begin
dbfn := dir+DirectorySeparator+'usr.fdbb';
write('Opening file :'+dbfn);
try
dbfs := TFileStream.Create(dbfn,fmOpenRead+fmShareExclusive);
except
writeln('FAILED');
abort;
end;
writeln(' OK');
end
else
dbfs := nil;
if adb then
CheckDbResult(conn.SYS.RestoreDatabaseReadable(sfs,dbfs,FDBName,@ProgressCB,cFRE_PL_ADMIN_USER,cFRE_PL_ADMIN_PASS))
else
CheckDbResult(scon.RestoreDatabaseReadable(sfs,nil,'',@ProgressCB,cFRE_PL_ADMIN_USER,cFRE_PL_ADMIN_PASS));
CheckDbResult(GFRE_DB_PS_LAYER.DeployDatabaseScheme(GFRE_DB.GetDatabasescheme,cFRE_PL_ADMIN_USER,cFRE_PL_ADMIN_PASS));
end
else
begin
writeln('ABORTED');
end;
end;
procedure TFRE_CLISRV_APP.AddUser(const userencoding: string);
var param : TFRE_DB_StringArray;
conn : IFRE_DB_SYS_CONNECTION;
username : TFRE_DB_String;
domain : TFRE_DB_String;
domuid : TFRE_DB_GUID;
pass : TFRE_DB_String;
uclass : TFRE_DB_String;
internal : boolean;
begin
FREDB_SeperateString(userencoding,',',param); { must be username@domain, password, class}
if Length(param)<>3 then
begin
writeln('syntax error, must have 3 parameters');
exit;
end;
username := param[0];
pass := param[1];
uclass := uppercase(param[2]);
case uclass of
'FEEDER','MIGHTYFEEDER' : internal := true;
'WEBUSER' : internal := false;
else
raise EFRE_DB_Exception.Create(edb_ERROR,'userclass must be WEBUSER or FEEDER');
end;
FREDB_SplitLocalatDomain(username,username,domain);
try
conn := GFRE_DBI.NewSysOnlyConnection;
CheckDbResult(conn.Connect(cFRE_ADMIN_USER,cFRE_ADMIN_PASS));
domuid := conn.GetCurrentUserTokenRef.GetDomainID(domain);
GFRE_DB.Initialize_Extension_ObjectsBuild;
CheckDbResult(conn.AddUser(username,domuid,pass,'Auto','Auto',nil,'',internal,'cli added user','cli added user',uclass));
finally
conn.Finalize;
end;
end;
procedure TFRE_CLISRV_APP.GenerateTestdata;
var
conn : IFRE_DB_CONNECTION;
domainId : TFRE_DB_Guid;
res : TFRE_DB_Errortype;
fdbs : IFRE_DB_Object;
begin
_CheckDBNameSupplied;
_CheckAdminUserSupplied;
_CheckAdminPassSupplied;
if not FDeployed then
_CheckNoCustomextensionsSet;
res := GFRE_DB_PS_LAYER.GetDatabaseScheme(fdbs);
if res = edb_OK then
begin
GFRE_DB.SetDatabasescheme(fdbs);
FChosenExtensionList := ListFromString(GFRE_DB.GetDeployedExtensionlist);
RegisterExtensions;
GFRE_DB.InstantiateApplicationObjectsAndRecordModules;
end;
{ a testdomain is created globally for all extensiosn}
conn := GFRE_DBI.NewConnection;
try
CheckDbResult(conn.Connect(FDBName,cG_OVERRIDE_USER,cG_OVERRIDE_PASS),' could not login into '+FDBName+' for testdomain creation');
if not conn.SYS.DomainExists('test') then begin
CheckDbResult(conn.AddDomain('test','This domain is for testing only','Test Domain'));
end;
domainId:=conn.SYS.DomainID('test');
if not conn.SYS.UserExists('admin',domainId) then begin
CheckDbResult(conn.SYS.AddUser('admin',domainId,'test','admin','test'));
end;
if not conn.SYS.UserExists('manager',domainId) then begin
CheckDbResult(conn.SYS.AddUser('manager',domainId,'test','manager','test'));
end;
if not conn.SYS.UserExists('viewer',domainId) then begin
CheckDbResult(conn.SYS.AddUser('viewer',domainId,'test','viewer','test'));
end;
finally
conn.Finalize;
end;
GFRE_DBI_REG_EXTMGR.GenerateTestData4Exts(FChosenExtensionList,FDBName,cG_OVERRIDE_USER,cG_OVERRIDE_PASS);
end;
procedure TFRE_CLISRV_APP.DoUnitTest;
var conn : IFRE_DB_SYS_CONNECTION;
begin
_CheckDBNameSupplied;
_CheckAdminUserSupplied;
_CheckAdminPassSupplied;
GFRE_DBI_REG_EXTMGR.GenerateUnitTestsdata(FChosenExtensionList,FDBName,cG_OVERRIDE_USER,cG_OVERRIDE_PASS);
end;
procedure TFRE_CLISRV_APP.InitExtensions;
var conn : IFRE_DB_CONNECTION;
res : TFRE_DB_Errortype;
fdbs : IFRE_DB_Object;
begin
_CheckDBNameSupplied;
_CheckAdminUserSupplied;
_CheckAdminPassSupplied;
if not FDeployed then
_CheckNoCustomextensionsSet;
res := GFRE_DB_PS_LAYER.GetDatabaseScheme(fdbs);
if res = edb_OK then
GFRE_DB.SetDatabasescheme(fdbs)
else
begin
writeln('Could not get the databasescheme ['+CFRE_DB_Errortype[res]+'], you need to deploy first');
abort;
end;
writeln('INITIALIZING DATABASE FOR EXTENSIONS : '+GFRE_DB.GetDeploymentInfo);
GDBPS_DISABLE_NOTIFY := true;
FChosenExtensionList := ListFromString(GFRE_DB.GetDeployedExtensionlist);
RegisterExtensions;
CONN := GFRE_DBI.NewConnection;
CheckDbResult(CONN.Connect(FDBName,cG_OVERRIDE_USER,cG_OVERRIDE_PASS),'cannot connect db');
GFRE_DB.InstantiateApplicationObjectsAndRecordModules;
GFRE_DBI.DBInitializeAllSystemClasses(conn);
GFRE_DBI.DBInitializeAllExClasses(conn);
conn.Finalize;
GFRE_DBI_REG_EXTMGR.InitDatabase4Extensions(FChosenExtensionList,FDBName,cG_OVERRIDE_USER,cG_OVERRIDE_PASS);
GDBPS_DISABLE_NOTIFY := false;
end;
procedure TFRE_CLISRV_APP.ShowVersions;
var conn : IFRE_DB_SYS_CONNECTION;
begin
_CheckDBNameSupplied;
_CheckAdminUserSupplied;
_CheckAdminPassSupplied;
CONN := GFRE_DBI.NewSysOnlyConnection;
CheckDbResult(CONN.Connect(cG_OVERRIDE_USER,cG_OVERRIDE_PASS),'cannot connect system db');
writeln(conn.GetClassesVersionDirectory.DumpToString);
conn.Finalize;
end;
procedure TFRE_CLISRV_APP.ShowRights;
var conn : IFRE_DB_SYS_CONNECTION;
begin
_CheckUserSupplied;
_CheckPassSupplied;
CONN := GFRE_DBI.NewSysOnlyConnection;
CheckDbResult(CONN.Connect(cG_OVERRIDE_USER,cG_OVERRIDE_PASS),'cannot connect system db');
writeln(conn.DumpUserRights);
conn.Finalize;
end;
procedure TFRE_CLISRV_APP.ShowApps;
var apa : TFRE_DB_APPLICATION_ARRAY;
i : integer;
begin
writeln('AVAILABLE APPS:');
apa := GFRE_DB.GetApps;
for i:=0 to high(apa) do
begin
writeln(i,' : ',apa[i].AppClassName,' ',apa[i].ObjectName);
end;
end;
procedure TFRE_CLISRV_APP.ShowDeploy;
begin
exit; { deploy info is written on start in any case }
end;
procedure TFRE_CLISRV_APP.DumpScheme(const scheme: shortstring);
var so : TFRE_DB_SchemeObject;
begin
if scheme='' then
begin
writeln(GFRE_DB.GetDatabasescheme.DumpToString);
end
else
begin
if GFRE_DB.GetSysScheme(scheme,so) then
writeln(so.DumpToString)
else
writeln('Scheme [',scheme,'] not found');
end;
end;
procedure TFRE_CLISRV_APP.RemoveExtensions;
begin
_CheckDBNameSupplied;
_CheckAdminUserSupplied;
_CheckAdminPassSupplied;
writeln('Remove apps for extensions :'+uppercase(FChosenExtensionList.Commatext));
GFRE_DBI_REG_EXTMGR.Remove4Extensions(FChosenExtensionList,FDBName,cG_OVERRIDE_USER,cG_OVERRIDE_PASS);
end;
procedure TFRE_CLISRV_APP.RegisterExtensions;
begin
FRE_DBBASE.Register_DB_Extensions;
GFRE_DBI_REG_EXTMGR.RegisterExtensions4DB(FChosenExtensionList);
FRE_BASE_SERVER.RegisterLogin;
end;
procedure TFRE_CLISRV_APP.DeployDatabaseScheme(deploy_revision: string);
var extl : string;
begin
_CheckDBNameSupplied;
_CheckAdminUserSupplied;
_CheckAdminPassSupplied;
CheckDbResult(GFRE_DB.ClearSystemSchemes);
RegisterExtensions;
extl := FChosenExtensionList.Commatext;
if extl='' then
begin
writeln('you have to choose some extensions to deploy');
abort;
end;
if deploy_revision='' then
deploy_revision:=GetEnvironmentVariable('LOGNAME')+'/'+ApplicationName;
writeln('>BUILDING METADATA SCHEMES : ',extl);
GFRE_DB.Initialize_Extension_ObjectsBuild;
GFRE_DB.SetupDeploymentInfo(extl,deploy_revision);
writeln('>BUILDING SCHEME DONE');
writeln('>DEPLOYING SCHEME');
CheckDbResult(GFRE_DB_PS_LAYER.DeployDatabaseScheme(GFRE_DB.GetDatabasescheme,cFRE_PL_ADMIN_USER,cFRE_PL_ADMIN_PASS));
writeln('>METADATA DEPLOYMENT DONE');
writeln(GFRE_DB.GetDeploymentInfo);
FDeployed := true;
end;
procedure TFRE_CLISRV_APP.VerifyExtensions;
var i : integer;
FCleanList : IFOS_STRINGS;
begin
FCleanList := GFRE_TF.Get_FOS_Strings;
for i:=0 to FChosenExtensionList.Count-1 do begin
if FAvailExtensionList.IndexOf(FChosenExtensionList[i])>-1 then begin
FCleanList.Add(uppercase(FChosenExtensionList[i]));
end else begin
writeln('ignoring invalid extension : ',FChosenExtensionList[i]);
end;
end;
FChosenExtensionList := FCleanList;
end;
procedure TFRE_CLISRV_APP.ListExtensions;
begin
writeln('Available Extensions:');
writeln(FAvailExtensionList.Commatext);
writeln('Chosen Extensions:');
writeln(FChosenExtensionList.Commatext);
end;
procedure TFRE_CLISRV_APP.PrepareStartup;
begin
Setup_SSL_CMD_CA_Interface;
Setup_APS_Comm;
InitMinimal;
if cFRE_PS_LAYER_USE_EMBEDDED then
begin
GFRE_DB_PS_LAYER := Get_PersistanceLayer_PS_Simple(cFRE_SERVER_DEFAULT_DIR+DirectorySeparator+'db')
//GFRE_DB_P.S_LAYER := Get_PersistanceLayer_PS_Net(cFRE_PS_LAYER_HOST,cFRE_PS_LAYER_IP,cFRE_PS_LAYER_PORT,true);
end
else
GFRE_DB_PS_LAYER := Get_PersistanceLayer_PS_Net(cFRE_PS_LAYER_HOST,cFRE_PS_LAYER_IP,cFRE_PS_LAYER_PORT,false);
InitTransfromManager;
Init4Server;
GFRE_DBI.LocalZone := cFRE_SERVER_DEFAULT_TIMEZONE;
end;
procedure TFRE_CLISRV_APP.CfgTestLog;
procedure Setup_HTTP_Request_Logging;
begin
GFRE_Log.AddRule(CFRE_DB_LOGCATEGORY[dblc_HTTP_ZIP],fll_Debug,'*',flra_DropEntry);
GFRE_Log.AddRule(CFRE_DB_LOGCATEGORY[dblc_HTTP_CACHE],fll_Debug,'*',flra_DropEntry);
GFRE_Log.AddRule(CFRE_DB_LOGCATEGORY[dblc_HTTP_REQ],fll_Info,'*',flra_DropEntry);
GFRE_Log.AddRule(CFRE_DB_LOGCATEGORY[dblc_HTTP_REQ],fll_Debug,'*',flra_DropEntry);
GFRE_Log.AddRule(CFRE_DB_LOGCATEGORY[dblc_HTTP_RES],fll_Info,'*',flra_DropEntry);
GFRE_Log.AddRule(CFRE_DB_LOGCATEGORY[dblc_HTTP_RES],fll_Debug,'*',flra_DropEntry);
end;
procedure Setup_DB_Logging;
begin
GFRE_Log.AddRule(CFRE_DB_LOGCATEGORY[dblc_DB],fll_Debug,'*',flra_DropEntry);
//GFRE_Log.AddRule(CFRE_DB_LOGCATEGORY[dblc_DB],fll_Warning,'*',flra_DropEntry);
end;
procedure Setup_Server_Logging;
begin
//GFRE_Log.AddRule(CFRE_DB_LOGCATEGORY[dblc_SERVER],fll_Debug,'*',flra_DropEntry); // DROP : Server / DEBUG
//GFRE_Log.AddRule(CFRE_DB_LOGCATEGORY[dblc_SERVER_DATA],fll_Debug,'*',flra_DropEntry);// DROP : Server / Dispatch / Input Output
//GFRE_Log.AddRule(CFRE_DB_LOGCATEGORY[dblc_SERVER],fll_Info,'*',flra_DropEntry); // DROP : Server / INFO
//GFRE_Log.AddRule(CFRE_DB_LOGCATEGORY[dblc_SERVER],fll_Notice,'*',flra_DropEntry); // DROP : Server / NOTICE
end;
procedure Setup_WS_Session_Logging;
begin
GFRE_Log.AddRule(CFRE_DB_LOGCATEGORY[dblc_WEBSOCK],fll_Debug,'*',flra_DropEntry); // DROP : Websock / JSON / IN / OUT
GFRE_Log.AddRule(CFRE_DB_LOGCATEGORY[dblc_WS_JSON],fll_Debug,'*',flra_DropEntry); // DROP : JSON
GFRE_Log.AddRule(CFRE_DB_LOGCATEGORY[dblc_SESSION],fll_Debug,'*',flra_DropEntry); // DROP SESSION DEBUG
GFRE_Log.AddRule(CFRE_DB_LOGCATEGORY[dblc_SESSION],fll_Info,'*',flra_DropEntry); // DROP SESSION INFO
end;
procedure Setup_APS_COMM_Logging;
begin
GFRE_Log.AddRule(CFRE_DB_LOGCATEGORY[dblc_APSCOMM],fll_Info,'*',flra_DropEntry); // DROP APSCOMM INFO
GFRE_Log.AddRule(CFRE_DB_LOGCATEGORY[dblc_APSCOMM],fll_Debug,'*',flra_DropEntry); // DROP APSCOMM DEBUG
//GFRE_Log.AddRule(CFRE_DB_LOGCATEGORY[dblc_APSCOMM],fll_Notice,'*',flra_DropEntry);
end;
procedure Setup_Persistance_Layer_Logging;
begin
//GFRE_Log.AddRule(CFRE_DB_LOGCATEGORY[dblc_PERSISTANCE],fll_Info,'*',flra_DropEntry);
//GFRE_Log.AddRule(CFRE_DB_LOGCATEGORY[dblc_PERSISTANCE],fll_Debug,'*',flra_DropEntry);
GFRE_Log.AddRule(CFRE_DB_LOGCATEGORY[dblc_PERSISTANCE_NOTIFY],fll_Info,'*',flra_DropEntry);
GFRE_Log.AddRule(CFRE_DB_LOGCATEGORY[dblc_PERSISTANCE_NOTIFY],fll_Debug,'*',flra_DropEntry);
end;
procedure Setup_FlexcomLogging;
begin
GFRE_Log.AddRule(CFRE_DB_LOGCATEGORY[dblc_FLEXCOM],fll_Debug,'*',flra_DropEntry);
//GFRE_Log.AddRule(CFRE_DB_LOGCATEGORY[dblc_FLEX_IO],fll_Debug,'*',flra_DropEntry);
end;
begin
Setup_DB_Logging;
Setup_HTTP_Request_Logging;
Setup_Server_Logging;
Setup_WS_Session_Logging;
//Setup_APS_COMM_Logging;
//Setup_Persistance_Layer_Logging;
//Setup_FlexcomLogging;
GFRE_Log.AddRule('*',fll_Invalid,'*',flra_LogToOnConsole,false); // All To Console
GFRE_Log.AddRule('*',fll_Invalid,'*',flra_DropEntry); // No File Logging
GFRE_LOG.DisableSyslog;
end;
procedure TFRE_CLISRV_APP.EndlessLogTest;
var
cat: TFRE_DB_LOGCATEGORY;
begin
while true do
for cat in TFRE_DB_LOGCATEGORY do
begin
GFRE_DB.LogDebug(cat,' <DEBUG LOG ENTRY> ');
GFRE_DB.LogInfo(cat,' <INFO LOG ENTRY> ');
GFRE_DB.LogEmergency(cat,' <EMERGENCY LOG ENTRY>');
GFRE_DB.LogWarning(cat,' <WARNING LOG ENTRY> ');
GFRE_DB.LogError (cat,' <ERROR LOG ENTRY> ');
GFRE_DB.LogNotice(cat,' <NOTICE LOG ENTRY> ');
end;
end;
procedure TFRE_CLISRV_APP.SchemeDump(const filename: string; const classfile: string);
var lconn : IFRE_DB_CONNECTION;
sconn : IFRE_DB_SYS_CONNECTION;
res : TFRE_DB_Errortype;
mems : TMemorystream;
system : boolean;
begin
_CheckDBNameSupplied;
if filename='' then begin
writeln('No filename for graph set !');
exit;
end;
if (FChosenExtensionList.Count=0) then begin
writeln('SchemeDump for system database');
system := true;
end else begin
writeln('SchemeDump for extensions :'+uppercase(FChosenExtensionList.Commatext));
system := false;
end;
mems := TMemorystream.Create;
try
if system then begin
sconn := GFRE_DBI.NewSysOnlyConnection();
sconn.Connect(cG_OVERRIDE_USER,cG_OVERRIDE_PASS);
GFRE_DB.Initialize_Extension_ObjectsBuild;
sconn.DrawScheme(mems,classfile);
end else begin
lconn := GFRE_DBI.NewConnection;
res := lconn.Connect(FDBName,cG_OVERRIDE_USER,cG_OVERRIDE_PASS);
GFRE_DB.Initialize_Extension_ObjectsBuild;
if res<>edb_OK then begin
WriteLn('SCHEME DUMP CHECK CONNECT FAILED : ',CFRE_DB_Errortype[res]);
end;
lconn.DrawScheme(mems,classfile);
lconn.Finalize;
end;
mems.SaveToFile(filename);
finally
mems.free;
end;
end;
procedure TFRE_CLISRV_APP.DumpAll(const filterstring : string);
var conn : IFRE_DB_CONNECTION;
filter : TFRE_DB_StringArray;
procedure Local(const obj:IFRE_DB_Object; var halt:boolean ; const current,max : NativeInt);
begin
writeln('DUMPING OBJ : ',current,'/',max,' ',obj.UID_String,' ',obj.SchemeClass);
obj.Finalize;
end;
begin
CONN := GetActiveDatabaseConnection;
if filterstring<>'' then
FREDB_SeperateString(filterstring,',',filter);
writeln('');
writeln('DUMPING ALL OBJECTS FROM ',FDBName,' FILTER [',filterstring,']');
writeln('');
conn.ForAllDatabaseObjectsDo(@local,filter);
writeln('');
writeln('DUMPING ALL SYSTEM OBJECTS FILTER [',filterstring,']');
writeln('');
conn.sys.ForAllDatabaseObjectsDo(@local,filter);
conn.Finalize;
end;
procedure TFRE_CLISRV_APP.OverviewDump;
var conn : IFRE_DB_CONNECTION;
procedure WriteALine(const line:string);
begin
writeln(line);
end;
begin
CONN := GetActiveDatabaseConnection;
conn.OverviewDump(@WriteALine);
end;
procedure TFRE_CLISRV_APP.ExpandReferences(const input: string);
var conn : IFRE_DB_CONNECTION;
i : NativeInt;
uids : TFRE_DB_GUIDArray;
refs : TFRE_DB_GUIDArray;
u,r : ansistring;
ua,rl: TFRE_DB_StringArray;
rlcs : TFRE_DB_NameTypeRLArray;
uido : IFRE_DB_ObjectArray;
refo : IFRE_DB_ObjectArray;
begin
if not GFRE_BT.SepLeftRight(input,'/',u,r) then
begin
writeln('You must provide uidlist/RLC e.g 01a0baf86f35800dfc7c1efd7b9ef165,3fb4cc3eb902d947600de91e78592943/DATALINKPARENT>>TFRE_DB_ZONE,SERVICEPARENT>>,..');
exit;
end;
FREDB_SeperateString(u,',',ua);
uids := FREDB_StringArray2UidArray(ua);
FREDB_SeperateString(r,',',rl);
rlcs := FREDB_StringArray2NametypeRLArray(rl);
_CheckDBNameSupplied;
_CheckAdminUserSupplied;
_CheckAdminPassSupplied;
_CheckNoCustomextensionsSet;
CONN := GFRE_DBI.NewConnection;
CheckDbResult(CONN.Connect(FDBName,cG_OVERRIDE_USER,cG_OVERRIDE_PASS),'cannot connect system db');
conn.ExpandReferences(uids,rlcs,refs);
conn.BulkFetch(uids,uido);
conn.BulkFetch(refs,refo);
writeln('UIDS');
writeln(FREDB_GuidArray2String(uids));
for i:=0 to high(uido) do
begin
writeln(i,':>----');
writeln(uido[i].DumpToString());
writeln(i,':<----');
end;
writeln('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');
writeln('RESOLVE TO');
writeln(FREDB_GuidArray2String(refs));
for i:=0 to high(refo) do
begin
writeln(i,':>----');
writeln(refo[i].DumpToString());
writeln(i,':<----');
end;
writeln('<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<');
conn.Finalize;
end;
constructor TFRE_CLISRV_APP.Create(TheOwner: TComponent);
begin
inherited Create(TheOwner);
StopOnException :=True;
FAvailExtensionList := GFRE_DBI_REG_EXTMGR.GetExtensionList;
FAvailExtensionList.SetCaseSensitive(false);
FDefaultStyle := 'eurocumulus';
FChosenExtensionList := GFRE_TF.Get_FOS_Strings;
FShortOpts := GFRE_TF.Get_FOS_Strings;
FLongOpts := GFRE_TF.Get_FOS_Strings;
FHelpOpts := GFRE_TF.Get_FOS_Strings;
end;
destructor TFRE_CLISRV_APP.Destroy;
begin
inherited Destroy;
end;
end.
|
unit ibSHDDLFinderEditors;
interface
uses
SysUtils, Classes, DesignIntf,
SHDesignIntf, ibSHDesignIntf, ibSHCommonEditors;
type
TibSHDDLFinderPropEditor = class(TibBTPropertyEditor)
public
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure GetValues(AValues: TStrings); override;
procedure SetValue(const Value: string); override;
procedure Edit; override;
end;
IibSHLookInPropEditor = interface
['{122B3B9B-1BB7-4880-A160-D9A0A67CE41B}']
end;
TibBTLookInPropEditor = class(TibSHDDLFinderPropEditor, IibSHLookInPropEditor)
end;
implementation
{ TibSHDDLFinderPropEditor }
function TibSHDDLFinderPropEditor.GetAttributes: TPropertyAttributes;
begin
Result := inherited GetAttributes;
end;
function TibSHDDLFinderPropEditor.GetValue: string;
var
DDLFinder: IibSHDDLFinder;
begin
Result := inherited GetValue;
if Supports(Self, IibSHLookInPropEditor) and Supports(Component, IibSHDDLFinder, DDLFinder) then
begin
Result := EmptyStr;
if DDLFinder.LookIn.Domains then Result := Format('%s, %s', [Result, 'Domains']);
if DDLFinder.LookIn.Tables then Result := Format('%s, %s', [Result, 'Tables']);
if DDLFinder.LookIn.Constraints then Result := Format('%s, %s', [Result, 'Constraints']);
if DDLFinder.LookIn.Indices then Result := Format('%s, %s', [Result, 'Indices']);
if DDLFinder.LookIn.Views then Result := Format('%s, %s', [Result, 'Views']);
if DDLFinder.LookIn.Procedures then Result := Format('%s, %s', [Result, 'Procedures']);
if DDLFinder.LookIn.Triggers then Result := Format('%s, %s', [Result, 'Triggers']);
if DDLFinder.LookIn.Generators then Result := Format('%s, %s', [Result, 'Generators']);
if DDLFinder.LookIn.Exceptions then Result := Format('%s, %s', [Result, 'Exceptions']);
if DDLFinder.LookIn.Functions then Result := Format('%s, %s', [Result, 'Functions']);
if DDLFinder.LookIn.Filters then Result := Format('%s, %s', [Result, 'Filters']);
if DDLFinder.LookIn.Roles then Result := Format('%s, %s', [Result, 'Roles']);
if Pos(', ', Result) = 1 then Result := Copy(Result, 3, MaxInt);
if Length(Result) = 0 then Result := '< none >';
end;
end;
procedure TibSHDDLFinderPropEditor.GetValues(AValues: TStrings);
begin
inherited GetValues(AValues);
end;
procedure TibSHDDLFinderPropEditor.SetValue(const Value: string);
begin
inherited SetValue(Value);
end;
procedure TibSHDDLFinderPropEditor.Edit;
begin
inherited Edit;
end;
end.
|
unit Hash;
interface
// Get String SHA256 hash in hexadecimal string format
function getsha256(strToEncrypt: String): String;
implementation
uses DCPsha256, ArrayUtils;
function getsha256(strToEncrypt: String): String;
var
hashCalculator : TDCP_sha256;
digest : array[0..31] of byte; // sha256 produces a 256bit digest (32bytes)
source : string;
begin
Source:= strToEncrypt; // here your string for get sha256
Result := '';
if Source <> '' then
begin
hashCalculator := TDCP_sha256.Create(nil); // create the hash
hashCalculator.Init; // initialize it
hashCalculator.UpdateStr(Source);
hashCalculator.Final(Digest); // produce the digest (output)
Result := GetHexadecimalString(digest);
end;
end;
end.
|
unit SelectGroupForm;
interface
uses
Windows,
SysUtils,
Classes,
Graphics,
Controls,
Forms,
StdCtrls,
ComCtrls,
ImgList,
uMemory,
uMemoryEx,
uDBIcons,
uDBContext,
uDBEntities,
uDBManager,
uBitmapUtils,
uDBForm,
uConstants;
type
TFormSelectGroup = class(TDBForm)
LbInfo: TLabel;
CbeGroupList: TComboBoxEx;
BtOk: TButton;
BtCancel: TButton;
GroupsImageList: TImageList;
procedure FormCreate(Sender: TObject);
procedure BtCancelClick(Sender: TObject);
procedure BtOkClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
FContext: IDBContext;
FGroupsRepository: IGroupsRepository;
protected
function GetFormID: string; override;
public
{ Public declarations }
ShowResult: Boolean;
Groups: TGroups;
procedure LoadLanguage;
function Execute(out Group: TGroup): Boolean;
procedure RecreateGroupsList;
end;
function SelectGroup(out Group: TGroup) : Boolean;
implementation
{$R *.dfm}
function SelectGroup(out Group: TGroup): Boolean;
var
FormSelectGroup: TFormSelectGroup;
begin
Application.CreateForm(TFormSelectGroup, FormSelectGroup);
try
Result := FormSelectGroup.Execute(Group);
finally
R(FormSelectGroup);
end;
end;
procedure TFormSelectGroup.FormCreate(Sender: TObject);
begin
FContext := DBManager.DBContext;
FGroupsRepository := FContext.Groups;
Groups := FGroupsRepository.GetAll(True, True);
RecreateGroupsList;
ShowResult := False;
LoadLanguage;
end;
procedure TFormSelectGroup.LoadLanguage;
begin
BeginTranslate;
try
Caption := L('Select group');
LbInfo.Caption := L('Select, please, necessary group') + ':';
BtCancel.Caption := L('Cancel');
BtOk.Caption := L('Ok');
finally
EndTranslate;
end;
end;
procedure TFormSelectGroup.BtCancelClick(Sender: TObject);
begin
Close;
end;
function TFormSelectGroup.Execute(out Group: TGroup): Boolean;
begin
Result := False;
ShowModal;
if ShowResult and (CbeGroupList.ItemIndex > -1) then
begin
Group := Groups[CbeGroupList.ItemIndex].Clone;
Result := True;
end;
end;
procedure TFormSelectGroup.BtOkClick(Sender: TObject);
begin
ShowResult := True;
Close;
end;
procedure TFormSelectGroup.FormDestroy(Sender: TObject);
begin
F(Groups);
end;
function TFormSelectGroup.GetFormID: string;
begin
Result := 'SelectGroup';
end;
procedure FillGroupsToImageList(ImageList : TImageList; Groups : TGroups; BackgroundColor : TColor);
var
I: Integer;
SmallB, B: TBitmap;
begin
ImageList.Clear;
for I := -1 to Groups.Count - 1 do
begin
SmallB := TBitmap.Create;
try
SmallB.PixelFormat := Pf24bit;
SmallB.Width := 16;
SmallB.Height := 18;
SmallB.Canvas.Pen.Color := BackgroundColor;
SmallB.Canvas.Brush.Color := BackgroundColor;
if I = -1 then
DrawIconEx(SmallB.Canvas.Handle, 0, 0, Icons[DB_IC_GROUPS], 16, 16, 0, 0, DI_NORMAL)
else
begin
if (Groups[I].GroupImage <> nil) and not Groups[I].GroupImage.Empty then
begin
B := TBitmap.Create;
try
B.PixelFormat := Pf24bit;
B.Assign(Groups[I].GroupImage);
DoResize(16, 16, B, SmallB);
finally
F(B);
end;
end;
end;
ImageList.Add(SmallB, nil);
finally
F(SmallB);
end;
end;
end;
procedure TFormSelectGroup.RecreateGroupsList;
var
I: Integer;
begin
CbeGroupList.Clear;
FillGroupsToImageList(GroupsImageList, Groups, Theme.PanelColor);
for I := 0 to Groups.Count - 1 do
with CbeGroupList.ItemsEx.Add do
begin
ImageIndex := I + 1;
Caption := Groups[I].GroupName;
end;
if CbeGroupList.Items.Count > 0 then
CbeGroupList.ItemIndex := 0;
end;
end.
|
//
// Generated by JavaToPas v1.5 20150830 - 104114
////////////////////////////////////////////////////////////////////////////////
unit android.webkit.WebSettings_LayoutAlgorithm;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes;
type
JWebSettings_LayoutAlgorithm = interface;
JWebSettings_LayoutAlgorithmClass = interface(JObjectClass)
['{CB5F0604-DE8C-4754-91B6-2912E43F96AD}']
function _GetNARROW_COLUMNS : JWebSettings_LayoutAlgorithm; cdecl; // A: $4019
function _GetNORMAL : JWebSettings_LayoutAlgorithm; cdecl; // A: $4019
function _GetSINGLE_COLUMN : JWebSettings_LayoutAlgorithm; cdecl; // A: $4019
function _GetTEXT_AUTOSIZING : JWebSettings_LayoutAlgorithm; cdecl; // A: $4019
function valueOf(&name : JString) : JWebSettings_LayoutAlgorithm; cdecl; // (Ljava/lang/String;)Landroid/webkit/WebSettings$LayoutAlgorithm; A: $9
function values : TJavaArray<JWebSettings_LayoutAlgorithm>; cdecl; // ()[Landroid/webkit/WebSettings$LayoutAlgorithm; A: $9
property NARROW_COLUMNS : JWebSettings_LayoutAlgorithm read _GetNARROW_COLUMNS;// Landroid/webkit/WebSettings$LayoutAlgorithm; A: $4019
property NORMAL : JWebSettings_LayoutAlgorithm read _GetNORMAL; // Landroid/webkit/WebSettings$LayoutAlgorithm; A: $4019
property SINGLE_COLUMN : JWebSettings_LayoutAlgorithm read _GetSINGLE_COLUMN;// Landroid/webkit/WebSettings$LayoutAlgorithm; A: $4019
property TEXT_AUTOSIZING : JWebSettings_LayoutAlgorithm read _GetTEXT_AUTOSIZING;// Landroid/webkit/WebSettings$LayoutAlgorithm; A: $4019
end;
[JavaSignature('android/webkit/WebSettings_LayoutAlgorithm')]
JWebSettings_LayoutAlgorithm = interface(JObject)
['{4489DB2C-2373-4B6E-94AD-8D528181B79B}']
end;
TJWebSettings_LayoutAlgorithm = class(TJavaGenericImport<JWebSettings_LayoutAlgorithmClass, JWebSettings_LayoutAlgorithm>)
end;
implementation
end.
|
unit API_Files;
interface
uses
System.JSON, System.SysUtils, System.Classes, Vcl.Dialogs;
type
TFilesEngine = class
private
FPathList: array of string;
FCurrentPath: String;
function CheckLastSlash(Path: String): String;
procedure ScanForNewPath;
procedure CheckThisPath(FileMask: String; JSON: TJSONObject);
public
procedure GetFileNamesByMask(SearchPath, FileMask: String;
JSON: TJSONObject);
class procedure CreateFile(FileName: String);
class procedure SaveTextToFile(FileName, Text: String);
class procedure AppendToFile(FileName, Text: String);
class function GetTextFromFile(FileName: String): String;
end;
implementation
procedure TFilesEngine.CheckThisPath(FileMask: string; JSON: TJSONObject);
var
SearchResult: TSearchRec;
SearchMask: String;
jpair: TJSONPair;
begin
SearchMask := FCurrentPath + FileMask;
if FindFirst(SearchMask, faAnyFile, SearchResult) = 0 then
begin
repeat
if (SearchResult.Name <> '.') and (SearchResult.Name <> '..') then
begin
jpair := TJSONPair.Create(FCurrentPath, SearchResult.Name);
JSON.AddPair(jpair);
end;
until FindNext(SearchResult) <> 0;
FindClose(SearchResult);
end;
end;
procedure TFilesEngine.ScanForNewPath;
var
SearchResult: TSearchRec;
Path: String;
begin
if FindFirst(FCurrentPath + '*.*', faAnyFile, SearchResult) = 0 then
begin
repeat
if (SearchResult.Attr = faDirectory) and (SearchResult.Name <> '.') and
(SearchResult.Name <> '..') then
begin
Path := FCurrentPath + SearchResult.Name;
FPathList := FPathList + [Path];
end;
until FindNext(SearchResult) <> 0;
FindClose(SearchResult);
end;
end;
function TFilesEngine.CheckLastSlash(Path: string): String;
begin
if Path[Length(Path)] <> '\' then
Path := Path + '\';
result := Path;
end;
procedure TFilesEngine.GetFileNamesByMask(SearchPath: string; FileMask: string;
JSON: TJSONObject);
begin
SearchPath := CheckLastSlash(SearchPath);
FPathList := [SearchPath];
while Length(FPathList) > 0 do
begin
FCurrentPath := CheckLastSlash(FPathList[0]);
ScanForNewPath;
CheckThisPath(FileMask, JSON);
Delete(FPathList, 0, 1);
end;
end;
class procedure TFilesEngine.CreateFile(FileName: string);
var
SL: TStringList;
begin
SL := TStringList.Create;
try
SL.SaveToFile(FileName);
finally
SL.Free;
end;
end;
class procedure TFilesEngine.AppendToFile(FileName, Text: String);
var
EditFile: TextFile;
begin
try
AssignFile(EditFile, FileName);
Append(EditFile);
WriteLn(EditFile, Text);
CloseFile(EditFile);
except
ShowMessage('Ошибка открытия или записи файла');
end;
end;
class function TFilesEngine.GetTextFromFile(FileName: string): string;
var
SL: TStringList;
begin
if FileExists(FileName) then
begin
SL := TStringList.Create;
try
SL.LoadFromFile(FileName);
result := SL.Text;
finally
SL.Free;
end;
end;
end;
class procedure TFilesEngine.SaveTextToFile(FileName, Text: String);
var
SL: TStringList;
begin
SL := TStringList.Create;
try
SL.Text := Text;
SL.SaveToFile(FileName);
finally
SL.Free;
end;
end;
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
Component for handling joystick messages
}
unit VXS.Joystick;
interface
{$I VXScene.inc}
{$IFDEF UNIX}{$MESSAGE Error 'Unit not supported'}{$ENDIF}
uses
Winapi.Windows,
Winapi.Messages,
Winapi.MMSystem,
System.Classes,
System.SysUtils,
FMX.Forms,
FMX.Controls,
VXS.Strings;
type
TJoystickButton = (jbButton1, jbButton2, jbButton3, jbButton4);
TJoystickButtons = set of TJoystickButton;
TJoystickID = (jidNoJoystick, jidJoystick1, jidJoystick2);
TJoystickDesignMode = (jdmInactive, jdmActive);
TJoyPos = (jpMin, jpCenter, jpMax);
TJoyAxis = (jaX, jaY, jaZ, jaR, jaU, jaV);
TJoystickEvent = procedure(Sender: TObject; JoyID: TJoystickID;
Buttons: TJoystickButtons; XDeflection, YDeflection: Integer) of Object;
{ A component interfacing the Joystick via the (regular) windows API. }
TVXJoystick = class(TComponent)
private
FWindowHandle: HWND;
FNumButtons, FLastX, FLastY, FLastZ: Integer;
FThreshold, FInterval: Cardinal;
FCapture, FNoCaptureErrors: Boolean;
FJoystickID: TJoystickID;
FMinMaxInfo: array [TJoyAxis, TJoyPos] of Integer;
FXPosInfo, FYPosInfo: array [0 .. 4] of Integer;
FOnJoystickButtonChange, FOnJoystickMove: TJoystickEvent;
FXPosition, FYPosition: Integer;
FJoyButtons: TJoystickButtons;
procedure SetCapture(AValue: Boolean);
procedure SetInterval(AValue: Cardinal);
procedure SetJoystickID(AValue: TJoystickID);
procedure SetThreshold(AValue: Cardinal);
protected
function MakeJoyButtons(Param: UINT): TJoystickButtons;
procedure DoJoystickCapture(AHandle: HWND; AJoystick: TJoystickID);
procedure DoJoystickRelease(AJoystick: TJoystickID);
procedure DoXYMove(Buttons: Word; XPos, YPos: Integer);
procedure DoZMove(Buttons: Word; ZPos: Integer);
procedure ReapplyCapture(AJoystick: TJoystickID);
procedure WndProc(var Msg: TMessage);
procedure Loaded; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
property JoyButtons: TJoystickButtons read FJoyButtons;
property XPosition: Integer read FXPosition;
property YPosition: Integer read FYPosition;
published
{ When set to True, the component attempts to capture the joystick.
If capture is successfull, retrieving joystick status is possible,
if not, an error message is triggered. }
property Capture: Boolean read FCapture write SetCapture default False;
{ If true joystick capture errors do not result in exceptions. }
property NoCaptureErrors: Boolean read FNoCaptureErrors
write FNoCaptureErrors default True;
{ Polling frequency (milliseconds) }
property Interval: Cardinal read FInterval write SetInterval default 100;
property JoystickID: TJoystickID read FJoystickID write SetJoystickID
default jidNoJoystick;
property Threshold: Cardinal read FThreshold write SetThreshold
default 1000;
property OnJoystickButtonChange: TJoystickEvent read FOnJoystickButtonChange
write FOnJoystickButtonChange;
property OnJoystickMove: TJoystickEvent read FOnJoystickMove
write FOnJoystickMove;
end;
// ---------------------------------------------------------------------
implementation
// ---------------------------------------------------------------------
const
cJoystickIDToNative: array [jidNoJoystick .. jidJoystick2] of Byte = (9,
JOYSTICKID1, JOYSTICKID2);
// ------------------
// ------------------ TJoystick ------------------
// ------------------
constructor TVXJoystick.Create(AOwner: TComponent);
begin
inherited;
FWindowHandle := AllocateHWnd(WndProc);
FInterval := 100;
FThreshold := 1000;
FJoystickID := jidNoJoystick;
FLastX := -1;
FLastY := -1;
FLastZ := -1;
FNoCaptureErrors := True;
end;
destructor TVXJoystick.Destroy;
begin
DeallocateHWnd(FWindowHandle);
inherited;
end;
procedure TVXJoystick.WndProc(var Msg: TMessage);
begin
with Msg do
begin
case FJoystickID of
jidJoystick1: // check only 1st stick
case Msg of
MM_JOY1MOVE:
DoXYMove(wParam, lParamLo, lParamHi);
MM_JOY1ZMOVE:
DoZMove(wParam, lParamLo);
MM_JOY1BUTTONDOWN:
if Assigned(FOnJoystickButtonChange) then
FOnJoystickButtonChange(Self, FJoystickID, MakeJoyButtons(wParam),
FLastX, FLastY);
MM_JOY1BUTTONUP:
if Assigned(FOnJoystickButtonChange) then
FOnJoystickButtonChange(Self, FJoystickID, MakeJoyButtons(wParam),
FLastX, FLastY);
end;
jidJoystick2: // check only 2nd stick
case Msg of
MM_JOY2MOVE:
DoXYMove(wParam, lParamLo, lParamHi);
MM_JOY2ZMOVE:
DoZMove(wParam, lParamLo);
MM_JOY2BUTTONDOWN:
if Assigned(FOnJoystickButtonChange) then
FOnJoystickButtonChange(Self, FJoystickID, MakeJoyButtons(wParam),
FLastX, FLastY);
MM_JOY2BUTTONUP:
if Assigned(FOnJoystickButtonChange) then
FOnJoystickButtonChange(Self, FJoystickID, MakeJoyButtons(wParam),
FLastX, FLastY);
end;
jidNoJoystick:
; // ignore
else
Assert(False);
end;
Result := 0;
end;
end;
procedure TVXJoystick.Loaded;
begin
inherited;
ReapplyCapture(FJoystickID);
end;
procedure TVXJoystick.Assign(Source: TPersistent);
begin
if Source is TVXJoystick then
begin
FInterval := TVXJoystick(Source).FInterval;
FThreshold := TVXJoystick(Source).FThreshold;
FCapture := TVXJoystick(Source).FCapture;
FJoystickID := TVXJoystick(Source).FJoystickID;
try
ReapplyCapture(FJoystickID);
except
FJoystickID := jidNoJoystick;
FCapture := False;
raise;
end;
end
else
inherited Assign(Source);
end;
function TVXJoystick.MakeJoyButtons(Param: UINT): TJoystickButtons;
begin
Result := [];
if (Param and JOY_BUTTON1) > 0 then
Include(Result, jbButton1);
if (Param and JOY_BUTTON2) > 0 then
Include(Result, jbButton2);
if (Param and JOY_BUTTON3) > 0 then
Include(Result, jbButton3);
if (Param and JOY_BUTTON4) > 0 then
Include(Result, jbButton4);
FJoyButtons := Result;
end;
function DoScale(AValue: Integer): Integer;
begin
Result := Round(AValue / 1);
end;
procedure TVXJoystick.ReapplyCapture(AJoystick: TJoystickID);
var
jc: TJoyCaps;
begin
DoJoystickRelease(AJoystick);
if FCapture and (not(csDesigning in ComponentState)) then
with jc do
begin
joyGetDevCaps(cJoystickIDToNative[FJoystickID], @jc, SizeOf(jc));
FNumButtons := wNumButtons;
FMinMaxInfo[jaX, jpMin] := DoScale(wXMin);
FMinMaxInfo[jaX, jpCenter] := DoScale((wXMin + wXMax) div 2);
FMinMaxInfo[jaX, jpMax] := DoScale(wXMax);
FMinMaxInfo[jaY, jpMin] := DoScale(wYMin);
FMinMaxInfo[jaY, jpCenter] := DoScale((wYMin + wYMax) div 2);
FMinMaxInfo[jaY, jpMax] := DoScale(wYMax);
FMinMaxInfo[jaZ, jpMin] := DoScale(wZMin);
FMinMaxInfo[jaZ, jpCenter] := DoScale((wZMin + wZMax) div 2);
FMinMaxInfo[jaZ, jpMax] := DoScale(wZMax);
FMinMaxInfo[jaR, jpMin] := DoScale(wRMin);
FMinMaxInfo[jaR, jpCenter] := DoScale((wRMin + wRMax) div 2);
FMinMaxInfo[jaR, jpMax] := DoScale(wRMax);
FMinMaxInfo[jaU, jpMin] := DoScale(wUMin);
FMinMaxInfo[jaU, jpCenter] := DoScale((wUMin + wUMax) div 2);
FMinMaxInfo[jaU, jpMax] := DoScale(wUMax);
FMinMaxInfo[jaV, jpMin] := DoScale(wVMin);
FMinMaxInfo[jaV, jpCenter] := DoScale((wVMin + wVMax) div 2);
FMinMaxInfo[jaV, jpMax] := DoScale(wVMax);
DoJoystickCapture(FWindowHandle, AJoystick)
end;
end;
procedure TVXJoystick.DoJoystickCapture(AHandle: HWND; AJoystick: TJoystickID);
var
res: Cardinal;
begin
res := joySetCapture(AHandle, cJoystickIDToNative[AJoystick],
FInterval, True);
if res <> JOYERR_NOERROR then
begin
FCapture := False;
if not NoCaptureErrors then
begin
case res of
MMSYSERR_NODRIVER:
raise Exception.Create(strNoJoystickDriver);
JOYERR_UNPLUGGED:
raise Exception.Create(strConnectJoystick);
JOYERR_NOCANDO:
raise Exception.Create(strJoystickError);
else
raise Exception.Create(strJoystickError);
end;
end;
end
else
joySetThreshold(cJoystickIDToNative[AJoystick], FThreshold);
end;
procedure TVXJoystick.DoJoystickRelease(AJoystick: TJoystickID);
begin
if AJoystick <> jidNoJoystick then
joyReleaseCapture(cJoystickIDToNative[AJoystick]);
end;
procedure TVXJoystick.SetCapture(AValue: Boolean);
begin
if FCapture <> AValue then
begin
FCapture := AValue;
if not(csReading in ComponentState) then
begin
try
ReapplyCapture(FJoystickID);
except
FCapture := False;
raise;
end;
end;
end;
end;
procedure TVXJoystick.SetInterval(AValue: Cardinal);
begin
if FInterval <> AValue then
begin
FInterval := AValue;
if not(csReading in ComponentState) then
ReapplyCapture(FJoystickID);
end;
end;
procedure TVXJoystick.SetJoystickID(AValue: TJoystickID);
begin
if FJoystickID <> AValue then
begin
try
if not(csReading in ComponentState) then
ReapplyCapture(AValue);
FJoystickID := AValue;
except
on E: Exception do
begin
ReapplyCapture(FJoystickID);
Application.ShowException(E);
end;
end;
end;
end;
// ------------------------------------------------------------------------------
procedure TVXJoystick.SetThreshold(AValue: Cardinal);
begin
if FThreshold <> AValue then
begin
FThreshold := AValue;
if not(csReading in ComponentState) then
ReapplyCapture(FJoystickID);
end;
end;
// ------------------------------------------------------------------------------
function Approximation(Data: array of Integer): Integer;
// calculate a better estimation of the last value in the given data, depending
// on the other values (used to approximate a smoother joystick movement)
//
// based on Gauss' principle of smallest squares in Maximum-Likelihood and
// linear normal equations
var
SumX, SumY, SumXX, SumYX: Double;
I, Comps: Integer;
a0, a1: Double;
begin
SumX := 0;
SumY := 0;
SumXX := 0;
SumYX := 0;
Comps := High(Data) + 1;
for I := 0 to High(Data) do
begin
SumX := SumX + I;
SumY := SumY + Data[I];
SumXX := SumXX + I * I;
SumYX := SumYX + I * Data[I];
end;
a0 := (SumY * SumXX - SumX * SumYX) / (Comps * SumXX - SumX * SumX);
a1 := (Comps * SumYX - SumY * SumX) / (Comps * SumXX - SumX * SumX);
Result := Round(a0 + a1 * High(Data));
end;
procedure TVXJoystick.DoXYMove(Buttons: Word; XPos, YPos: Integer);
var
I: Integer;
dX, dY: Integer;
begin
XPos := DoScale(XPos);
YPos := DoScale(YPos);
if (FLastX = -1) or (FLastY = -1) then
begin
FLastX := XPos;
FLastY := YPos;
for I := 0 to 4 do
begin
FXPosInfo[I] := XPos;
FYPosInfo[I] := YPos;
end;
end
else
begin
Move(FXPosInfo[1], FXPosInfo[0], 16);
FXPosInfo[4] := XPos;
XPos := Approximation(FXPosInfo);
Move(FYPosInfo[1], FYPosInfo[0], 16);
FYPosInfo[4] := YPos;
YPos := Approximation(FYPosInfo);
MakeJoyButtons(Buttons);
dX := Round((XPos - FMinMaxInfo[jaX, jpCenter]) * 100 / FMinMaxInfo[jaX,
jpCenter]);
dY := Round((YPos - FMinMaxInfo[jaY, jpCenter]) * 100 / FMinMaxInfo[jaY,
jpCenter]);
if Assigned(FOnJoystickMove) then
FOnJoystickMove(Self, FJoystickID, FJoyButtons, dX, dY);
FXPosition := dX;
FYPosition := dY;
FLastX := XPos;
FLastY := YPos;
end;
end;
procedure TVXJoystick.DoZMove(Buttons: Word; ZPos: Integer);
begin
if FLastZ = -1 then
FLastZ := Round(ZPos * 100 / 65536);
MakeJoyButtons(Buttons);
end;
//------------------------------------------------------------------
initialization
//------------------------------------------------------------------
RegisterClasses([TVXJoystick]);
end.
|
unit LibProj;
interface
uses
Classes, SysUtils, SyncObjs, Generics.Collections,
LibProjProjections;
type
TProjectionsManager = class;
TPointsTransformer = class;
IProjection = interface(IUnknown)
['{EE6FB2E9-9327-46E3-A0FF-2A55AF324498}']
procedure CreateHandle(); stdcall;
procedure DestroyHandle(); stdcall;
procedure HandleNeeded; stdcall;
/// <param name="a">
/// MajorAxis
/// </param>
/// <param name="b">
/// MinorAxis
/// </param>
/// <param name="e2">
/// EccentricitySquared
/// </param>
function GetSpheroidDefinition(out a,b,e2: Double): Boolean; stdcall;
function GetCreateDefinition: string; stdcall;
function GetDefinition: string; stdcall;
function GetWKTDefinition(const PrettyPrint: Boolean): string; stdcall;
function GetHandle: Pointer; stdcall;
procedure SetHandle(Value: Pointer); stdcall;
function GetIsGeocraphic(): Boolean; stdcall;
function GetIsGeocentric(): Boolean; stdcall;
function HandleValid(): Boolean; stdcall;
function TransformPoint(Dst: IProjection; var X,Y: Double; AngularUnits: Boolean = False): Boolean; stdcall;
function TransformPoints(Dst: IProjection; var X,Y: Double; Count: Integer; AngularUnits: Boolean): Boolean; stdcall;
property Handle: Pointer read GetHandle write SetHandle;
end;
TProjection = class(TInterfacedObject,IProjection)
private
FSourceDefn: string;
FGeoProjection: IProjection;
FHandle: Pointer;
FOwner: TProjectionsManager;
FOwnGeoProjection: Boolean;
procedure SetDefinition(const Value: string);
function GetWKTDefinition(const PrettyPrint: Boolean): string; stdcall;
constructor Create; overload;
protected
procedure CreateHandle(); stdcall;
procedure DestroyHandle(); stdcall;
procedure HandleNeeded; stdcall;
function GetHandle: Pointer; stdcall;
procedure SetHandle(Value: Pointer); stdcall;
function GetOwner: TPersistent;
function GetSpheroidDefinition(out a,b,e2: Double): Boolean; stdcall;
function GetCreateDefinition: string; stdcall;
function GetDefinition: string; stdcall;
function GetIsGeocraphic(): Boolean; stdcall;
function GetIsGeoCentric(): Boolean; stdcall;
property Handle: Pointer read GetHandle write SetHandle;
public
constructor Create(const ADefn: string); overload;
constructor CreateOwned(AOwner: TProjectionsManager; const ADefn: string); overload;
constructor CreateOwned(AOwner: TProjectionsManager); overload;
destructor Destroy(); override;
function HandleValid(): Boolean; stdcall;
function GetGeographic: IProjection;
function TransformPoint(Dst: IProjection; var X,Y: Double; AngularUnits: Boolean = False): Boolean; stdcall;
function TransformPoints(Dst: IProjection; var X,Y: Double; Count: Integer; AngularUnits: Boolean): Boolean; stdcall;
property Definition: string read GetDefinition write SetDefinition;
property IsGeographic: Boolean read GetIsGeocraphic;
property IsGeocentric: Boolean read GetIsGeocentric;
end;
IPointsTransformer = interface(IUnknown)
['{AD17E7B1-B047-4C25-B3A2-345FC4FD2375}']
function TransformPointsXY(const Src,Dst: IProjection; var X,Y: Double; Count: Integer; AngularUnits: Boolean): Boolean; stdcall;
function TransformPointXY(const Src,Dst: IProjection; var X,Y: Double; AngularUnits: Boolean): Boolean; stdcall;
end;
TPointsTransformer = class(TInterfacedObject,IPointsTransformer)
private
FOwner: TProjectionsManager;
protected
function GetOwner: TPersistent;
public
constructor CreateOwned(AOwner: TProjectionsManager);
destructor Destroy(); override;
function TransformPointsXY(const Src,Dst: IProjection; var X,Y: Double; Count: Integer; AngularUnits: Boolean): Boolean; stdcall;
function TransformPointXY(const Src,Dst: IProjection; var X,Y: Double; AngularUnits: Boolean): Boolean; stdcall;
end;
IProjectionsManager = interface(IUnknown)
['{85C50F1B-D9C8-4958-885E-3B4A9F2FB61A}']
procedure Changes; stdcall;
procedure Changed; stdcall;
function GetContainer(): TObject; stdcall;
function GetPointsTransformer: IPointsTransformer;
function GetProjectionByDefinition(const Defn: string): IProjection; stdcall;
function GetProjectionByCode(const EpsgCode: Integer): IProjection; stdcall;
function GetGeographic(Src: IProjection): IProjection;
function TryGetProjection(const Defn: string; out Proj: IProjection): Boolean; stdcall;
function MakeNewProjectionFromDefn(const Defn: string; out proj: IProjection): Integer; stdcall;
function MakeNewProjectionFromEpsg(const Code: Integer; out proj: IProjection): Integer; stdcall;
property ProjectionByDefinition[const Defn: string]: IProjection read GetProjectionByDefinition;
property ProjectionByEpsgCode[const Code: Integer]: IProjection read GetProjectionByCode;
end;
TProjectionsManager = class(TComponent, IProjectionsManager)
private
FContainer: TDictionary<string,IProjection>;
FPointsTransformer: IPointsTransformer;
FGuard: TCriticalSection;
[volatile] FChangesCount: Integer;
procedure Changes; stdcall;
procedure Changed; stdcall;
protected
function GetContainer: TObject; stdcall;
function GetPointsTransformer: IPointsTransformer;
function GetProjectionByDefinition(const Defn: string): IProjection; stdcall;
function GetProjectionByCode(const EpsgCode: Integer): IProjection; stdcall;
function TryGetProjection(const Defn: string; out Proj: IProjection): Boolean; stdcall;
function MakeNewProjectionFromDefn(const Defn: string; out proj: IProjection): Integer; stdcall;
function MakeNewProjectionFromEpsg(const Code: Integer; out proj: IProjection): Integer; stdcall;
function GetGeographic(Src: IProjection): IProjection;
function KnownProjections: TDictionary<string,IProjection>;
{ IProjectionsManager }
property PointsTransformer: IPointsTransformer read GetPointsTransformer;
public
destructor Destroy(); override;
{ IPointsTransformer }
function TransformPointsXY(const Src,Dst: IProjection; var X,Y: Double; Count: Integer; AngularUnits: Boolean): Boolean; stdcall;
function TransformPointXY(const Src,Dst: IProjection; var X,Y: Double; AngularUnits: Boolean): Boolean; stdcall;
property ProjectionByDefinition[const Defn: string]: IProjection read GetProjectionByDefinition;
property ProjectionByEpsgCode[const Code: Integer]: IProjection read GetProjectionByCode;
end;
implementation
uses
LibProjApi;
{ TProjection }
constructor TProjection.Create(const ADefn: string);
begin
CreateOwned(nil,ADefn);
end;
constructor TProjection.Create;
begin
inherited Create;
end;
procedure TProjection.CreateHandle();
begin
DestroyHandle();
// try
if FOwner = nil then
FHandle := PJ_init_plus(GetCreateDefinition)
else
begin
FOwner.Changes;
try
FHandle := PJ_init_plus(GetCreateDefinition);
finally
FOwner.Changed;
end;
end;
// except
// on E: Exception do
//
// end;
end;
constructor TProjection.CreateOwned(AOwner: TProjectionsManager);
begin
CreateOwned(AOwner,'');
end;
constructor TProjection.CreateOwned(AOwner: TProjectionsManager; const ADefn: string);
begin
Create();
FGeoProjection := nil;
FOwner := AOwner;
FSourceDefn := ADefn;
end;
destructor TProjection.Destroy;
begin
DestroyHandle();
if FOwnGeoProjection then
FGeoProjection := nil;
inherited;
end;
procedure TProjection.DestroyHandle;
begin
if FHandle <> nil then
begin
if FOwner <> nil then
begin
FOwner.Changes;
try
PJ_free(FHandle);
FHandle := nil;
finally
FOwner.Changed;
end;
end;
end;
end;
function TProjection.GetCreateDefinition: string;
begin
Result := FSourceDefn;
end;
function TProjection.GetDefinition: string;
begin
Result := PJ_get_definition(Handle);
end;
function TProjection.GetGeographic: IProjection;
var
GeoHandle: Pointer;
begin
if FGeoProjection = nil then
begin
FOwnGeoProjection := FOwner = nil;
if FOwnGeoProjection then
begin
GeoHandle := PJ_latlong_from_proj(Self.Handle);
if GeoHandle <> nil then
begin
FGeoProjection := TProjection.Create('');
FGeoProjection.Handle := GeoHandle;
TProjection( FGeoProjection ).FSourceDefn := FGeoProjection.GetDefinition;
end;
end
else
Result := FOwner.GetGeographic(Self);
end;
Result := FGeoProjection;
end;
function TProjection.GetHandle: Pointer;
begin
if FHandle = nil then
CreateHandle();
Result := FHandle;
end;
function TProjection.GetIsGeoCentric: Boolean;
begin
Result := PJ_is_geocentric(Handle);
end;
function TProjection.GetIsGeocraphic: Boolean;
begin
Result := PJ_is_geographic(Handle);
end;
function TProjection.GetOwner: TPersistent;
begin
Result := FOwner;
end;
function TProjection.GetSpheroidDefinition(out a, b, e2: Double): Boolean;
begin
Result := PJ_get_spheroid_defn(Handle,a,e2);
if Result then
begin
b := a * Sqrt(1 - e2)
end
else
b := a.NegativeInfinity;
end;
function TProjection.GetWKTDefinition(const PrettyPrint: Boolean): string;
begin
Result := LibProjDefnToWKTProjection(Definition,PrettyPrint);
end;
procedure TProjection.HandleNeeded;
begin
if not HandleValid then
CreateHandle;
end;
function TProjection.HandleValid: Boolean;
begin
Result := Assigned(FHandle)
end;
procedure TProjection.SetDefinition(const Value: string);
begin
if not SameText(Value,FSourceDefn) then
begin
DestroyHandle;
FSourceDefn := Value;
end;
end;
procedure TProjection.SetHandle(Value: Pointer);
begin
if (Value <> FHandle) then
begin
if FOwner = nil then
begin
DestroyHandle;
FHandle := Value;
end
else
begin
FOwner.Changes;
try
DestroyHandle;
FHandle := Value;
finally
FOwner.Changed;
end;
end;
end;
end;
function TProjection.TransformPoint(Dst: IProjection; var X, Y: Double; AngularUnits: Boolean): Boolean;
begin
Result := TransformPoints(Dst,X,Y,1,AngularUnits);
end;
function TProjection.TransformPoints(Dst: IProjection; var X, Y: Double; Count: Integer;
AngularUnits: Boolean): Boolean;
var
Transformer: IPointsTransformer;
begin
Result := Self.HandleValid and Assigned(Dst) and Dst.HandleValid;
if Result then
begin
if not Assigned(FOwner) then
Transformer := TPointsTransformer.Create()
else
Transformer := FOwner.PointsTransformer;
Result := Transformer.TransformPointsXY(Self,Dst,X,Y,Count,AngularUnits);
end;
end;
{ TProjectionsManager }
procedure TProjectionsManager.Changed;
begin
Dec(FChangesCount);
if FChangesCount = 0 then
begin
if FGuard <> nil then
FGuard.Leave;
end;
end;
procedure TProjectionsManager.Changes;
begin
Inc(FChangesCount);
if FChangesCount = 1 then
begin
if FGuard = nil then
FGuard := TCriticalSection.Create;
FGuard.Enter;
end;
end;
destructor TProjectionsManager.Destroy;
begin
Changes;
try
FPointsTransformer := nil;
FreeAndNil(FContainer);
finally
Changed;
end;
FreeAndNil(FGuard);
inherited;
end;
function TProjectionsManager.GetContainer: TObject;
begin
if FContainer = nil then
FContainer := TObjectDictionary<string, IProjection>.Create([]);
Result := FContainer;
end;
function TProjectionsManager.GetGeographic(Src: IProjection): IProjection;
var
GeoDefn: string;
begin
Result := nil;
if Src <> nil then
begin
GeoDefn := PJ_get_definition( PJ_latlong_from_proj(Src.Handle));
if GeoDefn <> '' then
Result := ProjectionByDefinition[GeoDefn];
end;
end;
function TProjectionsManager.GetPointsTransformer: IPointsTransformer;
begin
if FPointsTransformer = nil then
FPointsTransformer := TPointsTransformer.CreateOwned(Self);
Result := FPointsTransformer;
end;
function TProjectionsManager.GetProjectionByCode(const EpsgCode: Integer): IProjection;
begin
Result := GetProjectionByDefinition(LibProjDefnFromEpsgCode(EpsgCode));
end;
function TProjectionsManager.GetProjectionByDefinition(const Defn: string): IProjection;
begin
TryGetProjection(Defn,Result);
end;
function TProjectionsManager.KnownProjections: TDictionary<string, IProjection>;
begin
Result := TDictionary<string, IProjection>(GetContainer);
end;
function TProjectionsManager.MakeNewProjectionFromDefn(const Defn: string; out proj: IProjection): Integer;
begin
Result := -1;
if Defn <> '' then
begin
Changes;
try
proj := TProjection.CreateOwned(Self,Defn);
proj.HandleNeeded;
if proj.HandleValid then
Result := 0
else
begin
Result := PJ_get_errno();
if Result = 0 then // unknown error or exception false
Result := -1;
proj := nil;
end;
finally
Changed;
end;
end;
end;
function TProjectionsManager.MakeNewProjectionFromEpsg(const Code: Integer; out proj: IProjection): Integer;
begin
Result := -1;
if TryGetProjection(LibProjDefnFromEpsgCode(Code),proj) then
Result := 0;
end;
function TProjectionsManager.TransformPointsXY(const Src, Dst: IProjection;
var X, Y: Double; Count: Integer; AngularUnits: Boolean): Boolean;
begin
Result := PointsTransformer.TransformPointsXY(Src, Dst,x,y,count,AngularUnits);
end;
function TProjectionsManager.TransformPointXY(const Src, Dst: IProjection;
var X, Y: Double; AngularUnits: Boolean): Boolean;
begin
Result := PointsTransformer.TransformPointXY(Src, Dst,x,y,AngularUnits);
end;
function TProjectionsManager.TryGetProjection(const Defn: string;
out Proj: IProjection): Boolean;
begin
Proj := nil;
Changes;
try
Result := (Defn <> '') and KnownProjections.TryGetValue(Defn,Proj);
if not Result then
begin
Result := MakeNewProjectionFromDefn(Defn,Proj) = 0;
if Result then
KnownProjections.AddOrSetValue(Proj.GetCreateDefinition,Proj);
end;
finally
Changed;
end;
end;
{ TPointsTransformer }
constructor TPointsTransformer.CreateOwned(AOwner: TProjectionsManager);
begin
inherited Create;
FOwner := AOwner;
end;
destructor TPointsTransformer.Destroy;
begin
inherited Destroy();
FOwner := nil;
end;
function TPointsTransformer.GetOwner: TPersistent;
begin
Result := FOwner;
end;
function TPointsTransformer.TransformPointsXY(const Src,Dst: IProjection; var X,Y: Double; Count: Integer;
AngularUnits: Boolean): Boolean;
begin
Result := Assigned(Src) and Assigned(Dst) and (Src.HandleValid) and (Dst.HandleValid);
if Result then
Result := PJ_transform_points2D(Src.Handle,Dst.Handle,@X,@Y,Count,AngularUnits) = 0;
end;
function TPointsTransformer.TransformPointXY(const Src,Dst: IProjection;
var X,Y: Double; AngularUnits: Boolean): Boolean;
begin
Result := TransformPointsXY(Src,Dst,X,Y,1,AngularUnits);
end;
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.Console.Command.Base;
interface
uses
DPM.Core.Configuration.Interfaces,
DPM.Core.Logging,
DPM.Console.ExitCodes,
DPM.Console.Command,
VSoft.CancellationToken;
type
TBaseCommand = class(TInterfacedObject, ICommandHandler)
private
FLogger : ILogger;
protected
FConfigurationManager : IConfigurationManager;
function Execute(const cancellationToken : ICancellationToken): TExitCode;virtual;
function ExecuteCommand(const cancellationToken : ICancellationToken) : TExitCode;
function ForceNoBanner : boolean;virtual;
property Logger : ILogger read FLogger;
public
constructor Create(const logger : ILogger; const configurationManager : IConfigurationManager);virtual;
end;
implementation
uses
DPM.Core.Constants,
DPM.Console.Options;
{ TBaseCommand }
constructor TBaseCommand.Create(const logger : ILogger; const configurationManager : IConfigurationManager);
begin
FLogger := logger;
FConfigurationManager := configurationManager;
end;
function TBaseCommand.Execute(const cancellationToken : ICancellationToken): TExitCode;
begin
result := TExitCode.NotImplemented;
end;
function TBaseCommand.ExecuteCommand(const cancellationToken : ICancellationToken): TExitCode;
begin
if not FConfigurationManager.EnsureDefaultConfig then
result := TExitCode.InitException
else
result := Execute(cancellationToken);
end;
function TBaseCommand.ForceNoBanner: boolean;
begin
result := false;
end;
end.
|
unit SerialNumberCls;
interface
uses classes,SysUtils, DbClient, ADODB, DB, Variants, ShellAPI, Forms, Windows, Dialogs,
Messages, StdCtrls, Buttons, ExtCtrls, ComCtrls;
type
TSerialNumber = class
FConnection: TADOConnection;
FSerialNumber: String;
FMaxQty: Integer;
FIsValidated: Boolean;
FIDModel : Integer;
FIDStore : Integer;
FIDItem : Integer;
FGiftCard : Boolean;
fIdInvoice: Integer;
// Antonio, August 06, 2013
fIsIssued: Byte;
private
function getSerialNumber: String;
procedure setSerialNumber(const Value: String);
procedure setMaxQty(const Value: Integer);
procedure setIdInvoice(const Value: Integer);
protected
procedure setConnection(connection: TADOConnection);
public
property IdInvoice: Integer write setIdInvoice;
property Connection: TADOConnection write setConnection;
property SerialNumber: String read getSerialNumber write setSerialNumber;
property MaxQty: Integer write setMaxQty;
property IsValidated: Boolean read FIsValidated;
property IsGiftCard: Boolean read FGiftCard write FGiftCard ;
property IsIssued: Byte read fIsIssued write fIsIssued;
constructor Create(idmodel, idstore, iditem, maxqty: Integer);
function getIsValidated(idItem: Integer): Boolean;
function addAccountNumber(serial_number: String): Boolean; virtual;
function getSerial(iditem: Integer): TDataSet; virtual; abstract;
function add(movId: Integer; serialNumber, identification, processor: String): Boolean; virtual; abstract;
function remove(movId: Integer; serialNumber: String): Boolean; virtual; abstract;
function getSerials(firstIdItem: Integer):TDataSet; virtual; abstract;
function getCountSerialNumber(IdItem: Integer): Integer; virtual; abstract;
end;
TSerialNumberFromPurchase = class(TSerialNumber)
end;
TSerialNumberFromInventory = class(TSerialNumber)
end;
TSerialNumberFromTransfer = class(TSerialNumber)
end;
TSerialNumberFromSale = class(TSerialNumber)
protected
function getSerial(iditem: Integer): TDataSet; override;
// function getSerial(serialNumber: String): TDataSet; override;
function add(movId: Integer; serialNumber, identification, processor: String): Boolean; override;
function remove(movId: Integer; serialNumber: String): Boolean;
function getSerials(firstIdItem: Integer):TDataSet; override;
function getCountSerialNumber(IdItem: Integer): Integer; override;
end;
TSerialNumberFromPreSale = class(TSerialNumber)
private
protected
function getSerial(iditem: Integer): TDataSet; override;
function add(movId: Integer; serialNumber, identification, processor: String): Boolean; override;
function remove(movId: Integer; serialNumber: String): Boolean;
function getSerials(firstIdItem: Integer):TDataSet; override;
function getCountSerialNumber(IdItem: Integer): Integer; override;
public
function isDuplicateSerial(serial_number: String; id_preinventory: Integer = 0): Boolean;
function getSerialCurrent(id_preinventory: Integer): TDataSet;
function getSerialRecorded: TDataSet;
procedure savePreserialToVerification(arg_cds: TClientDataset);
end;
implementation
uses uMsgConstant, uSystemConst, uDm;
{ TSerialNumberFromSale }
function TSerialNumberFromSale.add(movId: Integer; serialNumber, identification,
processor: String): Boolean;
var
qry: TADOQuery;
begin
result := false;
try
try
qry := TADOQuery.Create(nil);
qry.Connection := FConnection;
qry.SQL.Add('insert into SerialMov(InventoryMovID, SerialNumber, IdentificationNumber, Processor) values(:movid, :serial, :identifier, :processor)');
qry.Parameters.ParamByName('movid').Value := movId;
qry.Parameters.ParamByName('serial').Value := serialNumber;
qry.Parameters.ParamByName('identifier').Value := identification;
qry.Parameters.ParamByName('processor').Value := processor;
qry.ExecSQL;
result := true;
except
on e: Exception do
raise Exception.Create('Add Serial Number error: ' + e.Message);
end;
finally
freeAndNil(qry);
end;
end;
function TSerialNumberFromSale.getCountSerialNumber(
IdItem: Integer): Integer;
begin
//
end;
function TSerialNumberFromSale.getSerial(iditem: Integer): TDataSet;
var
qry: TADOQuery;
begin
try
result := nil;
qry := TADOQuery.Create(nil);
qry.Connection := FConnection;
qry.SQL.Add('select PreInventoryMovID, SerialNumber, IdentificationNumber, Processor');
qry.sql.Add(' from SerialMov');
qry.SQL.Add(' where InventoryMovID =:iditem');
qry.Parameters.ParamByName('iditem').Value := iditem;
qry.Open;
result := qry;
finally
freeAndNil(qry);
end;
end;
function TSerialNumberFromSale.getSerials(firstIdItem: Integer): TDataSet;
begin
//
end;
function TSerialNumberFromSale.remove(movId: Integer;
serialNumber: String): Boolean;
begin
//
end;
{ TSerialNumber }
function TSerialNumber.addAccountNumber(serial_number: String): Boolean;
var
qryInsert: TADOQuery;
dExpDate: TDateTime;
iMonth: Integer;
begin
iMonth := DM.fSystem.SrvParam[PARAM_GIFT_EXP_DATE];
if iMonth > 0 then
dExpDate := IncMonth(Now, iMonth);
result := false;
try
try
qryInsert := TADOQuery.Create(nil);
qryInsert.Connection := FConnection;
qryInsert.Sql.add('INSERT into Sal_AccountCard (IDAccountCard, CardNumber, CardDate, ExpirationDate, Amount, IDPreInventoryMov, IDUser)');
qryInsert.Sql.add(' VALUES (:IDAccountCard, :CardNumber, :CardDate, :ExpirationDate, :amount, :IDPreInventoryMov, :IDUser)');
qryInsert.Parameters.ParamByName('IDAccountCard').Value := DM.GetNextID('Sal_AccountCard.IDAccountCard');
qryInsert.Parameters.ParamByName('CardNumber').Value := serial_number;
qryInsert.Parameters.ParamByName('CardDate').Value := Now;
if iMonth > 0 then
qryInsert.Parameters.ParamByName('ExpirationDate').Value := dExpDate
else
qryInsert.Parameters.ParamByName('ExpirationDate').Value := NULL;
qryInsert.parameters.parambyname('amount').Value := 0;
qryInsert.Parameters.ParamByName('IDPreInventoryMov').Value := FIDItem;
qryInsert.Parameters.ParamByName('IDUser').Value := DM.fUser.ID;
qryInsert.ExecSQL;
result := true;
except
on e: exception do
raise exception.Create('Insert Sal_AccountCard error: ' + e.Message);
end;
finally
freeAndNil(qryInsert);
end;
end;
constructor TSerialNumber.Create(idmodel, idstore, iditem, maxqty: Integer);
begin
FIDModel := idmodel;
FIDStore := idstore;
FIDItem := iditem;
FMaxQty := maxqty;
end;
function TSerialNumber.getIsValidated(idItem: Integer): Boolean;
begin
//verify max quantity
result := ( getCountSerialNumber(idItem) < FMaxQty );
if ( not result ) then begin
raise Exception.Create('Can not enter more than ' + intToStr(FMaxQty )+ ' ' + MSG_EXC_PART2_NO_MORE_SERIAL);
result := false;
end;
FIsValidated := result;
end;
function TSerialNumber.getSerialNumber: String;
begin
result := FSerialNumber;
end;
procedure TSerialNumber.setConnection(connection: TADOConnection);
begin
FConnection := connection;
end;
procedure TSerialNumber.setIdInvoice(const Value: Integer);
begin
fIdInvoice := value;
end;
procedure TSerialNumber.setMaxQty(const Value: Integer);
begin
FMaxQty := value;
end;
procedure TSerialNumber.setSerialNumber(const Value: String);
begin
if ( Length(value) > 30 ) then begin
FSerialNumber := '';
raise Exception.Create(MSG_CRT_SERIAL_GREATER_THEN_30);
end;
if ( value = '' ) then begin
FSerialNumber := '';
raise Exception.Create(MSG_CRT_NO_SERIALNUMBER);
end;
FSerialNumber := value;
end;
{ TSerialNumberFromPreSale }
function TSerialNumberFromPreSale.add(movId: Integer; serialNumber, identification, processor: String): Boolean;
var
qry: TADOQuery;
cdsPreserialMov: TClientDataset;
begin
result := false;
try
try
qry := TADOQuery.Create(nil);
qry.Connection := FConnection;
qry.SQL.Add('insert into PreSerialMov (PreInventoryMovID, SerialNumber, IdentificationNumber, Processor, IsIssued) values(:movid, :serial, :identifier, :processor, :issued)');
qry.Parameters.ParamByName('movid').Value := movId;
qry.Parameters.ParamByName('serial').Value := serialNumber;
qry.Parameters.ParamByName('identifier').Value := identification;
qry.Parameters.ParamByName('processor').Value := processor;
// Antonio, August 06, 2013
if ( FGiftCard ) then
qry.Parameters.ParamByName('issued').Value := fIsIssued
else
qry.Parameters.ParamByName('issued').Value := null;
qry.ExecSQL;
result := true;
// save list to after compare serial numbers
dm.cdsPreserialMov.Insert();
dm.cdsPreserialMov.FieldByName('PreinventoryMovID').Value := movID;
dm.cdsPreserialMov.fieldByName('SerialNumber').Value := serialNumber;
dm.cdsPreserialMov.FieldByName('Invoice').value := intToStr(fIdInvoice);
dm.cdsPreserialMov.Post;
except
on e: Exception do
raise Exception.Create('Erro found when I tried add serial number: ' + e.Message);
end;
finally
freeAndNil(qry);
end;
end;
function TSerialNumberFromPreSale.getCountSerialNumber(
IdItem: Integer): Integer;
var
qry: TADOQuery;
begin
try
result := 0;
qry := TADOQuery.Create(nil);
qry.Connection := FConnection;
qry.SQL.Add('select PreInventoryMovID, SerialNumber, IdentificationNumber');
qry.sql.Add(' from PreSerialMov');
qry.SQL.Add(' where PreInventoryMovID =:preinv');
qry.Parameters.ParamByName('preinv').Value := idItem;
qry.Open;
if ( not qry.IsEmpty ) then
result := qry.RecordCount;
finally
freeAndNil(qry);
end;
end;
function TSerialNumberFromPreSale.getSerial(iditem: Integer): TDataSet;
var
qry: TADOQuery;
begin
try
result := nil;
qry := TADOQuery.Create(nil);
qry.Connection := FConnection;
qry.SQL.Add('select PreInventoryMovID, SerialNumber, IdentificationNumber, Processor');
qry.sql.Add(' from PreSerialMov');
qry.SQL.Add(' where PreInventoryMovID =:iditem');
qry.Parameters.ParamByName('iditem').Value := iditem;
qry.Open;
result := qry;
finally
// freeAndNil(qry);
end;
end;
function TSerialNumberFromPreSale.getSerialCurrent(
id_preinventory: Integer): TDataSet;
begin
result := getSerial(id_preinventory);
end;
function TSerialNumberFromPreSale.getSerialRecorded: TDataSet;
var
qry: TADOQuery;
begin
try
result := nil;
qry := TADOQuery.Create(nil);
qry.Connection := FConnection;
qry.SQL.Add('select InventoryMovID, SerialNumber, IdentificationNumber, Processor');
qry.sql.Add(' from SerialMov');
qry.Open;
result := qry;
finally
// freeAndNil(qry);
end;
end;
function TSerialNumberFromPreSale.getSerials(firstIdItem: Integer): TDataSet;
var
qry: TADOQuery;
begin
qry := TADOQuery.create(nil);
try
try
qry.Connection := FConnection;
qry.SQL.Add(' select');
qry.SQL.Add(' ac.IDPreInventoryMov');
qry.SQL.Add(' ,ac.CardNumber');
qry.SQL.Add(' ,CAST('''' as varchar(30)) IdentificationNumber');
qry.SQL.Add(' from Sal_AccountCard ac');
qry.SQL.Add(' where ac.IDPreInventoryMov between :idItemIni and :idItemEnd');
qry.Parameters.ParamByName('idItemIni').Value := firstIdItem;
qry.Parameters.ParamByName('idItemEnd').Value := FIDItem;
qry.Open;
result := qry;
except
on e: Exception do
raise Exception.Create('Get Serials Error: ' + e.Message);
end;
finally
freeAndNil(qry);
end;
end;
function TSerialNumberFromPreSale.isDuplicateSerial(serial_number: String; id_preinventory: Integer = 0): Boolean;
var
qry: TADOQuery;
begin
try
result := false;
// first I try for Sal_AccountCard
qry := TADOQuery.Create(nil);
qry.Connection := FConnection;
qry.SQL.Add('select CardNumber');
qry.sql.Add(' from Sal_AccountCard');
qry.SQL.Add(' where CardNumber =:serial');
qry.Parameters.ParamByName('serial').Value := serial_number;
qry.Open;
result := ( not qry.IsEmpty );
if ( result ) then
raise Exception.Create('Can not duplicate serial number [Sal_AccountCard]');
// finally I try
qry.Close;
qry.SQL.Add('select SerialNumber');
qry.sql.Add(' from PreSerialMov');
qry.SQL.Add(' where PreInventoryMovID =:idpreinv');
qry.Parameters.ParamByName('idpreinv').Value := id_preinventory;
qry.Open;
result := ( not qry.IsEmpty );
if ( result ) then
raise Exception.Create('Can not duplicate serial number [PreSerialMov]');
// finally I try
qry.Close;
qry.SQL.Add('SELECT Serial FROM InventorySerial WHERE ModelID=:modelId');
qry.sql.Add(' AND Serial =:serialNumber');
qry.SQL.Add(' AND StoreID =:idStore');
qry.Parameters.ParamByName('modelId').Value := FIDModel;
qry.Parameters.ParamByName('serialNumber').Value := serial_number;
qry.Parameters.ParamByName('idStore').Value := FIDStore;
qry.Open;
result := ( not qry.IsEmpty );
if ( result ) then
raise Exception.Create('Can not duplicate serial number [InventorySerial]');
finally
freeAndNil(qry);
end;
end;
function TSerialNumberFromPreSale.remove(movId: Integer;
serialNumber: String): Boolean;
begin
//
end;
procedure TSerialNumberFromPreSale.savePreserialToVerification(arg_cds: TClientDataset);
begin
try
arg_cds.post();
except
on e: Exception do
raise Exception.Create('fail to save PreserialMov list');
end;
end;
end.
|
unit Event.Cnst;
//------------------------------------------------------------------------------
// модуль определения событий для БД
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
interface
uses
Ils.MySql.EnumPublisher;
//------------------------------------------------------------------------------
const
CEventTypeTable = 'eventclass';
CEventKindTable = 'eventtype';
CEventSystemKindTable = 'eventsystemtype';
CEventGeoZoneKindTable = 'eventgeotype';
CEventTripKindTable = 'eventtriptype';
//------------------------------------------------------------------------------
type
TEventClass = (
ecBinarySensor,
ecMultilevelSensor,
ecGeoZone,
ecMove,
ecTrip,
ecWaypoint
);
TEventClasses = set of TEventClass;
TEventUserType = (
eutBinaryFall, //0
eutBinaryFront, //1
eutRangeIn, //2
eutRangeOut, //3
egzEnterZone, //4
egzLeaveZone, //5
egzEnterDepot, //6
egzLeaveDepot, //7
estTrackStop, //8
estTrackMove, //9
ettDepotEnter, //10
ettDepotLeave, //11
ettTripStarted, //12
ettTripFinished, //13
ettTripInRange, //14
ettTripOutOfRange, //15
ettTripLatePoint, //16
ettTripLeadPoint, //17
ettTripNotPoint, //18
ewpWaypointMoveIn, //19
ewpWaypointMoveOut, //20
ewpWaypointEnter, //21
ewpWaypointLeave //22
);
TEventUserTypes = set of TEventUserType;
TEventSystemType = (estVehicleStop, estVehicleMove);
const
CEventSystemType: array [TEventUserType] of string = (
'BinaryFall',
'BinaryFront',
'RangeIn',
'RangeOut',
'EnterZone',
'LeaveZone',
'EnterDepot',
'LeaveDepot',
'Stop',
'Move',
'DepotEnter',
'DepotLeave',
'TripStarted',
'TripFinished',
'TripInRange',
'TripOutOfRange',
'TripLatePoint',
'TripLeadPoint',
'TripNotPoint',
'WaypointMoveIn',
'WaypointMoveOut',
'WaypointEnter',
'WaypointLeave'
);
type
TEventSystemTypes = set of TEventUserType;
//------------------------------------------------------------------------------
const
CEventClassInfo: array[TEventClass] of TEnumTextInfo = (
(Name: 'binary'; Comment: 'События по бинарным датчикам'),
(Name: 'multilevel'; Comment: 'События по многоуровневым датчикам'),
(Name: 'geo'; Comment: 'События по геообъектам'),
(Name: 'move'; Comment: 'События по типу движения'),
(Name: 'trip'; Comment: 'События по плановому маршруту'),
(Name: 'waypoint'; Comment: 'События по путевым точкам')
);
CEventUserTypeInfo: array[TEventUserType] of TEnumTextInfo = (
(ClassID: Ord(ecBinarySensor); Name: 'Двухуровневый датчик выключен'; Comment: ''; Name2: 'Двухуровневый датчик включён'),
(ClassID: Ord(ecBinarySensor); Name: 'Двухуровневый датчик включён'; Comment: ''; Name2: 'Двухуровневый датчик выключен'),
(ClassID: Ord(ecMultilevelSensor); Name: 'Вход в диапазон'; Comment: 'Вход значения датчика в заданный диапазон'; Name2: 'Выход из диапазона'),
(ClassID: Ord(ecMultilevelSensor); Name: 'Выход из диапазона'; Comment: 'Выход значения датчика из заданного диапазона'; Name2: 'Вход в диапазон'),
(ClassID: Ord(ecGeoZone); Name: 'Вход в зону'; Comment: 'Первая точка в зоне'; Name2: 'Выход из зоны'),
(ClassID: Ord(ecGeoZone); Name: 'Выход из зоны'; Comment: 'Первая точка вне зоны'; Name2: 'Вход в зону'),
(ClassID: Ord(ecGeoZone); Name: 'Вход в точку'; Comment: 'Первое положение внутри точки'; Name2: 'Выход из точки'),
(ClassID: Ord(ecGeoZone); Name: 'Выход из точки'; Comment: 'Первое положение вне точки'; Name2: 'Вход в точку'),
(ClassID: Ord(ecMove); Name: 'Остановка'; Comment: 'Точка остановки'; Name2: 'Движение'),
(ClassID: Ord(ecMove); Name: 'Движение'; Comment: 'Точка начала движения'; Name2: 'Остановка'),
(ClassID: Ord(ecTrip); Name: 'Прибытие в точку'; Comment: ''; Name2: 'Убытие из точки'),
(ClassID: Ord(ecTrip); Name: 'Убытие из точки'; Comment: ''; Name2: 'Прибытие в точку'),
(ClassID: Ord(ecTrip); Name: 'Начало исполнения плана'; Comment: ''; Name2: ''),
(ClassID: Ord(ecTrip); Name: 'Окончание исполнения плана'; Comment: ''; Name2: ''),
(ClassID: Ord(ecTrip); Name: 'Возврат на плановый трек'; Comment: ''; Name2: 'Отклонение от планового трека'),
(ClassID: Ord(ecTrip); Name: 'Отклонение от планового трека'; Comment: ''; Name2: 'Возврат на плановый трек'),
(ClassID: Ord(ecTrip); Name: 'Опоздание на плановую точку'; Comment: ''; Name2: ''),
(ClassID: Ord(ecTrip); Name: 'Опережение плановой точки'; Comment: ''; Name2: ''),
(ClassID: Ord(ecTrip); Name: 'Остановка вне плановой точки'; Comment: ''; Name2: ''),
(ClassID: Ord(ecWaypoint); Name: 'Приближение к плановой точке'; Comment: ''; Name2: 'Удаление от плановой точки'),
(ClassID: Ord(ecWaypoint); Name: 'Удаление от плановой точки'; Comment: ''; Name2: 'Приближение к плановой точке'),
(ClassID: Ord(ecWaypoint); Name: 'Вход в плановую точку'; Comment: ''; Name2: 'Выход из плановуй точки'),
(ClassID: Ord(ecWaypoint); Name: 'Выход из плановуй точки'; Comment: ''; Name2: 'Вход в плановую точку')
);
//------------------------------------------------------------------------------
implementation
end.
|
{ ============================================
Software Name : RFID_ACCESS
============================================ }
{ ******************************************** }
{ Written By WalWalWalides }
{ CopyRight © 2019 }
{ Email : WalWalWalides@gmail.com }
{ GitHub :https://github.com/walwalwalides }
{ ******************************************** }
unit UStates;
interface
uses
System.Classes, System.SysUtils;
type
IStateDispacher = interface
procedure Notify(Obj : TObject);
end;
TPAppStateEnum = (
stUnknow,
stPrepareUI,
stVerifyData,
stRunning,
stPrepareMode,
stShutDown
);
IPAppState = interface
procedure Execute;
function EnumState : TPAppStateEnum;
end;
TPAppState = class
private
FState : IPAppState;
FStateDispacher : IStateDispacher;
FOnChangeState : TNotifyEvent;
procedure SetState(State : IPAppState);
function GetState: TPAppStateEnum;
public
constructor Create(StateDisp : IStateDispacher);
destructor Destroy; override;
procedure ChangeState(const State : TPAppStateEnum);
procedure Execute;
property EnumState : TPAppStateEnum read GetState;
property OnChangeState : TNotifyEvent read FOnChangeState write FOnChangeState;
end;
implementation
uses
Base;
{ TPAppState }
procedure TPAppState.ChangeState(const State: TPAppStateEnum);
begin
case State of
TPAppStateEnum.stPrepareUI :
begin
Self.SetState(TStatePrepareUI.Create);
Self.Execute;
end;
TPAppStateEnum.stVerifyData :
begin
if FState is TStatePrepareUI then
begin
Self.SetState(TStatePrepareDataBase.Create);
Self.Execute;
end;
end;
TPAppStateEnum.stShutDown :
begin
if not (FState is TStateShutDown) then
begin
Self.SetState(TStateShutDown.Create);
Self.Execute;
end;
end;
end;
if Assigned (FOnChangeState) then FOnChangeState(Self);
FStateDispacher.Notify(Self);
end;
constructor TPAppState.Create(StateDisp : IStateDispacher);
begin
FStateDispacher := StateDisp;
end;
destructor TPAppState.Destroy;
begin
FState := nil;
inherited;
end;
procedure TPAppState.Execute;
begin
FState.Execute;
end;
function TPAppState.GetState: TPAppStateEnum;
begin
Result := FState.EnumState;
end;
procedure TPAppState.SetState(State: IPAppState);
begin
FState := State;
end;
end.
|
{ ******************************************************* }
{ }
{ TFacturaElectronica }
{ }
{ Copyright (C) 2017 Bambu Code SA de CV }
{ }
{ ******************************************************* }
unit Facturacion.PAC.Ecodex;
interface
uses Facturacion.ProveedorAutorizadoCertificacion,
Facturacion.Comprobante,
EcodexWsComun,
EcodexWsTimbrado,
EcodexWsClientes,
EcodexWsCancelacion,
PAC.Ecodex.ManejadorDeSesion,
System.Generics.Collections,
System.SysUtils;
type
TProveedorEcodex = class(TInterfacedObject, IProveedorAutorizadoCertificacion)
private
fCredencialesPAC: TFacturacionCredencialesPAC;
fDominioWebService: string;
fManejadorDeSesion: TEcodexManejadorDeSesion;
fwsClientesEcodex: IEcodexServicioClientes;
fwsTimbradoEcodex: IEcodexServicioTimbrado;
fwsCancelacionEcodex: IEcodexServicioCancelacion;
function ExtraerNodoTimbre(const aComprobanteXML: TEcodexComprobanteXML)
: TCadenaUTF8;
procedure ProcesarExcepcionDePAC(const aExcepcion: Exception);
public
procedure Configurar(const aDominioWebService: string;
const aCredencialesPAC: TFacturacionCredencialesPAC;
const aTransaccionInicial: Int64);
function ObtenerSaldoTimbresDeCliente(const aRFC: String): Integer;
function CancelarDocumento(const aUUID: TCadenaUTF8): Boolean;
function CancelarDocumentos(const aUUIDS: TListadoUUID):
TListadoCancelacionUUID;
function TimbrarDocumento(const aComprobante: IComprobanteFiscal;
const aTransaccion: Int64): TCadenaUTF8;
function ObtenerAcuseDeCancelacion(const aUUID: string): string;
end;
const
_LONGITUD_UUID = 36;
implementation
uses Classes,
xmldom,
Facturacion.Tipos,
Soap.XSBuiltIns,
XMLIntf,
{$IFDEF CODESITE}
CodeSiteLogging,
{$ENDIF}
System.RegularExpressions,
{$IF Compilerversion >= 20}
Xml.Win.Msxmldom,
{$ELSE}
Msxmldom,
{$IFEND}
XMLDoc;
{ TProveedorEcodex }
procedure TProveedorEcodex.Configurar(const aDominioWebService: string;
const aCredencialesPAC: TFacturacionCredencialesPAC;
const aTransaccionInicial: Int64);
begin
fDominioWebService := aDominioWebService;
fCredencialesPAC := aCredencialesPAC;
fManejadorDeSesion := TEcodexManejadorDeSesion.Create(fDominioWebService,
aTransaccionInicial);
fManejadorDeSesion.AsignarCredenciales(fCredencialesPAC);
// Incializamos las instancias de los WebServices
fwsTimbradoEcodex := GetWsEcodexTimbrado(False, fDominioWebService +
'/ServicioTimbrado.svc');
fwsClientesEcodex := GetWsEcodexClientes(False, fDominioWebService +
'/ServicioClientes.svc');
fwsCancelacionEcodex := GetWsEcodexCancelacion(False, fDominioWebService +
'/ServicioCancelacion.svc');
end;
function TProveedorEcodex.ExtraerNodoTimbre(const aComprobanteXML
: TEcodexComprobanteXML): TCadenaUTF8;
var
contenidoComprobanteXML: TCadenaUTF8;
const
_REGEX_TIMBRE = '<tfd:TimbreFiscalDigital.*?/>';
begin
Assert(aComprobanteXML <> nil,
'La respuesta del servicio de timbrado fue nula');
{$IF Compilerversion >= 20}
// Delphi 2010 y superiores
contenidoComprobanteXML := aComprobanteXML.DatosXML;
{$ELSE}
contenidoComprobanteXML := UTF8Encode(aComprobanteXML.DatosXML);
{$IFEND}
Result := TRegEx.Match(contenidoComprobanteXML, _REGEX_TIMBRE).Value;
Assert(Result <> '', 'El XML del timbre estuvo vacio');
end;
function TProveedorEcodex.ObtenerSaldoTimbresDeCliente
(const aRFC: String): Integer;
var
solicitudEdoCuenta: TEcodexSolicitudEstatusCuenta;
respuestaEdoCuenta: TEcodexRespuestaEstatusCuenta;
tokenDeUsuario: string;
I: Integer;
begin
Assert(Trim(aRFC) <> '', 'El RFC para la solicitud de saldo fue vacio');
Assert(fManejadorDeSesion <> nil,
'La instancia fManejadorDeSesion no debio ser nula');
Assert(fwsClientesEcodex <> nil,
'La instancia fwsClientesEcodex no debio ser nula');
Result := 0;
// 1. Creamos la solicitud del edo de cuenta
solicitudEdoCuenta := TEcodexSolicitudEstatusCuenta.Create;
// 2. Iniciamos una nueva sesion solicitando un nuevo token
tokenDeUsuario := fManejadorDeSesion.ObtenerNuevoTokenDeUsuario;
try
solicitudEdoCuenta.RFC := aRFC;
solicitudEdoCuenta.Token := tokenDeUsuario;
solicitudEdoCuenta.TransaccionID := fManejadorDeSesion.NumeroDeTransaccion;
try
respuestaEdoCuenta := fwsClientesEcodex.EstatusCuenta(solicitudEdoCuenta);
{$IFDEF CODESITE}
CodeSite.Send('Codigo', respuestaEdoCuenta.Estatus.Codigo);
CodeSite.Send('Descripcion', respuestaEdoCuenta.Estatus.Descripcion);
CodeSite.Send('Fecha de Inicio', respuestaEdoCuenta.Estatus.FechaInicio);
CodeSite.Send('Fecha de fin', respuestaEdoCuenta.Estatus.FechaFin);
CodeSite.Send('Timbres asignados',
respuestaEdoCuenta.Estatus.TimbresAsignados);
CodeSite.Send('Timbres disponibles',
respuestaEdoCuenta.Estatus.TimbresDisponibles);
CodeSite.Send('Num certificados cargados',
Length(respuestaEdoCuenta.Estatus.Certificados));
// Mostramos los certificados cargados
for I := 0 to Length(respuestaEdoCuenta.Estatus.Certificados) - 1 do
begin
CodeSite.Send('Certificado cargado Num. ' + IntToStr(I),
respuestaEdoCuenta.Estatus.Certificados[I]);
end;
{$ENDIF}
// 3. Regresamos los timbres disponibles y no los asignados
Result := respuestaEdoCuenta.Estatus.TimbresDisponibles;
except
On E: Exception do
if Not(E Is EPACException) then
ProcesarExcepcionDePAC(E)
else
raise;
end;
finally
// fUltimoXMLEnviado := GetUltimoXMLEnviadoEcodexWsClientes;
// fUltimoXMLRecibido := GetUltimoXMLRecibidoEcodexWsClientes;
solicitudEdoCuenta.Free;
end;
end;
procedure TProveedorEcodex.ProcesarExcepcionDePAC(const aExcepcion: Exception);
var
mensajeExcepcion: string;
numeroErrorSAT: Integer;
begin
mensajeExcepcion := aExcepcion.Message;
if (aExcepcion Is EEcodexFallaValidacionException) Or
(aExcepcion Is EEcodexFallaServicioException) Or
(aExcepcion is EEcodexFallaSesionException) then
begin
if (aExcepcion Is EEcodexFallaValidacionException) then
begin
mensajeExcepcion := EEcodexFallaValidacionException(aExcepcion)
.Descripcion;
numeroErrorSAT := EEcodexFallaValidacionException(aExcepcion).Numero;
case numeroErrorSAT of
// Errores técnicos donde la librería no creo bien el XML
33101, 33102, 33105, 33106, 33111, 33116, 33126, 33127, 33128,
33139, 33143, 33150:
raise ESATErrorTecnicoXMLException.Create(mensajeExcepcion,
numeroErrorSAT, False);
// Algun valor que debía venir de un catálogo no fue correcto
33104, 33112, 33120, 33121, 33125, 33130, 33136, 33140, 33142, 33145,
33155, 33156, 33164, 33165, 33172, 33185:
raise ESATValorNoEnCatalogoException.Create(mensajeExcepcion,
numeroErrorSAT, False);
// Problema donde los datos del emisor no son correctos
33131:
raise ESATDatoEmisorIncorrectoException.Create(mensajeExcepcion,
numeroErrorSAT, False);
// Problema donde los datos del receptor no son correctos
33132, 33133, 33134, 33135:
raise ESATDatoReceptorIncorrectoException.Create(mensajeExcepcion,
numeroErrorSAT, False);
// Errores de validacion, reglas de negocio, etc.
33107, 33108, 33109, 33110, 33113, 33114, 33115, 33118, 33122, 33123,
33124, 33137, 33138, 33141, 33144, 33147, 33149, 33152, 33154,
33157, 33158, 33159, 33161, 33166, 33167, 33169, 33170, 33171, 33174,
33176, 33177, 33178, 33103, 33179, 33180, 33181, 33182, 33183, 33184,
33186, 33187, 33189, 33190, 33192, 33193, 33195:
raise ESATProblemaDeLlenadoException.Create(mensajeExcepcion,
numeroErrorSAT, False);
33196:
raise ESATNoIdentificadoException.Create(mensajeExcepcion,
numeroErrorSAT, False);
else
raise ESATErrorGenericoException.Create('EFallaValidacionException (' +
IntToStr(EEcodexFallaValidacionException(aExcepcion).Numero) + ') ' +
mensajeExcepcion, numeroErrorSAT, False);
end;
end;
if (aExcepcion Is EEcodexFallaServicioException) then
begin
case EEcodexFallaServicioException(aExcepcion).Numero of
29: raise EPACCancelacionFallidaCertificadoNoCargadoException.Create(EEcodexFallaServicioException(aExcepcion).Descripcion,
0,
EEcodexFallaServicioException(aExcepcion).Numero,
False); // NO es reintentable
end;
mensajeExcepcion := 'EFallaServicioException (' +
IntToStr(EEcodexFallaServicioException(aExcepcion).Numero) + ') ' +
EEcodexFallaServicioException(aExcepcion).Descripcion;
end;
if (aExcepcion Is EEcodexFallaSesionException) then
begin
mensajeExcepcion := 'EEcodexFallaSesionException (' +
IntToStr(EEcodexFallaSesionException(aExcepcion).Estatus) + ') ' +
EEcodexFallaSesionException(aExcepcion).Descripcion;
end;
// Si llegamos aqui y no se ha lanzado ningun otro error lanzamos el error genérico de PAC
// con la propiedad reintentable en verdadero para que el cliente pueda re-intentar el proceso anterior
raise EPACErrorGenericoException.Create(mensajeExcepcion, 0, 0, True);
end;
end;
function TProveedorEcodex.TimbrarDocumento(const aComprobante
: IComprobanteFiscal; const aTransaccion: Int64): TCadenaUTF8;
var
solicitudTimbrado: TSolicitudTimbradoEcodex;
respuestaTimbrado: TEcodexRespuestaTimbrado;
tokenDeUsuario: string;
mensajeFalla: string;
begin
if fwsTimbradoEcodex = nil then
raise EPACNoConfiguradoException.Create
('No se ha configurado el PAC, favor de configurar con metodo Configurar');
// 1. Creamos la solicitud de timbrado
solicitudTimbrado := TSolicitudTimbradoEcodex.Create;
try
// 2. Iniciamos una nueva sesion solicitando un nuevo token
tokenDeUsuario := fManejadorDeSesion.ObtenerNuevoTokenDeUsuario();
// 3. Asignamos el documento XML
solicitudTimbrado.ComprobanteXML := TEcodexComprobanteXML.Create;
solicitudTimbrado.ComprobanteXML.DatosXML := aComprobante.Xml;
solicitudTimbrado.RFC := fCredencialesPAC.RFC;
solicitudTimbrado.Token := tokenDeUsuario;
solicitudTimbrado.TransaccionID := aTransaccion;
try
mensajeFalla := '';
// 4. Realizamos la solicitud de timbrado
respuestaTimbrado := fwsTimbradoEcodex.TimbraXML(solicitudTimbrado);
Result := ExtraerNodoTimbre(respuestaTimbrado.ComprobanteXML);
respuestaTimbrado.Free;
except
On E: Exception do
ProcesarExcepcionDePAC(E);
end;
finally
if Assigned(solicitudTimbrado) then
solicitudTimbrado.Free;
end;
end;
function TProveedorEcodex.CancelarDocumento(const aUUID: TCadenaUTF8): Boolean;
var
arregloUUIDs: TListadoUUID;
resultadoCancelacion : TListadoCancelacionUUID;
solicitudCancelacion: TEcodexSolicitudCancelacion;
respuestaCancelacion: TEcodexRespuestaCancelacion;
tokenDeUsuario : String;
begin
Assert(Length(aUUID) = _LONGITUD_UUID, 'La longitud del UUID debio de ser de ' + IntToStr(_LONGITUD_UUID));
tokenDeUsuario := fManejadorDeSesion.ObtenerNuevoTokenDeUsuario();
solicitudCancelacion := TEcodexSolicitudCancelacion.Create;
try
solicitudCancelacion.RFC := fCredencialesPAC.RFC;
solicitudCancelacion.Token := tokenDeUsuario;
solicitudCancelacion.TransaccionID := fManejadorDeSesion.NumeroDeTransaccion;
solicitudCancelacion.UUID := aUUID;
try
respuestaCancelacion := fwsTimbradoEcodex.CancelaTimbrado(solicitudCancelacion);
Result := respuestaCancelacion.Cancelada;
respuestaCancelacion.Free;
except
On E: Exception do
ProcesarExcepcionDePAC(E);
end;
finally
solicitudCancelacion.Free;
end;
end;
function TProveedorEcodex.ObtenerAcuseDeCancelacion(const aUUID: string):
string;
var
tokenDeUsuario: String;
solicitudAcuse : TEcodexSolicitudAcuse;
respuestaAcuse : TEcodexRespuestaRecuperarAcuse;
begin
Assert(Length(aUUID) = _LONGITUD_UUID, 'La longitud del UUID debio de ser de ' + IntToStr(_LONGITUD_UUID));
Result := '';
// 1. Creamos la solicitud de cancelacion
solicitudAcuse := TEcodexSolicitudAcuse.Create;
// 2. Iniciamos una nueva sesion solicitando un nuevo token
tokenDeUsuario := fManejadorDeSesion.ObtenerNuevoTokenDeUsuario;
try
try
solicitudAcuse.UUID := aUUID;
solicitudAcuse.RFC := fCredencialesPAC.RFC;
solicitudAcuse.Token := tokenDeUsuario;
solicitudAcuse.TransaccionID := fManejadorDeSesion.NumeroDeTransaccion;
respuestaAcuse := fwsCancelacionEcodex.RecuperarAcuses(solicitudAcuse);
Result := respuestaAcuse.AcuseXML;
respuestaAcuse.Free;
except
On E:Exception do
ProcesarExcepcionDePAC(E);
end;
finally
if Assigned(solicitudAcuse) then
solicitudAcuse.Free;
end;
end;
function TProveedorEcodex.CancelarDocumentos(const aUUIDS: TListadoUUID):
TListadoCancelacionUUID;
var
solicitudCancelacion: TEcodexSolicitudCancelaMultiple;
respuestaCancelacion: TEcodexRespuestaCancelaMultiple;
tokenDeUsuario: string;
mensajeFalla: string;
uuidPorCancelar, estado: String;
I: Integer;
arregloGuids : Array_Of_guid;
const
// Ref: Pagina 15 de "Guia de integracion Ecodex".
_CADENA_CANCELADO = 'Cancelado';
begin
Assert(fwsCancelacionEcodex <> nil, 'La instancia fwsCancelacionEcodex no debio ser nula');
if fwsTimbradoEcodex = nil then
raise EPACNoConfiguradoException.Create
('No se ha configurado el PAC, favor de configurar con metodo Configurar');
// 1. Creamos la solicitud de timbrado
solicitudCancelacion := TEcodexSolicitudCancelaMultiple.Create;
Result := TDictionary<String, Boolean>.Create;
try
// 2. Iniciamos una nueva sesion solicitando un nuevo token
tokenDeUsuario := fManejadorDeSesion.ObtenerNuevoTokenDeUsuario();
// 3. Asignamos los parametros de cancelacion
SetLength(arregloGuids, Length(aUUIDS));
for I := 0 to Length(aUUIDS) - 1 do
begin
uuidPorCancelar := aUUIDS[I];
arregloGuids[I] := uuidPorCancelar;
end;
solicitudCancelacion.TEcodexListaCancelar := TEcodexListaCancelar2.Create;
solicitudCancelacion.TEcodexListaCancelar.guid := arregloGuids;
solicitudCancelacion.RFC := TXSString.Create;
solicitudCancelacion.RFC.XSToNative(fCredencialesPAC.RFC);
solicitudCancelacion.Token := TXSString.Create;
solicitudCancelacion.Token.XSToNative(tokenDeUsuario);
solicitudCancelacion.TransaccionID := fManejadorDeSesion.NumeroDeTransaccion;
try
mensajeFalla := '';
// 4. Realizamos la solicitud de cancelacion
respuestaCancelacion := fwsCancelacionEcodex.CancelaMultiple(solicitudCancelacion);
// Convertir el array que regresa Ecodex al dictionary que
// estamos regresando
for I := 0 to Length(respuestaCancelacion.Resultado.TEcodexResultadoCancelacion) - 1 do
begin
estado := respuestaCancelacion.Resultado.TEcodexResultadoCancelacion[I].Estatus.NativeToXS;
Result.Add(respuestaCancelacion.Resultado.TEcodexResultadoCancelacion[I].UUID,
estado = _CADENA_CANCELADO);
end;
respuestaCancelacion.Free;
except
On E: Exception do
ProcesarExcepcionDePAC(E);
end;
finally
if Assigned(solicitudCancelacion) then
solicitudCancelacion.Free;
end;
end;
end.
|
unit UDFormulas;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, ExtCtrls, Buttons, UCrpe32;
type
TCrpeFormulasDlg = class(TForm)
pnlFormulas: TPanel;
lblFormula: TLabel;
lblNames: TLabel;
lbNames: TListBox;
memoFormulas: TMemo;
editCount: TEdit;
lblCount: TLabel;
cbFormulaSyntax: TComboBox;
lblFormulaSyntax: TLabel;
gbFormat: TGroupBox;
editFieldName: TEdit;
lblFieldName: TLabel;
lblFieldType: TLabel;
editFieldType: TEdit;
lblFieldLength: TLabel;
editFieldLength: TEdit;
btnBorder: TButton;
btnFont: TButton;
btnFormat: TButton;
editTop: TEdit;
lblTop: TLabel;
lblLeft: TLabel;
editLeft: TEdit;
lblSection: TLabel;
editWidth: TEdit;
lblWidth: TLabel;
lblHeight: TLabel;
editHeight: TEdit;
cbSection: TComboBox;
btnOk: TButton;
btnClear: TButton;
FontDialog1: TFontDialog;
btnCheck: TButton;
btnCheckAll: TButton;
rgUnits: TRadioGroup;
btnHiliteConditions: TButton;
cbObjectPropertiesActive: TCheckBox;
procedure btnCheckClick(Sender: TObject);
procedure btnCheckAllClick(Sender: TObject);
procedure btnClearClick(Sender: TObject);
procedure lbNamesClick(Sender: TObject);
procedure memoFormulasChange(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure UpdateFormulas;
procedure btnOkClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure cbFormulaSyntaxChange(Sender: TObject);
procedure btnFontClick(Sender: TObject);
procedure editSizeEnter(Sender: TObject);
procedure editSizeExit(Sender: TObject);
procedure cbSectionChange(Sender: TObject);
procedure btnBorderClick(Sender: TObject);
procedure btnFormatClick(Sender: TObject);
procedure rgUnitsClick(Sender: TObject);
procedure btnHiliteConditionsClick(Sender: TObject);
procedure InitializeControls(OnOff: boolean);
procedure InitializeFormatControls(OnOff: boolean);
procedure cbObjectPropertiesActiveClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Cr : TCrpe;
PrevSize : string;
FormulaIndex : integer;
end;
var
CrpeFormulasDlg: TCrpeFormulasDlg;
bFormulas : boolean;
implementation
{$R *.DFM}
uses TypInfo, UCrpeUtl, UDBorder, UDFormat, UDHiliteConditions,
UDFont, UCrpeClasses;
{------------------------------------------------------------------------------}
{ FormCreate }
{------------------------------------------------------------------------------}
procedure TCrpeFormulasDlg.FormCreate(Sender: TObject);
begin
bFormulas := True;
LoadFormPos(Self);
btnOk.Tag := 1;
FormulaIndex := -1;
cbObjectPropertiesActive.Tag := 1;
end;
{------------------------------------------------------------------------------}
{ FormShow }
{------------------------------------------------------------------------------}
procedure TCrpeFormulasDlg.FormShow(Sender: TObject);
begin
UpdateFormulas;
end;
{------------------------------------------------------------------------------}
{ UpdateFormulas }
{------------------------------------------------------------------------------}
procedure TCrpeFormulasDlg.UpdateFormulas;
var
OnOff : boolean;
begin
FormulaIndex := -1;
{Enable/Disable controls}
if IsStrEmpty(Cr.ReportName) then
OnOff := False
else
begin
OnOff := (Cr.Formulas.Count > 0);
{Get Formulas Index}
if OnOff then
begin
if Cr.Formulas.ItemIndex > -1 then
FormulaIndex := Cr.Formulas.ItemIndex
else
FormulaIndex := 0;
end;
end;
cbObjectPropertiesActive.Checked := Cr.Formulas.ObjectPropertiesActive;
InitializeControls(OnOff);
{Update list box}
if OnOff then
begin
{Fill Section ComboBox}
cbSection.Clear;
cbSection.Items.AddStrings(Cr.SectionFormat.Names);
{Fill Names ListBox}
lbNames.Items.AddStrings(Cr.Formulas.Names);
cbFormulaSyntax.ItemIndex := Ord(Cr.FormulaSyntax);
editCount.Text := IntToStr(Cr.Formulas.Count);
lbNames.ItemIndex := FormulaIndex;
lbNamesClick(self);
end;
end;
{------------------------------------------------------------------------------}
{ InitializeControls }
{------------------------------------------------------------------------------}
procedure TCrpeFormulasDlg.InitializeControls(OnOff: boolean);
var
i : integer;
begin
{Enable/Disable the Form Controls}
for i := 0 to ComponentCount - 1 do
begin
if TComponent(Components[i]).Tag = 0 then
begin
if Components[i] is TButton then
TButton(Components[i]).Enabled := OnOff;
if Components[i] is TRadioGroup then
TRadioGroup(Components[i]).Enabled := OnOff;
if Components[i] is TComboBox then
begin
TComboBox(Components[i]).Color := ColorState(OnOff);
TComboBox(Components[i]).Enabled := OnOff;
end;
if Components[i] is TListBox then
begin
TListBox(Components[i]).Clear;
TListBox(Components[i]).Color := ColorState(OnOff);
TListBox(Components[i]).Enabled := OnOff;
end;
if Components[i] is TEdit then
begin
TEdit(Components[i]).Text := '';
if TEdit(Components[i]).ReadOnly = False then
TEdit(Components[i]).Color := ColorState(OnOff);
TEdit(Components[i]).Enabled := OnOff;
end;
if Components[i] is TMemo then
begin
TMemo(Components[i]).Clear;
TMemo(Components[i]).Color := ColorState(OnOff);
TMemo(Components[i]).Enabled := OnOff;
end;
end;
end;
end;
{------------------------------------------------------------------------------}
{ InitializeFormatControls }
{------------------------------------------------------------------------------}
procedure TCrpeFormulasDlg.InitializeFormatControls(OnOff: boolean);
var
i : integer;
begin
{Enable/Disable the Form Controls}
for i := 0 to ComponentCount - 1 do
begin
{Check Tag}
if TComponent(Components[i]).Tag <> 0 then
Continue;
{Make sure these components are owned by the Format groupbox}
if Components[i] is TButton then
begin
if TButton(Components[i]).Parent <> gbFormat then Continue;
TButton(Components[i]).Enabled := OnOff;
end;
if Components[i] is TRadioGroup then
begin
if TRadioGroup(Components[i]).Parent <> gbFormat then Continue;
TRadioGroup(Components[i]).Enabled := OnOff;
end;
if Components[i] is TComboBox then
begin
if TComboBox(Components[i]).Parent <> gbFormat then Continue;
TComboBox(Components[i]).Color := ColorState(OnOff);
TComboBox(Components[i]).Enabled := OnOff;
end;
if Components[i] is TEdit then
begin
if TEdit(Components[i]).Parent <> gbFormat then Continue;
TEdit(Components[i]).Text := '';
if TEdit(Components[i]).ReadOnly = False then
TEdit(Components[i]).Color := ColorState(OnOff);
TEdit(Components[i]).Enabled := OnOff;
end;
end;
end;
{------------------------------------------------------------------------------}
{ lbNamesClick }
{------------------------------------------------------------------------------}
procedure TCrpeFormulasDlg.lbNamesClick(Sender: TObject);
var
OnOff : Boolean;
begin
FormulaIndex := lbNames.ItemIndex;
memoFormulas.OnChange := nil;
memoFormulas.Lines.Assign(Cr.Formulas[FormulaIndex].Formula);
memoFormulas.OnChange := memoFormulasChange;
cbFormulaSyntax.ItemIndex := Ord(Cr.FormulaSyntax);
{Activate Format options}
OnOff := Cr.Formulas.Item.Handle > 0;
InitializeFormatControls(OnOff);
if OnOff then
begin
{Field Info}
editFieldName.Text := Cr.Formulas.Item.FieldName;
editFieldType.Text := GetEnumName(TypeInfo(TCrFieldValueType),
Ord(Cr.Formulas.Item.FieldType));
editFieldLength.Text := IntToStr(Cr.Formulas.Item.FieldLength);
{Size and Position}
cbSection.ItemIndex := Cr.SectionFormat.IndexOf(Cr.Formulas.Item.Section);
rgUnitsClick(Self);
end;
{Set HiliteConditions button}
btnHiliteConditions.Enabled := (Cr.Formulas.Item.FieldType in [fvInt8s..fvCurrency])
and OnOff;
end;
{------------------------------------------------------------------------------}
{ rgUnitsClick }
{------------------------------------------------------------------------------}
procedure TCrpeFormulasDlg.rgUnitsClick(Sender: TObject);
begin
if rgUnits.ItemIndex = 0 then {inches}
begin
editTop.Text := TwipsToInchesStr(Cr.Formulas.Item.Top);
editLeft.Text := TwipsToInchesStr(Cr.Formulas.Item.Left);
editWidth.Text := TwipsToInchesStr(Cr.Formulas.Item.Width);
editHeight.Text := TwipsToInchesStr(Cr.Formulas.Item.Height);
end
else {twips}
begin
editTop.Text := IntToStr(Cr.Formulas.Item.Top);
editLeft.Text := IntToStr(Cr.Formulas.Item.Left);
editWidth.Text := IntToStr(Cr.Formulas.Item.Width);
editHeight.Text := IntToStr(Cr.Formulas.Item.Height);
end;
end;
{------------------------------------------------------------------------------}
{ memoFormulasChange }
{------------------------------------------------------------------------------}
procedure TCrpeFormulasDlg.memoFormulasChange(Sender: TObject);
begin
Cr.Formulas.Item.Formula.Assign(memoFormulas.Lines);
end;
{------------------------------------------------------------------------------}
{ cbFormulaSyntaxChange }
{------------------------------------------------------------------------------}
procedure TCrpeFormulasDlg.cbFormulaSyntaxChange(Sender: TObject);
begin
Cr.FormulaSyntax := TCrFormulaSyntax(cbFormulaSyntax.ItemIndex);
end;
{------------------------------------------------------------------------------}
{ btnCheckClick }
{------------------------------------------------------------------------------}
procedure TCrpeFormulasDlg.btnCheckClick(Sender: TObject);
begin
if Cr.Formulas.Item.Check then
MessageDlg('Formula is Good!', mtInformation, [mbOk], 0)
else
MessageDlg('Formula has an Error.' + Chr(10) +
Cr.LastErrorString, mtError, [mbOk], 0);
end;
{------------------------------------------------------------------------------}
{ btnCheckAllClick }
{------------------------------------------------------------------------------}
procedure TCrpeFormulasDlg.btnCheckAllClick(Sender: TObject);
var
i : integer;
s : string;
begin
Screen.Cursor := crHourglass;
lbNames.ItemIndex := 0;
for i := 0 to (lbNames.Items.Count - 1) do
begin
lbNames.ItemIndex:= i;
memoFormulas.OnChange := nil;
memoFormulas.Lines.Assign(Cr.Formulas[i].Formula);
memoFormulas.OnChange := memoFormulasChange;
if not Cr.Formulas.Item.Check then
begin
MessageBeep(0);
s := 'The Formula "' + Cr.Formulas.Item.Name + '" has an error!' +
Chr(10) + 'Continue checking?';
if Application.MessageBox(PChar(s), 'Formula Error', MB_OKCANCEL + MB_DEFBUTTON1) = IDOK then
Continue
else
Break;
end;
end;
if i = (lbNames.Items.Count) then
begin
MessageBeep(0);
MessageDlg('Finished verifying formulas!', mtInformation, [mbOk], 0)
end;
Screen.Cursor := crDefault;
end;
{------------------------------------------------------------------------------}
{ cbObjectPropertiesActiveClick }
{------------------------------------------------------------------------------}
procedure TCrpeFormulasDlg.cbObjectPropertiesActiveClick(Sender: TObject);
begin
Cr.Formulas.ObjectPropertiesActive := cbObjectPropertiesActive.Checked;
UpdateFormulas;
end;
{------------------------------------------------------------------------------}
{ editSizeEnter }
{------------------------------------------------------------------------------}
procedure TCrpeFormulasDlg.editSizeEnter(Sender: TObject);
begin
if Sender is TEdit then
PrevSize := TEdit(Sender).Text;
end;
{------------------------------------------------------------------------------}
{ editSizeExit }
{------------------------------------------------------------------------------}
procedure TCrpeFormulasDlg.editSizeExit(Sender: TObject);
begin
if rgUnits.ItemIndex = 0 then {inches}
begin
if not IsFloating(TEdit(Sender).Text) then
TEdit(Sender).Text := PrevSize
else
begin
if TEdit(Sender).Name = 'editTop' then
Cr.Formulas.Item.Top := InchesStrToTwips(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editLeft' then
Cr.Formulas.Item.Left := InchesStrToTwips(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editWidth' then
Cr.Formulas.Item.Width := InchesStrToTwips(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editHeight' then
Cr.Formulas.Item.Height := InchesStrToTwips(TEdit(Sender).Text);
UpdateFormulas; {this will truncate any decimals beyond 3 places}
end;
end
else {twips}
begin
if not IsNumeric(TEdit(Sender).Text) then
TEdit(Sender).Text := PrevSize
else
begin
if TEdit(Sender).Name = 'editTop' then
Cr.Formulas.Item.Top := StrToInt(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editLeft' then
Cr.Formulas.Item.Left := StrToInt(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editWidth' then
Cr.Formulas.Item.Width := StrToInt(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editHeight' then
Cr.Formulas.Item.Height := StrToInt(TEdit(Sender).Text);
end;
end;
end;
{------------------------------------------------------------------------------}
{ cbSectionChange }
{------------------------------------------------------------------------------}
procedure TCrpeFormulasDlg.cbSectionChange(Sender: TObject);
begin
Cr.Formulas.Item.Section := cbSection.Items[cbSection.ItemIndex];
end;
{------------------------------------------------------------------------------}
{ btnBorderClick }
{------------------------------------------------------------------------------}
procedure TCrpeFormulasDlg.btnBorderClick(Sender: TObject);
begin
CrpeBorderDlg := TCrpeBorderDlg.Create(Application);
CrpeBorderDlg.Border := Cr.Formulas.Item.Border;
CrpeBorderDlg.ShowModal;
end;
{------------------------------------------------------------------------------}
{ btnFontClick }
{------------------------------------------------------------------------------}
procedure TCrpeFormulasDlg.btnFontClick(Sender: TObject);
begin
if Cr.Version.Crpe.Major > 7 then
begin
CrpeFontDlg := TCrpeFontDlg.Create(Application);
CrpeFontDlg.Crf := Cr.Formulas.Item.Font;
CrpeFontDlg.ShowModal;
end
else
begin
FontDialog1.Font.Assign(Cr.Formulas.Item.Font);
if FontDialog1.Execute then
Cr.Formulas.Item.Font.Assign(FontDialog1.Font);
end;
end;
{------------------------------------------------------------------------------}
{ btnFormatClick }
{------------------------------------------------------------------------------}
procedure TCrpeFormulasDlg.btnFormatClick(Sender: TObject);
begin
CrpeFormatDlg := TCrpeFormatDlg.Create(Application);
CrpeFormatDlg.Format := Cr.Formulas.Item.Format;
CrpeFormatDlg.ShowModal;
end;
{------------------------------------------------------------------------------}
{ btnHiliteConditionsClick }
{------------------------------------------------------------------------------}
procedure TCrpeFormulasDlg.btnHiliteConditionsClick(Sender: TObject);
begin
CrpeHiliteConditionsDlg := TCrpeHiliteConditionsDlg.Create(Application);
CrpeHiliteConditionsDlg.Crh := Cr.Formulas.Item.HiliteConditions;
CrpeHiliteConditionsDlg.ShowModal;
end;
{------------------------------------------------------------------------------}
{ btnClearClick }
{------------------------------------------------------------------------------}
procedure TCrpeFormulasDlg.btnClearClick(Sender: TObject);
begin
Cr.Formulas.Clear;
UpdateFormulas;
end;
{------------------------------------------------------------------------------}
{ btnOkClick }
{------------------------------------------------------------------------------}
procedure TCrpeFormulasDlg.btnOkClick(Sender: TObject);
begin
rgUnits.ItemIndex := 1; {change to twips to avoid the UpdateFormulas call}
if (not IsStrEmpty(Cr.ReportName)) and (FormulaIndex > -1) then
begin
editSizeExit(editTop);
editSizeExit(editLeft);
editSizeExit(editWidth);
editSizeExit(editHeight);
end;
SaveFormPos(Self);
Close;
end;
{------------------------------------------------------------------------------}
{ FormClose }
{------------------------------------------------------------------------------}
procedure TCrpeFormulasDlg.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
bFormulas := False;
Release;
end;
end.
|
// my stub as not in sdeanutils
unit SDUHTTPServer;
interface
const
HTTPCMD_GET = 'get';
HTTPSTATUS_OK = 200;
HTTPSTATUS_MULTI_STATUS = -1;
HTTPSTATUS_TEXT_MULTI_STATUS = '';
{
100: ResponseText := RSHTTPContinue;
// 2XX: Success
200: ResponseText := RSHTTPOK;
201: ResponseText := RSHTTPCreated;
202: ResponseText := RSHTTPAccepted;
203: ResponseText := RSHTTPNonAuthoritativeInformation;
204: ResponseText := RSHTTPNoContent;
205: ResponseText := RSHTTPResetContent;
206: ResponseText := RSHTTPPartialContent;
// 3XX: Redirections
301: ResponseText := RSHTTPMovedPermanently;
302: ResponseText := RSHTTPMovedTemporarily;
303: ResponseText := RSHTTPSeeOther;
304: ResponseText := RSHTTPNotModified;
305: ResponseText := RSHTTPUseProxy;
// 4XX Client Errors
400: ResponseText := RSHTTPBadRequest;
401: ResponseText := RSHTTPUnauthorized;
403: ResponseText := RSHTTPForbidden;
404: begin
ResponseText := RSHTTPNotFound;
// Close connection
CloseConnection := True;
end;
405: ResponseText := RSHTTPMethodNotAllowed;
406: ResponseText := RSHTTPNotAcceptable;
407: ResponseText := RSHTTPProxyAuthenticationRequired;
408: ResponseText := RSHTTPRequestTimeout;
409: ResponseText := RSHTTPConflict;
410: ResponseText := RSHTTPGone;
411: ResponseText := RSHTTPLengthRequired;
412: ResponseText := RSHTTPPreconditionFailed;
413: ResponseText := RSHTTPRequestEntityTooLong;
414: ResponseText := RSHTTPRequestURITooLong;
415: ResponseText := RSHTTPUnsupportedMediaType;
417: ResponseText := RSHTTPExpectationFailed;
// 5XX Server errors
500: ResponseText := RSHTTPInternalServerError;
501: ResponseText := RSHTTPNotImplemented;
502: ResponseText := RSHTTPBadGateway;
503: ResponseText := RSHTTPServiceUnavailable;
504: ResponseText := RSHTTPGatewayTimeout;
505: ResponseText := RSHTTPHTTPVersionNotSupported;
}
implementation
end.
|
namespace org.me.sqlitesample;
//Sample app by Brian Long (http://blong.com)
{
This example demonstrates SQLite's usage in an Android app
This activity uses helper classes (CustomerDatabaseAdapter and
CustomerDatabaseHelper), defined in another source file
}
interface
uses
java.util,
android.app,
android.os,
android.view,
android.widget,
android.util;
type
DBActivity = public class(ListActivity)
private
adapter: CustomerDatabaseAdapter;
protected
method onDestroy; override;
method onListItemClick(l: ListView; v: View; position: Integer; id: Int64); override;
public
method onCreate(savedInstanceState: Bundle); override;
end;
implementation
method DBActivity.onCreate(savedInstanceState: Bundle);
begin
inherited;
Log.i('DB', 'onCreate');
ContentView := R.layout.db;
//Create an instance of our database helper class
adapter := new CustomerDatabaseAdapter(Self);
//Open the database
adapter.Open;
//These are the field names we'll be displaying
var fieldsFrom: array of String := [CustomerDatabaseAdapter.ALIAS_FULLNAME, CustomerDatabaseAdapter.FLD_TOWN];
//This is where we'll display them
var viewsTo: array of Integer := [Android.R.id.text1, Android.R.id.text2];
var cursor := adapter.FetchAllCustomers;
//ensure the cursor gets some Android lifetime management applied to it
startManagingCursor(cursor);
//Hook everything up to this ListActivity's ListView
ListView.Adapter := new SimpleCursorAdapter(self, Android.R.layout.simple_list_item_2, cursor, fieldsFrom, viewsTo);
end;
method DBActivity.onDestroy;
begin
adapter.Close;
Log.i('DB', 'onDestroy');
inherited
end;
method DBActivity.onListItemClick(l: ListView; v: View; position: Integer; id: Int64);
begin
//When a list item is clicked on, get the customer linked to that DB row id
var cursor := adapter.FetchCustomer(id);
//Don't forget the Android lifetime management on this temporary cursor, just in case
startManagingCursor(cursor);
//Build up an info string
var msg := WideString.format('Customer %s, %s from %s row id %s',
cursor.String[cursor.ColumnIndexOrThrow[CustomerDatabaseAdapter.FLD_LAST]],
cursor.String[cursor.ColumnIndexOrThrow[CustomerDatabaseAdapter.FLD_FIRST]],
cursor.String[cursor.ColumnIndexOrThrow[CustomerDatabaseAdapter.FLD_TOWN]],
id);
//Briefly display the info string as a short toast message
Toast.makeText(self, msg, Toast.LENGTH_SHORT).show
end;
end. |
Unit Cpu;
{ * Cpu: *
* *
* Esta Unidad chequea el tipo de procesador , solo detecta las marcas AMD *
* e Intel , y tambien detect ala velocidad del micro , y llena la *
* estructura struc_cpu , con la informacion del coprocesador, *
* registros MMX , SSE y SSE2 *
* *
* Copyright (c) 2003-2006 Matias Vara <matiasevara@gmail.com> *
* All Rights Reserved *
* *
* Versiones : *
* 1 / 11 / 2003 : Primera Version . *
* *
***************************************************************************
}
INTERFACE
{$I ../include/head/asm.h}
{$I ../include/head/printk_.h}
{$I ../include/toro/cpu.inc}
var p_cpu : struc_cpu;
implementation
{ * Cpu_Id : *
* *
* Este proc. se encarga de identificar el procesador , solo indenti *
* fica procesadores Intel y Amd *
* *
***********************************************************************
}
procedure cpu_id;
var cpui:boolean;
mc,types,model,family,features:dword;
begin
asm
pushfd
pop eax
mov ecx , eax
or eax , 200000h
push eax
popfd
pushfd
pop eax
xor eax , ecx
je @no_es
mov cpui , 1
jmp @salir_test
@no_es:
mov cpui , 0
@salir_test:
end;
if (cpui) then
begin
asm
xor eax , eax
cpuid
mov mc , ebx
xor eax , eax
inc eax
cpuid
mov features, edx
push eax
and eax, 7000h
shr eax, 12
mov types, eax
pop eax
push eax
and eax, 0F00h
shr eax, 8
mov family, eax
pop eax
push eax
and eax, 0F0h
shr eax, 4
mov model, eax
end;
if mc=Intel_Id then p_cpu.marca := Intel;
if mc=Amd_Id then p_cpu.marca := Amd;
p_cpu.family := family;
p_cpu.Model := model;
p_cpu.types := types;
end;
end;
{ * Cpu_Init : *
* *
* Inicializa el modulo de CPu identificandolo *
* *
***********************************************************************
}
procedure cpu_init;[public,alias :'CPU_INIT'];
begin
Cpu_Id;
printk('/nProcesador ... ',[]);
if p_cpu.marca = amd then printk('/Vamd\n',[])
else printk('/Vintel\n',[]);
end;
end.
|
unit Win32.MFTransform;
// Updated to SDK 10.0.17763.0
// (c) Translation to Pascal by Norbert Sonnleitner
{$IFDEF FPC}
{$MODE delphi}
{$ENDIF}
interface
uses
Windows, Classes, SysUtils, Win32.MFObjects, CMC.WTypes;
const
MFPlat_DLL = 'MFPlat.dll';
const
IID_IMFTransform: TGUID = '{bf94c121-5b05-4e6f-8000-ba598961414d}';
IID_IMFDeviceTransform: TGUID = '{D818FBD8-FC46-42F2-87AC-1EA2D1F9BF32}';
IID_IMFDeviceTransformCallback: TGUID = '{6D5CB646-29EC-41FB-8179-8C4C6D750811}';
MFT_AUDIO_DECODER_DEGRADATION_INFO_ATTRIBUTE: TGUID = '{6c3386ad-ec20-430d-b2a5-505c7178d9c4}';
MEDeviceStreamCreated: TGUID = '{0252a1cf-3540-43b4-9164-d72eb405fa40}';
MF_SA_D3D_AWARE: TGUID = '{eaa35c29-775e-488e-9b61-b3283e49583b}';
MF_SA_REQUIRED_SAMPLE_COUNT: TGUID = '{18802c61-324b-4952-abd0-176ff5c696ff}';
MFT_END_STREAMING_AWARE: TGUID = '{70fbc845-b07e-4089-b064-399dc6110f29}';
MF_SA_REQUIRED_SAMPLE_COUNT_PROGRESSIVE: TGUID = '{b172d58e-fa77-4e48-8d2a-1df2d850eac2}';
MF_SA_AUDIO_ENDPOINT_AWARE: TGUID = '{c0381701-805c-42b2-ac8d-e2b4bf21f4f8}';
MFT_AUDIO_DECODER_AUDIO_ENDPOINT_ID: TGUID = '{c7ccdd6e-5398-4695-8be7-51b3e95111bd}';
MFT_AUDIO_DECODER_SPATIAL_METADATA_CLIENT: TGUID = '{05987df4-1270-4999-925f-8e939a7c0af7}';
MF_SA_MINIMUM_OUTPUT_SAMPLE_COUNT: TGUID = '{851745d5-c3d6-476d-9527-498ef2d10d18}';
MF_SA_MINIMUM_OUTPUT_SAMPLE_COUNT_PROGRESSIVE: TGUID = '{0f5523a5-1cb2-47c5-a550-2eeb84b4d14a}';
MFT_SUPPORT_3DVIDEO: TGUID = '{093f81b1-4f2e-4631-8168-7934032a01d3}';
MF_ENABLE_3DVIDEO_OUTPUT: TGUID = '{bdad7bca-0e5f-4b10-ab16-26de381b6293}';
MF_SA_D3D11_BINDFLAGS: TGUID = '{eacf97ad-065c-4408-bee3-fdcbfd128be2}';
MF_SA_D3D11_USAGE: TGUID = '{e85fe442-2ca3-486e-a9c7-109dda609880}';
MF_SA_D3D11_AWARE: TGUID = '{206b4fc8-fcf9-4c51-afe3-9764369e33a0}';
MF_SA_D3D11_SHARED: TGUID = '{7b8f32c3-6d96-4b89-9203-dd38b61414f3}';
MF_SA_D3D11_SHARED_WITHOUT_MUTEX: TGUID = '{39dbd44d-2e44-4931-a4c8-352d3dc42115}';
MF_SA_D3D11_ALLOW_DYNAMIC_YUV_TEXTURE: TGUID = '{ce06d49f-0613-4b9d-86a6-d8c4f9c10075}';
MF_SA_D3D11_HW_PROTECTED: TGUID = '{3a8ba9d9-92ca-4307-a391-6999dbf3b6ce}';
MF_SA_BUFFERS_PER_SAMPLE: TGUID = '{873c5171-1e3d-4e25-988d-b433ce041983}';
MFT_DECODER_EXPOSE_OUTPUT_TYPES_IN_NATIVE_ORDER: TGUID = '{ef80833f-f8fa-44d9-80d8-41ed6232670c}';
MFT_DECODER_QUALITY_MANAGEMENT_CUSTOM_CONTROL: TGUID = '{a24e30d7-de25-4558-bbfb-71070a2d332e}';
MFT_DECODER_QUALITY_MANAGEMENT_RECOVERY_WITHOUT_ARTIFACTS: TGUID = '{d8980deb-0a48-425f-8623-611db41d3810}';
MFT_REMUX_MARK_I_PICTURE_AS_CLEAN_POINT: TGUID = '{364e8f85-3f2e-436c-b2a2-4440a012a9e8}';
MFT_DECODER_FINAL_VIDEO_RESOLUTION_HINT: TGUID = '{dc2f8496-15c4-407a-b6f0-1b66ab5fbf53}';
MFT_ENCODER_SUPPORTS_CONFIG_EVENT: TGUID = '{86a355ae-3a77-4ec4-9f31-01149a4e92de}';
MFT_ENUM_HARDWARE_VENDOR_ID_Attribute: TGUID = '{3aecb0cc-035b-4bcc-8185-2b8d551ef3af}';
MF_TRANSFORM_ASYNC: TGUID = '{f81a699a-649a-497d-8c73-29f8fed6ad7a}';
MF_TRANSFORM_ASYNC_UNLOCK: TGUID = '{e5666d6b-3422-4eb6-a421-da7db1f8e207}';
MF_TRANSFORM_FLAGS_Attribute: TGUID = '{9359bb7e-6275-46c4-a025-1c01e45f1a86}';
MF_TRANSFORM_CATEGORY_Attribute: TGUID = '{ceabba49-506d-4757-a6ff-66c184987e4e}';
MFT_TRANSFORM_CLSID_Attribute: TGUID = '{6821c42b-65a4-4e82-99bc-9a88205ecd0c}';
MFT_INPUT_TYPES_Attributes: TGUID = '{4276c9b1-759d-4bf3-9cd0-0d723d138f96}';
MFT_OUTPUT_TYPES_Attributes: TGUID = '{8eae8cf3-a44f-4306-ba5c-bf5dda242818}';
MFT_ENUM_HARDWARE_URL_Attribute: TGUID = '{2fb866ac-b078-4942-ab6c-003d05cda674}';
MFT_FRIENDLY_NAME_Attribute: TGUID = '{314ffbae-5b41-4c95-9c19-4e7d586face3}';
MFT_CONNECTED_STREAM_ATTRIBUTE: TGUID = '{71eeb820-a59f-4de2-bcec-38db1dd611a4}';
MFT_CONNECTED_TO_HW_STREAM: TGUID = '{34e6e728-06d6-4491-a553-4795650db912}';
MFT_PREFERRED_OUTPUTTYPE_Attribute: TGUID = '{7e700499-396a-49ee-b1b4-f628021e8c9d}';
MFT_PROCESS_LOCAL_Attribute: TGUID = '{543186e4-4649-4e65-b588-4aa352aff379}';
MFT_PREFERRED_ENCODER_PROFILE: TGUID = '{53004909-1ef5-46d7-a18e-5a75f8b5905f}';
MFT_HW_TIMESTAMP_WITH_QPC_Attribute: TGUID = '{8d030fb8-cc43-4258-a22e-9210bef89be4}';
MFT_FIELDOFUSE_UNLOCK_Attribute: TGUID = '{8ec2e9fd-9148-410d-831e-702439461a8e}';
MFT_CODEC_MERIT_Attribute: TGUID = '{88a7cb15-7b07-4a34-9128-e64c6703c4d3}';
MFT_ENUM_TRANSCODE_ONLY_ATTRIBUTE: TGUID = '{111ea8cd-b62a-4bdb-89f6-67ffcdc2458b}';
MF_DMFT_FRAME_BUFFER_INFO: TGUID = '{396CE1C9-67A9-454C-8797-95A45799D804}';
MFPKEY_CLSID: TPROPERTYKEY = (fmtid: '{c57a84c0-1a80-40a3-97b5-9272a403c8ae}'; pid: $01);
MFPKEY_CATEGORY: TPROPERTYKEY = (fmtid: '{c57a84c0-1a80-40a3-97b5-9272a403c8ae}'; pid: $02);
MFPKEY_EXATTRIBUTE_SUPPORTED: TPROPERTYKEY = (fmtid: '{456fe843-3c87-40c0-949d-1409c97dab2c}'; pid: $01);
MFPKEY_MULTICHANNEL_CHANNEL_MASK: TPROPERTYKEY = (fmtid: '{58bdaf8c-3224-4692-86d0-44d65c5bf82b}'; pid: $01);
const
MFT_STREAMS_UNLIMITED = $FFFFFFFF;
MFT_OUTPUT_BOUND_LOWER_UNBOUNDED = $8000000000000000;
MFT_OUTPUT_BOUND_UPPER_UNBOUNDED = $7fffffffffffffff;
type
TMFT_INPUT_DATA_BUFFER_FLAGS = (MFT_INPUT_DATA_BUFFER_PLACEHOLDER = $FFFFFFFF);
TMFT_OUTPUT_DATA_BUFFER_FLAGS = (MFT_OUTPUT_DATA_BUFFER_INCOMPLETE = $1000000, MFT_OUTPUT_DATA_BUFFER_FORMAT_CHANGE = $100,
MFT_OUTPUT_DATA_BUFFER_STREAM_END = $200, MFT_OUTPUT_DATA_BUFFER_NO_SAMPLE = $300);
TMFT_INPUT_STATUS_FLAGS = (MFT_INPUT_STATUS_ACCEPT_DATA = $1);
TMFT_OUTPUT_STATUS_FLAGS = (MFT_OUTPUT_STATUS_SAMPLE_READY = $1);
TMFT_INPUT_STREAM_INFO_FLAGS = (MFT_INPUT_STREAM_WHOLE_SAMPLES = $1, MFT_INPUT_STREAM_SINGLE_SAMPLE_PER_BUFFER = $2,
MFT_INPUT_STREAM_FIXED_SAMPLE_SIZE = $4, MFT_INPUT_STREAM_HOLDS_BUFFERS = $8, MFT_INPUT_STREAM_DOES_NOT_ADDREF = $100,
MFT_INPUT_STREAM_REMOVABLE = $200, MFT_INPUT_STREAM_OPTIONAL = $400, MFT_INPUT_STREAM_PROCESSES_IN_PLACE = $800);
TMFT_OUTPUT_STREAM_INFO_FLAGS = (MFT_OUTPUT_STREAM_WHOLE_SAMPLES = $1, MFT_OUTPUT_STREAM_SINGLE_SAMPLE_PER_BUFFER = $2,
MFT_OUTPUT_STREAM_FIXED_SAMPLE_SIZE = $4, MFT_OUTPUT_STREAM_DISCARDABLE = $8, MFT_OUTPUT_STREAM_OPTIONAL = $10,
MFT_OUTPUT_STREAM_PROVIDES_SAMPLES = $100, MFT_OUTPUT_STREAM_CAN_PROVIDE_SAMPLES = $200, MFT_OUTPUT_STREAM_LAZY_READ = $400,
MFT_OUTPUT_STREAM_REMOVABLE = $800);
TMFT_SET_TYPE_FLAGS = (MFT_SET_TYPE_TEST_ONLY = $1);
TMFT_PROCESS_OUTPUT_FLAGS = (MFT_PROCESS_OUTPUT_DISCARD_WHEN_NO_BUFFER = $1, MFT_PROCESS_OUTPUT_REGENERATE_LAST_OUTPUT = $2);
TMFT_PROCESS_OUTPUT_STATUS = (MFT_PROCESS_OUTPUT_STATUS_NEW_STREAMS = $100);
TMFT_DRAIN_TYPE = (MFT_DRAIN_PRODUCE_TAILS = 0, MFT_DRAIN_NO_TAILS = $1);
TMFT_MESSAGE_TYPE = (MFT_MESSAGE_COMMAND_FLUSH = 0, MFT_MESSAGE_COMMAND_DRAIN = $1, MFT_MESSAGE_SET_D3D_MANAGER =
$2, MFT_MESSAGE_DROP_SAMPLES = $3,
MFT_MESSAGE_COMMAND_TICK = $4, MFT_MESSAGE_NOTIFY_BEGIN_STREAMING = $10000000, MFT_MESSAGE_NOTIFY_END_STREAMING = $10000001,
MFT_MESSAGE_NOTIFY_END_OF_STREAM = $10000002, MFT_MESSAGE_NOTIFY_START_OF_STREAM = $10000003,
MFT_MESSAGE_NOTIFY_RELEASE_RESOURCES = $10000004,
MFT_MESSAGE_NOTIFY_REACQUIRE_RESOURCES = $10000005, MFT_MESSAGE_NOTIFY_EVENT = $10000006,
MFT_MESSAGE_COMMAND_SET_OUTPUT_STREAM_STATE = $10000007,
MFT_MESSAGE_COMMAND_FLUSH_OUTPUT_STREAM = $10000008,
MFT_MESSAGE_COMMAND_MARKER = $20000000);
TMFT_INPUT_STREAM_INFO = record
hnsMaxLatency: LONGLONG;
dwFlags: DWORD;
cbSize: DWORD;
cbMaxLookahead: DWORD;
cbAlignment: DWORD;
end;
TMFT_OUTPUT_STREAM_INFO = record
dwFlags: DWORD;
cbSize: DWORD;
cbAlignment: DWORD;
end;
TMFT_OUTPUT_DATA_BUFFER = record
dwStreamID: DWORD;
pSample: IMFSample;
dwStatus: DWORD;
pEvents: IMFCollection;
end;
PMFT_OUTPUT_DATA_BUFFER = ^TMFT_OUTPUT_DATA_BUFFER;
IMFTransform = interface(IUnknown)
['{bf94c121-5b05-4e6f-8000-ba598961414d}']
function GetStreamLimits(out pdwInputMinimum: DWORD; out pdwInputMaximum: DWORD; out pdwOutputMinimum: DWORD;
out pdwOutputMaximum: DWORD): HResult;
stdcall;
function GetStreamCount(out pcInputStreams: DWORD; out pcOutputStreams: DWORD): HResult; stdcall;
function GetStreamIDs(dwInputIDArraySize: DWORD; out pdwInputIDs: PDWORD; dwOutputIDArraySize: DWORD;
out pdwOutputIDs: PDWORD): HResult; stdcall;
function GetInputStreamInfo(dwInputStreamID: DWORD; out pStreamInfo: TMFT_INPUT_STREAM_INFO): HResult; stdcall;
function GetOutputStreamInfo(dwOutputStreamID: DWORD; out pStreamInfo: TMFT_OUTPUT_STREAM_INFO): HResult; stdcall;
function GetAttributes(out pAttributes: IMFAttributes): HResult; stdcall;
function GetInputStreamAttributes(dwInputStreamID: DWORD; out pAttributes: IMFAttributes): HResult; stdcall;
function GetOutputStreamAttributes(dwOutputStreamID: DWORD; out pAttributes: IMFAttributes): HResult; stdcall;
function DeleteInputStream(dwStreamID: DWORD): HResult; stdcall;
function AddInputStreams(cStreams: DWORD; adwStreamIDs: PDWORD): HResult; stdcall;
function GetInputAvailableType(dwInputStreamID: DWORD; dwTypeIndex: DWORD; out ppType: IMFMediaType): HResult; stdcall;
function GetOutputAvailableType(dwOutputStreamID: DWORD; dwTypeIndex: DWORD; out ppType: IMFMediaType): HResult; stdcall;
function SetInputType(dwInputStreamID: DWORD; pType: IMFMediaType; dwFlags: DWORD): HResult; stdcall;
function SetOutputType(dwOutputStreamID: DWORD; pType: IMFMediaType; dwFlags: DWORD): HResult; stdcall;
function GetInputCurrentType(dwInputStreamID: DWORD; out ppType: IMFMediaType): HResult; stdcall;
function GetOutputCurrentType(dwOutputStreamID: DWORD; out ppType: IMFMediaType): HResult; stdcall;
function GetInputStatus(dwInputStreamID: DWORD; out pdwFlags: DWORD): HResult; stdcall;
function GetOutputStatus(out pdwFlags: DWORD): HResult; stdcall;
function SetOutputBounds(hnsLowerBound: LONGLONG; hnsUpperBound: LONGLONG): HResult; stdcall;
function ProcessEvent(dwInputStreamID: DWORD; pEvent: IMFMediaEvent): HResult; stdcall;
function ProcessMessage(eMessage: TMFT_MESSAGE_TYPE; ulParam: ULONG_PTR): HResult; stdcall;
function ProcessInput(dwInputStreamID: DWORD; pSample: IMFSample; dwFlags: DWORD): HResult; stdcall;
function ProcessOutput(dwFlags: DWORD; cOutputBufferCount: DWORD; var pOutputSamples: PMFT_OUTPUT_DATA_BUFFER;
out pdwStatus: DWORD): HResult; stdcall;
end;
TDeviceStreamState = (
DeviceStreamState_Stop = 0,
DeviceStreamState_Pause = (DeviceStreamState_Stop + 1),
DeviceStreamState_Run = (DeviceStreamState_Pause + 1),
DeviceStreamState_Disabled = (DeviceStreamState_Run + 1)
);
PDeviceStreamState = ^TDeviceStreamState;
TSTREAM_MEDIUM = record
gidMedium: TGUID;
unMediumInstance: UINT32;
end;
PSTREAM_MEDIUM = ^TSTREAM_MEDIUM;
IMFDeviceTransform = interface(IUnknown)
['{D818FBD8-FC46-42F2-87AC-1EA2D1F9BF32}']
function InitializeTransform(pAttributes: IMFAttributes): HResult; stdcall;
function GetInputAvailableType(dwInputStreamID: DWORD; dwTypeIndex: DWORD; out pMediaType: IMFMediaType): HResult; stdcall;
function GetInputCurrentType(dwInputStreamID: DWORD; out pMediaType: IMFMediaType): HResult; stdcall;
function GetInputStreamAttributes(dwInputStreamID: DWORD; out ppAttributes: IMFAttributes): HResult; stdcall;
function GetOutputAvailableType(dwOutputStreamID: DWORD; dwTypeIndex: DWORD; out pMediaType: IMFMediaType): HResult; stdcall;
function GetOutputCurrentType(dwOutputStreamID: DWORD; out pMediaType: IMFMediaType): HResult; stdcall;
function GetOutputStreamAttributes(dwOutputStreamID: DWORD; out ppAttributes: IMFAttributes): HResult; stdcall;
function GetStreamCount(out pcInputStreams: DWORD; out pcOutputStreams: DWORD): HResult; stdcall;
function GetStreamIDs(dwInputIDArraySize: DWORD; out pdwInputStreamIds: DWORD; dwOutputIDArraySize: DWORD;
out pdwOutputStreamIds: DWORD): HResult; stdcall;
function ProcessEvent(dwInputStreamID: DWORD; pEvent: IMFMediaEvent): HResult; stdcall;
function ProcessInput(dwInputStreamID: DWORD; pSample: IMFSample; dwFlags: DWORD): HResult; stdcall;
function ProcessMessage(eMessage: TMFT_MESSAGE_TYPE; ulParam: ULONG_PTR): HResult; stdcall;
function ProcessOutput(dwFlags: DWORD; cOutputBufferCount: DWORD; var pOutputSample: PMFT_OUTPUT_DATA_BUFFER;
out pdwStatus: DWORD): HResult; stdcall;
function SetInputStreamState(dwStreamID: DWORD; pMediaType: IMFMediaType; Value: TDeviceStreamState;
dwFlags: DWORD): HResult; stdcall;
function GetInputStreamState(dwStreamID: DWORD; out Value: TDeviceStreamState): HResult; stdcall;
function SetOutputStreamState(dwStreamID: DWORD; pMediaType: IMFMediaType; Value: TDeviceStreamState;
dwFlags: DWORD): HResult; stdcall;
function GetOutputStreamState(dwStreamID: DWORD; out Value: TDeviceStreamState): HResult; stdcall;
function GetInputStreamPreferredState(dwStreamID: DWORD; out Value: TDeviceStreamState;
out ppMediaType: IMFMediaType): HResult; stdcall;
function FlushInputStream(dwStreamIndex: DWORD; dwFlags: DWORD): HResult; stdcall;
function FlushOutputStream(dwStreamIndex: DWORD; dwFlags: DWORD): HResult; stdcall;
end;
IMFDeviceTransformCallback = interface(IUnknown)
['{6D5CB646-29EC-41FB-8179-8C4C6D750811}']
function OnBufferSent(pCallbackAttributes: IMFAttributes; pinId: DWORD): HResult; stdcall;
end;
TMF3DVideoOutputType = (MF3DVideoOutputType_BaseView = 0, MF3DVideoOutputType_Stereo = 1);
TMFT_AUDIO_DECODER_DEGRADATION_REASON = (
MFT_AUDIO_DECODER_DEGRADATION_REASON_NONE = 0,
MFT_AUDIO_DECODER_DEGRADATION_REASON_LICENSING_REQUIREMENT = 1
);
TMFT_AUDIO_DECODER_DEGRADATION_TYPE = (
MFT_AUDIO_DECODER_DEGRADATION_TYPE_NONE = 0,
MFT_AUDIO_DECODER_DEGRADATION_TYPE_DOWNMIX2CHANNEL = 1,
MFT_AUDIO_DECODER_DEGRADATION_TYPE_DOWNMIX6CHANNEL = 2,
MFT_AUDIO_DECODER_DEGRADATION_TYPE_DOWNMIX8CHANNEL = 3
);
TMFAudioDecoderDegradationInfo = record
eDegradationReason: TMFT_AUDIO_DECODER_DEGRADATION_REASON;
eType: TMFT_AUDIO_DECODER_DEGRADATION_TYPE;
end;
TMFT_STREAM_STATE_PARAM = record
StreamId: DWORD;
State: TMF_STREAM_STATE;
end;
PMFT_STREAM_STATE_PARAM = ^TMFT_STREAM_STATE_PARAM;
function MFCreateTransformActivate(out ppActivate: IMFActivate): HResult; stdcall; external MFPlat_DLL;
implementation
end.
|
{================================================================================
Copyright (C) 1997-2002 Mills Enterprise
Unit : rmDataStorage
Purpose : To allow the storage of text or binary data within the application
Date : 03-04-2000
Author : Ryan J. Mills
Version : 1.92
Notes : The original idea for these components came from Daniel Parnell's
TStringz component. I created these after I came across some
limitations in that component. These components are more functional
and provide more design time properties.
================================================================================}
unit rmDataStorage;
interface
{$I CompilerDefines.INC}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
rmLibrary;
type
TrmDataStorageFileName = string;
TrmDataStorageLongint = Longint;
TrmCustomDataStorage = class(TComponent)
private
{ Private declarations }
procedure SetDataSize(const Value: TrmDataStorageLongint);
protected
{ Protected declarations }
procedure DefineProperties(Filer: TFiler); override;
procedure ReadBinaryData(Stream: TStream); virtual;
procedure WriteBinaryData(Stream: TStream); virtual;
function GetDataSize: TrmDataStorageLongint; virtual;
public
{ Public declarations }
constructor create(AOwner:TComponent); override;
procedure WriteToFile(filename:string); virtual;
procedure LoadFromFile(FileName:string); virtual;
procedure WriteToStream(Dest:TStream); virtual;
procedure ClearData; virtual;
published
{ Published declarations }
property DataSize : TrmDataStorageLongint read GetDataSize write SetDataSize stored false;
end;
TrmTextDataStorage = class(TrmCustomDataStorage)
private
{ Private declarations }
fData : TStringList;
procedure SetData(const Value: TStringList);
protected
{ Protected declarations }
procedure ReadBinaryData(Stream: TStream); override;
procedure WriteBinaryData(Stream: TStream); override;
function GetDataSize: TrmDataStorageLongint; override;
public
{ Public declarations }
constructor create(AOwner:TComponent); override;
destructor destroy; override;
procedure WriteToFile(filename:string); override;
procedure LoadFromFile(FileName:string); override;
procedure WriteToStream(Dest:TStream); override;
procedure ClearData; override;
published
{ Published declarations }
property Data : TStringList read fData write SetData stored False;
end;
TrmBinaryDataStorage = class(TrmCustomDataStorage)
private
{ Private declarations }
fData : TMemoryStream;
function GetData: TMemoryStream;
protected
{ Protected declarations }
procedure ReadBinaryData(Stream: TStream); override;
procedure WriteBinaryData(Stream: TStream); override;
function GetDataSize: TrmDataStorageLongint; override;
public
{ Public declarations }
constructor create(AOwner:TComponent); override;
destructor destroy; override;
procedure WriteToFile(filename:string); override;
procedure LoadFromFile(FileName:string); override;
procedure WriteToStream(Dest:TStream); override;
procedure ClearData; override;
property Data : TMemoryStream read GetData;
published
{ Published declarations }
end;
implementation
{ TrmCustomDataStorage }
procedure TrmCustomDataStorage.ClearData;
begin
if not (csdesigning in componentstate) then
Raise Exception.create('Not in design mode');
end;
constructor TrmCustomDataStorage.create(AOwner: TComponent);
begin
inherited;
end;
procedure TrmCustomDataStorage.DefineProperties(Filer: TFiler);
begin
inherited;
Filer.DefineBinaryProperty('StoredData',ReadBinaryData, WriteBinaryData, True);
end;
function TrmCustomDataStorage.GetDataSize: TrmDataStorageLongint;
begin
Result := 0;
end;
procedure TrmCustomDataStorage.LoadFromFile(FileName: string);
begin
if not (csdesigning in componentstate) then
Raise Exception.create('Not in design mode.');
if not FileExists(filename) then
Raise Exception.create('File does not exist.');
end;
procedure TrmCustomDataStorage.ReadBinaryData(Stream: TStream);
begin
//Do Nothing....
end;
procedure TrmCustomDataStorage.SetDataSize(
const Value: TrmDataStorageLongint);
begin
//Do Nothing....
end;
procedure TrmCustomDataStorage.WriteBinaryData(Stream: TStream);
begin
//Do Nothing....
end;
procedure TrmCustomDataStorage.WriteToFile(filename: string);
begin
//Do Nothing....
end;
procedure TrmCustomDataStorage.WriteToStream(Dest: TStream);
begin
//Do Nothing...
end;
{ TrmTextDataStorage }
procedure TrmTextDataStorage.ClearData;
begin
inherited;
fData.Clear;
end;
constructor TrmTextDataStorage.create(AOwner: TComponent);
begin
inherited;
fData := TStringlist.create;
end;
destructor TrmTextDataStorage.destroy;
begin
inherited;
fData.free;
end;
function TrmTextDataStorage.GetDataSize: TrmDataStorageLongint;
begin
Result := length(fData.Text);
end;
procedure TrmTextDataStorage.LoadFromFile(FileName: string);
begin
inherited;
fData.LoadFromFile(filename);
end;
procedure TrmTextDataStorage.ReadBinaryData(Stream: TStream);
var
n : longint;
wData : TMemoryStream;
begin
fData.Clear;
Stream.ReadBuffer(n,SizeOf(n));
if n > 0 then
begin
wData := tmemoryStream.create;
try
if not assigned(wData) then
raise Exception.Create('Out of memory');
wData.CopyFrom(Stream, n);
wData.Position := 0;
fData.LoadFromStream(wData);
finally
wData.free;
end;
end;
end;
procedure TrmTextDataStorage.SetData(const Value: TStringList);
begin
if csDesigning in componentState then
FData.assign(Value)
else
Raise Exception.create('Not in design mode.');
end;
procedure TrmTextDataStorage.WriteBinaryData(Stream: TStream);
var
wData : TMemoryStream;
n : longint;
begin
wData := tmemoryStream.create;
try
fData.SaveToStream(wData);
n := wData.Size;
Stream.WriteBuffer(n, sizeof(n));
if n > 0 then
Stream.CopyFrom(wData, 0);
finally
wData.free;
end;
end;
procedure TrmTextDataStorage.WriteToFile(filename: string);
begin
inherited;
fData.SaveToFile(filename);
end;
procedure TrmTextDataStorage.WriteToStream(Dest: TStream);
begin
fdata.SaveToStream(dest);
end;
{ TrmBinaryDataStorage }
procedure TrmBinaryDataStorage.ClearData;
begin
inherited;
fData.Clear;
end;
constructor TrmBinaryDataStorage.create(AOwner: TComponent);
begin
inherited;
fData := TMemoryStream.Create;
end;
destructor TrmBinaryDataStorage.destroy;
begin
inherited;
fData.free;
end;
function TrmBinaryDataStorage.GetData: TMemoryStream;
begin
fData.Position := 0;
Result := fData;
end;
function TrmBinaryDataStorage.GetDataSize: TrmDataStorageLongint;
begin
result := fData.Size;
end;
procedure TrmBinaryDataStorage.LoadFromFile(FileName: string);
begin
inherited;
fData.LoadFromFile(filename);
end;
procedure TrmBinaryDataStorage.ReadBinaryData(Stream: TStream);
var
n : longint;
begin
fData.Clear;
Stream.ReadBuffer(n,SizeOf(n));
if n > 0 then
fData.CopyFrom(Stream, n);
end;
procedure TrmBinaryDataStorage.WriteBinaryData(Stream: TStream);
var
n : longint;
begin
n := fData.Size;
Stream.WriteBuffer(n, sizeof(n));
if n > 0 then
Stream.CopyFrom(fData, 0);
end;
procedure TrmBinaryDataStorage.WriteToFile(filename: string);
begin
fData.SaveToFile(filename);
end;
procedure TrmBinaryDataStorage.WriteToStream(Dest: TStream);
begin
fData.Position := 0;
TrmStream(fData).copyto(Dest,0);
end;
end.
|
unit MainOJ;
// Demonstration project for TojVirtualStringTree to generally show how to get started.
// Written by Mike Lischke.
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ojVirtualTrees, StdCtrls, ExtCtrls, strUtils, System.Types;
type
TMainForm = class(TForm)
VST: TojVirtualStringTree;
ClearButton: TButton;
AddOneButton: TButton;
Edit1: TEdit;
Button1: TButton;
Label1: TLabel;
CloseButton: TButton;
Button2: TButton;
btnSaveToStream: TButton;
btnLoadFromStream: TButton;
procedure FormCreate(Sender: TObject);
procedure ClearButtonClick(Sender: TObject);
procedure AddButtonClick(Sender: TObject);
procedure CloseButtonClick(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure VSTInitNode(Sender: TojBaseVirtualTree; ParentNode, Node: TojVirtualNode; var InitialStates: TVirtualNodeInitStates);
procedure VSTFreeNode(Sender: TojBaseVirtualTree; Node: TojVirtualNode);
procedure VSTGetText(Sender: TojBaseVirtualTree; Node: TojVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string);
procedure VST_OnGetNodeUserDataClass(Sender: TojBaseVirtualTree; var NodeUserDataClass: TClass);
procedure btnSaveToStreamClick(Sender: TObject);
procedure btnLoadFromStreamClick(Sender: TObject);
procedure VSTGetCellText(Sender: TojCustomVirtualStringTree; var E: TVSTGetCellTextEventArgs);
end;
var
MainForm: TMainForm;
//----------------------------------------------------------------------------------------------------------------------
implementation
{$R *.DFM}
type
TojStringData = class
Caption: string;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TMainForm.FormCreate(Sender: TObject);
begin
// We assign the OnGetText handler manually to keep the demo source code compatible
// with older Delphi versions after using UnicodeString instead of WideString.
VST.OnGetText := VSTGetText;
// Let the tree know how much data space we need.
// VST.NodeDataSize := SizeOf(TMyRec);
// Set an initial number of nodes.
VST.RootNodeCount := 120;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TMainForm.btnLoadFromStreamClick(Sender: TObject);
var v_fpath, v_app_path: string;
v_stream: TMemoryStream;
begin
v_app_path:= ChangeFileExt(Application.ExeName, '');
v_fpath:= v_app_path + '_tree' + '.vtv';
if FileExists(v_fpath) then
begin
v_stream:= TMemoryStream.Create;
try
v_stream.LoadFromFile(v_fpath);
v_stream.Position:= 0;
VST.LoadFromStream(v_stream);
finally
FreeAndNil(v_stream);
end;
end
else
ShowMessage('No such file as ' +v_fpath);
v_fpath:= v_app_path + '_header' + '.vtv';
if FileExists(v_fpath) then
begin
v_stream:= TMemoryStream.Create;
try
v_stream.LoadFromFile(v_fpath);
v_stream.Position:= 0;
VST.Header.LoadFromStream(v_stream);
finally
FreeAndNil(v_stream);
end;
end
else
ShowMessage('No such file as ' +v_fpath);
end;
procedure TMainForm.btnSaveToStreamClick(Sender: TObject);
var v_fpath, v_app_path: string;
v_stream: TMemoryStream;
begin
v_app_path:= ChangeFileExt(Application.ExeName, '');
v_fpath:= v_app_path + '_tree' + '.vtv';
v_stream:= TMemoryStream.Create;
try
VST.SaveToStream(v_stream, nil);
v_stream.SaveToFile(v_fpath);
finally
FreeAndNil(v_stream);
end;
v_fpath:= v_app_path + '_header' + '.vtv';
v_stream:= TMemoryStream.Create;
try
VST.Header.SaveToStream(v_stream);
v_stream.SaveToFile(v_fpath);
finally
FreeAndNil(v_stream);
end;
end;
procedure TMainForm.Button2Click(Sender: TObject);
begin
// VST.NodeDataSize:= 100;
VST._UserDataClassName:= '';
end;
procedure TMainForm.ClearButtonClick(Sender: TObject);
var
Start: Cardinal;
begin
Screen.Cursor := crHourGlass;
try
Start := GetTickCount;
VST.Clear;
Label1.Caption := Format('Last operation duration: %d ms, TNC: %d', [GetTickCount - Start, TojVirtualNode.TotalNodeCount]);
finally
Screen.Cursor := crDefault;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TMainForm.AddButtonClick(Sender: TObject);
var
Count: Cardinal;
Start: Cardinal;
begin
// Add some nodes to the treeview.
Screen.Cursor := crHourGlass;
with VST do
try
Start := GetTickCount;
case (Sender as TButton).Tag of
0: // add to root
begin
Count := StrToInt(Edit1.Text);
RootNodeCount := RootNodeCount + Count;
end;
1: // add as child
if Assigned(FocusedNode) then
begin
Count := StrToInt(Edit1.Text);
ChildCount[FocusedNode] := ChildCount[FocusedNode] + Count;
Expanded[FocusedNode] := True;
InvalidateToBottom(FocusedNode);
end;
end;
Label1.Caption := Format('Last operation duration: %d ms, TNC: %d', [GetTickCount - Start, TojVirtualNode.TotalNodeCount]);
finally
Screen.Cursor := crDefault;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TMainForm.VSTFreeNode(Sender: TojBaseVirtualTree; Node: TojVirtualNode);
//var
// Data: PMyRec;
begin
// UserData is owned by tree; do nothing
// Data := Sender.GetNodeData(Node);
// // Explicitely free the string, the VCL cannot know that there is one but needs to free
// // it nonetheless. For more fields in such a record which must be freed use Finalize(Data^) instead touching
// // every member individually.
// Finalize(Data^);
end;
procedure TMainForm.VSTGetCellText(Sender: TojCustomVirtualStringTree; var E: TVSTGetCellTextEventArgs);
begin
with sender do
case GetNodeLevel(E.Node) of
0: E.CellText:= E.FieldName + ' ' +TojVirtualStringNode(E.Node).Caption;
1: E.CellText:= E.Node.Tag ;
else
E.CellText:= sender.GetNodeData<TojStringData>(E.Node).Caption;
// E.CellText:= TojVirtualStringNode(E.Node).Caption;
end;
end;
procedure TMainForm.VSTGetText(Sender: TojBaseVirtualTree; Node: TojVirtualNode;
Column: TColumnIndex; TextType: TVSTTextType; var CellText: string);
begin
// CellText:= TojVirtualStringNode(Node).Caption;
with sender do
case GetNodeLevel(Node) of
0: CellText:= TojVirtualStringNode(Node).Caption;
1: CellText:= Node.Tag;
else
CellText:= TojVirtualStringNode(Node).Caption;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TMainForm.VSTInitNode(Sender: TojBaseVirtualTree; ParentNode,
Node: TojVirtualNode; var InitialStates: TVirtualNodeInitStates);
begin
with sender do
case GetNodeLevel(Node) of
0: TojVirtualStringNode(Node).Caption := Format('CPT Level %d, Index %d', [GetNodeLevel(Node), Node.Index]);
1: Node.Tag:= Format('TAG Level %d, Index %d', [GetNodeLevel(Node), Node.Index]);
else
TojVirtualStringNode(Node).Caption:= Format('CPTE Level %d, Index %d', [GetNodeLevel(Node), Node.Index]);
end;
end;
procedure TMainForm.VST_OnGetNodeUserDataClass(Sender: TojBaseVirtualTree;
var NodeUserDataClass: TClass);
begin
if NodeUserDataClass = nil
then NodeUserDataClass:= TojStringData;
end;
procedure TMainForm.CloseButtonClick(Sender: TObject);
begin
Close;
end;
initialization
// GTA
TojVirtualStringTree.registerUserDataClass(TojStringData);
finalization
end.
|
unit Demo.PieChart.Sample;
interface
uses
System.Classes, Demo.BaseFrame, cfs.GCharts;
type
TDemo_PieChart_Sample = class(TDemoBaseFrame)
public
procedure GenerateChart; override;
end;
implementation
procedure TDemo_PieChart_Sample.GenerateChart;
var
Chart: IcfsGChartProducer; //Defined as TInterfacedObject. No need try..finally
begin
Chart := TcfsGChartProducer.Create;
Chart.ClassChartType := TcfsGChartProducer.CLASS_PIE_CHART;
// Data
Chart.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Topping'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Slices')
]);
Chart.Data.AddRow(['Mushrooms', 3]);
Chart.Data.AddRow(['Onions', 1]);
Chart.Data.AddRow(['Olives', 1]);
Chart.Data.AddRow(['Zucchini', 1]);
Chart.Data.AddRow(['Pepperoni', 2]);
// Options
Chart.Options.Title('How Much Pizza I Ate Last Night');
// Generate
GChartsFrame.DocumentInit;
GChartsFrame.DocumentSetBody('<div id="Chart" style="width:100%;height:100%;"></div>');
GChartsFrame.DocumentGenerate('Chart', Chart);
GChartsFrame.DocumentPost;
end;
initialization
RegisterClass(TDemo_PieChart_Sample);
end.
|
unit UnitPasswordForm;
interface
uses
System.UITypes,
System.Types,
System.SysUtils,
System.Classes,
Winapi.Windows,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
Vcl.Menus,
Vcl.Clipbrd,
Vcl.PlatformDefaultStyleActnCtrls,
Vcl.ActnPopup,
Data.DB,
Dmitry.CRC32,
Dmitry.Utils.System,
Dmitry.Utils.Files,
Dmitry.Controls.WatermarkedEdit,
FormManegerUnit,
GraphicCrypt,
uConstants,
uDBForm,
uTranslate,
uShellIntegration,
uSettings,
uMemory,
uDatabaseDirectoriesUpdater,
uFormInterfaces,
uSessionPasswords;
type
PasswordType = Integer;
const
PASS_TYPE_IMAGE_FILE = 0;
PASS_TYPE_IMAGE_BLOB = 1;
PASS_TYPE_IMAGE_STENO = 2;
PASS_TYPE_IMAGES_CRC = 3;
type
TPassWordForm = class(TDBForm, IRequestPasswordForm)
LbTitle: TLabel;
BtCancel: TButton;
BtOk: TButton;
CbSavePassToSession: TCheckBox;
CbSavePassPermanent: TCheckBox;
CbDoNotAskAgain: TCheckBox;
BtCancelForFiles: TButton;
InfoListBox: TListBox;
BtHideDetails: TButton;
PmCopyFileList: TPopupActionBar;
CopyText1: TMenuItem;
LbInfo: TLabel;
PmCloseAction: TPopupActionBar;
CloseDialog1: TMenuItem;
Skipthisfiles1: TMenuItem;
EdPassword: TWatermarkedEdit;
procedure FormCreate(Sender: TObject);
procedure LoadLanguage;
procedure BtOkClick(Sender: TObject);
procedure EdPasswordKeyPress(Sender: TObject; var Key: Char);
procedure BtCancelClick(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure CopyText1Click(Sender: TObject);
procedure BtCancelForFilesClick(Sender: TObject);
procedure CloseDialog1Click(Sender: TObject);
procedure Skipthisfiles1Click(Sender: TObject);
procedure BtHideDetailsClick(Sender: TObject);
procedure InfoListBoxMeasureItem(Control: TWinControl; Index: Integer;
var Height: Integer);
procedure InfoListBoxDrawItem(Control: TWinControl; Index: Integer;
aRect: TRect; State: TOwnerDrawState);
procedure FormDestroy(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
FFileName: string;
FPassword: string;
DB: TField;
UseAsk: Boolean;
FCRC: Cardinal;
FOpenedList: Boolean;
DialogType: PasswordType;
FSkip: Boolean;
PassIcon: TIcon;
protected
function GetFormID : string; override;
procedure LoadFileList(FileList: TStrings);
procedure ReallignControlsEx;
property Password: string read FPassword write FPassword;
procedure CustomFormAfterDisplay; override;
procedure InterfaceDestroyed; override;
public
{ Public declarations }
function ForImage(FileName: string): string;
function ForImageEx(FileName: string; out AskAgain: Boolean): string;
function ForBlob(DF: TField; FileName: string): string;
function ForSteganoraphyFile(FileName: string; CRC: Cardinal) : string;
function ForManyFiles(FileList: TStrings; CRC: Cardinal; var Skip: Boolean): string;
end;
implementation
{$R *.dfm}
function TPassWordForm.ForImage(FileName: string): string;
begin
FFileName := FileName;
DB := nil;
LbTitle.Caption := Format(TA('Enter password to file "%s" here:', 'Password'), [Mince(FileName, 30)]);
UseAsk := False;
DialogType := PASS_TYPE_IMAGE_FILE;
ReallignControlsEx;
ShowModal;
Result := Password;
end;
function TPassWordForm.ForImageEx(FileName: string;
out AskAgain: Boolean): string;
begin
FFileName := FileName;
DB := nil;
UseAsk := True;
DialogType := PASS_TYPE_IMAGE_FILE;
ReallignControlsEx;
LbTitle.Caption := Format(TA('Enter password to file "%s" here:', 'Password'), [Mince(FileName, 30)]);
ShowModal;
AskAgain := not CbDoNotAskAgain.Checked;
Result := Password;
end;
function TPassWordForm.ForBlob(DF: TField; FileName: string): string;
begin
FFileName := '';
DB := DF;
UseAsk := False;
DialogType := PASS_TYPE_IMAGE_BLOB;
ReallignControlsEx;
LbTitle.Caption := Format(TA('Enter password to file "%s" here:', 'Password'), [Mince(FileName, 30)]);
ShowModal;
Result := Password;
end;
function TPassWordForm.ForManyFiles(FileList: TStrings; CRC: Cardinal;
var Skip: Boolean): string;
begin
FFileName := '';
DB := nil;
LbTitle.Caption := TA('Enter password for group of files (press "Show files" to see list) here:', 'Password');
FCRC := CRC;
DialogType := PASS_TYPE_IMAGES_CRC;
UseAsk := False;
ReallignControlsEx;
LoadFileList(FileList);
FSkip := Skip;
ShowModal;
Skip := FSkip;
Result := Password;
end;
function TPassWordForm.ForSteganoraphyFile(FileName: string;
CRC: Cardinal): string;
begin
FFileName := FileName;
DB := nil;
UseAsk := False;
FCRC := CRC;
DialogType := PASS_TYPE_IMAGE_STENO;
ReallignControlsEx;
LbTitle.Caption := Format(TA('Enter password to file "%s" here:', 'Password'), [Mince(FileName, 30)]);
ShowModal;
Result := Password;
end;
procedure TPassWordForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caHide;
end;
procedure TPassWordForm.FormCreate(Sender: TObject);
begin
FOpenedList := False;
ClientHeight := BtOk.Top + BtOk.Height + 5;
CbSavePassToSession.Checked := AppSettings.Readbool('Options', 'AutoSaveSessionPasswords', True);
CbSavePassPermanent.Checked := AppSettings.Readbool('Options', 'AutoSaveINIPasswords', False);
LoadLanguage;
Password := '';
PassIcon := TIcon.Create;
PassIcon.Handle := LoadIcon(HInstance, PWideChar('PASSWORD'));
end;
procedure TPassWordForm.FormDestroy(Sender: TObject);
begin
F(PassIcon);
end;
procedure TPassWordForm.LoadLanguage;
begin
BeginTranslate;
try
EdPassword.WatermarkText := L('Enter your password here');
Caption := L('Password is required');
LbTitle.Caption := L('Enter password to open file "%s" here:');
BtCancel.Caption := L('Cancel');
BtOk.Caption := L('OK');
CbSavePassToSession.Caption := L('Save password for session');
CbSavePassPermanent.Caption := L('Save password in settings');
CbDoNotAskAgain.Caption := L('Don''t ask again');
BtCancelForFiles.Caption := L('Show files');
LbInfo.Caption := L('These files have the same password (hashes are equals)');
CloseDialog1.Caption := L('Close');
Skipthisfiles1.Caption := L('Skip these files');
BtHideDetails.Caption := L('Hide list');
CopyText1.Caption := L('Copy text');
finally
EndTranslate;
end;
end;
procedure TPassWordForm.BtOkClick(Sender: TObject);
function TEST: Boolean;
var
Crc, Crc2: Cardinal;
begin
Result := False;
if (DialogType = PASS_TYPE_IMAGE_STENO) or (DialogType = PASS_TYPE_IMAGES_CRC) then
begin
//unicode password
CalcStringCRC32(EdPassword.Text, Crc);
//old-style pasword
CalcAnsiStringCRC32(AnsiString(EdPassword.Text), Crc2);
Result := (Crc = FCRC) or (Crc2 = FCRC);
Exit;
end;
if FFileName <> '' then
Result := ValidPassInCryptGraphicFile(FFileName, EdPassword.Text);
if DB <> nil then
Result := ValidPassInCryptBlobStreamJPG(DB, EdPassword.Text);
end;
begin
if TEST then
begin
Password := EdPassword.Text;
if CbSavePassToSession.Checked then
SessionPasswords.AddForSession(Password);
if CbSavePassPermanent.Checked then
SessionPasswords.SaveInSettings(Password);
if CbSavePassToSession.Checked or CbSavePassPermanent.Checked then
RecheckDirectoryOnDrive(ExtractFilePath(FFileName));
Close;
end else
MessageBoxDB(Handle, L('Password is invalid!'), L('Error'), TD_BUTTON_OK, TD_ICON_ERROR);
end;
procedure TPassWordForm.EdPasswordKeyPress(Sender: TObject; var Key: Char);
begin
if Key = Char(VK_RETURN) then
begin
if ShiftKeyDown then
begin
SessionPasswords.AddForSession(EdPassword.Text);
Exit;
end;
Key := #0;
BtOkClick(Sender);
end;
if Key = Char(VK_ESCAPE) then
begin
Password := '';
Close;
end;
end;
procedure TPassWordForm.BtCancelClick(Sender: TObject);
var
P: TPoint;
begin
if (DialogType = PASS_TYPE_IMAGES_CRC) then
begin
P.X := BtCancel.Left;
P.Y := BtCancel.Top + BtCancel.Height;
P := ClientToScreen(P);
PmCloseAction.Popup(P.X, P.Y);
end else
begin
Password := '';
Close;
end;
end;
procedure TPassWordForm.FormKeyPress(Sender: TObject; var Key: Char);
begin
if Key = Char(VK_ESCAPE) then
begin
Password := '';
Close;
end;
end;
function TPassWordForm.GetFormID: string;
begin
Result := 'Password';
end;
procedure TPassWordForm.ReallignControlsEx;
begin
if not UseAsk then
begin
CbDoNotAskAgain.Visible := False;
BtCancel.Top := CbSavePassPermanent.Top + CbSavePassPermanent.Height + 3;
BtOk.Top := CbSavePassPermanent.Top + CbSavePassPermanent.Height + 3;
CbSavePassToSession.Enabled := CbSavePassToSession.Enabled and not(DialogType = PASS_TYPE_IMAGE_STENO) and not
(DialogType = PASS_TYPE_IMAGES_CRC);
CbSavePassPermanent.Enabled := CbSavePassPermanent.Enabled and not(DialogType = PASS_TYPE_IMAGE_STENO);
CbDoNotAskAgain.Enabled := CbDoNotAskAgain.Enabled and not(DialogType = PASS_TYPE_IMAGE_STENO);
if (DialogType = PASS_TYPE_IMAGES_CRC) then
CbSavePassToSession.Checked := True;
if (DialogType = PASS_TYPE_IMAGES_CRC) then
begin
LbTitle.Height := 50;
EdPassword.Top := LbTitle.Top + LbTitle.Height + 3;
CbSavePassToSession.Top := EdPassword.Top + EdPassword.Height + 5;
CbSavePassPermanent.Top := CbSavePassToSession.Top + CbSavePassToSession.Height + 3;
CbDoNotAskAgain.Top := CbSavePassPermanent.Top; // +CbSavePassPermanent.Height+3; //invisible
BtCancel.Top := CbDoNotAskAgain.Top + CbDoNotAskAgain.Height + 3;
BtOk.Top := CbDoNotAskAgain.Top + CbDoNotAskAgain.Height + 3;
BtCancelForFiles.Top := CbDoNotAskAgain.Top + CbDoNotAskAgain.Height + 3;
LbInfo.Top := BtCancelForFiles.Top + BtCancelForFiles.Height + 3;
InfoListBox.Top := LbInfo.Top + LbInfo.Height + 3;
end;
ClientHeight := BtOk.Top + BtOk.Height + 3;
end;
end;
procedure TPassWordForm.CopyText1Click(Sender: TObject);
begin
TextToClipboard(InfoListBox.Items.Text);
end;
procedure TPassWordForm.CustomFormAfterDisplay;
begin
inherited;
if EdPassword <> nil then
EdPassword.Refresh;
end;
procedure TPassWordForm.LoadFileList(FileList: TStrings);
begin
InfoListBox.Items.Assign(FileList);
BtCancelForFiles.Visible := True;
InfoListBox.Visible := True;
LbInfo.Visible := True;
BtHideDetails.Visible := True;
CbSavePassToSession.Enabled := False;
CbDoNotAskAgain.Enabled := True;
end;
procedure TPassWordForm.BtCancelForFilesClick(Sender: TObject);
begin
if FOpenedList then
begin
FOpenedList := False;
ClientHeight := BtCancelForFiles.Top + BtCancelForFiles.Height + 3;
InfoListBox.Visible := False;
BtHideDetails.Visible := False;
LbInfo.Visible := False;
end else
begin
FOpenedList := True;
ClientHeight := BtHideDetails.Top + BtHideDetails.Height + 3;
InfoListBox.Visible := True;
BtHideDetails.Visible := True;
LbInfo.Visible := True;
end;
end;
procedure TPassWordForm.CloseDialog1Click(Sender: TObject);
begin
Password := '';
Close;
end;
procedure TPassWordForm.Skipthisfiles1Click(Sender: TObject);
begin
Password := '';
FSkip := True;
Close;
end;
procedure TPassWordForm.BtHideDetailsClick(Sender: TObject);
begin
FOpenedList := False;
ClientHeight := BtCancelForFiles.Top + BtCancelForFiles.Height + 3;
InfoListBox.Visible := False;
BtHideDetails.Visible := False;
LbInfo.Visible := False;
end;
procedure TPassWordForm.InfoListBoxMeasureItem(Control: TWinControl;
Index: Integer; var Height: Integer);
begin
Height := InfoListBox.Canvas.TextHeight('Iy') * 3 + 5;
end;
procedure TPassWordForm.InterfaceDestroyed;
begin
inherited;
Release;
end;
procedure TPassWordForm.InfoListBoxDrawItem(Control: TWinControl;
Index: Integer; aRect: TRect; State: TOwnerDrawState);
var
ListBox: TListBox;
begin
ListBox := Control as TListBox;
if OdSelected in State then
begin
ListBox.Canvas.Brush.Color := Theme.HighlightColor;
ListBox.Canvas.Font.Color := Theme.HighlightTextColor;
end else
begin
ListBox.Canvas.Brush.Color := Theme.ListColor;
ListBox.Canvas.Font.Color := Theme.ListFontColor;
end;
// clearing rect
ListBox.Canvas.Pen.Color := ListBox.Canvas.Brush.Color;
ListBox.Canvas.Rectangle(ARect);
ListBox.Canvas.Pen.Color := ClBlack;
ListBox.Canvas.Font.Color := ClBlack;
Text := ListBox.Items[index];
DrawIconEx(ListBox.Canvas.Handle, ARect.Left, ARect.Top, PassIcon.Handle, 16, 16, 0, 0, DI_NORMAL);
ARect.Left := ARect.Left + 20;
DrawText(ListBox.Canvas.Handle, PWideChar(Text), Length(Text), ARect, DT_NOPREFIX + DT_LEFT + DT_WORDBREAK);
end;
initialization
FormInterfaces.RegisterFormInterface(IRequestPasswordForm, TPassWordForm);
end.
|
unit UntCustomDAO;
interface
uses
IBQuery;
type
TCustomDAO = class
protected
function CreateQuery(sql: string = ''): TIBQuery;
protected
procedure ParseQueryRecordToObject(qry: TIBQuery; obj: TObject);
procedure ParseDataChangedToQryInsert(qryAtual, qryInsert: TIBQuery; obj: TObject);
end;
implementation
uses
UntDm, SysUtils, DB, TypInfo;
{ TCustomDAO }
function TCustomDAO.CreateQuery(sql: string): TIBQuery;
begin
result := TIBQuery.Create(nil);
result.Database := Dm.Database;
if Trim(sql) <> '' then
result.SQL.Text := sql;
end;
procedure TCustomDAO.ParseQueryRecordToObject(qry: TIBQuery; obj: TObject);
var
classTypeInfo: PTypeInfo;
index: integer;
field: TField;
prop: PPropInfo;
typeName: string;
begin
classTypeInfo := PTypeInfo(obj.ClassInfo);
for index := 0 to pred(qry.FieldCount) do
begin
field := qry.Fields[index];
prop := GetPropInfo(classTypeInfo, field.FieldName);
if prop = nil then
continue;
case prop^.PropType^^.Kind of
tkInteger, tkInt64:
SetPropValue(obj, field.FieldName, field.AsInteger);
tkChar, tkString, tkWChar, tkLString, tkWString:
SetPropValue(obj, field.FieldName, field.AsString);
tkVariant:
SetPropValue(obj, field.FieldName, field.AsVariant);
tkFloat:
begin
typeName := LowerCase(prop^.PropType^.Name);
if (typeName = 'tdatetime') or (typeName = 'tdate') or (typeName = 'ttime') then
SetPropValue(obj, field.FieldName, field.AsDateTime)
else
SetPropValue(obj, field.FieldName, field.AsFloat);
end;
else
raise Exception.Create('Tipo "' + GetEnumName(TypeInfo(TTypeKind), Ord(prop^.PropType^^.Kind)) + '" ainda não tratado');
end;
end;
end;
procedure TCustomDAO.ParseDataChangedToQryInsert(qryAtual, qryInsert: TIBQuery; obj: TObject);
var
classTypeInfo: PTypeInfo;
index: integer;
field: TField;
param: TParam;
prop: PPropInfo;
propValue: string;
begin
classTypeInfo := PTypeInfo(obj.ClassInfo);
for index := 0 to pred(qryAtual.FieldCount) do
begin
field := qryAtual.Fields[index];
param := qryInsert.Params.FindParam(field.FieldName);
if param = nil then
continue;
prop := GetPropInfo(classTypeInfo, field.FieldName);
if prop = nil then
continue;
propValue := GetPropValue(obj, field.FieldName);
if field.AsString <> propValue then
begin
case prop^.PropType^^.Kind of
tkInteger, tkChar, tkWChar, tkClass:
param.AsInteger := GetOrdProp(obj, prop);
tkFloat:
param.AsFloat := GetFloatProp(obj, prop);
tkString, tkLString:
param.AsString := GetStrProp(obj, prop);
tkWString:
param.AsString := GetWideStrProp(obj, prop);
tkVariant:
param.Value := GetVariantProp(obj, prop);
tkInt64:
param.AsInteger := GetInt64Prop(obj, prop);
else
raise Exception.Create('Tipo "' + GetEnumName(TypeInfo(TTypeKind), Ord(prop^.PropType^^.Kind)) + '" ainda não tratado');
end;
end
else
begin
param.Value := field.Value;
end;
end;
end;
end.
|
unit uModRekening;
interface
uses uModApp;
type
TModRekeningGroup = class;
TModRekening = class(TModApp)
private
FRekeningGroup: TModRekeningGroup;
FREK_CODE: String;
FREK_PARENT: TModRekening;
FREK_DESCRIPTION: String;
FREK_LEVEL: Integer;
FREK_NAME: String;
FREK_IS_DEBET: Integer;
FREK_IS_GROUP: Integer;
FREK_IS_LEAF: Integer;
public
class function GetTableName: String; override;
published
[AttributeOfForeign('REF$GRUP_REKENING_ID')]
property RekeningGroup: TModRekeningGroup read FRekeningGroup write
FRekeningGroup;
[AttributeOfCode]
property REK_CODE: String read FREK_CODE write FREK_CODE;
[AttributeOfForeign('REKENING_PARENT_ID')]
property REK_PARENT: TModRekening read FREK_PARENT write FREK_PARENT;
property REK_DESCRIPTION: String read FREK_DESCRIPTION write FREK_DESCRIPTION;
property REK_LEVEL: Integer read FREK_LEVEL write FREK_LEVEL;
property REK_NAME: String read FREK_NAME write FREK_NAME;
property REK_IS_DEBET: Integer read FREK_IS_DEBET write FREK_IS_DEBET;
property REK_IS_GROUP: Integer read FREK_IS_GROUP write FREK_IS_GROUP;
property REK_IS_LEAF: Integer read FREK_IS_LEAF write FREK_IS_LEAF;
end;
TModRekeningGroup = class(TModApp)
private
FGROREK_NAME: String;
FGROREK_DESCRIPTION: String;
FGROREK_ID: Integer;
public
class function GetTableName: String; override;
published
property GROREK_NAME: String read FGROREK_NAME write FGROREK_NAME;
property GROREK_DESCRIPTION: String read FGROREK_DESCRIPTION write
FGROREK_DESCRIPTION;
property GROREK_ID: Integer read FGROREK_ID write FGROREK_ID;
end;
implementation
class function TModRekening.GetTableName: String;
begin
Result := 'REKENING';
end;
class function TModRekeningGroup.GetTableName: String;
begin
Result := 'REF$GRUP_REKENING';
end;
initialization
TModRekening.RegisterRTTI;
TModRekeningGroup.RegisterRTTI;
end.
|
unit Unit6;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TForm6 = class(TForm)
Label1: TLabel;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form6: TForm6;
implementation
{$R *.dfm}
procedure TForm6.FormCreate(Sender: TObject);
begin
label1.Caption:='Webcam 1.0 jest programem do pobierania i archiwizowania obrazu z kamery internetowej, oraz wysyłania go na serwer ftp. Można wykorzystać go do udostępniania i umieszczania obrazu na żywo na stronie internetowej, lub do zdalnego monitoringu.'+#13 +
'Aby rozpocząć pracę z programem należy wybrać jedną z opcji wysyłania obrazu na serwer (tak/nie). Aby używać programu bez opcji wysyłania obrazu na serwer należy w menu opcje odznaczyć pozycję "wysyłaj obraz na serwer" i kliknąć odblokowany button start.'+#13 +
'W przypadku gdy chcemy wysyłać obraz na serwer należy w menu opcje wybrać połączenie ftp, uzupełnić wszystkie pola i wybrać OK. Zostanie wówczas przeprowadzony test połączenia. Gdy wynik będzie pozytywny, zostanie odblokowany przycisk start. '+
'Jeżeli nie - należy wprowadzić dane ponownie.'+#13 +
'Aby przerwać wysyłanie - należy wcisnąć button stop.';
end;
end.
|
unit uMainForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
editDecimal: TEdit;
Label1: TLabel;
editHex: TEdit;
Label2: TLabel;
editBinary: TEdit;
Label4: TLabel;
btnClear: TButton;
btnExit: TButton;
procedure editDecimalChange(Sender: TObject);
procedure editHexChange(Sender: TObject);
procedure editOctalChange(Sender: TObject);
procedure editBinaryChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure btnClearClick(Sender: TObject);
procedure btnExitClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
Function binToDec(Value :string) : integer;
function DecToBin(value : Integer; MinBit : Integer) : string;
var
Form1: TForm1;
num: Integer;
implementation
{$R *.dfm}
procedure TForm1.editDecimalChange(Sender: TObject);
begin
try
if editDecimal.Focused then
begin
num := StrToInt(editDecimal.Text);
editHex.Text := Format('%.2x', [num]);
editBinary.Text := DecToBin(num, 8);
end;
except on e:Exception do
begin
editHex.Clear;
editBinary.Clear;
end;
end;
end;
procedure TForm1.editHexChange(Sender: TObject);
begin
try
if editHex.Focused then
begin
num := StrToInt('$' + editHex.Text);
editDecimal.Text := IntToStr(num);
editBinary.Text := DecToBin(num, 8);
end;
except on e:Exception do
begin
editDecimal.Clear;
editBinary.Clear;
end;
end;
end;
procedure TForm1.editOctalChange(Sender: TObject);
begin
;
end;
procedure TForm1.editBinaryChange(Sender: TObject);
begin
try
if editBinary.Focused then
begin
num := binToDec(editBinary.Text);
editDecimal.Text := IntToStr(num);
editHex.Text := Format('%.2x', [num]);
end;
except on e:Exception do
begin
editDecimal.Clear;
editBinary.Clear;
end;
end;
end;
{ 二进制转十进制 }
Function binToDec(Value :string) : integer;
var
str : String;
Int : Integer;
i : integer;
begin
Str := UpperCase(Value);
Int := 0;
FOR i := 1 TO Length(str) DO
Int := Int * 2+ ORD(str[i]) - 48;
Result := Int;
end;
{ 十进制转二进制}
function DecToBin(value : Integer; MinBit : Integer) : string;
begin
result := '';
while (value > 0) do
begin
if (Trunc(value / 2) * 2 = value) then
result := '0' + result
else
Result := '1' + Result;
value := Trunc(value / 2);
end;
//填满MaxBit位
while (Length(Result) < MinBit) Do Result := '0' + Result;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
self.KeyPreview := true;
end;
procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char);
begin
if key = #27 then
Application.Terminate;
end;
procedure TForm1.btnClearClick(Sender: TObject);
begin
editDecimal.Clear;
editHex.Clear;
editBinary.Clear;
editDecimal.SetFocus;
end;
procedure TForm1.btnExitClick(Sender: TObject);
begin
Application.Terminate;
end;
end.
|
(*----------------------------------------------------------------------------*
* Direct3D sample from DirectX 9.0 SDK December 2006 *
* Delphi adaptation by Alexey Barkovoy (e-mail: directx@clootie.ru) *
* *
* Supported compilers: Delphi 5,6,7,9; FreePascal 2.0 *
* *
* Latest version can be downloaded from: *
* http://www.clootie.ru *
* http://sourceforge.net/projects/delphi-dx9sdk *
*----------------------------------------------------------------------------*
* $Id: SkinMesh.pas,v 1.6 2007/02/05 22:21:09 clootie Exp $
*----------------------------------------------------------------------------*)
//-----------------------------------------------------------------------------
// File: SkinMesh.h, SkinMesh.cpp
//
// Desc: Skinned mesh loader
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
{$I DirectX.inc}
unit SkinMesh;
interface
uses
Windows, SysUtils, Math,
Direct3D9, D3DX9;
const
MAX_BONES = 26;
type
//--------------------------------------------------------------------------------------
// Name: struct D3DXFRAME_DERIVED
// Desc: Structure derived from D3DXFRAME so we can add some app-specific
// info that will be stored with each frame
//--------------------------------------------------------------------------------------
PD3DXFrameDerived = ^TD3DXFrameDerived;
TD3DXFrameDerived = packed record
Name: PAnsiChar;
TransformationMatrix: TD3DXMatrix;
pMeshContainer: PD3DXMeshContainer;
pFrameSibling: PD3DXFrame;
pFrameFirstChild: PD3DXFrame;
////////////////////////////////////////////
CombinedTransformationMatrix: TD3DXMatrixA16;
end;
PD3DXMaterialArray = ^TD3DXMaterialArray;
TD3DXMaterialArray = array[0..MaxInt div SizeOf(TD3DXMaterial) - 1] of TD3DXMaterial;
PIDirect3DTexture9Array = ^TIDirect3DTexture9Array;
TIDirect3DTexture9Array = array[0..MaxInt div SizeOf(IDirect3DTexture9) - 1] of IDirect3DTexture9;
PD3DXMatrixPointerArray = ^TD3DXMatrixPointerArray;
TD3DXMatrixPointerArray = array[0..MaxInt div SizeOf(Pointer) - 1] of PD3DXMatrix;
PD3DXMatrixArray = ^TD3DXMatrixArray;
TD3DXMatrixArray = array[0..MaxInt div SizeOf(TD3DXMatrix) - 1] of TD3DXMatrix;
PD3DXAttributeRangeArray = ^TD3DXAttributeRangeArray;
TD3DXAttributeRangeArray = array[0..MaxInt div SizeOf(TD3DXAttributeRange) - 1] of TD3DXAttributeRange;
//-----------------------------------------------------------------------------
// Name: struct D3DXMESHCONTAINER_DERIVED
// Desc: Structure derived from D3DXMESHCONTAINER so we can add some app-specific
// info that will be stored with each mesh
//-----------------------------------------------------------------------------
PD3DXMeshContainerDerived = ^TD3DXMeshContainerDerived;
TD3DXMeshContainerDerived = packed record { public D3DXMESHCONTAINER }
Name: PAnsiChar;
MeshData: TD3DXMeshData;
pMaterials: PD3DXMaterial;
pEffects: PD3DXEffectInstance;
NumMaterials: DWORD;
pAdjacency: PDWORD;
pSkinInfo: ID3DXSkinInfo;
pNextMeshContainer: PD3DXMeshContainer;
////////////////////////////////////////////
ppTextures: PIDirect3DTexture9Array; // array of textures, entries are NULL if no texture specified
// SkinMesh info
pAttributeTable: PD3DXAttributeRange;
NumAttributeGroups: DWORD;
NumInfl: DWORD;
pBoneCombinationBuf: ID3DXBuffer;
ppBoneMatrixPtrs: PD3DXMatrixPointerArray;
pBoneOffsetMatrices: PD3DXMatrixArray;
NumPaletteEntries: DWORD;
end;
//-----------------------------------------------------------------------------
// Name: class CAllocateHierarchy
// Desc: Custom version of ID3DXAllocateHierarchy with custom methods to create
// frames and meshcontainers.
//-----------------------------------------------------------------------------
CAllocateHierarchy = class(ID3DXAllocateHierarchy)
public
function CreateFrame(Name: PAnsiChar; out ppNewFrame: PD3DXFrame): HResult; override;
function CreateMeshContainer(Name: PAnsiChar; const pMeshData: TD3DXMeshData;
pMaterials: PD3DXMaterial; pEffectInstances: PD3DXEffectInstance;
NumMaterials: DWORD; pAdjacency: PDWORD; pSkinInfo: ID3DXSkinInfo;
out ppMeshContainerOut: PD3DXMeshContainer): HResult; override;
function DestroyFrame(pFrameToFree: PD3DXFrame): HResult; override;
function DestroyMeshContainer(pMeshContainerToFree: PD3DXMeshContainer): HResult; override;
public
constructor Create;
function FilterMesh(const pd3dDevice: IDirect3DDevice9; const pMeshIn: ID3DXMesh; out ppMeshOut: ID3DXMesh): HRESULT;
end;
// Public functions
function SetupBoneMatrixPointersOnMesh(pMeshContainerBase: PD3DXMeshContainer; pFrameRoot: PD3DXFrame): HRESULT;
function SetupBoneMatrixPointers(pFrame: PD3DXFrame; pFrameRoot: PD3DXFrame): HRESULT;
procedure UpdateFrameMatrices(pFrameBase: PD3DXFrame; const pParentMatrix: PD3DXMatrix);
//todo: Fill Bug report to MS
//procedure UpdateSkinningMethod(pFrameBase: PD3DXFrame);
function GenerateSkinnedMesh(const pd3dDevice: IDirect3DDevice9; pMeshContainer: PD3DXMeshContainerDerived): HRESULT;
implementation
//--------------------------------------------------------------------------------------
// Name: AllocateName()
// Desc: Allocates memory for a string to hold the name of a frame or mesh
//--------------------------------------------------------------------------------------
//Clootie: AllocateName == StrNew in Delphi
(*HRESULT AllocateName( LPCSTR Name, char** ppNameOut )
{
HRESULT hr = S_OK;
char* pNewName = NULL;
// Start clean
(*ppNameOut) = NULL;
// No work to be done if name is NULL
if( NULL == Name )
{
hr = S_OK;
goto e_Exit;
}
// Allocate a new buffer
const UINT BUFFER_LENGTH = (UINT)strlen(Name) + 1;
pNewName = new CHAR[BUFFER_LENGTH];
if( NULL == pNewName )
{
hr = E_OUTOFMEMORY;
goto e_Exit;
}
// Copy the string and return
StringCchCopyA( pNewName, BUFFER_LENGTH, Name );
(*ppNameOut) = pNewName;
pNewName = NULL;
hr = S_OK;
e_Exit:
SAFE_DELETE_ARRAY( pNewName );
return hr;
}*)
{ CAllocateHierarchy }
constructor CAllocateHierarchy.Create;
begin
end;
//--------------------------------------------------------------------------------------
// Name: CAllocateHierarchy::CreateFrame()
// Desc: Create a new derived D3DXFRAME object
//--------------------------------------------------------------------------------------
function CAllocateHierarchy.CreateFrame(Name: PAnsiChar;
out ppNewFrame: PD3DXFrame): HResult;
var
pFrame: PD3DXFrameDerived;
begin
Result := S_OK;
// Start clean
ppNewFrame := nil;
// Create a new frame
New(pFrame); // {PD3DXFrameDerived}
try try
// Clear the new frame
ZeroMemory(pFrame, SizeOf(TD3DXFrameDerived));
// Duplicate the name string
pFrame.Name:= StrNew(Name);
// Initialize other data members of the frame
D3DXMatrixIdentity(pFrame.TransformationMatrix);
D3DXMatrixIdentity(pFrame.CombinedTransformationMatrix);
ppNewFrame := PD3DXFrame(pFrame);
pFrame := nil;
except
on EOutOfMemory do Result:= E_OUTOFMEMORY;
else raise;
end;
finally
Dispose(pFrame);
end;
end;
//--------------------------------------------------------------------------------------
// Name: CAllocateHierarchy::CreateMeshContainer()
// Desc: Create a new derived D3DXMESHCONTAINER object
//--------------------------------------------------------------------------------------
function CAllocateHierarchy.CreateMeshContainer(Name: PAnsiChar;
const pMeshData: TD3DXMeshData; pMaterials: PD3DXMaterial;
pEffectInstances: PD3DXEffectInstance; NumMaterials: DWORD;
pAdjacency: PDWORD; pSkinInfo: ID3DXSkinInfo;
out ppMeshContainerOut: PD3DXMeshContainer): HResult;
var
pNewMeshContainer: PD3DXMeshContainerDerived;
pNewAdjacency: PDWORD;
pNewBoneOffsetMatrices: PD3DXMatrixArray;
pd3dDevice: IDirect3DDevice9;
pNewMesh: ID3DXMesh;
pTempMesh: ID3DXMesh;
NumBones: DWORD;
iBone: Integer;
begin
pNewMesh := nil;
pNewMeshContainer := nil;
pNewAdjacency := nil;
pNewBoneOffsetMatrices := nil;
// Start clean
ppMeshContainerOut := nil;
Result:= E_FAIL;
try try
// This sample does not handle patch meshes, so fail when one is found
if (pMeshData._Type <> D3DXMESHTYPE_MESH) then Exit;
// Get the pMesh interface pointer out of the mesh data structure
pNewMesh := pMeshData.pMesh as ID3DXMesh;
// Get the device
Result := pNewMesh.GetDevice(pd3dDevice);
if FAILED(Result) then Exit;
// Allocate the overloaded structure to return as a D3DXMESHCONTAINER
New(pNewMeshContainer); // = new D3DXMESHCONTAINER_DERIVED;
// Clear the new mesh container
FillChar(pNewMeshContainer^, 0, SizeOf(TD3DXMeshContainerDerived));
//---------------------------------
// Name
//---------------------------------
// Copy the name. All memory as input belongs to caller, interfaces can be addref'd though
pNewMeshContainer.Name := StrNew(Name);
//---------------------------------
// MeshData
//---------------------------------
// Rearrange the mesh as desired
Result := FilterMesh(pd3dDevice, ID3DXMesh(pMeshData.pMesh), pNewMesh);
if FAILED(Result) then Exit;
// Copy the pointer
pNewMeshContainer.MeshData._Type := D3DXMESHTYPE_MESH;
pNewMeshContainer.MeshData.pMesh := pNewMesh;
pNewMesh := nil;
//---------------------------------
// Materials (disabled)
//---------------------------------
pNewMeshContainer.NumMaterials := 0;
pNewMeshContainer.pMaterials := nil;
//---------------------------------
// Adjacency
//---------------------------------
pTempMesh := pNewMeshContainer.MeshData.pMesh as ID3DXMesh;
GetMem(pNewAdjacency, SizeOf(DWORD)*pTempMesh.GetNumFaces*3);
Result := pTempMesh.GenerateAdjacency(1e-6, pNewAdjacency);
if FAILED(Result) then Exit;
// Copy the pointer
pNewMeshContainer.pAdjacency := pNewAdjacency;
pNewAdjacency := nil;
//---------------------------------
// SkinInfo
//---------------------------------
// if there is skinning information, save off the required data and then setup for HW skinning
if (pSkinInfo <> nil) then
begin
// first save off the SkinInfo and original mesh data
pNewMeshContainer.pSkinInfo := pSkinInfo;
// Will need an array of offset matrices to move the vertices from the figure space to the
// bone's space
NumBones := pSkinInfo.GetNumBones;
GetMem(pNewBoneOffsetMatrices, SizeOf(TD3DXMatrix)*NumBones);
// Get each of the bone offset matrices so that we don't need to get them later
for iBone := 0 to NumBones - 1 do
begin
pNewBoneOffsetMatrices[iBone] := pSkinInfo.GetBoneOffsetMatrix(iBone)^;
end;
// Copy the pointer
pNewMeshContainer.pBoneOffsetMatrices := pNewBoneOffsetMatrices;
pNewBoneOffsetMatrices := nil;
// GenerateSkinnedMesh will take the general skinning information and transform it to a
// HW friendly version
Result := GenerateSkinnedMesh(pd3dDevice, pNewMeshContainer);
if FAILED(Result) then Exit;
end;
// Copy the mesh container and return
ppMeshContainerOut := PD3DXMeshContainer(pNewMeshContainer);
pNewMeshContainer := nil;
Result := S_OK;
except
on EOutOfMemory do Result:= E_OUTOFMEMORY;
else raise;
end;
finally
FreeMem(pNewBoneOffsetMatrices);
FreeMem(pNewAdjacency);
pNewMesh := nil;
pd3dDevice := nil;
// Call Destroy function to properly clean up the memory allocated
if (pNewMeshContainer <> nil) then DestroyMeshContainer(PD3DXMeshContainer(pNewMeshContainer));
end;
end;
//--------------------------------------------------------------------------------------
// Name: CAllocateHierarchy::FilterMesh
// Desc: Alter or optimize the mesh before adding it to the new mesh container
//--------------------------------------------------------------------------------------
function CAllocateHierarchy.FilterMesh(const pd3dDevice: IDirect3DDevice9;
const pMeshIn: ID3DXMesh; out ppMeshOut: ID3DXMesh): HRESULT;
const
// Create a new vertex declaration to hold all the required data
VertexDecl: array[0..6] of TD3DVertexElement9 =
(
(Stream: 0; Offset: 0; _Type: D3DDECLTYPE_FLOAT3; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_POSITION; UsageIndex: 0),
(Stream: 0; Offset: 12; _Type: D3DDECLTYPE_FLOAT3; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_NORMAL; UsageIndex: 0),
(Stream: 0; Offset: 24; _Type: D3DDECLTYPE_FLOAT3; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_TANGENT; UsageIndex: 0),
(Stream: 0; Offset: 36; _Type: D3DDECLTYPE_FLOAT2; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_TEXCOORD; UsageIndex: 0),
(Stream: 0; Offset: 44; _Type: D3DDECLTYPE_FLOAT4; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_BLENDWEIGHT; UsageIndex: 0),
(Stream: 0; Offset: 60; _Type: D3DDECLTYPE_FLOAT4; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_BLENDINDICES; UsageIndex: 0),
{D3DDECL_END()}(Stream:$FF; Offset:0; _Type:D3DDECLTYPE_UNUSED; Method:TD3DDeclMethod(0); Usage:TD3DDeclUsage(0); UsageIndex:0)
);
var
pTempMesh: ID3DXMesh;
pNewMesh: ID3DXMesh;
begin
pTempMesh := nil;
pNewMesh := nil;
// Start clean
ppMeshOut := nil;
// Clone mesh to the new vertex format
Result := pMeshIn.CloneMesh(pMeshIn.GetOptions, @VertexDecl, pd3dDevice, pTempMesh);
if FAILED(Result) then Exit;
// Compute tangents, which are required for normal mapping
Result := D3DXComputeTangentFrameEx(pTempMesh, DWORD(D3DDECLUSAGE_TEXCOORD), 0, DWORD(D3DDECLUSAGE_TANGENT), 0,
D3DX_DEFAULT, 0, DWORD(D3DDECLUSAGE_NORMAL), 0,
0, nil, -1, 0, -1, pNewMesh, nil);
if FAILED(Result) then Exit;
// Copy the mesh and return
ppMeshOut := pNewMesh;
pNewMesh := nil;
pTempMesh := nil;
Result := S_OK;
end;
//--------------------------------------------------------------------------------------
// Called either by CreateMeshContainer when loading a skin mesh, or when
// changing methods. This function uses the pSkinInfo of the mesh
// container to generate the desired drawable mesh and bone combination
// table.
//--------------------------------------------------------------------------------------
function GenerateSkinnedMesh(const pd3dDevice: IDirect3DDevice9;
pMeshContainer: PD3DXMeshContainerDerived): HRESULT;
var
pMeshStart: ID3DXMesh;
pSkinInfo: ID3DXSkinInfo;
begin
Result:= S_OK;
// Save off the mesh
pMeshStart := ID3DXMesh(pMeshContainer.MeshData.pMesh);
pMeshContainer.MeshData.pMesh := nil;
// Start clean
pMeshContainer.pBoneCombinationBuf := nil;
// Get the SkinInfo
if (pMeshContainer.pSkinInfo = nil) then Exit;
pSkinInfo := pMeshContainer.pSkinInfo;
if (pSkinInfo = nil) then
begin
Result := E_INVALIDARG;
Exit;
end;
// Use ConvertToIndexedBlendedMesh to generate drawable mesh
pMeshContainer.NumPaletteEntries := Min(MAX_BONES, pSkinInfo.GetNumBones);
Result := pSkinInfo.ConvertToIndexedBlendedMesh(
pMeshStart,
D3DXMESHOPT_VERTEXCACHE or D3DXMESH_MANAGED,
pMeshContainer.NumPaletteEntries,
pMeshContainer.pAdjacency,
nil, nil, nil,
@pMeshContainer.NumInfl,
pMeshContainer.NumAttributeGroups,
pMeshContainer.pBoneCombinationBuf,
ID3DXMesh(pMeshContainer.MeshData.pMesh));
if FAILED(Result) then Exit;
pMeshStart := nil;
Result := S_OK;
end;
//--------------------------------------------------------------------------------------
// Name: CAllocateHierarchy::DestroyFrame()
// Desc:
//--------------------------------------------------------------------------------------
function CAllocateHierarchy.DestroyFrame(
pFrameToFree: PD3DXFrame): HResult;
begin
StrDispose(pFrameToFree.Name);
Dispose(pFrameToFree);
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// Name: CAllocateHierarchy::DestroyMeshContainer()
// Desc:
//--------------------------------------------------------------------------------------
function CAllocateHierarchy.DestroyMeshContainer(pMeshContainerToFree: PD3DXMeshContainer): HResult;
var
pMeshContainer: PD3DXMeshContainerDerived;
begin
pMeshContainer := PD3DXMeshContainerDerived(pMeshContainerToFree);
with pMeshContainer^ do
begin
StrDispose(Name);
FreeMem(pAdjacency);
FreeMem(pMaterials);
FreeMem(pBoneOffsetMatrices);
FreeMem(ppBoneMatrixPtrs);
pBoneCombinationBuf := nil;
MeshData.pMesh := nil;
pSkinInfo := nil;
end;
Dispose(pMeshContainer);
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// Update the frame matrices
//--------------------------------------------------------------------------------------
procedure UpdateFrameMatrices(pFrameBase: PD3DXFrame; const pParentMatrix: PD3DXMatrix);
var
pFrame: PD3DXFrameDerived;
begin
pFrame := PD3DXFrameDerived(pFrameBase);
// Concatenate all matrices in the chain
if (pParentMatrix <> nil)
then D3DXMatrixMultiply(pFrame.CombinedTransformationMatrix, pFrame.TransformationMatrix, pParentMatrix^)
else pFrame.CombinedTransformationMatrix := pFrame.TransformationMatrix;
// Call siblings
if Assigned(pFrame.pFrameSibling)
then UpdateFrameMatrices(pFrame.pFrameSibling, pParentMatrix);
// Call children
if Assigned(pFrame.pFrameFirstChild)
then UpdateFrameMatrices(pFrame.pFrameFirstChild, @pFrame.CombinedTransformationMatrix);
end;
//--------------------------------------------------------------------------------------
// Called to setup the pointers for a given bone to its transformation matrix
//--------------------------------------------------------------------------------------
function SetupBoneMatrixPointersOnMesh(pMeshContainerBase: PD3DXMeshContainer; pFrameRoot: PD3DXFrame): HRESULT;
var
iBone, cBones: Integer;
pFrame: PD3DXFrameDerived;
pMeshContainer: PD3DXMeshContainerDerived;
begin
pMeshContainer := PD3DXMeshContainerDerived(pMeshContainerBase);
// if there is a skinmesh, then setup the bone matrices
if (pMeshContainer.pSkinInfo <> nil) then
begin
cBones := pMeshContainer.pSkinInfo.GetNumBones;
// pMeshContainer.ppBoneMatrixPtrs := new D3DXMATRIX*[cBones];
try
GetMem(pMeshContainer.ppBoneMatrixPtrs, SizeOf(PD3DXMatrix)*cBones);
except
Result:= E_OUTOFMEMORY;
Exit;
end;
for iBone := 0 to cBones - 1 do
begin
pFrame := PD3DXFrameDerived(D3DXFrameFind(pFrameRoot, pMeshContainer.pSkinInfo.GetBoneName(iBone)));
if (pFrame = nil) then
begin
Result:= E_FAIL;
Exit;
end;
pMeshContainer.ppBoneMatrixPtrs[iBone] := @pFrame.CombinedTransformationMatrix;
end;
end;
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// Called to setup the pointers for a given bone to its transformation matrix
//--------------------------------------------------------------------------------------
function SetupBoneMatrixPointers(pFrame: PD3DXFrame; pFrameRoot: PD3DXFrame): HRESULT;
begin
if (pFrame.pMeshContainer <> nil) then
begin
Result := SetupBoneMatrixPointersOnMesh(pFrame.pMeshContainer, pFrameRoot);
if FAILED(Result) then Exit;
end;
if (pFrame.pFrameSibling <> nil) then
begin
Result := SetupBoneMatrixPointers(pFrame.pFrameSibling, pFrameRoot);
if FAILED(Result) then Exit;
end;
if (pFrame.pFrameFirstChild <> nil) then
begin
Result := SetupBoneMatrixPointers(pFrame.pFrameFirstChild, pFrameRoot);
if FAILED(Result) then Exit;
end;
Result:= S_OK;
end;
end.
|
unit uSisSenhaTrocaDlg;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
uParentDialogFrm, StdCtrls, Buttons, ExtCtrls, siComp, siLangRT, Mask,
SuperComboADO;
type
TSisSenhaTrocaDlg = class(TParentDialogFrm)
edAtual: TEdit;
edNova1: TEdit;
edNova2: TEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
scUser: TSuperComboADO;
procedure btOkClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
uses uDM, uMsgBox, uMsgCOnstant;
{$R *.DFM}
procedure TSisSenhaTrocaDlg.btOkClick(Sender: TObject);
begin
inherited;
if edNova1.text <> edNova2.text then
MsgBox(MSG_CRT_ERROR_PW_NOT_MATCH, vbCritical + vbOkOnly)
else
begin
with DM.quFreeSQL do
begin
Close;
SQL.Text := 'SELECT U.CodSystemUser as CodigoUsuario, U.PW as Senha ' +
'FROM SystemUser U ' +
'WHERE U.IDUser = ' + scUser.LookUpValue + ' and Desativado = 0';
Open;
if DM.quFreeSQL.IsEmpty or (UpperCase(edAtual.Text) <> UpperCase(DM.quFreeSQL.FieldByName('Senha').AsString)) then
MsgBox(MSG_INF_INVALID_USER_PASSWORD, vbOKOnly + vbInformation)
else
begin
if MsgBox(MSG_QST_SURE, vbQuestion + vbYesNo) = vbYes then
begin
Close;
DM.RunSQL('UPDATE SystemUser SET PW = ' + #39 + edNova1.Text + #39 + ' WHERE IDUser = ' + scUser.LookUpValue);
Self.Close;
end;
end;
Close;
end;
end;
end;
procedure TSisSenhaTrocaDlg.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action := caFree;
end;
end.
|
unit UCWind;
interface
uses Windows;
type
CWind = class(TObject)
private
{ Private declarations }
hPorta: THandle;
bImpressoraOnLine: Boolean;
bTampaAberta: Boolean;
bImpressoraComPapel: Boolean;
bPoucoPapel: Boolean;
bSensorGaveta: Boolean;
iTimeOut: Integer;
public
{ Public declarations }
function Conectar( pcPorta: PChar; strBaudRate: String = '9600';
chParidade: Char = 'N'; iBitsDados: cardinal = 8;
iStopBit: cardinal = 1):Boolean;
function Desconectar(): Boolean;
function ConfigurarTimeOut( iTimeOut: Integer ): Boolean;
function ImprimeTexto( strTexto: String ): Integer;
function ImprimeTextoFormatado( flagFormatacao: Integer; strTexto: String ): Integer;
function PegaStatusImpressora(): Integer;
procedure AcionarGuilhotina();
procedure ImprimeCodBarUPCA();
procedure ImprimeCodBarUPCE();
procedure ImprimeCodBarEAN13();
procedure ImprimeCodBarEAN8();
procedure ImprimeCodBarCode39();
procedure ImprimeCodBarITF();
procedure ImprimeCodBarCODABAR();
procedure ImprimeCodBarCode93();
procedure ImprimeCodBarCode128();
procedure ImprimeCodBarISBN();
procedure ImprimeCodBarMSI();
procedure ImprimeCodBarPLESSEY();
procedure DefineTextoCodBarTopo();
procedure DefineTextoCodBarBase();
end;
implementation
uses SysUtils, Classes;
Const
// Comandos seriais
ESC: Char = #27; // ESC - Escape
LF : Char = #10; // Line Feed
GS : Char = #29; // GS
// Flags de Formatação de Texto
TXT_SUBLINHADO: Integer = 1;
TXT_TAMANHO_FONTE: Integer = 2;
TXT_ENFATIZADO: Integer = 4;
TXT_ALTURA_DUPLA: Integer = 8;
TXT_LARGURA_DUPLA: Integer = 16;
TXT_ITALICO: Integer = 32;
TXT_SOBRESCRITO: Integer = 64;
TXT_SUBESCRITO: Integer = 128;
TXT_EXPANDIDO: Integer = 256;
TXT_CONDENSADO: Integer = 512;
//****************************************************************************//
// Data: 17/11/2006 //
// Desenvolvedor: Claudio Sampaio //
// //
// Destrição: Conecta e configura à porta de comunicação serial //
// Função: Conectar( pcPorta: PChar; strBaudRate: String; chParidade: Char; //
// iBitsDados: cardinal; iStopBit: cardinal):Boolean; //
// Parametros: //
// [IN] pcPorta: PChar - Identificação da porta serial de comunicação //
// [IN] strBaudRate: String - Velocidade de conexão com a porta serial //
// [IN] chParidade: Char - Valor da paridade de dados (P - Par, I - Impar, //
// N - Sem paridade) //
// [IN] iBitsDados: Cardinal - Número de bits por dados //
// [IN] iStopBit: Cardinal - Número de stop bits //
// //
// Retorno: //
// A função retorna um valor boleano, TRUE caso a conexão seja realizada com//
// sucesso, caso contrário retorna FALSE //
// //
//****************************************************************************//
function CWind.Conectar( pcPorta: PChar; strBaudRate: String = '9600';
chParidade: Char = 'N'; iBitsDados: cardinal = 8;
iStopBit: cardinal = 1):Boolean;
const
RxBufferSize = 256;
TxBufferSize = 256;
var
bSucesso: Boolean;
DCB: TDCB;
Config: string;
begin
bSucesso := TRUE;
hPorta := CreateFile(pcPorta,
GENERIC_WRITE,
0,
nil,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0);
if ( hPorta = INVALID_HANDLE_VALUE ) then
begin
bSucesso := FALSE;
end
else begin
if ( StrComp(pcPorta,'LPT') < 0 ) then // Se não for LPT configura a porta
begin
// Configura o tamanho do buffer
if not SetupComm(hPorta, RxBufferSize, TxBufferSize) then
bSucesso := False;
// Lê o estado da porta serial
if not GetCommState(hPorta, DCB) then
bSucesso := False;
//Config := 'baud=9600 parity=n data=8 stop=1';
Config := 'baud=' + '9600' + 'parity=' + 'N' + 'data=' +
IntToStr(iBitsDados) + 'stop=' + IntToStr(iStopBit);
// Constroi arquivo de configuração da porta serial
if not BuildCommDCB(@Config[1], DCB) then
bSucesso := FALSE;
// Configura o estado da porta serial
if not SetCommState(hPorta, DCB) then
bSucesso := FALSE;
// Configura TimeOut
if not ConfigurarTimeOut(6) then
bSucesso := FALSE;
// Pega Status da Impressora
PegaStatusImpressora();
end;
end;
Conectar:= bSucesso;
end;
//****************************************************************************//
// Data: 17/11/2006 //
// Desenvolvedor: Claudio Sampaio //
// //
// Destrição: Configura TimeOut da porta serial //
// Função: ConfigurarTimeOut( iTimeOut: Integer ): Boolean; //
// Parametros: //
// [IN] iTimeOut: integer - TimeOut da porta de comunicação
// //
// Retorno: //
// A função retorna um valor boleano, TRUE caso a conexão seja realizada com//
// sucesso, caso contrário retorna FALSE //
// //
//****************************************************************************//
function CWind.ConfigurarTimeOut( iTimeOut: Integer ): Boolean;
var
CommTimeouts: TCommTimeouts;
bSucesso: Boolean;
begin
bSucesso := TRUE;
with CommTimeouts do
begin
ReadIntervalTimeout := 1;
ReadTotalTimeoutMultiplier := 0;
ReadTotalTimeoutConstant := iTimeOut * 1000;
WriteTotalTimeoutMultiplier := 0;
WriteTotalTimeoutConstant := 1000;
end;
if not SetCommTimeouts(hPorta, CommTimeouts) then
bSucesso := FALSE;
ConfigurarTimeOut := bSucesso;
end;
//****************************************************************************//
// Data: 20/11/2006 //
// Desenvolvedor: Claudio Sampaio //
// //
// Destrição: Fecha conexão com a porta serial //
// Função: Desconectar(): Boolean; //
// Parametros: //
// Nenhum //
// //
// Retorno: //
// A função retorna um valor boleano, TRUE caso a conexão seja realizada //
// com sucesso, caso contrário retorna FALSE //
// //
//****************************************************************************//
function CWind.Desconectar(): Boolean;
var bSucesso: Boolean;
begin
bSucesso := CloseHandle(hPorta);
Desconectar := bSucesso;
end;
//****************************************************************************//
// Data: 20/11/2006 //
// Desenvolvedor: Claudio Sampaio //
// //
// Destrição: Imprime texto sem formatação na impressora //
// Função: ImprimeTexto( strTexto: String ): Integer; //
// Parametros: //
// [IN] strTexto: String - buffer contento o texto que será impresso na //
// impressora. //
// //
// Retorno: //
// Número de caracteres escritos na impressora, em caso de falha a função //
// retorna -1. //
// //
//****************************************************************************//
function CWind.ImprimeTexto( strTexto: String ): Integer;
var
i, iNumCaracteresEscritos: integer;
iNumCaracteres: Cardinal;
dwBytesWritten: DWORD;
bSucesso: Boolean;
begin
bSucesso := WriteFile( hPorta, Pchar(strTexto)[0], Cardinal(Length(strTexto)) , dwBytesWritten, nil);
{for i:= 1 to Length(strTexto) do
begin
bSucesso := WriteFile(hPorta,
strTexto[i],
1,
iNumCaracteres,
nil);
if (bSucesso) then
iNumCaracteresEscritos := iNumCaracteresEscritos + 1
else begin
iNumCaracteresEscritos := -1;
ImprimeTexto := iNumCaracteresEscritos;
end;
end;}
if ( bSucesso ) then
// Avança uma linha
bSucesso := WriteFile(hPorta,
LF,
1,
iNumCaracteres,
nil);
end;
//****************************************************************************//
// Data: 04/12/2006 //
// Desenvolvedor: Claudio Sampaio //
// //
// Destrição: Imprime texto com formatação informada na impressora //
// Função: ImprimeTextoFormatado( flagFormatacao: Integer, //
// strTexto: String ): Integer; //
// Parametros: //
// [IN] flagFormatacao: Integer - flags de formatação do texto: //
// FLAGS DESCRIÇÃO //
// TXT_SUBLINHADO - Texto sublinhado //
// TXT_TAMANHO_FONTE - Tamanho da Fonte (A ou B) //
// TXT_ENFATIZADO - Texto enfatizado //
// TXT_ALTURA_DUPLA - Texto com altura dupla //
// TXT_LARGURA_DUPLA - Texto com largura dupla //
// TXT_ITALICO - Texto Italico //
// TXT_SOBRESCRITO - Texto sobre escrito //
// TXT_SUBESCRITO - Texto subscrito //
// TXT_EXPANDIDO - Texto Expandido //
// TXT_CONDENSADO - Texto Condensado //
// //
// [IN] strTexto: String - buffer contento o texto que será impresso na //
// impressora. //
// //
// Retorno: //
// Número de caracteres escritos na impressora, em caso de falha a função //
// retorna -1. //
// //
//****************************************************************************//
function CWind.ImprimeTextoFormatado( flagFormatacao: Integer; strTexto: String ): Integer;
var
strAbreFormatacao, strFechaFormatacao, strTextoFormatado: String;
iNumCaracteresEscritos: Integer;
begin
strAbreFormatacao := '';
strFechaFormatacao := '';
if ( (flagFormatacao and TXT_SUBLINHADO) = 1 ) then
begin
strAbreFormatacao := strAbreFormatacao + ESC + '-' + Chr(1);
strFechaFormatacao := strFechaFormatacao + ESC + '-' + Chr(0);
end;
if ( (flagFormatacao and TXT_TAMANHO_FONTE) = 1 ) then
begin
strAbreFormatacao := strAbreFormatacao + ESC + 'M' + Chr(1);
strFechaFormatacao := strFechaFormatacao + ESC + 'M' + Chr(0);
end;
if ( (flagFormatacao and TXT_ENFATIZADO) = 1 ) then
begin
strAbreFormatacao := strAbreFormatacao + ESC + 'E';
strFechaFormatacao := strFechaFormatacao + ESC + 'F';
end;
if ( (flagFormatacao and TXT_ALTURA_DUPLA) = 1 ) then
begin
strAbreFormatacao := strAbreFormatacao + ESC + 'd' + Chr(1);
strFechaFormatacao := strFechaFormatacao + ESC + 'd' + Chr(0);
end;
if ( (flagFormatacao and TXT_LARGURA_DUPLA) = 1 ) then
begin
strAbreFormatacao := strAbreFormatacao + ESC + '!' + Chr(32); // TODO: Rever
strFechaFormatacao := strFechaFormatacao + ESC + '!' + Chr(0);
end;
if ( (flagFormatacao and TXT_ITALICO) = 1 ) then
begin
strAbreFormatacao := strAbreFormatacao + ESC + Chr(4);
strFechaFormatacao := strFechaFormatacao + ESC + Chr(5);
end;
if ( (flagFormatacao and TXT_SOBRESCRITO) = 1 ) then
begin
strAbreFormatacao := strAbreFormatacao + ESC + 'S' + Chr(1);
strFechaFormatacao := strFechaFormatacao + ESC + 'T';
end;
if ( (flagFormatacao and TXT_SUBESCRITO) = 1 ) then
begin
strAbreFormatacao := strAbreFormatacao + ESC + 'S' + Chr(0);
strFechaFormatacao := strFechaFormatacao + ESC + 'T';
end;
if ( (flagFormatacao and TXT_EXPANDIDO) = 1 ) then
begin
//strAbreFormatacao := strAbreFormatacao + ESC + 'S' + Chr(0);
//strFechaFormatacao := strFechaFormatacao + ESC + 'T';
end;
if ( (flagFormatacao and TXT_CONDENSADO) = 1 ) then
begin
//strAbreFormatacao := strAbreFormatacao + ESC + 'S' + Chr(0);
//strFechaFormatacao := strFechaFormatacao + ESC + 'T';
end;
strTextoFormatado := strAbreFormatacao + strTexto + strFechaFormatacao;
iNumCaracteresEscritos := ImprimeTexto(strTextoFormatado);
end;
//****************************************************************************//
// Data: 20/11/2006 //
// Desenvolvedor: Claudio Sampaio //
// //
// Destrição: Pega o status atual da impressora //
// Função: PegaStatusImpressora(): Integer; //
// Parametros: //
// Nenhum //
// //
// Retorno: //
// Retorna uma byte com o status atual da impressora: //
// Bit 0 - [0]Impressora off-line | [1]Impressora on-line //
// Bit 1 - [0]Impressora com Papel | [1]Impressora sem Papel //
// Bit 2 - [0]Sensor de gaveta baixo | [1]Sensor de gaveta alto //
// Bit 3 - [0]Tampa fechada | [1]Tampa aberta //
// Bit 4 - [0]Impre. com papel suficiente | [1]Impre. com pouco papel //
// Bit 5 - [0]Gilhotinha funcionando corretamente | [1]Falha na Gilhotinha //
// Bit 6-7 - sem utilização(nível lógico sempre "0") //
// //
//****************************************************************************//
function CWind.PegaStatusImpressora(): Integer;
const
ENQ: Char = #05;
begin
Result := 0;
end;
//****************************************************************************//
// Data: 22/02/2010 //
// Desenvolvedor: Oscar Menezes //
// //
// Descrição: Aciona a Guilhotina da Impressora //
// Função: AcionarGuilhotina(); //
// Parametros: //
// Nenhum //
// //
// Retorno: //
// Nenhum //
// //
//****************************************************************************//
procedure CWind.AcionarGuilhotina();
var
strTextoComando: String;
begin
strTextoComando:= ESC + 'w';
ImprimeTexto(strTextoComando);
end;
//****************************************************************************//
// Data: 24/02/2010 //
// Desenvolvedor: Oscar Menezes //
// //
// Descrição: Imprime um Código de Barras UPC-A //
// Função: ImprimeCodBarUPCA() //
// Parametros: //
// Nenhum //
// //
// Retorno: //
// Nenhum //
// //
//****************************************************************************//
procedure CWind.ImprimeCodBarUPCA();
var
strTextoComando: String;
begin
ImprimeTexto('Barcode UPCA:' + LF);
strTextoComando:= GS + chr(107) + chr(0) + '01234567890' + chr(0) ;
ImprimeTexto(strTextoComando);
end;
procedure CWind.ImprimeCodBarUPCE();
var
strTextoComando: String;
begin
ImprimeTexto('Barcode UPCE:' + LF);
strTextoComando:= GS + chr(107) + chr(1) + '123456' + chr(0) ;
ImprimeTexto(strTextoComando);
end;
procedure CWind.ImprimeCodBarEAN13();
var
strTextoComando: String;
begin
ImprimeTexto('Barcode EAN13:' + LF);
strTextoComando:= GS + chr(107) + chr(2) + '012345678912' + chr(0) ;
ImprimeTexto(strTextoComando);
end;
procedure CWind.ImprimeCodBarEAN8();
var
strTextoComando: String;
begin
ImprimeTexto('Barcode EAN8:' + LF);
strTextoComando:= GS + chr(107) + chr(3) + '1234567' + chr(0) ;
ImprimeTexto(strTextoComando);
end;
procedure CWind.ImprimeCodBarCode39();
var
strTextoComando: String;
begin
ImprimeTexto('Barcode Code39:' + LF);
strTextoComando:= GS + chr(107) + chr(4) + '01234567890' + chr(0) ;
ImprimeTexto(strTextoComando);
end;
procedure CWind.ImprimeCodBarITF();
var
strTextoComando: String;
begin
ImprimeTexto('Barcode ITF:' + LF);
strTextoComando:= GS + chr(107) + chr(5) + '01234567890' + chr(0) ;
ImprimeTexto(strTextoComando);
end;
procedure CWind.ImprimeCodBarCODABAR();
var
strTextoComando: String;
begin
ImprimeTexto('Barcode CODABAR:' + LF);
strTextoComando:= GS + chr(107) + chr(6) + '01234567890' + chr(0) ;
ImprimeTexto(strTextoComando);
end;
procedure CWind.ImprimeCodBarCode93();
var
strTextoComando: String;
begin
ImprimeTexto('Barcode Code93:' + LF);
strTextoComando:= GS + chr(107) + chr(72) + '10' + '0123456789' + chr(0) ;
ImprimeTexto(strTextoComando);
end;
procedure CWind.ImprimeCodBarCode128();
var
strTextoComando: String;
begin
ImprimeTexto('Barcode Code128:' + LF);
strTextoComando:= GS + chr(107) + chr(73) + chr(10) + '0123456789' + chr(0) ;
ImprimeTexto(strTextoComando);
end;
procedure CWind.ImprimeCodBarISBN();
var
strTextoComando: String;
begin
ImprimeTexto('Barcode ISBN:' + LF);
strTextoComando:= GS + chr(107) + chr(21) + '1123456789' + chr(0) ;
ImprimeTexto(strTextoComando);
end;
procedure CWind.ImprimeCodBarMSI();
var
strTextoComando: String;
begin
ImprimeTexto('Barcode MSI:' + LF);
strTextoComando:= GS + chr(107) + chr(22) + '0123456789' + chr(0) ;
ImprimeTexto(strTextoComando);
end;
procedure CWind.ImprimeCodBarPLESSEY();
var
strTextoComando: String;
begin
ImprimeTexto('Barcode PLESSEY:' + LF);
strTextoComando:= GS + chr(107) + chr(23) + '0123456789' + chr(0) ;
ImprimeTexto(strTextoComando);
end;
// Falta o PDF-417 devido a complexidade das regras
procedure CWind.DefineTextoCodBarTopo();
var
strTextoComando: String;
begin
strTextoComando:= GS + chr(72) + chr(1);
ImprimeTexto(strTextoComando);
end;
procedure CWind.DefineTextoCodBarBase();
var
strTextoComando: String;
begin
strTextoComando:= GS + chr(72) + chr(2);
ImprimeTexto(strTextoComando);
end;
end.
|
unit uFrmAvgCostCalculation;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Mask, DateBox, Buttons, ExtCtrls, ComCtrls, ADODB, DB,
DBClient;
type
TFrmAvgCostCalculation = class(TForm)
dtStart: TDateBox;
Label1: TLabel;
btnStart: TBitBtn;
btnClose: TBitBtn;
pnlCalculation: TPanel;
Label2: TLabel;
Label3: TLabel;
pbModel: TProgressBar;
pbTrans: TProgressBar;
cdsBalance: TClientDataSet;
quMovHistory: TADODataSet;
quModel: TADODataSet;
quModelLastBalance: TADODataSet;
cmdInsertBalance: TADOCommand;
cmdUpdateBalance: TADOCommand;
lbModelTotal: TLabel;
quModelLastAvgCost: TADODataSet;
procedure btnCloseClick(Sender: TObject);
procedure btnStartClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
private
procedure OpenModel(IDModel : variant);
procedure CloseModel;
procedure CalculateAvgCost;
procedure CreateBalance(IDModel : Integer; Data : TDateTime);
procedure UpdateBalance(IDModel : Integer; Data : TDateTime; AQty : Double; AAvgCost, ABalanceTotal : Currency);
procedure StartCalculation;
procedure GetModelLastBalance(AIDModel : Integer; var AQty : Double; var AAvgCost, ABalanceTotal : Currency);
function GetModelLastAvgCostNonZero(AIDModel: Integer; ABalanceDate: TDateTime): Currency;
public
function Start(AExecucaoAutomatica : Boolean) : Boolean;
end;
var
FrmAvgCostCalculation: TFrmAvgCostCalculation;
implementation
uses uDM, uDateTimeFunctions;
{$R *.dfm}
{ TFrmAvgCostCalculation }
function TFrmAvgCostCalculation.Start(AExecucaoAutomatica : Boolean): Boolean;
begin
dtStart.Date := Date;
if not AExecucaoAutomatica then
begin
ShowModal;
Result := True;
end
else
begin
Show;
btnStartClick(Self);
Close;
Result := True;
end;
end;
procedure TFrmAvgCostCalculation.btnCloseClick(Sender: TObject);
begin
Close;
end;
procedure TFrmAvgCostCalculation.btnStartClick(Sender: TObject);
begin
try
pnlCalculation.Visible := True;
btnClose.Enabled := False;
btnStart.Visible := False;
StartCalculation;
finally
btnClose.Enabled := True;
btnStart.Visible := True;
pnlCalculation.Visible:= False;
end;
end;
procedure TFrmAvgCostCalculation.StartCalculation;
begin
//Abrir os modelos ativos para fazer o calculo
OpenModel(Null);
//OpenModel(1932);
//Percorrer os modelos calculando o custo medio
CalculateAvgCost;
end;
procedure TFrmAvgCostCalculation.CloseModel;
begin
with quModel do
if Active then
Close;
end;
procedure TFrmAvgCostCalculation.OpenModel(IDModel: variant);
begin
with quModel do
if not Active then
begin
Parameters.ParamByName('IDModel').Value := IDModel;
Open;
pbModel.Max := RecordCount;
pbModel.Position := 0;
end;
end;
procedure TFrmAvgCostCalculation.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
CloseModel;
end;
procedure TFrmAvgCostCalculation.FormShow(Sender: TObject);
begin
//dtStart.Date := FirstDateMonth;
end;
procedure TFrmAvgCostCalculation.CalculateAvgCost;
var
FModelQty, FMovQty : Double;
FAvgCostOut,
FModelBalanceTotal,
FLastAvgCost,
FMovCost,
FNewAvgCost : Currency;
begin
with quModel do
begin
First;
while not EOF do
begin
//Pegar o ultimo balance do modelo
GetModelLastBalance(FieldByName('IDModel').AsInteger, FModelQty, FAvgCostOut, FModelBalanceTotal);
//Calculo o custo médio da última data antes da data de processamento
if FModelQty > 0 then
FLastAvgCost := FModelBalanceTotal/FModelQty
else
FLastAvgCost := 0;
//Abro o query de movimento dos produtos
try
if quMovHistory.Active then
quMovHistory.Close;
quMovHistory.Parameters.ParamByName('IDModel').Value := FieldByName('IDModel').AsInteger;
quMovHistory.Parameters.ParamByName('Date').Value := Trunc(dtStart.Date);
quMovHistory.Open;
quMovHistory.First;
pbTrans.Max := quMovHistory.RecordCount;
pbTrans.Position := 0;
while not quMovHistory.Eof do
begin
//Cria a linha do balance
CreateBalance(FieldByName('IDModel').AsInteger, Trunc(quMovHistory.FieldByName('MovDate').AsDateTime));
FMovQty := 0;
FMovCost := 0;
FNewAvgCost := 0;
//Pego o total de quantidades de entrada, sem compras e importação. Esta quantidade será adicionada à
//quantidade total de estoque, sem afetar o custo médio.
if (quMovHistory.FieldByName('IDInventMovType').AsInteger in [4, 11, 19, 21]) and quMovHistory.FieldByName('UpdateOnHand').AsBoolean then
begin
FMovQty := quMovHistory.FieldByName('Qty').AsFloat;
//Calculo a nova quantidade e valor total do estoque
FModelQty := (FModelQty + FMovQty);
if FModelQty > 0 then
begin
FModelBalanceTotal := FModelBalanceTotal + (FLastAvgCost * FMovQty);
FAvgCostOut := FModelBalanceTotal / FModelQty;
end
else
FModelBalanceTotal := 0;
end;
//Pego a quantidade e o custo total comprado e importado
if (quMovHistory.FieldByName('IDInventMovType').AsInteger in [2, 5]) and quMovHistory.FieldByName('UpdateOnHand').AsBoolean then
begin
FMovQty := quMovHistory.FieldByName('Qty').AsFloat;
FMovCost := Abs(quMovHistory.FieldByName('Cost').AsCurrency);
//Calculo a nova quantidade e valor total do estoque. Se a quantidade em estoque antes das compras
//for negativa, deve ser encontrado o custo médio das compras para achar o valor total de estoque
//com a diferença entre a quantidade anterior e a comprada.
if (FModelQty + FMovQty) > 0 then
begin
if FModelQty < 0 then
FModelBalanceTotal := ((FMovQty * FMovCost) / FMovQty) * (FModelQty + FMovQty)
else
FModelBalanceTotal := FModelBalanceTotal + (FMovQty * FMovCost);
FAvgCostOut := FModelBalanceTotal / (FModelQty + FMovQty);
end
else
begin
FModelBalanceTotal := 0;
FAvgCostOut := 0;
end;
FModelQty := FModelQty + FMovQty;
FNewAvgCost := FAvgCostOut;
end;
//Pego o total de quantidades de saída. Esta quantidade será removida da quantidade total de estoque,
//sem afetar o custo médio, desde que não zere a quantidade.
if (quMovHistory.FieldByName('IDInventMovType').AsInteger in [1, 3, 12, 22]) and not quMovHistory.FieldByName('UpdateOnHand').AsBoolean then
begin
FMovQty := quMovHistory.FieldByName('Qty').AsFloat;
if FModelQty > 0 then
begin
if FMovQty > 0 then
begin
FAvgCostOut := GetModelLastAvgCostNonZero(FieldByName('IDModel').AsInteger, quMovHistory.FieldByName('MovDate').AsDateTime);
if FNewAvgCost = 0 then
FModelBalanceTotal := FModelBalanceTotal + (FMovQty * FAvgCostOut)
else
FModelBalanceTotal := FModelBalanceTotal + (FMovQty * FNewAvgCost);
end
else
begin
FModelBalanceTotal := FModelBalanceTotal + (FMovQty * FAvgCostOut);
if FModelBalanceTotal = 0 then
FAvgCostOut := 0;
end
end
else
begin
if FMovQty > 0 then
begin
FAvgCostOut := GetModelLastAvgCostNonZero(FieldByName('IDModel').AsInteger, quMovHistory.FieldByName('MovDate').AsDateTime);
if FNewAvgCost = 0 then
FModelBalanceTotal := (FMovQty * FAvgCostOut)
else
FModelBalanceTotal := (FMovQty * FNewAvgCost);
end
else
begin
FAvgCostOut := 0;
FModelBalanceTotal := 0;
end
end;
FModelQty := FModelQty + FMovQty;
FNewAvgCost := FAvgCostOut;
if FModelQty = 0 then
FModelBalanceTotal := 0;
end;
UpdateBalance(FieldByName('IDModel').AsInteger,
Trunc(quMovHistory.FieldByName('MovDate').AsDateTime),
FModelQty,
FAvgCostOut,
FModelBalanceTotal);
Application.ProcessMessages;
pbTrans.StepIt;
quMovHistory.Next;
end;
finally
quMovHistory.Close;
end;
pbModel.StepIt;
lbModelTotal.Caption := 'Gerando (' + IntToStr(pbModel.Position) + ' de ' + IntToStr(pbModel.Max) + ')';
Application.ProcessMessages;
Next;
end;
end;
end;
procedure TFrmAvgCostCalculation.GetModelLastBalance(AIDModel: Integer;
var AQty: Double; var AAvgCost, ABalanceTotal: Currency);
begin
with quModelLastBalance do
try
if Active then
Close;
Parameters.ParamByName('IDModel').Value := AIDModel;
Parameters.ParamByName('IDModel1').Value := AIDModel;
Parameters.ParamByName('Date').Value := Trunc(dtStart.Date);
Open;
AQty := FieldByName('Qty').AsFloat;
AAvgCost := FieldByName('AvgCostOut').AsCurrency;
ABalanceTotal := FieldByName('BalanceTotal').AsCurrency;
finally
Close;
end;
end;
procedure TFrmAvgCostCalculation.CreateBalance(IDModel: Integer;
Data: TDateTime);
begin
with cmdInsertBalance do
begin
Parameters.ParamByName('IDModel1').Value := IDModel;
Parameters.ParamByName('Date').Value := Data;
Parameters.ParamByName('IDModel').Value := IDModel;
Parameters.ParamByName('BalanceDate').Value := Data;
Parameters.ParamByName('Qty').Value := 0;
Parameters.ParamByName('AvgCostOut').Value := 0;
Parameters.ParamByName('BalanceTotal').Value := 0;
Execute;
end;
end;
procedure TFrmAvgCostCalculation.UpdateBalance(IDModel: Integer;
Data: TDateTime; AQty: Double; AAvgCost, ABalanceTotal: Currency);
begin
with cmdUpdateBalance do
begin
Parameters.ParamByName('IDModel').Value := IDModel;
Parameters.ParamByName('BalanceDate').Value := Data;
Parameters.ParamByName('Qty').Value := AQty;
Parameters.ParamByName('AvgCostOut').Value := AAvgCost;
Parameters.ParamByName('BalanceTotal').Value := ABalanceTotal;
Execute;
end;
end;
function TFrmAvgCostCalculation.GetModelLastAvgCostNonZero(AIDModel: Integer; ABalanceDate: TDateTime): Currency;
begin
with quModelLastAvgCost do
try
if Active then
Close;
Parameters.ParamByName('IDModel').Value := AIDModel;
Parameters.ParamByName('IDModel1').Value := AIDModel;
Parameters.ParamByName('Date').Value := ABalanceDate;
Open;
Result := FieldByName('AvgCostOut').AsCurrency;
finally
Close;
end;
end;
end.
|
unit DOMQuickRTTI;
interface
uses classes,typinfo,sysutils,QuickRTTI, MSXML2_TLB, Dialogs;
type
{
This file is released under an MIT style license as detailed at opensource.org.
Just don't preteend you wrote it, and leave this comment in the text, and
I'll be happy. Consider it my resume :)
www.bigattichouse.com
www.delphi-programming.com
}
TDOMQuickRTTI = class (TPersistent)
private
fobj:TPersistent;
PList:PPropList;
props:tstringlist;
objs:TStringlist;
ftag,fobjid:String;
fid:integer;
fOutputSchemaInfo: boolean;
protected
function outputXML :String; override;
procedure inputXML (sXML:String); override;
procedure SetValue (Fieldname:String; Value:String);
function GetValue (Fieldname:String):String;
procedure SetObject (o:TPersistent);
function dtType(TypeKind:TTypeKind):string;
public
constructor create;
destructor destroy;override;
function propertyCount:integer;
function indexof(name:String):Integer;
function propertynames(index:integer):String;
function propertyVarTypes(index:integer):String;
function propertyTypes(index:integer):TTypeKind;
property Value[Fieldname:String]:String read GetValue write SetValue;
function outputDOMXML(Doc : IXMLDOMDocument2) :IXMLDOMElement;
procedure inputDOMXML (DomElem:IXMLDOMElement);
procedure CreateSchemas(Schemas : IXMLDOMSchemaCollection);
published
property RTTIObject:TPersistent read fobj write SetObject;
property ObjectID:String read fobjid write fobjid;
property XML:String read outputXML write inputXML;
property TagName:String read ftag write ftag;
property ID:integer read fid write fid;
property OutputSchemaInfo: boolean read fOutputSchemaInfo write fOutputSchemaInfo;
end;
implementation
constructor TQuickRTTI.create;
begin
objs:=tstringlist.create;
props:=tstringlist.create;
ftag:='';
fid:=-1;
fOutputSchemaInfo := False;
end;
destructor TQuickRTTI.destroy;
var tempq:TQuickRTTI;
begin
try
while objs.count>0 do
begin
tempq:=TQuickRTTI(objs.objects[objs.count-1]);
tempq.free;
objs.delete(objs.count-1);
end;
objs.free; //KV
props.free; //KV
finally
inherited destroy;
end;
end;
procedure TQuickRTTI.SetObject (o:TPersistent);
// Modified by KV
var
Count, PropCount : integer;
PTI:PTypeInfo;
PTempList : PPropList;
Tinfo:TPropInfo;
i:integer;
//vin:variant;
tempq:TQuickRTTI;
ttinfo:TTypeinfo;
begin
if not(assigned(props)) then props:=tstringlist.create;
props.clear;
fobj:=o;
PTI:=o.ClassInfo ;
PropCount := GetTypeData(PTI)^.PropCount;
if PropCount = 0 then exit;
GetMem(PTempList, PropCount * SizeOf(Pointer));
try
PList:= PTempList;
Count := GetPropList(PTI,[ tkInteger, tkChar, tkEnumeration, tkFloat,
tkString, tkSet, tkClass, tkMethod, tkWChar, tkLString, tkWString,
tkVariant, tkArray, tkRecord, tkInterface, tkInt64, tkDynArray],
PList);
{getting the list... but I'm pretty much trying to ignore
method calls for this version}
for i:= 0 to Count-1 do
if assigned(Plist[i]) then
begin
Tinfo:= Plist[i]^;
//vin:=GetPropValue(fobj,Tinfo.Name,True);
ttinfo:=tinfo.PropType^^;
if ttinfo.kind=tkClass then
begin
tempq:=TQuickRTTI.create;
tempq.RTTIObject := TPersistent(GetObjectProp(fobj,Tinfo.name));
objs.AddObject (Uppercase(Tinfo.Name),tempq) ;
tempq.TagName := Tinfo.name;
end;
props.addobject(Uppercase(Tinfo.Name), Pointer(PList[i]) );
end;
finally
FreeMem(PTempList, PropCount * SizeOf(Pointer));
end;
end;
function TQuickRTTI.propertyCount:integer;
begin
result:=-1;
if assigned(props) then result:=props.count;
end;
function TQuickRTTI.propertynames(index:integer):String;
begin
result:='';
if assigned(props) then result:=props[index];
end;
function TQuickRTTI.indexof(name:String):Integer;
begin
result := -1; //KV
if assigned(props) then
result:=props.IndexOf (Uppercase(name))
end;
function TQuickRTTI.propertyVarTypes(index:integer):string;
var Tinfo:TPropInfo;
begin
result:='';
if assigned(props) then
begin
Tinfo:=TPropinfo(Pointer(props.objects[index])^);
result:=Tinfo.PropType^.name;
end;
end;
function TQuickRTTI.propertyTypes(index:integer):TTYpeKind;
var Tinfo:TPropInfo;
begin
if assigned(props) then
begin
Tinfo:=TPropinfo(Pointer(props.objects[index])^);
result:=Tinfo.PropType^.kind;
end else
Raise Exception.Create('Internal Error'); //KV
end;
procedure TQuickRTTI.SetValue (Fieldname:String;Value:String);
var vin:Variant; fname:Shortstring;
begin
fname:=fieldname;
Vin:=Value;
SetPropValue(fobj,fName,Vin);
end;
function TQuickRTTI.GetValue (Fieldname:String):String;
var v,vin:Variant;
fname,sname,ename:Shortstring;
ppos,idx:integer;q:TQuickRTTi;
begin
fname:=fieldname;
ppos:=pos('.',fname);
if ppos>0 then begin
sname:= copy(fname,1,ppos-1);
ename:= copy(fname,ppos+1,length(fname)-ppos-1)
end;
if ppos>1 then
begin
{Property.anotherproperty}
idx:=objs.indexof(sname);
if idx>0 then
begin
q:=TQuickRTTI(objs.objects[idx]);
result:=q.Value[ename];
end;
end
else
vin:=GetPropValue(fobj,fName,True);
Varcast(v,vin,varString);
result:=vin;
end;
function TQuickRTTI.outputXML(Doc: IXMLDOMDocument2): IXMLDOMElement;
{
Use the MSXML parser to create the object representation as an IXMLDomElement.
Then use the IXMLDomElement.xml property to get the XML object representation.
The RTTI property OutputSchemaInfo determines whether Namespace schema info is included.
}
var
i,k:integer;
typname:ttypekind;
q:TQuickRTTI;
s:TStrings;
C:TCollection;
DomNode, DomNode1 : IXMLDOMNode;
begin
Result := Doc.createElement(TagName);
Result.setAttribute('TYPE',fobj.ClassName);
if OutputSchemaInfo then
Result.setAttribute('xmlns','x-schema:'+'delphi.'+RTTIObject.ClassName+'.'+TagName+'.xml');
if fid>-1 then
Result.setAttribute('ID',inttostr(fid));
if fobjid<>'' then
Result.setAttribute('ID',fobjid);
// The above line allows us to have collections of items.. like tlist
for i:= 0 to props.count-1 do
begin
typname := self.propertyTypes (i);
if typname<>tkclass then begin
DomNode := Doc.CreateNode(NODE_ELEMENT, props[i], '');
DomNode1 := Doc.CreateNode(NODE_TEXT, '', '');
DomNode1.nodeValue := GetValue(propertynames(i));
DomNode.appendChild(DomNode1);
Result.appendChild(DomNode);
end else begin
q:= TQuickRTTI(objs.objects[objs.indexof(propertynames(i))]);
q.OutputSchemaInfo := OutputSchemaInfo;
Result.appendChild(q.outputDomXML(Doc));
end;
end;
if RTTIObject is TStrings then begin
s:=TStrings(self.rttiobject);
for k:= 0 to s.Count-1 do begin
DomNode := Doc.CreateNode(NODE_ELEMENT, 'LINE', '');
(DomNode as IXMLDOMElement).setAttribute('INDEX',inttostr(k));
DomNode1 := Doc.CreateNode(NODE_TEXT, '', '');
DomNode1.nodeValue := s[k];
DomNode.appendChild(DomNode1);
Result.appendChild(DomNode);
end;
end;
if RTTIObject is TCollection then begin
c:=Tcollection(self.rttiobject);
q:=TQuickRTTI.create;
q.OutputSchemaInfo := OutputSchemaInfo;
for k:= 0 to c.Count-1 do begin
{create and output any internal items}
if C.Items[k] is TPersistent then begin
q.rttiobject:=TPersistent(C.Items[k]) ;
q.tagname:='ITEM' ;
Result.appendChild(q.outputDomXML(Doc));
end;
end;
q.free;
end;
end;
procedure TQuickRTTI.inputXML(DomElem: IXMLDOMElement);
{
The equivalent to inputXML using the XMLparser. Can optionally validate
the XML file using the Schema information created by CreateSchemas.
See the quicktest example for how to do this.
}
var
q:TQuickRTTI;
Node : IXMLDomNode;
Index, i : integer;
begin
q:=TQuickRTTi.create;
if RTTIObject is TStrings then TStrings(RTTIObject).clear;
if RTTIObject is TCollection then TCollection(self.rttiobject).Clear;
for i := 0 to DomElem.ChildNodes.length - 1 do begin
Node := DomElem.ChildNodes.item[i];
if Node.NodeType = NODE_ELEMENT then begin
if (RTTIObject is TStrings) and (Node.NodeName = 'LINE') then
TStrings(RTTIObject).Add(Node.Text)
else if (RTTIObject is TCollection) and (Node.NodeName = 'ITEM') then begin
q.RTTIObject := TCollection(self.rttiobject).Add;
q.inputDOMXML(Node as IXMLDOMElement);
end else begin
Index := IndexOf(Node.nodeName);
if Index < 0 then continue;
if propertyTypes(Index) = tkClass then
TQuickRtti(objs.objects[objs.indexof(props[Index])]).inputDomXML(Node as IXMLDOMElement)
else
SetValue(props[Index],Node.Text);
end;
end;
end;
q.free;
end;
function GetEnumNames(PTD : PTypeData): string;
var
i : integer;
P: ^ShortString;
begin
P := @PTD^.NameList;
for i := PTD.MinValue to PTD.MaxValue do begin
Result := Result + P^;
if i < PTD.MaxValue then begin
Inc(Integer(P), Length(P^) + 1);
Result := Result + '';
end;
end;
end;
procedure TQuickRTTI.CreateSchemas(Schemas : IXMLDOMSchemaCollection);
{
Create Schema information. One Schema is created for each class and added to
the IXMLDOMSchemaCollection. This Scema collection can be used to validate
XML input. See the quicktest for an example.
}
var
i, Count:integer;
typname:ttypekind;
q:TQuickRTTI;
C:TCollection;
Doc : IXMLDOMDocument2;
Schema, Root, DomNode, DomNode1 : IXMLDOMElement;
SS : string;
begin
Doc := CoDOMDocument.Create;
Doc.async := False;
Schema := Doc.createElement('Schema');
Schema.SetAttribute('xmlns','urn:schemas-microsoft-com:xml-data');
Schema.SetAttribute('xmlns:dt','urn:schemas-microsoft-com:datatypes');
Doc.appendChild(Schema);
DomNode := Doc.createElement('AttributeType');
DomNode.SetAttribute('name', 'TYPE');
//DomNode.SetAttribute('dt:type', 'enumeration');
//DomNode.SetAttribute('dt:values', fobj.ClassName);
DomNode.SetAttribute('dt:type', 'string');
Schema.appendChild(DomNode);
if RTTIObject is TStrings then begin
DomNode := Doc.createElement('AttributeType');
DomNode.SetAttribute('name', 'INDEX');
DomNode.SetAttribute('dt:type', 'int');
Schema.appendChild(DomNode);
DomNode := Doc.createElement('ElementType');
DomNode.SetAttribute('name', 'LINE');
DomNode.SetAttribute('dt:type', 'string');
DomNode1 := Doc.createElement('attribute');
DomNode1.SetAttribute('type', 'INDEX');
DomNode.appendChild(DomNode1);
Schema.appendChild(DomNode);
end;
Root := Doc.createElement('ElementType');
Root.SetAttribute('name', TagName);
DomNode := Doc.createElement('attribute');
DomNode.SetAttribute('type', 'TYPE');
Root.appendChild(DomNode);
if RTTIObject is TStrings then begin
DomNode := Doc.createElement('element');
DomNode.SetAttribute('type', 'LINE');
DomNode.SetAttribute('maxOccurs', '*');
end;
if RTTIObject is TCollection then begin
c:=Tcollection(self.rttiobject);
q:=TQuickRTTI.create;
try
Count := c.Count;
if Count = 0 then
// temprorarily add an object
c.Add;
q.rttiobject:=TPersistent(C.Items[0]) ;
q.TagName := 'ITEM';
q.CreateSchemas(Schemas);
Schema.SetAttribute('xmlns:'+q.RTTIObject.ClassName+'ITEM',
'delphi.'+q.RTTIObject.ClassName+'.'+'ITEM');
DomNode := Doc.createElement('element');
DomNode.SetAttribute('type', q.RTTIObject.ClassName+'ITEM'+':'+'ITEM');
Root.appendChild(DomNode);
if Count = 0 then c.Clear;
finally
q.free;
end;
end;
for i:= 0 to props.count-1 do begin
typname := self.propertyTypes (i);
if typname<>tkclass then begin
DomNode := Doc.createElement('ElementType');
DomNode.SetAttribute('name', propertynames(i));
DomNode.SetAttribute('dt:type', dtType(typname));
if typname = tkEnumeration then begin
DomNode.SetAttribute('dt:values', GetEnumNames(GetTypeData(PPropInfo(props[i])^.PropType^)));
end;
Schema.appendChild(DomNode);
DomNode := Doc.createElement('element');
DomNode.SetAttribute('type', propertynames(i));
Root.appendChild(DomNode);
end else begin
q:= TQuickRTTI(objs.objects[objs.indexof(propertynames(i))]);
q.CreateSchemas(Schemas);
Schema.SetAttribute('xmlns:'+q.RTTIObject.ClassName+propertynames(i),
'delphi.'+q.RTTIObject.ClassName+'.'+propertynames(i));
DomNode := Doc.createElement('element');
DomNode.SetAttribute('type', q.RTTIObject.ClassName+propertynames(i)+':'+propertynames(i));
Root.appendChild(DomNode);
end;
end;
Schema.AppendChild(Root);
SS := Doc.xml;
Doc.Save(Doc); //!!! to avoid a very mysterious bug in the following statement
Schemas.add('x-schema:'+'delphi.'+RTTIObject.ClassName+'.'+TagName+'.xml', Doc);
end;
function TQuickRTTI.dtType(TypeKind: TTypeKind): string;
begin
Result := '';
Case TypeKind of
tkInteger : Result := 'int';
tkChar : Result := 'char';
tkEnumeration : Result := 'enumeration';
tkFloat : Result := 'float';
tkString : Result := 'string';
tkSet : Result := 'string';
tkClass : Result := 'string';
tkMethod : Result := 'string';
tkWChar : Result := 'char';
tkLString : Result := 'string';
tkWString : Result := 'string';
tkVariant : Result := 'string';
tkArray : Result := 'string';
tkRecord : Result := 'string';
tkInterface : Result := 'string';
tkInt64 : Result := 'int';
tkDynArray : Result := 'string';
end;
end;
end.
|
UNIT UEarthquake;
INTERFACE
USES UDate; {* make functions and procedures from UDate available in this scope *}
{* exposed functions and procedures *}
{* Inserts new earthquake to earthquakes list sorted by date (DESC)
*
* @param latitude REAL Latitude value of geopoint
* @param longitude REAL Longitude value of geopoint
* @param strength REAL Strength value of earthquake (richter magnitude scale)
* @param city STRING City near geopoint of earthquake
* @param date Date Date when earthquake occured.
*}
PROCEDURE AddEarthquake(latitude, longitude, strength: REAL; city: STRING; date: Date);
{* Returns total number of earthquakes in list
*
* @return INTEGER Number of earthquakes
*}
FUNCTION TotalNumberOfEarthquakes: INTEGER;
{* Returns Number of earthquakes between two given dates
*
* @paramIn fromDate Date (inclusive) date beginning of timespan
* @paramIn toDate Date (inclusive) date ending of timespan
* @return INTEGER Number of earthquakes found
*}
FUNCTION NumberOfEarthquakesInTimespan(fromDate, toDate: Date): INTEGER;
{* Gets the data of earthquake with biggest strength in given region
*
* @paramIn latitudeIn1 REAL Latitude value of first geopoint
* @paramIn longitudeIn1 REAL Longitude value of first geopoint
* @paramIn latitudeIn2 REAL Latitude value of second geopoint
* @paramIn longitudeIn2 REAL Longitude value of second geopoint
* @paramOut latitudeOut REAL Latitude value of found earthquake
* @paramOut longitudeOut REAL Longitude value of found earthquake
* @paramOut strength REAL Strength value of found earthquake
* @paramOut city STRING City of found earthquake
* @paramOut day INTEGER day of found earthquake (part of date)
* @paramOut month INTEGER month of found earthquake (part of date)
* @paramOut year INTEGER year of found earthquake (part of date )
*}
PROCEDURE GetStrongestEarthquakeInRegion(latitudeIn1, longitudeIn1, latitudeIn2, longitudeIn2: REAL;
VAR latitudeOut, longitudeOut, strength: REAL; VAR city: STRING; VAR day, month, year: INTEGER);
{* Gets average earthquake strength in region
*
* @paramIn latitudeIn1 REAL Latitude value of first geopoint
* @paramIn longitudeIn1 REAL Longitude value of first geopoint
* @paramIn latitudeIn2 REAL Latitude value of second geopoint
* @paramIn longitudeIn2 REAL Longitude value of second geopoint
* @return REAL Average Strength value
*}
FUNCTION AverageEarthquakeStrengthInRegion(latitudeIn1, longitudeIn1, latitudeIn2, longitudeIn2: REAL): REAL;
{* Displays earthquakes list of entries close to city
*
* @paramIn city STRING City value to be searched for in earthquakes
*}
PROCEDURE PrintEarthquakesCloseToCity(city: STRING);
{* Displays earthquakes list of entries with strength bigger or equal to strength
*
* @paramIn strength REAL Strength value to be searched for in earthquakes
*}
PROCEDURE PrintStrongCityEarthquakes(strength: REAL);
{* Disposes the city list and all it's earthquakes and re-initializes the list anchor *}
PROCEDURE Reset;
{* Deletes earthquake list entries that occured before the given date and returns the number of deleted elements
*
* @paramIn beforeDate Date (inclusive) date which is after the dates
* of entries that should be deleted.
* @paramOut deletedElementCount INTEGER Number of elements that were deleted
*}
PROCEDURE DeleteAllEarthquakesBeforeDate(beforeDate: Date; VAR deletedElementCount: INTEGER);
{* Deletes earthquake list entries that match the given city and returns the number of deleted elements
*
* @paramIn city STRING City value of entries that should be deleted
* @paramOut deletedElementCount INTEGER Number of elements that were deleted
*}
PROCEDURE DeleteAllEarthquakesCloseToCity(city: STRING; VAR deletedElementCount: INTEGER);
{* Displays all earthquake list entries grouped by their cities *}
PROCEDURE PrintEarthquakesGroupedByCity;
IMPLEMENTATION
TYPE
Earthquake = ^EarthquakeRec; {* Earthquake pointer *}
EarthquakeRec = RECORD
city: STRING;
strength, latitude, longitude: REAL;
date: Date;
left, right: Earthquake;
END;
EarthquakeList = Earthquake;
City = ^CityRec; {* City pointer *}
CityRec = RECORD
name: STRING;
prev, next: City;
earthquakes: EarthquakeList; {* Earthquake pointer *}
END;
CityList = City;
VAR
list: CityList; {* global list of city entries *}
{* Initialize city list *}
PROCEDURE InitCityList;
VAR
cityEntry: City;
BEGIN
{* create anchor element *}
New(cityEntry);
cityEntry^.next := cityEntry;
cityEntry^.prev := cityEntry;
list := cityEntry;
END;
{* returns the pointer of the searched city entry or the anchor if the searched entry can't be found *}
FUNCTION GetCityPtrOrAnchor(name: STRING): City;
VAR
temp: City;
BEGIN
temp := list^.next;
WHILE (temp <> list) AND (temp^.name <> name) DO
temp := temp^.next;
GetCityPtrOrAnchor := temp;
END;
PROCEDURE AddEarthquakeToTree(earthquakeEntry: Earthquake; cityEntry: City);
VAR
earthquakeTemp, parent: Earthquake;
BEGIN
earthquakeTemp := cityEntry^.earthquakes;
parent := earthquakeTemp;
WHILE earthquakeTemp <> NIL DO BEGIN
parent := earthquakeTemp;
IF LiesBefore(earthquakeTemp^.date, earthquakeEntry^.date) THEN
earthquakeTemp := earthquakeTemp^.right
ELSE earthquakeTemp := earthquakeTemp^.left;
END;
IF parent = NIL THEN earthquakeTemp := earthquakeEntry
ELSE IF LiesBefore(parent^.date, earthquakeEntry^.date) THEN parent^.right := earthquakeEntry
ELSE parent^.left := earthquakeEntry;
END;
PROCEDURE AddEarthquake(latitude, longitude, strength: REAL; city: STRING; date: Date);
VAR
earthquakeEntry: Earthquake;
cityEntry: City;
BEGIN
{* fill earthquakeEntry properties with parameter values *}
New(earthquakeEntry);
earthquakeEntry^.date := date;
earthquakeEntry^.latitude := latitude;
earthquakeEntry^.longitude := longitude;
earthquakeEntry^.strength := strength;
earthquakeEntry^.city := city;
earthquakeEntry^.left := NIL;
earthquakeEntry^.right := NIL;
cityEntry := GetCityPtrOrAnchor(city);
IF cityEntry <> list THEN
BEGIN
{* add earthquake to city list *}
AddEarthquakeToTree(earthquakeEntry, cityEntry);
END ELSE
BEGIN
{* create new city entry with the earthquake *}
New(cityEntry);
cityEntry^.name := city;
cityEntry^.earthquakes := earthquakeEntry;
cityEntry^.next := list;
cityEntry^.prev := list^.prev;
list^.prev^.next := cityEntry;
list^.prev := cityEntry;
END;
END;
FUNCTION CalculateNumberOfEarthquakesInTree(tree: EarthquakeList): INTEGER;
VAR
count: INTEGER;
BEGIN
count := 0;
IF tree <> NIL THEN BEGIN
count := 1;
IF tree^.right <> NIL THEN count := count + CalculateNumberOfEarthquakesInTree(tree^.right);
IF tree^.left <> NIL THEN count := count + CalculateNumberOfEarthquakesInTree(tree^.left);
END;
CalculateNumberOfEarthquakesInTree := count;
END;
FUNCTION TotalNumberOfEarthquakes: INTEGER;
VAR
tempCity: City;
count: INTEGER;
BEGIN
tempCity := list^.next;
count := 0;
{* iterate over list and the earthquake lists of the city entries*}
WHILE tempCity <> list DO BEGIN
IF tempCity^.earthquakes <> NIL THEN
BEGIN
count := count + CalculateNumberOfEarthquakesInTree(tempCity^.earthquakes);
END;
tempCity := tempCity^.next;
END;
TotalNumberOfEarthquakes := count;
END;
FUNCTION CalculateNumberOfEarthquakesInTimespan(fromDate, toDate: Date; tree: Earthquake): INTEGER;
VAR
count: INTEGER;
BEGIN
count := 0;
IF (tree <> NIL) AND LiesBefore(fromDate, tree^.date) AND LiesBefore(tree^.date, toDate) THEN BEGIN
count := count + 1;
END;
IF tree^.right <> NIL THEN count := count + CalculateNumberOfEarthquakesInTimespan(fromDate, toDate, tree^.right);
IF tree^.left <> NIL THEN count := count + CalculateNumberOfEarthquakesInTimespan(fromDate, toDate, tree^.left);
CalculateNumberOfEarthquakesInTimespan := count;
END;
FUNCTION NumberOfEarthquakesInTimespan(fromDate, toDate: Date): INTEGER;
VAR
count: INTEGER;
tempDate: Date;
tempCity: City;
BEGIN
{* Swap dates if toDate is earlier than fromDate *}
IF not LiesBefore(fromDate, toDate) THEN {* exposed by UDate *}
BEGIN
tempDate := toDate;
toDate := fromDate;
fromDate := tempDate;
END;
count := 0;
tempCity := list^.next;
{* start iterating over all earthquakes in list *}
WHILE tempCity <> list DO BEGIN
count := count + CalculateNumberOfEarthquakesInTimespan(fromDate, toDate, tempCity^.earthquakes);
tempCity := tempCity^.next;
END;
NumberOfEarthquakesInTimespan := count
END;
// {* Swaps two REAL values and returns them *}
PROCEDURE SwapValues(VAR val1, val2: REAL);
VAR
temp: REAL;
BEGIN
temp := val1;
val1 := val2;
val2 := temp;
END;
// {* returns true if geopoint (checkLatitude and checkLongitude) is in region *}
FUNCTION GeopointInRegion(latitude1, longitude1, latitude2, longitude2, checkLatitude, checkLongitude: REAL): BOOLEAN;
BEGIN
GeopointInRegion := false;
IF latitude1 > latitude2 THEN
BEGIN
{* swap geopoints so check conditions will work *}
SwapValues(latitude1, latitude2);
SwapValues(longitude1, longitude2);
END;
{* check if given geopoint is in region.
* The region can be seen as a rectangle in a coordinate system
*}
IF (checkLatitude >= latitude1) and (checkLatitude <= latitude2) THEN
IF (checkLongitude >= longitude1) and (checkLongitude <= longitude2) THEN
GeopointInRegion := true;
END;
PROCEDURE FindStrongestEarthquakeInRegion(latitudeIn1, longitudeIn1, latitudeIn2, longitudeIn2: REAL; tree: Earthquake; VAR strongestEarthquake: Earthquake);
BEGIN
IF (tree <> NIL) AND GeopointInRegion(latitudeIn1, longitudeIn1, latitudeIn2, longitudeIn2,
tree^.latitude, tree^.longitude) AND (tree^.strength > strongestEarthquake^.strength) THEN
strongestEarthquake^ := tree^;
IF tree^.right <> NIL THEN FindStrongestEarthquakeInRegion(latitudeIn1, longitudeIn1, latitudeIn2, longitudeIn2, tree^.right, strongestEarthquake);
IF tree^.right <> NIL THEN FindStrongestEarthquakeInRegion(latitudeIn1, longitudeIn1, latitudeIn2, longitudeIn2, tree^.right, strongestEarthquake);
END;
PROCEDURE GetStrongestEarthquakeInRegion(latitudeIn1, longitudeIn1, latitudeIn2, longitudeIn2: REAL;
VAR latitudeOut, longitudeOut, strength: REAL; VAR city: STRING; VAR day, month, year: INTEGER);
VAR
strongestEarthquake: Earthquake;
tempCity: City;
BEGIN
New(strongestEarthquake); {* dynamically allocate memory for strongestEarthquake *}
strongestEarthquake^.strength := 0; {* initial value for the searched strength *}
tempCity := list^.next;
WHILE tempCity <> list DO BEGIN
FindStrongestEarthquakeInRegion(latitudeIn1, longitudeIn1, latitudeIn2, longitudeIn2, tempCity^.earthquakes, strongestEarthquake);
tempCity := tempCity^.next;
END;
{* Convert the found earthquake entry to primitive datatypes to return them *}
latitudeOut := strongestEarthquake^.latitude;
longitudeOut := strongestEarthquake^.longitude;
strength := strongestEarthquake^.strength;
city := strongestEarthquake^.city;
day := strongestEarthquake^.date.day;
month := strongestEarthquake^.date.month;
year := strongestEarthquake^.date.year;
{* dispose strongestEarthquake since it's not used anymore *}
Dispose(strongestEarthquake);
END;
PROCEDURE GetTotalEarthquakeStrengthAndNumberInRegion(latitudeIn1, longitudeIn1, latitudeIn2, longitudeIn2: REAL; tree: Earthquake; VAR count: INTEGER; VAR strength: REAL);
BEGIN
IF (tree <> NIL) AND GeopointInRegion(latitudeIn1, longitudeIn1, latitudeIn2, longitudeIn2,
tree^.latitude, tree^.longitude) THEN BEGIN
Inc(count);
strength := strength + tree^.strength;
END;
IF tree^.right <> NIL THEN GetTotalEarthquakeStrengthAndNumberInRegion(latitudeIn1, longitudeIn1, latitudeIn2, longitudeIn2, tree^.right, count, strength);
IF tree^.right <> NIL THEN GetTotalEarthquakeStrengthAndNumberInRegion(latitudeIn1, longitudeIn1, latitudeIn2, longitudeIn2, tree^.right, count, strength);
END;
FUNCTION AverageEarthquakeStrengthInRegion(latitudeIn1, longitudeIn1, latitudeIn2, longitudeIn2: REAL): REAL;
VAR
strength: REAL;
count: INTEGER;
tempCity: City;
BEGIN
strength := 0;
count := 0;
tempCity := list^.next;
{* iterate all city entries *}
WHILE tempCity <> list DO BEGIN
GetTotalEarthquakeStrengthAndNumberInRegion(latitudeIn1, longitudeIn1, latitudeIn2, longitudeIn2, tempCity^.earthquakes, count, strength);
tempCity := tempCity^.next;
END;
IF count > 0 THEN
AverageEarthquakeStrengthInRegion := strength / count
ELSE AverageEarthquakeStrengthInRegion := 0; {* return 0 in case no earthquakes were found in region *}
END;
PROCEDURE DisplayEarthquake(earthquake: Earthquake);
BEGIN
WriteLn();
Write('DATE: ');
DisplayDate(earthquake^.date);
WriteLn();
WriteLn('STRENGTH: ', earthquake^.strength);
WriteLn('LATITUDE: ', earthquake^.latitude);
WriteLn('LONGITUDE: ', earthquake^.longitude);
WriteLn('CITY: ', earthquake^.city);
WriteLn();
END;
PROCEDURE FindAndPrintEarthquakesCloseToCity(tree: Earthquake);
BEGIN
IF tree <> NIL THEN BEGIN
FindAndPrintEarthquakesCloseToCity(tree^.right);
DisplayEarthquake(tree);
FindAndPrintEarthquakesCloseToCity(tree^.left);
END;
END;
PROCEDURE PrintEarthquakesCloseToCity(city: STRING);
VAR
tempCity: City;
BEGIN
WriteLn('-----------------------------------------------------');
WriteLn();
WriteLn('Earthquakes close to ' , city);
WriteLn();
{* get the city with the name from the parameter *}
tempCity := GetCityPtrOrAnchor(city);
IF tempCity <> list THEN
BEGIN
FindAndPrintEarthquakesCloseToCity(tempCity^.earthquakes);
END ELSE WriteLn('No entries found..');
WriteLn();
WriteLn('-----------------------------------------------------');
END;
PROCEDURE PrintStrongCityEarthquakesRecursive(tree: Earthquake; strength: REAL);
BEGIN
IF tree <> NIL THEN BEGIN
PrintStrongCityEarthquakesRecursive(tree^.right, strength);
IF tree^.strength >= strength THEN BEGIN
{* print earthquake entry *}
Write('Date: ');
DisplayDate(tree^.date);
WriteLn(' | CITY: ', tree^.city);
END;
PrintStrongCityEarthquakesRecursive(tree^.left, strength);
END;
END;
PROCEDURE PrintStrongCityEarthquakes(strength: REAL);
VAR
tempCity: City;
BEGIN
WriteLn('-----------------------------------------------------');
WriteLn();
WriteLn('Earthquakes with strength >= ' , strength);
WriteLn();
{* copy list to tempEarthquake, so the list pointer won't be moved away from the first element *}
tempCity := list^.next;
WHILE tempCity <> list DO BEGIN
PrintStrongCityEarthquakesRecursive(tempCity^.earthquakes, strength);
tempCity := tempCity^.next;
END;
WriteLn();
WriteLn('-----------------------------------------------------');
END;
PROCEDURE DisposeEarthquakeTree(tree: Earthquake; VAR count: INTEGER);
BEGIN
IF tree <> NIL THEN BEGIN
Inc(count);
DisposeEarthquakeTree(tree^.left, count);
DisposeEarthquakeTree(tree^.right, count);
Dispose(tree);
END;
END;
FUNCTION FindEarthquakeTreeBeforeDate(beforeDate: Date; tree: Earthquake): INTEGER;
VAR
found: BOOLEAN;
deletedElementCount: INTEGER;
BEGIN
deletedElementCount := 0;
found := false;
WHILE (tree <> NIL) AND NOT found DO BEGIN
IF LiesBefore(tree^.date, beforeDate) THEN BEGIN
found := true;
DisposeEarthquakeTree(tree, deletedElementCount)
END ELSE tree := tree^.left;
END;
IF (tree = NIL) and not found THEN WriteLn('!!!!!!!!! oh shit !!!!!!!!!!');
FindEarthquakeTreeBeforeDate := deletedElementCount;
END;
// Balancing should work before this really makes sense
PROCEDURE DeleteAllEarthquakesBeforeDate(beforeDate: Date; VAR deletedElementCount: INTEGER);
// VAR
// tempCity: City;
// tempEarthquake, previousTemp: Earthquake;
BEGIN
// tempCity := list^.next;
// deletedElementCount := 0;
// WHILE tempCity <> list DO BEGIN
// // tempEarthquake := tempCity^.earthquakes;
// {* represents a "old" or previous copy of temp *}
// deletedElementCount := deletedElementCount + FindEarthquakeTreeBeforeDate(beforeDate, tempCity^.earthquakes);
// // tempEarthquake := FindEarthquakeTreeBeforeDate(beforeDate, tempCity^.earthquakes);
// // WriteLn('asdf: ', tempEarthquake^.city, ' | ', tempEarthquake^.strength);
// // DisposeEarthquakeTree(tempEarthquake, deletedElementCount);
// // previousTemp := tempEarthquake;
// tempCity := tempCity^.next;
// END;
END;
PROCEDURE DeleteAllEarthquakesCloseToCity(city: STRING; VAR deletedElementCount: INTEGER);
VAR
tempCity, nextCity, prevCity: City;
BEGIN
deletedElementCount := 0;
tempCity := GetCityPtrOrAnchor(city);
IF tempCity <> list THEN BEGIN
{* delete City with all earthquakes *}
DisposeEarthquakeTree(tempCity^.earthquakes, deletedElementCount);
nextCity := tempCity^.next;
prevCity := tempCity^.prev;
prevCity^.next := nextCity;
nextCity^.prev := prevCity;
Dispose(tempCity);
END;
END;
PROCEDURE DisplayList(tree: Earthquake);
BEGIN
IF tree^.right <> NIL THEN DisplayList(tree^.right);
IF tree <> NIL THEN BEGIN
WriteLn();
Write('DATE: ');
DisplayDate(tree^.date);
WriteLn();
WriteLn('STRENGTH: ', tree^.strength);
WriteLn('LATITUDE: ', tree^.latitude);
WriteLn('LONGITUDE: ', tree^.longitude);
WriteLn('CITY: ', tree^.city);
WriteLn();
END;
IF tree^.left <> NIL THEN DisplayList(tree^.left);
END;
PROCEDURE PrintEarthquakesGroupedByCity;
VAR
tempCity: City;
BEGIN
{* Check if list is empty *}
IF list^.next <> list THEN BEGIN
tempCity := list^.next;
{* iterate all list entries and print it's earthquakes *}
WriteLn;
WriteLn('----------------------------------');
WHILE tempCity <> list DO BEGIN
WriteLn;
WriteLn('-- ', tempCity^.name, ' --');
IF tempCity^.earthquakes = NIL THEN
WriteLn('No entries found..')
ELSE DisplayList(tempCity^.earthquakes);
tempCity := tempCity^.next;
END;
END ELSE WriteLn('No entries found..');
WriteLn('----------------------------------');
WriteLn;
END;
// PROCEDURE AddEarthquakeToArray(tree: Earthquake; VAR arr: EarthquakeArray; VAR count: INTEGER);
// BEGIN
// IF tree <> NIL THEN BEGIN
// IF (tree <> NIL) AND (tree^.left <> NIL) THEN AddEarthquakeToArray(tree^.left, arr, count);
// Inc(count);
// SetLength(arr, count);
// arr[count - 1] := tree;
// IF (tree <> NIL) AND (tree^.right <> NIL) THEN AddEarthquakeToArray(tree^.right, arr, count);
// END;
// END;
// PROCEDURE BalanceTree(VAR arr: EarthquakeArray; VAR arrCount: INTEGER; startIndex: INTEGER; iteration: INTEGER; tree: Earthquake; VAR direction: Direction);
// VAR
// idx: INTEGER;
// right: INTEGER;
// BEGIN
// IF direction = left THEN BEGIN
// idx := arrCount / iteration;
// END;
// IF direction = right THEN BEGIN
// idx := arrCount / iteration +
// END;
// IF
// left := arrCount - startIndex div 2;
// right := arrCount * (1 div 4) + startIndex;
// tree^.left := arr[left];
// tree^.right := arr[right];
// FOR i := 0 TO middle DO BEGIN
// END;
// END;
// PROCEDURE BalanceTree(VAR arr: EarthquakeArray; VAR arrCount: INTEGER; startIndex: INTEGER; endIndex: INTEGER; iteration: INTEGER; tree: Earthquake; VAR direction: Direction);
// VAR
// idx: INTEGER;
// right: INTEGER;
// BEGIN
// IF direction = left THEN BEGIN
// idx := endIndex - startIndex;
// END;
// IF direction = right THEN BEGIN
// idx := arrCount / iteration +
// END;
// IF
// left := arrCount - startIndex div 2;
// right := arrCount * (1 div 4) + startIndex;
// tree^.left := arr[left];
// tree^.right := arr[right];
// FOR i := 0 TO middle DO BEGIN
// END;
// END;
// PROCEDURE BalanceTreeAndBuildTree(tree: Earthquake);
// VAR
// arr: EarthquakeArray;
// count, i: INTEGER;
// BEGIN
// count := 0;
// SetLength(arr, count);
// AddEarthquakeToArray(tree, arr, count);
// // ...
// END;
// PROCEDURE BalanceTrees;
// VAR
// tempCity: City;
// BEGIN
// tempCity := list^.next;
// WHILE tempCity <> list DO BEGIN
// IF tempCity^.earthquakes <> NIL THEN
// BalanceTreeAndBuildTree(tempCity^.earthquakes);
// tempCity := tempCity^.next;
// END;
// END;
PROCEDURE Reset;
VAR
tempCity, nextCity: City;
deletedElementCount: INTEGER;
BEGIN
deletedElementCount := 0;
tempCity := list^.next;
WHILE tempCity <> list DO BEGIN
{* Dispose all pointers to earthquake entries *}
DisposeEarthquakeTree(tempCity^.earthquakes, deletedElementCount);
{* Dispose all pointers to city entries *}
nextCity := tempCity^.next;
Dispose(tempCity);
tempCity := nextCity;
END;
Dispose(list); {* Dispose anchor *}
InitCityList; {* Re-initialize list anchor for upcoming operations *}
END;
BEGIN
{* Init on first run of Unit *}
InitCityList;
END. |
unit Stud_Vacation_Ctrl_MainForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, ExtCtrls, cxMaskEdit, cxDropDownEdit,
cxCalendar, cxTextEdit, cxButtonEdit, cxContainer, cxEdit, cxLabel,
cxControls, cxGroupBox, StdCtrls, cxButtons, gr_uCommonConsts,
PackageLoad, DB, FIBDatabase, pFIBDatabase, FIBDataSet, pFIBDataSet, IBase,
ZTypes, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, GlobalSpr,
Stud_Vacation_Ctrl_DM, gr_uMessage, ActnList, ZProc, uCommonSp,
Unit_NumericConsts, Dates, gr_uCommonLoader, gr_uCommonProc, cxGraphics,
dxStatusBar,Registry;
type
TFCtrlStudVacation = class(TForm)
BoxMan: TcxGroupBox;
LabelMan: TcxLabel;
EditMan: TcxButtonEdit;
BoxDates: TcxGroupBox;
DateBegLabel: TcxLabel;
EditDateBeg: TcxDateEdit;
EditDateEnd: TcxDateEdit;
DateEndLabel: TcxLabel;
EditPrikaz: TcxButtonEdit;
LabelPrikaz: TcxLabel;
YesBtn: TcxButton;
Actions: TActionList;
ActionYes: TAction;
ActionEnter: TAction;
CancelBtn: TcxButton;
dxStatusBar1: TdxStatusBar;
ActionF9: TAction;
procedure YesBtnClick(Sender: TObject);
procedure ActionEnterExecute(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure CancelBtnClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ActionF9Execute(Sender: TObject);
procedure RestoreFromBuffer(Sender:TObject);
private
PRes:Variant;
PLanguageIndex:byte;
Pcfs:TZControlFormStyle;
PIdStud:int64;
PIdStudVac:integer;
public
constructor Create(AOwner:TComponent);reintroduce;
function PrepareData(Db_Handle:TISC_DB_HANDLE;fs:TZControlFormStyle;Id:int64):boolean;
function DeleteRecord(Db_Handle:TISC_DB_HANDLE;Id:integer):boolean;
property Res:Variant read PRes;
end;
var
FCtrlStudVacation: TFCtrlStudVacation;
function ViewStudVacationCtrl(AParameter:TObject):Variant;stdcall;
exports ViewStudVacationCtrl;
implementation
uses FIBQuery;
{$R *.dfm}
//******************************************************************************
function ViewStudVacationCtrl(AParameter:TObject):Variant;stdcall;
var Form:TFCtrlStudVacation;
begin
Form:=TFCtrlStudVacation.Create(TgrCtrlSimpleParam(AParameter).Owner);
if TgrCtrlSimpleParam(AParameter).fs=zcfsDelete then
result:=Form.DeleteRecord(TgrCtrlSimpleParam(AParameter).DB_Handle,
TgrCtrlSimpleParam(AParameter).Id)
else
begin
result := Form.PrepareData(TgrCtrlSimpleParam(AParameter).DB_Handle,
TgrCtrlSimpleParam(AParameter).fs,
TgrCtrlSimpleParam(AParameter).Id);
if Result<>False then
begin
Result := Form.ShowModal;
if Result=mrYes then Result:=Form.Res
else Result := NULL;
end
else Result:=NULL;
end;
Form.Destroy;
end;
//******************************************************************************
constructor TFCtrlStudVacation.Create(AOwner:TComponent);
begin
inherited Create(AOwner);
DM:=TDM.Create(Self);
PRes:=NULL;
PLanguageIndex:=LanguageIndex;
LabelMan.Caption := LabelStudent_Caption[PLanguageIndex];
DateBegLabel.Caption := LabelDateBeg_Caption[PLanguageIndex];
DateEndLabel.Caption := LabelDateEnd_Caption[PLanguageIndex];
LabelPrikaz.Caption := LabelPrikaz_Caption[PLanguageIndex];
BoxMan.Caption := '';
BoxDates.Caption := '';
YesBtn.Caption := YesBtn_Caption[PLanguageIndex];
CancelBtn.Caption := CancelBtn_Caption[PLanguageIndex];
CancelBtn.Hint := CancelBtn.Caption+' (Esc)';
end;
//******************************************************************************
function TFCtrlStudVacation.DeleteRecord(Db_Handle:TISC_DB_HANDLE;Id:integer):boolean;
var PLanguageIndex:byte;
begin
Result:=False;
PLanguageIndex := IndexLanguage;
if grShowMessage(Caption_Delete[PLanguageIndex],
DeleteRecordQuestion_Text[PLanguageIndex],mtConfirmation,[mbYes,mbCancel])=mrYes then
with DM do
try
DB.Handle:=Db_Handle;
StProc.Transaction.StartTransaction;
StProc.StoredProcName:='GR_CN_DT_STUD_VAC_D';
StProc.Prepare;
StProc.ParamByName('ID_VACATION').AsInteger:=Id;
StProc.ExecProc;
StProc.Transaction.Commit;
Result:=True;
PRes:=-1;
except
on E:Exception do
begin
grShowMessage(ECaption[PlanguageIndex],e.Message,mtError,[mbOK]);
StProc.Transaction.Rollback;
Result:=False;
end;
end;
end;
//******************************************************************************
function TFCtrlStudVacation.PrepareData(Db_Handle:TISC_DB_HANDLE;fs:TZControlFormStyle;Id:int64):boolean;
var PDay,PMonth,PYear:word;
DBegStud,DEndStud,DBeg,DEnd:TDate;
begin
Result:=True;
Pcfs := fs;
case fs of
zcfsInsert:
begin
Caption:=Caption_Insert[PLanguageIndex];
with DM do
try
DB.Handle:=Db_Handle;
StProc.Transaction.StartTransaction;
StProc.StoredProcName:='GR_CN_DT_STUD_INF_FOR_I';
StProc.Prepare;
StProc.ParamByName('ID_STUD').AsInt64:=Id;
StProc.ExecProc;
PIdStud := Id;
EditMan.Text := StProc.ParamByName('FIO').AsString;
EditDateBeg.Date :=StProc.ParamByName('DATE_BEG_STUD').AsDate;
EditDateEnd.Date :=StProc.ParamByName('DATE_END_STUD').AsDate;
StProc.Transaction.Commit;
except
on E:Exception do
begin
grShowMessage(ECaption[PLanguageIndex],e.Message,mtError,[mbOK]);
StProc.Transaction.Rollback;
Result:=false;
end;
end;
end;
zcfsUpdate:
begin
Caption:=Caption_Update[PLanguageIndex];
with DM do
try
DB.Handle:=Db_Handle;
StProc.Transaction.StartTransaction;
StProc.StoredProcName:='GR_DT_STUD_VAC_S_BY_KEY';
StProc.Prepare;
StProc.ParamByName('old_ID_VACATION').AsInteger:=Id;
StProc.ExecProc;
PIdStudVac := Id;
PIdStud := StProc.ParamByName('ID_STUD').AsInt64;
EditMan.Text := StProc.ParamByName('FIO').AsString;
EditDateBeg.Date := StProc.ParamByName('DATE_BEG').asDate;
EditDateEnd .date := StProc.ParamByName('DATE_END').asDate;
EditPrikaz.Text := StProc.paramByName('PRIKAZ').AsString;
StProc.Transaction.Commit;
except
on E:Exception do
begin
grShowMessage(ECaption[PLanguageIndex],e.Message,mtError,[mbOK]);
StProc.Transaction.Rollback;
Result:=false;
end;
end;
end;
zcfsShowDetails:
begin
Caption:=Caption_Detail[PLanguageIndex];
self.BoxDates.Enabled := false;
YesBtn.Visible:=False;
CancelBtn.Caption := ExitBtn_Caption[PlanguageIndex];
///EditDepartment.Properties.Buttons[0].Visible:=False;
with DM do
try
DB.Handle:=Db_Handle;
//DSetCatStud.Open;
StProc.Transaction.StartTransaction;
StProc.StoredProcName:='GR_DT_STUD_VAC_S_BY_KEY';
StProc.Prepare;
StProc.ParamByName('old_ID_VACATION').AsInt64:=Id;
StProc.ExecProc;
PIdStud:=StProc.ParamByName('ID_STUD').AsInteger;
EditMan.Text := StProc.ParamByName('FIO').AsString;
EditDateEnd.Date := StProc.ParamByName('DATE_END').AsDate;
EditDateBeg.Date := StProc.ParamByName('DATE_BEG').AsDate;
EditPrikaz.Text := StProc.ParamByNAme('PRIKAZ').Asstring;
StProc.Transaction.Commit;
except
on E:Exception do
begin
grShowMessage(ECaption[PLanguageIndex],e.Message,mtError,[mbOK]);
StProc.Transaction.Rollback;
Result:=false;
end;
end;
end;
end;
end;
//******************************************************************************
procedure TFCtrlStudVacation.YesBtnClick(Sender: TObject);
var Res:Int64;
begin
YesBtn.SetFocus;
if EditDateBeg.Date>EditDateEnd.Date then
begin
grShowMessage(ECaption[PLanguageIndex],EInputTerms_Text[PLanguageIndex],mtWarning,[mbOk]);
exit;
end;
with DM do
try
StProcTransaction.StartTransaction;
case Pcfs of
zcfsInsert: StProc.StoredProcName:='GR_CN_DT_STUD_VAC_I';
zcfsUpdate: StProc.StoredProcName:='GR_CN_DT_STUD_VAC_U';
end;
StProc.Prepare;
StProc.ParamByName('ID_STUD').AsInt64:=PIdStud;
StProc.ParamByName('DATE_BEG').AsDate:=StrToDate(EditDateBeg.Text);
StProc.ParamByName('DATE_END').AsDate:=StrToDate(EditDateEnd.Text);
StProc.ParamByName('PRIKAZ').AsString:=EditPrikaz.Text;
case Pcfs of
zcfsUpdate: StProc.ParamByName('ID_VACATION').AsInteger:=PIdStudVac;
end;
StProc.ExecProc;
if pcfs=zcfsInsert then
Res:=StProc.ParamByName('ID_VACATION').AsInteger
else Res:=0;
StProc.Transaction.Commit;
PRes:=Res;
ModalResult:=mrYes;
except
on e:Exception do
begin
grShowMessage(ECaption[PLanguageIndex],e.message,mtError,[mbOk]);
StProc.transaction.RollBack;
PRes:=NULL;
end;
end;
end;
//******************************************************************************
procedure TFCtrlStudVacation.ActionEnterExecute(Sender: TObject);
begin
if CancelBtn.Focused=true then begin ModalResult := mrCancel; exit; end;
if YesBtn.Focused=true then begin ActionYes.Execute;exit; end;
if EditPrikaz.Focused=true then YesBtn.SetFocus;
if EditDateEnd.Focused=true then EditPrikaz.SetFocus;
if EditDateBeg.Focused=true then EditDateEnd.SetFocus;
end;
procedure TFCtrlStudVacation.FormShow(Sender: TObject);
begin
if Pcfs=zcfsInsert then RestoreFromBuffer(self);
//FormResize(sender);
//if PUpdateDateEnd=1 then EditDateEnd.Setfocus;
end;
procedure TFCtrlStudVacation.RestoreFromBuffer(Sender:TObject);
var reg:TRegistry;
Kod:integer;
Key:string;
begin
Key := '\Software\Grant\CtrlStudVacation';
reg := TRegistry.Create;
reg.RootKey:=HKEY_CURRENT_USER;
if not reg.OpenKey(Key,False) then
begin
reg.free;
Exit;
end;
if reg.ReadString('IsBuffer')<>'1' then
begin
reg.Free;
exit;
end;
EditDateBeg.EditValue:=reg.ReadDate('DateBegPeriod');
EditDateEnd.EditValue:=reg.ReadDate('DateEndPeriod');
EditPrikaz.Text:=reg.ReadString('EditPrikaz');
EditDateBeg.SetFocus;
Reg.Free;
end;
procedure TFCtrlStudVacation.CancelBtnClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TFCtrlStudVacation.FormCreate(Sender: TObject);
begin
dxStatusBar1.Panels[0].Text := 'F9 - '+ToBuffer_Caption[PLanguageIndex];
dxStatusBar1.Panels[1].Text := 'F10 - '+YesBtn.Caption;
dxStatusBar1.Panels[2].Text := 'Esc - '+CancelBtn.Caption;
end;
procedure TFCtrlStudVacation.ActionF9Execute(Sender: TObject);
var reg: TRegistry;
Key:string;
begin
CancelBtn.SetFocus;
Key := '\Software\Grant\CtrlStudVacation';
reg:=TRegistry.Create;
try
reg.RootKey:=HKEY_CURRENT_USER;
reg.OpenKey(Key,True);
reg.WriteString('IsBuffer','1');
reg.WriteDate('DateBegPeriod',EditDateBeg.EditValue);
reg.WriteDate('DateEndPeriod',EditDateEnd.EditValue);
reg.WriteString('EditPrikaz',EditPrikaz.Text);
finally
reg.Free;
end;
end;
end.
|
unit U01009;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, UDataModule, Vcl.ExtCtrls, Vcl.Buttons,
Vcl.ComCtrls, Vcl.StdCtrls, JvExComCtrls, JvAnimate;
type
TF01009 = class(TForm)
PanelStatus: TPanel;
PanelCAPTION: TPanel;
btnIniciarOk: TSpeedButton;
PanelCOMPLEMENTO: TPanel;
btnCancelar: TButton;
Panel1: TPanel;
procedure btnIniciarOkClick(Sender: TObject);
procedure btnCancelarClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure ExecutaBackupBD();
function ExecutarProcesso(cmd: string): Boolean;
end;
var
F01009: TF01009;
implementation
{$R *.dfm}
{ TF01009 }
uses Vcl.FileCtrl, SHELLAPI;
procedure TF01009.btnCancelarClick(Sender: TObject);
begin
close;
end;
procedure TF01009.ExecutaBackupBD;
Var
strBanco, strHost, strUsuario, strSenha, strComando, strCaminho, strArquivo: string;
begin
try
//Pega Caminho
strCaminho := ExtractFilePath(Application.ExeName) + 'backup\';
if not DirectoryExists(strCaminho) then
begin
CreateDir(strCaminho);
end;
//Verifica se mysqldump.exe esta na pasta do EXE
if FileExists(ExtractFilePath(Application.ExeName) + 'mysqldump.exe') then
begin
//Configurações
strArquivo := strCaminho + 'BD_' + FormatDateTime('YYYY-mm-dd_hhnnss', Now) + '.sql';
strHost := DModule.FDConnection.Params.Values['SERVER'] ; // '192.168.1.200';
strUsuario := DModule.FDConnection.Params.UserName; //'ruan';
strSenha := DModule.FDConnection.Params.Password;//'ruan';
strBanco := DModule.FDConnection.Params.Database; //'gym';
strComando := 'cmd.exe /c ""' +
ExtractFilePath(Application.ExeName) +
'\mysqldump.exe" ' + strBanco +
' --routines --events --databases --opt -c -e '+
' -h' + strHost +
' -u' + strUsuario +
' -p' + strSenha +
'' +
'>' + '"' +
strArquivo + '""';
ExecutarProcesso(strComando);
end
else
begin
ShowMessage('Atenção o aplicativo auxiliar mysqldump não se encontra no diretório, ' +
'solicite o mesmo ao suporte do sistema ');
end;
finally
//FreeAndNil(Ini);
end;
end;
function TF01009.ExecutarProcesso(cmd: string): Boolean;
var
SUInfo : TStartupInfo;
ProcInfo: TProcessInformation;
begin
FillChar(SUInfo, SizeOf(SUInfo), #0);
SUInfo.cb := SizeOf(SUInfo);
SUInfo.dwFlags := STARTF_USESHOWWINDOW;
SUInfo.wShowWindow := SW_HIDE;
Result := CreateProcess(nil, PChar(cmd), nil, nil, False, CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS, nil, nil, SUInfo, ProcInfo);
if (Result) then
begin
WaitForSingleObject(ProcInfo.hProcess, INFINITE);
CloseHandle(ProcInfo.hProcess);
CloseHandle(ProcInfo.hThread);
end;
end;
procedure TF01009.btnIniciarOkClick(Sender: TObject);
begin
if( btnIniciarOk.Caption = 'INICIAR') then
begin
try
TThread.CreateAnonymousThread(
procedure ()
begin
PanelCAPTION.Caption := 'ROTINA DE BACKUP EXECUTANDO. '+#13+'AGUARDE!';
btnIniciarOk.Enabled := false;
BTNCANCELAR.Enabled := FALSE;
ExecutaBackupBD;
TThread.Synchronize (TThread.CurrentThread,
procedure ()
begin
//fazer depois que acabar o processo
PanelCAPTION.Caption := 'BACKUP CONCLUÍDO!';
btnIniciarOk.Enabled := TRUE;
btnIniciarOk.Caption := 'OK';
//ABRE PASTA ONDE FICA OS BACKUPS
ShellExecute(Application.HANDLE, 'open', PChar(ExtractFilePath(Application.ExeName) + '\backup'),nil,nil,SW_SHOWMAXIMIZED);
end);
// .free aqui!!
end
).Start;
except
ON E: Exception DO
begin
PanelCAPTION.Caption := 'ERRO ENCONTRADO, CONSULTE SUPORTE!';
ShowMessage(E.Message);
end;
end;
end ELSE
BEGIN
if( btnIniciarOk.Caption = 'OK') then
begin
CLOSE;
end;
END;
end;
Initialization
RegisterClass(TF01009);
Finalization
UnRegisterClass(TF01009);
end.
|
// ************************************************************************ //
// The types declared in this file were generated from data read from the
// WSDL File described below:
// WSDL : http://10.10.0.158:8083/oxhide/services/UserServer?wsdl
// >Import : http://10.10.0.158:8083/oxhide/services/UserServer?wsdl:0
// Encoding : UTF-8
// Version : 1.0
// (2012-4-1 15:16:11 - - $Rev: 10138 $)
// ************************************************************************ //
unit UserServer;
interface
uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns;
const
IS_NLBL = $0004;
IS_REF = $0080;
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]
// !:boolean - "http://www.w3.org/2001/XMLSchema"[Gbl]
// ************************************************************************ //
// Namespace : http://users.server.oxhide.sxsihe.com
// transport : http://schemas.xmlsoap.org/soap/http
// style : document
// binding : UserServerHttpBinding
// service : UserServer
// port : UserServerHttpPort
// URL : http://10.10.0.158:8083/oxhide/services/UserServer
// ************************************************************************ //
UserServerPortType = interface(IInvokable)
['{9752F248-09DE-6C49-BBD4-A6967012A604}']
function saveToken(const in0: WideString): Boolean; stdcall;
procedure unSendData(const in0: WideString; const in1: WideString); stdcall;
function sendTokenData(const in0: WideString): WideString; stdcall;
function login(const in0: WideString): WideString; stdcall;
function hasRescource(const in0: WideString; const in1: WideString; const in2: WideString): Boolean; stdcall;
function loginCheck(const in0: WideString): Boolean; stdcall;
end;
function GetUserServerPortType(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): UserServerPortType;
implementation
uses SysUtils;
function GetUserServerPortType(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): UserServerPortType;
const
defWSDL = 'http://10.10.0.141:8083/oxhide/services/UserServer?wsdl';
defURL = 'http://10.10.0.141:8083/oxhide/services/UserServer';
defSvc = 'UserServer';
defPrt = 'UserServerHttpPort';
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 UserServerPortType);
if UseWSDL then
begin
RIO.WSDLLocation := Addr;
RIO.Service := defSvc;
RIO.Port := defPrt;
end else
RIO.URL := Addr;
finally
if (Result = nil) and (HTTPRIO = nil) then
RIO.Free;
end;
end;
initialization
InvRegistry.RegisterInterface(TypeInfo(UserServerPortType), 'http://users.server.oxhide.sxsihe.com', 'UTF-8');
InvRegistry.RegisterDefaultSOAPAction(TypeInfo(UserServerPortType), '');
InvRegistry.RegisterInvokeOptions(TypeInfo(UserServerPortType), ioDocument);
InvRegistry.RegisterExternalParamName(TypeInfo(UserServerPortType), 'saveToken', 'out_', 'out');
InvRegistry.RegisterExternalParamName(TypeInfo(UserServerPortType), 'sendTokenData', 'out_', 'out');
InvRegistry.RegisterExternalParamName(TypeInfo(UserServerPortType), 'login', 'out_', 'out');
InvRegistry.RegisterExternalParamName(TypeInfo(UserServerPortType), 'hasRescource', 'out_', 'out');
InvRegistry.RegisterExternalParamName(TypeInfo(UserServerPortType), 'loginCheck', 'out_', 'out');
end. |
function Split(const str, separator: string): ArrayOfInteger;
var
i, n: integer;
strline, strfield: string;
begin
{ Number of occurences of the separator }
n:= Occurs(str, separator);
{ Size of the array to be returned is the number of occurences of the separator }
SetLength(Result, n + 1);
i := 0;
strline:= str;
repeat
if Pos(separator, strline) > 0 then
begin
strfield:= Copy(strline, 1, Pos(separator, strline) - 1);
strline:= Copy(strline, Pos(separator, strline) + 1, Length(strline) - pos(separator,strline));
end
else
begin
strfield:= strline;
strline:= '';
end;
Split[i]:= StrToInt(strfield);
Inc(i);
until strline= '';
//if Split[High(Split)] = '' then SetLength(Split, Length(Split) -1);
end; |
unit VolumeRGBIntData;
interface
uses Windows, Graphics, BasicDataTypes, Abstract3DVolumeData, RGBIntDataSet,
AbstractDataSet, dglOpenGL, Math;
type
T3DVolumeRGBIntData = class (TAbstract3DVolumeData)
private
FDefaultColor: TPixelRGBIntData;
// Gets
function GetData(_x, _y, _z, _c: integer):integer;
function GetDataUnsafe(_x, _y, _z, _c: integer):integer;
function GetDefaultColor:TPixelRGBIntData;
// Sets
procedure SetData(_x, _y, _z, _c: integer; _value: integer);
procedure SetDataUnsafe(_x, _y, _z, _c: integer; _value: integer);
procedure SetDefaultColor(_value: TPixelRGBIntData);
protected
// Constructors and Destructors
procedure Initialize; override;
// Gets
function GetBitmapPixelColor(_Position: longword):longword; override;
function GetRPixelColor(_Position: longword):byte; override;
function GetGPixelColor(_Position: longword):byte; override;
function GetBPixelColor(_Position: longword):byte; override;
function GetAPixelColor(_Position: longword):byte; override;
function GetRedPixelColor(_x,_y,_z: integer):single; override;
function GetGreenPixelColor(_x,_y,_z: integer):single; override;
function GetBluePixelColor(_x,_y,_z: integer):single; override;
function GetAlphaPixelColor(_x,_y,_z: integer):single; override;
// Sets
procedure SetBitmapPixelColor(_Position, _Color: longword); override;
procedure SetRGBAPixelColor(_Position: integer; _r, _g, _b, _a: byte); override;
procedure SetRedPixelColor(_x,_y,_z: integer; _value:single); override;
procedure SetGreenPixelColor(_x,_y,_z: integer; _value:single); override;
procedure SetBluePixelColor(_x,_y,_z: integer; _value:single); override;
procedure SetAlphaPixelColor(_x,_y,_z: integer; _value:single); override;
// Copies
procedure CopyData(const _Data: TAbstractDataSet; _DataXSize, _DataYSize, _DataZSize: integer); override;
public
// Gets
function GetOpenGLFormat:TGLInt; override;
// copies
procedure Assign(const _Source: TAbstract3DVolumeData); override;
// Misc
procedure ScaleBy(_Value: single); override;
procedure Invert; override;
procedure Fill(_Value: integer);
// properties
property Data[_x,_y,_z,_c:integer]:integer read GetData write SetData; default;
property DataUnsafe[_x,_y,_z,_c:integer]:integer read GetDataUnsafe write SetDataUnsafe;
property DefaultColor:TPixelRGBIntData read GetDefaultColor write SetDefaultColor;
end;
implementation
// Constructors and Destructors
procedure T3DVolumeRGBIntData.Initialize;
begin
FDefaultColor.r := 0;
FDefaultColor.g := 0;
FDefaultColor.b := 0;
FData := TRGBIntDataSet.Create;
end;
// Gets
function T3DVolumeRGBIntData.GetData(_x, _y, _z, _c: integer):integer;
begin
if IsPixelValid(_x,_y,_z) and (_c >= 0) and (_c <= 2) then
begin
case (_c) of
0: Result := (FData as TRGBIntDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x];
1: Result := (FData as TRGBIntDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x];
else
begin
Result := (FData as TRGBIntDataSet).Blue[(_z * FYxXSize) + (_y * FXSize) + _x];
end;
end;
end
else
begin
case (_c) of
0: Result := FDefaultColor.r;
1: Result := FDefaultColor.g;
else
begin
Result := FDefaultColor.b;
end;
end;
end;
end;
function T3DVolumeRGBIntData.GetDataUnsafe(_x, _y, _z, _c: integer):integer;
begin
case (_c) of
0: Result := (FData as TRGBIntDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x];
1: Result := (FData as TRGBIntDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x];
else
begin
Result := (FData as TRGBIntDataSet).Blue[(_z * FYxXSize) + (_y * FXSize) + _x];
end;
end;
end;
function T3DVolumeRGBIntData.GetDefaultColor:TPixelRGBIntData;
begin
Result := FDefaultColor;
end;
function T3DVolumeRGBIntData.GetBitmapPixelColor(_Position: longword):longword;
begin
Result := RGB((FData as TRGBIntDataSet).Blue[_Position],(FData as TRGBIntDataSet).Green[_Position],(FData as TRGBIntDataSet).Red[_Position]);
end;
function T3DVolumeRGBIntData.GetRPixelColor(_Position: longword):byte;
begin
Result := (FData as TRGBIntDataSet).Red[_Position] and $FF;
end;
function T3DVolumeRGBIntData.GetGPixelColor(_Position: longword):byte;
begin
Result := (FData as TRGBIntDataSet).Green[_Position] and $FF;
end;
function T3DVolumeRGBIntData.GetBPixelColor(_Position: longword):byte;
begin
Result := (FData as TRGBIntDataSet).Blue[_Position] and $FF;
end;
function T3DVolumeRGBIntData.GetAPixelColor(_Position: longword):byte;
begin
Result := 0;
end;
function T3DVolumeRGBIntData.GetRedPixelColor(_x,_y,_z: integer):single;
begin
Result := (FData as TRGBIntDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x];
end;
function T3DVolumeRGBIntData.GetGreenPixelColor(_x,_y,_z: integer):single;
begin
Result := (FData as TRGBIntDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x];
end;
function T3DVolumeRGBIntData.GetBluePixelColor(_x,_y,_z: integer):single;
begin
Result := (FData as TRGBIntDataSet).Blue[(_z * FYxXSize) + (_y * FXSize) + _x];
end;
function T3DVolumeRGBIntData.GetAlphaPixelColor(_x,_y,_z: integer):single;
begin
Result := 0;
end;
function T3DVolumeRGBIntData.GetOpenGLFormat:TGLInt;
begin
Result := GL_RGB;
end;
// Sets
procedure T3DVolumeRGBIntData.SetBitmapPixelColor(_Position, _Color: longword);
begin
(FData as TRGBIntDataSet).Red[_Position] := GetRValue(_Color);
(FData as TRGBIntDataSet).Green[_Position] := GetGValue(_Color);
(FData as TRGBIntDataSet).Blue[_Position] := GetBValue(_Color);
end;
procedure T3DVolumeRGBIntData.SetRGBAPixelColor(_Position: integer; _r, _g, _b, _a: byte);
begin
(FData as TRGBIntDataSet).Red[_Position] := _r;
(FData as TRGBIntDataSet).Green[_Position] := _g;
(FData as TRGBIntDataSet).Blue[_Position] := _b;
end;
procedure T3DVolumeRGBIntData.SetRedPixelColor(_x,_y,_z: integer; _value:single);
begin
(FData as TRGBIntDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x] := Round(_value);
end;
procedure T3DVolumeRGBIntData.SetGreenPixelColor(_x,_y,_z: integer; _value:single);
begin
(FData as TRGBIntDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x] := Round(_value);
end;
procedure T3DVolumeRGBIntData.SetBluePixelColor(_x,_y,_z: integer; _value:single);
begin
(FData as TRGBIntDataSet).Blue[(_z * FYxXSize) + (_y * FXSize) + _x] := Round(_value);
end;
procedure T3DVolumeRGBIntData.SetAlphaPixelColor(_x,_y,_z: integer; _value:single);
begin
// do nothing
end;
procedure T3DVolumeRGBIntData.SetData(_x, _y, _z, _c: integer; _value: integer);
begin
if IsPixelValid(_x,_y,_z) and (_c >= 0) and (_c <= 2) then
begin
case (_c) of
0: (FData as TRGBIntDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x] := _value;
1: (FData as TRGBIntDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x] := _value;
2: (FData as TRGBIntDataSet).Blue[(_z * FYxXSize) + (_y * FXSize) + _x] := _value;
end;
end;
end;
procedure T3DVolumeRGBIntData.SetDataUnsafe(_x, _y, _z, _c: integer; _value: integer);
begin
case (_c) of
0: (FData as TRGBIntDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x] := _value;
1: (FData as TRGBIntDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x] := _value;
2: (FData as TRGBIntDataSet).Blue[(_z * FYxXSize) + (_y * FXSize) + _x] := _value;
end;
end;
procedure T3DVolumeRGBIntData.SetDefaultColor(_value: TPixelRGBIntData);
begin
FDefaultColor.r := _value.r;
FDefaultColor.g := _value.g;
FDefaultColor.b := _value.b;
end;
// Copies
procedure T3DVolumeRGBIntData.Assign(const _Source: TAbstract3DVolumeData);
begin
inherited Assign(_Source);
FDefaultColor.r := (_Source as T3DVolumeRGBIntData).FDefaultColor.r;
FDefaultColor.g := (_Source as T3DVolumeRGBIntData).FDefaultColor.g;
FDefaultColor.b := (_Source as T3DVolumeRGBIntData).FDefaultColor.b;
end;
procedure T3DVolumeRGBIntData.CopyData(const _Data: TAbstractDataSet; _DataXSize, _DataYSize, _DataZSize: integer);
var
x,y,z,ZPos,ZDataPos,Pos,maxPos,DataPos,maxX, maxY, maxZ: integer;
begin
maxX := min(FXSize,_DataXSize)-1;
maxY := min(FYSize,_DataYSize)-1;
maxZ := min(FZSize,_DataZSize)-1;
for z := 0 to maxZ do
begin
ZPos := z * FYxXSize;
ZDataPos := z * _DataYSize * _DataXSize;
for y := 0 to maxY do
begin
Pos := ZPos + (y * FXSize);
DataPos := ZDataPos + (y * _DataXSize);
maxPos := Pos + maxX;
for x := Pos to maxPos do
begin
(FData as TRGBIntDataSet).Data[x] := (_Data as TRGBIntDataSet).Data[DataPos];
inc(DataPos);
end;
end;
end;
end;
// Misc
procedure T3DVolumeRGBIntData.ScaleBy(_Value: single);
var
x,maxx: integer;
begin
maxx := (FYxXSize * FZSize) - 1;
for x := 0 to maxx do
begin
(FData as TRGBIntDataSet).Red[x] := Round((FData as TRGBIntDataSet).Red[x] * _Value);
(FData as TRGBIntDataSet).Green[x] := Round((FData as TRGBIntDataSet).Green[x] * _Value);
(FData as TRGBIntDataSet).Blue[x] := Round((FData as TRGBIntDataSet).Blue[x] * _Value);
end;
end;
procedure T3DVolumeRGBIntData.Invert;
var
x,maxx: integer;
begin
maxx := (FYxXSize * FZSize) - 1;
for x := 0 to maxx do
begin
(FData as TRGBIntDataSet).Red[x] := 255 - (FData as TRGBIntDataSet).Red[x];
(FData as TRGBIntDataSet).Green[x] := 255 - (FData as TRGBIntDataSet).Green[x];
(FData as TRGBIntDataSet).Blue[x] := 255 - (FData as TRGBIntDataSet).Blue[x];
end;
end;
procedure T3DVolumeRGBIntData.Fill(_value: integer);
var
x,maxx: integer;
begin
maxx := (FYxXSize * FZSize) - 1;
for x := 0 to maxx do
begin
(FData as TRGBIntDataSet).Red[x] := _value;
(FData as TRGBIntDataSet).Green[x] := _value;
(FData as TRGBIntDataSet).Blue[x] := _value;
end;
end;
end.
|
{/*!
Provides a wrapper class of Gisdk resource compiler for just-in-time script compiling.
\modified 2019-07-17 13:10pam
\author Wuping Xin
*/}
namespace TsmPluginFx.Core;
uses
RemObjects.Elements.RTL;
type
CaliperScriptCompiler = public class
public
class method Compile(const aScript: String; const aCompilerPath: String; const aUiDbFilePathWithoutExt: String): tuple of (Success: Boolean, Errors: ImmutableList<String>);
begin
// Save the script content to a disk file in the same directory as the UI database.
var lScriptFilePath := aUiDbFilePathWithoutExt + 'Script.rsc';
if File.Exists(lScriptFilePath) then File.Delete(lScriptFilePath);
File.WriteText(lScriptFilePath, aScript);
// Delete any pre-existing error file.
var lCompilerErrorFilePath := aUiDbFilePathWithoutExt + '.err';
if File.Exists(lCompilerErrorFilePath) then File.Delete(lCompilerErrorFilePath);
// Compile the script
var lArgs := new List<String>('-u', aUiDbFilePathWithoutExt, lScriptFilePath);
Process.Run(aCompilerPath, lArgs.ToArray);
// Check if there is any errors.
var lErrors := if File.Exists(lCompilerErrorFilePath) then File.ReadLines(lCompilerErrorFilePath);
result := (assigned(lErrors), lErrors);
end;
end;
end. |
unit CFCNMonthCalendar;
interface
uses Windows, Classes, CFMonthCalendar, Graphics;
type
TCFCNMonthCalendar = class(TCFCustomMonthCalendar)
private
FOnPaintCNDate: TPaintDateEvent;
/// <summary>
/// 获取相应的农历日期
/// </summary>
/// <param name="ADate">阳历日期</param>
/// <returns>农历</returns>
function GetLunarDate(const ADate: TDate): string;
/// <summary>
/// 进行绘制农历和节气
/// </summary>
/// <param name="Sender"></param>
/// <param name="ACanvas"></param>
/// <param name="ADate">阳历日期</param>
/// <param name="ARect">指定日期区域</param>
procedure DoOnPaintDate(Sender: TObject; const ACanvas: TCanvas; const ADate: TDate; const ARect: TRect);
protected
/// <summary> 利用画布绘制 </summary>
procedure DrawControl(ACanvas: TCanvas); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property OnPaintCNDate: TPaintDateEvent read FOnPaintCNDate write FOnPaintCNDate;
property Date;
property MaxDate;
property MinDate;
end;
implementation
uses
hxCalendar, DateUtils, SysUtils;
{ TCFCNMonthCalendar }
var
FJQ: Boolean; // 标记是否为节气
constructor TCFCNMonthCalendar.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Self.OnPaintDate := DoOnPaintDate;
end;
destructor TCFCNMonthCalendar.Destroy;
begin
inherited;
end;
procedure TCFCNMonthCalendar.DrawControl(ACanvas: TCanvas);
begin
inherited;
end;
function TCFCNMonthCalendar.GetLunarDate(const ADate: TDate): string;
var
vThxCalendar: ThxCalendar;
vHzDate: THzDate;
begin
FJQ := False;
vHzDate := vThxCalendar.ToLunar(ADate); // 得到农历
if vThxCalendar.GetJQ(ADate) <> '' then // 节气存在返回节气
begin
Result := vThxCalendar.GetJQ(ADate);
FJQ := True;
end
else
Result := vThxCalendar.FormatLunarDay(vHzDate.Day);
end;
procedure TCFCNMonthCalendar.DoOnPaintDate(Sender: TObject; const ACanvas: TCanvas;
const ADate: TDate; const ARect: TRect);
var
vS: string;
vOldFontSize: Byte;
vRect: TRect;
vOldFontColor: TColor;
vHeight: Integer;
begin
vRect := ARect;
vHeight := ARect.Bottom - ARect.Top;
vRect.Bottom := vRect.Bottom - Round(vHeight * 0.55); // 定义放日期的区域,乘0.55是为了公历字体大于农历
vS := FormatDateTime('D', DateOf(ADate));
DrawTextEx(ACanvas.Handle, PChar(vS), -1, vRect, DT_CENTER or DT_BOTTOM or DT_SINGLELINE, nil);
// 记住之前相关的画笔字体大小和颜色
vOldFontSize := ACanvas.Font.Size;
vOldFontColor := ACanvas.Font.Color;
// 得到相应的农历和节气并进行显示
try
vS := GetLunarDate(ADate);
ACanvas.Font.Size := Round(vOldFontSize * 0.7);
if FJQ then // 节气显示为红色
ACanvas.Font.Color := clRed
else // 显示农历
ACanvas.Font.Color := clGrayText;
// 输出对应的农历
vRect := Rect(ARect.Left, ARect.Top + Round(vHeight * 0.55), ARect.Right, ARect.Bottom); // 定义农历文字的区域
DrawTextEx(ACanvas.Handle, PChar(vS), -1, vRect, DT_CENTER or DT_TOP or DT_SINGLELINE, nil);
finally
// 恢复画笔的字体的大小和颜色
ACanvas.Font.Size := vOldFontSize;
ACanvas.Font.Color := vOldFontColor;
end;
if Assigned(FOnPaintCNDate) then
FOnPaintCNDate(Self, ACanvas, ADate, ARect);
end;
end.
|
(*
Category: SWAG Title: FILE COPY/MOVE ROUTINES
Original name: 0013.PAS
Description: Rename File #1
Author: SWAG SUPPORT TEAM, minor changes by Nacho
Date: 05-28-93 13:35
*)
{
> Does anybody know how to do a "fast" move of a File?
> ie: not copying it but just moving the FAT Record
Yup. In Pascal you can do it With the Rename command. The Format is:
Rename (Var F; NewName : String)
where F is a File Variable of any Type.
to move a File Really fast, and to avoid having to copy it somewhere first and
then deleting the original, do this:
}
Program MoveIt; {No error checking done}
Var
F : File;
FName : String;
NName : String;
begin
FName := '1.pas';
NName := '2.pas';
Assign (F, FName);
{NName:= new directory / File name}
Rename (F, NName);
End.
|
(*
Category: SWAG Title: ANYTHING NOT OTHERWISE CLASSIFIED
Original name: 0154.PAS
Description: Calculating Windchill
Author: PETER KOLDING & KERRY SOKALSKY
Date: 05-26-95 23:32
*)
{
Given the time of year, I offer the following pascal function,
(my translation of M. Cooper's WINDCHILL public domain C code):
Calculates windchill, given temperature (Fahrenheit) and windspeed (mph)
---------------------------------------------------------------------------
NOTE:
I have converted Mr. Kolding's original function so that it accepts and
returns real parameters. I have also offered a Metric equivalent.
- Kerry (SWAG Support Team)
}
Function WindChill(FahrenheitTemp, Mph_WindSpeed : Real) : Real;
begin
WindChill := 0.0817 *
(3.71 * Sqrt(Mph_WindSpeed) + 5.81 - 0.25 * Mph_WindSpeed) *
(FahrenheitTemp - 91.4) + 91.4;
end;
Function MetricWindChill(CelciusTemp, Kph_WindSpeed : Real) : Real;
Var
FahrenheitTemp,
Mph_WindSpeed : Real;
begin
{ Convert Celcius to Fahrenhiet - VERY exact :) }
FahrenheitTemp := (CelciusTemp * 492 / 273.16) + 32;
{ Convert Kph to Mph }
Mph_WindSpeed := Kph_WindSpeed * 1.609;
{ Use exact same formula as above }
MetricWindChill :=
0.0817 * (3.71 * Sqrt(Mph_WindSpeed) + 5.81 - 0.25 * Mph_WindSpeed) *
(FahrenheitTemp - 91.4) + 91.4;
end;
begin
{ Room Temperature Test: }
Writeln('68 F + 0 Mph Wind Speed: ', WindChill(68, 0) : 0 : 2);
Writeln('20 C + 0 Kph Wind Speed: ', MetricWindChill(20, 0) : 0 : 2);
end.
|
namespace RemObjects.Elements.EUnit;
interface
uses
Sugar;
type
Assert = public partial static class {$IF NOUGAT}mapped to Object{$ENDIF}
public
method AreEqual(Actual, Expected : String; IgnoreCase: Boolean := false; Message: String := nil);
method AreNotEqual(Actual, Expected: String; IgnoreCase: Boolean := false; Message: String := nil);
method Contains(SubString, InString: String; Message: String := nil);
method DoesNotContains(SubString, InString: String; Message: String := nil);
method StartsWith(Prefix, SourceString: String; Message: String := nil);
method EndsWith(Suffix, SourceString: String; Message: String := nil);
method IsEmpty(Actual: String; Message: String := nil);
method IsNotEmpty(Actual: String; Message: String := nil);
end;
implementation
class method Assert.AreEqual(Actual: String; Expected: String; IgnoreCase: Boolean := false; Message: String := nil);
begin
if (Expected = nil) and (Actual = nil) then
exit;
if (Expected = nil) and (Actual <> nil) then
Fail(Actual, Expected, coalesce(Message, AssertMessages.NotEqual));
if IgnoreCase then
FailIfNot(Expected.EqualsIgnoreCase(Actual), Actual, Expected, coalesce(Message, AssertMessages.NotEqual))
else
FailIfNot(Expected.Equals(Actual), Actual, Expected, coalesce(Message, AssertMessages.NotEqual));
end;
class method Assert.AreNotEqual(Actual: String; Expected: String; IgnoreCase: Boolean := false; Message: String := nil);
begin
if (Expected = nil) and (Actual = nil) then
Fail(Actual, Expected, coalesce(Message, AssertMessages.Equal));
if (Expected = nil) and (Actual <> nil) then
exit;
if IgnoreCase then
FailIf(Expected.EqualsIgnoreCase(Actual), Actual, Expected, coalesce(Message, AssertMessages.Equal))
else
FailIf(Expected.Equals(Actual), Actual, Expected, coalesce(Message, AssertMessages.Equal));
end;
class method Assert.Contains(SubString: String; InString: String; Message: String := nil);
begin
ArgumentNilException.RaiseIfNil(InString, "InString");
ArgumentNilException.RaiseIfNil(SubString, "SubString");
FailIfNot(InString.Contains(SubString), SubString, "String", coalesce(Message, AssertMessages.DoesNotContains));
end;
class method Assert.DoesNotContains(SubString: String; InString: String; Message: String := nil);
begin
ArgumentNilException.RaiseIfNil(InString, "InString");
ArgumentNilException.RaiseIfNil(SubString, "SubString");
FailIf(InString.Contains(SubString), SubString, "String", coalesce(Message, AssertMessages.UnexpectedContains));
end;
class method Assert.StartsWith(Prefix: String; SourceString: String; Message: String := nil);
begin
ArgumentNilException.RaiseIfNil(Prefix, "Prefix");
ArgumentNilException.RaiseIfNil(SourceString, "SourceString");
FailIfNot(SourceString.StartsWith(Prefix), Prefix, SourceString, coalesce(Message, AssertMessages.StringPrefixMissing));
end;
class method Assert.EndsWith(Suffix: String; SourceString: String; Message: String := nil);
begin
ArgumentNilException.RaiseIfNil(Suffix, "Suffix");
ArgumentNilException.RaiseIfNil(SourceString, "SourceString");
FailIfNot(SourceString.EndsWith(Suffix), Suffix, SourceString, coalesce(Message, AssertMessages.StringSufixMissing));
end;
class method Assert.IsEmpty(Actual: String; Message: String := nil);
begin
ArgumentNilException.RaiseIfNil(Actual, "Actual");
FailIfNot(Actual.Length = 0, Actual, "String", coalesce(Message, AssertMessages.IsNotEmpty));
end;
class method Assert.IsNotEmpty(Actual: String; Message: String := nil);
begin
ArgumentNilException.RaiseIfNil(Actual, "Actual");
FailIfNot(Actual.Length <> 0, Actual, "String", coalesce(Message, AssertMessages.IsEmpty));
end;
end. |
unit uShareImagesThread;
interface
uses
Winapi.Windows,
Winapi.ActiveX,
System.SysUtils,
System.Classes,
Vcl.Graphics,
Vcl.Imaging.Jpeg,
Vcl.Imaging.pngImage,
Vcl.ComCtrls,
Dmitry.Utils.System,
CCR.Exif,
uConstants,
uRuntime,
uMemory,
uLogger,
uThreadEx,
uThreadForm,
uAssociations,
uShellThumbnails,
uAssociatedIcons,
uPhotoShareInterfaces,
uShellIntegration,
uShareUtils,
uImageLoader,
uDBEntities;
type
TShareImagesThread = class;
TItemUploadProgress = class(TInterfacedObject, IUploadProgress)
private
FThread: TShareImagesThread;
FItem: TMediaItem;
public
constructor Create(Thread: TShareImagesThread; Item: TMediaItem);
procedure OnProgress(Sender: IPhotoShareProvider; Max, Position: Int64; var Cancel: Boolean);
end;
TShareImagesThread = class(TThreadEx)
private
FData: TMediaItem;
FIsPreview: Boolean;
FAlbum: IPhotoServiceAlbum;
FProvider: IPhotoShareProvider;
FIsAlbumCreated: Boolean;
procedure ShowError(ErrorText: string);
procedure CreateAlbum;
procedure ProcessItem(Data: TMediaItem);
procedure ProcessImage(Data: TMediaItem);
procedure ProcessVideo(Data: TMediaItem);
procedure NotifyProgress(Data: TMediaItem; Max, Position: Int64; var Cancel: Boolean);
protected
procedure Execute; override;
function GetThreadID: string; override;
public
constructor Create(AOwnerForm: TThreadForm; Provider: IPhotoShareProvider; IsPreview: Boolean);
destructor Destroy; override;
end;
implementation
uses
uFormSharePhotos;
{ TShareImagesThread }
constructor TShareImagesThread.Create(AOwnerForm: TThreadForm; Provider: IPhotoShareProvider; IsPreview: Boolean);
begin
inherited Create(AOwnerForm, AOwnerForm.StateID);
FIsPreview := IsPreview;
FProvider := Provider;
FData := nil;
FAlbum := nil;
FIsAlbumCreated := False;
end;
procedure TShareImagesThread.CreateAlbum;
var
FAlbumID, AlbumName: string;
AlbumDate: TDateTime;
FAccess: Integer;
begin
SynchronizeEx(
procedure
begin
TFormSharePhotos(OwnerForm).GetAlbumInfo(FAlbumID, AlbumName, AlbumDate, FAccess, FAlbum);
end
);
if FAlbumID = '' then
begin
if FProvider.CreateAlbum(AlbumName, '', AlbumDate, FAccess, FAlbum) then
begin
FAlbumID := FAlbum.AlbumID;
FIsAlbumCreated := True;
end else
ShowError(L('Can''t create album!'));
end;
end;
destructor TShareImagesThread.Destroy;
begin
F(FData);
inherited;
end;
procedure TShareImagesThread.Execute;
var
ErrorMessage: string;
begin
inherited;
FreeOnTerminate := True;
try
//for video previews
CoInitializeEx(nil, COINIT_APARTMENTTHREADED);
try
if not FIsPreview then
SynchronizeEx(
procedure
begin
TFormSharePhotos(OwnerForm).PbMain.Style := pbstMarquee;
TFormSharePhotos(OwnerForm).PbMain.Show;
end
);
try
if not FIsPreview then
begin
CreateAlbum;
SynchronizeEx(
procedure
begin
TFormSharePhotos(OwnerForm).PbMain.Style := pbstNormal;
end
);
if FAlbum = nil then
Exit;
end;
repeat
if IsTerminated or DBTerminating then
Break;
SynchronizeEx(
procedure
begin
if FIsPreview then
TFormSharePhotos(OwnerForm).GetDataForPreview(FData)
else
TFormSharePhotos(OwnerForm).GetData(FData);
end
);
if IsTerminated or DBTerminating then
Break;
if FData <> nil then
begin
if not FIsPreview then
SynchronizeEx(
procedure
begin
TFormSharePhotos(OwnerForm).StartProcessing(FData);
end
);
ErrorMessage := '';
try
try
ProcessItem(FData);
except
on e: Exception do
ErrorMessage := e.Message;
end;
finally
if not FIsPreview or (ErrorMessage <> '') then
SynchronizeEx(
procedure
begin
TFormSharePhotos(OwnerForm).EndProcessing(FData, ErrorMessage);
end
);
end;
end;
until FData = nil;
finally
if not FIsPreview then
SynchronizeEx(
procedure
begin
TFormSharePhotos(OwnerForm).PbMain.Hide;
end
);
end;
finally
if not FIsPreview then
SynchronizeEx(
procedure
begin
TFormSharePhotos(OwnerForm).SharingDone;
end
);
CoUninitialize;
end;
except
on e: Exception do
begin
EventLog(e);
ShowError(e.Message);
end;
end;
end;
function TShareImagesThread.GetThreadID: string;
begin
Result := 'PhotoShare';
end;
procedure TShareImagesThread.NotifyProgress(Data: TMediaItem; Max, Position: Int64; var Cancel: Boolean);
begin
Cancel := not SynchronizeEx(
procedure
begin
TFormSharePhotos(OwnerForm).NotifyItemProgress(Data, Max, Position);
end
);
end;
procedure TShareImagesThread.ProcessItem(Data: TMediaItem);
begin
if CanShareVideo(Data.FileName) then
ProcessVideo(Data)
else
ProcessImage(Data);
if FIsAlbumCreated then
begin
SynchronizeEx(
procedure
begin
TFormSharePhotos(OwnerForm).HideAlbumCreation;
TFormSharePhotos(OwnerForm).ReloadAlbums;
end
);
FIsAlbumCreated := False;
end;
end;
procedure TShareImagesThread.ProcessImage(Data: TMediaItem);
var
PhotoItem: IPhotoServiceItem;
ItemProgress: IUploadProgress;
begin
ProcessImageForSharing(Data, FIsPreview,
procedure(Data: TMediaItem; Preview: TGraphic)
begin
SynchronizeEx(
procedure
begin
TFormSharePhotos(OwnerForm).UpdatePreview(Data, Preview);
end
);
end,
procedure(Data: TMediaItem; S: TStream; ContentType: string)
begin
ItemProgress := TItemUploadProgress.Create(Self, Data);
try
FAlbum.UploadItem(ExtractFileName(Data.FileName), ExtractFileName(Data.FileName),
Data.Comment, Data.Date, ContentType, S, ItemProgress, PhotoItem);
finally
ItemProgress := nil;
end;
end
);
end;
procedure TShareImagesThread.ProcessVideo(Data: TMediaItem);
var
TempBitmap: TBitmap;
Ico: TIcon;
FS: TFileStream;
ContentType: string;
ItemProgress: IUploadProgress;
VideoItem: IPhotoServiceItem;
begin
if FIsPreview then
begin
TempBitmap := TBitmap.Create;
try
if ExtractVideoThumbnail(Data.FileName, 32, TempBitmap) then
begin
SynchronizeEx(
procedure
begin
TFormSharePhotos(OwnerForm).UpdatePreview(Data, TempBitmap);
end
);
end else
begin
Ico := TAIcons.Instance.GetIconByExt(Data.FileName, False, 32, False);
try
SynchronizeEx(
procedure
begin
TFormSharePhotos(OwnerForm).UpdatePreview(Data, Ico);
end
);
finally
F(Ico);
end;
end;
finally
F(TempBitmap);
end;
end else
begin
ContentType := GetFileMIMEType(Data.FileName);
FS := TFileStream.Create(Data.FileName, fmOpenRead or fmShareDenyWrite);
try
FS.Seek(0, soFromBeginning);
ItemProgress := TItemUploadProgress.Create(Self, Data);
try
FAlbum.UploadItem(ExtractFileName(Data.FileName), ExtractFileName(Data.FileName),
ExtractFileName(Data.FileName), Data.Date, ContentType, FS, ItemProgress, VideoItem);
finally
ItemProgress := nil;
end;
finally
F(FS);
end;
end;
end;
procedure TShareImagesThread.ShowError(ErrorText: string);
begin
SynchronizeEx(
procedure
begin
MessageBoxDB(Handle, ErrorText, L('Warning'), TD_BUTTON_OK, TD_ICON_ERROR);
end
);
end;
{ TItemUploadProgress }
constructor TItemUploadProgress.Create(Thread: TShareImagesThread;
Item: TMediaItem);
begin
FThread := Thread;
FItem := Item;
end;
procedure TItemUploadProgress.OnProgress(Sender: IPhotoShareProvider; Max,
Position: Int64; var Cancel: Boolean);
begin
FThread.NotifyProgress(FItem, Max, Position, Cancel);
end;
end.
|
unit BasicSet;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, Spin;
type
TFrmBasicSet = class(TForm)
PageControl1: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
TabSheet3: TTabSheet;
GroupBox1: TGroupBox;
GroupBox2: TGroupBox;
CheckBoxTestServer: TCheckBox;
CheckBoxEnableMakingID: TCheckBox;
CheckBoxEnableGetbackPassword: TCheckBox;
CheckBoxAutoClear: TCheckBox;
Label1: TLabel;
Label2: TLabel;
ButtonSave: TButton;
ButtonClose: TButton;
SpinEditAutoClearTime: TSpinEdit;
ButtonRestoreBasic: TButton;
ButtonRestoreNet: TButton;
GroupBox3: TGroupBox;
GroupBox4: TGroupBox;
GroupBox5: TGroupBox;
GroupBox6: TGroupBox;
CheckBoxDynamicIPMode: TCheckBox;
Label3: TLabel;
Label4: TLabel;
EditGateAddr: TEdit;
EditGatePort: TEdit;
Label5: TLabel;
Label6: TLabel;
EditMonAddr: TEdit;
EditMonPort: TEdit;
Label7: TLabel;
Label8: TLabel;
EditServerAddr: TEdit;
EditServerPort: TEdit;
GroupBox7: TGroupBox;
CheckBoxAutoUnLockAccount: TCheckBox;
Label9: TLabel;
Label10: TLabel;
SpinEditUnLockAccountTime: TSpinEdit;
CheckBoxMinimize: TCheckBox;
GroupBox8: TGroupBox;
Label12: TLabel;
CheckBoxRandomCode: TCheckBox;
procedure CheckBoxTestServerClick(Sender: TObject);
procedure CheckBoxEnableMakingIDClick(Sender: TObject);
procedure CheckBoxEnableGetbackPasswordClick(Sender: TObject);
procedure CheckBoxAutoClearClick(Sender: TObject);
procedure SpinEditAutoClearTimeChange(Sender: TObject);
procedure CheckBoxAutoUnLockAccountClick(Sender: TObject);
procedure SpinEditUnLockAccountTimeChange(Sender: TObject);
procedure ButtonRestoreBasicClick(Sender: TObject);
procedure EditGateAddrChange(Sender: TObject);
procedure EditGatePortChange(Sender: TObject);
procedure EditMonAddrChange(Sender: TObject);
procedure EditMonPortChange(Sender: TObject);
procedure EditServerAddrChange(Sender: TObject);
procedure EditServerPortChange(Sender: TObject);
procedure CheckBoxDynamicIPModeClick(Sender: TObject);
procedure ButtonRestoreNetClick(Sender: TObject);
procedure ButtonSaveClick(Sender: TObject);
procedure ButtonCloseClick(Sender: TObject);
procedure CheckBoxMinimizeClick(Sender: TObject);
procedure CheckBoxRandomCodeClick(Sender: TObject);
private
{ Private declarations }
procedure LockSaveButtonEnabled();
procedure UnLockSaveButtonEnabled();
public
{ Public declarations }
procedure OpenBasicSet();
end;
var
FrmBasicSet: TFrmBasicSet;
implementation
uses HUtil32, LSShare;
var
Config: pTConfig;
{$R *.dfm}
procedure TFrmBasicSet.LockSaveButtonEnabled();
begin
ButtonSave.Enabled := False;
end;
procedure TFrmBasicSet.UnLockSaveButtonEnabled();
begin
ButtonSave.Enabled := True;
end;
procedure TFrmBasicSet.OpenBasicSet();
begin
Config := @g_Config;
CheckBoxTestServer.Checked := Config.boTestServer;
CheckBoxEnableMakingID.Checked := Config.boEnableMakingID;
CheckBoxEnableGetbackPassword.Checked := Config.boEnableGetbackPassword;
CheckBoxAutoClear.Checked := Config.boAutoClearID;
SpinEditAutoClearTime.Value := Config.dwAutoClearTime;
CheckBoxAutoUnLockAccount.Checked := Config.boUnLockAccount;
SpinEditUnLockAccountTime.Value := Config.dwUnLockAccountTime;
EditGateAddr.Text := Config.sGateAddr;
EditGatePort.Text := IntToStr(Config.nGatePort);
EditServerAddr.Text := Config.sServerAddr;
EditServerPort.Text := IntToStr(Config.nServerPort);
EditMonAddr.Text := Config.sMonAddr;
EditMonPort.Text := IntToStr(Config.nMonPort);
CheckBoxDynamicIPMode.Checked := Config.boDynamicIPMode;
CheckBoxMinimize.Checked := Config.boMinimize;
// CheckBoxRandomCode.Checked := Config.boRandomCode; //20080614 去掉验证码功能
LockSaveButtonEnabled();
ShowModal;
end;
procedure TFrmBasicSet.CheckBoxTestServerClick(Sender: TObject);
begin
Config := @g_Config;
Config.boTestServer := CheckBoxTestServer.Checked;
UnLockSaveButtonEnabled();
end;
procedure TFrmBasicSet.CheckBoxEnableMakingIDClick(Sender: TObject);
begin
Config := @g_Config;
Config.boEnableMakingID := CheckBoxEnableMakingID.Checked;
UnLockSaveButtonEnabled();
end;
procedure TFrmBasicSet.CheckBoxEnableGetbackPasswordClick(Sender: TObject);
begin
Config := @g_Config;
Config.boEnableGetbackPassword := CheckBoxEnableGetbackPassword.Checked;
UnLockSaveButtonEnabled();
end;
procedure TFrmBasicSet.CheckBoxAutoClearClick(Sender: TObject);
begin
Config := @g_Config;
Config.boAutoClearID := CheckBoxAutoClear.Checked;
UnLockSaveButtonEnabled();
end;
procedure TFrmBasicSet.SpinEditAutoClearTimeChange(Sender: TObject);
begin
Config := @g_Config;
Config.dwAutoClearTime := SpinEditAutoClearTime.Value;
UnLockSaveButtonEnabled();
end;
procedure TFrmBasicSet.CheckBoxAutoUnLockAccountClick(Sender: TObject);
begin
Config := @g_Config;
Config.boUnLockAccount := CheckBoxAutoUnLockAccount.Checked;
UnLockSaveButtonEnabled();
end;
procedure TFrmBasicSet.SpinEditUnLockAccountTimeChange(Sender: TObject);
begin
Config := @g_Config;
Config.dwUnLockAccountTime := SpinEditUnLockAccountTime.Value;
UnLockSaveButtonEnabled();
end;
procedure TFrmBasicSet.ButtonRestoreBasicClick(Sender: TObject);
begin
Config := @g_Config;
CheckBoxTestServer.Checked := True;
CheckBoxEnableMakingID.Checked := True;
CheckBoxEnableGetbackPassword.Checked := True;
CheckBoxAutoClear.Checked := True;
SpinEditAutoClearTime.Value := 1;
CheckBoxAutoUnLockAccount.Checked := False;
SpinEditUnLockAccountTime.Value := 10;
end;
procedure TFrmBasicSet.EditGateAddrChange(Sender: TObject);
begin
Config := @g_Config;
Config.sGateAddr := Trim(EditGateAddr.Text);
UnLockSaveButtonEnabled();
end;
procedure TFrmBasicSet.EditGatePortChange(Sender: TObject);
begin
Config := @g_Config;
Config.nGatePort := Str_ToInt(Trim(EditGatePort.Text), 5500);
UnLockSaveButtonEnabled();
end;
procedure TFrmBasicSet.EditMonAddrChange(Sender: TObject);
begin
Config := @g_Config;
Config.sMonAddr := Trim(EditMonAddr.Text);
UnLockSaveButtonEnabled();
end;
procedure TFrmBasicSet.EditMonPortChange(Sender: TObject);
begin
Config := @g_Config;
Config.nMonPort := Str_ToInt(Trim(EditMonPort.Text), 3000);
UnLockSaveButtonEnabled();
end;
procedure TFrmBasicSet.EditServerAddrChange(Sender: TObject);
begin
Config := @g_Config;
Config.sServerAddr := Trim(EditServerAddr.Text);
UnLockSaveButtonEnabled();
end;
procedure TFrmBasicSet.EditServerPortChange(Sender: TObject);
begin
Config := @g_Config;
Config.nServerPort := Str_ToInt(Trim(EditServerPort.Text), 5600);
UnLockSaveButtonEnabled();
end;
procedure TFrmBasicSet.CheckBoxDynamicIPModeClick(Sender: TObject);
begin
Config := @g_Config;
Config.boDynamicIPMode := CheckBoxDynamicIPMode.Checked;
UnLockSaveButtonEnabled();
end;
procedure TFrmBasicSet.ButtonRestoreNetClick(Sender: TObject);
begin
EditGateAddr.Text := '0.0.0.0';
EditGatePort.Text := '5500';
EditServerAddr.Text := '0.0.0.0';
EditServerPort.Text := '5600';
EditMonAddr.Text := '0.0.0.0';
EditMonPort.Text := '3000';
CheckBoxDynamicIPMode.Checked := False;
end;
procedure WriteConfig(Config: pTConfig);
procedure WriteConfigString(sSection, sIdent, sDefault: string);
begin
Config.IniConf.WriteString(sSection, sIdent, sDefault);
end;
procedure WriteConfigInteger(sSection, sIdent: string; nDefault: Integer);
begin
Config.IniConf.WriteInteger(sSection, sIdent, nDefault);
end;
procedure WriteConfigBoolean(sSection, sIdent: string; boDefault: Boolean);
begin
Config.IniConf.WriteBool(sSection, sIdent, boDefault);
end;
resourcestring
sSectionServer = 'Server';
sSectionDB = 'DB';
sIdentDBServer = 'DBServer';
sIdentFeeServer = 'FeeServer';
sIdentLogServer = 'LogServer';
sIdentGateAddr = 'GateAddr';
sIdentGatePort = 'GatePort';
sIdentServerAddr = 'ServerAddr';
sIdentServerPort = 'ServerPort';
sIdentMonAddr = 'MonAddr';
sIdentMonPort = 'MonPort';
sIdentDBSPort = 'DBSPort';
sIdentFeePort = 'FeePort';
sIdentLogPort = 'LogPort';
sIdentReadyServers = 'ReadyServers';
sIdentTestServer = 'TestServer';
sIdentDynamicIPMode = 'DynamicIPMode';
sIdentIdDir = 'IdDir';
sIdentWebLogDir = 'WebLogDir';
sIdentCountLogDir = 'CountLogDir';
sIdentFeedIDList = 'FeedIDList';
sIdentFeedIPList = 'FeedIPList';
sIdentEnableGetbackPassword = 'GetbackPassword';
sIdentAutoClearID = 'AutoClearID';
sIdentAutoClearTime = 'AutoClearTime';
sIdentUnLockAccount = 'UnLockAccount';
sIdentUnLockAccountTime = 'UnLockAccountTime';
sIdentMinimize = 'Minimize';
//sIdentRandomCode = 'RandomCode'; //20080614 去掉验证码功能
begin
WriteConfigString(sSectionServer, sIdentDBServer, Config.sDBServer);
WriteConfigString(sSectionServer, sIdentFeeServer, Config.sFeeServer);
WriteConfigString(sSectionServer, sIdentLogServer, Config.sLogServer);
WriteConfigString(sSectionServer, sIdentGateAddr, Config.sGateAddr);
WriteConfigInteger(sSectionServer, sIdentGatePort, Config.nGatePort);
WriteConfigString(sSectionServer, sIdentServerAddr, Config.sServerAddr);
WriteConfigInteger(sSectionServer, sIdentServerPort, Config.nServerPort);
WriteConfigString(sSectionServer, sIdentMonAddr, Config.sMonAddr);
WriteConfigInteger(sSectionServer, sIdentMonPort, Config.nMonPort);
WriteConfigInteger(sSectionServer, sIdentDBSPort, Config.nDBSPort);
WriteConfigInteger(sSectionServer, sIdentFeePort, Config.nFeePort);
WriteConfigInteger(sSectionServer, sIdentLogPort, Config.nLogPort);
WriteConfigInteger(sSectionServer, sIdentReadyServers, Config.nReadyServers);
WriteConfigBoolean(sSectionServer, sIdentTestServer, Config.boEnableMakingID);
WriteConfigBoolean(sSectionServer, sIdentEnableGetbackPassword, Config.boEnableGetbackPassword);
WriteConfigBoolean(sSectionServer, sIdentAutoClearID, Config.boAutoClearID);
WriteConfigInteger(sSectionServer, sIdentAutoClearTime, Config.dwAutoClearTime);
WriteConfigBoolean(sSectionServer, sIdentUnLockAccount, Config.boUnLockAccount);
WriteConfigInteger(sSectionServer, sIdentUnLockAccountTime, Config.dwUnLockAccountTime);
WriteConfigBoolean(sSectionServer, sIdentDynamicIPMode, Config.boDynamicIPMode);
WriteConfigBoolean(sSectionServer, sIdentMinimize, Config.boMinimize);
// WriteConfigBoolean(sSectionServer, sIdentRandomCode, Config.boRandomCode); //20080614 去掉验证码功能
WriteConfigString(sSectionDB, sIdentIdDir, Config.sIdDir);
WriteConfigString(sSectionDB, sIdentWebLogDir, Config.sWebLogDir);
WriteConfigString(sSectionDB, sIdentCountLogDir, Config.sCountLogDir);
WriteConfigString(sSectionDB, sIdentFeedIDList, Config.sFeedIDList);
WriteConfigString(sSectionDB, sIdentFeedIPList, Config.sFeedIPList);
end;
procedure TFrmBasicSet.ButtonSaveClick(Sender: TObject);
begin
WriteConfig(Config);
LockSaveButtonEnabled();
end;
procedure TFrmBasicSet.ButtonCloseClick(Sender: TObject);
begin
Close;
end;
procedure TFrmBasicSet.CheckBoxMinimizeClick(Sender: TObject);
begin
Config := @g_Config;
Config.boMinimize := CheckBoxMinimize.Checked;
UnLockSaveButtonEnabled();
end;
procedure TFrmBasicSet.CheckBoxRandomCodeClick(Sender: TObject);
begin
{Config := @g_Config; //20080614 去掉验证码功能
Config.boRandomCode := CheckBoxRandomCode.Checked;
UnLockSaveButtonEnabled(); }
end;
end.
|
unit uHIDUsage;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, GlobalTypes;
const
// global usage
HID_USAGE_UNDEFINED = $00;
HID_USAGE_DESKTOP = $01;
HID_USAGE_SIMULATION_CONTROL = $02;
HID_USAGE_VR_CONTROL = $03;
HID_USAGE_SPORT_CONTROL = $04;
HID_USAGE_GAME_CONTROL = $05;
HID_USAGE_GENERIC_CONTROL = $06;
HID_USAGE_KEYBOARD = $07;
HID_USAGE_LEDS = $08;
HID_USAGE_BUTTON = $09;
HID_USAGE_ORDINAL = $0A;
HID_USAGE_TELEPHONY = $0B;
HID_USAGE_CUSTOMER = $0C;
HID_USAGE_DIGITISER = $0D;
HID_USAGE_PID_PAGE = $0F;
HID_USAGE_UNICODE = $10;
HID_USAGE_ALPHA_DISPLAY = $14;
HID_USAGE_MEDICAL = $40;
HID_USAGE_BAR_CODE = $8C;
HID_USAGE_SCALE = $8D;
HID_USAGE_MSR = $8E; // magnetic strip readers
HID_USAGE_POS = $8F; // point of sale
HID_USAGE_CAMERA = $90;
HID_USAGE_ARCADE = $91;
HID_USAGE_VENDOR = $FF;
// desktop local usage
DESkTOP_USAGE_UNDEFINED = $00;
DESkTOP_USAGE_POINTER = $01;
DESkTOP_USAGE_MOUSE = $02;
DESkTOP_USAGE_JOYSTICK = $04;
DESkTOP_USAGE_GAME_PAD = $05;
DESkTOP_USAGE_KEYBOARD = $06;
DESkTOP_USAGE_KEYPAD = $07;
DESkTOP_USAGE_MULTI_AXIS = $08;
DESkTOP_USAGE_TABLET = $09;
DESkTOP_USAGE_X = $30;
DESkTOP_USAGE_Y = $31;
DESkTOP_USAGE_Z = $32;
DESkTOP_USAGE_RX = $33;
DESkTOP_USAGE_RY = $34;
DESkTOP_USAGE_RZ = $35;
DESkTOP_USAGE_SLIDER = $36;
DESkTOP_USAGE_DIAL = $37;
DESkTOP_USAGE_WHEEL = $38;
DESkTOP_USAGE_HAT = $39;
DESkTOP_USAGE_COUNTED = $3A;
DESkTOP_USAGE_BYTE_COUNT = $3B;
DESkTOP_USAGE_MOTION_WAKEUP = $3C;
DESkTOP_USAGE_START = $3D;
DESkTOP_USAGE_SELECT = $3E;
DESkTOP_USAGE_VX = $40;
DESkTOP_USAGE_VY = $41;
DESkTOP_USAGE_VZ = $42;
DESkTOP_USAGE_VBRX = $43;
DESkTOP_USAGE_VBRY = $44;
DESkTOP_USAGE_VBRZ = $45;
DESkTOP_USAGE_VNO = $46;
DESkTOP_USAGE_FEATURE_NOTIFY = $47;
DESkTOP_USAGE_RES_MULTI = $48;
DESkTOP_USAGE_SYS_CONTROL = $80;
DESkTOP_USAGE_SYS_POWER_DOWN = $81;
DESkTOP_USAGE_SYS_SLEEP = $82;
DESkTOP_USAGE_SYS_WAKE_UP = $83;
DESkTOP_USAGE_SYS_CONTEXT_MENU = $84;
DESkTOP_USAGE_SYS_MAIN_MENU = $85;
DESkTOP_USAGE_SYS_APP_MENU = $86;
DESkTOP_USAGE_SYS_MENU_HELP = $87;
DESkTOP_USAGE_SYS_MENU_EXIT = $88;
DESkTOP_USAGE_SYS_MENU_SELECT = $89;
DESkTOP_USAGE_SYS_MENU_RIGHT = $8A;
DESkTOP_USAGE_SYS_MENU_LEFT = $8B;
DESkTOP_USAGE_SYS_MENU_UP = $8C;
DESkTOP_USAGE_SYS_MENU_DOWN = $8D;
DESkTOP_USAGE_SYS_COLD_RESTART = $8E;
DESkTOP_USAGE_SYS_WARM_RESTART = $8F;
DESkTOP_USAGE_DPAD_UP = $90;
DESkTOP_USAGE_DPAD_DOWN = $91;
DESkTOP_USAGE_DPAD_RIGHT = $92;
DESkTOP_USAGE_DPAD_LEFT = $93;
DESkTOP_USAGE_SYS_DOCK = $A0;
DESkTOP_USAGE_SYS_UNDOCK = $A1;
DESkTOP_USAGE_SYS_SETUP = $A2;
DESkTOP_USAGE_SYS_BREAK = $A3;
DESkTOP_USAGE_SYS_DEBUG_BREAK = $A4;
DESkTOP_USAGE_APP_BREAK = $A5;
DESkTOP_USAGE_APP_DEBUG_BREAK = $A6;
DESkTOP_USAGE_SYS_SPEAKER_MUTE = $A7;
DESkTOP_USAGE_SYS_HIBERNATE = $A8;
DESkTOP_USAGE_SYS_DISPLAY_INVERT = $B0;
DESkTOP_USAGE_SYS_DISPLAY_INTERNAL = $B1;
DESkTOP_USAGE_SYS_DISPLAY_EXTERNAL = $B2;
DESkTOP_USAGE_SYS_DISPLAY_BOTH = $B3;
DESkTOP_USAGE_SYS_DISPLAY_DUAL = $B4;
DESkTOP_USAGE_SYS_DISPLAY_TOGGLE = $B5;
DESkTOP_USAGE_SYS_DISPLAY_SWAP = $B6;
DESkTOP_USAGE_SYS_DISPLAY_AUTOSCALE = $B7;
// simulation local usage
SIM_USAGE_UNDEFINED = $00;
SIM_USAGE_FLIGHT = $01;
SIM_USAGE_AUTOMOBILE = $02;
SIM_USAGE_TANK = $03;
SIM_USAGE_SPACESHIP = $04;
SIM_USAGE_SUBMARINE = $05;
SIM_USAGE_SAILING = $06;
SIM_USAGE_MOTORCYCLE = $07;
SIM_USAGE_SPORTS = $08;
SIM_USAGE_AIRPLANE = $09;
SIM_USAGE_HELICOPTER = $0A;
SIM_USAGE_MAGIC_CARPET = $0B;
SIM_USAGE_BICYCLE = $0C;
SIM_USAGE_FLIGHT_CONTROL_STICK = $20;
SIM_USAGE_FLIGHT_STICK = $21;
SIM_USAGE_CYCLIC = $22;
SIM_USAGE_CYCLIC_TRIM = $23;
SIM_USAGE_FLIGHT_YOKE = $24;
SIM_USAGE_TRACK_CONTROL = $25;
SIM_USAGE_AILERON = $B0;
SIM_USAGE_AILERON_TRIM = $B1;
SIM_USAGE_ANTI_TORGUE = $B2;
SIM_USAGE_AUTOPILOT = $B3;
SIM_USAGE_CHAFF = $B4;
SIM_USAGE_COLLECTIVE = $B5;
SIM_USAGE_DIVE_BRAKE = $B6;
SIM_USAGE_COUNTERMEASURES = $B7;
SIM_USAGE_ELEVATOR = $B8;
SIM_USAGE_ELEVATOR_TRIM = $B9;
SIM_USAGE_RUDDER = $BA;
SIM_USAGE_THROTTLE = $BB;
SIM_USAGE_FLIGHT_COMMS = $BC;
SIM_USAGE_FLARE = $BD;
SIM_USAGE_LANDING_GEAR = $BE;
SIM_USAGE_TOE_BRAKE = $BF;
SIM_USAGE_TRIGGER = $C0;
SIM_USAGE_WEAPONS_ARM = $C1;
SIM_USAGE_WEAPONS_SELECT = $C2;
SIM_USAGE_WING_FLAPS = $C3;
SIM_USAGE_ACCELERATOR = $C4;
SIM_USAGE_BRAKE = $C5;
SIM_USAGE_CLUTCH = $C6;
SIM_USAGE_SHIFTER = $C7;
SIM_USAGE_STEERING = $C8;
SIM_USAGE_TURRET_DIRECTION = $C9;
SIM_USAGE_BARREL_ELEVATION = $CA;
SIM_USAGE_DIVE_PLANE = $CB;
SIM_USAGE_BALLAST = $CC;
SIM_USAGE_BICYCLE_CRANK = $CD;
SIM_USAGE_HANDLE_BARS = $CE;
SIM_USAGE_FRONT_BRAKE = $CF;
SIM_USAGE_REAR_BRAKE = $D0;
// vr local usage
VR_UASGE_UNIDENTIFIED = $00;
VR_UASGE_BELT = $01;
VR_UASGE_BODY_SUIT = $02;
VR_UASGE_FLEXOR = $03;
VR_UASGE_GOVE = $04;
VR_UASGE_HEAD_TRACKER = $05;
VR_UASGE_HEAD_MOUNTED_DISPLAY = $06;
VR_UASGE_HAND_TRACKER = $07;
VR_UASGE_OCULOLEMETR = $08;
VR_UASGE_VEST = $09;
VR_UASGE_ANIMATRONIC = $0A;
VR_UASGE_STEREO_ENABLE = $20;
VR_UASGE_DISPLAY_ENABLE = $21;
// sports local usage
SPORTS_USAGE_UNIDENTIFIED = $00;
SPORTS_USAGE_BASEBALL_BAT = $01;
SPORTS_USAGE_GOLF_CLUB = $02;
SPORTS_USAGE_ROWING_MACHINE = $03;
SPORTS_USAGE_TREADMILL = $04;
SPORTS_USAGE_OAR = $30;
SPORTS_USAGE_SLOPE = $31;
SPORTS_USAGE_RATE = $32;
SPORTS_USAGE_STICK_SPEED = $33;
SPORTS_USAGE_STICK_FACE_ANGLE = $34;
SPORTS_USAGE_STICK_HEEL = $35;
SPORTS_USAGE_STICK_FOLLOW_THROUGH = $36;
SPORTS_USAGE_STICK_TEMPO = $37;
SPORTS_USAGE_STICK_TYPE = $38;
SPORTS_USAGE_STICK_HEIGHT = $39;
SPORTS_USAGE_PUTTER = $50;
SPORTS_USAGE_1IRON = $51;
SPORTS_USAGE_2IRON = $52;
SPORTS_USAGE_3IRON = $53;
SPORTS_USAGE_4IRON = $54;
SPORTS_USAGE_5IRON = $55;
SPORTS_USAGE_6IRON = $56;
SPORTS_USAGE_7IRON = $57;
SPORTS_USAGE_8IRON = $58;
SPORTS_USAGE_9IRON = $59;
SPORTS_USAGE_10IRON = $5A;
SPORTS_USAGE_11IRON = $5B;
SPORTS_USAGE_SAND_WEDGE = $5C;
SPORTS_USAGE_LOFT_WEDGE = $5D;
SPORTS_USAGE_POWER_WEDGE = $5E;
SPORTS_USAGE_1WOOD = $5F;
SPORTS_USAGE_3WOOD = $60;
SPORTS_USAGE_5WOOD = $61;
SPORTS_USAGE_7WOOD = $62;
SPORTS_USAGE_9WOOD = $63;
// games local uaage
GAMES_USAGE_UNDEFINED = $00;
GAMES_USAGE_3D_CONTROLLER = $01;
GAMES_USAGE_PINBALL = $02;
GAMES_USAGE_GUN = $03;
GAMES_USAGE_POV = $20;
GAMES_USAGE_TURN = $21;
GAMES_USAGE_PITCH = $22;
GAMES_USAGE_ROLL = $23;
GAMES_USAGE_MOVE_LEFT_RIGHT = $24;
GAMES_USAGE_MOVE_FORWARD_BACKWARD = $25;
GAMES_USAGE_MOVE_UP_DOWN = $26;
GAMES_USAGE_LEAN_LEFT_RIGHT = $27;
GAMES_USAGE_LEAN_FORWARD_BACKWORD = $28;
GAMES_USAGE_POV_HEIGHT = $29;
GAMES_USAGE_FLIPPER = $2A;
GAMES_USAGE_SECONDAY_FLIFFER = $2B;
GAMES_USAGE_BUMP = $2C;
GAMES_USAGE_NEW_GAME = $2D;
GAMES_USAGE_SHOOT_BALL = $2E;
GAMES_USAGE_PLAYER = $2F;
GAMES_USAGE_GUN_BOLT = $30;
GAMES_USAGE_GUN_CLIP = $31;
GAMES_USAGE_GUN_SELECTOR = $32;
GAMES_USAGE_GUN_SINGLE_SHOT = $33;
GAMES_USAGE_GUN_BURST = $34;
GAMES_USAGE_GUN_AUTOMATIC = $35;
GAMES_USAGE_GUN_SAFETY = $36;
GAMES_USAGE_GAMEPAD_FIRE = $37;
GAMES_USAGE_GAMEPAD_TRIGGER = $39;
// generic local usage
GENERIC_USAGE_UNIDENTIFIED = $00;
GENERIC_USAGE_BATTERY_STRENGTH = $20;
GENERIC_USAGE_WIRELESS_CHANNEL = $21;
GENERIC_USAGE_WIRELESS_ID = $22;
GENERIC_USAGE_DISCOVER_WIRELESS = $23;
GENERIC_USAGE_CODE_CHAR_ENTERED = $24;
GENERIC_USAGE_CODE_CHAR_ERASED = $25;
GENERIC_USAGE_CODE_CLEARED = $26;
// telphony local usage
// consumer local usage
// digitiser local usage
DIGITISER_USAGE_UNDEFINED = $00;
DIGITISER_USAGE_DIGITISER = $01;
DIGITISER_USAGE_PEN = $02;
DIGITISER_USAGE_LIGHT_PEN = $03;
DIGITISER_USAGE_TOUCH_SCREEN = $04;
DIGITISER_USAGE_TOOUCH_PAD = $05;
DIGITISER_USAGE_WHITE_BOARD = $06;
DIGITISER_USAGE_COORD_MEASURING = $07;
DIGITISER_USAGE_3D_DIGITISER = $08;
DIGITISER_USAGE_STEREO_PLOTTER = $09;
DIGITISER_USAGE_ARTICULATED_ARM = $0A;
DIGITISER_USAGE_ARMATURE = $0B;
DIGITISER_USAGE_MULTI_POINT_DIGITISER = $0C;
DIGITISER_USAGE_FREE_SPACE_WAND = $0D;
DIGITISER_USAGE_STYLUS = $20;
DIGITISER_USAGE_PUCK = $21;
DIGITISER_USAGE_FINGER = $22;
DIGITISER_USAGE_TIP_PRESSURE = $30;
DIGITISER_USAGE_BARREL_PRESSURE = $31;
DIGITISER_USAGE_IN_RANGE = $32;
DIGITISER_USAGE_TOUCH = $33;
DIGITISER_USAGE_UNTOUCH = $34;
DIGITISER_USAGE_TAP = $35;
DIGITISER_USAGE_QUALITY = $36;
DIGITISER_USAGE_DATA_VALID = $37;
DIGITISER_USAGE_TRANSDUCER_INDEX = $38;
DIGITISER_USAGE_TABLET_FUNCTION_KEYS = $39;
DIGITISER_USAGE_PROGRAM_CHANGE_KEYS = $3A;
DIGITISER_USAGE_BATTERY_STRENGTH = $3B;
DIGITISER_USAGE_INVERT = $3C;
DIGITISER_USAGE_X_TILT = $3D;
DIGITISER_USAGE_Y_TILT = $3E;
DIGITISER_USAGE_AZIMUTH = $3F;
DIGITISER_USAGE_ALTITUDE = $40;
DIGITISER_USAGE_TWIST = $41;
DIGITISER_USAGE_TIP_SWITCH = $42;
DIGITISER_USAGE_SECONDARY_TIP_SWITCH = $43;
DIGITISER_USAGE_BARREL_SWITCH = $44;
DIGITISER_USAGE_ERASER = $45;
DIGITISER_USAGE_TABLET_PICK = $46;
function HIDUsageToStr (Usage : byte) : string;
function LocalUsageToStr (Page, Usage : byte) : string;
function DesktopLocalUsageToStr (Usage : byte) : string;
function SportsLocalUsageToStr (Usage : byte) : string;
function GamesLocalUsageToStr (Usage : byte) : string;
function SimLocalUsageToStr (Usage : byte) : string;
function DigitiserLocalUsageToStr (Usage : byte) : string;
function GenericLocalUsageToStr (Usage : byte) : string;
function VRLocalUsageToStr (Usage : byte) : string;
function InputToStr (ip : byte) : string;
procedure PrintHIDUsage (b : array of byte);
implementation
uses uLog;
function LocalUsageToStr (Page, Usage : byte) : string;
begin
case Page of
HID_USAGE_DESKTOP : Result := DesktopLocalUsageToStr (Usage);
HID_USAGE_SIMULATION_CONTROL : Result := SimLocalUsageToStr (Usage);
HID_USAGE_SPORT_CONTROL : Result := SportsLocalUsageToStr (Usage);
HID_USAGE_GAME_CONTROL : Result := GamesLocalUsageToStr (Usage);
HID_USAGE_VR_CONTROL : Result := VRLocalUsageToStr (Usage);
HID_USAGE_DIGITISER : Result := DigitiserLocalUsageToStr (Usage);
HID_USAGE_GENERIC_CONTROL : Result := GenericLocalUsageToStr (Usage);
else Result := Usage.ToHexString (2);
end;
end;
function HIDUsageToStr (Usage : byte) : string;
begin
case Usage of
HID_USAGE_UNDEFINED : Result := 'Undefined';
HID_USAGE_DESKTOP : Result := 'Desktop';
HID_USAGE_SIMULATION_CONTROL : Result := 'Simulation';
HID_USAGE_VR_CONTROL : Result := 'VR';
HID_USAGE_SPORT_CONTROL : Result := 'Sport';
HID_USAGE_GAME_CONTROL : Result := 'Game';
HID_USAGE_GENERIC_CONTROL : Result := 'Generic';
HID_USAGE_KEYBOARD : Result := 'Keyboard';
HID_USAGE_LEDS : Result := 'LEDS';
HID_USAGE_BUTTON : Result := 'Button';
HID_USAGE_ORDINAL : Result := 'Ordinal';
HID_USAGE_TELEPHONY : Result := 'Telphony';
HID_USAGE_CUSTOMER : Result := 'Customer';
HID_USAGE_DIGITISER : Result := 'Digitiser';
HID_USAGE_PID_PAGE : Result := 'PID Page';
HID_USAGE_UNICODE : Result := 'Unicode';
HID_USAGE_ALPHA_DISPLAY : Result := 'Aplhanumeric Display';
HID_USAGE_MEDICAL : Result := 'Medical';
HID_USAGE_BAR_CODE : Result := 'Bar Code Scanner';
HID_USAGE_SCALE : Result := 'Scale';
HID_USAGE_MSR : Result := 'Magnetic Strip Reader';
HID_USAGE_POS : Result := 'Point of Sale';
HID_USAGE_CAMERA : Result := 'Camera';
HID_USAGE_ARCADE : Result := 'Arcade';
HID_USAGE_VENDOR : Result := 'Vendor Specific';
else Result := Usage.ToHexString (4);
end;
end;
function DesktopLocalUsageToStr (Usage : byte) : string;
begin
case Usage of
DESkTOP_USAGE_UNDEFINED : Result := 'Undefined';
DESkTOP_USAGE_POINTER : Result := 'Pointer';
DESkTOP_USAGE_MOUSE : Result := 'Mouse';
DESkTOP_USAGE_JOYSTICK : Result := 'Joystick';
DESkTOP_USAGE_GAME_PAD : Result := 'Game Pad';
DESkTOP_USAGE_KEYBOARD : Result := 'Keyboard';
DESkTOP_USAGE_KEYPAD : Result := 'Keypad';
DESkTOP_USAGE_MULTI_AXIS : Result := 'Multi Axis Controller';
DESkTOP_USAGE_TABLET : Result := 'Tablet';
DESkTOP_USAGE_X : Result := 'X';
DESkTOP_USAGE_Y : Result := 'Y';
DESkTOP_USAGE_Z : Result := 'Z';
DESkTOP_USAGE_RX : Result := 'RX';
DESkTOP_USAGE_RY : Result := 'RY';
DESkTOP_USAGE_RZ : Result := 'RZ';
DESkTOP_USAGE_SLIDER : Result := 'Slider';
DESkTOP_USAGE_DIAL : Result := 'Dial';
DESkTOP_USAGE_WHEEL : Result := 'Wheel';
DESkTOP_USAGE_HAT : Result := 'Hat';
DESkTOP_USAGE_COUNTED : Result := 'Conted Buffer';
DESkTOP_USAGE_BYTE_COUNT : Result := 'Byte Count';
DESkTOP_USAGE_MOTION_WAKEUP : Result := 'Motion Wakeup';
DESkTOP_USAGE_START : Result := 'Start';
DESkTOP_USAGE_SELECT : Result := 'Select';
DESkTOP_USAGE_VX : Result := 'VX';
DESkTOP_USAGE_VY : Result := 'VY';
DESkTOP_USAGE_VZ : Result := 'VZ';
DESkTOP_USAGE_VBRX : Result := 'VBRX';
DESkTOP_USAGE_VBRY : Result := 'VBRY';
DESkTOP_USAGE_VBRZ : Result := 'VBRZ';
DESkTOP_USAGE_VNO : Result := 'V No';
DESkTOP_USAGE_FEATURE_NOTIFY : Result := 'Feature Notification';
DESkTOP_USAGE_RES_MULTI : Result := 'Multi Resolution';
DESkTOP_USAGE_SYS_CONTROL : Result := 'System Control';
DESkTOP_USAGE_SYS_POWER_DOWN : Result := 'System Power Down';
DESkTOP_USAGE_SYS_SLEEP : Result := 'System Sleep';
DESkTOP_USAGE_SYS_WAKE_UP : Result := 'System Wakeup';
DESkTOP_USAGE_SYS_CONTEXT_MENU : Result := 'Context Menu';
DESkTOP_USAGE_SYS_MAIN_MENU : Result := 'Main Menu';
DESkTOP_USAGE_SYS_APP_MENU : Result := 'App Menu';
DESkTOP_USAGE_SYS_MENU_HELP : Result := 'Menu Help';
DESkTOP_USAGE_SYS_MENU_EXIT : Result := 'Menu Exit';
DESkTOP_USAGE_SYS_MENU_SELECT : Result := 'Menu Select';
DESkTOP_USAGE_SYS_MENU_RIGHT : Result := 'Menu Right';
DESkTOP_USAGE_SYS_MENU_LEFT : Result := 'Menu Left';
DESkTOP_USAGE_SYS_MENU_UP : Result := 'Menu Up';
DESkTOP_USAGE_SYS_MENU_DOWN : Result := 'Menu Down';
DESkTOP_USAGE_SYS_COLD_RESTART : Result := 'Cold Restart';
DESkTOP_USAGE_SYS_WARM_RESTART : Result := 'Warn Restart';
DESkTOP_USAGE_DPAD_UP : Result := 'DPAD Up';
DESkTOP_USAGE_DPAD_DOWN : Result := 'DPAD Down';
DESkTOP_USAGE_DPAD_RIGHT : Result := 'DPAD Right';
DESkTOP_USAGE_DPAD_LEFT : Result := 'DPAD Left';
DESkTOP_USAGE_SYS_DOCK : Result := 'Dock';
DESkTOP_USAGE_SYS_UNDOCK : Result := 'Undock';
DESkTOP_USAGE_SYS_SETUP : Result := 'Setup';
DESkTOP_USAGE_SYS_BREAK : Result := 'Break';
DESkTOP_USAGE_SYS_DEBUG_BREAK : Result := 'Debugger Break';
DESkTOP_USAGE_APP_BREAK : Result := 'App Break';
DESkTOP_USAGE_APP_DEBUG_BREAK : Result := 'App Debugger Break';
DESkTOP_USAGE_SYS_SPEAKER_MUTE : Result := 'Speaker Mute';
DESkTOP_USAGE_SYS_HIBERNATE : Result := 'Hibernate';
DESkTOP_USAGE_SYS_DISPLAY_INVERT : Result := 'Display Invert';
DESkTOP_USAGE_SYS_DISPLAY_INTERNAL : Result := 'Display Internal';
DESkTOP_USAGE_SYS_DISPLAY_EXTERNAL : Result := 'Display External';
DESkTOP_USAGE_SYS_DISPLAY_BOTH : Result := 'Display Both';
DESkTOP_USAGE_SYS_DISPLAY_DUAL : Result := 'Display Dual';
DESkTOP_USAGE_SYS_DISPLAY_TOGGLE : Result := 'Display Toggle';
DESkTOP_USAGE_SYS_DISPLAY_SWAP : Result := 'Display Swap';
DESkTOP_USAGE_SYS_DISPLAY_AUTOSCALE : Result := 'Display Autoscale';
else Result := 'Reserved (' + Usage.ToHexString (4) + ')';
end;
end;
function SimLocalUsageToStr (Usage : byte) : string;
begin
case Usage of
SIM_USAGE_UNDEFINED : Result := 'Undefined';
SIM_USAGE_FLIGHT : Result := 'Flight';
SIM_USAGE_AUTOMOBILE : Result := 'Automobile';
SIM_USAGE_TANK : Result := 'Tank';
SIM_USAGE_SPACESHIP : Result := 'Space Ship';
SIM_USAGE_SUBMARINE : Result := 'Submarine';
SIM_USAGE_SAILING : Result := 'Sailing';
SIM_USAGE_MOTORCYCLE : Result := 'Motor Cycle';
SIM_USAGE_SPORTS : Result := 'Sports';
SIM_USAGE_AIRPLANE : Result := 'Airplane';
SIM_USAGE_HELICOPTER : Result := 'Helicopter';
SIM_USAGE_MAGIC_CARPET : Result := 'Magic Carpet';
SIM_USAGE_BICYCLE : Result := 'Bicycle';
SIM_USAGE_FLIGHT_CONTROL_STICK : Result := 'Flight Control Stick';
SIM_USAGE_FLIGHT_STICK : Result := 'Flight stick';
SIM_USAGE_CYCLIC : Result := 'Cyclic';
SIM_USAGE_CYCLIC_TRIM : Result := 'Cyclic Trim';
SIM_USAGE_FLIGHT_YOKE : Result := 'Flight Yoke';
SIM_USAGE_TRACK_CONTROL : Result := 'Track Control';
SIM_USAGE_AILERON : Result := 'Aileron';
SIM_USAGE_AILERON_TRIM : Result := 'Aileron Trim';
SIM_USAGE_ANTI_TORGUE : Result := 'Anti Torgue';
SIM_USAGE_AUTOPILOT : Result := 'Auto Pilot';
SIM_USAGE_CHAFF : Result := 'Chaff';
SIM_USAGE_COLLECTIVE : Result := 'Collective';
SIM_USAGE_DIVE_BRAKE : Result := 'Dive Brake';
SIM_USAGE_COUNTERMEASURES : Result := 'Counter Measures';
SIM_USAGE_ELEVATOR : Result := 'Elevator';
SIM_USAGE_ELEVATOR_TRIM : Result := 'Elevator Trim';
SIM_USAGE_RUDDER : Result := 'Rudder';
SIM_USAGE_THROTTLE : Result := 'Throttle';
SIM_USAGE_FLIGHT_COMMS : Result := 'Flight Comms';
SIM_USAGE_FLARE : Result := 'Flare';
SIM_USAGE_LANDING_GEAR : Result := 'Landing Gear';
SIM_USAGE_TOE_BRAKE : Result := 'Toe Brake';
SIM_USAGE_TRIGGER : Result := 'Trigger';
SIM_USAGE_WEAPONS_ARM : Result := 'Weapons Arm';
SIM_USAGE_WEAPONS_SELECT : Result := 'Weapoms Select';
SIM_USAGE_WING_FLAPS : Result := 'Wing Flaps';
SIM_USAGE_ACCELERATOR : Result := 'Accelerator';
SIM_USAGE_BRAKE : Result := 'Brake';
SIM_USAGE_CLUTCH : Result := 'Clutch';
SIM_USAGE_SHIFTER : Result := 'Shifter';
SIM_USAGE_STEERING : Result := 'Steering';
SIM_USAGE_TURRET_DIRECTION : Result := 'Turret Direction';
SIM_USAGE_BARREL_ELEVATION : Result := 'Barrel Elevation';
SIM_USAGE_DIVE_PLANE : Result := 'Dive Plane';
SIM_USAGE_BALLAST : Result := 'Ballast';
SIM_USAGE_BICYCLE_CRANK : Result := 'Bicycle Crank';
SIM_USAGE_HANDLE_BARS : Result := 'Handle Bars';
SIM_USAGE_FRONT_BRAKE : Result := 'Fromt Brake';
SIM_USAGE_REAR_BRAKE : Result := 'Read Brake';
else Result := 'Reserved (' + Usage.ToHexString (4) + ')';
end;
end;
function SportsLocalUsageToStr (Usage : byte) : string;
begin
case Usage of
SPORTS_USAGE_UNIDENTIFIED : Result := 'Undefined';
SPORTS_USAGE_BASEBALL_BAT : Result := 'Baseball Bat';
SPORTS_USAGE_GOLF_CLUB : Result := 'Golf Club';
SPORTS_USAGE_ROWING_MACHINE : Result := 'Rowing Machine';
SPORTS_USAGE_TREADMILL : Result := 'Tradmill';
SPORTS_USAGE_OAR : Result := 'Oar';
SPORTS_USAGE_SLOPE : Result := 'Slope';
SPORTS_USAGE_RATE : Result := 'Rate';
SPORTS_USAGE_STICK_SPEED : Result := 'Stick Speed';
SPORTS_USAGE_STICK_FACE_ANGLE : Result := 'Stick face Angle';
SPORTS_USAGE_STICK_HEEL : Result := 'Stick Heel';
SPORTS_USAGE_STICK_FOLLOW_THROUGH : Result := 'Stick Follow Through';
SPORTS_USAGE_STICK_TEMPO : Result := 'Stick Tempo';
SPORTS_USAGE_STICK_TYPE : Result := 'stick Type';
SPORTS_USAGE_STICK_HEIGHT : Result := 'Stick Height';
SPORTS_USAGE_PUTTER : Result := 'Putter';
SPORTS_USAGE_1IRON : Result := '1 Iron';
SPORTS_USAGE_2IRON : Result := '2 Iron';
SPORTS_USAGE_3IRON : Result := '3 Iron';
SPORTS_USAGE_4IRON : Result := '4 Iron';
SPORTS_USAGE_5IRON : Result := '5 Iron';
SPORTS_USAGE_6IRON : Result := '6 Iron';
SPORTS_USAGE_7IRON : Result := '7 Iron';
SPORTS_USAGE_8IRON : Result := '8 Iron';
SPORTS_USAGE_9IRON : Result := '9 Iron';
SPORTS_USAGE_10IRON : Result := '10 Iron';
SPORTS_USAGE_11IRON : Result := '11 Iron';
SPORTS_USAGE_SAND_WEDGE : Result := 'Sand Wedge';
SPORTS_USAGE_LOFT_WEDGE : Result := 'Loft Wedge';
SPORTS_USAGE_POWER_WEDGE : Result := 'Power Wwedge';
SPORTS_USAGE_1WOOD : Result := '1 Wood';
SPORTS_USAGE_3WOOD : Result := '3 Wood';
SPORTS_USAGE_5WOOD : Result := '5 Wood';
SPORTS_USAGE_7WOOD : Result := '7 Wood';
SPORTS_USAGE_9WOOD : Result := '9 Wood';
else Result := 'Reserved (' + Usage.ToHexString (4) + ')';
end;
end;
function GamesLocalUsageToStr (Usage : byte) : string;
begin
case Usage of
GAMES_USAGE_UNDEFINED : Result := 'Undefined';
GAMES_USAGE_3D_CONTROLLER : Result := '3D Controller';
GAMES_USAGE_PINBALL : Result := 'Pinball';
GAMES_USAGE_GUN : Result := 'Gun';
GAMES_USAGE_POV : Result := 'Point of View';
GAMES_USAGE_TURN : Result := 'Turn';
GAMES_USAGE_PITCH : Result := 'Pitch';
GAMES_USAGE_ROLL : Result := 'Roll';
GAMES_USAGE_MOVE_LEFT_RIGHT : Result := 'Move Left/Right';
GAMES_USAGE_MOVE_FORWARD_BACKWARD : Result := 'Move Forward/Backward';
GAMES_USAGE_MOVE_UP_DOWN : Result := 'Move Up/Down';
GAMES_USAGE_LEAN_LEFT_RIGHT : Result := 'Lean Left/Right';
GAMES_USAGE_LEAN_FORWARD_BACKWORD : Result := 'Lean Forward/Backward';
GAMES_USAGE_POV_HEIGHT : Result := 'POV Height';
GAMES_USAGE_FLIPPER : Result := 'Flipper';
GAMES_USAGE_SECONDAY_FLIFFER : Result := 'scondary Flipper';
GAMES_USAGE_BUMP : Result := 'Bump';
GAMES_USAGE_NEW_GAME : Result := 'New Game';
GAMES_USAGE_SHOOT_BALL : Result := 'Shoot Ball';
GAMES_USAGE_PLAYER : Result := 'Player';
GAMES_USAGE_GUN_BOLT : Result := 'Gun Bolt';
GAMES_USAGE_GUN_CLIP : Result := 'Gun Clip';
GAMES_USAGE_GUN_SELECTOR : Result := 'Gun Selector';
GAMES_USAGE_GUN_SINGLE_SHOT : Result := 'Gun Single Shot';
GAMES_USAGE_GUN_BURST : Result := 'Gun Burst';
GAMES_USAGE_GUN_AUTOMATIC : Result := 'Gun Automatic';
GAMES_USAGE_GUN_SAFETY : Result := 'Gun Safety';
GAMES_USAGE_GAMEPAD_FIRE : Result := 'Gamepad Fire';
GAMES_USAGE_GAMEPAD_TRIGGER : Result := 'FGmepad Trigger';
else Result := 'Reserved (' + Usage.ToHexString (4) + ')';
end;
end;
function DigitiserLocalUsageToStr (Usage : byte) : string;
begin
case Usage of
DIGITISER_USAGE_UNDEFINED : Result := 'Undefined';
DIGITISER_USAGE_DIGITISER : Result := 'Digitiser';
DIGITISER_USAGE_PEN : Result := 'Pen';
DIGITISER_USAGE_LIGHT_PEN : Result := 'Light Pen';
DIGITISER_USAGE_TOUCH_SCREEN : Result := 'Touch Screen';
DIGITISER_USAGE_TOOUCH_PAD : Result := 'Touch Pad';
DIGITISER_USAGE_WHITE_BOARD : Result := 'White Board';
DIGITISER_USAGE_COORD_MEASURING : Result := 'Coordinate Measuring';
DIGITISER_USAGE_3D_DIGITISER : Result := '3D Digitiser';
DIGITISER_USAGE_STEREO_PLOTTER : Result := 'Stereo Plotter';
DIGITISER_USAGE_ARTICULATED_ARM : Result := 'Articulated Arm';
DIGITISER_USAGE_ARMATURE : Result := 'Armature';
DIGITISER_USAGE_MULTI_POINT_DIGITISER : Result := 'Multi Point Digitiser';
DIGITISER_USAGE_FREE_SPACE_WAND : Result := 'Free Space Wand';
DIGITISER_USAGE_STYLUS : Result := 'Stylus';
DIGITISER_USAGE_PUCK : Result := 'Puck';
DIGITISER_USAGE_FINGER : Result := 'Finger';
DIGITISER_USAGE_TIP_PRESSURE : Result := 'Tip Pressure';
DIGITISER_USAGE_BARREL_PRESSURE : Result := 'Barrel Pressure';
DIGITISER_USAGE_IN_RANGE : Result := 'In Range';
DIGITISER_USAGE_TOUCH : Result := 'Touch';
DIGITISER_USAGE_UNTOUCH : Result := 'Untouch';
DIGITISER_USAGE_TAP : Result := 'Tap';
DIGITISER_USAGE_QUALITY : Result := 'Quality';
DIGITISER_USAGE_DATA_VALID : Result := 'Data Valid';
DIGITISER_USAGE_TRANSDUCER_INDEX : Result := 'Transducer Index';
DIGITISER_USAGE_TABLET_FUNCTION_KEYS : Result := 'Tablet Function Keys';
DIGITISER_USAGE_PROGRAM_CHANGE_KEYS : Result := 'Program Change Keys';
DIGITISER_USAGE_BATTERY_STRENGTH : Result := 'Battery Strength';
DIGITISER_USAGE_INVERT : Result := 'Invert';
DIGITISER_USAGE_X_TILT : Result := 'X Tilt';
DIGITISER_USAGE_Y_TILT : Result := 'Y Tilt';
DIGITISER_USAGE_AZIMUTH : Result := 'Azimuth';
DIGITISER_USAGE_ALTITUDE : Result := 'Altitude';
DIGITISER_USAGE_TWIST : Result := 'Twist';
DIGITISER_USAGE_TIP_SWITCH : Result := 'Tip Switch';
DIGITISER_USAGE_SECONDARY_TIP_SWITCH : Result := 'Secondary Tip Switch';
DIGITISER_USAGE_BARREL_SWITCH : Result := 'Barrel Switch';
DIGITISER_USAGE_ERASER : Result := 'Eraser';
DIGITISER_USAGE_TABLET_PICK : Result := 'Tablet Pick';
else Result := 'Reserved (' + Usage.ToHexString (4) + ')';
end;
end;
function GenericLocalUsageToStr (Usage : byte) : string;
begin
case Usage of
GENERIC_USAGE_UNIDENTIFIED : Result := 'Unidentified';
GENERIC_USAGE_BATTERY_STRENGTH : Result := 'Battery Strength';
GENERIC_USAGE_WIRELESS_CHANNEL : Result := 'Wireless Channel';
GENERIC_USAGE_WIRELESS_ID : Result := 'Wireless ID';
GENERIC_USAGE_DISCOVER_WIRELESS : Result := 'Discover Wireless';
GENERIC_USAGE_CODE_CHAR_ENTERED : Result := 'Security Code Char Entered';
GENERIC_USAGE_CODE_CHAR_ERASED : Result := 'Security Code Char Erased';
GENERIC_USAGE_CODE_CLEARED : Result := 'Security Code Cleared';
else Result := 'Reserved (' + Usage.ToHexString (4) + ')';
end;
end;
function VRLocalUsageToStr (Usage : byte) : string;
begin
case Usage of
VR_UASGE_UNIDENTIFIED : Result := 'Unidentified';
VR_UASGE_BELT : Result := 'Belt';
VR_UASGE_BODY_SUIT : Result := 'Body Suit';
VR_UASGE_FLEXOR : Result := 'Flexor';
VR_UASGE_GOVE : Result := 'Glove';
VR_UASGE_HEAD_TRACKER : Result := 'Head Tracker';
VR_UASGE_HEAD_MOUNTED_DISPLAY : Result := 'Head Mounted Display';
VR_UASGE_HAND_TRACKER : Result := 'Hand Tracker';
VR_UASGE_OCULOLEMETR : Result := 'Oculolemeter';
VR_UASGE_VEST : Result := 'Vest';
VR_UASGE_ANIMATRONIC : Result := 'animatronic';
VR_UASGE_STEREO_ENABLE : Result := 'Stereo Enable';
VR_UASGE_DISPLAY_ENABLE : Result := 'Display Enable';
else Result := 'Reserved (' + Usage.ToHexString (4) + ')';
end;
end;
function InputToStr (ip : byte) : string;
begin
if ip and $01 = 0 then Result := 'Data,' else Result := 'Const,';
if ip and $02 = 0 then Result := Result + 'Array,' else Result := Result + 'Var,';
if ip and $04 = 0 then Result := Result + 'Abs' else Result := Result + 'Rel';
end;
procedure PrintHIDUsage (b : array of byte);
var
i, x : integer;
done : boolean;
cc : integer;
s : string;
page : byte;
item_size, item_type, item_tag : byte;
function indent : string;
var
id : integer;
begin
Result := '';
for id := 1 to cc do Result := Result + ' ';
end;
function ValueOf (index, size : integer) : integer;
begin
Result := 0;
case size of
1 :
begin
Result := b[index];
if Result > $7f then Result := Result - $100;
end;
2 :
begin
Result := b[index] + (b[index + 1] shl 8);
if Result > $7fff then Result := Result - $10000;
end;
end; // case
end;
begin
i := 0;
done := false;
cc := 0;
page := 0;
while not done do
begin
if i > high (b) then
done := true
else
begin
x := b[i];
if x = 0 then done := true
else
begin
item_size := x and $03; // extra bytes
if item_size = 3 then item_size := 4; // values are 0,1,2 and 4
item_type := (x shr 2) and $03;
item_tag := (x shr 4) and $0f;
s := '';
case item_type of
0 : // main
begin
case item_tag of
8 : // input
s := 'INPUT (' + InputToStr (b[i + 1]) + ')';
9 : // output
s := 'OUTPUT (' + InputToStr (b[i + 1]) + ')';
10 : // start collection;
begin
case b[i + 1] of
$00 : s := 'Physical';
$01 : s := 'Application';
$03 : s := 'Logical';
$04..$7f : s := 'Reserved'
else s := 'Vendor Defined';
end;
s := 'COLLECTION (' + s + ')';
end;
11 : // feature
s := 'FEATURE (' + InputToStr (b[i + 1]) + ')';
12 : // end collection
s := 'END_COLLECTION';
end; // case
end; // main
1 : // global
begin
case item_tag of
0 : // usage page
begin
s := 'USAGE_PAGE (' + HIDUsageToStr (b[i + 1]) + ')';
page := b[i + 1];
end;
1 : // logical minimum
s := 'LOGICAL_MINIMUM (' + ValueOf (i + 1, item_size).ToString + ')';
2 : // logical maximum
s := 'LOGICAL_MAXIMUM (' + ValueOf (i + 1, item_size).ToString + ')';
3 : // physical minimum
s := 'PHYSICAL MINIMUM (' + ValueOf (i + 1, item_size).ToString + ')';
4 : // physical maximum
s := 'PHYSICAL MAXIMUM (' + ValueOf (i + 1, item_size).ToString + ')';
5 : // unit exponent
s := 'UNIT_EXPONENT (' + ValueOf (i + 1, item_size).ToString + ')';
6 : // unit
s := 'UNIT (' + ValueOf (i + 1, item_size).ToString + ')';
7 : // report size
s := 'REPORT_SIZE (' + ValueOf (i + 1, item_size).ToString + ')';
8 : // report id
s := 'REPORT_ID (' + ValueOf (i + 1, item_size).ToString + ')';
9 : // report count
s := 'REPORT_COUNT (' + ValueOf (i + 1, item_size).ToString + ')';
10 : // push
s := 'PUSH';
11 : // pop
s := 'POP';
end; // case
end; // global
$02 : // local
begin
case item_tag of
0 : // usage
s := 'USAGE (' + LocalUsageToStr (page, b[i + 1]) + ')';
1 : // usage minimum
s := 'USAGE_MINIMUM (' + ValueOf (i + 1, item_size).ToString + ')';
2 : // usage maximum
s := 'USAGE_MAXIMUM (' + ValueOf (i + 1, item_size).ToString + ')';
3 : // designator index
s := 'DESIGNATOR_INDEX (' + ValueOf (i + 1, item_size).ToString + ')';
4 : // designator minimum
s := 'DESIGNATOR_MINIMUM (' + ValueOf (i + 1, item_size).ToString + ')';
5 : // designator maximum
s := 'DESIGNATOR_MAXIMUM (' + ValueOf (i + 1, item_size).ToString + ')';
7 : // string index
s := 'STRING_INDEX (' + ValueOf (i + 1, item_size).ToString + ')';
8 : // string minimum
s := 'STRING_MINIMUM (' + ValueOf (i + 1, item_size).ToString + ')';
9 : // string maximum
s := 'STRING_MAXIMUM (' + ValueOf (i + 1, item_size).ToString + ')';
10 : // delimiter
s := 'DELIMITER (' + ValueOf (i + 1, item_size).ToString + ')';
end; // case
end; // local
end; // case
if b[i] = $c0 then cc := cc - 1;
if s <> '' then Log (indent + s);
// sleep (1000);
if b[i] = $a1 then cc := cc + 1;
i := i + 1 + item_size;
end;
end;
end;
end;
end.
|
unit Un_DLL_MX;
interface
type
pDouble = ^Double;
mxComplexty = (mxREAL, mxCOMPLEX);pmxArray=^mxArray;
mxArray=record
end;
//Из библиотеки libmx.dll
function mxCreateDoubleMatrix(m,n:Integer;
mxData:mxComplexty):pmxArray; cdecl; external 'libmx.dll';
procedure mxSetName(arr_ptr:pmxArray; const name:String);
cdecl; external 'libmx.dll';
function mxGetPr(arr_ptr:pmxArray):pDouble;cdecl; external 'libmx.dll';
function mxGetPi(arr_ptr:pmxArray):pDouble;cdecl; external 'libmx.dll';
function mxGetM(arr_ptr:pmxArray):Integer; cdecl; external 'libmx.dll';
function mxGetN(arr_ptr:pmxArray):Integer; cdecl; external 'libmx.dll';
procedure mxDestroyArray(arr_ptr:pmxArray); cdecl; external 'libmx.dll';
procedure mxFree(var ram:THandle); cdecl; external 'libmx.dll';
function mxTranspose(x:pmxArray):pmxArray; cdecl; external 'libmx.dll';
// Из библиотеки mclmcr.dll
function mclInitializeApplication(A:THandle;B:Integer):Boolean;
cdecl; external 'mclmcr.dll';
function mclTerminateApplication:Boolean; cdecl; external 'mclmcr.dll';
//Из моей библиотеки lpa_dll
function _linprogInitialize:Boolean; cdecl; external 'linprog.dll';
function _linprogTerminate:Boolean; cdecl; external 'linprog.dll';
procedure _mlfLp121(i:Integer; var pout:pmxArray; f,A,b,lb:pmxArray);
cdecl; external 'linprog.dll';
implementation
end.
|
unit uHydrometerVid_AE;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit,
StdCtrls, cxControls, cxGroupBox, cxButtons, ibase, uConsts;
type
TfrmHydrometerVid_AE = class(TForm)
OkButton: TcxButton;
CancelButton: TcxButton;
cxGroupBox1: TcxGroupBox;
NameLabel: TLabel;
NameEdit: TcxTextEdit;
procedure CancelButtonClick(Sender: TObject);
procedure OkButtonClick(Sender: TObject);
private
PLanguageIndex : byte;
procedure FormIniLanguage();
public
ID_NAME : int64;
DB_Handle : TISC_DB_HANDLE;
constructor Create(AOwner:TComponent; LanguageIndex : byte);reintroduce;
end;
{var
frmHydrometerVid_AE: TfrmHydrometerVid_AE;}
implementation
{$R *.dfm}
constructor TfrmHydrometerVid_AE.Create(AOwner:TComponent; LanguageIndex : byte);
begin
Screen.Cursor:=crHourGlass;
inherited Create(AOwner);
PLanguageIndex:= LanguageIndex;
FormIniLanguage();
Screen.Cursor:=crDefault;
DecimalSeparator := ',';
end;
procedure TfrmHydrometerVid_AE.FormIniLanguage;
begin
NameLabel.caption := uConsts.bs_name_hydrometer_type[PLanguageIndex];
OkButton.Caption := uConsts.bs_Accept[PLanguageIndex];
CancelButton.Caption := uConsts.bs_Cancel[PLanguageIndex];
end;
procedure TfrmHydrometerVid_AE.CancelButtonClick(Sender: TObject);
begin
close;
end;
procedure TfrmHydrometerVid_AE.OkButtonClick(Sender: TObject);
begin
if (NameEdit.text = '') then
begin
ShowMessage('Необхідно заповнити назву виду водоміра !');
NameEdit.SetFocus;
exit;
end;
ModalResult:=mrOk;
end;
end.
|
unit ciUnit;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, NppDockingForms, Vcl.OleCtrls, SHDocVw,
Vcl.ExtCtrls, Vcl.WinXCtrls, Vcl.ComCtrls;
type
Tci = class(TNppDockingForm)
ci: TPanel;
WebBrowser1: TWebBrowser;
ResultLabel: TPanel;
StatusBar1: TStatusBar;
ProgressBar1: TProgressBar;
procedure WebBrowser1DownloadBegin(Sender: TObject);
procedure WebBrowser1DownloadComplete(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure StatusBar1DrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel;
const Rect: TRect);
procedure WebBrowser1ProgressChange(ASender: TObject; Progress,
ProgressMax: Integer);
private
FFileName: string;
const cnstCIExec = 'Инспекция файла';
function GetWebBrowserFile: String;
procedure SetWebBrowserFile(const Value: String);
public
procedure DoCodeinsp;
property WebBrowserFile: string read GetWebBrowserFile write SetWebBrowserFile;
end;
implementation
uses
CIFormUnit;
{$R *.dfm}
procedure Tci.DoCodeinsp;
var FCiForm: TCIForm;
begin
FCiForm := TCIForm.Create(self);
try
if FCiForm.ShowModal = mrOK then
begin
//WebBrowser1.Navigate('about:blank');
FFileName := FCiForm.FileName;
FCiForm.Navigate(WebBrowser1);
Show;
end;
finally
FCiForm.Free;
end;
end;
procedure Tci.FormCreate(Sender: TObject);
var
ProgressBarStyle: integer;
begin
//enable status bar 2nd Panel custom drawing
StatusBar1.Panels[0].Style := psOwnerDraw;
//place the progress bar into the status bar
ProgressBar1.Parent := StatusBar1;
//remove progress bar border
ProgressBarStyle := GetWindowLong(ProgressBar1.Handle,
GWL_EXSTYLE);
ProgressBarStyle := ProgressBarStyle
- WS_EX_STATICEDGE;
SetWindowLong(ProgressBar1.Handle,
GWL_EXSTYLE,
ProgressBarStyle);
end;
function Tci.GetWebBrowserFile: String;
begin
Result := ResultLabel.Caption;
end;
procedure Tci.SetWebBrowserFile(const Value: String);
begin
ResultLabel.Caption := Value;
end;
procedure Tci.StatusBar1DrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel;
const Rect: TRect);
begin
if Panel = StatusBar.Panels[0] then
with ProgressBar1 do begin
Top := Rect.Top;
Left := Rect.Left;
Width := Rect.Right - Rect.Left;
Height := Rect.Bottom - Rect.Top;
end;
end;
procedure Tci.WebBrowser1DownloadBegin(Sender: TObject);
begin
WebBrowserFile := '';
ProgressBar1.Position := 0;
end;
procedure Tci.WebBrowser1DownloadComplete(Sender: TObject);
begin
WebBrowserFile := cnstCIExec + ': ' + FFileName;
end;
procedure Tci.WebBrowser1ProgressChange(ASender: TObject; Progress,
ProgressMax: Integer);
begin
ProgressBar1.Max := ProgressMax;
ProgressBar1.Position := Progress;
end;
end.
|
unit uAccessGrid;
interface
type
TAccessGrid = class
private
FObjectID: integer;
function GetCanDelete: boolean;
function GetCanInsert: boolean;
function GetCanUpdate: boolean;
public
property ObjectID: integer read FObjectID write FObjectID;
property CanInsert: boolean read GetCanInsert;
property CanUpdate: boolean read GetCanUpdate;
property CanDelete: boolean read GetCanDelete;
end;
implementation
{ TAccessGrid }
function TAccessGrid.GetCanDelete: boolean;
begin
result:=true;
end;
function TAccessGrid.GetCanInsert: boolean;
begin
result:=true;
end;
function TAccessGrid.GetCanUpdate: boolean;
begin
result:=true;
end;
end.
|
unit uImportSeriesPreview;
interface
uses
Generics.Collections,
System.SysUtils,
System.Classes,
Winapi.ActiveX,
Vcl.Graphics,
Dmitry.Utils.ShellIcons,
Dmitry.PathProviders,
UnitBitmapImageList,
uThreadForm,
uThreadEx,
uMemory,
uIconUtils,
uImageLoader,
uDBEntities,
uPortableDeviceUtils;
type
TImportSeriesPreview = class(TThreadEx)
private
{ Private declarations }
FData: TList<TPathItem>;
FImageSize: Integer;
FPacketImages: TBitmapImageList;
FPacketInfos: TList<TPathItem>;
FBitmap: TBitmap;
FItemParam: TPathItem;
protected
procedure Execute; override;
procedure SendPacketOfPreviews;
procedure UpdatePreview;
public
constructor Create(OwnerForm: TThreadForm; Items: TList<TPathItem>; ImageSize: Integer);
destructor Destroy; override;
end;
implementation
uses
uFormImportImages;
{ TImportSeriesPreview }
constructor TImportSeriesPreview.Create(OwnerForm: TThreadForm;
Items: TList<TPathItem>; ImageSize: Integer);
begin
inherited Create(OwnerForm, OwnerForm.SubStateID);
FData := Items;
FImageSize := ImageSize;
end;
destructor TImportSeriesPreview.Destroy;
begin
FreeList(FData);
inherited;
end;
procedure TImportSeriesPreview.Execute;
var
I: Integer;
Data: TObject;
PI: TPathItem;
FIcon: TIcon;
MediaItem: TMediaItem;
ImageInfo: ILoadImageInfo;
begin
inherited;
FreeOnTerminate := True;
CoInitializeEx(nil, COINIT_MULTITHREADED);
try
FPacketImages := TBitmapImageList.Create;
FPacketInfos := TList<TPathItem>.Create;
try
//loading list with icons
for I := 0 to FData.Count - 1 do
begin
PI := FData[I];
FIcon := TIcon.Create;
FIcon.Handle := ExtractDefaultAssociatedIcon('*' + ExtractFileExt(PI.Path), ImageSizeToIconSize16_32_48(FImageSize));
FPacketImages.AddIcon(FIcon, True);
FPacketInfos.Add(PI);
if I mod 10 = 0 then
SynchronizeEx(SendPacketOfPreviews);
end;
if FPacketInfos.Count > 0 then
SynchronizeEx(SendPacketOfPreviews);
for I := 0 to FData.Count - 1 do
begin
if IsTerminated then
Break;
FItemParam := FData[I];
FBitmap := TBitmap.Create;
try
Data := nil;
if IsDevicePath(FData[I].Path) then
begin
if FData[I].Provider.ExtractPreview(FData[I], FImageSize, FImageSize, FBitmap, Data) then
begin
if SynchronizeEx(UpdatePreview) then
FBitmap := nil;
end;
end else
begin
MediaItem := TMediaItem.CreateFromFile(FData[I].Path);
try
if LoadImageFromPath(MediaItem, 1, '', [ilfGraphic, ilfICCProfile, ilfEXIF], ImageInfo, FImageSize, FImageSize) then
begin
F(FBitmap);
FBitmap := ImageInfo.GenerateBitmap(MediaItem, FImageSize, FImageSize, pf32bit, clNone, [ilboFreeGraphic, ilboRotate, ilboApplyICCProfile, ilboQualityResize]);
if (FBitmap <> nil) and SynchronizeEx(UpdatePreview) then
FBitmap := nil;
end;
finally
F(MediaItem);
end;
end;
finally
F(FBitmap);
end;
end;
finally
F(FPacketImages);
F(FPacketInfos);
end;
finally
CoUninitialize;
end;
end;
procedure TImportSeriesPreview.SendPacketOfPreviews;
begin
TFormImportImages(OwnerForm).AddPreviews(FPacketInfos, FPacketImages);
FPacketInfos.Clear;
FPacketImages.Clear;
end;
procedure TImportSeriesPreview.UpdatePreview;
begin
TFormImportImages(OwnerForm).UpdatePreview(FItemParam, FBitmap);
end;
end.
|
unit Server.Logger;
interface
function GetLoggingConfiguration(const ALogFilename: String; const ALogLevel: String): String;
implementation
uses
SysUtils
, Spring.Logging
, Spring.Logging.Configuration.Builder
, Classes.DailyFileLogAppender
;
{======================================================================================================================}
function GetLoggingConfiguration(const ALogFilename: String; const ALogLevel: String): String;
{======================================================================================================================}
const
LOG_LEVEL_ERROR = 'ERROR';
LOG_LEVEL_WARN = 'WARN';
LOG_LEVEL_INFO = 'INFO';
LOG_LEVEL_DEBUG = 'DEBUG';
var
builder: TLoggingConfigurationBuilder;
logLevels: TLogLevels;
begin
logLevels := [TLogLevel.Error];
if SameText(ALogLevel, LOG_LEVEL_WARN) then logLevels := logLevels + [TLogLevel.Warn];
if SameText(ALogLevel, LOG_LEVEL_INFO) then logLevels := logLevels + [TLogLevel.Warn, TLogLevel.Info];
if SameText(ALogLevel, LOG_LEVEL_DEBUG) then logLevels := logLevels + [TLogLevel.Warn, TLogLevel.Info, TLogLevel.Debug];
builder := TLoggingConfigurationBuilder.Create
.BeginAppender('fileAppender', TDailyFileLogAppender)
.Enabled(True)
.Levels(logLevels)
.EventTypes([
TLogEventType.Text,
TLogEventType.Entering,
TLogEventType.Leaving
])
.Prop('Filename', ALogFilename)
.EndAppender
.BeginLogger('default') // Naming it 'default' enable us to inject it simply tagging a property like [Inject]
.EndLogger;
// .BeginLogger('anotherLogger') // 'anotherLogger' will become a container service-name of this logger
// .Assign('TLogger') // but only if this begin/end section is not empty!
// .EndLogger; // We can then inject it tagging a property as [Inject('anotherLogger')]
Result := builder.ToString;
end;
end.
|
namespace AppBarExample;
interface
uses
System,
System.Collections.Generic,
System.Linq,
System.Threading.Tasks,
Windows.Foundation,
Windows.UI.Popups,
Windows.UI.Xaml,
Windows.UI.Xaml.Controls,
Windows.UI.Xaml.Data,
Windows.UI.Xaml.Navigation;
type
MainPage = partial class
private
method AppBar_Click(sender: Object; e: RoutedEventArgs);
method Sticky_Click(sender: Object; e: RoutedEventArgs);
protected
public
constructor ;
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected
method OnNavigatedTo(e: NavigationEventArgs); override;
end;
implementation
constructor MainPage;
begin
System.Diagnostics.Debug.WriteLine("MainPage Constructor");
InitializeComponent();
end;
method MainPage.OnNavigatedTo(e: NavigationEventArgs);
begin
end;
method MainPage.AppBar_Click(sender: Object; e: RoutedEventArgs);
begin
var msg := new MessageDialog("App Bar Button '" + String((sender as Button).Tag) + "' clicked.");
msg.Commands.Add(new UICommand("OK", nil, "ok"));
msg.Commands.Add(new UICommand("Again", nil, "again"));
var cmd := await msg.ShowAsync;
if String(cmd.Id) = "again" then
new MessageDialog("You like MessageDialogs - here is another one!").ShowAsync;
end;
method MainPage.Sticky_Click(sender: Object; e: Windows.UI.Xaml.RoutedEventArgs);
begin
// Toggle Sticky property
TopAppBar1.IsSticky := Boolean((sender as CheckBox).IsChecked);
// Syncronize AppBars for aesthetics
if not TopAppBar1.IsSticky then
TopAppBar.IsOpen := self.BottomAppBar.IsOpen;
end;
end.
|
namespace RemObjects.Elements.System;
interface
type
ArrayUtils = public static class
public
class method asIterable(x: array of Boolean): sequence of nullable Boolean;iterator;
class method asIterable(x: array of SByte): sequence of nullable SByte;iterator;
class method asIterable(x: array of Char): sequence of nullable Char;iterator;
class method asIterable(x: array of Double): sequence of nullable Double;iterator;
class method asIterable(x: array of Single): sequence of nullable Single;iterator;
class method asIterable(x: array of Integer): sequence of nullable Integer;iterator;
class method asIterable(x: array of Int64): sequence of nullable Int64;iterator;
class method asIterable(x: array of Int16): sequence of nullable Int16;iterator;
class method asIterableUnsigned(x: array of SByte): sequence of remobjects.elements.system.UnsignedByte;iterator;
class method asIterableUnsigned(x: array of Integer): sequence of remobjects.elements.system.UnsignedInteger;iterator;
class method asIterableUnsigned(x: array of Int64): sequence of remobjects.elements.system.UnsignedLong;iterator;
class method asIterableUnsigned(x: array of Int16): sequence of remobjects.elements.system.UnsignedShort; iterator;
class method asIterable<T>(x: array of T): sequence of T; iterator;
class method fill(a: array of Object; val: Object);
begin
var ct := if val <> nil then val.getClass().getDeclaredConstructor();
if ct <> nil then
ct.setAccessible(true);
for i: Integer := 0 to length(a) -1 do begin
if i = 0 then
a[i] := val
else begin
a[i] := if ct = nil then nil else ct.newInstance();
end;
end;
end;
class method getSubArray<T>(val: array of T; aStart, aLength: Integer): array of T;
begin
result := java.util.Arrays.copyOfRange(val, aStart, aStart+aLength);
end;
class method getSubArray(val: array of SByte; aRange: Range): array of SByte;
begin
var lLength := length(val);
var lStart := aRange.fStart.GetOffset(lLength);
var lEnd := aRange.fEnd.GetOffset(lLength);
result := java.util.Arrays.copyOfRange(val, lStart, lEnd);
end;
//class method getSubArray(val: array of Byte; aRange: Range): array of Byte;
//begin
//var lLength := length(val);
//var lStart := aRange.fStart.GetOffset(lLength);
//var lEnd := aRange.fEnd.GetOffset(lLength);
//result := java.util.Arrays.copyOfRange(val, lStart, lEnd);
//end;
class method getSubArray(val: array of Int16; aRange: Range): array of Int16;
begin
var lLength := length(val);
var lStart := aRange.fStart.GetOffset(lLength);
var lEnd := aRange.fEnd.GetOffset(lLength);
result := java.util.Arrays.copyOfRange(val, lStart, lEnd);
end;
//class method getSubArray(val: array of UInt16; aRange: Range): array of UInt16;
//begin
//var lLength := length(val);
//var lStart := aRange.fStart.GetOffset(lLength);
//var lEnd := aRange.fEnd.GetOffset(lLength);
//result := java.util.Arrays.copyOfRange(val, lStart, lEnd);
//end;
class method getSubArray(val: array of Int32; aRange: Range): array of Int32;
begin
var lLength := length(val);
var lStart := aRange.fStart.GetOffset(lLength);
var lEnd := aRange.fEnd.GetOffset(lLength);
result := java.util.Arrays.copyOfRange(val, lStart, lEnd);
end;
//class method getSubArray(val: array of UInt32; aRange: Range): array of UInt32;
//begin
//var lLength := length(val);
//var lStart := aRange.fStart.GetOffset(lLength);
//var lEnd := aRange.fEnd.GetOffset(lLength);
//result := java.util.Arrays.copyOfRange(val, lStart, lEnd);
//end;
class method getSubArray(val: array of Int64; aRange: Range): array of Int64;
begin
var lLength := length(val);
var lStart := aRange.fStart.GetOffset(lLength);
var lEnd := aRange.fEnd.GetOffset(lLength);
result := java.util.Arrays.copyOfRange(val, lStart, lEnd);
end;
//class method getSubArray(val: array of UInt64; aRange: Range): array of UInt64;
//begin
//var lLength := length(val);
//var lStart := aRange.fStart.GetOffset(lLength);
//var lEnd := aRange.fEnd.GetOffset(lLength);
//result := java.util.Arrays.copyOfRange(val, lStart, lEnd);
//end;
//class method getSubArray<Single>(val: array of Single; aRange: Range): array of Single;
//begin
//var lLength := length(val);
//var lStart := aRange.fStart.GetOffset(lLength);
//var lEnd := aRange.fEnd.GetOffset(lLength);
//result := java.util.Arrays.copyOfRange(val, lStart, lEnd);
//end;
class method getSubArray<Double>(val: array of Double; aRange: Range): array of Double;
begin
var lLength := length(val);
var lStart := aRange.fStart.GetOffset(lLength);
var lEnd := aRange.fEnd.GetOffset(lLength);
result := java.util.Arrays.copyOfRange(val, lStart, lEnd);
end;
class method getSubArray(val: array of Boolean; aRange: Range): array of Boolean;
begin
var lLength := length(val);
var lStart := aRange.fStart.GetOffset(lLength);
var lEnd := aRange.fEnd.GetOffset(lLength);
result := java.util.Arrays.copyOfRange(val, lStart, lEnd);
end;
class method getSubArray(val: array of Char; aRange: Range): array of Char;
begin
var lLength := length(val);
var lStart := aRange.fStart.GetOffset(lLength);
var lEnd := aRange.fEnd.GetOffset(lLength);
result := java.util.Arrays.copyOfRange(val, lStart, lEnd);
end;
//class method getSubArray(val: array of AnsiChar; aRange: Range): array of AnsiChar;
//begin
//var lLength := length(val);
//var lStart := aRange.fStart.GetOffset(lLength);
//var lEnd := aRange.fEnd.GetOffset(lLength);
//result := java.util.Arrays.copyOfRange(val, lStart, lEnd);
//end;
end;
implementation
class method ArrayUtils.asIterable(x: array of Boolean): sequence of nullable Boolean;
begin
for i: Integer := 0 to length(x) -1 do
yield x[i];
end;
class method ArrayUtils.asIterable(x: array of SByte): sequence of nullable SByte;
begin
for i: Integer := 0 to length(x) -1 do
yield x[i];
end;
class method ArrayUtils.asIterable(x: array of Char): sequence of nullable Char;
begin
for i: Integer := 0 to length(x) -1 do
yield x[i];
end;
class method ArrayUtils.asIterable(x: array of Double): sequence of nullable Double;
begin
for i: Integer := 0 to length(x) -1 do
yield x[i];
end;
class method ArrayUtils.asIterable(x: array of Single): sequence of nullable Single;
begin
for i: Integer := 0 to length(x) -1 do
yield x[i];
end;
class method ArrayUtils.asIterable(x: array of Integer): sequence of nullable Integer;
begin
for i: Integer := 0 to length(x) -1 do
yield x[i];
end;
class method ArrayUtils.asIterable(x: array of Int64): sequence of nullable Int64;
begin
for i: Integer := 0 to length(x) -1 do
yield x[i];
end;
class method ArrayUtils.asIterable(x: array of Int16): sequence of nullable Int16;
begin
for i: Integer := 0 to length(x) -1 do
yield x[i];
end;
class method ArrayUtils.asIterable<T>(x: array of T): sequence of T;
begin
for i: Integer := 0 to length(x) -1 do
yield x[i];
end;
class method ArrayUtils.asIterableUnsigned(x: array of SByte): sequence of remobjects.elements.system.UnsignedByte;
begin
for i: Integer := 0 to length(x) -1 do
yield new remobjects.elements.system.UnsignedByte(x[i]);
end;
class method ArrayUtils.asIterableUnsigned(x: array of Integer): sequence of remobjects.elements.system.UnsignedInteger;
begin
for i: Integer := 0 to length(x) -1 do
yield new remobjects.elements.system.UnsignedInteger(x[i]);
end;
class method ArrayUtils.asIterableUnsigned(x: array of Int64): sequence of remobjects.elements.system.UnsignedLong;
begin
for i: Integer := 0 to length(x) -1 do
yield new remobjects.elements.system.UnsignedLong(x[i]);
end;
class method ArrayUtils.asIterableUnsigned(x: array of Int16): sequence of remobjects.elements.system.UnsignedShort;
begin
for i: Integer := 0 to length(x) -1 do
yield new remobjects.elements.system.UnsignedShort(x[i]);
end;
end. |
unit uFileDir;
interface
uses
SysUtils,
Classes,
ShellAPI,
ShlObj,
Forms,
Dialogs,
Windows;
const
UNIT_NAME = 'FileDir';
kernel = 'kernel32.dll';
user = 'user32.dll';
COMPARED_EQUAL = 0;
ucCRLF = #13#10;
BUFFER_MAX_LENGTH = 400;
apiTEMP = 'temp'; {Temp system variable}
apiUSERDIR = 'USERPROFILE'; {User variable}
OFN_DONTADDTORECENT = $02000000;
OFN_FILEMUSTEXIST = $00001000;
OFN_HIDEREADONLY = $00000004;
OFN_PATHMUSTEXIST = $00000800;
var
lg_StartFolder: String;
function OpenSaveFileDialog(ParentHandle: THandle; const DefExt, Filter,
InitialDir, Title: string; var FileName: string; IsOpenDialog: Boolean):
Boolean;
type
TErrorRaisedEvent = procedure (Sender: TObject; exc : TObject; procedureName : string) of object;
CFileDir = class(TObject)
private
FShowError : Boolean;
//p : TObject;
app : TApplication;
FOnError : TErrorRaisedEvent;
procedure Emsg( s : string );
function Parms(v: array of Variant; Paired: Boolean): String;
Function CountStrOcc(const StringWithStringOccurances, StringToCount : String; StartPos : Cardinal = 1; CaseSensitive : Boolean = True) : Cardinal;
Function ucPos( StringToSearchIn, StringToFind : String; StartPos : Cardinal = 1; CaseSensitive : boolean = True) : Cardinal;
function CompareString( const S1, S2 : String; CaseSensitive : boolean = False) : integer;
Function PosRev( const StringToSearch, StringToFind : String; StartPos : Cardinal = 0; CaseSensitive : boolean = false) : Cardinal;
Procedure ParseString(const vS : string; ParseChar : Char; ParsedString : TStringList; TrimOnInsert : boolean = false);
function ForceStr( StringtoForceCharIn : String; StringToForceToFront : String = ''; StringToForceAtEnd : String = '' ) : String;
function ucLeft( s : String; NumOfLeftChar : integer ) : String;
function ucRight( s : String; NumOfRightChar : integer ) : String;
function GetStringParm( v: array of Variant; Paired : Boolean = false; MajorDelimiter : String = ', '; MinorDelimiter : String = '') : String;
Function GetPairStrParm( sa: array of String; QuoteStrings : boolean = True; MajorDelimiter : String = ';'; MinorDelimiter : String = ',') : String;
function GetEnvironmentVariable(sVariable: string): String;
procedure ErrorRaised(functionName: string; e: TObject);
public
function GetVersion(const sFileName: string): string; overload;
procedure GetVersion(const sFileName: string; var ReturnVersion : string ); overload;
property ShowError: boolean read FShowError write FShowError;
property OnError: TErrorRaisedEvent read FOnError write FOnError;
function Slash( StringToForceSlashAtEnd : String) : String;
function GetSystemTempDir: String;
Function AppDir: String;
Function AddPath(const FileName : String) : String;
Function AppExe: String;
Function RelativePath(const OriginalPath, OffsetPath : String) : String;
function AppendToFileName(FullPathName,
StringToAppend: String): String;
function ChangeExt(FullPathName, NewExtention: String): String;
function ChangePath(FullPathName, NewPath: String): String;
function CopyFile(ExistingFile, NewFile: String) : boolean;
Function ucExtractFileName( FullPathName : String; ExcludeExtention : Boolean = False) : String;
function GetFileList( PathName : String; ShowDirectory : boolean = false) : TStringList;
function DeleteFilesInPath( const PathName : String ) : integer;
function TextFileToString(FileToReadFrom: String;
StripCrlf: Boolean = false): String;
procedure WriteString(StringToWrite, FileToWriteTo: String;
AppendToFile: boolean = false);
function BrowseForFolder( var FolderName: String ): Boolean; overload;
function BrowseForFolder( const InitialFolder: string; var FolderName: String ): Boolean; overload;
function DestroyPath( const pathToDestroy : string ) : boolean;
Function OpenDlg(var SelectedFile : String; DefaultFileTypes : String = 'All Files (*.*)|*.*'; Title : String = '{AppName}'; DefaultFile : String = '') : Boolean;
Function OpenDlgAPI(var SelectedFile : String; DefaultFileTypes : String = 'All Files (*.*)|*.*'; Title : String = '{AppName}'; DefaultFile : String = ''; DefaultExt : String = 'txt'; InitialPath : String = '{CURDIR}' ) : Boolean;
Function SaveDlgAPI(var SelectedFile : String; DefaultFileTypes : String = 'All Files (*.*)|*.*'; Title : String = '{AppName}'; DefaultFile : String = ''; DefaultExt : String = 'txt'; InitialPath : String = '{CURDIR}' ) : Boolean;
function GetChildDirs( PathName : String; DirectoryList : TStringList; CurrentDepth : longint;
MaxDepth : longint = 0 ) : longint;
function _GetSubDirList( PathName : String; DirectoryList : TStringList;
CurrentDepth : longint; MaxDepth : longint = 0 ) : longint;
function GetSubDirList( PathName : String; MaxDepth : longint = 0 ) : TStringList;
constructor Create(); overload;
constructor Create(callingWindowedApp : TObject); overload;
destructor Destroy; override;
function GetFileDateTime(FullFileName : String): TDateTime;
function GetShortFileName(const FileName : TFileName ) : TFileName;
function GetUserDir() : string;
function GetAppDataDir: string;
function GetCookiesDir: string;
function GetDesktop: string;
function GetDesktopDir: string;
function GetFavDir: string;
function GetFontsDir: string;
function GetHistoryDir: string;
function GetMyDocDir: string;
function GetNetHoodDir: string;
function GetPrintHoodDir: string;
function GetProgDir: string;
function GetRecentDir: string;
function GetSendToDir: string;
function GetSpecialFolder(FolderID: Integer): string;
function GetStartMenuDir: string;
function GetStartUpDir: string;
function GetTemplateDir: string;
function GetTmpInternetDir: string;
end;
POpenFilenameA = ^TOpenFilenameA;
POpenFilename = POpenFilenameA;
tagOFNA = packed record
lStructSize: DWORD;
hWndOwner: HWND;
hInstance: HINST;
lpstrFilter: PAnsiChar;
lpstrCustomFilter: PAnsiChar;
nMaxCustFilter: DWORD;
nFilterIndex: DWORD;
lpstrFile: PAnsiChar;
nMaxFile: DWORD;
lpstrFileTitle: PAnsiChar;
nMaxFileTitle: DWORD;
lpstrInitialDir: PAnsiChar;
lpstrTitle: PAnsiChar;
Flags: DWORD;
nFileOffset: Word;
nFileExtension: Word;
lpstrDefExt: PAnsiChar;
lCustData: LPARAM;
lpfnHook: function(Wnd: HWND; Msg: UINT; wParam: WPARAM; lParam: LPARAM): UINT stdcall;
lpTemplateName: PAnsiChar;
end;
TOpenFilenameA = tagOFNA;
TOpenFilename = TOpenFilenameA;
function APICopyFile(ExistingFile, NewFile: PChar; nFailIfExists: LongInt): LongInt; stdcall;
external kernel name 'CopyFileA';
function APIGetSystemDir(pcDir : PChar; lMaxBufferLength: LongInt): LongInt; stdcall;
external kernel name 'GetSystemDirectoryA';
//function APIGetTempDir(pcDir : PChar; lMaxBufferLength: LongInt): LongInt; stdcall;
// external kernel name 'GetTempPathA';
function APIGetTempDir(lMaxBufferLength: Cardinal; pcDir : PChar): Cardinal; stdcall;
external kernel name 'GetTempPathA';
function APIGetWinDir(pcDir : PChar; lMaxBufferLength: LongInt): LongInt; stdcall;
external kernel name 'GetWindowsDirectoryA';
function APIGetEnvironmentVariable(pcVarName, pcVarValue : PChar; lMaxVarValueLength: LongInt): LongInt; stdcall;
external kernel name 'GetEnvironmentVariableA';
function BrowseForFolderCallBack(Wnd: HWND; uMsg: UINT; lParam,
lpData: LPARAM): Integer stdcall;
function BrowseForFolderAPI(const browseTitle: String; var SelectedFolder : string;
const initialFolder: String =''): boolean;
Procedure WriteString( StringToWrite, FileToWriteTo : String; AppendToFile : boolean);
function GetModuleName: string;
implementation
function GetOpenFileName(var OpenFile: TOpenFilename): Bool; stdcall; external 'comdlg32.dll' name 'GetOpenFileNameA';
function GetSaveFileName(var OpenFile: TOpenFilename): Bool; stdcall; external 'comdlg32.dll' name 'GetSaveFileNameA';
function CharReplace(const Source: string; oldChar, newChar: Char): string;
var
i: Integer;
begin
Result := Source;
for i := 1 to Length(Result) do
if Result[i] = oldChar then
Result[i] := newChar
end;
function OpenSaveFileDialog(ParentHandle: THandle; const DefExt, Filter, InitialDir, Title: string; var FileName: string; IsOpenDialog: Boolean): Boolean;
var
ofn: TOpenFileName;
szFile: array[0..MAX_PATH] of Char;
begin
Result := False;
FillChar(ofn, SizeOf(TOpenFileName), 0);
with ofn do
begin
lStructSize := SizeOf(TOpenFileName);
hwndOwner := ParentHandle;
lpstrFile := szFile;
nMaxFile := SizeOf(szFile);
if (Title <> '') then
lpstrTitle := PChar(Title);
if (InitialDir <> '') then
lpstrInitialDir := PChar(InitialDir);
StrPCopy(lpstrFile, FileName);
lpstrFilter := PChar(CharReplace(Filter, '|', #0)+#0#0);
if DefExt <> '' then
lpstrDefExt := PChar(DefExt);
end;
if IsOpenDialog then
begin
if GetOpenFileName(ofn) then
begin
Result := True;
FileName := StrPas(szFile);
end;
end
else
begin
if GetSaveFileName(ofn) then
begin
Result := True;
FileName := StrPas(szFile);
end;
end
end;
procedure CFileDir.Emsg( s : string );
begin
if ( FShowError ) then
MessageDlg(s, mtError,[mbOk], 0);
End;
Function CFileDir.AddPath(const FileName : String) : String;
var
s : String;
Begin
try
result := '';
if ( FileName <> '' ) then begin
if (FileName[1] = '.') then begin //Current Directory
s := FileName;
Result := AppDir;
end else if ((FileName[1] = '.') and (FileName[2] = '\')) then begin //Current Directory
s := FileName;
Delete(s, 1, 2);
Result := AppDir + s;
end else if ( ExtractFilePath(FileName) = '' ) then //No Directory
Result := AppDir + FileName
else if ((FileName[1] = '.') and (FileName[2] = '.')) then begin //Realtive Directory
Result := RelativePath(AppDir, FileName)
end else //Leave alone of path doesn't meet above criteria
Result := FileName;
end;
except
ErrorRaised(UNIT_NAME + ':CFileDir.AddPath(' + Parms( [ 'FileName', FileName ], True) + ')', ExceptObject);
raise;
end; {try}
End;
Function CFileDir.AppDir: String;
Begin
Result := ExtractFilePath(app.EXEName)
End;
Function CFileDir.AppExe: String;
Begin
Result := ExtractFileName(app.EXEName)
End;
function CFileDir.BrowseForFolder(const InitialFolder: string;
var FolderName: String): Boolean;
begin
lg_StartFolder := InitialFolder;
Result := self.BrowseForFolder( FolderName );
end;
procedure CFileDir.ErrorRaised(functionName: string; e: TObject);
begin
if ( Assigned( FOnError )) then begin
FOnError( self, e, functionName );
end;
End;
Function CFileDir.RelativePath(const OriginalPath, OffsetPath : String) : String;
var i, nPos, nAntiOffset : SmallInt;
ParsedDirectory : TStringList;
s : String;
Begin
result := OriginalPath;
ParsedDirectory := TStringList.Create;
try
nAntiOffset := CountStrOcc(OffsetPath, '..');
if ( nAntiOffset > 0 ) then begin
nPos := PosRev(OffsetPath, '..');
s := Copy(OffsetPath, nPos + 2, 9999);
ParseString(OriginalPath, '\', ParsedDirectory);
with ParsedDirectory do begin
if Count > 2 then begin
if ( ParsedDirectory[0] = '\' ) then begin //UNC Path
ParsedDirectory[1] := '\\' + ParsedDirectory[1];
ParsedDirectory.Delete(0);
end;
for i := (Count - (1 + nAntiOffset)) downto 1 do begin //We stop at one because we should always have at least the root directory
s := '\' + ParsedDirectory[i] + s;
end; {i}
end; {if}
end; {with}
end; {if}
s := ParsedDirectory[0] + s;
result := s;
except
ErrorRaised(UNIT_NAME + ':CFileDir.RelativePath(' + Parms( [ 'OriginalPath', OriginalPath, 'OffsetPath', OffsetPath ], True) + ')', ExceptObject);
raise;
end; {try}
ParsedDirectory.Free;
End;
Function CFileDir.ChangePath( FullPathName, NewPath : String) : String;
Begin
result := Slash(NewPath) + ExtractFileName(FullPathName);
End;
Function CFileDir.AppendToFileName( FullPathName, StringToAppend : String) : String;
Begin
result := ExtractFilePath(FullPathName) + ucExtractFileName(FullPathName, True) + StringToAppend + ExtractFileExt(FullPathName);
End;
Function CFileDir.ChangeExt( FullPathName, NewExtention : String) : String;
Begin
result := FullPathName;
try
if ( NewExtention[1] = '.' ) then
result := ExtractFilePath(FullPathName) + ucExtractFileName(FullPathName, True) + NewExtention
else
result := ExtractFilePath(FullPathName) + ucExtractFileName(FullPathName, True) + '.' + NewExtention;
except
ErrorRaised(UNIT_NAME + ':CFileDir.ChangeExt(' + Parms( [ 'FullPathName', FullPathName, 'NewExtention', NewExtention ], True) + ')', ExceptObject);
raise;
end; {try}
End;
function CFileDir.Parms( v: array of Variant; Paired : Boolean ) : String;
Begin
try
Parms := GetStringParm(v, Paired, ', ', ' = ');
except
ErrorRaised(UNIT_NAME + ':CFileDir.Parms' + '- Error', ExceptObject);
raise;
end; {try.. except}
End;
function CFileDir.CopyFile(ExistingFile, NewFile : String) : boolean;
{Wrapper around the semi cryptic Windows API CopyFile Rountine}
var
lResult : LongInt;
begin
lResult := -1;
try
if not DirectoryExists(ExtractFilePath(NewFile)) then ForceDirectories(ExtractFilePath(NewFile));
lResult := APICopyFile(PChar(ExistingFile), PChar(NewFile), 0 ); {copy even if NewFileExists}
if ( lResult = -1 ) then
raise Exception.Create('APICopyFile returned an error value. lResult=' + IntToStr(lResult) );
result := true;
except
ErrorRaised('Kernel Call via procedure "DuplicateFile" for function CopyFile Failed! lResult=' + IntToStr(lResult), ExceptObject);
result := false;
end {try};
End;
constructor CFileDir.Create;
begin
lg_StartFolder := '';
end;
constructor CFileDir.Create(callingWindowedApp: TObject);
begin
app := callingWindowedApp as TApplication;
end;
destructor CFileDir.Destroy;
begin
app := nil;
inherited;
end;
function CFileDir.DestroyPath(const pathToDestroy : string): boolean;
var
SHFileOpStruct : TSHFileOpStruct;
DirBuf : array [0..255] of char;
begin
try
if ( Length( pathToDestroy ) = 0 ) then begin
Result := false;
Exit;
end;
Fillchar(SHFileOpStruct,Sizeof(SHFileOpStruct),0) ;
FillChar(DirBuf, Sizeof(DirBuf), 0 ) ;
if ( pathToDestroy[Length(pathToDestroy)] = '\' ) then
StrPCopy( DirBuf, Copy(pathToDestroy, 0, Length(pathToDestroy)-1 ) )
else
StrPCopy( DirBuf, pathToDestroy );
with SHFileOpStruct do begin
Wnd := 0;
pFrom := @DirBuf;
wFunc := FO_DELETE;
fFlags := FOF_ALLOWUNDO;
fFlags := fFlags or FOF_NOCONFIRMATION;
fFlags := fFlags or FOF_SILENT;
end;
Result := (SHFileOperation(SHFileOpStruct) = 0) ;
except
Result := false;
end;
end;
function CFileDir.CountStrOcc(const StringWithStringOccurances,
StringToCount: String; StartPos: Cardinal;
CaseSensitive: Boolean): Cardinal;
var cCounter, cStPos : Cardinal;
Begin
cCounter := 0;
cStPos := StartPos;
try
While (cStPos > 0) do begin
cStPos := ucPos( StringWithStringOccurances, StringToCount, cStPos, CaseSensitive);
if ( cStPos > 0 ) then begin
Inc(cCounter);
Inc(cStPos);
end;
end;
except
ErrorRaised(UNIT_NAME + ':CountWord(' + Parms( [ 'StringWithStringOccurances', StringWithStringOccurances, 'StringToCount', StringToCount, 'StartPos', StartPos, 'CaseSensitive', CaseSensitive ], True) + ')', ExceptObject);
raise;
end; {try}
result := cCounter;
end;
function CFileDir.CompareString(const S1, S2: String;
CaseSensitive: boolean): integer;
Begin
if CaseSensitive then
CompareString := CompareStr(S1, S2)
else
CompareString := CompareText(S1, S2);
End;
function CFileDir.PosRev(const StringToSearch, StringToFind: String;
StartPos: Cardinal; CaseSensitive: boolean): Cardinal;
var i, lStringToFindLength, lStringToSearchLength : Cardinal;
Begin
try
result := 0;
lStringToFindLength := Length(StringToFind);
lStringToSearchLength := Length(StringToSearch);
if (( StartPos > 0 ) and ( StartPos < lStringToSearchLength + 1)) then
i := StartPos
else
i := lStringToSearchLength;
while i > 0 do begin
if (CompareString(Copy(StringToSearch, i, lStringToFindLength), StringToFind, CaseSensitive) = 0 ) then begin
result := i;
break;
end; {if}
Dec(i);
end; {while}
except
ErrorRaised(UNIT_NAME + ':PosRev - Error finding substring. Parms=' + Parms([ 'StringToSearch', StringToFind, 'StringToFind', StringToFind, 'StartPos', StartPos, 'CaseSensitive', CaseSensitive], True), ExceptObject);
raise;
end; {try}
End;
Procedure CFileDir.ParseString(const vS : string; ParseChar : Char; ParsedString : TStringList; TrimOnInsert : boolean );
Var
i, StPos : integer;
s, newStr : String;
Begin
s := vS + ParseChar;
i := 1; StPos := 1;
While i <= Length(s) do begin
if ( s[i] = ParseChar ) and ( i > 1 ) then begin
if TrimOnInsert then
newStr := Trim(Copy(s, StPos, i - StPos))
else
newStr := Copy(s, StPos, i - StPos);
if ( Length(newStr) > 0 ) then ParsedString.Add(newStr);
StPos := i + 1;
end;{if}
Inc(i);
end; {while}
End;
function CFileDir.ForceStr(StringtoForceCharIn, StringToForceToFront,
StringToForceAtEnd: String): String;
var s : String;
Begin
s := StringtoForceCharIn;
if ( StringToForceAtEnd <> '' ) and ( ucRight(StringtoForceCharIn, Length(StringToForceAtEnd)) <> StringToForceAtEnd ) then
s := s + StringToForceAtEnd;
if ( StringToForceToFront <> '' ) and ( ucLeft(StringtoForceCharIn, Length(StringToForceToFront)) <> StringToForceToFront) then
s := StringToForceToFront + s;
result := s;
End;
function CFileDir.SaveDlgAPI(var SelectedFile: String; DefaultFileTypes, Title,
DefaultFile, DefaultExt, InitialPath: String): Boolean;
var sPath, sNewFileName : String;
Begin
if (( InitialPath='{CURDIR}' ) or ( Length(InitialPath) = 0 )) then
begin
InitialPath:= AddPath('.');
end;
if Title = '{AppName}' then
Title := Application.Title
else
Title := Title;
SelectedFile := '';
sNewFileName := DefaultFile;
if ( OpenSaveFileDialog(Application.Handle, DefaultExt, DefaultFileTypes, InitialPath, Title, sNewFileName, false) ) then
begin
SelectedFile := sNewFileName;
Result := true;
end else
Result := false;
end;
function CFileDir.Slash(StringToForceSlashAtEnd: String): String;
begin
result := ForceStr( StringToForceSlashAtEnd, '', '\');
end;
function CFileDir.ucLeft( s : String; NumOfLeftChar : integer ) : String;
Begin
Result := Copy(s, 1, NumOfLeftChar );
End;
function CFileDir.ucRight( s : String; NumOfRightChar : integer ) : String;
Begin
Result := Copy(s, ((Length(s) - NumOfRightChar) + 1), NumOfRightChar);
End;
function CFileDir.ucExtractFileName(FullPathName: String;
ExcludeExtention: Boolean): String;
var
s : String;
nPos : Integer;
Begin
result := '';
try
s := ExtractFileName( FullPathName );
if ExcludeExtention then begin
nPos := PosRev(s, '.', 9999, True);
if ( nPos > 0 ) then s := Copy(s, 1, nPos - 1);
end; {if}
result := s;
except
ErrorRaised(UNIT_NAME + ':CFileDir.ucExtractFileName - Error while Extracting File Name. Parms=' + Parms([ 'FullPathName', FullPathName, 'ExcludeExtention', ExcludeExtention ], True), ExceptObject);
raise;
end; {try}
End;
function CFileDir.GetPairStrParm(sa: array of String;
QuoteStrings: boolean; MajorDelimiter, MinorDelimiter: String): String;
var
i : ShortInt; s, sNew : String;
bFirstOp : boolean;
Begin
result := '';
try
s := ''; sNew := ''; bFirstOp := True;
for i := Low(sa) to High(sa) do begin
s := sa[i];
if QuoteStrings then s := ForceStr(s, '"', '"');
if ( i < High(sa)) then begin
if bFirstOp then
s := s + MinorDelimiter
else
s := s + MajorDelimiter;
end;
bFirstOp := not bFirstOp;
sNew := sNew + s;
end; {for}
result := sNew;
except
ErrorRaised(UNIT_NAME + ':ucGetStringParm(' + Parms( [ 'v', 'Variant()', 'QuoteStrings', QuoteStrings, 'MajorDelimiter', MajorDelimiter, 'MinorDelimiter', MinorDelimiter], True) + ')', ExceptObject);
end; {try}
End;
function CFileDir.GetShortFileName(const FileName: TFileName): TFileName;
var
buffer: array[0..MAX_PATH-1] of char;
begin
SetString(Result, buffer, GetShortPathName(
pchar(FileName), buffer, MAX_PATH-1));
end;
function CFileDir.GetStringParm(v: array of Variant; Paired: Boolean;
MajorDelimiter, MinorDelimiter: String): String;
begin
end;
function CFileDir.ucPos(StringToSearchIn, StringToFind: String;
StartPos: Cardinal; CaseSensitive: boolean): Cardinal;
var
nStartPos, cPos : Cardinal;
Begin
result := 0;
try
if (( StartPos > Length(StringToSearchIn)) or ( StartPos < 1 )) then
nStartPos := 0
else
nStartPos := StartPos;
for cPos := nStartPos to Length(StringToSearchIn) do begin
if ( CompareString(StringToFind, Copy(StringToSearchIn, cPos, Length(StringToFind)), CaseSensitive) = COMPARED_EQUAL ) then begin
result := cPos;
Break;
end;
end; {for}
except
ErrorRaised(UNIT_NAME + ':CFileDir.ucPos ' + Parms( [ 'StringToSearchIn', StringToSearchIn, 'StringToFind', StringToFind , 'StartPos', StartPos ], True), ExceptObject);
raise;
end; {try}
End;
function CFileDir.DeleteFilesInPath( const PathName: String): integer;
var
slFilesToDelete : TSTringList;
i, nDelCount : integer;
begin
Result := 0;
nDelCount := 0;
try
slFilesToDelete := GetFileList( PathName, true );
for i := 0 to slFilesToDelete.Count - 1 do begin
if ( DeleteFile( PChar( slFilesToDelete[i] ) ) ) then
Inc( nDelCount );
end;
finally
FreeAndNil( slFilesToDelete );
end;
Result := nDelCount;
end;
function CFileDir.GetFileList( PathName : String; ShowDirectory : boolean = false) : TStringList;
//Obtain list of all files in a directoy with mask "Pathfile".. wild card characters work
var
slResult : TStringList;
nReturnCode : integer;
bIsDirectory : boolean;
sCurrent, sPathName : String;
SearchRec: TSearchRec;
Begin
bIsDirectory := False;
slResult := TStringList.Create;
sPathName := AddPath(PathName);
try
try
//nReturnCode := FindFirst(sPathName, faAnyFile, SearchRec);
FindFirst(sPathName, faAnyFile, SearchRec);
//SearchRec.Attr = faDirectory;
sCurrent := SearchRec.Name;
While ( sCurrent <> '' ) do begin
sCurrent := Slash(ExtractFileDir(sPathName)) + sCurrent;
if ( sCurrent[Length(sCurrent)] <> '.') then begin
if ( ShowDirectory ) and (bIsDirectory) then sCurrent := sCurrent + '+';
if ((ShowDirectory) and ( bIsDirectory)) or (not bIsDirectory) then begin
slResult.Add( sCurrent );
end; {if}
end; { if}
bIsDirectory := False;
nReturnCode := FindNext(SearchRec);
if nReturnCode = 0 then begin
sCurrent := SearchRec.Name;
if ( SearchRec.Attr = faDirectory ) then bIsDirectory := True;
end else
sCurrent := '';
end; {while}
slResult.Sort;
finally
FindClose( SearchRec.FindHandle );
end;
except
ErrorRaised(UNIT_NAME + ':GetFileList' + Parms( [ 'PathName', PathName, 'ShowDirectory' , ShowDirectory] , True), ExceptObject);
raise;
end; {try}
result := slResult;
End;
Procedure CFileDir.WriteString( StringToWrite, FileToWriteTo : String; AppendToFile : boolean);
var
F1 : TextFile;
sFileName, sDir : string;
Begin
try
sFileName := AddPath(FileToWriteTo);
sDir := ExtractFilePath(sFileName);
if (not DirectoryExists(sDir)) then ForceDirectories(sDir);
AssignFile(F1, sFileName);
if ( AppendToFile ) and (FileExists(sFileName)) then
Append(F1)
else
Rewrite(F1);
Write(F1, StringToWrite);
CloseFile(F1);
except
ErrorRaised(UNIT_NAME + ':WriteString' + Parms( [ 'StringToWrite', StringToWrite, 'FileToWriteTo', 'FileToWriteTo' , 'AppendToFile', AppendToFile ], True), ExceptObject);
raise;
end; {try}
End;
Function CFileDir.TextFileToString( FileToReadFrom : String; StripCrlf : Boolean ) : String;
var
F1 : TextFile;
sFileName, sInput, s : string;
Begin
try
sFileName := AddPath(FileToReadFrom);
AssignFile(F1, sFileName);
Reset(F1);
while not Eof(F1) do begin
Readln(F1, sInput);
s := s + sInput;
if not StripCrlf then s := s + ucCrLf
end;
CloseFile(F1);
except
ErrorRaised(UNIT_NAME + ':TextFileToString' + Parms( [ 'FileToReadFrom', FileToReadFrom, 'StripCrlf', StripCrlf ], True), ExceptObject);
raise;
end; {try}
TextFileToString := s;
End;
//function CFileDir.BrowseForFolder(var FolderName: String): Boolean;
//Begin
// Result := BrowseForFolderAPI( 'Browser For Folder', FolderName );
//End;
function CFileDir.BrowseForFolder(var FolderName: String): Boolean;
var
BrowseInfo : TBrowseInfo;
ItemIDList : PItemIDList;
DisplayName : array[0..MAX_PATH] of Char;
begin
Result:=False;
FillChar(BrowseInfo,SizeOf(BrowseInfo),#0);
with BrowseInfo do begin
// hwndOwner:=Application.Handle;
hwndOwner:=0;
pszDisplayName:=@DisplayName[0];
lpszTitle:='Select a folder';
ulFlags:=BIF_RETURNONLYFSDIRS;
if ( Length( lg_StartFolder ) > 0 ) then
lpfn := BrowseForFolderCallBack;
end;
ItemIDList:=SHBrowseForFolder(BrowseInfo);
if Assigned(ItemIDList) then begin
if SHGetPathFromIDList(ItemIDList,DisplayName) then
begin
FolderName:=DisplayName;
lg_StartFolder := '';
Result:=True;
end;
GlobalFreePtr(ItemIDList);
end;
lg_StartFolder := '';
End;
Function CFileDir.OpenDlg(var SelectedFile : String; DefaultFileTypes : String = 'All Files (*.*)|*.*'; Title : String = '{AppName}'; DefaultFile : String = '') : Boolean;
var dlg : TOpenDialog; sPath, sNewFileName : String;
Begin
SelectedFile := '';
result := false;
dlg := TOpenDialog.Create(nil);
try
dlg.Filter := DefaultFileTypes;
if Title = '{AppName}' then
dlg.Title := Application.Title
else
dlg.Title := Title;
sPath := ExtractFilePath(DefaultFile);
if ( Trim(sPath) = '' ) then sPath := AppDir;
dlg.InitialDir := sPath;
dlg.FileName := ExtractFileName(DefaultFile);
if dlg.Execute then begin
SelectedFile := dlg.FileName;
result := True;
end;
except
ErrorRaised(UNIT_NAME + ':OpenDlg', ExceptObject);
raise;
end; {try}
dlg.Free;
End;
Function CFileDir.OpenDlgAPI(var SelectedFile : String; DefaultFileTypes : String = 'All Files (*.*)|*.*'; Title : String = '{AppName}'; DefaultFile : String = ''; DefaultExt : String = 'txt'; InitialPath : String = '{CURDIR}' ) : Boolean;
var sPath, sNewFileName : String;
Begin
if (( InitialPath='{CURDIR}' ) or ( Length(InitialPath) = 0 )) then
begin
InitialPath:= AddPath('.');
end;
if Title = '{AppName}' then
Title := Application.Title
else
Title := Title;
SelectedFile := '';
sNewFileName := DefaultFile;
if ( OpenSaveFileDialog(Application.Handle, DefaultExt, DefaultFileTypes, InitialPath, Title, sNewFileName, True) ) then
begin
SelectedFile := sNewFileName;
Result := true;
end else
Result := false;
End;
function CFileDir.GetFileDateTime(FullFileName : String): TDateTime;
var
FileHandle : integer;
begin
try
FileHandle := FileOpen(FullFileName, fmShareDenyNone);
if ( FileHandle > 0 ) then
result := FileDateToDateTime(FileGetDate(FileHandle))
else
result := 0.0;
FileClose(FileHandle);
except
ErrorRaised(UNIT_NAME + ':OpenDlg', ExceptObject);
raise;
end; {try}
end;
function CFileDir.GetSystemTempDir : String;
Begin
GetSystemTempDir := self.Slash( GetEnvironmentVariable(apiTEMP) );
end;
function CFileDir.GetUserDir: string;
begin
Result := Slash( GetEnvironmentVariable( apiUSERDIR ) );
end;
procedure CFileDir.GetVersion(const sFileName: string;
var ReturnVersion: string);
var
VerInfoSize: DWORD;
VerInfo: Pointer;
VerValueSize: DWORD;
VerValue: PVSFixedFileInfo;
Dummy: DWORD;
begin
ReturnVersion := '';
VerInfoSize := GetFileVersionInfoSize(PChar(sFileName), Dummy);
GetMem(VerInfo, VerInfoSize);
GetFileVersionInfo(PChar(sFileName), 0, VerInfoSize, VerInfo);
VerQueryValue(VerInfo, '\', Pointer(VerValue), VerValueSize);
with VerValue^ do
begin
ReturnVersion := IntToStr(dwFileVersionMS shr 16);
ReturnVersion := ReturnVersion + '.' + IntToStr(dwFileVersionMS and $FFFF);
ReturnVersion := ReturnVersion + '.' + IntToStr(dwFileVersionLS shr 16);
ReturnVersion := ReturnVersion + '.' + IntToStr(dwFileVersionLS and $FFFF);
end;
FreeMem(VerInfo, VerInfoSize);
end;
function CFileDir.GetVersion(const sFileName:string): string;
var
VerInfoSize: DWORD;
VerInfo: Pointer;
VerValueSize: DWORD;
VerValue: PVSFixedFileInfo;
Dummy: DWORD;
begin
VerInfoSize := GetFileVersionInfoSize(PChar(sFileName), Dummy);
GetMem(VerInfo, VerInfoSize);
GetFileVersionInfo(PChar(sFileName), 0, VerInfoSize, VerInfo);
VerQueryValue(VerInfo, '\', Pointer(VerValue), VerValueSize);
with VerValue^ do
begin
Result := IntToStr(dwFileVersionMS shr 16);
Result := Result + '.' + IntToStr(dwFileVersionMS and $FFFF);
Result := Result + '.' + IntToStr(dwFileVersionLS shr 16);
Result := Result + '.' + IntToStr(dwFileVersionLS and $FFFF);
end;
FreeMem(VerInfo, VerInfoSize);
end;
Function CFileDir.GetEnvironmentVariable(sVariable : string) : String;
{ Returns the value of an environment variable.. Wrapper around WIN API Call}
var
pcPath : PChar;
rc : LongInt;
begin
Result := '';
GetMem(pcPath, BUFFER_MAX_LENGTH);
try
rc := APIGetEnvironmentVariable(PChar(sVariable), pcPath,LongInt(BUFFER_MAX_LENGTH));
except
ErrorRaised('Exception Raised while trying to call function APIGetSystemDir', ExceptObject);
end;
if ( rc > 0 ) then Result := StrPas(pcPath);
FreeMem(pcPath);
end;
function CFileDir.GetSubDirList( PathName : String; MaxDepth : longint = 0 ) : TStringList;
//Obtains all the folders and child folders from a path up to a depth specified on MacDepth
var
slResult : TStringList;
i : LongInt;
Begin
i := 0;
slResult := TStringList.Create;
try
_GetSubDirList(PathName, slResult, i, MaxDepth);
except
ErrorRaised(UNIT_NAME + 'GetSubDirList' + Parms( [ 'PathName', PathName, 'MaxDepth', MaxDepth], True), ExceptObject);
raise;
end;
slResult.Sort;
result := slResult;
End;
function CFileDir._GetSubDirList( PathName : String; DirectoryList : TStringList; CurrentDepth : longint; MaxDepth : longint = 0 ) : longint;
var
i, nCount : integer;
slCurLvlDir : TStringList;
Begin
slCurLvlDir := TStringList.Create;
i := 0;
nCount := 0;
try
if ( GetChildDirs(PathName, slCurLvlDir, CurrentDepth, MaxDepth) > 0 ) then begin
Inc(CurrentDepth);
for i := 0 to slCurLvlDir.Count - 1 do begin
_GetSubDirList(slCurLvlDir[i], DirectoryList, CurrentDepth, MaxDepth);
end; {for}
end;
DirectoryList.AddStrings(slCurLvlDir);
except
ErrorRaised(UNIT_NAME + ':_GetSubDirList' + Parms( [ 'PathName', PathName, 'DirectoryList', 'TStringList' , 'CurrentDepth', CurrentDepth, 'MaxDepth', MaxDepth], True), ExceptObject);
raise;
end; {try}
_GetSubDirList := DirectoryList.Count;
slCurLvlDir.Destroy;
End;
function CFileDir.GetChildDirs( PathName : String; DirectoryList : TStringList; CurrentDepth : longint; MaxDepth : longint = 0 ) : longint;
var
nReturnCode, nCount : integer;
bIsDirectory : boolean;
sCurrentDir : String;
SearchRec: TSearchRec;
Begin
nCount := 0;
bIsDirectory := False;
if ( CurrentDepth <= MaxDepth ) then begin
try
nReturnCode := FindFirst(Slash(PathName) + '*.*', faDirectory, SearchRec);
//SearchRec.Attr = faDirectory;
sCurrentDir := SearchRec.Name;
While ( sCurrentDir <> '' ) do begin
sCurrentDir := Slash(PathName) + sCurrentDir;
if ( sCurrentDir[Length(sCurrentDir)] <> '.') then begin
//if bIsDirectory then sCurrentDir := sCurrentDir + '+';
if bIsDirectory then begin
DirectoryList.Add(sCurrentDir);
Inc(nCount);
end; {if}
end; { if}
bIsDirectory := False;
nReturnCode := FindNext(SearchRec);
if nReturnCode = 0 then begin
sCurrentDir := SearchRec.Name;
bIsDirectory := DirectoryExists( Slash(PathName) + sCurrentDir );
//if ( SearchRec.Attr = faDirectory ) then bIsDirectory := True;
end else
sCurrentDir := '';
end; {while}
except
ErrorRaised(UNIT_NAME + ':GetChildDirs' + Parms( [ 'PathName', PathName, 'DirectoryList', 'TStringList' , 'CurrentDepth', CurrentDepth, 'MaxDepth' , MaxDepth] , True), ExceptObject);
raise;
end; {try}
end; {if}
result := nCount;
End;
function CFileDir.GetSpecialFolder(FolderID : longint) : string;
var
Path : pchar;
idList : PItemIDList;
begin
GetMem(Path, MAX_PATH);
SHGetSpecialFolderLocation(0, FolderID, idList);
SHGetPathFromIDList(idList, Path);
Result := string(Path);
FreeMem(Path);
end;
function CFileDir.GetTmpInternetDir: string;
begin
Result := Slash(GetSpecialFolder(CSIDL_INTERNET_CACHE));
end;
function CFileDir.GetCookiesDir: string;
begin
Result := Slash(GetSpecialFolder(CSIDL_COOKIES));
end;
function CFileDir.GetHistoryDir: string;
begin
Result := Slash(GetSpecialFolder(CSIDL_HISTORY));
end;
function CFileDir.GetDesktop: string;
begin
Result := Slash(GetSpecialFolder(CSIDL_DESKTOP));
end;
function CFileDir.GetDesktopDir: string;
begin
Result := Slash(GetSpecialFolder(CSIDL_DESKTOPDIRECTORY));
end;
function CFileDir.GetProgDir: string;
begin
Result := Slash(GetSpecialFolder(CSIDL_PROGRAMS));
end;
function CFileDir.GetMyDocDir: string;
begin
Result := Slash(GetSpecialFolder(CSIDL_PERSONAL));
end;
function CFileDir.GetFavDir: string;
begin
Result := Slash(GetSpecialFolder(CSIDL_FAVORITES));
end;
function CFileDir.GetStartUpDir: string;
begin
Result := Slash(GetSpecialFolder(CSIDL_STARTUP));
end;
function CFileDir.GetRecentDir: string;
begin
Result := Slash(GetSpecialFolder(CSIDL_RECENT));
end;
function CFileDir.GetSendToDir: string;
begin
Result := Slash(GetSpecialFolder(CSIDL_SENDTO));
end;
function CFileDir.GetStartMenuDir: string;
begin
Result := Slash(GetSpecialFolder(CSIDL_STARTMENU));
end;
function CFileDir.GetNetHoodDir: string;
begin
Result := Slash(GetSpecialFolder(CSIDL_NETHOOD));
end;
function CFileDir.GetFontsDir: string;
begin
Result := Slash(GetSpecialFolder(CSIDL_FONTS));
end;
function CFileDir.GetTemplateDir: string;
begin
Result := Slash(GetSpecialFolder(CSIDL_TEMPLATES));
end;
function CFileDir.GetAppDataDir: string;
begin
Result := Slash(GetSpecialFolder(CSIDL_APPDATA));
end;
function CFileDir.GetPrintHoodDir: string;
begin
Result := Slash(GetSpecialFolder(CSIDL_PRINTHOOD));
end;
function BrowseForFolderCallBack(Wnd: HWND; uMsg: UINT;
lParam, lpData: LPARAM): Integer stdcall;
begin
if uMsg = BFFM_INITIALIZED then
SendMessage(Wnd,BFFM_SETSELECTION, 1,
Integer(@lg_StartFolder[1]));
result := 0;
end;
function BrowseForFolderAPI(const browseTitle: String; var SelectedFolder : string;
const initialFolder: String =''): boolean;
var
browse_info: TBrowseInfo;
folder: array[0..MAX_PATH] of char;
find_context: PItemIDList;
begin
FillChar(browse_info,SizeOf(browse_info),#0);
lg_StartFolder := initialFolder;
browse_info.pszDisplayName := @folder[0];
browse_info.lpszTitle := PChar(browseTitle);
browse_info.ulFlags := BIF_RETURNONLYFSDIRS;
browse_info.lpfn := BrowseForFolderCallBack;
find_context := SHBrowseForFolder(browse_info);
if Assigned(find_context) then
begin
if SHGetPathFromIDList(find_context,folder) then
SelectedFolder := folder
else
SelectedFolder := '';
end
else
SelectedFolder := '';
Result := ( Length(SelectedFolder) > 0 );
end;
function GetModuleName: string;
var
NameBuffer: array[ 0..MAX_PATH ] of char;
begin
ZeroMemory( @NameBuffer, SizeOf( NameBuffer ) );
GetModuleFileName( HInstance, NameBuffer, Pred( SizeOf( NameBuffer ) ) );
Result := ExtractFileName(NameBuffer);
end;
Procedure WriteString( StringToWrite, FileToWriteTo : String; AppendToFile : boolean);
var
fd : CFiledir;
Begin
try
fd := CFiledir.Create();
fd.WriteString( StringToWrite + #13#10, FileToWriteTo, AppendToFile );
finally
FreeAndNil( fd );
end; {try}
End;
END.
|
unit EditBone.Output;
interface
uses
Winapi.Windows, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.ComCtrls, EditBone.Types,
VirtualTrees, BCComponent.SkinManager, BCControl.PageControl, BCCommon.Images, sPageControl;
type
TEBOutput = class(TObject)
procedure VirtualDrawTreeDrawNode(Sender: TBaseVirtualTree; const PaintInfo: TVTPaintInfo);
procedure VirtualDrawTreeFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode);
procedure VirtualDrawTreeGetNodeWidth(Sender: TBaseVirtualTree; HintCanvas: TCanvas; Node: PVirtualNode;
Column: TColumnIndex; var NodeWidth: Integer);
procedure VirtualDrawTreeInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode;
var InitialStates: TVirtualNodeInitStates);
procedure TabsheetDblClick(Sender: TObject);
private
FCancelSearch: Boolean;
FProcessingTabSheet: Boolean;
FProcessingPage: TsTabSheet;
FTabsheetDblClick: TNotifyEvent;
FOpenAll: TOpenAllEvent;
FRootNode: PVirtualNode;
FPageControl: TBCPageControl;
FTabSheetFindInFiles: TTabSheet;
FSkinManager: TBCSkinManager;
function GetOutputTreeView(ATabSheet: TTabSheet): TVirtualDrawTree;
function TabFound(const ATabCaption: string): Boolean;
function CheckCancel(const ATabIndex: Integer = -1): Boolean;
public
constructor Create(AOwner: TBCPageControl);
function CloseTabSheet(const AFreePage: Boolean = True; const ATabIndex: Integer = -1): Boolean;
function SelectedLine(var AFilename: string; var ALine: LongWord; var ACharacter: LongWord): Boolean;
function AddTreeView(const ATabCaption: string): TVirtualDrawTree;
procedure AddTreeViewLine(AOutputTreeView: TVirtualDrawTree; const AFilename: string; const ALine, ACharacter: LongInt;
const AText: string; const ASearchString: string; const ALength: Integer);
procedure ReadOutputFile;
procedure SetOptions;
procedure WriteOutputFile;
procedure CloseAllOtherTabSheets;
procedure CloseAllTabSheets;
procedure CopyToClipboard(const AOnlySelected: Boolean = False);
procedure SetProcessingTabSheet(const AValue: Boolean);
procedure OpenFiles(const AOnlySelected: Boolean = False);
procedure SetCheckedState(const AValue: TCheckState);
property OnTabsheetDblClick: TNotifyEvent read FTabsheetDblClick write FTabsheetDblClick;
property OnOpenAll: TOpenAllEvent read FOpenAll write FOpenAll;
property ProcessingTabSheet: Boolean read FProcessingTabSheet write SetProcessingTabSheet;
property CancelSearch: Boolean read FCancelSearch write FCancelSearch;
property SkinManager: TBCSkinManager read FSkinManager write FSkinManager;
property PageControl: TBCPageControl read FPageControl;
end;
implementation
uses
BCCommon.Options.Container, System.UITypes, System.Math, Vcl.Clipbrd, BCCommon.Messages,
BCCommon.Language.Strings, BCCommon.FileUtils, BCCommon.Consts, BCCommon.StringUtils, System.Types,
BCControl.Panel;
constructor TEBOutput.Create(AOwner: TBCPageControl);
begin
inherited Create;
FPageControl := AOwner;
FTabSheetFindInFiles := AOwner.Pages[0];
end;
procedure TEBOutput.TabsheetDblClick(Sender: TObject);
begin
if Assigned(FTabsheetDblClick) then
FTabsheetDblClick(Sender);
end;
procedure TEBOutput.OpenFiles(const AOnlySelected: Boolean);
var
LFileNames: TStrings;
procedure GetFileNames;
var
LOutputTreeView: TVirtualDrawTree;
LNode: PVirtualNode;
LData: POutputRec;
begin
LOutputTreeView := GetOutputTreeView(PageControl.ActivePage);
LNode := LOutputTreeView.GetFirst;
while Assigned(LNode) do
begin
if not AOnlySelected or AOnlySelected and (LOutputTreeView.CheckState[LNode] = csCheckedNormal) then
begin
LData := LOutputTreeView.GetNodeData(LNode);
LFileNames.Add(LData.FileName);
end;
LNode := LNode.NextSibling;
end;
end;
begin
if Assigned(FOpenAll) then
begin
LFileNames := TStringList.Create;
try
GetFileNames;
FOpenAll(LFileNames);
finally
LFileNames.Free;
end;
end;
end;
function TEBOutput.TabFound(const ATabCaption: string): Boolean;
var
i: Integer;
begin
Result := False;
{ check if there already is a tab with same name }
for i := 0 to PageControl.PageCount - 1 do
if Trim(PageControl.Pages[i].Caption) = ATabCaption then
begin
PageControl.ActivePageIndex := i;
Result := True;
Break;
end;
end;
function TEBOutput.AddTreeView(const ATabCaption: string): TVirtualDrawTree;
var
LTabSheet: TsTabSheet;
LVirtualDrawTree: TVirtualDrawTree;
//LPanel: TBCPanel;
LTabCaption: string;
begin
LTabCaption := StringReplace(ATabCaption, '&', '&&', [rfReplaceAll]);
{ check if there already is a tab with same name }
if TabFound(LTabCaption) then
begin
Result := GetOutputTreeView(PageControl.ActivePage);
if Assigned(Result) then
begin
Result.Clear;
Result.Tag := 0;
end;
Exit;
end;
LTabSheet := TsTabSheet.Create(PageControl);
LTabSheet.PageControl := PageControl;
if Assigned(FTabSheetFindInFiles) then
FTabSheetFindInFiles.PageIndex := FPageControl.PageCount - 1;
LTabSheet.TabVisible := False;
LTabSheet.ImageIndex := IMAGE_INDEX_FIND_IN_FILES;
LTabSheet.Caption := LTabCaption;
PageControl.ActivePage := LTabSheet;
LVirtualDrawTree := TVirtualDrawTree.Create(LTabSheet);
with LVirtualDrawTree do
begin
Parent := LTabSheet;
Align := alClient;
AlignWithMargins := True;
Margins.Left := 2;
Margins.Top := 2;
if FSkinManager.Active then
Margins.Right := 2
else
Margins.Right := 4;
Margins.Bottom := 2;
TreeOptions.AutoOptions := [toAutoDropExpand, toAutoScroll, toAutoChangeScale, toAutoScrollOnExpand, toAutoTristateTracking];
TreeOptions.MiscOptions := [toCheckSupport, toFullRepaintOnResize, toToggleOnDblClick, toWheelPanning];
TreeOptions.PaintOptions := [toHideFocusRect, toShowButtons, toShowRoot, toThemeAware, toGhostedIfUnfocused];
TreeOptions.SelectionOptions := [toFullRowSelect, toMiddleClickSelect];
OnDrawNode := VirtualDrawTreeDrawNode;
OnFreeNode := VirtualDrawTreeFreeNode;
OnGetNodeWidth := VirtualDrawTreeGetNodeWidth;
OnInitNode := VirtualDrawTreeInitNode;
OnDblClick := TabsheetDblClick;
NodeDataSize := SizeOf(TOutputRec);
DefaultNodeHeight := Max(Canvas.TextHeight('Tg'), 18);
Indent := OptionsContainer.OutputIndent;
if OptionsContainer.OutputUseExplorerTheme then
TreeOptions.PaintOptions := TreeOptions.PaintOptions + [toUseExplorerTheme]
else
TreeOptions.PaintOptions := TreeOptions.PaintOptions - [toUseExplorerTheme];
if OptionsContainer.OutputShowTreeLines then
TreeOptions.PaintOptions := TreeOptions.PaintOptions + [toShowTreeLines]
else
TreeOptions.PaintOptions := TreeOptions.PaintOptions - [toShowTreeLines];
end;
Result := LVirtualDrawTree;
LTabSheet.TabVisible := True;
end;
procedure TEBOutput.VirtualDrawTreeDrawNode(Sender: TBaseVirtualTree; const PaintInfo: TVTPaintInfo);
var
LData: POutputRec;
S, Temp: string;
LRect: TRect;
LFormat: Cardinal;
LColor: TColor;
begin
with Sender as TVirtualDrawTree, PaintInfo do
begin
LData := Sender.GetNodeData(Node);
if not Assigned(LData) then
Exit;
if Assigned(FSkinManager) then
LColor := FSkinManager.GetActiveEditFontColor
else
LColor := clWindowText;
if vsSelected in PaintInfo.Node.States then
begin
if Assigned(FSkinManager) then
LColor := FSkinManager.GetHighLightFontColor
else
LColor := clHighlightText;
end;
Canvas.Font.Color := LColor;
if LData.Level = 0 then
Canvas.Font.Style := Canvas.Font.Style + [fsBold]
else
Canvas.Font.Style := Canvas.Font.Style - [fsBold];
SetBKMode(Canvas.Handle, TRANSPARENT);
LRect := ContentRect;
InflateRect(LRect, -TextMargin, 0);
Dec(LRect.Right);
Dec(LRect.Bottom);
if LData.Level = 2 then
LRect.Left := 4;
if (LData.Level = 0) or (LData.Level = 2) then
S := LData.Filename
else
S := LData.Text;
if Length(S) > 0 then
begin
LFormat := DT_TOP or DT_LEFT or DT_VCENTER or DT_SINGLELINE;
if (LData.Level = 0) or (LData.Level = 2) or (LData.SearchString = '') then
begin
if LData.Level = 0 then
S := System.SysUtils.Format('%s [%d]', [S, Node.ChildCount]);
if LData.Level = 1 then
S := System.SysUtils.Format('%s (%d, %d): ', [ExtractFilename(LData.Filename), LData.Line +
OptionsContainer.LeftMarginLineNumbersStartFrom, LData.Character]) + S;
DrawText(Canvas.Handle, S, Length(S), LRect, LFormat)
end
else
begin
S := LData.Text;
S := System.Copy(S, 0, LData.TextCharacter - 1);
S := System.SysUtils.Format('%s (%d, %d): ', [ExtractFilename(LData.Filename), LData.Line +
OptionsContainer.LeftMarginLineNumbersStartFrom, LData.Character]) + S;
DrawText(Canvas.Handle, S, Length(S), LRect, LFormat);
S := StringReplace(S, Chr(9), '', [rfReplaceAll]); { replace tabs }
Inc(LRect.Left, Canvas.TextWidth(S));
Canvas.Font.Color := clRed;
S := Copy(LData.Text, LData.TextCharacter, LData.Length);
Temp := StringReplace(S, '&', '&&', [rfReplaceAll]);
Canvas.Font.Style := Canvas.Font.Style + [fsBold];
DrawText(Canvas.Handle, Temp, Length(Temp), LRect, LFormat);
Canvas.Font.Color := LColor;
inc(LRect.Left, Canvas.TextWidth(S));
Canvas.Font.Style := Canvas.Font.Style - [fsBold];
S := System.Copy(LData.Text, Integer(LData.TextCharacter) + LData.Length, Length(LData.Text));
DrawText(Canvas.Handle, S, Length(S), LRect, LFormat);
end;
end;
end;
end;
procedure TEBOutput.VirtualDrawTreeGetNodeWidth(Sender: TBaseVirtualTree;
HintCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; var NodeWidth: Integer);
var
LData: POutputRec;
LMargin, LBoldWidth: Integer;
S: string;
begin
with Sender as TVirtualDrawTree do
begin
LMargin := TextMargin;
LData := Sender.GetNodeData(Node);
if Assigned(LData) then
case LData.Level of
0: begin
Canvas.Font.Style := Canvas.Font.Style + [fsBold];
NodeWidth := Canvas.TextWidth(Trim(Format('%s [%d]', [LData.FileName, Node.ChildCount]))) + 2 * LMargin;
end;
1: begin
S := System.SysUtils.Format('%s (%d, %d): ', [ExtractFilename(LData.Filename), LData.Line, LData.Character]);
Canvas.Font.Style := Canvas.Font.Style + [fsBold];
LBoldWidth := Canvas.TextWidth(LData.SearchString);
Canvas.Font.Style := Canvas.Font.Style - [fsBold];
LBoldWidth := LBoldWidth - Canvas.TextWidth(LData.SearchString);
NodeWidth := Canvas.TextWidth(Trim(S + LData.Text)) + 2 * LMargin + LBoldWidth;
end;
end;
end;
end;
procedure TEBOutput.VirtualDrawTreeFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode);
var
Data: POutputRec;
begin
Data := Sender.GetNodeData(Node);
Finalize(Data^);
inherited;
end;
procedure TEBOutput.AddTreeViewLine(AOutputTreeView: TVirtualDrawTree; const AFilename: string; const ALine, ACharacter: LongInt;
const AText: string; const ASearchString: string; const ALength: Integer);
var
LNode, LLastNode: PVirtualNode;
LNodeData: POutputRec;
S: WideString;
begin
if not FProcessingTabSheet then
Exit;
if FCancelSearch then
Exit;
if not Assigned(AOutputTreeView) then
Exit;
AOutputTreeView.DefaultNodeHeight := Max(AOutputTreeView.Canvas.TextHeight('Tg'), 18);
AOutputTreeView.BeginUpdate;
LLastNode := AOutputTreeView.GetLast;
if Assigned(LLastNode) then
begin
LNodeData := AOutputTreeView.GetNodeData(LLastNode);
if (LNodeData.Filename <> AFileName) or (LNodeData.Line = -1) then
LLastNode := nil;
end;
if not Assigned(LLastNode) then
begin
FRootNode := AOutputTreeView.AddChild(nil);
LNodeData := AOutputTreeView.GetNodeData(FRootNode);
LNodeData.Level := 0;
if ALine = -1 then
begin
LNodeData.Level := 2;
LNodeData.Filename := AText;
end
else
LNodeData.Filename := AFilename;
end;
if ALine <> -1 then
begin
LNode := AOutputTreeView.AddChild(FRootNode);
LNodeData := AOutputTreeView.GetNodeData(LNode);
LNodeData.Level := 1;
LNodeData.Line := ALine;
LNodeData.Character := ACharacter;
LNodeData.SearchString := ASearchString;
LNodeData.Filename := AFilename;
LNodeData.Length := ALength;
S := AText;
if LNodeData.SearchString <> '' then
begin
if ACharacter > 255 then
begin
LNodeData.TextCharacter := 11;
S := System.Copy(s, ACharacter - 10, System.Length(s));
end
else
LNodeData.TextCharacter := ACharacter;
if System.Length(S) > 255 then
S := Format('%s...', [System.Copy(S, 0, 251)]);
end;
if toAutoExpand in AOutputTreeView.TreeOptions.AutoOptions then
if not AOutputTreeView.Expanded[FRootNode] then
AOutputTreeView.FullExpand(FRootNode);
LNodeData.Text := S;
AOutputTreeView.Tag := AOutputTreeView.Tag + 1;
end;
AOutputTreeView.EndUpdate;
end;
function TEBOutput.SelectedLine(var AFilename: string; var ALine: LongWord; var ACharacter: LongWord): Boolean;
var
LNode: PVirtualNode;
LNodeData: POutputRec;
LOutputTreeView: TVirtualDrawTree;
begin
Result := False;
LOutputTreeView := GetOutputTreeView(PageControl.ActivePage);
if not Assigned(LOutputTreeView) then
Exit;
LNode := LOutputTreeView.GetFirstSelected;
LNodeData := LOutputTreeView.GetNodeData(LNode);
Result := Assigned(LNodeData) and (LNodeData.Text <> '');
if Result then
begin
AFilename := LNodeData.Filename;
ALine := LNodeData.Line;
ACharacter := LNodeData.Character;
end;
end;
procedure TEBOutput.CopyToClipboard(const AOnlySelected: Boolean);
var
LOutputTreeView: TVirtualDrawTree;
LNode, LChildNode: PVirtualNode;
LData, LChildData: POutputRec;
LStringList: TStrings;
begin
LOutputTreeView := GetOutputTreeView(PageControl.ActivePage);
if Assigned(LOutputTreeView) then
begin
LStringList := TStringList.Create;
try
LNode := LOutputTreeView.GetFirst;
while Assigned(LNode) do
begin
if not AOnlySelected or AOnlySelected and (LOutputTreeView.CheckState[LNode] = csCheckedNormal) then
begin
LData := LOutputTreeView.GetNodeData(LNode);
LStringList.Add(LData.FileName);
LChildNode := LNode.FirstChild;
while Assigned(LChildNode) do
begin
LChildData := LOutputTreeView.GetNodeData(LChildNode);
LStringList.Add(System.SysUtils.Format(' %s (%d, %d): %s', [ExtractFilename(LChildData.Filename),
LChildData.Line, LChildData.Character, LChildData.Text]));
LChildNode := LChildNode.NextSibling;
end;
end;
LNode := LNode.NextSibling;
end;
finally
Clipboard.AsText := LStringList.Text;
LStringList.Free;
end;
end;
end;
function TEBOutput.CheckCancel(const ATabIndex: Integer = -1): Boolean;
var
LTabSheet: TTabSheet;
begin
Result := False;
Application.ProcessMessages;
if ATabIndex <> -1 then
LTabSheet := PageControl.Pages[ATabIndex]
else
LTabSheet := PageControl.ActivePage;
if FProcessingTabSheet then
if FProcessingPage = LTabSheet then
begin
if AskYesOrNo(LanguageDataModule.GetYesOrNoMessage('CancelSearch')) then
FCancelSearch := True
else
Result := True;
end;
end;
function TEBOutput.CloseTabSheet(const AFreePage: Boolean = True; const ATabIndex: Integer = -1): Boolean;
var
LActivePageIndex: Integer;
begin
Result := True;
FPageControl.TabClosed := True;
if CheckCancel(ATabIndex) then
Exit(False);
if FPageControl.PageCount > 0 then
begin
if ATabIndex = -1 then
LActivePageIndex := FPageControl.ActivePageIndex
else
LActivePageIndex := ATabIndex;
if AFreePage and (FPageControl.PageCount > 0) then
begin
FPageControl.Pages[LActivePageIndex].Free;
if LActivePageIndex > 0 then
FPageControl.ActivePageIndex := LActivePageIndex - 1
else
if FPageControl.PageCount > 0 then
FPageControl.ActivePageIndex := 0;
end
else
begin
TsTabSheet(FPageControl.Pages[LActivePageIndex]).TabVisible := False;
FPageControl.Pages[LActivePageIndex].PageIndex := LActivePageIndex + 1;
end;
end;
end;
procedure TEBOutput.CloseAllTabSheets;
var
i, j: Integer;
begin
Screen.Cursor := crHourGlass;
try
PageControl.Visible := False;
j := PageControl.PageCount - 2;
for i := j downto 0 do
if TsTabSheet(PageControl.Pages[i]).TabType = ttTab then
CloseTabSheet(True, i);
PageControl.Visible := True;
finally
Screen.Cursor := crDefault;
end;
end;
procedure TEBOutput.CloseAllOtherTabSheets;
var
i, j: Integer;
LTabSheet: TsTabSheet;
begin
if CheckCancel then
Exit;
LTabSheet := PageControl.ActivePage;
LTabSheet.PageIndex := 0; { move the page first }
Screen.Cursor := crHourGlass;
try
PageControl.Visible := False;
j := PageControl.PageCount - 2;
for i := j downto 1 do
PageControl.Pages[i].Free;
PageControl.ActivePage := LTabSheet;
PageControl.Visible := True;
finally
Screen.Cursor := crDefault;
end;
end;
procedure TEBOutput.SetProcessingTabSheet(const AValue: Boolean);
begin
FProcessingTabSheet := AValue;
FProcessingPage := PageControl.ActivePage;
FCancelSearch := False;
end;
function TEBOutput.GetOutputTreeView(ATabSheet: TTabSheet): TVirtualDrawTree;
begin
Result := nil;
if Assigned(ATabSheet) and Assigned(ATabSheet.Controls[0]) and (ATabSheet.Controls[0] is TVirtualDrawTree) then
Result := TVirtualDrawTree(ATabSheet.Controls[0]);
end;
procedure TEBOutput.SetOptions;
var
i: Integer;
LVirtualDrawTree: TVirtualDrawTree;
LNode: PVirtualNode;
begin
PageControl.MultiLine := OptionsContainer.OutputMultiLine;
PageControl.ShowCloseBtns := OptionsContainer.OutputShowCloseButton;
PageControl.RightClickSelect := OptionsContainer.OutputRightClickSelect;
FTabSheetFindInFiles.TabVisible := OptionsContainer.OutputShowFindInFilesButton;
if OptionsContainer.OutputShowImage then
PageControl.Images := ImagesDataModule.ImageListSmall
else
PageControl.Images := nil;
for i := 0 to PageControl.PageCount - 2 do
begin
LVirtualDrawTree := GetOutputTreeView(PageControl.Pages[i]);
LVirtualDrawTree.Indent := OptionsContainer.OutputIndent;
if OptionsContainer.OutputUseExplorerTheme then
LVirtualDrawTree.TreeOptions.PaintOptions := LVirtualDrawTree.TreeOptions.PaintOptions + [toUseExplorerTheme]
else
LVirtualDrawTree.TreeOptions.PaintOptions := LVirtualDrawTree.TreeOptions.PaintOptions - [toUseExplorerTheme];
if OptionsContainer.OutputShowTreeLines then
LVirtualDrawTree.TreeOptions.PaintOptions := LVirtualDrawTree.TreeOptions.PaintOptions + [toShowTreeLines]
else
LVirtualDrawTree.TreeOptions.PaintOptions := LVirtualDrawTree.TreeOptions.PaintOptions - [toShowTreeLines];
{ check box }
LNode := LVirtualDrawTree.GetFirst;
while Assigned(LNode) do
begin
LVirtualDrawTree.ReinitNode(LNode, False);
LNode := LVirtualDrawTree.GetNextSibling(LNode);
end;
end;
end;
procedure TEBOutput.SetCheckedState(const AValue: TCheckState);
var
LOutputTreeView: TVirtualDrawTree;
LNode: PVirtualNode;
begin
LOutputTreeView := GetOutputTreeView(PageControl.ActivePage);
LNode := LOutputTreeView.GetFirst;
while Assigned(LNode) do
begin
LOutputTreeView.CheckState[LNode] := AValue;
LNode := LNode.NextSibling;
end;
end;
procedure TEBOutput.ReadOutputFile;
var
LFilename, S: string;
LOutputFile: TStreamReader;
LVirtualDrawTree: TVirtualDrawTree;
LFilenameToken, LText, LSearchString: string;
LLineToken, LCharacterToken: Cardinal;
LLength: Integer;
begin
FProcessingTabSheet := True;
LVirtualDrawTree := nil;
LFilename := GetOutFilename;
if FileExists(LFilename) then
begin
LOutputFile := TStreamReader.Create(LFilename, TEncoding.Unicode);
try
while not LOutputFile.EndOfStream do
begin
S := LOutputFile.ReadLine;
if Pos('s:', S) = 1 then
LVirtualDrawTree := AddTreeView(Format(LanguageDataModule.GetConstant('SearchFor'), [Copy(S, 3, Length(S))]))
else
if Assigned(LVirtualDrawTree) then
begin
LFilenameToken := GetNextToken(OUTPUT_FILE_SEPARATOR, S);
S := RemoveTokenFromStart(OUTPUT_FILE_SEPARATOR, S);
LLineToken := StrToInt(GetNextToken(OUTPUT_FILE_SEPARATOR, S));
S := RemoveTokenFromStart(OUTPUT_FILE_SEPARATOR, S);
LCharacterToken := StrToInt(GetNextToken(OUTPUT_FILE_SEPARATOR, S));
S := RemoveTokenFromStart(OUTPUT_FILE_SEPARATOR, S);
LText := GetNextToken(OUTPUT_FILE_SEPARATOR, S);
S := RemoveTokenFromStart(OUTPUT_FILE_SEPARATOR, S);
LSearchString := GetNextToken(OUTPUT_FILE_SEPARATOR, S);
S := RemoveTokenFromStart(OUTPUT_FILE_SEPARATOR, S);
LLength := StrToIntDef(S, Length(LSearchString));
AddTreeViewLine(LVirtualDrawTree, LFilenameToken, LLineToken, LCharacterToken, LText, LSearchString, LLength);
end;
end;
finally
LOutputFile.Free;
end;
end;
FProcessingTabSheet := False;
end;
procedure TEBOutput.WriteOutputFile;
var
i: Integer;
LFilename: string;
LOutputFile: TStreamWriter;
LNode: PVirtualNode;
LNodeData: POutputRec;
LVirtualDrawTree: TVirtualDrawTree;
begin
FProcessingTabSheet := True;
LFilename := GetOutFilename;
if FileExists(LFilename) then
DeleteFile(LFilename);
if OptionsContainer.OutputSaveTabs then
if PageControl.PageCount > 0 then
begin
LOutputFile := TStreamWriter.Create(LFilename, False, TEncoding.Unicode);
try
for i := 0 to PageControl.PageCount - 2 do
begin
LVirtualDrawTree := GetOutputTreeView(PageControl.Pages[i]);
if Assigned(LVirtualDrawTree) then
begin
{ tab sheet }
LNode := LVirtualDrawTree.GetFirst;
LNode := LVirtualDrawTree.GetFirstChild(LNode);
if Assigned(LNode) then
begin
LNodeData := LVirtualDrawTree.GetNodeData(LNode);
LOutputFile.Writeline(Format('s:%s', [LNodeData.SearchString]));
end;
{ data }
while Assigned(LNode) do
begin
LNodeData := LVirtualDrawTree.GetNodeData(LNode);
if LNodeData.SearchString <> '' then
LOutputFile.WriteLine(Format('%s%s%d%s%d%s%s%s%s%s%d', [LNodeData.Filename, OUTPUT_FILE_SEPARATOR, LNodeData.Line,
OUTPUT_FILE_SEPARATOR, LNodeData.Character, OUTPUT_FILE_SEPARATOR, LNodeData.Text, OUTPUT_FILE_SEPARATOR,
LNodeData.SearchString, OUTPUT_FILE_SEPARATOR, LNodeData.Length]));
LNode := LVirtualDrawTree.GetNext(LNode);
end;
end;
end;
finally
LOutputFile.Free;
end;
end;
FProcessingTabSheet := False;
end;
procedure TEBOutput.VirtualDrawTreeInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode;
var InitialStates: TVirtualNodeInitStates);
var
LData: POutputRec;
begin
with Sender do
if OptionsContainer.OutputShowCheckBox then
begin
if GetNodeLevel(Node) = 0 then
begin
LData := GetNodeData(Node);
if LData.Level <> 2 then
begin
CheckType[Node] := ctCheckBox;
CheckState[Node] := csCheckedNormal;
end;
end
end
else
CheckType[Node] := ctNone;
end;
end.
|
namespace Project2;
interface
type
ConsoleApp = class
private
public
class method Main;
method Test(aIdentifier: Integer); async;
end;
implementation
class method ConsoleApp.Main;
begin
Console.WriteLine('Asynch method example');
with lMyConsoleApp := new ConsoleApp() do begin
{ The following loop will start 5 threads that will execute asynchronously }
for i: Integer := 0 to 4 do
lMyConsoleApp.Test(i);
{ This code will be executed BEFORE all the Test methods have completed their execution }
Console.WriteLine('All 5 threads have been spawned!');
Console.ReadLine();
end;
end;
method ConsoleApp.Test(aIdentifier: integer);
begin
for i: Integer := 0 to 4 do begin
Console.WriteLine('Thread '+aIdentifier.ToString+': '+i.ToString);
System.Threading.Thread.Sleep(100);
end;
Console.WriteLine('Thread '+aIdentifier.ToString+' is done.');
end;
end. |
unit uImageLoader;
interface
uses
LiteGIFX2;
type
TImageIDs = (
G_FIRST = 0,
G_FIRSTLINE = 0,
G_FIRSTMINUS = 1,
G_FIRSTPLUS = 2,
G_LASTLINE = 3,
G_LASTMINUS = 4,
G_LASTPLUS = 5,
G_MIDDLELINE = 6,
G_MIDDLEMINUS = 7,
G_MIDDLEPLUS = 8,
G_ONEMINUS = 9,
G_ONEPLUS = 10,
G_VERTICAL = 11,
G_CHECKBOX0 = 12,
G_CHECKBOX1 = 13,
G_CHECKBOX2 = 14,
G_USER0 = 15,
G_USER1 = 16,
G_USER2 = 17,
G_USER3 = 18,
G_REFRESH = 19,
G_CHAT = 20,
G_LINE = 21,
G_IGNORED = 22,
G_POPUP_IGNORED = 23,
G_POPUP_PRIVATE_MESSAGE = 24,
G_POPUP_MASSMESSAGE = 25,
G_POPUP_PRIVATE_CHAT = 26,
G_POPUP_CREATE_LINE = 27,
G_POPUP_EXIT = 28,
G_POPUP_SEE_SHARE = 29,
G_POPUP_NICKNAME = 30,
G_POPUP_CLOSE = 31,
G_POPUP_SAVE = 32,
G_CLEAR = 33,
G_REFRESHB = 34,
G_STATUS0 = 35,
G_STATUS1 = 36,
G_STATUS2 = 37,
G_STATUS3 = 38,
G_SMILE = 39,
G_DEBUG = 40,
G_SETTINGS = 41,
G_ABOUT = 42,
G_T_MAINICON = 43,
G_T_MAINICON_1 = 44,
G_T_MAINICON_2 = 45,
G_T_MAINICON_3 = 46,
G_T_MESS_1 = 47,
G_T_MESS_2 = 48,
G_LAST = 48
);
TDreamChatImageLoader = class
private
class procedure Load();
class procedure Unload();
public
class function GetImage(id: TImageIDs): TGif;
end;
implementation
uses Classes, SysUtils, uPathBuilder,
{$IFDEF USELOG4D}, log4d {$ENDIF USELOG4D}
DreamChatConsts;
const
ImageNames: array[TImageIDs] of string = (
'firstline.gif',
'firstminus.gif',
'firstplus.gif',
'lastline.gif',
'lastminus.gif',
'lastplus.gif',
'middleline.gif',
'middleminus.gif',
'middleplus.gif',
'oneminus.gif',
'oneplus.gif',
'vertical.gif',
'checkbox0.gif',
'checkbox1.gif',
'checkbox2.gif',
'user0.gif',
'user1.gif',
'user2.gif',
'user3.gif',
'refresh.gif',
'chat.gif',
'line.gif',
'ignored.gif',
'POP_Ignored.gif',
'POP_privatemess.gif',
'POP_massmessage.gif',
'POP_privatechat.gif',
'POP_createline.gif',
'POP_exit.gif',
'POP_SeeShare.gif',
'POP_NickName.gif',
'POP_Close.gif',
'POP_Save.gif',
'clear.gif',
'refreshb.gif',
'status0.gif',
'status1.gif',
'status2.gif',
'status3.gif',
'smile.gif',
'debug.gif',
'settings.gif',
'about.gif',
't_MAINICON.gif',
't_MAINICON_1.gif',
't_MAINICON_2.gif',
't_MAINICON_3.gif',
't_mess_1.gif',
't_mess_2.gif'
);
var
FGifArray: array[TImageIDs] of TGif;
Initialised: boolean = False;
{ TDreamChatImageLoader }
class function TDreamChatImageLoader.GetImage(id: TImageIDs): TGif;
begin
Load();
Result := FGifArray[id];
end;
class procedure TDreamChatImageLoader.Load;
var
i: TImageIDs;
MS: TMemoryStream;
{$IFDEF USELOG4D}
logger: TLogLogger;
{$ENDIF USELOG4D}
begin
if Initialised then exit;
MS := TMemoryStream.Create;
try
for i:= G_FIRST to G_LAST do begin
FGifArray[i] := TGif.Create;
try
MS.LoadFromFile(TPathBuilder.GetImagesFolderName() + ImageNames[i]);
except
on E:Exception do begin
// nothing to do here, just log and ignore absence of the file
{$IFDEF USELOG4D}
logger := TLogLogger.GetLogger(DREAMCHATLOGGER_NAME);
logger.Error('[TImageLoader.Load()]' + E.Message, E);
{$ENDIF USELOG4D}
end;
end;
FGifArray[i].LoadFromStream(MS);
end;
finally
MS.Free;
end;
Initialised := True;
end;
class procedure TDreamChatImageLoader.Unload;
var
i: TImageIDs;
begin
if not Initialised then exit;
for i:= G_FIRST to G_LAST do begin
FGifArray[i].Free;
FGifArray[i] := nil;
end;
Initialised := False;
end;
initialization
TDreamChatImageLoader.load();
finalization
if Initialised
then TDreamChatImageLoader.Unload();
end.
|
namespace RemObjects.Elements.EUnit;
interface
type
ArgumentNilException = public class (ArgumentException)
public
constructor (anArgument: String);
class method RaiseIfNil(Obj: Object; Name: String);
end;
implementation
constructor ArgumentNilException(anArgument: String);
begin
inherited constructor(anArgument, "Argument '"+anArgument+"' can not be nil");
end;
class method ArgumentNilException.RaiseIfNil(Obj: Object; Name: String);
begin
if Obj = nil then
raise new ArgumentNilException(Name);
end;
end. |
unit CriticalBlockTest_U;
// Description:
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
// Enabled compiler define: FREEOTFE_DEBUG if needed
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ComCtrls,
OTFEFreeOTFE_U,
OTFEFreeOTFEBase_U, Spin64;
type
TCriticalBlockTest_F = class(TForm)
pbClose: TButton;
reReport: TRichEdit;
OpenDialog1: TOpenDialog;
GroupBox3: TGroupBox;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label9: TLabel;
edFilename: TEdit;
edUserPassword: TEdit;
pbBrowse: TButton;
pcSpecific: TPageControl;
tsWrite: TTabSheet;
tsRead: TTabSheet;
Label6: TLabel;
Label7: TLabel;
Label10: TLabel;
Label8: TLabel;
Label11: TLabel;
Label12: TLabel;
Label13: TLabel;
Label14: TLabel;
Label15: TLabel;
sePartitionLength: TSpinEdit64;
seVolumeFlags: TSpinEdit64;
edMasterKey: TEdit;
edHashDriver: TEdit;
edHashGUID: TEdit;
edCypherDriver: TEdit;
edCypherGUID: TEdit;
edRandomData: TEdit;
edSalt: TEdit;
Label4: TLabel;
Label5: TLabel;
seSaltLength: TSpinEdit64;
Label16: TLabel;
pbCreateFile: TButton;
pbWriteCriticalData: TButton;
pbReadCriticalData: TButton;
pbClear: TButton;
edDriveLetter: TEdit;
Label18: TLabel;
Label19: TLabel;
pbReadRawData: TButton;
se64Offset: TSpinEdit64;
pbWriteRawData: TButton;
seKeyIterations: TSpinEdit64;
Label20: TLabel;
edVolumeIV: TEdit;
Label21: TLabel;
procedure pbReadCriticalDataClick(Sender: TObject);
procedure pbWriteCriticalDataClick(Sender: TObject);
procedure pbCreateFileClick(Sender: TObject);
procedure pbBrowseClick(Sender: TObject);
procedure pbClearClick(Sender: TObject);
procedure pbCloseClick(Sender: TObject);
procedure pbReadRawDataClick(Sender: TObject);
procedure pbWriteRawDataClick(Sender: TObject);
private
{ Private declarations }
public
OTFEFreeOTFE1: TOTFEFreeOTFEBase;
end;
implementation
{$R *.DFM}
uses
ComObj, // Required for StringToGUID
SDUGeneral,
OTFEFreeOTFE_VolumeFileAPI,
DriverAPI;
procedure TCriticalBlockTest_F.pbReadCriticalDataClick(Sender: TObject);
var
dumpStrings: TStringList;
dumpFilename: string;
begin
dumpFilename := 'C:\VolumeCDBDump.txt';
if MessageDlg(
'!!! WARNING !!!'+SDUCRLF+
SDUCRLF+
'Due to the way in which this test is implemented, a PLAINTEXT '+SDUCRLF+
'version of your CDB''s contents dumped to a temporary file '+SDUCRLF+
'before being read back in and the temporary file deleted.'+SDUCRLF+
SDUCRLF+
'Do you wish to proceed?',
mtConfirmation, [mbYes, mbNo], 0) = mrYes then
begin
if OTFEFreeOTFE1.DumpCriticalDataToFile(
edFilename.text,
se64Offset.Value,
edUserPassword.text,
seSaltLength.value,
seKeyIterations.value,
dumpFilename
) then
begin
dumpStrings := TStringList.Create();
try
dumpStrings.LoadFromFile(dumpFilename);
reReport.lines.AddStrings(dumpStrings);
finally
dumpStrings.Free();
end;
DeleteFile(dumpFilename);
end
else
begin
reReport.lines.add('Dump FAILED (Dump attempted to '+dumpFilename+')');
end;
end;
end;
procedure TCriticalBlockTest_F.pbWriteCriticalDataClick(
Sender: TObject);
var
volumeDetails: TVolumeDetailsBlock;
CDBMetaData: TCDBMetaData;
begin
// These are ignored; populated automatically on writing
CDBMetaData.MACAlgorithm:= fomacUnknown;
CDBMetaData.KDFAlgorithm:= fokdfUnknown;
CDBMetaData.HashDriver := edHashDriver.text;
CDBMetaData.HashGUID := StringToGUID(edHashGUID.text);
CDBMetaData.CypherDriver := edCypherDriver.text;
CDBMetaData.CypherGUID := StringToGUID(edCypherGUID.text);
// This is ignored; populated automatically on writing
volumeDetails.CDBFormatID:= 0;
volumeDetails.PartitionLen:= sePartitionLength.value;
volumeDetails.VolumeFlags:= seVolumeFlags.value;
volumeDetails.MasterKeyLength:= (Length(edMasterKey.Text)*8);
volumeDetails.MasterKey:= edMasterKey.Text;
volumeDetails.VolumeIVLength:= (Length(edVolumeIV.Text)*8);
volumeDetails.VolumeIV:= edVolumeIV.Text;
volumeDetails.RequestedDriveLetter := #0;
if (edDriveLetter.text <> '') then
begin
volumeDetails.RequestedDriveLetter := edDriveLetter.text[1];
end;
if OTFEFreeOTFE1.WriteVolumeCriticalData(
edFilename.text,
se64Offset.Value,
edUserPassword.text,
edSalt.Text,
seKeyIterations.Value,
volumeDetails,
CDBMetaData,
edRandomData.Text
) then
begin
showmessage('Written OK');
end
else
begin
showmessage('Write FAILED.');
end;
end;
procedure TCriticalBlockTest_F.pbCreateFileClick(Sender: TObject);
var
userCancel: boolean;
begin
if SDUCreateLargeFile(edFilename.text, sePartitionLength.value + (CRITICAL_DATA_LENGTH div 8), FALSE, userCancel) then
begin
showmessage('File created OK');
end
else
begin
showmessage('File create FAILED.');
end;
end;
procedure TCriticalBlockTest_F.pbBrowseClick(Sender: TObject);
begin
OpenDialog1.Filename := edFilename.text;
if OpenDialog1.execute() then
begin
edFilename.text := OpenDialog1.FileName;
end;
end;
procedure TCriticalBlockTest_F.pbClearClick(Sender: TObject);
begin
reReport.Lines.Clear();
end;
procedure TCriticalBlockTest_F.pbCloseClick(Sender: TObject);
begin
Close();
end;
procedure TCriticalBlockTest_F.pbReadRawDataClick(Sender: TObject);
{$IFDEF FREEOTFE_DEBUG}
var
prettyData: TStringList;
data: string;
{$ENDIF}
begin
{$IFDEF FREEOTFE_DEBUG}
reReport.Lines.Add('Reading raw data from: '+edFilename.text+' (offset: '+inttostr(se64Offset.Value)+')');
if OTFEFreeOTFE1.DEBUGReadRawVolumeCriticalData(edFilename.text, se64Offset.Value, data) then
begin
reReport.Lines.Add('Raw data read:');
prettyData:= TStringList.Create();
try
SDUPrettyPrintHex(data, 0, length(data), prettyData);
reReport.Lines.AddStrings(prettyData);
finally
prettyData.Free();
end;
end
else
begin
reReport.Lines.Add('FAILED to read data.');
end;
{$ELSE}
showmessage('FREEOTFE_DEBUG compiler flag must be set to test this function');
{$ENDIF}
end;
procedure TCriticalBlockTest_F.pbWriteRawDataClick(
Sender: TObject);
{$IFDEF FREEOTFE_DEBUG}
var
data: string;
i: integer;
{$ENDIF}
begin
{$IFDEF FREEOTFE_DEBUG}
if (MessageDlg(
'!!! DANGER !!!'+CRLF+
CRLF+
'This will write test data to:'+CRLF+
CRLF+
edFilename.Text+CRLF+
CRLF+
'If you specified a partition or drive, test data will be written to '+CRLF+
'that area.'+CRLF+
CRLF+
'DO YOU WANT TO PROCEED?',
mtWarning, [mbYes,mbNo], 0) = mrYes) then
begin
reReport.Lines.Add('Writing raw data : '+edFilename.text+' (offset: '+inttostr(se64Offset.Value)+')');
for i:=0 to ((CRITICAL_DATA_LENGTH div 8)-1) do
begin
data := data + chr(ord('a') + (i mod 26));
end;
if OTFEFreeOTFE1.DEBUGWriteRawVolumeCriticalData(edFilename.text, se64Offset.Value, data) then
begin
reReport.Lines.Add('Raw data written OK');
end
else
begin
reReport.Lines.Add('FAILED to write data.');
end;
end;
{$ELSE}
showmessage('FREEOTFE_DEBUG compiler flag must be set to test this function');
{$ENDIF}
end;
END.
|
unit SDFilesystem_Local;
// To use:
// Filesystem := TSDFilesystem_Local.Create();
// TSDFilesystem_Local(Filesystem).DriveLetter := 'C';
// Filesystem.Mounted := TRUE;
interface
uses
Windows,
SDUGeneral,
SDUSysUtils,
SDFilesystem;
type
TSDFilesystem_Local = class(TSDCustomFilesystem)
private
FDriveLetter: char;
protected
function DoMount(): boolean; override;
procedure DoDismount(); override;
function GetCaseSensitive(): boolean; override;
function GetFreeSpace(): ULONGLONG; override;
function GetSize(): ULONGLONG; override;
public
constructor Create(); override;
destructor Destroy(); override;
function FilesystemTitle(): string; override;
function Format(): boolean; override;
function LoadContentsFromDisk(path: string; items: TSDDirItemList): boolean; override;
function ExtractFile(srcPath: WideString; extractToFilename: string): boolean; override;
function GetItem(path: WideString; item: TSDDirItem): boolean; override;
published
property DriveLetter: char read FDriveLetter write FDriveLetter default #0;
end;
implementation
uses
SysUtils,
SDUFileIterator_U;
constructor TSDFilesystem_Local.Create();
begin
inherited;
end;
destructor TSDFilesystem_Local.Destroy();
begin
inherited;
end;
function TSDFilesystem_Local.GetCaseSensitive(): boolean;
begin
Result := FALSE;
end;
function TSDFilesystem_Local.FilesystemTitle(): string;
begin
Result := 'Local filesystem';
end;
function TSDFilesystem_Local.DoMount(): boolean;
begin
Assert(
(DriveLetter <> #0),
'Drive letter of drive to mount not specified'
);
Result := TRUE;
end;
procedure TSDFilesystem_Local.DoDismount();
begin
inherited;
end;
function TSDFilesystem_Local.LoadContentsFromDisk(path: string; items: TSDDirItemList): boolean;
procedure AddItem(filename: string);
var
currItem: TSDDirItem;
fullFilename: WideString;
begin
currItem := TSDDirItem.Create();
fullFilename := IncludeTrailingPathDelimiter(DriveLetter+':'+path)+filename;
GetItem(fullFilename, currItem);
items.Add(currItem);
end;
var
dc: TSDUFileIterator;
currName: string;
begin
AssertMounted();
dc := TSDUFileIterator.Create(nil);
try
dc.Directory := IncludeTrailingPathDelimiter(DriveLetter+':'+path);
dc.OmitStartDirPrefix := TRUE;
dc.IncludeDirNames := TRUE;
items.clear();
dc.Reset();
currName := dc.Next();
while (currName <> '') do
begin
AddItem(currName);
currName := dc.Next();
end;
// Add in current and parent dirs
AddItem(DIR_CURRENT_DIR);
AddItem(DIR_PARENT_DIR);
finally
dc.Free();
end;
Result := TRUE;
end;
function TSDFilesystem_Local.ExtractFile(srcPath: WideString; extractToFilename: string): boolean;
var
tmpFullSrc: string;
begin
// Result := SDUCopyFile(DriveLetter+':'+srcPath, extractToFilename);
tmpFullSrc := DriveLetter+':'+srcPath;
Result := CopyFile(PChar(tmpFullSrc), PChar(extractToFilename), FALSE);
end;
function TSDFilesystem_Local.GetFreeSpace(): ULONGLONG;
begin
Result := DiskFree(Ord(DriveLetter) - 64);
end;
function TSDFilesystem_Local.GetSize(): ULONGLONG;
begin
Result := DiskSize(Ord(DriveLetter) - 64);
end;
function TSDFilesystem_Local.Format(): boolean;
begin
Result := FALSE;
end;
function TSDFilesystem_Local.GetItem(path: WideString; item: TSDDirItem): boolean;
var
retval: boolean;
tmpDateTime: TDateTime;
tmpTimeStamp: TTimeStamp;
// attr: integer;
attr: DWORD;
pathAsString: string;
begin
retval := FALSE;
if (
SysUtils.FileExists(path) or
SysUtils.DirectoryExists(path)
) then
begin
retval := TRUE;
item.Filename := ExtractFilename(path);
item.IsFile := SysUtils.FileExists(path);
item.IsDirectory := SysUtils.DirectoryExists(path);
item.Size := 0;
if item.IsFile then
begin
item.Size := SDUGetFileSize(path);
if SDUFileAge(path, tmpDateTime) then
begin
item.TimestampLastModified := DateTimeToTimeStamp(tmpDateTime);
end
else
begin
tmpTimeStamp.Time := 0;
tmpTimeStamp.Date := 0;
item.TimestampLastModified := tmpTimeStamp;
end;
// This directive is ineffective; so we use the below, which isn't as obvious
// what it's doing, but reduces the number of compiler warnings
// {$WARN UNIT_PLATFORM OFF}
// attr := FileGetAttr(path);
// item.IsReadOnly := ((attr and faReadonly) = faReadonly);
// item.IsHidden := ((attr and faHidden) = faHidden);
//{$WARN UNIT_PLATFORM ON}
pathAsString := path;
attr := GetFileAttributes(PChar(pathAsString));
// item.IsReadOnly := FileIsReadOnly(path);
item.IsReadOnly := ((attr and FILE_ATTRIBUTE_READONLY) <> 0);
item.IsHidden := ((attr and FILE_ATTRIBUTE_HIDDEN) <> 0);
end;
end;
Result := retval;
end;
END.
|
unit UnitQuickGroupInfo;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Classes,
System.Math,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.ImgList,
Vcl.Menus,
Vcl.StdCtrls,
Vcl.ExtCtrls,
Vcl.ComCtrls,
Vcl.AppEvnts,
Vcl.PlatformDefaultStyleActnCtrls,
Vcl.ActnPopup,
Vcl.Imaging.jpeg,
Dmitry.Controls.WebLinkList,
Dmitry.Controls.WebLink,
uMemory,
uConstants,
uBitmapUtils,
uDBForm,
uDBContext,
uDBEntities,
uDBManager,
uShellIntegration,
uThemesUtils,
uVCLHelpers,
uFormInterfaces;
type
TFormQuickGroupInfo = class(TDBForm, IGroupInfoForm)
GroupImage: TImage;
GroupNameEdit: TEdit;
CommentMemo: TMemo;
BtnOk: TButton;
DateEdit: TEdit;
AccessEdit: TEdit;
PmGroupOptions: TPopupActionBar;
EditGroup1: TMenuItem;
CommentLabel: TLabel;
DateLabel: TLabel;
AccessLabel: TLabel;
SearchForGroup1: TMenuItem;
KeyWordsMemo: TMemo;
CbAddKeywords: TCheckBox;
KeyWordsLabel: TLabel;
Label3: TLabel;
CbInclude: TCheckBox;
GroupsImageList: TImageList;
WllGroups: TWebLinkList;
AeMain: TApplicationEvents;
BtnEdit: TButton;
procedure BtnOkClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure EditGroup1Click(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure SearchForGroup1Click(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure AeMainMessage(var Msg: tagMSG; var Handled: Boolean);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure GroupImageClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
FContext: IDBContext;
FGroupsRepository: IGroupsRepository;
FGroup: TGroup;
FCloseOwner: Boolean;
FOwner: TForm;
FNewRelatedGroups: string;
procedure GroupClick(Sender: TObject);
procedure FillImageList;
procedure LoadLanguage;
procedure ReloadGroups;
protected
function GetFormID: string; override;
procedure InterfaceDestroyed; override;
public
{ Public declarations }
procedure Execute(AOwner: TForm; Group: TGroup; CloseOwner: Boolean); overload;
procedure Execute(AOwner: TForm; GroupName: string; CloseOwner: Boolean); overload;
end;
implementation
{$R *.dfm}
uses
UnitFormChangeGroup,
uManagerExplorer;
procedure TFormQuickGroupInfo.Execute(AOwner: TForm; GroupName: string;
CloseOwner: Boolean);
var
Group: TGroup;
begin
Group := FGroupsRepository.GetByName(GroupName, False);
try
Execute(AOwner, Group, CloseOwner);
finally
F(Group);
end;
end;
procedure TFormQuickGroupInfo.Execute(AOwner: TForm; Group: TGroup; CloseOwner: Boolean);
const
Otstup = 3;
Otstupa = 2;
var
FineDate: array [0 .. 255] of Char;
TempSysTime: TSystemTime;
begin
FCloseOwner := CloseOwner;
FOwner := AOwner;
FGroup := FGroupsRepository.GetByCode(Group.GroupCode, True);
try
if FGroup = nil then
begin
MessageBoxDB(Handle, L('Group not found!'), L('Warning'), TD_BUTTON_OK, TD_ICON_WARNING);
Close;
Exit;
end;
GroupNameEdit.Text := FGroup.GroupName;
FNewRelatedGroups := FGroup.RelatedGroups;
CbInclude.Checked := FGroup.IncludeInQuickList;
if FGroup.GroupImage <> nil then
GroupImage.Picture.Graphic := FGroup.GroupImage;
CommentLabel.Top := Max(GroupImage.Top + GroupImage.Height, GroupNameEdit.Top + GroupNameEdit.Height) + 3;
CommentMemo.Top := CommentLabel.Top + CommentLabel.Height + 3;
CommentMemo.Text := FGroup.GroupComment;
CommentMemo.Height := (CommentMemo.Lines.Count + 1) * (Abs(CommentMemo.Font.Height) + 2) + Otstup;
KeyWordsLabel.Top := CommentMemo.Top + CommentMemo.Height + Otstup;
KeyWordsMemo.Top := KeyWordsLabel.Top + KeyWordsLabel.Height + Otstup;
KeyWordsMemo.Text := FGroup.GroupKeyWords;
CbAddKeywords.Top := KeyWordsMemo.Top + KeyWordsMemo.Height + Otstup;
CbAddKeywords.Checked := FGroup.AutoAddKeyWords;
Label3.Top := CbAddKeywords.Top + CbAddKeywords.Height + Otstup;
WllGroups.Top := Label3.Top + Label3.Height + Otstup;
CbInclude.Top := WllGroups.Top + WllGroups.Height + Otstup;
DateLabel.Top := CbInclude.Top + CbInclude.Height + Otstup;
DateEdit.Top := DateLabel.Top + DateLabel.Height + Otstupa;
AccessLabel.Top := DateEdit.Top + DateEdit.Height + Otstupa;
AccessEdit.Top := AccessLabel.Top + AccessLabel.Height + Otstup;
BtnOk.Top := AccessEdit.Top + AccessEdit.Height + Otstup;
BtnEdit.Top := AccessEdit.Top + AccessEdit.Height + Otstup;
ClientHeight := BtnOk.Top + BtnOk.Height + Otstup;
DateTimeToSystemTime(FGroup.GroupDate, TempSysTime);
GetDateFormat(LOCALE_USER_DEFAULT, DATE_USE_ALT_CALENDAR, @TempSysTime, 'd MMMM yyyy ', @FineDate, 255);
DateEdit.Text := Format(L('Created %s'), [FineDate]);
if FGroup.GroupAccess = GROUP_ACCESS_COMMON then
AccessEdit.Text := L('Public group');
if FGroup.GroupAccess = GROUP_ACCESS_PRIVATE then
AccessEdit.Text := L('Private group');
ReloadGroups;
FixFormPosition;
ShowModal;
finally
F(FGroup);
end;
end;
procedure TFormQuickGroupInfo.AeMainMessage(var Msg: tagMSG;
var Handled: Boolean);
begin
if (Msg.message = WM_MOUSEWHEEL) then
WllGroups.PerformMouseWheel(Msg.wParam, Handled);
end;
procedure TFormQuickGroupInfo.BtnOkClick(Sender: TObject);
begin
Close;
end;
procedure TFormQuickGroupInfo.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caHide;
end;
procedure TFormQuickGroupInfo.FormCreate(Sender: TObject);
begin
FContext := DBManager.DBContext;
FGroupsRepository := FContext.Groups;
Loadlanguage;
BtnEdit.AdjustButtonWidth;
end;
procedure TFormQuickGroupInfo.FormDestroy(Sender: TObject);
begin
FGroupsRepository := nil;
FContext := nil;
end;
procedure TFormQuickGroupInfo.EditGroup1Click(Sender: TObject);
begin
Hide;
Application.ProcessMessages;
DBChangeGroup(FGroup);
Close;
end;
procedure TFormQuickGroupInfo.FormShow(Sender: TObject);
begin
BtnOk.SetFocus;
end;
function TFormQuickGroupInfo.GetFormID: string;
begin
Result := 'GroupInfo';
end;
procedure TFormQuickGroupInfo.GroupClick(Sender: TObject);
begin
GroupInfoForm.Execute(nil, TWebLink(Sender).Text, False);
end;
procedure TFormQuickGroupInfo.GroupImageClick(Sender: TObject);
var
P: TPoint;
begin
P := GroupImage.ClientToScreen(GroupImage.ClientRect.CenterPoint);
PmGroupOptions.Popup(P.X, P.Y);
end;
procedure TFormQuickGroupInfo.InterfaceDestroyed;
begin
inherited;
Release;
end;
procedure TFormQuickGroupInfo.LoadLanguage;
begin
BeginTranslate;
try
Caption:= L('Group info');
DateLabel.Caption := L('Date created');
AccessLabel.Caption := L('Attributes');
BtnOk.Caption := L('Ok');
EditGroup1.Caption := L('Edit group');
SearchForGroup1.Caption := L('Search for group photos');
CbAddKeywords.Caption := L('Auto add keywords');
KeyWordsLabel.Caption := L('Keywords for group') + ':';
CommentLabel.Caption := L('Comment for group') + ':';
CbInclude.Caption := L('Include in quick access list');
Label3.Caption := L('Related groups') + ':';
BtnEdit.Caption := L('Edit group');
finally
EndTranslate;
end;
end;
procedure TFormQuickGroupInfo.SearchForGroup1Click(Sender: TObject);
begin
with ExplorerManager.NewExplorer(False) do
begin
SetPath(cGroupsPath + '\' + FGroup.GroupName);
Show;
end;
BtnOk.OnClick(Sender);
Close;
if FCloseOwner then
FOwner.Close;
end;
procedure TFormQuickGroupInfo.ReloadGroups;
var
I: Integer;
FCurrentGroups: TGroups;
WL: TWebLink;
LblInfo: TStaticText;
begin
FillImageList;
FCurrentGroups := TGroups.CreateFromString(FNewRelatedGroups);
try
for I := 0 to FCurrentGroups.Count - 1 do
begin
WL := WllGroups.AddLink;
WL.Text := FCurrentGroups[I].GroupName;
WL.ImageList := GroupsImageList;
WL.ImageIndex := I;
WL.Tag := I;
WL.OnClick := GroupClick;
end;
if FCurrentGroups.Count = 0 then
begin
LblInfo := TStaticText.Create(WllGroups);
LblInfo.Parent := WllGroups;
WllGroups.AddControl(LblInfo);
LblInfo.Caption := L('There are no related groups');
end;
finally
F(FCurrentGroups);
end;
WllGroups.ReallignList;
end;
procedure TFormQuickGroupInfo.FillImageList;
var
I: Integer;
Group: TGroup;
SmallB: TBitmap;
FCurrentGroups: TGroups;
begin
GroupsImageList.Clear;
FCurrentGroups := TGroups.CreateFromString(FNewRelatedGroups);
try
for I := 0 to FCurrentGroups.Count - 1 do
begin
SmallB := TBitmap.Create;
try
SmallB.PixelFormat := pf24bit;
SmallB.Canvas.Brush.Color := Theme.PanelColor;
SmallB.SetSize(16, 16);
Group := FGroupsRepository.GetByName(FCurrentGroups[I].GroupName, True);
try
if (Group <> nil) and (Group.GroupImage <> nil) and not Group.GroupImage.Empty then
begin
SmallB.Assign(Group.GroupImage);
CenterBitmap24To32ImageList(SmallB, 16);
end;
finally
F(Group);
end;
GroupsImageList.Add(SmallB, nil);
finally
F(SmallB);
end;
end;
finally
F(FCurrentGroups);
end;
end;
procedure TFormQuickGroupInfo.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if Key = VK_ESCAPE then
Close;
end;
initialization
FormInterfaces.RegisterFormInterface(IGroupInfoForm, TFormQuickGroupInfo);
end.
|
{
Solução do desafio 5 em Pascal por Elias Correa (Jan/2019)
Download freepascal compiler (fpc) here https://www.freepascal.org/ or thru your distro package manager
Compile with:
fpc desafio5.pas -O4
}
program Desafio5;
{$MODE OBJFPC}
uses
{$ifdef unix}
cthreads,
cmem, // the c memory manager is on some systems much faster for multi-threading
{$endif}
SysUtils, Classes, Contnrs;
const
BufferLength = 1024 * 1024 * 8; //amount of data each thread will work out from file (in Bytes)
type
TArea = record
FName: ShortString;
FTotalEmployees: LongInt;
FTotalSalary: Int64;
FMinSalary, FMaxSalary: Int64;
FMinNames, FMaxNames: TStringList;
end;
PArea = ^TArea;
TSurname = record
FTotalEmployees: LongInt;
FMaxSalary: Int64;
FMaxNames: TStringList;
end;
PSurname = ^TSurname;
TThreadData = record
FBuffer: array[0 .. BufferLength - 1] of Char;
FTotalEmployees: LongInt;
FTotalSalary: Int64;
FMinSalary, FMaxSalary: Int64;
FMinNames, FMaxNames: TStringList;
FAreas, FSurnames: TFPHashList;
end;
PThreadData = ^TThreadData;
function ConcatNames(AName, ASurname: PShortString): ShortString; Inline;
begin
if (AName <> nil) and (ASurname <> nil) then
begin
SetLength(Result, Length(AName^) + Length(ASurname^) + 1);
Move(AName^[1], Result[1], Length(AName^));
Result[Length(AName^) + 1] := ' ';
Move(ASurname^[1], Result[Length(AName^) + 2], Length(ASurname^));
end
else
begin
Result := AName^;
end;
end;
procedure AppendNameList(var ANameList: TStringList; var AListSalary: Int64; AName, ASurname: PShortString; ASalary: Int64; AKeepMinSalary: Boolean); inline;
begin
if ANameList = nil then ANameList := TStringList.Create;
if AListSalary = ASalary then
begin
ANameList.Append(ConcatNames(AName, ASurname));
end
else if (AListSalary = 0) or
(AKeepMinSalary and (ASalary < AListSalary)) or
((not AKeepMinSalary) and (ASalary > AListSalary)) then
begin
AListSalary := ASalary;
ANameList.Clear;
ANameList.Append(ConcatNames(AName, ASurname));
end;
end;
procedure JoinNameList(const ASourceList: TStringList; var ADestList: TStringList; ASourceSalary: Int64; var ADestSalary: Int64; AKeepMinSalary: Boolean); inline;
begin
if ASourceList = nil then exit;
if ADestList = nil then ADestList := TStringList.Create;
if ASourceSalary = ADestSalary then
begin
ADestList.AddStrings(ASourceList);
end
else if (ADestSalary = 0) or
(AKeepMinSalary and (ASourceSalary < ADestSalary)) or
((not AKeepMinSalary) and (ASourceSalary > ADestSalary)) then
begin
ADestSalary := ASourceSalary;
ADestList.Clear;
ADestList.AddStrings(ASourceList);
end;
end;
function GetItem(var AList: TFPHashList; const AName: ShortString; ASize: SizeInt): Pointer; inline;
var
Item: Pointer;
begin
Item := AList.Find(AName);
if Item = nil then
begin
Item := GetMem(ASize);
FillChar(Item^, ASize, 0);
AList.Add(AName, Item);
end;
Result := Item;
end;
procedure LoadJsonChunk(var JsonFile: TFileStream; ABuffer: PChar);
var
Len: SizeInt;
begin
Len := JsonFile.Read(ABuffer^, BufferLength - 1);
//rewind file until a '}' is found, reading only complete objects
if JsonFile.Position <> JsonFile.Size then
begin
while ABuffer[Len - 1] <> '}' do
begin
Dec(Len);
JsonFile.Position := JsonFile.Position - 1;
end;
end;
//null terminated
ABuffer[Len] := #0;
end;
function GetString(var ABuffer: PChar): PShortString; inline;
var
Start: PChar = nil;
C: PChar;
begin
C := ABuffer;
while (C^ <> #0) and (C^ <> '"') do Inc(C);
if C^ = '"' then
begin
Start := C;
Inc(C); //skip '"'
end;
while (C^ <> #0) and (C^ <> '"') do Inc(C);
if C^ = '"' then
begin
if Start <> nil then
Start[0] := Char(C - Start - 1); //store length in the 0 index (short pascal strings)
Inc(C); //skip '"'
end;
Result := PShortString(Start);
ABuffer := C;
end;
function GetNumber(var ABuffer: PChar): Int64; inline;
var
C: PChar;
begin
Result := 0;
C := ABuffer;
while (C^ <> #0) and (not (C^ in ['0'..'9', '.'])) do Inc(C);
while C^ in ['0'..'9', '.'] do
begin
if C^ <> '.' then
Result := Result * 10 + (LongInt(C^) - LongInt('0'));
Inc(C);
end;
ABuffer := C;
end;
procedure ParseJsonChunk(ABuffer: PChar; var AData: TThreadData);
var
C: PChar;
Name, Surname, Code: PShortString;
Salary: Int64;
begin
C := ABuffer;
while C^ <> #0 do
begin
//find a property
while (C^ <> #0) and (C^ <> '"') do Inc(C);
if C^ = '"' then Inc(C); //skip '"'
//employee (starts with i of id)
if C^ = 'i' then
begin
//ignore id
while (C^ <> #0) and (C^ <> ',') do Inc(C);
//get name
while (C^ <> #0) and (C^ <> ':') do Inc(C);
Name := GetString(C);
//get surname
while (C^ <> #0) and (C^ <> ':') do Inc(C);
Surname := GetString(C);
//get salary
while (C^ <> #0) and (C^ <> ':') do Inc(C);
Salary := GetNumber(C);
//get area
while (C^ <> #0) and (C^ <> ':') do Inc(C);
Code := GetString(C);
//update global counters
Inc(AData.FTotalEmployees);
AData.FTotalSalary += Salary;
AppendNameList(AData.FMinNames, AData.FMinSalary, Name, Surname, Salary, True);
AppendNameList(AData.FMaxNames, AData.FMaxSalary, Name, Surname, Salary, False);
//update areas
with PArea(GetItem(AData.FAreas, Code^, SizeOf(TArea)))^ do
begin
Inc(FTotalEmployees);
FTotalSalary += Salary;
AppendNameList(FMinNames, FMinSalary, Name, Surname, Salary, True);
AppendNameList(FMaxNames, FMaxSalary, Name, Surname, Salary, False);
end;
//update surnames
with PSurname(GetItem(AData.FSurnames, Surname^, SizeOf(TSurname)))^ do
begin
Inc(FTotalEmployees);
AppendNameList(FMaxNames, FMaxSalary, Name, nil, Salary, False);
end;
end
//area (starts with c of code)
else if C^ = 'c' then //area
begin
//get code
while (C^ <> #0) and (C^ <> ':') do Inc(C);
Code := GetString(C);
//get name
while (C^ <> #0) and (C^ <> ':') do Inc(C);
Name := GetString(C);
//set area name
PArea(GetItem(AData.FAreas, Code^, SizeOf(TArea)))^.FName := Name^;
end;
end;
end;
var
CriticalSection: TRTLCriticalSection;
EmployeeFile: TFileStream;
procedure ThreadProc(AData: Pointer);
begin
TThread.CurrentThread.FreeOnTerminate := False;
while not TThread.CurrentThread.CheckTerminated do
begin
EnterCriticalSection(CriticalSection);
if EmployeeFile.Position = EmployeeFile.Size then
TThread.CurrentThread.Terminate;
LoadJsonChunk(EmployeeFile, @(PThreadData(AData)^.FBuffer[0]));
LeaveCriticalSection(CriticalSection);
ParseJsonChunk(@(PThreadData(AData)^.FBuffer[0]), PThreadData(AData)^);
end;
end;
var
Threads: array of TThread;
Data: array of TThreadData;
I, J: LongInt;
MostEmployees: LongInt = 0;
LeastEmployees: LongInt = High(LongInt);
AreaInfo: PArea;
SurnameInfo: PSurname;
begin
//check command line params
if ParamCount <> 1 then
begin
WriteLn('Usage: ', ParamStr(0), ' <input file>');
Halt(1);
end;
FormatSettings.DecimalSeparator := '.';
SetLength(Threads, TThread.ProcessorCount);
SetLength(Data, TThread.ProcessorCount);
//init thread data
for I := 0 to High(Data) do
begin
with Data[I] do
begin
FMinNames := TStringList.Create;
FMaxNames := TStringList.Create;
FAreas := TFPHashList.Create;
FSurnames := TFPHashList.Create;
end;
end;
InitCriticalSection(CriticalSection);
EmployeeFile := TFileStream.Create(ParamStr(1), fmOpenRead or fmShareDenyWrite);
for I := 0 to High(Threads) do
begin
Threads[I] := TThread.ExecuteInThread(@ThreadProc, @Data[I]);
Threads[I].Priority := tpTimeCritical;
end;
for I := 0 to High(Threads) do
begin
Threads[I].WaitFor;
Threads[I].Free;
end;
EmployeeFile.Free;
DoneCriticalSection(CriticalSection);
//join results
with Data[0] do
begin
for I := 1 to High(Data) do
begin
//global
FTotalEmployees += Data[I].FTotalEmployees;
FTotalSalary += Data[I].FTotalSalary;
JoinNameList(Data[I].FMinNames, FMinNames, Data[I].FMinSalary, FMinSalary, True);
JoinNameList(Data[I].FMaxNames, FMaxNames, Data[I].FMaxSalary, FMaxSalary, False);
//areas
for J := 0 to Data[I].FAreas.Count - 1 do
begin
AreaInfo := Data[I].FAreas.Items[J];
with PArea(GetItem(FAreas, Data[I].FAreas.NameOfIndex(J), SizeOf(TArea)))^ do
begin
if Length(AreaInfo^.FName) <> 0 then FName := AreaInfo^.FName;
FTotalEmployees += AreaInfo^.FTotalEmployees;
FTotalSalary += AreaInfo^.FTotalSalary;
JoinNameList(AreaInfo^.FMinNames, FMinNames, AreaInfo^.FMinSalary, FMinSalary, True);
JoinNameList(AreaInfo^.FMaxNames, FMaxNames, AreaInfo^.FMaxSalary, FMaxSalary, False);
end;
end;
//surnames
for J := 0 to Data[I].FSurnames.Count - 1 do
begin
SurnameInfo := Data[I].FSurnames.Items[J];
with PSurname(GetItem(FSurnames, Data[I].FSurnames.NameOfIndex(J), SizeOf(TSurname)))^ do
begin
FTotalEmployees += SurnameInfo^.FTotalEmployees;
JoinNameList(SurnameInfo^.FMaxNames, FMaxNames, SurnameInfo^.FMaxSalary, FMaxSalary, False);
end;
end;
end;
end;
//print results
//global
with Data[0] do
begin
for I := 0 to FMinNames.Count - 1 do
WriteLn('global_min|', FMinNames[I], '|', (FMinSalary * 0.01):0:2);
for I := 0 to FMaxNames.Count - 1 do
WriteLn('global_max|', FMaxNames[I], '|', (FMaxSalary * 0.01):0:2);
WriteLn('global_avg|', ((FTotalSalary * 0.01) / FTotalEmployees):0:2);
end;
//areas
for I := 0 to Data[0].FAreas.Count - 1 do
begin
with PArea(Data[0].FAreas.Items[I])^ do
begin
if FTotalEmployees > 0 then
begin
WriteLn('area_avg|', FName, '|', ((FTotalSalary * 0.01) / FTotalEmployees):0:2);
for J := 0 to FMinNames.Count - 1 do
WriteLn('area_min|', FName, '|', FMinNames[J], '|', (FMinSalary * 0.01):0:2);
for J := 0 to FMaxNames.Count - 1 do
WriteLn('area_max|', FName, '|', FMaxNames[J], '|', (FMaxSalary * 0.01):0:2);
if FTotalEmployees > MostEmployees then
MostEmployees := FTotalEmployees;
if (FTotalEmployees > 0) and (FTotalEmployees < LeastEmployees) then
LeastEmployees := FTotalEmployees;
end;
end;
end;
for I := 0 to Data[0].FAreas.Count - 1 do
begin
with PArea(Data[0].FAreas.Items[I])^ do
begin
if FTotalEmployees = MostEmployees then
WriteLn('most_employees|', FName, '|', FTotalEmployees);
if FTotalEmployees = LeastEmployees then
WriteLn('least_employees|', FName, '|', FTotalEmployees);
end;
end;
//surnames
for I := 0 to Data[0].FSurnames.Count - 1 do
begin
with PSurname(Data[0].FSurnames.Items[I])^ do
if FTotalEmployees > 1 then
for J := 0 to FMaxNames.Count - 1 do
WriteLn('last_name_max|', Data[0].FSurnames.NameOfIndex(I), '|', FMaxNames[J], ' ', Data[0].FSurnames.NameOfIndex(I), '|', (Double(FMaxSalary) * Double(0.01)):0:2);
end;
end. |
unit MyCat.Config;
interface
type
TCapabilities = class
public const
// new more secure passwords
CLIENT_LONG_PASSWORD = 1;
// Found instead of affected rows
// 返回找到(匹配)的行数,而不是改变了的行数。
CLIENT_FOUND_ROWS = 2;
// Get all column flags
CLIENT_LONG_FLAG = 4;
// One can specify db on connect
CLIENT_CONNECT_WITH_DB = 8;
// Don't allow database.table.column
// 不允许“数据库名.表名.列名”这样的语法。这是对于ODBC的设置。
// 当使用这样的语法时解析器会产生一个错误,这对于一些ODBC的程序限制bug来说是有用的。
CLIENT_NO_SCHEMA = 16;
// Can use compression protocol
// 使用压缩协议
CLIENT_COMPRESS = 32;
// Odbc client
CLIENT_ODBC = 64;
// Can use LOAD DATA LOCAL
CLIENT_LOCAL_FILES = 128;
// Ignore spaces before '('
// 允许在函数名后使用空格。所有函数名可以预留字。
CLIENT_IGNORE_SPACE = 256;
// New 4.1 protocol This is an interactive client
CLIENT_PROTOCOL_41 = 512;
// This is an interactive client
// 允许使用关闭连接之前的不活动交互超时的描述,而不是等待超时秒数。
// 客户端的会话等待超时变量变为交互超时变量。
CLIENT_INTERACTIVE = 1024;
// Switch to SSL after handshake
// 使用SSL。这个设置不应该被应用程序设置,他应该是在客户端库内部是设置的。
// 可以在调用mysql_real_connect()之前调用mysql_ssl_set()来代替设置。
CLIENT_SSL = 2048;
// IGNORE sigpipes
// 阻止客户端库安装一个SIGPIPE信号处理器。
// 这个可以用于当应用程序已经安装该处理器的时候避免与其发生冲突。
CLIENT_IGNORE_SIGPIPE = 4096;
// Client knows about transactions
CLIENT_TRANSACTIONS = 8192;
// Old flag for 4.1 protocol
CLIENT_RESERVED = 16384;
// New 4.1 authentication
CLIENT_SECURE_CONNECTION = 32768;
// Enable/disable multi-stmt support
// 通知服务器客户端可以发送多条语句(由分号分隔)。如果该标志为没有被设置,多条语句执行。
CLIENT_MULTI_STATEMENTS = 65536;
// Enable/disable multi-results
// 通知服务器客户端可以处理由多语句或者存储过程执行生成的多结果集。
// 当打开CLIENT_MULTI_STATEMENTS时,这个标志自动的被打开。
CLIENT_MULTI_RESULTS = 131072;
CLIENT_PLUGIN_AUTH = $00080000; // 524288
end;
TFields = class
public const
FIELD_TYPE_DECIMAL = 0;
FIELD_TYPE_TINY = 1;
FIELD_TYPE_SHORT = 2;
FIELD_TYPE_LONG = 3;
FIELD_TYPE_FLOAT = 4;
FIELD_TYPE_DOUBLE = 5;
FIELD_TYPE_NULL = 6;
FIELD_TYPE_TIMESTAMP = 7;
FIELD_TYPE_LONGLONG = 8;
FIELD_TYPE_INT24 = 9;
FIELD_TYPE_DATE = 10;
FIELD_TYPE_TIME = 11;
FIELD_TYPE_DATETIME = 12;
FIELD_TYPE_YEAR = 13;
FIELD_TYPE_NEWDATE = 14;
FIELD_TYPE_VARCHAR = 15;
FIELD_TYPE_BIT = 16;
FIELD_TYPE_NEW_DECIMAL = 246;
FIELD_TYPE_ENUM = 247;
FIELD_TYPE_SET = 248;
FIELD_TYPE_TINY_BLOB = 249;
FIELD_TYPE_MEDIUM_BLOB = 250;
FIELD_TYPE_LONG_BLOB = 251;
FIELD_TYPE_BLOB = 252;
FIELD_TYPE_VAR_STRING = 253;
FIELD_TYPE_STRING = 254;
FIELD_TYPE_GEOMETRY = 255;
NOT_NULL_FLAG = $0001;
PRI_KEY_FLAG = $0002;
UNIQUE_KEY_FLAG = $0004;
MULTIPLE_KEY_FLAG = $0008;
BLOB_FLAG = $0010;
UNSIGNED_FLAG = $0020;
ZEROFILL_FLAG = $0040;
BINARY_FLAG = $0080;
ENUM_FLAG = $0100;
AUTO_INCREMENT_FLAG = $0200;
TIMESTAMP_FLAG = $0400;
SET_FLAG = $0800;
end;
implementation
end.
|
unit Project;
interface
uses
SysUtils, Classes, LrProject;
type
TProjectItems = class;
//
TProjectItem = class(TCollectionItem)
private
FIsFolder: Boolean;
FFilename: string;
FItems: TProjectItems;
protected
procedure SetFilename(const Value: string);
procedure SetIsFolder(const Value: Boolean);
procedure SetItems(const Value: TProjectItems);
public
constructor Create(inOwner: TCollection); override;
destructor Destroy; override;
function GetPublishPath: string;
procedure Subsume(inItem: TProjectItem);
published
property Filename: string read FFilename write SetFilename;
property IsFolder: Boolean read FIsFolder write SetIsFolder;
property Items: TProjectItems read FItems write SetItems;
end;
//
TProjectItems = class(TCollection)
private
FParentItem: TProjectItem;
protected
function GetProjectItems(inIndex: Integer): TProjectItem;
protected
procedure CompareNSwap(inItemA, inItemB: TProjectItem);
public
constructor Create;
function FindItem(const inFilename: string): TProjectItem;
procedure Sort;
property ParentItem: TProjectItem read FParentItem write FParentItem;
property ProjectItems[inIndex: Integer]: TProjectItem
read GetProjectItems; default;
end;
//
TProject = class(TLrProject)
private
FUrl: string;
FPublishFolder: string;
FItems: TProjectItems;
protected
function GetLibFolder: string;
function GetRoot: TProjectItem;
procedure SetFilename(const Value: string); override;
procedure SetItems(const Value: TProjectItems);
procedure SetPublishFolder(const Value: string);
procedure SetUrl(const Value: string);
protected
function GetRelativePath(const inFilename: string): string;
procedure Changed; override;
procedure ManuallyLoaded; override;
procedure UpdateFilenames(inItems: TProjectItems = nil);
public
constructor Create(inOwner: TComponent); override;
destructor Destroy; override;
function GetProjectFolder: string;
function GetPublishedImagesFolder(const inFilename: string): string;
function GetPublishFolder(const inFilename: string): string;
function GetPublishUrl(const inFilename: string): string;
function GetRelativePublishFolder(const inFilename: string): string;
function GetSourceImagesFolder(const inFilename: string): string;
function PathToProjectUrl(const inPath: string): string;
function ProjectPath(const inFilename: string): string;
procedure AddPage(inFilename: string; inParent: TProjectItem = nil);
procedure AddExistingPage(inParent: TProjectItem = nil);
procedure Clear;
procedure MoveItem(inSrc, inDst: TProjectItem);
procedure NewFolder(inParent: TProjectItem);
procedure Remove(const inFilename: string);
procedure RemoveItem(inItem: TProjectItem);
procedure Rename(const inOld, inNew: string); overload;
procedure Rename(inItem: TProjectItem; const inName: string); overload;
procedure Sort(inItems: TProjectItems = nil);
published
property Items: TProjectItems read FItems write SetItems;
property LibFolder: string read GetLibFolder;
property ProjectFolder: string read GetProjectFolder;
property PublishFolder: string read FPublishFolder write SetPublishFolder;
property Root: TProjectItem read GetRoot;
property Url: string read FUrl write SetUrl;
end;
implementation
uses
StrUtils, LrUtils, ThPathUtils, Config, Main;
const
cLibFolder = 'libs\';
cImagesFolder = 'images\';
{ TProjectItem }
constructor TProjectItem.Create(inOwner: TCollection);
begin
inherited;
FItems := TProjectItems.Create;
FItems.ParentItem := Self;
end;
destructor TProjectItem.Destroy;
begin
FItems.Free;
inherited;
end;
procedure TProjectItem.SetFilename(const Value: string);
begin
FFilename := Value;
end;
procedure TProjectItem.SetIsFolder(const Value: Boolean);
begin
FIsFolder := Value;
end;
procedure TProjectItem.SetItems(const Value: TProjectItems);
begin
if Value = nil then
FItems := nil
else
FItems.Assign(Value);
end;
procedure TProjectItem.Subsume(inItem: TProjectItem);
begin
FItems.Free;
FItems := inItem.Items;
Filename := inItem.Filename;
IsFolder := inItem.IsFolder;
inItem.Items := nil;
inItem.Free;
end;
function TProjectItem.GetPublishPath: string;
var
item: TProjectItem;
begin
Result := '';
item := TProjectItems(Collection).ParentItem;
while (item <> nil) do
begin
Result := IncludeTrailingBackslash(item.Filename) + Result;
item := TProjectItems(item.Collection).ParentItem;
end;
end;
{ TProjectItems }
constructor TProjectItems.Create;
begin
inherited Create(TProjectItem);
end;
function TProjectItems.GetProjectItems(inIndex: Integer): TProjectItem;
begin
Result := TProjectItem(Items[inIndex]);
end;
function TProjectItems.FindItem(const inFilename: string): TProjectItem;
var
i: Integer;
begin
Result := nil;
for i := 0 to Pred(Count) do
begin
if ProjectItems[i].Filename = inFilename then
Result := ProjectItems[i]
else
Result := ProjectItems[i].Items.FindItem(inFilename);
if Result <> nil then
break;
end;
end;
procedure TProjectItems.CompareNSwap(inItemA, inItemB: TProjectItem);
var
i: Integer;
begin
if (inItemB.IsFolder and not inItemA.IsFolder)
or ((inItemA.IsFolder = inItemB.IsFolder)
and (CompareText(inItemA.Filename, inItemB.Filename) > 0)) then
begin
i := inItemA.Index;
inItemA.Index := inItemB.Index;
inItemB.Index := i;
end;
end;
procedure TProjectItems.Sort;
var
i, j: Integer;
begin
for i := 0 to Pred(Count) do
for j := 0 to Pred(Pred(Count)) do
CompareNSwap(ProjectItems[j], ProjectItems[j + 1]);
end;
{ TProject }
constructor TProject.Create(inOwner: TComponent);
begin
inherited;
FItems := TProjectItems.Create;
with TProjectItem(FItems.Add) do
IsFolder := true;
end;
destructor TProject.Destroy;
begin
FItems.Free;
inherited;
end;
procedure TProject.Clear;
begin
Root.Items.Clear;
Url := '';
PublishFolder := '';
end;
procedure TProject.ManuallyLoaded;
begin
// if not DirectoryExists(PublishFolder) then
// PublishFolder := '';
UpdateFilenames;
Sort;
end;
function TProject.GetRoot: TProjectItem;
begin
Result := Items[0];
end;
function TProject.GetProjectFolder: string;
begin
Result := ExtractFilePath(Filename);
end;
function TProject.GetRelativePath(const inFilename: string): string;
begin
Result := ExtractRelativePath(ProjectFolder, inFilename);
end;
function TProject.GetPublishFolder(const inFilename: string): string;
var
item: TProjectItem;
begin
item := Items.FindItem(GetRelativePath(inFilename));
if item <> nil then
Result := item.GetPublishPath
else
Result := PublishFolder;
end;
function TProject.GetRelativePublishFolder(const inFilename: string): string;
begin
Result := ExtractRelativePath(PublishFolder, inFilename);
end;
function TProject.PathToProjectUrl(const inPath: string): string;
begin
Result := Url + ThPathToUrl(GetRelativePublishFolder(inPath));
//Result := Url + ThPathToUrl(ExtractRelativePath(PublishFolder, inPath));
end;
function TProject.GetPublishUrl(const inFilename: string): string;
var
item: TProjectItem;
begin
item := Items.FindItem(GetRelativePath(inFilename));
if item = nil then
Result := Url
else
Result := PathToProjectUrl(item.GetPublishPath);
end;
function TProject.ProjectPath(const inFilename: string): string;
begin
if ExtractFileDrive(inFilename) = '' then
Result := ProjectFolder + inFilename
else
Result := inFilename;
end;
function TProject.GetSourceImagesFolder(const inFilename: string): string;
begin
Result := ProjectFolder + cImagesFolder;
end;
function TProject.GetPublishedImagesFolder(const inFilename: string): string;
begin
Result := GetPublishFolder(inFilename) + cImagesFolder;
end;
procedure TProject.Changed;
begin
UpdateFilenames;
Sort;
inherited;
end;
procedure TProject.UpdateFilenames(inItems: TProjectItems);
var
i: Integer;
begin
if inItems = nil then
inItems := Items;
for i := 0 to Pred(inItems.Count) do
with inItems[i] do
begin
if not IsFolder then
Filename := GetRelativePath(Filename)
else
UpdateFilenames(Items);
end;
end;
procedure TProject.Sort(inItems: TProjectItems);
var
i: Integer;
begin
if inItems = nil then
inItems := Items;
inItems.Sort;
for i := 0 to Pred(inItems.Count) do
with inItems[i] do
if IsFolder then
Sort(Items);
end;
procedure TProject.SetPublishFolder(const Value: string);
begin
if Value <> FPublishFolder then
begin
if Value = '' then
FPublishFolder := ''
else
FPublishFolder := IncludeTrailingBackslash(Value);
Root.Filename := PublishFolder;
Changed;
end;
end;
procedure TProject.SetUrl(const Value: string);
begin
if Value <> FUrl then
begin
if Value = '' then
FUrl := ''
else
FUrl := IncludeTrailingFrontslash(Value);
Changed;
end;
end;
function TProject.GetLibFolder: string;
begin
Result := IncludeTrailingBackslash(PublishFolder + cLibFolder);
end;
procedure TProject.SetItems(const Value: TProjectItems);
begin
FItems.Assign(Value);
end;
procedure TProject.MoveItem(inSrc, inDst: TProjectItem);
begin
TProjectItem(inDst.Items.Insert(0)).Subsume(inSrc);
Changed;
end;
procedure TProject.NewFolder(inParent: TProjectItem);
begin
with TProjectItem(inParent.Items.Add) do
begin
IsFolder := true;
Filename := inParent.Filename + '\New Folder';
end;
Changed;
end;
procedure TProject.AddPage(inFilename: string; inParent: TProjectItem = nil);
begin
inFilename := GetRelativePath(inFilename);
if Items.FindItem(inFilename) = nil then
begin
if inParent = nil then
inParent := Root;
TProjectItem(inParent.Items.Add).Filename := inFilename;
Changed;
end;
end;
procedure TProject.AddExistingPage(inParent: TProjectItem = nil);
begin
with MainForm.OpenDialog do
if Execute then
AddPage(Filename, inParent);
end;
procedure TProject.RemoveItem(inItem: TProjectItem);
begin
inItem.Free;
Changed;
end;
procedure TProject.Remove(const inFilename: string);
var
item: TProjectItem;
begin
item := Items.FindItem(GetRelativePath(inFilename));
if item <> nil then
begin
item.Free;
Changed;
end;
end;
procedure TProject.Rename(inItem: TProjectItem; const inName: string);
begin
inItem.Filename := inName;
Changed;
end;
procedure TProject.Rename(const inOld, inNew: string);
var
item: TProjectItem;
begin
item := Items.FindItem(GetRelativePath(inOld));
if item <> nil then
Rename(item, GetRelativePath(inNew));
end;
procedure TProject.SetFilename(const Value: string);
begin
inherited;
// Changed;
end;
end.
|
unit uFrmParent;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, uFactoryFormIntf, uParamObject, ExtCtrls,
ActnList, uBaseInfoDef, uGridConfig, uDBComConfig, uDefCom, uModelFunIntf,
cxGridLevel, cxClasses, cxControls, cxGridCustomView, dxBar, uWmLabelEditBtn,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxGroupBox;
type
TfrmParent = class(TForm, IFormIntf)
actlstEvent: TActionList;
procedure FormShow(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
FMoudleNo: Integer; //模块的编号和uMoudleNoDef单元的常量对应
FParamList: TParamObject; //初始化是传入的参数
FTitle: string; //窗体工具栏显示的名称
FDBComItem: TFormDBComItem; //配置界面控件和数据字段
protected
{ IInterface }
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
{ IFormIntf }
procedure CreateParamList(AOwner: TComponent; AParam: TParamObject);
procedure FrmShow;
function FrmShowModal: Integer;
procedure FrmFree;
procedure FrmClose;
procedure ResizeFrm(AParentForm: TWinControl);
function GetForm: TForm;
procedure DoSelectBasic(Sender: TObject; ABasicType: TBasicType;
ASelectBasicParam: TSelectBasicParam;
ASelectOptions: TSelectBasicOptions; var ABasicDatas: TSelectBasicDatas;
var AReturnCount: Integer); virtual;
procedure BeforeFormShow; virtual;
procedure InitParamList; virtual; //产品可以在窗口创建之前先对参数进行处理;不要对界面的控件进行处理
procedure BeforeFormDestroy; virtual;
procedure SetTitle(const Value: string); virtual;
procedure IniView; virtual; //初始化视图
procedure IniData; virtual;
procedure InitialAllComponent; virtual;
procedure InitcxGridClass(AComp: TComponent);
procedure InitPanel(AComp: TComponent);
procedure InitdxBar(AComp: TComponent);
procedure InitWmLabelEditBtn(AComp: TComponent);
procedure InitcxGroupBox(AComp: TComponent);
public
{ Public declarations }
constructor CreateFrmParamList(AOwner: TComponent; AParam: TParamObject); virtual; //带参数的创建
property MoudleNo: Integer read FMoudleNo write FMoudleNo;
property ParamList: TParamObject read FParamList write FParamList;
class function GetMdlDisName: string; virtual; //得到模块显示名称
property Title: string read FTitle write SetTitle; //代表了子类的lbltitle.caption
property DBComItem: TFormDBComItem read FDBComItem write FDBComItem;
function FrmShowStyle: TShowStyle; virtual; abstract; //窗体显示的类型,是否modal
end;
var
frmParent: TfrmParent;
implementation
uses uSysSvc, uDBIntf, uMainFormIntf, uMoudleNoDef, uFrmBaseSelect;
{$R *.dfm}
{ TParentForm }
procedure TfrmParent.BeforeFormDestroy;
begin
ParamList.Free;
end;
procedure TfrmParent.BeforeFormShow;
begin
if Self.GetMdlDisName <> '' then
Title := Self.GetMdlDisName;
IniView;
end;
procedure TfrmParent.CreateParamList(AOwner: TComponent;
AParam: TParamObject);
begin
CreateFrmParamList(AOwner, AParam);
end;
procedure TfrmParent.FormShow(Sender: TObject);
begin
Color := clWhite;
FDBComItem := TFormDBComItem.Create(Self);
FDBComItem.OnSelectBasic := DoSelectBasic;
BeforeFormShow();
end;
procedure TfrmParent.InitParamList;
begin
end;
procedure TfrmParent.FormDestroy(Sender: TObject);
begin
BeforeFormDestroy();
FDBComItem.Free;
end;
constructor TfrmParent.CreateFrmParamList(AOwner: TComponent;
AParam: TParamObject);
begin
//要设置窗口的Visable为false,不然在调用create和设置Parent以后就会执行show事件
ParamList := TParamObject.Create;
if Assigned(AParam) then ParamList.Params := AParam.Params;
InitParamList();
Create(AOwner);
// 赋窗体标题
if Self.GetMdlDisName <> EmptyStr then
Self.Caption := Self.GetMdlDisName;
end;
procedure TfrmParent.FrmShow;
begin
Self.Show;
end;
procedure TfrmParent.FrmFree;
begin
Self.Free;
end;
procedure TfrmParent.FrmClose;
begin
Self.Close;
end;
function TfrmParent.FrmShowModal: Integer;
begin
Result := Self.ShowModal;
end;
class function TfrmParent.GetMdlDisName: string;
begin
Result := '';
end;
procedure TfrmParent.SetTitle(const Value: string);
begin
FTitle := Value;
Caption := Value;
end;
procedure TfrmParent.IniData;
begin
end;
procedure TfrmParent.IniView;
begin
end;
function TfrmParent._AddRef: Integer;
begin
Result := -1;
end;
function TfrmParent._Release: Integer;
begin
Result := -1;
end;
function TfrmParent.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
if GetInterface(IID, Obj) then
Result := 0
else
Result := E_NOINTERFACE;
end;
procedure TfrmParent.DoSelectBasic(Sender: TObject; ABasicType: TBasicType;
ASelectBasicParam: TSelectBasicParam;
ASelectOptions: TSelectBasicOptions; var ABasicDatas: TSelectBasicDatas;
var AReturnCount: Integer);
begin
//基本信息选择
//双击、按钮为全部,回车支持模糊查询
if ASelectBasicParam.SelectBasicMode <> sbtKeydown then
ASelectBasicParam.SearchString := '';
AReturnCount := SelectBasicData(ABasicType, ASelectBasicParam,
ASelectOptions, ABasicDatas);
end;
procedure TfrmParent.InitialAllComponent;
var i: Integer;
begin
Font.Name := '宋体';
Font.Size := 10;
for i := 0 to ComponentCount - 1 do
begin
if (Components[i] is TcxGridTableView) then InitcxGridClass(Components[i])
else if (Components[i] is TdxBar) then InitdxBar(Components[i])
else if (Components[i] is TPanel) then InitPanel(Components[i])
else if (Components[i] is TWmLabelEditBtn) then InitWmLabelEditBtn(Components[i])
else if (Components[i] is TcxGroupBox) then InitcxGroupBox(Components[i]);
end;
end;
procedure TfrmParent.FormCreate(Sender: TObject);
begin
InitialAllComponent();
end;
procedure TfrmParent.InitcxGridClass(AComp: TComponent);
var
aCxGrid: TcxGridTableView;
begin
aCxGrid := TcxGridTableView(AComp);
aCxGrid.OptionsView.DataRowHeight := 25;
end;
procedure TfrmParent.ResizeFrm(AParentForm: TWinControl);
begin
Width := AParentForm.Width;
Height := AParentForm.Height;
end;
function TfrmParent.GetForm: TForm;
begin
Result := Self;
end;
procedure TfrmParent.InitPanel(AComp: TComponent);
begin
TPanel(AComp).Color := clWhite;
end;
procedure TfrmParent.InitdxBar(AComp: TComponent);
begin
TdxBar(AComp).Color := clWhite;
end;
procedure TfrmParent.InitWmLabelEditBtn(AComp: TComponent);
begin
// TWmLabelEditBtn(AComp).LabelFont.Name := '宋体';
// TWmLabelEditBtn(AComp).LabelFont.Size := 9;
//
// TWmLabelEditBtn(AComp).Style.Font.Name := '宋体';
// TWmLabelEditBtn(AComp).Style.Font.Size := 9;
end;
procedure TfrmParent.InitcxGroupBox(AComp: TComponent);
begin
// TcxGroupBox(AComp).Font.Name := '宋体';
// TcxGroupBox(AComp).Font.Size := 9;
//
// TcxGroupBox(AComp).Style.Font.Name := '宋体';
// TcxGroupBox(AComp).Style.Font.Size := 9;
end;
initialization
end.
|
unit TextureAtlasExtractorCommand;
interface
uses ControllerDataTypes, ActorActionCommandBase, Actor, GLConstants;
{$INCLUDE source/Global_Conditionals.inc}
type
TTextureAtlasExtractorCommand = class (TActorActionCommandBase)
const
C_DEFAULT_ANGLE = C_TEX_MIN_ANGLE;
C_DEFAULT_SIZE = 1024;
protected
FAngle: single;
FSize: longint;
public
constructor Create(var _Actor: TActor; var _Params: TCommandParams); override;
procedure Execute; override;
end;
implementation
uses StopWatch, TextureAtlasExtractorBase, TextureAtlasExtractor, GlobalVars,
SysUtils;
constructor TTextureAtlasExtractorCommand.Create(var _Actor: TActor; var _Params: TCommandParams);
begin
FCommandName := 'Texture Atlas Extraction SBGames 2010';
ReadAttributes1Int1Single(_Params, FSize, FAngle, C_DEFAULT_SIZE, C_DEFAULT_ANGLE);
inherited Create(_Actor,_Params);
end;
procedure TTextureAtlasExtractorCommand.Execute;
var
TexExtractor : CTextureAtlasExtractorBase;
{$ifdef SPEED_TEST}
StopWatch : TStopWatch;
{$endif}
begin
{$ifdef SPEED_TEST}
StopWatch := TStopWatch.Create(true);
{$endif}
// First, we'll build the texture atlas.
TexExtractor := CTextureAtlasExtractor.Create(FActor.Models[0]^.LOD[FActor.Models[0]^.CurrentLOD],FAngle);
TexExtractor.ExecuteWithDiffuseTexture(FSize);
TexExtractor.Free;
{$ifdef SPEED_TEST}
StopWatch.Stop;
GlobalVars.SpeedFile.Add('Texture atlas and diffuse texture extraction for LOD takes: ' + FloatToStr(StopWatch.ElapsedNanoseconds) + ' nanoseconds.');
StopWatch.Free;
{$endif}
end;
end.
|
(*
Category: SWAG Title: SORTING ROUTINES
Original name: 0064.PAS
Description: Combsort with wrapper
Author: GLENN GROTZINGER
Date: 11-29-96 08:17
*)
{ Pascal example of COMBSORT with wrapper. }
program combsorttest;
{ Pascal implementation of modified bubble sort or combsort.
combsort algorithm published 4-91 in Byte by Steven Lacey and
Richard Box
Ported from COBOL source by Glenn Grotzinger }
const
irgap: real = 1.3;
var
a: array[1..20] of integer;
swapvalue: integer;
swapnumber: integer;
i: integer;
jumpsize, tablesize, upperlimit: integer;
swap: boolean;
begin
randomize;
for i := 1 to 20 do
a[i] := random(15);
for i := 1 to 20 do
write(a[i], ' ');
writeln;
swap := true;
tablesize := 20;
jumpsize := tablesize;
repeat
jumpsize := trunc(jumpsize/irgap);
swap := true;
for i := 1 to (tablesize-jumpsize) do
begin
swapnumber := i + jumpsize;
if a[i] > a[swapnumber] then
begin
swapvalue := a[i];
a[i] := a[swapnumber];
a[swapnumber] := swapvalue;
swap := false;
end;
end;
until (swap) and (jumpsize <= 1);
for i := 1 to 20 do
write(a[i], ' ');
writeln;
end.
|
//
// Generated by JavaToPas v1.4 20140526 - 133024
////////////////////////////////////////////////////////////////////////////////
unit android.net.Uri;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
Androidapi.JNI.os,
android.net.Uri_Builder;
type
JUri = interface;
JUriClass = interface(JObjectClass)
['{191CE90D-F218-47E2-AEEC-C7E5E3053858}']
function _GetCREATOR : JParcelable_Creator; cdecl; // A: $19
function _GetEMPTY : JUri; cdecl; // A: $19
function buildUpon : JUri_Builder; cdecl; // ()Landroid/net/Uri$Builder; A: $401
function compareTo(other : JUri) : Integer; cdecl; // (Landroid/net/Uri;)I A: $1
function decode(s : JString) : JString; cdecl; // (Ljava/lang/String;)Ljava/lang/String; A: $9
function encode(s : JString) : JString; cdecl; overload; // (Ljava/lang/String;)Ljava/lang/String; A: $9
function encode(s : JString; allow : JString) : JString; cdecl; overload; // (Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; A: $9
function equals(o : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $1
function fromFile(&file : JFile) : JUri; cdecl; // (Ljava/io/File;)Landroid/net/Uri; A: $9
function fromParts(scheme : JString; ssp : JString; fragment : JString) : JUri; cdecl;// (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Landroid/net/Uri; A: $9
function getAuthority : JString; cdecl; // ()Ljava/lang/String; A: $401
function getBooleanQueryParameter(key : JString; defaultValue : boolean) : boolean; cdecl;// (Ljava/lang/String;Z)Z A: $1
function getEncodedAuthority : JString; cdecl; // ()Ljava/lang/String; A: $401
function getEncodedFragment : JString; cdecl; // ()Ljava/lang/String; A: $401
function getEncodedPath : JString; cdecl; // ()Ljava/lang/String; A: $401
function getEncodedQuery : JString; cdecl; // ()Ljava/lang/String; A: $401
function getEncodedSchemeSpecificPart : JString; cdecl; // ()Ljava/lang/String; A: $401
function getEncodedUserInfo : JString; cdecl; // ()Ljava/lang/String; A: $401
function getFragment : JString; cdecl; // ()Ljava/lang/String; A: $401
function getHost : JString; cdecl; // ()Ljava/lang/String; A: $401
function getLastPathSegment : JString; cdecl; // ()Ljava/lang/String; A: $401
function getPath : JString; cdecl; // ()Ljava/lang/String; A: $401
function getPathSegments : JList; cdecl; // ()Ljava/util/List; A: $401
function getPort : Integer; cdecl; // ()I A: $401
function getQuery : JString; cdecl; // ()Ljava/lang/String; A: $401
function getQueryParameter(key : JString) : JString; cdecl; // (Ljava/lang/String;)Ljava/lang/String; A: $1
function getQueryParameterNames : JSet; cdecl; // ()Ljava/util/Set; A: $1
function getQueryParameters(key : JString) : JList; cdecl; // (Ljava/lang/String;)Ljava/util/List; A: $1
function getScheme : JString; cdecl; // ()Ljava/lang/String; A: $401
function getSchemeSpecificPart : JString; cdecl; // ()Ljava/lang/String; A: $401
function getUserInfo : JString; cdecl; // ()Ljava/lang/String; A: $401
function hashCode : Integer; cdecl; // ()I A: $1
function isAbsolute : boolean; cdecl; // ()Z A: $1
function isHierarchical : boolean; cdecl; // ()Z A: $401
function isOpaque : boolean; cdecl; // ()Z A: $1
function isRelative : boolean; cdecl; // ()Z A: $401
function parse(uriString : JString) : JUri; cdecl; // (Ljava/lang/String;)Landroid/net/Uri; A: $9
function toString : JString; cdecl; // ()Ljava/lang/String; A: $401
function withAppendedPath(baseUri : JUri; pathSegment : JString) : JUri; cdecl;// (Landroid/net/Uri;Ljava/lang/String;)Landroid/net/Uri; A: $9
procedure writeToParcel(&out : JParcel; uri : JUri) ; cdecl; // (Landroid/os/Parcel;Landroid/net/Uri;)V A: $9
property CREATOR : JParcelable_Creator read _GetCREATOR; // Landroid/os/Parcelable$Creator; A: $19
property EMPTY : JUri read _GetEMPTY; // Landroid/net/Uri; A: $19
end;
[JavaSignature('android/net/Uri$Builder')]
JUri = interface(JObject)
['{9A3F7B76-94F2-4367-86E6-989C4C32F88D}']
function buildUpon : JUri_Builder; cdecl; // ()Landroid/net/Uri$Builder; A: $401
function compareTo(other : JUri) : Integer; cdecl; // (Landroid/net/Uri;)I A: $1
function equals(o : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $1
function getAuthority : JString; cdecl; // ()Ljava/lang/String; A: $401
function getBooleanQueryParameter(key : JString; defaultValue : boolean) : boolean; cdecl;// (Ljava/lang/String;Z)Z A: $1
function getEncodedAuthority : JString; cdecl; // ()Ljava/lang/String; A: $401
function getEncodedFragment : JString; cdecl; // ()Ljava/lang/String; A: $401
function getEncodedPath : JString; cdecl; // ()Ljava/lang/String; A: $401
function getEncodedQuery : JString; cdecl; // ()Ljava/lang/String; A: $401
function getEncodedSchemeSpecificPart : JString; cdecl; // ()Ljava/lang/String; A: $401
function getEncodedUserInfo : JString; cdecl; // ()Ljava/lang/String; A: $401
function getFragment : JString; cdecl; // ()Ljava/lang/String; A: $401
function getHost : JString; cdecl; // ()Ljava/lang/String; A: $401
function getLastPathSegment : JString; cdecl; // ()Ljava/lang/String; A: $401
function getPath : JString; cdecl; // ()Ljava/lang/String; A: $401
function getPathSegments : JList; cdecl; // ()Ljava/util/List; A: $401
function getPort : Integer; cdecl; // ()I A: $401
function getQuery : JString; cdecl; // ()Ljava/lang/String; A: $401
function getQueryParameter(key : JString) : JString; cdecl; // (Ljava/lang/String;)Ljava/lang/String; A: $1
function getQueryParameterNames : JSet; cdecl; // ()Ljava/util/Set; A: $1
function getQueryParameters(key : JString) : JList; cdecl; // (Ljava/lang/String;)Ljava/util/List; A: $1
function getScheme : JString; cdecl; // ()Ljava/lang/String; A: $401
function getSchemeSpecificPart : JString; cdecl; // ()Ljava/lang/String; A: $401
function getUserInfo : JString; cdecl; // ()Ljava/lang/String; A: $401
function hashCode : Integer; cdecl; // ()I A: $1
function isAbsolute : boolean; cdecl; // ()Z A: $1
function isHierarchical : boolean; cdecl; // ()Z A: $401
function isOpaque : boolean; cdecl; // ()Z A: $1
function isRelative : boolean; cdecl; // ()Z A: $401
function toString : JString; cdecl; // ()Ljava/lang/String; A: $401
end;
TJUri = class(TJavaGenericImport<JUriClass, JUri>)
end;
implementation
end.
|
unit BZK2_Camera;
interface
type
TBZK2Camera = class
private
Actor : integer;
public
// Constructors & Destructors
constructor Create;
destructor Destroy; override;
// I/O
procedure WriteToFile (var MyFile : System.Text);
// Gets
function GetActor : integer;
// Sets
procedure SetActor (Value : integer);
// Assign
procedure Assign(const Camera: TBZK2Camera);
end;
implementation
// Constructors & Destructors
constructor TBZK2Camera.Create;
begin
Actor := 0;
end;
destructor TBZK2Camera.Destroy;
begin
inherited Destroy;
end;
// I/O
procedure TBZK2Camera.WriteToFile (var MyFile : System.Text);
begin
WriteLn(MyFile,'<Camera>');
WriteLn(MyFile,Actor);
WriteLn(MyFile,'</Camera>');
end;
// Gets
function TBZK2Camera.GetActor : integer;
begin
Result := Actor;
end;
// Sets
procedure TBZK2Camera.SetActor (Value : integer);
begin
Actor := Value;
end;
procedure TBZK2Camera.Assign(const Camera: TBZK2Camera);
begin
SetActor(Camera.GetActor);
end;
end.
|
{*******************************************************************************}
{ }
{ Newton Game Dynamics Delphi-Headertranslation }
{ Current SDK version 2.0 Beta }
{ }
{ Copyright (c) 2004,05,06,09 Stuart "Stucuk" Carey }
{ Sascha Willems }
{ Jon Walton }
{ Dominique Louis }
{ }
{ Initial Author : S.Spasov (Sury) }
{ }
{*******************************************************************************}
{ }
{ License : }
{ }
{ 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. }
{ }
{*******************************************************************************}
{ }
{ See "Readme_NewtonImport.txt" for more information and detailed history }
{ }
{*******************************************************************************}
{ Original copyright from newton.h :
* Copyright (c) <2003-2011> <Julio Jerez, Newton Game Dynamics>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*
}
unit NewtonImport;
// Note: Declare the following in Projects->Options->Conditionals not in this unit! - Stucuk
//{$DEFINE NEWTON_DOUBLE_PRECISION} // This is needed when you want to use double precision
interface
uses
{$IFDEF __GPC__}
system,
gpc,
{$ENDIF}
{$IFDEF UNIX}
{$IFDEF FPC}
{$IFDEF Ver1_0}
linux,
{$ELSE}
pthreads,
baseunix,
unix,
{$ENDIF}
x,
xlib,
{$ELSE}
Types,
Libc,
Xlib,
{$ENDIF}
{$ENDIF}
{$IFDEF __MACH__}
GPCMacOSAll,
{$ENDIF}
Classes,
Maths3D;
const
{$IFDEF WIN32}
{$IFDEF NEWTONTUTORIAL}
NewtonDLL = '..\..\sdk\dll\Newton.dll';
{$ELSE}
NewtonDLL = 'Newton.dll';
{$ENDIF}
{$ENDIF}
{$IFDEF UNIX}
{$IFDEF DARWIN} // MacOS X
NewtonDLL = 'libnewton.dylib';
{$ELSE}
NewtonDLL = 'libnewton.so';
{$ENDIF}
{$ENDIF}
{$IFDEF MACOS}
NewtonDLL = 'libnewton';
{$ENDIF}
(*Comment this line if you get weird errors*)
{$DEFINE NICE_CODE_PARAMS}
{type }
const
NEWTON_PROFILER_WORLD_UPDATE = 0;
NEWTON_PROFILER_COLLISION_UPDATE = 1;
NEWTON_PROFILER_COLLISION_UPDATE_BROAD_PHASE = 2;
NEWTON_PROFILER_COLLISION_UPDATE_NARROW_PHASE = 3;
NEWTON_PROFILER_DYNAMICS_UPDATE = 4;
NEWTON_PROFILER_DYNAMICS_CONSTRAINT_GRAPH = 5;
NEWTON_PROFILER_FORCE_CALLBACK_UPDATE = 6;
NEWTON_PROFILER_DYNAMICS_SOLVE_CONSTRAINT_GRAPH = 7;
SERIALIZE_ID_BOX = 0;
SERIALIZE_ID_CONE = 1;
SERIALIZE_ID_SPHERE = 2;
SERIALIZE_ID_CAPSULE = 3;
SERIALIZE_ID_CYLINDER = 4;
SERIALIZE_ID_COMPOUND = 5;
SERIALIZE_ID_CONVEXHULL = 6;
SERIALIZE_ID_CONVEXMODIFIER = 7;
SERIALIZE_ID_CHAMFERCYLINDER = 8;
SERIALIZE_ID_TREE = 9;
SERIALIZE_ID_NULL = 10;
SERIALIZE_ID_HEIGHTFIELD = 11;
SERIALIZE_ID_USERMESH = 12;
SERIALIZE_ID_SCENE = 13;
SERIALIZE_ID_COMPOUND_BREAKABLE = 14;
type
{I did this to speed up the translation process and avoid bugs}
{if you don't like me screw up the Delphi syntax with those
(C++ types just do a simple find and replace =)
{Pascal to C++}
{simple types}
Bool = Boolean;
//Moved Maths related C++ Definitions to Maths3D.pas
{Pointer types}
Pvoid = Pointer; //void pointer
PBool = ^Bool;
{end Pascal to C++}
{well this might look stupid
but i did it in order to make
code complete and code parameters hint window
to show the actual type for ex. PNewtonWorld
instead of just "Pointer" , thus making programming a lot easier}
{$IFDEF NICE_CODE_PARAMS}
PNewtonMesh = ^Pointer;
PNewtonBody = ^Pointer;
PNewtonWorld = ^Pointer;
PNewtonJoint = ^Pointer;
PNewtonContact = ^Pointer;
PNewtonMaterial = ^Pointer;
PNewtonCollision = ^Pointer;
PNewtonSceneProxy = ^Pointer;
PNewtonBreakableComponentMesh = ^Pointer;
PNewtonMeshVertex = ^Pointer;
PNewtonMeshEdge = ^Pointer;
PNewtonMeshFace = ^Pointer;
PNewtonMeshPoint= ^Pointer;
// JointLibrary
PNewtonUserJoint = ^Pointer;
//PNewtonRagDoll = ^Pointer;
//PNewtonRagDollBone = ^Pointer;
{$ELSE}
PNewtonMesh = Pointer;
PNewtonBody = Pointer;
PNewtonWorld = Pointer;
PNewtonJoint = Pointer;
PNewtonContact = Pointer;
PNewtonMaterial = Pointer;
PNewtonCollision = Pointer;
PNewtonSceneProxy = Pointer;
PNewtonBreakableComponentMesh = Pointer;
PNewtonMeshVertex = Pointer;
PNewtonMeshEdge = Pointer;
PNewtonMeshFace = Pointer;
PNewtonMeshPoint= Pointer;
// JointLibrary
PNewtonUserJoint = Pointer;
//PNewtonRagDoll = Pointer;
//PNewtonRagDollBone = Pointer;
{$ENDIF}
PNewtonCollisionInfoRecord = ^NewtonCollisionInfoRecord;
NewtonCollisionInfoRecord = Record
{
Note: NewtonCollisionInfoRecord needs to be converted!!!
}
end;
PNewtonJointRecord = ^NewtonJointRecord;
NewtonJointRecord = record
m_attachmenMatrix_0 : array[ 0..3,0..3 ] of float;
m_attachmenMatrix_1 : array[ 0..3,0..3 ] of float;
m_minLinearDof : array[ 0..2 ] of float;
m_maxLinearDof : array[ 0..2 ] of float;
m_minAngularDof : array[ 0..2 ] of float;
m_maxAngularDof : array[ 0..2 ] of float;
m_attachBody_0 : PNewtonBody;
m_attachBody_1 : PNewtonBody;
m_extraParameters : array[ 0..15 ] of float;
m_bodiesCollisionOn : int;
m_descriptionType : array[ 0..31 ] of NChar;
end;
PNewtonUserMeshCollisionCollideDesc = ^NewtonUserMeshCollisionCollideDesc;
NewtonUserMeshCollisionCollideDesc = record
m_boxP0 : array[ 0..3 ] of float; // lower bounding box of intersection query in local space
m_boxP1 : array[ 0..3 ] of float; // upper bounding box of intersection query in local space
m_threadNumber : int; // current thread executing this query
m_faceCount : int; // the application should set here how many polygons intersect the query box
m_vertexStrideInBytes : int; // the application should set here the size of each vertex
m_userData : Pointer; // user data passed to the collision geometry at creation time
m_vertex : ^float; // the application should the pointer to the vertex array.
m_userAttribute : ^int; // the application should set here the pointer to the user data, one for each face
m_faceIndexCount : ^int; // the application should set here the pointer to the vertex count of each face.
m_faceVertexIndex : ^int; // the application should set here the pointer index array for each vertex on a face.
m_objBody : PNewtonBody; // pointer to the colliding body
m_polySoupBody : PNewtonBody; // pointer to the rigid body owner of this collision tree
end;
PNewtonWorldConvexCastReturnInfo = ^NewtonWorldConvexCastReturnInfo;
NewtonWorldConvexCastReturnInfo = record
m_point : array[ 0..3 ] of float; // collision point in global space
m_normal : array[ 0..3 ] of float; // surface normal at collision point in global space
m_normalOnHitPoint : array[ 0..3 ] of float; // surface normal at the surface of the hit body,
// is the same as the normal calculated by a ray cast hitting the body at the hit poi
m_penetration : float; // contact penetration at collision point
m_contactID : int; // collision ID at contact point
m_hitBody : PNewtonBody; // body hit at contact point
end;
PNewtonUserMeshCollisionRayHitDesc = ^NewtonUserMeshCollisionRayHitDesc;
NewtonUserMeshCollisionRayHitDesc = record
m_p0 : array[ 0..3 ] of float; // ray origin in collision local space
m_p1 : array[ 0..3 ] of float; // ray destination in collision local space
m_normalOut : array[ 0..3 ] of float; // copy here the normal at the ray intersection
m_userIdOut : int; // copy here a user defined id for further feedback
m_userData : Pointer; // user data passed to the collision geometry at creation time
end;
PNewtonHingeSliderUpdateDesc = ^NewtonHingeSliderUpdateDesc;
NewtonHingeSliderUpdateDesc = record
m_accel : float;
m_minFriction : float;
m_maxFriction : float;
m_timestep : float;
end;
// *****************************************************************************************************************************
//
// Callbacks
//
// *****************************************************************************************************************************
PNewtonAllocMemory = ^NewtonAllocMemory;
NewtonAllocMemory = function( sizeInBytes : int ) : Pointer; cdecl;
PNewtonFreeMemory = ^NewtonFreeMemory;
NewtonFreeMemory = procedure( ptr : Pointer; sizeInBytes : int ); cdecl;
//Added for 2.0
NewtonGetTicksCountCallback = function () : cardinal; cdecl;
PNewtonGetTicksCountCallback = ^NewtonGetTicksCountCallback;
NewtonSerialize = procedure( serializeHandle : Pointer; const buffer : Pointer; size : size_t ); cdecl;
PNewtonSerialize = ^NewtonSerialize;
NewtonDeserialize = procedure( serializeHandle : Pointer; buffer : Pointer; size : size_t ); cdecl;
PNewtonDeserialize = ^NewtonDeserialize;
NewtonUserMeshCollisionDestroyCallback = procedure( descData : Pointer ); cdecl;
PNewtonUserMeshCollisionDestroyCallback = ^NewtonUserMeshCollisionDestroyCallback;
NewtonUserMeshCollisionCollideCallback = procedure( NewtonUserMeshCollisionCollideDesc : PNewtonUserMeshCollisionCollideDesc ); cdecl;
PNewtonUserMeshCollisionCollideCallback = ^NewtonUserMeshCollisionCollideCallback;
NewtonUserMeshCollisionRayHitCallback = function( NewtonUserMeshCollisionRayHitDesc : PNewtonUserMeshCollisionRayHitDesc ) : int; cdecl;
PNewtonUserMeshCollisionRayHitCallback = ^NewtonUserMeshCollisionRayHitCallback;
//Added for 2.0
NewtonUserMeshCollisionGetCollisionInfo = procedure( userData : Pointer; infoRecord : PNewtonCollisionInfoRecord ); cdecl;
PNewtonUserMeshCollisionGetCollisionInfo = ^NewtonUserMeshCollisionGetCollisionInfo;
//Added for 2.0
NewtonUserMeshCollisionGetFacesInAABB = procedure( userData : Pointer; const p0 : PFloat; const p1 : PFloat; const vertexArray : PFloat; vertexCount : pint;
vertexStrideInBytes : pint; const indexList : pint; maxIndexCount : int; const userDataList : pint ); cdecl;
PNewtonUserMeshCollisionGetFacesInAABB = ^NewtonUserMeshCollisionGetFacesInAABB;
//Added for 2.0
NewtonCollisionTreeRayCastCallback = function( interception : Float; normal : PFloat; faceId : int; usedData : Pointer) : Float; cdecl;
PNewtonCollisionTreeRayCastCallback = ^NewtonCollisionTreeRayCastCallback;
//Updated for 2.0 - collision tree call back (obsoleted no recommended)
NewtonTreeCollisionCallback = procedure( const bodyWithTreeCollision : PNewtonBody; const body : PNewtonBody; faceID : int;
const vertex : PFloat; vertexstrideInBytes : int); cdecl;
PNewtonTreeCollisionCallback = ^NewtonTreeCollisionCallback;
NewtonBodyDestructor = procedure( const body : PNewtonBody ); cdecl;
PNewtonBodyDestructor = ^NewtonBodyDestructor;
//Updated for 2.0
NewtonBodyLeaveWorld = procedure( const body : PNewtonBody; threadIndex : int ); cdecl;
PNewtonBodyLeaveWorld = ^NewtonBodyLeaveWorld;
//Updated for 2.0
NewtonApplyForceAndTorque = procedure( const body : PNewtonBody; timestep : Float; threadIndex : int ); cdecl;
PNewtonApplyForceAndTorque = ^NewtonApplyForceAndTorque;
//Removed for 2.0
//NewtonBodyActivationState = procedure( const body : PNewtonBody; state : unsigned_int ); cdecl;
//PNewtonBodyActivationState = ^NewtonBodyActivationState;
//Updated for 2.0
NewtonSetTransform = procedure( const body : PNewtonBody; const matrix : PFloat; threadIndex : int ); cdecl;
PNewtonSetTransform = ^NewtonSetTransform;
//Added for 2.0
NewtonIslandUpdate = function( islandHandle : Pointer; bodyCount : int) : int; cdecl;
PNewtonIslandUpdate = ^NewtonIslandUpdate;
//NewtonSetRagDollTransform = procedure( const bone : PNewtonRagDollBone ); cdecl;
//PNewtonSetRagDollTransform = ^NewtonSetRagDollTransform;
NewtonGetBuoyancyPlane = function(const collisionID : Int; context : Pointer; const globalSpaceMatrix : PFloat; globalSpacePlane : PFloat ) : Int; cdecl;
PNewtonGetBuoyancyPlane = ^NewtonGetBuoyancyPlane;
//Removed for 2.0
//NewtonVehicleTireUpdate = procedure( const vehicle: PNewtonJoint ); cdecl;
//PNewtonVehicleTireUpdate = ^NewtonVehicleTireUpdate;
NewtonWorldRayPrefilterCallback = function (const body : PNewtonBody; const collision : PNewtonCollision; userData : Pointer) : cardinal; cdecl;
PNewtonWorldRayPrefilterCallback = ^NewtonWorldRayPrefilterCallback;
NewtonWorldRayFilterCallback = function( const body : PNewtonBody; const hitNormal: PFloat; collisionID : Int; userData: Pointer; intersetParam: Float ) : Float; cdecl;
PNewtonWorldRayFilterCallback = ^NewtonWorldRayFilterCallback;
//Added for 2.0
NewtonOnAABBOverlap = function( const material : PNewtonMaterial; const body0 : PNewtonBody; const body1 : PNewtonBody; threadIndex : int ) : int; cdecl;
PNewtonOnAABBOverlap = ^NewtonOnAABBOverlap;
//Added for 2.0
NewtonContactsProcess = procedure( const contact : PNewtonJoint; timestep : Float; threadIndex : int ); cdecl;
PNewtonContactsProcess = ^NewtonContactsProcess;
//Removed for 2.0
//NewtonContactBegin = function( const material : PNewtonMaterial; const body0 : PNewtonBody; const body1 : PNewtonBody ) : int; cdecl;
//PNewtonContactBegin = ^NewtonContactBegin;
//Removed for 2.0
//NewtonContactProcess = function( const material : PNewtonMaterial; const contact : PNewtonContact ) : int; cdecl;
//PNewtonContactProcess = ^NewtonContactProcess;
//Removed for 2.0
//NewtonContactEnd = procedure( const material : PNewtonMaterial ); cdecl;
//PNewtonContactEnd = ^NewtonContactEnd;
NewtonBodyIterator = procedure( const body : PNewtonBody ); cdecl;
PNewtonBodyIterator = ^NewtonBodyIterator;
//Added for 2.0
NewtonJointIterator = procedure( const joint : PNewtonJoint ); cdecl;
PNewtonJointIterator = ^NewtonJointIterator;
//Updated for 2.0
NewtonCollisionIterator = procedure( userData : Pointer; vertexCount : int; const FaceArray : PFloat; faceId : int ); cdecl;
PNewtonCollisionIterator = ^NewtonCollisionIterator;
//Updated for 2.0
NewtonBallCallBack = procedure( const ball : PNewtonJoint; timestep : Float ); cdecl;
PNewtonBallCallBack = ^NewtonBallCallBack;
NewtonHingeCallBack = function( const hinge : PNewtonJoint; desc : PNewtonHingeSliderUpdateDesc ) : Unsigned_int; cdecl;
PNewtonHingeCallBack = ^NewtonHingeCallBack;
NewtonSliderCallBack = function( const slider : PNewtonJoint; desc : PNewtonHingeSliderUpdateDesc ) : Unsigned_int; cdecl;
PNewtonSliderCallBack = ^NewtonSliderCallBack;
NewtonUniversalCallBack = function( const universal : PNewtonJoint; desc : PNewtonHingeSliderUpdateDesc ) : Unsigned_int; cdecl;
PNewtonUniversalCallBack = ^NewtonUniversalCallBack;
NewtonCorkscrewCallBack = function( const corkscrew : PNewtonJoint; desc : PNewtonHingeSliderUpdateDesc ) : Unsigned_int; cdecl;
PNewtonCorkscrewCallBack = ^NewtonCorkscrewCallBack;
//Updated for 2.0
NewtonUserBilateralCallBack = procedure( const userJoint: PNewtonJoint; timestep : Float; threadIndex : int); cdecl;
PNewtonUserBilateralCallBack = ^NewtonUserBilateralCallBack;
//Added for 2.0
NewtonUserBilateralGetInfoCallBack = procedure( const userJoint : PNewtonJoint; info : PNewtonJointRecord ); cdecl;
PNewtonUserBilateralGetInfoCallBack = ^NewtonUserBilateralGetInfoCallBack;
NewtonConstraintDestructor = procedure( const me : PNewtonJoint ); cdecl;
PNewtonConstraintDestructor = ^NewtonConstraintDestructor;
// *****************************************************************************************************************************
//
// world control functions
//
// *****************************************************************************************************************************
function NewtonCreate( malloc : NewtonAllocMemory; mfree : NewtonFreeMemory ) : PNewtonWorld; cdecl; external{$IFDEF __GPC__}name 'NewtonCreate'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonDestroy( const newtonWorld : PNewtonWorld ); cdecl; external{$IFDEF __GPC__}name 'NewtonDestroy'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonDestroyAllBodies( const newtonWorld : PNewtonWorld ); cdecl; external{$IFDEF __GPC__}name 'NewtonDestroyAllBodies'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
function NewtonGetMemoryUsed() : int; cdecl; external{$IFDEF __GPC__}name 'NewtonGetMemoryUsed'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonUpdate( const newtonWorld : PNewtonWorld; timestep : float ); cdecl; external{$IFDEF __GPC__}name 'NewtonUpdate'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
procedure NewtonInvalidateCache( const newtonWorld : PNewtonWorld); cdecl; external{$IFDEF __GPC__}name 'NewtonInvalidateCache'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
procedure NewtonCollisionUpdate( const newtonWorld : PNewtonWorld); cdecl; external{$IFDEF __GPC__}name 'NewtonCollisionUpdate'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonSetSolverModel(const NewtonWorld : PNewtonWorld; Model : Int); cdecl; external{$IFDEF __GPC__}name 'NewtonSetSolverModel'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonSetPlatformArchitecture (const newtonWorld : PNewtonWorld; mode : Int); cdecl; external{$IFDEF __GPC__}name 'NewtonSetPlatformArchitecture'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
function NewtonGetPlatformArchitecture (const newtonWorld : PNewtonWorld; description : PCharArray) : int; cdecl; external{$IFDEF __GPC__}name 'NewtonGetPlatformArchitecture'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
procedure NewtonSetMultiThreadSolverOnSingleIsland (const newtonWorld : PNewtonWorld; mode : Int); cdecl; external{$IFDEF __GPC__}name 'NewtonSetMultiThreadSolverOnSingleIsland'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
procedure NewtonSetPerformanceClock (const newtonWorld : PNewtonWorld; NewtonGetTicksCountCallback : PNewtonGetTicksCountCallback); cdecl; external{$IFDEF __GPC__}name 'NewtonSetPerformanceClock'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
function NewtonReadPerformanceTicks (const newtonWorld : PNewtonWorld; thread : cardinal; performanceEntry : cardinal) : cardinal; cdecl; external{$IFDEF __GPC__}name 'NewtonReadPerformanceTicks'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
procedure NewtonWorldCriticalSectionLock (const newtonWorld : PNewtonWorld); cdecl; external{$IFDEF __GPC__}name 'NewtonWorldCriticalSectionLock'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
procedure NewtonWorldCriticalSectionUnlock (const newtonWorld : PNewtonWorld); cdecl; external{$IFDEF __GPC__}name 'NewtonWorldCriticalSectionUnlock'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
procedure NewtonSetThreadsCount (const newtonWorld : PNewtonWorld; threads : int); cdecl; external{$IFDEF __GPC__}name 'NewtonSetThreadsCount'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
function NewtonGetThreadsCount (const newtonWorld : PNewtonWorld) : int; cdecl; external{$IFDEF __GPC__}name 'NewtonGetThreadsCount'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonSetFrictionModel(const NewtonWorld : PNewtonWorld; Model : Int); cdecl; external{$IFDEF __GPC__}name 'NewtonSetFrictionModel'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Removed for 2.0
//function NewtonGetTimeStep(const NewtonWorld : PNewtonWorld) :Float; cdecl; external{$IFDEF __GPC__}name 'NewtonGetTimeStep'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonSetMinimumFrameRate( const newtonWorld : PNewtonWorld; frameRate : float ); cdecl; external{$IFDEF __GPC__}name 'NewtonSetMinimumFrameRate'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonSetBodyLeaveWorldEvent( const newtonWorld : PNewtonWorld; callback : PNewtonBodyLeaveWorld ); cdecl; external{$IFDEF __GPC__}name 'NewtonSetBodyLeaveWorldEvent'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonSetWorldSize( const newtonWorld : PNewtonWorld; const minPoint : PFloat; const maxPoint : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonSetWorldSize'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
procedure NewtonSetIslandUpdateEvent( const newtonWorld : PNewtonWorld; NewtonIslandUpdate : PNewtonIslandUpdate ); cdecl; external{$IFDEF __GPC__}name 'NewtonSetIslandUpdateEvent'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Removed for 2.0
//procedure NewtonWorldFreezeBody( const newtonWorld : PNewtonWorld; const body : PNewtonBody ); cdecl; external{$IFDEF __GPC__}name 'NewtonWorldFreezeBody'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Removed for 2.0
//procedure NewtonWorldUnfreezeBody( const newtonWorld : PNewtonWorld; const body : PNewtonBody ); cdecl; external{$IFDEF __GPC__}name 'NewtonWorldUnfreezeBody'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Removed for 2.0
//procedure NewtonWorldForEachBodyDo( const newtonWorld : PNewtonWorld; callback : PNewtonBodyIterator ); cdecl; external{$IFDEF __GPC__}name 'NewtonWorldForEachBodyDo'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
procedure NewtonWorldForEachJointDo (const newtonWorld : PNewtonWorld; callback : PNewtonJointIterator); cdecl; external{$IFDEF __GPC__}name 'NewtonWorldForEachJointDo'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonWorldForEachBodyInAABBDo (const newtonWorld : PNewtonWorld; const p0 : PFloat; const p1 : PFloat; callback : PNewtonBodyIterator); cdecl; external{$IFDEF __GPC__}name 'NewtonWorldForEachBodyInAABBDo'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonWorldSetUserData( const newtonWorld : PNewtonWorld; userData : Pointer); cdecl; external{$IFDEF __GPC__}name 'NewtonWorldSetUserData'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonWorldGetUserData( const newtonWorld : PNewtonWorld) : Pointer; cdecl; external{$IFDEF __GPC__}name 'NewtonWorldGetUserData'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonWorldGetVersion( const newtonWorld : PNewtonWorld) : int; cdecl; external{$IFDEF __GPC__}name 'NewtonWorldGetVersion'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonWorldRayCast( const newtonWorld : PNewtonWorld; const p0 : PFloat; const p1 : PFloat;
filter : PNewtonWorldRayFilterCallback; userData: Pointer;
prefilter : NewtonWorldRayPrefilterCallback); cdecl; external{$IFDEF __GPC__}name 'NewtonWorldRayCast'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
procedure NewtonWorldConvexCast( const newtonWorld : PNewtonWorld; const matrix : PFloat; const target : PFloat; const shape : PNewtonCollision;
hitParam : PFloat; userData: Pointer; prefilter : NewtonWorldRayPrefilterCallback;
info : PNewtonWorldConvexCastReturnInfo; maxContactsCount : int; threadIndex : int); cdecl; external{$IFDEF __GPC__}name 'NewtonWorldConvexCast'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
function NewtonWorldGetBodyCount( const newtonWorld : PNewtonWorld) : int; cdecl; external{$IFDEF __GPC__}name 'NewtonWorldGetBodyCount'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
function NewtonWorldGetConstraintCount( const newtonWorld : PNewtonWorld) : int; cdecl; external{$IFDEF __GPC__}name 'NewtonWorldGetConstraintCount'{$ELSE}NewtonDLL{$ENDIF __GPC__};
// *****************************************************************************************************************************
//
// Simulation islands
//
// *****************************************************************************************************************************
//Added for 2.0
function NewtonIslandGetBody( const island : Pointer; bodyIndex : int) : PNewtonBody; cdecl; external{$IFDEF __GPC__}name 'NewtonIslandGetBody'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
procedure NewtonIslandGetBodyAABB( const island : Pointer; bodyIndex : int; p0 : PFloat; p1 : PFloat); cdecl; external{$IFDEF __GPC__}name 'NewtonIslandGetBodyAABB'{$ELSE}NewtonDLL{$ENDIF __GPC__};
// *****************************************************************************************************************************
//
// Physics Material Section
//
// *****************************************************************************************************************************
function NewtonMaterialCreateGroupID( const newtonWorld : PNewtonWorld ) : int; cdecl; external{$IFDEF __GPC__}name 'NewtonMaterialCreateGroupID'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonMaterialGetDefaultGroupID( const newtonWorld : PNewtonWorld ) : int; cdecl; external{$IFDEF __GPC__}name 'NewtonMaterialGetDefaultGroupID'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonMaterialDestroyAllGroupID( const newtonWorld : PNewtonWorld ); cdecl; external{$IFDEF __GPC__}name 'NewtonMaterialDestroyAllGroupID'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonMaterialGetUserData( const NewtonWorld: PNewtonWorld; id0: int; id1: int): Pointer; cdecl; external{$IFDEF __GPC__}name 'NewtonMaterialGetUserData'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
procedure NewtonMaterialSetSurfaceThickness( const newtonWorld : PNewtonWorld; id0 : int; id1 : int; thickness : Float); cdecl; external{$IFDEF __GPC__}name 'NewtonMaterialSetSurfaceThickness'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonMaterialSetContinuousCollisionMode (const newtonWorld : PNewtonWOrld; id0, id1, state : int); cdecl; external{$IFDEF __GPC__}name 'NewtonMaterialSetContinuousCollisionMode'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Updated for 2.0
procedure NewtonMaterialSetCollisionCallback( const newtonWorld : PNewtonWorld; id0 : int; id1 : int; userData : Pointer; AABBOverlap : PNewtonOnAABBOverlap; process : PNewtonContactsProcess ); cdecl; external{$IFDEF __GPC__}name 'NewtonMaterialSetCollisionCallback'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonMaterialSetDefaultSoftness( const newtonWorld : PNewtonWorld; id0 : int; id1 : int; value : float ); cdecl; external{$IFDEF __GPC__}name 'NewtonMaterialSetDefaultSoftness'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonMaterialSetDefaultElasticity( const newtonWorld : PNewtonWorld; id0 : int; id1 : int; elasticCoef : float ); cdecl; external{$IFDEF __GPC__}name 'NewtonMaterialSetDefaultElasticity'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonMaterialSetDefaultCollidable( const newtonWorld : PNewtonWorld; id0 : int; id1 : int; state : int ); cdecl; external{$IFDEF __GPC__}name 'NewtonMaterialSetDefaultCollidable'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonMaterialSetDefaultFriction( const newtonWorld : PNewtonWorld; id0 : int; id1 : int; staticFriction : float; kineticFriction : float ); cdecl; external{$IFDEF __GPC__}name 'NewtonMaterialSetDefaultFriction'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
function NewtonWorldGetFirstMaterial( const NewtonWorld: PNewtonWorld): PNewtonMaterial; cdecl; external{$IFDEF __GPC__}name 'NewtonWorldGetFirstMaterial'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
function NewtonWorldGetNextMaterial( const NewtonWorld: PNewtonWorld; const material : PNewtonMaterial): PNewtonMaterial; cdecl; external{$IFDEF __GPC__}name 'NewtonWorldGetNextMaterial'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0 - These 2 should proberly be moved to the newtonworld section
function NewtonWorldGetFirstBody( const NewtonWorld: PNewtonWorld): PNewtonBody; cdecl; external{$IFDEF __GPC__}name 'NewtonWorldGetFirstBody'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
function NewtonWorldGetNextBody( const NewtonWorld: PNewtonWorld; const curBody : PNewtonBody): PNewtonBody; cdecl; external{$IFDEF __GPC__}name 'NewtonWorldGetNextBody'{$ELSE}NewtonDLL{$ENDIF __GPC__};
// *****************************************************************************************************************************
//
// Physics Contact control functions
//
// *****************************************************************************************************************************
//Removed for 2.0
//procedure NewtonMaterialDisableContact( const material : PNewtonMaterial ); cdecl; external{$IFDEF __GPC__}name 'NewtonMaterialDisableContact'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Removed for 2.0
//function NewtonMaterialGetCurrentTimestep( const material : PNewtonMaterial) : float; cdecl; external{$IFDEF __GPC__}name 'NewtonMaterialGetCurrentTimestep'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonMaterialGetMaterialPairUserData( const material : PNewtonMaterial) : Pointer; cdecl; external{$IFDEF __GPC__}name 'NewtonMaterialGetMaterialPairUserData'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonMaterialGetContactFaceAttribute( const material : PNewtonMaterial) : Unsigned_int; cdecl; external{$IFDEF __GPC__}name 'NewtonMaterialGetContactFaceAttribute'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonMaterialGetBodyCollisionID( const material : PNewtonMaterial; body : PNewtonBody) : Unsigned_int; cdecl; external{$IFDEF __GPC__}name 'NewtonMaterialGetBodyCollisionID'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Updated for 2.0
function NewtonMaterialGetContactNormalSpeed( const material : PNewtonMaterial ) : float; cdecl; external{$IFDEF __GPC__}name 'NewtonMaterialGetContactNormalSpeed'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonMaterialGetContactForce( const material : PNewtonMaterial; force : PFloat); cdecl; external{$IFDEF __GPC__}name 'NewtonMaterialGetContactForce'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonMaterialGetContactPositionAndNormal( const material : PNewtonMaterial; posit : PFloat; normal : PFloat); cdecl; external{$IFDEF __GPC__}name 'NewtonMaterialGetContactPositionAndNormal'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonMaterialGetContactTangentDirections( const material : PNewtonMaterial; dir0 : PFloat; dir : PFloat); cdecl; external{$IFDEF __GPC__}name 'NewtonMaterialGetContactTangentDirections'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Updated for 2.0
function NewtonMaterialGetContactTangentSpeed( const material : PNewtonMaterial; index : int ) : float; cdecl; external{$IFDEF __GPC__}name 'NewtonMaterialGetContactTangentSpeed'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonMaterialSetContactSoftness( const material : PNewtonMaterial; softness : float ); cdecl; external{$IFDEF __GPC__}name 'NewtonMaterialSetContactSoftness'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonMaterialSetContactElasticity( const material : PNewtonMaterial; restitution : float ); cdecl; external{$IFDEF __GPC__}name 'NewtonMaterialSetContactElasticity'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonMaterialSetContactFrictionState( const material : PNewtonMaterial; state : int; index : int ); cdecl; external{$IFDEF __GPC__}name 'NewtonMaterialSetContactFrictionState'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonMaterialSetContactFrictionCoef( const material : PNewtonMaterial; staticFrictionCoef,kineticFrictionCoef : float; index : int ); cdecl; external{$IFDEF __GPC__}name 'NewtonMaterialSetContactStaticFrictionCoef'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonMaterialSetContactNormalAcceleration (const material : PNewtonMaterial; accel : float); cdecl; external{$IFDEF __GPC__}name 'NewtonMaterialSetContactNormalAcceleration'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonMaterialSetContactNormalDirection(const material : PNewtonMaterial; directionVector : PFloat); cdecl; external{$IFDEF __GPC__}name 'NewtonMaterialSetContactNormalDirection'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonMaterialSetContactTangentAcceleration( const material : PNewtonMaterial; accel : float; index : int ); cdecl; external{$IFDEF __GPC__}name 'NewtonMaterialSetContactTangentAcceleration'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonMaterialContactRotateTangentDirections( const material : PNewtonMaterial; const directionVector : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonMaterialContactRotateTangentDirections'{$ELSE}NewtonDLL{$ENDIF __GPC__};
// *****************************************************************************************************************************
//
// convex collision primitives creation functions
//
// *****************************************************************************************************************************
function NewtonCreateNull( const newtonWorld : PNewtonWorld) : PNewtonCollision; cdecl; external{$IFDEF __GPC__}name 'NewtonCreateNull'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonCreateSphere( const newtonWorld : PNewtonWorld; radiusX, radiusY, radiusZ : float; const offsetMatrix : PFloat ) : PNewtonCollision; cdecl; external{$IFDEF __GPC__}name 'NewtonCreateSphere'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonCreateBox( const newtonWorld : PNewtonWorld; dx : float; dy : float; dz : float; const offsetMatrix : PFloat ) : PNewtonCollision; cdecl; external{$IFDEF __GPC__}name 'NewtonCreateBox'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonCreateCone( const newtonWorld : PNewtonWorld; radius : Float; height : Float; const offsetMatrix : PFloat) : PNewtonCollision; cdecl; external{$IFDEF __GPC__}name 'NewtonCreateCone'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonCreateCapsule( const newtonWorld : PNewtonWorld; radius : Float; height : Float; const offsetMatrix : PFloat) : PNewtonCollision; cdecl; external{$IFDEF __GPC__}name 'NewtonCreateCapsule'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonCreateCylinder( const newtonWorld : PNewtonWorld; radius : Float; height : Float; const offsetMatrix : PFloat) : PNewtonCollision; cdecl; external{$IFDEF __GPC__}name 'NewtonCreateCylinder'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonCreateChamferCylinder( const newtonWorld : PNewtonWorld; raduis : Float; height : Float; const offsetMatrix : PFloat) : PNewtonCollision; cdecl; external{$IFDEF __GPC__}name 'NewtonCreateChamferCylinder'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonCreateConvexHull( const newtonWorld : PNewtonWorld; count : int; const vertexCloud : PFloat; strideInBytes : int; const offsetMatrix : PFloat) : PNewtonCollision; cdecl; external{$IFDEF __GPC__}name 'NewtonCreateConvexHull'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
function NewtonCreateConvexHullFromMesh( const newtonWorld : PNewtonWorld; mesh : PNewtonMesh; tolerance : Float) : PNewtonCollision; cdecl; external{$IFDEF __GPC__}name 'NewtonCreateConvexHullFromMesh'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonCreateConvexHullModifier( const newtonWorld : PNewtonWorld; const convexHullCollision : PNewtonCollision): PNewtonCollision; cdecl; external{$IFDEF __GPC__}name 'NewtonCreateConvexHullModifier'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonConvexHullModifierGetMatrix(const convexHullCollision : PNewtonCollision; matrix : PFloat); cdecl; external{$IFDEF __GPC__}name 'NewtonConvexHullModifierGetMatrix'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonConvexHullModifierSetMatrix(const convexHullCollision : PNewtonCollision; const matrix : PFloat); cdecl; external{$IFDEF __GPC__}name 'NewtonConvexHullModifierSetMatrix'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
function NewtonCollisionIsTriggerVolume( const convexCollision : PNewtonCollision): int; cdecl; external{$IFDEF __GPC__}name 'NewtonCollisionIsTriggerVolume'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
procedure NewtonCollisionSetAsTriggerVolume( const convexCollision : PNewtonCollision; trigger : int ); cdecl; external{$IFDEF __GPC__}name 'NewtonCollisionSetAsTriggerVolume'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonConvexCollisionSetUserID( const convexCollision : PNewtonCollision; id : unsigned_int ); cdecl; external{$IFDEF __GPC__}name 'NewtonConvexCollisionSetUserID'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonConvexCollisionGetUserID( const convexCollision : PNewtonCollision) : unsigned_int; cdecl; external{$IFDEF __GPC__}name 'NewtonConvexCollisionGetUserID'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonConvexCollisionCalculateVolume(const convexCollision : PNewtonCollision) : Float; cdecl; external{$IFDEF __GPC__}name 'NewtonConvexCollisionCalculateVolume'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonConvexCollisionCalculateInertialMatrix (const convexCollision : PNewtonCollision; inertia, origin : PFloat); cdecl; external{$IFDEF __GPC__}name 'NewtonConvexCollisionCalculateInertialMatrix'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonCollisionMakeUnique (const newtonWorld : PNewtonWorld; const collision : PNewtonCollision); cdecl; external{$IFDEF __GPC__}name 'NewtonCollisionMakeUnique'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonReleaseCollision( const newtonWorld : PNewtonWorld; const collision : PNewtonCollision ); cdecl; external{$IFDEF __GPC__}name 'NewtonReleaseCollision'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
function NewtonAddCollisionReference( const Collision : PNewtonCollision): int; cdecl; external{$IFDEF __GPC__}name 'NewtonAddCollisionReference'{$ELSE}NewtonDLL{$ENDIF __GPC__};
// *****************************************************************************************************************************
//
// complex collision primitives creation functions
// note: can only be used with static bodies (bodies with infinite mass)
//
// *****************************************************************************************************************************
type
TCollisionPrimitiveArray = array of PNewtonCollision;
function NewtonCreateCompoundCollision( const newtonWorld : PNewtonWorld; count : int;
const collisionPrimitiveArray : TcollisionPrimitiveArray ) : PNewtonCollision; cdecl; external{$IFDEF __GPC__}name 'NewtonCreateCompoundCollision'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
function NewtonCreateCompoundCollisionFromMesh( const newtonWorld : PNewtonWorld; const mesh : PNewtonMesh; concavity : Float; maxShapeCount : int ) : PNewtonCollision; cdecl; external{$IFDEF __GPC__}name 'NewtonCreateCompoundCollisionFromMesh'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Updated for 2.0
function NewtonCreateUserMeshCollision( const newtonWorld : PNewtonWorld; const minBox : PFloat;
const maxBox : PFloat; userData : Pointer; collideCallback : NewtonUserMeshCollisionCollideCallback;
rayHitCallback : NewtonUserMeshCollisionRayHitCallback; destroyCallback : NewtonUserMeshCollisionDestroyCallback;
getInfoCallback : NewtonUserMeshCollisionGetCollisionInfo; facesInAABBCallback : NewtonUserMeshCollisionGetFacesInAABB ) : PNewtonCollision; cdecl; external{$IFDEF __GPC__}name 'NewtonCreateUserMeshCollision'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
function NewtonCreateSceneCollision( const newtonWorld : PNewtonWorld ) : PNewtonCollision; cdecl; external{$IFDEF __GPC__}name 'NewtonCreateSceneCollision'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
function NewtonSceneCollisionCreateProxy( scene : PNewtonCollision; collision : PNewtonCollision ) : PNewtonSceneProxy; cdecl; external{$IFDEF __GPC__}name 'NewtonSceneCollisionCreateProxy'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
procedure NewtonSceneCollisionDestroyProxy( scene : PNewtonCollision; Proxy : PNewtonSceneProxy ); cdecl; external{$IFDEF __GPC__}name 'NewtonSceneCollisionDestroyProxy'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
procedure NewtonSceneProxySetMatrix( Proxy : PNewtonSceneProxy; const Matrix : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonSceneProxySetMatrix'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
procedure NewtonSceneProxyGetMatrix( Proxy : PNewtonSceneProxy; Matrix : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonSceneProxyGetMatrix'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
procedure NewtonSceneCollisionOptimize( scene : PNewtonCollision ); cdecl; external{$IFDEF __GPC__}name 'NewtonSceneCollisionOptimize'{$ELSE}NewtonDLL{$ENDIF __GPC__};
// ***********************************************************************************************************
//
// Collision serialization functions
//
// ***********************************************************************************************************
//Added for 2.0
function NewtonCreateCollisionFromSerialization( const newtonWorld : PNewtonWorld; deserializeFunction : PNewtonDeserialize; serializeHandle : Pointer ) : PNewtonCollision; cdecl; external{$IFDEF __GPC__}name 'NewtonCreateCollisionFromSerialization'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
procedure NewtonCollisionSerialize( const newtonWorld : PNewtonWorld; const collision : PNewtonCollision; serializeFunction : PNewtonSerialize; serializeHandle : Pointer ); cdecl; external{$IFDEF __GPC__}name 'NewtonCollisionSerialize'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
procedure NewtonCollisionGetInfo( const collision : PNewtonCollision; collisionInfo : PNewtonCollisionInfoRecord); cdecl; external{$IFDEF __GPC__}name 'NewtonCollisionGetInfo'{$ELSE}NewtonDLL{$ENDIF __GPC__};
// **********************************************************************************************
//
// Static collision shapes functions
//
// **********************************************************************************************
//Added for 2.0
function NewtonCreateHeightFieldCollision( const newtonWorld : PNewtonWorld; width, height, gridDiagonals : int; elevationMap : PUnsigned_short; attributeMap : P2Char; horizontalScale,verticalScale : Float) : PNewtonCollision; cdecl; external{$IFDEF __GPC__}name 'NewtonCreateHeightFieldCollision'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Updated for 2.0
function NewtonCreateTreeCollision( const newtonWorld : PNewtonWorld ) : PNewtonCollision; cdecl; external{$IFDEF __GPC__}name 'NewtonCreateTreeCollision'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
procedure NewtonTreeCollisionSetUserRayCastCallback( const treeCollision : PNewtonCollision; rayHitCallback : PNewtonCollisionTreeRayCastCallback ); cdecl; external{$IFDEF __GPC__}name 'NewtonTreeCollisionSetUserRayCastCallback'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonTreeCollisionBeginBuild( const treeCollision : PNewtonCollision ); cdecl; external{$IFDEF __GPC__}name 'NewtonTreeCollisionBeginBuild'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonTreeCollisionAddFace( const treeCollision : PNewtonCollision; vertexCount : int; const vertexPtr : PFloat;
strideInBytes : int; faceAttribute : int ); cdecl; external{$IFDEF __GPC__}name 'NewtonTreeCollisionAddFace'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonTreeCollisionEndBuild( const treeCollision : PNewtonCollision; optimize : int ); cdecl; external{$IFDEF __GPC__}name 'NewtonTreeCollisionEndBuild'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonTreeCollisionGetFaceAtribute( const treeCollision : PNewtonCollision; const faceIndexArray : Pint ) : int; cdecl; external{$IFDEF __GPC__}name 'NewtonTreeCollisionGetFaceAtribute'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonTreeCollisionSetFaceAtribute( const treeCollision : PNewtonCollision; const faceIndexArray : Pint;
attribute : int ); cdecl; external{$IFDEF __GPC__}name 'NewtonTreeCollisionSetFaceAtribute'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
function NewtonTreeCollisionGetVertexListIndexListInAABB( const treeCollision : PNewtonCollision; const p0, p1 : PFloat; const vertexArray : PFloat; vertexCount,vertexStrideInBytes : PInt; const indexList : PInt; maxIndexCount : Int; const faceAttribute : PInt ) : int; cdecl; external{$IFDEF __GPC__}name 'NewtonTreeCollisionGetVertexListIndexListInAABB'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
procedure NewtonStaticCollisionSetDebugCallback( const staticCollision : PNewtonCollision; userCallback : PNewtonTreeCollisionCallback ); cdecl; external{$IFDEF __GPC__}name 'NewtonStaticCollisionSetDebugCallback'{$ELSE}NewtonDLL{$ENDIF __GPC__};
// *****************************************************************************************************************************
//
// General purpose collision library functions
//
// *****************************************************************************************************************************
//Updated for 2.0
function NewtonCollisionPointDistance (const newtonWorld : PNewtonWorld; const point : PFloat;
const collision : PNewtonCollision; const matrix : PFloat; contact : PFloat; normal : PFloat; threadIndex : int) : Int;
cdecl; external{$IFDEF __GPC__}name 'NewtonCollisionPointDistance'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Updated for 2.0
function NewtonCollisionClosestPoint (const newtonWorld : PNewtonWorld; const collsionA : PNewtonCollision;
const matrixA : PFloat; const collisionB : PNewtonCollision; const matrixB : PFloat;
contactA, contactB, normalAB : PFloat; threadIndex : int) : Int;
cdecl; external{$IFDEF __GPC__}name 'NewtonCollisionClosestPoint'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Updated for 2.0
function NewtonCollisionCollide (const newtonWorld : PNewtonWorld; maxSize : Int; const collsionA : PNewtonCollision;
const matrixA : PFloat; const collisionB : PNewtonCollision; const matrixB : PFloat;
contacts, normals, penetration : PFloat; threadIndex : int) : Int;
cdecl; external{$IFDEF __GPC__}name 'NewtonCollisionCollide'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Updated for 2.0
function NewtonCollisionCollideContinue (const newtonWorld : PNewtonWorld; maxSize : Int; const timestep : Float;
const collsionA : PNewtonCollision; const matrixA : PFloat; const velocA : PFloat; const omegaA : Float;
const collsionB : PNewtonCollision; const matrixB : PFloat; const velocB : PFloat; const omegaB : Float;
timeOfImpact : PFloat; contacts : PFloat; normals : PFloat; penetration : PFloat; threadIndex : int) : Int;
cdecl; external{$IFDEF __GPC__}name 'NewtonCollisionCollideContinue'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
procedure NewtonCollisionSupportVertex( const collision : PNewtonCollision; const dir : PFloat; vertex : PFloat); cdecl; external{$IFDEF __GPC__}name 'NewtonCollisionSupportVertex'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonCollisionRayCast(const collision : PNewtonCollision; const p0: PFloat; const p1: PFloat; normals: PFloat; attribute: pint): float; cdecl; external{$IFDEF __GPC__}name 'NewtonCollisionRayCast'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonCollisionCalculateAABB( const collision : PNewtonCollision; const matrix : PFloat; p0 : PFloat; p1 : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonCollisionCalculateAABB'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonCollisionForEachPolygonDo (const collision : PNewtonCollision; const matrix : PFloat; callback : NewtonCollisionIterator; UserData : Pointer);cdecl; external{$IFDEF __GPC__}name 'NewtonReleaseCollision'{$ELSE}NewtonDLL{$ENDIF __GPC__};
// *****************************************************************************************************************************
//
// transforms utility functions
//
// *****************************************************************************************************************************
procedure NewtonGetEulerAngle( const matrix : PFloat; eulersAngles : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonGetEulerAngle'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonSetEulerAngle( const eulersAngles : PFloat; matrix : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonSetEulerAngle'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
function NewtonCalculateSpringDamperAcceleration(dt, ks, x, kd, s : Float): float; cdecl; external{$IFDEF __GPC__}name 'NewtonCalculateSpringDamperAcceleration'{$ELSE}NewtonDLL{$ENDIF __GPC__};
// *****************************************************************************************************************************
//
// body manipulation functions
//
// *****************************************************************************************************************************
function NewtonCreateBody( const newtonWorld : PNewtonWorld; const collision : PNewtonCollision ) : PNewtonBody; cdecl; external{$IFDEF __GPC__}name 'NewtonCreateBody'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonDestroyBody( const newtonWorld : PNewtonWorld; const body : PNewtonBody ); cdecl; external{$IFDEF __GPC__}name 'NewtonDestroyBody'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBodyAddForce( const body : PNewtonBody; const force : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodyAddForce'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBodyAddTorque( const body : PNewtonBody; const torque : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodyAddTorque'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
procedure NewtonBodyCalculateInverseDynamicsForce( const body : PNewtonBody; timestep : Float; const desiredVeloc : PFloat; forceOut : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodyCalculateInverseDynamicsForce'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBodySetMatrix( const body : PNewtonBody; const matrix : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodySetMatrix'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBodySetMatrixRecursive( const body : PNewtonBody; const matrix : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodySetMatrixRecursive'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBodySetMassMatrix( const body : PNewtonBody; mass : float; Ixx : float; Iyy : float; Izz : float ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodySetMassMatrix'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBodySetMaterialGroupID( const body : PNewtonBody; id : int ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodySetMaterialGroupID'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBodySetContinuousCollisionMode(const body : PNewtonbody; state : unsigned_int); cdecl; external{$IFDEF __GPC__}name 'NewtonBodySetContinuousCollisionMode'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBodySetJointRecursiveCollision( const body : PNewtonBody; state : unsigned_int ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodySetJointRecursiveCollision'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBodySetOmega( const body : PNewtonBody; const omega : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodySetOmega'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBodySetVelocity( const body : PNewtonBody; const velocity : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodySetVelocity'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBodySetForce( const body : PNewtonBody; const force : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodySetForce'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBodySetTorque( const body : PNewtonBody; const torque : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodySetTorque'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBodySetCentreOfMass(const body : PNewtonBody; const com : PFloat); cdecl; external{$IFDEF __GPC__}name 'NewtonBodySetCentreOfMass'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBodySetLinearDamping( const body : PNewtonBody; linearDamp : float ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodySetLinearDamping'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBodySetAngularDamping( const body : PNewtonBody; const angularDamp : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodySetAngularDamping'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBodySetUserData( const body : PNewtonBody; userData : Pointer ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodySetUserData'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Removed for 2.0
//procedure NewtonBodyCoriolisForcesMode( const body : PNewtonBody; mode : int); cdecl; external{$IFDEF __GPC__}name 'NewtonBodyCoriolisForcesMode'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBodySetCollision( const body : PNewtonBody; const collision : PNewtonCollision ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodySetCollision'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Removed for 2.0
//procedure NewtonBodySetAutoFreeze( const body : PNewtonBody; state : int ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodySetAutoFreeze'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Removed for 2.0
//procedure NewtonBodySetFreezeTreshold( const body : PNewtonBody; freezeSpeed2 : float; freezeOmega2 : float; framesCount : int ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodySetFreezeTreshold'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Updated for 2.0
function NewtonBodyGetSleepState( const body : PNewtonBody) : Int; cdecl; external{$IFDEF __GPC__}name 'NewtonBodyGetSleepState'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
function NewtonBodyGetAutoSleep( const body : PNewtonBody) : Int; cdecl; external{$IFDEF __GPC__}name 'NewtonBodyGetAutoSleep'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
procedure NewtonBodySetAutoSleep( const body : PNewtonBody; state : int ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodySetAutoSleep'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
function NewtonBodyGetFreezeState( const body : PNewtonBody) : Int; cdecl; external{$IFDEF __GPC__}name 'NewtonBodyGetFreezeState'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
procedure NewtonBodySetFreezeState( const body : PNewtonBody; state : int ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodySetFreezeState'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBodySetTransformCallback( const body : PNewtonBody; callback : NewtonSetTransform ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodySetTransformCallback'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBodySetDestructorCallback( const body : PNewtonBody; callback : NewtonBodyDestructor ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodySetDestructorCallback'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Removed for 2.0
//procedure NewtonBodySetAutoactiveCallback( const body : PNewtonBody; callback : NewtonBodyActivationState ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodySetAutoactiveCallback'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBodySetForceAndTorqueCallback( const body : PNewtonBody; callback : NewtonApplyForceAndTorque ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodySetForceAndTorqueCallback'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonBodyGetForceAndTorqueCallback( const body : PNewtonBody ): NewtonApplyForceAndTorque; cdecl; external{$IFDEF __GPC__}name 'NewtonBodyGetForceAndTorqueCallback'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonBodyGetUserData( const body : PNewtonBody ) : Pointer; cdecl; external{$IFDEF __GPC__}name 'NewtonBodyGetUserData'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonBodyGetWorld( const body : PNewtonBody) : PNewtonWorld; cdecl; external{$IFDEF __GPC__}name 'NewtonBodyGetWorld'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonBodyGetCollision( const body : PNewtonBody ) : PNewtonCollision; cdecl; external{$IFDEF __GPC__}name 'NewtonBodyGetCollision'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonBodyGetMaterialGroupID( const body : PNewtonBody ) : Int; cdecl; external{$IFDEF __GPC__}name 'NewtonBodyGetMaterialGroupID'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonBodyGetContinuousCollisionMode( const body : PNewtonBody ) : Int; cdecl; external{$IFDEF __GPC__}name 'NewtonBodyGetContinuousCollisionMode'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonBodyGetJointRecursiveCollision( const body : PNewtonBody ) : Int; cdecl; external{$IFDEF __GPC__}name 'NewtonBodyGetJointRecursiveCollision'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBodyGetMatrix( const body : PNewtonBody; matrix : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodyGetMatrix'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
procedure NewtonBodyGetRotation( const body : PNewtonBody; rotation : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodyGetRotation'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBodyGetMassMatrix( const body : PNewtonBody; mass : PFloat; Ixx : PFloat; Iyy : PFloat; Izz : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodyGetMassMatrix'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBodyGetInvMass( const body : PNewtonBody; invMass : PFloat; invIxx : PFloat; invIyy : PFloat; invIzz : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodyGetInvMass'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBodyGetOmega( const body : PNewtonBody; vector : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodyGetOmega'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBodyGetVelocity( const body : PNewtonBody; vector : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodyGetVelocity'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBodyGetForce( const body : PNewtonBody; vector : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodyGetForce'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBodyGetTorque( const body : PNewtonBody; vector : PFloat); cdecl; external{$IFDEF __GPC__}name 'NewtonBodyGetTorque'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
procedure NewtonBodyGetForceAcc( const body : PNewtonBody; vector : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodyGetForceAcc'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Added for 2.0
procedure NewtonBodyGetTorqueAcc( const body : PNewtonBody; vector : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodyGetTorqueAcc'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBodyGetCentreOfMass(const body : PNewtonBody; com : PFloat); cdecl; external{$IFDEF __GPC__}name 'NewtonBodyGetCentreOfMass'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Removed for 2.0
//function NewtonBodyGetAutoFreeze( const body : PNewtonBody ) : Int; cdecl; external{$IFDEF __GPC__}name 'NewtonBodyGetAutoFreeze'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonBodyGetLinearDamping( const body : PNewtonBody ) : float; cdecl; external{$IFDEF __GPC__}name 'NewtonBodyGetLinearDamping'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBodyGetAngularDamping( const body : PNewtonBody; vector : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodyGetAngularDamping'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBodyGetAABB( const body : PNewtonBody; p0 : PFloat; p1 : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodyGetAABB'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Removed for 2.0
procedure NewtonBodyGetFreezeTreshold( const body : PNewtonBody; freezeSpeed2 : PFloat; freezeOmega2 : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodyGetFreezeTreshold'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonBodyGetFirstJoint( const body : PNewtonBody ) : PNewtonJoint; cdecl; external{$IFDEF __GPC__}name 'NewtonBodyGetFirstJoint'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonBodyGetNextJoint( const body : PNewtonBody; const joint : PNewtonJoint ) : PNewtonJoint; cdecl; external{$IFDEF __GPC__}name 'NewtonBodyGetNextJoint'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonBodyGetFirstContactJoint( const body : PNewtonBody ) : PNewtonJoint; cdecl; external{$IFDEF __GPC__}name 'NewtonBodyGetFirstContactJoint'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonBodyGetNextContactJoint( const body : PNewtonBody; const contactJoint : PNewtonJoint ) : PNewtonJoint; cdecl; external{$IFDEF __GPC__}name 'NewtonBodyGetNextContactJoint'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonContactJointGetFirstContact( const contactJoint : PNewtonJoint ) : Pointer; cdecl; external{$IFDEF __GPC__}name 'NewtonContactJointGetFirstContact'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonContactJointGetNextContact( const contactJoint : PNewtonJoint; contact : Pointer ) : Pointer; cdecl; external{$IFDEF __GPC__}name 'NewtonContactJointGetNextContact'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonContactJointGetContactCount( const contactJoint : PNewtonJoint ) : int; cdecl; external{$IFDEF __GPC__}name 'NewtonContactJointGetContactCount'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonContactJointRemoveContact( const contactJoint : PNewtonJoint; contact : Pointer ); cdecl; external{$IFDEF __GPC__}name 'NewtonContactJointRemoveContact'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonContactGetMaterial( const contact : Pointer ) : PNewtonMaterial; cdecl; external{$IFDEF __GPC__}name 'NewtonContactGetMaterial'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBodyAddBuoyancyForce( const body : PNewtonBody; fluidDensity : float; fluidLinearViscosity : float; fluidAngularViscosity : float;
const gravityVector : PFloat; buoyancyPlane : NewtonGetBuoyancyPlane; context : Pointer ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodyAddBuoyancyForce'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//procedure NewtonBodyForEachPolygonDo( const body : PNewtonBody; callback : NewtonCollisionIterator ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodyForEachPolygonDo'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBodyAddImpulse(const body : PNewtonBody; const pointDeltaVeloc : PFloat; const pointPosit : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonBodyAddImpulse'{$ELSE}NewtonDLL{$ENDIF __GPC__};
// *****************************************************************************************************************************
//
// Common joint funtions
//
// *****************************************************************************************************************************
function NewtonJointGetUserData( const joint : PNewtonJoint ) : Pointer; cdecl; external{$IFDEF __GPC__}name 'NewtonJointGetUserData'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonJointSetUserData( const joint : PNewtonJoint; userData : Pointer ); cdecl; external{$IFDEF __GPC__}name 'NewtonJointSetUserData'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonJointGetBody0( const joint : PNewtonJoint ) : PNewtonBody; cdecl; external{$IFDEF __GPC__}name 'NewtonJointGetBody0'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonJointGetBody1( const joint : PNewtonJoint ) : PNewtonBody; cdecl; external{$IFDEF __GPC__}name 'NewtonJointGetBody1'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonJointGetInfo( const joint : PNewtonJoint; info : PNewtonJointRecord ); cdecl; external{$IFDEF __GPC__}name 'NewtonJointGetInfo'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonJointGetCollisionState( const joint : PNewtonJoint ) : int; cdecl; external{$IFDEF __GPC__}name 'NewtonJointGetCollisionState'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonJointSetCollisionState( const joint : PNewtonJoint; state : int ); cdecl; external{$IFDEF __GPC__}name 'NewtonJointSetCollisionState'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonJointGetStiffness( const joint : PNewtonJoint): float; cdecl; external{$IFDEF __GPC__}name 'NewtonJointGetStiffness'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonJointSetStiffness( const joint: PNewtonJoint; state: float); cdecl; external{$IFDEF __GPC__}name 'NewtonJointSetStiffness'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonDestroyJoint( const newtonWorld : PNewtonWorld; const joint : PNewtonJoint ); cdecl; external{$IFDEF __GPC__}name 'NewtonDestroyJoint'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonJointSetDestructor( const joint : PNewtonJoint; _destructor : NewtonConstraintDestructor ); cdecl; external{$IFDEF __GPC__}name 'NewtonJointSetDestructor'{$ELSE}NewtonDLL{$ENDIF __GPC__};
// *****************************************************************************************************************************
//
// Ball and Socket joint functions
//
// *****************************************************************************************************************************
function NewtonConstraintCreateBall( const newtonWorld : PNewtonWorld; const pivotPoint : PFloat;
const childBody : PNewtonBody; const parentBody : PNewtonBody ) : PNewtonJoint; cdecl; external{$IFDEF __GPC__}name 'NewtonConstraintCreateBall'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBallSetUserCallback( const ball : PNewtonJoint; callback : NewtonBallCallBack ); cdecl; external{$IFDEF __GPC__}name 'NewtonBallSetUserCallback'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBallGetJointAngle( const ball : PNewtonJoint; angle : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonBallGetJointAngle'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBallGetJointOmega( const ball : PNewtonJoint; omega : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonBallGetJointOmega'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBallGetJointForce( const ball : PNewtonJoint; force : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonBallGetJointForce'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonBallSetConeLimits( const ball : PNewtonJoint; const pin : PFloat; maxConeAngle : float; maxTwistAngle : float ); cdecl; external{$IFDEF __GPC__}name 'NewtonBallSetConeLimits'{$ELSE}NewtonDLL{$ENDIF __GPC__};
// *****************************************************************************************************************************
//
// Hinge joint functions
//
// *****************************************************************************************************************************
function NewtonConstraintCreateHinge( const newtonWorld : PNewtonWorld;
const pivotPoint : PFloat; const pinDir : PFloat;
const childBody : PNewtonBody; const parentBody : PNewtonBody ) : PNewtonJoint; cdecl; external{$IFDEF __GPC__}name 'NewtonConstraintCreateHinge'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonHingeSetUserCallback( const hinge : PNewtonJoint; callback : NewtonHingeCallBack ); cdecl; external{$IFDEF __GPC__}name 'NewtonHingeSetUserCallback'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonHingeGetJointAngle( const hinge : PNewtonJoint ) : float; cdecl; external{$IFDEF __GPC__}name 'NewtonHingeGetJointAngle'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonHingeGetJointOmega( const hinge : PNewtonJoint ) : float; cdecl; external{$IFDEF __GPC__}name 'NewtonHingeGetJointOmega'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonHingeGetJointForce( const hinge : PNewtonJoint; force : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonHingeGetJointForce'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonHingeCalculateStopAlpha( const hinge : PNewtonJoint; const desc : PNewtonHingeSliderUpdateDesc; angle : float ) : float; cdecl; external{$IFDEF __GPC__}name 'NewtonHingeCalculateStopAlpha'{$ELSE}NewtonDLL{$ENDIF __GPC__};
// *****************************************************************************************************************************
//
// Slider joint functions
//
// *****************************************************************************************************************************
function NewtonConstraintCreateSlider( const newtonWorld : PNewtonWorld;
const pivotPoint : PFloat; const pinDir : PFloat;
const childBody : PNewtonBody; const parentBody : PNewtonBody ) : PNewtonJoint; cdecl; external{$IFDEF __GPC__}name 'NewtonConstraintCreateSlider'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonSliderSetUserCallback( const slider : PNewtonJoint; callback : NewtonSliderCallBack ); cdecl; external{$IFDEF __GPC__}name 'NewtonSliderSetUserCallback'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonSliderGetJointPosit( const slider : PNewtonJoint ) : float; cdecl; external{$IFDEF __GPC__}name 'NewtonSliderGetJointPosit'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonSliderGetJointVeloc( const slider : PNewtonJoint ) : float; cdecl; external{$IFDEF __GPC__}name 'NewtonSliderGetJointVeloc'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonSliderGetJointForce( const slider : PNewtonJoint; force : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonSliderGetJointForce'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonSliderCalculateStopAccel( const slider : PNewtonJoint; const desc : PNewtonHingeSliderUpdateDesc; position : float ) : float; cdecl; external{$IFDEF __GPC__}name 'NewtonSliderCalculateStopAccel'{$ELSE}NewtonDLL{$ENDIF __GPC__};
// *****************************************************************************************************************************
//
// Corkscrew joint functions
//
// *****************************************************************************************************************************
function NewtonConstraintCreateCorkscrew( const newtonWorld : PNewtonWorld;
const pivotPoint : PFloat; const pinDir : PFloat;
const childBody : PNewtonBody; const parentBody : PNewtonBody ) : PNewtonJoint; cdecl; external{$IFDEF __GPC__}name 'NewtonConstraintCreateCorkscrew'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonCorkscrewSetUserCallback( const corkscrew : PNewtonJoint; callback : NewtonCorkscrewCallBack ); cdecl; external{$IFDEF __GPC__}name 'NewtonCorkscrewSetUserCallback'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonCorkscrewGetJointPosit( const corkscrew : PNewtonJoint ) : float; cdecl; external{$IFDEF __GPC__}name 'NewtonCorkscrewGetJointPosit'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonCorkscrewGetJointAngle( const corkscrew : PNewtonJoint ) : float; cdecl; external{$IFDEF __GPC__}name 'NewtonCorkscrewGetJointAngle'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonCorkscrewGetJointVeloc( const corkscrew : PNewtonJoint ) : float; cdecl; external{$IFDEF __GPC__}name 'NewtonCorkscrewGetJointVeloc'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonCorkscrewGetJointOmega( const corkscrew : PNewtonJoint ) : float; cdecl; external{$IFDEF __GPC__}name 'NewtonCorkscrewGetJointOmega'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonCorkscrewGetJointForce( const corkscrew : PNewtonJoint; force : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonCorkscrewGetJointForce'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonCorkscrewCalculateStopAlpha( const corkscrew : PNewtonJoint; const desc : PNewtonHingeSliderUpdateDesc; angle : float ) : float; cdecl; external{$IFDEF __GPC__}name 'NewtonCorkscrewCalculateStopAlpha'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonCorkscrewCalculateStopAccel( const corkscrew : PNewtonJoint; const desc : PNewtonHingeSliderUpdateDesc; position : float ) : float; cdecl; external{$IFDEF __GPC__}name 'NewtonCorkscrewCalculateStopAccel'{$ELSE}NewtonDLL{$ENDIF __GPC__};
// *****************************************************************************************************************************
//
// Universal joint functions
//
// *****************************************************************************************************************************
function NewtonConstraintCreateUniversal( const newtonWorld: PNewtonWorld; const pivotPoint: PFloat; const pinDir0: PFloat;
const pinDir1: PFloat; const childBody: PNewtonBody; const parentBody: PNewtonBody): PNewtonJoint; cdecl; external{$IFDEF __GPC__}name 'NewtonConstraintCreateUniversal'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonUniversalSetUserCallback(const universal: PNewtonJoint; callback: NewtonUniversalCallback); cdecl; external{$IFDEF __GPC__}name 'NewtonUniversalSetUserCallback'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonUniversalGetJointAngle0(const universal: PNewtonJoint):float; cdecl; external{$IFDEF __GPC__}name 'NewtonUniversalGetJointAngle0'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonUniversalGetJointAngle1(const universal: PNewtonJoint):float; cdecl; external{$IFDEF __GPC__}name 'NewtonUniversalGetJointAngle1'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonUniversalGetJointOmega0(const universal: PNewtonJoint):float; cdecl; external{$IFDEF __GPC__}name 'NewtonUniversalGetJointOmega0'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonUniversalGetJointOmega1(const universal: PNewtonJoint):float; cdecl; external{$IFDEF __GPC__}name 'NewtonUniversalGetJointOmega1'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonUniversalGetJointForce(const universal: PNewtonJoint; force: PFloat); cdecl; external{$IFDEF __GPC__}name 'NewtonUniversalGetJointForce'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonUniversalCalculateStopAlpha0(const universal : PNewtonJoint; const desc: PNewtonHingeSliderUpdateDesc; angle: float): float; cdecl; external{$IFDEF __GPC__}name 'NewtonUniversalCalculateStopAlpha0'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonUniversalCalculateStopAlpha1(const universal : PNewtonJoint; const desc: PNewtonHingeSliderUpdateDesc; angle: float): float; cdecl; external{$IFDEF __GPC__}name 'NewtonUniversalCalculateStopAlpha1'{$ELSE}NewtonDLL{$ENDIF __GPC__};
// *****************************************************************************************************************************
//
// Up vector joint unctions
//
// *****************************************************************************************************************************
function NewtonConstraintCreateUpVector( const newtonWorld : PNewtonWorld; const pinDir : PFloat; const body : PNewtonBody ) : PNewtonJoint; cdecl; external{$IFDEF __GPC__}name 'NewtonConstraintCreateUpVector'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonUpVectorGetPin( const upVector : PNewtonJoint; pin : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonUpVectorGetPin'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonUpVectorSetPin( const upVector : PNewtonJoint; const pin : PFloat ); cdecl; external{$IFDEF __GPC__}name 'NewtonUpVectorSetPin'{$ELSE}NewtonDLL{$ENDIF __GPC__};
// *****************************************************************************************************************************
//
// User defined bilateral Joint
//
// *****************************************************************************************************************************
function NewtonConstraintCreateUserJoint(const NewtonWorld : PNewtonWorld; MaxDOF : Integer; Callback : PNewtonUserBilateralCallBack;
const ChildBody: PNewtonBody; const parentBody: PNewtonBody): PNewtonJoint;
cdecl; external{$IFDEF __GPC__}name 'NewtonConstraintCreateUserJoint'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonUserJointAddLinearRow(const Joint : PNewtonJoint; const pivot0 : PFloat; const pivot1 : PFloat; const Dir : PFloat); cdecl; external{$IFDEF __GPC__}name 'NewtonUserJointAddLinearRow'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonUserJointAddAngularRow(const Joint : PNewtonJoint; RelativeAngle : Float; const Dir : PFloat); cdecl; external{$IFDEF __GPC__}name 'NewtonUserJointAddAngularRow'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonUserJointAddGeneralRow(const Joint : PNewtonJoint; const Jacobian0 : PFloat; const Jacobian1 : PFloat); cdecl; external{$IFDEF __GPC__}name 'NewtonUserJointAddGeneralRow'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonUserJointSetRowMinimumFriction(const Joint : PNewtonJoint; Friction : Float); cdecl; external{$IFDEF __GPC__}name 'NewtonUserJointSetRowMinimumFriction'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonUserJointSetRowMaximumFriction(const Joint : PNewtonJoint; Friction : Float); cdecl; external{$IFDEF __GPC__}name 'NewtonUserJointSetRowMaximumFriction'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonUserJointSetRowAcceleration(const Joint : PNewtonJoint; Acceleration : Float); cdecl; external{$IFDEF __GPC__}name 'NewtonUserJointSetRowAcceleration'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonUserJointSetRowSpringDamperAcceleration(const joint : PNewtonJoint; springK : Float; springD : Float); cdecl; external{$IFDEF __GPC__}name 'NewtonUserJointSetRowSpringDamperAcceleration'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonUserJointSetRowStiffness(const Joint : PNewtonJoint; Stiffness : Float); cdecl; external{$IFDEF __GPC__}name 'NewtonUserJointSetRowStiffness'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonUserJointGetRowForce (const Joint : PNewtonJoint; Row : Int) : Float; cdecl; external{$IFDEF __GPC__}name 'NewtonUserJointGetRowForce'{$ELSE}NewtonDLL{$ENDIF __GPC__};
// **********************************************************************************************
//
// Mesh joint functions
//
// **********************************************************************************************
//Added Mesh joint functions for 2.0
function NewtonMeshCreate () : PNewtonMesh; cdecl; external{$IFDEF __GPC__}name 'NewtonMeshCreate'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonMeshCreateFromCollision (const collision : PNewtonCollision) : PNewtonMesh; cdecl; external{$IFDEF __GPC__}name 'NewtonMeshCreateFromCollision'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonMeshDestroy(const mesh : PNewtonMesh); cdecl; external{$IFDEF __GPC__}name 'NewtonMeshDestroy'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonMeshCalculateVertexNormals(const mesh : PNewtonMesh; angleInRadians : Float); cdecl; external{$IFDEF __GPC__}name 'NewtonMeshCalculateVertexNormals'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonMeshApplySphericalMapping(const mesh : PNewtonMesh; material : int); cdecl; external{$IFDEF __GPC__}name 'NewtonMeshApplySphericalMapping'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonMeshApplyBoxMapping(const mesh : PNewtonMesh; front,side,top : int); cdecl; external{$IFDEF __GPC__}name 'NewtonMeshApplyBoxMapping'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonMeshApplyCylindricalMapping(const mesh : PNewtonMesh; cylinderMaterial,capMaterial : int); cdecl; external{$IFDEF __GPC__}name 'NewtonMeshApplyCylindricalMapping'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonMeshPlaneClip (const mesh : PNewtonMesh; const plane : PFloat; const textureProjectionMatrix : PFloat; meshOut : PNewtonMesh; maxMeshCount,capMaterial : int) : int; cdecl; external{$IFDEF __GPC__}name 'NewtonMeshPlaneClip'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonMeshBeginFace(const mesh : PNewtonMesh); cdecl; external{$IFDEF __GPC__}name 'NewtonMeshBeginFace'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonMeshAddFace(const mesh : PNewtonMesh; vertexCount : int; const vertex : PFloat; strideInBytes,materialIndex : int ); cdecl; external{$IFDEF __GPC__}name 'NewtonMeshAddFace'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonMeshEndFace(const mesh : PNewtonMesh); cdecl; external{$IFDEF __GPC__}name 'NewtonMeshEndFace'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonMeshGetVertexCount (const mesh : PNewtonMesh) : int; cdecl; external{$IFDEF __GPC__}name 'NewtonMeshGetVertexCount'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonMeshGetVertexStreams(const mesh : PNewtonMesh; vertexStrideInByte : int; vertex : PFloat; normalStrideInByte : int; normal : PFloat; uvStrideInByte : int; uv : PFloat); cdecl; external{$IFDEF __GPC__}name 'NewtonMeshGetVertexStreams'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonMeshGetIndirectVertexStreams(const mesh : PNewtonMesh; vertexStrideInByte : int; vertex : PFloat; vertexIndices : PInt; vertexCount : PInt; normalStrideInByte : int; normal : PFloat; normalIndices : PInt; normalCount : PInt; uvStrideInByte : int; uv : PFloat; uvIndices : PInt; uvCount : PInt); cdecl; external{$IFDEF __GPC__}name 'NewtonMeshGetIndirectVertexStreams'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonMeshFirstMaterial (const mesh : PNewtonMesh) : int; cdecl; external{$IFDEF __GPC__}name 'NewtonMeshFirstMaterial'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonMeshNextMaterial (const mesh : PNewtonMesh; materialHandle : int) : int; cdecl; external{$IFDEF __GPC__}name 'NewtonMeshNextMaterial'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonMeshMaterialGetMaterial (const mesh : PNewtonMesh; materialHandle : int) : int; cdecl; external{$IFDEF __GPC__}name 'NewtonMeshMaterialGetMaterial'{$ELSE}NewtonDLL{$ENDIF __GPC__};
function NewtonMeshMaterialGetIndexCount (const mesh : PNewtonMesh; materialHandle : int) : int; cdecl; external{$IFDEF __GPC__}name 'NewtonMeshMaterialGetIndexCount'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonMeshMaterialGetIndexStream(const mesh : PNewtonMesh; materialHandle : int; index : PInt); cdecl; external{$IFDEF __GPC__}name 'NewtonMeshMaterialGetIndexStream'{$ELSE}NewtonDLL{$ENDIF __GPC__};
procedure NewtonMeshMaterialGetIndexStreamShort(const mesh : PNewtonMesh; materialHandle : int; index : PShort); cdecl; external{$IFDEF __GPC__}name 'NewtonMeshMaterialGetIndexStreamShort'{$ELSE}NewtonDLL{$ENDIF __GPC__};
//Removed Ragdoll & Vehicle procedures/functions for 2.0
implementation
end. |
(*
Category: SWAG Title: ANYTHING NOT OTHERWISE CLASSIFIED
Original name: 0159.PAS
Description: approx phase of the moon
Author: TIM MIDDLETON
Date: 09-04-95 10:53
*)
program moondays;
uses dos;
{----------------------------------------------------------------------}
{-- Calculate Approxmiate Phase of the Moon: --}
{----------------------------------------------------------------------}
{-- Uses formula by P. Harvey in the "Journal of the British --}
{-- Astronomical Association", July 1941. Formula is accurate to --}
{-- within one day (or on some occassions two days). If anyone knows --}
{-- a better formula please let me know! Internet: as544@torfree.net --}
{----------------------------------------------------------------------}
{-- Calculates number of days since the new moon where: --}
{-- 0 = New moon 15 = Full Moon --}
{-- 7 = First Quarter 22 = Last Quarter (right half dark) --}
{----------------------------------------------------------------------}
Function Moon_age(y : word; m : word; d : word) : byte;
var i : integer;
c : word;
begin
c:=(y div 100);
if (m>2) then dec(m,2) else inc(m,10);
i:=((((((y mod 19)*11)+(c div 3)+(c div 4)+8)-c)+m+d) mod 30);
moon_age:=i;
end;
{----------------------------------------------------------------------}
{-- Enable Dos redirection: --}
{----------------------------------------------------------------------}
Procedure DosRedirect;
begin
ASSIGN(Input,'');RESET(Input);
ASSIGN(Output,'');REWRITE(Output);
end;
{**********************************************************************}
{**********************************************************************}
var
ty, tm, td, tdow : word;
BEGIN
DosRedirect;
Getdate(ty,tm,td,tdow);
WriteLn('Today is the day ',td,' in the month ',tm,
' and the year ',ty);
tdow := Moon_age(ty,tm,td);
Write('The moon is ',tdow,' day');
if tdow<>1 then write('s');
write(' old.');
case tdow of
0 : Write(' New moon!');
7 : Write(' First Quater!');
15: Write(' Full moon!');
22: Write(' Last Quarter!');
end;
writeln;
END.
|
(*
* Various helpers and data types to deal with the DNS protocol
*
* Overview of DNS protocol: http://www.zytrax.com/books/dns/ch15/
*)
unit DNSProtocol;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, StrUtils;
type
TTwoByte = Array [0..1] of Byte; // TODO: Rename to T16Bit
T32Bit = Array [0..3] of Byte;
TByteString = Array of Byte;
TIPv4Addr = Array [0..3] of Byte;
(*
* Request message header data structure
* 12 Bytes
*)
TDNSRequestHeader = record
MessageID: TTwoByte; // Message ID. Has to be sent back
Flags: TTwoByte; // Flags, 1 bit must turned on
QDCount: TTwoByte; // Question count (1)
ANCount: TTwoByte; // Answer count (1)
NSCount: TTwoByte; // Name server count (0)
ARCount: TTwoByte; // Additional records count (0)
end;
(*
* Request question data structure
* n + 4 Bytes
*)
TDNSRequestQuestion = record
QName: TByteString; // ! m y d o m a i n ! c o m \0 (! == 2 length bytes)
QType: TTwoByte; // The RR type, for example, SOA or AAAA
QClass: TTwoByte; // The RR class, for instance, Internet, Chaos etc.
end;
(*
* Response data structure
*
*)
TDNSRequestAnswer = record
Header: TDNSRequestHeader;
Question: TDNSRequestQuestion;
QNamePtr: TTwoByte; // (2 byte pointer to question section) The name being returned e.g. www or ns1.example.net If the name is in the same domain as the question then typically only the host part (label) is returned, if not then a FQDN is returned.
QType: TTwoByte; // The RR type, for example, SOA or AAAA
QClass: TTwoByte; // The RR class, for instance, Internet, Chaos etc.
TTL: T32Bit; // The TTL in seconds of the RR, say, 2800
RLength: TTwoByte; // The length of RR specific data in octets, for example, 27
RData: TIPv4Addr; // The RR specific data (see Binary RR Formats below) whose length is defined by RDLENGTH, for instance, 192.168.254.2
end;
(*
* Forward declarations
*)
procedure Reverse( var a: Array of Byte );
function IntToTwoBytes( Int : Integer ): TTwoByte;
function IntTo32Bit( Int : Integer ): T32Bit;
function QNameToDomainString( var QName: TByteString ): String;
function GetRequestHeader( Request: TStream ): TDNSRequestHeader;
function GetRequestQuestion( Request: TStream ): TDNSRequestQuestion;
function GetRequestAnswer( Header: TDNSRequestHeader;
Question:TDNSRequestQuestion; AddressList: TStringList ): TDNSRequestAnswer;
function MatchHostName( Hostname: String; AddressList: TStringlist ): String;
implementation
(*
* Write integer into 16 bit / 2 byte array.
*)
function intToTwoBytes( Int : Integer ): TTwoByte;
begin
Move(Int, Result[0], SizeOf(TTwoByte));
reverse(Result);
end;
(*
* Write integer into 32 bit / 4 byte array.
*)
function intTo32Bit( Int : Integer ): T32Bit;
begin
Move(Int, Result[0], SizeOf(T32Bit));
reverse(Result);
end;
(*
* Reverse Byte array
*)
procedure reverse( var a: Array of Byte );
var
i, j, tmp: Byte;
begin
i := Low(a); j := High(a);
while i<j do begin
tmp:=a[i]; a[i]:=a[j]; a[j]:=tmp;
inc(i); dec(j)
end;
end;
(*
* Parse request stream for necesary header bits
*
*)
function getRequestHeader( Request: TStream ): TDNSRequestHeader;
var
Header: TDNSRequestHeader;
HeaderOffset: Byte = 0;
begin
// Go to beginning
Request.Seek(HeaderOffset, soBeginning);
// Read Message ID
Request.read(Header.MessageID, SizeOf(Header.MessageID));
// Read flags
Request.read(Header.Flags, SizeOf(Header.Flags));
// Read question count
Request.read(Header.QDCount, SizeOf(Header.QDCount));
// Read Answer count
Request.read(Header.ANCount, SizeOf(Header.ANCount));
// Read name servers count
Request.read(Header.NSCount, SizeOf(Header.NSCount));
// Read additional records count
Request.read(Header.ARCount, SizeOf(Header.ARCount));
Result := Header;
end;
(*
* Parse request stream for necesary question bits
* Parse requested domain name
*
*)
function getRequestQuestion( Request: TStream ): TDNSRequestQuestion;
var
Question: TDNSRequestQuestion;
CharByte: Byte;
begin
try
// Seek past Header
Request.Seek(sizeOf(TDNSRequestHeader), soBeginning);
// Read the requested domain name until 0 terminating byte.
repeat Request.read(CharByte, 1); until (CharByte = 0) ;
// Set Qname length
SetLength(Question.Qname, Request.Position - sizeOf(TDNSRequestHeader));
// Seek back past header and read the QName
Request.Seek(sizeOf(TDNSRequestHeader), soBeginning);
Request.read(Question.Qname[0], Length(Question.Qname));
// Read Question Type and Class
Request.Read(Question.QType, SizeOf(Question.QType));
Request.Read(Question.QClass, SizeOf(Question.QClass));
except
On E: Exception do
Raise Exception.Create('DNS question ' + E.Message);
end;
Result := Question;
end;
(*
* Convert the QName into string reperesentation e.g. example.com
*
* QNAme format: ! m y d o m a i n ! c o m \0
*
* Zero terminated, ! = length in two bytes
*)
function QNameToDomainString( var QName: TByteString ): String;
var
Index: Byte = 0;
QNameStr: String;
Buffer: TByteString;
begin
repeat
// Allocate memory for bytes
SetLength(Buffer, QName[Index]);
// Copy bytes
Buffer := Copy(QName, Index + 1, QName[Index]);
// Cast to string
SetString(QNameStr, PAnsiChar(@Buffer[0]), Length(Buffer));
Result := Result + '.' + QNameStr;
// Next Index
Inc(Index, QName[Index] + 1);
until Index = High(QName);
// Deallocate memory
SetLength(Buffer, 0);
// Remove leading dot.
Result := copy(Result, 2, Length(Result));
end;
(*
* Match Host name from the list of Addresses.
*
* Returns the IP Address of the matched pattern.
*)
function matchHostName( Hostname: String; AddressList: TStringlist ): String;
var
AddressLine: String;
IPAddress,
Pattern: String;
Line: Integer;
SpacePos: Byte;
begin
try
// Loop Address line
for Line:=0 to AddressList.count - 1 do begin
// Is comment line
if (pos('#', AddressList.Strings[Line]) > 0) or (pos(';', AddressList.Strings[Line]) > 0) then Continue;
// Clean up the addres line and split pattern and IP
AddressLine := Trim(AddressList.Strings[Line]);
// Search space: First tab or space character
if pos(#32, AddressLine) > 0 then SpacePos := pos(#32, AddressLine)
else if pos(#9, AddressLine) > 0 then SpacePos := pos(#9, AddressLine)
else Continue;
IPAddress := Trim(copy(AddressLine, 1, SpacePos));
Pattern := Trim(copy(AddressLine, SpacePos, Length(AddressLine)));
// Check for Match
if isWild(Hostname, Pattern, true) then Exit(IpAddress);
end;
except
On E: Exception do Raise Exception.Create('Matching hostname ' + E.Message);
end;
// No match found
Exit('');
end;
(*
* Match questioned hostname and generate answer
*
*)
function getRequestAnswer( Header: TDNSRequestHeader;
Question:TDNSRequestQuestion; AddressList: TStringList ): TDNSRequestAnswer;
var
Answer: TDNSRequestAnswer;
IpAddress,
Hostname: String;
Tmp: Byte;
begin
// Get hostname
Hostname := QNameToDomainString(Question.QName);
// Find match for requested hostname
IpAddress := matchHostName(Hostname, AddressList);
// Basic data for answer
Result.QNamePtr[0] := %11000000;
Result.QNamePtr[1] := 12; // 12 bytes after header
Result.QType := Question.QType; //intToTwoBytes(5);
Result.QClass := Question.QClass;//intToTwoBytes(1);
Result.TTL := intTo32Bit(0);
Result.RLength := intToTwoBytes(4); //ipAddress
Result.RData[0] := 127;
Result.RData[1] := 0;
Result.RData[2] := 0;
Result.RData[3] := 1;
Result.Question := Question;
// Dubug
Writeln(StdErr, 'Resolving QNAME '+Hostname);
//For Tmp in Question.QName do Write(StdErr, intToHex(Tmp, 2), ' ');
//Writeln(StdErr, '');
//
// Assemble the header
//
// Copy original Setup header, message ID's etc..
Result.Header := Header;
// Reset QR, error flags etc
Result.Header.Flags := intToTwoBytes(%1000010000000000); // QR=1, AA=1,
// No Match was found
if Length(IpAddress) = 0 then begin
Result.Header.ANCount := intToTwoBytes(0); // 1 answer
end
// Found 1 answer
else begin
Result.Header.ANCount := intToTwoBytes(1); // 1 answer
end;
Result.Header.QDCount := intToTwoBytes(1); // 1 question
Result.Header.ARCount := intToTwoBytes(0); // 0 Authority RRs
Result.Header.NSCount := intToTwoBytes(0); // 0 Additional RRs
end;
end.
|
unit GuiaAlvo.View.Principal;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Edit, FMX.Controls.Presentation, FMX.StdCtrls, FMX.WebBrowser,
FMX.Objects, FMX.Layouts, FMX.TabControl, FMX.ListView.Types, FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.ListView, FMX.Effects,
FMX.DateTimeCtrls, FMX.ScrollBox, FMX.Memo, FMX.TMSListEditor, System.Actions, FMX.ActnList, uFormat, uFuncoes,
FMX.Ani, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdExplicitTLSClientServerBase, IdFTP, System.Rtti, FMX.Grid.Style,
FMX.Grid, FMX.TMSListView, IdFTPCommon, FMX.ListBox, System.SyncObjs, FMX.Filter.Effects,
FMX.TMSBaseControl, FMX.TMSRating, GuiaAlvo.Model.FuncoesServidor, GuiaAlvo.Controller.RedesSociais, GuiaAlvo.Model.RedesSociais;
type
TMyThread = class(TThread)
private
FUrlFtp, FFileFtp : String;
FImage : TListItemImage;
FimgImage : TImage;
FAniLoading : TAniIndicator;
Fms: TMemoryStream;
public
procedure LoadingImages(APathFtp, ANomeImage : String; AImage : TImage; AListImage : TListItemImage; ALoading : TAniIndicator);
protected
procedure Execute; override;
constructor create;
end;
TfrmGestorClient = class(TForm)
recMenuLateral: TRectangle;
Layout1: TLayout;
Layout2: TLayout;
Layout3: TLayout;
Layout4: TLayout;
Circle1: TCircle;
Circle2: TCircle;
Label1: TLabel;
Layout5: TLayout;
Layout6: TLayout;
Layout7: TLayout;
Label2: TLabel;
Circle3: TCircle;
Label3: TLabel;
Label4: TLabel;
Line1: TLine;
VertScrollBox1: TVertScrollBox;
recMenu1: TRectangle;
Layout8: TLayout;
Layout9: TLayout;
Label5: TLabel;
recMenu10: TRectangle;
Layout10: TLayout;
Layout11: TLayout;
Label6: TLabel;
recMenu8: TRectangle;
Layout12: TLayout;
Layout13: TLayout;
Label7: TLabel;
recMenu7: TRectangle;
Layout14: TLayout;
Layout15: TLayout;
Label8: TLabel;
recMenu6: TRectangle;
Layout16: TLayout;
Layout17: TLayout;
Label9: TLabel;
recMenu4: TRectangle;
Layout20: TLayout;
Layout21: TLayout;
Label11: TLabel;
recMenu3: TRectangle;
Layout22: TLayout;
Layout23: TLayout;
Label12: TLabel;
recMenu2: TRectangle;
Layout24: TLayout;
Layout25: TLayout;
Label13: TLabel;
Image1: TImage;
Image2: TImage;
Image3: TImage;
Image4: TImage;
Image6: TImage;
Image7: TImage;
Image8: TImage;
Image9: TImage;
tabMenu: TTabControl;
tbiCadastro: TTabItem;
StyleBook1: TStyleBook;
tbiAvaliacoes: TTabItem;
Rectangle1: TRectangle;
Layout26: TLayout;
Image10: TImage;
Layout27: TLayout;
Label14: TLabel;
Rectangle2: TRectangle;
Layout28: TLayout;
Image11: TImage;
Layout29: TLayout;
Label15: TLabel;
lytView: TLayout;
Image12: TImage;
imgchbChecked: TImage;
imgchbUnchecked: TImage;
imgNull: TImage;
recModal: TRectangle;
recAddCheckList: TRectangle;
ShadowEffect1: TShadowEffect;
Layout36: TLayout;
Image31: TImage;
Layout37: TLayout;
Label33: TLabel;
Rectangle20: TRectangle;
Label35: TLabel;
Rectangle21: TRectangle;
Label36: TLabel;
Rectangle22: TRectangle;
Label37: TLabel;
tbcGuiaAlvo: TTabControl;
tbiRedesSociais: TTabItem;
tbiDeliverys: TTabItem;
Layout33: TLayout;
Line4: TLine;
Line5: TLine;
Image23: TImage;
Label17: TLabel;
Label18: TLabel;
Image24: TImage;
Image25: TImage;
Image26: TImage;
Rectangle12: TRectangle;
edtIFood: TEdit;
Rectangle13: TRectangle;
edtUberEats: TEdit;
Rectangle14: TRectangle;
edtRappi: TEdit;
tbiTelefones: TTabItem;
Layout34: TLayout;
Line6: TLine;
Line7: TLine;
Image27: TImage;
Label19: TLabel;
Label21: TLabel;
Rectangle15: TRectangle;
edtTelefone: TEdit;
Rectangle16: TRectangle;
edtContato: TEdit;
Label22: TLabel;
Label23: TLabel;
Label24: TLabel;
Label25: TLabel;
chkZap: TImage;
chkInterno: TImage;
imgWhatsApp: TImage;
Label26: TLabel;
Label27: TLabel;
Label28: TLabel;
Rectangle17: TRectangle;
Label29: TLabel;
tbiCheckList: TTabItem;
Layout35: TLayout;
Line8: TLine;
Line9: TLine;
Image30: TImage;
Label30: TLabel;
Label31: TLabel;
tbiGrupo: TTabItem;
tbiImagens: TTabItem;
tbiSobre: TTabItem;
tbiAvaliacao: TTabItem;
Rectangle23: TRectangle;
Label32: TLabel;
Layout38: TLayout;
Line10: TLine;
Line11: TLine;
Image29: TImage;
Label38: TLabel;
Label39: TLabel;
Rectangle24: TRectangle;
Rectangle25: TRectangle;
Rectangle26: TRectangle;
Rectangle27: TRectangle;
lstvSubGrupo: TListView;
Label40: TLabel;
Label41: TLabel;
Rectangle28: TRectangle;
Label42: TLabel;
lstvGrupo: TListView;
Layout39: TLayout;
Line12: TLine;
Line13: TLine;
Image32: TImage;
Label44: TLabel;
Label45: TLabel;
recLogo: TRectangle;
recAnuncioPrincipal: TRectangle;
GridLayout: TGridLayout;
Line14: TLine;
imgLixeiraFoto: TImage;
tbiFuncionamento: TTabItem;
Layout56: TLayout;
Line15: TLine;
Line16: TLine;
Image57: TImage;
Label51: TLabel;
Label52: TLabel;
edtAbreSeg: TTimeEdit;
Rectangle58: TRectangle;
Rectangle59: TRectangle;
edtParaSeg: TTimeEdit;
Rectangle60: TRectangle;
edtFechaSeg: TTimeEdit;
Rectangle61: TRectangle;
edtVoltaSeg: TTimeEdit;
Rectangle62: TRectangle;
edtParaTer: TTimeEdit;
Rectangle63: TRectangle;
edtAbreTer: TTimeEdit;
Rectangle64: TRectangle;
edtFechaQui: TTimeEdit;
Rectangle65: TRectangle;
edtVoltaTer: TTimeEdit;
Rectangle66: TRectangle;
edtVoltaQui: TTimeEdit;
Rectangle67: TRectangle;
edtFechaTer: TTimeEdit;
Rectangle68: TRectangle;
edtParaQui: TTimeEdit;
Rectangle69: TRectangle;
edtAbreQui: TTimeEdit;
Rectangle70: TRectangle;
edtAbreQua: TTimeEdit;
Rectangle71: TRectangle;
edtParaQua: TTimeEdit;
Rectangle72: TRectangle;
edtVoltaQua: TTimeEdit;
Rectangle73: TRectangle;
edtFechaQua: TTimeEdit;
Rectangle74: TRectangle;
edtVoltaSex: TTimeEdit;
Rectangle75: TRectangle;
edtFechaSex: TTimeEdit;
Rectangle76: TRectangle;
edtParaSex: TTimeEdit;
Rectangle77: TRectangle;
edtAbreSex: TTimeEdit;
Rectangle78: TRectangle;
edtAbreSab: TTimeEdit;
Rectangle79: TRectangle;
edtParaSab: TTimeEdit;
Rectangle80: TRectangle;
edtVoltaSab: TTimeEdit;
Rectangle81: TRectangle;
edtFechaSab: TTimeEdit;
Rectangle82: TRectangle;
edtVoltaDom: TTimeEdit;
Rectangle83: TRectangle;
edtFechaDom: TTimeEdit;
Rectangle84: TRectangle;
edtParaDom: TTimeEdit;
Rectangle85: TRectangle;
edtAbreDom: TTimeEdit;
chkFechadoSeg: TImage;
chkFechadoTer: TImage;
chkFechadoQui: TImage;
chkFechadoQua: TImage;
chkFechadoSab: TImage;
chkFechadoSex: TImage;
chkFechadoDom: TImage;
Label54: TLabel;
Label55: TLabel;
Label56: TLabel;
Label57: TLabel;
Label58: TLabel;
Label59: TLabel;
Label60: TLabel;
Label53: TLabel;
Rectangle86: TRectangle;
Rectangle87: TRectangle;
Rectangle88: TRectangle;
Label61: TLabel;
sbtnFecha: TSpeedButton;
sbtnVolta: TSpeedButton;
sbtnPara: TSpeedButton;
sbtnAbre: TSpeedButton;
imgrbChecked: TImage;
imgrbUnchecked: TImage;
lblMsgFormatoFoto: TLabel;
Layout32: TLayout;
Line2: TLine;
Line3: TLine;
Image22: TImage;
Label16: TLabel;
Label20: TLabel;
Image13: TImage;
Image14: TImage;
Image15: TImage;
Image16: TImage;
Image19: TImage;
Image21: TImage;
Image20: TImage;
Image18: TImage;
Image17: TImage;
Rectangle11: TRectangle;
edtLinkAppleStore: TEdit;
Rectangle9: TRectangle;
edtLinkGooglePlay: TEdit;
Rectangle10: TRectangle;
edtLinkEmail: TEdit;
Rectangle7: TRectangle;
edtLinkSite: TEdit;
Rectangle8: TRectangle;
edtLinkGooglePlus: TEdit;
Rectangle5: TRectangle;
edtLinkYoutube: TEdit;
Rectangle6: TRectangle;
edtLinkTwitter: TEdit;
Rectangle4: TRectangle;
edtLinkInstagran: TEdit;
Rectangle3: TRectangle;
edtLinkFacebook: TEdit;
Rectangle33: TRectangle;
Layout40: TLayout;
Line17: TLine;
Line18: TLine;
Image28: TImage;
Label62: TLabel;
Label63: TLabel;
Rectangle34: TRectangle;
edtSlogam: TEdit;
mmDescricao: TMemo;
Label64: TLabel;
mmTag: TTMSFMXListEditor;
Rectangle35: TRectangle;
Label65: TLabel;
Layout41: TLayout;
Line19: TLine;
Line20: TLine;
Image33: TImage;
Label66: TLabel;
Label67: TLabel;
Layout60: TLayout;
recMenuTopo1: TRectangle;
imgMenu1: TImage;
recMenuTopo5: TRectangle;
imgMenu5: TImage;
recMenuTopo3: TRectangle;
imgMenu3: TImage;
recMenuTopo4: TRectangle;
recMenuTopo2: TRectangle;
imgMenu2: TImage;
recMenu9: TRectangle;
Layout61: TLayout;
Image47: TImage;
Layout62: TLayout;
Label79: TLabel;
imgMenu4: TImage;
tbiContrato: TTabItem;
Layout63: TLayout;
Layout64: TLayout;
Label80: TLabel;
Label81: TLabel;
Layout65: TLayout;
Label82: TLabel;
Label83: TLabel;
Layout66: TLayout;
Label84: TLabel;
Label85: TLabel;
Rectangle46: TRectangle;
Layout67: TLayout;
Label86: TLabel;
Image48: TImage;
Rectangle47: TRectangle;
Label87: TLabel;
ActionList: TActionList;
actRedesSociais: TChangeTabAction;
actDeliverys: TChangeTabAction;
actTelefones: TChangeTabAction;
actCheckList: TChangeTabAction;
actGrupoSubGrupo: TChangeTabAction;
actFuncionamento: TChangeTabAction;
actImagens: TChangeTabAction;
actSobre: TChangeTabAction;
actAvaliacoes: TChangeTabAction;
actAtualizaApp: TChangeTabAction;
imgInterno: TImage;
imgLoading: TCircle;
faLoading: TFloatAnimation;
lblCaptionLoading: TLabel;
lytloading: TLayout;
imgLixeira: TImage;
lstvTelefones: TListView;
recCancelar: TRectangle;
Label88: TLabel;
lytImages: TLayout;
recMenu5: TRectangle;
Layout18: TLayout;
Image5: TImage;
Layout19: TLayout;
Label10: TLabel;
lstvCheckList: TListView;
Rectangle18: TRectangle;
edtCheckList: TEdit;
Rectangle19: TRectangle;
lstvNovoCheckList: TListView;
recAddGrupo: TRectangle;
ShadowEffect2: TShadowEffect;
Layout30: TLayout;
Image34: TImage;
Rectangle49: TRectangle;
Label78: TLabel;
Rectangle50: TRectangle;
Label89: TLabel;
Rectangle51: TRectangle;
edtGrupo: TEdit;
Layout68: TLayout;
Label90: TLabel;
recAddSubGrupo: TRectangle;
ShadowEffect3: TShadowEffect;
Layout69: TLayout;
Image35: TImage;
Rectangle54: TRectangle;
Label92: TLabel;
Rectangle55: TRectangle;
Label93: TLabel;
Layout70: TLayout;
Label94: TLabel;
Rectangle36: TRectangle;
Label34: TLabel;
mmDescricaoGrupo: TMemo;
Label96: TLabel;
Rectangle48: TRectangle;
lstvGrupoListaGrupos: TListView;
Layout71: TLayout;
Rectangle56: TRectangle;
edtSubCategoria: TEdit;
Label91: TLabel;
Rectangle52: TRectangle;
lstvNovoSubGrupo: TListView;
Rectangle29: TRectangle;
Label95: TLabel;
imgNovo: TImage;
recCorIcone1: TFillRGBEffect;
recCorIcone2: TFillRGBEffect;
recCorIcone3: TFillRGBEffect;
recCorIcone4: TFillRGBEffect;
recCorIcone5: TFillRGBEffect;
Label43: TLabel;
recAnuncioDestaque: TRectangle;
recAnuncioSecao: TRectangle;
Image38: TImage;
opdgImagens: TOpenDialog;
Label46: TLabel;
imgEditaFoto: TImage;
Rectangle31: TRectangle;
edtTituloEmpresa: TEdit;
Label97: TLabel;
Label98: TLabel;
Label99: TLabel;
Rectangle30: TRectangle;
imgVerFoto: TImage;
FillRGBEffect1: TFillRGBEffect;
recViewFoto: TRectangle;
Label47: TLabel;
tabViewCelular: TTabControl;
tbGrupo: TTabItem;
tbSubGrupo: TTabItem;
tbListaComercio: TTabItem;
tbComercio: TTabItem;
recTool: TRectangle;
sbtnVoltar: TImage;
FillRGBEffect16: TFillRGBEffect;
lytTitulos: TLayout;
Layout46: TLayout;
lblGrupo: TLabel;
Line21: TLine;
Layout47: TLayout;
lblSubGrupo: TLabel;
btnAdicionar: TImage;
FillRGBEffect5: TFillRGBEffect;
recSearch: TRectangle;
imgBtnMenuPrincipal: TImage;
faButtomOnMenu: TFloatAnimation;
faButtomOffMenu: TFloatAnimation;
FillRGBEffect12: TFillRGBEffect;
imgBtnPesquisa: TImage;
FloatAnimation1: TFloatAnimation;
FloatAnimation2: TFloatAnimation;
edtBusca: TEdit;
imgSino: TImage;
FillRGBEffect6: TFillRGBEffect;
faSino: TFloatAnimation;
btnEnviar: TImage;
FillRGBEffect7: TFillRGBEffect;
btnHome: TImage;
FillRGBEffect8: TFillRGBEffect;
Layout72: TLayout;
Image36: TImage;
Image37: TImage;
Label48: TLabel;
Layout73: TLayout;
Label49: TLabel;
Rectangle32: TRectangle;
Image39: TImage;
FillRGBEffect2: TFillRGBEffect;
Layout74: TLayout;
Layout75: TLayout;
Label50: TLabel;
Line22: TLine;
Layout76: TLayout;
Label100: TLabel;
Image45: TImage;
FillRGBEffect11: TFillRGBEffect;
ListView1: TListView;
Image40: TImage;
Layout77: TLayout;
Image41: TImage;
Layout78: TLayout;
Label101: TLabel;
Label102: TLabel;
Rectangle37: TRectangle;
Image42: TImage;
FillRGBEffect3: TFillRGBEffect;
Layout79: TLayout;
Layout80: TLayout;
Label103: TLabel;
Line23: TLine;
Layout81: TLayout;
Label104: TLabel;
Image43: TImage;
FillRGBEffect4: TFillRGBEffect;
Line24: TLine;
TMSFMXRating1: TTMSFMXRating;
Label105: TLabel;
Label106: TLabel;
Rectangle38: TRectangle;
Image44: TImage;
FillRGBEffect9: TFillRGBEffect;
Layout82: TLayout;
Layout83: TLayout;
Label107: TLabel;
Line25: TLine;
Layout84: TLayout;
Label108: TLabel;
Image46: TImage;
FillRGBEffect10: TFillRGBEffect;
VertScrollBox2: TVertScrollBox;
Image49: TImage;
Layout85: TLayout;
lblComercio: TLabel;
lblSlogam: TLabel;
Layout86: TLayout;
Layout87: TLayout;
recLogoCom: TRectangle;
imgLogoCom: TImage;
aniLoadingLogo: TAniIndicator;
ShadowEffect6: TShadowEffect;
Layout88: TLayout;
Image50: TImage;
faLigacao: TFloatAnimation;
Layout89: TLayout;
Rectangle39: TRectangle;
tmsrtEstrelas: TTMSFMXRating;
lblPontuacao: TLabel;
Layout90: TLayout;
Image51: TImage;
faGPS: TFloatAnimation;
Layout91: TLayout;
Image52: TImage;
faWhats: TFloatAnimation;
recSobrenos: TRectangle;
lblSobre: TLabel;
lytSobrenos: TLayout;
lblTituloSobrenos: TLabel;
Rectangle40: TRectangle;
recSalvarRedesSociais: TRectangle;
Label109: TLabel;
recSalvarDelivery: TRectangle;
Label110: TLabel;
Rectangle43: TRectangle;
Label111: TLabel;
Rectangle44: TRectangle;
Label112: TLabel;
Rectangle45: TRectangle;
Label113: TLabel;
Rectangle53: TRectangle;
Label114: TLabel;
imgStatusRedesSociais: TImage;
imgWarning: TImage;
imgStop: TImage;
imgCheck: TImage;
imgStatusDelivery: TImage;
imgSTatusTelefone: TImage;
imgStatusCheckList: TImage;
imgStatusGrupo: TImage;
imgStatusFuncionamento: TImage;
imgStatusImagens: TImage;
imgStatusSobre: TImage;
imgStatusAvaliacao: TImage;
imgUpdate: TImage;
FlowLayout1: TFlowLayout;
Layout43: TLayout;
chkAmbiente: TImage;
Label68: TLabel;
Layout44: TLayout;
Label69: TLabel;
Layout58: TLayout;
chkAtendimento: TImage;
Label76: TLabel;
Layout59: TLayout;
Label77: TLabel;
Layout54: TLayout;
chkLimpeza: TImage;
Label74: TLabel;
Layout55: TLayout;
Label75: TLabel;
Layout51: TLayout;
chkLocalizacao: TImage;
Label72: TLabel;
Layout52: TLayout;
Label73: TLabel;
Layout48: TLayout;
chkPrecos: TImage;
Label70: TLabel;
Layout49: TLayout;
Label71: TLabel;
Label115: TLabel;
imgAvaliacaoBloqueada: TImage;
procedure edtLinkFacebookKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
procedure edtLinkInstagranKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
procedure edtLinkTwitterKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
procedure edtLinkYoutubeKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
procedure edtLinkGooglePlusKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
procedure edtLinkSiteKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
procedure edtLinkEmailKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
procedure edtLinkGooglePlayKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
procedure edtLinkAppleStoreKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
procedure edtIFoodKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
procedure edtUberEatsKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
procedure edtRappiKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
procedure edtTelefoneKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
procedure edtContatoKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
procedure edtAbreSegKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
procedure mmDescricaoKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
procedure edtSlogamKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
procedure recMenu1Click(Sender: TObject);
procedure recMenu2Click(Sender: TObject);
procedure recMenu3Click(Sender: TObject);
procedure recMenu4Click(Sender: TObject);
procedure recMenu5Click(Sender: TObject);
procedure recMenu6Click(Sender: TObject);
procedure recMenu7Click(Sender: TObject);
procedure recMenu8Click(Sender: TObject);
procedure recMenu9Click(Sender: TObject);
procedure edtTelefoneTyping(Sender: TObject);
procedure chkZapClick(Sender: TObject);
procedure chkInternoClick(Sender: TObject);
procedure Rectangle17Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure lstvTelefonesDblClick(Sender: TObject);
procedure lstvTelefonesItemClickEx(const Sender: TObject; ItemIndex: Integer; const LocalClickPos: TPointF; const ItemObject: TListItemDrawable);
procedure recCancelarClick(Sender: TObject);
procedure lstvCheckListItemClickEx(const Sender: TObject; ItemIndex: Integer; const LocalClickPos: TPointF; const ItemObject: TListItemDrawable);
procedure Rectangle23Click(Sender: TObject);
procedure Rectangle20Click(Sender: TObject);
procedure lstvNovoCheckListItemClickEx(const Sender: TObject; ItemIndex: Integer; const LocalClickPos: TPointF; const ItemObject: TListItemDrawable);
procedure Rectangle22Click(Sender: TObject);
procedure Rectangle21Click(Sender: TObject);
procedure lstvGrupoItemClickEx(const Sender: TObject; ItemIndex: Integer; const LocalClickPos: TPointF; const ItemObject: TListItemDrawable);
procedure lstvSubGrupoItemClickEx(const Sender: TObject; ItemIndex: Integer; const LocalClickPos: TPointF; const ItemObject: TListItemDrawable);
procedure Rectangle50Click(Sender: TObject);
procedure edtGrupoKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
procedure Rectangle49Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure edtSubCategoriaKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
procedure lstvNovoSubGrupoItemClickEx(const Sender: TObject; ItemIndex: Integer; const LocalClickPos: TPointF; const ItemObject: TListItemDrawable);
procedure recOutrosGrupoClick(Sender: TObject);
procedure Rectangle29Click(Sender: TObject);
procedure Rectangle55Click(Sender: TObject);
procedure Rectangle28Click(Sender: TObject);
procedure lstvGrupoListaGruposItemClickEx(const Sender: TObject; ItemIndex: Integer; const LocalClickPos: TPointF; const ItemObject: TListItemDrawable);
procedure Rectangle54Click(Sender: TObject);
procedure recMenu10Click(Sender: TObject);
procedure recMenuTopo1Click(Sender: TObject);
procedure sbtnAbreClick(Sender: TObject);
procedure chkFechadoSegClick(Sender: TObject);
procedure recAnuncioPrincipalClick(Sender: TObject);
procedure recAnuncioDestaqueClick(Sender: TObject);
procedure recAnuncioSecaoClick(Sender: TObject);
procedure recLogoClick(Sender: TObject);
procedure Image38Click(Sender: TObject);
procedure recViewFotoClick(Sender: TObject);
procedure chkAtendimentoClick(Sender: TObject);
procedure tbcGuiaAlvoChange(Sender: TObject);
procedure recSalvarRedesSociaisClick(Sender: TObject);
procedure recSalvarDeliveryClick(Sender: TObject);
procedure lstvTelefonesPainting(Sender: TObject; Canvas: TCanvas; const ARect: TRectF);
procedure Rectangle45Click(Sender: TObject);
procedure Rectangle53Click(Sender: TObject);
procedure Rectangle43Click(Sender: TObject);
private
FControllerRedes : TControllerRedesSociais;
procedure AddFoneLista(AIdRegistro: Integer; ATelefone, AContato, AZap, AInterno: String);
procedure CarregaListaTelefone(AIdCom: Integer);
procedure Loading(CaptionLoading : String; Status : Boolean = False);
procedure AddListaCheckList(AIdCheckList : Integer; ACheckList : String; AChecked, ANovo : Boolean);
function CarregaCheckList(AIdCom: Integer) : Boolean;
procedure AddNovaCheckList(ACheckList: String);
procedure AddGrupoLista(AIdGrupo : Integer; AGrupo : String; AGrupoChecked, ANovo : Boolean);
function ListaGrupos : Boolean;
procedure AddSubGrupo(AIdSubGrupo: Integer; ASubGrupo: String; AChecked, ANovo : Boolean);
function CarregaListaSubGrupo(AIdCom, AIdGrupo : Integer): Boolean;
procedure AddGruposNovos(AIdGrupo : Integer; AGrupo : String; ANovo, AChecked : Boolean);
procedure CarregaGruposNovos(AIdChecked : Integer);
procedure AddNovaSubCategoria(ACheckList: String);
procedure MenuLateral(AAtivo: String);
procedure MenuTopo(AAtivo: String);
function ExtensaoValida(AFileName, AExtensao: String): Boolean;
procedure CriaQuadroFotos(AIdFile : Integer; AFileFoto : String);
procedure OnClickDelFoto(Sender: TObject);
procedure OnClickViewFoto(Sender: TObject);
procedure OnClickEditFoto(Sender: TObject);
function IndiceImagens: Integer;
function ValidaDelivery: Boolean;
function ValidaRedesSociais: Boolean;
procedure LoadStart;
{ Private declarations }
public
MyThread : TMyThread;
FRedesSociais : TRedeSocial;
end;
var
frmGestorClient: TfrmGestorClient;
lcIdTelefone : Integer;
lcPausaThread: TCriticalSection;
lcIdChecked : Integer;
lcExtensao : String;
lcIndexFotos : Integer = 1;
const
AFieldsTime : Array[1..28] of String = ('edtAbreSeg','edtParaSeg','edtVoltaSeg','edtFechaSeg',
'edtAbreTer','edtParaTer','edtVoltaTer','edtFechaTer',
'edtAbreQua','edtParaQua','edtVoltaQua','edtFechaQua',
'edtAbreQui','edtParaQui','edtVoltaQui','edtFechaQui',
'edtAbreSex','edtParaSex','edtVoltaSex','edtFechaSex',
'edtAbreSab','edtParaSab','edtVoltaSab','edtFechaSab',
'edtAbreDom','edtParaDom','edtVoltaDom','edtFechaDom');
implementation
uses
System.UIConsts, FMX.Platform.win, Winapi.Windows, Guia.Controle, uMensagens, GuiaAlvo.Controller.DataModuleDados;
{$R *.fmx}
procedure TfrmGestorClient.Loading(CaptionLoading : String; Status : Boolean = False);
begin
recModal.Visible := Status;
lytloading.Visible := Status;
faLoading.Enabled := Status;
lblCaptionLoading.Text := CaptionLoading;
end;
procedure TfrmGestorClient.OnClickDelFoto(Sender : TObject);
var
AIdFoto : String;
begin
AIdFoto := TRectangle(Sender).Tag.ToString;
TLayout(GridLayout.FindComponent('imgAnuncio' + AIdFoto)).DisposeOf;
end;
procedure TfrmGestorClient.OnClickViewFoto(Sender : TObject);
var
AName,
AIdFoto : String;
begin
AIdFoto := TRectangle(Sender).Tag.ToString;
recViewFoto.Visible := True;
recModal.Visible := True;
recViewFoto.Fill.Bitmap.Assign(TRectangle(TLayout(GridLayout.FindComponent('imgAnuncio' + AIdFoto)).FindComponent('recViewImagem' + AIdFoto)).Fill.Bitmap);
end;
procedure TfrmGestorClient.OnClickEditFoto(Sender : TObject);
var
AIdFoto : String;
begin
AIdFoto := TRectangle(Sender).Tag.ToString;
opdgImagens.Filter := 'JPG|*.jpg';
opdgImagens.Options := [TOpenOption.ofHideReadOnly,TOpenOption.ofEnableSizing];
if opdgImagens.Execute then
begin
if SizeImgpx(opdgImagens.FileName) <> ctrSIZEANUNCIOCOMERCIO then
begin
MessageBox(WindowHandleToPLatform(Self.Handle).Wnd,
pChar('A foto deve ser no formato ' + ctrSIZEANUNCIOCOMERCIO),
'Guia Alvo', MB_OK + MB_ICONEXCLAMATION);
Exit;
end
else
begin
case ExtensaoValida(opdgImagens.FileName, '.jpg') of
True : TRectangle(TLayout(GridLayout.FindComponent('imgAnuncio' + AIdFoto)).FindComponent('recViewImagem' + AIdFoto)).Fill.Bitmap.Bitmap.LoadFromFile(opdgImagens.FileName);
False : begin
MessageBox(WindowHandleToPlatform(Self.Handle).Wnd,
'Extensão inválida, a foto deve ser no formato .jpg!',
'Guia Alvo', MB_OK + MB_ICONINFORMATION);
Exit;
end;
end;
end;
end;
end;
procedure TfrmGestorClient.CriaQuadroFotos(AIdFile : Integer; AFileFoto : String);
var
ALayout, ALayoutRodape : TLayout;
ARectangle : TRectangle;
begin
ALayout := TLayout.Create(GridLayout);
ALayout.Parent := GridLayout;
ALayout.Margins.Bottom := 4;
ALayout.Margins.Left := 4;
ALayout.Name := 'imgAnuncio' + AIdFile.ToString;
ALayout.Tag := AIdFile;
ALayoutRodape := TLayout.Create(ALayout);
ALayoutRodape.Parent := ALayout;
ALayoutRodape.Align := TAlignLayout.Bottom;
ALayoutRodape.Height := 25;
ARectangle := TRectangle.Create(ALayout);
ARectangle.Parent := ALayout;
ARectangle.Align := TAlignLayout.Client;
ARectangle.Fill.Kind := TBrushKind.Bitmap;
ARectangle.Fill.Bitmap.WrapMode := TWrapMode.TileStretch;
ARectangle.Stroke.Color := TAlphaColorRec.Gainsboro;
ARectangle.Stroke.Thickness := 2;
ARectangle.XRadius := 5;
ARectangle.YRadius := 5;
ARectangle.Name := 'recViewImagem' + AIdFile.ToString;
ARectangle.Fill.Bitmap.Bitmap.LoadFromFile(AFileFoto);
ARectangle.Tag := AIdFile;
ARectangle := TRectangle.Create(ALayout);
ARectangle.Parent := ALayoutRodape;
ARectangle.Align := TAlignLayout.Right;
ARectangle.Fill.Kind := TBrushKind.Bitmap;
ARectangle.Fill.Bitmap.WrapMode := TWrapMode.TileStretch;
ARectangle.Stroke.Thickness := 0;
ARectangle.Fill.Bitmap.Bitmap := imgVerFoto.Bitmap;
ARectangle.Width := 25;
ARectangle.Tag := AIdFile;
ARectangle.Cursor := crHandPoint;
ARectangle.HitTest := True;
ARectangle.Name := 'recBtnView' + AIdFile.ToString;
ARectangle.OnClick := OnClickViewFoto;
ARectangle := TRectangle.Create(ALayout);
ARectangle.Parent := ALayoutRodape;
ARectangle.Align := TAlignLayout.Right;
ARectangle.Fill.Kind := TBrushKind.Bitmap;
ARectangle.Fill.Bitmap.WrapMode := TWrapMode.TileStretch;
ARectangle.Stroke.Thickness := 0;
ARectangle.Fill.Bitmap.Bitmap := imgEditaFoto.Bitmap;
ARectangle.Width := 25;
ARectangle.Tag := AIdFile;
ARectangle.Cursor := crHandPoint;
ARectangle.HitTest := True;
ARectangle.Name := 'recBtnEdit' + AIdFile.ToString;
ARectangle.OnClick := OnClickEditFoto;
ARectangle := TRectangle.Create(ALayout);
ARectangle.Parent := ALayoutRodape;
ARectangle.Align := TAlignLayout.Right;
ARectangle.Fill.Kind := TBrushKind.Bitmap;
ARectangle.Fill.Bitmap.WrapMode := TWrapMode.TileStretch;
ARectangle.Stroke.Thickness := 0;
ARectangle.Fill.Bitmap.Bitmap := imgLixeiraFoto.Bitmap;
ARectangle.Width := 25;
ARectangle.Tag := AIdFile;
ARectangle.Cursor := crHandPoint;
ARectangle.HitTest := True;
ARectangle.Name := 'recBtnDel' + AIdFile.ToString;
ARectangle.OnClick := OnClickDelFoto;
end;
procedure TfrmGestorClient.lstvCheckListItemClickEx(const Sender: TObject; ItemIndex: Integer; const LocalClickPos: TPointF; const ItemObject: TListItemDrawable);
var
AIdCheckList : Integer;
begin
if TListView(Sender).Selected <> nil then
begin
AIdCheckList := lstvCheckList.Items[lstvCheckList.ItemIndex].Tag;
if ItemObject is TListItemImage then
begin
if TListItemImage(ItemObject).Name = 'Image2' then
begin
TThread.CreateAnonymousThread(
procedure
begin
TThread.Synchronize(nil,
procedure
begin
try
AddCheckListCom(cfgIdComercio, AIdCheckList);
if CarregaCheckList(cfgIdComercio) = False then
imgStatusCheckList.Bitmap.Assign(imgStop.Bitmap) else
imgStatusCheckList.Bitmap.Assign(imgCheck.Bitmap);
except
MessageBox(WindowHandleToPlatform(Self.Handle).Wnd,
pChar(ERRO_SELECTED_CHECKLIST),
'Guia Alvo', MB_OK + MB_ICONERROR);
end;
end);
end).Start;
end;
end;
end;
end;
procedure TfrmGestorClient.lstvGrupoItemClickEx(const Sender: TObject; ItemIndex: Integer; const LocalClickPos: TPointF; const ItemObject: TListItemDrawable);
var
AIdGrupo : Integer;
begin
if TListView(Sender).Selected <> nil then
begin
AIdGrupo := lstvGrupo.Items[lstvGrupo.ItemIndex].Tag;
if ItemObject is TListItemImage then
begin
if TListItemImage(ItemObject).Name = 'Image2' then
begin
TThread.CreateAnonymousThread(
procedure
begin
TThread.Synchronize(nil,
procedure
begin
Try
UpdateGrupoCom(cfgIdComercio, AIdGrupo);
cfgIdCategoria := AIdGrupo;
ListaGrupos;
if CarregaListaSubGrupo(cfgIdComercio, cfgIdCategoria) = False then
imgStatusGrupo.Bitmap.Assign(imgStop.Bitmap) else
imgStatusGrupo.Bitmap.Assign(imgCheck.Bitmap);
Except
MessageBox(WindowHandleToPlatform(Self.Handle).Wnd,
pChar(ERRO_SELECTED_GROUP),
'Guia Alvo', MB_OK + MB_ICONERROR);
end;
end);
end).Start;
end;
end;
end;
end;
procedure TfrmGestorClient.lstvGrupoListaGruposItemClickEx(const Sender: TObject; ItemIndex: Integer; const LocalClickPos: TPointF; const ItemObject: TListItemDrawable);
begin
if TListView(Sender).Selected <> nil then
begin
lcIdChecked := lstvGrupoListaGrupos.Items[lstvGrupoListaGrupos.ItemIndex].Tag;
if ItemObject is TListItemImage then
begin
if TListItemImage(ItemObject).Name = 'Image2' then
begin
TThread.CreateAnonymousThread(
procedure
begin
TThread.Synchronize(nil,
procedure
begin
Try
CarregaGruposNovos(lcIdChecked);
Except
MessageBox(WindowHandleToPlatform(Self.Handle).Wnd,
pChar(ERRO_LOAD_NEW_GROUP),
'Guia Alvo', MB_OK + MB_ICONERROR);
end;
end);
end).Start;
end;
end;
end;
end;
procedure TfrmGestorClient.lstvNovoCheckListItemClickEx(const Sender: TObject; ItemIndex: Integer; const LocalClickPos: TPointF; const ItemObject: TListItemDrawable);
var
AIndexCheckList : Integer;
begin
if TListView(Sender).Selected <> nil then
begin
AIndexCheckList := lstvNovoCheckList.ItemIndex;
if ItemObject is TListItemImage then
begin
if TListItemImage(ItemObject).Name = 'Image2' then
begin
lstvNovoCheckList.Items.Delete(AIndexCheckList);
end;
end;
end;
end;
procedure TfrmGestorClient.lstvNovoSubGrupoItemClickEx(const Sender: TObject; ItemIndex: Integer; const LocalClickPos: TPointF; const ItemObject: TListItemDrawable);
var
AIndexSubCategoria : Integer;
begin
if TListView(Sender).Selected <> nil then
begin
AIndexSubCategoria := lstvNovoSubGrupo.ItemIndex;
if ItemObject is TListItemImage then
begin
if TListItemImage(ItemObject).Name = 'Image2' then
lstvNovoSubGrupo.Items.Delete(AIndexSubCategoria);
end;
end;
end;
procedure TfrmGestorClient.lstvSubGrupoItemClickEx(const Sender: TObject; ItemIndex: Integer; const LocalClickPos: TPointF; const ItemObject: TListItemDrawable);
var
AIdSubGrupo : Integer;
begin
if TListView(Sender).Selected <> nil then
begin
AIdSubGrupo := lstvSubGrupo.Items[lstvSubGrupo.ItemIndex].Tag;
if ItemObject is TListItemImage then
begin
if TListItemImage(ItemObject).Name = 'Image2' then
begin
TThread.CreateAnonymousThread(
procedure
begin
TThread.Synchronize(nil,
procedure
begin
try
InsertSubCatCom(cfgIdComercio, cfgIdCategoria, AIdSubGrupo);
if CarregaListaSubGrupo(cfgIdComercio, cfgIdCategoria) = False then
imgStatusGrupo.Bitmap.Assign(imgStop.Bitmap) else
imgStatusGrupo.Bitmap.Assign(imgCheck.Bitmap);
Except
MessageBox(WindowHandleToPlatform(Self.Handle).Wnd,
pChar(ERRO_SELECTED_CATEGORY),
'Guia Alvo', MB_OK + MB_ICONERROR);
end;
end);
end).Start;
end;
end;
end;
end;
procedure TfrmGestorClient.lstvTelefonesDblClick(Sender: TObject);
var
ATexto : TListItemText;
AImage : TListItemImage;
AItem : TListViewItem;
begin
lcIdTelefone := lstvTelefones.Items[lstvTelefones.ItemIndex].Tag;
AItem := lstvTelefones.Items[lstvTelefones.ItemIndex];
ATexto := AItem.Objects.FindDrawable('Text1') as TListItemText;
edtTelefone.Text := ATexto.Text;
ATexto := AItem.Objects.FindDrawable('Text2') as TListItemText;
edtContato.Text := ATexto.Text;
AImage := AItem.Objects.FindDrawable('Image3') as TListItemImage;
if AImage.Bitmap <> nil then
chkZap.Bitmap := imgchbChecked.Bitmap else
chkZap.Bitmap := imgchbUnChecked.Bitmap;
AImage := AItem.Objects.FindDrawable('Image4') as TListItemImage;
if AImage.Bitmap <> nil then
chkInterno.Bitmap := imgchbChecked.Bitmap else
chkInterno.Bitmap := imgchbUnChecked.Bitmap;
//lstvTelefones.Items.Delete(lstvTelefones.ItemIndex);
Label29.Text := 'ALTERAR';
recCancelar.Visible := True;
end;
procedure TfrmGestorClient.lstvTelefonesItemClickEx(const Sender: TObject; ItemIndex: Integer; const LocalClickPos: TPointF; const ItemObject: TListItemDrawable);
var
AIdTelefone : Integer;
begin
if TListView(Sender).Selected <> nil then
begin
AIdTelefone := lstvTelefones.Items[lstvTelefones.ItemIndex].Tag;
if ItemObject is TListItemImage then
begin
if TListItemImage(ItemObject).Name = 'Image6' then
begin
case MessageBox(WindowHandleToPlatForm(Self.Handle).Wnd,
'Confirma a exclusão do telefone selecionado?',
'Guia Alvo', MB_YESNO + MB_ICONQUESTION) of
ID_YES : begin
TThread.CreateAnonymousThread(
procedure
begin
TThread.Synchronize(nil,
procedure
begin
Loading('Excluindo...', True);
end);
DeleteFone(AIdTelefone);
CarregaListaTelefone(cfgIdComercio);
TThread.Synchronize(nil,
procedure
begin
Loading('',False);
end);
end).Start;
end;
ID_NO : Exit;
end;
end;
end;
end;
end;
procedure TfrmGestorClient.lstvTelefonesPainting(Sender: TObject; Canvas: TCanvas; const ARect: TRectF);
begin
if lstvTelefones.Items.Count = 0 then
imgSTatusTelefone.Bitmap.Assign(imgStop.Bitmap) else
imgSTatusTelefone.Bitmap.Assign(imgCheck.Bitmap);
end;
function NextFieldsTime(Sender: TObject) : Integer;
var
ACampoAtual : String;
ANextField : Integer;
begin
ACampoAtual := TEdit(Sender).Name;
for var i := 1 to 28 do
begin
if AFieldsTime[i] = ACampoAtual then
ANextField := i;
end;
if ANextField = 28 then
Result := 1 else
Result := ANextField + 1;
end;
procedure TfrmGestorClient.chkAtendimentoClick(Sender: TObject);
begin
if cfgAlteraAvaliacao = True then
IsImageChecked(TImage(Sender)) else
MessageBox(WindowHandleToPlatform(Self.Handle).Wnd,
'Você não pode mais mudar as avaliações pois ' +
'ja existe(m) avaliação(ões) registrada!',
'GuiaAlvo Alvo', MB_OK + MB_ICONEXCLAMATION);
end;
procedure TfrmGestorClient.chkFechadoSegClick(Sender: TObject);
begin
if TImage(Sender).Tag = 0 then
begin
TImage(Sender).Bitmap := imgchbChecked.Bitmap;
TImage(Sender).Tag := 1;
end
else
begin
TImage(Sender).Bitmap := imgchbUnChecked.Bitmap;
TImage(Sender).Tag := 0;
end;
end;
procedure TfrmGestorClient.chkInternoClick(Sender: TObject);
begin
IsImageChecked(chkInterno);
end;
procedure TfrmGestorClient.AddFoneLista(AIdRegistro : Integer; ATelefone, AContato, AZap, AInterno : String);
var
AItem : TListViewItem;
AText : TListItemText;
AImage : TListItemImage;
begin
AItem := lstvTelefones.Items.Add;
AItem.Tag := AIdRegistro;
AText := TListItemText(AItem.Objects.FindDrawable('Text1'));
if Length(ATelefone) = 11 then
AText.Text := Mask('(##) #####-####', ATelefone) else
AText.Text := Mask('(##) ####-####', ATelefone);
AText := TListItemText(AItem.Objects.FindDrawable('Text2'));
AText.Text := AContato;
AImage := TListItemImage(AItem.Objects.FindDrawable('Image6'));
AImage.Bitmap := imgLixeira.Bitmap;
if AZap = '1' then
begin
AImage := TListItemImage(AItem.Objects.FindDrawable('Image3'));
AImage.Bitmap := imgWhatsApp.Bitmap;
end
else
begin
AImage := TListItemImage(AItem.Objects.FindDrawable('Image3'));
AImage.Bitmap := nil;
end;
if AInterno = '1' then
begin
AImage := TListItemImage(AItem.Objects.FindDrawable('Image4'));
AImage.Bitmap := imgInterno.Bitmap;
end
else
begin
AImage := TListItemImage(AItem.Objects.FindDrawable('Image4'));
AImage.Bitmap := nil;
end;
end;
procedure TfrmGestorClient.chkZapClick(Sender: TObject);
begin
IsImageChecked(chkZap);
end;
procedure TfrmGestorClient.edtSubCategoriaKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
begin
if Key = VK_RETURN then
begin
if edtSubCategoria.Text = '' then
begin
MessageBox(WindowHandleToPlatform(Self.Handle).Wnd,
'É necessário informar um nome para a Sub-Categoria',
'Guia Alvo', MB_OK + MB_ICONEXCLAMATION);
edtSubCategoria.SetFocus;
Exit;
end
else
begin
AddNovaSubCategoria(edtSubCategoria.Text);
edtSubCategoria.Text := '';
end;
end;
end;
procedure TfrmGestorClient.edtAbreSegKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
begin
NextField(Key, TEdit(Self.FindComponent(AFieldsTime[NextFieldsTime(Sender)])));
end;
procedure TfrmGestorClient.edtContatoKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
begin
NextField(Key, edtTelefone);
end;
procedure TfrmGestorClient.edtGrupoKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
begin
if Key = VK_RETURN then
mmDescricaoGrupo.SetFocus;
end;
procedure TfrmGestorClient.edtIFoodKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
begin
NextField(Key, edtUberEats);
end;
procedure TfrmGestorClient.edtLinkAppleStoreKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
begin
NextField(Key, edtLinkFacebook);
end;
procedure TfrmGestorClient.edtLinkEmailKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
begin
NextField(Key, edtLinkGooglePlay);
end;
procedure TfrmGestorClient.edtLinkFacebookKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
begin
NextField(Key, edtLinkInstagran);
end;
procedure TfrmGestorClient.edtLinkGooglePlayKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
begin
NextField(Key, edtLinkAppleStore);
end;
procedure TfrmGestorClient.edtLinkGooglePlusKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
begin
NextField(Key, edtLinkSite);
end;
procedure TfrmGestorClient.edtLinkInstagranKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
begin
NextField(Key, edtLinkTwitter);
end;
procedure TfrmGestorClient.edtLinkSiteKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
begin
NextField(Key, edtLinkEmail);
end;
procedure TfrmGestorClient.edtLinkTwitterKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
begin
NextField(Key, edtLinkYoutube);
end;
procedure TfrmGestorClient.edtLinkYoutubeKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
begin
NextField(Key, edtLinkGooglePlus);
end;
procedure TfrmGestorClient.edtRappiKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
begin
NextField(Key, edtIFood);
end;
procedure TfrmGestorClient.edtSlogamKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
begin
if Key = vkReturn then
mmTag.SetFocus;
end;
procedure TfrmGestorClient.edtTelefoneKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
begin
NextField(Key, edtContato);
end;
procedure TfrmGestorClient.edtTelefoneTyping(Sender: TObject);
begin
Formatar(Sender, TFormato.erFixoMovel);
end;
procedure TfrmGestorClient.edtUberEatsKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
begin
NextField(Key, edtRappi);
end;
procedure TfrmGestorClient.AddGrupoLista(AIdGrupo : Integer; AGrupo : String; AGrupoChecked, ANovo : Boolean);
var
AItem : TListViewItem;
AText : TListItemText;
AImage : TListItemImage;
begin
AItem := lstvGrupo.Items.Add;
AItem.Tag := AIdGrupo;
AText := AItem.Objects.FindDrawable('Text1') as TListItemText;
AText.Text := AGrupo;
AImage := AItem.Objects.FindDrawable('Image2') as TListItemImage;
case AGrupoChecked of
True : AImage.Bitmap := imgrbChecked.Bitmap;
False : AImage.Bitmap := imgrbUnChecked.Bitmap;
end;
if ANovo = True then
begin
AImage := AItem.Objects.FindDrawable('Image3') as TListItemImage;
AImage.Bitmap := imgNovo.Bitmap;
end;
end;
function TfrmGestorClient.ListaGrupos : Boolean;
var
AQtde : Boolean;
begin
AQtde := False;
lstvGrupo.Items.Clear;
LoadGrupos(cfgIdComercio);
dmGeralClient.memGrupo.First;
lstvGrupo.BeginUpdate;
while not dmGeralClient.memGrupo.Eof do
begin
var ANovo : Boolean;
if dmGeralClient.memGrupo.FieldByName('CATNOVO').AsString = 'T' then
ANovo := True else
ANovo := False;
if (cfgIdCategoria <> 0) and (dmGeralClient.memGrupo.FieldByName('IDCAT').AsInteger = cfgIdCategoria) then
begin
AddGrupoLista(dmGeralClient.memGrupo.FieldByName('IDCAT').AsInteger,
dmGeralClient.memGrupo.FieldByName('NOMECAT').AsString,
True, ANovo);
AQtde := True;
end
else
begin
AddGrupoLista(dmGeralClient.memGrupo.FieldByName('IDCAT').AsInteger,
dmGeralClient.memGrupo.FieldByName('NOMECAT').AsString,
False, ANovo);
end;
dmGeralClient.memGrupo.Next;
end;
lstvGrupo.EndUpdate;
Result := AQtde;
end;
procedure TfrmGestorClient.FormCreate(Sender: TObject);
begin
LoadStart;
cfgAlteraAvaliacao := podeAlterarAvaliacao;
imgAvaliacaoBloqueada.Visible := not cfgAlteraAvaliacao;
case cfgAlteraAvaliacao of
True : imgStatusAvaliacao.Bitmap.Assign(imgWarning.Bitmap);
False : imgStatusAvaliacao.Bitmap.Assign(imgCheck.Bitmap);
end;
end;
procedure TfrmGestorClient.LoadStart;
var
AGrupo, ASubGrupo : Boolean;
AListaTag : TStringList;
AIndex : Integer;
begin
LoadFichaComercio(cfgIdComercio);
mmDescricao.Text := dmGeralClient.memComercio.FieldByName('SOBRECOM').AsString;
edtSlogam.Text := dmGeralClient.memComercio.FieldByName('SLOGAMCOM').AsString;
try
AListaTag := TStringList.Create;
ExtractStrings([';'],[],pChar(dmGeralClient.memComercio.FieldByName('TAGCOM').AsString), AListaTag);
mmTag.Items.Clear;
for AIndex := 0 to AListaTag.Count - 1 do
mmTag.Items.Add.Text := AListaTag.Strings[AIndex];
finally
FreeAndNil(AListaTag);
end;
if (mmDescricao.Text = '') or (edtSlogam.Text = '') or (mmTag.Items.Count <= 0) then
imgStatusSobre.Bitmap.Assign(imgWarning.Bitmap) else
imgStatusSobre.Bitmap.Assign(imgCheck.Bitmap);
edtIFood.Text := dmGeralClient.memComercio.FieldByName('IFOODCOM').AsString;
edtUberEats.Text := dmGeralClient.memComercio.FieldByName('UBEREATSCOM').AsString;
edtRappi.Text := dmGeralClient.memComercio.FieldByName('RAPPICOM').AsString;
Try
cfgIdCategoria := dmGeralClient.memFichaComercio.FieldByName('IDCAT_COM').AsInteger;
Except
cfgIdCategoria := 0;
end;
lcPausaThread := TCriticalSection.Create;
getControle;
lytImages.Visible := False;
LoadControle(dmGeralClient.memControle);
CarregaListaTelefone(cfgIdComercio);
case CarregaCheckList(cfgIdComercio) of
True : imgStatusCheckList.Bitmap.Assign(imgCheck.Bitmap);
False : imgStatusCheckList.Bitmap.Assign(imgStop.Bitmap);
end;
AGrupo := ListaGrupos;
ASubGrupo := CarregaListaSubGrupo(cfgIdComercio, cfgIdCategoria);
if (AGrupo = True) and (ASubGrupo = True) then
imgStatusGrupo.Bitmap.Assign(imgCheck.Bitmap) else
imgStatusGrupo.Bitmap.Assign(imgStop.Bitmap);
case PreencheHoras of
False : imgStatusFuncionamento.Bitmap.Assign(imgWarning.Bitmap);
True : imgStatusFuncionamento.Bitmap.Assign(imgCheck.Bitmap);
end;
case ValidaRedesSociais of
True : imgStatusRedesSociais.Bitmap.Assign(imgCheck.Bitmap);
False : imgStatusRedesSociais.Bitmap.Assign(imgWarning.Bitmap);
end;
case ValidaDelivery of
True : imgStatusDelivery.Bitmap.Assign(imgCheck.Bitmap);
False : imgStatusDelivery.Bitmap.Assign(imgWarning.Bitmap);
end;
if lstvTelefones.Items.Count = 0 then
imgSTatusTelefone.Bitmap.Assign(imgStop.Bitmap) else
imgSTatusTelefone.Bitmap.Assign(imgCheck.Bitmap);
end;
procedure TfrmGestorClient.FormDestroy(Sender: TObject);
begin
if Assigned(lcPausaThread) then FreeAndNil(lcPausaThread);
end;
function MaxFotos(AQtdeFotos : Integer) : Boolean;
begin
if AQtdeFotos > cfgQtdeAnuncio then
begin
Result := True;
case MessageBox(WindowHandleToPlatform(frmGestorClient.Handle).Wnd,
pChar(uMensagens.MSG_QTDE_LIMITE_IMAGES), 'Guia Alvo',
MB_YESNO + MB_ICONQUESTION) of
ID_YES : begin
Abort;
//Mudar de plano
end;
ID_NO : begin
Abort;
//Cancela a operação
end;
end;
end
else
begin
Result := False;
end;
end;
function TfrmGestorClient.IndiceImagens : Integer;
var
fLista : TStringList;
i : Integer;
ANomeComponente : String;
begin
Try
fLista := TStringList.Create;
for i := 0 to GridLayout.ComponentCount - 1 do
begin
if GridLayout.Components[i] is TLayout then
begin
ANomeComponente := TLayout(GridLayout.Components[i]).Name;
if Pos('imgAnuncio', ANomeComponente) > 0 then
fLista.Add(ApenasNumeros(ANomeComponente));
end;
end;
fLista.Sorted := True;
finally
Try
Result := fLista.Strings[fLista.Count - 1].ToInteger;
Except
Result := 0;
end;
FreeAndNil(fLista);
end;
end;
procedure TfrmGestorClient.Image38Click(Sender: TObject);
var
pError : Boolean;
pQtdeImagens : Integer;
begin
lcIndexFotos := IndiceImagens;
pQtdeImagens := GridLayout.ChildrenCount;
if not MaxFotos(pQtdeImagens) then
begin
pError := False;
opdgImagens.Filter := 'JPG|*.jpg';
opdgImagens.Options := [TOpenOption.ofHideReadOnly,TOpenOption.ofEnableSizing, TOpenOption.ofAllowMultiSelect];
if opdgImagens.Execute then
begin
for var i := 0 to opdgImagens.Files.Count - 1 do
begin
if (ExtensaoValida(opdgImagens.Files[i], '.jpg') = True) and (SizeImgPx(opdgImagens.Files[i]) = ctrSIZEANUNCIOCOMERCIO) then
begin
lcIndexFotos := lcIndexFotos + 1;
pQtdeImagens := pQtdeImagens + 1;
CriaQuadroFotos(lcIndexFotos ,opdgImagens.Files[i]);
MaxFotos(pQtdeImagens);
end
else
begin
pError := True;
end;
end;
if pError = True then
begin
MessageBox(WindowHandleToPlatForm(Self.Handle).Wnd,
pChar('Algumas imagens não puderam ser carregadas por serem de formatos compatíveis!'+#13+
'As fotos devem ser ".jpg" no formato ' + ctrSIZEANUNCIOCOMERCIO),
'Guia Alvo', MB_OK);
Exit;
end;
end;
end;
end;
procedure TfrmGestorClient.CarregaListaTelefone(AIdCom : Integer);
begin
lstvTelefones.Items.Clear;
getTelefone(AIdCom);
dmGeralClient.memTelefones.First;
lstvTelefones.BeginUpdate;
while not dmGeralClient.memTelefones.Eof do
begin
frmGestorClient.AddFoneLista(dmGeralClient.memTelefones.FieldByName('IDFONE').AsInteger,
dmGeralClient.memTelefones.FieldByName('TELFONE').AsString,
dmGeralClient.memTelefones.FieldByName('CONTATOFONE').AsString,
dmGeralClient.memTelefones.FieldByName('ZAPFONE').AsString,
dmGeralClient.memTelefones.FieldByName('INTFONE').AsString);
dmGeralClient.memTelefones.Next;
end;
lstvTelefones.EndUpdate;
end;
procedure TfrmGestorClient.mmDescricaoKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
begin
NextField(Key, edtSlogam);
end;
procedure TfrmGestorClient.recMenu9Click(Sender: TObject);
begin
actAvaliacoes.ExecuteTarget(Self);
MenuLateral(TRectangle(Sender).Name);
end;
procedure TfrmGestorClient.recMenuTopo1Click(Sender: TObject);
begin
MenuTopo(TRectangle(Sender).Name);
end;
procedure TfrmGestorClient.recMenu10Click(Sender: TObject);
begin
MenuLateral(TRectangle(Sender).Name);
end;
procedure TfrmGestorClient.recMenu1Click(Sender: TObject);
begin
MenuLateral(TRectangle(Sender).Name);
actRedesSociais.ExecuteTarget(Self);
end;
procedure TfrmGestorClient.recCancelarClick(Sender: TObject);
begin
CarregaListaTelefone(cfgIdComercio);
edtTelefone.Text := '';
edtContato.Text := '';
chkZap.Bitmap := imgchbUnchecked.Bitmap;
chkInterno.Bitmap := imgchbUnchecked.Bitmap;
edtTelefone.SetFocus;
Label29.Text := 'ADICIONAR';
recCancelar.Visible := False;
end;
procedure TfrmGestorClient.recLogoClick(Sender: TObject);
begin
opdgImagens.Filter := 'PNG|*.png';
opdgImagens.Options := [TOpenOption.ofHideReadOnly,TOpenOption.ofEnableSizing];
if opdgImagens.Execute then
begin
if SizeImgpx(opdgImagens.FileName) <> ctrSIZELOGOCOMERCIO then
begin
MessageBox(WindowHandleToPLatform(Self.Handle).Wnd,
pChar('O logo deve ser no formato ' + ctrSIZELOGOCOMERCIO),
'Guia Alvo', MB_OK + MB_ICONEXCLAMATION);
Exit;
end
else
begin
case ExtensaoValida(opdgImagens.FileName, '.png') of
True : begin
recLogo.Fill.Bitmap.Bitmap.LoadFromFile(opdgImagens.FileName);
Label46.Visible := False;
end;
False : begin
MessageBox(WindowHandleToPlatform(Self.Handle).Wnd,
'Extensão inválida, o logo deve ser no formato .png!',
'Guia Alvo', MB_OK + MB_ICONINFORMATION);
Exit;
end;
end;
end;
end;
end;
procedure TfrmGestorClient.recMenu4Click(Sender: TObject);
begin
actCheckList.ExecuteTarget(Self);
MenuLateral(TRectangle(Sender).Name);
end;
procedure TfrmGestorClient.recMenu2Click(Sender: TObject);
begin
actDeliverys.ExecuteTarget(Self);
MenuLateral(TRectangle(Sender).Name);
end;
procedure TfrmGestorClient.recMenu6Click(Sender: TObject);
begin
actFuncionamento.ExecuteTarget(Self);
MenuLateral(TRectangle(Sender).Name);
end;
procedure TfrmGestorClient.recMenu5Click(Sender: TObject);
begin
actGrupoSubGrupo.ExecuteTarget(Self);
MenuLateral(TRectangle(Sender).Name);
end;
procedure TfrmGestorClient.recMenu7Click(Sender: TObject);
begin
actImagens.ExecuteTarget(Self);
MenuLateral(TRectangle(Sender).Name);
end;
procedure TfrmGestorClient.recOutrosGrupoClick(Sender: TObject);
begin
CarregaGruposNovos(0);
recModal.Visible := True;
recAddSubGrupo.Visible := True;
end;
procedure TfrmGestorClient.recSalvarDeliveryClick(Sender: TObject);
begin
Try
case gravaDelivery(edtUberEats.Text, edtRappi.Text, edtIFood.Text) of
True: begin
if ValidaDelivery = False then
begin
imgStatusDelivery.Bitmap := imgWarning.Bitmap;
MessageBox(WindowHandleToPlatForm(Self.Handle).Wnd,
'As informações foram salvas, porém você não cadastrou nenhuma das opções.',
'Guia Alvo', MB_OK + MB_ICONINFORMATION);
end
else
begin
imgStatusDelivery.Bitmap := imgCheck.Bitmap;
MessageBox(WindowHandleToPlatForm(Self.Handle).Wnd,
'Informações salvas com sucesso!', 'Guia Alvo', MB_OK + MB_ICONINFORMATION);
end;
end;
False: begin
MessageBox(WindowHandleToPlatForm(Self.Handle).Wnd,
pChar(ERRO_UPDATE_SOCIAIS), 'Guia Alvo', MB_OK + MB_ICONINFORMATION);
Exit;
end;
end;
Except
On E:Exception do
begin
MessageBox(WindowHandleToPlatForm(Self.Handle).Wnd,
pChar(ERRO_SESSION_LOAD), 'Guia Alvo', MB_OK + MB_ICONINFORMATION);
Exit;
end;
end;
end;
function TfrmGestorClient.ValidaRedesSociais : Boolean;
begin
if (FRedesSociais.SITECOM = '') and
(FRedesSociais.EMAILCOM = '') and
(FRedesSociais.FACECOM = '') and
(FRedesSociais.INSTACOM = '') and
(FRedesSociais.TWITERCOM = '') and
(FRedesSociais.GOOGLECOM = '') and
(FRedesSociais.TUBECOM = '') and
(FRedesSociais.APPCOM = '') and
(FRedesSociais.APPLECOM = '') then
Result := False else Result := True;
end;
function TfrmGestorClient.ValidaDelivery : Boolean;
begin
if (edtUberEats.Text = '') and
(edtRappi.Text = '') and
(edtIFood.Text = '') then
Result := False else
Result := True;
end;
procedure TfrmGestorClient.recSalvarRedesSociaisClick(Sender: TObject);
begin
Try
FRedesSociais.SITECOM := edtLinkSite.Text;
FRedesSociais.EMAILCOM := edtLinkEmail.Text;
FRedesSociais.FACECOM := edtLinkFacebook.Text;
FRedesSociais.INSTACOM := edtLinkInstagran.Text;
FRedesSociais.TWITERCOM := edtLinkTwitter.Text;
FRedesSociais.GOOGLECOM := edtLinkGooglePlus.Text;
FRedesSociais.TUBECOM := edtLinkYoutube.Text;
FRedesSociais.APPCOM := edtLinkGooglePlay.Text;
FRedesSociais.APPLECOM := edtLinkAppleStore.Text;
case FControllerRedes.SalvaRedesSociais(FRedesSociais) of
True: begin
if ValidaRedesSociais = True then
begin
imgStatusRedesSociais.Bitmap := imgWarning.Bitmap;
MessageBox(WindowHandleToPlatForm(Self.Handle).Wnd,
'As informações foram salvas, porém você não cadastrou nenhuma das opções, se realmente não possua ' +
'providencie pois no final das contas pode fazer a diferença.', 'Guia Alvo', MB_OK + MB_ICONINFORMATION);
end
else
begin
imgStatusRedesSociais.Bitmap := imgCheck.Bitmap;
MessageBox(WindowHandleToPlatForm(Self.Handle).Wnd,
'Informações salvas com sucesso!', 'Guia Alvo', MB_OK + MB_ICONINFORMATION);
end;
end;
False: begin
MessageBox(WindowHandleToPlatForm(Self.Handle).Wnd,
pChar(ERRO_UPDATE_DELIVERY), 'Guia Alvo', MB_OK + MB_ICONINFORMATION);
Exit;
end;
end;
Except
On E:Exception do
begin
MessageBox(WindowHandleToPlatForm(Self.Handle).Wnd,
pChar(ERRO_SESSION_LOAD), 'Guia Alvo', MB_OK + MB_ICONINFORMATION);
Exit;
end;
end;
end;
procedure TfrmGestorClient.recMenu8Click(Sender: TObject);
begin
actSobre.ExecuteTarget(Self);
MenuLateral(TRectangle(Sender).Name);
end;
procedure TfrmGestorClient.Rectangle17Click(Sender: TObject);
var
AStatus : Integer;
begin
if Length(ApenasNumeros(edtTelefone.Text)) < 10 then
begin
MessageBox(WindowHandleToPlatform(Self.Handle).Wnd,
'O telefone informado é inválido, verifique!',
'Guia Alvo', MB_OK + MB_ICONERROR);
edtTelefone.SetFocus;
Exit;
end;
if lcIdTelefone = 0 then
AStatus := 1 else AStatus := 2;
if TelRepetido(ApenasNumeros(edtTelefone.Text)) = AStatus then
begin
MessageBox(WindowHandleToplatform(Self.Handle).Wnd,
'O telefone informado já está cadastrado.',
'Guia Alvo', MB_OK + MB_ICONERROR);
edtTelefone.SetFocus;
Exit;
end
else
begin
TThread.CreateAnonymousThread(
procedure
begin
TThread.Synchronize(nil,
procedure
begin
Loading('Salvando...', True);
end);
AddTelefone(ApenasNumeros(edtTelefone.Text), edtContato.Text, chkZap.Tag.ToString, chkInterno.Tag.ToString, cfgIdComercio, lcIdTelefone);
CarregaListaTelefone(cfgIdComercio);
TThread.Synchronize(nil,
procedure
begin
Loading('');
Label29.Text := 'ADICIONAR';
recCancelar.Visible := False;
lcIdTelefone := 0;
edtTelefone.Text := '';
edtContato.Text := '';
chkZap.Bitmap := imgchbUnchecked.Bitmap;
chkInterno.Bitmap := imgchbUnchecked.Bitmap;
edtTelefone.SetFocus;
end);
end).Start;
end;
end;
procedure TfrmGestorClient.Rectangle20Click(Sender: TObject);
begin
if edtCheckList.Text = '' then
begin
MessageBox(WindowHandleToPlatform(Self.Handle).Wnd,
'É necessário informar um nome para a checklist',
'Guia Alvo', MB_OK + MB_ICONEXCLAMATION);
edtCheckList.SetFocus;
Exit;
end
else
begin
AddNovaCheckList(edtCheckList.Text);
edtCheckList.Text := '';
end;
end;
procedure TfrmGestorClient.Rectangle21Click(Sender: TObject);
var
AText : TListItemText;
begin
if lstvNovoCheckList.Items.Count = 0 then
begin
MessageBox(WIndowHandleToPlatForm(Self.Handle).Wnd,
'Nenhuma CheckList na lista para enviar!',
'Guia Alvo', MB_OK + MB_ICONERROR);
edtCheckList.SetFocus;
Exit;
end
else
begin
for var i := 0 to lstvNovoCheckList.Items.Count - 1 do
begin
AText := TListItemText(lstvNovoCheckList.Items[i].Objects.FindDrawable('Text1'));
AddCheckListNovo(AText.Text, cfgIdComercio);
end;
CarregaCheckList(cfgIdComercio);
MessageBox(WindowHandleToPlatForm(Self.Handle).Wnd,
'Sua solicitação de inclusão de checklist foi enviada com sucesso, ' +
'assim que aprovada sera adicionada automaticamente em seu cadastro.',
'Guia Alvo', MB_OK + MB_ICONINFORMATION);
Rectangle22Click(Self);
end;
end;
procedure TfrmGestorClient.Rectangle22Click(Sender: TObject);
begin
edtCheckList.Text := '';
lstvNovoCheckList.Items.Clear;
recAddCheckList.Visible := False;
recModal.Visible := False;
end;
procedure TfrmGestorClient.Rectangle23Click(Sender: TObject);
begin
recModal.Visible := True;
recAddCheckList.Visible := True;
end;
procedure TfrmGestorClient.Rectangle28Click(Sender: TObject);
begin
CarregaGruposNovos(0);
recModal.Visible := True;
recAddSubGrupo.Visible := True;
end;
procedure TfrmGestorClient.Rectangle29Click(Sender: TObject);
begin
recModal.Visible := True;
recAddGrupo.Visible := True;
end;
function TfrmGestorClient.ExtensaoValida(AFileName, AExtensao : String) : Boolean;
var
AExt : String;
begin
AExt := ExtractFileExt(AFileName);
if AExt <> AExtensao then
Result := False else
Result := True;
end;
procedure TfrmGestorClient.recAnuncioDestaqueClick(Sender: TObject);
begin
opdgImagens.Filter := 'JPG|*.jpg';
opdgImagens.Options := [TOpenOption.ofHideReadOnly,TOpenOption.ofEnableSizing];
if opdgImagens.Execute then
begin
if SizeImgpx(opdgImagens.FileName) <> ctrSIZEIMGDESTAKE then
begin
MessageBox(WindowHandleToPLatform(Self.Handle).Wnd,
pChar('O anúncio de destaque deve ser no formato ' + ctrSIZEIMGDESTAKE),
'Guia Alvo', MB_OK + MB_ICONEXCLAMATION);
Exit;
end
else
begin
case ExtensaoValida(opdgImagens.FileName, '.jpg') of
True : recAnuncioDestaque.Fill.Bitmap.Bitmap.LoadFromFile(opdgImagens.FileName);
False : begin
MessageBox(WindowHandleToPlatform(Self.Handle).Wnd,
'Extensão inválida, o anúncio deve ser no formato .jpg!',
'Guia Alvo', MB_OK + MB_ICONINFORMATION);
Exit;
end;
end;
end;
end;
end;
procedure TfrmGestorClient.recAnuncioPrincipalClick(Sender: TObject);
begin
opdgImagens.Filter := 'JPG|*.jpg';
opdgImagens.Options := [TOpenOption.ofHideReadOnly,TOpenOption.ofEnableSizing];
if opdgImagens.Execute then
begin
if SizeImgpx(opdgImagens.FileName) <> ctrSIZEIMGDESTAKE then
begin
MessageBox(WindowHandleToPLatform(Self.Handle).Wnd,
pChar('O anúncio principal deve ser no formato ' + ctrSIZEIMGDESTAKE),
'Guia Alvo', MB_OK + MB_ICONEXCLAMATION);
Exit;
end
else
begin
case ExtensaoValida(opdgImagens.FileName, '.jpg') of
True : recAnuncioPrincipal.Fill.Bitmap.Bitmap.LoadFromFile(opdgImagens.FileName);
False : begin
MessageBox(WindowHandleToPlatform(Self.Handle).Wnd,
'Extensão inválida, o anúncio deve ser no formato .jpg!',
'Guia Alvo', MB_OK + MB_ICONINFORMATION);
Exit;
end;
end;
end;
end;
end;
procedure TfrmGestorClient.recAnuncioSecaoClick(Sender: TObject);
begin
opdgImagens.Filter := 'JPG|*.jpg';
opdgImagens.Options := [TOpenOption.ofHideReadOnly,TOpenOption.ofEnableSizing];
if opdgImagens.Execute then
begin
if SizeImgpx(opdgImagens.FileName) <> ctrSIZEIMGDESTAKE then
begin
MessageBox(WindowHandleToPLatform(Self.Handle).Wnd,
pChar('O anúncio da seção deve ser no formato ' + ctrSIZEIMGDESTAKE),
'Guia Alvo', MB_OK + MB_ICONEXCLAMATION);
Exit;
end
else
begin
case ExtensaoValida(opdgImagens.FileName, '.jpg') of
True : recAnuncioSecao.Fill.Bitmap.Bitmap.LoadFromFile(opdgImagens.FileName);
False : begin
MessageBox(WindowHandleToPlatform(Self.Handle).Wnd,
'Extensão inválida, o anúncio deve ser no formato .jpg!',
'Guia Alvo', MB_OK + MB_ICONINFORMATION);
Exit;
end;
end;
end;
end;
end;
procedure TfrmGestorClient.Rectangle43Click(Sender: TObject);
var
ASemana : Array [1..7] of String;
AIndex : Integer;
const
AtxtSem : Array [1..7] of String = ('Seg','Ter','Qua','Qui','Sex','Sab','Dom');
begin
case ValidaHoras(Self) of
False : begin
imgStatusFuncionamento.Bitmap := imgStop.Bitmap;
MessageBox(WindowHandleToPlatform(Self.Handle).Wnd,
'Existe algum inconsistência nos horários.' + #13 +
'Corrija para continuar!',
'Guia Alvo', MB_OK + MB_ICONEXCLAMATION);
Exit;
end;
True : begin
try
for AIndex := 1 to 7 do
ASemana[AIndex] := geraHoraBD(AtxtSem[AIndex],Self);
salvaFuncionamento(cfgIdComercio, ASemana[1], ASemana[2], ASemana[3],
ASemana[4], ASemana[5], ASemana[6], ASemana[7]);
imgStatusFuncionamento.Bitmap := imgCheck.Bitmap;
MessageBox(WindowHandleToPlatform(Self.Handle).Wnd,
'Horário de funcionamento cadastrado com sucesso!',
'Guia Alvo', MB_OK + MB_ICONINFORMATION);
except on E : Exception do
begin
imgStatusFuncionamento.Bitmap := imgStop.Bitmap;
MessageBox(WindowHandleToPlatform(Self.Handle).Wnd,
pChar(format(ERRO_UPDATE_HORARIOS, [E.Message])),
'Guia Alvo', MB_OK + MB_ICONINFORMATION);
end;
end;
end;
end;
end;
procedure TfrmGestorClient.Rectangle45Click(Sender: TObject);
var
AIndex : Integer;
ATag : String;
begin
try
for AIndex := 0 to mmTag.Items.Count - 1 do
ATag := ATag + ';' + mmTag.Items[AIndex].Text;
ATag := Copy(ATag, 2, Length(ATag));
imgStatusSobre.Bitmap.Assign(imgWarning.Bitmap);
if mmDescricao.Text = '' then
begin
MessageBox(WindowHandleToPlatform(Self.Handle).Wnd,
'É necessário falar um pouco da sua empresa no campo descrição!', 'GuiaAlvo',
MB_OK + MB_ICONWARNING);
Exit;
end;
if edtSlogam.Text = '' then
begin
MessageBox(WindowHandleToPlatform(Self.Handle).Wnd,
'É necessário criar um Slogam para sua empresa!', 'GuiaAlvo',
MB_OK + MB_ICONWARNING);
Exit;
end;
if mmTag.Items.Count <= 0 then
begin
MessageBox(WindowHandleToPlatform(Self.Handle).Wnd,
'É necessário adicionar Tag´s da sua empresa, pois será através delas que ' +
'sua empresa será encontrada no aplicativo GuiaAlvo!', 'GuiaAlvo',
MB_OK + MB_ICONWARNING);
Exit;
end;
gravaSobre(mmDescricao.Text, edtSlogam.Text, ATag);
MessageBox(WindowHandleToPlatform(Self.Handle).Wnd,
'Informações salva com sucesso.', 'GuiaAlvo',
MB_OK + MB_ICONINFORMATION);
imgStatusSobre.Bitmap.Assign(imgCheck.Bitmap);
Except
end;
end;
procedure TfrmGestorClient.Rectangle49Click(Sender: TObject);
var
ASolicitacoes : Integer;
begin
TThread.CreateAnonymousThread(
procedure
begin
lcPausaThread.Enter;
try
TThread.Synchronize(nil,
procedure
begin
Loading('Validando Grupo...', True);
end);
Try
ASolicitacoes := SolicitacoesNovaCategoria;
except
MessageBox(WindowHandleToPlatForm(Self.Handle).Wnd,
pChar(ERRO_GROUP_REQUESTS),
'Guia Alvo', MB_OK + MB_ICONERROR);
Exit;
end;
TThread.Synchronize(nil,
procedure
begin
Loading('');
end);
finally
lcPausaThread.Leave;
end;
end).Start;
if ASolicitacoes >= 3 then
begin
MessageBox(WindowHandleToPlatForm(Self.Handle).Wnd,
pChar('Você ja possui ' + ASolicitacoes.ToString +
'solicitações, aguarde a analise para fazer mais solicitações caso seja necessário!'),
'Guia Alvo', MB_OK + MB_OK);
edtGrupo.SetFocus;
Exit;
end;
if Length(edtGrupo.Text) < 3 then
begin
MessageBox(WindowHandleToPlatForm(Self.Handle).Wnd,
'O campo grupo esta com o preenchimento inválido!',
'Guia Alvo', MB_OK + MB_OK);
edtGrupo.SetFocus;
Exit;
end;
if Length(mmDescricaoGrupo.Text) < 30 then
begin
MessageBox(WindowHandleToPlatForm(Self.Handle).Wnd,
'A descrição do grupo deve conter no minimo de 30 caracteres!',
'Guia Alvo', MB_OK + MB_OK);
mmDescricaoGrupo.SetFocus;
Exit;
end
else
begin
TThread.CreateAnonymousThread(
procedure
begin
TThread.Synchronize(nil,
procedure
begin
Loading('Enviando novo grupo...', True);
end);
Try
InsertCategoria(edtGrupo.Text, mmDescricaoGrupo.Text);
MessageBox(WindowHandleToPlatForm(Self.Handle).Wnd,
'Solicitação de um novo grupo enviada com sucesso, ' +
'vamos analisar as informações enviadas e assim que ' +
'aprovado você será notificado para fazer o uso deste novo grupo.',
'Guia Alvo', MB_OK + MB_ICONINFORMATION);
edtGrupo.Text := '';
ListaGrupos;
mmDescricaoGrupo.Lines.Clear;
recAddGrupo.Visible:= False;
recModal.Visible := False;
Except
MessageBox(WindowHandleToPlatForm(Self.Handle).Wnd,
pChar(ERRO_INSERT_GROUP),
'Guia Alvo', MB_OK + MB_ICONERROR);
Exit;
end;
TThread.Synchronize(nil,
procedure
begin
Loading('');
end);
end).Start;
end;
end;
procedure TfrmGestorClient.Rectangle50Click(Sender: TObject);
begin
edtGrupo.Text := '';
recAddGrupo.Visible:= False;
recModal.Visible := False;
end;
procedure TfrmGestorClient.Rectangle53Click(Sender: TObject);
var
AErro : Boolean;
begin
AErro := False;
if (chkAmbiente.Tag = 1) or (chkAtendimento.Tag = 1) or
(chkLimpeza.Tag = 1) or (chkLocalizacao.Tag = 1) or
(chkPrecos.Tag = 1) then
AErro := False else
AErro := True;
case AErro of
True : begin
MessageBox(WindowHandleToPlatform(Self.Handle).Wnd,
'Para salvar é necessário selecionar pelo menos um dos tipos de avaliação!',
'Guia Alvo', MB_ICONWARNING);
Exit;
end;
False : begin
gravaCadastroAvaliacoes(StrToBoolValue(chkAmbiente.Tag.ToString, '1', '0'),
StrToBoolValue(chkAtendimento.Tag.ToString, '1', '0'),
StrToBoolValue(chkLimpeza.Tag.ToString, '1', '0'),
StrToBoolValue(chkLocalizacao.Tag.ToString, '1', '0'),
StrToBoolValue(chkPrecos.Tag.ToString, '1', '0'));
MessageBox(WIndowHandleToPlatForm(Self.Handle).Wnd,
'Lista de avaliações salva com sucesso!',
'Guia Alvo', MB_OK + MB_ICONINFORMATION);
end;
end;
end;
procedure TfrmGestorClient.Rectangle54Click(Sender: TObject);
var
AText : TListItemText;
begin
if lstvNovoSubGrupo.Items.Count = 0 then
begin
MessageBox(WIndowHandleToPlatForm(Self.Handle).Wnd,
'Nenhum Sub-Grupo na lista para enviar!',
'Guia Alvo', MB_OK + MB_ICONERROR);
edtSubCategoria.SetFocus;
Exit;
end
else
begin
for var i := 0 to lstvNovoSubGrupo.Items.Count - 1 do
begin
AText := TListItemText(lstvNovoSubGrupo.Items[i].Objects.FindDrawable('Text1'));
InsertNewSubCategoria(lcIdChecked, AText.Text);
end;
ListaGrupos;
CarregaListaSubGrupo(cfgIdComercio, cfgIdCategoria);
MessageBox(WindowHandleToPlatForm(Self.Handle).Wnd,
'Sua solicitação de inclusão de novo(s) sub-grupo(s) foi(am) enviada(s) com sucesso, ' +
'assim que aprovada sera adicionada automaticamente em seu cadastro.',
'Guia Alvo', MB_OK + MB_ICONINFORMATION);
lstvNovoSubGrupo.Items.Clear;
Rectangle55Click(Self);
lcIdChecked := 0;
end;
end;
procedure TfrmGestorClient.MenuLateral(AAtivo : String);
var
I : Integer;
begin
for i := 1 to 10 do
begin
Application.ProcessMessages;
if TRectangle(frmGestorClient.FindComponent('RecMenu' + i.ToString)).Name = AAtivo then
TRectangle(frmGestorClient.FindComponent('RecMenu' + i.ToString)).Fill.Color := StringToAlphaColor('#FFE8EAFF') else
TRectangle(frmGestorClient.FindComponent('RecMenu' + i.ToString)).Fill.Color := TAlphaColorRec.White;
end;
end;
procedure TfrmGestorClient.MenuTopo(AAtivo : String);
var
I : Integer;
begin
for i := 1 to 5 do
begin
if TRectangle(frmGestorClient.FindComponent('recMenuTopo' + i.ToString)).Name = AAtivo then
begin
TRectangle(frmGestorClient.FindComponent('recMenuTopo' + i.ToString)).Fill.Color := StringToAlphaColor('#FF0070F9');
TFillRGBEffect(Self.FindComponent('recCorIcone' + i.ToString)).Color := TAlphaColorRec.White;
end
else
begin
TRectangle(frmGestorClient.FindComponent('recMenuTopo' + i.ToString)).Fill.Color := StringToAlphaColor('#FFC9C6C6');
TFillRGBEffect(Self.FindComponent('recCorIcone' + i.ToString)).Color := StringToAlphaColor('#FFACA8A8');
end;
end;
end;
procedure TfrmGestorClient.Rectangle55Click(Sender: TObject);
begin
recAddSubGrupo.Visible := False;
recModal.Visible := False;
lcIdChecked := 0;
end;
procedure TfrmGestorClient.recViewFotoClick(Sender: TObject);
begin
recViewFoto.Visible := False;
recViewFoto.Fill.Bitmap.Bitmap := nil;
recModal.Visible := False;
end;
procedure TfrmGestorClient.sbtnAbreClick(Sender: TObject);
begin
ReplicaHoras(Sender);
end;
procedure TfrmGestorClient.tbcGuiaAlvoChange(Sender: TObject);
begin
if tbcGuiaAlvo.ActiveTab = tbiAvaliacao then
begin
if not cfgAlteraAvaliacao then
Rectangle53.Visible := False else
Rectangle53.Visible := True;
end;
FormCreate(Self);
end;
procedure TfrmGestorClient.AddNovaCheckList(ACheckList : String);
var
AItem : TListViewItem;
AText : TListItemText;
AImage : TListItemImage;
begin
AItem := lstvNovoCheckList.Items.Add;
AText := TListItemText(AItem.Objects.FindDrawable('Text1'));
AText.Text := ACheckList;
AImage := TListItemImage(AItem.Objects.FindDrawable('Image2'));
AImage.Bitmap := imgLixeira.Bitmap;
end;
procedure TfrmGestorClient.AddNovaSubCategoria(ACheckList : String);
var
AItem : TListViewItem;
AText : TListItemText;
AImage : TListItemImage;
begin
AItem := lstvNovoSubGrupo.Items.Add;
AText := TListItemText(AItem.Objects.FindDrawable('Text1'));
AText.Text := ACheckList;
AImage := TListItemImage(AItem.Objects.FindDrawable('Image2'));
AImage.Bitmap := imgLixeira.Bitmap;
end;
procedure TfrmGestorClient.AddListaCheckList(AIdCheckList : Integer; ACheckList : String; AChecked, ANovo : Boolean);
var
AItem : TListViewItem;
AText : TListItemText;
AImage : TListItemImage;
begin
AItem := lstvCheckList.Items.Add;
AItem.Tag := AIdCheckList;
AImage := TListItemImage(AItem.Objects.FindDrawable('Image2'));
case AChecked of
True : AImage.Bitmap := imgchbChecked.Bitmap;
False : AImage.Bitmap := imgchbUnchecked.Bitmap;
end;
if ANovo = True then
begin
AImage := TListItemImage(AItem.Objects.FindDrawable('Image3'));
AImage.Bitmap := imgNovo.Bitmap;
end;
AText := TListItemText(AItem.Objects.FindDrawable('Text1'));
AText.Text := ACheckList;
end;
procedure TfrmGestorClient.AddSubGrupo(AIdSubGrupo : Integer; ASubGrupo : String; AChecked, ANovo : Boolean);
var
AItem : TListViewItem;
AText : TListItemText;
AImage : TListItemImage;
begin
AItem := lstvSubGrupo.Items.Add;
AItem.Tag := AIdSubGrupo;
AText := AItem.Objects.FindDrawable('Text1') as TListItemText;
AText.Text := ASubGrupo;
AImage := AItem.Objects.FindDrawable('Image2') as TListItemImage;
case AChecked of
True : AImage.Bitmap := imgchbChecked.Bitmap;
False : AImage.Bitmap := imgchbUnchecked.Bitmap;
end;
if ANovo = True then
begin
AImage := AItem.Objects.FindDrawable('Image3') as TListItemImage;
AImage.Bitmap := imgNovo.Bitmap;
end;
end;
function TfrmGestorClient.CarregaListaSubGrupo(AIdCom, AIdGrupo : Integer) : Boolean;
var
AQtde : Integer;
begin
AQtde := 0;
lstvSubGrupo.Items.Clear;
LoadSubGrupo(AIdGrupo);
LoadSubCatCom(AIdCom);
dmGeralClient.memSubGrupo.First;
dmGeralClient.memSubCatCom.First;
while not dmGeralClient.memSubGrupo.Eof do
begin
dmGeralClient.memSubCatCom.Filter := 'ID_SUBCAT = ' + dmGeralClient.memSubGrupo.FieldByName('IDSUBCAT').AsString;
dmGeralClient.memSubCatCom.Filtered := True;
var ANovo : Boolean;
if dmGeralClient.memSubGrupo.FieldByName('SUBCATNOVO').AsString = 'T' then
ANovo := True else
ANovo := False;
if dmGeralClient.memSubCatCom.RecordCount = 0 then
begin
AddSubGrupo(dmGeralClient.memSubGrupo.FieldByName('IDSUBCAT').AsInteger,
dmGeralClient.memSubGrupo.FieldByName('NOMESUBCAT').AsString,
False, ANovo);
end
else
begin
AddSubGrupo(dmGeralClient.memSubGrupo.FieldByName('IDSUBCAT').AsInteger,
dmGeralClient.memSubGrupo.FieldByName('NOMESUBCAT').AsString,
True, ANovo);
AQtde := AQtde + 1;
end;
dmGeralClient.memSubGrupo.Next;
end;
if AQtde > 0 then
Result := True else
Result := False;
end;
function TfrmGestorClient.CarregaCheckList(AIdCom : Integer) : Boolean;
var
i : Integer;
begin
i := 0;
lstvCheckList.Items.Clear;
LoadCheckList;
LoadCheckListSelected(cfgIdComercio);
dmGeralClient.memCheckList.First;
lstvCheckList.BeginUpdate;
while not dmGeralClient.memCheckList.Eof do
begin
dmGeralClient.memCheckListSelected.Filter := 'IDCHECK = ' + QuotedStr(dmGeralClient.memCheckList.FieldByName('IDCHECK').AsString);
dmGeralClient.memCheckListSelected.Filtered := True;
var AChecked : Boolean;
if dmGeralClient.memCheckListSelected.RecordCount > 0 then
AChecked := True else AChecked := False;
var ANovo : Boolean;
if dmGeralClient.memCheckList.FieldByName('NOVOCHECK').AsString = 'T' then
ANovo := True else ANovo := False;
AddListaCheckList(dmGeralClient.memCheckList.FieldByName('IDCHECK').AsInteger,
dmGeralClient.memCheckList.FieldByName('DESCRCHECK').AsString,
AChecked, ANovo);
if AChecked = True then
i := i + 1;
dmGeralClient.memCheckList.Next;
end;
lstvCheckList.EndUpdate;
if i > 0 then
Result := True else
Result := False;
end;
procedure TfrmGestorClient.CarregaGruposNovos(AIdChecked : Integer);
begin
TThread.CreateAnonymousThread(
procedure
var
pNovo : Boolean;
begin
Try
LoadGrupos(cfgIdComercio, 'T');
dmGeralClient.memGrupo.First;
lstvGrupoListaGrupos.Items.Clear;
while not dmGeralClient.memGrupo.Eof do
begin
if dmGeralClient.memGrupo.FieldByName('CATNOVO').AsString = 'T' then
pNovo := True else
pNovo := False;
if AIdChecked = dmGeralClient.memGrupo.FieldByName('IDCAT').AsInteger then
AddGruposNovos(dmGeralClient.memGrupo.FieldByName('IDCAT').AsInteger,
dmGeralClient.memGrupo.FieldByName('NOMECAT').AsString,
pNovo, True) else
AddGruposNovos(dmGeralClient.memGrupo.FieldByName('IDCAT').AsInteger,
dmGeralClient.memGrupo.FieldByName('NOMECAT').AsString,
pNovo, False);
dmGeralClient.memGrupo.Next;
end;
Except
MessageBox(WindowHandleToPlatForm(Self.Handle).Wnd,
pChar(ERRO_LIST_GROUP),
'Guia Alvo', MB_OK + MB_ICONERROR);
Exit;
end;
end).Start;
end;
procedure TfrmGestorClient.AddGruposNovos(AIdGrupo : Integer; AGrupo : String; ANovo, AChecked : Boolean);
var
AItem : TListViewItem;
AText : TListItemText;
AImage : TListItemImage;
begin
AItem := lstvGrupoListaGrupos.Items.Add;
AItem.Tag := AIdGrupo;
AText := AItem.Objects.FindDrawable('Text1') as TListItemText;
AText.Text := AGrupo;
case AChecked of
True : begin
AImage := AItem.Objects.FindDrawable('Image2') as TListItemImage;
AImage.Bitmap := imgrbChecked.Bitmap;
end;
False : begin
AImage := AItem.Objects.FindDrawable('Image2') as TListItemImage;
AImage.Bitmap := imgrbUnchecked.Bitmap;
end;
end;
if ANovo = True then
begin
AImage := AItem.Objects.FindDrawable('Image3') as TListItemImage;
AImage.Bitmap := imgNovo.Bitmap;
if lcIdChecked = 0 then
begin
lcIdChecked := AIdGrupo;
AImage := AItem.Objects.FindDrawable('Image2') as TListItemImage;
AImage.Bitmap := imgrbChecked.Bitmap;
end;
end;
end;
procedure TfrmGestorClient.recMenu3Click(Sender: TObject);
begin
actTelefones.ExecuteTarget(Self);
MenuLateral(TRectangle(Sender).Name);
end;
procedure TMyThread.LoadingImages(APathFtp, ANomeImage : String; AImage : TImage; AListImage : TListItemImage; ALoading : TAniIndicator);
begin
With frmGestorClient do
begin
MyThread := TMyThread.create;
MyThread.FUrlFtp := APathFtp;
MyThread.FFileFtp := ANomeImage;
if AImage = nil then
MyThread.FImage := AListImage else
MyThread.FimgImage := AImage;
if ALoading <> nil then
MyThread.FAniLoading := ALoading;
MyThread.FreeOnTerminate := True;
MyThread.Start;
end;
end;
{ TMyThread }
constructor TMyThread.create;
begin
inherited Create(True);
end;
procedure TMyThread.Execute;
var
AFtp : TIdFTP;
begin
inherited;
Self.Fms := TMemoryStream.Create;
Self.Fms.Position := 0;
AFtp := TIdFTP.Create;
ConectaFTP(AFtp);
AFtp.ChangeDir(Self.FUrlFtp);
AFtp.TransferType := ftBinary;
AFtp.Get(Self.FFileFtp, Self.Fms);
Synchronize(
procedure
var
img : TImage;
begin
img := TImage.Create(nil);
img.Bitmap.LoadFromStream(Self.Fms);
if FImage <> nil then
begin
Self.FImage.Bitmap := img.Bitmap;
Self.FImage.OwnsBitmap := True;
end
else
begin
Self.FimgImage.Bitmap := img.Bitmap;
if FAniLoading <> nil then
begin
FAniLoading.Enabled := False;
FAniLoading.Visible := False;
end;
end;
img.DisposeOf;
Self.Fms.DisposeOf;
AFtp.DisposeOf;
end);
end;
end.
|
{$I CetusOptions.inc}
unit ctsPointerInterface;
interface
uses
ctsTypesDef,
ctsBaseInterfaces;
type
TctsDataType = Pointer;
{.$I template\ctsStructIntf.inc}
// ctsStruct.int
PctsDataType = ^TctsDataType;
TctsDisposeEvent = procedure(AData: TctsDataType) of object;
TctsCompareEvent = function(AData1, AData2: TctsDataType): LongInt of object;
TctsNotifyEvent = procedure(AValue: TctsDataType; ANotifyAction: TctsNotifyAction) of object;
// observer
IctsObserver = interface(IctsBaseObserver)
['{89848C61-C6B6-4CAE-BF5B-5D02A9D482F4}']
function GetOnChanged: TctsNotifyEvent;
procedure SetOnChanged(const AValue: TctsNotifyEvent);
property OnChanged: TctsNotifyEvent read GetOnChanged write SetOnChanged;
end;
IctsObserverGenerator = interface(IctsObserverRegister)
['{96D5A9AE-F62A-4409-9406-AD59C5BDEADE}']
function GenerateObserver: IctsObserver;
end;
// iterator
IctsIterator = interface(IUnknown)
['{3BED617C-AF2E-4003-8FE5-3B73856404B0}']
function GetData: TctsDataType;
function HasNext: Boolean;
function HasPrior: Boolean;
procedure Insert(AItem: TctsDataType);
procedure Next;
procedure Prior;
procedure Remove;
procedure SetData(const aData: TctsDataType);
property Data: TctsDataType read GetData write SetData;
end;
// collection vector list.
IctsCollection = interface(IctsContainer)
['{4ABAFAC4-F71A-4275-8216-254C284B28B5}']
procedure Add(const AItem: TctsDataType);
procedure Clear;
function Contain(const AItem: TctsDataType): Boolean;
function First: IctsIterator;
function GetCompare: TctsCompareEvent;
function GetDispose: TctsDisposeEvent;
function IsSorted: Boolean;
function Last: IctsIterator;
procedure Pack;
function Remove(const AItem: TctsDataType): Boolean;
procedure SetCompare(const AValue: TctsCompareEvent);
procedure SetDispose(const AValue: TctsDisposeEvent);
procedure Sort;
{$IFDEF USE_Object}
function GetOwnsObjects: Boolean;
procedure SetOwnsObjects(const Value: Boolean);
property OwnsObjects: Boolean read GetOwnsObjects write SetOwnsObjects;
{$ENDIF}
property Compare: TctsCompareEvent read GetCompare write SetCompare;
property Dispose: TctsDisposeEvent read GetDispose write SetDispose;
end;
PctsArray = ^TctsArray;
TctsArray = array[0..ctsMaxBlockSize - 1] of TctsDataType;
IctsVector = interface(IctsCollection)
['{E5C83823-912C-4B42-88BB-E336A0D73329}']
procedure Delete(const AIndex: LongInt);
function GetArray: PctsArray;
function GetCapacity: LongInt;
function GetItems(AIndex: LongInt): TctsDataType;
function IndexOf(const AItem: TctsDataType): LongInt;
procedure Insert(const AIndex: LongInt; const AItem: TctsDataType);
procedure SetCapacity(const AValue: LongInt);
procedure SetItems(AIndex: LongInt; const AItem: TctsDataType);
property Capacity: LongInt read GetCapacity write SetCapacity;
property Items[AIndex: LongInt]: TctsDataType read GetItems write SetItems; default;
end;
PctsNode = ^TctsNode;
TctsNode = packed record
Data: TctsDataType;
case Boolean of
False: (Link: PctsNode);
True: (Next, Prior: PctsNode)
end;
IctsList = interface(IctsCollection)
['{23A434F6-388E-4578-BB4F-014C815796BE}']
procedure DeleteNode(aNode: PctsNode);
function GetHead: PctsNode;
function GetTail: PctsNode;
procedure InsertNode(aNode: PctsNode; const AItem: TctsDataType);
end;
// stack and queue
IctsOrderOperator = interface(IctsBaseContainer)
['{A544295E-C7A5-44C0-9974-65E8A6AB2F3C}']
procedure Pop;
procedure Push(const aItem: TctsDataType);
end;
IctsStack = interface(IctsOrderOperator)
['{792A684C-33A6-4F62-88AA-7BC7A5726EE9}']
function Top: TctsDataType;
end;
IctsQueue = interface(IctsOrderOperator)
['{61B33183-C6BA-44B0-9D8D-1F29906D6AEF}']
function Back: TctsDataType;
function Front: TctsDataType;
end;
implementation
end.
|
unit PrintMOParams;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, FIBQuery, pFIBQuery,
pFIBStoredProc, DB, FIBDataSet, pFIBDataSet, FIBDatabase, pFIBDatabase,
cxControls, cxContainer, cxEdit, cxCheckBox, cxTextEdit, cxMaskEdit,
cxDropDownEdit, cxMRUEdit, frxClass, frxDBSet, uneTypes, cxSpinEdit,
frxExportPDF, frxExportImage, frxExportRTF, frxExportXML, frxExportXLS,
frxExportHTML, frxExportTXT, frxDesgn, ibase, cxRadioGroup;
type
//Перечисляемый тип для определения типа преобразований
TEnm_TypeCoversion = ( ctIntToSet, ctSetToInt );
TfrmGetMOParams = class(TForm)
dbWork : TpFIBDatabase;
trRead : TpFIBTransaction;
trWrite : TpFIBTransaction;
dstWork : TpFIBDataSet;
spcWork : TpFIBStoredProc;
btnOK : TcxButton;
btnCancel : TcxButton;
gbxPeriod : TGroupBox;
lblYear : TLabel;
lblMonth : TLabel;
edtYear : TcxSpinEdit;
edtMonth : TcxMRUEdit;
frxDS: TfrxDBDataset;
dstWork_DOT: TpFIBDataSet;
cxRadioButton1: TcxRadioButton;
cxRadioButton2: TcxRadioButton;
frxReport1: TfrxReport;
procedure FormShortCut (var Msg: TWMKey; var Handled: Boolean);
procedure btnOKClick(Sender: TObject);
public
fidsystem:Integer;
constructor Create( AOwner:TComponent; dbHandle:TISC_DB_HANDLE; id_system:Integer ); reintroduce;
procedure FillMonthList(var aMonthList: TStringList; const aFillMode: TFillMode );
end;
implementation
uses DateUtils, uneUtils;
{$R *.dfm}
procedure TfrmGetMOParams.FillMonthList(var aMonthList: TStringList; const aFillMode: TFillMode );
var
i, n : Integer;
begin
try
try
case aFillMode of
fmInc : begin
end;
fmDec : begin
end;
fmFull : begin
n := High( cMonthUA );
for i := Low( cMonthUA ) to n
do begin
aMonthList.Add( cMonthUA[i] )
end;
end;
end;
except
//Протоколируем ИС
end;
except
on E: Exception
do begin
MessageBox( Handle, PChar( sErrorTextExtUA + E.Message ), PChar( sMsgCaptionErrUA ), MB_OK or MB_ICONERROR );
end;
end;
end;
constructor TfrmGetMOParams.Create(AOwner:TComponent; dbHandle:TISC_DB_HANDLE; id_system:Integer);
var FillMode : TFillMode;
MonthList :TStringList;
IndexSearch:Integer;
begin
inherited Create(AOwner );
Self.fidsystem:=id_system;
Self.dbWork.Handle:=dbHandle;
self.trRead.StartTransaction;
MonthList := TStringList.Create;
FillMode := fmFull;
FillMonthList( MonthList, FillMode );
edtMonth.Properties.LookupItems.AddStrings( MonthList );
edtYear.Value:=YearOf(Date);
edtYear.Properties.MinValue := 2011;
edtYear.Properties.MaxValue := 2050;
IndexSearch := edtMonth.Properties.LookupItems.IndexOf( cMonthUA[MonthOf( Date ) - 1] );
if IndexSearch = -1
then begin
edtMonth.Text := edtMonth.Properties.LookupItems.Strings[0];
end
else begin
edtMonth.Text := cMonthUA[MonthOf( Date ) - 1]
end;
end;
procedure TfrmGetMOParams.FormShortCut(var Msg: TWMKey;
var Handled: Boolean);
begin
case Msg.CharCode of
VK_F10 : begin
ModalResult := mrOk;
Handled := True;
end;
VK_ESCAPE : begin
ModalResult := mrCancel;
Handled := True;
end;
end;
end;
procedure TfrmGetMOParams.btnOKClick(Sender: TObject);
var i,n:Integer;
pCurrPeriod:TDateTime;
begin
Screen.Cursor:=crHourGlass;
//Получаем дату, соответствующую выбранному пользователем периоду
n := High( cMonthUA );
for i := Low( cMonthUA ) to n
do begin
if edtMonth.Text = cMonthUA[i] then Break;
end;
pCurrPeriod := EncodeDate( StrToInt( edtYear.Text ), i + 1, cFIRST_DAY_OF_MONTH );
if dstWork_DOT.Active then dstWork_DOT.Close;
dstWork_DOT.SelectSQL.Text:='select * from JO5_GET_MO_TITLE_PARAMS('+''''+DateToStr(pCurrPeriod)+''''+','+IntTostr(self.fidsystem)+')';
dstWork_DOT.Open;
if cxRadioButton1.Checked
then begin
//отбираем данные по МО
if dstWork.Active then dstWork.Close;
dstWork.SelectSQL.Text:='select * from JO5_GET_MO('+''''+DateToStr(pCurrPeriod)+''''+','+IntTostr(self.fidsystem)+',-1) where suma<>0 order by OPER_TEXT';
dstWork.Open;
end
else begin
//отбираем данные по МО
if dstWork.Active then dstWork.Close;
dstWork.SelectSQL.Text:='select * from JO5_GET_MO_D_FULL('+''''+DateToStr(pCurrPeriod)+''''+','+IntTostr(self.fidsystem)+',-1) order by PROGRAM_TEXT, TF_TEXT, smeta_kod asc';
dstWork.Open;
end;
Screen.Cursor:=crDefault;
if cxRadioButton1.Checked
then frxReport1.LoadFromFile(ExtractFilePath(Application.ExeName)+'\Reports\Jo5\JO5_MO.fr3')
else frxReport1.LoadFromFile(ExtractFilePath(Application.ExeName)+'\Reports\Jo5\JO5_MO_D.fr3');
if cxRadioButton1.Checked
then begin
if dstWork_DOT.RecordCount>0
then begin
frxReport1.Variables['organization'] :=''''+dstWork_DOT.FieldByName('name_customer').AsString+'''';
frxReport1.Variables['OKPO'] :=''''+dstWork_DOT.FieldByName('kod_edrpou').AsString+'''';
frxReport1.Variables['PERIOD'] :=''''+edtMonth.Text+' '+edtYear.Text+'''';
frxReport1.Variables['SYS_TITLE'] :=''''+dstWork_DOT.FieldByName('sys_title').AsString+'''';
end
else begin
frxReport1.Variables['ORGANIZATION'] :='';
frxReport1.Variables['OKPO'] :='';
frxReport1.Variables['PERIOD'] :='';
end;
end
else begin
if dstWork_DOT.RecordCount>0
then begin
frxReport1.Variables['PERIOD'] :=''''+edtMonth.Text+' '+edtYear.Text+'''';
end
else begin
frxReport1.Variables['PERIOD'] :='';
end;
end;
frxReport1.PrepareReport(true);
frxReport1.ShowPreparedReport;
end;
end.
|
unit Objekt.SepaBSHeader;
interface
uses
SysUtils, Classes, Objekt.SepaBSPosList;
type
TSepaBSHeader = class
private
fIBAN: string;
fAuftraggeber: string;
fBIC: string;
fBS: TSepaBSPosList;
fZahlDatum: TDateTime;
fPmtMtd: string;
fPmtInfId: string;
fChrgBr: string;
fMsgId: string;
fChanged: Boolean;
function getCtrlSum: Currency;
function getNbOfTxs: Integer;
function getMsgId: string;
function getPmtInfId: string;
public
constructor Create;
destructor Destroy; override;
procedure Init;
property IBAN: string read fIBAN write fIBAN;
property Auftraggeber: string read fAuftraggeber write fAuftraggeber;
property BIC: string read fBIC write fBIC;
property BS: TSepaBSPosList read fBS write fBS;
property ZahlDatum: TDateTime read fZahlDatum write fZahlDatum;
property PmtInfId: string read getPmtInfId write fPmtInfId;
property PmtMtd: string read fPmtMtd write fPmtMtd;
property NbOfTxs: Integer read getNbOfTxs;
property CtrlSum: Currency read getCtrlSum;
property ChrgBr: string read fChrgBr write fChrgBr;
property MsgId: string read getMsgId write fMsgId;
property Changed: Boolean read fChanged write fChanged;
end;
implementation
{ TSepaBSHeader }
constructor TSepaBSHeader.Create;
begin
fBS := TSepaBSPosList.Create;
fChanged := false;
Init;
end;
destructor TSepaBSHeader.Destroy;
begin
FreeAndNil(fBS);
inherited;
end;
function TSepaBSHeader.getCtrlSum: Currency;
var
i1: Integer;
begin
Result := 0;
for i1 := 0 to fBS.Count -1 do
Result := Result + fBS.Item[i1].Betrag;
end;
function TSepaBSHeader.getMsgId: string;
begin
if fMsgId = '' then
fMsgId := FormatDateTime('yyyy-mm-dd hh:mm:nn:zzz', now);
Result := fMsgId;
end;
function TSepaBSHeader.getNbOfTxs: Integer;
var
i1: Integer;
begin
Result := 0;
for i1 := 0 to fBS.Count -1 do
Inc(Result);
end;
function TSepaBSHeader.getPmtInfId: string;
begin
if fPmtInfId = '' then
fPmtInfId := FormatDateTime('yyyymmddhhnnsszzz', now);
Result := fPmtInfId;
end;
procedure TSepaBSHeader.Init;
begin
fIBAN := '';
fAuftraggeber := '';
fBIC := '';
fZahldatum := StrToDate('01.01.1999');
fPmtMtd := '';
fPmtInfId := '';
fChrgBr := '';
end;
end.
|
//---------------------------------------------------------------------------
// 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 FormShareComponent;
interface
uses
System.Classes, System.ImageList, System.Win.ShareContract, System.Win.WinRT, WinAPI.ApplicationModel.DataTransfer,
Vcl.Forms, Vcl.ShareContract, Vcl.ImgList, Vcl.Controls, Vcl.StdCtrls, Vcl.ExtCtrls;
type
TFShareComponent = class(TForm)
Memo1: TMemo;
Panel1: TPanel;
Label1: TLabel;
ButtonShare: TButton;
EditShareText: TEdit;
ShareContractComponent: TSharingContract;
Label2: TLabel;
EditApplicationName: TEdit;
Label3: TLabel;
EditDescription: TEdit;
Label4: TLabel;
EditPackageName: TEdit;
Label5: TLabel;
EditWebAddress: TEdit;
Label6: TLabel;
EditContentSourceWebLink: TEdit;
Label7: TLabel;
EditContentSourceApplicationLink: TEdit;
Label8: TLabel;
EditDataTitle: TEdit;
ImageList1: TImageList;
procedure ButtonShareClick(Sender: TObject);
procedure ShareContractComponentAppChosen(const Sender: TObject; const AManager: IDataTransferManager;
const Args: ITargetApplicationChosenEventArgs);
procedure ShareContractComponentTranferImage(const Sender: TObject; const ARequest: IDataProviderRequest);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FShareComponent: TFShareComponent;
implementation
uses
System.SysUtils, System.IOUtils;
{$R *.dfm}
procedure TFShareComponent.ButtonShareClick(Sender: TObject);
begin
// Set the shared properties
ShareContractComponent.ApplicationName := EditApplicationName.Text;
ShareContractComponent.Description := EditDescription.Text;
ShareContractComponent.DataTitle := EditDataTitle.Text;
ShareContractComponent.DataText := EditShareText.Text;
ShareContractComponent.PackageName := EditPackageName.Text;
ShareContractComponent.ContentSourceApplicationLink := EditContentSourceApplicationLink.Text;
ShareContractComponent.ContentSourceWebLink := EditContentSourceWebLink.Text;
ShareContractComponent.IconFile := 'Penguins.bmp';
ShareContractComponent.ImageFile := 'Penguins.jpg';
ShareContractComponent.LogoFile := 'Penguins.bmp';
ShareContractComponent.RtfText := 'This is the RTF Text. Should be a large RTF text that is shared...';
ShareContractComponent.HTML := '<p>Here is our store logo: <img src=''Penguins.bmp''>.</p>';
ShareContractComponent.WebAddress := EditWebAddress.Text;
// Launch Sharing process. Shows applications that can receive our shared information.
ShareContractComponent.InitSharing;
end;
procedure TFShareComponent.ShareContractComponentAppChosen(const Sender: TObject; const AManager: IDataTransferManager;
const Args: ITargetApplicationChosenEventArgs);
begin
// With this event we can know which application is going to receive our data.
Memo1.Lines.Add('Application Chosen: ' + args.ApplicationName.ToString);
end;
procedure TFShareComponent.ShareContractComponentTranferImage(const Sender: TObject; const ARequest: IDataProviderRequest);
begin
// We must provide the stream with the data, the source of the stream can be any we can imagine. Hence the event
// to retrieve it.
// For testing purposes we do the same that we do in the TShareContract class.
ARequest.SetData(TShareContract.FileNameToStream(TShareContract(Sender).ImageFile));
end;
end.
|
unit uClienteDAOClient;
interface
uses DBXCommon, DBXClient, DBXJSON, DSProxy, Classes, SysUtils, DB, SqlExpr, DBXDBReaders, Generics.Collections, DBXJSONReflect, Cliente;
type
TClienteDAOClient = class(TDSAdminClient)
private
FListCommand: TDBXCommand;
FNextCodigoCommand: TDBXCommand;
FInsertCommand: TDBXCommand;
FUpdateCommand: TDBXCommand;
FDeleteCommand: TDBXCommand;
FFindByCodigoCommand: TDBXCommand;
public
constructor Create(ADBXConnection: TDBXConnection); overload;
constructor Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); overload;
destructor Destroy; override;
function List: TDBXReader;
function NextCodigo: string;
function Insert(Cliente: TCliente): Boolean;
function Update(Cliente: TCliente): Boolean;
function Delete(Cliente: TCliente): Boolean;
function FindByCodigo(Codigo: string): TCliente;
end;
implementation
function TClienteDAOClient.List: TDBXReader;
begin
if FListCommand = nil then
begin
FListCommand := FDBXConnection.CreateCommand;
FListCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FListCommand.Text := 'TClienteDAO.List';
FListCommand.Prepare;
end;
FListCommand.ExecuteUpdate;
Result := FListCommand.Parameters[0].Value.GetDBXReader(FInstanceOwner);
end;
function TClienteDAOClient.NextCodigo: string;
begin
if FNextCodigoCommand = nil then
begin
FNextCodigoCommand := FDBXConnection.CreateCommand;
FNextCodigoCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FNextCodigoCommand.Text := 'TClienteDAO.NextCodigo';
FNextCodigoCommand.Prepare;
end;
FNextCodigoCommand.ExecuteUpdate;
Result := FNextCodigoCommand.Parameters[0].Value.GetWideString;
end;
function TClienteDAOClient.Insert(Cliente: TCliente): Boolean;
begin
if FInsertCommand = nil then
begin
FInsertCommand := FDBXConnection.CreateCommand;
FInsertCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FInsertCommand.Text := 'TClienteDAO.Insert';
FInsertCommand.Prepare;
end;
if not Assigned(Cliente) then
FInsertCommand.Parameters[0].Value.SetNull
else
begin
FMarshal := TDBXClientCommand(FInsertCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler;
try
FInsertCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(Cliente), True);
if FInstanceOwner then
Cliente.Free
finally
FreeAndNil(FMarshal)
end
end;
FInsertCommand.ExecuteUpdate;
Result := FInsertCommand.Parameters[1].Value.GetBoolean;
end;
function TClienteDAOClient.Update(Cliente: TCliente): Boolean;
begin
if FUpdateCommand = nil then
begin
FUpdateCommand := FDBXConnection.CreateCommand;
FUpdateCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FUpdateCommand.Text := 'TClienteDAO.Update';
FUpdateCommand.Prepare;
end;
if not Assigned(Cliente) then
FUpdateCommand.Parameters[0].Value.SetNull
else
begin
FMarshal := TDBXClientCommand(FUpdateCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler;
try
FUpdateCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(Cliente), True);
if FInstanceOwner then
Cliente.Free
finally
FreeAndNil(FMarshal)
end
end;
FUpdateCommand.ExecuteUpdate;
Result := FUpdateCommand.Parameters[1].Value.GetBoolean;
end;
function TClienteDAOClient.Delete(Cliente: TCliente): Boolean;
begin
if FDeleteCommand = nil then
begin
FDeleteCommand := FDBXConnection.CreateCommand;
FDeleteCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FDeleteCommand.Text := 'TClienteDAO.Delete';
FDeleteCommand.Prepare;
end;
if not Assigned(Cliente) then
FDeleteCommand.Parameters[0].Value.SetNull
else
begin
FMarshal := TDBXClientCommand(FDeleteCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler;
try
FDeleteCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(Cliente), True);
if FInstanceOwner then
Cliente.Free
finally
FreeAndNil(FMarshal)
end
end;
FDeleteCommand.ExecuteUpdate;
Result := FDeleteCommand.Parameters[1].Value.GetBoolean;
end;
function TClienteDAOClient.FindByCodigo(Codigo: string): TCliente;
begin
if FFindByCodigoCommand = nil then
begin
FFindByCodigoCommand := FDBXConnection.CreateCommand;
FFindByCodigoCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FFindByCodigoCommand.Text := 'TClienteDAO.FindByCodigo';
FFindByCodigoCommand.Prepare;
end;
FFindByCodigoCommand.Parameters[0].Value.SetWideString(Codigo);
FFindByCodigoCommand.ExecuteUpdate;
if not FFindByCodigoCommand.Parameters[1].Value.IsNull then
begin
FUnMarshal := TDBXClientCommand(FFindByCodigoCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler;
try
Result := TCliente(FUnMarshal.UnMarshal(FFindByCodigoCommand.Parameters[1].Value.GetJSONValue(True)));
if FInstanceOwner then
FFindByCodigoCommand.FreeOnExecute(Result);
finally
FreeAndNil(FUnMarshal)
end
end
else
Result := nil;
end;
constructor TClienteDAOClient.Create(ADBXConnection: TDBXConnection);
begin
inherited Create(ADBXConnection);
end;
constructor TClienteDAOClient.Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean);
begin
inherited Create(ADBXConnection, AInstanceOwner);
end;
destructor TClienteDAOClient.Destroy;
begin
FreeAndNil(FListCommand);
FreeAndNil(FNextCodigoCommand);
FreeAndNil(FInsertCommand);
FreeAndNil(FUpdateCommand);
FreeAndNil(FDeleteCommand);
FreeAndNil(FFindByCodigoCommand);
inherited;
end;
end.
|
{*
FtermSSH : An SSH implementation in Delphi for FTerm2 by kxn@cic.tsinghua.edu.cn
Cryptograpical code from OpenSSL Project
*}
unit sshwsock;
interface
uses Classes, WSocket, sshsession, sshutil;
type
TSSHSockState = (dsBeforeSession, dsSockVersion, dsSockSession);
TSSHWSocket = class(TWSocket)
private
InternalBuf: TSSHBuffer;
state: TSSHSockState;
FisSSH: boolean;
procedure OnAuthUser(Sender: TSSHSession; var user: string; var canceled: boolean);
procedure OnAuthPass(Sender: TSSHSession; var pass: string; var canceled: boolean);
protected
Version: integer;
FirstPass: boolean;
Session: TSSHSession;
function TriggerDataAvailable(Error: word): boolean; override;
function ChooseVersion(Ver: string): integer;
procedure TriggerSessionConnected(Error: word); override;
function ShowAuthForm(tag: integer): boolean;
public
HmacBug: boolean;
//isBBS: boolean;
preferversion : integer;
sshuser, sshpass: string;
cols, rows: integer;
stermtype: string;
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
procedure SetIsSSH(Value: boolean);
procedure AddData(Data: Pointer; Len: integer);
procedure InternalClose(bShut: boolean; Error: word); override;
procedure DoTriggerSessionConnected(Error: word);
function Receive(Buffer: Pointer; BufferSize: integer): integer; override;
function MySend(Data: Pointer; Len: integer): integer; // work-around
function Send(Data: Pointer; Len: integer): integer; override;
procedure SetSSHUserPass(ValueUser, ValuePass: string);
procedure SetWindowSize(cols, rows: integer);
property IsSSH: boolean read FisSSH write SetIsSSH;
end;
implementation
uses Math, Dialogs, sshkex, SysUtils, forms, sshauthfrm, controls;
{ TSSHWSocket }
const
V1Str: string = 'SSH-1.5-FTermSSH';
V2Str: string = 'SSH-2.0-FTermSSH';
procedure TSSHWSocket.AddData(Data: Pointer; Len: integer);
var
error: word;
begin
error := 0;
InternalBuf.Add(Data, Len);
if Assigned(FOnDataAvailable) then repeat
FOnDataAvailable(Self, Error);
until InternalBuf.Length = 0;
end;
function TSSHWSocket.ChooseVersion(Ver: string): integer;
var
s: string;
RemoteV: string;
rp : integer;
begin
if Copy(Ver, 1, 4) <> 'SSH-' then
begin
Result := -1;
exit;
end;
s := Copy(Ver, 5, 1);
if s = '1' then Result := 1
else if s = '2' then Result := 2
else
Result := -1;
{fuse: remote version str pos }
rp := Pos('SSH_', Ver);
RemoteV := Copy(Ver, rp+4, 4);
if RemoteV[1] = '2' then begin
if preferversion = 1 then Result := 1
else Result := 2;
end;
{ if (RemoteV = '2.0.') or (RemoteV = '2.1.') or (RemoteV = '2.2.') or (RemoteV = '2.3.') then
HmacBug := True
else
Hmacbug := False;
}
end;
constructor TSSHWSocket.Create(aOwner: TComponent);
begin
inherited;
if FisSSH then
begin
InternalBuf := TSSHBuffer.Create(1024);
end;
FirstPass := True;
end;
destructor TSSHWSocket.Destroy;
begin
if FisSSH then
begin
if Assigned(Session) then
begin
Session.Free;
Session := nil;
end;
if Assigned(InternalBuf) then InternalBuf.Free;
end;
inherited;
end;
procedure TSSHWSocket.SetIsSSH(Value: boolean);
begin
FisSSH := Value;
if FisSSH and not Assigned(InternalBuf) then
begin
InternalBuf := TSSHBuffer.Create(1024);
end;
end;
procedure TSSHWSocket.DoTriggerSessionConnected(Error: word);
begin
if Assigned(FOnSessionConnected) then FOnSessionConnected(Self, Error);
end;
procedure TSSHWSocket.InternalClose(bShut: boolean; Error: word);
begin
inherited InternalClose(bShut, Error);
if FisSSH and Assigned(Session) then
begin
// Session.Disconnect('User Close');
Session.Free;
Session := nil;
state := dsBeforeSession;
end;
end;
function TSSHWSocket.MySend(Data: Pointer; Len: integer): integer;
begin
Result := inherited Send(Data, Len);
end;
function TSSHWSocket.Receive(Buffer: Pointer;
BufferSize: integer): integer;
var
len: integer;
begin
if FisSSH then
begin
if state = dsBeforeSession then
begin
Result := inherited Receive(Buffer, BufferSize);
end
else
begin
if Assigned(InternalBuf) then
begin
len := Min(bufferSize, InternalBuf.Length);
InternalBuf.GetBuffer(Buffer, len);
Result := Len;
end
else
Result := 0;
end;
end
else
Result := inherited Receive(Buffer, BufferSize);
end;
function TSSHWSocket.Send(Data: Pointer; Len: integer): integer;
begin
if FisSSH then
begin
if state = dsBeforeSession then
begin
Result := inherited Send(Data, Len);
end
else
begin
if Assigned(Session.MainChan) then
begin
Session.MainChan.Send(Data, Len);
Result := Len;
end
else
Result := -1;
end;
end
else
Result := inherited Send(Data, Len);
end;
function TSSHWSocket.TriggerDataAvailable(Error: word): boolean;
var
svstr: string;
cvstr: string;
len: integer;
begin
if not FisSSH then
begin
Result := inherited TriggerDataAvailable(Error);
Exit;
end;
Result := True; // never return false!!!!!
{begin ssh}
case state of
dsBeforeSession:
begin
if (FSocksState <> socksData) then
begin
{ We are not in line mode }
Result := inherited TriggerDataAvailable(Error);
Exit;
end;
state := dsSockVersion;
end;
dsSockVersion:
begin
// Bug: Assume the SSH server send version information only
SetLength(svstr, 255);
len := inherited Receive(PChar(svstr), 255);
SetLength(svstr, len);
svstr := Trim(svstr);
Version := ChooseVersion(svstr);
case Version of
1:
begin
cvstr := V1Str;
Session := TSSH1Session.Create(Self);
Session.OnUserPrompt := OnAuthUser;
Session.OnPassPrompt := OnAuthPass;
end;
2:
begin
cvstr := V2Str;
Session := TSSH2Session.Create(Self);
TSSH2DHGSHA1Kex(TSSH2Session(Session).KeyEx).ServerVersion := svstr;
TSSH2DHGSHA1Kex(TSSH2Session(Session).KeyEx).ClientVersion := cvstr;
Session.OnUserPrompt := OnAuthUser;
Session.OnPassPrompt := OnAuthPass;
end;
else
begin
Close;
Result := True;
exit;
end;
end;
cvstr := cvstr + chr($0a);
inherited Send(PChar(cvstr), Length(cvstr));
Session.Sock := Self; // faint
state := dsSockSession;
end;
dsSockSession:
begin
Session.InBuffer.Ensure(5000);
len := inherited Receive(Session.InBuffer.Data + Session.InBuffer.length, 5000);
if len <= 0 then
begin
Result := True;
exit;
end;
Session.InBuffer.Increase(len);
try
if Version = 2 then
TSSH2Session(Session).InPacket.OnData(Session.InBuffer)
else
TSSH1Session(Session).InPacket.OnData(Session.InBuffer);
if Session.Closed then Close;
except
on E: ESSHError do
begin
ShowMessage(E.Message);
Close;
end;
end;
end;
end;
Result := True;
end;
procedure TSSHWSocket.TriggerSessionConnected(Error: word);
begin
// inherited;
// don't trigger this until ssh logined
//if not FisSSH then
// if state = dsBeforeSession then
inherited;
FirstPass := True;
end;
procedure TSSHWSocket.OnAuthUser(Sender: TSSHSession; var user: string;
var canceled: boolean);
begin
if sshuser <> '' then
begin
user := sshuser;
end
else
begin
canceled := ShowAuthForm(0);
if not canceled then user := sshuser;
end;
end;
function TSSHWSocket.ShowAuthForm(tag: integer): boolean;
var
f: TSSHAuthForm;
begin
f := TSSHAuthForm.Create(Application);
f.lblsite.Caption := Addr;
f.edUser.Text := sshuser;
f.edPass.Text := sshpass;
if tag = 0 then f.ActiveControl := f.edUser
else
f.ActiveControl := f.edPass;
if f.ShowModal = mrOk then
begin
sshuser := f.edUser.Text;
sshpass := f.edpass.Text;
Result := False;
end
else
begin
Result := True;
end;
//FirstPass := False;
f.Free;
end;
procedure TSSHWSocket.OnAuthPass(Sender: TSSHSession; var pass: string;
var canceled: boolean);
begin
if FirstPass and (sshpass <> '') then
begin
pass := sshpass;
FirstPass := False;
end
else
begin
canceled := ShowAuthForm(1);
if not canceled then pass := sshpass;
FirstPass := False;
end;
end;
procedure TSSHWSocket.SetSSHUserPass(ValueUser, ValuePass: string);
begin
sshuser := ValueUser;
sshpass := ValuePass;
end;
procedure TSSHWSocket.SetWindowSize(cols, rows: integer);
begin
self.cols := cols;
self.rows := rows;
if Assigned(Session) then Session.ChangeWindowSize(cols, rows);
end;
end.
|
unit ibSHView;
interface
uses
SysUtils, Classes, Controls, Contnrs, Forms,
SHDesignIntf,
ibSHDesignIntf, ibSHDBObject;
type
TibBTView = class(TibBTDBObject, IibSHView)
private
FFieldList: TComponentList;
FTriggerList: TComponentList;
FRecordCount: Integer;
FData: TSHComponent;
function GetField(Index: Integer): IibSHField;
function GetTrigger(Index: Integer): IibSHTrigger;
function GetRecordCountFrmt: string;
procedure SetRecordCount;
function GetData: IibSHData;
protected
function QueryInterface(const IID: TGUID; out Obj): HResult; override; stdcall;
procedure SetOwnerIID(Value: TGUID); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Refresh; override;
property RecordCountFrmt: string read GetRecordCountFrmt;
property Data: IibSHData read GetData;
published
property Description;
property Fields;
property Triggers;
property OwnerName;
end;
implementation
uses
ibSHConsts, ibSHSQLs, ibSHValues;
{ TibBTView }
function TibBTView.GetField(Index: Integer): IibSHField;
begin
Assert(Index <= Pred(Fields.Count), 'Index out of bounds');
Supports(CreateParam(FFieldList, IibSHField, Index), IibSHField, Result);
end;
function TibBTView.GetTrigger(Index: Integer): IibSHTrigger;
begin
Assert(Index <= Pred(Triggers.Count), 'Index out of bounds');
Supports(CreateParam(FTriggerList, IibSHTrigger, Index), IibSHTrigger, Result);
if Assigned(Result) and (Result.State = csUnknown) then
begin
Result.Caption := Triggers[Index];
Result.State := csSource;
Result.SourceDDL.Text := DDLGenerator.GetDDLText(Result);
end;
end;
function TibBTView.GetRecordCountFrmt: string;
begin
case FRecordCount of
-1: Result := Format('%s', [EmptyStr]);
0: Result := Format('%s', [SEmpty]);
else
Result := FormatFloat('###,###,###,###', FRecordCount);
end;
end;
procedure TibBTView.SetRecordCount;
var
S: string;
vCodeNormalizer: IibSHCodeNormalizer;
begin
S := Self.Caption;
if Supports(Designer.GetDemon(IibSHCodeNormalizer), IibSHCodeNormalizer, vCodeNormalizer) then
S := vCodeNormalizer.MetadataNameToSourceDDL(BTCLDatabase, S);
try
Screen.Cursor := crHourGlass;
if BTCLDatabase.DRVQuery.ExecSQL(Format(FormatSQL(SQL_GET_RECORD_COUNT), [S]), [], False) then
FRecordCount := BTCLDatabase.DRVQuery.GetFieldIntValue(0);
finally
BTCLDatabase.DRVQuery.Transaction.Commit;
Screen.Cursor := crDefault;
end;
end;
function TibBTView.GetData: IibSHData;
begin
Supports(FData, IibSHData, Result);
end;
function TibBTView.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
if IsEqualGUID(IID, IibSHData) then
begin
IInterface(Obj) := Data;
if Pointer(Obj) <> nil then
Result := S_OK
else
Result := E_NOINTERFACE;
end
else
Result := inherited QueryInterface(IID, Obj);
end;
procedure TibBTView.SetOwnerIID(Value: TGUID);
var
vComponentClass: TSHComponentClass;
begin
if not IsEqualGUID(OwnerIID, Value) then
begin
inherited SetOwnerIID(Value);
if Assigned(FData) then FData.Free;
vComponentClass := Designer.GetComponent(IibSHData);
if Assigned(vComponentClass) then
FData := vComponentClass.Create(Self);
end;
end;
constructor TibBTView.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FFieldList := TComponentList.Create;
FTriggerList := TComponentList.Create;
FRecordCount := -1;
end;
destructor TibBTView.Destroy;
begin
if Assigned(FData) then FData.Free;
FFieldList.Free;
FTriggerList.Free;
inherited Destroy;
end;
procedure TibBTView.Refresh;
begin
FFieldList.Clear;
FTriggerList.Clear;
inherited Refresh;
end;
end.
|
(*----------------------------------------------------------------------------*
* Direct3D sample from DirectX 9.0 SDK December 2006 *
* Delphi adaptation by Alexey Barkovoy (e-mail: directx@clootie.ru) *
* *
* Supported compilers: Delphi 5,6,7,9; FreePascal 2.0 *
* *
* Latest version can be downloaded from: *
* http://www.clootie.ru *
* http://sourceforge.net/projects/delphi-dx9sdk *
*----------------------------------------------------------------------------*
* $Id: HDRPipelineUnit.pas,v 1.5 2007/02/05 22:21:08 clootie Exp $
*----------------------------------------------------------------------------*)
//======================================================================
//
// HIGH DYNAMIC RANGE RENDERING DEMONSTRATION
// Written by Jack Hoxley, November 2005
//
//======================================================================
{$I DirectX.inc}
unit HDRPipelineUnit;
interface
uses
Windows, DXTypes, Direct3D9, D3DX9,
DXUT, DXUTcore, DXUTmisc, DXUTenum, DXUTgui, DXUTSettingsDlg,
SysUtils, Math, StrSafe;
//--------------------------------------------------------------------------------------
// Data Structure Definitions
//--------------------------------------------------------------------------------------
type
TTLVertex = record
p: TD3DXVector4;
t: TD3DXVector2;
end;
const
FVF_TLVERTEX = D3DFVF_XYZRHW or D3DFVF_TEX1;
//--------------------------------------------------------------------------------------
// Global variables
//--------------------------------------------------------------------------------------
var
g_pFont: ID3DXFont = nil; // Font for drawing text
g_pTextSprite: ID3DXSprite = nil; // Sprite for batching draw text calls
g_pArrowTex: IDirect3DTexture9 = nil; // Used to indicate flow between cells
g_Camera: CModelViewerCamera; // A model viewing camera
g_HUD: CDXUTDialog; // Dialog for standard controls
g_Config: CDXUTDialog; // Dialog for the shader/render parameters
g_SettingsDlg: CD3DSettingsDlg; // Used for the "change device" button
g_DialogResourceManager: CDXUTDialogResourceManager; // Manager for shared resources of dialogs
g_pFinalPassPS: IDirect3DPixelShader9 = nil; // The pixel shader that maps HDR->LDR
g_pFinalPassPSConsts: ID3DXConstantTable = nil; // The interface for setting param/const data for the above PS
g_dwLastFPSCheck: DWORD = 0; // The time index of the last frame rate check
g_dwFrameCount: DWORD = 0; // How many frames have elapsed since the last check
g_dwFrameRate: DWORD = 0; // How many frames rendered during the PREVIOUS interval
g_fExposure: Single = 0.5; // The exposure bias fed into the FinalPass.psh shader (OnFrameRender )
//--------------------------------------------------------------------------------------
// UI control IDs
//--------------------------------------------------------------------------------------
const
IDC_TOGGLEFULLSCREEN = 1;
IDC_TOGGLEREF = 2;
IDC_CHANGEDEVICE = 3;
IDC_THRESHOLDSLIDER = 4;
IDC_THRESHOLDLABEL = 5;
IDC_EXPOSURESLIDER = 6;
IDC_EXPOSURELABEL = 7;
IDC_MULTIPLIERSLIDER = 8;
IDC_MULTIPLIERLABEL = 9;
IDC_MEANSLIDER = 10;
IDC_MEANLABEL = 11;
IDC_STDDEVSLIDER = 12;
IDC_STDDEVLABEL = 13;
//--------------------------------------------------------------------------------------
// HIGH DYNAMIC RANGE VARIABLES
//--------------------------------------------------------------------------------------
var
g_FloatRenderTargetFmt: TD3DFormat = D3DFMT_UNKNOWN; // 128 or 64 bit rendering...
g_DepthFormat: TD3DFormat = D3DFMT_UNKNOWN; // How many bits of depth buffer are we using?
g_dwApproxMemory: DWORD = 0; // How many bytes of VRAM are we using up?
g_pFinalTexture: IDirect3DTexture9 = nil;
//--------------------------------------------------------------------------------------
// Forward declarations
//--------------------------------------------------------------------------------------
function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall;
function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall;
function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall;
procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall;
procedure OnLostDevice(pUserContext: Pointer); stdcall;
procedure OnDestroyDevice(pUserContext: Pointer); stdcall;
//--------------------------------------------------------------------------------------
// Forward declarations
//--------------------------------------------------------------------------------------
procedure InitApp;
procedure RenderText;
procedure DrawHDRTextureToScreen;
procedure CreateCustomDXUTobjects;
procedure DestroyCustomDXUTobjects;
implementation
uses
HDREnumeration, HDRScene, Luminance, PostProcess;
//--------------------------------------------------------------------------------------
// Debug output helper
//--------------------------------------------------------------------------------------
var g_szStaticOutput: array[0..MAX_PATH-1] of WideChar;
function DebugHelper(szFormat: PWideChar; cSizeBytes: LongWord): PWideChar;
begin
StringCchFormat(g_szStaticOutput, MAX_PATH, szFormat, [cSizeBytes]);
Result:= g_szStaticOutput;
end;
//--------------------------------------------------------------------------------------
// Initialize the app
//--------------------------------------------------------------------------------------
procedure InitApp;
var
iY: Integer;
begin
// Initialize dialogs
g_SettingsDlg.Init(g_DialogResourceManager);
g_HUD.Init(g_DialogResourceManager);
g_Config.Init(g_DialogResourceManager);
g_HUD.SetFont(0, 'Arial', 14, FW_NORMAL );
g_HUD.SetCallback(OnGUIEvent);
g_Config.SetFont(0, 'Arial', 12, FW_NORMAL);
g_Config.SetCallback(OnGUIEvent);
iY := 10;
g_HUD.AddButton(IDC_TOGGLEFULLSCREEN, 'Toggle full screen', 35, iY, 125, 22); Inc(iY, 24);
g_HUD.AddButton(IDC_TOGGLEREF, 'Toggle REF (F3)', 35, iY, 125, 22); Inc(iY, 24);
g_HUD.AddButton(IDC_CHANGEDEVICE, 'Change device (F2)', 35, iY, 125, 22, VK_F2);
g_Config.AddStatic(IDC_MULTIPLIERLABEL, 'Gaussian Multiplier: (0.4)', 35, 0, 125, 15);
g_Config.AddSlider(IDC_MULTIPLIERSLIDER, 35, 20, 125, 16, 0, 20, 4);
g_Config.AddStatic(IDC_MEANLABEL, 'Gaussian Mean: (0.0)', 35, 40, 125, 15);
g_Config.AddSlider(IDC_MEANSLIDER, 35, 60, 125, 16, -10, 10, 0);
g_Config.AddStatic(IDC_STDDEVLABEL, 'Gaussian Std. Dev: (0.8)', 35, 80, 125, 15);
g_Config.AddSlider(IDC_STDDEVSLIDER, 35, 100, 125, 16, 0, 10, 8);
g_Config.AddStatic(IDC_THRESHOLDLABEL, 'Bright-Pass Threshold: (0.8)', 35, 120, 125, 15);
g_Config.AddSlider(IDC_THRESHOLDSLIDER, 35, 140, 125, 16, 0, 25, 8);
g_Config.AddStatic(IDC_EXPOSURELABEL, 'Exposure: (0.5)', 35, 160, 125, 15);
g_Config.AddSlider(IDC_EXPOSURESLIDER, 35, 180, 125, 16, 0, 200, 50);
end;
//--------------------------------------------------------------------------------------
// Rejects any devices that aren't acceptable by returning false
//--------------------------------------------------------------------------------------
function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall;
var
pD3D: IDirect3D9;
begin
Result:= False;
// Skip backbuffer formats that don't support alpha blending
pD3D := DXUTGetD3DObject;
if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,
AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING,
D3DRTYPE_TEXTURE, BackBufferFormat))
then Exit;
// Also need post pixel processing support
if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,
AdapterFormat, D3DUSAGE_RENDERTARGET or D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING,
D3DRTYPE_SURFACE, BackBufferFormat)) then Exit;
// We must have SM2.0 support for this sample to run. We
// don't need to worry about the VS version as we can shift
// that to the CPU if necessary...
if (pCaps.PixelShaderVersion < D3DPS_VERSION(2,0)) then Exit;
// We must have floating point render target support, where available we'll use 128bit,
// but we can also use 64bit. We'll store the best one we can use...
if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,
AdapterFormat, D3DUSAGE_RENDERTARGET,
D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) then
begin
//we don't support 128bit render targets :-(
if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,
AdapterFormat, D3DUSAGE_RENDERTARGET,
D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) then
begin
//we don't support 128 or 64 bit render targets. This demo
//will not work with this device.
Exit;
end;
end;
Result:= True;
end;
//--------------------------------------------------------------------------------------
// Before a device is created, modify the device settings as needed
//--------------------------------------------------------------------------------------
function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall;
begin
// If device doesn't support HW T&L or doesn't support 2.0 vertex shaders in HW
// then switch to SWVP.
if (pCaps.DevCaps and D3DDEVCAPS_HWTRANSFORMANDLIGHT = 0) or
(pCaps.VertexShaderVersion < D3DVS_VERSION(2,0))
then pDeviceSettings.BehaviorFlags := D3DCREATE_SOFTWARE_VERTEXPROCESSING
else pDeviceSettings.BehaviorFlags := D3DCREATE_HARDWARE_VERTEXPROCESSING;
// This application is designed to work on a pure device by not using
// IDirect3D9::Get*() methods, so create a pure device if supported and using HWVP.
if (pCaps.DevCaps and D3DDEVCAPS_PUREDEVICE <> 0) and
(pDeviceSettings.BehaviorFlags and D3DCREATE_HARDWARE_VERTEXPROCESSING <> 0)
then pDeviceSettings.BehaviorFlags := pDeviceSettings.BehaviorFlags or D3DCREATE_PUREDEVICE;
g_DepthFormat := pDeviceSettings.pp.AutoDepthStencilFormat;
// TODO: Some devices **WILL** allow multisampled HDR targets, this can be
// checked via a device format enumeration. If multisampling is a requirement, an
// enumeration/check could be added here.
if (pDeviceSettings.pp.MultiSampleType <> D3DMULTISAMPLE_NONE) then
begin
// Multisampling and HDRI don't play nice!
OutputDebugString('Multisampling is enabled. Disabling now!'#10);
pDeviceSettings.pp.MultiSampleType := D3DMULTISAMPLE_NONE;
end;
Result:= True;
end;
//--------------------------------------------------------------------------------------
// Create any D3DPOOL_MANAGED resources here
//--------------------------------------------------------------------------------------
function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
var
str: array[0..MAX_PATH-1] of WideChar;
vecEye, vecAt: TD3DXVector3;
begin
// Allow the GUI to set itself up..
Result:= g_DialogResourceManager.OnCreateDevice(pd3dDevice);
if V_Failed(Result) then Exit;
Result:= g_SettingsDlg.OnCreateDevice(pd3dDevice);
if V_Failed(Result) then Exit;
// Determine any necessary enumerations
Result:= HDREnumeration.FindBestHDRFormat(g_FloatRenderTargetFmt);
if V_Failed(Result) then Exit;
// Initialize the font
Result:= D3DXCreateFont(pd3dDevice, 12, 0, FW_NORMAL, 1, FALSE, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH or FF_DONTCARE,
'Arial', g_pFont);
if V_Failed(Result) then Exit;
V(DXUTFindDXSDKMediaFile(str, MAX_PATH, 'misc\Arrows.bmp'));
if FAILED(Result) then
begin
// Couldn't find the sprites
OutputDebugString('OnCreateDevice() - Could not locate ''Arrows.bmp''.'#10);
Exit;
end;
V(D3DXCreateTextureFromFileW(pd3dDevice, str, g_pArrowTex));
if FAILED(Result) then
begin
// Couldn't load the sprites!
OutputDebugString('OnCreateDevice() - Could not load ''Arrows.bmp''.'#10);
Exit;
end;
// Setup the camera's view parameters
vecEye := D3DXVector3(0.0, 0.0, -5.0);
vecAt := D3DXVector3(0.0, 0.0, -0.0);
g_Camera.SetViewParams(vecEye, vecAt);
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// Create any D3DPOOL_DEFAULT resources here
//--------------------------------------------------------------------------------------
function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
var
pCode: ID3DXBuffer;
fAspectRatio: Single;
iMultiplier: Cardinal;
str: array[0..MAX_PATH-1] of WideChar;
begin
// Allow the GUI time to reset itself..
Result:= g_DialogResourceManager.OnResetDevice;
if V_Failed(Result) then Exit;
Result:= g_SettingsDlg.OnResetDevice;
if V_Failed(Result) then Exit;
if (g_pFont <> nil) then
begin
Result:= g_pFont.OnResetDevice;
if V_Failed(Result) then Exit;
end;
// Create a sprite to help batch calls when drawing many lines of text
Result:= D3DXCreateSprite(pd3dDevice, g_pTextSprite);
if V_Failed(Result) then Exit;
pd3dDevice.SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP);
pd3dDevice.SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP);
pd3dDevice.SetSamplerState(1, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP);
pd3dDevice.SetSamplerState(1, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP);
pd3dDevice.SetSamplerState(2, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP);
pd3dDevice.SetSamplerState(2, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP);
// Setup the camera's projection parameters
fAspectRatio := pBackBufferSurfaceDesc.Width / pBackBufferSurfaceDesc.Height;
g_Camera.SetProjParams(D3DX_PI/4, fAspectRatio, 0.1, 1000.0);
g_Camera.SetWindow(pBackBufferSurfaceDesc.Width, pBackBufferSurfaceDesc.Height);
// Configure the GUI
g_HUD.SetLocation(pBackBufferSurfaceDesc.Width - 170, pBackBufferSurfaceDesc.Height - 90);
g_HUD.SetSize(170, 170);
g_Config.SetLocation(pBackBufferSurfaceDesc.Width - 170, pBackBufferSurfaceDesc.Height - 300);
g_Config.SetSize(170, 210);
// Recreate the floating point resources
Result:= pd3dDevice.CreateTexture(pBackBufferSurfaceDesc.Width, pBackBufferSurfaceDesc.Height,
1, D3DUSAGE_RENDERTARGET, pBackBufferSurfaceDesc.Format,
D3DPOOL_DEFAULT, g_pFinalTexture, nil);
if V_Failed(Result) then Exit;
//Attempt to recalulate some memory statistics:
case pBackBufferSurfaceDesc.Format of
//32bit modes:
D3DFMT_A2R10G10B10,
D3DFMT_A8R8G8B8,
D3DFMT_X8R8G8B8:
iMultiplier := 4;
//24bit modes:
D3DFMT_R8G8B8:
iMultiplier := 3;
//16bit modes:
D3DFMT_X1R5G5B5,
D3DFMT_A1R5G5B5,
D3DFMT_R5G6B5:
iMultiplier := 2;
else
iMultiplier := 1;
end;
//the *3 constant due to having double buffering AND the composition render target..
g_dwApproxMemory := pBackBufferSurfaceDesc.Width * pBackBufferSurfaceDesc.Height * 3 * iMultiplier;
case g_DepthFormat of
//16 bit formats
D3DFMT_D16,
D3DFMT_D16_LOCKABLE,
D3DFMT_D15S1:
g_dwApproxMemory := g_dwApproxMemory + (pBackBufferSurfaceDesc.Width * pBackBufferSurfaceDesc.Height * 2);
//32bit formats:
D3DFMT_D32,
D3DFMT_D32F_LOCKABLE,
D3DFMT_D24X8,
D3DFMT_D24S8,
D3DFMT_D24X4S4,
D3DFMT_D24FS8:
g_dwApproxMemory := g_dwApproxMemory + (pBackBufferSurfaceDesc.Width * pBackBufferSurfaceDesc.Height * 4);
end;
{$IFDEF DEBUG}
OutputDebugStringW(DebugHelper('HDR Demo : Basic Swap Chain/Depth Buffer Occupy %d bytes.'#13, g_dwApproxMemory));
{$ENDIF}
Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, 'Shader Code\FinalPass.psh');
if V_Failed(Result) then Exit;
Result:= D3DXCompileShaderFromFileW(str,
nil, nil,
'main',
'ps_2_0',
0,
@pCode,
nil,
@g_pFinalPassPSConsts
);
if V_Failed(Result) then Exit;
Result:= pd3dDevice.CreatePixelShader(PDWORD(pCode.GetBufferPointer), g_pFinalPassPS);
if V_Failed(Result) then Exit;
pCode := nil;
// Hand over execution to the 'HDRScene' module so it can perform it's
// resource creation:
Result:= HDRScene.CreateResources(pd3dDevice, pBackBufferSurfaceDesc);
if V_Failed(Result) then Exit;
g_dwApproxMemory := g_dwApproxMemory + HDRScene.CalculateResourceUsage;
{$IFDEF DEBUG}
OutputDebugStringW(DebugHelper('HDR Demo : HDR Scene Resources Occupy %d bytes.'#10, HDRScene.CalculateResourceUsage));
{$ENDIF}
// Hand over execution to the 'Luminance' module so it can perform it's
// resource creation:
Result:= Luminance.CreateResources(pd3dDevice, pBackBufferSurfaceDesc);
if V_Failed(Result) then Exit;
g_dwApproxMemory := g_dwApproxMemory + Luminance.ComputeResourceUsage;
{$IFDEF DEBUG}
OutputDebugStringW(DebugHelper('HDR Demo : Luminance Resources Occupy %d bytes.'#10, Luminance.ComputeResourceUsage));
{$ENDIF}
// Hand over execution to the 'PostProcess' module so it can perform it's
// resource creation:
Result:= PostProcess.CreateResources(pd3dDevice, pBackBufferSurfaceDesc);
if V_Failed(Result) then Exit;
g_dwApproxMemory := g_dwApproxMemory + PostProcess.CalculateResourceUsage;
{$IFDEF DEBUG}
begin
OutputDebugStringW(DebugHelper('HDR Demo : Post Processing Resources Occupy %d bytes.'#10, PostProcess.CalculateResourceUsage));
OutputDebugStringW(DebugHelper('HDR Demo : Total Graphics Resources Occupy %d bytes.'#10, g_dwApproxMemory));
end;
{$ENDIF}
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// Handle updates to the scene
//--------------------------------------------------------------------------------------
procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
begin
// Update the camera's position based on user input
g_Camera.FrameMove(fElapsedTime);
// Compute the frame rate based on a 1/4 second update cycle
if ((GetTickCount - g_dwLastFPSCheck) >= 250) then
begin
g_dwFrameRate := g_dwFrameCount * 4;
g_dwFrameCount := 0;
g_dwLastFPSCheck := GetTickCount;
end;
Inc(g_dwFrameCount);
// The original HDR scene needs to update some of it's internal structures, so
// pass the message along...
HDRScene.UpdateScene(pd3dDevice, fTime, g_Camera);
end;
//--------------------------------------------------------------------------------------
// OnFrameRender()
// ---------------
// NOTES: This function makes particular use of the 'D3DPERF_BeginEvent()' and
// 'D3DPERF_EndEvent()' functions. See the documentation for more details,
// but these are essentially used to provide better output from PIX. If you
// perform a full call-stream capture on this sample, PIX will group together
// related calls, making it much easier to interpret the results.
//--------------------------------------------------------------------------------------
procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
var
//Cache some results for later use
pLDRSurface: IDirect3DSurface9;
pFinalSurf: IDirect3DSurface9;
pHDRTex: IDirect3DTexture9;
pLumTex: IDirect3DTexture9;
pBloomTex: IDirect3DTexture9;
d: TD3DSurfaceDesc;
vv: array[0..3] of TTLVertex;
fCellWidth, fCellHeight, fFinalHeight, fFinalWidth: Single;
begin
// If the user is currently in the process of selecting
// a new device and/or configuration then we hand execution
// straight back to the framework...
if g_SettingsDlg.Active then
begin
g_SettingsDlg.OnRender(fElapsedTime);
Exit;
end;
//Configure the render targets
V(pd3dDevice.GetRenderTarget(0, pLDRSurface)); //This is the output surface - a standard 32bit device
// Clear the render target and the zbuffer
V(pd3dDevice.Clear(0, nil, D3DCLEAR_TARGET or D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB($ff, $ff, $ff, $ff), 1.0, 0));
// Render the scene
if SUCCEEDED(pd3dDevice.BeginScene) then
begin
// RENDER THE COMPLETE SCENE
//--------------------------
// The first part of each frame is to actually render the "core"
// resources - those that would be required for an HDR-based pipeline.
// HDRScene creates an unprocessed, raw, image to work with.
D3DPERF_BeginEvent(D3DCOLOR_XRGB(255, 0, 0), 'HDRScene Rendering');
HDRScene.RenderScene(pd3dDevice);
D3DPERF_EndEvent;
// Luminance attempts to calculate what sort of tone/mapping should
// be done as part of the post-processing step.
D3DPERF_BeginEvent(D3DCOLOR_XRGB(0, 0, 255), 'Luminance Rendering');
Luminance.MeasureLuminance(pd3dDevice);
D3DPERF_EndEvent;
// The post-processing adds the blur to the bright (over-exposed) areas
// of the image.
D3DPERF_BeginEvent(D3DCOLOR_XRGB(255, 0, 0), 'Post-Processing Rendering');
PostProcess.PerformPostProcessing(pd3dDevice);
D3DPERF_EndEvent;
// When all the individual components have been created we have the final
// composition. The output of this is the image that will be displayed
// on screen.
D3DPERF_BeginEvent(D3DCOLOR_XRGB(255, 0, 255), 'Final Image Composition');
begin
g_pFinalTexture.GetSurfaceLevel(0, pFinalSurf);
pd3dDevice.SetRenderTarget(0, pFinalSurf);
HDRScene.GetOutputTexture(pHDRTex);
Luminance.GetLuminanceTexture(pLumTex);
PostProcess.GetTexture(pBloomTex);
pd3dDevice.SetTexture(0, pHDRTex);
pd3dDevice.SetTexture(1, pLumTex);
pd3dDevice.SetTexture(2, pBloomTex);
pd3dDevice.SetPixelShader(g_pFinalPassPS);
pBloomTex.GetLevelDesc(0, d);
g_pFinalPassPSConsts.SetFloat(pd3dDevice, 'g_rcp_bloom_tex_w', 1.0 / d.Width);
g_pFinalPassPSConsts.SetFloat(pd3dDevice, 'g_rcp_bloom_tex_h', 1.0 / d.Height);
g_pFinalPassPSConsts.SetFloat(pd3dDevice, 'fExposure', g_fExposure);
g_pFinalPassPSConsts.SetFloat(pd3dDevice, 'fGaussianScalar', PostProcess.GetGaussianMultiplier);
DrawHDRTextureToScreen;
pd3dDevice.SetPixelShader(nil);
pd3dDevice.SetTexture(2, nil);
pd3dDevice.SetTexture(1, nil);
pd3dDevice.SetTexture(0, nil);
pd3dDevice.SetRenderTarget(0, pLDRSurface);
SAFE_RELEASE(pBloomTex);
SAFE_RELEASE(pLumTex);
SAFE_RELEASE(pHDRTex);
SAFE_RELEASE(pFinalSurf);
end;
D3DPERF_EndEvent;
// RENDER THE GUI COMPONENTS
//--------------------------
// The remainder of the rendering is specific to this example rather
// than to a general-purpose HDRI pipeline. The following code outputs
// each individual stage of the above process so that, in real-time, you
// can see exactly what is happening...
D3DPERF_BeginEvent(D3DCOLOR_XRGB(255, 0, 255), 'GUI Rendering');
begin
pLDRSurface.GetDesc(d);
vv[0].t := D3DXVector2(0.0, 0.0);
vv[1].t := D3DXVector2(1.0, 0.0);
vv[2].t := D3DXVector2(0.0, 1.0);
vv[3].t := D3DXVector2(1.0, 1.0);
pd3dDevice.SetPixelShader(nil);
pd3dDevice.SetVertexShader(nil);
pd3dDevice.SetFVF(FVF_TLVERTEX);
fCellWidth := (d.Width - 48.0) / 4.0;
fCellHeight := (d.Height - 36.0) / 4.0;
fFinalHeight := d.Height - (fCellHeight + 16.0);
fFinalWidth := fFinalHeight / 0.75;
vv[0].p := D3DXVector4(fCellWidth + 16.0, fCellHeight + 16.0, 0.0, 1.0);
vv[1].p := D3DXVector4(fCellWidth + 16.0 + fFinalWidth, fCellHeight + 16.0, 0.0, 1.0);
vv[2].p := D3DXVector4(fCellWidth + 16.0, fCellHeight + 16.0 + fFinalHeight, 0.0, 1.0);
vv[3].p := D3DXVector4(fCellWidth + 16.0 + fFinalWidth, fCellHeight + 16.0 + fFinalHeight, 0.0, 1.0);
pd3dDevice.SetTexture(0, g_pFinalTexture);
pd3dDevice.DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, vv, SizeOf(TTLVertex));
// Draw the original HDR scene to the GUI
D3DPERF_BeginEvent(D3DCOLOR_XRGB(255, 0, 0), 'GUI: HDR Scene');
HDRScene.DrawToScreen(pd3dDevice, g_pFont, g_pTextSprite, g_pArrowTex);
D3DPERF_EndEvent;
// Draw the various down-sampling stages to the luminance measurement
D3DPERF_BeginEvent(D3DCOLOR_XRGB(255, 0, 0), 'GUI: Luminance Measurements');
Luminance.DisplayLuminance(pd3dDevice, g_pFont, g_pTextSprite, g_pArrowTex);
D3DPERF_EndEvent;
// Draw the bright-pass, downsampling and bloom steps
D3DPERF_BeginEvent(D3DCOLOR_XRGB(255, 0, 0), 'GUI: Post-Processing Effects');
PostProcess.DisplaySteps(pd3dDevice, g_pFont, g_pTextSprite, g_pArrowTex);
D3DPERF_EndEvent;
end;
D3DPERF_EndEvent;
D3DPERF_BeginEvent(D3DCOLOR_XRGB(64, 0, 64), 'User Interface Rendering');
RenderText;
V(g_HUD.OnRender(fElapsedTime));
V(g_Config.OnRender(fElapsedTime));
D3DPERF_EndEvent;
// We've finished all of the rendering, so make sure that D3D
// is aware of this...
V(pd3dDevice.EndScene);
end;
//Remove any memory involved in the render target switching
SAFE_RELEASE(pLDRSurface);
end;
//--------------------------------------------------------------------------------------
// Render the help and statistics text. This function uses the ID3DXFont interface for
// efficient text rendering.
//--------------------------------------------------------------------------------------
const iMaxStringSize = 1024;
procedure RenderText;
var
pd3dsdBackBuffer: PD3DSurfaceDesc;
txtHelper: CDXUTTextHelper;
xOff: DWORD;
strRT: WideString;
str: array[0..iMaxStringSize-1] of WideChar;
begin
// The helper object simply helps keep track of text position, and color
// and then it calls pFont->DrawText( g_pSprite, strMsg, -1, &rc, DT_NOCLIP, g_clr );
// If NULL is passed in as the sprite object, then it will work however the
// pFont->DrawText() will not be batched together. Batching calls will improves performance.
pd3dsdBackBuffer := DXUTGetBackBufferSurfaceDesc;
txtHelper:= CDXUTTextHelper.Create(g_pFont, g_pTextSprite, 15);
// Output statistics
txtHelper._Begin;
xOff := 16 + ((pd3dsdBackBuffer.Width - 48) div 4);
txtHelper.SetInsertionPos(xOff + 5, pd3dsdBackBuffer.Height - 40);
txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 0.0, 1.0));
txtHelper.SetForegroundColor(D3DXColor(1.0, 0.5, 0.0, 1.0));
//fill out the text...
if (g_FloatRenderTargetFmt = D3DFMT_A16B16G16R16F) then strRT := 'Using 64bit floating-point render targets.'#10
else if (g_FloatRenderTargetFmt = D3DFMT_A32B32G32R32F) then strRT := 'Using 128bit floating-point render targets.'#10;
StringCchFormat(str, iMaxStringSize, 'Final Composed Image (%dx%d) @ %dfps.'#10 +
'%s Approx Memory Consumption is %d bytes.'#10,
[pd3dsdBackBuffer.Width,
pd3dsdBackBuffer.Height,
g_dwFrameRate,
strRT,
g_dwApproxMemory]);
txtHelper.DrawTextLine(str);
txtHelper.SetInsertionPos(xOff + 5, ((pd3dsdBackBuffer.Height - 36) div 4) + 20);
txtHelper.DrawTextLine('Drag with LEFT mouse button : Rotate occlusion cube.');
txtHelper.DrawTextLine('Drag with RIGHT mouse button : Rotate view of scene.');
txtHelper._End;
txtHelper.Free;
end;
//--------------------------------------------------------------------------------------
// Handle messages to the application
//--------------------------------------------------------------------------------------
function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall;
begin
Result:= 0;
// Always allow dialog resource manager calls to handle global messages
// so GUI state is updated correctly
pbNoFurtherProcessing := g_DialogResourceManager.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
if g_SettingsDlg.IsActive then
begin
g_SettingsDlg.MsgProc(hWnd, uMsg, wParam, lParam);
Exit;
end;
// Give on screen UI a chance to handle this message
pbNoFurtherProcessing := g_HUD.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
pbNoFurtherProcessing := g_Config.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
// Pass all windows messages to camera so it can respond to user input
g_Camera.HandleMessages(hWnd, uMsg, wParam, lParam);
end;
//--------------------------------------------------------------------------------------
// Handles the GUI events
//--------------------------------------------------------------------------------------
procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall;
var
str: array[0..99] of WideChar;
fNewThreshold: Single;
mul: Single;
mean: Single;
sd: Single;
begin
case nControlID of
IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen;
IDC_TOGGLEREF: DXUTToggleREF;
IDC_CHANGEDEVICE: with g_SettingsDlg do Active := not Active;
IDC_THRESHOLDSLIDER:
begin
fNewThreshold := g_Config.GetSlider(IDC_THRESHOLDSLIDER).Value / 10.0;
PostProcess.SetBrightPassThreshold(fNewThreshold);
StringCchFormat(str, 100, 'Bright-Pass Threshold: (%f)', [fNewThreshold]);
g_Config.GetStatic(IDC_THRESHOLDLABEL).Text := str;
end;
IDC_EXPOSURESLIDER:
begin
g_fExposure := g_Config.GetSlider(IDC_EXPOSURESLIDER).Value / 100.0;
StringCchFormat(str, 100, 'Exposure: (%f)', [g_fExposure]);
g_Config.GetStatic(IDC_EXPOSURELABEL).Text := str;
end;
IDC_MULTIPLIERSLIDER:
begin
mul := g_Config.GetSlider(IDC_MULTIPLIERSLIDER).Value / 10.0;
PostProcess.SetGaussianMultiplier(mul);
StringCchFormat(str, 100, 'Gaussian Multiplier: (%f)', [mul]);
g_Config.GetStatic(IDC_MULTIPLIERLABEL).Text := str;
end;
IDC_MEANSLIDER:
begin
mean := g_Config.GetSlider(IDC_MEANSLIDER).Value / 10.0;
PostProcess.SetGaussianMean(mean);
StringCchFormat(str, 100, 'Gaussian Mean: (%f)', [mean]);
g_Config.GetStatic(IDC_MEANLABEL).Text := str;
end;
IDC_STDDEVSLIDER:
begin
sd := g_Config.GetSlider(IDC_STDDEVSLIDER).Value / 10.0;
PostProcess.SetGaussianStandardDeviation(sd);
StringCchFormat(str, 100, 'Gaussian Std. Dev: (%f)', [sd]);
g_Config.GetStatic(IDC_STDDEVLABEL).Text := str;
end;
end;
end;
//--------------------------------------------------------------------------------------
// Release resources created in the OnResetDevice callback here
//--------------------------------------------------------------------------------------
procedure OnLostDevice(pUserContext: Pointer); stdcall;
begin
// Let the GUI do it's lost-device work:
g_DialogResourceManager.OnLostDevice;
g_SettingsDlg.OnLostDevice;
if (g_pFont <> nil) then g_pFont.OnLostDevice;
SAFE_RELEASE(g_pTextSprite);
SAFE_RELEASE(g_pArrowTex);
// Free up the HDR resources
SAFE_RELEASE(g_pFinalTexture);
// Free up the final screen pass resources
SAFE_RELEASE(g_pFinalPassPS);
SAFE_RELEASE(g_pFinalPassPSConsts);
HDRScene.DestroyResources;
Luminance.DestroyResources;
PostProcess.DestroyResources;
end;
//--------------------------------------------------------------------------------------
// Release resources created in the OnCreateDevice callback here
//--------------------------------------------------------------------------------------
procedure OnDestroyDevice; stdcall;
begin
g_DialogResourceManager.OnDestroyDevice;
g_SettingsDlg.OnDestroyDevice;
SAFE_RELEASE(g_pFont);
SAFE_RELEASE(g_pTextSprite);
SAFE_RELEASE(g_pArrowTex);
// Free up the HDR resources
SAFE_RELEASE(g_pFinalTexture);
// Free up the final screen pass resources
SAFE_RELEASE(g_pFinalPassPS);
SAFE_RELEASE(g_pFinalPassPSConsts);
HDRScene.DestroyResources;
Luminance.DestroyResources;
PostProcess.DestroyResources;
end;
//--------------------------------------------------------------------------------------
// The last stage of the HDR pipeline requires us to take the image that was rendered
// to an HDR-format texture and map it onto a LDR render target that can be displayed
// on screen. This is done by rendering a screen-space quad and setting a pixel shader
// up to map HDR->LDR.
//--------------------------------------------------------------------------------------
procedure DrawHDRTextureToScreen;
var
pDev: IDirect3DDevice9;
desc: TD3DSurfaceDesc;
pSurfRT: IDirect3DSurface9;
fWidth: Single;
fHeight: Single;
v: array[0..3] of TTLVertex;
begin
// Find out what dimensions the screen is
pDev := DXUTGetD3DDevice;
pDev.GetRenderTarget(0, pSurfRT);
pSurfRT.GetDesc(desc);
pSurfRT := nil;
// To correctly map from texels->pixels we offset the coordinates
// by -0.5f:
fWidth := desc.Width - 0.5;
fHeight := desc.Height - 0.5;
// Now we can actually assemble the screen-space geometry
v[0].p := D3DXVector4(-0.5, -0.5, 0.0, 1.0);
v[0].t := D3DXVector2(0.0, 0.0);
v[1].p := D3DXVector4(fWidth, -0.5, 0.0, 1.0);
v[1].t := D3DXVector2(1.0, 0.0);
v[2].p := D3DXVector4(-0.5, fHeight, 0.0, 1.0);
v[2].t := D3DXVector2(0.0, 1.0);
v[3].p := D3DXVector4(fWidth, fHeight, 0.0, 1.0);
v[3].t := D3DXVector2(1.0, 1.0);
// Configure the device and render..
pDev.SetVertexShader(nil);
pDev.SetFVF(FVF_TLVERTEX);
pDev.SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
pDev.SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
pDev.DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, SizeOf(TTLVertex));
end;
procedure CreateCustomDXUTobjects;
begin
g_DialogResourceManager:= CDXUTDialogResourceManager.Create; // manager for shared resources of dialogs
g_SettingsDlg:= CD3DSettingsDlg.Create; // Device settings dialog
g_Camera:= CModelViewerCamera.Create;
g_HUD:= CDXUTDialog.Create;
g_Config:= CDXUTDialog.Create;
end;
procedure DestroyCustomDXUTobjects;
begin
FreeAndNil(g_DialogResourceManager);
FreeAndNil(g_SettingsDlg);
FreeAndNil(g_Camera);
FreeAndNil(g_HUD);
FreeAndNil(g_Config);
end;
end.
|
unit BsRepLoader;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxGraphics, cxCustomData, cxStyles, cxTL, DB, FIBDatabase,
pFIBDatabase, FIBDataSet, pFIBDataSet, cxControls, cxInplaceContainer,
cxTLData, cxDBTL, dxBar, dxBarExtItems, ActnList, cxMaskEdit, ImgList,
cxClasses, cxGridTableView, uCommon_Types, FIBQuery,
pFIBQuery, pFIBStoredProc, ExtCtrls, DateUtils, cxTextEdit, cxDBEdit,
cxContainer, cxEdit, cxLabel, uCommon_Messages, cxFilter, cxData,
cxDataStorage, cxDBData, cxGridLevel, cxGridCustomView,
cxGridCustomTableView, cxGridDBTableView, cxGrid, cxButtonEdit,
cxLookAndFeelPainters, StdCtrls, cxButtons, cxDropDownEdit, uCommon_Loader,
cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, Menus,
uCommon_Funcs, uConsts, cxCheckBox, cxCalendar, cxMemo, frxExportPDF,
frxExportXML, frxExportXLS, frxClass, frxExportHTML, frxDBSet;
const
pnlGridHeight=159;
frmTop=180;
type
TfrmReportLoader = class(TForm)
ReportReadTrans: TpFIBTransaction;
ActionList1: TActionList;
ImageList: TImageList;
pnlGrid: TPanel;
BarManager: TdxBarManager;
btnSelect: TdxBarLargeButton;
btnClose: TdxBarLargeButton;
ActClose: TAction;
ReportGridDBView: TcxGridDBTableView;
ReportGridLevel: TcxGridLevel;
ReportGrid: TcxGrid;
ReportDSet: TpFIBDataSet;
ReportDS: TDataSource;
ColumnNumReport: TcxGridDBColumn;
ColumnNameReport: TcxGridDBColumn;
Panel1: TPanel;
DisObjStyleRepository: TcxStyleRepository;
cxStyle1: TcxStyle;
cxStyle2: TcxStyle;
cxStyle3: TcxStyle;
cxStyle4: TcxStyle;
cxStyle5: TcxStyle;
cxStyle6: TcxStyle;
cxStyle7: TcxStyle;
cxStyle8: TcxStyle;
cxStyle9: TcxStyle;
cxStyle10: TcxStyle;
cxStyle11: TcxStyle;
cxStyle12: TcxStyle;
cxStyle13: TcxStyle;
cxStyle14: TcxStyle;
DisObjectGridStyle: TcxGridTableViewStyleSheet;
BsConstDset: TpFIBDataSet;
ActPrint: TAction;
ReportDB: TpFIBDatabase;
ReportWriteTrans: TpFIBTransaction;
ColumnGroupName: TcxGridDBColumn;
frDB: TfrxDBDataset;
frReport: TfrxReport;
PrintDSet: TpFIBDataSet;
frxHTMLExport1: TfrxHTMLExport;
frxXLSExport1: TfrxXLSExport;
frxXMLExport1: TfrxXMLExport;
frxPDFExport1: TfrxPDFExport;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnCloseClick(Sender: TObject);
procedure btnSelectClick(Sender: TObject);
procedure ReportGridDBViewDblClick(Sender: TObject);
procedure ReportDSetEndScroll(DataSet: TDataSet);
private
{ Private declarations }
procedure CloseConnect;
procedure ReportDSetCloseOpen;
public
{ Public declarations }
constructor Create(AParameter:TBsSimpleParams);reintroduce;
end;
var
frmReportLoader: TfrmReportLoader;
implementation
{$R *.dfm}
constructor TfrmReportLoader.Create(AParameter:TBsSimpleParams);
begin
inherited Create(AParameter.Owner);
ReportDB.Handle:=AParameter.Db_Handle;
BsConstDset.Close;
BsConstDset.SQLs.SelectSQL.Text:='SELECT DISTINCT * FROM BS_CONSTS';
BsConstDset.Open;
ReportDSetCloseOpen;
end;
procedure TfrmReportLoader.ReportDSetCloseOpen;
begin
if ReportDSet.Active then ReportDSet.Close;
ReportDSet.SQLs.SelectSQL.Text:='SELECT DISTINCT * FROM BS_DT_REPORTS_SEL ORDER BY NUM_REPORT';
ReportDSet.Open;
end;
procedure TfrmReportLoader.CloseConnect;
var i:Integer;
begin
for i:=0 to ReportDB.TransactionCount-1 do
begin
if ReportDB.Transactions[i].Active then ReportDB.Transactions[i].Rollback;
end;
ReportDB.Close;
end;
procedure TfrmReportLoader.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
CloseConnect;
if FormStyle = fsMDIChild then action:=caFree;
end;
procedure TfrmReportLoader.btnCloseClick(Sender: TObject);
begin
Close
end;
procedure TfrmReportLoader.btnSelectClick(Sender: TObject);
var sqlStr:String;
AParameter:TBsSimpleParams;
begin
if ReportDSet.IsEmpty then Exit;
if ReportDSet['With_Filters']=1 then
begin
AParameter:= TBsSimpleParams.Create;
AParameter.Owner:=self;
AParameter.Db_Handle:= ReportDB.Handle;
AParameter.Formstyle:=fsMDIChild;
AParameter.WaitPakageOwner:=self;
AParameter.ID_Locate:=ReportDSet['Id_Report'];
RunFunctionFromPackage(AParameter, 'BillingSystem\BsUnivReport.bpl','ShowUnivReport');
AParameter.Free;
end
else
begin
try
sqlStr:='SELECT DISTINCT * FROM '+ReportDSet['Name_Procedure'];
if not VarIsNull(ReportDSet['Add_Info']) then sqlStr:=sqlStr+ReportDSet['Add_Info'];
if PrintDSet.Active then PrintDSet.Close;
PrintDSet.SQLs.SelectSQL.Text:=sqlStr;
PrintDSet.Open;
if PrintDSet.IsEmpty then
begin
bsShowMessage('Увага!', 'Для формування звіту не має даних!', mtInformation, [mbOK]);
Exit;
end;
frReport.Clear;
frReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'Reports\'+ReportDSet['Name_Fr3'], True);
frReport.ShowReport(True);
except on E:Exception do
begin
bsShowMessage('Увага!', E.Message, mtInformation, [mbOK]);
end;
end;
end;
end;
procedure TfrmReportLoader.ReportGridDBViewDblClick(Sender: TObject);
begin
btnSelectClick(Sender);
end;
procedure TfrmReportLoader.ReportDSetEndScroll(DataSet: TDataSet);
begin
{if ReportDSet['With_Filters']=1 then btnSelect.Caption:='Показати звіт'
else btnSelect.Caption:='Друк звіту'; }
end;
end.
|
Unit UnitConexao;
interface
uses
Windows,
Classes,
IdTCPClient,
IdIOHandler,
UnitCompressString,
UnitConstantes,
InformacoesServidor,
UnitConfigs,
UnitExecutarComandos;
type
TConnectionHeader = record
Password: int64;
PacketSize: int64;
end;
type
TIdTCPClientNew = class(TIdTCPClient)
private
EnviandoString: boolean;
RecebendoString: boolean;
ConnectionPassword: int64;
procedure _EnviarString(xStr: WideString);
function _ReceberString: WideString;
public
constructor Create(AOwner: TComponent; Pass: int64);
procedure EnviarString(Str: WideString);
function ReceberString: WideString;
property FEnviandoString: boolean read EnviandoString write EnviandoString;
property FRecebendoString: boolean read RecebendoString write RecebendoString;
property FConnectionPassword: int64 read ConnectionPassword write ConnectionPassword;
end;
implementation
constructor TIdTCPClientNew.Create(AOwner: TComponent; Pass: int64);
begin
inherited Create(AOwner);
FEnviandoString := False;
FRecebendoString := False;
FConnectionPassword := Pass;
end;
procedure TIdTCPClientNew.EnviarString(Str: WideString);
begin
_EnviarString(Str);
end;
procedure TIdTCPClientNew._EnviarString(xStr: WideString);
var
ConnectionHeader: TConnectionHeader;
BytesHeader, ToSendStream: TMemoryStream;
i: integer;
Str: Widestring;
begin
Str := xStr;
if Str = '' then Exit;
if Connected = False then Exit;
i := 0;
while (i < 1000) and (Connected = True) and ((EnviandoString = True) or (RecebendoString = True)) do Sleep(random(100));
if Connected = False then Exit;
if i >= 1000 then Exit;
Str := CompressString(Str);
ToSendStream := TMemoryStream.Create;
ToSendStream.Write(pointer(Str)^, Length(Str) * 2);
ToSendStream.Position := 0;
ConnectionHeader.PacketSize := ToSendStream.Size;
ConnectionHeader.Password := ConnectionPassword;
BytesHeader := TMemoryStream.Create;
BytesHeader.Write(ConnectionHeader, SizeOf(TConnectionHeader));
BytesHeader.Position := 0;
EnviandoString := True;
try
IOHandler.Write(BytesHeader, BytesHeader.Size);
IOHandler.Write(ToSendStream, ToSendStream.Size);
finally
IOHandler.WriteBufferClear;
end;
EnviandoString := False;
BytesHeader.Free;
ToSendStream.Free;
end;
function TIdTCPClientNew.ReceberString: WideString;
begin
Result := _ReceberString;
end;
function TIdTCPClientNew._ReceberString: WideString;
var
ConnectionHeader: TConnectionHeader;
BytesHeader, ToRecvStream: TMemoryStream;
IsOK, Continue: boolean;
i: integer;
begin
result := '';
IsOK := True;
Continue := True;
if IOHandler.InputBufferIsEmpty then
begin
try
IOHandler.CheckForDataOnSource(10);
finally
if IOHandler.InputBufferIsEmpty then Continue := False;
end;
end;
if Continue = False then Exit;
if Connected = False then Exit;
i := 0;
while (i < 1000) and (Connected = True) and ((EnviandoString = True) or (RecebendoString = True)) do
begin
inc(i);
Sleep(random(100));
end;
if Connected = False then Exit;
if i >= 1000 then Exit;
RecebendoString := True;
try
Result := IOHandler.ReadLn;
except
Result := '';
end;
if Result = '' then
begin
RecebendoString := False;
Exit;
end else
if Result = PING then
begin
Result := PING + DelimitadorComandos;
RecebendoString := False;
Exit;
end;
BytesHeader := TMemoryStream.Create;
try
IOHandler.ReadStream(BytesHeader, SizeOf(TConnectionHeader), False);
except
Result := '';
RecebendoString := False;
Exit;
end;
if BytesHeader.Size >= SizeOf(TConnectionHeader) then
begin
BytesHeader.Position := 0;
BytesHeader.Read(ConnectionHeader, SizeOf(TConnectionHeader));
end else ConnectionHeader.Password := ConnectionPassword + 1;
BytesHeader.Free;
if ConnectionHeader.Password = ConfiguracoesServidor.Password then
begin
ToRecvStream := TMemoryStream.Create;
try
IOHandler.ReadStream(ToRecvStream, ConnectionHeader.PacketSize, False);
except
Result := '';
RecebendoString := False;
Exit;
end;
ToRecvStream.Position := 0;
if ToRecvStream.Size = ConnectionHeader.PacketSize then
begin
SetLength(Result, ToRecvStream.Size div 2);
ToRecvStream.Read(pointer(Result)^, ToRecvStream.Size);
Result := DecompressString(Result);
end;
ToRecvStream.Free;
end else IsOK := False;
RecebendoString := False;
if IsOK = False then Disconnect;
end;
end. |
{================================================================================
Copyright (C) 1997-2002 Mills Enterprise
Unit : rmToolWin
Purpose : This is a alternate form for all forms that use the bsSizableToolWin
borderstyle. This window does not suffer from the M$ ALT-Tab bug.
Date : 04-29-2001
Author : Ryan J. Mills
Version : 1.92
================================================================================}
unit rmToolWin;
interface
{$I CompilerDefines.INC}
uses windows, messages, classes, forms, Graphics;
type
TMoveSize = (msEntered, msMoving, msSizing, msExited) ;
TWMSizing = packed record
Msg: Cardinal;
SizingSide: Longint;
WindowRect: PRect;
Result: Longint;
end;
TWMMoving = TWMSizing;
TrmCustomToolWinForm = class(TCustomForm)
private
{ Private }
fInNCPaint: boolean;
fActive: boolean;
fMoveSize: TMoveSize;
fFrameRect, fLastFrameRect, FPosRect: TRect;
fCloseBtnDown, fCloseBtnPressed: boolean;
fOnMove: TNotifyEvent;
fWindowBMP: TBitmap;
fStandardMoving: boolean;
function AdjustFormFrameRect(wRect: TRect) : TRect;
procedure wmEnterSizeMove(var msg: TMessage) ; message WM_ENTERSIZEMOVE;
procedure wmExitSizeMove(var msg: TMessage) ; message WM_EXITSIZEMOVE;
procedure wmMoving(var msg: TWMMoving) ; message WM_MOVING;
procedure wmSizing(var msg: TWMSizing) ; message WM_SIZING;
procedure wmMove(Var msg: TWMMove) ; message wm_move;
procedure wmWindowPosChanging(var msg: TWMWindowPosChanging) ; message WM_WINDOWPOSCHANGING;
procedure WMNCActivate(var Message: TWMNCActivate) ; message WM_NCActivate;
procedure WMNCCalcSize(var Message: TWMNCCalcSize) ; message WM_NCCALCSIZE;
procedure WMNCHitTest(var Message: TWMNCHitTest) ; message WM_NCHITTEST;
procedure WMNCPaint(var Message: TMessage) ; message WM_NCPAINT;
procedure WMNCLButtonDown(var Message: TWMNCLButtonDown) ; message WM_NCLBUTTONDOWN;
procedure WMNCLButtonUp(var Message: TWMNCLButtonUp) ; message WM_NCLBUTTONUP;
procedure WMNCMouseMove(var Message: TWMNCMouseMove) ; message WM_NCMOUSEMOVE;
procedure WMLButtonUp(var Message: TWMLButtonUp) ; message WM_LBUTTONUP;
procedure WMMouseMove(var Message: TWMMouseMove) ; message WM_MOUSEMOVE;
procedure WMKillFocus(var msg: TWMKillFocus) ; message WM_KillFocus;
procedure SetInternalFrameRect(const Value: TRect) ;
procedure setncactive(const Value: boolean);
protected
{ Protected }
function FormCaptionRect(Screen: boolean) : TRect;
function FormCaptionTextRect(Screen: boolean) : TRect;
function FormBtnRect(Screen: boolean) : TRect;
function FormFrameRect(Screen: boolean) : TRect;
function FormClientRect(screen: boolean) : TRect;
property InternalFrameRect: TRect read fFrameRect write SetInternalFrameRect;
property OnMove: TNotifyEvent read fonMove write fOnMove;
property StandardMoving: boolean read fStandardMoving write fStandardMoving default true;
property MoveSize : TMoveSize read fMoveSize;
property NCActive : boolean read factive write setncactive;
public
{ Public }
constructor CreateNew(AOwner: TComponent; Dummy: Integer = 0) ; override;
destructor destroy; override;
end;
TrmToolWinForm = class(TrmCustomToolWinForm)
published
{ Published }
property Action;
property ActiveControl;
property Align;
property BiDiMode;
property BorderWidth;
property Caption;
property ClientHeight;
property ClientWidth;
property Color;
property Ctl3D;
property DefaultMonitor;
property Enabled;
property ParentFont default False;
property Font;
property Height;
property HelpFile;
property KeyPreview;
property Menu;
property OldCreateOrder;
property ParentBiDiMode;
property PixelsPerInch;
property PopupMenu;
property Position;
property PrintScale;
property Scaled;
property ShowHint;
property Visible;
property Width;
property OnActivate;
property OnCanResize;
property OnClick;
property OnClose;
property OnCloseQuery;
property OnContextPopup;
property OnCreate;
property OnDblClick;
property OnDestroy;
property OnDeactivate;
property OnDragDrop;
property OnDragOver;
property OnHide;
property OnHelp;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
property OnMouseWheelDown;
property OnMouseWheelUp;
property OnMove;
property OnPaint;
property OnResize;
property OnShortCut;
property OnShow;
end;
function WindowCaptionHeight: integer;
function WindowButtonHeight: integer;
function WindowButtonWidth: integer;
function WindowBorderWidth: integer;
function WindowBorderHeight: integer;
function WindowUseGradientCaption: Boolean;
function WindowCaptionFontName: string;
function WindowCaptionFontSize: integer;
function WindowCaptionFontStyle: TFontStyles;
implementation
uses rmLibrary, ExtCtrls;
const
PenSize = 3;
var
NewBrush: TBrush;
function WindowCaptionHeight: integer;
begin
result := GetSystemMetrics(SM_CYSMCAPTION) ; //Small Caption Height
end;
function WindowButtonHeight: integer;
begin
result := WindowCaptionHeight - 5;
end;
function WindowButtonWidth: integer;
begin
result := WindowButtonHeight + 2;
end;
function WindowBorderWidth: integer;
begin
result := GetSystemMetrics(SM_CXSIZEFRAME); //Sizeable Frame Width
end;
function WindowBorderHeight: integer;
begin
result := GetSystemMetrics(SM_CYSIZEFRAME); //Sizeable Frame Height
end;
function WindowUseGradientCaption: Boolean;
begin
SystemParametersInfo(SPI_GETGRADIENTCAPTIONS, 0, @Result, 0) ;
end;
function WindowCaptionFontName: string;
var
wMetrics: TNONCLIENTMETRICS;
begin
wMetrics.cbSize := sizeof(TNONCLIENTMETRICS) ;
SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(TNONCLIENTMETRICS) , @wMetrics, 0) ;
result := wMetrics.lfSmCaptionFont.lfFaceName;
end;
function WindowCaptionFontSize: integer;
var
wMetrics: TNONCLIENTMETRICS;
begin
wMetrics.cbSize := sizeof(TNONCLIENTMETRICS) ;
SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(TNONCLIENTMETRICS) , @wMetrics, 0) ;
result := wMetrics.lfSmCaptionFont.lfHeight;
end;
function WindowCaptionFontStyle: TFontStyles;
var
wMetrics: TNONCLIENTMETRICS;
begin
wMetrics.cbSize := sizeof(TNONCLIENTMETRICS) ;
SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(TNONCLIENTMETRICS) , @wMetrics, 0) ;
result := [];
if wMetrics.lfSmCaptionFont.lfWeight = fw_bold then
result := result + [fsbold];
if wMetrics.lfSmCaptionFont.lfItalic > 0 then
result := result + [fsItalic];
if wMetrics.lfSmCaptionFont.lfUnderline > 0 then
result := result + [fsUnderLine];
if wMetrics.lfSmCaptionFont.lfStrikeOut > 0 then
result := result + [fsStrikeOut];
end;
procedure DrawFrameRect(FrameRect: TRect) ;
var
DC: hDC; { device context for the window }
DesktopWindow: THandle;
OldHBrush: HBrush;
begin
DesktopWindow := GetDesktopWindow;
DC := GetDCEx(DesktopWindow, 0, DCX_CACHE or DCX_LOCKWINDOWUPDATE) ;
try
if NewBrush = nil then
begin
NewBrush := TBrush.Create;
NewBrush.Bitmap := AllocPatternBitmap(clBlack, clWhite) ;
end;
OldHBrush := SelectObject(DC, NewBrush.Handle) ;
with FrameRect do
begin
PatBlt(DC, Left + PenSize, Top, Right - Left - PenSize, PenSize, PATINVERT) ;
PatBlt(DC, Right - PenSize, Top + PenSize, PenSize, Bottom - Top - PenSize, PATINVERT) ;
PatBlt(DC, Left, Bottom - PenSize, Right - Left - PenSize, PenSize, PATINVERT) ;
PatBlt(DC, Left, Top, PenSize, Bottom - Top - PenSize, PATINVERT) ;
end;
SelectObject(DC, OldHBrush) ;
finally
ReleaseDC(DesktopWindow, DC) ;
end;
end;
{ TrmToolWinForm }
constructor TrmCustomToolWinForm.CreateNew(AOwner: TComponent; Dummy: Integer) ;
begin
inherited CreateNew(AOwner, Dummy) ;
if csDesigning in componentstate then exit;
fStandardMoving := true;
fWindowBMP := tbitmap.create;
AutoScroll := false;
VertScrollBar.Visible := false;
HorzScrollBar.Visible := false;
fActive := false;
fInNCPaint := false;
KeyPreview := true;
BorderStyle := bsNone;
fCloseBtnDown := false;
fCloseBtnPressed := false;
end;
procedure TrmCustomToolWinForm.wmEnterSizeMove(var msg: tmessage) ;
begin
if csDesigning in ComponentState then
begin
inherited;
exit;
end;
inherited;
FPosRect := BoundsRect;
fMoveSize := msEntered;
end;
procedure TrmCustomToolWinForm.wmExitSizeMove(var msg: tmessage) ;
begin
if csDesigning in ComponentState then
begin
inherited;
exit;
end;
if (fMoveSize = msMoving) then
begin
fMoveSize := msExited;
if not (fStandardMoving) then
begin
DrawFrameRect(fLastFrameRect) ;
SetBounds(fLastFrameRect.left, fLastFrameRect.top, width, height) ;
msg.Result := integer(true) ;
fLastFrameRect := Rect(0, 0, 0, 0) ;
end
else
inherited;
end
else
begin
fMoveSize := msExited;
inherited;
end;
Invalidate;
end;
procedure TrmCustomToolWinForm.wmMoving(var msg: TWMMoving) ;
begin
if csDesigning in ComponentState then
begin
inherited;
exit;
end;
inherited;
if fMoveSize = msEntered then
fMoveSize := msMoving;
if (fMoveSize = msMoving) then
begin
if not (fStandardMoving) then
begin
if not IsRectEmpty(fLastFrameRect) then
DrawFrameRect(fLastFrameRect) ;
fFrameRect := msg.WindowRect^;
try
DrawFrameRect(fFrameRect) ;
finally
fLastFrameRect := fFrameRect;
end;
end
else
fLastFrameRect := rect(0, 0, 0, 0) ;
end;
end;
procedure TrmCustomToolWinForm.wmSizing(var msg: TWMSizing) ;
var
xofs, yofs: integer;
wRect: TRect;
begin
if csDesigning in ComponentState then
begin
inherited;
exit;
end;
inherited;
if fMoveSize = msEntered then
fMoveSize := msSizing;
if (fMoveSize = msSizing) then
begin
wRect := msg.WindowRect^;
if not (((wRect.left <> 0) and (wRect.top <> 0) ) and
(((wrect.top <> top) and (wRect.bottom = height) ) or
((wrect.Left <> Left) and (wRect.right = width) ) ) ) then
begin
xofs := wRect.Left;
yofs := wRect.Top;
offsetrect(wRect, -xofs, -yofs) ;
try
wRect := AdjustFormFrameRect(wRect) ;
finally
offsetrect(wRect, xofs, yofs) ;
end;
end
else
begin
wRect := rect(left, top, width, height) ;
end;
InternalFrameRect := wRect;
end;
end;
procedure TrmCustomToolWinForm.wmWindowPosChanging(var msg: TWMWindowPosChanging) ;
var
wRect: trect;
begin
if csDesigning in ComponentState then
begin
inherited;
exit;
end;
if fMoveSize = msMoving then
begin
if fStandardMoving then
inherited
else
begin
msg.WindowPos.x := left;
msg.WindowPos.y := top;
Msg.Result := 0
end;
end
else if (fMoveSize = msSizing) then
begin
inherited;
wrect := AdjustFormFrameRect(rect(msg.windowpos.x, msg.windowpos.y, msg.windowpos.cx, msg.windowpos.cy) ) ;
msg.windowpos.x := wrect.left;
msg.windowpos.y := wrect.top;
msg.windowpos.cx := wrect.right;
msg.windowpos.cy := wrect.bottom;
end;
end;
procedure TrmCustomToolWinForm.WMNCCalcSize(var Message: TWMNCCalcSize) ;
begin
if csDesigning in ComponentState then
begin
inherited;
exit;
end;
//Adjust the size of the clientwidth rect for the drawing of the
//Borders
inherited;
with Message.CalcSize_Params^ do
begin
InflateRect(rgrc[0], -WindowBorderWidth, -WindowBorderHeight);
rgrc[0].top := rgrc[0].top + WindowCaptionHeight;
end;
end;
procedure TrmCustomToolWinForm.WMNCHitTest(var Message: TWMNCHitTest) ;
var
wpt: TPoint;
wRect: TRect;
BorderWidth, BorderHeight: integer;
begin
if csDesigning in ComponentState then
begin
inherited;
exit;
end;
inherited;
//Figure out where the hell the mouse is in relation to
//what's on the window....
BorderWidth := WindowBorderWidth;
BorderHeight := WindowBorderHeight;
wpt := Point(Message.XPos, Message.YPos) ;
wRect := FormFrameRect(true) ;
if (PtInRect(Rect(wRect.left, wRect.top, wRect.Left + 10 + borderwidth, wRect.top + borderheight) , wpt) or
PtInRect(Rect(wRect.Left, wRect.top, wRect.Left + BorderWidth, wRect.top + 10 + borderheight) , wpt) ) then //TopLeft
begin
Message.Result := htTopLeft;
end
else if (PtInRect(Rect(wRect.right - (10 + borderwidth) , wRect.bottom - borderheight, wRect.right, wRect.bottom) , wpt) or
PtInRect(Rect(wRect.right - BorderWidth, wRect.bottom - (10 + borderheight) , wRect.right, wRect.bottom) , wpt) ) then //BottomRight
begin
Message.Result := htBottomRight;
end
else if (PtInRect(Rect(wRect.right - (10 + borderwidth) , wRect.top, wRect.right, wRect.top + borderheight) , wpt) or
PtInRect(Rect(wRect.right - BorderWidth, wRect.top, wRect.right, wRect.top + (10 + borderheight) ) , wpt) ) then //TopRight
begin
Message.Result := htTopRight;
end
else if (PtInRect(Rect(wRect.Left, wRect.bottom - (10 + borderheight) , wRect.left + BorderWidth, wRect.bottom) , wpt) or
PtInRect(Rect(wRect.Left, wRect.bottom - borderheight, wRect.left + (10 + borderwidth) , wRect.bottom) , wpt) ) then //BottomRight
begin
Message.Result := htBottomLeft;
end
else if PtInRect(Rect(wRect.left + 10 + borderWidth, wRect.top, wRect.right - (10 + borderWidth) , wRect.top + borderheight) , wpt) then //Top
begin
Message.Result := htTop;
end
else if PtInRect(Rect(wRect.Left, wRect.top + 10 + borderheight, wRect.Left + BorderWidth, wRect.bottom - (10 + borderheight) ) , wpt) then //Left
begin
Message.Result := htLeft;
end
else if PtInRect(Rect(wRect.left + 10 + borderWidth, wRect.Bottom - borderheight, wRect.right - (10 + borderWidth) , wRect.Bottom) , wpt) then //bottom
begin
Message.Result := htBottom;
end
else if PtInRect(Rect(wRect.right - BorderWidth, wRect.top + 10 + borderheight, wRect.right, wRect.bottom - (10 + borderheight) ) , wpt) then //Right
begin
Message.Result := htRight;
end
else if PtInRect(FormBtnRect(true) , wpt) then //CloseButton
begin
Message.Result := htClose;
end
else if PtInRect(FormCaptionRect(true) , wpt) then //Caption
begin
Message.Result := htCaption;
end
else if PtInRect(FormClientRect(true) , wpt) then //Client
begin
Message.Result := htclient;
end
else
Message.result := HTNOWHERE;
end;
procedure TrmCustomToolWinForm.WMNCPaint(var Message: TMessage) ;
var
DC: HDC;
wRect: TRect;
Rgn1, Rgn2, Rgn3: HRGN;
cLeft, cRight: TColor;
wFrameRect, wCaptionRect, wBtnRect, wCaptionTextRect, wClientRect: TRect;
begin
if csDesigning in ComponentState then
begin
inherited;
exit;
end;
//This is where the magic of the whole thing comes into play....
wFrameRect := FormFrameRect(false) ;
wCaptionRect := FormCaptionRect(false) ;
wBtnRect := FormBtnRect(false) ;
wCaptionTextRect := FormCaptionTextRect(false) ;
wClientRect := FormClientRect(false) ;
fInNCPaint := true;
try
fWindowBMP.Width := wFrameRect.right - wFrameRect.left;
fWindowBMP.height := wFrameRect.bottom - wFrameRect.Top;
fWindowBMP.canvas.Brush.Color := Color;
fWindowBMP.Canvas.FillRect(wFrameRect) ;
if WinOSVersion in [wosWin98, wosWinNT2k] then
begin
if WindowUseGradientCaption then
begin
if fActive or Self.Focused then
begin
cLeft := clActiveCaption;
cRight := clGradientActiveCaption;
fWindowBMP.Canvas.font.Color := clCaptionText;
end
else
begin
cLeft := clInActiveCaption;
cRight := clGradientInactiveCaption;
fWindowBMP.Canvas.font.Color := clInactiveCaptionText;
end;
GradientFill(fWindowBMP.canvas, cLeft, cRight, wCaptionRect) ;
end
else
begin
if fActive or Self.Focused then
begin
fWindowBMP.Canvas.brush.color := clActiveCaption;
fWindowBMP.Canvas.font.Color := clCaptionText;
end
else
begin
fWindowBMP.Canvas.brush.color := clInActiveCaption;
fWindowBMP.Canvas.font.Color := clInactiveCaptionText;
end;
fWindowBMP.Canvas.fillrect(wCaptionRect) ;
end;
end
else
begin
if fActive or Self.Focused then
begin
fWindowBMP.Canvas.brush.color := clActiveCaption;
fWindowBMP.Canvas.font.Color := clCaptionText;
end
else
begin
fWindowBMP.Canvas.brush.color := clInActiveCaption;
fWindowBMP.Canvas.font.Color := clInactiveCaptionText;
end;
fWindowBMP.Canvas.fillrect(wCaptionRect) ;
end;
fWindowBMP.Canvas.Pen.Color := clBtnFace;
fWindowBMP.Canvas.MoveTo(wCaptionRect.Left, wCaptionRect.Bottom - 1) ;
fWindowBMP.Canvas.LineTo(wCaptionRect.Right, wCaptionRect.Bottom - 1) ;
fWindowBMP.Canvas.font.name := WindowCaptionFontName;
fWindowBMP.Canvas.font.height := WindowCaptionFontSize;
fWindowBMP.Canvas.Brush.Style := bsClear;
fWindowBMP.Canvas.Font.Style := WindowCaptionFontStyle;
wRect := wCaptionTextRect;
DrawText(fWindowBMP.Canvas.handle, pchar(caption) , length(caption) , wRect, DT_SINGLELINE or DT_VCENTER or DT_END_ELLIPSIS) ;
DrawFrameControl(fWindowBMP.canvas.handle, wBtnRect, DFC_Caption, DFCS_CAPTIONCLOSE) ;
wRect := wFrameRect;
if Parent = nil then
begin
Frame3D(fWindowBMP.Canvas, wRect, cl3DLight, cl3DDkShadow, 1) ;
Frame3D(fWindowBMP.Canvas, wRect, clBtnHighlight, clBtnShadow, 1) ;
end
else
begin
Frame3D(fWindowBMP.Canvas, wRect, clBtnface, clBtnface, 2) ;
end;
Frame3D(fWindowBMP.Canvas, wRect, clBtnface, clBtnface, 2) ;
Rgn1 := CreateRectRgn(wFrameRect.Left, wFrameRect.Top, wFrameRect.Right, wFrameRect.Bottom) ;
GetWindowRgn(handle, Rgn1) ;
Rgn2 := CreateRectRgn(wClientRect.Left, wClientRect.Top, wClientRect.Right, wClientRect.Bottom) ;
Rgn3 := CreateRectRgn(0, 0, width, height) ;
CombineRgn(Rgn3, Rgn1, Rgn2, Rgn_XOR) ;
try
if Rgn3 <> 0 then
SetWindowRgn(handle, Rgn3, false) ;
DC := GetWindowDC(Handle) ;
try
BitBlt(DC, 0, 0, fWindowBMP.width, fWindowBMP.height, fWindowBMP.Canvas.Handle, 0, 0, SRCCOPY) ;
finally
ReleaseDC(Handle, DC) ;
end;
finally
SetWindowRgn(handle, 0, false) ;
DeleteObject(Rgn1) ;
DeleteObject(Rgn2) ;
DeleteObject(Rgn3) ;
end;
finally
fInNCPaint := false;
end;
Message.result := 0;
end;
function TrmCustomToolWinForm.FormFrameRect(Screen: boolean) : TRect;
begin
if Screen then
result := BoundsRect
else
begin
if fMoveSize = msSizing then
begin
result := InternalFrameRect;
offsetrect(result, -result.left, -result.Top) ;
end
else
result := rect(0, 0, width, height) ;
end;
end;
function TrmCustomToolWinForm.FormCaptionRect(screen: boolean) : TRect;
begin
result := FormFrameRect(screen) ;
InflateRect(result, -WindowBorderWidth, -WindowBorderHeight) ;
Result.Bottom := Result.top + WindowCaptionHeight;
end;
function TrmCustomToolWinForm.FormCaptionTextRect(Screen: boolean) : TRect;
begin
result := FormCaptionRect(screen) ;
Result.left := Result.Left + 2;
Result.right := Result.right - WindowButtonWidth - 2;
end;
function TrmCustomToolWinForm.FormBtnRect(screen: boolean) : TRect;
begin
Result := FormCaptionRect(screen) ;
Result.Right := Result.Right - 2;
Result.Left := Result.Right - WindowButtonWidth;
Result.top := Result.top + 2;
Result.bottom := Result.top + WindowButtonHeight;
end;
function TrmCustomToolWinForm.FormClientRect(screen: boolean) : TRect;
var
wRect: TRect;
begin
if screen then
wRect := rect(ClientOrigin.x, ClientOrigin.y, ClientOrigin.x + clientwidth, ClientOrigin.y + clientheight)
else
begin
wRect := ClientRect;
OffsetRect(wRect, WindowBorderWidth, WindowBorderheight + WindowCaptionHeight) ;
end;
result := wRect;
end;
procedure TrmCustomToolWinForm.WMNCLButtonDown(var Message: TWMNCLButtonDown) ;
var
DC: HDC;
begin
if csDesigning in ComponentState then
begin
inherited;
exit;
end;
DC := GetWindowDC(handle) ;
try
if Message.HitTest = htClose then
begin
SendCancelMode(Self) ;
MouseCapture := true;
DrawFrameControl(DC, FormBtnRect(false) , DFC_Caption, DFCS_CAPTIONCLOSE or DFCS_PUSHED) ;
fCloseBtnPressed := true;
Message.Result := 0;
end
else
inherited;
finally
if DC <> 0 then
ReleaseDC(handle, DC) ;
end;
end;
procedure TrmCustomToolWinForm.WMNCLButtonUp(var Message: TWMNCLButtonUp) ;
var
DC: HDC;
begin
if csDesigning in ComponentState then
begin
inherited;
exit;
end;
DC := GetWindowDC(handle) ;
try
DrawFrameControl(DC, FormBtnRect(false) , DFC_Caption, DFCS_CAPTIONCLOSE) ;
if fCloseBtnPressed and (Message.HitTest = htClose) then
begin
Message.Result := 0;
close;
end
else
inherited;
finally
fCloseBtnPressed := false;
if DC <> 0 then
ReleaseDC(handle, DC) ;
end;
end;
procedure TrmCustomToolWinForm.WMNCMouseMove(var Message: TWMNCMouseMove) ;
var
DC: HDC;
begin
if csDesigning in ComponentState then
begin
inherited;
exit;
end;
try
DC := GetWindowDC(handle) ;
try
if fCloseBtnPressed then
begin
if Message.HitTest = htClose then
DrawFrameControl(DC, FormBtnRect(false) , DFC_Caption, DFCS_PUSHED or DFCS_CAPTIONCLOSE)
else
DrawFrameControl(DC, FormBtnRect(false) , DFC_Caption, DFCS_CAPTIONCLOSE) ;
message.result := 0;
end
else
inherited;
finally
if DC <> 0 then
ReleaseDC(handle, DC) ;
end;
except
//for some reason we occasionally get a Range Checking error here.
end;
end;
procedure TrmCustomToolWinForm.WMLButtonUp(var Message: TWMLButtonUp) ;
var
DC: HDC;
pt: TPoint;
WasBtnPressed: boolean;
begin
if csDesigning in ComponentState then
begin
inherited;
exit;
end;
WasBtnPressed := fCloseBtnPressed;
fCloseBtnPressed := false;
MouseCapture := false;
DC := GetWindowDC(handle) ;
try
DrawFrameControl(DC, FormBtnRect(false) , DFC_Caption, DFCS_CAPTIONCLOSE) ;
pt := clienttoscreen(point(message.XPos, Message.YPos) ) ;
if WasBtnPressed and ptInRect(FormBtnRect(true) , pt) then
begin
Message.Result := 0;
close;
end
else
inherited;
finally
if DC <> 0 then
ReleaseDC(handle, DC) ;
end;
end;
procedure TrmCustomToolWinForm.WMMouseMove(var Message: TWMMouseMove) ;
var
DC: HDC;
pt: TPoint;
begin
if csDesigning in ComponentState then
begin
inherited;
exit;
end;
DC := GetWindowDC(handle) ;
try
if fCloseBtnPressed then
begin
pt := clienttoscreen(point(message.XPos, Message.YPos) ) ;
if ptInRect(FormBtnRect(true) , pt) then
DrawFrameControl(DC, FormBtnRect(false) , DFC_Caption, DFCS_PUSHED or DFCS_CAPTIONCLOSE)
else
DrawFrameControl(DC, FormBtnRect(false) , DFC_Caption, DFCS_CAPTIONCLOSE) ;
message.result := 0;
end
else
inherited;
finally
if DC <> 0 then
ReleaseDC(handle, DC) ;
end;
end;
procedure TrmCustomToolWinForm.WMNCActivate(var Message: TWMNCActivate) ;
begin
inherited;
//Your supposed to pass the handle of the region to paint according to the Win32 API
//But because I'm handling the NCPainting myself, I figure that I can skip passing the
//handle of the rgn. Mostly because I'm not paying attention to it in the first place.
fActive := Message.active;
SendMessage(self.handle, wm_ncPaint, 0, 0) ;
end;
procedure TrmCustomToolWinForm.WMKillFocus(var msg: TWMKillFocus) ;
begin
inherited;
fActive := false;
SendMessage(self.handle, wm_ncPaint, 0, 0) ;
end;
function TrmCustomToolWinForm.AdjustFormFrameRect(wRect: TRect) : TRect;
var
fixed: boolean;
wPosRect: TRect;
begin
wPosRect := fPosRect;
fixed := false;
if wRect.right <= 40 + (WindowButtonWidth + (WindowBorderWidth * 2) + 6) then
begin
wRect.right := 40 + (WindowButtonWidth + (WindowBorderWidth * 2) + 6) ;
fixed := true;
end;
if wRect.bottom <= (WindowCaptionHeight + (WindowBorderWidth * 2) ) then
begin
wRect.bottom := (WindowCaptionHeight + (WindowBorderWidth * 2) ) ;
fixed := true;
end;
if fixed then
begin
if wRect.left > wPosRect.left then
wRect.left := wPosRect.right - wRect.right;
if wRect.top > wPosRect.Top then
wRect.top := wPosRect.bottom - wRect.bottom;
end;
result := wRect;
end;
procedure TrmCustomToolWinForm.SetInternalFrameRect(const Value: TRect) ;
begin
fFrameRect := Value;
end;
procedure TrmCustomToolWinForm.wmMove(var msg: TwmMove) ;
begin
inherited;
if assigned(fonMove) then
fOnMove(self) ;
end;
destructor TrmCustomToolWinForm.destroy;
begin
fWindowBMP.free;
inherited;
end;
procedure TrmCustomToolWinForm.setncactive(const Value: boolean);
begin
factive := Value;
SendMessage(self.handle, wm_ncPaint, 0, 0) ;
end;
initialization
NewBrush := TBrush.Create;
NewBrush.Bitmap := AllocPatternBitmap(clBlack, clWhite) ;
finalization
if assigned(NewBrush) then
NewBrush.free;
end.
|
unit UMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, ExtCtrls, ComCtrls, StdCtrls;
type
TNode = record
x, y: Integer;
number: Integer;
end;
TPrices = array [1..10, 1..10] of Integer;
TPath = record
str: String;
val: Integer;
end;
TPathes = array of TPath;
TfrmMain = class(TForm)
pnlControls: TPanel;
strgMatrix: TStringGrid;
editNumOfNodes: TEdit;
udNumOfNodes: TUpDown;
editFrom: TEdit;
editTo: TEdit;
udTo: TUpDown;
udFrom: TUpDown;
labelFrom: TLabel;
labelTo: TLabel;
btnShowGraph: TButton;
memoPathes: TMemo;
imgGraph: TImage;
procedure editFromKeyPress(Sender: TObject; var Key: Char);
procedure editToKeyPress(Sender: TObject; var Key: Char);
procedure editNumOfNodesKeyPress(Sender: TObject; var Key: Char);
procedure editNumOfNodesChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnShowGraphClick(Sender: TObject);
procedure strgMatrixKeyPress(Sender: TObject; var Key: Char);
private
PNumberOfNodes: Integer;
nodes: array of TNode;
matrix: TPrices;
procedure SetNumberOfNodes(const Value: Integer);
property numberOfNodes: Integer read PNumberOfNodes write SetNumberOfNodes;
procedure setColRowNames;
procedure setNodes(rad: Integer);
procedure fillMatrix;
procedure randomFillGrid;
procedure clearImage;
procedure drawNodeWithText(x, y, rad: Integer; note: String);
procedure drawNodes(rad: Integer);
procedure drawLines(rad: Integer);
procedure drawLine(nodeA, nodeB: TNode; rad, noteA, noteB: Integer);
procedure drawCenter(node: TNode; rad: Integer);
function findCenter(matrix: TPrices; num: Integer):Integer;
function floid(matrix: TPrices; num: Integer):TPrices;
procedure findPathes(a, b: Integer; var pathes: TPathes; str: String; val: Integer);
procedure outputPathes(pathes: TPathes);
procedure sortPathes(var pathes: TPathes);
function getSpaces(n: Integer):String;
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
uses Math;
{$R *.dfm}
procedure TfrmMain.setColRowNames;
var
i: Integer;
begin
for i := 1 to numberOfNodes do
begin
strgMatrix.Cells[i, 0] := IntToStr(i);
strgMatrix.Cells[0, i] := IntToStr(i);
end;
end;
procedure TfrmMain.SetNumberOfNodes(const Value: Integer);
begin
PNumberOfNodes := Value;
if udTo.Position > Value then
udTo.Position := Value;
if udFrom.Position > Value then
udFrom.Position := Value;
udTo.Max := Value;
udFrom.Max := Value;
strgMatrix.ColCount := Value + 1;
strgMatrix.RowCount := Value + 1;
strgMatrix.DefaultColWidth := trunc((strgMatrix.Width - Value * 1.5) / (Value + 1));
strgMatrix.DefaultRowHeight := trunc((strgMatrix.Height - Value * 1.5) / (Value + 1));
setColRowNames;
end;
procedure TfrmMain.editFromKeyPress(Sender: TObject; var Key: Char);
begin
if not (key in ['0'..'9', #8]) then
key := #0;
if (editFrom.Text = '1') and (key <> '0') and (key <> #8) then
key := #0;
end;
procedure TfrmMain.editToKeyPress(Sender: TObject; var Key: Char);
begin
if not (key in ['0'..'9', #8]) then
key := #0;
if (editTo.Text = '1') and (key <> '0') and (key <> #8) then
key := #0;
end;
procedure TfrmMain.editNumOfNodesKeyPress(Sender: TObject; var Key: Char);
begin
if not (key in ['0'..'9', #8]) then
key := #0;
if (editNumOfNodes.Text = '1') and (key <> '0') and (key <> #8) then
key := #0;
end;
procedure TfrmMain.editNumOfNodesChange(Sender: TObject);
begin
if editNumOfNodes.Text = '' then
numberOfNodes := 1
else
numberOfNodes := StrToInt(editNumOfNodes.Text);
end;
procedure TfrmMain.clearImage;
begin
with imgGraph.Canvas do
begin
Brush.Color := clWhite;
FillRect(Rect(0, 0, imgGraph.Width, imgGraph.Height));
end;
end;
procedure TfrmMain.drawNodeWithText(x, y, rad: Integer; note: String);
begin
with imgGraph.Canvas do
begin
Pen.Color := clBlue;
Brush.Color := clBlue;
Ellipse(x - rad, y - rad, x + rad, y + rad);
Font.Color := clWhite;
TextOut(x - TextWidth(note) div 2, y - TextHeight(note) div 2, note);
end;
end;
procedure TfrmMain.randomFillGrid;
var
i, j: Integer;
begin
Randomize;
for i := 1 to 10 do
begin
for j := 1 to 10 do
begin
if i = j then
strgMatrix.Cells[j, i] := ''
else
if random(2) = 1 then
strgMatrix.Cells[j, i] := IntToStr(random(100))
else
strgMatrix.Cells[j, i] := '0';
end;
end;
end;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
clearImage;
numberOfNodes := 5;
randomFillGrid;
end;
procedure TfrmMain.setNodes(rad: Integer);
var
i: Integer;
phi, alpha: Real;
begin
SetLength(nodes, numberOfNodes);
phi := 2 * Pi / numberOfNodes;
alpha := phi;
for i := 0 to numberOfNodes - 1 do
begin
nodes[i].number := i + 1;
nodes[i].x := round(rad * cos(alpha) + imgGraph.Width / 2);
nodes[i].y := round(rad * sin(alpha) + imgGraph.Height / 2);
alpha := alpha + phi;
end;
end;
procedure TfrmMain.drawNodes(rad: Integer);
var
i: Integer;
begin
for i := 0 to numberOfNodes - 1 do
drawNodeWithText(nodes[i].x, nodes[i].y, rad, IntToStr(nodes[i].number));
end;
procedure TfrmMain.fillMatrix;
var
i, j: Integer;
begin
for i := 1 to numberOfNodes do
begin
for j := 1 to numberOfNodes do
begin
if strgMatrix.Cells[j, i] = '' then
matrix[i, j] := 0
else
matrix[i, j] := StrToInt(strgMatrix.Cells[j, i]);
end;
end;
end;
procedure TfrmMain.drawLine(nodeA, nodeB: TNode; rad, noteA, noteB: Integer);
var
dx, dy, sinPhi, cosPhi, radDx, radDy: Real;
begin
dy := abs(nodeA.y - nodeB.y);
dx := abs(nodeA.x - nodeB.x);
if (dy <> 0) or (dx <> 0) then
begin
sinPhi := dy / sqrt(sqr(dx) + sqr(dy));
cosPhi := dx / sqrt(sqr(dx) + sqr(dy));
radDx := cosPhi;
radDy := sinPhi;
if nodeA.x < nodeB.x then
radDx := -radDx;
if nodeA.y < nodeB.y then
radDy := -radDy;
radDy := rad * radDy;
radDx := rad * radDx;
nodeA.x := round(nodeA.x - radDx);
nodeA.y := round(nodeA.y - radDy);
nodeB.x := round(nodeB.x + radDx);
nodeB.y := round(nodeB.y + radDy);
with imgGraph.Canvas do
begin
Pen.Color := clBlack;
MoveTo(nodeA.x, nodeA.y);
LineTo(nodeB.x, nodeB.y);
if noteA <> 0 then
begin
Pen.Color := clRed;
Brush.Color := clRed;
Ellipse(nodeB.x - 5, nodeB.y - 5, nodeB.x + 5, nodeB.y + 5);
Pen.Color := clBlack;
Brush.Color := clWhite;
Font.Color := clBlack;
Font.Name := 'Tahoma';
Font.Size := 7;
Ellipse(round(nodeB.x + radDx - 10),
round(nodeB.y + radDy - 5),
round(nodeB.x + radDx + 10),
round(nodeB.y + radDy + 5));
TextOut(round(nodeB.x + radDx - TextWidth(IntToStr(noteA)) / 2),
round(nodeB.y + radDy - TextHeight(IntToStr(noteA)) / 2),
IntToStr(noteA));
end;
if noteB <> 0 then
begin
Pen.Color := clRed;
Brush.Color := clRed;
Ellipse(nodeA.x - 5, nodeA.y - 5, nodeA.x + 5, nodeA.y + 5);
Pen.Color := clBlack;
Brush.Color := clWhite;
Font.Color := clBlack;
Font.Name := 'Tahoma';
Font.Size := 7;
Ellipse(round(nodeA.x - radDx - 10),
round(nodeA.y - radDy - 5),
round(nodeA.x - radDx + 10),
round(nodeA.y - radDy + 5));
TextOut(round(nodeA.x - radDx - TextWidth(IntToStr(noteB)) / 2),
round(nodeA.y - radDy - TextHeight(IntToStr(noteB)) / 2),
IntToStr(noteB));
end;
end;
end
end;
procedure TfrmMain.drawLines(rad: Integer);
var
i, j: Integer;
begin
for i := 1 to numberOfNodes do
begin
for j := 1 to i - 1 do
if (matrix[i, j] <> 0) or (matrix[j, i] <> 0) then
drawLine(nodes[i - 1], nodes[j - 1], rad, matrix[i, j], matrix[j, i]);
end;
end;
procedure TfrmMain.drawCenter(node: TNode; rad: Integer);
begin
with imgGraph.Canvas do
begin
Brush.Color := clWhite;
Pen.Color := clRed;
Ellipse(node.x - rad, node.y - rad, node.x + rad, node.y + rad);
end;
end;
function TfrmMain.floid(matrix: TPrices; num: Integer):TPrices;
var
prices: TPrices;
k, i, j: Integer;
begin
result := matrix;
for i := 1 to num do
for j := 1 to num do
begin
if i = j then
result[i, j] := 0;
if (result[i, j] = 0) and (i <> j) then
result[i, j] := MaxInt div 3;
end;
for k := 1 to num do
begin
prices := result;
for i := 1 to num do
for j := 1 to num do
if prices[i, k] + prices[k, j] < result[i, j] then
result[i, j] := prices[i, k] + prices[k, j];
end;
end;
function TfrmMain.findCenter(matrix: TPrices; num: Integer):Integer;
var
prices: TPrices;
k, i, j: Integer;
begin
prices := floid(matrix, num);
for j := 1 to num do
for i := 2 to num do
if prices[i, j] > prices[1, j] then
prices[1, j] := prices[i, j];
k := prices[1, 1];
result := 1;
for j := 2 to num do
if prices[1, j] < k then
begin
k := prices[1, j];
result := j;
end;
end;
procedure TfrmMain.findPathes(a, b: Integer; var pathes: TPathes; str: String; val: Integer);
var
j: Integer;
visit: Boolean;
begin
if a = b then
begin
SetLength(pathes, length(pathes) + 1);
pathes[length(pathes) - 1].str := str;
pathes[length(pathes) - 1].val := val;
end
else
begin
for j := 1 to numberOfNodes do
begin
matrix[j, j] := 0;
if matrix[a, j] <> 0 then
begin
visit := pos(IntToStr(j), str) = 0;
if visit then
findPathes(j, b, pathes, str + IntToStr(j) + ' ', val + matrix[a, j]);
end;
end;
end;
end;
function TfrmMain.getSpaces(n: Integer): String;
var
i: Integer;
begin
result := '';
for i := 1 to n do
result := result + ' ';
end;
procedure TfrmMain.sortPathes(var pathes: TPathes);
var
i, j, temp: Integer;
tempStr: String;
begin
for i := 1 to length(pathes) - 1 do
begin
for j := length(pathes) - 1 downto i do
begin
if pathes[j - 1].val > pathes[j].val then
begin
temp := pathes[j - 1].val;
pathes[j - 1].val := pathes[j].val;
pathes[j].val := temp;
tempStr := pathes[j - 1].str;
pathes[j - 1].str := pathes[j].str;
pathes[j].str := tempStr;
end;
end;
end;
end;
procedure TfrmMain.outputPathes(pathes: TPathes);
var
i, max: Integer;
begin
memoPathes.Font.Name := 'Courier New';
memoPathes.Lines.Clear;
sortPathes(pathes);
max := 0;
for i := 0 to length(pathes) - 1 do
if length(pathes[i].str) > max then
max := length(pathes[i].str);
for i := 0 to length(pathes) - 1 do
memoPathes.Lines.Add(pathes[i].str + getSpaces(max - length(pathes[i].str) + 5) + IntToStr(pathes[i].val));
end;
procedure TfrmMain.btnShowGraphClick(Sender: TObject);
var
pathes: TPathes;
a, b: Integer;
begin
fillMatrix;
clearImage;
setNodes(200);
drawCenter(nodes[findCenter(matrix, numberOfNodes) - 1], 30);
drawNodes(20);
drawLines(20);
if editFrom.Text = '' then
editFrom.Text := '1';
if editTo.Text = '' then
editTo.Text := IntToStr(numberOfNodes);
a := StrToInt(editFrom.Text);
b := StrToInt(editTo.Text);
findPathes(a, b, pathes, editFrom.Text + ' ', 0);
outputPathes(pathes);
end;
procedure TfrmMain.strgMatrixKeyPress(Sender: TObject; var Key: Char);
begin
if not (Key in ['0'..'9', #8]) then
key := #0;
end;
end.
|
{
Copyright (c) 2016, Vencejo Software
Distributed under the terms of the Modified BSD License
The full license is distributed with this software
}
unit ooConfigSectionTest;
interface
uses
ooTextKey,
ooDataInput.Intf, ooDataOutput.Intf,
ooConfig.Intf;
type
TConfigSectionTest = class sealed(TInterfacedObject, IConfigSection)
strict private
const
INT_KEY = 'IntegerValue';
STR_KEY = 'StringValue';
BOOL_KEY = 'BooleanValue';
public
ValueInteger: Longint;
ValueString: string;
ValueBoolean: Boolean;
function Marshal(const DataOutput: IDataOutput): Boolean;
function Unmarshal(const DataInput: IDataInput): Boolean;
function Name: String;
function Description: String;
class function New: IConfigSection;
end;
implementation
function TConfigSectionTest.Name: String;
begin
Result := 'SECTION_TEST';
end;
function TConfigSectionTest.Description: String;
begin
Result := 'Config test';
end;
function TConfigSectionTest.Unmarshal(const DataInput: IDataInput): Boolean;
begin
ValueInteger := DataInput.ReadInteger(TTextKey.New(INT_KEY));
ValueString := DataInput.ReadString(TTextKey.New(STR_KEY));
ValueBoolean := DataInput.ReadBoolean(TTextKey.New(BOOL_KEY));
Result := True;
end;
function TConfigSectionTest.Marshal(const DataOutput: IDataOutput): Boolean;
begin
DataOutput.WriteInteger(TTextKey.New(INT_KEY), ValueInteger);
DataOutput.WriteString(TTextKey.New(STR_KEY), ValueString);
DataOutput.WriteBoolean(TTextKey.New(BOOL_KEY), ValueBoolean);
Result := True;
end;
class function TConfigSectionTest.New: IConfigSection;
begin
Result := TConfigSectionTest.Create;
end;
end.
|
unit ConsoleToolbox;
{ Basic toolbox for building command line apps in this package }
interface
uses SysUtils;
{ Cast BadUsage(err) to terminate app and output usage information, perhaps with
a error message. }
type
EBadUsage = class(Exception);
procedure BadUsage(const AMessage: string = '');
{ Returns the filename of the current program }
function ProgramName: string;
function ProgramFolder: string;
type
TCommandLineApp = class
protected
function HandleSwitch(const s: string; var i: integer): boolean; virtual;
function HandleParam(const s: string; var i: integer): boolean; virtual;
public
procedure Init; virtual; //Initialize any variables
procedure ParseCommandLine; virtual; //usually you don't need to override this
procedure Run; virtual; //do actual work
procedure ShowUsage; overload; virtual; //override this one preferably, the other one resorts to it
procedure ShowUsage(const AMessage: string); overload; virtual;
end;
CCommandLineApp = class of TCommandLineApp;
{ Application instance. Set it if you create application object by hand }
var
Application: TCommandLineApp;
{ Creates and runs a command line application in a default fashion.
You may write your own version of this if you need anything more fancy. }
procedure RunApp(const AAppClass: CCommandLineApp);
implementation
procedure BadUsage(const AMessage: string);
begin
raise EBadUsage.Create(AMessage);
end;
function ProgramName: string;
begin
Result := ExtractFilename(ParamStr(0));
end;
function ProgramFolder: string;
begin
Result := ExtractFilePath(ParamStr(0));
end;
{ Override to initialize any variables }
procedure TCommandLineApp.Init;
begin
end;
{ To add any after-the-parsing checks, override, call inherited then check. }
procedure TCommandLineApp.ParseCommandLine;
var i: integer;
s: string;
begin
i := 1;
while i<=ParamCount do begin
s := Trim(AnsiLowerCase(ParamStr(i)));
if s='' then continue;
if (s[1]='-') or (s[1]='/') then begin
if not HandleSwitch(s, i) then
BadUsage(s+' is not a valid switch.');
end else
if not HandleParam(s, i) then
BadUsage('I do not understand what do you mean by '+s+'.');
Inc(i);
end;
end;
{ Override to handle switches. If your switch takes any params, you have to
increment i accordingly. E.g. 3 params => i := i+3; at the end. }
function TCommandLineApp.HandleSwitch(const s: string; var i: integer): boolean;
begin
Result := false;
end;
{ Override to handle params that are not switches, and not trailing params for
switches. }
function TCommandLineApp.HandleParam(const s: string; var i: integer): boolean;
begin
Result := false;
end;
procedure TCommandLineApp.Run;
begin
end;
{ Shows the usage information. Override if your case is more complicated }
procedure TCommandLineApp.ShowUsage;
begin
writeln(ErrOutput, 'Usage: '+ProgramName); //and that's it.
end;
{ Shows the error message + the usage information. Usually you don't need to
override this one. }
procedure TCommandLineApp.ShowUsage(const AMessage: string);
begin
if AMessage<>'' then
writeln(ErrOutput, AMessage);
ShowUsage;
end;
procedure DumpException(E: Exception);
begin
while E<>nil do begin
Writeln(ErrOutput, E.ClassName, ': ', E.Message);
if E.StackTrace<>'' then
Writeln(ErrOutput, E.StackTrace);
E := E.InnerException;
if E<>nil then
Writeln(ErrOutput, ''); //empty line
end;
end;
procedure RunApp(const AAppClass: CCommandLineApp);
begin
Application := AAppClass.Create;
try
Application.Init;
Application.ParseCommandLine;
Application.Run;
except
on E: EBadUsage do
Application.ShowUsage(E.Message);
on E: Exception do
DumpException(E);
end;
end;
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, Menus,
StdCtrls;
type
{ TForm1 }
TForm1 = class(TForm)
Button1: TButton;
MainMenu1: TMainMenu;
Memo1: TMemo;
MenuItem1: TMenuItem;
MenuItem2: TMenuItem;
MenuItem3: TMenuItem;
MenuItem4: TMenuItem;
OpenDialog1: TOpenDialog;
SaveDialog1: TSaveDialog;
procedure Button1Click(Sender: TObject);
procedure MenuItem2Click(Sender: TObject);
procedure MenuItem3Click(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
TCard = record
cardSet: string;
cardNumber: string;
cardName: string;
unique: string;
hasDie: string;
cardType: string;
color: string;
faction: string;
rarity: string;
keywords: string;
points: string;
health: string;
cost: string;
side1: string;
side2: string;
side3: string;
side4: string;
side5: string;
side6: string;
ability: string;
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
procedure TForm1.MenuItem2Click(Sender: TObject);
var
f: TextFile;
s: String;
begin
OpenDialog1.InitialDir := '.\InputFiles';
OpenDialog1.Filter := 'Comma delimited files|*.csv';
if OpenDialog1.Execute then
begin
try
Memo1.Clear;
AssignFile(f, OpenDialog1.FileName);
Reset(f);
while not EoF(f) do
begin
Readln(f, s);
Memo1.Lines.Add(s);
end;
finally
CloseFile(f);
end;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
tmpCard: TCard;
tmpMemo: TMemo;
tmpS, item: String;
i, j, k, index: Integer;
begin
tmpMemo := TMemo.Create(nil);
tmpMemo.Clear;
// pass 1 - turn appropriate commas to pipes
for i:=0 to Memo1.Lines.Count-1 do
begin
tmpS := Memo1.Lines[i];
k:=0;
for j:=1 to Length(tmpS) do
if (tmpS[j] = ',') and (k < 18) then
begin
tmpS[j] := '|';
Inc(k);
end;
tmpMemo.Lines.Add(tmpS);
end;
Memo1.Lines.Clear;
for i:=0 to tmpMemo.Lines.Count-1 do
Memo1.Lines.Add(tmpMemo.Lines[i]);
tmpMemo.Lines.Clear;
// pass 2 - Separate out values
for i:=0 to Memo1.Lines.Count-1 do
begin
j:=0;
tmpS := Memo1.Lines[i];
repeat
index := Pos('|', tmpS);
item := Copy(tmpS, 1, index-1);
case j of
0: tmpCard.cardSet:=item;
1: tmpCard.cardNumber:=item;
2: tmpCard.cardName:=item;
3:
begin
if item = 'Y' then
tmpCard.unique := 'X'
else
tmpCard.unique := ' ';
end;
4: tmpCard.cardType:=item;
5: tmpCard.color:=item;
6: tmpCard.faction:=item;
7:
begin
if item='Purple' then item := 'Legendary'
else if item = 'Green' then item := 'Rare'
else if item = 'Yellow' then item := 'Uncommon'
else if item = 'Blue' then item := 'Common'
else if item = 'Grey' then item := 'Starter';
tmpCard.rarity:=item;
end;
8: tmpCard.keywords:=item;
9: tmpCard.points:=item;
10: tmpCard.health:=item;
11: tmpCard.cost:=item;
12:
begin
tmpCard.side1:=item;
if item > '' then tmpCard.hasDie := 'X';
end;
13: tmpCard.side2:=item;
14: tmpCard.side3:=item;
15: tmpCard.side4:=item;
16: tmpCard.side5:=item;
17: tmpCard.side6:=item;
end;
Inc(j);
tmpS := Copy(tmpS, index+1, 999);
tmpCard.ability:=tmpS;
until (Pos('|', tmpS) = 0);
tmpS := tmpCard.cardSet + '|' +
tmpCard.cardNumber + '|' +
tmpCard.cardName + '|' +
tmpCard.unique + '|' +
tmpCard.hasDie + '|' +
tmpCard.cardType + '|' +
tmpCard.color + '|' +
tmpCard.faction + '|' +
tmpCard.rarity + '|' +
tmpCard.keywords + '|' +
tmpCard.points + '|' +
tmpCard.health + '|' +
tmpCard.cost + '|' +
tmpCard.side1 + '|' +
tmpCard.side2 + '|' +
tmpCard.side3 + '|' +
tmpCard.side4 + '|' +
tmpCard.side5 + '|' +
tmpCard.side6 + '|' +
tmpCard.ability;
tmpMemo.Lines.Add(tmpS);
end;
Memo1.Lines.Clear;
for i:=0 to tmpMemo.Lines.Count-1 do
Memo1.Lines.Add(tmpMemo.Lines[i]);
end;
procedure TForm1.MenuItem3Click(Sender: TObject);
var
f: TextFile;
i: Integer;
begin
SaveDialog1.InitialDir := '.\OutputFiles';
SaveDialog1.Filter := 'Text File|*.txt';
SaveDialog1.DefaultExt := 'txt';
SaveDialog1.FileName := '.txt';
if SaveDialog1.Execute then
begin
AssignFile(f, SaveDialog1.FileName);
Rewrite(f);
for i:=0 to Memo1.Lines.Count-1 do
Writeln(f, Format('%s',[Memo1.Lines[i]]));
CloseFile(f);
end;
end;
end.
|
unit UFileMem;
{
This file is part of AbstractMem framework
Copyright (C) 2020 Albert Molina - bpascalblockchain@gmail.com
https://github.com/PascalCoinDev/
*** BEGIN LICENSE BLOCK *****
The contents of this files are subject to the Mozilla Public 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.mozilla.org/MPL
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the License.
The Initial Developer of the Original Code is Albert Molina.
See ConfigAbstractMem.inc file for more info
***** END LICENSE BLOCK *****
}
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
interface
uses
Classes, SysUtils,
SyncObjs,
UAbstractBTree, UAbstractMem, UCacheMem;
{$I ./ConfigAbstractMem.inc }
type
EFileMem = Class(Exception);
TFileMem = Class(TAbstractMem)
private
FFileStream : TFileStream;
FCache : TCacheMem;
FFileName: String;
FIsStableCache: Boolean;
FIsFlushingCache : Boolean;
function OnCacheNeedDataProc(var ABuffer; AStartPos : Integer; ASize : Integer) : Boolean;
function OnCacheSaveDataProc(const ABuffer; AStartPos : Integer; ASize : Integer) : Boolean;
procedure SetMaxCacheSize(const Value: Integer);
function GetMaxCacheSize: Integer;
function GetMaxCacheDataBlocks: Integer;
procedure SetMaxCacheDataBlocks(const Value: Integer);
procedure CacheIsNOTStable; inline;
protected
function AbsoluteWrite(const AAbsolutePosition : Int64; const ABuffer; ASize : Integer) : Integer; override;
function AbsoluteRead(const AAbsolutePosition : Int64; var ABuffer; ASize : Integer) : Integer; override;
procedure DoIncreaseSize(var ANextAvailablePos, AMaxAvailablePos : Integer; ANeedSize : Integer); override;
function IsAbstractMemInfoStable : Boolean; override;
public
Constructor Create(const AFileName : String; AReadOnly : Boolean); reintroduce;
Destructor Destroy; override;
function New(AMemSize : Integer) : TAMZone; override;
procedure Write(const APosition : Integer; const ABuffer; ASize : Integer); overload; override;
function Read(const APosition : Integer; var ABuffer; ASize : Integer) : Integer; overload; override;
{$IFDEF ABSTRACTMEM_TESTING_MODE}
// Warning: Accessing Cache is not Safe Thread protected, use LockCache/UnlockCache instead
property Cache : TCacheMem read FCache;
{$ENDIF}
property MaxCacheSize : Integer read GetMaxCacheSize write SetMaxCacheSize;
property MaxCacheDataBlocks : Integer read GetMaxCacheDataBlocks write SetMaxCacheDataBlocks;
Function FlushCache : Boolean;
//
function LockCache : TCacheMem;
procedure UnlockCache;
property FileName : String read FFileName;
End;
implementation
{ TFileMem }
function TFileMem.AbsoluteRead(const AAbsolutePosition: Int64; var ABuffer; ASize: Integer): Integer;
begin
FFileStream.Seek(AAbsolutePosition,soFromBeginning);
Result := FFileStream.Read(ABuffer,ASize);
end;
function TFileMem.AbsoluteWrite(const AAbsolutePosition: Int64; const ABuffer; ASize: Integer): Integer;
begin
FFileStream.Seek(AAbsolutePosition,soFromBeginning);
Result := FFileStream.Write(ABuffer,ASize);
CacheIsNOTStable;
end;
procedure TFileMem.CacheIsNOTStable;
begin
If (FIsStableCache) // Only will mark first time
And (Not FIsFlushingCache) // Only will mark when not Flushing cache
And (Assigned(FCache)) then begin
FIsStableCache := False;
SaveHeader;
end;
end;
constructor TFileMem.Create(const AFileName: String; AReadOnly: Boolean);
var LFileMode : Integer;
LReadOnly : Boolean;
begin
FIsStableCache := True;
FIsFlushingCache := False;
FFileName := AFileName;
if AReadOnly then LFileMode := fmOpenRead + fmShareDenyNone
else begin
if FileExists(AFileName) then LFileMode := fmOpenReadWrite else LFileMode := fmCreate;
LFileMode := LFileMode + fmShareDenyWrite;
end;
FCache := TCacheMem.Create(OnCacheNeedDataProc,OnCacheSaveDataProc);
LReadOnly := True;
try
FFileStream := TFileStream.Create(AFileName,LFileMode);
LReadOnly := AReadOnly; // To protect against raise exception
finally
inherited Create(0,LReadOnly);
end;
end;
destructor TFileMem.Destroy;
begin
if Not ReadOnly then FlushCache;
FreeAndNil(FCache);
inherited;
FreeAndNil(FFileStream);
FreeAndNil(FCache);
end;
procedure TFileMem.DoIncreaseSize(var ANextAvailablePos, AMaxAvailablePos: Integer; ANeedSize: Integer);
var LBuff : TBytes;
begin
if (ANeedSize<=0) And (AMaxAvailablePos<=0) then begin
FCache.Clear;
FFileStream.Seek(0,soFromEnd);
FFileStream.Size := 0;
Exit;
end;
FFileStream.Seek(0,soFromEnd);
// GoTo ANextAvailablePos
if (FFileStream.Position<ANextAvailablePos) then begin
SetLength(LBuff,ANextAvailablePos - FFileStream.Position);
FillChar(LBuff[0],Length(LBuff),0);
FFileStream.Write(LBuff[0],Length(LBuff));
end;
if (FFileStream.Position<ANextAvailablePos) then raise EFileMem.Create(Format('End file position (%d) is less than next available pos %d',[FFileStream.Position,ANextAvailablePos]));
// At this time ANextAvailablePos <= FFileStream.Position
AMaxAvailablePos := ANextAvailablePos + ANeedSize;
if (FFileStream.Size<AMaxAvailablePos) then begin
SetLength(LBuff,AMaxAvailablePos - FFileStream.Position);
FillChar(LBuff[0],Length(LBuff),0);
FFileStream.Write(LBuff[0],Length(LBuff));
end else AMaxAvailablePos := FFileStream.Size;
CacheIsNOTStable;
end;
function TFileMem.FlushCache: Boolean;
begin
if Not Assigned(FCache) then Exit(True);
FLock.Acquire;
try
Result := FCache.FlushCache;
finally
FIsStableCache := True;
FIsFlushingCache := True;
try
SaveHeader;
finally
FIsFlushingCache := False;
end;
FLock.Release;
end;
end;
function TFileMem.GetMaxCacheDataBlocks: Integer;
begin
if Not Assigned(FCache) then Exit(0);
Result := FCache.MaxCacheDataBlocks;
end;
function TFileMem.GetMaxCacheSize: Integer;
begin
if Not Assigned(FCache) then Exit(0);
Result := FCache.MaxCacheSize;
end;
function TFileMem.IsAbstractMemInfoStable: Boolean;
begin
Result := FIsStableCache;
end;
function TFileMem.LockCache: TCacheMem;
begin
FLock.Acquire;
Result := FCache;
end;
function TFileMem.New(AMemSize: Integer): TAMZone;
var LBuffer : TBytes;
begin
Result := inherited New(AMemSize);
// Initialize cache
if Not Assigned(FCache) then Exit;
FLock.Acquire;
try
SetLength(LBuffer,Result.size);
FillChar(LBuffer[0],Result.size,0);
FCache.SaveToCache(LBuffer[0],Result.size,Result.position,True);
finally
FLock.Release;
end;
end;
function TFileMem.OnCacheNeedDataProc(var ABuffer; AStartPos, ASize: Integer): Boolean;
begin
Result := inherited Read(AStartPos,ABuffer,ASize) = ASize;
end;
function TFileMem.OnCacheSaveDataProc(const ABuffer; AStartPos, ASize: Integer): Boolean;
begin
inherited Write(AStartPos,ABuffer,ASize);
Result := True;
end;
function TFileMem.Read(const APosition: Integer; var ABuffer; ASize: Integer): Integer;
begin
if Not Assigned(FCache) then begin
Result := inherited;
Exit;
end;
FLock.Acquire;
try
if FCache.LoadData(ABuffer,APosition,ASize) then Result := ASize
else Result := 0;
finally
FLock.Release;
end;
end;
procedure TFileMem.SetMaxCacheDataBlocks(const Value: Integer);
begin
if Not Assigned(FCache) then Exit;
FLock.Acquire;
Try
FCache.MaxCacheDataBlocks := Value;
Finally
FLock.Release;
End;
end;
procedure TFileMem.SetMaxCacheSize(const Value: Integer);
begin
if Not Assigned(FCache) then Exit;
FLock.Acquire;
Try
FCache.MaxCacheSize := Value;
Finally
FLock.Release;
End;
end;
procedure TFileMem.UnlockCache;
begin
FLock.Release;
end;
procedure TFileMem.Write(const APosition: Integer; const ABuffer; ASize: Integer);
begin
if (Not Assigned(FCache)) Or (FIsFlushingCache) then begin
inherited;
Exit;
end;
CheckInitialized(True);
FLock.Acquire;
try
FCache.SaveToCache(ABuffer,ASize,APosition,True);
finally
FLock.Release;
end;
end;
end.
|
unit frmInput;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TInputForm = class(TForm)
lblPrompt: TLabel;
cbbWorkerList: TComboBox;
btn1: TButton;
btn2: TButton;
lblMonitor: TLabel;
cbbMonitorList: TComboBox;
moRemark: TMemo;
lbRemark: TLabel;
private
{ Private declarations }
public
{ Public declarations }
end;
function ModifyProductWidth(const GF_NO: string): Boolean;
function InputBoxEx(const AWorkerList, AMonitorList: string; var AWorkerID, AMonitorID: string): Boolean;
function GetNewVatNo(BatchNO, MachineID, VatStudio, CurVatCode: String; Volume: Single): String;
var
InputForm: TInputForm;
implementation
uses
ServerDllPub, uShowMessage, uLogin, uDictionary, uGlobal, StrUtils;
{$R *.dfm}
function GetNewVatNo(BatchNO, MachineID, VatStudio, CurVatCode: String; Volume: Single): String;
var
AForm: TInputForm;
sErrorMsg: WideString;
begin
Result := '';
AForm := TInputForm.Create(nil);
try
AForm.Caption := '选择新缸号';
AForm.lblPrompt.Caption := '请选择新缸号:';
AForm.cbbWorkerList.Style := csDropDownList;
AForm.cbbMonitorList.Visible:=False;
AForm.lblMonitor.Visible:=False;
AForm.lbRemark.Visible := False;
AForm.moRemark.Visible := False;
AForm.Height := 115;
Dictionary.cds_VatList.Filter:=Format('Machine_ID = ''%s'' AND Vat_Studio = ''%s'' AND Vat_Cubage >= %8.0f', [MachineID, VatStudio, Volume]);
Dictionary.cds_VatList.Filter:=Format('Machine_ID = ''%s'' AND Vat_Studio = ''%s'' ', [MachineID, VatStudio]);
Dictionary.cds_VatList.Filtered:=True;
try
TGlobal.FillComboBoxFromDataSet(Dictionary.cds_VatList, 'Vat_Code', 'Vat_NO', '->', AForm.cbbWorkerList);
finally
Dictionary.cds_VatList.Filtered:=False;
end;
TGlobal.SetComboBoxValue(AForm.cbbWorkerList, CurVatCode);
if AForm.ShowModal = mrOK then
begin
Result := AForm.cbbWorkerList.Text;
//保存到数据库
FNMServerArtObj.ChangeVatCode(BatchNO, LeftStr(Result, 8), sErrorMsg);
if sErrorMsg <> '' then
begin
TMsgDialog.ShowMsgDialog(sErrorMsg, mtError);
Exit;
end;
end;
finally
FreeAndNil(AForm);
end;
end;
function InputBoxEx(const AWorkerList, AMonitorList: string; var AWorkerID, AMonitorID: string): Boolean;
var
AForm: TInputForm;
begin
Result := False;
AForm := TInputForm.Create(nil);
try
AForm.Caption := '选择责任人';
AForm.lblPrompt.Caption := '请选择责任人:';
AForm.lblMonitor.Caption := '请选择班长:';
AForm.cbbWorkerList.Style := csDropDownList;
AForm.cbbMonitorList.Style := csDropDownList;
AForm.cbbWorkerList.Items.Text := AWorkerList;
AForm.cbbMonitorList.Items.Text := AMonitorList;
AForm.lbRemark.Visible := False;
AForm.moRemark.Visible := False;
AForm.Height := 158;
Result := AForm.ShowModal = mrOK;
if Result then
begin
AWorkerID := AForm.cbbWorkerList.Text;
AMonitorID := AForm.cbbMonitorList.Text;
end;
finally
FreeAndNil(AForm);
end;
end;
function ModifyProductWidth(const GF_NO: string): Boolean;
var
AForm: TInputForm;
sReason, sGF_Key,sErrorMsg: WideString;
iWidth: Double;
begin
Result := False;
AForm := TInputForm.Create(nil);
try
AForm.Caption := '修改门幅';
AForm.lblPrompt.Caption := '请输入品名:';
AForm.lblMonitor.Caption := '请输入门幅:';
AForm.cbbWorkerList.Style := csSimple;
AForm.cbbWorkerList.Text := GF_NO;
AForm.cbbMonitorList.Style := csSimple;
AForm.lbRemark.Visible := True;
AForm.moRemark.Visible := True;
AForm.Height := 224;
Result := AForm.ShowModal = mrOK;
if Result then
begin
sReason := Trim(AForm.moRemark.Text);
if sReason = '' then
begin
TMsgDialog.ShowMsgDialog('请输入修改幅宽的原因', mtError);
Exit;
end;
sGF_Key := AForm.cbbWorkerList.Text;
iWidth := StrToFloat(AForm.cbbMonitorList.Text);
FNMServerArtObj.ModifyProductWidth(sGF_Key, iWidth, sReason, Login.LoginName, sErrorMsg);
if sErrorMsg <> '' then
begin
TMsgDialog.ShowMsgDialog(sErrorMsg, mtError);
Exit;
end;
end;
finally
FreeAndNil(AForm);
end;
end;
end.
|
{
Laz-Model
Copyright (C) 2002 Eldean AB, Peter Söderman, Ville Krumlinde
Portions (C) 2016 Peter Dyson. Initial Lazarus port
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit uIterators;
{$mode objfpc}{$H+}
interface
{
Iterators and filters for model navigation.
}
uses
Classes, SysUtils, Contnrs,
uModelEntity;
type
//Baseclass for iterators
TModelIterator = class(TInterfacedObject, IModelIterator)
private
FItems : TObjectList;
OwnsItems : boolean;
NextI : integer;
FNext : TModelEntity;
FHasNext : boolean;
private
procedure Init(List : IModelIterator; Filter : IIteratorFilter; Order : TIteratorOrder);
protected
procedure Advance; virtual;
public
constructor Create(ObList : TObjectList; MakeCopy : boolean = False); overload;
constructor Create(List : IModelIterator; Filter : IIteratorFilter; Order : TIteratorOrder = ioNone); overload;
constructor Create(List : IModelIterator;
OneClass : TModelEntityClass;
MinVisibility : TVisibility = Low(TVisibility);
Order : TIteratorOrder = ioNone); overload;
constructor Create(List : IModelIterator; Order : TIteratorOrder = ioNone); overload;
constructor Create(List : IModelIterator; MinVisibility : TVisibility); overload;
destructor Destroy; override;
//IModelIterator
function HasNext : boolean;
function Next : TModelEntity;
procedure Reset;
function Count : integer;
end;
//Baseclass for filter used in iterators
TIteratorFilter = class(TInterfacedObject, IIteratorFilter)
public
function Accept(M : TModelEntity) : boolean; virtual; abstract;
end;
{ TDataTypeFilter }
// Filters DataTypes from other classifiers
TDataTypeFilter = class(TIteratorFilter)
public
function Accept(M : TModelEntity) : boolean; override;
end;
{ TClassAndVisibilityFilter }
//Filters on a class and a minimum visibilty
TClassAndVisibilityFilter = class(TIteratorFilter)
private
OneClass : TModelEntityClass;
MinVisibility : TVisibility;
public
constructor Create(AOneClass : TModelEntityClass; AMinVisibility : TVisibility = Low(TVisibility));
function Accept(M : TModelEntity) : boolean; override;
end;
//Excludes an entity
{ TEntitySkipFilter }
TEntitySkipFilter = class(TIteratorFilter)
private
SkipEntity : TModelEntity;
public
constructor Create(ASkipEntity : TModelEntity);
function Accept(M : TModelEntity) : boolean; override;
end;
implementation
uses uModel;
{ TDataTypeFilter }
function TDataTypeFilter.Accept(M: TModelEntity): boolean;
begin
Result := (M is TDataType);
end;
{ TModelIterator }
//Creates iterator as a direct copy of an objectlist.
//If makecopy=false then reference oblist, else copy all items.
constructor TModelIterator.Create(ObList: TObjectList; MakeCopy : boolean = False);
var
I : integer;
begin
inherited Create;
if MakeCopy then
begin
//Copy oblist to items
OwnsItems := True;
FItems := TObjectList.Create(False);
for I:=0 to ObList.Count-1 do
FItems.Add(ObList[I]);
end
else
begin
//Reference same list instead of copy
OwnsItems := False;
FItems := ObList;
end;
Advance;
end;
//Creates an iterator based on another iterator, filter with Filter, sort on Order.
constructor TModelIterator.Create(List: IModelIterator; Filter : IIteratorFilter; Order : TIteratorOrder = ioNone);
begin
inherited Create;
Init(List, Filter, Order);
end;
//Creates an iterator based on another iterator, filter on class and
//visibility, sort result.
constructor TModelIterator.Create(List: IModelIterator;
OneClass: TModelEntityClass;
MinVisibility : TVisibility = Low(TVisibility);
Order : TIteratorOrder = ioNone);
begin
inherited Create;
Init(List, TClassAndVisibilityFilter.Create(OneClass,MinVisibility), Order);
end;
//Creates an iterator based on another iterator, sort result.
constructor TModelIterator.Create(List: IModelIterator; Order: TIteratorOrder);
begin
inherited Create;
Init(List, nil, Order);
end;
//Creates an iterator based on another iterator, filtered on visibility.
constructor TModelIterator.Create(List: IModelIterator; MinVisibility: TVisibility);
begin
inherited Create;
//TModelEntity as classfilter = always true
Init(List, TClassAndVisibilityFilter.Create(TModelEntity,MinVisibility), ioNone);
end;
destructor TModelIterator.Destroy;
begin
if OwnsItems then
FreeAndNil(FItems);
inherited;
end;
function SortVisibility(Item1, Item2: Pointer): Integer;
var
E1,E2 : TModelEntity;
begin
//Visibility, then alpha
E1 := TModelEntity(Item1);
E2 := TModelEntity(Item2);
if (E1.Visibility<E2.Visibility) then
Result:=-1 //Lower
else if (E1.Visibility=E2.Visibility) then
Result := CompareText(E1.Name,E2.Name)
else
Result:=1; //Higher
end;
function SortAlpha(Item1, Item2: Pointer): Integer;
begin
Result := CompareText( TModelEntity(Item1).Name , TModelEntity(Item2).Name );
end;
//Called by all iterator constructors that has an iterator as a parameter
//Initializes iterator
procedure TModelIterator.Init(List: IModelIterator; Filter: IIteratorFilter; Order : TIteratorOrder);
var
E : TModelEntity;
begin
OwnsItems := True;
FItems := TObjectList.Create(False);
if Assigned(Filter) then
while List.HasNext do
begin
E := List.Next;
if Filter.Accept( E ) then
FItems.Add( E );
end
else//Not filtered
while List.HasNext do
FItems.Add( List.Next );
//Sort
case Order of
ioNone : ;
ioVisibility : FItems.Sort( @SortVisibility );
ioAlpha : FItems.Sort( @SortAlpha );
end;
Advance;
end;
procedure TModelIterator.Advance;
begin
FHasNext := NextI < FItems.Count;
if FHasNext then
begin
FNext := FItems[NextI] as TModelEntity;
Inc(NextI);
end;
end;
function TModelIterator.HasNext: boolean;
begin
Result := FHasNext;
end;
function TModelIterator.Next: TModelEntity;
begin
if not FHasNext then
raise Exception.Create(ClassName + '.Next at end');
Result := FNext;
Advance;
end;
procedure TModelIterator.Reset;
begin
NextI := 0;
Advance;
end;
{
Returns nr of elements.
}
function TModelIterator.Count: integer;
begin
Result := FItems.Count;
end;
{ TClassAndVisibilityFilter }
constructor TClassAndVisibilityFilter.Create(AOneClass: TModelEntityClass;
AMinVisibility: TVisibility);
begin
inherited Create;
Self.OneClass := AOneClass;
Self.MinVisibility := AMinVisibility;
end;
function TClassAndVisibilityFilter.Accept(M: TModelEntity): boolean;
begin
Result := (M is OneClass) and (M.Visibility>=MinVisibility);
end;
{ TEntitySkipFilter }
constructor TEntitySkipFilter.Create(ASkipEntity: TModelEntity);
begin
Self.SkipEntity := ASkipEntity;
end;
function TEntitySkipFilter.Accept(M: TModelEntity): boolean;
begin
Result := M<>SkipEntity;
end;
end.
|
unit uMediaPlayers;
interface
uses
Generics.Collections,
System.Win.Registry,
System.SysUtils,
System.Classes,
Winapi.Windows,
Winapi.ShlObj,
uMemory,
uAppUtils,
uSettings,
uConstants,
uShellUtils;
function GetPlayerInternalPath: string;
function IsPlayerInternalInstalled: Boolean;
function GetVlcPlayerPath: string;
function IsVlcPlayerInstalled: Boolean;
function GetKMPlayerPath: string;
function IsKmpPlayerInstalled: Boolean;
function GetMediaPlayerClassicPath: string;
function IsMediaPlayerClassicInstalled: Boolean;
function GetWindowsMediaPlayerPath: string;
function IsWindowsMediaPlayerInstalled: Boolean;
function GetShellPlayerForFile(FileName: string): string;
procedure RegisterVideoFiles;
implementation
function GetLocalShellPlayerForFile(FileName: string): string;
var
Reg: TRegistry;
AssociationsKey, Handler, CommandLine: string;
begin
Result := '';
Reg := TRegistry.Create(KEY_READ);
try
Reg.RootKey := HKEY_CURRENT_USER;
AssociationsKey := '\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\' + ExtractFileExt(FileName);
if Reg.OpenKey(AssociationsKey + '\UserChoice', False) then
begin
Handler := Reg.ReadString('Progid');
if Handler <> '' then
begin
Reg.CloseKey;
Reg.RootKey := HKEY_CLASSES_ROOT;
if Reg.OpenKey('\' + Handler + '\shell\open\command', False) then
begin
CommandLine := Reg.ReadString('');
if CommandLine <> '' then
Result := ParamStrEx(CommandLine, -1);
end;
end;
end;
finally
F(Reg);
end;
end;
function GetShellPlayerForFile(FileName: string): string;
var
Reg: TRegistry;
Handler,
CommandLine: string;
begin
Result := GetLocalShellPlayerForFile(FileName);
if Result <> '' then
Exit;
Reg := TRegistry.Create(KEY_READ);
try
Reg.RootKey := HKEY_CLASSES_ROOT;
if Reg.OpenKey(ExtractFileExt(FileName), False) then
begin
Handler := Reg.ReadString('');
if Handler <> '' then
begin
if Reg.OpenKey('\' + Handler + '\shell\open\command', False) then
begin
CommandLine := Reg.ReadString('');
if CommandLine <> '' then
Result := ParamStrEx(CommandLine, -1);
end;
end;
end;
finally
F(Reg);
end;
end;
function IsPlayerInternalInstalled: Boolean;
begin
Result := GetPlayerInternalPath <> '';
end;
function GetPlayerInternalPath: string;
var
InternalMediaPlayerPath: string;
begin
Result := '';
InternalMediaPlayerPath := ExtractFilePath(ParamStr(0)) + 'MediaPlayer\mpc-hc.exe';
if FileExists(InternalMediaPlayerPath) then
Result := InternalMediaPlayerPath;
end;
function IsVlcPlayerInstalled: Boolean;
begin
Result := GetVlcPlayerPath <> '';
end;
function GetVlcPlayerPath: string;
var
Reg: TRegistry;
begin
Reg := TRegistry.Create(KEY_READ);
try
Reg.RootKey := HKEY_LOCAL_MACHINE;
if Reg.OpenKey('\SOFTWARE\Wow6432Node\VideoLAN\VLC', False) then
Result := Reg.ReadString('');
finally
F(Reg);
end;
end;
function IsKmpPlayerInstalled: Boolean;
begin
Result := GetKMPlayerPath <> '';
end;
function GetKMPlayerPath: string;
var
Reg: TRegistry;
begin
Reg := TRegistry.Create(KEY_READ);
try
Reg.RootKey := HKEY_CURRENT_USER;
if Reg.OpenKey('\Software\KMPlayer\KMP3.0\OptionArea', False) then
Result := Reg.ReadString('InstallPath');
finally
F(Reg);
end;
end;
function IsMediaPlayerClassicInstalled: Boolean;
begin
Result := GetMediaPlayerClassicPath <> '';
end;
function GetMediaPlayerClassicPath: string;
const
MPC_PATHS : array[0..1] of string =
('%PROGRAM%\Essentials Codec Pack\MPC\mpc-hc.exe',
'%PROGRAM_86%\Essentials Codec Pack\MPC\mpc-hc.exe');
var
FileName: string;
I: Integer;
begin
Result := '';
for I := Low(MPC_PATHS) to High(MPC_PATHS) do
begin
FileName := StringReplace(MPC_PATHS[I], '%PROGRAM%', GetSystemPath(CSIDL_PROGRAM_FILES), []);
FileName := StringReplace(FileName, '%PROGRAM_86%', GetSystemPath(CSIDL_PROGRAM_FILESX86), []);
if FileExists(FileName) then
Result := FileName;
end;
end;
function IsWindowsMediaPlayerInstalled: Boolean;
begin
Result := GetWindowsMediaPlayerPath <> '';
end;
function GetWindowsMediaPlayerPath: string;
const
WMP_PATHS : array[0..1] of string =
('%PROGRAM%\Windows Media Player\wmplayer.exe',
'%PROGRAM_86%\Windows Media Player\wmplayer.exe');
var
FileName: string;
I: Integer;
begin
Result := '';
for I := Low(WMP_PATHS) to High(WMP_PATHS) do
begin
FileName := StringReplace(WMP_PATHS[I], '%PROGRAM%', GetSystemPath(CSIDL_PROGRAM_FILES), []);
FileName := StringReplace(FileName, '%PROGRAM_86%', GetSystemPath(CSIDL_PROGRAM_FILESX86), []);
if FileExists(FileName) then
Result := FileName;
end;
end;
procedure RegisterVideoFiles;
var
Ext, Player: string;
VideoFileExtensions: TArray<string>;
ExistedData: TStrings;
begin
Player := GetPlayerInternalPath;
VideoFileExtensions := uConstants.cVideoFileExtensions.ToUpper.Split([',']);
ExistedData := AppSettings.ReadKeys(cMediaAssociationsData);
try
if ExistedData.Count > 0 then
Exit;
finally
F(ExistedData);
end;
for Ext in VideoFileExtensions do
AppSettings.WriteString(cMediaAssociationsData + '\' + Ext, '', Player);
end;
end.
|
//
// Generated by JavaToPas v1.5 20171018 - 171214
////////////////////////////////////////////////////////////////////////////////
unit android.app.RemoteAction;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
Androidapi.JNI.os,
android.graphics.drawable.Icon,
android.app.PendingIntent;
type
JRemoteAction = interface;
JRemoteActionClass = interface(JObjectClass)
['{F3463CDF-3260-4F72-B5EC-EAE6AC519FBD}']
function _GetCREATOR : JParcelable_Creator; cdecl; // A: $19
function clone : JRemoteAction; cdecl; // ()Landroid/app/RemoteAction; A: $1
function describeContents : Integer; cdecl; // ()I A: $1
function getActionIntent : JPendingIntent; cdecl; // ()Landroid/app/PendingIntent; A: $1
function getContentDescription : JCharSequence; cdecl; // ()Ljava/lang/CharSequence; A: $1
function getIcon : JIcon; cdecl; // ()Landroid/graphics/drawable/Icon; A: $1
function getTitle : JCharSequence; cdecl; // ()Ljava/lang/CharSequence; A: $1
function init(icon : JIcon; title : JCharSequence; contentDescription : JCharSequence; intent : JPendingIntent) : JRemoteAction; cdecl;// (Landroid/graphics/drawable/Icon;Ljava/lang/CharSequence;Ljava/lang/CharSequence;Landroid/app/PendingIntent;)V A: $1
function isEnabled : boolean; cdecl; // ()Z A: $1
procedure dump(prefix : JString; pw : JPrintWriter) ; cdecl; // (Ljava/lang/String;Ljava/io/PrintWriter;)V A: $1
procedure setEnabled(enabled : boolean) ; cdecl; // (Z)V A: $1
procedure writeToParcel(&out : JParcel; flags : Integer) ; cdecl; // (Landroid/os/Parcel;I)V A: $1
property CREATOR : JParcelable_Creator read _GetCREATOR; // Landroid/os/Parcelable$Creator; A: $19
end;
[JavaSignature('android/app/RemoteAction')]
JRemoteAction = interface(JObject)
['{6BA8F09F-B2AE-4E32-BFC4-DD48070C5085}']
function clone : JRemoteAction; cdecl; // ()Landroid/app/RemoteAction; A: $1
function describeContents : Integer; cdecl; // ()I A: $1
function getActionIntent : JPendingIntent; cdecl; // ()Landroid/app/PendingIntent; A: $1
function getContentDescription : JCharSequence; cdecl; // ()Ljava/lang/CharSequence; A: $1
function getIcon : JIcon; cdecl; // ()Landroid/graphics/drawable/Icon; A: $1
function getTitle : JCharSequence; cdecl; // ()Ljava/lang/CharSequence; A: $1
function isEnabled : boolean; cdecl; // ()Z A: $1
procedure dump(prefix : JString; pw : JPrintWriter) ; cdecl; // (Ljava/lang/String;Ljava/io/PrintWriter;)V A: $1
procedure setEnabled(enabled : boolean) ; cdecl; // (Z)V A: $1
procedure writeToParcel(&out : JParcel; flags : Integer) ; cdecl; // (Landroid/os/Parcel;I)V A: $1
end;
TJRemoteAction = class(TJavaGenericImport<JRemoteActionClass, JRemoteAction>)
end;
implementation
end.
|
{******************************************************************************}
{ }
{ WiRL: RESTful Library for Delphi }
{ }
{ Copyright (c) 2015-2021 WiRL Team }
{ }
{ https://github.com/delphi-blocks/WiRL }
{ }
{******************************************************************************}
unit WiRL.Data.Utils;
interface
uses
System.Classes, System.SysUtils, Generics.Collections, Data.DB;
type
TDataUtils = class
private
class function RecordToXML(const ADataSet: TDataSet; const ARootPath: string = ''): string; static;
class function RecordToCSV(const ADataSet: TDataSet): string; static;
public
class function DataSetToXML(const ADataSet: TDataSet): string; overload; static;
class function DataSetToXML(const ADataSet: TDataSet; const AAcceptFunc: TFunc<Boolean>): string; overload; static;
class function DataSetToCSV(const ADataSet: TDataSet): string; static;
end;
TDataSetList = class(TObjectList<TDataSet>)
end;
implementation
uses
System.Rtti, System.StrUtils, System.DateUtils,
WiRL.Rtti.Utils,
WiRL.Core.Utils;
type
TJSONFieldType = (NestedObject, NestedArray, SimpleValue);
class function TDataUtils.RecordToCSV(const ADataSet: TDataSet): string;
var
LField: TField;
begin
Result := '';
for LField in ADataSet.Fields do
begin
{ TODO -opaolo -c : Check field types 02/09/2021 15:33:33 }
Result := Result + LField.AsString + ',';
end;
Result := Result.TrimRight([',']);
end;
class function TDataUtils.RecordToXML(const ADataSet: TDataSet; const ARootPath: string = ''): string;
var
LField: TField;
begin
Result := '';
for LField in ADataSet.Fields do
begin
{ TODO -opaolo -c : Check field types 02/09/2021 15:33:33 }
Result := Result
+ Format('<%s>%s</%s>', [LField.FieldName, LField.AsString, LField.FieldName]);
end;
end;
class function TDataUtils.DataSetToCSV(const ADataSet: TDataSet): string;
var
LBookmark: TBookmark;
begin
Result := '';
if not Assigned(ADataSet) then
Exit;
if not ADataSet.Active then
ADataSet.Open;
ADataSet.DisableControls;
try
LBookmark := ADataSet.Bookmark;
try
ADataSet.First;
while not ADataSet.Eof do
try
Result := Result + TDataUtils.RecordToCSV(ADataSet) + sLineBreak;
finally
ADataSet.Next;
end;
finally
ADataSet.GotoBookmark(LBookmark);
end;
finally
ADataSet.EnableControls;
end;
end;
class function TDataUtils.DataSetToXML(const ADataSet: TDataSet): string;
begin
Result := DataSetToXML(ADataSet, nil);
end;
class function TDataUtils.DataSetToXML(const ADataSet: TDataSet; const AAcceptFunc: TFunc<Boolean>): string;
var
LBookmark: TBookmark;
begin
Result := '';
if not Assigned(ADataSet) then
Exit;
if not ADataSet.Active then
ADataSet.Open;
ADataSet.DisableControls;
try
LBookmark := ADataSet.Bookmark;
try
ADataSet.First;
while not ADataSet.Eof do
try
if (not Assigned(AAcceptFunc)) or (AAcceptFunc()) then
Result := Result + '<row>' + RecordToXML(ADataSet) + '</row>';
finally
ADataSet.Next;
end;
finally
ADataSet.GotoBookmark(LBookmark);
end;
finally
ADataSet.EnableControls;
end;
end;
end.
|
// ************************************************************************
// ***************************** CEF4Delphi *******************************
// ************************************************************************
//
// CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based
// browser in Delphi applications.
//
// The original license of DCEF3 still applies to CEF4Delphi.
//
// For more information about CEF4Delphi visit :
// https://www.briskbard.com/index.php?lang=en&pageid=cef
//
// Copyright © 2017 Salvador Díaz Fau. All rights reserved.
//
// ************************************************************************
// ************ vvvv Original license and comments below vvvv *************
// ************************************************************************
(*
* Delphi Chromium Embedded 3
*
* Usage allowed under the restrictions of the Lesser GNU General Public License
* or alternatively the restrictions of the Mozilla Public License 1.1
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* Unit owner : Henri Gourvest <hgourvest@gmail.com>
* Web site : http://www.progdigy.com
* Repository : http://code.google.com/p/delphichromiumembedded/
* Group : http://groups.google.com/group/delphichromiumembedded
*
* Embarcadero Technologies, Inc is not permitted to use or redistribute
* this source code without explicit permission.
*
*)
unit uCEFFrame;
{$IFNDEF CPUX64}
{$ALIGN ON}
{$MINENUMSIZE 4}
{$ENDIF}
{$I cef.inc}
interface
uses
uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes;
type
TCefFrameRef = class(TCefBaseRefCountedRef, ICefFrame)
public
function IsValid: Boolean;
procedure Undo;
procedure Redo;
procedure Cut;
procedure Copy;
procedure Paste;
procedure Del;
procedure SelectAll;
procedure ViewSource;
procedure GetSource(const visitor: ICefStringVisitor);
procedure GetSourceProc(const proc: TCefStringVisitorProc);
procedure GetText(const visitor: ICefStringVisitor);
procedure GetTextProc(const proc: TCefStringVisitorProc);
procedure LoadRequest(const request: ICefRequest);
procedure LoadUrl(const url: ustring);
procedure LoadString(const str, url: ustring);
procedure ExecuteJavaScript(const code, scriptUrl: ustring; startLine: Integer);
function IsMain: Boolean;
function IsFocused: Boolean;
function GetName: ustring;
function GetIdentifier: Int64;
function GetParent: ICefFrame;
function GetUrl: ustring;
function GetBrowser: ICefBrowser;
function GetV8Context: ICefv8Context;
procedure VisitDom(const visitor: ICefDomVisitor);
procedure VisitDomProc(const proc: TCefDomVisitorProc);
class function UnWrap(data: Pointer): ICefFrame;
end;
implementation
uses
uCEFMiscFunctions, uCEFLibFunctions, uCEFBrowser, uCEFStringVisitor, uCEFv8Context, uCEFDomVisitor;
function TCefFrameRef.IsValid: Boolean;
begin
Result := PCefFrame(FData)^.is_valid(PCefFrame(FData)) <> 0;
end;
procedure TCefFrameRef.Copy;
begin
PCefFrame(FData)^.copy(PCefFrame(FData));
end;
procedure TCefFrameRef.Cut;
begin
PCefFrame(FData)^.cut(PCefFrame(FData));
end;
procedure TCefFrameRef.Del;
begin
PCefFrame(FData)^.del(PCefFrame(FData));
end;
procedure TCefFrameRef.ExecuteJavaScript(const code, scriptUrl: ustring;
startLine: Integer);
var
j, s: TCefString;
begin
j := CefString(code);
s := CefString(scriptUrl);
PCefFrame(FData)^.execute_java_script(PCefFrame(FData), @j, @s, startline);
end;
function TCefFrameRef.GetBrowser: ICefBrowser;
begin
Result := TCefBrowserRef.UnWrap(PCefFrame(FData)^.get_browser(PCefFrame(FData)));
end;
function TCefFrameRef.GetIdentifier: Int64;
begin
Result := PCefFrame(FData)^.get_identifier(PCefFrame(FData));
end;
function TCefFrameRef.GetName: ustring;
begin
Result := CefStringFreeAndGet(PCefFrame(FData)^.get_name(PCefFrame(FData)));
end;
function TCefFrameRef.GetParent: ICefFrame;
begin
Result := TCefFrameRef.UnWrap(PCefFrame(FData)^.get_parent(PCefFrame(FData)));
end;
procedure TCefFrameRef.GetSource(const visitor: ICefStringVisitor);
begin
PCefFrame(FData)^.get_source(PCefFrame(FData), CefGetData(visitor));
end;
procedure TCefFrameRef.GetSourceProc(const proc: TCefStringVisitorProc);
begin
GetSource(TCefFastStringVisitor.Create(proc));
end;
procedure TCefFrameRef.getText(const visitor: ICefStringVisitor);
begin
PCefFrame(FData)^.get_text(PCefFrame(FData), CefGetData(visitor));
end;
procedure TCefFrameRef.GetTextProc(const proc: TCefStringVisitorProc);
begin
GetText(TCefFastStringVisitor.Create(proc));
end;
function TCefFrameRef.GetUrl: ustring;
begin
Result := CefStringFreeAndGet(PCefFrame(FData)^.get_url(PCefFrame(FData)));
end;
function TCefFrameRef.GetV8Context: ICefv8Context;
begin
Result := TCefv8ContextRef.UnWrap(PCefFrame(FData)^.get_v8context(PCefFrame(FData)));
end;
function TCefFrameRef.IsFocused: Boolean;
begin
Result := PCefFrame(FData)^.is_focused(PCefFrame(FData)) <> 0;
end;
function TCefFrameRef.IsMain: Boolean;
begin
Result := PCefFrame(FData)^.is_main(PCefFrame(FData)) <> 0;
end;
procedure TCefFrameRef.LoadRequest(const request: ICefRequest);
begin
PCefFrame(FData)^.load_request(PCefFrame(FData), CefGetData(request));
end;
procedure TCefFrameRef.LoadString(const str, url: ustring);
var
s, u: TCefString;
begin
s := CefString(str);
u := CefString(url);
PCefFrame(FData)^.load_string(PCefFrame(FData), @s, @u);
end;
procedure TCefFrameRef.LoadUrl(const url: ustring);
var
u: TCefString;
begin
u := CefString(url);
PCefFrame(FData)^.load_url(PCefFrame(FData), @u);
end;
procedure TCefFrameRef.Paste;
begin
PCefFrame(FData)^.paste(PCefFrame(FData));
end;
procedure TCefFrameRef.Redo;
begin
PCefFrame(FData)^.redo(PCefFrame(FData));
end;
procedure TCefFrameRef.SelectAll;
begin
PCefFrame(FData)^.select_all(PCefFrame(FData));
end;
procedure TCefFrameRef.Undo;
begin
PCefFrame(FData)^.undo(PCefFrame(FData));
end;
procedure TCefFrameRef.ViewSource;
begin
PCefFrame(FData)^.view_source(PCefFrame(FData));
end;
procedure TCefFrameRef.VisitDom(const visitor: ICefDomVisitor);
begin
PCefFrame(FData)^.visit_dom(PCefFrame(FData), CefGetData(visitor));
end;
procedure TCefFrameRef.VisitDomProc(const proc: TCefDomVisitorProc);
begin
VisitDom(TCefFastDomVisitor.Create(proc) as ICefDomVisitor);
end;
class function TCefFrameRef.UnWrap(data: Pointer): ICefFrame;
begin
if data <> nil then
Result := Create(data) as ICefFrame else
Result := nil;
end;
end.
|
unit uFrmAskDocument;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uPai, siComp, siLangRT, StdCtrls, Buttons, ExtCtrls, DBCtrls;
type
TFrmAskDocument = class(TFrmPai)
lblDocument: TLabel;
lblNumber: TLabel;
cmbDocument: TDBLookupComboBox;
edtNumber: TEdit;
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure btCloseClick(Sender: TObject);
private
FIDDocumentType: Integer;
FDocumentNumber: String;
procedure SetDefaultDocument;
function ValidateFields: Boolean;
public
function Start: Boolean;
property DocumentNumber: String read FDocumentNumber write FDocumentNumber;
property IDDocumentType: Integer read FIDDocumentType write FIDDocumentType;
end;
implementation
uses uDM, uMsgBox, uMsgConstant, DB;
{$R *.dfm}
{ TFrmAskDocument }
function TFrmAskDocument.Start: Boolean;
begin
edtNumber.Clear;
SetDefaultDocument;
ShowModal;
Result := ModalResult = mrOk;
end;
procedure TFrmAskDocument.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
inherited;
if ModalResult <> mrOk then
CanClose := False;
end;
procedure TFrmAskDocument.btCloseClick(Sender: TObject);
begin
if not ValidateFields then
ModalResult := mrNone
else
begin
FDocumentNumber := edtNumber.Text;
FIDDocumentType := cmbDocument.KeyValue;
end;
end;
procedure TFrmAskDocument.SetDefaultDocument;
begin
DM.cdsDocumentType.Locate('DefaultType', '1', []);
cmbDocument.KeyValue := DM.cdsDocumentTypeIDDocumentType.AsInteger;
end;
function TFrmAskDocument.ValidateFields: Boolean;
begin
Result := False;
if edtNumber.Text = '' then
begin
MsgBox(MSG_CRT_NO_NUMBER, vbInformation + vbOKOnly);
edtNumber.SetFocus;
Exit;
end;
if VarToStr(cmbDocument.KeyValue) = '' then
begin
MsgBox(MSG_CRT_INVALID_DOCUMENT, vbInformation + vbOKOnly);
cmbDocument.SetFocus;
Exit;
end;
Result := True;
end;
end.
|
unit CplxMath;
{* This unit contains functins for working with complex numbers. To use with
KOL library and its kolmath.pas unit instead of standard math.pas, define
synmbol KOL in project options, or uncomment its definition below. }
interface
//{$DEFINE KOL}
{$IFNDEF KOL}
{$IFDEF KOL_MCK}
{$DEFINE KOL}
{$ENDIF}
{$ENDIF}
uses {$IFDEF KOL} kolmath, kol {$ELSE} math, sysutils {$ENDIF};
type
{$IFDEF CPLX_EXTENDED}
Double = Extended;
{$ENDIF}
Complex = record Re, Im: double end;
{* }
function CfromReIm( Re, Im: Double ): Complex;
{* Re + i * Im }
function Cadd( const X, Y: Complex ): Complex;
{* X + Y }
function Cneg( const X: Complex ): Complex;
{* -X }
function Csub( const X, Y: Complex ): Complex;
{* X - Y }
function Cmul( const X, Y: Complex ): Complex;
{* X * Y }
function CmulD( const X: Complex; D: Double ): Complex;
{* X * D }
function CmulI( const X: Complex ): Complex;
{* i * X }
function Cdiv( const X, Y: Complex ): Complex;
{* X / Y }
function Cmod( const X: Complex ): Double;
{* Q( X.Re^2 + X.Im^2 ) }
function Carg( const X: Complex ): Double;
{* arctg( X.Im / X.Re ) }
function CfromModArg( R, Arg: Double ): Complex;
{* R * ( cos Arg + i * sin Arg ) }
function Cpow( const X: Complex; Pow: Double ): Complex;
{* X ^ Pow }
function Cpower( const X, Pow: Complex ): Complex;
{* X ^ Pow }
function CIntPower( const X: Complex; Pow: Integer ): Complex;
{* X ^ Pow}
function Csqrt( const X: Complex ): Complex;
{* Q( X ) }
function Cexp( const X: Complex ): Complex;
{* exp( X ) }
function Cln( const X: Complex ): Complex;
{* ln( X ) }
function Ccos( const X: Complex ): Complex;
{* cos( X ) }
function Csin( const X: Complex ): Complex;
{* sin( X ) }
function C2Str( const X: Complex ): String;
{* }
function C2StrEx( const X: Complex ): String;
{* experimental }
implementation
function CfromReIm( Re, Im: Double ): Complex;
begin
Result.Re := Re;
Result.Im := Im;
end;
function Cadd( const X, Y: Complex ): Complex;
begin
Result.Re := X.Re + Y.Re;
Result.Im := X.Im + Y.Im;
end;
function Cneg( const X: Complex ): Complex;
begin
Result.Re := -X.Re;
Result.Im := -X.Im;
end;
function Csub( const X, Y: Complex ): Complex;
begin
Result := Cadd( X, Cneg( Y ) );
end;
function Cmul( const X, Y: Complex ): Complex;
begin
Result.Re := X.Re * Y.Re - X.Im * Y.Im;
Result.Im := X.Re * Y.Im + X.Im * Y.Re;
end;
function CmulD( const X: Complex; D: Double ): Complex;
begin
Result.Re := X.Re * D;
Result.Im := X.Im * D;
end;
function CmulI( const X: Complex ): Complex;
begin
Result.Re := -X.Im;
Result.Im := X.Re;
end;
function Cdiv( const X, Y: Complex ): Complex;
var Z: Double;
begin
Z := 1.0 / ( Y.Re * Y.Re + Y.Im * Y.Im );
Result.Re := (X.Re * Y.Re + X.Im * Y.Im ) * Z;
Result.Im := (X.Im * Y.Re - X.Re * Y.Im ) * Z;
end;
function Cmod( const X: Complex ): Double;
begin
Result := sqrt( X.Re * X.Re + X.Im * X.Im );
end;
function Carg( const X: Complex ): Double;
begin
Result := ArcTan2( X.Im, X.Re );
end;
function CfromModArg( R, Arg: Double ): Complex;
begin
Result.Re := R * cos( Arg );
Result.Im := R * sin( Arg );
end;
function Cpow( const X: Complex; Pow: Double ): Complex;
var R, A: Double;
begin
R := power( Cmod( X ), Pow );
A := Pow * Carg( X );
Result := CfromModArg( R, A );
end;
function Cpower( const X, Pow: Complex ): Complex;
begin
Result := Cexp( Cmul( X, Cln( Pow ) ) );
end;
function CIntPower( const X: Complex; Pow: Integer ): Complex;
begin
if (Pow < 0) or (Pow > 100) then Result := Cpow( X, Pow )
else if Pow = 0 then
begin
Result.Re := 1;
Result.Im := 0;
end
else
begin
Result := X;
while Pow > 1 do
begin
Result := Cmul( Result, X );
dec( Pow );
end;
end;
end;
function Csqrt( const X: Complex ): Complex;
begin
Result := Cpow( X, 0.5 );
end;
function Cexp( const X: Complex ): Complex;
var Z: Double;
begin
Z := exp( X.Re );
Result.Re := Z * cos( X.Im );
Result.Im := Z * sin( X.Im );
end;
function Cln( const X: Complex ): Complex;
begin
Result := CfromModArg( ln( Cmod( X ) ), Carg( X ) );
end;
function Ccos( const X: Complex ): Complex;
begin
Result := CmulI( X );
Result := CmulD( Cadd( Cexp( Result ), Cexp( Cneg( Result ) ) ),
0.5 );
end;
function Csin( const X: Complex ): Complex;
begin
Result := CmulI( X );
Result := CmulD( Csub( Cexp(Result), Cexp( Cneg(Result) ) ),
0.5 );
end;
{$IFDEF KOL}
function Abs( X: Double ): Double;
begin
Result := EAbs( X );
end;
{$ENDIF}
{$IFNDEF KOL}
function Double2Str( D: Double ): String;
begin
Result := DoubleToStr( D );
end;
{$ENDIF}
function C2Str( const X: Complex ): String;
begin
if Abs( X.Im ) < 1e-307 then
begin
Result := Double2Str( X.Re );
end
else
begin
Result := '';
if Abs( X.Re ) > 1e-307 then
begin
Result := Double2Str( X.Re );
if X.Im > 0.0 then
Result := Result + ' + ';
end;
if X.Im < 0.0 then
Result := Result + '- i * ' + Double2Str( -X.Im )
else
Result := Result + 'i * ' + Double2Str( X.Im );
end;
end;
function C2StrEx( const X: Complex ): String;
begin
if Abs( X.Im ) < 1e-307 then
begin
Result := Double2StrEx( X.Re );
end
else
begin
Result := '';
if Abs( X.Re ) > 1e-307 then
begin
Result := Double2StrEx( X.Re );
if X.Im > 0.0 then
Result := Result + ' + ';
end;
if X.Im < 0.0 then
Result := Result + '- i * ' + Double2StrEx( -X.Im )
else
Result := Result + 'i * ' + Double2StrEx( X.Im );
end;
end;
end.
|
unit AscFile;
interface
uses Classes, ClueTypes;
type
TStats = record
isValid : boolean;
low : integer;
high : integer;
constructor Create(valid : boolean);
end;
TAscFile = class
private
_name : string;
_rows : integer;
_cols : integer;
_left_X : double;
_bottom_Y : double;
_isCorner : boolean;
_cellSize : double;
_unknown : integer;
_buffer : TMatrix<integer>;
_countMetaData : integer;
_last : integer;
_c_pos : integer;
_stats: TStats;
_parts: TStringList;
function getStats: TStats;
protected
function ReadLine(var Stream: TBufferedFileStream; var line: string): boolean;
function nextMetaField(var ascfile : TBufferedFileStream) : string;
procedure loadMetadata(var ascfile : TBufferedFileStream);
function nextRow(var ascfile : TBufferedFileStream) : TVector<integer>;
public
constructor Create;
destructor Destroy; override;
function isCorner : boolean;
function line(row : integer) : TVector<integer>;
function isNodata(row, col : integer) : boolean;
function map : TMatrix<integer>;
procedure load;
property filename : string read _name write _name;
property rows : integer read _rows;
property cols : integer read _cols;
property bottomY : double read _bottom_Y;
property leftX : double read _left_X;
property pixelIsArea : boolean read isCorner;
property cellsize : double read _cellSize;
property nodata : integer read _unknown;
property stats : TStats read getStats;
end;
implementation
uses
sysutils, vcl.dialogs, math;
constructor TAscFile.Create;
begin
_buffer := nil;
_last := 0;
_c_pos := 0;
_unknown := -MaxInt;
_stats := TStats.Create(false);
_parts := TStringList.Create;
end;
destructor TAscFile.Destroy;
begin
_parts.Free;
inherited;
end;
function TAscFile.getStats: TStats;
var
r, c,
l, h, v : integer;
begin
if _buffer = nil then
exit;
l := +maxint;
h := -maxint;
for r := 0 to _rows - 1 do begin
for c := 0 to _cols - 1 do begin
v := _buffer[r][c];
l := Math.min(l, v);
h := Math.max(h, v);
end;
end;
_stats.isValid := true;
_stats.low := l;
_stats.high := h;
getStats := _stats;
end;
function TAscFile.isCorner : boolean;
begin
result := not _isCorner;
end;
function TAscFile.isNodata(row, col: integer): boolean;
begin
if _buffer = nil then
isNodata := true;
isNoData := _buffer[row][col] = _unknown;
end;
function TAscFile.Line(row : integer) : TVector<integer>;
begin
if (row >= 0) and (row < rows) then
result := _buffer[row];
result := nil;
end;
function TAscFile.map : TMatrix<integer>;
begin
if _buffer = nil then
load();
result := _buffer;
end;
function TAscFile.ReadLine(var Stream: TBufferedFileStream; var line: string): boolean;
var
RawLine: UTF8String;
ch: AnsiChar;
begin
result := false;
ch := #0;
while (Stream.Read(ch, 1) = 1) and (ch <> #13) do
begin
result := true;
RawLine := RawLine + UTF8String(ch);
end;
line := string(RawLine);
if ch = #13 then
begin
result := true;
if (Stream.Read(ch, 1) = 1) and (ch <> #10) then
Stream.Seek(-1, soCurrent) // unread it if not LF character.
end
end;
function TAscFile.nextMetaField(var ascfile : TBufferedFileStream) : string;
var
line : string;
position : int64;
num : double;
begin
position := ascfile.Position;
line := '';
ReadLine(ascfile, line);
_parts.CommaText := line;
_isCorner := _parts[0] = 'center';
result := '';
if _parts.Count = 2 then
result := _parts[1]
else begin
if TryStrToFloat(_parts[0], num) then
ascfile.Position := position; // reset file pointer if not metadata field
end;
end;
procedure TAscFile.loadMetadata(var ascfile : TBufferedFileStream);
var
unk : string;
format : TFormatSettings;
begin
format.DecimalSeparator := '.';
format.ThousandSeparator := ',';
_cols := StrToInt(nextMetaField(ascfile));
_rows := StrToInt(nextMetaField(ascfile));
_left_X := StrToFloat(nextMetaField(ascfile), format);
_bottom_Y := StrToFloat(nextMetaField(ascfile), format);
_cellSize := StrToFloat(nextMetaField(ascfile), format);
// now try optional stuff
unk := nextMetaField(ascfile);
_countMetaData := 5;
if length(unk) > 0 then begin
_countMetaData := 6;
_unknown := StrToInt(unk);
end;
end;
function TAscFile.nextRow(var ascfile: TBufferedFileStream): TVector<integer>;
var
RawLine: UTF8String;
ch: AnsiChar;
values : TVector<integer>;
strval : string;
col : integer;
eof : boolean;
begin
setLength(values, _cols);
ch := #0;
col := 0;
eof := false;
while (not eof) and (col < _cols) do begin
eof := ascfile.Read(ch, 1) = 0;
// skip white space
while (not eof) and ( (ch = #13) or (ch = #10) or (ch = ' ') or (ch = #9)) do
eof := ascfile.Read(ch, 1) = 0;
// either EOF or ch is non-whitespace
while (not eof) and (ch <> #13) and (ch <> #10) and (ch <> ' ') and (ch <> #9) do
begin
RawLine := RawLine + UTF8String(ch);
eof := ascfile.Read(ch, 1) = 0;
end;
// either EOF of ch is whitespace
// convert found string to value
strval := string(RawLine);
RawLine := '';
values[col] := StrToIntDef(strval, _unknown);
inc(col);
end;
result := values;
end;
procedure TAscFile.load;
var
row : integer;
ascfile : TBufferedFileStream;
begin
ascfile := TBufferedFileStream.Create(_name, fmOpenRead);
try
try
loadMetadata(ascfile);
SetLength(_buffer, _rows);
for row := 0 to _rows - 1 do
_buffer[row] := nextRow(ascfile);
except
on EConvertError do begin
ShowMessage('Integer number expected: does the ASC file contain floats?');
end;
end;
finally
ascfile.Free;
end;
end;
{ TStats }
constructor TStats.Create(valid : boolean);
begin
isValid := valid;
end;
end.
|
unit ModelBank;
interface
{$INCLUDE source/Global_Conditionals.inc}
uses Model, ModelBankItem, SysUtils, {$IFDEF VOXEL_SUPPORT}Voxel, HVA,{$ENDIF} Palette,
GlConstants, ShaderBank;
type
TModelBank = class
private
FNextID: integer;
Items : array of TModelBankItem;
// Constructors and Destructors
procedure Clear;
// Adds
function Search(const _Filename: string): integer; overload;
function Search(const _Model: PModel): integer; overload;
{$IFDEF VOXEL_SUPPORT}
function Search(const _Voxel: PVoxel): integer; overload;
{$ENDIF}
function SearchReadOnly(const _Filename: string): integer; overload;
function SearchReadOnly(const _Model: PModel): integer; overload;
{$IFDEF VOXEL_SUPPORT}
function SearchReadOnly(const _Voxel: PVoxel): integer; overload;
{$ENDIF}
function SearchEditable(const _Model: PModel): integer; overload;
public
// Constructors and Destructors
constructor Create;
destructor Destroy; override;
// I/O
function Load(var _Model: PModel; const _Filename: string; _ShaderBank : PShaderBank): PModel;
function Save(var _Model: PModel; const _Filename,_TexExt: string): boolean;
// Adds
function Add(const _filename: string; _ShaderBank : PShaderBank): PModel; overload;
function Add(const _Model: PModel): PModel; overload;
{$IFDEF VOXEL_SUPPORT}
function Add(const _Voxel: PVoxel; const _HVA: PHVA; const _Palette: PPalette; _ShaderBank : PShaderBank; _Quality: integer = C_QUALITY_CUBED): PModel; overload;
function Add(const _VoxelSection: PVoxelSection; const _Palette: PPalette; _ShaderBank : PShaderBank; _Quality: integer = C_QUALITY_CUBED): PModel; overload;
{$ENDIF}
function AddReadOnly(const _filename: string; _ShaderBank : PShaderBank): PModel; overload;
function AddReadOnly(const _Model: PModel): PModel; overload;
{$IFDEF VOXEL_SUPPORT}
function AddReadOnly(const _Voxel: PVoxel; const _HVA: PHVA; const _Palette: PPalette; _ShaderBank : PShaderBank; _Quality: integer = C_QUALITY_CUBED): PModel; overload;
function AddReadOnly(const _VoxelSection: PVoxelSection; const _Palette: PPalette; _ShaderBank : PShaderBank; _Quality: integer = C_QUALITY_CUBED): PModel; overload;
{$ENDIF}
function Clone(const _filename: string; _ShaderBank : PShaderBank): PModel; overload;
function Clone(const _Model: PModel): PModel; overload;
{$IFDEF VOXEL_SUPPORT}
function Clone(const _Voxel: PVoxel; const _HVA: PHVA; const _Palette: PPalette; _ShaderBank : PShaderBank; _Quality: integer = C_QUALITY_CUBED): PModel; overload;
{$ENDIF}
// Deletes
procedure Delete(const _Model : PModel);
// Search
function Search(const _ID: integer): TModel; overload;
function SearchReadOnly(const _ID: integer): TModel; overload;
function SearchEditable(const _ID: integer): TModel; overload;
// Properties
property NextID: integer read FNextID;
end;
implementation
uses GlobalVars {$ifdef VOXEL_SUPPORT}, ModelVxt{$endif};
// Constructors and Destructors
constructor TModelBank.Create;
begin
SetLength(Items,0);
FNextID := 0;
end;
destructor TModelBank.Destroy;
begin
Clear;
inherited Destroy;
end;
// Only activated when the program is over.
procedure TModelBank.Clear;
var
i : integer;
begin
for i := Low(Items) to High(Items) do
begin
Items[i].Free;
end;
end;
// I/O
function TModelBank.Load(var _Model: PModel; const _Filename: string; _ShaderBank : PShaderBank): PModel;
var
i : integer;
begin
i := SearchEditable(_Model);
if i <> -1 then
begin
Items[i].DecCounter;
if Items[i].GetCount = 0 then
begin
Items[i].Free;
Items[i] := TModelBankItem.Create(_Filename,_ShaderBank);
Items[i].SetEditable(true);
inc(FNextID);
Result := Items[i].GetModel;
end
else
begin
SetLength(Items,High(Items)+2);
Items[High(Items)] := TModelBankItem.Create(_Filename,_ShaderBank);
Items[High(Items)].SetEditable(true);
inc(FNextID);
Result := Items[High(Items)].GetModel;
end;
end
else
begin
SetLength(Items,High(Items)+2);
Items[High(Items)] := TModelBankItem.Create(_Filename,_ShaderBank);
Items[High(Items)].SetEditable(true);
inc(FNextID);
Result := Items[High(Items)].GetModel;
end;
end;
function TModelBank.Save(var _Model: PModel; const _Filename, _TexExt: string): boolean;
var
i : integer;
Model : PModel;
begin
i := Search(_Model);
if i <> -1 then
begin
Model := Items[i].GetModel;
Model^.SaveLODToFile(_Filename, _TexExt);
Items[i].SetFilename(_Filename);
Result := true;
end
else
begin
Result := false;
end;
end;
// Adds
function TModelBank.Search(const _filename: string): integer;
var
i : integer;
begin
Result := -1;
if Length(_Filename) = 0 then
exit;
i := Low(Items);
while i <= High(Items) do
begin
if CompareStr(_Filename,Items[i].GetFilename) = 0 then
begin
Result := i;
exit;
end;
inc(i);
end;
end;
function TModelBank.Search(const _Model: PModel): integer;
var
i : integer;
begin
Result := -1;
if _Model = nil then
exit;
i := Low(Items);
while i <= High(Items) do
begin
if _Model = Items[i].GetModel then
begin
Result := i;
exit;
end;
inc(i);
end;
end;
{$IFDEF VOXEL_SUPPORT}
function TModelBank.Search(const _Voxel: PVoxel): integer;
var
i : integer;
Model: PModel;
begin
Result := -1;
if _Voxel = nil then
exit;
i := Low(Items);
while i <= High(Items) do
begin
Model := Items[i].GetModel;
if Model <> nil then
begin
if Model^.ModelType = C_MT_VOXEL then
begin
if Model^.IsOpened then
begin
if _Voxel = (Model^ as TModelVxt).Voxel then
begin
Result := i;
exit;
end;
end;
end;
end;
inc(i);
end;
end;
{$ENDIF}
function TModelBank.Search(const _ID: integer): TModel;
var
i : integer;
begin
Result := nil;
if (_ID < 0) then
exit;
i := Low(Items);
while i <= High(Items) do
begin
if Items[i].GetModel <> nil then
begin
if _ID = Items[i].GetModel^.ID then
begin
Result := Items[i].GetModel^;
exit;
end;
end;
inc(i);
end;
end;
function TModelBank.SearchReadOnly(const _filename: string): integer;
var
i : integer;
begin
Result := -1;
if Length(_Filename) = 0 then
exit;
i := Low(Items);
while i <= High(Items) do
begin
if not Items[i].GetEditable then
begin
if CompareStr(_Filename,Items[i].GetFilename) = 0 then
begin
Result := i;
exit;
end;
end;
inc(i);
end;
end;
function TModelBank.SearchReadOnly(const _Model: PModel): integer;
var
i : integer;
begin
Result := -1;
if _Model = nil then
exit;
i := Low(Items);
while i <= High(Items) do
begin
if not Items[i].GetEditable then
begin
if _Model = Items[i].GetModel then
begin
Result := i;
exit;
end;
end;
inc(i);
end;
end;
{$IFDEF VOXEL_SUPPORT}
function TModelBank.SearchReadOnly(const _Voxel: PVoxel): integer;
var
i : integer;
Model: PModel;
begin
Result := -1;
if _Voxel = nil then
exit;
i := Low(Items);
while i <= High(Items) do
begin
if not Items[i].GetEditable then
begin
Model := Items[i].GetModel;
if Model <> nil then
begin
if Model^.ModelType = C_MT_VOXEL then
begin
if _Voxel = (Model^ as TModelVxt).Voxel then
begin
Result := i;
exit;
end;
end;
end;
end;
inc(i);
end;
end;
{$ENDIF}
function TModelBank.SearchReadOnly(const _ID: integer): TModel;
var
i : integer;
begin
Result := nil;
if _ID < 0 then
exit;
i := Low(Items);
while i <= High(Items) do
begin
if not Items[i].GetEditable then
begin
if Items[i].GetModel <> nil then
begin
if _ID = Items[i].GetModel^.ID then
begin
Result := Items[i].GetModel^;
exit;
end;
end;
end;
inc(i);
end;
end;
function TModelBank.SearchEditable(const _Model: PModel): integer;
var
i : integer;
begin
Result := -1;
if _Model = nil then
exit;
i := Low(Items);
while i <= High(Items) do
begin
if Items[i].GetEditable then
begin
if _Model = Items[i].GetModel then
begin
Result := i;
exit;
end;
end;
inc(i);
end;
end;
function TModelBank.SearchEditable(const _ID: integer): TModel;
var
i : integer;
begin
Result := nil;
if _ID < 0 then
exit;
i := Low(Items);
while i <= High(Items) do
begin
if Items[i].GetEditable then
begin
if _ID = Items[i].GetModel^.ID then
begin
Result := Items[i].GetModel^;
exit;
end;
end;
inc(i);
end;
end;
function TModelBank.Add(const _filename: string; _ShaderBank : PShaderBank): PModel;
var
i : integer;
begin
i := Search(_Filename);
if i <> -1 then
begin
Items[i].IncCounter;
Result := Items[i].GetModel;
end
else
begin
SetLength(Items,High(Items)+2);
Items[High(Items)] := TModelBankItem.Create(_Filename,_ShaderBank);
inc(FNextID);
Result := Items[High(Items)].GetModel;
end;
end;
function TModelBank.Add(const _Model: PModel): PModel;
var
i : integer;
begin
i := Search(_Model);
if i <> -1 then
begin
Items[i].IncCounter;
Result := Items[i].GetModel;
end
else
begin
SetLength(Items,High(Items)+2);
Items[High(Items)] := TModelBankItem.Create(_Model);
inc(FNextID);
Result := Items[High(Items)].GetModel;
end;
end;
{$IFDEF VOXEL_SUPPORT}
function TModelBank.Add(const _Voxel: PVoxel; const _HVA: PHVA; const _Palette: PPalette; _ShaderBank : PShaderBank; _Quality: integer = C_QUALITY_CUBED): PModel;
var
i : integer;
begin
i := Search(_Voxel);
if i <> -1 then
begin
Items[i].IncCounter;
Result := Items[i].GetModel;
end
else
begin
SetLength(Items,High(Items)+2);
Items[High(Items)] := TModelBankItem.Create(_Voxel,_HVA,_Palette,_ShaderBank,_Quality);
inc(FNextID);
Result := Items[High(Items)].GetModel;
end;
end;
function TModelBank.Add(const _VoxelSection: PVoxelSection; const _Palette: PPalette; _ShaderBank : PShaderBank; _Quality: integer = C_QUALITY_CUBED): PModel;
begin
SetLength(Items,High(Items)+2);
Items[High(Items)] := TModelBankItem.Create(_VoxelSection,_Palette,_ShaderBank,_Quality);
inc(FNextID);
Result := Items[High(Items)].GetModel;
end;
{$ENDIF}
function TModelBank.AddReadOnly(const _filename: string; _ShaderBank : PShaderBank): PModel;
var
i : integer;
begin
i := SearchReadOnly(_Filename);
if i <> -1 then
begin
Items[i].IncCounter;
Result := Items[i].GetModel;
end
else
begin
SetLength(Items,High(Items)+2);
Items[High(Items)] := TModelBankItem.Create(_Filename,_ShaderBank);
inc(FNextID);
Result := Items[High(Items)].GetModel;
end;
end;
function TModelBank.AddReadOnly(const _Model: PModel): PModel;
var
i : integer;
begin
i := SearchReadOnly(_Model);
if i <> -1 then
begin
Items[i].IncCounter;
Result := Items[i].GetModel;
end
else
begin
SetLength(Items,High(Items)+2);
Items[High(Items)] := TModelBankItem.Create(_Model);
inc(FNextID);
Result := Items[High(Items)].GetModel;
end;
end;
{$IFDEF VOXEL_SUPPORT}
function TModelBank.AddReadOnly(const _Voxel: PVoxel; const _HVA: PHVA; const _Palette: PPalette; _ShaderBank : PShaderBank; _Quality: integer = C_QUALITY_CUBED): PModel;
var
i : integer;
begin
i := SearchReadOnly(_Voxel);
if i <> -1 then
begin
Items[i].IncCounter;
Result := Items[i].GetModel;
end
else
begin
SetLength(Items,High(Items)+2);
Items[High(Items)] := TModelBankItem.Create(_Voxel,_HVA,_Palette,_ShaderBank,_Quality);
inc(FNextID);
Result := Items[High(Items)].GetModel;
end;
end;
function TModelBank.AddReadOnly(const _VoxelSection: PVoxelSection; const _Palette: PPalette; _ShaderBank : PShaderBank; _Quality: integer = C_QUALITY_CUBED): PModel;
begin
SetLength(Items,High(Items)+2);
Items[High(Items)] := TModelBankItem.Create(_VoxelSection,_Palette,_ShaderBank,_Quality);
inc(FNextID);
Result := Items[High(Items)].GetModel;
end;
{$ENDIF}
function TModelBank.Clone(const _filename: string; _ShaderBank : PShaderBank): PModel;
begin
SetLength(Items,High(Items)+2);
Items[High(Items)] := TModelBankItem.Create(_Filename,_ShaderBank);
inc(FNextID);
Result := Items[High(Items)].GetModel;
end;
function TModelBank.Clone(const _Model: PModel): PModel;
begin
SetLength(Items,High(Items)+2);
Items[High(Items)] := TModelBankItem.Create(_Model);
inc(FNextID);
Result := Items[High(Items)].GetModel;
end;
{$IFDEF VOXEL_SUPPORT}
function TModelBank.Clone(const _Voxel: PVoxel; const _HVA: PHVA; const _Palette: PPalette; _ShaderBank : PShaderBank; _Quality: integer = C_QUALITY_CUBED): PModel;
begin
SetLength(Items,High(Items)+2);
Items[High(Items)] := TModelBankItem.Create(_Voxel,_HVA,_Palette,_ShaderBank,_Quality);
inc(FNextID);
Result := Items[High(Items)].GetModel;
end;
{$ENDIF}
// Deletes
procedure TModelBank.Delete(const _Model : PModel);
var
i : integer;
begin
i := Search(_Model);
if i <> -1 then
begin
Items[i].DecCounter;
if Items[i].GetCount = 0 then
begin
Items[i].Free;
while i < High(Items) do
begin
Items[i] := Items[i+1];
inc(i);
end;
SetLength(Items,High(Items));
end;
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.