text stringlengths 14 6.51M |
|---|
unit Unit_Common_Consts;
interface
resourcestring
Common_AddStud0_Text = '';
Common_AddStud1_Text = 'Навчання: Денна (безкоштовне по держ. заказу) ';
Common_AddStud2_Text = 'Навчання: Денна (платне за договором)';
Common_AddStud3_Text = 'Навчання: Денна (безкоштовне по держ. заказу)';
Common_AddStud4_Text = 'Навчання: Заочна(платне за договором)';
Common_NameWork0_Text = 'Неможливо встановити';
Common_NameWork1_Text = 'Основне місце роботи. ';
Common_NameWork2_Text = 'За сумісництвом. ';
Common_NameWork3_Text = '';
implementation
end.
|
//
// Generated by JavaToPas v1.5 20160510 - 150058
////////////////////////////////////////////////////////////////////////////////
unit android.media.MediaMuxer_OutputFormat;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes;
type
JMediaMuxer_OutputFormat = interface;
JMediaMuxer_OutputFormatClass = interface(JObjectClass)
['{DFA1D78F-E577-4597-9106-C33FA123DA6B}']
function _GetMUXER_OUTPUT_MPEG_4 : Integer; cdecl; // A: $19
function _GetMUXER_OUTPUT_WEBM : Integer; cdecl; // A: $19
property MUXER_OUTPUT_MPEG_4 : Integer read _GetMUXER_OUTPUT_MPEG_4; // I A: $19
property MUXER_OUTPUT_WEBM : Integer read _GetMUXER_OUTPUT_WEBM; // I A: $19
end;
[JavaSignature('android/media/MediaMuxer_OutputFormat')]
JMediaMuxer_OutputFormat = interface(JObject)
['{599B1EB0-61C0-496C-9901-BAFA7A38A722}']
end;
TJMediaMuxer_OutputFormat = class(TJavaGenericImport<JMediaMuxer_OutputFormatClass, JMediaMuxer_OutputFormat>)
end;
const
TJMediaMuxer_OutputFormatMUXER_OUTPUT_MPEG_4 = 0;
TJMediaMuxer_OutputFormatMUXER_OUTPUT_WEBM = 1;
implementation
end.
|
unit Odontologia.Vistas.Template;
interface
uses
Data.DB,
Winapi.Windows,
Winapi.Messages,
System.ImageList,
System.SysUtils,
System.Variants,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
Vcl.Buttons,
Vcl.Grids,
Vcl.DBGrids,
Vcl.WinXPanels,
Vcl.ExtCtrls,
Vcl.ImgList,
Odontologia.Vista.Estilos;
type
TPagTemplate = class(TForm)
DataSource1: TDataSource;
ImageList1: TImageList;
CardPanel1: TCardPanel;
Card1: TCard;
Card2: TCard;
DBGrid1: TDBGrid;
PnlPrincipal: TPanel;
PnlCentralGrid: TPanel;
PnlCentralGridLinea: TPanel;
PnlPieBotonAccion: TPanel;
PnlPieBotonPagina: TPanel;
PnlSubTitulo: TPanel;
PnlCabecera: TPanel;
PnlCabeceraBusqueda: TPanel;
PnlCentralFormulario: TPanel;
PnlPieBotonEdicion: TPanel;
PnlCabeceraBusquedaLinea: TPanel;
PnlCabeceraTitulo: TPanel;
btnActualizar: TSpeedButton;
btnNuevo: TSpeedButton;
btnPrior: TSpeedButton;
btnNext: TSpeedButton;
btnBorrar: TSpeedButton;
btnCancelar: TSpeedButton;
btnGuardar: TSpeedButton;
lblTitulo: TLabel;
lblTitulo2: TLabel;
lblPagina: TLabel;
lblSearch: TLabel;
edtSearch: TEdit;
btnCerrar: TSpeedButton;
procedure FormCreate(Sender: TObject);
procedure btnCerrarClick(Sender: TObject);
procedure btnNuevoClick(Sender: TObject);
procedure btnActualizarClick(Sender: TObject);
procedure btnGuardarClick(Sender: TObject);
procedure btnCancelarClick(Sender: TObject);
procedure DBGrid1DblClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
PagTemplate: TPagTemplate;
implementation
uses
Odontologia.Vistas.Main;
{$R *.dfm}
procedure TPagTemplate.btnActualizarClick(Sender: TObject);
begin
modoEdicion := False;
end;
procedure TPagTemplate.btnCancelarClick(Sender: TObject);
begin
modoEdicion := False;
end;
procedure TPagTemplate.btnCerrarClick(Sender: TObject);
begin
if MessageDlg('Está seguro de cerrar la ventana?', mtConfirmation,
[mbOk, mbCancel], 0) = mrOk then
close;
end;
procedure TPagTemplate.btnGuardarClick(Sender: TObject);
begin
modoEdicion := False;
end;
procedure TPagTemplate.btnNuevoClick(Sender: TObject);
begin
modoEdicion := True;
end;
procedure TPagTemplate.DBGrid1DblClick(Sender: TObject);
begin
modoEdicion := True;
end;
procedure TPagTemplate.FormCreate(Sender: TObject);
begin
Self.Font.Color := FONT_COLOR;
Self.Font.Size := FONT_H7;
CardPanel1.ActiveCard := Card1;
CardPanel1.Color := COLOR_BACKGROUND;
PnlPrincipal.Color := COLOR_BACKGROUND;
PnlCabeceraBusqueda.Color := COLOR_BACKGROUND;
PnlCabeceraTitulo.Color := COLOR_BACKGROUND;
PnlCabeceraBusquedaLinea.Color := COLOR_BACKGROUND_DESTAK;
PnlCentralGridLinea.Color := COLOR_BACKGROUND_DESTAK;
PnlCentralGrid.Color := COLOR_BACKGROUND;
PnlPieBotonAccion.Color := COLOR_BACKGROUND;
PnlPieBotonPagina.Color := COLOR_BACKGROUND;
PnlCentralFormulario.Color := COLOR_BACKGROUND;
PnlPieBotonEdicion.Color := COLOR_BACKGROUND;
PnlSubTitulo.Color := COLOR_BACKGROUND;
lblTitulo.Font.Color := FONT_COLOR3;
lblTitulo.Font.Size := FONT_H5;
lblTitulo2.Font.Color := FONT_COLOR3;
lblTitulo2.Font.Size := FONT_H5;
end;
end.
|
unit SdStructures_U;
// Description:
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
Classes, SysUtils, Windows;
const
CipherType : array[0..8] of string = ('Summer v1', 'Blowfish 256 bit', 'TEA (16 round) 128 bit',
'TEA (32 round) 128 bit', 'IDEA - AscomTech AG 128 bit', 'DES 56 bit', 'Square 128 bit',
'Mitsubishi Misty1 128 bit', 'Triple DES 168 bit');
const
MAX_SCRAMDISK_SLOTS = 7;
type
EScramDiskError = Exception;
ESDWrongVersion = EScramDiskError;
ESDVxdNotFound = EScramDiskError;
ESDVxdNotConnected = EScramDiskError;
ESDDriveInUse = EScramDiskError;
// ==========
// -- begin -- Introduced for ScramDisk v3.xx
// ==========
TDIOCParams = packed record
dwIoControlCode: DWORD;
lpvInBuffer: Pointer; // xxx - should be DWORD or Pointer?
cbInBuffer: DWORD;
lpvOutBuffer: Pointer; // xxx - should be DWORD or Pointer?
cbOutBuffer: DWORD;
pUserSpace: Pointer; // NT pointer to context ram used by driver
end;
// Fields common to physical and logical disk DCB's
TDCB_COMMON = packed record
DCB_physical_dcb: longword; // DCB for physical device
DCB_expansion_length: longword; // total length of IOP extension filled
// in by IOS (excludes IOP size)
//
// Link fields follow
//
DCB_ptr_cd: Pointer; // pointer to calldown list
DCB_next_dcb: longword; // link to next DCB
DCB_next_logical_dcb: longword; // pointer to next logical dcb
// for physical device
DCB_drive_lttr_equiv: byte; // drive number (A: = 0, etc.)
// set up by iosserv during logical
// device associate processing.
DCB_unit_number: byte; // either physical drive number
// (sequential drive number or'd
// with 80h) or unit number within
// tsd. set up by iosbid for disk
// physical dcb's. set up by tsdpart
// for disk logical dcb's. set up by
// tsdaer for cdrom physical dcb's.
DCB_TSD_Flags: word; // Flags for TSD
//
// Volume Tracking fields follow
//
DCB_vrp_ptr: longword; // pointer to VRP for this DCB
DCB_dmd_flags: longword; // demand bits of the topmost layer
DCB_device_flags: longword; // was BDD_Flags
DCB_device_flags2: longword; // second set of general purpose flags
DCB_Partition_Start: longword; // partition start sector
DCB_track_table_ptr: longword; // pointer for the track table buffer
// for ioctls
DCB_bds_ptr: longword; // DOS BDS corresp. to this DCB
// (logical DCB's only)
DCB_Reserved1: longword; // reserved - MBZ
DCB_Reserved2: longword; // reserved - MBZ
DCB_apparent_blk_shift: byte; // log of apparent_blk_size
DCB_partition_type: byte; // partition type
DCB_sig: word; // padding and signature
DCB_device_type: byte; // Device Type
DCB_Exclusive_VM: longword; // handle for exclusive access to this device
DCB_disk_bpb_flags: byte; // bpb flags see defines below
DCB_cAssoc: byte; // count of logical drives
// associated with this logical DCB
DCB_Sstor_Host: byte; // This field indicates a sstor host volume
DCB_user_drvlet: word; // contains the userdriveletter settings else ff
DCB_Reserved3: word; // reserved - MBZ
DCB_Reserved4: longword; // reserved - MBZ
end;
// blockdev compatible fields in physical disk DCB's
TDCB_BLOCKDEV = packed record
// The initial set of fields below should not be re-ordered or modified in
// anyway as the offset and the size of fileds have to match those
// in BLOCKDEV.H for COMPATIBITLITY!!!
DCB_BDD_Next: longword;
DCB_BDD_BD_Major_Version: byte; // INIT <BDD_BD_Major_Ver>
DCB_BDD_BD_Minor_Version: byte; // INIT <BDD_BD_Minor_Ver>
DCB_BDD_Device_SubType: byte;
DCB_BDD_Int_13h_Number: byte;
DCB_BDD_flags: longword; // was BDD_Flags
DCB_BDD_Name_Ptr: longword;
DCB_apparent_sector_cnt: array [0..1] of longword; // num. of secs as seen by tsd and above
DCB_apparent_blk_size: longword; // blk size of dev. as seen by tsd and above
DCB_apparent_head_cnt: longword; // num. of heads as seen by tsd and above
DCB_apparent_cyl_cnt: longword; // num. of cyls as seen by tsd and above
DCB_apparent_spt: longword; // num. of secs/trk as seen by tsd and above
DCB_BDD_Sync_Cmd_Proc: longword;
DCB_BDD_Command_Proc: longword;
DCB_BDD_Hw_Int_Proc: longword; // INIT <0>
DCB_BDP_Cmd_Queue_Ascending: longword;
DCB_BDP_Cmd_Queue_Descending: longword;
DCB_BDP_Current_Flags: longword;
DCB_BDP_Int13_Param_Ptr: longword;
DCB_BDP_Current_Command: longword;
DCB_BDP_Current_Position: array [0..1] of longword;
DCB_BDP_Reserved: array [0..4] of longword;
DCB_fastdisk_bdd: longword; // set for DCBs created when a fastdisk regs
// with the blockdev BDD for it else 0
// End BlockDev compatibility
end;
// define the device control block (dcb) for physical devices (i.e., disks)
TMYDCB = packed record
DCB_cmn: TDCB_COMMON;
DCB_max_xfer_len: longword; // maximum transfer length
//
// Actual geometry data follows
//
DCB_actual_sector_cnt: array [0..1] of longword; // number of sectors as seen below
// the tsd.
DCB_actual_blk_size: longword; // actual block size of the device
// as seen below the tsd.
DCB_actual_head_cnt: longword; // number of heads as seen below
// the tsd.
DCB_actual_cyl_cnt: longword; // number of cylinders as seen
// below the tsd.
DCB_actual_spt: longword; // number of sectors per track as
// seen below the tsd.
DCB_next_ddb_dcb: Pointer; // link to next DCB on DDB chain
DCB_dev_node: Pointer; // pointer to dev node for this device
DCB_bus_type: byte; // Type of BUS, see below
DCB_bus_number: byte; // channel (cable) within adapter
DCB_queue_freeze: byte; // queue freeze depth counter
DCB_max_sg_elements: byte; // max # s/g elements. set initially
// by port, but may be MORE RESTRICTIVELY
// updated by other layers
DCB_io_pend_count: byte; // indicates number of requests pending
// for this DCB (VOLUME TRACKING LAYER USE ONLY)
DCB_lock_count: byte; // depth counter for LOCK MEDIA commands
// (VOLUME TRACKING LAYER USE ONLY)
//
// SCSI fields follow
//
DCB_SCSI_VSD_FLAGS: word; // Flags for SRB builder
DCB_scsi_target_id: byte; // SCSI target ID
DCB_scsi_lun: byte; // SCSI logical unit number
DCB_scsi_hba: byte; // adapter number relative to port driver
DCB_max_sense_data_len: byte; // Maximum sense Length
DCB_srb_ext_size: word; // miniport srb extension length
DCB_inquiry_flags: array [0..7] of byte; // Device Inquiry Flags
DCB_vendor_id: array [0..7] of AnsiChar; // Vendor ID string
DCB_product_id: array [0..15] of AnsiChar; // Product ID string
DCB_rev_level: array [0..3] of byte; // Product revision level
DCB_port_name: array [0..7] of byte;
DCB_current_unit: byte; // used to emulate multiple logical devices
// with a single physical device
DCB_blocked_iop: longword; // pointer to requests for an inactive
// volume (VOLUME TRACKING LAYER USE ONLY)
DCB_vol_unlock_timer: longword; // unlock timer handle
DCB_access_timer: byte; // used to measure time between accesses
DCB_Vol_Flags: byte; // Flags for Volume Tracking
// volume tracking use only
DCB_q_algo: byte; // queuing algorithm index - see
// values below.
DCB_unit_on_ctl: byte; // relative device number on ctlr (0-based)
DCB_Port_Specific: longword; // bytes for PORT DRIVER use
DCB_spindown_timer: longword; // timer for drive spin down
DCB_bdd: TDCB_BLOCKDEV;
end;
PTMYDCB = ^TMYDCB;
// ==========
// -- end -- Introduced for ScramDisk v3.xx
// ==========
TDeviceInfo = packed record
dr_lett1 : AnsiChar;
dr_lett1status : AnsiChar;
dr_lett2 : AnsiChar;
dr_lett2status : AnsiChar;
dr_lett3 : AnsiChar;
dr_lett3status : AnsiChar;
dr_lett4 : AnsiChar;
dr_lett4status : AnsiChar;
dr_lett5 : AnsiChar;
dr_lett5status : AnsiChar;
dr_lett6 : AnsiChar;
dr_lett6status : AnsiChar;
dr_lett7 : AnsiChar;
dr_lett7status : AnsiChar;
dr_lett8 : AnsiChar;
dr_lett8status : AnsiChar;
end;
TMountType = (mtNotMounted, mtPartition, mtSVLFile, mtWAVFile, mtTimedOut, mtUnknown);
// "VolumeName" has been removed from TSlotInfo - call GetVolumeInformation if
// you need this information
TSlotInfo = packed record
SlotNo: Integer;
MountType: TMountType;
HostDriveLetter: AnsiString;
DriveMountedAs: AnsiString;
CipherType: string;
FileName: string; // Will be set to partition ID if a partition is mounted.
// Under Win9x/Me, set to the drive ID if a partition is
// mounted.
Comments: string;
PreferredDrive: string;
NoAccesses: Integer;
LastAccess: TDateTime;
readonly: boolean;
softReadOnly: boolean; // mounted as readonly because header information
// set to readonly
mediaReadOnly: boolean; // mounted as readonly because the media on which
// the volume resides is readonly/the volume file's
// file attributes are readonly
wavFileBits: integer; // Gets set to either 4 (of 16 bits) or 8 (of 16 bits)
partitionRemovable: boolean; // If mountType=mtPartition, this will be
// TRUE if the partition is removable,
// otherwise FALSE
viaSKFFile: boolean; // Set to TRUE if mounted via an SKF file
bfs: boolean; // Bypassed File System! ScramDisk v3 (and above) under Windows 9x/Me only
end;
TDeviceIOControlRegisters = packed record
EBX : DWORD;
EDX : DWORD;
ECX : DWORD;
EAX : DWORD;
EDI : DWORD;
ESI : DWORD;
Flags : DWORD;
end;
TParamBlock = packed record
Operation : Integer;
NumLocks : Integer;
end;
{
// XXX - delete if no problems with mounting under v2.02 and v3 under Win95/98/ME
// xxx - previously called - DELETE IF NO PROBS -
TMountFileStruct = packed record
DCB: Integer;
Reserved1 : Integer; //reserved....
Reserved2 : Integer; //reserved....
WavOffset : Integer; // this has the offset to the WAV data if WAV (|0x80000000 if 4 bit wav)
// Win32 needs to calculate wavoffset. See Scramdisk source code...
FileName : PChar; // string of file to mount.
MountDrive : Integer;
MountSlot : Integer;
MountResult : Integer; // set to 3 if file mounts ok Bit 8 set if WAV and buffer cannot allocate...
// Set to 0x83 (bit 7 set) if file ALREADY mounted.....
// Set to 0 if no slots free
// 1 Not mounted
Critical : PChar; // Points at 2k critical data, for SKF mount or nil for normal
end;
}
// xxx - previously called - DELETE THIS LINE IF NO PROBS - TNewNTMountFileStruct
TMountFileStruct = packed record
//union
//{
// MYPDCB dcb;
// int NtRealError;
//};
delphiUnion: record
case Byte of
0: ( dcb: PTMYDCB );
1: ( NtRealError: integer );
end;
DrvObjAbandoned: cardinal; // flags1; //inclusive
bytespersector: cardinal; // flagsMagic; //inclusive
wavoffset: cardinal; // attrib
fname: PAnsiChar; // previously "FileName"
mountdrive: cardinal;
LogicalDrives: cardinal; // Previously "mountslot"
mountresult: cardinal; // Set to 3 if file mounts OK - bit 8 set if WAV and buffer cannot allocate
// Set to 0x83 (bit 7 set) if file ALREADY mounted
// Set to 0 if no slots free
// 1 Not mounted
critical: PAnsiChar;
end;
// xxx - previously called - DELETE THIS LINE IF NO PROBS - PTNewNTMountFileStruct = ^TNewNTMountFileStruct;
PTMountFileStruct = ^TMountFileStruct;
TInfoStruct = packed record
// slotNo is added, and infotext is reduced by 4 bytes to compensate
// in comparison to the original ScramDisk source code, which just passed
// slotNo as the first 4 bytes of infotext
slotNo: integer; // slotNo and infotext - "infotext" in
infotext: array [0..255] of Ansichar; // the ScramDisk source is 256 bytes
// long, and slotNo doesn't exist in the
// struct. However, due to the wierdo way
// ScramDisk does things (passing slotNo
// in as the first 4 bytes of infotext),
// this is what the Delphi record should
// look like.
// YUCK!
// i.e. It may look wrong here, but it
// works, so just don't ask, OK?
accessed: integer; // any user... 4
preferredletter: integer; // any user 4
magiclow: integer; // any user 4
magichigh: integer; // any user 4
newtime: TSystemTime; //any user 16 bytes
TimeValid1: integer; // any user 4 bytes
oldtime: TSystemTime; //any user 16 bytes
TimeValid2: integer; //any user 4
newmode: integer; //any user 4
sumLOW: cardinal;
sumHIGH: cardinal;
sum3: cardinal; //dummy
sum4: cardinal; //dummy
invalidsum: Ansichar;
owner: Ansichar;
spare2: Ansichar;
spare3: Ansichar;
writeEnabled: integer;
dummy: array [0..171] of Ansichar; // Ugg... ScramDisk shouldn't never
// actually use this - it's not part of
// the struct. However, ScramDisk uses a
// 516 byte buffer for when calling
// DevioceIOControl with READINFOBLOCK,
// and during this call, data is written
// past the end of the struct.
// We therefore have to add in this array
// to compensate
// DOUBLE YUCK IN ONE STRUCT!
end;
PInfoStruct = ^TInfoStruct;
TWavInfo = packed record
DataPointer : PAnsiChar;
FileOffset : Cardinal;
NumChannels : Word;
WavType : Word;
BitsPerSample : Word;
Length : Cardinal;
end;
TDDB = packed record
DDB_phys_addr : Cardinal;
DDB_Next_DDB : Cardinal;
DDB_Next_DDB_init : Cardinal;
DDB_dcb_ptr : Cardinal;
DDB_number_buses : Byte;
DDB_ios_flags : Byte;
DDB_sig : Word;
DDB_dvt : Pointer;
DDB_devnode_ptr : Pointer;
DDB_reserved : Pointer;
end;
TSlotInfoEx = packed record
DriveMountedFrom : string;
DriveMountedAs : string;
VolumeName : string;
end;
// bpb introduced in ScramDisk v3
Tbpb = packed record
bytespersector: word;
sectorspercluster: byte;
sectorsreserved: word;
numfats: byte;
numdirentries: word;
smalldisksectors: word;
mediadescripter: byte;
sectorsperfat: word;
sectorspertrack: word;
numheads: word;
hiddensectorcount: longword;
bigdisksectors: longword;
drivenum: byte;
bytereserved: byte;
extendbootsig: byte;
serialnumber: longword;
volname: array [0..10] of AnsiChar;
padding: array [0..4] of AnsiChar; // Additional field required to get it to a
// DWORD boundry
voltype: array [0..7] of AnsiChar;
end;
TCryptVol = packed record
cipher : Integer;
index : Integer;
wavoffset : Integer;
ldcb: PTMYDCB;
linkediop : Integer;
booted : Integer;
driveinuse : Integer;
drive : Integer;
cryptsectorfirst : Cardinal;
cryptsectorlast : Cardinal;
physdevDCB : PTMYDCB;
mainkeys : array[0..2047] of AnsiChar;
mountfilehandle : Integer;
devicetype : Integer;
SKFCreateTime : Integer;
flags: integer; // Previously "digestindex : Integer;" with ScramDisk v2.02h
timeoutcount: DWORD;
spare3 : Integer;
volname : array[0..15] of AnsiChar;
digest : array[0..19] of AnsiChar;
bpb: Tbpb;
// spare is an array of char with dimensions [0..((20*7)-sizeof(bpb))-1];
// bpb is 56 bytes long
spare: array[0..83] of AnsiChar;
addb : TDDB;
logicaldcb: TMYDCB;
mounted_file_name : array[0..511] of AnsiChar;
end;
PTCryptVol = ^TCryptVol;
const
VWIN32_DIOC_DOS_IOCTL = 1;
PD_GETCVS = 1;
PD_INQUIRE_DEVICES = 2;
NUMBER_MOUNT_TYPES = 3;
REQMON_INQUIRE_DEVICES = 4;
INQUIRE_CRYPT_DEVICES = 4;
SUPPLY_PASSWORD = 5;
CLOSE_CRYPTED_DEVICE1 = 6;
CLOSE_CRYPTED_DEVICE2 = 7;
CLOSE_CRYPTED_DEVICE3 = 8;
CLOSE_CRYPTED_DEVICE4 = 9;
PUTCVS = 10;
DISKIO = 11;
GETDCBINFO = 12;
FINDDRIVELETTER = 13;
DISMOUNTDRIVE = 14;
MOUNTFILE = 15;
GETSHIFTCONST = 16;
CLEARPASSWORDS = 17;
MOUNTNEWDISK = 18;
BORDER = 19;
VALIDATEPASSWORD = 20;
APPQUERY = 21;
VOLQUERY = 22;
GETDRIVERVERSION = 23;
SETTIMEOUT = 24;
RELEASETIMESLICE = 25;
READINFOBLOCK = 26;
WRITEINFOBLOCK = 27;
R0FILEIO = 28;
RING0CALLBACK = 29;
UNINSTALLSCRAMDISK = 30;
SETKEYFILEPASSWORD = 31;
GETKEYFILEPASSWORD = 32;
GETPASSWORDBUFFER = 33;
GETINKEY = 34;
SUPPLYDATEANDTIME = 35;
SUPPLYCLICKEDFILENAME = 36;
SENDFORCEQUIT = 37;
REVOKESKFDATA = 38;
RAWDEVICEDATA = 39;
CHANGEPASSWORDS = 40;
CLOSE_CRYPTED_DEVICE_N = 41;
APP_REQUEST_REFRESH = 42;
INQUIRE_SLOT = 43;
E_NOT_CONNECTED = 'ScramDisk not connected - set Active to TRUE first';
E_DRIVE_IN_USE = 'Close all windows and applications used by this drive first';
implementation
end.
|
unit Class_Dict;
//YXC_2010_05_08_22_50_59
//×Öµä±í
interface
uses
Classes,SysUtils,ADODB,Class_DBPool;
type
TDict=class(TObject)
public
DictIdex:Integer; //×ÖµäÐòÁÐ
DictCode:string; //×Öµä±àÂë
DictName:string; //×ÖµäÃû³Æ
DictValu:string; //×ÖµäÖµ
public
procedure InsertDB(AADOCon:TADOConnection);
procedure UpdateDB;overload;
procedure UpdateDB(AADOCon:TADOConnection);overload;
procedure DeleteDB;overload;
procedure DeleteDB(AADOCon:TADOConnection);overload;
function GetNextCode(AADOCon:TADOConnection):Integer;
function CheckExist(AADOCon:TADOConnection):Boolean;
public
class function ReadDS(AADODS:TADODataSet):TDict;
class function ReadDB(ACode:string):TDict;overload;
class function ReadDB(ACode:string;AADOCon:TADOConnection):TDict;overload;
class function StrsDB:TStringList;overload;
class function StrsDB(ASQL:string):TStringList;overload;
class function StrsDB(AADOCon:TADOConnection;ASQL:string):TStringList;overload;
end;
implementation
uses
UtilLib;
{ TDict }
function TDict.CheckExist(AADOCon: TADOConnection): Boolean;
begin
Result:=TryCheckExist(AADOCon,'TBL_DICT',['DICT_VALU',DictValu]);
end;
procedure TDict.DeleteDB(AADOCon: TADOConnection);
var
ASQL:string;
begin
ASQL:='DELETE FROM TBL_DICT WHERE DICT_IDEX=%D';
ASQL:=Format(ASQL,[DictIdex]);
TryDeleteDB(AADOCon,ASQL);
end;
procedure TDict.DeleteDB;
var
ADOCon:TADOConnection;
begin
try
ADOCon:=TDBPool.GetConnect();
DeleteDB(ADOCon);
finally
FreeAndNil(ADOCon);
end;
end;
function TDict.GetNextCode(AADOCon: TADOConnection): Integer;
begin
Result:=TryCheckField(AADOCon,'DICT_IDEX','TBL_DICT',[]);
end;
procedure TDict.InsertDB(AADOCon: TADOConnection);
var
ADOCmd : TADOCommand;
begin
try
ADOCmd := TADOCommand.Create(nil);
ADOCmd.Connection := AADOCon;
ADOCmd.Prepared := True;
with ADOCmd do
begin
CommandText:= 'INSERT INTO TBL_DICT '
+ ' (DICT_IDEX, DICT_CODE, DICT_NAME, DICT_VALU)'
+ ' VALUES(:DICT_IDEX, :DICT_CODE, :DICT_NAME, :DICT_VALU)';
with Parameters do
begin
ParamByName('DICT_IDEX').Value := DICTIDEX;
ParamByName('DICT_CODE').Value := DICTCODE;
ParamByName('DICT_NAME').Value := DICTNAME;
ParamByName('DICT_VALU').Value := DICTVALU;
end;
Execute;
end;
finally
FreeAndNil(ADOCmd);
end;
end;
class function TDict.ReadDB(ACode: string; AADOCon: TADOConnection): TDict;
var
ADODS:TADODataSet;
AObj :TDict;
ASQL :string;
begin
Result:=nil;
try
ADODS:=TADODataSet.Create(nil);
ADODS.Connection:=AADOCon;
ADODS.Prepared:=True;
ASQL:='SELECT * FROM TBL_DICT WHERE DICT_CODE=%S';
ASQL:=Format(ASQL,[QuotedStr(ACode)]);
ADODS.CommandText:=ASQL;
ADODS.Open;
ADODS.First;
if ADODS.RecordCount=0 then Exit;
while not ADODS.Eof do
begin
Result:=ReadDS(ADODS);
ADODS.Next;
end;
finally
FreeAndNil(ADODS);
end;
end;
class function TDict.ReadDB(ACode: string): TDict;
var
ADOCon:TADOConnection;
begin
try
ADOCon:=TDBPool.GetConnect();
Result:=ReadDB(ACode,ADOCon);
finally
FreeAndNil(ADOCon);
end;
end;
class function TDict.ReadDS(AADODS: TADODataSet): TDict;
begin
Result:=TDict.Create;
with Result do
begin
DictIdex:=AADODS.FieldByName('DICT_IDEX').AsInteger;
DictCode:=AADODS.FieldByName('DICT_CODE').AsString;
DictName:=AADODS.FieldByName('DICT_NAME').AsString;
DictValu:=AADODS.FieldByName('DICT_VALU').AsString;
end;
end;
class function TDict.StrsDB: TStringList;
var
ASQL :string;
ADOCon:TADOConnection;
begin
try
ADOCon:=TDBPool.GetConnect();
ASQL :='SELECT * FROM TBL_DICT';
Result:=StrsDB(ADOCon,ASQL);
finally
FreeAndNil(ADOCon);
end;
end;
class function TDict.StrsDB(AADOCon: TADOConnection;
ASQL: string): TStringList;
var
ADODS:TADODataSet;
AObj :TDict;
begin
Result:=nil;
try
ADODS:=TADODataSet.Create(nil);
ADODS.Connection:=AADOCon;
ADODS.Prepared:=True;
if ASQL='' then raise Exception.Create('ASQL=NIL');
ADODS.CommandText:=ASQL;
ADODS.Open;
ADODS.First;
if ADODS.RecordCount=0 then Exit;
Result:=TStringList.Create;
while not ADODS.Eof do
begin
AObj:=ReadDS(ADODS);
Result.AddObject(AObj.DictName,AObj);
ADODS.Next;
end;
finally
FreeAndNil(ADODS);
end;
end;
class function TDict.StrsDB(ASQL: string): TStringList;
var
ADOCon:TADOConnection;
begin
try
ADOCon:=TDBPool.GetConnect();
Result:=StrsDB(ADOCon,ASQL);
finally
FreeAndNil(ADOCon);
end;
end;
procedure TDict.UpdateDB(AADOCon: TADOConnection);
var
ADOCmd : TADOCommand;
begin
try
ADOCmd := TADOCommand.Create(nil);
ADOCmd.Connection := AADOCon;
ADOCmd.Prepared := True;
with ADOCmd do
begin
CommandText :='UPDATE TBL_DICT SET'
+ ' DICT_CODE = :DICT_CODE,'
+ ' DICT_NAME = :DICT_NAME,'
+ ' DICT_VALU = :DICT_VALU'
+ ' WHERE DICT_IDEX = :DICT_IDEX';
with Parameters do
begin
ParamByName('DICT_IDEX').Value := DICTIDEX;
ParamByName('DICT_CODE').Value := DICTCODE;
ParamByName('DICT_NAME').Value := DICTNAME;
ParamByName('DICT_VALU').Value := DICTVALU;
end;
Execute;
end;
finally
FreeAndNil(ADOCmd)
end;
end;
procedure TDict.UpdateDB;
var
ADOCon:TADOConnection;
begin
try
ADOCon:=TDBPool.GetConnect();
UpdateDB(ADOCon);
finally
FreeAndNil(ADOCon);
end;
end;
end.
|
unit UnitDebugScriptForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Grids, ValEdit, uStringUtils;
type
TDebugScriptForm = class(TForm)
ListBox1: TListBox;
Panel1: TPanel;
Button1: TButton;
Button2: TButton;
Button3: TButton;
Panel2: TPanel;
Panel3: TPanel;
Timer: TTimer;
ValueListEditor1: TStringGrid;
Splitter1: TSplitter;
Panel4: TPanel;
Button4: TButton;
procedure ListBox1DrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Button1Click(Sender: TObject);
procedure TimerTimer(Sender: TObject);
procedure ValueListEditor1DblClick(Sender: TObject);
procedure Panel2Resize(Sender: TObject);
procedure ValueListEditor1SelectCell(Sender: TObject; ACol,
ARow: Integer; var CanSelect: Boolean);
procedure ValueListEditor1SetEditText(Sender: TObject; ACol,
ARow: Integer; const Value: String);
procedure FormDestroy(Sender: TObject);
private
ActiveLine : integer;
fWaiting : boolean;
fCanClose : boolean;
p : Pointer;
{ Private declarations }
public
anil : boolean;
procedure LoadScript(aScript : string);
procedure SetActiveLine(Line : integer);
Procedure SetScript(ap : pointer);
procedure Wait;
procedure Stop;
Function Working : boolean;
Function Waitind : boolean;
{ Public declarations }
end;
implementation
uses uScript, UnitScripts;
{$R *.dfm}
procedure TDebugScriptForm.ListBox1DrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
begin
if ActiveLine=Index+1 then
begin
ListBox1.Canvas.Pen.Color:=ClRed;
ListBox1.Canvas.Brush.Color:=ClRed;
ListBox1.Canvas.Rectangle(Rect);
ListBox1.Canvas.TextOut(Rect.Left,Rect.Top,ListBox1.Items[index]);
ListBox1.Canvas.Font.Color:=ClWhite;
end else
begin
ListBox1.Canvas.Brush.Color:=ClWhite;
ListBox1.Canvas.Pen.Color:=ClWhite;
ListBox1.Canvas.Rectangle(Rect);
ListBox1.Canvas.TextOut(Rect.Left,Rect.Top,ListBox1.Items[index]);
ListBox1.Canvas.Font.Color:=ClBlack;
end;
end;
procedure TDebugScriptForm.LoadScript(aScript: string);
var
p, oldp : integer;
sub : string;
begin
oldp:=1;
repeat
p:=PosExS(';',aScript,oldp);
sub:=Copy(aScript,oldp,p-oldp+1);
ListBox1.Items.Add(sub);
oldp:=p+1;
until p=0;
// ListBox1.Items.Text:=aScript;
end;
procedure TDebugScriptForm.SetActiveLine(Line: integer);
begin
ActiveLine:=Line;
ListBox1.Refresh;
end;
procedure TDebugScriptForm.Wait;
var
Variable, Val : string;
i : integer;
begin
for i:=1 to ValueListEditor1.RowCount do
begin
Variable:=ValueListEditor1.Cells[0,i];
if Variable<>'' then
begin
Val:=VarValue(TScript(p),Variable);
ValueListEditor1.Cells[1,i]:=Val;
end;
end;
fCanClose:=false;
fWaiting:=true;
Repeat
Application.ProcessMessages;
until not fWaiting;
fCanClose:=true;
end;
procedure TDebugScriptForm.FormCreate(Sender: TObject);
begin
anil:=false;
fWaiting:=false;
fCanClose:=true;
ValueListEditor1.Cells[0,0]:='Variable';
ValueListEditor1.Cells[1,0]:='Value';
end;
procedure TDebugScriptForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
fWaiting:=false;
Timer.Enabled:=true;
// Repeat
// Application.ProcessMessages;
// until fCanClose;
end;
procedure TDebugScriptForm.Button1Click(Sender: TObject);
begin
fWaiting:=false;
Timer.Enabled:=true;
{ Repeat
Application.ProcessMessages;
until fCanClose; }
end;
procedure TDebugScriptForm.Stop;
begin
fWaiting:=false;
Timer.Enabled:=true;
{ Repeat
Application.ProcessMessages;
until fCanClose; }
end;
function TDebugScriptForm.Working: boolean;
begin
Result:=not fCanClose;
end;
procedure TDebugScriptForm.TimerTimer(Sender: TObject);
begin
if fCanClose then
begin
Timer.Enabled:=false;
fCanClose:=false;
anil:=true;
Release;
Free;
end;
end;
procedure TDebugScriptForm.ValueListEditor1DblClick(Sender: TObject);
var
p : TPoint;
c,r : integer;
begin
// ValueListEditor1.EditorMode:=true;
GetCursorPos(p);
p:=ValueListEditor1.ScreenToClient(p);
ValueListEditor1.MouseToCell(p.x,p.y,c,r);
if (c<0) or (r<0) then
begin
ValueListEditor1.RowCount:= ValueListEditor1.RowCount+1;
end;
end;
procedure TDebugScriptForm.Panel2Resize(Sender: TObject);
begin
ValueListEditor1.ColWidths[0]:=Panel2.Width div 2-5;
ValueListEditor1.ColWidths[1]:=Panel2.Width div 2-5;
end;
procedure TDebugScriptForm.ValueListEditor1SelectCell(Sender: TObject;
ACol, ARow: Integer; var CanSelect: Boolean);
begin
if (ACol=1) then CanSelect:=false;
end;
procedure TDebugScriptForm.ValueListEditor1SetEditText(Sender: TObject;
ACol, ARow: Integer; const Value: String);
var
Variable, Val : string;
begin
Variable:=ValueListEditor1.Cells[ACol,ARow];
Val:=VarValue(TScript(p^),Variable);
ValueListEditor1.Cells[ACol+1,ARow]:=Val;
//
end;
procedure TDebugScriptForm.SetScript(ap: pointer);
begin
p:=ap;
end;
function TDebugScriptForm.Waitind: boolean;
begin
Result:=fWaiting;
end;
procedure TDebugScriptForm.FormDestroy(Sender: TObject);
begin
anil:=false;
end;
end.
|
unit TerminologyServer;
interface
uses
SysUtils, Classes, IniFiles,
AdvObjects, AdvStringObjectMatches, AdvStringLists,
KDBManager, KDBOdbcExpress,
FHIRTypes, FHIRComponents, FHIRResources, FHIRUtilities,
TerminologyServices, SnomedServices, LoincServices, UcumServices, RxNormServices,
FHIRValueSetChecker,
TerminologyServerStore;
Type
TTerminologyServer = class (TTerminologyServerStore)
private
FExpansions : TAdvStringObjectMatch;
FDependencies : TAdvStringObjectMatch; // object is TAdvStringList of identity
procedure AddDependency(name, value : String);
function getCodeDefinition(c : TFHIRValueSetDefineConcept; code : string) : TFHIRValueSetDefineConcept; overload;
function getCodeDefinition(vs : TFHIRValueSet; code : string) : TFHIRValueSetDefineConcept; overload;
protected
procedure invalidateVS(id : String); override;
public
constructor Create;
Destructor Destroy;
function Link: TTerminologyServer; overload;
// load external terminology resources (snomed, Loinc)
procedure load(ini : TIniFile; db : TKDBManager);
// functional services
// if this id identifies a value set known to the external resources (if it does, construct it and return it)
function isKnownValueSet(id : String; out vs : TFHIRValueSet): Boolean;
// given a value set, expand it
function expandVS(vs : TFHIRValueSet; cacheId : String; textFilter : String) : TFHIRValueSet; overload;
function expandVS(uri : String; textFilter : String) : TFHIRValueSet; overload;
// these are internal services - not for use outside the terminology server
function expandVS(uri: String; textFilter : String; dependencies : TStringList) : TFHIRValueSet; overload;
function expandVS(vs: TFHIRValueSet; cacheId : String; textFilter : String; dependencies : TStringList): TFHIRValueSet; overload;
function validate(vs : TFHIRValueSet; coding : TFhirCoding) : TFhirOperationOutcome; overload;
function validate(vs : TFHIRValueSet; coded : TFhirCodeableConcept) : TFhirOperationOutcome; overload;
function translate(vs : TFHIRValueSet; coding : TFhirCoding; dest : String) : TFhirOperationOutcome; overload;
Function MakeChecker(uri : string) : TValueSetChecker;
function getDisplayForCode(system, code : String): String;
function checkCode(op : TFhirOperationOutcome; path : string; code : string; system : string; display : string) : boolean;
end;
implementation
uses
FHIRValueSetExpander;
{ TTerminologyServer }
constructor TTerminologyServer.Create;
begin
inherited;
FExpansions := TAdvStringObjectMatch.create;
FExpansions.PreventDuplicates;
FDependencies := TAdvStringObjectMatch.create;
FDependencies.PreventDuplicates;
end;
destructor TTerminologyServer.Destroy;
begin
FDependencies.Free;
FExpansions.free;
inherited;
end;
procedure TTerminologyServer.load(ini : TIniFile; db : TKDBManager);
var
fn : string;
begin
if ini.ReadString('RxNorm', 'database', '') <> '' then
begin
write('Connect to RxNorm');
RxNorm := TRxNormServices.Create(TKDBOdbcDirect.create('rxnorm', 100, 'SQL Server Native Client 11.0',
Ini.ReadString('database', 'server', ''), Ini.ReadString('RxNorm', 'database', ''),
Ini.ReadString('database', 'username', ''), Ini.ReadString('database', 'password', '')));
end;
fn := ini.ReadString('snomed', 'cache', '');
if fn <> '' then
begin
write('Load Snomed from '+fn);
Snomed := TSnomedServices.Create;
Snomed.Load(fn);
writeln(' - done');
end;
fn := ini.ReadString('loinc', 'cache', '');
if fn <> '' then
begin
write('Load Loinc from '+fn);
Loinc := TLoincServices.Create;
Loinc.Load(fn);
writeln(' - done');
end;
fn := ini.ReadString('ucum', 'source', '');
if fn <> '' then
begin
write('Load Ucum from '+fn);
Ucum := TUcumServices.Create;
Ucum.Import(fn);
writeln(' - done');
end;
end;
function TTerminologyServer.Link: TTerminologyServer;
begin
result := TTerminologyServer(inherited Link);
end;
procedure TTerminologyServer.AddDependency(name, value : String);
var
ts : TAdvStringList;
begin
// must be in lock
if FDependencies.ExistsByKey(name) then
ts := FDependencies.GetValueByKey(name) as TAdvStringList
else
begin
ts := TAdvStringList.Create;
FDependencies.Add(name, ts);
end;
if not ts.ExistsByValue(value) then
ts.Add(value);
end;
procedure TTerminologyServer.invalidateVS(id: String);
var
ts : TAdvStringList;
i : integer;
begin
// must be in lock
if FDependencies.ExistsByKey(id) then
begin
ts := FDependencies.GetValueByKey(id) as TAdvStringList;
for i := 0 to ts.Count - 1 do
if FExpansions.ExistsByKey(ts[i]) then
FExpansions.DeleteByKey(ts[i]);
FDependencies.DeleteByKey(id);
end;
for i := FExpansions.Count - 1 downto 0 do
if FExpansions.KeyByIndex[i].StartsWith(id+#1) then
FExpansions.DeleteByIndex(i);
end;
function TTerminologyServer.expandVS(vs: TFHIRValueSet; cacheId : String; textFilter : String): TFHIRValueSet;
var
ts : TStringList;
begin
ts := TStringList.create;
try
result := expandVS(vs, cacheId, textFilter, ts);
finally
ts.free;
end;
end;
function TTerminologyServer.expandVS(vs: TFHIRValueSet; cacheId : String; textFilter : String; dependencies : TStringList): TFHIRValueSet;
var
s : String;
exp : TFHIRValueSetExpander;
begin
result := nil;
if cacheId <> '' then
begin
FLock.Lock('expandVS.1');
try
if FExpansions.ExistsByKey(cacheId+#1+textFilter) then
result := (FExpansions.matches[cacheId+#1+textFilter] as TFhirValueSet).link;
finally
FLock.Unlock;
end;
end;
if result = nil then
begin
exp := TFHIRValueSetExpander.create(self.Link);
try
result := exp.expand(vs, textFilter, dependencies);
if (dependencies.Count > 0) and (cacheId <> '') then
begin
FLock.Lock('expandVS.2');
try
FExpansions.Add(cacheId+#1+textFilter, result.Link);
// in addition, we trace the dependencies so we can expire the cache
for s in dependencies do
AddDependency(s, cacheId);
finally
FLock.Unlock;
end;
end;
finally
exp.Free;
end;
end;
end;
function TTerminologyServer.expandVS(uri: String; textFilter : String): TFHIRValueSet;
var
vs : TFHIRValueSet;
ts : TStringList;
begin
ts := TStringList.create;
try
vs := getValueSetByUrl(uri);
try
result := expandVS(vs, uri, textFilter, ts);
finally
vs.Free;
end;
finally
ts.Free;
end;
end;
function TTerminologyServer.expandVS(uri: String; textFilter : String; dependencies: TStringList): TFHIRValueSet;
var
vs : TFHIRValueSet;
begin
vs := getValueSetByUrl(uri);
try
if vs = nil then
raise Exception.Create('Unable to find value set "'+uri+'"');
result := expandVS(vs, uri, textFilter);
finally
vs.Free;
end;
end;
function TTerminologyServer.isKnownValueSet(id: String; out vs: TFHIRValueSet): Boolean;
begin
vs := nil;
if id.StartsWith('http://snomed.info/') then
vs := Snomed.buildValueSet(id)
else if id.StartsWith('http://loinc.org/vs/LP') then
vs := Loinc.buildValueSet(id);
result := vs <> nil;
end;
function TTerminologyServer.MakeChecker(uri: string): TValueSetChecker;
var
vs : TFhirValueSet;
begin
result := TValueSetChecker.create(self.Link, uri);
try
vs := getValueSetByUrl(uri);
try
result.prepare(vs);
finally
vs.Free;
end;
result.Link;
finally
result.Free;
end;
end;
function TTerminologyServer.validate(vs : TFHIRValueSet; coding : TFhirCoding) : TFhirOperationOutcome;
var
check : TValueSetChecker;
begin
check := TValueSetChecker.create(self.Link, vs.identifierST);
try
check.prepare(vs);
result := check.check(coding);
finally
check.Free;
end;
end;
function TTerminologyServer.validate(vs : TFHIRValueSet; coded : TFhirCodeableConcept) : TFhirOperationOutcome;
var
check : TValueSetChecker;
begin
check := TValueSetChecker.create(self.Link, vs.identifierST);
try
check.prepare(vs);
result := check.check(coded);
finally
check.Free;
end;
end;
function TTerminologyServer.checkCode(op : TFhirOperationOutcome; path : string; code : string; system : string; display : string) : boolean;
var
vs : TFhirValueSet;
def : TFhirValueSetDefineConcept;
d : String;
begin
result := false;
if system.StartsWith('http://hl7.org/fhir') then
begin
if (system = 'http://hl7.org/fhir/sid/icd-10') then
result := true// nothing for now....
else
begin
vs := getCodeSystem(system);
if op.warning('InstanceValidator', 'code-unknown', path, vs <> nil, 'Unknown Code System '+system) then
begin
def := getCodeDefinition(vs, code);
if (op.warning('InstanceValidator', 'code-unknown', path, def <> nil, 'Unknown Code ('+system+'#'+code+')')) then
result := op.warning('InstanceValidator', 'code-unknown', path, (display = '') or (display = def.DisplayST), 'Display for '+system+' code "'+code+'" should be "'+def.DisplayST+'"');
end;
end;
end
else if system.StartsWith('http://snomed.info/sct') and (Snomed <> nil) then
begin
if op.warning('InstanceValidator', 'code-unknown', path, Snomed.IsValidConcept(code), 'The SNOMED-CT term "'+code+'" is unknown') then
begin
d := Snomed.GetDisplayName(code, '');
result := op.warning('InstanceValidator', 'code-unknown', path, (display = '') or (display = d), 'Display for SNOMED-CT term "'+code+'" should be "'+d+'"');
end;
end
else if system.StartsWith('http://loinc.org') and (Loinc <> nil) then
begin
d := Loinc.GetDisplayByName(code);
if op.warning('InstanceValidator', 'code-unknown', path, d <> '', 'The LOINC code "'+code+'" is unknown') then
result := op.warning('InstanceValidator', 'code-unknown', path, (display = '') or (display = d), 'Display for Loinc Code "'+code+'" should be "'+d+'"');
end
else if system.StartsWith('http://unitsofmeasure.org') and (Ucum <> nil) then
begin
d := Ucum.validate(code);
result := op.warning('InstanceValidator', 'code-unknown', path, d = '', 'The UCUM code "'+code+'" is not valid: '+d);
// we don't make rules about display for UCUM.
end
else
result := true;
end;
function TTerminologyServer.getCodeDefinition(c : TFHIRValueSetDefineConcept; code : string) : TFHIRValueSetDefineConcept;
var
i : integer;
g : TFHIRValueSetDefineConcept;
r : TFHIRValueSetDefineConcept;
begin
result := nil;
if (code = c.CodeST) then
result := c;
for i := 0 to c.conceptList.Count - 1 do
begin
g := c.conceptList[i];
r := getCodeDefinition(g, code);
if (r <> nil) then
begin
result := r;
exit;
end;
end;
end;
function TTerminologyServer.getCodeDefinition(vs : TFHIRValueSet; code : string) : TFHIRValueSetDefineConcept;
var
i : integer;
c : TFHIRValueSetDefineConcept;
r : TFHIRValueSetDefineConcept;
begin
result := nil;
for i := 0 to vs.define.conceptList.Count - 1 do
begin
c := vs.define.conceptList[i];
r := getCodeDefinition(c, code);
if (r <> nil) then
begin
result := r;
exit;
end;
end;
end;
function TTerminologyServer.getDisplayForCode(system, code: String): String;
var
provider : TCodeSystemProvider;
begin
provider := getProvider(system, true);
if provider <> nil then
try
result := provider.getDisplay(code);
finally
provider.Free;
end;
end;
function TTerminologyServer.translate(vs: TFHIRValueSet; coding: TFhirCoding; dest : String): TFhirOperationOutcome;
var
isCs, ok: boolean;
i, j : integer;
cm : TLoadedConceptMap;
cc : TFhirCodeableConcept;
c : TFHIRCoding;
maps : TFhirConceptMapConceptMapList;
map : TFhirConceptMapConceptMap;
begin
result := TFhirOperationOutcome.Create;
try
if checkCode(result, '', coding.codeST, coding.systemST, coding.displayST) then
begin
cc := TFhirCodeableConcept.Create;
try
cc.codingList.Add(coding.Link);
isCs := HasCodeSystem(dest);
ok := false;
// iterate the concept maps
// a concept map is a match if there is a translation from source to dest
FLock.Lock('translate');
try
for i := 0 to FConceptMaps.count - 1 do
begin
cm := FConceptMaps.values[i] as TLoadedConceptMap;
if (cm.source <> nil) and (cm.source.identifierST = vs.identifierST) and
cm.hasTranslation(coding.systemST, coding.codeST, maps) then
try
for j := 0 to maps.Count - 1 do
begin
map := maps[j];
if (map.equivalenceST in [ConceptEquivalenceEqual, ConceptEquivalenceEquivalent, ConceptEquivalenceWider, ConceptEquivalenceInexact]) and
(not isCs {if we'rea value set mapping, we'll just run with all the maps) } or (map.{$IFDEF FHIR-DSTU}systemST{$ELSE}codeSystemST{$ENDIF} = dest)) then
begin
ok := true;
c := cc.codingList.Append;
c.system := map.{$IFDEF FHIR-DSTU}system{$ELSE}codeSystem{$ENDIF}.Clone;
c.code := map.code.Clone;
c.displayST := getDisplayForCode(map.{$IFDEF FHIR-DSTU}systemST{$ELSE}codeSystemST{$ENDIF}, map.codeST);
if map.commentsST <> '' then
result.hint('terminology-server', 'mapping', '', false, 'Mapping from "'+coding.systemST+'"/"'+coding.codeST+'" to "'+c.systemST+'"/"'+c.codeST+'": '+map.commentsST)
end;
end;
finally
maps.free;
end;
end;
result.error('terminology-server', 'mapping', '', ok, 'No Mapping found');
finally
FLock.Unlock;
end;
if ok then
result.AddExtension('http://hl7.org/fhir/Profile/general-extensions#translation', cc.Link);
finally
cc.free;
end;
end;
result.Link;
finally
result.Free;
end;
end;
(*
function TTerminologyServer.checkCode(op: TFhirOperationOutcome; path, code, system, display: string; context: TFHIRProfileStructureElement): boolean;
begin
{
function getValueSet(system : string) : TFHIRValueSet;
}
end;
procedure TTerminologyServer.DropTerminologyResource(key: Integer; aType : TFhirResourceType);
begin
end;
function TTerminologyServer.expandVS(vs: TFHIRValueSet): TFHIRValueSet;
begin
end;
function TTerminologyServer.isKnownValueSet(id: String;
out vs: TFHIRValueSet): Boolean;
begin
end;
procedure TTerminologyServer.load(ini: TIniFile);
begin
end;
procedure TTerminologyServer.SeeSpecificationResource(resource: TFHIRResource);
begin
end;
procedure TTerminologyServer.SeeTerminologyResource(key: Integer;
resource: TFHIRResource);
begin
end;
function TTerminologyServer.translate(vs: TFHIRValueSet;
coding: TFhirCoding): TFhirOperationOutcome;
begin
end;
function TTerminologyServer.validate(vs: TFHIRValueSet;
coding: TFhirCoding): TFhirOperationOutcome;
begin
end;
function TTerminologyServer.validate(vs: TFHIRValueSet;
coded: TFhirCodeableConcept): TFhirOperationOutcome;
begin
end;
function TTerminologyServer.MakeChecker(uri: string): TValueSetChecker;
begin
{
function TTerminologyServer.findValueSet(uri: string): TFhirValueSet;
begin
// result := FValuesets.matches[TFHIRUri(ref).value] as TFHIRValueSet
end;
if Fchecks.ExistsByKey(vs.identifierST) then
result := FChecks.matches[vs.identifierST] as TValueSetChecker
else
begin
end;}
end;
end.
function TFHIRDataStore.translate(vs: TFHIRValueSet; coding: TFhirCoding): TFhirOperationOutcome;
var
cm : TFhirConceptMap;
s : String;
begin
s.Substring()
result := TFhirOperationOutcome.Create;
try
cm := FindConceptMap(vs, coding.systemST);
try
if cm = nil then
rule(
finally
cm.Free;
end;
result.link;
finally
result.Free;
end;
cm := T
// is there a valueset?
// is there a concept map for the value set
// else
// is there a concept map for the code system
end;
function TFHIRDataStore.validate(vs: TFHIRValueSet; coding: TFhirCoding): TFhirOperationOutcome;
var
check : TValueSetChecker;
begin
check := TValueSetChecker.create;
try
FLock.Lock('validate');
try
check.ValueSets := FValuesetExpander.ValueSets.Link;
check.CodeSystems := FValuesetExpander.CodeSystems.Link;
check.prepare(vs);
result := check.check(coding);
finally
FLock.Unlock;
end;
finally
check.Free;
end;
end;
function TFHIRDataStore.validate(vs: TFHIRValueSet; coded: TFhirCodeableConcept): TFhirOperationOutcome;
var
check : TValueSetChecker;
begin
check := TValueSetChecker.create;
try
FLock.Lock('validate');
try
check.ValueSets := FValuesetExpander.ValueSets.Link;
check.CodeSystems := FValuesetExpander.CodeSystems.Link;
check.prepare(vs);
result := check.check(coded);
finally
FLock.Unlock;
end;
finally
result.Free;
end;
end;
procedure TFHIRDataStore.DelistValueSet(key: Integer);
var
vs : TFHIRValueSet;
begin
FLock.Lock('DelistValueSet');
try
if FValueSetTracker.ExistsByKey(inttostr(key)) then
begin
vs := FValueSetTracker.Matches[inttostr(key)] as TFhirValueSet;
if (vs.define <> nil) then
FValuesetExpander.CodeSystems.DeleteByKey(vs.define.systemST);
if (vs.identifierST <> '') then
FValuesetExpander.ValueSets.DeleteByKey(vs.identifierST);
FValueSetTracker.DeleteByKey(inttostr(key));
end;
finally
FLock.Unlock;
end;
end;
procedure TFHIRDataStore.DelistConceptMap(key: Integer);
var
vs : TFHIRConceptMap;
begin
FLock.Lock('DelistConceptMap');
try
if FConceptMapTracker.ExistsByKey(inttostr(key)) then
begin
vs := FConceptMapTracker.Matches[inttostr(key)] as TFhirConceptMap;
FConceptMapTracker.DeleteByKey(inttostr(key));
end;
finally
FLock.Unlock;
end;
end;
begin
vs := resource as TFHIRValueSet;
FValueSetTracker.add(inttostr(key), vs.link);
if (vs.define <> nil) then
FValuesetExpander.CodeSystems.add(vs.define.systemST, vs.link);
if (vs.identifierST <> '') then
FValuesetExpander.ValueSets.add(vs.identifierST, vs.link);
end
else if resource.ResourceType = frtConceptMap then
begin
cm := resource as TFhirConceptMap;
FConceptMapTracker.add(inttostr(key), cm.link);
end
if (aType = frtValueSet) and (FValueSetTracker.ExistsByKey(inttostr(key))) then
begin
vs := FValueSetTracker.Matches[inttostr(key)] as TFHIRValueSet;
if (vs.define <> nil) then
FValuesetExpander.CodeSystems.DeleteByKey(vs.define.systemST);
if (vs.identifierST <> '') then
FValuesetExpander.ValueSets.DeleteByKey(vs.identifierST);
FValueSetTracker.DeleteByKey(inttostr(key));
end
else if (aType = frtConceptMap) and (FValueSetTracker.ExistsByKey(inttostr(key))) then
begin
cm := FConceptMapTracker.Matches[inttostr(key)] as TFHIRConceptMap;
FValueSetTracker.DeleteByKey(inttostr(key));
end
procedure DelistValueSet(key : Integer);
procedure DelistConceptMap(key : Integer);
if request.ResourceType = frtValueSet then
FRepository.DelistValueSet(ResourceKey);
if request.ResourceType = frtConceptMap then
FRepository.DelistConceptMap(ResourceKey);
function TFHIRValidator.getValueSet(system : string) : TFHIRValueSet;
begin
if FCodeSystems.ExistsByKey(system) then
result := FCodeSystems.matches[system] as TFHIRValueSet
else
result := nil;
end;
begin
vs := r as TFhirValueSet;
FValuesets.add(vs.IdentifierST, vs.link);
if (vs.Define <> nil) then
FCodesystems.add(vs.Define.SystemST, vs.link);
end;
*)
end.
|
unit uProducts;
interface
Type
TProducts = class
private
Fcode: string;
Fid: integer;
Fdescr: string;
Fquantity: double;
Ftax: double;
Flist_price: double;
procedure Setcode(const Value: string);
procedure Setdescr(const Value: string);
procedure Setid(const Value: integer);
procedure Setlist_price(const Value: double);
procedure Setquantity(const Value: double);
procedure Settax(const Value: double);
published
property id : integer read Fid write Setid;
property code : string read Fcode write Setcode;
property descr : string read Fdescr write Setdescr;
property list_price : double read Flist_price write Setlist_price;
property tax : double read Ftax write Settax;
property quantity : double read Fquantity write Setquantity;
end;
implementation
{ TProducts }
procedure TProducts.Setcode(const Value: string);
begin
Fcode := Value;
end;
procedure TProducts.Setdescr(const Value: string);
begin
Fdescr := Value;
end;
procedure TProducts.Setid(const Value: integer);
begin
Fid := Value;
end;
procedure TProducts.Setlist_price(const Value: double);
begin
Flist_price := Value;
end;
procedure TProducts.Setquantity(const Value: double);
begin
Fquantity := Value;
end;
procedure TProducts.Settax(const Value: double);
begin
Ftax := Value;
end;
end.
|
program Sorting;
VAR
elements : array of integer;
TYPE
{ Type of the element array. }
IntegerArray = ARRAY OF Integer;
{ Function pointer: http://www.gnu-pascal.de/gpc/Pointer-Types.html }
ProcPtr = function(left, right : integer): integer;
FUNCTION compareTo(VAR left, right : integer) : integer;
BEGIN
if left < right then
begin
compareTo := -1;
end
else if left > right then
begin
compareTo := 1;
end
else
begin
compareTo := 0;
end
END;
PROCEDURE swap(VAR a, b: integer);
VAR
t: integer;
BEGIN
t := a;
a := b;
b := t;
END;
PROCEDURE Quicksort(VAR arr : IntegerArray; left : integer; right : integer; sort_function : ProcPtr);
var
pivot : integer;
leftIdx : integer;
rightIdx : integer;
begin
Randomize;
if (right - left) > 0 then
begin
{ Random number between left and right }
pivot := arr[Random(right - left) + left];
leftIdx := left;
rightIdx := right;
while leftIdx < rightIdx do
begin
//while arr[leftIdx] < pivot do
while sort_function^(arr[leftIdx], pivot) < 0 do
begin
leftIdx := leftIdx + 1;
end;
//while arr[rightIdx] > pivot do
while sort_function^(arr[rightIdx], pivot) > 0 do
begin
rightIdx := rightIdx - 1;
end;
Swap(arr[leftIdx], arr[rightIdx]);
end;
if left < rightIdx then
Quicksort(arr, left, rightIdx - 1);
if leftIdx < right then
Quicksort(arr, leftIdx + 1, right);
end;
end;
begin
elements[0] := 2;
elements[1] := 9;
elements[2] := 1;
elements[3] := 5;
Quicksort(elements, 0, 3, @compareTo);
end. |
unit TpWebVariable;
interface
uses
SysUtils, Classes,
Db, AdoDb,
ThHtmlDocument, ThHeaderComponent, ThTag,
TpControls, TpForm;
type
TTpWebVariable = class(TThHeaderComponent)
private
FDefaultValue: string;
FForm: TTpForm;
protected
procedure SetDefaultValue(const Value: string);
procedure SetForm(const Value: TTpForm);
protected
procedure Tag(inTag: TThTag); override;
procedure UnassignComponent(AComponent: TComponent); override;
published
property DefaultValue: string read FDefaultValue write SetDefaultValue;
property Form: TTpForm read FForm write SetForm;
end;
implementation
procedure TTpWebVariable.SetDefaultValue(const Value: string);
begin
FDefaultValue := Value;
end;
procedure TTpWebVariable.SetForm(const Value: TTpForm);
begin
ChangeComponentProp(TComponent(FForm), Value);
end;
procedure TTpWebVariable.UnassignComponent(AComponent: TComponent);
begin
if AComponent = Form then
FForm := nil;
end;
procedure TTpWebVariable.Tag(inTag: TThTag);
begin
with inTag do
begin
Add(tpClass, 'TTpWebVar');
Add('tpName', Name);
Add('tpValue', DefaultValue);
if Assigned(Form) then
Add('tpForm', Form.Name);
end;
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, ShellAPI, Menus, StdCtrls;
type
TForm1 = class(TForm)
Timer1: TTimer;
Label1: TLabel;
procedure Timer1Timer(Sender: TObject);
procedure FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
function ExecAndWait(const FileName, Params: ShortString; const WinState: Word): boolean; export;
var
StartInfo: TStartupInfo;
ProcInfo: TProcessInformation;
CmdLine: ShortString;
begin
{ Помещаем имя файла между кавычками, с соблюдением всех пробелов в именах Win9x }
CmdLine := '"' + Filename + '" ' + Params;
FillChar(StartInfo, SizeOf(StartInfo), #0);
with StartInfo do
begin
cb := SizeOf(StartInfo);
dwFlags := STARTF_USESHOWWINDOW;
wShowWindow := WinState;
end;
Result := CreateProcess(nil, PChar( String( CmdLine ) ), nil, nil, false,
CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS, nil,
PChar(ExtractFilePath(Filename)),StartInfo,ProcInfo);
{ Ожидаем завершения приложения }
if Result then
begin
WaitForSingleObject(ProcInfo.hProcess, INFINITE);
{ Free the Handles }
CloseHandle(ProcInfo.hProcess);
CloseHandle(ProcInfo.hThread);
end;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
var t:TDateTime;
myYear, myMonth, myDay, myHour, myMin, mySec, myMilli : Word;
txtfile:string;
begin
ShowWindow(Application.Handle, sw_Hide);
t:=Now();
label1.Caption:=DateTimeToStr(t);
Form1.Height:=label1.Top+label1.Height+50;
Form1.Width:=label1.Left+label1.Width+50;
DecodeTime(t, myHour, myMin, mySec, myMilli);
DecodeDate(t, myYear, myMonth, myDay);
if myHour=1 then
begin
txtfile:='E:\Backup82\Fran\Fran_'+inttostr(myYear)+'{.}';
if myMonth<10 then txtfile:=txtfile+'0'+inttostr(myMonth)+'{.}'
else txtfile:=txtfile+inttostr(myMonth)+'{.}';
if myDay<10 then txtfile:=txtfile+'0'+inttostr(myDay)+'.zip'
else txtfile:=txtfile+inttostr(myDay)+'.zip';
if NOT FileExists(txtfile) then
ExecAndWait( 'D:\backupFran.bat', '', SW_SHOWNORMAL);
txtfile:='E:\Backup82\Work\Work_'+inttostr(myYear)+'{.}';
if myMonth<10 then txtfile:=txtfile+'0'+inttostr(myMonth)+'{.}'
else txtfile:=txtfile+inttostr(myMonth)+'{.}';
if myDay<10 then txtfile:=txtfile+'0'+inttostr(myDay)+'.zip'
else txtfile:=txtfile+inttostr(myDay)+'.zip';
if NOT FileExists(txtfile) then
ExecAndWait( 'D:\backupWork.bat', '', SW_SHOWNORMAL);
end;
end;
procedure TForm1.FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if Form1.BorderStyle=bsNone then
Form1.BorderStyle:=bsDialog
else Form1.BorderStyle:=bsNone;
end;
end.
|
unit Main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,Ini, StdCtrls, ExtCtrls,SPComm,Box,Clipbrd,StrUtils;
const
Colors : array [0.. 8] of Integer = (
clBtnFace,clRed,clFuchsia,clLime,clYellow,clTeal,clSilver,clWhite,clOlive
);
//* CRC 高位字节值表 */
CRCTableHi:array[0..255] of DWORD = (
$00, $C1, $81, $40,$01, $C0, $80, $41,$01, $C0, $80, $41,$00, $C1, $81, $40,
$01, $C0, $80, $41,$00, $C1, $81, $40,$00, $C1, $81, $40,$01, $C0, $80, $41,
$01, $C0, $80, $41,$00, $C1, $81, $40,$00, $C1, $81, $40,$01, $C0, $80, $41,
$00, $C1, $81, $40,$01, $C0, $80, $41,$01, $C0, $80, $41,$00, $C1, $81, $40,
$01, $C0, $80, $41,$00, $C1, $81, $40,$00, $C1, $81, $40,$01, $C0, $80, $41,
$00, $C1, $81, $40,$01, $C0, $80, $41,$01, $C0, $80, $41,$00, $C1, $81, $40,
$00, $C1, $81, $40,$01, $C0, $80, $41,$01, $C0, $80, $41,$00, $C1, $81, $40,
$01, $C0, $80, $41,$00, $C1, $81, $40,$00, $C1, $81, $40,$01, $C0, $80, $41,
$01, $C0, $80, $41,$00, $C1, $81, $40,$00, $C1, $81, $40,$01, $C0, $80, $41,
$00, $C1, $81, $40,$01, $C0, $80, $41,$01, $C0, $80, $41,$00, $C1, $81, $40,
$00, $C1, $81, $40,$01, $C0, $80, $41,$01, $C0, $80, $41,$00, $C1, $81, $40,
$01, $C0, $80, $41,$00, $C1, $81, $40,$00, $C1, $81, $40,$01, $C0, $80, $41,
$00, $C1, $81, $40,$01, $C0, $80, $41,$01, $C0, $80, $41,$00, $C1, $81, $40,
$01, $C0, $80, $41,$00, $C1, $81, $40,$00, $C1, $81, $40,$01, $C0, $80, $41,
$01, $C0, $80, $41,$00, $C1, $81, $40,$00, $C1, $81, $40,$01, $C0, $80, $41,
$00, $C1, $81, $40,$01, $C0, $80, $41,$01, $C0, $80, $41,$00, $C1, $81, $40
);
//* CRC低位字节值表*/
CRCTableLo:array[0..255] of DWORD = (
$00, $C0, $C1, $01,$C3, $03, $02, $C2,$C6, $06, $07, $C7,$05, $C5, $C4, $04,
$CC, $0C, $0D, $CD,$0F, $CF, $CE, $0E,$0A, $CA, $CB, $0B,$C9, $09, $08, $C8,
$D8, $18, $19, $D9,$1B, $DB, $DA, $1A,$1E, $DE, $DF, $1F,$DD, $1D, $1C, $DC,
$14, $D4, $D5, $15,$D7, $17, $16, $D6,$D2, $12, $13, $D3,$11, $D1, $D0, $10,
$F0, $30, $31, $F1,$33, $F3, $F2, $32,$36, $F6, $F7, $37,$F5, $35, $34, $F4,
$3C, $FC, $FD, $3D,$FF, $3F, $3E, $FE,$FA, $3A, $3B, $FB,$39, $F9, $F8, $38,
$28, $E8, $E9, $29,$EB, $2B, $2A, $EA,$EE, $2E, $2F, $EF,$2D, $ED, $EC, $2C,
$E4, $24, $25, $E5,$27, $E7, $E6, $26,$22, $E2, $E3, $23,$E1, $21, $20, $E0,
$A0, $60, $61, $A1,$63, $A3, $A2, $62,$66, $A6, $A7, $67,$A5, $65, $64, $A4,
$6C, $AC, $AD, $6D,$AF, $6F, $6E, $AE,$AA, $6A, $6B, $AB,$69, $A9, $A8, $68,
$78, $B8, $B9, $79,$BB, $7B, $7A, $BA,$BE, $7E, $7F, $BF,$7D, $BD, $BC, $7C,
$B4, $74, $75, $B5,$77, $B7, $B6, $76,$72, $B2, $B3, $73,$B1, $71, $70, $B0,
$50, $90, $91, $51,$93, $53, $52, $92,$96, $56, $57, $97,$55, $95, $94, $54,
$9C, $5C, $5D, $9D,$5F, $9F, $9E, $5E,$5A, $9A, $9B, $5B,$99, $59, $58, $98,
$88, $48, $49, $89,$4B, $8B, $8A, $4A,$4E, $8E, $8F, $4F,$8D, $4D, $4C, $8C,
$44, $84, $85, $45,$87, $47, $46, $86,$82, $42, $43, $83,$41, $81, $80, $40
);
type
TMainForm = class(TForm)
Logs: TMemo;
Panel1: TPanel;
ClearLogBtn: TButton;
LogClear: TCheckBox;
AutoChange: TCheckBox;
Timer: TTimer;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure ClearLogBtnClick(Sender: TObject);
procedure AutoChangeClick(Sender: TObject);
procedure TimerTimer(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
PointStart:Integer;
PointEnd:Integer;
Events : TStrings;
SpComm : TComm;
Comm : string;
procedure InitC;
procedure CustomReceiveData(Sender: TObject; Buffer: Pointer; BufferLength: Word);
procedure CustomReceiveErrorEvent(Sender: TObject; EventMask : DWORD);
procedure AddLog(logContent:string);
function ByteToStr(BufferArr:array of Byte):string;
procedure ComboBoxChange(Sender: TObject);
function ModBusCRC16(Data: string;var CRC16Hi,CRC16Lo:DWORD): string;
end;
var
MainForm : TMainForm;
PControl : TPControl;
implementation
{$R *.dfm}
procedure TMainForm.FormCreate(Sender: TObject);
begin
WindowState := wsMaximized;
PControl := TPControl.Create(Application);
PControl.Parent := Self;
PControl.Width := Screen.Width;
PControl.Height := Screen.Monitors[0].Height - 300;
PControl.Left := 0;
PControl.Top := 0;
InitC;
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
try
SpComm.StopComm;
except
end;
end;
procedure TMainForm.InitC;
var
HCount,SCount:Integer;
I,K,N :Integer;
GroupBox :TGroupBox;
ComboBox :TComboBox;
PCount : Integer;
begin
PointStart := StrToInt(Ini.ReadIni('server','pointStart'));
if PointStart < 1 then
begin
AddLog('最少从1开始..');
PointStart := 1;
end;
PointEnd := StrToInt(Ini.ReadIni('server','pointEnd'));
if PointEnd > 255 then
begin
AddLog('最多到255..');
PointEnd := 255;
end;
PCount := PointEnd - PointStart + 1;
Comm := Ini.ReadIni('server','com');
Events := TStringList.Create;
Events.LoadFromFile(ExtractFileDir(PARAMSTR(0)) + '\event.txt');
HCount := (PControl.Width - 20) div 138; //一行多少
SCount := (PCount + HCount - 1) div HCount; //多少行
for I := 0 to SCount - 1 do
begin
for K := 1 to HCount do
begin
N := (I * HCount) + K + PointStart - 1;
if N <= PointEnd then
begin
GroupBox := TGroupBox.Create(Self);
GroupBox.Parent := PControl;
GroupBox.Caption := InttoStr(N);
GroupBox.Width := 130;
GroupBox.Height := 50;
GroupBox.Left := 8 * K + 130 * (K - 1);
GroupBox.Top := 8 * (I + 1) + 50 * I;
GroupBox.Name := 'G' + GroupBox.Caption;
ComboBox := TComboBox.Create(Self);
ComboBox.Parent := GroupBox;
ComboBox.Items := Events;
ComboBox.ItemIndex := 0;
ComboBox.Left := 16;
ComboBox.Top := 16;
ComboBox.DropDownCount := 10;
ComboBox.Name := 'C' + GroupBox.Caption;
ComboBox.Width:= 97;
ComboBox.Style := csDropDownList;
ComboBox.OnChange := ComboBoxChange;
end;
end;
end;
SpComm := TComm.Create(Application);
SpComm.CommName := Comm;
SpComm.BaudRate := 4800;
SpComm.Parity := None;
SpComm.ByteSize := _8;
SpComm.StopBits := _1;
SpComm.OnReceiveData := CustomReceiveData;
SpComm.OnReceiveError := CustomReceiveErrorEvent;
try
SpComm.StartComm;
AddLog(Comm + '打开成功');
except
AddLog(Comm + '打开失败,不存在或被占用');
end;
end;
procedure TMainForm.CustomReceiveData(Sender: TObject; Buffer: Pointer; BufferLength: Word);
var
Str: string;
BufferArr,BufferArrSender : array of Byte;
BeginPoint,PointCount,BufferLengthSender,I,OutIndex,BeginOut,K : Integer;
ComboBox :TComboBox;
GroupBoxSrc :TControl;
StrToCrc : string;
CRC16Lo,CRC16Hi:DWORD;
begin
OutIndex := 0;
BeginOut := -1;
K := 1;
SetLength(BufferArr, BufferLength);
Move(buffer^, PChar(@BufferArr[0])^, BufferLength);
if Length(BufferArr) <> 8 then
AddLog('接受的命令长度不符 >>' + ByteToStr(BufferArr))
else if (BufferArr[1] <> $03) then
AddLog('接受的命令头不以0103开始 >>' + ByteToStr(BufferArr))
else if ModBusCRC16((IntToHex(BufferArr[0],2) + ' '+ IntToHex(BufferArr[1],2) + ' '+ IntToHex(BufferArr[2],2) + ' '+ IntToHex(BufferArr[3],2) + ' '+ IntToHex(BufferArr[4],2) + ' '+ IntToHex(BufferArr[5],2)),CRC16Lo,CRC16Hi) <> (IntToHex(BufferArr[6],2) + IntToHex(BufferArr[7],2)) then
AddLog('CRC检验错误 >>' + ByteToStr(BufferArr))
else
begin
BeginPoint := BufferArr[3];
PointCount := BufferArr[5];
if PointCount > 100 then //最多100
begin
AddLog('请求' + IntToStr(PointCount) + '个,限制100以内,改为100个');
PointCount := 100;
end;
AddLog('收到 >> ' + ByteToStr(BufferArr)+',从' + IntToStr(BeginPoint) +'开始,查询' + IntToStr(PointCount)+'个寄存器,从机:' + IntToHex(BufferArr[0],2));
BufferLengthSender := 5 + PointCount * 2;
SetLength(BufferArrSender,BufferLengthSender);
BufferArrSender[0] := BufferArr[0];
BufferArrSender[1] := $03;
for I := 1 to PointCount do
begin
BufferArrSender[K + 2] := $00;
GroupBoxSrc := PControl.FindChildControl('G' + InttoStr(BeginPoint+1));
if Assigned(GroupBoxSrc) then
begin
ComboBox := (GroupBoxSrc as TGroupBox).FindChildControl('C' + InttoStr(BeginPoint+1)) as TComboBox;
if ComboBox.ItemIndex < 4 then
BufferArrSender[K + 3] := ComboBox.ItemIndex
else
BufferArrSender[K + 3] := ComboBox.ItemIndex + 1;
end
else
begin
Dec(PointCount);
SetLength(BufferArrSender,Length(BufferArrSender) - 2);
if BeginOut = -1 then
BeginOut := BeginPoint;
Inc(OutIndex);
end;
Inc(BeginPoint);
K := K + 2;
end;
BufferArrSender[2] := PointCount * 2;
for I := 0 to Length(BufferArrSender) - 3 do
begin
StrToCrc := StrToCrc + IntToHex(BufferArrSender[I],2) + ' ';
end;
ModBusCRC16(StrToCrc,CRC16Lo,CRC16Hi);
BufferArrSender[Length(BufferArrSender)-2] := CRC16Lo;
BufferArrSender[Length(BufferArrSender)-1] := CRC16Hi;
if BeginOut <> -1 then
AddLog('从'+InttoStr(BeginOut)+'地址开始越界了' + IntToStr(OutIndex) +'个寄存器,实际返回' + IntToStr(PointCount) + '个');
// AddLog('发送 >> ' + ByteToStr(BufferArrSender));
SpComm.WriteCommData(PChar(BufferArrSender),Length(BufferArrSender));
end;
end;
procedure TMainForm.CustomReceiveErrorEvent(Sender: TObject; EventMask : DWORD);
begin
AddLog(InttoStr(EventMask));
end;
procedure TMainForm.AddLog(logContent:string);
begin
if (LogClear.Checked) and (Logs.Lines.Count >= 100) then
Logs.Lines.Clear;
Logs.Lines.Add(FormatDateTime('hh:mm:ss', now) + ' ' + logContent);
end;
procedure TMainForm.ClearLogBtnClick(Sender: TObject);
begin
Clipboard.AsText := Logs.Text;
Logs.Lines.Clear;
end;
procedure TMainForm.ComboBoxChange(Sender: TObject);
begin
((Sender as TComboBox).Parent as TGroupBox).Color := Colors[(Sender as TComboBox).ItemIndex];
end;
procedure TMainForm.AutoChangeClick(Sender: TObject);
begin
Timer.Enabled := AutoChange.Checked;
end;
function TMainForm.ByteToStr(BufferArr:array of Byte):string;
var
Str:string;
I :Integer;
begin
Str := '';
for I := 0 to Length(BufferArr) - 1 do
begin
Str := Str + IntToHex(BufferArr[I],2) + ' ';
end;
Result := Str;
end;
function TMainForm.ModBusCRC16(Data:String;var CRC16Hi,CRC16Lo:DWORD) : string;
var
uIndex,uIndex1:Integer;
Data1:String;
begin
CRC16Lo := $FF; //CRC16Lo为CRC寄存器低8位
CRC16Hi := $FF; //CRC16Hi为CRC寄存器高8位
uIndex1:=1;
Data1:=Trim(Data);
while Length(Data1)>0 do
begin
uIndex := CRC16Hi xor (StrToInt('$'+(Data1[1])+(Data1[2])));
CRC16Hi := CRC16Lo xor CRCTableHi[uIndex];
CRC16Lo := CRCTableLo[uIndex];
Data1:=Trim(MidStr(Data1,3,Length(Data1)));
end;
Result := IntToHex(CRC16Hi,2) + IntToHex(CRC16Lo,2);
end;
procedure TMainForm.TimerTimer(Sender: TObject);
var
GroupBox :TGroupBox;
ComboBox :TComboBox;
I:Integer;
begin
Randomize;
I := Random(PointEnd-PointStart) + PointStart;
GroupBox := PControl.FindChildControl('G' + InttoStr(I)) as TGroupBox;
ComboBox := GroupBox.FindChildControl('C' + InttoStr(I)) as TComboBox;
Randomize;
I := Random(8);
ComboBox.ItemIndex := I;
GroupBox.Color := Colors[I];
end;
end.
|
{***************************************************************************}
{ }
{ Spring Framework for Delphi }
{ }
{ Copyright (c) 2009-2014 Spring4D Team }
{ }
{ http://www.spring4d.org }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit Spring.Container.Registration;
{$I Spring.inc}
interface
uses
Rtti,
Spring,
Spring.Collections,
Spring.Container.Core,
Spring.Services;
type
/// <summary>
/// TComponentRegistry
/// </summary>
TComponentRegistry = class(TInterfacedObject, IComponentRegistry, IInterface)
private
fContainerContext: IContainerContext;
fRttiContext: TRttiContext;
fModels: IList<TComponentModel>;
fDefaultRegistrations: IDictionary<PTypeInfo, TComponentModel>;
fUnnamedRegistrations: IDictionary<PTypeInfo, TComponentModel>;
fServiceTypeMappings: IDictionary<PTypeInfo, IList<TComponentModel>>;
fServiceNameMappings: IDictionary<string, TComponentModel>;
protected
procedure CheckIsNonGuidInterface(serviceType: TRttiType);
procedure Validate(componentType, serviceType: PTypeInfo; var serviceName: string);
function BuildActivatorDelegate(elementTypeInfo: PTypeInfo; out componentType: TRttiType): TActivatorDelegate;
public
constructor Create(const context: IContainerContext);
destructor Destroy; override;
function RegisterComponent(componentTypeInfo: PTypeInfo): TComponentModel;
procedure RegisterService(const model: TComponentModel; serviceType: PTypeInfo); overload;
procedure RegisterService(const model: TComponentModel; serviceType: PTypeInfo; const name: string); overload;
procedure RegisterDefault(const model: TComponentModel; serviceType: PTypeInfo);
procedure UnregisterAll;
function HasService(serviceType: PTypeInfo): Boolean; overload;
function HasService(const name: string): Boolean; overload;
function HasService(serviceType: PTypeInfo; const name: string): Boolean; overload;
function HasDefault(serviceType: PTypeInfo): Boolean;
function FindOne(componentType: PTypeInfo): TComponentModel; overload;
function FindOne(const name: string): TComponentModel; overload;
function FindDefault(serviceType: PTypeInfo): TComponentModel;
function FindAll: IEnumerable<TComponentModel>; overload;
function FindAll(serviceType: PTypeInfo): IEnumerable<TComponentModel>; overload;
end;
/// <summary>
/// Internal helper class for non-generic fluent style registration of a
/// component.
/// </summary>
TRegistration = record
private
{$IFNDEF DELPHIXE_UP}
fRegistry: TComponentRegistry;
{$ELSE}
fRegistry: IComponentRegistry;
{$ENDIF}
fModel: TComponentModel;
constructor Create(const registry: IComponentRegistry; componentType: PTypeInfo);
public
function Implements(serviceType: PTypeInfo): TRegistration; overload;
function Implements(serviceType: PTypeInfo; const name: string): TRegistration; overload;
function DelegateTo(const delegate: TActivatorDelegate): TRegistration; overload;
{$REGION 'Typed Injections'}
function InjectConstructor(const parameterTypes: array of PTypeInfo): TRegistration; overload;
function InjectProperty(const propertyName: string): TRegistration; overload;
function InjectMethod(const methodName: string): TRegistration; overload;
function InjectMethod(const methodName: string; const parameterTypes: array of PTypeInfo): TRegistration; overload;
function InjectField(const fieldName: string): TRegistration; overload;
{$ENDREGION}
{$REGION 'Named/Valued Injections'}
function InjectConstructor(const arguments: array of TValue): TRegistration; overload;
function InjectProperty(const propertyName: string; const value: TValue): TRegistration; overload;
function InjectMethod(const methodName: string; const arguments: array of TValue): TRegistration; overload;
function InjectField(const fieldName: string; const value: TValue): TRegistration; overload;
{$ENDREGION}
function AsSingleton: TRegistration; overload;
function AsSingleton(refCounting: TRefCounting): TRegistration; overload;
function AsSingletonPerThread: TRegistration;
function AsTransient: TRegistration;
function AsPooled(minPoolSize, maxPoolSize: Integer): TRegistration; {$IFDEF CPUARM}experimental;{$ENDIF}
function AsDefault: TRegistration; overload;
function AsDefault(serviceType: PTypeInfo): TRegistration; overload;
end;
/// <summary>
/// Internal helper class for generic fluent style registration of a
/// component.
/// </summary>
TRegistration<T> = record
private
fRegistration: TRegistration;
constructor Create(const registry: IComponentRegistry);
public
function Implements(serviceType: PTypeInfo): TRegistration<T>; overload;
function Implements(serviceType: PTypeInfo; const name: string): TRegistration<T>; overload;
function Implements<TServiceType>: TRegistration<T>; overload;
function Implements<TServiceType>(const name: string): TRegistration<T>; overload;
function DelegateTo(const delegate: TActivatorDelegate<T>): TRegistration<T>; overload;
{$REGION 'Typed Injections'}
function InjectConstructor(const parameterTypes: array of PTypeInfo): TRegistration<T>; overload;
function InjectProperty(const propertyName: string): TRegistration<T>; overload;
function InjectMethod(const methodName: string): TRegistration<T>; overload;
function InjectMethod(const methodName: string; const parameterTypes: array of PTypeInfo): TRegistration<T>; overload;
function InjectField(const fieldName: string): TRegistration<T>; overload;
{$ENDREGION}
{$REGION 'Named/Valued Injections'}
function InjectConstructor(const arguments: array of TValue): TRegistration<T>; overload;
function InjectProperty(const propertyName: string; const value: TValue): TRegistration<T>; overload;
function InjectMethod(const methodName: string; const arguments: array of TValue): TRegistration<T>; overload;
function InjectField(const fieldName: string; const value: TValue): TRegistration<T>; overload;
{$ENDREGION}
function AsSingleton: TRegistration<T>; overload;
function AsSingleton(refCounting: TRefCounting): TRegistration<T>; overload;
function AsSingletonPerThread: TRegistration<T>;
function AsTransient: TRegistration<T>;
function AsPooled(minPoolSize, maxPoolSize: Integer): TRegistration<T>; {$IFDEF CPUARM}experimental;{$ENDIF}
function AsDefault: TRegistration<T>; overload;
function AsDefault(serviceType: PTypeInfo): TRegistration<T>; overload;
function AsDefault<TServiceType>: TRegistration<T>; overload;
end;
/// <summary>
/// Provides both generic and non-generic fluent-style registration
/// methods.
/// </summary>
/// <remarks>
/// Why both TRegistration and TRegistration(T) are defined as record and
/// their constructors are private, is to provide generic and non-generic
/// fluent-style registration with only necessary methods.
/// </remarks>
TRegistrationManager = class
private
fRegistry: IComponentRegistry;
public
constructor Create(const registry: IComponentRegistry);
function RegisterComponent<TComponentType>: TRegistration<TComponentType>; overload;
function RegisterComponent(componentType: PTypeInfo): TRegistration; overload;
end;
implementation
uses
SysUtils,
TypInfo,
Spring.Collections.Lists,
Spring.Container.ResourceStrings,
Spring.Helpers,
Spring.Reflection;
{$REGION 'TComponentRegistry'}
constructor TComponentRegistry.Create(const context: IContainerContext);
begin
Guard.CheckNotNull(context, 'context');
inherited Create;
fContainerContext := context;
fRttiContext := TRttiContext.Create;
fModels := TCollections.CreateObjectList<TComponentModel>(True);
fDefaultRegistrations := TCollections.CreateDictionary<PTypeInfo, TComponentModel>;
fUnnamedRegistrations := TCollections.CreateDictionary<PTypeInfo, TComponentModel>;
fServiceTypeMappings := TCollections.CreateDictionary<PTypeInfo, IList<TComponentModel>>;
fServiceNameMappings := TCollections.CreateDictionary<string, TComponentModel>;
end;
destructor TComponentRegistry.Destroy;
begin
fRttiContext.Free;
inherited Destroy;
end;
function TComponentRegistry.BuildActivatorDelegate(elementTypeInfo: PTypeInfo;
out componentType: TRttiType): TActivatorDelegate;
begin
case elementTypeInfo.Kind of
tkClass:
begin
componentType := fRttiContext.GetType(TypeInfo(TList<TObject>));
Result :=
function: TValue
var
list: TList<TObject>;
value: TValue;
begin
list := TList<TObject>.Create;
for value in fContainerContext.ServiceResolver.ResolveAll(elementTypeInfo) do
list.Add(value.AsObject);
Result := TValue.From<TList<TObject>>(list);
end;
end;
tkInterface:
begin
componentType := fRttiContext.GetType(TypeInfo(TList<IInterface>));
Result :=
function: TValue
var
list: TList<IInterface>;
value: TValue;
begin
list := TList<IInterface>.Create;
for value in fContainerContext.ServiceResolver.ResolveAll(elementTypeInfo) do
list.Add(value.AsInterface);
Result := TValue.From<TList<IInterface>>(list);
end;
end
else
raise ERegistrationException.CreateResFmt(@SUnsupportedType, [componentType.Name]);
end;
end;
procedure TComponentRegistry.CheckIsNonGuidInterface(serviceType: TRttiType);
begin
if serviceType.IsInterface and not serviceType.AsInterface.HasGuid
and not TType.IsDelegate(serviceType.Handle) then
begin
if serviceType.IsPublicType then
raise ERegistrationException.CreateResFmt(@SMissingGuid, [serviceType.QualifiedName])
else
raise ERegistrationException.CreateResFmt(@SMissingGuid, [serviceType.Name]);
end;
end;
procedure TComponentRegistry.Validate(componentType, serviceType: PTypeInfo;
var serviceName: string);
var
componentTypeObject: TRttiType;
serviceTypeObject: TRttiType;
begin
componentTypeObject := fRttiContext.GetType(componentType);
serviceTypeObject := fRttiContext.GetType(serviceType);
CheckIsNonGuidInterface(serviceTypeObject);
if not TType.IsAssignable(componentType, serviceType)
and not componentTypeObject.IsInterface then
begin
raise ERegistrationException.CreateResFmt(@SIncompatibleTypes, [
GetTypeName(componentType), GetTypeName(serviceType)]);
end;
if serviceName = '' then
begin
// if fUnnamedRegistrations.ContainsKey(serviceType) then
// raise ERegistrationException.CreateResFmt(@SDuplicatedUnnamedService, [
// GetTypeName(serviceType)]);
serviceName := serviceTypeObject.DefaultName + '@' + componentTypeObject.DefaultName;
end;
if HasService(serviceName) then
begin
raise ERegistrationException.CreateResFmt(@SDuplicatedName, [serviceName]);
end;
end;
procedure TComponentRegistry.UnregisterAll;
begin
fServiceNameMappings.Clear;
fServiceTypeMappings.Clear;
fDefaultRegistrations.Clear;
fModels.Clear;
end;
procedure TComponentRegistry.RegisterService(const model: TComponentModel;
serviceType: PTypeInfo);
begin
RegisterService(model, serviceType, '');
end;
procedure TComponentRegistry.RegisterService(const model: TComponentModel;
serviceType: PTypeInfo; const name: string);
var
models: IList<TComponentModel>;
serviceName: string;
begin
Guard.CheckNotNull(model, 'model');
Guard.CheckNotNull(serviceType, 'serviceType');
serviceName := name;
Validate(model.ComponentTypeInfo, serviceType, serviceName);
model.Services[serviceName] := serviceType;
if not fServiceTypeMappings.TryGetValue(serviceType, models) then
begin
models := TCollections.CreateList<TComponentModel>(False);
fServiceTypeMappings.AddOrSetValue(serviceType, models);
end;
models.Add(model);
fServiceNameMappings.Add(serviceName, model);
if name = '' then
begin
fUnnamedRegistrations.AddOrSetValue(serviceType, model);
RegisterDefault(model, serviceType);
end;
end;
procedure TComponentRegistry.RegisterDefault(const model: TComponentModel;
serviceType: PTypeInfo);
begin
if not model.HasService(serviceType) then
raise ERegistrationException.CreateResFmt(@SMissingServiceType,
[GetTypeName(serviceType)]);
fDefaultRegistrations.AddOrSetValue(serviceType, model);
end;
function TComponentRegistry.RegisterComponent(
componentTypeInfo: PTypeInfo): TComponentModel;
var
componentType: TRttiType;
elementTypeInfo: PTypeInfo;
activatorDelegate: TActivatorDelegate;
begin
Guard.CheckNotNull(componentTypeInfo, 'componentTypeInfo');
componentType := fRttiContext.GetType(componentTypeInfo);
if componentType.IsDynamicArray then
begin
elementTypeInfo := componentType.AsDynamicArray.ElementType.Handle;
activatorDelegate := BuildActivatorDelegate(elementTypeInfo, componentType);
end;
Result := TComponentModel.Create(fContainerContext, componentType);
Result.ActivatorDelegate := activatorDelegate;
if componentType.IsInterface then
RegisterService(Result, componentType.Handle);
fModels.Add(Result);
end;
function TComponentRegistry.FindOne(const name: string): TComponentModel;
begin
fServiceNameMappings.TryGetValue(name, Result);
end;
function TComponentRegistry.FindOne(componentType: PTypeInfo): TComponentModel;
begin
Guard.CheckNotNull(componentType, 'componentType');
Result := fModels.FirstOrDefault(
function(const model: TComponentModel): Boolean
begin
Result := model.ComponentTypeInfo = componentType;
end);
end;
function TComponentRegistry.FindDefault(
serviceType: PTypeInfo): TComponentModel;
var
models: IList<TComponentModel>;
begin
Guard.CheckNotNull(serviceType, 'serviceType');
if not fDefaultRegistrations.TryGetValue(serviceType, Result)
and fServiceTypeMappings.TryGetValue(serviceType, models)
and (models.Count = 1) then
begin
Result := models[0];
end;
end;
function TComponentRegistry.FindAll: IEnumerable<TComponentModel>;
begin
Result := fModels;
end;
function TComponentRegistry.FindAll(
serviceType: PTypeInfo): IEnumerable<TComponentModel>;
var
models: IList<TComponentModel>;
defaultModel: TComponentModel;
begin
Guard.CheckNotNull(serviceType, 'serviceType');
if fServiceTypeMappings.TryGetValue(serviceType, models) then
begin
fUnnamedRegistrations.TryGetValue(serviceType, defaultModel);
Result := models.Where(
function(const model: TComponentModel): Boolean
begin
Result := model <> defaultModel;
end);
end
else
begin
Result := TCollections.CreateList<TComponentModel>(False);
end;
end;
function TComponentRegistry.HasService(serviceType: PTypeInfo): Boolean;
begin
Guard.CheckNotNull(serviceType, 'serviceType');
Result := fServiceTypeMappings.ContainsKey(serviceType);
end;
function TComponentRegistry.HasService(const name: string): Boolean;
begin
Result := fServiceNameMappings.ContainsKey(name);
end;
function TComponentRegistry.HasService(serviceType: PTypeInfo;
const name: string): Boolean;
var
model: TComponentModel;
begin
Guard.CheckNotNull(serviceType, 'serviceType');
Result := fServiceNameMappings.TryGetValue(name, model) and
model.HasService(serviceType);
end;
function TComponentRegistry.HasDefault(serviceType: PTypeInfo): Boolean;
var
models: IList<TComponentModel>;
begin
Result := fDefaultRegistrations.ContainsKey(serviceType)
or (fServiceTypeMappings.TryGetValue(serviceType, models)
and (models.Count = 1));
end;
{$ENDREGION}
{$REGION 'TRegistration'}
constructor TRegistration.Create(const registry: IComponentRegistry;
componentType: PTypeInfo);
begin
Guard.CheckNotNull(registry, 'registry');
Guard.CheckNotNull(componentType, 'componentType');
{$IFNDEF DELPHIXE_UP}
fRegistry := registry as TComponentRegistry;
{$ELSE}
fRegistry := registry;
{$ENDIF}
fModel := fRegistry.RegisterComponent(componentType);
end;
function TRegistration.Implements(serviceType: PTypeInfo): TRegistration;
begin
fRegistry.RegisterService(fModel, serviceType);
Result := Self;
end;
function TRegistration.Implements(serviceType: PTypeInfo;
const name: string): TRegistration;
begin
fRegistry.RegisterService(fModel, serviceType, name);
Result := Self;
end;
function TRegistration.DelegateTo(const delegate: TActivatorDelegate): TRegistration;
begin
fModel.ActivatorDelegate := delegate;
Result := Self;
end;
function TRegistration.InjectConstructor(
const parameterTypes: array of PTypeInfo): TRegistration;
begin
fModel.InjectConstructor(parameterTypes);
Result := Self;
end;
function TRegistration.InjectProperty(
const propertyName: string): TRegistration;
begin
fModel.InjectProperty(propertyName);
Result := Self;
end;
function TRegistration.InjectMethod(const methodName: string;
const parameterTypes: array of PTypeInfo): TRegistration;
begin
fModel.InjectMethod(methodName, parameterTypes);
Result := Self;
end;
function TRegistration.InjectMethod(const methodName: string): TRegistration;
begin
fModel.InjectMethod(methodName);
Result := Self;
end;
function TRegistration.InjectField(const fieldName: string): TRegistration;
begin
fModel.InjectField(fieldName);
Result := Self;
end;
function TRegistration.InjectConstructor(
const arguments: array of TValue): TRegistration;
begin
fModel.InjectConstructor(arguments);
Result := Self;
end;
function TRegistration.InjectProperty(const propertyName: string;
const value: TValue): TRegistration;
begin
fModel.InjectProperty(propertyName, value);
Result := Self;
end;
function TRegistration.InjectMethod(const methodName: string;
const arguments: array of TValue): TRegistration;
begin
fModel.InjectMethod(methodName, arguments);
Result := Self;
end;
function TRegistration.InjectField(const fieldName: string;
const value: TValue): TRegistration;
begin
fModel.InjectField(fieldName, value);
Result := Self;
end;
function TRegistration.AsSingleton: TRegistration;
begin
Result := AsSingleton(TRefCounting.Unknown);
end;
function TRegistration.AsSingleton(refCounting: TRefCounting): TRegistration;
begin
if (refCounting = TRefCounting.True) and fModel.ComponentType.IsInstance
and not Supports(fModel.ComponentType.AsInstance.MetaclassType, IInterface) then
raise ERegistrationException.CreateResFmt(@SMissingInterface, [fModel.ComponentType.Name]);
fModel.LifetimeType := TLifetimeType.Singleton;
fModel.RefCounting := refCounting;
Result := Self;
end;
function TRegistration.AsSingletonPerThread: TRegistration;
begin
fModel.LifetimeType := TLifetimeType.SingletonPerThread;
Result := Self;
end;
function TRegistration.AsTransient: TRegistration;
begin
fModel.LifetimeType := TLifetimeType.Transient;
Result := Self;
end;
function TRegistration.AsPooled(minPoolSize, maxPoolSize: Integer): TRegistration;
begin
fModel.LifetimeType := TLifetimeType.Pooled;
fModel.MinPoolsize := minPoolSize;
fModel.MaxPoolsize := maxPoolSize;
Result := Self;
end;
function TRegistration.AsDefault: TRegistration;
var
serviceType: PTypeInfo;
begin
for serviceType in fModel.Services.Values do
fRegistry.RegisterDefault(fModel, serviceType);
Result := Self;
end;
function TRegistration.AsDefault(serviceType: PTypeInfo): TRegistration;
begin
fRegistry.RegisterDefault(fModel, serviceType);
Result := Self;
end;
{$ENDREGION}
{$REGION 'TRegistration<T>'}
constructor TRegistration<T>.Create(
const registry: IComponentRegistry);
begin
fRegistration := TRegistration.Create(registry, TypeInfo(T));
end;
function TRegistration<T>.Implements(serviceType: PTypeInfo): TRegistration<T>;
begin
fRegistration.Implements(serviceType);
Result := Self;
end;
function TRegistration<T>.Implements(serviceType: PTypeInfo;
const name: string): TRegistration<T>;
begin
fRegistration.Implements(serviceType, name);
Result := Self;
end;
function TRegistration<T>.Implements<TServiceType>: TRegistration<T>;
begin
Result := Implements(TypeInfo(TServiceType));
end;
function TRegistration<T>.Implements<TServiceType>(
const name: string): TRegistration<T>;
begin
Result := Implements(TypeInfo(TServiceType), name);
end;
function TRegistration<T>.DelegateTo(
const delegate: TActivatorDelegate<T>): TRegistration<T>;
begin
fRegistration.DelegateTo(
function: TValue
begin
Result := TValue.From<T>(delegate());
end);
Result := Self;
end;
function TRegistration<T>.InjectConstructor(
const parameterTypes: array of PTypeInfo): TRegistration<T>;
begin
fRegistration.InjectConstructor(parameterTypes);
Result := Self;
end;
function TRegistration<T>.InjectProperty(
const propertyName: string): TRegistration<T>;
begin
fRegistration.InjectProperty(propertyName);
Result := Self;
end;
function TRegistration<T>.InjectMethod(const methodName: string;
const parameterTypes: array of PTypeInfo): TRegistration<T>;
begin
fRegistration.InjectMethod(methodName, parameterTypes);
Result := Self;
end;
function TRegistration<T>.InjectMethod(
const methodName: string): TRegistration<T>;
begin
fRegistration.InjectMethod(methodName);
Result := Self;
end;
function TRegistration<T>.InjectField(
const fieldName: string): TRegistration<T>;
begin
fRegistration.InjectField(fieldName);
Result := Self;
end;
function TRegistration<T>.InjectConstructor(
const arguments: array of TValue): TRegistration<T>;
begin
fRegistration.InjectConstructor(arguments);
Result := Self;
end;
function TRegistration<T>.InjectProperty(const propertyName: string;
const value: TValue): TRegistration<T>;
begin
fRegistration.InjectProperty(propertyName, value);
Result := Self;
end;
function TRegistration<T>.InjectMethod(const methodName: string;
const arguments: array of TValue): TRegistration<T>;
begin
fRegistration.InjectMethod(methodName, arguments);
Result := Self;
end;
function TRegistration<T>.InjectField(const fieldName: string;
const value: TValue): TRegistration<T>;
begin
fRegistration.InjectField(fieldName, value);
Result := Self;
end;
function TRegistration<T>.AsSingleton: TRegistration<T>;
begin
fRegistration.AsSingleton;
Result := Self;
end;
function TRegistration<T>.AsSingleton(refCounting: TRefCounting): TRegistration<T>;
begin
fRegistration.AsSingleton(refCounting);
Result := Self;
end;
function TRegistration<T>.AsSingletonPerThread: TRegistration<T>;
begin
fRegistration.AsSingletonPerThread;
Result := Self;
end;
function TRegistration<T>.AsTransient: TRegistration<T>;
begin
fRegistration.AsTransient;
Result := Self;
end;
function TRegistration<T>.AsPooled(minPoolSize, maxPoolSize: Integer): TRegistration<T>;
begin
{$WARN SYMBOL_EXPERIMENTAL OFF}
fRegistration.AsPooled(minPoolSize, maxPoolSize);
{$WARN SYMBOL_EXPERIMENTAL ON}
Result := Self;
end;
function TRegistration<T>.AsDefault: TRegistration<T>;
begin
fRegistration.AsDefault;
Result := Self;
end;
function TRegistration<T>.AsDefault(serviceType: PTypeInfo): TRegistration<T>;
begin
fRegistration.AsDefault(serviceType);
Result := Self;
end;
function TRegistration<T>.AsDefault<TServiceType>: TRegistration<T>;
begin
Result := AsDefault(TypeInfo(TServiceType));
end;
{$ENDREGION}
{$REGION 'TRegistrationManager'}
constructor TRegistrationManager.Create(
const registry: IComponentRegistry);
begin
inherited Create;
fRegistry := registry;
end;
function TRegistrationManager.RegisterComponent(
componentType: PTypeInfo): TRegistration;
begin
Guard.CheckNotNull(componentType, 'componentType');
Result := TRegistration.Create(fRegistry, componentType);
end;
function TRegistrationManager.RegisterComponent<TComponentType>: TRegistration<TComponentType>;
begin
Result := TRegistration<TComponentType>.Create(fRegistry);
end;
{$ENDREGION}
end.
|
// GLBumpmapHDS
{: Implements a HDS that automatically generates an elevation bumpmap.<p>
The object-space elevation bumpmap can be used for dynamic terrain lighting.<p>
A bumpmap texture is generated for each terrain tile, and placed into a TGLMaterialLibrary.
<b>History : </b><font size=-1><ul>
<li>22/01/10 - Yar - Added GLTextureFormat to uses
<li>13/02/07 - LIN- Thread-safe, for use with TGLAsyncHDS
Also takes advantage of texture-coodrinates, calculated by HeightDataSource
<li>02/02/07 - LIN- GLBumpmapHDS is now derived from THeightDataSourceFilter.
HeightDataSource replaces ElevationHDS.
(More efficient, since it no longer has to copy and release the entire Source HDS's THeightData object.)
<li>01/02/07 - LIN- Added 'MaxTextures' property.
if the MaterialLibrary.Materials.Count > MaxTextures, then unused textures are deleted.
Set MaxTextures=0 to disable Auto-deletes, and manage your normal-map textures manually.
WARNING: If you use THeightData.MaterialName, instead of THeightData.LibMaterial,
then HeightData does NOT register the texture as being used.
So make sure MaxTextures=0 if you use MaterialName.
<li>25/01/07 - LIN- Replaced 'StartPreparingData' and 'GenerateBumpmap' functions.
Now supports a TGLBitmap with multiple tiles.
Now works with HeightTileFileHDS.
World texture coordinates for individual textures are now calculated,
(TGLLibMaterial.TextureOffset and TGLLibMaterial.TextureScale)
Bugfix: Terrain position no longer jumps when InfiniteWrap is turned off.
<li>15/04/04 - EG - Fixed hdsNone support (Phil Scadden)
<li>20/03/04 - EG - Works, reasonnably seamless but still quite inefficient
<li>20/02/04 - EG - Creation
</ul></font>
}
unit GLBumpmapHDS;
interface
uses Classes, GLHeightData, GLGraphics, GLVectorGeometry, GLTexture, Dialogs, Forms,
SyncObjs, GLMaterial, GLTextureFormat;
type
TGLBumpmapHDS = class;
// TNewTilePreparedEvent
//
TNewTilePreparedEvent = procedure (Sender : TGLBumpmapHDS; heightData : THeightData;
normalMapMaterial : TGLLibMaterial) of object;
// TGLBumpmapHDS
//
{: An Height Data Source that generates elevation bumpmaps automatically.<p>
The HDS must be connected to another HDS, which will provide the elevation
data, and to a MaterialLibrary where bumpmaps will be placed. }
TGLBumpmapHDS = class (THeightDataSourceFilter)
private
{ Private Declarations }
//FElevationHDS : THeightDataSource;
FBumpmapLibrary : TGLMaterialLibrary;
FOnNewTilePrepared : TNewTilePreparedEvent;
FBumpScale : Single;
FSubSampling : Integer;
FMaxTextures : integer;
Uno:TCriticalSection;
protected
{ Protected Declarations }
procedure SetBumpmapLibrary(const val : TGLMaterialLibrary);
procedure SetBumpScale(const val : Single);
function StoreBumpScale : Boolean;
procedure SetSubSampling(const val : Integer);
procedure Trim(MaxTextureCount:integer);
public
{ Public Declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Release(aHeightData : THeightData); override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure GenerateNormalMap(heightData : THeightData; normalMap : TGLBitmap32; scale : Single);
procedure TrimTextureCache(MaxTextureCount:integer);
//procedure TileTextureCoordinates(heightData : THeightData; TextureScale:TTexPoint; TextureOffset:TTexPoint);
procedure PreparingData(heightData : THeightData); override;
published
{ Published Declarations }
property BumpmapLibrary : TGLMaterialLibrary read FBumpmapLibrary write SetBumpmapLibrary;
property OnNewTilePrepared : TNewTilePreparedEvent read FOnNewTilePrepared write FOnNewTilePrepared;
property BumpScale : Single read FBumpScale write SetBumpScale stored StoreBumpScale;
{: Specifies the amount of subsampling for the bump texture.<p>
This value must be a power of 2, and is used to divide the height
tile resolution to determine the bump texture resolution (f.i.
a tile size of 128 with a subsampling of 4 will result in textures
of a resolution of 32x32. SubSampling won't allow texture resolution
to get below 16x16 (minimal bumpmap resolution). }
property SubSampling : Integer read FSubSampling write SetSubSampling default 1;
property MaxPoolSize;
{: If MaxTextures>0 then the Bumpmap library is trimmed down to size whenever
the texture count is larger than MaxTextures. The oldest, unused texture is trimmed first.
However, if you used THeightData.MaterialName, instead of THeightData.LibMaterial,
then the THeightData component does not register the texture as being used.
So, if you use THeightData.MaterialName then make sure MaxTextures=0.
If MaxTextures=0 or if treads(GLAsyncHDS) are used, then the texture cache
is NOT trimmed automatically.
You will have to manually trim the cache from the main thread, by
calling 'TrimTextureCache'. (GLAsyncHDS.OnIdle is a good place.) }
property MaxTextures :integer read FMaxTextures write FMaxTextures;
property OnSourceDataFetched;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
uses SysUtils, OpenGL1x, OpenGLTokens, GLUtils;
const
cDefaultBumpScale = 0.01;
// ------------------
// ------------------ TGLBumpmapHDS ------------------
// ------------------
// Create
//
constructor TGLBumpmapHDS.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FBumpScale:=cDefaultBumpScale;
FSubSampling:=1;
Uno:=TCriticalSection.Create;
end;
// Destroy
//
destructor TGLBumpmapHDS.Destroy;
begin
BumpmapLibrary:=nil;
inherited Destroy;
end;
// Notification
//
procedure TGLBumpmapHDS.Notification(AComponent: TComponent; Operation: TOperation);
begin
if Operation=opRemove then begin
if AComponent=FBumpmapLibrary then BumpmapLibrary:=nil;
end;
inherited;
end;
// Release
//
procedure TGLBumpmapHDS.Release(aHeightData : THeightData);
var libMat : TGLLibMaterial;
begin
libMat:=aHeightData.LibMaterial;
aHeightData.MaterialName:='';
if (FMaxTextures>0)and(assigned(LibMat))and(libMat.IsUsed=false)
then LibMat.free;
inherited;
end;
// TrimTextureCache
//
// This will repeatedly delete the oldest unused texture from the TGLMaterialLibrary,
// until the texture count drops to MaxTextureCount.
// DONT use this if you used THeightData.MaterialName to link your terrain textures.
// Either use with THeightData.LibMaterial, or manually delete unused Normal-Map textures.
//
procedure TGLBumpmapHDS.TrimTextureCache(MaxTextureCount:integer); //Thread-safe Version
begin
if assigned(self) then begin
uno.Acquire;
Trim(MaxTextureCount);
uno.Release;
end;
end;
procedure TGLBumpmapHDS.Trim(MaxTextureCount:integer); //internal use only
var matLib: TGLMaterialLibrary;
libMat: TGLLibMaterial;
i:integer;
cnt:integer;
begin
matLib:=FBumpmapLibrary;
if matLib<>nil then begin
cnt:=matlib.Materials.Count;
i:=0;
while (i<cnt)and(cnt>=MaxTextureCount) do begin
libMat:=matlib.Materials[i];
if libMat.IsUsed then i:=i+1
else libmat.Free;
cnt:=matlib.Materials.Count;
end;
end;
end;
// PreparingData
//
procedure TGLBumpmapHDS.PreparingData(heightData : THeightData);
var HD : THeightData;
libMat: TGLLibMaterial;
bmp32 : TGLBitmap32;
MatName:string;
begin
if not assigned (FBumpmapLibrary) then exit;
//--Generate Normal Map for tile--
HD:=HeightData;
MatName:='BumpHDS_x'+IntToStr(HD.XLeft)+'y'+IntToStr(HD.YTop)+'.'; //name contains xy coordinates of the current tile
Uno.Acquire;
LibMat:=FBumpmapLibrary.Materials.GetLibMaterialByName(MatName); //Check if Tile Texture already exists
if LibMat=nil then begin
if (FMaxTextures>0) then begin
if HD.Thread=nil //Dont trim the cache from a sub-thread;
then TrimTextureCache(FMaxTextures) //Trim unused textures from the material library
end;
//Generate new NormalMap texture for this tile
libMat:=FBumpmapLibrary.Materials.Add;
libMat.Name:=MatName;
//Transfer tile texture coordinates to generated texture
libMat.TextureScale.X :=HD.TextureCoordinatesScale.S;
libMat.TextureScale.Y :=HD.TextureCoordinatesScale.T;
libMat.TextureOffset.X:=HD.TextureCoordinatesOffset.S;
libMat.TextureOffset.Y:=HD.TextureCoordinatesOffset.T;
//------------------------------------------------------
//--Set up new Normalmap texture for the current tile--
libMat.Material.MaterialOptions:=[moNoLighting];
with libMat.Material.Texture do begin
ImageClassName:=TGLBlankImage.ClassName;
Enabled:=True;
MinFilter:=miNearestMipmapNearest;
MagFilter:=maLinear; //MagFilter:=maNearest;
TextureMode:=tmReplace;
TextureWrap:=twNone;
TextureFormat:=tfRGB16;
//TextureFormat:=tfRGBA16;
bmp32:=(Image as TGLBlankImage).GetBitmap32(GL_TEXTURE_2D);
GenerateNormalMap(HD , bmp32, FBumpScale);
end;
//----------------------------------------------------
end;
//HD.MaterialName:=LibMat.Name;
HD.LibMaterial:=LibMat; //attach texture to current tile
if Assigned(FOnNewTilePrepared) then FOnNewTilePrepared(Self,HD,libMat);
Uno.Release;
end;
// GenerateNormalMap
//
procedure TGLBumpmapHDS.GenerateNormalMap(heightData : THeightData;
normalMap : TGLBitmap32;
scale : Single);
var mapSize:integer;
HD : THeightData;
x,y:integer;
scaleVec:TAffineVector;
vec : TAffineVector;
nmRow : PGLPixel32Array;
px,py:integer;
begin
HD:=HeightData;
MapSize:=(HD.Size-1);
mapSize:=mapSize div SubSampling;
normalMap.Height:=mapSize;
normalMap.Width :=mapSize;
normalMap.Blank :=false;
SetVector(ScaleVec,1,1,FBumpScale);
for y:=0 to mapSize-1 do begin
nmRow:=normalMap.ScanLine[mapSize-1-y];
for x:=0 to mapSize-1 do begin
px:=x*subsampling;
py:=y*subsampling;
vec:=HD.NormalAtNode(px,py,ScaleVec);
nmRow[x].r:=round(128+127*vec[0]); //nmRow[x].r:=0; //Red
nmRow[x].g:=round(128+127*vec[1]); //nmRow[x].g:=0; //Green
nmRow[x].b:=round(128+127*vec[2]); //nmRow[x].b:=0; //Blue
nmRow[x].a:=255;
end;
end;
end;
// SetBumpmapLibrary
//
procedure TGLBumpmapHDS.SetBumpmapLibrary(const val : TGLMaterialLibrary);
begin
if val<>FBumpmapLibrary then begin
if Assigned(FBumpmapLibrary) then
FBumpmapLibrary.RemoveFreeNotification(Self);
FBumpmapLibrary:=val;
if Assigned(FBumpmapLibrary) then
FBumpmapLibrary.FreeNotification(Self);
MarkDirty;
end;
end;
// SetBumpScale
//
procedure TGLBumpmapHDS.SetBumpScale(const val : Single);
begin
if FBumpScale<>val then begin
FBumpScale:=val;
MarkDirty;
end;
end;
// StoreBumpScale
//
function TGLBumpmapHDS.StoreBumpScale : Boolean;
begin
Result:=(FBumpScale<>cDefaultBumpScale);
end;
// SetSubSampling
//
procedure TGLBumpmapHDS.SetSubSampling(const val : Integer);
begin
if val<>FSubSampling then begin
FSubSampling:=RoundDownToPowerOf2(val);
if FSubSampling<1 then
FSubSampling:=1;
MarkDirty;
end;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// class registrations
RegisterClass(TGLBumpmapHDS);
end.
|
unit gr_AccList_PrintDM;
interface
uses
SysUtils, Classes, FIBDatabase, pFIBDatabase, DB, FIBDataSet,
pFIBDataSet, frxClass, frxDesgn, frxDBSet, IBase, IniFiles,
ZProc, Forms, Variants, Dates, Dialogs,
gr_uCommonLoader, gr_uCommonProc, gr_uMessage, gr_uCommonConsts,
gr_uWaitForm, FIBQuery, pFIBQuery, pFIBStoredProc;
type
TPrintDM = class(TDataModule)
frxDSetGlobalData: TfrxDBDataset;
frxDesigner1: TfrxDesigner;
frxUserDataSet: TfrxUserDataSet;
ReadTransaction: TpFIBTransaction;
DSetAccUdList: TpFIBDataSet;
DSetAccNarList: TpFIBDataSet;
DSetGlobalData: TpFIBDataSet;
DB: TpFIBDatabase;
DSetSystemData: TpFIBDataSet;
frxDSetSystemData: TfrxDBDataset;
StProc: TpFIBStoredProc;
UdateTransaction: TpFIBTransaction;
DSource: TDataSource;
frxDSetAccNarList: TfrxDBDataset;
Report: TfrxReport;
DSetSmetaList: TpFIBDataSet;
frxDSetSmetaList: TfrxDBDataset;
DSetSheets: TpFIBDataSet;
frxDSetSheets: TfrxDBDataset;
procedure ReportGetValue(const VarName: String; var Value: Variant);
procedure DataModuleDestroy(Sender: TObject);
function DayClocks(Sender:TObject):String;
private
pParameter:TgrAccListParam;
PIdSession:Integer;
public
procedure ReportCreate(AParameter:TgrAccListParam);
end;
implementation
{$R *.dfm}
const FullNameReport = '\grAccList.fr3';
procedure TPrintDM.ReportCreate(AParameter:TgrAccListParam);
var wf:TForm;
begin
try
DB.Handle:=AParameter.DB_handle;
pParameter:=AParameter;
if(pParameter.TypeTable=2)then
try
wf:=ShowWaitForm(TForm(pParameter.Owner),wfPrepareData);
DB.Handle:=PParameter.DB_Handle;
StProc.Transaction.StartTransaction;
StProc.StoredProcName:='GR_SVOD_PREPARE_DATA';
StProc.Prepare;
StProc.ParamByName('KOD_SETUP').AsInteger :=PParameter.KodSetup2;
StProc.ExecProc;
AParameter.IdGroupAccount:=StProc.ParamByName('ID_SESSION').AsInteger;
StProc.Transaction.Commit;
CloseWaitForm(wf);
except
on E:Exception do
begin
CloseWaitForm(wf);
grShowMessage(ECaption[1{PlanguageIndex}],e.Message,mtError,[mbOK]);
StProc.Transaction.Rollback;
end;
end;
DSetAccNarList.SQLs.SelectSQL.Text := 'SELECT * FROM Z_ACCOUNT_ACC_NAR_S('+IntToStr(AParameter.IdGroupAccount)+','+
' ?ID_MAN,'+
IntToStr(AParameter.KodSetup2)+','+
IntToStr(AParameter.TypeTable)+') ORDER BY KOD_SETUP3 descending,KOD_VIDOPL,NAME_VIDOPL';
DSetAccUdList.SQLs.SelectSQL.Text := 'SELECT * FROM Z_ACCOUNT_ACC_UD_S('+IntToStr(AParameter.IdGroupAccount)+','+
' ?ID_MAN,'+
IntToStr(AParameter.KodSetup2)+','+
IntToStr(AParameter.TypeTable)+') order by KOD_SETUP3 descending,KOD_VIDOPL,NAME_VIDOPL';
DSetSmetaList.SQLs.SelectSQL.Text:='SELECT * FROM Z_ACCOUNT_ACC_SMETA_S('+IntToStr(AParameter.IdGroupAccount)+',?ID_MAN,'+
IntToStr(AParameter.KodSetup2)+','+IntToStr(AParameter.TypeTable)+')'; // ORDER BY ID_DEPARTMENT,ID_SMETA';
DSetSheets.SQLs.SelectSQL.Text:='SELECT * FROM Z_ACCOUNT_ACC_S_SHEET(?ID_MAN,'+IntToStr(AParameter.IdGroupAccount)+')';
if AParameter.TypeTable=2 then
DSetGlobalData.SQLs.SelectSQL.Text := 'SELECT * FROM GR_ACCOUNT_GLOBALDATA_S_FILTER('+IntToStr(AParameter.IdGroupAccount)+','+ IntToStr(AParameter.Id_man)+','+
IntToStr(AParameter.KodSetup2)+','+
IntToStr(AParameter.TypeTable)+','+
AParameter.KOD_SETUP1+','+
AParameter.KOD_SETUP2+','+
AParameter.id+','+
AParameter.ID_TYPE+','+
AParameter.PAYMENT_TYPE+') order by ORG_STR_NAME'
else
DSetGlobalData.SQLs.SelectSQL.Text := 'SELECT * FROM GR_ACCOUNT_GLOBALDATA_S('+IntToStr(AParameter.IdGroupAccount)+','+ IntToStr(AParameter.Id_man)+','+
IntToStr(AParameter.KodSetup2)+','+
IntToStr(AParameter.TypeTable)+') order by ORG_STR_NAME';
DSetSystemData.SQLs.SelectSQL.Text := 'SELECT SHORT_NAME FROM Z_SETUP';
DSetGlobalData.Open;
DSetAccNarList.Open;
DSetAccUdList.Open;
DSetSmetaList.Open;
DSetSheets.Open;
DSetSystemData.Open;
frxUserDataSet.Fields.Add('N_CODE_DEPARTMENT');
frxUserDataSet.Fields.Add('N_KOD_SETUP_3');
frxUserDataSet.Fields.Add('N_KOD_VIDOPL');
frxUserDataSet.Fields.Add('N_NAME_VIDOPL');
frxUserDataSet.Fields.Add('N_DAY_CLOCK');
frxUserDataSet.Fields.Add('N_PERCENT_SUMCLOCK');
frxUserDataSet.Fields.Add('N_SUMMA');
frxUserDataSet.Fields.Add('U_KOD_SETUP_3');
frxUserDataSet.Fields.Add('U_KOD_VIDOPL');
frxUserDataSet.Fields.Add('U_NAME_VIDOPL');
frxUserDataSet.Fields.Add('U_SUMMA');
frxUserDataSet.RangeEnd := reCount;
frxUserDataSet.RangeEndCount := ifThen(DSetAccUdList.RecordCount>DSetAccNarList.RecordCount,DSetAccUdList.RecordCount,DSetAccNarList.RecordCount);
Report.Clear;
Report.LoadFromFile(ExtractFilePath(Application.ExeName)+PathReports+FullNameReport,True);
Report.Variables.Clear;
Report.Variables['P_PERIOD']:=''''+AnsiLowerCase(KodSetupToPeriod(AParameter.KodSetup2,2))+'''';
Report.Variables['P_SUMMARY']:='''';//+FZPrintAccList_P_Summary_Text+'''';
Report.Variables['P_UD']:='''';//+FZPrintAccList_P_Ud_Text+'''';
if grDesignReport
then Report.DesignReport
else Report.ShowReport;
Report.Free;
except
on E:Exception do
begin
grShowMessage(ECaption[Indexlanguage],e.Message,mtError,[mbOK]);
end;
end;
if(pParameter.TypeTable=2)then
try
StProc.Transaction.StartTransaction;
StProc.StoredProcName:='Z_SVOD_PREPARE_DATA_DELETE';
StProc.Prepare;
StProc.ParamByName('ID_SESSION').AsInteger:=AParameter.IdGroupAccount;
StProc.ExecProc;
StProc.Transaction.Commit;
except
on E:Exception do
begin
grShowMessage(ECaption[1],e.Message,mtError,[mbOK]);
StProc.Transaction.Rollback;
end;
end;
end;
procedure TPrintDM.ReportGetValue(const VarName: String;
var Value: Variant);
var Sum_Nar,Sum_Ud:Extended;
begin
if UpperCase(VarName)='P_ACCLIST_TYPE' then
begin
if DSetGlobalData['KOD_SETUP1']=pParameter.KodSetup2 then Value:=''
else Value:='Перерахунок';
end;
if UpperCase(VarName)='P_STUDENT' then
begin
if VarIsNULL(DSetGlobalData['TN']) then Value:=''
else Value:=VarToStr(DSetGlobalData['TN'])+' - ';
Value:=value+VarToStr(DSetGlobalData['FIO']);
frxUserDataSet.RangeEndCount := ifThen(DSetAccUdList.RecordCount>DSetAccNarList.RecordCount,DSetAccUdList.RecordCount,DSetAccNarList.RecordCount);
end;
if UpperCase(VarName)='P_SUM_NAR' then
begin
Sum_Nar:=0;
DSetAccNarList.First;
while not DSetAccNarList.Eof do
Begin
Sum_Nar:=Sum_Nar+DSetAccNarList['SUMMA'];
DSetAccNarList.Next;
end;
Value:=FloatToStrF(Sum_Nar,ffFixed,16,2);
end;
if UpperCase(VarName)='P_SUM_UD' then
begin
Sum_Ud:=0;
DSetAccUdList.First;
while not DSetAccUdList.Eof do
Begin
Sum_Ud:=Sum_Ud+DSetAccUdList['SUMMA'];
DSetAccUdList.Next;
end;
Value :=FloatToStrF(Sum_Ud,ffFixed,16,2);
end;
if UpperCase(VarName)='P_VIPLATA' then
begin
Sum_Nar:=0;
DSetAccNarList.First;
while not DSetAccNarList.Eof do
Begin
Sum_Nar:=Sum_Nar+DSetAccNarList['SUMMA'];
DSetAccNarList.Next;
end;
Sum_Ud:=0;
DSetAccUdList.First;
while not DSetAccUdList.Eof do
Begin
Sum_Ud:=Sum_Ud+DSetAccUdList['SUMMA'];
DSetAccUdList.Next;
end;
Value:=FloatToStrF(Sum_Nar-Sum_Ud,ffFixed,16,2);
end;
if UpperCase(VarName)='N_SUMMA' then
begin
if DSetAccNarList.RecordCount-1>=frxUserDataSet.RecNo then
begin
DSetAccNarList.RecNo:=frxUserDataSet.RecNo+1;
Value:=DSetAccNarList.FieldValues['SUMMA'];
end
else
Value:=NULL;
end;
if UpperCase(VarName)='N_CODE_DEPARTMENT' then
begin
if DSetAccNarList.RecordCount-1>=frxUserDataSet.RecNo then
begin
DSetAccNarList.RecNo:=frxUserDataSet.RecNo+1;
Value:=DSetAccNarList.FieldValues['CODE_DEPARTMENT'];
end
else
Value:=NULL;
end;
if UpperCase(VarName)='N_KOD_SETUP_3' then
begin
if DSetAccNarList.RecordCount-1>=frxUserDataSet.RecNo then
begin
DSetAccNarList.RecNo:=frxUserDataSet.RecNo+1;
Value:=KodSetupToPeriod(DSetAccNarList['KOD_SETUP3'],1);
end
else
Value:=NULL;
end;
if UpperCase(VarName)='N_KOD_VIDOPL' then
begin
if DSetAccNarList.RecordCount-1>=frxUserDataSet.RecNo then
begin
DSetAccNarList.RecNo:=frxUserDataSet.RecNo+1;
Value:=DSetAccNarList.FieldValues['KOD_VIDOPL'];
end
else
Value:=NULL;
end;
if UpperCase(VarName)='N_NAME_VIDOPL' then
begin
if DSetAccNarList.RecordCount-1>=frxUserDataSet.RecNo then
begin
DSetAccNarList.RecNo:=frxUserDataSet.RecNo+1;
Value:=DSetAccNarList.FieldValues['NAME_VIDOPL'];
end
else
Value:=NULL;
end;
if UpperCase(VarName)='N_DAY_CLOCK' then
begin
if DSetAccNarList.RecordCount-1>=frxUserDataSet.RecNo then
begin
DSetAccNarList.RecNo:=frxUserDataSet.RecNo+1;
Value:=DayClocks(self);
end
else
Value:=NULL;
end;
if UpperCase(VarName)='N_KOD_SMETA' then
begin
if DSetAccNarList.RecordCount-1>=frxUserDataSet.RecNo then
begin
DSetAccNarList.RecNo:=frxUserDataSet.RecNo+1;
Value:=DSetAccNarList.FieldValues['KOD_SMETA'];
end
else
Value:=NULL;
end;
if UpperCase(VarName)='U_KOD_SETUP_3' then
begin
if DSetAccUdList.RecordCount-1>=frxUserDataSet.RecNo then
begin
DSetAccUdList.RecNo:=frxUserDataSet.RecNo+1;
Value:=KodSetupToPeriod(DSetAccUdList['KOD_SETUP3'],1);
end
else
Value:=NULL;
end;
if UpperCase(VarName)='U_KOD_VIDOPL' then
begin
if DSetAccUdList.RecordCount-1>=frxUserDataSet.RecNo then
begin
DSetAccUdList.RecNo:=frxUserDataSet.RecNo+1;
Value:=DSetAccUdList.FieldValues['KOD_VIDOPL'];
end
else
Value:=NULL;
end;
if UpperCase(VarName)='U_NAME_VIDOPL' then
begin
if DSetAccUdList.RecordCount-1>=frxUserDataSet.RecNo then
begin
DSetAccUdList.RecNo:=frxUserDataSet.RecNo+1;
Value:=DSetAccUdList.FieldValues['NAME_VIDOPL'];
end
else
Value:=NULL;
end;
if UpperCase(VarName)='U_SUMMA' then
begin
if DSetAccUdList.RecordCount-1>=frxUserDataSet.RecNo then
begin
DSetAccUdList.RecNo:=frxUserDataSet.RecNo+1;
Value:=DSetAccUdList.FieldValues['SUMMA'];
end
else
Value:=NULL;
end;
if UpperCase(VarName)='P_SUM_NAR' then
begin
Sum_Nar:=0;
DSetAccNarList.First;
while not DSetAccNarList.Eof do
Begin
Sum_Nar:=Sum_Nar+DSetAccNarList['SUMMA'];
DSetAccNarList.Next;
end;
Value:=FloatToStrF(Sum_Nar,ffFixed,16,2);
end;
if UpperCase(VarName)='P_SUM_UD' then
begin
Sum_Ud:=0;
DSetAccUdList.First;
while not DSetAccUdList.Eof do
Begin
Sum_Ud:=Sum_Ud+DSetAccUdList['SUMMA'];
DSetAccUdList.Next;
end;
Value :=FloatToStrF(Sum_Ud,ffFixed,16,2);
end;
end;
procedure TPrintDM.DataModuleDestroy(Sender: TObject);
begin
if ReadTransaction.InTransaction then ReadTransaction.Commit;
end;
function TPrintDM.DayClocks(Sender:TObject):String;
var PValue:Variant;
Sign:string[1];
begin
Result:='';
if (DSetAccNarList['NDAY']=0) or (VarIsNull(DSetAccNarList['NDAY'])) then Result:='--'
else
begin
sign:=IfThen(DSetAccNarList['NDAY']<0,'-','');
PValue:=Abs(DSetAccNarList['NDAY']);
Result:=Sign+ifThen(PValue<10,'0','')+VarToStr(PValue);
end;
end;
end.
|
unit uCS_Resources;
interface
uses Dialogs, StdCtrls, Classes, IBase, FIBDataSet, pFIBDataSet, FIBDatabase,
pFIBDatabase, IniFiles;
{Type TNamePrKViewWithFilter=(PrKViewKartkaAbit);
Type TNamePrKVuzLicense=(PrK_SP_MIN_PERELIK_SHIFR, PrK_SP_VUZ_LICENCE, PrK_SP_PLAN_NABORA,
PrK_SP_EDUCORG, PrK_SP_CEL_ZAMOVNIK, PrK_SP_PLAN_CEL_NABOR,
PrK_SP_EKZ_RASP);
}
Type TNamePrKSprav =(PrK_SP_DERG_ZAKAZ, PrK_SP_EXZFORM, PrK_SP_GURTOG, PrK_SP_IN_LANG,
PrK_SP_IS_COPY, PrK_SP_KAT_PRI_X, PrK_SP_KURS, PrK_SP_LEVEL_VLADEN,
PrK_SP_MOVA, PrK_SP_NPK, PrK_SP_OLD_PRICH, PrK_SP_PREDM,
PrK_SP_PRICH, PrK_SP_PRIZN_ZACHISL, PrK_SP_RISH_TYPE, PrK_SP_TYPE_DOK_OBR,
PrK_SP_TYPE_PEREKL, PrK_SP_TYPE_RAZN, PrK_SP_TYPE_UCHZ, PrK_SP_UKR_LANG,
PrK_SP_VID_DII, PrK_SP_ZABR,
PrK_SP_FOB_PROT, PrK_SP_GOD_NABORA, PrK_SP_OCENKA, PrK_SP_PREIM,
PrK_SP_FORM_OBUCH_KATEGORY, PrK_SP_VID_DOG, PrK_SP_MIN_PERELIK_PRIM,
PrK_SP_MIN_PERELIK_SPEC, PrK_SP_TYPE_KAT_STUD, PrK_SP_SROK_OB,
PrK_SP_PREDM_u, PrK_SP_POTOK, PrK_SP_TYPE_DOP_DOK, PrK_SP_ISPIT_VEDOM_TYPE,
PrK_SP_DOLGNOST_PK, PrK_SP_KAT_PRI_D, PrK_SP_TYPE_ZACH);
Type TNamePrKSpravEdit=(PrKSpravEditStandart,PrKSpravEditFobProt);
Type TWrongDataPrKSpr =(EmptyName,EmptyShortName,EmptyKod,ZerroKod,ThisKodExist,
EmptyNpp,ZerroNpp,ThisNppExist,EmptyVinitPadeg,
EmptyRoditPadeg,AllDataOk);
Type RejimPrK =(AddPrK,ChangePrk,ViewPrK,DelPrK);
Type
TDataPrKSprav = class
private
FKod: integer;
FShortName: string;
FName: string;
FId: Int64;
FNpp: integer;
procedure SetKod(const Value: integer);
procedure SetName(const Value: string);
procedure SetShortName(const Value: string);
procedure SetId(const Value: Int64);
procedure SetNpp(const Value: integer);
public
constructor Create(aKodMax: Integer;aNppMax: Integer);overload;virtual;
constructor Create(aKodMax: Integer;aNppMax: Integer;aShortName: String);overload;virtual;
constructor Create(aId:int64; aName:String; aShortName:String;
aKod:integer;aNpp: Integer);overload;
// Функция которая при добавлении(изм) данных проверяет их правильность
function AddChangeData(aId:Int64; aName, aShortName:String;
aKod:integer; aAllDataKods: variant;
aNpp:integer; aAllDataNpps: variant):TWrongDataPrKSpr;
Property Id : Int64 read FId write SetId;
Property Kod : integer read FKod write SetKod;
Property Npp : integer read FNpp write SetNpp;
Property Name : string read FName write SetName;
Property ShortName :string read FShortName write SetShortName;
end;
function SelectLanguage : integer; stdcall;
function SelectShemaColor : integer; stdcall;
//exports SelectLanguage;
function GetImageDBHandle(MAIN_DB_HANDLE:TISC_DB_HANDLE):TISC_DB_HANDLE; // Получаем хэндл базы фотографий
function prkMessageDlg(const Caption : string; const Msg : string;const DlgType: TMsgDlgType;
const Buttons: TMsgDlgButtons;aIndexLanguage: integer) : word;stdcall;
//exports agMessageDlg;
implementation
uses Forms,SysUtils,Windows,Variants,registry, uCS_Constants,
AccMgmt;
{ TDataPrKSprav }
constructor TDataPrKSprav.Create(aKodMax: Integer;aNppMax: Integer);
begin
Kod :=aKodMax+1;
Npp :=aNppMax+1;
Name :='';
ShortName :='';
end;
constructor TDataPrKSprav.Create(aKodMax: Integer;aNppMax: Integer;aShortName: String);
begin
Kod :=aKodMax+1;
Npp :=aNppMax+1;
Name :='';
ShortName :=aShortName;
end;
function TDataPrKSprav.AddChangeData(aId:Int64; aName, aShortName: String;
aKod: integer; aAllDataKods: variant;
aNpp:integer; aAllDataNpps: variant): TWrongDataPrKSpr;
var
i,razmer: integer;
begin
if Trim(aName)='' then
begin
result:=EmptyName;
exit;
end;
if Trim(aShortName)='' then
begin
result:=EmptyShortName;
exit;
end;
if aKod=0 then
begin
result:=ZerroKod;
exit;
end;
if aKod=Unassigned then
begin
result:=EmptyKod;
exit;
end;
if aNpp=0 then
begin
result:=ZerroNpp;
exit;
end;
if aNpp=Unassigned then
begin
result:=EmptyNpp;
exit;
end;
if (aKod<>Kod)and(VarArrayDimCount(aAllDataKods)>0) then
begin
razmer:=VarArrayHighBound(aAllDataKods, 1)-VarArrayLowBound(aAllDataKods, 1);
for i:=0 to razmer do
begin
if aAllDataKods[i]=aKod then
begin
result:=ThisKodExist;
exit;
end;
end;
end;
if (aNpp<>Npp)and(VarArrayDimCount(aAllDataNpps)>0) then
begin
razmer:=VarArrayHighBound(aAllDataNpps, 1)-VarArrayLowBound(aAllDataNpps, 1);
for i:=0 to razmer do
begin
if aAllDataNpps[i]=aNpp then
begin
result:=ThisNppExist;
exit;
end;
end;
end;
Id :=aId;
Name :=aName;
ShortName:=aShortName;
Kod :=aKod;
Npp :=aNpp;
result:=AllDataOk;
end;
constructor TDataPrKSprav.Create(aId: int64; aName, aShortName: String;
aKod: integer;aNpp: Integer);
begin
Id :=aId;
Kod :=aKod;
Npp :=aNpp;
Name :=aName;
ShortName :=aShortName;
end;
procedure TDataPrKSprav.SetId(const Value: Int64);
begin
FId := Value;
end;
procedure TDataPrKSprav.SetKod(const Value: integer);
begin
FKod := Value;
end;
procedure TDataPrKSprav.SetNpp(const Value: integer);
begin
FNpp := Value;
end;
procedure TDataPrKSprav.SetName(const Value: string);
begin
FName := Value;
end;
procedure TDataPrKSprav.SetShortName(const Value: string);
begin
FShortName := Value;
end;
{ выбор языка: 0-украинский, 1-русский}
function SelectLanguage: integer;
var
reg :TRegistry;
RegisterValue :integer;
begin
//вслучае боков по умолчанию будет украинский язык
RegisterValue:=0;
//чтение из регистра
reg:=TRegistry.Create;
try
reg.RootKey :=HKEY_CURRENT_USER;
if reg.OpenKey('\Software\CS\Languages\',false) then
begin
RegisterValue:=reg.ReadInteger('Index');
end;
finally
reg.Free;
end;
result:=RegisterValue;
end;
{ выбор цветовой схемы: 0-желтая, 1-голубая}
function SelectShemaColor : integer;
var
reg :TRegistry;
RegisterValue :integer;
begin
//вслучае боков по умолчанию будет желтая схема язык
RegisterValue:=0;
//чтение из регистра
reg:=TRegistry.Create;
try
reg.RootKey :=HKEY_CURRENT_USER;
if reg.OpenKey('\Software\CS\ShemaColor\',false) then
begin
RegisterValue:=reg.ReadInteger('Color');
end;
finally
reg.Free;
end;
result:=RegisterValue;
end;
{Переделанный MessageDlg}
function prkMessageDlg(const Caption : string; const Msg : string;
const DlgType: TMsgDlgType; const Buttons: TMsgDlgButtons;
aIndexLanguage: integer) : word;
var
formD : TForm;
i : integer;
begin
if Buttons = [] then begin
Result := 0;
exit;
end;
formD := CreateMessageDialog(Msg, DlgType, Buttons);
formD.Caption := Caption;
for i := 0 to formD.ComponentCount - 1 do if formD.Components[i] is TButton then begin
if UpperCase(TButton(formD.Components[i]).Caption) = 'OK' then TButton(formD.Components[i]).Caption := nMsgDlgOk[aIndexLanguage];
if UpperCase(TButton(formD.Components[i]).Caption) = 'CANCEL' then TButton(formD.Components[i]).Caption := nMsgDlgCansel[aIndexLanguage];
if UpperCase(TButton(formD.Components[i]).Caption) = '&YES' then TButton(formD.Components[i]).Caption := nMsgDlgYes[aIndexLanguage];
if UpperCase(TButton(formD.Components[i]).Caption) = '&NO' then TButton(formD.Components[i]).Caption := nMsgDlgNo[aIndexLanguage];
if UpperCase(TButton(formD.Components[i]).Caption) = '&ABORT' then TButton(formD.Components[i]).Caption := nMsgDlgAbort[aIndexLanguage];
if UpperCase(TButton(formD.Components[i]).Caption) = '&RETRY' then TButton(formD.Components[i]).Caption := nMsgDlgRetry[aIndexLanguage];
if UpperCase(TButton(formD.Components[i]).Caption) = '&IGNORE'then TButton(formD.Components[i]).Caption := nMsgDlgIgnore[aIndexLanguage];
if UpperCase(TButton(formD.Components[i]).Caption) = '&ALL' then TButton(formD.Components[i]).Caption := nMsgDlgAll[aIndexLanguage];
if UpperCase(TButton(formD.Components[i]).Caption) = '&HELP' then TButton(formD.Components[i]).Caption := nMsgDlgHelp[aIndexLanguage];
if UpperCase(TButton(formD.Components[i]).Caption) = 'N&O TO ALL' then TButton(formD.Components[i]).Caption := nMsgDlgNoToAll[aIndexLanguage];
if UpperCase(TButton(formD.Components[i]).Caption) = 'YES TO &ALL' then TButton(formD.Components[i]).Caption := nMsgDlgYesToAll[aIndexLanguage];
end;
Result := formD.ShowModal;
end;
function GetImageDBHandle(MAIN_DB_HANDLE:TISC_DB_HANDLE):TISC_DB_HANDLE;
var
CurrUserInfo:AccMgmt.TUserInfo;
ResultInfo:AccMgmt.TResultInfo;
DB:TpFIBDatabase;
ReadTransaction:TpFIBTransaction;
DSet:TpFIBDataSet;
pShowFoto:Variant;
F:TIniFile;
ImagePath:String;
begin
CurrUserInfo:=AccMgmt.fibGetCurrentUserInfo;
{ Первый шаг проверки - разрешено ли использование пакета фотографий,
второй шаг - проверка на наличие базы, т.к. мало ли что можно отметить в таблице}
// Первый шаг
Result:=nil;
DB:=TpFIBDatabase.Create(nil);
ReadTransaction:=TpFIBTransaction.Create(nil);
DSet:=TpFIBDataSet.Create(nil);
ReadTransaction.DefaultDatabase:=DB;
DB.DefaultTransaction:=ReadTransaction;
DSet.Database:=DB;
DSet.Transaction:=ReadTransaction;
DB.Handle:=MAIN_DB_HANDLE;
ReadTransaction.Active:=True;
DSet.SQLs.SelectSQL.Text:='SELECT SHOW_FOTO FROM PUB_SYS_DATA';
DSet.Open;
pShowFoto:=DSet['SHOW_FOTO'];
ReadTransaction.Active:=False;
DSet.Free;
ReadTransaction.Free;
DB.Free;
if pShowFoto<>1 then Exit; // Не повезло.
// Второй шаг
// Проверяем на наличие базы по ее пути в config.ini
F:=TIniFile.Create(ExtractFileDir(Application.ExeName)+'\config.ini');
try
ImagePath:=F.ReadString('IMAGE_CONNECTION','Path','');
finally;
F.Free;
end;
if ImagePath='' then Exit; // Не повезло.
// Пытаемся установить подключение
ResultInfo:=AccMgmt.fibInitImageConnection(CurrUserInfo.UserName,CurrUserInfo.Password);
if ResultInfo.ErrorCode <> ACCMGMT_OK then // ошибка
if ResultInfo.ErrorCode=-12 then
{... т.е. если ошибка "Невірне ім'я або пароль"(а она появляется при повторной
загрузке справочника физических лиц, то мы вызываем fibInitImageConnection
снова и база, закрытая предыдущим вызовом, вновь открывается. Вот так вот,
и не надо нигде запоминать хэндл базы.}
begin
ResultInfo:=AccMgmt.fibInitImageConnection(CurrUserInfo.UserName,CurrUserInfo.Password);
if ResultInfo.ErrorCode <> ACCMGMT_OK then // ошибка, мало ли чего...
Result:=nil
else
Result:=ResultInfo.DBHandle;
end
else
Result:=nil
else
Result:=ResultInfo.DBHandle;
end;
end.
|
//------------------------------------------------------------------------------
//GameTypes UNIT
//------------------------------------------------------------------------------
// What it does-
// Contains game related Types
//
// Changes -
// February 25th, 2008 - RaX - Created
//
//------------------------------------------------------------------------------
unit GameTypes;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
//uses
{RTL/VCL}
{Project}
{Third Party}
type
TLookTypes =
(
LOOK_JOB,
LOOK_HAIR,
LOOK_WEAPON,
LOOK_HEAD_BOTTOM,
LOOK_HEAD_TOP,
LOOK_HEAD_MID,
LOOK_HAIR_COLOR,
LOOK_CLOTHES_COLOR,
LOOK_SHIELD,
LOOK_SHOES,
LOOK_MOB
);
TGenders =
(
MALE,
FEMALE,
BOTH
);
function GenderToChar(const AGender : TGenders) : Char;
function CharToGender(AChar : Char) : TGenders;
implementation
function GenderToChar(const AGender : TGenders) : Char;
begin
case AGender of
MALE :
begin
Result := 'm';
end;
FEMALE :
begin
Result := 'f';
end;
else
begin
Result := 's';
end;
end;
end;
function CharToGender(AChar : Char) : TGenders;
begin
case AChar of
'm',
'M':
begin
Result := MALE;
end;
'f',
'F':
begin
Result := FEMALE;
end;
else
begin
Result := BOTH;
end;
end;
end;
end.
|
//
// Generated by JavaToPas v1.5 20180804 - 082358
////////////////////////////////////////////////////////////////////////////////
unit java.nio.file.FileSystemException;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes;
type
JFileSystemException = interface;
JFileSystemExceptionClass = interface(JObjectClass)
['{53B22B08-81D2-4765-BB63-242B89D67FF9}']
function getFile : JString; cdecl; // ()Ljava/lang/String; A: $1
function getMessage : JString; cdecl; // ()Ljava/lang/String; A: $1
function getOtherFile : JString; cdecl; // ()Ljava/lang/String; A: $1
function getReason : JString; cdecl; // ()Ljava/lang/String; A: $1
function init(&file : JString) : JFileSystemException; cdecl; overload; // (Ljava/lang/String;)V A: $1
function init(&file : JString; other : JString; reason : JString) : JFileSystemException; cdecl; overload;// (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V A: $1
end;
[JavaSignature('java/nio/file/FileSystemException')]
JFileSystemException = interface(JObject)
['{D44E252C-DE0A-42AE-91C3-0156F2105236}']
function getFile : JString; cdecl; // ()Ljava/lang/String; A: $1
function getMessage : JString; cdecl; // ()Ljava/lang/String; A: $1
function getOtherFile : JString; cdecl; // ()Ljava/lang/String; A: $1
function getReason : JString; cdecl; // ()Ljava/lang/String; A: $1
end;
TJFileSystemException = class(TJavaGenericImport<JFileSystemExceptionClass, JFileSystemException>)
end;
implementation
end.
|
unit Effects;
interface
uses
System.Types,
System.SysUtils,
System.Classes,
System.Math,
Winapi.Windows,
Vcl.Graphics,
Dmitry.Graphics.Types,
Scanlines,
uDBGraphicTypes,
uMemory,
uBitmapUtils;
procedure Inverse(S, D: TBitmap; CallBack : TProgressCallBackProc = nil);
procedure ReplaceColorInImage(S,D : TBitmap; BaseColor, NewColor : TColor; Size, Level : Integer; CallBack : TProgressCallBackProc = nil); overload;
procedure GrayScaleImage(S,D : TBitmap; n : integer; CallBack : TProgressCallBackProc = nil); overload;
procedure GrayScaleImage(S,D : TBitmap; CallBack : TProgressCallBackProc = nil); overload;
procedure Sepia(S,D : TBitmap; Depth: Integer; CallBack : TProgressCallBackProc = nil); overload;
procedure Sepia(S,D : TBitmap; CallBack : TProgressCallBackProc = nil); overload;
procedure Dither(S, D: TBitmap; CallBack : TProgressCallBackProc = nil);
procedure ChangeBrightness(S,D : TBitmap; Brightness: Integer); overload;
procedure ChangeBrightness(Image : TBitmap; Brightness: Integer); overload;
procedure ChangeBrightness(Image : TArPARGB; Width, Height : integer; Brightness: Integer); overload;
procedure WaveSin(S, D: TBitmap; Frequency, Length: Integer; Hor: Boolean; BackColor: TColor; CallBack : TProgressCallBackProc = nil);
procedure PixelsEffect(S, D: TBitmap; Hor, Ver: Word; CallBack : TProgressCallBackProc = nil);
procedure Sharpen(S, D: TBitmap; alpha: Single; CallBack : TProgressCallBackProc = nil);
procedure Blocks(S, D: TBitmap; Hor, Ver, MaxOffset: Integer; BackColor: TColor);
procedure Gamma(S, D: TBitmap; L: Double); overload;
procedure Gamma(Image: TBitmap; L: Double); overload;
procedure SetRGBChannelValue(S, D: TBitmap; Red, Green, Blue: Integer); overload;
procedure SetRGBChannelValue(Image: TBitmap; Red, Green, Blue: Integer); overload;
procedure SetRGBChannelValue(Image: TArPARGB; Width, Height : integer; Red, Green, Blue: Integer); overload;
procedure Disorder(S, D: TBitmap; Hor, Ver: Integer; BackColor: TColor; CallBack : TProgressCallBackProc = nil); overload;
procedure Disorder(S, D: TBitmap; CallBack : TProgressCallBackProc = nil); overload;
procedure Contrast(S, D: TBitmap; Value: Extended; Local: Boolean); overload;
procedure Contrast(Image: TBitmap; Value: Extended; Local: Boolean); overload;
procedure Contrast(Image: TArPARGB; Width, Height : integer; Value: Extended; Local: Boolean); overload;
procedure SetContractBrightnessRGBChannelValue(ImageS, ImageD: TArPARGB; Width, Height: Integer; Contrast : Extended; var OverageBrightnss : Integer; Brightness, Red, Green, Blue: Integer); overload;
Procedure Colorize(S,D : TBitmap; Luma: Integer);
Procedure AutoLevels(S,D : TBitmap; CallBack : TProgressCallBackProc = nil);
Procedure AutoColors(S,D : TBitmap; CallBack : TProgressCallBackProc = nil);
function GistogrammRW(S: TBitmap; Rect: TRect; var CountR: int64): T255IntArray;
procedure Rotate90(S,D : tbitmap; CallBack : TProgressCallBackProc = nil);
procedure Rotate270(S,D : Tbitmap; CallBack : TProgressCallBackProc = nil);
procedure Rotate180(S,D : Tbitmap; CallBack : TProgressCallBackProc = nil);
procedure FlipHorizontal(S,D : TBitmap; CallBack : TProgressCallBackProc = nil);
procedure FlipVertical(S,D : TBitmap; CallBack : TProgressCallBackProc = nil);
procedure RotateBitmap(Bmp, Bitmap: TBitmap; Angle: Double; BackColor: TColor; CallBack : TProgressCallBackProc = nil);
//procedure SmoothResizeA(Width, Height : integer; S,D : TBitmap; CallBack : TProgressCallBackProc = nil);
procedure StrRotated(X, Y: Integer; arect: TRect; DC: HDC; Font: HFont; Str: string; Ang: Extended; Options: Cardinal);
procedure CoolDrawTextEx(bitmap:Tbitmap; text:string; Font: HFont; coolcount:integer; coolcolor:Tcolor; aRect : TRect; aType : integer; Options : Cardinal);
function GistogrammB(S : TBitmap; var Terminated : boolean; CallBack : TProgressCallBackProc = nil; X : Extended =1; Y : Extended =0) : T255IntArray;
function GistogrammG(S : TBitmap; var Terminated : boolean; CallBack : TProgressCallBackProc = nil; X : Extended =1; Y : Extended =0) : T255IntArray;
function GistogrammR(S : TBitmap; var Terminated : boolean; CallBack : TProgressCallBackProc = nil; X : Extended =1; Y : Extended =0) : T255IntArray;
function Gistogramma(S : TBitmap; var Terminated : boolean; CallBack : TProgressCallBackProc = nil; X : Extended =1; Y : Extended =0) : T255IntArray;
function GetGistogrammBitmap(Height: Integer; SBitmap: TBitmap; Options: Byte; var MinC, MaxC: Integer): TBitmap;
procedure GetGistogrammBitmapW(Height: Integer; Source: T255IntArray; var MinC, MaxC: Integer; Bitmap: TBitmap; Color: TColor);
procedure GetGistogrammBitmapWRGB(Height: Integer; SGray, SR, SG, SB: T255IntArray; var MinC, MaxC: Integer; Bitmap: TBitmap; BackColor: TColor);
function GetGistogrammBitmapX(Height,d : integer; G : T255IntArray; var MinC, MaxC : Integer) : TBitmap;
//new effects from ScineLineFX
procedure Emboss(S, D: TBitmap; CallBack : TProgressCallBackProc = nil);
procedure AntiAlias(S, D: TBitmap; CallBack : TProgressCallBackProc = nil);
procedure AddColorNoise(S, D: TBitmap; Amount : Integer; CallBack : TProgressCallBackProc = nil);
procedure AddMonoNoise(S, D: TBitmap; Amount : Integer; CallBack : TProgressCallBackProc = nil);
procedure FishEye(Bmp, Dst: TBitmap; xAmount: Integer; CallBack : TProgressCallBackProc = nil);
procedure Twist(Bmp, Dst: TBitmap; Amount: integer; CallBack : TProgressCallBackProc = nil);
procedure SplitBlur(S, D: TBitmap; Amount : Integer; CallBack : TProgressCallBackProc = nil);
procedure SplitBlurW(D: TBitmap; Amount : Integer; CallBack : TProgressCallBackProc = nil);
procedure GaussianBlur(D: TBitmap; Amount : Integer; CallBack : TProgressCallBackProc = nil);
procedure ProportionalSize(aWidth, aHeight: Integer; var aWidthToSize, aHeightToSize: Integer);
procedure ProportionalSizeX(aWidth, aHeight: Integer; var aWidthToSize, aHeightToSize: Integer);
implementation
procedure ProportionalSizeX(AWidth, AHeight: Integer; var AWidthToSize, AHeightToSize: Integer);
begin
if (AWidthToSize = 0) or (AHeightToSize = 0) then
begin
AHeightToSize := 0;
AWidthToSize := 0;
end else
begin
if (AHeightToSize / AWidthToSize) < (AHeight / AWidth) then
begin
AHeightToSize := Round((AWidth / AWidthToSize) * AHeightToSize);
AWidthToSize := AWidth;
end else
begin
AWidthToSize := Round((AHeight / AHeightToSize) * AWidthToSize);
AHeightToSize := AHeight;
end;
end;
end;
procedure ProportionalSize(AWidth, AHeight: Integer; var AWidthToSize, AHeightToSize: Integer);
begin
if (AWidthToSize < AWidth) and (AHeightToSize < AHeight) then
Exit;
if (AWidthToSize = 0) or (AHeightToSize = 0) then
begin
AHeightToSize := 0;
AWidthToSize := 0;
end else
begin
if (AHeightToSize / AWidthToSize) < (AHeight / AWidth) then
begin
AHeightToSize := Round((AWidth / AWidthToSize) * AHeightToSize);
AWidthToSize := AWidth;
end else
begin
AWidthToSize := Round((AHeight / AHeightToSize) * AWidthToSize);
AHeightToSize := AHeight;
end;
end;
end;
procedure Inverse(S, D: TBitmap; CallBack: TProgressCallBackProc = nil);
var
I, J: Integer;
PS, PD: PARGB;
Terminating: Boolean;
begin
S.PixelFormat := Pf24bit;
D.PixelFormat := Pf24bit;
D.Width := S.Width;
D.Height := S.Height;
Terminating := False;
for I := 0 to S.Height - 1 do
begin
PS := S.ScanLine[I];
PD := D.ScanLine[I];
for J := 0 to S.Width - 1 do
begin
PD[J].R := 255 - PS[J].R;
PD[J].G := 255 - PS[J].G;
PD[J].B := 255 - PS[J].B;
end;
if I mod 50 = 0 then
if Assigned(CallBack) then
CallBack(Round(100 * I / S.Height), Terminating);
if Terminating then
Break;
end;
end;
procedure GrayScaleImage(S, D: TBitmap; CallBack: TProgressCallBackProc = nil);
begin
GrayScaleImage(S, D, 100, CallBack);
end;
procedure GrayScaleImage(S,D : TBitmap; N : integer; CallBack : TProgressCallBackProc = nil);
var
I, J : Integer;
p1, p2 : PARGB;
W1, W2, GR : Byte;
Terminating : boolean;
begin
S.PixelFormat := pf24bit;
D.PixelFormat := pf24bit;
D.Width := S.Width;
D.Height := S.Height;
N := Min(100, Max(N, 0));
W1 := Round((N / 100)*255);
W2 := 255 - W1;
Terminating := False;
for I := 0 to S.Height - 1 do
begin
p1 := S.ScanLine[I];
p2 := D.ScanLine[I];
for J := 0 to S.Width - 1 do
begin
GR := (p1[j].R * 77 + p1[j].G * 151 + p1[j].B * 28) shr 8;
p2[j].R := (W2 * p1[j].R + W1 * GR) shr 8;
p2[j].G := (W2 * p1[j].G + W1 * GR) shr 8;
p2[j].B := (W2 * p1[j].B + W1 * GR) shr 8;
end;
if I mod 50 = 0 then
If Assigned(CallBack) then CallBack(Round(100*I / S.Height),Terminating);
if Terminating then Break;
end;
end;
procedure Sepia(S,D : TBitmap; CallBack : TProgressCallBackProc = nil);
begin
Sepia(S, D, 20, CallBack);
end;
procedure Sepia(S, D: TBitmap; Depth: Integer; CallBack: TProgressCallBackProc = nil);
var
Color2: Longint;
R, G, B, Rr, Gg: Byte;
I, J: Integer;
Ps, Pd: PARGB;
Terminating: Boolean;
begin
S.PixelFormat := pf24bit;
D.PixelFormat := pf24bit;
D.Width := S.Width;
D.Height := S.Height;
Terminating := False;
for I := 0 to S.Height - 1 do
begin
Ps := S.ScanLine[I];
PD := D.ScanLine[I];
for J := 0 to S.Width - 1 do
begin
R := Ps[J].R;
G := Ps[J].G;
B := Ps[J].B;
Color2 := (R + G + B) div 3;
R := Color2;
G := Color2;
B := Color2;
Rr := Min(255, R + (Depth * 2));
Gg := Min(255, G + Depth);
if Rr <= ((Depth * 2) - 1) then
Rr := 255;
if Gg <= (Depth - 1) then
Gg := 255;
Pd[J].R := Rr;
Pd[J].G := Gg;
Pd[J].B := B;
end;
if I mod 50 = 0 then
if Assigned(CallBack) then
CallBack(Round(100 * I / S.Height), Terminating);
if Terminating then
Break;
end;
end;
procedure Dither(S, D: TBitmap; CallBack : TProgressCallBackProc = nil);
var
ScanlS, ScanlD: PColor3Array;
Error1R, Error1G, Error1B, Error2R, Error2G, Error2B: PIntegerArray;
X, Y: Integer;
Dx: Integer;
C, CD: TColor3;
SR, SG, SB: Integer;
DR, DG, DB: Integer;
ER, EG, EB: Integer;
Terminating: Boolean;
procedure Swap(var p1, p2: PIntegerArray);
var
t: PIntegerArray;
begin
t := p1;
p1 := p2;
p2 := t;
end;
function clamp(x, min, max: integer): integer;
begin
result := x;
if result < min then
result := min
else
if result > max then
result := max;
end;
begin
D.Width := S.Width;
D.Height := S.Height;
S.PixelFormat := Pf24bit;
D.PixelFormat := Pf24bit;
Error1R := AllocMem((S.Width + 2) * Sizeof(Integer));
Error1G := AllocMem((S.Width + 2) * Sizeof(Integer));
Error1B := AllocMem((S.Width + 2) * Sizeof(Integer));
Error2R := AllocMem((S.Width + 2) * Sizeof(Integer));
Error2G := AllocMem((S.Width + 2) * Sizeof(Integer));
Error2B := AllocMem((S.Width + 2) * Sizeof(Integer));
Dx := 1;
Terminating := False;
for Y := 0 to S.Height - 1 do
begin
ScanlS := S.ScanLine[Y];
ScanlD := D.ScanLine[Y];
if Dx > 0 then
X := 0
else
X := S.Width - 1;
while (X >= 0) and (X < S.Width) do
begin
C := ScanlS[X];
SR := C.R;
SG := C.G;
SB := C.B;
ER := Error1R[X + 1];
// eG := error1G[x + 1];
// eB := error1B[x + 1];
DR := (SR * 16 + ER) div 16;
// dG := (sR * 16 + eR) div 16;
// dB := (sR * 16 + eR) div 16;
DR := Clamp(DR, 0, 255) and (255 shl 4);
DG := Clamp(DR, 0, 255) and (255 shl 4);
DB := Clamp(DR, 0, 255) and (255 shl 4);
CD.R := DR;
CD.G := DG;
CD.B := DB;
ScanlD[X] := CD;
ER := SR - DR;
EG := SG - DG;
EB := SB - DB;
Inc(Error1R[X + 1 + Dx], (ER * 7)); { next }
Inc(Error1G[X + 1 + Dx], (EG * 7));
Inc(Error1B[X + 1 + Dx], (EB * 7));
Inc(Error2R[X + 1], (ER * 5)); { top }
Inc(Error2G[X + 1], (EG * 5));
Inc(Error2B[X + 1], (EB * 5));
Inc(Error2R[X + 1 + Dx], (ER * 1)); { diag forward }
Inc(Error2G[X + 1 + Dx], (EG * 1));
Inc(Error2B[X + 1 + Dx], (EB * 1));
Inc(Error2R[X + 1 - Dx], (ER * 3)); { diag backward }
Inc(Error2G[X + 1 - Dx], (EG * 3));
Inc(Error2B[X + 1 - Dx], (EB * 3));
Inc(X, Dx);
end;
Dx := Dx * -1;
Swap(Error1R, Error2R);
Swap(Error1G, Error2G);
Swap(Error1B, Error2B);
FillChar(Error2R^, Sizeof(Integer) * (S.Width + 2), 0);
FillChar(Error2G^, Sizeof(Integer) * (S.Width + 2), 0);
FillChar(Error2B^, Sizeof(Integer) * (S.Width + 2), 0);
if Y mod 50 = 0 then
if Assigned(CallBack) then
CallBack(Round(100 * Y / S.Height), Terminating);
if Terminating then
Break;
end;
FreeMem(Error1R);
FreeMem(Error1G);
FreeMem(Error1B);
FreeMem(Error2R);
FreeMem(Error2G);
FreeMem(Error2B);
end;
procedure ChangeBrightness(S, D: TBitmap; Brightness: Integer);
var
LUT: array [Byte] of Byte;
V, I: Integer;
W, H, X, Y: Integer;
LineSize: LongInt;
PLineStartS, PLineStartD: PByte;
Ps, Pd: PByte;
begin
D.Width := S.Width;
D.Height := S.Height;
S.PixelFormat := Pf24bit;
D.PixelFormat := Pf24bit;
for I := 0 to 255 do
begin
V := I + Brightness;
if V < 0 then
V := 0
else if V > 255 then
V := 255;
LUT[I] := V;
end;
W := S.Width;
H := S.Height - 1;
PLineStartS := PByte(S.ScanLine[H]);
PLineStartD := PByte(D.ScanLine[H]);
LineSize := ((W * 3 + 3) div 4) * 4;
W := W * 3 - 1;
for Y := 0 to H do
begin
Ps := PLineStartS;
Pd := PLineStartD;
for X := 0 to W do
begin
Pd^ := LUT[Ps^];
Inc(Ps);
Inc(Pd);
end;
Inc(PLineStartS, LineSize);
Inc(PLineStartD, LineSize);
end;
end;
procedure ChangeBrightness(Image: TBitmap; Brightness: Integer);
var
LUT: array [Byte] of Byte;
V, I: Integer;
W, H, X, Y: Integer;
LineSize: LongInt;
PLineStartD: PByte;
Pd: PByte;
begin
Image.PixelFormat := Pf24bit;
for I := 0 to 255 do
begin
V := I + Brightness;
if V < 0 then
V := 0
else if V > 255 then
V := 255;
LUT[I] := V;
end;
W := Image.Width;
H := Image.Height - 1;
PLineStartD := PByte(Image.ScanLine[H]);
LineSize := ((W * 3 + 3) div 4) * 4;
W := W * 3 - 1;
for Y := 0 to H do
begin
Pd := PLineStartD;
for X := 0 to W do
begin
Pd^ := LUT[Pd^];
Inc(Pd);
end;
Inc(PLineStartD, LineSize);
end;
end;
procedure ChangeBrightness(Image : TArPARGB; Width, Height : integer; Brightness: Integer);
var
LUT: array [Byte] of Byte;
V, I: Integer;
X, Y: Integer;
begin
for I := 0 to 255 do
begin
V := I + Brightness;
if V < 0 then
V := 0
else if V > 255 then
V := 255;
LUT[I] := V;
end;
for Y := 0 to Height - 1 do
begin
for X := 0 to Width - 1 do
begin
Image[Y, X].R := LUT[Image[Y, X].R];
Image[Y, X].G := LUT[Image[Y, X].G];
Image[Y, X].B := LUT[Image[Y, X].B];
end;
end;
end;
procedure WaveSin(S, D: TBitmap; Frequency, Length:
Integer; Hor: Boolean; BackColor: TColor; CallBack : TProgressCallBackProc = nil);
function Min(A, B: Integer): Integer;
begin
if A < B then
Result := A
else
Result := B;
end;
function Max(A, B: Integer): Integer;
begin
if A > B then
Result := A
else
Result := B;
end;
const
Rad = Pi / 180;
type
TRGB = record
B, G, R: Byte;
end;
PRGB = ^TRGB;
var
C, X, Y, F: Integer;
Dest, Src: PRGB;
P: PARGB;
R, G, B: Byte;
Terminating: Boolean;
DPArr, SPArr : array of PRGB;
XA, YA : array of Integer;
begin
D.Width := S.Width;
D.Height := S.Height;
S.PixelFormat := pf24bit;
D.PixelFormat := pf24bit;
Terminating := False;
R := GetRValue(BackColor);
G := GetGValue(BackColor);
B := GetBValue(BackColor);
SetLength(DPArr, D.Height);
for Y := 0 to D.Height - 1 do
DPArr[Y] := D.ScanLine[Y];
SetLength(SPArr, S.Height);
for Y := 0 to S.Height - 1 do
SPArr[Y] := S.ScanLine[Y];
SetLength(YA, S.Height);
SetLength(XA, S.Width);
for Y := 0 to D.Height - 1 do
YA[Y] := Round(Sin(Y * Rad * Length) * Frequency);
for X := 0 to D.Width - 1 do
XA[X] := Round(Sin(X * Rad * Length) * Frequency);
for Y := 0 to D.Height - 1 do
begin
P := PARGB(DPArr[Y]);
for X := 0 to D.Width - 1 do
begin
P[X].R := R;
P[X].G := G;
P[X].B := B;
end;
end;
for Y := 0 to S.Height - 1 do
begin
Src := SPArr[Y];
if Hor then
begin
for X := 0 to S.Width - 1 do
begin
C := XA[X] + Y;
F := Min(Max(C, 0), D.Height - 1);
Dest := DPArr[F];
Inc(Dest, X);
Dest^ := Src^;
Inc(Src);
end;
end else
begin
for X := 0 to S.Width - 1 do
begin
C := YA[Y] + X;
F := Min(Max(C, 0), D.Width - 1);
Dest := DPArr[Y];
Inc(Dest, F);
Dest^ := Src^;
Inc(Src);
end;
end;
if Y mod 50 = 0 then
if Assigned(CallBack) then
CallBack(Round(100 * (Y / S.Height)), Terminating);
if Terminating then
Break;
end;
end;
procedure PixelsEffect(S, D: TBitmap; Hor, Ver: Word; CallBack : TProgressCallBackProc = nil);
type
TRGB = record
B, G, R: Byte;
end;
PRGB = ^TRGB;
TpRGB = array of PARGB;
var
I, J, X, Y, Xd, Yd, K, L, Rr, Gg, Bb, H, Hx, Hy, Dw1, Dh1: Integer;
Sour: PRGB;
Dp, Sp: TpRGB;
Terminating: Boolean;
begin
Terminating := False;
D.Width := S.Width;
D.Height := S.Height;
S.PixelFormat := Pf24bit;
D.PixelFormat := Pf24bit;
if (Hor = 1) and (Ver = 1) then
begin
AssignBitmap(D, S);
Exit;
end;
Dw1 := D.Width - 1;
Dh1 := D.Height - 1;
SetLength(Dp, D.Height);
for I := 0 to D.Height - 1 do
Dp[I] := D.ScanLine[I];
SetLength(Sp, S.Height);
for I := 0 to S.Height - 1 do
Sp[I] := S.ScanLine[I];
Xd := (S.Width - 1) div Hor;
Yd := (S.Height - 1) div Ver;
for I := 0 to Xd do
begin
Hx := Min(Hor * (I + 1), S.Width - 1);
for J := 0 to Yd do
begin
H := 0;
Rr := 0;
Gg := 0;
Bb := 0;
Hy := Min(Ver * (J + 1), S.Height - 1);
for Y := J * Ver to Hy do
begin
Sour := PRGB(Sp[Y]);
Inc(Sour, I * Hor);
for X := I * Hor to Hx do
begin
Inc(Rr, Sour^.R);
Inc(Gg, Sour^.G);
Inc(Bb, Sour^.B);
Inc(H);
Inc(Sour);
end;
end;
Rr := Rr div H;
Gg := Gg div H;
Bb := Bb div H;
for K := I * Hor to Min(Hx + 1, Dw1) do
for L := J * Ver to Min(Hy + 1, Dh1) do
begin
Dp[L, K].R := Rr;
Dp[L, K].G := Gg;
Dp[L, K].B := Bb;
end;
if I mod 25 = 0 then
if Assigned(CallBack) then
CallBack(Round(100 * (I / Xd)), Terminating);
if Terminating then
Break;
end;
end;
end;
procedure Sharpen(S, D: TBitmap; alpha: Single; CallBack : TProgressCallBackProc = nil);
//to sharpen, alpha must be >1.
//pixelformat pf24bit
//sharpens sbm to tbm
var
i, j, k: integer;
sr: array[0..2] of PByte;
st: array[0..4] of pRGBTriple;
tr: PByte;
tt, p: pRGBTriple;
beta: Single;
inta, intb: integer;
bmh, bmw: integer;
re, gr, bl: integer;
BytesPerScanline: integer;
Terminating : boolean;
begin
Terminating:=false;
//sharpening is blending of the current pixel
//with the average of the surrounding ones,
//but with a negative weight for the average
Assert((S.Width > 2) and (S.Height > 2), 'Bitmap must be at least 3x3');
Assert((alpha > 1) and (alpha < 6), 'Alpha must be >1 and <6');
beta := (alpha - 1) / 5; //we assume alpha>1 and beta<1
intb := round(beta * $10000);
inta := round(alpha * $10000); //integer scaled alpha and beta
S.PixelFormat := pf24bit;
D.PixelFormat := pf24bit;
D.Width := S.Width;
D.Height := S.Height;
bmw := S.Width - 2;
bmh := S.Height - 2;
BytesPerScanline := (((bmw + 2) * 24 + 31) and not 31) div 8;
tr := D.Scanline[0];
tt := pRGBTriple(tr);
sr[0] := S.Scanline[0];
st[0] := pRGBTriple(sr[0]);
for j := 0 to bmw + 1 do
begin
tt^ := st[0]^;
inc(tt); inc(st[0]); //first row unchanged
end;
sr[1] := PByte(NativeInt(sr[0]) - BytesPerScanline);
sr[2] := PByte(NativeInt(sr[1]) - BytesPerScanline);
for i := 1 to bmh do
begin
if i mod 50=0 then
If Assigned(CallBack) then CallBack(Round(100*i/bmh),Terminating);
if Terminating then Break;
Dec(tr, BytesPerScanline);
tt := pRGBTriple(tr);
st[0] := pRGBTriple(NativeInt(sr[0]) + 3); //top
st[1] := pRGBTriple(sr[1]); //left
st[2] := pRGBTriple(NativeInt(sr[1]) + 3); //center
st[3] := pRGBTriple(NativeInt(sr[1]) + 6); //right
st[4] := pRGBTriple(NativeInt(sr[2]) + 3); //bottom
tt^ := st[1]^; //1st col unchanged
for j := 1 to bmw do
begin
//calcutate average weighted by -beta
re := 0; gr := 0; bl := 0;
for k := 0 to 4 do
begin
re := re + st[k]^.rgbtRed;
gr := gr + st[k]^.rgbtGreen;
bl := bl + st[k]^.rgbtBlue;
inc(st[k]);
end;
re := (intb * re + $7FFF) shr 16;
gr := (intb * gr + $7FFF) shr 16;
bl := (intb * bl + $7FFF) shr 16;
//add center pixel weighted by alpha
p := pRGBTriple(st[1]); //after inc, st[1] is at center
re := (inta * p^.rgbtRed + $7FFF) shr 16 - re;
gr := (inta * p^.rgbtGreen + $7FFF) shr 16 - gr;
bl := (inta * p^.rgbtBlue + $7FFF) shr 16 - bl;
//clamp and move into target pixel
inc(tt);
if re < 0 then
re := 0
else
if re > 255 then
re := 255;
if gr < 0 then
gr := 0
else
if gr > 255 then
gr := 255;
if bl < 0 then
bl := 0
else
if bl > 255 then
bl := 255;
//this looks stupid, but avoids function calls
tt^.rgbtRed := re;
tt^.rgbtGreen := gr;
tt^.rgbtBlue := bl;
end;
inc(tt);
inc(st[1]);
tt^ := st[1]^; //Last col unchanged
sr[0] := sr[1];
sr[1] := sr[2];
Dec(sr[2], BytesPerScanline);
end;
// copy last row
Dec(tr, BytesPerScanline);
tt := pRGBTriple(tr);
st[1] := pRGBTriple(sr[1]);
for j := 0 to bmw + 1 do
begin
tt^ := st[1]^;
inc(tt); inc(st[1]);
end;
end;
procedure Blocks(S, D: TBitmap; Hor, Ver, MaxOffset: Integer; BackColor: TColor);
function RandomInRadius(Num, Radius: Integer): Integer;
begin
if Random(2) = 0 then
Result := Num + Random(Radius)
else
Result := Num - Random(Radius);
end;
var
X, Y, Xd, Yd: Integer;
begin
D.Width := S.Width;
D.Height := S.Height;
S.PixelFormat := pf24bit;
D.PixelFormat := pf24bit;
AssignBitmap(D, S);
D.Canvas.Brush.Color := BackColor;
D.Canvas.FillRect(Rect(0, 0, D.Width, D.Height));
Xd := (D.Width - 1) div Hor;
Yd := (D.Height - 1) div Ver;
Randomize;
for X := 0 to Xd do
for Y := 0 to Yd do
BitBlt(D.Canvas.Handle, RandomInRadius(Hor * X, MaxOffset), RandomInRadius(Ver * Y, MaxOffset), Hor, Ver,
S.Canvas.Handle, Hor * X, Ver * Y, SRCCOPY);
end;
procedure Gamma(S, D: TBitmap; L: Double);
{0.0 < L < 7.0}
function Power(Base, Exponent: Extended): Extended;
begin
Result := Exp(Exponent * Ln(Base));
end;
type
TRGB = record
B, G, R: Byte;
end;
pRGB = ^TRGB;
var
Sour, Dest: pRGB;
X, Y: Word;
GT: array[0..255] of Byte;
begin
D.Width := S.Width;
D.Height := S.Height;
S.PixelFormat := pf24bit;
D.PixelFormat := pf24bit;
GT[0] := 0;
if L = 0 then
L := 0.01;
for X := 1 to 255 do
GT[X] := Round(255 * Power(X / 255, 1 / L));
for Y := 0 to S.Height - 1 do
begin
Dest := D.ScanLine[y];
Sour := S.ScanLine[y];
for X := 0 to S.Width - 1 do
begin
with Dest^ do
begin
R := GT[Sour^.R];
G := GT[Sour^.G];
B := GT[Sour^.B];
end;
Inc(Dest);
Inc(Sour);
end;
end;
end;
procedure Gamma(Image: TBitmap; L: Double);
{0.0 < L < 7.0}
function Power(Base, Exponent: Extended): Extended;
begin
Result := Exp(Exponent * Ln(Base));
end;
type
TRGB = record
B, G, R: Byte;
end;
pRGB = ^TRGB;
var
Dest: pRGB;
X, Y: Word;
GT: array[0..255] of Byte;
begin
Image.PixelFormat := pf24bit;
GT[0] := 0;
if L = 0 then
L := 0.01;
for X := 1 to 255 do
GT[X] := Round(255 * Power(X / 255, 1 / L));
for Y := 0 to Image.Height - 1 do
begin
Dest := Image.ScanLine[y];
for X := 0 to Image.Width - 1 do
begin
with Dest^ do
begin
R := GT[R];
G := GT[G];
B := GT[B];
end;
Inc(Dest);
end;
end;
end;
procedure SetRGBChannelValue(S, D: TBitmap; Red, Green, Blue: Integer);
var
I, J: Integer;
PS, PD : PARGB;
RuleArrayR, RuleArrayG, RuleArrayB : array[0..255] of byte;
begin
S.PixelFormat := pf24bit;
D.PixelFormat := pf24bit;
D.Width := S.Width;
D.Height := S.Height;
if (Red = 0) and (Green = 0) and (Blue = 0) then
begin
AssignBitmap(D, S);
Exit;
end;
for I := 0 to 255 do
begin
RuleArrayR[I] := Round(Min(255, Max(0, I * (1 + (Red / 100)))));
RuleArrayG[I] := Round(Min(255, Max(0, I * (1 + (Green / 100)))));
RuleArrayB[I] := Round(Min(255, Max(0, I * (1 + (Blue / 100)))));
end;
for I := 0 to S.Height - 1 do
begin
PS := S.ScanLine[I];
PD := D.ScanLine[I];
for J := 0 to S.Width - 1 do
begin
PD[J].R := RuleArrayR[PS[J].R];
PD[J].G := RuleArrayR[PS[J].G];
PD[J].B := RuleArrayR[PS[J].B];
end;
end;
end;
procedure SetRGBChannelValue(Image: TBitmap; Red, Green, Blue: Integer);
var
I, J: Integer;
PD: PARGB;
RuleArrayR, RuleArrayG, RuleArrayB: array [0 .. 255] of Byte;
begin
Image.PixelFormat := Pf24bit;
if (Red = 0) and (Green = 0) and (Blue = 0) then
Exit;
for I := 0 to 255 do
begin
RuleArrayR[I] := Round(Min(255, Max(0, I * (1 + (Red / 100)))));
RuleArrayG[I] := Round(Min(255, Max(0, I * (1 + (Green / 100)))));
RuleArrayB[I] := Round(Min(255, Max(0, I * (1 + (Blue / 100)))));
end;
for I := 0 to Image.Height - 1 do
begin
PD := Image.ScanLine[I];
for J := 0 to Image.Width - 1 do
begin
PD[J].R := RuleArrayR[PD[J].R];
PD[J].G := RuleArrayR[PD[J].G];
PD[J].B := RuleArrayR[PD[J].B];
end;
end;
end;
procedure SetRGBChannelValue(Image: TArPARGB; Width, Height: Integer; Red, Green, Blue: Integer); overload;
var
I, J: Integer;
Rx, Gx, Bx: Extended;
RArray, GArray, BArray: T255ByteArray;
begin
if (Red = 0) and (Green = 0) and (Blue = 0) then
begin
Exit;
end;
Rx := 1 + (Red / 100);
Gx := 1 + (Green / 100);
Bx := 1 + (Blue / 100);
for I := 0 to 255 do
begin
RArray[I] := Round(Min(255, Max(0, I * (Rx))));
GArray[I] := Round(Min(255, Max(0, I * (Gx))));
BArray[I] := Round(Min(255, Max(0, I * (Bx))));
end;
for I := 0 to Height - 1 do
begin
for J := 0 to Width - 1 do
begin
Image[I, J].R := RArray[Image[I, J].R];
Image[I, J].G := GArray[Image[I, J].G];
Image[I, J].B := BArray[Image[I, J].B];
end;
end;
end;
procedure Disorder(S, D: TBitmap; CallBack: TProgressCallBackProc = nil);
begin
Disorder(S, D, 10, 10, $0, CallBack);
end;
procedure Disorder(S, D: TBitmap; Hor, Ver: Integer; BackColor: TColor; CallBack : TProgressCallBackProc = nil);
function RandomInRadius(Num, Radius: Integer): Integer;
begin
if Random(2) = 0 then
Result := Num + Random(Radius)
else
Result := Num - Random(Radius);
end;
type
TRGB = record
B, G, R: Byte;
end;
pRGB = ^TRGB;
var
i, x, y, WW, HH, xr, yr: Integer;
Terminate : Boolean;
xS, xD : TArPARGB;
r,g,b : Byte;
begin
D.Width := S.Width;
D.Height := S.Height;
S.PixelFormat := Pf24bit;
D.PixelFormat := Pf24bit;
Setlength(XS, S.Height);
for I := 0 to S.Height - 1 do
XS[I] := S.ScanLine[I];
Setlength(XD, D.Height);
for I := 0 to D.Height - 1 do
XD[I] := D.ScanLine[I];
Randomize;
Terminate := False;
try
WW := S.Width - 1;
HH := S.Height - 1;
r:=GetRValue(BackColor);
g:=GetGValue(BackColor);
b:=GetBValue(BackColor);
for y := 0 to HH do
begin
for x := 0 to WW do
begin
xD[y,x].r:=r;
xD[y,x].g:=g;
xD[y,x].b:=b;
end;
if y mod 50=0 then
if Assigned(CallBack) then CallBack(Round(y*100*(0.3/hh)+20),Terminate);
if Terminate then break;
end;
if not Terminate then
for y := 0 to HH do
begin
for x := 0 to WW do
begin
xr := RandomInRadius(x, Hor);
yr := RandomInRadius(y, Ver);
if (xr >= 0) and (xr < WW) and (yr >= 0) and (yr < HH) then
begin
xD[y,x]:=xS[yr,xr];
xD[yr,xr]:=xS[y,x];
end;
end;
if y mod 50=0 then
if Assigned(CallBack) then CallBack(Round(y*100*(0.5/hh)+50),Terminate);
if Terminate then break;
end;
finally
end;
end;
procedure Contrast(S, D: TBitmap; Value: Extended; Local: Boolean);
function BLimit(B: Integer): Byte; inline;
begin
if B < 0 then
Result := 0
else if B > 255 then
Result := 255
else
Result := B;
end;
var
Dest, Sour: pRGBTriple;
x, y, mr, mg, mb,
W, H, tr, tg, tb: Integer;
vd: Double;
begin
D.Width := S.Width;
D.Height := S.Height;
S.PixelFormat := pf24bit;
D.PixelFormat := pf24bit;
if Value = 0 then
begin
AssignBitmap(D, S);
Exit;
end;
W := S.Width - 1;
H := S.Height - 1;
if Local then
begin
mR := 128;
mG := 128;
mB := 128;
end
else
begin
tr := 0;
tg := 0;
tb := 0;
for y := 0 to H do
begin
Dest := D.ScanLine[y];
Sour := S.ScanLine[y];
for x := 0 to W do
begin
with Dest^ do
begin
Inc(tb, Sour^.rgbtRed);
Inc(tg, Sour^.rgbtGreen);
Inc(tr, Sour^.rgbtBlue);
end;
Inc(Dest);
Inc(Sour);
end;
end;
mB := Trunc(tb / (W * H));
mG := Trunc(tg / (W * H));
mR := Trunc(tr / (W * H));
end;
if Value > 0 then
vd := 1 + (Value / 10)
else
vd := 1 - (Sqrt(-Value) / 10);
for y := 0 to H do
begin
Dest := D.ScanLine[y];
Sour := S.ScanLine[y];
for x := 0 to W do
begin
with Dest^ do
begin
rgbtRed := BLimit(mB + Trunc((Sour^.rgbtRed - mB) * vd));
rgbtGreen := BLimit(mG + Trunc((Sour^.rgbtGreen - mG) * vd));
rgbtBlue := BLimit(mR + Trunc((Sour^.rgbtBlue - mR) * vd));
end;
Inc(Dest);
Inc(Sour);
end;
end;
end;
procedure Contrast(Image: TBitmap; Value: Extended; Local: Boolean);
function BLimit(B: Integer): Byte; inline;
begin
if B < 0 then
Result := 0
else if B > 255 then
Result := 255
else
Result := B;
end;
var
Dest : pRGBTriple;
x, y, mr, mg, mb,
W, H, tr, tg, tb: Integer;
vd: Double;
begin
Image.PixelFormat := pf24bit;
W := Image.Width - 1;
H := Image.Height - 1;
if Local then
begin
mR := 128;
mG := 128;
mB := 128;
end else
begin
tr := 0;
tg := 0;
tb := 0;
for y := 0 to H do
begin
Dest := Image.ScanLine[y];
for x := 0 to W do
begin
with Dest^ do
begin
Inc(tb, Dest^.rgbtRed);
Inc(tg, Dest^.rgbtGreen);
Inc(tr, Dest^.rgbtBlue);
end;
Inc(Dest);
end;
end;
mB := Trunc(tb / (W * H));
mG := Trunc(tg / (W * H));
mR := Trunc(tr / (W * H));
end;
if Value > 0 then
vd := 1 + (Value / 10)
else
vd := 1 - (Sqrt(-Value) / 10);
for y := 0 to H do
begin
Dest := Image.ScanLine[y];
for x := 0 to W do
begin
with Dest^ do
begin
rgbtRed := BLimit(mB + Trunc((rgbtRed - mB) * vd));
rgbtGreen := BLimit(mG + Trunc((rgbtGreen - mG) * vd));
rgbtBlue := BLimit(mR + Trunc((rgbtBlue - mR) * vd));
end;
Inc(Dest);
end;
end;
end;
procedure Contrast(Image: TArPARGB; Width, Height : integer; Value: Extended; Local: Boolean);
function BLimit(B: Integer): Byte;
begin
if B < 0 then
Result := 0
else if B > 255 then
Result := 255
else
Result := B;
end;
var
x, y, {mr, mg,} mb,
i, W, H, {tr, tg, }tb: Integer;
vd: Double;
ContrastArray : T255ByteArray;
begin
W := Width - 1;
H := Height - 1;
if Local then
begin
// mR := 128;
// mG := 128;
mB := 128;
end else
begin
// tr := 0;
// tg := 0;
tb := 0;
for y := 0 to H do
begin
for x := 0 to W do
begin
Inc(tb,Image[y,x].b);
// Inc(tg,Image[y,x].g);
// Inc(tr,Image[y,x].r);
end;
end; {Trunc}
mB := Round(tb / (W * H));
// mG := Round(tg / (W * H));
// mR := Round(tr / (W * H));
end;
if Value > 0 then
vd := 1 + (Value / 10)
else
vd := 1 - (Sqrt(-Value) / 10);
for i:=0 to 255 do
ContrastArray[i]:=BLimit(mB + Round((i - mB) * vd));
for y := 0 to H do
begin
for x := 0 to W do
begin
Image[y,x].r:=ContrastArray[Image[y,x].r];
Image[y,x].g:=ContrastArray[Image[y,x].g];
Image[y,x].b:=ContrastArray[Image[y,x].b];
end;
end;
end;
procedure Colorize(S, D: TBitmap; Luma: Integer);
var
Ps, Pd: PARGB;
I, J: Integer;
LumMatrix: array [0 .. 255] of Byte;
begin
S.PixelFormat := Pf24bit;
D.PixelFormat := Pf24bit;
D.Width := S.Width;
D.Height := S.Height;
for I := 0 to 255 do
LumMatrix[I] := Round(Min(255, I * Luma / 255));
for I := 0 to S.Height - 1 do
begin
Ps := S.ScanLine[I];
Pd := D.ScanLine[I];
for J := 0 to S.Width - 1 do
begin
Pd[J].R := LumMatrix[Ps[J].R];
Pd[J].G := LumMatrix[Ps[J].G];
Pd[J].B := LumMatrix[Ps[J].B];
end;
end;
end;
function Gistogramma(S: TBitmap; var Terminated: Boolean; CallBack: TProgressCallBackProc = nil; X: Extended = 1;
Y: Extended = 0): T255IntArray;
var
I, J: Integer;
Ps: PARGB;
L: Byte;
Terminating: Boolean;
begin
S.PixelFormat := Pf24bit;
for I := 0 to 255 do
Result[I] := 0;
Terminating := False;
Terminated := False;
for I := 0 to S.Height - 1 do
begin
Ps := S.ScanLine[I];
for J := 0 to S.Width - 1 do
begin
L := (Ps[J].R * 77 + Ps[J].G * 151 + Ps[J].B * 28) shr 8;
Inc(Result[L]);
end;
if I mod 50 = 0 then
if Assigned(CallBack) then
CallBack(Round(100 * (I * X / S.Height + Y)), Terminating);
if Terminating then
begin
Terminated := True;
Break;
end;
end;
end;
function GistogrammR(S: TBitmap; var Terminated: Boolean; CallBack: TProgressCallBackProc = nil; X: Extended = 1;
Y: Extended = 0): T255IntArray;
var
I, J: Integer;
Ps: PARGB;
Terminating: Boolean;
begin
S.PixelFormat := Pf24bit;
for I := 0 to 255 do
Result[I] := 0;
Terminating := False;
Terminated := False;
for I := 0 to S.Height - 1 do
begin
Ps := S.ScanLine[I];
for J := 0 to S.Width - 1 do
begin
Inc(Result[Ps[J].R]);
end;
if I mod 50 = 0 then
if Assigned(CallBack) then
CallBack(Round(100 * (I * X / S.Height + Y)), Terminating);
if Terminating then
begin
Terminated := True;
Break;
end;
end;
end;
function GistogrammG(S: TBitmap; var Terminated: Boolean; CallBack: TProgressCallBackProc = nil; X: Extended = 1;
Y: Extended = 0): T255IntArray;
var
I, J: Integer;
Ps: PARGB;
Terminating: Boolean;
begin
S.PixelFormat := Pf24bit;
for I := 0 to 255 do
Result[I] := 0;
Terminating := False;
Terminated := False;
for I := 0 to S.Height - 1 do
begin
Ps := S.ScanLine[I];
for J := 0 to S.Width - 1 do
begin
Inc(Result[Ps[J].G]);
end;
if I mod 50 = 0 then
if Assigned(CallBack) then
CallBack(Round(100 * (I * X / S.Height + Y)), Terminating);
if Terminating then
begin
Terminated := True;
Break;
end;
end;
end;
function GistogrammB(S: TBitmap; var Terminated: Boolean; CallBack: TProgressCallBackProc = nil; X: Extended = 1;
Y: Extended = 0): T255IntArray;
var
I, J: Integer;
Ps: PARGB;
Terminating: Boolean;
begin
S.PixelFormat := Pf24bit;
for I := 0 to 255 do
Result[I] := 0;
Terminating := False;
Terminated := False;
for I := 0 to S.Height - 1 do
begin
Ps := S.ScanLine[I];
for J := 0 to S.Width - 1 do
begin
Inc(Result[Ps[J].B]);
end;
if I mod 50 = 0 then
if Assigned(CallBack) then
CallBack(Round(100 * (I * X / S.Height + Y)), Terminating);
if Terminating then
begin
Terminated := True;
Break;
end;
end;
end;
procedure AutoLevels(S, D: TBitmap; CallBack: TProgressCallBackProc = nil);
var
Ps, Pd: PARGB;
I, J, MinCount: Integer;
L: Byte;
Count: Int64;
RL: T255ByteArray;
Gistogramm: T255IntArray;
Terminated: Boolean;
Terminating: Boolean;
begin
D.Width := S.Width;
D.Height := S.Height;
S.PixelFormat := Pf24bit;
D.PixelFormat := Pf24bit;
Gistogramm := Gistogramma(S, Terminated, CallBack, 0.5);
if Terminated then
Exit;
MinCount := (S.Height div 50) * (S.Width div 50);
Count := 0;
L := 0;
for I := 255 downto 0 do
begin
Inc(Count, Gistogramm[I]);
if Count > MinCount then
begin
L := I;
Break;
end;
end;
if L = 0 then
L := 1;
for I := 0 to 255 do
begin
RL[I] := Min(255, Round((255 / L) * I));
end;
Terminating := False;
for I := 0 to S.Height - 1 do
begin
Ps := S.ScanLine[I];
Pd := D.ScanLine[I];
for J := 0 to S.Width - 1 do
begin
Pd[J].R := Rl[Ps[J].R];
Pd[J].G := Rl[Ps[J].G];
Pd[J].B := Rl[Ps[J].B];
end;
if I mod 50 = 0 then
if Assigned(CallBack) then
CallBack(Round(100 * (I * 0.5 / S.Height + 0.5)), Terminating);
if Terminating then
Break;
end;
end;
procedure AutoColors(S, D: TBitmap; CallBack: TProgressCallBackProc = nil);
var
Ps, Pd: PARGB;
I, J, MinCount: Integer;
Count: Int64;
R, G, B: Byte;
Rx, Bx, Gx: T255ByteArray;
GistogrammaR, GistogrammaG, GistogrammaB: T255IntArray;
Terminated, Terminating: Boolean;
begin
D.Width := S.Width;
D.Height := S.Height;
S.PixelFormat := Pf24bit;
D.PixelFormat := Pf24bit;
GistogrammaR := GistogrammR(S, Terminated, CallBack, 0.25, 0);
if Terminated then
Exit;
GistogrammaG := GistogrammG(S, Terminated, CallBack, 0.25, 0.25);
if Terminated then
Exit;
GistogrammaB := GistogrammB(S, Terminated, CallBack, 0.25, 0.5);
if Terminated then
Exit;
Count := 0;
R := 0;
G := 0;
B := 0;
MinCount := (S.Height div 10) * (S.Width div 10);
for I := 255 downto 0 do
begin
Inc(Count, GistogrammaR[I]);
if Count > MinCount then
begin
R := I;
Break;
end;
end;
Count := 0;
for I := 255 downto 0 do
begin
Inc(Count, GistogrammaG[I]);
if Count > MinCount then
begin
G := I;
Break;
end;
end;
Count := 0;
for I := 255 downto 0 do
begin
Inc(Count, GistogrammaB[I]);
if Count > MinCount then
begin
B := I;
Break;
end;
end;
if R = 0 then
R := 1;
if G = 0 then
G := 1;
if B = 0 then
B := 1;
for I := 0 to 255 do
begin
Rx[I] := Min(255, Round((255 / R) * I));
Gx[I] := Min(255, Round((255 / G) * I));
Bx[I] := Min(255, Round((255 / B) * I));
end;
Terminating := False;
for I := 0 to S.Height - 1 do
begin
Ps := S.ScanLine[I];
Pd := D.ScanLine[I];
for J := 0 to S.Width - 1 do
begin
Pd[J].R := Rx[Ps[J].R];
Pd[J].G := Gx[Ps[J].G];
Pd[J].B := Bx[Ps[J].B];
end;
if I mod 50 = 0 then
if Assigned(CallBack) then
CallBack(Round(100 * (I * 0.25 / S.Height + 0.75)), Terminating);
if Terminating then
Break;
end;
end;
function GistogrammRW(S: TBitmap; Rect: TRect; var CountR: Int64): T255IntArray;
var
I, J: Integer;
Ps: PARGB;
begin
S.PixelFormat := Pf24bit;
for I := 0 to 255 do
Result[I] := 0;
CountR := 0;
for I := Max(0, Rect.Top) to Min(Rect.Bottom - 1, S.Height - 1) do
begin
Ps := S.ScanLine[I];
for J := Max(0, Rect.Left) to Min(Rect.Right - 1, S.Width - 1) do
if Ps[J].R > Max(Ps[J].G, Ps[J].B) then
begin
Inc(CountR, 1);
Inc(Result[Ps[J].R - Max(Ps[J].G, Ps[J].B)], 1);
end;
end;
end;
procedure Rotate180(S, D: Tbitmap; CallBack: TProgressCallBackProc = nil);
var
I, J: Integer;
P1, P2: Pargb;
Terminating: Boolean;
begin
S.PixelFormat := Pf24bit;
D.PixelFormat := Pf24bit;
D.Width := S.Width;
D.Height := S.Height;
Terminating := False;
for I := 0 to S.Height - 1 do
begin
P1 := S.ScanLine[I];
P2 := D.ScanLine[S.Height - I - 1];
for J := 0 to S.Width - 1 do
P2[J] := P1[S.Width - 1 - J];
if I mod 50 = 0 then
if Assigned(CallBack) then
CallBack(Round(100 * (I * 0.25 / S.Height + 0.75)), Terminating);
if Terminating then
begin
Break;
end;
end;
end;
procedure Rotate270(S, D: Tbitmap; CallBack: TProgressCallBackProc = nil);
var
I, J: Integer;
P1: Pargb;
P: array of Pargb;
Terminating: Boolean;
begin
S.PixelFormat := Pf24bit;
D.PixelFormat := Pf24bit;
D.Width := S.Height;
D.Height := S.Width;
Setlength(P, S.Width);
for I := 0 to S.Width - 1 do
P[I] := D.ScanLine[S.Width - 1 - I];
Terminating := False;
for I := 0 to S.Height - 1 do
begin
P1 := S.ScanLine[I];
for J := 0 to S.Width - 1 do
P[J, I] := P1[J];
if I mod 50 = 0 then
if Assigned(CallBack) then
CallBack(Round(100 * (I * 0.25 / S.Height + 0.75)), Terminating);
if Terminating then
begin
Break;
end;
end;
end;
procedure Rotate90(S,D : tbitmap; CallBack : TProgressCallBackProc = nil);
var
i, j : integer;
p1 : pargb;
p : array of pargb;
Terminating : Boolean;
begin
S.PixelFormat:=pf24bit;
D.PixelFormat:=pf24bit;
D.Width:=S.Height;
D.Height:=S.Width;
setlength(p,S.Width);
for i:=0 to S.Width-1 do
p[i]:=D.ScanLine[i];
Terminating:=false;
for i:=0 to S.Height-1 do
begin
p1:=S.ScanLine[S.Height-i-1];
for j:=0 to S.Width-1 do
begin
p[j,i]:=p1[j];
end;
if i mod 50=0 then
If Assigned(CallBack) then CallBack(Round(100*(i*0.25/S.Height+0.75)),Terminating);
if Terminating then
begin
Break;
end;
end;
end;
procedure FlipHorizontal(S,D : TBitmap; CallBack : TProgressCallBackProc = nil);
var
i,j : integer;
ps, pd : PARGB;
Terminating : Boolean;
begin
S.PixelFormat:=pf24bit;
D.PixelFormat:=pf24bit;
D.Width:=S.Width;
D.Height:=S.Height;
Terminating:=false;
for i:=0 to S.Height-1 do
begin
ps:=S.ScanLine[i];
pd:=D.ScanLine[i];
for j:=0 to S.Width-1 do
begin
pd[j]:=ps[S.Width-1-j];
end;
if i mod 50=0 then
If Assigned(CallBack) then CallBack(Round(100*(i*0.25/S.Height+0.75)),Terminating);
if Terminating then
begin
Break;
end;
end;
end;
procedure FlipVertical(S,D : TBitmap; CallBack : TProgressCallBackProc = nil);
var
i,j : integer;
ps, pd : PARGB;
Terminating : Boolean;
begin
S.PixelFormat:=pf24bit;
D.PixelFormat:=pf24bit;
D.Width:=S.Width;
D.Height:=S.Height;
Terminating:=false;
for i:=0 to S.Height-1 do
begin
ps:=S.ScanLine[i];
pd:=D.ScanLine[S.Height-1-i];
for j:=0 to S.Width-1 do
begin
pd[j]:=ps[j];
end;
if i mod 50=0 then
If Assigned(CallBack) then CallBack(Round(100*(i*0.25/S.Height+0.75)),Terminating);
if Terminating then
begin
Break;
end;
end;
end;
procedure RotateBitmap(Bmp, Bitmap: TBitmap; Angle: Double; BackColor: TColor; CallBack : TProgressCallBackProc = nil);
type TRGB = record
B, G, R: Byte;
end;
pRGB = ^TRGB;
pByteArray = ^TByteArray;
TByteArray = array[0..32767] of Byte;
TRectList = array [1..4] of TPoint;
var
x, y, W, H, v1, v2: Integer;
Dest, Src: pRGB;
VertArray: array of pByteArray;
// Bmp: TBitmap;
Terminating: boolean;
p: PARGB;
rgb: TRGB;
procedure SinCos(AngleRad: Double; var ASin, ACos: Double);
begin
ASin := Sin(AngleRad);
ACos := Cos(AngleRad);
end;
function RotateRect(const Rect: TRect; const Center: TPoint; Angle: Double): TRectList;
var DX, DY: Integer;
SinAng, CosAng: Double;
function RotPoint(PX, PY: Integer): TPoint;
begin
DX := PX - Center.x;
DY := PY - Center.y;
Result.x := Center.x + Round(DX * CosAng - DY * SinAng);
Result.y := Center.y + Round(DX * SinAng + DY * CosAng);
end;
begin
SinCos(Angle * (Pi / 180), SinAng, CosAng);
Result[1] := RotPoint(Rect.Left, Rect.Top);
Result[2] := RotPoint(Rect.Right, Rect.Top);
Result[3] := RotPoint(Rect.Right, Rect.Bottom);
Result[4] := RotPoint(Rect.Left, Rect.Bottom);
end;
function Min(A, B: Integer): Integer;
begin
if A < B then Result := A
else Result := B;
end;
function Max(A, B: Integer): Integer;
begin
if A > B then Result := A
else Result := B;
end;
function GetRLLimit(const RL: TRectList): TRect;
begin
Result.Left := Min(Min(RL[1].x, RL[2].x), Min(RL[3].x, RL[4].x));
Result.Top := Min(Min(RL[1].y, RL[2].y), Min(RL[3].y, RL[4].y));
Result.Right := Max(Max(RL[1].x, RL[2].x), Max(RL[3].x, RL[4].x));
Result.Bottom := Max(Max(RL[1].y, RL[2].y), Max(RL[3].y, RL[4].y));
end;
procedure Rotate;
var
I, X, Y, Xr, Yr, Yp: Integer;
ACos, ASin: Double;
Lim: TRect;
YPSin, YPCos : Integer;
XWAC, XWAS : array of Integer;
SrcAr: array of pRGB;
begin
W := Bmp.Width;
H := Bmp.Height;
SinCos(-Angle * Pi / 180, ASin, ACos);
Lim := GetRLLimit(RotateRect(Rect(0, 0, Bmp.Width, Bmp.Height), Point(0, 0), Angle));
Bitmap.Width := Lim.Right - Lim.Left;
Bitmap.Height := Lim.Bottom - Lim.Top;
Rgb.R := GetRValue(BackColor);
Rgb.G := GetGValue(BackColor);
Rgb.B := GetBValue(BackColor);
SetLength(XWAS, Bitmap.Width);
SetLength(XWAC, Bitmap.Width);
for I := 0 to Bitmap.Width - 1 do
begin
XWAC[I] := Round((I + Lim.Left) * ACos);
XWAS[I] := Round((I + Lim.Left) * ASin);
end;
SetLength(SrcAr, Bmp.Height);
for I := 0 to Bmp.Height - 1 do
SrcAr[I] := Bmp.ScanLine[I];
for Y := 0 to Bitmap.Height - 1 do
begin
Dest := Bitmap.ScanLine[Y];
P := PARGB(Dest);
for X := 0 to Bitmap.Width - 1 do
begin
P[X].R := Rgb.R;
P[X].G := Rgb.G;
P[X].B := Rgb.B;
end;
Yp := Y + Lim.Top;
YPSin := Round(Yp * ASin);
YPCos := Round(Yp * ACos);
for X := 0 to Bitmap.Width - 1 do
begin
Xr := XWAC[X] - YPSin;
Yr := XWAS[X] + YPCos;
if (Xr > -1) and (Xr < W) and (Yr > -1) and (Yr < H) then
begin
Src := SrcAr[Yr];
Inc(Src, Xr);
Dest^ := Src^;
end;
Inc(Dest);
end;
if Y mod 50 = 0 then
if Assigned(CallBack) then
CallBack(Round(100 * Y / Bitmap.Height), Terminating);
if Terminating then
Break;
end;
end;
{function TrimInt(i,Min,Max:Integer):Integer;
begin
if i>Max then Result:=Max
else if i<Min then Result:=Min
else Result:=i;
end;
function IntToByte(i:Integer):Byte;
begin
if i>255 then Result:=255
else if i<0 then Result:=0
else Result:=i;
end;
procedure SmoothRotate;
var
Top,
Bottom,
Left,
Right,
eww,nsw,
fx,fy,
wx,wy, Theta: Extended;
cAngle,
sAngle: Double;
xDiff,
yDiff,
ifx,ify,
px,py,
ix,iy,
x,y, gap: Integer;
nw,ne,
sw,se: TRGB;
Tmp: PRGB;
Line: Pointer;
begin
Theta:=Abs(Angle)*(Pi/180);
x:=Round(Abs(Bmp.Width*Cos(Theta))+Abs(Bmp.Height*Sin(Theta))+0.4);
y:=Round(Abs(Bmp.Width*Sin(Theta))+Abs(Bmp.Height*Cos(Theta))+0.4);
Bitmap.SetSize(x, y);
Bitmap.PixelFormat := pf24bit;
Angle:=-Angle*Pi/180;
sAngle:=Sin(Angle);
cAngle:=Cos(Angle);
xDiff:=(Bitmap.Width-Bmp.Width)div 2;
yDiff:=(Bitmap.Height-Bmp.Height)div 2;
Line:=Bitmap.ScanLine[0];
gap := NativeInt(Bitmap.ScanLine[1]) - NativeInt(Line);
for y:=0 to Bitmap.Height-1 do
begin
Tmp := Line;
py:=2*(y)+1;
for x:=0 to Bitmap.Width-1 do
begin
px:=2*(x)+1;
fx:=(((px*cAngle-py*sAngle)-1)/ 2)-xDiff;
fy:=(((px*sAngle+py*cAngle)-1)/ 2)-yDiff;
ifx:=Round(fx);
ify:=Round(fy);
if(ifx>-1)and(ifx<Bmp.Width)and(ify>-1)and(ify<Bmp.Height)then
begin
eww:=fx-ifx;
nsw:=fy-ify;
iy:=TrimInt(ify+1,0,Bmp.Height-1);
ix:=TrimInt(ifx+1,0,Bmp.Width-1);
nw:=PARGB(Bmp.ScanLine[ify])[ifx];
ne:=PARGB(Bmp.ScanLine[ify])[ix];
sw:=PARGB(Bmp.ScanLine[iy])[ifx];
se:=PARGB(Bmp.ScanLine[iy])[ix];
Top:=nw.b+eww*(ne.b-nw.b);
Bottom:=sw.b+eww*(se.b-sw.b);
Tmp.b:=IntToByte(Round(Top+nsw*(Bottom-Top)));
Top:=nw.g+eww*(ne.g-nw.g);
Bottom:=sw.g+eww*(se.g-sw.g);
Tmp.g:=IntToByte(Round(Top+nsw*(Bottom-Top)));
Top:=nw.r+eww*(ne.r-nw.r);
Bottom:=sw.r+eww*(se.r-sw.r);
Tmp.r:=IntToByte(Round(Top+nsw*(Bottom-Top)));
end;
Inc(Tmp);
end;
Line:=Pointer(NativeInt(Line)+gap);
end;
end; }
begin
Terminating := False;
Bitmap.PixelFormat := pf24Bit;
W := Bitmap.Width - 1;
H := Bitmap.Height - 1;
if Frac(Angle) <> 0.0
then Rotate
else
case Trunc(Angle) of
-360, 0, 360, 720: AssignBitmap(Bitmap, Bmp);
90, 270: begin
Bitmap.Width := H + 1;
Bitmap.Height := W + 1;
SetLength(VertArray, H + 1);
v1 := 0;
v2 := 0;
if Angle = 90.0 then v1 := H
else v2 := W;
for y := 0 to H do VertArray[y] := Bmp.ScanLine[Abs(v1 - y)];
for x := 0 to W do
begin
Dest := Bitmap.ScanLine[x];
for y := 0 to H do
begin
v1 := Abs(v2 - x)*3;
with Dest^ do
begin
B := VertArray[y, v1];
G := VertArray[y, v1+1];
R := VertArray[y, v1+2];
end;
Inc(Dest);
end;
if x mod 50=0 then
If Assigned(CallBack) then CallBack(Round(100*x/W),Terminating);
if Terminating then Break;
end
end;
180: begin
for y := 0 to H do
begin
Dest := Bitmap.ScanLine[y];
Src := Bmp.ScanLine[H - y];
Inc(Src, W);
for x := 0 to W do
begin
Dest^ := Src^;
Dec(Src);
Inc(Dest);
end;
if y mod 50=0 then
If Assigned(CallBack) then CallBack(Round(100*y/Bitmap.Height),Terminating);
if Terminating then Break;
end;
end;
else Rotate;
end;
end;
procedure StrRotated(X, Y: Integer; Arect: TRect; DC: HDC; Font: HFont; Str: string; Ang: Extended; Options: Cardinal);
var
NXF, OXF: TXForm;
S: TStrings;
FNew, FOld: HFont;
begin
FNew := Font;
FOld := SelectObject(DC, FNew);
S := TStringList.Create;
S.Text := Str;
SetGraphicsMode(DC, GM_Advanced);
GetWorldTransform(DC, OXF);
NXF.EM11 := Cos(Ang * Pi / 180);
NXF.EM22 := Cos(Ang * Pi / 180);
NXF.EM12 := Sin(Ang * Pi / 180);
NXF.EM21 := -Sin(Ang * Pi / 180);
NXF.EDX := X;
NXF.EDY := Y;
ModifyWorldTransform(DC, NXF, MWT_RIGHTMULTIPLY);
SetBkMode(DC, Transparent);
DrawText(DC, PChar(S.Text), Length(S.Text), Arect, Options);
SetWorldTransform(DC, OXF);
S.Free;
SelectObject(DC, FOld);
end;
procedure CoolDrawTextEx(bitmap:Tbitmap; text:string; Font: HFont; coolcount:integer; coolcolor:Tcolor; aRect : TRect; aType : integer; Options : Cardinal);
var
Drawrect: Trect;
C: Integer;
Tempb, Temp: TBitmap;
I, J, K: Integer;
P, P1, Pv, Pn, Pc: PARGB;
begin
Tempb := TBitmap.Create;
try
Tempb.PixelFormat := Pf24bit;
Tempb.Canvas.Font.Assign(Bitmap.Canvas.Font);
Tempb.Canvas.Font.Color := 0;
Tempb.Canvas.Brush.Color := $FFFFFF;
Tempb.Width := ARect.Right - ARect.Left;
Tempb.Height := ARect.Bottom - ARect.Top;
case AType of
0:
begin
DrawRect := Rect(Point(Coolcount, Coolcount), Point(Tempb.Width - Coolcount, Tempb.Height - Coolcount));
StrRotated(0, 0, DrawRect, Tempb.Canvas.Handle, Font, Text, 0, Options);
end;
1:
begin
DrawRect := Rect(Point(Coolcount, Coolcount), Point(Tempb.Height - Coolcount, Tempb.Width - Coolcount));
StrRotated(ARect.Right - ARect.Left, 0, DrawRect, Tempb.Canvas.Handle, Font, Text, 90, Options);
end;
2:
begin
DrawRect := Rect(Point(Coolcount, Coolcount), Point(Tempb.Width - Coolcount, Tempb.Height - Coolcount));
StrRotated(ARect.Right - ARect.Left, ARect.Bottom - ARect.Top, DrawRect, Tempb.Canvas.Handle, Font, Text, 180,
Options);
end;
3:
begin
DrawRect := Rect(Point(Coolcount, Coolcount), Point(Tempb.Height - Coolcount, Tempb.Width - Coolcount));
StrRotated(0, ARect.Bottom - ARect.Top, DrawRect, Tempb.Canvas.Handle, Font, Text, 270, Options);
end;
end;
Temp := TBitmap.Create;
try
Temp.PixelFormat := pf24bit;
Temp.Canvas.Brush.Color := $0;
Temp.Width := ARect.Right - ARect.Left;
Temp.Height := ARect.Bottom - ARect.Top;
Temp.Canvas.Font.Assign(Bitmap.Canvas.Font);
Temp.Canvas.Font.Color := 0;
for I := 0 to Temp.Height - 1 do
begin
P1 := Temp.ScanLine[I];
P := Tempb.ScanLine[I];
for J := 0 to Temp.Width - 1 do
begin
if P[J].R <> $FF then
begin
P1[J].R := $FF;
P1[J].G := $FF;
P1[J].B := $FF;
end;
end;
end;
Tempb.Canvas.Brush.Color := $0;
Tempb.Canvas.Pen.Color := $0;
Tempb.Canvas.Rectangle(0, 0, Tempb.Width, Tempb.Height);
for K := 1 to Coolcount do
begin
for I := 1 to Temp.Height - 2 do
begin
P := Tempb.ScanLine[I];
Pv := Temp.ScanLine[I - 1];
Pc := Temp.ScanLine[I];
Pn := Temp.ScanLine[I + 1];
for J := 1 to Temp.Width - 2 do
begin
C := 9;
if (Pv[J - 1].R <> 0) then
Dec(C);
if (Pv[J + 1].R <> 0) then
Dec(C);
if (Pn[J - 1].R <> 0) then
Dec(C);
if (Pn[J + 1].R <> 0) then
Dec(C);
if (Pc[J - 1].R <> 0) then
Dec(C);
if (Pc[J + 1].R <> 0) then
Dec(C);
if (Pn[J].R <> 0) then
Dec(C);
if (Pv[J].R <> 0) then
Dec(C);
if C <> 9 then
begin
P[J].R := Min($FF, P[J].R + (Pv[J - 1].R + Pv[J + 1].R + Pn[J - 1].R + Pn[J + 1].R + Pc[J - 1].R + Pc[J + 1]
.R + Pn[J].R + Pv[J].R) div (C + 1));
P[J].G := Min($FF, P[J].G + (Pv[J - 1].G + Pv[J + 1].G + Pn[J - 1].G + Pn[J + 1].G + Pc[J - 1].G + Pc[J + 1]
.G + Pn[J].G + Pv[J].G) div (C + 1));
P[J].B := Min($FF, P[J].B + (Pv[J - 1].B + Pv[J + 1].B + Pn[J - 1].B + Pn[J + 1].B + Pc[J - 1].B + Pc[J + 1]
.B + Pn[J].B + Pv[J].B) div (C + 1));
end;
end;
end;
AssignBitmap(Temp, Tempb);
end;
Bitmap.PixelFormat := Pf24bit;
if Bitmap.Width = 0 then
Exit;
for I := Max(0, ARect.Top) to Min(Tempb.Height - 1 + ARect.Top, Bitmap.Height - 1) do
begin
P := Bitmap.ScanLine[I];
P1 := Tempb.ScanLine[I - ARect.Top];
for J := Max(0, ARect.Left) to Min(Tempb.Width + ARect.Left - 1, Bitmap.Width - 1) do
begin
P[J].R := Min(Round(P[J].R * (1 - P1[J - ARect.Left].R / 255)) + Round
(Getrvalue(Coolcolor) * P1[J - ARect.Left].R / 255), 255);
P[J].G := Min(Round(P[J].G * (1 - P1[J - ARect.Left].G / 255)) + Round
(Getgvalue(Coolcolor) * P1[J - ARect.Left].G / 255), 255);
P[J].B := Min(Round(P[J].B * (1 - P1[J - ARect.Left].B / 255)) + Round
(Getbvalue(Coolcolor) * P1[J - ARect.Left].B / 255), 255);
end;
end;
DrawRect := Rect(Point(ARect.Left + Coolcount, ARect.Top + Coolcount), Point(ARect.Left + Temp.Width - Coolcount,
Temp.Height + ARect.Top - Coolcount));
case AType of
0:
begin
DrawRect := Rect(Point(ARect.Left + Coolcount, ARect.Top + Coolcount),
Point(ARect.Left + Temp.Width - Coolcount, Temp.Height + ARect.Top - Coolcount));
StrRotated(0, 0, DrawRect, Bitmap.Canvas.Handle, Font, Text, 0, Options);
end;
1:
begin
DrawRect := Rect(Point(Coolcount, Coolcount), Point(Temp.Height - Coolcount, Temp.Width - Coolcount));
StrRotated(ARect.Right, ARect.Top, DrawRect, Bitmap.Canvas.Handle, Font, Text, 90, Options);
end;
2:
begin
DrawRect := Rect(Point(Coolcount, Coolcount), Point(Temp.Width - Coolcount, Temp.Height - Coolcount));
StrRotated(ARect.Right, ARect.Bottom, DrawRect, Bitmap.Canvas.Handle, Font, Text, 180, Options);
end;
3:
begin
DrawRect := Rect(Point(Coolcount, Coolcount), Point(Temp.Height - Coolcount, Temp.Width - Coolcount));
StrRotated(ARect.Left, ARect.Bottom, DrawRect, Bitmap.Canvas.Handle, Font, Text, 270, Options);
end;
end;
finally
F(Temp);
end;
finally
F(Tempb);
end;
end;
function GetGistogrammBitmap(Height : integer; SBitmap : TBitmap; Options : byte; var MinC, MaxC : Integer) : TBitmap;
var
T: Boolean;
I, J, Xc: Integer;
X, MaxCount: Integer;
G: T255IntArray;
GE: array [0 .. 255] of Extended;
begin
Result := TBitmap.Create;
Result.PixelFormat := Pf24bit;
case Options of
0:
G := Gistogramma(SBitmap, T);
1:
G := GistogrammR(SBitmap, T);
2:
G := GistogrammG(SBitmap, T);
3:
G := GistogrammB(SBitmap, T);
end;
MaxCount := 1;
for I := 0 to 255 do
if G[I] > MaxCount then
begin
X := G[I] div 2;
Xc := 0;
for J := 0 to 255 do
if I <> J then
if G[J] > X then
Inc(Xc);
if Xc > 5 then
MaxCount := G[I];
end;
if MaxCount = 1 then
begin
for I := 0 to 255 do
if G[I] > MaxCount then
MaxCount := G[I];
end;
for I := 0 to 255 do
GE[I] := G[I] / MaxCount;
MinC := 0;
for I := 0 to 255 do
begin
if GE[I] > 0.05 then
begin
MinC := I;
Break;
end;
end;
MaxC := 0;
for I := 255 downto 0 do
begin
if GE[I] > 0.05 then
begin
MaxC := I;
Break;
end;
end;
Result.Width := 256;
Result.Height := Height;
Result.Canvas.Rectangle(0, 0, 256, Height);
for I := 0 to 255 do
begin
Result.Canvas.MoveTo(I + 1, Height);
Result.Canvas.LineTo(I + 1, Height - Round(Height * GE[I]));
end;
Result.Canvas.Pen.Color := $888888;
Result.Canvas.MoveTo(MinC, 0);
Result.Canvas.LineTo(MinC, Height);
Result.Canvas.Pen.Color := $888888;
Result.Canvas.MoveTo(MaxC, 0);
Result.Canvas.LineTo(MaxC, Height);
end;
function GetGistogrammBitmapX(Height,d : integer; G : T255IntArray; var MinC, MaxC : Integer) : TBitmap;
var
I, J, Xc: Integer;
X, MaxCount: Integer;
GE: array [0 .. 255] of Extended;
begin
Result := TBitmap.Create;
Result.PixelFormat := Pf24bit;
MaxCount := 1;
for I := 0 to 255 do
if G[I] > MaxCount then
begin
X := G[I] div 2;
Xc := 0;
for J := 0 to 255 do
if I <> J then
if G[J] > X then
Inc(Xc);
if Xc > 5 then
MaxCount := G[I];
end;
if MaxCount = 1 then
begin
for I := 0 to 255 do
if G[I] > MaxCount then
MaxCount := G[I];
end;
for I := 0 to 255 do
GE[I] := G[I] / MaxCount;
MinC := 0;
for I := 0 to 255 do
begin
if GE[I] > 0.05 then
begin
MinC := I;
Break;
end;
end;
MaxC := 0;
for I := 255 downto 0 do
begin
if GE[I] > 0.05 then
begin
MaxC := I;
Break;
end;
end;
Result.Width := 256;
Result.Height := Height;
Result.Canvas.Rectangle(0, 0, 256, Height);
for I := 0 to 255 do
begin
Result.Canvas.MoveTo(I + 1, Height - D);
Result.Canvas.LineTo(I + 1, Height - D - Round((Height - D) * GE[I]));
end;
Result.Canvas.Pen.Color := $888888;
Result.Canvas.MoveTo(MinC, 0);
Result.Canvas.LineTo(MinC, Height - D);
Result.Canvas.Pen.Color := $888888;
Result.Canvas.MoveTo(MaxC, 0);
Result.Canvas.LineTo(MaxC, Height - D);
end;
procedure GetGistogrammBitmapW(Height: Integer; Source: T255IntArray; var MinC, MaxC: Integer; Bitmap: TBitmap; Color: TColor);
var
I, J, Xc: Integer;
X, MaxCount: Integer;
GE: array [0 .. 255] of Extended;
begin
Bitmap.PixelFormat := pf24bit;
MaxCount := 1;
for I := 0 to 255 do
if Source[I] > MaxCount then
begin
X := Source[I] div 2;
Xc := 0;
for J := 0 to 255 do
if I <> J then
if Source[J] > X then
Inc(Xc);
if Xc > 5 then
MaxCount := Source[I];
end;
if MaxCount = 1 then
begin
for I := 0 to 255 do
if Source[I] > MaxCount then
MaxCount := Source[I];
end;
for I := 0 to 255 do
GE[I] := Source[I] / MaxCount;
MinC := 0;
for I := 0 to 255 do
begin
if GE[I] > 0.05 then
begin
MinC := I;
Break;
end;
end;
MaxC := 0;
for I := 255 downto 0 do
begin
if GE[I] > 0.05 then
begin
MaxC := I;
Break;
end;
end;
Bitmap.Width := 256;
Bitmap.Height := Height;
Bitmap.Canvas.Pen.Color := clGray;
Bitmap.Canvas.Brush.Color := clGray;
Bitmap.Canvas.Rectangle(0, 0, 256, Height);
Bitmap.Canvas.Pen.Color := Color;
for I := 0 to 255 do
begin
Bitmap.Canvas.MoveTo(I, Height - 1);
Bitmap.Canvas.LineTo(I, Height - Round(Height * GE[I]) - 1);
end;
Bitmap.Canvas.Pen.Color := $888888;
Bitmap.Canvas.MoveTo(MinC, 0);
Bitmap.Canvas.LineTo(MinC, Height);
Bitmap.Canvas.Pen.Color := $888888;
Bitmap.Canvas.MoveTo(MaxC, 0);
Bitmap.Canvas.LineTo(MaxC, Height);
end;
procedure GetGistogrammBitmapWRGB(Height: Integer; SGray, SR, SG, SB: T255IntArray; var MinC, MaxC: Integer; Bitmap: TBitmap; BackColor: TColor);
type
ExtendedArray255 = array[0 .. 255] of Extended;
var
I, J: Integer;
GGray, GR, GG, GB: ExtendedArray255;
P: PARGB;
PArray: array of PARGB;
R, B, G: Byte;
RGB: TRGB;
function NormalizeGistogramm(Gisto: T255IntArray): ExtendedArray255;
var
I, J: Integer;
MaxCount, Xc: Integer;
X: Integer;
begin
MaxCount := 1;
for I := 0 to 255 do
if Gisto[I] > MaxCount then
begin
X := Gisto[I] div 2;
Xc := 0;
for J := 0 to 255 do
if I <> J then
if Gisto[J] > X then
Inc(Xc);
if Xc > 5 then
MaxCount := Gisto[I];
end;
if MaxCount = 1 then
begin
for I := 0 to 255 do
if Gisto[I] > MaxCount then
MaxCount := Gisto[I];
end;
for I := 0 to 255 do
Result[I] := Gisto[I] / MaxCount;
end;
begin
Bitmap.PixelFormat := pf24bit;
GGray := NormalizeGistogramm(SGray);
GR := NormalizeGistogramm(SR);
GG := NormalizeGistogramm(SG);
GB := NormalizeGistogramm(SB);
BackColor := ColorToRGB(BackColor);
R := GetRValue(BackColor);
G := GetGValue(BackColor);
B := GetBValue(BackColor);
MinC := 0;
for I := 0 to 255 do
begin
if GGray[I] > 0.05 then
begin
MinC := I;
Break;
end;
end;
MaxC := 0;
for I := 255 downto 0 do
begin
if GGray[I] > 0.05 then
begin
MaxC := I;
Break;
end;
end;
Bitmap.SetSize(256, Height);
SetLength(PArray, Bitmap.Height);
for I := 0 to Bitmap.Height - 1 do
PArray[I] := Bitmap.ScanLine[I];
RGB.R := 0;
RGB.G := 0;
RGB.B := 0;
for I := 0 to Bitmap.Height - 1 do
for J := 0 to Bitmap.Width - 1 do
PArray[I][J] := RGB;
for I := 0 to 255 do
begin
for J := Max(0, Height - Round(Height * GR[I])) to Bitmap.Height - 1 do
PArray[J][I].R := 255;
for J := Max(0, Height - Round(Height * GG[I])) to Bitmap.Height - 1 do
PArray[J][I].G := 255;
for J := Max(0, Height - Round(Height * GB[I])) to Bitmap.Height - 1 do
PArray[J][I].B := 255;
end;
for I := 0 to Bitmap.Height - 1 do
begin
P := PArray[I];
for J := 0 to Bitmap.Width - 1 do
begin
if (P^[J].R = 0) and (P^[J].G = 0) and (P^[J].B = 0) then
begin
P^[J].R := R;
P^[J].G := G;
P^[J].B := B;
end;
end;
end;
RGB.R := $88;
RGB.G := $88;
RGB.B := $88;
for I := 0 to Bitmap.Height - 1 do
PArray[I][MinC] := RGB;
for I := 0 to Bitmap.Height - 1 do
PArray[I][MaxC] := RGB;
end;
procedure ReplaceColorInImage(S,D : TBitmap; BaseColor, NewColor : TColor; Size, Level : Integer; CallBack : TProgressCallBackProc = nil); overload;
var
I, J: Integer;
Ps, Pd: PARGB;
Terminating: Boolean;
R1, R2, G1, G2, B1, B2: Byte;
C: Extended;
function CompareColor(R1, R2, G1, G2, B1, B2: Byte): Extended;
var
R, G, B: Extended;
begin
R := Power(1 - Abs(R1 - R2) / 255, Level);
G := Power(1 - Abs(G1 - G2) / 255, Level);
B := Power(1 - Abs(B1 - B2) / 255, Level);
Result := R * G * B;
Result := Min(1, Result * Size / 100);
end;
begin
R1 := GetRValue(ColorToRGB(BaseColor));
G1 := GetGValue(ColorToRGB(BaseColor));
B1 := GetBValue(ColorToRGB(BaseColor));
R2 := GetRValue(ColorToRGB(NewColor));
G2 := GetGValue(ColorToRGB(NewColor));
B2 := GetBValue(ColorToRGB(NewColor));
S.PixelFormat := Pf24bit;
D.PixelFormat := Pf24bit;
D.Width := S.Width;
D.Height := S.Height;
Terminating := False;
for I := 0 to S.Height - 1 do
begin
PS := S.ScanLine[I];
PD := D.ScanLine[I];
for J := 0 to S.Width - 1 do
begin
C := CompareColor(PS[J].R, R1, PS[J].G, G1, PS[J].B, B1);
PD[J].R := Round(PS[J].R * (1 - C) + R2 * C);
PD[J].G := Round(PS[J].G * (1 - C) + G2 * C);
PD[J].B := Round(PS[J].B * (1 - C) + B2 * C);
end;
if I mod 50 = 0 then
if Assigned(CallBack) then
CallBack(Round(100 * I / S.Height), Terminating);
if Terminating then
Break;
end;
end;
procedure Emboss(S, D: TBitmap; CallBack : TProgressCallBackProc = nil);
var
x, y : Integer;
p1, p2 : Pbytearray;
SL : TScanlines;
Terminating : Boolean;
begin
AssignBitmap(D, S);
D.PixelFormat := pf24bit;
SL := TScanlines.Create(D);
Terminating := False;
try
for y := 0 to D.Height-2 do
begin
p1 := PByteArray(SL[y]);
p2 := PByteArray(SL[y+1]);
for x := 0 to D.Width-4 do
begin
p1[x*3] := (p1[x*3]+(p2[(x+3)*3] xor $FF))shr 1;
p1[x*3+1] := (p1[x*3+1]+(p2[(x+3)*3+1] xor $FF))shr 1;
p1[x*3+2] := (p1[x*3+2]+(p2[(x+3)*3+2] xor $FF))shr 1;
end;
if y mod 50=0 then
If Assigned(CallBack) then CallBack(Round(100*y/D.Height),Terminating);
if Terminating then Break;
end;
finally
SL.Free;
end;
end;
procedure AntiAliasRect(clip: tbitmap; XOrigin, YOrigin, XFinal, YFinal: Integer; CallBack : TProgressCallBackProc = nil);
var
Memo, x, y : Integer; (* Composantes primaires des points environnants *)
p0, p1, p2 : pbytearray;
SL : TScanlines;
Terminating : boolean;
begin
if XFinal<XOrigin then begin Memo := XOrigin; XOrigin := XFinal; XFinal := Memo; end; (* Inversion des valeurs *)
if YFinal<YOrigin then begin Memo := YOrigin; YOrigin := YFinal; YFinal := Memo; end; (* si diff,rence n,gative*)
Terminating:=false;
XOrigin := max(1,XOrigin);
YOrigin := max(1,YOrigin);
XFinal := min(clip.width-2,XFinal);
YFinal := min(clip.height-2,YFinal);
clip.PixelFormat := pf24bit;
SL := TScanlines.Create(clip);
try
for y := YOrigin to YFinal do
begin
p0 := PByteArray(SL[y-1]);
p1 := PByteArray(SL[y]);
p2 := PByteArray(SL[y+1]);
for x := XOrigin to XFinal do
begin
p1[x*3] := (p0[x*3]+p2[x*3]+p1[(x-1)*3]+p1[(x+1)*3])div 4;
p1[x*3+1] := (p0[x*3+1]+p2[x*3+1]+p1[(x-1)*3+1]+p1[(x+1)*3+1])div 4;
p1[x*3+2] := (p0[x*3+2]+p2[x*3+2]+p1[(x-1)*3+2]+p1[(x+1)*3+2])div 4;
end;
if y mod 50=0 then
If Assigned(CallBack) then CallBack(Round(100*y/clip.Height),Terminating);
if Terminating then Break;
end;
finally
SL.Free;
end;
end;
procedure AntiAlias(S, D: TBitmap; CallBack: TProgressCallBackProc = nil);
begin
AssignBitmap(D, S);
D.PixelFormat := Pf24bit;
AntiAliasRect(D, 0, 0, D.Width, D.Height, CallBack);
end;
function IntToByte(i:Integer):Byte;
begin
if i > 255 then
Result := 255
else
if i < 0 then
Result := 0
else
Result := i;
end;
procedure AddColorNoise(S, D: TBitmap; Amount : Integer; CallBack : TProgressCallBackProc = nil);
var
p0: pbytearray;
x, y, r, g, b: Integer;
SL : TScanLines;
Terminating: Boolean;
begin
AssignBitmap(D, S);
D.PixelFormat := pf24bit;
Terminating := False;
SL := TScanLines.Create(D);
try
for y := 0 to D.Height-1 do
begin
//p0 := clip.ScanLine [y];
p0 := PByteArray(SL[y]);
for x := 0 to D.Width-1 do
begin
r := p0[x*3]+(Random(Amount)-(Amount shr 1));
g := p0[x*3+1]+(Random(Amount)-(Amount shr 1));
b := p0[x*3+2]+(Random(Amount)-(Amount shr 1));
p0[x*3] := IntToByte(r);
p0[x*3+1] := IntToByte(g);
p0[x*3+2] := IntToByte(b);
end;
if y mod 50=0 then
If Assigned(CallBack) then CallBack(Round(100*y/D.Height),Terminating);
if Terminating then Break;
end;
finally
SL.Free;
end;
end;
procedure AddMonoNoise(S, D: TBitmap; Amount : Integer; CallBack : TProgressCallBackProc = nil);
var
P0: Pbytearray;
X, Y, A, R, G, B: Integer;
Terminating: Boolean;
SL: TScanLines;
begin
AssignBitmap(D, S);
D.PixelFormat := Pf24bit;
Terminating := False;
SL := TScanlines.Create(D);
try
for Y := 0 to D.Height - 1 do
begin
P0 := PByteArray(SL[Y]);
for X := 0 to D.Width - 1 do
begin
A := Random(Amount) - (Amount shr 1);
R := P0[X * 3] + A;
G := P0[X * 3 + 1] + A;
B := P0[X * 3 + 2] + A;
P0[X * 3] := IntToByte(R);
P0[X * 3 + 1] := IntToByte(G);
P0[X * 3 + 2] := IntToByte(B);
end;
if Y mod 50 = 0 then
if Assigned(CallBack) then
CallBack(Round(100 * Y / D.Height), Terminating);
if Terminating then
Break;
end;
finally
SL.Free;
end;
end;
procedure FishEye(Bmp, Dst: TBitmap; xAmount: Integer; CallBack : TProgressCallBackProc = nil);
var
xmid, ymid : Extended;
fx, fy : Extended;
r1, r2 : Extended;
ifx, ify : integer;
dx, dy : Extended;
rmax : Extended;
ty, tx : Integer;
weight_x, weight_y : array[0..1] of Extended;
weight : Extended;
new_red, new_green : Integer;
new_blue : Integer;
total_red, total_green : Extended;
total_blue : Extended;
ix, iy : Integer;
sli, slo : PByteArray;
SL1, SL2 : TScanlines;
Amount: Extended;
Terminating : boolean;
begin
Amount:=0.5+xAmount/100;
xmid := Bmp.Width/2;
ymid := Bmp.Height/2;
AssignBitmap(Dst, Bmp);
rmax := Dst.Width * Amount;
Terminating:=false;
SL1 := TScanlines.Create(Bmp);
SL2 := TScanlines.Create(Dst);
try
for ty := 0 to Dst.Height - 1 do
begin
for tx := 0 to Dst.Width - 1 do begin
dx := tx - xmid;
dy := ty - ymid;
r1 := Sqrt(dx * dx + dy * dy);
if r1 = 0 then
begin
fx := xmid;
fy := ymid;
end else
begin
if (abs(1 - r1/rmax)>0.0001) and (abs(r1)>0.001) then
begin
r2 := rmax / 2 * (1 / (1 - r1/rmax) - 1);
fx := dx * r2 / r1 + xmid;
fy := dy * r2 / r1 + ymid;
end else
begin
fx := xmid+r1/rmax;
fy := ymid+r1/rmax;
end;
end;
ify := Trunc(fy);
ifx := Trunc(fx);
// Calculate the weights.
if fy >= 0 then begin
weight_y[1] := fy - ify;
weight_y[0] := 1 - weight_y[1];
end else begin
weight_y[0] := -(fy - ify);
weight_y[1] := 1 - weight_y[0];
end;
if fx >= 0 then begin
weight_x[1] := fx - ifx;
weight_x[0] := 1 - weight_x[1];
end else begin
weight_x[0] := -(fx - ifx);
Weight_x[1] := 1 - weight_x[0];
end;
if ifx < 0 then
ifx := Bmp.Width-1-(-ifx mod Bmp.Width)
else
if ifx > Bmp.Width-1 then
ifx := ifx mod Bmp.Width;
if ify < 0 then
ify := Bmp.Height-1-(-ify mod Bmp.Height)
else
if ify > Bmp.Height-1 then
ify := ify mod Bmp.Height;
total_red := 0.0;
total_green := 0.0;
total_blue := 0.0;
for ix := 0 to 1 do begin
for iy := 0 to 1 do begin
try
if ify + iy < Bmp.Height then
//sli := Bmp.scanline[ify + iy]
sli := PByteArray(SL1[ify + iy])
else
//sli := Bmp.scanline[Bmp.Height - ify - iy];
sli := PByteArray(SL1[Bmp.Height - ify - iy]);
if ifx + ix < Bmp.Width then begin
new_red := sli[(ifx + ix)*3];
new_green := sli[(ifx + ix)*3+1];
new_blue := sli[(ifx + ix)*3+2];
end else begin
new_red := sli[(Bmp.Width - ifx - ix)*3];
new_green := sli[(Bmp.Width - ifx - ix)*3+1];
new_blue := sli[(Bmp.Width - ifx - ix)*3+2];
end;
weight := weight_x[ix] * weight_y[iy];
total_red := total_red + new_red * weight;
total_green := total_green + new_green * weight;
total_blue := total_blue + new_blue * weight;
except
end;
end;
end;
//slo := Dst.scanline[ty];
slo := PByteArray(SL2[ty]);
slo[tx*3] := Round(total_red);
slo[tx*3+1] := Round(total_green);
slo[tx*3+2] := Round(total_blue);
end;
if ty mod 50=0 then
If Assigned(CallBack) then CallBack(Round(100*ty/Dst.Height),Terminating);
if Terminating then Break;
end;
finally
SL2.Free;
SL1.Free;
end;
end;
procedure GaussianBlur(D: TBitmap; Amount : Integer; CallBack : TProgressCallBackProc = nil);
var
i : Integer;
begin
for i := Amount downto 0 do
SplitBlurW(D,3,CallBack);
end;
procedure SplitBlur(S, D : TBitmap; Amount : Integer; CallBack : TProgressCallBackProc = nil);
begin
AssignBitmap(D, S);
D.PixelFormat := pf24Bit;
SplitBlurW(D,Amount,CallBack);
end;
procedure SplitBlurW(D: TBitmap; Amount : Integer; CallBack : TProgressCallBackProc = nil);
//procedure SplitBlur(var clip: tbitmap; Amount: integer);
var
P0, P1, P2: Pbytearray;
Cx, X, Y: Integer;
Buf: array [0 .. 3, 0 .. 2] of Byte;
Terminating: Boolean;
SL: TScanlines;
begin
if Amount = 0 then Exit;
Terminating:=false;
SL := TScanlines.Create(D);
try
for y := 0 to D.Height-1 do
begin
//p0 := clip.scanline[y];
//if y-Amount<0 then p1 := clip.scanline[y]
//else {y-Amount>0} p1 := clip.ScanLine[y-Amount];
//if y+Amount<clip.Height then p2 := clip.ScanLine[y+Amount]
//else {y+Amount>=Height} p2 := clip.ScanLine[clip.Height-y];
p0 := PByteArray(SL[y]);
if y-Amount<0
then p1 := PByteArray(SL[y])
else {y-Amount>0}
p1 := PByteArray(SL[y-Amount]);
if y+Amount<D.Height then
p2 := PByteArray(SL[y+Amount])
else {y+Amount>=Height}
p2 := PByteArray(SL[D.Height-y]);
for x := 0 to D.Width-1 do begin
if x-Amount<0 then
cx := x
else {x-Amount>0}
cx := x-Amount;
Buf[0,0] := p1[cx*3];
Buf[0,1] := p1[cx*3+1];
Buf[0,2] := p1[cx*3+2];
Buf[1,0] := p2[cx*3];
Buf[1,1] := p2[cx*3+1];
Buf[1,2] := p2[cx*3+2];
if x+Amount<D.Width then
cx := x+Amount
else {x+Amount>=Width}
cx := D.Width-x;
Buf[2,0] := p1[cx*3];
Buf[2,1] := p1[cx*3+1];
Buf[2,2] := p1[cx*3+2];
Buf[3,0] := p2[cx*3];
Buf[3,1] := p2[cx*3+1];
Buf[3,2] := p2[cx*3+2];
p0[x*3] := (Buf[0,0]+Buf[1,0]+Buf[2,0]+Buf[3,0])shr 2;
p0[x*3+1] := (Buf[0,1]+Buf[1,1]+Buf[2,1]+Buf[3,1])shr 2;
p0[x*3+2] := (Buf[0,2]+Buf[1,2]+Buf[2,2]+Buf[3,2])shr 2;
end;
if y mod 50=0 then
If Assigned(CallBack) then CallBack(Round(100*y/D.Height),Terminating);
if Terminating then Break;
end;
finally
SL.Free;
end;
end;
procedure Twist(Bmp, Dst: TBitmap; Amount: integer; CallBack : TProgressCallBackProc = nil);
var
fxmid, fymid : Single;
txmid, tymid : Single;
fx,fy : Single;
tx2, ty2 : Single;
r : Single;
theta : Single;
ifx, ify : integer;
dx, dy : Single;
OFFSET : Single;
ty, tx : Integer;
weight_x, weight_y : array[0..1] of Single;
weight : Single;
new_red, new_green : Integer;
new_blue : Integer;
total_red, total_green : Single;
total_blue : Single;
ix, iy : Integer;
sli, slo : PBytearray;
SL1, SL2 : TScanlines;
Terminating : Boolean;
function ArcTan2(xt,yt : Single): Single;
begin
if xt = 0 then
if yt > 0 then
Result := Pi/2
else
Result := -(Pi/2)
else begin
Result := ArcTan(yt/xt);
if xt < 0 then
Result := Pi + ArcTan(yt/xt);
end;
end;
begin
AssignBitmap(Dst, Bmp);
Terminating:=false;
OFFSET := -(Pi/2);
dx := Bmp.Width - 1;
dy := Bmp.Height - 1;
r := Sqrt(dx * dx + dy * dy);
tx2 := r;
ty2 := r;
txmid := (Bmp.Width-1)/2; //Adjust these to move center of rotation
tymid := (Bmp.Height-1)/2; //Adjust these to move ......
fxmid := (Bmp.Width-1)/2;
fymid := (Bmp.Height-1)/2;
if tx2 >= Bmp.Width then tx2 := Bmp.Width-1;
if ty2 >= Bmp.Height then ty2 := Bmp.Height-1;
SL1 := TScanlines.Create(Bmp);
SL2 := TScanlines.Create(Dst);
try
for ty := 0 to Round(ty2) do begin
for tx := 0 to Round(tx2) do begin
dx := tx - txmid;
dy := ty - tymid;
r := Sqrt(dx * dx + dy * dy);
if r = 0 then begin
fx := 0;
fy := 0;
end
else begin
theta := ArcTan2(dx,dy) - r/Amount - OFFSET;
fx := r * Cos(theta);
fy := r * Sin(theta);
end;
fx := fx + fxmid;
fy := fy + fymid;
ify := Trunc(fy);
ifx := Trunc(fx);
// Calculate the weights.
if fy >= 0 then begin
weight_y[1] := fy - ify;
weight_y[0] := 1 - weight_y[1];
end else begin
weight_y[0] := -(fy - ify);
weight_y[1] := 1 - weight_y[0];
end;
if fx >= 0 then begin
weight_x[1] := fx - ifx;
weight_x[0] := 1 - weight_x[1];
end else begin
weight_x[0] := -(fx - ifx);
Weight_x[1] := 1 - weight_x[0];
end;
if ifx < 0 then
ifx := Bmp.Width-1-(-ifx mod Bmp.Width)
else
if ifx > Bmp.Width-1 then
ifx := ifx mod Bmp.Width;
if ify < 0 then
ify := Bmp.Height-1-(-ify mod Bmp.Height)
else
if ify > Bmp.Height-1 then
ify := ify mod Bmp.Height;
total_red := 0.0;
total_green := 0.0;
total_blue := 0.0;
for ix := 0 to 1 do begin
for iy := 0 to 1 do begin
if ify + iy < Bmp.Height then
//sli := Bmp.scanline[ify + iy]
sli := PByteArray(SL1[ify + iy])
else
//sli := Bmp.scanline[Bmp.Height - ify - iy];
sli := PByteArray(SL1[Bmp.Height - ify - iy]);
if ifx + ix < Bmp.Width then begin
new_red := sli[(ifx + ix)*3];
new_green := sli[(ifx + ix)*3+1];
new_blue := sli[(ifx + ix)*3+2];
end else begin
new_red := sli[(Bmp.Width - ifx - ix)*3];
new_green := sli[(Bmp.Width - ifx - ix)*3+1];
new_blue := sli[(Bmp.Width - ifx - ix)*3+2];
end;
weight := weight_x[ix] * weight_y[iy];
total_red := total_red + new_red * weight;
total_green := total_green + new_green * weight;
total_blue := total_blue + new_blue * weight;
end;
end;
//slo := Dst.scanline[ty];
slo := PByteArray(SL2[ty]);
slo[tx*3] := Round(total_red);
slo[tx*3+1] := Round(total_green);
slo[tx*3+2] := Round(total_blue);
end;
if ty mod 50=0 then
If Assigned(CallBack) then CallBack(Round(100*ty/Dst.Height),Terminating);
if Terminating then Break;
end;
finally
SL2.Free;
SL1.Free;
end;
end;
procedure SetContractBrightnessRGBChannelValue(ImageS, ImageD: TArPARGB; Width, Height: Integer; Contrast : Extended; var OverageBrightnss : Integer; Brightness, Red, Green, Blue: Integer); overload;
var
Mr, Mg, Mb, I, J, W, H: Integer;
vd: Double;
ContrastArrayR,
ContrastArrayG,
ContrastArrayB: T255ByteArray;
LUT: array [Byte] of Byte;
V: Integer;
Rx, Gx, Bx: Extended;
RArray, GArray, BArray: T255ByteArray;
RFull, GFull, BFull: T255ByteArray;
PARGBS, PARGBD : PRGB;
function BLimit(B: Integer): Byte;
begin
if B < 0 then
Result := 0
else if B > 255 then
Result := 255
else
Result := B;
end;
begin
W := Width - 1;
H := Height - 1;
//contrast
if OverageBrightnss < 0 then
begin
OverageBrightnss := 0;
for I := 0 to H do
for J := 0 to W do
Inc(OverageBrightnss, (ImageS[I, J].R * 77 + ImageS[I, J].G * 151 + ImageS[I, J].B * 28) shr 8);
end;
MR := Round(OverageBrightnss / (W * H));
MG := Round(OverageBrightnss / (W * H));
MB := Round(OverageBrightnss / (W * H));
if Contrast > 0 then
Vd := 1 + (Contrast / 10)
else
Vd := 1 - (Sqrt(-Contrast) / 10);
for I := 0 to 255 do
begin
ContrastArrayR[I] := BLimit(MR + Round((I - MR) * Vd));
ContrastArrayG[I] := BLimit(MG + Round((I - MG) * Vd));
ContrastArrayB[I] := BLimit(MB + Round((I - MB) * Vd));
end;
//brightness
for I := 0 to 255 do
begin
V := I + Brightness;
if V < 0 then
V := 0
else if V > 255 then
V := 255;
LUT[I] := V;
end;
//RGB
Rx := 1 + (Red / 100);
Gx := 1 + (Green / 100);
Bx := 1 + (Blue / 100);
for I := 0 to 255 do
begin
RArray[I] := Round(Min(255, Max(0, I * (Rx))));
GArray[I] := Round(Min(255, Max(0, I * (Gx))));
BArray[I] := Round(Min(255, Max(0, I * (Bx))));
end;
for I := 0 to 255 do
begin
RFull[I] := RArray[LUT[ContrastArrayR[I]]];
GFull[I] := GArray[LUT[ContrastArrayG[I]]];
BFull[I] := BArray[LUT[ContrastArrayB[I]]];
end;
for I := 0 to Height - 1 do
begin
PARGBS := PRGB(ImageS[I]);
PARGBD := PRGB(ImageD[I]);
for J := 0 to Width - 1 do
begin
PARGBD.R := RFull[PARGBS.R];
PARGBD.G := GFull[PARGBS.G];
PARGBD.B := BFull[PARGBS.B];
Inc(PARGBS, 1);
Inc(PARGBD, 1);
end;
end;
end;
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages,
System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Imaging.JPEG,
//
GLCadencer, GLTexture, GLCgShader, GLScene,
GLTerrainRenderer, GLHeightData, GLHUDObjects, //Gaps in terrain mesh!
GLWin32Viewer, GLAsyncTimer, GLNavigator,
GLBitmapFont, GLWindowsFont, GLUserShader, GLMaterial,
GLCoordinates, GLCrossPlatform, GLBaseClasses, GLRenderContextInfo, OpenGLTokens;
type
TForm1 = class(TForm)
GLScene1: TGLScene;
GLSceneViewer1: TGLSceneViewer;
GLCustomHDS1: TGLCustomHDS;
Camera: TGLCamera;
Terrain: TGLTerrainRenderer;
CgBlendedTexture: TCgShader;
MLTerrain: TGLMaterialLibrary;
GLCadencer1: TGLCadencer;
AsyncTimer1: TGLAsyncTimer;
GLNavigator1: TGLNavigator;
GLHUDText1: TGLHUDText;
GLWindowsBitmapFont1: TGLWindowsBitmapFont;
GLUserInterface1: TGLUserInterface;
GLUserShader1: TGLUserShader;
procedure GLCustomHDS1StartPreparingData(heightData: TGLHeightData);
procedure FormCreate(Sender: TObject);
procedure GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
procedure AsyncTimer1Timer(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure TerrainGetTerrainBounds(var l, t, r, b: Single);
procedure FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure CgBlendedTextureUnApplyFP(CgProgram: TCgProgram);
procedure CgBlendedTextureApplyFP(CgProgram: TCgProgram;
Sender: TObject);
procedure GLUserShader1DoApply(Sender: TObject;
var rci: TGLRenderContextInfo);
procedure GLUserShader1DoUnApply(Sender: TObject; Pass: Integer;
var rci: TGLRenderContextInfo; var Continue: Boolean);
private
FHFFData : TStream;
public
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
GLApplicationFileIO, GLKeyboard, CgGL, OpenGL1x;
procedure TForm1.FormCreate(Sender: TObject);
begin
SetCurrentDir(ExtractFilePath(Application.ExeName)+'media');
FHFFData:=CreateFileStream('volcano.hff', fmOpenRead);
with MLTerrain do begin
AddTextureMaterial('BlendMap','volcano_BM.jpg');
AddTextureMaterial('Sand','sand.jpg');
AddTextureMaterial('Grass','grass.jpg');
AddTextureMaterial('Rock','rock.jpg');
with AddTextureMaterial('LightMap','volcano_LM.jpg') do begin
TextureScale.SetPoint(1,-1,1);
Material.MaterialOptions:=[moNoLighting];
Material.Texture.TextureMode:=tmReplace;
end;
end;
GLUserInterface1.MouseLookActive:=True;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
GLUserInterface1.MouseLookActive:=False;
FHFFData.Free;
end;
procedure TForm1.GLCustomHDS1StartPreparingData(heightData: TGLHeightData);
var
oldType : TGLHeightDataType;
i,j,xl,yt,s : Integer;
h : Word;
begin
if Assigned(FHFFData) then begin;
xl:=heightData.XLeft;
yt:=heightData.YTop;
if xl<0 then xl:=xl+1024;
if yt<0 then yt:=yt+1024;
s:=heightData.Size;
oldType:=heightData.DataType;
heightData.Allocate(hdtSmallInt);
for j:=0 to s-1 do begin
FHFFData.Position:=2*(xl+(j+yt)*1024)+64;
for i:=0 to s-1 do begin
FHFFData.Read(h,2);
heightData.SmallIntRaster[j][i]:=h-32768;
end;
end;
if oldType<>hdtSmallInt then
heightData.DataType:=oldType;
heightData.DataState:=hdsReady;
end else
heightData.DataState:=hdsNone;
end;
procedure TForm1.TerrainGetTerrainBounds(var l, t, r,
b: Single);
begin
l:=0;
t:=1024;
r:=1024;
b:=0;
end;
procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
var
speed : Single;
begin
speed:=25;
if IsKeyDown(VK_SHIFT) then begin
speed:=speed*10;
end;
if IsKeyDown(VK_UP) or IsKeyDown('W') or IsKeyDown('Z') then
GLNavigator1.MoveForward(deltaTime*speed)
else if IsKeyDown(VK_DOWN) or IsKeyDown('S') then
GLNavigator1.MoveForward(-deltaTime*speed);
if IsKeyDown(VK_LEFT) or IsKeyDown('A') or IsKeyDown('Q') then
GLNavigator1.StrafeHorizontal(-deltaTime*speed)
else if IsKeyDown(VK_RIGHT) or IsKeyDown('D') then
GLNavigator1.StrafeHorizontal(deltaTime*speed);
if IsKeyDown(VK_NEXT) then
GLNavigator1.StrafeVertical(-deltaTime*speed)
else if IsKeyDown(VK_PRIOR) then
GLNavigator1.StrafeVertical(deltaTime*speed);
if Camera.Position.Z<Terrain.InterpolatedHeight(Camera.Position.AsVector)+3 then
Camera.Position.Z:=Terrain.InterpolatedHeight(Camera.Position.AsVector)+3;
GLUserInterface1.MouseUpdate;
GLUserInterface1.MouseLook;
GLSceneViewer1.Invalidate;
end;
procedure TForm1.AsyncTimer1Timer(Sender: TObject);
begin
GLHUDText1.Text:='Blended Terrain - '+GLSceneViewer1.FramesPerSecondText;
GLSceneViewer1.ResetPerformanceMonitor;
end;
procedure TForm1.FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case Key of
27 : Form1.Close;
end;
end;
procedure TForm1.CgBlendedTextureApplyFP(CgProgram: TCgProgram;
Sender: TObject);
begin
with CGProgram.ParamByName('blendmap') do begin
SetAsTexture2D(MLTerrain.LibMaterialByName('BlendMap').Material.Texture.Handle);
EnableTexture;
end;
with CGProgram.ParamByName('channel1') do begin
SetAsTexture2D(MLTerrain.LibMaterialByName('Sand').Material.Texture.Handle);
EnableTexture;
end;
with CGProgram.ParamByName('channel2') do begin
SetAsTexture2D(MLTerrain.LibMaterialByName('Grass').Material.Texture.Handle);
EnableTexture;
end;
with CGProgram.ParamByName('channel3') do begin
SetAsTexture2D(MLTerrain.LibMaterialByName('Rock').Material.Texture.Handle);
EnableTexture;
end;
end;
procedure TForm1.CgBlendedTextureUnApplyFP(CgProgram: TCgProgram);
begin
CGProgram.ParamByName('blendmap').DisableTexture;
CGProgram.ParamByName('channel1').DisableTexture;
CGProgram.ParamByName('channel2').DisableTexture;
CGProgram.ParamByName('channel3').DisableTexture;
end;
procedure TForm1.GLUserShader1DoApply(Sender: TObject;
var rci: TGLRenderContextInfo);
begin
if GLSceneViewer1.Buffer.LimitOf[limNbTextureUnits]<4 then
GLUserShader1.Enabled:=False;
CgBlendedTexture.Apply(rci, Sender);
end;
procedure TForm1.GLUserShader1DoUnApply(Sender: TObject; Pass: Integer;
var rci: TGLRenderContextInfo; var Continue: Boolean);
begin
if Pass = 1 then begin
CgBlendedTexture.UnApply(rci);
MLTerrain.LibMaterialByName('LightMap').Apply(rci);
glPushAttrib(GL_ENABLE_BIT or GL_DEPTH_BUFFER_BIT or GL_COLOR_BUFFER_BIT);
glDepthFunc(GL_EQUAL);
glEnable(GL_BLEND);
glBlendFunc(GL_DST_COLOR, GL_ZERO);
Continue:=True;
Exit;
end;
glPopAttrib;
MLTerrain.LibMaterialByName('LightMap').UnApply(rci);
Continue:=False;
end;
end.
|
unit uFormImportPicturesSettings;
interface
uses
Winapi.Windows,
System.SysUtils,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
Dmitry.Controls.Base,
Dmitry.Controls.WebLink,
uVCLHelpers,
uDBForm,
uConstants,
uSettings,
uMemoryEx;
type
TFormImportPicturesSettings = class(TDBForm)
LbDirectoryFormat: TLabel;
CbFormatCombo: TComboBox;
CbOnlyImages: TCheckBox;
CbDeleteAfterImport: TCheckBox;
CbAddToCollection: TCheckBox;
BtnOk: TButton;
BtnCancel: TButton;
WlFilter: TWebLink;
BtnChangePatterns: TButton;
CbOpenDestination: TCheckBox;
procedure BtnOkClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure BtnCancelClick(Sender: TObject);
procedure BtnChangePatternsClick(Sender: TObject);
private
{ Private declarations }
procedure LoadLanguage;
procedure ReadOptions;
procedure ReadPatternList;
protected
{ Protected declarations }
function GetFormID: string; override;
public
{ Public declarations }
end;
implementation
uses
uPicturesImportPatternEdit;
{$R *.dfm}
procedure TFormImportPicturesSettings.BtnCancelClick(Sender: TObject);
begin
Close;
end;
procedure TFormImportPicturesSettings.BtnChangePatternsClick(Sender: TObject);
var
PicturesImportPatternEdit: TPicturesImportPatternEdit;
begin
PicturesImportPatternEdit := TPicturesImportPatternEdit.Create(Self);
try
PicturesImportPatternEdit.ShowModal;
if PicturesImportPatternEdit.ModalResult = mrOk then
ReadPatternList;
finally
R(PicturesImportPatternEdit);
end;
end;
procedure TFormImportPicturesSettings.BtnOkClick(Sender: TObject);
begin
AppSettings.WriteString('ImportPictures', 'Pattern', CbFormatCombo.Value);
AppSettings.WriteBool('ImportPictures', 'OnlyImages', CbOnlyImages.Checked);
AppSettings.WriteBool('ImportPictures', 'DeleteFiles', CbDeleteAfterImport.Checked);
AppSettings.WriteBool('ImportPictures', 'AddToCollection', CbAddToCollection.Checked);
AppSettings.WriteBool('ImportPictures', 'OpenDestination', CbOpenDestination.Checked);
Close;
ModalResult := mrOk;
end;
procedure TFormImportPicturesSettings.FormCreate(Sender: TObject);
begin
ReadOptions;
LoadLanguage;
ModalResult := mrCancel;
end;
function TFormImportPicturesSettings.GetFormID: string;
begin
Result := 'ImportPictures';
end;
procedure TFormImportPicturesSettings.LoadLanguage;
begin
BeginTranslate;
try
Caption := L('Import settings');
BtnOk.Caption := L('Ok');
BtnCancel.Caption := L('Cancel');
LbDirectoryFormat.Caption := L('Directory format') + ':';
CbOnlyImages.Caption := L('Import only supported images');
CbDeleteAfterImport.Caption := L('Delete files after import');
CbAddToCollection.Caption := L('Add files to collection after copying files');
CbOnlyImages.AdjustWidth(20);
WlFilter.Left := CbOnlyImages.Left + CbOnlyImages.Width + 10;
WlFilter.Top := CbOnlyImages.Top + CbOnlyImages.Height div 2 - WlFilter.Height div 2;
CbOpenDestination.Caption := L('Open destination directory after import');
finally
EndTranslate;
end;
end;
procedure TFormImportPicturesSettings.ReadOptions;
begin
ReadPatternList;
CbOnlyImages.Checked := AppSettings.ReadBool('ImportPictures', 'OnlyImages', False);
CbDeleteAfterImport.Checked := AppSettings.ReadBool('ImportPictures', 'DeleteFiles', True);
CbAddToCollection.Checked := AppSettings.ReadBool('ImportPictures', 'AddToCollection', True);
CbOpenDestination.Checked := AppSettings.ReadBool('ImportPictures', 'OpenDestination', True);
end;
procedure TFormImportPicturesSettings.ReadPatternList;
begin
CbFormatCombo.Items.Text := AppSettings.ReadString('ImportPictures', 'PatternList', DefaultImportPatternList);
if CbFormatCombo.Items.Count > 0 then
CbFormatCombo.ItemIndex := 0;
CbFormatCombo.Value := AppSettings.ReadString('ImportPictures', 'Pattern', DefaultImportPattern);
end;
end.
|
unit UPlayer;
interface
uses
w3system, UPlat, UGlobalsNoUserTypes;
const
MAXMOVESPEED = 5; //The maximum speed the player can move left or right
PLAYERHEAD = UGlobalsNoUserTypes.PLAYERHEAD; //Width of the player
PLAYERHEIGHT = UGlobalsNoUserTypes.PLAYERHEIGHT; //Height of the player
MAXJUMPFRAMES = 15; //Max jump height
SHOTINTERVAL = 30; //How long between each of the player's shots (min value)
SPEEDINC = 0.5; //How much the speed will increase when it starts moving
SPEEDDEC = 0.2; //How much the speed will decrease when it stops moving
MAXKNOCKBACKFRAMES = 6; //The max height knockback will cause
KNOCKBACKXCHANGE = 5; //How much the x will change every frame while knockback is active
DAMAGE = 15; //The default amount of damage caused by the player's shots
REGEN = 0.1; //The default amount of health regen for the player
type TPlayer = class(TObject)
public
//SX: the starting X, used for the respawn of the player
//SY: the starting y, used for the respawn of the player
//HealthRegen: is the amount of health gained each frame
//GravSpeed: the amount added to the y when falling, gravity speed
//Jump: the jump frame, subtracts from the y its value when active
//Jumps: the amount of jumps that has happened in the air, allowed double jumping
//Fall: the falling frame for if the player falls through a platform
//i: used for iteration
//KnockBackFrame: is the knock back's frame and subtracts from y its value
//Damage: the damage the player's shots will cause
//timeSinceShot: how many frames it has been before since the player has shot
//AtGround: if the player is Grounded, so on a platform
//FaceLeft: if the player is facing left
//GoingLeft: if the player is moving left
//GoingRight: if the player is moving right
//canShoot: if the player is able to shoot again
//LeftDown: if the left key is held down still
//RightDown: if the right key is held down still
//Dead: if the player is dead
//CanMove: if the player is able to move
//KnockbackLeft: if the player's knockback (when active) is going left
//CanWallJump: records if the player is on the side of a platforms, allowing it to wall jump off of it
X, Y, SX, SY, MoveSpeed, Health, HealthRegen: float;
GravSpeed, Jump, Jumps, Fall, i, KnockBackFrame, Damage, timeSinceShot : integer;
AtGround, FaceLeft, GoingLeft, GoingRight, canShoot, LeftDown,
RightDown, dead, canMove, KnockBackLeft, FallChangeThisFrame, CanWallJump : boolean;
colour : string;
constructor start(); //Starts the player, so it can be spawned using the create procedure
//Spawns the player properly ready for a level
procedure create(newX,newY : float; newColour : string; newHealth : integer;
FixedPlats, RandPlats : Array of TPlat; newDamage : integer = DAMAGE); virtual;
procedure update(width : float; PLAYERHEALTH : integer); //Updates the co-ordinate of the player
//and changes all the other variables
procedure FallDead(); //Makes the player fall if it is dead
procedure updateShoot(); //updates the shoot so makes you able to shoot
procedure resetShoot(); //resets shot based variables
//This checks if the player is grounded so is it on a platform and will properly set it upon it
procedure isGrounded(height : float; Fixed : array of UPlat.TPlat; Rand : array of UPlat.TPlat);
procedure Move(Direction : MoveCommands); //Changes the players move direction
procedure doJump(); //makes the player start to jump
procedure doFall(); //Makes the player start to fall through platforms
procedure CollidedLeft(Plat : TPlat); //runs code for if the player collided on the left
procedure CollidedRight(Plat : TPlat); //runs code for if the player collided on the right
procedure CollidedTop(Plat : TPlat); //runs code for if the player collided on the top of it
procedure CollidedBottom(Plat : TPlat); //runs code for if the player collided on the bottom of it
function CollideLeft(Plat : TPlat) : boolean; //checks if it hit a platform on the left of the player
function CollideRight(Plat : TPlat) : boolean; //checks if it hit a platform on the right of the player
function CollideTop(Plat : TPlat) : boolean; //checks if it hit a platform on the top of the player
function CollideBottom(Plat : TPlat) : boolean; //checks if it hit a platform on the bottom of the player
function ShootAngle(Targx, Targy : float) : float; //Gets the angle to shoot at relative to its own X and Y position,
//as well as the target's x and y position
end;
implementation
constructor TPlayer.start();
begin
x := 0;
y := 0;
SX := 0;
SY := 0;
end;
procedure TPlayer.create(newX, newY : float; newColour : string; newHealth : integer;
FixedPlats, RandPlats : array of TPlat; newDamage : integer = DAMAGE);
begin
X := newX;
Y := newY;
SX := newX;
SY := newY;
GravSpeed := 0;
Jump := 0;
GoingLeft := False;
GoingRight := False;
AtGround := False;
Jumps := 2;
Fall := 0;
FaceLeft := False;
colour := newColour;
timeSinceShot := SHOTINTERVAL;
canShoot := True;
MoveSpeed := 0;
canMove := True;
dead := False;
KnockBackFrame := -1;
Damage := newDamage;
Health := newHealth;
HealthRegen := REGEN;
CanWallJump := false;
end;
procedure TPlayer.update(width : float; PLAYERHEALTH : integer);
begin
if (AtGround = False) and (Jumps <> 2) then //If it is not at ground, set jumps to one
//so it is able to jump one more time in the air.
begin
Jumps := 1;
end;
X += MoveSpeed; // Adds the movespeed to the x so that it moves left or right
if GoingLeft then // if it is going left then change the move speed (to a minus)
begin
if MoveSpeed > -MAXMOVESPEED then
begin
MoveSpeed -= SPEEDINC;
end;
end;
if GoingRight then // if it is going right then change the move speed (to a plus)
begin
if MoveSpeed < MAXMOVESPEED then
begin
MoveSpeed += SPEEDINC;
end;
end;
if (GoingLeft = False) and (GoingRight = False) then // If not moving, stop the player moving
begin
if MoveSpeed > 0 then
begin
MoveSpeed -= SPEEDDEC;
end;
if MoveSpeed < 0 then
begin
MoveSpeed += SPEEDDEC;
end;
if (MoveSpeed >= -1) and (MoveSpeed <= 1) then
begin
MoveSpeed := 0;
end;
end;
if X + PLAYERHEAD >= width then // Stop the player moving if it hits the right hand side of the screen
begin
X := width - PLAYERHEAD - 0.25;
GoingRight := False;
MoveSpeed := 0;
end;
if X <= 0 then // Stop the player moving if it hits the left hand side of the screen
begin
X := 0 + 0.25;
GoingLeft := False;
MoveSpeed := 0;
end;
if Jump > 0 then // If the player's jump frame is above 0, change it and the player's Y
begin
Y -= Jump; // Makes the player move up by how many its jump frame is
Jump -= 1; // Subtracts 1 from the jump frame
GravSpeed := 0; // Sets gravity to 0
AtGround := True; // Sets it to be at ground so gravity is off
end;
if KnockBackFrame > 0 then // If the knockback is active, act accordingly
begin
if KnockBackLeft then // If it is going left, make the player move left
begin
X -= KNOCKBACKXCHANGE;
end
else // else make the player move right
begin
X += KNOCKBACKXCHANGE;
end;
Y -= KnockBackFrame; // Subtract the knockbackframes from the player Y so it moves up
KnockBackFrame -= 1; // Make the knockbackframe one less as another frame has passed
GravSpeed := 0; // Sets the gravity to 0
AtGround := True; // Sets it to grounded making it turn off the gravity
MoveSpeed := 0; // Makes the move speed 0 so the player cannot move while knockback is active
end;
if KnockBackFrame = 0 then // If knockback is active but just falling at the end of it
begin
if KnockBackLeft then // If the knockback is going left minus the x change so it moves left
begin
X -= KNOCKBACKXCHANGE;
end
else // Else make it add the x change so it moves right
begin
X += KNOCKBACKXCHANGE;
end;
AtGround := False;
MoveSpeed := 0; // Makes the move speed 0 so the player cannot move while knockback is active
end;
FallChangeThisFrame := false;
if Fall > 0 then // If the player is falling
begin
Fall -= 1; // Subtract one from the fall frame so it will eventually stop falling
AtGround := False; // Turns on gravity
FallChangeThisFrame := true; // Records that the falling has changed this frame
end;
if (AtGround = False) and (Jump = 0) then // If the player is not grounded and not jumping
begin
Y += GravSpeed; // Adds gravity to the Y to make it fall
if GravSpeed <= PLAYERHEIGHT - 15 then // Cap the gravity so it won't go above a certain value
begin
GravSpeed += 1; // If it is not at the capped limit, add one to the gravity speed
end;
end;
if Health <= 0 then // If the player health is below 0, make the player dead
begin
Health := 0;
dead := True;
end
else // Otherwise regenerate the health, as long as it is below the max health
begin
if Health < PLAYERHEALTH then
begin
Health += HealthRegen;
end;
end;
end;
procedure TPlayer.FallDead();
begin
MoveSpeed := 0; // Make it unable to move left or right.
Y += GravSpeed; // Add the gravity to the Y
if GravSpeed <= PLAYERHEIGHT - 15 then // Adds one to the gravity if it is within
// the capped limit.
begin
GravSpeed += 1;
end;
end;
procedure TPlayer.updateShoot();
begin
timeSinceShot += 1; // adds one to the time since it shot
if timeSinceShot >= SHOTINTERVAL then // If it has been the minimum time allowed before
// it can shoot again, make it able to shoot.
begin
canShoot := True;
end;
end;
procedure TPlayer.resetShoot();
begin
canShoot := False; // Makes it unable to shoot
timeSinceShot := 0; // Records that it has just shot in the current frame
end;
procedure TPlayer.isGrounded(height : float; Fixed : array of UPlat.TPlat;
Rand : array of UPlat.TPlat);
begin
CanWallJump := false; // So that you can not always wall jump even when not on a wall
i := 0;
while i <= High(Fixed) do // Iterate through the fixed platforms
begin
if (Fall = 0) or (Fixed[i].noFall) then // If the player is not falling, or you cannot fall through the platform
begin
if CollideLeft(Fixed[i]) then // Checks the left side collision, and act accordingly
begin
CollidedLeft(Fixed[i]);
break;
end;
end;
i += 1; // Selects the next platform
end;
i := 0;
while i <= High(Fixed) do // Iterate through the fixed platforms
begin
if (Fall = 0) or (Fixed[i].noFall) then // If the player is not falling, or you cannot fall through the platform
begin
if CollideRight(Fixed[i]) then // Checks the right side collision, and acts accordingly
begin
CollidedRight(Fixed[i]);
break;
end;
end;
i += 1; // Selects the next platform
end;
i := 0;
while i <= High(Rand) do // Iterate through the random platforms
begin
if (Fall = 0) or (Rand[i].noFall) then // If the player is not falling, or you cannot fall through the platform
begin
if CollideLeft(Rand[i]) then // Checks the left side collision, and acts accordingly
begin
CollidedLeft(Rand[i]);
break;
end;
end;
i += 1; // Selects the next platform
end;
i := 0;
while i <= High(Rand) do // Iterate through the random platforms
begin
if (Fall = 0) or (Rand[i].noFall) then // If the player is not falling, or you cannot fall through the platform
begin
if CollideRight(Rand[i]) then // Checks the right side collision and acts accordingly
begin
CollidedRight(Rand[i]);
break;
end;
end;
i += 1; // Selects the next platform
end;
AtGround := False; // Sets atGround to false so that it iterates over the
// platforms and if it is no longer grounded, it will set it to not
// grounded rather than just keep this at true
// Iterate through the fixed platforms
i := 0;
while (i <= High(Fixed)) do
begin
if CollideTop(Fixed[i]) then // Checks the top side collision, and acts accordingly
begin
CollidedTop(Fixed[i]);
break;
end;
i += 1; // Selects the next platform
end;
i := 0;
while (i <= High(Rand)) do // Iterate through the random platforms
begin
if CollideTop(Rand[i]) then // Checks the top side collision, and act accordingly
begin
CollidedTop(Rand[i]);
break;
end;
i += 1; // Selects the next platform
end;
i := 0;
// Iterate through the fixed platforms while the player is not AtGround
while (AtGround = False) and (i <= High(Fixed)) do
begin
if CollideBottom(Fixed[i]) then // Checks the bottom collision, and acts accordingly
begin
if (Fall = 0) or (Fixed[i].noFall) then // If the player is not falling, or you cannot fall through the platform
begin
Fall := 0;
CollidedBottom(Fixed[i]);
break;
end
// Keeps us falling if were still in a vertical platform
else if (FallChangeThisFrame = true) and (Fall <= 2) and (Fixed[i].horizontal = false) then
begin
Fall := 2;
break;
end;
end;
i += 1; // Selects the next platform
end;
i := 0;
// Iterate through the random platforms while the player is not AtGround
while (AtGround = False) and (i <= High(Rand)) do
begin
if CollideBottom(Rand[i]) then // Checks the bottom collision and acts accordingly
begin
if (Fall = 0) or (Rand[i].noFall) then // If the player is not falling, or you cannot fall through the platform
begin
Fall := 0;
CollidedBottom(Rand[i]);
break;
end
// Keeps us falling if were still in a vertical platform
else if (FallChangeThisFrame = true) and (Fall <= 2) and (Rand[i].horizontal = false) then
begin
Fall := 2;
break;
end;
end;
i += 1; // Selects the next platform
end;
if Y <= -1 then // If the Y is less than 0
begin
Jump := 0; // Stop it increasing height and ready to fall
Y := 0; // Sets the Y to 0, being the minimum
GravSpeed := 0; // Sets the gravity to 0
end;
if (Y >= height) and (Dead = False) then // If the Y is lower than the
// maximum y and it is not already dead
begin
dead := True; // Sets the player to dead
end;
end;
procedure TPlayer.Move(Direction : MoveCommands);
begin
if Direction = MoveCommands.right then // If it was instructed to move right, make it move right.
begin
GoingLeft := False;
GoingRight := True;
FaceLeft := False;
end
else if Direction = MoveCommands.left then // If it was instructed to move left, make it move left.
begin
GoingLeft := True;
GoingRight := False;
FaceLeft := True;
end
else if Direction = MoveCommands.null then // If it was instructed to stop moving, stop it moving.
begin
GoingLeft := False;
GoingRight := False;
end;
end;
procedure TPlayer.doJump();
begin
if (Jumps < 2) and (Jump <= 7) and (Fall = 0) then // If you have done less than 2 jumps already and
// the player's jump frame is less than 7 (to
// stop a massive jump at the start)
begin
Fall := 0;
Jumps += 1; // Increase the amount of jumps done
Jump := MAXJUMPFRAMES; // Sets the frames for the jump to the maximum
end;
if (CanWallJump) and (Fall = 0) then // Jumps off the wall if the player can
begin
Fall := 0;
Jumps := 1; // Sets it to one, so that the player can do another jump in the
// air after jumping off the wall
Jump := MAXJUMPFRAMES; // Sets the frames for the jump to the maximum
if MoveSpeed = 0 then
begin
if FaceLeft then
MoveSpeed := MAXMOVESPEED
else
MoveSpeed := -MAXMOVESPEED;
end
else if MoveSpeed < 0 then
MoveSpeed := MAXMOVESPEED
else
MoveSpeed := -MAXMOVESPEED;
end;
end;
procedure TPlayer.doFall();
begin
if (Fall = 0) and (AtGround = True) then // If the fall is inactive and you are on a platform
begin
Fall := 15; // Fall frames set to 15
GravSpeed := 0;
end;
end;
procedure TPlayer.CollidedLeft(Plat : TPlat);
begin
if MoveSpeed < 0.2 then
begin
MoveSpeed := -0.1; // So you do not shoot off after getting out the way of the platform and so you do not stick to the platform
X := Plat.X + Plat.Width + 0.1; // Sets the x to the right hand side of the platform
end;
if Plat.NoWallJump = false then
CanWallJump := true; // Allows the player to jump off the wall if the platform is not a no wall jump platform
if KnockBackFrame <> -1 then // Stop knockback so you can move again and so you dont move through the platform
begin
Jump := KnockBackFrame;
KnockBackFrame := -1;
end;
end;
procedure TPlayer.CollidedRight(Plat : TPlat);
begin
if MoveSpeed > -0.2 then
begin
MoveSpeed := 0.1; // So you do not shoot off after getting out the way of the platform and so you do not stick to the platform
X := Plat.X - PLAYERHEAD - 0.1; // Puts the X to the left of the platform
end;
if Plat.NoWallJump = false then
CanWallJump := true; // Allows the player to jump off the wall if the platform is not a no wall jump platform
if KnockBackFrame <> -1 then // Stop knockback so you can move again and so you don't move through the platform
begin
Jump := KnockBackFrame;
KnockBackFrame := -1;
end;
end;
procedure TPlayer.CollidedTop(Plat : TPlat);
begin
Jump := 0; // Sets the jump frame to 0, meaning it is going to start falling again
if KnockBackFrame <> -1 then // If the knockback is not inactive
begin
KnockBackFrame := 0; // Sets the knockback to active, but falling
end;
Y := Plat.Y + Plat.Height + 0.25; // Puts the player Y to under the platform
GravSpeed := 0; // Sets the gravity to 0, and it will fall
end;
procedure TPlayer.CollidedBottom(Plat : TPlat);
begin
Y := Plat.Y - PLAYERHEIGHT; // Sets the Y on top of the platform
AtGround := True; // Sets it to be AtGround
Jumps := 0; // Makes you able to (double) jump again
GravSpeed := 0; // Sets the gravity to 0 so it does not fall any more
KnockBackFrame := -1; // Makes the player knockback inactive (for if it was active)
if Plat.Crumble then
begin
Plat.Crumbling := true; // if the plat is a crumble one, it will activate the crumble sequence
end;
end;
function TPlayer.CollideLeft(Plat : TPlat) : boolean;
var
// If this is false, it won't bother checking the Y collision as it has already
// failed the X collision, so has not collided. This makes it more efficient.
stillCheck : boolean;
begin
stillCheck := false;
// Checks if the left hand side overlaps the right hand side of the platform
if (X <= Plat.X + Plat.Width) and (X >= Plat.X + Plat.Width - MAXMOVESPEED - 1) then
begin
stillCheck := true; // If it overlapped, still check the y axis overlap
end;
if stillCheck then // Checks for a Y overlap
begin
// If the bottom of the player is overlapping the y range of the platform
if (Y + PLAYERHEIGHT > Plat.Y) and (Y + PLAYERHEIGHT < Plat.Y + Plat.HEIGHT) then
begin
Exit(true); // If it succeeded, it passed both so it returns true
end
// If the top of the player is overlapping the y range of the platform
else if (Y > Plat.Y) and (Y < Plat.Y + Plat.HEIGHT) then
begin
Exit(true); // If it succeeded, it passed both so it returns true
end
// If the top of the player if higher than the top of the platform
// and the bottom of the player is lower than the bottom of the platform
else if (Y < Plat.Y) and (Y + PLAYERHEIGHT > Plat.Y + Plat.HEIGHT) then
begin
Exit(true); // If it succeeded, it passed both so it returns true
end;
end;
Exit(false); // At least one of the two failed, so it did not collide
end;
function TPlayer.CollideRight(Plat : TPlat) : boolean;
var
// If this is false, it wont bother checking the Y collision as it has already
// failed the X collision, so has not collided. This makes it more efficient.
stillCheck : boolean;
begin
stillCheck := false;
// Checks if the right hand side of the player overlaps the left side of the platform
if (X + PLAYERHEAD >= Plat.X) and (X + PLAYERHEAD <= Plat.X + MAXMOVESPEED + 1) then
begin
stillCheck := true; // If it overlapped, still check the y axis overlap
end;
if stillCheck then // Checks for a Y overlap
begin
// If the bottom of the player is overlapping the y range of the platform
if (Y + PLAYERHEIGHT > Plat.Y) and (Y + PLAYERHEIGHT < Plat.Y + Plat.HEIGHT) then
begin
Exit(true); // If it succeed, it passed both so it returns true
end
// If the top of the player is overlapping the y range of the platform
else if (Y > Plat.Y) and (Y < Plat.Y + Plat.HEIGHT) then
begin
Exit(true); // If it succeed, it passed both so it returns true
end
// If the top of the player if higher than the top of the platform
// and the bottom of the player is lower than the bottom of the platform
else if (Y < Plat.Y) and (Y + PLAYERHEIGHT > Plat.Y + Plat.HEIGHT) then
begin
Exit(true); // If it succeeded, it passed both so it returns true
end;
end;
Exit(false); // At least one of the two failed, so it did not collide.
end;
function TPlayer.CollideTop(Plat : TPlat) : boolean;
var
// If this is false, it won't bother checking the Y collision as it has already
// failed the X collision, so has not collided. This makes it more efficient.
stillCheck : boolean;
begin
stillCheck := false;
if (Jump <> 0) // if the player's jump is not active, it is not
// moving up so won't hit the top
and (Plat.jumpThrough = false) // This is as if it can jump through it, it
// should not bother checking
and (Y + PLAYERHEIGHT > Plat.Y + Plat.HEIGHT) then // This is so that it knows the player
// is underneath the platform
begin
// Checks if the x range of the player is inside the x range of the platform
if (X < Plat.X + Plat.Width) and (X + PLAYERHEAD > Plat.X) then
begin
stillCheck := true; // if it was true, it will still check the y collision
end;
if stillCheck then // Run the y collision if it is worth checking still
begin
// Checks if the y range is inside the platforms's Y range
if (Y <= Plat.Y + Plat.Height) and (Y + PLAYERHEIGHT >= Plat.Y) then
begin
Exit(true); // If this was true, both were true so its hit
end;
end;
end;
Exit(False); // It is not moving up or can jump through the platform
// or did not collide both, so returns false
end;
function TPlayer.CollideBottom(Plat : TPlat) : boolean;
var
// if this is false, it will not bother checking the Y collision as it has already
// failed the X collision, so has not collided. This makes it more efficient
stillCheck : boolean;
begin
stillCheck := false;
if (Jump = 0) then // if the player's Jump is active, it is not
// moving down so will not land on a platform
begin
// Checks if the x range of the player is inside the x range of the platform
if (X < Plat.X + Plat.Width) and (X + PLAYERHEAD > Plat.X) then
begin
stillCheck := true; // if it was true, it will still check the y collision
end;
if stillCheck then // Run the y collision if it is worth checking still
begin
if GravSpeed < Plat.Height then // Doing two different ways if the gravspeed
// is less than the height of the platform is
// for graphical purposes as it looks
// strange doing it the normal way of
// checking the whole range of the player's
// Y as opposed to just checking if the bottom
// is inside the platform's y range
begin
// Checks if the bottom y is inside the platform's Y range
if (Y + PLAYERHEIGHT <= Plat.Y + Plat.Height) and (Y + PLAYERHEIGHT >= Plat.Y) then
begin
Exit(true); // If this was true, both were true so it has hit
end;
end
else
begin
// Checks if the y range is inside the platforms's Y range
if (Y <= Plat.Y + Plat.Height) and (Y + PLAYERHEIGHT >= Plat.Y) then
begin
Exit(true); // If this was true, both were true so it has hit
end;
end;
end;
end;
Exit(False); // It is not moving up or can jump through the platform
// or did not collide both, so returns false
end;
function TPlayer.ShootAngle(Targx, Targy : float) : float;
var
DifferenceX, DifferenceY : float; // The difference in X and Y between the turret
// and player, making it easy to use in the trigonometry
Angle : float; // The angle that will be returned
begin
DifferenceX := Targx - X;
DifferenceY := Targy - Y;
if (DifferenceX = 0) and (DifferenceY = 0) then // If the player is on the turret
Angle := 0
else if (DifferenceX = 0) and (DifferenceY < 0) then // If the player is above the turret
Angle := 0
else if (DifferenceX = 0) and (DifferenceY > 0) then // If the player is under the turret
Angle := 180
else if (DifferenceX > 0) and (DifferenceY = 0) then // If the player is to the right of the turret
Angle := 90
else if (DifferenceX < 0) and (DifferenceY = 0) then // If the player is to the left of the turret
Angle := 270
// The trigonmetry below works out the angle in radians, throughout the program
// we have been using degrees so at the end of each equation we need
// / (Pi / 180) to convert it from radians to degrees
else if (DifferenceX > 0) and (DifferenceY < 0) then // Angles 0 to 90
begin
if DifferenceX >= DifferenceY * -1 then // Angles 45 to 90
// Uses the angle from the 90 degrees line (right) so it is Y / X
// and needs the 90 - (ANGLE) to make it correct for this quadrant (upper right)
// The DifferenceY is negative so needs the * -1 to make it positive so it works properly
Angle := 90 - (Tanh((DifferenceY * -1) / DifferenceX) / (Pi / 180))
else // Angles 0 to 44
// Uses the angle from the 0 degrees line (up) so is the X / Y
Angle := Tanh(DifferenceX / (DifferenceY * -1)) / (Pi / 180);
end
else if (DifferenceX > 0) and (DifferenceY > 0) then // Angles 90 to 180
begin
if DifferenceX >= DifferenceY then // Angles 90 to 135
// Uses the angle from the 90 degrees line (right) so it is Y / X
// and needs the 90 + (ANGLE) to make it correct for this quadrant (lower right)
Angle := 90 + (Tanh(DifferenceY / DifferenceX) / (Pi / 180))
else // Angles 136 to 180
// Uses the angle from the 180 degrees line (down) so it is X / Y
// and needs to 180 - (ANGLE) to make it correct for this quadrant (lower right)
Angle := 180 - (Tanh(DifferenceX / DifferenceY) / (Pi / 180));
end
else if (DifferenceX < 0) and (DifferenceY < 0) then // Angles 270 to 360
begin
if DifferenceX <= DifferenceY then // Angles 270 to 315
// Uses the angle from the 270 degrees line (left) so it is Y / X
// and needs the 270 + (ANGLE) to make it correct for the quadrant (upper left)
// both are negative so they both need * -1 to make them positive so it works properly
Angle := 270 + (Tanh((DifferenceY * -1) / (DifferenceX * -1)) / (Pi / 180))
else // Angles 316 to 360
// Uses the angle from the 360 degrees line (up) so it is X / Y
// and needs the 360 - (ANGLE) to make it correct for the quadrant (upper left)
// both are negative so they both need * -1 to make them positive so it works properly
Angle := 360 - (Tanh((DifferenceX * -1) / (DifferenceY * -1)) / (Pi / 180));
end
else if (DifferenceX < 0) and (DifferenceY > 0) then // Angles 180 to 270
begin
if DifferenceX * -1 >= DifferenceY then // Angles 225 to 270
// Uses the angle from the 270 degrees line (left) so it is Y / X
// and needs the 270 - (ANGLE) to make it correct for the quadrant (lower left)
// the X is negative so it needs the * -1 to make it positive so it works properly
Angle := 270 - (Tanh(DifferenceY / (DifferenceX * -1)) / (Pi / 180))
else // Angles 224 to 180
// Uses the angle from the 180 degrees line (down) so it is X / Y
// and needs the 180 + (ANGLE) to make it correct for the quadrant (lower left)
// the X is negative so it needs the * -1 to make it positive so it works properly
Angle := 180 + (Tanh((DifferenceX * -1) / DifferenceY) / (Pi / 180));
end;
if FaceLeft then // Make it only be able to shoot to the left
begin
if (Angle < 200) and (Angle >= 90) then
Angle := 200
else if ((Angle < 90) and (Angle >= 0)) or (Angle > 340) then
Angle := 340;
end
else // Make it only be able to shoot to the right
begin
if ((Angle < 360) and (Angle >= 270)) or (Angle < 20) then
Angle := 20
else if (Angle < 270) and (Angle > 160) then
Angle := 160;
end;
Exit(Angle); // Return the angle for the bullet
end;
end. |
{..............................................................................}
{ Summary Server Process Report - }
{ Generate a report for all installed servers' processes. }
{ }
{ Copyright (c) 2004 by Altium Limited }
{..............................................................................}
Var
ReportFile : TStringList;
{..............................................................................}
{..............................................................................}
Function BooleanToString (Value : LongBool) : String;
Begin
Result := 'True';
If Value = True Then Result := 'True'
Else Result := 'False';
End;
{..............................................................................}
{..............................................................................}
Procedure ReportServerProcessInfo;
Var
I : Integer;
J : Integer;
K : Integer;
FileName : TDynamicString;
ReportDocument : IServerDocument;
RecordCount : Integer;
CommandCount : Integer;
ParameterCount : Integer;
ServerRecord : IServerRecord;
ServerProcess : IServerProcess;
S : TDynamicString;
Begin
If Client = Nil Then Exit;
BeginHourGlass;
S := '';
ReportFile := TStringList.Create;
Try
ReportFile.Add('Server Processes information:');
ReportFile.Add('=============================');
ReportFile.Add('');
RecordCount := Client.GetServerRecordCount;
ReportFile.Add(' Server Record Count : ' + IntToStr(RecordCount));
ReportFile.Add(' =========================');
ReportFile.Add('');
For I := 0 to RecordCount - 1 Do
Begin
ServerRecord := Client.GetServerRecord(I);
ReportFile.Add(' Server Name = ' + ServerRecord.GetName + ' #' + IntToStr(I + 1));
ReportFile.Add(' ===============================================================');
ReportFile.Add(' Server Version ' + ServerRecord.GetVersion);
ReportFile.Add(' Server Copyright info ' + ServerRecord.GetCopyRight);
ReportFile.Add(' Server Date ' + ServerRecord.GetDate);
ReportFile.Add(' Server Info ' + ServerRecord.GetGeneralInfo);
ReportFile.Add(' RCS path ' + ServerRecord.GetRCSFilePath);
ReportFile.Add(' Ins Path ' + ServerRecord.GetInsPath);
ReportFile.Add(' Exe Path' + ServerRecord.GetExePath);
ReportFile.Add(' Number of document types ' + IntToStr(ServerRecord.GetWindowKindCount));
ReportFile.Add(' Number of commands ' + IntToStr(ServerRecord.GetCommandCount));
ReportFile.Add(' =====================================');
CommandCount := ServerRecord.GetCommandCount;
For J := 0 To CommandCount - 1 Do
Begin
ServerProcess := ServerRecord.GetCommand(J);
ReportFile.Add(' Process #' + IntToStr(J + 1) + ' Name = ' +
ServerProcess.GetOriginalId + ' LongSummary = ' + ServerProcess.GetLongSummary);
S := '';
ParameterCount := ServerProcess.GetParameterCount;
For K := 0 To ParameterCount - 1 Do
S := S + ServerProcess.GetParameter(K) + ', ';
ReportFile.Add(' Parameters = ' + S);
End;
ReportFile.Add('');
S := '';
End;
Finally
FileName := SpecialFolder_MyDesigns + '\ServerProcesses_Report.Txt';
ReportFile.SaveToFile(FileName);
ReportFile.Free;
End;
ReportDocument := Client.OpenDocument('Text', FileName);
If ReportDocument <> Nil Then
Client.ShowDocument(ReportDocument);
EndHourGlass;
End;
{..............................................................................}
{..............................................................................}
|
unit SettingsUnit;
// ------------------------------------
// MesoScan - Scan Settings dialog box
// ------------------------------------
// 1-6-12 MinPixelDwellTimeAdded
// 29.11.16 Lens table added
// 16.01.17 ZStage.XScaleFactor and ZStage.YScaleFactor added
// 22.03.17 USB-controlled CoolLED pE-x support added
// 10.05.17 ZPositionMin, ZPositionMax limits added
// 09.10.17 MainFrm.Cam1.CameraTemperatureSetPoint now updated by settings
// 06.11.17 Cam1.CCDTapOffsetLT etc. CCD tap black offset adjustment properties added and can be changed by user
// 08.04.19 Calbration bar and temperature set point labells now in correct places
// 19.03.22 Light source chanage time setting added
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, ValidatedEdit, math,
Vcl.ExtCtrls,LabIOUnit,LightSourceUnit, Vcl.ComCtrls, Vcl.Grids, strutils ;
type
TSettingsFrm = class(TForm)
bOK: TButton;
bCancel: TButton;
Page: TPageControl;
CameraTab: TTabSheet;
GroupBox4: TGroupBox;
cbCamera: TComboBox;
ModePanel: TPanel;
lbCameraMode: TLabel;
cbCameraMode: TComboBox;
ComPanel: TPanel;
lbComPort: TLabel;
cbCameraPort: TComboBox;
ReadoutSpeedPanel: TPanel;
Label1: TLabel;
cbReadoutSpeed: TComboBox;
ADCPanel: TPanel;
Label48: TLabel;
cbCameraADC: TComboBox;
CameraPanel: TPanel;
Label77: TLabel;
cbCameraNames: TComboBox;
LightSourceTab: TTabSheet;
LEDGrp: TGroupBox;
Label4: TLabel;
Label5: TLabel;
ZStageTab: TTabSheet;
GroupBox2: TGroupBox;
Label10: TLabel;
Label13: TLabel;
edZScaleFactor: TValidatedEdit;
cbZStageType: TComboBox;
edZStepTime: TValidatedEdit;
Label6: TLabel;
pnLightSource0: TPanel;
Edit2: TEdit;
ComboBox2: TComboBox;
ValidatedEdit3: TValidatedEdit;
ValidatedEdit4: TValidatedEdit;
Label7: TLabel;
pnLightSource1: TPanel;
Edit3: TEdit;
ComboBox3: TComboBox;
ValidatedEdit5: TValidatedEdit;
ValidatedEdit6: TValidatedEdit;
pnLightSource2: TPanel;
Edit4: TEdit;
ComboBox4: TComboBox;
ValidatedEdit7: TValidatedEdit;
ValidatedEdit8: TValidatedEdit;
pnLightSource3: TPanel;
Edit5: TEdit;
ComboBox5: TComboBox;
ValidatedEdit9: TValidatedEdit;
ValidatedEdit10: TValidatedEdit;
pnLightSource4: TPanel;
Edit6: TEdit;
ComboBox6: TComboBox;
ValidatedEdit11: TValidatedEdit;
ValidatedEdit12: TValidatedEdit;
pnLightSource5: TPanel;
Edit7: TEdit;
ComboBox7: TComboBox;
ValidatedEdit13: TValidatedEdit;
ValidatedEdit14: TValidatedEdit;
pnLightSource6: TPanel;
Edit8: TEdit;
ComboBox8: TComboBox;
ValidatedEdit15: TValidatedEdit;
ValidatedEdit16: TValidatedEdit;
pnLightSource7: TPanel;
Edit9: TEdit;
ComboBox9: TComboBox;
ValidatedEdit17: TValidatedEdit;
ValidatedEdit18: TValidatedEdit;
GroupBox5: TGroupBox;
Label25: TLabel;
edImageJPath: TEdit;
ckSaveAsMultipageTIFF: TCheckBox;
LensTab: TTabSheet;
CalibrationGrp: TGroupBox;
Label2: TLabel;
Label11: TLabel;
edNumLenses: TValidatedEdit;
sgLensTable: TStringGrid;
edRelayLensMagnification: TValidatedEdit;
udNumLenses: TUpDown;
edXScalefactor: TValidatedEdit;
Label12: TLabel;
edYScaleFactor: TValidatedEdit;
Label14: TLabel;
CoolLEDGrp: TGroupBox;
cbLightSourceControlPort: TComboBox;
Label15: TLabel;
cbSourceType: TComboBox;
lbSourceType: TLabel;
Label16: TLabel;
edZpositionMin: TValidatedEdit;
Label17: TLabel;
edZPositionMax: TValidatedEdit;
Label18: TLabel;
edRawFileFolder: TEdit;
BlackLevelOffsetsGrp: TGroupBox;
Label19: TLabel;
Label20: TLabel;
edCCDTapOffsetRT: TValidatedEdit;
Label21: TLabel;
Label22: TLabel;
edCCDTapOffsetLB: TValidatedEdit;
edCCDTapOffsetLT: TValidatedEdit;
edCCDTapOffsetRB: TValidatedEdit;
GroupBox1: TGroupBox;
Label3: TLabel;
Label9: TLabel;
Label41: TLabel;
edCalibrationBarSize: TValidatedEdit;
edCameraPixelSize: TValidatedEdit;
edTemperatureSetPoint: TValidatedEdit;
ControlPortPanel: TPanel;
Label8: TLabel;
cbZStagePort: TComboBox;
SerialNumberPanel: TPanel;
Label23: TLabel;
edSerialNumber: TEdit;
LSCommonGrp: TGroupBox;
edLightSourceChangeTime: TValidatedEdit;
Label24: TLabel;
procedure FormShow(Sender: TObject);
procedure bOKClick(Sender: TObject);
procedure bCancelClick(Sender: TObject);
procedure cbZStageTypeChange(Sender: TObject);
procedure cbCameraChange(Sender: TObject);
procedure cbCameraNamesChange(Sender: TObject);
procedure cbCameraADCChange(Sender: TObject);
procedure cbCameraModeChange(Sender: TObject);
procedure udNumLensesChangingEx(Sender: TObject; var AllowChange: Boolean;
NewValue: Integer; Direction: TUpDownDirection);
procedure edNumLensesKeyPress(Sender: TObject; var Key: Char);
procedure cbSourceTypeChange(Sender: TObject);
private
{ Private declarations }
procedure ShowLightSourcePanel ;
procedure SetLightSourcePanel(
Num : Integer ;
Panel : TPanel ) ;
procedure GetLightSourcePanel(
Num : Integer ;
Panel : TPanel ) ;
procedure NewCamera(Reopen : Boolean) ;
public
{ Public declarations }
end;
var
SettingsFrm: TSettingsFrm;
implementation
{$R *.dfm}
uses MainUnit, ZStageUnit;
procedure TSettingsFrm.FormShow(Sender: TObject);
// --------------------------
// Initialise form on display
// --------------------------
var
i : Integer ;
begin
if MainFrm.Cam1.CameraActive then MainFrm.Cam1.StopCapture ;
// Get camera library list
MainFrm.Cam1.GetCameraLibList( cbCamera.Items ) ;
cbCamera.ItemIndex := MainFrm.CameraType ;
// Get names of available cameras
MainFrm.Cam1.GetCameraNameList( cbCameraNames.Items ) ;
cbCameraNames.ItemIndex := MainFrm.Cam1.SelectedCamera ;
// Get camera COM port
cbCameraPort.ItemIndex := MainFrm.Cam1.ComPort - 1 ;
// Reset camera
NewCamera(false) ;
// Z stage control
ZStage.GetZStageTypes(cbZStageType.Items);
cbZStageType.ItemIndex := Min(Max(ZStage.StageType,0),cbZStageType.Items.Count-1) ;
ZStage.GetControlPorts(cbZStagePort.Items);
cbZStagePort.ItemIndex := Min(Max(ZStage.ControlPort,0),cbZStagePort.Items.Count-1) ;
// Light Sources
LightSource.GetSourceTypes(cbSourceType.Items);
cbSourceType.ItemIndex := LightSource.SourceType ;
ShowLightSourcePanel ;
edLightSourceChangeTime.Value := LightSource.ChangeTime ;
// COM port list
LightSource.GetControlPorts(cbLightSourceControlPort.Items);
cbLightSourceControlPort.ItemIndex := Min(Max(LightSource.ControlPort-1,0),
cbLightSourceControlPort.Items.Count-1) ;
SetLightSourcePanel( 0, pnLightSource0 ) ;
SetLightSourcePanel( 1, pnLightSource1 ) ;
SetLightSourcePanel( 2, pnLightSource2 ) ;
SetLightSourcePanel( 3, pnLightSource3 ) ;
SetLightSourcePanel( 4, pnLightSource4 ) ;
SetLightSourcePanel( 5, pnLightSource5 ) ;
SetLightSourcePanel( 6, pnLightSource6 ) ;
SetLightSourcePanel( 7, pnLightSource7 ) ;
// Stage control
edXScaleFactor.Units := ZStage.ScaleFactorUnits ;
edXScaleFactor.Value := ZStage.XScaleFactor ;
edYScaleFactor.Units := ZStage.ScaleFactorUnits ;
edYScaleFactor.Value := ZStage.YScaleFactor ;
edZScaleFactor.Units := ZStage.ScaleFactorUnits ;
edZScaleFactor.Value := ZStage.ZScaleFactor ;
edZStepTime.Value := ZStage.ZStepTime ;
edZPositionMin.Value := ZStage.ZPositionMin ;
edZPositionMax.Value := ZStage.ZPositionMax ;
edSerialNumber.Text := ZStage.SerialNumber ;
edNumLenses.Value := MainFrm.NumLenses ;
sgLensTable.RowCount := MainFrm.NumLenses+1 ;
sgLensTable.Cells[0,0] := ' Name ' ;
sgLensTable.ColWidths[0] := 90 ; //sgLensTable.Canvas.TextWidth(sgLensTable.Cells[0,0]);
sgLensTable.Cells[1,0] := ' Magnification ' ;
sgLensTable.ColWidths[1] := 90 ;//sgLensTable.Canvas.TextWidth(sgLensTable.Cells[1,0]);
for I := 0 to MainFrm.NumLenses-1 do
begin
sgLensTable.Cells[0,i+1] := MainFrm.LensName[i] ;
sgLensTable.Cells[1,i+1] := format('%.4g',[MainFrm.LensMagnification[i]]);
end;
edRelayLensMagnification.Value := MainFrm.RelayLensMagnification ;
edCameraPixelSize.Value := MainFrm.CameraPixelSize ;
edTemperatureSetPoint.Value := MainFrm.Cam1.CameraTemperatureSetPoint ;
edCalibrationBarSize.Value := MainFrm.CalibrationBarSize ;
// CCD tap black level offsets
edCCDTapOffsetLT.Value := MainFRm.Cam1.CCDTapOffsetLT ;
edCCDTapOffsetRT.Value := MainFRm.Cam1.CCDTapOffsetRT ;
edCCDTapOffsetLB.Value := MainFRm.Cam1.CCDTapOffsetLB ;
edCCDTapOffsetRB.Value := MainFRm.Cam1.CCDTapOffsetRB ;
edImageJPath.Text := MainFrm.ImageJPath ;
ckSaveAsMultipageTIFF.Checked := MainFrm.SaveAsMultipageTIFF ;
edRawFileFolder.Text := ExtractFilePath(MainFrm.RawImagesFileName) ;
// Show optional controls
ControlPortPanel.Visible := ZStage.IsControlPortRequired ;
SerialNumberPanel.Visible := ZStage.IsSerialNumberRequired ;
end;
procedure TSettingsFrm.ShowLightSourcePanel ;
// -----------------------------------------
// Show settings panel for light source type
// -----------------------------------------
begin
// Select panel
LEDGrp.Visible := False ;
CoolLEDGrp.Visible := False ;
case LightSource.SourceType of
lsLED : LEDGrp.Visible := True ;
lsCoolLED,lsThorlabsFW102 : CoolLEDGrp.Visible := True ;
end ;
end ;
procedure TSettingsFrm.bCancelClick(Sender: TObject);
// ---------------------
// Cancel and close form
// ---------------------
begin
Close
end;
procedure TSettingsFrm.bOKClick(Sender: TObject);
// --------------------------
// Update program settings
// --------------------------
var
i,Code : Integer ;
begin
// Light source
GetLightSourcePanel( 0, pnLightSource0 ) ;
GetLightSourcePanel( 1, pnLightSource1 ) ;
GetLightSourcePanel( 2, pnLightSource2 ) ;
GetLightSourcePanel( 3, pnLightSource3 ) ;
GetLightSourcePanel( 4, pnLightSource4 ) ;
GetLightSourcePanel( 5, pnLightSource5 ) ;
GetLightSourcePanel( 6, pnLightSource6 ) ;
GetLightSourcePanel( 7, pnLightSource7 ) ;
ZStage.ControlPort := cbZStagePort.ItemIndex ;
ZStage.XScaleFactor := edXScaleFactor.Value ;
ZStage.YScaleFactor := edYScaleFactor.Value ;
ZStage.ZScaleFactor := edZScaleFactor.Value ;
ZStage.ZStepTime := edZStepTime.Value ;
ZStage.ZPositionMin := edZPositionMin.Value ;
ZStage.ZPositionMax := edZPositionMax.Value ;
ZStage.SerialNumber := edSerialNumber.Text ;
LightSource.ControlPort := cbLightSourceControlPort.ItemIndex + 1 ;
LightSource.ChangeTime := edLightSourceChangeTime.Value ;
LightSource.Close ;
LightSource.Open ;
MainFrm.SetScanZoomToFullField ;
MainFrm.NumLenses := Round(edNumLenses.Value);
MainFrm.RelayLensMagnification := Max(edRelayLensMagnification.Value,0.001) ;
for I := 0 to MainFrm.NumLenses-1 do
begin
MainFrm.LensName[i] := sgLensTable.Cells[0,i+1] ;
Val(sgLensTable.Cells[1,i+1],MainFrm.LensMagnification[i],Code) ;
end;
MainFrm.CameraPixelSize := edCameraPixelSize.Value ;
MainFrm.MagnifiedCameraPixelSize := MainFrm.CameraPixelSize/
(MainFrm.RelayLensMagnification) ;
MainFrm.Cam1.CameraTemperatureSetPoint := edTemperatureSetPoint.Value ;
MainFrm.CalibrationBarSize := edCalibrationBarSize.Value ;
// CCD tap black level offsets
MainFRm.Cam1.CCDTapOffsetLT := Round(edCCDTapOffsetLT.Value) ;
MainFRm.Cam1.CCDTapOffsetRT := Round(edCCDTapOffsetRT.Value) ;
MainFRm.Cam1.CCDTapOffsetLB := Round(edCCDTapOffsetLB.Value) ;
MainFRm.Cam1.CCDTapOffsetRB := Round(edCCDTapOffsetRB.Value) ;
// Update camera gain list
MainFrm.Cam1.GetCameraGainList( MainFrm.cbCameraGain.Items );
MainFrm.cbCameraGain.ItemIndex := 0 ;
// Camera readout speed
MainFrm.Cam1.ReadoutSpeed := cbReadoutSpeed.ItemIndex ;
MainFrm.ImageJPath := edImageJPath.Text ;
MainFrm.SaveAsMultipageTIFF := ckSaveAsMultipageTIFF.Checked ;
MainFrm.RawImagesFileName := edRawFileFolder.Text + '\mesocam.raw' ;
// Ensure no duplications of \
for i := 1 to 3 do MainFrm.RawImagesFileName := ANSIReplaceStr( MainFrm.RawImagesFileName, '\\', '\');
Close ;
end;
procedure TSettingsFrm.cbCameraADCChange(Sender: TObject);
begin
MainFrm.Cam1.CameraADC := cbCameraADC.ItemIndex ;
NewCamera(true) ;
end;
procedure TSettingsFrm.cbCameraChange(Sender: TObject);
// --------------
// Camera changed
// --------------
begin
NewCamera(true) ;
// Set camera readout speed to maximum
if cbReadoutSpeed.Visible then
begin
cbReadoutSpeed.ItemIndex := MainFrm.Cam1.DefaultReadoutSpeed ;
end ;
end;
procedure TSettingsFrm.cbCameraModeChange(Sender: TObject);
begin
MainFrm.Cam1.CameraMode := cbCameraMode.ItemIndex ;
// MainFrm.Cam1.CameraADC := MainFrm.Cam1.CameraADC ;
NewCamera(true) ;
end;
procedure TSettingsFrm.cbCameraNamesChange(Sender: TObject);
begin
MainFrm.Cam1.SelectedCamera := cbCameraNames.ItemIndex ;
NewCamera(true) ;
end;
procedure TSettingsFrm.cbSourceTypeChange(Sender: TObject);
// -------------------------
// Light source type changed
// -------------------------
begin
LightSource.SourceType := cbSourceType.ItemIndex ;
ShowLightSourcePanel ;
end;
procedure TSettingsFrm.cbZStageTypeChange(Sender: TObject);
//
// Zstage type changed
//
begin
ZStage.StageType := cbZStageType.ItemIndex ;
ZStage.GetControlPorts(cbZStagePort.Items);
cbZStagePort.ItemIndex := Min(Max(ZStage.ControlPort,0),cbZStagePort.Items.Count-1) ;
edZScaleFactor.Units := ZStage.ScaleFactorUnits ;
edZScaleFactor.Value := ZStage.ZScaleFactor ;
// Show optional controls
ControlPortPanel.Visible := ZStage.IsControlPortRequired ;
SerialNumberPanel.Visible := ZStage.IsSerialNumberRequired ;
end;
procedure TSettingsFrm.edNumLensesKeyPress(Sender: TObject; var Key: Char);
// -------------------------------
// No. of available lenses changed
// -------------------------------
begin
if Key = #13 then sgLensTable.RowCount := Round(edNumLenses.Value) + 1 ;
end;
procedure TSettingsFrm.SetLightSourcePanel(
Num : Integer ;
Panel : TPanel ) ;
//
// Update light source settings panel controls
// -------------------------------------------
var
i : Integer ;
begin
for i := 0 to 3 do if Panel.Controls[i].Tag = 0 then
TEdit(Panel.Controls[i]).Text := LightSource.Names[Num] ;
for i := 0 to 3 do if Panel.Controls[i].Tag = 1 then
begin
LightSource.GetControlLineNames( TComboBox(Panel.Controls[i]).Items ) ;
TComboBox(Panel.Controls[i]).ItemIndex :=
TComboBox(Panel.Controls[i]).Items.IndexOfObject(TObject(LightSource.ControlLines[Num])) ;
end ;
for i := 0 to 3 do if Panel.Controls[i].Tag = 2 then
TValidatedEdit(Panel.Controls[i]).Value := LightSource.MinLevel[Num] ;
for i := 0 to 3 do if Panel.Controls[i].Tag = 3 then
TValidatedEdit(Panel.Controls[i]).Value := LightSource.MaxLevel[Num] ;
end;
procedure TSettingsFrm.udNumLensesChangingEx(Sender: TObject;
var AllowChange: Boolean; NewValue: Integer; Direction: TUpDownDirection);
begin
case Direction of
updUp : edNumLenses.Value := edNumLenses.Value + 1.0 ;
updDown : edNumLenses.Value := edNumLenses.Value - 1.0 ;
end;
sgLensTable.RowCount := Round(edNumLenses.Value) + 1 ;
end;
procedure TSettingsFrm.GetLightSourcePanel(
Num : Integer ;
Panel : TPanel ) ;
// -----------------------------------------
// Read light source settings panel controls
// -----------------------------------------
var
i : Integer ;
begin
for i := 0 to 3 do if Panel.Controls[i].Tag = 0 then
LightSource.Names[Num] := TEdit(Panel.Controls[i]).Text ;
for i := 0 to 3 do if (Panel.Controls[i].Tag = 1) and
(TComboBox(Panel.Controls[i]).ItemIndex >= 0) then
LightSource.ControlLines[Num] := Integer(
TComboBox(Panel.Controls[i]).Items.Objects[TComboBox(Panel.Controls[i]).ItemIndex]) ;
for i := 0 to 3 do if Panel.Controls[i].Tag = 2 then
LightSource.MinLevel[Num] := TValidatedEdit(Panel.Controls[i]).Value;
for i := 0 to 3 do if Panel.Controls[i].Tag = 3 then
LightSource.MaxLevel[Num] := TValidatedEdit(Panel.Controls[i]).Value ;
end;
procedure TSettingsFrm.NewCamera(Reopen : Boolean) ;
// ---------------------------------------------
// Setup up dialog box for newly selected camera
// ---------------------------------------------
var
iTop : Integer ;
begin
// Close existing camera and re-open new if required
if Reopen then
begin
Screen.Cursor := crHourglass ;
MainFrm.edStatus.Text := ' WAIT: Initialising camera ... ' ;
MainFrm.Cam1.CloseCamera ;
// Update main camera type
MainFrm.CameraType := cbCamera.ItemIndex ;
// Open new camera
MainFrm.Cam1.ComPort := cbCameraPort.ItemIndex + 1 ;
MainFrm.Cam1.OpenCamera( MainFrm.CameraType ) ;
MainFrm.Cam1.FrameInterval := 0.1 ;
MainFrm.edStatus.Text := ' Camera Initialised ' ;
Screen.Cursor := crDefault ;
end ;
// Get list of available camera operating modes
iTop := cbCamera.Top + cbCamera.Height + 5 ;
// Show camera selection panel if more than one camera available
CameraPanel.Top := iTop ;
if MainFrm.Cam1.NumCameras > 1 then
begin
CameraPanel.Visible := True ;
iTop := iTop + CameraPanel.Height ;
end
else CameraPanel.Visible := False ;
// Initialise look-up tables
MainFrm.GreyLo := 0 ;
MainFrm.GreyHi := MainFrm.Cam1.GreyLevelMax ;
MainFrm.GreyLevelMax := MainFrm.Cam1.GreyLevelMax ;
MainFrm.UpdateLUT( MainFrm.Cam1.GreyLevelMax ) ;
ModePanel.Top := iTop ;
MainFrm.Cam1.GetCameraModeList( cbCameraMode.Items );
if cbCameraMode.Items.Count > 1 then ModePanel.Visible := True
else ModePanel.Visible := False ;
cbCameraMode.ItemIndex := Min(MainFrm.Cam1.CameraMode,cbCameraMode.Items.Count-1) ;
if ModePanel.Visible then iTop := iTop + ModePanel.Height ;
// Get list of available camera A/D converters
ADCPanel.Top := iTop ;
MainFrm.Cam1.GetCameraADCList( cbCameraADC.Items );
cbCameraADC.ItemIndex := MainFrm.Cam1.CameraADC ;
if cbCameraADC.Items.Count > 1 then ADCPanel.Visible := True
else ADCPanel.Visible := False ;
if ADCPanel.Visible then iTop := iTop + ADCPanel.Height ;
// Get list of available camera readout speeds
ReadoutSpeedPanel.Top := iTop ;
MainFrm.Cam1.GetCameraReadoutSpeedList( cbReadoutSpeed.Items );
cbReadoutSpeed.ItemIndex := MainFrm.Cam1.ReadoutSpeed ;
if cbReadoutSpeed.Items.Count > 0 then ReadoutSpeedPanel.Visible := True
else ReadoutSpeedPanel.Visible := False ;
if ReadoutSpeedPanel.Visible then iTop := iTop + ReadoutSpeedPanel.Height ;
// Display camera control COM port (if present)
ComPanel.Top := iTop ;
if MainFrm.Cam1.ComPortUsed then
begin
ComPanel.Visible := True ;
iTop := iTop + ComPanel.Height ;
cbCameraPort.ItemIndex := MainFrm.Cam1.ComPort - 1 ;
end
else
begin
cbCameraPort.ItemIndex := -1 ;
ComPanel.Visible := False ;
end ;
//edCameraTriggerOffset.Value := MainFrm.CameraTriggerOffset ;
//edCameraReadoutTime.Value := MainFrm.Cam1.AdditionalReadoutTime ;
end ;
end.
|
unit frmJournalPedagogue;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Mask, Vcl.ComCtrls, dbfunc, uKernel;
type
TfJournalPedagogue = class(TForm)
Panel3: TPanel;
Panel1: TPanel;
lvLGNameLastLesson: TListView;
rgMounth: TRadioGroup;
bIndividualJournal: TButton;
bClose: TButton;
bCollectiveJournal: TButton;
cmbAcademicYear: TComboBox;
Label1: TLabel;
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure lvLGNameLastLessonItemChecked(Sender: TObject; Item: TListItem);
procedure bIndividualJournalClick(Sender: TObject);
procedure bCollectiveJournalClick(Sender: TObject);
procedure lvLGNameLastLessonSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
procedure cmbAcademicYearChange(Sender: TObject);
private
AcademicYear: TResultTable;
GropeNameLastLesson: TResultTable;
FIDPedagogue: integer;
FStrPedagogue: string;
FIDAcademicYear: integer;
FStrAcademicYear: string;
procedure SetIDPedagogue(const Value: integer);
procedure SetStrPedagogue(const Value: string);
procedure SetIDAcademicYear(const Value: integer);
procedure SetStrAcademicYear(const Value: string);
procedure ShowLGNameLastLesson;
public
property StrPedagogue: string read FStrPedagogue write SetStrPedagogue;
property IDPedagogue: integer read FIDPedagogue write SetIDPedagogue;
property StrAcademicYear: string read FStrAcademicYear
write SetStrAcademicYear;
property IDAcademicYear: integer read FIDAcademicYear
write SetIDAcademicYear;
end;
var
fJournalPedagogue: TfJournalPedagogue;
implementation
{$R *.dfm}
uses frmJournalPedagogueByCollectiveGroupChild,
frmJournalPedagogueByIndividualGroupChild;
{ TfJournalPedagogue }
// журнал педагога, журнал посещаемости (инд, групп- и мелкогрупповых занятий)
// разновидности (особенности, описания) журналов
// инд страничка ученика: lv с датой, днем недели, кол-во часов (0 или 1), тема занятия (с кодом/шифром) или коммент к уроку, возможно статус
// процедура для автозаполнения статусов расписания как утвержденных
procedure TfJournalPedagogue.bCollectiveJournalClick(Sender: TObject);
begin
if (not Assigned(fJournalPedagogueByCollectiveGroupChild)) then
fJournalPedagogueByCollectiveGroupChild :=
TfJournalPedagogueByCollectiveGroupChild.Create(Self);
// fJournalPedagogueByCollectiveGroupChild.IDPedagogue := IDPedagogue;
// fJournalPedagogueByCollectiveGroupChild.IDCurAcademicYear := IDCurAY;
fJournalPedagogueByCollectiveGroupChild.Show;
end;
procedure TfJournalPedagogue.bIndividualJournalClick(Sender: TObject);
begin
if (not Assigned(fJournalPedagogueByIndividualGroupChild)) then
fJournalPedagogueByIndividualGroupChild :=
TfJournalPedagogueByIndividualGroupChild.Create(Self);
fJournalPedagogueByIndividualGroupChild.IDPedagogue := IDPedagogue;
fJournalPedagogueByIndividualGroupChild.IDAcademicYear := IDAcademicYear;
fJournalPedagogueByIndividualGroupChild.StrPedagogue := StrPedagogue;
fJournalPedagogueByIndividualGroupChild.StrAcademicYear := StrAcademicYear;
if rgMounth.ItemIndex > 3 then
fJournalPedagogueByIndividualGroupChild.Month := rgMounth.ItemIndex - 3
else
fJournalPedagogueByIndividualGroupChild.Month := rgMounth.ItemIndex + 9;
fJournalPedagogueByIndividualGroupChild.Show;
end;
procedure TfJournalPedagogue.cmbAcademicYearChange(Sender: TObject);
begin
IDAcademicYear := AcademicYear[cmbAcademicYear.ItemIndex].ValueByName('ID');
ShowLGNameLastLesson;
end;
procedure TfJournalPedagogue.FormCreate(Sender: TObject);
begin
AcademicYear := nil;
GropeNameLastLesson := nil;
end;
procedure TfJournalPedagogue.FormDestroy(Sender: TObject);
begin
if Assigned(AcademicYear) then
FreeAndNil(AcademicYear);
if Assigned(GropeNameLastLesson) then
FreeAndNil(GropeNameLastLesson);
end;
procedure TfJournalPedagogue.FormShow(Sender: TObject);
begin
Panel1.Caption := StrPedagogue + ', ' + StrAcademicYear + ' учебный год.';
if not Assigned(AcademicYear) then
AcademicYear := Kernel.GetAcademicYear;
Kernel.FillingComboBox(cmbAcademicYear, AcademicYear, 'NAME', false);
Kernel.ChooseComboBoxItemIndex(cmbAcademicYear, AcademicYear, true, 'ID',
IDAcademicYear);
rgMounth.ItemIndex := 0;
ShowLGNameLastLesson;
end;
procedure TfJournalPedagogue.lvLGNameLastLessonItemChecked(Sender: TObject;
Item: TListItem);
begin
// если отметить последнего человека из списка, то отметятся все
// если отмечаем первого человека, то отмечаются все, но если потом снимаем отметку со второго, то снимаются остальные
end;
procedure TfJournalPedagogue.lvLGNameLastLessonSelectItem(Sender: TObject;
Item: TListItem; Selected: Boolean);
begin
if (not Assigned(fJournalPedagogueByIndividualGroupChild)) then
fJournalPedagogueByIndividualGroupChild :=
TfJournalPedagogueByIndividualGroupChild.Create(Self);
// fJournalPedagogueByIndividualGroupChild.IDLearningGroup := GropeNameLastLesson
// [Item.Index].ValueByName('ID_OUT');
with GropeNameLastLesson[Item.Index] do
begin
fJournalPedagogueByIndividualGroupChild.IDLearningGroup := ValueByName('ID_OUT');
fJournalPedagogueByIndividualGroupChild.StrLGName := ValueByName('L_G_NAME');
fJournalPedagogueByIndividualGroupChild.StrEducationProgram := ValueByName('STR_PROGRAM');
fJournalPedagogueByIndividualGroupChild.StrLearningLevel := ValueByName('STR_LEVEL');
fJournalPedagogueByIndividualGroupChild.WeekCountHour := ValueByName('WEEK_COUNT_HOUR');
end;
end;
procedure TfJournalPedagogue.SetIDAcademicYear(const Value: integer);
begin
if FIDAcademicYear <> Value then
FIDAcademicYear := Value;
end;
procedure TfJournalPedagogue.SetIDPedagogue(const Value: integer);
begin
if FIDPedagogue <> Value then
FIDPedagogue := Value;
end;
procedure TfJournalPedagogue.SetStrAcademicYear(const Value: string);
begin
if FStrAcademicYear <> Value then
FStrAcademicYear := Value;
end;
procedure TfJournalPedagogue.SetStrPedagogue(const Value: string);
begin
if FStrPedagogue <> Value then
FStrPedagogue := Value;
end;
procedure TfJournalPedagogue.ShowLGNameLastLesson;
begin
if Assigned(GropeNameLastLesson) then
FreeAndNil(GropeNameLastLesson);
GropeNameLastLesson := Kernel.GetLGNameLastLesson(IDPedagogue,
IDAcademicYear);
// выбираю данные из энтой процедуры, аналогично списку класса педагога
Kernel.GetLVGropeNameLastLesson(lvLGNameLastLesson, GropeNameLastLesson);
if lvLGNameLastLesson.Items.Count > 0 then
lvLGNameLastLesson.ItemIndex := 0;
end;
end.
|
{$I-,Q-,R-,S-}
{Tres granjeros se levantan a las 5am cada amñana y se dirigen al establo para
ordeñar trs vacas. El primer granjero comienza a ordeñar su vaca en el tiempo
300 (medido en segundos después de las 5am) y termina en el tiempo 1000. El
segundo granjero comienza en le tiempo 700 y termina en el tiempo 1200. El
tercer granjero ocmienza en el teimpo 1500 y termina en el tiempo 2100. La
mayor cantidad de tiempo continuo durante al menos un granjero estuvo
ordeñando una vaca fué 900 segundos (de 300 a 1200). La cantidad mayor de
teimpo en el cual no se estuvo haciendo ningún ordeñamiento entre el comienzo
y el fin del ordeñamiento fué 300 segundos (1500 menos 1200).
Su trabajo es escribir un program que examinará una lista de comienzos de
inicio y final para N(1 <= N <= 5000) granjeros ordeñando N vacas y
calcule en segundos:
- El intervalo de tiempo más largo en que al menos una vaca fué ordeñada.
- El intervalo más largo de tiempo (desde que se comienza el ordeño) durante
el cual ninguna vaca fué ordeñada.
NOMBRE DEL PROGRAMA: milk2
FORMATO DE ENTRADA
Línea 1: Un solo entero: N
Líneas 2..N+1: Dos enteros no negativos menores que 1000000, el comienzo y
el fin en segundos después de las 0500
ENTRADA EJEMPLO (archivo milk2.in)
3
300 1000
700 1200
1500 2100
FORMATO DE SALIDA
Una sola línea con dos enteros que representan el intervalo de tiempo
continuo más grande de ordeño y el más largo sin ordeño.
SALIDA EJEMPLO (archivo milk2.out)
900 300
}
const
mx = 5001;
var
fe,fs : text;
n,m,mint,maxt : longint;
tab : array[0..mx,1..2] of longint;
procedure open;
var
i : longint;
begin
assign(fe,'milk2.in'); reset(fe);
assign(fs,'milk2.out'); rewrite(fs);
readln(fe,n);
for i:=1 to n do
readln(fe,tab[i,1],tab[i,2]);
close(fe);
end;
procedure qsort(ini,fin,p : longint);
var
i,j,k,t : longint;
begin
i:=ini; j:=fin; k:=tab[(i+j) div 2,p];
repeat
while (tab[i,p] < k) do inc(i);
while (tab[j,p] > k) do dec(j);
if i<=j then
begin
tab[0]:=tab[i]; tab[i]:=tab[j]; tab[j]:=tab[0];
inc(i); dec(j);
end;
until i>j;
if i < fin then qsort(i,fin,p);
if j > ini then qsort(ini,j,p);
end;
function max(n1,n2 : longint) : longint;
begin
if n1 > n2 then
max:=n1
else max:=n2;
end;
procedure work;
var
i,j,k,r,c : longint;
begin
qsort(1,n,2);
qsort(1,n,1);
r:=tab[1,1]; c:=tab[1,2];
mint:=0; maxt:=c-r;
for i:=2 to n do
begin
if (tab[i,1] <= c) and (tab[i,2] > c) then
begin
maxt:=max(maxt,tab[i,2] - r);
c:=tab[i,2];
end
else
if (tab[i,1] > c) then
begin
maxt:=max(maxt,tab[i,2] - tab[i,1]);
mint:=max(mint,tab[i,1] - c);
r:=tab[i,1]; c:=tab[i,2];
end;
end;
end;
procedure closer;
begin
writeln(fs,maxt,' ',mint);
close(fs);
end;
begin
open;
work;
closer;
end. |
{
SuperMaximo GameLibrary : Texture class unit
by Max Foster
License : http://creativecommons.org/licenses/by/3.0/
}
unit TextureClass;
{$mode objfpc}{$H+}
interface
uses dglOpenGL;
const
TEXTURE_1D = GL_TEXTURE_1D; //A single line of colours
TEXTURE_2D = GL_TEXTURE_2D; //A regular two dimentional image
TEXTURE_3D = GL_TEXTURE_3D; //A stack of multiple TEXTURE_2Ds in one package. Essentially an array of TEXTURE_2D
TEXTURE_RECTANGLE = GL_TEXTURE_RECTANGLE; //A two dimentional image where texture coordinates do not need to be normalised
TEXTURE_CUBE = GL_TEXTURE_CUBE_MAP; //Six textures that form a net of a cube. Useful for 'skyboxes'; a box with a background
//scene that the 3D world is contained inside
type
PTexture = ^TTexture;
TTexture = object
private
name_ : string;
texture_ : GLuint;
type__ : GLenum;
public
//Creates an OpenGL texture object with the specified name and texture type. The texture files to load
//are passed in an array of strings
constructor create(newName : string; textureType : GLenum; fileNames : array of string);
destructor destroy;
//Erase the old texture data (if any) and load a new texture
procedure reload(textureType : GLenum; fileNames : array of string);
function name : string;
function texture : GLuint; //Return the OpenGL texture value to pass to OpenGL functions
function type_ : GLenum; //Return the OpenGL texture type
end;
function texture(searchName : string) : PTexture;
function addTexture(newName : string; textureType : GLenum; fileNames : array of string) : PTexture;
procedure destroyTexture(searchName : string);
procedure destroyAllTextures;
implementation
uses SysUtils, Classes, SDL, SDL_image, Display;
var
allTextures : array['a'..'z'] of TList;
constructor TTexture.create(newName : string; textureType : GLenum; fileNames : array of string);
var
i : integer;
begin
name_ := newName;
for i := 0 to length(fileNames)-1 do
begin
fileNames[i] := setDirSeparators(fileNames[i]);
end;
reload(textureType, fileNames); //Let's keep it DRY (Don't Repeat Yourself)
end;
destructor TTexture.destroy;
begin
glDeleteTextures(1, @texture_);
end;
procedure TTexture.reload(textureType : GLenum; fileNames : array of string);
var
initialised : boolean = false;
i : word;
image : PSDL_Surface;
textureFormat : GLenum;
//Sides of the cube map
sides : array[0..4] of GLenum = (GL_TEXTURE_CUBE_MAP_NEGATIVE_X, GL_TEXTURE_CUBE_MAP_POSITIVE_Y, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
GL_TEXTURE_CUBE_MAP_POSITIVE_Z, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z);
begin
type__ := textureType;
if (textureType = TEXTURE_3D) then
begin
if (glSlVersion < 1.5) then
begin //If the GPU doesn't support TEXTURE_2D_ARRAYS, create a texture atlas
textureType := GL_TEXTURE_2D;
glGenTextures(1, @texture_);
glBindTexture(GL_TEXTURE_2D, texture_);
//Tell OpenGL to mipmap nicely
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);
end
else
begin
textureType := GL_TEXTURE_2D_ARRAY;
glGenTextures(1, @texture_);
glBindTexture(GL_TEXTURE_2D_ARRAY, texture_);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_GENERATE_MIPMAP, GL_TRUE);
end;
for i := 0 to length(fileNames)-1 do
begin
image := IMG_Load(pchar(fileNames[i]));
if (image = nil) then writeln('Could not load image ', fileNames[i]) else
begin
if (image^.format^.BytesPerPixel = 4) then
begin
if (image^.format^.Rmask = $000000ff) then textureFormat := GL_RGBA else textureFormat := GL_BGRA;
end
else
begin
if (image^.format^.Rmask = $000000ff) then textureFormat := GL_RGB else textureFormat := GL_BGR;
end;
if (not initialised) then
begin //Set up the texture buffer
if (glSlVersion < 1.5) then glTexImage2D(GL_TEXTURE_2D, 0, image^.format^.BytesPerPixel, image^.w*length(fileNames), image^.h, 0, textureFormat, GL_UNSIGNED_BYTE, nil)
else glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, image^.format^.BytesPerPixel, image^.w, image^.h, length(fileNames), 0, textureFormat, GL_UNSIGNED_BYTE, nil);
initialised := true;
end;
//Slot the textures into the relevant places in the buffer
if (glSlVersion < 1.5) then glTexSubImage2D(GL_TEXTURE_2D, 0, image^.w*i, 0, image^.w, image^.h, textureFormat, GL_UNSIGNED_BYTE, image^.pixels)
else glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, i, image^.w, image^.h, 1, textureFormat, GL_UNSIGNED_BYTE, image^.pixels);
SDL_FreeSurface(image);
end;
end;
glBindTexture(textureType, 0); //Unbind the texture
end
else
begin
image := IMG_Load(pchar(fileNames[0]));
if (image = nil) then writeln('Could not load image ', fileNames[0]) else
begin
if (image^.format^.BytesPerPixel = 4) then
begin
if (image^.format^.Rmask = $000000ff) then textureFormat := GL_RGBA else textureFormat := GL_BGRA;
end
else
begin
if (image^.format^.Rmask = $000000ff) then textureFormat := GL_RGB else textureFormat := GL_BGR;
end;
glGenTextures(1, @texture_);
glBindTexture(textureType, texture_);
glTexParameteri(textureType, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(textureType, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);
if (textureType <> TEXTURE_CUBE) then
begin //If this is a TEXTURE_2D, don't do anything fancy, just put the pixel data straight into graphics memory
glTexImage2D(textureType, 0, image^.format^.BytesPerPixel, image^.w, image^.h, 0, textureFormat, GL_UNSIGNED_BYTE, image^.pixels);
SDL_FreeSurface(image);
end
else
begin
//For a cube map we need to loop through each face of the cube
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, image^.format^.BytesPerPixel, image^.w, image^.h, 0, textureFormat, GL_UNSIGNED_BYTE, image^.pixels);
SDL_FreeSurface(image);
for i := 0 to 3 do
begin
image := IMG_Load(pchar(fileNames[i+1]));
if (image = nil) then writeln('Could not load image ', fileNames[i+1]) else
begin
glTexImage2D(sides[i], 0, image^.format^.BytesPerPixel, image^.w, image^.h, 0, textureFormat, GL_UNSIGNED_BYTE, image^.pixels);
SDL_FreeSurface(image);
end;
end;
end;
glBindTexture(textureType, 0);
end;
end;
end;
function TTexture.name : string;
begin
result := name_;
end;
function TTexture.texture : GLuint;
begin
result := texture_;
end;
function TTexture.type_ : GLenum;
begin
result := type__;
end;
function texture(searchName : string) : PTexture;
var
letter : char;
i : word;
tempTexture : PTexture;
begin
letter := searchName[1];
result := nil;
if (allTextures[letter].count > 0) then
begin
for i := 0 to allTextures[letter].count-1 do
begin
tempTexture := PTexture(allTextures[letter][i]);
if (tempTexture^.name = searchName) then result := tempTexture;
end;
end;
end;
function addTexture(newName : string; textureType : GLenum; fileNames : array of string) : PTexture;
var
letter : char;
begin
letter := newName[1];
allTextures[letter].add(new(PTexture, create(newName, textureType, fileNames)));
result := allTextures[letter].last;
end;
procedure destroyTexture(searchName : string);
var
letter : char;
i : word;
tempTexture : PTexture;
begin
letter := searchName[1];
if (allTextures[letter].count > 0) then
begin
for i := 0 to allTextures[letter].count-1 do
begin
tempTexture := PTexture(allTextures[letter][i]);
if (tempTexture^.name = searchName) then
begin
dispose(tempTexture, destroy);
allTextures[letter].delete(i);
break;
end;
end;
end;
end;
procedure destroyAllTextures;
var
i : char;
j : integer;
tempTexture : PTexture;
begin
for i := 'a' to 'z' do
begin
if (allTextures[i].count > 0) then
begin
for j := 0 to allTextures[i].count-1 do
begin
tempTexture := PTexture(allTextures[i][j]);
dispose(tempTexture, destroy);
end;
allTextures[i].clear;
end;
end;
end;
procedure initializeAllTextures;
var
i : char;
begin
for i := 'a' to 'z' do
begin
allTextures[i] := TList.create;
end;
end;
procedure finalizeAllTextures;
var
i : char;
begin
for i := 'a' to 'z' do
begin
allTextures[i].destroy;
end;
end;
initialization
initializeAllTextures;
finalization
finalizeAllTextures;
end.
|
{
This demo application accompanies the article
"How to call Delphi code from scripts running in a TWebBrowser" at
http://www.delphidabbler.com/articles?article=22.
This unit defines a class that extends the TWebBrowser's external object.
This code is copyright (c) P D Johnson (www.delphidabbler.com), 2005-2006.
v1.0 of 2005/05/09 - original version
v1.1 of 2006/02/11 - changed base URL of programs to reflect current use
}
{$A8,B-,C+,D+,E-,F-,G+,H+,I+,J-,K-,L+,M-,N+,O+,P+,Q-,R-,S-,T-,U-,V+,W-,X+,Y+,Z1}
{$WARN UNSAFE_TYPE OFF}
unit uWebJSExternal;
interface
uses
Classes,
ComObj,
WebJS_TLB,
ActiveX;
type
TWebJSExternal = class(TAutoIntfObject, IWebJSExternal, IDispatch)
private
FExternalObject: IWebJSExternal;
protected
{ IWebJSExternal methods }
function SaveLocation(Lat: Double; Lng: Double; const FileName: WideString): Shortint; safecall;
procedure ZoomPan(Lat: Double; Lng: Double; Zoom: SYSINT); safecall;
procedure UpdateEmbed(); safecall;
procedure MapStarted(); safecall;
function CanSaveLocation(Lat: Double; Lng: Double; Value: Shortint): Shortint; safecall;
public
constructor Create(ExternalObject: IWebJSExternal);
destructor Destroy; override;
end;
implementation
uses
SysUtils;
{ TWebJSExternal }
constructor TWebJSExternal.Create(ExternalObject: IWebJSExternal);
var
TypeLib: ITypeLib; // type library information
ExeName: WideString; // name of our program's exe file
begin
FExternalObject := ExternalObject;
// Get name of application
ExeName := ParamStr(0);
// Load type library from application's resources
OleCheck(LoadTypeLib(PWideChar(ExeName), TypeLib));
// Call inherited constructor
inherited Create(TypeLib, IWebJSExternal);
end;
destructor TWebJSExternal.Destroy;
begin
FExternalObject := nil;
inherited;
end;
function TWebJSExternal.CanSaveLocation(Lat: Double; Lng: Double; Value: Shortint): Shortint;
begin
Result := FExternalObject.CanSaveLocation(Lat, Lng, Value);
end;
procedure TWebJSExternal.MapStarted();
begin
FExternalObject.MapStarted();
end;
procedure TWebJSExternal.UpdateEmbed();
begin
FExternalObject.UpdateEmbed();
end;
procedure TWebJSExternal.ZoomPan(Lat, Lng: Double; Zoom: SYSINT);
begin
FExternalObject.ZoomPan(Lat, Lng, Zoom);
end;
function TWebJSExternal.SaveLocation(Lat, Lng: Double; const FileName: WideString): Shortint;
begin
Result := FExternalObject.SaveLocation(Lat, Lng, FileName);
end;
end.
|
unit ThDbEdit;
interface
uses
Classes, DB, DBCtrls,
ThInput, ThDbData;
type
TThCustomDbEdit = class(TThInput)
private
FData: TThDbData;
protected
function GetFieldName: string;
function GetDataSource: TDataSource;
procedure SetFieldName(const Value: string);
procedure SetDataSource(const Value: TDataSource);
protected
procedure DataChange(Sender: TObject);
function GetFieldText: string;
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
protected
property Data: TThDbData read FData;
property FieldName: string read GetFieldName write SetFieldName;
property DataSource: TDataSource read GetDataSource write SetDataSource;
end;
//
TThDbEdit = class(TThCustomDbEdit)
published
property FieldName;
property DataSource;
end;
implementation
{ TThCustomDbEdit }
constructor TThCustomDbEdit.Create(AOwner: TComponent);
begin
inherited;
FData := TThDbData.Create;
FData.OnDataChange := DataChange;
end;
destructor TThCustomDbEdit.Destroy;
begin
FData.Free;
inherited;
end;
procedure TThCustomDbEdit.DataChange(Sender: TObject);
begin
Caption := GetFieldText;
Invalidate;
end;
function TThCustomDbEdit.GetFieldText: string;
begin
Result := Data.FieldText;
end;
procedure TThCustomDbEdit.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
Data.Notification(AComponent, Operation);
end;
function TThCustomDbEdit.GetFieldName: string;
begin
Result := Data.FieldName;
end;
function TThCustomDbEdit.GetDataSource: TDataSource;
begin
Result := Data.DataSource;
end;
procedure TThCustomDbEdit.SetFieldName(const Value: string);
begin
Data.FieldName := Value;
end;
procedure TThCustomDbEdit.SetDataSource(const Value: TDataSource);
begin
if DataSource <> nil then
DataSource.RemoveFreeNotification(Self);
Data.DataSource := Value;
if DataSource <> nil then
DataSource.FreeNotification(Self);
end;
end.
|
unit Form_Main;
// Description: Simple Hash
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
// A simple demonstation application of how to use the hash components
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, HashAlg_U, HashAlgMD5_U;
type
TfrmMain = class(TForm)
edText: TEdit;
pbHashInput: TButton;
edFilename: TEdit;
pbBrowse: TButton;
rbHashText: TRadioButton;
rbHashFile: TRadioButton;
mmoReport: TMemo;
pbClose: TButton;
Label1: TLabel;
Label2: TLabel;
hashAlg: THashAlgMD5;
OpenDialog1: TOpenDialog;
procedure pbCloseClick(Sender: TObject);
procedure pbHashInputClick(Sender: TObject);
procedure pbBrowseClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
function HashText(userText: string): string;
function HashFile(filename: string): string;
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
uses
HashValue_U,
SDUGeneral;
procedure TfrmMain.pbCloseClick(Sender: TObject);
begin
Close();
end;
function TfrmMain.HashText(userText: string): string;
var
hashValue: THashValue;
begin
hashValue:= THashValue.Create();
try
hashAlg.HashString(userText, hashValue);
Result := hashAlg.PrettyPrintHashValue(hashValue);
finally
hashValue.Free();
end;
end;
function TfrmMain.HashFile(filename: string): string;
var
hashValue: THashValue;
begin
hashValue:= THashValue.Create();
try
hashAlg.HashFile(filename, hashValue);
Result := hashAlg.PrettyPrintHashValue(hashValue);
finally
hashValue.Free();
end;
end;
procedure TfrmMain.pbHashInputClick(Sender: TObject);
begin
mmoReport.Lines.Add('The '+hashAlg.Title+' hash of:');
if rbHashFile.checked then
begin
mmoReport.Lines.Add(edFilename.text);
mmoReport.Lines.Add('is:');
mmoReport.Lines.Add(HashFile(edFilename.text));
end
else
begin
mmoReport.Lines.Add(edText.text);
mmoReport.Lines.Add('is:');
mmoReport.Lines.Add(HashText(edText.text));
end;
mmoReport.Lines.Add('');
end;
procedure TfrmMain.pbBrowseClick(Sender: TObject);
begin
SDUOpenSaveDialogSetup(OpenDialog1, edFilename.Text);
if OpenDialog1.Execute then
begin
edFilename.Text := OpenDialog1.Filename;
rbHashFile.Checked := TRUE;
end;
end;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
self.Caption := Application.Title;
mmoReport.Lines.Clear();
edText.Text := 'abc';
edFilename.Text := '';
end;
END.
|
{
@abstract(Provides Native Format highlighters import and export)
@authors(Vitalik [2vitalik@gmail.com], Quadr0 [quadr02005@gmail.com])
@created(2005)
@lastmod(2006-06-30)
}
{$IFNDEF QSynUniFormatNativeXml}
unit SynUniFormatNativeXml;
{$ENDIF}
{$I SynUniHighlighter.inc}
interface
uses
{$IFDEF SYN_CLX}
QGraphics,
QSynUniClasses,
{$ELSE}
SysUtils,
Graphics,
Classes,
{$IFDEF SYN_COMPILER_6_UP}
Variants,
{$ENDIF}
SynUniFormat,
SynUniClasses,
SynUniRules,
SynUniHighlighter,
{$ENDIF}
(*
{$IFDEF MSWINDOWS}
MSXML,
{$ELSE}
oxmldom,
{$ENDIF}
*)
{ XMLDoc,
XMLIntf; } // DW
SimpleXML; // DW
type
TSynUniFormatNativeXml = class(TSynUniFormat)
class function ImportInfo(AInfo: TSynInfo; ANode: IXMLNode): Boolean; virtual;
class function ExportInfo(AInfo: TSynInfo; ANode: IXMLNode): Boolean; virtual;
class function ImportEditorProperties(AEditorProperties: TEditorProperties; ANode: IXMLNode): Boolean; virtual;
class function ExportEditorProperties(AEditorProperties: TEditorProperties; ANode: IXMLNode): Boolean; virtual;
class function ImportAttributes(Attributes: TSynAttributes; ANode: IXMLNode): Boolean; virtual;
class function ExportAttributes(Attributes: TSynAttributes; ANode: IXMLNode): Boolean; virtual;
class function ImportSchemes(ASchemes: TSynUniSchemes; ANode: IXMLNode): Boolean; virtual;
class function ExportSchemes(ASchemes: TSynUniSchemes; ANode: IXMLNode): Boolean; virtual;
class function ImportToken(AToken: TSynMultiToken; ANode: IXMLNode): Boolean; virtual;
class function ExportToken(AToken: TSynMultiToken; ANode: IXMLNode): Boolean; virtual;
class function ImportKeyList(AKeyList: TSynKeyList; ANode: IXMLNode): Boolean; virtual;
class function ExportKeyList(AKeyList: TSynKeyList; ANode: IXMLNode): Boolean; virtual;
class function ImportSet(ASet: TSynSet; ANode: IXMLNode): Boolean; virtual;
class function ExportSet(ASet: TSynSet; ANode: IXMLNode): Boolean; virtual;
class function ImportRange(ARange: TSynRange; ANode: IXMLNode): Boolean; virtual;
class function ExportRange(ARange: TSynRange; ANode: IXMLNode): Boolean; virtual;
class function ImportHighlighter(SynUniSyn: TSynUniSyn; ANode: IXMLNode): Boolean; virtual;
class function ExportHighlighter(SynUniSyn: TSynUniSyn; ANode: IXMLNode): Boolean; virtual;
class function ImportFromStream(AObject: TObject; AStream: TStream): Boolean; override;
class function ExportToStream(AObject: TObject; AStream: TStream): Boolean; override;
class function ImportFromFile(AObject: TObject; AFileName: string): Boolean; override;
class function ExportToFile(AObject: TObject; AFileName: string): Boolean; override;
class procedure LoadAdditionalAttributes(ANode: IXMLNode); virtual; //!!EK
class procedure SaveAdditionalAttributes(ANode: IXMLNode); virtual; //!!EK
end;
function CreateXmlDocument(RootNode: string): IXmlDocument;
{$IFNDEF SYN_COMPILER_6_UP}
function VarToStr(const V: Variant; const ADefault: string = ''): string;
{$ENDIF}
function VarToBool(const V: Variant; Default: Boolean = False): Boolean;
function VarToColor(const V: Variant; Default: TColor): TColor;
function VarToInt(const V: Variant; Default: Integer = 0): Integer;
function VarToSet(const V: Variant): TCharSet;
{$IFNDEF SYN_COMPILER_7_UP}
function StrToBoolDef(const S: string; const Default: Boolean): Boolean;
function BoolToStr(B: Boolean; UseBoolStrs: Boolean = False): string;
{$ENDIF}
implementation
{$IFNDEF SYN_COMPILER_7_UP}
//------------------------------------------------------------------------------
function StrToBoolDef(const S: string; const Default: Boolean): Boolean;
begin
if (S = 'True') or (S = '1') or (S = '-1') then
Result := True
else if (S = 'False') or (S = '0') then
Result := False
else
Result := Default;
end;
//------------------------------------------------------------------------------
function BoolToStr(B: Boolean; UseBoolStrs: Boolean = False): string;
const
cSimpleBoolStrs: array [Boolean] of String = ('0', '-1');
begin
if UseBoolStrs then
begin
if B then
Result := 'True'
else
Result := 'False';
end
else
Result := cSimpleBoolStrs[B];
end;
{$ENDIF}
//------------------------------------------------------------------------------
function CreateXmlDocument(RootNode: string): IXmlDocument;
begin
Result := SimpleXML.CreateXmlDocument(RootNode);
// Result.Active := True;
// Result.Options := [doNodeAutoIndent, doAttrNull, doNodeAutoCreate];
// Result.Version := '1.0';
// Result.Encoding := 'windows-1251';
//if RootNode <> '' then
// Result.Node.AddChild(RootNode);
end;
{$IFNDEF SYN_COMPILER_6_UP}
//------------------------------------------------------------------------------
function FindVarData(const V: Variant): PVarData;
begin
Result := @TVarData(V);
while Result.VType = varByRef or varVariant do
Result := PVarData(Result.VPointer);
end;
//------------------------------------------------------------------------------
function VarIsNull(const V: Variant): Boolean;
begin
Result := FindVarData(V)^.VType = varNull;
end;
//------------------------------------------------------------------------------
function VarToStr(const V: Variant; const ADefault: string): string;
begin
if not VarIsNull(V) then
Result := V
else
Result := ADefault;
end;
{$ENDIF}
//------------------------------------------------------------------------------
function VarToBool(const V: Variant; Default: Boolean): Boolean;
begin
Result := StrToBoolDef(VarToStr(V), Default);
end;
//------------------------------------------------------------------------------
function VarToColor(const V: Variant; Default: TColor): TColor;
begin
if VarToStr(V) <> '' then
Result := StringToColor(VarToStr(V))
else
Result := Default;
end;
//------------------------------------------------------------------------------
function VarToInt(const V: Variant; Default: Integer): Integer;
begin
Result := StrToIntDef(VarToStr(V), Default);
end;
//------------------------------------------------------------------------------
function VarToSet(const V: Variant): TCharSet;
begin
Result := StrToSet(VarToStr(V));
end;
//------------------------------------------------------------------------------
function VarToPChar(const V: Variant): PChar;
begin
Result := PChar(VarToStr(V));
end;
//------------------------------------------------------------------------------
//----------------------- TSynUniFormatNativeXml -------------------------------
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml.ImportInfo(AInfo: TSynInfo; ANode: IXMLNode): Boolean;
begin Result := False; end;
class function TSynUniFormatNativeXml.ExportInfo(AInfo: TSynInfo; ANode: IXMLNode): Boolean;
begin Result := False; end;
class function TSynUniFormatNativeXml.ImportEditorProperties(AEditorProperties: TEditorProperties; ANode: IXMLNode): Boolean;
begin Result := False; end;
class function TSynUniFormatNativeXml.ExportEditorProperties(AEditorProperties: TEditorProperties; ANode: IXMLNode): Boolean;
begin Result := False; end;
class function TSynUniFormatNativeXml.ImportAttributes(Attributes: TSynAttributes; ANode: IXMLNode): Boolean;
begin Result := False; end;
class function TSynUniFormatNativeXml.ExportAttributes(Attributes: TSynAttributes; ANode: IXMLNode): Boolean;
begin Result := False; end;
class function TSynUniFormatNativeXml.ImportSchemes(ASchemes: TSynUniSchemes; ANode: IXMLNode): Boolean;
begin Result := False; end;
class function TSynUniFormatNativeXml.ExportSchemes(ASchemes: TSynUniSchemes; ANode: IXMLNode): Boolean;
begin Result := False; end;
class function TSynUniFormatNativeXml.ImportToken(AToken: TSynMultiToken; ANode: IXMLNode): Boolean;
begin Result := False; end;
class function TSynUniFormatNativeXml.ExportToken(AToken: TSynMultiToken; ANode: IXMLNode): Boolean;
begin Result := False; end;
class function TSynUniFormatNativeXml.ImportKeyList(AKeyList: TSynKeyList; ANode: IXMLNode): Boolean;
begin Result := False; end;
class function TSynUniFormatNativeXml.ExportKeyList(AKeyList: TSynKeyList; ANode: IXMLNode): Boolean;
begin Result := False; end;
class function TSynUniFormatNativeXml.ImportSet(ASet: TSynSet; ANode: IXMLNode): Boolean;
begin Result := False; end;
class function TSynUniFormatNativeXml.ExportSet(ASet: TSynSet; ANode: IXMLNode): Boolean;
begin Result := False; end;
class function TSynUniFormatNativeXml.ImportRange(ARange: TSynRange; ANode: IXMLNode): Boolean;
begin Result := False; end;
class function TSynUniFormatNativeXml.ExportRange(ARange: TSynRange; ANode: IXMLNode): Boolean;
begin Result := False; end;
class function TSynUniFormatNativeXml.ImportHighlighter(SynUniSyn: TSynUniSyn; ANode: IXMLNode): Boolean;
begin Result := False; end;
class function TSynUniFormatNativeXml.ExportHighlighter(SynUniSyn: TSynUniSyn; ANode: IXMLNode): Boolean;
begin Result := False; end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml.ImportFromStream(AObject: TObject; AStream: TStream): Boolean;
var
XMLDocument: IXMLDocument;
begin
VerifyStream(AStream);
AStream.Position := 0; // DW
XMLDocument := CreateXmlDocument('');
XMLDocument.Load(AStream);
if AObject is TSynUniSyn then
begin
Result := ImportHighlighter(TSynUniSyn(AObject), XMLDocument.DocumentElement);
//TSynUniSyn(AObject).Prepare(); //TODO: Нужно ли это?.. Может убрать?..
TSynUniSyn(AObject).FileName := '';
end
else if AObject is TSynRange then
Result := ImportRange(TSynRange(AObject), XMLDocument.DocumentElement)
else if AObject is TSynKeyList then
Result := ImportKeyList(TSynKeyList(AObject), XMLDocument.DocumentElement)
else if AObject is TSynSet then
Result := ImportSet(TSynSet(AObject), XMLDocument.DocumentElement)
else if AObject is TSynInfo then
Result := ImportInfo(TSynInfo(AObject), XMLDocument.DocumentElement)
else if AObject is TEditorProperties then
Result := ImportEditorProperties(TEditorProperties(AObject), XMLDocument.DocumentElement)
else if AObject is TSynAttributes then
Result := ImportAttributes(TSynAttributes(AObject), XMLDocument.DocumentElement)
else if AObject is TSynSet then
Result := ImportSet(TSynSet(AObject), XMLDocument.DocumentElement)
else if AObject is TSynUniSchemes then
Result := ImportSchemes(TSynUniSchemes(AObject), XMLDocument.DocumentElement)
else if AObject is TSynMultiToken then
Result := ImportToken(TSynMultiToken(AObject), XMLDocument.DocumentElement)
else begin
raise Exception.Create(ClassName + '.ImportFromStream: Cannot import into '+AObject.ClassName+' object');
Result := False;
end;
//XMLDocument.Active := False;
//SynUniSyn.DefHighlightChange(SynUniSyn);
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml.ExportToStream(AObject: TObject; AStream: TStream): Boolean;
var
XmlDocument: IXmlDocument;
begin
VerifyStream(AStream);
if (AObject is TSynUniSyn) then begin
XmlDocument := CreateXmlDocument('SynUniHighlighter');
Result := ExportHighlighter(TSynUniSyn(AObject), XmlDocument.DocumentElement);
end
else if AObject is TSynRange then begin
XmlDocument := CreateXmlDocument('Range');
Result := ExportRange(TSynRange(AObject), XMLDocument.DocumentElement);
end
else if AObject is TSynKeyList then begin
XmlDocument := CreateXmlDocument('KeyList');
Result := ExportKeyList(TSynKeyList(AObject), XMLDocument.DocumentElement);
end
else if AObject is TSynSet then begin
XmlDocument := CreateXmlDocument('Set');
Result := ExportSet(TSynSet(AObject), XMLDocument.DocumentElement);
end
else if AObject is TSynInfo then begin
XmlDocument := CreateXmlDocument('Info');
Result := ExportInfo(TSynInfo(AObject), XMLDocument.DocumentElement);
end
else if AObject is TSynAttributes then begin
XmlDocument := CreateXmlDocument('Attributes');
Result := ExportAttributes(TSynAttributes(AObject), XMLDocument.DocumentElement);
end
else if AObject is TSynUniSchemes then begin
XmlDocument := CreateXmlDocument('Schemes');
Result := ExportSchemes(TSynUniSchemes(AObject), XMLDocument.DocumentElement);
end
else begin
raise Exception.Create(ClassName + '.ExportToStream: Cannot export from '+AObject.ClassName+' object');
Result := False;
end;
XmlDocument.Save(AStream);
XmlDocument.RemoveAllAttrs();
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml.ImportFromFile(AObject: TObject; AFileName: string): Boolean;
var
FileStream: TFileStream;
begin
VerifyFileName(AFileName);
FileStream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite);
try
ImportFromStream(AObject, FileStream);
finally
FreeAndNil(FileStream);
end;
if AObject is TSynUniSyn then
TSynUniSyn(AObject).FileName := AFileName;
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml.ExportToFile(AObject: TObject; AFileName: string): Boolean;
var
FileStream: TFileStream;
begin
VerifyEmptyFileName(AFileName);
FileStream := TFileStream.Create(AFileName, fmCreate or fmShareDenyWrite);
try
ExportToStream(AObject, FileStream);
finally
FreeAndNil(FileStream);
end;
if AObject is TSynUniSyn then
TSynUniSyn(AObject).FileName := AFileName;
Result := True;
end;
//------------------------------------------------------------------------------
class procedure TSynUniFormatNativeXml.LoadAdditionalAttributes(ANode: IXMLNode); //!!EK
begin
// virtual holder
end;
//------------------------------------------------------------------------------
class procedure TSynUniFormatNativeXml.SaveAdditionalAttributes(ANode: IXMLNode); //!!EK
begin
// virtual holder
end;
//----------------------------------------------------------------------------
end.
|
Unit ClassWatch;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
Interface
Uses
Windows, IRPMonDll, Classes,
Generics.Collections, Generics.Defaults;
Type
TWatchableClass = Class
Private
FName : WideString;
FGUid : WideString;
FBeginning : Boolean;
FUpperFilter : Boolean;
FRegistered : Boolean;
Public
Constructor Create(AGuid:WideString; AName:WideString; AUpperFilter:Boolean); Reintroduce; Overload;
Constructor Create(Var ARecord:CLASS_WATCH_RECORD); Reintroduce; Overload;
Function Register(ABeginning:Boolean):Cardinal;
Function Unregister:Cardinal;
Class Function Enumerate(AList:TList<TWatchableClass>):Cardinal;
Property Registered : Boolean Read FRegistered;
Property Beginning : Boolean Read FBeginning;
Property UpperFIlter : Boolean Read FUpperFilter;
Property Name : WideString Read FName;
Property GUid : WideString Read FGuid;
end;
TWatchableClassComparer = Class (TComparer<TWatchableClass>)
{$IFDEF FPC}
Function Compare(constref Left, Right: TWatchableClass): Integer; Override;
{$ELSE}
Function Compare(const Left, Right: TWatchableClass): Integer; Override;
{$ENDIF}
end;
Implementation
Uses
SysUtils, Utils;
(** TWatchableClass **)
Constructor TWatchableClass.Create(AGuid:WideString; AName:WideString; AUpperFilter:Boolean);
begin
Inherited Create;
FGUid := AGuid;
FName := AName;
FRegistered := False;
FUpperFilter := AUpperFilter;
FBeginning := False;
end;
Constructor TWatchableClass.Create(Var ARecord:CLASS_WATCH_RECORD);
begin
Inherited Create;
FGuid := Copy(WideString(ARecord.ClassGuidString), 1, StrLen(ARecord.ClassGuidString));
FRegistered := True;
FBeginning := ARecord.Beginning <> 0;
FUpperFilter := ARecord.UpperFilter <> 0;
end;
Function TWatchableClass.Register(ABeginning:Boolean):Cardinal;
begin
Result := IRPMonDllClassWatchRegister(PWideChar(FGuid), FUpperFilter, ABeginning);
If Result = ERROR_SUCCESS Then
begin
FBeginning := ABeginning;
FRegistered := True;
end;
end;
Function TWatchableClass.Unregister:Cardinal;
begin
Result := IRPMonDllClassWatchUnregister(PWIdeChar(FGuid), FUpperFIlter, FBeginning);
If Result = ERROR_SUCCESS THen
FRegistered := False;
end;
Class Function TWatchableClass.Enumerate(AList:TList<TWatchableClass>):Cardinal;
Var
strclassGuid : WideString;
I : Integer;
p : TPair<WideString, TWatchableClass>;
wc : TWatchableClass;
classNameLen : Cardinal;
className : Packed Array [0..MAX_PATH] Of WideChar;
dwValue : Cardinal;
dwValueLen : Cardinal;
cKey : HKEY;
classGuidLen : Cardinal;
classGuid : Packed Array [0..38] Of WideChar;
classIndex : Integer;
classesKey : HKEY;
cwCount : Cardinal;
tmp : PCLASS_WATCH_RECORD;
cwArray : PCLASS_WATCH_RECORD;
dict : TDictionary<WideString, TWatchableClass>;
key : WideString;
wcComparer : TWatchableClassComparer;
begin
dict := TDictionary<WideString, TWatchableClass>.Create;
Result := IRPMonDllClassWatchEnum(cwArray, cwCount);
If Result = ERROR_SUCCESS THen
begin
Result := RegOpenKeyEx(HKEY_LOCAL_MACHINE, 'SYSTEM\CurrentControlSet\Control\Class', 0, KEY_READ, classesKey);
If Result = ERROR_SUCCESS THen
begin
classIndex := 0;
Repeat
classGuidLen := SizeOf(classGuid) Div SizeOf(WideChar);
FillChar(classGuid, SizeOf(classGUid), 0);
Result := RegEnumKeyExW(classesKey, classIndex, classGuid, classGuidLen, Nil, Nil, Nil, Nil);
If Result = ERROR_SUCCESS THen
begin
Result := RegOpenKeyExW(classesKey, classGuid, 0, KEY_READ, cKey);
If Result = ERROR_SUCCESS THen
begin
dwValueLen := SizeOf(dwValue);
Result := RegQueryValueExW(cKey, 'NoUseClass', Nil, Nil, @dwValue, @dwValueLen);
If (Result <> ERROR_SUCCESS) Or (dwValue = 0) Then
begin
classNameLen := SizeOf(className);
FillChar(className, SizeOf(className), 0);
Result := RegQueryValueExW(cKey, 'Class', Nil, Nil, @className, @classNameLen);
If Result = ERROR_SUCCESS Then
begin
strclassGuid := Copy(WideString(classGuid), 1, StrLen(classGuid));
wc := TWatchableClass.Create(
strclassGuid,
Copy(WideString(className), 1, StrLen(className)),
False);
key := WideUpperCase(strClassGuid) + 'L';
dict.Add(key, wc);
wc := TWatchableClass.Create(
strclassGuid,
Copy(WideString(className), 1, StrLen(className)),
True);
key := WideUpperCase(strClassGuid) + 'U';
dict.Add(key, wc);
end;
end;
If Result = ERROR_FILE_NOT_FOUND Then
Result := ERROR_SUCCESS;
RegCloseKey(cKey);
end;
end;
Inc(classIndex);
Until Result <> ERROR_SUCCESS;
If Result = ERROR_NO_MORE_ITEMS Then
Result := ERROR_SUCCESS;
RegCloseKey(classesKey);
end;
tmp := cwArray;
For I := 0 To cwCount - 1 Do
begin
key := WideUpperCase(COpy(WideString(tmp.ClassGuidString), 1, StrLen(tmp.ClassGuidString)));
If tmp.UpperFilter <> 0 Then
key := Key + 'U'
Else key := key + 'L';
If dict.TryGetValue(key, wc) Then
begin
wc.FRegistered := True;
wc.FBeginning := tmp.Beginning <> 0;
end;
Inc(tmp);
end;
IRPMonDllClassWatchEnumFree(cwArray, cwCount);
end;
If Result = ERROR_SUCCESS Then
begin
For p In dict Do
AList.Add(p.Value);
wcComparer := TWatchableClassComparer.Create;
AList.Sort(wcComparer);
wcComparer.Free;
end;
dict.Free;
end;
{$IFDEF FPC}
Function TWatchableClassComparer.Compare(constref Left, Right: TWatchableClass): Integer;
{$ELSE}
Function TWatchableClassComparer.Compare(const Left, Right: TWatchableClass): Integer;
{$ENDIF}
begin
Result := WideCompareText(Left.Name, Right.Name);
If Result = 0 Then
begin
If Left.UpperFilter <> Right.UpperFilter Then
begin
If Not Left.UpperFIlter Then
Result := -1
Else Result := 1;
end;
end;
end;
End.
|
unit LrDynamicProperties;
interface
uses
SysUtils, TypInfo, Classes;
type
TLrDynamicPropertyType = ( ptString, ptEvent, ptLastType=MAXINT );
//
TLrDynamicPropertyItem = class(TCollectionItem)
private
FName: string;
FPropertyType: TLrDynamicPropertyType;
FValue: string;
FData: TPersistent;
protected
function GetDisplayName: string; override;
procedure SetData(const Value: TPersistent);
public
constructor Create(inCollection: TCollection); override;
destructor Destroy; override;
published
property Data: TPersistent read FData write SetData;
property Value: string read FValue write FValue;
property Name: string read FName write FName;
property PropertyType: TLrDynamicPropertyType read FPropertyType
write FPropertyType;
end;
//
TLrDynamicProperties = class(TCollection)
private
FOwner: TComponent;
FExtendable: Boolean;
protected
function GetProps(inIndex: Integer): TLrDynamicPropertyItem;
function GetOwner: TPersistent; override;
procedure PropertyAdded(inItem: TLrDynamicPropertyItem); virtual;
public
constructor Create(AOwner: TComponent; inExtendable: Boolean = false);
function AddProperty(
inType: TLrDynamicPropertyType = ptString): TLrDynamicPropertyItem;
function FindProperty(const inName: string): TLrDynamicPropertyItem;
procedure Notify(Item: TCollectionItem;
Action: TCollectionNotification); override;
public
property Extendable: Boolean read FExtendable write FExtendable;
property Props[inIndex: Integer]: TLrDynamicPropertyItem read GetProps;
default;
end;
implementation
{ TLrDynamicPropertyItem }
constructor TLrDynamicPropertyItem.Create(inCollection: TCollection);
begin
inherited;
end;
destructor TLrDynamicPropertyItem.Destroy;
begin
inherited;
end;
function TLrDynamicPropertyItem.GetDisplayName: string;
begin
Result := Name;
end;
procedure TLrDynamicPropertyItem.SetData(const Value: TPersistent);
begin
if Data <> nil then
Data.Assign(Value);
end;
{ TLrDynamicProperties }
constructor TLrDynamicProperties.Create(AOwner: TComponent;
inExtendable: Boolean = false);
begin
inherited Create(TLrDynamicPropertyItem);
FOwner := AOwner;
Extendable := inExtendable;
end;
function TLrDynamicProperties.GetOwner: TPersistent;
begin
Result := FOwner;
end;
procedure TLrDynamicProperties.Notify(Item: TCollectionItem;
Action: TCollectionNotification);
begin
inherited;
if Action = cnAdded then
PropertyAdded(TLrDynamicPropertyItem(Item));
end;
procedure TLrDynamicProperties.PropertyAdded(inItem: TLrDynamicPropertyItem);
begin
//
end;
function TLrDynamicProperties.AddProperty(
inType: TLrDynamicPropertyType): TLrDynamicPropertyItem;
begin
Result := TLrDynamicPropertyItem(Add);
Result.PropertyType := inType;
end;
function TLrDynamicProperties.GetProps(inIndex: Integer): TLrDynamicPropertyItem;
begin
Result := TLrDynamicPropertyItem(Items[inIndex]);
end;
function TLrDynamicProperties.FindProperty(
const inName: string): TLrDynamicPropertyItem;
var
i: Integer;
begin
Result := nil;
for i := 0 to Pred(Count) do
if Props[i].Name = inName then
begin
Result := Props[i];
break;
end;
end;
end.
|
unit API_ORM_GUI;
interface
uses
System.Classes,
Vcl.ExtCtrls,
Vcl.StdCtrls,
Vcl.Controls,
Vcl.Forms,
API_MVC,
API_ORM,
API_ORM_Bind;
type
/// <summary>
/// View(Form) Class in the MVC pattern with ORM bind support
/// </summary>
TViewORM = class(TViewAbstract)
private
FRememberPosition: Boolean;
procedure RestorePosition;
procedure SavePosition;
protected
FBind: TBind;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
/// <summary>
/// Set True if need to remember current form size and restore it at next time form open.
/// Generally initialize inside TViewAbstract.InitView procedure.
/// </summary>
/// <remarks> See also
/// <see cref="API_MVC|TViewAbstract.InitView"/>
/// </remarks>
property RememberPosition: Boolean read FRememberPosition write FRememberPosition;
end;
TEditChangeEvent = procedure(aEdit: TControl) of object;
TEntityPanelAbstract = class abstract(TScrollBox)
private
FFieldsCount: integer;
procedure CreateEntityFields;
protected
FEntity: TEntityAbstract;
FAfterEditChange: TEditChangeEvent;
function GetStringValue(aFieldName: string): string;
function GetIntegerValue(aFieldName: string): integer;
procedure CreateFieldControl(aDBField: TDBField; aNum: Integer);
procedure InitPanel; virtual;
procedure CntrlChange(Sender: TObject);
public
constructor Create(aOwner: TWinControl);
procedure BuildControls(aEntity: TEntityAbstract);
procedure ClearControls;
property OnAfterEditChange: TEditChangeEvent read FAfterEditChange write FAfterEditChange;
end;
implementation
uses
API_Files,
Data.DB,
System.Generics.Collections,
System.SysUtils;
procedure TViewORM.SavePosition;
var
PosStrings: TStringList;
FilePath: string;
begin
TFilesEngine.CreateDirIfNotExists('ini');
PosStrings := TStringList.Create;
try
PosStrings.Values['Top'] := Self.Top.ToString;
PosStrings.Values['Left'] := Self.Left.ToString;
PosStrings.Values['Height'] := Self.Height.ToString;
PosStrings.Values['Width'] := Self.Width.ToString;
FilePath := GetCurrentDir + '\ini\' + Self.Name + '.ini';
PosStrings.SaveToFile(FilePath);
finally
PosStrings.Free;
end;
end;
procedure TViewORM.RestorePosition;
var
PosStrings: TStringList;
FilePath: string;
begin
TFilesEngine.CreateDirIfNotExists('ini');
PosStrings := TStringList.Create;
try
FilePath := GetCurrentDir + '\ini\' + Self.Name + '.ini';
if not FileExists(FilePath) then
Self.Position := poMainFormCenter
else
begin
PosStrings.LoadFromFile(FilePath);
Self.Top := PosStrings.Values['Top'].ToInteger;
Self.Left := PosStrings.Values['Left'].ToInteger;
Self.Height := PosStrings.Values['Height'].ToInteger;
Self.Width := PosStrings.Values['Width'].ToInteger;
end;
finally
PosStrings.Free;
end;
end;
constructor TViewORM.Create(AOwner: TComponent);
begin
inherited;
if RememberPosition then
RestorePosition;
FBind := TBind.Create;
end;
destructor TViewORM.Destroy;
begin
if RememberPosition then
SavePosition;
FBind.Free;
inherited;
end;
procedure TEntityPanelAbstract.CreateEntityFields;
var
DBField: TDBField;
begin
for DBField in FEntity.Fields do
begin
CreateFieldControl(DBField, FFieldsCount);
Inc(FFieldsCount);
end;
end;
procedure TEntityPanelAbstract.ClearControls;
begin
DestroyComponents;
end;
procedure TEntityPanelAbstract.CntrlChange(Sender: TObject);
var
FieldName: string;
Pair: TPair<string, TEntityAbstract>;
begin
FieldName := (Sender as TControl).Name;
Delete(FieldName, 1, 5);
if FEntity.Data.ContainsKey(FieldName) then
begin
if Sender is TEdit then
FEntity.Data.Items[FieldName] := (Sender as TEdit).Text;
if Sender is TColorBox then
FEntity.Data.Items[FieldName] := (Sender as TColorBox).Selected;
end
else
for Pair in FEntity.OneRelations do
begin
if Pair.Value = nil then Continue;
if Pair.Value.Data.ContainsKey(FieldName) then
begin
if Sender is TEdit then
Pair.Value.Data.Items[FieldName] := (Sender as TEdit).Text;
if Sender is TColorBox then
Pair.Value.Data.Items[FieldName] := (Sender as TColorBox).Selected;
end;
end;
if Assigned(FAfterEditChange) then FAfterEditChange(Sender as TControl);
end;
procedure TEntityPanelAbstract.InitPanel;
begin
end;
function TEntityPanelAbstract.GetStringValue(aFieldName: string): string;
begin
Result := FEntity.Data.Items[aFieldName];
end;
function TEntityPanelAbstract.GetIntegerValue(aFieldName: string): integer;
begin
Result := FEntity.Data.Items[aFieldName];
end;
procedure TEntityPanelAbstract.CreateFieldControl(aDBField: TDBField; aNum: Integer);
var
lblFieldTitle: TLabel;
edtControl: TEdit;
clrbxControl: TColorBox;
CntrlName: string;
begin
lblFieldTitle := TLabel.Create(Self);
CntrlName := 'lbl' + aDBField.FieldName;
if Self.FindComponent(CntrlName) = nil then
lblFieldTitle.Name := CntrlName
else
lblFieldTitle.Name := CntrlName + '_2';
lblFieldTitle.Parent := Self;
lblFieldTitle.Left := 10;
lblFieldTitle.Top := aNum * 42 + 6;
lblFieldTitle.Caption := aDBField.FieldName;
case aDBField.FieldType of
ftInteger, ftString, ftBoolean:
begin
if aDBField.FieldName.Contains('COLOR') then
begin
clrbxControl := TColorBox.Create(Self);
clrbxControl.Name := 'cntrl' + aDBField.FieldName;
clrbxControl.Parent := Self;
clrbxControl.Left := 10;
clrbxControl.Top := aNum * 42 + 20;
clrbxControl.Selected := GetIntegerValue(aDBField.FieldName);
clrbxControl.OnChange := CntrlChange;
end
else
begin
edtControl := TEdit.Create(Self);
CntrlName := 'cntrl' + aDBField.FieldName;
if Self.FindComponent(CntrlName) = nil then
edtControl.Name := CntrlName
else
edtControl.Name := CntrlName + '_2';
edtControl.Parent := Self;
edtControl.Left := 10;
edtControl.Top := aNum * 42 + 20;
edtControl.Text := GetStringValue(aDBField.FieldName);
edtControl.OnChange := CntrlChange;
end;
end;
end;
end;
procedure TEntityPanelAbstract.BuildControls(aEntity: TEntityAbstract);
var
Pair: TPair<string, TEntityAbstract>;
begin
if aEntity = nil then Exit;
InitPanel;
FFieldsCount := 0;
FEntity := aEntity;
CreateEntityFields;
for Pair in aEntity.OneRelations do
begin
FEntity := Pair.Value;
if Assigned(FEntity) then CreateEntityFields;
end;
FEntity := aEntity;
end;
constructor TEntityPanelAbstract.Create(aOwner: TWinControl);
begin
inherited Create(aOwner);
Self.Parent := aOwner;
Self.Align := alClient;
Self.BevelOuter := bvNone;
Self.BorderStyle := bsNone;
Self.ParentBackground := True;
end;
end.
|
{================================================================================
Copyright (C) 1997-2002 Mills Enterprise
Unit : rmGlobalComponentHook
Purpose : Provides a standard stack type interface to the rmControls that
descend from TComponent and that hook their owners WndProc. This
enables the component to correctly backout of the hook with out
hanging the form or application.
Date : 10-26-2000
Author : Ryan J. Mills
Version : 1.92
================================================================================}
unit rmGlobalComponentHook;
interface
{$I CompilerDefines.INC}
uses Controls, Windows;
Procedure PushOldProc(aWinControl:TWinControl; OldHook:TFarProc);
Function PopOldProc(aWinControl:TWinControl):TFarProc;
implementation
uses classes;
type
TrmWinControlHookList = class(TObject)
private
fWinControl:TWinControl;
fHooks:TList;
public
constructor Create(aWinControl:TWinControl);
destructor destroy; override;
property WinControl:TWinControl read fWinControl;
procedure AddHook(oldHook:TFarProc);
function GetNextHook:TFarProc;
function Count:integer;
end;
var
FormList : TList;
Procedure PushOldProc(aWinControl:TWinControl; OldHook:TFarProc);
var
loop : integer;
wHook : TrmWinControlHookList;
found : boolean;
begin
found := false;
wHook := nil;
for loop := 0 to formlist.count-1 do
begin
wHook := TrmWinControlHookList(formlist[loop]);
found := wHook.WinControl = aWinControl;
if found then break;
end;
if found then
wHook.AddHook(oldHook)
else
begin
if assigned(aWinControl) then
begin
wHook := TrmWinControlHookList.create(aWinControl);
formlist.add(wHook);
wHook.addhook(oldhook);
end;
end;
end;
Function PopOldProc(aWinControl:TWinControl):TFarProc;
var
loop : integer;
wHook : TrmWinControlHookList;
found : boolean;
begin
found := false;
wHook := nil;
for loop := 0 to formlist.count-1 do
begin
wHook := TrmWinControlHookList(formlist[loop]);
found := wHook.WinControl = aWinControl;
if found then break;
end;
if found then
begin
result := wHook.GetNextHook;
if wHook.Count = 0 then
begin
Formlist.Delete(loop);
wHook.free;
end;
end
else
result := nil;
end;
{ TrmWinControlHookList }
procedure TrmWinControlHookList.AddHook(oldHook: TFarProc);
begin
fhooks.add(oldhook);
end;
function TrmWinControlHookList.Count: integer;
begin
result := fhooks.count;
end;
constructor TrmWinControlHookList.Create(aWinControl:TWinControl);
begin
fWinControl := aWinControl;
fhooks := TList.create;
end;
destructor TrmWinControlHookList.destroy;
begin
fhooks.free;
inherited;
end;
function TrmWinControlHookList.GetNextHook: TFarProc;
begin
result := fhooks[fhooks.count-1];
fhooks.delete(fhooks.count-1);
end;
initialization
FormList := TList.create;
finalization
FormList.free;
end.
|
//**************************************************************************************************
//
// Unit uUpdatesChanges
// unit for the Delphi Dev Shell Tools
// https://github.com/RRUZ/delphi-dev-shell-tools
//
// The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the
// License at http://www.mozilla.org/MPL/
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either express or implied. See the License for the specific language governing rights
// and limitations under the License.
//
// The Original Code is uUpdatesChanges.pas.
//
// The Initial Developer of the Original Code is Rodrigo Ruz V.
// Portions created by Rodrigo Ruz V. are Copyright (C) 2013-2015 Rodrigo Ruz V.
// All Rights Reserved.
//
//**************************************************************************************************
unit uUpdatesChanges;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Imaging.pngimage,
Vcl.ExtCtrls, Vcl.OleCtrls, SHDocVw, Vcl.Styles.WebBrowser;
type
TWebBrowser=class(TVclStylesWebBrowser);
TFrmUpdateChanges = class(TForm)
ImageUpdate: TImage;
LabelMsg: TLabel;
BtnOk: TButton;
BtnCancel: TButton;
WebBrowser1: TWebBrowser;
btnDetails: TButton;
Panel2: TPanel;
procedure FormCreate(Sender: TObject);
procedure BtnCancelClick(Sender: TObject);
procedure BtnOkClick(Sender: TObject);
procedure btnDetailsClick(Sender: TObject);
private
{ Private declarations }
FExecute : Boolean;
FURLFeed: string;
procedure Load;
public
{ Public declarations }
property URLFeed: string read FURLFeed write FURLFeed;
function Execute: Boolean;
end;
function CheckChangesUpdates(const msg : string): Boolean;
implementation
uses
Vcl.Styles,
Vcl.Themes,
Vcl.GraphUtil,
MsHtml,
System.Win.ComObj,
Winapi.ActiveX,
Winapi.msxml;
{$R *.dfm}
function CheckChangesUpdates(const msg : string): Boolean;
var
Frm : TFrmUpdateChanges;
begin
Frm:=TFrmUpdateChanges.Create(nil);
try
Frm.LabelMsg.Caption:=msg;
Frm.URLFeed:= 'http://code.google.com/feeds/p/delphi-dev-shell-tools/svnchanges/basic';
Frm.ShowModal;
Result:=Frm.FExecute;
finally
Frm.Free;
end;
end;
procedure TFrmUpdateChanges.BtnCancelClick(Sender: TObject);
begin
FExecute:=False;
Close;
end;
procedure TFrmUpdateChanges.BtnOkClick(Sender: TObject);
begin
FExecute:=True;
Close;
end;
procedure TFrmUpdateChanges.btnDetailsClick(Sender: TObject);
begin
if ClientHeight<200 then
begin
Height:=Height+210;
Load;
end
else
Height:=Height-210;
end;
function TFrmUpdateChanges.Execute: Boolean;
begin
ShowModal;
Result:=Execute;
end;
procedure TFrmUpdateChanges.FormCreate(Sender: TObject);
begin
FExecute:=False;
end;
procedure TFrmUpdateChanges.Load;
const
COMPLETED= 4;
OK = 200;
XslRss =
'<xsl:stylesheet version="1.0"'+
' xmlns:atom="http://www.w3.org/2005/Atom"'+
' xmlns:xsl="http://www.w3.org/1999/XSL/Transform"'+
' xmlns:dc="http://purl.org/dc/elements/1.1/">'+
' <xsl:output method="html"/>'+
' <xsl:template match="/">'+
' <xsl:apply-templates select="/atom:feed/atom:head"/>'+
' <xsl:apply-templates select="/atom:feed"/>'+
' </xsl:template>'+
' <xsl:template match="atom:feed/atom:head">'+
' <h3><xsl:value-of select="atom:title"/></h3>'+
' <xsl:if test="atom:tagline"><p><xsl:value-of select="atom:tagline"/></p></xsl:if>'+
' <xsl:if test="atom:subtitle"><p><xsl:value-of select="atom:subtitle"/></p></xsl:if>'+
' </xsl:template>'+
' <xsl:template match="/atom:feed">'+
' <html xmlns="http://www.w3.org/1999/xhtml">'+
' <body style="font-family:Arial;font-size:12pt;background-color:%s">'+
' <div style="background-color:%s;color:%s;font-family: Tahoma;font-size:12px">'+
' <h3><xsl:value-of select="atom:title"/></h3>'+
' </div>'+
' <xsl:if test="atom:tagline"><p><xsl:value-of select="atom:tagline"/></p></xsl:if>'+
' <xsl:if test="atom:subtitle"><p><xsl:value-of select="atom:subtitle"/></p></xsl:if>'+
' <ul>'+
' <xsl:apply-templates select="atom:entry"/>'+
' </ul>'+
' </body>'+
' </html>'+
' </xsl:template>'+
' <xsl:template match="atom:entry">'+
' <div style="background-color:%s;color:%s;font-family: monospace;font-size:12px">'+
' <a href="{atom:link[@rel=''related'']/@href}" title="{substring(atom:published, 0, 11)}"><xsl:value-of select="atom:title"/></a>'+
' <xsl:choose>'+
' <xsl:when test="atom:content != ''''">'+
' <p><xsl:value-of select="atom:content" disable-output-escaping="yes" /></p>'+
' </xsl:when>'+
' <xsl:otherwise>'+
' <p><xsl:value-of select="atom:summary" disable-output-escaping="yes" /></p>'+
' </xsl:otherwise>'+
' </xsl:choose>'+
' </div>'+
' </xsl:template>'+
'</xsl:stylesheet>';
var
XMLHTTPRequest : IXMLHTTPRequest;
StringStream : TStringStream;
StreamAdapter : IStream;
PersistStreamInit: IPersistStreamInit;
XmlStr : string;
XMLDOMDocument : IXMLDOMDocument;
Xsl : IXMLDOMDocument;
FontColor : string;
BackColor : string;
LColor : TColor;
begin
if not TStyleManager.IsCustomStyleActive then
LColor:=clWhite
else
LColor:=StyleServices.GetSystemColor(clWindow);
BackColor:= ColorToWebColorStr(LColor);
if not TStyleManager.IsCustomStyleActive then
LColor:=clBlack
else
LColor:=StyleServices.GetSystemColor(clWindowText);
FontColor:= ColorToWebColorStr(LColor);
WebBrowser1.HandleNeeded;
WebBrowser1.Navigate('about:blank');
while WebBrowser1.ReadyState < READYSTATE_INTERACTIVE do
Application.ProcessMessages;
if Assigned(WebBrowser1.Document) then
begin
XMLHTTPRequest := CreateOleObject('MSXML2.XMLHTTP') As IXMLHTTPRequest;
try
XMLHTTPRequest.open('GET', FURLFeed, False, EmptyParam, EmptyParam);
XMLHTTPRequest.send('');
if (XMLHTTPRequest.readyState = COMPLETED) and (XMLHTTPRequest.status = OK) then
begin
XmlStr:=XMLHTTPRequest.responseText;
XMLDOMDocument := CoDOMDocument.Create();
XMLDOMDocument.async:=false;
XMLDOMDocument.loadXML(XmlStr);
Xsl:=CoDomDocument.Create();
Xsl.async:=false;
Xsl.loadXML(Format(XslRss,[BackColor , BackColor, FontColor, BackColor , FontColor]));
XmlStr:=XMLDOMDocument.transformNode(Xsl);
StringStream:=TStringStream.Create(XmlStr);
try
if WebBrowser1.Document.QueryInterface( IPersistStreamInit, PersistStreamInit) = S_OK then
begin
StringStream.Seek(0, 0) ;
StreamAdapter:= TStreamAdapter.Create(StringStream);
PersistStreamInit.Load(StreamAdapter);
end;
finally
StringStream.Free;
end;
end;
finally
XMLHTTPRequest:=nil;
end;
end;
end;
end.
|
unit pkcs11_library;
interface
uses
Sysutils,
Classes,
pkcs11t,
pkcs11f,
pkcs11_api,
pkcs11_slot,
pkcs11_slot_event_thread;
const
PKCS11_USER_CANCELED = '<CANCELED>';
type
{$TYPEINFO ON} // Needed to allow "published"
TPKCS11Library = class(TPKCS11API)
private
FDLLHandle: THandle;
FFilename: string;
FInitializeCalled: boolean;
FSlotEventThread: TPKCS11SlotEventThread;
FOnSlotEvent: TPKCS11SlotEvent;
FCachedSlotsArray: TPKCS11SlotArray;
protected
procedure LoadDLL(DLLfilename: string);
procedure FreeDLL();
procedure GetProcs();
function LibraryGetFunctionList(): boolean;
procedure ImportFunctionList();
function GetSlotList({onlySlotsWithTokenPresent: boolean; }var slotsArray: TPKCS11SlotArray): boolean;
function GetCountSlots({onlySlotsWithTokenPresent: boolean}): integer;
function GetSlotByArrayIdx(arrIdx: integer): TPKCS11Slot;
function GetSlotBySlotID(slotID: integer): TPKCS11Slot;
function GetInfo(var info: CK_INFO): boolean;
function GetCryptokiVersion(): CK_VERSION;
function GetManufacturerID(): string;
function GetFlags(): CK_FLAGS;
function GetlibraryDescription(): string;
function GetlibraryVersion(): CK_VERSION;
procedure EventThreadStart();
procedure EventThreadStop();
procedure EventThreadCallback(Sender: TObject; SlotID: integer);
public
constructor Create(filename: string); overload;
destructor Destroy(); override;
property Filename: string read FFilename;
function Initialize(): boolean;
function Finalize(): boolean;
property CryptokiVersion: CK_VERSION read GetCryptokiVersion;
property ManufacturerID: string read GetManufacturerID;
property Flags: CK_FLAGS read GetFlags;
property LibraryDescription: string read GetLibraryDescription;
property LibraryVersion: CK_VERSION read GetLibraryVersion;
property CountSlots: integer read GetCountSlots;
// Retrieve a slot by a *Delphi* index; [0..CountSlots-1]
property Slot[arrayIdx: integer]: TPKCS11Slot read GetSlotByArrayIdx;
// Retrieve a slot by it's PKCS#11 slot ID
property SlotByID[slotIdx: integer]: TPKCS11Slot read GetSlotBySlotID;
published
property InitializeCalled: boolean read FInitializeCalled;
property OnSlotEvent: TPKCS11SlotEvent read FOnSlotEvent write FOnSlotEvent;
end;
// Autodetect PKCS#11 library. If more than one are found, prompt the user
// which one to use
// Returns: One of:
// *) The DLL filename,
// *) PKCS11_USER_CANCELED if the user canceled
// *) An empty string if none can be found
function PKCS11AutoDetectLibrary(AOwner: TComponent): string;
// Verify a PKCS#11 library
// Note: This only carries out a basic check on the library
// Returns: TRUE/FALSE, depending on whether the DLL supplied supports the
// PKCS#11 interface
function PKCS11VerifyLibrary(LibraryDLL: string): boolean;
implementation
uses
Windows, Dialogs, Controls, Forms,
SDUi18n,
SDUGeneral,
PKCS11KnownLibs,
PKCS11LibrarySelectDlg,
SDUProgressDlg;
function PKCS11AutoDetectLibrary(AOwner: TComponent): string;
var
dlg: TPKCS11LibrarySelectDialog;
i: integer;
cntFound: integer;
lastFound: TPKCS11KnownLibrary;
progressDlg: TSDUProgressDialog;
prevCursor: TCursor;
canceled: boolean;
begin
Result := '';
canceled := FALSE;
prevCursor := Screen.Cursor;
dlg:= TPKCS11LibrarySelectDialog.Create(AOwner);
try
progressDlg := TSDUProgressDialog.Create(nil);
try
progressDlg.Min := 0;
// Yes, this is correct; it's driverFilenames.count and *not*
// (driverFilenames.count - 1)
progressDlg.Max := length(PKCS11_KNOWN_LIBRARIES);
progressDlg.Position := 0;
progressDlg.Title := _('Detecting PKCS#11 libraries...');
progressDlg.ShowStatusText := TRUE;
progressDlg.Show();
Screen.Cursor := crAppStart;
Application.ProcessMessages();
cntFound := 0;
for i:=low(PKCS11_KNOWN_LIBRARIES) to high(PKCS11_KNOWN_LIBRARIES) do
begin
progressDlg.StatusText := Format(
_('Checking for: [%s] %s'),
[
PKCS11_KNOWN_LIBRARIES[i].DLLFilename,
PKCS11KnownLibraryPrettyDesc(PKCS11_KNOWN_LIBRARIES[i])
]
);
Application.ProcessMessages();
if progressDlg.Cancel then
begin
canceled := TRUE;
break;
end;
if PKCS11VerifyLibrary(PKCS11_KNOWN_LIBRARIES[i].DLLFilename) then
begin
lastFound := PKCS11_KNOWN_LIBRARIES[i];
dlg.Add(lastFound);
inc(cntFound);
end;
progressDlg.IncPosition();
Application.ProcessMessages();
end;
finally
progressDlg.Free();
Screen.Cursor := prevCursor;
end;
if canceled then
begin
Result := PKCS11_USER_CANCELED;
end
else
begin
if (cntFound = 1) then
begin
// Only one found; return it's filename
Result := lastFound.DLLFilename;
end
else if (cntFound > 1) then
begin
// Multiple found; prompt user to select which one to usef
if (dlg.ShowModal() = mrOK) then
begin
Result := dlg.SelectedLibrary.DLLFilename;
end
else
begin
Result := PKCS11_USER_CANCELED;
end;
end;
end;
finally
dlg.Free();
end;
end;
function PKCS11VerifyLibrary(LibraryDLL: string): boolean;
var
lib: TPKCS11Library;
begin
result := TRUE;
if result then
begin
LibraryDLL := trim(LibraryDLL);
result:= (LibraryDLL <> '');
end;
if result then
begin
result:= FALSE;
try
lib:= TPKCS11Library.Create(LibraryDLL);
try
lib.Initialize();
lib.Finalize();
result := TRUE;
finally
lib.Free();
end;
except
on E:Exception do
begin
// Nothing - just swallow it
end;
end;
end;
end;
constructor TPKCS11Library.Create(filename: string);
begin
inherited Create();
FCachedSlotsArray := nil;
FSlotEventThread := nil;
FOnSlotEvent := nil;
FInitializeCalled := FALSE;
LoadDLL(filename);
end;
destructor TPKCS11Library.Destroy();
var
i: integer;
begin
EventThreadStop();
// Free off any cached slots
if (FCachedSlotsArray <> nil) then
begin
for i:=low(FCachedSlotsArray) to high(FCachedSlotsArray) do
begin
FCachedSlotsArray[i].Free();
end;
end;
FreeDLL();
inherited;
end;
procedure TPKCS11Library.LoadDLL(DLLfilename: string);
begin
// need to use LoadLibraryEx so it uses path if user specified one
FDLLHandle := LoadLibraryEx(PChar(DLLfilename),THandle(nil),LOAD_WITH_ALTERED_SEARCH_PATH);
if FDLLHandle=0 then begin
raise EPKCS11DLLNotFound.Create(SDUParamSubstitute(E_EPKCS11_DLLNOTFOUND, [DLLfilename]));
end;
FFilename:= DLLfilename;
GetProcs();
// Sanity check; we've got at least *some* functionality, right?
if (
(@LibraryFunctionList.CK_C_Initialize = nil) and
(@LibraryFunctionList.CK_C_GetInfo = nil) and
(@LibraryFunctionList.CK_C_GetSlotList = nil) and
(@LibraryFunctionList.CK_C_GetSlotInfo = nil) and
(@LibraryFunctionList.CK_C_OpenSession = nil)
) then begin
raise EPKCS11DLLNoAPI.Create(E_EPKCS11_DLLNOAPI);
end;
end;
procedure TPKCS11Library.FreeDLL();
begin
if (FDLLHandle<>0) then
begin
FreeLibrary(FDLLHandle);
FDLLHandle := 0;
end;
end;
procedure TPKCS11Library.GetProcs();
begin
ImportFunctionList();
// If we imported the function list correctly, attempt to list again via
// C_GetFunctionList - this should get the version ID populated as well
if (@LibraryFunctionList.CK_C_GetFunctionList <> nil) then
begin
LibraryGetFunctionList();
end;
end;
procedure TPKCS11Library.ImportFunctionList();
begin
FFunctionList.version.major := 0;
FFunctionList.version.minor := 0;
@FFunctionList.CK_C_Initialize := GetProcAddress(FDLLHandle, FN_NAME_C_Initialize);
@FFunctionList.CK_C_Finalize := GetProcAddress(FDLLHandle, FN_NAME_C_Finalize);
@FFunctionList.CK_C_GetInfo := GetProcAddress(FDLLHandle, FN_NAME_C_GetInfo);
@FFunctionList.CK_C_GetFunctionList := GetProcAddress(FDLLHandle, FN_NAME_C_GetFunctionList);
@FFunctionList.CK_C_GetSlotList := GetProcAddress(FDLLHandle, FN_NAME_C_GetSlotList);
@FFunctionList.CK_C_GetSlotInfo := GetProcAddress(FDLLHandle, FN_NAME_C_GetSlotInfo);
@FFunctionList.CK_C_GetTokenInfo := GetProcAddress(FDLLHandle, FN_NAME_C_GetTokenInfo);
@FFunctionList.CK_C_GetMechanismList := GetProcAddress(FDLLHandle, FN_NAME_C_GetMechanismList);
@FFunctionList.CK_C_GetMechanismInfo := GetProcAddress(FDLLHandle, FN_NAME_C_GetMechanismInfo);
@FFunctionList.CK_C_InitToken := GetProcAddress(FDLLHandle, FN_NAME_C_InitToken);
@FFunctionList.CK_C_InitPIN := GetProcAddress(FDLLHandle, FN_NAME_C_InitPIN);
@FFunctionList.CK_C_SetPIN := GetProcAddress(FDLLHandle, FN_NAME_C_SetPIN);
@FFunctionList.CK_C_OpenSession := GetProcAddress(FDLLHandle, FN_NAME_C_OpenSession);
@FFunctionList.CK_C_CloseSession := GetProcAddress(FDLLHandle, FN_NAME_C_CloseSession);
@FFunctionList.CK_C_CloseAllSessions := GetProcAddress(FDLLHandle, FN_NAME_C_CloseAllSessions);
@FFunctionList.CK_C_GetSessionInfo := GetProcAddress(FDLLHandle, FN_NAME_C_GetSessionInfo);
@FFunctionList.CK_C_GetOperationState := GetProcAddress(FDLLHandle, FN_NAME_C_GetOperationState);
@FFunctionList.CK_C_SetOperationState := GetProcAddress(FDLLHandle, FN_NAME_C_SetOperationState);
@FFunctionList.CK_C_Login := GetProcAddress(FDLLHandle, FN_NAME_C_Login);
@FFunctionList.CK_C_Logout := GetProcAddress(FDLLHandle, FN_NAME_C_Logout);
@FFunctionList.CK_C_CreateObject := GetProcAddress(FDLLHandle, FN_NAME_C_CreateObject);
@FFunctionList.CK_C_CopyObject := GetProcAddress(FDLLHandle, FN_NAME_C_CopyObject);
@FFunctionList.CK_C_DestroyObject := GetProcAddress(FDLLHandle, FN_NAME_C_DestroyObject);
@FFunctionList.CK_C_GetObjectSize := GetProcAddress(FDLLHandle, FN_NAME_C_GetObjectSize);
@FFunctionList.CK_C_GetAttributeValue := GetProcAddress(FDLLHandle, FN_NAME_C_GetAttributeValue);
@FFunctionList.CK_C_SetAttributeValue := GetProcAddress(FDLLHandle, FN_NAME_C_SetAttributeValue);
@FFunctionList.CK_C_FindObjectsInit := GetProcAddress(FDLLHandle, FN_NAME_C_FindObjectsInit);
@FFunctionList.CK_C_FindObjects := GetProcAddress(FDLLHandle, FN_NAME_C_FindObjects);
@FFunctionList.CK_C_FindObjectsFinal := GetProcAddress(FDLLHandle, FN_NAME_C_FindObjectsFinal);
@FFunctionList.CK_C_EncryptInit := GetProcAddress(FDLLHandle, FN_NAME_C_EncryptInit);
@FFunctionList.CK_C_Encrypt := GetProcAddress(FDLLHandle, FN_NAME_C_Encrypt);
@FFunctionList.CK_C_EncryptUpdate := GetProcAddress(FDLLHandle, FN_NAME_C_EncryptUpdate);
@FFunctionList.CK_C_EncryptFinal := GetProcAddress(FDLLHandle, FN_NAME_C_EncryptFinal);
@FFunctionList.CK_C_DecryptInit := GetProcAddress(FDLLHandle, FN_NAME_C_DecryptInit);
@FFunctionList.CK_C_Decrypt := GetProcAddress(FDLLHandle, FN_NAME_C_Decrypt);
@FFunctionList.CK_C_DecryptUpdate := GetProcAddress(FDLLHandle, FN_NAME_C_DecryptUpdate);
@FFunctionList.CK_C_DecryptFinal := GetProcAddress(FDLLHandle, FN_NAME_C_DecryptFinal);
@FFunctionList.CK_C_DigestInit := GetProcAddress(FDLLHandle, FN_NAME_C_DigestInit);
@FFunctionList.CK_C_Digest := GetProcAddress(FDLLHandle, FN_NAME_C_Digest);
@FFunctionList.CK_C_DigestUpdate := GetProcAddress(FDLLHandle, FN_NAME_C_DigestUpdate);
@FFunctionList.CK_C_DigestKey := GetProcAddress(FDLLHandle, FN_NAME_C_DigestKey);
@FFunctionList.CK_C_DigestFinal := GetProcAddress(FDLLHandle, FN_NAME_C_DigestFinal);
@FFunctionList.CK_C_SignInit := GetProcAddress(FDLLHandle, FN_NAME_C_SignInit);
@FFunctionList.CK_C_Sign := GetProcAddress(FDLLHandle, FN_NAME_C_Sign);
@FFunctionList.CK_C_SignUpdate := GetProcAddress(FDLLHandle, FN_NAME_C_SignUpdate);
@FFunctionList.CK_C_SignFinal := GetProcAddress(FDLLHandle, FN_NAME_C_SignFinal);
@FFunctionList.CK_C_SignRecoverInit := GetProcAddress(FDLLHandle, FN_NAME_C_SignRecoverInit);
@FFunctionList.CK_C_SignRecover := GetProcAddress(FDLLHandle, FN_NAME_C_SignRecover);
@FFunctionList.CK_C_VerifyInit := GetProcAddress(FDLLHandle, FN_NAME_C_VerifyInit);
@FFunctionList.CK_C_Verify := GetProcAddress(FDLLHandle, FN_NAME_C_Verify);
@FFunctionList.CK_C_VerifyUpdate := GetProcAddress(FDLLHandle, FN_NAME_C_VerifyUpdate);
@FFunctionList.CK_C_VerifyFinal := GetProcAddress(FDLLHandle, FN_NAME_C_VerifyFinal);
@FFunctionList.CK_C_VerifyRecoverInit := GetProcAddress(FDLLHandle, FN_NAME_C_VerifyRecoverInit);
@FFunctionList.CK_C_VerifyRecover := GetProcAddress(FDLLHandle, FN_NAME_C_VerifyRecover);
@FFunctionList.CK_C_DigestEncryptUpdate := GetProcAddress(FDLLHandle, FN_NAME_C_DigestEncryptUpdate);
@FFunctionList.CK_C_DecryptDigestUpdate := GetProcAddress(FDLLHandle, FN_NAME_C_DecryptDigestUpdate);
@FFunctionList.CK_C_SignEncryptUpdate := GetProcAddress(FDLLHandle, FN_NAME_C_SignEncryptUpdate);
@FFunctionList.CK_C_DecryptVerifyUpdate := GetProcAddress(FDLLHandle, FN_NAME_C_DecryptVerifyUpdate);
@FFunctionList.CK_C_GenerateKey := GetProcAddress(FDLLHandle, FN_NAME_C_GenerateKey);
@FFunctionList.CK_C_GenerateKeyPair := GetProcAddress(FDLLHandle, FN_NAME_C_GenerateKeyPair);
@FFunctionList.CK_C_WrapKey := GetProcAddress(FDLLHandle, FN_NAME_C_WrapKey);
@FFunctionList.CK_C_UnwrapKey := GetProcAddress(FDLLHandle, FN_NAME_C_UnwrapKey);
@FFunctionList.CK_C_DeriveKey := GetProcAddress(FDLLHandle, FN_NAME_C_DeriveKey);
@FFunctionList.CK_C_SeedRandom := GetProcAddress(FDLLHandle, FN_NAME_C_SeedRandom);
@FFunctionList.CK_C_GenerateRandom := GetProcAddress(FDLLHandle, FN_NAME_C_GenerateRandom);
@FFunctionList.CK_C_GetFunctionStatus := GetProcAddress(FDLLHandle, FN_NAME_C_GetFunctionStatus);
@FFunctionList.CK_C_CancelFunction := GetProcAddress(FDLLHandle, FN_NAME_C_CancelFunction);
@FFunctionList.CK_C_WaitForSlotEvent := GetProcAddress(FDLLHandle, FN_NAME_C_WaitForSlotEvent);
end;
function TPKCS11Library.LibraryGetFunctionList(): boolean;
var
pFuncList: ^CK_FUNCTION_LIST;
begin
CheckFnAvailable(@LibraryFunctionList.CK_C_GetFunctionList, FN_NAME_C_GetFunctionList);
LastRV := LibraryFunctionList.CK_C_GetFunctionList(@pFuncList);
if RVSuccess(LastRV) then
begin
FFunctionList := pFuncList^;
end;
Result := RVSuccess(LastRV);
end;
function TPKCS11Library.GetCountSlots({onlySlotsWithTokenPresent: boolean}): integer;
var
slotsArray: TPKCS11SlotArray;
begin
Result := 0;
if GetSlotList({onlySlotsWithTokenPresent, }slotsArray) then
begin
Result := length(slotsArray);
end;
end;
// This method populates FCachedSlotsArray
function TPKCS11Library.GetSlotList({onlySlotsWithTokenPresent: boolean; }var slotsArray: TPKCS11SlotArray): boolean;
var
apiTokenPresent: CK_BBOOL;
slotID: CK_SLOT_ID;
ulCount: CK_ULONG;
ptrBuffer: CK_SLOT_ID_PTR;
ptrBufferOffset: CK_SLOT_ID_PTR;
bufferSize: integer;
i: integer;
slotObj: TPKCS11Slot;
begin
CheckFnAvailable(@LibraryFunctionList.CK_C_GetSlotList, FN_NAME_C_GetSlotList);
apiTokenPresent := CK_FALSE;
{
if onlySlotsWithTokenPresent then
begin
apiTokenPresent := CK_TRUE;
end;
}
if (FCachedSlotsArray <> nil) then
begin
slotsArray := FCachedSlotsArray;
Result := TRUE;
exit;
end;
// Get count..
ulCount := 0;
LastRV := LibraryFunctionList.CK_C_GetSlotList(apiTokenPresent, nil, @ulCount);
if RVSuccess(LastRV) then
begin
// Get...
bufferSize := (sizeof(slotID) * ulCount);
ptrBuffer := allocmem(bufferSize);
try
LastRV := LibraryFunctionList.CK_C_GetSlotList(apiTokenPresent, ptrBuffer, @ulCount);
if RVSuccess(LastRV) then
begin
SetLength(slotsArray, ulCount);
ptrBufferOffset := ptrBuffer;
for i:=1 to ulCount do
begin
slotObj:= TPKCS11Slot.Create();
slotID := ptrBufferOffset^;
slotObj.SlotID := slotID;
slotObj.LibraryFunctionList := LibraryFunctionList;
slotsArray[i-1] := slotObj;
ptrBufferOffset := Pointer(PChar(ptrBufferOffset) + sizeof(ptrBufferOffset^));
end;
FCachedSlotsArray := slotsArray;
end;
finally
FreeMem(ptrBuffer);
end;
end;
Result := RVSuccess(LastRV);
end;
function TPKCS11Library.GetSlotByArrayIdx(arrIdx: integer): TPKCS11Slot;
var
slotsArray: TPKCS11SlotArray;
begin
Result := nil;
if GetSlotList({FALSE, }slotsArray) then
begin
// Sanity check
if ((low(slotsArray) + arrIdx) > high(slotsArray)) then
begin
raise EPKCS11ListIndexOutOFBounds.Create(E_EPKCS11_LISTINDEXOUTOFBOUNDS);
end;
Result := slotsArray[(low(slotsArray) + arrIdx)];
end;
end;
function TPKCS11Library.GetSlotBySlotID(slotID: integer): TPKCS11Slot;
var
slotsArray: TPKCS11SlotArray;
i: integer;
begin
Result := nil;
if GetSlotList({FALSE, }slotsArray) then
begin
for i:=low(slotsArray) to high(slotsArray) do
begin
if (slotsArray[i].SlotID = slotID) then
begin
Result := slotsArray[i];
break
end;
end;
end;
end;
function TPKCS11Library.Initialize(): boolean;
begin
CheckFnAvailable(@LibraryFunctionList.CK_C_Initialize, FN_NAME_C_Initialize);
LastRV := LibraryFunctionList.CK_C_Initialize(nil);
Result := RVSuccess(LastRV);
if Result then
begin
FInitializeCalled := TRUE;
EventThreadStart();
end;
end;
function TPKCS11Library.Finalize(): boolean;
begin
CheckFnAvailable(@LibraryFunctionList.CK_C_Finalize, FN_NAME_C_Finalize);
LastRV := LibraryFunctionList.CK_C_Finalize(nil);
Result := RVSuccess(LastRV);
if Result then
begin
FInitializeCalled := FALSE;
EventThreadStop();
end;
end;
function TPKCS11Library.GetInfo(var info: CK_INFO): boolean;
begin
CheckFnAvailable(@LibraryFunctionList.CK_C_GetInfo, FN_NAME_C_GetInfo);
ZeroMemory(@info, sizeof(info));
LastRV := LibraryFunctionList.CK_C_GetInfo(@info);
Result := RVSuccess(LastRV);
end;
function TPKCS11Library.GetCryptokiVersion(): CK_VERSION;
var
info: CK_INFO;
begin
Result := NULL_VERSION;
if (GetInfo(info)) then
begin
Result := info.cryptokiVersion;
end;
end;
function TPKCS11Library.GetManufacturerID(): string;
var
info: CK_INFO;
begin
Result := '';
if (GetInfo(info)) then
begin
Result := UTF8CHARArrayToString(TCK_UTF8CHARArray_32(info.manufacturerID));
end;
end;
function TPKCS11Library.GetFlags(): CK_FLAGS;
var
info: CK_INFO;
begin
Result := 0;
if (GetInfo(info)) then
begin
Result := info.Flags;
end;
end;
function TPKCS11Library.GetLibraryDescription(): string;
var
info: CK_INFO;
begin
Result := '';
if (GetInfo(info)) then
begin
Result := UTF8CHARArrayToString(TCK_UTF8CHARArray_32(info.libraryDescription));
end;
end;
function TPKCS11Library.GetLibraryVersion(): CK_VERSION;
var
info: CK_INFO;
begin
Result := NULL_VERSION;
if (GetInfo(info)) then
begin
Result := info.libraryVersion;
end;
end;
procedure TPKCS11Library.EventThreadStart();
begin
if (FSlotEventThread = nil) then
begin
// Note: Don't use CheckFnAvailable(...) here
if (@LibraryFunctionList.CK_C_WaitForSlotEvent <> nil) then
begin
FSlotEventThread := TPKCS11SlotEventThread.Create(TRUE);
FSlotEventThread.LibraryFunctionList := LibraryFunctionList;
FSlotEventThread.LibraryCallback := EventThreadCallback;
FSlotEventThread.Resume();
end;
end;
end;
procedure TPKCS11Library.EventThreadStop();
begin
if (FSlotEventThread <> nil) then
begin
FSlotEventThread.Terminate();
FSlotEventThread.Free();
FSlotEventThread := nil;
end;
end;
procedure TPKCS11Library.EventThreadCallback(Sender: TObject; SlotID: integer);
begin
if Assigned(FOnSlotEvent) then
begin
FOnSlotEvent(self, SlotID);
end;
end;
END.
|
//Даны три одномерных массива a, b и c разного размера.
//Для каждого из этих массивов сформировать массив, содержащий номера элементов исходного массива,
//которые меньше половины среднего арифметического значений исходного массива.
//Для формирования массива из номеров элементов, меньших половины среднего арифметического, использовать процедуру.
//Для ввода и вывода массивов также использовать процедуры.
program lab11_v30;
const
nmax = 20;
type
mas = array[1..nmax] of real;
var
// Входные данные
a,b,c,ay,by,cy: mas;
// Промежуточные данные
i,j,an, bn, cn,ayn,byn,cyn: integer;
sa, sb, sc: real;
f:textfile;
procedure vvod(var x:mas;var n:integer; var f:textfile );
var i: integer;
begin
readln(f, n);
if n > nmax then writeln('NZID')
else begin
for i := 1 to n-1 do
read(f,x[i]);
readln(f,x[n]);
end;
end;
procedure print(var x:mas; n:integer);
var i: integer;
begin
for i := 1 to n do
write(x[i]);
writeln;
end;
function srarifm(var x:mas; n:integer):real;
var s: real;
i: integer;
begin
s := 0;
for i:=1 to n do begin
s := s + x[i];
end;
srarifm := s / n;
end;
procedure createvector(var x,y:mas; var s:real;var n,m:integer);
var i: integer;
begin
m := 1;
for i:=1 to n do begin
if x[i] < (s/2) then begin
y[m] := i;
m := m + 1;
end;
end;
m := m - 1;
end;
procedure writevector(var y:mas; m:integer;var f:textfile);
var i: integer;
begin
for i:=1 to m do begin
write(f, y[i], ' ');
end;
writeln(f);
end;
begin
if ParamCount < 2 then { Проверяем количество параметров }
writeln('Недостаточно параметров!')
else
begin
if not FileExists(ParamStr(1)) then { Проверяем существование файла }
writeln('Невозможно открыть файл ''', ParamStr(1), ''' для чтения')
else
begin
AssignFile(f, ParamStr(1)); { Открываем файл }
Reset(f);
vvod(a,an,f);
vvod(b,bn,f);
vvod(c,cn,f);
CloseFile(f); { Закрываем файл }
print(a, an);
print(b, bn);
print(c, cn);
sa := srarifm(a,an);
sb := srarifm(b,bn);
sc := srarifm(c,cn);
createvector(a,ay,sa,an,ayn);
createvector(b,by,sb,bn,byn);
createvector(c,cy,sc,cn,cyn);
AssignFile(f, ParamStr(2));
rewrite(f);
writeln(f,'Array A:');
writevector(a,an,f);
writeln(f,'Arithmetic mean: ',sa);
writeln(f,'Indexes of numbers less than s/2:');
writevector(ay,ayn,f);
writeln(f);
writeln(f,'Array B:');
writevector(b,bn,f);
writeln(f,'Arithmetic mean: ',sb);
writeln(f,'Indexes of numbers less than s/2:');
writevector(by,byn,f);
writeln(f);
writeln(f,'Array C:');
writevector(c,cn,f);
writeln(f,'Arithmetic mean: ',sc);
writeln(f,'Indexes of numbers less than s/2:');
writevector(cy,cyn,f);
CloseFile(f);
end;
end;
end. |
unit BCEditor.Lines;
interface {********************************************************************}
uses
SysUtils, Classes, Generics.Collections, RegularExpressions,
Graphics, Controls,
BCEditor.Utils, BCEditor.Consts, BCEditor.Types;
type
TBCEditorLines = class(TStrings)
protected type
TCompare = function(Lines: TBCEditorLines; Line1, Line2: Integer): Integer;
TOption = (loTrimTrailingSpaces, loTrimTrailingLines,
loUndoGrouped, loUndoAfterLoad, loUndoAfterSave);
TOptions = set of TOption;
TState = set of (lsLoading, lsSaving, lsDontTrim, lsUndo, lsRedo,
lsCaretMoved, lsSelChanged, lsTextChanged, lsInserting);
TLine = packed record
type
TFlags = set of (lfHasTabs);
TState = (lsLoaded, lsModified, lsSaved);
public
Background: TColor;
CodeFolding: packed record
BeginRange: Pointer;
EndRange: Pointer;
TreeLine: Boolean;
end;
FirstRow: Integer;
Flags: TFlags;
Foreground: TColor;
Range: Pointer;
State: TLine.TState;
Text: string;
end;
TItems = TList<TLine>;
TSearch = class
private
FArea: TBCEditorLinesArea;
FBackwards: Boolean;
FCaseSensitive: Boolean;
FEngine: (eNormal, eLinesRegExpr, eTextRegExpr);
FErrorMessage: string;
FFoundLength: Integer;
FFoundPosition: TBCEditorLinesPosition;
FLines: TBCEditorLines;
FPattern: string;
FRegEx: TRegEx;
FRegExOptions: TRegexOptions;
FReplaceText: string;
FWholeWords: Boolean;
function FindLinesRegEx(const APosition: TBCEditorLinesPosition; const AFoundLength: Integer): Boolean;
function FindNormal(const APosition: TBCEditorLinesPosition; const AFoundLength: Integer): Boolean;
function FindTextRegEx(const APosition: TBCEditorLinesPosition; const AFoundLength: Integer): Boolean;
protected
property Lines: TBCEditorLines read FLines;
public
constructor Create(const ALines: TBCEditorLines;
const AArea: TBCEditorLinesArea;
const ACaseSensitive, AWholeWords, ARegExpr, ABackwards: Boolean;
const APattern: string; const AReplaceText: string = '');
function Find(var APosition: TBCEditorLinesPosition; out AFoundLength: Integer): Boolean;
procedure Replace();
property Area: TBCEditorLinesArea read FArea;
property ErrorMessage: string read FErrorMessage;
end;
TUndoItem = packed record
type
TType = (utSelection, utInsert, utReplace, utBackspace, utDelete,
utClear, utInsertIndent, utDeleteIndent);
public
BlockNumber: Integer;
UndoType: TType;
CaretPosition: TBCEditorLinesPosition;
SelArea: TBCEditorLinesArea;
Area: TBCEditorLinesArea;
Text: string;
function ToString(): string;
end;
public type
TChangeEvent = procedure(Sender: TObject; const Line: Integer) of object;
TUndoList = class(TList<TUndoItem>)
strict private
FBlockNumber: Integer;
FChanges: Integer;
FCurrentBlockNumber: Integer;
FGroupBreak: Boolean;
FLines: TBCEditorLines;
FUpdateCount: Integer;
function GetUpdated(): Boolean;
public
procedure BeginUpdate();
procedure Clear();
constructor Create(const ALines: TBCEditorLines);
procedure EndUpdate();
procedure GroupBreak();
function Peek(): TUndoItem;
function Pop(): TUndoItem;
procedure Push(const AUndoType: TUndoItem.TType;
const ACaretPosition: TBCEditorLinesPosition; const ASelArea: TBCEditorLinesArea;
const AArea: TBCEditorLinesArea; const AText: string = '';
const ABlockNumber: Integer = 0); overload;
property Changes: Integer read FChanges;
property Lines: TBCEditorLines read FLines;
property Updated: Boolean read GetUpdated;
property UpdateCount: Integer read FUpdateCount;
end;
protected const
BOFPosition: TBCEditorLinesPosition = ( Char: 0; Line: 0; );
strict private const
DefaultOptions = [loUndoGrouped];
strict private
FCaretPosition: TBCEditorLinesPosition;
FCaseSensitive: Boolean;
FEditor: TCustomControl;
FItems: TItems;
FModified: Boolean;
FOldCaretPosition: TBCEditorLinesPosition;
FOldSelArea: TBCEditorLinesArea;
FOldUndoListCount: Integer;
FOnAfterUpdate: TNotifyEvent;
FOnBeforeUpdate: TNotifyEvent;
FOnCaretMoved: TNotifyEvent;
FOnCleared: TNotifyEvent;
FOnDeleted: TChangeEvent;
FOnDeleting: TChangeEvent;
FOnInserted: TChangeEvent;
FOnSelChange: TNotifyEvent;
FOnUpdated: TChangeEvent;
FOptions: TOptions;
FReadOnly: Boolean;
FRedoList: TUndoList;
FSelArea: TBCEditorLinesArea;
FSortOrder: TBCEditorSortOrder;
FState: TState;
FUndoList: TUndoList;
procedure DoDelete(ALine: Integer);
procedure DoDeleteIndent(ABeginPosition, AEndPosition: TBCEditorLinesPosition;
const AIndentText: string);
procedure DoDeleteText(const AArea: TBCEditorLinesArea);
procedure DoInsertIndent(const AArea: TBCEditorLinesArea;
const AIndentText: string);
procedure DoInsert(ALine: Integer; const AText: string);
function DoInsertText(APosition: TBCEditorLinesPosition;
const AText: string): TBCEditorLinesPosition;
procedure DoPut(ALine: Integer; const AText: string);
procedure ExchangeItems(ALine1, ALine2: Integer);
procedure ExecuteUndoRedo(const List: TUndoList);
function GetArea(): TBCEditorLinesArea; inline;
function GetBOLPosition(ALine: Integer): TBCEditorLinesPosition; inline;
function GetCanRedo(): Boolean;
function GetCanUndo(): Boolean;
function GetChar(APosition: TBCEditorLinesPosition): Char;
function GetEOFPosition(): TBCEditorLinesPosition;
function GetEOLPosition(ALine: Integer): TBCEditorLinesPosition; inline;
function GetLineArea(ALine: Integer): TBCEditorLinesArea; inline;
function GetTextIn(const AArea: TBCEditorLinesArea): string;
procedure InternalClear(const AClearUndo: Boolean); overload;
procedure SetCaretPosition(const AValue: TBCEditorLinesPosition);
procedure SetModified(const AValue: Boolean);
procedure SetSelArea(AValue: TBCEditorLinesArea);
procedure QuickSort(ALeft, ARight: Integer; ACompare: TCompare);
protected
procedure Backspace(AArea: TBCEditorLinesArea);
procedure ClearUndo();
function CompareStrings(const S1, S2: string): Integer; override;
procedure CustomSort(const ABeginLine, AEndLine: Integer; ACompare: TCompare);
procedure DeleteIndent(ABeginPosition, AEndPosition: TBCEditorLinesPosition;
const AIndentText: string);
procedure DeleteText(AArea: TBCEditorLinesArea); overload;
function Get(ALine: Integer): string; override;
function GetCount(): Integer; override;
function GetTextLength(): Integer;
function GetTextStr(): string; override;
procedure InsertIndent(ABeginPosition, AEndPosition: TBCEditorLinesPosition;
const AIndentText: string);
function CharIndexOf(const APosition: TBCEditorLinesPosition): Integer;
function InsertText(APosition: TBCEditorLinesPosition;
const AText: string): TBCEditorLinesPosition; overload;
function IsWordBreakChar(const AChar: Char): Boolean; inline;
function PositionOf(const ACharIndex: Integer): TBCEditorLinesPosition; overload; inline;
function PositionOf(const ACharIndex: Integer;
const ARelativePosition: TBCEditorLinesPosition): TBCEditorLinesPosition; overload;
procedure Put(ALine: Integer; const AText: string); override;
procedure Redo(); inline;
function ReplaceText(const AArea: TBCEditorLinesArea; const AText: string): TBCEditorLinesPosition;
procedure SetBackground(const ALine: Integer; const AValue: TColor); inline;
procedure SetCodeFoldingBeginRange(const ALine: Integer; const AValue: Pointer);
procedure SetCodeFoldingEndRange(const ALine: Integer; const AValue: Pointer);
procedure SetCodeFoldingTreeLine(const ALine: Integer; const AValue: Boolean);
procedure SetFirstRow(const ALine: Integer; const AValue: Integer); inline;
procedure SetForeground(const ALine: Integer; const AValue: TColor); inline;
procedure SetRange(const ALine: Integer; const AValue: Pointer); inline;
procedure SetTextStr(const AValue: string); override;
procedure SetUpdateState(AUpdating: Boolean); override;
procedure Sort(const ABeginLine, AEndLine: Integer); virtual;
procedure Undo(); inline;
procedure UndoGroupBreak();
function ValidPosition(const APosition: TBCEditorLinesPosition): Boolean;
property Area: TBCEditorLinesArea read GetArea;
property BOLPosition[Line: Integer]: TBCEditorLinesPosition read GetBOLPosition;
property CanRedo: Boolean read GetCanRedo;
property CanUndo: Boolean read GetCanUndo;
property CaretPosition: TBCEditorLinesPosition read FCaretPosition write SetCaretPosition;
property CaseSensitive: Boolean read FCaseSensitive write FCaseSensitive default False;
property Char[Position: TBCEditorLinesPosition]: Char read GetChar;
property Editor: TCustomControl read FEditor write FEditor;
property EOFPosition: TBCEditorLinesPosition read GetEOFPosition;
property EOLPosition[ALine: Integer]: TBCEditorLinesPosition read GetEOLPosition;
property Items: TItems read FItems;
property Modified: Boolean read FModified write SetModified;
property LineArea[Line: Integer]: TBCEditorLinesArea read GetLineArea;
property OnAfterUpdate: TNotifyEvent read FOnAfterUpdate write FOnAfterUpdate;
property OnBeforeUpdate: TNotifyEvent read FOnBeforeUpdate write FOnBeforeUpdate;
property OnCaretMoved: TNotifyEvent read FOnCaretMoved write FOnCaretMoved;
property OnCleared: TNotifyEvent read FOnCleared write FOnCleared;
property OnDeleted: TChangeEvent read FOnDeleted write FOnDeleted;
property OnDeleting: TChangeEvent read FOnDeleting write FOnDeleting;
property OnInserted: TChangeEvent read FOnInserted write FOnInserted;
property OnSelChange: TNotifyEvent read FOnSelChange write FOnSelChange;
property OnUpdated: TChangeEvent read FOnUpdated write FOnUpdated;
property Options: TOptions read FOptions write FOptions;
property ReadOnly: Boolean read FReadOnly write FReadOnly;
property RedoList: TUndoList read FRedoList;
property SelArea: TBCEditorLinesArea read FSelArea write SetSelArea;
property SortOrder: TBCEditorSortOrder read FSortOrder write FSortOrder;
property State: TState read FState;
property TextIn[const Area: TBCEditorLinesArea]: string read GetTextIn;
property UndoList: TUndoList read FUndoList;
public
function Add(const AText: string): Integer; override;
procedure Clear(); overload; override;
constructor Create(const AEditor: TCustomControl);
procedure Delete(ALine: Integer); overload; override;
destructor Destroy; override;
procedure Insert(ALine: Integer; const AText: string); override;
procedure SaveToStream(AStream: TStream; AEncoding: TEncoding = nil); override;
end;
implementation {***************************************************************}
uses
Windows,
Math, StrUtils, SysConst;
resourcestring
SBCEditorCharIndexInLineBreak = 'Character index is inside line break (%d)';
SBCEditorPatternContainsWordBreakChar = 'Pattern contains word break character';
function HasLineBreak(const AText: string): Boolean;
var
LEndPos: PChar;
LPos: PChar;
begin
LPos := PChar(AText); LEndPos := PChar(@AText[Length(AText)]);
while (LPos <= LEndPos) do
if (CharInSet(LPos^, [BCEDITOR_LINEFEED, BCEDITOR_CARRIAGE_RETURN])) then
Exit(True)
else
Inc(LPos);
Result := False;
end;
{ TBCEditorLines.TSearch ******************************************************}
constructor TBCEditorLines.TSearch.Create(const ALines: TBCEditorLines;
const AArea: TBCEditorLinesArea;
const ACaseSensitive, AWholeWords, ARegExpr, ABackwards: Boolean;
const APattern: string; const AReplaceText: string = '');
var
LIndex: Integer;
begin
Assert((BOFPosition <= AArea.BeginPosition) and (AArea.BeginPosition <= AArea.EndPosition) and (AArea.EndPosition <= ALines.EOFPosition));
inherited Create();
FLines := ALines;
FArea := AArea;
FCaseSensitive := ACaseSensitive;
FWholeWords := AWholeWords;
if (not ARegExpr) then
FEngine := eNormal
else if (Pos(ReplaceStr(ReplaceStr(Lines.LineBreak, #13, '\r'), #10, '\n'), APattern) > 0) then
FEngine := eTextRegExpr
else
FEngine := eLinesRegExpr;
FBackwards := ABackwards;
if (FCaseSensitive or (FEngine <> eNormal)) then
FPattern := APattern
else
begin
// Since we modify FPattern with CharLowerBuff, we need a copy of the
// string - not only a copy of the pointer to the string...
FPattern := Copy(APattern, 1, Length(APattern));
CharLowerBuff(PChar(FPattern), Length(FPattern));
end;
FReplaceText := AReplaceText;
if (FEngine = eNormal) then
begin
if (FWholeWords) then
for LIndex := 1 to Length(FPattern) do
if (FLines.IsWordBreakChar(FPattern[LIndex])) then
begin
FErrorMessage := SBCEditorPatternContainsWordBreakChar;
FPattern := '';
break;
end;
end
else
begin
FRegExOptions := [roSingleLine, roCompiled];
{$if CompilerVersion > 26}
Include(FRegExOptions, roNotEmpty);
{$endif}
if (FCaseSensitive) then
Exclude(FRegExOptions, roIgnoreCase)
else
Include(FRegExOptions, roIgnoreCase);
FRegEx := TRegEx.Create(FPattern, FRegExOptions);
end;
end;
function TBCEditorLines.TSearch.Find(var APosition: TBCEditorLinesPosition;
out AFoundLength: Integer): Boolean;
begin
Assert((FArea.BeginPosition <= APosition) and (APosition <= FArea.EndPosition));
case (FEngine) of
eNormal: Result := FindNormal(APosition, AFoundLength);
eLinesRegExpr: Result := FindLinesRegEx(APosition, AFoundLength);
eTextRegExpr: Result := FindTextRegEx(APosition, AFoundLength);
else raise ERangeError.Create('FEngine: ' + IntToStr(Ord(FEngine)));
end;
if (FBackwards) then
Result := Result and (FFoundPosition >= FArea.BeginPosition)
else
Result := Result and (FFoundPosition <= FArea.EndPosition);
if (Result) then
begin
APosition := FFoundPosition;
AFoundLength := FFoundLength;
end;
end;
function TBCEditorLines.TSearch.FindLinesRegEx(const APosition: TBCEditorLinesPosition;
const AFoundLength: Integer): Boolean;
var
LMatch: TMatch;
begin
FFoundPosition := APosition;
Result := False;
if (FBackwards) then
while (not Result and (FFoundPosition.Line >= 0)) do
begin
try
LMatch := FRegEx.Match(FLines[FFoundPosition.Line]);
except
on E: Exception do
FErrorMessage := E.Message;
end;
Result := (FErrorMessage = '') and LMatch.Success and (LMatch.Index - 1 < FFoundPosition.Char);
while (Result and LMatch.Success) do
begin
FFoundPosition.Char := LMatch.Index - 1;
LMatch := LMatch.NextMatch();
end;
if (not Result) then
if (FFoundPosition.Line = 0) then
FFoundPosition := LinesPosition(0, -1)
else
FFoundPosition := FLines.EOLPosition[FFoundPosition.Line - 1];
end
else
while (not Result and (FFoundPosition.Line < FLines.Count)) do
begin
try
LMatch := FRegEx.Match(FLines[FFoundPosition.Line]);
while (LMatch.Success and (LMatch.Index - 1 < FFoundPosition.Char)) do
LMatch := LMatch.NextMatch();
except
on E: Exception do
FErrorMessage := E.Message;
end;
Result := (FErrorMessage = '') and LMatch.Success;
if (Result) then
FFoundPosition.Char := LMatch.Index - 1
else
FFoundPosition := FLines.BOLPosition[FFoundPosition.Line + 1];
end;
if (Result) then
FFoundLength := LMatch.Length;
end;
function TBCEditorLines.TSearch.FindNormal(const APosition: TBCEditorLinesPosition;
const AFoundLength: Integer): Boolean;
var
LLineLength: Integer;
LLinePos: PChar;
LLineText: string;
LPatternEndPos: PChar;
LPatternLength: Integer;
LPatternPos: PChar;
begin
LPatternLength := Length(FPattern);
if (LPatternLength = 0) then
Result := False
else
begin
Result := False;
FFoundPosition := APosition;
while (not Result
and (FBackwards and (FFoundPosition >= FLines.BOFPosition)
or not FBackwards and (FFoundPosition <= FLines.EOFPosition))) do
begin
LLineLength := Length(FLines.Items[FFoundPosition.Line].Text);
if (LLineLength > 0) then
begin
if (FCaseSensitive) then
LLineText := FLines.Items[FFoundPosition.Line].Text
else
begin
// Since we modify LLineText with CharLowerBuff, we need a copy of the
// string - not only a copy of the pointer to the string...
LLineText := Copy(FLines.Items[FFoundPosition.Line].Text, 1, LLineLength);
CharLowerBuff(PChar(LLineText), Length(LLineText));
end;
if (FBackwards and (FFoundPosition.Char = Length(LLineText))) then
Dec(FFoundPosition.Char);
while (not Result
and (FBackwards and (FFoundPosition.Char >= 0)
or not FBackwards and (FFoundPosition.Char + LPatternLength <= LLineLength))) do
begin
LLinePos := @LLineText[1 + FFoundPosition.Char];
if (not FWholeWords or not FLines.IsWordBreakChar(LLinePos^)) then
begin
LPatternPos := @FPattern[1];
LPatternEndPos := @FPattern[LPatternLength];
while ((LPatternPos <= LPatternEndPos)
and (LPatternPos^ = LLinePos^)) do
begin
Inc(LPatternPos);
Inc(LLinePos);
end;
Result := LPatternPos > LPatternEndPos;
end;
if (not Result) then
if (FBackwards) then
Dec(FFoundPosition.Char)
else
Inc(FFoundPosition.Char);
end;
end;
if (not Result) then
if (FBackwards) then
begin
if (FFoundPosition.Line = 0) then
FFoundPosition := LinesPosition(0, -1)
else
FFoundPosition := FLines.EOLPosition[FFoundPosition.Line - 1];
end
else
FFoundPosition := FLines.BOLPosition[FFoundPosition.Line + 1];
end;
if (Result) then
FFoundLength := LPatternLength;
end;
end;
function TBCEditorLines.TSearch.FindTextRegEx(const APosition: TBCEditorLinesPosition;
const AFoundLength: Integer): Boolean;
var
LFoundPosition: Integer;
LInput: string;
LMatch: TMatch;
begin
FFoundPosition := APosition;
LInput := Lines.Text;
LFoundPosition := Lines.CharIndexOf(FFoundPosition);
if (FBackwards) then
begin
try
LMatch := FRegEx.Match(LInput);
except
on E: Exception do
FErrorMessage := E.Message;
end;
Result := (FErrorMessage = '') and LMatch.Success and (LMatch.Index - 1 < LFoundPosition);
while (Result and LMatch.Success) do
begin
LFoundPosition := LMatch.Index - 1;
LMatch := LMatch.NextMatch();
end;
end
else
begin
try
LMatch := FRegEx.Match(LInput);
while (LMatch.Success and (LMatch.Index - 1 < LFoundPosition)) do
LMatch := LMatch.NextMatch();
except
on E: Exception do
FErrorMessage := E.Message;
end;
Result := (FErrorMessage = '') and LMatch.Success;
if (Result) then
LFoundPosition := LMatch.Index - 1
else
LFoundPosition := Length(LInput);
end;
if (Result) then
begin
FFoundPosition := Lines.PositionOf(LFoundPosition);
FFoundLength := LMatch.Length;
end;
end;
procedure TBCEditorLines.TSearch.Replace();
var
LEndPosition: TBCEditorLinesPosition;
begin
Assert((BOFPosition <= FFoundPosition) and (FFoundPosition <= FLines.EOFPosition));
LEndPosition := FLines.PositionOf(FFoundLength, FFoundPosition);
if (FEngine = eNormal) then
FLines.ReplaceText(LinesArea(FFoundPosition, LEndPosition), FReplaceText)
else if (FEngine = eLinesRegExpr) then
Assert(False)
else
FLines.ReplaceText(LinesArea(FFoundPosition, LEndPosition), FRegEx.Replace(FLines.TextIn[LinesArea(FFoundPosition, LEndPosition)], FPattern, FReplaceText, FRegExOptions));
end;
{ TBCEditorLines.TUndoList ****************************************************}
function TBCEditorLines.TUndoItem.ToString(): string;
begin
Result :=
'BlockNumber: ' + IntToStr(BlockNumber) + #13#10
+ 'UndoType: ' + IntToStr(Ord(UndoType)) + #13#10
+ 'CaretPosition: ' + CaretPosition.ToString() + #13#10
+ 'SelArea: ' + SelArea.ToString() + #13#10
+ 'Area: ' + Area.ToString() + #13#10
+ 'Text: ' + Text;
end;
{ TBCEditorLines.TUndoList ****************************************************}
procedure TBCEditorLines.TUndoList.BeginUpdate();
begin
if (UpdateCount = 0) then
begin
Inc(FBlockNumber);
FChanges := 0;
FCurrentBlockNumber := FBlockNumber;
end;
Inc(FUpdateCount);
end;
procedure TBCEditorLines.TUndoList.Clear();
begin
inherited;
FBlockNumber := 0;
FGroupBreak := False;
end;
constructor TBCEditorLines.TUndoList.Create(const ALines: TBCEditorLines);
begin
inherited Create();
FLines := ALines;
FBlockNumber := 0;
FUpdateCount := 0;
end;
procedure TBCEditorLines.TUndoList.EndUpdate();
begin
if (FUpdateCount > 0) then
begin
Dec(FUpdateCount);
if (FUpdateCount = 0) then
begin
FChanges := 0;
FCurrentBlockNumber := 0;
end;
end;
end;
function TBCEditorLines.TUndoList.GetUpdated(): Boolean;
begin
Result := (FUpdateCount > 0) and (FChanges > 0);
end;
procedure TBCEditorLines.TUndoList.GroupBreak();
begin
FGroupBreak := True;
end;
function TBCEditorLines.TUndoList.Peek(): TUndoItem;
begin
Assert(Count > 0);
Result := List[Count - 1];
end;
function TBCEditorLines.TUndoList.Pop(): TUndoItem;
begin
Result := Peek();
Delete(Count - 1);
end;
procedure TBCEditorLines.TUndoList.Push(const AUndoType: TUndoItem.TType;
const ACaretPosition: TBCEditorLinesPosition; const ASelArea: TBCEditorLinesArea;
const AArea: TBCEditorLinesArea; const AText: string = '';
const ABlockNumber: Integer = 0);
var
LHandled: Boolean;
LItem: TUndoItem;
begin
if (not (lsLoading in Lines.State)) then
begin
LHandled := False;
if ((Lines.State * [lsUndo, lsRedo] = [])
and (loUndoGrouped in Lines.Options)
and not FGroupBreak
and (Count > 0) and (List[Count - 1].UndoType = AUndoType)) then
case (AUndoType) of
utSelection: LHandled := True; // Ignore
utInsert:
if (List[Count - 1].Area.EndPosition = AArea.BeginPosition) then
begin
List[Count - 1].Area.EndPosition := AArea.EndPosition;
LHandled := True;
end;
utReplace:
if (List[Count - 1].Area.EndPosition = AArea.BeginPosition) then
begin
List[Count - 1].Area.EndPosition := AArea.EndPosition;
List[Count - 1].Text := List[Count - 1].Text + AText;
LHandled := True;
end;
utBackspace:
if (List[Count - 1].Area.BeginPosition = AArea.EndPosition) then
begin
List[Count - 1].Area.BeginPosition := AArea.BeginPosition;
List[Count - 1].Text := AText + List[Count - 1].Text;
LHandled := True;
end;
utDelete:
if (List[Count - 1].Area.EndPosition = AArea.BeginPosition) then
begin
List[Count - 1].Area.EndPosition := AArea.EndPosition;
List[Count - 1].Text := List[Count - 1].Text + AText;
LHandled := True;
end;
end;
if (not LHandled) then
begin
if (ABlockNumber > 0) then
LItem.BlockNumber := ABlockNumber
else if (FCurrentBlockNumber > 0) then
LItem.BlockNumber := FCurrentBlockNumber
else
begin
Inc(FBlockNumber);
LItem.BlockNumber := FBlockNumber;
end;
LItem.Area := AArea;
LItem.CaretPosition := ACaretPosition;
LItem.SelArea := ASelArea;
LItem.Text := AText;
LItem.UndoType := AUndoType;
Add(LItem);
end;
if (UpdateCount > 0) then
Inc(FChanges);
FGroupBreak := False;
end;
end;
{ TBCEditorLines **************************************************************}
function CompareLines(ALines: TBCEditorLines; AIndex1, AIndex2: Integer): Integer;
begin
Result := ALines.CompareStrings(ALines.Items[AIndex1].Text, ALines.Items[AIndex2].Text);
if (ALines.SortOrder = soDesc) then
Result := - Result;
end;
function TBCEditorLines.Add(const AText: string): Integer;
begin
Result := Count;
Insert(Count, AText);
end;
procedure TBCEditorLines.Backspace(AArea: TBCEditorLinesArea);
var
LCaretPosition: TBCEditorLinesPosition;
LSelArea: TBCEditorLinesArea;
LText: string;
begin
Assert((BOFPosition <= AArea.BeginPosition) and (AArea.BeginPosition < AArea.EndPosition) and (AArea.EndPosition <= EOFPosition));
LCaretPosition := CaretPosition;
LSelArea := SelArea;
LText := TextIn[AArea];
BeginUpdate();
try
DoDeleteText(AArea);
UndoList.Push(utBackspace, LCaretPosition, LSelArea,
AArea, LText);
finally
EndUpdate();
end;
CaretPosition := AArea.BeginPosition;
end;
procedure TBCEditorLines.Clear();
begin
InternalClear(True);
end;
procedure TBCEditorLines.ClearUndo();
begin
UndoList.Clear();
RedoList.Clear();
end;
function TBCEditorLines.CompareStrings(const S1, S2: string): Integer;
begin
if CaseSensitive then
Result := CompareStr(S1, S2)
else
Result := CompareText(S1, S2);
if SortOrder = soDesc then
Result := -1 * Result;
end;
constructor TBCEditorLines.Create(const AEditor: TCustomControl);
begin
inherited Create();
FEditor := AEditor;
FCaretPosition := BOFPosition;
FCaseSensitive := False;
FItems := TItems.Create();
FModified := False;
FOnAfterUpdate := nil;
FOnBeforeUpdate := nil;
FOnCaretMoved := nil;
FOnCleared := nil;
FOnDeleted := nil;
FOnDeleting := nil;
FOnInserted := nil;
FOnSelChange := nil;
FOnUpdated := nil;
FOptions := DefaultOptions;
FRedoList := TUndoList.Create(Self);
FReadOnly := False;
FSelArea.BeginPosition := BOFPosition;
FSelArea.EndPosition := BOFPosition;
FState := [];
FUndoList := TUndoList.Create(Self);
end;
procedure TBCEditorLines.CustomSort(const ABeginLine, AEndLine: Integer;
ACompare: TCompare);
var
LArea: TBCEditorLinesArea;
LText: string;
begin
BeginUpdate();
BeginUpdate();
try
if (AEndLine < Count - 1) then
LArea := LinesArea(BOLPosition[ABeginLine], BOLPosition[ABeginLine + 1])
else
LArea := LinesArea(BOLPosition[ABeginLine], LinesPosition(Length(Items[AEndLine].Text), AEndLine));
LText := TextIn[LArea];
UndoList.Push(utDelete, CaretPosition, SelArea,
LinesArea(LArea.BeginPosition, InvalidLinesPosition), LText);
QuickSort(ABeginLine, AEndLine, ACompare);
UndoList.Push(utInsert, InvalidLinesPosition, InvalidLinesArea,
LArea);
finally
EndUpdate();
EndUpdate();
RedoList.Clear();
end;
end;
procedure TBCEditorLines.Delete(ALine: Integer);
var
LBeginPosition: TBCEditorLinesPosition;
LCaretPosition: TBCEditorLinesPosition;
LSelArea: TBCEditorLinesArea;
LText: string;
LUndoType: TUndoItem.TType;
begin
Assert((0 <= ALine) and (ALine < Count));
LCaretPosition := CaretPosition;
LSelArea := SelArea;
if (Count = 1) then
begin
LBeginPosition := BOLPosition[ALine];
LText := Items[ALine].Text;
LUndoType := utClear;
end
else if (ALine < Count - 1) then
begin
LBeginPosition := BOLPosition[ALine];
LText := Items[ALine].Text + LineBreak;
LUndoType := utDelete;
end
else
begin
LBeginPosition := EOLPosition[ALine - 1];
LText := LineBreak + Items[ALine].Text;
LUndoType := utDelete;
end;
BeginUpdate();
try
DoDelete(ALine);
UndoList.Push(LUndoType, LCaretPosition, LSelArea,
LinesArea(LBeginPosition, InvalidLinesPosition), LText);
finally
EndUpdate();
end;
end;
procedure TBCEditorLines.DeleteIndent(ABeginPosition, AEndPosition: TBCEditorLinesPosition;
const AIndentText: string);
var
LArea: TBCEditorLinesArea;
LCaretPosition: TBCEditorLinesPosition;
LLine: Integer;
LIndentFound: Boolean;
LIndentTextLength: Integer;
LSelArea: TBCEditorLinesArea;
begin
LArea := LinesArea(Min(ABeginPosition, AEndPosition), Max(ABeginPosition, AEndPosition));
Assert((BOFPosition <= LArea.BeginPosition) and (LArea.EndPosition <= EOFPosition));
LIndentTextLength := Length(AIndentText);
LIndentFound := LArea.BeginPosition.Line <> LArea.EndPosition.Line;
for LLine := LArea.BeginPosition.Line to LArea.EndPosition.Line do
if (Copy(Items[LLine].Text, 1 + LArea.BeginPosition.Char, LIndentTextLength) <> AIndentText) then
begin
LIndentFound := False;
break;
end;
if (LIndentFound) then
begin
LCaretPosition := CaretPosition;
LSelArea := SelArea;
DoDeleteIndent(LArea.BeginPosition, LArea.EndPosition, AIndentText);
UndoList.Push(utDeleteIndent, LCaretPosition, LSelArea,
LArea, AIndentText);
RedoList.Clear();
end
else
begin
BeginUpdate();
try
for LLine := LArea.BeginPosition.Line to LArea.EndPosition.Line do
if (LeftStr(Items[LLine].Text, LIndentTextLength) = AIndentText) then
DeleteText(LinesArea(BOLPosition[LLine], LinesPosition(Length(AIndentText), LLine)));
finally
EndUpdate();
end;
end;
if ((ABeginPosition <= CaretPosition) and (CaretPosition <= AEndPosition)
and (CaretPosition.Char > Length(Items[CaretPosition.Line].Text))) then
FCaretPosition.Char := Length(Items[CaretPosition.Line].Text);
if (FSelArea.Containts(ABeginPosition) and FSelArea.Containts(AEndPosition))
and (CaretPosition.Char > Length(Items[FSelArea.BeginPosition.Line].Text)) then
FSelArea.BeginPosition.Char := Length(Items[SelArea.BeginPosition.Line].Text);
if ((ABeginPosition <= FSelArea.EndPosition) and (FSelArea.EndPosition <= AEndPosition)
and (FSelArea.EndPosition.Char > Length(Items[FSelArea.EndPosition.Line].Text))) then
FSelArea.EndPosition.Char := Length(Items[SelArea.EndPosition.Line].Text);
end;
procedure TBCEditorLines.DeleteText(AArea: TBCEditorLinesArea);
var
LCaretPosition: TBCEditorLinesPosition;
LInsertArea: TBCEditorLinesArea;
LSelArea: TBCEditorLinesArea;
LText: string;
begin
BeginUpdate();
try
if (AArea.IsEmpty()) then
// Do nothing
else
begin
LCaretPosition := CaretPosition;
LSelArea := SelArea;
if (AArea.BeginPosition.Char > Length(Items[AArea.BeginPosition.Line].Text)) then
begin
LInsertArea.BeginPosition := EOLPosition[AArea.BeginPosition.Line];
LInsertArea.EndPosition := DoInsertText(LInsertArea.BeginPosition, StringOfChar(BCEDITOR_SPACE_CHAR, AArea.BeginPosition.Char - LInsertArea.BeginPosition.Char));
UndoList.Push(utInsert, LCaretPosition, LSelArea,
LInsertArea);
Assert(LInsertArea.EndPosition = AArea.BeginPosition);
end;
LText := TextIn[AArea];
DoDeleteText(AArea);
UndoList.Push(utDelete, LCaretPosition, LSelArea,
LinesArea(AArea.BeginPosition, InvalidLinesPosition), LText);
end;
CaretPosition := AArea.BeginPosition;
finally
EndUpdate();
end;
RedoList.Clear();
end;
destructor TBCEditorLines.Destroy;
begin
FItems.Free();
FRedoList.Free();
FUndoList.Free();
inherited;
end;
procedure TBCEditorLines.DoDelete(ALine: Integer);
begin
Assert((0 <= ALine) and (ALine < Count));
if (Assigned(OnDeleting)) then
OnDeleting(Self, ALine);
Items.Delete(ALine);
if (Count = 0) then
CaretPosition := BOFPosition
else if (ALine < Count) then
CaretPosition := BOLPosition[ALine]
else
CaretPosition := EOLPosition[ALine - 1];
if (UpdateCount > 0) then
Include(FState, lsTextChanged);
if ((Count = 0) and Assigned(OnCleared)) then
OnCleared(Self)
else if (Assigned(OnDeleted)) then
OnDeleted(Self, ALine);
end;
procedure TBCEditorLines.DoDeleteIndent(ABeginPosition, AEndPosition: TBCEditorLinesPosition;
const AIndentText: string);
var
LLine: Integer;
LLinesBeginPosition: TBCEditorLinesPosition;
LLinesEndPosition: TBCEditorLinesPosition;
begin
Assert((BOFPosition <= ABeginPosition) and (AEndPosition <= EOFPosition));
Assert(ABeginPosition <= AEndPosition);
if (Count > 0) then
begin
LLinesBeginPosition := BOLPosition[ABeginPosition.Line];
if (ABeginPosition = AEndPosition) then
LLinesEndPosition := EOLPosition[AEndPosition.Line]
else if ((AEndPosition.Char = 0) and (AEndPosition.Line > ABeginPosition.Line)) then
LLinesEndPosition := EOLPosition[AEndPosition.Line - 1]
else
LLinesEndPosition := AEndPosition;
BeginUpdate();
try
for LLine := LLinesBeginPosition.Line to LLinesEndPosition.Line do
if (LeftStr(Items[LLine].Text, Length(AIndentText)) = AIndentText) then
DoPut(LLine, Copy(Items[LLine].Text, 1 + Length(AIndentText), MaxInt));
finally
EndUpdate();
end;
end;
end;
procedure TBCEditorLines.DoDeleteText(const AArea: TBCEditorLinesArea);
var
Line: Integer;
begin
Assert((BOFPosition <= AArea.BeginPosition) and (AArea.EndPosition <= EOFPosition));
Assert(AArea.BeginPosition <= AArea.EndPosition);
if (AArea.IsEmpty()) then
// Nothing to do...
else if (AArea.BeginPosition.Line = AArea.EndPosition.Line) then
DoPut(AArea.BeginPosition.Line, LeftStr(Items[AArea.BeginPosition.Line].Text, AArea.BeginPosition.Char)
+ Copy(Items[AArea.EndPosition.Line].Text, 1 + AArea.EndPosition.Char, MaxInt))
else
begin
BeginUpdate();
try
DoPut(AArea.BeginPosition.Line, LeftStr(Items[AArea.BeginPosition.Line].Text, AArea.BeginPosition.Char)
+ Copy(Items[AArea.EndPosition.Line].Text, 1 + AArea.EndPosition.Char, MaxInt));
for Line := AArea.EndPosition.Line downto AArea.BeginPosition.Line + 1 do
DoDelete(Line);
finally
EndUpdate();
end;
end;
end;
procedure TBCEditorLines.DoInsertIndent(const AArea: TBCEditorLinesArea;
const AIndentText: string);
var
LEndLine: Integer;
LLine: Integer;
begin
Assert((BOFPosition <= AArea.BeginPosition) and (AArea.EndPosition <= EOFPosition));
Assert(AArea.BeginPosition <= AArea.EndPosition);
if (Count > 0) then
begin
if ((AArea.EndPosition.Char = 0) and (AArea.EndPosition.Line > AArea.BeginPosition.Line)) then
LEndLine := AArea.EndPosition.Line - 1
else
LEndLine := AArea.EndPosition.Line;
BeginUpdate();
try
for LLine := AArea.BeginPosition.Line to LEndLine do
DoPut(LLine, AIndentText + Items[LLine].Text);
finally
EndUpdate();
end;
end;
end;
procedure TBCEditorLines.DoInsert(ALine: Integer; const AText: string);
var
LLine: TLine;
begin
Assert((0 <= ALine) and (ALine <= Count));
BeginUpdate();
try
LLine.Background := clNone;
LLine.CodeFolding.BeginRange := nil;
LLine.CodeFolding.EndRange := nil;
LLine.CodeFolding.TreeLine := False;
LLine.Flags := [];
LLine.FirstRow := -1;
LLine.Foreground := clNone;
LLine.Range := nil;
LLine.State := lsModified;
LLine.Text := '';
Items.Insert(ALine, LLine);
Include(FState, lsInserting);
try
DoPut(ALine, AText);
finally
Exclude(FState, lsInserting);
end;
if (ALine < Count - 1) then
CaretPosition := BOLPosition[ALine + 1]
else
CaretPosition := EOLPosition[ALine];
SelArea := LinesArea(CaretPosition, CaretPosition);
if (UpdateCount > 0) then
Include(FState, lsTextChanged);
if (Assigned(OnInserted)) then
OnInserted(Self, ALine);
finally
EndUpdate();
end;
end;
function TBCEditorLines.DoInsertText(APosition: TBCEditorLinesPosition;
const AText: string): TBCEditorLinesPosition;
var
LEndPos: PChar;
LEOL: Boolean;
LLine: Integer;
LLineBeginPos: PChar;
LLineBreak: array [0..2] of System.Char;
LLineEnd: string;
LPos: PChar;
begin
Assert(BOFPosition <= APosition);
Assert((APosition.Line = 0) and (Count = 0) or (APosition.Line < Count) and (APosition.Char <= Length(Items[APosition.Line].Text)),
'APosition: ' + APosition.ToString() + #13#10
+ 'EOFPosition: ' + EOFPosition.ToString() + #13#10
+ 'Length: ' + IntToStr(Length(Items[APosition.Line].Text)));
if (AText = '') then
Result := APosition
else if (not HasLineBreak(AText)) then
begin
if (Count = 0) then
begin
DoInsert(0, AText);
Result := EOLPosition[0];
end
else
begin
DoPut(APosition.Line, LeftStr(Items[APosition.Line].Text, APosition.Char)
+ AText
+ Copy(Items[APosition.Line].Text, 1 + APosition.Char, MaxInt));
Result := LinesPosition(APosition.Char + Length(AText), APosition.Line);
end;
end
else
begin
LLineBreak[0] := #0; LLineBreak[1] := #0; LLineBreak[2] := #0;
BeginUpdate();
try
LLine := APosition.Line;
LPos := @AText[1];
LEndPos := @AText[Length(AText)];
LLineBeginPos := LPos;
while ((LPos <= LEndPos) and not CharInSet(LPos^, [BCEDITOR_LINEFEED, BCEDITOR_CARRIAGE_RETURN])) do
Inc(LPos);
if (Count = 0) then
begin
DoInsert(0, LeftStr(AText, LPos - LLineBeginPos));
LLine := 1;
end
else if (LLine < Count) then
begin
if (APosition.Char = 0) then
begin
LLineEnd := Items[LLine].Text;
if (LLineBeginPos < LPos) then
DoPut(LLine, LeftStr(AText, LPos - LLineBeginPos))
else if (Items[LLine].Text <> '') then
DoPut(LLine, '');
end
else
begin
LLineEnd := Copy(Items[LLine].Text, 1 + APosition.Char, MaxInt);
if (LLineBeginPos < LPos) then
DoPut(LLine, LeftStr(Items[LLine].Text, APosition.Char) + LeftStr(AText, LPos - LLineBeginPos))
else if (Length(Items[LLine].Text) > APosition.Char) then
DoPut(LLine, LeftStr(Items[LLine].Text, APosition.Char));
end;
Inc(LLine);
end
else
begin
DoInsert(LLine, LeftStr(AText, LPos - LLineBeginPos));
Inc(LLine);
end;
if (LPos <= LEndPos) then
begin
LLineBreak[0] := LPos^;
if ((LLineBreak[0] = BCEDITOR_CARRIAGE_RETURN) and (LPos < LEndPos) and (LPos[1] = BCEDITOR_LINEFEED)) then
LLineBreak[1] := LPos[1];
end;
LEOL := (LPos <= LEndPos) and (LPos[0] = LLineBreak[0]) and ((LLineBreak[1] = #0) or (LPos < LEndPos) and (LPos[1] = LLineBreak[1]));
while (LEOL) do
begin
if (LLineBreak[1] = #0) then
Inc(LPos)
else
Inc(LPos, 2);
LLineBeginPos := LPos;
repeat
LEOL := (LPos <= LEndPos) and (LPos[0] = LLineBreak[0]) and ((LLineBreak[1] = #0) or (LPos < LEndPos) and (LPos[1] = LLineBreak[1]));
if (not LEOL) then
Inc(LPos);
until ((LPos > LEndPos) or LEOL);
if (LEOL) then
begin
DoInsert(LLine, Copy(AText, 1 + LLineBeginPos - @AText[1], LPos - LLineBeginPos));
Inc(LLine);
end;
end;
if (LPos <= LEndPos) then
begin
DoInsert(LLine, Copy(AText, LPos - @AText[1], LEndPos + 1 - LPos) + LLineEnd);
Result := LinesPosition(LEndPos + 1 - (LLineBeginPos + 1), LLine);
end
else
begin
DoInsert(LLine, RightStr(AText, LEndPos + 1 - LLineBeginPos) + LLineEnd);
Result := LinesPosition(1 + LEndPos + 1 - (LLineBeginPos + 1), LLine);
end;
finally
EndUpdate();
if ((lsLoading in State) and (LLineBreak[0] <> #0)) then
LineBreak := StrPas(PChar(@LLineBreak[0]));
end;
end;
end;
procedure TBCEditorLines.DoPut(ALine: Integer; const AText: string);
var
LModified: Boolean;
LPos: PChar;
LEndPos: PChar;
begin
Assert((0 <= ALine) and (ALine < Count));
LModified := AText <> Items[ALine].Text;
if (LModified) then
begin
Items.List[ALine].Flags := [];
Items.List[ALine].State := lsModified;
Items.List[ALine].Text := AText;
if (AText <> '') then
begin
LPos := @AText[1];
LEndPos := @AText[Length(AText)];
while (LPos <= LEndPos) do
begin
if (LPos^ = BCEDITOR_TAB_CHAR) then
begin
Include(Items.List[ALine].Flags, lfHasTabs);
break;
end;
Inc(LPos);
end;
end;
end;
CaretPosition := EOLPosition[ALine];
if (LModified and not (lsInserting in State)) then
begin
if (UpdateCount > 0) then
Include(FState, lsTextChanged);
if (Assigned(OnUpdated)) then
OnUpdated(Self, ALine);
end;
end;
procedure TBCEditorLines.ExchangeItems(ALine1, ALine2: Integer);
var
LLine: TLine;
begin
LLine := Items[ALine1];
Items[ALine1] := Items[ALine2];
Items[ALine2] := LLine;
end;
var
Progress: string;
procedure TBCEditorLines.ExecuteUndoRedo(const List: TUndoList);
var
LPreviousBlockNumber: Integer;
LCaretPosition: TBCEditorLinesPosition;
LDestinationList: TUndoList;
LEndPosition: TBCEditorLinesPosition;
LSelArea: TBCEditorLinesArea;
LText: string;
LUndoItem: TUndoItem;
begin
if (not ReadOnly and (List.Count > 0)) then
begin
if (List = UndoList) then
begin
Include(FState, lsUndo);
LDestinationList := RedoList;
LUndoItem := List.Peek();
Progress := RightStr(Progress + '-U' + LUndoItem.BlockNumber.ToString(), 50);
end
else
begin
Include(FState, lsRedo);
LDestinationList := UndoList;
Progress := RightStr(Progress + '-R' + LUndoItem.BlockNumber.ToString(), 50);
end;
BeginUpdate();
LCaretPosition := CaretPosition;
LSelArea := SelArea;
repeat
LUndoItem := List.Pop();
case (LUndoItem.UndoType) of
utSelection:
begin
LDestinationList.Push(LUndoItem.UndoType, LCaretPosition, LSelArea,
LUndoItem.Area, LUndoItem.Text, LUndoItem.BlockNumber);
end;
utInsert,
utReplace,
utBackspace,
utDelete:
begin
if (not LUndoItem.Area.IsEmpty()
and ((LUndoItem.UndoType in [utReplace])
or ((LUndoItem.UndoType in [utBackspace, utDelete]) xor (List = UndoList)))) then
begin
// Debug 2017-05-03
try
LText := TextIn[LUndoItem.Area];
except
on E: Exception do
E.RaiseOuterException(Exception.Create(LUndoItem.ToString() + #13#10
+ 'Progress: ' + Progress + #13#10
+ 'LDestinationList.Count: ' + IntToStr(LDestinationList.Count) + #13#10
+ 'Area: ' + Area.ToString() + #13#10#13#10
+ E.ClassName + ':' + #13#10
+ E.Message));
end;
DoDeleteText(LUndoItem.Area);
if (not (LUndoItem.UndoType in [utReplace])) then
LDestinationList.Push(LUndoItem.UndoType, LCaretPosition, LSelArea,
LUndoItem.Area, LText, LUndoItem.BlockNumber);
end
else
LText := '';
if ((LUndoItem.UndoType in [utReplace])
or ((LUndoItem.UndoType in [utBackspace, utDelete]) xor (List <> UndoList))) then
begin
if (LUndoItem.Text = '') then
LEndPosition := LUndoItem.Area.BeginPosition
else
try
LEndPosition := DoInsertText(LUndoItem.Area.BeginPosition, LUndoItem.Text);
except
on E: Exception do
E.RaiseOuterException(EAssertionFailed.Create(LUndoItem.ToString() + #13#10
+ 'Progress: ' + Progress + #13#10#13#10
+ E.ClassName + ':' + #13#10
+ E.Message));
end;
LDestinationList.Push(LUndoItem.UndoType, LCaretPosition, LSelArea,
LinesArea(LUndoItem.Area.BeginPosition, LEndPosition), LText, LUndoItem.BlockNumber);
end;
end;
utClear:
if (List = RedoList) then
begin
LText := Text;
InternalClear(False);
LDestinationList.Push(LUndoItem.UndoType, LCaretPosition, LSelArea,
LinesArea(BOFPosition, InvalidLinesPosition), LText, LUndoItem.BlockNumber);
end
else
begin
LEndPosition := DoInsertText(LUndoItem.Area.BeginPosition, LUndoItem.Text);
LDestinationList.Push(LUndoItem.UndoType, LCaretPosition, LSelArea,
LinesArea(LUndoItem.Area.BeginPosition, LEndPosition), '', LUndoItem.BlockNumber);
end;
utInsertIndent,
utDeleteIndent:
begin
if ((LUndoItem.UndoType <> utInsertIndent) xor (List = UndoList)) then
DoDeleteIndent(LUndoItem.Area.BeginPosition, LUndoItem.Area.EndPosition,
LUndoItem.Text)
else
DoInsertIndent(LUndoItem.Area, LUndoItem.Text);
LDestinationList.Push(LUndoItem.UndoType, LCaretPosition, LSelArea,
LUndoItem.Area, LUndoItem.Text, LUndoItem.BlockNumber);
end;
else raise ERangeError.Create('UndoType: ' + IntToStr(Ord(LUndoItem.UndoType)));
end;
LCaretPosition := LUndoItem.CaretPosition;
LSelArea := LUndoItem.SelArea;
LPreviousBlockNumber := LUndoItem.BlockNumber;
if (List.Count > 0) then
LUndoItem := List.Peek();
until ((List.Count = 0)
or (LUndoItem.BlockNumber <> LPreviousBlockNumber));
CaretPosition := LCaretPosition;
SelArea := LSelArea;
EndUpdate();
if (List = UndoList) then
Exclude(FState, lsUndo)
else
Exclude(FState, lsRedo);
end;
end;
function TBCEditorLines.Get(ALine: Integer): string;
begin
Assert((0 <= ALine) and (ALine < Count));
Result := Items[ALine].Text;
end;
function TBCEditorLines.GetArea(): TBCEditorLinesArea;
begin
Result := LinesArea(BOFPosition, EOFPosition);
end;
function TBCEditorLines.GetBOLPosition(ALine: Integer): TBCEditorLinesPosition;
begin
Result := LinesPosition(0, ALine);
end;
function TBCEditorLines.GetCanRedo(): Boolean;
begin
Result := RedoList.Count > 0;
end;
function TBCEditorLines.GetCanUndo(): Boolean;
begin
Result := UndoList.Count > 0;
end;
function TBCEditorLines.GetChar(APosition: TBCEditorLinesPosition): Char;
begin
Assert((0 <= APosition.Line) and (APosition.Line < Items.Count));
Assert((0 <= APosition.Char) and (APosition.Char < Length(Items.List[APosition.Line].Text)));
Result := Items[APosition.Line].Text[1 + APosition.Char];
end;
function TBCEditorLines.GetCount(): Integer;
begin
Result := Items.Count;
end;
function TBCEditorLines.GetEOFPosition(): TBCEditorLinesPosition;
begin
if (Count = 0) then
Result := BOFPosition
else
Result := EOLPosition[Count - 1];
end;
function TBCEditorLines.GetEOLPosition(ALine: Integer): TBCEditorLinesPosition;
begin
Assert((0 <= ALine) and (ALine < Count));
Result := LinesPosition(Length(Items[ALine].Text), ALine)
end;
function TBCEditorLines.GetLineArea(ALine: Integer): TBCEditorLinesArea;
begin
Result := LinesArea(BOLPosition[ALine], EOLPosition[ALine]);
end;
function TBCEditorLines.GetTextIn(const AArea: TBCEditorLinesArea): string;
var
LEndChar: Integer;
LEndLine: Integer;
LLine: Integer;
StringBuilder: TStringBuilder;
begin
Assert((BOFPosition <= AArea.BeginPosition) and (AArea.EndPosition <= EOFPosition),
'BOFPosition: ' + BOFPosition.ToString() + #13#10
+ 'AArea: ' + AArea.ToString() + #13#10
+ 'EOFPosition: ' + EOFPosition.ToString());
Assert(AArea.BeginPosition <= AArea.EndPosition,
'AArea: ' + AArea.ToString() + #13#10
+ 'Length(' + IntToStr(AArea.BeginPosition.Line) + '):' + IntToStr(Length(Items[AArea.BeginPosition.Line].Text)) + #13#10
+ 'Length(' + IntToStr(AArea.EndPosition.Line) + '):' + IntToStr(Length(Items[AArea.EndPosition.Line].Text)));
if (Count = 0) then
begin
Assert((AArea.BeginPosition = BOFPosition) and AArea.IsEmpty());
Result := '';
end
else
begin
Assert(AArea.BeginPosition.Char <= Length(Items[AArea.BeginPosition.Line].Text),
'AArea.BeginPosition: ' + AArea.BeginPosition.ToString() + #13#10
+ 'Length: ' + IntToStr(Length(Items[AArea.EndPosition.Line].Text)));
Assert(AArea.EndPosition.Char <= Length(Items[AArea.EndPosition.Line].Text),
'AArea.EndPosition: ' + AArea.EndPosition.ToString() + #13#10
+ 'Length: ' + IntToStr(Length(Items[AArea.EndPosition.Line].Text)));
LEndLine := AArea.EndPosition.Line;
if ((loTrimTrailingLines in Options) and (lsSaving in State)) then
while ((LEndLine > 0)
and (Trim(Items[LEndLine].Text) = '')
and (Trim(Items[LEndLine - 1].Text) = '')) do
Dec(LEndLine);
if (AArea.IsEmpty()) then
Result := ''
else if (AArea.BeginPosition.Line = LEndLine) then
begin
if (LEndLine = AArea.EndPosition.Line) then
LEndChar := AArea.EndPosition.Char
else
LEndChar := Length(Items[LEndLine].Text);
if ((loTrimTrailingSpaces in Options) and (lsSaving in State)) then
while ((LEndChar > 0) and (Items[LEndLine].Text[1 + LEndChar - 1] = BCEDITOR_SPACE_CHAR)) do
Dec(LEndChar);
Result := Copy(Items[AArea.BeginPosition.Line].Text, 1 + AArea.BeginPosition.Char, LEndChar - AArea.BeginPosition.Char)
end
else
begin
StringBuilder := TStringBuilder.Create();
LEndChar := Length(Items[AArea.BeginPosition.Line].Text);
if ((loTrimTrailingSpaces in Options) and (lsSaving in State)) then
while ((LEndChar > AArea.BeginPosition.Char) and (Items[AArea.BeginPosition.Line].Text[1 + LEndChar - 1] = BCEDITOR_SPACE_CHAR)) do
Dec(LEndChar);
// Debug 2017-05-07
Assert(LEndChar - AArea.BeginPosition.Char >= 0,
'LEndChar: ' + IntToStr(LEndChar) + #13#10
+ 'ABeginPosition.Char: ' + IntToStr(AArea.BeginPosition.Char) + #13#10
+ 'Length: ' + IntToStr(Length(Items[AArea.BeginPosition.Line].Text)));
StringBuilder.Append(Items[AArea.BeginPosition.Line].Text, AArea.BeginPosition.Char, LEndChar - AArea.BeginPosition.Char);
for LLine := AArea.BeginPosition.Line + 1 to LEndLine - 1 do
begin
StringBuilder.Append(LineBreak);
LEndChar := Length(Items[LLine].Text);
if ((loTrimTrailingSpaces in Options) and (lsSaving in State)) then
while ((LEndChar > 0) and (Items[LLine].Text[1 + LEndChar - 1] = BCEDITOR_SPACE_CHAR)) do
Dec(LEndChar);
// Debug 2017-05-20
Assert((0 <= LLine) and (LLine < Items.Count),
'LLine: ' + IntToStr(LLine) + #13#10
+ 'Count: ' + IntToStr(Items.Count));
Assert((0 <= LEndChar) and (LEndChar <= Length(Items[LLine].Text)),
'LEndChar: ' + LEndChar.ToString() + #13#10
+ 'Length: ' + Length(Items[LLine].Text).ToString());
StringBuilder.Append(Items[LLine].Text, 0, LEndChar);
end;
if (LEndLine = AArea.EndPosition.Line) then
LEndChar := AArea.EndPosition.Char
else
LEndChar := Length(Items[LEndLine].Text);
if ((loTrimTrailingSpaces in Options) and (lsSaving in State) and (LEndChar = Length(Items[LEndLine].Text))) then
while ((LEndChar > 0) and (Items[LEndLine].Text[1 + LEndChar - 1] = BCEDITOR_SPACE_CHAR)) do
Dec(LEndChar);
if ((LEndChar > 0)
or not (loTrimTrailingSpaces in Options) or not (lsSaving in State) or (LEndChar <> Length(Items[LEndLine].Text))) then
begin
StringBuilder.Append(LineBreak);
StringBuilder.Append(Items[LEndLine].Text, 0, LEndChar);
end;
Result := StringBuilder.ToString();
StringBuilder.Free();
end;
end;
end;
function TBCEditorLines.GetTextLength(): Integer;
var
LLine: Integer;
LLineBreakLength: Integer;
begin
Result := 0;
LLineBreakLength := Length(LineBreak);
for LLine := 0 to Count - 2 do
begin
Inc(Result, Length(Items[LLine].Text));
Inc(Result, LLineBreakLength);
end;
if (Count > 0) then
Inc(Result, Length(Items[Count - 1].Text))
end;
function TBCEditorLines.GetTextStr: string;
begin
Include(FState, lsSaving);
try
Result := TextIn[LinesArea(BOFPosition, EOFPosition)];
finally
Exclude(FState, lsSaving);
end;
end;
function TBCEditorLines.CharIndexOf(const APosition: TBCEditorLinesPosition): Integer;
var
LLine: Integer;
LLineBreakLength: Integer;
begin
LLineBreakLength := Length(LineBreak);
Result := 0;
for LLine := 0 to APosition.Line - 1 do
begin
Inc(Result, Length(Items[LLine].Text));
Inc(Result, LLineBreakLength);
end;
Inc(Result, APosition.Char);
end;
procedure TBCEditorLines.Insert(ALine: Integer; const AText: string);
var
LCaretPosition: TBCEditorLinesPosition;
LSelArea: TBCEditorLinesArea;
begin
LCaretPosition := CaretPosition;
LSelArea := SelArea;
DoInsert(ALine, AText);
if (not (lsLoading in State)) then
begin
UndoList.Push(utInsert, LCaretPosition, LSelArea,
LinesArea(BOLPosition[ALine], LinesPosition(Length(AText), ALine)));
RedoList.Clear();
end;
end;
procedure TBCEditorLines.InsertIndent(ABeginPosition, AEndPosition: TBCEditorLinesPosition;
const AIndentText: string);
var
LArea: TBCEditorLinesArea;
LCaretPosition: TBCEditorLinesPosition;
LSelArea: TBCEditorLinesArea;
begin
LArea.BeginPosition := Min(ABeginPosition, AEndPosition);
LArea.EndPosition := Max(ABeginPosition, AEndPosition);
LCaretPosition := CaretPosition;
LSelArea := SelArea;
DoInsertIndent(LArea, AIndentText);
UndoList.Push(utInsertIndent, LCaretPosition, LSelArea,
LArea, AIndentText);
RedoList.Clear();
end;
function TBCEditorLines.InsertText(APosition: TBCEditorLinesPosition;
const AText: string): TBCEditorLinesPosition;
var
LCaretPosition: TBCEditorLinesPosition;
LIndex: Integer;
LPosition: TBCEditorLinesPosition;
LSelArea: TBCEditorLinesArea;
LText: string;
begin
BeginUpdate();
try
if (AText = '') then
Result := APosition
else
begin
LCaretPosition := CaretPosition;
LSelArea := SelArea;
if ((APosition.Line < Count) and (APosition.Char <= Length(Items[APosition.Line].Text))) then
begin
LPosition := APosition;
Result := DoInsertText(LPosition, AText);
end
else if (APosition.Line < Count) then
begin
LPosition := EOLPosition[APosition.Line];
Result := DoInsertText(LPosition, StringOfChar(BCEDITOR_SPACE_CHAR, APosition.Char - LPosition.Char) + AText);
end
else
begin
if (Count = 0) then
begin
LPosition := BOFPosition;
LText := '';
end
else
begin
LPosition := EOLPosition[Count - 1];
LText := LineBreak;
end;
for LIndex := Count to APosition.Line - 1 do
LText := LText + LineBreak;
LText := LText + StringOfChar(BCEDITOR_SPACE_CHAR, APosition.Char);
Result := DoInsertText(LPosition, LText + AText);
end;
UndoList.Push(utInsert, LCaretPosition, LSelArea,
LinesArea(LPosition, Result));
end;
CaretPosition := Result;
finally
EndUpdate();
RedoList.Clear();
end;
end;
procedure TBCEditorLines.InternalClear(const AClearUndo: Boolean);
begin
if (AClearUndo) then
ClearUndo();
Items.Clear();
LineBreak := BCEDITOR_CARRIAGE_RETURN + BCEDITOR_LINEFEED;
FCaretPosition := BOFPosition;
FSelArea := LinesArea(BOFPosition, BOFPosition);
if (Assigned(OnCleared)) then
OnCleared(Self);
end;
function TBCEditorLines.IsWordBreakChar(const AChar: Char): Boolean;
begin
Result := CharInSet(AChar,
[BCEDITOR_NONE_CHAR .. BCEDITOR_SPACE_CHAR]
+ BCEDITOR_WORD_BREAK_CHARACTERS
+ BCEDITOR_EXTRA_WORD_BREAK_CHARACTERS);
end;
function TBCEditorLines.PositionOf(const ACharIndex: Integer): TBCEditorLinesPosition;
begin
Result := PositionOf(ACharIndex, BOFPosition);
end;
function TBCEditorLines.PositionOf(const ACharIndex: Integer;
const ARelativePosition: TBCEditorLinesPosition): TBCEditorLinesPosition;
var
LLength: Integer;
LLineBreakLength: Integer;
begin
Assert((BOFPosition <= ARelativePosition) and (ARelativePosition <= EOFPosition));
if (Count = 0) then
begin
if (ACharIndex <> 0) then
raise ERangeError.CreateFmt(SCharIndexOutOfBounds, [ACharIndex]);
Result := BOFPosition;
end
else
begin
LLength := ACharIndex;
Result := ARelativePosition;
if ((0 <= Result.Char + LLength) and (Result.Char + LLength <= Length(Items[Result.Line].Text))) then
Inc(Result.Char, LLength)
else if (LLength < 0) then
begin
LLineBreakLength := Length(LineBreak);
Inc(LLength, Result.Char + LLineBreakLength);
Dec(Result.Line);
if ((0 <= LLength) and (LLength < LLineBreakLength)) then
LLength := 0
else
while ((Result.Line >= 0) and (LLength < LLineBreakLength)) do
begin
Inc(LLength, Length(Items[Result.Line].Text) + LLineBreakLength);
Dec(Result.Line);
end;
if (Result.Line < 0) then
Result := BOFPosition
else
begin
if (- LLength > Length(Items[Result.Line].Text)) then
raise ERangeError.CreateFmt(SCharIndexOutOfBounds, [ACharIndex]);
Result.Char := LLength + Length(Items[Result.Line].Text);
end;
end
else
begin
LLineBreakLength := Length(LineBreak);
Dec(LLength, (Length(Items[Result.Line].Text) - Result.Char) + LLineBreakLength);
Inc(Result.Line);
if (LLength < 0) then
LLength := 0;
while ((Result.Line < Count) and (LLength >= Length(Items[Result.Line].Text) + LLineBreakLength)) do
begin
Dec(LLength, Length(Items[Result.Line].Text) + LLineBreakLength);
Inc(Result.Line);
end;
Result.Char := LLength;
Result := Min(Result, EOFPosition);
end;
end;
end;
procedure TBCEditorLines.Put(ALine: Integer; const AText: string);
begin
Assert((0 <= ALine) and (ALine < Count));
ReplaceText(LinesArea(BOLPosition[ALine], EOLPosition[ALine]), AText);
end;
procedure TBCEditorLines.QuickSort(ALeft, ARight: Integer; ACompare: TCompare);
var
LLeft: Integer;
LMiddle: Integer;
LRight: Integer;
begin
repeat
LLeft := ALeft;
LRight := ARight;
LMiddle := (ALeft + ARight) shr 1;
repeat
while ACompare(Self, LLeft, LMiddle) < 0 do
Inc(LLeft);
while ACompare(Self, LRight, LMiddle) > 0 do
Dec(LRight);
if LLeft <= LRight then
begin
if LLeft <> LRight then
ExchangeItems(LLeft, LRight);
if LMiddle = LLeft then
LMiddle := LRight
else
if LMiddle = LRight then
LMiddle := LLeft;
Inc(LLeft);
Dec(LRight);
end;
until LLeft > LRight;
if ALeft < LRight then
QuickSort(ALeft, LRight, ACompare);
ALeft := LLeft;
until LLeft >= ARight;
end;
procedure TBCEditorLines.Redo();
begin
ExecuteUndoRedo(RedoList);
end;
function TBCEditorLines.ReplaceText(const AArea: TBCEditorLinesArea;
const AText: string): TBCEditorLinesPosition;
var
LCaretPosition: TBCEditorLinesPosition;
LSelArea: TBCEditorLinesArea;
LText: string;
begin
if (AArea.IsEmpty()) then
InsertText(AArea.BeginPosition, AText)
else
begin
BeginUpdate();
try
LCaretPosition := CaretPosition;
LSelArea := SelArea;
LText := TextIn[AArea];
DoDeleteText(AArea);
Result := DoInsertText(AArea.BeginPosition, AText);
// Debug 2017-05-08
Assert(Result.Char <= Length(Items[Result.Line].Text));
UndoList.Push(utReplace, LCaretPosition, LSelArea,
LinesArea(AArea.BeginPosition, Result), LText);
CaretPosition := Result;
finally
EndUpdate();
end;
end;
end;
procedure TBCEditorLines.SaveToStream(AStream: TStream; AEncoding: TEncoding);
begin
inherited;
if (not (loUndoAfterSave in Options)) then
begin
UndoList.Clear();
RedoList.Clear();
end;
end;
procedure TBCEditorLines.SetBackground(const ALine: Integer; const AValue: TColor);
begin
Assert((0 <= ALine) and (ALine < Count));
Items.List[ALine].Background := AValue;
end;
procedure TBCEditorLines.SetCaretPosition(const AValue: TBCEditorLinesPosition);
begin
Assert(BOFPosition <= AValue);
if (AValue <> FCaretPosition) then
begin
BeginUpdate();
FCaretPosition := AValue;
SelArea := LinesArea(Min(AValue, EOFPosition), Min(AValue, EOFPosition));
Include(FState, lsCaretMoved);
EndUpdate();
end
else
SelArea := LinesArea(AValue, AValue);
end;
procedure TBCEditorLines.SetCodeFoldingBeginRange(const ALine: Integer; const AValue: Pointer);
begin
Assert((0 <= ALine) and (ALine < Count));
Items.List[ALine].CodeFolding.BeginRange := AValue;
end;
procedure TBCEditorLines.SetCodeFoldingEndRange(const ALine: Integer; const AValue: Pointer);
begin
Assert((0 <= ALine) and (ALine < Count));
Items.List[ALine].CodeFolding.EndRange := AValue;
end;
procedure TBCEditorLines.SetCodeFoldingTreeLine(const ALine: Integer; const AValue: Boolean);
begin
Assert((0 <= ALine) and (ALine < Count));
Items.List[ALine].CodeFolding.TreeLine := AValue;
end;
procedure TBCEditorLines.SetFirstRow(const ALine: Integer; const AValue: Integer);
begin
Assert((0 <= ALine) and (ALine < Count));
Items.List[ALine].FirstRow := AValue;
end;
procedure TBCEditorLines.SetForeground(const ALine: Integer; const AValue: TColor);
begin
Assert((0 <= ALine) and (ALine < Count));
Items.List[ALine].Foreground := AValue;
end;
procedure TBCEditorLines.SetModified(const AValue: Boolean);
var
LLine: Integer;
begin
if (FModified <> AValue) then
begin
FModified := AValue;
if (not FModified) then
begin
UndoList.GroupBreak();
BeginUpdate();
for LLine := 0 to Count - 1 do
if (Items[LLine].State = lsModified) then
Items.List[LLine].State := lsSaved;
EndUpdate();
Editor.Invalidate();
end;
end;
end;
procedure TBCEditorLines.SetRange(const ALine: Integer; const AValue: Pointer);
begin
Assert((0 <= ALine) and (ALine < Count));
Items.List[ALine].Range := AValue;
end;
procedure TBCEditorLines.SetSelArea(AValue: TBCEditorLinesArea);
begin
if (AValue <> FSelArea) then
begin
BeginUpdate();
FSelArea.BeginPosition := AValue.BeginPosition;
if (FSelArea.BeginPosition.Line < Count) then
FSelArea.BeginPosition.Char := Min(FSelArea.BeginPosition.Char, Length(Items[FSelArea.BeginPosition.Line].Text))
else
FSelArea.BeginPosition := EOFPosition;
FSelArea.EndPosition := AValue.EndPosition;
if (FSelArea.EndPosition.Line < Count) then
FSelArea.EndPosition.Char := Min(FSelArea.EndPosition.Char, Length(Items[FSelArea.EndPosition.Line].Text))
else
FSelArea.EndPosition := EOFPosition;
Include(FState, lsSelChanged);
EndUpdate();
end;
end;
procedure TBCEditorLines.SetTextStr(const AValue: string);
var
LEndPosition: TBCEditorLinesPosition;
LLine: Integer;
LOldCaretPosition: TBCEditorLinesPosition;
LOldSelArea: TBCEditorLinesArea;
begin
LOldCaretPosition := CaretPosition;
LOldSelArea := SelArea;
Include(FState, lsLoading);
BeginUpdate();
if (loUndoAfterLoad in Options) then
DeleteText(LinesArea(BOFPosition, EOFPosition));
InternalClear(not (loUndoAfterLoad in Options));
LEndPosition := InsertText(BOFPosition, AValue);
for LLine := 0 to Count - 1 do
Items.List[LLine].State := lsLoaded;
if (loUndoAfterLoad in Options) then
begin
UndoList.Push(utInsert, BOFPosition, InvalidLinesArea,
LinesArea(BOFPosition, LEndPosition));
RedoList.Clear();
end;
CaretPosition := BOFPosition;
EndUpdate();
Exclude(FState, lsLoading);
end;
procedure TBCEditorLines.SetUpdateState(AUpdating: Boolean);
begin
if (AUpdating) then
begin
if (not (csReading in Editor.ComponentState) and Assigned(OnBeforeUpdate)) then
OnBeforeUpdate(Self);
UndoList.BeginUpdate();
FState := FState - [lsCaretMoved, lsSelChanged, lsTextChanged];
FOldUndoListCount := UndoList.Count;
FOldCaretPosition := CaretPosition;
FOldSelArea := SelArea;
end
else
begin
if (not (lsRedo in State) and ((lsCaretMoved in State) or (lsSelChanged in State)) and not UndoList.Updated) then
begin
if (not (lsUndo in State)) then
begin
if ((UndoList.Count = FOldUndoListCount)
and (CaretPosition <> FOldCaretPosition)
or (SelArea <> FOldSelArea)) then
UndoList.Push(utSelection, FOldCaretPosition, FOldSelArea,
InvalidLinesArea);
RedoList.Clear();
end;
end;
UndoList.EndUpdate();
if (Assigned(OnCaretMoved) and (lsCaretMoved in FState)) then
OnCaretMoved(Self);
if (Assigned(OnSelChange) and (lsSelChanged in FState)) then
OnSelChange(Self);
if (Assigned(OnAfterUpdate)) then
OnAfterUpdate(Self);
FState := FState - [lsCaretMoved, lsSelChanged, lsTextChanged];
end;
end;
procedure TBCEditorLines.Sort(const ABeginLine, AEndLine: Integer);
begin
CustomSort(ABeginLine, AEndLine, CompareLines);
end;
procedure TBCEditorLines.Undo();
begin
ExecuteUndoRedo(UndoList);
end;
procedure TBCEditorLines.UndoGroupBreak();
begin
if ((loUndoGrouped in Options) and CanUndo) then
UndoList.GroupBreak();
end;
function TBCEditorLines.ValidPosition(const APosition: TBCEditorLinesPosition): Boolean;
begin
Result := (0 <= APosition.Line) and (APosition.Line < Count)
and (0 <= APosition.Char) and (APosition.Char < Length(Items[APosition.Line].Text));
end;
end.
|
{-------------------------------------------------------------------------------
Copyright 2012 Ethea S.r.l.
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 Kitto.Ext.TreePanel;
{$I Kitto.Defines.inc}
interface
uses
ExtTree,
EF.Tree,
Kitto.Ext.Base, Kitto.Ext.Controller, Kitto.Metadata.Views, Kitto.Ext.Utils;
type
/// <summary>
/// A tree panel that can display a tree view with clickable nodes. Used
/// by the TreePanel controller.
/// </summary>
TKExtTreePanel = class(TExtTreeTreePanel)
private
FView: TKView;
FTreeViewRenderer: TKExtTreeViewRenderer;
FConfig: TEFNode;
procedure SetView(const AValue: TKView);
protected
procedure InitDefaults; override;
public
destructor Destroy; override;
property View: TKView read FView write SetView;
published
procedure DisplayView;
end;
TKExtTreePanelController = class(TKExtPanelControllerBase)
private
FTreePanel: TKExtTreePanel;
protected
procedure DoDisplay; override;
procedure InitDefaults; override;
end;
implementation
uses
SysUtils,
Ext,
EF.Localization,
Kitto.Ext.Session;
{ TKExtTreePanelController }
procedure TKExtTreePanelController.DoDisplay;
begin
inherited;
Title := _(View.DisplayLabel);
FTreePanel.FConfig := Config;
FTreePanel.View := View;
end;
procedure TKExtTreePanelController.InitDefaults;
begin
inherited;
Layout := lyFit;
FTreePanel := TKExtTreePanel.CreateAndAddTo(Items);
end;
{ TKExtTreePanel }
destructor TKExtTreePanel.Destroy;
begin
FreeAndNil(FTreeViewRenderer);
inherited;
end;
procedure TKExtTreePanel.InitDefaults;
begin
inherited;
Root := TExtTreeTreeNode.Create(Self);
RootVisible := False;
AutoScroll := True;
Border := False;
end;
procedure TKExtTreePanel.SetView(const AValue: TKView);
var
LViewNode: TEFNode;
LView: TKTreeView;
begin
Assert(Assigned(AValue));
FView := AValue;
if not Assigned(FTreeViewRenderer) then
begin
FTreeViewRenderer := TKExtTreeViewRenderer.Create;
FTreeViewrenderer.Session := Session;
end;
LViewNode := FConfig.GetNode('TreeView');
LView := Session.Config.Views.ViewByNode(LViewNode) as TKTreeView;
FTreeViewRenderer.RenderAsTree(LView, Root, Self, DisplayView);
end;
procedure TKExtTreePanel.DisplayView;
begin
Session.DisplayView(TKView(Session.QueryAsInteger['View']));
end;
initialization
TKExtControllerRegistry.Instance.RegisterClass('TreePanel', TKExtTreePanelController);
finalization
TKExtControllerRegistry.Instance.UnregisterClass('TreePanel');
end.
|
unit ChainsawFiler;
{
Interface to XML files in Log4D format (see log4d.dtd).
Written by Keith Wood (kbwood@iprimus.com.au)
Version 1.0 - 19 September 2003.
}
interface
uses
Classes, SysUtils, DBClient, Log4D, Log4DXML, ComObj, ActiveX, MSXML2_TLB;
{ Load a file in standard XML logging format into the dataset. }
procedure LoadFromFile(const DataSet: TCustomClientDataSet;
const FileName: string);
{ Save the contents of the dataset to a file in standard XML logging format. }
procedure SaveToFile(const DataSet: TCustomClientDataSet;
const FileName: string);
implementation
resourcestring
MessageFormat = '%s during load: %s at %d,%d in %s';
type
{ SAX handler for Log4D XML files. }
TLogFileHandler = class(TObject, IVBSAXContentHandler, IVBSAXErrorHandler)
private
FCurTag: string;
FDataSet: TCustomClientDataSet;
FElapsedTimeIndex: Integer;
FErrorClassIndex: Integer;
FErrorMsgIndex: Integer;
FLevelNameIndex: Integer;
FLevelValueIndex: Integer;
FLoggerIndex: Integer;
FMessageIndex: Integer;
FNDCIndex: Integer;
FThreadIdIndex: Integer;
FTimestampIndex: Integer;
FValue: WideString;
public
constructor Create(const DataSet: TCustomClientDataSet);
{ IVBSAXContentHandler }
procedure _Set_documentLocator(const Param1: IVBSAXLocator); safecall;
procedure startDocument; safecall;
procedure endDocument; safecall;
procedure startPrefixMapping(var strPrefix: WideString;
var strURI: WideString); safecall;
procedure endPrefixMapping(var strPrefix: WideString); safecall;
procedure startElement(var strNamespaceURI: WideString;
var strLocalName: WideString; var strQName: WideString;
const oAttributes: IVBSAXAttributes); safecall;
procedure endElement(var strNamespaceURI: WideString;
var strLocalName: WideString; var strQName: WideString); safecall;
procedure characters(var strChars: WideString); safecall;
procedure ignorableWhitespace(var strChars: WideString); safecall;
procedure processingInstruction(var strTarget: WideString;
var strData: WideString); safecall;
procedure skippedEntity(var strName: WideString); safecall;
{ IVBSAXErrorHandler }
procedure Error(const oLocator: IVBSAXLocator;
var strErrorMessage: WideString; nErrorCode: Integer); safecall;
procedure FatalError(const oLocator: IVBSAXLocator;
var strErrorMessage: WideString; nErrorCode: Integer); safecall;
procedure IgnorableWarning(const oLocator: IVBSAXLocator;
var strErrorMessage: WideString; nErrorCode: Integer); safecall;
{ IDispatch }
function GetTypeInfoCount(out Count: Integer): HResult; stdcall;
function GetTypeInfo(Index, LocaleID: Integer; out TypeInfo): HResult;
stdcall;
function GetIDsOfNames(const IID: TGUID; Names: Pointer;
NameCount, LocaleID: Integer; DispIDs: Pointer): HResult; stdcall;
function Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer;
Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult;
stdcall;
{ IUnknown }
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
end;
{ TLogFileHandler -------------------------------------------------------------}
{ Parse logging files in XML format and add details to dataset.
Sample XML:
<?xml version="1.0"?>
<!DOCTYPE log4d:eventSet SYSTEM "log4d.dtd">
<log4d:eventSet version="1.2"
xmlns:log4d="http://log4d.sourceforge.net/log4d">
<log4d:event logger="myapp.other" levelName="FATAL" levelValue="50000"
thread="1496" timestamp="20030919200503" elapsed="17685">
<log4d:message><![CDATA[Error in calculation]]></log4d:message>
<log4d:NDC><![CDATA[abc|def]]></log4d:NDC>
<log4d:exception class="EDivByZero">
<![CDATA[Floating point division by zero]]></log4d:exception>
</log4d:event>
</log4d:eventSet>
}
constructor TLogFileHandler.Create(const DataSet: TCustomClientDataSet);
begin
inherited Create;
FDataSet := DataSet;
end;
{ IVBSAXContentHandler --------------------------------------------------------}
procedure TLogFileHandler._Set_documentLocator(const Param1: IVBSAXLocator);
begin
// Do nothing
end;
{ Save text content for later use. }
procedure TLogFileHandler.characters(var strChars: WideString);
begin
FValue := FValue + strChars;
end;
procedure TLogFileHandler.endDocument;
begin
// Do nothing
end;
{ Add accumulated text to appropriate field. }
procedure TLogFileHandler.endElement(var strNamespaceURI, strLocalName,
strQName: WideString);
begin
if strQName = EventTag then
FDataSet.Post
else if strQName = ExceptionTag then
FDataSet.Fields[FErrorMsgIndex].AsString := FValue
else if strQName = MessageTag then
FDataSet.Fields[FErrorMsgIndex].AsString := FValue
else if strQName = NDCTag then
FDataSet.Fields[FNDCIndex].AsString := FValue;
FValue := '';
end;
procedure TLogFileHandler.endPrefixMapping(var strPrefix: WideString);
begin
// Do nothing
end;
procedure TLogFileHandler.ignorableWhitespace(var strChars: WideString);
begin
// Do nothing
end;
procedure TLogFileHandler.processingInstruction(var strTarget,
strData: WideString);
begin
// Do nothing
end;
procedure TLogFileHandler.skippedEntity(var strName: WideString);
begin
// Do nothing
end;
{ Initialisation. }
procedure TLogFileHandler.startDocument;
begin
FDataSet.EmptyDataSet;
FValue :='';
// Locate fields once only
FElapsedTimeIndex := FDataSet.FieldByName('ElapsedTime').Index;
FErrorClassIndex := FDataSet.FieldByName('ErrorClass').Index;
FErrorMsgIndex := FDataSet.FieldByName('ErrorMessage').Index;
FLevelNameIndex := FDataSet.FieldByName('LevelName').Index;
FLevelValueIndex := FDataSet.FieldByName('LevelValue').Index;
FLoggerIndex := FDataSet.FieldByName('LoggerName').Index;
FMessageIndex := FDataSet.FieldByName('Message').Index;
FNDCIndex := FDataSet.FieldByName('NDC').Index;
FThreadIdIndex := FDataSet.FieldByName('ThreadId').Index;
FTimestampIndex := FDataSet.FieldByName('Timestamp').Index;
end;
{ Create a record and/or load values from attributes. }
procedure TLogFileHandler.startElement(var strNamespaceURI, strLocalName,
strQName: WideString; const oAttributes: IVBSAXAttributes);
begin
FCurTag := strQName;
if strQName = EventTag then
begin
FDataSet.Append;
FDataSet.Fields[FLoggerIndex].AsString :=
oAttributes.getValueFromQName(LoggerAttr);
FDataSet.Fields[FLevelNameIndex].AsString :=
oAttributes.getValueFromQName(LevelNameAttr);
FDataSet.Fields[FLevelValueIndex].AsString :=
oAttributes.getValueFromQName(LevelValueAttr);
FDataSet.Fields[FThreadIdIndex].AsString :=
oAttributes.getValueFromQName(ThreadAttr);
FDataSet.Fields[FTimestampIndex].AsString :=
oAttributes.getValueFromQName(TimestampAttr);
FDataSet.Fields[FElapsedTimeIndex].AsString :=
oAttributes.getValueFromQName(ElapsedAttr);
end
else if strQName = ExceptionTag then
FDataSet.Fields[FErrorClassIndex].AsString :=
oAttributes.getValueFromQName(ClassAttr);
end;
procedure TLogFileHandler.startPrefixMapping(var strPrefix,
strURI: WideString);
begin
// Do nothing
end;
{ IVBSAXErrorHandler ----------------------------------------------------------}
{ Abort the load process. }
procedure TLogFileHandler.Error(const oLocator: IVBSAXLocator;
var strErrorMessage: WideString; nErrorCode: Integer);
begin
raise ELogException.Create(Format(MessageFormat, ['Error', strErrorMessage,
oLocator.LineNumber, oLocator.ColumnNumber, oLocator.SystemId]));
end;
{ Abort the load process. }
procedure TLogFileHandler.FatalError(const oLocator: IVBSAXLocator;
var strErrorMessage: WideString; nErrorCode: Integer);
begin
raise ELogException.Create(Format(MessageFormat,
['Fatal error', strErrorMessage, oLocator.LineNumber,
oLocator.ColumnNumber, oLocator.SystemId]));
end;
{ Ignore warnings. }
procedure TLogFileHandler.IgnorableWarning(const oLocator: IVBSAXLocator;
var strErrorMessage: WideString; nErrorCode: Integer);
begin
// Do nothing
end;
{ IDispatch -------------------------------------------------------------------}
{ These functions are required by the IDispatch interface but are not used. }
function TLogFileHandler.GetTypeInfoCount(out Count: Integer): HResult;
begin
Result := E_NOTIMPL;
end;
function TLogFileHandler.GetTypeInfo(Index, LocaleID: Integer; out TypeInfo):
HResult;
begin
Result := E_NOTIMPL;
end;
function TLogFileHandler.GetIDsOfNames(const IID: TGUID; Names: Pointer;
NameCount, LocaleID: Integer; DispIDs: Pointer): HResult;
begin
Result := E_NOTIMPL;
end;
function TLogFileHandler.Invoke(DispID: Integer; const IID: TGUID;
LocaleID: Integer; Flags: Word;
var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult;
begin
Result := E_NOTIMPL;
end;
{ IUnknown --------------------------------------------------------------------}
{ These functions are required by the IUnknown interface but are not used. }
function TLogFileHandler.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
Result := E_NOINTERFACE;
end;
function TLogFileHandler._AddRef: Integer;
begin
Result := 1;
end;
function TLogFileHandler._Release: Integer;
begin
Result := 1;
end;
{ External routines -----------------------------------------------------------}
{ Load a file in standard XML logging format into the dataset. }
procedure LoadFromFile(const DataSet: TCustomClientDataSet;
const FileName: string);
var
Handler: TLogFileHandler;
Reader: IVBSAXXMLReader;
begin
Handler := TLogFileHandler.Create(DataSet);
try
Reader := Log4DXMl.CreateSaxReader;
Reader.ContentHandler := Handler;
Reader.ErrorHandler := Handler;
Reader.ParseURL(FileName);
finally
Handler.Free;
end;
end;
{ Save the contents of the dataset to a file in standard XML logging format. }
procedure SaveToFile(const DataSet: TCustomClientDataSet;
const FileName: string);
var
Layout: TLogXMLLayout;
Contents: TStringList;
ElapsedTimeIndex, ErrorClassIndex, ErrorMsgIndex, LevelNameIndex,
LevelValueIndex, LoggerIndex, MessageIndex, NDCIndex,
ThreadIdIndex, TimestampIndex: Integer;
begin
// Locate fields once only
ElapsedTimeIndex := DataSet.FieldByName('ElapsedTime').Index;
ErrorClassIndex := DataSet.FieldByName('ErrorClass').Index;
ErrorMsgIndex := DataSet.FieldByName('ErrorMessage').Index;
LevelNameIndex := DataSet.FieldByName('LevelName').Index;
LevelValueIndex := DataSet.FieldByName('LevelValue').Index;
LoggerIndex := DataSet.FieldByName('LoggerName').Index;
MessageIndex := DataSet.FieldByName('Message').Index;
NDCIndex := DataSet.FieldByName('NDC').Index;
ThreadIdIndex := DataSet.FieldByName('ThreadId').Index;
TimestampIndex := DataSet.FieldByName('Timestamp').Index;
// Reuse the standard XML layout
Layout := TLogXMLLayout.Create;
try
Contents := TStringList.Create;
try
Contents.Append(Layout.Header);
// Process each record through the layout
with DataSet do
begin
First;
while not EOF do
begin
Contents.Append(Layout.Format(Fields[LoggerIndex].AsString,
Fields[LevelNameIndex].AsString, Fields[LevelValueIndex].AsInteger,
Fields[ThreadIdIndex].AsInteger, Fields[TimestampIndex].AsDateTime,
Fields[ElapsedTimeIndex].AsInteger, Fields[MessageIndex].AsString,
Fields[NDCIndex].AsString, Fields[ErrorMsgIndex].AsString,
Fields[ErrorClassIndex].AsString));
Next;
end;
end;
Contents.Append(Layout.Footer);
// And write out the results
Contents.SaveToFile(FileName);
finally
Contents.Free;
end;
finally
Layout.Free;
end;
end;
initialization
CoInitialize(nil);
finalization
CoUninitialize;
end.
|
//
// Generated by JavaToPas v1.4 20140515 - 181839
////////////////////////////////////////////////////////////////////////////////
unit android.text.style.SuggestionSpan;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
Androidapi.JNI.os,
Androidapi.JNI.GraphicsContentViewText,
android.text.TextPaint;
type
JSuggestionSpan = interface;
JSuggestionSpanClass = interface(JObjectClass)
['{884D006D-C593-4737-83BA-7B9FF7C90F66}']
function _GetACTION_SUGGESTION_PICKED : JString; cdecl; // A: $19
function _GetCREATOR : JParcelable_Creator; cdecl; // A: $19
function _GetFLAG_AUTO_CORRECTION : Integer; cdecl; // A: $19
function _GetFLAG_EASY_CORRECT : Integer; cdecl; // A: $19
function _GetFLAG_MISSPELLED : Integer; cdecl; // A: $19
function _GetSUGGESTIONS_MAX_SIZE : Integer; cdecl; // A: $19
function _GetSUGGESTION_SPAN_PICKED_AFTER : JString; cdecl; // A: $19
function _GetSUGGESTION_SPAN_PICKED_BEFORE : JString; cdecl; // A: $19
function _GetSUGGESTION_SPAN_PICKED_HASHCODE : JString; cdecl; // A: $19
function describeContents : Integer; cdecl; // ()I A: $1
function equals(o : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $1
function getFlags : Integer; cdecl; // ()I A: $1
function getLocale : JString; cdecl; // ()Ljava/lang/String; A: $1
function getSpanTypeId : Integer; cdecl; // ()I A: $1
function getSuggestions : TJavaArray<JString>; cdecl; // ()[Ljava/lang/String; A: $1
function hashCode : Integer; cdecl; // ()I A: $1
function init(context : JContext; locale : JLocale; suggestions : TJavaArray<JString>; flags : Integer; notificationTargetClass : JClass) : JSuggestionSpan; cdecl; overload;// (Landroid/content/Context;Ljava/util/Locale;[Ljava/lang/String;ILjava/lang/Class;)V A: $1
function init(context : JContext; suggestions : TJavaArray<JString>; flags : Integer) : JSuggestionSpan; cdecl; overload;// (Landroid/content/Context;[Ljava/lang/String;I)V A: $1
function init(locale : JLocale; suggestions : TJavaArray<JString>; flags : Integer) : JSuggestionSpan; cdecl; overload;// (Ljava/util/Locale;[Ljava/lang/String;I)V A: $1
function init(src : JParcel) : JSuggestionSpan; cdecl; overload; // (Landroid/os/Parcel;)V A: $1
procedure setFlags(flags : Integer) ; cdecl; // (I)V A: $1
procedure updateDrawState(tp : JTextPaint) ; cdecl; // (Landroid/text/TextPaint;)V A: $1
procedure writeToParcel(dest : JParcel; flags : Integer) ; cdecl; // (Landroid/os/Parcel;I)V A: $1
property ACTION_SUGGESTION_PICKED : JString read _GetACTION_SUGGESTION_PICKED;// Ljava/lang/String; A: $19
property CREATOR : JParcelable_Creator read _GetCREATOR; // Landroid/os/Parcelable$Creator; A: $19
property FLAG_AUTO_CORRECTION : Integer read _GetFLAG_AUTO_CORRECTION; // I A: $19
property FLAG_EASY_CORRECT : Integer read _GetFLAG_EASY_CORRECT; // I A: $19
property FLAG_MISSPELLED : Integer read _GetFLAG_MISSPELLED; // I A: $19
property SUGGESTIONS_MAX_SIZE : Integer read _GetSUGGESTIONS_MAX_SIZE; // I A: $19
property SUGGESTION_SPAN_PICKED_AFTER : JString read _GetSUGGESTION_SPAN_PICKED_AFTER;// Ljava/lang/String; A: $19
property SUGGESTION_SPAN_PICKED_BEFORE : JString read _GetSUGGESTION_SPAN_PICKED_BEFORE;// Ljava/lang/String; A: $19
property SUGGESTION_SPAN_PICKED_HASHCODE : JString read _GetSUGGESTION_SPAN_PICKED_HASHCODE;// Ljava/lang/String; A: $19
end;
[JavaSignature('android/text/style/SuggestionSpan')]
JSuggestionSpan = interface(JObject)
['{476088C3-4A2B-43B7-BF71-D058CF452FE6}']
function describeContents : Integer; cdecl; // ()I A: $1
function equals(o : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $1
function getFlags : Integer; cdecl; // ()I A: $1
function getLocale : JString; cdecl; // ()Ljava/lang/String; A: $1
function getSpanTypeId : Integer; cdecl; // ()I A: $1
function getSuggestions : TJavaArray<JString>; cdecl; // ()[Ljava/lang/String; A: $1
function hashCode : Integer; cdecl; // ()I A: $1
procedure setFlags(flags : Integer) ; cdecl; // (I)V A: $1
procedure updateDrawState(tp : JTextPaint) ; cdecl; // (Landroid/text/TextPaint;)V A: $1
procedure writeToParcel(dest : JParcel; flags : Integer) ; cdecl; // (Landroid/os/Parcel;I)V A: $1
end;
TJSuggestionSpan = class(TJavaGenericImport<JSuggestionSpanClass, JSuggestionSpan>)
end;
const
TJSuggestionSpanFLAG_EASY_CORRECT = 1;
TJSuggestionSpanFLAG_MISSPELLED = 2;
TJSuggestionSpanFLAG_AUTO_CORRECTION = 4;
TJSuggestionSpanACTION_SUGGESTION_PICKED = 'android.text.style.SUGGESTION_PICKED';
TJSuggestionSpanSUGGESTION_SPAN_PICKED_AFTER = 'after';
TJSuggestionSpanSUGGESTION_SPAN_PICKED_BEFORE = 'before';
TJSuggestionSpanSUGGESTION_SPAN_PICKED_HASHCODE = 'hashcode';
TJSuggestionSpanSUGGESTIONS_MAX_SIZE = 5;
implementation
end.
|
unit DataRW;
//
// PHOLIAGE Model, (c) Roelof Oomen, 2006-2007
//
// Data Reading and Writing classes
//
interface
uses
LCLIntf, LCLType, Variants, Classes, fpspreadsheet,
Ellipsoid_Integration, UExcel;
type
TMyCSV2=class
private
m_RowCount,
m_ColCount : Integer;
Data : array of array of String;
Function GetFieldText(Row,Col:Integer):String;
Function GetFieldTextD(Row,Col:Integer):Double;
public
// CSV separator character
Separator : char;
// Dimensions
property RowCount: Integer read m_RowCount;
property ColCount: Integer read m_ColCount;
// Row and Col are 1-based to comply with Excel automation
property Item[Row,Col:Integer]:String read GetFieldText;
property ItemD[Row,Col:Integer]:Double read GetFieldTextD;
// Load the data
procedure LoadFile(const FileName: string);
// Extra constructor
Constructor Create(FileName:String; sep : char); overload;
end;
TMyCSV=class(TStringList)
private
Function GetFieldText(Row,Col:Integer):String;
procedure SetFieldText(Row,Col:Integer;Value:String);
public
// CSV separator character
Separator : char;
// Row and Col are 1-based to comply with Excel automation
property FieldText[Row,Col:Integer]:String read GetFieldText write SetFieldText;
procedure LoadFile(const FileName:String);
end;
ReadPlot = class
private
function ReadExcelData(Plot : TPlot; FileName : String):Integer;
function ReadCSVData(Plot : TPlot; FileName : String):Integer;
public
function ReadData(Plot : TPlot; FileName : String):Integer;
end;
TWriteExcel = class (WriteXLS)
function Write(Plot:TPlot; xlsname : String): boolean;
end;
// Wrapper for TsWorkSheet with 1-based row and column indexing
TSheet = class helper for TsWorksheet
function ReadAsUTF8Text(ARow, ACol: Cardinal): string;
function ReadAsNumber(ARow, ACol: Cardinal): Double;
end;
implementation
uses
SysUtils, StrUtils, Dialogs,
Model_Absorption, Math,
// fpspreadsheet supported file formats
xlsbiff2, xlsbiff5, xlsbiff8, xlsxooxml, fpsopendocument;
function ReadPlot.ReadCSVData(Plot: TPlot; FileName: String): Integer;
var
CSV : TMyCSV2;
c, I_H, PlHeight : Double;
I, col : Integer;
Diam : boolean;
Ellipsoid : TEllipsoid;
Env : TEnvironment;
Phot : TPhotosynthesis;
tmpS : String;
// Names of currently read colums for error message
colnames : TStringList;
begin
result:=0;
I:=1;
col:=1;
colnames:=TStringList.Create;
colnames.Clear;
try
try
CSV := TMyCSV2.Create(FileName, #59);
Colnames.Add('Name/Location');
// Cells.Item[row, column]
Plot.name:=CSV.Item[4,1];
Plot.location:=CSV.Item[4,2];
Colnames[0]:='Clouding const/Horiz. light';
c:=CSV.ItemD[7,1];
if c=0 then
Raise EInOutError.Create('Clouding constant cannot not be zero');
I_H:=CSV.ItemD[7,2];
// Check if a,b and c are written as radii or diameters
if LeftStr(CSV.Item[8,4],8)='Diameter' then
Diam:=true
else
Diam:=false;
Ellipsoid:=TEllipsoid.Create;
Env:=Ellipsoid.Ring.Ellipse.Env;
Phot:=Ellipsoid.Ring.Ellipse.Env.Photosynthesis;
Colnames.Clear;
// Read all column names to be able to give specific error messages
I:=1;
repeat
tmpS:=CSV.Item[9,I];
if tmpS<>'' then
colnames.Add(tmpS);
inc(I);
until tmpS='';
for I := 10 to CSV.RowCount do
with CSV do
begin
col:=1;
Ellipsoid.Name:=Item[I,col];
// Stop on first empty line
if Ellipsoid.Name='' then
break;
// Set up crown dimensions
inc(col);
PlHeight:=StrToFloat(Item[I,col]);
inc(col);
Env.Crown.a:=StrToFloat(Item[I,col]);
inc(col);
Env.Crown.b:=StrToFloat(Item[I,col]);
inc(col);
Env.Crown.c:=StrToFloat(Item[I,col]);
if (Env.Crown.a=0) or (Env.Crown.b=0) or (Env.Crown.c=0) then
Raise EInOutError.Create('Crown dimensions cannot be zero');
If Diam then
begin
Env.Crown.a:=Env.Crown.a/2;
Env.Crown.b:=Env.Crown.b/2;
Env.Crown.c:=Env.Crown.c/2;
end;
// Set up vegetation parameters
inc(col);
Env.Vegetation.r_gap:=StrToFloat(Item[I,col]);
inc(col);
Env.Vegetation.h_t:= StrToFloat(Item[I,col]);
inc(col);
Env.Vegetation.h_b:= StrToFloat(Item[I,col]);
if PlHeight<>0 then
begin
// Origin of data is plant stem base
Env.Vegetation.h_t:=Env.Vegetation.h_t-(PlHeight-Env.Crown.a);
Env.Vegetation.h_b:=Env.Vegetation.h_b-(PlHeight-Env.Crown.a);
end;
// Add leaves and leaf angle classes
Env.Crown.F.Clear;
inc(col);
Env.Crown.F.F:=StrToFloat(Item[I,col]);
// Calculate leaf area density from plant total leaf area
// and crown volume
Env.Crown.F.F:=Env.Crown.F.F/(4/3*pi*Env.crown.a*Env.crown.b*Env.crown.c);
inc(col);
Env.Crown.F.addclassD(15,30, StrToFloat(Item[I,col]));
inc(col);
Env.Crown.F.addclassD(45,30, StrToFloat(Item[I,col]));
inc(col);
Env.Crown.F.addclassD(75,30, StrToFloat(Item[I,col]));
try
Env.Crown.F.fractionise;
except
on E:EMathError do
Raise EInOutError.Create('At least one crown leaf angle class must not be zero');
end;
inc(col);
Env.Crown.F.a_L:=StrToFloat(Item[I,col]);
// Add leaves and leaf angle classes
Env.Vegetation.F.Clear;
inc(col);
Env.Vegetation.F.F:=StrToFloat(Item[I,col]);
// Calculate leaf area density from vegetation LAI and thickness
Env.Vegetation.F.F:=Env.Vegetation.F.F/(Env.Vegetation.h_t-Env.Vegetation.h_b);
inc(col);
Env.Vegetation.F.addclassD(15,30, StrToFloat(Item[I,col]));
inc(col);
Env.Vegetation.F.addclassD(45,30, StrToFloat(Item[I,col]));
inc(col);
Env.Vegetation.F.addclassD(75,30, StrToFloat(Item[I,col]));
try
Env.Vegetation.F.fractionise;
except
on E:EMathError do
Raise EInOutError.Create('At least one vegetation leaf angle class must not be zero');
end;
inc(col);
Env.Vegetation.F.a_L:=StrToFloat(Item[I,col]);
Env.Light.c:=c;
Env.Light.I_H:=I_H;
inc(col);
Phot.N_top:=StrToFloat(Item[I,col]);
inc(col);
Phot.a_N:=StrToFloat(Item[I,col]);
inc(col);
Phot.a_P:=StrToFloat(Item[I,col]);
inc(col);
Phot.b_P:=StrToFloat(Item[I,col]);
inc(col);
// This column can be empty
tmpS:=Item[I,col];
if tmpS='' then
begin
Phot.p_lin:=true;
tmpS:='0';
end
else
Phot.p_lin:=false;
Phot.c_P:=StrToFloat(tmpS);
inc(col);
// This column can be empty
tmpS:=Item[I,col];
if tmpS='' then
tmpS:='0';
Phot.a_R:=StrToFloat(tmpS);
inc(col);
Phot.b_R:=StrToFloat(Item[I,col]);
inc(col);
Phot.phi:=StrToFloat(Item[I,col]);
inc(col);
Phot.theta:=StrToFloat(Item[I,col]);
SetLength(Plot.Plants,Length(Plot.Plants)+1);
SetLength(Plot.Heights,Length(Plot.Plants));
Plot.Plants[High(Plot.Plants)]:=Ellipsoid;
Plot.Heights[High(Plot.Plants)]:=PlHeight;
Ellipsoid:=TEllipsoid.Create;
Env:=Ellipsoid.Ring.Ellipse.Env;
Phot:=Ellipsoid.Ring.Ellipse.Env.Photosynthesis;
Result:=I-9;
end;
except
on E: Exception do
begin
Result:=0; // 0 plants correctly read
Plot.Clear; // Clear everything read so far
ShowMessage(' '+E.Message+' in row '+IntToStr(I)+', column "'+colnames[col-1]+'".');
end;
end;
finally
FreeAndNil(ColNames);
FreeAndNil(Ellipsoid);
FreeAndNil(CSV);
end;
end;
function ReadPlot.ReadExcelData(Plot : TPlot; FileName : String):Integer;
var
WorkBook: TsWorkbook; // Spreadsheet workbook
Sheet: TsWorksheet;
c, I_H, PlHeight : Double;
I, col : Integer;
Diam : boolean;
Ellipsoid : TEllipsoid;
Env : TEnvironment;
Phot : TPhotosynthesis;
tmpS : String;
// Names of currently read colums for error message
colnames : TStringList;
begin
result:=0;
I:=1;
col:=1;
colnames:=TStringList.Create;
colnames.Clear;
Workbook := TsWorkbook.Create;
try
Workbook.ReadFromFile(FileName);
try
Sheet := WorkBook.GetWorksheetByIndex(0);
Colnames.Add('Name/Location');
// Cells.Item[row, column]
Plot.name:=Sheet.ReadAsUTF8Text(4,1);
Plot.location:=Sheet.ReadAsUTF8Text(4,2);
Colnames[0]:='Clouding const/Horiz. light';
c:=Sheet.ReadAsNumber(7,1);
if c=0 then
Raise EInOutError.Create('Clouding constant cannot not be zero');
I_H:=Sheet.ReadAsNumber(7,2);
// Check if a,b and c are written as radii or diameters
if LeftStr(Sheet.ReadAsUTF8Text(8,4) ,8)='Diameter' then
Diam:=true
else
Diam:=false;
Ellipsoid:=TEllipsoid.Create;
Env:=Ellipsoid.Ring.Ellipse.Env;
Phot:=Ellipsoid.Ring.Ellipse.Env.Photosynthesis;
Colnames.Clear;
// Read all column names to be able to give specific error messages
I:=1;
repeat
tmpS:=Sheet.ReadAsUTF8Text(9,I);
if tmpS<>'' then
colnames.Add(tmpS);
inc(I);
until tmpS='';
for I := 10 to Sheet.GetLastRowIndex() do
with Sheet.Cells do
begin
col:=1;
Ellipsoid.Name:=Sheet.ReadAsUTF8Text(I,col);
// Stop on first empty line
if Ellipsoid.Name='' then
break;
// Set up crown dimensions
inc(col);
PlHeight:=Sheet.ReadAsNumber(I,col);
inc(col);
Env.Crown.a:=Sheet.ReadAsNumber(I,col);
inc(col);
Env.Crown.b:=Sheet.ReadAsNumber(I,col);
inc(col);
Env.Crown.c:=Sheet.ReadAsNumber(I,col);
if (Env.Crown.a=0) or (Env.Crown.b=0) or (Env.Crown.c=0) then
Raise EInOutError.Create('Crown dimensions cannot be zero');
If Diam then
begin
Env.Crown.a:=Env.Crown.a/2;
Env.Crown.b:=Env.Crown.b/2;
Env.Crown.c:=Env.Crown.c/2;
end;
// Set up vegetation parameters
inc(col);
Env.Vegetation.r_gap:=Sheet.ReadAsNumber(I,col);
inc(col);
Env.Vegetation.h_t:= Sheet.ReadAsNumber(I,col);
inc(col);
Env.Vegetation.h_b:= Sheet.ReadAsNumber(I,col);
if PlHeight<>0 then
begin
// Origin of data is plant stem base
Env.Vegetation.h_t:=Env.Vegetation.h_t-(PlHeight-Env.Crown.a);
Env.Vegetation.h_b:=Env.Vegetation.h_b-(PlHeight-Env.Crown.a);
end;
// Add leaves and leaf angle classes
Env.Crown.F.Clear;
inc(col);
Env.Crown.F.F:=Sheet.ReadAsNumber(I,col);
// Calculate leaf area density from plant total leaf area
// and crown volume
Env.Crown.F.F:=Env.Crown.F.F/(4/3*pi*Env.crown.a*Env.crown.b*Env.crown.c);
inc(col);
Env.Crown.F.addclassD(15,30, Sheet.ReadAsNumber(I,col));
inc(col);
Env.Crown.F.addclassD(45,30, Sheet.ReadAsNumber(I,col));
inc(col);
Env.Crown.F.addclassD(75,30, Sheet.ReadAsNumber(I,col));
try
Env.Crown.F.fractionise;
except
on E:EMathError do
Raise EInOutError.Create('At least one crown leaf angle class must not be zero');
end;
inc(col);
Env.Crown.F.a_L:=Sheet.ReadAsNumber(I,col);
// Add leaves and leaf angle classes
Env.Vegetation.F.Clear;
inc(col);
Env.Vegetation.F.F:=Sheet.ReadAsNumber(I,col);
// Calculate leaf area density from vegetation LAI and thickness
Env.Vegetation.F.F:=Env.Vegetation.F.F/(Env.Vegetation.h_t-Env.Vegetation.h_b);
inc(col);
Env.Vegetation.F.addclassD(15,30, Sheet.ReadAsNumber(I,col));
inc(col);
Env.Vegetation.F.addclassD(45,30, Sheet.ReadAsNumber(I,col));
inc(col);
Env.Vegetation.F.addclassD(75,30, Sheet.ReadAsNumber(I,col));
try
Env.Vegetation.F.fractionise;
except
on E:EMathError do
Raise EInOutError.Create('At least one vegetation leaf angle class must not be zero');
end;
inc(col);
Env.Vegetation.F.a_L:=Sheet.ReadAsNumber(I,col);
Env.Light.c:=c;
Env.Light.I_H:=I_H;
inc(col);
Phot.N_top:=Sheet.ReadAsNumber(I,col);
inc(col);
Phot.a_N:=Sheet.ReadAsNumber(I,col);
inc(col);
Phot.a_P:=Sheet.ReadAsNumber(I,col);
inc(col);
Phot.b_P:=Sheet.ReadAsNumber(I,col);
inc(col);
// This column can be empty
tmpS:=Sheet.ReadAsUTF8Text(I,col);
if tmpS='' then
begin
Phot.p_lin:=true;
tmpS:='0';
end
else
Phot.p_lin:=false;
Phot.c_P:=StrToFloat(tmpS);
inc(col);
// This column can be empty
tmpS:=Sheet.ReadAsUTF8Text(I,col);
if tmpS='' then
tmpS:='0';
Phot.a_R:=StrToFloat(tmpS);
inc(col);
Phot.b_R:=Sheet.ReadAsNumber(I,col);
inc(col);
Phot.phi:=Sheet.ReadAsNumber(I,col);
inc(col);
Phot.theta:=Sheet.ReadAsNumber(I,col);
SetLength(Plot.Plants,Length(Plot.Plants)+1);
SetLength(Plot.Heights,Length(Plot.Plants));
Plot.Plants[High(Plot.Plants)]:=Ellipsoid;
Plot.Heights[High(Plot.Plants)]:=PlHeight;
Ellipsoid:=TEllipsoid.Create;
Env:=Ellipsoid.Ring.Ellipse.Env;
Phot:=Ellipsoid.Ring.Ellipse.Env.Photosynthesis;
Result:=I-9;
end;
except
on E: Exception do
begin
Result:=0; // 0 plants correctly read
Plot.Clear; // Clear everything read so far
ShowMessage(' '+E.Message+' in row '+IntToStr(I)+', column "'+colnames[col-1]+'".');
end;
end;
finally
FreeAndNil(ColNames);
FreeAndNil(Ellipsoid);
FreeAndNil(WorkBook);
end;
end;
function ReadPlot.ReadData(Plot: TPlot; FileName: String): Integer;
begin
Result:=0;
if UpperCase(ExtractFileExt(FileName))='.CSV' then
result:=ReadCSVData(Plot,FileName);
if UpperCase(ExtractFileExt(FileName))='.XLS' then
result:=ReadExcelData(Plot,FileName);
end;
{ TWriteExcel }
function TWriteExcel.Write(Plot:TPlot; xlsname : String): boolean;
var
name_int,
row, col, i : integer;
begin
XlsOpen(xlsname);
row:=0;
XlsWriteCellLabel(0,row,'PHOLIAGE model results');
inc(row);
XlsWriteCellLabel(0,row,'Plot details');
inc(row);
XlsWriteCellLabel(0,row,'Name');
XlsWriteCellLabel(1,row,'Location');
inc(row);
XlsWriteCellLabel(0,row,AnsiString(Plot.Name));
XlsWriteCellLabel(1,row,AnsiString(Plot.Location));
inc(row);
XlsWriteCellLabel(0,row,'Results');
inc(row);
XlsWriteCellLabel(0,row,'Plant ID');
XlsWriteCellLabel(1,row,'PPFD absorbed');
XlsWriteCellLabel(2,row,'Net photosynthesis');
inc(row);
for i:=0 to High(Plot.Plants) do
with Plot.Plants[i] do
begin
col:=0;
try
name_int:=strtoint(name);
XlsWriteCellRk(col,row,name_int); // save as integer
except
XlsWriteCellLabel(col,row,AnsiString(name)); // save as string
end;
Inc(Col);
XlsWriteCellNumber(col,row,Plot.AbsResults[i]);
Inc(Col);
XlsWriteCellNumber(col,row,Plot.PhotResults[i]);
Inc(Row);
end;
XlsClose;
result:=true;
end;
Function TMyCSV.GetFieldText(Row,Col:Integer):String;
var s:String;StartPos,EndPos,SLen,fY:Integer;
begin
Dec(Row);
Dec(Col);
Result:='';
if Row<Count then
begin
s:=Strings[Row];
fY:=0;
StartPos:=1;
EndPos:=1;
SLen:=length(s);
While EndPos<= SLen do
begin
if s[EndPos]=separator then
begin
if fY=Col then Break;
StartPos:=EndPos+1;
Inc(fY);
end;
inc(EndPos);
end;
if fY=Col then result:=copy(s,StartPos,EndPos-StartPos);
end;
end;
procedure TMyCSV.SetFieldText(Row,Col:Integer;Value:String);
var
s : String;
StartPos,
EndPos,
SLen,
fY : Integer;
FieldModified : Boolean;
begin
Dec(Row);
Dec(Col);
FieldModified:=False;
if Row>=Count then
begin
for fy:=0 to Row-Count do
Add('');
end;
s:=Strings[Row];
fY:=0;
StartPos:=1;
EndPos:=1;
SLen:=length(s);
While EndPos<= SLen do
begin
if s[EndPos]=separator then
begin
if fY=col then
begin
S:=copy(s,0,StartPos-1)+Value+copy(s,EndPos,SLen);
FieldModified:=True;
Break;
end;
StartPos:=EndPos+1;
Inc(fY);
end;
inc(EndPos);
end;
if not FieldModified then
begin
for StartPos:=0 to col-fY-1 do
S:=S+separator;
S:=S+Value;
end;
Strings[Row]:=s;
end;
procedure TMyCSV.LoadFile(const FileName:String);
var
Stream : TStream;
Size : Int64;
S,
CurrentLine : string;
EndPos,
StartPos : Integer;
begin
Clear;
CurrentLine:='';
StartPos:=1;
EndPos:=1;
Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
try
Stream.Position:=0;
Size := Stream.Size;
SetString(S, nil, Size);
Stream.Read(Pointer(S)^, Size);
finally
FreeAndNil(Stream);
end;
while EndPos <= Size do
begin
if (S[EndPos] + S[EndPos + 1] = #13#10) or (EndPos=Size) then
begin
CurrentLine:=CurrentLine+','+copy(S,StartPos,EndPos-StartPos);
CurrentLine:=Copy(CurrentLine,2,length(CurrentLine));
Add(CurrentLine);
CurrentLine:='';
StartPos:=EndPos+2;
Inc(EndPos);
end
else
if S[EndPos] = separator then
begin
CurrentLine:=CurrentLine+','+copy(S,StartPos,EndPos-StartPos);
StartPos:=EndPos+1;
end;
Inc(EndPos);
end;
end;
constructor TMyCSV2.Create(FileName:String; sep : Char);
begin
inherited Create;
separator := sep;
LoadFile(FileName);
end;
function TMyCSV2.GetFieldText(Row, Col: Integer): String;
begin
if Row>m_RowCount then
result := ''
else
if Col>m_ColCount then
result := ''
else
result:=data[row-1,col-1];
end;
function TMyCSV2.GetFieldTextD(Row, Col: Integer): Double;
begin
if Row>m_RowCount then
result := 0
else
if Col>m_ColCount then
result := 0
else
result:=StrToFloat(data[row-1,col-1]);
end;
procedure TMyCSV2.LoadFile(const FileName: string);
var
Stream : TStream;
Size : Int64;
S : string;
Start,ArraySize :Integer;
Y, I, X : Integer;
begin
Start:=1;
I := 1; // Placeholder
X := 0; // Holds Horz. Position
Y := 0; // Array Vert. Position
ArraySize:=0;
Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
try
Stream.Position:=0;
Size := Stream.Size;
SetString(S, nil, Size);
Stream.Read(Pointer(S)^, Size);
finally
FreeAndNil(Stream);
end;
while I <= Size do
begin
ArraySize:=Max(X,ArraySize);
m_RowCount:=Y+1;
m_ColCount:=ArraySize+1;
SetLength(Data, Y + 1, ArraySize + 1);
if S[i] + S[I + 1] = #13#10 then
begin
Data[Y, X] := Copy(S,Start,I-Start);
Start:=I+2;
Inc(Y);
Inc(I);
X:=0;
end
else if S[i] = separator then
begin
Data [Y, X] := Copy(S,Start,I-Start);
Start:=I+1;
inc(X);
end
else if I=Size then Data[Y, X] := Copy(S,Start,I-Start);
Inc(I);
end;
end;
function TSheet.ReadAsUTF8Text(ARow, ACol: Cardinal): string;
begin
Result := inherited ReadAsUTF8Text(ARow-1, ACol-1);
end;
function TSheet.ReadAsNumber(ARow, ACol: Cardinal): Double;
begin
Result := inherited ReadAsNumber(ARow-1, ACol-1);
end;
end.
|
unit MovimentoRepository;
interface
uses BasicRepository, System.Generics.Collections, System.SysUtils, TurnoVO,
OperadorVO, MovimentoVO, SuprimentoVO, SangriaVO, MovimentoFechamentoVO,
TipoImpressaoVO, ImprimirVO, ViewImprimirVO, ViewVendaVO, Nfc01VO, Nfc02VO,
TerminalVO, PessoaVO, VendedorVO;
type
TMovimentoRepository = class(TBasicRepository)
class function getTuno: TList<TTurnoVO>;
class function getOperador(Identificacao: string): TOperadorVO;
class procedure MovimentoInserir(Movimento: TMovimentoVO);
class procedure MovimentoInserirSuprimento(Suprimento: TSuprimentoVO);
class function getMovimentoByIdCaixa(idOfCaixa: Integer): TMovimentoVO;
class procedure SangriaInserir(Sangria: TSangriaVO);
class procedure MovimentoFechar(idOfMovimento: Integer);
class procedure MovimentoFechamentoInserir(Lst: TList<TMovimentoFechamentoVO>);
class function getTipoImpressao: TList<TTipoImpressaoVO>;
class function getImprimir(idOfMovimento, idOfTipoImpressao: Integer): TList<TImprimirVO>;
class function getImprimirPedido(idOfMovimento, idOfTipoImpressao: Integer): TList<TViewImprimirVO>;
class procedure Reimprimir(idOfImprimir: Integer);
class function getVendasDoMovimento(idOfMovimento: Integer): TList<TViewVendaVO>;
class function getNF(idOfVenda: Integer): TNfc01VO;
class function getResultNF(idOfVenda: Integer): TNfc02VO;
class function getTerminal(Identificador: string): TTerminalVO;
class function PessoaInserir(Pessoa: TPessoaVO): Integer;
class function GetVendedorAll: TList<TVendedorVO>;
class function getVendedor(Identificacao: string): TVendedorVO;
end;
implementation
{ TMovimentoRepository }
class function TMovimentoRepository.getImprimir(idOfMovimento,
idOfTipoImpressao: Integer): TList<TImprimirVO>;
var
Filtro: string;
begin
Filtro:= 'ID_MOVIMENTO = ' + IntToStr(idOfMovimento) +
' AND ID_TIPO_IMPRESSAO = ' + IntToStr(idOfTipoImpressao) +
' ORDER BY LANCAMENTO DESC';
Result:= Consultar<TImprimirVO>(False,Filtro);
end;
class function TMovimentoRepository.getImprimirPedido(idOfMovimento,
idOfTipoImpressao: Integer): TList<TViewImprimirVO>;
var
Filtro: string;
begin
Filtro:= 'ID_MOVIMENTO = ' + IntToStr(idOfMovimento) +
' AND ID_TIPO_IMPRESSAO = ' + IntToStr(idOfTipoImpressao) +
' ORDER BY LANCAMENTO DESC';
Result:= Consultar<TViewImprimirVO>(False,Filtro);
end;
class function TMovimentoRepository.getMovimentoByIdCaixa(
idOfCaixa: Integer): TMovimentoVO;
var
Filtro: string;
begin
Filtro:= 'ID_CAIXA = ' + IntToStr(idOfCaixa) + ' AND SITUACAO = ' + QuotedStr('A');
Result:= ConsultarUmObjeto<TMovimentoVO>(Filtro,True);
end;
class function TMovimentoRepository.getNF(idOfVenda: Integer): TNfc01VO;
var
Filtro: string;
begin
Filtro:= 'ID_VENDA = ' + IntToStr(idOfVenda);
Result:= ConsultarUmObjeto<TNfc01VO>(Filtro,False);
end;
class function TMovimentoRepository.getOperador(
Identificacao: string): TOperadorVO;
var
Filtro: string;
begin
Filtro:= 'SENHA = ' + QuotedStr(Identificacao);
Result:= ConsultarUmObjeto<TOperadorVO>(Filtro,False);
end;
class function TMovimentoRepository.getResultNF(idOfVenda: Integer): TNfc02VO;
var
Filtro: string;
begin
Filtro:= 'ID_VENDA = ' + IntToStr(idOfVenda);
Result:= ConsultarUmObjeto<TNfc02VO>(Filtro,False);
end;
class function TMovimentoRepository.getTerminal(
Identificador: string): TTerminalVO;
var
Filtro: string;
begin
Filtro:= 'identificador = ' + QuotedStr(Identificador);
Result:= ConsultarUmObjeto<TTerminalVO>(Filtro,False);
end;
class function TMovimentoRepository.getTipoImpressao: TList<TTipoImpressaoVO>;
begin
Result:= Consultar<TTipoImpressaoVO>(False,'ID NOT IN(2,7,8)');
end;
class function TMovimentoRepository.getTuno: TList<TTurnoVO>;
begin
Result:= Consultar<TTurnoVO>(False,'ID > 0');
end;
class procedure TMovimentoRepository.MovimentoFechamentoInserir(
Lst: TList<TMovimentoFechamentoVO>);
var
I: Integer;
begin
for I := 0 to Pred(Lst.Count) do
begin
Inserir(Lst.Items[i]);
Lst.Items[i].Free;
end;
end;
class procedure TMovimentoRepository.MovimentoFechar(idOfMovimento: Integer);
var
SQL_COMANDO: string;
begin
SQL_COMANDO:= 'execute procedure fechar_movimento(' + IntToStr(idOfMovimento) + ')';
ComandoSQL(SQL_COMANDO);
end;
class procedure TMovimentoRepository.MovimentoInserir(Movimento: TMovimentoVO);
begin
Movimento.Id:= Inserir(Movimento);
end;
class procedure TMovimentoRepository.MovimentoInserirSuprimento(
Suprimento: TSuprimentoVO);
begin
Inserir(Suprimento);
end;
class function TMovimentoRepository.PessoaInserir(Pessoa: TPessoaVO): Integer;
begin
Result:= Inserir(Pessoa);
end;
class procedure TMovimentoRepository.Reimprimir(idOfImprimir: Integer);
var
Filtro: string;
begin
Filtro:= 'UPDATE IMPRIMIR SET IMPRESSO = ' + QuotedStr('N') + ' WHERE ID = ' + IntToStr(idOfImprimir);
ComandoSQL(Filtro);
Filtro:= 'UPDATE IMPRIMIR P SET P.IMPRESSO = ' + QuotedStr('N') +
' WHERE P.ID_TIPO_IMPRESSAO = 8 AND P.IDOFTABLE = ' +
' (SELECT I.IDOFTABLE FROM IMPRIMIR I WHERE i.ID_TIPO_IMPRESSAO = 5 AND I.ID = ' + IntToStr(idOfImprimir) + ')';
ComandoSQL(Filtro);
end;
class procedure TMovimentoRepository.SangriaInserir(Sangria: TSangriaVO);
begin
Inserir(Sangria);
end;
class function TMovimentoRepository.getVendasDoMovimento(
idOfMovimento: Integer): TList<TViewVendaVO>;
var
Filtro: string;
begin
Filtro:= 'ID_MOVIMENTO = ' + IntToStr(idOfMovimento);
Result:= Consultar<TViewVendaVO>(False,Filtro);
end;
class function TMovimentoRepository.getVendedor(
Identificacao: string): TVendedorVO;
var
Filtro: string;
begin
Filtro:= 'SENHA = ' + QuotedStr(Identificacao);
Result:= ConsultarUmObjeto<TVendedorVO>(Filtro,False);
end;
class function TMovimentoRepository.GetVendedorAll: TList<TVendedorVO>;
var
Filtro: string;
begin
Filtro:= 'ID > 0';
Result:= Consultar<TVendedorVO>(False,Filtro);
end;
end.
|
unit InflatablesList_HTML_NamedCharRefs;
{$INCLUDE '.\InflatablesList_defs.inc'}
interface
uses
AuxTypes;
type
TILHTMLNamedCharRef = record
Name: UnicodeString;
CodePointA: UInt32;
CodePointB: UInt32;
end;
const
IL_HTML_NAMED_CHAR_REF_MAXLEN = 33; // max length of name in the following table
IL_HTML_NAMED_CHAR_REFS: array[0..2230] of TILHTMLNamedCharRef = (
(Name: UnicodeString('Á'); CodePointA: 193; CodePointB: 0),
(Name: UnicodeString('Á'); CodePointA: 193; CodePointB: 0),
(Name: UnicodeString('á'); CodePointA: 225; CodePointB: 0),
(Name: UnicodeString('á'); CodePointA: 225; CodePointB: 0),
(Name: UnicodeString('Ă'); CodePointA: 258; CodePointB: 0),
(Name: UnicodeString('ă'); CodePointA: 259; CodePointB: 0),
(Name: UnicodeString('∾'); CodePointA: 8766; CodePointB: 0),
(Name: UnicodeString('∿'); CodePointA: 8767; CodePointB: 0),
(Name: UnicodeString('∾̳'); CodePointA: 8766; CodePointB: 819),
(Name: UnicodeString('Â'); CodePointA: 194; CodePointB: 0),
(Name: UnicodeString('Â'); CodePointA: 194; CodePointB: 0),
(Name: UnicodeString('â'); CodePointA: 226; CodePointB: 0),
(Name: UnicodeString('â'); CodePointA: 226; CodePointB: 0),
(Name: UnicodeString('´'); CodePointA: 180; CodePointB: 0),
(Name: UnicodeString('´'); CodePointA: 180; CodePointB: 0),
(Name: UnicodeString('А'); CodePointA: 1040; CodePointB: 0),
(Name: UnicodeString('а'); CodePointA: 1072; CodePointB: 0),
(Name: UnicodeString('Æ'); CodePointA: 198; CodePointB: 0),
(Name: UnicodeString('Æ'); CodePointA: 198; CodePointB: 0),
(Name: UnicodeString('æ'); CodePointA: 230; CodePointB: 0),
(Name: UnicodeString('æ'); CodePointA: 230; CodePointB: 0),
(Name: UnicodeString('⁡'); CodePointA: 8289; CodePointB: 0),
(Name: UnicodeString('𝔄'); CodePointA: 120068; CodePointB: 0),
(Name: UnicodeString('𝔞'); CodePointA: 120094; CodePointB: 0),
(Name: UnicodeString('À'); CodePointA: 192; CodePointB: 0),
(Name: UnicodeString('À'); CodePointA: 192; CodePointB: 0),
(Name: UnicodeString('à'); CodePointA: 224; CodePointB: 0),
(Name: UnicodeString('à'); CodePointA: 224; CodePointB: 0),
(Name: UnicodeString('ℵ'); CodePointA: 8501; CodePointB: 0),
(Name: UnicodeString('ℵ'); CodePointA: 8501; CodePointB: 0),
(Name: UnicodeString('Α'); CodePointA: 913; CodePointB: 0),
(Name: UnicodeString('α'); CodePointA: 945; CodePointB: 0),
(Name: UnicodeString('Ā'); CodePointA: 256; CodePointB: 0),
(Name: UnicodeString('ā'); CodePointA: 257; CodePointB: 0),
(Name: UnicodeString('⨿'); CodePointA: 10815; CodePointB: 0),
(Name: UnicodeString('&'); CodePointA: 38; CodePointB: 0),
(Name: UnicodeString('&'); CodePointA: 38; CodePointB: 0),
(Name: UnicodeString('&'); CodePointA: 38; CodePointB: 0),
(Name: UnicodeString('&'); CodePointA: 38; CodePointB: 0),
(Name: UnicodeString('⩕'); CodePointA: 10837; CodePointB: 0),
(Name: UnicodeString('⩓'); CodePointA: 10835; CodePointB: 0),
(Name: UnicodeString('∧'); CodePointA: 8743; CodePointB: 0),
(Name: UnicodeString('⩜'); CodePointA: 10844; CodePointB: 0),
(Name: UnicodeString('⩘'); CodePointA: 10840; CodePointB: 0),
(Name: UnicodeString('⩚'); CodePointA: 10842; CodePointB: 0),
(Name: UnicodeString('∠'); CodePointA: 8736; CodePointB: 0),
(Name: UnicodeString('⦤'); CodePointA: 10660; CodePointB: 0),
(Name: UnicodeString('∠'); CodePointA: 8736; CodePointB: 0),
(Name: UnicodeString('⦨'); CodePointA: 10664; CodePointB: 0),
(Name: UnicodeString('⦩'); CodePointA: 10665; CodePointB: 0),
(Name: UnicodeString('⦪'); CodePointA: 10666; CodePointB: 0),
(Name: UnicodeString('⦫'); CodePointA: 10667; CodePointB: 0),
(Name: UnicodeString('⦬'); CodePointA: 10668; CodePointB: 0),
(Name: UnicodeString('⦭'); CodePointA: 10669; CodePointB: 0),
(Name: UnicodeString('⦮'); CodePointA: 10670; CodePointB: 0),
(Name: UnicodeString('⦯'); CodePointA: 10671; CodePointB: 0),
(Name: UnicodeString('∡'); CodePointA: 8737; CodePointB: 0),
(Name: UnicodeString('∟'); CodePointA: 8735; CodePointB: 0),
(Name: UnicodeString('⊾'); CodePointA: 8894; CodePointB: 0),
(Name: UnicodeString('⦝'); CodePointA: 10653; CodePointB: 0),
(Name: UnicodeString('∢'); CodePointA: 8738; CodePointB: 0),
(Name: UnicodeString('Å'); CodePointA: 197; CodePointB: 0),
(Name: UnicodeString('⍼'); CodePointA: 9084; CodePointB: 0),
(Name: UnicodeString('Ą'); CodePointA: 260; CodePointB: 0),
(Name: UnicodeString('ą'); CodePointA: 261; CodePointB: 0),
(Name: UnicodeString('𝔸'); CodePointA: 120120; CodePointB: 0),
(Name: UnicodeString('𝕒'); CodePointA: 120146; CodePointB: 0),
(Name: UnicodeString('⩯'); CodePointA: 10863; CodePointB: 0),
(Name: UnicodeString('≈'); CodePointA: 8776; CodePointB: 0),
(Name: UnicodeString('⩰'); CodePointA: 10864; CodePointB: 0),
(Name: UnicodeString('≊'); CodePointA: 8778; CodePointB: 0),
(Name: UnicodeString('≋'); CodePointA: 8779; CodePointB: 0),
(Name: UnicodeString('''); CodePointA: 39; CodePointB: 0),
(Name: UnicodeString('⁡'); CodePointA: 8289; CodePointB: 0),
(Name: UnicodeString('≈'); CodePointA: 8776; CodePointB: 0),
(Name: UnicodeString('≊'); CodePointA: 8778; CodePointB: 0),
(Name: UnicodeString('Å'); CodePointA: 197; CodePointB: 0),
(Name: UnicodeString('Å'); CodePointA: 197; CodePointB: 0),
(Name: UnicodeString('å'); CodePointA: 229; CodePointB: 0),
(Name: UnicodeString('å'); CodePointA: 229; CodePointB: 0),
(Name: UnicodeString('𝒜'); CodePointA: 119964; CodePointB: 0),
(Name: UnicodeString('𝒶'); CodePointA: 119990; CodePointB: 0),
(Name: UnicodeString('≔'); CodePointA: 8788; CodePointB: 0),
(Name: UnicodeString('*'); CodePointA: 42; CodePointB: 0),
(Name: UnicodeString('≈'); CodePointA: 8776; CodePointB: 0),
(Name: UnicodeString('≍'); CodePointA: 8781; CodePointB: 0),
(Name: UnicodeString('Ã'); CodePointA: 195; CodePointB: 0),
(Name: UnicodeString('Ã'); CodePointA: 195; CodePointB: 0),
(Name: UnicodeString('ã'); CodePointA: 227; CodePointB: 0),
(Name: UnicodeString('ã'); CodePointA: 227; CodePointB: 0),
(Name: UnicodeString('Ä'); CodePointA: 196; CodePointB: 0),
(Name: UnicodeString('Ä'); CodePointA: 196; CodePointB: 0),
(Name: UnicodeString('ä'); CodePointA: 228; CodePointB: 0),
(Name: UnicodeString('ä'); CodePointA: 228; CodePointB: 0),
(Name: UnicodeString('∳'); CodePointA: 8755; CodePointB: 0),
(Name: UnicodeString('⨑'); CodePointA: 10769; CodePointB: 0),
(Name: UnicodeString('≌'); CodePointA: 8780; CodePointB: 0),
(Name: UnicodeString('϶'); CodePointA: 1014; CodePointB: 0),
(Name: UnicodeString('‵'); CodePointA: 8245; CodePointB: 0),
(Name: UnicodeString('∽'); CodePointA: 8765; CodePointB: 0),
(Name: UnicodeString('⋍'); CodePointA: 8909; CodePointB: 0),
(Name: UnicodeString('∖'); CodePointA: 8726; CodePointB: 0),
(Name: UnicodeString('⫧'); CodePointA: 10983; CodePointB: 0),
(Name: UnicodeString('⊽'); CodePointA: 8893; CodePointB: 0),
(Name: UnicodeString('⌅'); CodePointA: 8965; CodePointB: 0),
(Name: UnicodeString('⌆'); CodePointA: 8966; CodePointB: 0),
(Name: UnicodeString('⌅'); CodePointA: 8965; CodePointB: 0),
(Name: UnicodeString('⎵'); CodePointA: 9141; CodePointB: 0),
(Name: UnicodeString('⎶'); CodePointA: 9142; CodePointB: 0),
(Name: UnicodeString('≌'); CodePointA: 8780; CodePointB: 0),
(Name: UnicodeString('Б'); CodePointA: 1041; CodePointB: 0),
(Name: UnicodeString('б'); CodePointA: 1073; CodePointB: 0),
(Name: UnicodeString('„'); CodePointA: 8222; CodePointB: 0),
(Name: UnicodeString('∵'); CodePointA: 8757; CodePointB: 0),
(Name: UnicodeString('∵'); CodePointA: 8757; CodePointB: 0),
(Name: UnicodeString('∵'); CodePointA: 8757; CodePointB: 0),
(Name: UnicodeString('⦰'); CodePointA: 10672; CodePointB: 0),
(Name: UnicodeString('϶'); CodePointA: 1014; CodePointB: 0),
(Name: UnicodeString('ℬ'); CodePointA: 8492; CodePointB: 0),
(Name: UnicodeString('ℬ'); CodePointA: 8492; CodePointB: 0),
(Name: UnicodeString('Β'); CodePointA: 914; CodePointB: 0),
(Name: UnicodeString('β'); CodePointA: 946; CodePointB: 0),
(Name: UnicodeString('ℶ'); CodePointA: 8502; CodePointB: 0),
(Name: UnicodeString('≬'); CodePointA: 8812; CodePointB: 0),
(Name: UnicodeString('𝔅'); CodePointA: 120069; CodePointB: 0),
(Name: UnicodeString('𝔟'); CodePointA: 120095; CodePointB: 0),
(Name: UnicodeString('⋂'); CodePointA: 8898; CodePointB: 0),
(Name: UnicodeString('◯'); CodePointA: 9711; CodePointB: 0),
(Name: UnicodeString('⋃'); CodePointA: 8899; CodePointB: 0),
(Name: UnicodeString('⨀'); CodePointA: 10752; CodePointB: 0),
(Name: UnicodeString('⨁'); CodePointA: 10753; CodePointB: 0),
(Name: UnicodeString('⨂'); CodePointA: 10754; CodePointB: 0),
(Name: UnicodeString('⨆'); CodePointA: 10758; CodePointB: 0),
(Name: UnicodeString('★'); CodePointA: 9733; CodePointB: 0),
(Name: UnicodeString('▽'); CodePointA: 9661; CodePointB: 0),
(Name: UnicodeString('△'); CodePointA: 9651; CodePointB: 0),
(Name: UnicodeString('⨄'); CodePointA: 10756; CodePointB: 0),
(Name: UnicodeString('⋁'); CodePointA: 8897; CodePointB: 0),
(Name: UnicodeString('⋀'); CodePointA: 8896; CodePointB: 0),
(Name: UnicodeString('⤍'); CodePointA: 10509; CodePointB: 0),
(Name: UnicodeString('⧫'); CodePointA: 10731; CodePointB: 0),
(Name: UnicodeString('▪'); CodePointA: 9642; CodePointB: 0),
(Name: UnicodeString('▴'); CodePointA: 9652; CodePointB: 0),
(Name: UnicodeString('▾'); CodePointA: 9662; CodePointB: 0),
(Name: UnicodeString('◂'); CodePointA: 9666; CodePointB: 0),
(Name: UnicodeString('▸'); CodePointA: 9656; CodePointB: 0),
(Name: UnicodeString('␣'); CodePointA: 9251; CodePointB: 0),
(Name: UnicodeString('▒'); CodePointA: 9618; CodePointB: 0),
(Name: UnicodeString('░'); CodePointA: 9617; CodePointB: 0),
(Name: UnicodeString('▓'); CodePointA: 9619; CodePointB: 0),
(Name: UnicodeString('█'); CodePointA: 9608; CodePointB: 0),
(Name: UnicodeString('=⃥'); CodePointA: 61; CodePointB: 8421),
(Name: UnicodeString('≡⃥'); CodePointA: 8801; CodePointB: 8421),
(Name: UnicodeString('⫭'); CodePointA: 10989; CodePointB: 0),
(Name: UnicodeString('⌐'); CodePointA: 8976; CodePointB: 0),
(Name: UnicodeString('𝔹'); CodePointA: 120121; CodePointB: 0),
(Name: UnicodeString('𝕓'); CodePointA: 120147; CodePointB: 0),
(Name: UnicodeString('⊥'); CodePointA: 8869; CodePointB: 0),
(Name: UnicodeString('⊥'); CodePointA: 8869; CodePointB: 0),
(Name: UnicodeString('⋈'); CodePointA: 8904; CodePointB: 0),
(Name: UnicodeString('⧉'); CodePointA: 10697; CodePointB: 0),
(Name: UnicodeString('┐'); CodePointA: 9488; CodePointB: 0),
(Name: UnicodeString('╕'); CodePointA: 9557; CodePointB: 0),
(Name: UnicodeString('╖'); CodePointA: 9558; CodePointB: 0),
(Name: UnicodeString('╗'); CodePointA: 9559; CodePointB: 0),
(Name: UnicodeString('┌'); CodePointA: 9484; CodePointB: 0),
(Name: UnicodeString('╒'); CodePointA: 9554; CodePointB: 0),
(Name: UnicodeString('╓'); CodePointA: 9555; CodePointB: 0),
(Name: UnicodeString('╔'); CodePointA: 9556; CodePointB: 0),
(Name: UnicodeString('─'); CodePointA: 9472; CodePointB: 0),
(Name: UnicodeString('═'); CodePointA: 9552; CodePointB: 0),
(Name: UnicodeString('┬'); CodePointA: 9516; CodePointB: 0),
(Name: UnicodeString('╤'); CodePointA: 9572; CodePointB: 0),
(Name: UnicodeString('╥'); CodePointA: 9573; CodePointB: 0),
(Name: UnicodeString('╦'); CodePointA: 9574; CodePointB: 0),
(Name: UnicodeString('┴'); CodePointA: 9524; CodePointB: 0),
(Name: UnicodeString('╧'); CodePointA: 9575; CodePointB: 0),
(Name: UnicodeString('╨'); CodePointA: 9576; CodePointB: 0),
(Name: UnicodeString('╩'); CodePointA: 9577; CodePointB: 0),
(Name: UnicodeString('⊟'); CodePointA: 8863; CodePointB: 0),
(Name: UnicodeString('⊞'); CodePointA: 8862; CodePointB: 0),
(Name: UnicodeString('⊠'); CodePointA: 8864; CodePointB: 0),
(Name: UnicodeString('┘'); CodePointA: 9496; CodePointB: 0),
(Name: UnicodeString('╛'); CodePointA: 9563; CodePointB: 0),
(Name: UnicodeString('╜'); CodePointA: 9564; CodePointB: 0),
(Name: UnicodeString('╝'); CodePointA: 9565; CodePointB: 0),
(Name: UnicodeString('└'); CodePointA: 9492; CodePointB: 0),
(Name: UnicodeString('╘'); CodePointA: 9560; CodePointB: 0),
(Name: UnicodeString('╙'); CodePointA: 9561; CodePointB: 0),
(Name: UnicodeString('╚'); CodePointA: 9562; CodePointB: 0),
(Name: UnicodeString('│'); CodePointA: 9474; CodePointB: 0),
(Name: UnicodeString('║'); CodePointA: 9553; CodePointB: 0),
(Name: UnicodeString('┼'); CodePointA: 9532; CodePointB: 0),
(Name: UnicodeString('╪'); CodePointA: 9578; CodePointB: 0),
(Name: UnicodeString('╫'); CodePointA: 9579; CodePointB: 0),
(Name: UnicodeString('╬'); CodePointA: 9580; CodePointB: 0),
(Name: UnicodeString('┤'); CodePointA: 9508; CodePointB: 0),
(Name: UnicodeString('╡'); CodePointA: 9569; CodePointB: 0),
(Name: UnicodeString('╢'); CodePointA: 9570; CodePointB: 0),
(Name: UnicodeString('╣'); CodePointA: 9571; CodePointB: 0),
(Name: UnicodeString('├'); CodePointA: 9500; CodePointB: 0),
(Name: UnicodeString('╞'); CodePointA: 9566; CodePointB: 0),
(Name: UnicodeString('╟'); CodePointA: 9567; CodePointB: 0),
(Name: UnicodeString('╠'); CodePointA: 9568; CodePointB: 0),
(Name: UnicodeString('‵'); CodePointA: 8245; CodePointB: 0),
(Name: UnicodeString('˘'); CodePointA: 728; CodePointB: 0),
(Name: UnicodeString('˘'); CodePointA: 728; CodePointB: 0),
(Name: UnicodeString('¦'); CodePointA: 166; CodePointB: 0),
(Name: UnicodeString('¦'); CodePointA: 166; CodePointB: 0),
(Name: UnicodeString('𝒷'); CodePointA: 119991; CodePointB: 0),
(Name: UnicodeString('ℬ'); CodePointA: 8492; CodePointB: 0),
(Name: UnicodeString('⁏'); CodePointA: 8271; CodePointB: 0),
(Name: UnicodeString('∽'); CodePointA: 8765; CodePointB: 0),
(Name: UnicodeString('⋍'); CodePointA: 8909; CodePointB: 0),
(Name: UnicodeString('⧅'); CodePointA: 10693; CodePointB: 0),
(Name: UnicodeString('\'); CodePointA: 92; CodePointB: 0),
(Name: UnicodeString('⟈'); CodePointA: 10184; CodePointB: 0),
(Name: UnicodeString('•'); CodePointA: 8226; CodePointB: 0),
(Name: UnicodeString('•'); CodePointA: 8226; CodePointB: 0),
(Name: UnicodeString('≎'); CodePointA: 8782; CodePointB: 0),
(Name: UnicodeString('⪮'); CodePointA: 10926; CodePointB: 0),
(Name: UnicodeString('≏'); CodePointA: 8783; CodePointB: 0),
(Name: UnicodeString('≎'); CodePointA: 8782; CodePointB: 0),
(Name: UnicodeString('≏'); CodePointA: 8783; CodePointB: 0),
(Name: UnicodeString('Ć'); CodePointA: 262; CodePointB: 0),
(Name: UnicodeString('ć'); CodePointA: 263; CodePointB: 0),
(Name: UnicodeString('⩄'); CodePointA: 10820; CodePointB: 0),
(Name: UnicodeString('⩉'); CodePointA: 10825; CodePointB: 0),
(Name: UnicodeString('⩋'); CodePointA: 10827; CodePointB: 0),
(Name: UnicodeString('∩'); CodePointA: 8745; CodePointB: 0),
(Name: UnicodeString('⋒'); CodePointA: 8914; CodePointB: 0),
(Name: UnicodeString('⩇'); CodePointA: 10823; CodePointB: 0),
(Name: UnicodeString('⩀'); CodePointA: 10816; CodePointB: 0),
(Name: UnicodeString('ⅅ'); CodePointA: 8517; CodePointB: 0),
(Name: UnicodeString('∩︀'); CodePointA: 8745; CodePointB: 65024),
(Name: UnicodeString('⁁'); CodePointA: 8257; CodePointB: 0),
(Name: UnicodeString('ˇ'); CodePointA: 711; CodePointB: 0),
(Name: UnicodeString('ℭ'); CodePointA: 8493; CodePointB: 0),
(Name: UnicodeString('⩍'); CodePointA: 10829; CodePointB: 0),
(Name: UnicodeString('Č'); CodePointA: 268; CodePointB: 0),
(Name: UnicodeString('č'); CodePointA: 269; CodePointB: 0),
(Name: UnicodeString('Ç'); CodePointA: 199; CodePointB: 0),
(Name: UnicodeString('Ç'); CodePointA: 199; CodePointB: 0),
(Name: UnicodeString('ç'); CodePointA: 231; CodePointB: 0),
(Name: UnicodeString('ç'); CodePointA: 231; CodePointB: 0),
(Name: UnicodeString('Ĉ'); CodePointA: 264; CodePointB: 0),
(Name: UnicodeString('ĉ'); CodePointA: 265; CodePointB: 0),
(Name: UnicodeString('∰'); CodePointA: 8752; CodePointB: 0),
(Name: UnicodeString('⩌'); CodePointA: 10828; CodePointB: 0),
(Name: UnicodeString('⩐'); CodePointA: 10832; CodePointB: 0),
(Name: UnicodeString('Ċ'); CodePointA: 266; CodePointB: 0),
(Name: UnicodeString('ċ'); CodePointA: 267; CodePointB: 0),
(Name: UnicodeString('¸'); CodePointA: 184; CodePointB: 0),
(Name: UnicodeString('¸'); CodePointA: 184; CodePointB: 0),
(Name: UnicodeString('¸'); CodePointA: 184; CodePointB: 0),
(Name: UnicodeString('⦲'); CodePointA: 10674; CodePointB: 0),
(Name: UnicodeString('¢'); CodePointA: 162; CodePointB: 0),
(Name: UnicodeString('¢'); CodePointA: 162; CodePointB: 0),
(Name: UnicodeString('·'); CodePointA: 183; CodePointB: 0),
(Name: UnicodeString('·'); CodePointA: 183; CodePointB: 0),
(Name: UnicodeString('𝔠'); CodePointA: 120096; CodePointB: 0),
(Name: UnicodeString('ℭ'); CodePointA: 8493; CodePointB: 0),
(Name: UnicodeString('Ч'); CodePointA: 1063; CodePointB: 0),
(Name: UnicodeString('ч'); CodePointA: 1095; CodePointB: 0),
(Name: UnicodeString('✓'); CodePointA: 10003; CodePointB: 0),
(Name: UnicodeString('✓'); CodePointA: 10003; CodePointB: 0),
(Name: UnicodeString('Χ'); CodePointA: 935; CodePointB: 0),
(Name: UnicodeString('χ'); CodePointA: 967; CodePointB: 0),
(Name: UnicodeString('ˆ'); CodePointA: 710; CodePointB: 0),
(Name: UnicodeString('≗'); CodePointA: 8791; CodePointB: 0),
(Name: UnicodeString('↺'); CodePointA: 8634; CodePointB: 0),
(Name: UnicodeString('↻'); CodePointA: 8635; CodePointB: 0),
(Name: UnicodeString('⊛'); CodePointA: 8859; CodePointB: 0),
(Name: UnicodeString('⊚'); CodePointA: 8858; CodePointB: 0),
(Name: UnicodeString('⊝'); CodePointA: 8861; CodePointB: 0),
(Name: UnicodeString('⊙'); CodePointA: 8857; CodePointB: 0),
(Name: UnicodeString('®'); CodePointA: 174; CodePointB: 0),
(Name: UnicodeString('Ⓢ'); CodePointA: 9416; CodePointB: 0),
(Name: UnicodeString('⊖'); CodePointA: 8854; CodePointB: 0),
(Name: UnicodeString('⊕'); CodePointA: 8853; CodePointB: 0),
(Name: UnicodeString('⊗'); CodePointA: 8855; CodePointB: 0),
(Name: UnicodeString('○'); CodePointA: 9675; CodePointB: 0),
(Name: UnicodeString('⧃'); CodePointA: 10691; CodePointB: 0),
(Name: UnicodeString('≗'); CodePointA: 8791; CodePointB: 0),
(Name: UnicodeString('⨐'); CodePointA: 10768; CodePointB: 0),
(Name: UnicodeString('⫯'); CodePointA: 10991; CodePointB: 0),
(Name: UnicodeString('⧂'); CodePointA: 10690; CodePointB: 0),
(Name: UnicodeString('∲'); CodePointA: 8754; CodePointB: 0),
(Name: UnicodeString('”'); CodePointA: 8221; CodePointB: 0),
(Name: UnicodeString('’'); CodePointA: 8217; CodePointB: 0),
(Name: UnicodeString('♣'); CodePointA: 9827; CodePointB: 0),
(Name: UnicodeString('♣'); CodePointA: 9827; CodePointB: 0),
(Name: UnicodeString(':'); CodePointA: 58; CodePointB: 0),
(Name: UnicodeString('∷'); CodePointA: 8759; CodePointB: 0),
(Name: UnicodeString('⩴'); CodePointA: 10868; CodePointB: 0),
(Name: UnicodeString('≔'); CodePointA: 8788; CodePointB: 0),
(Name: UnicodeString('≔'); CodePointA: 8788; CodePointB: 0),
(Name: UnicodeString(','); CodePointA: 44; CodePointB: 0),
(Name: UnicodeString('@'); CodePointA: 64; CodePointB: 0),
(Name: UnicodeString('∁'); CodePointA: 8705; CodePointB: 0),
(Name: UnicodeString('∘'); CodePointA: 8728; CodePointB: 0),
(Name: UnicodeString('∁'); CodePointA: 8705; CodePointB: 0),
(Name: UnicodeString('ℂ'); CodePointA: 8450; CodePointB: 0),
(Name: UnicodeString('≅'); CodePointA: 8773; CodePointB: 0),
(Name: UnicodeString('⩭'); CodePointA: 10861; CodePointB: 0),
(Name: UnicodeString('≡'); CodePointA: 8801; CodePointB: 0),
(Name: UnicodeString('∮'); CodePointA: 8750; CodePointB: 0),
(Name: UnicodeString('∯'); CodePointA: 8751; CodePointB: 0),
(Name: UnicodeString('∮'); CodePointA: 8750; CodePointB: 0),
(Name: UnicodeString('𝕔'); CodePointA: 120148; CodePointB: 0),
(Name: UnicodeString('ℂ'); CodePointA: 8450; CodePointB: 0),
(Name: UnicodeString('∐'); CodePointA: 8720; CodePointB: 0),
(Name: UnicodeString('∐'); CodePointA: 8720; CodePointB: 0),
(Name: UnicodeString('©'); CodePointA: 169; CodePointB: 0),
(Name: UnicodeString('©'); CodePointA: 169; CodePointB: 0),
(Name: UnicodeString('©'); CodePointA: 169; CodePointB: 0),
(Name: UnicodeString('©'); CodePointA: 169; CodePointB: 0),
(Name: UnicodeString('℗'); CodePointA: 8471; CodePointB: 0),
(Name: UnicodeString('∳'); CodePointA: 8755; CodePointB: 0),
(Name: UnicodeString('↵'); CodePointA: 8629; CodePointB: 0),
(Name: UnicodeString('✗'); CodePointA: 10007; CodePointB: 0),
(Name: UnicodeString('⨯'); CodePointA: 10799; CodePointB: 0),
(Name: UnicodeString('𝒞'); CodePointA: 119966; CodePointB: 0),
(Name: UnicodeString('𝒸'); CodePointA: 119992; CodePointB: 0),
(Name: UnicodeString('⫏'); CodePointA: 10959; CodePointB: 0),
(Name: UnicodeString('⫑'); CodePointA: 10961; CodePointB: 0),
(Name: UnicodeString('⫐'); CodePointA: 10960; CodePointB: 0),
(Name: UnicodeString('⫒'); CodePointA: 10962; CodePointB: 0),
(Name: UnicodeString('⋯'); CodePointA: 8943; CodePointB: 0),
(Name: UnicodeString('⤸'); CodePointA: 10552; CodePointB: 0),
(Name: UnicodeString('⤵'); CodePointA: 10549; CodePointB: 0),
(Name: UnicodeString('⋞'); CodePointA: 8926; CodePointB: 0),
(Name: UnicodeString('⋟'); CodePointA: 8927; CodePointB: 0),
(Name: UnicodeString('↶'); CodePointA: 8630; CodePointB: 0),
(Name: UnicodeString('⤽'); CodePointA: 10557; CodePointB: 0),
(Name: UnicodeString('⩈'); CodePointA: 10824; CodePointB: 0),
(Name: UnicodeString('⩆'); CodePointA: 10822; CodePointB: 0),
(Name: UnicodeString('≍'); CodePointA: 8781; CodePointB: 0),
(Name: UnicodeString('∪'); CodePointA: 8746; CodePointB: 0),
(Name: UnicodeString('⋓'); CodePointA: 8915; CodePointB: 0),
(Name: UnicodeString('⩊'); CodePointA: 10826; CodePointB: 0),
(Name: UnicodeString('⊍'); CodePointA: 8845; CodePointB: 0),
(Name: UnicodeString('⩅'); CodePointA: 10821; CodePointB: 0),
(Name: UnicodeString('∪︀'); CodePointA: 8746; CodePointB: 65024),
(Name: UnicodeString('↷'); CodePointA: 8631; CodePointB: 0),
(Name: UnicodeString('⤼'); CodePointA: 10556; CodePointB: 0),
(Name: UnicodeString('⋞'); CodePointA: 8926; CodePointB: 0),
(Name: UnicodeString('⋟'); CodePointA: 8927; CodePointB: 0),
(Name: UnicodeString('⋎'); CodePointA: 8910; CodePointB: 0),
(Name: UnicodeString('⋏'); CodePointA: 8911; CodePointB: 0),
(Name: UnicodeString('¤'); CodePointA: 164; CodePointB: 0),
(Name: UnicodeString('¤'); CodePointA: 164; CodePointB: 0),
(Name: UnicodeString('↶'); CodePointA: 8630; CodePointB: 0),
(Name: UnicodeString('↷'); CodePointA: 8631; CodePointB: 0),
(Name: UnicodeString('⋎'); CodePointA: 8910; CodePointB: 0),
(Name: UnicodeString('⋏'); CodePointA: 8911; CodePointB: 0),
(Name: UnicodeString('∲'); CodePointA: 8754; CodePointB: 0),
(Name: UnicodeString('∱'); CodePointA: 8753; CodePointB: 0),
(Name: UnicodeString('⌭'); CodePointA: 9005; CodePointB: 0),
(Name: UnicodeString('†'); CodePointA: 8224; CodePointB: 0),
(Name: UnicodeString('‡'); CodePointA: 8225; CodePointB: 0),
(Name: UnicodeString('ℸ'); CodePointA: 8504; CodePointB: 0),
(Name: UnicodeString('↓'); CodePointA: 8595; CodePointB: 0),
(Name: UnicodeString('↡'); CodePointA: 8609; CodePointB: 0),
(Name: UnicodeString('⇓'); CodePointA: 8659; CodePointB: 0),
(Name: UnicodeString('‐'); CodePointA: 8208; CodePointB: 0),
(Name: UnicodeString('⫤'); CodePointA: 10980; CodePointB: 0),
(Name: UnicodeString('⊣'); CodePointA: 8867; CodePointB: 0),
(Name: UnicodeString('⤏'); CodePointA: 10511; CodePointB: 0),
(Name: UnicodeString('˝'); CodePointA: 733; CodePointB: 0),
(Name: UnicodeString('Ď'); CodePointA: 270; CodePointB: 0),
(Name: UnicodeString('ď'); CodePointA: 271; CodePointB: 0),
(Name: UnicodeString('Д'); CodePointA: 1044; CodePointB: 0),
(Name: UnicodeString('д'); CodePointA: 1076; CodePointB: 0),
(Name: UnicodeString('‡'); CodePointA: 8225; CodePointB: 0),
(Name: UnicodeString('⇊'); CodePointA: 8650; CodePointB: 0),
(Name: UnicodeString('ⅅ'); CodePointA: 8517; CodePointB: 0),
(Name: UnicodeString('ⅆ'); CodePointA: 8518; CodePointB: 0),
(Name: UnicodeString('⤑'); CodePointA: 10513; CodePointB: 0),
(Name: UnicodeString('⩷'); CodePointA: 10871; CodePointB: 0),
(Name: UnicodeString('°'); CodePointA: 176; CodePointB: 0),
(Name: UnicodeString('°'); CodePointA: 176; CodePointB: 0),
(Name: UnicodeString('∇'); CodePointA: 8711; CodePointB: 0),
(Name: UnicodeString('Δ'); CodePointA: 916; CodePointB: 0),
(Name: UnicodeString('δ'); CodePointA: 948; CodePointB: 0),
(Name: UnicodeString('⦱'); CodePointA: 10673; CodePointB: 0),
(Name: UnicodeString('⥿'); CodePointA: 10623; CodePointB: 0),
(Name: UnicodeString('𝔇'); CodePointA: 120071; CodePointB: 0),
(Name: UnicodeString('𝔡'); CodePointA: 120097; CodePointB: 0),
(Name: UnicodeString('⥥'); CodePointA: 10597; CodePointB: 0),
(Name: UnicodeString('⇃'); CodePointA: 8643; CodePointB: 0),
(Name: UnicodeString('⇂'); CodePointA: 8642; CodePointB: 0),
(Name: UnicodeString('´'); CodePointA: 180; CodePointB: 0),
(Name: UnicodeString('˙'); CodePointA: 729; CodePointB: 0),
(Name: UnicodeString('˝'); CodePointA: 733; CodePointB: 0),
(Name: UnicodeString('`'); CodePointA: 96; CodePointB: 0),
(Name: UnicodeString('˜'); CodePointA: 732; CodePointB: 0),
(Name: UnicodeString('⋄'); CodePointA: 8900; CodePointB: 0),
(Name: UnicodeString('⋄'); CodePointA: 8900; CodePointB: 0),
(Name: UnicodeString('⋄'); CodePointA: 8900; CodePointB: 0),
(Name: UnicodeString('♦'); CodePointA: 9830; CodePointB: 0),
(Name: UnicodeString('♦'); CodePointA: 9830; CodePointB: 0),
(Name: UnicodeString('¨'); CodePointA: 168; CodePointB: 0),
(Name: UnicodeString('ⅆ'); CodePointA: 8518; CodePointB: 0),
(Name: UnicodeString('ϝ'); CodePointA: 989; CodePointB: 0),
(Name: UnicodeString('⋲'); CodePointA: 8946; CodePointB: 0),
(Name: UnicodeString('÷'); CodePointA: 247; CodePointB: 0),
(Name: UnicodeString('÷'); CodePointA: 247; CodePointB: 0),
(Name: UnicodeString('÷'); CodePointA: 247; CodePointB: 0),
(Name: UnicodeString('⋇'); CodePointA: 8903; CodePointB: 0),
(Name: UnicodeString('⋇'); CodePointA: 8903; CodePointB: 0),
(Name: UnicodeString('Ђ'); CodePointA: 1026; CodePointB: 0),
(Name: UnicodeString('ђ'); CodePointA: 1106; CodePointB: 0),
(Name: UnicodeString('⌞'); CodePointA: 8990; CodePointB: 0),
(Name: UnicodeString('⌍'); CodePointA: 8973; CodePointB: 0),
(Name: UnicodeString('$'); CodePointA: 36; CodePointB: 0),
(Name: UnicodeString('𝔻'); CodePointA: 120123; CodePointB: 0),
(Name: UnicodeString('𝕕'); CodePointA: 120149; CodePointB: 0),
(Name: UnicodeString('¨'); CodePointA: 168; CodePointB: 0),
(Name: UnicodeString('˙'); CodePointA: 729; CodePointB: 0),
(Name: UnicodeString('⃜'); CodePointA: 8412; CodePointB: 0),
(Name: UnicodeString('≐'); CodePointA: 8784; CodePointB: 0),
(Name: UnicodeString('≑'); CodePointA: 8785; CodePointB: 0),
(Name: UnicodeString('≐'); CodePointA: 8784; CodePointB: 0),
(Name: UnicodeString('∸'); CodePointA: 8760; CodePointB: 0),
(Name: UnicodeString('∔'); CodePointA: 8724; CodePointB: 0),
(Name: UnicodeString('⊡'); CodePointA: 8865; CodePointB: 0),
(Name: UnicodeString('⌆'); CodePointA: 8966; CodePointB: 0),
(Name: UnicodeString('∯'); CodePointA: 8751; CodePointB: 0),
(Name: UnicodeString('¨'); CodePointA: 168; CodePointB: 0),
(Name: UnicodeString('⇓'); CodePointA: 8659; CodePointB: 0),
(Name: UnicodeString('⇐'); CodePointA: 8656; CodePointB: 0),
(Name: UnicodeString('⇔'); CodePointA: 8660; CodePointB: 0),
(Name: UnicodeString('⫤'); CodePointA: 10980; CodePointB: 0),
(Name: UnicodeString('⟸'); CodePointA: 10232; CodePointB: 0),
(Name: UnicodeString('⟺'); CodePointA: 10234; CodePointB: 0),
(Name: UnicodeString('⟹'); CodePointA: 10233; CodePointB: 0),
(Name: UnicodeString('⇒'); CodePointA: 8658; CodePointB: 0),
(Name: UnicodeString('⊨'); CodePointA: 8872; CodePointB: 0),
(Name: UnicodeString('⇑'); CodePointA: 8657; CodePointB: 0),
(Name: UnicodeString('⇕'); CodePointA: 8661; CodePointB: 0),
(Name: UnicodeString('∥'); CodePointA: 8741; CodePointB: 0),
(Name: UnicodeString('⤓'); CodePointA: 10515; CodePointB: 0),
(Name: UnicodeString('↓'); CodePointA: 8595; CodePointB: 0),
(Name: UnicodeString('↓'); CodePointA: 8595; CodePointB: 0),
(Name: UnicodeString('⇓'); CodePointA: 8659; CodePointB: 0),
(Name: UnicodeString('⇵'); CodePointA: 8693; CodePointB: 0),
(Name: UnicodeString('̑'); CodePointA: 785; CodePointB: 0),
(Name: UnicodeString('⇊'); CodePointA: 8650; CodePointB: 0),
(Name: UnicodeString('⇃'); CodePointA: 8643; CodePointB: 0),
(Name: UnicodeString('⇂'); CodePointA: 8642; CodePointB: 0),
(Name: UnicodeString('⥐'); CodePointA: 10576; CodePointB: 0),
(Name: UnicodeString('⥞'); CodePointA: 10590; CodePointB: 0),
(Name: UnicodeString('⥖'); CodePointA: 10582; CodePointB: 0),
(Name: UnicodeString('↽'); CodePointA: 8637; CodePointB: 0),
(Name: UnicodeString('⥟'); CodePointA: 10591; CodePointB: 0),
(Name: UnicodeString('⥗'); CodePointA: 10583; CodePointB: 0),
(Name: UnicodeString('⇁'); CodePointA: 8641; CodePointB: 0),
(Name: UnicodeString('↧'); CodePointA: 8615; CodePointB: 0),
(Name: UnicodeString('⊤'); CodePointA: 8868; CodePointB: 0),
(Name: UnicodeString('⤐'); CodePointA: 10512; CodePointB: 0),
(Name: UnicodeString('⌟'); CodePointA: 8991; CodePointB: 0),
(Name: UnicodeString('⌌'); CodePointA: 8972; CodePointB: 0),
(Name: UnicodeString('𝒟'); CodePointA: 119967; CodePointB: 0),
(Name: UnicodeString('𝒹'); CodePointA: 119993; CodePointB: 0),
(Name: UnicodeString('Ѕ'); CodePointA: 1029; CodePointB: 0),
(Name: UnicodeString('ѕ'); CodePointA: 1109; CodePointB: 0),
(Name: UnicodeString('⧶'); CodePointA: 10742; CodePointB: 0),
(Name: UnicodeString('Đ'); CodePointA: 272; CodePointB: 0),
(Name: UnicodeString('đ'); CodePointA: 273; CodePointB: 0),
(Name: UnicodeString('⋱'); CodePointA: 8945; CodePointB: 0),
(Name: UnicodeString('▿'); CodePointA: 9663; CodePointB: 0),
(Name: UnicodeString('▾'); CodePointA: 9662; CodePointB: 0),
(Name: UnicodeString('⇵'); CodePointA: 8693; CodePointB: 0),
(Name: UnicodeString('⥯'); CodePointA: 10607; CodePointB: 0),
(Name: UnicodeString('⦦'); CodePointA: 10662; CodePointB: 0),
(Name: UnicodeString('Џ'); CodePointA: 1039; CodePointB: 0),
(Name: UnicodeString('џ'); CodePointA: 1119; CodePointB: 0),
(Name: UnicodeString('⟿'); CodePointA: 10239; CodePointB: 0),
(Name: UnicodeString('É'); CodePointA: 201; CodePointB: 0),
(Name: UnicodeString('É'); CodePointA: 201; CodePointB: 0),
(Name: UnicodeString('é'); CodePointA: 233; CodePointB: 0),
(Name: UnicodeString('é'); CodePointA: 233; CodePointB: 0),
(Name: UnicodeString('⩮'); CodePointA: 10862; CodePointB: 0),
(Name: UnicodeString('Ě'); CodePointA: 282; CodePointB: 0),
(Name: UnicodeString('ě'); CodePointA: 283; CodePointB: 0),
(Name: UnicodeString('Ê'); CodePointA: 202; CodePointB: 0),
(Name: UnicodeString('Ê'); CodePointA: 202; CodePointB: 0),
(Name: UnicodeString('ê'); CodePointA: 234; CodePointB: 0),
(Name: UnicodeString('ê'); CodePointA: 234; CodePointB: 0),
(Name: UnicodeString('≖'); CodePointA: 8790; CodePointB: 0),
(Name: UnicodeString('≕'); CodePointA: 8789; CodePointB: 0),
(Name: UnicodeString('Э'); CodePointA: 1069; CodePointB: 0),
(Name: UnicodeString('э'); CodePointA: 1101; CodePointB: 0),
(Name: UnicodeString('⩷'); CodePointA: 10871; CodePointB: 0),
(Name: UnicodeString('Ė'); CodePointA: 278; CodePointB: 0),
(Name: UnicodeString('ė'); CodePointA: 279; CodePointB: 0),
(Name: UnicodeString('≑'); CodePointA: 8785; CodePointB: 0),
(Name: UnicodeString('ⅇ'); CodePointA: 8519; CodePointB: 0),
(Name: UnicodeString('≒'); CodePointA: 8786; CodePointB: 0),
(Name: UnicodeString('𝔈'); CodePointA: 120072; CodePointB: 0),
(Name: UnicodeString('𝔢'); CodePointA: 120098; CodePointB: 0),
(Name: UnicodeString('⪚'); CodePointA: 10906; CodePointB: 0),
(Name: UnicodeString('È'); CodePointA: 200; CodePointB: 0),
(Name: UnicodeString('È'); CodePointA: 200; CodePointB: 0),
(Name: UnicodeString('è'); CodePointA: 232; CodePointB: 0),
(Name: UnicodeString('è'); CodePointA: 232; CodePointB: 0),
(Name: UnicodeString('⪖'); CodePointA: 10902; CodePointB: 0),
(Name: UnicodeString('⪘'); CodePointA: 10904; CodePointB: 0),
(Name: UnicodeString('⪙'); CodePointA: 10905; CodePointB: 0),
(Name: UnicodeString('∈'); CodePointA: 8712; CodePointB: 0),
(Name: UnicodeString('⏧'); CodePointA: 9191; CodePointB: 0),
(Name: UnicodeString('ℓ'); CodePointA: 8467; CodePointB: 0),
(Name: UnicodeString('⪕'); CodePointA: 10901; CodePointB: 0),
(Name: UnicodeString('⪗'); CodePointA: 10903; CodePointB: 0),
(Name: UnicodeString('Ē'); CodePointA: 274; CodePointB: 0),
(Name: UnicodeString('ē'); CodePointA: 275; CodePointB: 0),
(Name: UnicodeString('∅'); CodePointA: 8709; CodePointB: 0),
(Name: UnicodeString('∅'); CodePointA: 8709; CodePointB: 0),
(Name: UnicodeString('◻'); CodePointA: 9723; CodePointB: 0),
(Name: UnicodeString('∅'); CodePointA: 8709; CodePointB: 0),
(Name: UnicodeString('▫'); CodePointA: 9643; CodePointB: 0),
(Name: UnicodeString(' '); CodePointA: 8196; CodePointB: 0),
(Name: UnicodeString(' '); CodePointA: 8197; CodePointB: 0),
(Name: UnicodeString(' '); CodePointA: 8195; CodePointB: 0),
(Name: UnicodeString('Ŋ'); CodePointA: 330; CodePointB: 0),
(Name: UnicodeString('ŋ'); CodePointA: 331; CodePointB: 0),
(Name: UnicodeString(' '); CodePointA: 8194; CodePointB: 0),
(Name: UnicodeString('Ę'); CodePointA: 280; CodePointB: 0),
(Name: UnicodeString('ę'); CodePointA: 281; CodePointB: 0),
(Name: UnicodeString('𝔼'); CodePointA: 120124; CodePointB: 0),
(Name: UnicodeString('𝕖'); CodePointA: 120150; CodePointB: 0),
(Name: UnicodeString('⋕'); CodePointA: 8917; CodePointB: 0),
(Name: UnicodeString('⧣'); CodePointA: 10723; CodePointB: 0),
(Name: UnicodeString('⩱'); CodePointA: 10865; CodePointB: 0),
(Name: UnicodeString('ε'); CodePointA: 949; CodePointB: 0),
(Name: UnicodeString('Ε'); CodePointA: 917; CodePointB: 0),
(Name: UnicodeString('ε'); CodePointA: 949; CodePointB: 0),
(Name: UnicodeString('ϵ'); CodePointA: 1013; CodePointB: 0),
(Name: UnicodeString('≖'); CodePointA: 8790; CodePointB: 0),
(Name: UnicodeString('≕'); CodePointA: 8789; CodePointB: 0),
(Name: UnicodeString('≂'); CodePointA: 8770; CodePointB: 0),
(Name: UnicodeString('⪖'); CodePointA: 10902; CodePointB: 0),
(Name: UnicodeString('⪕'); CodePointA: 10901; CodePointB: 0),
(Name: UnicodeString('⩵'); CodePointA: 10869; CodePointB: 0),
(Name: UnicodeString('='); CodePointA: 61; CodePointB: 0),
(Name: UnicodeString('≂'); CodePointA: 8770; CodePointB: 0),
(Name: UnicodeString('≟'); CodePointA: 8799; CodePointB: 0),
(Name: UnicodeString('⇌'); CodePointA: 8652; CodePointB: 0),
(Name: UnicodeString('≡'); CodePointA: 8801; CodePointB: 0),
(Name: UnicodeString('⩸'); CodePointA: 10872; CodePointB: 0),
(Name: UnicodeString('⧥'); CodePointA: 10725; CodePointB: 0),
(Name: UnicodeString('⥱'); CodePointA: 10609; CodePointB: 0),
(Name: UnicodeString('≓'); CodePointA: 8787; CodePointB: 0),
(Name: UnicodeString('ℯ'); CodePointA: 8495; CodePointB: 0),
(Name: UnicodeString('ℰ'); CodePointA: 8496; CodePointB: 0),
(Name: UnicodeString('≐'); CodePointA: 8784; CodePointB: 0),
(Name: UnicodeString('⩳'); CodePointA: 10867; CodePointB: 0),
(Name: UnicodeString('≂'); CodePointA: 8770; CodePointB: 0),
(Name: UnicodeString('Η'); CodePointA: 919; CodePointB: 0),
(Name: UnicodeString('η'); CodePointA: 951; CodePointB: 0),
(Name: UnicodeString('Ð'); CodePointA: 208; CodePointB: 0),
(Name: UnicodeString('Ð'); CodePointA: 208; CodePointB: 0),
(Name: UnicodeString('ð'); CodePointA: 240; CodePointB: 0),
(Name: UnicodeString('ð'); CodePointA: 240; CodePointB: 0),
(Name: UnicodeString('Ë'); CodePointA: 203; CodePointB: 0),
(Name: UnicodeString('Ë'); CodePointA: 203; CodePointB: 0),
(Name: UnicodeString('ë'); CodePointA: 235; CodePointB: 0),
(Name: UnicodeString('ë'); CodePointA: 235; CodePointB: 0),
(Name: UnicodeString('€'); CodePointA: 8364; CodePointB: 0),
(Name: UnicodeString('!'); CodePointA: 33; CodePointB: 0),
(Name: UnicodeString('∃'); CodePointA: 8707; CodePointB: 0),
(Name: UnicodeString('∃'); CodePointA: 8707; CodePointB: 0),
(Name: UnicodeString('ℰ'); CodePointA: 8496; CodePointB: 0),
(Name: UnicodeString('ⅇ'); CodePointA: 8519; CodePointB: 0),
(Name: UnicodeString('ⅇ'); CodePointA: 8519; CodePointB: 0),
(Name: UnicodeString('≒'); CodePointA: 8786; CodePointB: 0),
(Name: UnicodeString('Ф'); CodePointA: 1060; CodePointB: 0),
(Name: UnicodeString('ф'); CodePointA: 1092; CodePointB: 0),
(Name: UnicodeString('♀'); CodePointA: 9792; CodePointB: 0),
(Name: UnicodeString('ffi'); CodePointA: 64259; CodePointB: 0),
(Name: UnicodeString('ff'); CodePointA: 64256; CodePointB: 0),
(Name: UnicodeString('ffl'); CodePointA: 64260; CodePointB: 0),
(Name: UnicodeString('𝔉'); CodePointA: 120073; CodePointB: 0),
(Name: UnicodeString('𝔣'); CodePointA: 120099; CodePointB: 0),
(Name: UnicodeString('fi'); CodePointA: 64257; CodePointB: 0),
(Name: UnicodeString('◼'); CodePointA: 9724; CodePointB: 0),
(Name: UnicodeString('▪'); CodePointA: 9642; CodePointB: 0),
(Name: UnicodeString('fj'); CodePointA: 102; CodePointB: 106),
(Name: UnicodeString('♭'); CodePointA: 9837; CodePointB: 0),
(Name: UnicodeString('fl'); CodePointA: 64258; CodePointB: 0),
(Name: UnicodeString('▱'); CodePointA: 9649; CodePointB: 0),
(Name: UnicodeString('ƒ'); CodePointA: 402; CodePointB: 0),
(Name: UnicodeString('𝔽'); CodePointA: 120125; CodePointB: 0),
(Name: UnicodeString('𝕗'); CodePointA: 120151; CodePointB: 0),
(Name: UnicodeString('∀'); CodePointA: 8704; CodePointB: 0),
(Name: UnicodeString('∀'); CodePointA: 8704; CodePointB: 0),
(Name: UnicodeString('⋔'); CodePointA: 8916; CodePointB: 0),
(Name: UnicodeString('⫙'); CodePointA: 10969; CodePointB: 0),
(Name: UnicodeString('ℱ'); CodePointA: 8497; CodePointB: 0),
(Name: UnicodeString('⨍'); CodePointA: 10765; CodePointB: 0),
(Name: UnicodeString('½'); CodePointA: 189; CodePointB: 0),
(Name: UnicodeString('½'); CodePointA: 189; CodePointB: 0),
(Name: UnicodeString('⅓'); CodePointA: 8531; CodePointB: 0),
(Name: UnicodeString('¼'); CodePointA: 188; CodePointB: 0),
(Name: UnicodeString('¼'); CodePointA: 188; CodePointB: 0),
(Name: UnicodeString('⅕'); CodePointA: 8533; CodePointB: 0),
(Name: UnicodeString('⅙'); CodePointA: 8537; CodePointB: 0),
(Name: UnicodeString('⅛'); CodePointA: 8539; CodePointB: 0),
(Name: UnicodeString('⅔'); CodePointA: 8532; CodePointB: 0),
(Name: UnicodeString('⅖'); CodePointA: 8534; CodePointB: 0),
(Name: UnicodeString('¾'); CodePointA: 190; CodePointB: 0),
(Name: UnicodeString('¾'); CodePointA: 190; CodePointB: 0),
(Name: UnicodeString('⅗'); CodePointA: 8535; CodePointB: 0),
(Name: UnicodeString('⅜'); CodePointA: 8540; CodePointB: 0),
(Name: UnicodeString('⅘'); CodePointA: 8536; CodePointB: 0),
(Name: UnicodeString('⅚'); CodePointA: 8538; CodePointB: 0),
(Name: UnicodeString('⅝'); CodePointA: 8541; CodePointB: 0),
(Name: UnicodeString('⅞'); CodePointA: 8542; CodePointB: 0),
(Name: UnicodeString('⁄'); CodePointA: 8260; CodePointB: 0),
(Name: UnicodeString('⌢'); CodePointA: 8994; CodePointB: 0),
(Name: UnicodeString('𝒻'); CodePointA: 119995; CodePointB: 0),
(Name: UnicodeString('ℱ'); CodePointA: 8497; CodePointB: 0),
(Name: UnicodeString('ǵ'); CodePointA: 501; CodePointB: 0),
(Name: UnicodeString('Γ'); CodePointA: 915; CodePointB: 0),
(Name: UnicodeString('γ'); CodePointA: 947; CodePointB: 0),
(Name: UnicodeString('Ϝ'); CodePointA: 988; CodePointB: 0),
(Name: UnicodeString('ϝ'); CodePointA: 989; CodePointB: 0),
(Name: UnicodeString('⪆'); CodePointA: 10886; CodePointB: 0),
(Name: UnicodeString('Ğ'); CodePointA: 286; CodePointB: 0),
(Name: UnicodeString('ğ'); CodePointA: 287; CodePointB: 0),
(Name: UnicodeString('Ģ'); CodePointA: 290; CodePointB: 0),
(Name: UnicodeString('Ĝ'); CodePointA: 284; CodePointB: 0),
(Name: UnicodeString('ĝ'); CodePointA: 285; CodePointB: 0),
(Name: UnicodeString('Г'); CodePointA: 1043; CodePointB: 0),
(Name: UnicodeString('г'); CodePointA: 1075; CodePointB: 0),
(Name: UnicodeString('Ġ'); CodePointA: 288; CodePointB: 0),
(Name: UnicodeString('ġ'); CodePointA: 289; CodePointB: 0),
(Name: UnicodeString('≥'); CodePointA: 8805; CodePointB: 0),
(Name: UnicodeString('≧'); CodePointA: 8807; CodePointB: 0),
(Name: UnicodeString('⪌'); CodePointA: 10892; CodePointB: 0),
(Name: UnicodeString('⋛'); CodePointA: 8923; CodePointB: 0),
(Name: UnicodeString('≥'); CodePointA: 8805; CodePointB: 0),
(Name: UnicodeString('≧'); CodePointA: 8807; CodePointB: 0),
(Name: UnicodeString('⩾'); CodePointA: 10878; CodePointB: 0),
(Name: UnicodeString('⪩'); CodePointA: 10921; CodePointB: 0),
(Name: UnicodeString('⩾'); CodePointA: 10878; CodePointB: 0),
(Name: UnicodeString('⪀'); CodePointA: 10880; CodePointB: 0),
(Name: UnicodeString('⪂'); CodePointA: 10882; CodePointB: 0),
(Name: UnicodeString('⪄'); CodePointA: 10884; CodePointB: 0),
(Name: UnicodeString('⋛︀'); CodePointA: 8923; CodePointB: 65024),
(Name: UnicodeString('⪔'); CodePointA: 10900; CodePointB: 0),
(Name: UnicodeString('𝔊'); CodePointA: 120074; CodePointB: 0),
(Name: UnicodeString('𝔤'); CodePointA: 120100; CodePointB: 0),
(Name: UnicodeString('≫'); CodePointA: 8811; CodePointB: 0),
(Name: UnicodeString('⋙'); CodePointA: 8921; CodePointB: 0),
(Name: UnicodeString('⋙'); CodePointA: 8921; CodePointB: 0),
(Name: UnicodeString('ℷ'); CodePointA: 8503; CodePointB: 0),
(Name: UnicodeString('Ѓ'); CodePointA: 1027; CodePointB: 0),
(Name: UnicodeString('ѓ'); CodePointA: 1107; CodePointB: 0),
(Name: UnicodeString('⪥'); CodePointA: 10917; CodePointB: 0),
(Name: UnicodeString('≷'); CodePointA: 8823; CodePointB: 0),
(Name: UnicodeString('⪒'); CodePointA: 10898; CodePointB: 0),
(Name: UnicodeString('⪤'); CodePointA: 10916; CodePointB: 0),
(Name: UnicodeString('⪊'); CodePointA: 10890; CodePointB: 0),
(Name: UnicodeString('⪊'); CodePointA: 10890; CodePointB: 0),
(Name: UnicodeString('⪈'); CodePointA: 10888; CodePointB: 0),
(Name: UnicodeString('≩'); CodePointA: 8809; CodePointB: 0),
(Name: UnicodeString('⪈'); CodePointA: 10888; CodePointB: 0),
(Name: UnicodeString('≩'); CodePointA: 8809; CodePointB: 0),
(Name: UnicodeString('⋧'); CodePointA: 8935; CodePointB: 0),
(Name: UnicodeString('𝔾'); CodePointA: 120126; CodePointB: 0),
(Name: UnicodeString('𝕘'); CodePointA: 120152; CodePointB: 0),
(Name: UnicodeString('`'); CodePointA: 96; CodePointB: 0),
(Name: UnicodeString('≥'); CodePointA: 8805; CodePointB: 0),
(Name: UnicodeString('⋛'); CodePointA: 8923; CodePointB: 0),
(Name: UnicodeString('≧'); CodePointA: 8807; CodePointB: 0),
(Name: UnicodeString('⪢'); CodePointA: 10914; CodePointB: 0),
(Name: UnicodeString('≷'); CodePointA: 8823; CodePointB: 0),
(Name: UnicodeString('⩾'); CodePointA: 10878; CodePointB: 0),
(Name: UnicodeString('≳'); CodePointA: 8819; CodePointB: 0),
(Name: UnicodeString('𝒢'); CodePointA: 119970; CodePointB: 0),
(Name: UnicodeString('ℊ'); CodePointA: 8458; CodePointB: 0),
(Name: UnicodeString('≳'); CodePointA: 8819; CodePointB: 0),
(Name: UnicodeString('⪎'); CodePointA: 10894; CodePointB: 0),
(Name: UnicodeString('⪐'); CodePointA: 10896; CodePointB: 0),
(Name: UnicodeString('⪧'); CodePointA: 10919; CodePointB: 0),
(Name: UnicodeString('⩺'); CodePointA: 10874; CodePointB: 0),
(Name: UnicodeString('>'); CodePointA: 62; CodePointB: 0),
(Name: UnicodeString('>'); CodePointA: 62; CodePointB: 0),
(Name: UnicodeString('>'); CodePointA: 62; CodePointB: 0),
(Name: UnicodeString('>'); CodePointA: 62; CodePointB: 0),
(Name: UnicodeString('≫'); CodePointA: 8811; CodePointB: 0),
(Name: UnicodeString('⋗'); CodePointA: 8919; CodePointB: 0),
(Name: UnicodeString('⦕'); CodePointA: 10645; CodePointB: 0),
(Name: UnicodeString('⩼'); CodePointA: 10876; CodePointB: 0),
(Name: UnicodeString('⪆'); CodePointA: 10886; CodePointB: 0),
(Name: UnicodeString('⥸'); CodePointA: 10616; CodePointB: 0),
(Name: UnicodeString('⋗'); CodePointA: 8919; CodePointB: 0),
(Name: UnicodeString('⋛'); CodePointA: 8923; CodePointB: 0),
(Name: UnicodeString('⪌'); CodePointA: 10892; CodePointB: 0),
(Name: UnicodeString('≷'); CodePointA: 8823; CodePointB: 0),
(Name: UnicodeString('≳'); CodePointA: 8819; CodePointB: 0),
(Name: UnicodeString('≩︀'); CodePointA: 8809; CodePointB: 65024),
(Name: UnicodeString('≩︀'); CodePointA: 8809; CodePointB: 65024),
(Name: UnicodeString('ˇ'); CodePointA: 711; CodePointB: 0),
(Name: UnicodeString(' '); CodePointA: 8202; CodePointB: 0),
(Name: UnicodeString('½'); CodePointA: 189; CodePointB: 0),
(Name: UnicodeString('ℋ'); CodePointA: 8459; CodePointB: 0),
(Name: UnicodeString('Ъ'); CodePointA: 1066; CodePointB: 0),
(Name: UnicodeString('ъ'); CodePointA: 1098; CodePointB: 0),
(Name: UnicodeString('⥈'); CodePointA: 10568; CodePointB: 0),
(Name: UnicodeString('↔'); CodePointA: 8596; CodePointB: 0),
(Name: UnicodeString('⇔'); CodePointA: 8660; CodePointB: 0),
(Name: UnicodeString('↭'); CodePointA: 8621; CodePointB: 0),
(Name: UnicodeString('^'); CodePointA: 94; CodePointB: 0),
(Name: UnicodeString('ℏ'); CodePointA: 8463; CodePointB: 0),
(Name: UnicodeString('Ĥ'); CodePointA: 292; CodePointB: 0),
(Name: UnicodeString('ĥ'); CodePointA: 293; CodePointB: 0),
(Name: UnicodeString('♥'); CodePointA: 9829; CodePointB: 0),
(Name: UnicodeString('♥'); CodePointA: 9829; CodePointB: 0),
(Name: UnicodeString('…'); CodePointA: 8230; CodePointB: 0),
(Name: UnicodeString('⊹'); CodePointA: 8889; CodePointB: 0),
(Name: UnicodeString('𝔥'); CodePointA: 120101; CodePointB: 0),
(Name: UnicodeString('ℌ'); CodePointA: 8460; CodePointB: 0),
(Name: UnicodeString('ℋ'); CodePointA: 8459; CodePointB: 0),
(Name: UnicodeString('⤥'); CodePointA: 10533; CodePointB: 0),
(Name: UnicodeString('⤦'); CodePointA: 10534; CodePointB: 0),
(Name: UnicodeString('⇿'); CodePointA: 8703; CodePointB: 0),
(Name: UnicodeString('∻'); CodePointA: 8763; CodePointB: 0),
(Name: UnicodeString('↩'); CodePointA: 8617; CodePointB: 0),
(Name: UnicodeString('↪'); CodePointA: 8618; CodePointB: 0),
(Name: UnicodeString('𝕙'); CodePointA: 120153; CodePointB: 0),
(Name: UnicodeString('ℍ'); CodePointA: 8461; CodePointB: 0),
(Name: UnicodeString('―'); CodePointA: 8213; CodePointB: 0),
(Name: UnicodeString('─'); CodePointA: 9472; CodePointB: 0),
(Name: UnicodeString('𝒽'); CodePointA: 119997; CodePointB: 0),
(Name: UnicodeString('ℋ'); CodePointA: 8459; CodePointB: 0),
(Name: UnicodeString('ℏ'); CodePointA: 8463; CodePointB: 0),
(Name: UnicodeString('Ħ'); CodePointA: 294; CodePointB: 0),
(Name: UnicodeString('ħ'); CodePointA: 295; CodePointB: 0),
(Name: UnicodeString('≎'); CodePointA: 8782; CodePointB: 0),
(Name: UnicodeString('≏'); CodePointA: 8783; CodePointB: 0),
(Name: UnicodeString('⁃'); CodePointA: 8259; CodePointB: 0),
(Name: UnicodeString('‐'); CodePointA: 8208; CodePointB: 0),
(Name: UnicodeString('Í'); CodePointA: 205; CodePointB: 0),
(Name: UnicodeString('Í'); CodePointA: 205; CodePointB: 0),
(Name: UnicodeString('í'); CodePointA: 237; CodePointB: 0),
(Name: UnicodeString('í'); CodePointA: 237; CodePointB: 0),
(Name: UnicodeString('⁣'); CodePointA: 8291; CodePointB: 0),
(Name: UnicodeString('Î'); CodePointA: 206; CodePointB: 0),
(Name: UnicodeString('Î'); CodePointA: 206; CodePointB: 0),
(Name: UnicodeString('î'); CodePointA: 238; CodePointB: 0),
(Name: UnicodeString('î'); CodePointA: 238; CodePointB: 0),
(Name: UnicodeString('И'); CodePointA: 1048; CodePointB: 0),
(Name: UnicodeString('и'); CodePointA: 1080; CodePointB: 0),
(Name: UnicodeString('İ'); CodePointA: 304; CodePointB: 0),
(Name: UnicodeString('Е'); CodePointA: 1045; CodePointB: 0),
(Name: UnicodeString('е'); CodePointA: 1077; CodePointB: 0),
(Name: UnicodeString('¡'); CodePointA: 161; CodePointB: 0),
(Name: UnicodeString('¡'); CodePointA: 161; CodePointB: 0),
(Name: UnicodeString('⇔'); CodePointA: 8660; CodePointB: 0),
(Name: UnicodeString('𝔦'); CodePointA: 120102; CodePointB: 0),
(Name: UnicodeString('ℑ'); CodePointA: 8465; CodePointB: 0),
(Name: UnicodeString('Ì'); CodePointA: 204; CodePointB: 0),
(Name: UnicodeString('Ì'); CodePointA: 204; CodePointB: 0),
(Name: UnicodeString('ì'); CodePointA: 236; CodePointB: 0),
(Name: UnicodeString('ì'); CodePointA: 236; CodePointB: 0),
(Name: UnicodeString('ⅈ'); CodePointA: 8520; CodePointB: 0),
(Name: UnicodeString('⨌'); CodePointA: 10764; CodePointB: 0),
(Name: UnicodeString('∭'); CodePointA: 8749; CodePointB: 0),
(Name: UnicodeString('⧜'); CodePointA: 10716; CodePointB: 0),
(Name: UnicodeString('℩'); CodePointA: 8489; CodePointB: 0),
(Name: UnicodeString('IJ'); CodePointA: 306; CodePointB: 0),
(Name: UnicodeString('ij'); CodePointA: 307; CodePointB: 0),
(Name: UnicodeString('Ī'); CodePointA: 298; CodePointB: 0),
(Name: UnicodeString('ī'); CodePointA: 299; CodePointB: 0),
(Name: UnicodeString('ℑ'); CodePointA: 8465; CodePointB: 0),
(Name: UnicodeString('ⅈ'); CodePointA: 8520; CodePointB: 0),
(Name: UnicodeString('ℐ'); CodePointA: 8464; CodePointB: 0),
(Name: UnicodeString('ℑ'); CodePointA: 8465; CodePointB: 0),
(Name: UnicodeString('ı'); CodePointA: 305; CodePointB: 0),
(Name: UnicodeString('ℑ'); CodePointA: 8465; CodePointB: 0),
(Name: UnicodeString('⊷'); CodePointA: 8887; CodePointB: 0),
(Name: UnicodeString('Ƶ'); CodePointA: 437; CodePointB: 0),
(Name: UnicodeString('⇒'); CodePointA: 8658; CodePointB: 0),
(Name: UnicodeString('℅'); CodePointA: 8453; CodePointB: 0),
(Name: UnicodeString('∈'); CodePointA: 8712; CodePointB: 0),
(Name: UnicodeString('∞'); CodePointA: 8734; CodePointB: 0),
(Name: UnicodeString('⧝'); CodePointA: 10717; CodePointB: 0),
(Name: UnicodeString('ı'); CodePointA: 305; CodePointB: 0),
(Name: UnicodeString('⊺'); CodePointA: 8890; CodePointB: 0),
(Name: UnicodeString('∫'); CodePointA: 8747; CodePointB: 0),
(Name: UnicodeString('∬'); CodePointA: 8748; CodePointB: 0),
(Name: UnicodeString('ℤ'); CodePointA: 8484; CodePointB: 0),
(Name: UnicodeString('∫'); CodePointA: 8747; CodePointB: 0),
(Name: UnicodeString('⊺'); CodePointA: 8890; CodePointB: 0),
(Name: UnicodeString('⋂'); CodePointA: 8898; CodePointB: 0),
(Name: UnicodeString('⨗'); CodePointA: 10775; CodePointB: 0),
(Name: UnicodeString('⨼'); CodePointA: 10812; CodePointB: 0),
(Name: UnicodeString('⁣'); CodePointA: 8291; CodePointB: 0),
(Name: UnicodeString('⁢'); CodePointA: 8290; CodePointB: 0),
(Name: UnicodeString('Ё'); CodePointA: 1025; CodePointB: 0),
(Name: UnicodeString('ё'); CodePointA: 1105; CodePointB: 0),
(Name: UnicodeString('Į'); CodePointA: 302; CodePointB: 0),
(Name: UnicodeString('į'); CodePointA: 303; CodePointB: 0),
(Name: UnicodeString('𝕀'); CodePointA: 120128; CodePointB: 0),
(Name: UnicodeString('𝕚'); CodePointA: 120154; CodePointB: 0),
(Name: UnicodeString('Ι'); CodePointA: 921; CodePointB: 0),
(Name: UnicodeString('ι'); CodePointA: 953; CodePointB: 0),
(Name: UnicodeString('⨼'); CodePointA: 10812; CodePointB: 0),
(Name: UnicodeString('¿'); CodePointA: 191; CodePointB: 0),
(Name: UnicodeString('¿'); CodePointA: 191; CodePointB: 0),
(Name: UnicodeString('𝒾'); CodePointA: 119998; CodePointB: 0),
(Name: UnicodeString('ℐ'); CodePointA: 8464; CodePointB: 0),
(Name: UnicodeString('∈'); CodePointA: 8712; CodePointB: 0),
(Name: UnicodeString('⋵'); CodePointA: 8949; CodePointB: 0),
(Name: UnicodeString('⋹'); CodePointA: 8953; CodePointB: 0),
(Name: UnicodeString('⋴'); CodePointA: 8948; CodePointB: 0),
(Name: UnicodeString('⋳'); CodePointA: 8947; CodePointB: 0),
(Name: UnicodeString('∈'); CodePointA: 8712; CodePointB: 0),
(Name: UnicodeString('⁢'); CodePointA: 8290; CodePointB: 0),
(Name: UnicodeString('Ĩ'); CodePointA: 296; CodePointB: 0),
(Name: UnicodeString('ĩ'); CodePointA: 297; CodePointB: 0),
(Name: UnicodeString('І'); CodePointA: 1030; CodePointB: 0),
(Name: UnicodeString('і'); CodePointA: 1110; CodePointB: 0),
(Name: UnicodeString('Ï'); CodePointA: 207; CodePointB: 0),
(Name: UnicodeString('Ï'); CodePointA: 207; CodePointB: 0),
(Name: UnicodeString('ï'); CodePointA: 239; CodePointB: 0),
(Name: UnicodeString('ï'); CodePointA: 239; CodePointB: 0),
(Name: UnicodeString('Ĵ'); CodePointA: 308; CodePointB: 0),
(Name: UnicodeString('ĵ'); CodePointA: 309; CodePointB: 0),
(Name: UnicodeString('Й'); CodePointA: 1049; CodePointB: 0),
(Name: UnicodeString('й'); CodePointA: 1081; CodePointB: 0),
(Name: UnicodeString('𝔍'); CodePointA: 120077; CodePointB: 0),
(Name: UnicodeString('𝔧'); CodePointA: 120103; CodePointB: 0),
(Name: UnicodeString('ȷ'); CodePointA: 567; CodePointB: 0),
(Name: UnicodeString('𝕁'); CodePointA: 120129; CodePointB: 0),
(Name: UnicodeString('𝕛'); CodePointA: 120155; CodePointB: 0),
(Name: UnicodeString('𝒥'); CodePointA: 119973; CodePointB: 0),
(Name: UnicodeString('𝒿'); CodePointA: 119999; CodePointB: 0),
(Name: UnicodeString('Ј'); CodePointA: 1032; CodePointB: 0),
(Name: UnicodeString('ј'); CodePointA: 1112; CodePointB: 0),
(Name: UnicodeString('Є'); CodePointA: 1028; CodePointB: 0),
(Name: UnicodeString('є'); CodePointA: 1108; CodePointB: 0),
(Name: UnicodeString('Κ'); CodePointA: 922; CodePointB: 0),
(Name: UnicodeString('κ'); CodePointA: 954; CodePointB: 0),
(Name: UnicodeString('ϰ'); CodePointA: 1008; CodePointB: 0),
(Name: UnicodeString('Ķ'); CodePointA: 310; CodePointB: 0),
(Name: UnicodeString('ķ'); CodePointA: 311; CodePointB: 0),
(Name: UnicodeString('К'); CodePointA: 1050; CodePointB: 0),
(Name: UnicodeString('к'); CodePointA: 1082; CodePointB: 0),
(Name: UnicodeString('𝔎'); CodePointA: 120078; CodePointB: 0),
(Name: UnicodeString('𝔨'); CodePointA: 120104; CodePointB: 0),
(Name: UnicodeString('ĸ'); CodePointA: 312; CodePointB: 0),
(Name: UnicodeString('Х'); CodePointA: 1061; CodePointB: 0),
(Name: UnicodeString('х'); CodePointA: 1093; CodePointB: 0),
(Name: UnicodeString('Ќ'); CodePointA: 1036; CodePointB: 0),
(Name: UnicodeString('ќ'); CodePointA: 1116; CodePointB: 0),
(Name: UnicodeString('𝕂'); CodePointA: 120130; CodePointB: 0),
(Name: UnicodeString('𝕜'); CodePointA: 120156; CodePointB: 0),
(Name: UnicodeString('𝒦'); CodePointA: 119974; CodePointB: 0),
(Name: UnicodeString('𝓀'); CodePointA: 120000; CodePointB: 0),
(Name: UnicodeString('⇚'); CodePointA: 8666; CodePointB: 0),
(Name: UnicodeString('Ĺ'); CodePointA: 313; CodePointB: 0),
(Name: UnicodeString('ĺ'); CodePointA: 314; CodePointB: 0),
(Name: UnicodeString('⦴'); CodePointA: 10676; CodePointB: 0),
(Name: UnicodeString('ℒ'); CodePointA: 8466; CodePointB: 0),
(Name: UnicodeString('Λ'); CodePointA: 923; CodePointB: 0),
(Name: UnicodeString('λ'); CodePointA: 955; CodePointB: 0),
(Name: UnicodeString('⟨'); CodePointA: 10216; CodePointB: 0),
(Name: UnicodeString('⟪'); CodePointA: 10218; CodePointB: 0),
(Name: UnicodeString('⦑'); CodePointA: 10641; CodePointB: 0),
(Name: UnicodeString('⟨'); CodePointA: 10216; CodePointB: 0),
(Name: UnicodeString('⪅'); CodePointA: 10885; CodePointB: 0),
(Name: UnicodeString('ℒ'); CodePointA: 8466; CodePointB: 0),
(Name: UnicodeString('«'); CodePointA: 171; CodePointB: 0),
(Name: UnicodeString('«'); CodePointA: 171; CodePointB: 0),
(Name: UnicodeString('⇤'); CodePointA: 8676; CodePointB: 0),
(Name: UnicodeString('⤟'); CodePointA: 10527; CodePointB: 0),
(Name: UnicodeString('←'); CodePointA: 8592; CodePointB: 0),
(Name: UnicodeString('↞'); CodePointA: 8606; CodePointB: 0),
(Name: UnicodeString('⇐'); CodePointA: 8656; CodePointB: 0),
(Name: UnicodeString('⤝'); CodePointA: 10525; CodePointB: 0),
(Name: UnicodeString('↩'); CodePointA: 8617; CodePointB: 0),
(Name: UnicodeString('↫'); CodePointA: 8619; CodePointB: 0),
(Name: UnicodeString('⤹'); CodePointA: 10553; CodePointB: 0),
(Name: UnicodeString('⥳'); CodePointA: 10611; CodePointB: 0),
(Name: UnicodeString('↢'); CodePointA: 8610; CodePointB: 0),
(Name: UnicodeString('⤙'); CodePointA: 10521; CodePointB: 0),
(Name: UnicodeString('⤛'); CodePointA: 10523; CodePointB: 0),
(Name: UnicodeString('⪫'); CodePointA: 10923; CodePointB: 0),
(Name: UnicodeString('⪭'); CodePointA: 10925; CodePointB: 0),
(Name: UnicodeString('⪭︀'); CodePointA: 10925; CodePointB: 65024),
(Name: UnicodeString('⤌'); CodePointA: 10508; CodePointB: 0),
(Name: UnicodeString('⤎'); CodePointA: 10510; CodePointB: 0),
(Name: UnicodeString('❲'); CodePointA: 10098; CodePointB: 0),
(Name: UnicodeString('{'); CodePointA: 123; CodePointB: 0),
(Name: UnicodeString('['); CodePointA: 91; CodePointB: 0),
(Name: UnicodeString('⦋'); CodePointA: 10635; CodePointB: 0),
(Name: UnicodeString('⦏'); CodePointA: 10639; CodePointB: 0),
(Name: UnicodeString('⦍'); CodePointA: 10637; CodePointB: 0),
(Name: UnicodeString('Ľ'); CodePointA: 317; CodePointB: 0),
(Name: UnicodeString('ľ'); CodePointA: 318; CodePointB: 0),
(Name: UnicodeString('Ļ'); CodePointA: 315; CodePointB: 0),
(Name: UnicodeString('ļ'); CodePointA: 316; CodePointB: 0),
(Name: UnicodeString('⌈'); CodePointA: 8968; CodePointB: 0),
(Name: UnicodeString('{'); CodePointA: 123; CodePointB: 0),
(Name: UnicodeString('Л'); CodePointA: 1051; CodePointB: 0),
(Name: UnicodeString('л'); CodePointA: 1083; CodePointB: 0),
(Name: UnicodeString('⤶'); CodePointA: 10550; CodePointB: 0),
(Name: UnicodeString('“'); CodePointA: 8220; CodePointB: 0),
(Name: UnicodeString('„'); CodePointA: 8222; CodePointB: 0),
(Name: UnicodeString('⥧'); CodePointA: 10599; CodePointB: 0),
(Name: UnicodeString('⥋'); CodePointA: 10571; CodePointB: 0),
(Name: UnicodeString('↲'); CodePointA: 8626; CodePointB: 0),
(Name: UnicodeString('≤'); CodePointA: 8804; CodePointB: 0),
(Name: UnicodeString('≦'); CodePointA: 8806; CodePointB: 0),
(Name: UnicodeString('⟨'); CodePointA: 10216; CodePointB: 0),
(Name: UnicodeString('⇤'); CodePointA: 8676; CodePointB: 0),
(Name: UnicodeString('←'); CodePointA: 8592; CodePointB: 0),
(Name: UnicodeString('←'); CodePointA: 8592; CodePointB: 0),
(Name: UnicodeString('⇐'); CodePointA: 8656; CodePointB: 0),
(Name: UnicodeString('⇆'); CodePointA: 8646; CodePointB: 0),
(Name: UnicodeString('↢'); CodePointA: 8610; CodePointB: 0),
(Name: UnicodeString('⌈'); CodePointA: 8968; CodePointB: 0),
(Name: UnicodeString('⟦'); CodePointA: 10214; CodePointB: 0),
(Name: UnicodeString('⥡'); CodePointA: 10593; CodePointB: 0),
(Name: UnicodeString('⥙'); CodePointA: 10585; CodePointB: 0),
(Name: UnicodeString('⇃'); CodePointA: 8643; CodePointB: 0),
(Name: UnicodeString('⌊'); CodePointA: 8970; CodePointB: 0),
(Name: UnicodeString('↽'); CodePointA: 8637; CodePointB: 0),
(Name: UnicodeString('↼'); CodePointA: 8636; CodePointB: 0),
(Name: UnicodeString('⇇'); CodePointA: 8647; CodePointB: 0),
(Name: UnicodeString('↔'); CodePointA: 8596; CodePointB: 0),
(Name: UnicodeString('↔'); CodePointA: 8596; CodePointB: 0),
(Name: UnicodeString('⇔'); CodePointA: 8660; CodePointB: 0),
(Name: UnicodeString('⇆'); CodePointA: 8646; CodePointB: 0),
(Name: UnicodeString('⇋'); CodePointA: 8651; CodePointB: 0),
(Name: UnicodeString('↭'); CodePointA: 8621; CodePointB: 0),
(Name: UnicodeString('⥎'); CodePointA: 10574; CodePointB: 0),
(Name: UnicodeString('↤'); CodePointA: 8612; CodePointB: 0),
(Name: UnicodeString('⊣'); CodePointA: 8867; CodePointB: 0),
(Name: UnicodeString('⥚'); CodePointA: 10586; CodePointB: 0),
(Name: UnicodeString('⋋'); CodePointA: 8907; CodePointB: 0),
(Name: UnicodeString('⧏'); CodePointA: 10703; CodePointB: 0),
(Name: UnicodeString('⊲'); CodePointA: 8882; CodePointB: 0),
(Name: UnicodeString('⊴'); CodePointA: 8884; CodePointB: 0),
(Name: UnicodeString('⥑'); CodePointA: 10577; CodePointB: 0),
(Name: UnicodeString('⥠'); CodePointA: 10592; CodePointB: 0),
(Name: UnicodeString('⥘'); CodePointA: 10584; CodePointB: 0),
(Name: UnicodeString('↿'); CodePointA: 8639; CodePointB: 0),
(Name: UnicodeString('⥒'); CodePointA: 10578; CodePointB: 0),
(Name: UnicodeString('↼'); CodePointA: 8636; CodePointB: 0),
(Name: UnicodeString('⪋'); CodePointA: 10891; CodePointB: 0),
(Name: UnicodeString('⋚'); CodePointA: 8922; CodePointB: 0),
(Name: UnicodeString('≤'); CodePointA: 8804; CodePointB: 0),
(Name: UnicodeString('≦'); CodePointA: 8806; CodePointB: 0),
(Name: UnicodeString('⩽'); CodePointA: 10877; CodePointB: 0),
(Name: UnicodeString('⪨'); CodePointA: 10920; CodePointB: 0),
(Name: UnicodeString('⩽'); CodePointA: 10877; CodePointB: 0),
(Name: UnicodeString('⩿'); CodePointA: 10879; CodePointB: 0),
(Name: UnicodeString('⪁'); CodePointA: 10881; CodePointB: 0),
(Name: UnicodeString('⪃'); CodePointA: 10883; CodePointB: 0),
(Name: UnicodeString('⋚︀'); CodePointA: 8922; CodePointB: 65024),
(Name: UnicodeString('⪓'); CodePointA: 10899; CodePointB: 0),
(Name: UnicodeString('⪅'); CodePointA: 10885; CodePointB: 0),
(Name: UnicodeString('⋖'); CodePointA: 8918; CodePointB: 0),
(Name: UnicodeString('⋚'); CodePointA: 8922; CodePointB: 0),
(Name: UnicodeString('⪋'); CodePointA: 10891; CodePointB: 0),
(Name: UnicodeString('⋚'); CodePointA: 8922; CodePointB: 0),
(Name: UnicodeString('≦'); CodePointA: 8806; CodePointB: 0),
(Name: UnicodeString('≶'); CodePointA: 8822; CodePointB: 0),
(Name: UnicodeString('≶'); CodePointA: 8822; CodePointB: 0),
(Name: UnicodeString('⪡'); CodePointA: 10913; CodePointB: 0),
(Name: UnicodeString('≲'); CodePointA: 8818; CodePointB: 0),
(Name: UnicodeString('⩽'); CodePointA: 10877; CodePointB: 0),
(Name: UnicodeString('≲'); CodePointA: 8818; CodePointB: 0),
(Name: UnicodeString('⥼'); CodePointA: 10620; CodePointB: 0),
(Name: UnicodeString('⌊'); CodePointA: 8970; CodePointB: 0),
(Name: UnicodeString('𝔏'); CodePointA: 120079; CodePointB: 0),
(Name: UnicodeString('𝔩'); CodePointA: 120105; CodePointB: 0),
(Name: UnicodeString('≶'); CodePointA: 8822; CodePointB: 0),
(Name: UnicodeString('⪑'); CodePointA: 10897; CodePointB: 0),
(Name: UnicodeString('⥢'); CodePointA: 10594; CodePointB: 0),
(Name: UnicodeString('↽'); CodePointA: 8637; CodePointB: 0),
(Name: UnicodeString('↼'); CodePointA: 8636; CodePointB: 0),
(Name: UnicodeString('⥪'); CodePointA: 10602; CodePointB: 0),
(Name: UnicodeString('▄'); CodePointA: 9604; CodePointB: 0),
(Name: UnicodeString('Љ'); CodePointA: 1033; CodePointB: 0),
(Name: UnicodeString('љ'); CodePointA: 1113; CodePointB: 0),
(Name: UnicodeString('⇇'); CodePointA: 8647; CodePointB: 0),
(Name: UnicodeString('≪'); CodePointA: 8810; CodePointB: 0),
(Name: UnicodeString('⋘'); CodePointA: 8920; CodePointB: 0),
(Name: UnicodeString('⌞'); CodePointA: 8990; CodePointB: 0),
(Name: UnicodeString('⇚'); CodePointA: 8666; CodePointB: 0),
(Name: UnicodeString('⥫'); CodePointA: 10603; CodePointB: 0),
(Name: UnicodeString('◺'); CodePointA: 9722; CodePointB: 0),
(Name: UnicodeString('Ŀ'); CodePointA: 319; CodePointB: 0),
(Name: UnicodeString('ŀ'); CodePointA: 320; CodePointB: 0),
(Name: UnicodeString('⎰'); CodePointA: 9136; CodePointB: 0),
(Name: UnicodeString('⎰'); CodePointA: 9136; CodePointB: 0),
(Name: UnicodeString('⪉'); CodePointA: 10889; CodePointB: 0),
(Name: UnicodeString('⪉'); CodePointA: 10889; CodePointB: 0),
(Name: UnicodeString('⪇'); CodePointA: 10887; CodePointB: 0),
(Name: UnicodeString('≨'); CodePointA: 8808; CodePointB: 0),
(Name: UnicodeString('⪇'); CodePointA: 10887; CodePointB: 0),
(Name: UnicodeString('≨'); CodePointA: 8808; CodePointB: 0),
(Name: UnicodeString('⋦'); CodePointA: 8934; CodePointB: 0),
(Name: UnicodeString('⟬'); CodePointA: 10220; CodePointB: 0),
(Name: UnicodeString('⇽'); CodePointA: 8701; CodePointB: 0),
(Name: UnicodeString('⟦'); CodePointA: 10214; CodePointB: 0),
(Name: UnicodeString('⟵'); CodePointA: 10229; CodePointB: 0),
(Name: UnicodeString('⟵'); CodePointA: 10229; CodePointB: 0),
(Name: UnicodeString('⟸'); CodePointA: 10232; CodePointB: 0),
(Name: UnicodeString('⟷'); CodePointA: 10231; CodePointB: 0),
(Name: UnicodeString('⟷'); CodePointA: 10231; CodePointB: 0),
(Name: UnicodeString('⟺'); CodePointA: 10234; CodePointB: 0),
(Name: UnicodeString('⟼'); CodePointA: 10236; CodePointB: 0),
(Name: UnicodeString('⟶'); CodePointA: 10230; CodePointB: 0),
(Name: UnicodeString('⟶'); CodePointA: 10230; CodePointB: 0),
(Name: UnicodeString('⟹'); CodePointA: 10233; CodePointB: 0),
(Name: UnicodeString('↫'); CodePointA: 8619; CodePointB: 0),
(Name: UnicodeString('↬'); CodePointA: 8620; CodePointB: 0),
(Name: UnicodeString('⦅'); CodePointA: 10629; CodePointB: 0),
(Name: UnicodeString('𝕃'); CodePointA: 120131; CodePointB: 0),
(Name: UnicodeString('𝕝'); CodePointA: 120157; CodePointB: 0),
(Name: UnicodeString('⨭'); CodePointA: 10797; CodePointB: 0),
(Name: UnicodeString('⨴'); CodePointA: 10804; CodePointB: 0),
(Name: UnicodeString('∗'); CodePointA: 8727; CodePointB: 0),
(Name: UnicodeString('_'); CodePointA: 95; CodePointB: 0),
(Name: UnicodeString('↙'); CodePointA: 8601; CodePointB: 0),
(Name: UnicodeString('↘'); CodePointA: 8600; CodePointB: 0),
(Name: UnicodeString('◊'); CodePointA: 9674; CodePointB: 0),
(Name: UnicodeString('◊'); CodePointA: 9674; CodePointB: 0),
(Name: UnicodeString('⧫'); CodePointA: 10731; CodePointB: 0),
(Name: UnicodeString('('); CodePointA: 40; CodePointB: 0),
(Name: UnicodeString('⦓'); CodePointA: 10643; CodePointB: 0),
(Name: UnicodeString('⇆'); CodePointA: 8646; CodePointB: 0),
(Name: UnicodeString('⌟'); CodePointA: 8991; CodePointB: 0),
(Name: UnicodeString('⇋'); CodePointA: 8651; CodePointB: 0),
(Name: UnicodeString('⥭'); CodePointA: 10605; CodePointB: 0),
(Name: UnicodeString('‎'); CodePointA: 8206; CodePointB: 0),
(Name: UnicodeString('⊿'); CodePointA: 8895; CodePointB: 0),
(Name: UnicodeString('‹'); CodePointA: 8249; CodePointB: 0),
(Name: UnicodeString('𝓁'); CodePointA: 120001; CodePointB: 0),
(Name: UnicodeString('ℒ'); CodePointA: 8466; CodePointB: 0),
(Name: UnicodeString('↰'); CodePointA: 8624; CodePointB: 0),
(Name: UnicodeString('↰'); CodePointA: 8624; CodePointB: 0),
(Name: UnicodeString('≲'); CodePointA: 8818; CodePointB: 0),
(Name: UnicodeString('⪍'); CodePointA: 10893; CodePointB: 0),
(Name: UnicodeString('⪏'); CodePointA: 10895; CodePointB: 0),
(Name: UnicodeString('['); CodePointA: 91; CodePointB: 0),
(Name: UnicodeString('‘'); CodePointA: 8216; CodePointB: 0),
(Name: UnicodeString('‚'); CodePointA: 8218; CodePointB: 0),
(Name: UnicodeString('Ł'); CodePointA: 321; CodePointB: 0),
(Name: UnicodeString('ł'); CodePointA: 322; CodePointB: 0),
(Name: UnicodeString('⪦'); CodePointA: 10918; CodePointB: 0),
(Name: UnicodeString('⩹'); CodePointA: 10873; CodePointB: 0),
(Name: UnicodeString('<'); CodePointA: 60; CodePointB: 0),
(Name: UnicodeString('<'); CodePointA: 60; CodePointB: 0),
(Name: UnicodeString('<'); CodePointA: 60; CodePointB: 0),
(Name: UnicodeString('<'); CodePointA: 60; CodePointB: 0),
(Name: UnicodeString('≪'); CodePointA: 8810; CodePointB: 0),
(Name: UnicodeString('⋖'); CodePointA: 8918; CodePointB: 0),
(Name: UnicodeString('⋋'); CodePointA: 8907; CodePointB: 0),
(Name: UnicodeString('⋉'); CodePointA: 8905; CodePointB: 0),
(Name: UnicodeString('⥶'); CodePointA: 10614; CodePointB: 0),
(Name: UnicodeString('⩻'); CodePointA: 10875; CodePointB: 0),
(Name: UnicodeString('◃'); CodePointA: 9667; CodePointB: 0),
(Name: UnicodeString('⊴'); CodePointA: 8884; CodePointB: 0),
(Name: UnicodeString('◂'); CodePointA: 9666; CodePointB: 0),
(Name: UnicodeString('⦖'); CodePointA: 10646; CodePointB: 0),
(Name: UnicodeString('⥊'); CodePointA: 10570; CodePointB: 0),
(Name: UnicodeString('⥦'); CodePointA: 10598; CodePointB: 0),
(Name: UnicodeString('≨︀'); CodePointA: 8808; CodePointB: 65024),
(Name: UnicodeString('≨︀'); CodePointA: 8808; CodePointB: 65024),
(Name: UnicodeString('¯'); CodePointA: 175; CodePointB: 0),
(Name: UnicodeString('¯'); CodePointA: 175; CodePointB: 0),
(Name: UnicodeString('♂'); CodePointA: 9794; CodePointB: 0),
(Name: UnicodeString('✠'); CodePointA: 10016; CodePointB: 0),
(Name: UnicodeString('✠'); CodePointA: 10016; CodePointB: 0),
(Name: UnicodeString('⤅'); CodePointA: 10501; CodePointB: 0),
(Name: UnicodeString('↦'); CodePointA: 8614; CodePointB: 0),
(Name: UnicodeString('↦'); CodePointA: 8614; CodePointB: 0),
(Name: UnicodeString('↧'); CodePointA: 8615; CodePointB: 0),
(Name: UnicodeString('↤'); CodePointA: 8612; CodePointB: 0),
(Name: UnicodeString('↥'); CodePointA: 8613; CodePointB: 0),
(Name: UnicodeString('▮'); CodePointA: 9646; CodePointB: 0),
(Name: UnicodeString('⨩'); CodePointA: 10793; CodePointB: 0),
(Name: UnicodeString('М'); CodePointA: 1052; CodePointB: 0),
(Name: UnicodeString('м'); CodePointA: 1084; CodePointB: 0),
(Name: UnicodeString('—'); CodePointA: 8212; CodePointB: 0),
(Name: UnicodeString('∺'); CodePointA: 8762; CodePointB: 0),
(Name: UnicodeString('∡'); CodePointA: 8737; CodePointB: 0),
(Name: UnicodeString(' '); CodePointA: 8287; CodePointB: 0),
(Name: UnicodeString('ℳ'); CodePointA: 8499; CodePointB: 0),
(Name: UnicodeString('𝔐'); CodePointA: 120080; CodePointB: 0),
(Name: UnicodeString('𝔪'); CodePointA: 120106; CodePointB: 0),
(Name: UnicodeString('℧'); CodePointA: 8487; CodePointB: 0),
(Name: UnicodeString('µ'); CodePointA: 181; CodePointB: 0),
(Name: UnicodeString('µ'); CodePointA: 181; CodePointB: 0),
(Name: UnicodeString('*'); CodePointA: 42; CodePointB: 0),
(Name: UnicodeString('⫰'); CodePointA: 10992; CodePointB: 0),
(Name: UnicodeString('∣'); CodePointA: 8739; CodePointB: 0),
(Name: UnicodeString('·'); CodePointA: 183; CodePointB: 0),
(Name: UnicodeString('·'); CodePointA: 183; CodePointB: 0),
(Name: UnicodeString('⊟'); CodePointA: 8863; CodePointB: 0),
(Name: UnicodeString('−'); CodePointA: 8722; CodePointB: 0),
(Name: UnicodeString('∸'); CodePointA: 8760; CodePointB: 0),
(Name: UnicodeString('⨪'); CodePointA: 10794; CodePointB: 0),
(Name: UnicodeString('∓'); CodePointA: 8723; CodePointB: 0),
(Name: UnicodeString('⫛'); CodePointA: 10971; CodePointB: 0),
(Name: UnicodeString('…'); CodePointA: 8230; CodePointB: 0),
(Name: UnicodeString('∓'); CodePointA: 8723; CodePointB: 0),
(Name: UnicodeString('⊧'); CodePointA: 8871; CodePointB: 0),
(Name: UnicodeString('𝕄'); CodePointA: 120132; CodePointB: 0),
(Name: UnicodeString('𝕞'); CodePointA: 120158; CodePointB: 0),
(Name: UnicodeString('∓'); CodePointA: 8723; CodePointB: 0),
(Name: UnicodeString('𝓂'); CodePointA: 120002; CodePointB: 0),
(Name: UnicodeString('ℳ'); CodePointA: 8499; CodePointB: 0),
(Name: UnicodeString('∾'); CodePointA: 8766; CodePointB: 0),
(Name: UnicodeString('Μ'); CodePointA: 924; CodePointB: 0),
(Name: UnicodeString('μ'); CodePointA: 956; CodePointB: 0),
(Name: UnicodeString('⊸'); CodePointA: 8888; CodePointB: 0),
(Name: UnicodeString('⊸'); CodePointA: 8888; CodePointB: 0),
(Name: UnicodeString('∇'); CodePointA: 8711; CodePointB: 0),
(Name: UnicodeString('Ń'); CodePointA: 323; CodePointB: 0),
(Name: UnicodeString('ń'); CodePointA: 324; CodePointB: 0),
(Name: UnicodeString('∠⃒'); CodePointA: 8736; CodePointB: 8402),
(Name: UnicodeString('≉'); CodePointA: 8777; CodePointB: 0),
(Name: UnicodeString('⩰̸'); CodePointA: 10864; CodePointB: 824),
(Name: UnicodeString('≋̸'); CodePointA: 8779; CodePointB: 824),
(Name: UnicodeString('ʼn'); CodePointA: 329; CodePointB: 0),
(Name: UnicodeString('≉'); CodePointA: 8777; CodePointB: 0),
(Name: UnicodeString('♮'); CodePointA: 9838; CodePointB: 0),
(Name: UnicodeString('ℕ'); CodePointA: 8469; CodePointB: 0),
(Name: UnicodeString('♮'); CodePointA: 9838; CodePointB: 0),
(Name: UnicodeString(' '); CodePointA: 160; CodePointB: 0),
(Name: UnicodeString(' '); CodePointA: 160; CodePointB: 0),
(Name: UnicodeString('≎̸'); CodePointA: 8782; CodePointB: 824),
(Name: UnicodeString('≏̸'); CodePointA: 8783; CodePointB: 824),
(Name: UnicodeString('⩃'); CodePointA: 10819; CodePointB: 0),
(Name: UnicodeString('Ň'); CodePointA: 327; CodePointB: 0),
(Name: UnicodeString('ň'); CodePointA: 328; CodePointB: 0),
(Name: UnicodeString('Ņ'); CodePointA: 325; CodePointB: 0),
(Name: UnicodeString('ņ'); CodePointA: 326; CodePointB: 0),
(Name: UnicodeString('≇'); CodePointA: 8775; CodePointB: 0),
(Name: UnicodeString('⩭̸'); CodePointA: 10861; CodePointB: 824),
(Name: UnicodeString('⩂'); CodePointA: 10818; CodePointB: 0),
(Name: UnicodeString('Н'); CodePointA: 1053; CodePointB: 0),
(Name: UnicodeString('н'); CodePointA: 1085; CodePointB: 0),
(Name: UnicodeString('–'); CodePointA: 8211; CodePointB: 0),
(Name: UnicodeString('⤤'); CodePointA: 10532; CodePointB: 0),
(Name: UnicodeString('↗'); CodePointA: 8599; CodePointB: 0),
(Name: UnicodeString('⇗'); CodePointA: 8663; CodePointB: 0),
(Name: UnicodeString('↗'); CodePointA: 8599; CodePointB: 0),
(Name: UnicodeString('≠'); CodePointA: 8800; CodePointB: 0),
(Name: UnicodeString('≐̸'); CodePointA: 8784; CodePointB: 824),
(Name: UnicodeString('​'); CodePointA: 8203; CodePointB: 0),
(Name: UnicodeString('​'); CodePointA: 8203; CodePointB: 0),
(Name: UnicodeString('​'); CodePointA: 8203; CodePointB: 0),
(Name: UnicodeString('​'); CodePointA: 8203; CodePointB: 0),
(Name: UnicodeString('≢'); CodePointA: 8802; CodePointB: 0),
(Name: UnicodeString('⤨'); CodePointA: 10536; CodePointB: 0),
(Name: UnicodeString('≂̸'); CodePointA: 8770; CodePointB: 824),
(Name: UnicodeString('≫'); CodePointA: 8811; CodePointB: 0),
(Name: UnicodeString('≪'); CodePointA: 8810; CodePointB: 0),
(Name: UnicodeString('
'); CodePointA: 10; CodePointB: 0),
(Name: UnicodeString('∄'); CodePointA: 8708; CodePointB: 0),
(Name: UnicodeString('∄'); CodePointA: 8708; CodePointB: 0),
(Name: UnicodeString('𝔑'); CodePointA: 120081; CodePointB: 0),
(Name: UnicodeString('𝔫'); CodePointA: 120107; CodePointB: 0),
(Name: UnicodeString('≧̸'); CodePointA: 8807; CodePointB: 824),
(Name: UnicodeString('≱'); CodePointA: 8817; CodePointB: 0),
(Name: UnicodeString('≱'); CodePointA: 8817; CodePointB: 0),
(Name: UnicodeString('≧̸'); CodePointA: 8807; CodePointB: 824),
(Name: UnicodeString('⩾̸'); CodePointA: 10878; CodePointB: 824),
(Name: UnicodeString('⩾̸'); CodePointA: 10878; CodePointB: 824),
(Name: UnicodeString('⋙̸'); CodePointA: 8921; CodePointB: 824),
(Name: UnicodeString('≵'); CodePointA: 8821; CodePointB: 0),
(Name: UnicodeString('≫⃒'); CodePointA: 8811; CodePointB: 8402),
(Name: UnicodeString('≯'); CodePointA: 8815; CodePointB: 0),
(Name: UnicodeString('≯'); CodePointA: 8815; CodePointB: 0),
(Name: UnicodeString('≫̸'); CodePointA: 8811; CodePointB: 824),
(Name: UnicodeString('↮'); CodePointA: 8622; CodePointB: 0),
(Name: UnicodeString('⇎'); CodePointA: 8654; CodePointB: 0),
(Name: UnicodeString('⫲'); CodePointA: 10994; CodePointB: 0),
(Name: UnicodeString('∋'); CodePointA: 8715; CodePointB: 0),
(Name: UnicodeString('⋼'); CodePointA: 8956; CodePointB: 0),
(Name: UnicodeString('⋺'); CodePointA: 8954; CodePointB: 0),
(Name: UnicodeString('∋'); CodePointA: 8715; CodePointB: 0),
(Name: UnicodeString('Њ'); CodePointA: 1034; CodePointB: 0),
(Name: UnicodeString('њ'); CodePointA: 1114; CodePointB: 0),
(Name: UnicodeString('↚'); CodePointA: 8602; CodePointB: 0),
(Name: UnicodeString('⇍'); CodePointA: 8653; CodePointB: 0),
(Name: UnicodeString('‥'); CodePointA: 8229; CodePointB: 0),
(Name: UnicodeString('≦̸'); CodePointA: 8806; CodePointB: 824),
(Name: UnicodeString('≰'); CodePointA: 8816; CodePointB: 0),
(Name: UnicodeString('↚'); CodePointA: 8602; CodePointB: 0),
(Name: UnicodeString('⇍'); CodePointA: 8653; CodePointB: 0),
(Name: UnicodeString('↮'); CodePointA: 8622; CodePointB: 0),
(Name: UnicodeString('⇎'); CodePointA: 8654; CodePointB: 0),
(Name: UnicodeString('≰'); CodePointA: 8816; CodePointB: 0),
(Name: UnicodeString('≦̸'); CodePointA: 8806; CodePointB: 824),
(Name: UnicodeString('⩽̸'); CodePointA: 10877; CodePointB: 824),
(Name: UnicodeString('⩽̸'); CodePointA: 10877; CodePointB: 824),
(Name: UnicodeString('≮'); CodePointA: 8814; CodePointB: 0),
(Name: UnicodeString('⋘̸'); CodePointA: 8920; CodePointB: 824),
(Name: UnicodeString('≴'); CodePointA: 8820; CodePointB: 0),
(Name: UnicodeString('≪⃒'); CodePointA: 8810; CodePointB: 8402),
(Name: UnicodeString('≮'); CodePointA: 8814; CodePointB: 0),
(Name: UnicodeString('⋪'); CodePointA: 8938; CodePointB: 0),
(Name: UnicodeString('⋬'); CodePointA: 8940; CodePointB: 0),
(Name: UnicodeString('≪̸'); CodePointA: 8810; CodePointB: 824),
(Name: UnicodeString('∤'); CodePointA: 8740; CodePointB: 0),
(Name: UnicodeString('⁠'); CodePointA: 8288; CodePointB: 0),
(Name: UnicodeString(' '); CodePointA: 160; CodePointB: 0),
(Name: UnicodeString('𝕟'); CodePointA: 120159; CodePointB: 0),
(Name: UnicodeString('ℕ'); CodePointA: 8469; CodePointB: 0),
(Name: UnicodeString('⫬'); CodePointA: 10988; CodePointB: 0),
(Name: UnicodeString('¬'); CodePointA: 172; CodePointB: 0),
(Name: UnicodeString('¬'); CodePointA: 172; CodePointB: 0),
(Name: UnicodeString('≢'); CodePointA: 8802; CodePointB: 0),
(Name: UnicodeString('≭'); CodePointA: 8813; CodePointB: 0),
(Name: UnicodeString('∦'); CodePointA: 8742; CodePointB: 0),
(Name: UnicodeString('∉'); CodePointA: 8713; CodePointB: 0),
(Name: UnicodeString('≠'); CodePointA: 8800; CodePointB: 0),
(Name: UnicodeString('≂̸'); CodePointA: 8770; CodePointB: 824),
(Name: UnicodeString('∄'); CodePointA: 8708; CodePointB: 0),
(Name: UnicodeString('≯'); CodePointA: 8815; CodePointB: 0),
(Name: UnicodeString('≱'); CodePointA: 8817; CodePointB: 0),
(Name: UnicodeString('≧̸'); CodePointA: 8807; CodePointB: 824),
(Name: UnicodeString('≫̸'); CodePointA: 8811; CodePointB: 824),
(Name: UnicodeString('≹'); CodePointA: 8825; CodePointB: 0),
(Name: UnicodeString('⩾̸'); CodePointA: 10878; CodePointB: 824),
(Name: UnicodeString('≵'); CodePointA: 8821; CodePointB: 0),
(Name: UnicodeString('≎̸'); CodePointA: 8782; CodePointB: 824),
(Name: UnicodeString('≏̸'); CodePointA: 8783; CodePointB: 824),
(Name: UnicodeString('∉'); CodePointA: 8713; CodePointB: 0),
(Name: UnicodeString('⋵̸'); CodePointA: 8949; CodePointB: 824),
(Name: UnicodeString('⋹̸'); CodePointA: 8953; CodePointB: 824),
(Name: UnicodeString('∉'); CodePointA: 8713; CodePointB: 0),
(Name: UnicodeString('⋷'); CodePointA: 8951; CodePointB: 0),
(Name: UnicodeString('⋶'); CodePointA: 8950; CodePointB: 0),
(Name: UnicodeString('⧏̸'); CodePointA: 10703; CodePointB: 824),
(Name: UnicodeString('⋪'); CodePointA: 8938; CodePointB: 0),
(Name: UnicodeString('⋬'); CodePointA: 8940; CodePointB: 0),
(Name: UnicodeString('≮'); CodePointA: 8814; CodePointB: 0),
(Name: UnicodeString('≰'); CodePointA: 8816; CodePointB: 0),
(Name: UnicodeString('≸'); CodePointA: 8824; CodePointB: 0),
(Name: UnicodeString('≪̸'); CodePointA: 8810; CodePointB: 824),
(Name: UnicodeString('⩽̸'); CodePointA: 10877; CodePointB: 824),
(Name: UnicodeString('≴'); CodePointA: 8820; CodePointB: 0),
(Name: UnicodeString('⪢̸'); CodePointA: 10914; CodePointB: 824),
(Name: UnicodeString('⪡̸'); CodePointA: 10913; CodePointB: 824),
(Name: UnicodeString('∌'); CodePointA: 8716; CodePointB: 0),
(Name: UnicodeString('∌'); CodePointA: 8716; CodePointB: 0),
(Name: UnicodeString('⋾'); CodePointA: 8958; CodePointB: 0),
(Name: UnicodeString('⋽'); CodePointA: 8957; CodePointB: 0),
(Name: UnicodeString('⊀'); CodePointA: 8832; CodePointB: 0),
(Name: UnicodeString('⪯̸'); CodePointA: 10927; CodePointB: 824),
(Name: UnicodeString('⋠'); CodePointA: 8928; CodePointB: 0),
(Name: UnicodeString('∌'); CodePointA: 8716; CodePointB: 0),
(Name: UnicodeString('⧐̸'); CodePointA: 10704; CodePointB: 824),
(Name: UnicodeString('⋫'); CodePointA: 8939; CodePointB: 0),
(Name: UnicodeString('⋭'); CodePointA: 8941; CodePointB: 0),
(Name: UnicodeString('⊏̸'); CodePointA: 8847; CodePointB: 824),
(Name: UnicodeString('⋢'); CodePointA: 8930; CodePointB: 0),
(Name: UnicodeString('⊐̸'); CodePointA: 8848; CodePointB: 824),
(Name: UnicodeString('⋣'); CodePointA: 8931; CodePointB: 0),
(Name: UnicodeString('⊂⃒'); CodePointA: 8834; CodePointB: 8402),
(Name: UnicodeString('⊈'); CodePointA: 8840; CodePointB: 0),
(Name: UnicodeString('⊁'); CodePointA: 8833; CodePointB: 0),
(Name: UnicodeString('⪰̸'); CodePointA: 10928; CodePointB: 824),
(Name: UnicodeString('⋡'); CodePointA: 8929; CodePointB: 0),
(Name: UnicodeString('≿̸'); CodePointA: 8831; CodePointB: 824),
(Name: UnicodeString('⊃⃒'); CodePointA: 8835; CodePointB: 8402),
(Name: UnicodeString('⊉'); CodePointA: 8841; CodePointB: 0),
(Name: UnicodeString('≁'); CodePointA: 8769; CodePointB: 0),
(Name: UnicodeString('≄'); CodePointA: 8772; CodePointB: 0),
(Name: UnicodeString('≇'); CodePointA: 8775; CodePointB: 0),
(Name: UnicodeString('≉'); CodePointA: 8777; CodePointB: 0),
(Name: UnicodeString('∤'); CodePointA: 8740; CodePointB: 0),
(Name: UnicodeString('∦'); CodePointA: 8742; CodePointB: 0),
(Name: UnicodeString('∦'); CodePointA: 8742; CodePointB: 0),
(Name: UnicodeString('⫽⃥'); CodePointA: 11005; CodePointB: 8421),
(Name: UnicodeString('∂̸'); CodePointA: 8706; CodePointB: 824),
(Name: UnicodeString('⨔'); CodePointA: 10772; CodePointB: 0),
(Name: UnicodeString('⊀'); CodePointA: 8832; CodePointB: 0),
(Name: UnicodeString('⋠'); CodePointA: 8928; CodePointB: 0),
(Name: UnicodeString('⊀'); CodePointA: 8832; CodePointB: 0),
(Name: UnicodeString('⪯̸'); CodePointA: 10927; CodePointB: 824),
(Name: UnicodeString('⪯̸'); CodePointA: 10927; CodePointB: 824),
(Name: UnicodeString('⤳̸'); CodePointA: 10547; CodePointB: 824),
(Name: UnicodeString('↛'); CodePointA: 8603; CodePointB: 0),
(Name: UnicodeString('⇏'); CodePointA: 8655; CodePointB: 0),
(Name: UnicodeString('↝̸'); CodePointA: 8605; CodePointB: 824),
(Name: UnicodeString('↛'); CodePointA: 8603; CodePointB: 0),
(Name: UnicodeString('⇏'); CodePointA: 8655; CodePointB: 0),
(Name: UnicodeString('⋫'); CodePointA: 8939; CodePointB: 0),
(Name: UnicodeString('⋭'); CodePointA: 8941; CodePointB: 0),
(Name: UnicodeString('⊁'); CodePointA: 8833; CodePointB: 0),
(Name: UnicodeString('⋡'); CodePointA: 8929; CodePointB: 0),
(Name: UnicodeString('⪰̸'); CodePointA: 10928; CodePointB: 824),
(Name: UnicodeString('𝒩'); CodePointA: 119977; CodePointB: 0),
(Name: UnicodeString('𝓃'); CodePointA: 120003; CodePointB: 0),
(Name: UnicodeString('∤'); CodePointA: 8740; CodePointB: 0),
(Name: UnicodeString('∦'); CodePointA: 8742; CodePointB: 0),
(Name: UnicodeString('≁'); CodePointA: 8769; CodePointB: 0),
(Name: UnicodeString('≄'); CodePointA: 8772; CodePointB: 0),
(Name: UnicodeString('≄'); CodePointA: 8772; CodePointB: 0),
(Name: UnicodeString('∤'); CodePointA: 8740; CodePointB: 0),
(Name: UnicodeString('∦'); CodePointA: 8742; CodePointB: 0),
(Name: UnicodeString('⋢'); CodePointA: 8930; CodePointB: 0),
(Name: UnicodeString('⋣'); CodePointA: 8931; CodePointB: 0),
(Name: UnicodeString('⊄'); CodePointA: 8836; CodePointB: 0),
(Name: UnicodeString('⫅̸'); CodePointA: 10949; CodePointB: 824),
(Name: UnicodeString('⊈'); CodePointA: 8840; CodePointB: 0),
(Name: UnicodeString('⊂⃒'); CodePointA: 8834; CodePointB: 8402),
(Name: UnicodeString('⊈'); CodePointA: 8840; CodePointB: 0),
(Name: UnicodeString('⫅̸'); CodePointA: 10949; CodePointB: 824),
(Name: UnicodeString('⊁'); CodePointA: 8833; CodePointB: 0),
(Name: UnicodeString('⪰̸'); CodePointA: 10928; CodePointB: 824),
(Name: UnicodeString('⊅'); CodePointA: 8837; CodePointB: 0),
(Name: UnicodeString('⫆̸'); CodePointA: 10950; CodePointB: 824),
(Name: UnicodeString('⊉'); CodePointA: 8841; CodePointB: 0),
(Name: UnicodeString('⊃⃒'); CodePointA: 8835; CodePointB: 8402),
(Name: UnicodeString('⊉'); CodePointA: 8841; CodePointB: 0),
(Name: UnicodeString('⫆̸'); CodePointA: 10950; CodePointB: 824),
(Name: UnicodeString('≹'); CodePointA: 8825; CodePointB: 0),
(Name: UnicodeString('Ñ'); CodePointA: 209; CodePointB: 0),
(Name: UnicodeString('Ñ'); CodePointA: 209; CodePointB: 0),
(Name: UnicodeString('ñ'); CodePointA: 241; CodePointB: 0),
(Name: UnicodeString('ñ'); CodePointA: 241; CodePointB: 0),
(Name: UnicodeString('≸'); CodePointA: 8824; CodePointB: 0),
(Name: UnicodeString('⋪'); CodePointA: 8938; CodePointB: 0),
(Name: UnicodeString('⋬'); CodePointA: 8940; CodePointB: 0),
(Name: UnicodeString('⋫'); CodePointA: 8939; CodePointB: 0),
(Name: UnicodeString('⋭'); CodePointA: 8941; CodePointB: 0),
(Name: UnicodeString('Ν'); CodePointA: 925; CodePointB: 0),
(Name: UnicodeString('ν'); CodePointA: 957; CodePointB: 0),
(Name: UnicodeString('#'); CodePointA: 35; CodePointB: 0),
(Name: UnicodeString('№'); CodePointA: 8470; CodePointB: 0),
(Name: UnicodeString(' '); CodePointA: 8199; CodePointB: 0),
(Name: UnicodeString('≍⃒'); CodePointA: 8781; CodePointB: 8402),
(Name: UnicodeString('⊬'); CodePointA: 8876; CodePointB: 0),
(Name: UnicodeString('⊭'); CodePointA: 8877; CodePointB: 0),
(Name: UnicodeString('⊮'); CodePointA: 8878; CodePointB: 0),
(Name: UnicodeString('⊯'); CodePointA: 8879; CodePointB: 0),
(Name: UnicodeString('≥⃒'); CodePointA: 8805; CodePointB: 8402),
(Name: UnicodeString('>⃒'); CodePointA: 62; CodePointB: 8402),
(Name: UnicodeString('⤄'); CodePointA: 10500; CodePointB: 0),
(Name: UnicodeString('⧞'); CodePointA: 10718; CodePointB: 0),
(Name: UnicodeString('⤂'); CodePointA: 10498; CodePointB: 0),
(Name: UnicodeString('≤⃒'); CodePointA: 8804; CodePointB: 8402),
(Name: UnicodeString('<⃒'); CodePointA: 60; CodePointB: 8402),
(Name: UnicodeString('⊴⃒'); CodePointA: 8884; CodePointB: 8402),
(Name: UnicodeString('⤃'); CodePointA: 10499; CodePointB: 0),
(Name: UnicodeString('⊵⃒'); CodePointA: 8885; CodePointB: 8402),
(Name: UnicodeString('∼⃒'); CodePointA: 8764; CodePointB: 8402),
(Name: UnicodeString('⤣'); CodePointA: 10531; CodePointB: 0),
(Name: UnicodeString('↖'); CodePointA: 8598; CodePointB: 0),
(Name: UnicodeString('⇖'); CodePointA: 8662; CodePointB: 0),
(Name: UnicodeString('↖'); CodePointA: 8598; CodePointB: 0),
(Name: UnicodeString('⤧'); CodePointA: 10535; CodePointB: 0),
(Name: UnicodeString('Ó'); CodePointA: 211; CodePointB: 0),
(Name: UnicodeString('Ó'); CodePointA: 211; CodePointB: 0),
(Name: UnicodeString('ó'); CodePointA: 243; CodePointB: 0),
(Name: UnicodeString('ó'); CodePointA: 243; CodePointB: 0),
(Name: UnicodeString('⊛'); CodePointA: 8859; CodePointB: 0),
(Name: UnicodeString('Ô'); CodePointA: 212; CodePointB: 0),
(Name: UnicodeString('Ô'); CodePointA: 212; CodePointB: 0),
(Name: UnicodeString('ô'); CodePointA: 244; CodePointB: 0),
(Name: UnicodeString('ô'); CodePointA: 244; CodePointB: 0),
(Name: UnicodeString('⊚'); CodePointA: 8858; CodePointB: 0),
(Name: UnicodeString('О'); CodePointA: 1054; CodePointB: 0),
(Name: UnicodeString('о'); CodePointA: 1086; CodePointB: 0),
(Name: UnicodeString('⊝'); CodePointA: 8861; CodePointB: 0),
(Name: UnicodeString('Ő'); CodePointA: 336; CodePointB: 0),
(Name: UnicodeString('ő'); CodePointA: 337; CodePointB: 0),
(Name: UnicodeString('⨸'); CodePointA: 10808; CodePointB: 0),
(Name: UnicodeString('⊙'); CodePointA: 8857; CodePointB: 0),
(Name: UnicodeString('⦼'); CodePointA: 10684; CodePointB: 0),
(Name: UnicodeString('Œ'); CodePointA: 338; CodePointB: 0),
(Name: UnicodeString('œ'); CodePointA: 339; CodePointB: 0),
(Name: UnicodeString('⦿'); CodePointA: 10687; CodePointB: 0),
(Name: UnicodeString('𝔒'); CodePointA: 120082; CodePointB: 0),
(Name: UnicodeString('𝔬'); CodePointA: 120108; CodePointB: 0),
(Name: UnicodeString('˛'); CodePointA: 731; CodePointB: 0),
(Name: UnicodeString('Ò'); CodePointA: 210; CodePointB: 0),
(Name: UnicodeString('Ò'); CodePointA: 210; CodePointB: 0),
(Name: UnicodeString('ò'); CodePointA: 242; CodePointB: 0),
(Name: UnicodeString('ò'); CodePointA: 242; CodePointB: 0),
(Name: UnicodeString('⧁'); CodePointA: 10689; CodePointB: 0),
(Name: UnicodeString('⦵'); CodePointA: 10677; CodePointB: 0),
(Name: UnicodeString('Ω'); CodePointA: 937; CodePointB: 0),
(Name: UnicodeString('∮'); CodePointA: 8750; CodePointB: 0),
(Name: UnicodeString('↺'); CodePointA: 8634; CodePointB: 0),
(Name: UnicodeString('⦾'); CodePointA: 10686; CodePointB: 0),
(Name: UnicodeString('⦻'); CodePointA: 10683; CodePointB: 0),
(Name: UnicodeString('‾'); CodePointA: 8254; CodePointB: 0),
(Name: UnicodeString('⧀'); CodePointA: 10688; CodePointB: 0),
(Name: UnicodeString('Ō'); CodePointA: 332; CodePointB: 0),
(Name: UnicodeString('ō'); CodePointA: 333; CodePointB: 0),
(Name: UnicodeString('Ω'); CodePointA: 937; CodePointB: 0),
(Name: UnicodeString('ω'); CodePointA: 969; CodePointB: 0),
(Name: UnicodeString('Ο'); CodePointA: 927; CodePointB: 0),
(Name: UnicodeString('ο'); CodePointA: 959; CodePointB: 0),
(Name: UnicodeString('⦶'); CodePointA: 10678; CodePointB: 0),
(Name: UnicodeString('⊖'); CodePointA: 8854; CodePointB: 0),
(Name: UnicodeString('𝕆'); CodePointA: 120134; CodePointB: 0),
(Name: UnicodeString('𝕠'); CodePointA: 120160; CodePointB: 0),
(Name: UnicodeString('⦷'); CodePointA: 10679; CodePointB: 0),
(Name: UnicodeString('“'); CodePointA: 8220; CodePointB: 0),
(Name: UnicodeString('‘'); CodePointA: 8216; CodePointB: 0),
(Name: UnicodeString('⦹'); CodePointA: 10681; CodePointB: 0),
(Name: UnicodeString('⊕'); CodePointA: 8853; CodePointB: 0),
(Name: UnicodeString('↻'); CodePointA: 8635; CodePointB: 0),
(Name: UnicodeString('⩔'); CodePointA: 10836; CodePointB: 0),
(Name: UnicodeString('∨'); CodePointA: 8744; CodePointB: 0),
(Name: UnicodeString('⩝'); CodePointA: 10845; CodePointB: 0),
(Name: UnicodeString('ℴ'); CodePointA: 8500; CodePointB: 0),
(Name: UnicodeString('ℴ'); CodePointA: 8500; CodePointB: 0),
(Name: UnicodeString('ª'); CodePointA: 170; CodePointB: 0),
(Name: UnicodeString('ª'); CodePointA: 170; CodePointB: 0),
(Name: UnicodeString('º'); CodePointA: 186; CodePointB: 0),
(Name: UnicodeString('º'); CodePointA: 186; CodePointB: 0),
(Name: UnicodeString('⊶'); CodePointA: 8886; CodePointB: 0),
(Name: UnicodeString('⩖'); CodePointA: 10838; CodePointB: 0),
(Name: UnicodeString('⩗'); CodePointA: 10839; CodePointB: 0),
(Name: UnicodeString('⩛'); CodePointA: 10843; CodePointB: 0),
(Name: UnicodeString('Ⓢ'); CodePointA: 9416; CodePointB: 0),
(Name: UnicodeString('𝒪'); CodePointA: 119978; CodePointB: 0),
(Name: UnicodeString('ℴ'); CodePointA: 8500; CodePointB: 0),
(Name: UnicodeString('Ø'); CodePointA: 216; CodePointB: 0),
(Name: UnicodeString('Ø'); CodePointA: 216; CodePointB: 0),
(Name: UnicodeString('ø'); CodePointA: 248; CodePointB: 0),
(Name: UnicodeString('ø'); CodePointA: 248; CodePointB: 0),
(Name: UnicodeString('⊘'); CodePointA: 8856; CodePointB: 0),
(Name: UnicodeString('Õ'); CodePointA: 213; CodePointB: 0),
(Name: UnicodeString('Õ'); CodePointA: 213; CodePointB: 0),
(Name: UnicodeString('õ'); CodePointA: 245; CodePointB: 0),
(Name: UnicodeString('õ'); CodePointA: 245; CodePointB: 0),
(Name: UnicodeString('⨶'); CodePointA: 10806; CodePointB: 0),
(Name: UnicodeString('⨷'); CodePointA: 10807; CodePointB: 0),
(Name: UnicodeString('⊗'); CodePointA: 8855; CodePointB: 0),
(Name: UnicodeString('Ö'); CodePointA: 214; CodePointB: 0),
(Name: UnicodeString('Ö'); CodePointA: 214; CodePointB: 0),
(Name: UnicodeString('ö'); CodePointA: 246; CodePointB: 0),
(Name: UnicodeString('ö'); CodePointA: 246; CodePointB: 0),
(Name: UnicodeString('⌽'); CodePointA: 9021; CodePointB: 0),
(Name: UnicodeString('‾'); CodePointA: 8254; CodePointB: 0),
(Name: UnicodeString('⏞'); CodePointA: 9182; CodePointB: 0),
(Name: UnicodeString('⎴'); CodePointA: 9140; CodePointB: 0),
(Name: UnicodeString('⏜'); CodePointA: 9180; CodePointB: 0),
(Name: UnicodeString('¶'); CodePointA: 182; CodePointB: 0),
(Name: UnicodeString('¶'); CodePointA: 182; CodePointB: 0),
(Name: UnicodeString('∥'); CodePointA: 8741; CodePointB: 0),
(Name: UnicodeString('∥'); CodePointA: 8741; CodePointB: 0),
(Name: UnicodeString('⫳'); CodePointA: 10995; CodePointB: 0),
(Name: UnicodeString('⫽'); CodePointA: 11005; CodePointB: 0),
(Name: UnicodeString('∂'); CodePointA: 8706; CodePointB: 0),
(Name: UnicodeString('∂'); CodePointA: 8706; CodePointB: 0),
(Name: UnicodeString('П'); CodePointA: 1055; CodePointB: 0),
(Name: UnicodeString('п'); CodePointA: 1087; CodePointB: 0),
(Name: UnicodeString('%'); CodePointA: 37; CodePointB: 0),
(Name: UnicodeString('.'); CodePointA: 46; CodePointB: 0),
(Name: UnicodeString('‰'); CodePointA: 8240; CodePointB: 0),
(Name: UnicodeString('⊥'); CodePointA: 8869; CodePointB: 0),
(Name: UnicodeString('‱'); CodePointA: 8241; CodePointB: 0),
(Name: UnicodeString('𝔓'); CodePointA: 120083; CodePointB: 0),
(Name: UnicodeString('𝔭'); CodePointA: 120109; CodePointB: 0),
(Name: UnicodeString('Φ'); CodePointA: 934; CodePointB: 0),
(Name: UnicodeString('φ'); CodePointA: 966; CodePointB: 0),
(Name: UnicodeString('ϕ'); CodePointA: 981; CodePointB: 0),
(Name: UnicodeString('ℳ'); CodePointA: 8499; CodePointB: 0),
(Name: UnicodeString('☎'); CodePointA: 9742; CodePointB: 0),
(Name: UnicodeString('Π'); CodePointA: 928; CodePointB: 0),
(Name: UnicodeString('π'); CodePointA: 960; CodePointB: 0),
(Name: UnicodeString('⋔'); CodePointA: 8916; CodePointB: 0),
(Name: UnicodeString('ϖ'); CodePointA: 982; CodePointB: 0),
(Name: UnicodeString('ℏ'); CodePointA: 8463; CodePointB: 0),
(Name: UnicodeString('ℎ'); CodePointA: 8462; CodePointB: 0),
(Name: UnicodeString('ℏ'); CodePointA: 8463; CodePointB: 0),
(Name: UnicodeString('⨣'); CodePointA: 10787; CodePointB: 0),
(Name: UnicodeString('⊞'); CodePointA: 8862; CodePointB: 0),
(Name: UnicodeString('⨢'); CodePointA: 10786; CodePointB: 0),
(Name: UnicodeString('+'); CodePointA: 43; CodePointB: 0),
(Name: UnicodeString('∔'); CodePointA: 8724; CodePointB: 0),
(Name: UnicodeString('⨥'); CodePointA: 10789; CodePointB: 0),
(Name: UnicodeString('⩲'); CodePointA: 10866; CodePointB: 0),
(Name: UnicodeString('±'); CodePointA: 177; CodePointB: 0),
(Name: UnicodeString('±'); CodePointA: 177; CodePointB: 0),
(Name: UnicodeString('±'); CodePointA: 177; CodePointB: 0),
(Name: UnicodeString('⨦'); CodePointA: 10790; CodePointB: 0),
(Name: UnicodeString('⨧'); CodePointA: 10791; CodePointB: 0),
(Name: UnicodeString('±'); CodePointA: 177; CodePointB: 0),
(Name: UnicodeString('ℌ'); CodePointA: 8460; CodePointB: 0),
(Name: UnicodeString('⨕'); CodePointA: 10773; CodePointB: 0),
(Name: UnicodeString('𝕡'); CodePointA: 120161; CodePointB: 0),
(Name: UnicodeString('ℙ'); CodePointA: 8473; CodePointB: 0),
(Name: UnicodeString('£'); CodePointA: 163; CodePointB: 0),
(Name: UnicodeString('£'); CodePointA: 163; CodePointB: 0),
(Name: UnicodeString('⪷'); CodePointA: 10935; CodePointB: 0),
(Name: UnicodeString('⪻'); CodePointA: 10939; CodePointB: 0),
(Name: UnicodeString('≺'); CodePointA: 8826; CodePointB: 0),
(Name: UnicodeString('≼'); CodePointA: 8828; CodePointB: 0),
(Name: UnicodeString('⪷'); CodePointA: 10935; CodePointB: 0),
(Name: UnicodeString('≺'); CodePointA: 8826; CodePointB: 0),
(Name: UnicodeString('≼'); CodePointA: 8828; CodePointB: 0),
(Name: UnicodeString('≺'); CodePointA: 8826; CodePointB: 0),
(Name: UnicodeString('⪯'); CodePointA: 10927; CodePointB: 0),
(Name: UnicodeString('≼'); CodePointA: 8828; CodePointB: 0),
(Name: UnicodeString('≾'); CodePointA: 8830; CodePointB: 0),
(Name: UnicodeString('⪯'); CodePointA: 10927; CodePointB: 0),
(Name: UnicodeString('⪹'); CodePointA: 10937; CodePointB: 0),
(Name: UnicodeString('⪵'); CodePointA: 10933; CodePointB: 0),
(Name: UnicodeString('⋨'); CodePointA: 8936; CodePointB: 0),
(Name: UnicodeString('⪯'); CodePointA: 10927; CodePointB: 0),
(Name: UnicodeString('⪳'); CodePointA: 10931; CodePointB: 0),
(Name: UnicodeString('≾'); CodePointA: 8830; CodePointB: 0),
(Name: UnicodeString('′'); CodePointA: 8242; CodePointB: 0),
(Name: UnicodeString('″'); CodePointA: 8243; CodePointB: 0),
(Name: UnicodeString('ℙ'); CodePointA: 8473; CodePointB: 0),
(Name: UnicodeString('⪹'); CodePointA: 10937; CodePointB: 0),
(Name: UnicodeString('⪵'); CodePointA: 10933; CodePointB: 0),
(Name: UnicodeString('⋨'); CodePointA: 8936; CodePointB: 0),
(Name: UnicodeString('∏'); CodePointA: 8719; CodePointB: 0),
(Name: UnicodeString('∏'); CodePointA: 8719; CodePointB: 0),
(Name: UnicodeString('⌮'); CodePointA: 9006; CodePointB: 0),
(Name: UnicodeString('⌒'); CodePointA: 8978; CodePointB: 0),
(Name: UnicodeString('⌓'); CodePointA: 8979; CodePointB: 0),
(Name: UnicodeString('∝'); CodePointA: 8733; CodePointB: 0),
(Name: UnicodeString('∝'); CodePointA: 8733; CodePointB: 0),
(Name: UnicodeString('∷'); CodePointA: 8759; CodePointB: 0),
(Name: UnicodeString('∝'); CodePointA: 8733; CodePointB: 0),
(Name: UnicodeString('≾'); CodePointA: 8830; CodePointB: 0),
(Name: UnicodeString('⊰'); CodePointA: 8880; CodePointB: 0),
(Name: UnicodeString('𝒫'); CodePointA: 119979; CodePointB: 0),
(Name: UnicodeString('𝓅'); CodePointA: 120005; CodePointB: 0),
(Name: UnicodeString('Ψ'); CodePointA: 936; CodePointB: 0),
(Name: UnicodeString('ψ'); CodePointA: 968; CodePointB: 0),
(Name: UnicodeString(' '); CodePointA: 8200; CodePointB: 0),
(Name: UnicodeString('𝔔'); CodePointA: 120084; CodePointB: 0),
(Name: UnicodeString('𝔮'); CodePointA: 120110; CodePointB: 0),
(Name: UnicodeString('⨌'); CodePointA: 10764; CodePointB: 0),
(Name: UnicodeString('𝕢'); CodePointA: 120162; CodePointB: 0),
(Name: UnicodeString('ℚ'); CodePointA: 8474; CodePointB: 0),
(Name: UnicodeString('⁗'); CodePointA: 8279; CodePointB: 0),
(Name: UnicodeString('𝒬'); CodePointA: 119980; CodePointB: 0),
(Name: UnicodeString('𝓆'); CodePointA: 120006; CodePointB: 0),
(Name: UnicodeString('ℍ'); CodePointA: 8461; CodePointB: 0),
(Name: UnicodeString('⨖'); CodePointA: 10774; CodePointB: 0),
(Name: UnicodeString('?'); CodePointA: 63; CodePointB: 0),
(Name: UnicodeString('≟'); CodePointA: 8799; CodePointB: 0),
(Name: UnicodeString('"'); CodePointA: 34; CodePointB: 0),
(Name: UnicodeString('"'); CodePointA: 34; CodePointB: 0),
(Name: UnicodeString('"'); CodePointA: 34; CodePointB: 0),
(Name: UnicodeString('"'); CodePointA: 34; CodePointB: 0),
(Name: UnicodeString('⇛'); CodePointA: 8667; CodePointB: 0),
(Name: UnicodeString('∽̱'); CodePointA: 8765; CodePointB: 817),
(Name: UnicodeString('Ŕ'); CodePointA: 340; CodePointB: 0),
(Name: UnicodeString('ŕ'); CodePointA: 341; CodePointB: 0),
(Name: UnicodeString('√'); CodePointA: 8730; CodePointB: 0),
(Name: UnicodeString('⦳'); CodePointA: 10675; CodePointB: 0),
(Name: UnicodeString('⟩'); CodePointA: 10217; CodePointB: 0),
(Name: UnicodeString('⟫'); CodePointA: 10219; CodePointB: 0),
(Name: UnicodeString('⦒'); CodePointA: 10642; CodePointB: 0),
(Name: UnicodeString('⦥'); CodePointA: 10661; CodePointB: 0),
(Name: UnicodeString('⟩'); CodePointA: 10217; CodePointB: 0),
(Name: UnicodeString('»'); CodePointA: 187; CodePointB: 0),
(Name: UnicodeString('»'); CodePointA: 187; CodePointB: 0),
(Name: UnicodeString('⥵'); CodePointA: 10613; CodePointB: 0),
(Name: UnicodeString('⇥'); CodePointA: 8677; CodePointB: 0),
(Name: UnicodeString('⤠'); CodePointA: 10528; CodePointB: 0),
(Name: UnicodeString('⤳'); CodePointA: 10547; CodePointB: 0),
(Name: UnicodeString('→'); CodePointA: 8594; CodePointB: 0),
(Name: UnicodeString('↠'); CodePointA: 8608; CodePointB: 0),
(Name: UnicodeString('⇒'); CodePointA: 8658; CodePointB: 0),
(Name: UnicodeString('⤞'); CodePointA: 10526; CodePointB: 0),
(Name: UnicodeString('↪'); CodePointA: 8618; CodePointB: 0),
(Name: UnicodeString('↬'); CodePointA: 8620; CodePointB: 0),
(Name: UnicodeString('⥅'); CodePointA: 10565; CodePointB: 0),
(Name: UnicodeString('⥴'); CodePointA: 10612; CodePointB: 0),
(Name: UnicodeString('⤖'); CodePointA: 10518; CodePointB: 0),
(Name: UnicodeString('↣'); CodePointA: 8611; CodePointB: 0),
(Name: UnicodeString('↝'); CodePointA: 8605; CodePointB: 0),
(Name: UnicodeString('⤚'); CodePointA: 10522; CodePointB: 0),
(Name: UnicodeString('⤜'); CodePointA: 10524; CodePointB: 0),
(Name: UnicodeString('∶'); CodePointA: 8758; CodePointB: 0),
(Name: UnicodeString('ℚ'); CodePointA: 8474; CodePointB: 0),
(Name: UnicodeString('⤍'); CodePointA: 10509; CodePointB: 0),
(Name: UnicodeString('⤏'); CodePointA: 10511; CodePointB: 0),
(Name: UnicodeString('⤐'); CodePointA: 10512; CodePointB: 0),
(Name: UnicodeString('❳'); CodePointA: 10099; CodePointB: 0),
(Name: UnicodeString('}'); CodePointA: 125; CodePointB: 0),
(Name: UnicodeString(']'); CodePointA: 93; CodePointB: 0),
(Name: UnicodeString('⦌'); CodePointA: 10636; CodePointB: 0),
(Name: UnicodeString('⦎'); CodePointA: 10638; CodePointB: 0),
(Name: UnicodeString('⦐'); CodePointA: 10640; CodePointB: 0),
(Name: UnicodeString('Ř'); CodePointA: 344; CodePointB: 0),
(Name: UnicodeString('ř'); CodePointA: 345; CodePointB: 0),
(Name: UnicodeString('Ŗ'); CodePointA: 342; CodePointB: 0),
(Name: UnicodeString('ŗ'); CodePointA: 343; CodePointB: 0),
(Name: UnicodeString('⌉'); CodePointA: 8969; CodePointB: 0),
(Name: UnicodeString('}'); CodePointA: 125; CodePointB: 0),
(Name: UnicodeString('Р'); CodePointA: 1056; CodePointB: 0),
(Name: UnicodeString('р'); CodePointA: 1088; CodePointB: 0),
(Name: UnicodeString('⤷'); CodePointA: 10551; CodePointB: 0),
(Name: UnicodeString('⥩'); CodePointA: 10601; CodePointB: 0),
(Name: UnicodeString('”'); CodePointA: 8221; CodePointB: 0),
(Name: UnicodeString('”'); CodePointA: 8221; CodePointB: 0),
(Name: UnicodeString('↳'); CodePointA: 8627; CodePointB: 0),
(Name: UnicodeString('ℜ'); CodePointA: 8476; CodePointB: 0),
(Name: UnicodeString('ℛ'); CodePointA: 8475; CodePointB: 0),
(Name: UnicodeString('ℜ'); CodePointA: 8476; CodePointB: 0),
(Name: UnicodeString('ℝ'); CodePointA: 8477; CodePointB: 0),
(Name: UnicodeString('ℜ'); CodePointA: 8476; CodePointB: 0),
(Name: UnicodeString('▭'); CodePointA: 9645; CodePointB: 0),
(Name: UnicodeString('®'); CodePointA: 174; CodePointB: 0),
(Name: UnicodeString('®'); CodePointA: 174; CodePointB: 0),
(Name: UnicodeString('®'); CodePointA: 174; CodePointB: 0),
(Name: UnicodeString('®'); CodePointA: 174; CodePointB: 0),
(Name: UnicodeString('∋'); CodePointA: 8715; CodePointB: 0),
(Name: UnicodeString('⇋'); CodePointA: 8651; CodePointB: 0),
(Name: UnicodeString('⥯'); CodePointA: 10607; CodePointB: 0),
(Name: UnicodeString('⥽'); CodePointA: 10621; CodePointB: 0),
(Name: UnicodeString('⌋'); CodePointA: 8971; CodePointB: 0),
(Name: UnicodeString('𝔯'); CodePointA: 120111; CodePointB: 0),
(Name: UnicodeString('ℜ'); CodePointA: 8476; CodePointB: 0),
(Name: UnicodeString('⥤'); CodePointA: 10596; CodePointB: 0),
(Name: UnicodeString('⇁'); CodePointA: 8641; CodePointB: 0),
(Name: UnicodeString('⇀'); CodePointA: 8640; CodePointB: 0),
(Name: UnicodeString('⥬'); CodePointA: 10604; CodePointB: 0),
(Name: UnicodeString('Ρ'); CodePointA: 929; CodePointB: 0),
(Name: UnicodeString('ρ'); CodePointA: 961; CodePointB: 0),
(Name: UnicodeString('ϱ'); CodePointA: 1009; CodePointB: 0),
(Name: UnicodeString('⟩'); CodePointA: 10217; CodePointB: 0),
(Name: UnicodeString('⇥'); CodePointA: 8677; CodePointB: 0),
(Name: UnicodeString('→'); CodePointA: 8594; CodePointB: 0),
(Name: UnicodeString('→'); CodePointA: 8594; CodePointB: 0),
(Name: UnicodeString('⇒'); CodePointA: 8658; CodePointB: 0),
(Name: UnicodeString('⇄'); CodePointA: 8644; CodePointB: 0),
(Name: UnicodeString('↣'); CodePointA: 8611; CodePointB: 0),
(Name: UnicodeString('⌉'); CodePointA: 8969; CodePointB: 0),
(Name: UnicodeString('⟧'); CodePointA: 10215; CodePointB: 0),
(Name: UnicodeString('⥝'); CodePointA: 10589; CodePointB: 0),
(Name: UnicodeString('⥕'); CodePointA: 10581; CodePointB: 0),
(Name: UnicodeString('⇂'); CodePointA: 8642; CodePointB: 0),
(Name: UnicodeString('⌋'); CodePointA: 8971; CodePointB: 0),
(Name: UnicodeString('⇁'); CodePointA: 8641; CodePointB: 0),
(Name: UnicodeString('⇀'); CodePointA: 8640; CodePointB: 0),
(Name: UnicodeString('⇄'); CodePointA: 8644; CodePointB: 0),
(Name: UnicodeString('⇌'); CodePointA: 8652; CodePointB: 0),
(Name: UnicodeString('⇉'); CodePointA: 8649; CodePointB: 0),
(Name: UnicodeString('↝'); CodePointA: 8605; CodePointB: 0),
(Name: UnicodeString('↦'); CodePointA: 8614; CodePointB: 0),
(Name: UnicodeString('⊢'); CodePointA: 8866; CodePointB: 0),
(Name: UnicodeString('⥛'); CodePointA: 10587; CodePointB: 0),
(Name: UnicodeString('⋌'); CodePointA: 8908; CodePointB: 0),
(Name: UnicodeString('⧐'); CodePointA: 10704; CodePointB: 0),
(Name: UnicodeString('⊳'); CodePointA: 8883; CodePointB: 0),
(Name: UnicodeString('⊵'); CodePointA: 8885; CodePointB: 0),
(Name: UnicodeString('⥏'); CodePointA: 10575; CodePointB: 0),
(Name: UnicodeString('⥜'); CodePointA: 10588; CodePointB: 0),
(Name: UnicodeString('⥔'); CodePointA: 10580; CodePointB: 0),
(Name: UnicodeString('↾'); CodePointA: 8638; CodePointB: 0),
(Name: UnicodeString('⥓'); CodePointA: 10579; CodePointB: 0),
(Name: UnicodeString('⇀'); CodePointA: 8640; CodePointB: 0),
(Name: UnicodeString('˚'); CodePointA: 730; CodePointB: 0),
(Name: UnicodeString('≓'); CodePointA: 8787; CodePointB: 0),
(Name: UnicodeString('⇄'); CodePointA: 8644; CodePointB: 0),
(Name: UnicodeString('⇌'); CodePointA: 8652; CodePointB: 0),
(Name: UnicodeString('‏'); CodePointA: 8207; CodePointB: 0),
(Name: UnicodeString('⎱'); CodePointA: 9137; CodePointB: 0),
(Name: UnicodeString('⎱'); CodePointA: 9137; CodePointB: 0),
(Name: UnicodeString('⫮'); CodePointA: 10990; CodePointB: 0),
(Name: UnicodeString('⟭'); CodePointA: 10221; CodePointB: 0),
(Name: UnicodeString('⇾'); CodePointA: 8702; CodePointB: 0),
(Name: UnicodeString('⟧'); CodePointA: 10215; CodePointB: 0),
(Name: UnicodeString('⦆'); CodePointA: 10630; CodePointB: 0),
(Name: UnicodeString('𝕣'); CodePointA: 120163; CodePointB: 0),
(Name: UnicodeString('ℝ'); CodePointA: 8477; CodePointB: 0),
(Name: UnicodeString('⨮'); CodePointA: 10798; CodePointB: 0),
(Name: UnicodeString('⨵'); CodePointA: 10805; CodePointB: 0),
(Name: UnicodeString('⥰'); CodePointA: 10608; CodePointB: 0),
(Name: UnicodeString(')'); CodePointA: 41; CodePointB: 0),
(Name: UnicodeString('⦔'); CodePointA: 10644; CodePointB: 0),
(Name: UnicodeString('⨒'); CodePointA: 10770; CodePointB: 0),
(Name: UnicodeString('⇉'); CodePointA: 8649; CodePointB: 0),
(Name: UnicodeString('⇛'); CodePointA: 8667; CodePointB: 0),
(Name: UnicodeString('›'); CodePointA: 8250; CodePointB: 0),
(Name: UnicodeString('𝓇'); CodePointA: 120007; CodePointB: 0),
(Name: UnicodeString('ℛ'); CodePointA: 8475; CodePointB: 0),
(Name: UnicodeString('↱'); CodePointA: 8625; CodePointB: 0),
(Name: UnicodeString('↱'); CodePointA: 8625; CodePointB: 0),
(Name: UnicodeString(']'); CodePointA: 93; CodePointB: 0),
(Name: UnicodeString('’'); CodePointA: 8217; CodePointB: 0),
(Name: UnicodeString('’'); CodePointA: 8217; CodePointB: 0),
(Name: UnicodeString('⋌'); CodePointA: 8908; CodePointB: 0),
(Name: UnicodeString('⋊'); CodePointA: 8906; CodePointB: 0),
(Name: UnicodeString('▹'); CodePointA: 9657; CodePointB: 0),
(Name: UnicodeString('⊵'); CodePointA: 8885; CodePointB: 0),
(Name: UnicodeString('▸'); CodePointA: 9656; CodePointB: 0),
(Name: UnicodeString('⧎'); CodePointA: 10702; CodePointB: 0),
(Name: UnicodeString('⧴'); CodePointA: 10740; CodePointB: 0),
(Name: UnicodeString('⥨'); CodePointA: 10600; CodePointB: 0),
(Name: UnicodeString('℞'); CodePointA: 8478; CodePointB: 0),
(Name: UnicodeString('Ś'); CodePointA: 346; CodePointB: 0),
(Name: UnicodeString('ś'); CodePointA: 347; CodePointB: 0),
(Name: UnicodeString('‚'); CodePointA: 8218; CodePointB: 0),
(Name: UnicodeString('⪸'); CodePointA: 10936; CodePointB: 0),
(Name: UnicodeString('Š'); CodePointA: 352; CodePointB: 0),
(Name: UnicodeString('š'); CodePointA: 353; CodePointB: 0),
(Name: UnicodeString('⪼'); CodePointA: 10940; CodePointB: 0),
(Name: UnicodeString('≻'); CodePointA: 8827; CodePointB: 0),
(Name: UnicodeString('≽'); CodePointA: 8829; CodePointB: 0),
(Name: UnicodeString('⪰'); CodePointA: 10928; CodePointB: 0),
(Name: UnicodeString('⪴'); CodePointA: 10932; CodePointB: 0),
(Name: UnicodeString('Ş'); CodePointA: 350; CodePointB: 0),
(Name: UnicodeString('ş'); CodePointA: 351; CodePointB: 0),
(Name: UnicodeString('Ŝ'); CodePointA: 348; CodePointB: 0),
(Name: UnicodeString('ŝ'); CodePointA: 349; CodePointB: 0),
(Name: UnicodeString('⪺'); CodePointA: 10938; CodePointB: 0),
(Name: UnicodeString('⪶'); CodePointA: 10934; CodePointB: 0),
(Name: UnicodeString('⋩'); CodePointA: 8937; CodePointB: 0),
(Name: UnicodeString('⨓'); CodePointA: 10771; CodePointB: 0),
(Name: UnicodeString('≿'); CodePointA: 8831; CodePointB: 0),
(Name: UnicodeString('С'); CodePointA: 1057; CodePointB: 0),
(Name: UnicodeString('с'); CodePointA: 1089; CodePointB: 0),
(Name: UnicodeString('⊡'); CodePointA: 8865; CodePointB: 0),
(Name: UnicodeString('⋅'); CodePointA: 8901; CodePointB: 0),
(Name: UnicodeString('⩦'); CodePointA: 10854; CodePointB: 0),
(Name: UnicodeString('⤥'); CodePointA: 10533; CodePointB: 0),
(Name: UnicodeString('↘'); CodePointA: 8600; CodePointB: 0),
(Name: UnicodeString('⇘'); CodePointA: 8664; CodePointB: 0),
(Name: UnicodeString('↘'); CodePointA: 8600; CodePointB: 0),
(Name: UnicodeString('§'); CodePointA: 167; CodePointB: 0),
(Name: UnicodeString('§'); CodePointA: 167; CodePointB: 0),
(Name: UnicodeString(';'); CodePointA: 59; CodePointB: 0),
(Name: UnicodeString('⤩'); CodePointA: 10537; CodePointB: 0),
(Name: UnicodeString('∖'); CodePointA: 8726; CodePointB: 0),
(Name: UnicodeString('∖'); CodePointA: 8726; CodePointB: 0),
(Name: UnicodeString('✶'); CodePointA: 10038; CodePointB: 0),
(Name: UnicodeString('𝔖'); CodePointA: 120086; CodePointB: 0),
(Name: UnicodeString('𝔰'); CodePointA: 120112; CodePointB: 0),
(Name: UnicodeString('⌢'); CodePointA: 8994; CodePointB: 0),
(Name: UnicodeString('♯'); CodePointA: 9839; CodePointB: 0),
(Name: UnicodeString('Щ'); CodePointA: 1065; CodePointB: 0),
(Name: UnicodeString('щ'); CodePointA: 1097; CodePointB: 0),
(Name: UnicodeString('Ш'); CodePointA: 1064; CodePointB: 0),
(Name: UnicodeString('ш'); CodePointA: 1096; CodePointB: 0),
(Name: UnicodeString('↓'); CodePointA: 8595; CodePointB: 0),
(Name: UnicodeString('←'); CodePointA: 8592; CodePointB: 0),
(Name: UnicodeString('∣'); CodePointA: 8739; CodePointB: 0),
(Name: UnicodeString('∥'); CodePointA: 8741; CodePointB: 0),
(Name: UnicodeString('→'); CodePointA: 8594; CodePointB: 0),
(Name: UnicodeString('↑'); CodePointA: 8593; CodePointB: 0),
(Name: UnicodeString('­'); CodePointA: 173; CodePointB: 0),
(Name: UnicodeString('­'); CodePointA: 173; CodePointB: 0),
(Name: UnicodeString('Σ'); CodePointA: 931; CodePointB: 0),
(Name: UnicodeString('σ'); CodePointA: 963; CodePointB: 0),
(Name: UnicodeString('ς'); CodePointA: 962; CodePointB: 0),
(Name: UnicodeString('ς'); CodePointA: 962; CodePointB: 0),
(Name: UnicodeString('∼'); CodePointA: 8764; CodePointB: 0),
(Name: UnicodeString('⩪'); CodePointA: 10858; CodePointB: 0),
(Name: UnicodeString('≃'); CodePointA: 8771; CodePointB: 0),
(Name: UnicodeString('≃'); CodePointA: 8771; CodePointB: 0),
(Name: UnicodeString('⪞'); CodePointA: 10910; CodePointB: 0),
(Name: UnicodeString('⪠'); CodePointA: 10912; CodePointB: 0),
(Name: UnicodeString('⪝'); CodePointA: 10909; CodePointB: 0),
(Name: UnicodeString('⪟'); CodePointA: 10911; CodePointB: 0),
(Name: UnicodeString('≆'); CodePointA: 8774; CodePointB: 0),
(Name: UnicodeString('⨤'); CodePointA: 10788; CodePointB: 0),
(Name: UnicodeString('⥲'); CodePointA: 10610; CodePointB: 0),
(Name: UnicodeString('←'); CodePointA: 8592; CodePointB: 0),
(Name: UnicodeString('∘'); CodePointA: 8728; CodePointB: 0),
(Name: UnicodeString('∖'); CodePointA: 8726; CodePointB: 0),
(Name: UnicodeString('⨳'); CodePointA: 10803; CodePointB: 0),
(Name: UnicodeString('⧤'); CodePointA: 10724; CodePointB: 0),
(Name: UnicodeString('∣'); CodePointA: 8739; CodePointB: 0),
(Name: UnicodeString('⌣'); CodePointA: 8995; CodePointB: 0),
(Name: UnicodeString('⪪'); CodePointA: 10922; CodePointB: 0),
(Name: UnicodeString('⪬'); CodePointA: 10924; CodePointB: 0),
(Name: UnicodeString('⪬︀'); CodePointA: 10924; CodePointB: 65024),
(Name: UnicodeString('Ь'); CodePointA: 1068; CodePointB: 0),
(Name: UnicodeString('ь'); CodePointA: 1100; CodePointB: 0),
(Name: UnicodeString('⌿'); CodePointA: 9023; CodePointB: 0),
(Name: UnicodeString('⧄'); CodePointA: 10692; CodePointB: 0),
(Name: UnicodeString('/'); CodePointA: 47; CodePointB: 0),
(Name: UnicodeString('𝕊'); CodePointA: 120138; CodePointB: 0),
(Name: UnicodeString('𝕤'); CodePointA: 120164; CodePointB: 0),
(Name: UnicodeString('♠'); CodePointA: 9824; CodePointB: 0),
(Name: UnicodeString('♠'); CodePointA: 9824; CodePointB: 0),
(Name: UnicodeString('∥'); CodePointA: 8741; CodePointB: 0),
(Name: UnicodeString('⊓'); CodePointA: 8851; CodePointB: 0),
(Name: UnicodeString('⊓︀'); CodePointA: 8851; CodePointB: 65024),
(Name: UnicodeString('⊔'); CodePointA: 8852; CodePointB: 0),
(Name: UnicodeString('⊔︀'); CodePointA: 8852; CodePointB: 65024),
(Name: UnicodeString('√'); CodePointA: 8730; CodePointB: 0),
(Name: UnicodeString('⊏'); CodePointA: 8847; CodePointB: 0),
(Name: UnicodeString('⊑'); CodePointA: 8849; CodePointB: 0),
(Name: UnicodeString('⊏'); CodePointA: 8847; CodePointB: 0),
(Name: UnicodeString('⊑'); CodePointA: 8849; CodePointB: 0),
(Name: UnicodeString('⊐'); CodePointA: 8848; CodePointB: 0),
(Name: UnicodeString('⊒'); CodePointA: 8850; CodePointB: 0),
(Name: UnicodeString('⊐'); CodePointA: 8848; CodePointB: 0),
(Name: UnicodeString('⊒'); CodePointA: 8850; CodePointB: 0),
(Name: UnicodeString('□'); CodePointA: 9633; CodePointB: 0),
(Name: UnicodeString('□'); CodePointA: 9633; CodePointB: 0),
(Name: UnicodeString('⊓'); CodePointA: 8851; CodePointB: 0),
(Name: UnicodeString('⊏'); CodePointA: 8847; CodePointB: 0),
(Name: UnicodeString('⊑'); CodePointA: 8849; CodePointB: 0),
(Name: UnicodeString('⊐'); CodePointA: 8848; CodePointB: 0),
(Name: UnicodeString('⊒'); CodePointA: 8850; CodePointB: 0),
(Name: UnicodeString('⊔'); CodePointA: 8852; CodePointB: 0),
(Name: UnicodeString('▪'); CodePointA: 9642; CodePointB: 0),
(Name: UnicodeString('□'); CodePointA: 9633; CodePointB: 0),
(Name: UnicodeString('▪'); CodePointA: 9642; CodePointB: 0),
(Name: UnicodeString('→'); CodePointA: 8594; CodePointB: 0),
(Name: UnicodeString('𝒮'); CodePointA: 119982; CodePointB: 0),
(Name: UnicodeString('𝓈'); CodePointA: 120008; CodePointB: 0),
(Name: UnicodeString('∖'); CodePointA: 8726; CodePointB: 0),
(Name: UnicodeString('⌣'); CodePointA: 8995; CodePointB: 0),
(Name: UnicodeString('⋆'); CodePointA: 8902; CodePointB: 0),
(Name: UnicodeString('⋆'); CodePointA: 8902; CodePointB: 0),
(Name: UnicodeString('☆'); CodePointA: 9734; CodePointB: 0),
(Name: UnicodeString('★'); CodePointA: 9733; CodePointB: 0),
(Name: UnicodeString('ϵ'); CodePointA: 1013; CodePointB: 0),
(Name: UnicodeString('ϕ'); CodePointA: 981; CodePointB: 0),
(Name: UnicodeString('¯'); CodePointA: 175; CodePointB: 0),
(Name: UnicodeString('⊂'); CodePointA: 8834; CodePointB: 0),
(Name: UnicodeString('⋐'); CodePointA: 8912; CodePointB: 0),
(Name: UnicodeString('⪽'); CodePointA: 10941; CodePointB: 0),
(Name: UnicodeString('⫅'); CodePointA: 10949; CodePointB: 0),
(Name: UnicodeString('⊆'); CodePointA: 8838; CodePointB: 0),
(Name: UnicodeString('⫃'); CodePointA: 10947; CodePointB: 0),
(Name: UnicodeString('⫁'); CodePointA: 10945; CodePointB: 0),
(Name: UnicodeString('⫋'); CodePointA: 10955; CodePointB: 0),
(Name: UnicodeString('⊊'); CodePointA: 8842; CodePointB: 0),
(Name: UnicodeString('⪿'); CodePointA: 10943; CodePointB: 0),
(Name: UnicodeString('⥹'); CodePointA: 10617; CodePointB: 0),
(Name: UnicodeString('⊂'); CodePointA: 8834; CodePointB: 0),
(Name: UnicodeString('⋐'); CodePointA: 8912; CodePointB: 0),
(Name: UnicodeString('⊆'); CodePointA: 8838; CodePointB: 0),
(Name: UnicodeString('⫅'); CodePointA: 10949; CodePointB: 0),
(Name: UnicodeString('⊆'); CodePointA: 8838; CodePointB: 0),
(Name: UnicodeString('⊊'); CodePointA: 8842; CodePointB: 0),
(Name: UnicodeString('⫋'); CodePointA: 10955; CodePointB: 0),
(Name: UnicodeString('⫇'); CodePointA: 10951; CodePointB: 0),
(Name: UnicodeString('⫕'); CodePointA: 10965; CodePointB: 0),
(Name: UnicodeString('⫓'); CodePointA: 10963; CodePointB: 0),
(Name: UnicodeString('⪸'); CodePointA: 10936; CodePointB: 0),
(Name: UnicodeString('≻'); CodePointA: 8827; CodePointB: 0),
(Name: UnicodeString('≽'); CodePointA: 8829; CodePointB: 0),
(Name: UnicodeString('≻'); CodePointA: 8827; CodePointB: 0),
(Name: UnicodeString('⪰'); CodePointA: 10928; CodePointB: 0),
(Name: UnicodeString('≽'); CodePointA: 8829; CodePointB: 0),
(Name: UnicodeString('≿'); CodePointA: 8831; CodePointB: 0),
(Name: UnicodeString('⪰'); CodePointA: 10928; CodePointB: 0),
(Name: UnicodeString('⪺'); CodePointA: 10938; CodePointB: 0),
(Name: UnicodeString('⪶'); CodePointA: 10934; CodePointB: 0),
(Name: UnicodeString('⋩'); CodePointA: 8937; CodePointB: 0),
(Name: UnicodeString('≿'); CodePointA: 8831; CodePointB: 0),
(Name: UnicodeString('∋'); CodePointA: 8715; CodePointB: 0),
(Name: UnicodeString('∑'); CodePointA: 8721; CodePointB: 0),
(Name: UnicodeString('∑'); CodePointA: 8721; CodePointB: 0),
(Name: UnicodeString('♪'); CodePointA: 9834; CodePointB: 0),
(Name: UnicodeString('¹'); CodePointA: 185; CodePointB: 0),
(Name: UnicodeString('¹'); CodePointA: 185; CodePointB: 0),
(Name: UnicodeString('²'); CodePointA: 178; CodePointB: 0),
(Name: UnicodeString('²'); CodePointA: 178; CodePointB: 0),
(Name: UnicodeString('³'); CodePointA: 179; CodePointB: 0),
(Name: UnicodeString('³'); CodePointA: 179; CodePointB: 0),
(Name: UnicodeString('⊃'); CodePointA: 8835; CodePointB: 0),
(Name: UnicodeString('⋑'); CodePointA: 8913; CodePointB: 0),
(Name: UnicodeString('⪾'); CodePointA: 10942; CodePointB: 0),
(Name: UnicodeString('⫘'); CodePointA: 10968; CodePointB: 0),
(Name: UnicodeString('⫆'); CodePointA: 10950; CodePointB: 0),
(Name: UnicodeString('⊇'); CodePointA: 8839; CodePointB: 0),
(Name: UnicodeString('⫄'); CodePointA: 10948; CodePointB: 0),
(Name: UnicodeString('⊃'); CodePointA: 8835; CodePointB: 0),
(Name: UnicodeString('⊇'); CodePointA: 8839; CodePointB: 0),
(Name: UnicodeString('⟉'); CodePointA: 10185; CodePointB: 0),
(Name: UnicodeString('⫗'); CodePointA: 10967; CodePointB: 0),
(Name: UnicodeString('⥻'); CodePointA: 10619; CodePointB: 0),
(Name: UnicodeString('⫂'); CodePointA: 10946; CodePointB: 0),
(Name: UnicodeString('⫌'); CodePointA: 10956; CodePointB: 0),
(Name: UnicodeString('⊋'); CodePointA: 8843; CodePointB: 0),
(Name: UnicodeString('⫀'); CodePointA: 10944; CodePointB: 0),
(Name: UnicodeString('⊃'); CodePointA: 8835; CodePointB: 0),
(Name: UnicodeString('⋑'); CodePointA: 8913; CodePointB: 0),
(Name: UnicodeString('⊇'); CodePointA: 8839; CodePointB: 0),
(Name: UnicodeString('⫆'); CodePointA: 10950; CodePointB: 0),
(Name: UnicodeString('⊋'); CodePointA: 8843; CodePointB: 0),
(Name: UnicodeString('⫌'); CodePointA: 10956; CodePointB: 0),
(Name: UnicodeString('⫈'); CodePointA: 10952; CodePointB: 0),
(Name: UnicodeString('⫔'); CodePointA: 10964; CodePointB: 0),
(Name: UnicodeString('⫖'); CodePointA: 10966; CodePointB: 0),
(Name: UnicodeString('⤦'); CodePointA: 10534; CodePointB: 0),
(Name: UnicodeString('↙'); CodePointA: 8601; CodePointB: 0),
(Name: UnicodeString('⇙'); CodePointA: 8665; CodePointB: 0),
(Name: UnicodeString('↙'); CodePointA: 8601; CodePointB: 0),
(Name: UnicodeString('⤪'); CodePointA: 10538; CodePointB: 0),
(Name: UnicodeString('ß'); CodePointA: 223; CodePointB: 0),
(Name: UnicodeString('ß'); CodePointA: 223; CodePointB: 0),
(Name: UnicodeString('	'); CodePointA: 9; CodePointB: 0),
(Name: UnicodeString('⌖'); CodePointA: 8982; CodePointB: 0),
(Name: UnicodeString('Τ'); CodePointA: 932; CodePointB: 0),
(Name: UnicodeString('τ'); CodePointA: 964; CodePointB: 0),
(Name: UnicodeString('⎴'); CodePointA: 9140; CodePointB: 0),
(Name: UnicodeString('Ť'); CodePointA: 356; CodePointB: 0),
(Name: UnicodeString('ť'); CodePointA: 357; CodePointB: 0),
(Name: UnicodeString('Ţ'); CodePointA: 354; CodePointB: 0),
(Name: UnicodeString('ţ'); CodePointA: 355; CodePointB: 0),
(Name: UnicodeString('Т'); CodePointA: 1058; CodePointB: 0),
(Name: UnicodeString('т'); CodePointA: 1090; CodePointB: 0),
(Name: UnicodeString('⃛'); CodePointA: 8411; CodePointB: 0),
(Name: UnicodeString('⌕'); CodePointA: 8981; CodePointB: 0),
(Name: UnicodeString('𝔗'); CodePointA: 120087; CodePointB: 0),
(Name: UnicodeString('𝔱'); CodePointA: 120113; CodePointB: 0),
(Name: UnicodeString('∴'); CodePointA: 8756; CodePointB: 0),
(Name: UnicodeString('∴'); CodePointA: 8756; CodePointB: 0),
(Name: UnicodeString('∴'); CodePointA: 8756; CodePointB: 0),
(Name: UnicodeString('Θ'); CodePointA: 920; CodePointB: 0),
(Name: UnicodeString('θ'); CodePointA: 952; CodePointB: 0),
(Name: UnicodeString('ϑ'); CodePointA: 977; CodePointB: 0),
(Name: UnicodeString('ϑ'); CodePointA: 977; CodePointB: 0),
(Name: UnicodeString('≈'); CodePointA: 8776; CodePointB: 0),
(Name: UnicodeString('∼'); CodePointA: 8764; CodePointB: 0),
(Name: UnicodeString('  '); CodePointA: 8287; CodePointB: 8202),
(Name: UnicodeString(' '); CodePointA: 8201; CodePointB: 0),
(Name: UnicodeString(' '); CodePointA: 8201; CodePointB: 0),
(Name: UnicodeString('≈'); CodePointA: 8776; CodePointB: 0),
(Name: UnicodeString('∼'); CodePointA: 8764; CodePointB: 0),
(Name: UnicodeString('Þ'); CodePointA: 222; CodePointB: 0),
(Name: UnicodeString('Þ'); CodePointA: 222; CodePointB: 0),
(Name: UnicodeString('þ'); CodePointA: 254; CodePointB: 0),
(Name: UnicodeString('þ'); CodePointA: 254; CodePointB: 0),
(Name: UnicodeString('˜'); CodePointA: 732; CodePointB: 0),
(Name: UnicodeString('∼'); CodePointA: 8764; CodePointB: 0),
(Name: UnicodeString('≃'); CodePointA: 8771; CodePointB: 0),
(Name: UnicodeString('≅'); CodePointA: 8773; CodePointB: 0),
(Name: UnicodeString('≈'); CodePointA: 8776; CodePointB: 0),
(Name: UnicodeString('⨱'); CodePointA: 10801; CodePointB: 0),
(Name: UnicodeString('⊠'); CodePointA: 8864; CodePointB: 0),
(Name: UnicodeString('×'); CodePointA: 215; CodePointB: 0),
(Name: UnicodeString('×'); CodePointA: 215; CodePointB: 0),
(Name: UnicodeString('⨰'); CodePointA: 10800; CodePointB: 0),
(Name: UnicodeString('∭'); CodePointA: 8749; CodePointB: 0),
(Name: UnicodeString('⤨'); CodePointA: 10536; CodePointB: 0),
(Name: UnicodeString('⌶'); CodePointA: 9014; CodePointB: 0),
(Name: UnicodeString('⫱'); CodePointA: 10993; CodePointB: 0),
(Name: UnicodeString('⊤'); CodePointA: 8868; CodePointB: 0),
(Name: UnicodeString('𝕋'); CodePointA: 120139; CodePointB: 0),
(Name: UnicodeString('𝕥'); CodePointA: 120165; CodePointB: 0),
(Name: UnicodeString('⫚'); CodePointA: 10970; CodePointB: 0),
(Name: UnicodeString('⤩'); CodePointA: 10537; CodePointB: 0),
(Name: UnicodeString('‴'); CodePointA: 8244; CodePointB: 0),
(Name: UnicodeString('™'); CodePointA: 8482; CodePointB: 0),
(Name: UnicodeString('™'); CodePointA: 8482; CodePointB: 0),
(Name: UnicodeString('▵'); CodePointA: 9653; CodePointB: 0),
(Name: UnicodeString('▿'); CodePointA: 9663; CodePointB: 0),
(Name: UnicodeString('◃'); CodePointA: 9667; CodePointB: 0),
(Name: UnicodeString('⊴'); CodePointA: 8884; CodePointB: 0),
(Name: UnicodeString('≜'); CodePointA: 8796; CodePointB: 0),
(Name: UnicodeString('▹'); CodePointA: 9657; CodePointB: 0),
(Name: UnicodeString('⊵'); CodePointA: 8885; CodePointB: 0),
(Name: UnicodeString('◬'); CodePointA: 9708; CodePointB: 0),
(Name: UnicodeString('≜'); CodePointA: 8796; CodePointB: 0),
(Name: UnicodeString('⨺'); CodePointA: 10810; CodePointB: 0),
(Name: UnicodeString('⃛'); CodePointA: 8411; CodePointB: 0),
(Name: UnicodeString('⨹'); CodePointA: 10809; CodePointB: 0),
(Name: UnicodeString('⧍'); CodePointA: 10701; CodePointB: 0),
(Name: UnicodeString('⨻'); CodePointA: 10811; CodePointB: 0),
(Name: UnicodeString('⏢'); CodePointA: 9186; CodePointB: 0),
(Name: UnicodeString('𝒯'); CodePointA: 119983; CodePointB: 0),
(Name: UnicodeString('𝓉'); CodePointA: 120009; CodePointB: 0),
(Name: UnicodeString('Ц'); CodePointA: 1062; CodePointB: 0),
(Name: UnicodeString('ц'); CodePointA: 1094; CodePointB: 0),
(Name: UnicodeString('Ћ'); CodePointA: 1035; CodePointB: 0),
(Name: UnicodeString('ћ'); CodePointA: 1115; CodePointB: 0),
(Name: UnicodeString('Ŧ'); CodePointA: 358; CodePointB: 0),
(Name: UnicodeString('ŧ'); CodePointA: 359; CodePointB: 0),
(Name: UnicodeString('≬'); CodePointA: 8812; CodePointB: 0),
(Name: UnicodeString('↞'); CodePointA: 8606; CodePointB: 0),
(Name: UnicodeString('↠'); CodePointA: 8608; CodePointB: 0),
(Name: UnicodeString('Ú'); CodePointA: 218; CodePointB: 0),
(Name: UnicodeString('Ú'); CodePointA: 218; CodePointB: 0),
(Name: UnicodeString('ú'); CodePointA: 250; CodePointB: 0),
(Name: UnicodeString('ú'); CodePointA: 250; CodePointB: 0),
(Name: UnicodeString('↑'); CodePointA: 8593; CodePointB: 0),
(Name: UnicodeString('↟'); CodePointA: 8607; CodePointB: 0),
(Name: UnicodeString('⇑'); CodePointA: 8657; CodePointB: 0),
(Name: UnicodeString('⥉'); CodePointA: 10569; CodePointB: 0),
(Name: UnicodeString('Ў'); CodePointA: 1038; CodePointB: 0),
(Name: UnicodeString('ў'); CodePointA: 1118; CodePointB: 0),
(Name: UnicodeString('Ŭ'); CodePointA: 364; CodePointB: 0),
(Name: UnicodeString('ŭ'); CodePointA: 365; CodePointB: 0),
(Name: UnicodeString('Û'); CodePointA: 219; CodePointB: 0),
(Name: UnicodeString('Û'); CodePointA: 219; CodePointB: 0),
(Name: UnicodeString('û'); CodePointA: 251; CodePointB: 0),
(Name: UnicodeString('û'); CodePointA: 251; CodePointB: 0),
(Name: UnicodeString('У'); CodePointA: 1059; CodePointB: 0),
(Name: UnicodeString('у'); CodePointA: 1091; CodePointB: 0),
(Name: UnicodeString('⇅'); CodePointA: 8645; CodePointB: 0),
(Name: UnicodeString('Ű'); CodePointA: 368; CodePointB: 0),
(Name: UnicodeString('ű'); CodePointA: 369; CodePointB: 0),
(Name: UnicodeString('⥮'); CodePointA: 10606; CodePointB: 0),
(Name: UnicodeString('⥾'); CodePointA: 10622; CodePointB: 0),
(Name: UnicodeString('𝔘'); CodePointA: 120088; CodePointB: 0),
(Name: UnicodeString('𝔲'); CodePointA: 120114; CodePointB: 0),
(Name: UnicodeString('Ù'); CodePointA: 217; CodePointB: 0),
(Name: UnicodeString('Ù'); CodePointA: 217; CodePointB: 0),
(Name: UnicodeString('ù'); CodePointA: 249; CodePointB: 0),
(Name: UnicodeString('ù'); CodePointA: 249; CodePointB: 0),
(Name: UnicodeString('⥣'); CodePointA: 10595; CodePointB: 0),
(Name: UnicodeString('↿'); CodePointA: 8639; CodePointB: 0),
(Name: UnicodeString('↾'); CodePointA: 8638; CodePointB: 0),
(Name: UnicodeString('▀'); CodePointA: 9600; CodePointB: 0),
(Name: UnicodeString('⌜'); CodePointA: 8988; CodePointB: 0),
(Name: UnicodeString('⌜'); CodePointA: 8988; CodePointB: 0),
(Name: UnicodeString('⌏'); CodePointA: 8975; CodePointB: 0),
(Name: UnicodeString('◸'); CodePointA: 9720; CodePointB: 0),
(Name: UnicodeString('Ū'); CodePointA: 362; CodePointB: 0),
(Name: UnicodeString('ū'); CodePointA: 363; CodePointB: 0),
(Name: UnicodeString('¨'); CodePointA: 168; CodePointB: 0),
(Name: UnicodeString('¨'); CodePointA: 168; CodePointB: 0),
(Name: UnicodeString('_'); CodePointA: 95; CodePointB: 0),
(Name: UnicodeString('⏟'); CodePointA: 9183; CodePointB: 0),
(Name: UnicodeString('⎵'); CodePointA: 9141; CodePointB: 0),
(Name: UnicodeString('⏝'); CodePointA: 9181; CodePointB: 0),
(Name: UnicodeString('⋃'); CodePointA: 8899; CodePointB: 0),
(Name: UnicodeString('⊎'); CodePointA: 8846; CodePointB: 0),
(Name: UnicodeString('Ų'); CodePointA: 370; CodePointB: 0),
(Name: UnicodeString('ų'); CodePointA: 371; CodePointB: 0),
(Name: UnicodeString('𝕌'); CodePointA: 120140; CodePointB: 0),
(Name: UnicodeString('𝕦'); CodePointA: 120166; CodePointB: 0),
(Name: UnicodeString('⤒'); CodePointA: 10514; CodePointB: 0),
(Name: UnicodeString('↑'); CodePointA: 8593; CodePointB: 0),
(Name: UnicodeString('↑'); CodePointA: 8593; CodePointB: 0),
(Name: UnicodeString('⇑'); CodePointA: 8657; CodePointB: 0),
(Name: UnicodeString('⇅'); CodePointA: 8645; CodePointB: 0),
(Name: UnicodeString('↕'); CodePointA: 8597; CodePointB: 0),
(Name: UnicodeString('↕'); CodePointA: 8597; CodePointB: 0),
(Name: UnicodeString('⇕'); CodePointA: 8661; CodePointB: 0),
(Name: UnicodeString('⥮'); CodePointA: 10606; CodePointB: 0),
(Name: UnicodeString('↿'); CodePointA: 8639; CodePointB: 0),
(Name: UnicodeString('↾'); CodePointA: 8638; CodePointB: 0),
(Name: UnicodeString('⊎'); CodePointA: 8846; CodePointB: 0),
(Name: UnicodeString('↖'); CodePointA: 8598; CodePointB: 0),
(Name: UnicodeString('↗'); CodePointA: 8599; CodePointB: 0),
(Name: UnicodeString('υ'); CodePointA: 965; CodePointB: 0),
(Name: UnicodeString('ϒ'); CodePointA: 978; CodePointB: 0),
(Name: UnicodeString('ϒ'); CodePointA: 978; CodePointB: 0),
(Name: UnicodeString('Υ'); CodePointA: 933; CodePointB: 0),
(Name: UnicodeString('υ'); CodePointA: 965; CodePointB: 0),
(Name: UnicodeString('↥'); CodePointA: 8613; CodePointB: 0),
(Name: UnicodeString('⊥'); CodePointA: 8869; CodePointB: 0),
(Name: UnicodeString('⇈'); CodePointA: 8648; CodePointB: 0),
(Name: UnicodeString('⌝'); CodePointA: 8989; CodePointB: 0),
(Name: UnicodeString('⌝'); CodePointA: 8989; CodePointB: 0),
(Name: UnicodeString('⌎'); CodePointA: 8974; CodePointB: 0),
(Name: UnicodeString('Ů'); CodePointA: 366; CodePointB: 0),
(Name: UnicodeString('ů'); CodePointA: 367; CodePointB: 0),
(Name: UnicodeString('◹'); CodePointA: 9721; CodePointB: 0),
(Name: UnicodeString('𝒰'); CodePointA: 119984; CodePointB: 0),
(Name: UnicodeString('𝓊'); CodePointA: 120010; CodePointB: 0),
(Name: UnicodeString('⋰'); CodePointA: 8944; CodePointB: 0),
(Name: UnicodeString('Ũ'); CodePointA: 360; CodePointB: 0),
(Name: UnicodeString('ũ'); CodePointA: 361; CodePointB: 0),
(Name: UnicodeString('▵'); CodePointA: 9653; CodePointB: 0),
(Name: UnicodeString('▴'); CodePointA: 9652; CodePointB: 0),
(Name: UnicodeString('⇈'); CodePointA: 8648; CodePointB: 0),
(Name: UnicodeString('Ü'); CodePointA: 220; CodePointB: 0),
(Name: UnicodeString('Ü'); CodePointA: 220; CodePointB: 0),
(Name: UnicodeString('ü'); CodePointA: 252; CodePointB: 0),
(Name: UnicodeString('ü'); CodePointA: 252; CodePointB: 0),
(Name: UnicodeString('⦧'); CodePointA: 10663; CodePointB: 0),
(Name: UnicodeString('⦜'); CodePointA: 10652; CodePointB: 0),
(Name: UnicodeString('ϵ'); CodePointA: 1013; CodePointB: 0),
(Name: UnicodeString('ϰ'); CodePointA: 1008; CodePointB: 0),
(Name: UnicodeString('∅'); CodePointA: 8709; CodePointB: 0),
(Name: UnicodeString('ϕ'); CodePointA: 981; CodePointB: 0),
(Name: UnicodeString('ϖ'); CodePointA: 982; CodePointB: 0),
(Name: UnicodeString('∝'); CodePointA: 8733; CodePointB: 0),
(Name: UnicodeString('↕'); CodePointA: 8597; CodePointB: 0),
(Name: UnicodeString('⇕'); CodePointA: 8661; CodePointB: 0),
(Name: UnicodeString('ϱ'); CodePointA: 1009; CodePointB: 0),
(Name: UnicodeString('ς'); CodePointA: 962; CodePointB: 0),
(Name: UnicodeString('⊊︀'); CodePointA: 8842; CodePointB: 65024),
(Name: UnicodeString('⫋︀'); CodePointA: 10955; CodePointB: 65024),
(Name: UnicodeString('⊋︀'); CodePointA: 8843; CodePointB: 65024),
(Name: UnicodeString('⫌︀'); CodePointA: 10956; CodePointB: 65024),
(Name: UnicodeString('ϑ'); CodePointA: 977; CodePointB: 0),
(Name: UnicodeString('⊲'); CodePointA: 8882; CodePointB: 0),
(Name: UnicodeString('⊳'); CodePointA: 8883; CodePointB: 0),
(Name: UnicodeString('⫨'); CodePointA: 10984; CodePointB: 0),
(Name: UnicodeString('⫫'); CodePointA: 10987; CodePointB: 0),
(Name: UnicodeString('⫩'); CodePointA: 10985; CodePointB: 0),
(Name: UnicodeString('В'); CodePointA: 1042; CodePointB: 0),
(Name: UnicodeString('в'); CodePointA: 1074; CodePointB: 0),
(Name: UnicodeString('⊢'); CodePointA: 8866; CodePointB: 0),
(Name: UnicodeString('⊨'); CodePointA: 8872; CodePointB: 0),
(Name: UnicodeString('⊩'); CodePointA: 8873; CodePointB: 0),
(Name: UnicodeString('⊫'); CodePointA: 8875; CodePointB: 0),
(Name: UnicodeString('⫦'); CodePointA: 10982; CodePointB: 0),
(Name: UnicodeString('⊻'); CodePointA: 8891; CodePointB: 0),
(Name: UnicodeString('∨'); CodePointA: 8744; CodePointB: 0),
(Name: UnicodeString('⋁'); CodePointA: 8897; CodePointB: 0),
(Name: UnicodeString('≚'); CodePointA: 8794; CodePointB: 0),
(Name: UnicodeString('⋮'); CodePointA: 8942; CodePointB: 0),
(Name: UnicodeString('|'); CodePointA: 124; CodePointB: 0),
(Name: UnicodeString('‖'); CodePointA: 8214; CodePointB: 0),
(Name: UnicodeString('|'); CodePointA: 124; CodePointB: 0),
(Name: UnicodeString('‖'); CodePointA: 8214; CodePointB: 0),
(Name: UnicodeString('∣'); CodePointA: 8739; CodePointB: 0),
(Name: UnicodeString('|'); CodePointA: 124; CodePointB: 0),
(Name: UnicodeString('❘'); CodePointA: 10072; CodePointB: 0),
(Name: UnicodeString('≀'); CodePointA: 8768; CodePointB: 0),
(Name: UnicodeString(' '); CodePointA: 8202; CodePointB: 0),
(Name: UnicodeString('𝔙'); CodePointA: 120089; CodePointB: 0),
(Name: UnicodeString('𝔳'); CodePointA: 120115; CodePointB: 0),
(Name: UnicodeString('⊲'); CodePointA: 8882; CodePointB: 0),
(Name: UnicodeString('⊂⃒'); CodePointA: 8834; CodePointB: 8402),
(Name: UnicodeString('⊃⃒'); CodePointA: 8835; CodePointB: 8402),
(Name: UnicodeString('𝕍'); CodePointA: 120141; CodePointB: 0),
(Name: UnicodeString('𝕧'); CodePointA: 120167; CodePointB: 0),
(Name: UnicodeString('∝'); CodePointA: 8733; CodePointB: 0),
(Name: UnicodeString('⊳'); CodePointA: 8883; CodePointB: 0),
(Name: UnicodeString('𝒱'); CodePointA: 119985; CodePointB: 0),
(Name: UnicodeString('𝓋'); CodePointA: 120011; CodePointB: 0),
(Name: UnicodeString('⫋︀'); CodePointA: 10955; CodePointB: 65024),
(Name: UnicodeString('⊊︀'); CodePointA: 8842; CodePointB: 65024),
(Name: UnicodeString('⫌︀'); CodePointA: 10956; CodePointB: 65024),
(Name: UnicodeString('⊋︀'); CodePointA: 8843; CodePointB: 65024),
(Name: UnicodeString('⊪'); CodePointA: 8874; CodePointB: 0),
(Name: UnicodeString('⦚'); CodePointA: 10650; CodePointB: 0),
(Name: UnicodeString('Ŵ'); CodePointA: 372; CodePointB: 0),
(Name: UnicodeString('ŵ'); CodePointA: 373; CodePointB: 0),
(Name: UnicodeString('⩟'); CodePointA: 10847; CodePointB: 0),
(Name: UnicodeString('∧'); CodePointA: 8743; CodePointB: 0),
(Name: UnicodeString('⋀'); CodePointA: 8896; CodePointB: 0),
(Name: UnicodeString('≙'); CodePointA: 8793; CodePointB: 0),
(Name: UnicodeString('℘'); CodePointA: 8472; CodePointB: 0),
(Name: UnicodeString('𝔚'); CodePointA: 120090; CodePointB: 0),
(Name: UnicodeString('𝔴'); CodePointA: 120116; CodePointB: 0),
(Name: UnicodeString('𝕎'); CodePointA: 120142; CodePointB: 0),
(Name: UnicodeString('𝕨'); CodePointA: 120168; CodePointB: 0),
(Name: UnicodeString('℘'); CodePointA: 8472; CodePointB: 0),
(Name: UnicodeString('≀'); CodePointA: 8768; CodePointB: 0),
(Name: UnicodeString('≀'); CodePointA: 8768; CodePointB: 0),
(Name: UnicodeString('𝒲'); CodePointA: 119986; CodePointB: 0),
(Name: UnicodeString('𝓌'); CodePointA: 120012; CodePointB: 0),
(Name: UnicodeString('⋂'); CodePointA: 8898; CodePointB: 0),
(Name: UnicodeString('◯'); CodePointA: 9711; CodePointB: 0),
(Name: UnicodeString('⋃'); CodePointA: 8899; CodePointB: 0),
(Name: UnicodeString('▽'); CodePointA: 9661; CodePointB: 0),
(Name: UnicodeString('𝔛'); CodePointA: 120091; CodePointB: 0),
(Name: UnicodeString('𝔵'); CodePointA: 120117; CodePointB: 0),
(Name: UnicodeString('⟷'); CodePointA: 10231; CodePointB: 0),
(Name: UnicodeString('⟺'); CodePointA: 10234; CodePointB: 0),
(Name: UnicodeString('Ξ'); CodePointA: 926; CodePointB: 0),
(Name: UnicodeString('ξ'); CodePointA: 958; CodePointB: 0),
(Name: UnicodeString('⟵'); CodePointA: 10229; CodePointB: 0),
(Name: UnicodeString('⟸'); CodePointA: 10232; CodePointB: 0),
(Name: UnicodeString('⟼'); CodePointA: 10236; CodePointB: 0),
(Name: UnicodeString('⋻'); CodePointA: 8955; CodePointB: 0),
(Name: UnicodeString('⨀'); CodePointA: 10752; CodePointB: 0),
(Name: UnicodeString('𝕏'); CodePointA: 120143; CodePointB: 0),
(Name: UnicodeString('𝕩'); CodePointA: 120169; CodePointB: 0),
(Name: UnicodeString('⨁'); CodePointA: 10753; CodePointB: 0),
(Name: UnicodeString('⨂'); CodePointA: 10754; CodePointB: 0),
(Name: UnicodeString('⟶'); CodePointA: 10230; CodePointB: 0),
(Name: UnicodeString('⟹'); CodePointA: 10233; CodePointB: 0),
(Name: UnicodeString('𝒳'); CodePointA: 119987; CodePointB: 0),
(Name: UnicodeString('𝓍'); CodePointA: 120013; CodePointB: 0),
(Name: UnicodeString('⨆'); CodePointA: 10758; CodePointB: 0),
(Name: UnicodeString('⨄'); CodePointA: 10756; CodePointB: 0),
(Name: UnicodeString('△'); CodePointA: 9651; CodePointB: 0),
(Name: UnicodeString('⋁'); CodePointA: 8897; CodePointB: 0),
(Name: UnicodeString('⋀'); CodePointA: 8896; CodePointB: 0),
(Name: UnicodeString('Ý'); CodePointA: 221; CodePointB: 0),
(Name: UnicodeString('Ý'); CodePointA: 221; CodePointB: 0),
(Name: UnicodeString('ý'); CodePointA: 253; CodePointB: 0),
(Name: UnicodeString('ý'); CodePointA: 253; CodePointB: 0),
(Name: UnicodeString('Я'); CodePointA: 1071; CodePointB: 0),
(Name: UnicodeString('я'); CodePointA: 1103; CodePointB: 0),
(Name: UnicodeString('Ŷ'); CodePointA: 374; CodePointB: 0),
(Name: UnicodeString('ŷ'); CodePointA: 375; CodePointB: 0),
(Name: UnicodeString('Ы'); CodePointA: 1067; CodePointB: 0),
(Name: UnicodeString('ы'); CodePointA: 1099; CodePointB: 0),
(Name: UnicodeString('¥'); CodePointA: 165; CodePointB: 0),
(Name: UnicodeString('¥'); CodePointA: 165; CodePointB: 0),
(Name: UnicodeString('𝔜'); CodePointA: 120092; CodePointB: 0),
(Name: UnicodeString('𝔶'); CodePointA: 120118; CodePointB: 0),
(Name: UnicodeString('Ї'); CodePointA: 1031; CodePointB: 0),
(Name: UnicodeString('ї'); CodePointA: 1111; CodePointB: 0),
(Name: UnicodeString('𝕐'); CodePointA: 120144; CodePointB: 0),
(Name: UnicodeString('𝕪'); CodePointA: 120170; CodePointB: 0),
(Name: UnicodeString('𝒴'); CodePointA: 119988; CodePointB: 0),
(Name: UnicodeString('𝓎'); CodePointA: 120014; CodePointB: 0),
(Name: UnicodeString('Ю'); CodePointA: 1070; CodePointB: 0),
(Name: UnicodeString('ю'); CodePointA: 1102; CodePointB: 0),
(Name: UnicodeString('ÿ'); CodePointA: 255; CodePointB: 0),
(Name: UnicodeString('ÿ'); CodePointA: 255; CodePointB: 0),
(Name: UnicodeString('Ÿ'); CodePointA: 376; CodePointB: 0),
(Name: UnicodeString('Ź'); CodePointA: 377; CodePointB: 0),
(Name: UnicodeString('ź'); CodePointA: 378; CodePointB: 0),
(Name: UnicodeString('Ž'); CodePointA: 381; CodePointB: 0),
(Name: UnicodeString('ž'); CodePointA: 382; CodePointB: 0),
(Name: UnicodeString('З'); CodePointA: 1047; CodePointB: 0),
(Name: UnicodeString('з'); CodePointA: 1079; CodePointB: 0),
(Name: UnicodeString('Ż'); CodePointA: 379; CodePointB: 0),
(Name: UnicodeString('ż'); CodePointA: 380; CodePointB: 0),
(Name: UnicodeString('ℨ'); CodePointA: 8488; CodePointB: 0),
(Name: UnicodeString('​'); CodePointA: 8203; CodePointB: 0),
(Name: UnicodeString('Ζ'); CodePointA: 918; CodePointB: 0),
(Name: UnicodeString('ζ'); CodePointA: 950; CodePointB: 0),
(Name: UnicodeString('𝔷'); CodePointA: 120119; CodePointB: 0),
(Name: UnicodeString('ℨ'); CodePointA: 8488; CodePointB: 0),
(Name: UnicodeString('Ж'); CodePointA: 1046; CodePointB: 0),
(Name: UnicodeString('ж'); CodePointA: 1078; CodePointB: 0),
(Name: UnicodeString('⇝'); CodePointA: 8669; CodePointB: 0),
(Name: UnicodeString('𝕫'); CodePointA: 120171; CodePointB: 0),
(Name: UnicodeString('ℤ'); CodePointA: 8484; CodePointB: 0),
(Name: UnicodeString('𝒵'); CodePointA: 119989; CodePointB: 0),
(Name: UnicodeString('𝓏'); CodePointA: 120015; CodePointB: 0),
(Name: UnicodeString('‍'); CodePointA: 8205; CodePointB: 0),
(Name: UnicodeString('‌'); CodePointA: 8204; CodePointB: 0));
implementation
end.
|
{
ID: Reinier C‚sar Mujica Hern ndez
PROG: bigfact
GRADO: 11
CENTRO: IPVCE "Ernesto Guevara"
}
{Problema 12: Max Factor [Hal Burch, 2005]
Para mejorar la organización de su granja, el Granjero Juan rotula
cada una de sus N (1 <= N <= 5,000) vacas con un número serial
distinto en el rango 1..20,000. Desafortunadamente, él es incapaz de
hacer que las vacas interpreten algunos números seriales tan bien como
otras. En particular, una vaca cuyo número serial tenga el factor
primo más grande disfruta la posición social más alta entre las otras
vacas.
(Recuerde que un número primo es simplemente un número que no tenga
divisores excepto 1 y el mismo. El número 7 es un número primo,
mientras que el número 6, siendo divisible por 2 y 3, no lo es).
Dado un conjunto de N (1 <= N <= 5,000) números eriales en el rango
1..20,000, determien aquel que tenga el factor primo más grande.
NOMBRE DEL PROBLEMA: bigfact
FORMATO DE ENTRADA:
* Lìnea 1: Un solo entero, N
* Lìneas 2..N+1: Los números seriales a ser considerados, uno por
lìnea.
ENTRADA EJEMPLO (archivo bigfact.in):
4
36
38
40
42
FORMATO DE SALIDA:
Línea 1: El entero con el factor primo más grande. Si hay más de
uno, de cómo salida el que aparezca más temprano en el
archivo de entrada.
SALIDA EJEMPLO (archivo bigfact.out):
38
DETALLES DE LA SALIDA:
19 es un factor primo de 38. Ningún otro numero tiene un factor primo
más grande.
}
{$I-,Q-,R-,S-}
var
fe,fs : text;
n,act,sol : longint;
procedure open;
begin
assign(fe,'bigfact.in'); reset(fe);
assign(fs,'bigfact.out'); rewrite(fs);
readln(fe,n);
end;
procedure work;
var
i,j,k,s : longint;
begin
j:=-maxlongint; sol:=1;
for i:=1 to n do
begin
readln(fe,act);
k:=2; s:=act;
while (act <> 1) do
begin
while (act mod k <> 0) do inc(k);
act:=act div k;
if k > j then
begin
j:=k;
sol:=s;
end;
end;
end;
end;
procedure closer;
begin
writeln(fs,sol);
close(fs);
end;
begin
open;
work;
closer;
end. |
unit LIB.List0;
interface //#################################################################### ■
uses LIB;
type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【インタフェース】
IItem0 = interface;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% IItem0
IItem0 = interface
///// アクセス
function Get_Prev :IItem0;
procedure Set_Prev( const _Prev_:IItem0 );
function Get_Next :IItem0;
procedure Set_Next( const _Next_:IItem0 );
///// プロパティ
property Prev :IItem0 read Get_Prev write Set_Prev;
property Next :IItem0 read Get_Next write Set_Next;
end;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】
TItem0<_TPrev_:IItem0;_TNext_:IItem0> = class;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TItem0<_TPrev_,_TNext_>
TItem0<_TPrev_:IItem0;_TNext_:IItem0> = class( TInterfacedBase, IItem0 )
private
///// アクセス
function Get_Prev :IItem0;
procedure Set_Prev( const _Prev_:IItem0 );
function Get_Next :IItem0;
procedure Set_Next( const _Next_:IItem0 );
protected
_Prev :_TPrev_;
_Next :_TNext_;
///// アクセス
function GetPrev :_TPrev_;
procedure SetPrev( const Prev_:_TPrev_ );
function GetNext :_TNext_;
procedure SetNext( const Next_:_TNext_ );
public
///// プロパティ
property Prev :_TPrev_ read GetPrev write SetPrev;
property Next :_TNext_ read GetNext write SetNext;
end;
implementation //############################################################### ■
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TItem0<_TPrev_,_TNext_>
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
function TItem0<_TPrev_,_TNext_>.Get_Prev :IItem0;
begin
Result := _Prev;
end;
procedure TItem0<_TPrev_,_TNext_>.Set_Prev( const _Prev_:IItem0 );
begin
_Prev := _TPrev_( _Prev_ );
end;
function TItem0<_TPrev_,_TNext_>.Get_Next :IItem0;
begin
Result := _Next;
end;
procedure TItem0<_TPrev_,_TNext_>.Set_Next( const _Next_:IItem0 );
begin
_Next := _TNext_( _Next_ );
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected
function TItem0<_TPrev_,_TNext_>.GetPrev :_TPrev_;
begin
Result := _Prev;
end;
procedure TItem0<_TPrev_,_TNext_>.SetPrev( const Prev_:_TPrev_ );
begin
_Prev := Prev_;
end;
function TItem0<_TPrev_,_TNext_>.GetNext :_TNext_;
begin
Result := _Next;
end;
procedure TItem0<_TPrev_,_TNext_>.SetNext( const Next_:_TNext_ );
begin
_Next := Next_;
end;
end. //######################################################################### ■
|
Program matriz_exemplo_2 ;
var
matriz: array[1..5, 1..5] of integer;
vetor: array[1..5] of integer;
criador_de_valores: integer;
lin, col, soma: integer;
Begin
criador_de_valores := 1;
soma := 0;
//Criando a matriz
for lin:= 1 to 5 do
begin
for col:= 1 to 5 do
begin
matriz[lin,col] := criador_de_valores;
criador_de_valores := criador_de_valores+1;
end;
end;
//imprimindo a matriz
writeln('Imprimindo a matriz');
writeln;
for lin:= 1 to 5 do
begin
for col:= 1 to 5 do
begin
write(matriz[lin,col], ' ');
end;
writeln;
end;
writeln;
//somando linhas
for lin:= 1 to 5 do
begin
for col:= 1 to 5 do
begin
soma := matriz[lin,col] + soma;
end;
writeln;
write('A soma da ', lin, ' linha é: ', soma);
soma := 0;
end;
writeln;
writeln;
//achando a diagonal principal
writeln('Os valores da diagonal principal são: ');
for lin:= 1 to 5 do
begin
for col:= 1 to 5 do
begin
if lin = col then
begin
vetor[lin] := matriz[lin,col];
write(vetor[lin], ' ');
end;
end;
end;
End.
|
unit MainFormaN35;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,IBase, StdCtrls, cxLookAndFeelPainters, frxDesgn, frxClass, DB,
FIBDataSet, pFIBDataSet, frxDBSet, FIBDatabase, pFIBDatabase, cxButtons,
cxControls, cxContainer, cxEdit, cxLabel, ActnList, ComCtrls, FIBQuery,
pFIBQuery, pFIBStoredProc, ExtCtrls, cxCheckBox;
type
TfrmMainFormaN35 = class(TForm)
cxLabelStatus: TcxLabel;
cxButton1: TcxButton;
cxButton2: TcxButton;
pFIBDatabase: TpFIBDatabase;
WriteTransaction: TpFIBTransaction;
ReadTransaction: TpFIBTransaction;
frxDBDataset: TfrxDBDataset;
pFIBDataSet: TpFIBDataSet;
frxReport: TfrxReport;
frxDesigner1: TfrxDesigner;
ActionList1: TActionList;
ActionDesigned: TAction;
pFIBDataSetF35: TpFIBDataSet;
frxDBDataset2: TfrxDBDataset;
StatusBar1: TStatusBar;
pFIBStoredProc: TpFIBStoredProc;
cxCheckBoxFamily: TcxCheckBox;
procedure cxButton1Click(Sender: TObject);
procedure cxButton2Click(Sender: TObject);
procedure ActionDesignedExecute(Sender: TObject);
procedure frxReportAfterPrintReport(Sender: TObject);
private
constructor Create (Aowner:Tcomponent;DBL:TISC_DB_HANDLE;id_people:Int64;type_doc_print:integer);overload;
{ Private declarations }
public
{ Public declarations }
end;
function FormaN35(AOwner:TComponent;DB:TISC_DB_HANDLE;id_people:Int64;type_doc_print:integer):Integer;stdcall;
exports FormaN35;
var
frmMainFormaN35: TfrmMainFormaN35;
id_people_pr:Int64;
print_page:Integer;
type_print:Integer;
designer_rep:Integer;
implementation
{$R *.dfm}
function FormaN35(AOwner:TComponent;DB:TISC_DB_HANDLE;id_people:Int64;type_doc_print:integer):Integer;
var
PrProp:TfrmMainFormaN35;
begin
PrProp:=TfrmMainFormaN35.Create(AOwner,DB,id_people,type_doc_print);
PrProp.ShowModal;
PrProp.Free;
end;
constructor TfrmMainFormaN35.Create (Aowner:Tcomponent;DBL:TISC_DB_HANDLE;id_people:Int64;type_doc_print:integer);
begin
Inherited Create(Aowner);
pFIBDatabase.Handle:=DBL;
id_people_pr:=id_people;
Caption:='Печать 35 формы.';
cxLabelStatus.Caption:='Печать первой страницы';
type_print:=type_doc_print;
designer_rep:=0;
print_page:=0;
if type_print=0 then
begin
cxCheckBoxFamily.Visible:=true;
end
else
begin
cxCheckBoxFamily.Visible:=false;
end;
end;
procedure TfrmMainFormaN35.cxButton1Click(Sender: TObject);
begin
if type_print=0 then
begin
//cxCheckBoxFamily.Visible:=true;
if print_page=0 then
begin
with pFIBDataSet do
begin
Database:=Database;
Transaction:=ReadTransaction;
Active:=false;
ParamByName('param_people').AsInt64:=id_people_pr;
Active:=true;
end;
frxReport.Clear;
frxReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'Reports\Studcity\'+'PeopleN35.fr3');
frxReport.Variables.Clear;
if designer_rep=1 then
begin
frxReport.DesignReport;
end
else
begin
frxReport.PrepareReport();
frxReport.PrintOptions.ShowDialog:=false;
frxReport.Print;
end;
print_page:=1;
cxLabelStatus.Caption:='Печать второй страницы';
end
else
begin
frxReport.Clear;
frxReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'Reports\Studcity\'+'PeopleN35_Page2.fr3');
frxReport.Variables.Clear;
if designer_rep=1 then
begin
frxReport.DesignReport;
end
else
begin
frxReport.PrepareReport();
frxReport.PrintOptions.ShowDialog:=false;
frxReport.Print;
//записываем на сервер
With pFIBStoredProc do
begin
try
StoredProcName:='ST_DT_DOC_SAVE_CHANGE';
Database:=pFIBDatabase;
Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
Prepare;
ParamByName('ID_PEOPLE').AsInt64:=id_people_pr;
ParamByName('KOD_DOCS').AsInteger:=3001;
ExecProc;
Transaction.Commit;
except
begin
Transaction.Rollback;
ShowMessage('Ошибка при сохранении статического листка учета. Обратитесь к администратору!!!');
raise;
end;
end;
end;//конец
end;
close;
end;
end;
//печать общего списка
if type_print=2 then
begin
if print_page=0 then
begin
with pFIBDataSetF35 do
begin
Database:=Database;
Transaction:=ReadTransaction;
Active:=false;
ParamByName('param_id_list').AsInt64:=id_people_pr;
Active:=true;
end;
frxReport.Clear;
frxReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'Reports\Studcity\'+'PeopleN35_TOListROVD.fr3');
frxReport.Variables.Clear;
print_page:=1;
cxLabelStatus.Caption:='Печать второй страницы';
if designer_rep=1 then
begin
frxReport.DesignReport;
end
else
begin
frxReport.PrepareReport();
frxReport.PrintOptions.ShowDialog:=false;
frxReport.Print;
end;
end
else
begin
frxReport.Clear;
frxReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'Reports\Studcity\'+'PeopleN35_Page2.fr3');
frxReport.Variables.Clear;
if designer_rep=1 then
begin
frxReport.DesignReport;
end
else
begin
frxReport.PrepareReport();
frxReport.PrintOptions.ShowDialog:=false;
frxReport.Print;
end;
close;
end;
end;
end;
procedure TfrmMainFormaN35.cxButton2Click(Sender: TObject);
begin
Close;
end;
procedure TfrmMainFormaN35.ActionDesignedExecute(Sender: TObject);
begin
if designer_rep=0 then
begin
designer_rep:=1;
StatusBar1.Panels[0].Text:='Режим отладки отчетов';
end
else
begin
designer_rep:=0;
StatusBar1.Panels[0].Text:='';
end;
end;
procedure TfrmMainFormaN35.frxReportAfterPrintReport(Sender: TObject);
begin
if (type_print=2) and (print_page=1) then
begin
pFIBStoredProc.Database:=pFIBDatabase;
pFIBStoredProc.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
pFIBStoredProc.StoredProcName:='ST_DT_LIST_ROVD_PRINT_SAVE';
pFIBStoredProc.Prepare;
pFIBStoredProc.ParamByName('ID_LIST').AsInt64:=id_people_pr;
pFIBStoredProc.ParamByName('PRINT_FORM').AsInteger:=2;
try
pFIBStoredProc.ExecProc;
except
begin
WriteTransaction.Rollback;
Exit;
end;
end;
WriteTransaction.Commit;
end;
end;
end.
|
unit htLayout;
interface
uses
Windows, SysUtils, Types, Classes, Controls, Graphics,
htInterfaces, htMarkup;
type
ThtCustomLayout = class(TCustomControl, IhtGenerator)
protected
procedure AlignControls(AControl: TControl; var Rect: TRect); override;
procedure GenerateCtrl(inMarkup: ThtMarkup;
const inContainer: string; inCtrl: TControl);
procedure Paint; override;
public
constructor Create(inOwner: TComponent); override;
procedure Generate(inMarkup: ThtMarkup);
end;
//
ThtLayout = class(ThtCustomLayout)
published
property Align;
property Visible;
end;
implementation
uses
LrControlIterator, LrVclUtils;
{ ThtCustomLayout }
constructor ThtCustomLayout.Create(inOwner: TComponent);
begin
inherited;
ControlStyle := ControlStyle + [ csAcceptsControls ];
end;
procedure ThtCustomLayout.Paint;
function Middle(inCtrl: TControl): Integer;
begin
Result := inCtrl.Top + inCtrl.Height div 2;
end;
function Center(inCtrl: TControl): Integer;
begin
Result := inCtrl.Left + inCtrl.Width div 2;
end;
begin
inherited;
with Canvas do
begin
Pen.Width := 1;
Pen.Color := clSilver;
Pen.Style := psDot;
Brush.Style := bsClear;
Rectangle(ClientRect);
///
Pen.Style := psSolid;
Pen.Color := clBlue;
with TLrCtrlIterator.Create(Self) do
try
while Next do
begin
MoveTo(0, Middle(Ctrl));
LineTo(ClientWidth, Middle(Ctrl));
MoveTo(Center(Ctrl), 0);
LineTo(Center(Ctrl), ClientHeight);
end;
finally
Free;
end;
end;
end;
procedure ThtCustomLayout.AlignControls(AControl: TControl; var Rect: TRect);
var
i: Integer;
begin
Invalidate;
for i := 0 to Pred(ControlCount) do
Controls[i].Align := alNone;
inherited;
end;
procedure ThtCustomLayout.Generate(inMarkup: ThtMarkup);
begin
inMarkup.Add('<div style="position:relative; width:100%;">');
// inMarkup.Add('<div style="position:relative; width:100%; height:100%;">');
with TLrCtrlIterator.Create(Self) do
try
while Next do
begin
// inMarkup.Add(Format(
// ' <div style="border: 1px solid black; background-color: #ddd; position:absolute; left: %dpx; top: %dpx; width: %dpx; height:%dpx;">',
// [ Ctrl.Left, Ctrl.Top, Ctrl.Width, Ctrl.Height ]));
inMarkup.Styles.Add(
Format(
'#%s { ' +
'border: 1px solid black; ' +
'background-color: #ddd; ' +
'position:absolute; ' +
'left: %dpx; top: %dpx; width: %dpx; height:%dpx; ' +
'}',
[ Ctrl.Name, Ctrl.Left, Ctrl.Top, Ctrl.Width, Ctrl.Height ])
);
inMarkup.Add(Format(' <div id="%s">', [ Ctrl.Name ]));
GenerateCtrl(inMarkup, Ctrl.Name, Ctrl);
{
if (ThIsAs(Ctrl, IhtGenerator, g)) then
g.Generate(inMarkup)
else
inMarkup.Add(' ' + Ctrl.Name);
}
inMarkup.Add(' </div>');
end;
finally
Free;
end;
inMarkup.Add('</div>');
end;
procedure ThtCustomLayout.GenerateCtrl(inMarkup: ThtMarkup;
const inContainer: string; inCtrl: TControl);
var
// handled: Boolean;
c: IhtControl;
g: IhtGenerator;
begin
// handled := false;
// if Assigned(OnGenerateCtrl) then
// OnGenerateCtrl(inMarkup, inContainer, inCtrl, handled);
// if not handled then
if (LrIsAs(inCtrl, IhtGenerator, g)) then
g.Generate(inMarkup)
else if LrIsAs(inCtrl, IhtControl, c) then
c.Generate(inContainer, inMarkup)
// else if (inCtrl is TWinControl) then
// GenerateWinCtrl(inCtrl)
else
inMarkup.Add(inCtrl.Name);
end;
end.
|
unit EditBone.Types;
interface
uses
System.Classes;
type
TOpenAllEvent = procedure(var AFileNames: TStrings);
TOutputRec = packed record
Level: Byte;
Filename: string;
Line: LongInt;
Character: LongInt;
TextCharacter: LongWord;
Text: string;
SearchString: string;
Length: Integer;
end;
POutputRec = ^TOutputRec;
TFormatType = (ftJSON, ftSQL, ftXML);
implementation
end.
|
unit ClientPipe1;
interface
uses Windows, Messages,
util1;
procedure SendToPipe;
implementation
procedure SendToPipe;
var
fSuccess:BOOL;
cbRead, cbWritten, dwMode:Dword;
st:string[19];
ok:boolean;
const
lpszPipename:string = '\\.\pipe\mynamedpipe';
hPipe:Thandle=0;
Connected:boolean=false;
begin
if not connected then
begin
ok:=false;
while not ok do
begin
hPipe := CreateFile(
PansiChar(lpszPipename), // pipe name
GENERIC_READ or // read and write access
GENERIC_WRITE,
0, // no sharing
Nil, // no security attributes
OPEN_EXISTING, // opens existing pipe
0, // default attributes
0); // no template file
ok:= (hPipe <> INVALID_HANDLE_VALUE);
if not ok then
begin
if not WaitNamedPipe(PansiChar(lpszPipename), 20000) then
begin
messageCentral('Could not open pipe');
exit;
end;
end;
end;
dwMode := PIPE_READMODE_MESSAGE;
fSuccess := SetNamedPipeHandleState(
hPipe, // pipe handle
dwMode, // new pipe mode
Nil, // don't set max. bytes
Nil); // don't set max. time
if not fSuccess then
begin
MessageCentral('SetNamedPipeHandleState');
exit;
end;
end;
connected:=true;
st:='COUCOU';
fSuccess := WriteFile(
hPipe, // pipe handle
st, // message
20, // message length
cbWritten, // bytes written
Nil); // not overlapped
if not fSuccess then
begin
MessageCentral('WriteFile error');
exit;
end;
fSuccess := ReadFile(
hPipe, // pipe handle
st, // buffer to receive reply
20, // size of buffer
cbRead, // number of bytes read
Nil); // not overlapped
if not fSuccess and (GetLastError<> ERROR_MORE_DATA) then exit;
messageCentral('Rešu '+st);
// CloseHandle(hPipe);
end;
end.
|
unit uAdditionalPageFrame;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, uAdditionalPageData, uFormControl, uFControl, SpFormUnit,
uLabeledFControl, uCharControl, ComCtrls, uIntControl, uSpravControl,
uEnumControl, uDateControl, Buttons, SpCommon, ExtCtrls, uBoolControl,
uInvisControl, uCommonSp, cxControls, cxContainer, cxEdit, cxLabel,
cxDropDownEdit, cxMRUEdit, cxMaskEdit, cxCalendar, cxTextEdit, cxCheckBox,
cxRadioGroup, cxMemo;
type
TfmPCardAdditionalPage = class(TFrame)
qFFC_Additional: TqFFormControl;
Panel1: TPanel;
SB_AdditionalApply: TSpeedButton;
SB_AdditionalReset: TSpeedButton;
qFSC_MedView: TqFSpravControl;
lblShowInfo: TLabel;
CameFromEdit: TcxTextEdit;
lblCameFrom: TcxLabel;
lblPostBefore: TcxLabel;
PostBeforeEdit: TcxTextEdit;
DateCame: TcxDateEdit;
lblDateCame: TcxLabel;
rgGraduate: TRadioGroup;
lblDateAspir: TcxLabel;
DateAspir: TcxDateEdit;
IgdivEdit: TcxTextEdit;
lblIgdiv: TcxLabel;
lblPhone: TcxLabel;
PhoneEdit: TcxTextEdit;
lblDiscipline: TcxLabel;
DisciplineEdit: TcxTextEdit;
lblReKval: TcxLabel;
ReKvalEdit: TcxTextEdit;
lblDateLastMed: TcxLabel;
DateLastMed: TcxDateEdit;
cbAspir: TCheckBox;
cbDoct: TCheckBox;
lblDateDoct: TcxLabel;
DateDoct: TcxDateEdit;
NoteEdit: TcxMemo;
lblNote: TcxLabel;
lblAspir: TcxLabel;
lblDoct: TcxLabel;
lblPersData: TcxLabel;
isGetProcPersData: TCheckBox;
procedure SB_AdditionalApplyClick(Sender: TObject);
procedure SB_AdditionalResetClick(Sender: TObject);
procedure qFSC_MedViewOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: String);
procedure Came_fromChange(Sender: TObject);
procedure cbAspirClick(Sender: TObject);
procedure cbDoctClick(Sender: TObject);
procedure CameFromEditPropertiesChange(Sender: TObject);
procedure PostBeforeEditPropertiesChange(Sender: TObject);
procedure DateCamePropertiesChange(Sender: TObject);
procedure IgdivEditPropertiesChange(Sender: TObject);
procedure PhoneEditPropertiesChange(Sender: TObject);
procedure DisciplineEditPropertiesChange(Sender: TObject);
procedure ReKvalEditPropertiesChange(Sender: TObject);
procedure DateLastMedPropertiesChange(Sender: TObject);
procedure IgdivEditKeyPress(Sender: TObject; var Key: Char);
procedure ReKvalEditKeyPress(Sender: TObject; var Key: Char);
procedure DateAspirPropertiesChange(Sender: TObject);
procedure DateDoctPropertiesChange(Sender: TObject);
procedure NoteEditPropertiesChange(Sender: TObject);
procedure isGetProcPersDataPropertiesChange(Sender: TObject);
procedure isGetProcPersDataClick(Sender: TObject);
private
DM: TdmPCAdditionalPage;
public
Mode:TFormMode;
IdPcard: Variant;
IdManAddInfo:Variant;
constructor Create(AOwner: TComponent; DM: TdmPCAdditionalPage; Mode:TFormMode; Id_PCard: Integer);
reintroduce;
procedure RefreshPage;
end;
implementation
uses DateUtils, BaseTypes;
{$R *.dfm}
constructor TfmPCardAdditionalPage.Create(AOwner: TComponent; DM: TdmPCAdditionalPage; Mode:TFormMode; Id_PCard: Integer);
begin
inherited Create(AOwner);
Self.DM := DM;
Self.Mode:=Mode;
IdPcard:=Id_PCard;
qFFC_Additional.Prepare(DM.DB, Mode, Id_PCard, Null);
SB_AdditionalApply.Enabled:=(Mode=fmModify);
SB_AdditionalReset.Enabled:=(Mode=fmModify);
//qFBC_IsAspirChange(qFBC_IsAspir);
NoteEdit.Lines.Text:='';
RefreshPage;
lblShowInfo.visible:=false;
if Mode<>fmModify then
begin
CameFromEdit.Enabled:=False;
PostBeforeEdit.Enabled:=False;
DateCame.Enabled:=False;
IgdivEdit.Enabled:=False;
cbAspir.Enabled:=False;
DateAspir.Enabled:=False;
cbDoct.Enabled:=False;
DateDoct.Enabled:=False;
DisciplineEdit.Enabled:=False;
ReKvalEdit.Enabled:=False;
NoteEdit.Enabled:=False;
DateLastMed.Enabled:=False;
end;
end;
procedure TfmPCardAdditionalPage.RefreshPage;
begin
with DM do
begin
ManDSet.Close;
ManDSet.SQLs.SelectSQL.Text:='select distinct * from asup_man_addinfo_s(:id_pcard)';
ManDSet.ParamByName('id_pcard').AsInt64:=IdPcard;
ManDSet.Open;
if not ManDSet.IsEmpty then
begin
if VarIsNull(ManDSet['Came_From']) then CameFromEdit.Text:=''
else CameFromEdit.Text:=ManDSet['Came_From'];
if VarIsNull(ManDSet['Were_Before']) then PostBeforeEdit.Text:=''
else PostBeforeEdit.Text:=ManDSet['Were_Before'];
if VarIsNull(ManDSet['Date_Came']) then DateCame.EditValue:=Null
else DateCame.EditValue:=ManDSet['Date_Came'];
if VarIsNull(ManDSet['Is_Aspir']) then cbAspir.Checked:=False
else if ManDSet['Is_Aspir']='T' then cbAspir.Checked:=True
else cbAspir.Checked:=False;
if VarIsNull(ManDSet['Date_Aspir']) then DateAspir.EditValue:=Null
else DateAspir.EditValue:=ManDSet['Date_Aspir'];
if VarIsNull(ManDSet['Is_Doct']) then cbDoct.Checked:=False
else if ManDSet['Is_Doct']='T' then cbDoct.Checked:=True
else cbDoct.Checked:=False;
if VarIsNull(ManDSet['Date_Doct']) then DateDoct.EditValue:=Null
else DateDoct.EditValue:=ManDSet['Date_Doct'];
if VarIsNull(ManDSet['Igdiv']) then IgdivEdit.Text:=''
else IgdivEdit.Text:=IntToStr(ManDSet['Igdiv']);
{if VarIsNull(ManDSet['Telefon']) then PhoneEdit.Text:=''
else PhoneEdit.Text:=ManDSet['Telefon'];}
if VarIsNull(ManDSet['Discipline']) then DisciplineEdit.Text:=''
else DisciplineEdit.Text:=ManDSet['Discipline'];
if not VarIsNull(ManDSet['Id_Medview']) then
begin
qFSC_MedView.Value:=ManDSet['Id_Medview'];
qFSC_MedView.DisplayText:=ManDSet['Name_Medview'];
end
else
begin
qFSC_MedView.DisplayText:='';
qFSC_MedView.Value:=null;
end;
if VarIsNull(ManDSet['Year_P']) then ReKvalEdit.Text:=''
else ReKvalEdit.Text:=IntToStr(ManDSet['Year_P']);
if VarIsNull(ManDSet['Date_Vut']) then DateLastMed.EditValue:=Null
else DateLastMed.EditValue:=ManDSet['Date_Vut'];
If VarIsNull(ManDSet['Note']) then NoteEdit.Lines.Text:=''
else NoteEdit.Lines.Text:=ManDSet['Note'];
cbAspirClick(Self);
cbDoctClick(Self);
IdManAddInfo:=ManDSet['Id_Man_Addinfo'];
if VarIsNull(ManDSet['Is_Get_Proc_Pers_Data']) then isGetProcPersData.Checked:=False
else
begin
if ManDSet['Is_Get_Proc_Pers_Data']='T' then isGetProcPersData.Checked:=True
else isGetProcPersData.Checked:=False;
end;
end;
end;
end;
procedure TfmPCardAdditionalPage.SB_AdditionalApplyClick(Sender: TObject);
begin
with DM do
begin
StorProc.Transaction.StartTransaction;
StorProc.StoredProcName:='ASUP_MAN_ADDINFO_IU';
StorProc.Prepare;
StorProc.ParamByName('Id_Man_Addinfo').Value:=IdManAddInfo;
StorProc.ParamByName('Id_Pcard').AsInt64:=IdPcard;
StorProc.ParamByName('Came_From').AsString:=CameFromEdit.Text;
StorProc.ParamByName('Were_Before').AsString:=PostBeforeEdit.Text;
if DateCame.Text='' then StorProc.ParamByName('Date_Came').Value:=null
else StorProc.ParamByName('Date_Came').AsDate:=StrToDate(DateCame.Text);
if cbAspir.Checked then StorProc.ParamByName('Is_Aspir').AsString:='T'
else StorProc.ParamByName('Is_Aspir').AsString:='F';
if DateAspir.Text='' then StorProc.ParamByName('Date_Aspir').Value:=null
else StorProc.ParamByName('Date_Aspir').AsDate:=StrToDate(DateAspir.Text);
if cbDoct.Checked then StorProc.ParamByName('Is_Doct').AsString:='T'
else StorProc.ParamByName('Is_Doct').AsString:='F';
if DateDoct.Text='' then StorProc.ParamByName('Date_Doct').Value:=null
else StorProc.ParamByName('Date_Doct').AsDate:=StrToDate(DateDoct.Text);
if IgdivEdit.Text<>'' then StorProc.ParamByName('Igdiv').AsInteger:=StrToInt(IgdivEdit.Text);
StorProc.ParamByName('Telefon').AsString:='';
StorProc.ParamByName('Discipline').AsString:=DisciplineEdit.Text;
if VarIsNull(qFSC_MedView.Value) then StorProc.ParamByName('Id_Medview').Value:=null
else StorProc.ParamByName('Id_Medview').AsInteger:=qFSC_MedView.Value;
if ReKvalEdit.Text<>'' then StorProc.ParamByName('Year_P').AsInteger:=StrToInt(ReKvalEdit.Text);
if DateLastMed.Text='' then StorProc.ParamByName('Date_Vut').Value:=Null
else StorProc.ParamByName('Date_Vut').AsDate:=StrToDate(DateLastMed.Text);
StorProc.ParamByName('Note').AsString:=NoteEdit.Lines.Text;
if isGetProcPersData.Checked then StorProc.ParamByName('Is_Get_Proc_Pers_Data').AsString:='T'
else StorProc.ParamByName('Is_Get_Proc_Pers_Data').AsString:='F';
try
StorProc.ExecProc;
StorProc.Transaction.Commit;
except on E: Exception
do begin
agMessageDlg('Увага!', e.Message, mtInformation, [mbOK]);
StorProc.Transaction.Rollback;
end;
end;
end;
RefreshPage;
lblShowInfo.visible:=false;
end;
procedure TfmPCardAdditionalPage.SB_AdditionalResetClick(Sender: TObject);
begin
RefreshPage;
lblShowInfo.visible:=false;
end;
procedure TfmPCardAdditionalPage.qFSC_MedViewOpenSprav(Sender: TObject;
var Value: Variant; var DisplayText: String);
var
form: TSpForm;
PropParams: TSpParams;
begin
PropParams:=TSpParams.Create;
with PropParams do
begin
Table := 'Asup_Sp_medview';
Title := 'Медичний огляд';
IdField := 'Id_medview';
SpFields := 'Name_medview';
ColumnNames := 'Назва';
SpMode := [spfModify,spfFind,spfSelect,spfExt];
end;
form := TSpForm.Create(Self);
form.Init(PropParams);
if (form.ShowModal=mrOk) then
begin
value:=form.ResultQuery['Id_medview'];
DisplayText:=form.ResultQuery['name_medview'];
end;
form.Free;
PropParams.Free;
end;
procedure TfmPCardAdditionalPage.Came_fromChange(Sender: TObject);
begin
if not VarIsNull(qFSC_MedView.Value) then lblShowInfo.visible:=true;
end;
procedure TfmPCardAdditionalPage.cbAspirClick(Sender: TObject);
begin
lblShowInfo.visible:=True;
if cbAspir.Checked then
begin
lblDateAspir.Visible:=True;
DateAspir.Visible:=True;
end
else
begin
lblDateAspir.Visible:=False;
DateAspir.Visible:=False;
end;
end;
procedure TfmPCardAdditionalPage.cbDoctClick(Sender: TObject);
begin
lblShowInfo.visible:=True;
if cbDoct.Checked then
begin
lblDateDoct.Visible:=True;
DateDoct.Visible:=True;
end
else
begin
lblDateDoct.Visible:=False;
DateDoct.Visible:=False;
end;
end;
procedure TfmPCardAdditionalPage.CameFromEditPropertiesChange(
Sender: TObject);
begin
lblShowInfo.visible:=True;
end;
procedure TfmPCardAdditionalPage.PostBeforeEditPropertiesChange(
Sender: TObject);
begin
lblShowInfo.visible:=True;
end;
procedure TfmPCardAdditionalPage.DateCamePropertiesChange(Sender: TObject);
begin
lblShowInfo.visible:=True;
end;
procedure TfmPCardAdditionalPage.IgdivEditPropertiesChange(
Sender: TObject);
begin
lblShowInfo.visible:=True;
end;
procedure TfmPCardAdditionalPage.PhoneEditPropertiesChange(
Sender: TObject);
begin
// lblShowInfo.visible:=True;
end;
procedure TfmPCardAdditionalPage.DisciplineEditPropertiesChange(
Sender: TObject);
begin
lblShowInfo.visible:=True;
end;
procedure TfmPCardAdditionalPage.ReKvalEditPropertiesChange(
Sender: TObject);
begin
lblShowInfo.visible:=True;
end;
procedure TfmPCardAdditionalPage.DateLastMedPropertiesChange(
Sender: TObject);
begin
lblShowInfo.visible:=True;
end;
procedure TfmPCardAdditionalPage.IgdivEditKeyPress(Sender: TObject;
var Key: Char);
begin
if (key in ['0'..'9']) or (key=#8) then IgdivEdit.Properties.ReadOnly:=false
else IgdivEdit.Properties.ReadOnly:=true;
end;
procedure TfmPCardAdditionalPage.ReKvalEditKeyPress(Sender: TObject;
var Key: Char);
begin
if (key in ['0'..'9']) or (key=#8) then ReKvalEdit.Properties.ReadOnly:=false
else ReKvalEdit.Properties.ReadOnly:=true;
end;
procedure TfmPCardAdditionalPage.DateAspirPropertiesChange(
Sender: TObject);
begin
lblShowInfo.visible:=True;
end;
procedure TfmPCardAdditionalPage.DateDoctPropertiesChange(Sender: TObject);
begin
lblShowInfo.visible:=True;
end;
procedure TfmPCardAdditionalPage.NoteEditPropertiesChange(Sender: TObject);
begin
lblShowInfo.visible:=True;
end;
procedure TfmPCardAdditionalPage.isGetProcPersDataPropertiesChange(
Sender: TObject);
begin
lblShowInfo.visible:=True;
end;
procedure TfmPCardAdditionalPage.isGetProcPersDataClick(Sender: TObject);
begin
lblShowInfo.visible:=True;
end;
end.
|
{*****************************************************************}
{ ceosconsts is part of Ceos middleware/n-tier JSONRPC components }
{ }
{ Beta version }
{ }
{ This library 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. }
{ }
{ by Jose Benedito - josebenedito@gmail.com }
{ www.jbsolucoes.net }
{*****************************************************************}
unit ceosconsts;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
const
JSONRPC_VERSION : string = '2.0';
JSON_HEADER_CONTENT_TYPE: string = 'Content-type: application/json; charset=UTF-8';
CEOS_VERSION : string = '0.0.3';
CEOS_DEFAULT_PORT : integer = 8080;
ERR_INTERNAL_ERROR = -32000;
ERR_REQUEST_ERROR = -32100;
ERR_UNKNOW_FUNCTION = -32601;
ERR_REQUEST_CONTENT = -32600;
ERR_INVALID_CONTENT = -32602;
ERR_INVALID_QUERY = -32300;
implementation
end.
|
unit readthread;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, threads, callstack,
Ultibo, GlobalConst;
type
TReadThread = class(TThread)
protected
FActive: boolean;
FRecordSize : Longword;
FBytesRead : Longword;
FFirstMessageSent : Boolean;
FRecordBufferP : pchar;
FUpdateBufferP : pchar;
FDeviceCloseRequested : boolean;
FExecutionIsOver : boolean;
protected
procedure SetActive(state: boolean);
procedure DeviceOpen; virtual; abstract;
procedure DeviceClose; virtual; abstract;
procedure ReadData; virtual; abstract;
procedure WriteData(data: string); virtual; abstract;
procedure OnRecordAvailable(recP : pchar; bufsize : integer); virtual; abstract;
procedure OnConnectionEstablished; virtual; abstract;
procedure SetRecordSize(ASize : longword); virtual;
function ExtraBufferByteCount : integer; virtual; abstract;
public
SystemBooted : boolean;
constructor Create(aRecordSize : Integer; CreateSuspended: Boolean);
destructor Destroy; override;
procedure Execute; override;
procedure FastForward(secs : integer); virtual abstract;
property Active: boolean read FActive write SetActive;
property Terminated;
property RecordSize : Longword read FRecordSize write SetRecordSize;
property ExecutionIsOver : boolean read FExecutionIsOver;
end;
implementation
uses
logoutput;
constructor TReadThread.Create(aRecordSize : Integer; CreateSuspended : boolean);
begin
inherited Create(CreateSuspended);
FExecutionIsOver := false;
SystemBooted := true;
FActive := False;
FRecordSize := aRecordSize;
FBytesRead := 0;
log('getting ' + inttostr(frecordsize + extrabufferbytecount) + ' bytes for record buffer');
FRecordBufferP := Getmem(FRecordSize + ExtraBufferByteCount);
fillchar(FRecordBufferP^, FRecordSize + ExtraBufferByteCount, 0);
FUpdateBufferP := FRecordBufferP;
FFirstMessageSent := False;
FDeviceCloseRequested := False;
end;
destructor TReadThread.Destroy;
begin
log('TReadThread.Destroy');
DeviceClose;
inherited Destroy;
end;
procedure TReadThread.SetActive(state: boolean);
begin
if state=FActive then exit;
if state then
DeviceOpen
else
DeviceClose;
FActive:=state;
end;
procedure TReadThread.SetRecordSize(ASize : longword);
begin
if (ASize <> FRecordSize) then
begin
if (FRecordBufferP <> nil) then
FreeMem(FRecordBufferP);
FRecordSize := ASize;
log('setrecordsize getting ' + inttostr(asize + ExtraBufferByteCount) + ' bytes for record buffer');
getmem(FRecordBufferP, ASize + ExtraBufferByteCount);
fillchar(FRecordBufferP^, ASize, 0);
FUpdateBufferP := FRecordBufferP;
FBytesRead := 0;
end;
end;
procedure TReadThread.Execute;
begin
ThreadSetName(GetCurrentThreadId, 'SPEEDY MSG HANDLER');
{$ifdef RPI3}
ThreadSetAffinity(GetCurrentThread, CPU_AFFINITY_3);
ThreadMigrate(GetCurrentThreadId, 3);
{$endif}
try
try
while not Terminated do
begin
if (Active) then
begin
ReadData;
if (FBytesRead = FRecordSize) then
begin
if (not FFirstMessageSent) then
begin
OnConnectionEstablished;
FFirstMessageSent := True;
end;
OnRecordAvailable(FRecordBufferP, FRecordSize + ExtraBufferByteCount);
FBytesRead := 0;
FUpdateBufferP := FRecordBufferP;
end;
if (FDeviceCloseRequested) then
begin
Active := False;
FDeviceCloseRequested := False;
end;
end;
end;
except
on e:exception do
begin
log('Exception occurred: ' + e.message + ' at ' + inttohex(longword(exceptaddr), 8));
dumpcallstack;
end;
end;
finally
log('Execution of read thread has completed');
FreeMem(FRecordBufferP);
FRecordBufferP := nil;
FExecutionIsOver := true;
end;
end;
end.
|
unit ibSHWizardViewFrm;
interface
uses
SHDesignIntf, ibSHDesignIntf, ibSHDDLWizardCustomFrm,
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, SynEdit, pSHSynEdit, StdCtrls, ExtCtrls, ComCtrls, StrUtils;
type
TibSHWizardViewForm = class(TibSHDDLWizardCustomForm)
PageControl1: TPageControl;
TabSheet1: TTabSheet;
Bevel1: TBevel;
Panel1: TPanel;
Label1: TLabel;
Edit1: TEdit;
TabSheet2: TTabSheet;
Bevel2: TBevel;
Panel2: TPanel;
pSHSynEdit1: TpSHSynEdit;
private
{ Private declarations }
protected
{ Protected declarations }
procedure SetTMPDefinitions; override;
public
{ Public declarations }
constructor Create(AOwner: TComponent; AParent: TWinControl;
AComponent: TSHComponent; ACallString: string); override;
destructor Destroy; override;
end;
var
ibSHWizardViewForm: TibSHWizardViewForm;
implementation
{$R *.dfm}
{ TibSHWizardViewForm }
constructor TibSHWizardViewForm.Create(AOwner: TComponent; AParent: TWinControl;
AComponent: TSHComponent; ACallString: string);
begin
inherited Create(AOwner, AParent, AComponent, ACallString);
InitPageCtrl(PageControl1);
InitDescrEditor(pSHSynEdit1);
SetFormSize(250, 400);
Edit1.Text := DBObject.Caption;
Edit1.Enabled := not (DBState = csAlter);
end;
destructor TibSHWizardViewForm.Destroy;
begin
inherited Destroy;
end;
procedure TibSHWizardViewForm.SetTMPDefinitions;
begin
TMPObject.Caption := NormalizeCaption(Trim(Edit1.Text));
(TMPObject as IibSHView).Fields.Assign((DBObject as IibSHView).Fields);
(TMPObject as IibSHView).BodyText.Assign((DBObject as IibSHView).BodyText);
end;
end.
|
/// Модуль LightPT автоматической легковесной проверки заданий
unit LightPT;
{$reference System.Net.Http.dll}
{$reference System.Security.dll}
interface
{==============================================================}
{ Класс для формирования вывода }
{==============================================================}
type
/// Класс для формирования вывода
ObjectList = class
lst := new List<object>;
public
static function New: ObjectList := ObjectList.Create;
procedure Add(o: object) := lst.Add(o);
function AddRange(sq: sequence of integer): ObjectList; begin lst.AddRange(sq.Select(x -> object(x))); Result := Self end;
function AddRange(sq: sequence of real): ObjectList; begin lst.AddRange(sq.Select(x -> object(x))); Result := Self end;
function AddRange(sq: sequence of string): ObjectList; begin lst.AddRange(sq.Select(x -> object(x))); Result := Self end;
function AddRange(sq: sequence of char): ObjectList; begin lst.AddRange(sq.Select(x -> object(x))); Result := Self end;
function AddRange(sq: sequence of boolean): ObjectList; begin lst.AddRange(sq.Select(x -> object(x))); Result := Self end;
function AddRange(sq: sequence of object): ObjectList; begin lst.AddRange(sq); Result := Self end;
function AddRange(sq: sequence of System.Type): ObjectList; begin lst.AddRange(sq.Select(x -> object(x))); Result := Self end;
function AddFill(n: integer; elem: object): ObjectList; begin lst.AddRange(ArrFill(n,elem)); Result := Self end;
function AddArithm(n: integer; a0,step: integer): ObjectList; begin lst.AddRange(ArrGen(n,a0,x->x+step).Select(x -> object(x))); Result := Self end;
function AddArithm(n: integer; a0,step: real): ObjectList; begin lst.AddRange(ArrGen(n,a0,x->x+step).Select(x -> object(x))); Result := Self end;
function AddFib(n: integer): ObjectList; begin lst.AddRange(ArrGen(n,1,1,(x,y)->x+y).Select(x -> object(x))); Result := Self end;
function AddGeom(n: integer; a0,step: integer): ObjectList; begin lst.AddRange(ArrGen(n,a0,x->x*step).Select(x -> object(x))); Result := Self end;
function AddGeom(n: integer; a0,step: real): ObjectList; begin lst.AddRange(ArrGen(n,a0,x->x*step).Select(x -> object(x))); Result := Self end;
end;
{==================================================================================}
{ Сервисные типы }
{==================================================================================}
type
MessageColorT = (MsgColorGreen, MsgColorRed, MsgColorOrange, MsgColorMagenta, MsgColorGray);
TaskStatus = (NotUnderControl, Solved, IOError, BadSolution, PartialSolution, InitialTask, BadInitialTask, InitialTaskPT4, ErrFix, Demo); // Короткий результат для БД
{==================================================================================}
{ Переопределенные функций стандартного модуля с заполнением ввода и вывода }
{==================================================================================}
/// Возвращает случайное целое в диапазоне от a до b
function Random(a, b: integer): integer;
/// Возвращает случайное целое в диапазоне от 0 до n-1
function Random(n: integer): integer;
/// Возвращает случайное вещественное в диапазоне [0..1)
function Random: real;
/// Возвращает случайное вещественное в диапазоне [a,b)
function Random(a, b: real): real;
/// Возвращает случайный символ в диапазоне от a до b
function Random(a, b: char): char;
/// Возвращает случайное целое в диапазоне
function Random(diap: IntRange): integer;
/// Возвращает случайное вещественное в диапазоне
function Random(diap: RealRange): real;
/// Возвращает случайный символ в диапазоне
function Random(diap: CharRange): char;
/// Возвращает кортеж из двух случайных целых в диапазоне от a до b
function Random2(a, b: integer): (integer, integer);
/// Возвращает кортеж из двух случайных вещественных в диапазоне от a до b
function Random2(a, b: real): (real, real);
/// Возвращает кортеж из двух случайных символов в диапазоне от a до b
function Random2(a, b: char): (char, char);
/// Возвращает кортеж из двух случайных целых в диапазоне
function Random2(diap: IntRange): (integer, integer);
/// Возвращает кортеж из двух случайных символов в диапазоне
function Random2(diap: CharRange): (char, char);
/// Возвращает кортеж из двух случайных вещественных в диапазоне
function Random2(diap: RealRange): (real, real);
/// Возвращает кортеж из трех случайных целых в диапазоне от a до b
function Random3(a, b: integer): (integer, integer, integer);
/// Возвращает кортеж из трех случайных вещественных в диапазоне от a до b
function Random3(a, b: real): (real, real, real);
/// Возвращает кортеж из трех случайных символов в диапазоне от a до b
function Random3(a, b: char): (char, char, char);
/// Возвращает кортеж из трех случайных целых в диапазоне
function Random3(diap: IntRange): (integer, integer, integer);
/// Возвращает кортеж из трех случайных вещественных в диапазоне
function Random3(diap: RealRange): (real, real, real);
/// Возвращает кортеж из трех случайных символов в диапазоне
function Random3(diap: CharRange): (char, char, char);
/// Возвращает массив размера n, заполненный случайными целыми значениями в диапазоне от a до b
function ArrRandomInteger(n: integer; a: integer; b: integer): array of integer;
/// Возвращает массив размера n, заполненный случайными целыми значениями в диапазоне от 0 до 100
function ArrRandomInteger(n: integer): array of integer;
/// Возвращает массив размера n, заполненный случайными вещественными значениями в диапазоне от a до b
function ArrRandomReal(n: integer; a: real; b: real): array of real;
/// Возвращает массив размера n, заполненный случайными вещественными значениями в диапазоне от 0 до 10
function ArrRandomReal(n: integer): array of real;
/// Возвращает двумерный массив размера m x n, заполненный случайными целыми значениями
function MatrRandomInteger(m: integer; n: integer; a: integer; b: integer): array [,] of integer;
/// Возвращает двумерный массив размера m x n, заполненный случайными целыми значениями
function MatrRandomInteger(m: integer; n: integer): array [,] of integer;
/// Возвращает двумерный массив размера m x n, заполненный случайными вещественными значениями
function MatrRandomReal(m: integer; n: integer; a: real; b: real): array [,] of real;
/// Возвращает двумерный массив размера m x n, заполненный случайными вещественными значениями
function MatrRandomReal(m: integer; n: integer): array [,] of real;
/// Возвращает двумерный массив размера m x n, заполненный элементами gen(i,j)
//function MatrGen<T>(m, n: integer; gen: (integer,integer)->T): array [,] of T;
/// Выводит приглашение к вводу и возвращает значение типа integer, введенное с клавиатуры
function ReadInteger(prompt: string): integer;
/// Выводит приглашение к вводу и возвращает два значения типа integer, введенные с клавиатуры
function ReadInteger2(prompt: string): (integer, integer);
/// Выводит приглашение к вводу и возвращает значение типа integer, введенное с клавиатуры
function ReadlnInteger(prompt: string): integer;
///- procedure Print(a,b,...);
/// Выводит значения a,b,... на экран, после каждого значения выводит пробел
procedure Print(params args: array of object);
///- procedure Println(a,b,...);
/// Выводит значения a,b,... на экран, после каждого значения выводит пробел и переходит на новую строку
procedure Println(params args: array of object);
/// Выводит значение экран и выводит пробел
procedure Print(ob: object);
/// Выводит значение экран и выводит пробел
procedure Print(s: string);
/// Выводит значение экран и выводит пробел
procedure Print(c: char);
{=========================================================================}
{ Сервисные процедуры }
{=========================================================================}
procedure ColoredMessage(msg: string; color: MessageColorT);
procedure ColoredMessage(msg: string);
{=========================================================================}
{ Основные процедуры для проверки правильности ввода-вывода }
{=========================================================================}
// Самые часто используемые: CheckInput, CheckOutput, CheckOutputSeq
/// Проверить типы вводимых данных
procedure CheckInput(a: array of System.Type);
/// Проверить значения при выводе
procedure CheckOutput(params arr: array of object);
/// Проверить, что данные не вводились
procedure CheckInputIsEmpty;
/// Проверить, что помимо начального ввода других данных не вводилось
procedure CheckInputIsInitial;
/// Синоним CheckInput
procedure CheckInputTypes(a: array of System.Type);
/// Проверить количество вводимых данных
procedure CheckInputCount(n: integer);
/// Проверить количество вводимых данных
procedure CheckInput2Count(i: integer);
/// Проверить количество выводимых данных
procedure CheckOutput2Count(i: integer);
/// Проверить последовательность значений при выводе
procedure CheckOutputSeq(a: sequence of integer);
/// Проверить последовательность значений при выводе
procedure CheckOutputSeq(a: sequence of real);
/// Проверить последовательность значений при выводе
procedure CheckOutputSeq(a: sequence of string);
/// Проверить последовательность значений при выводе
procedure CheckOutputSeq(a: sequence of char);
/// Проверить последовательность значений при выводе
procedure CheckOutputSeq(a: sequence of boolean);
/// Проверить последовательность значений при выводе
procedure CheckOutputSeq(a: sequence of object);
/// Проверить последовательность значений при выводе
procedure CheckOutputSeq(a: sequence of word);
/// Проверить последовательность значений при выводе
procedure CheckOutputSeq(a: ObjectList);
/// Проверить вывод в виде строки
procedure CheckOutputString(str: string);
/// Сравнить типы выведенных значений с указанными
procedure CompareTypeWithOutput(params a: array of System.Type);
/// Сравнить два значения
function CompareValues(o1, o2: Object): boolean;
/// Сравнить два массива
function CompareArrValues(a,lst: array of object): boolean;
/// Сравнить значения с выводом
function CompareValuesWithOutput(params a: array of object): boolean;
// Для совместимости
procedure CheckOutputNew(params arr: array of object);
procedure CheckOutputSeqNew(a: sequence of integer);
procedure CheckOutputSeqNew(a: sequence of real);
procedure CheckOutputSeqNew(a: sequence of string);
procedure CheckOutputSeqNew(a: sequence of char);
procedure CheckOutputSeqNew(a: sequence of boolean);
procedure CheckOutputSeqNew(a: sequence of object);
procedure CheckOutputSeqNew(a: sequence of word);
procedure CheckOutputSeqNew(a: ObjectList);
{============================================================================================}
{ Подпрограммы для проверки начального ввода-вывода, представленного в заготовке задания }
{============================================================================================}
procedure CheckData(InitialInput: array of System.Type := nil;
InitialOutput: array of System.Type := nil;
Input: array of System.Type := nil);
procedure CheckInitialIO;
procedure CheckInitialIOIsEmpty;
procedure InitialOutput(a: array of System.Type);
procedure InitialInput(a: array of System.Type);
//procedure CheckInitialOutputValues(params a: array of object); - тут значений быть не должно!
procedure CheckInitialOutput(params a: array of System.Type);
procedure CheckInitialInput(params a: array of System.Type);
procedure CheckInitialOutputSeq(a: sequence of System.Type);
procedure CheckInitialInputSeq(a: sequence of System.Type);
procedure CheckInitialIOSeqs(input,output: sequence of System.Type);
procedure CheckOutputAfterInitial(params arr: array of object); // проверить только то, что после исходного вывода
procedure CheckOutputAfterInitialSeq(seq: sequence of integer);
procedure CheckOutputAfterInitialSeq(seq: sequence of real);
procedure CheckOutputAfterInitialSeq(seq: sequence of string);
procedure CheckOutputAfterInitialSeq(seq: sequence of boolean);
procedure CheckOutputAfterInitialSeq(seq: sequence of char);
procedure CheckOutputAfterInitialSeq(seq: sequence of object);
procedure CheckOutputAfterInitialSeq(seq: ObjectList);
{=========================================================}
{ Функции для проверки элементов ввода-вывода }
{=========================================================}
/// i-тый элемент ввода - целое
function IsInt(i: integer): boolean;
/// i-тый элемент ввода - вещественное
function IsRe(i: integer): boolean;
/// i-тый элемент ввода - строка
function IsStr(i: integer): boolean;
/// i-тый элемент ввода - логическое
function IsBoo(i: integer): boolean;
/// i-тый элемент ввода - символ
function IsChr(i: integer): boolean;
/// i-тый элемент вывода - целое
function OutIsInt(i: integer): boolean;
/// i-тый элемент вывода - вещественное
function OutIsRe(i: integer): boolean;
/// i-тый элемент вывода - строка
function OutIsStr(i: integer): boolean;
/// i-тый элемент вывода - логическое
function OutIsBoo(i: integer): boolean;
/// i-тый элемент вывода - символ
function OutIsChr(i: integer): boolean;
/// i-тый элемент ввода как целое
function Int(i: integer): integer;
/// i-тый элемент ввода как вещественное
function Re(i: integer): real;
/// i-тый элемент ввода как строка
function Str(i: integer): string;
/// i-тый элемент ввода как логическое
function Boo(i: integer): boolean;
/// i-тый элемент ввода как символ
function Chr(i: integer): char;
/// i-тый элемент вывода как целое
function OutAsInt(i: integer): integer;
/// i-тый элемент вывода как вещественное
function OutAsRe(i: integer): real;
/// i-тый элемент вывода как строка
function OutAsBoo(i: integer): boolean;
/// i-тый элемент вывода как логическое
function OutAsChr(i: integer): char;
/// i-тый элемент вывода как символ
function OutAsStr(i: integer): string;
/// Следующий элемент ввода как целое
function Int: integer;
/// Следующий элемент ввода как вещественное
function Re: real;
/// Следующий элемент ввода как строка
function Str: string;
/// Следующий элемент ввода как логическое
function Boo: boolean;
/// Следующий элемент ввода как символ
function Chr: char;
/// Следующие два элемента ввода как целые
function Int2: (integer, integer);
/// Следующие два элемента ввода как вещественные
function Re2: (real, real);
/// Следующие n элементов ввода как массив целых
function IntArr(n: integer): array of integer;
/// Следующие n элементов ввода как массив вещественных
function ReArr(n: integer): array of real;
/// Следующие n элементов ввода как массив логических
function BooArr(n: integer): array of boolean;
/// Следующие n элементов ввода как массив символов
function ChrArr(n: integer): array of char;
/// Следующие n элементов ввода как массив строк
function StrArr(n: integer): array of string;
// функции, возвращающие входные и выходные списки, а также их срезы, приведенные к нужному типу
function InputListAsIntegers: array of integer;
function InputListAsReals: array of real;
function InputListAsBooleans: array of boolean;
function InputListAsChars: array of char;
function InputListAsStrings: array of string;
function OutputListAsIntegers: array of integer;
function OutputListAsReals: array of real;
function OutputListAsBooleans: array of boolean;
function OutputListAsChars: array of char;
function OutputListAsStrings: array of string;
function InputListSliceAsIntegers(a,b: integer): array of integer;
function InputListSliceAsReals(a,b: integer): array of real;
function InputListSliceAsBooleans(a,b: integer): array of boolean;
function InputListSliceAsChars(a,b: integer): array of char;
function InputListSliceAsStrings(a,b: integer): array of string;
function OutputListSliceAsIntegers(a,b: integer): array of integer;
function OutputListSliceAsReals(a,b: integer): array of real;
function OutputListSliceAsBooleans(a,b: integer): array of boolean;
function OutputListSliceAsChars(a,b: integer): array of char;
function OutputListSliceAsStrings(a,b: integer): array of string;
{=========================================================}
{ Процедуры генерации ошибок }
{=========================================================}
/// Генерация ошибки неверного количества входных значений
procedure ErrorInputCount(Count, n: integer);
/// Генерация ошибки неверного количества выходных значений
procedure ErrorOutputCount(Count, n: integer);
/// Генерация ошибки неверного типа n-того входного значения
procedure ErrorInputType(n: integer; ExpectedType, ActualType: string);
/// Генерация ошибки неверного типа n-того выходного значения
procedure ErrorOutputType(n: integer; ExpectedType, ActualType: string);
{=========================================================}
{ Фильтрация выходного списка }
{=========================================================}
/// Преобразование строк, являющихся целыми, в целые в OutputList
procedure ConvertStringsToNumbersInOutputList;
/// Если в OutputList массивы, вытянуть их в единый список
procedure FlattenOutput;
/// Очистить выходной список от пробелов
procedure ClearOutputListFromSpaces;
/// Отфильтровать в выходном списке только числа
procedure FilterOnlyNumbers;
/// Отфильтровать в выходном списке только числа и логические
procedure FilterOnlyNumbersAndBools;
var
TaskResult: TaskStatus := NotUnderControl; // Записывается в БД
/// Строка, содержащая вывод. Нужна для проверки решения как многострочной строки
OutputString := new StringBuilder;
/// Список выведенных элементов
OutputList := new List<object>;
/// Список введенных элементов
InputList := new List<object>;
/// Список типов элементов, выведенных в заготовке задания (cRe, cInt и т.д.)
InitialOutputList := new List<System.Type>;
/// Список типов элементов, введенных в заготовке задания
InitialInputList := new List<System.Type>;
/// Ссылка на основную процедуру проверки в модуле Task
CheckTask: procedure(name: string);
/// Целый тип для проверки ввода-вывода
function cInt: System.Type;
/// Вещественный тип для проверки ввода-вывода
function cRe: System.Type;
/// Строковый тип для проверки ввода-вывода
function cStr: System.Type;
/// Логический тип для проверки ввода-вывода
function cBool: System.Type;
/// Символьный тип для проверки ввода-вывода
function cChar: System.Type;
implementation
uses __RedirectIOMode;
uses System.Management;
uses System.Security.Cryptography;
uses System.IO;
uses System;
uses System.Net.Http;
uses System.Threading.Tasks;
// Исключения - для вывода сообщения
// TaskResult - для базы данных
// Запоминать исключение в глобальной переменной TaskException - для доп. параметров для БД в формате
// ПодтипИсключения(парам1,...,парамn)
// Эту строку также можно писать в БД как доп параметры TaskResultInfo
// Чем хороши исключения - их можно делать разными с абсолютно разными параметрами
const lightptname = 'lightpt.dat';
type
PTException = class(Exception)
function Info: string; virtual := 'NoInfo';
end;
var
CreateNewLineBeforeMessage := False;
TaskResultInfo: string; // доп. информация о результате. Как правило пуста. Или содержит TaskException.Info. Или содержит для Solved и BadSolution информацию о модуле: Robot, Drawman, PT4
TaskException: PTException := new PTException;
WriteInfoCallBack: procedure (LessonName,TaskName,TaskPlatform: string; result: TaskStatus; AdditionalInfo: string);
LessonName: string := '';
TaskNamesMap := new Dictionary<string,string>;
ServerAddr := 'https://air.mmcs.sfedu.ru/pascalabc';
{=========================================================}
{ Типы, связанные с сетью }
{=========================================================}
type
UserTypeEnum = (None, Student, Teacher, Admin);
ServerAccessProvider = class
private
client: HTTPClient;
public
ServerAddr: string;
auto property ShortFIO: string;
auto property FullFIO: string;
auto property Password: string;
auto property Group: string;
auto property UserType: UserTypeEnum;
constructor (ServerAddr: string);
begin
Self.ServerAddr := ServerAddr;
client := new HttpClient();
client.Timeout := TimeSpan.FromSeconds(10);
end;
function SendPostRequest(FullFIO, Password, LessonName, TaskName, TaskPlatform, TaskResult, TaskResultInfo: string): Task<string>;
begin
var values := Dict(
( 'shortFIO', '' ),
( 'FIO', FullFIO ),
( 'taskName', TaskName ),
( 'lessonName', LessonName ),
( 'taskPlatform', TaskPlatform ),
( 'taskResult', TaskResult ),
( 'taskResultInfo', TaskResultInfo ),
( 'content', '' ),
( 'password', Password )
);
var content := new FormUrlEncodedContent(values);
var response := client.PostAsync(ServerAddr + '/add.php', content);
Result := response.Result.Content.ReadAsStringAsync();
end;
end;
{=========================================================}
{ Типы исключений при решении }
{=========================================================}
type
InputCountException = class(PTException) // Ровно Count
Count: integer; // Count - сколько введено
n: integer; // n - сколько требуется ввести
constructor(Count, n: integer);
begin
Self.Count := Count;
Self.n := n;
TaskResult := IOError;
TaskException := Self;
end;
function Info: string; override := $'InputCount({Count},{n})';
end;
InputCount2Exception = class(PTException) // Не меньше Count
Count: integer; // Count - сколько введено
i: integer; // i - какой номер требуется ввести (с нуля)
constructor(Count, i: integer);
begin
Self.Count := Count;
Self.i := i;
TaskResult := IOError;
TaskException := Self;
end;
function Info: string; override := $'InputCount2({Count},{i})';
end;
InputTypeException = class(PTException)
n: integer; // номер параметра
ExpectedType, ActualType: string;
constructor(n: integer; ExpectedType, ActualType: string);
begin
Self.n := n;
Self.ExpectedType := ExpectedType;
Self.ActualType := ActualType;
TaskResult := IOError;
TaskException := Self;
end;
function Info: string; override := $'InputType({n},{ExpectedType},{ActualType})';
end;
OutputCountException = class(PTException) // Ровно Count
Count: integer; // Count - сколько выведено
n: integer; // n - сколько требуется вывести
constructor(Count, n: integer);
begin
Self.Count := Count;
Self.n := n;
TaskResult := IOError;
TaskException := Self;
end;
function Info: string; override := $'OutputCount({Count},{n})';
end;
OutputCount2Exception = class(PTException) // Ровно Count
Count: integer; // Count - сколько выведено
i: integer; // n - какой номер требуется вывести
constructor(Count, i: integer);
begin
Self.Count := Count;
Self.i := i;
TaskResult := IOError;
TaskException := Self;
end;
function Info: string; override := $'Output2Count({Count},{i})';
end;
OutputTypeException = class(PTException)
n: integer; // номер параметра
ExpectedType, ActualType: string;
constructor(n: integer; ExpectedType, ActualType: string);
begin
Self.n := n;
Self.ExpectedType := ExpectedType;
Self.ActualType := ActualType;
TaskResult := IOError;
TaskException := Self;
end;
function Info: string; override := $'OutputType({n},{ExpectedType},{ActualType})';
end;
var
Cur := 0;
TaskName := ExtractFileName(System.Environment.GetCommandLineArgs[0]).Replace('.exe', '');
{=========================================================}
{ Сервисные функции }
{=========================================================}
procedure ErrorInputCount(Count, n: integer) := raise new InputCountException(Count,n);
procedure ErrorOutputCount(Count, n: integer) := raise new OutputCountException(Count,n);
procedure ErrorInputType(n: integer; ExpectedType, ActualType: string)
:= raise new InputTypeException(n,ExpectedType,ActualType);
procedure ErrorOutputType(n: integer; ExpectedType, ActualType: string)
:= raise new OutputTypeException(n,ExpectedType,ActualType);
/// Является ли задание заданием для задачника PT
function IsPT := System.Type.GetType('PT4.PT4') <> nil;
/// Является ли задание заданием для Робота
function IsRobot := System.Type.GetType('RobotField.RobotField');
/// Является ли задание заданием для Чертежника
function IsDrawman := System.Type.GetType('DrawManField.DrawManField');
/// Полный путь к папке auth-файла
function FindAuthDat: string;
begin
var auth := 'auth.dat';
Result := '';
// В текущем каталоге
if FileExists(auth) then
Result := ExpandFileName(auth)
// Если нет, в каталоге уровня выше
else if FileExists(System.IO.Path.Combine('..',auth)) then
begin
Result := ExpandFileName(System.IO.Path.Combine('..',auth))
end
// Если нет, в корневом каталоге сетевого диска - Это не работает на старых Win 10 куда не устанавливается NET 4/7/1
{else begin
var fullname := ExpandFileName(auth);
var drive := ExtractFileDrive(fullname);
var di := new System.IO.DriveInfo(drive);
if di.DriveType = System.IO.DriveType.Network then
begin
var af := System.IO.Path.Combine(di.RootDirectory.FullName,auth);
if FileExists(af) then
Result := af;
end
end;}
end;
{=================================================================}
{ Функции для шифрования-дешифрования при записи в auth.dat }
{=================================================================}
// На некоторых компьютерах давала сбой, поэтому просто возвращает константу
function ProcessorId: string;
begin
{var mbs := new ManagementObjectSearcher('Select ProcessorId From Win32_processor');
var mbsList := mbs.Get();
Result := '';
foreach var mo: ManagementObject in mbsList do
begin
var pId := mo['ProcessorId'];
if pId <> nil then
Result := pId.ToString()
else Result := 'AAAAAAAAAAAAAAAA';
break;
end;}
Result := 'AAAAAAAAAAAAAAAA';
end;
function Encrypt(src: string): array of byte; // записать в файл
begin
var ae := Aes.Create();
var key := Encoding.UTF8.GetBytes(ProcessorId);
var crypt := ae.CreateEncryptor(key, key);
var ms := new MemoryStream();
var cs := new CryptoStream(ms, crypt, CryptoStreamMode.Write);
var sw := new StreamWriter(cs);
sw.Write(src);
sw.Close;
cs.Close;
ms.Close;
Result := ms.ToArray;
end;
function Decrypt(data: array of byte): string;
begin
if data = nil then
begin
Result := '';
exit
end;
var ae := Aes.Create();
var key := Encoding.UTF8.GetBytes(ProcessorId);
var crypt := ae.CreateDecryptor(key, key);
var ms := new MemoryStream(data);
var cs := new CryptoStream(ms, crypt, CryptoStreamMode.Read);
var sr := new StreamReader(cs);
var text := sr.ReadToEnd;
sr.Close;
cs.Close;
ms.Close;
Result := text;
end;
{=========================================================}
{ Функции для проверки ввода-вывода }
{=========================================================}
function cInt := typeof(integer);
function cRe := typeof(real);
function cStr := typeof(string);
function cBool := typeof(boolean);
function cChar := typeof(char);
procedure CheckData(InitialInput, InitialOutput, Input: array of System.Type);
begin
CheckInitialIOSeqs(InitialInput, InitialOutput);
if Input = nil then
CheckInputIsInitial
else CheckInput(Input);
end;
procedure CheckInitialIO;
begin
if (OutputList.Count = InitialOutputList.Count) and (InputList.Count = InitialInputList.Count) then
TaskResult := InitialTask
else if (InputList.Count < InitialInputList.Count) or (InputList.Count = InitialInputList.Count) and (OutputList.Count < InitialOutputList.Count) then
TaskResult := BadInitialTask;
end;
procedure CheckInitialIOIsEmpty := CheckInitialIO;
procedure InitialOutput(a: array of System.Type);
begin
InitialOutputList.Clear;
if a<>nil then
InitialOutputList.AddRange(a);
end;
procedure InitialInput(a: array of System.Type);
begin
InitialInputList.Clear;
if a<>nil then
InitialInputList.AddRange(a);
end;
function CompareValues(o1, o2: Object): boolean;
begin
if (o1 is real) and (o2 is real) then
begin
var r1 := real(o1);
var r2 := real(o2);
Result := Abs(r1 - r2) < 0.0001;
exit;
end;
Result := o1.Equals(o2);
end;
function CompareArrValues(a,lst: array of object): boolean;
begin
Result := True;
if a.Length <> OutputList.Count then
Result := False;
for var i := 0 to a.Length - 1 do
if not CompareValues(a[i], lst[i]) then
begin
Result := False;
exit;
end;
end;
function CompareValuesWithOutput(params a: array of object): boolean := CompareArrValues(a,OutputList.ToArray);
{procedure CheckInitialOutputValues(params a: array of object);
begin
if CompareArrValues(a,OutputList.ToArray) then
TaskResult := InitialTask;
end;}
// По сути отдельные функции - это неправильно. Необходим CheckInitialInputOutput
procedure CheckInitialOutput(params a: array of System.Type);
begin
InitialOutput(a);
CheckInitialIO;
end;
procedure CheckInitialInput(params a: array of System.Type);
begin
InitialInput(a);
CheckInitialIO;
end;
procedure CheckInitialOutputSeq(a: sequence of System.Type) := CheckInitialOutput(a.ToArray);
procedure CheckInitialInputSeq(a: sequence of System.Type) := CheckInitialInput(a.ToArray);
procedure CheckInitialIOSeqs(input,output: sequence of System.Type);
begin
InitialInput(input?.ToArray);
InitialOutput(output?.ToArray);
CheckInitialIO;
end;
procedure CheckInputCount(n: integer);
begin
if InputList.Count <> n then
raise new InputCountException(InputList.Count, n)
end;
procedure CheckInput2Count(i: integer);
begin
if InputList.Count <= i then
raise new InputCount2Exception(InputList.Count, i + 1)
end;
procedure CheckOutput2Count(i: integer);
begin
if OutputList.Count <= i then
raise new OutputCount2Exception(OutputList.Count, i + 1)
end;
function IsInt(i: integer) := InputList[i] is integer;
function IsRe(i: integer) := InputList[i] is real;
function IsStr(i: integer) := InputList[i] is string;
function IsBoo(i: integer) := InputList[i] is boolean;
function IsChr(i: integer) := InputList[i] is char;
function OutIsInt(i: integer) := OutputList[i] is integer;
function OutIsRe(i: integer) := OutputList[i] is real;
function OutIsStr(i: integer) := OutputList[i] is string;
function OutIsBoo(i: integer) := OutputList[i] is boolean;
function OutIsChr(i: integer) := OutputList[i] is char;
function Int(i: integer): integer;
begin
CheckInput2Count(i);
if not IsInt(i) then
raise new InputTypeException(i + 1, 'integer', TypeName(InputList[i]));
Result := integer(InputList[i]);
end;
function Re(i: integer): real;
begin
CheckInput2Count(i);
if not IsRe(i) then
raise new InputTypeException(i + 1, 'real', TypeName(InputList[i]));
Result := real(InputList[i]);
end;
function Str(i: integer): string;
begin
CheckInput2Count(i);
if not IsStr(i) then
raise new InputTypeException(i + 1, 'string', TypeName(InputList[i]));
Result := string(InputList[i]);
end;
function Boo(i: integer): boolean;
begin
CheckInput2Count(i);
if not IsBoo(i) then
raise new InputTypeException(i + 1, 'boolean', TypeName(InputList[i]));
Result := boolean(InputList[i]);
end;
function Chr(i: integer): char;
begin
CheckInput2Count(i);
if not IsChr(i) then
raise new InputTypeException(i + 1, 'char', TypeName(InputList[i]));
Result := char(InputList[i]);
end;
function OutAsInt(i: integer): integer;
begin
CheckOutput2Count(i);
if not OutIsInt(i) then
raise new OutputTypeException(i + 1, 'integer', TypeName(OutputList[i]));
Result := integer(OutputList[i]);
end;
function OutAsRe(i: integer): real;
begin
CheckOutput2Count(i);
if not OutIsRe(i) then
raise new OutputTypeException(i + 1, 'real', TypeName(OutputList[i]));
Result := real(OutputList[i]);
end;
function OutAsBoo(i: integer): boolean;
begin
CheckOutput2Count(i);
if not OutIsBoo(i) then
raise new OutputTypeException(i + 1, 'boolean', TypeName(OutputList[i]));
Result := boolean(OutputList[i]);
end;
function OutAsChr(i: integer): char;
begin
CheckOutput2Count(i);
if not OutIsChr(i) then
raise new OutputTypeException(i + 1, 'char', TypeName(OutputList[i]));
Result := char(OutputList[i]);
end;
function OutAsStr(i: integer): string;
begin
CheckOutput2Count(i);
if not OutIsStr(i) then
raise new OutputTypeException(i + 1, 'string', TypeName(OutputList[i]));
Result := string(OutputList[i]);
end;
function Int: integer;
begin
Result := Int(Cur);
Cur += 1;
end;
function Re: real;
begin
Result := Re(Cur);
Cur += 1;
end;
function Str: string;
begin
Result := Str(Cur);
Cur += 1;
end;
function Boo: boolean;
begin
Result := Boo(Cur);
Cur += 1;
end;
function Chr: char;
begin
Result := Chr(Cur);
Cur += 1;
end;
function Int2: (integer, integer) := (Int, Int);
function Re2: (real, real) := (Re, Re);
function IntArr(n: integer): array of integer := (1..n).Select(x -> Int).ToArray;
function ReArr(n: integer): array of real := (1..n).Select(x -> Re).ToArray;
function BooArr(n: integer): array of boolean := (1..n).Select(x -> Boo).ToArray;
function ChrArr(n: integer): array of char := (1..n).Select(x -> Chr).ToArray;
function StrArr(n: integer): array of string := (1..n).Select(x -> Str).ToArray;
// функции, возвращающие входные и выходные списки, а также их срезы, приведенные к нужному типу
function InputListAsIntegers: array of integer := InputList.Select((x,i) -> Int(i)).ToArray;
function InputListAsReals: array of real := InputList.Select((x,i) -> Re(i)).ToArray;
function InputListAsBooleans: array of boolean := InputList.Select((x,i) -> Boo(i)).ToArray;
function InputListAsChars: array of char := InputList.Select((x,i) -> Chr(i)).ToArray;
function InputListAsStrings: array of string := InputList.Select((x,i) -> Str(i)).ToArray;
function OutputListAsIntegers: array of integer := OutputList.Select((x,i) -> OutAsInt(i)).ToArray;
function OutputListAsReals: array of real := OutputList.Select((x,i) -> OutAsRe(i)).ToArray;
function OutputListAsBooleans: array of boolean := OutputList.Select((x,i) -> OutAsBoo(i)).ToArray;
function OutputListAsChars: array of char := OutputList.Select((x,i) -> OutAsChr(i)).ToArray;
function OutputListAsStrings: array of string := OutputList.Select((x,i) -> OutAsStr(i)).ToArray;
function InputListSliceAsIntegers(a,b: integer): array of integer := (a..b).Select(i->Int(i)).ToArray;
function InputListSliceAsReals(a,b: integer): array of real := (a..b).Select(i->Re(i)).ToArray;
function InputListSliceAsBooleans(a,b: integer): array of boolean := (a..b).Select(i->Boo(i)).ToArray;
function InputListSliceAsChars(a,b: integer): array of char := (a..b).Select(i->Chr(i)).ToArray;
function InputListSliceAsStrings(a,b: integer): array of string := (a..b).Select(i->Str(i)).ToArray;
function OutputListSliceAsIntegers(a,b: integer): array of integer := (a..b).Select(i->OutAsInt(i)).ToArray;
function OutputListSliceAsReals(a,b: integer): array of real := (a..b).Select(i->OutAsRe(i)).ToArray;
function OutputListSliceAsBooleans(a,b: integer): array of boolean := (a..b).Select(i->OutAsBoo(i)).ToArray;
function OutputListSliceAsChars(a,b: integer): array of char := (a..b).Select(i->OutAsChr(i)).ToArray;
function OutputListSliceAsStrings(a,b: integer): array of string := (a..b).Select(i->OutAsStr(i)).ToArray;
function ConvertOne(ob: Object): Object;
begin
Result := ob;
if ob is string then
begin
var s := string(ob);
var ival: integer;
var rval: real;
if s.TryToInteger(ival) then
Result := ival
else if s.TryToReal(rval) then
Result := rval
end
end;
procedure ConvertStringsToNumbersInOutputList;
begin
for var i:=0 to OutputList.Count - 1 do
OutputList[i] := ConvertOne(OutputList[i]);
end;
{=========================================================================}
{ Переопределенные функции PABCSystem с заполнением ввода и вывода }
{=========================================================================}
/// Возвращает случайное целое в диапазоне от a до b
function Random(a, b: integer): integer;
begin
Result := PABCSystem.Random(a, b);
if IsPT then exit;
InputList.Add(Result);
end;
function Random(n: integer): integer;
begin
Result := PABCSystem.Random(n);
if IsPT then exit;
InputList.Add(Result);
end;
/// Возвращает случайное вещественное в диапазоне [0..1)
function Random: real;
begin
Result := PABCSystem.Random;
if IsPT then exit;
InputList.Add(Result);
end;
/// Возвращает случайное вещественное в диапазоне [a,b)
function Random(a, b: real): real;
begin
Result := PABCSystem.Random(a, b);
if IsPT then exit;
InputList.Add(Result);
end;
/// Возвращает случайный символ в диапазоне от a до b
function Random(a, b: char): char;
begin
Result := PABCSystem.Random(a, b);
if IsPT then exit;
InputList.Add(Result);
end;
/// Возвращает случайное целое в диапазоне
function Random(diap: IntRange): integer;
begin
Result := PABCSystem.Random(diap);
if IsPT then exit;
InputList.Add(Result);
end;
/// Возвращает случайное вещественное в диапазоне
function Random(diap: RealRange): real;
begin
Result := PABCSystem.Random(diap);
if IsPT then exit;
InputList.Add(Result);
end;
/// Возвращает случайный символ в диапазоне
function Random(diap: CharRange): char;
begin
Result := PABCSystem.Random(diap);
if IsPT then exit;
InputList.Add(Result);
end;
/// Возвращает кортеж из двух случайных целых в диапазоне от a до b
function Random2(a, b: integer): (integer, integer);
begin
Result := PABCSystem.Random2(a, b);
if IsPT then exit;
InputList.Add(Result[0]);
InputList.Add(Result[1]);
end;
/// Возвращает кортеж из двух случайных вещественных в диапазоне от a до b
function Random2(a, b: real): (real, real);
begin
Result := PABCSystem.Random2(a, b);
if IsPT then exit;
InputList.Add(Result[0]);
InputList.Add(Result[1]);
end;
/// Возвращает кортеж из двух случайных символов в диапазоне от a до b
function Random2(a, b: char): (char, char);
begin
Result := PABCSystem.Random2(a, b);
if IsPT then exit;
InputList.Add(Result[0]);
InputList.Add(Result[1]);
end;
/// Возвращает кортеж из двух случайных целых в диапазоне
function Random2(diap: IntRange): (integer, integer);
begin
Result := PABCSystem.Random2(diap);
if IsPT then exit;
InputList.Add(Result[0]);
InputList.Add(Result[1]);
end;
/// Возвращает кортеж из двух случайных символов в диапазоне
function Random2(diap: CharRange): (char, char);
begin
Result := PABCSystem.Random2(diap);
if IsPT then exit;
InputList.Add(Result[0]);
InputList.Add(Result[1]);
end;
/// Возвращает кортеж из двух случайных вещественных в диапазоне
function Random2(diap: RealRange): (real, real);
begin
Result := PABCSystem.Random2(diap);
if IsPT then exit;
InputList.Add(Result[0]);
InputList.Add(Result[1]);
end;
/// Возвращает кортеж из трех случайных целых в диапазоне от a до b
function Random3(a, b: integer): (integer, integer, integer);
begin
Result := PABCSystem.Random3(a, b);
if IsPT then exit;
InputList.Add(Result[0]);
InputList.Add(Result[1]);
InputList.Add(Result[2]);
end;
/// Возвращает кортеж из трех случайных вещественных в диапазоне от a до b
function Random3(a, b: real): (real, real, real);
begin
Result := PABCSystem.Random3(a, b);
if IsPT then exit;
InputList.Add(Result[0]);
InputList.Add(Result[1]);
InputList.Add(Result[2]);
end;
/// Возвращает кортеж из трех случайных символов в диапазоне от a до b
function Random3(a, b: char): (char, char, char);
begin
Result := PABCSystem.Random3(a, b);
if IsPT then exit;
InputList.Add(Result[0]);
InputList.Add(Result[1]);
InputList.Add(Result[2]);
end;
/// Возвращает кортеж из трех случайных целых в диапазоне
function Random3(diap: IntRange): (integer, integer, integer);
begin
Result := PABCSystem.Random3(diap);
if IsPT then exit;
InputList.Add(Result[0]);
InputList.Add(Result[1]);
InputList.Add(Result[2]);
end;
/// Возвращает кортеж из трех случайных вещественных в диапазоне
function Random3(diap: RealRange): (real, real, real);
begin
Result := PABCSystem.Random3(diap);
if IsPT then exit;
InputList.Add(Result[0]);
InputList.Add(Result[1]);
InputList.Add(Result[2]);
end;
/// Возвращает кортеж из трех случайных символов в диапазоне
function Random3(diap: CharRange): (char, char, char);
begin
Result := PABCSystem.Random3(diap);
if IsPT then exit;
InputList.Add(Result[0]);
InputList.Add(Result[1]);
InputList.Add(Result[2]);
end;
/// Возвращает массив размера n, заполненный случайными целыми значениями в диапазоне от a до b
function ArrRandomInteger(n: integer; a: integer; b: integer): array of integer;
begin
Result := PABCSystem.ArrRandomInteger(n, a, b);
if IsPT then exit;
for var i:=0 to n-1 do
InputList.Add(Result[i]);
end;
/// Возвращает массив размера n, заполненный случайными целыми значениями в диапазоне от 0 до 100
function ArrRandomInteger(n: integer): array of integer := ArrRandomInteger(n,0,100);
/// Возвращает массив размера n, заполненный случайными вещественными значениями в диапазоне от a до b
function ArrRandomReal(n: integer; a: real; b: real): array of real;
begin
Result := PABCSystem.ArrRandomReal(n, a, b);
if IsPT then exit;
for var i:=0 to n-1 do
InputList.Add(Result[i]);
end;
/// Возвращает массив размера n, заполненный случайными вещественными значениями в диапазоне от 0 до 10
function ArrRandomReal(n: integer): array of real := ArrRandomReal(n,0,10);
/// Непонятно, зачем эти функции переопределять!!! Только Read и Random!!!
{/// Возвращает массив из count элементов, заполненных значениями gen(i)
function ArrGen<T>(count: integer; gen: integer->T): array of T;
begin
Result := PABCSystem.ArrGen(count,gen);
if IsPT then exit;
for var i:=0 to Result.Length-1 do
InputList.Add(Result[i]);
end;
/// Возвращает массив из count элементов, заполненных значениями gen(i), начиная с i=from
function ArrGen<T>(count: integer; gen: integer->T; from: integer): array of T;
begin
Result := PABCSystem.ArrGen(count,gen,from);
if IsPT then exit;
for var i:=0 to Result.Length-1 do
InputList.Add(Result[i]);
end;
/// Возвращает массив из count элементов, начинающихся с first, с функцией next перехода от предыдущего к следующему
function ArrGen<T>(count: integer; first: T; next: T->T): array of T;
begin
Result := PABCSystem.ArrGen(count,first,next);
if IsPT then exit;
for var i:=0 to Result.Length-1 do
InputList.Add(Result[i]);
end;
/// Возвращает массив из count элементов, начинающихся с first и second, с функцией next перехода от двух предыдущих к следующему
function ArrGen<T>(count: integer; first, second: T; next: (T,T) ->T): array of T;
begin
Result := PABCSystem.ArrGen(count,first,second,next);
if IsPT then exit;
for var i:=0 to Result.Length-1 do
InputList.Add(Result[i]);
end;}
{/// Возвращает массив из n целых, введенных с клавиатуры
function ReadArrInteger(n: integer): array of integer;
begin
Result := PABCSystem.ReadArrInteger(n); // и всё!!! Данные в InputList уже внесены!
end;
/// Возвращает массив из n вещественных, введенных с клавиатуры
function ReadArrReal(n: integer): array of real;
begin
Result := PABCSystem.ReadArrReal(n);
end;
/// Возвращает массив из n строк, введенных с клавиатуры
function ReadArrString(n: integer): array of string;
begin
Result := PABCSystem.ReadArrString(n);
end;
/// Возвращает матрицу m на n целых, введенных с клавиатуры
function ReadMatrInteger(m, n: integer): array [,] of integer;
begin
Result := PABCSystem.ReadMatrInteger(m,n); // и всё!!! Данные в InputList уже внесены!
end;
/// Возвращает матрицу m на n вещественных, введенных с клавиатуры
function ReadMatrReal(m, n: integer): array [,] of real;
begin
Result := PABCSystem.ReadMatrReal(m,n);
end;}
/// Возвращает двумерный массив размера m x n, заполненный случайными целыми значениями
function MatrRandomInteger(m: integer; n: integer; a: integer; b: integer): array [,] of integer;
begin
Result := PABCSystem.MatrRandomInteger(m,n,a,b);
if IsPT then exit;
foreach var x in Result.ElementsByRow do
InputList.Add(x);
end;
/// Возвращает двумерный массив размера m x n, заполненный случайными целыми значениями
function MatrRandomInteger(m: integer; n: integer): array [,] of integer := MatrRandomInteger(m,n,0,100);
/// Возвращает двумерный массив размера m x n, заполненный случайными вещественными значениями
function MatrRandomReal(m: integer; n: integer; a: real; b: real): array [,] of real;
begin
Result := PABCSystem.MatrRandomReal(m,n,a,b);
if IsPT then exit;
foreach var x in Result.ElementsByRow do
InputList.Add(x);
end;
/// Возвращает двумерный массив размера m x n, заполненный случайными вещественными значениями
function MatrRandomReal(m: integer; n: integer): array [,] of real := MatrRandomReal(m,n,0,10);
/// Возвращает двумерный массив размера m x n, заполненный элементами gen(i,j)
{function MatrGen<T>(m, n: integer; gen: (integer,integer)->T): array [,] of T;
begin
Result := PABCSystem.MatrGen(m,n,gen);
if IsPT then exit;
foreach var x in Result.ElementsByRow do
InputList.Add(x);
end;}
{function ReadString: string;
begin
Result := PABCSystem.ReadString;
if IsPT then exit;
InputList.Add(Result);
CreateNewLineBeforeMessage := False;
end;
function ReadlnString := ReadString;
function ReadString2 := (ReadString, ReadString);
function ReadlnString2 := ReadString2;}
/// Выводит приглашение к вводу и возвращает значение типа integer, введенное с клавиатуры
function ReadInteger(prompt: string): integer;
begin
Result := PABCSystem.ReadInteger(prompt);
if IsPT then exit;
OutputList.RemoveAt(OutputList.Count - 1);
OutputList.RemoveAt(OutputList.Count - 1);
CreateNewLineBeforeMessage := False;
end;
/// Выводит приглашение к вводу и возвращает значение типа integer, введенное с клавиатуры
function ReadlnInteger(prompt: string): integer;
begin
Result := PABCSystem.ReadlnInteger(prompt);
if IsPT then exit;
OutputList.RemoveAt(OutputList.Count - 1);
OutputList.RemoveAt(OutputList.Count - 1);
CreateNewLineBeforeMessage := False;
end;
/// Выводит приглашение к вводу и возвращает два значения типа integer, введенные с клавиатуры
function ReadInteger2(prompt: string): (integer, integer);
begin
Result := PABCSystem.ReadInteger2(prompt);
if IsPT then exit;
OutputList.RemoveAt(OutputList.Count - 1);
OutputList.RemoveAt(OutputList.Count - 1);
CreateNewLineBeforeMessage := False;
end;
///- procedure Print(a,b,...);
/// Выводит значения a,b,... на экран, после каждого значения выводит пробел
procedure Print(params args: array of object);
begin
foreach var ob in args do
begin
PABCSystem.Print(ob);
if not IsPT then
OutputList.RemoveAt(OutputList.Count - 1)
end;
CreateNewLineBeforeMessage := True;
end;
///- procedure Println(a,b,...);
/// Выводит значения a,b,... на экран, после каждого значения выводит пробел и переходит на новую строку
procedure Println(params args: array of object);
begin
Print(args);
Writeln;
if IsPT then exit;
CreateNewLineBeforeMessage := False;
end;
/// Выводит значение экран и выводит пробел
procedure Print(ob: object);
begin
PABCSystem.Print(ob);
if IsPT then exit;
OutputList.RemoveAt(OutputList.Count - 1);
CreateNewLineBeforeMessage := True;
end;
/// Выводит значение экран и выводит пробел
procedure Print(s: string);
begin
PABCSystem.Print(s);
if IsPT then exit;
OutputList.RemoveAt(OutputList.Count - 1);
CreateNewLineBeforeMessage := True;
end;
/// Выводит значение экран и выводит пробел
procedure Print(c: char);
begin
PABCSystem.Print(object(c));
if IsPT then exit;
OutputList.RemoveAt(OutputList.Count - 1);
CreateNewLineBeforeMessage := True;
end;
// конец переопределенных функций с заполнением ввода-вывода
function ToObjArray(a: array of integer) := a.Select(x -> object(x)).ToArray;
function ToObjArray(a: array of real) := a.Select(x -> object(x)).ToArray;
function ToObjArray(a: array of string) := a.Select(x -> object(x)).ToArray;
function ToObjArray(a: array of char) := a.Select(x -> object(x)).ToArray;
function ToObjArray(a: array of boolean) := a.Select(x -> object(x)).ToArray;
procedure CompareTypeWithOutput(params a: array of System.Type);
begin
TaskResult := Solved;
var mn := Min(a.Length, OutputList.Count);
for var i := 0 to mn - 1 do
if a[i] <> OutputList[i].GetType then
raise new OutputTypeException(i + 1, TypeToTypeName(a[i]), TypeName(OutputList[i]));
if a.Length <> OutputList.Count then
raise new OutputCountException(OutputList.Count, a.Length);
end;
/// Не меняет TaskResult если типы правильные
procedure CheckInputTypes(a: array of System.Type);
begin
// Несоответствие количества вводимых параметров
if a.Length <> InputList.Count then
raise new InputCountException(InputList.Count, a.Length);
for var i := 0 to a.Length - 1 do
if a[i] <> InputList[i].GetType then
raise new InputTypeException(i + 1, TypeToTypeName(a[i]), TypeName(InputList[i]));
end;
/// Синоним CheckInputTypes
procedure CheckInput(a: array of System.Type) := CheckInputTypes(a);
procedure CheckInputIsEmpty := CheckInputTypes(new System.Type[0]);
procedure CheckInputIsInitial;
begin
CheckInput(InitialInputList.ToArray);
end;
procedure CheckInput(seq: sequence of System.Type) := CheckInputTypes(seq.ToArray);
procedure CheckOutputAfterInitialSeq(seq: sequence of integer) := CheckOutputAfterInitial(ToObjArray(seq.ToArray));
procedure CheckOutputAfterInitialSeq(seq: sequence of real) := CheckOutputAfterInitial(ToObjArray(seq.ToArray));
procedure CheckOutputAfterInitialSeq(seq: sequence of string) := CheckOutputAfterInitial(ToObjArray(seq.ToArray));
procedure CheckOutputAfterInitialSeq(seq: sequence of boolean) := CheckOutputAfterInitial(ToObjArray(seq.ToArray));
procedure CheckOutputAfterInitialSeq(seq: sequence of char) := CheckOutputAfterInitial(ToObjArray(seq.ToArray));
procedure CheckOutputAfterInitialSeq(seq: sequence of object) := CheckOutputAfterInitial(seq.ToArray);
procedure CheckOutputAfterInitialSeq(seq: ObjectList) := CheckOutputAfterInitial(seq.lst.ToArray);
procedure ClearOutputListFromSpaces;
begin
OutputList := OutputList.Where(s -> (not (s is string)) or ((s as string) <> ' ')).ToList;
OutputList := OutputList.Where(s -> (not (s is char)) or ((char(s)) <> ' ')).ToList;
end;
procedure FilterOnlyNumbers;
begin
OutputList := OutputList.Where(x -> (x is integer) or (x is real) or (x is int64)).ToList;
end;
procedure FilterOnlyNumbersAndBools;
begin
OutputList := OutputList.Where(x -> (x is integer) or (x is real) or (x is int64) or (x is boolean)).ToList;
end;
function MsgColorCode(color: MessageColorT): char;
begin
Result := #65530; // Black
case color of
MsgColorGreen: Result := #65535;
MsgColorRed: Result := #65534;
MsgColorOrange: Result := #65533;
MsgColorMagenta: Result := #65532;
MsgColorGray: Result := #65531;
end;
end;
procedure ColoredMessage(msg: string; color: MessageColorT);
begin
if CreateNewLineBeforeMessage then
Console.WriteLine;
Console.WriteLine(MsgColorCode(color) + msg);
CreateNewLineBeforeMessage := False;
end;
procedure ColoredMessage(msg: string);
begin
if CreateNewLineBeforeMessage then
Console.WriteLine;
Console.WriteLine(MsgColorCode(MsgColorRed) + msg);
CreateNewLineBeforeMessage := False;
end;
/// Здесь проверялся RuntimeType - в новом CheckOutput RuntimeType вообще не проверяется
procedure CheckOutputOld(params arr: array of object);
begin
if (TaskResult = InitialTask) or (TaskResult = BadInitialTask) then
exit;
var mn := Min(arr.Length, OutputList.Count);
TaskResult := Solved;
// Несоответствие типов
for var i := 0 to mn - 1 do
begin
if (arr[i].GetType.Name = 'RuntimeType') and (arr[i] <> OutputList[i].GetType) then
raise new OutputTypeException(i + 1, TypeToTypeName(arr[i] as System.Type), TypeName(OutputList[i]))
else if (arr[i].GetType.Name <> 'RuntimeType') and (arr[i].GetType <> OutputList[i].GetType) then
raise new OutputTypeException(i + 1, TypeToTypeName(arr[i].GetType), TypeName(OutputList[i]));
end;
// Несоответствие количества выводимых параметров
if arr.Length <> OutputList.Count then
raise new OutputCountException(OutputList.Count, arr.Length);
// Несоответствие значений
for var i := 0 to mn - 1 do
if (arr[i].GetType.Name <> 'RuntimeType') and not CompareValues(arr[i], OutputList[i]) then
begin
TaskResult := BadSolution; // Если типы разные, то IOErrorSolution
exit;
end;
end;
// Добавим сюда проверку типов RuntimeType
procedure CheckOutput(params arr: array of object);
begin
// TaskResult = InitialTask - ничего выводить не надо
// TaskResult = BadInitialTask - потом будет выведено исключение, что часть изначальных данных удалена
if (TaskResult = InitialTask) or (TaskResult = BadInitialTask) then
exit;
var mn := Min(arr.Length, OutputList.Count);
// Несоответствие типов или значений
var ind := -1;
for var i := 0 to mn - 1 do
begin
// Если типы не совпадают
if (arr[i].GetType.Name <> 'RuntimeType') and (arr[i].GetType <> OutputList[i].GetType) or
(arr[i].GetType.Name = 'RuntimeType') and (arr[i] <> OutputList[i].GetType)
then
begin
ind := i; // то запомнить индекс первого несовпадения
if ind > InitialOutputList.Count then
ColoredMessage('Часть выведенных данных правильная',MsgColorGray);
raise new OutputTypeException(i + 1, TypeToTypeName(arr[i].GetType), TypeName(OutputList[i]));
end;
// Если значения не совпадают (если задан маркер типа, то проверка значений пропускается)
if (arr[i].GetType.Name <> 'RuntimeType') and not CompareValues(arr[i], OutputList[i]) then
begin
ind := i; // то запомнить индекс первого несовпадения
if ind > InitialOutputList.Count then
begin
ColoredMessage('Часть выведенных данных правильная',MsgColorGray);
ColoredMessage($'Элемент {i + 1}: ожидалось значение {arr[i]}, а выведено {OutputList[i]}',MsgColorGray);
end;
TaskResult := BadSolution;
exit;
end;
end;
if ind = -1 then
ind := mn;
if arr.Length <> OutputList.Count then
begin
if (ind = mn) and (ind<>0) then
ColoredMessage('Все выведенные данные правильны',MsgColorGray)
else if ind > 0 then
ColoredMessage('Часть выведенных данных правильная',MsgColorGray);
raise new OutputCountException(OutputList.Count, arr.Length);
end;
TaskResult := Solved;
end;
procedure CheckOutputAfterInitial(params arr: array of object);
begin
if (TaskResult = InitialTask) or (TaskResult = BadInitialTask) then
exit;
// Если мы попали сюда, то OutputList.Count >= InitialOutputList.Count
var mn := Min(arr.Length, OutputList.Count - InitialOutputList.Count);
var i0 := InitialOutputList.Count;
var ind := -1;
for var i := i0 to i0 + mn - 1 do
begin
// Если типы не совпадают
if (arr[i-i0].GetType.Name <> 'RuntimeType') and (arr[i-i0].GetType <> OutputList[i].GetType) or
(arr[i-i0].GetType.Name = 'RuntimeType') and (arr[i-i0] <> OutputList[i].GetType)
then
begin
ind := i; // то запомнить индекс первого несовпадения
if ind >= InitialOutputList.Count then
ColoredMessage('Часть выведенных данных правильная',MsgColorGray);
raise new OutputTypeException(i + 1, TypeToTypeName(arr[i-i0].GetType), TypeName(OutputList[i]));
end;
// Если значения не совпадают (если задан маркер типа, то проверка значений пропускается)
if (arr[i-i0].GetType.Name <> 'RuntimeType') and not CompareValues(arr[i-i0], OutputList[i]) then
begin
ind := i; // то запомнить индекс первого несовпадения
if ind > InitialOutputList.Count then
begin
ColoredMessage('Часть выведенных данных правильная',MsgColorGray);
ColoredMessage($'Элемент {i + 1}: ожидалось значение {arr[i-i0]}, а выведено {OutputList[i]}',MsgColorGray);
end;
TaskResult := BadSolution;
exit;
end;
end;
if ind = -1 then
ind := mn;
if arr.Length <> OutputList.Count - InitialOutputList.Count then
begin
if (ind = mn) and (ind<>i0) then
ColoredMessage('Все выведенные данные правильны',MsgColorGray)
else if ind > 0 then
ColoredMessage('Часть выведенных данных правильная',MsgColorGray);
raise new OutputCountException(OutputList.Count, arr.Length + i0);
end;
TaskResult := Solved;
end;
procedure CheckOutputAfterInitialOld(params arr: array of object); // проверить только то, что после исходного вывода
begin
if (TaskResult = InitialTask) or (TaskResult = BadInitialTask) then
exit;
// Здесь всегда OutputList.Count > InitialOutputList.Count
// Если arr.Length > OutputList.Count - InitialOutputList.Count, то мы не вывели часть данных
// Если arr.Length < OutputList.Count - InitialOutputList.Count, то мы вывели больше чем надо
if arr.Length <> OutputList.Count - InitialOutputList.Count then
raise new OutputCountException(OutputList.Count, InitialOutputList.Count + arr.Length);
TaskResult := Solved;
// Несоответствие типов
var a := OutputList.Count - arr.Length;
for var i := a to OutputList.Count - 1 do
begin
if (arr[i-a].GetType.Name = 'RuntimeType') and (arr[i-a] <> OutputList[i].GetType) then
raise new OutputTypeException(i + 1, TypeToTypeName(arr[i-a] as System.Type), TypeName(OutputList[i]))
else if (arr[i-a].GetType.Name <> 'RuntimeType') and (arr[i-a].GetType <> OutputList[i].GetType) then
raise new OutputTypeException(i + 1, TypeName(arr[i-a]), TypeName(OutputList[i]));
end;
// Несоответствие значений
for var i := a to OutputList.Count - 1 do
if (arr[i-a].GetType.Name <> 'RuntimeType') and not CompareValues(arr[i-a], OutputList[i]) then
begin
TaskResult := BadSolution; // Если типы разные, то IOErrorSolution
exit;
end;
end;
procedure CheckOutputSeq(a: sequence of integer) := CheckOutput(ToObjArray(a.ToArray));
procedure CheckOutputSeq(a: sequence of real) := CheckOutput(ToObjArray(a.ToArray));
procedure CheckOutputSeq(a: sequence of string) := CheckOutput(ToObjArray(a.ToArray));
procedure CheckOutputSeq(a: sequence of char) := CheckOutput(ToObjArray(a.ToArray));
procedure CheckOutputSeq(a: sequence of boolean) := CheckOutput(ToObjArray(a.ToArray));
procedure CheckOutputSeq(a: sequence of object) := CheckOutput(a.ToArray);
procedure CheckOutputSeq(a: ObjectList) := CheckOutput(a.lst.ToArray);
procedure CheckOutputSeq(a: sequence of word) := CheckOutputSeq(a.Select(x->object(x)));
procedure CheckOutputNew(params arr: array of object) := CheckOutput(arr);
procedure CheckOutputSeqNew(a: sequence of integer) := CheckOutputSeq(a);
procedure CheckOutputSeqNew(a: sequence of real) := CheckOutputSeq(a);
procedure CheckOutputSeqNew(a: sequence of string) := CheckOutputSeq(a);
procedure CheckOutputSeqNew(a: sequence of char) := CheckOutputSeq(a);
procedure CheckOutputSeqNew(a: sequence of boolean) := CheckOutputSeq(a);
procedure CheckOutputSeqNew(a: sequence of object) := CheckOutputSeq(a);
procedure CheckOutputSeqNew(a: sequence of word) := CheckOutputSeq(a);
procedure CheckOutputSeqNew(a: ObjectList) := CheckOutputSeq(a);
procedure CheckOutputSeqOld(a: sequence of integer) := CheckOutputOld(ToObjArray(a.ToArray));
procedure CheckOutputSeqOld(a: sequence of real) := CheckOutputOld(ToObjArray(a.ToArray));
procedure CheckOutputSeqOld(a: sequence of string) := CheckOutputOld(ToObjArray(a.ToArray));
procedure CheckOutputSeqOld(a: sequence of char) := CheckOutputOld(ToObjArray(a.ToArray));
procedure CheckOutputSeqOld(a: sequence of boolean) := CheckOutputOld(ToObjArray(a.ToArray));
procedure CheckOutputSeqOld(a: sequence of object) := CheckOutputOld(a.ToArray);
procedure CheckOutputSeqOld(a: ObjectList) := CheckOutputOld(a.lst.ToArray);
procedure CheckOutputString(str: string);
function Char2Str(c: char): string;
begin
if (c = #10) or (c = #13) then
Result := '''ПереходНаНовуюСтроку'''
else Result := '''' + c + '''';
end;
begin
if (TaskResult = InitialTask) or (TaskResult = BadInitialTask) then
exit;
var ostr := OutputString.ToString;
var mn := Min(str.Length, ostr.Length);
var ind := -1;
for var i := 1 to mn do
begin
if str[i] <> ostr[i] then
begin
ind := i;
ColoredMessage($'Элемент {i}: ожидался символ {Char2Str(str[i])}, а выведен символ {Char2Str(ostr[i])}',MsgColorGray);
TaskResult := BadSolution;
exit;
end;
end;
if ind = -1 then
ind := mn;
if str.Length <> ostr.Length then
begin
if (ind = mn) and (ind<>0) then
ColoredMessage('Все выведенные данные правильны',MsgColorGray)
else if ind > 0 then
ColoredMessage('Часть выведенных данных правильная',MsgColorGray);
raise new OutputCountException(ostr.Length, str.Length);
end;
TaskResult := Solved;
end;
type
IntAr = array of integer;
RealAr = array of real;
IntAr2 = array [,] of integer;
RealAr2 = array [,] of real;
function FlattenElement(x: object): List<object>;
begin
var lst := new List<object>;
if x is IntAr (var iarr) then
lst.AddRange(iarr.Select(x -> object(x)))
else if x is RealAr (var rarr) then
lst.AddRange(rarr.Select(x -> object(x)))
else if x is IntAr2 (var iarr) then
lst.AddRange(iarr.ElementsByRow.Select(x -> object(x)))
else if x is RealAr2 (var rarr) then
lst.AddRange(rarr.ElementsByRow.Select(x -> object(x)))
else if x is List<integer> (var larr) then
lst.AddRange(larr.Select(x -> object(x)))
else if x is List<real> (var lrarr) then
lst.AddRange(lrarr.Select(x -> object(x)))
else lst.Add(x);
Result := lst;
end;
procedure FlattenOutput;
begin
// если в OutputList массивы, вытянуть их в единый список
OutputList := OutputList.SelectMany(x -> FlattenElement(x)).ToList;
end;
function NValues(n: integer): string;
begin
case n of
1: Result := n + ' значение';
2, 3, 4: Result := n + ' значения';
5..100000: Result := n + ' значений';
end;
end;
{=========================================================}
{ Итоговые функции для проверки решения }
{=========================================================}
procedure RobotCheckSolution;
begin
TaskResult := BadSolution;
var t := System.Type.GetType('RobotField.RobotField');
if t<>nil then
begin
TaskResultInfo := 'Robot';
var f := t.GetField('RobField',System.Reflection.BindingFlags.Public or System.Reflection.BindingFlags.Static);
var IsSol := f.FieldType.GetMethod('IsSolution');
var bool := IsSol.Invoke(f.GetValue(nil),nil);
if boolean(bool) then
TaskResult := Solved;
// RobField.TaskName
var RBTaskNameInfo := f.FieldType.GetField('TaskName');
var v := string(RBTaskNameInfo.GetValue(f.GetValue(nil)));
// Добавлять RB к имени задания если его там нет
if not v.ToLower.StartsWith('rb') then
v := v.Insert(0,'RB');
TaskName := v;
end;
end;
procedure DrawmanCheckSolution;
begin
TaskResult := BadSolution;
var t := System.Type.GetType('DrawManField.DrawManField');
if t<>nil then
begin
TaskResultInfo := 'Drawman';
var f := t.GetField('DMField',System.Reflection.BindingFlags.Public or System.Reflection.BindingFlags.Static);
var IsSol := f.FieldType.GetMethod('IsSolution');
var bool := IsSol.Invoke(f.GetValue(nil),nil);
if boolean(bool) then
TaskResult := Solved;
// DMField.TaskName
var DMTaskNameInfo := f.FieldType.GetField('TaskName');
var v := string(DMTaskNameInfo.GetValue(f.GetValue(nil)));
// Добавлять DM к имени задания если его там нет
if not v.ToLower.StartsWith('dm') then
v := v.Insert(0,'DM');
TaskName := v;
end;
end;
// Вызов PT4.PT4.__FinalizeModule__ отражением
procedure PT4CheckSolution;
begin
var t := System.Type.GetType('PT4.PT4');
if t<>nil then
begin
var meth := t.GetMethod('__FinalizeModule__',System.Reflection.BindingFlags.Public or System.Reflection.BindingFlags.Static);
if meth <> nil then
meth.Invoke(nil,nil);
//
var f := t.GetField('TaskName',System.Reflection.BindingFlags.Public or System.Reflection.BindingFlags.Static);
TaskName := string(f.GetValue(nil));
end;
end;
// Вызов PT4.PT4.GetSolutionInfo отражением
function GetSolutionInfoPT4: string;
begin
var t := System.Type.GetType('PT4.PT4');
if t<>nil then
begin
var meth := t.GetMethod('GetSolutionInfo',System.Reflection.BindingFlags.Public or System.Reflection.BindingFlags.Static);
if meth <> nil then
Result := string(meth.Invoke(nil,nil))
else Result := '';
end;
end;
procedure CalcPT4Result(info: string; var TaskResult: TaskStatus; var TaskResultInfo: string);
// info - строка, возвращаемая GetSolutionInfoPT4
function HasSubstr(s_ru, s_en: string): boolean;
begin
result := false;
if Pos(s_ru, info) > 0 then
result := true
else if Pos(s_en, info) > 0 then
result := true
end;
function TypeNamePT(s: string): string;
begin
result := '';
case s of
'логического типа', 'of logical type':
result := 'boolean';
'целого типа', 'of integer type':
result := 'integer';
'вещественного типа', 'of real-number type':
result := 'real';
'символьного типа', 'of character type':
result := 'char';
'строкового типа', 'of string type':
result := 'string';
end;
if result = '' then
if s.startswith('типа') then
result := copy(s, 6, 100)
else if s.startswith('of') then
begin
delete(s, 1, 3);
delete(s, length(s) - 4, 100);
result := s;
end;
end;
procedure ExtractParts(var p1, p2, p3: string);
begin
var m := Regex.Match(info, 'Для ввода (.*)-го элемента \((.*)\) использована переменная (.*).');
if m.Success then
begin
p1 := m.Groups[1].Value;
p2 := TypeNamePT(m.Groups[2].Value);
p3 := TypeNamePT(m.Groups[3].Value);
exit;
end;
m := Regex.Match(info, 'A variable (.*) is used for input of data item with the order number (.*) \((.*)\).');
if m.Success then
begin
p1 := m.Groups[2].Value;
p2 := TypeNamePT(m.Groups[3].Value);
p3 := TypeNamePT(m.Groups[1].Value);
exit;
end;
m := Regex.Match(info, 'Для вывода (.*)-го элемента \((.*)\) использовано выражение (.*).');
if m.Success then
begin
p1 := m.Groups[1].Value;
p2 := TypeNamePT(m.Groups[2].Value);
p3 := TypeNamePT(m.Groups[3].Value);
exit;
end;
m := Regex.Match(info, 'An expression (.*) is used for output of data item with the order number (.*) \((.*)\).');
if m.Success then
begin
p1 := m.Groups[2].Value;
p2 := TypeNamePT(m.Groups[3].Value);
p3 := TypeNamePT(m.Groups[1].Value);
exit;
end;
m := Regex.Match(info, 'Количество выведенных данных: (.*) \(из (.*)\).');
if m.Success then
begin
p1 := m.Groups[1].Value;
p2 := m.Groups[2].Value;
p3 := '';
exit;
end;
m := Regex.Match(info, 'The program has output (.*) data item\(s\) \(the amount of the required items is (.*)\).');
if m.Success then
begin
p1 := m.Groups[1].Value;
p2 := m.Groups[2].Value;
p3 := '';
exit;
end;
m := Regex.Match(info, 'Количество прочитанных данных: (.*) \(из (.*)\).');
if m.Success then
begin
p1 := m.Groups[1].Value;
p2 := m.Groups[2].Value;
p3 := '';
exit;
end;
m := Regex.Match(info, 'The program has used (.*) input data item\(s\) \(the amount of the required items is (.*)\).');
if m.Success then
begin
p1 := m.Groups[1].Value;
p2 := m.Groups[2].Value;
p3 := '';
exit;
end;
end;
begin
// Если мы сюда зашли, то TaskResult уже под контролем. Но она и так должна быть TaskStatus.InitialTaskPT4
TaskResult := TaskStatus.InitialTaskPT4;
TaskResultInfo := 'PT4';
var p1, p2, p3: string;
if info = '' then
exit;
if HasSubstr('Задание выполнено', 'The task is solved') then
//ColoredMessage('Задание выполнено', MsgColorGreen)
TaskResult := TaskStatus.Solved
else if HasSubstr('Ошибочное решение', 'Wrong solution') then
//ColoredMessage('Неверное решение')
TaskResult := TaskStatus.BadSolution
else if HasSubstr('Неверно указан тип при выводе результатов', 'Invalid type is used for an output data item') then
begin
ExtractParts(p1, p2, p3);
TaskResult := TaskStatus.IOError;
TaskResultInfo := $'OutputType({p1},{p2},{p3})';
//ColoredMessage($'Ошибка вывода. При выводе {p1}-го элемента типа {p2} выведено значение типа {p3}');
end
else if HasSubstr('Выведены не все результирующие данные', 'Some data are not output') then
begin
ExtractParts(p1, p2, p3);
TaskResult := TaskStatus.IOError;
TaskResultInfo := $'OutputCount({p1},{p2})';
//ColoredMessage($'Выведено {p1}, а требуется вывести {p2}', MsgColorOrange);
end
else if HasSubstr('Неверно указан тип при вводе исходных данных', 'Invalid type is used for an input data item') then
begin
ExtractParts(p1, p2, p3);
TaskResult := TaskStatus.IOError;
TaskResultInfo := $'InputType({p1},{p2},{p3})';
//ColoredMessage($'Ошибка ввода. При вводе {p1}-го элемента типа {p2} использована переменная типа {p3}');
end
else if HasSubstr('Введены не все требуемые исходные данные', 'Some required data are not input.') then
begin
ExtractParts(p1, p2, p3);
TaskResult := TaskStatus.IOError;
TaskResultInfo := $'InputCount({p1},{p2})';
//ColoredMessage($'Введено {p1}, а требуется ввести {p2}', MsgColorOrange);
end
else if HasSubstr('Запуск с правильным вводом данных', 'Correct data input') then
begin
TaskResult := TaskStatus.PartialSolution;
//ColoredMessage('Запуск с правильным вводом данных', MsgColorGray)
end;
{else
ColoredMessage('PT4: '+info.Replace(#13#10, ' ').TrimStart().TrimEnd('.',' '));}
end;
function ConvertTaskName(tn: string): string;
begin
var TName := tn;
// Если есть номер с подчеркиванием в начале, то отбросить его
var ind := TName.IndexOf('_');
if (ind >= 0) and TName[1].IsDigit then // Значит, в начале - номер, он служит лишь для упорядочения файлов
TName := TName.Remove(0,ind + 1);
if TName.ToLower in TaskNamesMap then
TName := TaskNamesMap[TName.ToLower];
Result := TName;
end;
procedure CheckMyPT;
begin
if CheckTask = nil then
exit;
var TName := TaskName;
try
TName := ConvertTaskName(TaskName);
CheckTask(TName);
// Если это задача из задачника, то результат будет NotUnderControl. И дальше необходимо это преобразовывать
case TaskResult of
Solved: ColoredMessage('Задание выполнено', MsgColorGreen);
BadSolution: ColoredMessage('Неверное решение');
InitialTask: ;
BadInitialTask: ColoredMessage('Вы удалили часть кода - восстановите его!', MsgColorMagenta);
end;
except
on e: OutputTypeException do
begin
//Writeln(#10+$'Неверно указан тип при выводе данных');
ColoredMessage($'Ошибка вывода. При выводе {e.n}-го элемента типа {e.ExpectedType} выведено значение типа {e.ActualType}');
end;
on e: OutputCountException do
begin
if e.Count = 0 then
ColoredMessage($'Требуется вывести {NValues(e.n)}', MsgColorGray)
else ColoredMessage($'Выведено {NValues(e.Count)}, а требуется вывести {e.n}', MsgColorOrange);
end;
on e: OutputCount2Exception do
begin
if e.Count = 0 then
ColoredMessage($'Требуется вывести по крайней мере {NValues(e.i)}', MsgColorGray)
else ColoredMessage($'Выведено {NValues(e.Count)}, а требуется вывести по крайней мере {e.i}', MsgColorOrange);
end;
on e: InputTypeException do
begin
//Writeln(#10+$'Неверно указан тип при вводе исходных данных');
ColoredMessage($'Ошибка ввода. При вводе {e.n}-го элемента типа {e.ExpectedType} использована переменная типа {e.ActualType}');
end;
on e: InputCountException do
begin
if e.Count = 0 then
ColoredMessage($'Требуется ввести {NValues(e.n)}', MsgColorGray)
else if e.n <> 0 then
ColoredMessage($'Введено {NValues(e.Count)}, а требуется ввести {e.n}', MsgColorOrange)
else ColoredMessage($'Введено {NValues(e.Count)}, хотя ничего вводить не требуется', MsgColorOrange);
end;
on e: InputCount2Exception do
begin
if e.Count = 0 then
ColoredMessage($'Требуется ввести по крайней мере {NValues(e.i)}', MsgColorGray)
else ColoredMessage($'Введено {NValues(e.Count)}, а требуется ввести по крайней мере {e.i}', MsgColorOrange);
end;
end;
// Для задачника надо вызывать процедуру __FinalizeModule__ из модуля PT4 jnhf;tybtv, а в модуле PT4 эту процедуру тогда не вызывть
// Для задачника в CheckTaskPT надо сказать, что проверяется задача из задачника. И выводить на экран ничего не надо - только в базу.
TaskResultInfo := TaskException.Info;
var TaskPlatform := 'LT';
// Теперь тщательно проверяем задачник и исполнителей
if IsPT then
begin
PT4CheckSolution;
TName := TaskName;
var info := GetSolutionInfoPT4;
CalcPT4Result(info,TaskResult,TaskResultInfo);
TaskPlatform := 'PT';
end
else if IsRobot then
begin
RobotCheckSolution;
TName := TaskName;
TaskPlatform := 'RB';
end
else if IsDrawman then
begin
DrawmanCheckSolution;
TName := TaskName;
TaskPlatform := 'DM';
end;
// Хотелось бы писать в БД для Робота и др. имя задания в Task
if WriteInfoCallBack<>nil then
WriteInfoCallBack(LessonName,TName,TaskPlatform,TaskResult,TaskResultInfo);
end;
procedure LoadLightPTInfo;
begin
try
var lines := ReadAllLines(lightptname);
foreach var line in lines do
begin
if line.Trim = '' then
continue;
if LessonName = '' then
LessonName := line.ToWords.First // первое слово
else begin
var (name1,name2) := Regex.Split(line,'->');
TaskNamesMap[name1.Trim.ToLower] := name2.Trim;
end;
end;
if LessonName = '' then
begin
// Имя текущей папки. Плохо - в lightpt забыли написать имя урока
//var ttt := ExtractFileDir(System.Environment.GetCommandLineArgs[0]);
var ttt := ExpandFileName('.');
var LastDir := ttt.ToWords(System.IO.Path.DirectorySeparatorChar).LastOrDefault;
// Каталог может содержать пробелы. Брать первое слово
if LastDir<>nil then
LessonName := LastDir.ToWords.First;
end;
except
end;
end;
{=========================================================}
{ Процедуры для записи в базы данных }
{=========================================================}
procedure WriteInfoToRemoteDatabase(auth: string; LessonName, TaskName, TaskPlatform, TaskResult, AdditionalInfo: string);
begin
// Считать логин пароль из auth
var data := System.IO.File.ReadAllBytes(auth);
var arr := Decrypt(data).Split(#10);
var login,pass: string;
if arr.Length >= 2 then
begin
login := arr[0];
pass := arr[1];
// Теперь как-то записать в БД информацию
var User := new ServerAccessProvider(ServerAddr);
var t2 := User.SendPostRequest(login, pass, LessonName, TaskName, TaskPlatform, TaskResult, AdditionalInfo);
var v := t2.Result;
v := v;
//Console.WriteLine(v);
end;
end;
procedure WriteInfoToDatabases(LessonName,TaskName,TaskPlatform: string; TaskResult: TaskStatus; AdditionalInfo: string := '');
begin
try
System.IO.File.AppendAllText('db.txt', $'{LessonName} {TaskName} {dateTime.Now.ToString(''u'')} {TaskResult.ToString} {AdditionalInfo}' + #10);
var auth := FindAuthDat();
var args := System.Environment.GetCommandLineArgs;
if (auth <> '') and (args.Length = 3) and (args[2].ToLower = 'true') then
// Есть проблема паузы при плохой сети
WriteInfoToRemoteDatabase(auth,LessonName,TaskName,TaskPlatform,TaskResult.ToString, AdditionalInfo);
except
on e: System.AggregateException do
begin
foreach var x in e.InnerExceptions do
if x is HTTPRequestException then
ColoredMessage(x.InnerException?.Message??'',MsgColorGray)
else ColoredMessage(x.Message,MsgColorGray);
end;
on e: Exception do
ColoredMessage(e.Message,MsgColorGray);
end;
end;
{===========================================================}
{ Переопределенные подсистемы ввода и вывода }
{===========================================================}
type
IOLightSystem = class(__ReadSignalOISystem)
public
procedure write(obj: object); override;
begin
inherited write(obj);
OutputString += _ObjectToString(obj);
OutputList += obj;
CreateNewLineBeforeMessage := True;
end;
procedure writeln; override;
begin
inherited writeln;
OutputString += NewLine;
CreateNewLineBeforeMessage := False;
end;
function ReadLine: string; override;
begin
Result := inherited ReadLine;
InputList.Add(Result);
CreateNewLineBeforeMessage := False;
end;
procedure readln; override;
begin
inherited readln;
CreateNewLineBeforeMessage := False;
end;
procedure read(var x: integer); override;
begin
inherited Read(x);
InputList.Add(x);
CreateNewLineBeforeMessage := True;
end;
procedure read(var x: real); override;
begin
inherited Read(x);
InputList.Add(x);
CreateNewLineBeforeMessage := True;
end;
procedure read(var x: char); override;
begin
inherited Read(x);
InputList.Add(x);
CreateNewLineBeforeMessage := True;
end;
procedure read(var x: string); override;
begin
inherited Read(x);
InputList.Add(x);
CreateNewLineBeforeMessage := True;
end;
procedure read(var x: byte); override;
begin
inherited Read(x);
InputList.Add(x);
CreateNewLineBeforeMessage := True;
end;
procedure read(var x: shortint); override;
begin
inherited Read(x);
InputList.Add(x);
CreateNewLineBeforeMessage := True;
end;
procedure read(var x: smallint); override;
begin
inherited Read(x);
InputList.Add(x);
CreateNewLineBeforeMessage := True;
end;
procedure read(var x: word); override;
begin
inherited Read(x);
InputList.Add(x);
CreateNewLineBeforeMessage := True;
end;
procedure read(var x: longword); override;
begin
inherited Read(x);
InputList.Add(x);
CreateNewLineBeforeMessage := True;
end;
procedure read(var x: int64); override;
begin
inherited Read(x);
InputList.Add(x);
CreateNewLineBeforeMessage := True;
end;
procedure read(var x: uint64); override;
begin
inherited Read(x);
InputList.Add(x);
CreateNewLineBeforeMessage := True;
end;
procedure read(var x: single); override;
begin
inherited Read(x);
InputList.Add(x);
CreateNewLineBeforeMessage := True;
end;
procedure read(var x: boolean); override;
begin
inherited Read(x);
InputList.Add(x);
CreateNewLineBeforeMessage := True;
end;
procedure read(var x: BigInteger); override;
begin
inherited Read(x);
InputList.Add(x);
CreateNewLineBeforeMessage := True;
end;
end;
initialization
// Если LightPT добавляется в конец uses, то ее секция инициализации вызывается первой
// В этом случае ввод-вывод обязательно переключается, но потом он перекрывается и в основной программе не срабатывает
// Но в CheckPT используется ColoredMessage, которая выводит с помощью Console.WriteLine - ей всё равно
var tn := TypeName(CurrentIOSystem);
if (tn = 'IOStandardSystem') or (tn = '__ReadSignalOISystem') or (tn = 'IOGraphABCSystem') then
CurrentIOSystem := new IOLightSystem;
WriteInfoCallBack := WriteInfoToDatabases;
// Расшифровка LightPT.dat
LoadLightPTInfo;
finalization
CheckMyPT
end. |
unit MVVM.Bindings.LiveBindings;
interface
uses
System.Classes,
System.TypInfo,
System.SysUtils,
System.Generics.Collections,
System.RTTI,
System.Bindings.Expression, System.Bindings.Helper,
System.Bindings.EvalProtocol, System.Bindings.Outputs,
Data.DB,
System.Actions,
Spring.Collections,
MVVM.Bindings.Commands,
MVVM.Interfaces,
MVVM.Types,
MVVM.Bindings;
const
STRATEGY_NAME = 'LIVEBINDINGS';
type
TStrategy_LiveBindings = class(TBindingStrategyBase)
private type
TInternalBindindExpression = class(TBindingDefault)
private
FExpression: TBindingExpression;
public
constructor Create(ABindingStrategy: IBindingStrategy; const InputScopes: array of IScope; const BindExprStr: string; const OutputScopes: array of IScope; const OutputExpr: string; const OutputConverter: IValueRefConverter; Manager: TBindingManager = nil; Options: TBindings.TCreateOptions = [coNotifyOutput]); reintroduce;
destructor Destroy; override;
function IsObjectInBinding(const AObject: TObject): Boolean; override;
procedure OnBindingAssignedValueEvent(AssignValueRec: TBindingAssignValueRec; const AValue: TValue);
property Expression: TBindingExpression read FExpression;
end;
private
class var
FObjectListLinkers: IDictionary<TClass, TProc<PTypeInfo, TComponent, TEnumerable<TObject>>>;
FObjectDataSetLinkers: IDictionary<TClass, TProc<TDataSet, TComponent>>;
private
var
FEnabled: Boolean;
class constructor CreateC;
class destructor DestroyC;
protected
function GetEnabled: Boolean; override;
procedure SetEnabled(const AValue: Boolean); override;
procedure DoEnableAll;
procedure DoDisableAll;
function ExistBindingCommandActionFor(AObject: TContainedAction; out ACommand: IBinding): Boolean;
function InternalBindCollection(AServiceType: PTypeInfo; AComponent: TComponent; ACollection: TEnumerable<TObject>): Boolean;
function InternalBindDataSet(ADataSet: TDataSet; AComponent: TComponent): Boolean;
public
constructor Create; override;
destructor Destroy; override;
// function GetPlatformBindActionCommandType: TBindingCommandClass; override;
procedure Notify(const AObject: TObject; const APropertyName: string = ''); overload; override;
procedure Bind(const ASource: TObject; const ASourcePropertyPath: String; const ATarget: TObject; const ATargetPropertyPath: String; const ADirection: EBindDirection = EBindDirection.OneWay; const AFlags: EBindFlags = []; const AValueConverterClass: TValueConverterClass = nil; const AExtraParams: TBindExtraParams = []); overload; override;
procedure Bind(const ASources: TSourcePairArray; const ASourceExpresion: String; const ATarget: TObject; const ATargetAlias: String; const ATargetPropertyPath: String; const AFlags: EBindFlags = []; const AExtraParams: TBindExtraParams = []); overload; override;
procedure BindCollection(AServiceType: PTypeInfo; const ACollection: TEnumerable<TObject>; const ATarget: ICollectionViewProvider; const ATemplate: TDataTemplateClass); override;
// DataSets
procedure BindDataSet(const ADataSet: TDataSet; const ATarget: ICollectionViewProvider; const ATemplate: TDataTemplateClass = nil); override;
function ClearDataSetBindingFromComponent(ATarget: TComponent): Boolean;
// - Components
procedure BindDataSetFieldToProperty(ADataSet: TDataSet; const AFieldName: String; const ATarget: TComponent; const ATargetPropertyPath: String); overload; override;
procedure BindDataSetFieldToProperty(ADataSet: TDataSet; const AFieldName: String; const ATarget: TComponent; const ATargetPropertyPath: String; const AValueConverterClass: TValueConverterClass); overload; override;
procedure BindDataSetFieldToProperty(ADataSet: TDataSet; const AFieldName: String; const ATarget: TComponent; const ATargetPropertyPath: String; const ACustomFormat: String); overload; override;
// -- Combobox
procedure BindDataSetToCombobox(ADataSet: TDataSet; ATarget: TComponent; const AField: String; const AOnlyFillValues: Boolean = True); overload; override;
procedure BindDataSetToCombobox(ADataSet: TDataSet; ATarget: TComponent; const AField: String; const ACustomFormat: String; const AOnlyFillValues: Boolean = True); overload; override;
// -- ListBox
procedure BindDataSetToListBox(ADataSet: TDataSet; ATarget: TComponent; const AField: String; const ACustomDisplayExpression: string; const AOnlyFillValues: Boolean = True); overload; override;
procedure BindDataSetToListBox(ADataSet: TDataSet; ATarget: TComponent; const ALinks: array of TListBoxConversionData; const AOnlyFillValues: Boolean = True); overload; override;
// -- ListView
procedure BindDataSetToListView(ADataSet: TDataSet; ATarget: TComponent; const AField: String; const ACustomDisplayExpression: String; const AOnlyFillValues: Boolean = True); overload; override;
procedure BindDataSetToListView(ADataSet: TDataSet; ATarget: TComponent; const ALinks: array of TListViewConversionData; const AOnlyFillValues: Boolean = True); overload; override;
procedure BindDataSetAppendFieldToListView(ADataSet: TDataSet; ATarget: TComponent; const ALink: TListViewConversionData; const AOnlyFillValues: Boolean = True); overload; override;
// -- Grids
procedure BindDataSetToGrid(ADataSet: TDataSet; ATarget: TComponent); overload; override;
procedure BindDataSetToGrid(ADataSet: TDataSet; ATarget: TComponent; const AColumnLinks: array of TGridColumnTemplate); overload; override;
// Actions
procedure BindAction(AAction: IBindableAction); overload; override;
// Unbinds
procedure Unbind(const ASource: TObject); override;
class procedure RegisterClassObjectListCollectionBinder(const AClass: TClass; AProcedure: TProc < PTypeInfo, TComponent, TEnumerable < TObject >> ); static;
class procedure RegisterClassDataSetCollectionBinder(const AClass: TClass; AProcedure: TProc<TDataSet, TComponent>); static;
property Enabled: Boolean read GetEnabled write SetEnabled;
end;
implementation
uses
Data.Bind.Grid,
Data.Bind.Components,
Data.Bind.DBScope,
Data.Bind.Controls,
Data.Bind.ObjectScope,
MVVM.Utils,
Spring;
{ TStrategy_LiveBindings }
procedure TStrategy_LiveBindings.Bind(const ASource: TObject; const ASourcePropertyPath: String; const ATarget: TObject; const ATargetPropertyPath: String; const ADirection: EBindDirection; const AFlags: EBindFlags; const AValueConverterClass: TValueConverterClass; const AExtraParams: TBindExtraParams);
var
LSrcProperty, LDstProperty: String;
lAssocInput, lAssocOutput: IScope;
lManaged1, lManaged2: IBindingDefault;
LToAdd1, LToAdd2: IBinding;
LOptions: TBindings.TCreateOptions;
begin
LOptions := [coNotifyOutput];
if not(EBindFlag.DontApply in AFlags) then
LOptions := LOptions + [coEvaluate];
lAssocInput := TBindings.CreateAssociationScope([Associate(ASource, 'Src')]);
lAssocOutput := TBindings.CreateAssociationScope([Associate(ATarget, 'Dst')]);
if not(EBindFlag.UsesExpressions in AFlags) then
begin
LSrcProperty := 'Src.' + ASourcePropertyPath;
LDstProperty := 'Dst.' + ATargetPropertyPath;
end
else
begin
LSrcProperty := ASourcePropertyPath;
LDstProperty := ATargetPropertyPath;
end;
LToAdd1 := TInternalBindindExpression.Create(Self, [lAssocInput], LSrcProperty, [lAssocOutput], LDstProperty, nil, nil, LOptions);
Supports(LToAdd1, IBindingDefault, lManaged1);
// Free Event
lManaged1.SetManager(ASource);
lManaged1.SetFreeNotification(ASource);
lManaged1.SetManager(ATarget);
lManaged1.SetFreeNotification(ATarget);
AddBinding(LToAdd1);
// Bidirectional?
if ADirection = EBindDirection.TwoWay then
begin
lAssocInput := TBindings.CreateAssociationScope([Associate(ATarget, 'Src')]);
lAssocOutput := TBindings.CreateAssociationScope([Associate(ASource, 'Dst')]);
if not(EBindFlag.UsesExpressions in AFlags) then
begin
LSrcProperty := 'Src.' + ATargetPropertyPath;
LDstProperty := 'Dst.' + ASourcePropertyPath;
end
else
begin
LSrcProperty := ATargetPropertyPath;
LDstProperty := ASourcePropertyPath;
end;
LToAdd2 := TInternalBindindExpression.Create(Self, [lAssocInput], LSrcProperty, [lAssocOutput], LDstProperty, nil, nil, LOptions);
Supports(LToAdd2, IBindingDefault, lManaged2);
// Free Event
lManaged2.SetManager(ASource);
lManaged2.SetFreeNotification(ASource);
lManaged2.SetManager(ATarget);
lManaged2.SetFreeNotification(ATarget);
AddBinding(LToAdd2);
end;
end;
procedure TStrategy_LiveBindings.Bind(const ASources: TSourcePairArray; const ASourceExpresion: String; const ATarget: TObject; const ATargetAlias: String; const ATargetPropertyPath: String; const AFlags: EBindFlags; const AExtraParams: TBindExtraParams);
var
LSrcProperty, LDstProperty: String;
lAssocInput, lAssocOutput: IScope;
lManaged: IBindingDefault;
LToAdd: IBinding;
LOptions: TBindings.TCreateOptions;
LArrayAsociacion: array of TBindingAssociation;
I, LCnt: Integer;
begin
LOptions := [coNotifyOutput];
if not(DontApply in AFlags) then
LOptions := LOptions + [coEvaluate];
LCnt := Length(ASources);
SetLength(LArrayAsociacion, LCnt);
for I := 0 to LCnt - 1 do
begin
LArrayAsociacion[I] := Associate(ASources[I].Source, ASources[I].Alias);
end;
lAssocInput := TBindings.CreateAssociationScope(LArrayAsociacion);
lAssocOutput := TBindings.CreateAssociationScope([Associate(ATarget, ATargetAlias)]);
LSrcProperty := ASourceExpresion;
LDstProperty := ATargetPropertyPath;
LToAdd := TInternalBindindExpression.Create(Self, [lAssocInput], LSrcProperty, [lAssocOutput], LDstProperty, nil, nil, LOptions);
Supports(LToAdd, IBindingDefault, lManaged);
// asociacion de eventos de fin
for I := 0 to LCnt - 1 do
begin
lManaged.SetFreeNotification(ASources[I].Source);
end;
lManaged.SetManager(ATarget);
lManaged.SetFreeNotification(ATarget);
FBindings.Add(LToAdd);
end;
procedure TStrategy_LiveBindings.BindAction(AAction: IBindableAction);
var
LCommand: IBinding;
LObject: TContainedAction;
begin
Guard.CheckNotNull(AAction, '<BindAction> (Param=AAction) cannot be null');
LObject := AAction as TContainedAction;
// if already Exists the binded object we reuse the command
if not ExistBindingCommandActionFor(LObject, LCommand) then
LCommand := TBindingCommandAction.Create(LObject);
AAction.Binding := LCommand;
AddBinding(LCommand);
end;
procedure TStrategy_LiveBindings.BindCollection(AServiceType: PTypeInfo; const ACollection: TEnumerable<TObject>; const ATarget: ICollectionViewProvider; const ATemplate: TDataTemplateClass);
var
LView: ICollectionView;
begin
Guard.CheckNotNull(ATarget, '<BindCollection> (Param=ATarget) cannot be null');
Guard.CheckNotNull(ATarget, '<BindCollection> (Param=ATemplate) cannot be null');
LView := ATarget.GetCollectionView;
if (LView = nil) then
raise EBindError.CreateFmt('Function %s.GetCollectionView cannot return nil', [TObject(ATarget).QualifiedClassName]);
LView.Template := ATemplate;
LView.Source := TCollectionSource(ACollection);
if not InternalBindCollection(AServiceType, LView.Component, ACollection) then
raise EBindError.CreateFmt('Component %s has not registered a binder', [TObject(ATarget).QualifiedClassName]);
end;
procedure TStrategy_LiveBindings.BindDataSet(const ADataSet: TDataSet; const ATarget: ICollectionViewProvider; const ATemplate: TDataTemplateClass);
var
LView: ICollectionView;
begin
Guard.CheckNotNull(ATarget, '<BindDataSet> (Param=ADataSet) cannot be null');
Guard.CheckNotNull(ATarget, '<BindDataSet> (Param=ATarget) cannot be null');
Guard.CheckNotNull(ATarget, '<BindDataSet> (Param=ATemplate) cannot be null');
LView := ATarget.GetCollectionView;
if (LView = nil) then
raise EBindError.CreateFmt('Function %s.GetCollectionView cannot return nil', [TObject(ATarget).QualifiedClassName]);
LView.Template := ATemplate;
if not InternalBindDataSet(ADataSet, LView.Component) then
raise EBindError.CreateFmt('Component %s has not registered a binder', [TObject(ATarget).QualifiedClassName]);
end;
procedure TStrategy_LiveBindings.BindDataSetAppendFieldToListView(ADataSet: TDataSet; ATarget: TComponent; const ALink: TListViewConversionData; const AOnlyFillValues: Boolean);
var
LFiller: TLinkFillControlToField;
LLinker: TLinkListControlToField;
LSource: TBindSourceDB;
I, J : Integer;
LFound : Boolean;
LItem : TCollectionItem;
LItem1: TFormatExpressionItem;
begin
//si hay link lo usamos
LFiller := nil;
LLinker := nil;
LFound := False;
for I := 0 to ATarget.ComponentCount - 1 do
begin
if (ATarget.Components[I] is TBindSourceDB) then
begin
for J := 0 to ATarget.Components[I].ComponentCount - 1 do
begin
if (ATarget.Components[I].Components[J] is TLinkFillControlToField) then
begin
LFiller := ATarget.Components[I].Components[J] as TLinkFillControlToField;
LFiller.Active := False;
LFound := True;
Break;
end;
if (ATarget.Components[I].Components[J] is TLinkListControlToField) then
begin
LLinker := ATarget.Components[I].Components[J] as TLinkListControlToField;
LLinker.Active := False;
LFound := True;
Break;
end;
end;
if LFound then
break;
end;
end;
if Assigned(LFiller) then
begin
LItem1 := LFiller.FillExpressions.AddExpression;
LItem1.SourceMemberName := ALink.DataSetField;
LItem1.ControlMemberName := ALink.ListViewField;
if not ALink.CustomFormat.IsEmpty then
LItem1.CustomFormat := ALink.CustomFormat;
LFiller.Active := True;
Exit;
end;
if Assigned(LLinker) then
begin
LItem1 := LLinker.FillExpressions.AddExpression;
LItem1.SourceMemberName := ALink.DataSetField;
LItem1.ControlMemberName := ALink.ListViewField;
if not ALink.CustomFormat.IsEmpty then
LItem1.CustomFormat := ALink.CustomFormat;
LLinker.Active := True;
end;
end;
procedure TStrategy_LiveBindings.BindDataSetFieldToProperty(ADataSet: TDataSet; const AFieldName: String; const ATarget: TComponent; const ATargetPropertyPath: String);
var
LinkPropertyToField: TLinkPropertyToField;
LSource: TBindSourceDB;
begin
LSource := TBindSourceDB.Create(nil); //TO-DO
LSource.DataSet := ADataSet;
LinkPropertyToField := TLinkPropertyToField.Create(nil); //TO-DO
LinkPropertyToField.Category := 'Quick Bindings';
LinkPropertyToField.DataSource := LSource;
LinkPropertyToField.FieldName := AFieldName;
LinkPropertyToField.Component := ATarget;
LinkPropertyToField.ComponentProperty := ATargetPropertyPath;
LinkPropertyToField.Active := True;
end;
procedure TStrategy_LiveBindings.BindDataSetFieldToProperty(ADataSet: TDataSet; const AFieldName: String; const ATarget: TComponent; const ATargetPropertyPath: String; const AValueConverterClass: TValueConverterClass);
begin
raise Exception.Create('Method not suitable for this kind of binding (LiveBindings)');
end;
procedure TStrategy_LiveBindings.BindDataSetFieldToProperty(ADataSet: TDataSet; const AFieldName: String; const ATarget: TComponent; const ATargetPropertyPath, ACustomFormat: String);
var
LinkPropertyToField: TLinkPropertyToField;
LSource: TBindSourceDB;
begin
LSource := TBindSourceDB.Create(nil); //TO-DO
LSource.DataSet := ADataSet;
LinkPropertyToField := TLinkPropertyToField.Create(nil); //TO-DO
LinkPropertyToField.Category := 'Quick Bindings';
LinkPropertyToField.DataSource := LSource;
LinkPropertyToField.FieldName := AFieldName;
LinkPropertyToField.Component := ATarget;
LinkPropertyToField.CustomFormat := ACustomFormat;
LinkPropertyToField.ComponentProperty := ATargetPropertyPath;
LinkPropertyToField.Active := True;
end;
procedure TStrategy_LiveBindings.BindDataSetToCombobox(ADataSet: TDataSet; ATarget: TComponent; const AField, ACustomFormat: String; const AOnlyFillValues: Boolean);
var
LFiller: TLinkFillControlToField;
LLinker: TLinkListControlToField;
LSource: TBindSourceDB;
I : Integer;
begin
for I := 0 to ATarget.ComponentCount - 1 do
begin
if (ATarget.Components[I] is TBindSourceDB) then
begin
ATarget.Components[I].Free;
Break;
end;
end;
LSource := TBindSourceDB.Create(ATarget);
LSource.DataSet := ADataSet;
if AOnlyFillValues then
begin
LFiller := TLinkFillControlToField.Create(LSource);
LFiller.Category := 'Quick Bindings';
LFiller.Control := ATarget;
LFiller.Track := True;
LFiller.FillDataSource := LSource;
LFiller.FillDisplayFieldName := AField;
if not ACustomFormat.IsEmpty then
LFiller.FillDisplayCustomFormat := ACustomFormat;
LFiller.AutoFill := True;
LFiller.Active := True;
end
else begin
LLinker := TLinkListControlToField.Create(LSource);
LLinker.Category := 'Quick Bindings';
LLinker.Control := ATarget;
LLinker.DataSource := LSource;
LLinker.FieldName := AField;
if not ACustomFormat.IsEmpty then
LLinker.CustomFormat := ACustomFormat;
LLinker.Active := True;
end;
end;
procedure TStrategy_LiveBindings.BindDataSetToCombobox(ADataSet: TDataSet; ATarget: TComponent; const AField: String; const AOnlyFillValues: Boolean);
var
LFiller: TLinkFillControlToField;
LLinker: TLinkListControlToField;
LSource: TBindSourceDB;
I : Integer;
begin
for I := 0 to ATarget.ComponentCount - 1 do
begin
if (ATarget.Components[I] is TBindSourceDB) then
begin
ATarget.Components[I].Free;
Break;
end;
end;
LSource := TBindSourceDB.Create(ATarget);
LSource.DataSet := ADataSet;
if AOnlyFillValues then
begin
LFiller := TLinkFillControlToField.Create(LSource);
LFiller.Category := 'Quick Bindings';
LFiller.Control := ATarget;
LFiller.Track := True;
LFiller.FillDataSource := LSource;
LFiller.FillDisplayFieldName := AField;
LFiller.AutoFill := True;
LFiller.Active := True;
end
else begin
LLinker := TLinkListControlToField.Create(LSource);
LLinker.Category := 'Quick Bindings';
LLinker.Control := ATarget;
LLinker.DataSource := LSource;
LLinker.FieldName := AField;
LLinker.Active := True;
end;
end;
procedure TStrategy_LiveBindings.BindDataSetToGrid(ADataSet: TDataSet; ATarget: TComponent; const AColumnLinks: array of TGridColumnTemplate);
var
LGridLinker: TLinkGridToDataSource;
LColumnLinker: TLinkGridToDataSourceColumn;
LSource: TBindSourceDB;
I, J: Integer;
LExisteS, LExisteL: Boolean;
begin
Guard.CheckNotNull(ATarget, '<BindDataSet> (Param=ADataSet) cannot be null');
Guard.CheckNotNull(ATarget, '<BindDataSet> (Param=ATarget) cannot be null');
// mirar si existe o no un linkado previo
LExisteS := False;
LExisteL := False;
for I := 0 to ATarget.ComponentCount - 1 do
begin
if (ATarget.Components[I] is TBindSourceDB) then
begin
LExisteS := True;
LSource := ATarget.Components[I] as TBindSourceDB;
for J := 0 to ATarget.Components[I].ComponentCount - 1 do
begin
if (ATarget.Components[I].Components[J] is TLinkGridToDataSource) then
begin
LGridLinker := ATarget.Components[I].Components[J] as TLinkGridToDataSource;
LGridLinker.Active := False;
LExisteL := True;
Break;
end;
end;
if LExisteL then
Break;
end;
end;
if not LExisteS then
begin
LSource := TBindSourceDB.Create(ATarget);
LSource.DataSet := ADataSet;
end;
if not LExisteL then
begin
LGridLinker := TLinkGridToDataSource.Create(LSource);
LGridLinker.Category := 'Quick Bindings';
LGridLinker.GridControl := ATarget;
LGridLinker.DataSource := LSource;
end;
for I := Low(AColumnLinks) to High(AColumnLinks) do
begin
LColumnLinker := LGridLinker.Columns.Add;
LColumnLinker.MemberName := AColumnLinks[I].DataSetField;
LColumnLinker.Header := AColumnLinks[I].HeaderText;
LColumnLinker.ReadOnly := AColumnLinks[I].ReadOnly;
LColumnLinker.Width := AColumnLinks[I].Width;
LColumnLinker.Visible := True;
LColumnLinker.CustomFormat := AColumnLinks[I].CustomFormat;
LColumnLinker.CustomParse := AColumnLinks[I].CustomParse;
LColumnLinker.ColumnStyle := AColumnLinks[I].ColumnStyle;
end;
LGridLinker.Active := True;
end;
procedure TStrategy_LiveBindings.BindDataSetToListBox(ADataSet: TDataSet; ATarget: TComponent; const ALinks: array of TListBoxConversionData; const AOnlyFillValues: Boolean);
var
LFiller: TLinkFillControlToField;
LLinker: TLinkListControlToField;
LSource: TBindSourceDB;
I : Integer;
LItem : TCollectionItem;
LItem1: TFormatExpressionItem;
begin
ClearDataSetBindingFromComponent(ATarget);
LSource := TBindSourceDB.Create(ATarget);
LSource.DataSet := ADataSet;
if AOnlyFillValues then
begin
LFiller := TLinkFillControlToField.Create(LSource);
LFiller.Category := 'Quick Bindings';
LFiller.Control := ATarget;
LFiller.Track := True;
LFiller.FillDataSource := LSource;
for I := Low(ALinks) to High(ALinks) do
begin
LItem1 := LFiller.FillExpressions.AddExpression;
LItem1.SourceMemberName := ALinks[I].DataSetField;
LItem1.ControlMemberName := ALinks[I].ListBoxField;
if not ALinks[I].CustomFormat.IsEmpty then
LItem1.CustomFormat := ALinks[I].CustomFormat;
end;
LFiller.AutoFill := True;
LFiller.Active := True;
end
else begin
LLinker := TLinkListControlToField.Create(LSource);
LLinker.Category := 'Quick Bindings';
LLinker.Control := ATarget;
LLinker.DataSource := LSource;
//LLinker.FieldName := AField;
for I := Low(ALinks) to High(ALinks) do
begin
LItem1 := LLinker.FillExpressions.AddExpression;
LItem1.SourceMemberName := ALinks[I].DataSetField;
LItem1.ControlMemberName := ALinks[I].ListBoxField;
if not ALinks[I].CustomFormat.IsEmpty then
LItem1.CustomFormat := ALinks[I].CustomFormat;
end;
LLinker.Active := True;
end;
end;
procedure TStrategy_LiveBindings.BindDataSetToListView(ADataSet: TDataSet; ATarget: TComponent; const AField, ACustomDisplayExpression: String; const AOnlyFillValues: Boolean);
var
LFiller: TLinkFillControlToField;
LLinker: TLinkListControlToField;
LSource: TBindSourceDB;
I : Integer;
begin
ClearDataSetBindingFromComponent(ATarget);
LSource := TBindSourceDB.Create(ATarget);
LSource.DataSet := ADataSet;
if AOnlyFillValues then
begin
LFiller := TLinkFillControlToField.Create(LSource);
LFiller.Category := 'Quick Bindings';
LFiller.Control := ATarget;
LFiller.Track := True;
LFiller.FillDataSource := LSource;
LFiller.FillDisplayFieldName := AField;
if not ACustomDisplayExpression.IsEmpty then
LFiller.FillDisplayCustomFormat := ACustomDisplayExpression;
LFiller.AutoFill := True;
LFiller.Active := True;
end
else begin
LLinker := TLinkListControlToField.Create(LSource);
LLinker.Category := 'Quick Bindings';
LLinker.Control := ATarget;
LLinker.DataSource := LSource;
LLinker.FieldName := AField;
if not ACustomDisplayExpression.IsEmpty then
LLinker.CustomFormat := ACustomDisplayExpression;
LLinker.Active := True;
end;
end;
procedure TStrategy_LiveBindings.BindDataSetToListView(ADataSet: TDataSet; ATarget: TComponent; const ALinks: array of TListViewConversionData; const AOnlyFillValues: Boolean);
var
LFiller: TLinkFillControlToField;
LLinker: TLinkListControlToField;
LSource: TBindSourceDB;
I : Integer;
LItem : TCollectionItem;
LItem1: TFormatExpressionItem;
begin
ClearDataSetBindingFromComponent(ATarget);
LSource := TBindSourceDB.Create(ATarget);
LSource.DataSet := ADataSet;
if AOnlyFillValues then
begin
LFiller := TLinkFillControlToField.Create(LSource);
LFiller.Category := 'Quick Bindings';
LFiller.Control := ATarget;
LFiller.Track := True;
LFiller.FillDataSource := LSource;
for I := Low(ALinks) to High(ALinks) do
begin
LItem1 := LFiller.FillExpressions.AddExpression;
LItem1.SourceMemberName := ALinks[I].DataSetField;
LItem1.ControlMemberName := ALinks[I].ListViewField;
if not ALinks[I].CustomFormat.IsEmpty then
LItem1.CustomFormat := ALinks[I].CustomFormat;
end;
LFiller.AutoFill := True;
LFiller.Active := True;
end
else begin
LLinker := TLinkListControlToField.Create(LSource);
LLinker.Category := 'Quick Bindings';
LLinker.DataSource := LSource;
for I := Low(ALinks) to High(ALinks) do
begin
if ALinks[I].IsKeyField then
begin
LLinker.FieldName := ALinks[I].DataSetField;
LLinker.CustomFormat := ALinks[I].CustomFormat;
Break;
end
end;
LLinker.Control := ATarget;
for I := Low(ALinks) to High(ALinks) do
begin
if not ALinks[I].IsKeyField then
begin
LItem1 := LLinker.FillExpressions.AddExpression;
LItem1.SourceMemberName := ALinks[I].DataSetField;
LItem1.ControlMemberName := ALinks[I].ListViewField;
if not ALinks[I].CustomFormat.IsEmpty then
LItem1.CustomFormat := ALinks[I].CustomFormat;
end;
end;
LLinker.Active := True;
end;
end;
procedure TStrategy_LiveBindings.BindDataSetToListBox(ADataSet: TDataSet; ATarget: TComponent; const AField, ACustomDisplayExpression: string; const AOnlyFillValues: Boolean);
var
LFiller: TLinkFillControlToField;
LLinker: TLinkListControlToField;
LSource: TBindSourceDB;
begin
ClearDataSetBindingFromComponent(ATarget);
LSource := TBindSourceDB.Create(ATarget);
LSource.DataSet := ADataSet;
if AOnlyFillValues then
begin
LFiller := TLinkFillControlToField.Create(LSource);
LFiller.Category := 'Quick Bindings';
LFiller.Control := ATarget;
LFiller.Track := True;
LFiller.FillDataSource := LSource;
LFiller.FillDisplayFieldName := AField;
if not ACustomDisplayExpression.IsEmpty then
LFiller.FillDisplayCustomFormat := ACustomDisplayExpression;
LFiller.AutoFill := True;
LFiller.Active := True;
end
else begin
LLinker := TLinkListControlToField.Create(LSource);
LLinker.Category := 'Quick Bindings';
LLinker.Control := ATarget;
LLinker.DataSource := LSource;
LLinker.FieldName := AField;
if not ACustomDisplayExpression.IsEmpty then
LLinker.CustomFormat := ACustomDisplayExpression;
LLinker.Active := True;
end;
end;
procedure TStrategy_LiveBindings.BindDataSetToGrid(ADataSet: TDataSet; ATarget: TComponent);
var
LLinker: TLinkGridToDataSource;
LSource: TBindSourceDB;
begin
Guard.CheckNotNull(ATarget, '<BindDataSet> (Param=ADataSet) cannot be null');
Guard.CheckNotNull(ATarget, '<BindDataSet> (Param=ATarget) cannot be null');
ClearDataSetBindingFromComponent(ATarget);
LSource := TBindSourceDB.Create(ATarget);
LSource.DataSet := ADataSet;
LLinker := TLinkGridToDataSource.Create(LSource);
LLinker.Category := 'Quick Bindings';
LLinker.GridControl := ATarget;
LLinker.DataSource := LSource;
LLinker.Active := True;
end;
function TStrategy_LiveBindings.ClearDataSetBindingFromComponent(ATarget: TComponent): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 to ATarget.ComponentCount - 1 do
begin
if (ATarget.Components[I] is TBindSourceDB) then
begin
ATarget.Components[I].Free;
Exit(True);
end;
end;
end;
constructor TStrategy_LiveBindings.Create;
begin
inherited;
end;
class constructor TStrategy_LiveBindings.CreateC;
begin
FObjectListLinkers := TCollections.CreateDictionary<TClass, TProc<PTypeInfo, TComponent, TEnumerable<TObject>>>;
FObjectDataSetLinkers := TCollections.CreateDictionary<TClass, TProc<TDataSet, TComponent>>;
end;
destructor TStrategy_LiveBindings.Destroy;
begin
ClearBindings;
inherited;
end;
class destructor TStrategy_LiveBindings.DestroyC;
begin
FObjectListLinkers := nil;
FObjectDataSetLinkers := nil;
end;
procedure TStrategy_LiveBindings.DoDisableAll;
var
I: IBinding; // TBindingBase
begin
AdquireWrite;
try
for I in FBindings do
begin
I.Enabled := False;
end;
finally
ReleaseWrite;
end;
end;
procedure TStrategy_LiveBindings.DoEnableAll;
var
I: IBinding; // TBindingBase
begin
AdquireWrite;
try
for I in FBindings do
begin
I.Enabled := True;
end;
finally
ReleaseWrite;
end;
end;
function TStrategy_LiveBindings.ExistBindingCommandActionFor(AObject: TContainedAction; out ACommand: IBinding): Boolean;
var
I: IBinding;
LData: TBindingCommandAction;
begin
Result := False;
AdquireRead;
try
for I in FBindings do
begin
LData := I as TBindingCommandAction;
if LData.Command = AObject then
Exit(True);
end;
finally
ReleaseRead;
end;
end;
function TStrategy_LiveBindings.GetEnabled: Boolean;
begin
Result := FEnabled
end;
// function TStrategy_LiveBindings.GetPlatformBindActionCommandType: TBindingCommandClass;
// begin
//
// end;
function TStrategy_LiveBindings.InternalBindCollection(AServiceType: PTypeInfo; AComponent: TComponent; ACollection: TEnumerable<TObject>): Boolean;
var
LClass: TClass;
begin
Result := False;
for LClass in FObjectListLinkers.Keys do
begin
if AComponent.ClassType.InheritsFrom(LClass) then
begin
FObjectListLinkers[LClass](AServiceType, AComponent, ACollection);
Exit(True);
end;
end;
end;
function TStrategy_LiveBindings.InternalBindDataSet(ADataSet: TDataSet; AComponent: TComponent): Boolean;
var
// LProc: TProc<TDataSet, TComponent>;
LClass: TClass;
begin
Result := False;
for LClass in FObjectDataSetLinkers.Keys do
begin
if AComponent.ClassType.InheritsFrom(LClass) then
begin
FObjectDataSetLinkers[LClass](ADataSet, AComponent);
Exit(True);
end;
end;
end;
procedure TStrategy_LiveBindings.Notify(const AObject: TObject; const APropertyName: string);
begin
TBindings.Notify(AObject, APropertyName);
end;
class procedure TStrategy_LiveBindings.RegisterClassDataSetCollectionBinder(const AClass: TClass; AProcedure: TProc<TDataSet, TComponent>);
begin
FObjectDataSetLinkers[AClass] := AProcedure;
end;
class procedure TStrategy_LiveBindings.RegisterClassObjectListCollectionBinder(const AClass: TClass; AProcedure: TProc < PTypeInfo, TComponent, TEnumerable < TObject >> );
begin
FObjectListLinkers[AClass] := AProcedure;
end;
procedure TStrategy_LiveBindings.SetEnabled(const AValue: Boolean);
begin
if FEnabled <> AValue then
begin
FEnabled := AValue;
case FEnabled of
True:
begin
DoEnableAll;
end;
False:
begin
DoDisableAll;
end;
end;
end;
end;
procedure TStrategy_LiveBindings.Unbind(const ASource: TObject);
var
LBindingsToRemove: IEnumerable<IBinding>;
// LBinding: IBinding;
begin
AdquireWrite;
try
LBindingsToRemove := FBindings.Where(
function(const ABinding: IBinding): Boolean // TBindingBase
begin
Result := ABinding.IsObjectInBinding(ASource)
end);
FBindings.RemoveRange(LBindingsToRemove.ToArray);
// FBindings.RemoveAll(function (const ABinding: TBindingBase): Boolean
// begin
// Result := ABinding.IsObjectInBinding(ASource)
// end
// );
finally
ReleaseWrite
end;
// for LBinding in LBindingsToRemove do
// LBinding.Free;
end;
{ TStrategy_LiveBindings.TInternalBindindExpression }
constructor TStrategy_LiveBindings.TInternalBindindExpression.Create(ABindingStrategy: IBindingStrategy; const InputScopes: array of IScope; const BindExprStr: string; const OutputScopes: array of IScope; const OutputExpr: string; const OutputConverter: IValueRefConverter; Manager: TBindingManager; Options: TBindings.TCreateOptions);
begin
inherited Create(ABindingStrategy);
FExpression := TBindings.CreateManagedBinding(InputScopes, BindExprStr, OutputScopes, OutputExpr, nil, nil, Options);
FExpression.OnAssignedValueEvent := OnBindingAssignedValueEvent;
end;
destructor TStrategy_LiveBindings.TInternalBindindExpression.Destroy;
begin
//Utils.IdeDebugMsg('<TStrategy_LiveBindings.TInternalBindindExpression.Destroy> ID: ' + ID);
TBindings.RemoveBinding(FExpression);
// FExpression.Free;
inherited;
end;
function TStrategy_LiveBindings.TInternalBindindExpression.IsObjectInBinding(const AObject: TObject): Boolean;
begin
Result := FExpression.Associations.ContainsKey(AObject);
end;
procedure TStrategy_LiveBindings.TInternalBindindExpression.OnBindingAssignedValueEvent(AssignValueRec: TBindingAssignValueRec; const AValue: TValue);
begin
DoOnBindingAssignedValue(AssignValueRec.OutObj, AssignValueRec.OutProp, AValue);
end;
initialization
TBindingManager.RegisterBindingStrategy(STRATEGY_NAME, TStrategy_LiveBindings);
end.
|
namespace Filefind;
{ RemObjects Oxygene Sample application
This application lists all files in the current directory and
in all subdirectories of current directory, that satisfy to the given mask.
}
interface
uses System.*;
type
ConsoleApp = static class
private
class method Shorten(aFolderName: String): String;
class method ProcessFolder(aFolderName, aMask: String);
public
class method Main(args: array of String);
end;
implementation
class method ConsoleApp.ProcessFolder(aFolderName, aMask: string);
var
lFiles: array of String;
begin
Console.CursorLeft := 0;
Console.Write(Shorten(aFolderName));
try
lFiles := Directory.GetFiles(aFolderName, aMask);
for each f in lFiles do begin
Console.WriteLine();
Console.WriteLine(' '+Path.GetFileName(f));
end;
lFiles := Directory.GetDirectories(aFolderName);
for each d in lFiles do begin
ProcessFolder(d, aMask);
end;
except
on E: DirectoryNotFoundException, UnauthorizedAccessException do begin
//Console.WriteLine(' '+E.Message);
end;
end;
end;
class method ConsoleApp.Main(args: array of string);
begin
Console.WriteLine('RemObjects Oxygene Filefind utility.');
Console.WriteLine('Free and unsupported, use at your own risk.');
Console.WriteLine();
if length(args) = 1 then begin
ProcessFolder(System.Environment.CurrentDirectory, args[0]);
Console.WriteLine();
Console.WriteLine('Done.');
Console.WriteLine();
end
else begin
Console.WriteLine('Syntax');
Console.WriteLine(' Filefind <Mask>');
Console.WriteLine();
exit;
end;
end;
class method ConsoleApp.Shorten(aFolderName: string): string;
begin
var lWidth := Console.WindowWidth-1;
if aFolderName.Length > lWidth then begin
var lStart := aFolderName.IndexOf(Path.DirectorySeparatorChar, 2);
if (lStart > 40) or (lStart = -1) then lStart := aFolderName.IndexOf(Path.DirectorySeparatorChar);
result := aFolderName.Substring(1, lStart)+'...'+Path.DirectorySeparatorChar;
result := result+aFolderName.Substring(lWidth-result.Length);
end
else result := aFolderName;
if result.Length < lWidth then
result := result.PadRight(lWidth);
end;
end. |
// Copyright (c) 2009, ConTEXT Project Ltd
// 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 ConTEXT Project Ltd 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
unit fFileList;
interface
{$I ConTEXT.inc}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, uMultiLanguage;
type
TfmFileList = class(TForm)
lb: TListBox;
btnOK: TButton;
btnCancel: TButton;
eName: TEdit;
procedure FormShow(Sender: TObject);
procedure eNameChange(Sender: TObject);
procedure eNameKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure btnOKClick(Sender: TObject);
procedure lbClick(Sender: TObject);
private
FSelectedEditor :TObject;
procedure FilesToList;
procedure IncPosition(Count:integer);
procedure DecPosition(Count:integer);
procedure SelectedItemToEdit;
public
property SelectedEditor :TObject read FSelectedEditor write FSelectedEditor;
end;
implementation
{$R *.DFM}
uses
fMain, fEditor;
////////////////////////////////////////////////////////////////////////////////////////////
// Functions
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmFileList.FilesToList;
var
n :integer;
ed :TfmEditor;
begin
n:=0;
while fmMain.Enum(ed,n) do begin
lb.Items.AddObject(ExtractFileName(ed.FileName),ed);
end;
end;
//------------------------------------------------------------------------------------------
procedure TfmFileList.SelectedItemToEdit;
begin
if (lb.ItemIndex<>-1) then begin
eName.Text:=lb.Items[lb.ItemIndex];
eName.SelectAll;
end;
end;
//------------------------------------------------------------------------------------------
procedure TfmFileList.IncPosition(Count:integer);
begin
if (lb.ItemIndex<lb.Items.Count-Count) then
lb.ItemIndex:=lb.ItemIndex+Count
else
lb.ItemIndex:=lb.Items.Count-1;
SelectedItemToEdit;
end;
//------------------------------------------------------------------------------------------
procedure TfmFileList.DecPosition(Count:integer);
begin
if (lb.ItemIndex>Count-1) then
lb.ItemIndex:=lb.ItemIndex-Count
else
lb.ItemIndex:=0;
SelectedItemToEdit;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Buttons
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmFileList.btnOKClick(Sender: TObject);
begin
if (lb.ItemIndex<>-1) then
SelectedEditor:=lb.Items.Objects[lb.ItemIndex];
ModalResult:=mrOK;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Events
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmFileList.eNameChange(Sender: TObject);
var
n :integer;
s :string;
found :boolean;
begin
s:=UpperCase(eName.Text);
found:=FALSE;
if (Length(s)>0) then begin
n:=0;
while (n<lb.Items.Count) do begin
if (UpperCase(Copy(lb.Items[n],1,Length(s)))=s) then begin
lb.ItemIndex:=n;
found:=TRUE;
BREAK;
end;
inc(n);
end;
end;
if not found then
lb.ItemIndex:=-1;
end;
//------------------------------------------------------------------------------------------
procedure TfmFileList.eNameKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Shift=[]) then begin
case Key of
VK_DOWN:
begin
IncPosition(1);
Key:=0;
end;
VK_UP:
begin
DecPosition(1);
Key:=0;
end;
VK_NEXT:
begin
IncPosition((lb.Height div lb.ItemHeight)-1);
Key:=0;
end;
VK_PRIOR:
begin
DecPosition((lb.Height div lb.ItemHeight)-1);
Key:=0;
end;
end;
end;
end;
//------------------------------------------------------------------------------------------
procedure TfmFileList.lbClick(Sender: TObject);
begin
SelectedItemToEdit;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Form events
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmFileList.FormShow(Sender: TObject);
begin
mlApplyLanguageToForm(SELF, Name);
FilesToList;
if Assigned(SelectedEditor) then begin
lb.ItemIndex:=lb.Items.IndexOfObject(SelectedEditor);
SelectedItemToEdit;
end;
end;
//------------------------------------------------------------------------------------------
end.
|
// Copyright (c) 2009, ConTEXT Project Ltd
// 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 ConTEXT Project Ltd 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
unit uRuler;
interface
{$I ConTEXT.inc}
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, RsRuler;
type
TRuler = class
private
fRelativeXPos: integer;
fLeftIndent: integer;
procedure SetRelativeXPos(const Value: integer);
procedure SetLeftIndent(const Value: integer);
private
fRuler: TRsRuler;
fCurrentX: integer;
fCharWidth: integer;
fCurrentXOffset: integer;
fEditor: TForm;
procedure SetCharWidth(const Value: integer);
procedure SetCurrentX(const Value: integer);
procedure SetCurrentXOffset(const Value: integer);
property RelativeXPos: integer read fRelativeXPos write SetRelativeXPos;
public
constructor Create(Editor: TForm);
destructor Destroy; override;
property CharWidth: integer read fCharWidth write SetCharWidth;
property CurrentX: integer read fCurrentX write SetCurrentX;
property CurrentXOffset: integer read fCurrentXOffset write SetCurrentXOffset;
property LeftIndent: integer read fLeftIndent write SetLeftIndent;
end;
implementation
////////////////////////////////////////////////////////////////////////////////////////////
// Property functions
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TRuler.SetCharWidth(const Value: integer);
begin
if (fCharWidth<>Value) then begin
fCharWidth:=Value;
fRuler.HairBlockWidth:=Value;
fRuler.Scale:=(Value*100);
end;
end;
//------------------------------------------------------------------------------------------
procedure TRuler.SetRelativeXPos(const Value: integer);
begin
if (fRelativeXPos<>Value) then begin
fRelativeXPos:=Value;
fRuler.HairLinePos:=(fCharWidth*Value)+1;
end;
end;
//------------------------------------------------------------------------------------------
procedure TRuler.SetCurrentX(const Value: integer);
begin
fCurrentX:=Value;
RelativeXPos:=Value-fCurrentXOffset;
end;
//------------------------------------------------------------------------------------------
procedure TRuler.SetCurrentXOffset(const Value: integer);
begin
if (fCurrentXOffset<>Value) then begin
fCurrentXOffset:=Value;
RelativeXPos:=fCurrentX-fCurrentXOffset;
fRuler.LeftOffset:=Value;
end;
end;
//------------------------------------------------------------------------------------------
procedure TRuler.SetLeftIndent(const Value: integer);
begin
fLeftIndent:=Value;
fRuler.LeftIndent:=Value;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Constructor, destructor
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
constructor TRuler.Create(Editor: TForm);
begin
fEditor:=Editor;
fRuler:=TRsRuler.Create(Editor);
with fRuler do begin
HairLineStyle:=hlsBlock;
Height:=23;
Units:=ruPixel;
Flat:=TRUE;
ScaleColor:=clWindow;
TickColor:=clWindowText;
Direction:=rdTop;
ScaleDir:=rsdNormal;
Scale:=800;
HairLine:=TRUE;
HairLinePos:=-1;
HairBlockWidth:=0;
LeftOffset:=0;
Align:=alTop;
Parent:=Editor;
end;
fCurrentX:=-1;
end;
//------------------------------------------------------------------------------------------
destructor TRuler.Destroy;
begin
fRuler.Free;
inherited;
end;
//------------------------------------------------------------------------------------------
end.
|
unit Coche.Types;
interface
type
RCoche = record
ID: Integer;
Nombre: string;
Imagen: TObject;
Dueño: Integer;
end;
TNotify_Coche = procedure(const AData: RCoche) of object;
implementation
end.
|
unit ideSHDesignIntf;
interface
uses
SysUtils, Classes, Controls, Contnrs, StdCtrls, ComCtrls, Menus, ActnList,
SHDesignIntf, SHDevelopIntf;
type
IideBTMain = interface
['{55860B04-61BF-42FC-9D5A-F8321A8BA0F5}']
{ Functions for MainMenu properties
}
function GetCanNew: Boolean;
function GetCanOpen: Boolean;
function GetCanSave: Boolean;
function GetCanSaveAs: Boolean;
function GetCanSaveAll: Boolean;
function GetCanClose: Boolean;
function GetCanClosePage: Boolean;
function GetCanCloseAll: Boolean;
function GetCanPrint: Boolean;
function GetCanExit: Boolean;
function GetCanUndo: Boolean;
function GetCanRedo: Boolean;
function GetCanCut: Boolean;
function GetCanCopy: Boolean;
function GetCanPaste: Boolean;
function GetCanSelectAll: Boolean;
function GetCanClearAll: Boolean;
function GetCanFind: Boolean;
function GetCanReplace: Boolean;
function GetCanSearchAgain: Boolean;
function GetCanSearchIncremental: Boolean;
function GetCanGoToLineNumber: Boolean;
function GetCanShowWindowList: Boolean;
function GetCanShowObjectList: Boolean;
function GetCanBrowseNext: Boolean;
function GetCanBrowsePrevious: Boolean;
function GetCanBrowseBack: Boolean;
function GetCanBrowseForward: Boolean;
function GetCanShowEnvironmentOptions: Boolean;
function GetCanShowEnvironmentConfigurator: Boolean;
{ Functions for misc properties
}
function GetMainMenu: TMainMenu;
function GetImageList: TImageList;
function GetActionList: TActionList;
{ Procedures for MainMenu properties
}
procedure New;
procedure Open;
procedure Save;
procedure SaveAs;
procedure SaveAll;
procedure Close;
procedure ClosePage;
procedure CloseAll;
procedure Print;
procedure Exit;
procedure Undo;
procedure Redo;
procedure Cut;
procedure Copy;
procedure Paste;
procedure SelectAll;
procedure ClearAll;
procedure Find;
procedure Replace;
procedure SearchAgain;
procedure SearchIncremental;
procedure GoToLineNumber;
procedure ShowWindowList;
procedure ShowObjectList;
procedure BrowseNext;
procedure BrowsePrevious;
procedure BrowseBack;
procedure BrowseForward;
procedure ShowEnvironmentOptionsProc(const IID: TGUID);
procedure ShowEnvironmentOptions;
procedure ShowEnvironmentConfigurator;
procedure UnderConstruction;
procedure NotSupported;
{ MainMenu properties
}
// File
property CanNew: Boolean read GetCanNew;
property CanOpen: Boolean read GetCanOpen;
property CanSave: Boolean read GetCanSave;
property CanSaveAs: Boolean read GetCanSaveAs;
property CanSaveAll: Boolean read GetCanSaveAll;
property CanClose: Boolean read GetCanClose;
property CanClosePage: Boolean read GetCanClosePage;
property CanCloseAll: Boolean read GetCanCloseAll;
property CanPrint: Boolean read GetCanPrint;
property CanExit: Boolean read GetCanExit;
// Edit
property CanUndo: Boolean read GetCanUndo;
property CanRedo: Boolean read GetCanRedo;
property CanCut: Boolean read GetCanCut;
property CanCopy: Boolean read GetCanCopy;
property CanPaste: Boolean read GetCanPaste;
property CanSelectAll: Boolean read GetCanSelectAll;
property CanClearAll: Boolean read GetCanClearAll;
// Search
property CanFind: Boolean read GetCanFind;
property CanReplace: Boolean read GetCanReplace;
property CanSearchAgain: Boolean read GetCanSearchAgain;
property CanSearchIncremental: Boolean read GetCanSearchIncremental;
property CanGoToLineNumber: Boolean read GetCanGoToLineNumber;
// View
property CanShowWindowList: Boolean read GetCanShowWindowList;
property CanShowObjectList: Boolean read GetCanShowObjectList;
property CanBrowseNext: Boolean read GetCanBrowseNext;
property CanBrowsePrevious: Boolean read GetCanBrowsePrevious;
property CanBrowseBack: Boolean read GetCanBrowseBack;
property CanBrowseForward: Boolean read GetCanBrowseForward;
// Project
// Tools
property CanShowEnvironmentOptions: Boolean read GetCanShowEnvironmentOptions;
property CanShowEnvironmentConfigurator: Boolean read GetCanShowEnvironmentConfigurator;
// Window
{ Misc properties
}
property MainMenu: TMainMenu read GetMainMenu;
property ImageList: TImageList read GetImageList;
property ActionList: TActionList read GetActionList;
end;
IideBTRegistry = interface
['{42F7A7E7-E84F-4D07-AB7F-25CDBEDBD152}']
function GetRegLibraryCount: Integer;
function GetRegPackageCount: Integer;
function GetRegComponentCount: Integer;
function GetRegComponentFormCount: Integer;
function GetRegPropertyEditorCount: Integer;
function GetRegInterfaceCount: Integer;
function GetRegDemonCount: Integer;
function GetRegLibraryDescription(Index: Integer): string;
function GetRegLibraryFileName(Index: Integer): string;
function GetRegLibraryName(Index: Integer): string;
function GetRegPackageDescription(Index: Integer): string;
function GetRegPackageFileName(Index: Integer): string;
function GetRegPackageName(Index: Integer): string;
function GetRegBranchList: TComponentList;
function GetRegBranchInfo(Index: Integer): ISHBranchInfo; overload;
function GetRegBranchInfo(const BranchIID: TGUID): ISHBranchInfo; overload;
function GetRegBranchInfo(const BranchName: string): ISHBranchInfo; overload;
function GetRegComponentClass(Index: Integer): TSHComponentClass;
function GetRegComponentHint(Index: Integer): string;
function GetRegComponentAssociation(Index: Integer): string;
function GetRegComponentClassIID(Index: Integer): TGUID;
function SupportInterface(const IID: TGUID; out Intf;
const Description: string): Boolean;
function GetRegDemon(Index: Integer): TSHComponent; overload;
function GetRegDemon(const ClassIID: TGUID): TSHComponent; overload;
function GetRegComponent(const ClassIID: TGUID): TSHComponentClass;
function GetRegImageIndex(const AStringIID: string): Integer;
function GetRegCallStrings(const AClassIID: TGUID): TStrings;
function GetRegComponentForm(const ClassIID: TGUID;
const CallString: string): TSHComponentFormClass;
function GetRegComponentFactory(const ClassIID: TGUID): ISHComponentFactory; overload;
function GetRegComponentFactory(const ClassIID, BranchIID: TGUID): ISHComponentFactory; overload;
function GetRegComponentOptions(const ClassIID: TGUID): ISHComponentOptions;
function GetRegPropertyEditor(const ClassIID: TGUID;
const PropertyName: string): TSHPropertyEditorClass;
procedure RegisterLibrary(const FileName: string);
procedure UnRegisterLibrary(const FileName: string);
function ExistsLibrary(const FileName: string): Boolean;
procedure LoadLibrariesFromFile;
procedure SaveLibrariesToFile;
procedure RegisterPackage(const FileName: string);
procedure UnRegisterPackage(const FileName: string);
function ExistsPackage(const FileName: string): Boolean;
procedure LoadPackagesFromFile;
procedure SavePackagesToFile;
procedure LoadOptionsFromFile;
procedure SaveOptionsToFile;
procedure LoadOptionsFromList;
procedure SaveOptionsToList;
procedure LoadImagesFromFile;
procedure RegisterComponents(ComponentClasses: array of TSHComponentClass);
procedure RegisterComponentForm(const ClassIID: TGUID;
const CallString: string; ComponentForm: TSHComponentFormClass);
procedure RegisterPropertyEditor(const ClassIID: TGUID;
const PropertyName: string; PropertyEditor: TSHPropertyEditorClass);
procedure RegisterImage(const StringIID, FileName: string);
procedure RegisterInterface(const Intf: IInterface;
const Description: string);
property RegLibraryCount: Integer read GetRegLibraryCount;
property RegPackageCount: Integer read GetRegPackageCount;
property RegComponentCount: Integer read GetRegComponentCount;
property RegComponentFormCount: Integer read GetRegComponentFormCount;
property RegPropertyEditorCount: Integer read GetRegPropertyEditorCount;
property RegInterfaceCount: Integer read GetRegInterfaceCount;
property RegDemonCount: Integer read GetRegDemonCount;
end;
IideSHComponentFactory = interface
['{E367E5E0-F0B2-435F-9F44-5B3763C0D4AB}']
function GetComponents: TComponentList;
function GetComponentForms: TComponentList;
function CreateComponent(const OwnerIID, ClassIID: TGUID;
const ACaption: string): TSHComponent;
function DestroyComponent(AComponent: TSHComponent): Boolean;
function FindComponent(const InstanceIID: TGUID): TSHComponent; overload;
function FindComponent(const OwnerIID, ClassIID: TGUID): TSHComponent; overload;
function FindComponent(const OwnerIID, ClassIID: TGUID; const ACaption: string): TSHComponent; overload;
procedure SendEvent(Event: TSHEvent);
property Components: TComponentList read GetComponents;
property ComponentForms: TComponentList read GetComponentForms;
end;
IideBTObject = interface
['{54FB0BCA-568C-49CF-82C4-7F337511AC45}']
function GetCurrentComponent: TSHComponent;
function GetEnabled: Boolean;
procedure SetEnabled(Value: Boolean);
function GetFlat: Boolean;
procedure SetFlat(Value: Boolean);
function GetPageCtrl: TPageControl;
procedure SetPageCtrl(Value: TPageControl);
function Exists(AComponent: TSHComponent): Boolean;
function Add(AComponent: TSHComponent): Boolean;
function Remove(AComponent: TSHComponent): Boolean;
property CurrentComponent: TSHComponent read GetCurrentComponent;
property Enabled: Boolean read GetEnabled write SetEnabled;
property Flat: Boolean read GetFlat write SetFlat;
property PageCtrl: TPageControl read GetPageCtrl write SetPageCtrl;
end;
IideSHConnection = interface
['{07662AB0-C7B1-4F22-A6F3-37F97837FA35}']
function GetCanConnect: Boolean;
function GetCanReconnect: Boolean;
function GetCanDisconnect: Boolean;
function GetCanDisconnectAll: Boolean;
function GetCanRefresh: Boolean;
function GetCanMoveUp: Boolean;
function GetCanMoveDown: Boolean;
function GetLoadingFromFile: Boolean;
function GetCurrentServer: TSHComponent;
function GetCurrentDatabase: TSHComponent;
function GetCurrentServerInUse: Boolean;
function GetCurrentDatabaseInUse: Boolean;
function GetServerCount: Integer;
function GetDatabaseCount: Integer;
procedure Connect;
procedure Reconnect;
procedure Disconnect;
function DisconnectAll: Boolean;
procedure Refresh;
procedure MoveUp;
procedure MoveDown;
function FindConnection(AConnection: TSHComponent): Boolean;
function RegisterConnection(AConnection: TSHComponent): Boolean;
function UnregisterConnection(AConnection: TSHComponent): Boolean;
function DestroyConnection(AConnection: TSHComponent): Boolean;
function ConnectTo(AConnection: TSHComponent): Boolean;
function ReconnectTo(AConnection: TSHComponent): Boolean;
function DisconnectFrom(AConnection: TSHComponent): Boolean;
procedure RefreshConnection(AConnection: TSHComponent);
procedure ActivateConnection(AConnection: TSHComponent);
function SynchronizeConnection(AConnection: TSHComponent; const AClassIID: TGUID;
const ACaption: string; Operation: TOperation): Boolean;
procedure SetRegistrationMenuItems(AMenuItem: TMenuItem);
procedure SetConnectionMenuItems(AMenuItem: TMenuItem);
procedure SaveToFile;
procedure LoadFromFile;
property CanConnect: Boolean read GetCanConnect;
property CanReconnect: Boolean read GetCanReconnect;
property CanDisconnect: Boolean read GetCanDisconnect;
property CanDisconnectAll: Boolean read GetCanDisconnectAll;
property CanRefresh: Boolean read GetCanRefresh;
property CanMoveUp: Boolean read GetCanMoveUp;
property CanMoveDown: Boolean read GetCanMoveDown;
property LoadingFromFile: Boolean read GetLoadingFromFile;
property CurrentServer: TSHComponent read GetCurrentServer;
property CurrentDatabase: TSHComponent read GetCurrentDatabase;
property CurrentServerInUse: Boolean read GetCurrentServerInUse;
property CurrentDatabaseInUse: Boolean read GetCurrentDatabaseInUse;
property ServerCount: Integer read GetServerCount;
property DatabaseCount: Integer read GetDatabaseCount;
end;
IideSHToolbox = interface
['{7BC789C7-8F20-4D83-ACF2-75F3346883F1}']
procedure ReloadComponents;
procedure InvalidateComponents;
procedure _InspCreateForm(AComponent: TSHComponent);
function _InspFindForm(AComponent: TSHComponent): TSHComponentForm;
procedure _InspDestroyForm(AComponent: TSHComponent);
procedure _InspHideForm(AComponent: TSHComponent);
procedure _InspShowForm(AComponent: TSHComponent);
procedure _InspRefreshForm(AComponent: TSHComponent);
procedure _InspPrepareForm(AComponent: TSHComponent);
procedure _InspAddAction(AAction: TSHAction);
procedure _InspUpdateNodes;
end;
IideSHNavigator = interface
['{59A1DAEF-DB97-49B8-B32E-ADFDE8A05FC7}']
function GetCurrentBranch: TSHComponent;
function GetCurrentServer: TSHComponent;
function GetCurrentDatabase: TSHComponent;
function GetCurrentServerInUse: Boolean;
function GetCurrentDatabaseInUse: Boolean;
function GetServerCount: Integer;
function GetDatabaseCount: Integer;
function GetCanConnect: Boolean;
function GetCanReconnect: Boolean;
function GetCanDisconnect: Boolean;
function GetCanDisconnectAll: Boolean;
function GetCanRefresh: Boolean;
function GetCanMoveUp: Boolean;
function GetCanMoveDown: Boolean;
function GetCanShowScheme: Boolean;
function GetCanShowPalette: Boolean;
function GetLoadingFromFile: Boolean;
function GetToolbox: IideSHToolbox;
procedure SetBranchMenuItems(AMenuItem: TMenuItem);
procedure SetRegistrationMenuItems(AMenuItem: TMenuItem);
procedure SetConnectionMenuItems(AMenuItem: TMenuItem);
function RegisterConnection(AConnection: TSHComponent): Boolean; // регистрация соединения
function UnregisterConnection(AConnection: TSHComponent): Boolean; // отрегистрация соединения
function DestroyConnection(AConnection: TSHComponent): Boolean; // разрушение соединения
function DisconnectAllConnections: Boolean; // отключить все коннекты
function ConnectTo(AConnection: TSHComponent): Boolean;
function ReconnectTo(AConnection: TSHComponent): Boolean;
function DisconnectFrom(AConnection: TSHComponent): Boolean;
procedure RefreshConnection(AConnection: TSHComponent);
procedure ActivateConnection(AConnection: TSHComponent);
function SynchronizeConnection(AConnection: TSHComponent; const AClassIID: TGUID;
const ACaption: string; Operation: TOperation): Boolean;
procedure Connect;
procedure Reconnect;
procedure Disconnect;
function DisconnectAll: Boolean;
procedure Refresh;
procedure SaveRegisteredInfoToFile; // сохранение регинфы в файл
procedure LoadRegisteredInfoFromFile; // вычитка регинфы из файла
procedure RecreatePalette;
procedure RefreshPalette;
procedure ShowScheme;
procedure ShowPalette;
property CurrentBranch: TSHComponent read GetCurrentBranch;
property CurrentServer: TSHComponent read GetCurrentServer;
property CurrentDatabase: TSHComponent read GetCurrentDatabase;
property CurrentServerInUse: Boolean read GetCurrentServerInUse;
property CurrentDatabaseInUse: Boolean read GetCurrentDatabaseInUse;
property ServerCount: Integer read GetServerCount;
property DatabaseCount: Integer read GetDatabaseCount;
property CanConnect: Boolean read GetCanConnect;
property CanReconnect: Boolean read GetCanReconnect;
property CanDisconnect: Boolean read GetCanDisconnect;
property CanDisconnectAll: Boolean read GetCanDisconnectAll;
property CanRefresh: Boolean read GetCanRefresh;
property CanMoveUp: Boolean read GetCanMoveUp;
property CanMoveDown: Boolean read GetCanMoveDown;
property CanShowScheme: Boolean read GetCanShowScheme;
property CanShowPalette: Boolean read GetCanShowPalette;
property LoadingFromFile: Boolean read GetLoadingFromFile;
property Toolbox: IideSHToolbox read GetToolbox;
end;
IideBTBaseForm = interface
['{4E34ADD2-C09B-4EAA-A853-294C42E5E6E0}']
function GetActive: Boolean;
procedure SetActive(Value: Boolean);
function GetCurrentComponent: TSHComponent;
function Exists(AComponent: TSHComponent): Boolean;
function Add(AComponent: TSHComponent): Boolean;
function Remove(AComponent: TSHComponent): Boolean;
property Active: Boolean read GetActive write SetActive;
property CurrentComponent: TSHComponent read GetCurrentComponent;
end;
IideBTRegistratorForm = interface(IideBTBaseForm)
['{996F56F6-76A0-432E-911F-5886F0FD6826}']
function GetLoading: Boolean;
function GetCurrentServer: TSHComponent;
function GetCurrentDatabase: TSHComponent;
function GetCanMoveUp: Boolean;
function GetCanMoveDown: Boolean;
procedure MoveUp;
procedure MoveDown;
procedure SaveToFile;
procedure LoadFromFile;
function ExistsConnected: Boolean;
function DisconnectAll: Boolean;
property Loading: Boolean read GetLoading;
property CurrentServer: TSHComponent read GetCurrentServer;
property CurrentDatabase: TSHComponent read GetCurrentDatabase;
property CanMoveUp: Boolean read GetCanMoveUp;
property CanMoveDown: Boolean read GetCanMoveDown;
end;
IideBTNavigatorForm = interface(IideBTBaseForm)
['{BD8046BC-40CB-4E8C-8664-DD6F03F9565B}']
function GetCurrentServer: TSHComponent;
function GetCurrentDatabase: TSHComponent;
function SynchronizeConnection(const AOwnerIID, AClassIID: TGUID;
const ACaption: string; Operation: TOperation): Boolean;
procedure Refresh(AComponent: TSHComponent);
property CurrentServer: TSHComponent read GetCurrentServer;
property CurrentDatabase: TSHComponent read GetCurrentDatabase;
end;
IideSHObjectEditor = interface(IideBTObject)
['{441B05B0-57FD-4422-97F8-263805B9B2BE}']
function GetMultiLine: Boolean;
procedure SetMultiLine(Value: Boolean);
function GetFilterMode: Boolean;
procedure SetFilterMode(Value: Boolean);
function GetCurrentComponentForm: TSHComponentForm;
function GetCurrentCallString: string;
function GetCallStringCount: Integer;
procedure CreateEditor;
procedure ChangeEditor;
function GetComponent(Index: Integer): TSHComponent;
function GetCallStrings(Index: Integer): TStrings;
procedure GetCaptionList(APopupMenu: TPopupMenu); overload;
procedure GetCaptionList(AMenuItem: TMenuItem); overload;
procedure GetBackList(APopupMenu: TPopupMenu);
procedure GetForwardList(APopupMenu: TPopupMenu);
function GetCanBrowseBack(AComponent: TSHComponent): Boolean;
function GetCanBrowseForward(AComponent: TSHComponent): Boolean;
procedure Jump(AFromComponent, AToComponent: TSHComponent);
procedure JumpRemove(const AOwnerIID, AClassIID: TGUID; const ACaption: string);
procedure BrowseNext;
procedure BrowsePrevious;
procedure BrowseBack;
procedure BrowseForward;
function Exists(AComponent: TSHComponent; const CallString: string = ''): Boolean; overload;
function Add(AComponent: TSHComponent; const CallString: string = ''): Boolean; overload;
function Remove(AComponent: TSHComponent; const CallString: string = ''): Boolean; overload;
function CanUpdateToolbarActions: Boolean;
procedure UpdateToolbarActions;
property MultiLine: Boolean read GetMultiLine write SetMultiLine;
property FilterMode: Boolean read GetFilterMode write SetFilterMode;
property CurrentComponentForm: TSHComponentForm read GetCurrentComponentForm;
property CurrentCallString: string read GetCurrentCallString;
property CallStringCount: Integer read GetCallStringCount;
end;
IideBTMegaEditor = interface
['{D80700B7-3CBC-4378-A0F0-97DB50000CC9}']
function GetActive: Boolean;
procedure SetActive(Value: Boolean);
function GetMultiLine: Boolean;
procedure SetMultiLine(Value: Boolean);
function GetFilterMode: Boolean;
procedure SetFilterMode(Value: Boolean);
procedure GetCaptionList(APopupMenu: TPopupMenu);
function Exists(AComponent: TSHComponent; const CallString: string): Boolean;
function Add(AComponent: TSHComponent; const CallString: string): Boolean;
function Remove(AComponent: TSHComponent; const CallString: string): Boolean;
procedure Toggle(AIndex: Integer);
function Close: Boolean;
function CloseAll: Boolean;
function ShowEditor(AComponent: TSHComponent): Boolean; overload;
function ShowEditor(const AIndex: Integer): Boolean; overload;
function DestroyEditor(const AIndex: Integer): Boolean;
property Active: Boolean read GetActive write SetActive;
property MultiLine: Boolean read GetMultiLine write SetMultiLine;
property FilterMode: Boolean read GetFilterMode write SetFilterMode;
end;
implementation
end.
|
program prova04;
uses crt;
type
data=record
ano:integer;
mes:integer;
dia:integer;
end;
procedure atribui(var x:data); {procedure que atribui uma data (usuario - input)}
begin
writeln('Data para verificar:');
writeln('ano:'); readln(x.ano); {ano}
writeln('mes:'); readln(x.mes); {mes}
writeln('dia:'); readln(x.dia); {dia}
end;
procedure transf(x:data); {procedure que checa uma data (output)}
begin
clrscr;
if x.ano < 0 then {checa se o ano é negativo, caso contrario a data é valida}
write('ano negativo, data invalida')
else
if x.dia < 1 then {checa se o dia é negativo ou 0, caso contrario a data é valida}
write('dia negativo ou 0, data invalida')
else
begin
case x.mes of {checa se o mes esta compreendido entre 1 e 12, caso contrario a data é invalida}
1:if (x.dia > 31) then write('dia ',x.dia,' nao existe no mes ',x.mes) else write(x.dia,'/',x.mes,'/',x.ano,' e uma data valida!');
2:if ((x.ano+2) mod 6) <> 0 then {checagem para anos bisextos em fevereiro}
if (x.dia > 28) then write('dia ',x.dia,' nao existe no mes ',x.mes,' em anos nao bisextos') else write(x.dia,'/',x.mes,'/',x.ano,' e uma data valida!')
else if (x.dia > 29) then write('dia ',x.dia,' nao existe no mes ',x.mes,' em anos bisextos') else write(x.dia,'/',x.mes,'/',x.ano,' e uma data valida!');
3:if (x.dia > 31) then write('dia ',x.dia,' nao existe no mes ',x.mes) else write(x.dia,'/',x.mes,'/',x.ano,' e uma data valida!');
4:if (x.dia > 30) then write('dia ',x.dia,' nao existe no mes ',x.mes) else write(x.dia,'/',x.mes,'/',x.ano,' e uma data valida!');
5:if (x.dia > 31) then write('dia ',x.dia,' nao existe no mes ',x.mes) else write(x.dia,'/',x.mes,'/',x.ano,' e uma data valida!');
6:if (x.dia > 30) then write('dia ',x.dia,' nao existe no mes ',x.mes) else write(x.dia,'/',x.mes,'/',x.ano,' e uma data valida!');
7:if (x.dia > 31) then write('dia ',x.dia,' nao existe no mes ',x.mes) else write(x.dia,'/',x.mes,'/',x.ano,' e uma data valida!');
8:if (x.dia > 31) then write('dia ',x.dia,' nao existe no mes ',x.mes) else write(x.dia,'/',x.mes,'/',x.ano,' e uma data valida!');
9:if (x.dia > 30) then write('dia ',x.dia,' nao existe no mes ',x.mes) else write(x.dia,'/',x.mes,'/',x.ano,' e uma data valida!');
10:if (x.dia > 31) then write('dia ',x.dia,' nao existe no mes ',x.mes) else write(x.dia,'/',x.mes,'/',x.ano,' e uma data valida!');
11:if (x.dia > 30) then write('dia ',x.dia,' nao existe no mes ',x.mes) else write(x.dia,'/',x.mes,'/',x.ano,' e uma data valida!');
12:if (x.dia > 31) then write('dia ',x.dia,' nao existe no mes ',x.mes) else write(x.dia,'/',x.mes,'/',x.ano,' e uma data valida!');
else
write('mes inexistente, data invalida');
end;
end;
end;
var
dat:data;
begin
atribui(dat);
transf(dat);
readkey;
end. |
unit uDepartmentGroup;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, DBGrids, Buttons, ExtCtrls, DB, IBCustomDataSet, IBQuery,
PersonalCommon, SpCommon, DepartmentsViewUnit;
type
TfmDepartmentsGroup = class(TForm)
TopPanel: TPanel;
AddButton: TSpeedButton;
ModifyButton: TSpeedButton;
DeleteButton: TSpeedButton;
SelectButton: TSpeedButton;
CancelButton: TSpeedButton;
RefreshButton: TSpeedButton;
GroupsGrid: TDBGrid;
Panel1: TPanel;
AddDep: TSpeedButton;
AddTreeButton: TSpeedButton;
DeleteDeptButton: TSpeedButton;
DeptsGrid: TDBGrid;
DeptGroupSelect: TIBQuery;
DeptGroupSelectID_DEPT_GROUP: TIntegerField;
DeptGroupSelectNAME_DEPT_GROUP: TIBStringField;
DeptGroupSource: TDataSource;
WorkQuery: TIBQuery;
DeptsByGroup: TIBQuery;
DeptsByGroupID_DEPARTMENT: TIntegerField;
DeptsByGroupNAME_FULL: TIBStringField;
DeptsSource: TDataSource;
RefreshDeptsButton: TSpeedButton;
procedure FormCreate(Sender: TObject);
procedure RefreshButtonClick(Sender: TObject);
procedure AddButtonClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ModifyButtonClick(Sender: TObject);
procedure DeleteButtonClick(Sender: TObject);
procedure AddDepClick(Sender: TObject);
procedure RefreshDeptsButtonClick(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
procedure AddTreeButtonClick(Sender: TObject);
procedure DeleteDeptButtonClick(Sender: TObject);
procedure GroupsGridKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure SelectButtonClick(Sender: TObject);
procedure GroupsGridDblClick(Sender: TObject);
private
{ Private declarations }
public
Id_Dept_Group: Integer;
end;
var
fmDepartmentsGroup: TfmDepartmentsGroup;
procedure SelectDepartmentGroup(var Value: Variant; var DisplayText: string);
implementation
{$R *.dfm}
procedure SelectDepartmentGroup(var Value: Variant; var DisplayText: string);
var
form: TfmDepartmentsGroup;
begin
form := TfmDepartmentsGroup.Create(Application.MainForm);
form.SelectButton.Visible := True;
form.ShowModal;
with form do
if Id_Dept_Group <> -1 then
begin
Value := DeptGroupSelect['Id_Dept_Group'];
DisplayText := DeptGroupSelect['Name_Dept_Group'];
end;
form.Free;
end;
procedure TfmDepartmentsGroup.FormCreate(Sender: TObject);
begin
CancelButton.Align := alRight;
SelectButton.Align := alRight;
DeptGroupSelect.Transaction := ReadTransaction;
DeptGroupSelect.Open;
DeptsByGroup.Transaction := ReadTransaction;
DeptsByGroup.Open;
Id_Dept_Group := -1;
end;
procedure TfmDepartmentsGroup.RefreshButtonClick(Sender: TObject);
begin
DeptGroupSelect.Close;
DeptGroupSelect.Open;
end;
procedure TfmDepartmentsGroup.AddButtonClick(Sender: TObject);
var
s: string;
begin
if InputQuery('Введіть назву групи підрозділів', 'Назва групи підрозділів', s)
then
begin
WorkQuery.Transaction := WriteTransaction;
WorkQuery.SQL.Text := 'EXECUTE PROCEDURE Sp_Dept_Group_Insert ' +
QuotedStr(s);
ExecQuery(WorkQuery);
RefreshButton.Click;
end;
end;
procedure TfmDepartmentsGroup.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if FormStyle = fsMDIChild then
Action := caFree;
end;
procedure TfmDepartmentsGroup.ModifyButtonClick(Sender: TObject);
var
s: string;
begin
if DeptGroupSelect.IsEmpty then Exit;
if InputQuery('Введіть нову назву групи підрозділів', 'Назва групи підрозділів', s)
then
begin
WorkQuery.Transaction := WriteTransaction;
WorkQuery.SQL.Text := 'EXECUTE PROCEDURE Sp_Dept_Group_Update ' +
IntToStr(DeptGroupSelect['Id_Dept_Group']) + ',' + QuotedStr(s);
ExecQuery(WorkQuery);
RefreshButton.Click;
end;
end;
procedure TfmDepartmentsGroup.DeleteButtonClick(Sender: TObject);
begin
if DeptGroupSelect.IsEmpty then Exit;
if MessageDlg('Ви справді бажаєте вилучити групу підрозділів ' +
DeptGroupSelect['Name_Dept_Group'], mtConfirmation, [mbYes, mbNo], 0) = mrYes
then
begin
WorkQuery.Transaction := WriteTransaction;
WorkQuery.SQL.Text := 'EXECUTE PROCEDURE Sp_Dept_Group_Delete ' +
IntToStr(DeptGroupSelect['Id_Dept_Group']);
ExecQuery(WorkQuery);
RefreshButton.Click;
end;
end;
procedure TfmDepartmentsGroup.AddDepClick(Sender: TObject);
var
form: TDepartmentsViewForm;
begin
if DeptGroupSelect.IsEmpty then Exit;
form := TDepartmentsViewForm.Create(Self);
form.Prepare(True, Date);
form.CanSelectRoot := True;
if form.ShowModal = mrOk then
with form do
begin
WorkQuery.Transaction := WriteTransaction;
WorkQuery.SQL.Text := 'EXECUTE PROCEDURE Add_Dept_To_Group ' +
IntToStr(DeptGroupSelect['Id_Dept_Group']) + ',' +
IntToStr(Selected_Id) + ', 0';
ExecQuery(WorkQuery);
RefreshDeptsButton.Click;
end;
end;
procedure TfmDepartmentsGroup.RefreshDeptsButtonClick(Sender: TObject);
begin
DeptsByGroup.Close;
DeptsByGroup.Open;
end;
procedure TfmDepartmentsGroup.CancelButtonClick(Sender: TObject);
begin
Close;
end;
procedure TfmDepartmentsGroup.AddTreeButtonClick(Sender: TObject);
var
form: TDepartmentsViewForm;
begin
if DeptGroupSelect.IsEmpty then Exit;
form := TDepartmentsViewForm.Create(Self);
form.Prepare(True, Date);
form.CanSelectRoot := True;
if form.ShowModal = mrOk then
with form do
begin
WorkQuery.Transaction := WriteTransaction;
WorkQuery.SQL.Text := 'EXECUTE PROCEDURE Add_Dept_To_Group ' +
IntToStr(DeptGroupSelect['Id_Dept_Group']) + ',' +
IntToStr(Selected_Id) + ', 1';
ExecQuery(WorkQuery);
RefreshDeptsButton.Click;
end;
end;
procedure TfmDepartmentsGroup.DeleteDeptButtonClick(Sender: TObject);
begin
if DeptsByGroup.IsEmpty then Exit;
if MessageDlg('Ви справді бажаєте вилучити підрозділ ' +
DeptsByGroup['Name_Full'] + ' з групи?', mtConfirmation,
[mbYes, mbNo], 0) = mrYes
then
begin
WorkQuery.Transaction := WriteTransaction;
WorkQuery.SQL.Text := 'EXECUTE PROCEDURE Remove_Dept_From_Group ' +
IntToStr(DeptGroupSelect['Id_Dept_Group']) + ',' +
IntToStr(DeptsByGroup['Id_Department']);
ExecQuery(WorkQuery);
RefreshDeptsButton.Click;
end;
end;
procedure TfmDepartmentsGroup.GroupsGridKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if (Key = ord('Z')) and (ssAlt in Shift) and (ssShift in Shift)
and (ssCtrl in Shift) then
try
ShowMessage('Id_Dept_Group: ' + IntToStr(DeptGroupSelect['Id_Dept_Group']));
except
end;
end;
procedure TfmDepartmentsGroup.SelectButtonClick(Sender: TObject);
begin
if DeptGroupSelect.IsEmpty then Exit;
Id_Dept_Group := DeptGroupSelect['Id_Dept_Group'];
Close;
end;
procedure TfmDepartmentsGroup.GroupsGridDblClick(Sender: TObject);
begin
if not DeptGroupSelect.IsEmpty and SelectButton.Visible then
SelectButton.Click;
end;
end.
|
unit FMX.MaterialIconsFont;
{
Material Design Icons 3.0.1
https://material.io/icons/
Based on FMX.FontAwesome by ZuBy, 2017
https://github.com/rzaripov1990/FMX.FontAwesome
}
interface
uses
FMX.Types, FMX.FontGlyphs, System.SysUtils
{$IFDEF ANDROID}
, FMX.FontGlyphs.Android
{$ENDIF};
const
{$IF defined(MSWINDOWS) or defined(MACOS)}
MaterialIconsFontName = 'Material Icons';
{$ELSEIF defined(ANDROID)}
MaterialIconsFontName = 'MaterialIcons-Regular';
{$ENDIF}
const
mi_3d_rotation = WideChar($e84d);
mi_ac_unit = WideChar($eb3b);
mi_access_alarm = WideChar($e190);
mi_access_alarms = WideChar($e191);
mi_access_time = WideChar($e192);
mi_accessibility = WideChar($e84e);
mi_accessible = WideChar($e914);
mi_account_balance = WideChar($e84f);
mi_account_balance_wallet = WideChar($e850);
mi_account_box = WideChar($e851);
mi_account_circle = WideChar($e853);
mi_adb = WideChar($e60e);
mi_add = WideChar($e145);
mi_add_a_photo = WideChar($e439);
mi_add_alarm = WideChar($e193);
mi_add_alert = WideChar($e003);
mi_add_box = WideChar($e146);
mi_add_circle = WideChar($e147);
mi_add_circle_outline = WideChar($e148);
mi_add_location = WideChar($e567);
mi_add_shopping_cart = WideChar($e854);
mi_add_to_photos = WideChar($e39d);
mi_add_to_queue = WideChar($e05c);
mi_adjust = WideChar($e39e);
mi_airline_seat_flat = WideChar($e630);
mi_airline_seat_flat_angled = WideChar($e631);
mi_airline_seat_individual_suite = WideChar($e632);
mi_airline_seat_legroom_extra = WideChar($e633);
mi_airline_seat_legroom_normal = WideChar($e634);
mi_airline_seat_legroom_reduced = WideChar($e635);
mi_airline_seat_recline_extra = WideChar($e636);
mi_airline_seat_recline_normal = WideChar($e637);
mi_airplanemode_active = WideChar($e195);
mi_airplanemode_inactive = WideChar($e194);
mi_airplay = WideChar($e055);
mi_airport_shuttle = WideChar($eb3c);
mi_alarm = WideChar($e855);
mi_alarm_add = WideChar($e856);
mi_alarm_off = WideChar($e857);
mi_alarm_on = WideChar($e858);
mi_album = WideChar($e019);
mi_all_inclusive = WideChar($eb3d);
mi_all_out = WideChar($e90b);
mi_android = WideChar($e859);
mi_announcement = WideChar($e85a);
mi_apps = WideChar($e5c3);
mi_archive = WideChar($e149);
mi_arrow_back = WideChar($e5c4);
mi_arrow_downward = WideChar($e5db);
mi_arrow_drop_down = WideChar($e5c5);
mi_arrow_drop_down_circle = WideChar($e5c6);
mi_arrow_drop_up = WideChar($e5c7);
mi_arrow_forward = WideChar($e5c8);
mi_arrow_upward = WideChar($e5d8);
mi_art_track = WideChar($e060);
mi_aspect_ratio = WideChar($e85b);
mi_assessment = WideChar($e85c);
mi_assignment = WideChar($e85d);
mi_assignment_ind = WideChar($e85e);
mi_assignment_late = WideChar($e85f);
mi_assignment_return = WideChar($e860);
mi_assignment_returned = WideChar($e861);
mi_assignment_turned_in = WideChar($e862);
mi_assistant = WideChar($e39f);
mi_assistant_photo = WideChar($e3a0);
mi_attach_file = WideChar($e226);
mi_attach_money = WideChar($e227);
mi_attachment = WideChar($e2bc);
mi_audiotrack = WideChar($e3a1);
mi_autorenew = WideChar($e863);
mi_av_timer = WideChar($e01b);
mi_backspace = WideChar($e14a);
mi_backup = WideChar($e864);
mi_battery_alert = WideChar($e19c);
mi_battery_charging_full = WideChar($e1a3);
mi_battery_full = WideChar($e1a4);
mi_battery_std = WideChar($e1a5);
mi_battery_unknown = WideChar($e1a6);
mi_beach_access = WideChar($eb3e);
mi_beenhere = WideChar($e52d);
mi_block = WideChar($e14b);
mi_bluetooth = WideChar($e1a7);
mi_bluetooth_audio = WideChar($e60f);
mi_bluetooth_connected = WideChar($e1a8);
mi_bluetooth_disabled = WideChar($e1a9);
mi_bluetooth_searching = WideChar($e1aa);
mi_blur_circular = WideChar($e3a2);
mi_blur_linear = WideChar($e3a3);
mi_blur_off = WideChar($e3a4);
mi_blur_on = WideChar($e3a5);
mi_book = WideChar($e865);
mi_bookmark = WideChar($e866);
mi_bookmark_border = WideChar($e867);
mi_border_all = WideChar($e228);
mi_border_bottom = WideChar($e229);
mi_border_clear = WideChar($e22a);
mi_border_color = WideChar($e22b);
mi_border_horizontal = WideChar($e22c);
mi_border_inner = WideChar($e22d);
mi_border_left = WideChar($e22e);
mi_border_outer = WideChar($e22f);
mi_border_right = WideChar($e230);
mi_border_style = WideChar($e231);
mi_border_top = WideChar($e232);
mi_border_vertical = WideChar($e233);
mi_branding_watermark = WideChar($e06b);
mi_brightness_1 = WideChar($e3a6);
mi_brightness_2 = WideChar($e3a7);
mi_brightness_3 = WideChar($e3a8);
mi_brightness_4 = WideChar($e3a9);
mi_brightness_5 = WideChar($e3aa);
mi_brightness_6 = WideChar($e3ab);
mi_brightness_7 = WideChar($e3ac);
mi_brightness_auto = WideChar($e1ab);
mi_brightness_high = WideChar($e1ac);
mi_brightness_low = WideChar($e1ad);
mi_brightness_medium = WideChar($e1ae);
mi_broken_image = WideChar($e3ad);
mi_brush = WideChar($e3ae);
mi_bubble_chart = WideChar($e6dd);
mi_bug_report = WideChar($e868);
mi_build = WideChar($e869);
mi_burst_mode = WideChar($e43c);
mi_business = WideChar($e0af);
mi_business_center = WideChar($eb3f);
mi_cached = WideChar($e86a);
mi_cake = WideChar($e7e9);
mi_call = WideChar($e0b0);
mi_call_end = WideChar($e0b1);
mi_call_made = WideChar($e0b2);
mi_call_merge = WideChar($e0b3);
mi_call_missed = WideChar($e0b4);
mi_call_missed_outgoing = WideChar($e0e4);
mi_call_received = WideChar($e0b5);
mi_call_split = WideChar($e0b6);
mi_call_to_action = WideChar($e06c);
mi_camera = WideChar($e3af);
mi_camera_alt = WideChar($e3b0);
mi_camera_enhance = WideChar($e8fc);
mi_camera_front = WideChar($e3b1);
mi_camera_rear = WideChar($e3b2);
mi_camera_roll = WideChar($e3b3);
mi_cancel = WideChar($e5c9);
mi_card_giftcard = WideChar($e8f6);
mi_card_membership = WideChar($e8f7);
mi_card_travel = WideChar($e8f8);
mi_casino = WideChar($eb40);
mi_cast = WideChar($e307);
mi_cast_connected = WideChar($e308);
mi_center_focus_strong = WideChar($e3b4);
mi_center_focus_weak = WideChar($e3b5);
mi_change_history = WideChar($e86b);
mi_chat = WideChar($e0b7);
mi_chat_bubble = WideChar($e0ca);
mi_chat_bubble_outline = WideChar($e0cb);
mi_check = WideChar($e5ca);
mi_check_box = WideChar($e834);
mi_check_box_outline_blank = WideChar($e835);
mi_check_circle = WideChar($e86c);
mi_chevron_left = WideChar($e5cb);
mi_chevron_right = WideChar($e5cc);
mi_child_care = WideChar($eb41);
mi_child_friendly = WideChar($eb42);
mi_chrome_reader_mode = WideChar($e86d);
mi_class = WideChar($e86e);
mi_clear = WideChar($e14c);
mi_clear_all = WideChar($e0b8);
mi_close = WideChar($e5cd);
mi_closed_caption = WideChar($e01c);
mi_cloud = WideChar($e2bd);
mi_cloud_circle = WideChar($e2be);
mi_cloud_done = WideChar($e2bf);
mi_cloud_download = WideChar($e2c0);
mi_cloud_off = WideChar($e2c1);
mi_cloud_queue = WideChar($e2c2);
mi_cloud_upload = WideChar($e2c3);
mi_code = WideChar($e86f);
mi_collections = WideChar($e3b6);
mi_collections_bookmark = WideChar($e431);
mi_color_lens = WideChar($e3b7);
mi_colorize = WideChar($e3b8);
mi_comment = WideChar($e0b9);
mi_compare = WideChar($e3b9);
mi_compare_arrows = WideChar($e915);
mi_computer = WideChar($e30a);
mi_confirmation_number = WideChar($e638);
mi_contact_mail = WideChar($e0d0);
mi_contact_phone = WideChar($e0cf);
mi_contacts = WideChar($e0ba);
mi_content_copy = WideChar($e14d);
mi_content_cut = WideChar($e14e);
mi_content_paste = WideChar($e14f);
mi_control_point = WideChar($e3ba);
mi_control_point_duplicate = WideChar($e3bb);
mi_copyright = WideChar($e90c);
mi_create = WideChar($e150);
mi_create_new_folder = WideChar($e2cc);
mi_credit_card = WideChar($e870);
mi_crop = WideChar($e3be);
mi_crop_16_9 = WideChar($e3bc);
mi_crop_3_2 = WideChar($e3bd);
mi_crop_5_4 = WideChar($e3bf);
mi_crop_7_5 = WideChar($e3c0);
mi_crop_din = WideChar($e3c1);
mi_crop_free = WideChar($e3c2);
mi_crop_landscape = WideChar($e3c3);
mi_crop_original = WideChar($e3c4);
mi_crop_portrait = WideChar($e3c5);
mi_crop_rotate = WideChar($e437);
mi_crop_square = WideChar($e3c6);
mi_dashboard = WideChar($e871);
mi_data_usage = WideChar($e1af);
mi_date_range = WideChar($e916);
mi_dehaze = WideChar($e3c7);
mi_delete = WideChar($e872);
mi_delete_forever = WideChar($e92b);
mi_delete_sweep = WideChar($e16c);
mi_description = WideChar($e873);
mi_desktop_mac = WideChar($e30b);
mi_desktop_windows = WideChar($e30c);
mi_details = WideChar($e3c8);
mi_developer_board = WideChar($e30d);
mi_developer_mode = WideChar($e1b0);
mi_device_hub = WideChar($e335);
mi_devices = WideChar($e1b1);
mi_devices_other = WideChar($e337);
mi_dialer_sip = WideChar($e0bb);
mi_dialpad = WideChar($e0bc);
mi_directions = WideChar($e52e);
mi_directions_bike = WideChar($e52f);
mi_directions_boat = WideChar($e532);
mi_directions_bus = WideChar($e530);
mi_directions_car = WideChar($e531);
mi_directions_railway = WideChar($e534);
mi_directions_run = WideChar($e566);
mi_directions_subway = WideChar($e533);
mi_directions_transit = WideChar($e535);
mi_directions_walk = WideChar($e536);
mi_disc_full = WideChar($e610);
mi_dns = WideChar($e875);
mi_do_not_disturb = WideChar($e612);
mi_do_not_disturb_alt = WideChar($e611);
mi_do_not_disturb_off = WideChar($e643);
mi_do_not_disturb_on = WideChar($e644);
mi_dock = WideChar($e30e);
mi_domain = WideChar($e7ee);
mi_done = WideChar($e876);
mi_done_all = WideChar($e877);
mi_donut_large = WideChar($e917);
mi_donut_small = WideChar($e918);
mi_drafts = WideChar($e151);
mi_drag_handle = WideChar($e25d);
mi_drive_eta = WideChar($e613);
mi_dvr = WideChar($e1b2);
mi_edit = WideChar($e3c9);
mi_edit_location = WideChar($e568);
mi_eject = WideChar($e8fb);
mi_email = WideChar($e0be);
mi_enhanced_encryption = WideChar($e63f);
mi_equalizer = WideChar($e01d);
mi_error = WideChar($e000);
mi_error_outline = WideChar($e001);
mi_euro_symbol = WideChar($e926);
mi_ev_station = WideChar($e56d);
mi_event = WideChar($e878);
mi_event_available = WideChar($e614);
mi_event_busy = WideChar($e615);
mi_event_note = WideChar($e616);
mi_event_seat = WideChar($e903);
mi_exit_to_app = WideChar($e879);
mi_expand_less = WideChar($e5ce);
mi_expand_more = WideChar($e5cf);
mi_explicit = WideChar($e01e);
mi_explore = WideChar($e87a);
mi_exposure = WideChar($e3ca);
mi_exposure_neg_1 = WideChar($e3cb);
mi_exposure_neg_2 = WideChar($e3cc);
mi_exposure_plus_1 = WideChar($e3cd);
mi_exposure_plus_2 = WideChar($e3ce);
mi_exposure_zero = WideChar($e3cf);
mi_extension = WideChar($e87b);
mi_face = WideChar($e87c);
mi_fast_forward = WideChar($e01f);
mi_fast_rewind = WideChar($e020);
mi_favorite = WideChar($e87d);
mi_favorite_border = WideChar($e87e);
mi_featured_play_list = WideChar($e06d);
mi_featured_video = WideChar($e06e);
mi_feedback = WideChar($e87f);
mi_fiber_dvr = WideChar($e05d);
mi_fiber_manual_record = WideChar($e061);
mi_fiber_new = WideChar($e05e);
mi_fiber_pin = WideChar($e06a);
mi_fiber_smart_record = WideChar($e062);
mi_file_download = WideChar($e2c4);
mi_file_upload = WideChar($e2c6);
mi_filter = WideChar($e3d3);
mi_filter_1 = WideChar($e3d0);
mi_filter_2 = WideChar($e3d1);
mi_filter_3 = WideChar($e3d2);
mi_filter_4 = WideChar($e3d4);
mi_filter_5 = WideChar($e3d5);
mi_filter_6 = WideChar($e3d6);
mi_filter_7 = WideChar($e3d7);
mi_filter_8 = WideChar($e3d8);
mi_filter_9 = WideChar($e3d9);
mi_filter_9_plus = WideChar($e3da);
mi_filter_b_and_w = WideChar($e3db);
mi_filter_center_focus = WideChar($e3dc);
mi_filter_drama = WideChar($e3dd);
mi_filter_frames = WideChar($e3de);
mi_filter_hdr = WideChar($e3df);
mi_filter_list = WideChar($e152);
mi_filter_none = WideChar($e3e0);
mi_filter_tilt_shift = WideChar($e3e2);
mi_filter_vintage = WideChar($e3e3);
mi_find_in_page = WideChar($e880);
mi_find_replace = WideChar($e881);
mi_fingerprint = WideChar($e90d);
mi_first_page = WideChar($e5dc);
mi_fitness_center = WideChar($eb43);
mi_flag = WideChar($e153);
mi_flare = WideChar($e3e4);
mi_flash_auto = WideChar($e3e5);
mi_flash_off = WideChar($e3e6);
mi_flash_on = WideChar($e3e7);
mi_flight = WideChar($e539);
mi_flight_land = WideChar($e904);
mi_flight_takeoff = WideChar($e905);
mi_flip = WideChar($e3e8);
mi_flip_to_back = WideChar($e882);
mi_flip_to_front = WideChar($e883);
mi_folder = WideChar($e2c7);
mi_folder_open = WideChar($e2c8);
mi_folder_shared = WideChar($e2c9);
mi_folder_special = WideChar($e617);
mi_font_download = WideChar($e167);
mi_format_align_center = WideChar($e234);
mi_format_align_justify = WideChar($e235);
mi_format_align_left = WideChar($e236);
mi_format_align_right = WideChar($e237);
mi_format_bold = WideChar($e238);
mi_format_clear = WideChar($e239);
mi_format_color_fill = WideChar($e23a);
mi_format_color_reset = WideChar($e23b);
mi_format_color_text = WideChar($e23c);
mi_format_indent_decrease = WideChar($e23d);
mi_format_indent_increase = WideChar($e23e);
mi_format_italic = WideChar($e23f);
mi_format_line_spacing = WideChar($e240);
mi_format_list_bulleted = WideChar($e241);
mi_format_list_numbered = WideChar($e242);
mi_format_paint = WideChar($e243);
mi_format_quote = WideChar($e244);
mi_format_shapes = WideChar($e25e);
mi_format_size = WideChar($e245);
mi_format_strikethrough = WideChar($e246);
mi_format_textdirection_l_to_r = WideChar($e247);
mi_format_textdirection_r_to_l = WideChar($e248);
mi_format_underlined = WideChar($e249);
mi_forum = WideChar($e0bf);
mi_forward = WideChar($e154);
mi_forward_10 = WideChar($e056);
mi_forward_30 = WideChar($e057);
mi_forward_5 = WideChar($e058);
mi_free_breakfast = WideChar($eb44);
mi_fullscreen = WideChar($e5d0);
mi_fullscreen_exit = WideChar($e5d1);
mi_functions = WideChar($e24a);
mi_g_translate = WideChar($e927);
mi_gamepad = WideChar($e30f);
mi_games = WideChar($e021);
mi_gavel = WideChar($e90e);
mi_gesture = WideChar($e155);
mi_get_app = WideChar($e884);
mi_gif = WideChar($e908);
mi_golf_course = WideChar($eb45);
mi_gps_fixed = WideChar($e1b3);
mi_gps_not_fixed = WideChar($e1b4);
mi_gps_off = WideChar($e1b5);
mi_grade = WideChar($e885);
mi_gradient = WideChar($e3e9);
mi_grain = WideChar($e3ea);
mi_graphic_eq = WideChar($e1b8);
mi_grid_off = WideChar($e3eb);
mi_grid_on = WideChar($e3ec);
mi_group = WideChar($e7ef);
mi_group_add = WideChar($e7f0);
mi_group_work = WideChar($e886);
mi_hd = WideChar($e052);
mi_hdr_off = WideChar($e3ed);
mi_hdr_on = WideChar($e3ee);
mi_hdr_strong = WideChar($e3f1);
mi_hdr_weak = WideChar($e3f2);
mi_headset = WideChar($e310);
mi_headset_mic = WideChar($e311);
mi_healing = WideChar($e3f3);
mi_hearing = WideChar($e023);
mi_help = WideChar($e887);
mi_help_outline = WideChar($e8fd);
mi_high_quality = WideChar($e024);
mi_highlight = WideChar($e25f);
mi_highlight_off = WideChar($e888);
mi_history = WideChar($e889);
mi_home = WideChar($e88a);
mi_hot_tub = WideChar($eb46);
mi_hotel = WideChar($e53a);
mi_hourglass_empty = WideChar($e88b);
mi_hourglass_full = WideChar($e88c);
mi_http = WideChar($e902);
mi_https = WideChar($e88d);
mi_image = WideChar($e3f4);
mi_image_aspect_ratio = WideChar($e3f5);
mi_import_contacts = WideChar($e0e0);
mi_import_export = WideChar($e0c3);
mi_important_devices = WideChar($e912);
mi_inbox = WideChar($e156);
mi_indeterminate_check_box = WideChar($e909);
mi_info = WideChar($e88e);
mi_info_outline = WideChar($e88f);
mi_input = WideChar($e890);
mi_insert_chart = WideChar($e24b);
mi_insert_comment = WideChar($e24c);
mi_insert_drive_file = WideChar($e24d);
mi_insert_emoticon = WideChar($e24e);
mi_insert_invitation = WideChar($e24f);
mi_insert_link = WideChar($e250);
mi_insert_photo = WideChar($e251);
mi_invert_colors = WideChar($e891);
mi_invert_colors_off = WideChar($e0c4);
mi_iso = WideChar($e3f6);
mi_keyboard = WideChar($e312);
mi_keyboard_arrow_down = WideChar($e313);
mi_keyboard_arrow_left = WideChar($e314);
mi_keyboard_arrow_right = WideChar($e315);
mi_keyboard_arrow_up = WideChar($e316);
mi_keyboard_backspace = WideChar($e317);
mi_keyboard_capslock = WideChar($e318);
mi_keyboard_hide = WideChar($e31a);
mi_keyboard_return = WideChar($e31b);
mi_keyboard_tab = WideChar($e31c);
mi_keyboard_voice = WideChar($e31d);
mi_kitchen = WideChar($eb47);
mi_label = WideChar($e892);
mi_label_outline = WideChar($e893);
mi_landscape = WideChar($e3f7);
mi_language = WideChar($e894);
mi_laptop = WideChar($e31e);
mi_laptop_chromebook = WideChar($e31f);
mi_laptop_mac = WideChar($e320);
mi_laptop_windows = WideChar($e321);
mi_last_page = WideChar($e5dd);
mi_launch = WideChar($e895);
mi_layers = WideChar($e53b);
mi_layers_clear = WideChar($e53c);
mi_leak_add = WideChar($e3f8);
mi_leak_remove = WideChar($e3f9);
mi_lens = WideChar($e3fa);
mi_library_add = WideChar($e02e);
mi_library_books = WideChar($e02f);
mi_library_music = WideChar($e030);
mi_lightbulb_outline = WideChar($e90f);
mi_line_style = WideChar($e919);
mi_line_weight = WideChar($e91a);
mi_linear_scale = WideChar($e260);
mi_link = WideChar($e157);
mi_linked_camera = WideChar($e438);
mi_list = WideChar($e896);
mi_live_help = WideChar($e0c6);
mi_live_tv = WideChar($e639);
mi_local_activity = WideChar($e53f);
mi_local_airport = WideChar($e53d);
mi_local_atm = WideChar($e53e);
mi_local_bar = WideChar($e540);
mi_local_cafe = WideChar($e541);
mi_local_car_wash = WideChar($e542);
mi_local_convenience_store = WideChar($e543);
mi_local_dining = WideChar($e556);
mi_local_drink = WideChar($e544);
mi_local_florist = WideChar($e545);
mi_local_gas_station = WideChar($e546);
mi_local_grocery_store = WideChar($e547);
mi_local_hospital = WideChar($e548);
mi_local_hotel = WideChar($e549);
mi_local_laundry_service = WideChar($e54a);
mi_local_library = WideChar($e54b);
mi_local_mall = WideChar($e54c);
mi_local_movies = WideChar($e54d);
mi_local_offer = WideChar($e54e);
mi_local_parking = WideChar($e54f);
mi_local_pharmacy = WideChar($e550);
mi_local_phone = WideChar($e551);
mi_local_pizza = WideChar($e552);
mi_local_play = WideChar($e553);
mi_local_post_office = WideChar($e554);
mi_local_printshop = WideChar($e555);
mi_local_see = WideChar($e557);
mi_local_shipping = WideChar($e558);
mi_local_taxi = WideChar($e559);
mi_location_city = WideChar($e7f1);
mi_location_disabled = WideChar($e1b6);
mi_location_off = WideChar($e0c7);
mi_location_on = WideChar($e0c8);
mi_location_searching = WideChar($e1b7);
mi_lock = WideChar($e897);
mi_lock_open = WideChar($e898);
mi_lock_outline = WideChar($e899);
mi_looks = WideChar($e3fc);
mi_looks_3 = WideChar($e3fb);
mi_looks_4 = WideChar($e3fd);
mi_looks_5 = WideChar($e3fe);
mi_looks_6 = WideChar($e3ff);
mi_looks_one = WideChar($e400);
mi_looks_two = WideChar($e401);
mi_loop = WideChar($e028);
mi_loupe = WideChar($e402);
mi_low_priority = WideChar($e16d);
mi_loyalty = WideChar($e89a);
mi_mail = WideChar($e158);
mi_mail_outline = WideChar($e0e1);
mi_map = WideChar($e55b);
mi_markunread = WideChar($e159);
mi_markunread_mailbox = WideChar($e89b);
mi_memory = WideChar($e322);
mi_menu = WideChar($e5d2);
mi_merge_type = WideChar($e252);
mi_message = WideChar($e0c9);
mi_mic = WideChar($e029);
mi_mic_none = WideChar($e02a);
mi_mic_off = WideChar($e02b);
mi_mms = WideChar($e618);
mi_mode_comment = WideChar($e253);
mi_mode_edit = WideChar($e254);
mi_monetization_on = WideChar($e263);
mi_money_off = WideChar($e25c);
mi_monochrome_photos = WideChar($e403);
mi_mood = WideChar($e7f2);
mi_mood_bad = WideChar($e7f3);
mi_more = WideChar($e619);
mi_more_horiz = WideChar($e5d3);
mi_more_vert = WideChar($e5d4);
mi_motorcycle = WideChar($e91b);
mi_mouse = WideChar($e323);
mi_move_to_inbox = WideChar($e168);
mi_movie = WideChar($e02c);
mi_movie_creation = WideChar($e404);
mi_movie_filter = WideChar($e43a);
mi_multiline_chart = WideChar($e6df);
mi_music_note = WideChar($e405);
mi_music_video = WideChar($e063);
mi_my_location = WideChar($e55c);
mi_nature = WideChar($e406);
mi_nature_people = WideChar($e407);
mi_navigate_before = WideChar($e408);
mi_navigate_next = WideChar($e409);
mi_navigation = WideChar($e55d);
mi_near_me = WideChar($e569);
mi_network_cell = WideChar($e1b9);
mi_network_check = WideChar($e640);
mi_network_locked = WideChar($e61a);
mi_network_wifi = WideChar($e1ba);
mi_new_releases = WideChar($e031);
mi_next_week = WideChar($e16a);
mi_nfc = WideChar($e1bb);
mi_no_encryption = WideChar($e641);
mi_no_sim = WideChar($e0cc);
mi_not_interested = WideChar($e033);
mi_note = WideChar($e06f);
mi_note_add = WideChar($e89c);
mi_notifications = WideChar($e7f4);
mi_notifications_active = WideChar($e7f7);
mi_notifications_none = WideChar($e7f5);
mi_notifications_off = WideChar($e7f6);
mi_notifications_paused = WideChar($e7f8);
mi_offline_pin = WideChar($e90a);
mi_ondemand_video = WideChar($e63a);
mi_opacity = WideChar($e91c);
mi_open_in_browser = WideChar($e89d);
mi_open_in_new = WideChar($e89e);
mi_open_with = WideChar($e89f);
mi_pages = WideChar($e7f9);
mi_pageview = WideChar($e8a0);
mi_palette = WideChar($e40a);
mi_pan_tool = WideChar($e925);
mi_panorama = WideChar($e40b);
mi_panorama_fish_eye = WideChar($e40c);
mi_panorama_horizontal = WideChar($e40d);
mi_panorama_vertical = WideChar($e40e);
mi_panorama_wide_angle = WideChar($e40f);
mi_party_mode = WideChar($e7fa);
mi_pause = WideChar($e034);
mi_pause_circle_filled = WideChar($e035);
mi_pause_circle_outline = WideChar($e036);
mi_payment = WideChar($e8a1);
mi_people = WideChar($e7fb);
mi_people_outline = WideChar($e7fc);
mi_perm_camera_mic = WideChar($e8a2);
mi_perm_contact_calendar = WideChar($e8a3);
mi_perm_data_setting = WideChar($e8a4);
mi_perm_device_information = WideChar($e8a5);
mi_perm_identity = WideChar($e8a6);
mi_perm_media = WideChar($e8a7);
mi_perm_phone_msg = WideChar($e8a8);
mi_perm_scan_wifi = WideChar($e8a9);
mi_person = WideChar($e7fd);
mi_person_add = WideChar($e7fe);
mi_person_outline = WideChar($e7ff);
mi_person_pin = WideChar($e55a);
mi_person_pin_circle = WideChar($e56a);
mi_personal_video = WideChar($e63b);
mi_pets = WideChar($e91d);
mi_phone = WideChar($e0cd);
mi_phone_android = WideChar($e324);
mi_phone_bluetooth_speaker = WideChar($e61b);
mi_phone_forwarded = WideChar($e61c);
mi_phone_in_talk = WideChar($e61d);
mi_phone_iphone = WideChar($e325);
mi_phone_locked = WideChar($e61e);
mi_phone_missed = WideChar($e61f);
mi_phone_paused = WideChar($e620);
mi_phonelink = WideChar($e326);
mi_phonelink_erase = WideChar($e0db);
mi_phonelink_lock = WideChar($e0dc);
mi_phonelink_off = WideChar($e327);
mi_phonelink_ring = WideChar($e0dd);
mi_phonelink_setup = WideChar($e0de);
mi_photo = WideChar($e410);
mi_photo_album = WideChar($e411);
mi_photo_camera = WideChar($e412);
mi_photo_filter = WideChar($e43b);
mi_photo_library = WideChar($e413);
mi_photo_size_select_actual = WideChar($e432);
mi_photo_size_select_large = WideChar($e433);
mi_photo_size_select_small = WideChar($e434);
mi_picture_as_pdf = WideChar($e415);
mi_picture_in_picture = WideChar($e8aa);
mi_picture_in_picture_alt = WideChar($e911);
mi_pie_chart = WideChar($e6c4);
mi_pie_chart_outlined = WideChar($e6c5);
mi_pin_drop = WideChar($e55e);
mi_place = WideChar($e55f);
mi_play_arrow = WideChar($e037);
mi_play_circle_filled = WideChar($e038);
mi_play_circle_outline = WideChar($e039);
mi_play_for_work = WideChar($e906);
mi_playlist_add = WideChar($e03b);
mi_playlist_add_check = WideChar($e065);
mi_playlist_play = WideChar($e05f);
mi_plus_one = WideChar($e800);
mi_poll = WideChar($e801);
mi_polymer = WideChar($e8ab);
mi_pool = WideChar($eb48);
mi_portable_wifi_off = WideChar($e0ce);
mi_portrait = WideChar($e416);
mi_power = WideChar($e63c);
mi_power_input = WideChar($e336);
mi_power_settings_new = WideChar($e8ac);
mi_pregnant_woman = WideChar($e91e);
mi_present_to_all = WideChar($e0df);
mi_print = WideChar($e8ad);
mi_priority_high = WideChar($e645);
mi_public = WideChar($e80b);
mi_publish = WideChar($e255);
mi_query_builder = WideChar($e8ae);
mi_question_answer = WideChar($e8af);
mi_queue = WideChar($e03c);
mi_queue_music = WideChar($e03d);
mi_queue_play_next = WideChar($e066);
mi_radio = WideChar($e03e);
mi_radio_button_checked = WideChar($e837);
mi_radio_button_unchecked = WideChar($e836);
mi_rate_review = WideChar($e560);
mi_receipt = WideChar($e8b0);
mi_recent_actors = WideChar($e03f);
mi_record_voice_over = WideChar($e91f);
mi_redeem = WideChar($e8b1);
mi_redo = WideChar($e15a);
mi_refresh = WideChar($e5d5);
mi_remove = WideChar($e15b);
mi_remove_circle = WideChar($e15c);
mi_remove_circle_outline = WideChar($e15d);
mi_remove_from_queue = WideChar($e067);
mi_remove_red_eye = WideChar($e417);
mi_remove_shopping_cart = WideChar($e928);
mi_reorder = WideChar($e8fe);
mi_repeat = WideChar($e040);
mi_repeat_one = WideChar($e041);
mi_replay = WideChar($e042);
mi_replay_10 = WideChar($e059);
mi_replay_30 = WideChar($e05a);
mi_replay_5 = WideChar($e05b);
mi_reply = WideChar($e15e);
mi_reply_all = WideChar($e15f);
mi_report = WideChar($e160);
mi_report_problem = WideChar($e8b2);
mi_restaurant = WideChar($e56c);
mi_restaurant_menu = WideChar($e561);
mi_restore = WideChar($e8b3);
mi_restore_page = WideChar($e929);
mi_ring_volume = WideChar($e0d1);
mi_room = WideChar($e8b4);
mi_room_service = WideChar($eb49);
mi_rotate_90_degrees_ccw = WideChar($e418);
mi_rotate_left = WideChar($e419);
mi_rotate_right = WideChar($e41a);
mi_rounded_corner = WideChar($e920);
mi_router = WideChar($e328);
mi_rowing = WideChar($e921);
mi_rss_feed = WideChar($e0e5);
mi_rv_hookup = WideChar($e642);
mi_satellite = WideChar($e562);
mi_save = WideChar($e161);
mi_scanner = WideChar($e329);
mi_schedule = WideChar($e8b5);
mi_school = WideChar($e80c);
mi_screen_lock_landscape = WideChar($e1be);
mi_screen_lock_portrait = WideChar($e1bf);
mi_screen_lock_rotation = WideChar($e1c0);
mi_screen_rotation = WideChar($e1c1);
mi_screen_share = WideChar($e0e2);
mi_sd_card = WideChar($e623);
mi_sd_storage = WideChar($e1c2);
mi_search = WideChar($e8b6);
mi_security = WideChar($e32a);
mi_select_all = WideChar($e162);
mi_send = WideChar($e163);
mi_sentiment_dissatisfied = WideChar($e811);
mi_sentiment_neutral = WideChar($e812);
mi_sentiment_satisfied = WideChar($e813);
mi_sentiment_very_dissatisfied = WideChar($e814);
mi_sentiment_very_satisfied = WideChar($e815);
mi_settings = WideChar($e8b8);
mi_settings_applications = WideChar($e8b9);
mi_settings_backup_restore = WideChar($e8ba);
mi_settings_bluetooth = WideChar($e8bb);
mi_settings_brightness = WideChar($e8bd);
mi_settings_cell = WideChar($e8bc);
mi_settings_ethernet = WideChar($e8be);
mi_settings_input_antenna = WideChar($e8bf);
mi_settings_input_component = WideChar($e8c0);
mi_settings_input_composite = WideChar($e8c1);
mi_settings_input_hdmi = WideChar($e8c2);
mi_settings_input_svideo = WideChar($e8c3);
mi_settings_overscan = WideChar($e8c4);
mi_settings_phone = WideChar($e8c5);
mi_settings_power = WideChar($e8c6);
mi_settings_remote = WideChar($e8c7);
mi_settings_system_daydream = WideChar($e1c3);
mi_settings_voice = WideChar($e8c8);
mi_share = WideChar($e80d);
mi_shop = WideChar($e8c9);
mi_shop_two = WideChar($e8ca);
mi_shopping_basket = WideChar($e8cb);
mi_shopping_cart = WideChar($e8cc);
mi_short_text = WideChar($e261);
mi_show_chart = WideChar($e6e1);
mi_shuffle = WideChar($e043);
mi_signal_cellular_4_bar = WideChar($e1c8);
mi_signal_cellular_connected_no_internet_4_bar = WideChar($e1cd);
mi_signal_cellular_no_sim = WideChar($e1ce);
mi_signal_cellular_null = WideChar($e1cf);
mi_signal_cellular_off = WideChar($e1d0);
mi_signal_wifi_4_bar = WideChar($e1d8);
mi_signal_wifi_4_bar_lock = WideChar($e1d9);
mi_signal_wifi_off = WideChar($e1da);
mi_sim_card = WideChar($e32b);
mi_sim_card_alert = WideChar($e624);
mi_skip_next = WideChar($e044);
mi_skip_previous = WideChar($e045);
mi_slideshow = WideChar($e41b);
mi_slow_motion_video = WideChar($e068);
mi_smartphone = WideChar($e32c);
mi_smoke_free = WideChar($eb4a);
mi_smoking_rooms = WideChar($eb4b);
mi_sms = WideChar($e625);
mi_sms_failed = WideChar($e626);
mi_snooze = WideChar($e046);
mi_sort = WideChar($e164);
mi_sort_by_alpha = WideChar($e053);
mi_spa = WideChar($eb4c);
mi_space_bar = WideChar($e256);
mi_speaker = WideChar($e32d);
mi_speaker_group = WideChar($e32e);
mi_speaker_notes = WideChar($e8cd);
mi_speaker_notes_off = WideChar($e92a);
mi_speaker_phone = WideChar($e0d2);
mi_spellcheck = WideChar($e8ce);
mi_star = WideChar($e838);
mi_star_border = WideChar($e83a);
mi_star_half = WideChar($e839);
mi_stars = WideChar($e8d0);
mi_stay_current_landscape = WideChar($e0d3);
mi_stay_current_portrait = WideChar($e0d4);
mi_stay_primary_landscape = WideChar($e0d5);
mi_stay_primary_portrait = WideChar($e0d6);
mi_stop = WideChar($e047);
mi_stop_screen_share = WideChar($e0e3);
mi_storage = WideChar($e1db);
mi_store = WideChar($e8d1);
mi_store_mall_directory = WideChar($e563);
mi_straighten = WideChar($e41c);
mi_streetview = WideChar($e56e);
mi_strikethrough_s = WideChar($e257);
mi_style = WideChar($e41d);
mi_subdirectory_arrow_left = WideChar($e5d9);
mi_subdirectory_arrow_right = WideChar($e5da);
mi_subject = WideChar($e8d2);
mi_subscriptions = WideChar($e064);
mi_subtitles = WideChar($e048);
mi_subway = WideChar($e56f);
mi_supervisor_account = WideChar($e8d3);
mi_surround_sound = WideChar($e049);
mi_swap_calls = WideChar($e0d7);
mi_swap_horiz = WideChar($e8d4);
mi_swap_vert = WideChar($e8d5);
mi_swap_vertical_circle = WideChar($e8d6);
mi_switch_camera = WideChar($e41e);
mi_switch_video = WideChar($e41f);
mi_sync = WideChar($e627);
mi_sync_disabled = WideChar($e628);
mi_sync_problem = WideChar($e629);
mi_system_update = WideChar($e62a);
mi_system_update_alt = WideChar($e8d7);
mi_tab = WideChar($e8d8);
mi_tab_unselected = WideChar($e8d9);
mi_tablet = WideChar($e32f);
mi_tablet_android = WideChar($e330);
mi_tablet_mac = WideChar($e331);
mi_tag_faces = WideChar($e420);
mi_tap_and_play = WideChar($e62b);
mi_terrain = WideChar($e564);
mi_text_fields = WideChar($e262);
mi_text_format = WideChar($e165);
mi_textsms = WideChar($e0d8);
mi_texture = WideChar($e421);
mi_theaters = WideChar($e8da);
mi_thumb_down = WideChar($e8db);
mi_thumb_up = WideChar($e8dc);
mi_thumbs_up_down = WideChar($e8dd);
mi_time_to_leave = WideChar($e62c);
mi_timelapse = WideChar($e422);
mi_timeline = WideChar($e922);
mi_timer = WideChar($e425);
mi_timer_10 = WideChar($e423);
mi_timer_3 = WideChar($e424);
mi_timer_off = WideChar($e426);
mi_title = WideChar($e264);
mi_toc = WideChar($e8de);
mi_today = WideChar($e8df);
mi_toll = WideChar($e8e0);
mi_tonality = WideChar($e427);
mi_touch_app = WideChar($e913);
mi_toys = WideChar($e332);
mi_track_changes = WideChar($e8e1);
mi_traffic = WideChar($e565);
mi_train = WideChar($e570);
mi_tram = WideChar($e571);
mi_transfer_within_a_station = WideChar($e572);
mi_transform = WideChar($e428);
mi_translate = WideChar($e8e2);
mi_trending_down = WideChar($e8e3);
mi_trending_flat = WideChar($e8e4);
mi_trending_up = WideChar($e8e5);
mi_tune = WideChar($e429);
mi_turned_in = WideChar($e8e6);
mi_turned_in_not = WideChar($e8e7);
mi_tv = WideChar($e333);
mi_unarchive = WideChar($e169);
mi_undo = WideChar($e166);
mi_unfold_less = WideChar($e5d6);
mi_unfold_more = WideChar($e5d7);
mi_update = WideChar($e923);
mi_usb = WideChar($e1e0);
mi_verified_user = WideChar($e8e8);
mi_vertical_align_bottom = WideChar($e258);
mi_vertical_align_center = WideChar($e259);
mi_vertical_align_top = WideChar($e25a);
mi_vibration = WideChar($e62d);
mi_video_call = WideChar($e070);
mi_video_label = WideChar($e071);
mi_video_library = WideChar($e04a);
mi_videocam = WideChar($e04b);
mi_videocam_off = WideChar($e04c);
mi_videogame_asset = WideChar($e338);
mi_view_agenda = WideChar($e8e9);
mi_view_array = WideChar($e8ea);
mi_view_carousel = WideChar($e8eb);
mi_view_column = WideChar($e8ec);
mi_view_comfy = WideChar($e42a);
mi_view_compact = WideChar($e42b);
mi_view_day = WideChar($e8ed);
mi_view_headline = WideChar($e8ee);
mi_view_list = WideChar($e8ef);
mi_view_module = WideChar($e8f0);
mi_view_quilt = WideChar($e8f1);
mi_view_stream = WideChar($e8f2);
mi_view_week = WideChar($e8f3);
mi_vignette = WideChar($e435);
mi_visibility = WideChar($e8f4);
mi_visibility_off = WideChar($e8f5);
mi_voice_chat = WideChar($e62e);
mi_voicemail = WideChar($e0d9);
mi_volume_down = WideChar($e04d);
mi_volume_mute = WideChar($e04e);
mi_volume_off = WideChar($e04f);
mi_volume_up = WideChar($e050);
mi_vpn_key = WideChar($e0da);
mi_vpn_lock = WideChar($e62f);
mi_wallpaper = WideChar($e1bc);
mi_warning = WideChar($e002);
mi_watch = WideChar($e334);
mi_watch_later = WideChar($e924);
mi_wb_auto = WideChar($e42c);
mi_wb_cloudy = WideChar($e42d);
mi_wb_incandescent = WideChar($e42e);
mi_wb_iridescent = WideChar($e436);
mi_wb_sunny = WideChar($e430);
mi_wc = WideChar($e63d);
mi_web = WideChar($e051);
mi_web_asset = WideChar($e069);
mi_weekend = WideChar($e16b);
mi_whatshot = WideChar($e80e);
mi_widgets = WideChar($e1bd);
mi_wifi = WideChar($e63e);
mi_wifi_lock = WideChar($e1e1);
mi_wifi_tethering = WideChar($e1e2);
mi_work = WideChar($e8f9);
mi_wrap_text = WideChar($e25b);
mi_youtube_searched_for = WideChar($e8fa);
mi_zoom_in = WideChar($e8ff);
mi_zoom_out = WideChar($e900);
mi_zoom_out_map = WideChar($e56b);
procedure MaterialIconsFontAssign(aControl: TFmxObject);
implementation
uses
FMX.Graphics;
procedure MaterialIconsFontAssign(aControl: TFmxObject);
var
aTextSettings: ITextSettings;
begin
if Supports(aControl, ITextSettings, aTextSettings) then
begin
aTextSettings.StyledSettings := [];
aTextSettings.TextSettings.Font.Family := MaterialIconsFontName;
end;
end;
end.
|
unit InflatablesList_ItemShopParsingSettings_IO;
{$INCLUDE '.\InflatablesList_defs.inc'}
interface
uses
Classes,
AuxTypes,
InflatablesList_ItemShopParsingSettings_Search;
const
IL_SHOPPARSSETT_SIGNATURE = UInt32($53524150); // PARS
IL_SHOPPARSSETT_STREAMSTRUCTURE_00000000 = UInt32($00000000);
IL_SHOPPARSSETT_STREAMSTRUCTURE_00000001 = UInt32($00000001);
IL_SHOPPARSSETT_STREAMSTRUCTURE_SAVE = IL_SHOPPARSSETT_STREAMSTRUCTURE_00000001;
type
TILItemShopParsingSettings_IO = class(TILItemShopParsingSettings_Search)
protected
fFNSaveToStream: procedure(Stream: TStream) of object;
fFNLoadFromStream: procedure(Stream: TStream) of object;
procedure InitSaveFunctions(Struct: UInt32); virtual; abstract;
procedure InitLoadFunctions(Struct: UInt32); virtual; abstract;
procedure Save(Stream: TStream; Struct: UInt32); virtual;
procedure Load(Stream: TStream; Struct: UInt32); virtual;
public
procedure SaveToStream(Stream: TStream); virtual;
procedure LoadFromStream(Stream: TStream); virtual;
procedure SaveToFile(const FileName: String); virtual;
procedure LoadFromFile(const FileName: String); virtual;
end;
implementation
uses
SysUtils,
StrRect, BinaryStreaming;
procedure TILItemShopParsingSettings_IO.Save(Stream: TStream; Struct: UInt32);
begin
InitSaveFunctions(Struct);
fFNSaveToStream(Stream);
end;
//------------------------------------------------------------------------------
procedure TILItemShopParsingSettings_IO.Load(Stream: TStream; Struct: UInt32);
begin
InitLoadFunctions(Struct);
fFNLoadFromStream(Stream);
end;
//==============================================================================
procedure TILItemShopParsingSettings_IO.SaveToStream(Stream: TStream);
begin
Stream_WriteUInt32(Stream,IL_SHOPPARSSETT_SIGNATURE);
Stream_WriteUInt32(Stream,IL_SHOPPARSSETT_STREAMSTRUCTURE_SAVE);
Save(Stream,IL_SHOPPARSSETT_STREAMSTRUCTURE_SAVE);
end;
//------------------------------------------------------------------------------
procedure TILItemShopParsingSettings_IO.LoadFromStream(Stream: TStream);
begin
If Stream_ReadUInt32(Stream) = IL_SHOPPARSSETT_SIGNATURE then
Load(Stream,Stream_ReadUInt32(Stream))
else
raise Exception.Create('TILItemShopParsingSettings_IO.LoadFromStream: Invalid stream.');
end;
//------------------------------------------------------------------------------
procedure TILItemShopParsingSettings_IO.SaveToFile(const FileName: String);
var
FileStream: TMemoryStream;
begin
FileStream := TMemoryStream.Create;
try
SaveToStream(FileStream);
FileStream.SaveToFile(StrToRTL(FileName));
finally
FileStream.Free;
end;
end;
//------------------------------------------------------------------------------
procedure TILItemShopParsingSettings_IO.LoadFromFile(const FileName: String);
var
FileStream: TMemoryStream;
begin
FileStream := TMemoryStream.Create;
try
FileStream.LoadFromFile(StrToRTL(FileName));
FileStream.Seek(0,soBeginning);
LoadFromStream(FileStream);
finally
FileStream.Free;
end;
end;
end.
|
// ***************************************************************
// madGraphics.pas version: 1.0 · date: 2001-03-04
// -------------------------------------------------------------
// gray scaling, smooth stretching, alpha blending, ...
// -------------------------------------------------------------
// Copyright (C) 1999 - 2001 www.madshi.net, All Rights Reserved
// ***************************************************************
unit madGraphics;
{$I mad.inc}
{$R-}{$Q-}
interface
uses Windows, Graphics;
// ***************************************************************
type TGrayPercent = (gp100, gp75, gp50, gp0);
procedure GrayScale (bmp: TBitmap; percent: TGrayPercent = gp100);
// ***************************************************************
type TStretchQuality = (sqLow, sqHigh, sqVeryHigh);
procedure StretchBitmap (srcBmp, dstBmp : TBitmap;
srcMsk, dstMsk : TBitmap;
quality : TStretchQuality = sqHigh); overload;
procedure StretchBitmap (bmp, msk : TBitmap;
newWidth : integer;
newHeight : integer;
quality : TStretchQuality = sqHigh); overload;
// ***************************************************************
procedure AlphaBlend (src1, src2, dst : TBitmap;
alpha : cardinal = 128); overload;
procedure AlphaBlend (src, dst : TBitmap;
alpha : cardinal = 128;
msk : TBitmap = nil;
x : integer = 0;
y : integer = 0 ); overload;
// ***************************************************************
procedure Draw (imageList, index : cardinal;
dst : TBitmap;
x : integer = 0;
y : integer = 0;
width : integer = 0;
height : integer = 0;
grayPercent : TGrayPercent = gp0;
alpha : cardinal = 256;
stretchQuality : TStretchQuality = sqHigh); overload;
procedure Draw (bmp, msk : TBitmap;
dst : TBitmap;
x : integer = 0;
y : integer = 0;
width : integer = 0;
height : integer = 0;
grayPercent : TGrayPercent = gp0;
alpha : cardinal = 256;
stretchQuality : TStretchQuality = sqHigh); overload;
// ***************************************************************
implementation
uses SysUtils, Classes, Math, CommCtrl;
// ***************************************************************
function GetPixelFormat(bmp: TBitmap) : integer;
var ds : TDibSection;
begin
result := 0;
if GetObject(bmp.handle, sizeOf(TDibSection), @ds) <> 0 then begin
result := ds.dsBmih.biBitCount;
if result = 16 then
if ds.dsBitFields[2] = $1F then begin
if (ds.dsBitFields[1] = $3E0) and (ds.dsBitFields[0] = $7C00) then
result := 15
else if (ds.dsBitFields[1] <> $7E0) or (ds.dsBitFields[0] <> $F800) then
result := 0;
end else
result := 0;
end;
end;
function ForcePixelFormat(const bmps: array of TBitmap; pixelFormat: TPixelFormat) : boolean;
var i1 : integer;
begin
result := true;
for i1 := 0 to high(bmps) do
if (bmps[i1].PixelFormat <> pixelFormat) and
((pixelFormat <> pf15bit) or (GetPixelFormat(bmps[i1]) <> 15)) then begin
bmps[i1].PixelFormat := pixelFormat;
if (bmps[i1].PixelFormat <> pixelFormat) and
((pixelFormat <> pf15bit) or (GetPixelFormat(bmps[i1]) <> 15)) then begin
result := false;
exit;
end;
end;
end;
// ***************************************************************
type
TXtab32 = array [0..2*255 + 4*255 + 1*255] of integer;
TXtab16 = array [0..2*031 + 2*063 + 1*031] of word;
TXtab15 = array [0..2*031 + 4*031 + 1*031] of word;
var
xtab32 : array [TGrayPercent] of TXtab32;
xtab16 : array [TGrayPercent] of TXtab16;
xtab15 : array [TGrayPercent] of TXtab15;
xtab32Ready : array [TGrayPercent] of boolean = (false, false, false, false);
xtab16Ready : array [TGrayPercent] of boolean = (false, false, false, false);
xtab15Ready : array [TGrayPercent] of boolean = (false, false, false, false);
//32bit: 160ms -> 100ms 130 125
//24bit: 140ms -> 120ms 165 155
//16bit: 245ms (355ms for the non-asm variant) -> 100ms 130 140
//15bit: not supported by my graphics card -> 100ms 130 170
procedure GrayScale(bmp: TBitmap; percent: TGrayPercent = gp100);
procedure GrayScaleLine15_100(line: pointer; width: integer; var xtab);
asm
push edi
push ebx
mov edi, eax
mov ebx, edx
shl ebx, 1
add ebx, eax
@0:
movzx eax, word[edi]
mov edx, eax
and eax, $000003E0
shr eax, 3
and edx, $0000001F
add eax, edx
movzx edx, word[edi]
shr edx, 9
and edx, $FE
add eax, edx
mov ax, [eax*2+ecx]
mov [edi], ax
add edi, 2
cmp ebx, edi
jnz @0
pop ebx
pop edi
end;
procedure GrayScaleLine15_75(line: pointer; width: integer; var xtab);
asm
push edi
push esi
push ebx
mov edi, eax
mov esi, edx
shl esi, 1
add esi, eax
@0:
movzx eax, word[edi]
mov edx, eax
mov ebx, eax
shr ebx, 2
and ebx, $1CE7
and edx, $0000001F
and eax, $000003E0
shr eax, 3
add edx, eax
movzx eax, word[edi]
shr eax, 9
and edx, $FE
add edx, eax
add bx, [edx*2+ecx]
mov [edi], bx
add edi, 2
cmp esi, edi
jnz @0
pop ebx
pop esi
pop edi
end;
procedure GrayScaleLine15_50(line: pointer; width: integer; var xtab);
asm
push edi
push esi
push ebx
mov edi, eax
mov esi, edx
shl esi, 1
add esi, eax
@0:
movzx eax, word[edi]
mov edx, eax
mov ebx, eax
shr ebx, 1
and ebx, $3DEF
and edx, $0000001F
and eax, $000003E0
shr eax, 3
add edx, eax
movzx eax, word[edi]
shr eax, 9
and edx, $FE
add edx, eax
add bx, [edx*2+ecx]
mov [edi], bx
add edi, 2
cmp esi, edi
jnz @0
pop ebx
pop esi
pop edi
end;
procedure GrayScaleLine16_100(line: pointer; width: integer; var xtab);
asm
push edi
push ebx
mov edi, eax
mov ebx, edx
shl ebx, 1
add ebx, eax
@0:
movzx eax, word[edi]
mov edx, eax
and eax, $000007E0
shr eax, 4
and edx, $0000001F
add eax, edx
movzx edx, word[edi]
shr edx, 10
and edx, $FE
add eax, edx
mov ax, [eax*2+ecx]
mov [edi], ax
add edi, 2
cmp ebx, edi
jnz @0
pop ebx
pop edi
end;
procedure GrayScaleLine16_75(line: pointer; width: integer; var xtab);
asm
push edi
push esi
push ebx
mov edi, eax
mov esi, edx
shl esi, 1
add esi, eax
@0:
movzx eax, word[edi]
mov edx, eax
mov ebx, eax
shr ebx, 2
and ebx, $39E7
and edx, $0000001F
and eax, $000007E0
shr eax, 4
add edx, eax
movzx eax, word[edi]
shr eax, 10
and edx, $FE
add edx, eax
add bx, [edx*2+ecx]
mov [edi], bx
add edi, 2
cmp esi, edi
jnz @0
pop ebx
pop esi
pop edi
end;
procedure GrayScaleLine16_50(line: pointer; width: integer; var xtab);
asm
push edi
push esi
push ebx
mov edi, eax
mov esi, edx
shl esi, 1
add esi, eax
@0:
movzx eax, word[edi]
mov edx, eax
mov ebx, eax
shr ebx, 1
and ebx, $7BEF
and edx, $0000001F
and eax, $000007E0
shr eax, 4
add edx, eax
movzx eax, word[edi]
shr eax, 10
and edx, $FE
add edx, eax
add bx, [edx*2+ecx]
mov [edi], bx
add edi, 2
cmp esi, edi
jnz @0
pop ebx
pop esi
pop edi
end;
procedure GrayScaleLine24_100(line: pointer; width: integer; var xtab);
asm
push edi
push ebx
mov edi, eax
mov ebx, edx
add ebx, edx
add ebx, edx
add ebx, eax
@0:
movzx edx, byte[edi+2]
movzx eax, byte[edi+1]
shl eax, 2
add edx, eax
movzx eax, byte[edi]
add edx, eax
add edx, eax
mov edx, [edx*4+ecx]
mov [edi], dl
mov [edi+1], dl
mov [edi+2], dl
add edi, 3
cmp ebx, edi
jnz @0
pop ebx
pop edi
end;
procedure GrayScaleLine24_75(line: pointer; width: integer; var xtab);
asm
push edi
push esi
push ebx
mov edi, eax
mov esi, edx
add esi, edx
add esi, edx
add esi, eax
@0:
movzx eax, byte[edi+2]
mov ebx, [edi]
shr ebx, 2
and ebx, $003F3F3F
movzx edx, byte[edi+1]
shl edx, 2
add eax, edx
movzx edx, byte[edi]
add eax, edx
add eax, edx
add ebx, [eax*4+ecx]
mov [edi], bl
shr ebx, 8
mov [edi+1], bl
mov [edi+2], bh
add edi, 3
cmp esi, edi
jnz @0
pop ebx
pop esi
pop edi
end;
procedure GrayScaleLine24_50(line: pointer; width: integer; var xtab);
asm
push edi
push esi
push ebx
mov edi, eax
mov esi, edx
add esi, edx
add esi, edx
add esi, eax
@0:
movzx eax, byte[edi+2]
mov ebx, [edi]
shr ebx, 1
and ebx, $007F7F7F
movzx edx, byte[edi+1]
shl edx, 2
add eax, edx
movzx edx, byte[edi]
add eax, edx
add eax, edx
add ebx, [eax*4+ecx]
mov [edi], bl
shr ebx, 8
mov [edi+1], bl
mov [edi+2], bh
add edi, 3
cmp esi, edi
jnz @0
pop ebx
pop esi
pop edi
end;
procedure GrayScaleLine32_100(line: pointer; width: integer; var xtab);
asm
push edi
push ebx
mov edi, eax
mov ebx, edx
shl ebx, 2
add ebx, eax
@0:
movzx eax, byte[edi+2]
movzx edx, byte[edi+1]
shl edx, 2
add eax, edx
movzx edx, byte[edi]
add eax, edx
add eax, edx
mov eax, [eax*4+ecx]
mov [edi], eax
add edi, 4
cmp ebx, edi
jnz @0
pop ebx
pop edi
end;
procedure GrayScaleLine32_75(line: pointer; width: integer; var xtab);
asm
push edi
push esi
push ebx
mov edi, eax
mov esi, edx
shl esi, 2
add esi, eax
@0:
movzx eax, byte[edi+2]
mov ebx, [edi]
shr ebx, 2
and ebx, $003F3F3F
movzx edx, byte[edi+1]
shl edx, 2
add eax, edx
movzx edx, byte[edi]
add eax, edx
add eax, edx
add ebx, [eax*4+ecx]
mov [edi], ebx
add edi, 4
cmp esi, edi
jnz @0
pop ebx
pop esi
pop edi
end;
procedure GrayScaleLine32_50(line: pointer; width: integer; var xtab);
asm
push edi
push esi
push ebx
mov edi, eax
mov esi, edx
shl esi, 2
add esi, eax
@0:
movzx eax, byte[edi+2]
mov ebx, [edi]
shr ebx, 1
and ebx, $007F7F7F
movzx edx, byte[edi+1]
shl edx, 2
add eax, edx
movzx edx, byte[edi]
add eax, edx
add eax, edx
add ebx, [eax*4+ecx]
mov [edi], ebx
add edi, 4
cmp esi, edi
jnz @0
pop ebx
pop esi
pop edi
end;
procedure CheckXTab32(gp: TGrayPercent);
var i1 : integer;
gray : integer;
begin
if not xtab32Ready[gp] then begin
for i1 := 0 to high(xtab32[gp]) do begin
gray := round(i1 / 7);
case gp of
gp50 : gray := gray div 2;
gp75 : gray := gray - gray div 4;
end;
xtab32[gp][i1] := gray shl 16 + gray shl 8 + gray;
end;
xtab32Ready[gp] := true;
end;
end;
procedure CheckXTab16(gp: TGrayPercent);
var i1 : integer;
gray : integer;
begin
if not xtab16Ready[gp] then begin
for i1 := 0 to high(xtab16[gp]) do begin
gray := round(i1 * 31 / high(xtab16[gp]));
case gp of
gp50 : gray := gray div 2;
gp75 : gray := gray - gray div 4;
end;
xtab16[gp][i1] := gray shl 11 + gray shl 6 + gray;
end;
xtab16Ready[gp] := true;
end;
end;
procedure CheckXTab15(gp: TGrayPercent);
var i1 : integer;
gray : integer;
begin
if not xtab15Ready[gp] then begin
for i1 := 0 to high(xtab15[gp]) do begin
gray := round(i1 * 31 / high(xtab15[gp]));
case gp of
gp50 : gray := gray div 2;
gp75 : gray := gray - gray div 4;
end;
xtab15[gp][i1] := gray shl 10 + gray shl 5 + gray;
end;
xtab15Ready[gp] := true;
end;
end;
var iy, iw, ih : integer;
line : PByteArray;
lineDif : integer;
casei : integer;
begin
if percent <> gp0 then
with bmp do begin
iw := Width;
ih := Height;
if (iw > 0) and (ih > 0) then begin
if GetPixelFormat(bmp) < 15 then PixelFormat := pf32bit;
case GetPixelFormat(bmp) of
15 : begin casei := $150; CheckXTab15(percent) end;
16 : begin casei := $160; CheckXTab16(percent) end;
24 : begin casei := $240; CheckXTab32(percent) end;
32 : begin casei := $320; CheckXtab32(percent) end;
else exit;
end;
inc(casei, ord(percent));
line := ScanLine[0];
if ih > 1 then lineDif := integer(ScanLine[1]) - integer(line)
else lineDif := 0;
for iy := 0 to Height - 1 do begin
case casei of
$150 : GrayScaleLine15_100(line, iw, xtab15[gp100]);
$151 : GrayScaleLine15_75 (line, iw, xtab15[gp75 ]);
$152 : GrayScaleLine15_50 (line, iw, xtab15[gp50 ]);
$160 : GrayScaleLine16_100(line, iw, xtab16[gp100]);
$161 : GrayScaleLine16_75 (line, iw, xtab16[gp75 ]);
$162 : GrayScaleLine16_50 (line, iw, xtab16[gp50 ]);
$240 : GrayScaleLine24_100(line, iw, xtab32[gp100]);
$241 : GrayScaleLine24_75 (line, iw, xtab32[gp75 ]);
$242 : GrayScaleLine24_50 (line, iw, xtab32[gp50 ]);
$320 : GrayScaleLine32_100(line, iw, xtab32[gp100]);
$321 : GrayScaleLine32_75 (line, iw, xtab32[gp75 ]);
$322 : GrayScaleLine32_50 (line, iw, xtab32[gp50 ]);
end;
inc(integer(line), lineDif);
end;
end;
end;
end;
// ***************************************************************
var MitchellScaleListCache : TList = nil;
MitchellScaleListSection : TRTLCriticalSection;
procedure StretchBitmap(srcBmp, dstBmp : TBitmap;
srcMsk, dstMsk : TBitmap;
quality : TStretchQuality = sqHigh);
type
TContributorPixel = record
pixel : integer; // source pixel
weight : integer; // weight of this source pixel
end;
TPContributorPixel = ^TContributorPixel;
// list of source pixels contributing to the destination pixel
TContributorPixels = record
itemCount : integer;
items : TPContributorPixel;
end;
// list for the full width/height of a bitmap
TContributorList = array [0..0] of TContributorPixels;
TPContributorList = ^TContributorList;
// full list structure including src and dst information
TMitchellScaleList = record
src, dst : integer;
contributorList : TPContributorList;
end;
procedure GetContributorList(var result: TPContributorList; src_, dst_: integer);
var scale, center, weight : single;
capacity : integer;
i1, i2 : integer;
pcp : TPContributorPixel;
msl : ^TMitchellScaleList;
begin
if MitchellScaleListCache = nil then
InitializeCriticalSection(MitchellScaleListSection);
EnterCriticalSection(MitchellScaleListSection);
try
if MitchellScaleListCache = nil then
MitchellScaleListCache := TList.Create;
for i1 := 0 to MitchellScaleListCache.Count - 1 do
with TMitchellScaleList(pointer(MitchellScaleListCache[i1])^) do
if (src = src_) and (dst = dst_) then begin
result := contributorList;
exit;
end;
GetMem(result, dst_ * sizeof(TContributorPixels));
if dst_ < src_ then begin
scale := dst_ / src_;
capacity := (4 * src_ div dst_ + 1) * sizeOf(TContributorPixel);
for i1 := 0 to dst_ - 1 do
with result^[i1] do begin
GetMem(items, capacity);
pcp := items;
for i2 := ((i1 - 2) * src_ - dst_ + 1) div dst_ to ((i1 + 2) * src_ + dst_ - 1) div dst_ do begin
weight := abs(i1 - i2 * scale);
if weight < 2 then begin
if weight < 1 then
pcp^.weight := round(((( 7 / 6 * weight - 2) * weight ) * weight + 8 / 9) * scale * $10000)
else pcp^.weight := round((((- 7 / 18 * weight + 2) * weight - 10 / 3) * weight + 16 / 9) * scale * $10000);
if i2 < 0 then pcp^.pixel := - i2
else if i2 >= src_ then pcp^.pixel := src_ * 2 - i2 - 1
else pcp^.pixel := i2;
inc(pcp);
end;
end;
itemCount := (integer(pcp) - integer(items)) div sizeOf(TContributorPixel) - 1;
end;
end else begin
scale := src_ / dst_;
for i1 := 0 to dst_ - 1 do
with result^[i1] do begin
GetMem(items, 5 * sizeOf(TContributorPixel));
pcp := items;
center := i1 * scale;
for i2 := (i1 * src_ - 3 * dst_ + 1) div dst_ to (i1 * src_ + 3 * dst_ - 1) div dst_ do begin
weight := abs(center - i2);
if weight < 2 then begin
if weight < 1 then
pcp^.weight := round(((( 7 / 6 * weight - 2) * weight ) * weight + 8 / 9) * $10000)
else pcp^.weight := round((((- 7 / 18 * weight + 2) * weight - 10 / 3) * weight + 16 / 9) * $10000);
if i2 < 0 then pcp^.pixel := - i2
else if i2 >= src_ then pcp^.pixel := src_ * 2 - i2 - 1
else pcp^.pixel := i2;
inc(pcp);
end;
end;
itemCount := (integer(pcp) - integer(items)) div sizeOf(TContributorPixel) - 1;
end;
end;
New(msl);
msl^.src := src_;
msl^.dst := dst_;
msl^.contributorList := result;
MitchellScaleListCache.Add(msl);
finally LeaveCriticalSection(MitchellScaleListSection) end;
end;
procedure MitchellResampling15; // 370 / 195
var ix, iy, ic : integer;
weight : integer;
clx, cly : TPContributorList;
fr, fg, fb, fm : integer;
sbBits, dbBits : integer;
smBits, dmBits : integer;
sbDif, dbDif : integer;
smDif, dmDif : integer;
sbLine, tbBuf : PWordArray;
smLine, tmBuf : PByteArray;
dbPix : ^word;
dmPix : ^byte;
pcp : TPContributorPixel;
dw1 : integer;
begin
GetContributorList(clx, srcBmp.Width, dstBmp.Width );
GetContributorList(cly, srcBmp.Height, dstBmp.Height);
tbBuf := AllocMem(srcBmp.Height * 2 + srcBmp.Height * 1);
sbBits := integer(srcBmp.ScanLine[0]);
dbBits := integer(dstBmp.ScanLine[0]);
if srcBmp.Height > 1 then
sbDif := integer(srcBmp.ScanLine[1]) - sbBits
else sbDif := 0;
if dstBmp.Height > 1 then
dbDif := integer(dstBmp.ScanLine[1]) - dbBits
else dbDif := 0;
if srcMsk <> nil then begin
tmBuf := pointer(integer(tbBuf) + srcBmp.Height * 2);
smBits := integer(srcMsk.ScanLine[0]);
dmBits := integer(dstMsk.ScanLine[0]);
if srcMsk.Height > 1 then
smDif := integer(srcMsk.ScanLine[1]) - smBits
else smDif := 0;
if dstMsk.Height > 1 then
dmDif := integer(dstMsk.ScanLine[1]) - dmBits
else dmDif := 0;
for ix := 0 to dstBmp.Width - 1 do begin
dbPix := pointer(tbBuf );
dmPix := pointer(tmBuf );
sbLine := pointer(sbBits);
smLine := pointer(smBits);
for iy := 0 to srcBmp.Height - 1 do begin
fr := 0;
fg := 0;
fb := 0;
fm := 0;
pcp := clx^[ix].items;
for ic := 0 to clx^[ix].itemCount do begin
weight := (pcp^.weight * (256 - smLine^[pcp^.pixel])) div 256;
inc(fm, weight);
dw1 := sbLine^[pcp^.pixel];
inc(fr, (dw1 shr 10 ) * weight);
inc(fg, (dw1 and $03E0) * weight);
inc(fb, (dw1 and $001F) * weight);
inc(pcp);
end;
if fr < 0 then fr := 0
else if fr > $001F0000 then fr := $7C00
else fr := (fr shr 6) and $7C00;
if fg < 0 then
else if fg > $03E00000 then inc(fr, $03E0)
else inc(fr, (fg shr 16) and $03E0);
if fb < 0 then
else if fb > $001F0000 then inc(fr, $001F)
else inc(fr, fb shr 16);
dbPix^ := word(fr);
inc(dbPix);
if fm < 0 then dmPix^ := 255
else if fm > $0000FF00 then dmPix^ := 0
else dmPix^ := 255 - fm shr 8;
inc(dmPix);
inc(integer(sbLine), sbDif);
inc(integer(smLine), smDif);
end;
dbPix := pointer(dbBits + ix * 2);
dmPix := pointer(dmBits + ix );
for iy := 0 to dstBmp.Height - 1 do begin
fr := 0;
fg := 0;
fb := 0;
fm := 0;
pcp := cly^[iy].items;
for ic := 0 to cly^[iy].itemCount do begin
weight := (pcp^.weight * (256 - tmBuf^[pcp^.pixel])) div 256;
inc(fm, weight);
dw1 := tbBuf^[pcp^.pixel];
inc(fr, (dw1 shr 10 ) * weight);
inc(fg, (dw1 and $03E0) * weight);
inc(fb, (dw1 and $001F) * weight);
inc(pcp);
end;
if fr < 0 then fr := 0
else if fr > $001F0000 then fr := $7C00
else fr := (fr shr 6) and $7C00;
if fg < 0 then
else if fg > $03E00000 then inc(fr, $03E0)
else inc(fr, (fg shr 16) and $03E0);
if fb < 0 then
else if fb > $001F0000 then inc(fr, $001F)
else inc(fr, fb shr 16);
dbPix^ := word(fr);
inc(integer(dbPix), dbDif);
if fm < 0 then dmPix^ := 255
else if fm > $0000FF00 then dmPix^ := 0
else dmPix^ := 255 - fm shr 8;
inc(dmPix, dmDif);
end;
end;
end else
for ix := 0 to dstBmp.Width - 1 do begin
dbPix := pointer(tbBuf );
sbLine := pointer(sbBits);
for iy := 0 to srcBmp.Height - 1 do begin
fr := 0;
fg := 0;
fb := 0;
pcp := clx^[ix].items;
for ic := 0 to clx^[ix].itemCount do begin
weight := pcp^.weight;
dw1 := sbLine^[pcp^.pixel];
inc(fr, (dw1 shr 10 ) * weight);
inc(fg, (dw1 and $03E0) * weight);
inc(fb, (dw1 and $001F) * weight);
inc(pcp);
end;
if fr < 0 then fr := 0
else if fr > $001F0000 then fr := $7C00
else fr := (fr shr 6) and $7C00;
if fg < 0 then
else if fg > $03E00000 then inc(fr, $03E0)
else inc(fr, (fg shr 16) and $03E0);
if fb < 0 then
else if fb > $001F0000 then inc(fr, $001F)
else inc(fr, fb shr 16);
dbPix^ := word(fr);
inc(dbPix);
inc(integer(sbLine), sbDif);
end;
dbPix := pointer(dbBits + ix * 2);
for iy := 0 to dstBmp.Height - 1 do begin
fr := 0;
fg := 0;
fb := 0;
pcp := cly^[iy].items;
for ic := 0 to cly^[iy].itemCount do begin
weight := pcp^.weight;
dw1 := tbBuf^[pcp^.pixel];
inc(fr, (dw1 shr 10 ) * weight);
inc(fg, (dw1 and $03E0) * weight);
inc(fb, (dw1 and $001F) * weight);
inc(pcp);
end;
if fr < 0 then fr := 0
else if fr > $001F0000 then fr := $7C00
else fr := (fr shr 6) and $7C00;
if fg < 0 then
else if fg > $03E00000 then inc(fr, $03E0)
else inc(fr, (fg shr 16) and $03E0);
if fb < 0 then
else if fb > $001F0000 then inc(fr, $001F)
else inc(fr, fb shr 16);
dbPix^ := word(fr);
inc(integer(dbPix), dbDif);
end;
end;
FreeMem(tbBuf);
end;
procedure MitchellResampling16; // 370 / 195
var ix, iy, ic : integer;
weight : integer;
clx, cly : TPContributorList;
fr, fg, fb, fm : integer;
sbBits, dbBits : integer;
smBits, dmBits : integer;
sbDif, dbDif : integer;
smDif, dmDif : integer;
sbLine, tbBuf : PWordArray;
smLine, tmBuf : PByteArray;
dbPix : ^word;
dmPix : ^byte;
pcp : TPContributorPixel;
dw1 : integer;
begin
GetContributorList(clx, srcBmp.Width, dstBmp.Width );
GetContributorList(cly, srcBmp.Height, dstBmp.Height);
tbBuf := AllocMem(srcBmp.Height * 2 + srcBmp.Height * 1);
sbBits := integer(srcBmp.ScanLine[0]);
dbBits := integer(dstBmp.ScanLine[0]);
if srcBmp.Height > 1 then
sbDif := integer(srcBmp.ScanLine[1]) - sbBits
else sbDif := 0;
if dstBmp.Height > 1 then
dbDif := integer(dstBmp.ScanLine[1]) - dbBits
else dbDif := 0;
if srcMsk <> nil then begin
tmBuf := pointer(integer(tbBuf) + srcBmp.Height * 2);
smBits := integer(srcMsk.ScanLine[0]);
dmBits := integer(dstMsk.ScanLine[0]);
if srcMsk.Height > 1 then
smDif := integer(srcMsk.ScanLine[1]) - smBits
else smDif := 0;
if dstMsk.Height > 1 then
dmDif := integer(dstMsk.ScanLine[1]) - dmBits
else dmDif := 0;
for ix := 0 to dstBmp.Width - 1 do begin
dbPix := pointer(tbBuf );
dmPix := pointer(tmBuf );
sbLine := pointer(sbBits);
smLine := pointer(smBits);
for iy := 0 to srcBmp.Height - 1 do begin
fr := 0;
fg := 0;
fb := 0;
fm := 0;
pcp := clx^[ix].items;
for ic := 0 to clx^[ix].itemCount do begin
weight := (pcp^.weight * (256 - smLine^[pcp^.pixel])) div 256;
inc(fm, weight);
dw1 := sbLine^[pcp^.pixel];
inc(fr, (dw1 shr 11 ) * weight);
inc(fg, (dw1 and $07E0) * weight);
inc(fb, (dw1 and $001F) * weight);
inc(pcp);
end;
if fr < 0 then fr := 0
else if fr > $001F0000 then fr := $F800
else fr := (fr shr 5) and $F800;
if fg < 0 then
else if fg > $07E00000 then inc(fr, $07E0)
else inc(fr, (fg shr 16) and $07E0);
if fb < 0 then
else if fb > $001F0000 then inc(fr, $001F)
else inc(fr, fb shr 16);
dbPix^ := word(fr);
inc(dbPix);
if fm < 0 then dmPix^ := 255
else if fm > $0000FF00 then dmPix^ := 0
else dmPix^ := 255 - fm shr 8;
inc(dmPix);
inc(integer(sbLine), sbDif);
inc(integer(smLine), smDif);
end;
dbPix := pointer(dbBits + ix * 2);
dmPix := pointer(dmBits + ix );
for iy := 0 to dstBmp.Height - 1 do begin
fr := 0;
fg := 0;
fb := 0;
fm := 0;
pcp := cly^[iy].items;
for ic := 0 to cly^[iy].itemCount do begin
weight := (pcp^.weight * (256 - tmBuf^[pcp^.pixel])) div 256;
inc(fm, weight);
dw1 := tbBuf^[pcp^.pixel];
inc(fr, (dw1 shr 11 ) * weight);
inc(fg, (dw1 and $07E0) * weight);
inc(fb, (dw1 and $001F) * weight);
inc(pcp);
end;
if fr < 0 then fr := 0
else if fr > $001F0000 then fr := $F800
else fr := (fr shr 5) and $F800;
if fg < 0 then
else if fg > $07E00000 then inc(fr, $07E0)
else inc(fr, (fg shr 16) and $07E0);
if fb < 0 then
else if fb > $001F0000 then inc(fr, $001F)
else inc(fr, fb shr 16);
dbPix^ := word(fr);
inc(integer(dbPix), dbDif);
if fm < 0 then dmPix^ := 255
else if fm > $0000FF00 then dmPix^ := 0
else dmPix^ := 255 - fm shr 8;
inc(dmPix, dmDif);
end;
end;
end else
for ix := 0 to dstBmp.Width - 1 do begin
dbPix := pointer(tbBuf );
sbLine := pointer(sbBits);
for iy := 0 to srcBmp.Height - 1 do begin
fr := 0;
fg := 0;
fb := 0;
pcp := clx^[ix].items;
for ic := 0 to clx^[ix].itemCount do begin
weight := pcp^.weight;
dw1 := sbLine^[pcp^.pixel];
inc(fr, (dw1 shr 11 ) * weight);
inc(fg, (dw1 and $07E0) * weight);
inc(fb, (dw1 and $001F) * weight);
inc(pcp);
end;
if fr < 0 then fr := 0
else if fr > $001F0000 then fr := $F800
else fr := (fr shr 5) and $F800;
if fg < 0 then
else if fg > $07E00000 then inc(fr, $07E0)
else inc(fr, (fg shr 16) and $07E0);
if fb < 0 then
else if fb > $001F0000 then inc(fr, $001F)
else inc(fr, fb shr 16);
dbPix^ := word(fr);
inc(dbPix);
inc(integer(sbLine), sbDif);
end;
dbPix := pointer(dbBits + ix * 2);
for iy := 0 to dstBmp.Height - 1 do begin
fr := 0;
fg := 0;
fb := 0;
pcp := cly^[iy].items;
for ic := 0 to cly^[iy].itemCount do begin
weight := pcp^.weight;
dw1 := tbBuf^[pcp^.pixel];
inc(fr, (dw1 shr 11 ) * weight);
inc(fg, (dw1 and $07E0) * weight);
inc(fb, (dw1 and $001F) * weight);
inc(pcp);
end;
if fr < 0 then fr := 0
else if fr > $001F0000 then fr := $F800
else fr := (fr shr 5) and $F800;
if fg < 0 then
else if fg > $07E00000 then inc(fr, $07E0)
else inc(fr, (fg shr 16) and $07E0);
if fb < 0 then
else if fb > $001F0000 then inc(fr, $001F)
else inc(fr, fb shr 16);
dbPix^ := word(fr);
inc(integer(dbPix), dbDif);
end;
end;
FreeMem(tbBuf);
end;
procedure MitchellResampling24; // 385 / 200
type TRGB = packed record r, g, b: byte; end;
var ix, iy, ic : integer;
weight : integer;
clx, cly : TPContributorList;
fr, fg, fb, fm : integer;
sbBits, dbBits : integer;
smBits, dmBits : integer;
sbDif, dbDif : integer;
smDif, dmDif : integer;
sbLine, tbBuf : PByteArray;
smLine, tmBuf : PByteArray;
dbPix : ^byte;
dmPix : ^byte;
pcp : TPContributorPixel;
begin
GetContributorList(clx, srcBmp.Width, dstBmp.Width );
GetContributorList(cly, srcBmp.Height, dstBmp.Height);
tbBuf := AllocMem(srcBmp.Height * 4 + srcBmp.Height * 1);
sbBits := integer(srcBmp.ScanLine[0]);
dbBits := integer(dstBmp.ScanLine[0]);
if srcBmp.Height > 1 then
sbDif := integer(srcBmp.ScanLine[1]) - sbBits
else sbDif := 0;
if dstBmp.Height > 1 then
dbDif := integer(dstBmp.ScanLine[1]) - dbBits - 2
else dbDif := 0;
if srcMsk <> nil then begin
tmBuf := pointer(integer(tbBuf) + srcBmp.Height * 4);
smBits := integer(srcMsk.ScanLine[0]);
dmBits := integer(dstMsk.ScanLine[0]);
if srcMsk.Height > 1 then
smDif := integer(srcMsk.ScanLine[1]) - smBits
else smDif := 0;
if dstMsk.Height > 1 then
dmDif := integer(dstMsk.ScanLine[1]) - dmBits
else dmDif := 0;
for ix := 0 to dstBmp.Width - 1 do begin
dbPix := pointer(tbBuf );
sbLine := pointer(sbBits);
dmPix := pointer(tmBuf );
smLine := pointer(smBits);
for iy := 0 to srcBmp.Height - 1 do begin
fr := 0;
fg := 0;
fb := 0;
fm := 0;
pcp := clx^[ix].items;
for ic := 0 to clx^[ix].itemCount do begin
weight := (pcp^.weight * (256 - smLine^[pcp^.pixel])) div 256;
inc(fm, weight);
with TRGB(pointer(@sbLine^[pcp^.pixel * 3])^) do begin
inc(fr, r * weight);
inc(fg, g * weight);
inc(fb, b * weight);
end;
inc(pcp);
end;
if fr < 0 then dbPix^ := 0
else if fr > $FF0000 then dbPix^ := 255
else dbPix^ := fr shr 16;
inc(dbPix);
if fg < 0 then dbPix^ := 0
else if fg > $FF0000 then dbPix^ := 255
else dbPix^ := fg shr 16;
inc(dbPix);
if fb < 0 then dbPix^ := 0
else if fb > $FF0000 then dbPix^ := 255
else dbPix^ := fb shr 16;
inc(dbPix, 2);
if fm < 0 then dmPix^ := 255
else if fm > $00FF00 then dmPix^ := 0
else dmPix^ := 255 - fm shr 8;
inc(dmPix);
inc(integer(sbLine), sbDif);
inc(integer(smLine), smDif);
end;
dbPix := pointer(dbBits + ix * 3);
dmPix := pointer(dmBits + ix );
for iy := 0 to dstBmp.Height - 1 do begin
fr := 0;
fg := 0;
fb := 0;
fm := 0;
pcp := cly^[iy].items;
for ic := 0 to cly^[iy].itemCount do begin
weight := (pcp^.weight * (256 - tmBuf^[pcp^.pixel])) div 256;
inc(fm, weight);
with TRGB(pointer(@tbBuf^[pcp^.pixel * 4])^) do begin
inc(fr, r * weight);
inc(fg, g * weight);
inc(fb, b * weight);
end;
inc(pcp);
end;
if fr < 0 then dbPix^ := 0
else if fr > $FF0000 then dbPix^ := 255
else dbPix^ := fr shr 16;
inc(dbPix);
if fg < 0 then dbPix^ := 0
else if fg > $FF0000 then dbPix^ := 255
else dbPix^ := fg shr 16;
inc(dbPix);
if fb < 0 then dbPix^ := 0
else if fb > $FF0000 then dbPix^ := 255
else dbPix^ := fb shr 16;
inc(dbPix, dbDif);
if fm < 0 then dmPix^ := 255
else if fm > $00FF00 then dmPix^ := 0
else dmPix^ := 255 - fm shr 8;
inc(dmPix, dmDif);
end;
end;
end else
for ix := 0 to dstBmp.Width - 1 do begin
dbPix := pointer(tbBuf );
sbLine := pointer(sbBits);
for iy := 0 to srcBmp.Height - 1 do begin
fr := 0;
fg := 0;
fb := 0;
pcp := clx^[ix].items;
for ic := 0 to clx^[ix].itemCount do begin
weight := pcp^.weight;
with TRGB(pointer(@sbLine^[pcp^.pixel * 3])^) do begin
inc(fr, r * weight);
inc(fg, g * weight);
inc(fb, b * weight);
end;
inc(pcp);
end;
if fr < 0 then dbPix^ := 0
else if fr > $FF0000 then dbPix^ := 255
else dbPix^ := fr shr 16;
inc(dbPix);
if fg < 0 then dbPix^ := 0
else if fg > $FF0000 then dbPix^ := 255
else dbPix^ := fg shr 16;
inc(dbPix);
if fb < 0 then dbPix^ := 0
else if fb > $FF0000 then dbPix^ := 255
else dbPix^ := fb shr 16;
inc(dbPix, 2);
inc(integer(sbLine), sbDif);
end;
dbPix := pointer(dbBits + ix * 3);
for iy := 0 to dstBmp.Height - 1 do begin
fr := 0;
fg := 0;
fb := 0;
pcp := cly^[iy].items;
for ic := 0 to cly^[iy].itemCount do begin
weight := pcp^.weight;
with TRGB(pointer(@tbBuf^[pcp^.pixel * 4])^) do begin
inc(fr, r * weight);
inc(fg, g * weight);
inc(fb, b * weight);
end;
inc(pcp);
end;
if fr < 0 then dbPix^ := 0
else if fr > $FF0000 then dbPix^ := 255
else dbPix^ := fr shr 16;
inc(dbPix);
if fg < 0 then dbPix^ := 0
else if fg > $FF0000 then dbPix^ := 255
else dbPix^ := fg shr 16;
inc(dbPix);
if fb < 0 then dbPix^ := 0
else if fb > $FF0000 then dbPix^ := 255
else dbPix^ := fb shr 16;
inc(dbPix, dbDif);
end;
end;
FreeMem(tbBuf);
end;
procedure MitchellResampling32; // 375 / 200
type TRGB = packed record r, g, b: byte; end;
var ix, iy, ic : integer;
weight : integer;
clx, cly : TPContributorList;
fr, fg, fb, fm : integer;
sbBits, dbBits : integer;
smBits, dmBits : integer;
sbDif, dbDif : integer;
smDif, dmDif : integer;
sbLine, tbBuf : PByteArray;
smLine, tmBuf : PByteArray;
dbPix : ^byte;
dmPix : ^byte;
pcp : TPContributorPixel;
begin
GetContributorList(clx, srcBmp.Width, dstBmp.Width );
GetContributorList(cly, srcBmp.Height, dstBmp.Height);
tbBuf := AllocMem(srcBmp.Height * 4 + srcBmp.Height * 1);
sbBits := integer(srcBmp.ScanLine[0]);
dbBits := integer(dstBmp.ScanLine[0]);
if srcBmp.Height > 1 then
sbDif := integer(srcBmp.ScanLine[1]) - sbBits
else sbDif := 0;
if dstBmp.Height > 1 then
dbDif := integer(dstBmp.ScanLine[1]) - dbBits - 2
else dbDif := 0;
if srcMsk <> nil then begin
tmBuf := pointer(integer(tbBuf) + srcBmp.Height * 4);
smBits := integer(srcMsk.ScanLine[0]);
dmBits := integer(dstMsk.ScanLine[0]);
if srcMsk.Height > 1 then
smDif := integer(srcMsk.ScanLine[1]) - smBits
else smDif := 0;
if dstMsk.Height > 1 then
dmDif := integer(dstMsk.ScanLine[1]) - dmBits
else dmDif := 0;
for ix := 0 to dstBmp.Width - 1 do begin
dbPix := pointer(tbBuf );
sbLine := pointer(sbBits);
dmPix := pointer(tmBuf );
smLine := pointer(smBits);
for iy := 0 to srcBmp.Height - 1 do begin
fr := 0;
fg := 0;
fb := 0;
fm := 0;
pcp := clx^[ix].items;
for ic := 0 to clx^[ix].itemCount do begin
weight := (pcp^.weight * (256 - smLine^[pcp^.pixel])) div 256;
inc(fm, weight);
with TRGB(pointer(@sbLine^[pcp^.pixel * 4])^) do begin
inc(fr, r * weight);
inc(fg, g * weight);
inc(fb, b * weight);
end;
inc(pcp);
end;
if fr < 0 then dbPix^ := 0
else if fr > $FF0000 then dbPix^ := 255
else dbPix^ := fr shr 16;
inc(dbPix);
if fg < 0 then dbPix^ := 0
else if fg > $FF0000 then dbPix^ := 255
else dbPix^ := fg shr 16;
inc(dbPix);
if fb < 0 then dbPix^ := 0
else if fb > $FF0000 then dbPix^ := 255
else dbPix^ := fb shr 16;
inc(dbPix, 2);
if fm < 0 then dmPix^ := 255
else if fm > $00FF00 then dmPix^ := 0
else dmPix^ := 255 - fm shr 8;
inc(dmPix);
inc(integer(sbLine), sbDif);
inc(integer(smLine), smDif);
end;
dbPix := pointer(dbBits + ix * 4);
dmPix := pointer(dmBits + ix );
for iy := 0 to dstBmp.Height - 1 do begin
fr := 0;
fg := 0;
fb := 0;
fm := 0;
pcp := cly^[iy].items;
for ic := 0 to cly^[iy].itemCount do begin
weight := (pcp^.weight * (256 - tmBuf^[pcp^.pixel])) div 256;
inc(fm, weight);
with TRGB(pointer(@tbBuf^[pcp^.pixel * 4])^) do begin
inc(fr, r * weight);
inc(fg, g * weight);
inc(fb, b * weight);
end;
inc(pcp);
end;
if fr < 0 then dbPix^ := 0
else if fr > $FF0000 then dbPix^ := 255
else dbPix^ := fr shr 16;
inc(dbPix);
if fg < 0 then dbPix^ := 0
else if fg > $FF0000 then dbPix^ := 255
else dbPix^ := fg shr 16;
inc(dbPix);
if fb < 0 then dbPix^ := 0
else if fb > $FF0000 then dbPix^ := 255
else dbPix^ := fb shr 16;
inc(dbPix, dbDif);
if fm < 0 then dmPix^ := 255
else if fm > $00FF00 then dmPix^ := 0
else dmPix^ := 255 - fm shr 8;
inc(dmPix, dmDif);
end;
end;
end else
for ix := 0 to dstBmp.Width - 1 do begin
dbPix := pointer(tbBuf );
sbLine := pointer(sbBits);
for iy := 0 to srcBmp.Height - 1 do begin
fr := 0;
fg := 0;
fb := 0;
pcp := clx^[ix].items;
for ic := 0 to clx^[ix].itemCount do begin
weight := pcp^.weight;
with TRGB(pointer(@sbLine^[pcp^.pixel * 4])^) do begin
inc(fr, r * weight);
inc(fg, g * weight);
inc(fb, b * weight);
end;
inc(pcp);
end;
if fr < 0 then dbPix^ := 0
else if fr > $FF0000 then dbPix^ := 255
else dbPix^ := fr shr 16;
inc(dbPix);
if fg < 0 then dbPix^ := 0
else if fg > $FF0000 then dbPix^ := 255
else dbPix^ := fg shr 16;
inc(dbPix);
if fb < 0 then dbPix^ := 0
else if fb > $FF0000 then dbPix^ := 255
else dbPix^ := fb shr 16;
inc(dbPix, 2);
inc(integer(sbLine), sbDif);
end;
dbPix := pointer(dbBits + ix * 4);
for iy := 0 to dstBmp.Height - 1 do begin
fr := 0;
fg := 0;
fb := 0;
pcp := cly^[iy].items;
for ic := 0 to cly^[iy].itemCount do begin
weight := pcp^.weight;
with TRGB(pointer(@tbBuf^[pcp^.pixel * 4])^) do begin
inc(fr, r * weight);
inc(fg, g * weight);
inc(fb, b * weight);
end;
inc(pcp);
end;
if fr < 0 then dbPix^ := 0
else if fr > $FF0000 then dbPix^ := 255
else dbPix^ := fr shr 16;
inc(dbPix);
if fg < 0 then dbPix^ := 0
else if fg > $FF0000 then dbPix^ := 255
else dbPix^ := fg shr 16;
inc(dbPix);
if fb < 0 then dbPix^ := 0
else if fb > $FF0000 then dbPix^ := 255
else dbPix^ := fb shr 16;
inc(dbPix, dbDif);
end;
end;
FreeMem(tbBuf);
end;
procedure Bilinear15; // 2820 -> 540
var ix, iy : integer;
x, y, xdif, ydif : integer;
xp1, xp2, yp : integer;
wy, wyi, wx : integer;
w11, w21, w12, w22 : integer;
sbBits, sbLine1, sbLine2 : integer;
smBits, smLine1, smLine2 : PByteArray;
dbLine : integer;
dmLine : ^byte;
sbLineDif, dbLineDif : integer;
smLineDif, dmLineDif : integer;
w : integer;
begin
y := 0;
xdif := (srcBmp.Width shl 16) div dstBmp.Width;
ydif := (srcBmp.Height shl 16) div dstBmp.Height;
sbBits := integer(srcBmp.ScanLine[0]);
if srcBmp.Height > 1 then
sbLineDif := integer(srcBmp.ScanLine[1]) - sbBits
else sbLineDif := 0;
dbLine := integer(dstBmp.ScanLine[0]);
if dstBmp.Height > 1 then
dbLineDif := integer(dstBmp.ScanLine[1]) - dbLine - 2 * dstBmp.Width
else dbLineDif := 0;
if srcMsk <> nil then begin
smBits := srcMsk.ScanLine[0];
if srcMsk.Height > 1 then
smLineDif := integer(srcMsk.ScanLine[1]) - integer(smBits)
else smLineDif := 0;
dmLine := dstMsk.ScanLine[0];
if dstMsk.Height > 1 then
dmLineDif := integer(dstMsk.ScanLine[1]) - integer(dmLine) - 1 * dstBmp.Width
else dmLineDif := 0;
end else begin
smBits := nil;
smLineDif := 0;
dmLine := nil;
dmLineDif := 0;
end;
w := srcBmp.Width - 1;
for iy := 0 to dstBmp.Height - 1 do begin
yp := y shr 16;
integer(sbLine1) := integer(sbBits) + sbLineDif * yp;
integer(smLine1) := integer(smBits) + smLineDif * yp;
if yp < srcBmp.Height - 1 then begin
integer(sbLine2) := integer(sbLine1) + sbLineDif;
integer(smLine2) := integer(smLine1) + smLineDif;
end else begin
sbLine2 := sbLine1;
smLine2 := smLine1;
end;
x := 0;
wy := y and $FFFF;
wyi := (not y) and $FFFF;
for ix := 0 to dstBmp.Width - 1 do begin
xp1 := x shr 16;
if xp1 < w then xp2 := xp1 + 1
else xp2 := xp1;
wx := x and $FFFF;
w21 := (wyi * wx) shr 16; w11 := wyi - w21;
w22 := (wy * wx) shr 16; w12 := wy - w22;
if smLine1 <> nil then begin
w11 := (w11 * (256 - smLine1^[xp1])) shr 8;
w21 := (w21 * (256 - smLine1^[xp2])) shr 8;
w12 := (w12 * (256 - smLine2^[xp1])) shr 8;
w22 := (w22 * (256 - smLine2^[xp2])) shr 8;
dmLine^ := 255 - byte((w11 + w21 + w12 + w22) shr 8);
end;
xp1 := xp1 * 2;
xp2 := xp2 * 2;
PWord(dbLine)^ := ( ( ( (PWord(sbLine1 + xp1)^ and $001F) * w11 + (PWord(sbLine1 + xp2)^ and $001F) * w21 +
(PWord(sbLine2 + xp1)^ and $001F) * w12 + (PWord(sbLine2 + xp2)^ and $001F) * w22 ) shr 16) and $001F) or
( ( ( (PWord(sbLine1 + xp1)^ and $03E0) * w11 + (PWord(sbLine1 + xp2)^ and $03E0) * w21 +
(PWord(sbLine2 + xp1)^ and $03E0) * w12 + (PWord(sbLine2 + xp2)^ and $03E0) * w22 ) shr 16) and $03E0) or
( ( ( (PWord(sbLine1 + xp1)^ and $7C00) * w11 + (PWord(sbLine1 + xp2)^ and $7C00) * w21 +
(PWord(sbLine2 + xp1)^ and $7C00) * w12 + (PWord(sbLine2 + xp2)^ and $7C00) * w22 ) shr 16) and $7C00);
inc(dbLine, 2);
inc(dmLine);
inc(x, xdif);
end;
inc(integer(dbLine), dbLineDif);
inc(integer(dmLine), dmLineDif);
inc(y, ydif);
end;
end;
procedure Bilinear16; // 2440 -> 540
var ix, iy : integer;
x, y, xdif, ydif : integer;
xp1, xp2, yp : integer;
wy, wyi, wx : integer;
w11, w21, w12, w22 : integer;
sbBits, sbLine1, sbLine2 : integer;
smBits, smLine1, smLine2 : PByteArray;
dbLine : integer;
dmLine : ^byte;
sbLineDif, dbLineDif : integer;
smLineDif, dmLineDif : integer;
w : integer;
begin
y := 0;
xdif := (srcBmp.Width shl 16) div dstBmp.Width;
ydif := (srcBmp.Height shl 16) div dstBmp.Height;
sbBits := integer(srcBmp.ScanLine[0]);
if srcBmp.Height > 1 then
sbLineDif := integer(srcBmp.ScanLine[1]) - sbBits
else sbLineDif := 0;
dbLine := integer(dstBmp.ScanLine[0]);
if dstBmp.Height > 1 then
dbLineDif := integer(dstBmp.ScanLine[1]) - dbLine - 2 * dstBmp.Width
else dbLineDif := 0;
if srcMsk <> nil then begin
smBits := srcMsk.ScanLine[0];
if srcMsk.Height > 1 then
smLineDif := integer(srcMsk.ScanLine[1]) - integer(smBits)
else smLineDif := 0;
dmLine := dstMsk.ScanLine[0];
if dstMsk.Height > 1 then
dmLineDif := integer(dstMsk.ScanLine[1]) - integer(dmLine) - 1 * dstBmp.Width
else dmLineDif := 0;
end else begin
smBits := nil;
smLineDif := 0;
dmLine := nil;
dmLineDif := 0;
end;
w := srcBmp.Width - 1;
for iy := 0 to dstBmp.Height - 1 do begin
yp := y shr 16;
integer(sbLine1) := integer(sbBits) + sbLineDif * yp;
integer(smLine1) := integer(smBits) + smLineDif * yp;
if yp < srcBmp.Height - 1 then begin
integer(sbLine2) := integer(sbLine1) + sbLineDif;
integer(smLine2) := integer(smLine1) + smLineDif;
end else begin
sbLine2 := sbLine1;
smLine2 := smLine1;
end;
x := 0;
wy := y and $FFFF;
wyi := (not y) and $FFFF;
for ix := 0 to dstBmp.Width - 1 do begin
xp1 := x shr 16;
if xp1 < w then xp2 := xp1 + 1
else xp2 := xp1;
wx := x and $FFFF;
w21 := (wyi * wx) shr 16; w11 := wyi - w21;
w22 := (wy * wx) shr 16; w12 := wy - w22;
if smLine1 <> nil then begin
w11 := (w11 * (256 - smLine1^[xp1])) shr 8;
w21 := (w21 * (256 - smLine1^[xp2])) shr 8;
w12 := (w12 * (256 - smLine2^[xp1])) shr 8;
w22 := (w22 * (256 - smLine2^[xp2])) shr 8;
dmLine^ := 255 - byte((w11 + w21 + w12 + w22) shr 8);
end;
xp1 := xp1 * 2;
xp2 := xp2 * 2;
PWord(dbLine)^ := ( ( ( (PWord(sbLine1 + xp1)^ and $001F) * w11 + (PWord(sbLine1 + xp2)^ and $001F) * w21 +
(PWord(sbLine2 + xp1)^ and $001F) * w12 + (PWord(sbLine2 + xp2)^ and $001F) * w22 ) shr 16) and $001F) or
( ( ( (PWord(sbLine1 + xp1)^ and $07E0) * w11 + (PWord(sbLine1 + xp2)^ and $07E0) * w21 +
(PWord(sbLine2 + xp1)^ and $07E0) * w12 + (PWord(sbLine2 + xp2)^ and $07E0) * w22 ) shr 16) and $07E0) or
( ( ( (PWord(sbLine1 + xp1)^ and $F800) * w11 + (PWord(sbLine1 + xp2)^ and $F800) * w21 +
(PWord(sbLine2 + xp1)^ and $F800) * w12 + (PWord(sbLine2 + xp2)^ and $F800) * w22 ) shr 16) and $F800);
inc(dbLine, 2);
inc(dmLine);
inc(x, xdif);
end;
inc(integer(dbLine), dbLineDif);
inc(integer(dmLine), dmLineDif);
inc(y, ydif);
end;
end;
procedure Bilinear24; // 550 -> 310
var ix, iy : integer;
x, y, xdif, ydif : integer;
xp1, xp2, yp : integer;
wy, wyi, wx : integer;
w11, w21, w12, w22 : integer;
sbBits, sbLine1, sbLine2 : PByteArray;
smBits, smLine1, smLine2 : PByteArray;
dbLine : PByteArray;
dmLine : ^byte;
sbLineDif, dbLineDif : integer;
smLineDif, dmLineDif : integer;
w : integer;
begin
y := 0;
xdif := (srcBmp.Width shl 16) div dstBmp.Width;
ydif := (srcBmp.Height shl 16) div dstBmp.Height;
sbBits := srcBmp.ScanLine[0];
if srcBmp.Height > 1 then
sbLineDif := integer(srcBmp.ScanLine[1]) - integer(sbBits)
else sbLineDif := 0;
dbLine := dstBmp.ScanLine[0];
if dstBmp.Height > 1 then
dbLineDif := integer(dstBmp.ScanLine[1]) - integer(dbLine) - 3 * dstBmp.Width
else dbLineDif := 0;
if srcMsk <> nil then begin
smBits := srcMsk.ScanLine[0];
if srcMsk.Height > 1 then
smLineDif := integer(srcMsk.ScanLine[1]) - integer(smBits)
else smLineDif := 0;
dmLine := dstMsk.ScanLine[0];
if dstMsk.Height > 1 then
dmLineDif := integer(dstMsk.ScanLine[1]) - integer(dmLine) - 1 * dstBmp.Width
else dmLineDif := 0;
end else begin
smBits := nil;
smLineDif := 0;
dmLine := nil;
dmLineDif := 0;
end;
w := srcBmp.Width - 1;
for iy := 0 to dstBmp.Height - 1 do begin
yp := y shr 16;
integer(sbLine1) := integer(sbBits) + sbLineDif * yp;
integer(smLine1) := integer(smBits) + smLineDif * yp;
if yp < srcBmp.Height - 1 then begin
integer(sbLine2) := integer(sbLine1) + sbLineDif;
integer(smLine2) := integer(smLine1) + smLineDif;
end else begin
sbLine2 := sbLine1;
smLine2 := smLine1;
end;
x := 0;
wy := y and $FFFF;
wyi := (not y) and $FFFF;
for ix := 0 to dstBmp.Width - 1 do begin
xp1 := x shr 16;
if xp1 < w then xp2 := xp1 + 1
else xp2 := xp1;
wx := x and $FFFF;
w21 := (wyi * wx) shr 16; w11 := wyi - w21;
w22 := (wy * wx) shr 16; w12 := wy - w22;
if smLine1 <> nil then begin
w11 := (w11 * (256 - smLine1^[xp1])) shr 8;
w21 := (w21 * (256 - smLine1^[xp2])) shr 8;
w12 := (w12 * (256 - smLine2^[xp1])) shr 8;
w22 := (w22 * (256 - smLine2^[xp2])) shr 8;
dmLine^ := 255 - byte((w11 + w21 + w12 + w22) shr 8);
end;
xp1 := xp1 * 3;
xp2 := xp2 * 3;
dbLine^[0] := (sbLine1[xp1 ] * w11 + sbLine1[xp2 ] * w21 + sbLine2[xp1 ] * w12 + sbLine2[xp2 ] * w22) shr 16;
dbLine^[1] := (sbLine1[xp1 + 1] * w11 + sbLine1[xp2 + 1] * w21 + sbLine2[xp1 + 1] * w12 + sbLine2[xp2 + 1] * w22) shr 16;
dbLine^[2] := (sbLine1[xp1 + 2] * w11 + sbLine1[xp2 + 2] * w21 + sbLine2[xp1 + 2] * w12 + sbLine2[xp2 + 2] * w22) shr 16;
inc(integer(dbLine), 3);
inc(dmLine);
inc(x, xdif);
end;
inc(integer(dbLine), dbLineDif);
inc(integer(dmLine), dmLineDif);
inc(y, ydif);
end;
end;
procedure Bilinear32; // 525 -> 305
var ix, iy : integer;
x, y, xdif, ydif : integer;
xp1, xp2, yp : integer;
wy, wyi, wx : integer;
w11, w21, w12, w22 : integer;
sbBits, sbLine1, sbLine2 : PByteArray;
smBits, smLine1, smLine2 : PByteArray;
dbLine : PByteArray;
dmLine : ^byte;
sbLineDif, dbLineDif : integer;
smLineDif, dmLineDif : integer;
w : integer;
begin
y := 0;
xdif := (srcBmp.Width shl 16) div dstBmp.Width;
ydif := (srcBmp.Height shl 16) div dstBmp.Height;
sbBits := srcBmp.ScanLine[0];
if srcBmp.Height > 1 then
sbLineDif := integer(srcBmp.ScanLine[1]) - integer(sbBits)
else sbLineDif := 0;
dbLine := dstBmp.ScanLine[0];
if dstBmp.Height > 1 then
dbLineDif := integer(dstBmp.ScanLine[1]) - integer(dbLine) - 4 * dstBmp.Width
else dbLineDif := 0;
if srcMsk <> nil then begin
smBits := srcMsk.ScanLine[0];
if srcMsk.Height > 1 then
smLineDif := integer(srcMsk.ScanLine[1]) - integer(smBits)
else smLineDif := 0;
dmLine := dstMsk.ScanLine[0];
if dstMsk.Height > 1 then
dmLineDif := integer(dstMsk.ScanLine[1]) - integer(dmLine) - 1 * dstBmp.Width
else dmLineDif := 0;
end else begin
smBits := nil;
smLineDif := 0;
dmLine := nil;
dmLineDif := 0;
end;
w := srcBmp.Width - 1;
for iy := 0 to dstBmp.Height - 1 do begin
yp := y shr 16;
integer(sbLine1) := integer(sbBits) + sbLineDif * yp;
integer(smLine1) := integer(smBits) + smLineDif * yp;
if yp < srcBmp.Height - 1 then begin
integer(sbLine2) := integer(sbLine1) + sbLineDif;
integer(smLine2) := integer(smLine1) + smLineDif;
end else begin
sbLine2 := sbLine1;
smLine2 := smLine1;
end;
x := 0;
wy := y and $FFFF;
wyi := (not y) and $FFFF;
for ix := 0 to dstBmp.Width - 1 do begin
xp1 := x shr 16;
if xp1 < w then xp2 := xp1 + 1
else xp2 := xp1;
wx := x and $FFFF;
w21 := (wyi * wx) shr 16; w11 := wyi - w21;
w22 := (wy * wx) shr 16; w12 := wy - w22;
if smLine1 <> nil then begin
w11 := (w11 * (256 - smLine1^[xp1])) shr 8;
w21 := (w21 * (256 - smLine1^[xp2])) shr 8;
w12 := (w12 * (256 - smLine2^[xp1])) shr 8;
w22 := (w22 * (256 - smLine2^[xp2])) shr 8;
dmLine^ := 255 - byte((w11 + w21 + w12 + w22) shr 8);
end;
xp1 := xp1 * 4;
xp2 := xp2 * 4;
dbLine^[0] := (sbLine1[xp1 ] * w11 + sbLine1[xp2 ] * w21 + sbLine2[xp1 ] * w12 + sbLine2[xp2 ] * w22) shr 16;
dbLine^[1] := (sbLine1[xp1 + 1] * w11 + sbLine1[xp2 + 1] * w21 + sbLine2[xp1 + 1] * w12 + sbLine2[xp2 + 1] * w22) shr 16;
dbLine^[2] := (sbLine1[xp1 + 2] * w11 + sbLine1[xp2 + 2] * w21 + sbLine2[xp1 + 2] * w12 + sbLine2[xp2 + 2] * w22) shr 16;
inc(integer(dbLine), 4);
inc(dmLine);
inc(x, xdif);
end;
inc(integer(dbLine), dbLineDif);
inc(integer(dmLine), dmLineDif);
inc(y, ydif);
end;
end;
begin
if (srcMsk <> nil) and
((dstMsk = nil) or
(srcMsk.PixelFormat <> pf8Bit) or (srcMsk.Width <> srcBmp.Width) or (srcMsk.Height <> srcBmp.Height) ) then
srcMsk := nil;
if srcMsk <> nil then begin
dstMsk.PixelFormat := pf8bit;
dstMsk.Width := dstBmp.Width;
dstMsk.Height := dstBmp.Height;
end else
dstMsk := nil;
case quality of
sqLow : dstBmp.Canvas.StretchDraw(Rect(0, 0, dstBmp.Width, dstBmp.Height), srcBmp);
sqHigh : case GetPixelFormat(dstBmp) of
15 : if ForcePixelFormat([srcBmp], pf15bit) then Bilinear15;
16 : if ForcePixelFormat([srcBmp], pf16bit) then Bilinear16;
24 : if ForcePixelFormat([srcBmp], pf24bit) then Bilinear24;
32 : if ForcePixelFormat([srcBmp], pf32bit) then Bilinear32;
end;
sqVeryHigh : case GetPixelFormat(dstBmp) of
15 : if ForcePixelFormat([srcBmp], pf15bit) then MitchellResampling15;
16 : if ForcePixelFormat([srcBmp], pf16bit) then MitchellResampling16;
24 : if ForcePixelFormat([srcBmp], pf24bit) then MitchellResampling24;
32 : if ForcePixelFormat([srcBmp], pf32bit) then MitchellResampling32;
end;
end;
end;
procedure StretchBitmap(bmp, msk : TBitmap;
newWidth : integer;
newHeight : integer;
quality : TStretchQuality = sqHigh);
var newBmp, newMsk : TBitmap;
begin
newBmp := TBitmap.Create;
try
if GetPixelFormat(bmp) = 15 then
newBmp.PixelFormat := pf15Bit
else newBmp.PixelFormat := bmp.PixelFormat;
newBmp.Width := newWidth;
newBmp.Height := newHeight;
newMsk := nil;
try
if (msk <> nil) and ((msk.PixelFormat <> pf8Bit) or (msk.Width <> bmp.Width) or (msk.Height <> bmp.Height)) then
msk := nil;
if msk <> nil then newMsk := TBitmap.Create;
StretchBitmap(bmp, newBmp, msk, newMsk, quality);
bmp.Assign(newBmp);
if msk <> nil then msk.Assign(newMsk);
finally newMsk.Free end;
finally newBmp.Free end;
end;
// ***************************************************************
procedure AlphaBlend_(src1, src2, msk, dst : TBitmap;
alpha : cardinal = 128;
x : integer = 0;
y : integer = 0 );
var w, h, s1x, s1y, s1ld, s2x, s2y, s2ld, dx, dy, dld, mld : integer;
procedure AlphaBlend15(src1, src2, dst: TBitmap; alpha: cardinal); // 395
var src1Line, src2Line, dstLine : ^cardinal;
mskLine : ^byte;
ix, iy, iw : integer;
i1, i2 : cardinal;
begin
src1Line := src1.ScanLine[s1y];
src2Line := src2.ScanLine[s2y];
dstLine := dst .ScanLine[ dy];
if msk <> nil then begin
mskLine := msk.ScanLine[s1y];
if h > 1 then begin
s1ld := integer(src1.ScanLine[s1y + 1]) - integer(src1Line) - w * 2;
s2ld := integer(src2.ScanLine[s2y + 1]) - integer(src2Line) - w * 2;
dld := integer(dst .ScanLine[ dy + 1]) - integer( dstLine) - w * 2;
mld := integer(msk .ScanLine[s1y + 1]) - integer( mskLine) - w;
end else begin
s1ld := 0;
s2ld := 0;
dld := 0;
mld := 0;
end;
inc(integer(src1Line), s1x * 2);
inc(integer(src2Line), s2x * 2);
inc(integer( dstLine), dx * 2);
inc(integer( mskLine), s1x );
for iy := 0 to h - 1 do begin
for ix := 0 to w - 1 do begin
if mskLine^ < 255 then begin
i1 := 256 - (((cardinal(256) - mskLine^) * alpha) shr 8);
i2 := ((alpha * (PWord(src1Line)^ and $001F) + i1 * (PWord(src2Line)^ and $001F)) shr 8) and $001F;
i2 := i2 + ((alpha * (PWord(src1Line)^ and $03E0) + i1 * (PWord(src2Line)^ and $03E0)) shr 8) and $03E0;
i2 := i2 + ((alpha * (PWord(src1Line)^ and $7C00) + i1 * (PWord(src2Line)^ and $7C00)) shr 8) and $7C00;
PWord(dstLine)^ := i2;
end;
inc(integer(src1Line), 2);
inc(integer(src2Line), 2);
inc(integer( dstLine), 2);
inc(mskLine);
end;
inc(integer(src1Line), s1ld);
inc(integer(src2Line), s2ld);
inc(integer( dstLine), dld);
inc(integer( mskLine), mld);
end;
end else begin
iw := w div 2;
if h > 1 then begin
s1ld := integer(src1.ScanLine[s1y + 1]) - integer(src1Line) - iw * 4;
s2ld := integer(src2.ScanLine[s2y + 1]) - integer(src2Line) - iw * 4;
dld := integer(dst .ScanLine[ dy + 1]) - integer( dstLine) - iw * 4;
end else begin
s1ld := 0;
s2ld := 0;
dld := 0;
end;
inc(integer(src1Line), s1x * 2);
inc(integer(src2Line), s2x * 2);
inc(integer( dstLine), dx * 2);
for iy := 0 to h - 1 do begin
for ix := 0 to iw - 1 do begin
i1 := (src2Line^ and $001F001F);
i2 := (((((src1Line^ and $001F001F) - i1) * alpha) shr 8 + i1) ) and $001F001F;
i1 := (src2Line^ and $03E003E0) shr 4;
i2 := i2 + (((((src1Line^ and $03E003E0) shr 4 - i1) * alpha) shr 8 + i1) shl 4) and $03E003E0;
i1 := (src2Line^ and $7C007C00) shr 8;
i2 := i2 + (((((src1Line^ and $7C007C00) shr 8 - i1) * alpha) shr 8 + i1) shl 8) and $7C007C00;
dstLine^ := i2;
inc(src1Line);
inc(src2Line);
inc( dstLine);
end;
inc(integer(src1Line), s1ld);
inc(integer(src2Line), s2ld);
inc(integer( dstLine), dld);
end;
if odd(w) then begin
integer(src1Line) := integer(src1.ScanLine[s1y]) + iw * 4 + s1x * 2;
integer(src2Line) := integer(src2.ScanLine[s2y]) + iw * 4 + s2x * 2;
integer( dstLine) := integer(dst .ScanLine[ dy]) + iw * 4 + dx * 2;
inc(s1ld, iw * 4);
inc(s2ld, iw * 4);
inc( dld, iw * 4);
for iy := 0 to h - 1 do begin
i1 := PWord(src2Line)^ and $001F;
i2 := ((((PWord(src1Line)^ and $001F) - i1) * alpha) shr 8 + i1) and $001F;
i1 := PWord(src2Line)^ and $03E0;
i2 := i2 + ((((PWord(src1Line)^ and $03E0) - i1) * alpha) shr 8 + i1) and $03E0;
i1 := PWord(src2Line)^ and $7C00;
i2 := i2 + ((((PWord(src1Line)^ and $7C00) - i1) * alpha) shr 8 + i1) and $7C00;
PWord(dstLine)^ := i2;
inc(integer(src1Line), s1ld);
inc(integer(src2Line), s2ld);
inc(integer( dstLine), dld);
end;
end;
end;
end;
procedure AlphaBlend16(src1, src2, dst: TBitmap; alpha: cardinal); // 395
var src1Line, src2Line, dstLine : ^cardinal;
mskLine : ^byte;
ix, iy, iw : integer;
i1, i2 : cardinal;
begin
src1Line := src1.ScanLine[s1y];
src2Line := src2.ScanLine[s2y];
dstLine := dst .ScanLine[ dy];
if msk <> nil then begin
mskLine := msk.ScanLine[s1y];
if h > 1 then begin
s1ld := integer(src1.ScanLine[s1y + 1]) - integer(src1Line) - w * 2;
s2ld := integer(src2.ScanLine[s2y + 1]) - integer(src2Line) - w * 2;
dld := integer(dst .ScanLine[ dy + 1]) - integer( dstLine) - w * 2;
mld := integer(msk .ScanLine[s1y + 1]) - integer( mskLine) - w;
end else begin
s1ld := 0;
s2ld := 0;
dld := 0;
mld := 0;
end;
inc(integer(src1Line), s1x * 2);
inc(integer(src2Line), s2x * 2);
inc(integer( dstLine), dx * 2);
inc(integer( mskLine), s1x );
for iy := 0 to h - 1 do begin
for ix := 0 to w - 1 do begin
if mskLine^ < 255 then begin
i1 := 256 - (((cardinal(256) - mskLine^) * alpha) shr 8);
i2 := ((alpha * (PWord(src1Line)^ and $001F) + i1 * (PWord(src2Line)^ and $001F)) shr 8) and $001F;
i2 := i2 + ((alpha * (PWord(src1Line)^ and $07E0) + i1 * (PWord(src2Line)^ and $07E0)) shr 8) and $07E0;
i2 := i2 + ((alpha * (PWord(src1Line)^ and $F800) + i1 * (PWord(src2Line)^ and $F800)) shr 8) and $F800;
PWord(dstLine)^ := i2;
end;
inc(integer(src1Line), 2);
inc(integer(src2Line), 2);
inc(integer( dstLine), 2);
inc(mskLine);
end;
inc(integer(src1Line), s1ld);
inc(integer(src2Line), s2ld);
inc(integer( dstLine), dld);
inc(integer( mskLine), mld);
end;
end else begin
iw := w div 2;
if h > 1 then begin
s1ld := integer(src1.ScanLine[s1y + 1]) - integer(src1Line) - iw * 4;
s2ld := integer(src2.ScanLine[s2y + 1]) - integer(src2Line) - iw * 4;
dld := integer(dst .ScanLine[ dy + 1]) - integer( dstLine) - iw * 4;
end else begin
s1ld := 0;
s2ld := 0;
dld := 0;
end;
inc(integer(src1Line), s1x * 2);
inc(integer(src2Line), s2x * 2);
inc(integer( dstLine), dx * 2);
for iy := 0 to h - 1 do begin
for ix := 0 to iw - 1 do begin
i1 := (src2Line^ and $001F001F);
i2 := (((((src1Line^ and $001F001F) - i1) * alpha) shr 8 + i1) ) and $001F001F;
i1 := (src2Line^ and $07E007E0) shr 4;
i2 := i2 + (((((src1Line^ and $07E007E0) shr 4 - i1) * alpha) shr 8 + i1) shl 4) and $07E007E0;
i1 := (src2Line^ and $F800F800) shr 8;
i2 := i2 + (((((src1Line^ and $F800F800) shr 8 - i1) * alpha) shr 8 + i1) shl 8) and $F800F800;
dstLine^ := i2;
inc(src1Line);
inc(src2Line);
inc( dstLine);
end;
inc(integer(src1Line), s1ld);
inc(integer(src2Line), s2ld);
inc(integer( dstLine), dld);
end;
if odd(w) then begin
integer(src1Line) := integer(src1.ScanLine[s1y]) + iw * 4 + s1x * 2;
integer(src2Line) := integer(src2.ScanLine[s2y]) + iw * 4 + s2x * 2;
integer( dstLine) := integer(dst .ScanLine[ dy]) + iw * 4 + dx * 2;
inc(s1ld, iw * 4);
inc(s2ld, iw * 4);
inc( dld, iw * 4);
for iy := 0 to h - 1 do begin
i1 := PWord(src2Line)^ and $001F;
i2 := ((((PWord(src1Line)^ and $001F) - i1) * alpha) shr 8 + i1) and $001F;
i1 := PWord(src2Line)^ and $07E0;
i2 := i2 + ((((PWord(src1Line)^ and $07E0) - i1) * alpha) shr 8 + i1) and $07E0;
i1 := PWord(src2Line)^ and $F800;
i2 := i2 + ((((PWord(src1Line)^ and $F800) - i1) * alpha) shr 8 + i1) and $F800;
PWord(dstLine)^ := i2;
inc(integer(src1Line), s1ld);
inc(integer(src2Line), s2ld);
inc(integer( dstLine), dld);
end;
end;
end;
end;
procedure AlphaBlend24(src1, src2, dst: TBitmap; alpha: cardinal); // 770
var src1Line, src2Line, dstLine : PByte;
mskLine : ^byte;
ix, iy, iw : integer;
i1 : cardinal;
begin
src1Line := src1.ScanLine[s1y];
src2Line := src2.ScanLine[s2y];
dstLine := dst .ScanLine[ dy];
iw := w - 1;
if h > 1 then begin
s1ld := integer(src1.ScanLine[s1y + 1]) - integer(src1Line) - w * 3;
s2ld := integer(src2.ScanLine[s2y + 1]) - integer(src2Line) - w * 3;
dld := integer(dst .ScanLine[ dy + 1]) - integer( dstLine) - w * 3;
end else begin
s1ld := 0;
s2ld := 0;
dld := 0;
end;
inc(integer(src1Line), s1x * 3);
inc(integer(src2Line), s2x * 3);
inc(integer( dstLine), dx * 3);
if msk <> nil then begin
mskLine := msk.ScanLine[s1y];
if h > 1 then
mld := integer(msk.ScanLine[s1y + 1]) - integer( mskLine) - w
else mld := 0;
inc(integer(mskLine), s1x);
end else begin
mskLine := nil;
mld := 0;
end;
for iy := 0 to h - 1 do begin
if mskLine <> nil then begin
for ix := 0 to iw do begin
if mskLine^ < 255 then begin
i1 := 256 - (((cardinal(256) - mskLine^) * alpha) shr 8);
dstLine^ := byte((alpha * src1Line^ + i1 * src2Line^) shr 8);
inc(src1Line);
inc(src2Line);
inc( dstLine);
dstLine^ := byte((alpha * src1Line^ + i1 * src2Line^) shr 8);
inc(src1Line);
inc(src2Line);
inc( dstLine);
dstLine^ := byte((alpha * src1Line^ + i1 * src2Line^) shr 8);
inc(src1Line);
inc(src2Line);
inc( dstLine);
end else begin
inc(src1Line, 3);
inc(src2Line, 3);
inc( dstLine, 3);
end;
inc(mskLine);
end;
end else
for ix := 0 to iw do begin
i1 := src2Line^;
dstLine^ := byte(((src1Line^ - i1) * alpha) shr 8 + i1);
inc(src1Line);
inc(src2Line);
inc( dstLine);
i1 := src2Line^;
dstLine^ := byte(((src1Line^ - i1) * alpha) shr 8 + i1);
inc(src1Line);
inc(src2Line);
inc( dstLine);
i1 := src2Line^;
dstLine^ := byte(((src1Line^ - i1) * alpha) shr 8 + i1);
inc(src1Line);
inc(src2Line);
inc( dstLine);
end;
inc(integer(src1Line), s1ld);
inc(integer(src2Line), s2ld);
inc(integer( dstLine), dld);
inc(integer( mskLine), mld);
end;
end;
procedure AlphaBlend32(src1, src2, dst: TBitmap; alpha: cardinal); // 630
var src1Line, src2Line, dstLine : ^cardinal;
mskLine : ^byte;
ix, iy, iw : integer;
i1, i2 : cardinal;
begin
src1Line := src1.ScanLine[s1y];
src2Line := src2.ScanLine[s2y];
dstLine := dst .ScanLine[ dy];
iw := w - 1;
if h > 1 then begin
s1ld := integer(src1.ScanLine[s1y + 1]) - integer(src1Line) - w * 4;
s2ld := integer(src2.ScanLine[s2y + 1]) - integer(src2Line) - w * 4;
dld := integer(dst .ScanLine[ dy + 1]) - integer( dstLine) - w * 4;
end else begin
s1ld := 0;
s2ld := 0;
dld := 0;
end;
inc(integer(src1Line), s1x * 4);
inc(integer(src2Line), s2x * 4);
inc(integer( dstLine), dx * 4);
if msk <> nil then begin
mskLine := msk.ScanLine[s1y];
if h > 1 then
mld := integer(msk.ScanLine[s1y + 1]) - integer( mskLine) - w
else mld := 0;
inc(integer(mskLine), s1x);
end else begin
mskLine := nil;
mld := 0;
end;
for iy := 0 to h - 1 do begin
if mskLine <> nil then begin
for ix := 0 to iw do begin
if mskLine^ < 255 then begin
i1 := 256 - (((cardinal(256) - mskLine^) * alpha) shr 8);
i2 := ((alpha * (src1Line^ and $00FF00FF) + i1 * (src2Line^ and $00FF00FF)) shr 8) and $00FF00FF;
i2 := i2 + ((alpha * (src1Line^ and $0000FF00) + i1 * (src2Line^ and $0000FF00)) shr 8) and $0000FF00;
dstLine^ := i2;
end;
inc(src1Line);
inc(src2Line);
inc( dstLine);
inc( mskLine);
end;
end else
for ix := 0 to iw do begin
i1 := src2Line^ and $00FF00FF;
i2 := ((((src1Line^ and $00FF00FF) - i1) * alpha) shr 8 + i1) and $00FF00FF;
i1 := src2Line^ and $0000FF00;
i2 := i2 + ((((src1Line^ and $0000FF00) - i1) * alpha) shr 8 + i1) and $0000FF00;
dstLine^ := i2;
inc(src1Line);
inc(src2Line);
inc( dstLine);
end;
inc(integer(src1Line), s1ld);
inc(integer(src2Line), s2ld);
inc(integer( dstLine), dld);
inc(integer( mskLine), mld);
end;
end;
begin
if dst = src2 then begin
if x < 0 then begin
w := Min(src1.Width + x, dst.Width);
s1x := -x;
dx := 0;
end else begin
w := Min(src1.Width, dst.Width - x);
s1x := 0;
dx := x;
end;
if y < 0 then begin
h := Min(src1.Height + y, dst.Height);
s1y := -y;
dy := 0;
end else begin
h := Min(src1.Height, dst.Height - y);
s1y := 0;
dy := y;
end;
s2x := dx;
s2y := dy;
if (msk <> nil) and ((msk.PixelFormat <> pf8Bit) or (msk.Width <> src1.Width) or (msk.Height <> src1.Height)) then
msk := nil;
end else begin
w := Min(src1.Width, Min(src2.Width, dst.Width ));
h := Min(src1.Height, Min(src2.Height, dst.Height));
s1x := 0; s2x := 0; dx := 0;
s1y := 0; s2y := 0; dy := 0;
end;
case GetPixelFormat(dst) of
15 : if ForcePixelFormat([src1, src2], pf15bit) then AlphaBlend15(src1, src2, dst, alpha);
16 : if ForcePixelFormat([src1, src2], pf16bit) then AlphaBlend16(src1, src2, dst, alpha);
24 : if ForcePixelFormat([src1, src2], pf24bit) then AlphaBlend24(src1, src2, dst, alpha);
32 : if ForcePixelFormat([src1, src2], pf32bit) then AlphaBlend32(src1, src2, dst, alpha);
end;
end;
procedure AlphaBlend(src1, src2, dst : TBitmap;
alpha : cardinal = 128);
begin
AlphaBlend_(src1, src2, nil, dst, alpha);
end;
procedure AlphaBlend(src, dst : TBitmap;
alpha : cardinal = 128;
msk : TBitmap = nil;
x : integer = 0;
y : integer = 0 );
begin
AlphaBlend_(src, dst, msk, dst, alpha, x, y);
end;
// ***************************************************************
procedure Draw(imageList, index : cardinal;
dst : TBitmap;
x : integer = 0;
y : integer = 0;
width : integer = 0;
height : integer = 0;
grayPercent : TGrayPercent = gp0;
alpha : cardinal = 256;
stretchQuality : TStretchQuality = sqHigh);
var bmp, msk : TBitmap;
ii : TImageInfo;
begin
if ImageList_GetImageInfo(imageList, index, ii) then begin
bmp := TBitmap.Create;
try
case GetPixelFormat(dst) of
15 : bmp.PixelFormat := pf15bit;
16 : bmp.PixelFormat := pf16bit;
24 : bmp.PixelFormat := pf24bit;
else bmp.PixelFormat := pf32bit;
end;
bmp.Width := ii.rcImage.Right - ii.rcImage.Left;
bmp.Height := ii.rcImage.Bottom - ii.rcImage.Top;
ImageList_Draw(imageList, index, bmp.Canvas.Handle, 0, 0, ILD_NORMAL);
msk := nil;
try
if ii.hbmMask <> 0 then begin
msk := TBitmap.Create;
msk.PixelFormat := pf8bit;
msk.Width := ii.rcImage.Right - ii.rcImage.Left;
msk.Height := ii.rcImage.Bottom - ii.rcImage.Top;
ImageList_Draw(imageList, index, msk.Canvas.Handle, 0, 0, ILD_MASK);
end;
if ((width <> 0) and (width <> bmp.Width)) or ((height <> 0) and (height <> bmp.Height)) then begin
if width = 0 then width := bmp.Width;
if height = 0 then height := bmp.Height;
StretchBitmap(bmp, msk, width, height, stretchQuality);
end;
GrayScale(bmp, grayPercent);
AlphaBlend(bmp, dst, alpha, msk, x, y);
finally msk.Free end;
finally bmp.Free end;
end;
end;
procedure Draw(bmp, msk : TBitmap;
dst : TBitmap;
x : integer = 0;
y : integer = 0;
width : integer = 0;
height : integer = 0;
grayPercent : TGrayPercent = gp0;
alpha : cardinal = 256;
stretchQuality : TStretchQuality = sqHigh);
begin
if width = 0 then width := bmp.Width;
if height = 0 then height := bmp.Height;
if (width <> bmp.Width) or (height <> bmp.Height) then
StretchBitmap(bmp, msk, width, height, stretchQuality);
GrayScale(bmp, grayPercent);
AlphaBlend(bmp, dst, alpha, msk, x, y);
end;
// ***************************************************************
{var bmp1, bmp2 : TBitmap;
begin
bmp1 := TBitmap.Create;
bmp1.LoadFromFile('c:\windows\desktop\cddrive.bmp');
bmp2 := TBitmap.Create;
bmp2.PixelFormat := pf24bit;
bmp2.Canvas.Brush.Color := clBtnFace;
bmp2.Width := 16;
bmp2.Height := 16;
Draw(bmp1, nil, bmp2, 0, 0, 0, 0, gp100, 128);
bmp2.SaveToFile('c:\windows\desktop\cddrive2.bmp');
ExitProcess(0); }
end.
|
PROGRAM TMM;
CONST
UpperPos = 3;
LowerPos = 1;
DefaultMorris = '.';
XMorris = 'X';
OMorris = 'O';
TYPE
Board = ARRAY[LowerPos..UpperPos] OF ARRAY[LowerPos..UpperPos] OF CHAR;
PROCEDURE InitBoard(VAR board: Board);
VAR
i, j: INTEGER;
BEGIN
FOR i := LowerPos TO UpperPos DO BEGIN
FOR j := LowerPos TO UpperPos DO BEGIN
board[i][j] := DefaultMorris;
END;
END;
END;
PROCEDURE DisplayBoard(board: Board);
VAR
i, j: INTEGER;
BEGIN
WriteLn();
WriteLn('y\x 1 2 3');
WriteLn();
FOR i := LowerPos TO UpperPos DO BEGIN
Write(i, ' ');
FOR j := LowerPos TO UpperPos DO BEGIN
Write(' ', board[i][j], ' ');
END;
WriteLn();
WriteLn();
END;
WriteLn();
END;
FUNCTION AssertBoardsEqual(board1, board2: Board): BOOLEAN;
VAR
i, j: INTEGER;
BEGIN
AssertBoardsEqual := true;
FOR i := LowerPos TO UpperPos DO
BEGIN
FOR j := LowerPos TO UpperPos DO
BEGIN
IF board1[i][j] <> board2[i][j] THEN
AssertBoardsEqual := false
END;
END;
END;
FUNCTION IsPositionFree(xPos, yPos: INTEGER; board: Board): BOOLEAN;
BEGIN
IsPositionFree := (board[yPos][xPos] = DefaultMorris);
END;
FUNCTION IsPositionInRange(xPos, yPos: INTEGER): BOOLEAN;
BEGIN
IsPositionInRange := false;
IF (yPos <= UpperPos) and (yPos >= LowerPos) THEN
IF (xPos <= UpperPos) and (xPos >= LowerPos) THEN
IsPositionInRange := true;
END;
PROCEDURE SetMorris(xPos, yPos: INTEGER; morrisType: CHAR; VAR board: Board; VAR isLegalMove: BOOLEAN);
BEGIN
isLegalMove := true;
IF IsPositionInRange(xPos, yPos) and IsPositionFree(xPos, yPos, board) THEN
board[yPos][xPos] := morrisType
ELSE BEGIN
isLegalMove := false;
END;
END;
PROCEDURE RemoveMorris(xPos, yPos: INTEGER; morrisType: CHAR; VAR board: Board);
BEGIN
IF IsPositionInRange(yPos, xPos) and (board[yPos][xPos] = morrisType) THEN
board[yPos][xPos] := DefaultMorris;
END;
PROCEDURE MoveMorris(oldXPos, oldYPos, newXPos, newYPos: INTEGER; morrisType: CHAR; VAR board: Board; VAR isLegalMove: BOOLEAN);
BEGIN
isLegalMove := true;
IF (IsPositionInRange(newXPos, newYPos)) and (IsPositionInRange(oldXPos, oldYPos)) THEN BEGIN
IF (board[oldYPos][oldXPos] = morrisType) and IsPositionFree(newXPos, newYPos, board) THEN BEGIN
RemoveMorris(oldXPos, oldYPos, morrisType, board);
SetMorris(newXPos, newYPos, morrisType, board, isLegalMove);
END ELSE BEGIN
isLegalMove := false;
END;
END ELSE BEGIN
isLegalMove := false;
END;
END;
PROCEDURE ShowIllegalMoveMessage;
BEGIN
WriteLn('Illegal Move !')
END;
FUNCTION IsHorizontalWin(board: Board): BOOLEAN;
BEGIN
IsHorizontalWin := false;
IF (board[1][1] <> DefaultMorris) and (board[1][1] = board[1][2]) and (board[1][2] = board[1][3]) THEN
IsHorizontalWin := true
ELSE IF (board[2][1] <> DefaultMorris) and (board[2][1] = board[2][2]) and (board[2][2] = board[2][3]) THEN
IsHorizontalWin := true
ELSE IF (board[3][1] <> DefaultMorris) and (board[3][1] = board[3][2]) and (board[3][2] = board[3][3]) THEN
IsHorizontalWin := true;
END;
FUNCTION IsVerticalWin(board: Board): BOOLEAN;
BEGIN
IsVerticalWin := false;
IF (board[1][1] <> DefaultMorris) and (board[1][1] = board[2][1]) and (board[2][1] = board[3][1]) THEN
IsVerticalWin := true
ELSE IF (board[1][2] <> DefaultMorris) and (board[1][2] = board[2][2]) and (board[2][2] = board[3][2]) THEN
IsVerticalWin := true
ELSE IF (board[1][3] <> DefaultMorris) and (board[1][3] = board[2][3]) and (board[2][3] = board[3][3]) THEN
IsVerticalWin := true;
END;
FUNCTION IsDiagonalWin(board: Board): BOOLEAN;
BEGIN
IsDiagonalWin := false;
IF (board[1][1] <> DefaultMorris) and (board[1][1] = board[2][2]) and (board[2][2] = board[3][3]) THEN
IsDiagonalWin := true
ELSE IF (board[1][3] <> DefaultMorris) and (board[1][3] = board[2][2]) and (board[2][2] = board[3][1]) THEN
IsDiagonalWin := true;
END;
FUNCTION IsGameOver(board: Board): BOOLEAN;
BEGIN
IsGameOver := false;
IF IsHorizontalWin(board) or IsVerticalWin(board) or IsDiagonalWin(board) THEN
IsGameOver := true;
END;
FUNCTION GetSwitchedMorrisType(morrisType: CHAR): CHAR;
BEGIN
GetSwitchedMorrisType := XMorris;
IF morrisType = XMorris THEN
GetSwitchedMorrisType := OMorris;
END;
// -----------------------------------------------------------------
FUNCTION IsBoardEmpty(board: Board): BOOLEAN;
VAR
emptyBoard: Board;
BEGIN
InitBoard(emptyBoard);
IsBoardEmpty := AssertBoardsEqual(board, emptyBoard);
END;
PROCEDURE GetWinningPositionPhase1(board: Board; VAR xPos, yPos: INTEGER; morrisType: CHAR; VAR couldWin: BOOLEAN);
VAR
hypotheticalBoard: Board;
i, j: INTEGER;
isLegalMove: BOOLEAN;
BEGIN
xPos := 0;
yPos := 0;
couldWin := false;
hypotheticalBoard := board;
FOR i := LowerPos TO UpperPos DO
BEGIN
FOR j := LowerPos TO UpperPos DO
BEGIN
SetMorris(j, i, morrisType, hypotheticalBoard, isLegalMove);
IF isLegalMove THEN
BEGIN
IF IsGameOver(hypotheticalBoard) THEN
BEGIN
couldWin := true;
xPos := j;
yPos := i;
END;
RemoveMorris(j, i, morrisType, hypotheticalBoard);
END
END;
END;
END;
PROCEDURE GetWinningPositionPhase2(board: Board; VAR oldXPos, oldYPos, newXPos, newYPos: INTEGER; morrisType: CHAR; VAR couldWin: BOOLEAN);
VAR
i, j: INTEGER;
k, h: INTEGER;
isLegalMove: BOOLEAN;
BEGIN
couldWin := false;
FOR i := LowerPos TO UpperPos DO
BEGIN
FOR j := LowerPos TO UpperPos DO
BEGIN
IF board[i][j] = morrisType THEN
BEGIN
FOR k := LowerPos TO UpperPos DO
BEGIN
FOR h := LowerPos TO UpperPos DO
BEGIN
MoveMorris(j, i, h, k, morrisType, board, isLegalMove);
IF isLegalMove THEN
BEGIN
IF IsGameOver(board) THEN
BEGIN
newXPos := h;
newYPos := k;
oldXPos := j;
oldYPos := i;
couldWin := true;
END;
MoveMorris(h, k, j, i, morrisType, board, isLegalMove);
END;
END;
END;
END;
END;
END;
END;
FUNCTION RemoveMorrisWouldLoose(board: Board; xPos, yPos: INTEGER; morrisType, enemyMorrisType: CHAR): BOOLEAN;
VAR
isLegalMove: BOOLEAN;
hypotheticalBoard: Board;
BEGIN
hypotheticalBoard := board;
RemoveMorris(xPos, yPos, morrisType, hypotheticalBoard);
SetMorris(xPos, yPos, enemyMorrisType, hypotheticalBoard, isLegalMove);
RemoveMorrisWouldLoose := IsGameOver(hypotheticalBoard)
END;
PROCEDURE BestMorrisToRemove(board: Board; VAR xPos, yPos: INTEGER; morrisType, enemyMorris: CHAR);
VAR
i, j: INTEGER;
BEGIN
FOR i := LowerPos TO UpperPos DO
BEGIN
FOR j := LowerPos TO UpperPos DO
BEGIN
IF board[i][j] = morrisType THEN
BEGIN
IF NOT RemoveMorrisWouldLoose(board, j, i, morrisType, enemyMorris) THEN
BEGIN
xPos := j;
yPos := i;
END;
END;
END;
END;
END;
PROCEDURE GetNeutralPosition(board: Board; VAR xPos, yPos: INTEGER; morrisType: CHAR);
VAR
i, j: INTEGER;
BEGIN
FOR i := LowerPos TO UpperPos DO
BEGIN
FOR j := LowerPos TO UpperPos DO
BEGIN
IF IsPositionFree(j, i, board) THEN
BEGIN
xPos := j;
yPos := i;
END;
END;
END;
END;
PROCEDURE ChooseBestMovePhase1(VAR board: Board; morrisType: CHAR);
VAR
hypotheticalBoard: Board;
isLegalMove: BOOLEAN;
xPos, yPos: INTEGER;
couldWin: BOOLEAN;
enemyMorrisType: CHAR;
BEGIN
hypotheticalBoard := board;
enemyMorrisType := GetSwitchedMorrisType(morrisType);
IF IsBoardEmpty(hypotheticalBoard) THEN
SetMorris(2, 2, morrisType, board, isLegalMove)
ELSE BEGIN
GetWinningPositionPhase1(hypotheticalBoard, xPos, yPos, morrisType, couldWin);
IF couldWin THEN
SetMorris(xPos, yPos, morrisType, board, isLegalMove)
ELSE BEGIN
GetWinningPositionPhase1(hypotheticalBoard, xPos, yPos, enemyMorrisType, couldWin);
IF couldWin THEN
BEGIN
SetMorris(xPos, yPos, morrisType, board, isLegalMove);
END
ELSE BEGIN
GetNeutralPosition(hypotheticalBoard, xPos, yPos, morrisType);
SetMorris(xPos, yPos, morrisType, board, isLegalMove);
END;
END;
END;
END;
PROCEDURE ChooseBestMovePhase2(VAR board: Board; computerMorris: CHAR);
VAR
hypotheticalBoard: Board;
isLegalMove: BOOLEAN;
oldXPos, oldYPos, newXPos, newYPos: INTEGER;
couldWin: BOOLEAN;
enemyMorrisType: CHAR;
BEGIN
hypotheticalBoard := board;
enemyMorrisType := GetSwitchedMorrisType(computerMorris);
//attack mode
GetWinningPositionPhase2(hypotheticalBoard, oldXPos, oldYPos, newXPos, newYPos, computerMorris, couldWin);
IF couldWin THEN
MoveMorris(oldXPos, oldYPos, newXPos, newYPos, computerMorris, board, isLegalMove)
ELSE BEGIN
// defend mode
GetWinningPositionPhase2(hypotheticalBoard, oldXPos, oldYPos, newXPos, newYPos, enemyMorrisType, couldWin);
IF couldWin THEN
BEGIN
BestMorrisToRemove(hypotheticalBoard, oldXPos, oldYPos, computerMorris, enemyMorrisType);
MoveMorris(oldXPos, oldYPos, newXPos, newYPos, computerMorris, board, isLegalMove);
END ELSE BEGIN
BestMorrisToRemove(hypotheticalBoard, oldXPos, oldYPos, computerMorris, enemyMorrisType);
GetNeutralPosition(hypotheticalBoard, newXPos, newYPos, computerMorris);
MoveMorris(oldXPos, oldYPos, newXPos, newYPos, computerMorris, board, isLegalMove);
END;
END;
END;
PROCEDURE RunPvPPhase1(VAR board: Board; VAR morrisType: CHAR);
VAR
morrisSetAmount: INTEGER;
isLegalMove: BOOLEAN;
xPos, yPos: INTEGER;
BEGIN
morrisSetAmount := 1;
WHILE (morrisSetAmount <= 6) and (not IsGameOver(board)) DO BEGIN
WriteLn('Place your morris (', morrisType,')');
Write('xPos: ');
ReadLn(xPos);
Write('yPos: ');
ReadLn(yPos);
SetMorris(xPos, yPos, morrisType, board, isLegalMove);
DisplayBoard(board);
IF isLegalMove THEN BEGIN
morrisType := GetSwitchedMorrisType(morrisType);
morrisSetAmount := morrisSetAmount + 1;
END ELSE BEGIN
ShowIllegalMoveMessage();
END;
END;
END;
PROCEDURE RunPVPPhase2(VAR board: Board; VAR morrisType: CHAR);
VAR
isLegalMove: BOOLEAN;
fromXPos, fromYPos, toXPos, toYPos: INTEGER;
BEGIN
WHILE not IsGameOver(board) DO BEGIN
// Real game begins: moving
WriteLn('Move your morris (', morrisType, ')');
WriteLn('From xPos: ');
ReadLn(fromXPos);
WriteLn('From yPos: ');
ReadLn(fromYPos);
WriteLn('To xPos: ');
ReadLn(toXPos);
WriteLn('To yPos: ');
ReadLn(toYPos);
MoveMorris(fromXPos, fromYPos, toXPos, toYPos, morrisType, board, isLegalMove);
DisplayBoard(board);
IF isLegalMove THEN BEGIN
morrisType := GetSwitchedMorrisType(morrisType);
END ELSE ShowIllegalMoveMessage;
END;
END;
PROCEDURE RunPvCPhase1 (VAR board: Board; VAR computerMorris: CHAR; VAR morrisType: CHAR);
VAR
morrisSetAmount: INTEGER;
isLegalMove: BOOLEAN;
xPos, yPos: INTEGER;
BEGIN
morrisSetAmount := 1;
WHILE (morrisSetAmount <= 6) and (not IsGameOver(board)) DO BEGIN
IF morrisType <> computerMorris THEN
BEGIN
WriteLn('Place your morris (', morrisType,')');
Write('xPos: ');
ReadLn(xPos);
Write('yPos: ');
ReadLn(yPos);
SetMorris(xPos, yPos, morrisType, board, isLegalMove);
DisplayBoard(board);
IF isLegalMove THEN BEGIN
morrisType := GetSwitchedMorrisType(morrisType);
morrisSetAmount := morrisSetAmount + 1;
END ELSE BEGIN
ShowIllegalMoveMessage();
END;
END ELSE BEGIN
ChooseBestMovePhase1(board, computerMorris);
DisplayBoard(board);
morrisType := GetSwitchedMorrisType(morrisType);
morrisSetAmount := morrisSetAmount + 1;
END;
END;
END;
PROCEDURE RunCvCPhase1 (VAR board: Board; VAR computerMorris: CHAR; VAR morrisType: CHAR; VAR count: INTEGER);
VAR
morrisSetAmount: INTEGER;
BEGIN
morrisSetAmount := 1;
WHILE (morrisSetAmount <= 6) and (not IsGameOver(board)) DO BEGIN
ChooseBestMovePhase1(board, morrisType);
DisplayBoard(board);
morrisType := GetSwitchedMorrisType(morrisType);
morrisSetAmount := morrisSetAmount + 1;
count := count + 1;
END;
END;
PROCEDURE RunPvCPhase2 (VAR board: Board; VAR computerMorris: CHAR; VAR morrisType: CHAR);
VAR
isLegalMove: BOOLEAN;
fromXPos, fromYPos, toXPos, toYPos: INTEGER;
BEGIN
WHILE (not IsGameOver(board)) DO BEGIN
IF morrisType <> computerMorris THEN
BEGIN
WriteLn('Move your morris (', morrisType,')');
WriteLn('From xPos: ');
ReadLn(fromXPos);
WriteLn('From yPos: ');
ReadLn(fromYPos);
WriteLn('To xPos: ');
ReadLn(toXPos);
WriteLn('To yPos: ');
ReadLn(toYPos);
MoveMorris(fromXPos, fromYPos, toXPos, toYPos, morrisType, board, isLegalMove);
DisplayBoard(board);
IF isLegalMove THEN BEGIN
morrisType := GetSwitchedMorrisType(morrisType);
END ELSE BEGIN
ShowIllegalMoveMessage();
END;
END ELSE BEGIN
ChooseBestMovePhase2(board, computerMorris);
DisplayBoard(board);
morrisType := GetSwitchedMorrisType(morrisType)
END;
END;
END;
PROCEDURE RunCvCPhase2 (VAR board: Board; VAR computerMorris: CHAR; VAR morrisType: CHAR; VAR count: INTEGER);
BEGIN
WHILE (not IsGameOver(board)) DO BEGIN
ChooseBestMovePhase2(board, morrisType);
DisplayBoard(board);
morrisType := GetSwitchedMorrisType(morrisType);
count := count + 1;
END;
END;
FUNCTION AssertInitBoard (board: Board): BOOLEAN;
VAR
i, j: INTEGER;
BEGIN
AssertInitBoard := true;
FOR i := LowerPos TO UpperPos DO
BEGIN
FOR j := LowerPos TO UpperPos DO
BEGIN
IF board[i][j] <> DefaultMorris THEN
AssertInitBoard := false;
END;
END;
END;
FUNCTION AssertTrue(bool: BOOLEAN): STRING;
BEGIN
AssertTrue := 'X';
IF bool THEN
AssertTrue := 'OK'
END;
FUNCTION AssertFalse(bool: BOOLEAN): STRING;
BEGIN
AssertFalse := 'X';
IF not bool THEN
AssertFalse := 'OK'
END;
FUNCTION AssertSetMorris(xPos, yPos: INTEGER; morrisType: CHAR; VAR board: Board): BOOLEAN;
VAR
isLegalMove: BOOLEAN;
BEGIN
SetMorris(xPos, yPos, morrisType, board, isLegalMove);
AssertSetMorris := isLegalMove;
END;
FUNCTION AssertMoveMorris(oldXPos, oldYPos, newXPos, newYPos: INTEGER; morrisType: CHAR; VAR board: Board): BOOLEAN;
VAR
isLegalMove: BOOLEAN;
BEGIN
MoveMorris(oldXPos, oldYPos, newXPos, newYPos, morrisType, board, isLegalMove);
AssertMoveMorris := isLegalMove;
END;
FUNCTION AssertGetNeutralPosition(board: Board; expectedXPos, expectedYPos: INTEGER; morrisType: CHAR): BOOLEAN;
VAR
xPos, yPos: INTEGER;
BEGIN
AssertGetNeutralPosition := false;
GetNeutralPosition(board, xPos, yPos, morrisType);
IF (xPos = expectedXPos) and (yPos = expectedYPos) THEN
AssertGetNeutralPosition := true;
END;
FUNCTION AssertChooseBestMovePhase1(VAR board, expectedBoard: Board; morrisType: CHAR): BOOLEAN;
BEGIN
AssertChooseBestMovePhase1 := false;
ChooseBestMovePhase1(board, morrisType);
IF AssertBoardsEqual(board, expectedBoard) THEN
AssertChooseBestMovePhase1 := true;
END;
FUNCTION AssertChooseBestMovePhase2(VAR board, expectedBoard: Board; morrisType: CHAR): BOOLEAN;
BEGIN
AssertChooseBestMovePhase2 := false;
ChooseBestMovePhase2(board, morrisType);
IF AssertBoardsEqual(board, expectedBoard) THEN
AssertChooseBestMovePhase2 := true;
END;
PROCEDURE RunTests;
VAR
testBoard, testBoard2, testBoard3, testBoard4, testBoardDiagonal1, testBoardDiagonal2, testBoardIsHorizontalWin, testBoardIsVerticalWin, testBoardNonWinning: Board;
count: INTEGER;
computerMorris, morrisType: CHAR;
BEGIN
count := 0;
{* Testing *}
InitBoard(testBoard);
InitBoard(testBoard2);
InitBoard(testBoard3);
InitBoard(testBoard4);
InitBoard(testBoardDiagonal1);
InitBoard(testBoardDiagonal2);
InitBoard(testBoardIsHorizontalWin);
InitBoard(testBoardIsVerticalWin);
InitBoard(testBoardNonWinning);
testBoard[1][1] := XMorris;
testBoard[1][2] := OMorris;
testBoard[1][3] := XMorris;
testBoard[2][2] := XMorris;
testBoard[3][3] := XMorris;
{* Test InitBoard *}
WriteLn('Tests InitBoard');
WriteLn('AssertInitBoard(testBoard) returns false -> ', AssertTrue((AssertInitBoard(testBoard) = false)));
WriteLn('AssertInitBoard(testBoard2) returns true -> ', AssertTrue((AssertInitBoard(testBoard2)= true)));
WriteLn();
{* Test IsPositionFree *}
WriteLn('Tests IsPositionFree');
WriteLn('IsPositionFree(1, 1, testBoard2) returns true -> ', AssertTrue((IsPositionFree(1, 1, testBoard2) = true)));
WriteLn('IsPositionFree(1, 1, testBoard) returns false -> ', AssertTrue((IsPositionFree(1, 1, testBoard) = false)));
WriteLn();
{* Test IsPositionInRange *}
WriteLn('Tests IsPositionInRange');
WriteLn('IsPositionInRange(1, 1) returns true -> ', AssertTrue((IsPositionInRange(1, 1) = true)));
WriteLn('IsPositionInRange(2, 3) returns true -> ', AssertTrue((IsPositionInRange(2, 3) = true)));
WriteLn('IsPositionInRange(0, 0) returns false -> ', AssertTrue((IsPositionInRange(0, 0) = false)));
WriteLn('IsPositionInRange(0, 1) returns false -> ', AssertTrue((IsPositionInRange(0, 1) = false)));
WriteLn('IsPositionInRange(1, 0) returns false -> ', AssertTrue((IsPositionInRange(1, 0) = false)));
WriteLn('IsPositionInRange(4, 2) returns false -> ', AssertTrue((IsPositionInRange(4, 2) = false)));
WriteLn('IsPositionInRange(2, 4) returns false -> ', AssertTrue((IsPositionInRange(2, 4) = false)));
WriteLn();
{* Test IsGameOver, within IsDiagonalWin, IsHorizontalWin, IsVerticalWin *}
WriteLn('Tests IsGameOver, with IsDiagonalWin, IsHorizontalWin, IsVerticalWin');
testBoardDiagonal1[1][1] := XMorris;
testBoardDiagonal1[2][2] := XMorris;
testBoardDiagonal1[3][3] := XMorris;
testBoardDiagonal2[1][3] := XMorris;
testBoardDiagonal2[2][2] := XMorris;
testBoardDiagonal2[3][1] := XMorris;
testBoardIsHorizontalWin[1][1] := XMorris;
testBoardIsHorizontalWin[1][2] := XMorris;
testBoardIsHorizontalWin[1][3] := XMorris;
testBoardIsVerticalWin[1][1] := XMorris;
testBoardIsVerticalWin[2][1] := XMorris;
testBoardIsVerticalWin[3][1] := XMorris;
testBoardNonWinning[1][1] := XMorris;
testBoardNonWinning[2][3] := XMorris;
testBoardNonWinning[3][2] := XMorris;
WriteLn('IsGameOver(testBoardDiagonal1) returns true -> ', AssertTrue(IsGameOver(testBoardDiagonal1)));
WriteLn('IsGameOver(testBoardDiagonal2) returns true -> ', AssertTrue(IsGameOver(testBoardDiagonal2)));
WriteLn('IsGameOver(testBoardIsHorizontalWin) returns true -> ', AssertTrue(IsGameOver(testBoardIsHorizontalWin)));
WriteLn('IsGameOver(testBoardIsVerticalWin) returns true -> ', AssertTrue(IsGameOver(testBoardIsVerticalWin)));
WriteLn('IsGameOver(testBoardNonWinning) returns false -> ', AssertFalse(IsGameOver(testBoardNonWinning)));
WriteLn();
{* Test SetMorris *}
testBoard4[1][1] := XMorris;
testBoard4[2][1] := OMorris;
testBoard4[3][1] := XMorris;
testBoard4[2][2] := OMorris;
testBoard4[1][3] := OMorris;
testBoard4[2][3] := XMorris;
WriteLn('Tests SetMorris');
WriteLn('AssertSetMorris(1, 1, XMorris, testBoard3, true) returns true -> ',
AssertTrue(AssertSetMorris(1, 1, XMorris, testBoard3)));
WriteLn('AssertSetMorris(1, 2, OMorris, testBoard3, true) returns true -> ',
AssertTrue(AssertSetMorris(1, 2, OMorris, testBoard3)));
WriteLn('AssertSetMorris(1, 3, XMorris, testBoard3, true) returns true -> ',
AssertTrue(AssertSetMorris(1, 3, XMorris, testBoard3)));
WriteLn('AssertSetMorris(2, 2, OMorris, testBoard3, true) returns true -> ',
AssertTrue(AssertSetMorris(2, 2, OMorris, testBoard3)));
WriteLn('AssertSetMorris(3, 1, OMorris, testBoard3, true) returns true -> ',
AssertTrue(AssertSetMorris(3, 1, OMorris, testBoard3)));
WriteLn('AssertSetMorris(3, 1, OMorris, testBoard3, false) returns false -> ',
AssertFalse(AssertSetMorris(3, 1, OMorris, testBoard3)));
WriteLn('AssertSetMorris(3, 1, XMorris, testBoard3, false) returns false -> ',
AssertFalse(AssertSetMorris(3, 1, XMorris, testBoard3)));
WriteLn('AssertSetMorris(3, 2, XMorris, testBoard3, false) returns true -> ',
AssertTrue(AssertSetMorris(3, 2, XMorris, testBoard3)));
WriteLn('AssertBoardsEqual(testBoard3, testBoard4) returns true -> ',
AssertTrue(AssertBoardsEqual(testBoard3, testBoard4)));
WriteLn();
{* Test MoveMorris, with RemoveMorris *}
testBoard4[1][2] := XMorris;
testBoard4[1][1] := DefaultMorris;
WriteLn('Tests MoveMorris, with RemoveMorris');
WriteLn('AssertMoveMorris(1, 1, 2, 1, XMorris, testBoard3) returns true -> ', AssertTrue(AssertMoveMorris(1, 1, 2, 1, XMorris, testBoard3)));
WriteLn('AssertMoveMorris(2, 3, 3, 3, XMorris, testBoard3) returns false -> ', AssertFalse(AssertMoveMorris(2, 3, 3, 3, XMorris, testBoard3))); // pick DefaultMorris
WriteLn('AssertMoveMorris(3, 1, 3, 3, XMorris, testBoard3) returns false -> ', AssertFalse(AssertMoveMorris(3, 1, 3, 3, XMorris, testBoard3))); // pick OMorris
WriteLn('AssertMoveMorris(1, 3, 3, 1, XMorris, testBoard3) returns false -> ', AssertFalse(AssertMoveMorris(1, 3, 3, 1, XMorris, testBoard3))); // field not free
WriteLn('AssertMoveMorris(1, 3, 3, 2, XMorris, testBoard3) returns false -> ', AssertFalse(AssertMoveMorris(1, 3, 3, 2, XMorris, testBoard3))); // field not free
WriteLn('AssertMoveMorris(1, 3, 1, 3, XMorris, testBoard3) returns false -> ', AssertFalse(AssertMoveMorris(1, 3, 1, 3, XMorris, testBoard3))); // move on same field
WriteLn('AssertBoardsEqual(testBoard3, testBoard4) returns true -> ',
AssertTrue(AssertBoardsEqual(testBoard3, testBoard4)));
WriteLn();
{* Tests GetNeutralPosition *}
WriteLn('Test GetNeutralPosition');
WriteLn('AssertGetNeutralPosition(testBoard3, 3, 3, XMorris) returns true -> ', AssertTrue(AssertGetNeutralPosition(testBoard3, 3, 3, XMorris)));
WriteLn('testBoard3[3][3] := XMorris;');
testBoard3[3][3] := XMorris;
WriteLn('AssertGetNeutralPosition(testBoard3, 3, 3, XMorris) returns false -> ', AssertFalse(AssertGetNeutralPosition(testBoard3, 3, 3, XMorris)));
WriteLn('AssertGetNeutralPosition(testBoard3, 2, 3, XMorris) returns true -> ', AssertTrue(AssertGetNeutralPosition(testBoard3, 2, 3, XMorris)));
testBoard3[3][3] := DefaultMorris;
WriteLn();
{* Test ChooseBestMovePhase1 *}
WriteLn('Test ChooseBestMovePhase1 (testBoard3, testBoard4 neu initialisiert)');
InitBoard(testBoard3);
InitBoard(testBoard4);
testBoard4[2][2] := XMorris;
WriteLn('First Set');
WriteLn('AssertChooseBestMovePhase1(testBoard3, testBoard4, XMorris) returns true -> ', AssertTrue(AssertChooseBestMovePhase1(testBoard3, testBoard4, XMorris)));
testBoard4[3][3] := OMorris;
WriteLn('AssertChooseBestMovePhase1(testBoard3, testBoard4, OMorris) returns true -> ', AssertTrue(AssertChooseBestMovePhase1(testBoard3, testBoard4, OMorris)));
testBoard4[3][2] := XMorris;
WriteLn('AssertChooseBestMovePhase1(testBoard3, testBoard4, OMorris) returns true -> ', AssertTrue(AssertChooseBestMovePhase1(testBoard3, testBoard4, XMorris)));
testBoard4[1][2] := OMorris;
WriteLn('AssertChooseBestMovePhase1(testBoard3, testBoard4, OMorris) returns true -> ', AssertTrue(AssertChooseBestMovePhase1(testBoard3, testBoard4, OMorris)));
WriteLn();
{* Test ChooseBestMovePhase2 *}
InitBoard(testBoard3);
InitBoard(testBoard4);
computerMorris := XMorris;
morrisType := OMorris;
RunCvCPhase1(testBoard4, computerMorris, morrisType, count);
testBoard3 := testBoard4;
testBoard4[1][1] := OMorris;
testBoard4[3][2] := DefaultMorris;
WriteLn('Test ChooseBestMovePhase2');
WriteLn('AssertChooseBestMovePhase2(testBoard3, testBoard4, OMorris) -> ', AssertTrue(AssertChooseBestMovePhase2(testBoard3, testBoard4, OMorris)));
END;
PROCEDURE RunPlayerVsComputer;
VAR
option: INTEGER;
computerMorris: CHAR;
morrisType: CHAR;
mainBoard: Board;
BEGIN
InitBoard(mainBoard);
morrisType := XMorris;
WriteLn('Who should start ?');
WriteLn('1. You');
WriteLn('2. Computer');
ReadLn(option);
IF option = 1 THEN
computerMorris := OMorris
ELSE IF option = 2 THEN
computerMorris := XMorris
ELSE BEGIN
WriteLn('Invalid input !');
RunPlayerVsComputer;
END;
RunPvCPhase1(mainBoard, computerMorris, morrisType);
RunPvCPhase2(mainBoard, computerMorris, morrisType);
morrisType := GetSwitchedMorrisType(morrisType);
WriteLn('Player ', morrisType, ' wins !');
END;
PROCEDURE RunPlayerVsPlayer;
VAR
mainBoard: Board;
morrisType: CHAR;
BEGIN
InitBoard(mainBoard);
morrisType := XMorris;
DisplayBoard(mainBoard);
RunPvPPhase1(mainBoard, morrisType);
RunPVPPhase2(mainBoard, morrisType);
morrisType := GetSwitchedMorrisType(morrisType);
WriteLn('Player ', morrisType, ' wins !');
END;
PROCEDURE RunComputerVsComputer;
VAR
computerMorris: CHAR;
morrisType: CHAR;
mainBoard: Board;
count: INTEGER;
BEGIN
count := 0;
InitBoard(mainBoard);
computerMorris := XMorris;
morrisType := XMorris;
RunCvCPhase1(mainBoard, computerMorris, morrisType, count);
RunCvCPhase2(mainBoard, computerMorris, morrisType, count);
morrisType := GetSwitchedMorrisType(morrisType);
WriteLn('Player ', morrisType, ' wins !');
WriteLn('moves: ', count);
END;
PROCEDURE StartOption(option: INTEGER);
BEGIN
IF option = 1 THEN
RunPlayerVsPlayer()
ELSE IF option = 2 THEN
RunPlayerVsComputer()
ELSE IF option = 3 THEN
RunComputerVsComputer()
ELSE IF option = 4 THEN
RunTests()
ELSE BEGIN
WriteLn('Option not found');
END;
END;
PROCEDURE ChooseOption;
VAR
option: INTEGER;
BEGIN
WriteLn();
WriteLn('-------------------');
WriteLn('Three Men''s Morris');
WriteLn('-------------------');
WriteLn('Please choose your option:');
WriteLn('1. Player vs Player');
WriteLn('2. Player vs Computer');
WriteLn('3. Computer vs Computer');
WriteLn('4. Testing');
ReadLn(option);
StartOption(option);
ChooseOption();
END;
{* Main Programm *}
BEGIN
ChooseOption();
END. |
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, NtBase;
type
TForm1 = class(TForm)
LanguageGroup: TRadioGroup;
NameGroup: TRadioGroup;
Label1: TLabel;
procedure FormCreate(Sender: TObject);
procedure LanguageGroupClick(Sender: TObject);
procedure NameGroupClick(Sender: TObject);
private
FUpdating: Boolean;
FLanguages: TNtLanguages;
procedure UpdateLanguages;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
NtLocalization, NtTranslator;
procedure TForm1.UpdateLanguages;
var
i: Integer;
begin
// Update the language names and the language selection.
FUpdating := True;
for i := 0 to FLanguages.Count - 1 do
begin
LanguageGroup.Items[i] := FLanguages[i].Names[TNtLanguageName(NameGroup.ItemIndex)];
if FLanguages[i].Code = TNtBase.GetActiveLocale then
LanguageGroup.ItemIndex := i;
end;
if LanguageGroup.ItemIndex = -1 then
LanguageGroup.ItemIndex := 0;
FUpdating := False;
end;
procedure TForm1.FormCreate(Sender: TObject);
var
i: Integer;
begin
// Get available languages
FLanguages := TNtLanguages.Create;
FLanguages.AddDefault;
TNtBase.GetAvailable(FLanguages);
// Initialize components
LanguageGroup.Columns := FLanguages.Count;
for i := 0 to FLanguages.Count - 1 do
LanguageGroup.Items.AddObject('', TObject(i));
NameGroup.ItemIndex := 0;
end;
procedure TForm1.LanguageGroupClick(Sender: TObject);
begin
if FUpdating then
Exit;
// User clicked a language button. Turn that language on.
TNtTranslator.SetNew(FLanguages[LanguageGroup.ItemIndex].Code);
UpdateLanguages;
end;
procedure TForm1.NameGroupClick(Sender: TObject);
begin
// Naming mode has been changed.
// Update the list to contain correct language names.
UpdateLanguages;
end;
initialization
DefaultLocale := 'en';
end.
|
unit SysInfo;
// CPU detection code adapted from http://www.bvbcode.com/code/06qjxeis-1648646
interface
const
CPU_TYPE_INTEL = 1;
CPU_TYPE_AMD = 2;
VendorIDIntel: array [0..11] of Char = 'GenuineIntel';
VendorIDAMD: array [0..11] of Char = 'AuthenticAMD';
type
TSysInfo = class
private
procedure CallCPUID(ValueEAX, ValueECX: Cardinal; var ReturnedEAX, ReturnedEBX, ReturnedECX, ReturnedEDX);
procedure ProcessIntel(HiVal: Cardinal);
procedure ProcessAMD(HiVal: Cardinal);
procedure DetectCPU;
public
CPUType: Byte;
VendorIDString: array [0..11] of Char;
CpuName: array [0..47] of Char;
PhysicalCore: Byte;
// Constructors and Destructors.
constructor Create;
end;
implementation
procedure TSysInfo.CallCPUID(ValueEAX, ValueECX: Cardinal; var ReturnedEAX, ReturnedEBX, ReturnedECX, ReturnedEDX);
begin
asm
PUSH EDI
PUSH EBX
MOV EAX, ValueEAX
MOV ECX, ValueECX
// CPUID
DB 0FH
DB 0A2H
MOV EDI, ReturnedEAX
MOV Cardinal PTR [EDI], EAX
MOV EAX, ReturnedEBX
MOV EDI, ReturnedECX
MOV Cardinal PTR [EAX], EBX
MOV Cardinal PTR [EDI], ECX
MOV EAX, ReturnedEDX
MOV Cardinal PTR [EAX], EDX
POP EBX
POP EDI
end;
end;
procedure TSysInfo.ProcessIntel(HiVal: Cardinal);
var
ExHiVal, EAX, EBX, ECX, EDX: Cardinal;
begin
CpuType := CPU_TYPE_INTEL;
if HiVal >= 4 then
begin
CallCPUID(4, 0, EAX, EBX, ECX, EDX);
PhysicalCore := ((EAX and $FC000000) shr 26) + 1;
end;
CallCPUID($80000000, 0, ExHiVal, EBX, ECX, EDX);
if ExHiVal >= $80000002 then
CallCPUID($80000002, 0, CpuName[0], CpuName[4], CpuName[8], CpuName[12]);
if ExHiVal >= $80000003 then
CallCPUID($80000003, 0, CpuName[16], CpuName[20], CpuName[24], CpuName[28]);
if ExHiVal >= $80000004 then
CallCPUID($80000004, 0, CpuName[32], CpuName[36], CpuName[40], CpuName[44]);
end;
procedure TSysInfo.ProcessAMD(HiVal: Cardinal);
var
ExHiVal, EAX, EBX, ECX, EDX: Cardinal;
begin
CpuType := CPU_TYPE_AMD;
CallCPUID($80000000, 0, ExHiVal, EBX, ECX, EDX);
if ExHiVal >= $80000002 then
CallCPUID($80000002, 0, CpuName[0], CpuName[4], CpuName[8], CpuName[12]);
if ExHiVal >= $80000003 then
CallCPUID($80000003, 0, CpuName[16], CpuName[20], CpuName[24], CpuName[28]);
if ExHiVal >= $80000004 then
CallCPUID($80000004, 0, CpuName[32], CpuName[36], CpuName[40], CpuName[44]);
if ExHival >= $80000008 then //get PhysicalCore;
begin
CallCPUID($80000008,0, EAX, EBX, ECX, EDX);
PhysicalCore := ECX and $F + 1;
end;
end;
procedure TSysInfo.DetectCPU;
var
Hival: Cardinal;
begin
PhysicalCore := 1;
CallCPUID(0, 0, HiVal, VendorIDString[0], VendorIDString[8], VendorIDString[4]);
if VendorIDString = VendorIDIntel then
ProcessIntel(HiVal)
else if VendorIDString = VendorIDAMD then
ProcessAMD(HiVal);
end;
constructor TSysInfo.Create;
begin
DetectCPU;
end;
end.
|
unit uPrintGuideReceipt;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, Db, DBTables, ComCtrls, ADODB, siComp, siLangRT,
PaiDeForms;
type
TPrintGuideReceipt = class(TFrmParentForms)
lblPrint: TLabel;
pnlPrinter: TPanel;
AniPrint: TAnimate;
btOk: TButton;
quTourGroup: TADOQuery;
quLancamento: TADOQuery;
quTourGroupEnterDate: TDateTimeField;
quTourGroupNumTourist: TIntegerField;
quTourGroupNumInvoices: TIntegerField;
quLancamentoDataLancamento: TDateTimeField;
quLancamentoTotalQuitado: TFloatField;
quLancamentoIDLancamento: TIntegerField;
quLancamentoGuide: TStringField;
quLancamentoAgency: TStringField;
quLancamentoGuideLastName: TStringField;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure btOkClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
//Translation
sCommReceipt,
sReprint,
sNoPayable,
sGuide,
sAgenci,
sDate,
sAmount,
sTourGroup,
sPax,
sInvoice,
sSignature,
sNome,
sPayBy,
sEndTicket,
sRecImpresso,
sClickOK : String;
MyIDLancamento : Integer;
ActualTime : TDateTime;
Quit : Boolean;
procedure ImpHeaderReceipt(Date: TDateTime; Valor: Currency ; Guide, Agency: String; Reprint: Boolean);
procedure ImpLine(NumPax, NumInvoices: Integer; EnterDate: TDateTime);
procedure ImpFooter;
public
{ Public declarations }
procedure Start(IDLancamento : Integer; Reprint: Boolean);
end;
implementation
uses uDM, uPassword, uNumericFunctions, XBase, uMsgBox, uMsgConstant,
uSqlFunctions, uDateTimeFunctions, uDMGlobal;
{$R *.DFM}
procedure TPrintGuideReceipt.Start(IDLancamento : Integer; Reprint: Boolean);
var
NotOk: Boolean;
begin
Quit := False;
MyIDLancamento := IDLancamento;
with quLancamento do
begin
Parameters.ParambyName('IDLancamento').Value := MyIDLancamento;
Open;
end;
with quTourGroup do
begin
Parameters.ParambyName('IDLancamento').Value := MyIDLancamento;
Open;
end;
Show;
Update;
Application.ProcessMessages;
NotOk := True;
while NotOk do
begin
try
DM.PrinterStart;
NotOk := False;
except
if MsgBox(MSG_CRT_ERROR_PRINTING, vbCritical + vbYesNo) = vbYes then
NotOk := True
else
begin
Exit;
end;
end;
end;
// -----------------------------------------------------------------
// Impressão do cabecalho do ticket
ImpHeaderReceipt( quLancamentoDataLancamento.AsDateTime,
quLancamentoTotalQuitado.AsCurrency,
quLancamentoGuide.AsString + ','+ quLancamentoGuideLastName.AsString,
quLancamentoAgency.AsString, Reprint);
// -----------------------------------------------------------------
// Impressão dos tourgroups
with quTourGroup do
begin
DisableControls;
First;
while not Eof do
begin
ImpLine( quTourGroupNumTourist.AsInteger,
quTourGroupNumInvoices.AsInteger,
quTourGroupEnterDate.AsDateTime);
Next;
end;
EnableControls;
end;
// -----------------------------------------------------------------
// Impressão dos Totais
ImpFooter;
DM.PrintLine(Chr(27)+Chr(12));
DM.PrinterStop;
lblPrint.Caption := sRecImpresso;
btOk.Visible := True;
AniPrint.Active := False;
AniPrint.Visible := False;
pnlPrinter.Caption := sClickOK;
Close;
end;
procedure TPrintGuideReceipt.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TPrintGuideReceipt.ImpHeaderReceipt( Date: TDateTime;
Valor: Currency;
Guide, Agency: String;
Reprint: Boolean);
begin
DM.PrintLine('========================================');
DM.PrintLine(sCommReceipt);
DM.PrintLine(' ---------------------------------- ');
DM.PrintLine('');
if Reprint then
begin
DM.PrintLine('');
DM.PrintLine(' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ');
DM.PrintLine(sReprint);
DM.PrintLine(sNoPayable);
DM.PrintLine(' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ');
DM.PrintLine('');
end;
DM.PrintLine(sGuide + Guide);
DM.PrintLine(sAgenci + Agency);
DM.PrintLine('');
DM.PrintLine(sDate + DateToStr(Date) );
DM.PrintLine(sAmount + FloatToStrF(Valor, ffCurrency, 20, 2));
DM.PrintLine('');
DM.PrintLine(sTourGroup);
DM.PrintLine('');
end;
procedure TPrintGuideReceipt.ImpLine(NumPax, NumInvoices: Integer; EnterDate: TDateTime);
begin
DM.PrintLine(' ' + DateToStr(EnterDate)+ ' ' +sPax + RightStr(' ' + IntToStr(NumPax) ,3) + sInvoice + RightStr(' ' + IntToStr(NumInvoices) ,3) );
DM.PrintLine('');
end;
procedure TPrintGuideReceipt.ImpFooter();
begin
DM.PrintLine('');
DM.PrintLine('');
DM.PrintLine('');
DM.PrintLine('');
DM.PrintLine(' ------------------------------------ ');
DM.PrintLine(sSignature);
DM.PrintLine('');
DM.PrintLine('');
DM.PrintLine(' ------------------------------------ ');
DM.PrintLine(sNome);
DM.PrintLine('');
DM.PrintLine('');
DM.PrintLine(' ------------------------------------ ');
DM.PrintLine(sPayBy);
DM.PrintLine('');
DM.PrintLine('');
DM.PrintLine('');
DM.PrintLine(sEndTicket);
DM.PrintLine('');
DM.PrintLine('');
DM.PrintLine('');
DM.PrintLine('');
DM.PrintLine('');
DM.PrintLine('');
end;
procedure TPrintGuideReceipt.FormShow(Sender: TObject);
begin
// Associa o fileName do Avi
AniPrint.Active := True;
btOk.Visible := False;
end;
procedure TPrintGuideReceipt.btOkClick(Sender: TObject);
begin
Close;
end;
procedure TPrintGuideReceipt.FormCreate(Sender: TObject);
begin
inherited;
Case DMGlobal.IDLanguage of
LANG_ENGLISH :
begin
sCommReceipt := ' C O M M I S S I O N R E C E I P T ';
sReprint := ' !! R E P R I N T !! ';
sNoPayable := ' !! N O T P A Y A B L E !! ';
sGuide := ' Guide: ';
sAgenci := ' Agency: ';
sDate := ' Date: ';
sAmount := ' Amount: ';
sTourGroup := '-------------- Tour Groups -------------';
sPax := ' Pax:';
sInvoice := ' Invoices:';
sSignature := ' Signature';
sNome := ' Name';
sPayBy := ' Payed By';
sEndTicket := '===============END OF TICKET============';
sRecImpresso := 'Receipt Printed';
sClickOK := 'Click OK to continue';
end;
LANG_PORTUGUESE :
begin
sCommReceipt := ' R E C I B O DE C O M I S S A O ';
sReprint := ' !! R E - I M P R E S S O !! ';
sNoPayable := ' !! N Ã O P A G A R !! ';
sGuide := ' Guia : ';
sAgenci := 'Agencia: ';
sDate := ' Data: ';
sAmount := ' Valor: ';
sTourGroup := '----------- Grupo de Turísmo -----------';
sPax := 'Pasg:';
sInvoice := ' Notas:';
sSignature := ' Assinatura';
sNome := ' Nome';
sPayBy := ' Pago por';
sEndTicket := '=============FINAL DO RECEBO============';
sRecImpresso := 'Recibo Impresso';
sClickOK := 'Clique OK para continuar';
end;
LANG_SPANISH :
begin
sCommReceipt := ' R E C I B O DE C O M I S I O N ';
sReprint := ' !! D U P L I C A D O !! ';
sNoPayable := ' !! N O P A G A R !! ';
sGuide := ' Guia : ';
sAgenci := 'Agencia: ';
sDate := ' Fecha : ';
sAmount := ' Valor: ';
sTourGroup := '-------------- Grupo Turismo -----------';
sPax := 'Pasj:';
sInvoice := ' Boletas:';
sSignature := ' Firma';
sNome := ' Nombre';
sPayBy := ' Pagado por';
sEndTicket := '==============FINAL DEL RECIBO==========';
sRecImpresso := 'Recibo Imprimido';
sClickOK := 'Clic OK para continuar';
end;
end;
end;
end.
|
unit DSA.Tree.PriorityQueue;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
DSA.Interfaces.Comparer,
DSA.Interfaces.DataStructure,
DSA.Tree.Heap;
type
TQueueKind = (Min, Max);
{ TPriorityQueue }
generic TPriorityQueue<T, TComparer> = class(TInterfacedObject,
specialize IQueue<T>)
private
type
THeap_T = specialize THeap<T, TComparer>;
IComparer_T = specialize IDSA_Comparer<T>;
var
__heap: THeap_T;
public
function GetSize: integer;
function IsEmpty: boolean;
procedure EnQueue(e: T);
function DeQueue: T;
function Peek: T;
constructor Create(queueKind: TQueueKind); overload;
constructor Create(queueKind: TQueueKind; c: IComparer_T); overload;
end;
implementation
{ TPriorityQueue }
constructor TPriorityQueue.Create(queueKind: TQueueKind);
begin
case queueKind of
Min:
__heap := THeap_T.Create(10, THeapkind.Min);
Max:
__heap := THeap_T.Create(10, THeapkind.Max);
end;
end;
constructor TPriorityQueue.Create(queueKind: TQueueKind; c: IComparer_T);
begin
Self.Create(queueKind);
__heap.SetComparer(c);
end;
function TPriorityQueue.DeQueue: T;
begin
Result := __heap.ExtractFirst;
end;
procedure TPriorityQueue.EnQueue(e: T);
begin
__heap.Add(e);
end;
function TPriorityQueue.Peek: T;
begin
Result := __heap.FindFirst;
end;
function TPriorityQueue.GetSize: integer;
begin
Result := __heap.Size;
end;
function TPriorityQueue.IsEmpty: boolean;
begin
Result := __heap.IsEmpty;
end;
end.
|
unit uModelBaseTypeIntf;
interface
uses DBClient, uParamObject, uBaseInfoDef, uModelBaseIntf;
type
IModelBaseTypeItype = interface(IModelBaseType) //基本信息编辑框-加载包
['{9743BAEE-5ADD-459E-8DFC-1168B55FDDDE}']
end;
IModelBaseTypePtype = interface(IModelBaseType) //基本信息编辑框-商品
['{759C8A8C-D902-4766-A655-450F880D582F}']
function SaveOneUnitInfo(aUnitInfo :TParamObject): Integer;//保存一条多单位信息
function GetUnitInfo(aPtypeId :string; ACdsU: TClientDataSet): Integer;//获取一个商品所有的多单位信息
end;
IModelBaseTypeBtype = interface(IModelBaseType) //基本信息编辑框-单位
['{DDD5E30A-E089-4E81-84AE-DC5A8D8ABEEE}']
end;
IModelBaseTypeEtype = interface(IModelBaseType) //基本信息编辑框-职员
['{5E8A8A03-D074-4390-8E4D-F3AEA4A239BA}']
end;
IModelBaseTypeDtype = interface(IModelBaseType) //基本信息编辑框-部门
['{A5C30EA0-E998-4232-8825-7B7BF37DC633}']
end;
IModelBaseTypeKtype = interface(IModelBaseType) //基本信息编辑框-仓库
['{F6F65231-46D9-4B17-988B-8E685E1BD0CC}']
end;
implementation
end.
|
unit uUtils;
{*******************************************************************************
* *
* Название модуля : *
* *
* uUtils *
* *
* Назначение модуля : *
* *
* Централизованное хранение используемых в приложении процедур и функций. *
* *
* Copyright © Год 2005, Автор: Найдёнов Е.А *
* *
*******************************************************************************}
interface
uses Windows, Classes, SysUtils, Dialogs, Controls, uTypes;
procedure LogException ( const aFileName: TFileName );
procedure SortFileList ( var aFileList: TStringList; aSortMode: TSortMode = smAlphabetically );
procedure ExtractKeyBlock ( var aKeyBlock: String; var aSeparatorCount: Integer; const aSeparatorChar: String );
procedure CreateMyProcess ( const aAppName, aCommandLine: PAnsiChar; aWindowState: Word );
procedure SetDirEndDelimiter ( var aDirPath: String );
function RenameScript ( var aFileName: String; const aKeyExpr, aSeparatorChar, aErrorChar : String; const aIsValid, aFullRename: Boolean; const aPrefixCharCount: Integer ): Boolean;
function GetScriptNames ( const aScriptDir, aSeparatorChar, aKeyExpr: String; const aPrefixCharCount: Integer; var aScriptNames: TStringList ): Boolean;
function GetScriptStatus ( const aScrStatus: TScriptStatus ): String;
function GetScriptNamesExt ( const aScriptDir, aSeparatorChar, aKeyExpr: String; const aPrefixCharCount: Integer; const aBackUpDate: TDate; var aScriptNames: TStringList ): Boolean;
implementation
uses StrUtils, DateUtils;
procedure LogException ( const aFileName: TFileName );
{*******************************************************************************
* *
* Название процедуры : *
* *
* LogException *
* *
* Назначение процедуры : *
* *
* Процедура протоколирует ошибки, возникающие в приложении *
* *
* IN: *
* *
* aFileName - полный путь к файлу протокола. *
* *
*******************************************************************************}
var
m : word;
Buf : array[0..511] of char;
FStream : TFileStream;
begin
if FileExists( aFileName )
then
m := fmOpenReadWrite
else
m := fmCreate;
FStream := TFileStream.Create( aFileName, m );
FStream.Seek( 0, soFromEnd );
StrPCopy( Buf, DateTimeToStr(Now)+ '. ' );
ExceptionErrorMessage( ExceptObject, ExceptAddr, @Buf[ StrLen(Buf) ], SizeOf(Buf) - StrLen(Buf) );
StrCat( Buf, #13#10 );
FStream.WriteBuffer( Buf, StrLen(Buf) );
FStream.Free;
end; //End of procedure LogException
procedure CreateMyProcess ( const aAppName, aCommandLine: PAnsiChar; aWindowState: Word );
{*******************************************************************************
* *
* Название процедуры : *
* *
* CreateMyProcess *
* *
* Назначение процедуры : *
* *
* Процедура создаёт процесс, в рамках которого в режиме коммандной строки *
* выполняется некоторое приложение. *
* *
* IN: *
* *
* aAppName - полный путь к запускаемому приложению. *
* aCommandLine - параметры коммандной строки. *
* aWindowState - тип прорисовки окна приложения. *
* *
*******************************************************************************}
var
Result : Boolean;
ExitCode : Cardinal;
ProcessInfo : TProcessInformation;
StartUpInfo : TStartupInfo;
begin
try
//Инициализируем объявленные структуры
FillChar(StartUpInfo, SizeOf(TStartUpInfo), 0);
with StartUpInfo do
begin
cb := SizeOf(TStartUpInfo);
dwFlags := STARTF_USESHOWWINDOW or STARTF_FORCEONFEEDBACK;
wShowWindow := aWindowState;
end;
//Создаём процесс
Result := CreateProcess( aAppName, aCommandLine, nil, nil, False, NORMAL_PRIORITY_CLASS, nil, nil, StartUpInfo, ProcessInfo);
if Result
then
with ProcessInfo do
begin
WaitForInputIdle(hProcess, INFINITE); // ждем завершения инициализации
WaitforSingleObject(ProcessInfo.hProcess, INFINITE); // ждем завершения процесса
GetExitCodeProcess(ProcessInfo.hProcess, ExitCode); // получаем код завершения
CloseHandle(hThread); // закрываем дескриптор процесса
CloseHandle(hProcess); // закрываем дескриптор потока
end;
except
LogException( cERROR_FILE_NAME );
end;
end; //End of procedure CreateMyProcess
procedure SortFileList( var aFileList: TStringList; aSortMode: TSortMode = smAlphabetically );
{*******************************************************************************
* *
* Название процедуры : *
* *
* SortFileList *
* *
* Назначение процедуры : *
* *
* Процедура сортирует список имён файлов. *
* *
* IN: *
* *
* aFileList - список имён файлов, подлежащий сортировке. *
* aSortMode - критерий сортировки. *
* *
* OUT: *
* *
* aFileList - отсортированный список имён файлов. *
* *
*******************************************************************************}
begin
case aSortMode of
smAlphabetically : begin
aFileList.Sorted := True;
end;
smDate : begin
end;
smOrder : begin
end;
end;
end; //End of procedure SortFileList
procedure ExtractKeyBlock ( var aKeyBlock: String; var aSeparatorCount: Integer; const aSeparatorChar: String );
{*******************************************************************************
* *
* Название процедуры : *
* *
* ExtractKeyBlock *
* *
* Назначение процедуры : *
* *
* Процедура выделяет блок ключевых выражений.(данная процедура явл. *
* вспомогательной) *
* *
* IN: *
* *
* aKeyBlock - строка, содержащая блоки ключевых выражений. *
* aSeparatorChar - символ-разделител, отделяющий друг от друга блоки *
* ключевых выражений. *
* aSeparatorCount - количество начальных символов-разделителей *
* *
* OUT: *
* *
* aKeyBlock - строка, содержащая 1 блок ключевых выражений. *
* aSeparatorCount - количество начальных символов-разделителей *
* *
*******************************************************************************}
var
Counter : Integer;
CharIndex : Integer;
begin
try
Counter := 0;
CharIndex := 0;
aKeyBlock := aSeparatorChar + aKeyBlock;
aSeparatorCount := 0;
//Ищем начало блока ключевых выражений
repeat
Inc( Counter );
CharIndex := PosEx( aSeparatorChar, aKeyBlock, CharIndex + 1 );
until ( aKeyBlock[CharIndex] <> aKeyBlock[CharIndex + 1] );
//Получаем количество начальных символов-разделителей
aSeparatorCount := Counter - 1;
//Отсекаем последовательность символов-разделителей, с которых начинается строка
Delete( aKeyBlock, 1, CharIndex );
CharIndex := Pos( aSeparatorChar, aKeyBlock );
//Отсекаем все символы, следующие за блоком ключевых выражений
Delete( aKeyBlock, CharIndex, Length( aKeyBlock ) - CharIndex + 1 );
except
LogException( cERROR_FILE_NAME );
end;
end; //End of procedure ExtractKeyBlock
function RenameScript( var aFileName: String; const aKeyExpr, aSeparatorChar, aErrorChar: String; const aIsValid, aFullRename: Boolean; const aPrefixCharCount: Integer ): Boolean;
{*******************************************************************************
* *
* Название функции : *
* *
* RenameScript *
* *
* Назначение функции : *
* *
* Ф-ция переименовывает файл скрипта в соответствии с принятым форматом. *
* *
* IN: *
* *
* aIsValid - признак, показывающий успешно ли был выполнен скрипт *
* aFullRename - признак, указывающий нужно ли полностью переименовы- *
* вать скрипт *
* aKeyExpr - один или несколько ключевых символов, определяющие *
* критерий отбора файлов скриптов. *
* aFileName - полный путь к файлу скрипта. *
* aErrorChar - "специальный" символ в имени файла скрипта, указыва- *
* ющий на то, что данный скрипт был применён с ошибками*
* aSeparatorChar - символ-разделитель, используемый для именования фай- *
* лов скриптов. *
* aPrefixCharCount - количество первых символов в именах файлов скриптов, *
* не используемых при анализе. *
* *
* OUT: *
* *
* Result - результат переименования файла. *
* *
* RESULT: Boolean. *
* *
* Если файл скрипта успешно переименован, то результат *
* возвращаемый функцией - истина, если нет - ложь. *
* *
*******************************************************************************}
var
i, j, m, n : Integer;
Delta : String;
IsValid : Boolean;
TmpBlock : String;
KeyBlock : String;
KeyIndex : Integer;
SepCount : Integer;
KeyBlocks : TStringList;
CharIndex : Integer;
FmtSettings : TFormatSettings;
TmpFileName : String;
DelCharCount : Integer;
begin
try
try
//Проверяем: не был ли удалён с сервера файл скрипта во время тестирования
if FileExists( aFileName )
then begin
TmpFileName := ExtractFileName( aFileName );
DelCharCount := aPrefixCharCount;
KeyBlock := TmpFileName;
//Получаем количество дней между датой создания скрипта и датой его применения
FmtSettings.DateSeparator := cDATE_SEPARATOR;
FmtSettings.ShortDateFormat := cFORMAT_DATE_TO_STR;
CharIndex := Pos( aSeparatorChar, Copy( KeyBlock, 1, DelCharCount ) );
Delete( KeyBlock, CharIndex, Length( KeyBlock ) - CharIndex + 1 );
//Добавляем к разнице между двумя датами управляющий ноль
Delta := IntToStr( DaysBetween( Date, StrToDate( KeyBlock, FmtSettings ) ) );
if StrToInt( Delta ) < 10
then
Delta := '0' + Delta;
KeyBlocks := TStringList.Create;
//Выделяем из имени файла блоки ключевых исмволов
repeat
KeyBlock := TmpFileName;
Delete( KeyBlock, 1, DelCharCount );
ExtractKeyBlock( KeyBlock, SepCount, aSeparatorChar );
KeyIndex := Pos( aKeyExpr, KeyBlock );
KeyBlocks.Add( KeyBlock );
DelCharCount := DelCharCount + Length( KeyBlock ) + SepCount;
until ( DelCharCount >= Length( TmpFileName ) );
n := KeyBlocks.Count - 3;
KeyIndex := Pos( KeyBlocks.Strings[1], TmpFileName ) + Length( KeyBlocks.Strings[1] );
//Формируем имя скрипта с учётом результата его применения
if aIsValid
then
TmpBlock := aKeyExpr + Delta
else
TmpBlock := aErrorChar + aKeyExpr + Delta;
TmpBlock := aSeparatorChar + aSeparatorChar + TmpBlock;
//Находим среди блоков ключевых символов позицию для данного блока(блоки должны располагаться в алфавитном порядке)
for i := 2 to n do
begin
m := Length( KeyBlocks.Strings[i] );
//Выделяем блок ключевых симлов, отбрасывая все цифры
for j := 1 to m
do
//Находим и отсекаем последовательность цифр в блоке ключевых символов
if KeyBlocks.Strings[i][j] in cDIGITS
then begin
KeyBlock := KeyBlocks.Strings[i];
Delete( KeyBlock, j, Length( KeyBlock ) - j + 1 );
Break;
end;
//Отсекаем последовательность символов, указывающих на ошибки при применении скрипта
Delete( KeyBlock, Pos( aErrorChar, KeyBlock ), Length( aErrorChar ) );
//Проверяем алфавитный порядок следования блоков, указывающих на дату применения скрипта
if KeyBlock < aKeyExpr
then begin
KeyIndex := Pos( KeyBlocks.Strings[i], TmpFileName ) + Length( KeyBlocks.Strings[i] );
end;
end;
//Вставляем в имя файла скрипта кол-во дней, прошедших с момента его создания
Insert( TmpBlock, TmpFileName, KeyIndex );
KeyIndex := Pos( aKeyExpr, KeyBlocks.Strings[0] );
KeyBlock := KeyBlocks.Strings[1];
IsValid := True;
//Проверяем: корректно ли зарезервировано место для ключевого выражения во 2-ом блоке
n := KeyIndex + Length( aKeyExpr ) - 1 ;
for i := KeyIndex to n do
if KeyBlock[i] <> cEMPTY_CHAR
then begin
IsValid := False;
Break;
end;
//Проверяем: подлежит ли полному переименованию данный скрипт?
if aFullRename
then begin
//Вставляем во 2-ой блок ключевое выражение
CharIndex := Pos( KeyBlocks.Strings[1], TmpFileName );
if IsValid
then
Delete( TmpFileName, CharIndex + KeyIndex - 1, Length( aKeyExpr ) );
Insert( aKeyExpr, TmpFileName, CharIndex + KeyIndex - 1 );
end;
//Возвращаем сформированние "новое" имя скрипта
aFileName := ExtractFilePath( aFileName ) + TmpFileName;
Result := True;
end
else
Result := False;
finally
KeyBlocks.Free;
end;
except
LogException( cERROR_FILE_NAME );
end;
end; //End of procedure RenameScript
function GetScriptNamesExt ( const aScriptDir, aSeparatorChar, aKeyExpr: String; const aPrefixCharCount: Integer; const aBackUpDate: TDate; var aScriptNames: TStringList ): Boolean;
{*******************************************************************************
* *
* Название функции : *
* *
* GetScriptNamesExt *
* *
* Назначение функции : *
* *
* Формирование списков имён файлов скриптов, которые должны быть применены. *
* *
* IN: *
* aKeyExpr - один или несколько ключевых символов, определяющие *
* критерий отбора файлов скриптов. *
* aScriptDir - путь к папке, содержащей файлы скриптов для тестиро- *
* вания. *
* aSeparatorChar - символ-разделитель, используемый для именования фай- *
* лов скриптов. *
* aBackUpDate - дата самого "свежего" бекапа. *
* aScriptNames - список имён файлов скриптов, подлежащих тестированию.*
* aPrefixCharCount - количество первых символов в именах файлов скриптов, *
* не используемых при анализе. *
* *
* OUT: *
* aScriptNames - список имён файлов скриптов, подлежащих тестированию.*
* *
* RESULT: Boolean. *
* *
* Если хотя бы один файл скрипта для тестирования найден, то результат *
* возвращаемый функцией - истина, если нет - ложь. *
* *
*******************************************************************************}
var
i, n : Integer;
Index : Integer;
FileRec : TSearchRec;
KeyBlock : String;
KeyBlocks : TStringList;
KeyIndex : Integer;
SearchRes : Integer;
TmpFileName : String;
FmtSettings : TFormatSettings;
DelCharCount : Integer;
ScriptExists : Boolean;
DaysCountScr : Integer;
DateCreateScr : TDate;
DateExecuteScr : TDate;
SeparatorCount : Integer;
StrDateCreteScr : String;
begin
try
try
//Пытаемся найти хотя бы один файл скрипта
SearchRes := FindFirst( aScriptDir + cSCRIPTS_MASK, faAnyFile, FileRec );
//Если не найден ни один скрипт
if SearchRes <> 0
then begin
Result := False;
Exit;
end
else begin
aScriptNames.Clear;
KeyBlocks := TStringList.Create;
FmtSettings.DateSeparator := cDATE_SEPARATOR;
FmtSettings.ShortDateFormat := cFORMAT_DATE_TO_STR;
end;
//Пытаемся найти все существующие файлы скриптов
while ( SearchRes = 0 ) do
begin
TmpFileName := FileRec.Name;
//Получаем дату создания скрипта
StrDateCreteScr := Copy( TmpFileName, 1, cDATE_DIGITS_COUNT );
DateCreateScr := StrToDate( StrDateCreteScr, FmtSettings );
//Отсекаем дату создания + порядковый номер скрипта
Delete( TmpFileName, 1, aPrefixCharCount );
KeyBlocks.Clear;
//Выделяем из имени файла блоки ключевых исмволов
repeat
KeyBlock := TmpFileName;
ExtractKeyBlock( KeyBlock, SeparatorCount, aSeparatorChar );
KeyBlocks.Add( KeyBlock );
DelCharCount := Length( KeyBlock ) + SeparatorCount;
Delete( TmpFileName, 1, DelCharCount );
until ( Length( TmpFileName ) = 0 );
//Отбрасываем ключевые блоки, содержащие ФИО, комментарий и не содержащие информации о дате применения скрипта
n := KeyBlocks.Count - 3;
ScriptExists := False;
//Проверяем: вошел ли скрипт в какое-либо обновление?
for i := 2 to n
do begin
Index := Pos( cUPDATE_EXPR, KeyBlocks.Strings[i] );
KeyIndex := Pos( aKeyExpr, KeyBlocks.Strings[i] );
//Вычисляем дату применения скрипта, не вошедшего ни в одно обновление
if ( Index = 0 ) AND ( KeyIndex <> 0 )
then begin
ScriptExists := True;
KeyBlock := KeyBlocks.Strings[i];
Delete( KeyBlock, 1, KeyIndex + Length( aKeyExpr ) - 1 );
DaysCountScr := StrToInt( KeyBlock );
DateExecuteScr := DateCreateScr + DaysCountScr;
end;
end;
//Запоминаем имя файла скрипта, подлежащего тестированию
if ScriptExists AND ( DateExecuteScr > aBackUpDate )
then begin
aScriptNames.Add( FileRec.Name );
end;
SearchRes := FindNext( FileRec );
end;
aScriptNames.Sorted := True;
//Формируем возвращаемый функцией результат
if aScriptNames.Count > 0
then begin
Result := True;
end;
finally
FindClose( FileRec );
if Assigned( KeyBlocks )
then
FreeAndNil( KeyBlocks );
end;
except
Result := False;
LogException( cERROR_FILE_NAME );
end;
end; //End of function GetScriptNamesExt
function GetScriptNames( const aScriptDir, aSeparatorChar, aKeyExpr: String; const aPrefixCharCount: Integer; var aScriptNames: TStringList ): Boolean;
{*******************************************************************************
* *
* Название функции : *
* *
* GetScriptNames *
* *
* Назначение функции : *
* *
* Формирование списка имён файлов скриптов, которые должны быть применены. *
* *
* IN: *
* *
* aKeyExpr - один или несколько ключевых символов, определяющие *
* критерий отбора файлов скриптов. *
* aScriptDir - путь к папке, содержащей файлы скриптов для тестиро- *
* вания. *
* aScriptNames - список имён файлов скриптов, подлежащих тестированию.*
* aSeparatorChar - символ-разделитель, используемый для именования фай- *
* лов скриптов. *
* aPrefixCharCount - количество первых символов в именах файлов скриптов, *
* не используемых при анализе. *
* *
* OUT: *
* *
* aScriptNames - список имён файлов скриптов, подлежащих тестированию.*
* *
* RESULT: Boolean. *
* *
* Если хотя бы один файл скрипта для применения найден, то результат *
* возвращаемый функцией - истина, если нет - ложь. *
* *
*******************************************************************************}
var
FileRec : TSearchRec;
SearchRes : Integer;
CharIndex : Integer;
TmpFileName : String;
DelCharCount : Integer;
begin
try
try
//Пытаемся найти хотя бы один файл скрипта
SearchRes := FindFirst( aScriptDir + cSCRIPTS_MASK, faAnyFile, FileRec );
if SearchRes = 0
then
Result := True
else
Result := False;
//Пытаемся найти все существующие файлы скриптов
while ( SearchRes = 0 ) do
begin
//Получаем 1-ый блок ключевых символов из имени файла скрипта
TmpFileName := FileRec.Name;
Delete( TmpFileName, 1, aPrefixCharCount );
ExtractKeyBlock( TmpFileName, DelCharCount, aSeparatorChar );
CharIndex := Pos( aKeyExpr, TmpFileName );
if CharIndex > 0
then begin
//Получаем 2-ой блок ключевых символов из имени файла скрипта
DelCharCount := aPrefixCharCount + Length( TmpFileName ) + DelCharCount;
TmpFileName := FileRec.Name;
Delete( TmpFileName, 1, DelCharCount );
ExtractKeyBlock( TmpFileName, DelCharCount, aSeparatorChar );
CharIndex := Pos( aKeyExpr, TmpFileName );
if CharIndex = 0
then begin
//Запоминаем имя файла скрипта, который нужно применить
aScriptNames.Add( FileRec.Name );
end;
end;
SearchRes := FindNext( FileRec );
end;
FindClose( FileRec );
aScriptNames.Sorted := True;
finally
end;
except
LogException( cERROR_FILE_NAME );
end;
end; //End of function GetScriptNames
function GetScriptStatus ( const aScrStatus: TScriptStatus ): String;
{*******************************************************************************
* *
* Название функции : *
* *
* GetScriptStatus *
* *
* Назначение функции : *
* *
* Возвращает в виде строки результат выполнения скриптов. *
* *
* IN: *
* *
* aScrStatus - параметр, содержащий результат выполнения скриптов. *
* *
* OUT: *
* *
* RESULT - строка, расшифровывающая результат выполнения скриптов. *
* *
*******************************************************************************}
begin
Result := cSCR_STATUS[ Ord( aScrStatus ) ];
end; //End of function GetScriptStatus
procedure SetDirEndDelimiter ( var aDirPath: String );
{*******************************************************************************
* *
* Название процедуры : *
* *
* SetDirEndDelimiter *
* *
* Назначение процедуры : *
* *
* В зависимости от типа ОС дополняет путь к дирректории корректным слешем, *
* если это необходимо. *
* *
* IN: *
* aDirPath - параметр, содержащий путь к дирректории. *
* OUT: *
* aDirPath - параметр, содержащий путь к дирректории. *
* *
*******************************************************************************}
begin
if Pos( cSEPARATOR_FOLDER_WIN, aDirPath ) <> 0
then begin
if aDirPath[ Length( aDirPath ) ] <> cSEPARATOR_FOLDER_WIN
then
aDirPath := aDirPath + cSEPARATOR_FOLDER_WIN
end
else
if aDirPath[ Length( aDirPath ) ] <> cSEPARATOR_FOLDER_UNX
then
aDirPath := aDirPath + cSEPARATOR_FOLDER_UNX;
end; //End of procedure SetDirEndDelimiter
end.
|
UNIT Mean4;
INTERFACE
// USES...
// TYPE
// Date = RECORD
// END;
// PROCUDRE....
{* Computes mean value of a sequence of numbers using an internal state. *}
{* IN nex: Next number in sequence to compute mean value for *}
{* OUT newMean: New mean value after considering "next". *}
{* RETURNS: .. *}
{* REF: .. *}
PROCEDURE Mean(next: INTEGER; VAR newMean: REAL);
{* Parameterlos ! *}
// FUNCTION LastMean: REAL;
IMPLEMENTATION
// USES ...
VAR
sum: INTEGER;
count: INTEGER;
PROCEDURE InitState;
BEGIN
sum := 0;
count := 0;
END;
PROCEDURE Mean(next: INTEGER; VAR newMean: REAL);
BEGIN
sum := sum + next;
count := count + 1;
newMean := sum / count;
END;
PROCEDURE Reset;
BEGIN
InitState;
END;
// optionaler Code, einmaliger Initialisierungscoode
BEGIN
InitState;
END. |
unit txTerms;
interface
uses Windows, WikiEngine_TLB, Classes, txDefs;
type
TTermStore=class(TObject)
private
FEnabled:boolean;
FInitError:string;
FInitTimeMS:integer;
FEngine:IEngine;
FList:TStringList;
FCurrentDomain:integer;
FCurrentSource:string;
FRenderLock:TRTLCriticalSection;
procedure DoCommands;
public
constructor Create(const DllPath: string);
destructor Destroy; override;
function TermLinks(ItemType:TtxItemType;ItemID,domainID:integer;xHTML:WideString):WideString;
procedure StoreTerms(ItemType:TtxItemType;ItemID,domainFromObjID:integer;xHTML:WideString);
function GetDomainID(ObjID:integer):integer;
property InitError:string read FInitError;
property InitTimeMS:integer read FInitTimeMS;
end;
TTermCheck=class(TInterfacedObject, IWikiPageCheck)
private
FStore:TTermStore;
public
constructor Create(Store:TTermStore);
function CheckPage(var Name: WideString;
const CurrentGroup: WideString): WordBool; safecall;
end;
implementation
uses SysUtils, DataLank, txSession, ComObj, ActiveX;
//const Class_txWebTermCheck:TGUID='{00007478-0000-C057-0001-5465726D4368}';
type
ETermStoreException=class(Exception);
{ TTermStore }
constructor TTermStore.Create(const DllPath: string);
type
T_DGCO=function(const CLSID, IID: TGUID; var Obj): HResult; stdcall;//DllGetClassObject
var
tc:TTimerIndex;
p:T_DGCO;
f:IClassFactory;
begin
tc:=GetTimerIndex;
inherited Create;
FInitError:='';
FInitTimeMS:=-1;
if Use_Terms then
begin
FEnabled:=true;
FList:=TStringList.Create;
FList.Sorted:=true;
FList.CaseSensitive:=false;
FList.Duplicates:=dupIgnore;
InitializeCriticalSection(FRenderLock);
//FEngine:=CoEngine.Create;
try
p:=GetProcAddress(LoadLibrary(PChar(DllPath)),'DllGetClassObject');
if @p=nil then RaiseLastOSError;
OleCheck(p(CLASS_Engine,IClassFactory,f));
OleCheck(f.CreateInstance(nil,IEngine,FEngine));
FEngine.WikiParseXML:=ModulePath+'txWikiEngine.xml';
FEngine.WikiPageCheck:=TTermCheck.Create(Self);
except
on e:Exception do
begin
FEnabled:=false;
FInitError:='{'+e.ClassName+'}'+e.Message;
end;
end;
FInitTimeMS:=GetTimerIndexMS(tc);
end
else
begin
FEnabled:=false;
end;
end;
destructor TTermStore.Destroy;
begin
if Use_Terms then
begin
DeleteCriticalSection(FRenderLock);
FList.Free;
try
FEngine:=nil;
except
//silent, (issue with closing with WikiPageCheck set?)
pointer(FEngine):=nil;
end;
end;
inherited;
end;
function TTermStore.TermLinks(ItemType:TtxItemType;ItemID,domainID:integer;xHTML: WideString): WideString;
begin
FCurrentDomain:=domainID;
FCurrentSource:=txItemTypeKey[ITemType]+IntToStr(ItemID);
try
if FEnabled then
begin
EnterCriticalSection(FRenderLock);
try
Result:=FEngine.Render(xHTML,'');
DoCommands;
finally
LeaveCriticalSection(FRenderLock);
end;
end
else Result:=xHTML;
except
on ETermStoreException do raise;
on Exception do
begin
//TODO: log error somewhere?
Result:=xHTML;
end;
end;
if FEnabled then FList.Clear;
end;
function TTermStore.GetDomainID(ObjID:integer):integer;
var
x:integer;
begin
x:=ObjID;
Result:=0;
if FEnabled then
if Use_ObjPath then
Result:=DBSingleValue('SELECT Tok.obj_id FROM ObjPath INNER JOIN Tok ON Tok.obj_id=ObjPath.pid '+
'INNER JOIN TokType ON TokType.id=Tok.toktype_id AND TokType.system=''wiki.prefix'' WHERE ObjPath.oid=? ORDER BY ObjPath.lvl LIMIT 1',[x],0)
else
while (x<>0) and (Result=0) do
begin
if DBExists('SELECT Tok.id FROM Tok LEFT JOIN TokType ON TokType.id=Tok.toktype_id WHERE Tok.obj_id=? AND TokType.system=''wiki.prefix'' LIMIT 1',[x]) then
Result:=x
else
x:=DBSingleValue('SELECT pid FROM Obj WHERE id=?',[x],0);
end;
end;
procedure TTermStore.StoreTerms(ItemType:TtxItemType;ItemID,domainFromObjID:integer;xHTML:WideString);
var
i,d:integer;
src:string;
begin
if FEnabled then
begin
d:=GetDomainID(domainFromObjID);
src:=txItemTypeKey[ITemType]+IntToStr(ItemID);
FList.Clear;
EnterCriticalSection(FRenderLock);
try
try
FEngine.Render(xHTML,'');
DoCommands;
except
on ETermStoreException do raise;
on Exception do ;//silent
end;
finally
LeaveCriticalSection(FRenderLock);
end;
//transaction? diff?
Session.DbCon.Execute('DELETE FROM Trl WHERE Trl.source=?',[src]);
for i:=0 to FList.Count-1 do
Session.DbCon.Execute('INSERT INTO Trl (source,domain_id,term) VALUES (?,?,?)',[src,d,FList[i]]);
end;
end;
procedure TTermStore.DoCommands;
var
x,y:WideString;
begin
while FEngine.GetModification(x,y) do
begin
if x='error' then raise ETermStoreException.Create(y)
else
raise ETermStoreException.Create('[TermStore]Unknown command "'+x+'"');
end;
end;
{ TTermCheck }
constructor TTermCheck.Create(Store:TTermStore);
begin
inherited Create;
FStore:=Store;
end;
function TTermCheck.CheckPage(var Name: WideString;
const CurrentGroup: WideString): WordBool;
begin
//TODO: domain?
FStore.FList.Add(Name);
Result:=DBExists('SELECT Trm.obj_id FROM Trm WHERE Trm.domain_id=? AND lower(Trm.term)=lower(?) LIMIT 1',[FStore.FCurrentDomain,Name]);
//TODO: update name from DB?
if Result then
Name:='Term.xxm?d='+IntToStr(FStore.FCurrentDomain)+'&r='+FStore.FCurrentSource+'&n='
else
Name:='fTerm.xxm?d='+IntToStr(FStore.FCurrentDomain)+'&r='+FStore.FCurrentSource+'&n=';
end;
end.
|
unit gsF_Memo;
{-----------------------------------------------------------------------------
dBase III/IV & FoxPro Memo File Handler
gsF_Memo Copyright (c) 1996 Griffin Solutions, Inc.
Date
4 Apr 1996
Programmer:
Richard F. Griffin tel: (912) 953-2680
Griffin Solutions, Inc. e-mail: grifsolu@hom.net
102 Molded Stone Pl
Warner Robins, GA 31088
Modified (m) 1997-2000 by Valery Votintsev 2:5021/22
-------------------------------------------------------------
This unit handles the objects for all dBase III/IV Memo (.DBT)
and FoxPro (.FPT) file operations.
Changes:
!!RFG 102097 Added FoundError virtual method to pass errors to the
owning DBF object. This allows capture at a single
point regardless of the object that fails.
------------------------------------------------------------------------------}
{$I gsF_FLAG.PAS}
interface
uses
Strings,
gsF_Dos,
gsF_Eror,
gsF_Disk,
vString,
gsF_Xlat,
gsF_Glbl;
{private}
const
moHeaderSize = 32;
type
{! moLineCode = (NoReturn, HardReturn, SoftReturn);}
GSrecMemoHeader = packed record
case byte of
0 : (DBIV : SmallInt;
StartLoc : SmallInt;
LenMemo : longint;);
1 : (Fox20 : longint;);
2 : (NextEmty : longint;
BlksEmty : longint;);
3 : (BlkArray :array[0..31] of char;);
end;
GSptrMemo = ^GSobjMemo;
GSobjMemo = object(GSO_DiskFile)
Owner : GSP_DiskFile;
TypeMemo : Byte; {83 for dBase III; 8B for dBase IV; F5 for FoxPro}
MemoBufPtr : PChar;
MemoBuffer : PChar;
MemoBufSize : LongInt; {!VV - was integer}
MemoLocation : Longint; {Current Memo record location}
MemoBloksUsed: Longint; {Memo Size in blocks}
BytesPerBlok : longint; {Memo Block size}
MemoChanged : boolean; {Memo Changed Flag}
MemoHeader : GSrecMemoHeader;
{ MemoLineLen : integer;}
constructor Create(AOwner: GSP_DiskFile; const FName : String; DBVer, FM : byte);
destructor Destroy; virtual;
Procedure FoundError(Code, Info:integer; StP: PChar); virtual;
procedure moAdjustBuffer(NewSpace: longint);
function gsClose: boolean; virtual;
procedure moHuntAvailBlock(numbytes : longint); virtual;
procedure moMemoBlockRelease(rpt : longint); virtual;
Procedure moMemoClear;
procedure moMemoPutLast(ps: PChar); virtual;
function moMemoLock : boolean;
procedure moMemoSetParam(var bl: longint); virtual;
function moMemoOffSet: integer; virtual;
procedure gsOpen; virtual;
Procedure moMemo2File(blk: longint; const FileName:string);
Function moFile2Memo(blk: longint; const FileName:string):longint;
procedure moMemoRead(buf: pointer; blk: longint; var cb: longint);
Procedure moMemoSpaceUsed(blk: longint; var cb: longint);
function moMemoWrite(buf: pointer;var blk: longint;var cb: longint): longint;
(*!
function moFindLine(lnum: integer; var lstart, lend: PChar): integer;
Procedure moMemoDelLine(linenum : integer);
function moMemoGetLine(linenum : integer) : String;
Procedure moMemoInsert(linenum : integer; const st : String;
TypeRtn: moLineCode);
Procedure moMemoInsLine(linenum : integer; const st : String);
function moMemoLines : integer;
procedure moMemoGet(rpt : longint);
function moMemoPut(rpt : longint) : longint;
procedure moMemoWidth(l : integer);
*)
function moMemoSize(blk: longint): longint;
end;
(*
GSptrMemo3 = ^GSobjMemo3;
GSobjMemo3 = object(GSobjMemo)
end;
GSptrMemo4 = ^GSobjMemo4;
GSobjMemo4 = object(GSobjMemo)
procedure moMemoBlockRelease(rpt : longint); virtual;
procedure moHuntAvailBlock(numbytes : longint); virtual;
procedure moMemoPutLast(ps: PChar); virtual;
procedure moMemoSetParam(var bl: longint); virtual;
function moMemoOffSet: integer; virtual;
procedure gsOpen; virtual;
end;
*)
GSptrFXMemo20 = ^GSobjFXMemo20;
GSobjFXMemo20 = object(GSobjMemo)
constructor Create(AOwner: GSP_DiskFile; const FName : String; DBVer, FM : byte);
procedure moHuntAvailBlock(numbytes : longint); virtual;
procedure moMemoPutLast(ps: PChar); virtual;
procedure moMemoSetParam(var bl: longint); virtual;
function moMemoOffSet: integer; virtual;
procedure gsOpen; virtual;
end;
{------------------------------------------------------------------------------
IMPLEMENTATION SECTION
------------------------------------------------------------------------------}
implementation
const
WorkBlockSize = 32768; {Don't read from disk more than 32K bytes}
MaxEditLength = 255;
{------------------------------------------------------------------------------
GSobjMemo
------------------------------------------------------------------------------}
CONSTRUCTOR GSobjMemo.Create(AOwner: GSP_DiskFile; const FName : String;
DBVer, FM : byte);
var
ext : String[4];
pth : String;
begin
case DBVer of
DB3WithMemo,
DB4WithMemo : ext := '.DBT';
VFP3File,
FXPWithMemo : ext := '.FPT';
end;
pth := CapClip(FName,[' ','"']);
pth := ChangeFileExt(pth,ext);
inherited Create(pth,FM);
Owner := AOwner;
TypeMemo := DBVer;
MemoBufPtr := nil;
MemoBuffer := nil;
MemoBufSize := 0;
BytesPerBlok := dBaseMemoSize;
{! MemoLineLen := 255;}
MemoBloksUsed := 0;
MemoLocation := 0;
if not dfFileExst then
gsTestForOk(dosFileNotFound, mmoInitError)
else
begin
gsOpen;
ObjType := GSobtDBTFile;
end;
end;
destructor GSobjMemo.Destroy;
begin
inherited Destroy;
end;
Procedure GSobjMemo.FoundError(Code, Info:integer; StP: PChar);
begin {!!RFG 102097}
if Owner <> nil then
Owner^.FoundError(Code,Info,StP)
else
inherited FoundError(Code,Info,StP);
end;
Procedure GSobjMemo.moAdjustBuffer(NewSpace: longint);
var
linetemp: PChar;
lenchk: longint;
sof: integer;
begin
if MemoBufPtr <> nil then
sof := (moMemoOffset)+StrLen(MemoBuffer)
else
sof := moMemoOffset;
lenchk := sof+NewSpace+1;
if lenchk > 65519 then
begin
FoundError(gsMemoAccessError, mmoMemoTooLarge, nil);
exit;
end;
if lenchk > MemoBufSize then
begin {get one extra block, just in case}
lenchk := ((lenchk + BytesPerBlok) div BytesPerBlok) * BytesPerBlok;
GetMem(linetemp, lenchk);
FillChar(linetemp^,lenchk,#0);
if MemoBufPtr <> nil then
begin
Move(MemoBufPtr^,linetemp^,MemoBufSize);
FreeMem(MemoBufPtr, MemoBufSize);
end;
MemoBufPtr := linetemp;
MemoBuffer := MemoBufPtr + moMemoOffset;
MemoBufSize := lenchk;
end;
end;
function GSobjMemo.gsClose: boolean;
begin
moMemoClear;
gsClose := inherited gsClose;
end;
procedure GSobjMemo.moHuntAvailBlock(numbytes : longint);
var
BlksReq : longint;
procedure NewDB3Block;
begin
gsRead(0, MemoHeader, moHeaderSize); {read header block from the .DBT}
MemoLocation := MemoHeader.NextEmty;
MemoHeader.NextEmty := MemoHeader.NextEmty + BlksReq;
gsWrite(0, MemoHeader, moHeaderSize);
end;
procedure OldDB3Block;
begin
if MemoBloksUsed < BlksReq then NewDB3Block;
end;
begin
BlksReq := (numbytes+2+pred(BytesPerBlok)) div BytesPerBlok; {2 = $1A1A}
if (MemoLocation > 0) then
OldDB3Block
else
NewDB3Block;
MemoBloksUsed := BlksReq;
FillChar(MemoHeader, SizeOf(MemoHeader), #0);
end;
Procedure GSobjMemo.moMemoBlockRelease(rpt : longint);
begin {dummy to match GSobjMemo4.MemoBlockRelease}
end;
(*!
{Find line number, return with lstart = line begin, lend = next line begin}
{or nil if at the end of the memo. }
{if line number not found, lstart and lend = nil; return highest line num}
function GSobjMemo.moFindLine(lnum: integer; var lstart, lend: PChar): integer;
var
i: integer;
begin
lend := MemoBuffer;
lstart := nil;
i := 0;
while (lend <> nil) and (lend[0] <> #0) and (i < lnum) do
begin
inc(i);
lstart := lend;
while (not (lend[0] in [#0,#$0D,#$8D])) do inc(lend);
if lend[0] <> #0 then
begin
inc(lend);
if lend[0] = #$0A then inc(lend);
end;
end;
if i <> lnum then
begin
lstart := nil;
lend := nil;
end;
moFindLine := i;
end;
*)
{!
Procedure GSobjMemo.moMemoDelLine(linenum : integer);
var
linestart: PChar;
lineend: PChar;
begin
linestart := nil;
if MemoBufSize > 0 then
if linenum > 0 then moFindLine(linenum, linestart, lineend);
if linestart <> nil then
begin
if lineend <> nil then
StrCopy(linestart,lineend)
else
linestart[0] := #0;
end
else
FoundError(gsMemoAccessError, mmoMemoLineMissing, nil);
end;
function GSobjMemo.moMemoGetLine(linenum : integer) : String;
var
linestart: PChar;
lineend: PChar;
linetemp: PChar;
linechk: PChar;
begin
linestart := nil;
if MemoBufSize > 0 then
if linenum > 0 then moFindLine(linenum, linestart, lineend);
if linestart <> nil then
begin
GetMem(linetemp,succ(lineend-linestart));
StrLCopy(linetemp,linestart,lineend-linestart);
linechk := StrEnd(linetemp)-1;
while (linechk >= linetemp) and (linechk[0] in [#$0D,#$0A,#$8D]) do
begin
linechk[0] := #0;
dec(linechk);
end;
moMemoGetLine := StrPas(linetemp);
FreeMem(linetemp,succ(lineend-linestart));
end
else
begin
moMemoGetLine := '';
end;
end;
Procedure GSobjMemo.moMemoInsert(linenum : integer; const st : String;
TypeRtn: moLineCode);
var
linestart: PChar;
lineend: PChar;
linetemp: PChar;
begin
linestart := nil;
GetMem(linetemp,length(st)+3);
StrPCopy(linetemp,st);
if TypeRtn = HardReturn then
StrCat(linetemp,#$0D#$0A)
else
if TypeRtn = SoftReturn then
StrCat(linetemp,#$8D#$0A);
moAdjustBuffer(StrLen(linetemp));
if (linenum = -1) or (linenum = 0) then
begin
StrCat(MemoBuffer,linetemp)
end
else
begin
if linenum > 0 then
begin
moFindLine(linenum, linestart, lineend);
if linestart <> nil then
begin
Move(linestart[0], linestart[StrLen(linetemp)], StrLen(linestart));
Move(linetemp[0],linestart[0],StrLen(linetemp));
end
else
StrCat(MemoBuffer,linetemp)
end
else
begin
FreeMem(linetemp,length(st)+3);
FoundError(gsMemoAccessError, mmoMemoLineMissing, nil);
exit;
end;
end;
FreeMem(linetemp,length(st)+3);
end;
Procedure GSobjMemo.moMemoInsLine(linenum : integer; const st : String);
begin
moMemoInsert(linenum,st,HardReturn);
end;
Function GSobjMemo.moMemoLines : integer;
var
linestart: PChar;
lineend: PChar;
begin
moMemoLines := moFindLine(MaxInt, linestart, lineend);
end;
}
Procedure GSobjMemo.moMemoClear;
begin
if MemoBufPtr <> nil then FreeMem(MemoBufPtr, MemoBufSize);
MemoBuffer := nil;
MemoBufPtr := nil;
MemoBufSize := 0;
end;
Function GSobjMemo.moMemoLock : boolean;
var
rsl: boolean;
begin
rsl := false;
case dfLockStyle of
DB4Lock : begin
rsl := gsLockRecord(dfDirtyReadMax - 1, 2);
end;
ClipLock : begin
rsl := gsLockRecord(dfDirtyReadMax, 1);
end;
Default,
FoxLock : begin
rsl := gsLockRecord(dfDirtyReadMax - 1, 1);
end;
end;
moMemoLock := rsl;
if not rsl then gsTestForOk(dfFileErr,dskLockError);
end;
(*!
Procedure GSobjMemo.moMemoGet(rpt : longint);
var
cb: longint;
lstart: PChar;
lend: PChar;
i: integer;
v: integer;
hc: char;
BEGIN { Get Memo Field }
moMemoClear;
MemoLocation := rpt; {Save starting block number}
MemoBloksUsed := 0;
if rpt = 0 then exit;
moMemoSpaceUsed(rpt, cb);
moAdjustBuffer(cb);
MemoBuffer := MemoBufPtr+moMemoOffset;
MemoBloksUsed := (cb+pred(BytesPerBlok)) div BytesPerBlok;
gsRead((rpt*BytesPerBlok), MemoBufPtr^, cb);
if MemoLineLen < 1 then exit; {Don't do wordwrap}
lend := MemoBuffer;
for i := moMemoOffset to cb-succ(moMemoOffset) do
if lend[i] = #0 then lend[i] := '~';
i := 0;
while (lend <> nil) and (lend[0] <> #0) do
begin
inc(i);
lstart := lend;
lend := StrPos(lstart,#$0D);
if lend = nil then
lend := StrPos(lstart,#$8D); {Check for soft return}
if lend <> nil then
v := lend - lstart
else
v := StrLen(lstart);
if v > MemoLineLen then {insert soft return}
begin
lend := lstart + MemoLineLen - 1;
while (lend > lstart) and (lend[0] <> ' ') and (lend[0] <> '-') do
dec(lend);
if lend = lstart then
lend := lstart + pred(MemoLineLen);
hc := lend[0];
lend[0] := #$0D;
moMemoInsert(i+1,'',SoftReturn);
lend[0] := hc;
inc(lend,2);
end
else
begin
if lend <> nil then
begin
if lend[0] <> #0 then
inc(lend);
if lend[0] = #$0A then inc(lend);
end;
end;
end;
end;
Function GSobjMemo.moMemoPut(rpt : longint) : longint;
var
rsl : boolean;
lstart: PChar;
lend: PChar;
bCnt : longint; {dB4 = bytes in memo; dB3 = zero}
es: array[0..7] of char;
BEGIN { Put Memo Field }
if dfFileShrd then
rsl := moMemoLock
else rsl := true;
if not rsl then
begin
moMemoPut := rpt;
exit;
end;
if MemoBuffer <> nil then
begin
lstart := MemoBuffer;
while (lstart[0] <> #0) and (lstart[0] <> #$8D) do inc(lstart);
if lstart[0] = #$8D then
begin
lend := lstart;
inc(lend);
if lend[0] = #$0A then inc(lend);
while lend[0] <> #0 do
begin
lstart[0] := lend[0];
inc(lend);
inc(lstart);
if lend[0] = #$8D then
begin
inc(lend);
if lend[0] = #$0A then inc(lend);
end;
end;
lstart[0] := #0;
end;
bCnt := StrLen(MemoBuffer);
end
else
bcnt := 0;
if bcnt = 0 then
begin
MemoLocation := 0;
MemoBloksUsed := 0;
moMemoClear;
moMemoPut := 0;
gsUnLock;
exit;
end;
MemoLocation := rpt;
moHuntAvailBlock(bCnt);
if moMemoOffset > 0 then
Move(MemoHeader,MemoBufPtr[0],moMemoOffset);
StrCopy(es,'');
moMemoPutLast(es);
if StrLen(es) > 0 then
moMemoInsert(-1,es,NoReturn);
gsWrite(MemoLocation*BytesPerBlok, MemoBufPtr[0], MemoBloksUsed*BytesPerBlok);
moMemoPut := MemoLocation;
gsUnLock;
end;
*)
Procedure GSobjMemo.moMemoPutLast(ps: PChar);
begin
StrCopy(ps,#$1A#$1A);
end;
Procedure GSobjMemo.moMemoSetParam(var bl: longint);
begin
bl := 0;
end;
{!
Procedure GSobjMemo.moMemoWidth(l : integer);
begin
MemoLineLen := l;
end;
}
Function GSobjMemo.moMemoOffset: integer;
begin
moMemoOffset := 0;
end;
PROCEDURE GSobjMemo.gsOpen;
BEGIN
if dfClosed then
gsReset; {If memo file, then open .DBT file}
END;
Procedure GSobjMemo.moMemoRead(buf: pointer; blk: longint; var cb: longint);
var
pba: GSptrCharArray; {pointer to BUF allocated}
rsz: longint;
rwk: longint;
sof: longint;
BEGIN
if cb = 0 then exit;
MemoLocation := blk; {Save starting block number}
MemoBloksUsed := 0; {Initialize blocks read}
if MemoLocation = 0 then
begin
cb := 0; {blocks used = 0}
pba := buf;
pba^[0] := #0; {#0 -> BUF[0] }
exit;
end;
moMemoSpaceUsed(blk, rsz); {rsz = number of bytes used by memo}
rsz := rsz - moMemoOffset; {rsz = bytes used by text only }
if cb < rsz then {if wanted to read less than rsz }
rsz := cb { then we will read less :) }
else
cb := rsz; { else CB = real Memo Text size }
sof := moMemoOffset; {offset in memo block (=8 bytes) }
MemoBloksUsed := (cb+sof+ pred(BytesPerBlok)) div BytesPerBlok;
{How many blocks occupied by memo }
repeat
if rsz > WorkBlockSize then begin
rwk := WorkBlockSize; {how many to read in this step }
rsz := rsz - WorkBlockSize; {the rest of memo not readed else}
end else begin
rwk := rsz; {read the last rest of memo }
rsz := 0; {all the memo rest will be readed}
end;
gsRead((blk*BytesPerBlok)+sof,buf^,rwk);
inc(sof,rwk); {sof := sof+rwk;}
buf := GSGetPointer(buf,rwk); {shift buf pointer to +rwk}
until rsz <= 0;
END;
{VV - new procedure for Writing Memo to a File}
Procedure GSobjMemo.moMemo2File(blk: longint; const FileName:string);
var
buf: GSptrCharArray; {pointer to BUF allocated}
rsz: longint;
rwk: longint;
sof: longint;
F : integer; {Output File handler}
BEGIN
MemoLocation:=blk;
if MemoLocation = 0 then exit; {Exit if Memo Empty}
GetMem(buf,WorkBlockSize); {Allocate Memory for work buffer}
F:=GsFileCreate(FileName); {Create the File}
MemoLocation := blk; {Save starting block number}
MemoBloksUsed := 0; {Initialize blocks read}
moMemoSpaceUsed(blk, rsz); {rsz = number of bytes used by memo}
rsz := rsz - moMemoOffset; {rsz = bytes used by text only }
sof := moMemoOffset; {offset in memo block (=8 bytes) }
MemoBloksUsed := (rsz + sof+ pred(BytesPerBlok)) div BytesPerBlok;
{How many blocks used by memo }
repeat
if rsz > WorkBlockSize then begin
rwk := WorkBlockSize; {how many to read in this step }
rsz := rsz - WorkBlockSize; {the rest of memo not readed else}
end else begin
rwk := rsz; {read the last rest of memo }
rsz := 0; {all the memo rest will be readed}
end;
gsRead((blk*BytesPerBlok)+sof,buf^,rwk);
inc(sof,rwk); {sof := sof+rwk;}
gsFileWrite(F,buf^,rwk); {Write to the file rwk bytes}
until rsz <= 0;
gsFileClose(F); {Close the File }
FreeMem(buf,WorkBlockSize);{Dispose Memory of work buffer}
END;
{VV - new procedure for Writing File into the Memo}
Function GSobjMemo.moFile2Memo(blk: longint; const FileName:string):longint;
var
buf: GSptrCharArray; {pointer to BUF allocated}
F : integer; {Output File handler}
var
rsl : boolean;
rsz : longint;
rwk : longint;
sof : longint;
pb: PChar;
BEGIN
If (not GsFileExists(FileName)) then exit; {Exit If No File }
GetMem(buf,WorkBlockSize); {Allocate Memory for work buffer}
{ pb:=pointer(buf);}
F:=GsFileOpen(FileName,fmOpenRead); {Open the File}
moFile2Memo := blk; {It is Old Memo Location}
if dfFileShrd then
rsl := moMemoLock {Try to Lock the MEMO }
else rsl := true;
if not rsl then begin
moFile2Memo := 0; {Exit if can't lock }
exit;
end;
MemoLocation := blk; {Remember Old Memo Location}
rsz := gsf_dos.gsFileSize(FileName); {Get count of bytes in the file}
moHuntAvailBlock(rsz); {If MemoSize>OldSize then New MemoLocation}
sof := moMemoOffset;
if sof > 0 then
gsWrite(MemoLocation*BytesPerBlok, MemoHeader, sof);
repeat
if rsz > WorkBlockSize then begin
rwk := WorkBlockSize;
rsz := rsz - WorkBlockSize;
end else begin
rwk := rsz;
rsz := 0;
end;
gsFileRead(F,buf^,rwk); {Read from the file rwk bytes}
gsWrite((MemoLocation*BytesPerBlok)+sof, buf^, rwk);
sof := sof+rwk;
{ buf := GSGetPointer(buf,rwk);}
until rsz <= 0;
{ buf:=GsPtrCharArray(pb);}
GetMem(pb,BytesPerBlok);
FillChar(pb[0],BytesPerBlok,#0);
moMemoPutLast(pb);
rwk := sof mod BytesPerBlok;
if rwk > 0 then
gsWrite((MemoLocation*BytesPerBlok)+sof, pb[0], BytesPerBlok - rwk);
blk := MemoLocation;
FreeMem(pb,BytesPerBlok);
moFile2Memo := MemoLocation;
gsUnLock;
gsFileClose(F); {Close the File }
FreeMem(buf,WorkBlockSize);{Dispose Memory of work buffer}
END;
Procedure GSobjMemo.moMemoSpaceUsed(blk: longint; var cb: longint);
{Calculate Memo Length in BYTES (CB) started from the BLK block}
var
ml: longint;
mc: longint;
fini: boolean;
tblok: gsPtrByteArray;
BEGIN
cb := moMemoOffset; {get data offset in memo}
if (blk = 0) then exit; {exit if memo empty}
gsRead(blk*BytesPerBlok, MemoHeader, moHeaderSize);
{Read the beginning of memo}
moMemoSetParam(cb); {cb = Total Memo Length (bytes)}
if moMemoOffset > 0 then
begin {Test for Fox or DBIV memo}
exit; {Exit if FoxBase because all done}
end;
{Continue for DBIII}
fini := false;
ml := blk; {Save starting block number}
cb := 0; {Let Memo length = 0 first }
GetMem(tblok,BytesPerBlok); {tblock - temp buffer for read}
while (not fini) do {loop until Done (EOF mark)}
begin
gsRead(ml*BytesPerBlok, tblok^, BytesPerBlok);
inc(ml); {then we will read the next block}
mc := 0; {byte counter in temp buf}
while (mc < BytesPerBlok) and (fini = false) do
begin
inc(cb); {how many blocks readed allready}
if (tblok^[mc] = $1A) or (cb = 65520) then
begin
fini := true; {Stop if EOF mark or too many blocks used}
dec(cb);
end;
inc(mc); {Step to next input buffer location}
end;
end;
FreeMem(tblok,BytesPerBlok);
END;
function GSobjMemo.moMemoWrite(buf: pointer; var blk: longint;var cb: longint): longint;
var
rsl : boolean;
rsz : longint;
rwk : longint;
sof : longint;
pb: PChar;
BEGIN
moMemoWrite := blk; {It is Old Memo Location}
if (cb = 0) and (blk = 0) then exit; {Exit If Memo Empty }
if dfFileShrd then
rsl := moMemoLock {Try to Lock the MEMO }
else rsl := true;
if not rsl then
begin
moMemoWrite := 0; {Exit if can't lock }
exit;
end;
MemoLocation := blk; {Remember Old Memo Location}
rsz := cb; {Get count of bytes in memo field}
moHuntAvailBlock(rsz); {If MemoSize>OldSize then New MemoLocation}
sof := moMemoOffset;
if sof > 0 then
gsWrite(MemoLocation*BytesPerBlok, MemoHeader, sof);
repeat
if rsz > WorkBlockSize then
begin
rwk := WorkBlockSize;
rsz := rsz - WorkBlockSize;
end
else
begin
rwk := rsz;
rsz := 0;
end;
gsWrite((MemoLocation*BytesPerBlok)+sof, buf^, rwk);
sof := sof+rwk;
buf := GSGetPointer(buf,rwk);
until rsz <= 0;
GetMem(pb,BytesPerBlok);
FillChar(pb[0],BytesPerBlok,#0);
moMemoPutLast(pb);
rwk := sof mod BytesPerBlok;
if rwk > 0 then
gsWrite((MemoLocation*BytesPerBlok)+sof, pb[0], BytesPerBlok - rwk);
blk := MemoLocation;
FreeMem(pb,BytesPerBlok);
moMemoWrite := MemoLocation;
gsUnLock;
end;
function GSobjMemo.moMemoSize(blk: longint): longint;
{Calculate how many bytes are in MEMO field started from blk}
var
cb: longint;
begin
moMemoSpaceUsed(blk, cb);
cb := cb-moMemoOffset;
moMemoSize := cb;
end;
(*!
{------------------------------------------------------------------------------
GSobjMemo4
------------------------------------------------------------------------------}
procedure GSobjMemo4.moHuntAvailBlock(numbytes : longint);
var
BlksReq : integer;
WBlok1 : longint;
WBlok2 : longint;
WBlok3 : longint;
procedure FitDB4Block;
var
match : boolean;
begin
match := false;
gsRead(0, MemoHeader, moHeaderSize); {read header block from the .DBT}
WBlok3 := gsFileSize div BytesPerBlok;
if WBlok3 = 0 then {empty file, fill up header block}
begin
inc(WBlok3);
gsWrite(0, MemoHeader, moHeaderSize);
end;
with MemoHeader do
begin
WBlok1 := NextEmty;
WBlok2 := 0;
while not match and (WBlok1 <> WBlok3) do
begin
gsRead(WBlok1*BytesPerBlok, MemoHeader, moHeaderSize);
if BlksEmty >= BlksReq then
begin
match := true;
WBlok3 := NextEmty;
if BlksEmty > BlksReq then {free any blocks not needed}
begin
WBlok3 := WBlok1+BlksReq;
BlksEmty := BlksEmty - BlksReq;
gsWrite(WBlok3*BytesPerBlok, MemoHeader, moHeaderSize);
end;
end
else {new memo won't fit this chunk}
begin
WBlok2 := WBlok1; {keep previous available chunk}
WBlok1 := NextEmty; {get next available chunk}
end;
end;
if not match then WBlok3 := WBlok3 + BlksReq;
gsRead(WBlok2*BytesPerBlok, MemoHeader, moHeaderSize);
NextEmty := WBlok3;
gsWrite(WBlok2*BytesPerBlok, MemoHeader, moHeaderSize);
end;
end;
begin
BlksReq := ((numbytes+moMemoOffset) div BytesPerBlok)+1;
if (MemoLocation > 0) then moMemoBlockRelease(MemoLocation);
FitDB4Block;
MemoLocation := WBlok1;
MemoBloksUsed := BlksReq;
MemoHeader.DBIV := -1;
MemoHeader.StartLoc:= moMemoOffset;
MemoHeader.LenMemo := numbytes+moMemoOffset;
end;
Procedure GSobjMemo4.moMemoBlockRelease(rpt : longint);
var
blks : longint;
begin
{ blks := MemoBloksUsed;}
with MemoHeader do
begin
gsRead(rpt*BytesPerBlok, MemoHeader, moMemoOffset);
blks := (BlksEmty + (BytesPerBlok-1)) div BytesPerBlok;
gsRead(0, MemoHeader, moMemoOffset);
BlksEmty := blks;
gsWrite(rpt*BytesPerBlok, MemoHeader, moMemoOffset);
NextEmty := rpt;
BlksEmty := 0;
end;
gsWrite(0, MemoHeader, moMemoOffset);
end;
Procedure GSobjMemo4.moMemoPutLast(ps: PChar);
begin
end;
Procedure GSobjMemo4.moMemoSetParam(var bl: longint);
begin
if MemoHeader.DBIV = -1 then
begin
bl := MemoHeader.LenMemo;
end
else
begin
gsTestForOk(gsBadDBTRecord, mmoMemoSetParamErr);
bl := moMemoOffset;
end;
end;
Function GSobjMemo4.moMemoOffset: integer;
begin
moMemoOffset := 8;
end;
PROCEDURE GSobjMemo4.gsOpen;
var
pb: pointer;
BEGIN
if dfClosed then
begin
gsReset; {If memo file, then open .DBT file}
gsRead(0, MemoHeader, moHeaderSize);
Move(MemoHeader.BlkArray[20],BytesPerBlok,SizeOf(longint));
if gsFileSize < BytesPerBlok then
begin
GetMem(pb,BytesPerBlok);
FillChar(pb^,BytesPerBlok,#0);
Move(MemoHeader, pb^, gsFileSize);
gsWrite(0, pb^, BytesPerBlok);
FreeMem(pb,BytesPerBlok);
end;
end;
END;
*)
{------------------------------------------------------------------------------
GSobjFXMemo20
------------------------------------------------------------------------------}
procedure MakeLeft2RightInt(r: longint; var x);
var
a: array[0..3] of byte absolute x;
ra: array[0..3] of byte absolute r;
begin
a[0] := ra[3];
a[1] := ra[2];
a[2] := ra[1];
a[3] := ra[0];
end;
Function MakeLongInt(var x): longint;
var
a: array[0..3] of byte absolute x;
r: longint;
ra: array[0..3] of byte absolute r;
begin
ra[0] := a[3];
ra[1] := a[2];
ra[2] := a[1];
ra[3] := a[0];
MakeLongInt := r;
end;
CONSTRUCTOR GSobjFXMemo20.Create(AOwner: GSP_DiskFile; const FName : String;
DBVer, FM : byte);
begin
inherited Create(AOwner, FName,DBVer,FM);
ObjType := GSobtFPTFile;
end;
procedure GSobjFXMemo20.moHuntAvailBlock(numbytes : longint);
var
BlksReq : longint;
procedure NewFoxBlock;
begin
with MemoHeader do
begin
gsRead(0, MemoHeader, moMemoOffset); {read header block from the .DBT}
MemoLocation := MakeLongInt(NextEmty);
MakeLeft2RightInt(MemoLocation + BlksReq, NextEmty);
gsWrite(0, MemoHeader, moMemoOffset);
end;
end;
procedure OldFoxBlock;
begin
if MemoBloksUsed < BlksReq then NewFoxBlock;
end;
begin
BlksReq := ((numbytes+moMemoOffset) div BytesPerBlok)+1;
if (MemoLocation > 0) then
OldFoxBlock
else
NewFoxBlock;
MemoBloksUsed := BlksReq;
MakeLeft2RightInt(1,MemoHeader.BlkArray[0]);
MakeLeft2RightInt(numbytes,MemoHeader.BlkArray[4]);
end;
Procedure GSobjFXMemo20.moMemoPutLast(ps: PChar);
begin
end;
Procedure GSobjFXMemo20.moMemoSetParam(var bl: longint);
{Real Memo Length = Text Memo Length + Memo Block Header Length}
begin
if (MemoHeader.Fox20 = $01000000) or (MemoHeader.Fox20 = 0) then
begin
bl := MakeLongInt(MemoHeader.LenMemo)+moMemoOffset;
end
else
begin
gsTestForOk(gsBadDBTRecord, mmoMemoSetParamErr);
bl := moMemoOffset;
end;
end;
Function GSobjFXMemo20.moMemoOffset: integer;
{If FoxBase - Set Real Memo offset to 8 bytes from the memo begin}
begin
moMemoOffset := 8;
end;
PROCEDURE GSobjFXMemo20.gsOpen;
BEGIN
if dfClosed then
begin
gsReset; {If memo file, then open .FPT file}
gsRead(0, MemoHeader, moHeaderSize);
BytesPerBlok := MakeLongInt(MemoHeader.BlkArray[4]) and $FFFF;
end;
END;
end.
|
unit uGeraSQL_Controller;
interface
uses uGeraSQL_Interface, Vcl.StdCtrls;
Type
TController_GeraSQL = class(TinterfacedObject, iController_GeraSQL)
Fcolunas: TMemo;
FTabela: TMemo;
FCondicao: TMemo;
class function New: iController_GeraSQL;
function SetColunas(Colunas: TMemo): iController_GeraSQL;
function SetTabela(Tabela: TMemo): iController_GeraSQL;
function SetCondicao(Condicao: TMemo): iController_GeraSQL;
function GeraSQL: String;
end;
implementation
uses
uspQuery, System.Classes, System.SysUtils;
{ TController_GeraSQL }
function TController_GeraSQL.GeraSQL: String;
var
qryGeraSQL: tspQuery;
Colunas: TStringList;
Tabelas: TStringList;
Condicoes: TStringList;
i: Integer;
begin
Colunas := TStringList.create;
Tabelas := TStringList.create;
Condicoes := TStringList.create;
qryGeraSQL := tspQuery.create(nil);
try
for i := 0 to Fcolunas.Lines.Count - 1 do
Colunas.Add(Fcolunas.Lines.Strings[i]);
Tabelas.Add(FTabela.Lines.Text);
Condicoes.Add(FCondicao.Lines.Text);
qryGeraSQL.spColunas := Colunas;
qryGeraSQL.spTabelas := Tabelas;
qryGeraSQL.spCondicoes := Condicoes;
qryGeraSQL.GeraSQL;
Result := qryGeraSQL.SQL.Strings[0];
finally
FreeAndNil(Colunas);
FreeAndNil(Tabelas);
FreeAndNil(Condicoes);
FreeAndNil(qryGeraSQL);
end;
end;
class function TController_GeraSQL.New: iController_GeraSQL;
begin
Result := Self.create;
end;
function TController_GeraSQL.SetColunas(Colunas: TMemo): iController_GeraSQL;
begin
Result := Self;
Fcolunas := Colunas;
end;
function TController_GeraSQL.SetCondicao(Condicao: TMemo): iController_GeraSQL;
begin
Result := Self;
FCondicao := Condicao;
end;
function TController_GeraSQL.SetTabela(Tabela: TMemo): iController_GeraSQL;
begin
Result := Self;
FTabela := Tabela;
end;
end.
|
unit ugerador_aleatorio;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls,
StdCtrls, ComCtrls, Grids, CheckLst
;
// Este registro guarda a informação do jogo escolhido, a quantidade de números jogados
// e a quantidade de volantes jogados.
type
TJogoInfo = record
JogoTipo: string;
bolaInicial: integer;
bolaFinal: integer;
// Cada jogo, pode-se apostar tantas bolas
bolaAposta: integer;
// Quantidade de volantes apostados.
quantidadeBilhetes: integer;
// Indica, que todos os números devem ser sorteados, antes de repetir um novo número.
naoRepetirBolas: boolean;
// Alternar entre par e impar.
alternarParImpar: boolean;
end;
type
TLotofacilEtapa = (
LOTOFACIL_ETAPA_ZERO, LOTOFACIL_ETAPA_UM,
LOTOFACIL_ETAPA_DOIS, LOTOFACIL_ETAPA_TRES,
LOTOFACIL_ETAPA_QUATRO);
const
JogoTipo: array[0..7] of string = ('DUPLASENA', 'LOTOFACIL',
'LOTOMANIA', 'MEGASENA', 'QUINA', 'INTRALOT_MINAS_5',
'INTRALOT_LOTOMINAS', 'INTRALOT_KENO_MINAS');
type
{
TJogoThread
Para evitar que a interface de usuário fica não-responsiva, criaremos
um thread.
}
TJogoThread = class(TThread)
public
constructor Create(jogoInfo: TJogoInfo; jogoGrade: TStringGrid;
CreateSuspended: boolean);
procedure Execute; override;
private
jogoInfo: TJogoInfo;
jogoGrade: TStringGrid;
procedure Preencher_Grade;
procedure Preencher_Grade_Lotofacil;
procedure Preencher_Grade_Lotomania;
end;
type
{ TfrmGerador_Aleatorio }
TfrmGerador_Aleatorio = class(TForm)
btnImportar: TButton;
btnGerar: TButton;
btnCopiar: TButton;
btnExportar: TButton;
btnLimpar_Resultados: TButton;
CheckListBox1 : TCheckListBox;
CheckListBox2 : TCheckListBox;
chkAlternarParImpar: TCheckBox;
cmbJogo_Tipo: TComboBox;
cmbJogo_com: TComboBox;
cmbJogo_Quantidade: TComboBox;
gradeJogos : TStringGrid;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6 : TLabel;
Label7 : TLabel;
PageControl1 : TPageControl;
panel_Superior: TPanel;
Panel2: TPanel;
panel_Direito: TPanel;
StatusBar1: TStatusBar;
TabSheet1 : TTabSheet;
TabSheet2 : TTabSheet;
procedure btnCopiarClick(Sender: TObject);
procedure btnExportarClick(Sender: TObject);
procedure btnGerarClick(Sender: TObject);
procedure btnImportarClick(Sender: TObject);
procedure btnLimpar_ResultadosClick(Sender: TObject);
procedure cmbJogo_comChange(Sender: TObject);
procedure cmbJogo_QuantidadeKeyPress(Sender: TObject; var Key: char);
procedure cmbJogo_TipoChange(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
private
strErro: string;
// Estrutura que guarda o jogo selecionado.
jogoInfo: TJogoInfo;
// Toda vez que o usuário clicar para gerar um novo resultado, iremos
// utilizar uma thread para evitar que a interface fique não-responsiva.
jogoThread: TJogoThread;
{ private declarations }
procedure Preencher_Jogos(Sender: TObject);
procedure Preencher_Jogos_Quantidade;
//function Retornar_Aposta_com_x_numeros(strJogo_com: string;
// out strErro: string): integer;
//function Retornar_Quantidade_de_Jogos(strJogo_Quantidade: string;
// out strErro: string): integer;
function Validar_Jogo: boolean; overload;
//function Validar_Campos(strJogo, strJogo_Com, strJogo_Quantidade: string;
// var strErro: string): boolean; overload;
procedure Exportar_Arquivo_csv;
procedure Importar_Arquivo_csv;
//procedure Preencher_Grade;
//function Validar_Jogo(strJogo: string; out strErro: string): boolean;
//procedure Preencher_Grade_Lotofacil;
public
{ public declarations }
end;
var
frmGerador_Aleatorio: TfrmGerador_Aleatorio;
implementation
uses dmLtk;
{$R *.lfm}
{ TJogoThread }
constructor TJogoThread.Create(jogoInfo: TJogoInfo; jogoGrade: TStringGrid;
CreateSuspended: boolean);
begin
self.FreeOnTerminate := True;
self.jogoInfo := jogoInfo;
self.jogoGrade := jogoGrade;
end;
procedure TJogoThread.Execute;
begin
if self.jogoInfo.JogoTipo = 'LOTOFACIL' then
self.Preencher_Grade_Lotofacil
else
self.Preencher_Grade;
end;
{ TfrmGerador_Aleatorio }
procedure TfrmGerador_Aleatorio.FormClose(Sender: TObject;
var CloseAction: TCloseAction);
begin
CloseAction := TCloseAction.caFree;
FreeAndNil(JogoThread);
end;
// A informação disponível na caixa de combinação é alterada conforme o tipo do
// jogo.
procedure TfrmGerador_Aleatorio.cmbJogo_comChange(Sender: TObject);
begin
end;
procedure TfrmGerador_Aleatorio.cmbJogo_QuantidadeKeyPress(Sender: TObject;
var Key: char);
begin
if not ((Key >= '0') and (Key <= '9')) and (Key <> '#9') then
Key := Char(Byte(0));
end;
procedure TfrmGerador_Aleatorio.btnGerarClick(Sender: TObject);
begin
// Vamos preencher os dados e passa para validar.
JogoInfo.JogoTipo := cmbJogo_Tipo.Text;
JogoInfo.bolaAposta := StrToInt(cmbJogo_Com.Text);
JogoInfo.quantidadeBilhetes := StrToInt(cmbJogo_Quantidade.Text);
JogoInfo.alternarParImpar := chkAlternarParImpar.Checked;
if Validar_Jogo = False then
begin
MessageDlg(strErro, TMsgDlgType.mtError, [mbOK], 0);
Exit;
end;
JogoThread := TJogoThread.Create(jogoInfo, gradeJogos, True);
JogoThread.Execute;
end;
procedure TfrmGerador_Aleatorio.btnImportarClick(Sender: TObject);
begin
self.Importar_Arquivo_csv;
end;
procedure TfrmGerador_Aleatorio.btnExportarClick(Sender: TObject);
begin
self.Exportar_Arquivo_csv;
end;
procedure TfrmGerador_Aleatorio.btnCopiarClick(Sender: TObject);
begin
// Vamos copiar para o ClipBoard;
self.gradeJogos.CopyToClipboard(False);
end;
procedure TfrmGerador_Aleatorio.btnLimpar_ResultadosClick(Sender: TObject);
var
iResposta: integer;
begin
iResposta := MessageDlg('Deseja apagar os resultados', TMsgDlgType.mtInformation,
[mbYes, mbNo], 0);
if iResposta = mrYes then
begin
gradeJogos.Clean;
gradeJogos.RowCount := 0;
end;
end;
// Toda vez que o usuário clicar na caixa de combinação Jogo_Tipo, devemos
// atualizar o controle cmbJogo_com para refletir a quantidade de números
// a jogar para o jogo respectivo.
procedure TfrmGerador_Aleatorio.cmbJogo_TipoChange(Sender: TObject);
var
iA: integer;
strJogo: string;
begin
// Sempre apagar o que já havia na caixa de combinação.
cmbJogo_com.Items.Clear;
strJogo := cmbJogo_Tipo.Text;
// Vamos garantir que sempre o valor estará em maiúsculas.
strJogo := UpCase(strJogo);
if strJogo = 'QUINA' then
begin
// Quina, agora, vc pode jogar de 5 a 15 números.
for iA := 5 to 15 do
begin
cmbJogo_com.Items.Add(IntToStr(iA));
end;
end
else
if (strJogo = 'MEGASENA') or (strJogo = 'DUPLASENA') then
begin
for iA := 6 to 15 do
begin
cmbJogo_com.Items.Add(IntToStr(iA));
end;
end
else
if strJogo = 'LOTOFACIL' then
begin
for iA := 15 to 18 do
begin
cmbJogo_com.Items.Add(IntToStr(iA));
end;
end
else
if strJogo = 'LOTOMANIA' then
begin
cmbJogo_com.Items.Add('50');
end
else
if strJogo = 'INTRALOT_MINAS_5' then
begin
cmbJogo_com.Items.Add('5');
end
else
if strJogo = 'INTRALOT_LOTOMINAS' then
begin
cmbJogo_com.Items.Add('6');
end;
if strJogo = 'INTRALOT_KENO_MINAS' then
begin
for iA := 10 downto 1 do
cmbJogo_Com.Items.Add(IntToStr(iA));
end;
// Selecionar sempre o primeiro ítem.
cmbJogo_com.ItemIndex := 0;
end;
procedure TfrmGerador_Aleatorio.FormCreate(Sender: TObject);
begin
self.Preencher_Jogos(Sender);
self.Preencher_Jogos_Quantidade;
end;
procedure TfrmGerador_Aleatorio.Preencher_Jogos(Sender: TObject);
var
iA: integer;
begin
// Preencher combobox com o nome dos jogos.
for iA := 0 to High(JogoTipo) do
cmbJogo_Tipo.Items.Add(JogoTipo[iA]);
// Definir o primeiro ítem, na inicialização.
cmbJogo_Tipo.ItemIndex := 0;
// Vamos também atualizar o controle 'cmbJogo_com' para refletir o jogo selecionado
cmbJogo_Tipo.OnChange(Sender);
end;
// Preencher o controle 'cmbJogo_Quantidade' com a lista de quantidade de jogos.
procedure TfrmGerador_Aleatorio.Preencher_Jogos_Quantidade;
var
iA: integer;
begin
for iA := 1 to 1000 do
begin
cmbJogo_Quantidade.Items.Add(IntToStr(iA));
end;
cmbJogo_Quantidade.ItemIndex := 0;
end;
// Validar o jogo e definir a menor e maior bola
function TfrmGerador_Aleatorio.Validar_Jogo: boolean;
var
strJogo: string;
begin
// Validar nome do jogo.
strJogo := UpperCase(JogoInfo.JogoTipo);
if (strJogo <> 'QUINA') and (strJogo <> 'MEGASENA') and
(strJogo <> 'LOTOFACIL') and (strJogo <> 'LOTOMANIA') and
(strJogo <> 'DUPLASENA') and (strJogo <> 'INTRALOT_MINAS_5') and
(strJogo <> 'INTRALOT_LOTOMINAS') and (strJogo <> 'INTRALOT_KENO_MINAS') then
begin
strErro := 'Jogo inválido: ' + strJogo;
Exit(False);
end;
// Definir limite inferior e superior.
// Nos jogos da loteria, somente o jogo lotomania, a menor bola é 0.
if strJogo = 'LOTOMANIA' then
JogoInfo.bolaInicial := 0
else
JogoInfo.bolaInicial := 1;
// Definir limite superior.
if strJogo = 'QUINA' then
JogoInfo.BolaFinal := 80
else if strJogo = 'MEGASENA' then
JogoInfo.BolaFinal := 60
else if strJogo = 'LOTOFACIL' then
JogoInfo.BolaFinal := 25
else if strJogo = 'LOTOMANIA' then
JogoInfo.BolaFinal := 99
else if strJogo = 'DUPLASENA' then
JogoInfo.BolaFinal := 50
else if strJogo = 'INTRALOT_MINAS_5' then
JogoInfo.BolaFinal := 34
else if strJogo = 'INTRALOT_LOTOMINAS' then
JogoInfo.BolaFinal := 38
else if strJogo = 'INTRALOT_KENO_MINAS' then
JogoInfo.BolaFinal := 80;
// Validar o campo de quantidade de números apostados escolhido pelo usuário.
if ((strJogo = 'MEGASENA') or (strJogo = 'DUPLASENA')) and not
(JogoInfo.bolaAposta in [6..15]) then
begin
strErro := 'Quantidade de bolas apostadas inválida para o jogo: ' + strJogo;
Exit(False);
end;
if (strJogo = 'QUINA') and not (JogoInfo.bolaAposta in [5..15]) then
begin
strErro := 'Quantidade de bolas apostadas inválida para o jogo: ' + strJogo;
Exit(False);
end;
if (strJogo = 'LOTOFACIL') and not (JogoInfo.bolaAposta in [15..18]) then
begin
strErro := 'Quantidade de bolas apostadas inválida para o jogo: ' + strJogo;
Exit(False);
end;
if (strJogo = 'LOTOMANIA') and (JogoInfo.bolaAposta <> 50) then
begin
strErro := 'Quantidade de bolas apostadas inválida para o jogo: ' + strJogo;
Exit(False);
end;
if (strJogo = 'INTRALOT_MINAS_5') and (JogoInfo.bolaAposta <> 5) then
begin
strErro := 'Quantidade de bolas apostadas inválida para o jogo: ' + strJogo;
Exit(False);
end;
if (strJogo = 'INTRALOT_LOTO_MINAS') and (JogoInfo.bolaAposta <> 6) then
begin
strErro := 'Quantidade de bolas apostadas inválida para o jogo: ' + strJogo;
Exit(False);
end;
if (strJogo = 'INTRALOT_KENO_MINAS') and (not (JogoInfo.bolaAposta in [1..10])) then
begin
strErro := 'Quantidade de bolas apostadas inválida para o jogo: ' + strJogo;
Exit(False);
end;
Exit(True);
end;
procedure TfrmGerador_Aleatorio.Exportar_Arquivo_csv;
var
dlgExportar_Csv: TSaveDialog;
strArquivo_Sugestao: string;
begin
// Se não há nenhum jogo gerado, emiti um erro e sair.
if gradeJogos.RowCount = 0 then
begin
MessageDlg('Erro, não há nenhum jogo gerado.', TMsgDlgType.mtError,
[mbOK], 0);
Exit;
end;
// Vamos pegar o nome do arquivo, através da caixa de diálogo.
dlgExportar_Csv := TSaveDialog.Create(TComponent(self));
dlgExportar_Csv.Filter := '*.csv';
dlgExportar_Csv.InitialDir := '/home/fabiuz/meus_documentos/exportados';
// Vamos sugerir um nome baseado no jogo atual
strArquivo_Sugestao := JogoInfo.JogoTipo + '_com_' +
IntToStr(JogoInfo.bolaAposta) + '_números_' + FormatDateTime('dd_mm_yyyy', Now) +
'-' + FormatDateTime('hh_mm_ss', Now) + '.csv';
dlgExportar_Csv.FileName := strArquivo_Sugestao;
if dlgExportar_Csv.Execute = False then
begin
Exit;
end;
// O Arquivo não pode existir
if FileExists(dlgExportar_Csv.FileName) = True then
begin
MessageDlg('Erro, arquivo já existe.', TMsgDlgType.mtError, [mbOK], 0);
Exit;
end;
gradeJogos.SaveToCSVFile(dlgExportar_Csv.FileName, ';', True, False);
end;
procedure TfrmGerador_Aleatorio.Importar_Arquivo_csv;
var
dlgExportar_Csv: TOpenDialog;
begin
dlgExportar_Csv := TOpenDialog.Create(TComponent(self));
dlgExportar_Csv.InitialDir := '~/meus_documentos/exportados/';
dlgExportar_Csv.Filter := '*.csv';
if dlgExportar_Csv.Execute = False then
begin
Exit;
end;
// Vamos verificar se o arquivo existe.
if FileExists(dlgExportar_Csv.FileName) = False then
begin
MessageDlg('Arquivo ' + dlgExportar_Csv.FileName + ' não existe.',
TMsgDlgType.mtError, [mbOK], 0);
Exit;
end;
// Se o arquivo existe, iremos preencher no controle 'gradeJogos'.
// Se o controle não está vazio, avisar ao usuário que os dados serão sobrescritos.
if gradeJogos.RowCount <> 0 then
begin
if MessageDlg(
'Os dados que serão importados, sobrescreverão os dados atuais, desejar continuar.',
TMsgDlgType.mtConfirmation, [mbYes, mbNo], 0) = mrNo then
begin
MessageDlg('Dados não foram importados, nenhuma informação foi sobrescrita.',
TMsgDlgType.mtInformation, [mbOK], 0);
Exit;
end;
end;
try
gradeJogos.LoadFromCSVFile(dlgExportar_csv.FileName, ';', True);
except
On Exception do
begin
MessageDlg('Um erro ocorreu ao importar.', TMsgDlgType.mtError, [mbOK], 0);
gradeJogos.RowCount := 0;
end;
end;
// Ajusta a largura das colunas
gradeJogos.AutoSizeColumns;
end;
procedure TJogoThread.Preencher_Grade;
type
TParImpar = (NumeroPar, NumeroImpar);
var
iA, iB, iC, iD, iE: integer;
numeroAleatorio: integer;
// Guarda cada bola, de cada aposta
//iJogo_Grade: array of array of integer;
iJogo_Grade: array[0..1000, 0..50] of integer;
bolaJaSorteada: array[0..99] of boolean;
// Indica a quantidade de bolas já sorteadas.
quantidadeBolasSorteadas: integer;
// Indica o total de bolas que compõe o jogo.
bolaTotal, numeroTemp, ColunaBolaCombinada: integer;
bTrocou: boolean;
listaNumero: TStringList;
TrocarParImpar: TParImpar;
listaNumeroPar: TStringList;
listaNumeroImpar: TStringList;
IndiceLista: longint;
strNumeroConcatenado: string;
//Data: TDateTime;
begin
bolaTotal := JogoInfo.bolaFinal - JogoInfo.bolaInicial + 1;
quantidadeBolasSorteadas := 0;
Dec(JogoInfo.quantidadeBilhetes);
// Iniciar o gerador de números randômicos.
Randomize;
// Vamos criar uma lista de string com os números
listaNumero := TStringList.Create;
listaNumeroImpar := TStringList.Create;
listaNUmeroPar := TStringList.Create;
for iC := JogoInfo.bolaInicial to JogoInfo.bolaFinal do
begin
bolaJaSorteada[iC] := False;
listaNumero.Add(IntToStr(iC));
if iC mod 2 = 0 then
ListaNumeroPar.Add(IntToStr(iC))
else
ListaNumeroImpar.Add(IntToStr(iC));
end;
// Indica qual o tipo do número a usar.
TrocarParImpar := TParImpar.NumeroPar;
for iA := 0 to JogoInfo.quantidadeBilhetes do
begin
iB := 0;
while iB < JogoInfo.bolaAposta do
begin
// Nossa lista irá guardar todos os números, iremos pegar um número aleatória,
// este número corresponde a qualquer número que corresponde ao índice da lista.
// Em seguida, iremos remove este ítem da lista, a lista, irá diminuir, até a
// quantidade de ítens ser igual a zero.
// Fiz, desta maneira, pois sempre é garantido que a cada iteração, sempre
// vai sair um ítem da lista, ao contrário, da outra tentativa, que às vezes,
// o mesmo número pode já ter sido selecionado e o loop demorar a executar.
// Hoje, 10/06/2016, coloquei uma nova opção, a opção de escolher
// se desejar que saía alternadamente par e impar.
// Devemos observar, que pode acontecer que a quantidade de números pares e
// impares não seja igual, neste caso, devemos pegar o número que resta,
// por exemplo, há os números 2, 5, 8, 15, 17.
// Por exemplo, ao percorrermos, iremos pegar par 2, impar 5, par 8, impar
// 15 e em seguida, deveriamos pegar um número par, mas há um número impar
// neste caso, devemos pegar o número ímpar.
if JogoInfo.alternarParImpar = True then
begin
// Se as duas lista está vazia então enviar mensagem de erro.
if (listaNumeroPar.Count = 0) and (listaNumeroImpar.Count = 0) then
begin
raise Exception.Create('Lista de números pares e impares vazia.');
Exit;
end;
RandSeed := Random(1000000);
if TrocarParImpar = TParImpar.NumeroPar then
begin
// Vamos verificar se há números pares ainda na lista.
if listaNumeroPar.Count <> 0 then
begin
IndiceLista := Random(listaNumeroPar.Count);
numeroAleatorio := StrToInt(listaNumeroPar.Strings[IndiceLista]);
// Sempre sai um número não precisamos, gravar um arranjo de booleanos
// indica o número já lido.
listaNumeroPar.Delete(IndiceLista);
// Gravar no arranjo.
iJogo_Grade[iA, iB] := numeroAleatorio;
Inc(quantidadeBolasSorteadas);
Inc(iB);
end;
// Alterna para impar.
TrocarParImpar := TParImpar.NumeroImpar;
end
else
begin
// Vamos verificar se há números impares na lista.
if listaNumeroImpar.Count <> 0 then
begin
IndiceLista := Random(listaNumeroImpar.Count);
numeroAleatorio := StrToInt(listaNumeroImpar.Strings[IndiceLista]);
// Sempre sai número impar, não precisamos marcar qual saiu.
listaNumeroImpar.Delete(IndiceLista);
// Gravar no arranjo.
iJogo_Grade[iA, iB] := numeroAleatorio;
Inc(quantidadeBolasSorteadas);
Inc(iB);
end
else
begin
// Geralmente, isto nunca acontecerá.
raise Exception.Create('Isto não deve nunca acontecer.' +
#10#13 +
'A próxima iteração é par mas não há nenhum par.');
Exit;
end;
// Alterna para par.
TrocarParImpar := TParImpar.NumeroPar;
end;
end
else
begin
// Isto quer dizer que o número pode vir em qualquer ordem de números par e impar.
IndiceLista := Random(ListaNumero.Count);
numeroAleatorio := StrToInt(ListaNumero.Strings[IndiceLista]);
// Retirar item da lista.
listaNumero.Delete(IndiceLista);
// Gravar no arranjo.
iJogo_Grade[iA, iB] := numeroAleatorio;
Inc(quantidadeBolasSorteadas);
Inc(iB);
end;
// Se a quantidade de bolas já foi atingida,
// devemos resetar a variável 'BolaJaSorteada', em seguida, devemos
// definir para true, as bolas que já foram sorteadas, aqui, neste loop.
if quantidadeBolasSorteadas = bolaTotal then
begin
quantidadeBolasSorteadas := 0;
// Garantir que a lista está vazia, não é necessário.
listaNumero.Clear;
listaNumeroPar.Clear;
listaNumeroImpar.Clear;
for iC := JogoInfo.bolaInicial to JogoInfo.bolaFinal do
begin
// Adiciona os números à lista de string de números.
listaNumero.Add(IntToStr(iC));
if iC mod 2 = 0 then
listaNumeroPar.Add(IntToStr(iC))
else
listaNumeroImpar.Add(IntToStr(iC));
end;
// Se iB é igual a quantidade de números apostados, e que se todos
// as bolas foram sorteadas, quer dizer, que todos os números foram
// sorteados, podemos começar um novo jogo, escolhendo qualquer número.
if iB = JogoInfo.bolaAposta then
begin
// Randomize os números.
//RandSeed := StrToFloat(Format('%f', [Now]));
RandSeed := Random(1000000);
//Randomize;
//Continue;
end
else
begin
// Se chegamos aqui, quer dizer, que a quantidade de bolas aposta
// ainda está incompleta, então devemos repetir bolas que estão no
// nos concurso anterior e que não pode estar no concurso atual.
// Vamos percorrer, cada bola já sorteada e retirar da lista de número
// que ainda não foram sorteados.
// Definir a quantidade de bolas sorteadas, da aposta corrente.
// Será iB - 1, pois iB é baseado em zero.
quantidadeBolasSorteadas := iB;
for iC := 0 to iB - 1 do
begin
if JogoInfo.alternarParImpar = True then
begin
// Vamos verificar se é par ou impar.
numeroAleatorio := iJogo_Grade[iA, iC];
if numeroAleatorio mod 2 = 0 then
begin
IndiceLista := ListaNumeroPar.IndexOf(IntToStr(numeroAleatorio));
if IndiceLista <> -1 then
begin
ListaNumeroPar.Delete(IndiceLista);
end
else
begin
// Isto, nunca pode acontecer.
raise Exception.Create(
'O número é par, mas não está na lista, deveria estar.');
Exit;
end;
end
else
begin
// O número é impar.
IndiceLista := ListaNumeroImpar.IndexOf(IntToStr(numeroAleatorio));
if IndiceLista <> -1 then
begin
ListaNumeroImpar.Delete(IndiceLista);
end
else
begin
// Isto, nunca pode acontecer.
raise Exception.Create(
'O número é impar, mas não está na lista, deveria estar.');
Exit;
end;
end;
end
else
begin
// O usuário não marcou que quer par e impar alternados.
IndiceLista := ListaNumero.IndexOf(IntToStr(iJogo_Grade[iA, iC]));
if IndiceLista <> -1 then
begin
ListaNumero.Delete(IndiceLista);
end
else
begin
// Isto, nunca pode acontecer, somente acontecer, se algum número
// repetiu, acho bem improvável acontecer.
raise Exception.Create(
'O número não foi localizado, provavelmente, este ' +
'número saiu mais de uma vez.');
Exit;
end;
end;
end;
end;
end;
end;
//O arranjo é baseado em zero, devemos diminuir iB, para utilizar
//com melhor desempenho no loop.
Dec(iB);
repeat
bTrocou := False;
for iE := 0 to iB - 1 do
begin
if iJogo_Grade[iA, iE] > iJogo_Grade[iA, iE + 1] then
begin
numeroTemp := iJogo_Grade[iA, iE];
iJogo_Grade[iA, iE] := iJogo_Grade[iA, iE + 1];
iJogo_Grade[iA, iE + 1] := numeroTemp;
bTrocou := True;
end;
end;
until bTrocou = False;
end;
// A quantidade de números apostados, indicará a quantidade de colunas que haverá.
// Também, haverá colunas adicionais para indicar informações para identificar
// O tipo do jogo, a quantidade de números apostados, e quantos jogos foram
// selecionados.
// Haverá 4 colunas a mais, para indicar:
// Tipo do jogo;
// quantidade de números apostados;
// quantidade de jogos apostados; e,
// bolas_concatenadas.
// bolas_repetidas;
JogoGrade.ColCount := JogoInfo.bolaAposta + 5;
// A quantidade de fileira será 1 maior, pois uma coluna será o cabeçalho.
// Retorna ao estado atual.
Inc(JogoInfo.quantidadeBilhetes);
JogoGrade.RowCount := JogoInfo.quantidadeBilhetes + 1;
// A primeira fileira conterá o cabeçalho
JogoGrade.FixedRows := 1;
// As três colunas iniciais de cada fileira, indica:
// O tipo do jogo,
// A quantidade de números apostados,
// e, quantidade de jogos apostados.
JogoGrade.FixedCols := 3;
// Vamos preencher o cabeçalho
JogoGrade.Cells[0, 0] := 'BILHETE';
JogoGrade.Cells[1, 0] := 'JOGO';
JogoGrade.Cells[2, 0] := 'APOSTA';
JogoGrade.Cells[JogoGrade.ColCount - 2, 0] := 'BOLAS_COMBINADAS';
JogoGrade.Cells[JogoGrade.ColCount - 1, 0] := 'REPETIU NOS BILHETES';
// Vamos começar na coluna 3, como os índices são baseados em 0
// iremos adicionar + 2
for iA := 1 to JogoInfo.bolaAposta do
begin
JogoGrade.Cells[iA + 2, 0] := 'B' + IntToStr(iA);
end;
// Preencher grid.
for iA := 1 to JogoInfo.quantidadeBilhetes do
begin
// Insira informações das colunas 1 a 2
JogoGrade.Cells[0, iA] := IntToStr(iA);
JogoGrade.cells[1, iA] := JogoInfo.JogoTipo;
JogoGrade.Cells[2, iA] := 'com ' + IntToStr(JogoInfo.bolaAposta) + ' números.';
//statusBar1.Panels[0].Text := 'Processando linha: ' + IntToStr(iA + 1);
//statusBar1.Refresh;
strNumeroConcatenado := '';
for iB := 0 to JogoInfo.bolaAposta - 1 do
begin
JogoGrade.Cells[3 + iB, iA] := IntToStr(iJogo_Grade[iA - 1, iB]);
strNumeroConcatenado += '_' + Format('%.2d', [iJogo_Grade[iA - 1, iB]]);
end;
// Números concatenados.
Inc(iB);
JogoGrade.Cells[3 + iB, iA] := strNumeroConcatenado;
JogoGrade.Cells[4 + iB, iA] := '';
end;
// Pega a coluna das bolas combinadas
ColunaBolaCombinada := JogoGrade.ColCount - 2;
for iA := 1 to JogoInfo.quantidadeBilhetes do
for iB := iA + 1 to JogoInfo.quantidadeBilhetes do
begin
if JogoGrade.Cells[ColunaBolaCombinada, iA] =
JogoGrade.Cells[ColunaBolaCombinada, iB] then
begin
// Vamos acrescentar os dados ao que já está na célula.
JogoGrade.Cells[ColunaBolaCombinada + 1, iB] :=
JogoGrade.Cells[ColunaBolaCombinada + 1, iB] + IntToStr(iA) + ';';
end;
end;
JogoGrade.AutoSizeColumns;
FreeAndNil(listaNumero);
end;
// Este gerador aleatório, gera os números aleatórios, entretanto, enquanto houver
// número ainda não sorteado, nenhum número já sorteado pode aparecer no próximo jogo.
// Exemplo, vamos supor que os números saem em ordem crescente.
// 1 , 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15.
// Então, na próxima linha, deve sortear os números que ainda não foram sorteados
// não pode haver repetidos, enquanto houver número sorteado.
// 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
// Observe, que na lotofacil há 25 números, você pode apostar de 15 a 18 números.
// No jogo, das 25 bolas são sorteadas 15 bolas.
// Então, isto quer dizer, que em nosso gerador, a cada 2 jogos, todos os números
// já foram sorteados, entretanto, se apostarmos 15 números, o primeiro jogo
// terá 15 números e o segundo 10 números, pois só há 25 números.
// Então, nosso gerador deve sortear 5 bolas do jogo anterior.
// E aí, que entra meu raciocínio para aumentar a chance de ganhar na lotofácil.
// Na lotofacil, sempre haverá no mínimo 5 números que sempre se repete do jogo anterior.
// No gerador aleatório cada tipo de aposta, terá um esquema para distribuir os números.
// Na aposta de 15 números:
// Irá selecionar os 15 primeiros números para o primeiro jogo;
// Em seguida, no segundo jogo, iremos pegar os 10 números restantes e definirmos
// como fixo, em seguida, iremos pegar 5 números do primeiro jogo.
// Depois, no terceiro jogo, iremos pegar os 10 números fixos do jogo anterior e pegar
// os 5 números ainda não sorteados do primeiro jogo
procedure TJogoThread.Preencher_Grade_Lotofacil;
type
TParImpar = (NumeroPar, NumeroImpar);
var
iA, iB, iC: integer;
numeroAleatorio: integer;
// Guarda cada bola, de cada aposta
//iJogo_Grade: array of array of integer;
iJogo_Grade: array[0..1000, 0..50] of integer;
bolaJaSorteada: array[0..99] of boolean;
// Indica a quantidade de bolas já sorteadas.
quantidadeBolasSorteadas: integer;
// Indica o total de bolas que compõe o jogo.
bolaTotal, numeroTemp, iD, iE, ColunaBolaCombinada: integer;
bTrocou: boolean;
TrocarParImpar: TParImpar;
listaNumero: TStringList;
listaNumeroPar: TStringList;
listaNumeroImpar: TStringList;
// Indica os números que estarão fixos, após o primeiro jogo
listaFixa: TStringList;
// Indica os números que estão no primeiro concurso
listaPrimeiroJogo, listaNaoFixa: TStringList;
IndiceLista: longint;
strNumeroConcatenado: string;
Data: TDateTime;
lotofacilEstado: TLotofacilEtapa;
begin
bolaTotal := JogoInfo.bolaFinal - JogoInfo.bolaInicial + 1;
quantidadeBolasSorteadas := 0;
Dec(JogoInfo.quantidadeBilhetes);
// Iniciar o gerador de números randômicos.
Randomize;
// Vamos criar uma lista de string com os números
listaNumero := TStringList.Create;
listaNumeroImpar := TStringList.Create;
listaNUmeroPar := TStringList.Create;
listaFixa:= TStringList.Create;
listaPrimeiroJogo:= TStringList.Create;
listaNaoFixa:=TStringList.Create;
// Indica qual o tipo do número a usar.
TrocarParImpar := TParImpar.NumeroPar;
lotofacilEstado := TLotofacilEtapa.LOTOFACIL_ETAPA_ZERO;
for iA := 0 to JogoInfo.quantidadeBilhetes do
begin
// Se está no passo zero, popular lista.
if lotofacilEstado = TLotofacilEtapa.LOTOFACIL_ETAPA_ZERO then
begin
// Apagar lista.
listaNumero.Clear;
listaNumeroPar.Clear;
listaNumeroImpar.Clear;
listaNaoFixa.Clear;
// Popular lista.
for iC := JogoInfo.bolaInicial to JogoInfo.bolaFinal do
begin
bolaJaSorteada[iC] := False;
listaNumero.Add(IntToStr(iC));
// Há duas lista, uma lista de números pares e uma lista de números ímpares.
// Definir popular conforme o tipo do número.
if iC mod 2 = 0 then
ListaNumeroPar.Add(IntToStr(iC))
else
ListaNumeroImpar.Add(IntToStr(iC));
end;
lotofacilEstado := TLotofacilEtapa.LOTOFACIL_ETAPA_UM;
// Gerar semente do gerador aleatório.
RandSeed := Random(1000000);
end;
case lotofacilEstado of
// Passo 1, sortea aleatoriamente 15 números.
TLotofacilEtapa.LOTOFACIL_ETAPA_UM:
begin
// Apaga as listas.
listaFixa.Clear;
listaPrimeiroJogo.Clear;
iB := 0;
while iB < JogoInfo.bolaAposta do
begin
// Pegar aleatóriamente um índice da lista de números.
indiceLista := Random(ListaNumero.Count);
// Pegar número que está na posição deste índice.
numeroAleatorio := StrToInt(ListaNumero.Strings[IndiceLista]);
// Adiciona este número à lista do primeiro jogo.
ListaPrimeiroJogo.Add(IntToStr(numeroAleatorio));
// Apagar item no índice que foi selecionado.
ListaNumero.Delete(indiceLista);
// Gravar no arranjo
iJogo_Grade[iA, iB] := numeroAleatorio;
Inc(iB);
// Continua até chegar ao fim do loop
Continue;
end;
// Percorremos todos os ítens, agora, pegar os números que serão fixos.
while listaNumero.Count <> 0 do
begin
listaFixa.Add(listaNumero.Strings[0]);
listaNumero.Delete(0);
end;
lotofacilEstado := TLotofacilEtapa.LOTOFACIL_ETAPA_DOIS;
end;
// Passo 2, insere os números fixos, em seguida, sortea aleatoriamente
// os números que foram sorteados no primeiro jogo.
TLotofacilEtapa.LOTOFACIL_ETAPA_DOIS:
begin
iB := 0;
// Preenche os números fixos.
for iC := 0 to listaFixa.Count - 1 do begin
iJogo_Grade[iA, iB] := StrToInt(listaFixa.Strings[iC]);
Inc(iB);
end;
// Cada tipo de aposta, terá uma quantidade de bolas não-fixas:
// Aposta de 15 números, haverá 10 números fixos e 5 números não-fixos;
// Aposta de 16 números, haverá 9 números fixos e 6 números não-fixos;
// Aposta de 17 numeros, haverá 8 números fixos e 7 números não-fixos;
// Aposta de 18 números, haverá 7 números fixos e 8 números não-fixos;
for iC := listaFixa.Count to jogoInfo.bolaAposta - 1 do
begin
// Seleciona um índice aleatoriamente.
indiceLista := Random(listaPrimeiroJogo.Count);
// Seleciona o número que está na posição do índice selecionado.
numeroAleatorio := StrToInt(listaPrimeiroJogo.Strings[indiceLista]);
// Apaga o índice selecionado da lista.
listaPrimeiroJogo.Delete(indiceLista);
// Insere na lista.
iJogo_Grade[iA, iB] := numeroAleatorio;
Inc(iB);
// Adiciona item a lista não-fixa, pois, quando não houver
// mais números selecionar os números já sorteados anteriormente.
listaNaoFixa.Add(IntToStr(numeroAleatorio));
end;
// Passa para etapa 3:
lotofacilEstado := TLotofacilEtapa.LOTOFACIL_ETAPA_TRES;
end;
// No passo 3, devemos preencher os números fixos e em seguidas os
// números não-fixos, entretanto, para as aposta de 17 e 18 números,
// há números faltando:
// Para a aposta de 17 números, faltará um número.
// Para a aposta de 18 números, faltará 4 números.
// Nas apostas de 17 e 18 números, na etapa 3, haverá falta de números
// pois, a etapa 3, termina as apostas de 17 e 18 números, então devemos
// pegar os números já sorteados da lista não-fixa e inserir na lista
// 'listaPrimeiroJogo'.
TLotofacilEtapa.LOTOFACIL_ETAPA_TRES:
begin
if jogoInfo.bolaAposta in [17..18] then
begin
for iC := 1 to 4 do
begin
indiceLista := Random(listaNaoFixa.Count);
numeroAleatorio := StrToInt(listaNaoFixa.Strings[indiceLista]);
listaNaoFixa.Delete(indiceLista);
listaPrimeiroJogo.Add(IntToStr(numeroAleatorio));
// Na aposta de 17 números, haverá somente 1 número faltando.
// Então, após definirmos este número podemos sair do loop.
if jogoInfo.bolaAposta = 17 then BREAK;
end;
end;
iB := 0;
// Preenche os números fixos.
for iC := 0 to listaFixa.Count - 1 do
begin
iJogo_Grade[iA, iB] := StrToInt(listaFixa.Strings[iC]);
Inc(iB);
end;
// Cada tipo de aposta, terá uma quantidade de bolas não-fixas:
// Aposta de 15 números, haverá 10 números fixos e 5 números não-fixos;
// Aposta de 16 números, haverá 9 números fixos e 6 números não-fixos;
// Aposta de 17 numeros, haverá 8 números fixos e 7 números não-fixos;
// Aposta de 18 números, haverá 7 números fixos e 8 números não-fixos;
for iC := listaFixa.Count to jogoInfo.bolaAposta - 1 do
begin
// Seleciona um índice aleatoriamente.
indiceLista := Random(listaPrimeiroJogo.Count);
// Seleciona o número que está na posição do índice selecionado.
numeroAleatorio := StrToInt(listaPrimeiroJogo.Strings[indiceLista]);
// Apaga o índice selecionado da lista.
listaPrimeiroJogo.Delete(indiceLista);
// Insere na lista.
iJogo_Grade[iA, iB] := numeroAleatorio;
Inc(iB);
// Adiciona item a lista não-fixa, pois, quando não houver
// mais números selecionar os números já sorteados anteriormente.
listaNaoFixa.Add(IntToStr(numeroAleatorio));
end;
// Só iremos passar para a etapa 4, se as apostas forem de 15, 16
if JogoInfo.bolaAposta in [17..18] then
lotofacilEstado := TLotofacilEtapa.LOTOFACIL_ETAPA_ZERO
else
lotofacilEstado := TLotofacilEtapa.LOTOFACIL_ETAPA_QUATRO;
end;
// Na etapa 4, os únicos tipos de aposta que pode ter é a aposta 15 e 16
// número e é também a última etapa.
// Nesta etapa, a aposta de 16 números faltará 5 números, então, devemos
// pegar os números já sorteados da lista não-fixa e inserir na lista
// 'listaPrimeiroJogo'.
TLotofacilEtapa.LOTOFACIL_ETAPA_QUATRO:
begin
if jogoInfo.bolaAposta = 16 then
begin
for iC := 1 to 5 do
begin
indiceLista := Random(listaNaoFixa.Count);
numeroAleatorio := StrToInt(listaNaoFixa.Strings[indiceLista]);
listaNaoFixa.Delete(indiceLista);
listaPrimeiroJogo.Add(IntToStr(numeroAleatorio));
end;
end;
iB := 0;
// Preenche os números fixos.
for iC := 0 to listaFixa.Count - 1 do
begin
iJogo_Grade[iA, iB] := StrToInt(listaFixa.Strings[iC]);
Inc(iB);
end;
// Cada tipo de aposta, terá uma quantidade de bolas não-fixas:
// Aposta de 15 números, haverá 10 números fixos e 5 números não-fixos;
// Aposta de 16 números, haverá 9 números fixos e 6 números não-fixos;
// Aposta de 17 numeros, haverá 8 números fixos e 7 números não-fixos;
// Aposta de 18 números, haverá 7 números fixos e 8 números não-fixos;
for iC := listaFixa.Count to jogoInfo.bolaAposta - 1 do
begin
// Seleciona um índice aleatoriamente.
indiceLista := Random(listaPrimeiroJogo.Count);
// Seleciona o número que está na posição do índice selecionado.
numeroAleatorio := StrToInt(listaPrimeiroJogo.Strings[indiceLista]);
// Apaga o índice selecionado da lista.
listaPrimeiroJogo.Delete(indiceLista);
// Insere na lista.
iJogo_Grade[iA, iB] := numeroAleatorio;
Inc(iB);
// Adiciona item a lista não-fixa, pois, quando não houver
// mais números selecionar os números já sorteados anteriormente.
listaNaoFixa.Add(IntToStr(numeroAleatorio));
end;
// Retorna para a etapa zero.
lotofacilEstado := TLotofacilEtapa.LOTOFACIL_ETAPA_ZERO
end;
end;
//O arranjo é baseado em zero, devemos diminuir iB, para utilizar
//com melhor desempenho no loop.
Dec(iB);
repeat
bTrocou := False;
for iE := 0 to iB - 1 do
begin
if iJogo_Grade[iA, iE] > iJogo_Grade[iA, iE + 1] then
begin
numeroTemp := iJogo_Grade[iA, iE];
iJogo_Grade[iA, iE] := iJogo_Grade[iA, iE + 1];
iJogo_Grade[iA, iE + 1] := numeroTemp;
bTrocou := True;
end;
end;
until bTrocou = False;
end;
// A quantidade de números apostados, indicará a quantidade de colunas que haverá.
// Também, haverá colunas adicionais para indicar informações para identificar
// O tipo do jogo, a quantidade de números apostados, e quantos jogos foram
// selecionados.
// Haverá 4 colunas a mais, para indicar:
// Tipo do jogo;
// quantidade de números apostados;
// quantidade de jogos apostados; e,
// bolas_concatenadas.
// bolas_repetidas;
JogoGrade.ColCount := JogoInfo.bolaAposta + 5;
// A quantidade de fileira será 1 maior, pois uma coluna será o cabeçalho.
// Retorna ao estado atual.
Inc(JogoInfo.quantidadeBilhetes);
JogoGrade.RowCount := JogoInfo.quantidadeBilhetes + 1;
// A primeira fileira conterá o cabeçalho
JogoGrade.FixedRows := 1;
// As três colunas iniciais de cada fileira, indica:
// O tipo do jogo,
// A quantidade de números apostados,
// e, quantidade de jogos apostados.
JogoGrade.FixedCols := 3;
// Vamos preencher o cabeçalho
JogoGrade.Cells[0, 0] := 'BILHETE';
JogoGrade.Cells[1, 0] := 'JOGO';
JogoGrade.Cells[2, 0] := 'APOSTA';
JogoGrade.Cells[JogoGrade.ColCount - 2, 0] := 'BOLAS_COMBINADAS';
JogoGrade.Cells[JogoGrade.ColCount - 1, 0] := 'REPETIU COM BILHETE:';
// Vamos começar na coluna 3, como os índices são baseados em 0
// iremos adicionar + 2
for iA := 1 to JogoInfo.bolaAposta do
begin
JogoGrade.Cells[iA + 2, 0] := 'B' + IntToStr(iA);
end;
// Preencher grid.
for iA := 1 to JogoInfo.quantidadeBilhetes do
begin
// Insira informações das colunas 1 a 2
JogoGrade.Cells[0, iA] := IntToStr(iA);
JogoGrade.cells[1, iA] := JogoInfo.JogoTipo;
JogoGrade.Cells[2, iA] := 'com ' + IntToStr(JogoInfo.bolaAposta) + ' números.';
//statusBar1.Panels[0].Text := 'Processando linha: ' + IntToStr(iA + 1);
//statusBar1.Refresh;
strNumeroConcatenado := '';
for iB := 0 to JogoInfo.bolaAposta - 1 do
begin
JogoGrade.Cells[3 + iB, iA] := IntToStr(iJogo_Grade[iA - 1, iB]);
strNumeroConcatenado += '_' + Format('%.2d', [iJogo_Grade[iA - 1, iB]]);
end;
// Números concatenados.
Inc(iB);
JogoGrade.Cells[3 + iB, iA] := strNumeroConcatenado;
JogoGrade.Cells[4 + iB, iA] := '';
end;
// Pega a coluna das bolas combinadas
ColunaBolaCombinada := JogoGrade.ColCount - 2;
for iA := 1 to JogoInfo.quantidadeBilhetes do
for iB := iA + 1 to JogoInfo.quantidadeBilhetes do
begin
if JogoGrade.Cells[ColunaBolaCombinada, iA] =
JogoGrade.Cells[ColunaBolaCombinada, iB] then
begin
// Vamos acrescentar os dados ao que já está na célula.
JogoGrade.Cells[ColunaBolaCombinada + 1, iB] :=
JogoGrade.Cells[ColunaBolaCombinada + 1, iB] + IntToStr(iA) + ';';
end;
end;
JogoGrade.AutoSizeColumns;
FreeAndNil(listaNumero);
end;
procedure TJogoThread.Preencher_Grade_Lotomania;
var bolasSorteadas: array of array of integer;
begin
end;
end.
|
{*
FtermSSH : An SSH implementation in Delphi for FTerm2 by kxn@cic.tsinghua.edu.cn
Cryptograpical code from OpenSSL Project
*}
unit sshmd5;
interface
uses SSHHash;
type
MD5CTX = record
Data: array[1..23] of integer;
end;
PMD5CTX = ^MD5CTX;
TSSHMD5 = class(TSSHHash)
protected
md5: MD5CTX;
function GetDigLen: integer; override;
public
constructor Create; override;
procedure Update(Data: Pointer; Len: integer); override;
procedure Final(Digest: Pointer); override;
property DigestLength: integer read GetDigLen;
end;
procedure MD5_Init(c: PMD5CTX); cdecl; external 'libeay32.dll';
procedure MD5_Update(c: PMD5CTX; Data: Pointer; Len: integer); cdecl;
external 'libeay32.dll';
procedure MD5_Final(Data: Pointer; c: PMD5CTX); cdecl; external 'libeay32.dll';
implementation
{ TSSHMD5 }
constructor TSSHMD5.Create;
begin
MD5_Init(@md5);
end;
procedure TSSHMD5.Final(Digest: Pointer);
begin
MD5_Final(Digest, @md5);
end;
function TSSHMD5.GetDigLen: integer;
begin
Result := 16;
end;
procedure TSSHMD5.Update(Data: Pointer; Len: integer);
begin
MD5_Update(@md5, Data, Len);
end;
end.
|
unit OldNodes;
interface
uses
SysUtils, Types, Graphics,
Style, Layout, Render3;
type
TCustomNode = class(TNode)
protected
function CreateRenderer: TRenderer; virtual;
procedure Paint(inCanvas: TCanvas; inRect: TRect); virtual;
public
procedure Render(inBox: TBox; inCanvas: TCanvas;
inRect: TRect);
end;
//
TNodeClass = class of TCustomNode;
//
TDivNode = class(TCustomNode)
public
class function GetContextClass: TContextClass; override;
procedure InitBox(inLayout: TLayout; var inBox: TBox); override;
end;
//
TInlineNode = class(TCustomNode)
public
class function GetContextClass: TContextClass; override;
procedure InitBox(inLayout: TLayout; var inBox: TBox); override;
end;
implementation
{ TCustomNode }
function TCustomNode.CreateRenderer: TRenderer;
begin
Result := TRenderer.Create;
end;
procedure TCustomNode.Render(inBox: TBox; inCanvas: TCanvas; inRect: TRect);
procedure RenderBoxes;
begin
if (inBox.Boxes.Count > 0) then
with CreateRenderer do
try
Render(inBox.Boxes, inCanvas, inRect);
finally
Free;
end;
end;
begin
Paint(inCanvas, inRect);
if (inBox.Boxes <> nil) then
RenderBoxes;
end;
procedure TCustomNode.Paint(inCanvas: TCanvas; inRect: TRect);
begin
if (Style.BackgroundColor <> clDefault) then
begin
inCanvas.Brush.Style := bsSolid;
inCanvas.Brush.Color := Style.BackgroundColor;
inCanvas.FillRect(inRect);
end;
if (Style.Color <> clDefault) then
inCanvas.Font.Color := Style.Color;
inCanvas.TextOut(inRect.Left, inRect.Top, Text);
inCanvas.Brush.Style := bsClear;
inCanvas.Rectangle(inRect);
end;
{ TDivNode }
class function TDivNode.GetContextClass: TContextClass;
begin
Result := TBlockContext;
end;
procedure TDivNode.InitBox(inLayout: TLayout; var inBox: TBox);
begin
with inBox do
begin
if Style.Width > 0 then
Width := Style.Width;
if Style.Height > 0 then
Height := Style.Height;
Offset := Point(0, Height);
end;
end;
{ TInlineNode }
class function TInlineNode.GetContextClass: TContextClass;
begin
Result := TInlineContext;
end;
procedure TInlineNode.InitBox(inLayout: TLayout; var inBox: TBox);
begin
with inBox do
begin
Width := inLayout.Canvas.TextWidth(Text);
Height := inLayout.Canvas.TextHeight(Text);
Offset := Point(Width, 0);
end;
end;
end.
|
unit SimpleLED;
interface
uses
System.SysUtils, System.Classes, Vcl.Controls, Vcl.Graphics;
type
TSimpleLEDIndicator = class(TGraphicControl)
private
fColor: TColor;
procedure SetColor(NewColor: TColor);
protected
procedure Paint; override;
procedure DrawIndicator(NewColor: TColor);
public
constructor Create(AOwner: TComponent); override;
property Color: TColor read fColor write SetColor;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('My Component', [TSimpleLEDIndicator]);
end;
{ TSimpleLEDIndicator }
constructor TSimpleLEDIndicator.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Height := 50;
Width := 50;
Color := clGreen;
end;
// Алгоритм отрисовки компонента
procedure TSimpleLEDIndicator.DrawIndicator(NewColor: TColor);
begin
Canvas.Pen.Style := psSolid;
Canvas.Brush.Style := bsSolid;
Canvas.Brush.Color := NewColor;
Canvas.Rectangle(0, 0, Width, Height);
end;
// Собственно отрисовка компонента
procedure TSimpleLEDIndicator.Paint;
begin
DrawIndicator(fColor);
end;
// Перерисовка компонента при изменении цвета
procedure TSimpleLEDIndicator.SetColor(NewColor: TColor);
begin
fColor := NewColor;
Refresh;
end;
end.
|
unit uFrmChoosePrice;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, PAIDETODOS, siComp, siLangRT, StdCtrls, LblEffct, ExtCtrls,
cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, DB,
cxDBData, cxGridLevel, cxClasses, cxControls, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, ADODB;
type
TChoosedPrice = class
IDVendor: Integer;
IDDescriptionPrice: Integer;
CostPrice: Currency;
SuggPrice: Currency;
SalePrice: Currency;
end;
TFrmChoosePrice = class(TFrmParent)
grdPriceTable: TcxGrid;
grdPriceTableDBTableView: TcxGridDBTableView;
grdPriceTableLevel: TcxGridLevel;
qryModelPrice: TADOQuery;
qryModelPriceIDDescriptionPrice: TIntegerField;
qryModelPriceIDVendor: TIntegerField;
qryModelPriceCostPrice: TBCDField;
qryModelPriceSuggPrice: TBCDField;
qryModelPriceSalePrice: TBCDField;
dsPriceTable: TDataSource;
qryModelPriceDescriptionPrice: TStringField;
qryModelPriceVendor: TStringField;
grdPriceTableDBTableViewCostPrice: TcxGridDBColumn;
grdPriceTableDBTableViewSuggPrice: TcxGridDBColumn;
grdPriceTableDBTableViewSalePrice: TcxGridDBColumn;
grdPriceTableDBTableViewDescriptionPrice: TcxGridDBColumn;
grdPriceTableDBTableViewVendor: TcxGridDBColumn;
qryStorePrice: TADOQuery;
IntegerField1: TIntegerField;
IntegerField2: TIntegerField;
BCDField1: TBCDField;
BCDField2: TBCDField;
BCDField3: TBCDField;
StringField1: TStringField;
StringField2: TStringField;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure grdPriceTableDBTableViewDblClick(Sender: TObject);
private
FChoosedPrice: TChoosedPrice;
FIDStore: Integer;
FIDModel: Integer;
procedure ClosePriceTableDS;
procedure OpenPriceTableDS;
procedure SetChoosedPrice;
public
function ChoosePrice(AIDStore, AIDModel: Integer): TChoosedPrice;
end;
implementation
uses uDM;
{$R *.dfm}
{ TFrmChoosePrice }
function TFrmChoosePrice.ChoosePrice(AIDStore, AIDModel: Integer): TChoosedPrice;
begin
FIDStore := AIDStore;
FIDModel := AIDModel;
OpenPriceTableDS;
ShowModal;
SetChoosedPrice;
ClosePriceTableDS;
Result := FChoosedPrice;
end;
procedure TFrmChoosePrice.ClosePriceTableDS;
begin
qryStorePrice.Close;
qryModelPrice.Close;
end;
procedure TFrmChoosePrice.FormCreate(Sender: TObject);
begin
inherited;
FChoosedPrice := TChoosedPrice.Create;
end;
procedure TFrmChoosePrice.FormDestroy(Sender: TObject);
begin
inherited;
FreeAndNil(FChoosedPrice);
end;
procedure TFrmChoosePrice.OpenPriceTableDS;
begin
with qryStorePrice do
begin
if Active then
Close;
Parameters.ParamByName('IDStore').Value := FIDStore;
Parameters.ParamByName('IDModel').Value := FIDModel;
Open;
end;
if qryStorePrice.IsEmpty then
begin
with qryModelPrice do
begin
if Active then
Close;
Parameters.ParamByName('IDModel').Value := FIDModel;
Open;
end;
dsPriceTable.DataSet := qryModelPrice;
end
else
dsPriceTable.DataSet := qryStorePrice;
end;
procedure TFrmChoosePrice.SetChoosedPrice;
begin
FChoosedPrice.IDVendor := dsPriceTable.DataSet.FieldByName('IDVendor').AsInteger;
FChoosedPrice.IDDescriptionPrice := dsPriceTable.DataSet.FieldByName('IDDescriptionPrice').AsInteger;
FChoosedPrice.CostPrice := dsPriceTable.DataSet.FieldByName('CostPrice').AsCurrency;
FChoosedPrice.SuggPrice := dsPriceTable.DataSet.FieldByName('SuggPrice').AsCurrency;
FChoosedPrice.SalePrice := dsPriceTable.DataSet.FieldByName('SalePrice').AsCurrency;
end;
procedure TFrmChoosePrice.grdPriceTableDBTableViewDblClick(
Sender: TObject);
begin
inherited;
Close;
end;
end.
|
unit uDlgObjectsForDocs;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uBASE_DialogForm, Menus, cxLookAndFeelPainters, StdCtrls,
cxButtons, ExtCtrls, uFrameObjectList, cxTextEdit, uCashDataSource,
cxClasses, cxGridCustomTableView, cxGridTableView, cxGridBandedTableView,
cxTableViewCds;
type
TdlgObjectsForDocs = class(TBASE_DialogForm)
FrameObjectList: TFrameObjectList;
procedure bbApplyFilterClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FrameByPropsbbInsertClick(Sender: TObject);
private
FPrimaryKey: integer;
public
property PrimaryKey: integer read FPrimaryKey write FPrimaryKey;
{ Public declarations }
end;
var
dlgObjectsForDocs: TdlgObjectsForDocs;
implementation
uses uParams, uAccess, ADODB, uDlgSelectObjectsForDocs, uCommonUtils,
uMain;
{$R *.dfm}
procedure TdlgObjectsForDocs.bbApplyFilterClick(Sender: TObject);
var
p: TParamCollection;
begin
p:=FrameObjectList.FrameObjectFilter.CreateFilterParams;
try
p['@код_Документ'].Value:=PrimaryKey;
FrameObjectList.FrameByProps.ApplyFilterParams(p);
finally
p.Free;
end;
end;
procedure TdlgObjectsForDocs.FormShow(Sender: TObject);
var
col: TcxGridBandedColumnCds;
begin
inherited;
col:=self.FrameObjectList.FrameByProps.ViewCds.CreateColumn as TcxGridBandedColumnCds;
col.DataBinding.FieldName:='Правовой статус.Наименование';
col.Caption:='Правовой статус';
col.AlternateCaption:='Документ.Правовой статус';
col.Position.BandIndex:=1;
col:=self.FrameObjectList.FrameByProps.ViewCds.CreateColumn as TcxGridBandedColumnCds;
col.DataBinding.FieldName:='Субъекты учета.Принято от';
col.Caption:='Принято от';
col.AlternateCaption:='Документ.Принято от';
col.Position.BandIndex:=1;
col:=self.FrameObjectList.FrameByProps.ViewCds.CreateColumn as TcxGridBandedColumnCds;
col.DataBinding.FieldName:='Субъекты учета.Закреплено за';
col.Caption:='Закреплено за';
col.AlternateCaption:='Документ.Закреплено за';
col.Position.BandIndex:=1;
col:=self.FrameObjectList.FrameByProps.ViewCds.CreateColumn as TcxGridBandedColumnCds;
col.DataBinding.FieldName:='Вид пользования имуществом.Наименование';
col.Caption:='Вид пользования';
col.AlternateCaption:='Документ.Вид пользования';
col.Position.BandIndex:=1;
FrameObjectList.FrameByProps.bbInsert.OnClick:=FrameByPropsbbInsertClick;
end;
procedure TdlgObjectsForDocs.FrameByPropsbbInsertClick(Sender: TObject);
var
a: TAccessSelectorForm;
i: integer;
qry: TAdoQuery;
p: TParamCollection;
sp: TAdoStoredProc;
begin
a:=TAccessSelectorForm.Create;
try
a.ObjectID:=9;
a.FormClass:=TdlgSelectObjectsForDocs;
a.FormAutoFree:=false;
p:=TParamCollection.Create(TParamItem);
try
if a.ShowModal(p, null)<>mrOK then exit;
finally
p.Free;
end;
sp:=TAdoStoredProc.Create(nil);
try
sp.Connection:=frmMain.ADOConnection;
sp.ProcedureName:='sp_Документы_добавить';
sp.Parameters.Refresh;
with (a.Form as TdlgSelectObjectsForDocs).SelectedIDs do
for i:=0 to Count-1 do begin
sp.Parameters.FindParam('@вк_Учетная_единица').Value:=Items[i].Value;
sp.Parameters.FindParam('@Документ').Value:=PrimaryKey;
sp.Parameters.FindParam('@Правовой_статус').Value:=Items[i].StatusID;
sp.Parameters.FindParam('@Принято_от').Value:=Items[i].OrgFrom;
sp.Parameters.FindParam('@Закреплено_за').Value:=Items[i].OrgTo;
sp.Parameters.FindParam('@Вид_пользования_имуществом').Value:=Items[i].ViewID;
sp.ExecProc;
// qry.SQL.Text:=format('sp_%sОбъект_добавить @код_%s = %d, @код_Объект = %d, @код_Вид_пользования = %s, @код_Статус = %s, @Flag = 1', [GetItemName, GetItemName, PrimaryKey, Items[i].Value, VariantToStrDB(Items[i].ViewID), VariantToStrDB(Items[i].StatusID)]);
end;
finally
sp.Free;
end;
finally
a.Free;
end;
end;
end.
|
unit pSHReplaceTextFrm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, pSHFindTextFrm, Menus, ExtCtrls, StdCtrls, Buttons,
pSHIntf;
type
TpSHReplaceTextForm = class(TpSHFindTextForm)
cbPromtOnReplace: TCheckBox;
cbReplaceText: TComboBox;
Label1: TLabel;
Button1: TButton;
private
function GetReplaceText: string;
procedure SetReplaceText(const Value: string);
{ Private declarations }
protected
function GetFindTextOptions: TBTFindTextOptions; override;
procedure SetFindTextOptions(const Value: TBTFindTextOptions); override;
procedure DoSaveSettings; override;
procedure DoRestoreSettings; override;
public
{ Public declarations }
property ReplaceText: string read GetReplaceText write SetReplaceText;
end;
var
pSHReplaceTextForm: TpSHReplaceTextForm;
implementation
{$R *.dfm}
{ TpSHReplaceTextForm }
function TpSHReplaceTextForm.GetReplaceText: string;
begin
Result := cbReplaceText.Text;
end;
procedure TpSHReplaceTextForm.SetReplaceText(const Value: string);
begin
cbReplaceText.Text := Value;
end;
function TpSHReplaceTextForm.GetFindTextOptions: TBTFindTextOptions;
begin
Result := inherited GetFindTextOptions;
if cbPromtOnReplace.Checked then
Include(Result, ftoPromptOnReplace);
end;
procedure TpSHReplaceTextForm.SetFindTextOptions(
const Value: TBTFindTextOptions);
begin
inherited SetFindTextOptions(Value);
if ftoPromptOnReplace in Value then
cbPromtOnReplace.Checked := True
else
cbPromtOnReplace.Checked := False;
end;
procedure TpSHReplaceTextForm.DoSaveSettings;
begin
inherited;
if ((ModalResult = mrOk) or (ModalResult = mrYesToAll)) and
Assigned(FindReplaceHistory) then
FindReplaceHistory.AddToReplaceHistory(ReplaceText);
end;
procedure TpSHReplaceTextForm.DoRestoreSettings;
begin
inherited;
if Assigned(FindReplaceHistory) then
cbReplaceText.Items.Text := FindReplaceHistory.ReplaceHistory.Text
end;
end.
|
unit HVABank;
interface
uses HVA, Voxel, HVABankItem, SysUtils;
type
THVABank = class
private
Items : array of THVABankItem;
// Constructors and Destructors
procedure Clear;
// Adds
function Search(const _Filename: string): integer; overload;
function Search(const _HVA: PHVA): integer; overload;
function SearchReadOnly(const _Filename: string): integer; overload;
function SearchReadOnly(const _HVA: PHVA): integer; overload;
function SearchEditable(const _HVA: PHVA): integer;
public
// Constructors and Destructors
constructor Create;
destructor Destroy; override;
// I/O
function Load(var _HVA: PHVA; const _Filename: string; const _Voxel: PVoxel): PHVA;
function LoadNew(const _Voxel: PVoxel): PHVA;
function Save(var _HVA: PHVA; const _Filename: string): boolean;
// Adds
function Add(const _filename: string; _Voxel: PVoxel): PHVA; overload;
function Add(const _HVA: PHVA): PHVA; overload;
function AddReadOnly(const _filename: string; _Voxel: PVoxel): PHVA; overload;
function AddReadOnly(const _HVA: PHVA): PHVA; overload;
function Clone(const _filename: string; _Voxel: PVoxel): PHVA; overload;
function Clone(const _HVA: PHVA): PHVA; overload;
function CloneEditable(const _HVA: PHVA): PHVA; overload;
// Deletes
procedure Delete(const _HVA : PHVA);
end;
implementation
// Constructors and Destructors
constructor THVABank.Create;
begin
SetLength(Items,0);
end;
destructor THVABank.Destroy;
begin
Clear;
inherited Destroy;
end;
// Only activated when the program is over.
procedure THVABank.Clear;
var
i : integer;
begin
for i := Low(Items) to High(Items) do
begin
Items[i].Free;
end;
end;
// I/O
function THVABank.Load(var _HVA: PHVA; const _Filename: string; const _Voxel: PVoxel): PHVA;
var
i : integer;
begin
i := SearchEditable(_HVA);
if i <> -1 then
begin
Items[i].DecCounter;
if Items[i].GetCount = 0 then
begin
Items[i].Free;
Items[i] := THVABankItem.Create(_Filename, _Voxel);
Items[i].SetEditable(true);
Result := Items[i].GetHVA;
end
else
begin
SetLength(Items,High(Items)+2);
Items[High(Items)] := THVABankItem.Create(_Filename, _Voxel);
Items[High(Items)].SetEditable(true);
Result := Items[High(Items)].GetHVA;
end;
end
else
begin
SetLength(Items,High(Items)+2);
Items[High(Items)] := THVABankItem.Create(_Filename, _Voxel);
Items[High(Items)].SetEditable(true);
Result := Items[High(Items)].GetHVA;
end;
end;
function THVABank.LoadNew(const _Voxel : PVoxel): PHVA;
begin
SetLength(Items,High(Items)+2);
Items[High(Items)] := THVABankItem.Create;
Items[High(Items)].SetEditable(true);
Result := Items[High(Items)].GetHVA;
Result^.p_Voxel := _Voxel;
end;
function THVABank.Save(var _HVA: PHVA; const _Filename: string): boolean;
var
i : integer;
HVA : PHVA;
begin
i := Search(_HVA);
if i <> -1 then
begin
HVA := Items[i].GetHVA;
HVA^.SaveFile(_Filename);
Items[i].SetFilename(_Filename);
Result := true;
end
else
begin
Result := false;
end;
end;
// Adds
function THVABank.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 THVABank.Search(const _HVA: PHVA): integer;
var
i : integer;
begin
Result := -1;
if _HVA = nil then
exit;
i := Low(Items);
while i <= High(Items) do
begin
if _HVA = Items[i].GetHVA then
begin
Result := i;
exit;
end;
inc(i);
end;
end;
function THVABank.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 THVABank.SearchReadOnly(const _HVA: PHVA): integer;
var
i : integer;
begin
Result := -1;
if _HVA = nil then
exit;
i := Low(Items);
while i <= High(Items) do
begin
if not Items[i].GetEditable then
begin
if _HVA = Items[i].GetHVA then
begin
Result := i;
exit;
end;
end;
inc(i);
end;
end;
function THVABank.SearchEditable(const _HVA: PHVA): integer;
var
i : integer;
begin
Result := -1;
if _HVA = nil then
exit;
i := Low(Items);
while i <= High(Items) do
begin
if Items[i].GetEditable then
begin
if _HVA = Items[i].GetHVA then
begin
Result := i;
exit;
end;
end;
inc(i);
end;
end;
function THVABank.Add(const _filename: string; _Voxel: PVoxel): PHVA;
var
i : integer;
begin
i := Search(_Filename);
if i <> -1 then
begin
Items[i].IncCounter;
Result := Items[i].GetHVA;
end
else
begin
SetLength(Items,High(Items)+2);
Items[High(Items)] := THVABankItem.Create(_Filename, _Voxel);
Result := Items[High(Items)].GetHVA;
end;
end;
function THVABank.Add(const _HVA: PHVA): PHVA;
var
i : integer;
begin
i := Search(_HVA);
if i <> -1 then
begin
Items[i].IncCounter;
Result := Items[i].GetHVA;
end
else
begin
SetLength(Items,High(Items)+2);
Items[High(Items)] := THVABankItem.Create(_HVA);
Result := Items[High(Items)].GetHVA;
end;
end;
function THVABank.AddReadOnly(const _filename: string; _Voxel: PVoxel): PHVA;
var
i : integer;
begin
i := SearchReadOnly(_Filename);
if i <> -1 then
begin
Items[i].IncCounter;
Result := Items[i].GetHVA;
end
else
begin
SetLength(Items,High(Items)+2);
Items[High(Items)] := THVABankItem.Create(_Filename, _Voxel);
Result := Items[High(Items)].GetHVA;
end;
end;
function THVABank.AddReadOnly(const _HVA: PHVA): PHVA;
var
i : integer;
begin
i := SearchReadOnly(_HVA);
if i <> -1 then
begin
Items[i].IncCounter;
Result := Items[i].GetHVA;
end
else
begin
SetLength(Items,High(Items)+2);
Items[High(Items)] := THVABankItem.Create(_HVA);
Result := Items[High(Items)].GetHVA;
end;
end;
function THVABank.Clone(const _filename: string; _Voxel: PVoxel): PHVA;
begin
SetLength(Items,High(Items)+2);
Items[High(Items)] := THVABankItem.Create(_Filename,_Voxel);
Result := Items[High(Items)].GetHVA;
end;
function THVABank.Clone(const _HVA: PHVA): PHVA;
begin
SetLength(Items,High(Items)+2);
Items[High(Items)] := THVABankItem.Create(_HVA);
Result := Items[High(Items)].GetHVA;
end;
function THVABank.CloneEditable(const _HVA: PHVA): PHVA;
begin
SetLength(Items,High(Items)+2);
Items[High(Items)] := THVABankItem.Create(_HVA);
Items[High(Items)].SetEditable(true);
Result := Items[High(Items)].GetHVA;
end;
// Deletes
procedure THVABank.Delete(const _HVA : PHVA);
var
i : integer;
begin
i := Search(_HVA);
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.
|
{===============================================================================
RadiantMediaPlayerConfigForm Unit
Radiant Shapes - Demo Source Unit
Copyright © 2012-2014 by Raize Software, Inc. All Rights Reserved.
Modification History
------------------------------------------------------------------------------
1.0 (29 Oct 2014)
* Initial release.
===============================================================================}
unit RadiantMediaPlayerConfigForm;
interface
uses
System.SysUtils,
System.Types,
System.UITypes,
System.Classes,
System.Variants,
FMX.Types,
FMX.Graphics,
FMX.Controls,
FMX.Controls.Presentation,
FMX.Forms,
FMX.Dialogs,
FMX.StdCtrls,
FMX.Colors,
FMX.Objects,
FMX.TabControl,
FMX.Layouts,
Radiant.Shapes;
type
TfrmConfiguration = class(TForm)
btnOK: TButton;
btnCancel: TButton;
cbxButtonColor: TComboColorBox;
cbxHighlightColor: TComboColorBox;
optStockColors: TRadioButton;
optCustomColors: TRadioButton;
Label2: TLabel;
Label3: TLabel;
lytStockColors: TLayout;
optColorScheme1: TRadioButton;
optColorScheme2: TRadioButton;
lytCustomColors: TLayout;
rectScheme1Color: TRadiantRectangle;
rectScheme1Highlight: TRadiantRectangle;
rectScheme2Color: TRadiantRectangle;
rectScheme2Highlight: TRadiantRectangle;
optColorScheme3: TRadioButton;
rectScheme3Color: TRadiantRectangle;
rectScheme3Highlight: TRadiantRectangle;
optColorScheme4: TRadioButton;
rectScheme4Color: TRadiantRectangle;
rectScheme4Highlight: TRadiantRectangle;
procedure optStockColorsChange(Sender: TObject);
procedure optCustomColorsChange(Sender: TObject);
procedure btnOKClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
SelectedButtonColor: TAlphaColor;
SelectedHighlightColor: TAlphaColor;
end;
var
frmConfiguration: TfrmConfiguration;
implementation
{$R *.fmx}
uses
RadiantMediaPlayerForm; // For style book reference
procedure TfrmConfiguration.btnOKClick(Sender: TObject);
begin
if optStockColors.IsChecked then
begin
if optColorScheme1.IsChecked then
begin
SelectedButtonColor := rectScheme1Color.Fill.Color;
SelectedHighlightColor := rectScheme1Highlight.Fill.Color;
end
else if optColorScheme2.IsChecked then
begin
SelectedButtonColor := rectScheme2Color.Fill.Color;
SelectedHighlightColor := rectScheme2Highlight.Fill.Color;
end
else if optColorScheme3.IsChecked then
begin
SelectedButtonColor := rectScheme3Color.Fill.Color;
SelectedHighlightColor := rectScheme3Highlight.Fill.Color;
end
else
begin
SelectedButtonColor := rectScheme4Color.Fill.Color;
SelectedHighlightColor := rectScheme4Highlight.Fill.Color;
end;
end
else // optCustomColors
begin
SelectedButtonColor := cbxButtonColor.Color;
SelectedHighlightColor := cbxHighlightColor.Color;
end;
end;
procedure TfrmConfiguration.optStockColorsChange(Sender: TObject);
begin
lytCustomColors.Enabled := False;
lytStockColors.Enabled := True;
end;
procedure TfrmConfiguration.optCustomColorsChange(Sender: TObject);
begin
lytStockColors.Enabled := False;
lytCustomColors.Enabled := True;
end;
end.
|
{*******************************************************************************
Title: T2TiPDV
Description: DataModule
The MIT License
Copyright: Copyright (C) 2014 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
alberteije@gmail.com
@author T2Ti.COM
@version 2.0
*******************************************************************************}
unit UDataModule;
{$mode objfpc}{$H+}
interface
uses
SysUtils, ACBrTEFDClass, Forms, ACBrDevice, ACBrBase, ACBrECF, FMTBcd,
DB, Classes, StdCtrls, Controls, LCLIntf, LCLType, LMessages, ACBrUtil, dateutils,
strutils, Dialogs, Inifiles, ACBrECFClass, ZConnection;
type
{ TFDataModule }
TFDataModule = class(TDataModule)
ACBrECF: TACBrECF;
Conexao: TZConnection;
OpenDialog: TOpenDialog;
procedure DataModuleCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
RemoteAppPath: string;
end;
var
FDataModule: TFDataModule;
implementation
uses UConfigConexao, Biblioteca, USplash;
{$R *.lfm}
procedure TFDataModule.DataModuleCreate(Sender: TObject);
var
ini: TIniFile;
BancoPAF: String;
begin
(*
FSplash.lbMensagem.Caption := 'Conectando a Base de Dados...';
FSplash.lbMensagem.Refresh;
Conexao.Connected := False;
try
ini := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'Conexao.ini');
BancoPAF := UpperCase(ini.ReadString('SGBD', 'BD', ''));
RemoteAppPath := UpperCase(ini.ReadString('IMPORTA', 'REMOTEAPP', ''));
if BancoPAF = 'MYSQL' then
Conexao.Protocol := 'mysql'
else if BancoPAF = 'FIREBIRD' then
Conexao.Protocol := 'firebird-2.5';
Conexao.HostName := ini.ReadString('SGBD', 'BDHostName', '');
Conexao.Database := ini.ReadString('SGBD', 'BDDatabase', '');
Conexao.User := ini.ReadString('SGBD', 'BDUser', '');
Conexao.Password := ini.ReadString('SGBD', 'BDPassword', '');
finally
FreeAndNil(ini);
end;
try
FSplash.Repaint;
Conexao.Connected := True;
FSplash.lbMensagem.Caption := 'Conectando a Base de Dados local...';
FSplash.lbMensagem.Refresh;
FSplash.imgBanco.Visible := True;
// SetTaskBar(false); //descomente se quiser que a barra do windows desapareça
except
FSplash.lbMensagem.Caption := 'Falha ao tentar conectar a Base de Dados';
FSplash.lbMensagem.Refresh;
Application.CreateForm(TFConfigConexao, FConfigConexao);
if FConfigConexao.ShowModal <> mrOK then
begin
SetTaskBar(True);
ACBrECF.Desativar;
Application.ProcessMessages;
Application.Terminate;
end
else
begin
SetTaskBar(False);
FSplash.imgBanco.Visible := True;
end;
end;
*)
end;
end.
|
unit o_addison;
interface
uses Classes, SysUtils, StdCtrls, IBDatabase, IBQuery,
sdfdata,
addisonbasics_TLB, afibu_TLB,
o_stammdaten, o_fibu_stamm, o_fibuexport;
const KundenSchema : array[0..22] of string = (
'SATZART', 'KONTO', 'BEZEICHNUNG', 'STRASSE', 'LAND',
'PLZ', 'ORT', 'TELEFON1', 'EMAIL', 'TELEFAX' , 'USTID',
'ZAHLUNGSART', 'BLZ1', 'BANKKONTO1', 'BANKNAME1', 'KEDITLIMIT',
'KUNDENNUMMER', 'ANREDE', 'KURZBEZ', 'VERDICHTKONTO',
'ZAHLSL', 'SORTSL1', 'SORTSL1BEZ');
const BuchenSchema : array[0..13] of string = (
'SATZART', 'KONTO', 'GEGENKONTO', 'BUCHUNGSDATUM', 'BETRAG',
'BUCHUNGSTEXT', 'BELEGDATUM', 'VALUTADATUM', 'NETTODATUM',
'BELEGNR', 'ABW_ZAHLUNGSART', 'BUCHSTEUERSL', 'BELEGNR2',
'ABW_ZAHLSL');
const ZSchluesselSchema : array[0..5] of string = (
'SATZART', 'ZAHLSL', 'ZAHLSL_NAME', 'ZAHLSL_TAGE1',
'ZAHLSL_PERCENT1', 'ZAHLSL_NETTOTAGE');
const KundenSchemaLaenge = 23;
const BuchenSchemaLaenge = 14;
const ZSchluesselSchemaLaenge = 6;
type TAddison = class(TFibuStamm)
private
CSVFile : TSdfDataSet;
BOMan : AddBOManager;
Mand : AddMandant;
FibuPrj : afibu_TLB.IAddProject;
ImpFibuPrj : AddFibuProjectImp;
Wirtschaftsjahr : RWFibuWJ;
OPSGesehen : array of integer;
ZFStart, ZFEnde : TDateTime;
procedure CSVSchema(aTyp : integer; aFilter : string);
function GetDebitorSaldo(aDebitorNummer : integer) : double;
procedure NeuerOP(OP: RwOP; OpNummerSchreiben : boolean);
procedure OPLoeschen(ID : integer);
function OPGesehen(aMLID : integer) : boolean;
procedure KeineOPSGesehen;
function BetragGleich(aBerag1, aBetrag2 : double) : boolean;
procedure ZahlungsschluesselAbgleichen;
public
constructor Create(aOwner: TComponent; aStammdaten: TStammdaten; aTransaction: TIBTransaction); override;
destructor Destroy; override;
function connect : boolean;
procedure disconnect;
function DebitorExport(aQuery : TIBQuery) : DataArray; override;
function KreditorExport(aQuery : TIBQuery) : DataArray; override;
function PostenExport(aQuery: TIBQuery) : DataArray; override;
procedure PostenReImport; override;
procedure ImportSalden; override;
procedure ImportZahlungen; override;
procedure OPListenAbgleich; override;
function getName: string; override;
end;
implementation
uses ComObj, Math, Dialogs, DateUtils,
o_vorgang, o_erloeskonto, o_empfaenger, o_zahlungsschluessel, f_Optima;
{ TAddison }
function TAddison.BetragGleich(aBerag1, aBetrag2: double): boolean;
begin
Result := SameValue(aBerag1, aBetrag2, 0.05);
end;
function TAddison.connect: boolean;
var Zeit : TDateTime;
ZFOK : boolean;
begin
Wirtschaftsjahr := nil;
Zeit := Time;
ZFOK := (
(ZFStart < ZFEnde) and (ZFStart < Zeit) and (Zeit < ZFEnde)
)
or
(
(not (ZFStart < ZFEnde)) and ((Zeit < ZFEnde) or (ZFStart < Zeit))
);
if not ZFOK then
begin
Inaktiviert;
Result := false;
exit;
end;
try
if (Stammdaten.getAddisonUser <> '') then
BOMan.ConnectEx(Stammdaten.getAddisonUser, Stammdaten.getAddisonPass)
else
BOMan.Connect;
except
on E:Exception do
begin
ShowMsg('Addison: ' + E.Message);
Result := false;
exit;
end;
end;
Mand := BOMan.GetMandant[
StrToInt(Stammdaten.ServerEinstellungen.ReadString('AddisonMandant', '99999'))
];
if Mand <> nil then
begin
addisonbasics_TLB.IAddProject(FibuPrj) := mand.GetFibuProject;
if FibuPrj <> nil then
begin
ImpFibuPrj := CreateComObject(CLASS_AddFibuProjectImp) as IAddFibuProjectImp;
ImpFibuPrj.Attach(FibuPrj);
Wirtschaftsjahr := ImpFibuPrj.GetWJDate[EncodeDate(YearOf(now), 1, 1)];
if Wirtschaftsjahr = nil then
Wirtschaftsjahr := ImpFibuPrj.GetWJDate[EncodeDate(YearOf(now) - 1, 1, 1)];
if Wirtschaftsjahr = nil then
LogMessage('Wirtschaftsjahr konnte nicht geöffnet werden!');
end;
end;
Result := (Wirtschaftsjahr <> nil);
end;
constructor TAddison.Create(aOwner: TComponent; aStammdaten: TStammdaten;
aTransaction: TIBTransaction);
begin
inherited;
CSVFile := TSdfDataSet.Create(self);
CSVFile.Delimiter := ';';
CSVFile.FirstLineAsSchema := false;
CSVFile.FileMustExist := false;
CSVFile.FileName := Stammdaten.ServerEinstellungen.ReadString('AddisonExportDir', '') + '\topfib.csv';
BOMan := CreateComObject(CLASS_AddBOManager) as IAddBOManager;
ZFStart := StrToTime(Stammdaten.ServerEinstellungen.ReadString('AddisonZFStart', '00:00'));
ZFEnde := StrToTime(Stammdaten.ServerEinstellungen.ReadString('AddisonZFEnde', '00:00'));
if Connect then
Disconnect
else
raise EFibuNotPresent.Create('Fehler beim Verbinden mit Addison-Datenbank');
end;
procedure TAddison.CSVSchema(aTyp: integer; aFilter : string);
var x : integer;
begin
CSVFile.Schema.Clear;
case aTyp of
1 : begin
x := 0;
while x < KundenSchemaLaenge do
begin
CSVFile.Schema.Add(KundenSchema[x]);
inc(x);
end;
end;
2 : begin
x := 0;
while x < BuchenSchemaLaenge do
begin
CSVFile.Schema.Add(BuchenSchema[x]);
inc(x);
end;
end;
3 : begin
x := 0;
while x < ZSchluesselSchemaLaenge do
begin
CSVFile.Schema.Add(ZSchluesselSchema[x]);
inc(x);
end;
end;
end;
if aFilter <> '' then
begin
CSVFile.Filter := aFilter;
CSVFile.Filtered := true;
end
else
begin
CSVFile.Filter := '';
CSVFile.Filtered := false;
end;
end;
function TAddison.DebitorExport(aQuery: TIBQuery) : DataArray;
var ZahlArten : TIBQuery;
i: integer;
ZSHelper : TZSHelper;
ZS : TZahlungsschluessel;
Firmenname : string;
begin
try
LogMessage('TobFib-Export: Debitoren');
ZahlArten := TIBQuery.Create(self);
ZahlArten.Transaction := self.Transaction;
ZahlArten.SQL.Text := 'SELECT * FROM ZAHLART';
ZSHelper := TZSHelper.create(self, Stammdaten, Transaction);
OpenTransaction;
ZahlArten.Open;
CSVSchema(1, '');
CSVFile.Open;
i := 0;
setlength(Result, 0);
while not aQuery.Eof do
begin
LogMessage('TobFib-Export: Debitor "' + aQuery.FieldByName('KU_MATCH').AsString + '"');
LogMessage('Zahlungsschlüssel suchen oder neu anlegen...');
ZS := ZSHelper.getZS(self, aQuery.FieldByName('KU_ZNETTOTAGE').AsInteger,
aQuery.FieldByName('KU_ZSKONTOTAGE').AsInteger,
aQuery.FieldByName('KU_ZSKONTO').AsFloat);
LogMessage('Zahlungsschlüssel gelesen...');
Firmenname := '';
if aQuery.FieldByName('KU_FIRMA').AsString <> '' then
Firmenname := aQuery.FieldByName('KU_FIRMA').AsString
else
Firmenname := aQuery.FieldByName('KU_VNAME').AsString + ' ' + aQuery.FieldByName('KU_NAME').AsString;
if Firmenname = '' then
Firmenname := aQuery.FieldByName('KU_MATCH').AsString;
CSVFile.Append;
CSVFile.FieldByName('SATZART').AsString := 'K';
CSVFile.FieldByName('KONTO').AsInteger := aQuery.FieldByName('KU_DEBITOR').AsInteger;
CSVFile.FieldByName('BEZEICHNUNG').AsString := Firmenname;
CSVFile.FieldByName('STRASSE').AsString := Trim(aQuery.FieldByName('KU_STRASSE').AsString + ' ' + aQuery.FieldByName('KU_HAUSNUMMER').asString);
CSVFile.FieldByName('LAND').AsString := aQuery.FieldByName('KU_LAND').AsString;
CSVFile.FieldByName('PLZ').AsString := aQuery.FieldByName('KU_PLZ').AsString;
CSVFile.FieldByName('ORT').AsString := aQuery.FieldByName('KU_ORT').AsString;
CSVFile.FieldByName('TELEFON1').AsString := aQuery.FieldByName('KU_TEL').AsString;
CSVFile.FieldByName('EMAIL').AsString := aQuery.FieldByName('KU_MAIL').AsString;
CSVFile.FieldByName('TELEFAX').AsString := aQuery.FieldByName('KU_FAX').AsString;
CSVFile.FieldByName('USTID').AsString := aQuery.FieldByName('KU_USTID').AsString;
if ZahlArten.Locate('ZA_ID', aQuery.FieldByName('KU_ZAHLART').AsInteger, [])
and (Zahlarten.FieldByName('ZA_BANKV').AsString = 'T') then
CSVFile.FieldByName('ZAHLUNGSART').AsString := 'A'
else
CSVFile.FieldByName('ZAHLUNGSART').AsString := 'N';
CSVFile.FieldByName('BLZ1').AsString := aQuery.FieldByName('KU_BLZ').AsString;
CSVFile.FieldByName('BANKKONTO1').AsString := aQuery.FieldByName('KU_KTONR').AsString;
CSVFile.FieldByName('BANKNAME1').AsString := aQuery.FieldByName('KU_BANK').AsString;
CSVFile.Fields[15].Asfloat := aQuery.FieldByName('KU_KREDITLIMIT').AsFloat;
CSVFile.Fields[16].AsString := aQuery.FieldByName('KU_NR').AsString;
CSVFile.Fields[17].AsString := aQuery.FieldByName('KU_ANREDE').AsString;
CSVFile.Fields[18].AsString := Firmenname;
CSVFile.Fields[19].AsString := aQuery.FieldByName('UT_KONTONR').AsString;
CSVFile.Fields[20].AsInteger := ZS.getID;
if aQuery.FieldByName('KU_EUAUSLAND').AsString = 'T' then
begin
CSVFile.Fields[21].AsInteger := 2;
CSVFile.Fields[22].AsString := 'EU-AUSLAND';
end
else
if aQuery.FieldByName('KU_AUSLAND').AsString = 'T' then
begin
CSVFile.Fields[21].AsInteger := 3;
CSVFile.Fields[22].AsString := 'DRITTLAND';
end
else
begin
CSVFile.Fields[21].AsInteger := 1;
CSVFile.Fields[22].AsString := 'INLAND';
end;
CSVFile.CheckBrowseMode;
setlength(Result, i + 1);
Result[i] := aQuery.FieldByName('KU_ID').AsInteger;
FreeAndNil(ZS);
inc(i);
aQuery.Next;
end;
CSVFile.Close;
ZahlArten.Close;
ZahlArten.Free;
ZSHelper.Free;
CommitTransaction;
ZahlungsschluesselAbgleichen;
LogMessage('TobFib-Export (Debitoren) abgeschlossen');
except
on E:Exception do
begin
ShowMessage(E.Message + #13 + 'function TAddison.DebitorExport(aQuery: TIBQuery) : DataArray;');
raise;
end;
end;
end;
destructor TAddison.destroy;
begin
try
BoMan := nil;
// Backup
CSVFile.Open;
if CSVFile.RecordCount > 0 then
CSVFile.SaveFileAs(Stammdaten.ServerEinstellungen.ReadString('AddisonExportDir', '') + '\backup.' + FormatDatetime('ddmmyyhhnn', now) + '.txt');
CSVFile.Close;
CSVFile.Free;
inherited;
except
on E:Exception do
begin
ShowMessage(E.Message + #13 + 'destructor TAddison.destroy');
raise;
end;
end;
end;
procedure TAddison.disconnect;
begin
BOMan.close;
end;
function TAddison.GetDebitorSaldo(aDebitorNummer: integer): double;
var FibuKonto : RWFibuKonto;
begin
Result := 0;
if Wirtschaftsjahr.IsDebitor[IntToStr(aDebitorNummer)] <> 0 then
begin
FibuKonto := Wirtschaftsjahr.m_Debitorkonten.SearchFibuKonto[IntToStr(aDebitorNummer)];
if FibuKonto <> nil then
begin
result := FibuKonto.m_Saldo[12];
FibuKonto := nil;
end;
end;
end;
function TAddison.getName: string;
begin
result := 'Addison';
end;
procedure TAddison.ImportSalden;
var ReadQuery : TIBQuery;
WriteQuery : TIBQuery;
begin
LogMessage('TobFib: Salden lesen');
if not Connect then
begin
LogMessage('Keine Verbindung zur Datenbank');
exit;
end;
if Wirtschaftsjahr = nil then
begin
LogMessage('Keine Verbindung zur Datenbank');
exit;
end;
ReadQuery := TIBQuery.Create(self);
ReadQuery.Transaction := Transaction;
WriteQuery := TIBQuery.Create(self);
WriteQuery.Transaction := Transaction;
OpenTransaction;
Readquery.SQL.Clear;
Readquery.SQL.Add('SELECT KU_MATCH, KU_ID, KU_DEBITOR FROM KUNDEN ' +
'WHERE (KU_DEBITOR != 0) and (KU_DEBITOR IS NOT NULL)');
WriteQuery.SQL.Clear;
WriteQuery.SQL.Add('UPDATE KUNDEN SET KU_SALDO = :Saldo WHERE KU_ID = :ID');
ReadQuery.Open;
while not ReadQuery.Eof do
begin
LogMessage(Readquery.FieldByName('KU_MATCH').AsString);
WriteQuery.ParamByName('ID').AsInteger :=
Readquery.FieldByName('KU_ID').AsInteger;
WriteQuery.ParamByName('Saldo').AsFloat :=
GetDebitorSaldo(ReadQuery.FieldByName('KU_DEBITOR').AsInteger);
WriteQuery.ExecSQL;
ReadQuery.Next;
end;
Readquery.Close;
Readquery.Free;
CommitTransaction;
LogMessage('TobFib: Salden lesen abgeschlossen');
Disconnect;
end;
procedure TAddison.ImportZahlungen;
begin
// Zahlungen können momentan nicht aus der Schnittstelle gelesen werden.
end;
procedure TAddison.KeineOPSGesehen;
begin
SetLength(OPSGesehen, 0);
end;
function TAddison.KreditorExport(aQuery : TIBQuery) : DataArray;
var ZahlArten : TIBQuery;
i : integer;
ZSHelper : TZSHelper;
ZS : TZahlungsschluessel;
Firmenname : string;
begin
LogMessage('TobFib-Export: Kreditoren');
ZahlArten := TIBQuery.Create(self);
ZahlArten.Transaction := self.Transaction;
ZahlArten.SQL.Text := 'SELECT * FROM ZAHLART';
ZahlArten.Open;
ZSHelper := TZSHelper.create(self, Stammdaten, Transaction);
OpenTransaction;
ZahlArten.Open;
CSVSchema(1, '');
CSVFile.Open;
i := 0;
setlength(Result, 0);
while not aQuery.Eof do
begin
LogMessage('TobFib-Export: Kreditor "' + aQuery.FieldByName('LT_MATCH').AsString + '"');
LogMessage('Zahlungsschlüssel suchen oder neu anlegen...');
ZS := ZSHelper.getZS(self, aQuery.FieldByName('LT_ZNETTOTAGE').AsInteger,
aQuery.FieldByName('LT_ZSKONTOTAGE').AsInteger,
aQuery.FieldByName('LT_ZSKONTO').AsFloat);
LogMessage('Zahlungsschlüssel gelesen...');
Firmenname := '';
if aQuery.FieldByName('LT_FIRMA').AsString <> '' then Firmenname := aQuery.FieldByName('LT_FIRMA').AsString
else Firmenname := aQuery.FieldByName('LT_VNAME').AsString + ' ' + aQuery.FieldByName('LT_NAME').AsString;
if Firmenname = '' then Firmenname := aQuery.FieldByName('LT_MATCH').AsString;
CSVFile.Append;
CSVFile.FieldByName('SATZART').AsString := 'K';
CSVFile.FieldByName('KONTO').AsInteger := aQuery.FieldByName('LT_KREDITOR').AsInteger;
CSVFile.FieldByName('BEZEICHNUNG').AsString := Firmenname;
CSVFile.FieldByName('STRASSE').AsString := Trim(aQuery.FieldByName('LT_STRASSE').AsString + ' ' + aQuery.FieldByName('LT_HAUSNUMMER').asString);
CSVFile.FieldByName('LAND').AsString := aQuery.FieldByName('LT_LAND').AsString;
CSVFile.FieldByName('PLZ').AsString := aQuery.FieldByName('LT_PLZ').AsString;
CSVFile.FieldByName('ORT').AsString := aQuery.FieldByName('LT_ORT').AsString;
CSVFile.FieldByName('TELEFON1').AsString := aQuery.FieldByName('LT_TEL').AsString;
CSVFile.FieldByName('EMAIL').AsString := aQuery.FieldByName('LT_MAIL').AsString;
CSVFile.FieldByName('TELEFAX').AsString := aQuery.FieldByName('LT_FAX').AsString;
CSVFile.FieldByName('USTID').AsString := aQuery.FieldByName('LT_USTID').AsString;
if ZahlArten.Locate('ZA_ID', aQuery.FieldByName('LT_ZAHLART').AsInteger, []) and
(Zahlarten.FieldByName('ZA_BANKV').AsString = 'T') then
CSVFile.FieldByName('ZAHLUNGSART').AsString := 'A'
else
CSVFile.FieldByName('ZAHLUNGSART').AsString := 'N';
CSVFile.FieldByName('BLZ1').AsString := aQuery.FieldByName('LT_BLZ').AsString;
CSVFile.FieldByName('BANKKONTO1').AsString := aQuery.FieldByName('LT_KTONR').AsString;
CSVFile.FieldByName('BANKNAME1').AsString := aQuery.FieldByName('LT_BANK').AsString;
CSVFile.Fields[15].Asfloat := 0;
CSVFile.Fields[16].AsString := aQuery.FieldByName('LT_NR').AsString;
CSVFile.Fields[17].AsString := aQuery.FieldByName('LT_ANREDE').AsString;
CSVFile.Fields[18].AsString := Firmenname;
CSVFile.Fields[19].AsString := aQuery.FieldByName('UT_KONTONR').AsString;
CSVFile.Fields[20].AsInteger := ZS.getID;
if aQuery.FieldByName('LT_EUAUSLAND').AsString = 'T' then
begin
CSVFile.Fields[21].AsInteger := 2;
CSVFile.Fields[22].AsString := 'EU-AUSLAND';
end
else if aQuery.FieldByName('LT_AUSLAND').AsString = 'T' then
begin
CSVFile.Fields[21].AsInteger := 3;
CSVFile.Fields[22].AsString := 'DRITTLAND';
end
else
begin
CSVFile.Fields[21].AsInteger := 1;
CSVFile.Fields[22].AsString := 'INLAND';
end;
CSVFile.CheckBrowseMode;
setlength(Result, i + 1);
Result[i] := aQuery.FieldByName('LT_ID').AsInteger;
FreeAndNil(ZS);
inc(i);
aQuery.Next;
end;
CSVFile.Close;
ZahlArten.Close;
ZahlArten.Free;
ZSHelper.Free;
CommitTransaction;
ZahlungsschluesselAbgleichen;
LogMessage('TobFib-Export (Kreditoren) abgeschlossen');
end;
procedure TAddison.NeuerOP(OP: RwOP; OpNummerSchreiben : boolean);
var WriteQuery : TIBQuery;
KUQuery : TIBQuery;
begin
WriteQuery := TIBQuery.Create(self);
WriteQuery.Transaction := self.Transaction;
KUQuery := TIBQuery.Create(self);
KUQuery.Transaction := self.Transaction;
KUQuery.SQL.Text := 'SELECT KU_NR, KU_DEBITOR, KU_MATCH, KU_ID ' +
'FROM KUNDEN WHERE ' +
'KU_DEBITOR = :Debitor ';
WriteQuery.SQL.Text := 'INSERT INTO MAHNLAUF ( ' +
'ML_ID, ML_KUNR, ML_OPNR, ML_DEBITOR, ML_MATCH, ML_MAHNLAUF, ' +
'ML_REDATUM, ML_MAHNBETRAG, ML_ZTAGENETTO, ' +
'ML_ZTAGESKONTO, ML_ZSKONTO, ML_LETZTEMDATUM, ' +
'ML_FAELLIGDATUM, ML_RENUMMER, ML_ERSTEMDATUM, ' +
'ML_GELEISTET, ML_KU_ID ' +
') VALUES ( ' +
'GEN_ID(MAHNLAUF_ID, 1), :Kundennr, :OPNr, :Debitornr, :Match, 0, ' +
':Redatum, :Betrag, :TageNetto, ' +
':TageSkonto, :Skonto, :LetzteMDatum, ' +
':Faelligdatum, :Beleg, :Erstemdatum, ' +
':Geleistet, :KuId ' +
')';
if (StrToInt(OP.m_Konto) < 70000) then
begin
KUQuery.ParamByName('Debitor').AsInteger := StrtoInt(trim(OP.m_Konto));
KUQuery.Open;
if (KUQuery.FieldByName('KU_NR').AsInteger <> 0) then
begin
LogMessage('ML: Neuer Datensatz: ' + OP.m_BelegNr + ' | ' + OP.m_BelegNr2);
WriteQuery.ParamByName('Kundennr').AsInteger := KUQuery.FieldByName('KU_NR').AsInteger;
if OPNummerSchreiben then
WriteQuery.ParamByName('OpNr').AsInteger := StrToInt(Trim(OP.m_BelegNr2))
else
WriteQuery.ParamByName('OpNr').AsInteger := 0;
WriteQuery.ParamByName('Debitornr').AsInteger := KUQuery.FieldByName('KU_DEBITOR').AsInteger;
WriteQuery.ParamByName('Match').AsString := KUQuery.FieldByName('KU_MATCH').AsString;
WriteQuery.ParamByName('KuId').AsInteger := KUQuery.FieldByName('Ku_Id').AsInteger;
WriteQuery.ParamByName('ReDatum').AsDateTime := OP.m_BelegDatum;
WriteQuery.ParamByName('Betrag').AsFloat := OP.m_Betrag;
WriteQuery.ParamByName('TageNetto').AsInteger := Trunc(op.m_BelegDatum - Op.m_NettoFaelligkeit);
WriteQuery.ParamByName('TageSkonto').AsInteger := Trunc(op.m_BelegDatum - Op.m_SkontoFaelligkeitStufe[0]);
WriteQuery.ParamByName('Skonto').AsFloat := op.m_SkontoProzentSatzStufe[0];
WriteQuery.ParamByName('LetzteMDatum').AsDateTime := OP.m_BelegDatum;
WriteQuery.ParamByName('Faelligdatum').AsDateTime := OP.m_NettoFaelligkeit;
WriteQuery.ParamByName('Beleg').asString := OP.m_BelegNr;
WriteQuery.ParamByName('ErsteMDatum').AsDateTime := OP.m_BelegDatum;
WriteQuery.ParamByName('Geleistet').AsFloat := 0;
Writequery.ExecSQL;
end;
KUQuery.Close;
end;
FreeAndNil(KUQuery);
FreeAndNil(WriteQuery);
end;
function TAddison.OPGesehen(aMLID: integer): boolean;
var x : integer;
begin
for x := 0 to High(OPSGesehen) do
if OPSGesehen[x] = aMLID then
begin
Result := true;
exit;
end;
SetLength(OPSGesehen, High(OPSGesehen) + 2);
OPSGesehen[High(OPSGesehen)] := aMLID;
Result := false;
end;
procedure TAddison.OPListenAbgleich;
var OPSuche : RwOPSuche;
OP : RwOP;
Pos : integer;
ReadQuery : TIBQuery;
x : integer;
OpSchreiben : boolean;
OPNummerOk : boolean;
begin
LogMessage('TobFib: OP-Listen-Abgleich');
if not Connect then
begin
LogMessage('OP-Abgleich: Keine Verbindung zur Datenbank!');
exit;
end;
if Wirtschaftsjahr = nil then
begin
LogMessage('OP-Abgleich: Keine Verbindung zur Datenbank!');
exit;
end;
ReadQuery := TIBQuery.Create(self);
Readquery.Transaction := Transaction;
OpenTransaction;
Readquery.SQL.Clear;
ReadQuery.SQL.Add('SELECT ML_ID, ML_OPNR, ML_DEBITOR, ' +
'ML_RENUMMER, ML_REDATUM, ML_MAHNBETRAG ' +
'FROM MAHNLAUF ' +
'ORDER BY ML_DEBITOR ');
Readquery.Open;
Pos := 0;
KeineOPSGesehen;
OPSuche := Wirtschaftsjahr.CreateOPSuche;
OPSuche.SearchBelegNr('*', '*');
if OPSuche.Count = 0 then beep;
OP := OPSuche.GetAt[Pos];
while OP <> nil do
begin
OPSchreiben := true;
OpNummerOK := (trim(OP.m_BelegNr2) <> '');
try
if OPNummerOK then
OPNummerOK := (StrtoInt(trim(OP.m_BelegNr2)) <> 0);
except
OPNummerOK := false;
end;
if OPNummerOK then
begin
if ReadQuery.Locate('ML_OPNR', trim(OP.m_BelegNr2), []) then
begin
// OP Vorhanden!
OPGesehen(ReadQuery.FieldByName('ML_ID').AsInteger);
OPSchreiben := false;
end;
end
else
begin
// 1. - Debitor vergleichen
// 2. - Beträge vergleichen
// 3. - Nachschauen ob ein ML-Eintrag schon mit
// anderem OP verglichen wurde
// 4. - wenn ein Unterschied, dann ist der OP noch nicht
// in die ML-Tabelle aufgenommen
if ReadQuery.Locate('ML_DEBITOR', trim(OP.m_Konto), []) then
begin
// Debitor gefunden, jetzt nach richtigem OP suchen!
while (not ReadQuery.Eof) and
(ReadQuery.FieldByName('ML_DEBITOR').AsString = OP.m_Konto) do
begin
// wenn Beträge übereinstimmen nehmen wir an dieser
// ML-Eintrag sei der vorgehaltene OP
if BetragGleich(ReadQuery.FieldByName('ML_MAHNBETRAG').AsFloat, OP.m_Betrag) then
begin
// Jetzt prüfen, ob wir ausgesuchten ML-Eintrag NICHT
// schon für einen anderen OP gehalten haben
if not OPGesehen(ReadQuery.FieldByName('ML_ID').AsInteger) then
begin
// Wir haben diesen ML-Eintrag noch nicht mit einem anderen
// OP in Verbindung gebracht.
// Daher ist der ausgesuchte ML-Eintrag tatsächlich unser OP
// und braucht nicht in die ML-Tabelle geschrieben werden.
OPSchreiben := false;
break;
end;
end;
ReadQuery.Next;
end;
end;
end;
if OPSchreiben then NeuerOP(OP, OPNummerOK);
if (pos > 0) and ((pos mod 20) = 0) then
LogMessage('ML: ' + IntToStr(pos) + ' Datensätze kontrolliert');
OP := nil;
inc(pos);
OP := OPSuche.GetAt[pos];
end;
ReadQuery.First;
while not ReadQuery.Eof do
begin
OPSchreiben := false;
if (ReadQuery.FieldByName('ML_OPNR').AsString <> '') and
(ReadQuery.FieldByName('ML_OPNR').AsInteger <> 0) then
begin
OP := nil;
// wir haben einen OP-Schlüssel, also suchen wir den Schlüssel
OPSuche.SearchBelegNr2(ReadQuery.FieldByName('ML_DEBITOR').AsString, IntToStr(ReadQuery.FieldByName('ML_OPNR').AsInteger));
OP := OPSuche.GetAt[0];
if OP = nil then OPSchreiben := true;
end
else
begin
// OP ohne OPNummer suchen, diese Methode sollte möglichst präzise sein!!!
if ReadQuery.FieldByName('ML_RENUMMER').AsString <> '' then
begin
OPSuche.SearchBelegNr(ReadQuery.FieldByName('ML_DEBITOR').AsString, ReadQuery.FieldByName('ML_RENUMMER').AsString)
end
else
begin
OPSuche.SearchBelegNr(ReadQuery.FieldByName('ML_DEBITOR').AsString,'*');
end;
OPSchreiben := true;
for x := 0 to OPSuche.Count - 1 do
begin
OP := nil;
OP := OPSuche.GetAt[x];
// Vergleichen der kriterien, die übrig sind
// ACHTUNG! Wertdifferenzen zwischen GS-Fibu und Addison kippen
// offene, agemahnte OPs in der ML-Tabelle, daher großzügiges
// Delta bei Betragsvergleich!
if SameValue(ReadQuery.FieldByName('ML_MAHNBETRAG').AsFloat, OP.m_Betrag, 1) then
begin
OPSchreiben := false;
break;
end;
end;
end;
if OPSchreiben then
OPLoeschen(ReadQuery.FieldByName('ML_ID').AsInteger);
if (ReadQuery.RecNo > 0) and ((ReadQuery.RecNo mod 20) = 0) then
LogMessage('ML: ' + IntToStr(ReadQuery.RecNo) + ' Datensätze kontrolliert');
ReadQuery.Next;
OP := nil;
end;
CommitTransaction;
FreeAndNil(ReadQuery);
LogMessage('TobFib: OP-Listen-Abgleich abgeschlossen.');
Disconnect;
end;
procedure TAddison.OPLoeschen(ID: integer);
var WriteQuery : TIBQuery;
begin
WriteQuery := TIBQuery.Create(self);
WriteQuery.Transaction := self.Transaction;
WriteQuery.SQL.Text := 'DELETE FROM MAHNLAUF WHERE ML_ID = :ID';
WriteQuery.ParamByName('ID').AsInteger := ID;
WriteQuery.ExecSQL;
LogMessage('ML: Datensatz ' + IntToStr(ID) + ' gelöscht.');
end;
function TAddison.PostenExport(aQuery: TIBQuery) : DataArray;
var FibuListe : TFibuExportListe;
Vorgang : TVorgang;
x : integer;
ZahlArten : TIBQuery;
i : integer;
OpNr : integer;
ZSHelper : TZSHelper;
ZS : TZahlungsschluessel;
begin
if aQuery.Eof then exit;
setLength(Result, 0);
i := 0;
LogMessage('TobFib-Export: Posten');
ZSHelper := TZSHelper.create(self, Stammdaten, Transaction);
OpenTransaction;
ZahlArten := TIBQuery.Create(self);
ZahlArten.Transaction := self.Transaction;
ZahlArten.SQL.Text := 'SELECT * FROM ZAHLART';
ZahlArten.Open;
CSVSchema(2, '');
CSVFile.Open;
FibuListe := TFibuExportListe.Create;
while not aQuery.Eof do
begin
// Vorgang := TVorgang.Create(aQuery.FieldByName('VO_ID').AsInteger, Transaction.DefaultDatabase, true, Stammdaten, self);
Vorgang := TVorgang.Create(self, aQuery.FieldByName('VO_ID').AsInteger, Stammdaten, Transaction);
LogMessage(Vorgang.getNummer);
ZS := ZSHelper.getZS(self, Vorgang.getNettoTage, Vorgang.getSkontoTage, Vorgang.getSkonto);
OPNr := OPNummer;
FibuListe.Clear;
Vorgang.FillFibuList(FibuListe);
if FibuListe.Count = 1 then
begin
CSVFile.Append;
LogMessage(Vorgang.getNummer);
CSVFile.FieldByName('SATZART').AsString := 'B';
CSVFile.FieldByName('KONTO').AsInteger := Vorgang.Empfaenger.getPersonenkonto;
CSVFile.FieldByName('GEGENKONTO').AsInteger := TFibuexportItem(FibuListe.Items[0]).getKonto.getKontoNr;
CSVFile.FieldByName('BUCHUNGSDATUM').AsString := FormatDateTime('mmyyyy', Vorgang.getDatum);
if Vorgang.getArt in [cGutschrift, cEingangsrechnung, cStornierung, cPreisdifferenz] then
CSVFile.FieldByName('BETRAG').AsFloat := -1 * TFibuexportItem(FibuListe.Items[0]).getBetragBrutto
else
CSVFile.FieldByName('BETRAG').AsFloat := TFibuexportItem(FibuListe.Items[0]).getBetragBrutto;
CSVFile.FieldByName('BUCHUNGSTEXT').AsString := 'OP: ' + Vorgang.getNummer + ' / ' + Vorgang.Empfaenger.getMatch;
CSVFile.FieldByName('BELEGDATUM').AsDateTime := Vorgang.getDatum;
if Vorgang.getSkontoTage <> 0 then
CSVFile.FieldByName('VALUTADATUM').AsDateTime := Vorgang.getDatum + Vorgang.getSkontoTage
else if Vorgang.getNettoTage <> 0 then
CSVFile.FieldByName('VALUTADATUM').AsDateTime := Vorgang.getDatum + Vorgang.getNettoTage
else
CSVFile.FieldByName('VALUTADATUM').AsDateTime := Vorgang.getDatum;
CSVFile.FieldByName('NETTODATUM').AsDateTime := Vorgang.getDatum + Vorgang.getNettoTage;
CSVFile.FieldByName('BELEGNR').AsString := Vorgang.getNummer;
CSVFile.FieldByName('BELEGNR2').AsString := IntToStr(OPNr);
if ZahlArten.Locate('ZA_ID', Vorgang.getZahlungsartID, []) and
(Zahlarten.FieldByName('ZA_BANKV').AsString = 'T') then
CSVFile.FieldByName('ABW_ZAHLUNGSART').AsString := 'A'
else
CSVFile.FieldByName('ABW_ZAHLUNGSART').AsString := 'N';
CSVFile.FieldByName('BUCHSTEUERSL').AsString := IntToStr(TFibuexportItem(FibuListe.Items[0]).getKonto.getPDXKennung);
CSVFile.FieldByName('ABW_ZAHLSL').AsInteger := ZS.getID;
CSVFile.CheckBrowseMode;
end
else if FibuListe.Count > 1 then
begin
// Aufteilungsbuchung - Aufteilungsbetrag
CSVFile.Append;
LogMessage(Vorgang.getNummer + ' - Aufteilungsbuchung');
CSVFile.FieldByName('SATZART').AsString := 'B';
CSVFile.FieldByName('KONTO').AsInteger := Vorgang.Empfaenger.getPersonenkonto;
CSVFile.FieldByName('GEGENKONTO').AsInteger := 0;
CSVFile.FieldByName('BUCHUNGSDATUM').AsString := FormatDateTime('mmyyyy', Vorgang.getDatum);
if Vorgang.getArt in [cGutschrift, cEingangsrechnung, cStornierung, cPreisdifferenz] then
CSVFile.FieldByName('BETRAG').AsFloat := -1 * Vorgang.getBruttosumme
else
CSVFile.FieldByName('BETRAG').AsFloat := Vorgang.getBruttosumme;
CSVFile.FieldByName('BUCHUNGSTEXT').AsString := 'OP: ' + Vorgang.getNummer + ' / ' + Vorgang.Empfaenger.getMatch;
CSVFile.FieldByName('BELEGDATUM').AsDateTime := Vorgang.getDatum;
if Vorgang.getSkontoTage <> 0 then
CSVFile.FieldByName('VALUTADATUM').AsDateTime := Vorgang.getDatum + Vorgang.getSkontoTage
else if Vorgang.getNettoTage <> 0 then
CSVFile.FieldByName('VALUTADATUM').AsDateTime := Vorgang.getDatum + Vorgang.getNettoTage
else
CSVFile.FieldByName('VALUTADATUM').AsDateTime := Vorgang.getDatum;
CSVFile.FieldByName('NETTODATUM').AsDateTime := Vorgang.getDatum + Vorgang.getNettoTage;
CSVFile.FieldByName('BELEGNR').AsString := Vorgang.getNummer;
CSVFile.FieldByName('BELEGNR2').AsString := IntToStr(OPNr);
if ZahlArten.Locate('ZA_ID', Vorgang.getZahlungsartID, []) and
(Zahlarten.FieldByName('ZA_BANKV').AsString = 'T') then
CSVFile.FieldByName('ABW_ZAHLUNGSART').AsString := 'A'
else
CSVFile.FieldByName('ABW_ZAHLUNGSART').AsString := 'N';
CSVFile.FieldByName('ABW_ZAHLSL').AsInteger := ZS.getID;
CSVFile.FieldByName('BUCHSTEUERSL').AsString := '';
CSVFile.CheckBrowseMode;
for x := 0 to FibuListe.Count - 1 do
begin
// Aufteilungsbuchung - Aufteilungs-Gegenbuchung
CSVFile.Append;
LogMessage(Vorgang.getNummer + ' - Aufteilungs-Gegenbuchung ' + IntToStr(x));
CSVFile.FieldByName('SATZART').AsString := 'B';
CSVFile.FieldByName('KONTO').AsInteger := TFibuexportItem(FibuListe.Items[x]).getKonto.getKontoNr;
CSVFile.FieldByName('GEGENKONTO').AsInteger := Vorgang.Empfaenger.getPersonenkonto;
CSVFile.FieldByName('BUCHUNGSDATUM').AsString := FormatDateTime('mmyyyy', Vorgang.getDatum);
if Vorgang.getArt in [cGutschrift, cEingangsrechnung, cStornierung, cPreisdifferenz] then
CSVFile.FieldByName('BETRAG').AsFloat := TFibuexportItem(FibuListe.Items[x]).getBetragBrutto
else
CSVFile.FieldByName('BETRAG').AsFloat := -1 * TFibuexportItem(FibuListe.Items[x]).getBetragBrutto;
CSVFile.FieldByName('BUCHUNGSTEXT').AsString := 'OP: ' + Vorgang.getNummer + ' / ' + Vorgang.Empfaenger.getMatch;
CSVFile.FieldByName('BELEGDATUM').AsDateTime := Vorgang.getDatum;
if Vorgang.getSkontoTage <> 0 then
CSVFile.FieldByName('VALUTADATUM').AsDateTime := Vorgang.getDatum + Vorgang.getSkontoTage
else if Vorgang.getNettoTage <> 0 then
CSVFile.FieldByName('VALUTADATUM').AsDateTime := Vorgang.getDatum + Vorgang.getNettoTage
else
CSVFile.FieldByName('VALUTADATUM').AsDateTime := Vorgang.getDatum;
CSVFile.FieldByName('NETTODATUM').AsDateTime := Vorgang.getDatum + Vorgang.getNettoTage;
CSVFile.FieldByName('BELEGNR').AsString := Vorgang.getNummer;
CSVFile.FieldByName('BELEGNR2').AsString := IntToStr(OPNr);
if ZahlArten.Locate('ZA_ID', Vorgang.getZahlungsartID, []) and
(Zahlarten.FieldByName('ZA_BANKV').AsString = 'T') then
CSVFile.FieldByName('ABW_ZAHLUNGSART').AsString := 'A'
else
CSVFile.FieldByName('ABW_ZAHLUNGSART').AsString := 'N';
CSVFile.FieldByName('ABW_ZAHLSL').AsInteger := ZS.getID;
CSVFile.FieldByName('BUCHSTEUERSL').AsString := IntToStr(TFibuexportItem(FibuListe.Items[x]).getKonto.getPDXKennung);
CSVFile.CheckBrowseMode;
end;
end;
setlength(Result, i + 1);
Result[i] := Vorgang.getID;
FreeAndNil(ZS);
//Vorgang.setFibuStapel(true);
//Vorgang.setExportDatum(date);
//Vorgang.saveToDB;
Vorgang.Free;
inc(i);
aQuery.Next;
end;
FibuListe.Free;
ZahlArten.Close;
ZahlArten.Free;
ZSHelper.Free;
CSVFile.Close;
CommitTransaction;
ZahlungsschluesselAbgleichen;
LogMessage('TobFib Export (Posten) abgeschlossen');
end;
procedure TAddison.PostenReImport;
var OPSuche : RwOPSuche;
OP : RwOP;
IBQVorgaenge : TIBQuery;
Vorgang : TVorgang;
Nummern : TStrings;
begin
LogMessage('TobFib Posten Reimport');
if not Connect then
begin
LogMessage('Posten Re-Import: Keine Verbindung zur Datenbank');
exit;
end;
Nummern := TStringList.Create;
CSVSchema(2, '');
CSVFile.Open;
while not CSVFile.Eof do
begin
if CSVFile.FieldByName('SATZART').AsString = 'B' then
Nummern.Add(CSVFile.FieldByName('BELEGNR').AsString);
CSVFile.Next;
end;
CSVFile.Close;
IBQVorgaenge := TIBQuery.Create(self);
IBQVorgaenge.Transaction := self.Transaction;
OpenTransaction;
with IBQVorgaenge do
begin
SQL.Clear;
SQL.Add('SELECT VO_ID ' +
'FROM VORGANG ' +
'WHERE ' +
'(VO_ART IN ("4","5","18","10","12")) ' +
'AND ' +
'(VO_STATUS <> 3) ' +
'AND ' +
'(VO_FIBUSTAPEL = "T") ' +
'AND ' +
'(VO_DELETE != "T") ' +
'ORDER BY VO_NUMMER');
Open;
while not Eof do
begin
// Vorgang := TVorgang.Create(FieldByName('VO_ID').AsInteger, self.Transaction.DefaultDatabase, true, Stammdaten, self);
Vorgang := TVorgang.Create(self, FieldByName('VO_ID').AsInteger, Stammdaten, Transaction);
// 1. OP noch in der Datei?
if (Nummern.Count = 0) or
(Nummern.IndexOf(Vorgang.getNummer) = -1) then
begin
// nicht vorhanden in Exportdatei
// 2. OP noch in Addison?
OP := nil;
OPSuche := Wirtschaftsjahr.CreateOPSuche;
if Vorgang.Empfaenger.isOfType(cKunde) then
OPSuche.SearchBelegNr(IntToStr(TKunden(Vorgang.Empfaenger).getDebitor), Vorgang.getNummer)
else
OPSuche.SearchBelegNr(IntToStr(TLieferant(Vorgang.Empfaenger).getKreditor), Vorgang.getNummer);
OP := OPSuche.GetAt[0];
if op = nil then
begin
// nicht Vorhanden in Addison
// Vorgang ist erledigt
LogMessage(' Vorgang erledigt: ' + Vorgang.getNummer);
Vorgang.setStatus(cErledigt);
Vorgang.saveToDB;
Vorgang.HistorienDatensatzAnlegen(12, 'Vorgang wurde erledigt. (Server: Fibu - PostenReImport).');
end
else
begin
LogMessage(' Vorgang noch offen: ' + Vorgang.getNummer);
end;
end;
Vorgang.Free;
if IBQVorgaenge.RecNo mod 10 = 0 then
LogMessage(IntToStr(IBQVorgaenge.RecNo) + ' Datensätze überprüft');
Next;
end;
Close;
Free;
end;
CommitTransaction;
Nummern.Free;
OP := nil;
Disconnect;
end;
procedure TAddison.ZahlungsschluesselAbgleichen;
var ReadQuery : TIBQuery;
WriteQuery : TIBQuery;
begin
LogMessage('Zahlungsschluessel aktualisieren');
ReadQuery := TIBQUery.Create(self);
WriteQuery := TIBQUery.Create(self);
with WriteQuery do
begin
Transaction := self.Transaction;
SQL.Text := 'UPDATE ZAHLUNGSSCHLUESSEL SET ZS_PDXUPDATE = "F" WHERE ZS_ID = :Id';
end;
OpenTransaction;
CSVSchema(3, '');
CSVFile.Open;
with ReadQuery do
begin
Transaction := self.Transaction;
SQL.Text := 'SELECT * FROM ZAHLUNGSSCHLUESSEL WHERE ' +
'ZS_PDXUPDATE = "T" AND ZS_DELETE <> "T" ';
Open;
CSVFile.First;
while not EOF do
begin
LogMessage(ReadQuery.FieldByName('ZS_BEZEICHNUNG').AsString);
CSVFile.Insert;
CSVFile.FieldByName('SATZART').AsString := 'Z';
CSVFile.FieldByName('ZAHLSL').AsInteger := ReadQuery.FieldByName('ZS_ID').AsInteger;
CSVFile.FieldByName('ZAHLSL_NAME').AsString := ReadQuery.FieldByName('ZS_BEZEICHNUNG').AsString;
CSVFile.FieldByName('ZAHLSL_TAGE1').AsInteger := ReadQuery.FieldByName('ZS_SKONTOTAGE').AsInteger;
CSVFile.FieldByName('ZAHLSL_PERCENT1').AsFloat := ReadQuery.FieldByName('ZS_SKONTO').AsFloat;
CSVFile.FieldByName('ZAHLSL_NETTOTAGE').AsInteger := readQuery.FieldByName('ZS_NETTOTAGE').AsInteger;
CSVFile.CheckBrowseMode;
WriteQuery.ParamByName('ID').AsInteger := ReadQuery.FieldByName('ZS_ID').AsInteger;
WriteQuery.ExecSQL;
Next;
end;
Close;
end;
CSVFile.Close;
CommitTransaction;
WriteQuery.Free;
ReadQuery.Free;
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 uCodeProvider;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, uFeedback, uConst;
type
TCodeChangeType = (cctAdd, cctRemove, cctChange);
TCodeChangeEvent = procedure(ChangeType: TCodeChangeType; Namn: string) of object;
TCodeProvider = class
private
FOnCodeChange: TCodeChangeEvent;
FActive: Boolean;
FSearchPath: TStringList;
FWatched: TStringList;
procedure SetActive(const Value: Boolean);
protected
Feedback : IEldeanFeedback;
LoadedCount : integer;
procedure HookChanges; virtual; abstract;
procedure UnhookChanges; virtual; abstract;
procedure AddChangeWatch(AName: string);
public
constructor Create(AFeedback : IEldeanFeedback = nil);
destructor Destroy; override;
function LocateFile(const AName: string): string; virtual; abstract;
function LoadStream(const AName: string): TStream; virtual; abstract;
procedure SaveStream(const AName: string; AStream: TStream); virtual; abstract;
procedure AddSearchPath(APath: string);
property Active: Boolean read FActive write SetActive;
property SearchPath: TStringList read FSearchPath;
property OnCodeChange: TCodeChangeEvent read FOnCodeChange write FOnCodeChange;
end;
implementation
procedure TCodeProvider.AddChangeWatch(AName: string);
begin
FWatched.Add(AName);
if Active then HookChanges; // Attach 'again' to recieve changes to this file.
end;
procedure TCodeProvider.AddSearchPath(APath: string);
begin
if APath<>'' then
begin
if APath[Length(APath)] <> PathDelim then
APath := APath + PathDelim;
if FSearchPath.IndexOf(APath) < 0 then
FSearchPath.Add(APath);
end;
end;
constructor TCodeProvider.Create(AFeedback : IEldeanFeedback = nil);
begin
inherited Create;
FSearchPath := TStringList.Create;
FWatched := TStringList.Create;
if Feedback=nil then
Self.Feedback := NilFeedback
else
Self.Feedback := AFeedback;
end;
destructor TCodeProvider.Destroy;
begin
Feedback.Message( IntToStr(LoadedCount) + rsFilesRead_ending_lc);
FreeAndNil(FSearchPath);
FreeAndNil(FWatched);
inherited;
end;
procedure TCodeProvider.SetActive(const Value: Boolean);
begin
if (not Active) and Value then
begin
// Activate source change hook
HookChanges;
FActive := Value;
end
else if Active and (not Value) then
begin
// Deactivate source change hook
UnhookChanges;
FActive := Value;
end;
end;
end.
|
unit uNCreateXML;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls,
Vcl.FileCtrl, ShlwApi, Xml.XMLIntf, Xml.XMLDoc, Vcl.ExtCtrls;
type
TUpdateFile = class(TInterfacedObject)
private
FFileName: string;
FFileURL: string;
FChkType: string;
FUpdateType: string;
FVersion: string;
FModyDatetime: string;
FFileSize: string;
FDeskFile: string;
FDeskDir: string;
function isBinFile(FileName: string): Boolean;
public
constructor Create;
property ChkType: string read FChkType write FChkType;
property DeskFile: string read FDeskFile write FDeskFile;
property DeskDir: string read FDeskDir write FDeskDir;
property FileName: string read FFileName write FFileName;
property FileSize: string read FFileSize write FFileSize;
property FileURL: string read FFileURL write FFileURL;
property ModyDatetime: string read FModyDatetime write FModyDatetime;
property UpdateType: string read FUpdateType write FUpdateType;
property Version: string read FVersion write FVersion;
end;
TFrmNCreateXML = class(TForm)
Label2: TLabel;
Labellbl1: TLabel;
edtDir: TEdit;
btnOpen: TButton;
grp1: TGroupBox;
grp2: TGroupBox;
Labellbl2: TLabel;
Labellbl3: TLabel;
btnSave: TButton;
grp3: TGroupBox;
rbNo: TRadioButton;
rbCreate: TRadioButton;
rbDate: TRadioButton;
rbSize: TRadioButton;
rbVer: TRadioButton;
edtFileName: TEdit;
edtURL: TEdit;
grp4: TGroupBox;
rbCopy: TRadioButton;
rbExecute: TRadioButton;
grp5: TGroupBox;
Labellbl7: TLabel;
edtSize: TEdit;
Labellbl5: TLabel;
edtVer: TEdit;
Label1: TLabel;
edtdeskDir: TEdit;
Labellbl8: TLabel;
edtDesk: TEdit;
Labellbl6: TLabel;
edtMody: TEdit;
btnUpdateXML: TButton;
btn1: TButton;
dlgOpen1: TOpenDialog;
ListBox1: TListBox;
btn2: TButton;
btnBatchSave: TButton;
btnAddDir: TButton;
lbledtFilter: TLabeledEdit;
procedure btnOpenClick(Sender: TObject);
procedure btn1Click(Sender: TObject);
procedure edtDirChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ListBox1Click(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure btnUpdateXMLClick(Sender: TObject);
procedure btn2Click(Sender: TObject);
procedure btnAddDirClick(Sender: TObject);
procedure btnBatchSaveClick(Sender: TObject);
private
function GetRelativePath(const Path, AFile: string): string;
procedure CreateXMLNode(root: IXmlNode; uFile: TUpdateFile);
public
{ Public declarations }
end;
const
binFiles: array[0..3] of string = ('.EXE', '.DLL', '.BPL', '.OCX');
procedure GetChildFileList(AStrings: TStrings; ASourFile, FileName: string); // 查找子目录
var
FrmNCreateXML: TFrmNCreateXML;
implementation
{$R *.dfm}
uses
uFileAction, System.IOUtils, System.StrUtils;
procedure GetFileInfo(temFile: TUpdateFile; FileName: string);
var
FileAction: TFileAction;
AFormatSettings: TFormatSettings;
begin
FileAction := TFileAction.Create(FileName);
AFormatSettings := TFormatSettings.Create();
AFormatSettings.DateSeparator := '-';
AFormatSettings.ShortDateFormat := 'yyyy-MM-dd';
try
if temFile.isBinFile(FileName) then
begin
temFile.ChkType := '1';
temFile.Version := FileAction.GetFileVersionAsText
end
else
begin
temFile.Version := '0.0.0.0';
temFile.ChkType := '4';
end;
temFile.FileSize := inttostr(FileAction.GetFileSize);
temFile.ModyDatetime := DatetimeTostr(FileAction.GetFileDate, AFormatSettings);
finally
freeandnil(FileAction);
end;
end;
procedure TFrmNCreateXML.btn1Click(Sender: TObject);
var
oldpath, sfile, newfile: string;
i, icount: Integer;
UFile: TUpdateFile;
begin
oldpath := edtDir.Text;
if oldpath = '' then
exit;
if dlgOpen1.InitialDir = '' then
dlgOpen1.InitialDir := oldpath;
if dlgOpen1.Execute(self.Handle) then
begin
icount := dlgopen1.Files.Count;
for i := 0 to icount - 1 do
begin
sfile := dlgopen1.Files[i];
newfile := GetRelativePath(oldpath, sfile);
if ((newfile[1] = '.') and (newfile[2] = '\')) then
Delete(newfile, 1, 2);
if listbox1.Items.IndexOf(newfile) = -1 then
begin
UFile := TUpdateFile.Create;
UFile.FileURL := newfile;
UFile.FileName := ExtractFileName(sfile);
UFile.DeskFile := ExtractFileName(sfile);
GetFileInfo(UFile, sfile);
Listbox1.AddItem(newfile, UFile);
end;
end;
end;
end;
procedure TFrmNCreateXML.btn2Click(Sender: TObject);
begin
if ListBox1.Count = 0 then
exit;
if ListBox1.ItemIndex = -1 then
exit;
ListBox1.DeleteSelected;
end;
procedure TFrmNCreateXML.btnBatchSaveClick(Sender: TObject);
var
upFile: TUpdateFile;
index: Integer;
begin
for index := 0 to ListBox1.Items.Count - 1 do
begin
if ListBox1.Selected[index] then
begin
upFile := TUpdateFile(ListBox1.Items.Objects[index]);
if rbSize.Checked then
upFile.ChkType := '3'
else if rbVer.Checked then
upFile.ChkType := '1'
else if rbDate.Checked then
upFile.ChkType := '2'
else if rbCreate.Checked then
upFile.ChkType := '4'
else if rbNo.Checked then
upFile.ChkType := '0';
if rbCopy.Checked then
upFile.UpdateType := '0'
else if rbExecute.Checked then
upFile.UpdateType := '1';
//upFile.FileSize := edtSize.Text;
//upFile.Version := edtVer.Text;
//upFile.DeskFile := edtDesk.Text;
upFile.DeskDir := edtdeskDir.Text;
//upFile.ModyDatetime := edtMody.Text;
end;
end;
end;
procedure TFrmNCreateXML.btnOpenClick(Sender: TObject);
var
temp: string;
begin
temp := edtDir.Text;
if SelectDirectory('请指定文件夹', '', temp) then
begin
edtDir.Text := IncludeTrailingPathDelimiter(temp);
end;
end;
procedure TFrmNCreateXML.btnSaveClick(Sender: TObject);
var
upFile: TUpdateFile;
begin
if ListBox1.ItemIndex > -1 then
begin
upFile := TUpdateFile(ListBox1.Items.Objects[ListBox1.ItemIndex]);
if rbSize.Checked then
upFile.ChkType := '3'
else if rbVer.Checked then
upFile.ChkType := '1'
else if rbDate.Checked then
upFile.ChkType := '2'
else if rbCreate.Checked then
upFile.ChkType := '4'
else if rbNo.Checked then
upFile.ChkType := '0';
if rbCopy.Checked then
upFile.UpdateType := '0'
else if rbExecute.Checked then
upFile.UpdateType := '1';
upFile.FileSize := edtSize.Text;
upFile.Version := edtVer.Text;
upFile.DeskFile := edtDesk.Text;
upFile.DeskDir := edtdeskDir.Text;
upFile.ModyDatetime := edtMody.Text;
end;
end;
procedure GetChildFileList(AStrings: TStrings; ASourFile, FileName: string); // 查找子目录
// AStrings存放路径, ASourceFile要查找的目录,FileName搜索的文件类型 若指定类型,则'*.jpg'or '*.png'
var
sour_path, sour_file: string;
TmpList: TStringList;
FileRec, subFileRec: TSearchrec;
i: Integer;
begin
if copy(ASourFile, Length(ASourFile), 1) <> '\' then
sour_path := IncludeTrailingPathDelimiter(Trim(ASourFile)) // 在路径后面加上反斜杠
else
sour_path := trim(ASourFile);
sour_file := FileName;
if not TDirectory.Exists(sour_path) then
begin
AStrings.Clear;
exit;
end;
TmpList := TStringList.Create;
TmpList.Clear;
if FindFirst(sour_path + '*.*', faAnyfile, FileRec) = 0 then
repeat
if ((FileRec.Attr and faDirectory) <> 0) then
begin
if ((FileRec.Name <> '.') and (FileRec.Name <> '..')) then
GetChildFileList(AStrings, sour_path + FileRec.Name + '\', sour_file);
end;
until FindNext(FileRec) <> 0;
FindClose(FileRec);
if FindFirst(sour_path + FileName, faAnyfile, subFileRec) = 0 then
repeat
if ((subFileRec.Attr and faDirectory) = 0) then
TmpList.Add(sour_path + subFileRec.Name);
until FindNext(subFileRec) <> 0;
FindClose(subFileRec);
for i := 0 to TmpList.Count - 1 do
AStrings.Add(TmpList.Strings[i]);
TmpList.Free;
end;
procedure TFrmNCreateXML.btnAddDirClick(Sender: TObject);
var
temp, newFile: string;
tempFiles: TStrings;
i: Integer;
UFile: TUpdateFile;
begin
temp := edtDir.Text;
if SelectDirectory('请指定文件夹', '', temp) then
begin
temp := IncludeTrailingPathDelimiter(temp);
tempFiles := TStringList.Create;
try
GetChildFileList(tempFiles, temp, '*.*');
for i := 0 to tempFiles.Count - 1 do
begin
newfile := GetRelativePath(edtDir.Text, tempFiles[i]);
if ((newfile[1] = '.') and (newfile[2] = '\')) then
Delete(newfile, 1, 2);
if listbox1.Items.IndexOf(newfile) = -1 then
begin
UFile := TUpdateFile.Create;
UFile.FileURL := newfile;
UFile.FileName := ExtractFileName(tempFiles[i]);
UFile.DeskFile := ExtractFileName(tempFiles[i]);
UFile.DeskDir := StringReplace(UFile.FileURL, lbledtFilter.Text, '', [rfIgnoreCase]);
UFile.DeskDir := StringReplace(UFile.DeskDir, UFile.FileName, '', [rfIgnoreCase]);
if Length(UFile.DeskDir) > 0 then
begin
UFile.DeskDir := LeftStr(UFile.DeskDir, Length(UFile.DeskDir) - 1);
end;
GetFileInfo(UFile, tempFiles[i]);
Listbox1.AddItem(newfile, UFile);
end;
end;
finally
FreeAndNil(tempFiles);
end;
end;
end;
procedure TFrmNCreateXML.btnUpdateXMLClick(Sender: TObject);
var
SavePathFileName: string;
ixd: IXmlDocument;
root: IXmlNode;
i: Integer;
begin
if ListBox1.Items.Count <= 0 then
Exit;
SavePathFileName := edtDir.Text + 'UpdateList.xml';
ixd := NewXmlDocument();
root := ixd.AddChild('UpdateLists');
for i := 0 to ListBox1.Items.Count - 1 do
begin
CreateXMLNode(root, TUpdateFIle(ListBox1.Items.Objects[i]));
end;
ixd.SaveToFile(SavePathFileName);
ShowMessage('XML文件生成成功,谢谢!');
end;
procedure TFrmNCreateXML.CreateXMLNode(root: IXmlNode; uFile: TUpdateFile);
var
node1: IXmlNode;
node2: IXmlNode;
node3: IXmlNode;
node4: IXmlNode;
node5: IXmlNode;
node6: IXmlNode;
node7: IXmlNode;
node8: IXmlNode;
node9: IXmlNode;
begin
node1 := root.AddChild('UpdateFile');
node2 := node1.AddChild('FileName');
node2.Text := uFile.FileName;
node3 := node1.AddChild('FileURL');
node3.Text := uFile.FileURL;
node4 := node1.AddChild('chkType');
node4.Text := uFile.ChkType;
node5 := node1.AddChild('UpdateType');
node5.Text := uFile.UpdateType;
node6 := node1.AddChild('Version');
node6.Text := uFile.Version;
node7 := node1.AddChild('DateTime');
node7.Text := uFile.ModyDatetime;
node8 := node1.AddChild('FileSize');
node8.Text := uFile.FileSize;
node9 := node1.AddChild('DeskFile');
if uFile.DeskDir <> '' then
node9.Text := uFile.DeskDir + '\' + uFile.DeskFile
else
node9.Text := uFile.DeskFile;
end;
procedure TFrmNCreateXML.edtDirChange(Sender: TObject);
begin
// ListBox1.Clear;
dlgOpen1.InitialDir := edtDir.Text;
end;
procedure TFrmNCreateXML.FormCreate(Sender: TObject);
begin
ListBox1.Items.Clear;
end;
function TFrmNCreateXML.GetRelativePath(const Path, AFile: string): string;
function GetAttr(IsDir: Boolean): DWORD;
begin
if IsDir then
Result := FILE_ATTRIBUTE_DIRECTORY
else
Result := FILE_ATTRIBUTE_NORMAL;
end;
var
p: array[0..MAX_PATH] of Char;
begin
PathRelativePathTo(p, PChar(Path), GetAttr(False), PChar(AFile), GetAttr(True));
Result := StrPas(p);
end;
procedure TFrmNCreateXML.ListBox1Click(Sender: TObject);
var
upFile: TUpdateFile;
begin
if ListBox1.Count = 0 then
exit;
if ListBox1.ItemIndex = -1 then
exit;
upFile := TUpdateFile(ListBox1.Items.Objects[ListBox1.ItemIndex]);
edtFileName.Text := upFile.FileName;
if upFile.FileName <> '' then
begin
edtURL.Text := upFile.FileURL;
if upFile.UpdateType = '0' then
rbCopy.Checked := True
else if upFile.UpdateType = '1' then
rbExecute.Checked := True;
if upFile.ChkType = '0' then
rbNo.Checked := True
else if upFile.ChkType = '1' then
rbVer.Checked := True
else if upFile.ChkType = '2' then
rbDate.Checked := True
else if upFile.ChkType = '3' then
rbSize.Checked := True
else if upFile.ChkType = '4' then
begin
rbCreate.Checked := True;
//rbExecute.Checked := True;
end;
edtSize.Text := upFile.FileSize;
edtVer.Text := upFile.Version;
edtMody.Text := upFile.ModyDatetime;
edtDesk.Text := upFile.DeskFile;
edtdeskDir.Text := upFile.DeskDir;
end;
end;
{ TUpdateFile }
constructor TUpdateFile.Create;
begin
inherited;
FChkType := '1';
FUpdateType := '0';
FVersion := '1';
FDeskDir := '';
end;
function TUpdateFile.isBinFile(FileName: string): Boolean;
var
i: Integer;
begin
Result := false;
// TODO -cMM: TUpdateFile.isBinFile default body inserted
for I := 0 to Length(binFiles) do
begin
if UpperCase(TPath.GetExtension(FileName)) = binFiles[i] then
begin
Result := True;
exit;
end;
end;
end;
end.
|
(*
* FPG EDIT : Edit FPG file from DIV2, FENIX and CDIV
*
*
* 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 uSort;
interface
type
Table_Sort = record
nSort, nLink : LongWord;
end;
function SortCompare( item1, item2 : Pointer ): integer;
implementation
function SortCompare( item1, item2 : Pointer ): integer;
begin
if Table_Sort(item1^).nSort < Table_Sort(item2^).nSort then
result := -1
else if Table_Sort(item1^).nSort > Table_Sort(item2^).nSort then
result := 1
else
result := 0;
end;
(*procedure Sort(var A: array of Table_Sort);
var
I, J : LongWord;
T : Table_Sort;
begin
for I := Low(A) to High(A) - 1 do
for J := High(A) downto I + 1 do
if A[I].nSort > A[J].nSort then
begin
T := A[I];
A[I] := A[J];
A[J] := T;
end;
end;*)
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, DSPack, StdCtrls, Buttons, DirectShow9, DSUtil, Math,
ComCtrls;
type
THSV = record // hue saturation value (HSV)
Hue , Sat , Val : Double;
end;
type
TForm1 = class(TForm)
VideoWindow1: TVideoWindow;
Image1: TImage;
ButtonBlue: TButton;
ButtonOrange: TButton;
ButtonToBiner: TButton;
ComboBox1: TComboBox;
FilterGraph1: TFilterGraph;
SampleGrabber1: TSampleGrabber;
Filter1: TFilter;
TimerConvert: TTimer;
LabelHMin: TLabel;
LabelSMin: TLabel;
LabelVMin: TLabel;
LabelHMax: TLabel;
LabelSMax: TLabel;
LabelVMax: TLabel;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
Label10: TLabel;
Label11: TLabel;
Label12: TLabel;
ScrollBarSMin: TScrollBar;
ScrollBarVMin: TScrollBar;
ScrollBarSMax: TScrollBar;
ScrollBarVMax: TScrollBar;
ButtonYellow: TButton;
ButtonGreen: TButton;
ButtonRed: TButton;
ScrollBarHMin: TScrollBar;
ScrollBarHMax: TScrollBar;
TimerBiner: TTimer;
ButtonToRGB: TButton;
procedure FormCreate(Sender: TObject);
procedure UpdateValue;
procedure ComboBox1Change(Sender: TObject);
procedure TimerConvertTimer(Sender: TObject);
procedure ButtonBlueClick(Sender: TObject);
procedure ScrollBarSMinChange(Sender: TObject);
procedure ScrollBarSMaxChange(Sender: TObject);
procedure ScrollBarVMinChange(Sender: TObject);
procedure ScrollBarVMaxChange(Sender: TObject);
procedure ButtonYellowClick(Sender: TObject);
procedure ButtonOrangeClick(Sender: TObject);
procedure ButtonGreenClick(Sender: TObject);
procedure ScrollBarHMinChange(Sender: TObject);
procedure ScrollBarHMaxChange(Sender: TObject);
procedure ButtonRedClick(Sender: TObject);
procedure TimerBinerTimer(Sender: TObject);
procedure ButtonToBinerClick(Sender: TObject);
procedure ButtonToRGBClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
CapEnum: TSysDevEnum;
maxH,maxS,maxV,minH,minS,minV: Integer;
implementation
{$R *.dfm}
function RGB2HSV(R,G,B: Byte): THSV;
var
Min_,Max_,Delta : Double;
H,S,V: Double;
begin
H:=0.0;
Min_ := Min(Min(R,G),B);
Max_ := Max(Max(R,G),B);
Delta:= (Max_-Min_);
V:= Max_;
if (Max_<> 0.0 ) then
S:=255.0* Delta/Max_
else
S:=0.0;
if (S<>0.0) then
begin
if R= Max_ then
H:= (G-B)/Delta
else
if G= Max_ then
H:= 2.0+(B-R)/Delta
else
if B= Max_ then
H:= 4.0+(R-G)/Delta
end
else
H:= -1.0;
H:= H*60;
if H<0.0 then
H:= H+360.0;
with Result Do
begin
Hue := H;;
Sat := S*100/255;
Val := V*100/255;
end;
end;
procedure RGB2Biner(Image1: TImage);
var
PC,PH: PByteArray;
R,G,B,K: byte;
x,y: Integer;
Hue,Sat,Val: Double;
Result: THSV;
begin
for y:=0 to Image1.Picture.Bitmap.Height-1 do
begin
PC := Image1.Picture.Bitmap.ScanLine[y];
PH := Image1.Picture.Bitmap.ScanLine[y];
for x:=0 to Image1.Picture.Bitmap.Width-1 do
begin
R := PC[3*x+2];
G := PC[3*x+1];
B := PC[3*x];
Result := RGB2HSV(R,G,B);
Hue := Result.Hue;
Sat := Result.Sat;
Val := Result.Val;
if (Hue>=minH) and (Hue<=maxH) and (Sat>=minS) and (Sat<=maxS) and (Val>=minV) and (Val<=maxV) then
K := 255
else
K := 0;
PH[3*x+2]:= K;
PH[3*x+1]:= K;
PH[3*x]:= K;
end;
end;
end;
procedure RGB2THRES(var Image1: Timage);
var
PC,PH: PByteArray;
R,G,B: byte;
x,y: Integer;
Hue,Sat,Val: Double;
Result: THSV;
begin
for y:=0 to Image1.Picture.Bitmap.Height-1 do
begin
PC := Image1.Picture.Bitmap.ScanLine[y];
PH := Image1.Picture.Bitmap.ScanLine[y];
for x:=0 to Image1.Picture.Bitmap.Width-1 do
begin
R := PC[3*x+2];
G := PC[3*x+1];
B := PC[3*x];
Result := RGB2HSV(R,G,B);
Hue := Result.Hue;
Sat := Result.Sat;
Val := Result.Val;
if (Hue>=minH) and (Hue<=maxH) and (Sat>=minS) and (Sat<=maxS) and (Val>=minV) and (Val<=maxV) then
begin
PH[3*x+2]:= R;
PH[3*x+1]:= G;
PH[3*x]:= B;
end
else
begin
PH[3*x+2]:= 0;
PH[3*x+1]:= 0;
PH[3*x]:= 0;
end;
end;
end;
end;
procedure TForm1.UpdateValue;
begin
LabelHMin.Caption := IntToStr(minH);
LabelHMax.Caption := IntToStr(maxH);
LabelSMin.Caption := IntToStr(minS);
LabelSMax.Caption := IntToStr(maxS);
LabelVMin.Caption := IntToStr(minV);
LabelVMax.Caption := IntToStr(maxV);
ScrollBarHMin.Position := minH;
ScrollBarHMax.Position := maxH;
ScrollBarSMin.Position := minS;
ScrollBarSMax.Position := maxS;
ScrollBarVMin.Position := minV;
ScrollBarVMax.Position := maxV;
end;
procedure TForm1.FormCreate(Sender: TObject);
var
i : integer;
begin
CapEnum := TSysDevEnum.Create(CLSID_VideoInputDeviceCategory);
for i :=0 to CapEnum.CountFilters -1 do
begin
combobox1.Items.add(CapEnum.Filters[i].FriendlyName);
end;
end;
procedure TForm1.ComboBox1Change(Sender: TObject);
begin
FilterGraph1.ClearGraph;
FilterGraph1.Active:= false;
Filter1.BaseFilter.Moniker:= CapEnum.GetMoniker(Combobox1.ItemIndex);
FilterGraph1.Active :=True;
with FilterGraph1 as ICaptureGraphBuilder2 do
RenderStream(@PIN_CATEGORY_PREVIEW, nil,Filter1 as IBaseFilter, SampleGrabber1 as IBaseFilter,
VideoWindow1 as IBaseFilter);
FilterGraph1.Play;
TimerConvert.Enabled := True;
end;
procedure TForm1.TimerConvertTimer(Sender: TObject);
begin
SampleGrabber1.GetBitmap(Image1.Picture.Bitmap);
RGB2THRES(Image1);
end;
procedure TForm1.TimerBinerTimer(Sender: TObject);
begin
SampleGrabber1.GetBitmap(Image1.Picture.Bitmap);
RGB2Biner(Image1);
end;
procedure TForm1.ScrollBarHMinChange(Sender: TObject);
begin
minH := ScrollBarHMin.Position;
LabelHMin.Caption := IntToStr(minH);
end;
procedure TForm1.ScrollBarHMaxChange(Sender: TObject);
begin
maxH := ScrollBarHMax.Position;
LabelHMax.Caption := IntToStr(maxH);
end;
procedure TForm1.ScrollBarSMinChange(Sender: TObject);
begin
minS := ScrollBarSMin.Position;
LabelSMin.Caption := IntToStr(minS);
end;
procedure TForm1.ScrollBarSMaxChange(Sender: TObject);
begin
maxS := ScrollBarSMax.Position;
LabelSMax.Caption := IntToStr(maxS);
end;
procedure TForm1.ScrollBarVMinChange(Sender: TObject);
begin
minV := ScrollBarVMin.Position;
LabelVMin.Caption := IntToStr(minV);
end;
procedure TForm1.ScrollBarVMaxChange(Sender: TObject);
begin
maxV := ScrollBarVMax.Position;
LabelVMax.Caption := IntToStr(maxV);
end;
procedure TForm1.ButtonBlueClick(Sender: TObject);
begin
minH := 190; maxH := 255;
minS := 0; maxS := 100;
minV := 0; maxV := 100;
UpdateValue();
end;
procedure TForm1.ButtonYellowClick(Sender: TObject);
begin
minH := 30; maxH := 60;
minS := 0; maxS := 100;
minV := 0; maxV := 100;
UpdateValue();
end;
procedure TForm1.ButtonOrangeClick(Sender: TObject);
begin
minH := 0; maxH := 30;
minS := 0; maxS := 100;
minV := 0; maxV := 100;
UpdateValue();
end;
procedure TForm1.ButtonGreenClick(Sender: TObject);
begin
minH := 70; maxH := 120;
minS := 0; maxS := 100;
minV := 0; maxV := 100;
UpdateValue();
end;
procedure TForm1.ButtonRedClick(Sender: TObject);
begin
minH := 320; maxH := 360;
minS := 0; maxS := 100;
minV := 0; maxV := 100;
UpdateValue();
end;
procedure TForm1.ButtonToBinerClick(Sender: TObject);
begin
TimerConvert.Enabled := False;
TimerBiner.Enabled := True;
end;
procedure TForm1.ButtonToRGBClick(Sender: TObject);
begin
TimerConvert.Enabled := True;
TimerBiner.Enabled := False;
end;
end.
|
{Delphi 16/256-Color PCX Reader Support objects}
{copyright 1998, MDRUtils(tm) Mark D. Rafn}
// **************************************************************************
// NOTE: Range Checking is turned off due to Borland zero length array types
// procedures needing this directive are labeled if you want to isolate
// **************************************************************************
{$R-}
unit Pcxctrl;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls,
Forms, Dialogs;
type
{use this structure instead of TRGBTriple.}
{TRGBTriple is reversed, confusing with read results}
TPCXTriple = record
r, g, b: byte;
end;
TPCXColors256 = array[0..255] of TPCXTriple;
TPcxColors16 = array[0..15] of TPCXTriple;
TPCXHeader = record
Maker: byte;
Version: byte;
Encoding: byte;
Bpp: byte;
Xmn, Ymn: smallint;
Xmx, Ymx: smallint;
HRes, VRes: smallint;
CMap: TPcxColors16;
Reserved: byte;
NPlanes: byte;
NBpl: smallint;
PalType: smallint;
end;
type
TPCXColorModel = (Color16, Color256);
TPCXBitmap = class(TBitmap)
private
FHeader: TPCXHeader;
FColorModel: TPCXColorModel;
function ConvertStream(Stream: TStream): TMemoryStream;
public
constructor Create; override;
destructor Destroy; override;
procedure LoadFromStream(Stream: TStream); override;
end;
TDecoder = class
ImageHeight, ImageWidth: longint;
ImageBytesPerLine: longint;
Buffer: array[0..1023] of byte;
BufferIndex: integer;
bmiSize: word;
ImageOffset: integer;
protected
procedure Decode_Row(Stream: TStream; RL: integer; ScanLine: TMemoryStream);
function MakeBMIInfo(Stream: TStream): PBitmapInfo; virtual;
function MakeBMInfoHeader: TBitMapInfoHeader; virtual; abstract;
procedure MakeBMIColors(Stream: TStream; BitmapInfo: PBitmapInfo);
virtual; abstract;
function GetPaletteSize: integer; virtual; abstract;
function MakeBMFileHeader(Bmi: PBitmapInfo): TBitmapFileHeader;
function GetImageSize: longint;
public
constructor Create;
destructor Destroy; override;
function DecodeStream(AStream: TStream; AHeader: TPCXHeader;
AImage: TMemoryStream): integer; virtual; abstract;
end;
TDecoder256 = class(TDecoder)
protected
function MakeBMInfoHeader: TBitMapInfoHeader; override;
procedure MakeBMIColors(Stream: TStream; BitmapInfo: PBitmapInfo); override;
function GetPaletteSize: integer; override;
public
function DecodeStream(AStream: TStream; PCXHeader: TPCXHeader;
AImage: TMemoryStream): integer; override;
end;
TDecoder16 = class(TDecoder)
protected
function MakeBMInfoHeader: TBitMapInfoHeader; override;
procedure MakeBMIColors(Stream: TStream; BitmapInfo: PBitmapInfo); override;
function GetPaletteSize: integer; override;
public
function DecodeStream(AStream: TStream; PCXHeader: TPCXHeader;
AImage: TMemoryStream): integer; override;
end;
EPCXPropertyError = class(Exception);
implementation
function AlignDouble(Size: longint): longint;
begin
AlignDouble := (Size + 3) div 4 * 4;
end;
procedure InvalidGraphic(Str: string); near;
begin
raise EInvalidGraphic.Create(Str);
end;
{ TPCXBitmap }
constructor TPCXBitmap.Create;
begin
inherited Create;
end;
destructor TPCXBitmap.Destroy;
begin
inherited Destroy;
end;
function TPCXBitmap.ConvertStream(Stream: TStream): TMemoryStream;
var
Image: TMemoryStream;
Decoder: TDecoder;
ImageHeight, ImageWidth: integer;
begin
Result := nil;
Stream.Position := 0;
Stream.Read(FHeader, Sizeof(FHeader));
with FHeader do
begin
if Maker <> $0A then
Exit;
if (Bpp = 8) and (NPlanes = 1) then
FColorModel := Color256
else if (Bpp = 1) and (NPlanes = 4) then
FColorModel := Color16
else
Exit;
ImageHeight := longint(Ymx) - longint(Ymn) + 1;
ImageWidth := longint(Xmx) - longint(Xmn) + 1;
end;
Image := TMemoryStream.Create;
if FColorModel = Color16 then
Decoder := TDecoder16.Create
else
Decoder := TDecoder256.Create;
try
if Decoder.DecodeStream(Stream, FHeader, Image) = 1 then
begin
Image.Position := 0;
Result := Image;
end
else
Image.Free;
finally
Decoder.Free;
end;
end;
procedure TPCXBitmap.LoadFromStream(Stream: TStream);
var
Image: TMemoryStream;
begin
Image := ConvertStream(Stream);
if Image = nil then
inherited LoadFromStream(Stream)
else
inherited LoadFromStream(Image);
end;
{ TDecoder }
constructor TDecoder.Create;
begin
inherited Create;
BufferIndex := 0;
FillChar(Buffer, SizeOf(Buffer), 0);
ImageBytesPerLine := -1;
end;
destructor TDecoder.Destroy;
begin
inherited Destroy;
end;
{ Decode an entire scanline into S regardless of image type }
procedure TDecoder.Decode_Row(Stream: TStream; RL: integer; ScanLine: TMemoryStream);
var
i, ByteCount, Repeats, RunLength: integer;
b: byte;
ReadCount, Count: longint;
begin
ByteCount := 0;
RunLength := RL;
ReadCount := SizeOf(Buffer);
Count := Stream.Size - Stream.Position;
if BufferIndex = 0 then
if Count > ReadCount then
Stream.ReadBuffer(Buffer, ReadCount)
else
Stream.ReadBuffer(Buffer, Count);
while (ByteCount < RunLength) do
begin
if BufferIndex = 1024 then
begin
if Count > ReadCount then
Stream.ReadBuffer(Buffer, ReadCount)
else
Stream.ReadBuffer(Buffer, Count);
BufferIndex := 0;
end;
b := Buffer[BufferIndex];
BufferIndex := BufferIndex + 1;
if (b >= 192) then
begin
Repeats := b - 192;
if BufferIndex = 1024 then
begin
if Count > ReadCount then
Stream.ReadBuffer(Buffer, ReadCount)
else
Stream.ReadBuffer(Buffer, Count);
BufferIndex := 0;
end;
b := Buffer[BufferIndex];
BufferIndex := BufferIndex + 1;
for i := 1 to Repeats do
begin
ScanLine.Write(b, 1);
ByteCount := ByteCount + 1;
end;
end
else
begin
ScanLine.Write(b, 1);
ByteCount := ByteCount + 1;
end;
end;
end;
function TDecoder.MakeBMFileHeader(Bmi: PBitmapInfo): TBitmapFileHeader;
var
Bmf: TBitmapFileHeader;
begin
with Bmf do
begin
bfType := $4D42;
bfSize := SizeOf(Bmf) + BmiSize + GetImageSize;
bfReserved1 := 0;
bfReserved2 := 0;
bfOffBits := SizeOf(Bmf) + BmiSize;
end;
Result := Bmf;
end;
function TDecoder.MakeBMIInfo(Stream: TStream): PBitmapInfo;
var
Bmi: PBitmapInfo;
begin
Bmi := nil;
bmiSize := SizeOf(TBitmapInfoHeader) + GetPaletteSize;
try
GetMem(Bmi, bmiSize);
Bmi^.bmiHeader := MakeBMInfoHeader;
MakeBMIColors(Stream, Bmi);
except
raise;
end;
Result := Bmi;
end;
function TDecoder.GetImageSize: longint;
begin
Result := ImageBytesPerLine * ImageHeight;
end;
{ TDecoder256 }
function TDecoder256.DecodeStream(AStream: TStream; PCXHeader: TPCXHeader;
AImage: TMemoryStream): integer;
var
Bmi: PBitMapInfo;
Bmf: TBitmapFileHeader;
Image: TMemoryStream;
Scanline: TMemoryStream;
LineCount: integer;
Size: longint;
begin
Result := 0;
Image := AImage;
with PCXHeader do
begin
ImageHeight := longint(Ymx) - longint(Ymn) + 1;
ImageWidth := longint(Xmx) - longint(Xmn) + 1;
ImageBytesPerLine := AlignDouble(longint(NBpl));
end;
Bmi := MakeBMIInfo(AStream);
Bmf := MakeBMFileHeader(Bmi);
Size := SizeOf(Bmf) + BmiSize + GetImageSize;
ImageOffset := Bmf.bfOffBits;
try
Image.SetSize(Size);
except
raise;
Exit;
end;
try
Image.Write(Bmf, SizeOf(Bmf));
Image.Write(Bmi^, BmiSize);
except
raise;
Exit;
end;
ScanLine := TMemoryStream.Create;
try
ScanLine.SetSize(ImageBytesPerLine);
except
raise;
Exit;
end;
AStream.Seek(128, 0);
for LineCount := (ImageHeight - 1) downto 0 do
begin
ScanLine.Position := 0;
//Decode_Row(AStream, ImageBytesPerLine, ScanLine); this was wrong 12.20.97
Decode_Row(AStream, pcxheader.nbpl, ScanLine);
try
Image.Position := longint(ImageOffset) + (longint(LineCount) *
longint(ImageBytesPerLine));
Image.Write(Scanline.Memory^, ImageBytesPerLine);
except
raise;
Exit;
end;
end;
ScanLine.Free;
Result := 1;
end;
function TDecoder256.MakeBMInfoHeader: TBitMapInfoHeader;
var
BitMapInfoHeader: TBitMapInfoHeader;
begin
with BitmapInfoHeader do
begin
biSize := Sizeof(TBitmapInfoHeader);
biWidth := ImageWidth;
biHeight := ImageHeight;
biPlanes := 1;
biBitCount := 8;
biCompression := 0;
biSizeImage := GetImageSize;
biXPelsperMeter := 0;
biYPelsperMeter := 0;
biClrUsed := 256;
biClrImportant := 0;
end;
Result := BitmapInfoHeader;
end;
{R-}
procedure TDecoder256.MakeBMIColors(Stream: TStream; BitmapInfo: PBitmapInfo);
var
b: byte;
i: integer;
PCXColors: TPCXColors256;
begin
Stream.Position := Stream.Size - 769;
Stream.Read(b, 1);
if b = $0C then
begin
Stream.Read(PCXColors, SizeOf(PCXColors));
for i := 0 to 255 do
with BitMapInfo^.bmiColors[i], PCXColors[i] do
begin
rgbRed := r;
rgbGreen := g;
rgbBlue := b;
rgbReserved := 0;
end;
end;
end;
{R+}
function TDecoder256.GetPaletteSize: integer;
begin
Result := Sizeof(TRGBQuad) * 256;
end;
{ TDecoder16 }
function TDecoder16.MakeBMInfoHeader: TBitMapInfoHeader;
var
BitMapInfoHeader: TBitMapInfoHeader;
begin
with BitmapInfoHeader do
begin
biSize := Sizeof(TBitmapInfoHeader);
biWidth := ImageWidth;
biHeight := ImageHeight;
biPlanes := 1;
biBitCount := 4;
biCompression := 0;
biSizeImage := GetImagesize;
biXPelsperMeter := 0;
biYPelsperMeter := 0;
biClrUsed := 0;
biClrImportant := 0;
end;
Result := BitmapInfoHeader;
end;
{R-}
procedure TDecoder16.MakeBMIColors(Stream: TStream; BitmapInfo: PBitmapInfo);
var
i: integer;
Header: TPCXHeader;
begin
Stream.Position := 0;
Stream.Read(Header, Sizeof(Header));
for i := 0 to 15 do
with BitMapInfo^.bmiColors[i], Header.CMap[i] do
begin
rgbRed := r;
rgbGreen := g;
rgbBlue := b;
rgbReserved := 0;
end;
end;
{R+}
function TDecoder16.GetPaletteSize: integer;
begin
Result := Sizeof(TRGBQuad) * 16;
end;
function TDecoder16.DecodeStream(AStream: TStream; PCXHeader: TPCXHeader;
AImage: TMemoryStream): integer;
var
Bmi: PBitMapInfo;
Bmf: TBitmapFileHeader;
Image: TMemoryStream;
Scanline: TMemoryStream;
ConvertedLine: TMemoryStream;
LineCount: integer;
Size: longint;
{not real elegant, but it works for now...}
procedure ConvertLine;
var
b1, b2, b3, b4, NewByte: byte;
i, j: integer;
aNewBytes: array[0..3] of byte;
begin
ConvertedLine.Seek(0, 0);
for i := 0 to (PCXHeader.Nbpl - 1) do
begin
ScanLine.Seek(i, 0);
Scanline.Read(b1, 1);
ScanLine.Seek(i + PCXHeader.Nbpl, 0);
Scanline.Read(b2, 1);
ScanLine.Seek(i + (PCXHeader.Nbpl * 2), 0);
Scanline.Read(b3, 1);
ScanLine.Seek(i + (PCXHeader.Nbpl * 3), 0);
Scanline.Read(b4, 1);
for j := 0 to 3 do
begin
NewByte := 0;
NewByte :=
((b1 and $80) shr 3) or ((b2 and $80) shr 2) or
((b3 and $80) shr 1) or (b4 and $80) or
((b1 and $40) shr 6) or ((b2 and $40) shr 5) or
((b3 and $40) shr 4) or ((b4 and $40) shr 3);
b1 := b1 shl 2;
b2 := b2 shl 2;
b3 := b3 shl 2;
b4 := b4 shl 2;
aNewBytes[j] := NewByte;
end;
ConvertedLine.Write(aNewBytes, 4);
end;
end;
begin
Result := 0;
Image := AImage;
with PCXHeader do
begin
ImageHeight := longint(Ymx) - longint(Ymn) + 1;
ImageWidth := longint(Xmx) - longint(Xmn) + 1;
ImageBytesPerLine := AlignDouble(NBpl * NPlanes);
end;
Bmi := MakeBMIInfo(AStream);
Bmf := MakeBMFileHeader(Bmi);
Size := SizeOf(Bmf) + BmiSize + (ImageBytesPerLine * ImageHeight);
ImageOffset := Bmf.bfOffBits;
try
Image.SetSize(Size);
except
raise;
Exit;
end;
try
Image.Write(Bmf, SizeOf(Bmf));
Image.Write(Bmi^, BmiSize);
except
raise;
Exit;
end;
ScanLine := TMemoryStream.Create;
ConvertedLine := TMemoryStream.Create;
try
ScanLine.SetSize(ImageBytesPerLine);
ConvertedLine.SetSize(ImageBytesPerLine);
except
raise;
Exit;
end;
AStream.Seek(128, 0);
for LineCount := (ImageHeight - 1) downto 0 do
begin
ScanLine.Position := 0;
// originally changed the next line to read the same as the 256 decoder
// but a problem reported by a user showed the orginal code was correct
// so I changed it back. The following line is original code and displays
// correctly. 02.10.98
Decode_Row(AStream, ImageBytesPerLine, ScanLine);
ConvertLine;
try
Image.Position := longint(ImageOffset) + (longint(LineCount) *
longint(ImageBytesPerLine));
Image.Write(ConvertedLine.Memory^, ImageBytesPerLine);
except
raise;
ScanLine.Free;
ConvertedLine.Free;
Exit;
end;
end;
ScanLine.Free;
ConvertedLine.Free;
Result := 1;
end;
{$R+}
end.
|
unit VendaRepository;
interface
uses BasicRepository, System.Generics.Collections, System.SysUtils, CartaoVO,
PessoaVO, VendaVO, VendaItemVO, VendaRecebimentoVO, ContaReceberVO,
CartaoRecebimentoVO, EsperaItemVO, EsperaVO;
type
TVendaRepository = class(TBasicRepository)
class function getCartao: TList<TCartaoVO>;
class function getPessoa(Campo,Valor: string): TList<TPessoaVO>;
class procedure VendaInserir(Venda: TVendaVO);
class procedure VendaInserirItens(idOfVenda: Integer; Itens: TList<TVendaItemVO>);
class procedure VendaInserirRecebimentos(idOfVenda: Integer; Itens: TList<TVendaRecebimentoVO>);
class procedure VendaInserirContaReceber(idOfVenda: Integer; ContaReceber: TContaReceberVO);
class procedure VendaInserirCartaoRecebimentos(idOfVenda: Integer; Itens: TList<TCartaoRecebimentoVO>);
class function getVendaEmEspera: TList<TEsperaVO>;
class function getVendaEmEsperaById(idOfEspera: Integer): TEsperaVO;
class procedure VendaEmEsperaInserir(Espera: TEsperaVO);
class procedure VendaEmEsperaItensInserir(idOfEspera: Integer; Lst: TList<TEsperaItemVO>);
class procedure VendaEmEspraAlterar(Espera: TEsperaVO);
class procedure VendaToNFCE(idOfVenda: Integer);
class procedure ReimprimirNF(idOfVenda: Integer);
class procedure VendaItensToDesconto(idOfVenda: Integer);
class procedure AdicionarPessoaAVenda(idOfVenda, idOfCliente: Integer);
class function getValorFiscal: Double;
end;
implementation
{ TVendaRepository }
class procedure TVendaRepository.AdicionarPessoaAVenda(idOfVenda,
idOfCliente: Integer);
var
Filtro: string;
begin
Filtro:= 'update venda set id_pessoa = ' + IntToStr(idOfCliente) +
' where id = ' + IntToStr(idOfVenda);
ComandoSQL(Filtro);
end;
class function TVendaRepository.getCartao: TList<TCartaoVO>;
var
Filtro: string;
begin
Filtro:= 'ID > 0 order by nome';
Result:= Consultar<TCartaoVO>(False,Filtro);
end;
class function TVendaRepository.getPessoa(Campo,
Valor: string): TList<TPessoaVO>;
var
Filtro: string;
begin
Filtro:= Campo + ' LIKE ' + QuotedStr('%' + Valor + '%') + ' ORDER BY ' + Campo;
Result:= Consultar<TPessoaVO>(False,Filtro);
end;
class function TVendaRepository.getValorFiscal: Double;
begin
with GetQuery do
begin
CommandText:= 'SELECT COALESCE(SUM(V.TOTAL),0) TOTAL FROM VENDA V WHERE V.FISCAL = '+ QuotedStr('S') + ' AND CAST(V.LANCAMENTO AS DATE) = CURRENT_DATE';
Open;
Result:= FieldByName('TOTAL').AsFloat;
Free;
end;
end;
class function TVendaRepository.getVendaEmEspera: TList<TEsperaVO>;
var
Filtro: string;
begin
Filtro:= 'ATENDIDO = ' + QuotedStr('N') + ' ORDER BY LANCAMENTO ';
Result:= Consultar<TEsperaVO>(False,Filtro);
end;
class function TVendaRepository.getVendaEmEsperaById(
idOfEspera: Integer): TEsperaVO;
var
Filtro: string;
begin
Filtro:= 'ID = ' + IntToStr(idOfEspera);
Result:= ConsultarUmObjeto<TEsperaVO>(Filtro,True);
end;
class procedure TVendaRepository.ReimprimirNF(idOfVenda: Integer);
var
Filtro: string;
begin
Filtro:= 'UPDATE IMPRIMIR P SET P.IMPRESSO = ' + QuotedStr('N') +
' WHERE P.ID_TIPO_IMPRESSAO = 7 AND P.IDOFTABLE = ' + IntToStr(idOfVenda);
ComandoSQL(Filtro);
end;
class procedure TVendaRepository.VendaEmEsperaInserir(Espera: TEsperaVO);
begin
Espera.Id:= Inserir(Espera);
end;
class procedure TVendaRepository.VendaEmEsperaItensInserir(
idOfEspera: Integer; Lst: TList<TEsperaItemVO>);
var
I: Integer;
begin
for I := 0 to Pred(Lst.Count) do
begin
Lst.Items[i].IdEspera:= idOfEspera;
Inserir(Lst.Items[i]);
end;
end;
class procedure TVendaRepository.VendaEmEspraAlterar(Espera: TEsperaVO);
begin
Alterar(Espera);
end;
class procedure TVendaRepository.VendaInserir(Venda: TVendaVO);
begin
Venda.Id:= Inserir(Venda);
end;
class procedure TVendaRepository.VendaInserirCartaoRecebimentos(
idOfVenda: Integer; Itens: TList<TCartaoRecebimentoVO>);
var
I: Integer;
begin
for I := 0 to Pred(Itens.Count) do
begin
Itens.Items[i].IdVenda:= idOfVenda;
Inserir(Itens.Items[i]);
end;
end;
class procedure TVendaRepository.VendaInserirContaReceber(idOfVenda: Integer;
ContaReceber: TContaReceberVO);
var
Comando: string;
begin
ContaReceber.IdVenda:= idOfVenda;
ContaReceber.Id:= Inserir(ContaReceber);
ContaReceber.Parcela.IdContaReceber:= ContaReceber.Id;
Inserir(ContaReceber.Parcela);
Comando:= 'execute procedure conta_recebertoabater('+ IntToStr(ContaReceber.IdPessoa) + ')';
ComandoSQL(Comando);
end;
class procedure TVendaRepository.VendaInserirItens(idOfVenda: Integer; Itens:
TList<TVendaItemVO>);
var
I: Integer;
begin
for I := 0 to Pred(Itens.Count) do
begin
Itens.Items[i].IdVenda:= idOfVenda;
Inserir(Itens.Items[i]);
end;
end;
class procedure TVendaRepository.VendaInserirRecebimentos(idOfVenda: Integer;
Itens: TList<TVendaRecebimentoVO>);
var
I: Integer;
begin
for I := 0 to Pred(Itens.Count) do
begin
Itens.Items[i].IdVenda:= idOfVenda;
Inserir(Itens.Items[i]);
end;
end;
class procedure TVendaRepository.VendaItensToDesconto(idOfVenda: Integer);
var
Filtro: string;
begin
Filtro:= 'execute procedure venda_itenstodesconto(' + IntToStr(idOfVenda) + ')';
ComandoSQL(Filtro);
end;
class procedure TVendaRepository.VendaToNFCE(idOfVenda: Integer);
var
Filtro: string;
begin
Filtro:= 'UPDATE VENDA SET FISCAL = ' + QuotedStr('S') +
' WHERE ID = ' + IntToStr(idOfVenda);
ComandoSQL(Filtro);
end;
end.
|
program GameMain;
uses SwinGame, sgTypes, math, sysutils, Crt, strutils;
type
AlbumImage = record
imgLocX, imgLocY : Integer;
rectLocX, rectLocY : Integer;
rectWidth, rectHeight : Integer;
rectColor : Color;
imagePath : String;
image : Bitmap;
end;
MenuLocation = (MainMenu, AlbumMenu);
UIButton = record
rectLocX, rectLocY : Integer;
rectWidth, rectHeight : Integer;
rectColor, outlineColor : Color;
labelText : String;
end;
Track = record
name, path : String;
doot : Music;
end;
TrackArray = Array of Track;
MusicGenre = (ProgMetal, Remix, Rock, Electropop);
Album = record
name, artist, path : String;
genre : MusicGenre;
trackCount : Integer;
tracks : TrackArray;
albumArt : AlbumImage;
end;
AlbumArray = Array of Album;
// It's easier to have these variables exit in a global scope since we may need them when
// using networked features
const
CONN : Connection = nil;
PORT : Integer = 4000;
// I seriously do not like how this locks up the ENTIRE program, but multi thread
// operations just won't work for me man
procedure OpenHost();
begin
CreateTCPHost(PORT);
while CONN = nil do
begin
AcceptTCPConnection();
CONN := FetchConnection();
end;
end;
procedure DrawAlbumImage(_img : AlbumImage);
begin
FillRectangle(_img.rectColor, _img.rectLocX, _img.rectLocY, _img.rectWidth, _img.rectHeight);
DrawBitmap(_img.image, _img.imgLocX, _img.imgLocY);
end;
procedure DrawUIButton(_btn : UIButton);
var
textX, textY : Integer;
begin
FillRectangle(_btn.outlineColor, _btn.rectLocX - 5, _btn.rectLocY - 1, _btn.rectWidth + 6, _btn.rectHeight + 2);
FillRectangle(_btn.rectColor, _btn.rectLocX, _btn.rectLocY, _btn.rectWidth, _btn.rectHeight);
// Positioning text is... weird. I guess this works though
textX := _btn.rectLocX + 5;
textY := Floor((_btn.rectLocY + (_btn.rectLocY + _btn.rectHeight)) / 2) - Floor((_btn.rectWidth / 20));
DrawText(_btn.labelText, _btn.outlineColor, textX, textY);
end;
// This procedure is most important when we want to make an album look "deselected"
procedure ResetAlbumRectColours(var userAlbums : AlbumArray);
var
i : Integer;
begin
i := 0;
while i <= High(userAlbums) do
begin
userAlbums[i].albumArt.rectColor := ColorBlack;
i += 1;
end;
end;
// This is mostly used for initialisation purposes
procedure ResetAlbumRectWidthHeight(var userAlbums : AlbumArray);
var
i : Integer;
begin
i := 0;
while i <= High(userAlbums) do
begin
userAlbums[i].albumArt.rectWidth := 206;
userAlbums[i].albumArt.rectHeight := 202;
i += 1;
end;
end;
function SetAlbumImagePosition(albImg : AlbumImage; locX, locY : Integer) : AlbumImage;
begin
albImg.imgLocX := locX;
albImg.imgLocY := locY;
albImg.rectLocX := locX - 5;
albImg.rectLocY := locY - 1;
result := albImg;
end;
procedure ResetAlbumImageDefaults(var userAlbums : AlbumArray);
begin
userAlbums[0].albumArt.imgLocX := 15;
userAlbums[0].albumArt.imgLocY := 10;
userAlbums[0].albumArt.rectLocX := 10;
userAlbums[0].albumArt.rectLocY := 9;
userAlbums[1].albumArt.imgLocX := userAlbums[0].albumArt.imgLocX + 230;
userAlbums[1].albumArt.imgLocY := userAlbums[0].albumArt.imgLocY;
userAlbums[1].albumArt.rectLocX := userAlbums[0].albumArt.rectLocX + 230;
userAlbums[1].albumArt.rectLocY := userAlbums[0].albumArt.rectLocY;
userAlbums[2].albumArt.imgLocX := userAlbums[0].albumArt.imgLocX;
userAlbums[2].albumArt.imgLocY := userAlbums[0].albumArt.imgLocY + 225;
userAlbums[2].albumArt.rectLocX := userAlbums[0].albumArt.rectLocX;
userAlbums[2].albumArt.rectLocY := userAlbums[0].albumArt.rectLocY + 225;
userAlbums[3].albumArt.imgLocX := userAlbums[2].albumArt.imgLocX + 230;
userAlbums[3].albumArt.imgLocY := userAlbums[2].albumArt.imgLocY;
userAlbums[3].albumArt.rectLocX := userAlbums[2].albumArt.rectLocX + 230;
userAlbums[3].albumArt.rectLocY := userAlbums[2].albumArt.rectLocY;
end;
function CheckButtonIsHovered(_btn : UIButton) : Boolean;
begin
result := PointInRect
(
MouseX(), MouseY(),
_btn.rectLocX, _btn.rectLocY,
_btn.rectWidth, _btn.rectHeight
);
end;
procedure ButtonHoverVisual(var _btn : UIButton);
begin
if (CheckButtonIsHovered(_btn)) and (MouseDown(LeftButton)) then _btn.outlineColor := ColorPurple
else if CheckButtonIsHovered(_btn) then _btn.outlineColor := ColorLightGrey
else _btn.outlineColor := ColorBlack;
end;
function CreateUIButton(x, y, width, height : Integer; rectColor, outlineColor: Color; labelText : String) : UIButton;
begin
result.rectLocX := x;
result.rectLocY := y;
result.rectWidth := width;
result.rectHeight := height;
result.rectColor := rectColor;
result.outlineColor := outlineColor;
result.labelText := labelText;
end;
// We use this function to create a string that we can use to send the album's information across the network.
// Is this a good solution? No. Does it work? Most of the time. Is that good enough? Yup.
function ConstructAlbumNetInfo(alb : Album) : String;
var
temp : String;
i : Integer;
begin
result := alb.name;
result += '|' + alb.artist;
WriteStr(temp, alb.genre);
result += '|' + temp;
result += '|' + IntToStr(alb.trackCount);
i := 0;
while i < alb.trackCount do
begin
result += '|' + alb.tracks[i].name;
i += 1;
end;
end;
// Load all the assets into the program before we continue. MUST BE CALLED FIRST THING!
procedure LoadAssets(var userAlbums : AlbumArray; var backButton, playAlbumButton, playButton, pauseButton, nextTrackButton, previousTrackButton, upButton, downButton, playTrackButton, startConnectionButton : UIButton);
var
tempString : String;
albumDataFile : TextFile;
i, a : Integer;
begin
SetLength(userAlbums, 4);
// Set generic values
ResetAlbumRectColours(userAlbums);
ResetAlbumRectWidthHeight(userAlbums);
// Prepare album data file for reading
AssignFile(albumDataFile, 'albums.dat');
Reset(albumDataFile);
// Iterate through each album and assign relevant info
i := 0;
while i <= High(userAlbums) do
begin
ReadLn(albumDataFile, userAlbums[i].name);
ReadLn(albumDataFile, userAlbums[i].artist);
ReadLn(albumDataFile, userAlbums[i].albumArt.imagePath);
userAlbums[i].albumArt.image := LoadBitmap(userAlbums[i].albumArt.imagePath);
ReadLn(albumDataFile, tempString);
userAlbums[i].genre := MusicGenre(StrToInt(tempString));
ReadLn(albumDataFile, tempString);
userAlbums[i].trackCount := StrToInt(tempString);
ReadLn(albumDataFile, userAlbums[i].path);
// Loop through to add all tracks
a := 0;
SetLength(userAlbums[i].tracks, userAlbums[i].trackCount);
while a < userAlbums[i].trackCount do
begin
ReadLn(albumDataFile, userAlbums[i].tracks[a].name);
ReadLn(albumDataFile, userAlbums[i].tracks[a].path);
userAlbums[i].tracks[a].doot := LoadMusic(userAlbums[i].path + userAlbums[i].tracks[a].path);
a += 1;
end;
i +=1;
end;
Close(albumDataFile); // Close file once we're done with it
ResetAlbumImageDefaults(userAlbums);
// UI Buttons
backButton := CreateUIButton(600, 450, 80, 30, ColorGrey, ColorBlack, 'Back');
playAlbumButton := CreateUIButton(15, 350, 100, 30, ColorGrey, ColorBlack, 'Play Album');
playButton := CreateUIButton(15, 390, 100, 20, ColorGrey, ColorBlack, 'Play');
pauseButton := CreateUIButton
(
playButton.rectLocX, playButton.rectLocY,
playButton.rectWidth, playButton.rectHeight,
playButton.rectColor, playButton.outlineColor, 'Pause'
);
nextTrackButton := CreateUIButton(15, 420, 100, 20, ColorGrey, ColorBlack, 'Next');
previousTrackButton := CreateUIButton(15, 450, 100, 20, ColorGrey, ColorBlack, 'Previous');
upButton := CreateUIButton(530, 10, 40, 25, ColorGrey, ColorBlack, 'Up');
downButton := CreateUIButton(580, 10, 40, 25, ColorGrey, ColorBlack, 'Down');
playTrackButton := CreateUIButton(530, 40, 90, 25, ColorGrey, ColorBlack, 'Play Track');
startConnectionButton := CreateUIButton(15, 450, 140, 20, ColorGrey, ColorBlack, 'Start Connection');
end;
// Handle all drawing for the main menu here
procedure DrawMainMenu(userAlbums : AlbumArray; albumSelection : Integer; startConnectionButton : UIButton);
var
i : Integer;
infoText : String;
begin
DrawUIButton(startConnectionButton);
// Show the user if they have hovered over an album and are able to click it
if albumSelection >= 0 then
begin
if MouseDown(LeftButton) then userAlbums[albumSelection].albumart.rectColor := ColorPurple
else userAlbums[albumSelection].albumArt.rectColor := ColorGrey;
end
else
begin
ResetAlbumRectColours(userAlbums);
end;
// Display all albums
i := 0;
while i <= (High(userAlbums)) do
begin
DrawAlbumImage(userAlbums[i].albumArt);
i += 1;
end;
DrawText('playing music is my passion.', ColorBlack, 460, 480);
// Display information on any album that has been hovered over
if albumSelection >= 0 then
infoText := userAlbums[albumSelection].name + ' - ' + userAlbums[albumSelection].artist
else
infoText := 'Select an album';
DrawText(infoText, ColorBlack, 10, 480);
end;
// Handle all inputs for the main menu here
procedure CheckMainMenuInput(userAlbums : AlbumArray; var albumSelection : Integer; var currentMenu : MenuLocation; var startConnectionButton : UIButton);
var
i : Integer;
begin
ButtonHoverVisual(startConnectionButton);
if (CheckButtonIsHovered(startConnectionButton)) and (MouseClicked(LeftButton)) then OpenHost();
albumSelection := -1;
i := 0;
while i <= High(userAlbums) do
begin
// Check to see if there is an album being hovered over
if PointInRect
(
MouseX(), MouseY(),
userAlbums[i].albumArt.rectLocX, userAlbums[i].albumArt.rectLocY,
userAlbums[i].albumArt.rectWidth, userAlbums[i].albumArt.rectHeight
) then albumSelection := i;
// Check if the album that is being hovered over has been clicked
if (albumSelection >= 0) and (MouseClicked(LeftButton)) then
begin
// If we're connected to a client we wanna send them all the album info
if CONN <> nil then
begin
SendTCPMessage(ConstructAlbumNetInfo(userAlbums[albumSelection]), CONN);
end;
currentMenu := AlbumMenu;
end;
i += 1;
end;
end;
// Handle all drawing for the album menu here
procedure DrawAlbumMenu(backButton, playAlbumButton, playButton, pauseButton, nextTrackButton, previousTrackButton, upButton, downButton, playTrackButton : UIButton; userAlbum : Album; musicPaused : Boolean; currentTrack, userTrackSelection : Integer);
var
tempString : String;
i, trackTextLocY : Integer;
begin
DrawUIButton(backButton);
DrawUIButton(playAlbumButton);
DrawUIButton(nextTrackButton);
DrawUIButton(previousTrackButton);
DrawUIButton(upButton);
DrawUIButton(downButton);
DrawUIButton(playTrackButton);
if musicPaused then DrawUIButton(playButton)
else DrawUIButton(pauseButton);
// Move the album image into the top left corner
userAlbum.albumArt := SetAlbumImagePosition(userAlbum.albumArt, 15, 10);
userAlbum.albumArt.rectColor := ColorBlack;
DrawAlbumImage(userAlbum.albumArt);
// Draw all the related album info below the album
DrawText('Album: ' + userAlbum.name, ColorBlack, 10, 225);
DrawText('Artist: ' + userAlbum.artist, ColorBlack, 10, 240);
Str(userAlbum.genre, tempString);
DrawText('Genre: ' + tempString, ColorBlack, 10, 255);
DrawText('Number of tracks: ' + IntToStr(userAlbum.trackCount), ColorBlack, 10, 270);
// Draw what is now playing if music is playing
if MusicPlaying() then
DrawText('Now playing: ' + userAlbum.tracks[currentTrack - 1].name, RandomRGBColor(255), 10, 285);
i := 0;
trackTextLocY := 10;
// Draw all the track names
while i < userAlbum.trackCount do
begin
DrawText(IntToStr(i + 1) + '. ' + userAlbum.tracks[i].name, ColorBlack, 300, trackTextLocY);
i += 1;
trackTextLocY += 15;
end;
DrawText('>', ColorRed, 290, 10 + (userTrackSelection * 15));
end;
procedure PlayAlbum(userAlbum : Album; var currentTrack : Integer);
begin
// Check if we have reached the end of the current song
if (currentTrack >= 0) and (not MusicPlaying()) then
begin
// Check if we are at the end of the album
if currentTrack = userAlbum.trackCount then currentTrack := -1
else
begin
// Play song and set current track to the next song
PlayMusic(userAlbum.tracks[currentTrack].doot, 1);
currentTrack += 1;
end;
end;
end;
// Handle all the inputs for the album menu here
procedure CheckAlbumMenuInput(var currentMenu : MenuLocation; var currentTrack, userTrackSelection: Integer; var musicPaused : Boolean; userAlbum : Album; var backButton, playAlbumButton, playButton, pauseButton, nextTrackButton, previousTrackButton, upButton, downButton, playTrackButton : UIButton);
var
netMessage : String;
begin
ButtonHoverVisual(backButton);
ButtonHoverVisual(playAlbumButton);
ButtonHoverVisual(playButton);
ButtonHoverVisual(pauseButton);
ButtonHoverVisual(nextTrackButton);
ButtonHoverVisual(previousTrackButton);
ButtonHoverVisual(upButton);
ButtonHoverVisual(downButton);
ButtonHoverVisual(playTrackButton);
netMessage := '';
// Recieve any TCP messages
if TCPMessageReceived() then netMessage := ReadMessage(CONN);
if netMessage <> '' then WriteLn(netMessage);
if ExtractDelimited(1, netMessage, ['|']) = 'VOLUME' then
SetMusicVolume(StrToFloat(ExtractDelimited(2, netMessage, ['|'])));
// Check if we're clicking on any of the UI buttons
if (CheckButtonIsHovered(backButton)) and (MouseClicked(LeftButton)) then currentMenu := MainMenu;
if (CheckButtonIsHovered(playAlbumButton)) and (MouseClicked(LeftButton)) and (currentTrack = -1) then currentTrack := 0;
// Play/pause music functionality
if musicPaused then
begin
if (CheckButtonIsHovered(playButton)) and (MouseClicked(LeftButton)) then musicPaused := false;
if netMessage = 'PAUSE' then musicPaused := false;
PauseMusic();
end
else
begin
if (CheckButtonIsHovered(pauseButton)) and (MouseClicked(LeftButton)) then musicPaused := true;
if netMessage = 'PAUSE' then musicPaused := true;
ResumeMusic();
end;
// NOTE: Both moving forwards or backwards out of the bounds of the album will
// force the program to stop all music playback
// Move forward one track
if ((CheckButtonIsHovered(nextTrackButton)) and (MouseClicked(LeftButton))) or (netMessage = 'NEXTTRACK') then
begin
if currentTrack = userAlbum.trackCount then
begin
currentTrack := -1;
StopMusic();
end
else if currentTrack = -1 then
begin
currentTrack := 0;
end
else
begin
PlayMusic(userAlbum.tracks[currentTrack].doot, 1);
currentTrack += 1;
end;
end;
// Move backwards one track
if ((CheckButtonIsHovered(previousTrackButton)) and (MouseClicked(LeftButton))) or (netMessage = 'PREVIOUSTRACK') then
begin
if currentTrack = 1 then
begin
currentTrack := -1;
StopMusic();
end
else if currentTrack > 1 then
begin
currentTrack -= 2;
PlayMusic(userAlbum.tracks[currentTrack].doot, 1);
currentTrack += 1;
end;
end;
// User track selection
if (CheckButtonIsHovered(upButton)) and (MouseClicked(LeftButton)) then userTrackSelection -=1;
if (CheckButtonIsHovered(downButton)) and (MouseClicked(Leftbutton)) then userTrackSelection += 1;
if userTrackSelection = userAlbum.trackCount then userTrackSelection := 0
else if userTrackSelection = -1 then userTrackSelection := userAlbum.trackCount - 1;
// Play user track selection
if (CheckButtonIsHovered(playTrackButton)) and (MouseClicked(LeftButton)) then
begin
StopMusic();
currentTrack := userTrackSelection;
musicPaused := false;
end;
// Check if we've set up to play any tracks
if (currentTrack >= 0) and (not musicPaused) then PlayAlbum(userAlbum, currentTrack);
end;
procedure Main();
var
// Universal
userAlbums : AlbumArray;
albumSelection, i, a : Integer;
currentMenu : MenuLocation;
// Album Menu
backButton, playAlbumButton, playButton, pauseButton, nextTrackButton, previousTrackButton, upButton, downButton, playTrackButton, startConnectionButton : UIButton;
currentTrack, userTrackSelection : Integer;
musicPaused : Boolean;
begin
OpenGraphicsWindow('playing music is my passion', 700, 500);
// Initialise assets and variables
LoadAssets(userAlbums, backButton, playAlbumButton, playButton, pauseButton, nextTrackButton, previousTrackButton, upButton, downButton, playTrackButton, startConnectionButton);
OpenAudio();
currentMenu := MainMenu;
albumSelection := 0;
repeat // The game loop...
ProcessEvents();
ClearScreen(ColorWhite);
// Start drawing everyting
if currentMenu = MainMenu then
begin
// We need to stop the music and set currentTrack to -1 so we reset all playback
StopMusic();
currentTrack := -1;
musicPaused := false;
userTrackSelection := 0;
CheckMainMenuInput(userAlbums, albumSelection, currentMenu, startConnectionButton);
DrawMainMenu(userAlbums, albumSelection, startConnectionButton);
end
else if currentMenu = AlbumMenu then
begin
CheckAlbumMenuInput(currentMenu, currentTrack, userTrackSelection, musicPaused, userAlbums[albumSelection], backButton, playAlbumButton, playButton, pauseButton, nextTrackButton, previousTrackButton, upButton, downButton, playTrackButton);
DrawAlbumMenu(backButton, playAlbumButton, playButton, pauseButton, nextTrackButton, previousTrackButton, upButton, downButton, playTrackButton, userAlbums[albumSelection], musicPaused, currentTrack, userTrackSelection);
end;
RefreshScreen(60);
until WindowCloseRequested();
// Release all assets before exiting
CloseAudio();
i := 0;
a := 0;
while i <= High(userAlbums) do
begin
while a < userAlbums[i].trackCount do
begin
FreeMusic(userAlbums[i].tracks[a].doot);
a += 1;
end;
i += 1;
end;
i := 0;
while i <= High(userAlbums) do
begin
FreeBitmap(userAlbums[i].albumArt.image);
i += 1;
end;
end;
begin
Main();
end.
|
{===============================================================================
TQQWry
Class with QQWry.DAT - by 冷风 (coldwind@citiz.net)
Status: Freeware
Compiler: Delphi4, Delphi5, Delphi6, Delphi7
Version: 1.0
Lastdate: 19 March 2005
Url: http://51tec.vicp.net/
在此unit中,实现了对于纯真网络(www.cz88.net)的IP数据库的读取,该数据库是在
搜捕的基础上实现的,现广泛应用于QQ和各种论坛上,主要目的是获取IP地址和所在区域
的对应关系。
本unit中,对于所有的输入参数没有进行校验,请自行在输入参数前确定参数无误,
此外,对于如何使用,在本unit中进行了详细的注解,也有例程进行了一定说明。
对于IP的搜索,本程序仅仅通过二分法进行查找。
--------------------------------------------------------------------------------
===============================================================================}
unit QQWry;
interface
uses
SysUtils, Classes, Controls, Math, Dialogs;
type
TQQWry = class(TObject)
public
constructor Create(cQQWryFileName: string);
destructor Destroy; override;
function GetQQWryFileName: string;
function GetQQWryFileSize: Cardinal;
function GetIPRecordNum: Cardinal;
function GetQQWryDate: TDate;
function GetQQWryDataFrom: string;
function GetIPLocation(IPLocationOffset: Cardinal): TStringList;
function GetIPMsg(IPRecordID: Cardinal): TStringList;
function GetIPRecordID(IP: string): Cardinal;
function GetIPValue(IP: string): Cardinal;
private
QQWryFileName: string;
QQWryFileStream: TFileStream;
QQWryFileSize: Cardinal;
IPRecordNum: Cardinal;
FirstIPIndexOffset, LastIPIndexOffset: Cardinal;
end;
implementation
///**
//* 构造一个TQQWry即QQIP地址数据库的对象
//* @param cQQWryFileName QQIP数据库文件的全名(包括路径),请确认文件存在和可读性
//* @return 无
//*/
constructor TQQWry.Create(cQQWryFileName: string);
begin
inherited Create;
QQWryFileName := cQQWryFileName;
QQWryFileStream := TFileStream.Create(QQWryFileName, fmOpenRead or fmShareDenyWrite, 0);
QQWryFileSize := QQWryFileStream.Size;
QQWryFileStream.Read(FirstIPIndexOffset, 4);
QQWryFileStream.Read(LastIPIndexOffset, 4);
IPRecordNum := (LastIPIndexOffset - FirstIPIndexOffset) div 7 + 1;
end;
///**
//* 析构函数,释放TQQWry对象,释放文件数据流对象
//* @param 无
//* @return 无
//*/
destructor TQQWry.Destroy;
begin
QQWryFileStream.Free;
inherited Destroy;
end;
///**
//* 获取QQIP数据库文件的全名(包括路径)
//* @param 无
//* @return QQIP数据库文件的全名(包括路径) string
//*/
function TQQWry.GetQQWryFileName: string;
begin
Result := QQWryFileName;
end;
///**
//* 获取QQIP数据库文件大小
//* @param 无
//* @return QQIP数据库文件大小 Cardinal
//*/
function TQQWry.GetQQWryFileSize: Cardinal;
begin
Result := QQWryFileSize;
end;
///**
//* 获取QQIP数据库内含有的IP地址信息记录条数
//* @param 无
//* @return QQIP数据库文件大小 Cardinal
//*/
function TQQWry.GetIPRecordNum: Cardinal;
begin
Result := IPRecordNum;
end;
///**
//* 获取当前QQIP数据库的更新日期
//* @param 无
//* @return QQIP当前数据库的更新日期 TDate
//*/
function TQQWry.GetQQWryDate: TDate;
var
DateString: string;
begin
DateString := GetIPMsg(GetIPRecordNum)[3];
DateString := Copy(DateString, 1, Pos('IP数据', DateString) - 1);
DateString := StringReplace(DateString, '年', '-', [rfReplaceAll, rfIgnoreCase]);
DateString := StringReplace(DateString, '月', '-', [rfReplaceAll, rfIgnoreCase]);
DateString := StringReplace(DateString, '日', '-', [rfReplaceAll, rfIgnoreCase]);
Result := StrToDate(DateString);
end;
///**
//* 获取当前QQIP数据库的来源信息
//* @param 无
//* @return 当前QQIP数据库的来源信息 string
//*/
function TQQWry.GetQQWryDataFrom: string;
begin
Result := GetIPMsg(GetIPRecordNum)[2];
end;
///**
//* 给定一个IP国家地区记录的偏移,返回该IP地址的信息
//* @param IPLocationOffset 国家记录的偏移 Cardinal
//* @return IP地址信息(国家信息/地区信息) string
//*/
function TQQWry.GetIPLocation(IPLocationOffset: Cardinal): TStringList;
const
//实际信息字串存放位置的重定向模式
REDIRECT_MODE_1 = 1;
REDIRECT_MODE_2 = 2;
var
RedirectMode: byte;
CountryFirstOffset, CountrySecondOffset: Cardinal;
CountryMsg, AreaMsg: string;
///**
//* 给定一个文件偏移值,返回在数据文件中该偏移下的字符串,即读取到0结尾的字符前
//* @param StringOffset 字符串在文件中的偏移值 Cardinal
//* @return 字符串 string
//*/
function ReadString(StringOffset: Cardinal): string;
var
ReadByte: char;
begin
Result := '';
QQWryFileStream.Seek(StringOffset, soFromBeginning);
QQWryFileStream.Read(ReadByte, 1);
while Ord(ReadByte) <> 0 do begin
Result := Result + ReadByte;
QQWryFileStream.Read(ReadByte, 1);
end;
end;
///**
//* 给定一个地区信息偏移值,返回在数据文件中该偏移量下的地区信息
//* @param AreaOffset 地区信息在文件中的偏移值 Cardinal;
//* @return 地区信息字符串 string
//*/
function ReadArea(AreaOffset: Cardinal): string;
var
ModeByte: byte;
ReadAreaOffset: Cardinal;
begin
QQWryFileStream.Seek(AreaOffset, soFromBeginning);
QQWryFileStream.Read(ModeByte, 1);
if (ModeByte = REDIRECT_MODE_1) or (ModeByte = REDIRECT_MODE_2) then begin
QQWryFileStream.Read(ReadAreaOffset, 3);
if ReadAreaOffset = 0 then Result := '未知地区'
else Result := ReadString(ReadAreaOffset);
end else begin
Result := ReadString(AreaOffset);
end;
end;
begin
//跳过4个字节,该4字节内容为该条IP信息里IP地址段中的终止IP值
QQWryFileStream.Seek(IPLocationOffset + 4, soFromBeginning);
//读取国家信息的重定向模式值
QQWryFileStream.Read(RedirectMode, 1);
//重定向模式1的处理
if RedirectMode = REDIRECT_MODE_1 then begin
//模式值为1,则后3个字节的内容为国家信息的重定向偏移值
QQWryFileStream.Read(CountryFirstOffset, 3);
//进行重定向
QQWryFileStream.Seek(CountryFirstOffset, soFromBeginning);
//第二次读取国家信息的重定向模式
QQWryFileStream.Read(RedirectMode, 1);
//第二次重定向模式为模式2的处理
if RedirectMode = REDIRECT_MODE_2 then begin
//后3字节的内容即为第二次重定向偏移值
QQWryFileStream.Read(CountrySecondOffset, 3);
//读取第二次重定向偏移值下的字符串值,即为国家信息
CountryMsg := ReadString(CountrySecondOffset);
//若第一次重定向模式为1,进行重定向后读取的第二次重定向模式为2,
//则地区信息存放在第一次国家信息偏移值的后面
QQWryFileStream.Seek(CountryFirstOffset + 4, soFromBeginning);
//第二次重定向模式不是模式2的处理
end else begin
CountryMsg := ReadString(CountryFirstOffset);
end;
//在重定向模式1下读地区信息值
AreaMsg := ReadArea(QQWryFileStream.Position);
//重定向模式2的处理
end else if RedirectMode = REDIRECT_MODE_2 then begin
QQWryFileStream.Read(CountrySecondOffset, 3);
CountryMsg := ReadString(CountrySecondOffset);
AreaMsg := ReadArea(IPLocationOffset + 8);
//不是重定向模式的处理,存放的即是IP地址信息
end else begin
CountryMsg := ReadString(QQWryFileStream.Position - 1);
AreaMsg := ReadArea(QQWryFileStream.Position);
end;
Result := TStringList.Create;
Result.Add(CountryMsg);
Result.Add(AreaMsg);
end;
///**
//* 给定一个IP地址信息记录号,返回该项记录的信息
//* @param IPRecordID IP地址信息记录号 Cardinal
//* @return 记录号信息(含3个部分:①起始IP地址 ②终止IP地址 ③国家信息/地区信息) TStringlist
//*/
function TQQWry.GetIPMsg(IPRecordID: Cardinal): TStringList;
var
aryStartIP: array[1..4] of byte;
strStartIP: string;
EndIPOffset: Cardinal;
aryEndIP: array[1..4] of byte;
strEndIP: string;
I: Integer;
begin
//根据记录ID号移到该记录号的索引处
QQWryFileStream.Seek(FirstIPIndexOffset + (IPRecordID - 1) * 7, soFromBeginning);
//索引的前4个字节为起始IP地址
QQWryFileStream.Read(aryStartIP, 4);
//后3个字节是内容区域的偏移值
QQWryFileStream.Read(EndIPOffset, 3);
//移至内容区域
QQWryFileStream.Seek(EndIPOffset, soFromBeginning);
//内容区域的前4个字节为终止IP地址
QQWryFileStream.Read(aryEndIP, 4);
//将起止IP地址转换为点分的形式
strStartIP := '';
for I := 4 downto 1 do begin
if I <> 1 then strStartIP := strStartIP + IntToStr(aryStartIP[I]) + '.'
else strStartIP := strStartIP + IntToStr(aryStartIP[I]);
end;
strEndIP := '';
for I := 4 downto 1 do begin
if I <> 1 then strEndIP := strEndIP + IntToStr(aryEndIP[I]) + '.'
else strEndIP := strEndIP + IntToStr(aryEndIP[I]);
end;
Result := TStringList.Create;
Result.Add(strStartIP);
Result.Add(strEndIP);
//获取该条记录下的IP地址信息
//以下三者是统一的:①内容区域的偏移值 ②终止IP地址的存放位置 ③国家信息紧接在终止IP地址存放位置后
Result.AddStrings(GetIPLocation(EndIPOffset));
end;
///**
//* 给定一个IP地址(四段点分字符串形式),返回该IP的数值
//* @param IP IP地址(四段点分字符串形式) string
//* @return 该IP的数值 Cardinal
//*/
function TQQWry.GetIPValue(IP: string): Cardinal;
var
tsIP: TStringList;
I: Integer;
function SplitStringToStringlist(aString: string; aSplitChar: string): TStringList;
begin
Result := TStringList.Create;
while Pos(aSplitChar, aString) > 0 do begin
Result.Add(Copy(aString, 1, Pos(aSplitChar, aString) - 1));
aString := Copy(aString, Pos(aSplitChar, aString) + 1, Length(aString) - Pos(aSplitChar, aString));
end;
Result.Add(aString);
end;
begin
tsIP := SplitStringToStringlist(IP, '.');
Result := 0;
for I := 3 downto 0 do begin
Result := Result + StrToInt(tsIP[I]) * Trunc(power(256, 3 - I));
end;
end;
///**
//* 给定一个IP地址(四段点分字符串形式),返回该IP地址所在的记录号
//* @param IP IP地址(四段点分字符串形式) string
//* @return 该IP地址所在的记录号 Cardinal
//*/
function TQQWry.GetIPRecordID(IP: string): Cardinal;
function SearchIPRecordID(IPRecordFrom, IPRecordTo, IPValue: Cardinal): Cardinal;
var
CompareIPValue1, CompareIPValue2: Cardinal;
begin
Result := 0;
QQWryFileStream.Seek(FirstIPIndexOffset + ((IPRecordTo - IPRecordFrom) div 2 + IPRecordFrom - 1) * 7, soFromBeginning);
QQWryFileStream.Read(CompareIPValue1, 4);
QQWryFileStream.Seek(FirstIPIndexOffset + ((IPRecordTo - IPRecordFrom) div 2 + IPRecordFrom) * 7, soFromBeginning);
QQWryFileStream.Read(CompareIPValue2, 4);
//找到了
if (IPValue >= CompareIPValue1) and (IPValue < CompareIPValue2) then begin
Result := (IPRecordTo - IPRecordFrom) div 2 + IPRecordFrom;
end else
//后半段找
if IPValue > CompareIPValue1 then begin
Result := SearchIPRecordID((IPRecordTo - IPRecordFrom) div 2 + IPRecordFrom + 1, IPRecordTo, IPValue);
end else
//前半段找
if IPValue < CompareIPValue1 then begin
Result := SearchIPRecordID(IPRecordFrom, (IPRecordTo - IPRecordFrom) div 2 + IPRecordFrom - 1, IPValue);
end;
end;
begin
Result := SearchIPRecordID(1, GetIPRecordNum, GetIPValue(IP));
end;
end.
|
unit userscript;
uses mteFunctions;
uses userUtilities;
const
target_filename = 'Deadly Wenches - Less Wenches Patch.esp';
lvln_entries = 2;
var
slMasters : TStringList;
target_file, skyrimFile, dwFile : IInterface;
//---------------------------------------------------------------------------------------
// File IO
//---------------------------------------------------------------------------------------
procedure getUserFile;
begin
target_file := getOrCreateFile(target_filename);
if not Assigned(target_file) then begin
AddMessage('File not created or retrieved!');
Exit;
end;
AddMastersToFile(target_file, slMasters, True);
end;
function getTargetLeveledListOverride(elem : IInterface): IInterface;
var
i : integer;
cur_ovr, next_ovr, m : IInterface;
s : string;
begin
if not Assigned(elem) then begin
AddMessage('getTargetLeveledListOverride: input "elem" not assigned.');
Exit;
end;
m := MasterOrSelf(elem);
cur_ovr := m;
//AddMessage(EditorID(elem));
for i := 0 to Pred(OverrideCount(m)) do begin
next_ovr := OverrideByIndex(m, i);
s := Name(GetFile(next_ovr));
if SameText(GetFileName(GetFile(next_ovr)), 'deadly wenches.esp') then
Break;
cur_ovr := next_ovr;
end;
Result := cur_ovr;
end;
procedure removeWenchesInLevelList(lvln : IInterface);
var
i, wench_index : integer;
lvln_ents, lvln_ent, lvln_ref, m_lvln_ref : IInterface;
s, target, file_str : string;
sl_wench : TStringList;
l_wench_cnt : TList;
begin
sl_wench := TStringList.Create;
l_wench_cnt := TList.Create;
lvln_ents := ElementByName(lvln, 'Leveled List Entries');
for i := Pred(ElementCount(lvln_ents)) downto 0 do begin
lvln_ent := ElementByIndex(lvln_ents, i);
lvln_ref := LinksTo(ElementByPath(lvln_ent, 'LVLO\Reference'));
s := GetElementEditValues(lvln_ent, 'LVLO\Level');
m_lvln_ref := getTargetLeveledListOverride(lvln_ref);
target := s + EditorID(m_lvln_ref);
if pos('DW_', EditorID(m_lvln_ref))=0 then Continue;
//AddMessage('Before check: ' + BaseName(GetFile(lvln_ref)) + ' | ' + target);
//file_str := LowerCase(BaseName(GetFile(m_lvln_ref)));
//if CompareStr(file_str, LowerCase('Deadly Wenches.esp')) <> 0 then begin
// AddMessage(IntToStr(CompareText(file_str, LowerCase('Deadly Wenches.esp'))));
//end;
//if CompareStr(file_str, LowerCase('Deadly Wenches.esp')) <> 0 then Continue;
//AddMessage('Found target: ' + target);
wench_index := sl_wench.IndexOf(target);
if wench_index = -1 then begin
//AddMessage('>>Adding');
sl_wench.Add(target);
l_wench_cnt.Add(1);
end else begin
if Integer(l_wench_cnt[wench_index]) >= lvln_entries then begin
//AddMessage('>>Revoving. Count ' + IntToStr(l_wench_cnt[wench_index]) + ' >= ' + IntToStr(lvln_entries));
RemoveElement(lvln_ents, lvln_ent)
end else begin
//AddMessage('>>Incrementing. Count ' + IntToStr(l_wench_cnt[wench_index]) + ' < ' + IntToStr(lvln_entries));
l_wench_cnt[wench_index] := Integer(l_wench_cnt[wench_index]) + 1;
end;
end;
end;
sl_wench.Free;
l_wench_cnt.Free;
end;
procedure getWenchRefFromLevelList(lvln : IInterface; sl_wench : TStringList; l_wench, l_wench_cnt : TList);
var
i, wench_index : integer;
lvln_ents, lvln_ent, lvln_ref, m_lvln_ref : IInterface;
s, target, file_str : string;
begin
lvln_ents := ElementByName(lvln, 'Leveled List Entries');
for i := 0 to Pred(ElementCount(lvln_ents)) do begin
lvln_ent := ElementByIndex(lvln_ents, i);
lvln_ref := LinksTo(ElementByPath(lvln_ent, 'LVLO\Reference'));
s := GetElementEditValues(lvln_ent, 'LVLO\Level');
m_lvln_ref := getTargetLeveledListOverride(lvln_ref);
target := s + EditorID(m_lvln_ref);
//AddMessage('Before check: ' + BaseName(GetFile(lvln_ref)) + ' | ' + target);
file_str := BaseName(GetFile(m_lvln_ref));
if not SameText(file_str, 'Deadly Wenches.esp') then Continue;
//AddMessage('Found target: ' + target);
wench_index := sl_wench.IndexOf(target);
if wench_index = -1 then begin
sl_wench.Add(target);
l_wench.Add(m_lvln_ref);
l_wench_cnt.Add(1);
end else begin
l_wench_cnt[wench_index] := Integer(l_wench_cnt[wench_index]) + 1;
end;
end;
end;
procedure reduceWenches;
var
i : integer;
lvlns, lvln, m_lvln, new_override : IInterface;
sl_wench : TStringList;
l_wench, l_wench_cnt : TList;
begin
lvlns := GetFileElements('deadly wenches.esp', 'LVLN');
for i := 0 to Pred(ElementCount(lvlns)) do begin
lvln := ElementByIndex(lvlns, i);
if IsMaster(lvln) then Continue;
//m_lvln := getTargetLeveledListOverride(lvln);
//new_override := wbCopyElementToFile(m_lvln, target_file, False, True);
new_override := wbCopyElementToFile(lvln, target_file, False, True);
removeWenchesInLevelList(new_override);
//sl_wench := TStringList.Create;
//l_wench := TList.Create;
//l_wench_cnt := TList.Create;
//getWenchRefFromLevelList(lvln, sl_wench, l_wench, l_wench_cnt);
//decreaseWenchesInLevelList(new_override, sl_wench, l_wench, l_wench_cnt);
//sl_wench.Free;
//l_wench.Free;
//l_wench_cnt.Free;
end;
end;
procedure decreaseWenchesInLevelList(lvln : IInterface; sl_wench : TStringList; l_wench, l_wench_cnt : TList);
var
i, j : integer;
target_additions : integer;
begin
for i := 0 to sl_wench.Count-1 do begin
target_additions := Min(l_wench_cnt[i], lvln_entries);
for j := 0 to target_additions-1 do begin
//AddMessage(EditorID(ObjectToElement(l_wench[i])));
AddLeveledListEntry(lvln, 1, ObjectToElement(l_wench[i]), 1);
end;
end;
end;
function isVampire(npc : IInterface) : boolean;
var
i, j : integer;
factions, faction : IInterface;
begin
factions := ElementByName(npc, 'Factions');
for i:= 0 to Pred(ElementCount(factions)) do begin
faction := ElementByIndex(factions, i);
faction := LinksTo(ElementByPath(faction, 'Faction'));
if EditorID(faction) = 'VampireFaction' then
Result := true;
Exit;
end;
Result := false;
end;
//---------------------------------------------------------------------------------------
// Global Variables
//---------------------------------------------------------------------------------------
procedure freeGlobalVariables;
begin
slMasters.Free;
end;
function getFileObject(filename : string): IInterface;
var
i : integer;
f : IInterface;
s : string;
begin
for i := 0 to FileCount - 1 do begin
f := FileByIndex(i);
s := GetFileName(f);
if SameText(s, filename) then begin
Result := f;
Exit;
end;
end;
end;
procedure setupGlobalVariables;
begin
skyrimFile := getFileObject('Skyrim.esm');
dwFile := getFileObject('Deadly Wenches.esp');
slMasters := TStringList.Create;
slMasters.Add('Skyrim.esm');
slMasters.Add('Update.esm');
slMasters.Add('Dawnguard.esm');
slMasters.Add('Dragonborn.esm');
//slMasters.Add('Unofficial Skyrim Legendary Edition Patch.esp');
slMasters.Add('Immersive Wenches.esp');
slMasters.Add('Deadly Wenches.esp');
end;
//---------------------------------------------------------------------------------------
// Required Tes5Edit Script Functions
//---------------------------------------------------------------------------------------
// Called before processing
// You can remove it if script doesn't require initialization code
function Initialize: integer;
begin
setupGlobalVariables;
getUserFile;
reduceWenches;
Result := 0;
end;
// called for every record selected in xEdit
function Process(e: IInterface): integer;
begin
Result := 0;
// comment this out if you don't want those messages
//AddMessage('Processing: ' + FullPath(e));
// processing code goes here
end;
// Called after processing
// You can remove it if script doesn't require finalization code
function Finalize: integer;
begin
freeGlobalVariables;
Result := 0;
end; // 23
end. |
unit Invoice.Controller.Facade;
interface
uses
Invoice.Controller.Interfaces, Invoice.Model.Interfaces;
type
TControllerGeneralFacade = class(TInterfacedObject, iControllerModelFacade)
private
FAppInfo: iControllerAppInfoFactory;
FWinInfo: iControllerWinInfoFactory;
FChart: iControllerChartFactory;
FIniFile: iControllerIniFileFactory;
FSecurity: iControllerSecurityFactory;
FTabForm: iControllerTabFormFactory;
FEntity: iModelEntityFactory;
public
constructor Create;
destructor Destroy; Override;
class function New: iControllerModelFacade;
function AppInfoFactory: iControllerAppInfoFactory;
function IniFileFactory: iControllerIniFileFactory;
function SecurityFactory: iControllerSecurityFactory;
function TabFormFactory: iControllerTabFormFactory;
function ChartFactory: iControllerChartFactory;
function WinInfoFactory: iControllerWinInfoFactory;
function EntityFactory: iModelEntityFactory;
end;
implementation
{ TControllerGeneralFacade }
uses
Invoice.Controller.Chart.Factory, Invoice.Controller.AppInfo.Factory, Invoice.Controller.IniFile.Factory, Invoice.Controller.Security.Factory,
Invoice.Controller.TabForm.Factory, Invoice.Controller.WinInfo.Factory, Invoice.Controller.Entity.Factory;
function TControllerGeneralFacade.AppInfoFactory: iControllerAppInfoFactory;
begin
FAppInfo := TControllerAppInfoFactory.New;
//
Result := FAppInfo;
end;
function TControllerGeneralFacade.ChartFactory: iControllerChartFactory;
begin
FChart := TControllerChartFactory.New;
//
Result := FChart;
end;
constructor TControllerGeneralFacade.Create;
begin
//
end;
destructor TControllerGeneralFacade.Destroy;
begin
inherited;
end;
function TControllerGeneralFacade.EntityFactory: iModelEntityFactory;
begin
FEntity := TControllerEntityFactory.New;
//
Result := FEntity;
end;
function TControllerGeneralFacade.IniFileFactory: iControllerIniFileFactory;
begin
FIniFile := TControllerIniFileFactory.New;
//
Result := FIniFile;
end;
class function TControllerGeneralFacade.New: iControllerModelFacade;
begin
Result := Self.Create;
end;
function TControllerGeneralFacade.SecurityFactory: iControllerSecurityFactory;
begin
FSecurity := TControllerSecurityFactory.New;
//
Result := FSecurity;
end;
function TControllerGeneralFacade.TabFormFactory: iControllerTabFormFactory;
begin
FTabForm := TControllerTabFormFactory.New;
//
Result := FTabForm;
end;
function TControllerGeneralFacade.WinInfoFactory: iControllerWinInfoFactory;
begin
FWinInfo := TControllerWinInfoFactory.New;
//
Result := FWinInfo;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.