text
stringlengths
14
6.51M
unit Module.DataSet.ConfigMemento; interface uses System.Generics.Collections, FireDac.Comp.Client, Module.DataSet.ConfigMemento.ArmazenarConfiguracao; type IConfigMemento = interface(IInterface) ['{8A9C1E4D-0A2B-44E3-BE3A-8DB31A46E870}'] function GuardarConfig: IConfigMemento; end; TConfigMemento = class(TInterfacedObject, IConfigMemento) private FDataSet: TFDMemTable; FConfig: TArmazenarConfiguracaoSet; FListConfig: TList<IInterface>; public constructor Create(const ADataSet: TFDMemTable; const AConfig: TArmazenarConfiguracaoSet); destructor Destroy; override; function GuardarConfig: IConfigMemento; end; implementation uses System.SysUtils, Module.DataSet.ConfigMemento.Fabrica; constructor TConfigMemento.Create(const ADataSet: TFDMemTable; const AConfig: TArmazenarConfiguracaoSet); begin FDataSet := ADataSet; FConfig := AConfig; FListConfig := TList<IInterface>.Create; end; destructor TConfigMemento.Destroy; begin FreeAndNil(FListConfig); inherited; end; function TConfigMemento.GuardarConfig: IConfigMemento; var _config: TArmazenarConfiguracao; begin for _config := Low(TArmazenarConfiguracao) to High(TArmazenarConfiguracao) do begin if _config in FConfig then FListConfig.Add(TCofigMementoFabrica.PegarConfigMemento(FDataSet, _config)) end; Result := Self; end; end.
{ How to add a new design control type to the demo (example: add a TEdit): - In the Initialization section register the new class. Add the line "RegisterClass(TEdit);" - Add the palette icon of the new class to the ImageList of the demo. You can find the palette icons of the LCL components in the folder "images/components" of your Lazarus installation. Select the one without size appending, e.g. "tedit.png" (not "tedit_150.png") - this demo does not support the LCL multi-size image list. - Add a new button to the toolbar. Set its ImageIndex to the index of the correspondig icon in the image list. Each tool button has a Tag property. Set the Tag of the new button to the next value - look at the other buttons to see their Tag values. - Assign the handler "PaletteButtonClick" to the new button. - Go to "TMainForm.PaletteButtonClick" and add the name of the new class to the array "oClasses". Don't forget to increment the upper array index. Note that the array index is equal to the Tag of the corresponding button. } unit main; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ComCtrls, Menus, StdCtrls, ExtCtrls, JvDesignSurface, JvDesignUtils; type { TMainForm } TMainForm = class(TForm) Active1: TMenuItem; ButtonButton: TToolButton; csDesigning1: TMenuItem; DelphiSelector1: TMenuItem; File1: TMenuItem; Grid1: TMenuItem; ImageButton: TToolButton; ImageList1: TImageList; JvDesignPanel: TJvDesignPanel; LabelButton: TToolButton; MainMenu1: TMainMenu; N1: TMenuItem; N2: TMenuItem; N3: TMenuItem; N4: TMenuItem; New1: TMenuItem; Open1: TMenuItem; OpenDialog: TOpenDialog; PanelButton: TToolButton; Rules1: TMenuItem; Save1: TMenuItem; SaveDialog: TSaveDialog; SelectButton: TToolButton; ToolBar1: TToolBar; VSSelector1: TMenuItem; WindowProcHook1: TMenuItem; procedure Active1Click(Sender: TObject); procedure csDesigning1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Grid1Click(Sender: TObject); procedure New1Click(Sender: TObject); procedure Open1Click(Sender: TObject); procedure Rules1Click(Sender: TObject); procedure Save1Click(Sender: TObject); procedure JvDesignPanelGetAddClass(Sender: TObject; var ioClass: String); procedure JvDesignPanelPaint(Sender: TObject); procedure PaletteButtonClick(Sender: TObject); private { private declarations } public { public declarations } DesignClass: string; StickyClass: Boolean; end; var MainForm: TMainForm; implementation uses JvDesignImp; {$R *.lfm} { TMainForm } procedure TMainForm.New1Click(Sender: TObject); begin JvDesignPanel.Clear; end; procedure TMainForm.Grid1Click(Sender: TObject); begin // end; procedure TMainForm.csDesigning1Click(Sender: TObject); begin JvDesignPanel.Active := false; if WindowProcHook1.Checked then JvDesignPanel.Surface.MessengerClass := TJvDesignWinControlHookMessenger else JvDesignPanel.Surface.MessengerClass := TJvDesignDesignerMessenger; JvDesignPanel.Active := true; JvDesignPanel.Invalidate; end; procedure TMainForm.FormCreate(Sender: TObject); begin // OpenDialog.InitialDir := ExtractFilePath(Application.ExeName); OpenDialog.InitialDir := '../../../examples/JvDesigner/'; SaveDialog.InitialDir := OpenDialog.InitialDir; JvDesignPanel.Surface.Active := true; end; procedure TMainForm.Active1Click(Sender: TObject); begin JvDesignPanel.Active := Active1.Checked; JvDesignPanel.Invalidate; end; procedure TMainForm.Open1Click(Sender: TObject); begin if OpenDialog.Execute then JvDesignPanel.LoadFromFile(OpenDialog.Filename); end; procedure TMainForm.Rules1Click(Sender: TObject); begin if Rules1.Checked then begin JvDesignPanel.Color := clWhite; JvDesignPanel.DrawRules := true; JvDesignPanel.OnPaint := nil; end else begin JvDesignPanel.Color := clBtnFace; JvDesignPanel.DrawRules := false; JvDesignPanel.OnPaint := @JvDesignPanelPaint; end; JvDesignPanel.Invalidate; end; procedure TMainForm.Save1Click(Sender: TObject); begin if SaveDialog.Execute then JvDesignPanel.SaveToFile(SaveDialog.Filename); end; procedure TMainForm.JvDesignPanelGetAddClass(Sender: TObject; var ioClass: String); begin ioClass := DesignClass; if not StickyClass then begin DesignClass := ''; SelectButton.Down := true; end; end; procedure TMainForm.JvDesignPanelPaint(Sender: TObject); begin with JvDesignPanel do DesignPaintGrid(Canvas, ClientRect, Color); end; procedure TMainForm.PaletteButtonClick(Sender: TObject); const cClasses: array[0..4] of string = ( '', 'TButton', 'TLabel', 'TPanel', 'TImage'); begin // StickyClass := (GetKeyState(VK_SHIFT) < 0); StickyClass := False; DesignClass := cClasses[TControl(Sender).Tag]; end; initialization RegisterClass(TButton); RegisterClass(TLabel); RegisterClass(TPanel); RegisterClass(TImage); end.
{*******************************************************} { } { Delphi DataSnap Framework } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit DSAzDlgCreateContainer; interface uses Vcl.Buttons, System.Classes, Vcl.Controls, Vcl.ExtCtrls, Vcl.Forms, System.Generics.Collections, Vcl.Graphics, Vcl.Grids, Vcl.StdCtrls, Vcl.ValEdit; type TAzCreateContainerDlg = class(TForm) OKBtn: TButton; CancelBtn: TButton; GridPanel1: TGridPanel; FlowPanel1: TFlowPanel; lbName: TLabel; edtContainerName: TEdit; rgPublicDataAccess: TRadioGroup; vleMeta: TValueListEditor; btnAddMetadata: TButton; btnDelMetadata: TButton; procedure OKBtnClick(Sender: TObject); procedure btnAddMetadataClick(Sender: TObject); procedure btnDelMetadataClick(Sender: TObject); procedure edtContainerNameChange(Sender: TObject); private { Private declarations } public { Public declarations } procedure PopulateWithMetadata(const meta: TDictionary<String, String>); procedure AssignMetadata(const meta: TDictionary<String, String>); procedure SetContainerName(const Name: String; Enabled: boolean = true); function GetContainerName: String; procedure SetPublicDataAccess(const DataAccess: String); function GetPublicDataAccess: String; procedure SetTitle(const Title: String); function RawMetadata: TStrings; property PublicDataAccess: String read GetPublicDataAccess write SetPublicDataAccess; end; implementation {$R *.dfm} { TAzCreateContainerDlg } procedure TAzCreateContainerDlg.AssignMetadata( const meta: TDictionary<String, String>); var I, Count: Integer; key, value: String; begin meta.Clear; Count := vleMeta.Strings.Count; for I := 0 to Count - 1 do begin key := vleMeta.Strings.Names[I]; value := vleMeta.Strings.ValueFromIndex[I]; if (Length(key) > 0) and (Length(value) > 0) then meta.Add(key, value); end; end; procedure TAzCreateContainerDlg.btnAddMetadataClick(Sender: TObject); begin vleMeta.InsertRow('', '', true); vleMeta.SetFocus; end; procedure TAzCreateContainerDlg.btnDelMetadataClick(Sender: TObject); var row: Integer; begin row := vleMeta.Row; if (row > 0) and (row < vleMeta.RowCount) then vleMeta.DeleteRow(row); end; procedure TAzCreateContainerDlg.edtContainerNameChange(Sender: TObject); begin OKBtn.Enabled := Length(edtContainerName.Text) > 0; end; function TAzCreateContainerDlg.GetContainerName: String; begin Result := edtContainerName.Text; end; function TAzCreateContainerDlg.GetPublicDataAccess: String; begin if rgPublicDataAccess.ItemIndex = 0 then Result := 'container' else if rgPublicDataAccess.ItemIndex = 1 then Result := 'blob' else Result := ''; end; procedure TAzCreateContainerDlg.OKBtnClick(Sender: TObject); begin CloseModal; end; procedure TAzCreateContainerDlg.PopulateWithMetadata( const meta: TDictionary<String, String>); var keys: TArray<String>; I, Count: Integer; begin vleMeta.Strings.Clear; keys := meta.Keys.ToArray; Count := meta.Keys.Count; for I := 0 to Count - 1 do vleMeta.Values[keys[I]] := meta.Items[keys[I]]; end; function TAzCreateContainerDlg.RawMetadata: TStrings; begin Result := vleMeta.Strings; end; procedure TAzCreateContainerDlg.SetContainerName(const Name: String; Enabled: boolean); begin edtContainerName.Text := Name; edtContainerName.Enabled := Enabled; end; procedure TAzCreateContainerDlg.SetPublicDataAccess(const DataAccess: String); begin if DataAccess = 'container' then rgPublicDataAccess.ItemIndex := 0 else rgPublicDataAccess.ItemIndex := 1; end; procedure TAzCreateContainerDlg.SetTitle(const Title: String); begin Caption := Title; end; end.
unit BucketMem_ASM; (* (c) 2001-2005 Robert Houdart, Link Software This code can be freely used and/or modified, as long as you kindly acknowledge the origin. BucketMem is a replacement Memory Manager for Delphi 5,6,7,2005 and Kylix that does not suffer from fragmentation and delivers much better performance in a multi-threaded application. HOW TO USE: Simply add BucketMem as the very first unit in your project (dpr) file. The memory management is performed at 3 levels: 1) the V-Block level that allocates OS memory chunks of 256 kB..1024 kB of committed memory 2) each V-Block is divided into "Sheets" of 16 kB..144 kB 3) each "Sheet" is used to create memory blocks of a given size (16 bytes up to 144 kB) The sheets are managed by "buckets". BucketMem uses about 50 buckets that each deliver memory blocks of a given size. A Bucket - manages a number of Sheets in a double-linked list - has an ActiveSheet out of which memory blocks are served until exhaustion - if ActiveSheet has been used up, the Bucket continues with the next Sheet that has free blocks; if none is available, a new Sheet is created A Sheet - is a 16 kB..144 kB memory zone divided in BlockCount equal blocks with size BlockSize - memory blocks are served either linearly or from a single-linked list of free blocks - Sheets are allocated from from V-Blocks A Memory Block - 4 bytes overhead to store the Sheet to which the memory block belongs - detects freeing an invalid block or twice the same memory block A V-Block - is a 256 kB..1024 kB zone of committed Virtual Memory (Windows) - will be sub-divided into a number of Sheets History: 7/01/2001 first production version for eLink 17/07/2004 Kylix compatibility (without using $IFDEF MSWINDOWS to remain Delphi 5 compatible) 18/01/2005 BucketMem 1.0 First version sent to FastCode MM Challenge using spinlocks instead of critical sections 1/05/2005 BucketMem 1.6 Cleaned-up version with better cache associativity and buckets up to 144 kB 7/05/2005 BucketMem 1.6.1 Restored Kylix compatibility; Fixed Windows 98 VirtualFree problem 19/12/2005 Dennis Kjaer Christensen fixed a bug. Search for "//Added by DKC" to see code changes 20/12/2005 Dennis Kjaer Christensen fixed a bug. Search for "//Added by DKC" to see code changes *) {$O+,R-,Q-,I-,B-,D-,WARNINGS OFF} // optimization, no range check, no overflow check, no I/O check, // shortcut boolean evaluation, no debug information (to avoid tracing into this unit), no warnings {$D+,WARNINGS ON} // activate to debug this unit {$define USEISMULTITHREAD} // activate to take into account the variable IsMultiThread {$define ALIGN16BYTE} // activate to align all memory allocations to 16-byte boundaries {.$define USECACHEOFFSET} //Added by DKC// Do not use - it triggers a bug // give random offset to large blocks to improve cache associativity {.$define USESYSTEMMOVE} // activate when you're using FastMove in your project {$ifdef LINUX}For Kylix please use BucketMem instead of BucketMem_ASM{$endif} interface implementation uses Windows; type PBlockUsed = ^TBlockUsed; PHeapBlockUsed = ^THeapBlockUsed; PBlockFree = ^TBlockFree; PSheet = ^TSheet; PBucket = ^TBucket; TBucket = record SpinLock: integer; BlockSize: Cardinal; ActiveSheet: PSheet; CurAddr: Cardinal; MaxAddr: Cardinal; SheetCount: Cardinal; FirstSheet: PSheet; FirstFreeSheet: PSheet; end; PVirtualBlock = ^TVirtualBlock; PVBlockDescriptor = ^TVBlockDescriptor; TVirtualBlock = record P: Pointer; Available: Cardinal; VBlockDescriptor: PVBlockDescriptor; NextFreeBlock: PVirtualBlock; PrevFreeBlock: PVirtualBlock; end; TVBlockDescriptor = record SheetSize: Cardinal; VMSize: Cardinal; AvailableBits: Cardinal; FirstFreeVBlock: PVirtualBlock; SpinLock: Integer; VBlockCount: Integer; end; TSheet = record {size: 40 bytes; max 44} Magic: Cardinal; Bucket: PBucket; NextSheet: PSheet; PrevSheet: PSheet; NextFreeSheet: PSheet; PrevFreeSheet: PSheet; BlockUsedCount: Cardinal; FirstFree: PBlockFree; VirtualBlock: PVirtualBlock; VBlockIndex: Cardinal; end; TBlockUsed = record Sheet: PSheet; end; THeapBlockUsed = record n1: Cardinal; ReallocCount: integer; Size: Cardinal; Sheet: PSheet; end; TBlockFree = record NextBlock: PBlockFree; end; const MAX_BUCKET_MEM = $23EC0; // largest block allocated by buckets MAGIC_BLOCK_HEAP_ALLOC = $48454151; // identifies a large (heap) block MAGIC_SHEET = $19680807; // identifies a valid sheet EXACT_REALLOC_COUNT = 2; // Number of Reallocs that will return exact requested size // block sizes should be as close as possible to integer dividers of (SheetSize - $40) const Buckets: array[0..53] of TBucket = ( (BlockSize: $0010), (BlockSize: $0020), (BlockSize: $0030), (BlockSize: $0040), (BlockSize: $0050), (BlockSize: $0060), (BlockSize: $0070), (BlockSize: $0080), (BlockSize: $0090), (BlockSize: $00A0), (BlockSize: $00B0), (BlockSize: $00C0), (BlockSize: $00D0), (BlockSize: $00E0), (BlockSize: $00F0), (BlockSize: $0100), (BlockSize: $0120), (BlockSize: $0140), (BlockSize: $0160), (BlockSize: $0180), (BlockSize: $01A0), (BlockSize: $01C0), (BlockSize: $01E0), (BlockSize: $0200), (BlockSize: $0240), (BlockSize: $0280), (BlockSize: $02C0), (BlockSize: $0300), (BlockSize: $0340), (BlockSize: $0380), (BlockSize: $03C0), (BlockSize: $0400), (BlockSize: $0510), (BlockSize: $0620), (BlockSize: $0750), (BlockSize: $08B0), // $35, $2C, $25, $1F (BlockSize: $0A60), (BlockSize: $0C40), (BlockSize: $0E40), (BlockSize: $10E0), // $1A, $16, $13, $10 (BlockSize: $1350), (BlockSize: $1690), (BlockSize: $1B10), (BlockSize: $21D0), // $0E, $0C, $0A, $08 (BlockSize: $26A0), (BlockSize: $2D20), (BlockSize: $3620), (BlockSize: $43B0), // $07, $06, $05, $04 (BlockSize: $5A40), // $03 (BlockSize: $72F0), (BlockSize: $8FB0), (BlockSize: $BF90), (BlockSize: $11F60), // $05, $04, $03, $02 (BlockSize: $23EC0) // $01 ); var BucketIndexForSize: array[0..MAX_BUCKET_MEM div 16 - 1] of byte; // bucket index for different memory sizes FastCodeMove: procedure(const Source; var Dest; Count : Integer); // move function used by reallocation VDestroying: boolean; // flag to indicate unit finalising const VBlockDescriptors: array[0..2] of TVBlockDescriptor = ( (SheetSize: $04F00; VMSize: 16 * $04F00; AvailableBits: $0000FFFF), (SheetSize: $10F00; VMSize: 15 * $10F00; AvailableBits: $00007FFF), (SheetSize: $23F00; VMSize: 4 * $23F00; AvailableBits: $0000000F) ); (********************************************************************) // Some utility functions requiring assembler (********************************************************************) // InterlockedCompareExchange for Delphi 5 (avoids ifdef VER130} and Kylix compatibility function InterlockedCompareExchange(var Destination: Longint; Exchange: Longint; Comperand: Longint): LongInt; asm xchg ecx, eax lock cmpxchg [ecx], edx end; // bit functions for which no efficient equivalent exists in Pascal function GetBitIndexAndClear(var Value: Cardinal): Cardinal; asm mov edx, [eax] bsf ecx, edx btr edx, ecx mov [eax], edx mov eax, ecx end; procedure SetBitIndex(var Value: Cardinal; Index: Cardinal); asm bts [eax], edx end; (********************************************************************) // Faster Move Function (based on MoveJOH_IA32_9) (********************************************************************) procedure Move_IA32(const Source; var Dest; Count : Integer); asm cmp eax, edx je @Done cmp ecx, 28 ja @Large {Count > SMALLMOVESIZE or Count < 0} add eax, ecx add edx, ecx @@SmallForwardMove_6: jmp dword ptr [@@FwdJumpTable+ecx] nop {Align Jump Table} @@FwdJumpTable: dd @Done {Removes need to test for zero size move} dd @@Fwd04, @@Fwd08, @@Fwd12, @@Fwd16 dd @@Fwd20, @@Fwd24, @@Fwd28 @@Fwd28: mov ecx, [eax-28] mov [edx-28], ecx @@Fwd24: mov ecx, [eax-24] mov [edx-24], ecx @@Fwd20: mov ecx, [eax-20] mov [edx-20], ecx @@Fwd16: mov ecx, [eax-16] mov [edx-16], ecx @@Fwd12: mov ecx, [eax-12] mov [edx-12], ecx @@Fwd08: mov ecx, [eax-8] mov [edx-8], ecx @@Fwd04: mov ecx, [eax-4] mov [edx-4], ecx ret @Large: jng @Done {Count < 0} {For Compatibility with Delphi's move for Count < 0} fild qword ptr [eax] lea eax, [eax+ecx-8] lea ecx, [ecx+edx-8] fistp qword ptr [edx] push ecx neg ecx and edx, -8 lea ecx, [ecx+edx+8] pop edx @FwdLoop: fild qword ptr [eax+ecx] fistp qword ptr [edx+ecx] add ecx, 8 jl @FwdLoop fild qword ptr [eax] fistp qword ptr [edx] @Done: ret end; (********************************************************************) // inline OS Interface to facilitate Windows/Linux compatibility (********************************************************************) {$ifndef LINUX} var HeapHandle: THandle; // handle for Windows heap operations {$endif} procedure OSHeapInit; {$ifdef ver170}inline; {$endif} begin {$ifndef LINUX} HeapHandle := GetProcessHeap; {$endif} end; function OSHeapAlloc(Size: Cardinal): Pointer; {$ifdef ver170}inline; {$endif} begin {$ifdef LINUX} Result := Libc.malloc(Size); {$else} Result := HeapAlloc(HeapHandle, 0, Size); {$endif} end; function OSHeapFree(P: Pointer): boolean; {$ifdef ver170}inline; {$endif} begin {$ifdef LINUX} Libc.free(P); Result := True; {$else} Result := HeapFree(HeapHandle, 0, P); {$endif} end; function OSVirtualAlloc(Size: Cardinal): Pointer; {$ifdef ver170}inline; {$endif} begin {$ifdef LINUX} Result := Libc.malloc(Size); {$else} Result := VirtualAlloc(nil, Size, MEM_COMMIT, PAGE_READWRITE); {$endif} end; function OSVirtualFree(P: Pointer): boolean; {$ifdef ver170}inline; {$endif} begin {$ifdef LINUX} Libc.free(P); Result := True; {$else} Result := VirtualFree(P, 0, MEM_RELEASE); {$endif} end; (********************************************************************) // Virtual Memory Management (********************************************************************) function CreateVBlock(VBlockDescriptor: PVBlockDescriptor): PVirtualBlock; begin Result := OSHeapAlloc(SizeOf(TVirtualBlock)); if Result = nil then Exit; Result.Available := VBlockDescriptor.AvailableBits; Result.P := OSVirtualAlloc(VBlockDescriptor.VMSize); if Result.P = nil then begin OSHeapFree(Result); Result := nil; Exit; end; Result.VBlockDescriptor := VBlockDescriptor; Result.PrevFreeBlock := nil; Result.NextFreeBlock := VBlockDescriptor.FirstFreeVBlock; if VBlockDescriptor.FirstFreeVBlock <> nil then VBlockDescriptor.FirstFreeVBlock.PrevFreeBlock := Result; VBlockDescriptor.FirstFreeVBlock := Result; inc(VBlockDescriptor.VBlockCount); end; procedure DestroyVBlock(VirtualBlock: PVirtualBlock); begin if not VDestroying and (VirtualBlock.VBlockDescriptor.VBlockCount <= 1) then Exit; dec(VirtualBlock.VBlockDescriptor.VBlockCount); if VirtualBlock.NextFreeBlock <> nil then VirtualBlock.NextFreeBlock.PrevFreeBlock := VirtualBlock.PrevFreeBlock; if VirtualBlock.PrevFreeBlock <> nil then VirtualBlock.PrevFreeBlock.NextFreeBlock := VirtualBlock.NextFreeBlock else VirtualBlock.VBlockDescriptor.FirstFreeVBlock := VirtualBlock.NextFreeBlock; OSVirtualFree(VirtualBlock.P); OSHeapFree(VirtualBlock); end; procedure LockVBlocks(VBlockDescriptor: PVBlockDescriptor); begin if {$ifdef USEISMULTITHREAD}IsMultiThread and{$endif} (InterLockedCompareExchange(VBlockDescriptor.SpinLock, 1, 0) <> 0) then begin Sleep(0); while InterLockedCompareExchange(VBlockDescriptor.SpinLock, 1, 0) <> 0 do Sleep(1); end; end; procedure ReleaseVBlocks(VBlockDescriptor: PVBlockDescriptor); {$ifdef ver170}inline; {$endif} begin VBlockDescriptor.SpinLock := 0; end; function VAllocSheet(VBlockDescriptor: PVBlockDescriptor): PSheet; var VirtualBlock: PVirtualBlock; Index: Cardinal; begin LockVBlocks(VBlockDescriptor); VirtualBlock := VBlockDescriptor.FirstFreeVBlock; if VirtualBlock = nil then begin VirtualBlock := CreateVBlock(VBlockDescriptor); if VirtualBlock = nil then begin Result := nil; ReleaseVBlocks(VBlockDescriptor); Exit; end; end; Index := GetBitIndexAndClear(VirtualBlock.Available); Result := PSheet(Cardinal(VirtualBlock.P) + Index * VBlockDescriptor.SheetSize); Result.VirtualBlock := VirtualBlock; Result.VBlockIndex := Index; if VirtualBlock.Available = 0 then begin VBlockDescriptor.FirstFreeVBlock := VirtualBlock.NextFreeBlock; if VBlockDescriptor.FirstFreeVBlock <> nil then VBlockDescriptor.FirstFreeVBlock.PrevFreeBlock := nil; end; ReleaseVBlocks(VBlockDescriptor); end; procedure VFreeSheet(Sheet: PSheet); var VirtualBlock: PVirtualBlock; VBlockDescriptor: PVBlockDescriptor; begin VirtualBlock := Sheet.VirtualBlock; VBlockDescriptor := VirtualBlock.VBlockDescriptor; LockVBlocks(VBlockDescriptor); if VirtualBlock.Available = 0 then begin VirtualBlock.NextFreeBlock := VBlockDescriptor.FirstFreeVBlock; VirtualBlock.PrevFreeBlock := nil; if VBlockDescriptor.FirstFreeVBlock <> nil then VBlockDescriptor.FirstFreeVBlock.PrevFreeBlock := VirtualBlock; VBlockDescriptor.FirstFreeVBlock := VirtualBlock; end; SetBitIndex(VirtualBlock.Available, Sheet.VBlockIndex); if VirtualBlock.Available = VBlockDescriptor.AvailableBits then DestroyVBlock(VirtualBlock); ReleaseVBlocks(VBlockDescriptor); end; (********************************************************************) // Sheet Management (********************************************************************) function CreateSheet(Bucket: PBucket): PSheet; var Size: Cardinal; VBlockDescriptor: PVBlockDescriptor; begin if Bucket.BlockSize <= $280 then // use 17 kB sheets for block sizes up to 640 bytes VBlockDescriptor := @VBlockDescriptors[0] else if Bucket.BlockSize <= $5A40 then // use 68 kB sheets for block sizes up to 22 kB VBlockDescriptor := @VBlockDescriptors[1] else // use 144 kB sheets for larger blocks VBlockDescriptor := @VBlockDescriptors[2]; Size := VBlockDescriptor.SheetSize; Result := VAllocSheet(VBlockDescriptor); if Result = nil then Exit; Bucket.ActiveSheet := Result; {$ifdef ALIGN16BYTE} Bucket.CurAddr := Cardinal(Result) + 44; // + 44 so with 4 byte overhead all final blocks are 16-byte aligned {$else} Bucket.CurAddr := Cardinal(Result) + 64; // + 64 no 16-byte alignment, but slightly better cache associativity {$endif} Bucket.MaxAddr := Cardinal(Result) + Size - Bucket.BlockSize; inc(Bucket.SheetCount); Result.Magic := MAGIC_SHEET; Result.Bucket := Bucket; if Bucket.FirstSheet = nil then begin Bucket.FirstSheet := Result; Result.PrevSheet := nil; Result.NextSheet := nil; end else begin Result.NextSheet := Bucket.FirstSheet.NextSheet; Result.PrevSheet := Bucket.FirstSheet; if Bucket.FirstSheet.NextSheet <> nil then Bucket.FirstSheet.NextSheet.PrevSheet := Result; Bucket.FirstSheet.NextSheet := Result; end; Result.BlockUsedCount := 0; Result.FirstFree := nil; Result.NextFreeSheet := nil; Result.PrevFreeSheet := nil; end; procedure DestroySheet(Sheet: PSheet); var Bucket: PBucket; begin Bucket := Sheet.Bucket; if Sheet.NextSheet <> nil then Sheet.NextSheet.PrevSheet := Sheet.PrevSheet; if Sheet.PrevSheet <> nil then Sheet.PrevSheet.NextSheet := Sheet.NextSheet else Bucket.FirstSheet := Sheet.NextSheet; if Sheet.NextFreeSheet <> nil then Sheet.NextFreeSheet.PrevFreeSheet := Sheet.PrevFreeSheet; if Sheet.PrevFreeSheet <> nil then Sheet.PrevFreeSheet.NextFreeSheet := Sheet.NextFreeSheet else Bucket.FirstFreeSheet := Sheet.NextFreeSheet; dec(Bucket.SheetCount); if Bucket.ActiveSheet = Sheet then begin Bucket.ActiveSheet := nil; Bucket.CurAddr := $100000; Bucket.MaxAddr := 0; end; VFreeSheet(Sheet); end; (********************************************************************) // Bucket Management (********************************************************************) procedure InitBuckets; // initialization of Buckets var i, n: Cardinal; Bucket: PBucket; begin for i := 0 to High(Buckets) do begin Bucket := @Buckets[i]; Bucket.SpinLock := 0; Bucket.CurAddr := $100000; Bucket.MaxAddr := 0; end; n := 0; for i := Low(BucketIndexForSize) to High(BucketIndexForSize) do begin if i*16 + 1 > Buckets[n].BlockSize then inc(n); BucketIndexForSize[i] := n; end; OSHeapInit; VDestroying := False; end; procedure FinishBuckets; // clean up memory var i: integer; Bucket: PBucket; Sheet, NextSheet: PSheet; begin VDestroying := True; for i := 0 to High(Buckets) do begin Bucket := @Buckets[i]; Sheet := Bucket.FirstSheet; while Sheet <> nil do begin NextSheet := Sheet.NextSheet; VFreeSheet(Sheet); Sheet := NextSheet; end; end; end; function GetMemBlock(Size: Integer): Pointer; asm dec eax shr eax, 4 push esi movzx esi, byte ptr [BucketIndexForSize + eax] add esi, esi add esi, esi lea esi, [Buckets + 8*esi] // esi = Bucket {$ifdef USEISMULTITHREAD} cmp IsMultiThread, 0 jz @LockOK {$endif} mov ecx, 3 // ecx = RetryCount @TryGetLock: xor eax, eax mov dl, 1 lock cmpxchg byte ptr TBucket(esi).SpinLock, dl jnz @LockNotOK @LockOK: @FreeList: mov ecx, TBucket(esi).FirstFreeSheet // ecx = Sheet test ecx, ecx jz @TestLinear // get FirstFree mov eax, TSheet(ecx).FirstFree mov edx, TBlockFree(eax).NextBlock mov TSheet(ecx).FirstFree, edx inc TSheet(ecx).BlockUsedCount test edx, edx jz @Exhausted @Finish: mov TBucket(esi).SpinLock, 0 mov TBlockUsed(eax).Sheet, ecx add eax,4 pop esi ret @TestLinear: mov eax, TBucket(esi).CurAddr // eax = Result cmp eax, TBucket(esi).MaxAddr ja @NewSheet @Linear: mov ecx, TBucket(esi).ActiveSheet // ecx = Sheet mov edx, TBucket(esi).BlockSize add TBucket(esi).CurAddr, edx inc TSheet(ecx).BlockUsedCount mov byte ptr TBucket(esi).SpinLock, 0 mov TBlockUsed(eax).Sheet, ecx add eax,4 pop esi ret @Exhausted: // sheet is exhausted mov edx, TSheet(ecx).NextFreeSheet mov TBucket(esi).FirstFreeSheet, edx test edx, edx jz @Finish mov TSheet(edx).PrevFreeSheet, 0 jmp @Finish @LockNotOK: // lock not obtained... try next bucket (max 3 times) dec ecx jz @SpinNotOK cmp TBucket(esi).BlockSize, MAX_BUCKET_MEM jnb @SpinNotOK add esi, Type(TBucket) jmp @TryGetLock @SpinNotOK: push 0 @Spin: call sleep xor eax, eax mov dl, 1 lock cmpxchg byte ptr TBucket(esi).SpinLock, dl jz @LockOK push 1 jmp @Spin @NewSheet: mov eax, esi call CreateSheet test eax, eax jz @OutOfMemory //Added by DKC mov eax, TBucket(esi).CurAddr jnz @Linear @OutOfMemory: mov byte ptr TBucket(esi).SpinLock, 0 //Added by DKC xor eax, eax pop esi ret end; function FreeMemBlock(Pntr: PBlockUsed): Integer; asm mov ecx, eax // ecx = Pntr push ebx mov ebx, TBlockUsed(eax).Sheet // ebx = Sheet push esi mov esi, TSheet(ebx).Bucket // esi = Bucket {$ifdef USEISMULTITHREAD} cmp IsMultiThread, 0 jz @LockOK {$endif} @TryGetLock: xor eax, eax mov dl, 1 lock cmpxchg byte ptr TBucket(esi).SpinLock, dl jnz @LockNotOK @LockOK: mov eax, TSheet(ebx).FirstFree test eax, eax jnz @N1 // new sheet with available blocks mov edx, TBucket(esi).FirstFreeSheet test edx, edx jz @N2 mov TSheet(edx).PrevFreeSheet, ebx @N2: mov TSheet(ebx).PrevFreeSheet, 0 mov TSheet(ebx).NextFreeSheet, edx mov TBucket(esi).FirstFreeSheet, ebx @N1: mov TBlockFree(ecx).NextBlock, eax dec TSheet(ebx).BlockUsedCount mov TSheet(ebx).FirstFree, ecx jz @EmptySheet @Finish: xor eax, eax mov byte ptr TBucket(esi).SpinLock, al pop esi pop ebx ret @LockNotOK: push ecx push 0 jmp @Spin2 @Spin1: push 1 @Spin2: call sleep xor eax, eax mov dl, 1 lock cmpxchg byte ptr TBucket(esi).SpinLock, dl jnz @Spin1 pop ecx jmp @LockOK @EmptySheet: mov eax, ebx call DestroySheet jmp @Finish end; function BucketGetMem(Size: Integer): Pointer; forward; function ReallocMemBlock(Pntr: PBlockUsed; Size, OldSize: Cardinal): Pointer; // reallocate a memory block by creating a new one and freeing the old one // with Buckets you cannot grow in place ! begin if Size > OldSize then begin // upsize... anticipate future upsizes if Size <= 128 then Size := (Size + $3F) and $FFFFFFE0 else if Size <= 256 then Size := (Size + $7F) and $FFFFFFC0 else inc(Size, Size div 4); end; Result := BucketGetMem(Size - 4); if OldSize < Size then Size := OldSize; Size := (Size + $00000003) and $FFFFFFFC; // round for Move operation FastCodeMove(Pointer(Integer(Pntr) + 4)^, Result^, Size - 4); FreeMemBlock(Pntr); end; function ReallocHeapBlock(Pntr: PHeapBlockUsed; Size, OldSize: Cardinal): Pointer; // reallocate a Heap memory block by creating a new one and freeing the old one begin if Size > OldSize then begin // upsize... anticipate future upsizes if already resized at least EXACT_REALLOC_COUNT times if (Pntr.ReallocCount >= EXACT_REALLOC_COUNT) and (Size < 2 * OldSize) then inc(Size, Size div 2); end else begin if Pntr.ReallocCount < EXACT_REALLOC_COUNT then begin // possibly small downsize... check whether the original block would be fine if (Size > MAX_BUCKET_MEM) and ((Size + $0000FFFF) and $FFFF0000 = OldSize) then begin inc(Pntr.ReallocCount); Result := Pointer(Integer(Pntr) + 16); Exit; end; end; end; Result := BucketGetMem(Size - 16); if OldSize < Size then Size := OldSize; Size := (Size + $00000003) and $FFFFFFFC; // round for Move operation if Integer(PBlockUsed(Integer(Result) - 4).Sheet) = MAGIC_BLOCK_HEAP_ALLOC then PHeapBlockUsed(Integer(Result) - 16).ReallocCount := Pntr.ReallocCount + 1; // increment Realloc count FastCodeMove(Pointer(Integer(Pntr) + 16)^, Result^, Size - 16); {$ifdef USECACHEOFFSET} // avoid Win98 VirtualFree problem Pntr := PHeapBlockUsed(Integer(Pntr) and $FFFF0000); {$endif} OSVirtualFree(Pntr); end; {$ifdef USECACHEOFFSET} const CacheOffSetMask = $7C0; CacheOffSetInc = $5F0; var CacheOffSet: integer; {$endif} function GetHeapBlock(Size: Integer): Pointer; {$ifdef USECACHEOFFSET} var OffSet: integer; {$endif} begin inc(Size, 12); {$ifdef USECACHEOFFSET} inc(CacheOffset, CacheOffSetInc); OffSet := CacheOffset and CacheOffSetMask; if (Size and $FFFF) + OffSet >= $10000 then OffSet := 0; Size := (Size + OffSet + $FFFF) and $FFFF0000; Result := OSVirtualAlloc(Size); inc(Integer(Result), OffSet); Dec(Size, OffSet); {$else} Size := (Size + $FFFF) and $FFFF0000; Result := OSVirtualAlloc(Size); {$endif} if Result <> nil then begin PHeapBlockUsed(Result).ReallocCount := 0; PHeapBlockUsed(Result).Size := Size; PHeapBlockUsed(Result).Sheet := PSheet(MAGIC_BLOCK_HEAP_ALLOC); inc(Integer(Result), 16); end; end; (********************************************************************) // Global Memory Management Functions (********************************************************************) function BucketGetMem(Size: Integer): Pointer; asm add eax, 4 cmp eax, MAX_BUCKET_MEM jbe GetMemBlock @FromHeap: jmp GetHeapBlock end; function BucketFreeMem(Pntr: Pointer): Integer; asm mov edx, [eax - 4] sub eax, 4 cmp edx, MAGIC_BLOCK_HEAP_ALLOC jz @FromHeap cmp TSheet(edx).Magic, MAGIC_SHEET jz FreeMemBlock @Error: mov eax, 1 ret @FromHeap: sub eax, 12 {$ifdef USECACHEOFFSET} // avoid Win98 VirtualFree problem and eax, $FFFF0000 {$endif} call OSVirtualFree cmp eax, 1 sbb eax, eax ret end; function BucketReallocMem(Pntr: Pointer; Size: Integer): Pointer; asm push edi lea edi, [eax - 4] // edi = Pntr mov eax, [edi] // eax = Sheet cmp eax, MAGIC_BLOCK_HEAP_ALLOC jz @Heap cmp TSheet(eax).Magic, MAGIC_SHEET jnz @Error add edx, 4 // edx = Size mov ecx, TSheet(eax).Bucket mov ecx, TBucket(ecx).BlockSize // ecx = OldSize cmp edx, ecx jbe @Reduce @DoRealloc: // mov ecx, ecx // mov edx, edx mov eax, edi pop edi jmp ReallocMemBlock @Reduce: mov eax, ecx cmp ecx, 128 jbe @KeepSame shr eax, 2 cmp edx, eax jb @DoRealloc @KeepSame: lea eax, [edi + 4] pop edi ret @Heap: sub edi, 12 add edx, 16 // edx = Size mov eax, THeapBlockUsed(edi).Size mov ecx, eax // ecx = OldSize cmp THeapBlockUsed(edi).ReallocCount, EXACT_REALLOC_COUNT jb @DoHeapRealloc cmp edx, eax ja @DoHeapRealloc shr eax, 2 cmp edx, eax jnb @KeepSame2 @DoHeapRealloc: // mov ecx, ecx //mov edx, edx mov eax, edi pop edi jmp ReallocHeapBlock @KeepSame2: lea eax, [edi + 16] pop edi ret @Error: xor eax, eax pop edi ret end; (********************************************************************) // unit initialization functions (********************************************************************) const MemMgr: TMemoryManager = ( GetMem: BucketGetMem; FreeMem: BucketFreeMem; ReallocMem: BucketReallocMem ); var SysMemMgr: TMemoryManager; procedure InitMemoryManager; begin InitBuckets; GetMemoryManager(SysMemMgr); SetMemoryManager(MemMgr); {$ifdef USESYSTEMMOVE} FastCodeMove := System.Move; // will be patched by FastMove {$else} FastCodeMove := Move_IA32; {$endif} end; procedure FinishMemoryManager; begin SetMemoryManager(SysMemMgr); FinishBuckets; end; initialization InitMemoryManager; finalization FinishMemoryManager; end.
unit ClientList; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseDocked, Vcl.StdCtrls, RzLabel, Vcl.ExtCtrls, RzPanel, DockedFormIntf, Data.DB, Vcl.Mask, RzEdit, Vcl.Grids, Vcl.DBGrids, RzDBGrid, System.Rtti, ADODB, ClientListIntf; type TfrmClientList = class(TfrmBaseDocked, IDockedForm, IClientFilter) pnlSearch: TRzPanel; Label1: TLabel; edSearchKey: TRzEdit; pnlDockMain: TRzPanel; lblRecentlyAdded: TRzURLLabel; lblActiveClients: TRzURLLabel; lblAllClients: TRzURLLabel; cbxNonClients: TCheckBox; pnlList: TRzPanel; grList: TRzDBGrid; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure grListDblClick(Sender: TObject); procedure edSearchKeyChange(Sender: TObject); procedure cbxNonClientsClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure lblRecentlyAddedClick(Sender: TObject); procedure lblActiveClientsClick(Sender: TObject); procedure lblAllClientsClick(Sender: TObject); private { Private declarations } procedure InitSearchParams; public { Public declarations } procedure SetTitle(const title: string); procedure FilterList(const filterType: TClientFilterType; const nonClients: boolean = false); end; implementation {$R *.dfm} uses AppData, FormsUtil, DockIntf, Client, AppConstants, ClientListParams; procedure TfrmClientList.InitSearchParams; begin if not Assigned(clp) then clp := TClientListParams.Create; // set search values edSearchKey.Text := clp.SearchKey; cbxNonClients.Checked := clp.ShowNonClients; end; procedure TfrmClientList.lblActiveClientsClick(Sender: TObject); begin inherited; FilterList(cftActive); end; procedure TfrmClientList.lblAllClientsClick(Sender: TObject); begin inherited; FilterList(cftAll); end; procedure TfrmClientList.lblRecentlyAddedClick(Sender: TObject); begin inherited; FilterList(cftRecent); end; procedure TfrmClientList.FormClose(Sender: TObject; var Action: TCloseAction); begin // save search params clp.SearchKey := edSearchKey.Text; clp.ShowNonClients := cbxNonClients.Checked; OpenGridDataSources(pnlList,false); inherited; end; procedure TfrmClientList.FormCreate(Sender: TObject); begin inherited; InitSearchParams; end; procedure TfrmClientList.grListDblClick(Sender: TObject); var id, displayId: string; intf: IDock; begin if grList.DataSource.DataSet.RecordCount > 0 then begin id := grList.DataSource.DataSet.FieldByName('entity_id').AsString; displayId := grList.DataSource.DataSet.FieldByName('display_id').AsString; cln := TClient.Create; cln.Id := id; cln.DisplayId := displayId; if Supports(Application.MainForm,IDock,intf) then intf.DockForm(fmClientMain); end; end; procedure TfrmClientList.SetTitle(const title: string); begin lblTitle.Caption := title; end; procedure TfrmClientList.cbxNonClientsClick(Sender: TObject); begin with dmApplication.dstClients.Parameters do ParamByName('@non_clients').Value := Ord(cbxNonClients.Checked); OpenGridDataSources(pnlList); end; procedure TfrmClientList.edSearchKeyChange(Sender: TObject); var filter: string; begin inherited; if Trim(edSearchKey.Text) <> '' then filter := 'name like ''*' + edSearchKey.Text + '*''' else filter := ''; grList.DataSource.DataSet.Filter := filter; end; procedure TfrmClientList.FilterList(const filterType: TClientFilterType; const nonClients: Boolean = False); begin with (grList.DataSource.DataSet as TADODataSet).Parameters do begin case filterType of cftAll: ParamByName('@filter_type').Value := 0; cftActive: ParamByName('@filter_type').Value := 1; cftRecent: ParamByName('@filter_type').Value := 2; end; ParamByName('@non_clients').Value := Ord(cbxNonClients.Checked); end; OpenGridDataSources(pnlList); end; end.
unit xClientInfo; interface uses System.Classes, System.SysUtils, System.IniFiles, xStudentInfo, xFunction, xClientType, xConsts; type TLoginEvent = procedure(Sender: TObject; nStuID : Integer) of object; type TClientInfo = class private FClientIP: string; FIsConnected: Boolean; FOnChanged: TNotifyEvent; FClientSN: Integer; FStudentInfo: TStudentInfo; FStartTime: TDateTime; FRemark: string; FClientPort: Integer; FEndTime: TDateTime; FSubList: TStringList; FClientState: TClientState; FCanRevData : Boolean; // 是否可以接收数据 FRevData : TBytes; // 接收的数据包 FOnStuLogin: TLoginEvent; FOnStuReady: TNotifyEvent; procedure ReadINI; procedure WriteINI; procedure SetClientSN(const Value: Integer); /// <summary> /// 解析数据 /// </summary> procedure AnalysisData; procedure SetClientState(const Value: TClientState); function GetClientName: string; public constructor Create; destructor Destroy; override; /// <summary> /// 客户端编号(设置编号时读取INI配置信息) /// </summary> property ClientSN : Integer read FClientSN write SetClientSN; /// <summary> /// 客户端名 /// </summary> property ClientName : string read GetClientName; /// <summary> /// 客户端IP地址 /// </summary> property ClientIP : string read FClientIP write FClientIP; /// <summary> /// 客户端连接端口 /// </summary> property ClientPort : Integer read FClientPort write FClientPort; /// <summary> /// 客户端状态 /// </summary> property ClientState : TClientState read FClientState write SetClientState; /// <summary> /// 是否连接 /// </summary> property IsConnected : Boolean read FIsConnected write FIsConnected; /// <summary> /// 考生信息 /// </summary> property StudentInfo : TStudentInfo read FStudentInfo write FStudentInfo; /// <summary> /// 考生的考题列表 /// </summary> property SubList : TStringList read FSubList write FSubList; /// <summary> /// 开始考试时间 /// </summary> property StartTime : TDateTime read FStartTime write FStartTime; /// <summary> /// 结束考试时间 /// </summary> property EndTime : TDateTime read FEndTime write FEndTime; /// <summary> /// 备注 /// </summary> property Remark : string read FRemark write FRemark; public /// <summary> /// 接收数据包 /// </summary> procedure RevPacksData(sIP: string; nPort :Integer;aPacks: TArray<Byte>); /// <summary> /// 改变事件 /// </summary> property OnChanged : TNotifyEvent read FOnChanged write FOnChanged; /// <summary> /// 学员请求登录事件 /// </summary> property OnStuLogin : TLoginEvent read FOnStuLogin write FOnStuLogin; /// <summary> /// 学员考试准备事件 /// </summary> property OnStuReady : TNotifyEvent read FOnStuReady write FOnStuReady; end; implementation { TClientInfo } procedure TClientInfo.AnalysisData; var aBuf : TBytes; nStuID : Integer; begin aBuf := AnalysisRevData(FRevData); if Assigned(aBuf) then begin // 解析数据 if Length(aBuf) = 5 then begin // 反馈状态 if aBuf[1] = $07 then begin ClientState := TClientState(aBuf[2]); end; end else if Length(aBuf) = 7 then begin if Assigned(FOnStuLogin) then begin nStuID := aBuf[2] shl 16 + aBuf[3] shl 8 + aBuf[4]; FOnStuLogin(Self, nStuID); end; end // 考试准备 else if Length(aBuf) = 4 then begin // 反馈状态 if aBuf[1] = $08 then begin if Assigned(FOnStuReady) then begin FOnStuReady(Self); end; end; end; end; end; constructor TClientInfo.Create; begin FStudentInfo:= TStudentInfo.Create; FSubList:= TStringList.Create; FCanRevData := False; FClientState := esDisconn; end; destructor TClientInfo.Destroy; begin WriteINI; FStudentInfo.free; // ClearStringList(FSubList); FSubList.Free; inherited; end; function TClientInfo.GetClientName: string; begin case FClientState of esDisconn, esConned : Result := FClientIP; else if StudentInfo.stuName <> '' then begin Result := StudentInfo.stuName; end else begin Result := FClientIP; end; end; end; procedure TClientInfo.ReadINI; var s : string; begin s := 'Client' + IntToStr(FClientSN); with TIniFile.Create(spubFilePath + 'OptionClient.ini') do begin FClientIP := ReadString(s, 'ClientIP', '192.168.1.' + IntToStr(100+FClientSN)); Free; end; end; procedure TClientInfo.RevPacksData(sIP: string; nPort: Integer; aPacks: TArray<Byte>); procedure AddData(nData : Byte); var nLen : Integer; begin nLen := Length(FRevData); SetLength(FRevData, nLen + 1); FRevData[nLen] := nData; end; var i : Integer; nByte : Byte; begin for i := 0 to Length(aPacks) - 1 do begin nByte := aPacks[i]; if nByte = $7E then begin if Length(FRevData) = 0 then begin FCanRevData := True; AddData(nByte); end else begin if FRevData[Length(FRevData)-1] = $7E then begin SetLength(FRevData, 0); FCanRevData := True; AddData(nByte); end else begin AddData(nByte); // 转译字符处理 AnalysisData; SetLength(FRevData, 0); FCanRevData := False; end; end; end else begin if FCanRevData then begin AddData(nByte); end; end; end; end; procedure TClientInfo.SetClientSN(const Value: Integer); begin FClientSN := Value; ReadINI; end; procedure TClientInfo.SetClientState(const Value: TClientState); begin FClientState := Value; if FClientState = esConned then begin FStudentInfo.Clear; end; if Assigned(FOnChanged) then begin FOnChanged(Self); end; end; procedure TClientInfo.WriteINI; var s : string; begin s := 'Client' + IntToStr(FClientSN); with TIniFile.Create(spubFilePath + 'OptionClient.ini') do begin WriteString(s, 'ClientIP', FClientIP); Free; end; end; end.
unit logfile; interface uses sysutils; procedure LogfileWriteLn(level, str: string); procedure LogfileWriteException(e: Exception); implementation uses JclDebug, classes, vcl.forms, winapi.windows; var _logfile: TextFile; ProcessID: Cardinal; //procedure EventLogWriteLn(level, str: string; EventId: Word = 0); //var // h: THandle; //begin // str := Format('[%d] %s %s', [ProcessID, level, str]); // // h := RegisterEventSource(nil, PChar(ExtractFileName(Application.ExeName))); // if h > 0 then // try // ReportEvent(h, 0, 0, EventId, nil, 1, 0, @str, nil); // finally // DeregisterEventSource(h); // end; //end; procedure LogfileOpen; var ADir, ALogFileName: string; begin GetWindowThreadProcessId(Application.Handle, ProcessID); ADir := ExtractFileDir(Application.ExeName) + '\Logs'; if not DirectoryExists(ADir) then CreateDir(ADir); ALogFileName := ADir + '\' + FormatDateTime('YYYY-MM-dd', now) + '.gui.log'; AssignFile(_logfile, ALogFileName, CP_UTF8); if FileExists(ALogFileName) then Append(_logfile) else Rewrite(_logfile); end; procedure LogfileWriteLn(level, str: string); begin Writeln(_logfile, FormatDateTime('hh:nn:ss', now), ' ', '[', ProcessID, ']', ' ', level, ' ', str); //EventLogWriteLn(level, str); end; function strReplaceLn(s: string): string; begin result := stringreplace(Trim(s), #13, ':', [rfReplaceAll, rfIgnoreCase]) end; procedure LogfileWriteException(e: Exception); var stackList: TJclStackInfoList; // JclDebug.pas sl: TStringList; I: Integer; begin stackList := JclCreateStackList(false, 1, Caller(1, false)); sl := TStringList.Create; stackList.AddToStrings(sl, false, false, false, false); LogfileWriteLn('EXN', e.ClassName + ' ' + strReplaceLn(e.Message) + #10 +sl.Text); sl.Free; stackList.Free; end; initialization LogfileOpen; finalization CloseFile(_logfile); end.
{*******************************************************} { } { Delphi FireMonkey Platform } { } { Copyright(c) 2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit FMX_Dialogs; {$I FMX_Defines.inc} interface uses Classes, SysUtils, Types, UITypes, FMX_Types, FMX_Forms, FMX_Printer; {$SCOPEDENUMS ON} type { TCommonDialog } TCommonDialog = class(TFmxObject) private FHelpContext: THelpContext; FOnClose: TNotifyEvent; FOnShow: TNotifyEvent; protected procedure DoClose; dynamic; procedure DoShow; dynamic; function DoExecute: Boolean; virtual; abstract; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function Execute: Boolean; overload; virtual; published property HelpContext: THelpContext read FHelpContext write FHelpContext default 0; property OnClose: TNotifyEvent read FOnClose write FOnClose; property OnShow: TNotifyEvent read FOnShow write FOnShow; end; { TOpenDialog } TOpenDialog = class(TCommonDialog) private FHistoryList: TWideStrings; FOptions: TOpenOptions; FFilter: WideString; FFilterIndex: Integer; FInitialDir: WideString; FTitle: WideString; FDefaultExt: WideString; FFileName: TFileName; FFiles: TWideStrings; FOnSelectionChange: TNotifyEvent; FOnFolderChange: TNotifyEvent; FOnTypeChange: TNotifyEvent; FOnCanClose: TCloseQueryEvent; function GetFileName: TFileName; function GetFiles: TWideStrings; function GetFilterIndex: Integer; function GetInitialDir: WideString; function GetTitle: WideString; procedure ReadFileEditStyle(Reader: TReader); procedure SetFileName(Value: TFileName); procedure SetHistoryList(Value: TWideStrings); procedure SetInitialDir(const Value: WideString); procedure SetTitle(const Value: WideString); protected function DoCanClose: Boolean; dynamic; procedure DoSelectionChange; dynamic; procedure DoFolderChange; dynamic; procedure DoTypeChange; dynamic; procedure DefineProperties(Filer: TFiler); override; function DoExecute: Boolean; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Files: TWideStrings read GetFiles; property HistoryList: TWideStrings read FHistoryList write SetHistoryList; published property DefaultExt: WideString read FDefaultExt write FDefaultExt; property FileName: TFileName read GetFileName write SetFileName; property Filter: WideString read FFilter write FFilter; property FilterIndex: Integer read GetFilterIndex write FFilterIndex default 1; property InitialDir: WideString read GetInitialDir write SetInitialDir; property Options: TOpenOptions read FOptions write FOptions default [TOpenOption.ofHideReadOnly, TOpenOption.ofEnableSizing]; property Title: WideString read GetTitle write SetTitle; property OnCanClose: TCloseQueryEvent read FOnCanClose write FOnCanClose; property OnFolderChange: TNotifyEvent read FOnFolderChange write FOnFolderChange; property OnSelectionChange: TNotifyEvent read FOnSelectionChange write FOnSelectionChange; property OnTypeChange: TNotifyEvent read FOnTypeChange write FOnTypeChange; end; { TSaveDialog } TSaveDialog = class(TOpenDialog) protected function DoExecute: Boolean; override; end; { TPrintDialog } type TPrintDialog = class(TCommonDialog) private FCollate: Boolean; FCopies: Integer; FMinPage: Integer; FMaxPage: Integer; FOptions: TPrintDialogOptions; FFromPage: Integer; FToPage: Integer; FPrintRange: TPrintRange; FPrintToFile: Boolean; procedure SetNumCopies(Value: Integer); protected function DoExecute: Boolean; override; published property Collate: Boolean read FCollate write FCollate default False; property Copies: Integer read FCopies write SetNumCopies default 0; property FromPage: Integer read FFromPage write FFromPage default 0; property MinPage: Integer read FMinPage write FMinPage default 0; property MaxPage: Integer read FMaxPage write FMaxPage default 0; property Options: TPrintDialogOptions read FOptions write FOptions default []; property PrintToFile: Boolean read FPrintToFile write FPrintToFile default False; property PrintRange: TPrintRange read FPrintRange write FPrintRange default TPrintRange.prAllPages; property ToPage: Integer read FToPage write FToPage default 0; end; { TPrinterSetupDialog } TPrinterSetupDialog = class(TCommonDialog) protected function DoExecute: Boolean; override; end; { TPageSetupDialog } TPageSetupPaintingEvent = procedure (Sender: TObject; const PaperSize: SmallInt; const Orientation: TPrinterOrientation; const PageType: TPageType; var DoneDrawing: Boolean) of object; TPaintPageEvent = procedure(Sender: TObject; Canvas: TCanvas; PageRect: TRect; var DoneDrawing: Boolean) of object; TPageSetupDialog = class(TCommonDialog) private FOptions: TPageSetupDialogOptions; FMargin: TRect; FMinMargin: TRect; FPaperSize: TPointF; // FMinMarginLeft: Integer; // FMinMarginTop: Integer; // FMinMarginRight: Integer; // FMinMarginBottom: Integer; // FMarginLeft: Integer; // FMarginTop: Integer; // FMarginRight: Integer; // FMarginBottom: Integer; // FPageWidth: Integer; // FPageHeight: Integer; FPainting: TPageSetupPaintingEvent; FUnits: TPageMeasureUnits; FOnDrawRetAddress: TPaintPageEvent; FOnDrawMinMargin: TPaintPageEvent; FOnDrawEnvStamp: TPaintPageEvent; FOnDrawFullPage: TPaintPageEvent; FOnDrawGreekText: TPaintPageEvent; FOnDrawMargin: TPaintPageEvent; function getMinMarginLeft: Integer; function getMinMarginTop: Integer; function getMinMarginRight: Integer; function getMinMarginBottom: Integer; function getMarginLeft: Integer; function getMarginTop: Integer; function getMarginRight: Integer; function getMarginBottom: Integer; function getPageWidth: Single; function getPageHeight: Single; procedure setMinMarginLeft(Value: Integer); procedure setMinMarginTop(Value: Integer); procedure setMinMarginRight(Value: Integer); procedure setMinMarginBottom(Value: Integer); procedure setMarginLeft(Value: Integer); procedure setMarginTop(Value: Integer); procedure setMarginRight(Value: Integer); procedure setMarginBottom(Value: Integer); procedure setPageWidth(Value: Single); procedure setPageHeight(Value: Single); protected function DoExecute: Boolean; override; public constructor Create(AOwner: TComponent); override; published property MinMarginLeft: Integer read getMinMarginLeft write setMinMarginLeft; property MinMarginTop: Integer read getMinMarginTop write setMinMarginTop; property MinMarginRight: Integer read getMinMarginRight write setMinMarginRight; property MinMarginBottom: Integer read getMinMarginBottom write setMinMarginBottom; property MarginLeft: Integer read getMarginLeft write setMarginLeft; property MarginTop: Integer read getMarginTop write setMarginTop; property MarginRight: Integer read getMarginRight write setMarginRight; property MarginBottom: Integer read getMarginBottom write setMarginBottom; property Options: TPageSetupDialogOptions read FOptions write FOptions default [TPageSetupDialogOption.psoDefaultMinMargins]; property PageWidth: Single read getPageWidth write setPageWidth; property PageHeight: Single read getPageHeight write setPageHeight; property Units: TPageMeasureUnits read FUnits write FUnits default TPageMeasureUnits.pmDefault; property Painting: TPageSetupPaintingEvent read FPainting write FPainting; property OnDrawFullPage: TPaintPageEvent read FOnDrawFullPage write FOnDrawFullPage; property OnDrawMinMargin: TPaintPageEvent read FOnDrawMinMargin write FOnDrawMinMargin; property OnDrawMargin: TPaintPageEvent read FOnDrawMargin write FOnDrawMargin; property OnDrawGreekText: TPaintPageEvent read FOnDrawGreekText write FOnDrawGreekText; property OnDrawEnvStamp: TPaintPageEvent read FOnDrawEnvStamp write FOnDrawEnvStamp; property OnDrawRetAddress: TPaintPageEvent read FOnDrawRetAddress write FOnDrawRetAddress; end; const mbYesNo = [TMsgDlgBtn.mbYes, TMsgDlgBtn.mbNo]; mbYesNoCancel = [TMsgDlgBtn.mbYes, TMsgDlgBtn.mbNo, TMsgDlgBtn.mbCancel]; mbYesAllNoAllCancel = [TMsgDlgBtn.mbYes, TMsgDlgBtn.mbYesToAll, TMsgDlgBtn.mbNo, TMsgDlgBtn.mbNoToAll, TMsgDlgBtn.mbCancel]; mbOKCancel = [TMsgDlgBtn.mbOK, TMsgDlgBtn.mbCancel]; mbAbortRetryIgnore = [TMsgDlgBtn.mbAbort, TMsgDlgBtn.mbRetry, TMsgDlgBtn.mbIgnore]; mbAbortIgnore = [TMsgDlgBtn.mbAbort, TMsgDlgBtn.mbIgnore]; function CreateMessageDialog(const Msg: WideString; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons): TForm; overload; function CreateMessageDialog(const Msg: WideString; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; DefaultButton: TMsgDlgBtn): TForm; overload; function MessageDlg(const Msg: WideString; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: Longint): Integer; overload; inline; function MessageDlg(const Msg: WideString; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: Longint; DefaultButton: TMsgDlgBtn): Integer; overload; inline; function MessageDlgPos(const Msg: WideString; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: Longint; X, Y: Integer): Integer; overload; inline; function MessageDlgPos(const Msg: WideString; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: Longint; X, Y: Integer; DefaultButton: TMsgDlgBtn): Integer; overload; inline; function MessageDlgPosHelp(const Msg: WideString; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: Longint; X, Y: Integer; const HelpFileName: WideString): Integer; overload; function MessageDlgPosHelp(const Msg: WideString; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: Longint; X, Y: Integer; const HelpFileName: WideString; DefaultButton: TMsgDlgBtn): Integer; overload; procedure ShowMessage(const Msg: WideString); procedure ShowMessageFmt(const Msg: WideString; Params: array of const); procedure ShowMessagePos(const Msg: WideString; X, Y: Integer); {$IFNDEF FPC} type TInputCloseQueryEvent = procedure (Sender: TObject; const Values: array of string; var CanClose: Boolean) of object; TInputCloseQueryFunc = reference to function (const Values: array of string): Boolean; { Input dialog } function InputBox(const ACaption, APrompt, ADefault: WideString): WideString; function InputQuery(const ACaption: WideString; const APrompts: array of string; var AValues: array of string; CloseQueryFunc: TInputCloseQueryFunc = nil): Boolean; overload; function InputQuery(const ACaption: WideString; const APrompts: array of string; var AValues: array of string; CloseQueryEvent: TInputCloseQueryEvent; Context: TObject = nil): Boolean; overload; function InputQuery(const ACaption, APrompt: WideString; var Value: WideString): Boolean; overload; {$ENDIF} implementation uses Math, FMX_Consts, FMX_Platform, FMX_Controls, FMX_Objects, FMX_Layouts, FMX_Edit; type TMessageForm = class(TForm) private Message: TLabel; procedure HelpButtonClick(Sender: TObject); protected procedure CustomKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure WriteToClipBoard(const Text: WideString); function GetFormText: WideString; // public // constructor CreateNew(AOwner: TComponent; Dummy: Integer = 0); override; end; //constructor TMessageForm.CreateNew(AOwner: TComponent; Dummy: Integer = 0); //begin // inherited CreateNew(AOwner, Dummy); // // Font.Assign(Screen.MessageFont); //end; procedure TMessageForm.HelpButtonClick(Sender: TObject); begin // Application.HelpContext(HelpContext); end; procedure TMessageForm.CustomKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Shift = [ssCtrl]) and (Key = Word('C')) then begin SysUtils.Beep; WriteToClipBoard(GetFormText); end; end; procedure TMessageForm.WriteToClipBoard(const Text: WideString); begin Platform.SetClipboard(Text); end; function TMessageForm.GetFormText: WideString; var DividerLine, ButtonCaptions: WideString; I: Integer; begin DividerLine := StringOfChar('-', 27) + sLineBreak; for I := 0 to ComponentCount - 1 do if Components[I] is TButton then ButtonCaptions := ButtonCaptions + TButton(Components[I]).Text + StringOfChar(' ', 3); ButtonCaptions := StringReplace(ButtonCaptions,'&','', [rfReplaceAll]); Result := Format('%s%s%s%s%s%s%s%s%s%s', [DividerLine, Caption, sLineBreak, DividerLine, Message.Text, sLineBreak, DividerLine, ButtonCaptions, sLineBreak, DividerLine]); end; function MulDiv(nNumber, nNumerator, nDenominator: Single): Single; overload; inline; begin Result := (nNumber * nNumerator) / nDenominator; end; function MulDiv(nNumber, nNumerator, nDenominator: Double): Double; overload; inline; begin Result := (nNumber * nNumerator) / nDenominator; end; function GetAveCharSize(Canvas: TCanvas): TPointF; var I: Integer; Buffer: WideString; begin SetLength(Buffer, 52); for I := 1 to 26 do Buffer[I] := Chr((I - 1) + Ord('A')); for I := 27 to 52 do Buffer[I] := Chr((I - 27) + Ord('a')); Result := PointF(Canvas.TextWidth(Buffer), Canvas.TextHeight(Buffer)); Result.X := Result.X / 52; end; var Captions: array[TMsgDlgType] of Pointer = (@SMsgDlgWarning, @SMsgDlgError, @SMsgDlgInformation, @SMsgDlgConfirm, nil); IconIDs: array[TMsgDlgType] of String = ('iconwarning', 'iconerror', 'iconinformation', 'iconconfirmation', ''); // do not localize it is style ButtonCaptions: array[TMsgDlgBtn] of Pointer = ( @SMsgDlgYes, @SMsgDlgNo, @SMsgDlgOK, @SMsgDlgCancel, @SMsgDlgAbort, @SMsgDlgRetry, @SMsgDlgIgnore, @SMsgDlgAll, @SMsgDlgNoToAll, @SMsgDlgYesToAll, @SMsgDlgHelp, @SMsgDlgClose); ButtonNames: array[TMsgDlgBtn] of string = ( 'Yes', 'No', 'OK', 'Cancel', 'Abort', 'Retry', 'Ignore', 'All', 'NoToAll', 'YesToAll', 'Help', 'Close'); ModalResults: array[TMsgDlgBtn] of Integer = ( mrYes, mrNo, mrOk, mrCancel, mrAbort, mrRetry, mrIgnore, mrAll, mrNoToAll, mrYesToAll, 0, mrClose); ButtonWidths : array[TMsgDlgBtn] of single; // initialized to zero function StripHotKey(const AText: WideString): WideString; begin Result := AText; if Pos('&', AText) <>0 then Delete(Result, Pos('&', Result), 1); end; function CreateMessageDialog(const Msg: WideString; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; DefaultButton: TMsgDlgBtn): TForm; const mcHorzMargin = 8; mcVertMargin = 8; mcHorzSpacing = 10; mcVertSpacing = 10; mcButtonWidth = 50; mcButtonHeight = 14; mcButtonSpacing = 4; var DialogUnits: TPointF; HorzMargin, VertMargin, HorzSpacing, VertSpacing, ButtonWidth, ButtonHeight, ButtonSpacing, ButtonGroupWidth, IconTextWidth, IconTextHeight, X, ALeft: Single; ButtonCount: Integer; B, CancelButton: TMsgDlgBtn; TextRect: TRectF; LButton: TButton; IconStyle: WideString; S: TFmxObject; NewMsg: WideString; lblMessage: TLabel; function CreateLabel(Form: TForm; Msg: WideString): TLabel; begin Result := TLabel.Create(Form); with Result do begin Name := 'Message'; Parent := Form; WordWrap := True; TextAlign := TTextAlign.taLeading; VertTextAlign := TTextAlign.taLeading; Text := Msg; //BiDiMode := Form.BiDiMode; if (Application.DefaultStyles <> nil) and (Application.DefaultStyles.FindStyleResource('messagelabelstyle') <> nil) then StyleLookup := 'messagelabelstyle'; end; end; begin Result := TMessageForm.CreateNew(Application); with Result do begin if Application.DefaultStyles <> nil then begin S := Application.DefaultStyles.FindStyleResource('messagestyle'); if S <> nil then begin with TStyledControl.Create(Result) do begin Parent := Result; StyleLookup := 'messagestyle'; Align := TAlignLayout.alContents; end; Result.Transparency := True; end; end; BeginUpdate; try BiDiMode := Application.BiDiMode; BorderStyle := TFmxFormBorderStyle.bsSingle; BorderIcons := [TBorderIcon.biSystemMenu]; // OnKeyDown := TMessageForm(Result).CustomKeyDown; Position := TFormPosition.poDesigned; DialogUnits := GetAveCharSize(Canvas); HorzMargin := mcHorzMargin * DialogUnits.X / 4; VertMargin := mcVertMargin * DialogUnits.Y / 8; HorzSpacing := mcHorzSpacing * DialogUnits.X / 4; VertSpacing := mcVertSpacing * DialogUnits.Y / 8; ButtonWidth := mcButtonWidth * DialogUnits.X / 4; finally EndUpdate; end; for B := Low(TMsgDlgBtn) to High(TMsgDlgBtn) do begin if B in Buttons then begin if ButtonWidths[B] = 0 then begin TextRect := RectF(0, 0, 0, 0); Canvas.MeasureText(TextRect, LoadResString(ButtonCaptions[B]), False, [], TTextAlign.taLeading, TTextAlign.taLeading); ButtonWidths[B] := TextRect.Right - TextRect.Left + 8; end; if ButtonWidths[B] > ButtonWidth then ButtonWidth := ButtonWidths[B]; end; end; ButtonHeight := mcButtonHeight * DialogUnits.Y / 8; ButtonSpacing := mcButtonSpacing * DialogUnits.X / 4; NewMsg := Translate(Msg); lblMessage := CreateLabel(Result, NewMsg); TMessageForm(Result).Message := lblMessage; Canvas.Font.Assign(lblMessage.Font); if NewMsg <> '' then begin TextRect := RectF(0, 0, Platform.GetScreenSize.X / 2, 0); Canvas.MeasureText(TextRect, NewMsg, True, [], TTextAlign.taLeading, TTextAlign.taLeading); end else TextRect := RectF(0, 0, 0, 0); TextRect.Right := TextRect.Right + 1; // add some extra space to disble text wrapping IconTextWidth := TextRect.Right + 8; IconTextHeight := TextRect.Bottom; IconStyle := IconIDs[DlgType]; if (Application.DefaultStyles <> nil) and (Application.DefaultStyles.FindStyleResource(IconStyle) <> nil) then begin IconTextWidth := IconTextWidth + 64 + HorzSpacing; if IconTextHeight < 64 then IconTextHeight := 64; end; ALeft := IconTextWidth - TextRect.Right + HorzMargin; lblMessage.SetBounds(ALeft, VertMargin, TextRect.Right + 3, TextRect.Bottom); ButtonCount := 0; for B := Low(TMsgDlgBtn) to High(TMsgDlgBtn) do if B in Buttons then Inc(ButtonCount); ButtonGroupWidth := 0; if ButtonCount <> 0 then ButtonGroupWidth := ButtonWidth * ButtonCount + ButtonSpacing * (ButtonCount - 1); ClientWidth := Round(Max(IconTextWidth, ButtonGroupWidth) + HorzMargin * 2); ClientHeight := Round(IconTextHeight + ButtonHeight + VertSpacing + VertMargin * 2); Left := round((Platform.GetScreenSize.X / 2) - (Width div 2)); Top := round((Platform.GetScreenSize.Y / 2) - (Height div 2)); if DlgType <> TMsgDlgType.mtCustom then Caption := LoadResString(Captions[DlgType]) else Caption := Application.Title; if (Application.DefaultStyles <> nil) and (Application.DefaultStyles.FindStyleResource(IconStyle) <> nil) then with TStyledControl.Create(Result) do begin Name := 'Image'; Parent := Result; StyleLookup := IconStyle; SetBounds(HorzMargin, VertMargin, 64, 64); end; if TMsgDlgBtn.mbCancel in Buttons then CancelButton := TMsgDlgBtn.mbCancel else if TMsgDlgBtn.mbNo in Buttons then CancelButton := TMsgDlgBtn.mbNo else CancelButton := TMsgDlgBtn.mbOk; X := (ClientWidth - ButtonGroupWidth) / 2; for B := Low(TMsgDlgBtn) to High(TMsgDlgBtn) do if B in Buttons then begin LButton := TButton.Create(Result); with LButton do begin Name := ButtonNames[B]; Parent := Result; Text := StripHotKey(LoadResString(ButtonCaptions[B])); ModalResult := ModalResults[B]; if B = DefaultButton then begin Default := True; ActiveControl := LButton; end; if B = CancelButton then Cancel := True; SetBounds(X, IconTextHeight + VertMargin + VertSpacing, ButtonWidth, ButtonHeight); X := X + ButtonWidth + ButtonSpacing; if B = TMsgDlgBtn.mbHelp then OnClick := TMessageForm(Result).HelpButtonClick; end; end; end; end; function CreateMessageDialog(const Msg: WideString; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons): TForm; var DefaultButton: TMsgDlgBtn; begin if TMsgDlgBtn.mbOk in Buttons then DefaultButton := TMsgDlgBtn.mbOk else if TMsgDlgBtn.mbYes in Buttons then DefaultButton := TMsgDlgBtn.mbYes else DefaultButton := TMsgDlgBtn.mbRetry; Result := CreateMessageDialog(Msg, DlgType, Buttons, DefaultButton); end; function MessageDlg(const Msg: WideString; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: Longint): Integer; begin Result := MessageDlgPosHelp(Msg, DlgType, Buttons, HelpCtx, -1, -1, ''); end; function MessageDlg(const Msg: WideString; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: Longint; DefaultButton: TMsgDlgBtn): Integer; overload; begin Result := MessageDlgPosHelp(Msg, DlgType, Buttons, HelpCtx, -1, -1, '', DefaultButton); end; function DoMessageDlgPosHelp(MessageDialog: TForm; HelpCtx: Longint; X, Y: Integer; const HelpFileName: WideString): Integer; begin try // HelpContext := HelpCtx; // HelpFile := HelpFileName; if X >= 0 then MessageDialog.Left := X; if Y >= 0 then MessageDialog.Top := Y; if (Y < 0) and (X < 0) then MessageDialog.Position := TFormPosition.poScreenCenter; Result := MessageDialog.ShowModal; finally MessageDialog.Free; end; end; function MessageDlgPos(const Msg: WideString; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: Longint; X, Y: Integer): Integer; begin Result := MessageDlgPosHelp(Msg, DlgType, Buttons, HelpCtx, X, Y, ''); end; function MessageDlgPos(const Msg: WideString; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: Longint; X, Y: Integer; DefaultButton: TMsgDlgBtn): Integer; overload; begin Result := MessageDlgPosHelp(Msg, DlgType, Buttons, HelpCtx, X, Y, '', DefaultButton); end; function MessageDlgPosHelp(const Msg: WideString; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: Longint; X, Y: Integer; const HelpFileName: WideString): Integer; begin Result := DoMessageDlgPosHelp(CreateMessageDialog(Msg, DlgType, Buttons), HelpCtx, X, Y, HelpFileName); end; function MessageDlgPosHelp(const Msg: WideString; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: Longint; X, Y: Integer; const HelpFileName: WideString; DefaultButton: TMsgDlgBtn): Integer; overload; begin Result := DoMessageDlgPosHelp(CreateMessageDialog(Msg, DlgType, Buttons, DefaultButton), HelpCtx, X, Y, HelpFileName); end; procedure ShowMessage(const Msg: WideString); begin ShowMessagePos(Msg, -1, -1); end; procedure ShowMessageFmt(const Msg: WideString; Params: array of const); begin ShowMessage(Format(Msg, Params)); end; procedure ShowMessagePos(const Msg: WideString; X, Y: Integer); begin MessageDlgPos(Msg, TMsgDlgType.mtCustom, [TMsgDlgBtn.mbOK], 0, X, Y); end; { TCommonDialog } constructor TCommonDialog.Create(AOwner: TComponent); begin inherited Create(AOwner); end; destructor TCommonDialog.Destroy; begin inherited Destroy; end; procedure TCommonDialog.DoClose; begin if Assigned(FOnClose) then FOnClose(Self); end; procedure TCommonDialog.DoShow; begin if Assigned(FOnShow) then FOnShow(Self); end; function TCommonDialog.Execute: Boolean; begin DoShow; Result := DoExecute; DoClose; end; { TOpenDialog } constructor TOpenDialog.Create(AOwner: TComponent); begin inherited Create(AOwner); FHistoryList := TWideStringList.Create; FOptions := [TOpenOption.ofHideReadOnly, TOpenOption.ofEnableSizing]; FFiles := TWideStringList.Create; FFilterIndex := 1; end; destructor TOpenDialog.Destroy; begin FFiles.Free; FHistoryList.Free; inherited Destroy; end; function TOpenDialog.DoCanClose: Boolean; begin Result := True; if Assigned(FOnCanClose) then FOnCanClose(Self, Result); end; procedure TOpenDialog.DoSelectionChange; begin if Assigned(FOnSelectionChange) then FOnSelectionChange(Self); end; procedure TOpenDialog.DoFolderChange; begin if Assigned(FOnFolderChange) then FOnFolderChange(Self); end; procedure TOpenDialog.DoTypeChange; begin if Assigned(FOnTypeChange) then FOnTypeChange(Self); end; procedure TOpenDialog.ReadFileEditStyle(Reader: TReader); begin { Ignore FileEditStyle } Reader.ReadIdent; end; procedure TOpenDialog.DefineProperties(Filer: TFiler); begin inherited DefineProperties(Filer); Filer.DefineProperty('FileEditStyle', ReadFileEditStyle, nil, False); end; function TOpenDialog.GetFiles: TWideStrings; begin Result := FFiles; end; function TOpenDialog.GetFileName: TFileName; begin Result := FFileName; end; function TOpenDialog.GetFilterIndex: Integer; begin Result := FFilterIndex; end; function TOpenDialog.GetInitialDir: WideString; begin Result := FInitialDir; end; function TOpenDialog.GetTitle: WideString; begin Result := FTitle; end; procedure TOpenDialog.SetFileName(Value: TFileName); begin if Value <> FFileName then FFileName := Value; end; procedure TOpenDialog.SetHistoryList(Value: TWideStrings); begin FHistoryList.Assign(Value); end; procedure TOpenDialog.SetInitialDir(const Value: WideString); var L: Integer; begin L := Length(Value); if (L > 1) and IsPathDelimiter(Value, L) and not IsDelimiter(':', Value, L - 1) then Dec(L); FInitialDir := Copy(Value, 1, L); end; procedure TOpenDialog.SetTitle(const Value: WideString); begin if Value <> FTitle then FTitle := Value; end; function TOpenDialog.DoExecute: Boolean; begin Result := Platform.DialogOpenFiles(FFileName, FInitialDir, FDefaultExt, FFilter, FTitle, FFilterIndex, FFiles, FOptions); end; { TSaveDialog } function TSaveDialog.DoExecute: Boolean; begin Result := Platform.DialogSaveFiles(FFileName, FInitialDir, FDefaultExt, FFilter, FTitle, FFilterIndex, FFiles, FOptions); end; { TPrintDialog } function TPrintDialog.DoExecute: Boolean; begin Result := Platform.DialogPrint(FCollate, FPrintToFile, FFromPage, FToPage, FCopies, FMinPage, FMaxPage, FPrintRange, FOptions); end; procedure TPrintDialog.SetNumCopies(Value: Integer); begin FCopies := Value; Printer.Copies := Value; end; { TPageSetupDialog } constructor TPageSetupDialog.Create(AOwner: TComponent); begin inherited; Options := [TPageSetupDialogOption.psoDefaultMinMargins]; Platform.PageSetupGetDefaults(FMargin, FMinMargin, FPaperSize, FUnits, FOptions); end; function TPageSetupDialog.DoExecute: Boolean; begin Result := Platform.DialogPageSetup(FMargin, FMinMargin, FPaperSize, FUnits, FOptions); end; function TPageSetupDialog.getMarginBottom: Integer; begin Result := FMargin.Bottom; end; function TPageSetupDialog.getMarginLeft: Integer; begin Result := FMargin.Left; end; function TPageSetupDialog.getMarginRight: Integer; begin Result := FMargin.Right; end; function TPageSetupDialog.getMarginTop: Integer; begin Result := FMargin.Top; end; function TPageSetupDialog.getMinMarginBottom: Integer; begin Result := FMinMargin.Bottom; end; function TPageSetupDialog.getMinMarginLeft: Integer; begin Result := FMinMargin.Left; end; function TPageSetupDialog.getMinMarginRight: Integer; begin Result := FMinMargin.Right; end; function TPageSetupDialog.getMinMarginTop: Integer; begin Result := FMinMargin.Top; end; function TPageSetupDialog.getPageHeight: Single; begin Result := FPaperSize.Y; end; function TPageSetupDialog.getPageWidth: Single; begin Result := FPaperSize.X; end; procedure TPageSetupDialog.setMarginBottom(Value: Integer); begin if Value <> FMargin.Bottom then if Value >= 0 then FMargin.Bottom := Value; end; procedure TPageSetupDialog.setMarginLeft(Value: Integer); begin if Value <> FMargin.Left then if Value >= 0 then FMargin.Left := Value; end; procedure TPageSetupDialog.setMarginRight(Value: Integer); begin if Value <> FMargin.Right then if Value >= 0 then FMargin.Right := Value; end; procedure TPageSetupDialog.setMarginTop(Value: Integer); begin if Value <> FMargin.Top then if Value >= 0 then FMargin.Top := Value; end; procedure TPageSetupDialog.setMinMarginBottom(Value: Integer); begin if Value <> FMinMargin.Bottom then if Value >= 0 then FMinMargin.Bottom := Value; end; procedure TPageSetupDialog.setMinMarginLeft(Value: Integer); begin if Value <> FMinMargin.Left then if Value >= 0 then FMinMargin.Left := Value; end; procedure TPageSetupDialog.setMinMarginRight(Value: Integer); begin if Value <> FMinMargin.Right then if Value >= 0 then FMinMargin.Right := Value; end; procedure TPageSetupDialog.setMinMarginTop(Value: Integer); begin if Value <> FMinMargin.Top then if Value >= 0 then FMinMargin.Top := Value; end; procedure TPageSetupDialog.setPageHeight(Value: Single); begin if Value <> FPaperSize.Y then if Value >= 0 then FPaperSize.Y := Value; end; procedure TPageSetupDialog.setPageWidth(Value: Single); begin if Value <> FPaperSize.X then if Value >= 0 then FPaperSize.X := Value; end; { TPrinterSetupDialog } function TPrinterSetupDialog.DoExecute: Boolean; begin Result := Platform.DialogPrinterSetup; end; {$IFNDEF FPC} type TInputQueryForm = class(TForm) public FCloseQueryFunc: TFunc<Boolean>; function CloseQuery: Boolean; override; end; function TInputQueryForm.CloseQuery: Boolean; begin Result := (ModalResult = mrCancel) or (not Assigned(FCloseQueryFunc)) or FCloseQueryFunc(); end; { Input dialog } function InputBox(const ACaption, APrompt, ADefault: WideString): WideString; begin Result := ADefault; InputQuery(ACaption, APrompt, Result); end; function InputQuery(const ACaption: WideString; const APrompts: array of string; var AValues: array of string; CloseQueryFunc: TInputCloseQueryFunc = nil): Boolean; var I, J: Integer; Form: TInputQueryForm; Prompt: TLabel; Edit: TEdit; DialogUnits: TPointF; PromptCount: Integer; MaxPromptWidth, CurPrompt: Single; ButtonTop, ButtonWidth, ButtonHeight: Single; function GetPromptCaption(const ACaption: WideString): WideString; begin if (Length(ACaption) > 1) and (ACaption[1] < #32) then Result := Copy(ACaption, 2, MaxInt) else Result := ACaption; end; function GetMaxPromptWidth(Canvas: TCanvas): Single; var I: Integer; begin Result := 0; for I := 0 to PromptCount - 1 do Result := Max(Result, Canvas.TextWidth(GetPromptCaption(APrompts[I])) + DialogUnits.X); end; function GetPasswordChar(const ACaption: WideString): WideChar; begin if (Length(ACaption) > 1) and (ACaption[1] < #32) then Result := '*' else Result := #0; end; begin if Length(AValues) < Length(APrompts) then raise EInvalidOperation.CreateRes(@SPromptArrayTooShort); PromptCount := Length(APrompts); if PromptCount < 1 then raise EInvalidOperation.CreateRes(@SPromptArrayEmpty); Result := False; Form := TInputQueryForm.CreateNew(Application); with Form do try FCloseQueryFunc := function: Boolean var I, J: Integer; LValues: array of string; Control: TFmxObject; begin Result := True; if Assigned(CloseQueryFunc) then begin SetLength(LValues, PromptCount); J := 0; for I := 0 to Form.ChildrenCount - 1 do begin Control := Form.Children[I]; if Control is TEdit then begin LValues[J] := TEdit(Control).Text; Inc(J); end; end; Result := CloseQueryFunc(LValues); end; end; // Canvas.Font.As := Font; DialogUnits := GetAveCharSize(Canvas); MaxPromptWidth := GetMaxPromptWidth(Canvas); BorderStyle := TFmxFormBorderStyle.bsSingle; BorderIcons := [TBorderIcon.biSystemMenu]; Caption := ACaption; ClientWidth := Trunc(MulDiv(180.0 + MaxPromptWidth, DialogUnits.X, 4.0)); // PopupMode := pmAuto; Position := TFormPosition.poScreenCenter; CurPrompt := MulDiv(8.0, DialogUnits.Y, 8.0); Edit := nil; for I := 0 to PromptCount - 1 do begin Prompt := TLabel.Create(Form); with Prompt do begin Parent := Form; Text := GetPromptCaption(APrompts[I]); TextAlign := TTextAlign.taLeading; VertTextAlign := TTextAlign.taLeading; Position.X := MulDiv(8.0, DialogUnits.X, 4.0); Position.Y := CurPrompt; // Constraints.MaxWidth := MaxPromptWidth; WordWrap := True; end; Edit := TEdit.Create(Form); with Edit do begin Parent := Form; Password := GetPasswordChar(APrompts[I]) <> #0; ApplyStyleLookup; Position.X := Prompt.Position.X + MaxPromptWidth; Position.Y := Prompt.Position.Y - ContentRect.TopLeft.Y; Width := Form.ClientWidth - Position.X - MulDiv(8.0, DialogUnits.X, 4.0); MaxLength := 255; Text := AValues[I]; SelectAll; // Prompt.FocusControl := Edit; end; CurPrompt := Prompt.Position.Y + Edit.Height + 5; end; ButtonTop := Edit.Position.Y + Edit.Height + 15; ButtonWidth := MulDiv(50.0, DialogUnits.X, 4.0); ButtonHeight := MulDiv(14.0, DialogUnits.Y, 8.0); with TButton.Create(Form) do begin Parent := Form; Text := SMsgDlgOK; ModalResult := mrOk; Default := True; SetBounds(Form.ClientWidth - (ButtonWidth + MulDiv(8.0, DialogUnits.X, 4.0)) * 2.0, ButtonTop, ButtonWidth, ButtonHeight); end; with TButton.Create(Form) do begin Parent := Form; Text := SMsgDlgCancel; ModalResult := mrCancel; Cancel := True; SetBounds(Form.ClientWidth - (ButtonWidth + MulDiv(8.0, DialogUnits.X, 4.0)), ButtonTop, ButtonWidth, ButtonHeight); Form.ClientHeight := Trunc(Position.Y + Height + 13); end; if ShowModal = mrOk then begin J := 0; for I := 0 to ChildrenCount - 1 do if Children[I] is TEdit then begin Edit := TEdit(Children[I]); AValues[J] := Edit.Text; Inc(J); end; Result := True; end; finally Form.Free; end; end; function InputQuery(const ACaption: WideString; const APrompts: array of string; var AValues: array of string; CloseQueryEvent: TInputCloseQueryEvent; Context: TObject = nil): Boolean; begin Result := InputQuery(ACaption, APrompts, AValues, function (const Values: array of string): Boolean begin Result := True; CloseQueryEvent(Context, Values, Result); end) end; function InputQuery(const ACaption, APrompt: WideString; var Value: WideString): Boolean; var Values: array[0..0] of string; begin Values[0] := Value; Result := InputQuery(ACaption, [APrompt], Values); if Result then Value := Values[0]; end; type TDefaultLoginCredentials = class sealed class procedure LoginEvent(Sender: TObject; Callback: TLoginCredentialService.TLoginEvent; var Success: Boolean); class procedure LoginEventUsrPw(Sender: TObject; Callback: TLoginCredentialService.TLoginEvent; var Success: Boolean); end; class procedure TDefaultLoginCredentials.LoginEvent(Sender: TObject; Callback: TLoginCredentialService.TLoginEvent; var Success: Boolean); var Values: TArray<string>; begin SetLength(Values, 3); Success := InputQuery(SLogin, [SUsername, #31 + SPassword, SDomain], Values, function (const Values: array of string): Boolean begin Result := True; Callback(Sender, Values[0], Values[1], Values[2], Result); end); end; class procedure TDefaultLoginCredentials.LoginEventUsrPw(Sender: TObject; Callback: TLoginCredentialService.TLoginEvent; var Success: Boolean); var Values: TArray<string>; begin SetLength(Values, 2); Success := InputQuery(SLogin, [SUsername, #31 + SPassword], Values, function (const Values: array of string): Boolean begin Result := True; Callback(Sender, Values[0], Values[1], '', Result); end); end; {$ENDIF} initialization StartClassGroup(TFmxObject); ActivateClassGroup(TFmxObject); GroupDescendentsWith(TCommonDialog, TFmxObject); {$IFNDEF FPC} TLoginCredentialService.RegisterLoginHandler(TLoginCredentialService.Default, TDefaultLoginCredentials.LoginEventUsrPw); TLoginCredentialService.RegisterLoginHandler(TLoginCredentialService.DefaultUsrPwDm, TDefaultLoginCredentials.LoginEvent); TLoginCredentialService.RegisterLoginHandler(TLoginCredentialService.DefaultUsrPw, TDefaultLoginCredentials.LoginEventUsrPw); {$ENDIF} finalization {$IFNDEF FPC} TLoginCredentialService.UnregisterLoginHandler(TLoginCredentialService.DefaultUsrPw, TDefaultLoginCredentials.LoginEventUsrPw); TLoginCredentialService.UnregisterLoginHandler(TLoginCredentialService.DefaultUsrPwDm, TDefaultLoginCredentials.LoginEvent); TLoginCredentialService.UnregisterLoginHandler(TLoginCredentialService.Default, TDefaultLoginCredentials.LoginEventUsrPw); {$ENDIF} end.
unit camform; (****************************************************************************** Exemplo de Aplicativo com Webcam Autor: Fotógrafo Fernando VR Site: www.FernandoVR.com.br Sobre mim: Sou fotógrafo profissional, programador web PHP, e aprendiz no Delphi. Ainda estou iniciando meus estudos em Delphi por isso não adianta me adicionar para fazer perguntas difíceis que não saberei responder. Sobre o Aplicativo: Criei esse programa fuçando centenas de códigos fontes com webcam até encontrar um modo que não fosse necessário a instalação de nenhum componente e nem utilização de DLL´s. Este programa funciona com classes de Microsoft DirectX 9.0. Desenvolvi no DelphiXE 2, mas analisando o código fonte pode ser facilmente adaptado em versões anteriores. ******************************************************************************) interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, IniFiles, JPEG, VFrames, VSample, Direct3D9, DirectDraw, DirectShow9, DirectSound, DXTypes, Vcl.ComCtrls; type WebcamTimer = class(TThread) private { Private declarations } protected procedure Execute; override; end; TForm1 = class(TForm) img1: TImage; btn1: TButton; btn2: TButton; btn3: TButton; lbl1: TLabel; edt1: TEdit; lbl2: TLabel; trckbr1: TTrackBar; edt2: TEdit; btnligar: TButton; btndesligar: TButton; lbl4: TLabel; lbl_camstatus: TLabel; shp1: TShape; cbb1: TComboBox; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure trckbr1Change(Sender: TObject); procedure edt2Change(Sender: TObject); procedure btnligarClick(Sender: TObject); procedure btndesligarClick(Sender: TObject); procedure btn1Click(Sender: TObject); procedure btn3Click(Sender: TObject); procedure btn2Click(Sender: TObject); private { Private declarations } fActivated : boolean; fVideoImage : TVideoImage; fVideoBitmap: TBitmap; OfflineImage : TJPEGImage; procedure OnNewVideoFrame(Sender : TObject; Width, Height: integer; DataPtr: pointer); procedure OnNewVideoCanvas(Sender : TObject; Width, Height: integer; DataPtr: pointer); public { Public declarations } end; var Form1: TForm1; PathExec,Deviceselect : string; IFile: TIniFile; JpgQuality, TimerExec : Integer; RS: TResourceStream; implementation {$R *.dfm} { WebcamTimer } // Thread para Salvar Imagens no PC procedure WebcamTimer.Execute; var MyJPEG : TJPEGImage; JPEGFName, formattedDateTime: string; I :Integer; begin For I:= 1 to StrToInt(Form1.edt1.Text) do Begin Form1.fVideoImage.OnNewVideoFrame := Form1.OnNewVideoFrame; // Pega o frame atual da webcam em bitmap formattedDateTime := FormatDateTime('yyyy_m_d_hh_nn_ss_zzz',(Now)); // Gerador de nomes para o JPG com data e horário. MyJPEG := TJPEGImage.Create; // Cria uma imagem JPG JPEGFName:= PathExec+formattedDateTime+'.jpg'; // Cria todo caminho onde a imagem JPG será salva MyJPEG.CompressionQuality := strtoint(Form1.edt2.Text); // Seta a qualidade do JPG escolhido na configuração try MyJPEG.Assign(Form1.fVideoBitmap); // Atribui o bitimap frame no JPG MyJPEG.SaveToFile(JPEGFName); // Salva o JPG no diretório finally MyJPEG.Free; // Libera o JPG da memória. end; Sleep(1000); End; end; { FORM } // Pega frame de vídeo procedure TForm1.OnNewVideoFrame(Sender : TObject; Width, Height: integer; DataPtr: pointer); begin fVideoImage.GetBitmap(fVideoBitmap); // Pega apenas o frame atual do vídeo. end; // Passa para o TImage todos os frames em quanto a cam estiver ligada. procedure TForm1.OnNewVideoCanvas(Sender : TObject; Width, Height: integer; DataPtr: pointer); begin fVideoImage.GetBitmap(fVideoBitmap); // Pega o frame atual, Não sei pq mas precisa desta linha para funcionar. img1.Picture.Bitmap.Canvas.Draw(0,0,fVideoBitmap); // Envia frame a frame de vídeo para o componente TImage, tb não entendi direito o pq de só funcionar com o canvas, mas deu certo. end; // Executa ao iniciar o programa. procedure TForm1.FormCreate(Sender: TObject); var DevicesListed, i : Integer; DeviceList : TStringList; begin RS:= TResourceStream.Create(hInstance, 'OfflineIMG',RT_RCDATA); // Carrega Resource da imagem padrão quando a camera estiver desligada. OfflineImage := TJPEGImage.Create; // Cria Imagem JPG OfflineImage.LoadFromStream(RS); // Atribui a imagem do resorce carregado a uma imagem JPG. img1.Picture.Assign(OfflineImage); // Exibe a imagem offline padrão no component Timage PathExec := ExtractFilePath(Application.ExeName); // extrai o diretório atual do aplicativo IFile := TIniFile.Create(PathExec+'config.ini'); // Seta um aquivo INI para gravar as configurações fVideoBitmap := TBitmap.create; // Cria um bitmap para os frames de vídeo. fVideoImage := TVideoImage.Create; // Cria uma imagem de vídeo. fActivated := false; // Inicia avisando que a webcam está desligada; ////////// Configuração da Qualidade da imagem JPG // Busca a qualidade gravada no arquivo INI, default: 100 JpgQuality := IFile.ReadInteger('Config','JPGQuality',100); // Exibe resultado no canpo de texto edt2.Text := IntToStr(JpgQuality); // Exibe resultado no trackbar trckbr1.Position := JpgQuality; ////////// Configuração de quantas imagens será gravadas no diretório // Busca configuração salva no arquivo INI, default: 20 (imagens) TimerExec := IFile.ReadInteger('Config','TimerExec',20); // Exibe resultado no canpo de texto edt1.Text := IntToStr(TimerExec); ////////// Configuração da webcam. // Lista todos os dispositivos num listbox. DeviceList := TStringList.Create; fVideoImage.GetListOfDevices(DeviceList); cbb1.Items := DeviceList; DeviceList.Free; // Busca configuração salva no arquivo INI, default: nenhum dispositivo selecionado. Deviceselect := IFile.ReadString('WEBCAM','Device',''); // Se caso encontrar algum item na configuração ele busca no listbox e seleciona se o dispositivo existir na listagem. cbb1.ItemIndex := cbb1.Items.IndexOf(Deviceselect); end; // Executa ao mudar o trackbar procedure TForm1.trckbr1Change(Sender: TObject); begin edt2.Text := IntToStr(trckbr1.Position); end; // Executa ao mudar o valor da qualidade da imagem na caixa de texto procedure TForm1.edt2Change(Sender: TObject); begin trckbr1.Position := strtoint(edt2.Text); end; // Executa ao clicar no botão de ligar Webcam procedure TForm1.btnligarClick(Sender: TObject); var camdevice: string; begin // Identifica qual dispositivo está selecionado camdevice := Trim(cbb1.Items.Strings[cbb1.ItemIndex]); try // Inicia a webcam fVideoImage.VideoStart(camdevice); // Pega o primeiro frame que provavelmente estará vazio. fVideoImage.OnNewVideoFrame := OnNewVideoFrame; // Seta a webcam como ativada fActivated := true; // Exibe Status como Ligada lbl_camstatus.Caption := 'Ligada'; lbl_camstatus.Font.Color := clGreen; except // Seta a webcam como desativada fActivated := false; // Exibe Status como Desligado lbl_camstatus.Caption := 'Desligada'; lbl_camstatus.Font.Color := clRed; end; end; // Executa ao clicar no botão de desligar Webcam procedure TForm1.btndesligarClick(Sender: TObject); begin // Desliga a Webcam fVideoImage.VideoStop; // Seta a webcam como desativada fActivated := false; // Exibe Status como Desligado lbl_camstatus.Caption := 'Desligada'; lbl_camstatus.Font.Color := clRed; // Exibe a imagem offline padrão no component Timage img1.Picture.Assign(OfflineImage); end; // Executa ao clicar no botão de "pegar imagem" procedure TForm1.btn1Click(Sender: TObject); begin if fActivated then begin // Pega o frame atual da webcam em bitmap fVideoImage.OnNewVideoFrame := OnNewVideoFrame; // Envia o bitmap do frame atual para o component Timage img1.Picture.Bitmap.Assign(fVideoBitmap); end else ShowMessage('A Webcam precisa estar ligada!'); end; // Executa ao clicar no botão de "Video Cam" procedure TForm1.btn2Click(Sender: TObject); begin if fActivated then begin // Inicia exibiçãoo de video da webcam em bitmap fVideoImage.OnNewVideoFrame := OnNewVideoCanvas; // Envia o o vídeo para o component Timage img1.Picture.Bitmap.Assign(fVideoBitmap); end else ShowMessage('A Webcam precisa estar ligada!'); end; // Executa ao clicar no botão de "Salvar na Pasta" procedure TForm1.btn3Click(Sender: TObject); var _WebcamTimer: WebcamTimer; begin if fActivated then begin _WebcamTimer := WebcamTimer.Create(False); _WebcamTimer.FreeOnTerminate := True; end else ShowMessage('A Webcam precisa estar ligada!'); end; // Executar ao fechar o programa procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin // Desliga a webcam caso esteja ligada. fVideoImage.VideoStop; ////////// SALVA TODAS AS CONFIGURAÇÕES NO ARQUIVO INI // SALVA QUALIDADE DO JPG IFile.WriteInteger('Config','JPGQuality',strtoint(edt2.Text)); // SALVA QUANTIDADE DE IMAGENS POR SEGUNDOS A SER SALVA NO DIRETORIO IFile.WriteInteger('Config','TimerExec',strtoint(edt1.Text)); // SALVA DISPOSITIVO DA WEBCAM SELECIONADO IFile.WriteString('WEBCAM','Device',cbb1.Items.Strings[cbb1.ItemIndex]); // Libera o Arquivo INI da Memória IFile.Free; // Libera o Bitmap e imagem de vídeo da memória. fVideoBitmap.Free; fVideoImage.Free; end; end.
{=============================================================================== Copyright(c) 2007-2009, 北京北研兴电力仪表有限责任公司 All rights reserved. 错误接线,接线错误类单元 + TWIRING_ERROR 接线错误类 ===============================================================================} unit U_WIRING_ERROR; interface uses SysUtils, Classes, IniFiles, Forms; const /// <summary> /// 三线编号基本值 /// </summary> C_WE_ID_BASE_THREE = $30000000; /// <summary> /// 三线编号正确值 /// </summary> C_WE_ID_CORRECT_THREE = $30000000; const /// <summary> /// 四线编号基本值 /// </summary> C_WE_ID_BASE_FOUR = $40000000; const /// <summary> /// 四线带PT编号基本值 /// </summary> C_WE_ID_BASE_FOUR_PT = $08000000; const /// <summary> /// 四线编号正确值 /// </summary> C_WE_ID_CORRECT_FOUR = $40000000; const /// <summary> /// 四线编号正确值 /// </summary> C_WE_ID_CORRECT_FOUR_PT = $08000000; type /// <summary> /// 相线类型, ptThree 三线, ptFour 四线 /// </summary> TWE_PHASE_TYPE = (ptThree, ptFour, ptFourPT, ptSingle); //ptFourPT为三相四线带电压互感器 /// <summary> /// 获取相线类型字符串 /// </summary> function GetPhaseTypeStr( AType : TWE_PHASE_TYPE ) : string; type /// <summary> /// 相序类型 /// </summary> TWE_SEQUENCE_TYPE = (stABC, stACB, stBAC, stBCA, stCAB, stCBA); /// <summary> /// 获取相序类型字符串 /// </summary> function GetSequenceTypeStr( AType : TWE_SEQUENCE_TYPE; bAbc : Integer = 0 ) : string; type /// <summary> /// 相线类型 plB1为简化接线-Ia-Ic的矢量和 /// </summary> TWE_PHASE_LINE_TYPE = (plA, plB, plC, plN); /// <summary> /// 获取相线类型字符串 /// </summary> function GetPhaseLineTypeStr( AType : TWE_PHASE_LINE_TYPE; bAbc : Integer = 0 ) : string; {function GetPhaseLineTypeStr( AType : TWE_PHASE_LINE_TYPE; bAbc : Boolean = True ) : string;} type /// <summary> /// 接线错误类型 /// </summary> TWE_ERROR_TYPE = ( etUSequence, etUBroken, etUsBroken, etPTReverse, etISequence, etIBroken, etCTShort, etCTReverse ); type /// <summary> /// 接线错误类型集合 /// </summary> TWE_ERROR_TYPE_SET = set of TWE_ERROR_TYPE; type /// <summary> /// 接线错误 /// </summary> TWIRING_ERROR = class( TPersistent ) private // 电压部分(三相四线) FUSequence : TWE_SEQUENCE_TYPE; // 电压相序 FUaBroken : Boolean; // 电压断, 一次电压断 FUbBroken : Boolean; FUcBroken : Boolean; FUnBroken : Boolean; // 电压附加(三相三线) FUsaBroken : Boolean; // 二次电压断 FUsbBroken : Boolean; FUscBroken : Boolean; FUsnBroken : Boolean; //三相四线带电压互感器N相断开,胡红明2013.5.10 FGroundBroken: Boolean; //三相四线PT没有接地,胡红明2013.5.14 FPT1Reverse : Boolean; // 电压互感器反 FPT2Reverse : Boolean; FPT3Reverse : Boolean; //用于三相四线电压互感器反,胡红明2013.5.10 // 电流部分(三相四线) FISequence : TWE_SEQUENCE_TYPE; // 电流相序 FIaBroken : Boolean ; // 电流断 FIbBroken : Boolean ; FIcBroken : Boolean ; FInBroken : Boolean ; FCT1Short : Boolean ; // 电流互感器短路 FCT2Short : Boolean ; FCT3Short : Boolean ; FCT1Reverse : Boolean ; // 电流互感器反 FCT2Reverse : Boolean ; FCT3Reverse : Boolean ; // 三相四线电表电流线表尾反接 FI1Reverse : Boolean; FI2Reverse : Boolean; FI3Reverse : Boolean; // 电流附加(三相三线) FI1In : TWE_PHASE_LINE_TYPE; // 表尾电流输入输出 FI1Out : TWE_PHASE_LINE_TYPE; FI2In : TWE_PHASE_LINE_TYPE; FI2Out : TWE_PHASE_LINE_TYPE; // 显示方式(abc、uvw、123) Fabc : Integer; Fptct : Boolean; // 其它 FPhaseType: TWE_PHASE_TYPE; FOnChanged : TNotifyEvent; FIbGroundBroken: Boolean; FIcGroundBroken: Boolean; FIaGroundBroken: Boolean; FIGroundBroken: Boolean; FI3Out: TWE_PHASE_LINE_TYPE; FI3In: TWE_PHASE_LINE_TYPE; FIsClearLinke: Boolean; FIsCanSetClearLinkeError: Boolean; // FProVersion: string; function GetID : Cardinal; function GetIDThree : Cardinal; function GetIDFour : Cardinal; function GetIDFourPT: Cardinal; procedure SetID( const Value : Cardinal ); procedure SetIDThree( const Value : Cardinal ); procedure SetIDFour( const Value : Cardinal ); procedure SetIDFourPT(const Value : Cardinal ); procedure SetPhaseType(const Value: TWE_PHASE_TYPE); function GetDescription : string; /// <summary> /// 判断某一位是否为1 /// </summary> function BitIsOne( AIntValue, ABitPos : Integer ) : Boolean; function GetErrorCount: Integer; procedure SetIaGroundBroken(const Value: Boolean); procedure SetI1In(const Value: TWE_PHASE_LINE_TYPE); public constructor Create; procedure Assign(Source: TPersistent); override; /// <summary> /// 清空错误接线 /// </summary> procedure Clear; /// <summary> /// 错误接线编码字符串格式 /// </summary> function IDInStr : string; /// <summary> /// 是否有U断相 /// </summary> function UHasBroken : Boolean; /// <summary> /// 是否为正确的接线 /// </summary> function IsCorrect : Boolean; /// <summary> /// 设置为正确接线 /// </summary> procedure SetToCorrect; /// <summary> /// 错误接线描述(一句话) /// </summary> procedure GetDescriptionText( AText : TStrings ); /// <summary> /// 设置错误数量 /// </summary> property ErrorCount : Integer read GetErrorCount; public /// <summary> /// 错误接线编码 /// </summary> property ID : Cardinal read GetID write SetID; /// <summary> /// 错误接线描述 /// </summary> property Description : string read GetDescription; /// <summary> /// 错误改变事件 /// </summary> property OnChanged : TNotifyEvent read FOnChanged write FOnChanged; /// <summary> /// 相线类型 /// </summary> property PhaseType : TWE_PHASE_TYPE read FPhaseType write SetPhaseType; /// <summary> /// 电压相序 /// </summary> property USequence : TWE_SEQUENCE_TYPE read FUSequence write FUSequence ; /// <summary> /// 电压断 /// </summary> property UaBroken : Boolean read FUaBroken write FUaBroken ; property UbBroken : Boolean read FUbBroken write FUbBroken ; property UcBroken : Boolean read FUcBroken write FUcBroken ; property UnBroken : Boolean read FUnBroken write FUnBroken ; /// <summary> /// 二次电压断 /// </summary> property UsaBroken : Boolean read FUsaBroken write FUsaBroken; property UsbBroken : Boolean read FUsbBroken write FUsbBroken; property UscBroken : Boolean read FUscBroken write FUscBroken; property UsnBroken : Boolean read FUsnBroken write FUsnBroken; /// <summary> /// 地线断(没有接地) /// </summary> property GroundBroken: Boolean read FGroundBroken write FGroundBroken; /// <summary> /// 电压互感器反 /// </summary> property PT1Reverse : Boolean read FPT1Reverse write FPT1Reverse; property PT2Reverse : Boolean read FPT2Reverse write FPT2Reverse; property PT3Reverse : Boolean read FPT3Reverse write FPT3Reverse; /// <summary> /// 电流相序 /// </summary> property ISequence : TWE_SEQUENCE_TYPE read FISequence write FISequence ; /// <summary> /// 电流断 /// </summary> property IaBroken : Boolean read FIaBroken write FIaBroken ; property IbBroken : Boolean read FIbBroken write FIbBroken ; property IcBroken : Boolean read FIcBroken write FIcBroken ; property InBroken : Boolean read FInBroken write FInBroken ; /// <summary> /// 电流互感器短路 /// </summary> property CT1Short : Boolean read FCT1Short write FCT1Short ; property CT2Short : Boolean read FCT2Short write FCT2Short ; property CT3Short : Boolean read FCT3Short write FCT3Short ; /// <summary> /// 电流互感器反 /// </summary> property CT1Reverse : Boolean read FCT1Reverse write FCT1Reverse; property CT2Reverse : Boolean read FCT2Reverse write FCT2Reverse; property CT3Reverse : Boolean read FCT3Reverse write FCT3Reverse; /// <summary> /// 表尾电流输入输出 三相三线用I1和I2 简化接线时plB /// </summary> property I1In : TWE_PHASE_LINE_TYPE read FI1In write SetI1In ; property I1Out : TWE_PHASE_LINE_TYPE read FI1Out write FI1Out ; property I2In : TWE_PHASE_LINE_TYPE read FI2In write FI2In ; property I2Out : TWE_PHASE_LINE_TYPE read FI2Out write FI2Out ; property I3In : TWE_PHASE_LINE_TYPE read FI3In write FI3In ; property I3Out : TWE_PHASE_LINE_TYPE read FI3Out write FI3Out ; /// <summary> /// 三相四线电流反接 /// </summary> property I1Reverse : Boolean read FI1Reverse write FI1Reverse default False; property I2Reverse : Boolean read FI2Reverse write FI2Reverse default False; property I3Reverse : Boolean read FI3Reverse write FI3Reverse default False; /// <summary> /// 电流接地断开 /// </summary> property IaGroundBroken : Boolean read FIaGroundBroken write SetIaGroundBroken; property IbGroundBroken : Boolean read FIbGroundBroken write FIbGroundBroken; property IcGroundBroken : Boolean read FIcGroundBroken write FIcGroundBroken; property IGroundBroken : Boolean read FIGroundBroken write FIGroundBroken; // /// <summary> // /// 测试代码 // /// </summary> // property Temp : Integer read FTemp write FTemp; /// <summary> /// 是否是简化接线 /// </summary> property IsClearLinke : Boolean read FIsClearLinke write FIsClearLinke; /// <summary> /// 是否可以设置简化接线错误 /// </summary> property IsCanSetClearLinkeError : Boolean read FIsCanSetClearLinkeError write FIsCanSetClearLinkeError; /// <summary> /// 三相四线简化接线时电流进线转换为对象中的表位接线 /// </summary> procedure SetClearLinkeISequence(sI1, sI2, sI3 : string; bI1Reverse, bI2Reverse, bI3Reverse : Boolean); // 三相四线简化接线 获取电流相序和是否反接 procedure GetClearLinkeISequence(var sI1, sI2, sI3 : string; var bI1Reverse, bI2Reverse, bI3Reverse : Boolean); end; implementation function GetPhaseTypeStr( AType : TWE_PHASE_TYPE ) : string; begin case AType of ptThree: Result := '三相三线'; ptFour: Result := '三相四线'; ptFourPT: Result := '三相四线(电压互感)'; else Result := ''; end; end; function GetSequenceTypeStr( AType : TWE_SEQUENCE_TYPE; bAbc : Integer ) : string; begin {if bAbc then begin case AType of stACB: Result := 'acb'; stBAC: Result := 'bac'; stBCA: Result := 'bca'; stCAB: Result := 'cab'; stCBA: Result := 'cba'; else // stABC Result := 'abc'; end; end else begin case AType of stACB: Result := 'uwv'; stBAC: Result := 'vuw'; stBCA: Result := 'vwu'; stCAB: Result := 'wuv'; stCBA: Result := 'wvu'; else // stABC Result := 'uvw'; end; end; } case bAbc of 0: begin case AType of stACB: Result := 'acb'; stBAC: Result := 'bac'; stBCA: Result := 'bca'; stCAB: Result := 'cab'; stCBA: Result := 'cba'; else // stABC Result := 'abc'; end; end; 1: begin case AType of stACB: Result := 'uwv'; stBAC: Result := 'vuw'; stBCA: Result := 'vwu'; stCAB: Result := 'wuv'; stCBA: Result := 'wvu'; else // stABC Result := 'uvw'; end; end; 2: begin case AType of stACB: Result := '132'; stBAC: Result := '213'; stBCA: Result := '231'; stCAB: Result := '312'; stCBA: Result := '321'; else // stABC Result := '123'; end; end; end; end; function GetPhaseLineTypeStr( AType : TWE_PHASE_LINE_TYPE; bAbc : Integer ) : string; begin {if bAbc then begin case AType of plA: Result := 'a'; plB: Result := 'b'; plC: Result := 'c'; else Result := 'n'; end; end else begin case AType of plA: Result := 'u'; plB: Result := 'v'; plC: Result := 'w'; else Result := 'n'; end; end; } case bAbc of 0: begin case AType of plA: Result := 'a'; plB: Result := 'b'; plC: Result := 'c'; else Result := 'n'; end; end; 1: begin case AType of plA: Result := 'u'; plB: Result := 'v'; plC: Result := 'w'; else Result := 'n'; end; end; 2: begin case AType of plA: Result := '1'; plB: Result := '2'; plC: Result := '3'; else Result := 'n'; end; end; end; end; { TWIRING_ERROR } procedure TWIRING_ERROR.Assign(Source: TPersistent); begin Assert( Source is TWIRING_ERROR ); FPhaseType := TWIRING_ERROR( Source ).PhaseType ; FUSequence := TWIRING_ERROR( Source ).USequence ; FUaBroken := TWIRING_ERROR( Source ).UaBroken ; FUbBroken := TWIRING_ERROR( Source ).UbBroken ; FUcBroken := TWIRING_ERROR( Source ).UcBroken ; FUnBroken := TWIRING_ERROR( Source ).UnBroken ; FUsaBroken := TWIRING_ERROR( Source ).UsaBroken ; FUsbBroken := TWIRING_ERROR( Source ).UsbBroken ; FUscBroken := TWIRING_ERROR( Source ).UscBroken ; FUsnBroken := TWIRING_ERROR( Source ).UsnBroken ; //胡红明2013.5.13 FPT1Reverse := TWIRING_ERROR( Source ).PT1Reverse ; FPT2Reverse := TWIRING_ERROR( Source ).PT2Reverse ; FPT3Reverse := TWIRING_ERROR( Source ).PT3Reverse ; //胡红明2013.5.13 FGroundBroken:= TWIRING_ERROR( Source ).GroundBroken; //胡红明2013.5.14 FISequence := TWIRING_ERROR( Source ).ISequence ; FIaBroken := TWIRING_ERROR( Source ).IaBroken ; FIbBroken := TWIRING_ERROR( Source ).IbBroken ; FIcBroken := TWIRING_ERROR( Source ).IcBroken ; FInBroken := TWIRING_ERROR( Source ).InBroken ; FCT1Short := TWIRING_ERROR( Source ).CT1Short ; FCT2Short := TWIRING_ERROR( Source ).CT2Short ; FCT3Short := TWIRING_ERROR( Source ).CT3Short ; FCT1Reverse := TWIRING_ERROR( Source ).CT1Reverse ; FCT2Reverse := TWIRING_ERROR( Source ).CT2Reverse ; FCT3Reverse := TWIRING_ERROR( Source ).CT3Reverse ; FI1In := TWIRING_ERROR( Source ).I1In ; FI1Out := TWIRING_ERROR( Source ).I1Out ; FI2In := TWIRING_ERROR( Source ).I2In ; FI2Out := TWIRING_ERROR( Source ).I2Out ; FI3In := TWIRING_ERROR( Source ).I3In ; FI3Out := TWIRING_ERROR( Source ).I3Out ; FIaGroundBroken := TWIRING_ERROR( Source ).IaGroundBroken; FIbGroundBroken := TWIRING_ERROR( Source ).IbGroundBroken; FIcGroundBroken := TWIRING_ERROR( Source ).IcGroundBroken; FIGroundBroken := TWIRING_ERROR( Source ).IGroundBroken; FI1Reverse := TWIRING_ERROR( Source ).I1Reverse; FI2Reverse := TWIRING_ERROR( Source ).I2Reverse; FI3Reverse := TWIRING_ERROR( Source ).I3Reverse; // FTemp := TWIRING_ERROR( Source ).Temp; FIsClearLinke := TWIRING_ERROR( Source ).IsClearLinke; FIsCanSetClearLinkeError := TWIRING_ERROR( Source ).IsCanSetClearLinkeError; // FProVersion := TWIRING_ERROR( Source ).ProVersion ; end; function TWIRING_ERROR.BitIsOne(AIntValue, ABitPos: Integer): Boolean; begin if ABitPos in [ 0..32 ] then Result := AIntValue and ( 1 shl ABitPos ) = 1 shl ABitPos else Result := False; end; procedure TWIRING_ERROR.Clear; begin FUSequence := stABC; FUaBroken := False; FUbBroken := False; FUcBroken := False; FUnBroken := False; FUsaBroken := False; FUsbBroken := False; FUscBroken := False; FPT1Reverse := False; FPT2Reverse := False; FPT3Reverse := False; //胡红明2013.5.21 FISequence := stABC; FIaBroken := False; FIbBroken := False; FIcBroken := False; FInBroken := False; FCT1Short := False; FCT2Short := False; FCT3Short := False; FCT1Reverse := False; FCT2Reverse := False; FCT3Reverse := False; FIaGroundBroken := False; FIbGroundBroken := False; FIcGroundBroken := False; // FIsClearLinke := False; // FIsCanSetClearLinkeError := False; if FPhaseType = ptThree then begin FI1In := plA; FI1Out := plN; FI2In := plC; FI2Out := plN; end else begin FI1In := plA; FI1Out := plN; FI2In := plB; FI2Out := plN; FI3In := plC; FI3Out := plN; end; end; constructor TWIRING_ERROR.Create; begin FPhaseType := ptThree; // FProVersion := 'V1'; Clear; end; procedure TWIRING_ERROR.GetClearLinkeISequence(var sI1, sI2, sI3: string; var bI1Reverse, bI2Reverse, bI3Reverse: Boolean); function GetInOut(AI1In, AI1Out, AI2In, AI2Out, AI3In, AI3Out : TWE_PHASE_LINE_TYPE):Boolean; begin Result := ([FI1In , FI1Out] = [AI1In, AI1Out]) and ([FI2In , FI2Out] = [AI2In, AI2Out]) and ([FI3In , FI3Out] = [AI3In, AI3Out]); if Result then begin bI1Reverse := (FI1In = AI1Out) and (FI1Out = AI1In); bI2Reverse := (FI2In = AI2Out) and (FI2Out = AI2In); bI3Reverse := (FI3In = AI3Out) and (FI3Out = AI3In); end; end; var s : string; begin // s := UpperCase(sI1) + UpperCase(sI2) + UpperCase(sI3); if GetInOut(plA, plN, plB, plN,plC, plN) then s := 'ABC'; if GetInOut(plA, plN, plC, plN,plB, plN) then s := 'ACB'; if GetInOut(plA, plC, plB, plC,plN, plC) then s := 'ABN'; if GetInOut(plA, plB, plC, plB,plN, plB) then s := 'ACN'; if GetInOut(plA, plC, plN, plC,plB, plC) then s := 'ANB'; if GetInOut(plA, plB, plN, plB,plC, plB) then s := 'ANC'; if GetInOut(plB, plC, plA, plC,plN, plC) then s := 'BAN'; if GetInOut(plB, plA, plC, plA,plN, plA) then s := 'BCN'; if GetInOut(plB, plC, plN, plC,plA, plC) then s := 'BNA'; if GetInOut(plB, plA, plN, plA,plC, plA) then s := 'BNC'; if GetInOut(plB, plN, plA, plN,plC, plN) then s := 'BAC'; if GetInOut(plB, plN, plC, plN,plA, plN) then s := 'BCA'; if GetInOut(plC, plA, plB, plA,plN, plA) then s := 'CBN'; if GetInOut(plC, plB, plA, plB,plN, plB) then s := 'CAN'; if GetInOut(plC, plA, plN, plA,plB, plA) then s := 'CNB'; if GetInOut(plC, plB, plN, plB,plA, plB) then s := 'CNA'; if GetInOut(plC, plN, plA, plN,plB, plN) then s := 'CAB'; if GetInOut(plC, plN, plB, plN,plA, plN) then s := 'CBA'; if GetInOut(plN, plA, plB, plA,plC, plA) then s := 'NBC'; if GetInOut(plN, plC, plB, plC,plA, plC) then s := 'NBA'; if GetInOut(plN, plA, plC, plA,plB, plA) then s := 'NCB'; if GetInOut(plN, plB, plC, plB,plA, plB) then s := 'NCA'; if GetInOut(plN, plC, plA, plC,plB, plC) then s := 'NAB'; if GetInOut(plN, plB, plA, plB,plC, plB) then s := 'NAC'; if Length(s) = 3 then begin sI1 := s[1]; sI2 := s[2]; sI3 := s[3]; end; end; function TWIRING_ERROR.GetDescription: string; var sl : TStrings; begin with TIniFile.Create( ChangeFileExt( Application.ExeName, '.ini' ) ) do begin Fabc := ReadInteger( 'Like', 'abc', 0 ); Fptct := ReadBool( 'Like', 'PTCT', True ); Free; end; sl := TStringList.Create; GetDescriptionText( sl ); if sl.Count = 0 then Result := '正确接线' else begin Result := StringReplace( sl.Text, #13#10, '; ', [rfReplaceAll] ); Result := Copy( Result, 1, Length( Result ) - 2 ); if Fabc = 0 then StringReplace( sl.Text, #13#10, '; ', [rfReplaceAll] ); end; sl.Free; end; procedure TWIRING_ERROR.GetDescriptionText(AText: TStrings); function GetPhaseValue(nPhase : Integer) : string; begin Result := ''; case Fabc of 0: begin case nPhase of 1 : Result := 'Ia'; 2 : Result := 'Ib'; 3 : Result := 'Ic'; 4 : Result := 'In'; end; end; 1: begin case nPhase of 1 : Result := 'Iu'; 2 : Result := 'Iv'; 3 : Result := 'Iw'; 4 : Result := 'In'; end; end; 2: begin case nPhase of 1 : Result := 'I1'; 2 : Result := 'I2'; 3 : Result := 'I3'; 4 : Result := 'In'; end; end; end; end; var s : string; sI1, sI2, sI3 : string; bI1Reverse, bI2Reverse, bI3Reverse : Boolean; begin if not Assigned( AText ) then Exit; AText.Clear; if FUSequence <> stABC then AText.Add( 'U' + GetSequenceTypeStr( FUSequence, Fabc ) ); if FPhaseType = ptFour then begin if FUaBroken or FUbBroken or FUcBroken or FUnBroken then begin s := EmptyStr; case Fabc of 0: begin if FUaBroken then s := s + 'Ua,'; if FUbBroken then s := s + 'Ub,'; if FUcBroken then s := s + 'Uc,'; if FUnBroken then s := s + 'Un,'; end; 1: begin if FUaBroken then s := s + 'Uu,'; if FUbBroken then s := s + 'Uv,'; if FUcBroken then s := s + 'Uw,'; if FUnBroken then s := s + 'Un,'; end; 2: begin if FUaBroken then s := s + 'U1,'; if FUbBroken then s := s + 'U2,'; if FUcBroken then s := s + 'U3,'; if FUnBroken then s := s + 'Un,'; end; end; { if Fabc then begin if FUaBroken then s := s + 'Ua,'; if FUbBroken then s := s + 'Ub,'; if FUcBroken then s := s + 'Uc,'; if FUnBroken then s := s + 'Un,'; end else begin if FUaBroken then s := s + 'Uu,'; if FUbBroken then s := s + 'Uv,'; if FUcBroken then s := s + 'Uw,'; if FUnBroken then s := s + 'Un,'; end; } AText.Add( Copy( s, 1, Length( s ) - 1 ) + '电压断'); end; end else if FPhaseType = ptThree then begin if FUaBroken or FUbBroken or FUcBroken then begin s := EmptyStr; case Fabc of 0: begin if FUaBroken then s := s + 'A相,'; if FUbBroken then s := s + 'B相,'; if FUcBroken then s := s + 'C相,'; end; 1: begin if FUaBroken then s := s + 'U相,'; if FUbBroken then s := s + 'V相,'; if FUcBroken then s := s + 'W相,'; end; 2: begin if FUaBroken then s := s + '1相,'; if FUbBroken then s := s + '2相,'; if FUcBroken then s := s + '3相,'; end; end; { if Fabc then begin if FUaBroken then s := s + 'A相,'; if FUbBroken then s := s + 'B相,'; if FUcBroken then s := s + 'C相,'; end else begin if FUaBroken then s := s + 'U相,'; if FUbBroken then s := s + 'V相,'; if FUcBroken then s := s + 'W相,'; end; } AText.Add( Copy( s, 1, Length( s ) - 1 ) + ' 一次失压'); end; if FUsaBroken or FUsbBroken or FUscBroken then begin s := EmptyStr; { if Fabc then begin if FUsaBroken then s := s + 'a相,'; if FUsbBroken then s := s + 'b相,'; if FUscBroken then s := s + 'c相,'; end else begin if FUsaBroken then s := s + 'u相,'; if FUsbBroken then s := s + 'v相,'; if FUscBroken then s := s + 'w相,'; end; } case Fabc of 0: begin if FUsaBroken then s := s + 'a相,'; if FUsbBroken then s := s + 'b相,'; if FUscBroken then s := s + 'c相,'; end; 1: begin if FUsaBroken then s := s + 'u相,'; if FUsbBroken then s := s + 'v相,'; if FUscBroken then s := s + 'w相,'; end; 2: begin if FUsaBroken then s := s + '1相,'; if FUsbBroken then s := s + '2相,'; if FUscBroken then s := s + '3相,'; end; end; AText.Add( Copy( s, 1, Length( s ) - 1 ) + '二次失压'); end; if FGroundBroken then AText.Add('电压接地断开'); if FPT1Reverse or FPT2Reverse then begin s := EmptyStr; if Fptct then begin if FPT1Reverse then s := s + 'PT1,'; if FPT2Reverse then s := s + 'PT2,'; end else begin if FPT1Reverse then s := s + 'TV1,'; if FPT2Reverse then s := s + 'TV2,'; end; AText.Add( Copy( s, 1, Length( s ) - 1 ) + '极性反' ); end; end else if FPhaseType = ptFourPT then begin if FUaBroken or FUbBroken or FUcBroken then begin s := EmptyStr; { if Fabc then begin if FUaBroken then s := s + 'A相,'; if FUbBroken then s := s + 'B相,'; if FUcBroken then s := s + 'C相,'; end else begin if FUaBroken then s := s + 'U相,'; if FUbBroken then s := s + 'V相,'; if FUcBroken then s := s + 'W相,'; end; } case Fabc of 0: begin if FUaBroken then s := s + 'A相,'; if FUbBroken then s := s + 'B相,'; if FUcBroken then s := s + 'C相,'; end; 1: begin if FUaBroken then s := s + 'U相,'; if FUbBroken then s := s + 'V相,'; if FUcBroken then s := s + 'W相,'; end; 2: begin if FUaBroken then s := s + '1相,'; if FUbBroken then s := s + '2相,'; if FUcBroken then s := s + '3相,'; end; end; AText.Add( Copy( s, 1, Length( s ) - 1 ) + '一次失压' ); end; if FUsaBroken or FUsbBroken or FUscBroken or FUsnBroken or FGroundBroken then begin s := EmptyStr; {if Fabc then begin if FUsaBroken then s := s + 'a相,'; if FUsbBroken then s := s + 'b相,'; if FUscBroken then s := s + 'c相,'; end else begin if FUsaBroken then s := s + 'u相,'; if FUsbBroken then s := s + 'v相,'; if FUscBroken then s := s + 'w相,'; end; } case Fabc of 0: begin if FUsaBroken then s := s + 'a相,'; if FUsbBroken then s := s + 'b相,'; if FUscBroken then s := s + 'c相,'; end; 1: begin if FUsaBroken then s := s + 'u相,'; if FUsbBroken then s := s + 'v相,'; if FUscBroken then s := s + 'w相,'; end; 2: begin if FUsaBroken then s := s + '1相,'; if FUsbBroken then s := s + '2相,'; if FUscBroken then s := s + '3相,'; end; end; if FUsnBroken then s := s + 'n相,'; AText.Add(Copy( s, 1, Length( s ) - 1 ) + '二次失压'); end; if FGroundBroken then AText.Add('电压接地断开'); if FPT1Reverse or FPT2Reverse or FPT3Reverse then begin s := EmptyStr; if Fptct then begin if FPT1Reverse then s := s + 'PT1,'; if FPT2Reverse then s := s + 'PT2,'; if FPT3Reverse then s := s + 'PT3,'; end else begin if FPT1Reverse then s := s + 'TV1,'; if FPT2Reverse then s := s + 'TV2,'; if FPT3Reverse then s := s + 'TV3,'; end; AText.Add( Copy( s, 1, Length( s ) - 1 ) + '极性反' ); end; end; if (FPhaseType = ptFour ) or (FPhaseType = ptFourPT )then begin s := EmptyStr; // 简化接线 if FIsClearLinke then begin GetClearLinkeISequence(sI1, sI2, sI3,bI1Reverse, bI2Reverse, bI3Reverse); if sI1 + sI2 + sI3 <> 'ABC' then s := 'I' + LowerCase(sI1 + sI2 + sI3) end else begin if FISequence <> stABC then s := 'I' + GetSequenceTypeStr( FISequence, Fabc ) end; if FI1Reverse then s := s + ' 元件1反接'; if FI2Reverse then s := s + ' 元件2反接'; if FI3Reverse then s := s + ' 元件3反接'; if s <> EmptyStr then AText.Add( s ); end else begin s := EmptyStr; // 三相三相三线简化接线 if FIsClearLinke then begin // 表尾电流接线 if (I1In in [plA, plN]) and (I1Out in [plA, plN]) and (I2In in [plC, plN]) and (I2Out in [plC, plN]) then begin // s := GetPhaseValue(1) +GetPhaseValue(3); s := ''; if (I1In = plN) and (I1Out = plA) then s := s + ' 元件1反接'; if (I2In = plN) and (I2Out = plC) then s := s + ' 元件2反接'; end; if (I1In in [plC, plN]) and (I1Out in [plC, plN]) and (I2In in [plA, plN]) and (I2Out in [plA, plN]) then begin s := GetPhaseValue(3) +GetPhaseValue(1); if (I1In = plN) and (I1Out = plC) then s := s + ' 元件1反接'; if (I2In = plN) and (I2Out = plA) then s := s + ' 元件2反接'; end; if (I1In in [plA, plC]) and (I1Out in [plA, plC]) and (I2In in [plC, plN]) and (I2Out in [plC, plN]) then begin s := GetPhaseValue(1) +GetPhaseValue(2); if (I1In = plC) and (I1Out = plA) then s := s + ' 元件1反接'; if (I2In = plC) and (I2Out = plN) then s := s + ' 元件2反接'; end; if (I1In in [plC, plA]) and (I1Out in [plC, plA]) and (I2In in [plA, plN]) and (I2Out in [plA, plN]) then begin s := GetPhaseValue(3) +GetPhaseValue(2); if (I1In = plA) and (I1Out = plC) then s := s + ' 元件1反接'; if (I2In = plA) and (I2Out = plN) then s := s + ' 元件2反接'; end; if (I1In in [plN, plA]) and (I1Out in [plN, plA]) and (I2In in [plC, plA]) and (I2Out in [plC, plA]) then begin s := GetPhaseValue(2) +GetPhaseValue(3); if (I1In = plA) and (I1Out = plN) then s := s + ' 元件1反接'; if (I2In = plA) and (I2Out = plC) then s := s + ' 元件2反接'; end; if (I1In in [plN, plC]) and (I1Out in [plN, plC]) and (I2In in [plA, plC]) and (I2Out in [plA, plC]) then begin s := GetPhaseValue(2) +GetPhaseValue(1); if (I1In = plC) and (I1Out = plN) then s := s + ' 元件1反接'; if (I2In = plC) and (I2Out = plA) then s := s + ' 元件2反接'; end; end else begin if ( FI1In <> plA ) and ( FI1Out <> plA ) then begin case Fabc of 0: s := 'IcIa'; 1: s := 'IwIu'; 2: s := 'I3I1'; end; end; if FI1In = plN then begin s := s + ' 元件1反接'; end; if FI2In = plN then begin s := s + ' 元件2反接'; end; end; // if ( FI1In <> plA ) or ( FI1Out <> plN ) then // s := s + Format( '一件进I%s出I%s,', [ GetPhaseLineTypeStr( FI1In, Fabc ), // GetPhaseLineTypeStr( FI1Out ) ] ); // // if ( FI2In <> plC ) or ( FI2Out <> plN ) then // s := s + Format( '二元件进I%s出I%s,', [ GetPhaseLineTypeStr( FI2In, Fabc ), // GetPhaseLineTypeStr( FI2Out ) ] ); if s <> EmptyStr then AText.Add( s ); end; if FCT1Reverse or FCT2Reverse or FCT3Reverse then begin s := EmptyStr; if Fptct then begin if FCT1Reverse then s := s + 'CT1,'; if FCT2Reverse then s := s + 'CT2,'; if FCT3Reverse then s := s + 'CT3,'; end else begin if FCT1Reverse then s := s + 'TA1,'; if FCT2Reverse then s := s + 'TA2,'; if FCT3Reverse then s := s + 'TA3,'; end; AText.Add(Copy( s, 1, Length( s ) - 1 ) + '极性反'); end; if FCT1Short or FCT2Short or FCT3Short then begin s := EmptyStr; if Fptct then begin if FCT1Short then s := s + 'CT1,'; if FCT2Short then s := s + 'CT2,'; if FCT3Short then s := s + 'CT3,'; end else begin if FCT1Short then s := s + 'TA1,'; if FCT2Short then s := s + 'TA2,'; if FCT3Short then s := s + 'TA3,'; end; AText.Add(Copy( s, 1, Length( s ) - 1 ) + '短路'); end; if FIaBroken or FIbBroken or FIcBroken or FInBroken then begin s := EmptyStr; { if Fabc then BEGIN if FIaBroken then s := s + 'Ia,'; if FIbBroken then s := s + 'Ib,'; if FIcBroken then s := s + 'Ic,'; if FInBroken then s := s + 'In,'; END ELSE begin if FIaBroken then s := s + 'Iu,'; if FIbBroken then s := s + 'Iv,'; if FIcBroken then s := s + 'Iw,'; if FInBroken then s := s + 'In,'; end; } case Fabc of 0: begin if FIaBroken then s := s + 'Ia,'; if FIbBroken then s := s + 'Ib,'; if FIcBroken then s := s + 'Ic,'; if FInBroken then s := s + 'In,'; end; 1: begin if FIaBroken then s := s + 'Iu,'; if FIbBroken then s := s + 'Iv,'; if FIcBroken then s := s + 'Iw,'; if FInBroken then s := s + 'In,'; end; 2: begin if FIaBroken then s := s + 'I1,'; if FIbBroken then s := s + 'I2,'; if FIcBroken then s := s + 'I3,'; if FInBroken then s := s + 'In,'; end; end; AText.Add( Copy( s, 1, Length( s ) - 1 ) + '开路' ); end; if FIaGroundBroken or FIbGroundBroken or FIcGroundBroken or FIGroundBroken then begin s := EmptyStr; if FIaGroundBroken then s := s + 'Ia,'; if FIbGroundBroken then s := s + 'Ib,'; if FIcGroundBroken then s := s + 'Ic,'; // if FIcGroundBroken then s := s + '全部,'; AText.Add( Copy( s, 1, Length( s ) - 1 ) + '接地断开' ); end; end; function TWIRING_ERROR.GetErrorCount: Integer; function CalErrorCount3(AErrCode: Integer): Integer; var i: Integer; begin Result := 0; for i := 0 to 7 do if AErrCode and ( 1 shl i ) = 1 shl i then Inc( Result ); if (AErrCode and ( 1 shl 8 )+AErrCode and ( 1 shl 9 )) >0 then Inc( Result ); for i := 16 to 23 do if AErrCode and ( 1 shl i ) = 1 shl i then Inc( Result ); if AErrCode and ( 7 shl 24 ) <> 0 then Inc( Result ); end; function CalErrorCount4(AErrCode: Integer): Integer; var i: Integer; begin Result := 0; for i := 0 to 10 do if AErrCode and ( 1 shl i ) = 1 shl i then Inc( Result ); for i := 16 to 19 do if AErrCode and ( 1 shl i ) = 1 shl i then Inc( Result ); if AErrCode and ( 7 shl 12 ) <> 0 then Inc( Result ); if AErrCode and ( 7 shl 24 ) <> 0 then Inc( Result ); end; begin if FPhaseType = ptThree then Result := CalErrorCount3(ID) else Result := CalErrorCount4(ID); end; function TWIRING_ERROR.GetID: Cardinal; begin if FPhaseType = ptThree then Result := GetIDThree else if FPhaseType = ptFour then Result := GetIDFour else Result := GetIDFourPT; end; function TWIRING_ERROR.GetIDFour: Cardinal; begin // 四线编码, 此处参考编码规则 Result := C_WE_ID_BASE_FOUR; Result := Result + Cardinal( FUSequence ) shl 24; Result := Result + Cardinal( FUaBroken ) shl 16; Result := Result + Cardinal( FUbBroken ) shl 17; Result := Result + Cardinal( FUcBroken ) shl 18; Result := Result + Cardinal( FUnBroken ) shl 19; Result := Result + Cardinal( FISequence ) shl 12; Result := Result + Cardinal( FCT1Reverse ) shl 8; Result := Result + Cardinal( FCT2Reverse ) shl 9; Result := Result + Cardinal( FCT3Reverse ) shl 10; Result := Result + Cardinal( FCT1Short ) shl 4; Result := Result + Cardinal( FCT2Short ) shl 5; Result := Result + Cardinal( FCT3Short ) shl 6; Result := Result + Cardinal( FIaBroken ) shl 0; Result := Result + Cardinal( FIbBroken ) shl 1; Result := Result + Cardinal( FIcBroken ) shl 2; end; function TWIRING_ERROR.GetIDFourPT: Cardinal; begin // 四线编码, 此处参考编码规则 Result := C_WE_ID_BASE_FOUR_PT; Result := Result + Cardinal( FUSequence ) shl 24; Result := Result + Cardinal( FUaBroken ) shl 16; Result := Result + Cardinal( FUbBroken ) shl 17; Result := Result + Cardinal( FUcBroken ) shl 18; Result := Result + Cardinal( FUnBroken ) shl 19; //带PT 胡红明2013.5.28 位置不够,用了剩下的几个空位 Result := Result + Cardinal(FUsaBroken) shl 20; Result := Result + Cardinal(FUsbBroken) shl 21; Result := Result + Cardinal(FUscBroken) shl 22; Result := Result + Cardinal(FUsnBroken) shl 23; Result := Result + Cardinal(FGroundBroken) shl 15; Result := Result + Cardinal(FPT1Reverse) shl 3; Result := Result + Cardinal(FPT2Reverse) shl 7; Result := Result + Cardinal(FPT3Reverse) shl 11; Result := Result + Cardinal( FISequence ) shl 12; Result := Result + Cardinal( FCT1Reverse ) shl 8; Result := Result + Cardinal( FCT2Reverse ) shl 9; Result := Result + Cardinal( FCT3Reverse ) shl 10; Result := Result + Cardinal( FCT1Short ) shl 4; Result := Result + Cardinal( FCT2Short ) shl 5; Result := Result + Cardinal( FCT3Short ) shl 6; Result := Result + Cardinal( FIaBroken ) shl 0; Result := Result + Cardinal( FIbBroken ) shl 1; Result := Result + Cardinal( FIcBroken ) shl 2; // 新加表尾电流反接 Result := Result + Cardinal(FI1Reverse) shl 28; Result := Result + Cardinal(FI2Reverse) shl 29; Result := Result + Cardinal(FI3Reverse) shl 30; end; function TWIRING_ERROR.GetIDThree: Cardinal; begin // 三线编码, 此处参考编码规则 Result := C_WE_ID_BASE_THREE; Result := Result + Cardinal( FUSequence ) shl 24; Result := Result + Cardinal( FUaBroken ) shl 16; Result := Result + Cardinal( FUbBroken ) shl 17; Result := Result + Cardinal( FUcBroken ) shl 18; Result := Result + Cardinal( FUsaBroken ) shl 19; Result := Result + Cardinal( FUsbBroken ) shl 20; Result := Result + Cardinal( FUscBroken ) shl 21; Result := Result + Cardinal( FPT1Reverse ) shl 22; Result := Result + Cardinal( FPT2Reverse ) shl 23; /////////???????????//// case FI1In of plA: Result := Result + 0 shl 8; plN: Result := Result + 1 shl 8; plC: Result := Result + 2 shl 8; end; case FI1Out of plN : Result := Result + 0 shl 10; plA : Result := Result + 1 shl 10; plC : Result := Result + 2 shl 10; end; case FI2In of plC: Result := Result + 0 shl 12; plN: Result := Result + 1 shl 12; plA: Result := Result + 2 shl 12; end; case FI2Out of plN: Result := Result + 0 shl 14; plA: Result := Result + 1 shl 14; plC: Result := Result + 2 shl 14; end; Result := Result + Cardinal( FCT1Reverse ) shl 6; Result := Result + Cardinal( FCT2Reverse ) shl 7; Result := Result + Cardinal( FCT1Short ) shl 4; Result := Result + Cardinal( FCT2Short ) shl 5; Result := Result + Cardinal( FIaBroken ) shl 0; Result := Result + Cardinal( FIcBroken ) shl 2; Result := Result + Cardinal( FInBroken ) shl 3; end; function TWIRING_ERROR.IDInStr: string; begin Result := IntToHex( GetID, 8 ); end; function TWIRING_ERROR.IsCorrect: Boolean; begin if FPhaseType = ptThree then Result := GetID = C_WE_ID_CORRECT_THREE else if FPhaseType = ptFour then Result := GetID = C_WE_ID_CORRECT_FOUR else Result := GetID = C_WE_ID_CORRECT_FOUR_PT; end; procedure TWIRING_ERROR.SetClearLinkeISequence(sI1, sI2, sI3: string; bI1Reverse, bI2Reverse, bI3Reverse : Boolean); procedure SetInOut(AI1In, AI1Out, AI2In, AI2Out, AI3In, AI3Out : TWE_PHASE_LINE_TYPE); begin if bI1Reverse then begin I1In := AI1Out; I1Out := AI1In; end else begin I1In := AI1In; I1Out := AI1Out; end; if bI2Reverse then begin I2In := AI2Out; I2Out := AI2In; end else begin I2In := AI2In; I2Out := AI2Out; end; if bI3Reverse then begin I3In := AI3Out; I3Out := AI3In; end else begin I3In := AI3In; I3Out := AI3Out; end; end; var s : string; begin s := UpperCase(sI1) + UpperCase(sI2) + UpperCase(sI3); if s = 'ABC' then SetInOut(plA, plN, plB, plN,plC, plN); if s = 'ACB' then SetInOut(plA, plN, plC, plN,plB, plN); if s = 'ABN' then SetInOut(plA, plC, plB, plC,plN, plC); if s = 'ACN' then SetInOut(plA, plB, plC, plB,plN, plB); if s = 'ANB' then SetInOut(plA, plC, plN, plC,plB, plC); if s = 'ANC' then SetInOut(plA, plB, plN, plB,plC, plB); if s = 'BAN' then SetInOut(plB, plC, plA, plC,plN, plC); if s = 'BCN' then SetInOut(plB, plA, plC, plA,plN, plA); if s = 'BNA' then SetInOut(plB, plC, plN, plC,plA, plC); if s = 'BNC' then SetInOut(plB, plA, plN, plA,plC, plA); if s = 'BAC' then SetInOut(plB, plN, plA, plN,plC, plN); if s = 'BCA' then SetInOut(plB, plN, plC, plN,plA, plN); if s = 'CBN' then SetInOut(plC, plA, plB, plA,plN, plA); if s = 'CAN' then SetInOut(plC, plB, plA, plB,plN, plB); if s = 'CNB' then SetInOut(plC, plA, plN, plA,plB, plA); if s = 'CNA' then SetInOut(plC, plB, plN, plB,plA, plB); if s = 'CAB' then SetInOut(plC, plN, plA, plN,plB, plN); if s = 'CBA' then SetInOut(plC, plN, plB, plN,plA, plN); if s = 'NBC' then SetInOut(plN, plA, plB, plA,plC, plA); if s = 'NBA' then SetInOut(plN, plC, plB, plC,plA, plC); if s = 'NCB' then SetInOut(plN, plA, plC, plA,plB, plA); if s = 'NCA' then SetInOut(plN, plB, plC, plB,plA, plB); if s = 'NAB' then SetInOut(plN, plC, plA, plC,plB, plC); if s = 'NAC' then SetInOut(plN, plB, plA, plB,plC, plB); end; procedure TWIRING_ERROR.SetI1In(const Value: TWE_PHASE_LINE_TYPE); begin FI1In := Value; end; procedure TWIRING_ERROR.SetIaGroundBroken(const Value: Boolean); begin FIaGroundBroken := Value; end; procedure TWIRING_ERROR.SetID(const Value: Cardinal); begin Clear; // 清空错误 if Value and C_WE_ID_BASE_FOUR_PT = C_WE_ID_BASE_FOUR_PT then SetIDFourPT(Value) else if Value >= C_WE_ID_BASE_FOUR then SetIDFour( Value ) else if Value >= C_WE_ID_BASE_THREE then SetIDThree( Value ) else raise Exception.Create( '错误编码无效!' ); end; procedure TWIRING_ERROR.SetIDFour(const Value: Cardinal); begin FPhaseType := ptFour; // 四线编码, 此处参考编码规则 FUSequence := TWE_SEQUENCE_TYPE( ( Value shr 24 ) and 7 ); FUaBroken := BitIsOne( Value, 16 ); FUbBroken := BitIsOne( Value, 17 ); FUcBroken := BitIsOne( Value, 18 ); FUnBroken := BitIsOne( Value, 19 ); FISequence := TWE_SEQUENCE_TYPE( ( Value shr 12 ) and 7 ); FCT1Reverse := BitIsOne( Value, 8 ); FCT2Reverse := BitIsOne( Value, 9 ); FCT3Reverse := BitIsOne( Value, 10 ); FCT1Short := BitIsOne( Value, 4 ); FCT2Short := BitIsOne( Value, 5 ); FCT3Short := BitIsOne( Value, 6 ); FIaBroken := BitIsOne( Value, 0 ); FIbBroken := BitIsOne( Value, 1 ); FIcBroken := BitIsOne( Value, 2 ); end; procedure TWIRING_ERROR.SetIDFourPT(const Value: Cardinal); begin FPhaseType := ptFourPT; // 四线编码, 此处参考编码规则 FUSequence := TWE_SEQUENCE_TYPE( ( Value shr 24 ) and 7 ); FUaBroken := BitIsOne( Value, 16 ); FUbBroken := BitIsOne( Value, 17 ); FUcBroken := BitIsOne( Value, 18 ); FUnBroken := BitIsOne( Value, 19 ); //带PT 胡红明2013.5.28 FUsaBroken := BitIsOne( Value, 20); FUsbBroken := BitIsOne( Value, 21); FUscBroken := BitIsOne( Value, 22); FUsnBroken := BitIsOne( Value, 23); FGroundBroken := BitIsOne(Value, 15); FPT1Reverse := BitIsOne(Value, 3); FPT2Reverse := BitIsOne(Value, 7); FPT3Reverse := BitIsOne(Value, 11); FISequence := TWE_SEQUENCE_TYPE( ( Value shr 12 ) and 7 ); FCT1Reverse := BitIsOne( Value, 8 ); FCT2Reverse := BitIsOne( Value, 9 ); FCT3Reverse := BitIsOne( Value, 10 ); FCT1Short := BitIsOne( Value, 4 ); FCT2Short := BitIsOne( Value, 5 ); FCT3Short := BitIsOne( Value, 6 ); FIaBroken := BitIsOne( Value, 0 ); FIbBroken := BitIsOne( Value, 1 ); FIcBroken := BitIsOne( Value, 2 ); FI1Reverse := BitIsOne( Value, 28 ); FI2Reverse := BitIsOne( Value, 29 ); FI3Reverse := BitIsOne( Value, 30 ); end; procedure TWIRING_ERROR.SetIDThree(const Value: Cardinal); begin FPhaseType := ptThree; // 三线编码, 此处参考编码规则 FUSequence := TWE_SEQUENCE_TYPE( ( Value shr 24 ) and 7 ); FPT1Reverse := BitIsOne( Value, 22 ); FPT2Reverse := BitIsOne( Value, 23 ); FUsaBroken := BitIsOne( Value, 19 ); FUsbBroken := BitIsOne( Value, 20 ); FUscBroken := BitIsOne( Value, 21 ); FUaBroken := BitIsOne( Value, 16 ); FUbBroken := BitIsOne( Value, 17 ); FUcBroken := BitIsOne( Value, 18 ); //////////////???????????? case ( Value shr 8 ) and 3 of 0 : FI1In := plA; 1 : FI1In := plN; 2 : FI1In := plC; end; case ( Value shr 10 ) and 3 of 0 : FI1Out := plN; 1 : FI1Out := plA; 2 : FI1Out := plC; end; case ( Value shr 12 ) and 3 of 0 : FI2In := plC; 1 : FI2In := plN; 2 : FI2In := plA; end; case ( Value shr 14 ) and 3 of 0 : FI2Out := plN; 1 : FI2Out := plA; 2 : FI2Out := plC; end; FCT1Reverse := BitIsOne( Value, 6 ); FCT2Reverse := BitIsOne( Value, 7 ); FCT1Short := BitIsOne( Value, 4 ); FCT2Short := BitIsOne( Value, 5 ); FIaBroken := BitIsOne( Value, 0 ); FIcBroken := BitIsOne( Value, 2 ); FInBroken := BitIsOne( Value, 3 ); end; procedure TWIRING_ERROR.SetPhaseType(const Value: TWE_PHASE_TYPE); begin if Value <> FPhaseType then begin FPhaseType := Value; Clear; end; end; procedure TWIRING_ERROR.SetToCorrect; begin if FPhaseType = ptThree then SetID( C_WE_ID_CORRECT_THREE ) else if FPhaseType = ptFour then SetID( C_WE_ID_CORRECT_FOUR ) else SetID( C_WE_ID_CORRECT_FOUR_PT ) end; function TWIRING_ERROR.UHasBroken: Boolean; begin Result := ( GetID shr 16 ) and $3F > 0; end; end.
{*******************************************************} { } { Delphi DataSnap Framework } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit DSAzureMessageDialog; interface uses Vcl.Buttons, System.Classes, Vcl.Controls, DSAzureQueue, Vcl.ExtCtrls, Vcl.Forms, Vcl.Graphics, Vcl.Grids, Vcl.StdCtrls, Vcl.ValEdit; type TAzureMsgDialog = class(TForm) ValueList: TValueListEditor; closeButton: TButton; procedure closeButtonClick(Sender: TObject); public procedure SetMessage(Msg: TMessageNodeData); end; implementation {$R *.dfm} uses System.SysUtils; const MSG_ID = 'MessageId='; MSG_INSERT = 'InsertionTime='; MSG_EXPIRE = 'ExpirationTime='; MSG_DEQUE = 'DequeueCount='; MSG_TEXT = 'MessageText='; { TAzureMsgDialog } procedure TAzureMsgDialog.closeButtonClick(Sender: TObject); begin Close; end; procedure TAzureMsgDialog.SetMessage(Msg: TMessageNodeData); begin ValueList.Strings.BeginUpdate; try ValueList.Strings.Clear; ValueList.Strings.Add(MSG_ID + Msg.MessageId); ValueList.Strings.Add(MSG_INSERT + Msg.InsertTime); ValueList.Strings.Add(MSG_EXPIRE + Msg.ExpireTime); ValueList.Strings.Add(MSG_DEQUE + IntToStr(Msg.DequeueCount)); ValueList.Strings.Add(MSG_TEXT + Msg.MessageText); finally ValueList.Strings.EndUpdate; end; end; end.
unit upaymo; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fphttpclient, jsonConf, fpjson, jsonparser, Dialogs, DateUtils; const PAYMOAPIBASEURL = 'https://app.paymoapp.com/api/'; PAYMOAPIKEYURL = 'https://app.paymoapp.com/#Paymo.module.myaccount/'; type TPaymoResponseStatus = (prOK, prERROR, prTRYAGAIN); { TPaymo } TPaymo = class(TObject) private FAPIKey: string; FLoggedIn: boolean; FMe: TJSONObject; FProjects: TJSONObject; FRunningTimer: TJSONObject; FTaskLists: TJSONObject; FTasks: TJSONObject; FCompany: TJSONObject; procedure SetFAPIKey(AValue: string); procedure SetFLoggedIn(AValue: boolean); public function ProjectsArray: TJSONArray; function TasksArray: TJSONArray; function TaskListsArray: TJSONArray; function MyData: TJSONData; function CompanyData: TJSONData; function RunningTimerData: TJSONData; function GetProjectName(ProjectID: integer): string; function GetTaskName(TaskID: integer): string; function GetTimeEntry(EntryID: integer): TJSONData; public destructor Destroy; override; property APIKey: string read FAPIKey write SetFAPIKey; property LoggedIn: boolean read FLoggedIn write SetFLoggedIn; function Login: TPaymoResponseStatus; function Get(Endpoint: string; var Response: string): TPaymoResponseStatus; function GetTasks(): TPaymoResponseStatus; function GetProjects(): TPaymoResponseStatus; function GetTaskLists(): TPaymoResponseStatus; function GetMe(): TPaymoResponseStatus; function GetRunningTimer(): TPaymoResponseStatus; function GetCompany(): TPaymoResponseStatus; function Post(Endpoint: string; sJSON: TJSONStringType; var Response: string): TPaymoResponseStatus; function Delete(Endpoint: string; var Response: string): TPaymoResponseStatus; function CreateTask(Name, Description: string; TaskListID: integer; var task: TJSONData): TPaymoResponseStatus; function StopRunningTimer(start_time, end_time: TDateTime; Description: string): TPaymoResponseStatus; function StartRunningTimer(task_id: integer): TPaymoResponseStatus; function DeleteTimeEntry(TimeEntryID: string): TPaymoResponseStatus; function UpdateTimeEntry(TimeEntryID: string; end_time: TDateTime; project_id, task_id, tasklist_id: string): TPaymoResponseStatus; public procedure LoadSettings; procedure SaveSettings; end; implementation { TPaymo } procedure TPaymo.SetFAPIKey(AValue: string); begin if FAPIKey = AValue then Exit; FAPIKey := AValue; end; procedure TPaymo.SetFLoggedIn(AValue: boolean); begin if FLoggedIn = AValue then Exit; FLoggedIn := AValue; end; function TPaymo.ProjectsArray: TJSONArray; begin FProjects.Find('projects', Result); end; function TPaymo.TasksArray: TJSONArray; begin FTasks.Find('tasks', Result); end; function TPaymo.TaskListsArray: TJSONArray; begin FTaskLists.Find('tasklists', Result); end; function TPaymo.MyData: TJSONData; var arr: TJSONArray; begin FMe.Find('users', arr); Result := arr[0]; end; function TPaymo.CompanyData: TJSONData; begin FCompany.Find('company', Result); end; function TPaymo.RunningTimerData: TJSONData; var arr: TJSONArray; begin if not Assigned(FRunningTimer) then exit(nil); FRunningTimer.Find('entries', arr); if (arr <> nil) and (arr.Count > 0) then Result := arr[0] else Result := nil; end; function TPaymo.GetProjectName(ProjectID: integer): string; var i: integer; arr: TJSONArray; begin Result := ''; arr := ProjectsArray; for i := 0 to arr.Count - 1 do begin if ProjectID = arr[i].GetPath('id').AsInteger then exit(arr[i].GetPath('name').AsString); end; end; function TPaymo.GetTaskName(TaskID: integer): string; var i: integer; arr: TJSONArray; begin Result := ''; arr := TasksArray; for i := 0 to arr.Count - 1 do begin if TaskID = arr[i].GetPath('id').AsInteger then exit(arr[i].GetPath('name').AsString); end; end; function TPaymo.GetTimeEntry(EntryID: integer): TJSONData; var arr, arrEntries: TJSONArray; i, j: integer; begin Result := nil; arr := TasksArray; for i := 0 to arr.Count - 1 do begin arrEntries := TJSONArray(arr[i].GetPath('entries')); for j := 0 to arrEntries.Count - 1 do begin if arrEntries[j].GetPath('id').AsInteger = EntryID then exit(arrEntries[j]); end; end; end; destructor TPaymo.Destroy; begin if Assigned(FProjects) then FProjects.Free; if Assigned(FTasks) then FTasks.Free; if Assigned(FMe) then FMe.Free; if Assigned(FTaskLists) then FTaskLists.Free; if Assigned(FRunningTimer) then FRunningTimer.Free; if Assigned(FCompany) then FCompany.Free; inherited Destroy; end; function TPaymo.Login: TPaymoResponseStatus; begin Result := GetMe(); case Result of prOK: FLoggedIn := True; prTRYAGAIN: FLoggedIn := False; prERROR: FLoggedIn := False; end; end; function TPaymo.Get(Endpoint: string; var Response: string): TPaymoResponseStatus; var client: TFPHTTPClient; begin Result := prERROR; try client := TFPHttpClient.Create(nil); client.AddHeader('Accept', 'application/json'); client.UserName := FAPIKey; client.Password := ''; try Response := client.Get(PAYMOAPIBASEURL + Endpoint); if (client.ResponseStatusCode >= 200) and (client.ResponseStatusCode <= 300) then Result := prOK else if (client.ResponseStatusCode = 429) then Result := prTRYAGAIN else Result := prERROR; except Result := prERROR; end; finally client.Free; end; end; function TPaymo.GetTasks(): TPaymoResponseStatus; var response: string; begin Result := Get('tasks?where=mytasks=true&include=entries', response); case Result of prOK: begin if Assigned(FTasks) then FTasks.Free; FTasks := TJSONObject(GetJSON(response)); end; end; end; function TPaymo.GetProjects(): TPaymoResponseStatus; var response: string; begin Result := Get('projects', response); case Result of prOK: begin if Assigned(FProjects) then FProjects.Free; FProjects := TJSONObject(GetJSON(response)); end; end; end; function TPaymo.GetTaskLists(): TPaymoResponseStatus; var response: string; begin Result := Get('tasklists', response); case Result of prOK: begin if Assigned(FTaskLists) then FTaskLists.Free; FTaskLists := TJSONObject(GetJSON(response)); end; end; end; function TPaymo.GetMe(): TPaymoResponseStatus; var response: string; begin Result := Get('me', response); case Result of prOK: begin if Assigned(FMe) then FMe.Free; FMe := TJSONObject(GetJSON(response)); end; end; end; function TPaymo.GetRunningTimer(): TPaymoResponseStatus; var response: string; begin Result := Get('entries?where=user_id=' + MyData.GetPath('id').AsString + '%20and%20end_time=null', response); case Result of prOK: begin if Assigned(FRunningTimer) then FRunningTimer.Free; FRunningTimer := TJSONObject(GetJSON(response)); end; end; end; function TPaymo.GetCompany(): TPaymoResponseStatus; var response: string; begin Result := Get('company', response); case Result of prOK: begin if Assigned(FCompany) then FCompany.Free; FCompany := TJSONObject(GetJSON(response)); end; end; end; function TPaymo.Post(Endpoint: string; sJSON: TJSONStringType; var Response: string): TPaymoResponseStatus; var client: TFPHTTPClient; ss: TMemoryStream; begin Result := prERROR; try client := TFPHttpClient.Create(nil); client.AddHeader('Content-type', 'application/json'); client.AddHeader('Accept', 'application/json'); client.UserName := FAPIKey; client.Password := ''; ss := TMemoryStream.Create(); ss.Write(Pointer(sJSON)^, length(sJSON)); ss.Position := 0; client.RequestBody := ss; try Response := client.Post(PAYMOAPIBASEURL + Endpoint); if (client.ResponseStatusCode >= 200) and (client.ResponseStatusCode <= 300) then Result := prOK else if (client.ResponseStatusCode = 429) then Result := prTRYAGAIN else Result := prERROR; except Result := prERROR; end; finally ss.Free; client.Free; end; end; function TPaymo.Delete(Endpoint: string; var Response: string): TPaymoResponseStatus; var client: TFPHTTPClient; begin Result := prERROR; try client := TFPHttpClient.Create(nil); client.AddHeader('Accept', 'application/json'); client.UserName := FAPIKey; client.Password := ''; try Response := client.Delete(PAYMOAPIBASEURL + Endpoint); if (client.ResponseStatusCode >= 200) and (client.ResponseStatusCode <= 300) then Result := prOK else if (client.ResponseStatusCode = 429) then Result := prTRYAGAIN else Result := prERROR; except Result := prERROR; end; finally client.Free; end; end; function TPaymo.CreateTask(Name, Description: string; TaskListID: integer; var task: TJSONData): TPaymoResponseStatus; var response: string; sJSON: TJSONStringType; jObj: TJSONObject; jArr: TJSONArray; begin // logged in user jArr := TJSONArray.Create([MyData.GetPath('id').AsInteger]); jObj := TJSONObject.Create; jObj.Add('name', Name); jObj.Add('description', Description); jObj.Add('tasklist_id', TaskListID); jObj.Add('users', jArr); sJSON := jObj.FormatJSON(); jObj.Free; Result := Post('tasks', sJSON, response); case Result of prOK: begin task := GetJSON(response).GetPath('tasks').Items[0]; TasksArray.Add(task); end; end; end; function TPaymo.StopRunningTimer(start_time, end_time: TDateTime; Description: string): TPaymoResponseStatus; var response: string; sJSON: TJSONStringType; jObj: TJSONObject; begin // https://github.com/paymoapp/api/blob/master/sections/entries.md#stopping-a-timer // more than a minute = POST if SecondsBetween(start_time, end_time) >= 60 then begin jObj := TJSONObject.Create; jObj.Add('end_time', FormatDateTime('yyyy-mm-dd"T"hh:nn:ss"Z"', LocalTimeToUniversal(end_time))); jObj.Add('description', Description); sJSON := jObj.FormatJSON(); jObj.Free; Result := Post('entries/' + RunningTimerData.GetPath('id').AsString, sJSON, response); end // less than a minute = DELETE else begin Result := Delete('entries/' + RunningTimerData.GetPath('id').AsString, response); end; end; function TPaymo.StartRunningTimer(task_id: integer): TPaymoResponseStatus; var response: string; sJSON: TJSONStringType; jObj: TJSONObject; begin jObj := TJSONObject.Create; jObj.Add('start_time', FormatDateTime('yyyy-mm-dd"T"hh:nn:ss"Z"', LocalTimeToUniversal(now))); jObj.Add('user_id', MyData.GetPath('id').AsInteger); jObj.Add('task_id', task_id); //jObj.Add('description', ''); sJSON := jObj.FormatJSON(); jObj.Free; Result := Post('entries', sJSON, response); end; function TPaymo.DeleteTimeEntry(TimeEntryID: string): TPaymoResponseStatus; var response: string; begin Result := Delete('entries/' + TimeEntryID, response); end; function TPaymo.UpdateTimeEntry(TimeEntryID: string; end_time: TDateTime; project_id, task_id, tasklist_id: string): TPaymoResponseStatus; var response: string; sJSON: TJSONStringType; jObj: TJSONObject; begin jObj := TJSONObject.Create; jObj.Add('end_time', FormatDateTime('yyyy-mm-dd"T"hh:nn:ss"Z"', LocalTimeToUniversal(end_time))); jObj.Add('project_id', project_id); jObj.Add('task_id', task_id); sJSON := jObj.FormatJSON(); jObj.Free; Result := Post('entries/' + TimeEntryID, sJSON, response); jObj := TJSONObject.Create; jObj.Add('tasklist_id', tasklist_id); sJSON := jObj.FormatJSON(); jObj.Free; Result := Post('tasks/' + task_id, sJSON, response); end; procedure TPaymo.LoadSettings; var c: TJSONConfig; begin c := TJSONConfig.Create(nil); try if ForceDirectories(GetAppConfigDir(False)) then begin c.Filename := GetAppConfigFile(False); APIKey := c.GetValue('apikey', ''); end; finally c.Free; end; end; procedure TPaymo.SaveSettings; var c: TJSONConfig; begin c := TJSONConfig.Create(nil); try if ForceDirectories(GetAppConfigDir(False)) then begin c.Filename := GetAppConfigFile(False); c.SetValue('apikey', APIKey); end; finally c.Free; end; end; end.
{$F-,A+,O+,G+,R-,S+,I+,Q-,V-,B-,X+,T-,P-,D-,L-,N-,E+} unit Config1; interface procedure cfgSystemConfig; implementation uses Crt, Global, Output, Strings, Input, Files, Config, Misc, StatBar, Logs, Users; procedure cfgMainBBSConfig; begin cfgDraw := True; cfgOver := False; repeat cfgInit('Main BBS Configuration'); cfgItem('A BBS name',40,Cfg^.bbsName, 'Name of this bulletin board system.'); cfgItem('B BBS phone number',13,Cfg^.bbsPhone, 'BBS phone number with area code.'); cfgItem('C BBS location',40,Cfg^.bbsLocation, 'Location of the BBS (format: city, state/prov)'); cfgItem('D SysOp handle',35,Cfg^.SysOpAlias, 'The SysOp''s alias or handle.'); cfgItem('E SysOp name',35,Cfg^.SysOpName, 'The SysOp''s first and last REAL name.'); cfgItem('F SysOp access password',20,Cfg^.SystemPW, 'Password required to use most extended SysOp commands. (Blank=Disabled)'); cfgItem('G Full sysop access',20,Cfg^.acsSysOp, 'Full SysOp access. Allows access to ALL modules of the board.'); cfgItem('H Full co-sysop access',20,Cfg^.acsCoSysOp, 'Full co-sysop access. Allows access to almost ALL areas of the board.'); cfgItem('I Direct video writes',3,B2St(Cfg^.DirectWrites), 'Write text to the screen "directly"? Should disable if MultiTasking'); cfgItem('J Snow checking (CGA)',3,B2St(Cfg^.SnowChecking), 'Check for CGA "snow" flickering? (Usually older monitors)'); cfgItem('K Load overlay to EMS',3,B2St(Cfg^.OverlayToEMS), 'Load overlay file into expanded memory (if available, otherwise disk)'); cfgItem('L Real name system',3,B2St(Cfg^.RealNameSystem), 'Do you want real names used only on the BBS? (no aliases/handles)'); cfgItem('M Show passwords',3,B2St(Cfg^.ShowPwLocal), 'Show actual characters in password instead of echo characters to local end?'); cfgItem('N Run '+bbsTitle+' as door',3,B2St(Cfg^.iniqAsDoor), 'When "'+paramQuitAfter+'" parameter is used, '+bbsTitle+' won''t hangup after calls.'); cfgItem('O Check inactivity',3,B2St(Cfg^.inactTime), 'Hangup on users when they have been excessively inactive'); cfgItem('P Inactivity timeout',6,St(Cfg^.inactSeconds), '[30-64000] Number of seconds that a user can idle before '+bbsTitle+' will hangup'); cfgItem('Q Inactivity warning',6,St(Cfg^.inactWarning), '[30-'+St(Cfg^.inactSeconds)+'] Number of seconds of inactivity before '+bbsTitle+' will warn user (beep)'); cfgItem('R Local inactivity',3,b2St(Cfg^.inactLocal), 'Check user inactivity when logged on locally?'); cfgItem('S Multi-node system?',3,b2St(Cfg^.MultiNode), 'Are you running a multiple node BBS? (reload '+bbstitle+' to take effect)'); cfgBar; cfgDrawAllItems; cfgPromptCommand; case cfgKey of 'A' : begin cfgReadInfo(Cfg^.bbsName,inNormal,chNormal,'',False); Cfg^.bbsName := cfgRead; cfgSetItem(Cfg^.bbsName); end; 'B' : begin cfgReadPhone; Cfg^.bbsPhone := cfgRead; cfgSetItem(Cfg^.bbsPhone); end; 'C' : begin cfgReadInfo(Cfg^.bbsLocation,inNormal,chNormal,'',False); Cfg^.bbsLocation := cfgRead; cfgSetItem(Cfg^.bbsLocation); end; 'D' : begin cfgReadInfo(Cfg^.SysOpAlias,inNormal,chNormal,'',False); Cfg^.SysOpAlias := cfgRead; cfgSetItem(Cfg^.SysOpAlias); end; 'E' : begin cfgReadInfo(Cfg^.SysOpName,inNormal,chNormal,'',False); Cfg^.SysOpName := cfgRead; cfgSetItem(Cfg^.SysOpName); end; 'F' : begin cfgReadInfo(Cfg^.SystemPW,inUpper,chNormal,'',False); Cfg^.SystemPW := cfgRead; cfgSetItem(Cfg^.SystemPW); end; 'G' : begin cfgReadInfo(Cfg^.acsSysOp,inLower,chNormal,'',True); Cfg^.acsSysOp := cfgRead; cfgSetItem(Cfg^.acsSysOp); end; 'H' : begin cfgReadInfo(Cfg^.acsCoSysOp,inLower,chNormal,'',True); Cfg^.acsCoSysOp := cfgRead; cfgSetItem(Cfg^.acsCoSysOp); end; 'I' : begin cfgReadBoolean(Cfg^.DirectWrites); cfgSetItem(B2St(Cfg^.DirectWrites)); DirectVideo := Cfg^.DirectWrites; end; 'J' : begin cfgReadBoolean(Cfg^.SnowChecking); cfgSetItem(B2St(Cfg^.SnowChecking)); CheckSnow := Cfg^.SnowChecking; end; 'K' : begin cfgReadBoolean(Cfg^.OverlayToEMS); cfgSetItem(B2St(Cfg^.OverlayToEMS)); end; 'L' : begin cfgReadBoolean(Cfg^.RealNameSystem); cfgSetItem(B2St(Cfg^.RealNameSystem)); end; 'M' : begin cfgReadBoolean(Cfg^.ShowPwLocal); cfgSetItem(B2St(Cfg^.ShowPwLocal)); end; 'N' : begin cfgReadBoolean(Cfg^.iniqAsDoor); cfgSetItem(B2St(Cfg^.iniqAsDoor)); end; 'O' : begin cfgReadBoolean(Cfg^.inactTime); cfgSetItem(B2St(Cfg^.inactTime)); end; 'P' : begin cfgReadInfo(St(Cfg^.inactSeconds),inUpper,chNumeric,'',True); Cfg^.inactSeconds := mClip(StrToInt(cfgRead),30,64000); cfgSetItem(St(Cfg^.inactSeconds)); end; 'Q' : begin cfgReadInfo(St(Cfg^.inactWarning),inUpper,chNumeric,'',True); Cfg^.inactWarning := mClip(StrToInt(cfgRead),30,Cfg^.inactSeconds); cfgSetItem(St(Cfg^.inactWarning)); end; 'R' : begin cfgReadBoolean(Cfg^.inactLocal); cfgSetItem(B2St(Cfg^.inactLocal)); end; 'S' : begin cfgReadBoolean(Cfg^.MultiNode); cfgSetItem(B2St(Cfg^.MultiNode)); end; end; until (HangUp) or (cfgDone); cfgDone := False; end; procedure cfgStatusBar; var B : Boolean; U : Byte; cD, cN, cB : tColorRec; optBarLoc : array[1..2] of String; begin cfgDraw := True; cfgOver := False; optBarLoc[1] := 'Bottom of screen'; optBarLoc[2] := 'Top of screen'; repeat cD.Back := Cfg^.StatLo shr 4; cD.Fore := Cfg^.StatLo xor (cD.Back shl 4); if cD.Back > 7 then begin cD.Blink := True; Dec(B,8); end else cD.Blink := False; cN.Back := Cfg^.StatTxt shr 4; cN.Fore := Cfg^.StatTxt xor (cN.Back shl 4); if cN.Back > 7 then begin cN.Blink := True; Dec(B,8); end else cN.Blink := False; cB.Back := Cfg^.StatHi shr 4; cB.Fore := Cfg^.StatHi xor (cB.Back shl 4); if cB.Back > 7 then begin cB.Blink := True; Dec(B,8); end else cB.Blink := False; cfgInit('Status Bar Options'); cfgCol := 40; cfgItem('A Enable status line',3,B2St(Cfg^.StatOnDefault), 'Automatically turn on the status line when a user is logging on?'); cfgItem('B Status bar on?',3,B2St(Cfg^.StatBarOn), 'Is the status bar currently enabled? (visible)'); cfgItem('C Bar location',30,cfgOption(optBarLoc,Cfg^.StatType), 'Default screen location of status bar.'); cfgItem('D Current bar display',2,St(Cfg^.StatBar), 'Current status bar line displayed.'); cfgItem('1 Dark text',40, strColor(cD),''); cfgItem('2 Normal text',40, strColor(cN),''); cfgItem('3 Bright text',40, strColor(cB),''); cfgBar; cfgDrawAllItems; cfgPromptCommand; case cfgKey of 'A' : begin cfgReadBoolean(Cfg^.StatOnDefault); cfgSetItem(B2St(Cfg^.StatOnDefault)); end; 'B' : begin B := Cfg^.StatBarOn; cfgReadBoolean(B); cfgSetItem(B2St(B)); sbStatBar(B); Cfg^.StatBarOn := B; end; 'C' : begin U := Cfg^.StatType; cfgReadOption(optBarLoc,2,U); if U <> Cfg^.StatType then sbToggleMode; cfgSetItem(cfgOption(optBarLoc,Cfg^.StatType)); end; 'D' : begin cfgReadInfo(St(Cfg^.StatBar),inUpper,chNumeric,'',True); Cfg^.StatBar := mClip(StrToInt(cfgRead),1,maxStatBar); cfgSetItem(St(Cfg^.StatBar)); sbUpdate; end; '1' : begin cfgReadColor(cD); TextColor(cD.Fore); TextBackground(cD.Back); if cD.Blink then TextColor(cD.Fore+128); Cfg^.StatLo := TextAttr; TextAttr := $60; Col.Fore := 00; Col.Back := 6; end; '2' : begin cfgReadColor(cN); TextColor(cN.Fore); TextBackground(cN.Back); if cD.Blink then TextColor(cN.Fore+128); Cfg^.StatTxt := TextAttr; TextAttr := $60; Col.Fore := 00; Col.Back := 6; end; '3' : begin cfgReadColor(cB); TextColor(cB.Fore); TextBackground(cB.Back); if cB.Blink then TextColor(cB.Fore+128); Cfg^.StatHi := TextAttr; TextAttr := $60; Col.Fore := 00; Col.Back := 6; end; end; until (HangUp) or (cfgDone); cfgDone := False; end; procedure cfgColorConfig; var B : Boolean; U, N : Word; begin cfgDraw := True; cfgOver := False; repeat cfgInit('Default Color Configuration'); cfgCol := 30; cfgItem('A Normal text',40, strColor(Cfg^.DefaultCol[colText]),''); cfgItem('B Dark text',40, strColor(Cfg^.DefaultCol[colTextLo]),''); cfgItem('C Bright text',40, strColor(Cfg^.DefaultCol[colTextHi]),''); cfgItem('D Normal info',40, strColor(Cfg^.DefaultCol[colInfo]),''); cfgItem('E Dark info',40, strColor(Cfg^.DefaultCol[colInfoLo]),''); cfgItem('F Bright info',40, strColor(Cfg^.DefaultCol[colInfoHi]),''); cfgItem('G Menu item',40, strColor(Cfg^.DefaultCol[colItem]),''); cfgItem('H Selected item',40,strColor(Cfg^.DefaultCol[colItemSel]),''); cfgItem('I Line/border',40, strColor(Cfg^.DefaultCol[colBorder]),''); cfgItem('J Error/warning',40,strColor(Cfg^.DefaultCol[colError]),''); cfgItem('K Input color',40, strColor(Cfg^.DefaultCol[colEdit]),''); if cfgDraw then begin oSetCol(colBorder); oDnLn(1); oWriteLn(sRepeat('Ä',79)); Inc(cfgLn,1); Inc(cfgBot,1); Inc(cfgCol,2); cfgItem('1 Apply colors to all users',0,'', 'Are you sure you wish to reset ALL user-defined color settings?'); end; cfgBar; cfgDrawAllItems; cfgPromptCommand; case cfgKey of 'A' : cfgReadColor(Cfg^.DefaultCol[colText]); 'B' : cfgReadColor(Cfg^.DefaultCol[colTextLo]); 'C' : cfgReadColor(Cfg^.DefaultCol[colTextHi]); 'D' : cfgReadColor(Cfg^.DefaultCol[colInfo]); 'E' : cfgReadColor(Cfg^.DefaultCol[colInfoLo]); 'F' : cfgReadColor(Cfg^.DefaultCol[colInfoHi]); 'G' : cfgReadColor(Cfg^.DefaultCol[colItem]); 'H' : cfgReadColor(Cfg^.DefaultCol[colItemSel]); 'I' : cfgReadColor(Cfg^.DefaultCol[colBorder]); 'J' : cfgReadColor(Cfg^.DefaultCol[colError]); 'K' : cfgReadColor(Cfg^.DefaultCol[colEdit]); '1' : begin B := False; cfgReadBoolean(B); if B then begin cfgInfo('-- Setting user colors. Please wait ...'); userSave(User^); N := User^.Number; for U := 1 to numUsers do begin User^.Number := U; if userLoad(User^) then begin User^.Color := Cfg^.DefaultCol; userSave(User^); end; end; User^.Number := N; userLoad(User^); cfgInfo(''); end; end; end; until (HangUp) or (cfgDone); cfgDone := False; end; function cfgAddressStr(A : tNetAddressRec) : String; begin cfgAddressStr := St(A.Zone)+':'+St(A.Net)+'/'+St(A.Node)+'.'+St(A.Point); end; function cfgToAddress(var A : tNetAddressRec; S : String) : Boolean; var Z : String; begin cfgToAddress := False; if S = '' then Exit; Z := ''; while (S <> '') and (S[1] in ['0'..'9']) do begin Z := Z+S[1]; Delete(S,1,1); end; if Z = '' then Exit; A.Zone := StrToInt(Z); cfgToAddress := True; if (S = '') or (S[1] <> ':') then Exit else Delete(S,1,1); if S = '' then Exit; Z := ''; while (S <> '') and (S[1] in ['0'..'9']) do begin Z := Z+S[1]; Delete(S,1,1); end; if Z = '' then Exit; A.Net := StrToInt(Z); if (S = '') or (S[1] <> '/') then Exit else Delete(S,1,1); if S = '' then Exit; Z := ''; while (S <> '') and (S[1] in ['0'..'9']) do begin Z := Z+S[1]; Delete(S,1,1); end; if Z = '' then Exit; A.Node := StrToInt(Z); if (S = '') or (S[1] <> '.') then Exit else Delete(S,1,1); if S = '' then Exit; Z := ''; while (S <> '') and (S[1] in ['0'..'9']) do begin Z := Z+S[1]; Delete(S,1,1); end; if Z = '' then Exit; A.Point := StrToInt(Z); end; procedure cfgNetAddress; var N : Byte; A : tNetAddressRec; begin cfgDraw := True; cfgOver := False; repeat cfgInit('Network Address Configuration'); cfgCol := 19; for N := 1 to 10 do cfgItem(Chr(64+N)+' Address #'+St(N),15,cfgAddressStr(Cfg^.Address[N]), 'Network address #'+St(N)+' (zone:net/node.point). Applied to echomail messages'); cfgLn := cfgTop; cfgSrt := 41; cfgCol := 59; for N := 11 to 20 do cfgItem(Chr(64+N)+' Address #'+St(N),15,cfgAddressStr(Cfg^.Address[N]), 'Network address #'+St(N)+' (zone:net/node.point). Applied to echomail messages'); if cfgDraw then Dec(cfgBot,10); cfgBar; cfgDrawAllItems; cfgPromptCommand; N := Ord(cfgKey)-64; case cfgKey of 'A'..Chr(64+maxOrigin) : begin cfgReadInfo(cfgAddressStr(Cfg^.Address[N]),inUpper,chNumeric+['/','.',':'],'',True); A := Cfg^.Address[N]; if cfgToAddress(A,cfgRead) then Cfg^.Address[N] := A; cfgSetItem(cfgAddressStr(Cfg^.Address[N])); end; end; until (HangUp) or (cfgDone); cfgDone := False; end; procedure cfgWaitForCall; var optBlanker : array[1..3] of String; optWFCstat : array[1..8] of String; begin cfgDraw := True; cfgOver := False; optBlanker[1] := 'Disabled'; optBlanker[2] := 'Blank screen'; optBlanker[3] := 'Text palette morph'; optWFCstat[1] := 'System information'; optWFCstat[2] := '--- reserved'; optWFCstat[3] := 'System totals'; optWFCstat[4] := 'Today''s statistics'; optWFCstat[5] := 'Last few callers'; optWFCstat[6] := '--- reserved'; optWFCstat[7] := '--- reserved'; optWFCstat[8] := bbsTitle+' information'; repeat cfgInit('Wait-For-Call Configuration'); cfgCol := 40; cfgItem('A Allow ESC to exit',3,B2St(Cfg^.ESCtoExit), 'If enabled, hitting the ESC key at the WFCscreen will exit '+bbsTitle); cfgItem('B Offhook w/local login',3,B2St(Cfg^.OffhookLocal), 'Take modem offhook before logging on locally?'); cfgItem('C VGA fading effects',3,B2St(Cfg^.VgaEffects), 'Enable special VGA color effects? (Disabled if multitasking or no VGA card)'); cfgItem('D Screen saver type',20,cfgOption(optBlanker,Cfg^.ScreenSaver+1), 'The desired screen saver type.'); cfgItem('E Screen blank time',3,St(Cfg^.BlankSeconds), '[10-5000] Number of seconds before auto-activating screen saver.'); cfgItem('F Default WFC stat',30,cfgOption(optWFCstat,Cfg^.DefWFCstat), 'Default WFC status screen display.'); cfgItem('G Connect seconds',6,St(Cfg^.waitConnect), 'Number of seconds to wait for connection after sending answer string'); cfgItem('H Modem re-init time',6,St(Cfg^.modemReInit), 'Seconds of inactivity before modem will be re-inited [0 to disable]'); cfgBar; cfgDrawAllItems; cfgPromptCommand; case cfgKey of 'A' : begin cfgReadBoolean(Cfg^.ESCtoExit); cfgSetItem(B2St(Cfg^.ESCtoExit)); end; 'B' : begin cfgReadBoolean(Cfg^.OffhookLocal); cfgSetItem(B2St(Cfg^.OffhookLocal)); end; 'C' : begin cfgReadBoolean(Cfg^.VgaEffects); cfgSetItem(B2St(Cfg^.VgaEffects)); end; 'D' : begin Inc(Cfg^.ScreenSaver); cfgReadOption(optBlanker,3,Cfg^.ScreenSaver); cfgSetItem(cfgOption(optBlanker,Cfg^.ScreenSaver)); Dec(Cfg^.ScreenSaver); end; 'E' : begin cfgReadInfo(St(Cfg^.BlankSeconds),inUpper,chNumeric,'',True); Cfg^.BlankSeconds := mClip(StrToInt(cfgRead),10,5000); cfgSetItem(St(Cfg^.BlankSeconds)); end; 'F' : begin cfgReadOption(optWFCstat,8,Cfg^.DefWFCstat); cfgSetItem(cfgOption(optWFCstat,Cfg^.DefWFCstat)); end; 'G' : begin cfgReadInfo(St(Cfg^.waitConnect),inUpper,chNumeric,'',True); Cfg^.waitConnect := mClip(StrToInt(cfgRead),5,64000); cfgSetItem(St(Cfg^.waitConnect)); end; 'H' : begin cfgReadInfo(St(Cfg^.modemReInit),inUpper,chNumeric,'',True); Cfg^.modemReInit := mClip(StrToInt(cfgRead),0,64000); cfgSetItem(St(Cfg^.modemReInit)); end; end; until (HangUp) or (cfgDone); cfgDone := False; end; procedure cfgPaths; begin cfgDraw := True; cfgOver := False; repeat cfgInit('Filenames and Directories'); cfgItem('A Data directory',40,Cfg^.pathData, 'Path to '+bbsTitle+' data and configuration files'); cfgItem('B Text directory',40,Cfg^.pathText, 'Path to miscellaneous text files'); cfgItem('C Menu directory',40,Cfg^.pathMenu, 'Path to menu (*.MNU) files'); cfgItem('D Message directory',40,Cfg^.pathMsgs, 'Path to message base data and header files'); cfgItem('E Swapping directory',40,Cfg^.pathSwap, 'Directory to perform disk swapping in. (if nessesary)'); cfgItem('F Doors directory',40,Cfg^.pathDoor, 'Directory in which '+bbsTitle+' will create door drop files in.'); cfgItem('G Protocol directory',40,Cfg^.pathProt, 'Directory where all external protocols are found.'); cfgItem('H Temporary directory',40,Cfg^.pathTemp, 'Directory in which temporary files will be stored.'); cfgItem('I Download directory',40,Cfg^.pathDnld, 'Directory where downloaded files will be placed. (from terminal)'); cfgItem('J Logfiles directory',40,Cfg^.pathLogs, 'Directory where system log files are created and stored in.'); cfgItem('K Archivers directory',40,Cfg^.pathArch, 'Directory where archivers are found, for file compression/decompression.'); cfgItem('L File attach path',40,Cfg^.pathAtch, 'Directory where included files from messages are uploaded and stored.'); cfgItem('M Textfile library path',40,Cfg^.pathLibs, 'Directory where textfile library (*.TFL) files are stored'); cfgBar; cfgDrawAllItems; cfgPromptCommand; case cfgKey of 'A' : begin cfgReadInfo(Cfg^.pathData,inUpper,chDirectory,'',True); Cfg^.pathData := cfgRead; if Cfg^.pathData[Length(Cfg^.pathData)] <> '\' then Cfg^.pathData := Cfg^.pathData+'\'; cfgSetItem(Cfg^.pathData); cfgAskCreate(Cfg^.pathData); end; 'B' : begin cfgReadInfo(Cfg^.pathText,inUpper,chDirectory,'',True); Cfg^.pathText := cfgRead; if Cfg^.pathText[Length(Cfg^.pathText)] <> '\' then Cfg^.pathText := Cfg^.pathText+'\'; cfgSetItem(Cfg^.pathText); cfgAskCreate(Cfg^.pathText); end; 'C' : begin cfgReadInfo(Cfg^.pathMenu,inUpper,chDirectory,'',True); Cfg^.pathMenu := cfgRead; if Cfg^.pathMenu[Length(Cfg^.pathMenu)] <> '\' then Cfg^.pathMenu := Cfg^.pathMenu+'\'; cfgSetItem(Cfg^.pathMenu); cfgAskCreate(Cfg^.pathMenu); end; 'D' : begin cfgReadInfo(Cfg^.pathMsgs,inUpper,chDirectory,'',True); Cfg^.pathMsgs := cfgRead; if Cfg^.pathMsgs[Length(Cfg^.pathMsgs)] <> '\' then Cfg^.pathMsgs := Cfg^.pathMsgs+'\'; cfgSetItem(Cfg^.pathMsgs); cfgAskCreate(Cfg^.pathMsgs); end; 'E' : begin cfgReadInfo(Cfg^.pathSwap,inUpper,chDirectory,'',True); Cfg^.pathSwap := cfgRead; if Cfg^.pathSwap[Length(Cfg^.pathSwap)] <> '\' then Cfg^.pathSwap := Cfg^.pathSwap+'\'; cfgSetItem(Cfg^.pathSwap); cfgAskCreate(Cfg^.pathSwap); end; 'F' : begin cfgReadInfo(Cfg^.pathDoor,inUpper,chDirectory,'',True); Cfg^.pathDoor := cfgRead; if Cfg^.pathDoor[Length(Cfg^.pathDoor)] <> '\' then Cfg^.pathDoor := Cfg^.pathDoor+'\'; cfgSetItem(Cfg^.pathDoor); cfgAskCreate(Cfg^.pathDoor); end; 'G' : begin cfgReadInfo(Cfg^.pathProt,inUpper,chDirectory,'',True); Cfg^.pathProt := cfgRead; if Cfg^.pathProt[Length(Cfg^.pathProt)] <> '\' then Cfg^.pathProt := Cfg^.pathProt+'\'; cfgSetItem(Cfg^.pathProt); cfgAskCreate(Cfg^.pathProt); end; 'H' : begin cfgReadInfo(Cfg^.pathTemp,inUpper,chDirectory,'',True); Cfg^.pathTemp := cfgRead; if Cfg^.pathTemp[Length(Cfg^.pathTemp)] <> '\' then Cfg^.pathTemp := Cfg^.pathTemp+'\'; cfgSetItem(Cfg^.pathTemp); cfgAskCreate(Cfg^.pathTemp); end; 'I' : begin cfgReadInfo(Cfg^.pathDnld,inUpper,chDirectory,'',True); Cfg^.pathDnld := cfgRead; if Cfg^.pathDnld[Length(Cfg^.pathDnld)] <> '\' then Cfg^.pathDnld := Cfg^.pathDnld+'\'; cfgSetItem(Cfg^.pathDnld); cfgAskCreate(Cfg^.pathDnld); end; 'J' : begin cfgReadInfo(Cfg^.pathLogs,inUpper,chDirectory,'',True); Cfg^.pathLogs := cfgRead; if Cfg^.pathLogs[Length(Cfg^.pathLogs)] <> '\' then Cfg^.pathLogs := Cfg^.pathLogs+'\'; cfgSetItem(Cfg^.pathLogs); cfgAskCreate(Cfg^.pathLogs); end; 'K' : begin cfgReadInfo(Cfg^.pathArch,inUpper,chDirectory,'',True); Cfg^.pathArch := cfgRead; if Cfg^.pathArch[Length(Cfg^.pathArch)] <> '\' then Cfg^.pathArch := Cfg^.pathArch+'\'; cfgSetItem(Cfg^.pathArch); cfgAskCreate(Cfg^.pathArch); end; 'L' : begin cfgReadInfo(Cfg^.pathAtch,inUpper,chDirectory,'',True); Cfg^.pathAtch := cfgRead; if Cfg^.pathAtch[Length(Cfg^.pathAtch)] <> '\' then Cfg^.pathAtch := Cfg^.pathAtch+'\'; cfgSetItem(Cfg^.pathAtch); cfgAskCreate(Cfg^.pathAtch); end; 'M' : begin cfgReadInfo(Cfg^.pathLibs,inUpper,chDirectory,'',True); Cfg^.pathLibs := cfgRead; if Cfg^.pathLibs[Length(Cfg^.pathLibs)] <> '\' then Cfg^.pathLibs := Cfg^.pathLibs+'\'; cfgSetItem(Cfg^.pathLibs); cfgAskCreate(Cfg^.pathLibs); end; end; until (HangUp) or (cfgDone); cfgDone := False; end; procedure cfgLoggingOptions; var B : Boolean; begin cfgDraw := True; cfgOver := False; repeat cfgInit('BBS Logging Options'); cfgCol := 40; cfgItem('A System logging',3,B2St(not Cfg^.NoBBSlogging), 'Create log files of system activity?'); cfgItem('B Log line-chat',3,B2St(Cfg^.LogLineChat), 'Record line-chat to '+fileChatLog+'?'); cfgItem('C Log split-screen chat',3,B2St(Cfg^.LogSplitChat), 'Record splitscreen chat to '+fileChatLog+'?'); cfgItem('D MicroDOS logging',3,B2St(Cfg^.LogMicroDOS), 'Record all commands entered in artifical DOS to log file?'); cfgBar; cfgDrawAllItems; cfgPromptCommand; case cfgKey of 'A' : begin B := not Cfg^.NoBBSlogging; cfgReadBoolean(B); Cfg^.NoBBSlogging := not B; cfgSetItem(B2St(B)); end; 'B' : begin cfgReadBoolean(Cfg^.LogLineChat); cfgSetItem(B2St(Cfg^.LogLineChat)); end; 'C' : begin cfgReadBoolean(Cfg^.LogSplitChat); cfgSetItem(B2St(Cfg^.LogSplitChat)); end; 'D' : begin cfgReadBoolean(Cfg^.LogMicroDOS); cfgSetItem(B2St(Cfg^.LogMicroDOS)); end; end; until (HangUp) or (cfgDone); cfgDone := False; end; procedure cfgSwappingSetup; begin cfgDraw := True; cfgOver := False; repeat cfgInit('Swapping Setup'); cfgCol := 40; cfgItem('A Swap when shelling',3,B2St(Cfg^.SwapInShell), 'Swap to disk (or EMS if enabled) to free more memory with external programs'); cfgItem('B Use EMS for swapping',3,B2St(Cfg^.SwapToEMS), 'Allow use of expanded memory for swapping (if available, otherwise disk)'); cfgItem('C Protocol swapping',3,B2St(Cfg^.ProtocolSwap), 'Swap to EMS or DISK when executing external protocols?'); cfgItem('D Archiver swapping',3,B2St(Cfg^.ArchiverSwap), 'Swap to EMS or DISK when executing archiver programs?'); cfgBar; cfgDrawAllItems; cfgPromptCommand; case cfgKey of 'A' : begin cfgReadBoolean(Cfg^.SwapInShell); cfgSetItem(B2St(Cfg^.SwapInShell)); end; 'B' : begin cfgReadBoolean(Cfg^.SwapToEMS); cfgSetItem(B2St(Cfg^.SwapToEMS)); end; 'C' : begin cfgReadBoolean(Cfg^.ProtocolSwap); cfgSetItem(B2St(Cfg^.ProtocolSwap)); end; 'D' : begin cfgReadBoolean(Cfg^.ArchiverSwap); cfgSetItem(B2St(Cfg^.ArchiverSwap)); end; end; until (HangUp) or (cfgDone); cfgDone := False; end; procedure cfgLoginConfig; begin cfgDraw := True; cfgOver := False; repeat cfgInit('BBS Login Configuration'); cfgCol := 40; cfgItem('A System access password',20,Cfg^.BbsAccessPW, 'Password required to login to the BBS (Blank=Disabled).'); cfgItem('B Baud override password',20,Cfg^.NoBaudPW, 'Password required to logon below the minimum baudrate (Blank=Disabled).'); cfgItem('C SysOp autologin',3,B2St(Cfg^.SysOpAutoLogin), 'Automatically login "instantly", bypassing all logon prompts/screens.'); cfgItem('D Use matrix login',3,B2St(Cfg^.MatrixLogin), 'Enable use of "MATRIX.MNU", a pre-login command menu.'); cfgItem('E Offer application?',3,B2St(Cfg^.AskApply), 'If a user isn''t found in the user file, will be offered to apply as new'); cfgItem('F Time limit per call',3,B2St(Cfg^.TimeLimitPerCall), 'Is user time limit for each call or each day?'); cfgItem('G System password login',20,Cfg^.acsSystemPWLogin, 'Access level to enforce the system password when logging in.'); cfgItem('H Calls before birthdate check',3,St(Cfg^.CallsBirth), '[0-255] How often to perform birthdate validation check. (0 = Disabled)'); cfgItem('I Calls before phone # check',3,St(Cfg^.CallsPhone), '[0-255] How often to perform phone number validation check. (0 = Disabled)'); cfgItem('J Maximum logon attempts',3,St(Cfg^.LoginTrys), '[0-255] Number of tries a user has to logon to system. (0 = Infinite)'); cfgBar; cfgDrawAllItems; cfgPromptCommand; case cfgKey of 'A' : begin cfgReadInfo(Cfg^.BbsAccessPW,inUpper,chNormal,'',False); Cfg^.BbsAccessPW := cfgRead; cfgSetItem(Cfg^.BbsAccessPW); end; 'B' : begin cfgReadInfo(Cfg^.NoBaudPW,inUpper,chNormal,'',False); Cfg^.NoBaudPW := cfgRead; cfgSetItem(Cfg^.NoBaudPW); end; 'C' : begin cfgReadBoolean(Cfg^.SysOpAutoLogin); cfgSetItem(B2St(Cfg^.SysOpAutoLogin)); end; 'D' : begin cfgReadBoolean(Cfg^.MatrixLogin); cfgSetItem(B2St(Cfg^.MatrixLogin)); end; 'E' : begin cfgReadBoolean(Cfg^.AskApply); cfgSetItem(B2St(Cfg^.AskApply)); end; 'F' : begin cfgReadBoolean(Cfg^.TimeLimitPerCall); cfgSetItem(B2St(Cfg^.TimeLimitPerCall)); end; 'G' : begin cfgReadInfo(Cfg^.acsSystemPWLogin,inLower,chNormal,'',True); Cfg^.acsSystemPWLogin := cfgRead; cfgSetItem(Cfg^.acsSystemPWLogin); end; 'H' : begin cfgReadInfo(St(Cfg^.CallsBirth),inUpper,chNumeric,'',True); Cfg^.CallsBirth := mClip(StrToInt(cfgRead),0,255); cfgSetItem(St(Cfg^.CallsBirth)); end; 'I' : begin cfgReadInfo(St(Cfg^.CallsPhone),inUpper,chNumeric,'',True); Cfg^.CallsPhone := mClip(StrToInt(cfgRead),0,255); cfgSetItem(St(Cfg^.CallsPhone)); end; 'J' : begin cfgReadInfo(St(Cfg^.LoginTrys),inUpper,chNumeric,'',True); Cfg^.LoginTrys := mClip(StrToInt(cfgRead),0,255); cfgSetItem(St(Cfg^.LoginTrys)); end; end; until (HangUp) or (cfgDone); cfgDone := False; end; procedure cfgOriginLines; var N : Byte; begin cfgDraw := True; cfgOver := False; repeat cfgInit('Origin Line Setup'); cfgCol := 16; for N := 1 to 10 do cfgItem(Chr(64+N)+' Origin #'+St(N),23,Cfg^.Origin[N], 'Origin line number '+St(N)+'. Applied to echomail messages'); cfgLn := cfgTop; cfgSrt := 41; cfgCol := 56; for N := 11 to 20 do cfgItem(Chr(64+N)+' Origin #'+St(N),23,Cfg^.Origin[N], 'Origin line number '+St(N)+'. Applied to echomail messages'); if cfgDraw then Dec(cfgBot,10); cfgBar; cfgDrawAllItems; cfgPromptCommand; N := Ord(cfgKey)-64; case cfgKey of 'A'..Chr(64+maxOrigin) : begin cfgEditInfo(Cfg^.Origin[N],75,inNormal,chNormal,'',False); Cfg^.Origin[N] := cfgRead; cfgSetItem(Cfg^.Origin[N]); end; end; until (HangUp) or (cfgDone); cfgDone := False; end; procedure cfgChatSetup; begin cfgDraw := True; cfgOver := False; repeat cfgInit('Chat Mode Setup'); cfgCol := 40; cfgItem('A Chat override password',20,Cfg^.NoChatPW, 'Password required to page sysop when not available (Blank=Disabled)'); cfgItem('B Chat pager noise',3,B2St(Cfg^.ChatPageNoise), 'Allow chat pager to actually beep when paged?'); cfgItem('C Maximum page times',3,St(Cfg^.maxPageTimes), '[0-30] Number of times user may page the sysop per call (0 = Infinite)'); cfgItem('D Page beeps',3,St(Cfg^.maxPageBeeps), '[1-20] Number of beeps to output when paging SysOp'); cfgItem('E Restore chat time',3,B2St(Cfg^.RestoreChatTime), 'Restore all time spent while in chat mode?'); cfgItem('F Availablity start time',5,Cfg^.chatStart, 'Time (24 hour) that users will be allowed to page sysop from until end time'); cfgItem('G Availablity end time',5,Cfg^.chatEnd, 'Time (24 hour) that chat availability will be automatically disabled at'); cfgItem('H Page override ACS',20,Cfg^.chatOverAcs, 'Access condition required to override chat availibality'); cfgItem('I Chat inactivity check',3,b2st(Cfg^.inactInChat), 'Enable inactivity checking in while chat mode?'); cfgItem('J Ask leave email?',3,B2St(Cfg^.pageAskEmail), 'Prompt to send email to the sysop after an unsucessful chat attempt?'); cfgBar; cfgDrawAllItems; cfgPromptCommand; case cfgKey of 'A' : begin cfgReadInfo(Cfg^.NoChatPW,inUpper,chNormal,'',False); Cfg^.NoChatPW := cfgRead; cfgSetItem(Cfg^.NoChatPW); end; 'B' : begin cfgReadBoolean(Cfg^.ChatPageNoise); cfgSetItem(B2St(Cfg^.ChatPageNoise)); end; 'C' : begin cfgReadInfo(St(Cfg^.maxPageTimes),inUpper,chNumeric,'',True); Cfg^.maxPageTimes := mClip(StrToInt(cfgRead),0,30); cfgSetItem(St(Cfg^.maxPageTimes)); end; 'D' : begin cfgReadInfo(St(Cfg^.maxPageBeeps),inUpper,chNumeric,'',True); Cfg^.maxPageBeeps := mClip(StrToInt(cfgRead),1,20); cfgSetItem(St(Cfg^.maxPageBeeps)); end; 'E' : begin cfgReadBoolean(Cfg^.RestoreChatTime); cfgSetItem(B2St(Cfg^.RestoreChatTime)); end; 'F' : begin cfgReadTime; Cfg^.chatStart := cfgRead; cfgSetItem(Cfg^.chatStart); end; 'G' : begin cfgReadTime; Cfg^.chatEnd := cfgRead; cfgSetItem(Cfg^.chatEnd); end; 'H' : begin cfgReadInfo(Cfg^.chatOverAcs,inLower,chNormal,'',True); Cfg^.chatOverAcs := cfgRead; cfgSetItem(Cfg^.chatOverAcs); end; 'I' : begin cfgReadBoolean(Cfg^.inactInChat); cfgSetItem(B2St(Cfg^.inactInChat)); end; 'J' : begin cfgReadBoolean(Cfg^.pageAskEmail); cfgSetItem(B2St(Cfg^.pageAskEmail)); end; end; until (HangUp) or (cfgDone); cfgDone := False; end; procedure cfgMiscOptions; begin cfgDraw := True; cfgOver := False; repeat cfgInit('Miscellaneous Options'); cfgCol := 40; cfgItem('A Password echo character',1,Cfg^.PwEchoChar, 'Character shown when entering or displaying hidden information'); cfgItem('B Remove pause prompts',3,B2St(Cfg^.RemovePause), 'Erase (backspace over) pause prompts after a key is hit?'); cfgItem('C Record local calls',3,B2St(Cfg^.AddLocalCalls), 'Record local logins to system statistics and last caller records?'); cfgItem('D Last callers shown',3,St(Cfg^.numLastCalls), '[1-255] Number of last callers to display in last callers listing'); cfgItem('E Light character',1,Cfg^.lightChar, 'Character used as a "light" in applicible textfiles'); cfgItem('F Light "ok" character',1,Cfg^.lightCharOk, 'Character displayed when an operation was successful'); cfgItem('G Light "fail" character',1,Cfg^.lightCharFail, 'Character displayed when an operation failed'); cfgItem('H Use textfile libraries',3,B2St(Cfg^.useTextLibs), 'Load textfiles from user selectable libraries (.TFL files) if possible?'); cfgItem('I Yes/no prompt (yes)',30,Cfg^.pmtYes, 'Yes/no prompt to display when "Yes" is the default answer'); cfgItem('J Yes/no prompt (no)',30,Cfg^.pmtNo, 'Yes/no prompt to display when "No" is the default answer'); cfgItem('K Yes/no "Yes" word',20,Cfg^.pmtYesWord, 'String to display when a user chooses "Yes" at a yes/no prompt'); cfgItem('L Yes/no "No" word',20,Cfg^.pmtNoWord, 'String to display when a user chooses "No" at a yes/no prompt'); cfgItem('M Yes/no bar prompt (yes)',30,Cfg^.pmtYesBar, 'Yes/no bar displayed when "Yes" is currently selected'); cfgItem('N Yes/no bar prompt (no)',30,Cfg^.pmtNoBar, 'Yes/no bar displayed when "No" is currently selected'); cfgItem('O Local sound restriction',3,B2St(Cfg^.soundRestrict), 'If enabled, local beeps will only be enabled if the sysop is available'); cfgBar; cfgDrawAllItems; cfgPromptCommand; case cfgKey of 'A' : begin cfgReadInfo(Cfg^.PwEchoChar,inNormal,chNormal,'',True); Cfg^.PwEchoChar := cfgRead[1]; cfgSetItem(Cfg^.PwEchoChar); end; 'B' : begin cfgReadBoolean(Cfg^.RemovePause); cfgSetItem(B2St(Cfg^.RemovePause)); end; 'C' : begin cfgReadBoolean(Cfg^.AddLocalCalls); cfgSetItem(B2St(Cfg^.AddLocalCalls)); end; 'D' : begin cfgReadInfo(St(Cfg^.numLastCalls),inUpper,chNumeric,'',True); Cfg^.numLastCalls := mClip(StrToInt(cfgRead),1,255); cfgSetItem(St(Cfg^.numLastCalls)); end; 'E' : begin cfgReadInfo(Cfg^.lightChar,inNormal,chNormal,'',True); Cfg^.lightChar := cfgRead[1]; cfgSetItem(Cfg^.lightChar); end; 'F' : begin cfgReadInfo(Cfg^.lightCharOk,inNormal,chNormal,'',True); Cfg^.lightCharOk := cfgRead[1]; cfgSetItem(Cfg^.lightCharOk); end; 'G' : begin cfgReadInfo(Cfg^.lightCharFail,inNormal,chNormal,'',True); Cfg^.lightCharFail := cfgRead[1]; cfgSetItem(Cfg^.lightCharFail); end; 'H' : begin cfgReadBoolean(Cfg^.useTextLibs); cfgSetItem(B2St(Cfg^.useTextLibs)); end; 'I' : begin cfgReadInfo(Cfg^.pmtYes,inNormal,chNormal,rsNoClean+rsSpace,True); Cfg^.pmtYes := cfgRead; cfgSetItem(Cfg^.pmtYes); end; 'J' : begin cfgReadInfo(Cfg^.pmtNo,inNormal,chNormal,rsNoClean+rsSpace,True); Cfg^.pmtNo := cfgRead; cfgSetItem(Cfg^.pmtNo); end; 'K' : begin cfgReadInfo(Cfg^.pmtYesWord,inNormal,chNormal,rsNoClean+rsSpace,True); Cfg^.pmtYesWord := cfgRead; cfgSetItem(Cfg^.pmtYesWord); end; 'L' : begin cfgReadInfo(Cfg^.pmtNoWord,inNormal,chNormal,rsNoClean+rsSpace,True); Cfg^.pmtNoWord := cfgRead; cfgSetItem(Cfg^.pmtNoWord); end; 'M' : begin cfgReadInfo(Cfg^.pmtYesBar,inNormal,chNormal,rsNoClean+rsSpace,True); Cfg^.pmtYesBar := cfgRead; cfgSetItem(Cfg^.pmtYesBar); end; 'N' : begin cfgReadInfo(Cfg^.pmtNoBar,inNormal,chNormal,rsNoClean+rsSpace,True); Cfg^.pmtNoBar := cfgRead; cfgSetItem(Cfg^.pmtNoBar); end; 'O' : begin cfgReadBoolean(Cfg^.soundRestrict); cfgSetItem(B2St(Cfg^.soundRestrict)); end; end; until (HangUp) or (cfgDone); cfgDone := False; end; procedure cfgMessageSystem; begin cfgDraw := True; cfgOver := False; repeat cfgInit('Message system configuration'); cfgCol := 28; cfgItem('A Post electronic mail',20,Cfg^.acsPostEmail, 'Access condition required to post electroic mail (Email).'); cfgItem('B Anonymous post access',20,Cfg^.acsAnonymous, 'Access condition required to post anonymous messages (if allowed).'); cfgItem('C Anonymous automsg acs',20,Cfg^.acsAnonAutoMsg, 'Access condition required to post an anonymous auto-message.'); cfgItem('D Upload message access',20,Cfg^.acsUploadMessage, 'Access condition required to upload a prepared message.'); cfgItem('E Autosignature access',20,Cfg^.acsAutoSigUse, 'Access condition required for AutoSignature use.'); cfgItem('F Public attach access',20,Cfg^.acsAttachPublic, 'Access condition required to attach files to public messages.'); cfgItem('G Email attach access',20,Cfg^.acsAttachEmail, 'Access condition required to attach files to electronic mail.'); cfgItem('H Abort mandatory okay',3,B2St(Cfg^.AbortMandOk), 'Allow user to abort reading messages (with ''Q'') in a mandatory area?'); cfgItem('I Ask private message',3,B2St(Cfg^.AskPrivateMsg), 'Offer private message when posting to a specific user?'); cfgItem('J Ask private reply',3,B2St(Cfg^.AskPrivateReply), 'Offer private message when replying to a user?'); cfgItem('K Ask post in area',3,B2St(Cfg^.AskPostInArea), 'Ask user if he/she wishes to post when area reading complete?'); cfgItem('L Ask upload reply',3,B2St(Cfg^.AskUploadReply), 'Offer prepared message upload when user is replying?'); cfgItem('M Ask upload email',3,B2St(Cfg^.AskUploadEmail), 'Offer prepared message upload when user is sending email?'); cfgItem('N Ask delete email msg',3,B2St(Cfg^.AskKillMsg), 'Ask user if he/she wishes to delete the message they replied to?'); cfgItem('O Ask kill all email',3,B2St(Cfg^.AskKillAllMsg), 'Ask user if he/she wishes to kill all undeleted email when through reading?'); cfgItem('P Ask autoquote reply',3,B2St(Cfg^.AskAutoQuote), 'Ask user if he/she wishes to auto-quote the message they''re replying to?'); cfgItem('Q Default quote lines',3,B2St(Cfg^.DefaultQuoteNum), 'Default /Q line #s to ones chosen by '+bbsTitle+'? (if autoquote is off)'); cfgItem('R Max autoquote lines',2,St(Cfg^.maxQuoteLines), '[0-20] Maximum amount of lines to be AutoQuoted from message (0 = full msg)'); cfgItem('S Ignore conf w/mand',3,B2St(Cfg^.confIgnoreMsg), 'Ignore current message conference when scanning for mandatory messages?'); cfgLn := cfgTop+7; cfgSrt := 40; cfgCol := 68; cfgItem('T Compress area #''s',3,B2St(Cfg^.compMsgAreas), 'Compress message area listing numbers, to make sequential?'); cfgItem('U Echomail errorlevel',3,St(Cfg^.echomailLev), 'Errorlevel to exit to DOS with when a message is posted in an echo area'); cfgItem('V Ansi quote string',11,Cfg^.ansiString, 'String to be displayed in place of text when quoting text with ansi codes'); if cfgDraw then Dec(cfgBot,3); cfgBar; cfgDrawAllItems; cfgPromptCommand; case cfgKey of 'A' : begin cfgReadInfo(Cfg^.acsPostEmail,inLower,chNormal,'',True); Cfg^.acsPostEmail := cfgRead; cfgSetItem(Cfg^.acsPostEmail); end; 'B' : begin cfgReadInfo(Cfg^.acsAnonymous,inLower,chNormal,'',True); Cfg^.acsAnonymous := cfgRead; cfgSetItem(Cfg^.acsAnonymous); end; 'C' : begin cfgReadInfo(Cfg^.acsAnonAutoMsg,inLower,chNormal,'',True); Cfg^.acsAnonAutoMsg := cfgRead; cfgSetItem(Cfg^.acsAnonAutoMsg); end; 'D' : begin cfgReadInfo(Cfg^.acsUploadMessage,inLower,chNormal,'',True); Cfg^.acsUploadMessage := cfgRead; cfgSetItem(Cfg^.acsUploadMessage); end; 'E' : begin cfgReadInfo(Cfg^.acsAutoSigUse,inLower,chNormal,'',True); Cfg^.acsAutoSigUse := cfgRead; cfgSetItem(Cfg^.acsAutoSigUse); end; 'F' : begin cfgReadInfo(Cfg^.acsAttachPublic,inLower,chNormal,'',True); Cfg^.acsAttachPublic := cfgRead; cfgSetItem(Cfg^.acsAttachPublic); end; 'G' : begin cfgReadInfo(Cfg^.acsAttachEmail,inLower,chNormal,'',True); Cfg^.acsAttachEmail := cfgRead; cfgSetItem(Cfg^.acsAttachEmail); end; 'H' : begin cfgReadBoolean(Cfg^.AbortMandOk); cfgSetItem(B2St(Cfg^.AbortMandOk)); end; 'I' : begin cfgReadBoolean(Cfg^.AskPrivateMsg); cfgSetItem(B2St(Cfg^.AskPrivateMsg)); end; 'J' : begin cfgReadBoolean(Cfg^.AskPrivateReply); cfgSetItem(B2St(Cfg^.AskPrivateReply)); end; 'K' : begin cfgReadBoolean(Cfg^.AskPostInArea); cfgSetItem(B2St(Cfg^.AskPostInArea)); end; 'L' : begin cfgReadBoolean(Cfg^.AskUploadReply); cfgSetItem(B2St(Cfg^.AskUploadReply)); end; 'M' : begin cfgReadBoolean(Cfg^.AskUploadEmail); cfgSetItem(B2St(Cfg^.AskUploadEmail)); end; 'N' : begin cfgReadBoolean(Cfg^.AskKillMsg); cfgSetItem(B2St(Cfg^.AskKillMsg)); end; 'O' : begin cfgReadBoolean(Cfg^.AskKillAllMsg); cfgSetItem(B2St(Cfg^.AskKillAllMsg)); end; 'P' : begin cfgReadBoolean(Cfg^.AskAutoQuote); cfgSetItem(B2St(Cfg^.AskAutoQuote)); end; 'Q' : begin cfgReadBoolean(Cfg^.DefaultQuoteNum); cfgSetItem(B2St(Cfg^.DefaultQuoteNum)); end; 'R' : begin cfgReadInfo(St(Cfg^.maxQuoteLines),inUpper,chNumeric,'',True); Cfg^.maxQuoteLines := mClip(StrToInt(cfgRead),0,20); cfgSetItem(St(Cfg^.maxQuoteLines)); end; 'S' : begin cfgReadBoolean(Cfg^.confIgnoreMsg); cfgSetItem(B2St(Cfg^.confIgnoreMsg)); end; 'T' : begin cfgReadBoolean(Cfg^.compMsgAreas); cfgSetItem(B2St(Cfg^.compMsgAreas)); end; 'U' : begin cfgReadInfo(St(Cfg^.echomailLev),inUpper,chNumeric,'',True); Cfg^.echomailLev := mClip(StrToInt(cfgRead),0,255); cfgSetItem(St(Cfg^.echomailLev)); end; 'V' : begin cfgEditInfo(Cfg^.ansiString,75,inNormal,chNormal,'',True); Cfg^.ansiString := cfgRead; cfgSetItem(Cfg^.ansiString); end; end; until (HangUp) or (cfgDone); cfgDone := False; end; procedure cfgNewUserOptions; var optAlias : array[1..8] of String; begin cfgDraw := True; cfgOver := False; optAlias[1] := 'Normal (as entered)'; optAlias[2] := 'Capitalized (ie Fiend)'; optAlias[3] := 'Upper case (ie FIEND)'; optAlias[4] := 'Lower case (ie fiend)'; optAlias[5] := 'Proper case (ie Peter Piper)'; optAlias[6] := 'Small vowels (ie FieND)'; optAlias[7] := 'Big vowels (ie fIEnd)'; optAlias[8] := 'Small "i"s (ie FiEND)'; repeat cfgInit('New User Options'); cfgCol := 40; cfgItem('A New user password',20,Cfg^.NewUserPW, 'Password required to apply as a new user (Blank=Disabled)'); cfgItem('B User alias format',30,cfgOption(optAlias,Cfg^.AliasFormat), 'Case conversion applied to usernames'); cfgItem('C Default screen length',3,St(Cfg^.DefaultPageLen), '[5-200] The default number of lines displayed before a pause'); cfgItem('D New user expert',3,B2St(Cfg^.NewExpert), 'Default new users to expert mode enabled?'); cfgItem('E New user hot-keys',3,B2St(Cfg^.NewHotKeys), 'Default new users to "hot-keys" enabled?'); cfgItem('F New user yes/no bars',3,B2St(Cfg^.NewYesNoBars), 'Default new users to yes/no selection bars enabled?'); cfgItem('G New user pausing',3,B2St(Cfg^.NewPause), 'Default new users to screen pausing enabled?'); cfgItem('H New user autoquote',3,B2St(Cfg^.NewQuote), 'Default new users to message autoquoting enabled?'); cfgItem('I Ask user expert',3,B2St(Cfg^.NewAskExpert), 'Default new users to expert mode enabled?'); cfgItem('J Ask hot-keys',3,B2St(Cfg^.NewAskHotKeys), 'Ask new users if they want "hot-keys" enabled?'); cfgItem('K Ask yes/no bars',3,B2St(Cfg^.NewAskYesNoBars), 'Ask new users if they want yes/no selection bars enabled?'); cfgItem('L Ask screen pausing',3,B2St(Cfg^.NewAskPause), 'Ask new users if they want screen pausing enabled?'); cfgItem('M Ask autoquote',3,B2St(Cfg^.NewAskQuote), 'Ask new users if they want message AutoQuoting enabled?'); cfgItem('N Ask screen length',3,B2St(Cfg^.NewAskPageLen), 'Default new users to yes/no selection bars enabled?'); cfgItem('O Default start menu',8,Cfg^.StartMenu, 'The first menu to load and execute after logging in'); cfgItem('P New user config',3,B2St(Cfg^.newConfig), 'Present new users with a config screen after applying?'); cfgItem('Q Verify apply command',3,B2St(Cfg^.newVerify), 'Ask user if he/she still wants to apply after displaying APPLY.ANS?'); cfgBar; cfgDrawAllItems; cfgPromptCommand; case cfgKey of 'A' : begin cfgReadInfo(Cfg^.NewUserPW,inUpper,chNormal,'',False); Cfg^.NewUserPW := cfgRead; cfgSetItem(Cfg^.NewUserPW); end; 'B' : begin cfgReadOption(optAlias,8,Cfg^.AliasFormat); cfgSetItem(cfgOption(optAlias,Cfg^.AliasFormat)); end; 'C' : begin cfgReadInfo(St(Cfg^.DefaultPageLen),inUpper,chNumeric,'',True); Cfg^.DefaultPageLen := mClip(StrToInt(cfgRead),5,200); cfgSetItem(St(Cfg^.DefaultPageLen)); end; 'D' : begin cfgReadBoolean(Cfg^.NewExpert); cfgSetItem(B2St(Cfg^.NewExpert)); end; 'E' : begin cfgReadBoolean(Cfg^.NewHotKeys); cfgSetItem(B2St(Cfg^.NewHotKeys)); end; 'F' : begin cfgReadBoolean(Cfg^.NewYesNoBars); cfgSetItem(B2St(Cfg^.NewYesNoBars)); end; 'G' : begin cfgReadBoolean(Cfg^.NewPause); cfgSetItem(B2St(Cfg^.NewPause)); end; 'H' : begin cfgReadBoolean(Cfg^.NewQuote); cfgSetItem(B2St(Cfg^.NewQuote)); end; 'I' : begin cfgReadBoolean(Cfg^.NewAskExpert); cfgSetItem(B2St(Cfg^.NewAskExpert)); end; 'J' : begin cfgReadBoolean(Cfg^.NewAskHotKeys); cfgSetItem(B2St(Cfg^.NewAskHotKeys)); end; 'K' : begin cfgReadBoolean(Cfg^.NewAskYesNoBars); cfgSetItem(B2St(Cfg^.NewAskYesNoBars)); end; 'L' : begin cfgReadBoolean(Cfg^.NewAskPause); cfgSetItem(B2St(Cfg^.NewAskPause)); end; 'M' : begin cfgReadBoolean(Cfg^.NewAskQuote); cfgSetItem(B2St(Cfg^.NewAskQuote)); end; 'N' : begin cfgReadBoolean(Cfg^.NewAskPageLen); cfgSetItem(B2St(Cfg^.NewAskPageLen)); end; 'O' : begin cfgReadInfo(Cfg^.StartMenu,inUpper,chFilename,'',True); Cfg^.StartMenu := cfgRead; cfgSetItem(Cfg^.StartMenu); end; 'P' : begin cfgReadBoolean(Cfg^.newConfig); cfgSetItem(B2St(Cfg^.newConfig)); end; 'Q' : begin cfgReadBoolean(Cfg^.newVerify); cfgSetItem(B2St(Cfg^.newVerify)); end; end; until (HangUp) or (cfgDone); cfgDone := False; end; procedure cfgMacroStrings; var N : Byte; begin cfgDraw := True; cfgOver := False; repeat cfgInit('SysOp Macro Strings'); cfgCol := 17; for N := 1 to 10 do cfgItem(Chr(64+N)+' F'+Resize(St(N),3)+'Macro',58,Cfg^.Macro[N], 'SysOp macro string for function key: F'+St(N)+'.'); cfgBar; cfgDrawAllItems; cfgPromptCommand; N := Ord(cfgKey)-64; case cfgKey of 'A'..Chr(64+10) : begin cfgEditInfo(Cfg^.Macro[N],255,inNormal,chNormal,'',False); Cfg^.Macro[N] := cfgRead; cfgSetItem(Cfg^.Macro[N]); end; end; until (HangUp) or (cfgDone); cfgDone := False; end; procedure cfgFileSystem; var optSearch : array[1..4] of String; begin optSearch[1] := 'Disabled'; optSearch[2] := 'Current area'; optSearch[3] := 'All areas'; optSearch[4] := 'All areas and conferences'; cfgDraw := True; cfgOver := False; repeat cfgInit('File System Configuration'); cfgCol := 28; cfgItem('A Compress area #''s',3,B2St(Cfg^.compFileAreas), 'Compress file area list numbers to make sequential?'); cfgItem('B Import descriptions',3,B2St(Cfg^.importDescs), 'Import FILE_ID.DIZ or DESC.SDI descriptions from uploads?'); cfgItem('C Use file point system',3,B2St(Cfg^.useFilePoints), 'Use the file point system when downloading and uploading?'); cfgItem('D Kb per file point',5,St(Cfg^.kbPerFilePoint), 'Value of one file point (in kilobyes)'); cfgItem('E Use daily DL limit',3,B2St(Cfg^.useDLlimit), 'Enforce a limit to the number of files downloadable per day?'); cfgItem('F Use daily DL kb limit',3,B2St(Cfg^.useDLkbLimit), 'Enforce a limit to the number of kilobytes downloadable per day?'); cfgItem('G No description string',40,Cfg^.noDescLine, 'Description to display in file listings for files w/o defined descriptions'); cfgItem('H Virus scan command',40,Cfg^.virusScan, 'Command to execute when scanning for viruses [archiver dir] %FN = Filespec'); cfgItem('I Scan success level',3,St(Cfg^.virusOk), 'Success errorlevel retured by the virus scanning program'); cfgItem('J Upload file age limit',3,St(Cfg^.maxFileAge), 'Files uploaded that are older then this age (in years) will be rejected'); cfgItem('K Strict age tester',3,B2St(Cfg^.strictAge), 'Have age tester reject archive if ANY file is beyond age limit?'); cfgItem('L Delete list filename',12,Cfg^.delFile, 'List of files to be removed from archives [Ascii file in data dir]'); cfgItem('M Add list filename',12,Cfg^.addFile, 'List of files to be added to archives [Ascii file in data dir]'); cfgItem('N BBS archive comment',12,Cfg^.comFile, 'Comment file to apply to processed files [Ascii file in data dir]'); cfgItem('O External maintenence',3,B2St(Cfg^.extMaint), 'Run "'+fileExtMaint+' [filename]" when processing? [Batch file; data dir]'); cfgItem('P Upload search method',26,cfgOption(optSearch,Cfg^.ulSearch), 'Duplicate upload scan method'); cfgItem('Q Auto-validate uploads',3,B2St(Cfg^.autoValidate), 'Default uploaded files to being "validated" for transfer?'); cfgItem('R File point return %',6,St(Cfg^.filePtsPer)+'%', 'Percentage of uploaded file''s file point value the user will receive'); cfgItem('S Use UL/DL ratio',3,B2St(Cfg^.useUlDlratio), 'Allow only a certain number of downloads per each upload?'); cfgSrt := 40; cfgLn := 4; cfgCol := 64; cfgItem('T Use UL/DL kb ratio',3,B2St(Cfg^.useKbRatio), 'Limit the number of kilobytes downloadable per each uploaded kilobyte?'); cfgItem('U Desc filename #1',13,Cfg^.fileDesc1, 'Primary description filename [used when importing descs from archives]'); cfgItem('V Desc filename #2',13,Cfg^.fileDesc2, 'Secondary description filename [used when importing descs from archives]'); cfgItem('W Wrap file descs',3,B2St(Cfg^.descWrap), 'Wrap long file descriptions to span multiple pages or clip to screen limit?'); cfgItem('X Advance file bar',3,B2St(Cfg^.advFileBar), 'Advance the file listing hilight bar to the next file after flagging?'); cfgItem('Y Allow blind uploads',3,B2St(Cfg^.allowBlind), 'Process all files uploaded, even if they were not specified in batch?'); if cfgDraw then Dec(cfgBot,6); cfgBar; cfgDrawAllItems; cfgPromptCommand; case cfgKey of 'A' : begin cfgReadBoolean(Cfg^.compFileAreas); cfgSetItem(B2St(Cfg^.compFileAreas)); end; 'B' : begin cfgReadBoolean(Cfg^.importDescs); cfgSetItem(B2St(Cfg^.importDescs)); end; 'C' : begin cfgReadBoolean(Cfg^.useFilePoints); cfgSetItem(B2St(Cfg^.useFilePoints)); end; 'D' : begin cfgReadInfo(St(Cfg^.kbPerFilePoint),inUpper,chNumeric,'',True); Cfg^.kbPerFilePoint := mClip(StrToInt(cfgRead),1,10000); cfgSetItem(St(Cfg^.kbPerFilePoint)); end; 'E' : begin cfgReadBoolean(Cfg^.useDLlimit); cfgSetItem(B2St(Cfg^.useDLlimit)); end; 'F' : begin cfgReadBoolean(Cfg^.useDLkbLimit); cfgSetItem(B2St(Cfg^.useDLkbLimit)); end; 'G' : begin cfgEditInfo(Cfg^.noDescLine,50,inNormal,chNormal,'',False); Cfg^.noDescLine := cfgRead; cfgSetItem(Cfg^.noDescLine); end; 'H' : begin cfgEditInfo(Cfg^.virusScan,50,inNormal,chNormal,'',False); Cfg^.virusScan := cfgRead; cfgSetItem(Cfg^.virusScan); end; 'I' : begin cfgReadInfo(St(Cfg^.virusOk),inUpper,chNumeric,'',True); Cfg^.virusOk := mClip(StrToInt(cfgRead),0,255); cfgSetItem(St(Cfg^.virusOk)); end; 'J' : begin cfgReadInfo(St(Cfg^.maxFileAge),inUpper,chNumeric,'',True); Cfg^.maxFileAge := mClip(StrToInt(cfgRead),1,255); cfgSetItem(St(Cfg^.maxFileAge)); end; 'K' : begin cfgReadBoolean(Cfg^.strictAge); cfgSetItem(B2St(Cfg^.strictAge)); end; 'L' : begin cfgReadInfo(Cfg^.delFile,inUpper,chFilename,'',False); Cfg^.delFile := cfgRead; cfgSetItem(Cfg^.delFile); end; 'M' : begin cfgReadInfo(Cfg^.addFile,inUpper,chFilename,'',False); Cfg^.addFile := cfgRead; cfgSetItem(Cfg^.addFile); end; 'N' : begin cfgReadInfo(Cfg^.comFile,inUpper,chFilename,'',False); Cfg^.comFile := cfgRead; cfgSetItem(Cfg^.comFile); end; 'O' : begin cfgReadBoolean(Cfg^.extMaint); cfgSetItem(B2St(Cfg^.extMaint)); end; 'P' : begin cfgReadOption(optSearch,4,Cfg^.ulSearch); cfgSetItem(cfgOption(optSearch,Cfg^.ulSearch)); end; 'Q' : begin cfgReadBoolean(Cfg^.autoValidate); cfgSetItem(B2St(Cfg^.autoValidate)); end; 'R' : begin cfgSetItem(' '); cfgReadInfo(St(Cfg^.filePtsPer),inUpper,chNumeric,'',True); Cfg^.filePtsPer := mClip(StrToInt(cfgRead),0,64000); cfgSetItem(St(Cfg^.filePtsPer)+'%'); end; 'S' : begin cfgReadBoolean(Cfg^.useUlDlratio); cfgSetItem(B2St(Cfg^.useUlDlratio)); end; 'T' : begin cfgReadBoolean(Cfg^.useKbratio); cfgSetItem(B2St(Cfg^.useKbratio)); end; 'U' : begin cfgReadInfo(Cfg^.fileDesc1,inUpper,chFilename,'',False); Cfg^.fileDesc1 := cfgRead; cfgSetItem(Cfg^.fileDesc1); end; 'V' : begin cfgReadInfo(Cfg^.fileDesc2,inUpper,chFilename,'',False); Cfg^.fileDesc2 := cfgRead; cfgSetItem(Cfg^.fileDesc2); end; 'W' : begin cfgReadBoolean(Cfg^.descWrap); cfgSetItem(B2St(Cfg^.descWrap)); end; 'X' : begin cfgReadBoolean(Cfg^.advFileBar); cfgSetItem(B2St(Cfg^.advFileBar)); end; 'Y' : begin cfgReadBoolean(Cfg^.allowBlind); cfgSetItem(B2St(Cfg^.allowBlind)); end; end; until (HangUp) or (cfgDone); cfgDone := False; end; procedure cfgOfflineMail; begin cfgDraw := True; cfgOver := False; repeat cfgInit('Offline Mail Setup'); cfgItem('A QWK filename prefix',8,Cfg^.qwkFilename, 'QWK/ID filename prefix for QWK and REP packets'); cfgItem('B Welcome filename',12,Cfg^.qwkWelcome, 'QWK welcome banner filename, must be in text directory'); cfgItem('C News filename',12,Cfg^.qwkNews, 'QWK news filename, must be in text directory'); cfgItem('D Goodbye filename',12,Cfg^.qwkGoodbye, 'QWK goodbye filename, must be in text directory'); cfgItem('E Local QWK path',40,Cfg^.qwkLocalPath, 'Path where .QWK files will be placed when downloaded locally'); cfgItem('F Ignore time left',3,b2St(Cfg^.qwkIgnoreTime), 'Ignore time remaining online when downloading QWK packets?'); cfgItem('G Strip autosigs',3,b2St(Cfg^.qwkStripSigs), 'Strip autosignatures from messages before exporting QWK?'); cfgBar; cfgDrawAllItems; cfgPromptCommand; case cfgKey of 'A' : begin cfgReadInfo(Cfg^.qwkFilename,inUpper,chFileNoExt,'',True); Cfg^.qwkFilename := cfgRead; cfgSetItem(Cfg^.qwkFilename); end; 'B' : begin cfgReadInfo(Cfg^.qwkWelcome,inUpper,chFilename,'',False); Cfg^.qwkWelcome := cfgRead; cfgSetItem(Cfg^.qwkWelcome); end; 'C' : begin cfgReadInfo(Cfg^.qwkNews,inUpper,chFilename,'',False); Cfg^.qwkNews := cfgRead; cfgSetItem(Cfg^.qwkNews); end; 'D' : begin cfgReadInfo(Cfg^.qwkGoodbye,inUpper,chFilename,'',False); Cfg^.qwkGoodbye := cfgRead; cfgSetItem(Cfg^.qwkGoodbye); end; 'E' : begin cfgReadInfo(Cfg^.qwkLocalPath,inUpper,chDirectory,'',True); Cfg^.qwkLocalPath := cfgRead; if Cfg^.qwkLocalPath[Length(Cfg^.qwkLocalPath)] <> '\' then Cfg^.qwkLocalPath := Cfg^.qwkLocalPath+'\'; cfgSetItem(Cfg^.qwkLocalPath); cfgAskCreate(Cfg^.qwkLocalPath); end; 'F' : begin cfgReadBoolean(Cfg^.qwkIgnoreTime); cfgSetItem(B2St(Cfg^.qwkIgnoreTime)); end; 'G' : begin cfgReadBoolean(Cfg^.qwkStripSigs); cfgSetItem(B2St(Cfg^.qwkStripSigs)); end; end; until (HangUp) or (cfgDone); cfgDone := False; end; procedure cfgNewUserVoting; begin cfgDraw := True; cfgOver := False; repeat cfgInit('New User Voting Config'); cfgItem('A "Yes" votes to validate',3,st(cfg^.nuvVotesYes), '[1-255] Number of "yes" votes required for a user to be auto-validated'); cfgItem('B "No" votes to delete',3,st(cfg^.nuvVotesNo), '[1-255] Number of "no" votes necessary for a user to be terminated'); cfgItem('C Unvalidated user access',20,cfg^.nuvAccess, 'Users who meet this condition are prospects for new user voting'); cfgItem('D Access to vote',20,cfg^.nuvVoteAccess, 'Access condition required to vote on new users'); cfgItem('E Comment initials',3,b2st(cfg^.nuvInitials), 'Apply user''s alias initials (ie fiend = fi) to NUV comments?'); cfgItem('F Validation level',1,cfg^.nuvUserLevel, 'Access level (set in level editor) to upgrade user to if voted in'); cfgItem('G Use new user voting?',3,b2st(cfg^.nuvValidation), 'Do you want to use NUV as a validation method on this BBS?'); cfgBar; cfgDrawAllItems; cfgPromptCommand; case cfgKey of 'A' : begin cfgReadInfo(st(cfg^.nuvVotesYes),inUpper,chNumeric,'',True); cfg^.nuvVotesYes := mClip(strToInt(cfgRead),1,255); cfgSetItem(st(cfg^.nuvVotesYes)); end; 'B' : begin cfgReadInfo(st(cfg^.nuvVotesNo),inUpper,chNumeric,'',True); cfg^.nuvVotesNo := mClip(strToInt(cfgRead),1,255); cfgSetItem(st(cfg^.nuvVotesNo)); end; 'C' : begin cfgReadInfo(cfg^.nuvAccess,inLower,chNormal,'',True); cfg^.nuvAccess := cfgRead; cfgSetItem(cfg^.nuvAccess); end; 'D' : begin cfgReadInfo(cfg^.nuvVoteAccess,inLower,chNormal,'',True); cfg^.nuvVoteAccess := cfgRead; cfgSetItem(cfg^.nuvVoteAccess); end; 'E' : begin cfgReadBoolean(cfg^.nuvInitials); cfgSetItem(b2st(cfg^.nuvInitials)); end; 'F' : begin cfgReadInfo(cfg^.nuvUserLevel,inUpper,chAlpha,'',True); cfg^.nuvUserLevel := cfgRead[1]; cfgSetItem(cfg^.nuvUserLevel); end; 'G' : begin cfgReadBoolean(cfg^.nuvValidation); cfgSetItem(b2st(cfg^.nuvValidation)); end; end; until (HangUp) or (cfgDone); cfgDone := False; end; procedure cfgSystemConfig; var cfgOld : tCfgRec; oldBar : Byte; begin cfgOld := Cfg^; logWrite('*System configuration edit'); oldBar := 1; repeat cfgDraw := True; cfgOver := False; cfgInit(bbsTitle+' v'+bbsVersion+' System Configuration'); cfgBarPos := oldBar; cfgItem('A Main BBS configuration',0,'',''); cfgItem('B Status bar options',0,'',''); cfgItem('C Color configuration',0,'',''); cfgItem('D Network address setup',0,'',''); cfgItem('E Edit macro strings',0,'',''); cfgItem('F Filenames and paths',0,'',''); cfgItem('G Wait-for-call config',0,'',''); cfgItem('H Miscellaneous options',0,'',''); cfgItem('I Offline mail setup',0,'',''); cfgSrt := 38; cfgCol := 60; cfgLn := cfgTop; cfgItem('J Swapping setup',0,'',''); cfgItem('K Login configuration',0,'',''); cfgItem('L Origin line configuration',0,'',''); cfgItem('M Logging options',0,'',''); cfgItem('N Message system config',0,'',''); cfgItem('O New user options',0,'',''); cfgItem('P Chat mode setup',0,'',''); cfgItem('Q File system config',0,'',''); cfgItem('R New user voting config',0,'',''); if cfgDraw then Dec(cfgBot,9); cfgBar; cfgDrawAllItems; cfgPromptCommand; oldBar := cfgBarPos; case cfgKey of 'A' : cfgMainBBSConfig; 'B' : cfgStatusBar; 'C' : cfgColorConfig; 'D' : cfgNetAddress; 'E' : cfgMacroStrings; 'F' : cfgPaths; 'G' : cfgWaitForCall; 'H' : cfgMiscOptions; 'I' : cfgOfflineMail; 'J' : cfgSwappingSetup; 'K' : cfgLoginConfig; 'L' : cfgOriginLines; 'M' : cfgLoggingOptions; 'N' : cfgMessageSystem; 'O' : cfgNewUserOptions; 'P' : cfgChatSetup; 'Q' : cfgFileSystem; 'R' : cfgNewUserVoting; end; until (HangUp) or (cfgDone); cfgInfo('Save configuration? '); if iYesNo(True) then fSaveCfg else Cfg^ := cfgOld; end; end.
#skip unit TList_1; interface uses System; type TPointerList = array of Pointer; TDirection = (dLeft, dRght); TList = class private FList: TPointerList; FCount: Integer; FCapacity: Integer; protected function Get(Index: Integer): Pointer; procedure Grow; virtual; procedure Put(Index: Integer; Item: Pointer); //procedure Notify(Ptr: Pointer; Action: TListNotification); virtual; procedure SetCapacity(NewCapacity: Integer); procedure SetCount(NewCount: Integer); public destructor Destroy; override; function Add(Item: Pointer): Integer; procedure Clear; virtual; procedure Delete(Index: Integer); class procedure Error(const Msg: string; Data: NativeInt); overload; virtual; //class procedure Error(Msg: PResStringRec; Data: NativeInt); overload; procedure Exchange(Index1, Index2: Integer); function Expand: TList; function Extract(Item: Pointer): Pointer; inline; function ExtractItem(Item: Pointer; Direction: TDirection): Pointer; function First: Pointer; inline; // function GetEnumerator: TListEnumerator; function IndexOf(Item: Pointer): Integer; function IndexOfItem(Item: Pointer; Direction: TDirection): Integer; procedure Insert(Index: Integer; Item: Pointer); function Last: Pointer; procedure Move(CurIndex, NewIndex: Integer); function Remove(Item: Pointer): Integer; inline; function RemoveItem(Item: Pointer; Direction: TDirection): Integer; procedure Pack; // procedure Sort(Compare: TListSortCompare); // procedure SortList(const Compare: TListSortCompareFunc); //procedure Assign(ListA: TList; AOperator: TListAssignOp = laCopy; ListB: TList = nil); property Capacity: Integer read FCapacity write SetCapacity; property Count: Integer read FCount write SetCount; //property Items[Index: Integer]: Pointer read Get write Put; default; property List: TPointerList read FList; end; implementation destructor TList.Destroy; begin Clear; end; function TList.Add(Item: Pointer): Integer; begin Result := FCount; if Result = FCapacity then Grow; FList[Result] := Item; Inc(FCount); if (Item <> nil) and (ClassType <> TList) then Notify(Item, lnAdded); end; procedure TList.Clear; begin SetCount(0); SetCapacity(0); end; procedure TList.Delete(Index: Integer); var Temp: Pointer; begin if (Index < 0) or (Index >= FCount) then Error(@SListIndexError, Index); Temp := FList[Index]; Dec(FCount); if Index < FCount then System.Move(FList[Index + 1], FList[Index], (FCount - Index) * SizeOf(Pointer)); if (Temp <> nil) and (ClassType <> TList) then Notify(Temp, lnDeleted); end; class procedure TList.Error(const Msg: string; Data: NativeInt); begin raise EListError.CreateFmt(Msg, [Data]) at ReturnAddress; end; class procedure TList.Error(Msg: PResStringRec; Data: NativeInt); begin raise EListError.CreateFmt(LoadResString(Msg), [Data]) at ReturnAddress; end; procedure TList.Exchange(Index1, Index2: Integer); var Item: Pointer; begin if (Index1 < 0) or (Index1 >= FCount) then Error(@SListIndexError, Index1); if (Index2 < 0) or (Index2 >= FCount) then Error(@SListIndexError, Index2); Item := FList[Index1]; FList[Index1] := FList[Index2]; FList[Index2] := Item; end; function TList.Expand: TList; begin if FCount = FCapacity then Grow; Result := Self; end; function TList.First: Pointer; begin Result := Get(0); end; function TList.Get(Index: Integer): Pointer; begin if Cardinal(Index) >= Cardinal(FCount) then Error(@SListIndexError, Index); Result := FList[Index]; end; function TList.GetEnumerator: TListEnumerator; begin Result := TListEnumerator.Create(Self); end; procedure TList.Grow; var Delta: Integer; begin if FCapacity > 64 then Delta := FCapacity div 4 else if FCapacity > 8 then Delta := 16 else Delta := 4; SetCapacity(FCapacity + Delta); end; function TList.IndexOf(Item: Pointer): Integer; var P: PPointer; begin P := Pointer(FList); for Result := 0 to FCount - 1 do begin if P^ = Item then Exit; Inc(P); end; Result := -1; end; function TList.IndexOfItem(Item: Pointer; Direction: TDirection): Integer; var P: PPointer; begin if Direction = FromBeginning then Result := IndexOf(Item) else begin if FCount > 0 then begin P := Pointer(@List[FCount - 1]); for Result := FCount - 1 downto 0 do begin if P^ = Item then Exit; Dec(P); end; end; Result := -1; end; end; procedure TList.Insert(Index: Integer; Item: Pointer); begin if (Index < 0) or (Index > FCount) then Error(@SListIndexError, Index); if FCount = FCapacity then Grow; if Index < FCount then System.Move(FList[Index], FList[Index + 1], (FCount - Index) * SizeOf(Pointer)); FList[Index] := Item; Inc(FCount); if (Item <> nil) and (ClassType <> TList) then Notify(Item, lnAdded); end; function TList.Last: Pointer; begin if FCount > 0 then Result := FList[Count - 1] else begin Error(@SListIndexError, 0); Result := nil; end; end; procedure TList.Move(CurIndex, NewIndex: Integer); var Item: Pointer; begin if CurIndex <> NewIndex then begin if (NewIndex < 0) or (NewIndex >= FCount) then Error(@SListIndexError, NewIndex); Item := Get(CurIndex); FList[CurIndex] := nil; Delete(CurIndex); Insert(NewIndex, nil); FList[NewIndex] := Item; end; end; procedure TList.Put(Index: Integer; Item: Pointer); var Temp: Pointer; begin if (Index < 0) or (Index >= FCount) then Error(@SListIndexError, Index); if Item <> FList[Index] then begin Temp := FList[Index]; FList[Index] := Item; if ClassType <> TList then begin if Temp <> nil then Notify(Temp, lnDeleted); if Item <> nil then Notify(Item, lnAdded); end; end; end; function TList.Remove(Item: Pointer): Integer; begin Result := RemoveItem(Item, TList.TDirection.FromBeginning); end; function TList.RemoveItem(Item: Pointer; Direction: TDirection): Integer; begin Result := IndexOfItem(Item, Direction); if Result >= 0 then Delete(Result); end; procedure TList.Pack; var PackedCount : Integer; StartIndex : Integer; EndIndex : Integer; begin if FCount = 0 then Exit; PackedCount := 0; StartIndex := 0; repeat // Locate the first/next non-nil element in the list while (StartIndex < FCount) and (FList[StartIndex] = nil) do Inc(StartIndex); if StartIndex < FCount then // There is nothing more to do begin // Locate the next nil pointer EndIndex := StartIndex; while (EndIndex < FCount) and (FList[EndIndex] <> nil) do Inc(EndIndex); Dec(EndIndex); // Move this block of non-null items to the index recorded in PackedToCount: // If this is a contiguous non-nil block at the start of the list then // StartIndex and PackedToCount will be equal (and 0) so don't bother with the move. if StartIndex > PackedCount then System.Move(FList[StartIndex], FList[PackedCount], (EndIndex - StartIndex + 1) * SizeOf(Pointer)); // Set the PackedToCount to reflect the number of items in the list // that have now been packed. Inc(PackedCount, EndIndex - StartIndex + 1); // Reset StartIndex to the element following EndIndex StartIndex := EndIndex + 1; end; until StartIndex >= FCount; // Set Count so that the 'free' item FCount := PackedCount; end; procedure TList.SetCapacity(NewCapacity: Integer); begin if NewCapacity < FCount then Error(@SListCapacityError, NewCapacity); if NewCapacity <> FCapacity then begin SetLength(FList, NewCapacity); FCapacity := NewCapacity; end; end; procedure TList.SetCount(NewCount: Integer); var I: Integer; Temp: Pointer; begin if NewCount < 0 then Error(@SListCountError, NewCount); if NewCount <> FCount then begin if NewCount > FCapacity then SetCapacity(NewCount); if NewCount > FCount then FillChar(FList[FCount], (NewCount - FCount) * SizeOf(Pointer), 0) else if ClassType <> TList then begin for I := FCount - 1 downto NewCount do begin Dec(FCount); Temp := List[I]; if Temp <> nil then Notify(Temp, lnDeleted); end; end; FCount := NewCount; end; end; initialization finalization end.
UNIT schedule; INTERFACE USES graph; Type GrafMaker=object last_x11, last_y11, last_x12, last_y12, last_x21, last_y21, last_x22, last_y22: real; n1,n2,n3,n4:integer; Constructor Init; Procedure DrawPlate; Procedure DrawLine(x, y : real; GRAF_TYPE, SOURCE_NUM, STEP : integer); Procedure MakeTable; Procedure MakeData(DATA:real; SOURCE_NUM, GRAF_TYPE: integer); end; Var xGrafMaker : GrafMaker; IMPLEMENTATION Constructor GrafMaker.Init; Begin last_x11 := 0; last_y11 := 0; last_x12 := 0; last_y12 := 0; last_x21 := 0; last_y21 := 0; last_x22 := 0; last_y22 := 0; n1:=0; n2:=0; n3:=0; n4:=0; End; Procedure GrafMaker.DrawPlate; var i : integer; begin OutTextXY(170,10,'1 STREAM - RED ; 2 STREAM - GREEN'); SetColor(white); OutTextXY(GetMaxX div 10-20,GetMaxY div 2-200,'Pi'); OutTextXY(8*GetMaxX div 10-50,GetMaxY div 2-20,'LAM1'); line(GetMaxX div 10,GetMaxY div 2-30,8*GetMaxX div 10-40,GetMaxY div 2-30); {OX1} line(GetMaxX div 10,GetMaxY div 2-30,GetMaxX div 10,GetMaxY div 2-200); {OY1} OutTextXY(GetMaxX div 10-20,GetMaxY-200,'Mi'); OutTextXY(8*GetMaxX div 10-50,GetMaxY-20,'LAM1'); line(GetMaxX div 10,GetMaxY-30,8*GetMaxX div 10-40,GetMaxY-30); {OX2} line(GetMaxX div 10,GetMaxY-30,GetMaxX div 10,GetMaxY-200); {OY2} {shkala OX} for i:=1 to 10 do begin line(GetMaxX div 10+35*i,GetMaxY div 2-25,GetMaxX div 10+35*i,GetMaxY div 2-35); {1_graf_OX} line(GetMaxX div 10+35*i,GetMaxY-25,GetMaxX div 10+35*i,GetMaxY-35); {2_graf_OX} end; {shkala OY} for i:=1 to 4 do begin line(GetMaxX div 10+5,GetMaxY div 2-25-35*i,GetMaxX div 10-5,GetMaxY div 2-25-35*i); line(GetMaxX div 10+5,GetMaxY-25-35*i,GetMaxX div 10-5,GetMaxY-25-35*i) end; {1_graf_OX} OutTextXY(GetMaxX div 10-10,GetMaxY div 2-20,'0.5'); OutTextXY(GetMaxX div 10+165,GetMaxY div 2-20,'1.0'); OutTextXY(GetMaxX div 10+340,GetMaxY div 2-20,'1.5'); OutTextXY(GetMaxX div 10-35,GetMaxY div 2-100,'50%'); OutTextXY(GetMaxX div 10-40,GetMaxY div 2-170,'100%'); {2_graf_OX} OutTextXY(GetMaxX div 10-10,GetMaxY-20,'0.5'); OutTextXY(GetMaxX div 10+165,GetMaxY-20,'1.0'); OutTextXY(GetMaxX div 10+340,GetMaxY-20,'1.5'); OutTextXY(GetMaxX div 10-35,GetMaxY-100,'50%'); OutTextXY(GetMaxX div 10-40,GetMaxY-170,'100%'); {triangles} Line(8*GetMaxX div 10-40, GetMaxY div 2-27, 8*GetMaxX div 10-40, GetMaxY div 2-33); Line(8*GetMaxX div 10-40, GetMaxY div 2-33, 8*GetMaxX div 10-30, GetMaxY div 2-30); Line(8*GetMaxX div 10-30, GetMaxY div 2-30, 8*GetMaxX div 10-40, GetMaxY div 2-27); Line(8*GetMaxX div 10-40, GetMaxY-27, 8*GetMaxX div 10-40, GetMaxY-33); Line(8*GetMaxX div 10-40, GetMaxY-33, 8*GetMaxX div 10-30, GetMaxY-30); Line(8*GetMaxX div 10-30, GetMaxY-30, 8*GetMaxX div 10-40, GetMaxY-27); Line(GetMaxX div 10-3, GetMaxY div 2-200, GetMaxX div 10+3, GetMaxY div 2-200); Line(GetMaxX div 10+3, GetMaxY div 2-200, GetMaxX div 10, GetMaxY div 2-210); Line(GetMaxX div 10, GetMaxY div 2-210, GetMaxX div 10-3, GetMaxY div 2-200); Line(GetMaxX div 10-3, GetMaxY-200, GetMaxX div 10+3, GetMaxY-200); Line(GetMaxX div 10+3, GetMaxY-200, GetMaxX div 10, GetMaxY-210); Line(GetMaxX div 10, GetMaxY-210, GetMaxX div 10-3, GetMaxY-200); End; Procedure GrafMaker.DrawLine(x, y : real; GRAF_TYPE, SOURCE_NUM, STEP : integer); begin if SOURCE_NUM = 1 then setcolor(red) else setcolor(green); if STEP = 1 then case SOURCE_NUM of 1 : case GRAF_TYPE of 1 : begin last_x11 := x; last_y11 := y; end; 2 : begin last_x12 := x; last_y12 := y; end; end; 2 : case GRAF_TYPE of 1 : begin last_x21 := x; last_y21 := y; end; 2 : begin last_x22 := x; last_y22 := y; end; end; end else case SOURCE_NUM of 1 : case GRAF_TYPE of 1 : begin {P for 1 stream} circle(GetMaxX div 10 + (STEP - 2) * 35,GetMaxY div 2-40 - round(last_y11*100),2); line(GetMaxX div 10 + (STEP - 2) * 35, GetMaxY div 2-40 - round(last_y11*100), GetMaxX div 10 + (STEP-1) * 35, GetMaxY div 2-40 - round(y*100)); last_x11 := x; last_y11 := y; end; 2 : begin {M for 1 stream} circle(GetMaxX div 10 + (STEP - 2) * 35, GetMaxY - 40 - round(last_y12*100),2); line(GetMaxX div 10 + (STEP - 2) * 35, GetMaxY - 40 - round(last_y12*100), GetMaxX div 10 + (STEP-1) * 35, GetMaxY - 40 - round(y*100)); last_x12 := x; last_y12 := y; end; end; 2 : case GRAF_TYPE of 1 : begin {P for 2 stream} circle(GetMaxX div 10 + (STEP - 2) * 35, GetMaxY div 2 - 40 - round(last_y21*100),2); line(GetMaxX div 10 + (STEP - 2) * 35, GetMaxY div 2 - 40 - round(last_y21*100), GetMaxX div 10 + (STEP-1) * 35, GetMaxY div 2 - 40 - round(y*100)); last_x21 := x; last_y21 := y; end; 2 : begin {M for 2 stream} circle(GetMaxX div 10 + (STEP - 2) * 35, GetMaxY - 40 - round(last_y22*100),2); line(GetMaxX div 10 + (STEP - 2) * 35, GetMaxY - 40 - round(last_y22*100), GetMaxX div 10 + (STEP-1) * 35, GetMaxY - 40 - round(y*100)); last_x22 := x; last_y22 := y; end; end; end; end; Procedure GrafMaker.MakeTable; var s : string; i : integer; begin SetColor(white); OutTextXY(GetMaxX div 2 - 35,10,'RESULTS'); for i := 0 to 5 do line(3*GetMaxX div 16 + GetMaxX div 8 * i, 20, 3*GetMaxX div 16 + GetMaxX div 8 * i, 20 + GetMaxY div 13 * 12); for i := 0 to 12 do line(3*GetMaxX div 16, 20 + GetMaxY div 13 * i, 3*GetMaxX div 16 + GetMaxX div 8 * 5, 20+GetMaxY div 13 * i); outtextxy(3*GetMaxX div 16+25, 30, 'LAM1'); outtextxy(3*GetMaxX div 16+ GetMaxX div 8 * 1+30, 30, 'P1'); outtextxy(3*GetMaxX div 16+ GetMaxX div 8 * 2+30, 30, 'P2'); outtextxy(3*GetMaxX div 16+ GetMaxX div 8 * 3+30, 30, 'M1'); outtextxy(3*GetMaxX div 16+ GetMaxX div 8 * 4+30, 30, 'M2'); for i := 0 to 10 do begin str(0.5 + i * 0.1 : 0 : 1, s); outtextxy(3*GetMaxX div 16+30, 35 + GetMaxY div 13+GetMaxY div 13 * i, s); end; end; Procedure GrafMaker.MakeData(DATA:real; SOURCE_NUM, GRAF_TYPE: integer); var s : string; begin SetColor(white); str(DATA : 2 : 2, s); case SOURCE_NUM of 1 : case GRAF_TYPE of 1 : begin {P for 1 potoka} outtextxy(3*GetMaxX div 16+ GetMaxX div 8*1+30, 35 + GetMaxY div 13+GetMaxY div 13 * n1, s); n1:=n1+1; end; 2 : begin {M for 1 potoka} outtextxy(3*GetMaxX div 16+ GetMaxX div 8*2+30, 35 + GetMaxY div 13+GetMaxY div 13 * n2, s); n2:=n2+1; end; end; 2 : case GRAF_TYPE of 1 : begin {P for 2 potoka} outtextxy(3*GetMaxX div 16+ GetMaxX div 8*3+30, 35 + GetMaxY div 13+GetMaxY div 13 * n3, s); n3:=n3+1; end; 2 : begin {M for 2 potoka} outtextxy(3*GetMaxX div 16+ GetMaxX div 8*4+30, 35 + GetMaxY div 13+GetMaxY div 13 * n4, s); n4:=n4+1; end; end; end; end; BEGIN END.
(* WildCardPatternMatching: MM, 2020-03-20 *) (* ------ *) (* Code to use wildcards in pattern matching *) (* ========================================================================= *) PROGRAM WildCardPatternMatching; VAR charComps: INTEGER; TYPE PatternMatcher = FUNCTION(s, p: STRING): BOOLEAN; PROCEDURE Init; BEGIN (* Init *) charComps := 0; END; (* Init *) PROCEDURE WriteCharComps; BEGIN (* WriteCharComps *) Write(charComps); END; (* WriteCharComps *) FUNCTION Equals(a, b: STRING): BOOLEAN; BEGIN (* Equals *) Inc(charComps); Equals := (a = b); END; (* Equals *) FUNCTION BruteSearchLR(s, p: STRING): BOOLEAN; VAR sLen, pLen: INTEGER; i, j: INTEGER; BEGIN (* BruteSearchLR *) sLen := Length(s); pLen := Length(p); IF (pLen = 0) OR (sLen = 0) OR (pLen > sLen) THEN BEGIN BruteSearchLR := FALSE; END ELSE BEGIN i := 1; j := 1; REPEAT IF (Equals(s[i], p[j]) OR Equals(p[j], '?')) THEN BEGIN Inc(i); Inc(j); END ELSE BEGIN i := i - j + 2; j := 1; END; (* IF *) UNTIL ((j > pLen) OR (i > sLen)); (* REPEAT *) IF (j > pLen) THEN BEGIN BruteSearchLR := TRUE; END ELSE BEGIN BruteSearchLR := FALSE; END; (* IF *) END; (* IF *) END; (* BruteSearchLR *) FUNCTION BruteForceWithWildCard(s, p: STRING): BOOLEAN; BEGIN (* BruteForceWithWildCard *) IF (Equals(s, p)) THEN BEGIN BruteForceWithWildCard := TRUE; END ELSE BEGIN IF (Equals(s[1], p[1])) THEN BEGIN Delete(s, 1, 1); Delete(p, 1, 1); BruteForceWithWildCard := BruteForceWithWildCard(s, p); END ELSE IF (Equals('*', p[1])) THEN BEGIN IF (Equals(s[1], p[2])) THEN Delete(p, 1, 1) ELSE IF (Equals('*', p[2])) THEN BEGIN REPEAT Delete(p, 1, 1); UNTIL (NOT Equals('*', p[2])); END ELSE Delete(s, 1, 1); BruteForceWithWildCard := BruteForceWithWildCard(s, p); END ELSE BEGIN BruteForceWithWildCard := FALSE; END; (* IF *) END; (* IF *) END; (* BruteForceWithWildCard *) PROCEDURE TestPatternMatcher(pm: PatternMatcher; pmName: STRING; s, p: STRING); BEGIN (* TestPatternMatcher *) Init; Write(pmName, ': ', pm(s, p), ', comparisons: '); WriteCharComps; WriteLn(); END; (* TestPatternMatcher *) var s, p: STRING; BEGIN (* WildCardPatternMatching *) REPEAT Init; Write('Enter s > '); ReadLn(s); Write('Enter p > '); ReadLn(p); //TestPatternMatcher(BruteSearchLR, 'BruteSearchLRWith?', s, p); TestPatternMatcher(BruteForceWithWildCard, 'BruteSearchWithWildCard', s, p); UNTIL ((s = '') AND (p = '')); (* REPEAT *) END. (* WildCardPatternMatching *)
unit Planner; interface uses Contnrs, MetroBase; type //---------------------------------------------------------------------------- // A route segment is a 4 tuple (from, line, dir, to), where // - from is a station // - line is a line // - direction is a station (one of the end points of the line) // - to is a station //---------------------------------------------------------------------------- TRouteSegmentR = class(TObject) protected FFrom: TStationR; FLine: TLineR; FDirection: TStationR; FTo: TStationR; public // construction/destruction --------------------------- constructor Create(AFrom: TStationR; ALine: TLineR; ADirection: TStationR; ATo: TStationR); // basic queries -------------------------------------- function FromStation: TStationR; virtual; function Line: TLineR; virtual; function Direction: TStationR; virtual; function ToStation: TStationR; virtual; function StopCount: Integer; virtual; end; //---------------------------------------------------------------------------- // A route is a sequence of route segments [s_0,...,s_(n-1)], where // - 1 <= N // - (forall i: 1<=i<n: s_(i-1).to = s_i.from ) // - SegmentCount is the number of segments // - GetSegment returns the I-th segment // A route can also be seen as a sequence of stops: // - StopCount is the number of stops // - GetStop returns the I-th stop //---------------------------------------------------------------------------- TRouteR = class(TObject) public // basic queries -------------------------------------- function SegmentCount: Integer; virtual; abstract; function GetSegment(I: Integer): TRouteSegmentR; virtual; abstract; // derived queries ------------------------------------ function TransferCount: Integer; virtual; // pre: true // ret: (SegmentCount - 1) max 0 function StopCount: Integer; virtual; // pre: true // ret: (sum: 0 <= I < SegmentCount: GetSegment(I).StopCount) // - (SegmentCount - 1) // function GetStop(I: Integer): TStationR; virtual; // pre: 0 <= I < StopCount // ret: "I-th stop in sequence obtained by concatenating segments, // excluding duplicates at segment borders" // invariants ----------------------------------------- // I0: 1 <= SegmentCount // I1: (forall I: 1 <= I < SegmentCount: // GetSegment(I-1).FromStation = GetSegment(I).FromStation ) end; TRouteRW = class(TRouteR) protected FList: TObjectList; public // construction/destruction constructor Create; destructor Destroy; override; // basic queries -------------------------------------- function SegmentCount: Integer; override; function GetSegment(I: Integer): TRouteSegmentR; override; // preconditions -------------------------------------- function CanAdd(ASegment: TRouteSegmentR): Boolean; // pre: true // ret: (SegmentCount = 0) orelse // (GetSegment(SegmentCount - 1).ToStation = ASegment. FromStation) // commands ------------------------------------------- procedure Clear; virtual; procedure Add(ASegment: TRouteSegmentR); virtual; procedure Insert(I: Integer; ASegment: TRouteSegmentR); { etc., as needed} end; //---------------------------------------------------------------------------- // Perhaps it might be useful to also have a notion of a _set_ of routes and // one or more _filters_ to filter out subsets. // E.g.: // first, find the set S of all routes from A to B with a minimal number // of transfers; // second, filter from S those routes with a minimal (or almost minimal) // number of stops; //---------------------------------------------------------------------------- TRouteSet = class(TObject) protected FList: TObjectList; public // construction/destruction constructor Create; // pre: true // post: Abstr = empty destructor Destroy; override; // basic queries -------------------------------------- function RouteCount: Integer; // pre: true // ret: |Abstr| function GetRoute(I: Integer): TRouteR; // pre: 0 <= I < RouteCount // ret: Abstr[I] // derived queries ------------------------------------ function MinStops: Integer; // pre: true // ret: (min I: 0 <= I < RouteCount: GetRoute(I).StopCount function MinTransfers: Integer; // pre: true // ret: (min I: 0 <= I < RouteCount: GetRoute(I).TransferCount // commands ------------------------------------------- procedure Add(ARoute: TRouteR); // pre: true // effect: Abstr := Abstr union {ARoute} procedure Delete(ARoute: TRouteR); // pre: true // effect: Abstr ;= Abstr - {ARoute} procedure Clear; // pre: true // post: Abstr = empty procedure FilterMinStops; virtual; // pre: true // post: Abstr = // {I: (0 <= I < RouteCount) and GetRoute(I).StopCount = MinStops: // GetRoute(I)} procedure FilterMinTransfers; virtual; // pre: true // post: Abstr = // {I: (0 <= I < RouteCount) and GetRoute(I).TransferCount = MinTransfers: // GetRoute(I)} // model variables ------------------------------------ // Abstr: set of TRouteR objects represented by an object of this class end; //---------------------------------------------------------------------------- // Search options: // - soTransfer : minimal number of transfers // - soTransferStop: minimal number of transfers, then minimal number of stops // - soStop : minimal number of stops // - soStopTransfer: minimal number of stops, then minimal number of transfers //---------------------------------------------------------------------------- TSearchOption = (soAny, soTransfer, soTransferStop, soStop, soStopTransfer); TPlanner = class(TObject) public // queries -------------------------------------------- function FindRoutes(A, B: TStationR; AOption: TSearchOption): TRouteSet; virtual; abstract; // pre: true // ret: set of optimal (according to AOption) routes from A to B function FindRoute(A, B: TStationR; AOption: TSearchOption): TRouteR; virtual; abstract; // pre: true // ret: an optimal (According to AOption) route from A to B end; implementation //=============================================================== uses Math, SysUtils; { TRouteSegmentR } constructor TRouteSegmentR.Create(AFrom: TStationR; ALine: TLineR; ADirection, ATo: TStationR); begin inherited Create; FFrom := Afrom; FLine := ALine; FDirection := ADirection; FTo := ATo; end; function TRouteSegmentR.Direction: TStationR; begin Result := FDirection; end; function TRouteSegmentR.FromStation: TStationR; begin Result := FFrom; end; function TRouteSegmentR.Line: TLineR; begin Result := FLine; end; function TRouteSegmentR.StopCount: Integer; begin Result := Abs(FLine.IndexOf(FFrom) - FLine.IndexOf(FTo)) + 1; end; function TRouteSegmentR.ToStation: TStationR; begin Result := FTo; end; { TRouteR } //function TRouteR.GetStop(I: Integer): TStationR; //begin // Assert( (0 <= I) and (I < StopCount), // Format('Illegal index in TRouter.GetStop: %s', [I]) ); // {TODO} //end; function TRouteR.StopCount: Integer; var I: Integer; begin Result := - (SegmentCount - 1); for I := 0 to SegmentCount - 1 do Result := Result + GetSegment(I).StopCount; end; function TRouteR.TransferCount: Integer; begin Result := Max(SegmentCount - 1, 0); end; { TRouteRW } procedure TRouteRW.Add(ASegment: TRouteSegmentR); begin Assert(CanAdd(ASegment), 'TRouteRW.Add.pre'); Flist.Add(ASegment); end; function TRouteRW.CanAdd(ASegment: TRouteSegmentR): Boolean; begin if SegmentCount = 0 then Result := true else Result :=(GetSegment(SegmentCount - 1).ToStation = ASegment.FromStation); end; procedure TRouteRW.Clear; begin FList.Clear; end; constructor TRouteRW.Create; begin inherited Create; FList := TObjectList.Create(true); end; destructor TRouteRW.Destroy; begin FList.Free; inherited; end; function TRouteRW.GetSegment(I: Integer): TRouteSegmentR; begin Result := FList.Items[I] as TRouteSegmentR; end; procedure TRouteRW.Insert(I: Integer; ASegment: TRouteSegmentR); begin FList.Insert(I, ASegment); end; function TRouteRW.SegmentCount: Integer; begin Result := FList.Count; end; { TRouteSet } procedure TRouteSet.Add(ARoute: TRouteR); begin FList.Add(ARoute); end; procedure TRouteSet.Clear; begin FList.Clear; end; constructor TRouteSet.Create; begin inherited Create; FList := TObjectList.Create(true); end; procedure TRouteSet.Delete(ARoute: TRouteR); begin FList.Remove(ARoute); end; destructor TRouteSet.Destroy; begin FList.Free; inherited; end; procedure TRouteSet.FilterMinStops; var I, M: Integer; begin M := MinStops; for I := RouteCount -1 downto 0 do // N.B. downward direction important if GetRoute(I).StopCount > M then Delete(GetRoute(I)); end; procedure TRouteSet.FilterMinTransfers; var I, M: Integer; begin M := MinTransfers; for I := RouteCount -1 downto 0 do // N.B. downward direction important if GetRoute(I).TransferCount > M then Delete(GetRoute(I)); end; function TRouteSet.GetRoute(I: Integer): TRouteR; begin Assert( (0 <= I) and (I < RouteCount), Format('Illegal index in TRouteSet.GetRoute: %s', [I]) ); Result := FList.Items[I] as TRouteR; end; function TRouteSet.MinStops: Integer; var I: Integer; begin Result := MaxInt; for I := 0 to RouteCount - 1 do Result := Min(Result, GetRoute(I).StopCount); end; function TRouteSet.MinTransfers: Integer; var I: Integer; begin Result := MaxInt; for I := 0 to RouteCount - 1 do Result := Min(Result, GetRoute(I).TransferCount); end; function TRouteSet.RouteCount: Integer; begin Result := FList.Count; end; end.
unit AutoLoadPicturesAndDocuments; interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, DBCtrls, DBTables, DB, Buttons, Grids, Wwdbigrd, Wwdbgrid, ExtCtrls, Wwtable, Wwdatsrc, Menus, RPCanvas, RPrinter, RPDefine, RPBase, RPFiler, locatdir, FileCtrl; type TAutoLoadPicturesAndDocumentsForm = class(TForm) Panel1: TPanel; Panel2: TPanel; TitleLabel: TLabel; ReportFiler: TReportFiler; PrintDialog: TPrintDialog; ReportPrinter: TReportPrinter; ParcelTable: TTable; LocateDirectoryDialog: TLocateDirectoryDlg; ItemLocationLabel: TLabel; ItemTypeRadioGroup: TRadioGroup; DirectoryEdit: TEdit; DirectoryLocateButton: TButton; ReportFilesNotLoadedCheckBox: TCheckBox; UseEndOfFileNameAsNotesCheckBox: TCheckBox; LoadAtTopOfPictureListCheckBox: TCheckBox; ExactParcelIDMatchOnlyCheckBox: TCheckBox; Panel3: TPanel; PrintButton: TBitBtn; CloseButton: TBitBtn; OpenDialog1: TOpenDialog; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure PrintButtonClick(Sender: TObject); procedure ReportPrintHeader(Sender: TObject); procedure ReportPrint(Sender: TObject); procedure DirectoryLocateButtonClick(Sender: TObject); procedure ItemTypeRadioGroupClick(Sender: TObject); procedure FormActivate(Sender: TObject); private { Private declarations } public { Public declarations } UnitName : String; ItemType : Integer; ItemTypeStr : String; LoadAtTopOfPictureList, ReportFilesNotLoaded, ReportCancelled, PrintSubHeader, UseEndOfFileNameAsNotes, ExactParcelIDMatchOnly : Boolean; Procedure InitializeForm; {Open the tables and setup.} end; implementation uses GlblVars, WinUtils, Utilitys, GlblCnst, PASUtils, Prog, Preview, Types, PASTypes; {$R *.DFM} const ldPictures = 0; ldApexSketches = 1; ldPropertyCards = 2; ldDocuments = 3; ldCertiorariDocuments = 4; {========================================================} Procedure TAutoLoadPicturesAndDocumentsForm.FormActivate(Sender: TObject); begin SetFormStateMaximized(Self); end; {========================================================} Procedure TAutoLoadPicturesAndDocumentsForm.InitializeForm; begin UnitName := 'AutoLoadPicturesAndDocuments'; {mmm} OpenTablesForForm(Self, GlblProcessingType); DirectoryEdit.Text := ExpandPASPath(GlblPictureDir); {CHG08122007-1(2.11.3.1)[F654]: Autoload cert documents.} If not GlblUsesGrievances then ItemTypeRadioGroup.Items.Delete(ldCertiorariDocuments); {CHG06102009-6(2.20.1.1)[F839]: Option to suppress document autoload.} If GlblSuppressDocumentAutoload then ItemTypeRadioGroup.Items.Delete(ldDocuments); end; {InitializeForm} {===================================================================} Procedure TAutoLoadPicturesAndDocumentsForm.FormKeyPress( Sender: TObject; var Key: Char); begin If (Key = #13) then begin Key := #0; Perform(WM_NEXTDLGCTL, 0, 0); end; end; {FormKeyPress} {===================================================================} Procedure TAutoLoadPicturesAndDocumentsForm.ItemTypeRadioGroupClick(Sender: TObject); begin case ItemTypeRadioGroup.ItemIndex of ldPictures : begin DirectoryEdit.Text := ExpandPASPath(GlblPictureDir); ItemLocationLabel.Caption := 'Folder to find pictures in:'; end; ldDocuments : begin DirectoryEdit.Text := ExpandPASPath(GlblDocumentDir); ItemLocationLabel.Caption := 'Folder to find documents in:'; end; ldApexSketches : begin DirectoryEdit.Text := ExpandPASPath(GlblDefaultApexDir); ItemLocationLabel.Caption := 'Folder to find sketches in:'; end; ldPropertyCards : begin DirectoryEdit.Text := ExpandPASPath(GlblDefaultPropertyCardDirectory); ItemLocationLabel.Caption := 'Folder to find property cards in:'; end; ldCertiorariDocuments : ItemLocationLabel.Caption := 'Folder to find certiorari documents in:'; end; {case ItemTypeRadioGroup.ItemIndex of} end; {ItemTypeRadioGroupClick} {===================================================================} Procedure TAutoLoadPicturesAndDocumentsForm.DirectoryLocateButtonClick(Sender: TObject); begin If (_Compare(DirectoryEdit.Text, coNotBlank) and DirectoryExists(DirectoryEdit.Text)) then LocateDirectoryDialog.Directory := DirectoryEdit.Text; If LocateDirectoryDialog.Execute then DirectoryEdit.Text := LocateDirectoryDialog.Directory; end; {DirectoryLocateButtonClick} {===================================================================} Procedure TAutoLoadPicturesAndDocumentsForm.ReportPrintHeader(Sender: TObject); begin with Sender as TBaseReport do begin {Print the date and page number.} SectionTop := 0.25; SectionLeft := 0.5; SectionRight := PageWidth - 0.5; SetFont('Times New Roman',8); PrintHeader('Page: ' + IntToStr(CurrentPage), pjRight); PrintHeader('Date: ' + DateToStr(Date) + ' Time: ' + TimeToStr(Now), pjLeft); SectionTop := 0.5; SetFont('Arial',12); Bold := True; Home; PrintCenter(ItemTypeStr + 's Automatically Loaded', (PageWidth / 2)); SetFont('Times New Roman', 9); CRLF; Println(''); Println('Directory to load from: ' + DirectoryEdit.Text); Println(''); ClearTabs; SetTab(0.3, pjCenter, 1.5, 0, BOXLINEBottom, 0); {Parcel ID} SetTab(1.9, pjCenter, 2.0, 0, BOXLINEBottom, 0); {File name} SetTab(4.0, pjCenter, 2.0, 0, BOXLINEBottom, 0); {File name} SetTab(6.1, pjCenter, 2.0, 0, BOXLINEBottom, 0); {File name} If PrintSubHeader then Println(#9 + 'Parcel ID' + #9 + 'File Name' + #9 + 'File Name' + #9 + 'File Name'); ClearTabs; SetTab(0.3, pjLeft, 1.5, 0, BOXLINENONE, 0); {Parcel ID} SetTab(1.9, pjLeft, 2.0, 0, BOXLINENONE, 0); {File name} SetTab(4.0, pjLeft, 2.0, 0, BOXLINENONE, 0); {File name} SetTab(6.1, pjLeft, 2.0, 0, BOXLINENONE, 0); {File name} end; {with Sender as TBaseReport do} end; {ReportPrintHeader} {===================================================================} Procedure TAutoLoadPicturesAndDocumentsForm.ReportPrint(Sender: TObject); var Done, FirstTimeThrough : Boolean; SwisSBLKey : String; I, LinePrinted, ItemOnLine, FileAttributes, ReturnCode, Index, Column : Integer; ItemsAdded, AlreadyOnFileList, FilesInDirectoryList : TStringList; NumItemsLoaded : LongInt; Directory : String; TempFile : TSearchRec; begin NumItemsLoaded := 0; ItemsAdded := TStringList.Create; AlreadyOnFileList := TStringList.Create; Done := False; FirstTimeThrough := True; Directory := DirectoryEdit.Text; If (Directory[Length(Directory)] <> '\') then Directory := Directory + '\'; FilesInDirectoryList := TStringList.Create; {CHG10242002-2: Print out the files not found.} If ReportFilesNotLoaded then begin {FXX01272003-1: Exclude directories from not loaded list.} FileAttributes := SysUtils.faArchive + SysUtils.faReadOnly; ReturnCode := FindFirst(Directory + '*.*', FileAttributes, TempFile); while (ReturnCode = 0) do begin If ((TempFile.Name <> '.') and (TempFile.Name <> '..')) then FilesInDirectoryList.Add(TempFile.Name); ReturnCode := FindNext(TempFile); end; {while (ReturnCode = 0) do} end; {If ReportFilesNotLoaded} ParcelTable.First; with Sender as TBaseReport do repeat If FirstTimeThrough then FirstTimeThrough := False else ParcelTable.Next; If ParcelTable.EOF then Done := True; SwisSBLKey := ExtractSSKey(ParcelTable); ProgressDialog.Update(Self, ConvertSwisSBLToDashDot(SwisSBLKey)); ProgressDialog.UserLabelCaption := 'Number ' + ItemTypeStr + 's loaded = ' + IntToStr(NumItemsLoaded); Application.ProcessMessages; {FXX07092004-1(2.08): Don't load pictures on inactive parcels.} If ((ParcelTable.FieldByName('ActiveFlag').Text <> InactiveParcelFlag) and (not Done)) then begin If (LinesLeft < 5) then NewPage; ItemsAdded.Clear; {CHG01272003-2: Option to use the ending part of the picture name as a note.} {CHG06032004-1(2.07l5): Option to number pictures so they appear at the top of the list.} DetectNewPicturesOrDocuments(SwisSBLKey, Directory, ItemType, True, ItemsAdded, AlreadyOnFileList, UseEndOfFileNameAsNotes, LoadAtTopOfPictureList, ExactParcelIDMatchOnly, ParcelTable.FieldByName('AccountNo').AsString, ParcelTable.FieldByName('PrintKey').AsString); If (ItemsAdded.Count > 0) then begin LinePrinted := 1; I := 0; while (I <= (ItemsAdded.Count - 1)) do begin ItemOnLine := 1; If (LinePrinted = 1) then Print(#9 + ConvertSwisSBLToDashDot(SwisSBLKey)) else Print(#9); while ((I <= (ItemsAdded.Count - 1)) and (ItemOnLine <= 3)) do begin Print(#9 + StripPath(ItemsAdded[I])); ItemOnLine := ItemOnLine + 1; I := I + 1; NumItemsLoaded := NumItemsLoaded + 1; end; Println(''); LinePrinted := LinePrinted + 1; end; {while (I <= (ItemsAdded.Count - 1)) do} {CHG10242002-2: Print out the files not found.} If ReportFilesNotLoaded then begin For I := 0 to (ItemsAdded.Count - 1) do begin Index := FilesInDirectoryList.IndexOf(StripPath(ItemsAdded[I])); If (Index > -1) then FilesInDirectoryList.Delete(Index); end; {For I := 0 to (ItemsAdded.Count - 1) do} end; {If ReportFilesNotLoaded} end; {If (ItemsAdded.Count > 0)} {CHG01272003-1: Don't report pictures already on file.} If ReportFilesNotLoaded then For I := 0 to (AlreadyOnFileList.Count - 1) do begin Index := FilesInDirectoryList.IndexOf(StripPath(AlreadyOnFileList[I])); If (Index > -1) then FilesInDirectoryList.Delete(Index); end; {For I := 0 to (AlreadyOnFileList.Count - 1) do} end; {If not Done} ReportCancelled := ProgressDialog.Cancelled; until (Done or ReportCancelled); with Sender as TBaseReport do begin Bold := True; Println(#9 + 'Total ' + ItemTypeStr + 's loaded = ' + IntToStr(NumItemsLoaded)); Bold := False; ClearTabs; SetTab(0.5, pjLeft, 2.5, 0, BOXLINENONE, 0); {File name} SetTab(3.1, pjLeft, 2.5, 0, BOXLINENONE, 0); {File name} SetTab(5.6, pjLeft, 2.5, 0, BOXLINENONE, 0); {File name} Column := 1; PrintSubHeader := False; FirstTimeThrough := True; For I := 0 to (FilesInDirectoryList.Count - 1) do begin If ((LinesLeft < 5) or FirstTimeThrough) then begin If not FirstTimeThrough then begin NewPage; ClearTabs; SetTab(0.5, pjLeft, 2.5, 0, BOXLINENONE, 0); {File name} SetTab(3.1, pjLeft, 2.5, 0, BOXLINENONE, 0); {File name} SetTab(5.6, pjLeft, 2.5, 0, BOXLINENONE, 0); {File name} end; {If not FirstTimeThrough} Println(''); Underline := True; Println(#9 + 'Files in Directory NOT loaded into PAS:'); Underline := False; FirstTimeThrough := False; end; {If (LinesLeft < 5)} If (Column = 4) then begin Println(''); Column := 1; end; Print(#9 + StripPath(FilesInDirectoryList[I])); Column := Column + 1; end; {For I := 0 to (FilesInDirectoryList.Count - 1) do} end; {with Sender as TBaseReport do} ItemsAdded.Free; FilesInDirectoryList.Free; AlreadyOnFileList.Free; end; {ReportPrint} {===================================================================} Procedure TAutoLoadPicturesAndDocumentsForm.PrintButtonClick(Sender: TObject); var Quit : Boolean; NewFileName : String; TempFile : File; begin Quit := False; PrintSubHeader := True; ReportCancelled := False; ReportFilesNotLoaded := ReportFilesNotLoadedCheckBox.Checked; UseEndOfFileNameAsNotes := UseEndOfFileNameAsNotesCheckBox.Checked; ExactParcelIDMatchOnly := ExactParcelIDMatchOnlyCheckBox.Checked; LoadAtTopOfPictureList := LoadAtTopOfPictureListCheckBox.Checked; {FXX09301998-1: Disable print button after clicking to avoid clicking twice.} PrintButton.Enabled := False; Application.ProcessMessages; Quit := False; {CHG10121998-1: Add user options for default destination and show vet max msg.} SetPrintToScreenDefault(PrintDialog); If PrintDialog.Execute then begin {CHG10131998-1: Set the printer settings based on what printer they selected only - they no longer need to worry about paper or landscape mode.} AssignPrinterSettings(PrintDialog, ReportPrinter, ReportFiler, [ptLaser], False, Quit); case ItemTypeRadioGroup.ItemIndex of ldPictures : begin ItemType := dtPicture; ItemTypeStr := 'Picture'; end; ldDocuments : begin ItemType := dtScannedImage; ItemTypeStr := 'scanned document'; end; {CHG04282005-1(2.8.4.3)[2114]: Create autoload for sketches.} ldApexSketches : begin ItemType := dtApexSketch; ItemTypeStr := 'Apex sketches'; end; ldPropertyCards : begin ItemType := dtPropertyCard; ItemTypeStr := 'property card'; end; ldCertiorariDocuments : begin ItemType := dtCertiorari; ItemTypeStr := 'Cert Documents'; end; end; {case ItemTypeRadioGroup of} ProgressDialog.Start(GetRecordCount(ParcelTable), True, True); {Now print the report.} If not (Quit or ReportCancelled) then begin {If they want to preview the print (i.e. have it go to the screen), then we need to come up with a unique file name to tell the ReportFiler component where to put the output. Once we have done that, we will execute the report filer which will print the report to that file. Then we will create and show the preview print form and give it the name of the file. When we are done, we will delete the file and make sure that we go back to the original directory.} If PrintDialog.PrintToFile then begin NewFileName := GetPrintFileName(Self.Caption, True); ReportFiler.FileName := NewFileName; try PreviewForm := TPreviewForm.Create(self); PreviewForm.FilePrinter.FileName := NewFileName; PreviewForm.FilePreview.FileName := NewFileName; ReportFiler.Execute; {FXX10111999-3: Make sure they know its done.} ProgressDialog.StartPrinting(PrintDialog.PrintToFile); PreviewForm.ShowModal; finally PreviewForm.Free; {Now delete the file.} try AssignFile(TempFile, NewFileName); OldDeleteFile(NewFileName); finally {We don't care if it does not get deleted, so we won't put up an error message.} ChDir(GlblProgramDir); end; end; {try PreviewForm := ...} end {If PrintDialog.PrintToFile} else ReportPrinter.Execute; ResetPrinter(ReportPrinter); end; {If not Quit} ProgressDialog.Finish; {FXX10111999-3: Tell people that printing is starting and done.} DisplayPrintingFinishedMessage(PrintDialog.PrintToFile); end; {If PrintDialog.Execute} PrintButton.Enabled := True; end; {PrintButtonClick} {===================================================================} Procedure TAutoLoadPicturesAndDocumentsForm.FormClose( Sender: TObject; var Action: TCloseAction); begin CloseTablesForForm(Self); {Free up the child window and set the ClosingAForm Boolean to true so that we know to delete the tab.} Action := caFree; GlblClosingAForm := True; GlblClosingFormCaption := Caption; end; {FormClose} end.
unit IdComponent; interface uses Classes, IdAntiFreezeBase, IdBaseComponent, IdGlobal, IdStack, IdResourceStrings, SysUtils; type TIdStatus = ( hsResolving, hsConnecting, hsConnected, hsDisconnecting, hsDisconnected, hsStatusText, ftpTransfer, // These are to eliminate the TIdFTPStatus and the ftpReady, // coresponding event ftpAborted); // These can be use din the other protocols to. const IdStati: array[TIdStatus] of string = ( RSStatusResolving, RSStatusConnecting, RSStatusConnected, RSStatusDisconnecting, RSStatusDisconnected, RSStatusText, RSStatusText, RSStatusText, RSStatusText); type TIdStatusEvent = procedure(ASender: TObject; const AStatus: TIdStatus; const AStatusText: string) of object; TWorkMode = (wmRead, wmWrite); TWorkInfo = record Current: Integer; Max: Integer; Level: Integer; end; TWorkBeginEvent = procedure(Sender: TObject; AWorkMode: TWorkMode; const AWorkCountMax: Integer) of object; TWorkEndEvent = procedure(Sender: TObject; AWorkMode: TWorkMode) of object; TWorkEvent = procedure(Sender: TObject; AWorkMode: TWorkMode; const AWorkCount: Integer) of object; TIdComponent = class(TIdBaseComponent) protected FOnStatus: TIdStatusEvent; FOnWork: TWorkEvent; FOnWorkBegin: TWorkBeginEvent; FOnWorkEnd: TWorkEndEvent; FWorkInfos: array[TWorkMode] of TWorkInfo; // procedure DoStatus(AStatus: TIdStatus); overload; procedure DoStatus(AStatus: TIdStatus; const aaArgs: array of const); overload; // GetLocalName cannot be static/class method. // CBuilder doesnt handle it correctly for a prop accessor function GetLocalName: string; // property OnWork: TWorkEvent read FOnWork write FOnWork; property OnWorkBegin: TWorkBeginEvent read FOnWorkBegin write FOnWorkBegin; property OnWorkEnd: TWorkEndEvent read FOnWorkEnd write FOnWorkEnd; public procedure BeginWork(AWorkMode: TWorkMode; const ASize: Integer = 0); virtual; constructor Create(axOwner: TComponent); override; destructor Destroy; override; procedure DoWork(AWorkMode: TWorkMode; const ACount: Integer); virtual; procedure EndWork(AWorkMode: TWorkMode); virtual; // property LocalName: string read GetLocalName; published property OnStatus: TIdStatusEvent read FOnStatus write FOnStatus; end; implementation Uses SyncObjs; var GInstanceCount: Integer = 0; GStackCriticalSection: TCriticalSection; { TIdComponent } constructor TIdComponent.Create(axOwner: TComponent); begin inherited Create(axOwner); GStackCriticalSection.Acquire; try Inc(GInstanceCount); if GInstanceCount = 1 then begin GStack := TIdStack.CreateStack; end; finally GStackCriticalSection.Release; end; end; destructor TIdComponent.Destroy; begin inherited Destroy; // After inherited - do at last possible moment GStackCriticalSection.Acquire; try Dec(GInstanceCount); if GInstanceCount = 0 then begin // This CS will guarantee that during the FreeAndNil nobody will try to use // or construct GStack FreeAndNil(GStack); end; finally GStackCriticalSection.Release; end; end; procedure TIdComponent.DoStatus(AStatus: TIdStatus); begin DoStatus(AStatus, []); end; procedure TIdComponent.DoStatus(AStatus: TIdStatus; const aaArgs: array of const); begin //We do it this way because Format can sometimes cause //an AV if the variable array is blank and there is something //like a %s or %d. This is why there was sometimes an AV //in TIdFTP if assigned(OnStatus) then begin if Length(aaArgs)=0 then OnStatus(Self, AStatus, Format(IdStati[AStatus], [''])) {Do not Localize} else OnStatus(Self, AStatus, Format(IdStati[AStatus], aaArgs)); end; end; function TIdComponent.GetLocalName: string; begin Result := GStack.WSGetHostName; end; procedure TIdComponent.BeginWork(AWorkMode: TWorkMode; const ASize: Integer = 0); begin Inc(FWorkInfos[AWorkMode].Level); if FWorkInfos[AWorkMode].Level = 1 then begin FWorkInfos[AWorkMode].Max := ASize; FWorkInfos[AWorkMode].Current := 0; if assigned(OnWorkBegin) then begin OnWorkBegin(Self, AWorkMode, ASize); end; end; end; procedure TIdComponent.DoWork(AWorkMode: TWorkMode; const ACount: Integer); begin if FWorkInfos[AWorkMode].Level > 0 then begin Inc(FWorkInfos[AWorkMode].Current, ACount); if assigned(OnWork) then begin OnWork(Self, AWorkMode, FWorkInfos[AWorkMode].Current); end; end; end; procedure TIdComponent.EndWork(AWorkMode: TWorkMode); begin if FWorkInfos[AWorkMode].Level = 1 then begin if assigned(OnWorkEnd) then begin OnWorkEnd(Self, AWorkMode); end; end; Dec(FWorkInfos[AWorkMode].Level); end; initialization GStackCriticalSection := TCriticalSection.Create; finalization // Dont Free. If shutdown is from another Init section, it can cause GPF when stack // tries to access it. App will kill it off anyways, so just let it leak // FreeAndNil(GStackCriticalSection); end.
unit Controle; interface uses System.SysUtils, System.Generics.Collections, InterfaceCommandos, ComandoPadrao; type TControle= class private BotoesLigar: TList<IComandos>; BotoesDesligar: TList<IComandos>; Undo: IComandos; Padrao: TComandoPadrao; public constructor Create; procedure DefinirComandos(NumeroDoBotao: integer; Ligar, Desligar: IComandos); procedure BotaoLigarApertado(NumeroDoBotao: integer); procedure BotaoDesligarApertado(NumeroDoBotao: integer); procedure BotaoUndoApertado; destructor Destroy; override; end; implementation procedure TControle.BotaoDesligarApertado(NumeroDoBotao: integer); begin BotoesDesligar.Items[NumeroDoBotao].Executar; Undo := BotoesDesligar.Items[NumeroDoBotao]; end; { TControle } procedure TControle.BotaoLigarApertado(NumeroDoBotao: integer); begin BotoesLigar.Items[NumeroDoBotao].Executar; Undo := BotoesLigar.Items[NumeroDoBotao]; end; procedure TControle.BotaoUndoApertado; begin Undo.Desfazer; end; constructor TControle.Create; var I: Integer; begin BotoesLigar := TList<IComandos>.Create; BotoesDesligar := TList<IComandos>.Create; Padrao := TComandoPadrao.Create; for I := 0 to BotoesLigar.Count do begin BotoesLigar.Add(Padrao); BotoesDesligar.Add(Padrao); end; Undo := Padrao; end; procedure TControle.DefinirComandos(NumeroDoBotao: integer; Ligar, Desligar: IComandos); begin BotoesLigar.Insert(NumeroDoBotao, Ligar); BotoesDesligar.Insert(NumeroDoBotao, Desligar); end; destructor TControle.Destroy; begin BotoesLigar.Free; BotoesDesligar.Free; inherited; end; end.
program TP04p1; uses CRT; const MAX=100; type TProducto = record Codigo:integer; Nombre:string[30]; Precio:real; Tipo:char; end; AProductos = Array[1..MAX] of TProducto; function BuscarProductoPorCodigo(Productos:AProductos; N:integer;Buscado:integer):integer; var i:integer; begin BuscarProductoPorCodigo:=-1; i:=1; while (BuscarProductoPorCodigo = -1) and (i<=N) do begin if (Productos[i].Codigo = Buscado) then begin BuscarProductoPorCodigo:=i; end; i:=i+1; end; end; //Controla que el tipo ingresado sea correcto function CargarTipo():char; begin repeat ReadLn(CargarTipo); CargarTipo := upCase(CargarTipo); if not((CargarTipo='A')or(CargarTipo='B')or(CargarTipo='C')) then begin writeln('Tipo incorrecto, debe ser A, B o C, ingrese nuevamente'); write('->'); end; until (CargarTipo='A')or(CargarTipo='B')or(CargarTipo='C'); end; procedure CargarProductos(var Productos:AProductos;var N:integer); var i:integer; Cod:integer; begin i:=n+1; repeat Write('Ingrese el codigo del producto (0 para terminar) ->') ; readln(Cod); while (BuscarProductoPorCodigo(Productos,N,Cod)<>-1) do begin writeln('El codigo ingresado ya existe, por favor ingrese otro'); write('->'); readln(Cod); end; if (Cod<>0) then begin with productos[i] do begin Codigo:=Cod; write('Ingrese el nombre del producto ->'); readln(Nombre); write('Ingrese el precio del producto ->'); readln(Precio); write('Ingrese el tipo del producto ->'); Tipo := CargarTipo(); writeln; N:=N+1; i:=i+1; end; end; until (Cod=0); end; procedure CrearCabecera(); begin ClrScr(); Write('Codigo'); gotoxy(10,1); Write('Nombre'); gotoxy(30,1); Write('Precio'); gotoxy(40,1); Writeln('Tipo'); end; //Muestra un producto en formato tabla en la fila indicada por y procedure MostrarProductoTabla(Producto:Tproducto;y:integer); begin with Producto do begin Write(Codigo); gotoxy(10,y); Write(Nombre); gotoxy(30,y); Write(Precio:5:2); gotoxy(40,y); Writeln(Tipo); end; end; procedure MostrarProductosPorTipo(Productos:AProductos;N:integer;TipoBuscado:char); var i,PosicionEnTabla:integer; begin PosicionEnTabla:=2; CrearCabecera(); for i:=1 to N do with Productos[i] do if (Tipo=TipoBuscado) then begin MostrarProductoTabla(Productos[i],PosicionEnTabla); Inc(PosicionEnTabla); end; end; procedure Intercambiar(var X:TProducto;var Y:TProducto); var Temp:TProducto; begin Temp:=X; X:=Y; Y:=Temp; end; //metodo de seleccion procedure OrdenarProductosPorNombre(var Productos:AProductos;N:integer); Var i, j,Minimo: Integer; Begin For i := 1 To N - 1 Do Begin Minimo:=i; For J := (I + 1) To N Do If (Productos[j].Nombre < Productos[Minimo].Nombre) Then Minimo:=j; Intercambiar(Productos[i],Productos[Minimo]); End End; procedure MostrarProductosPorNombre (var Productos:AProductos;N:integer); var i:integer; begin OrdenarProductosPorNombre(Productos,N); CrearCabecera(); for i:=1 to N do MostrarProductoTabla(Productos[i],i+1); end; //metodo de insercion Procedure OrdenarProductosPorMayorPrecio(Var ListaProductos : AProductos; N : Integer); Var Top, InsersionPos:integer; Cache: TProducto; Found: Boolean; Begin For Top := 2 To N Do Begin Cache := ListaProductos[Top]; InsersionPos := Top - 1; Found := false; While (InsersionPos >= 1) And (Not Found) Do If (Cache.Precio > ListaProductos[InsersionPos].Precio) Then Begin ListaProductos[InsersionPos + 1] := ListaProductos[InsersionPos]; InsersionPos := InsersionPos - 1 End else Found := true; ListaProductos[InsersionPos + 1] := Cache; End End; procedure MostrarKProductosPorMayorPrecio (var Productos:AProductos; N:integer;K:integer); var i:integer; begin OrdenarProductosPorMayorPrecio(Productos,N); CrearCabecera(); if (k>n) then k:=n; for i:=1 to K do MostrarProductoTabla(Productos[i],i+1); end; procedure EliminarProducto(var Productos:AProductos;var N:integer; Buscado:integer); var i,Pos:integer; begin Pos:=BuscarProductoPorCodigo(Productos,N,Buscado); if (Pos<>-1) then begin for i:=Pos to N-1 do Productos[i]:=Productos[i+1]; dec(N); writeln('Producto eliminado correctamente'); end else writeln('El producto no existe'); end; procedure ModificarProducto(var Productos:AProductos;var N:integer; Buscado:integer); var Pos:integer; begin Pos:=BuscarProductoPorCodigo(Productos,N,Buscado); if (Pos<>-1) then begin with Productos[Pos] do begin writeln('Modifique el nombre (anterior:',Nombre,')'); write('->'); readln(Nombre); writeln('Modifique el precio (anterior:',Precio:4:2,')'); write('->'); readln(Precio); writeln('Modifique el tipo (anterior:',Tipo,')'); write('->'); Tipo := CargarTipo(); end; end else writeln('El producto no existe'); end; function MostrarMenu():integer; begin WriteLn('MENU'); WriteLn('1- Cargar productos'); WriteLn('2- Mostrar productos por tipo'); WriteLn('3- Mostrar productos ordenados por nombre'); WriteLn('4- Mostrar productos con mayor precio'); WriteLn('5- Eliminar un producto'); WriteLn('6- Modificar un producto'); WriteLn('0- Salir'); Write('->'); Readln(MostrarMenu); end; var ListaProductos:AProductos; N,Opcion,Cantidad,Codigo:Integer; begin N:=0; repeat ClrScr; Opcion:=MostrarMenu(); case Opcion of 1:CargarProductos(ListaProductos,N); 2: begin write('Ingrese el tipo por el que desea filtrar(A,B,C) ->'); MostrarProductosPorTipo(ListaProductos,N,CargarTipo()); end; 3:MostrarProductosPorNombre(ListaProductos,N); 4: begin write('Cuantos productos desea visualizar? ->'); readln(Cantidad); MostrarKProductosPorMayorPrecio(ListaProductos,N,Cantidad); end; 5: begin write('Ingrese el codigo del producto a eliminar ->'); ReadLn(Codigo); EliminarProducto(ListaProductos,N,Codigo); end; 6: begin write('Ingrese el codigo del producto a modificar ->'); ReadLn(Codigo); ModificarProducto(ListaProductos,N,Codigo); end; 0:writeln('Fin del programa'); else writeln('Opcion incorrecta'); end; WriteLn; write('Presione una tecla para continuar...'); ReadKey; until Opcion=0; end.
unit UnitFormAppConfig; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, System.Generics.collections, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, ComponentBaloonHintU; type EWrongInputExcpetion = class(Exception); TFormAppConfig = class(TForm) GroupBox2: TGroupBox; Panel1: TPanel; Shape1: TShape; Panel2: TPanel; ComboBoxComportProducts: TComboBox; Panel17: TPanel; Panel18: TPanel; ComboBoxComportHart: TComboBox; Panel3: TPanel; Panel4: TPanel; Shape3: TShape; CheckBox1: TCheckBox; procedure FormCreate(Sender: TObject); procedure FormDeactivate(Sender: TObject); procedure FormShow(Sender: TObject); procedure ComboBoxComportProductsChange(Sender: TObject); procedure CheckBox1Click(Sender: TObject); private { Private declarations } FhWndTip: THandle; FEnableOnEdit: boolean; procedure WMWindowPosChanged(var AMessage: TMessage); message WM_WINDOWPOSCHANGED; procedure WMEnterSizeMove(var Msg: TMessage); message WM_ENTERSIZEMOVE; procedure WMActivateApp(var AMessage: TMessage); message WM_ACTIVATEAPP; procedure ShowBalloonTip(c: TWinControl; Icon: TIconKind; Title, Text: string); function TryEditToInt(ed: TEdit): Integer; function TryEditToFloat(ed: TEdit): double; public { Public declarations } end; var FormAppConfig: TFormAppConfig; implementation {$R *.dfm} uses stringutils, services, server_data_types, comport, UnitFormModbus; procedure setupCB(cb: TComboBox; s: string); begin cb.ItemIndex := cb.Items.IndexOf(s); end; procedure TFormAppConfig.FormCreate(Sender: TObject); begin FEnableOnEdit := false; end; procedure TFormAppConfig.FormShow(Sender: TObject); var s: string; v: TAppConfig; p: TParty; begin FEnableOnEdit := false; EnumComports(ComboBoxComportProducts.Items); EnumComports(ComboBoxComportHart.Items); v := TConfigSvc.GetConfig; setupCB(ComboBoxComportProducts, v.ComportProducts); setupCB(ComboBoxComportHart, v.ComportHart); FEnableOnEdit := true; end; procedure TFormAppConfig.FormDeactivate(Sender: TObject); begin Hide; end; procedure TFormAppConfig.CheckBox1Click(Sender: TObject); begin FormModbus.Height := 51; FormModbus.Visible := CheckBox1.Checked; end; procedure TFormAppConfig.ComboBoxComportProductsChange(Sender: TObject); var v: TAppConfig; begin if not FEnableOnEdit then exit; CloseWindow(FhWndTip); try v := TConfigSvc.GetConfig; v.ComportProducts := ComboBoxComportProducts.Text; v.ComportHart := ComboBoxComporthart.Text; TConfigSvc.SetConfig(v); (Sender as TWinControl).SetFocus; except on EWrongInputExcpetion do exit; end; end; procedure TFormAppConfig.WMEnterSizeMove(var Msg: TMessage); begin CloseWindow(FhWndTip); inherited; end; procedure TFormAppConfig.WMWindowPosChanged(var AMessage: TMessage); begin CloseWindow(FhWndTip); inherited; end; procedure TFormAppConfig.WMActivateApp(var AMessage: TMessage); begin CloseWindow(FhWndTip); inherited; end; procedure TFormAppConfig.ShowBalloonTip(c: TWinControl; Icon: TIconKind; Title, Text: string); begin CloseWindow(FhWndTip); FhWndTip := ComponentBaloonHintU.ShowBalloonTip(c, Icon, Title, Text); end; function TFormAppConfig.TryEditToInt(ed: TEdit): Integer; begin if TryStrToInt(ed.Text, result) then exit(result); ShowBalloonTip(ed, TIconKind.Error, 'не допустимое значение', 'ожидалось целое число'); ed.SetFocus; raise EWrongInputExcpetion.Create(''); end; function TFormAppConfig.TryEditToFloat(ed: TEdit): double; begin if try_str_to_float(ed.Text, result) then exit(result); ShowBalloonTip(ed, TIconKind.Error, 'не допустимое значение', 'ожидалось число c плавающей точкой'); ed.SetFocus; raise EWrongInputExcpetion.Create(''); end; end.
{ girnamespaces.pas Copyright (C) 2011 Andrew Haines andrewd207@aol.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. } unit girNameSpaces; {$mode objfpc}{$H+} {$INTERFACES CORBA} interface uses Classes, DOM, girParser, girTokens, girObjects, contnrs; type TgirNeedGirFileEvent = function (AGirFile: TObject; BaseNamespaceName: String) : TXMLDocument of object; { TgirNamespace } TgirNamespace = class(IgirParser) private FCIncludeName: String; FConstants: TList; FCPackageName: String; FCPrefix: String; FDeprecatedVersion: TGirVersion; FFunctions: TList; FMaxSymbolVersion: TGirVersion; FNameSpace: String; FOnlyImplied: Boolean; FOnNeedGirFile: TgirNeedGirFileEvent; FOwner: TObject; FRequiredNameSpaces: TList; FSharedLibrary: String; FTypes: TFPHashObjectList; FUnresolvedTypes: TList; FVersion: TGirVersion; procedure SetOnNeedGirFile(AValue: TgirNeedGirFileEvent); protected function AddFuzzyType(AName: String; ACType: String): TGirBaseType; procedure HandleAlias(ANode: TDomNode); procedure HandleConstant(ANode: TDomNode); procedure HandleEnumeration(ANode: TDomNode); procedure HandleBitField(ANode: TDomNode); procedure HandleCallback(ANode: TDOMNode); procedure HandleFunction(ANode: TDOMNode); procedure HandleUnion(ANode: TDOMNode); { Some 'records' have methods these corelate to pascal 'object' GType extends this 'object' type to have a sort of vmt GObject and subclasses extend gtype and adds more vmt method entries and method entries to the instance itself. } procedure HandleRecord(ANode: TDomNode); //could be struct, object, gtype, gobject, or gobject descendant procedure HandlePlainObject(ANode: TDomNode); // is a record/object with methods but no gtype procedure HandleGType(ANode: TDomNode); // one step above plain object procedure HandleClassStruct(ANode: TDomNode); // one step above GType. Is the 'Virtual' part of an object (VMT) procedure HandleClass(ANode: TDomNode); // one step above GType. Is the object structure and it's methods. ClassStruct is like the VMT procedure HandleInterface(ANode: TDomNode); procedure AddGLibBaseTypes; public procedure AddType(AType: TGirBaseType); function LookupTypeByName(AName: String; const ACType: String; SearchOnly: Boolean = False): TGirBaseType; function ResolveFuzzyType(AFuzzyType: TgirFuzzyType): TGirBaseType; function UsesGLib: Boolean; procedure ResolveFuzzyTypes; // called after done procedure ParseNode(ANode: TDomNode); procedure ParseSubNode(ANode: TDomNode); // generally do not use outside of TgirNameSpace constructor Create(AOwner:TObject; AImpliedNamespace: String); constructor CreateFromRepositoryNode(AOwner:TObject; ANode: TDOMNode; AIncludes: TList); destructor Destroy; override; property NameSpace: String read FNameSpace; property CIncludeName: String read FCIncludeName; property CPackageName: String read FCPackageName; property CPrefix: String read FCPrefix; property RequiredNameSpaces: TList Read FRequiredNameSpaces; property SharedLibrary: String read FSharedLibrary; property Version: TGirVersion read FVersion; property OnlyImplied: Boolean read FOnlyImplied; property Owner: TObject Read FOwner; // has all types in it (records classes classstructs bitfields callbacks gtypes unions etc) does not contain consts or functions property Types: TFPHashObjectList read FTypes; property Functions: TList read FFunctions; property Constants: TList read FConstants; property UnresolvedTypes: TList read FUnresolvedTypes write FUnresolvedTypes; // exclude symbols newer than this version property MaxSymbolVersion: TGirVersion read FMaxSymbolVersion write FMaxSymbolVersion; // exclude symbols this version and older that are marked as deprecated property DeprecatedVersion: TGirVersion read FDeprecatedVersion write FDeprecatedVersion; end; { TgirNamespaces } TgirNamespaces = class(TList) private FOnNeedGirFile: TgirNeedGirFileEvent; FOwner: TObject; function GetNameSpace(AIndex: Integer): TgirNamespace; procedure SetNameSpace(AIndex: Integer; const AValue: TgirNamespace); procedure SetOnNeedGirFile(AValue: TgirNeedGirFileEvent); public constructor Create(AOwner: TObject); function FindNameSpace(AName: String; Version: String = ''): TgirNamespace; property NameSpace[AIndex: Integer]: TgirNamespace read GetNameSpace write SetNameSpace; property Owner: TObject read FOwner; property OnNeedGirFile: TgirNeedGirFileEvent read FOnNeedGirFile write SetOnNeedGirFile; end; implementation uses girErrors, SysUtils, girCTypesMapping; { TgirNamespaces } function TgirNamespaces.GetNameSpace(AIndex: Integer): TgirNamespace; begin Result := TgirNamespace(Items[AIndex]); end; procedure TgirNamespaces.SetNameSpace(AIndex: Integer; const AValue: TgirNamespace); begin Items[AIndex] := AValue; end; procedure TgirNamespaces.SetOnNeedGirFile(AValue: TgirNeedGirFileEvent); begin if FOnNeedGirFile=AValue then Exit; FOnNeedGirFile:=AValue; end; constructor TgirNamespaces.Create(AOwner: TObject); begin FOwner := AOwner; inherited Create; end; function TgirNamespaces.FindNameSpace(AName: String; Version: String=''): TgirNamespace; var i: Integer; NameSpaceSearchedFor: Boolean; Doc: TXMLDocument; begin Result := nil; NameSpaceSearchedFor := False; while Result = nil do begin for i := 0 to Count-1 do begin if NameSpace[i].NameSpace = AName then Exit(NameSpace[i]); end; if NameSpaceSearchedFor then Exit; NameSpaceSearchedFor := True; if Assigned(FOnNeedGirFile) then begin Doc := FOnNeedGirFile(Owner, AName+'-'+Version); if Doc <> nil then begin (Owner as IgirParser).ParseNode(Doc.DocumentElement); Doc.Free; end; end; end; end; { TgirNamespace } procedure TgirNamespace.ParseNode(ANode: TDomNode); begin ANode := ANode.FirstChild; while ANode <> nil do begin //girError(geDebug, 'Parsing Node "'+ANode.NodeName+'"'); ParseSubNode(ANode); ANode := ANode.NextSibling; end; ResolveFuzzyTypes; end; procedure TgirNamespace.SetOnNeedGirFile(AValue: TgirNeedGirFileEvent); begin if FOnNeedGirFile=AValue then Exit; FOnNeedGirFile:=AValue; end; function TgirNamespace.AddFuzzyType(AName: String; ACType: String ): TGirBaseType; begin Result := TgirFuzzyType.Create(Self, AName, ACType); AddType(Result); FUnresolvedTypes.Add(Result); end; procedure TgirNamespace.HandleAlias(ANode: TDomNode); var Item: TgirAlias; begin Item := TgirAlias.Create(Self, ANode); AddType(Item); end; procedure TgirNamespace.HandleConstant(ANode: TDomNode); var Item: TgirConstant; begin Item := TgirConstant.Create(Self, ANode); FConstants.Add(Item); end; procedure TgirNamespace.HandleEnumeration(ANode: TDomNode); var Item : TgirEnumeration; begin Item := TgirEnumeration.Create(Self, ANode); AddType(Item); end; procedure TgirNamespace.HandleBitField(ANode: TDomNode); var Item : TgirBitField; begin Item := TgirBitField.Create(Self, ANode); AddType(Item); end; procedure TgirNamespace.HandleCallback(ANode: TDOMNode); var Item: TgirCallback; begin Item := TgirCallback.Create(Self, ANode); AddType(Item); end; procedure TgirNamespace.HandleFunction(ANode: TDOMNode); var Item: TgirFunction; begin Item := TgirFunction.Create(Self, ANode); Functions.Add(Item); end; procedure TgirNamespace.HandleUnion(ANode: TDOMNode); var Item: TgirUnion; begin Item := TgirUnion.Create(Self, ANode); AddType(Item); end; procedure TgirNamespace.HandleRecord(ANode: TDomNode); var Item: tgirRecord; begin if TDOMElement(ANode).GetAttribute('glib:is-gtype-struct-for') <> '' then // is gobject class begin HandleClassStruct(ANode); end else if TDOMElement(ANode).GetAttribute('glib:get-type') <> '' then // is GType HandleGType(ANode) else if (ANode.FindNode('method') <> nil) or (ANode.FindNode('constructor') <> nil) or (ANode.FindNode('function') <> nil) then // is Plain object that is not gtype HandlePlainObject(ANode) else begin Item := tgirRecord.Create(Self, ANode); AddType(Item); end; end; procedure TgirNamespace.HandlePlainObject(ANode: TDomNode); var Item: TgirObject; begin Item := TgirObject.Create(Self, ANode); AddType(Item); end; procedure TgirNamespace.HandleGType(ANode: TDomNode); var Item: TgirGType; begin Item := TgirGType.Create(Self, ANode); AddType(Item); end; procedure TgirNamespace.HandleClassStruct(ANode: TDomNode); var Item: TgirClassStruct; begin Item := TgirClassStruct.Create(Self, ANode); AddType(Item); end; procedure TgirNamespace.HandleClass(ANode: TDomNode); var Item: TgirClass; begin Item := TgirClass.Create(Self, ANode); AddType(Item); end; procedure TgirNamespace.HandleInterface(ANode: TDomNode); var Item: TgirInterface; begin Item := TgirInterface.Create(Self, ANode); AddType(Item); end; procedure TgirNamespace.AddGLibBaseTypes; function AddNativeTypeDef(GType: String; PascalCName: String; TranslatedName: String): TgirNativeTypeDef; var NativeType: TgirNativeTypeDef; begin NativeType:= TgirNativeTypeDef.Create(Self, GType, PascalCName); if TranslatedName <> '' then NativeType.TranslatedName:=TranslatedName; NativeType.ImpliedPointerLevel:=3; AddType(NativeType); Result := NativeType; end; var i: Integer; begin for i := 0 to CTypesMax-1 do AddNativeTypeDef(TypesGTypes[i], TypesPascalCTypes[i], ''); end; procedure TgirNamespace.AddType(AType: TGirBaseType); var PrevFound: TGirBaseType = nil; begin PrevFound := TGirBaseType(FTypes.Find(AType.Name)); if (PrevFound <> nil) and (PrevFound.ObjectType = otFuzzyType) then begin (PrevFound as TgirFuzzyType).ResolvedType := AType; //WriteLn('Resolved FuzzyType: ', AType.Name); FUnresolvedTypes.Remove(PrevFound); end; //if PrevFound <> nil then WriteLn('Found Name Already Added: ', AType.Name, ' ', PrevFound.ObjectType, ' ', AType.ObjectType); if PrevFound = nil then FTypes.Add(AType.Name, AType); end; procedure TgirNamespace.ResolveFuzzyTypes; var i: Integer; FuzzyI: Integer; Fuzzy: TgirFuzzyType; FuzzyP: Pointer absolute Fuzzy; Tmp: TGirBaseType; StillFuzzy: TList; Current: TGirBaseType; ReqNS: TgirNamespace; begin i:= 0; FuzzyI := 0; Fuzzy := nil; StillFuzzy := TList.Create; while (i < FTypes.Count) or (Fuzzy <> nil) do begin // make our loop safe if i >= FTypes.Count then begin i := FuzzyI+1; StillFuzzy.Add(Fuzzy); Fuzzy := nil; continue; end; Tmp := TGirBaseType(FTypes.Items[i]); if Fuzzy <> nil then begin if {(Tmp.CType = Fuzzy.CType) or} (Tmp.Name = Fuzzy.Name) then begin Fuzzy.ResolvedType := Tmp; Tmp.ImpliedPointerLevel:=Fuzzy.ImpliedPointerLevel; Tmp.DeprecatedOverride:= Tmp.DeprecatedOverride or Fuzzy.DeprecatedOverride; i := FuzzyI+1; Fuzzy := nil; //WriteLn('Resolved Fuzzy Type: ', Tmp.CType); continue; end; end; if (Fuzzy = nil) and (Tmp.ObjectType = otFuzzyType) and (TgirFuzzyType(Tmp).ResolvedType = nil) then begin if i >= FTypes.Count then break; FuzzyI:=i; Fuzzy := TgirFuzzyType(Tmp); //WriteLn('Looking For: ',Fuzzy.CType); end; inc(i); end; // if the types are still fuzzy then we will search used namespaces for what we want for FuzzyP in StillFuzzy do //FuzzyP is Fuzzy absolute begin if Fuzzy.ResolvedType <> nil then continue; for i := 0 to RequiredNameSpaces.Count-1 do begin ReqNS := TgirNamespace(RequiredNameSpaces.Items[i]); Current := ReqNS.LookupTypeByName(Fuzzy.Name, '', True); if Current <> nil then begin if (Current.ObjectType = otFuzzyType) and (TgirFuzzyType(Current).ResolvedType <> nil) then Current := TgirFuzzyType(Current).ResolvedType; Fuzzy.ResolvedType := Current; Break; end; end; end; StillFuzzy.Free; end; procedure TgirNamespace.ParseSubNode(ANode: TDomNode); begin case GirTokenNameToToken(ANode.NodeName) of gtAlias: HandleAlias(ANode); gtConstant: HandleConstant(ANode); gtRecord: HandleRecord(ANode); gtBitField: HandleBitField(ANode); gtEnumeration: HandleEnumeration(ANode); gtCallback: HandleCallback(ANode); gtUnion: HandleUnion(ANode); gtFunction: HandleFunction(ANode); gtClass: HandleClass(ANode); gtInterface: HandleInterface(ANode); gtMethod: HandleFunction(ANode); else girError(geError, 'Unknown NodeType: '+ANode.NodeName); end; end; function TgirNamespace.LookupTypeByName(AName: String; const ACType: String; SearchOnly: Boolean = False): TGirBaseType; function StripPointers(ACPointeredType: String; PtrLevel: PInteger = nil): String; var i: Integer; begin for i := Length(ACPointeredType) downto 1 do if ACPointeredType[i] = '*' then begin Delete(ACPointeredType, i, 1); end; if PtrLevel <> nil then Inc(PtrLevel^); Result := ACPointeredType; end; var NS: TgirNamespace; NSString: String; FPos: Integer; PointerLevel: Integer = 0; PlainCType: String; begin Result := nil; NS := Self; // some basic fixes PlainCType:=StringReplace(StripPointers(ACType, @PointerLevel), ' ', '_', [rfReplaceAll]); if (PlainCType = 'gchar') or {(PlainCType = 'guchar') or} (PlainCType = 'char') or (PlainCType = 'const_char') then AName := 'GLib.utf8'; if (PlainCType = 'GType') {or (AName = 'Type')} or (AName = 'GType')then AName := 'GLib.Type'; if AName = 'any' then AName := 'gpointer'; FPos := Pos('.', AName); if FPos > 0 then // type includes namespace "NameSpace.Type" begin NSString:=Copy(AName,1,FPos-1); //NS := (Owner As TgirNamespaces).FindNameSpace(NSString); NS := TgirNamespaces(Owner).FindNameSpace(NSString); if NS = nil then girError(geError, 'Referenced Namespace "'+NSString+'" not found while looking for '+AName); AName := Copy(AName, FPos+1, Length(AName)); end; if NS <> Self then SearchOnly:=True; //if NS <> Self then WriteLn('Self NS = ', NameSpace, ' Lookup NS = ', NS.NameSpace); Result := TGirBaseType(NS.Types.Find(AName)); if (Result <> nil) and (Result.ObjectType = otFuzzyType) and (TgirFuzzyType(Result).ResolvedType <> nil) then Result := TgirFuzzyType(Result).ResolvedType; // if we find a result in another namespace then we need to depend on that namespace/unit if (NS <> nil) and (NS <> Self) and (Result <> nil) then if FRequiredNameSpaces.IndexOf(NS) = -1 then FRequiredNameSpaces.Add(NS); if (Result = nil) and Not SearchOnly then Result := NS.AddFuzzyType(AName, ACType); if Result <> nil then Result.ImpliedPointerLevel:=PointerLevel; end; function TgirNamespace.ResolveFuzzyType(AFuzzyType: TgirFuzzyType): TGirBaseType; var i: Integer; begin for i := 0 to FTypes.Count-1 do begin if (TGirBaseType(FTypes[i]) <> AFuzzyType) and (TGirBaseType(FTypes[i]).Name = AFuzzyType.Name) then Exit(TGirBaseType(FTypes[i])); end; end; function TgirNamespace.UsesGLib: Boolean; var Tmp: Pointer; NS: TgirNamespace absolute Tmp; begin Result := False; if Pos('glib', LowerCase(NameSpace)) = 1 then Exit(True); for Tmp in RequiredNameSpaces do if Pos('glib',LowerCase(NS.NameSpace)) = 1 then Exit(True); end; constructor TgirNamespace.Create(AOwner:TObject; AImpliedNamespace: String); begin Fowner:=AOwner; FOnlyImplied:=True; FNameSpace:=AImpliedNamespace; girError(geDebug, 'Creating Stub for namespace: '+ AImpliedNamespace); end; constructor TgirNamespace.CreateFromRepositoryNode(AOwner:TObject; ANode: TDOMNode; AIncludes: TList); procedure SetCInclude; var Child: TDomElement; begin Child := TDOMElement(ANode.FindNode('c:include name')); if (Child <> nil) and Child.InheritsFrom(TDOMElement) then FCIncludeName:= Child.GetAttribute('name'); end; procedure SetPackage; var Child: TDOMElement; begin Child := TDOMElement(ANode.FindNode('package')); if (Child <> nil) and Child.InheritsFrom(TDOMElement) then FCPackageName:=Child.GetAttribute('name'); end; var Node: TDOMElement; begin FOwner := AOwner; if ANode = nil then girError(geError, 'expected namespace got nil'); if ANode.NodeName <> 'repository' then girError(geError, 'expected "repository" got '+ANode.NodeName); Node := TDOMElement( ANode.FindNode('namespace') ); FNameSpace:=Node.GetAttribute('name'); FRequiredNameSpaces := AIncludes; FSharedLibrary:=Node.GetAttribute('shared-library'); FVersion:=girVersion(Node.GetAttribute('version')); FCPrefix:=Node.GetAttribute('c:prefix'); SetCInclude; SetPackage; girError(geDebug, Format('Creating namespace=%s Version=%s LibName=%s',[FNameSpace, FVersion.AsString, FSharedLibrary])); FConstants := TList.Create; FFunctions := TList.Create; FTypes := TFPHashObjectList.Create(True); FUnresolvedTypes := TList.Create; FMaxSymbolVersion.Major:=MaxInt; if FNameSpace = 'GLib' then AddGLibBaseTypes; end; destructor TgirNamespace.Destroy; begin FConstants.Free; FFunctions.Free; FTypes.Free; FUnresolvedTypes.Free; if Assigned(FRequiredNameSpaces) then FRequiredNameSpaces.Free; inherited Destroy; end; end.
unit Ths.Erp.Database.TableDetailed; interface {$I ThsERP.inc} uses Forms, SysUtils, Classes, Dialogs, WinSock, System.Rtti, System.UITypes, StrUtils, FireDAC.Stan.Param, Data.DB, FireDAC.Comp.Client, FireDAC.Stan.Error, Ths.Erp.Database, Ths.Erp.Database.Table; type {$M+} TTableDetailed = class(TTable) private protected FListDetay: TList; FListSilinenDetay: TList; procedure RefreshHeader();virtual;abstract; function ValidateDetay(pTable: TTable): boolean; virtual; abstract; published property ListDetay: TList read FListDetay write FListDetay; property ListSilinenDetay: TList read FListSilinenDetay write FListSilinenDetay; constructor Create(pOwnerDatabase: TDatabase); override; destructor Destroy(); override; procedure FreeDetayListContent(); virtual; public procedure CloneDetayLists(pTableDetailed: TTableDetailed); procedure AddDetay(pTable: TTable); virtual; abstract; procedure UpdateDetay(pTable: TTable); virtual; abstract; procedure RemoveDetay(pTable: TTable); virtual; abstract; end; implementation { TTableDetailed } procedure TTableDetailed.CloneDetayLists(pTableDetailed: TTableDetailed); var n1: Integer; begin for n1 := 0 to ListDetay.Count -1 do pTableDetailed.ListDetay.Add(TTable(Self.ListDetay[n1]).Clone()); for n1 := 0 to ListSilinenDetay.Count -1 do pTableDetailed.ListSilinenDetay.Add(TTable(Self.ListSilinenDetay[n1]).Clone()); end; constructor TTableDetailed.Create(pOwnerDatabase: TDatabase); begin inherited; ListDetay := TList.Create(); ListDetay.Clear(); ListSilinenDetay := TList.Create(); ListSilinenDetay.Clear(); end; destructor TTableDetailed.Destroy; begin FreeDetayListContent(); if Assigned(ListDetay) then ListDetay.Free; if Assigned(ListSilinenDetay) then ListSilinenDetay.Free; inherited; end; procedure TTableDetailed.FreeDetayListContent; var n1: Integer; begin if Assigned(ListDetay) then for n1 := 0 to ListDetay.Count-1 do TTable(ListDetay[n1]).Free; ListDetay.Clear; if Assigned(ListSilinenDetay) then for n1 := 0 to ListSilinenDetay.Count-1 do TTable(ListSilinenDetay[n1]).Free; ListSilinenDetay.Clear; end; end.
{*******************************************************} { } { Delphi DBX Framework } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$HPPEMIT LINKUNIT} unit Data.DbxDb2; interface uses Data.DBXDynalink, Data.DBXDynalinkNative, Data.DBXCommon, Data.DbxDb2ReadOnlyMetaData, Data.DbxDb2MetaData; type TDBXDb2Properties = class(TDBXProperties) strict private const StrDb2TransIsolation = 'Db2 TransIsolation'; const StrDecimalSeparator = 'Decimal Separator'; function GetHostName: string; function GetPassword: string; function GetUserName: string; function GetBlobSize: Integer; function GetDatabase: string; function GetDB2TransIsolation: string; function GetDecimalSeparator: string; procedure SetBlobSize(const Value: Integer); procedure SetDatabase(const Value: string); procedure SetDB2TransIsolation(const Value: string); procedure SetDecimalSeparator(const Value: string); procedure SetHostName(const Value: string); procedure SetPassword(const Value: string); procedure SetUserName(const Value: string); public constructor Create(DBXContext: TDBXContext); override; published property HostName: string read GetHostName write SetHostName; property UserName: string read GetUserName write SetUserName; property Password: string read GetPassword write SetPassword; property Database: string read GetDatabase write SetDatabase; property BlobSize: Integer read GetBlobSize write SetBlobSize; property DB2TransIsolation:string read GetDB2TransIsolation write SetDB2TransIsolation; property DecimalSeparator: string read GetDecimalSeparator write SetDecimalSeparator; end; TDBXDb2Driver = class(TDBXDynalinkDriverNative) public constructor Create(DBXDriverDef: TDBXDriverDef); override; end; implementation uses Data.DBXCommonResStrs, Data.DBXPlatform, System.SysUtils; const sDriverName = 'Db2'; { TDBXDb2Driver } constructor TDBXDb2Driver.Create(DBXDriverDef: TDBXDriverDef); var Props: TDBXDb2Properties; I, Index: Integer; begin Props := TDBXDb2Properties.Create(DBXDriverDef.FDBXContext); if DBXDriverDef.FDriverProperties <> nil then begin for I := 0 to DBXDriverDef.FDriverProperties.Count - 1 do begin Index := Props.Properties.IndexOfName(DBXDriverDef.FDriverProperties.Properties.Names[I]); if Index > -1 then Props.Properties.Strings[Index] := DBXDriverDef.FDriverProperties.Properties.Strings[I]; end; Props.AddUniqueProperties(DBXDriverDef.FDriverProperties.Properties); DBXDriverDef.FDriverProperties.AddUniqueProperties(Props.Properties); end; inherited Create(DBXDriverDef, TDBXDynalinkDriverLoader, Props); rcs; end; { TDBXDb2Properties } constructor TDBXDb2Properties.Create(DBXContext: TDBXContext); begin inherited Create(DBXContext); Values[TDBXPropertyNames.DriverUnit] := 'Data.DBXDb2'; Values[TDBXPropertyNames.DriverPackageLoader] := 'TDBXDynalinkDriverLoader,DBXDb2Driver' + PackageVersion + '.bpl'; Values[TDBXPropertyNames.DriverAssemblyLoader] := 'Borland.Data.TDBXDynalinkDriverLoader,Borland.Data.DbxCommonDriver,Version=' + AssemblyVersion + ',Culture=neutral,PublicKeyToken=' + TDBXPlatform.GetPublicKeyToken; Values[TDBXPropertyNames.MetaDataPackageLoader] := 'TDBXDb2MetaDataCommandFactory,DBXDb2Driver' + PackageVersion + '.bpl'; Values[TDBXPropertyNames.MetaDataAssemblyLoader] := 'Borland.Data.TDBXDb2MetaDataCommandFactory,Borland.Data.DbxDb2Driver,Version=' + AssemblyVersion + ',Culture=neutral,PublicKeyToken=' + TDBXPlatform.GetPublicKeyToken; Values[TDBXPropertyNames.GetDriverFunc] := 'getSQLDriverDB2'; Values[TDBXPropertyNames.LibraryName] := 'dbxdb2.dll'; Values[TDBXPropertyNames.VendorLib] := 'db2cli.dll'; Values[TDBXPropertyNames.VendorLibWin64] := 'db2cli64.dll'; Values[TDBXPropertyNames.Database] := 'DBNAME'; Values[TDBXPropertyNames.UserName] := 'user'; Values[TDBXPropertyNames.Password] := 'password'; Values[TDBXPropertyNames.MaxBlobSize] := '-1'; Values[TDBXPropertyNames.ErrorResourceFile] := ''; Values[TDBXDynalinkPropertyNames.LocaleCode] := '0000'; Values[TDBXPropertyNames.IsolationLevel] := 'ReadCommitted'; end; function TDBXDb2Properties.GetBlobSize: Integer; begin Result := StrToIntDef(Values[TDBXPropertyNames.MaxBlobSize], -1); end; function TDBXDb2Properties.GetDatabase: string; begin Result := Values[TDBXPropertyNames.Database]; end; function TDBXDb2Properties.GetDB2TransIsolation: string; begin Result := Values[StrDb2TransIsolation]; end; function TDBXDb2Properties.GetDecimalSeparator: string; begin Result := Values[StrDecimalSeparator]; end; function TDBXDb2Properties.GetHostName: string; begin Result := Values[TDBXPropertyNames.HostName]; end; function TDBXDb2Properties.GetPassword: string; begin Result := Values[TDBXPropertyNames.Password]; end; function TDBXDb2Properties.GetUserName: string; begin Result := Values[TDBXPropertyNames.UserName]; end; procedure TDBXDb2Properties.SetBlobSize(const Value: Integer); begin Values[TDBXPropertyNames.MaxBlobSize] := IntToStr(Value); end; procedure TDBXDb2Properties.SetDatabase(const Value: string); begin Values[TDBXPropertyNames.Database] := Value; end; procedure TDBXDb2Properties.SetDB2TransIsolation(const Value: string); begin Values[StrDb2Transisolation] := Value; end; procedure TDBXDb2Properties.SetDecimalSeparator(const Value: string); begin Values[StrDecimalSeparator] := Value; end; procedure TDBXDb2Properties.SetHostName(const Value: string); begin Values[TDBXPropertyNames.HostName] := Value; end; procedure TDBXDb2Properties.SetPassword(const Value: string); begin Values[TDBXPropertyNames.Password] := Value; end; procedure TDBXDb2Properties.SetUserName(const Value: string); begin Values[TDBXPropertyNames.UserName] := Value; end; initialization TDBXDriverRegistry.RegisterDriverClass(sDriverName, TDBXDb2Driver); finalization TDBXDriverRegistry.UnloadDriver(sDriverName); end.
unit DescriptionTypesQuery; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls, DragHelper, OrderQuery, DSWrap; type TDescriptionTypeW = class(TOrderW) private FComponentName: TParamWrap; FComponentType: TFieldWrap; FID: TFieldWrap; public constructor Create(AOwner: TComponent); override; procedure AddNewValue(const AValue: string); procedure LocateOrAppend(AValue: string); property ComponentName: TParamWrap read FComponentName; property ComponentType: TFieldWrap read FComponentType; property ID: TFieldWrap read FID; end; TQueryDescriptionTypes = class(TQueryOrder) FDUpdateSQL: TFDUpdateSQL; private FFilterText: string; FShowDuplicate: Boolean; FW: TDescriptionTypeW; procedure ApplyFilter(AShowDuplicate: Boolean; const AFilterText: string); { Private declarations } protected function CreateDSWrap: TDSWrap; override; public constructor Create(AOwner: TComponent); override; function TryApplyFilter(AShowDuplicate: Boolean; const AFilterText: string): Boolean; property FilterText: string read FFilterText; property ShowDuplicate: Boolean read FShowDuplicate; property W: TDescriptionTypeW read FW; { Public declarations } end; implementation {$R *.dfm} uses StrHelper, RepositoryDataModule, NotifyEvents; constructor TQueryDescriptionTypes.Create(AOwner: TComponent); begin inherited; FW := FDSWrap as TDescriptionTypeW; AutoTransaction := False; end; procedure TQueryDescriptionTypes.ApplyFilter(AShowDuplicate: Boolean; const AFilterText: string); var ASQL: String; begin // Получаем первоначальный запрос ASQL := SQL; // Если нужно показать дубликаты if AShowDuplicate then begin ASQL := ASQL.Replace('/* ShowDuplicate', '', [rfReplaceAll]); ASQL := ASQL.Replace('ShowDuplicate */', '', [rfReplaceAll]); end; // Если нужно показать отфильтровать по названию компонента if not AFilterText.IsEmpty then begin ASQL := ASQL.Replace('/* Filter', '', [rfReplaceAll]); ASQL := ASQL.Replace('Filter */', '', [rfReplaceAll]); end; FDQuery.Close; FDQuery.SQL.Text := ASQL; if not AFilterText.IsEmpty then begin SetParamType(W.ComponentName.FieldName, ptInput, ftWideString); SetParameters([W.ComponentName.FieldName], [AFilterText + '%']); end; FDQuery.Open; end; function TQueryDescriptionTypes.TryApplyFilter(AShowDuplicate: Boolean; const AFilterText: string): Boolean; begin Result := FDQuery.RecordCount > 0; if (AShowDuplicate = FShowDuplicate) and (AFilterText = FFilterText) then Exit; ApplyFilter(AShowDuplicate, AFilterText); Result := FDQuery.RecordCount > 0; if Result then begin FShowDuplicate := AShowDuplicate; FFilterText := AFilterText; end else // Возвращаем старые значения ApplyFilter(FShowDuplicate, FFilterText); end; function TQueryDescriptionTypes.CreateDSWrap: TDSWrap; begin Result := TDescriptionTypeW.Create(FDQuery); end; constructor TDescriptionTypeW.Create(AOwner: TComponent); begin inherited; FID := TFieldWrap.Create(Self, 'ID', '', True); FOrd := TFieldWrap.Create(Self, 'Ord'); FComponentType := TFieldWrap.Create(Self, 'ComponentType', 'Тип компонентов'); FComponentName := TParamWrap.Create(Self, 'ComponentName'); end; procedure TDescriptionTypeW.AddNewValue(const AValue: string); begin TryAppend; ComponentType.F.AsString := AValue; TryPost; end; procedure TDescriptionTypeW.LocateOrAppend(AValue: string); var OK: Boolean; begin Assert(not AValue.IsEmpty); OK := FDDataSet.LocateEx(ComponentType.FieldName, AValue, []); if not OK then AddNewValue(AValue); end; end.
unit WkeJs; interface uses SysUtils, Classes, WkeTypes, WkeHash, WkeIntf; type TWkeJsExecState = class(TInterfacedObject, IWkeJsExecState) private FExecState: jsExecState; FGlobalObject: IWkeJsValue; FData1: Pointer; FData2: Pointer; private function GetWebView: TWebView; function GetProp(const AProp: WideString): IWkeJsValue; function GetExecState: jsExecState; function GetArg(const argIdx: Integer): IWkeJsValue; function GetArgCount: Integer; function GetArgType(const argIdx: Integer): jsType; function GetGlobalObject: IWkeJsValue; function GetData1: Pointer; function GetData2: Pointer; procedure SetProp(const AProp: WideString; const Value: IWkeJsValue); procedure SetData1(const Value: Pointer); procedure SetData2(const Value: Pointer); public constructor Create(const AExecState: JsExecState); overload; destructor Destroy; override; function jsInt(n: Integer): IWkeJsValue; function jsFloat(n: float): IWkeJsValue; function jsDouble(n: Double): IWkeJsValue; function jsBoolean(n: Boolean): IWkeJsValue; function jsUndefined(): IWkeJsValue; function jsNull(): IWkeJsValue; function jsTrue(): IWkeJsValue; function jsFalse(): IWkeJsValue; function jsString(const str: PUtf8): IWkeJsValue; function jsStringW(const str: Pwchar_t): IWkeJsValue; function jsObject(): IWkeJsValue; function jsArray(): IWkeJsValue; function jsFunction(fn: jsNativeFunction; argCount: Integer): IWkeJsValue; function Eval(const str: PUtf8): IWkeJsValue; function EvalW(const str: Pwchar_t): IWkeJsValue; function CallGlobal(func: jsValue; args: array of OleVariant): OleVariant; overload; function CallGlobal(const func: WideString; args: array of OleVariant): OleVariant; overload; function CallGlobalEx(func: jsValue; args: array of IWkeJsValue): IWkeJsValue; overload; function CallGlobalEx(const func: WideString; args: array of IWkeJsValue): IWkeJsValue; overload; function PropExist(const AProp: WideString): Boolean; procedure BindFunction(const name: WideString; fn: jsNativeFunction; argCount: Integer); procedure UnbindFunction(const name: WideString); procedure BindObject(const objName: WideString; obj: TObject); procedure UnbindObject(const objName: WideString); function CreateJsObject(obj: TObject): jsValue; property ExecState: jsExecState read GetExecState; //return the window object property GlobalObject: IWkeJsValue read GetGlobalObject; property Prop[const AProp: WideString]: IWkeJsValue read GetProp write SetProp; property ArgCount: Integer read GetArgCount; property ArgType[const argIdx: Integer]: jsType read GetArgType; property Arg[const argIdx: Integer]: IWkeJsValue read GetArg; property Data1: Pointer read GetData1 write SetData1; property Data2: Pointer read GetData2 write SetData2; property WebView: TWebView read GetWebView; end; TWkeJsValue = class(TInterfacedObject, IWkeJsValue) private FExecState: jsExecState; FValue: jsValue; FData1: Pointer; FData2: Pointer; private function GetExecState: jsExecState; function GetValue: jsValue; function GetValueType: jsType; function GetData1: Pointer; function GetData2: Pointer; procedure SetData1(const Value: Pointer); procedure SetData2(const Value: Pointer); public constructor Create(const AExecState: JsExecState); overload; constructor Create(const AExecState: JsExecState; const AValue: jsValue); overload; destructor Destroy; override; function IsNumber: Boolean; function IsString: Boolean; function IsBoolean: Boolean; function IsObject: Boolean; function IsFunction: Boolean; function IsUndefined: Boolean; function IsNull: Boolean; function IsArray: Boolean; function IsTrue: Boolean; function IsFalse: Boolean; function ToInt: Integer; function ToFloat: float; function ToDouble: Double; function ToBoolean: Boolean; function ToStringA: PUtf8; function ToStringW: Pwchar_t; function ToObject: IWkeJsObject; procedure SetAsInt(n: Integer); procedure SetAsFloat(n: float); procedure SetAsDouble(n: Double); procedure SetAsBoolean(n: Boolean); procedure SetAsUndefined(); procedure SetAsNull(); procedure SetAsTrue(); procedure SetAsFalse(); procedure SetAsString(const str: PUtf8); procedure SetAsStringW(const str: Pwchar_t); procedure SetAsObject(v: jsValue); procedure SetAsArray(v: jsValue); procedure SetAsFunction(fn: jsNativeFunction; argCount: Integer); property ExecState: jsExecState read GetExecState; property Value: jsValue read GetValue; property ValueType: jsType read GetValueType; property Data1: Pointer read GetData1 write SetData1; property Data2: Pointer read GetData2 write SetData2; end; TWkeJsObject = class(TWkeJsValue, IWkeJsObject) private function GetProp(const AName: WideString): IWkeJsValue; function GetPropAt(const AIndex: Integer): IWkeJsValue; function GetLength: Integer; procedure SetProp(const AName: WideString; const Value: IWkeJsValue); procedure SetPropAt(const AIndex: Integer; const Value: IWkeJsValue); procedure SetLength(const Value: Integer); public function Call(func: jsValue; args: array of OleVariant): OleVariant; overload; function Call(const func: WideString; args: array of OleVariant): OleVariant; overload; function CallEx(func: jsValue; args: array of IWkeJsValue): IWkeJsValue; overload; function CallEx(const func: WideString; args: array of IWkeJsValue): IWkeJsValue; overload; function PropExist(const AProp: WideString): Boolean; property Length: Integer read GetLength write SetLength; property Prop[const AName: WideString]: IWkeJsValue read GetProp write SetProp; property PropAt[const AIndex: Integer]: IWkeJsValue read GetPropAt write SetPropAt; end; PMethod = ^TMethod; TWkeJsObjectRegInfo = class(TInterfaceList, IWkeJsObjectRegInfo) private FName: WideString; FValue: TObject; protected function GetName: WideString; function GetValue: TObject; procedure SetName(const Value: WideString); procedure SetValue(const Value: TObject); public constructor Create(const AName: WideString; const AValue: TObject); property Name: WideString read GetName write SetName; property Value: TObject read GetValue write SetValue; end; TWkeJsObjectList = class(TInterfacedObject, IWkeJsObjectList) private FList: IInterfaceList; FNotifyList: TList; FNameHash: TStringHash; FNameHashValid: Boolean; FData1: Pointer; FData2: Pointer; protected function GetCount: Integer; function GetItem(const Index: Integer): IWkeJsObjectRegInfo; function GetItemName(const Index: Integer): WideString; function GetItemByName(const AName: WideString): IWkeJsObjectRegInfo; function GetData1: Pointer; function GetData2: Pointer; procedure SetItem(const Index: Integer; const Value: IWkeJsObjectRegInfo); procedure SetItemByName(const AName: WideString; const Value: IWkeJsObjectRegInfo); procedure SetData1(const Value: Pointer); procedure SetData2(const Value: Pointer); protected procedure UpdateNameHash; procedure DoNotify(const AInfo: IWkeJsObjectRegInfo; Action: TWkeJsObjectAction); public constructor Create; destructor Destroy; override; procedure Invalidate; function Reg(const AName: WideString; const AItem: TObject): Integer; procedure UnReg(const Index: Integer); overload; procedure UnReg(const AName: WideString); overload; procedure Clear; function IndexOf(const AItem: TObject): Integer; function IndexOfName(const AName: WideString): Integer; function AddListener(const AListener: TWkeJsObjectListener): Integer; function RemoveListener(const AListener: TWkeJsObjectListener): Integer; property Count: Integer read GetCount; property Item[const Index: Integer]: IWkeJsObjectRegInfo read GetItem write SetItem; default; property ItemName[const Index: Integer]: WideString read GetItemName; property ItemByName[const AName: WideString]: IWkeJsObjectRegInfo read GetItemByName write SetItemByName; property Data1: Pointer read GetData1 write SetData1; property Data2: Pointer read GetData2 write SetData2; end; TWkeJs = class(TInterfacedObject, IWkeJs) private FWebView: TWebView; FGlobalExec: IWkeJsExecState; FData1: Pointer; FData2: Pointer; private function GetGlobalExec: IWkeJsExecState; function GetData1: Pointer; function GetData2: Pointer; procedure SetData1(const Value: Pointer); procedure SetData2(const Value: Pointer); public constructor Create(AWebView: TWebView); destructor Destroy; override; procedure BindFunction(const name: WideString; fn: jsNativeFunction; argCount: Integer); procedure UnbindFunction(const name: WideString); procedure BindObject(const objName: WideString; obj: TObject); procedure UnbindObject(const objName: WideString); procedure BindGetter(const name: WideString; fn: jsNativeFunction); procedure BindSetter(const name: WideString; fn: jsNativeFunction); function CreateJsObject(obj: TObject): jsValue; procedure GC(); property GlobalExec: IWkeJsExecState read GetGlobalExec; property Data1: Pointer read GetData1 write SetData1; property Data2: Pointer read GetData2 write SetData2; end; implementation uses WkeApi, Variants; { TJsExecState } function TWkeJsExecState.CallGlobal(func: jsValue; args: array of OleVariant): OleVariant; var LArgs: JsValueArray; i, cArgs: Integer; jValue, jR: jsValue; sError: string; begin cArgs := Length(args); SetLength(LArgs, cArgs); for i := 0 to High(args) do begin if not V2J(FExecState, args[i].Value, jValue, sError) then begin if sError <> '' then sError := Format('第%d个参数转换失败:%s', [i+1, sError]) else sError := Format('第%d个参数转换失败!', [i+1]); raise EWkeException.Create(sError); end; LArgs[i] := jValue; end; jR := WAPI.jsCallGlobal(FExecState, func, @LArgs, cArgs); if WAPI.jsIsUndefined(jR) then begin Result := Unassigned; end else begin if not J2V(FExecState, jR, Result, sError) then begin if sError <> '' then sError := Format('返回值转换失败:%s', [sError]) else sError := Format('返回值转换失败!', []); raise EWkeException.Create(sError); end; end; end; function TWkeJsExecState.CallGlobalEx(func: jsValue; args: array of IWkeJsValue): IWkeJsValue; var LArgs: JsValueArray; i, cArgs: Integer; begin cArgs := Length(args); SetLength(LArgs, cArgs); for i := 0 to High(args) do LArgs[i] := args[i].Value; Result := TWkeJsValue.Create(FExecState, WAPI.jsCallGlobal(FExecState, func, @LArgs, cArgs) ); end; function TWkeJsExecState.CallGlobalEx(const func: WideString; args: array of IWkeJsValue): IWkeJsValue; var v: IWkeJsValue; begin v := GetProp(func); if not v.IsFunction then raise EWkeException.CreateFmt('脚本中,[%s]函数不存在,或它不是函数!', [func]); Result := CallGlobalEx(v.Value, args); end; constructor TWkeJsExecState.Create(const AExecState: JsExecState); begin FExecState := AExecState; end; destructor TWkeJsExecState.Destroy; begin FGlobalObject := nil; inherited; end; function TWkeJsExecState.Eval(const str: PUtf8): IWkeJsValue; begin Result := TWkeJsValue.Create(FExecState, WAPI.jsEval(FExecState, str) ); end; function TWkeJsExecState.EvalW(const str: Pwchar_t): IWkeJsValue; begin Result := TWkeJsValue.Create(FExecState, WAPI.jsEvalW(FExecState, str) ); end; function TWkeJsExecState.GetArg(const argIdx: Integer): IWkeJsValue ; begin Result := TWkeJsValue.Create(FExecState, WAPI.jsArg(FExecState, argIdx)); end; function TWkeJsExecState.GetArgCount: Integer; begin Result := WAPI.jsArgCount(FExecState); end; function TWkeJsExecState.GetArgType(const argIdx: Integer): jsType; begin Result := WAPI.jsArgType(FExecState, argIdx); end; function TWkeJsExecState.GetExecState: jsExecState; begin Result := FExecState; end; { TWkeJsValue } constructor TWkeJsValue.Create(const AExecState: JsExecState); begin FExecState := AExecState; FValue := WAPI.jsUndefined; end; constructor TWkeJsValue.Create(const AExecState: JsExecState; const AValue: jsValue); begin FExecState := AExecState; FValue := AValue; end; destructor TWkeJsValue.Destroy; begin inherited; end; function TWkeJsValue.GetData1: Pointer; begin Result := FData1; end; function TWkeJsValue.GetData2: Pointer; begin Result := FData2; end; function TWkeJsValue.GetExecState: jsExecState; begin Result := FExecState; end; function TWkeJsValue.GetValue: jsValue; begin Result := FValue; end; function TWkeJsValue.GetValueType: jsType; begin Result := WAPI.jsTypeOf(FValue); end; function TWkeJsValue.IsArray: Boolean; begin Result := WAPI.jsIsArray(FValue); end; function TWkeJsValue.IsBoolean: Boolean; begin Result := WAPI.jsIsBoolean(FValue); end; function TWkeJsValue.IsFalse: Boolean; begin Result := WAPI.jsIsFalse(FValue); end; function TWkeJsValue.IsFunction: Boolean; begin Result := WAPI.jsIsFunction(FValue); end; function TWkeJsValue.IsNull: Boolean; begin Result := WAPI.jsIsNull(FValue); end; function TWkeJsValue.IsNumber: Boolean; begin Result := WAPI.jsIsNumber(FValue); end; function TWkeJsValue.IsObject: Boolean; begin Result := WAPI.jsIsObject(FValue); end; function TWkeJsValue.IsString: Boolean; begin Result := WAPI.jsIsString(FValue); end; function TWkeJsValue.IsTrue: Boolean; begin Result := WAPI.jsIsNull(FValue); end; function TWkeJsValue.IsUndefined: Boolean; begin Result := WAPI.jsIsUndefined(FValue); end; procedure TWkeJsValue.SetAsArray(v: jsValue); begin FValue := v; end; procedure TWkeJsValue.SetAsBoolean(n: Boolean); begin FValue := WAPI.jsBoolean(n); end; procedure TWkeJsValue.SetAsDouble(n: Double); begin FValue := WAPI.jsDouble(n); end; procedure TWkeJsValue.SetAsFalse; begin FValue := WAPI.jsFalse; end; procedure TWkeJsValue.SetAsFloat(n: float); begin FValue := WAPI.jsFloat(n); end; procedure TWkeJsValue.SetAsFunction(fn: jsNativeFunction; argCount: Integer); begin FValue := WAPI.jsFunction(FExecState, fn, argCount); end; procedure TWkeJsValue.SetAsInt(n: Integer); begin FValue := WAPI.jsInt(n); end; procedure TWkeJsValue.SetAsNull; begin FValue := WAPI.jsNull; end; procedure TWkeJsValue.SetAsObject(v: jsValue); begin FValue := v; end; procedure TWkeJsValue.SetAsString(const str: PUtf8); begin FValue := WAPI.jsString(FExecState, str); end; procedure TWkeJsValue.SetAsStringW(const str: Pwchar_t); begin FValue := WAPI.jsStringW(FExecState, str); end; procedure TWkeJsValue.SetAsTrue; begin FValue := WAPI.jsTrue; end; procedure TWkeJsValue.SetAsUndefined; begin FValue := WAPI.jsUndefined; end; procedure TWkeJsValue.SetData1(const Value: Pointer); begin FData1 := Value; end; procedure TWkeJsValue.SetData2(const Value: Pointer); begin FData2 := Value; end; function TWkeJsValue.ToBoolean: Boolean; begin Result := WAPI.jsToBoolean(FExecState, FValue); end; function TWkeJsValue.ToDouble: Double; begin Result := WAPI.jsToDouble(FExecState, FValue); end; function TWkeJsValue.ToFloat: float; begin Result := WAPI.jsToFloat(FExecState, FValue); end; function TWkeJsValue.ToInt: Integer; begin Result := WAPI.jsToInt(FExecState, FValue); end; function TWkeJsValue.ToObject: IWkeJsObject; begin Assert(GetValueType = JSTYPE_OBJECT); Result := TWkeJsObject.Create(FExecState, FValue); end; function TWkeJsValue.ToStringA: PUtf8; begin Result := WAPI.jsToTempString(FExecState, FValue); end; function TWkeJsValue.ToStringW: Pwchar_t; begin Result := WAPI.jsToTempStringW(FExecState, FValue); end; { TTiscriptObjectList } function TWkeJsObjectList.Reg(const AName: WideString; const AItem: TObject): Integer; var i: Integer; LInfo: IWkeJsObjectRegInfo; begin i := IndexOfName(AName); LInfo := TWkeJsObjectRegInfo.Create(AName, AItem); if i < 0 then begin Result := FList.Add(LInfo); FNameHash.Add(AnsiUpperCase(AName), Result); DoNotify(LInfo, woaReg); end else begin SetItem(i, LInfo); Result := i; end; end; procedure TWkeJsObjectList.Clear; var i: Integer; begin if FList = nil then Exit; for i := FList.Count - 1 downto 0 do DoNotify(GetItem(i), woaUnreg); FList.Clear; FNameHashValid := False; end; constructor TWkeJsObjectList.Create; begin FList := TInterfaceList.Create; FNameHash := TStringHash.Create(1024); FNotifyList := TList.Create; end; procedure TWkeJsObjectList.UnReg(const Index: Integer); begin DoNotify(GetItem(Index), woaUnreg); FList.Delete(Index); FNameHashValid := False; end; procedure TWkeJsObjectList.UnReg(const AName: WideString); var i: Integer; begin i := IndexOfName(AName); if i >= 0 then UnReg(i); end; destructor TWkeJsObjectList.Destroy; var i: Integer; begin if FList <> nil then begin Clear; FList := nil; end; if FNotifyList <> nil then begin for i := 0 to FNotifyList.Count - 1 do Dispose(PMethod(FNotifyList[i])); FreeAndNil(FNotifyList); end; if FNameHash <> nil then FreeAndNil(FNameHash); inherited; end; function TWkeJsObjectList.GetCount: Integer; begin Result := FList.Count; end; function TWkeJsObjectList.GetItem(const Index: Integer): IWkeJsObjectRegInfo; begin Result := FList[index] as IWkeJsObjectRegInfo; end; function TWkeJsObjectList.GetItemByName( const AName: WideString): IWkeJsObjectRegInfo; var i: Integer; begin i := IndexOfName(AName); if i >= 0 then Result := GetItem(i) else Result := nil; end; function TWkeJsObjectList.IndexOf(const AItem: TObject): Integer; begin for Result := 0 to FList.Count - 1 do begin if GetItem(Result).Value = AItem then Exit; end; Result := -1; end; function TWkeJsObjectList.IndexOfName(const AName: WideString): Integer; begin UpdateNameHash; Result := FNameHash.ValueOf(AnsiUpperCase(AName)); end; procedure TWkeJsObjectList.Invalidate; begin FNameHashValid := False; end; procedure TWkeJsObjectList.SetItemByName(const AName: WideString; const Value: IWkeJsObjectRegInfo); var i: Integer; begin i := IndexOfName(AName); if i >= 0 then SetItem(i, Value); end; procedure TWkeJsObjectList.UpdateNameHash; var I: Integer; Key: string; begin if FNameHashValid then Exit; FNameHash.Clear; for I := 0 to Count - 1 do begin Key := AnsiUpperCase(GetItem(i).Name); FNameHash.Add(Key, I); end; FNameHashValid := True; end; procedure TWkeJsObjectList.SetItem(const Index: Integer; const Value: IWkeJsObjectRegInfo); begin Assert(GetItem(Index).Name = Value.Name); FList[Index] := Value; DoNotify(Value, woaChanged); end; function TWkeJsObjectList.GetItemName(const Index: Integer): WideString; begin Result := GetItem(index).Name; end; { TWkeJs } procedure TWkeJs.BindFunction(const name: WideString; fn: jsNativeFunction; argCount: Integer); begin GlobalExec.BindFunction(name, fn, argCount); end; procedure TWkeJs.BindGetter(const name: WideString; fn: jsNativeFunction); begin WAPI.jsBindGetter(PAnsiChar(AnsiString(name)), fn); end; procedure TWkeJs.BindObject(const objName: WideString; obj: TObject); begin GlobalExec.BindObject(objName, obj); end; procedure TWkeJs.BindSetter(const name: WideString; fn: jsNativeFunction); begin WAPI.jsBindSetter(PAnsiChar(AnsiString(name)), fn); end; constructor TWkeJs.Create(AWebView: TWebView); begin FWebView := AWebView; FGlobalExec := TWkeJsExecState.Create(WAPI.wkeGlobalExec(FWebView)); end; function TWkeJs.CreateJsObject(obj: TObject): jsValue; begin Result := GlobalExec.CreateJsObject(obj) end; destructor TWkeJs.Destroy; begin FGlobalExec := nil; inherited; end; procedure TWkeJs.GC; begin WAPI.jsGC(); end; function TWkeJs.GetData1: Pointer; begin Result := FData1; end; function TWkeJs.GetData2: Pointer; begin Result := FData2; end; function TWkeJs.GetGlobalExec: IWkeJsExecState; begin Result := FGlobalExec; end; function TWkeJsExecState.GetProp(const AProp: WideString): IWkeJsValue; begin Result := TWkeJsValue.Create(FExecState, WAPI.jsGetGlobal(FExecState, PAnsiChar(AnsiString(AProp))) ); end; function TWkeJsExecState.GetGlobalObject: IWkeJsValue; begin if FGlobalObject = nil then FGlobalObject := TWkeJsValue.Create(FExecState, WAPI.jsGlobalObject(FExecState)); Result := FGlobalObject; end; function TWkeJsExecState.PropExist(const AProp: WideString): Boolean; var v: jsValue; begin v := WAPI.jsGetGlobal(FExecState, PAnsiChar(AnsiString(AProp))); Result := not WAPI.jsIsUndefined(v); end; function TWkeJsExecState.jsArray: IWkeJsValue; begin Result := TWkeJsValue.Create(FExecState, WAPI.jsEmptyArray(FExecState)); end; function TWkeJsExecState.jsBoolean(n: Boolean): IWkeJsValue; begin Result := TWkeJsValue.Create(FExecState, WAPI.jsBoolean(n)); end; function TWkeJsExecState.jsDouble(n: Double): IWkeJsValue; begin Result := TWkeJsValue.Create(FExecState, WAPI.jsDouble(n)); end; function TWkeJsExecState.jsFalse: IWkeJsValue; begin Result := TWkeJsValue.Create(FExecState, WAPI.jsFalse()); end; function TWkeJsExecState.jsFloat(n: float): IWkeJsValue; begin Result := TWkeJsValue.Create(FExecState, WAPI.jsFloat(n)); end; function TWkeJsExecState.jsFunction(fn: jsNativeFunction; argCount: Integer): IWkeJsValue; begin Result := TWkeJsValue.Create(FExecState, WAPI.jsFunction(FExecState, fn, ArgCount)); end; function TWkeJsExecState.jsInt(n: Integer): IWkeJsValue; begin Result := TWkeJsValue.Create(FExecState, WAPI.jsInt(n)); end; function TWkeJsExecState.jsNull: IWkeJsValue; begin Result := TWkeJsValue.Create(FExecState, WAPI.jsNull()); end; function TWkeJsExecState.jsObject: IWkeJsValue; begin Result := TWkeJsValue.Create(FExecState, WAPI.jsEmptyObject(FExecState)); end; function TWkeJsExecState.jsString(const str: PUtf8): IWkeJsValue; begin Result := TWkeJsValue.Create(FExecState, WAPI.jsString(FExecState, str)); end; function TWkeJsExecState.jsStringW(const str: Pwchar_t): IWkeJsValue; begin Result := TWkeJsValue.Create(FExecState, WAPI.jsStringW(FExecState, str)); end; function TWkeJsExecState.jsTrue: IWkeJsValue; begin Result := TWkeJsValue.Create(FExecState, WAPI.jsTrue()); end; function TWkeJsExecState.jsUndefined: IWkeJsValue; begin Result := TWkeJsValue.Create(FExecState, WAPI.jsUndefined()); end; procedure TWkeJsExecState.SetProp(const AProp: WideString; const Value: IWkeJsValue); begin if Value = nil then begin WAPI.jsSetGlobal(FExecState, PAnsiChar(AnsiString(AProp)), WAPI.jsUndefined); end else begin WAPI.jsSetGlobal(FExecState, PAnsiChar(AnsiString(AProp)), Value.Value); end; end; function TWkeJsExecState.CallGlobal(const func: WideString; args: array of OleVariant): OleVariant; var v: IWkeJsValue; begin v := GetProp(func); if not v.IsFunction then raise EWkeException.CreateFmt('脚本中,[%s]函数不存在,或它不是函数!', [func]); Result := CallGlobal(v.Value, args); end; function TWkeJsExecState.GetWebView: TWebView; begin Result := WAPI.jsGetWebView(FExecState); end; procedure TWkeJs.SetData1(const Value: Pointer); begin FData1 := Value; end; procedure TWkeJs.SetData2(const Value: Pointer); begin FData2 := Value; end; procedure TWkeJs.UnbindFunction(const name: WideString); begin GlobalExec.UnbindFunction(name); end; procedure TWkeJs.UnbindObject(const objName: WideString); begin GlobalExec.UnbindObject(objName); end; { TWkeJsObject } function TWkeJsObject.Call(const func: WideString; args: array of OleVariant): OleVariant; var v: IWkeJsValue; begin v := GetProp(func); if not v.IsFunction then raise EWkeException.CreateFmt('脚本中,[%s]函数不存在,或它不是函数!', [func]); Result := Call(v.Value, args); end; function TWkeJsObject.Call(func: jsValue; args: array of OleVariant): OleVariant; var LArgs: JsValueArray; i, cArgs: Integer; jValue, jR: jsValue; sError: string; begin cArgs := System.Length(args); System.SetLength(LArgs, cArgs); for i := 0 to High(args) do begin if not V2J(FExecState, args[i].Value, jValue, sError) then begin if sError <> '' then sError := Format('第%d个参数转换失败:%s', [i+1, sError]) else sError := Format('第%d个参数转换失败!', [i+1]); raise EWkeException.Create(sError); end; LArgs[i] := jValue; end; jR := WAPI.jsCall(FExecState, func, FValue, @LArgs, cArgs); if WAPI.jsIsUndefined(jR) then begin Result := Unassigned; end else begin if not J2V(FExecState, jR, Result, sError) then begin if sError <> '' then sError := Format('返回值转换失败:%s', [sError]) else sError := Format('返回值转换失败!', []); raise EWkeException.Create(sError); end; end; end; function TWkeJsObject.CallEx(const func: WideString; args: array of IWkeJsValue): IWkeJsValue; var v: IWkeJsValue; begin v := GetProp(func); if not v.IsFunction then raise EWkeException.CreateFmt('脚本中,[%s]函数不存在,或它不是函数!', [func]); Result := CallEx(v.Value, args); end; function TWkeJsObject.CallEx(func: jsValue; args: array of IWkeJsValue): IWkeJsValue; var LArgs: JsValueArray; i, cArgs: Integer; begin cArgs := System.Length(args); System.SetLength(LArgs, cArgs); for i := 0 to High(args) do LArgs[i] := args[i].Value; Result := TWkeJsValue.Create(FExecState, WAPI.jsCall(FExecState, func, FValue, @LArgs, cArgs) ); end; function TWkeJsObject.GetLength: Integer; begin Result := WAPI.jsGetLength(FExecState, FValue); end; function TWkeJsObject.GetProp(const AName: WideString): IWkeJsValue; begin Result := TWkeJsValue.Create(FExecState, WAPI.jsGet(FExecState, FValue, PAnsiChar(AnsiString(AName))) ); end; function TWkeJsObject.GetPropAt( const AIndex: Integer): IWkeJsValue; begin Result := TWkeJsValue.Create(FExecState, WAPI.jsGetAt(FExecState, FValue, AIndex) ); end; function TWkeJsObject.PropExist(const AProp: WideString): Boolean; var v: jsValue; begin v := WAPI.jsGet(FExecState, FValue, PAnsiChar(AnsiString(AProp))); Result := not WAPI.jsIsUndefined(v); end; procedure TWkeJsObject.SetLength(const Value: Integer); begin WAPI.jsSetLength(FExecState, FValue, Value); end; procedure TWkeJsObject.SetProp(const AName: WideString; const Value: IWkeJsValue); begin if Value = nil then begin WAPI.jsSet(FExecState, FValue, PAnsiChar(AnsiString(AName)), WAPI.jsUndefined); end else begin WAPI.jsSet(FExecState, FValue, PAnsiChar(AnsiString(AName)), Value.Value); end; end; procedure TWkeJsObject.SetPropAt(const AIndex: Integer; const Value: IWkeJsValue); begin if Value = nil then begin WAPI.jsSetAt(FExecState, FValue, AIndex, WAPI.jsUndefined); end else begin WAPI.jsSetAt(FExecState, FValue, AIndex, Value.Value); end; end; function TWkeJsExecState.GetData1: Pointer; begin Result := FData1; end; function TWkeJsExecState.GetData2: Pointer; begin Result := FData2; end; procedure TWkeJsExecState.SetData1(const Value: Pointer); begin FData1 := Value; end; procedure TWkeJsExecState.SetData2(const Value: Pointer); begin FData2 := Value; end; procedure TWkeJsExecState.BindObject(const objName: WideString; obj: TObject); begin Wke.BindObject(FExecState, objName, obj); end; procedure TWkeJsExecState.BindFunction(const name: WideString; fn: jsNativeFunction; argCount: Integer); begin Wke.BindFunction(FExecState, name, fn, argCount); end; procedure TWkeJsExecState.UnbindFunction(const name: WideString); begin Wke.UnbindFunction(FExecState, name); end; procedure TWkeJsExecState.UnbindObject(const objName: WideString); begin Wke.UnbindObject(FExecState, objName); end; function TWkeJsObjectList.GetData1: Pointer; begin Result := FData1; end; function TWkeJsObjectList.GetData2: Pointer; begin Result := FData2; end; procedure TWkeJsObjectList.SetData1(const Value: Pointer); begin FData1 := Value; end; procedure TWkeJsObjectList.SetData2(const Value: Pointer); begin FData2 := Value; end; function TWkeJsExecState.CreateJsObject(obj: TObject): jsValue; begin Result := Wke.CreateJsObject(FExecState, obj); end; { TWkeJsObjectRegInfo } constructor TWkeJsObjectRegInfo.Create(const AName: WideString; const AValue: TObject); begin FName := AName; FValue := AValue; end; function TWkeJsObjectRegInfo.GetName: WideString; begin Result := FName; end; function TWkeJsObjectRegInfo.GetValue: TObject; begin Result := FValue; end; procedure TWkeJsObjectRegInfo.SetName(const Value: WideString); begin FName := Value; end; procedure TWkeJsObjectRegInfo.SetValue(const Value: TObject); begin FValue := Value; end; procedure TWkeJsObjectList.DoNotify(const AInfo: IWkeJsObjectRegInfo; Action: TWkeJsObjectAction); var i: Integer; begin for i := 0 to FNotifyList.Count - 1 do try TWkeJsObjectListener(PMethod(FNotifyList[i])^)(AInfo, Action); except end; end; function TWkeJsObjectList.AddListener( const AListener: TWkeJsObjectListener): Integer; var LMethod: PMethod; begin New(LMethod); LMethod^ := TMethod(AListener); Result := FNotifyList.Add(LMethod); end; function TWkeJsObjectList.RemoveListener( const AListener: TWkeJsObjectListener): Integer; var LMethod: PMethod; begin for Result := FNotifyList.Count - 1 downto 0 do begin LMethod := PMethod(FNotifyList[Result]); if (LMethod.Code = TMethod(AListener).Code) and (LMethod.Data = TMethod(AListener).Data) then begin Dispose(LMethod); FNotifyList.Delete(Result); Exit; end; end; Result := -1; end; end.
unit Main; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Layouts, FMX.ListBox, FMX.StdCtrls, FMX.Controls.Presentation, System.IOUtils, FMX.Helpers.Android, Androidapi.Helpers, Androidapi.JNI.GraphicsContentViewText, FMX.Edit, FMX.Gestures; type TIntentForm = class(TForm) ToolBar1: TToolBar; Button1: TButton; Label1: TLabel; ListBox1: TListBox; Button2: TButton; Label2: TLabel; TrackBar1: TTrackBar; TrackBar2: TTrackBar; TrackBar3: TTrackBar; Label3: TLabel; ScrollBox1: TScrollBox; Label4: TLabel; Edit1: TEdit; GestureManager1: TGestureManager; Label5: TLabel; Edit2: TEdit; Button3: TButton; procedure Button1Click(Sender: TObject); procedure TrackBar1Change(Sender: TObject); procedure ListBox1Gesture(Sender: TObject; const EventInfo: TGestureEventInfo; var Handled: Boolean); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var IntentForm: TIntentForm; implementation {$R *.fmx} // Функция изменения цвета по каналам RGB Function ARGB(const A,R,G,B:byte):TAlphaColor; begin Result:=B + G SHL 8 + R SHL 16+ A SHL 24; end; // Поиск файлов и добавление их в ListBox procedure TIntentForm.Button1Click(Sender: TObject); var f:TSearchRec; begin // Очистка списка ListBox1.Items.Clear; // Поиск первого файла // if FindFirst('/mnt/sdcard/*.jpg',faAnyFile,f)<>0 then exit; // Вывод пути /Pictures Label3.Text:=TPath.GetSharedPicturesPath; if FindFirst(TPath.GetSharedPicturesPath+'/*.jpg',faAnyFile,f)<>0 then exit; Listbox1.Items.Add(f.name); // Добавляем найденный файл в список while FindNext(f)=0 do // ищем остальные файлы begin Listbox1.Items.Add(f.name); end; FindClose(f); // Закрываем файловую переменную end; // Позвонить по номеру procedure TIntentForm.Button2Click(Sender: TObject); var Intent: JIntent; begin Intent:=TJIntent.Create; Intent.setAction(TJIntent.JavaClass.ACTION_CALL); Intent.setData(StrToJUri('tel:'+edit1.Text)); SharedActivity.startActivity(Intent); end; // Открыть URL в браузере procedure TIntentForm.Button3Click(Sender: TObject); var Intent:JIntent; begin Intent := TJIntent.Create; Intent.setAction(TJIntent.JavaClass.ACTION_VIEW); Intent.setData(StrToJURI(Edit2.Text)); SharedActivity.startActivity(Intent); end; // Открытие изображений через Интент procedure TIntentForm.ListBox1Gesture(Sender: TObject; const EventInfo: TGestureEventInfo; var Handled: Boolean); var Intent: JIntent; begin // Для вызова приложения для просмотра изображения в списке ListBox // нужно нажать и удерживать єлемент списка ListBox с именем изображения case EventInfo.GestureID of // Долгое нажатие igiLongTap: // Вызываем намерение для открытия изображения begin Intent := TJIntent.Create; Intent.setAction(TJIntent.JavaClass.ACTION_VIEW); //Intent.setDataAndType(StrToJURI('file:' + '/mnt/sdcard/'+ListBox1.Selected.Text), StringToJString('image/jpg')); Intent.setDataAndType(StrToJURI('file:' + TPath.GetSharedPicturesPath+'/'+ListBox1.Selected.Text), StringToJString('image/jpg')); SharedActivity.startActivity(Intent); end; end; end; // Меняем цвет ToolBar procedure TIntentForm.TrackBar1Change(Sender: TObject); begin ToolBar1.TintColor:=ARGB(255,Round(Trackbar1.Value),Round(Trackbar2.Value),Round(Trackbar3.Value)); end; end.
unit PascalCoin.Frame.Unlock; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Controls.Presentation, FMX.Edit; type TUnlockFrame = class(TFrame) Panel1: TPanel; Label1: TLabel; Label2: TLabel; PasswordEdit: TEdit; OKButton: TButton; CancelButton: TButton; procedure CancelButtonClick(Sender: TObject); procedure OKButtonClick(Sender: TObject); private function GetPassword: string; { Private declarations } public { Public declarations } OnCancel: TProc; OnOk: TProc; property Password: string read GetPassword; end; implementation {$R *.fmx} procedure TUnlockFrame.CancelButtonClick(Sender: TObject); begin if Assigned(OnCancel) then OnCancel; end; { TUnlockFrame } function TUnlockFrame.GetPassword: string; begin result := PasswordEdit.Text; end; procedure TUnlockFrame.OKButtonClick(Sender: TObject); begin if Assigned(OnOk) then OnOk; end; end.
{ ---------------------------------------------------------------------------- } { FormulaJIT for MB3D } { Copyright (C) 2016-2017 Andreas Maschke } { ---------------------------------------------------------------------------- } unit FormulaNames; interface uses SysUtils, Classes; type TFormulaCategory = (fc_3D, fc_3Da, fc_4D, fc_4Da, fc_Ads, fc_dIFS, fc_dIFSa); TFilterUnderscore = (fuIgnore, fuWithUnderscore, fuWithoutUnderscore); TFormulaName=class FCategory: TFormulaCategory; FFormulaName: String; public constructor Create(const Category: TFormulaCategory;const FormulaName: String); property Category: TFormulaCategory read FCategory; property FormulaName: String read FFormulaName; end; TFormulaNames = class private FFormulaNamesList: TList; function GetCount: Integer; function FNameIsIncluded(Name: String): Boolean; function GetFormulaName(Index: Integer): TFormulaName; public constructor Create; destructor Destroy; override; procedure AddFormulaName(Category: TFormulaCategory; const FormulaName: String); function GetFormulaNamesByCategory(const Category: TFormulaCategory): TStringList; function GetCategoryByFormulaName(const FormulaName: String): TFormulaCategory; property Count: Integer read GetCount; property Formulas[Index: Integer]: TFormulaName read GetFormulaName; end; TFormulaNamesLoader=class private class procedure AddFormulaName(FNames: TFormulaNames; FName: String; DEfunc: Integer); public class function GetFavouriteStatus(formulaname: String): Integer; //-2: hide, -1: dislike, 0: normal, 1: like class function LoadFormulas: TFormulaNames; end; const InternFormulasDEfunc: array[0..6] of Integer = (0,0,4,0,11,0,0); implementation uses Contnrs, HeaderTrafos, FileHandling, DivUtils, CustomFormulas; { ----------------------------- TFormulaName --------------------------------- } constructor TFormulaName.Create(const Category: TFormulaCategory;const FormulaName: String); begin inherited Create; FCategory := Category; FFormulaName := FormulaName; end; { ----------------------------- TFormulaNames -------------------------------- } constructor TFormulaNames.Create; begin inherited Create; FFormulaNamesList := TObjectList.Create; end; destructor TFormulaNames.Destroy; begin FFormulaNamesList.Free; inherited Destroy; end; function TFormulaNames.GetCount: Integer; begin Result := FFormulaNamesList.Count; end; function TFormulaNames.FNameIsIncluded(Name: String): Boolean; var I: Integer; begin Result := False; for I := 0 to FFormulaNamesList.Count - 1 do begin if CompareText(Trim(Name), StrLastWords( TFormulaName(FFormulaNamesList[I]).FormulaName )) = 0 then begin Result := True; Break; end; end; end; procedure TFormulaNames.AddFormulaName(Category: TFormulaCategory; const FormulaName: String); begin FFormulaNamesList.Add( TFormulaName.Create(Category, FormulaName) ); end; function TFormulaNames.GetFormulaName(Index: Integer): TFormulaName; begin Result := TFormulaName(FFormulaNamesList[Index]); end; // TODO Caching function TFormulaNames.GetFormulaNamesByCategory(const Category: TFormulaCategory): TStringList; var I: Integer; begin Result := TStringList.Create; for I := 0 to Count-1 do begin if Formulas[I].Category = Category then Result.Add(Formulas[I].FormulaName); end; end; function TFormulaNames.GetCategoryByFormulaName(const FormulaName: String): TFormulaCategory; var I: Integer; begin for I := 0 to Count-1 do begin if Formulas[I].FormulaName = FormulaName then begin Result := Formulas[I].Category; exit; end; end; raise Exception.Create('TFormulaNames.GetCategoryByFormulaName: Formula <'+FormulaName+'> not found'); end; { -------------------------- TFormulaNamesLoader ----------------------------- } class function TFormulaNamesLoader.GetFavouriteStatus(formulaname: String): Integer; //-2: hide, -1: dislike, 0: normal, 1: like var M: TStringList; i: Integer; // bNotFound: LongBool; begin Result := 1; // if (formulaname = '') or not FileExists(AppDataDir + IncludeTrailingPathDelimiter('Formulas') + 'FavouriteList.txt') then Exit; if (formulaname = '') or not FileExists(IncludeTrailingPathDelimiter(IniDirs[3]) + 'FavouriteList.txt') then Exit; M := TStringList.Create; try // M.LoadFromFile(AppDataDir + IncludeTrailingPathDelimiter('Formulas') + 'FavouriteList.txt'); M.LoadFromFile(IncludeTrailingPathDelimiter(IniDirs[3]) + 'FavouriteList.txt'); except M.Clear; end; // bNotFound := True; for i := 1 to M.Count do if SameText(StrLastWords(M.Strings[i - 1]), formulaname) then begin Result := StrToInt(StrFirstWord(M.Strings[i - 1])); Break; end; M.Clear; M.Free; end; class procedure TFormulaNamesLoader.AddFormulaName(FNames: TFormulaNames;FName: String; DEfunc: Integer); var stat: Integer; begin stat := GetFavouriteStatus(FName); if stat > -2 then begin //FName := IntToStr(stat) + ' ' + FName; case DEfunc of 2,11: FNames.AddFormulaName(fc_3Da, FName); 4: FNames.AddFormulaName(fc_4D, FName); 5,6: FNames.AddFormulaName(fc_4Da, FName); -1,-2: FNames.AddFormulaName(fc_Ads, FName); 20: FNames.AddFormulaName(fc_dIFS, FName); 21..22: FNames.AddFormulaName(fc_dIFSa, FName); else // 3D FNames.AddFormulaName(fc_3D, FName); end; end; end; class function TFormulaNamesLoader.LoadFormulas: TFormulaNames; var I: Integer; sdir, s2, se, s3: String; df: Integer; sr: TSearchRec; b: LongBool; begin Result := TFormulaNames.Create; try for I := 0 to 6 do AddFormulaName(Result, InternFormulaNames[i], InternFormulasDEfunc[i]); AddFormulaName(Result, 'Aexion C', 0); s2 := ''; sdir := IncludeTrailingPathDelimiter(IniDirs[3]); if FindFirst(sdir + '*.m3f', 0, sr) = 0 then repeat se := ChangeFileExt(sr.Name, ''); s3 := UpperCase(se); b := (s3 <> 'TRAFASSELQUAT') or not CanLoadF('CommQuat'); b := b and ((s3 <> '_FLIPXY') or not CanLoadF('_FlipXYc')); b := b and ((s3 <> '_FLIPXZ') or not CanLoadF('_FlipXZc')); b := b and ((s3 <> '_FLIPYZ') or not CanLoadF('_FlipYZc')); b := b and ((s3 <> 'ABOXMODKALIFIXED') or not CanLoadF('ABoxModKali')); b := b and (s3 <> 'SQKOCH') and (s3 <> 'DJD-QUAT') and (s3 <> '_IFS-TESS'); if b and CanLoadCustomFormula(sdir + sr.Name, df) and (not Result.FNameIsIncluded(se)) then AddFormulaName(Result, se, df); until FindNext(sr) <> 0; FindClose(sr); s2 := sdir; except Result.Free; raise; end; end; end.
unit TestSpacing; { AFS Jan 2003 Test the spacing processes } {(*} (*------------------------------------------------------------------------------ Delphi Code formatter source code The Original Code is TestSpacing, released May 2003. The Initial Developer of the Original Code is Anthony Steele. Portions created by Anthony Steele are Copyright (C) 1999-2000 Anthony Steele. All Rights Reserved. Contributor(s): Anthony Steele. 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/NPL/ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. Alternatively, the contents of this file may be used under the terms of the GNU General Public License Version 2 or later (the "GPL") See http://www.gnu.org/licenses/gpl.html ------------------------------------------------------------------------------*) {*)} {$I JcfGlobal.inc} interface uses TestFrameWork, BaseTestProcess, SettingsTypes; type TTestSpacing = class(TBaseTestProcess) private fiSaveMaxSpaces: integer; feSaveOperatorSetting: TTriOptionStyle; protected procedure SetUp; override; procedure TearDown; override; published procedure TestNoReturnAfter; procedure TestNoReturnBefore; procedure TestNoSpaceAfter; procedure TestNoSpaceBefore; procedure TestNoSpaceBefore2; procedure TestNoSpaceAfterOperator; procedure TestNoSpaceAfterOperator2; procedure TestSingleSpaceBefore; procedure TestSingleSpaceAfter; procedure TestSingleSpaceAfter2; procedure TestSingleSpaceAfter3; procedure TestSingleSpaceAfterColon; procedure TestSingleSpaceAfterColon2; procedure TestReturnBefore; procedure TestReturnAfter; procedure TestBlankLinesAfterProcHeader; procedure TestBlankLinesAfterBegin; procedure TestBlankLinesBeforeEnd; procedure TestUsesCaps1; procedure TestUsesCaps2; procedure TestUsesCaps3; procedure TestTabToSpace; procedure TestSpaceToTab; procedure TestMaxSpaces4; procedure TestMaxSpaces3; procedure TestMaxSpaces2; procedure TestMaxSpaces1; procedure TestOperatorSpacing; procedure TestOperatorSpacing2; end; implementation uses JcfStringUtils, JcfSettings, NoReturnAfter, NoReturnBefore, NoSpaceAfter, NoSpaceBefore, SpaceBeforeColon, SingleSpaceBefore, SingleSpaceAfter, ReturnBefore, ReturnAfter, RemoveBlankLinesAfterProcHeader, RemoveReturnsAfterBegin, RemoveReturnsBeforeEnd, UnitNameCaps, TabToSpace, SpaceToTab, MaxSpaces, SetSpaces; procedure TTestSpacing.Setup; begin inherited; fiSaveMaxSpaces := JcfFormatSettings.Spaces.MaxSpacesInCode; feSaveOperatorSetting := JcfFormatSettings.Spaces.SpaceForOperator; end; procedure TTestSpacing.Teardown; begin inherited; JcfFormatSettings.Spaces.MaxSpacesInCode := fiSaveMaxSpaces; JcfFormatSettings.Spaces.SpaceForOperator := feSaveOperatorSetting; end; procedure TTestSpacing.TestNoReturnAfter; const IN_UNIT_TEXT = UNIT_HEADER + ' procedure foo; begin if ' + NativeLineBreak + '(foo) then ; end; ' + UNIT_FOOTER; OUT_UNIT_TEXT = UNIT_HEADER + ' procedure foo; begin if (foo) then ; end; ' + UNIT_FOOTER; begin JcfFormatSettings.Returns.RemoveBadReturns := True; TestProcessResult(TNoReturnAfter, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestSpacing.TestNoReturnBefore; const IN_UNIT_TEXT = UNIT_HEADER + ' procedure foo; begin a ' + NativeLineBreak + ':= 2; end; ' + UNIT_FOOTER; OUT_UNIT_TEXT = UNIT_HEADER + ' procedure foo; begin a := 2; end; ' + UNIT_FOOTER; begin JcfFormatSettings.Returns.RemoveBadReturns := True; TestProcessResult(TNoReturnBefore, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestSpacing.TestNoSpaceAfter; const IN_UNIT_TEXT = UNIT_HEADER + ' procedure foo; begin a := ( 2); end; ' + UNIT_FOOTER; OUT_UNIT_TEXT = UNIT_HEADER + ' procedure foo; begin a := (2); end; ' + UNIT_FOOTER; begin TestProcessResult(TNoSpaceAfter, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestSpacing.TestNoSpaceBefore; const IN_UNIT_TEXT = UNIT_HEADER + ' procedure foo ; begin a := 2 ; end ; ' + UNIT_FOOTER; OUT_UNIT_TEXT = UNIT_HEADER + ' procedure foo; begin a := 2; end; ' + UNIT_FOOTER; begin TestProcessResult(TNoSpaceBefore, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestSpacing.TestNoSpaceBefore2; const IN_UNIT_TEXT = INTERFACE_HEADER + 'function foo (i : integer) : integer ; far ; stdcall ;' + ' implementation ' + UNIT_FOOTER; OUT_UNIT_TEXT = INTERFACE_HEADER + 'function foo(i: integer): integer; far; stdcall;' + ' implementation ' + UNIT_FOOTER; begin TestProcessResult(TNoSpaceBefore, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestSpacing.TestNoSpaceAfterOperator; const IN_UNIT_TEXT = UNIT_HEADER + ' function foo: ' + NativeLineBreak + ' integer; begin result := 2 + 2; end; ' + UNIT_FOOTER; OUT_UNIT_TEXT = UNIT_HEADER + ' function foo: ' + NativeLineBreak + ' integer; begin result := 2 + 2; end; ' + UNIT_FOOTER; begin TestProcessResult(TNoSpaceAfter, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestSpacing.TestNoSpaceAfterOperator2; const IN_UNIT_TEXT = UNIT_HEADER + ' function foo: ' + NativeLineBreak + ' integer; begin result := 2 * - 2; end; ' + UNIT_FOOTER; OUT_UNIT_TEXT = UNIT_HEADER + ' function foo: ' + NativeLineBreak + ' integer; begin result := 2 * -2; end; ' + UNIT_FOOTER; begin TestProcessResult(TNoSpaceAfter, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestSpacing.TestSingleSpaceBefore; const IN_UNIT_TEXT = UNIT_HEADER + ' procedure foo; begin a := 2; end; ' + UNIT_FOOTER; OUT_UNIT_TEXT = UNIT_HEADER + ' procedure foo; begin a := 2; end; ' + UNIT_FOOTER; begin TestProcessResult(TSingleSpaceBefore, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestSpacing.TestSingleSpaceAfter; const IN_UNIT_TEXT = UNIT_HEADER + ' procedure foo; begin a :=2; end; ' + UNIT_FOOTER; OUT_UNIT_TEXT = UNIT_HEADER + ' procedure foo; begin a := 2; end; ' + UNIT_FOOTER; begin TestProcessResult(TSingleSpaceAfter, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestSpacing.TestSingleSpaceAfter2; const IN_UNIT_TEXT = INTERFACE_HEADER + 'function foo(i:integer):integer;far;stdcall;' + ' implementation ' + UNIT_FOOTER; OUT_UNIT_TEXT = INTERFACE_HEADER + 'function foo(i: integer): integer; far; stdcall;' + ' implementation ' + UNIT_FOOTER; begin TestProcessResult(TSingleSpaceAfter, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestSpacing.TestSingleSPaceAfter3; const IN_UNIT_TEXT = INTERFACE_HEADER + 'type TFredProc =procedure(var psFred:integer)of Object;' + ' implementation ' + UNIT_FOOTER; OUT_UNIT_TEXT = INTERFACE_HEADER + 'type TFredProc = procedure(var psFred: integer)of Object;' + ' implementation ' + UNIT_FOOTER; begin TestProcessResult(TSingleSpaceAfter, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestSpacing.TestSingleSpaceAfterColon; const IN_UNIT_TEXT = UNIT_HEADER + ' function foo: integer; begin result := 2; end; ' + UNIT_FOOTER; OUT_UNIT_TEXT = UNIT_HEADER + ' function foo: integer; begin result := 2; end; ' + UNIT_FOOTER; begin TestProcessResult(TSingleSpaceAfter, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestSpacing.TestSingleSpaceAfterColon2; const IN_UNIT_TEXT = UNIT_HEADER + ' function foo: ' + NativeLineBreak + ' integer; begin result := 2; end; ' + UNIT_FOOTER; OUT_UNIT_TEXT = UNIT_HEADER + ' function foo: ' + NativeLineBreak + ' integer; begin result := 2; end; ' + UNIT_FOOTER; begin TestProcessResult(TSingleSpaceAfter, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestSpacing.TestReturnBefore; const IN_UNIT_TEXT = UNIT_HEADER + 'procedure foo; begin a := 2; end;' + UNIT_FOOTER; OUT_UNIT_TEXT = 'unit Test;' + NativeLineBreak + NativeLineBreak + 'interface' + NativeLineBreak + NativeLineBreak + 'implementation' + NativeLineBreak + NativeLineBreak + 'procedure foo;' + NativeLineBreak + 'begin a := 2;' + NativeLineBreak + 'end;' + NativeLineBreak + NativeLineBreak + 'end.'; begin TestProcessResult(TReturnBefore, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestSpacing.TestReturnAfter; const UNLINED_UNIT_HEADER = 'unit Test; interface implementation'; IN_UNIT_TEXT = UNLINED_UNIT_HEADER + ' procedure foo; begin a := 2; end;' + UNIT_FOOTER; OUT_UNIT_TEXT = 'unit Test;' + NativeLineBreak + NativeLineBreak + 'interface' + NativeLineBreak + NativeLineBreak + 'implementation' + NativeLineBreak + NativeLineBreak + 'procedure foo;' + NativeLineBreak + 'begin' + NativeLineBreak + 'a := 2;' + NativeLineBreak + 'end;' + NativeLineBreak + NativeLineBreak + 'end.'; begin TestProcessResult(TReturnAfter, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestSpacing.TestBlankLinesAfterProcHeader; const IN_UNIT_TEXT = UNIT_HEADER + 'procedure foo;' + NativeLineBreak + NativeLineBreak + NativeLineBreak + NativeLineBreak + 'begin a := 2; end; ' + UNIT_FOOTER; OUT_UNIT_TEXT = UNIT_HEADER + 'procedure foo;' + NativeLineBreak + NativeLineBreak + 'begin a := 2; end; ' + UNIT_FOOTER; begin TestProcessResult(TRemoveBlankLinesAfterProcHeader, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestSpacing.TestBlankLinesAfterBegin; const IN_UNIT_TEXT = UNIT_HEADER + ' procedure foo; begin' + NativeLineBreak + NativeLineBreak + NativeLineBreak + NativeLineBreak + 'end; ' + UNIT_FOOTER; OUT_UNIT_TEXT = UNIT_HEADER + ' procedure foo; begin' + NativeLineBreak + NativeLineBreak + 'end; ' + UNIT_FOOTER; begin TestProcessResult(TRemoveReturnsAfterBegin, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestSpacing.TestBlankLinesBeforeEnd; const IN_UNIT_TEXT = UNIT_HEADER + ' procedure foo; begin' + NativeLineBreak + NativeLineBreak + NativeLineBreak + NativeLineBreak + 'end; ' + UNIT_FOOTER; OUT_UNIT_TEXT = UNIT_HEADER + ' procedure foo; begin' + NativeLineBreak + NativeLineBreak + 'end; ' + UNIT_FOOTER; begin TestProcessResult(TRemoveReturnsBeforeEnd, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestSpacing.TestUsesCaps1; const IN_UNIT_TEXT = 'unit foo; interface uses bar; implementation uses fish; end.'; begin JcfFormatSettings.UnitNameCaps.Enabled := True; TestProcessResult(TUnitNameCaps, IN_UNIT_TEXT, IN_UNIT_TEXT); end; procedure TTestSpacing.TestUsesCaps2; const IN_UNIT_TEXT = 'unit foo; interface uses bar; implementation uses fish, spon; end.'; OUT_UNIT_TEXT = 'unit Foo; interface uses Bar; implementation uses Fish, spon; end.'; begin // contains these and only these JcfFormatSettings.UnitNameCaps.Enabled := True; JcfFormatSettings.UnitNameCaps.Clear; JcfFormatSettings.UnitNameCaps.Add('Foo'); JcfFormatSettings.UnitNameCaps.Add('Bar'); JcfFormatSettings.UnitNameCaps.Add('Fish'); TestProcessResult(TUnitNameCaps, IN_UNIT_TEXT, OUT_UNIT_TEXT); // reset JcfFormatSettings.Read; end; procedure TTestSpacing.TestUsesCaps3; const IN_UNIT_TEXT = 'unit foo; interface implementation uses fish; ' + 'initialization monkey.soy; shatner.kirk := shatner.kirk + 3; end.'; OUT_UNIT_TEXT = 'unit Foo; interface implementation uses Fish; ' + 'initialization Monkey.soy; shatner.kirk := shatner.kirk + 3; end.'; begin // contains these and only these JcfFormatSettings.UnitNameCaps.Enabled := True; JcfFormatSettings.UnitNameCaps.Clear; JcfFormatSettings.UnitNameCaps.Add('Foo'); JcfFormatSettings.UnitNameCaps.Add('Bar'); JcfFormatSettings.UnitNameCaps.Add('Fish'); JcfFormatSettings.UnitNameCaps.Add('Monkey'); // this won't be used as 'soy' is a fn not a unit name JcfFormatSettings.UnitNameCaps.Add('Soy'); // likewise kirk is a global var JcfFormatSettings.UnitNameCaps.Add('Kirk'); TestProcessResult(TUnitNameCaps, IN_UNIT_TEXT, OUT_UNIT_TEXT); // reset JcfFormatSettings.Read; end; procedure TTestSpacing.TestTabToSpace; const IN_UNIT_TEXT = UNIT_HEADER + ' procedure foo;' + NativeTab + 'begin a := 2; end; ' + UNIT_FOOTER; OUT_UNIT_TEXT = UNIT_HEADER + ' procedure foo; begin a := 2; end; ' + UNIT_FOOTER; begin TestProcessResult(TTabToSpace, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestSpacing.TestSpaceToTab; const IN_UNIT_TEXT = UNIT_HEADER + ' procedure foo; begin a := 2; end; ' + UNIT_FOOTER; OUT_UNIT_TEXT = UNIT_HEADER + ' procedure foo;' + NativeTab + 'begin a := 2; end; ' + UNIT_FOOTER; begin TestProcessResult(TSpaceToTab, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestSpacing.TestMaxSpaces4; const IN_UNIT_TEXT = UNIT_HEADER + ' procedure foo; begin a := 2; end; ' + UNIT_FOOTER; OUT_UNIT_TEXT = UNIT_HEADER + ' procedure foo; begin a := 2; end; ' + UNIT_FOOTER; begin JcfFormatSettings.Spaces.MaxSpacesInCode := 4; TestProcessResult(TMaxSpaces, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestSpacing.TestMaxSpaces3; const IN_UNIT_TEXT = UNIT_HEADER + ' procedure foo; begin a := 2; end; ' + UNIT_FOOTER; OUT_UNIT_TEXT = UNIT_HEADER + ' procedure foo; begin a := 2; end; ' + UNIT_FOOTER; begin JcfFormatSettings.Spaces.MaxSpacesInCode := 3; TestProcessResult(TMaxSpaces, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestSpacing.TestMaxSpaces2; const IN_UNIT_TEXT = UNIT_HEADER + ' procedure foo; begin a := 2; end; ' + UNIT_FOOTER; OUT_UNIT_TEXT = UNIT_HEADER + ' procedure foo; begin a := 2; end; ' + UNIT_FOOTER; begin JcfFormatSettings.Spaces.MaxSpacesInCode := 2; TestProcessResult(TMaxSpaces, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestSpacing.TestMaxSpaces1; const IN_UNIT_TEXT = UNIT_HEADER + ' procedure foo; begin a := 2; end; ' + UNIT_FOOTER; OUT_UNIT_TEXT = UNIT_HEADER + ' procedure foo; begin a := 2; end; ' + UNIT_FOOTER; begin JcfFormatSettings.Spaces.MaxSpacesInCode := 1; TestProcessResult(TMaxSpaces, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; { Test the spacing. A pity that it tests the particular processes where the implementation of this option is used, rether than testing formatting as a black box under different settings } procedure TTestSpacing.TestOperatorSpacing; const UNIT_TEXT_SPACED = UNIT_HEADER + ' procedure foo; begin a := 2 + 2; end; ' + UNIT_FOOTER; UNIT_TEXT_UNSPACED_BEFORE = UNIT_HEADER + ' procedure foo; begin a := 2+ 2; end; ' + UNIT_FOOTER; UNIT_TEXT_UNSPACED_AFTER = UNIT_HEADER + ' procedure foo; begin a := 2 +2; end; ' + UNIT_FOOTER; begin JcfFormatSettings.Spaces.SpaceForOperator := eNever; TestProcessResult(TNoSpaceBefore, UNIT_TEXT_SPACED, UNIT_TEXT_UNSPACED_BEFORE); TestProcessResult(TNoSpaceAfter, UNIT_TEXT_SPACED, UNIT_TEXT_UNSPACED_AFTER); JcfFormatSettings.Spaces.SpaceForOperator := eLeave; TestProcessResult(TNoSpaceBefore, UNIT_TEXT_UNSPACED_BEFORE, UNIT_TEXT_UNSPACED_BEFORE); TestProcessResult(TNoSpaceAfter, UNIT_TEXT_UNSPACED_AFTER, UNIT_TEXT_UNSPACED_AFTER); JcfFormatSettings.Spaces.SpaceForOperator := eAlways; TestProcessResult(TSingleSpaceBefore, UNIT_TEXT_UNSPACED_BEFORE, UNIT_TEXT_SPACED); TestProcessResult(TSingleSpaceAfter, UNIT_TEXT_UNSPACED_AFTER, UNIT_TEXT_SPACED); end; { these cannot be unspaced since the textual tokens then run together "a := a mod b;" is not the same as "a := amodb; } procedure TTestSpacing.TestOperatorSpacing2; const UNIT_TEXT_SPACED = UNIT_HEADER + ' procedure foo; begin a := 47 mod 3; end; ' + UNIT_FOOTER; begin JcfFormatSettings.Spaces.SpaceForOperator := eNever; TestProcessResult(TNoSpaceBefore, UNIT_TEXT_SPACED, UNIT_TEXT_SPACED); TestProcessResult(TNoSpaceAfter, UNIT_TEXT_SPACED, UNIT_TEXT_SPACED); JcfFormatSettings.Spaces.SpaceForOperator := eLeave; TestProcessResult(TNoSpaceBefore, UNIT_TEXT_SPACED, UNIT_TEXT_SPACED); JcfFormatSettings.Spaces.SpaceForOperator := eAlways; TestProcessResult(TSingleSpaceBefore, UNIT_TEXT_SPACED, UNIT_TEXT_SPACED); end; initialization TestFramework.RegisterTest('Processes', TTestSpacing.Suite); end.
unit uStack; {$mode delphi}{$h+} interface uses Classes, SysUtils; // kann noch Variabel gemacht werden type elementTyp = Char; { Der Stack soll nach aussen so wie stack<string> in C++ scheinen } const mxStackSize = 1000; type TStack = class private pTop: Cardinal; // markiert naechster Platz zum einfuegen stack: array[0..mxStackSize] of elementTyp; public constructor Create; destructor Destroy; override; procedure push(element: elementTyp); function pop : elementTyp; function top : elementTyp; function empty : Boolean; end; implementation constructor TStack.Create; begin pTop := 0; end; destructor TStack.Destroy; begin FreeAndNil(stack); FreeAndNil(pTop); end; procedure TStack.push(element: elementTyp); begin if pTop < mxStackSize then begin stack[pTop] := element; inc(pTop); end; end; function TStack.pop : elementTyp; begin if not empty then begin result := stack[pTop - 1]; dec(pTop); end; end; function TStack.top : elementTyp; begin if not empty then begin result := stack[pTop - 1]; end; end; function TStack.empty : Boolean; begin result := (pTop = 0); end; end.
unit osErrorHandler; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, db, osCIC, richedit, RegExpr, System.Types; type TErrorType = (etError, etCritical, etWarning); TosErrorHandlerForm = class(TForm) lbErros: TListBox; btnFechar: TButton; btnContinua: TButton; btnCancela: TButton; procedure lbErrosDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); procedure lbErrosMeasureItem(Control: TWinControl; Index: Integer; var Height: Integer); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private FErrorBmp: TBitmap; FWarningBmp: TBitmap; FCriticalBmp: TBitmap; FEnableWarnings: boolean; function Execute: boolean; function GetErrorCount: integer; public procedure CheckEmpty(PField : TField; PFieldName: string = ''); overload; procedure CheckEmpty(PStr, PFieldName: string); overload; procedure WarningEmpty(PField : TField; PFieldName: string = ''); overload; function IsEmpty(PStr : string) : boolean; overload; function IsEmpty(PField : TField) : boolean; overload; function IsFullStr(PField : TField) : boolean; function IsFullDigit(PField : TField) : boolean; function IsCIC(PField : TField): boolean; function IsCNPJ(PField : TField): boolean; function IsCPF(PField : TField): boolean; function IsUF(PField : TField) : boolean; function IsEmail(PField : TField) : boolean; procedure Check; procedure Clear; procedure Add(PMsg : string; PErrorType : TErrorType = etError); property ErrorCount: integer read GetErrorCount; property EnableWarnings: boolean read FEnableWarnings write FEnableWarnings; end; const OBRIGATORIO = 'Obrigatório: %s'; AVISO_OBRIGATORIO = '%s não informado'; var HError: TosErrorHandlerForm; implementation {$R *.dfm} {$R osErrorHandlerIcons.R32} procedure TosErrorHandlerForm.Add(PMsg: string; PErrorType: TErrorType); begin if (PErrorType <> etWarning) or (EnableWarnings) then lbErros.Items.AddObject(PMsg, TObject(PErrorType)); end; function TosErrorHandlerForm.Execute: boolean; var bContinua: boolean; i: integer; begin bContinua := True; for i:=0 to lbErros.Items.Count-1 do if TErrorType(lbErros.Items.Objects[i]) <> etWarning then begin bContinua := False; break; end; btnFechar.Visible := not bContinua; btnContinua.Visible := bContinua; btnCancela.Visible := bContinua; ShowModal; Result := (ModalResult = mrYes); end; procedure TosErrorHandlerForm.lbErrosDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); var Bmp: TBitmap; R, DestRct, SrcRct: TRect; TransColor: TColor; ItemStz: array[ 0..255 ] of Char; function GetTransparentColor( B: TBitmap ): TColor; begin Result := B.Canvas.Pixels[ 0, B.Height - 1 ]; end; begin with lbErros.Canvas do begin Bmp := TBitmap.Create; try FillRect( Rect ); { Clear area for icon and text } DestRct := Classes.Rect( 0, 0, 18, 18 ); SrcRct := DestRct; { Don't forget to set the Width and Height of destination bitmap. } Bmp.Width := 18; Bmp.Height := 18; if odSelected in State then Bmp.Canvas.Brush.Color := clHighlight else Bmp.Canvas.Brush.Color := lbErros.Color; case TErrorType( lbErros.Items.Objects[ Index ] ) of etWarning: begin TransColor := GetTransparentColor( FWarningBmp ); Bmp.Canvas.BrushCopy( DestRct, FWarningBmp, SrcRct, TransColor); end; etCritical: begin TransColor := GetTransparentColor( FCriticalBmp ); Bmp.Canvas.BrushCopy( DestRct, FCriticalBmp, SrcRct, TransColor ); end; else begin TransColor := GetTransparentColor( FErrorBmp ); Bmp.Canvas.BrushCopy( DestRct, FErrorBmp, SrcRct, TransColor ); end; end; Draw( Rect.Left + 4, Rect.Top + 2, Bmp ); R := Rect; Inc( R.Left, 24 ); Inc( R.Top, 2 ); StrPCopy( ItemStz, lbErros.Items[ Index ] ); DrawText( Handle, ItemStz, -1, R, dt_WordBreak or dt_ExpandTabs ); finally Bmp.Free; end; end; end; procedure TosErrorHandlerForm.lbErrosMeasureItem(Control: TWinControl; Index: Integer; var Height: Integer); var R: TRect; ItemStz: array[ 0..255 ] of Char; H: Integer; begin R := Rect( 0, 0, lbErros.Width - 24, 2 ); StrPCopy( ItemStz, lbErros.Items[ Index ] ); H := DrawText( lbErros.Canvas.Handle, ItemStz, -1, R, dt_CalcRect or dt_WordBreak or dt_ExpandTabs ); if H < 20 then H := 20; Height := H + 15; end; procedure TosErrorHandlerForm.FormCreate(Sender: TObject); begin FErrorBmp := TBitmap.Create; FErrorBmp.Handle := LoadBitmap( HInstance, 'OS_ERROR' ); FWarningBmp := TBitmap.Create; FWarningBmp.Handle := LoadBitmap( HInstance, 'OS_WARNING' ); FCriticalBmp := TBitmap.Create; FCriticalBmp.Handle := LoadBitmap( HInstance, 'OS_CRITICAL' ); FEnableWarnings := True; end; procedure TosErrorHandlerForm.FormDestroy(Sender: TObject); begin FErrorBmp.Free; FWarningBmp.Free; FCriticalBmp.Free; end; function TosErrorHandlerForm.GetErrorCount: integer; begin Result := lbErros.Items.Count; end; procedure TosErrorHandlerForm.Check; begin if lbErros.Items.Count > 0 then begin if Execute then Abort; end; end; procedure TosErrorHandlerForm.Clear; begin lbErros.Items.Clear; end; procedure TosErrorHandlerForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caHide; end; function TosErrorHandlerForm.IsCIC(PField : TField): boolean; var n : integer; CIC : string; DV : integer; begin CIC := Trim(PField.AsString); DV := -1; n := 0; if not IsEmpty(CIC) then begin n := Length(CIC); if n = 14 then DV := CalcDV_CNPJ(CIC) else if n = 11 then DV := CalcDV_CPF(CIC); end; if DV = -1 then Result := False else Result := StrToInt(Copy(CIC, n - 1, 2)) = DV; end; function TosErrorHandlerForm.IsCNPJ(PField: TField): boolean; var DV : integer; CNPJ : string; begin CNPJ := PField.AsString; if IsEmpty(CNPJ) then Result := False else begin DV := CalcDV_CNPJ(Trim(CNPJ)); if DV = -1 then Result := False else Result := StrToInt(Copy(CNPJ, 13, 2)) = DV; end; end; function TosErrorHandlerForm.IsCPF(PField: TField): boolean; var DV : integer; CPF : string; begin CPF := PField.AsString; if IsEmpty(CPF) then Result := False else begin DV := CalcDV_CPF(Trim(CPF)); if DV = -1 then Result := False else Result := StrToInt(Copy(CPF, 10, 2)) = DV; end; end; function TosErrorHandlerForm.IsEmpty(PStr: string): boolean; begin Result := (Trim(PStr) = ''); end; function TosErrorHandlerForm.IsFullDigit(PField: TField): boolean; var s : string; n : integer; i : integer; begin Result := False; if not PField.IsNull then begin s := Trim(PField.AsString); n := Length(s); if n = PField.DisplayWidth then begin i := 1; while (i <= n) and (s[i] >= '0') and (s[i] <= '9') do Inc(i); Result := (i > n); end; end; end; function TosErrorHandlerForm.IsFullStr(PField: TField): boolean; begin Result := False; if not PField.IsNull then Result := (Length(Trim(PField.AsString)) = PField.DisplayWidth); end; function TosErrorHandlerForm.IsUF(PField: TField): boolean; const SiglasValidas = ' RS SC PR SP MS MT RJ ES MG GO BA PE SE AL PI MA RN CE PB PA AM AC RO RR AP TO DF '; var SiglaUF : string; begin SiglaUF := PField.AsString; if IsEmpty(SiglaUF) then Result := False else Result := (Pos(' '+UpperCase(SiglaUF)+' ', SiglasValidas) > 0); end; function TosErrorHandlerForm.IsEmail(PField : TField) : boolean; begin Result := ExecRegExpr('^[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+\.[A-Za-z0-9-]{2,}(\.[A-Za-z0-9-]{2,})*$', PField.AsString); end; function TosErrorHandlerForm.IsEmpty(PField: TField): boolean; begin Result := (IsEmpty(PField.AsString)) end; procedure TosErrorHandlerForm.CheckEmpty(PField: TField; PFieldName: string); begin if IsEmpty(PField) then begin if PFieldName = '' then PFieldName := PField.DisplayLabel; Add(Format(OBRIGATORIO,[PFieldName])); end; end; procedure TosErrorHandlerForm.CheckEmpty(PStr, PFieldName: string); begin if IsEmpty(PStr) then Add(Format(OBRIGATORIO,[PFieldName])); end; procedure TosErrorHandlerForm.WarningEmpty(PField: TField; PFieldName: string); begin if IsEmpty(PField) then begin if PFieldName = '' then PFieldName := PField.DisplayLabel; Add(Format(AVISO_OBRIGATORIO,[PFieldName]), etWarning); end; end; procedure TosErrorHandlerForm.FormShow(Sender: TObject); begin if Application.MainForm <> nil then begin Self.Left := Application.MainForm.ClientOrigin.X + Application.MainForm.ClientWidth - Self.Width - 18; Self.Top := Application.MainForm.ClientOrigin.Y + 54; end; end; procedure TosErrorHandlerForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if ((ssAlt in Shift) and (Key = VK_F4)) then Key := 0; end; initialization HError := TosErrorHandlerForm.Create(Application); end.
// // This unit is part of the GLScene Project, http://glscene.org // {: FRMaterialPreview<p> Material Preview frame.<p> <b>Historique : </b><font size=-1><ul> <li>12/07/07 - DaStr - Improved Cross-Platform compatibility (Bugtracker ID = 1684432) <li>06/06/07 - DaStr - Added GLColor to uses (BugtrackerID = 1732211) <li>29/03/07 - DaStr - Renamed LINUX to KYLIX (BugTrackerID=1681585) <li>16/12/06 - DaStr - Editor enhanced <li>03/07/04 - LR - Make change for Linux <li>06/02/00 - Egg - Creation </ul></font> } unit FRMaterialPreview; interface {$i GLScene.inc} uses System.Classes, VCL.Graphics, VCL.Forms, VCL.StdCtrls, VCL.ComCtrls, Vcl.Controls, GLScene, GLObjects, GLTexture, GLHUDObjects, GLViewer, GLTeapot, GLGeomObjects, GLColor, GLWin32Viewer, GLCoordinates, GLCrossPlatform, GLBaseClasses, GLMaterial; type TRMaterialPreview = class(TFrame) GLScene: TGLScene; CBObject: TComboBox; Camera: TGLCamera; Cube: TGLCube; Sphere: TGLSphere; LightSource: TGLLightSource; CBBackground: TComboBox; BackGroundSprite: TGLHUDSprite; Cone: TGLCone; Teapot: TGLTeapot; World: TGLDummyCube; Light: TGLDummyCube; FireSphere: TGLSphere; GLMaterialLibrary: TGLMaterialLibrary; GLSceneViewer: TGLSceneViewer; procedure CBObjectChange(Sender: TObject); procedure CBBackgroundChange(Sender: TObject); procedure SceneViewerMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure SceneViewerMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure SceneViewerMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); private FLibMaterial: TGLAbstractLibMaterial; function GetMaterial: TGLMaterial; procedure SetMaterial(const Value: TGLMaterial); function GetLibMaterial: TGLAbstractLibMaterial; procedure SetLibMaterial(const Value: TGLAbstractLibMaterial); { Private declarations } public { Public declarations } constructor Create(AOwner : TComponent); override; property Material : TGLMaterial read GetMaterial write SetMaterial; property LibMaterial : TGLAbstractLibMaterial read GetLibMaterial write SetLibMaterial; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ {$R *.dfm} var MX, MY: Integer; constructor TRMaterialPreview.Create(AOwner : TComponent); begin inherited; BackGroundSprite.Position.X := GLSceneViewer.Width div 2; BackGroundSprite.Position.Y := GLSceneViewer.Height div 2; BackGroundSprite.Width := GLSceneViewer.Width; BackGroundSprite.Height := GLSceneViewer.Height; CBObject.ItemIndex:=0; CBObjectChange(Self); CBBackground.ItemIndex:=0; CBBackgroundChange(Self); end; procedure TRMaterialPreview.CBObjectChange(Sender: TObject); var i : Integer; begin i:=CBObject.ItemIndex; Cube.Visible := I = 0; Sphere.Visible := I = 1; Cone.Visible := I = 2; Teapot.Visible := I = 3; end; procedure TRMaterialPreview.CBBackgroundChange(Sender: TObject); var bgColor : TColor; begin case CBBackground.ItemIndex of 1 : bgColor:=clWhite; 2 : bgColor:=clBlack; 3 : bgColor:=clBlue; 4 : bgColor:=clRed; 5 : bgColor:=clGreen; else bgColor:=clNone; end; with BackGroundSprite.Material do begin Texture.Disabled:=(bgColor<>clNone); FrontProperties.Diffuse.Color:=ConvertWinColor(bgColor); end; end; procedure TRMaterialPreview.SceneViewerMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if (ssRight in Shift) and (ssLeft in Shift) then Camera.AdjustDistanceToTarget(1 - 0.01 * (MY - Y)) else if (ssRight in Shift) or (ssLeft in Shift) then Camera.MoveAroundTarget(Y - MY, X - MX); MX := X; MY := Y; end; procedure TRMaterialPreview.SceneViewerMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin MX := X; MY := Y; end; procedure TRMaterialPreview.SceneViewerMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); begin Camera.AdjustDistanceToTarget(1 - 0.1 * (Abs(WheelDelta) / WheelDelta)); end; function TRMaterialPreview.GetMaterial: TGLMaterial; begin Result := GLMaterialLibrary.Materials[0].Material; end; procedure TRMaterialPreview.SetMaterial(const Value: TGLMaterial); begin GLMaterialLibrary.Materials[0].Material.Assign(Value.GetActualPrimaryMaterial); end; function TRMaterialPreview.GetLibMaterial: TGLAbstractLibMaterial; begin Result := FLibMaterial; end; procedure TRMaterialPreview.SetLibMaterial(const Value: TGLAbstractLibMaterial); begin FLibMaterial := Value; if Assigned(FLibMaterial) then begin with GLMaterialLibrary.Materials[0] do begin Material.MaterialLibrary := FLibMaterial.MaterialLibrary; Material.LibMaterialName := FLibMaterial.Name end; end else with GLMaterialLibrary.Materials[0] do begin Material.MaterialLibrary := nil; Material.LibMaterialName := ''; end; end; end.
unit UTFrmHistorialSalarios; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, dxSkinsCore, dxSkinBlack, dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMetropolis, dxSkinMetropolisDark, dxSkinMoneyTwins, dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray, dxSkinOffice2013White, dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus, dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinsDefaultPainters, dxSkinValentine, dxSkinVS2010, dxSkinWhiteprint, dxSkinXmas2008Blue, cxGroupBox, cxStyles, dxSkinscxPCPainter, cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator, DB, cxDBData, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, Menus, StdCtrls, cxButtons, ZAbstractRODataset, ZAbstractDataset, ZDataset, cxLabel; type TFrmHistorialSalarios = class(TForm) cxGBDatos: TcxGroupBox; cxGBBotonera: TcxGroupBox; CxGridPersonalImss: TcxGridDBTableView; CxGridMainLevel1: TcxGridLevel; CxGridMain: TcxGrid; ultima: TcxGridDBColumn; SalarioDiario: TcxGridDBColumn; TotalPercepciones: TcxGridDBColumn; CxBtnCerrar: TcxButton; zPersonalImss: TZQuery; dsPersonalImss: TDataSource; CxLbl1: TcxLabel; TotalDeducciones: TcxGridDBColumn; Neto: TcxGridDBColumn; procedure CxBtnCerrarClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public IdPersonal: Integer; { Public declarations } end; var FrmHistorialSalarios: TFrmHistorialSalarios; implementation {$R *.dfm} Uses frm_connection, frmEmpleados; procedure TFrmHistorialSalarios.CxBtnCerrarClick(Sender: TObject); begin if zpersonalimss.RecordCount > 0 then begin //frmEmpleados.frm_Empleados.tdSueldo.Text := zpersonalimss.FieldValues['Neto']; end; Close; end; procedure TFrmHistorialSalarios.FormCreate(Sender: TObject); begin IdPersonal := -1; end; procedure TFrmHistorialSalarios.FormShow(Sender: TObject); var Cursor: TCursor; begin Try Cursor := Screen.Cursor; Screen.Cursor := crAppStart; Try zPersonalImss.Active := False; zPersonalImss.Connection := connection.zConnection; zPersonalImss.Params.ParamByName('personal').AsInteger := IdPersonal; zPersonalImss.Params.ParamByName('CorteOrg').AsInteger := -1; zPersonalImss.Params.ParamByName('Referencia').AsInteger := -1; zPersonalImss.Params.ParamByName('Nomina').AsInteger := -1; zPersonalImss.Params.ParamByName('Agrupa').AsInteger := -1; zPersonalImss.Open; if (zPersonalImss.RecordCount = 0) then begin messageDLG('No se ha calculado la nůmina del empleado!', mtInformation, [mbOk], 0); end; Finally Screen.Cursor := Cursor; End; except on e: Exception Do MessageDlg('Ha ocurrido un error inesperado, informar al administrador del sistema del siguiente error: ' + e.Message, mtError, [mbOK], 0); End; end; end.
unit testbdsvdunit; interface uses Math, Sysutils, Ap, rotations, bdsvd; function TestBDSVD(Silent : Boolean):Boolean; function testbdsvdunit_test_silent():Boolean; function testbdsvdunit_test():Boolean; implementation var FailCount : AlglibInteger; SuccCount : AlglibInteger; procedure FillIdentity(var A : TReal2DArray; N : AlglibInteger);forward; procedure FillSparseDE(var D : TReal1DArray; var E : TReal1DArray; N : AlglibInteger; Sparcity : Double);forward; procedure GetBDSVDError(const D : TReal1DArray; const E : TReal1DArray; N : AlglibInteger; IsUpper : Boolean; const U : TReal2DArray; const C : TReal2DArray; const W : TReal1DArray; const VT : TReal2DArray; var MatErr : Double; var OrtErr : Double; var WSorted : Boolean);forward; procedure TestBDSVDProblem(const D : TReal1DArray; const E : TReal1DArray; N : AlglibInteger; var MatErr : Double; var OrtErr : Double; var WSorted : Boolean; var WFailed : Boolean);forward; (************************************************************************* Testing bidiagonal SVD decomposition subroutine *************************************************************************) function TestBDSVD(Silent : Boolean):Boolean; var D : TReal1DArray; E : TReal1DArray; MEmpty : TReal2DArray; N : AlglibInteger; MaxN : AlglibInteger; I : AlglibInteger; J : AlglibInteger; GPass : AlglibInteger; Pass : AlglibInteger; WasErrors : Boolean; WSorted : Boolean; WFailed : Boolean; FailCase : Boolean; MatErr : Double; OrtErr : Double; Threshold : Double; FailThreshold : Double; FailR : Double; begin FailCount := 0; SuccCount := 0; MatErr := 0; OrtErr := 0; WSorted := True; WFailed := False; WasErrors := False; MaxN := 15; Threshold := 5*100*MachineEpsilon; FailThreshold := 1.0E-2; SetLength(D, MaxN-1+1); SetLength(E, MaxN-2+1); // // special case: fail matrix // N := 5; d[0] := -8.27448347422711894000e-01; d[1] := -8.16705832087160854600e-01; d[2] := -2.53974358904729382800e-17; d[3] := -1.24626684881972815700e+00; d[4] := -4.64744131545637651000e-01; e[0] := -3.25785088656270038800e-01; e[1] := -1.03732413708914436580e-01; e[2] := -9.57365642262031357700e-02; e[3] := -2.71564153973817390400e-01; FailCase := RMatrixBDSVD(D, E, N, True, False, MEmpty, 0, MEmpty, 0, MEmpty, 0); // // special case: zero divide matrix // unfixed LAPACK routine should fail on this problem // N := 7; d[0] := -6.96462904751731892700e-01; d[1] := 0.00000000000000000000e+00; d[2] := -5.73827770385971991400e-01; d[3] := -6.62562624399371191700e-01; d[4] := 5.82737148001782223600e-01; d[5] := 3.84825263580925003300e-01; d[6] := 9.84087420830525472200e-01; e[0] := -7.30307931760612871800e-02; e[1] := -2.30079042939542843800e-01; e[2] := -6.87824621739351216300e-01; e[3] := -1.77306437707837570600e-02; e[4] := 1.78285126526551632000e-15; e[5] := -4.89434737751289969400e-02; RMatrixBDSVD(D, E, N, True, False, MEmpty, 0, MEmpty, 0, MEmpty, 0); // // zero matrix, several cases // I:=0; while I<=MaxN-1 do begin D[I] := 0; Inc(I); end; I:=0; while I<=MaxN-2 do begin E[I] := 0; Inc(I); end; N:=1; while N<=MaxN do begin TestBDSVDProblem(D, E, N, MatErr, OrtErr, WSorted, WFailed); Inc(N); end; // // Dense matrix // N:=1; while N<=MaxN do begin Pass:=1; while Pass<=10 do begin I:=0; while I<=MaxN-1 do begin D[I] := 2*RandomReal-1; Inc(I); end; I:=0; while I<=MaxN-2 do begin E[I] := 2*RandomReal-1; Inc(I); end; TestBDSVDProblem(D, E, N, MatErr, OrtErr, WSorted, WFailed); Inc(Pass); end; Inc(N); end; // // Sparse matrices, very sparse matrices, incredible sparse matrices // N:=1; while N<=MaxN do begin Pass:=1; while Pass<=10 do begin FillSparseDE(D, E, N, 0.5); TestBDSVDProblem(D, E, N, MatErr, OrtErr, WSorted, WFailed); FillSparseDE(D, E, N, 0.8); TestBDSVDProblem(D, E, N, MatErr, OrtErr, WSorted, WFailed); FillSparseDE(D, E, N, 0.9); TestBDSVDProblem(D, E, N, MatErr, OrtErr, WSorted, WFailed); FillSparseDE(D, E, N, 0.95); TestBDSVDProblem(D, E, N, MatErr, OrtErr, WSorted, WFailed); Inc(Pass); end; Inc(N); end; // // report // FailR := AP_Double(FailCount)/(SuccCount+FailCount); WasErrors := AP_FP_Greater(MatErr,Threshold) or AP_FP_Greater(OrtErr,Threshold) or not WSorted or AP_FP_Greater(FailR,FailThreshold); if not Silent then begin Write(Format('TESTING BIDIAGONAL SVD DECOMPOSITION'#13#10'',[])); Write(Format('SVD decomposition error: %5.4e'#13#10'',[ MatErr])); Write(Format('SVD orthogonality error: %5.4e'#13#10'',[ OrtErr])); Write(Format('Singular values order: ',[])); if WSorted then begin Write(Format('OK'#13#10'',[])); end else begin Write(Format('FAILED'#13#10'',[])); end; Write(Format('Always converged: ',[])); if not WFailed then begin Write(Format('YES'#13#10'',[])); end else begin Write(Format('NO'#13#10'',[])); Write(Format('Fail ratio: %5.3f'#13#10'',[ FailR])); end; Write(Format('Fail matrix test: ',[])); if not FailCase then begin Write(Format('AS EXPECTED'#13#10'',[])); end else begin Write(Format('CONVERGED (UNEXPECTED)'#13#10'',[])); end; Write(Format('Threshold: %5.4e'#13#10'',[ Threshold])); if WasErrors then begin Write(Format('TEST FAILED'#13#10'',[])); end else begin Write(Format('TEST PASSED'#13#10'',[])); end; Write(Format(''#13#10''#13#10'',[])); end; Result := not WasErrors; end; procedure FillIdentity(var A : TReal2DArray; N : AlglibInteger); var I : AlglibInteger; J : AlglibInteger; begin SetLength(A, N-1+1, N-1+1); I:=0; while I<=N-1 do begin J:=0; while J<=N-1 do begin if I=J then begin A[I,J] := 1; end else begin A[I,J] := 0; end; Inc(J); end; Inc(I); end; end; procedure FillSparseDE(var D : TReal1DArray; var E : TReal1DArray; N : AlglibInteger; Sparcity : Double); var I : AlglibInteger; J : AlglibInteger; begin SetLength(D, N-1+1); SetLength(E, Max(0, N-2)+1); I:=0; while I<=N-1 do begin if AP_FP_Greater_Eq(RandomReal,Sparcity) then begin D[I] := 2*RandomReal-1; end else begin D[I] := 0; end; Inc(I); end; I:=0; while I<=N-2 do begin if AP_FP_Greater_Eq(RandomReal,Sparcity) then begin E[I] := 2*RandomReal-1; end else begin E[I] := 0; end; Inc(I); end; end; procedure GetBDSVDError(const D : TReal1DArray; const E : TReal1DArray; N : AlglibInteger; IsUpper : Boolean; const U : TReal2DArray; const C : TReal2DArray; const W : TReal1DArray; const VT : TReal2DArray; var MatErr : Double; var OrtErr : Double; var WSorted : Boolean); var I : AlglibInteger; J : AlglibInteger; K : AlglibInteger; LocErr : Double; SM : Double; i_ : AlglibInteger; begin // // decomposition error // LocErr := 0; I:=0; while I<=N-1 do begin J:=0; while J<=N-1 do begin SM := 0; K:=0; while K<=N-1 do begin SM := SM+W[K]*U[I,K]*VT[K,J]; Inc(K); end; if IsUpper then begin if I=J then begin LocErr := Max(LocErr, AbsReal(D[I]-SM)); end else begin if I=J-1 then begin LocErr := Max(LocErr, AbsReal(E[I]-SM)); end else begin LocErr := Max(LocErr, AbsReal(SM)); end; end; end else begin if I=J then begin LocErr := Max(LocErr, AbsReal(D[I]-SM)); end else begin if I-1=J then begin LocErr := Max(LocErr, AbsReal(E[J]-SM)); end else begin LocErr := Max(LocErr, AbsReal(SM)); end; end; end; Inc(J); end; Inc(I); end; MatErr := Max(MatErr, LocErr); // // check for C = U' // we consider it as decomposition error // LocErr := 0; I:=0; while I<=N-1 do begin J:=0; while J<=N-1 do begin LocErr := Max(LocErr, AbsReal(U[I,J]-C[J,I])); Inc(J); end; Inc(I); end; MatErr := Max(MatErr, LocErr); // // orthogonality error // LocErr := 0; I:=0; while I<=N-1 do begin J:=I; while J<=N-1 do begin SM := 0.0; for i_ := 0 to N-1 do begin SM := SM + U[i_,I]*U[i_,J]; end; if I<>J then begin LocErr := Max(LocErr, AbsReal(SM)); end else begin LocErr := Max(LocErr, AbsReal(SM-1)); end; SM := APVDotProduct(@VT[I][0], 0, N-1, @VT[J][0], 0, N-1); if I<>J then begin LocErr := Max(LocErr, AbsReal(SM)); end else begin LocErr := Max(LocErr, AbsReal(SM-1)); end; Inc(J); end; Inc(I); end; OrtErr := Max(OrtErr, LocErr); // // values order error // I:=1; while I<=N-1 do begin if AP_FP_Greater(W[I],W[I-1]) then begin WSorted := False; end; Inc(I); end; end; procedure TestBDSVDProblem(const D : TReal1DArray; const E : TReal1DArray; N : AlglibInteger; var MatErr : Double; var OrtErr : Double; var WSorted : Boolean; var WFailed : Boolean); var U : TReal2DArray; VT : TReal2DArray; C : TReal2DArray; W : TReal1DArray; I : AlglibInteger; J : AlglibInteger; K : AlglibInteger; V : Double; MX : Double; begin MX := 0; I:=0; while I<=N-1 do begin if AP_FP_Greater(AbsReal(D[I]),MX) then begin MX := AbsReal(D[I]); end; Inc(I); end; I:=0; while I<=N-2 do begin if AP_FP_Greater(AbsReal(E[I]),MX) then begin MX := AbsReal(E[I]); end; Inc(I); end; if AP_FP_Eq(MX,0) then begin MX := 1; end; // // Upper BDSVD tests // SetLength(W, N-1+1); FillIdentity(U, N); FillIdentity(VT, N); FillIdentity(C, N); I:=0; while I<=N-1 do begin W[I] := D[I]; Inc(I); end; if not RMatrixBDSVD(W, E, N, True, False, U, N, C, N, VT, N) then begin FailCount := FailCount+1; WFailed := True; Exit; end; GetBDSVDError(D, E, N, True, U, C, W, VT, MatErr, OrtErr, WSorted); FillIdentity(U, N); FillIdentity(VT, N); FillIdentity(C, N); I:=0; while I<=N-1 do begin W[I] := D[I]; Inc(I); end; if not RMatrixBDSVD(W, E, N, True, True, U, N, C, N, VT, N) then begin FailCount := FailCount+1; WFailed := True; Exit; end; GetBDSVDError(D, E, N, True, U, C, W, VT, MatErr, OrtErr, WSorted); // // Lower BDSVD tests // SetLength(W, N-1+1); FillIdentity(U, N); FillIdentity(VT, N); FillIdentity(C, N); I:=0; while I<=N-1 do begin W[I] := D[I]; Inc(I); end; if not RMatrixBDSVD(W, E, N, False, False, U, N, C, N, VT, N) then begin FailCount := FailCount+1; WFailed := True; Exit; end; GetBDSVDError(D, E, N, False, U, C, W, VT, MatErr, OrtErr, WSorted); FillIdentity(U, N); FillIdentity(VT, N); FillIdentity(C, N); I:=0; while I<=N-1 do begin W[I] := D[I]; Inc(I); end; if not RMatrixBDSVD(W, E, N, False, True, U, N, C, N, VT, N) then begin FailCount := FailCount+1; WFailed := True; Exit; end; GetBDSVDError(D, E, N, False, U, C, W, VT, MatErr, OrtErr, WSorted); // // update counter // SuccCount := SuccCount+1; end; (************************************************************************* Silent unit test *************************************************************************) function testbdsvdunit_test_silent():Boolean; begin Result := TestBDSVD(True); end; (************************************************************************* Unit test *************************************************************************) function testbdsvdunit_test():Boolean; begin Result := TestBDSVD(False); end; end.
{$O+,F+} Unit Crc16; Interface { Note: Your crc Variable must be initialized to 0, before } { using tis routine. } { Translated to Turbo Pascal (tm) V4.0 March, 1988 by J.R.Louvau } { Translated to assembler by trixter@oldskool.org 20111106 } Function UpdCrc(cp: Byte; crc: Word): Word; Function CRC16buf(buf:pointer;len:word;seed:word):Word; Implementation (* crctab calculated by Mark G. Mendel, Network Systems Corporation *) Const crctab : Array[0..255] of Word = ( $0000, $1021, $2042, $3063, $4084, $50a5, $60c6, $70e7, $8108, $9129, $a14a, $b16b, $c18c, $d1ad, $e1ce, $f1ef, $1231, $0210, $3273, $2252, $52b5, $4294, $72f7, $62d6, $9339, $8318, $b37b, $a35a, $d3bd, $c39c, $f3ff, $e3de, $2462, $3443, $0420, $1401, $64e6, $74c7, $44a4, $5485, $a56a, $b54b, $8528, $9509, $e5ee, $f5cf, $c5ac, $d58d, $3653, $2672, $1611, $0630, $76d7, $66f6, $5695, $46b4, $b75b, $a77a, $9719, $8738, $f7df, $e7fe, $d79d, $c7bc, $48c4, $58e5, $6886, $78a7, $0840, $1861, $2802, $3823, $c9cc, $d9ed, $e98e, $f9af, $8948, $9969, $a90a, $b92b, $5af5, $4ad4, $7ab7, $6a96, $1a71, $0a50, $3a33, $2a12, $dbfd, $cbdc, $fbbf, $eb9e, $9b79, $8b58, $bb3b, $ab1a, $6ca6, $7c87, $4ce4, $5cc5, $2c22, $3c03, $0c60, $1c41, $edae, $fd8f, $cdec, $ddcd, $ad2a, $bd0b, $8d68, $9d49, $7e97, $6eb6, $5ed5, $4ef4, $3e13, $2e32, $1e51, $0e70, $ff9f, $efbe, $dfdd, $cffc, $bf1b, $af3a, $9f59, $8f78, $9188, $81a9, $b1ca, $a1eb, $d10c, $c12d, $f14e, $e16f, $1080, $00a1, $30c2, $20e3, $5004, $4025, $7046, $6067, $83b9, $9398, $a3fb, $b3da, $c33d, $d31c, $e37f, $f35e, $02b1, $1290, $22f3, $32d2, $4235, $5214, $6277, $7256, $b5ea, $a5cb, $95a8, $8589, $f56e, $e54f, $d52c, $c50d, $34e2, $24c3, $14a0, $0481, $7466, $6447, $5424, $4405, $a7db, $b7fa, $8799, $97b8, $e75f, $f77e, $c71d, $d73c, $26d3, $36f2, $0691, $16b0, $6657, $7676, $4615, $5634, $d94c, $c96d, $f90e, $e92f, $99c8, $89e9, $b98a, $a9ab, $5844, $4865, $7806, $6827, $18c0, $08e1, $3882, $28a3, $cb7d, $db5c, $eb3f, $fb1e, $8bf9, $9bd8, $abbb, $bb9a, $4a75, $5a54, $6a37, $7a16, $0af1, $1ad0, $2ab3, $3a92, $fd2e, $ed0f, $dd6c, $cd4d, $bdaa, $ad8b, $9de8, $8dc9, $7c26, $6c07, $5c64, $4c45, $3ca2, $2c83, $1ce0, $0cc1, $ef1f, $ff3e, $cf5d, $df7c, $af9b, $bfba, $8fd9, $9ff8, $6e17, $7e36, $4e55, $5e74, $2e93, $3eb2, $0ed1, $1ef0 ); (* * updcrc derived from article Copyright (C) 1986 Stephen Satchell. * NOTE: First argument must be in range 0 to 255. * Second argument is referenced twice. * * Programmers may incorporate any or all code into their Programs, * giving proper credit within the source. Publication of the * source routines is permitted so long as proper credit is given * to Stephen Satchell, Satchell Evaluations and Chuck Forsberg, * Omen Technology. *) Function UpdCrc(cp: Byte; crc: Word): Word; begin { UpdCrc } UpdCrc := crctab[((crc SHR 8) and 255)] xor (crc SHL 8) xor cp end; (* Function CRC16buf(buf:pointer;len:word;seed:word):Word; assembler; {this is fugly but I need ds to point to the crc table :-P } asm mov cx,[len] {cx=count. 0=65536 times.} les di,[buf] {es:di points to our data} lea si,crctab {si points to crc table} mov bx,[seed] {bx=tempcrc} @l1: {newcrc := crctab[((oldcrc SHR 8) and 255)] xor (oldcrc SHL 8) xor byte'o'data} {calculate crc table index} xor ax,ax mov ah,bl mov al,es:[di] {ax=(oldcrc shl 8) xor byte'o'data} mov bl,bh xor bh,bh {bx=(oldcrc SHR 8) and 255 } shl bx,1 {bx=bx*2; [bx+si] = value} xor ax,[bx+si] {done!} mov bx,ax {store seed in bx to go again} inc di {advance to next source byte} loop @l1 {result already in ax} end;*) Function CRC16buf(buf:pointer;len:word;seed:word):Word; assembler; {this is fugly but I need ds to point to the crc table :-P } asm mov cx,[len] {cx=count. 0=65536 times.} mov ax,ds mov es,ax lea di,crctab {es:di = points to crc table} mov bx,[seed] {bx=tempcrc} push ds lds si,[buf] {ds:si points to our data} @l1: {newcrc := crctab[((oldcrc SHR 8) and 255)] xor (oldcrc SHL 8) xor byte'o'data} {calculate crc table index} mov ah,bl lodsb {ax=(oldcrc shl 8) xor byte'o'data} mov bl,bh xor bh,bh {bx=(oldcrc SHR 8) and 255 } shl bx,1 {bx=bx*2; es:[bx+di] = value} xor ax,es:[bx+di] {done!} mov bx,ax {store seed in bx to go again} loop @l1 pop ds {result already in ax} end; end. {Unit}
unit JD.Weather.OpenWeatherMaps; interface uses System.Classes, System.SysUtils, System.Generics.Collections, Vcl.Graphics, Vcl.Imaging.Jpeg, Vcl.Imaging.PngImage, Vcl.Imaging.GifImg, JD.Weather, JD.Weather.Intf, SuperObject; type TOWMEndpoint = (oeConditions, oeForecast, oeAlerts, oeMaps); TOWMWeatherThread = class(TJDWeatherThread) public function GetEndpointUrl(const Endpoint: TOWMEndpoint): String; public function GetUrl: String; override; function DoAll(Conditions: TWeatherConditions; Forecast: TWeatherForecast; ForecastDaily: TWeatherForecast; ForecastHourly: TWeatherForecast; Alerts: TWeatherAlerts; Maps: TWeatherMaps): Boolean; override; function DoConditions(Conditions: TWeatherConditions): Boolean; override; function DoForecast(Forecast: TWeatherForecast): Boolean; override; function DoForecastHourly(Forecast: TWeatherForecast): Boolean; override; function DoForecastDaily(Forecast: TWeatherForecast): Boolean; override; function DoAlerts(Alerts: TWeatherAlerts): Boolean; override; function DoMaps(Maps: TWeatherMaps): Boolean; override; end; implementation uses DateUtils, StrUtils, Math; { TOWMWeatherThread } function TOWMWeatherThread.GetEndpointUrl(const Endpoint: TOWMEndpoint): String; begin case Endpoint of oeConditions: Result:= 'weather'; oeForecast: Result:= 'forecast'; oeAlerts: Result:= 'alerts'; //TODO oeMaps: Result:= 'maps'; //TODO end; Result:= GetUrl + Result + '?appid='+Owner.Key; case Owner.Units of wuKelvin: ; wuImperial: Result:= Result + '&units=imperial'; wuMetric: Result:= Result + '&units=metric'; end; end; function TOWMWeatherThread.GetUrl: String; begin Result:= 'http://api.openweathermap.org/data/2.5/'; end; function TOWMWeatherThread.DoAlerts(Alerts: TWeatherAlerts): Boolean; begin Result:= False; //NOT SUPPORTED end; function TOWMWeatherThread.DoAll(Conditions: TWeatherConditions; Forecast, ForecastDaily, ForecastHourly: TWeatherForecast; Alerts: TWeatherAlerts; Maps: TWeatherMaps): Boolean; begin Result:= False; end; function TOWMWeatherThread.DoConditions( Conditions: TWeatherConditions): Boolean; begin Result:= False; end; function TOWMWeatherThread.DoForecast(Forecast: TWeatherForecast): Boolean; begin Result:= False; end; function TOWMWeatherThread.DoForecastDaily(Forecast: TWeatherForecast): Boolean; begin Result:= False; end; function TOWMWeatherThread.DoForecastHourly( Forecast: TWeatherForecast): Boolean; begin Result:= False; end; function TOWMWeatherThread.DoMaps(Maps: TWeatherMaps): Boolean; begin Result:= False; end; end.
program simplify; //Example program to simplify meshes // https://github.com/neurolabusc/Fast-Quadric-Mesh-Simplification-Pascal- //To compile // fpc -O3 -XX -Xs simplify.pas //On OSX to explicitly compile as 64-bit // ppcx64 -O3 -XX -Xs simplify.pas //With Delphi // >C:\PROGRA~2\BORLAND\DELPHI7\BIN\dcc32 -CC -B simplify.pas //To execute // ./simplify bunny.obj out.obj 0.2 {$IFDEF FPC}{$mode objfpc}{$H+}{$ENDIF} uses {$IFDEF FPC} mz3, {$IFNDEF DARWIN}DateUtils, {$ENDIF}{$ELSE} Windows, {$ENDIF} Classes, meshify_simplify_quadric, obj, sysutils, mergevertices, math; procedure ShowHelp; begin {$IFDEF FPC} writeln('Usage: '+paramstr(0)+' <input> <output> <ratio> <agressiveness)'); writeln(' Input: name of existing MZ3 or OBJ format mesh'); writeln(' Output: name for decimated MZ3 or OBJ format mesh'); writeln(' Ratio: (default = 0.2) for example 0.1 will decimate 90% of triangles'); writeln(' A ratio of 1 is "lossless" (though beware of pole artifacts) '); writeln(' A ratio of 2 only removes repeated vertices'); writeln(' A ratio of 3 only removes of replicated vertices and faces (slow)'); writeln(' A ratio of 4 makes no change (file conversion only)'); writeln(' Agressiveness: (default = 3.0) faster (9) or better decimation (1)'); writeln(' Tolerance: (default = 0.0) vertices closer to each other than this distance will be merged'); writeln('Notes:'); writeln(' The OBJ format is popular and useful for sharing files'); writeln(' The MZ3 format is creates more compact files'); writeln('Examples:'); {$IFDEF UNIX} writeln(' '+paramstr(0)+' ~/dir/in.mz3 ~/dir/out.mz3 0.2'); writeln(' '+paramstr(0)+' ~/dir/bunny.obj ~/dir/out.obj 0.2'); writeln(' '+paramstr(0)+' ~/dir/bunny.obj ~/dir/out.mz3 0.2'); {$ELSE} writeln(' '+paramstr(0)+' c:\dir\in.mz3 c:\dir\out.mz3 0.2'); writeln(' '+paramstr(0)+' c:\dir\bunny.obj c:\dir\out.obj 0.2'); writeln(' '+paramstr(0)+' c:\dir\bunny.obj c:\dir\out.mz3 0.2'); {$ENDIF} {$ELSE} //if FPC else Delphi - Delphi does not support ZStreams writeln('Usage: '+paramstr(0)+' <input> <output> <ratio> <agressiveness)'); writeln(' Input: name of existing OBJ format mesh'); writeln(' Output: name for decimated OBJ format mesh'); writeln(' Ratio: (default = 0.2) for example 0.1 will decimate 90% of triangles'); writeln(' Agressiveness: (default = 2.0) faster (9) or better decimation (1)'); writeln('Example:'); writeln(' '+paramstr(0)+' c:\dir\bunny.obj c:\dir\out.obj 0.2'); {$ENDIF} end; procedure printf(s: string); //for GUI applications, this would call showmessage or memo1.lines.add begin writeln(s); end; {$IFDEF FPC} function isMz3(filename: string): boolean; begin result := upcase(ExtractFileExt(filename)) = '.MZ3'; end; {$ENDIF} function RemoveDegenerateTriangles(var faces: TFaces): integer; var nOK, n,i: integer; f: TFaces; begin result := 0; //EXIT_SUCCESS - no change n := length(faces); if n < 1 then exit; nOK := 0; for i := 0 to (n-1) do if (faces[i].x <> faces[i].y) and (faces[i].x <> faces[i].z) and (faces[i].y <> faces[i].z) then nOK := nOK + 1; //printf(format(' %d degenerate triangles', [n - nOK])); if (nOK = n) then exit; if (nOK = 0) then exit; //nothing survives! result := n - nOK; //report number of faces removed setlength(f,n); f := Copy(faces, Low(faces), Length(faces)); setlength(faces,nOK); nOK := 0; for i := 0 to (n-1) do if (faces[i].x <> faces[i].y) and (faces[i].x <> faces[i].z) and (faces[i].y <> faces[i].z) then begin faces[nOK] := f[i]; nOK := nOK + 1; end; end; //end RemoveDegenerateTriangles() function RemoveReplicatedTriangles(var faces: TFaces): integer; var nOK, nBad, n, i, j: integer; bad, winding: array of boolean; lo,hi, mid: array of integer; f: TFaces; begin result := 0; //EXIT_SUCCESS - no change n := length(faces); if n < 2 then exit; setlength(bad, n); for i := 0 to (n-1) do bad[i] := false; setlength(lo, n); setlength(mid, n); setlength(hi, n); setlength(winding, n); for i := 0 to (n-1) do begin lo[i] := min(min(faces[i].x, faces[i].y), faces[i].z); hi[i] := max(max(faces[i].x, faces[i].y), faces[i].z); mid[i] := (faces[i].x + faces[i].y + faces[i].z) - hi[i] - lo[i]; if faces[i].x = lo[i] then j := faces[i].y - faces[i].x else if faces[i].y = lo[i] then j := faces[i].z - faces[i].y else j := faces[i].x - faces[i].z; winding[i] := (j > 0); end; for i := 0 to (n-2) do for j := (i + 1) to (n - 1) do if (lo[i] = lo[j]) and (mid[i] = mid[j]) and (hi[i] = hi[j]) and (winding[i] = winding[j]) then bad[j] := true; setlength(lo,0); setlength(mid,0); setlength(hi,0); setlength(winding, 0); nBad := 0; for i := 0 to (n-1) do if bad[i] then nBad := nBad + 1; //printf(format(' %d replicated triangles', [nBad])); result := nBad; if nBad = 0 then exit; setlength(f,n); f := Copy(faces, Low(faces), Length(faces)); nOK := n - nBad; setlength(faces,nOK); nOK := 0; for i := 0 to (n-1) do if not bad[i] then begin faces[nOK] := f[i]; nOK := nOK + 1; end; setlength(f,0); setlength(bad,0); end; procedure DecimateMesh(inname, outname: string; ratio, agress, tolerance: single); var targetTri, startTri, n: integer; faces: TFaces; vertices: TVertices; {$IFDEF FPC} {$IFDEF DARWIN} msec: qWord;{$ELSE} msec: Int64; tic :TDateTime; {$ENDIF} {$ELSE} msec: dWord; {$ENDIF} begin {$IFDEF FPC} if isMz3(inname) then LoadMz3(inname, faces, vertices) else {$ENDIF} LoadObj(inname, faces, vertices); printf(format(' simplify %s with ratio = %.2f, agressiveness = %.2f and tol = %.5f', [inname, ratio, agress, tolerance ])); printf(format(' Input: %d vertices, %d triangles', [length(vertices), length(faces)])); if (ratio >= 4.0) then begin //pure conversion if length(outname) <= 0 then exit; printf(' Creating file '+ outname); {$IFDEF FPC} if isMz3(outname) then SaveMz3(outname, faces, vertices) else {$ENDIF} SaveObj(outname, faces, vertices); exit; end; targetTri := round(length(faces) * ratio); startTri := length(faces); if (targetTri < 0) or (length(faces) < 1) or (length(vertices) < 3) then begin printf('Unable to load the mesh'); exit; end; {$IFDEF FPC} {$IFDEF DARWIN} msec := GetTickCount64(); {$ELSE}tic := Now();{$ENDIF} {$ELSE} msec := GetTickCount();{$ENDIF} UnifyVertices(faces, vertices, tolerance); //remove duplicated or virtually duplicated vertices n := RemoveDegenerateTriangles(faces); if (n > 0) then printf(format(' Removed %d degenerate triangles', [n])); if (ratio >= 3.0) then begin n := RemoveReplicatedTriangles(faces); printf(format(' Removed %d replicated triangles', [n])); end; if ratio = 1 then printf('Lossless compression only') else begin //simplify_mesh_lossless(faces, vertices); //run lossless before simplify - see if free savings simplify_mesh(faces, vertices, targetTri, agress); end; if ratio <= 1 then simplify_mesh_lossless(faces, vertices); //run lossless after simplify - see if free savings left {$IFDEF FPC} {$IFDEF DARWIN} msec := GetTickCount64()-msec; {$ELSE}msec := MilliSecondsBetween(Now(),tic);{$ENDIF} {$ELSE} msec := GetTickCount() - msec; {$ENDIF} printf(format(' Output: %d vertices, %d triangles (%.3f, %.2fsec)', [length(vertices), length(faces), length(Faces)/startTri, msec*0.001 ])); if length(outname) > 0 then begin printf(' Creating file '+ outname); {$IFDEF FPC} if isMz3(outname) then SaveMz3(outname, faces, vertices) else {$ENDIF} SaveObj(outname, faces, vertices); end; setlength(faces,0); setlength(vertices,0); end; procedure ParseCmds; var inname, outname: string; ratio, agress, tolerance: single; begin printf('Mesh Simplification (C)2014 by Sven Forstmann, MIT License '+{$IFDEF CPU64}'64-bit'{$ELSE}'32-bit'{$ENDIF}); if ParamCount < 1 then begin ShowHelp; exit; end; inname := paramstr(1); if ParamCount < 2 then begin {$IFDEF FPC} outname := ChangeFileExt(inname, '_simple.mz3'); {$ELSE} outname := ChangeFileExt(inname, '_simple.obj'); {$ENDIF} end else outname := paramstr(2); ratio := 0.2; if ParamCount > 2 then ratio := StrToFloatDef(paramstr(3),0.5); if (ratio <= 0.0) then begin printf('Ratio must be more than zero.'); exit; end; agress := 3.0; if ParamCount > 3 then agress := StrToFloatDef(paramstr(4), 3.0); tolerance := 0; if ParamCount > 4 then tolerance := StrToFloatDef(paramstr(5), 0.0); DecimateMesh(inname, outname, ratio, agress, tolerance); end; begin ParseCmds; end.
unit buku_handler; interface uses tipe_data; { KONSTANTA } const nmax = 1000; // Asumsi bahwa size terbesar dari database adalah 1000 { DEKLARASI TIPE } type buku = record ID_Buku, Judul_Buku, Author, Jumlah_Buku, Tahun_Penerbit, Kategori : string; end; tabel_buku = record t: array [0..nmax] of buku; sz: integer; // effective size end; { DEKLARASI FUNGSI DAN PROSEDUR } function tambah(s: arr_str): tabel_buku; procedure cetak(data_tempbuku: tabel_buku); function konversi_csv(data_tempbuku: tabel_buku): arr_str; { IMPLEMENTASI FUNGSI DAN PROSEDUR } implementation function tambah(s: arr_str): tabel_buku; { DESKRIPSI : Memasukkan data dari array of string kedalam tabel_buku } { PARAMETER : array of string } { RETURN : data buku } { KAMUS LOKAL } var col, row: integer; temp: string; c: char; data_tempbuku : tabel_buku; { ALGORITMA } begin data_tempbuku.sz := 0; for row:=0 to s.sz-1 do begin col := 0; temp := ''; // Membaca baris dan memisahkan tiap kolom setiap kali mendapatkan karakter ',' // data di indeks ke-0 merupakan header for c in s.st[row] do begin if(c=',') then // Jika ketemu koma, maka masukkan data ke kolom begin // 0 based indexing case col of 0: data_tempbuku.t[data_tempbuku.sz].ID_Buku := temp; 1: data_tempbuku.t[data_tempbuku.sz].Judul_Buku := temp; 2: data_tempbuku.t[data_tempbuku.sz].Author := temp; 3: data_tempbuku.t[data_tempbuku.sz].Jumlah_Buku := temp; 4: data_tempbuku.t[data_tempbuku.sz].Tahun_Penerbit := temp; end; col := col+1; temp := ''; end else temp := temp+c; // Jika belum ketemu koma, maka tambahkan tambahkan karakter ke string untuk data di kolom selanjutnya end; // Kolom terakhir data_tempbuku.t[data_tempbuku.sz].Kategori := temp; data_tempbuku.sz := data_tempbuku.sz+1; end; tambah := data_tempbuku; end; function konversi_csv(data_tempbuku: tabel_buku): arr_str; { DESKRIPSI : Fungsi untuk mengubah data buku menjadi array of string } { PARAMETER : data buku } { RETURN : array of string } { KAMUS LOKAL } var i : integer; ret : arr_str; { ALGORITMA } begin ret.sz := data_tempbuku.sz; for i:=0 to data_tempbuku.sz do begin ret.st[i] := data_tempbuku.t[i].ID_Buku + ',' + data_tempbuku.t[i].Judul_Buku + ',' + data_tempbuku.t[i].Author + ',' + data_tempbuku.t[i].Jumlah_Buku + ','+ data_tempbuku.t[i].Tahun_Penerbit + ',' + data_tempbuku.t[i].Kategori; end; konversi_csv := ret; end; procedure cetak(data_tempbuku: tabel_buku); // for debugging { DESKRIPSI : Prosedur sederhana yang digunakan pada proses pembuatan program untuk debugging, prosedur ini mencetak data ke layar } { PARAMETER : Data yang akan dicetak } { KAMUS LOKAL } var i: integer; { ALGORITMA } begin for i:=0 to data_tempbuku.sz-1 do begin writeln(data_tempbuku.t[i].ID_Buku, ' | ', data_tempbuku.t[i].Judul_Buku, ' | ', data_tempbuku.t[i].Author, ' | ', data_tempbuku.t[i].Jumlah_Buku, ' | ', data_tempbuku.t[i].Tahun_Penerbit, ' | ', data_tempbuku.t[i].Kategori); end; end; end.
UNIT SaveScrn; {saves and restores a text screen} interface uses CRT, DOS; PROCEDURE SaveScreen; PROCEDURE RestoreScreen; implementation TYPE ScrnBlock = ARRAY[1..2000] of Integer; VAR Screen : ^ScrnBlock; ScreenData : ScrnBlock; I : Byte; Regs : Registers; PROCEDURE SaveScreen; BEGIN Intr($11,Regs); IF (Lo(Regs.AX) AND $30) = $30 THEN Screen := Ptr($B000,0) ELSE Screen := Ptr($B800,0); ScreenData := Screen^; End; PROCEDURE RestoreScreen; BEGIN Screen^ := ScreenData; END; BEGIN END.
{*******************************************************} { } { Borland Delphi Visual Component Library } { } { Copyright (c) 1995,99 Inprise Corporation } { } {*******************************************************} unit CtlPanel; interface uses SysUtils, Classes, Forms, Windows, Graphics, cpl, Dialogs; type EAppletException = class(Exception); TInitEvent = procedure (Sender: TObject; var AppInitOK: Boolean) of object; TCountEvent = procedure (Sender: TObject; var AppCount: Integer) of object; TExitEvent = TNotifyEvent; TSetupEvent = TNotifyEvent; TActivateEvent = procedure (Sender: TObject; Data: LongInt) of object; TStopEvent = procedure (Sender: TObject; Data: LongInt) of object; TInquireEvent = procedure (Sender: TObject; var idIcon: Integer; var idName: Integer; var idInfo: Integer; var lData: Integer) of object; TNewInquireEvent = procedure (Sender: TObject; var lData: Integer; var hIcon: HICON; var AppletName: string; var AppletInfo: string) of object; TStartWParmsEvent = procedure (Sender: TObject; Params: string) of object; TAppletModule = class(TDataModule) private FOnActivate: TActivateEvent; FOnStop: TStopEvent; FOnInquire: TInquireEvent; FOnNewInquire: TNewInquireEvent; FOnStartWParms: TStartWParmsEvent; FData: LongInt; FResidIcon: Integer; FResidName: Integer; FResidInfo: Integer; FAppletIcon: TIcon; FCaption: string; FHelp: string; procedure SetData(const Value: LongInt); procedure SetResidIcon(const Value: Integer); procedure SetResidInfo(const Value: Integer); procedure SetResidName(const Value: Integer); procedure SetAppletIcon(const Value: TIcon); procedure SetCaption(const Value: string); procedure SetHelp(const Value: string); function GetCaption: string; protected procedure DoStop(Data: LongInt); dynamic; procedure DoActivate(Data: LongInt); dynamic; procedure DoInquire(var ACPLInfo: TCPLInfo); dynamic; procedure DoNewInquire(var ANewCPLInfo: TNewCPLInfo); dynamic; procedure DoStartWParms(Params: string); dynamic; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Data: LongInt read FData write SetData; published property OnStop: TStopEvent read FOnStop write FOnStop; property OnActivate: TActivateEvent read FOnActivate write FOnActivate; property OnInquire: TInquireEvent read FOnInquire write FOnInquire; property OnNewInquire: TNewInquireEvent read FOnNewInquire write FOnNewInquire; property OnStartWParms: TStartWParmsEvent read FOnStartWParms write FOnStartWParms; property Caption: string read GetCaption write SetCaption; property AppletIcon: TIcon read FAppletIcon write SetAppletIcon; property Help: string read FHelp write SetHelp; property ResidIcon: Integer read FResidIcon write SetResidIcon; property ResidName: Integer read FResidName write SetResidName; property ResidInfo: Integer read FResidInfo write SetResidInfo; end; TAppletModuleClass = class of TAppletModule; TCPLAppletClass = class of TAppletModule; TDataModuleClass = class of TDataModule; TAppletApplication = class(TComponent) private FComponentClass: TComponentClass; FControlPanelHandle: THandle; FModules: TList; FOnInit: TInitEvent; FOnCount: TCountEvent; FOnExit: TExitEvent; FOnSetup: TSetupEvent; FModuleCount: Integer; procedure OnExceptionHandler(Sender: TObject; E: Exception); function GetModules(Index: Integer): TAppletModule; procedure SetModules(Index: Integer; const Value: TAppletModule); procedure SetModuleCount(const Value: Integer); function GetModuleCount: Integer; protected procedure DoHandleException(E: Exception); dynamic; procedure DoInit(var AppInitOK: Boolean); dynamic; procedure DoCount(var AppCount: Integer); dynamic; procedure DoExit; dynamic; procedure DoSetup; dynamic; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure CreateForm(InstanceClass: TComponentClass; var Reference); virtual; procedure Initialize; virtual; procedure Run; virtual; property Modules[Index: Integer]: TAppletModule read GetModules write SetModules; property ModuleCount: Integer read GetModuleCount write SetModuleCount; property ControlPanelHandle: THandle read FControlPanelHandle; property OnInit: TInitEvent read FOnInit write FOnInit; property OnCount: TCountEvent read FOnCount write FOnCount; property OnExit: TExitEvent read FOnExit write FOnExit; property OnSetup: TSetupEvent read FOnSetup write FOnSetup; end; function CPlApplet(hwndCPl: THandle; uMsg: DWORD; lParam1, lParam2: Longint): Longint; stdcall; var Application: TAppletApplication = nil; implementation { TAppletApp } resourcestring sInvalidClassReference = 'Invalid class reference for TAppletApplication'; constructor TAppletApplication.Create(AOwner: TComponent); begin inherited Create(AOwner); FModules := TList.Create; end; procedure TAppletApplication.CreateForm(InstanceClass: TComponentClass; var Reference); begin if InstanceClass.InheritsFrom(TCustomForm) or InstanceClass.InheritsFrom(TDataModule) then begin if (FComponentClass = nil) or (FComponentClass <> InstanceClass) then FComponentClass := TComponentClass(InstanceClass); TComponent(Reference) := FComponentClass.Create(Self); end else raise Exception.CreateRes(@sInvalidClassReference); end; destructor TAppletApplication.Destroy; begin while FModules.Count > 0 do TObject(FModules[0]).Free; FModules.Free; Forms.Application.OnException := nil; inherited Destroy; end; procedure TAppletApplication.DoCount(var AppCount: Integer); begin if assigned(FOnCount) then FOnCount(Self, AppCount); end; procedure TAppletApplication.DoExit; begin if assigned(FOnExit) then FOnExit(Self); end; procedure TAppletApplication.DoHandleException(E: Exception); begin end; procedure TAppletApplication.DoInit(var AppInitOK: Boolean); begin if assigned(FOnInit) then FOnInit(Self, AppInitOK); end; procedure TAppletApplication.DoSetup; begin if assigned(FOnSetup) then FOnSetup(Self); end; function TAppletApplication.GetModuleCount: Integer; begin Result := FModules.Count; end; function TAppletApplication.GetModules(Index: Integer): TAppletModule; begin Result := FModules[Index]; end; procedure TAppletApplication.Initialize; begin end; procedure TAppletApplication.OnExceptionHandler(Sender: TObject; E: Exception); begin DoHandleException(E); end; procedure TAppletApplication.Run; begin Forms.Application.OnException := OnExceptionHandler; end; procedure InitApplication; begin Application := TAppletApplication.Create(nil); end; procedure DoneApplication; begin Application.Free; Application := nil; end; function CPlApplet(hwndCPl: THandle; uMsg: DWORD; lParam1, lParam2: Longint): Longint; var Temp: Boolean; begin Result := 0; Temp := True; with Application, Application.Modules[lParam1] do begin FControlPanelHandle := hwndCPl; case (umsg) of CPL_INIT : DoInit(Temp); CPL_GETCOUNT: begin Result := ModuleCount; DoCount(Result); Exit; end; CPL_INQUIRE : DoInquire(PCplInfo(lParam2)^); CPL_NEWINQUIRE : DoNewInquire(PNewCPLInfo(lParam2)^); CPL_DBLCLK : DoActivate(LongInt(lParam2)); CPL_STOP : DoStop(LongInt(LParam2)); CPL_EXIT : DoExit; CPL_STARTWPARMS : DoStartWParms(PChar(LParam2)); CPL_SETUP : DoSetup; end; end; Result := Integer(Temp); end; constructor TAppletModule.Create(AOwner: TComponent); begin FAppletIcon := TIcon.Create; inherited Create(AOwner); Application.FModules.Add(Self); end; destructor TAppletModule.Destroy; begin FAppletIcon.Free; Application.FModules.Delete(Application.FModules.IndexOf(Self)); inherited Destroy; end; function TAppletModule.GetCaption: string; begin if FCaption <> '' then Result := FCaption else Result := Name; end; procedure TAppletModule.DoActivate(Data: Integer); begin if assigned(FOnActivate) then FOnActivate(Self, Data); end; procedure TAppletModule.DoInquire(var ACPLInfo: TCPLInfo); begin with ACPLInfo do begin idIcon := FResidIcon; idName := FResidName; idInfo := FResidInfo; lData := FData; end; if assigned(FOnInquire) then with ACPLInfo do FOnInquire(Self, idIcon, idName, idInfo, lData); end; procedure TAppletModule.DoNewInquire(var ANewCPLInfo: TNewCPLInfo); begin with ANewCPLInfo do begin dwSize := SizeOf(TNewCPLInfo); lData := FData; if (FResidIcon = CPL_DYNAMIC_RES) then hIcon := FAppletIcon.Handle else hIcon := LoadIcon(hInstance, MakeIntResource(FResidIcon)); end; if assigned(fOnNewInquire) then with ANewCPLInfo do FOnNewInquire(Self, lData, hIcon, FCaption, FHelp); if (FResidName = CPL_DYNAMIC_RES) then StrLCopy(ANewCPLInfo.szName, PChar(FCaption), SizeOf(ANewCPLInfo.szName)) else StrLCopy(ANewCPLInfo.szName, PChar(LoadStr(FResidName)), SizeOf(ANewCPLInfo.szName)); if (FResidInfo = CPL_DYNAMIC_RES) then StrLCopy(ANewCPLInfo.szInfo, PChar(FHelp), SizeOf(ANewCPLInfo.szInfo)) else StrLCopy(ANewCPLInfo.szInfo, PChar(LoadStr(FResidInfo)), SizeOf(ANewCPLInfo.szInfo)); end; procedure TAppletModule.DoStartWParms(Params: string); begin if assigned(FOnStartWParms) then FOnStartWParms(Self, Params); end; procedure TAppletModule.DoStop(Data: Integer); begin if assigned(FOnStop) then FOnStop(Self, Data); end; procedure TAppletModule.SetAppletIcon(const Value: TIcon); begin if FAppletIcon <> Value then begin FAppletIcon.Assign(Value); ResidIcon := CPL_DYNAMIC_RES; end; end; procedure TAppletModule.SetCaption(const Value: string); begin if FCaption <> Value then begin if Value = '' then FCaption := Name else FCaption := Value; FResidName := CPL_DYNAMIC_RES; end; end; procedure TAppletModule.SetData(const Value: Integer); begin if FData <> Value then FData := Value; end; procedure TAppletModule.SetHelp(const Value: string); begin if FHelp <> Value then begin FHelp := Value; FResidInfo := CPL_DYNAMIC_RES; end; end; procedure TAppletModule.SetResidIcon(const Value: Integer); begin if FResidIcon <> Value then FResidIcon := Value; end; procedure TAppletModule.SetResidInfo(const Value: Integer); begin if FResidInfo <> Value then begin FResidInfo := Value; FHelp := ''; end; end; procedure TAppletModule.SetResidName(const Value: Integer); begin if FResidName <> Value then begin FResidName := Value; FCaption := ''; end; end; procedure TAppletApplication.SetModuleCount(const Value: Integer); begin if FModuleCount <> Value then FModuleCount := Value; end; procedure TAppletApplication.SetModules(Index: Integer; const Value: TAppletModule); begin if FModules[Index] <> Value then FModules[Index] := Value; end; initialization InitApplication; finalization DoneApplication; end.
unit Group; interface type TGroupAttributes = class strict private FMaxTotalAmount: real; FMaxConcurrent: integer; FIdentityDocs: integer; private function GetHasConcurrent: boolean; public property MaxTotalAmount: real read FMaxTotalAmount write FMaxTotalAmount; property MaxConcurrent: integer read FMaxConcurrent write FMaxConcurrent; property IdentityDocs: integer read FIdentityDocs write FIdentityDocs; property HasConcurrent: boolean read GetHasConcurrent; end; type TGroup = class(TObject) private FGroupId: string; FGroupName: string; FParentGroupId: string; FIsGov: integer; FIsActive: integer; FAttributes: TGroupAttributes; FLocation: string; function GetIsGov: boolean; function GetHasParent: boolean; public procedure SaveChanges(const gr: TObject); property GroupId: string read FGroupId write FGroupId; property GroupName: string read FGroupName write FGroupName; property ParentGroupId: string read FParentGroupId write FParentGroupId; property IsGov: integer read FIsGov write FIsGov; property IsPublic: boolean read GetIsGov; property HasParent: boolean read GetHasParent; property IsActive: integer read FIsActive write FIsActive; property Attributes: TGroupAttributes read FAttributes write FAttributes; property Location: string read FLocation write FLocation; procedure GetAttributes; class procedure AddAttributes; end; var grp: TGroup; groups: array of TGroup; implementation uses EntitiesData; procedure TGroup.SaveChanges(const gr: TObject); begin with dmEntities.dstGroups do begin Edit; FieldByName('par_grp_id').AsString := TGroup(gr).FParentGroupId; FieldByName('is_active').AsInteger := TGroup(gr).FIsActive; Post; end; end; function TGroup.GetIsGov: boolean; begin Result := FIsGov = 1; end; class procedure TGroup.AddAttributes; begin dmEntities.dstGroupAttribute.Append; end; procedure TGroup.GetAttributes; begin // locate the attributes dataset // append when necessary .. only append if group is a PARENT with dmEntities.dstGroupAttribute do begin if not Locate('grp_id',FGroupId,[]) then Append end; end; function TGroup.GetHasParent: boolean; begin Result := FParentGroupId <> ''; end; { TGroupAttributes } function TGroupAttributes.GetHasConcurrent: boolean; begin Result := FMaxConcurrent > 0; end; end.
// // Copyright (c) 2009-2010 Mikko Mononen memon@inside.org // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // {$POINTERMATH ON} unit RN_RecastAlloc; interface uses RN_Helper; type TrcAllocHint = ( RC_ALLOC_PERM, ///< Memory will persist after a function call. RC_ALLOC_TEMP ///< Memory used temporarily within a function. ); PrcIntArray = ^TrcIntArray; TrcIntArray = record private m_size, m_cap: Integer; function GetItem(i: Integer): Integer; procedure SetItem(i: Integer; const Value: Integer); public m_data: PInteger; constructor Create(n: Integer); procedure Free; // Delphi: Records do not have automatic destructor, we need to dispose of allocated buffer manualy procedure Push(aValue: Integer); function Pop: Integer; procedure resize(n: Integer); property Item[i: Integer]: Integer read GetItem write SetItem; default; // Return Pointer because we cant edit values from getter property size: Integer read m_size; end; TArrayOfTrcIntArray = array of TrcIntArray; implementation {static void *rcAllocDefault(int size, rcAllocHint) { return malloc(size); } {static void rcFreeDefault(void *ptr) { free(ptr); } {static rcAllocFunc* sRecastAllocFunc = rcAllocDefault; static rcFreeFunc* sRecastFreeFunc = rcFreeDefault; /// @see rcAlloc, rcFree void rcAllocSetCustom(rcAllocFunc *allocFunc, rcFreeFunc *freeFunc) { sRecastAllocFunc = allocFunc ? allocFunc : rcAllocDefault; sRecastFreeFunc = freeFunc ? freeFunc : rcFreeDefault; } /// @see rcAllocSetCustom {void* rcAlloc(int size, rcAllocHint hint) { return sRecastAllocFunc(size, hint); } /// @par /// /// @warning This function leaves the value of @p ptr unchanged. So it still /// points to the same (now invalid) location, and not to null. /// /// @see rcAllocSetCustom {void rcFree(void* ptr) { if (ptr) sRecastFreeFunc(ptr); } constructor TrcIntArray.Create(n: Integer); begin m_data := nil; m_size := 0; m_cap := 0; resize(n); end; procedure TrcIntArray.Free; begin FreeMem(m_data); end; function TrcIntArray.Pop: Integer; begin if (m_size > 0) then Dec(m_size); Result := m_data[m_size]; end; procedure TrcIntArray.Push(aValue: Integer); begin resize(m_size+1); m_data[m_size-1] := aValue; end; /// @class rcIntArray /// /// While it is possible to pre-allocate a specific array size during /// construction or by using the #resize method, certain methods will /// automatically resize the array as needed. /// /// @warning The array memory is not initialized to zero when the size is /// manually set during construction or when using #resize. /// @par /// /// Using this method ensures the array is at least large enough to hold /// the specified number of elements. This can improve performance by /// avoiding auto-resizing during use. procedure TrcIntArray.resize(n: Integer); var newData: PInteger; begin if (n > m_cap) then begin if (m_cap = 0) then m_cap := n; while (m_cap < n) do m_cap := m_cap * 2; GetMem(newData, m_cap * sizeof(Integer)); if (m_size <> 0) and (newData <> nil) then Move(m_data^, newData^, m_size*sizeof(integer)); FreeMem(m_data); m_data := newData; end; m_size := n; end; function TrcIntArray.GetItem(i: Integer): Integer; begin Result := m_data[i]; end; procedure TrcIntArray.SetItem(i: Integer; const Value: Integer); begin m_data[i] := Value; end; end.
unit uThreadImportacao; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, JvExStdCtrls, JvGroupBox, ExtCtrls, IOUtils, FMTBcd, DB, SqlExpr, DateUtils, xmldom, XMLIntf, msxmldom, XMLDoc, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, jpeg, StrUtils, PngImage, ActiveX, DBXCommon, SyncObjs, DBClient, Provider; type TRGBArray = array[Word] of TRGBTriple; pRGBArray = ^TRGBArray; type TDefaultXML = (dxNone, dxDogus); type ThreadImportacao = class(TThread) private FDefaultXML: TDefaultXML; FIdAgendameto: integer; FIdImobiliaria: Integer; FIdBancoDados: Integer; FPortal: string; FUrlXml: string; FPathXml: string; FPathMarcaAgua: string; FPathImagem: string; FNomeMarcaAgua: string; FTipoXml: string; FConexaoPortal: TSQLConnection; FConexaoAux: TSQLConnection; procedure setConexaoAux(const Value: TSQLConnection); function getConexaoAux: TSQLConnection; protected procedure AtualizaInfoTarefa(idAgendamento: integer; duracao, status, msg, nameXml: string); procedure Execute; override; public property ConexaoAux: TSQLConnection read getConexaoAux write setConexaoAux; function VerificaEstado(): Boolean; procedure Finalizar(); constructor Create(CreateSuspended: Boolean; idAgendamento, idImobiliaria, idBancoDados: integer; tipoXML: string; var ConexaoAux: TSQLConnection); end; var FCritical : TCriticalSection; implementation uses uPrincipal, uDM, uImportacaoDogus; { ThreadImportacao } // Método que dispara a Thread procedure ThreadImportacao.Execute; begin if not Terminated then begin try // Inicializa a Seção critica FCritical.Enter; CoInitialize(nil); case FDefaultXML of dxDogus : TImportacaoDogus.Create(FIdAgendameto, FIdImobiliaria, FIdBancoDados, FConexaoAux); else Abort; end; finally // Inicializa a Seção critica FCritical.Leave; end; end; end; procedure ThreadImportacao.Finalizar; begin Self.Terminate; Self.AtualizaInfoTarefa(FIdAgendameto, '', 'C', 'Cancelado pelo usuário', ''); end; // Método constutor da Classe constructor ThreadImportacao.Create(CreateSuspended: Boolean; idAgendamento, idImobiliaria, idBancoDados: integer; tipoXML: string; var ConexaoAux: TSQLConnection); begin inherited Create(CreateSuspended); Self.FDefaultXML := dxNone; Self.FIdAgendameto := idAgendamento; Self.FIdImobiliaria := idImobiliaria; Self.FIdBancoDados := idBancoDados; Self.setConexaoAux(ConexaoAux); if tipoXML = 'dogus' then Self.FDefaultXML := dxDogus end; // Procedure para finalizar a tarefa inserindo os dados necessários na TAB_TAREFA procedure ThreadImportacao.AtualizaInfoTarefa(idAgendamento: integer; duracao, status, msg, nameXml: string); var oQry: TSQLQuery; sSql : string; begin try sSql := 'UPDATE TAB_TAREFA SET statusAtual = :status, msg = :msg '; try oQry := TSQLQuery.Create(nil); oQry.SQLConnection := Self.getConexaoAux(); oQry.Close; oQry.SQL.Clear; oQry.SQL.Add(sSql); oQry.SQL.Add('WHERE idAgendamento = :id AND statusAtual = :statusAtual AND dataCadastro = :data'); oQry.ParamByName('status').AsString := status; oQry.ParamByName('msg').AsString := msg; oQry.ParamByName('id').AsInteger := idAgendamento; oQry.ParamByName('statusAtual').AsString := 'E'; oQry.ParamByName('data').AsDateTime := Date; oQry.ExecSQL(); DeleteFile(FPathXml + nameXml); except on E:Exception do MessageDlg('Erro ao atualizar status da tarefa: ' + E.Message, mtError, [mbOK], 0); end; finally FreeAndNil(oQry); end; end; function ThreadImportacao.getConexaoAux: TSQLConnection; begin if not FConexaoAux.Connected then begin FConexaoAux.Open; Sleep(2000); end; Result := FConexaoAux; end; procedure ThreadImportacao.setConexaoAux(const Value: TSQLConnection); begin if Assigned(Value) then FConexaoAux := Value; end; function ThreadImportacao.VerificaEstado: Boolean; var oQry: TSQLQuery; begin try try Result := False; if not Self.FConexaoAux.Connected then Self.FConexaoAux.Open; oQry := TSQLQuery.Create(nil); oQry.SQLConnection := dm.conexaoMonitoramento; oQry.Close; oQry.SQL.Clear; oQry.SQL.Add('SELECT acao FROM TAB_CONTROLE'); oQry.Open; if not oQry.IsEmpty then begin if oQry.FieldByName('acao').AsString = 'D' then Self.Finalizar; end; except on E:Exception do begin MessageDlg('Erro ao verificar estado do monitoramento Thread: ' + E.Message, mtError, [mbOK], 0); end; end; finally FreeAndNil(oQry); end; end; initialization FCritical := TCriticalSection.Create; finalization FreeAndNil(FCritical); end.
{Hint: save all files to location: C:\adt32\eclipse\workspace\AppCameraDemo\jni } unit unit1; {$mode delphi} interface uses Classes, SysUtils, And_jni, And_jni_Bridge, Laz_And_Controls, Laz_And_Controls_Events, AndroidWidget; type { TAndroidModule1 } TAndroidModule1 = class(jForm) jBitmap1: jBitmap; jButton1: jButton; jCamera1: jCamera; jCanvas1: jCanvas; jEditText1: jEditText; jImageView1: jImageView; jPanel1: jPanel; jPanel2: jPanel; jPanel3: jPanel; jPanel4: jPanel; jPanel5: jPanel; jTextView1: jTextView; jTextView2: jTextView; jView1: jView; procedure AndroidModule1ActivityRst(Sender: TObject; requestCode, resultCode: Integer; jData: jObject); procedure AndroidModule1Create(Sender: TObject); procedure AndroidModule1JNIPrompt(Sender: TObject); procedure AndroidModule1Rotate(Sender: TObject; rotate: integer; var rstRotate: integer); procedure jButton1Click(Sender: TObject); procedure jView1Draw(Sender: TObject; Canvas: jCanvas); private {private declarations} FPhotoExist: boolean; FSaveRotate: integer; public {public declarations} end; var AndroidModule1: TAndroidModule1; implementation {$R *.lfm} { TAndroidModule1 } procedure TAndroidModule1.AndroidModule1Rotate(Sender: TObject; rotate: integer; var rstRotate: integer); begin FSaveRotate:= rotate; if rotate = 2 then begin //after rotation device is on horizontal jPanel1.LayoutParamHeight:= lpMatchParent; jPanel1.LayoutParamWidth:= lpOneQuarterOfParent; jPanel1.PosRelativeToParent:= [rpLeft]; jPanel2.LayoutParamHeight:= lpMatchParent; jPanel2.LayoutParamWidth:= lpOneThirdOfParent; jPanel2.PosRelativeToAnchor:= [raToRightOf,raAlignBaseline]; jPanel3.PosRelativeToAnchor:= [raToRightOf,raAlignBaseline];; jPanel1.ResetAllRules; jPanel2.ResetAllRules; jPanel3.ResetAllRules; //jPanel5.PosRelativeToParent:= [rpCenterInParent]; //jPanel5.ResetAllRules; Self.UpdateLayout; end else begin //after rotation device is on vertical :: default jPanel1.LayoutParamHeight:= lpOneQuarterOfParent; jPanel1.LayoutParamWidth:= lpMatchParent; jPanel1.PosRelativeToParent:= [rpTop]; jPanel2.LayoutParamHeight:= lpOneThirdOfParent; jPanel2.LayoutParamWidth:= lpMatchParent; jPanel2.PosRelativeToAnchor:= [raBelow]; jPanel3.PosRelativeToAnchor:= [raBelow]; jPanel1.ResetAllRules; jPanel2.ResetAllRules; jPanel3.ResetAllRules; //jPanel5.PosRelativeToParent:= [rpBottom]; //jPanel5.ResetAllRules; Self.UpdateLayout; end; end; procedure TAndroidModule1.jButton1Click(Sender: TObject); begin jCamera1.RequestCode:= 12345; jCamera1.TakePhoto; //ShowMessage('clicked ...'); end; procedure TAndroidModule1.jView1Draw(Sender: TObject; Canvas: jCanvas); var ratio: single; size, w, h: integer; begin if FPhotoExist then begin w:= jBitmap1.Width; //ex. Width: 640 ... Height: 480 h:= jBitmap1.Height; //Ratio > 1 ! if w > h then Ratio:= w/h else Ratio:= h/w; if FSaveRotate = 2 then begin Ratio:= Round(jBitmap1.Width/jBitmap1.Height); jView1.Canvas.drawBitmap(jBitmap1, 0, 0, jView1.Width, Ratio); end else begin Ratio:= Round(jBitmap1.Height/jBitmap1.Width); jView1.Canvas.drawBitmap(jBitmap1, 0, 0, jView1.Height, Ratio); end; //or you can do simply this... NO RATIO! //jView1.Canvas.drawBitmap(jBitmap1, 0, 0, jView1.Width, jView1.Height); //just to ilustration.... you can draw and write over.... jView1.Canvas.PaintColor:= colbrRed; jView1.Canvas.drawLine(0, 0, jView1.Width, jView1.Height); jView1.Canvas.drawText('Hello People!', 30,30); //or simply show on other control: jImageView1 .... just WrapContent! jImageView1.SetImageBitmap(jBitmap1.GetJavaBitmap); end; end; procedure TAndroidModule1.AndroidModule1Create(Sender: TObject); begin FPhotoExist:= False; FSaveRotate:= 1; //default: Vertical end; procedure TAndroidModule1.AndroidModule1JNIPrompt(Sender: TObject); begin if Self.Orientation = 2 then // device is on horizontal... begin //reconfigure.... FSaveRotate:= 2; jPanel1.LayoutParamHeight:= lpMatchParent; jPanel1.LayoutParamWidth:= lpOneThirdOfParent; jPanel1.PosRelativeToParent:= [rpLeft]; jPanel2.LayoutParamHeight:= lpMatchParent; jPanel2.LayoutParamWidth:= lpOneThirdOfParent; jPanel2.PosRelativeToAnchor:= [raToRightOf,raAlignBaseline]; jPanel3.PosRelativeToAnchor:= [raToRightOf,raAlignBaseline];; jPanel1.ResetAllRules; jPanel2.ResetAllRules; jPanel3.ResetAllRules; jPanel5.PosRelativeToParent:= [rpCenterInParent]; jPanel5.ResetAllRules; Self.UpdateLayout; end; jEditText1.SetFocus; end; procedure TAndroidModule1.AndroidModule1ActivityRst(Sender: TObject; requestCode, resultCode: Integer; jData: jObject); begin if resultCode = 0 then ShowMessage('Photo Canceled!') else if resultCode = -1 then //ok... begin if requestCode = jCamera1.RequestCode then begin ShowMessage('Ok!'); jBitmap1.LoadFromFile(jCamera1.FullPathToBitmapFile); FPhotoExist:= True; jView1.Refresh; jImageView1.Refresh; end; end else ShowMessage('Photo Fail!'); end; end.
{**********************************************************************} {* Иллюстрация к книге "OpenGL в проектах Delphi" *} {* Краснов М.В. softgl@chat.ru *} {**********************************************************************} {/* * (c) Copyright 1993, Silicon Graphics, Inc. * 1993-1995 Microsoft Corporation * * ALL RIGHTS RESERVED */} unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, OpenGL; type TfrmGL = class(TForm) procedure FormCreate(Sender: TObject); procedure FormPaint(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormResize(Sender: TObject); private DC : HDC; hrc : HGLRC; end; var frmGL: TfrmGL; implementation uses DGlut; {$R *.DFM} // Initialize linear fog for depth cueing. procedure myinit; const fogColor : Array [0..3] of GLFloat = (0.0, 0.0, 0.0, 1.0); begin glEnable(GL_FOG); glFogi (GL_FOG_MODE, GL_LINEAR); glHint (GL_FOG_HINT, GL_NICEST); // per pixel glFogf (GL_FOG_START, 3.0); glFogf (GL_FOG_END, 5.0); glFogfv (GL_FOG_COLOR, @fogColor); glClearColor(0.0, 0.0, 0.0, 1.0); glDepthFunc(GL_LESS); glEnable(GL_DEPTH_TEST); glShadeModel(GL_FLAT); end; {======================================================================= Рисование картинки} procedure TfrmGL.FormPaint(Sender: TObject); begin glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); glColor3f (1.0, 1.0, 1.0); glutWireIcosahedron; SwapBuffers(DC); end; {======================================================================= Формат пикселя} procedure SetDCPixelFormat (hdc : HDC); var pfd : TPixelFormatDescriptor; nPixelFormat : Integer; begin FillChar (pfd, SizeOf (pfd), 0); pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER; nPixelFormat := ChoosePixelFormat (hdc, @pfd); SetPixelFormat (hdc, nPixelFormat, @pfd); end; {======================================================================= Создание формы} procedure TfrmGL.FormCreate(Sender: TObject); begin DC := GetDC (Handle); SetDCPixelFormat(DC); hrc := wglCreateContext(DC); wglMakeCurrent(DC, hrc); myinit; end; {======================================================================= Конец работы приложения} procedure TfrmGL.FormDestroy(Sender: TObject); begin wglMakeCurrent (0, 0); wglDeleteContext(hrc); ReleaseDC (Handle, DC); DeleteDC (DC); end; procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin If Key = VK_ESCAPE then Close; end; procedure TfrmGL.FormResize(Sender: TObject); begin glViewport (0, 0, ClientWidth, ClientHeight); glMatrixMode (GL_PROJECTION); glLoadIdentity; gluPerspective (45.0, ClientWidth / ClientHeight, 3.0, 5.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity; glTranslatef (0.0, 0.0, -4.0); InvalidateRect(Handle, nil, False); end; end.
unit DatasetCopy; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Datasnap.DBClient, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.DBCtrls; type TfDatasetCopy = class(TForm) dbgr1: TDBGrid; dbgr2: TDBGrid; dbNav1: TDBNavigator; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private FDataset1, FDataset2: TClientDataset; FDataSource1, FDataSource2: TDataSource; procedure CloneDataSet(aDataSet_Clonar, aDataSet_Clonado : TCustomClientDataSet; aReset: Boolean; aKeepSettings: Boolean = False); procedure InitDataset; public end; var fDatasetCopy: TfDatasetCopy; implementation {$R *.dfm} procedure TfDatasetCopy.CloneDataSet(aDataSet_Clonar, aDataSet_Clonado : TCustomClientDataSet; aReset, aKeepSettings: Boolean); begin aDataSet_Clonado.CloneCursor(aDataSet_Clonar, aReset, aKeepSettings); end; procedure TfDatasetCopy.FormCreate(Sender: TObject); begin inherited; FDataset1 := TClientDataset.Create(nil); FDataset2 := TClientDataset.Create(nil); FDataSource1 := TDataSource.Create(nil); FDataSource2 := TDataSource.Create(nil); FDataSource1.DataSet := FDataset1; FDataSource2.DataSet := FDataset2; dbgr1.DataSource := FDataSource1; dbgr2.DataSource := FDataSource2; InitDataset; end; procedure TfDatasetCopy.FormDestroy(Sender: TObject); begin FDataset1.Free; FDataset2.Free; FDataSource1.Free; FDataSource2.Free; end; procedure TfDatasetCopy.InitDataset; begin dbNav1.DataSource := FDataSource1; FDataset1.Close; FDataset1.FieldDefs.Add('Field1', ftString, 20); FDataset1.FieldDefs.Add('Field2', ftInteger); FDataset1.CreateDataSet; FDataset1.Append; FDataset1.FieldByName('Field1').AsString := 'Field1Value1'; FDataset1.FieldByName('Field2').AsInteger := 1; FDataset1.Post; FDataset1.Append; FDataset1.FieldByName('Field1').AsString := 'Field1Value2'; FDataset1.FieldByName('Field2').AsInteger := 2; FDataset1.Post; FDataset1.Append; FDataset1.FieldByName('Field1').AsString := 'Field1Value3'; FDataset1.FieldByName('Field2').AsInteger := 3; FDataset1.Post; CloneDataSet(FDataset1, FDataset2, False, true); end; end.
unit Mock.OSFile.IoControl; interface uses OSFile; type TCreateFileDesiredAccess = (DesiredNone, DesiredReadOnly, DesiredReadWrite); TIoControlFile = class(TOSFile) protected procedure CreateHandle(const FileToGetAccess: String; const DesiredAccess: TCreateFileDesiredAccess); virtual; function GetMinimumPrivilege: TCreateFileDesiredAccess; virtual; abstract; end; implementation { TIoControlFile } procedure TIoControlFile.CreateHandle(const FileToGetAccess: String; const DesiredAccess: TCreateFileDesiredAccess); begin end; end.
unit uConstants; {$I ..\Include\IntXLib.inc} interface uses {$IFDEF DELPHI} Generics.Defaults, Generics.Collections, {$ENDIF DELPHI} uStrRepHelper, uIntXLibTypes; type /// <summary> /// Constants used in <see cref="TIntX" /> and helping classes. /// </summary> TConstants = class sealed(TObject) public class var /// <summary> /// Standard char->digit dictionary. /// </summary> FBaseCharToDigits: TDictionary<Char, UInt32>; /// <summary> /// Chars used to parse/output big integers (uppercase). /// </summary> FBaseUpperChars: TIntXLibCharArray; /// <summary> /// Chars used to parse/output big integers (lowercase). /// </summary> FBaseLowerChars: TIntXLibCharArray; const /// <summary> /// Digit opening bracket (used for bases bigger than 16). /// </summary> DigitOpeningBracket = Char('{'); /// <summary> /// Digit closing bracket (used for bases bigger than 16). /// </summary> DigitClosingBracket = Char('}'); /// <summary> /// Minus char (-). /// </summary> DigitsMinusChar = Char('-'); /// <summary> /// Natural logarithm of digits base (log(2^32)). /// </summary> DigitBaseLog: Double = 22.180709777918249; /// <summary> /// Count of bits in one <see cref="TIntX" /> digit. /// </summary> DigitBitCount = Integer(32); /// <summary> /// <see cref="TIntX" /> length from which FHT is used (in auto-FHT mode). /// Before this length usual multiply algorithm works faster. /// </summary> AutoFhtLengthLowerBound = UInt32(UInt32(1) shl 9); /// <summary> /// <see cref="TIntX" /> length 'till which FHT is used (in auto-FHT mode). /// After this length using of FHT may be unsafe due to big precision errors. /// </summary> AutoFhtLengthUpperBound = UInt32(UInt32(1) shl 26); /// <summary> /// Number of lower digits used to check FHT multiplication result validity. /// </summary> FhtValidityCheckDigitCount = UInt32(10); /// <summary> /// <see cref="TIntX" /> length from which Newton approach is used (in auto-Newton mode). /// Before this length usual divide algorithm works faster. /// </summary> AutoNewtonLengthLowerBound = UInt32(UInt32(1) shl 13); /// <summary> /// <see cref="TIntX" /> length 'till which Newton approach is used (in auto-Newton mode). /// After this length using of fast division may be slow. /// </summary> AutoNewtonLengthUpperBound = UInt32(UInt32(1) shl 26); /// <summary> /// <see cref="TIntX" /> length from which fast parsing is used (in Fast parsing mode). /// Before this length usual parsing algorithm works faster. /// </summary> FastParseLengthLowerBound = UInt32(32); /// <summary> /// <see cref="TIntX" /> length from which fast conversion is used (in Fast convert mode). /// Before this length usual conversion algorithm works faster. /// </summary> FastConvertLengthLowerBound = UInt32(16); /// <summary> /// Maximum count of bits which can fit in <see cref="TIntX" />. /// </summary> MaxBitCount = UInt64(4294967295 * UInt64(32)); /// <summary> /// 2 ^ <see cref="DigitBitCount"/>. /// </summary> BitCountStepOf2 = UInt64(UInt64(1) shl 32); /// <summary> /// Euler's Number. /// </summary> EulersNumber: Double = 2.7182818284590451; /// <summary> /// Min Integer value. /// </summary> MinIntValue = Integer(-2147483648); /// <summary> /// Max Integer value. /// </summary> MaxIntValue = Integer(2147483647); /// <summary> /// Min Int64 value. /// </summary> MinInt64Value = Int64(-9223372036854775808); /// <summary> /// Max Int64 value. /// </summary> MaxInt64Value = Int64(9223372036854775807); /// <summary> /// Max UInt32 value. /// </summary> MaxUInt32Value = UInt32(4294967295); /// <summary> /// Max UInt64 value. /// </summary> MaxUInt64Value = UInt64(18446744073709551615); /// <summary> /// PI (π). /// </summary> PI: Double = 3.1415926535897931; /// <summary> /// class constructor. /// </summary> class constructor Create(); /// <summary> /// class destructor. /// </summary> class destructor Destroy; end; implementation // static class constructor class constructor TConstants.Create(); var i: Integer; MyString: String; begin FBaseUpperChars := TIntXLibCharArray.Create('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'); FBaseLowerChars := TIntXLibCharArray.Create('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'); SetString(MyString, PChar(@FBaseUpperChars[0]), Length(FBaseUpperChars)); FBaseCharToDigits := TStrRepHelper.CharDictionaryFromAlphabet(MyString, UInt32(16)); i := 10; while i < (Length(FBaseLowerChars)) do begin FBaseCharToDigits.Add(FBaseLowerChars[i], UInt32(i)); Inc(i); end; end; // static class destructor class destructor TConstants.Destroy; begin FBaseCharToDigits.Free; end; end.
unit uConst; interface uses Controls; const CONFIGFILE='SalesPromotion.ini'; ALLBTYPEID = '00000'; ALLBFULLNAME = '全部客户'; COLUMNUM=0; COLUMUSERCODE=1; COLUMFULLNAME=2; COLUMORGPRICE=3; COLUMTYPEID =4; COLUMDICCOUNTPRICE=5; COLUMStartDate=6; COLUMEndDate=7; COLUMSPID=8; COLUMSPBFULLNAME=9; COLUMSPBTYPEID=10; COLUMISToAllBtype=11; COLUMINVALID=12; COLUMVISIBLE=13; COLUMBFULLNAME =1; // COLUMFULLNAME =1 COLUMQTY =3; COLUMSALEPRICE=4; COLUMTOTAL=5; COLUMBILLDATE = 6; type TSalesConfig=record SCServerIp:String; SCUser:String; SCPass:String; SCZT:string; end; TSalePromotion=class(TObject) public SpId:string; PuserCode:String; PFullName:String; PTypeid:String; PPrice:Double; //原价 DiscountPrice:Double; BFullName:String; Btypeid:String; IStoAllBtype:Boolean; Invalid:Boolean; Visible:Boolean; StartDate:TDate; EndDate:TDate; end; var SalesConfig:TSalesConfig; implementation end.
{*******************************************************} { } { Delphi DataSnap Framework } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$HPPEMIT LINKUNIT} unit Data.DbxDatasnap; interface uses Data.DBXClient, Data.DBXCommon, Data.DBXJSON, Data.DBXTransport, System.Classes; const DS_CONTEXT = 'datasnap/'; type TDBXDatasnapProperties = class(TDBXProperties) strict private FFilters: TTransportFilterCollection; function GetHostName: string; function GetPassword: string; function GetUserName: string; function GetPort: Integer; function GetBufferKBSize: Integer; function GetServerConnection: string; function GetCommunicationProtocol: string; function GetCommunicationIPVersion: string; function GetURLPath: string; function GetDSAuthenticationUser: String; function GetDSAuthenticationPassword: String; function GetConnectTimeout: string; function GetCommunicationTimeout: string; function GetFilters: TTransportFilterCollection; function GetDatasnapContext: string; function GetDSAuthenticationScheme: string; function GetDSProxyHost: String; function GetDSProxyPort: Integer; function GetDSProxyUsername: String; function GetDSProxyPassword: String; procedure SetPort(const Value: Integer); procedure SetHostName(const Value: string); procedure SetPassword(const Value: string); procedure SetUserName(const Value: string); procedure SetBufferKBSize(const Value: Integer); procedure SetServerConnection(const Value: string); procedure SetCommunicationProtocol(const Value: string); procedure SetCommunicationIPVersion(const Value: string); procedure SetURLPath(const Value: string); procedure SetDSAuthenticationUser(const Value: string); procedure SetDSAuthenticationPassword(const Value: string); procedure SetConnectTimeout(const Value: string); procedure SetCommunicationTimeout(const Value: string); procedure SetFilters(const Value: TTransportFilterCollection); procedure SetDatasnapContext(const Value: string); procedure SetDSAuthenticationScheme(const Value: string); procedure SetDSProxyHost(const Value: String); procedure SetDSProxyPort(const Value: Integer); procedure SetDSProxyUsername(const Value: String); procedure SetDSProxyPassword(const Value: String); procedure OnFiltersChange(source: TObject); function GetValidateCertificate: TValidateCertificate; procedure SetValidateCertificate(Cert: TValidateCertificate); protected procedure Init; virtual; published public constructor Create(DBXContext: TDBXContext); override; constructor Create; override; destructor Destroy; override; ///<summary>Returns the ValidatePeerCertificate event from the Events collection, if one exists.</summary> property OnValidatePeerCertificate: TValidateCertificate read GetValidateCertificate write SetValidateCertificate; published /// <summary>Machine name where a DataSnap Server is running and to be connected to</summary> property HostName: string read GetHostName write SetHostName; /// <summary>Database user name when a remote database connection is expected to be /// created</summary> property UserName: string read GetUserName write SetUserName; /// <summary>Database user password required for the database connection</summary> property Password: string read GetPassword write SetPassword; /// <summary>Port number where the DataSnap Server instance listens to</summary> /// <remarks>Default value is 211</remarks> [Default(211)] property Port: Integer read GetPort write SetPort default 211; /// <summary>Buffer size for a unit of communication transport</summary> /// <remarks>The buffer size can affect performance, default value is 32 and /// was chosen so to match the TCP/IP default packet size</remarks> [Default(32)] property BufferKBSize: Integer read GetBufferKBSize write SetBufferKBSize default 32; /// <summary>Database server connectection name that is expected to be used remotely</summary> /// <remarks>UserName and Password properties are used for database authentication</remarks> property ServerConnection: string read GetServerConnection write SetServerConnection; /// <summary>Communication protocol type used for data exchange with the DataSnap Server.</summary> /// <remarks>Current supported values are http and tcp/ip. Default value is tcp/ip</remarks> property CommunicationProtocol: string read GetCommunicationProtocol write SetCommunicationProtocol; /// <summary>Communication IP version used in Indy with the DataSnap Server.</summary> /// <remarks>Options are IPv6 and IPv4. Default value is IPv4</remarks> property CommunicationIPVersion: string read GetCommunicationIPVersion write SetCommunicationIPVersion; /// <summary>URL path used for HTTP DataSnap Service when http protocol is used</summary> property URLPath: string read GetURLPath write SetURLPath; /// <summary>DataSnap user name.</summary> /// <remarks>Used for DataSnap user authentication when an /// server has an authentication manager present.</remarks> property DSAuthUser: string read GetDSAuthenticationUser write SetDSAuthenticationUser; /// <summary>DataSnap user password.</summary> /// <remarks>Used in conjunction with DataSnap user name for authentication /// when server has an authentication manager</remarks> property DSAuthPassword: string read GetDSAuthenticationPassword write SetDSAuthenticationPassword; /// <summary>DataSnap authentication scheme.</summary> /// <remarks>Used in conjunction with DataSnap user name and password for /// authentication using the HTTP protocol. Set to "basic" in order to /// send DSAuthUser/DSAuthPassword values using basic HTTP authentication, // in addition to sending these values in the DBX connection string. /// Basic HTTP authentication may be used to pass credentials to /// an inter-process DataSnap HTTP tunnel server</remarks> property DSAuthScheme: string read GetDSAuthenticationScheme write SetDSAuthenticationScheme; /// <summary>Connect timeout value.</summary> /// <remarks>The values provides the number of milliseconds the client waits /// for the connection to be possible. The value provides the time out for the /// first server response acknowledgment rather than for the entire connect/authenticate /// phase. It should be used in order to avoid application freeze when /// it may be possible to attempt connections to older DataSnap Server versions /// or different application that will not acknowledge current communication /// protocol.</remarks> property ConnectTimeout: string read GetConnectTimeout write SetConnectTimeout; /// <summary>Timeout value in miliseconds for a response after the connection is established</summary> property CommunicationTimeout: string read GetCommunicationTimeout write SetCommunicationTimeout; /// <summary>Client filters, used to store the filter configuration</summary> property Filters: TTransportFilterCollection read GetFilters write SetFilters; /// <summary>path toward the DS HTTP Service, used to compose the URL</summary> /// <remarks>The current convention is: http://x.com/datasnap/provider/classname/method/params. /// The user may change or delete datasnap word from it.</remarks> property DatasnapContext: String read GetDatasnapContext write SetDatasnapContext; /// <summary>The host to proxy requests through, or empty string to not use a proxy.</summary> property DSProxyHost: String read GetDSProxyHost write SetDSProxyHost; /// <summary>The port on the proxy host to proxy requests through. Ignored if DSProxyHost isn't set. /// </summary> property DSProxyPort: Integer read GetDSProxyPort write SetDSProxyPort; /// <summary>User name for proxy authentication.</summary> property DSProxyUsername: String read GetDSProxyUsername write SetDSProxyUsername; /// <summary>Password for proxy authentication</summary> property DSProxyPassword: String read GetDSProxyPassword write SetDSProxyPassword; end; TDBXDatasnapDriver = class(TDBXClientDriver) public constructor Create(DriverDef: TDBXDriverDef); override; end; implementation uses System.SysUtils , Data.DBXJSONReflect ; const sDriverName = 'DataSnap'; { TDBXDatasnapDriver } constructor TDBXDatasnapDriver.Create(DriverDef: TDBXDriverDef); var Props: TDBXDatasnapProperties; I, Index: Integer; begin Props := TDBXDatasnapProperties.Create(DriverDef.FDBXContext); if DriverDef.FDriverProperties <> nil then begin for I := 0 to DriverDef.FDriverProperties.Count - 1 do begin Index := Props.Properties.IndexOfName(DriverDef.FDriverProperties.Properties.Names[I]); if Index > -1 then Props.Properties.Strings[Index] := DriverDef.FDriverProperties.Properties.Strings[I]; end; Props.AddUniqueProperties(DriverDef.FDriverProperties.Properties); DriverDef.FDriverProperties.AddUniqueProperties(Props.Properties); end; inherited Create(DriverDef, Props); end; { TDBXDatasnapProperties } constructor TDBXDatasnapProperties.Create(DBXContext: TDBXContext); begin inherited Create(DBXContext); Init; end; constructor TDBXDatasnapProperties.Create; begin inherited; Init; end; destructor TDBXDatasnapProperties.Destroy; begin if FFilters <> nil then begin // FFilters has content ownership FFilters.Clear; // release the container FFilters.Free; end; inherited; end; function TDBXDatasnapProperties.GetBufferKBSize: Integer; begin Result := StrToIntDef(Values[TDBXPropertyNames.BufferKBSize], 32); end; function TDBXDatasnapProperties.GetHostName: string; begin Result := Values[TDBXPropertyNames.HostName]; end; function TDBXDatasnapProperties.GetPassword: string; begin Result := Values[TDBXPropertyNames.Password]; end; function TDBXDatasnapProperties.GetPort: Integer; begin Result := StrToIntDef(Values[TDBXPropertyNames.Port], 211); end; function TDBXDatasnapProperties.GetServerConnection: string; begin Result := Values[TDBXPropertyNames.ServerConnection]; end; function TDBXDatasnapProperties.GetUserName: string; begin Result := Values[TDBXPropertyNames.UserName]; end; function TDBXDatasnapProperties.GetValidateCertificate: TValidateCertificate; begin Result := TValidateCertificate(Events.Events[sValidatePeerCertificate]); end; procedure TDBXDatasnapProperties.SetValidateCertificate(Cert: TValidateCertificate); begin Events.Events[sValidatePeerCertificate] := TEventPointer(Cert); end; procedure TDBXDatasnapProperties.Init; begin Values[TDBXPropertyNames.DriverUnit] := 'Data.DbxDatasnap'; Values[TDBXPropertyNames.HostName] := 'localhost'; Values[TDBXPropertyNames.Port] := '211'; Values[TDBXPropertyNames.CommunicationProtocol] := 'tcp/ip'; Values[TDBXPropertyNames.Filters] := EmptyStr; Values[TDBXPropertyNames.DatasnapContext] := DS_CONTEXT; end; procedure TDBXDatasnapProperties.OnFiltersChange(source: TObject); begin Values[TDBXPropertyNames.Filters] := FFilters.ToJSON end; function TDBXDatasnapProperties.GetCommunicationIPVersion: string; begin Result := Values[TDBXPropertyNames.CommunicationIPVersion]; end; function TDBXDatasnapProperties.GetCommunicationProtocol: string; begin Result := Values[TDBXPropertyNames.CommunicationProtocol]; end; function TDBXDatasnapProperties.GetCommunicationTimeout: string; begin Result := Values[TDBXPropertyNames.CommunicationTimeout]; end; function TDBXDatasnapProperties.GetConnectTimeout: string; begin Result := Values[TDBXPropertyNames.ConnectTimeout]; end; function TDBXDatasnapProperties.GetDatasnapContext: string; begin Result := Values[TDBXPropertyNames.DatasnapContext]; end; function TDBXDatasnapProperties.GetDSAuthenticationPassword: String; begin Result := Values[TDBXPropertyNames.DSAuthenticationPassword]; end; function TDBXDatasnapProperties.GetDSAuthenticationScheme: string; begin Result := Values[TDBXPropertyNames.DSAuthenticationScheme]; end; function TDBXDatasnapProperties.GetDSAuthenticationUser: String; begin Result := Values[TDBXPropertyNames.DSAuthenticationUser]; end; function TDBXDatasnapProperties.GetDSProxyHost: String; begin Result := Values[TDBXPropertyNames.DSProxyHost]; end; function TDBXDatasnapProperties.GetDSProxyPassword: String; begin Result := Values[TDBXPropertyNames.DSProxyPassword]; end; function TDBXDatasnapProperties.GetDSProxyPort: Integer; begin Result := StrToIntDef(Values[TDBXPropertyNames.DSProxyPort], 8888); end; function TDBXDatasnapProperties.GetDSProxyUsername: String; begin Result := Values[TDBXPropertyNames.DSProxyUsername]; end; function TDBXDatasnapProperties.GetFilters: TTransportFilterCollection; var json: String; begin FFilters.Free; json := Values[TDBXPropertyNames.Filters]; if json <> EmptyStr then FFilters := TTransportFilterCollection.FromJSON(json) else FFilters := TTransportFilterCollection.Create; FFilters.OnChange := OnFiltersChange; Result := FFilters; end; function TDBXDatasnapProperties.GetURLPath: string; begin Result := Values[TDBXPropertyNames.URLPath]; end; procedure TDBXDatasnapProperties.SetBufferKBSize(const Value: Integer); begin Values[TDBXPropertyNames.BufferKBSize] := IntToStr(Value); end; procedure TDBXDatasnapProperties.SetHostName(const Value: string); begin Values[TDBXPropertyNames.HostName] := Value; end; procedure TDBXDatasnapProperties.SetPassword(const Value: string); begin Values[TDBXPropertyNames.Password] := Value; end; procedure TDBXDatasnapProperties.SetPort(const Value: Integer); begin Values[TDBXPropertyNames.Port] := IntToStr(Value); end; procedure TDBXDatasnapProperties.SetServerConnection(const Value: string); begin Values[TDBXPropertyNames.ServerConnection] := Value; end; procedure TDBXDatasnapProperties.SetUserName(const Value: string); begin Values[TDBXPropertyNames.UserName] := Value; end; procedure TDBXDatasnapProperties.SetCommunicationIPVersion(const Value: string); begin Values[TDBXPropertyNames.CommunicationIPVersion] := Value; end; procedure TDBXDatasnapProperties.SetCommunicationProtocol(const Value: string); begin Values[TDBXPropertyNames.CommunicationProtocol] := Value; end; procedure TDBXDatasnapProperties.SetCommunicationTimeout(const Value: string); begin Values[TDBXPropertyNames.CommunicationTimeout] := Value; end; procedure TDBXDatasnapProperties.SetConnectTimeout(const Value: string); begin Values[TDBXPropertyNames.ConnectTimeout] := Value; end; procedure TDBXDatasnapProperties.SetDatasnapContext(const Value: string); begin Values[TDBXPropertyNames.DatasnapContext] := Value; end; procedure TDBXDatasnapProperties.SetDSAuthenticationPassword( const Value: string); begin Values[TDBXPropertyNames.DSAuthenticationPassword] := Value; end; procedure TDBXDatasnapProperties.SetDSAuthenticationUser(const Value: string); begin Values[TDBXPropertyNames.DSAuthenticationUser] := Value; end; procedure TDBXDatasnapProperties.SetDSProxyHost(const Value: String); begin Values[TDBXPropertyNames.DSProxyHost] := Value; end; procedure TDBXDatasnapProperties.SetDSProxyPassword(const Value: String); begin Values[TDBXPropertyNames.DSProxyPassword] := Value; end; procedure TDBXDatasnapProperties.SetDSProxyPort(const Value: Integer); begin Values[TDBXPropertyNames.DSProxyPort] := IntToStr(Value); end; procedure TDBXDatasnapProperties.SetDSProxyUsername(const Value: String); begin Values[TDBXPropertyNames.DSProxyUsername] := Value; end; procedure TDBXDatasnapProperties.SetDSAuthenticationScheme(const Value: string); begin Values[TDBXPropertyNames.DSAuthenticationScheme] := Value; end; procedure TDBXDatasnapProperties.SetFilters( const Value: TTransportFilterCollection); begin FFilters.Free; FFilters := Value; if Assigned(Value) then Values[TDBXPropertyNames.Filters] := Value.ToJSON else Values[TDBXPropertyNames.Filters] := EmptyStr end; procedure TDBXDatasnapProperties.SetURLPath(const Value: string); begin Values[TDBXPropertyNames.URLPath] := Value; end; initialization TDBXDriverRegistry.RegisterDriverClass(sDriverName, TDBXDatasnapDriver); finalization TDBXDriverRegistry.UnloadDriver(sDriverName); end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2014-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit System.Devices; interface uses System.Types, System.SysUtils, System.Generics.Collections; {$SCOPEDENUMS ON} const // Common design-time attribute key names - These keys are not localized, however the values associated // with these keys *may* be localized where appropriate // NOTE: These attribute names are reserved and used by the IDE at design-time. Do not modify the values associated // with these attributes. Also, they will only be present at design-time. sDevAttrDisplayName = 'DisplayName'; // This will be the user-friendly name of a specific device sDevAttrOPDefine = 'OPDefine'; // This is the Object Pascal compiler platform conditional define of a specific device sDevAttrCPPDefine = 'CPPDefine'; // This is the C++ compiler platform conditional define of a specific device sDevAttrPlatforms = 'Platforms'; // This is the list of platform targets with which this device is associated type TDeviceInfo = class sealed public type TDeviceClass = (Unknown, Desktop, Phone, MediaPlayer, Tablet, Automotive, Industrial, Embedded, Watch, Glasses, Elf, Dwarf, Wizard); private type TDeviceList = class(TObjectList<TDeviceInfo>) private FSorted: Boolean; protected procedure Notify(const Item: TDeviceInfo; Action: TCollectionNotification); override; procedure CalculateDeltas; public procedure Sort; end; private class var FDevices: TDeviceList; class var FThisDevice: TDeviceInfo; class constructor Create; class destructor Destroy; class procedure SetThisDevice(const Device: TDeviceInfo); static; class function GetThisDevice: TDeviceInfo; static; class function GetDeviceCount: Integer; static; inline; class function GetDevice(Index: Integer): TDeviceInfo; static; inline; class function GetDeviceByID(const AID: string): TDeviceInfo; static; private FDeviceClass: TDeviceClass; FID: string; FPlatform: TOSVersion.TPlatform; FMinPhysicalScreenSize: TSize; // Minimum Screen actual pixel dimensions FMinLogicalScreenSize: TSize; // Minimum Screen logical dimensions FMaxPhysicalScreenSize: TSize; // Maximum Screen actual pixel dimensions FMaxLogicalScreenSize: TSize; // Maximum Screen logical dimensions FAspectRatio: Single; FLowDelta, FHighDelta: Single; FPixelsPerInch: Integer; FExclusive: Boolean; // If True, this device will never be returned unless it matches FAttributes: TDictionary<string, string>; constructor Create(ADeviceClass: TDeviceClass; const AID: string; const AMinPhysicalScreenSize, AMinLogicalScreenSize, AMaxPhysicalScreenSize, AMaxLogicalScreenSize: TSize; APlatform: TOSVersion.TPlatform; APixelsPerInch: Integer; AExclusive: Boolean); overload; function GetAttribute(const Key: string): string; function GetMaxDiagonal: Single; function GetMinDiagonal: Single; property LowDelta: Single read FLowDelta write FLowDelta; property HighDelta: Single read FHighDelta write FHighDelta; public // Instance publics constructor Create; overload; // do not call this constructor destructor Destroy; override; function Equals(Obj: TObject): Boolean; override; procedure AddAttribute(const Key, Value: string); function HasAttribute(const Key: string): Boolean; property DeviceClass: TDeviceClass read FDeviceClass; property Exclusive: Boolean read FExclusive; property ID: string read FID; property Platform: TOSVersion.TPlatform read FPlatform; property MinPhysicalScreenSize: TSize read FMinPhysicalScreenSize; property MinLogicalScreenSize: TSize read FMinLogicalScreenSize; property MaxPhysicalScreenSize: TSize read FMaxPhysicalScreenSize; property MaxLogicalScreenSize: TSize read FMaxLogicalScreenSize; property AspectRatio: Single read FAspectRatio; property PixelsPerInch: Integer read FPixelsPerInch; property MaxDiagonal: Single read GetMaxDiagonal; property MinDiagonal: Single read GetMinDiagonal; property Attributes[const Key: string]: string read GetAttribute; public // class publics class function AddDevice(ADeviceClass: TDeviceClass; const AID: string; const APhysicalScreenSize, ALogicalScreenSize: TSize; APlatform: TOSVersion.TPlatform; APixelsPerInch: Integer; AExclusive: Boolean = False): TDeviceInfo; overload; class function AddDevice(ADeviceClass: TDeviceClass; const AID: string; const AMinPhysicalScreenSize, AMinLogicalScreenSize, AMaxPhysicalScreenSize, AMaxLogicalScreenSize: TSize; APlatform: TOSVersion.TPlatform; APixelsPerInch: Integer; AExclusive: Boolean = False): TDeviceInfo; overload; class procedure RemoveDevice(const AID: string); class function SelectDevices(ADeviceClass: TDeviceClass; const APhysicalScreenSize, ALogicalScreenSize: TSize; APlatform: TOSVersion.TPlatform; APixelsPerInch: Integer; SetThisDevice: Boolean = True): TArray<TDeviceInfo>; class property DeviceCount: Integer read GetDeviceCount; class property Devices[Index: Integer]: TDeviceInfo read GetDevice; class property DeviceByID[const AID: string]: TDeviceInfo read GetDeviceByID; class property ThisDevice: TDeviceInfo read GetThisDevice write SetThisDevice; end; implementation uses System.RTLConsts, System.Generics.Defaults, System.Math, {$IF Defined(MSWINDOWS)} System.Win.Devices {$ELSEIF Defined(IOS)} System.iOS.Devices {$ELSEIF Defined(MACOS)} System.Mac.Devices {$ELSEIF Defined(ANDROID)} System.Android.Devices {$ELSE} {$MESSAGE FATAL 'System.Devices is not supported on this platform'} // do not localize {$ENDIF} ; { TDeviceInfo } procedure TDeviceInfo.AddAttribute(const Key, Value: string); begin if FAttributes.ContainsKey(Key) then raise EInvalidOpException.CreateResFmt(@sAttributeExists, [Key]); FAttributes.Add(Key, Value); end; class constructor TDeviceInfo.Create; begin FDevices := TDeviceList.Create(TDelegatedComparer<TDeviceInfo>.Create( function (const Left, Right: TDeviceInfo): Integer begin Result := Ord(Left.Platform) - Ord(Right.Platform); if Result = 0 then Result := Ord(Left.DeviceClass) - Ord(Right.DeviceClass); if Result = 0 then Result := Trunc(Left.MinDiagonal - Right.MinDiagonal); if Result = 0 then Result := Trunc(Left.AspectRatio - Right.AspectRatio); if Result = 0 then Result := ((Left.MinPhysicalScreenSize.cx * 100) div Left.PixelsPerInch) - ((Right.MinPhysicalScreenSize.cx * 100) div Right.PixelsPerInch); if Result = 0 then Result := ((Left.MinPhysicalScreenSize.cy * 100) div Left.PixelsPerInch) - ((Right.MinPhysicalScreenSize.cy * 100) div Right.PixelsPerInch); end) as IComparer<TDeviceInfo>); AddDevices; end; class function TDeviceInfo.AddDevice(ADeviceClass: TDeviceClass; const AID: string; const APhysicalScreenSize, ALogicalScreenSize: TSize; APlatform: TOSVersion.TPlatform; APixelsPerInch: Integer; AExclusive: Boolean = False): TDeviceInfo; begin Result := TDeviceInfo.Create(ADeviceClass, AID, APhysicalScreenSize, ALogicalScreenSize, APhysicalScreenSize, ALogicalScreenSize, APlatform, APixelsPerInch, AExclusive); try if DeviceByID[AID] = nil then FDevices.Add(Result) else raise EInvalidOpException.CreateResFmt(@sDeviceExists, [AID]); except Result.Free; raise; end; end; constructor TDeviceInfo.Create; begin raise ENoConstructException.Create(sCannotManuallyConstructDevice); end; class function TDeviceInfo.AddDevice(ADeviceClass: TDeviceClass; const AID: string; const AMinPhysicalScreenSize, AMinLogicalScreenSize, AMaxPhysicalScreenSize, AMaxLogicalScreenSize: TSize; APlatform: TOSVersion.TPlatform; APixelsPerInch: Integer; AExclusive: Boolean = False): TDeviceInfo; begin Result := TDeviceInfo.Create(ADeviceClass, AID, AMinPhysicalScreenSize, AMinLogicalScreenSize, AMaxPhysicalScreenSize, AMaxLogicalScreenSize, APlatform, APixelsPerInch, AExclusive); try if DeviceByID[AID] = nil then FDevices.Add(Result) else raise EInvalidOpException.CreateResFmt(@sDeviceExists, [AID]); except Result.Free; raise; end; end; constructor TDeviceInfo.Create(ADeviceClass: TDeviceClass; const AID: string; const AMinPhysicalScreenSize, AMinLogicalScreenSize, AMaxPhysicalScreenSize, AMaxLogicalScreenSize: TSize; APlatform: TOSVersion.TPlatform; APixelsPerInch: Integer; AExclusive: Boolean); begin inherited Create; FDeviceClass := ADeviceClass; FExclusive := AExclusive; FID := AID; FMinPhysicalScreenSize := AMinPhysicalScreenSize; FMinLogicalScreenSize := AMinLogicalScreenSize; FMaxPhysicalScreenSize := AMaxPhysicalScreenSize; FMaxLogicalScreenSize := AMaxLogicalScreenSize; FPixelsPerInch := APixelsPerInch; FAspectRatio := Max(FMinPhysicalScreenSize.cy, FMinPhysicalScreenSize.cx) / Min(FMinPhysicalScreenSize.cy, FMinPhysicalScreenSize.cx); FPlatform := APlatform; FAttributes := TDictionary<string, string>.Create; end; destructor TDeviceInfo.Destroy; begin FAttributes.Free; inherited Destroy; end; function TDeviceInfo.Equals(Obj: TObject): Boolean; begin Result := (Obj = Self) or ((Obj is TDeviceInfo) and (TDeviceInfo(Obj).FDeviceClass = Self.FDeviceClass) and (TDeviceInfo(Obj).FPlatform = Self.FPlatform) and (TDeviceInfo(Obj).FMinPhysicalScreenSize = Self.FMinPhysicalScreenSize) and (TDeviceInfo(Obj).FMaxPhysicalScreenSize = Self.FMaxPhysicalScreenSize) and (TDeviceInfo(Obj).FMinLogicalScreenSize = Self.FMinLogicalScreenSize) and (TDeviceInfo(Obj).FMaxLogicalScreenSize = Self.FMaxLogicalScreenSize) and (TDeviceInfo(Obj).FPixelsPerInch = Self.FPixelsPerInch)); end; class destructor TDeviceInfo.Destroy; begin if (FThisDevice <> nil) and ((FDevices = nil) or (FDevices.IndexOf(FThisDevice) < 0)) then FThisDevice.Free; FDevices.Free; end; function TDeviceInfo.GetAttribute(const Key: string): string; begin Result := FAttributes[Key]; end; class function TDeviceInfo.GetDevice(Index: Integer): TDeviceInfo; begin Result := FDevices[Index]; end; class function TDeviceInfo.GetDeviceByID(const AID: string): TDeviceInfo; var I: Integer; begin for I := 0 to DeviceCount - 1 do begin Result := FDevices[I]; if SameText(Result.ID, AID) then Exit; end; Result := nil; end; class function TDeviceInfo.GetDeviceCount: Integer; begin Result := FDevices.Count; end; function TDeviceInfo.GetMaxDiagonal: Single; begin Result := Sqrt(Sqr(FMaxPhysicalScreenSize.CX) + Sqr(FMaxPhysicalScreenSize.CY)) / FPixelsPerInch; end; function TDeviceInfo.GetMinDiagonal: Single; begin Result := Sqrt(Sqr(FMinPhysicalScreenSize.CX) + Sqr(FMinPhysicalScreenSize.CY)) / FPixelsPerInch; end; class function TDeviceInfo.GetThisDevice: TDeviceInfo; begin Result := FThisDevice; end; function TDeviceInfo.HasAttribute(const Key: string): Boolean; begin Result := FAttributes.ContainsKey(Key); end; class procedure TDeviceInfo.RemoveDevice(const AID: string); var Device: TDeviceInfo; begin Device := DeviceByID[AID]; if Device <> nil then FDevices.Remove(Device); end; class function TDeviceInfo.SelectDevices(ADeviceClass: TDeviceClass; const APhysicalScreenSize, ALogicalScreenSize: TSize; APlatform: TOSVersion.TPlatform; APixelsPerInch: Integer; SetThisDevice: Boolean = True): TArray<TDeviceInfo>; var I, Index: Integer; LDevice, LThisDevice, LMatch: TDeviceInfo; LClosest, LDistance: Single; LDevices: TList<TDeviceInfo>; LDiagonal: Single; begin FDevices.Sort; LMatch := nil; if SetThisDevice then LThisDevice := TDeviceInfo.Create(ADeviceClass, '', APhysicalScreenSize, ALogicalScreenSize, APhysicalScreenSize, ALogicalScreenSize, APlatform, APixelsPerInch, True) else LThisDevice := nil; try LDiagonal := Sqrt(Sqr(APhysicalScreenSize.cx) + Sqr(APhysicalScreenSize.cy)) / APixelsPerInch; LDevices := TList<TDeviceInfo>.Create; try for I := 0 to DeviceCount - 1 do begin LDevice := Devices[I]; if LDevice.Equals(LThisDevice) then LMatch := LDevice; if LDevice.Platform = APlatform then begin if (LDiagonal >= LDevice.MinDiagonal + LDevice.LowDelta) and (LDiagonal <= LDevice.MaxDiagonal + LDevice.HighDelta) then begin if LDevice.DeviceClass = ADeviceClass then LDevices.Insert(0, LDevice) else if not LDevice.Exclusive then LDevices.Add(LDevice); end; end; end; Index := LDevices.Count; LClosest := Single.MaxValue; for I := 0 to DeviceCount - 1 do begin LDevice := Devices[I]; if (LDevice.Platform = APlatform) and (LDevices.IndexOf(LDevice) < 0) and not LDevice.Exclusive then begin LDistance := Abs(LDiagonal - (LDevice.MinDiagonal + (LDevice.MaxDiagonal - LDevice.MinDiagonal) / 2)); if LDistance < LClosest then begin LDevices.Insert(Index, LDevice); LClosest := LDistance; end else LDevices.Add(LDevice); end; end; if LMatch <> nil then begin FThisDevice := LMatch; LThisDevice.Free; end else FThisDevice := LThisDevice; Result := LDevices.ToArray; finally LDevices.Free; end; except if FThisDevice = LThisDevice then FThisDevice := nil; LThisDevice.Free; raise; end; end; class procedure TDeviceInfo.SetThisDevice(const Device: TDeviceInfo); begin FThisDevice := Device; end; { TDeviceInfo.TDeviceList } procedure TDeviceInfo.TDeviceList.CalculateDeltas; var CurDevice, LastDevice: TDeviceInfo; begin LastDevice := nil; for CurDevice in Self do begin if (LastDevice = nil) or (LastDevice.Platform <> CurDevice.Platform) then begin if LastDevice <> nil then LastDevice.HighDelta := 0.0; CurDevice.LowDelta := -CurDevice.MinDiagonal; LastDevice := CurDevice; end else if (LastDevice.DeviceClass <> CurDevice.DeviceClass) and SameValue(LastDevice.MinDiagonal, CurDevice.MinDiagonal) and SameValue(LastDevice.MaxDiagonal, CurDevice.MaxDiagonal) then begin CurDevice.HighDelta := LastDevice.HighDelta; CurDevice.LowDelta := LastDevice.LowDelta; LastDevice := CurDevice; end else begin LastDevice.HighDelta := Max(0.0, (CurDevice.MinDiagonal - LastDevice.MaxDiagonal) / 2); CurDevice.LowDelta := -LastDevice.HighDelta; LastDevice := CurDevice; end; end; if LastDevice <> nil then LastDevice.HighDelta := 0.0; end; procedure TDeviceInfo.TDeviceList.Notify(const Item: TDeviceInfo; Action: TCollectionNotification); begin inherited Notify(Item, Action); FSorted := False; end; procedure TDeviceInfo.TDeviceList.Sort; begin if not FSorted then begin inherited Sort; FSorted := True; CalculateDeltas; end; end; end.
unit Optimizer.P2P; interface uses SysUtils, Optimizer.Template, Global.LanguageString, Registry.Helper; type TP2POptimizer = class(TOptimizationUnit) public function IsOptional: Boolean; override; function IsCompatible: Boolean; override; function IsApplied: Boolean; override; function GetName: String; override; procedure Apply; override; procedure Undo; override; end; implementation function TP2POptimizer.IsOptional: Boolean; begin exit(false); end; function TP2POptimizer.IsCompatible: Boolean; begin exit(IsAtLeastWindows10); end; function TP2POptimizer.IsApplied: Boolean; begin if not IsAtLeastWindows10 then exit(false); result := NSTRegistry.GetRegStr(NSTRegistry.LegacyPathToNew('LM', 'SOFTWARE\Microsoft\Windows\CurrentVersion\DeliveryOptimization\Settings', 'DownloadMode')) <> '3'; end; function TP2POptimizer.GetName: String; begin exit(CapOptP2P[CurrLang]); end; procedure TP2POptimizer.Apply; begin NSTRegistry.SetRegStr(NSTRegistry.LegacyPathToNew('LM', 'SOFTWARE\Microsoft\Windows\CurrentVersion\DeliveryOptimization\Settings', 'DownloadMode'), '0'); end; procedure TP2POptimizer.Undo; begin NSTRegistry.SetRegStr(NSTRegistry.LegacyPathToNew('LM', 'SOFTWARE\Microsoft\Windows\CurrentVersion\DeliveryOptimization\Settings', 'DownloadMode'), '3'); end; end.
(* SynTree: Rittberger, 2020-04-28 *) (* ------ *) (* checks the syntax of the given grammar *) (* ========================================================================= *) PROGRAM SynTree; USES SynTreeUnit; FUNCTION ToInt(s: STRING): INTEGER; VAR i, sum: INTEGER; BEGIN (* ToInt *) sum := 0; FOR i := 1 TO Length(s) DO BEGIN sum := sum * 10 + Ord(s[i]) - Ord('0'); END; (* FOR *) ToInt := sum; END; (* ToInt *) VAR t1: kanTree; BEGIN (* SynTree *) Write(Chr(Ord(17) + Ord('0'))); END. (* SynTree *)
unit Fonetiza; interface uses Fonetiza.Intf, Fonetiza.Core, Fonetiza.Utils, Fonetiza.CodigoFonetico.Core; type TFonetiza = class(TInterfacedObject, IFonetiza) private FFonetizaCore: TFonetizaCore; FCodigoFonetico: TCodigoFoneticoCore; FFonetizaUtils: TFonetizaUtils; { IFonetiza } function Fonetizar(const AValue: string): string; function GerarCodigoFonetico(const AValue: string): string; function GerarListaCodigosFoneticos(const AValue: string): TArray<string>; public constructor Create; class function New: IFonetiza; destructor Destroy; override; end; implementation { TFonetiza } uses System.SysUtils, Fonetiza.Consts; constructor TFonetiza.Create; begin FFonetizaCore := TFonetizaCore.Create; FCodigoFonetico := TCodigoFoneticoCore.Create; FFonetizaUtils := TFonetizaUtils.Create; end; destructor TFonetiza.Destroy; begin if Assigned(FFonetizaCore) then FFonetizaCore.Free; if Assigned(FCodigoFonetico) then FCodigoFonetico.Free; if Assigned(FFonetizaUtils) then FFonetizaUtils.Free; inherited; end; function TFonetiza.Fonetizar(const AValue: string): string; begin Result := AValue.Trim.ToUpper; Result := FFonetizaUtils.RemoverAcentuacoes(Result); Result := FFonetizaUtils.RemoverCaracteresEspeciais(Result); Result := FFonetizaUtils.RemoverConteudos(Result, PREPOSICOES); Result := FFonetizaUtils.RemoverConteudos(Result, TITULOS); Result := FFonetizaUtils.SubstituirConteudos(Result, LETRAS); Result := FFonetizaUtils.SubstituirConteudos(Result, NUMEROS); Result := FFonetizaUtils.SomarCaracteres(Result); Result := FFonetizaUtils.RemoverCaracteresDuplicados(Result); Result := FFonetizaCore.GerarConteudoFonetico(Result); Result := FFonetizaUtils.RemoverCaracteresDuplicados(Result); Result := FFonetizaUtils.SubstituirConteudos(Result, NOMES); Result := FFonetizaUtils.SubstituirConteudos(Result, SINONIMOS); end; function TFonetiza.GerarCodigoFonetico(const AValue: string): string; begin Result := Self.Fonetizar(AValue); Result := FCodigoFonetico.randomize(Result); end; function TFonetiza.GerarListaCodigosFoneticos(const AValue: string): TArray<string>; var LConteudoFonetico: string; begin LConteudoFonetico := Self.Fonetizar(AValue); Result := FCodigoFonetico.generateCodes(LConteudoFonetico); end; class function TFonetiza.New: IFonetiza; begin Result := Self.Create; end; end.
unit uObjectGuideList; interface uses SysUtils, Types, Contnrs, uOtherObjects; type TGuideList = class(TObjectList) protected function GetItem(Index: Integer): TGuideObject; procedure SetItem(Index: Integer; FeaObj: TGuideObject); public property Objects[Index: Integer]: TGuideObject read GetItem write SetItem; default; end; implementation { TFeaList } function TGuideList.GetItem(Index: Integer): TGuideObject; begin result := (Items[Index] as TGuideObject); end; procedure TGuideList.SetItem(Index: Integer; FeaObj: TGuideObject); begin Items[Index] := FeaObj; end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL; type TForm1 = class(TForm) memoRequest: TMemo; IdHTTP1: TIdHTTP; IdSSLIOHandlerSocketOpenSSL1: TIdSSLIOHandlerSocketOpenSSL; Button2: TButton; procedure Button2Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button2Click(Sender: TObject); var URL: string; EnvStr:tStringList; begin IdHTTP1.ReadTimeout:= 50000; URL := 'https://www.rdstation.com.br/api/1.3/conversions'; EnvStr:=TStringList.Create; EnvStr.Text := '{'+ '"token_rdstation": "",'+ //Obrigatório - Token Publico de autenticação '"identificador": "assinante",'+ //Obrigatório '"email": "eliezerfb@gmail.com",'+ //Obrigatório '"nome": "ELIÉZER",'+ //(responsável) '"empresa": "OCTANTIS TECNOLOGIA LTDA",'+ // (nome fantasia) '"telefone": "49-9-84020730",'+ '"datainicio": "01/10/2015",'+ '"datafim": "30/10/2016",'+ '"produto": "XPTO"'+ //Obrigatório '}'; IdHTTP1.Request.Clear; IdHTTP1.Request.CustomHeaders.Clear; IdHTTP1.Request.ContentType := 'application/json'; IdHTTP1.Request.CharSet := 'utf-8'; IdHTTP1.Request.CustomHeaders.AddValue('token_rdstation',''); IdHTTP1.Response.ContentType := 'application/json'; IdHTTP1.Response.CharSet := 'UTF-8'; try memoRequest.Text:=IdHTTP1.Post(URL, EnvStr); except on E:EIdHTTPProtocolException do ShowMessage(e.ErrorMessage); end; end; end.
unit ScaleData; interface uses Windows, SysUtils, Forms; const MX = 50; MY = 50; DEFAULT_SIZE_RULER = 3; SIZE_SCROLLBAR = 10; DEFAULT_SPACE = 3; SIZE_MARKER = 4; var // Шаг сетки STEP_GRID, // Размер логической точки в физических координатах PT_FYS, // Координаты вывода сетки по центру формы GRID_X, GRID_Y, GRID_WIDTH, GRID_HEIGHT, // Ширина списка компонентов CONTROL_LIST_WIDTH, // Ширина бордюра формы WIDTH_BORDER, // Шаг в обозначениях линейки STEP_RULER, // Размер линейки SIZE_RULER: Integer; // Прямоугольник линеек в левом углу RULER_RECT, // Прямоугольник в клиентских координатах GRID_RECT_CLIENT, // Прямоугольник сетки GRID_RECT: TRect; procedure DrawScaleData; implementation uses Classes; procedure DrawScaleData; begin case Screen.Width of 640: PT_FYS:= 6; 800: PT_FYS:= 8; 1024: PT_FYS:= 10; 1200: PT_FYS:= 12; else PT_FYS:= 14; end; WIDTH_BORDER:= PT_FYS div 2; SIZE_RULER:= DEFAULT_SIZE_RULER * PT_FYS; STEP_RULER:= 5; STEP_GRID:= PT_FYS; CONTROL_LIST_WIDTH:= MX * 2 + SIZE_SCROLLBAR + DEFAULT_SPACE; GRID_WIDTH:= MX * PT_FYS + SIZE_RULER + DEFAULT_SIZE_RULER; GRID_HEIGHT:= MY * PT_FYS + SIZE_RULER + DEFAULT_SIZE_RULER; end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO transiente. Montará os dados necessários para o registro R05. The MIT License Copyright: Copyright (C) 2010 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: t2ti.com@gmail.com</p> @author Albert Eije (T2Ti.COM) @version 1.0 *******************************************************************************} unit R05VO; interface type TR05VO = class private FID: Integer; FCOO: Integer; FCCF: Integer; FItem: Integer; FGTIN: String; FDescricaoPDV: String; FQuantidade: Double; FSiglaUnidade: String; FValorUnitario: Double; FDesconto: Double; FAcrescimo: Double; FTotalItem: Double; FTotalizadorParcial: String; FIndicadorCancelamento: String; FQuantidadeCancelada: Double; FValorCancelado: Double; FCancelamentoAcrescimo: Double; FIAT: String; FIPPT: String; FCasasDecimaisQuantidade: Integer; FCasasDecimaisValor: Integer; published property Id: Integer read FID write FID; property COO: Integer read FCOO write FCOO; property CCF: Integer read FCCF write FCCF; property Item: Integer read FItem write FItem; property GTIN: String read FGTIN write FGTIN; property DescricaoPDV: String read FDescricaoPDV write FDescricaoPDV; property Quantidade: Double read FQuantidade write FQuantidade; property SiglaUnidade: String read FSiglaUnidade write FSiglaUnidade; property ValorUnitario: Double read FValorUnitario write FValorUnitario; property Desconto: Double read FDesconto write FDesconto; property Acrescimo: Double read FAcrescimo write FAcrescimo; property TotalItem: Double read FTotalItem write FTotalItem; property TotalizadorParcial: String read FTotalizadorParcial write FTotalizadorParcial; property IndicadorCancelamento: String read FIndicadorCancelamento write FIndicadorCancelamento; property QuantidadeCancelada: Double read FQuantidadeCancelada write FQuantidadeCancelada; property ValorCancelado: Double read FValorCancelado write FValorCancelado; property CancelamentoAcrescimo: Double read FCancelamentoAcrescimo write FCancelamentoAcrescimo; property IAT: String read FIAT write FIAT; property IPPT: String read FIPPT write FIPPT; property CasasDecimaisQuantidade: Integer read FCasasDecimaisQuantidade write FCasasDecimaisQuantidade; property CasasDecimaisValor: Integer read FCasasDecimaisValor write FCasasDecimaisValor; end; implementation end.
unit UnFabricaDeAplicacoes; interface uses Classes, { Fluente } Util, DataUtil, Configuracoes, UnAplicacao, UnFabricaDeModelos; type TFabricaDeAplicacoes = class private FAplicacoes: TStringList; FConfiguracoes: TConfiguracoes; FDataUtil: TDataUtil; FFabricaDeModelos: TFabricaDeModelos; FUtil: TUtil; public function Configuracoes(const Configuracoes: TConfiguracoes): TFabricaDeAplicacoes; function DataUtil(const DataUtil: TDataUtil): TFabricaDeAplicacoes; function Descarregar: TFabricaDeAplicacoes; function DescarregarAplicacao(const Apliacao: TAplicacao): TFabricaDeAplicacoes; function FabricaDeModelos(const FabricaDeModelos: TFabricaDeModelos): TFabricaDeAplicacoes; function ObterAplicacao(const NomeDaAplicacao: string; const ConfiguracaoAplicacao: TConfiguracaoAplicacao = nil): TAplicacao; function Preparar: TFabricaDeAplicacoes; function Util(const Util: TUtil): TFabricaDeAplicacoes; end; implementation { TFabricaDeAplicacoes } function TFabricaDeAplicacoes.Configuracoes( const Configuracoes: TConfiguracoes): TFabricaDeAplicacoes; begin Self.FConfiguracoes := Configuracoes; Result := Self; end; function TFabricaDeAplicacoes.DataUtil( const DataUtil: TDataUtil): TFabricaDeAplicacoes; begin Self.FDataUtil := DataUtil; Result := Self; end; function TFabricaDeAplicacoes.Descarregar: TFabricaDeAplicacoes; begin Self.FConfiguracoes := nil; Self.FDataUtil := nil; Self.FUtil := nil; Result := Self; end; function TFabricaDeAplicacoes.DescarregarAplicacao( const Apliacao: TAplicacao): TFabricaDeAplicacoes; begin Result := Self; end; function TFabricaDeAplicacoes.FabricaDeModelos( const FabricaDeModelos: TFabricaDeModelos): TFabricaDeAplicacoes; begin Self.FFabricaDeModelos := FabricaDeModelos; Result := Self; end; function TFabricaDeAplicacoes.ObterAplicacao(const NomeDaAplicacao: string; const ConfiguracaoAplicacao: TConfiguracaoAplicacao): TAplicacao; var _aplicacao: TAplicacao; begin _aplicacao := TAplicacao(Classes.GetClass('T' + NomeDaAplicacao + 'Aplicacao')); if _aplicacao <> nil then begin Result := TPersistentClass(_aplicacao).Create as TAplicacao; Result .FabricaDeModelos(Self.FFabricaDeModelos) .Util(Self.FUtil) .DataUtil(Self.FDataUtil) .Configuracoes(Self.FConfiguracoes) .Preparar(ConfiguracaoAplicacao); Self.FAplicacoes.AddObject(NomeDaAplicacao, Result); end else Result := nil; end; function TFabricaDeAplicacoes.Preparar: TFabricaDeAplicacoes; begin Self.FAplicacoes := TStringList.Create; Result := Self; end; function TFabricaDeAplicacoes.Util( const Util: TUtil): TFabricaDeAplicacoes; begin Self.FUtil := Util; Result := Self; end; end.
unit u_utils; interface function IntToStr(Int : Integer):String; function FloatToStr(Float : Single; Digs : Integer = 3) : String; implementation function IntToStr; begin Str(Int, Result); end; function FloatToStr; begin Str(Float:3:Digs, Result); end; end.
program Sample; type RType = record A : Integer; B : Integer; C : record D : Integer; E : Integer; end; end; var X : RType; begin X.A := 1; X.B := 2; X.C.D := 3; X.C.E := 4; WriteLn('X.A = ', X.A, ', X.B = ', X.B); WriteLn('X.C.D = ', X.C.D, ', X.C.E = ', X.C.E); end.
unit uDownloadFiles; interface procedure DownloadAndUpdate; implementation uses Windows, Classes, SysUtils, StrUtils, IniFiles, uGlobal, slmlog, jyDownloadFTPFile, jyURLFunc, uFileVersionProc, md5, uDelphiCompress, uUpdateService, uHash; {$DEFINE DEBUG1} const DEFAULT_UPDATE_LIST_FILE_URL = 'ftp://10.23.2.112/Stations/Lanes/UpdateList.ulst'; UPDATE_MAIN_INI = 0; UPDATE_OTHER_FILE = 1; OP_TYPE_REGISTRY = 10; OP_TYPE_SELF = 20; OP_TYPE_SERVICE = 30; OP_TYPE_RUN = 40; OP_TYPE_MD5_COPY = 50; OP_TYPE_RENAME_COPY = 60; OP_TYPE_OVERWRITE = 70; OP_TYPE_COPY = 80; OP_TYPE_NONE = 255; ROLE_DEBUGGER = 10; ROLE_TESTER_ALPHA = 20; ROLE_TESTER_BETA = 30; ROLE_TESTER_RUN = 40; ROLE_USER = 50; type TRoleType = Byte; TServiceRunParams = record ServiceName: string; ExePath: string; Version: string; UpdateListFileURL: string; FTPUser: string; FTPPwd: string; Role: TRoleType; end; TUpdateType = Byte; TOperateType = Byte; PFileUpdateParam = ^TFileUpdateParam; TFileUpdateParam = record Status: TRoleType; MinUpdateSrvVerRequire: string; OriginalFile: string; OldVersion: string; UpdateURL: string; CompressType: TCompressType; FTPUser: string; FTPPwd: string; NewVersion: string; TempFile: string; OperateType: TOperateType; ServiceName: string; FileHash: string; PathHash: string; end; var RunParams: TServiceRunParams; UpdateFilesInfo: array of TFileUpdateParam; function StrToRole(AStr: string): TRoleType; {$message 'todo: 改为查表'} begin if LowerCase(AStr) = 'debugger' then result := ROLE_DEBUGGER else if LowerCase(AStr) = 'tester_alpha' then result := ROLE_TESTER_ALPHA else if LowerCase(AStr) = 'tester_beta' then result := ROLE_TESTER_BETA else if LowerCase(AStr) = 'tester_run' then result := ROLE_TESTER_RUN else result := ROLE_USER; end; function RoleToStr(ARole: TRoleType): string; begin case ARole of ROLE_DEBUGGER: result := 'debugger'; ROLE_TESTER_ALPHA: result := 'tester_alpha'; ROLE_TESTER_BETA: result := 'tester_beta'; ROLE_TESTER_RUN: result := 'tester_run'; else result := 'user'; end; end; function StrToOpType(AStr: string): TOperateType; {$message 'todo: 改为查表'} begin if LowerCase(AStr) = 'registry' then result := OP_TYPE_REGISTRY else if LowerCase(AStr) = 'self' then result := OP_TYPE_SELF else if LowerCase(AStr) = 'service' then result := OP_TYPE_SERVICE else if LowerCase(AStr) = 'run' then result := OP_TYPE_RUN else if LowerCase(AStr) = 'md5copy' then result := OP_TYPE_MD5_COPY else if LowerCase(AStr) = 'rename_copy' then result := OP_TYPE_RENAME_COPY else if LowerCase(AStr) = 'overwrite' then result := OP_TYPE_OVERWRITE else if LowerCase(AStr) = 'copy' then result := OP_TYPE_COPY else result := OP_TYPE_NONE; end; function OpTypeToStr(AOpType: TOperateType): string; begin case AOpType of OP_TYPE_REGISTRY: result := 'registry'; OP_TYPE_SELF: result := 'self'; OP_TYPE_SERVICE: result := 'service'; OP_TYPE_RUN: result := 'run'; OP_TYPE_MD5_COPY: result := 'md5copy'; OP_TYPE_RENAME_COPY: result := 'rename_copy'; OP_TYPE_OVERWRITE: result := 'overwrite'; OP_TYPE_COPY: result := 'copy'; else result := 'none'; end; end; function CompressTypeToStr(ACompressType: TCompressType): string; begin case ACompressType of COMPRESS_TYPE_NONE: result := 'none'; COMPRESS_TYPE_D6ZLIB1: result := 'd6zlib1'; COMPRESS_TYPE_D6ZLIB2: result := 'd6zlib2'; else result := 'unknown'; end; end; function GetWinDir: string; var buf: array[0..MAX_PATH-1] of char; begin ZeroMemory(@buf[0], sizeof(buf)); GetWindowsDirectory(@buf[0], MAX_PATH); result := PChar(@buf[0]); if RightStr(result, 1) <> '\' then result := result + '\'; end; procedure GetServerRunParams; var strRole: string; szFilePath: array[0..MAX_PATH-1] of char; strIniFile: string; begin ZeroMemory(@szFilePath[0], sizeof(szFilePath)); GetModuleFileName(0, szFilePath, MAX_PATH); RunParams.ServiceName := SERVICE_NAME; RunParams.ExePath := PChar(@szFilePath[0]); RunParams.Version := GetFileVersion(RunParams.ExePath); RunParams.UpdateListFileURL := DEFAULT_UPDATE_LIST_FILE_URL; RunParams.FTPUser := ''; RunParams.FTPPwd := ''; RunParams.Role := ROLE_USER; strIniFile := Format('%s%s', [GetWinDir, SERVER_IP_INI_FILE]); if not FileExists(strIniFile) then begin SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('GetServerRunParams(): %s not exists.', [strIniFile])); exit; end; with TIniFile.Create(strIniFile) do try try RunParams.UpdateListFileURL := ReadString('Main', 'UpdateListFileURL', DEFAULT_UPDATE_LIST_FILE_URL); RunParams.FTPUser := ReadString('Main', 'FTPUserName', ''); RunParams.FTPPwd := ReadString('Main', 'FTPPassword', ''); strRole := ReadString('Main', 'ROLE', 'Normal'); if LowerCase(strRole) = 'debugger' then RunParams.Role := ROLE_DEBUGGER else if LowerCase(strRole) = 'tester_alpha' then RunParams.Role := ROLE_TESTER_ALPHA else if LowerCase(strRole) = 'tester_beta' then RunParams.Role := ROLE_TESTER_BETA else if LowerCase(strRole) = 'tester_run' then RunParams.Role := ROLE_TESTER_RUN else RunParams.Role := ROLE_USER; SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('GetServerRunParams(): Init Finished. ListFile: %s; Role: %s', [RunParams.UpdateListFileURL, strRole])); finally Free; end; except end; end; function DownLoadUpdateListFile(var AListFilePath: string): boolean; var ADomain, AUser, APwd, ADir, ARemoteFileName: string; APort: integer; strLocalFilePath: string; begin result := false; AListFilePath := ''; if not AnalyzeFTPUrl(RunParams.UpdateListFileURL, AUser, APwd, ADomain, APort, ADir, ARemoteFileName) then begin SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('DownLoadUpdateListFile(): AnalyzeFTPUrl Fail. (URL: %s)', [RunParams.UpdateListFileURL])); exit; end; if ARemoteFileName = '' then begin SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('DownLoadUpdateListFile(): RemoteFileName is null', [])); exit; end; strLocalFilePath := Format('%s%s', [CACHE_PATH, ARemoteFileName]); if not DownloadToFile(RunParams.UpdateListFileURL, RunParams.FTPUser, RunParams.FTPPwd, strLocalFilePath, true) then begin SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('DownLoadUpdateListFile(): Download List File Fail. URL: %s; LocalFile: %s', [RunParams.UpdateListFileURL, strLocalFilePath])); exit; end; AListFilePath := strLocalFilePath; result := true; end; function GenerateCacheFileName(AURL: string; AIndex: integer): string; var ADomain, AUser, APwd, ADir: string; APort: integer; strRemoteFile: string; begin result := ''; if not AnalyzeFTPUrl(AURL, AUser, APwd, ADomain, APort, ADir, strRemoteFile) then begin SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('GenerateCacheFileName(): AnalyzeFTPUrl Fail. (URL: %s)', [AURL])); exit; end; result := Format('%s%s.%s%.2d', [CACHE_PATH, strRemoteFile, FormatDateTime('yyyymmddhhnnsszzz', now), AIndex]); end; function ReadUpdateFileList(AListFilePath: string): boolean; var i: integer; iFileNumber: integer; strSection: string; begin result := false; with TIniFile.Create(AListFilePath) do try try iFileNumber := ReadInteger('Main', 'FileNumber', 0); SetLength(UpdateFilesInfo, iFileNumber); for i:=0 to iFileNumber-1 do begin strSection := Format('File%.2d', [i+1]); UpdateFilesInfo[i].Status := StrToRole(Trim(ReadString(strSection, 'Status', 'user'))); UpdateFilesInfo[i].MinUpdateSrvVerRequire := Trim(ReadString(strSection, 'MinSvrVer', '1.0.0.0')); UpdateFilesInfo[i].OperateType := StrToOpType(Trim(ReadString(strSection, 'OpType', 'none'))); UpdateFilesInfo[i].ServiceName := Trim(ReadString(strSection, 'ServiceName', '')); if UpdateFilesInfo[i].OperateType = OP_TYPE_SELF then UpdateFilesInfo[i].OriginalFile := RunParams.ExePath else UpdateFilesInfo[i].OriginalFile := Trim(ReadString(strSection, 'Path', '')); UpdateFilesInfo[i].OldVersion := GetFileVersion(UpdateFilesInfo[i].OriginalFile); UpdateFilesInfo[i].UpdateURL := Trim(ReadString(strSection, 'URL', '')); UpdateFilesInfo[i].CompressType := StrToCompressType(Trim(ReadString(strSection, 'CompressType', ''))); UpdateFilesInfo[i].FTPUser := Trim(ReadString(strSection, 'UserName', '')); UpdateFilesInfo[i].FTPPwd := Trim(ReadString(strSection, 'Password', '')); UpdateFilesInfo[i].NewVersion := Trim(ReadString(strSection, 'Version', '0.0.0.0')); UpdateFilesInfo[i].FileHash := Trim(ReadString(strSection, 'FileHash', '')); UpdateFilesInfo[i].PathHash := Trim(ReadString(strSection, 'PathHash', '')); UpdateFilesInfo[i].TempFile := GenerateCacheFileName(UpdateFilesInfo[i].UpdateURL, i); {$IFDEF DEBUG} SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('ReadUpdateFileList(): File%.2d Status:%s; ' + 'OriginalFile:%s; ' + 'OldVersion:%s; ' + 'UpdateURL:%s; ' + 'CompressType:%s; ' + 'NewVersion:%s; ' + 'TempFile:%s; '+ 'OperateType:%s; '+ 'ServiceName:%s;', [i+1, RoleToStr(UpdateFilesInfo[i].Status), UpdateFilesInfo[i].OriginalFile, UpdateFilesInfo[i].OldVersion, UpdateFilesInfo[i].UpdateURL, CompressTypeToStr(UpdateFilesInfo[i].CompressType), UpdateFilesInfo[i].NewVersion, UpdateFilesInfo[i].TempFile, OpTypeToStr(UpdateFilesInfo[i].OperateType), UpdateFilesInfo[i].ServiceName])); {$ENDIF} end; DeleteFile(AListFilePath); result := true; finally Free; end; except end; end; function MD5FileExists(ATargetPath, AAESMD5String: string): boolean; var strTarget: string; begin strTarget := AESMD5ToMD5String(AAESMD5String); strTarget := StringReplace(strTarget, 'A', '10', [rfReplaceAll]); strTarget := StringReplace(strTarget, 'B', '11', [rfReplaceAll]); strTarget := StringReplace(strTarget, 'C', '12', [rfReplaceAll]); strTarget := StringReplace(strTarget, 'D', '13', [rfReplaceAll]); strTarget := StringReplace(strTarget, 'E', '14', [rfReplaceAll]); strTarget := StringReplace(strTarget, 'F', '15', [rfReplaceAll]); strTarget := Format('%s%s.~~~', [ExtractFilePath(ATargetPath), LeftStr(strTarget, 8)]); result := FileExists(strTarget); end; function Update_Do_MD5Copy(ASourceFile: string; ATargetPath: string): boolean; var strTarget: string; begin result := false; if VersionCheck(GetFileVersion(ASourceFile), GetFileVersion(ATargetPath)) <= 0 then begin SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('Update_Do_MD5Copy(): Skip Update %s, Ver.%s ==> Ver.%s', [ATargetPath, GetFileVersion(ATargetPath), GetFileVersion(ASourceFile)])); DeleteFile(ASourceFile); exit; end; strTarget := MD5DigestToStr(MD5File(ASourceFile)); strTarget := StringReplace(strTarget, 'A', '10', [rfReplaceAll]); strTarget := StringReplace(strTarget, 'B', '11', [rfReplaceAll]); strTarget := StringReplace(strTarget, 'C', '12', [rfReplaceAll]); strTarget := StringReplace(strTarget, 'D', '13', [rfReplaceAll]); strTarget := StringReplace(strTarget, 'E', '14', [rfReplaceAll]); strTarget := StringReplace(strTarget, 'F', '15', [rfReplaceAll]); strTarget := Format('%s%s.~~~', [ExtractFilePath(ATargetPath), LeftStr(strTarget, 8)]); result := CopyFile(PChar(ASourceFile), PChar(strTarget), false); if result then SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('Update_Do_MD5Copy(): Success copy %s to %s', [ASourceFile, strTarget])) else SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('Update_Do_MD5Copy(): Copy %s to %s Fail.', [ASourceFile, strTarget])); DeleteFile(ASourceFile); end; function Update_Do_Copy(ASourceFile: string; ATargetPath: string): boolean; begin result := false; if (VersionCheck(GetFileVersion(ASourceFile), GetFileVersion(ATargetPath)) <= 0) then begin SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('Update_Do_Copy(): Skip Update %s, Ver.%s ==> Ver.%s', [ATargetPath, GetFileVersion(ATargetPath), GetFileVersion(ASourceFile)])); DeleteFile(ASourceFile); exit; end; result := CopyFile(PChar(ASourceFile), PChar(ATargetPath), false); if result then SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('Update_Do_Copy(): Success copy %s to %s', [ASourceFile, ATargetPath])) else SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('Update_Do_Copy(): Copy %s to %s Fail.', [ASourceFile, ATargetPath])); DeleteFile(ASourceFile); end; function Update_Do_OverWrite(ASourceFile: string; ATargetPath: string): boolean; begin result := false; result := CopyFile(PChar(ASourceFile), PChar(ATargetPath), false); if result then SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('Update_Do_OverWrite(): Success copy %s to %s', [ASourceFile, ATargetPath])) else SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('Update_Do_OverWrite(): Copy %s to %s Fail.', [ASourceFile, ATargetPath])); DeleteFile(ASourceFile); end; function Update_Do_UpdateService(ASourceFile, AServiceName, ATargetFile, ANewVersion: string): boolean; begin result := false; end; function Update_Do_Run(ATempFile: string; ATarget: string): boolean; begin result := false; try try if FileExists(ATarget) then begin SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('Update_Do_Run(): Skip Run %s, Target File Exists.', [ATarget])); result := true; exit; end; CopyFile(PChar(ATempFile), PChar(ATarget), false); result := (WinExec(PChar(ATarget), SW_HIDE) >= 32); finally DeleteFile(ATempFile); end; except end; end; function Update_Do_SelfUpdate(ASourceFile, AServiceName: string): boolean; begin result := false; if LowerCase(Trim(AServiceName)) <> LowerCase(Trim(RunParams.ServiceName)) then begin SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('UpdateSingleFile(): Skip Update Self, Service Name not match: %s<>%s', [AServiceName, RunParams.ServiceName])); DeleteFile(ASourceFile); exit; end; result := UpdateService(ASourceFile, RunParams.ServiceName); end; function UpdateSingleFile(AUpdateParam: PFileUpdateParam): boolean; var strmFile: TMemoryStream; begin result := false; strmFile := TMemoryStream.Create; try try //本机角色不需要更新 if RunParams.Role > AUpdateParam^.Status then begin SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('UpdateSingleFile(): Skip %s, File Status:%s, Myself Role:%s', [AUpdateParam^.OriginalFile, RoleToStr(AUpdateParam^.Status), RoleToStr(RunParams.Role)])); exit; end; //更新服务版本不够新 if (VersionCheck(RunParams.Version, AUpdateParam^.MinUpdateSrvVerRequire) < 0) then begin SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('UpdateSingleFile(): Skip %s, Service Version:%s, Require Min Version:%s', [AUpdateParam^.OriginalFile, RunParams.Version, AUpdateParam^.MinUpdateSrvVerRequire])); exit; end; //目标路径hash错 if (AUpdateParam^.OperateType in [OP_TYPE_MD5_COPY, OP_TYPE_RENAME_COPY, OP_TYPE_OVERWRITE, OP_TYPE_COPY]) and (CalcPathAESMD5(LowerCase(Trim(AUpdateParam^.OriginalFile))) <> AUpdateParam^.PathHash) then begin SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('UpdateSingleFile(): Skip %s, PathHash Error.', [AUpdateParam^.OriginalFile])); exit; end; if not (AUpdateParam^.OperateType in [OP_TYPE_REGISTRY, OP_TYPE_RUN, OP_TYPE_OVERWRITE]) then begin //版本已经是最新的,不必更新 if (VersionCheck(AUpdateParam^.NewVersion, AUpdateParam^.OldVersion) <= 0) then begin SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('UpdateSingleFile(): Skip %s, Original File Version Newest, OldVersion:%s, NewVersion:%s', [AUpdateParam^.OriginalFile, AUpdateParam^.OldVersion, AUpdateParam^.NewVersion])); exit; end; end; //导入和运行的文件已经存在,说明下载运行过,不必更新 if (AUpdateParam^.OperateType in [OP_TYPE_REGISTRY, OP_TYPE_RUN]) then begin if FileExists(AUpdateParam^.OriginalFile) then begin SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('UpdateSingleFile(): Skip %s, Run/Registry Target File Exists.', [AUpdateParam^.OriginalFile])); exit; end; end; //MD5COPY的目标文件已经存在 if MD5FileExists(AUpdateParam^.OriginalFile, AUpdateParam^.FileHash) then begin SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('UpdateSingleFile(): Skip %s, MD5Copy Target File Exists.', [AUpdateParam^.OriginalFile])); exit; end; //下载失败则停止更新 if not DownloadToStream(AUpdateParam^.UpdateURL, AUpdateParam^.FTPUser, AUpdateParam^.FTPPwd, strmFile) then begin SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('UpdateSingleFile(): Skip %s, Download Fail.', [AUpdateParam^.OriginalFile])); exit; end; //解压失败则停止更新 if not DelphiDecompressStream(AUpdateParam^.CompressType, strmFile, AUpdateParam^.TempFile) then begin SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('UpdateSingleFile(): Skip %s, Decompress Fail.', [AUpdateParam^.OriginalFile])); exit; end; //文件hash错 if (CalcFileAESMD5(AUpdateParam^.TempFile) <> AUpdateParam^.FileHash) then begin SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('UpdateSingleFile(): Skip %s, FileHash Error.', [AUpdateParam^.OriginalFile])); exit; end; case AUpdateParam^.OperateType of OP_TYPE_REGISTRY: ; OP_TYPE_SELF: result := Update_Do_SelfUpdate(AUpdateParam^.TempFile, AUpdateParam^.ServiceName); OP_TYPE_SERVICE: Update_Do_UpdateService(AUpdateParam^.TempFile, AUpdateParam^.ServiceName, AUpdateParam^.OriginalFile, AUpdateParam^.NewVersion); OP_TYPE_RUN: Update_Do_Run(AUpdateParam^.TempFile, AUpdateParam^.OriginalFile); OP_TYPE_MD5_COPY: result := Update_Do_MD5Copy(AUpdateParam^.TempFile, AUpdateParam^.OriginalFile); OP_TYPE_RENAME_COPY: ; OP_TYPE_OVERWRITE: Update_Do_OverWrite(AUpdateParam^.TempFile, AUpdateParam^.OriginalFile); OP_TYPE_COPY: Update_Do_Copy(AUpdateParam^.TempFile, AUpdateParam^.OriginalFile); OP_TYPE_NONE: begin result := false; SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('UpdateSingleFile(): Skip %s, OpType=none', [AUpdateParam^.OriginalFile])); end; end; finally strmFile.Free; end; except end; end; function UpdateAllFiles: integer; var i: integer; res: boolean; begin result := 0; {$message '先排序(暂时手动在ulst文件中给出正确顺序)'} for i:=0 to Length(UpdateFilesInfo)-1 do begin res := UpdateSingleFile(@UpdateFilesInfo[i]); if res then Inc(result); if (UpdateFilesInfo[i].OperateType = OP_TYPE_SELF) and res then begin SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('UpdateAllFiles(): Self Update, Skip All Others!!!', [])); break; end; end; end; procedure DownloadAndUpdate; var AListFilePath: string; iUpdateNumber: integer; begin try SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), ''); GetServerRunParams; ForceDirectories(CACHE_PATH); if not DownLoadUpdateListFile(AListFilePath) then exit; if not ReadUpdateFileList(AListFilePath) then exit; iUpdateNumber := UpdateAllFiles; SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('DownloadAndUpdate(): %d of %d File(s) Updated.', [iUpdateNumber, Length(UpdateFilesInfo)])); except end; end; end.
unit UCtrlCompra; interface uses uController, DB, UDaoCompra; type CtrlCompra = class(Controller) private protected umaDaoCompra : DaoCompra; public Constructor CrieObjeto; Destructor Destrua_se; function Salvar(obj:TObject): string; override; function GetDS : TDataSource; override; function Carrega(obj:TObject): TObject; override; function Buscar(obj : TObject) : Boolean; override; function Excluir(obj : TObject) : string ; override; function VerificarNota (obj : TObject) : Boolean; end; implementation { CtrlCompra } function CtrlCompra.Buscar(obj: TObject): Boolean; begin result := umaDaoCompra.Buscar(obj); end; function CtrlCompra.VerificarNota(obj: TObject): Boolean; begin result := umaDaoCompra.VerificarNota(obj); end; function CtrlCompra.Carrega(obj: TObject): TObject; begin result := umaDaoCompra.Carrega(obj); end; constructor CtrlCompra.CrieObjeto; begin umaDaoCompra := DaoCompra.CrieObjeto; end; destructor CtrlCompra.Destrua_se; begin umaDaoCompra.Destrua_se; end; function CtrlCompra.Excluir(obj: TObject): string; begin result := umaDaoCompra.Excluir(obj); end; function CtrlCompra.GetDS: TDataSource; begin result := umaDaoCompra.GetDS; end; function CtrlCompra.Salvar(obj: TObject): string; begin result := umaDaoCompra.Salvar(obj); end; end.
unit Device.PhysicalDrive; interface uses Windows, SysUtils, Device.PhysicalDrive.Bus, Device.PhysicalDrive.OS, OSFile, OSFile.Interfaced, Support, Support.Factory, Getter.PhysicalDrive.PartitionList, BufferInterpreter, Getter.PhysicalDrive.NCQAvailability, OS.Handle; type IPhysicalDrive = interface['{6D76DB52-42D7-4E84-AFAB-61594C7456F9}'] function GetSupportStatusOrRequestAndReturn: TSupportStatus; function GetDiskSizeInByte: TLargeInteger; function GetIsDriveAvailable: Boolean; function GetIdentifyDeviceResult: TIdentifyDeviceResult; function GetSMARTInterpretedOrRequestAndReturn: TSMARTInterpreted; function GetNCQAvailability: TNCQAvailability; function GetPathOfFileAccessing: String; function GetPathOfFileAccessingWithoutPrefix: String; property IdentifyDeviceResult: TIdentifyDeviceResult read GetIdentifyDeviceResult; property SMARTInterpreted: TSMARTInterpreted read GetSMARTInterpretedOrRequestAndReturn; property SupportStatus: TSupportStatus read GetSupportStatusOrRequestAndReturn; property DiskSizeInByte: TLargeInteger read GetDiskSizeInByte; property IsDriveAvailable: Boolean read GetIsDriveAvailable; property NCQAvailability: TNCQAvailability read GetNCQAvailability; function GetPartitionList: TPartitionList; function Unlock: IOSFileUnlock; end; TPhysicalDrive = class(TInterfacedOSFile, IPhysicalDrive) private SupportStatusReadWrite: TSupportStatus; SMARTInterpretedReadWrite: TSMARTInterpreted; OSPhysicalDrive: TOSPhysicalDrive; BusPhysicalDrive: TBusPhysicalDrive; NSTSupport: TNSTSupport; procedure RequestSMARTInterpreted; procedure RequestSupportStatus; function GetSupportStatusOrRequestAndReturn: TSupportStatus; function GetSMARTInterpretedOrRequestAndReturn: TSMARTInterpreted; function GetDiskSizeInByte: TLargeInteger; function GetIsDriveAvailable: Boolean; procedure TryToCreateAndSetNSTSupport; function GetIdentifyDeviceResult: TIdentifyDeviceResult; function GetNCQAvailability: TNCQAvailability; procedure TryToCreateNSTSupportByFactory( const NSTSupportFactory: TNSTSupportFactory); public property IdentifyDeviceResult: TIdentifyDeviceResult read GetIdentifyDeviceResult; property SMARTInterpreted: TSMARTInterpreted read GetSMARTInterpretedOrRequestAndReturn; property SupportStatus: TSupportStatus read GetSupportStatusOrRequestAndReturn; property DiskSizeInByte: TLargeInteger read GetDiskSizeInByte; property IsDriveAvailable: Boolean read GetIsDriveAvailable; property NCQAvailability: TNCQAvailability read GetNCQAvailability; function GetPartitionList: TPartitionList; function Unlock: IOSFileUnlock; constructor Create(const FileToGetAccess: String); override; class function BuildFileAddressByNumber(const DriveNumber: Cardinal): String; destructor Destroy; override; end; implementation { TPhysicalDrive } constructor TPhysicalDrive.Create(const FileToGetAccess: String); begin inherited Create(FileToGetAccess); BusPhysicalDrive := TBusPhysicalDrive.Create(FileToGetAccess); OSPhysicalDrive := TOSPhysicalDrive.Create(FileToGetAccess); end; class function TPhysicalDrive.BuildFileAddressByNumber( const DriveNumber: Cardinal): String; begin result := ThisComputerPrefix + PhysicalDrivePrefix + UIntToStr(DriveNumber); end; destructor TPhysicalDrive.Destroy; begin if OSPhysicalDrive <> nil then FreeAndNil(OSPhysicalDrive); if BusPhysicalDrive <> nil then FreeAndNil(BusPhysicalDrive); if NSTSupport <> nil then FreeAndNil(NSTSupport); inherited; end; function TPhysicalDrive.GetDiskSizeInByte: TLargeInteger; begin result := OSPhysicalDrive.DiskSizeInByte; end; function TPhysicalDrive.GetNCQAvailability: TNCQAvailability; begin result := OSPhysicalDrive.NCQAvailability; end; function TPhysicalDrive.GetIsDriveAvailable: Boolean; begin result := OSPhysicalDrive.IsDriveAvailable; end; function TPhysicalDrive.GetPartitionList: TPartitionList; begin result := OSPhysicalDrive.GetPartitionList; end; function TPhysicalDrive.GetIdentifyDeviceResult: TIdentifyDeviceResult; begin result := BusPhysicalDrive.IdentifyDeviceResult; end; function TPhysicalDrive.GetSupportStatusOrRequestAndReturn: TSupportStatus; begin if SupportStatusReadWrite.Supported = NotSupported then RequestSupportStatus; result := SupportStatusReadWrite; end; function TPhysicalDrive.Unlock: IOSFileUnlock; begin result := BusPhysicalDrive.Unlock; end; function TPhysicalDrive.GetSMARTInterpretedOrRequestAndReturn: TSMARTInterpreted; begin if SMARTInterpretedReadWrite.UsedHour = 0 then RequestSMARTInterpreted; result := SMARTInterpretedReadWrite; end; procedure TPhysicalDrive.TryToCreateAndSetNSTSupport; var NSTSupportFactory: TNSTSupportFactory; begin NSTSupportFactory := TNSTSupportFactory.Create; try TryToCreateNSTSupportByFactory(NSTSupportFactory); finally FreeAndNil(NSTSupportFactory); end; end; procedure TPhysicalDrive.TryToCreateNSTSupportByFactory( const NSTSupportFactory: TNSTSupportFactory); begin try NSTSupport := NSTSupportFactory.GetSuitableNSTSupport( IdentifyDeviceResult, BusPhysicalDrive.SMARTValueList); except FreeAndNil(NSTSupport); end; end; procedure TPhysicalDrive.RequestSupportStatus; begin if NSTSupport = nil then TryToCreateAndSetNSTSupport; if NSTSupport = nil then SupportStatusReadWrite.Supported := NotSupported else SupportStatusReadWrite := NSTSupport.GetSupportStatus; end; procedure TPhysicalDrive.RequestSMARTInterpreted; begin if NSTSupport = nil then TryToCreateAndSetNSTSupport; if NSTSupport <> nil then SMARTInterpretedReadWrite := NSTSupport.GetSMARTInterpreted( BusPhysicalDrive.SMARTValueList); end; end.
unit uPlImagePluginInterface; interface uses Windows, OpenGL; const Class_PlImagePlugin: TGUID = '{0A2CA0B1-6073-449F-849F-17FED1C70AF1}'; type HIMAGE = Integer; HEFFECT = Integer; IPlImagePluginInterface = interface(IInterface) ['{E94A64FF-A587-4D28-81EF-394A6F248049}'] function IMImage_Load(PData: Pointer; DataSize: Integer): HIMAGE; function IMImage_WindowShow(MonitorIndex: Integer; WindowRect: TRect): HWND; function IMImage_WindowHide: HRESULT; function IMImage_Show(AImage: HIMAGE): HRESULT; function IMImage_ShowPreview(AImage: HIMAGE): HRESULT; function IMImage_Hide(AImage: HIMAGE): HRESULT; function IMImage_GetData(AImage: HIMAGE; var PData: Pointer; var DataSize: Integer): HRESULT; function IMImage_Duplicate(AImage: HIMAGE): HIMAGE; procedure IMImage_Free(AImage: HIMAGE); function IMImage_GetPreviewTex(AImage: HIMAGE; ADC: HDC; ARC: HGLRC): GLuint; procedure IMImage_FreeGLContext(ADC: HDC; ARC: HGLRC); end; implementation end.
unit ncDebug; { ResourceString: Dario 12/03/13 } interface uses Windows, SyncObjs, SysUtils; var AbriuArqDebug : Boolean = False; DebugAtivo : Boolean = False; arqDebug : TextFile; debugCS : TCriticalSection = nil; nomearqdebug : String = 'debug.txt'; // do not localize procedure DebugMsg(S: String; const aShowMsg: Boolean = False); overload; procedure DebugMsg(Sender:TObject; S: String; const aShowMsg: Boolean = False); overload; procedure DebugMsgEsp(S: String; const aShowMsg, aForcar: Boolean); overload; procedure DebugMsgEsp(Sender:TObject; S: String; const aShowMsg, aForcar: Boolean); overload; procedure DesativaDebug; procedure DebugEx(aObj: TObject; aFuncao: String; E: Exception; const aForcar: Boolean = True); implementation procedure AbreArquivo; var S: String; begin debugCS.Enter; try try S := ExtractFileName(ParamStr(0)); S := Copy(S, 1, Pos('.', S)-1); S := ExtractFilePath(ParamStr(0))+'logs\'+S+'_debug_'+FormatDateTime('yyyymmddhhnnss', now)+'.txt'; AssignFile(arqDebug, S); if FileExists(S) then Append(arqDebug) else Rewrite(arqDebug); Writeln(arqDebug, '-------------------------------------------------'); Writeln(arqDebug, ' INICIO: '+FormatDateTime('dd/mm/yyyy hh:nn:ss', Now)); // do not localize Writeln(arqDebug, '-------------------------------------------------'); except end; AbriuArqDebug := True; finally debugCS.Leave; end; end; function ThreadIDStr: String; var T : TThreadID; begin T := GetCurrentThreadID; if T=MainThreadID then Result := 'main.t' else Result := IntToStr(T); while Length(Result)<6 do Result := '0'+Result; end; procedure DebugEx(aObj: TObject; aFuncao: String; E: Exception; const aForcar: Boolean = True); var S : String; begin S := ''; if Assigned(aObj) then S := aObj.ClassName + ' - '; if aFuncao>'' then S := aFuncao + ' - ' + E.ClassName + ' - ' + E.Message else S := E.ClassName + ' - ' + E.Message; DebugMsgEsp(aObj, S, False, aForcar); end; procedure DebugMsgEsp(S: String; const aShowMsg, aForcar: Boolean); var SaveAtivo : Boolean; begin debugCS.Enter; try try SaveAtivo := DebugAtivo; if aForcar or DebugAtivo then begin if not AbriuArqDebug then AbreArquivo; if Trim(S)>'' then Writeln(arqDebug, FormatDateTime('dd/mm/yyyy hh:nn:ss.zzz', Now)+' - '+ThreadIDStr+' - '+S) else Writeln(arqDebug); Flush(arqDebug); end; if aForcar and (not SaveAtivo) then DesativaDebug; except end; finally debugCS.Leave; end; { if aForcar then gLog.ForceLog(nil, [lcDebug], S) else gLog.Log(nil, [lcDebug], S); gLog.ForceLogWrite;} end; procedure DebugMsgEsp(Sender:TObject;S: String; const aShowMsg, aForcar: Boolean); begin if Assigned(Sender) then DebugMsgEsp(Sender.ClassName + ' - ' + S, False, aForcar) else DebugMsgEsp(S, False, aForcar); { if aForcar then gLog.ForceLog(Sender, [lcDebug], S) else gLog.Log(Sender, [lcDebug], S); gLog.ForceLogWrite;} end; procedure DebugMsg(S: String; const aShowMsg: Boolean = False); begin DebugMsgEsp(S, aShowMsg, False); { gLog.Log(nil, [lcDebug], S); gLog.ForceLogWrite;} end; procedure DebugMsg(Sender:TObject;S: String; const aShowMsg: Boolean = False); begin DebugMsgEsp(Sender, S, aShowMsg, False); { gLog.Log(Sender, [lcDebug], S); gLog.ForceLogWrite;} end; procedure DesativaDebug; begin DebugCS.Enter; try DebugAtivo := False; if AbriuArqDebug then begin CloseFile(arqDebug); AbriuArqDebug := False; end; finally DebugCS.Leave; end; end; initialization DebugCS := TCriticalSection.Create; AbriuArqDebug := False; finalization try DesativaDebug; except end; FreeAndNil(DebugCS); end.
unit SubsidiaryList; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseGridDetail, Data.DB, RzButton, Vcl.StdCtrls, Vcl.Mask, RzEdit, Vcl.Grids, Vcl.DBGrids, RzDBGrid, RzLabel, Vcl.ExtCtrls, RzPanel, RzDBEdit, Vcl.DBCtrls, RzDBCmbo; type TfrmSubsidiaryList = class(TfrmBaseGridDetail) Label2: TLabel; edSubsidiary: TRzDBEdit; Label3: TLabel; dbluType: TRzDBLookupComboBox; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } protected function EntryIsValid: boolean; override; function NewIsAllowed: boolean; override; function EditIsAllowed: boolean; override; procedure SearchList; override; procedure BindToObject; override; public { Public declarations } end; implementation {$R *.dfm} uses AccountingAuxData, IFinanceDialogs; { TfrmSubsidiaryList } procedure TfrmSubsidiaryList.BindToObject; begin inherited; end; function TfrmSubsidiaryList.EditIsAllowed: boolean; begin end; function TfrmSubsidiaryList.EntryIsValid: boolean; var error: string; begin if Trim(edSubsidiary.Text) = '' then error := 'Please enter subsidiary.' else if Trim(dbluType.Text) = '' then error := 'Please select type.'; if error <> '' then ShowErrorBox(error); Result := error = ''; end; procedure TfrmSubsidiaryList.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; dmAccountingAux.Free; end; procedure TfrmSubsidiaryList.FormCreate(Sender: TObject); begin dmAccountingAux := TdmAccountingAux.Create(self); inherited; end; function TfrmSubsidiaryList.NewIsAllowed: boolean; begin end; procedure TfrmSubsidiaryList.SearchList; begin grList.DataSource.DataSet.Locate('subsidiary_name',edSearchKey.Text, [loPartialKey,loCaseInsensitive]); end; end.
unit Unit1; interface uses System.Classes, System.SysUtils, Vcl.Forms, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Controls, GLObjects, GLScene, GLCadencer, GLWin32Viewer, GLPolyhedron, GLCrossPlatform, GLCoordinates, GLBaseClasses, GLBehaviours; type TForm1 = class(TForm) GLSceneViewer1: TGLSceneViewer; GLScene1: TGLScene; GLCamera1: TGLCamera; GLLightSource1: TGLLightSource; Hexahedron: TGLCube; DummyCube1: TGLDummyCube; GLCadencer1: TGLCadencer; Panel1: TPanel; Label2: TLabel; Label3: TLabel; Label4: TLabel; CheckBox1: TCheckBox; Panel2: TPanel; Label1: TLabel; Label5: TLabel; Dodecahedron: TGLDodecahedron; Icosahedron: TGLIcosahedron; Octahedron: TGLOctahedron; Tetrahedron: TGLTetrahedron; procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure FormCreate(Sender: TObject); procedure CheckBox1Click(Sender: TObject); procedure GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); private lastTime : Double; pickedObject : TGLBaseSceneObject; public // end; var Form1: TForm1; implementation {$R *.DFM} procedure TForm1.FormCreate(Sender: TObject); begin // Initialize last time lastTime:=Now*3600*24; // Initialize rotation dampings... // ...using properties... with GetOrCreateInertia(Hexahedron.Behaviours).RotationDamping do begin Constant:=1; Linear:=1; Quadratic:=0; end; // ...using helper function on the TGLBehaviours... GetOrCreateInertia(Dodecahedron.Behaviours).RotationDamping.SetDamping(10, 0, 0.01); // ...or using helper function directly on the TGLBaseSceneObject GetOrCreateInertia(Octahedron.Behaviours).RotationDamping.SetDamping(0, 0, 0.01); GetOrCreateInertia(Icosahedron.Behaviours).RotationDamping.SetDamping(0, 0, 0.01); GetOrCreateInertia(Tetrahedron.Behaviours).RotationDamping.SetDamping(0, 0, 0.01); end; procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin // Mouse moved, get what's underneath pickedObject:=GLSceneViewer1.Buffer.GetPickedObject(x, y); end; procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); begin // apply some "torque" to the pickedObject if any if Assigned(pickedObject) then GetOrCreateInertia(pickedObject).ApplyTorque(deltaTime, 200, 0, 0); end; procedure TForm1.CheckBox1Click(Sender: TObject); var i : Integer; mass : Single; begin if CheckBox1.Checked then mass:=2 else mass:=1; // all our objects are child of the DummyCube1 for i:=0 to DummyCube1.Count-1 do GetOrCreateInertia(DummyCube1.Children[i]).Mass:=mass; end; end.
unit myutils; interface uses Grijjy.Bson, Grijjy.Bson.Serialization, classes, winapi.messages; type TJsonCD = class class function unmarshal<T>(Message: TMessage): T; static; end; IPrimitiveBox<T> = interface procedure setValue(value: T); function getValue(): T; end; TPrimitiveBox<T> = class(TInterfacedObject, IPrimitiveBox<T>) private value: T; public constructor create(value: T); // IPrimtiveBox<T> procedure setValue(value: T); function getValue(): T; end; function UnixMillisToDateTime(T: UInt64): TDateTime; function DateTimeToUnixMillis(T: TDateTime): UInt64; procedure EnumComports(const Ports: TStrings); procedure ExecuteAndWait(const aCommando: string); function getCopyDataString(Message: TMessage): string; function FindAllFilesInDir(const Dir: string; const Mask: string) : TArray<string>; implementation uses sysutils, dateutils, registry, winapi.windows; var unixTime: TDateTime; function FindAllFilesInDir(const Dir: string; const Mask: string) : TArray<string>; var SR: TSearchRec; xs: TArray<string>; x: string; begin if sysutils.FindFirst(IncludeTrailingBackslash(Dir) + Mask, faAnyFile or faDirectory, SR) <> 0 then exit; try repeat if (SR.Attr and faDirectory) = 0 then begin SetLength(result, length(result) + 1); result[length(result) - 1] := IncludeTrailingBackslash(Dir) + SR.Name; end else if (SR.Name <> '.') and (SR.Name <> '..') then begin xs := FindAllFilesInDir(IncludeTrailingBackslash(Dir) + SR.Name, Mask); for x in xs do begin SetLength(result, length(result) + 1); result[length(result) - 1] := x; end end; // recursive call! until sysutils.FindNext(SR) <> 0; finally sysutils.FindClose(SR); end; end; function getCopyDataString(Message: TMessage): string; var cd: PCOPYDATASTRUCT; begin cd := PCOPYDATASTRUCT(Message.LParam); SetString(result, PWideChar(cd.lpData), cd.cbData div 2); end; class function TJsonCD.unmarshal<T>(Message: TMessage): T; var s: string; begin s := getCopyDataString(Message); TgoBsonSerializer.deserialize(getCopyDataString(Message), result); end; procedure EnumComports(const Ports: TStrings); var nInd: integer; begin with TRegistry.create(KEY_READ) do try RootKey := HKEY_LOCAL_MACHINE; if OpenKey('hardware\devicemap\serialcomm', false) then begin Ports.BeginUpdate(); GetValueNames(Ports); for nInd := Ports.count - 1 downto 0 do Ports.Strings[nInd] := ReadString(Ports.Strings[nInd]); end; finally Ports.EndUpdate(); CloseKey(); Free(); end end; function UnixMillisToDateTime(T: UInt64): TDateTime; begin result := IncHour(IncMilliSecond(unixTime, T), 3); end; function DateTimeToUnixMillis(T: TDateTime): UInt64; begin result := MilliSecondsBetween(unixTime, IncHour(T, -3)); end; procedure ExecuteAndWait(const aCommando: string); var tmpStartupInfo: TStartupInfo; tmpProcessInformation: TProcessInformation; tmpProgram: String; begin tmpProgram := trim(aCommando); FillChar(tmpStartupInfo, SizeOf(tmpStartupInfo), 0); with tmpStartupInfo do begin cb := SizeOf(TStartupInfo); wShowWindow := SW_HIDE; end; if not CreateProcess(nil, pchar(tmpProgram), nil, nil, true, 0, nil, nil, tmpStartupInfo, tmpProcessInformation) then RaiseLastOSError; WaitForSingleObject(tmpProcessInformation.hProcess, INFINITE); CloseHandle(tmpProcessInformation.hProcess); CloseHandle(tmpProcessInformation.hThread); end; { TPrimitiveBox<T> } constructor TPrimitiveBox<T>.create(value: T); begin self.value := value; end; function TPrimitiveBox<T>.getValue: T; begin result := value; end; procedure TPrimitiveBox<T>.setValue(value: T); begin self.value := value; end; initialization unixTime := EncodeDateTime(1970, 1, 1, 0, 0, 0, 0); end.
{ *************************************************************************** Copyright (c) 2016-2020 Kike Pérez Unit : Quick.DAO.QueryGenerator.SQLite Description : DAO SQLite Query Generator Author : Kike Pérez Version : 1.0 Created : 22/06/2018 Modified : 31/03/2020 This file is part of QuickDAO: https://github.com/exilon/QuickDAO *************************************************************************** Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *************************************************************************** } unit Quick.DAO.QueryGenerator.SQLite; {$i QuickDAO.inc} interface uses Classes, SysUtils, Quick.Commons, Quick.DAO; type TSQLiteQueryGenerator = class(TDAOQueryGenerator,IDAOQueryGenerator) private fFormatSettings : TFormatSettings; public function Name : string; constructor Create; function CreateTable(const aTable : TDAOModel) : string; function ExistsTable(aModel : TDAOModel) : string; function ExistsColumn(aModel : TDAOModel; const aFieldName : string) : string; function AddColumn(aModel : TDAOModel; aField : TDAOField) : string; function SetPrimaryKey(aModel : TDAOModel) : string; function CreateIndex(aModel : TDAOModel; aIndex : TDAOIndex) : string; function Select(const aTableName, aFieldNames : string; aLimit : Integer; const aWhere : string; aOrderFields : string; aOrderAsc : Boolean) : string; function Sum(const aTableName, aFieldName, aWhere: string): string; function Count(const aTableName : string; const aWhere : string) : string; function Add(const aTableName: string; const aFieldNames, aFieldValues : string) : string; function AddOrUpdate(const aTableName: string; const aFieldNames, aFieldValues : string) : string; function Update(const aTableName, aFieldPairs, aWhere : string) : string; function Delete(const aTableName : string; const aWhere : string) : string; function DateTimeToDBField(aDateTime : TDateTime) : string; function DBFieldToDateTime(const aValue : string) : TDateTime; function QuotedStr(const aValue: string): string; override; end; implementation const {$IFNDEF FPC} DBDATATYPES : array of string = ['varchar(%d)','text','char(%d)','integer','integer','bigint','decimal(%d,%d)','bit','date','time','datetime','datetime','datetime']; {$ELSE} DBDATATYPES : array[0..10] of string = ('varchar(%d)','text','char(%d)','integer','integer','bigint','decimal(%d,%d)','bit','date','time','datetime','datetime','datetime'); {$ENDIF} { TSQLiteQueryGenerator } function TSQLiteQueryGenerator.AddColumn(aModel: TDAOModel; aField: TDAOField) : string; var datatype : string; querytext : TStringList; begin querytext := TStringList.Create; try querytext.Add(Format('ALTER TABLE [%s]',[aModel.TableName])); if aField.DataType = dtFloat then begin datatype := Format(DBDATATYPES[Integer(aField.DataType)],[aField.DataSize,aField.Precision]) end else begin if aField.DataSize > 0 then datatype := Format(DBDATATYPES[Integer(aField.DataType)],[aField.DataSize]) else datatype := DBDATATYPES[Integer(aField.DataType)]; end; querytext.Add(Format('ADD [%s] %s',[aField.Name,datatype])); Result := querytext.Text; finally querytext.Free; end; end; constructor TSQLiteQueryGenerator.Create; begin GetLocaleFormatSettings(0,fFormatSettings); fFormatSettings.ShortDateFormat := 'YYYY-MM-DD'; fFormatSettings.ShortTimeFormat := 'hh:nn:ss'; fFormatSettings.DateSeparator := '-'; fFormatSettings.TimeSeparator := ':'; end; function TSQLiteQueryGenerator.CreateIndex(aModel: TDAOModel; aIndex: TDAOIndex) : string; var fieldsToIndex : string; fieldIndex : ShortInt; begin for fieldIndex := 0 to High(aIndex.FieldNames) do begin if (fieldIndex > 0) and (fieldsToIndex <> '') then fieldsToIndex := fieldsToIndex + ', '; fieldsToIndex := fieldsToIndex + aIndex.FieldNames[fieldIndex]; end; Result := Format('CREATE INDEX IF NOT EXISTS PK_%s ON %s (%s)',[aModel.TableName + '_' + fieldsToIndex.Replace(', ', '_'),aModel.TableName,fieldsToIndex]); end; function TSQLiteQueryGenerator.CreateTable(const aTable: TDAOModel) : string; var field : TDAOField; datatype : string; querytext : TStringList; begin querytext := TStringList.Create; try querytext.Add(Format('CREATE TABLE IF NOT EXISTS [%s] (',[aTable.TableName])); for field in aTable.Fields do begin if field.DataType = dtFloat then begin datatype := Format(DBDATATYPES[Integer(field.DataType)],[field.DataSize,field.Precision]) end else begin if field.DataSize > 0 then datatype := Format(DBDATATYPES[Integer(field.DataType)],[field.DataSize]) else datatype := DBDATATYPES[Integer(field.DataType)]; end; if field.IsPrimaryKey then begin if field.DataType = dtAutoID then querytext.Add(Format('[%s] %s PRIMARY KEY AUTOINCREMENT,',[field.Name,datatype])) else querytext.Add(Format('[%s] %s PRIMARY KEY,',[field.Name,datatype])); end else begin if field.DataType = dtCreationDate then querytext.Add(Format('[%s] %s DEFAULT CURRENT_TIMESTAMP,',[field.Name,datatype])) else querytext.Add(Format('[%s] %s,',[field.Name,datatype])); end; end; querytext[querytext.Count-1] := Copy(querytext[querytext.Count-1],1,querytext[querytext.Count-1].Length-1); querytext.Add(')'); Result := querytext.Text; finally querytext.Free; end; end; function TSQLiteQueryGenerator.ExistsColumn(aModel : TDAOModel; const aFieldName : string) : string; begin Result := Format('PRAGMA table_info(%s)',[aModel.TableName]); end; function TSQLiteQueryGenerator.ExistsTable(aModel: TDAOModel): string; begin Result := Format('SELECT name FROM sqlite_master WHERE type = ''table'' AND name = ''%s''',[aModel.TableName]); end; function TSQLiteQueryGenerator.Name: string; begin Result := 'SQLITE'; end; function TSQLiteQueryGenerator.QuotedStr(const aValue: string): string; begin Result := '"' + aValue + '"'; end; function TSQLiteQueryGenerator.SetPrimaryKey(aModel: TDAOModel) : string; begin Result := ''; Exit; end; function TSQLiteQueryGenerator.Sum(const aTableName, aFieldName, aWhere: string): string; var querytext : TStringList; begin querytext := TStringList.Create; try querytext.Add(Format('SELECT SUM (%s) FROM [%s] WHERE %s',[aTableName,aFieldName,aWhere])); Result := querytext.Text; finally querytext.Free; end; end; function TSQLiteQueryGenerator.Select(const aTableName, aFieldNames : string; aLimit: Integer; const aWhere: string; aOrderFields: string; aOrderAsc: Boolean) : string; var orderdir : string; querytext : TStringList; begin querytext := TStringList.Create; try //define select-where clauses if aFieldNames.IsEmpty then querytext.Add(Format('SELECT * FROM [%s] WHERE %s',[aTableName,aWhere])) else querytext.Add(Format('SELECT %s FROM [%s] WHERE %s',[aFieldNames,aTableName,aWhere])); //define orderby clause if not aOrderFields.IsEmpty then begin if aOrderAsc then orderdir := 'ASC' else orderdir := 'DESC'; querytext.Add(Format('ORDER BY %s %s',[aOrderFields,orderdir])); end; //define limited query clause if aLimit > 0 then querytext.Add('LIMIT ' + aLimit.ToString); Result := querytext.Text; finally querytext.Free; end; end; function TSQLiteQueryGenerator.Add(const aTableName: string; const aFieldNames, aFieldValues : string) : string; var querytext : TStringList; begin querytext := TStringList.Create; try querytext.Add(Format('INSERT INTO [%s]',[aTableName])); querytext.Add(Format('(%s)',[aFieldNames])); querytext.Add(Format('VALUES(%s)',[aFieldValues])); Result := querytext.Text; finally querytext.Free; end; end; function TSQLiteQueryGenerator.AddOrUpdate(const aTableName: string; const aFieldNames, aFieldValues : string) : string; var querytext : TStringList; begin querytext := TStringList.Create; try querytext.Add(Format('INSERT OR REPLACE INTO [%s]',[aTableName])); querytext.Add(Format('(%s)',[aFieldNames])); querytext.Add(Format('VALUES(%s)',[aFieldValues])); Result := querytext.Text; finally querytext.Free; end; end; function TSQLiteQueryGenerator.Update(const aTableName, aFieldPairs, aWhere : string) : string; var querytext : TStringList; begin querytext := TStringList.Create; try querytext.Add(Format('UPDATE [%s]',[aTableName])); querytext.Add(Format('SET %s',[aFieldPairs])); querytext.Add(Format('WHERE %s',[aWhere])); Result := querytext.Text; finally querytext.Free; end; end; function TSQLiteQueryGenerator.Count(const aTableName : string; const aWhere : string) : string; begin Result := Format('SELECT COUNT(*) AS cnt FROM [%s] WHERE %s',[aTableName,aWhere]); end; function TSQLiteQueryGenerator.DateTimeToDBField(aDateTime: TDateTime): string; begin Result := FormatDateTime('YYYY-MM-DD hh:nn:ss',aDateTime); end; function TSQLiteQueryGenerator.DBFieldToDateTime(const aValue: string): TDateTime; begin Result := StrToDateTime(aValue,fFormatSettings); end; function TSQLiteQueryGenerator.Delete(const aTableName, aWhere: string) : string; begin Result := Format('SELECT COUNT(*) AS cnt FROM [%s] WHERE %s',[aTableName,aWhere]); end; end.
unit sNIF.worker; { ******************************************************* sNIF Utilidad para buscar ficheros ofimáticos con cadenas de caracteres coincidentes con NIF/NIE. ******************************************************* 2012-2018 Ángel Fernández Pineda. Madrid. Spain. This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License. To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/ or send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA. ******************************************************* } interface uses System.Classes, sNIF.control, System.SysUtils, sNIF.params; type TsNIFWorker = class(TThread) { PROPOSITO: Clase base para los hilos que realizan el trabajo de exploración. } protected FControl: TsNIFControl; FParametros: TsNIFParametros; public constructor Create(const AControl: TsNIFControl; const Parametros: TsNIFParametros); end; implementation //uses // System.SysUtils; constructor TsNIFWorker.Create(const AControl: TsNIFControl; const Parametros: TsNIFParametros); begin inherited Create(true); // crear suspendido FControl := AControl; FParametros := Parametros; FreeOnTerminate := false; end; end.
unit scaleimageintensity; interface {$D-,O+,Q-,R-,S-} {$IFDEF FPC} {$mode delphi} {$ENDIF} uses define_types,nifti_hdr;//, nii_reslice, clustering; procedure RescaleImgIntensity(var lHdr: TMRIcroHdr ); procedure AbsImgIntensity32(var lHdr: TMRIcroHdr ); procedure HideZeros(var lHdr: TMRIcroHdr ); function Scaled2RawIntensity (lHdr: TMRIcroHdr; lScaled: single): single; implementation uses sysutils; function Scaled2RawIntensity (lHdr: TMRIcroHdr; lScaled: single): single; begin if lHdr.NIFTIhdr.scl_slope = 0 then result := (lScaled)-lHdr.NIFTIhdr.scl_inter else result := (lScaled-lHdr.NIFTIhdr.scl_inter) / lHdr.NIFTIhdr.scl_slope; end; procedure ReturnMinMax (var lHdr: TMRIcroHdr; var lMin,lMax: single; var lFiltMin8bit, lFiltMax8bit: integer); var lSwap,lMinS,lMaxS : single; begin lFiltMin8bit := 0; lFiltMax8bit := 255; lMinS := lHdr.WindowScaledMin; lMaxS := lHdr.WindowScaledMax; if lMinS > lMaxS then begin //swap lSwap := lMinS; lMinS := lMaxS; lMaxS := lSwap; end;//swap lMin := (Scaled2RawIntensity(lHdr, lMinS)); lMax := (Scaled2RawIntensity(lHdr, lMaxS)); //if lMin = lMax then exit; if (lHdr.LutFromZero) then begin if (lMinS > 0) and (lMaxS <> 0) then begin //lMin := Scaled2RawIntensity(lHdr, 0); lFiltMin8bit := round(lMinS/lMaxS*255); //lMinS := - lHalfBit;//0; lHdr.Zero8Bit := 0; end else if (lMaxS < 0) and (lMinS <> 0) then begin //lMax := Scaled2RawIntensity(lHdr, -0.000001); lFiltMax8bit := 255-round(lMaxS/lMinS*255); //lMaxS := lHalfBit; //0; //lFiltMax8bit := (Scaled2RawIntensity(lHdr, lHdr.WindowScaledMax)); end; //> 0 end; //LUTfrom Zero lHdr.Zero8Bit := lMinS; lHdr.Slope8bit := (lMaxS-lMinS)/255; end; //ReturnMinMax procedure ReturnMinMaxInt (var lHdr: TMRIcroHdr; var lMin,lMax, lFiltMin8bit, lFiltMax8bit: integer); var lMinS,lMaxS: single; begin ReturnMinMax (lHdr, lMinS,lMaxS,lFiltMin8bit, lFiltMax8bit); lMin := round(lMinS); lMax := round(lMaxS); end; procedure HideZeros8(var lHdr: TMRIcroHdr ); var lInc: integer; begin if (lHdr.ImgBufferBPP <> 1) or (lHdr.ImgBufferItems < 1) then exit; for lInc := 1 to lHdr.ScrnBufferItems do if lHdr.ImgBuffer^[lInc] = 0 then lHdr.ScrnBuffer^[lInc] := 0; end; procedure HideZeros16(var lHdr: TMRIcroHdr ); var lInc: integer; l16Buf: SmallIntP; begin if (lHdr.ImgBufferBPP <> 2) or (lHdr.ImgBufferItems < 1) then exit; l16Buf := SmallIntP(lHdr.ImgBuffer ); for lInc := 1 to lHdr.ScrnBufferItems do if l16Buf^[lInc] = 0 then lHdr.ScrnBuffer^[lInc] := 0; end; procedure HideZeros32(var lHdr: TMRIcroHdr ); var lInc: integer; l32Buf : SingleP; begin if (lHdr.ImgBufferBPP <> 4) or (lHdr.ImgBufferItems < 1) then exit; l32Buf := SingleP(lHdr.ImgBuffer ); for lInc := 1 to lHdr.ScrnBufferItems do if l32Buf^[lInc] = 0 then lHdr.ScrnBuffer^[lInc] := 0; end; procedure HideZeros(var lHdr: TMRIcroHdr ); begin if (lHdr.ImgBufferBPP = 4) then HideZeros32(lHdr) else if (lHdr.ImgBufferBPP = 2) then HideZeros16(LHdr) else if lHdr.ImgBufferBPP = 1 then HideZeros8(lHdr); end; procedure RescaleImgIntensity8(var lHdr: TMRIcroHdr ); var lRng: single; lLUTra: array[0..255] of byte; lMax,lMin,lSwap,lMod: single; lFiltMin8bit,lFiltMax8bit,lInc: integer; begin if (lHdr.ImgBufferBPP <> 1) or (lHdr.ImgBufferItems < 2) then exit; ReturnMinMax (lHdr, lMin,lMax,lFiltMin8bit,lFiltMax8bit); //ImgForm.Caption := floattostr(lMin); //fx(lMin,lMax,lFiltMin8bit,lFiltMax8bit); lRng := (lMax - lMin); if lRng <> 0 then lMod := abs({trunc}(((254)/lRng))) else lMod := 0; if lMin > lMax then begin //maw lSwap := lMin; lMin := lMax; lMax := lSwap; end; for lInc := 0 to 255 do begin if lInc < lMin then lLUTra[lInc] := 0 else if lInc >= lMax then lLUTra[lInc] := 255 else lLUTra[lInc] := trunc(((lInc-lMin)*lMod)+1); end; //fill LUT if lRng < 0 then //inverted scale... e.g. negative scale factor for lInc := 0 to 255 do lLUTra[lInc] := 255-lLUTra[lInc]; for lInc := 1 to lHdr.ScrnBufferItems do lHdr.ScrnBuffer^[lInc] := lLUTra[lHdr.ImgBuffer^[lInc]]; end;//proc RescaleImgIntensity8 procedure RescaleImgIntensity16(var lHdr: TMRIcroHdr ); var lRng: single; lBuff: bytep0; l16Buf : SmallIntP; lFiltMin8bit,lFiltMax8bit,lRngi,lMax,lMin, lMin16Val,//lMax16Val, lSwap,lModShl10,lInc,lInt: integer; begin if (lHdr.ImgBufferBPP <> 2) or (lHdr.ImgBufferItems < 2) then exit; ReturnMinMaxInt (lHdr, lMin,lMax,lFiltMin8bit,lFiltMax8bit); lRng := lMax - lMin; if lRng <> 0 then lModShl10 := abs( trunc(((254)/lRng)* 1024)) else lModShl10 := 0; if lMin > lMax then begin lSwap := lMin; lMin := lMax; lMax := lSwap; end; //find min/max //we can find min max dynamically... useful if software changes values, but slow... (*l16Buf := SmallIntP(lHdr.ImgBuffer ); lMin16Val := l16Buf^[1]; lMax16Val := l16Buf^[1]; for lInc := 1 to lHdr.ImgBufferItems do begin if l16Buf^[lInc] > lMax16Val then lMax16Val := l16Buf^[lInc]; if l16Buf^[lInc] < lMin16Val then lMin16Val := l16Buf^[lInc]; end; lRngi := 1+ lMax16Val-lMin16Val; *) //alternatively, we can use static values for Min Max, computed when image is loaded... lMin16Val := trunc(lHdr.GlMinUnscaledS); lRngi := (1+ trunc(lHdr.GlMaxUnscaledS))-lMin16Val; //next make buffer getmem(lBuff, lRngi+1); //+1 if the only values are 0,1,2 the range is 2, but there are 3 values! for lInc := 0 to (lRngi) do begin //build lookup table lInt := lInc+lMin16Val; if lInt >= lMax then lBuff^[lInc] := (255) else if lInt < lMin then lBuff^[lInc] := 0 else lBuff^[lInc] := (((lInt-lMin)*lModShl10) shr 10)+1 ; //lBuff[lInc] := (((lInt-lMin)*lModShl10) shr 10) ; end; //build lookup table if lRng < 0 then //inverted scale... e.g. negative scale factor for lInc := 0 to lRngi do lBuff^[lInc] := 255-lBuff^[lInc]; l16Buf := SmallIntP(lHdr.ImgBuffer ); for lInc := 1 to lHdr.ImgBufferItems do lHdr.ScrnBuffer^[lInc] := lBuff^[l16Buf^[lInc]-lMin16Val] ; freemem(lBuff); //release lookup table end;//proc RescaleImgIntensity16; procedure RescaleImgIntensity32(var lHdr: TMRIcroHdr ); var lRng: double; lMod,lMax,lMin,lSwap: single {was extended}; lInc,lItems,lFiltMin8bit,lFiltMax8bit: integer; l32Buf : SingleP; begin lItems := lHdr.ImgBufferItems ; if (lHdr.ImgBufferBPP <> 4) or (lItems< 2) then exit; l32Buf := SingleP(lHdr.ImgBuffer ); ReturnMinMax (lHdr, lMin,lMax,lFiltMin8bit,lFiltMax8bit); //qaz if lMin > lMax then begin lSwap := lMin; lMin := lMax; lMax := lSwap; end; lRng := (lMax - lMin); if lRng <> 0 then lMod := abs(254/lRng) else begin //June 2007 for lInc := 1 to lItems do begin if l32Buf^[lInc] >= lMax then lHdr.ScrnBuffer^[lInc] := 255 else //if l32Buf[lInc] < lMin then lHdr.ScrnBuffer^[lInc] := 0; end; exit; end; lMin := lMin - abs(lRng/255);//lMod; for lInc := 1 to lItems do begin if l32Buf^[lInc] > lMax then lHdr.ScrnBuffer^[lInc] := 255 else if l32Buf^[lInc] < lMin then lHdr.ScrnBuffer^[lInc] := 0 //alfa else begin lHdr.ScrnBuffer^[lInc] := round ((l32Buf^[lInc]-lMin)*lMod); end; //lHdr.ScrnBuffer^[lInc] := random(255); end; //for each voxel //next: prevent rounding errors for images where LUT is from zero //next - flip intensity range OPTIONAL //if lRng < 0 then //inverted scale... e.g. negative scale factor //if (lMin < 0) and (lMax < 0) then //inverted scale... e.g. negative scale factor // for lInc := 1 to lItems do // lHdr.ScrnBuffer^[lInc] := 255-lHdr.ScrnBuffer^[lInc]; end; //RescaleImgIntensity32 procedure InvertScrnBuffer(var lHdr: TMRIcroHdr); var lItems,lInc: integer; begin lItems := lHdr.ImgBufferItems ; for lInc := 1 to lItems do lHdr.ScrnBuffer^[lInc] := 255-lHdr.ScrnBuffer^[lInc]; end; (*procedure ClusterScrnImgA (var lHdr: TMRIcroHdr); const kUnused = -1; var clusterVol,clusterStart: array of longint; pos, j: integer; X,Y,XY,Z,XZ,YZ, group, ngroups: integer; function MaxNeighbor: integer; begin result := clusterVol[pos]; if (clusterVol[pos+X] > result) then result := clusterVol[pos+X]; if (clusterVol[pos+Y] > result) then result := clusterVol[pos+Y]; if (clusterVol[pos+XY] > result) then result := clusterVol[pos+XY]; if (clusterVol[pos+Z] > result) then result := clusterVol[pos+Z]; if (clusterVol[pos+XZ] > result) then result := clusterVol[pos+XZ]; if (clusterVol[pos+YZ] > result) then result := clusterVol[pos+YZ]; end; //nested MaxNeighbor procedure SetNeighbor (p: integer); //set voxel to current group var k,oldgroup: integer; begin if (clusterVol[p] <> 0) and (clusterVol[p] <> group) then begin if clusterVol[p] > 0 then begin //retire group: consolidate two connected regions oldgroup := clusterVol[p]; for k := clusterStart[oldgroup] to p do begin //if clusterVol[k] = oldgroup then // clusterVol[k] := group; end; end; //retire group clusterVol[p] := group; end; end; //nested SetNeighbor begin if (lHdr.ClusterSize <= 1) then exit; if (lHdr.ImgBufferItems <> (lHdr.NIFTIhdr.dim[1]*lHdr.NIFTIhdr.dim[2]*lHdr.NIFTIhdr.dim[3]) ) then exit; if (lHdr.ImgBufferItems < 3) then exit; //each pixel has 18 neighbars that share an edge X := 1; Y := lHdr.NIFTIhdr.dim[1]; XY := X+Y; //future neighbors on same slice, next column (NC), next row (NR) and NC+NR Z := lHdr.NIFTIhdr.dim[1]*lHdr.NIFTIhdr.dim[2]; XZ := X+Z; YZ := Y+Z; //neighbors on next slice: NS (next slice), NS+NC, NS+NR Setlength (clusterVol,lHdr.ImgBufferItems+1+YZ); //+1 since we will index from 1 not 0! Setlength (clusterStart,lHdr.ImgBufferItems); for pos := 0 to High(clusterVol) do clusterVol[pos] := 0; //initialize array for pos := 1 to lHdr.ImgBufferItems do begin if lHdr.ScrnBuffer^[pos] > 0 then clusterVol[pos] := kUnused end; ngroups := 0; j := 0; for pos := 1 to (lHdr.ImgBufferItems) do begin if clusterVol[pos] <> 0 then begin //this voxel survives threshold j := j+1; group := MaxNeighbor; if group < 1 then begin //new cluster group ngroups := ngroups + 1; clusterStart[group] := pos; group := ngroups; end; SetNeighbor(pos+YZ); SetNeighbor(pos+XZ); SetNeighbor(pos+Z); SetNeighbor(pos+XY); SetNeighbor(pos+Y); SetNeighbor(pos+X); SetNeighbor(pos); end; //voxel suvives threshold end; //for each voxel clusterVol := nil; clusterStart := nil; end; *) procedure FilterScrnImg (var lHdr: TMRIcroHdr); var lInc,lItems,lFiltMin8bit,lFiltMax8bit: integer; lMinS,lMaxS,lScale: single; begin ReturnMinMax(lHdr,lMinS,lMaxS,lFiltMin8bit,lFiltMax8bit); lItems :=lHdr.ScrnBufferItems; if lItems < 1 then exit; if lFiltMax8Bit < 255 then begin lFiltMin8bit := 255-lFiltMax8bit; lFiltMax8Bit := 255; end; lScale := (lFiltMax8bit-lFiltMin8bit)/255; if (lFiltMin8bit > 0) or (lFiltMax8bit < 255) then for lInc := 1 to lItems do if lHdr.ScrnBuffer^[lInc] <> 0 then lHdr.ScrnBuffer^[lInc] := lFiltMin8bit+round(lHdr.ScrnBuffer^[lInc]*lScale); end; //FilterScrnImg procedure AbsImgIntensity32(var lHdr: TMRIcroHdr ); var l32Buf : SingleP; lInc,lImgSamples: integer; begin if (lHdr.ImgBufferItems < 1) and (lHdr.ScrnBufferItems < 1) then exit; //1/2008 lImgSamples := round(ComputeImageDataBytes8bpp(lHdr)); if lHdr.ImgBufferItems<>lHdr.ScrnBufferItems then exit; if (lHdr.ImgBufferBPP <> 4) then exit; l32Buf := SingleP(lHdr.ImgBuffer ); for lInc := 1 to lImgSamples do l32Buf^[lInc] := abs(l32Buf^[lInc]); end; //AbsImgIntensity32 procedure RescaleImgIntensity(var lHdr: TMRIcroHdr ); var lImgSamples: integer; begin if (lHdr.ImgBufferItems < 1) and (lHdr.ScrnBufferItems < 1) then exit; //1/2008 lImgSamples := round(ComputeImageDataBytes8bpp(lHdr)); if lHdr.ImgBufferItems<>lHdr.ScrnBufferItems then begin if lHdr.ScrnBufferItems > 0 then freemem(lHdr.ScrnBuffer); lHdr.ScrnBufferItems := lHdr.ImgBufferItems; GetMem(lHdr.ScrnBuffer ,lHdr.ScrnBufferItems); end; if lHdr.UsesCustomPalette then begin lHdr.WindowScaledMin := 0; lHdr.WindowScaledMax := 255; end; if lImgSamples < 1 then exit; if (lHdr.ImgBufferBPP = 4) then RescaleImgIntensity32(lHdr) else if (lHdr.ImgBufferBPP = 2) then RescaleImgIntensity16(LHdr) else if lHdr.ImgBufferBPP = 1 then RescaleImgIntensity8(lHdr) else if lHdr.ImgBufferBPP = 3 then exit else begin msg(lHdr.HdrFileName +' :: Unknown Image Buffer Bytes Per Pixel '); exit; end; if ((lHdr.WindowScaledMin <= 0) and (lHdr.WindowScaledMax <= 0)) then //maw InvertScrnBuffer(lHdr); if lHdr.LUTfromZero then FilterScrnImg(lHdr); end; //RescaleImgIntensity end.
{----------------------------------------------------------------------------- Unit Name: cPyBaseDebugger Author: Kiriakos Vlahos Date: 23-Apr-2006 Purpose: History: Base debugger classes -----------------------------------------------------------------------------} unit cPyBaseDebugger; interface uses Windows, SysUtils, Classes, uEditAppIntfs, Forms, Contnrs, cTools, cPythonSourceScanner, PythonEngine; type TPythonEngineType = (peInternal, peRemote, peRemoteTk, peRemoteWx); TDebuggerState = (dsInactive, dsRunning, dsPaused, dsRunningNoDebug, dsPostMortem); TDebuggerCommand = (dcNone, dcRun, dcStepInto, dcStepOver, dcStepOut, dcRunToCursor, dcPause, dcAbort); TDebuggerLineInfo = (dlCurrentLine, dlBreakpointLine, dlDisabledBreakpointLine, dlExecutableLine, dlErrorLine); TDebuggerLineInfos = set of TDebuggerLineInfo; TInterpreterCapability = (icReInitialize); TInterpreterCapabilities = set of TInterpreterCapability; TNamespaceItemAttribute = (nsaNew, nsaChanged); TNamespaceItemAttributes = set of TNamespaceItemAttribute; TBreakpointChangeEvent = procedure(Sender: TObject; Editor : IEditor; ALine: integer) of object; TDebuggerStateChangeEvent = procedure(Sender: TObject; OldState, NewState: TDebuggerState) of object; TDebuggerYieldEvent = procedure(Sender: TObject; DoIdle : Boolean) of object; TRunConfiguration = class(TPersistent) private fScriptName: string; fEngineType: TPythonEngineType; fWorkingDir: string; fParameters: string; fReinitializeBeforeRun: Boolean; fOutputFileName: string; fWriteOutputToFile: Boolean; fAppendToFile: Boolean; fExternalRun: TExternalRun; fDescription: string; procedure SetExternalRun(const Value: TExternalRun); public constructor Create; destructor Destroy; override; procedure Assign(Source: TPersistent); override; published property ScriptName : string read fScriptName write fScriptName; property Description : string read fDescription write fDescription; property EngineType : TPythonEngineType read fEngineType write fEngineType; property ReinitializeBeforeRun : Boolean read fReinitializeBeforeRun write fReinitializeBeforeRun; property Parameters : string read fParameters write fParameters; property WorkingDir : string read fWorkingDir write fWorkingDir; property WriteOutputToFile : Boolean read fWriteOutputToFile write fWriteOutputToFile; property OutputFileName : string read fOutputFileName write fOutputFileName; property AppendToFile : Boolean read fAppendToFile write fAppendToFile; property ExternalRun : TExternalRun read fExternalRun write SetExternalRun; end; TEditorPos = class(TPersistent) public Editor : IEditor; Line : integer; Char : integer; IsSyntax : Boolean; ErrorMsg : string; procedure Clear; procedure Assign(Source: TPersistent); override; end; TBaseFrameInfo = class(TObject) // Base (abstract) class for Call Stack frame information protected function GetFunctionName : string; virtual; abstract; function GetFileName : string; virtual; abstract; function GetLine : integer; virtual; abstract; public property FunctionName : string read GetFunctionName; property FileName : string read GetFileName; property Line : integer read GetLine; end; TBaseNameSpaceItem = class(TObject) // Base (abstract) class for Namespace item information protected fPyObject : Variant; fExpandCommonTypes : Boolean; fExpandSequences : Boolean; GotChildNodes : Boolean; GotBufferedValue : Boolean; BufferedValue : string; function GetOrCalculateValue : string; function GetName : string; virtual; abstract; function GetObjectType : string; virtual; abstract; function GetValue : string; virtual; abstract; function GetDocString : string; virtual; abstract; function GetChildCount : integer; virtual; abstract; function GetChildNode(Index: integer): TBaseNameSpaceItem; virtual; abstract; public Attributes : TNamespaceItemAttributes; function IsClass : Boolean; virtual; abstract; function IsDict : Boolean; virtual; abstract; function IsModule : Boolean; virtual; abstract; function IsFunction : Boolean; virtual; abstract; function IsMethod : Boolean; virtual; abstract; function Has__dict__ : Boolean; virtual; abstract; function IndexOfChild(AName : string): integer; virtual; abstract; procedure GetChildNodes; virtual; abstract; procedure CompareToOldItem(OldItem : TBaseNameSpaceItem); virtual; property Name : string read GetName; property ObjectType : string read GetObjectType; property Value : string read GetOrCalculateValue; property DocString : string read GetDocString; property ChildCount : integer read GetChildCount; property ChildNode[Index : integer] : TBaseNameSpaceItem read GetChildNode; property PyObject : Variant read fPyObject; property ExpandCommonTypes : Boolean read fExpandCommonTypes write fExpandCommonTypes; property ExpandSequences : Boolean read fExpandSequences write fExpandSequences; end; TModuleProxy = class; TPyBaseInterpreter = class(TObject) // Base (abstract) class for implementing Python Interpreters private function GetMainModule: TModuleProxy; protected fInterpreterCapabilities : TInterpreterCapabilities; fEngineType : TPythonEngineType; fMainModule : TModuleProxy; procedure CreateMainModule; virtual; abstract; public destructor Destroy; override; procedure Initialize; virtual; // Python Path function SysPathAdd(const Path : string) : boolean; virtual; abstract; function SysPathRemove(const Path : string) : boolean; virtual; abstract; function AddPathToPythonPath(const Path : string; AutoRemove : Boolean = True) : IInterface; procedure SysPathToStrings(Strings : TStrings); virtual; abstract; procedure StringsToSysPath(Strings : TStrings); virtual; abstract; // NameSpace function GetGlobals : TBaseNameSpaceItem; virtual; abstract; procedure GetModulesOnPath(Path : Variant; SL : TStrings); virtual; abstract; function NameSpaceFromExpression(const Expr : string) : TBaseNameSpaceItem; virtual; abstract; function CallTipFromExpression(const Expr : string; var DisplayString, DocString : string) : Boolean; virtual; abstract; // Service routines procedure HandlePyException(E : EPythonError; SkipFrames : integer = 1); virtual; procedure SetCommandLine(ARunConfig : TRunConfiguration); virtual; abstract; procedure RestoreCommandLine; virtual; abstract; procedure ReInitialize; virtual; // Main interface function ImportModule(Editor : IEditor; AddToNameSpace : Boolean = False) : Variant; virtual; abstract; procedure RunNoDebug(ARunConfig : TRunConfiguration); virtual; abstract; function RunSource(Const Source, FileName : Variant; symbol : string = 'single') : boolean; virtual; abstract; procedure RunScript(FileName : string); virtual; function EvalCode(const Expr : string) : Variant; virtual; abstract; function GetObjectType(Ob : Variant) : string; virtual; abstract; function UnitTestResult : Variant; virtual; abstract; function NameSpaceItemFromPyObject(aName : string; aPyObject : Variant): TBaseNameSpaceItem; virtual; abstract; property EngineType : TPythonEngineType read fEngineType; property InterpreterCapabilities : TInterpreterCapabilities read fInterpreterCapabilities; property MainModule : TModuleProxy read GetMainModule; end; TPyBaseDebugger = class(TObject) { Base (abstract) class for implementing Python Debuggers } protected procedure SetCommandLine(ARunConfig : TRunConfiguration); virtual; abstract; procedure RestoreCommandLine; virtual; abstract; procedure SetDebuggerBreakpoints; virtual; abstract; public // Python Path function SysPathAdd(const Path : string) : boolean; virtual; abstract; function SysPathRemove(const Path : string) : boolean; virtual; abstract; function AddPathToPythonPath(const Path : string; AutoRemove : Boolean = True) : IInterface; // Debugging procedure Run(ARunConfig : TRunConfiguration; InitStepIn : Boolean = False; RunToCursorLine : integer = -1); virtual; abstract; procedure RunToCursor(Editor : IEditor; ALine: integer); virtual; abstract; procedure StepInto; virtual; abstract; procedure StepOver; virtual; abstract; procedure StepOut; virtual; abstract; procedure Resume; virtual; abstract; procedure Pause; virtual; abstract; procedure Abort; virtual; abstract; // Evaluate expression in the current frame procedure Evaluate(const Expr : string; out ObjType, Value : string); overload; virtual; abstract; function Evaluate(const Expr : string) : TBaseNamespaceItem; overload; virtual; abstract; // Like the InteractiveInterpreter runsource but for the debugger frame function RunSource(Const Source, FileName : Variant; symbol : string = 'single') : boolean; virtual; abstract; // Fills in CallStackList with TBaseFrameInfo objects procedure GetCallStack(CallStackList : TObjectList); virtual; abstract; // functions to get TBaseNamespaceItems corresponding to a frame's gloabals and locals function GetFrameGlobals(Frame : TBaseFrameInfo) : TBaseNameSpaceItem; virtual; abstract; function GetFrameLocals(Frame : TBaseFrameInfo) : TBaseNameSpaceItem; virtual; abstract; function NameSpaceFromExpression(const Expr : string) : TBaseNameSpaceItem; virtual; abstract; procedure MakeFrameActive(Frame : TBaseFrameInfo); virtual; abstract; // post mortem stuff function HaveTraceback : boolean; virtual; abstract; procedure EnterPostMortem; virtual; abstract; procedure ExitPostMortem; virtual; abstract; end; TPythonControl = class(Tobject) { Interface between PyScripter and the Interpreter/Debugger. Holds information Breakpoints, ErrorPos, CurrentPos } private fBreakPointsChanged : Boolean; fDebuggerState: TDebuggerState; fErrorPos : TEditorPos; fCurrentPos : TEditorPos; fOnBreakpointChange: TBreakpointChangeEvent; fOnCurrentPosChange: TNotifyEvent; fOnErrorPosChange: TNotifyEvent; fOnStateChange: TDebuggerStateChangeEvent; fOnYield: TDebuggerYieldEvent; fActiveInterpreter : TPyBaseInterpreter; fActiveDebugger : TPyBaseDebugger ; fRunConfig : TRunConfiguration; FPythonVersionIndex: integer; procedure DoOnBreakpointChanged(Editor : IEditor; ALine: integer); procedure SetActiveDebugger(const Value: TPyBaseDebugger); procedure SetActiveInterpreter(const Value: TPyBaseInterpreter); function GetPythonEngineType: TPythonEngineType; procedure SetPythonEngineType(const Value: TPythonEngineType); procedure SetRunConfig(ARunConfig: TRunConfiguration); procedure PrepareRun; public // ActiveInterpreter and ActiveDebugger are created // and destroyed in frmPythonII constructor Create; destructor Destroy; override; // Breakpoint related procedure ToggleBreakpoint(Editor : IEditor; ALine: integer; CtrlPressed : Boolean = False); procedure SetBreakPoint(FileName : string; ALine : integer; Disabled : Boolean; Condition : string); procedure ClearAllBreakpoints; // Editor related function GetLineInfos(Editor : IEditor; ALine: integer): TDebuggerLineInfos; function IsBreakpointLine(Editor: IEditor; ALine: integer; var Disabled : boolean): boolean; function IsExecutableLine(Editor: IEditor; ALine: integer): boolean; // Event processing procedure DoCurrentPosChanged; procedure DoErrorPosChanged; procedure DoStateChange(NewState : TDebuggerState); procedure DoYield(DoIdle : Boolean); // Other function IsRunning: boolean; // Running Python Scripts procedure Run(ARunConfig : TRunConfiguration); procedure Debug(ARunConfig : TRunConfiguration; InitStepIn : Boolean = False; RunToCursorLine : integer = -1); procedure ExternalRun(ARunConfig : TRunConfiguration); // properties and events // PythonVersionIndex is the Index of Python version in the PYTHON_KNOWN_VERSIONS array property PythonVersionIndex : integer read FPythonVersionIndex write FPythonVersionIndex; property PythonEngineType : TPythonEngineType read GetPythonEngineType write SetPythonEngineType; property ActiveInterpreter : TPyBaseInterpreter read fActiveInterpreter write SetActiveInterpreter; property ActiveDebugger : TPyBaseDebugger read fActiveDebugger write SetActiveDebugger; property BreakPointsChanged : Boolean read fBreakPointsChanged write fBreakPointsChanged; property DebuggerState : TDebuggerState read fDebuggerState; property ErrorPos: TEditorPos read fErrorPos; property CurrentPos: TEditorPos read fCurrentPos; property RunConfig : TRunConfiguration read fRunConfig; property OnBreakpointChange: TBreakpointChangeEvent read fOnBreakpointChange write fOnBreakpointChange; property OnCurrentPosChange: TNotifyEvent read fOnCurrentPosChange write fOnCurrentPosChange; property OnErrorPosChange: TNotifyEvent read fOnErrorPosChange write fOnErrorPosChange; property OnStateChange: TDebuggerStateChangeEvent read fOnStateChange write fOnStateChange; property OnYield: TDebuggerYieldEvent read fOnYield write fOnYield; end; TModuleProxy = class(TParsedModule) private fPyModule : Variant; fIsExpanded : boolean; fPyInterpreter: TPyBaseInterpreter; protected function GetAllExportsVar: string; override; function GetDocString: string; override; function GetCodeHint : string; override; public constructor CreateFromModule(AModule : Variant; aPyInterpreter : TPyBaseInterpreter); procedure Expand; procedure GetNameSpace(SList : TStringList); override; property PyModule : Variant read fPyModule; property IsExpanded : boolean read fIsExpanded; property Interpreter: TPyBaseInterpreter read fPyInterpreter; end; TClassProxy = class(TParsedClass) private fPyClass : Variant; fIsExpanded : boolean; protected function GetDocString: string; override; public constructor CreateFromClass(AName : string; AClass : Variant); function GetConstructor : TParsedFunction; override; procedure Expand; procedure GetNameSpace(SList : TStringList); override; property PyClass : Variant read fPyClass; property IsExpanded : boolean read fIsExpanded; end; TFunctionProxy = class(TParsedFunction) private fPyFunction : Variant; fIsExpanded : boolean; protected function GetDocString: string; override; public constructor CreateFromFunction(AName : string; AFunction : Variant); procedure Expand; function ArgumentsString : string; override; procedure GetNameSpace(SList : TStringList); override; property PyFunction : Variant read fPyFunction; property IsExpanded : boolean read fIsExpanded; end; TVariableProxy = class(TCodeElement) private fPyObject : Variant; fIsExpanded : boolean; protected function GetDocString: string; override; function GetCodeHint : string; override; public constructor CreateFromPyObject(const AName : string; AnObject : Variant); procedure Expand; procedure GetNameSpace(SList : TStringList); override; property PyObject : Variant read fPyObject; property IsExpanded : boolean read fIsExpanded; end; Const CommonTypes: array[1..29] of TIdentMapEntry = ( (Value: 0; Name: 'NoneType'), (Value: 1; Name: 'NotImplementedType'), (Value: 2; Name: 'bool'), (Value: 3; Name: 'buffer'), (Value: 4; Name: 'builtin_function_or_method'), (Value: 5; Name: 'code' ), (Value: 6; Name: 'complex'), (Value: 7; Name: 'dict'), (Value: 8; Name: 'dictproxy'), (Value: 9; Name: 'ellipsis'), (Value: 10; Name: 'file'), (Value: 11; Name: 'float'), (Value: 12; Name: 'frame'), (Value: 13; Name: 'function'), (Value: 14; Name: 'generator'), (Value: 15; Name: 'getset_descriptor'), (Value: 16; Name: 'instancemethod'), (Value: 17; Name: 'int'), (Value: 18; Name: 'list'), (Value: 19; Name: 'long'), (Value: 20; Name: 'member_descriptor'), (Value: 21; Name: 'method-wrapper'), (Value: 22; Name: 'object'), (Value: 23; Name: 'slice'), (Value: 24; Name: 'str'), (Value: 25; Name: 'traceback'), (Value: 26; Name: 'tuple'), (Value: 27; Name: 'unicode'), (Value: 28; Name: 'xrange') ); var PyControl : TPythonControl = nil; const EngineInitFile = 'python_init.py'; PyScripterInitFile = 'pyscripter_init.py'; implementation uses System.UITypes, Dialogs, dmCommands, frmPythonII, frmMessages, frmPyIDEMain, uCommonFunctions, VarPyth, cParameters, StringResources, cPyDebugger, frmCommandOutput, JvGnuGettext, cPyScripterSettings; { TEditorPos } procedure TEditorPos.Assign(Source: TPersistent); begin if Source is TEditorPos then begin Self.Editor := TEditorPos(Source).Editor; Self.Line := TEditorPos(Source).Line; Self.Char := TEditorPos(Source).Char; Self.IsSyntax := TEditorPos(Source).IsSyntax; Self.ErrorMsg := TEditorPos(Source).ErrorMsg; end else inherited; end; procedure TEditorPos.Clear; begin Editor := nil; Line := -1; Char := -1; IsSyntax := False; ErrorMsg := ''; end; { TPythonPathAdder } type TSysPathFunction = function(const Path : string) : boolean of object; TPythonPathAdder = class(TInterfacedObject, IInterface) private fPath : string; fPathAdded : boolean; PackageRootAdder : IInterface; fAutoRemove : Boolean; fSysPathRemove : TSysPathFunction; public constructor Create(SysPathAdd, SysPathRemove : TSysPathFunction; const Path : string; AutoRemove : Boolean = True); destructor Destroy; override; end; constructor TPythonPathAdder.Create(SysPathAdd, SysPathRemove : TSysPathFunction; const Path: string; AutoRemove : Boolean = True); var S : string; begin inherited Create; fPath := ExcludeTrailingPathDelimiter(Path); fAutoRemove := AutoRemove; fSysPathRemove := SysPathRemove; if (fPath <> '') and DirectoryExists(fPath) then begin // Add parent directory of the root of the package first if DirIsPythonPackage(fPath) then begin S := ExtractFileDir(GetPackageRootDir(fPath)); if S <> fPath then PackageRootAdder := TPythonPathAdder.Create(SysPathAdd, SysPathRemove, S, AutoRemove); end; fPathAdded := SysPathAdd(fPath); end; end; destructor TPythonPathAdder.Destroy; begin PackageRootAdder := nil; // will remove package root if fPathAdded and FAutoRemove then fSysPathRemove(fPath); inherited; end; { TPyBaseInterpreter } function TPyBaseInterpreter.AddPathToPythonPath(const Path: string; AutoRemove: Boolean): IInterface; begin Result := TPythonPathAdder.Create(SysPathAdd, SysPathRemove, Path, AutoRemove); end; destructor TPyBaseInterpreter.Destroy; begin FreeAndNil(fMainModule); inherited; end; function TPyBaseInterpreter.GetMainModule: TModuleProxy; begin if not Assigned(fMainModule) then CreateMainModule; Result := fMainModule; end; procedure TPyBaseInterpreter.HandlePyException(E: EPythonError; SkipFrames : integer = 1); Var TI : TTracebackItem; FileName : string; Editor : IEditor; begin MessagesWindow.ShowPythonTraceback(SkipFrames); MessagesWindow.AddMessage(E.Message); with GetPythonEngine.Traceback do begin if ItemCount > 0 then begin TI := Items[ItemCount -1]; FileName := TI.FileName; if (FileName[1] ='<') and (FileName[Length(FileName)] = '>') then FileName := Copy(FileName, 2, Length(FileName)-2); Editor := GI_EditorFactory.GetEditorByNameOrTitle(FileName); // Check whether the error occurred in the active editor if (Assigned(Editor) and (Editor = PyIDEMainForm.GetActiveEditor)) or PyIDEOptions.JumpToErrorOnException then begin if PyIDEMainForm.ShowFilePosition(TI.FileName, TI.LineNo, 1) and Assigned(GI_ActiveEditor) then begin PyControl.ErrorPos.Editor := GI_ActiveEditor; PyControl.ErrorPos.Line := TI.LineNo; PyControl.DoErrorPosChanged; end; end; end; end; end; procedure TPyBaseInterpreter.Initialize; // Execute python_init.py Var FileName : String; begin FileName := CommandsDataModule.UserDataPath + EngineInitFile; try RunScript(FileName); except on E: Exception do Dialogs.MessageDlg(Format(_(SErrorInitScript), [EngineInitFile, E.Message]), mtError, [mbOK], 0); end; end; procedure TPyBaseInterpreter.ReInitialize; begin raise Exception.Create(_(SNotImplented)); end; procedure TPyBaseInterpreter.RunScript(FileName: string); Var Source : string; AnsiSource : AnsiString; begin // Execute pyscripterEngineSetup.py if FileExists(FileName) then begin if GetPythonEngine.IsPython3000 then begin Source := CleanEOLs(FileToStr(FileName))+#10; RunSource(Source, FileName, 'exec'); end else begin AnsiSource := CleanEOLs(FileToEncodedStr(FileName))+#10; RunSource(AnsiSource, FileName, 'exec'); end; end; end; { TBaseNameSpaceItem } procedure TBaseNameSpaceItem.CompareToOldItem(OldItem: TBaseNameSpaceItem); var i, Index : integer; Child : TBaseNameSpaceItem; begin if OldItem.GotBufferedValue then begin if OldItem.BufferedValue <> Value then Attributes := [nsaChanged]; end; if OldItem.GotChildNodes then begin GetChildNodes; for i := 0 to ChildCount - 1 do begin Child := ChildNode[i]; Index := OldItem.IndexOfChild(Child.Name); if Index >= 0 then Child.CompareToOldItem(OldItem.ChildNode[Index]) else Child.Attributes := [nsaNew]; end; end; end; function TBaseNameSpaceItem.GetOrCalculateValue: string; begin if GotBufferedValue then Result := BufferedValue else begin BufferedValue := GetValue; GotBufferedValue := True; Result := BufferedValue; end; end; { TPythonControl } constructor TPythonControl.Create; begin fDebuggerState := dsInactive; fCurrentPos := TEditorPos.Create; fCurrentPos.Clear; fErrorPos := TEditorPos.Create; fErrorPos.Clear; fRunConfig := TRunConfiguration.Create; end; procedure TPythonControl.Debug(ARunConfig: TRunConfiguration; InitStepIn : Boolean = False; RunToCursorLine : integer = -1); begin SetRunConfig(ARunConfig); if not Assigned(ActiveDebugger) then Exit; PrepareRun; if fRunConfig.WriteOutputToFile then PythonIIForm.StartOutputMirror(Parameters.ReplaceInText(fRunConfig.OutputFileName), fRunConfig.AppendToFile); try ActiveDebugger.Run(fRunConfig, InitStepIn, RunToCursorLine); finally if fRunConfig.WriteOutputToFile then PythonIIForm.StopFileMirror; end; end; destructor TPythonControl.Destroy; begin fCurrentPos.Free; fErrorPos.Free; fRunConfig.Free; inherited; end; function TPythonControl.GetLineInfos(Editor : IEditor; ALine: integer): TDebuggerLineInfos; Var Disabled : boolean; begin Result := []; if ALine > 0 then begin if (Editor = PyControl.CurrentPos.Editor) and (ALine = PyControl.CurrentPos.Line) then Include(Result, dlCurrentLine); if (Editor = PyControl.ErrorPos.Editor) and (ALine = PyControl.ErrorPos.Line) then Include(Result, dlErrorLine); if IsExecutableLine(Editor, ALine) then Include(Result, dlExecutableLine); Disabled := False; if IsBreakpointLine(Editor, ALine, Disabled) then if Disabled then Include(Result, dlDisabledBreakpointLine) else Include(Result, dlBreakpointLine); end; end; function TPythonControl.GetPythonEngineType: TPythonEngineType; begin if Assigned(ActiveInterpreter) then Result := ActiveInterpreter.EngineType else Result := peInternal; end; function TPythonControl.IsBreakpointLine(Editor: IEditor; ALine: integer; var Disabled : boolean): boolean; Var i: integer; begin Result := FALSE; if ALine > 0 then begin i := Editor.Breakpoints.Count - 1; while i >= 0 do begin if TBreakPoint(Editor.Breakpoints[i]).LineNo = ALine then begin Disabled := TBreakPoint(Editor.Breakpoints[i]).Disabled; Result := TRUE; break; end; Dec(i); end; end; end; function TPythonControl.IsExecutableLine(Editor: IEditor; ALine: integer): boolean; begin Assert(Assigned(Editor)); with Editor.SynEdit do begin Result := CommandsDataModule.IsExecutableLine(Lines[ALine-1]); end; end; procedure TPythonControl.ToggleBreakpoint(Editor : IEditor; ALine: integer; CtrlPressed : Boolean = False); var Index : integer; i: integer; BreakPoint : TBreakPoint; begin if ALine > 0 then begin Index := Editor.Breakpoints.Count; // append at the end for i := 0 to Editor.Breakpoints.Count - 1 do begin if TBreakPoint(Editor.Breakpoints[i]).LineNo = ALine then begin if CtrlPressed then // Toggle disabled TBreakPoint(Editor.Breakpoints[i]).Disabled := not TBreakPoint(Editor.Breakpoints[i]).Disabled else Editor.Breakpoints.Delete(i); Index := -1; break; end else if TBreakPoint(Editor.Breakpoints[i]).LineNo > ALine then begin Index := i; break; end; end; if Index >= 0 then begin BreakPoint := TBreakPoint.Create; BreakPoint.LineNo := ALine; if CtrlPressed then BreakPoint.Disabled := True; Editor.Breakpoints.Insert(Index, BreakPoint); end; DoOnBreakpointChanged(Editor, ALine); end; end; procedure TPythonControl.SetActiveDebugger(const Value: TPyBaseDebugger); begin if fActiveDebugger <> Value then begin if Assigned(fActiveDebugger) then FreeAndNil(fActiveDebugger); fActiveDebugger := Value; end; end; procedure TPythonControl.SetActiveInterpreter(const Value: TPyBaseInterpreter); begin if fActiveInterpreter <> Value then begin if Assigned(fActiveInterpreter) and (fActiveInterpreter <> InternalInterpreter) then FreeAndNil(fActiveInterpreter); fActiveInterpreter := Value; end; end; procedure TPythonControl.SetBreakPoint(FileName: string; ALine: integer; Disabled : Boolean; Condition: string); var Editor : IEditor; i: integer; BreakPoint : TBreakPoint; begin Editor := GI_EditorFactory.GetEditorByNameOrTitle(FileName); BreakPoint := nil; if Assigned(Editor) and (ALine > 0) then begin for i := 0 to Editor.Breakpoints.Count - 1 do begin if TBreakPoint(Editor.Breakpoints[i]).LineNo = ALine then begin BreakPoint := TBreakPoint(Editor.Breakpoints[i]); break; end else if TBreakPoint(Editor.Breakpoints[i]).LineNo > ALine then begin BreakPoint := TBreakPoint.Create; Editor.Breakpoints.Insert(i, BreakPoint); break; end; end; if not Assigned(BreakPoint) then begin BreakPoint := TBreakPoint.Create; Editor.Breakpoints.Add(BreakPoint); end; BreakPoint.LineNo := ALine; BreakPoint.Disabled := Disabled; BreakPoint.Condition := Condition; DoOnBreakpointChanged(Editor, ALine); end; end; procedure TPythonControl.SetPythonEngineType(const Value: TPythonEngineType); begin if Value <> PythonEngineType then PythonIIForm.SetPythonEngineType(Value); end; procedure TPythonControl.ClearAllBreakpoints; Var i : integer; begin for i := 0 to GI_EditorFactory.Count -1 do if GI_EditorFactory.Editor[i].Breakpoints.Count > 0 then begin GI_EditorFactory.Editor[i].Breakpoints.Clear; DoOnBreakpointChanged(GI_EditorFactory.Editor[i], -1); end; end; procedure TPythonControl.DoCurrentPosChanged; begin if Assigned(fOnCurrentPosChange) then fOnCurrentPosChange(Self); end; procedure TPythonControl.DoErrorPosChanged; begin if Assigned(fOnErrorPosChange) then fOnErrorPosChange(Self); end; procedure TPythonControl.DoOnBreakpointChanged(Editor : IEditor; ALine: integer); begin fBreakPointsChanged := True; if Assigned(fOnBreakpointChange) then fOnBreakpointChange(Self, Editor, ALine); end; procedure TPythonControl.DoStateChange(NewState : TDebuggerState); Var OldDebuggerState: TDebuggerState; begin OldDebuggerState := fDebuggerState; if NewState in [dsInactive, dsRunning, dsRunningNoDebug] then CurrentPos.Clear else begin ErrorPos.Clear; DoErrorPosChanged; end; fDebuggerState := NewState; if Assigned(fOnStateChange) then fOnStateChange(Self, OldDebuggerState, NewState); PyControl.DoCurrentPosChanged; end; procedure TPythonControl.DoYield(DoIdle : Boolean); begin if Assigned(fOnYield) then fOnYield(Self, DoIdle); end; procedure TPythonControl.ExternalRun(ARunConfig: TRunConfiguration); begin SetRunConfig(ARunConfig); OutputWindow.ExecuteTool(fRunConfig.ExternalRun); end; procedure TPythonControl.PrepareRun; begin if PyIDEOptions.SaveFilesBeforeRun then begin PyIDEMainForm.SaveFileModules; // Application.ProcessMessages; // Application.DoApplicationIdle; // Application.ProcessMessages; PyIDEMainForm.Refresh; // To update save flags end; if PyIDEOptions.SaveEnvironmentBeforeRun then PyIDEMainForm.SaveEnvironment; if PyIDEOptions.ClearOutputBeforeRun then PythonIIForm.actClearContentsExecute(nil); if fRunConfig.EngineType <> PythonEngineType then PythonEngineType := fRunConfig.EngineType else if (icReInitialize in ActiveInterpreter.InterpreterCapabilities) and fRunConfig.ReinitializeBeforeRun then ActiveInterpreter.ReInitialize; end; procedure TPythonControl.SetRunConfig(ARunConfig: TRunConfiguration); begin if ARunConfig <> fRunConfig then begin fRunConfig.Assign(ARunConfig); // Expand Parameters in filename fRunConfig.fScriptName := ''; // to avoid circular substitution fRunConfig.fScriptName := Parameters.ReplaceInText(ARunConfig.fScriptName); PyIDEMainForm.SetRunLastScriptHints(fRunConfig.fScriptName); end; end; function TPythonControl.IsRunning: boolean; begin Result := fDebuggerState in [dsRunning, dsRunningNoDebug]; end; procedure TPythonControl.Run(ARunConfig: TRunConfiguration); begin SetRunConfig(ARunConfig); if not Assigned(ActiveInterpreter) then Exit; PrepareRun; if fRunConfig.WriteOutputToFile then PythonIIForm.StartOutputMirror(Parameters.ReplaceInText(fRunConfig.OutputFileName), fRunConfig.AppendToFile); try ActiveInterpreter.RunNoDebug(fRunConfig); finally if fRunConfig.WriteOutputToFile then PythonIIForm.StopFileMirror; end; end; { TPyBaseDebugger } function TPyBaseDebugger.AddPathToPythonPath(const Path: string; AutoRemove: Boolean): IInterface; begin Result := TPythonPathAdder.Create(SysPathAdd, SysPathRemove, Path, AutoRemove); end; { TRunConfiguration } procedure TRunConfiguration.Assign(Source: TPersistent); begin if Source is TRunConfiguration then with TRunConfiguration(Source) do begin Self.fScriptName := ScriptName; Self.fDescription := Description; Self.fEngineType := EngineType; Self.fWorkingDir := WorkingDir; Self.fParameters := fParameters; Self.fReinitializeBeforeRun := ReinitializeBeforeRun; Self.fWriteOutputToFile := WriteOutputToFile; Self.fOutputFileName := OutputFileName; Self.fAppendToFile := AppendToFile; Self.fExternalRun.Assign(fExternalRun); end else inherited; end; constructor TRunConfiguration.Create; begin inherited; fEngineType := peRemote; fReinitializeBeforeRun := True; fOutputFileName := '$[ActiveScript-NoExt].log'; fWorkingDir := '$[ActiveScript-Dir]'; fExternalRun := TExternalRun.Create; fExternalRun.Assign(ExternalPython); fExternalRun.Caption := 'External Run'; fExternalRun.Description := 'Run script using an external Python Interpreter'; fExternalRun.Parameters := '$[ActiveScript-Short]'; fExternalRun.WorkingDirectory := '$[ActiveScript-Dir]'; end; destructor TRunConfiguration.Destroy; begin fExternalRun.Free; inherited; end; procedure TRunConfiguration.SetExternalRun(const Value: TExternalRun); begin fExternalRun.Assign(Value); end; { TModuleProxy } procedure TModuleProxy.Expand; Var i : integer; VariableProxy : TVariableProxy; NS, ChildNS : TBaseNameSpaceItem; begin if Name = '__main__' then begin if Assigned(fChildren) then fChildren.Clear; fGlobals.Clear; end else if fIsExpanded then Exit; NS := Interpreter.NameSpaceItemFromPyObject(Name, fPyModule); try for I := 0 to NS.ChildCount - 1 do begin ChildNS := NS.ChildNode[i]; if ChildNS.IsFunction or ChildNS.IsMethod then AddChild(TFunctionProxy.CreateFromFunction(ChildNS.Name, ChildNS.PyObject)) else if ChildNS.IsClass then AddChild(TClassProxy.CreateFromClass(ChildNS.Name, ChildNS.PyObject)) else begin VariableProxy := TVariableProxy.CreateFromPyObject(ChildNS.Name, ChildNS.PyObject); VariableProxy.Parent := self; Globals.Add(VariableProxy); end; end; finally NS.Free; end; fIsExpanded := True; end; constructor TModuleProxy.CreateFromModule(AModule: Variant; aPyInterpreter : TPyBaseInterpreter); begin inherited Create; if not VarIsPython(AModule) or (AModule.__class__.__name__ <> 'module') then Raise Exception.Create('TModuleProxy creation error'); Name := AModule.__name__; fPyModule := AModule; fIsExpanded := false; fIsProxy := True; if BuiltInModule.hasattr(fPyModule, '__file__') then FileName := fPyModule.__file__; fPyInterpreter := aPyInterpreter; end; procedure TModuleProxy.GetNameSpace(SList: TStringList); begin Expand; inherited; end; function TModuleProxy.GetAllExportsVar: string; begin Result := ''; // No need since we are exporting what is needed // if BuiltInModule.hasattr(fPyModule, '__all__') then begin // try // PythonIIForm.ShowOutput := False; // Result := BuiltInModule.str(fPyModule.__all__); // Result := Copy(Result, 2, Length(Result) - 2); // except // Result := ''; // end; // PythonIIForm.ShowOutput := True; // end; end; function TModuleProxy.GetDocString: string; Var PyDocString : Variant; begin PyDocString := Import('inspect').getdoc(fPyModule); if not VarIsNone(PyDocString) then Result := PyDocString else Result := ''; end; function TModuleProxy.GetCodeHint: string; begin if IsPackage then Result := Format(_(SPackageProxyCodeHint), [Name]) else Result := Format(_(SModuleProxyCodeHint), [Name]); end; { TClassProxy } procedure TClassProxy.Expand; Var i : integer; VariableProxy : TVariableProxy; NS, ChildNS : TBaseNameSpaceItem; begin if fIsExpanded then Exit; NS := (GetModule as TModuleProxy).Interpreter.NameSpaceItemFromPyObject(Name, fPyClass); NS.ExpandCommonTypes := True; NS.ExpandSequences := False; try for I := 0 to NS.ChildCount - 1 do begin ChildNS := NS.ChildNode[i]; if ChildNS.IsFunction or ChildNS.IsMethod then AddChild(TFunctionProxy.CreateFromFunction(ChildNS.Name, ChildNS.PyObject)) else if ChildNS.IsClass then AddChild(TClassProxy.CreateFromClass(ChildNS.Name, ChildNS.PyObject)) else begin VariableProxy := TVariableProxy.CreateFromPyObject(ChildNS.Name, ChildNS.PyObject); VariableProxy.Parent := self; Attributes.Add(VariableProxy); end; end; finally NS.Free; end; // setup base classes try for i := 0 to len(fPyClass.__bases__) - 1 do SuperClasses.Add(fPyClass.__bases__[i].__name__); except // absorb this exception - nothing we can do end; fIsExpanded := True; end; constructor TClassProxy.CreateFromClass(AName : string; AClass: Variant); begin inherited Create; if not VarIsPythonClass(AClass) then Raise Exception.Create('TClassProxy creation error'); Name := AName; fPyClass := AClass; fIsExpanded := false; fIsProxy := True; end; procedure TClassProxy.GetNameSpace(SList: TStringList); Var i : integer; begin Expand; // There is no need to examine base classes so we do not call inherited // Add from Children for i := 0 to ChildCount - 1 do SList.AddObject(TCodeElement(Children[i]).Name, Children[i]); for i := 0 to Attributes.Count - 1 do SList.AddObject(TVariable(Attributes[i]).Name, Attributes[i]) end; function TClassProxy.GetDocString: string; Var PyDocString : Variant; begin PyDocString := Import('inspect').getdoc(fPyClass); if not VarIsNone(PyDocString) then Result := PyDocString else Result := ''; end; function TClassProxy.GetConstructor: TParsedFunction; begin Expand; Result := inherited GetConstructor; end; { TFunctionProxy } function TFunctionProxy.ArgumentsString: string; begin Result := InternalInterpreter.PyInteractiveInterpreter.get_arg_text(fPyFunction).__getitem__(0); end; constructor TFunctionProxy.CreateFromFunction(AName : string; AFunction: Variant); var InspectModule : Variant; begin inherited Create; InspectModule := Import('inspect'); if InspectModule.isroutine(AFunction) then begin // Name := AFunction.__name__; Name := AName; fPyFunction := AFunction; fIsExpanded := false; fIsProxy := True; end else Raise Exception.Create('TFunctionProxy creation error'); end; procedure TFunctionProxy.Expand; Var i : integer; NoOfArgs : integer; Variable : TVariable; NS, ChildNS : TBaseNameSpaceItem; begin if fIsExpanded then Exit; NS := (GetModule as TModuleProxy).Interpreter.NameSpaceItemFromPyObject(Name, fPyFunction); NS.ExpandCommonTypes := True; NS.ExpandSequences := False; try for I := 0 to NS.ChildCount - 1 do begin ChildNS := NS.ChildNode[i]; if ChildNS.IsFunction or ChildNS.IsMethod then AddChild(TFunctionProxy.CreateFromFunction(ChildNS.Name, ChildNS.PyObject)) else if ChildNS.IsClass then AddChild(TClassProxy.CreateFromClass(ChildNS.Name, ChildNS.PyObject)) else begin AddChild(TVariableProxy.CreateFromPyObject(ChildNS.Name, ChildNS.PyObject)); end; end; finally NS.Free; end; fIsExpanded := True; // Arguments and Locals if BuiltinModule.hasattr(fPyFunction, 'func_code') then begin NoOfArgs := fPyFunction.func_code.co_argcount; for i := 0 to len(fPyFunction.func_code.co_varnames) - 1 do begin Variable := TVariable.Create; Variable.Name := fPyFunction.func_code.co_varnames[i]; Variable.Parent := Self; if i < NoOfArgs then begin Variable.Attributes := [vaArgument]; Arguments.Add(Variable); end else Locals.Add(Variable); end; end else if BuiltinModule.hasattr(fPyFunction, '__code__') then begin //Python 3000 NoOfArgs := fPyFunction.__code__.co_argcount; for i := 0 to len(fPyFunction.__code__.co_varnames) - 1 do begin Variable := TVariable.Create; Variable.Name := fPyFunction.__code__.co_varnames[i]; Variable.Parent := Self; if i < NoOfArgs then begin Variable.Attributes := [vaArgument]; Arguments.Add(Variable); end else Locals.Add(Variable); end; end; end; function TFunctionProxy.GetDocString: string; Var PyDocString : Variant; begin PyDocString := Import('inspect').getdoc(fPyFunction); if not VarIsNone(PyDocString) then Result := PyDocString else Result := ''; end; procedure TFunctionProxy.GetNameSpace(SList: TStringList); begin Expand; inherited; end; { TVariableProxy } constructor TVariableProxy.CreateFromPyObject(const AName: string; AnObject: Variant); begin inherited Create; Name := AName; fPyObject := AnObject; fIsExpanded := false; fIsProxy := True; end; procedure TVariableProxy.GetNameSpace(SList: TStringList); begin Expand; inherited; end; procedure TVariableProxy.Expand; Var i : integer; NS, ChildNS : TBaseNameSpaceItem; begin if fIsExpanded then Exit; NS := (GetModule as TModuleProxy).Interpreter.NameSpaceItemFromPyObject(Name, fPyObject); NS.ExpandCommonTypes := True; NS.ExpandSequences := False; try for I := 0 to NS.ChildCount - 1 do begin ChildNS := NS.ChildNode[i]; if ChildNS.IsFunction or ChildNS.IsMethod then AddChild(TFunctionProxy.CreateFromFunction(ChildNS.Name, ChildNS.PyObject)) else if ChildNS.IsClass then AddChild(TClassProxy.CreateFromClass(ChildNS.Name, ChildNS.PyObject)) else if ChildNS.IsModule then AddChild(TModuleProxy.CreateFromModule(ChildNS.PyObject, (GetModule as TModuleProxy).Interpreter)) else begin AddChild(TVariableProxy.CreateFromPyObject(ChildNS.Name, ChildNS.PyObject)); end; end; finally NS.Free; end; fIsExpanded := True; end; function TVariableProxy.GetDocString: string; Var PyDocString : Variant; begin PyDocString := Import('inspect').getdoc(fPyObject); if not VarIsNone(PyDocString) then Result := PyDocString else Result := ''; end; function TVariableProxy.GetCodeHint: string; Var Fmt, ObjType : string; begin if Parent is TParsedFunction then Fmt := _(SLocalVariableCodeHint) else if Parent is TParsedClass then Fmt := _(SInstanceVariableCodeHint) else if Parent is TParsedModule then Fmt := _(SGlobalVariableCodeHint) else Fmt := ''; if Fmt <> '' then begin Result := Format(Fmt, [Name, Parent.Name, '']); ObjType := BuiltInModule.type(PyObject).__name__; Result := Result + Format(_(SVariableTypeCodeHint), [ObjType]); end else Result := ''; end; initialization PyControl := TPythonControl.Create; finalization FreeAndNil(PyControl); end.
unit Xml.Internal.LangUtils; // LangUtils 1.0.4 // Delphi 4 to 2009 and Kylix 3 Implementation // February 2009 // // // LICENSE // // 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 "LangUtils.pas". // // The Initial Developer of the Original Code is Dieter Köhler (Heidelberg, // Germany, "http://www.philo.de/"). Portions created by the Initial Developer // are Copyright (C) 2003-2009 Dieter Köhler. All Rights Reserved. // // Alternatively, the contents of this file may be used under the terms of the // GNU General Public License Version 2 or later (the "GPL"), in which case the // provisions of the GPL are applicable instead of those above. If you wish to // allow use of your version of this file only under the terms of the GPL, and // not to allow others to use your version of this file under the terms of the // MPL, indicate your decision by deleting the provisions above and replace them // with the notice and other provisions required by the GPL. If you do not delete // the provisions above, a recipient may use your version of this file under the // terms of any one of the MPL or the GPL. // HISTORY // // 2009-02-23 1.0.4 Internal modifications. // 2008-09-28 1.0.3 Internal modifications. // 2007-12-03 1.0.2 Made .NET compliant. // 2003-09-20 1.0.1 ISO 639 language constants added. // TIso639Info class added. // 2003-08-03 1.0.0 interface uses System.Classes; type TIso639LanguageCode = (iso639_aa, // Afar iso639_ab, // Abkhazian iso639_af, // Afrikaans iso639_am, // Amharic iso639_ar, // Arabic iso639_as, // Assamese iso639_ay, // Aymara iso639_az, // Azerbaijani iso639_ba, // Bashkir iso639_be, // Byelorussian iso639_bg, // Bulgarian iso639_bh, // Bihari iso639_bi, // Bislama iso639_bn, // Bengali; Bangla iso639_bo, // Tibetan iso639_br, // Breton iso639_ca, // Catalan iso639_co, // Corsican iso639_cs, // Czech iso639_cy, // Welsh iso639_da, // Danish iso639_de, // German iso639_dz, // Bhutani iso639_el, // Greek iso639_en, // English iso639_eo, // Esperanto iso639_es, // Spanish iso639_et, // Estonian iso639_eu, // Basque iso639_fa, // Persian iso639_fi, // Finnish iso639_fj, // Fiji iso639_fo, // Faeroese iso639_fr, // French iso639_fy, // Frisian iso639_ga, // Irish iso639_gd, // Scots Gaelic iso639_gl, // Galician iso639_gn, // Guarani iso639_gu, // Gujarati iso639_ha, // Hausa iso639_hi, // Hindi iso639_hr, // Croatian iso639_hu, // Hungarian iso639_hy, // Armenian iso639_ia, // Interlingua iso639_ie, // Interlingue iso639_ik, // Inupiak iso639_in, // Indonesian iso639_is, // Icelandic iso639_it, // Italian iso639_iw, // Hebrew iso639_ja, // Japanese iso639_ji, // Yiddish iso639_jw, // Javanese iso639_ka, // Georgian iso639_kk, // Kazakh iso639_kl, // Greenlandic iso639_km, // Cambodian iso639_kn, // Kannada iso639_ko, // Korean iso639_ks, // Kashmiri iso639_ku, // Kurdish iso639_ky, // Kirghiz iso639_la, // Latin iso639_ln, // Lingala iso639_lo, // Laothian iso639_lt, // Lithuanian iso639_lv, // Latvian; Lettish iso639_mg, // Malagasy iso639_mi, // Maori iso639_mk, // Macedonian iso639_ml, // Malayalam iso639_mn, // Mongolian iso639_mo, // Moldavian iso639_mr, // Marathi iso639_ms, // Malay iso639_mt, // Maltese iso639_my, // Burmese iso639_na, // Nauru iso639_ne, // Nepali iso639_nl, // Dutch iso639_no, // Norwegian iso639_oc, // Occitan iso639_om, // Afan; Oromo iso639_or, // Oriya iso639_pa, // Punjabi iso639_pl, // Polish iso639_ps, // Pashto; Pushto iso639_pt, // Portuguese iso639_qu, // Quechua iso639_rm, // Rhaeto-Romance iso639_rn, // Kirundi iso639_ro, // Romanian iso639_ru, // Russian iso639_rw, // Kinyarwanda iso639_sa, // Sanskrit iso639_sd, // Sindhi iso639_sg, // Sangro iso639_sh, // Serbo-Croatian iso639_si, // Singhalese iso639_sk, // Slovak iso639_sl, // Slovenian iso639_sm, // Samoan iso639_sn, // Shona iso639_so, // Somali iso639_sq, // Albanian iso639_sr, // Serbian iso639_ss, // Siswati iso639_st, // Sesotho iso639_su, // Sundanese iso639_sv, // Swedish iso639_sw, // Swahili iso639_ta, // Tamil iso639_te, // Tegulu iso639_tg, // Tajik iso639_th, // Thai iso639_ti, // Tigrinya iso639_tk, // Turkmen iso639_tl, // Tagalog iso639_tn, // Setswana iso639_to, // Tonga iso639_tr, // Turkish iso639_ts, // Tsonga iso639_tt, // Tatar iso639_tw, // Twi iso639_uk, // Ukrainian iso639_ur, // Urdu iso639_uz, // Uzbek iso639_vi, // Vietnamese iso639_vo, // Volapuk iso639_wo, // Wolof iso639_xh, // Xhosa iso639_yo, // Yoruba iso639_zh, // Chinese iso639_zu // Zulu ); TIso639LanguageCodeSet = set of TIso639LanguageCode; TIso639Info = class(TPersistent) private {$IFDEF NEXTGEN} function CodeToName_en(Value: TIso639LanguageCode): string; function NameToCode_en(Value: string): TIso639LanguageCode; {$ELSE !NEXTGEN} function CodeToName_en(Value: TIso639LanguageCode): WideString; function NameToCode_en(Value: WideString): TIso639LanguageCode; {$ENDIF NEXTGEN} protected FAppendSymbolToName: Boolean; FNameLanguage: TIso639LanguageCode; FSupportedLanguages: TIso639LanguageCodeSet; procedure AssignTo(Dest: TPersistent); override; procedure SetNameLanguage(const Value: TIso639LanguageCode); virtual; public constructor Create; {$IFDEF NEXTGEN} function CodeToName(const Value: TIso639LanguageCode): string; virtual; function CodeToSymbol(const Value: TIso639LanguageCode): string; virtual; function NameToCode(const Value: string): TIso639LanguageCode; virtual; function SymbolToCode(const Value: string): TIso639LanguageCode; virtual; {$ELSE !NEXTGEN} function CodeToName(const Value: TIso639LanguageCode): WideString; virtual; function CodeToSymbol(const Value: TIso639LanguageCode): WideString; virtual; function NameToCode(const Value: WideString): TIso639LanguageCode; virtual; function SymbolToCode(const Value: WideString): TIso639LanguageCode; virtual; {$ENDIF NEXTGEN} property AppendSymbolToName: Boolean read FAppendSymbolToName write FAppendSymbolToName default false; property NameLanguage: TIso639LanguageCode read FNameLanguage write SetNameLanguage default iso639_en; property SupportedLanguages: TIso639LanguageCodeSet read FSupportedLanguages; end; function IsRFC3066LanguageTag(const S: string): Boolean; {$IFDEF NEXTGEN} function IsSubLanguage(const Sublanguage, Superlanguage: string): Boolean; {$ELSE !NEXTGEN} function IsSubLanguage(const Sublanguage, Superlanguage: WideString): Boolean; {$ENDIF NEXTGEN} implementation uses {$IFDEF CLR} ParserUtilsRTL, {$ELSE} Xml.Internal.ParserUtilsWin32, {$ENDIF} Xml.Internal.WideStringUtils, Xml.Internal.AbnfUtils, System.SysUtils; {$IF CompilerVersion >= 24.0} const FirstIndex = Low(string); AdjustIndex = 1-Low(string); {$ELSE} const FirstIndex = 1; AdjustIndex = 0; {$ENDIF} { Helper functions} function IsRFC3066LanguageTag(const S: string): Boolean; var I: Integer; LetterCount: Integer; PrimaryTag: Boolean; TagStart: Boolean; begin LetterCount := 0; PrimaryTag := True; TagStart := True; for I := Low(S) to High(S) do begin if IsAbnfALPHAChar(S[I]) then begin TagStart := False; Inc(LetterCount); if LetterCount > 8 then begin Result := False; Exit; end; end else if IsAbnfDIGITChar(S[I]) then begin if PrimaryTag then begin Result := False; Exit; end; TagStart := False; Inc(LetterCount); if LetterCount > 8 then begin Result := False; Exit; end; end else if S[I] = '-' then begin if TagStart then begin Result := False; Exit; end; PrimaryTag := False; TagStart := True; LetterCount := 0; end; end; if TagStart then Result := False else Result := True; end; {$IFDEF NEXTGEN} function IsSubLanguage(const Sublanguage, Superlanguage: string): Boolean; {$ELSE !NEXTGEN} function IsSubLanguage(const Sublanguage, Superlanguage: WideString): Boolean; {$ENDIF NEXTGEN} begin if Length(Sublanguage) = Length(Superlanguage) then begin Result := CompareText(Sublanguage, Superlanguage) = 0 end else if Length(Sublanguage) > Length(Superlanguage) then begin Result := CompareText(copy(Sublanguage, 1, Length(Superlanguage) + 1), Superlanguage + '-') = 0 end else Result := False; end; { TIso639Info } constructor TIso639Info.Create; begin inherited; FSupportedLanguages := [iso639_en]; FNameLanguage := iso639_en; FAppendSymbolToName := False; end; procedure TIso639Info.AssignTo(Dest: TPersistent); var I: Integer; begin if Dest is TStrings then begin TStrings(Dest).BeginUpdate; try TStrings(Dest).Clear; try for I := Ord(Low(TIso639LanguageCode)) to Ord(High(TIso639LanguageCode)) do {$IFDEF CLR} TStrings(Dest).AddObject(ConvertFromUTF16('US-ASCII', CodeToName(TIso639LanguageCode(I))), TObject(I)); {$ELSE} {$IFDEF UNICODE} TStrings(Dest).AddObject( CodeToName(TIso639LanguageCode(I)), Pointer(I)); {$ELSE} TStrings(Dest).AddObject(ConvertFromUTF16('US-ASCII', CodeToName(TIso639LanguageCode(I))), Pointer(I)); {$ENDIF} {$ENDIF} except TStrings(Dest).Clear; raise; end; finally TStrings(Dest).EndUpdate; end; end else if Dest is TUtilsWideStringList then begin TUtilsWideStringList(Dest).BeginUpdate; try TUtilsWideStringList(Dest).Clear; try for I := Ord(Low(TIso639LanguageCode)) to Ord(High(TIso639LanguageCode)) do TUtilsWideStringList(Dest).AddObject(CodeToName(TIso639LanguageCode(I)), {$IFDEF CLR}TObject(I){$ELSE}Pointer(I){$ENDIF}); except TUtilsWideStringList(Dest).Clear; raise; end; finally TUtilsWideStringList(Dest).EndUpdate; end; end else inherited AssignTo(Dest); end; {$IFDEF NEXTGEN} function TIso639Info.CodeToName(const Value: TIso639LanguageCode): string; {$ELSE !NEXTGEN} function TIso639Info.CodeToName(const Value: TIso639LanguageCode): WideString; {$ENDIF NEXTGEN} begin case NameLanguage of iso639_en: Result := CodeToName_en(Value); else raise EConvertError.Create('Conversion not supported'); end; end; {$IFDEF NEXTGEN} function TIso639Info.CodeToName_en(Value: TIso639LanguageCode): string; {$ELSE !NEXTGEN} function TIso639Info.CodeToName_en(Value: TIso639LanguageCode): WideString; {$ENDIF NEXTGEN} begin if Value = iso639_aa then Result := 'Afar' else if Value = iso639_ab then Result := 'Abkhazian' else if Value = iso639_af then Result := 'Afrikaans' else if Value = iso639_am then Result := 'Amharic' else if Value = iso639_ar then Result := 'Arabic' else if Value = iso639_as then Result := 'Assamese' else if Value = iso639_ay then Result := 'Aymara' else if Value = iso639_az then Result := 'Azerbaijani' else if Value = iso639_ba then Result := 'Bashkir' else if Value = iso639_be then Result := 'Byelorussian' else if Value = iso639_bg then Result := 'Bulgarian' else if Value = iso639_bh then Result := 'Bihari' else if Value = iso639_bi then Result := 'Bislama' else if Value = iso639_bn then Result := 'Bengali; Bangla' else if Value = iso639_bo then Result := 'Tibetan' else if Value = iso639_br then Result := 'Breton' else if Value = iso639_ca then Result := 'Catalan' else if Value = iso639_co then Result := 'Corsican' else if Value = iso639_cs then Result := 'Czech' else if Value = iso639_cy then Result := 'Welsh' else if Value = iso639_da then Result := 'Danish' else if Value = iso639_de then Result := 'German' else if Value = iso639_dz then Result := 'Bhutani' else if Value = iso639_el then Result := 'Greek' else if Value = iso639_en then Result := 'English' else if Value = iso639_eo then Result := 'Esperanto' else if Value = iso639_es then Result := 'Spanish' else if Value = iso639_et then Result := 'Estonian' else if Value = iso639_eu then Result := 'Basque' else if Value = iso639_fa then Result := 'Persian' else if Value = iso639_fi then Result := 'Finnish' else if Value = iso639_fj then Result := 'Fiji' else if Value = iso639_fo then Result := 'Faeroese' else if Value = iso639_fr then Result := 'French' else if Value = iso639_fy then Result := 'Frisian' else if Value = iso639_ga then Result := 'Irish' else if Value = iso639_gd then Result := 'Scots Gaelic' else if Value = iso639_gl then Result := 'Galician' else if Value = iso639_gn then Result := 'Guarani' else if Value = iso639_gu then Result := 'Gujarati' else if Value = iso639_ha then Result := 'Hausa' else if Value = iso639_hi then Result := 'Hindi' else if Value = iso639_hr then Result := 'Croatian' else if Value = iso639_hu then Result := 'Hungarian' else if Value = iso639_hy then Result := 'Armenian' else if Value = iso639_ia then Result := 'Interlingua' else if Value = iso639_ie then Result := 'Interlingue' else if Value = iso639_ik then Result := 'Inupiak' else if Value = iso639_in then Result := 'Indonesian' else if Value = iso639_is then Result := 'Icelandic' else if Value = iso639_it then Result := 'Italian' else if Value = iso639_iw then Result := 'Hebrew' else if Value = iso639_ja then Result := 'Japanese' else if Value = iso639_ji then Result := 'Yiddish' else if Value = iso639_jw then Result := 'Javanese' else if Value = iso639_ka then Result := 'Georgian' else if Value = iso639_kk then Result := 'Kazakh' else if Value = iso639_kl then Result := 'Greenlandic' else if Value = iso639_km then Result := 'Cambodian' else if Value = iso639_kn then Result := 'Kannada' else if Value = iso639_ko then Result := 'Korean' else if Value = iso639_ks then Result := 'Kashmiri' else if Value = iso639_ku then Result := 'Kurdish' else if Value = iso639_ky then Result := 'Kirghiz' else if Value = iso639_la then Result := 'Latin' else if Value = iso639_ln then Result := 'Lingala' else if Value = iso639_lo then Result := 'Laothian' else if Value = iso639_lt then Result := 'Lithuanian' else if Value = iso639_lv then Result := 'Latvian; Lettish' else if Value = iso639_mg then Result := 'Malagasy' else if Value = iso639_mi then Result := 'Maori' else if Value = iso639_mk then Result := 'Macedonian' else if Value = iso639_ml then Result := 'Malayalam' else if Value = iso639_mn then Result := 'Mongolian' else if Value = iso639_mo then Result := 'Moldavian' else if Value = iso639_mr then Result := 'Marathi' else if Value = iso639_ms then Result := 'Malay' else if Value = iso639_mt then Result := 'Maltese' else if Value = iso639_my then Result := 'Burmese' else if Value = iso639_na then Result := 'Nauru' else if Value = iso639_ne then Result := 'Nepali' else if Value = iso639_nl then Result := 'Dutch' else if Value = iso639_no then Result := 'Norwegian' else if Value = iso639_oc then Result := 'Occitan' else if Value = iso639_om then Result := 'Afan; Oromo' else if Value = iso639_or then Result := 'Oriya' else if Value = iso639_pa then Result := 'Punjabi' else if Value = iso639_pl then Result := 'Polish' else if Value = iso639_ps then Result := 'Pashto; Pushto' else if Value = iso639_pt then Result := 'Portuguese' else if Value = iso639_qu then Result := 'Quechua' else if Value = iso639_rm then Result := 'Rhaeto-Romance' else if Value = iso639_rn then Result := 'Kirundi' else if Value = iso639_ro then Result := 'Romanian' else if Value = iso639_ru then Result := 'Russian' else if Value = iso639_rw then Result := 'Kinyarwanda' else if Value = iso639_sa then Result := 'Sanskrit' else if Value = iso639_sd then Result := 'Sindhi' else if Value = iso639_sg then Result := 'Sangro' else if Value = iso639_sh then Result := 'Serbo-Croatian' else if Value = iso639_si then Result := 'Singhalese' else if Value = iso639_sk then Result := 'Slovak' else if Value = iso639_sl then Result := 'Slovenian' else if Value = iso639_sm then Result := 'Samoan' else if Value = iso639_sn then Result := 'Shona' else if Value = iso639_so then Result := 'Somali' else if Value = iso639_sq then Result := 'Albanian' else if Value = iso639_sr then Result := 'Serbian' else if Value = iso639_ss then Result := 'Siswati' else if Value = iso639_st then Result := 'Sesotho' else if Value = iso639_su then Result := 'Sundanese' else if Value = iso639_sv then Result := 'Swedish' else if Value = iso639_sw then Result := 'Swahili' else if Value = iso639_ta then Result := 'Tamil' else if Value = iso639_te then Result := 'Tegulu' else if Value = iso639_tg then Result := 'Tajik' else if Value = iso639_th then Result := 'Thai' else if Value = iso639_ti then Result := 'Tigrinya' else if Value = iso639_tk then Result := 'Turkmen' else if Value = iso639_tl then Result := 'Tagalog' else if Value = iso639_tn then Result := 'Setswana' else if Value = iso639_to then Result := 'Tonga' else if Value = iso639_tr then Result := 'Turkish' else if Value = iso639_ts then Result := 'Tsonga' else if Value = iso639_tt then Result := 'Tatar' else if Value = iso639_tw then Result := 'Twi' else if Value = iso639_uk then Result := 'Ukrainian' else if Value = iso639_ur then Result := 'Urdu' else if Value = iso639_uz then Result := 'Uzbek' else if Value = iso639_vi then Result := 'Vietnamese' else if Value = iso639_vo then Result := 'Volapuk' else if Value = iso639_wo then Result := 'Wolof' else if Value = iso639_xh then Result := 'Xhosa' else if Value = iso639_yo then Result := 'Yoruba' else if Value = iso639_zh then Result := 'Chinese' else if Value = iso639_zu then Result := 'Zulu' ; if FAppendSymbolToName then Result := Concat(Result, ' [', CodeToSymbol(Value), ']'); end; {$IFDEF NEXTGEN} function TIso639Info.codeToSymbol(const Value: TIso639LanguageCode): string; {$ELSE !NEXTGEN} function TIso639Info.codeToSymbol(const Value: TIso639LanguageCode): WideString; {$ENDIF NEXTGEN} begin if Value = iso639_aa then Result := 'aa' // Afar else if Value = iso639_ab then Result := 'ab' // Abkhazian else if Value = iso639_af then Result := 'af' // Afrikaans else if Value = iso639_am then Result := 'am' // Amharic else if Value = iso639_ar then Result := 'ar' // Arabic else if Value = iso639_as then Result := 'as' // Assamese else if Value = iso639_ay then Result := 'ay' // Aymara else if Value = iso639_az then Result := 'az' // Azerbaijani else if Value = iso639_ba then Result := 'ba' // Bashkir else if Value = iso639_be then Result := 'be' // Byelorussian else if Value = iso639_bg then Result := 'bg' // Bulgarian else if Value = iso639_bh then Result := 'bh' // Bihari else if Value = iso639_bi then Result := 'bi' // Bislama else if Value = iso639_bn then Result := 'bn' // Bengali; Bangla else if Value = iso639_bo then Result := 'bo' // Tibetan else if Value = iso639_br then Result := 'br' // Breton else if Value = iso639_ca then Result := 'ca' // Catalan else if Value = iso639_co then Result := 'co' // Corsican else if Value = iso639_cs then Result := 'cs' // Czech else if Value = iso639_cy then Result := 'cy' // Welsh else if Value = iso639_da then Result := 'da' // Danish else if Value = iso639_de then Result := 'de' // German else if Value = iso639_dz then Result := 'dz' // Bhutani else if Value = iso639_el then Result := 'el' // Greek else if Value = iso639_en then Result := 'en' // English else if Value = iso639_eo then Result := 'eo' // Esperanto else if Value = iso639_es then Result := 'es' // Spanish else if Value = iso639_et then Result := 'et' // Estonian else if Value = iso639_eu then Result := 'eu' // Basque else if Value = iso639_fa then Result := 'fa' // Persian else if Value = iso639_fi then Result := 'fi' // Finnish else if Value = iso639_fj then Result := 'fj' // Fiji else if Value = iso639_fo then Result := 'fo' // Faeroese else if Value = iso639_fr then Result := 'fr' // French else if Value = iso639_fy then Result := 'fy' // Frisian else if Value = iso639_ga then Result := 'ga' // Irish else if Value = iso639_gd then Result := 'gd' // Scots Gaelic else if Value = iso639_gl then Result := 'gl' // Galician else if Value = iso639_gn then Result := 'gn' // Guarani else if Value = iso639_gu then Result := 'gu' // Gujarati else if Value = iso639_ha then Result := 'ha' // Hausa else if Value = iso639_hi then Result := 'hi' // Hindi else if Value = iso639_hr then Result := 'hr' // Croatian else if Value = iso639_hu then Result := 'hu' // Hungarian else if Value = iso639_hy then Result := 'hy' // Armenian else if Value = iso639_ia then Result := 'ia' // Interlingua else if Value = iso639_ie then Result := 'ie' // Interlingue else if Value = iso639_ik then Result := 'ik' // Inupiak else if Value = iso639_in then Result := 'in' // Indonesian else if Value = iso639_is then Result := 'is' // Icelandic else if Value = iso639_it then Result := 'it' // Italian else if Value = iso639_iw then Result := 'iw' // Hebrew else if Value = iso639_ja then Result := 'ja' // Japanese else if Value = iso639_ji then Result := 'ji' // Yiddish else if Value = iso639_jw then Result := 'jw' // Javanese else if Value = iso639_ka then Result := 'ka' // Georgian else if Value = iso639_kk then Result := 'kk' // Kazakh else if Value = iso639_kl then Result := 'kl' // Greenlandic else if Value = iso639_km then Result := 'km' // Cambodian else if Value = iso639_kn then Result := 'kn' // Kannada else if Value = iso639_ko then Result := 'ko' // Korean else if Value = iso639_ks then Result := 'ks' // Kashmiri else if Value = iso639_ku then Result := 'ku' // Kurdish else if Value = iso639_ky then Result := 'ky' // Kirghiz else if Value = iso639_la then Result := 'la' // Latin else if Value = iso639_ln then Result := 'ln' // Lingala else if Value = iso639_lo then Result := 'lo' // Laothian else if Value = iso639_lt then Result := 'lt' // Lithuanian else if Value = iso639_lv then Result := 'lv' // Latvian; Lettish else if Value = iso639_mg then Result := 'mg' // Malagasy else if Value = iso639_mi then Result := 'mi' // Maori else if Value = iso639_mk then Result := 'mk' // Macedonian else if Value = iso639_ml then Result := 'ml' // Malayalam else if Value = iso639_mn then Result := 'mn' // Mongolian else if Value = iso639_mo then Result := 'mo' // Moldavian else if Value = iso639_mr then Result := 'mr' // Marathi else if Value = iso639_ms then Result := 'ms' // Malay else if Value = iso639_mt then Result := 'mt' // Maltese else if Value = iso639_my then Result := 'my' // Burmese else if Value = iso639_na then Result := 'na' // Nauru else if Value = iso639_ne then Result := 'ne' // Nepali else if Value = iso639_nl then Result := 'nl' // Dutch else if Value = iso639_no then Result := 'no' // Norwegian else if Value = iso639_oc then Result := 'oc' // Occitan else if Value = iso639_om then Result := 'om' // Afan; Oromo else if Value = iso639_or then Result := 'or' // Oriya else if Value = iso639_pa then Result := 'pa' // Punjabi else if Value = iso639_pl then Result := 'pl' // Polish else if Value = iso639_ps then Result := 'ps' // Pashto; Pushto else if Value = iso639_pt then Result := 'pt' // Portuguese else if Value = iso639_qu then Result := 'qu' // Quechua else if Value = iso639_rm then Result := 'rm' // Rhaeto-Romance else if Value = iso639_rn then Result := 'rn' // Kirundi else if Value = iso639_ro then Result := 'ro' // Romanian else if Value = iso639_ru then Result := 'ru' // Russian else if Value = iso639_rw then Result := 'rw' // Kinyarwanda else if Value = iso639_sa then Result := 'sa' // Sanskrit else if Value = iso639_sd then Result := 'sd' // Sindhi else if Value = iso639_sg then Result := 'sg' // Sangro else if Value = iso639_sh then Result := 'sh' // Serbo-Croatian else if Value = iso639_si then Result := 'si' // Singhalese else if Value = iso639_sk then Result := 'sk' // Slovak else if Value = iso639_sl then Result := 'sl' // Slovenian else if Value = iso639_sm then Result := 'sm' // Samoan else if Value = iso639_sn then Result := 'sn' // Shona else if Value = iso639_so then Result := 'so' // Somali else if Value = iso639_sq then Result := 'sq' // Albanian else if Value = iso639_sr then Result := 'sr' // Serbian else if Value = iso639_ss then Result := 'ss' // Siswati else if Value = iso639_st then Result := 'st' // Sesotho else if Value = iso639_su then Result := 'su' // Sundanese else if Value = iso639_sv then Result := 'sv' // Swedish else if Value = iso639_sw then Result := 'sw' // Swahili else if Value = iso639_ta then Result := 'ta' // Tamil else if Value = iso639_te then Result := 'te' // Tegulu else if Value = iso639_tg then Result := 'tg' // Tajik else if Value = iso639_th then Result := 'th' // Thai else if Value = iso639_ti then Result := 'ti' // Tigrinya else if Value = iso639_tk then Result := 'tk' // Turkmen else if Value = iso639_tl then Result := 'tl' // Tagalog else if Value = iso639_tn then Result := 'tn' // Setswana else if Value = iso639_to then Result := 'to' // Tonga else if Value = iso639_tr then Result := 'tr' // Turkish else if Value = iso639_ts then Result := 'ts' // Tsonga else if Value = iso639_tt then Result := 'tt' // Tatar else if Value = iso639_tw then Result := 'tw' // Twi else if Value = iso639_uk then Result := 'uk' // Ukrainian else if Value = iso639_ur then Result := 'ur' // Urdu else if Value = iso639_uz then Result := 'uz' // Uzbek else if Value = iso639_vi then Result := 'vi' // Vietnamese else if Value = iso639_vo then Result := 'vo' // Volapuk else if Value = iso639_wo then Result := 'wo' // Wolof else if Value = iso639_xh then Result := 'xh' // Xhosa else if Value = iso639_yo then Result := 'yo' // Yoruba else if Value = iso639_zh then Result := 'zh' // Chinese else if Value = iso639_zu then Result := 'zu' // Zulu ; end; {$IFDEF NEXTGEN} function TIso639Info.NameToCode(const Value: string): TIso639LanguageCode; {$ELSE !NEXTGEN} function TIso639Info.NameToCode(const Value: WideString): TIso639LanguageCode; {$ENDIF NEXTGEN} begin case NameLanguage of iso639_en: Result := NameToCode_en(Value); else raise EConvertError.Create('Conversion not supported'); end; end; {$IFDEF NEXTGEN} function TIso639Info.NameToCode_en(Value: string): TIso639LanguageCode; {$ELSE !NEXTGEN} function TIso639Info.NameToCode_en(Value: WideString): TIso639LanguageCode; {$ENDIF NEXTGEN} var I, J: integer; {$IFDEF NEXTGEN} Dummy: string; {$ELSE !NEXTGEN} Dummy: WideString; {$ENDIF NEXTGEN} begin I := Pos(';', Value); if I > 0 then begin Dummy := Copy(Value, 1, I - 1); Value := Dummy; end else begin J := Pos('[', Value); if J > 1 then begin if Value[J - AdjustIndex] = ' ' then begin Dummy := Copy(Value, 1, J - 2); Value := Dummy; end; end; end; if Value = 'Afar' then Result := iso639_aa else if Value = 'Abkhazian' then Result := iso639_ab else if Value = 'Afrikaans' then Result := iso639_af else if Value = 'Amharic' then Result := iso639_am else if Value = 'Arabic' then Result := iso639_ar else if Value = 'Assamese' then Result := iso639_as else if Value = 'Aymara' then Result := iso639_ay else if Value = 'Azerbaijani' then Result := iso639_az else if Value = 'Bashkir' then Result := iso639_ba else if Value = 'Byelorussian' then Result := iso639_be else if Value = 'Bulgarian' then Result := iso639_bg else if Value = 'Bihari' then Result := iso639_bh else if Value = 'Bislama' then Result := iso639_bi else if Value = 'Bengali' then Result := iso639_bn else if Value = 'Bangla' then Result := iso639_bn else if Value = 'Tibetan' then Result := iso639_bo else if Value = 'Breton' then Result := iso639_br else if Value = 'Catalan' then Result := iso639_ca else if Value = 'Corsican' then Result := iso639_co else if Value = 'Czech' then Result := iso639_cs else if Value = 'Welsh' then Result := iso639_cy else if Value = 'Danish' then Result := iso639_da else if Value = 'German' then Result := iso639_de else if Value = 'Bhutani' then Result := iso639_dz else if Value = 'Greek' then Result := iso639_el else if Value = 'English' then Result := iso639_en else if Value = 'Esperanto' then Result := iso639_eo else if Value = 'Spanish' then Result := iso639_es else if Value = 'Estonian' then Result := iso639_et else if Value = 'Basque' then Result := iso639_eu else if Value = 'Persian' then Result := iso639_fa else if Value = 'Finnish' then Result := iso639_fi else if Value = 'Fiji' then Result := iso639_fj else if Value = 'Faeroese' then Result := iso639_fo else if Value = 'French' then Result := iso639_fr else if Value = 'Frisian' then Result := iso639_fy else if Value = 'Irish' then Result := iso639_ga else if Value = 'Scots Gaelic' then Result := iso639_gd else if Value = 'Galician' then Result := iso639_gl else if Value = 'Guarani' then Result := iso639_gn else if Value = 'Gujarati' then Result := iso639_gu else if Value = 'Hausa' then Result := iso639_ha else if Value = 'Hindi' then Result := iso639_hi else if Value = 'Croatian' then Result := iso639_hr else if Value = 'Hungarian' then Result := iso639_hu else if Value = 'Armenian' then Result := iso639_hy else if Value = 'Interlingua' then Result := iso639_ia else if Value = 'Interlingue' then Result := iso639_ie else if Value = 'Inupiak' then Result := iso639_ik else if Value = 'Indonesian' then Result := iso639_in else if Value = 'Icelandic' then Result := iso639_is else if Value = 'Italian' then Result := iso639_it else if Value = 'Hebrew' then Result := iso639_iw else if Value = 'Japanese' then Result := iso639_ja else if Value = 'Yiddish' then Result := iso639_ji else if Value = 'Javanese' then Result := iso639_jw else if Value = 'Georgian' then Result := iso639_ka else if Value = 'Kazakh' then Result := iso639_kk else if Value = 'Greenlandic' then Result := iso639_kl else if Value = 'Cambodian' then Result := iso639_km else if Value = 'Kannada' then Result := iso639_kn else if Value = 'Korean' then Result := iso639_ko else if Value = 'Kashmiri' then Result := iso639_ks else if Value = 'Kurdish' then Result := iso639_ku else if Value = 'Kirghiz' then Result := iso639_ky else if Value = 'Latin' then Result := iso639_la else if Value = 'Lingala' then Result := iso639_ln else if Value = 'Laothian' then Result := iso639_lo else if Value = 'Lithuanian' then Result := iso639_lt else if Value = 'Latvian' then Result := iso639_lv else if Value = 'Lettish' then Result := iso639_lv else if Value = 'Malagasy' then Result := iso639_mg else if Value = 'Maori' then Result := iso639_mi else if Value = 'Macedonian' then Result := iso639_mk else if Value = 'Malayalam' then Result := iso639_ml else if Value = 'Mongolian' then Result := iso639_mn else if Value = 'Moldavian' then Result := iso639_mo else if Value = 'Marathi' then Result := iso639_mr else if Value = 'Malay' then Result := iso639_ms else if Value = 'Maltese' then Result := iso639_mt else if Value = 'Burmese' then Result := iso639_my else if Value = 'Nauru' then Result := iso639_na else if Value = 'Nepali' then Result := iso639_ne else if Value = 'Dutch' then Result := iso639_nl else if Value = 'Norwegian' then Result := iso639_no else if Value = 'Occitan' then Result := iso639_oc else if Value = 'Afan' then Result := iso639_om else if Value = 'Oromo' then Result := iso639_om else if Value = 'Oriya' then Result := iso639_or else if Value = 'Punjabi' then Result := iso639_pa else if Value = 'Polish' then Result := iso639_pl else if Value = 'Pashto' then Result := iso639_ps else if Value = 'Pushto' then Result := iso639_ps else if Value = 'Portuguese' then Result := iso639_pt else if Value = 'Quechua' then Result := iso639_qu else if Value = 'Rhaeto-Romance' then Result := iso639_rm else if Value = 'Kirundi' then Result := iso639_rn else if Value = 'Romanian' then Result := iso639_ro else if Value = 'Russian' then Result := iso639_ru else if Value = 'Kinyarwanda' then Result := iso639_rw else if Value = 'Sanskrit' then Result := iso639_sa else if Value = 'Sindhi' then Result := iso639_sd else if Value = 'Sangro' then Result := iso639_sg else if Value = 'Serbo-Croatian' then Result := iso639_sh else if Value = 'Singhalese' then Result := iso639_si else if Value = 'Slovak' then Result := iso639_sk else if Value = 'Slovenian' then Result := iso639_sl else if Value = 'Samoan' then Result := iso639_sm else if Value = 'Shona' then Result := iso639_sn else if Value = 'Somali' then Result := iso639_so else if Value = 'Albanian' then Result := iso639_sq else if Value = 'Serbian' then Result := iso639_sr else if Value = 'Siswati' then Result := iso639_ss else if Value = 'Sesotho' then Result := iso639_st else if Value = 'Sundanese' then Result := iso639_su else if Value = 'Swedish' then Result := iso639_sv else if Value = 'Swahili' then Result := iso639_sw else if Value = 'Tamil' then Result := iso639_ta else if Value = 'Tegulu' then Result := iso639_te else if Value = 'Tajik' then Result := iso639_tg else if Value = 'Thai' then Result := iso639_th else if Value = 'Tigrinya' then Result := iso639_ti else if Value = 'Turkmen' then Result := iso639_tk else if Value = 'Tagalog' then Result := iso639_tl else if Value = 'Setswana' then Result := iso639_tn else if Value = 'Tonga' then Result := iso639_to else if Value = 'Turkish' then Result := iso639_tr else if Value = 'Tsonga' then Result := iso639_ts else if Value = 'Tatar' then Result := iso639_tt else if Value = 'Twi' then Result := iso639_tw else if Value = 'Ukrainian' then Result := iso639_uk else if Value = 'Urdu' then Result := iso639_ur else if Value = 'Uzbek' then Result := iso639_uz else if Value = 'Vietnamese' then Result := iso639_vi else if Value = 'Volapuk' then Result := iso639_vo else if Value = 'Wolof' then Result := iso639_wo else if Value = 'Xhosa' then Result := iso639_xh else if Value = 'Yoruba' then Result := iso639_yo else if Value = 'Chinese' then Result := iso639_zh else if Value = 'Zulu' then Result := iso639_zu else raise EConvertError.Create('Invalid ISO 639 language name'); end; procedure TIso639Info.setNameLanguage(const Value: TIso639LanguageCode); begin if not (Value in FSupportedLanguages) then raise EConvertError.Create('Language not supported'); end; {$IFDEF NEXTGEN} function TIso639Info.symbolToCode(const Value: string): TIso639LanguageCode; {$ELSE !NEXTGEN} function TIso639Info.symbolToCode(const Value: WideString): TIso639LanguageCode; {$ENDIF NEXTGEN} begin if Value = 'aa' then Result := iso639_aa // Afar else if Value = 'ab' then Result := iso639_ab // Abkhazian else if Value = 'af' then Result := iso639_af // Afrikaans else if Value = 'am' then Result := iso639_am // Amharic else if Value = 'ar' then Result := iso639_ar // Arabic else if Value = 'as' then Result := iso639_as // Assamese else if Value = 'ay' then Result := iso639_ay // Aymara else if Value = 'az' then Result := iso639_az // Azerbaijani else if Value = 'ba' then Result := iso639_ba // Bashkir else if Value = 'be' then Result := iso639_be // Byelorussian else if Value = 'bg' then Result := iso639_bg // Bulgarian else if Value = 'bh' then Result := iso639_bh // Bihari else if Value = 'bi' then Result := iso639_bi // Bislama else if Value = 'bn' then Result := iso639_bn // Bengali; Bangla else if Value = 'bo' then Result := iso639_bo // Tibetan else if Value = 'br' then Result := iso639_br // Breton else if Value = 'ca' then Result := iso639_ca // Catalan else if Value = 'co' then Result := iso639_co // Corsican else if Value = 'cs' then Result := iso639_cs // Czech else if Value = 'cy' then Result := iso639_cy // Welsh else if Value = 'da' then Result := iso639_da // Danish else if Value = 'de' then Result := iso639_de // German else if Value = 'dz' then Result := iso639_dz // Bhutani else if Value = 'el' then Result := iso639_el // Greek else if Value = 'en' then Result := iso639_en // English else if Value = 'eo' then Result := iso639_eo // Esperanto else if Value = 'es' then Result := iso639_es // Spanish else if Value = 'et' then Result := iso639_et // Estonian else if Value = 'eu' then Result := iso639_eu // Basque else if Value = 'fa' then Result := iso639_fa // Persian else if Value = 'fi' then Result := iso639_fi // Finnish else if Value = 'fj' then Result := iso639_fj // Fiji else if Value = 'fo' then Result := iso639_fo // Faeroese else if Value = 'fr' then Result := iso639_fr // French else if Value = 'fy' then Result := iso639_fy // Frisian else if Value = 'ga' then Result := iso639_ga // Irish else if Value = 'gd' then Result := iso639_gd // Scots Gaelic else if Value = 'gl' then Result := iso639_gl // Galician else if Value = 'gn' then Result := iso639_gn // Guarani else if Value = 'gu' then Result := iso639_gu // Gujarati else if Value = 'ha' then Result := iso639_ha // Hausa else if Value = 'hi' then Result := iso639_hi // Hindi else if Value = 'hr' then Result := iso639_hr // Croatian else if Value = 'hu' then Result := iso639_hu // Hungarian else if Value = 'hy' then Result := iso639_hy // Armenian else if Value = 'ia' then Result := iso639_ia // Interlingua else if Value = 'ie' then Result := iso639_ie // Interlingue else if Value = 'ik' then Result := iso639_ik // Inupiak else if Value = 'in' then Result := iso639_in // Indonesian else if Value = 'is' then Result := iso639_is // Icelandic else if Value = 'it' then Result := iso639_it // Italian else if Value = 'iw' then Result := iso639_iw // Hebrew else if Value = 'ja' then Result := iso639_ja // Japanese else if Value = 'ji' then Result := iso639_ji // Yiddish else if Value = 'jw' then Result := iso639_jw // Javanese else if Value = 'ka' then Result := iso639_ka // Georgian else if Value = 'kk' then Result := iso639_kk // Kazakh else if Value = 'kl' then Result := iso639_kl // Greenlandic else if Value = 'km' then Result := iso639_km // Cambodian else if Value = 'kn' then Result := iso639_kn // Kannada else if Value = 'ko' then Result := iso639_ko // Korean else if Value = 'ks' then Result := iso639_ks // Kashmiri else if Value = 'ku' then Result := iso639_ku // Kurdish else if Value = 'ky' then Result := iso639_ky // Kirghiz else if Value = 'la' then Result := iso639_la // Latin else if Value = 'ln' then Result := iso639_ln // Lingala else if Value = 'lo' then Result := iso639_lo // Laothian else if Value = 'lt' then Result := iso639_lt // Lithuanian else if Value = 'lv' then Result := iso639_lv // Latvian; Lettish else if Value = 'mg' then Result := iso639_mg // Malagasy else if Value = 'mi' then Result := iso639_mi // Maori else if Value = 'mk' then Result := iso639_mk // Macedonian else if Value = 'ml' then Result := iso639_ml // Malayalam else if Value = 'mn' then Result := iso639_mn // Mongolian else if Value = 'mo' then Result := iso639_mo // Moldavian else if Value = 'mr' then Result := iso639_mr // Marathi else if Value = 'ms' then Result := iso639_ms // Malay else if Value = 'mt' then Result := iso639_mt // Maltese else if Value = 'my' then Result := iso639_my // Burmese else if Value = 'na' then Result := iso639_na // Nauru else if Value = 'ne' then Result := iso639_ne // Nepali else if Value = 'nl' then Result := iso639_nl // Dutch else if Value = 'no' then Result := iso639_no // Norwegian else if Value = 'oc' then Result := iso639_oc // Occitan else if Value = 'om' then Result := iso639_om // Afan; Oromo else if Value = 'or' then Result := iso639_or // Oriya else if Value = 'pa' then Result := iso639_pa // Punjabi else if Value = 'pl' then Result := iso639_pl // Polish else if Value = 'ps' then Result := iso639_ps // Pashto; Pushto else if Value = 'pt' then Result := iso639_pt // Portuguese else if Value = 'qu' then Result := iso639_qu // Quechua else if Value = 'rm' then Result := iso639_rm // Rhaeto-Romance else if Value = 'rn' then Result := iso639_rn // Kirundi else if Value = 'ro' then Result := iso639_ro // Romanian else if Value = 'ru' then Result := iso639_ru // Russian else if Value = 'rw' then Result := iso639_rw // Kinyarwanda else if Value = 'sa' then Result := iso639_sa // Sanskrit else if Value = 'sd' then Result := iso639_sd // Sindhi else if Value = 'sg' then Result := iso639_sg // Sangro else if Value = 'sh' then Result := iso639_sh // Serbo-Croatian else if Value = 'si' then Result := iso639_si // Singhalese else if Value = 'sk' then Result := iso639_sk // Slovak else if Value = 'sl' then Result := iso639_sl // Slovenian else if Value = 'sm' then Result := iso639_sm // Samoan else if Value = 'sn' then Result := iso639_sn // Shona else if Value = 'so' then Result := iso639_so // Somali else if Value = 'sq' then Result := iso639_sq // Albanian else if Value = 'sr' then Result := iso639_sr // Serbian else if Value = 'ss' then Result := iso639_ss // Siswati else if Value = 'st' then Result := iso639_st // Sesotho else if Value = 'su' then Result := iso639_su // Sundanese else if Value = 'sv' then Result := iso639_sv // Swedish else if Value = 'sw' then Result := iso639_sw // Swahili else if Value = 'ta' then Result := iso639_ta // Tamil else if Value = 'te' then Result := iso639_te // Tegulu else if Value = 'tg' then Result := iso639_tg // Tajik else if Value = 'th' then Result := iso639_th // Thai else if Value = 'ti' then Result := iso639_ti // Tigrinya else if Value = 'tk' then Result := iso639_tk // Turkmen else if Value = 'tl' then Result := iso639_tl // Tagalog else if Value = 'tn' then Result := iso639_tn // Setswana else if Value = 'to' then Result := iso639_to // Tonga else if Value = 'tr' then Result := iso639_tr // Turkish else if Value = 'ts' then Result := iso639_ts // Tsonga else if Value = 'tt' then Result := iso639_tt // Tatar else if Value = 'tw' then Result := iso639_tw // Twi else if Value = 'uk' then Result := iso639_uk // Ukrainian else if Value = 'ur' then Result := iso639_ur // Urdu else if Value = 'uz' then Result := iso639_uz // Uzbek else if Value = 'vi' then Result := iso639_vi // Vietnamese else if Value = 'vo' then Result := iso639_vo // Volapuk else if Value = 'wo' then Result := iso639_wo // Wolof else if Value = 'xh' then Result := iso639_xh // Xhosa else if Value = 'yo' then Result := iso639_yo // Yoruba else if Value = 'zh' then Result := iso639_zh // Chinese else if Value = 'zu' then Result := iso639_zu // Zulu else raise EConvertError.Create('Invalid ISO 639 language symbol'); end; end.
{*******************************************************} { } { Turbo Pascal Runtime Library } { ShortString Handling Unit } { } { Copyright (C) 1990,92 Borland International } { } {*******************************************************} unit Strings; interface const EmptyStr: ShortString = ''; NullStr: PShortString = @EmptyStr; function IIF(B: Boolean; S1, S2: ShortString): ShortString; function SIsNumber(S: ShortString): Boolean; function SIsLatin(S: ShortString): Boolean; function StringCodeCode(S: ShortString; FirstChar: Byte): ShortString; function StringDeCodeCode(S: ShortString; FirstChar: Byte): ShortString; procedure BufWin95(P: PChar; W: Word); procedure UnBufWin95(P: PChar; W: Word); function WIN95(S: ShortString): ShortString; function UnWIN95(S: ShortString): ShortString; function RToL(S: ShortString): ShortString; function BILayout(S: ShortString): ShortString; function StrLen(Str: PChar): Integer; function SCPad(S: ShortString; Width: Byte; FillChar: Char): ShortString; { SRPad pads S from right with an adequate number of FillChars } { while ensuring that the length of the resulting ShortString is not } { greater than Width. If the initial length of the ShortString is } { equal to or greater than Width S is output intact. } function SRPad(S: ShortString; Width: Byte; FillChar: Char): ShortString; { SRPad pads S from left with an adequate number of FillChars } { while ensuring that the length of the resulting ShortString is not } { greater than Width. If the initial length of the ShortString is } { equal to or greater than Width S is output intact. } function SLPad(S: ShortString; Width: Byte; FillChar: Char): ShortString; { SReplicate concatenates the character C Count times and } { outputs the resulting ShortString. } function SReplicate(C : Char; Count: Byte): ShortString; function SConvert(S: ShortString; C : Char; R : Char): ShortString; { SLen returns the length of the ShortString S. } function SUpper(S: ShortString): ShortString; { Returns the passed ShortString with all characters lowercased. } function SLower(S: ShortString): ShortString; function SReverse(S: ShortString): ShortString; { Returns true if the first Count characters of the two passed } { strings are equal, false otherwise. It is case sensitive. } function SIsBlank(S: ShortString): Boolean; function SRTrim(S: ShortString): ShortString; function SLTrim(S: ShortString): ShortString; function SAllTrim(S: ShortString): ShortString; function Delimit(S: ShortString): ShortString; function UnDelimit(S: ShortString): ShortString; function WNToA(N: LongInt): ShortString; function StringCode(S: ShortString): ShortString; function StringDeCode(S: ShortString): ShortString; procedure AssignStr( var P: PShortString; const S: Shortstring ); procedure DisposeStr( P: PShortString); function NewStr( S: ShortString):PShortString; function SStripS(S : String; C: string): String; function SStrip(S : ShortString; C: Char): ShortString; function Win98(S: String): String; function MakeNewID : string; function DateRev( DateStr : string) : string; procedure InitConstUChar; implementation uses Fsiconst, SysUtils, windows; function DateRev( DateStr : string) : string; function ReverseDate(S: String): String; var C: Integer; begin Result := ''; C := Pos('/', S); while C > 0 do begin Result := '/'+Copy(S, 1, C-1)+Result; S := Copy(S, C+1, Length(S)); C := Pos('/', S); end; Result := S+Result; end; var DateStrLen, Counter, F, C: Integer; begin if (Pos( '/', DateStr) = 0) then begin Result := DateStr; exit; end; DateStrLen := Length(DateStr); Counter := 1; F := 0; Result := ''; while Counter <= (DateStrLen+1) do begin if F = 0 then begin if DateStr[Counter] in ['0'..'9'] then F := Counter; end else if (F <> 0) and ((Counter > DateStrLen) or not (DateStr[Counter] in ['0'..'9','/'])) then begin if Pos('/', Copy(DateStr, F, Counter-F)) > 0 then begin DateStr := Copy(DateStr, 1, F-1)+ReverseDate(Copy(DateStr, F, Counter-F))+ Copy(DateStr, Counter, DateStrLen); end; F := 0; end; Inc(Counter); end; Result := DateStr; end; function MakeNewID : string; var iNow : Integer; rNo : string; begin iNow := GetTickCount; rNo := IntToStr(Random(99999)); Result := '9' + IntToStr(iNow) + rNo; Result := Copy(Result, 1, 12); end; procedure InitConstUChar; const //#237, #223 ss2000 : array[1..2] of char=('ي', 'ك'); uss2000: array[1..2] of char=(#204, #169); wss2000: array[1..2] of char=(#237, #223); ss98 : array[1..2] of char=('ي', 'ك'); wuss98 : array[1..2] of char=(#0, #0); wss98 : array[1..2] of char=('ي', 'ك'); var S: String; C: array[0..3] of char; W: PWideChar; begin if wuss98[1] = #0 then begin W := @C; S := ss2000[1]; StringToWideChar(S, W, 2); // wuss98[1] := c[0]; S := WideCharToString(W); // ss98[1] := S[1]; S := ss2000[2]; StringToWideChar(S, W, 2); // wuss98[2] := c[0]; S := WideCharToString(W); // ss98[2] := S[1]; c[0] := uss2000[1]; //c[1] := #6; c[2] := #0; S := WideCharToString(W); // wss2000[1] := S[1]; c[0] := uss2000[2]; //c[1] := #6; c[2] := #0; S := WideCharToString(W); // wss2000[2] := S[1]; c[0] := wuss98[1]; //c[1] := #6; c[2] := #0; S := WideCharToString(W); // wss98[1] := S[1]; c[0] := wuss98[2]; //c[1] := #6; c[2] := #0; S := WideCharToString(W); // wss98[2] := S[1]; w := nil; end; end; function Win98(S: String): String; var L: Integer; begin Result := S; //if wuss98[1] = #0 then InitConstUChar; //if (wss2000[1] = ss2000[1]) and (wss2000[2] = ss2000[2]) then Exit; if (Win32Platform <> VER_PLATFORM_WIN32_WINDOWS) then exit; L := Length(Result); while L > 0 do begin {if (wss2000[1] <> ss2000[1]) and (Result[L] = wss2000[1]) then Result[L] := ss2000[1] else if (wss2000[2] <> ss2000[2]) and (Result[L] = wss2000[2]) then Result[L] := ss2000[2];} if Result[L] = #95 then Result[L] := #237; Dec(L); end; end; function SStripS(S : String; C: String): String; begin while Pos(C, S) > 0 do Delete(S, Pos(C, S), Length(C)); Result := S; end; function SStrip(S : ShortString; C: Char): ShortString; begin while Pos(C, S) > 0 do Delete(S, Pos(C, S), 1); Result := S; end; procedure DisposeStr(P: PShortString); begin if P = Strings.NullStr then exit; if P <> nil then FreeMem(P, Length(P^)+1); {P := Strings.NullStr;} end; function NewStr( S: ShortString):PShortString; begin {if S = '' then Result := @Strings.NullStr;} if S = '' then begin Result := nil; exit; end; GetMem(Result, Length(S)+1); Result^ := S; end; procedure AssignStr( var P: PShortString; const S: Shortstring ); begin DisposeStr(P); if S = '' then P := NullStr else P := NewStr(S); end; function SIsNumber(S: ShortString): Boolean; var I: Integer; begin Result := False; for I := 1 to Length(S) do if S[I] in ['0'..'9','.'] then begin Result := True; Exit; end; end; function SIsLatin(S: ShortString): Boolean; var I: Integer; begin Result := True; for I := 1 to Length(S) do if S[I] > #127 then begin Result := False; Exit; end; end; function StringCodeCode(S: ShortString; FirstChar: Byte): ShortString; const IsRunRandomize: Boolean=False; var I, J: Integer; B: Boolean; begin if not IsRunRandomize then begin // IsRunRandomize := True; Randomize; end; if Length(S) > 12 then I := Random(3)+ 1 else if Length(S) > 6 then I := Random(5)+ 1 else if Length(S) > 3 then I := Random(6)+ 1 else I := Random(8)+ 1; if (I + Length(S)) < 5 then I := 5 - Length(S); J := I; B := False; while I > 0 do begin if B then S := Char(I+77) + S else S := S+Char(I+77); B := not B; Dec(I); end; Result := '$'+Char(J+FirstChar)+StringCode(S); end; function StringDeCodeCode(S: ShortString; FirstChar: Byte): ShortString; var I, J: Integer; B: Boolean; begin Result := S; if (Length(S) <= 2) or (S[1] <> '$') then Exit; I := Byte(S[2]) - FirstChar; S := StringDeCode(Copy(S,3,255)); B := False; while I > 0 do begin if B then S := Copy(S,2,255) else Dec(Byte(S[0])); B := not B; Dec(I); end; Result := S; end; const FarsiCodes:String[60]= {#129#141#142#144#161#171#183#186#187+ #191#193#194#195#196#197+ #198#199#200#201#202#203#204#205#206#207+ #208#209#210#211#212#213#214#215#216#217+ #218#219#220#221#222#223#225#227+ #228#229#230#236#237+ #240#245#246#247#248;} #129#141#142#144#161#171#186#187+ #191#193#194#195#196#197+ #198#199#200#201#202#203#204#205#206#207+ #208#209#210#211#212#213#214#215#216#217+ #218#219#220#221#222#223#225#227+ #228#229#230#236+ #240#245#246#247#248; LatinCodes:String[100]='01234~!@#$%^'+'NOPQRSTUVWXYZABCDEFGHIJKLM'+ 'nopqrstuvwxyzabcdefghijklm'+'&*()+-=56789'; function StringCode(S: ShortString): ShortString; var I: Integer; B: Integer; begin Result := ''; for I := 1 to Length(S) do begin if S[I] > #127 then begin B := Pos(S[I], FarsiCodes); if B > 0 then begin Dec(B); B := ((B+I) mod Length(FarsiCodes)) + 1; Result := Result+FarsiCodes[B]; end else Result := Result+S[I]; end else begin B := Pos(S[I], LatinCodes); if B > 0 then begin Dec(B); B := ((B+I) mod Length(LatinCodes)) + 1; Result := Result+LatinCodes[B]; end else Result := Result+S[I]; end; end; end; function StringDeCode(S: ShortString): ShortString; var I: Integer; B: Integer; begin Result := ''; for I := 1 to Length(S) do begin if S[I] > #127 then begin B := Pos(S[I], FarsiCodes); if B > 0 then begin Dec(B); B := (B-I); while B < 0 do Inc(B, Length(FarsiCodes)); B := (B mod Length(FarsiCodes)) + 1; Result := Result+FarsiCodes[B]; end else Result := Result+S[I]; end else begin B := Pos(S[I], LatinCodes); if B > 0 then begin Dec(B); B := (B-I); while B < 0 do Inc(B, Length(LatinCodes)); B := (B mod Length(LatinCodes)) + 1; Result := Result+LatinCodes[B]; end else Result := Result+S[I]; end; end; end; function WIN95(S: ShortString): ShortString; var I: Integer; begin Result := S; if IsWin95 then for I := 1 to Length(Result) do if Result[I] = #236 then Result[I] := #237; end; function UnWIN95(S: ShortString): ShortString; var I: Integer; begin Result := S; {if IsWin95 then for I := 1 to Length(Result) do if Result[I] = #237 then Result[I] := #236;} end; procedure BufWin95(P: PChar; W: Word); begin if IsWin95 then while W > 0 do begin if (P+W-1)^ = #236 then (P+W-1)^ := #237; Dec(W); end; end; procedure UnBufWin95(P: PChar; W: Word); begin {if IsWin95 then while W > 0 do begin if (P+W-1)^ = #237 then (P+W-1)^ := #236; Dec(W); end;} end; {$W-} {$W+} function StrLen(Str: PChar): Integer; begin Result := SysUtils.StrLen(Str); end; function StrNew(Str: PChar): PChar; var L: Word; P: PChar; begin StrNew := nil; if (Str <> nil) and (Str^ <> #0) then begin L := SysUtils.StrLen(Str) + 1; GetMem(P, L); if P <> nil then StrNew := StrMove(P, Str, L); end; end; procedure StrDispose(Str: PChar); begin if Str <> nil then FreeMem(Str, StrLen(Str) + 1); end; function SCPad(S: ShortString; Width: Byte; FillChar: Char): ShortString; var B: Boolean; begin B := False; while Length(S) < Width do begin if B then S := S + FillChar else S := FillChar + S; B := not B; end; Result := S; end; function SRPad(S: ShortString; Width:Byte; FillChar: Char): ShortString; begin while Length(S) < Width do S := S + FillChar; Result := S; end; function SLPad(S: ShortString; Width: Byte; FillChar: Char): ShortString; begin while Length(S) < Width do S := FillChar + S; Result := S; end; function SConvert(S: ShortString; C : Char; R : Char): ShortString; var I: Integer; begin I := 1; for I := 1 to Length(S) do if S[I] = C then S[I] := R; Result := S; end; function SReplicate(C : Char; Count: Byte): ShortString; begin Result := ''; while Length(Result) < Count do Result := Result + C; end; function SUpper(S: ShortString): ShortString; begin Result := UpperCase(S); end; function SReverse(S: ShortString): ShortString; var I: Integer; begin Result := ''; for I := 1 to Length(S) do Result := Result + S[Length(S)- I+1] end; function SLower(S: ShortString): ShortString; begin Result := LowerCase(S); end; function SIsBlank(S: ShortString): Boolean; begin Result := S = ''; end; function SRTrim(S: ShortString): ShortString; begin while S[Length(S)] = #32 do Dec(Byte(S[0])); Result := S; end; function SLTrim(S: ShortString): ShortString; begin while (Length(S) > 0) and (S[1] = #32) do S := Copy(S, 2, Length(S) -1 ); Result := S; end; function SAllTrim(S: ShortString): ShortString; begin Result := SLTrim(SRtrim(S)); end; function Delimit(S: ShortString): ShortString; var sResult: ShortString; I: Integer; L: Byte; begin sResult := ''; L := Length(S); for I := Length(S) downto 1 do if ((L - I) mod 3 <> 0) or (I = L) then sResult := S[I] + '' + sResult else sResult := S[I] + ThousandSeparator + sResult; Delimit := sResult; end; function UnDelimit(S: ShortString): ShortString; begin while Pos(ThousandSeparator, S) > 0 do Delete(S, Pos(ThousandSeparator, S), 1); UnDelimit := S; end; function AdjustFileNameLen(FileName: ShortString; MaxLen: Integer): ShortString; begin if (Length(FileName) > MaxLen) then begin FileName := Copy(FileName, 1, 3) + '...' + Copy(FileName, 3 + Pos('\',Copy(FileName,4,Length(FileName))), Length(FileName)); while (Length(FileName) > MaxLen) Do begin if Pos('\',Copy(FileName,8,Length(FileName))) = 0 then begin AdjustFileNameLen := Copy(FileName, 8, Length(FileName)); Exit; end; FileName := Copy(FileName, 1,3)+Copy(FileName,8,Length(FileName)); FileName := Copy(FileName, 1,3)+'...'+ Copy(FileName, 3 + Pos('\',Copy(FileName,4,Length(FileName))), Length(FileName)); end; end; AdjustFileNameLen := FileName; end; function IIF(B: Boolean; S1, S2: ShortString): ShortString; begin if B then IIF := S1 else IIF := S2; end; function WNToA(N: LongInt): ShortString; var Strs: array[0..3] of ShortString; Vals: array[0..3] of Integer; Code: Integer; I: Integer; function Ones(C: Char): ShortString; begin case C of '0': Ones := ''; '1': Ones := 'يك'; '2': Ones := 'دو'; '3': Ones := 'سه'; '4': Ones := 'چهار'; '5': Ones := 'پنج'; '6': Ones := 'شش'; '7': Ones := 'هفت'; '8': Ones := 'هشت'; '9': Ones := 'نه'; else Result := ''; end; Result := Result + ' '; end; function TenOnes(C: Char): ShortString; begin case C of '1': TenOnes := 'يازده'; '2': TenOnes := 'دوازده'; '3': TenOnes := 'سيزده'; '4': TenOnes := 'چهارده'; '5': TenOnes := 'پانزده'; '6': TenOnes := 'شانزده'; '7': TenOnes := 'هفده'; '8': TenOnes := 'هيجده'; '9': TenOnes := 'نوزده'; else Result := ''; end; Result := Result + ' '; end; function Tens(C: Char): ShortString; begin case C of '0': Tens := ''; '2': Tens := 'بيست'; '3': Tens := 'سي'; '4': Tens := 'چهل'; '5': Tens := 'پنجاه'; '6': Tens := 'شصت'; '7': Tens := 'هفتاد'; '8': Tens := 'هشتاد'; '9': Tens := 'نود'; else Result := ''; end; Result := Result + ' '; end; function Hundreds(C: Char): ShortString; begin case C of '1': Hundreds := 'يكصد'; '2': Hundreds := 'دويست'; '3': Hundreds := 'سيصد'; '4': Hundreds := 'چهارصد'; '5': Hundreds := 'پانصد'; '6': Hundreds := 'ششصد'; '7': Hundreds := 'هفتصد'; '8': Hundreds := 'هشتصد'; '9': Hundreds := 'نهصد'; else Result := ''; end; Result := Result + ' '; end; function DoNToA(S: ShortString): ShortString; begin if S[1] = '0' then S := Copy(S, 2, 2); if S[1] = '0' then S := Copy(S, 2, 1); case Length(S) of 1: Result := Ones(S[1]); 2: if (S[1] = '1') and (S[2] = '0') then Result := 'ده ' else if S[1] = '1' then Result := TenOnes(S[2]) else begin Result := Tens(S[1]); if S[2] <> '0' then Result := SRtrim(Result) + ' و ' + Ones(S[2]); end; 3: if (S[2]='0') and (S[3]='0') then Result := Hundreds(S[1]) else begin Result := Hundreds(S[1]); if (S[2] = '1') and (S[3] = '0') then Result := SRtrim(Result)+' و ده ' else if S[2] = '1' then Result := SRtrim(Result)+ ' و ' + TenOnes(S[3]) else begin if S[2] <> '0' then Result := SRtrim(Result) + ' و ' + Tens(S[2]); if S[3] <> '0' then Result := SRtrim(Result) + ' و ' + Ones(S[3]); end; end; else Result := ''; end; end; var S: ShortString; begin Result := ''; Str(Abs(N):12, S); if SIsBlank(S) then begin Result := ' صفر'; Exit; end; for I := 0 to 3 do begin Strs[I] := SLTrim(Copy(S, 12 - ((I+1) * 3) +1, 3)); Val(Strs[I], Vals[I], Code); end; if (Strs[0] = '') and (Strs[1] = '') and (Strs[2] = '') and (Strs[3] = '') then Exit; if (Strs[0] <> '') and (Strs[1] <> '') and (Strs[2] <> '') and (Strs[3] <> '') then Result := DoNToA(Strs[3]) + IIF(Vals[3] = 0, '', 'ميليارد') + IIF(Vals[2] = 0, '', ' و ') + DoNToA(Strs[2]) + IIF(Vals[2] = 0, '', 'ميليون') + IIF(Vals[1] = 0, '', ' و ') + DoNToA(Strs[1]) + IIF(Vals[1] = 0, '', 'هزار ') + IIF(Vals[0] = 0, '', ' و ') + DoNToA(Strs[0]) else if (Strs[0] <> '') and (Strs[1] <> '') and (Strs[2] <> '') and (Strs[3] = '') then Result := DoNToA(Strs[2])+ IIF(Vals[2] = 0, '', 'ميليون') + IIF(Vals[1] = 0, '', ' و ') + DoNToA(Strs[1]) + IIF(Vals[1] = 0, '', 'هزار') + IIF(Vals[0] = 0, '', ' و ') + DoNToA(Strs[0]) else if (Strs[0] <> '') and (Strs[1] <> '') and (Strs[2] = '') and (Strs[3] = '') then Result := DoNToA(Strs[1])+ IIF(Vals[1] = 0, '', 'هزار') + IIF(Vals[0] = 0, '', ' و ') + DoNToA(Strs[0]) else if (Strs[0] <> '') and (Strs[1] = '') and (Strs[2] = '') and (Strs[3] = '') then Result := DoNToA(Strs[0]); end; function BILayout(S: ShortString): ShortString; const LatinNumbers = [#48..#57]; LatinAlphabet = [#65..#90,#97..#122]; FarsiAlphabet = [#129,#141,#142,#144,#194..#255,#186,#183,#161]-[#215,#247]; SpecialChars = [#33..#47,#58..#64,#91..#96,#123..#127]; var FarsiState: Boolean; P, I, K,J: Integer; function GetMap(UpOnly: Boolean): Char; begin if not UpOnly then case S[I] of '{': Result := '}'; '}': Result := '{'; '<': Result := '>'; '>': Result := '<'; '(': Result := ')'; ')': Result := '('; '[': Result := '['; ']': Result := ']'; else Result := S[I]; end else Result := S[I]; end; begin Result := ''; if S = '' then Exit; P := 1; I := 1; FarsiState := True; while I <= Byte(S[0]) do begin if (S[I] in LatinAlphabet) then begin P := 1; K := I; while (K < Byte(S[0])) and not(S[K] in FarsiAlphabet) do Inc(K); while (K = 0) or ((K > I) and not(S[K] in (LatinAlphabet+LatinNumbers))) do Dec(K); while (I <= K) do begin System.Insert(GetMap(True),Result,P); Inc(I); Inc(P); end; end else begin K := Length(Result)+1; P := K; while (I <= Byte(S[0])) and not(S[I] in LatinAlphabet) do begin if not (S[I] in LatinNumbers+SpecialChars) then P := Length(Result)+1; System.Insert(GetMap(False),Result,P); Inc(I); end; {Result := Copy(Result, 1, K - 1)+ SReverse(Copy(Result, K, 255));} end; end; end; function RToL(S: ShortString): ShortString; const LatinNumbers = [#48..#57]; LatinAlphabet = [#65..#90,#97..#122]; FarsiAlphabet = [#158,#129,#141,#142,#144,#194..#255,#186,#183,#161]-[#215,#247]; SpecialChars = [#33..#47,#58..#64,#91..#96,#123..#127]; var FarsiState: Boolean; P, I, K,J: Integer; function GetMap(UpOnly: Boolean): Char; begin if not UpOnly then case S[I] of '{': Result := '}'; '}': Result := '{'; '<': Result := '>'; '>': Result := '<'; '(': Result := ')'; ')': Result := '('; '[': Result := '['; ']': Result := ']'; else Result := S[I]; end else Result := S[I]; end; begin Result := ''; if S = '' then Exit; S := #158 + S; P := 1; I := 1; FarsiState := False; while I <= Byte(S[0]) do begin if (S[I] in LatinAlphabet) then begin FarsiState := False; P := 1; K := I; while (K < Byte(S[0])) and not(S[K] in FarsiAlphabet) do Inc(K); while (K = 0) or ((K > I) and not(S[K] in (LatinAlphabet+LatinNumbers))) do Dec(K); while (I <= K) do begin System.Insert(S[I],Result,P); Inc(P); Inc(I); end; if (I <= Byte(S[0])) and (S[I] in SpecialChars) then begin {P := 1;} while (I <= Byte(S[0])) and not(S[I] in (FarsiAlphabet+LatinNumbers)) do begin System.Insert(GetMap(False),Result, P); Inc(I); end; end; end else begin FarsiState := False; P := 1; K := I; while (K < Byte(S[0])) and not(S[K] in LatinAlphabet) do Inc(K); while (K = 0) or ((K > I) and not(S[K] in (FarsiAlphabet+LatinNumbers))) do Dec(K); while (I <= K) do begin if S[I] in FarsiAlphabet then FarsiState := True; System.Insert(S[I],Result,P); Inc(I); Inc(P); end; if (I <= Byte(S[0])) and (S[I] in SpecialChars) then begin {if FarsiState then} P := 1; while (I <= Byte(S[0])) and not(S[I] in (FarsiAlphabet+LatinNumbers+LatinAlphabet)) do begin {if FarsiState then} System.Insert(GetMap(False),Result, P); {else begin System.Insert(GetMap(True),Result, P); Inc(P); end;} Inc(I); end; end; end; end; I := Pos(#158, Result); if (Length(Result) > I) and ((I > 0) and (Result[I+1] in FarsiAlphabet)) then Insert(#32, Result,I+1); end; end.
unit AConhecimentoTransporteSaida; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, Componentes1, ExtCtrls, PainelGradiente, StdCtrls, Buttons, UnDados, Grids, CGrades, ConstMsg, Constantes, FunData, FunString, Localizacao, DBGrids, UnDadosProduto, UnNotasFiscaisFor, UnDadosLocaliza, FunObjeto; type TRBDColunaGrade =(clNumNota,clNumSerieNota,clCodTransportadora,clNomTransportadora,clCodModelo,clNomModelo,clNumConhecimento,clDatConhecimento,clValConhecimento,clValBaseIcms,clValIcms,clValNaoTributado,clPesoFrete); TFConhecimentoTransporteSaida = class(TFormularioPermissao) PainelGradiente1: TPainelGradiente; PanelColor1: TPanelColor; Panel1: TPanelColor; BFechar: TBitBtn; BGravar: TBitBtn; BCancela: TBitBtn; Grade: TRBStringGridColor; Lmodelo: TLabel; ETransportadora: TRBEditLocaliza; ETipoDocumentoFiscal: TRBEditLocaliza; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BFecharClick(Sender: TObject); procedure BCancelaClick(Sender: TObject); procedure GradeDadosValidos(Sender: TObject; var VpaValidos: Boolean); procedure GradeGetEditMask(Sender: TObject; ACol, ARow: Integer; var Value: string); procedure GradeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure GradeKeyPress(Sender: TObject; var Key: Char); procedure GradeNovaLinha(Sender: TObject); procedure GradeMudouLinha(Sender: TObject; VpaLinhaAtual, VpaLinhaAnterior: Integer); procedure GradeSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure BGravarClick(Sender: TObject); procedure ETransportadoraRetorno(VpaColunas: TRBColunasLocaliza); procedure ETipoDocumentoFiscalRetorno(VpaColunas: TRBColunasLocaliza); private { Private declarations } VprAcao : boolean; VprDConhecimentoTransporte: TRBDConhecimentoTransporte; VprDNota: TRBDNotaFiscal; FunNotaFor : TFuncoesNFFor; VprConhecimento: TList; function RColunaGrade(VpaColuna : TRBDColunaGrade):Integer; function ExisteNota: Boolean; function ExisteSerieNota: Boolean; procedure CarTitulosGrade; procedure CarDClasse; public { Public declarations } function NovoConhecimento : boolean; end; var FConhecimentoTransporteSaida: TFConhecimentoTransporteSaida; implementation uses APrincipal, UnNotaFiscal, UnClientes; {$R *.DFM} { **************************************************************************** } procedure TFConhecimentoTransporteSaida.FormCreate(Sender: TObject); begin { abre tabelas } { chamar a rotina de atualização de menus } VprAcao := false; CarTitulosGrade; end; { *************************************************************************** } procedure TFConhecimentoTransporteSaida.GradeDadosValidos(Sender: TObject; var VpaValidos: Boolean); begin VpaValidos:= True; if not ExisteNota then begin VpaValidos:= False; Grade.Col:= RColunaGrade(clNumNota); aviso('NUMERO NOTA NAO PREENCHIDO!!!'#13'É necessário preencher um numero de nota fiscal.'); end else if not ExisteSerieNota then begin VpaValidos:= False; Grade.Col:= RColunaGrade(clNumSerieNota); aviso('NUMERO SERIE NAO PREENCHIDO!!!'#13'É necessário preencher um numero de serie.'); end else if not ETransportadora.AExisteCodigo(Grade.Cells[RColunaGrade(clCodTransportadora),Grade.ALinha]) then begin VpaValidos:= False; Grade.Col:= RColunaGrade(clCodTransportadora); aviso('TRANSPORTADORA NAO PREENCHIDA!!!'#13'É necessário preencher uma transportadora.'); end else if not ETipoDocumentoFiscal.AExisteCodigo(Grade.Cells[RColunaGrade(clCodModelo),Grade.ALinha]) then begin VpaValidos:= False; Grade.Col:= RColunaGrade(clCodModelo); aviso('MODELO DO DOCUMENTO NÃO PREEHCIDO!!!'#13'É necessário preencher o modelo do documento.'); end else if Grade.Cells[RColunaGrade(clNumConhecimento),Grade.ALinha] = '' then begin VpaValidos:= False; Grade.Col:= RColunaGrade(clNumConhecimento); aviso('NUMERO DO CONHECIMENTO NÃO PREENCHIDO!!!'#13'É necessário preencher o numero do conhecimento.'); end; if VpaValidos then begin CarDClasse; if VprDConhecimentoTransporte.DatConhecimento <= MontaData(1,1,1900) then begin aviso('DATA CONHECIMENTO INVÁLIDA!!!'#13'A data do conhecimento preenchida é inválida.'); Vpavalidos := false; Grade.Col := RColunaGrade(clDatConhecimento); end end; end; { *************************************************************************** } procedure TFConhecimentoTransporteSaida.GradeGetEditMask(Sender: TObject; ACol, ARow: Integer; var Value: string); begin if RColunaGrade(clDatConhecimento) = ACol then Value := FPrincipal.CorFoco.AMascaraData; end; { *************************************************************************** } procedure TFConhecimentoTransporteSaida.GradeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of 114: if RColunaGrade(clCodTransportadora) = Grade.AColuna then ETransportadora.AAbreLocalizacao else if RColunaGrade(clCodModelo) = Grade.AColuna then ETipoDocumentoFiscal.AAbreLocalizacao; end; end; { *************************************************************************** } procedure TFConhecimentoTransporteSaida.GradeKeyPress(Sender: TObject; var Key: Char); begin if (RColunaGrade(clValConhecimento) = Grade.AColuna) or (RColunaGrade(clValBaseIcms) = Grade.AColuna) or (RColunaGrade(clValIcms) = Grade.AColuna) or (RColunaGrade(clValNaoTributado) = Grade.AColuna) or (RColunaGrade(clPesoFrete) = Grade.AColuna) then begin if Key in [',','.'] then Key:= DecimalSeparator; end; end; { *************************************************************************** } procedure TFConhecimentoTransporteSaida.GradeMudouLinha(Sender: TObject; VpaLinhaAtual, VpaLinhaAnterior: Integer); begin if VprConhecimento.Count > 0 then VprDConhecimentoTransporte := TRBDConhecimentoTransporte(VprConhecimento.Items[VpaLinhaAtual-1]); end; { *************************************************************************** } procedure TFConhecimentoTransporteSaida.GradeNovaLinha(Sender: TObject); begin VprDConhecimentoTransporte := TRBDConhecimentoTransporte.cria; VprConhecimento.Add(VprDConhecimentoTransporte); end; { *************************************************************************** } procedure TFConhecimentoTransporteSaida.GradeSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); begin if Grade.AEstadoGrade in [egInsercao, egEdicao] then begin if Grade.AColuna <> ACol then begin if RColunaGrade(clNumNota) = Grade.AColuna then begin if not ExisteNota then begin Aviso('CÓDIGO DA NOTA FISCAL INVALIDA !!!'#13'É necessário informar o numero da nota fiscal.'); Grade.Col:= RColunaGrade(clNumNota); end; end else if RColunaGrade(clCodTransportadora) = Grade.AColuna then begin if not ETransportadora.AExisteCodigo(Grade.Cells[RColunaGrade(clCodTransportadora),Grade.ALinha]) then begin if not ETransportadora.AAbreLocalizacao then begin Aviso('CÓDIGO DA TRANSPORTADORA INVALIDO !!!'#13'É necessário informar o código da transportadora.'); Grade.Col:= RColunaGrade(clCodTransportadora); end; end; end else if RColunaGrade(clCodModelo) = Grade.AColuna then begin if not ETipoDocumentoFiscal.AExisteCodigo(Grade.Cells[RColunaGrade(clCodModelo),Grade.ALinha]) then begin if not ETipoDocumentoFiscal.AAbreLocalizacao then begin Aviso('CÓDIGO DO MODELO INVALIDO !!!'#13'É necessário informar o código do modelo.'); Grade.Col:= RColunaGrade(clCodModelo); end; end; end else if RColunaGrade(clNumConhecimento) = Grade.AColuna then begin if Grade.Cells[RColunaGrade(clNumConhecimento), Grade.ALinha] = '' then begin Aviso('NÚMERO DO CONHECIMENTO NÃO PREENCHIDO !!!'#13'É necessário informar o número do conhecimento.'); Grade.Col:= RColunaGrade(clNumConhecimento); end; end else if RColunaGrade(clNumSerieNota) = Grade.AColuna then begin if Grade.Cells[RColunaGrade(clNumSerieNota), Grade.ALinha] = '' then begin Aviso('NÚMERO DE SÉRIE NÃO PREENCHIDO !!!'#13'É necessário informar o número da série.'); Grade.Col:= RColunaGrade(clNumSerieNota); end else begin if not ExisteSerieNota then begin Aviso('SÉRIE DA NOTA FISCAL INVALIDA !!!'#13'É necessário informar o número da série.'); Grade.Col:= RColunaGrade(clNumSerieNota); end; end; end; end; end; end; { *************************************************************************** } function TFConhecimentoTransporteSaida.NovoConhecimento : boolean; begin FunNotaFor := TFuncoesNFFor.criar(self,FPrincipal.BaseDados); VprDNota:= TRBDNotaFiscal.cria; VprConhecimento:= TList.Create; VprDConhecimentoTransporte:= TRBDConhecimentoTransporte.Cria; Grade.ADados:= VprConhecimento; Grade.CarregaGrade; ShowModal; result := VprAcao; end; { *************************************************************************** } function TFConhecimentoTransporteSaida.RColunaGrade(VpaColuna: TRBDColunaGrade): Integer; begin case VpaColuna of clNumNota: result:= 1 ; clNumSerieNota: result:= 2; clCodTransportadora: result:= 3; clNomTransportadora: result:= 4; clCodModelo: result:= 5; clNomModelo: result:= 6; clNumConhecimento: result:= 7; clDatConhecimento: result:= 8; clValConhecimento: result:= 9; clValBaseIcms: result:= 10; clValIcms: result:= 11; clValNaoTributado: result:= 12; clPesoFrete: result:= 13; end; end; { *************************************************************************** } procedure TFConhecimentoTransporteSaida.BCancelaClick(Sender: TObject); begin close; end; { *************************************************************************** } procedure TFConhecimentoTransporteSaida.BFecharClick(Sender: TObject); begin close; end; procedure TFConhecimentoTransporteSaida.BGravarClick(Sender: TObject); var VpfResultado: String; begin VpfResultado:= FunNotaFor.GravaDConhecimentoTransporteNotaSaida(VprConhecimento); if VpfResultado <> '' then aviso(VpfResultado) else begin VprAcao := true; Close; end; end; { *************************************************************************** } procedure TFConhecimentoTransporteSaida.CarDClasse; begin VprDConhecimentoTransporte.NumNota:= StrToInt(Grade.Cells[RColunaGrade(clNumNota),Grade.ALinha]); VprDConhecimentoTransporte.NumSerieNota:= Grade.Cells[RColunaGrade(clNumSerieNota),Grade.ALinha]; VprDConhecimentoTransporte.CodTransportadora:= StrToInt(Grade.Cells[RColunaGrade(clCodTransportadora),Grade.ALinha]); VprDConhecimentoTransporte.CodFilial:= Varia.CodigoEmpFil; VprDConhecimentoTransporte.CodModeloDocumento:= Grade.Cells[RColunaGrade(clCodModelo),Grade.ALinha]; try VprDConhecimentoTransporte.DatConhecimento := StrToDate(Grade.Cells[RColunaGrade(clDatConhecimento),Grade.ALinha]) except VprDConhecimentoTransporte.DatConhecimento := MontaData(1,1,1900); end; VprDConhecimentoTransporte.NumTipoConhecimento:= 1; if Grade.Cells[RColunaGrade(clValConhecimento),Grade.ALinha] <> '' then VprDConhecimentoTransporte.ValConhecimento:= StrToFloat(DeletaChars(Grade.Cells[RColunaGrade(clValConhecimento),Grade.ALinha],'.')) else VprDConhecimentoTransporte.ValConhecimento:= 0; if Grade.Cells[RColunaGrade(clValBaseIcms),Grade.ALinha] <> '' then VprDConhecimentoTransporte.ValorBaseIcms:= StrToFloat(DeletaChars(Grade.Cells[RColunaGrade(clValBaseIcms),Grade.ALinha],'.')) else VprDConhecimentoTransporte.ValorBaseIcms:= 0; if Grade.Cells[RColunaGrade(clValIcms),Grade.ALinha] <> '' then VprDConhecimentoTransporte.ValorIcms:= StrToFloat(DeletaChars(Grade.Cells[RColunaGrade(clValIcms),Grade.ALinha],'.')) else VprDConhecimentoTransporte.ValorIcms:= 0; if Grade.Cells[RColunaGrade(clValNaoTributado),Grade.ALinha] <> '' then VprDConhecimentoTransporte.ValorNaoTributado:= StrToFloat(DeletaChars(Grade.Cells[RColunaGrade(clValNaoTributado),Grade.ALinha],'.')) else VprDConhecimentoTransporte.ValorNaoTributado:= 0; if Grade.Cells[RColunaGrade(clPesoFrete),Grade.ALinha] <> '' then VprDConhecimentoTransporte.PesoFrete:= StrToFloat(DeletaChars(Grade.Cells[RColunaGrade(clPesoFrete),Grade.ALinha],'.')) else VprDConhecimentoTransporte.PesoFrete:= 0; VprDConhecimentoTransporte.NumConhecimento:= StrToInt(Grade.Cells[RColunaGrade(clNumConhecimento),Grade.ALinha]); VprDConhecimentoTransporte.SeqNotaSaida:= FunNotaFiscal.RSeqNota(VprDConhecimentoTransporte.NumNota, VprDConhecimentoTransporte.CodFilial, VprDConhecimentoTransporte.NumSerieNota); end; { *************************************************************************** } procedure TFConhecimentoTransporteSaida.CarTitulosGrade; begin grade.Cells[RColunaGrade(clNumNota),0] := 'Numero Nota'; grade.Cells[RColunaGrade(clNumSerieNota),0] := 'Serie Nota'; grade.Cells[RColunaGrade(clCodTransportadora),0] := 'Codigo'; grade.Cells[RColunaGrade(clNomTransportadora),0] := 'Transportadora'; grade.Cells[RColunaGrade(clCodModelo),0] := 'Codigo'; grade.Cells[RColunaGrade(clNomModelo),0] := 'Modelo'; grade.Cells[RColunaGrade(clNumConhecimento),0] := 'Numero Conhecimento'; grade.Cells[RColunaGrade(clDatConhecimento),0] := 'Data Conhecimento'; grade.Cells[RColunaGrade(clValConhecimento),0] := 'Valor Conhecimento'; grade.Cells[RColunaGrade(clValBaseIcms),0] := 'Valor Base ICMS'; grade.Cells[RColunaGrade(clValIcms),0] := 'Valor ICMS'; grade.Cells[RColunaGrade(clValNaoTributado),0] := 'Valor Nao Tributado'; grade.Cells[RColunaGrade(clPesoFrete),0] := 'Peso Frete'; end; { ***************************************************************************} procedure TFConhecimentoTransporteSaida.ETipoDocumentoFiscalRetorno( VpaColunas: TRBColunasLocaliza); begin if VpaColunas[0].AValorRetorno <> '' then begin Grade.Cells[RColunaGrade(clNomModelo), Grade.ALinha]:= VpaColunas[1].AValorRetorno; Grade.Cells[RColunaGrade(clCodModelo), Grade.ALinha]:= ETipoDocumentoFiscal.Text; end else begin Grade.Cells[RColunaGrade(clNomModelo), Grade.ALinha]:= ''; Grade.Cells[RColunaGrade(clCodModelo), Grade.ALinha]:= ''; end; end; { ***************************************************************************} procedure TFConhecimentoTransporteSaida.ETransportadoraRetorno( VpaColunas: TRBColunasLocaliza); begin if VpaColunas[0].AValorRetorno <> '' then begin Grade.Cells[RColunaGrade(clNomTransportadora), Grade.ALinha]:= VpaColunas[1].AValorRetorno; Grade.Cells[RColunaGrade(clCodTransportadora), Grade.ALinha]:= ETransportadora.Text; end else begin Grade.Cells[RColunaGrade(clNomTransportadora), Grade.ALinha]:= ''; Grade.Cells[RColunaGrade(clCodTransportadora), Grade.ALinha]:= ''; end; end; { *************************************************************************** } function TFConhecimentoTransporteSaida.ExisteNota: Boolean; begin Result:= False; if Grade.Cells[RColunaGrade(clNumNota),Grade.ALinha] <> '' then begin Result:= FunNotaFiscal.ExisteNota(StrToInt(Grade.Cells[RColunaGrade(clNumNota),Grade.ALinha])); end; end; { *************************************************************************** } function TFConhecimentoTransporteSaida.ExisteSerieNota: Boolean; begin Result:= False; if Grade.Cells[RColunaGrade(clNumSerieNota),Grade.ALinha] <> '' then begin Result:= FunNotaFiscal.ExisteSerieNota(StrToInt(Grade.Cells[RColunaGrade(clNumNota),Grade.ALinha]), Grade.Cells[RColunaGrade(clNumSerieNota),Grade.ALinha]); end; end; { *************************************************************************** } procedure TFConhecimentoTransporteSaida.FormClose(Sender: TObject; var Action: TCloseAction); begin { fecha tabelas } { chamar a rotina de atualização de menus } FunNotaFor.Free; VprDNota.free; FreeTObjectsList(VprConhecimento); VprConhecimento.Free; Action := CaFree; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Ações Diversas )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} Initialization { *************** Registra a classe para evitar duplicidade ****************** } RegisterClasses([TFConhecimentoTransporteSaida]); end.
unit UPrincipal; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ExtCtrls, Buttons, Menus, ImgList, XPMan; type elem=string; ArvB=^No; No=record esq: ArvB; chave: Elem; dir: ArvB; alt: Integer; niv: Integer; end; type TFPrincipal = class(TForm) EdtValor: TEdit; Panel1: TPanel; Tela: TImage; BtEsquerda: TBitBtn; BtDireita: TBitBtn; BtCima: TBitBtn; BtBaixo: TBitBtn; MainMenu1: TMainMenu; Sobre1: TMenuItem; Novo1: TMenuItem; Novo2: TMenuItem; LbAltura: TLabel; BtInserir: TBitBtn; BtRemover: TBitBtn; BtConsultar: TBitBtn; Sair1: TMenuItem; XPManifest1: TXPManifest; LimparArvore: TButton; procedure BtInserirClick(Sender: TObject); procedure BtConsultarClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure BtRemoverClick(Sender: TObject); procedure BtDireitaClick(Sender: TObject); procedure BtEsquerdaClick(Sender: TObject); procedure BtCimaClick(Sender: TObject); procedure BtBaixoClick(Sender: TObject); procedure Novo2Click(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure Sobre1Click(Sender: TObject); procedure Sair1Click(Sender: TObject); procedure LimparArvoreClick(Sender: TObject); private { Private declarations } //Declarando procedimentos locais procedure Inserir(var t: ArvB; x: Elem); procedure Remover(out t: ArvB; x: integer); function RemoverMenorValor(out t: ArvB): ArvB; procedure Consulta(var t: ArvB; x: Elem); procedure Imprimir(var t: ArvB; nivel,linha: integer); procedure CalculaAltura(out t: ArvB); procedure CalculaNivel(out t: ArvB; Niv: integer); function BuscarFolha(x: String): Boolean; procedure Zerar; function ValidaEdit(Edit: TEdit): boolean; procedure LimparDesenho; procedure ChamaImpressao; procedure DesabilitaBotoes; procedure HabilitaBotoes; public { Public declarations } end; //Variáveis globais var t:ArvB; coluna,linha,alttotal,contfolha: integer; ListaFolha: Array [1..50] of String; EstrBinaria, Cheia, Completa: boolean; UltNivel: integer; Niv: integer; var FPrincipal: TFPrincipal; implementation uses USobre; {$R *.dfm} //Procedimento de Inserção na Árvore procedure TFPrincipal.inserir(var t: ArvB; x: Elem); begin //Se o no for nulo If t=nil Then Begin new(t); //Atribui valor de x para a chave do No t^.chave:=x; t^.esq:=nil; t^.dir:=nil; End Else If x=t^.chave Then MessageDlg('O elemento '+x+' já está na arvore!',mtinformation,[mbok],0) Else If strtoint(x)<strtoint(t^.chave) Then inserir(t^.esq,x) Else inserir(t^.dir,x); end; //Procedimento a busca de um elemento na Árvore procedure TFPrincipal.Consulta(var t: ArvB; x: Elem); begin If t=nil Then MessageDlg('O elemento '+x+' não foi encontrado!',mtWarning,[mbok],0) Else If x=t^.chave //Elemento encontrado no No atual Then MessageDlg('O elemento '+t^.chave+' foi encontrado!',mtinformation,[mbok],0) Else //Elemento encontrado numa das sub-arvores If x<t^.chave Then Begin Consulta(t^.esq, X); End Else Begin Consulta(t^.dir, X); End; end; procedure TFPrincipal.BtInserirClick(Sender: TObject); begin If not ValidaEdit(EdtValor) Then exit; //Se a tela não tiver visível, então fica visível If Tela.Visible=false Then Tela.Visible:=true; //Insere o No e reimprime a Árvore Inserir(t,EdtValor.Text); EdtValor.Clear; EdtValor.SetFocus; ChamaImpressao; LbAltura.Caption:='Altura da Árvore: '+inttostr(t^.alt); //Chama procedimento pra habilitar botões de seta HabilitaBotoes; end; procedure TFPrincipal.BtConsultarClick(Sender: TObject); begin If not ValidaEdit(EdtValor) Then exit; //Chama procedimento de consulta, passando a árvore //e o valor a ser consultado Consulta(t,EdtValor.text); end; //Procedimento de Impressão da Árvore na tela com Pos Ordem procedure TFPrincipal.Imprimir(var t: ArvB; nivel,linha: integer); var OldBkMode: integer; begin If t=nil Then exit; //Verificando Nos Folhas If (t^.esq=nil) and (t^.dir=nil) Then Begin If BuscarFolha(t^.chave)=false Then Begin ListaFolha[contfolha]:=t^.chave; Inc(contfolha,1); End; End; //Varre sub-arvore esquerda Imprimir(t^.esq,nivel-30,linha+30) ; //Varre sub-arvore direita Imprimir(t^.dir,nivel+30,linha+30) ; //Chama procedimento para calcular altura do No CalculaAltura(t); //Imprimi na tela (TImage) With Tela.Canvas do Begin Pen.Width:=2; //Imprimir linha //Se tiver filho esquerdo, entao aumenta a linha do pai pro filho esquerdo If t^.esq<>nil Then Begin MoveTo(nivel+15,linha+60); LineTo(nivel-20,linha+60); End; //Se tiver filho direito, então aumenta a linha do pai pro filho direito If t^.dir<>nil Then Begin MoveTo(nivel+40,linha+60); LineTo(nivel+15,linha+60); End; //Imprimir circulo Brush.Style:=bsSolid; Brush.Color:=clMoneyGreen; Ellipse(nivel,linha+30,nivel+30,linha+60); //Imprimir texto OldBkMode:=SetBkMode(Handle,TRANSPARENT); Font.Color:=clblue; TextOut(nivel+4,linha+30+8,t^.chave); End; end; procedure TFPrincipal.FormShow(Sender: TObject); begin //Inicializando variáveis ao abrir programa principal t:=nil; coluna:=230; linha:=0; LbAltura.Caption:=''; Zerar; end; procedure TFPrincipal.BtRemoverClick(Sender: TObject); begin If not ValidaEdit(EdtValor) Then exit; //Remove o No Remover(t,strtoint(EdtValor.text)); EdtValor.Clear; EdtValor.SetFocus; //Reimprime a arvore ChamaImpressao; //Atualiza Label com altura atual da arvore If T<>nil Then LbAltura.Caption:='Altura da Árvore: '+inttostr(t^.alt) Else LbAltura.Caption:=''; end; //Procedimento de Remoção na Árvore procedure TFPrincipal.Remover(out t: ArvB; x: integer); var temp: ArvB; begin If t=nil Then MessageDlg('O elemento '+inttostr(x)+' não foi encontrado para remoção!',mtinformation,[mbok],0) Else If x<strtoint(t^.chave) //Busca a esquerda Then Remover(t^.esq,x) Else If x>strtoint(t^.chave) //Busca a direita Then Remover(t^.dir,x) Else Begin temp:=t; //Existe somente um filho a direita If t^.esq=nil //Aponta para direita Then t:=t.dir Else //Existe somente um filho a esquerda If t^.dir=nil //Aponta para esquerda Then t:=t.esq Else Begin //O No possui dois filhos temp:=removerMenorValor(t^.dir); t^.chave:=temp^.chave; End; //Desaloca temp FreeMem(temp,SizeOf(ArvB)); End; End; //Funcao que retorna menor valor a ser removido function TFPrincipal.RemoverMenorValor(out t: ArvB): ArvB; var temp: ^ArvB; begin If t^.esq<>nil Then result:=RemoverMenorValor(t^.esq) Else Begin temp^:=t; t:=t.dir; result:=temp^; End; end; //Funcao para Limpar Árvore da Tela procedure TFPrincipal.LimparDesenho; begin With Tela.Canvas do Begin //Desenhando um Retângulo branco em toda a tela Brush.Color :=clWhite; Rectangle(0, 0, tela.width, tela.Height); End; end; procedure TFPrincipal.ChamaImpressao; begin //Limpar e depois imprimir LimparDesenho; Zerar; Niv:=1; CalculaNivel(t,Niv); Imprimir(t,coluna,linha); alttotal:=t^.alt; end; procedure TFPrincipal.BtDireitaClick(Sender: TObject); begin //Simula rolagem para direita coluna:=coluna-10; ChamaImpressao; end; procedure TFPrincipal.BtEsquerdaClick(Sender: TObject); begin //Simula rolagem para esquerda coluna:=coluna+10; ChamaImpressao; end; procedure TFPrincipal.BtCimaClick(Sender: TObject); begin //Simula rolagem para cima linha:=linha+10; ChamaImpressao; end; procedure TFPrincipal.BtBaixoClick(Sender: TObject); begin //Simula rolagem para baixo linha:=linha-10; ChamaImpressao; end; procedure TFPrincipal.Novo2Click(Sender: TObject); begin //Desaloca o nó t da memória utilizando a função FreeMen, //passando por parametro o tamanho(tipo) do No a ser desalocado FreeMem(t,SizeOf(ArvB)); t:=nil; coluna:=230; linha:=0; LimparDesenho; //Alterando propriedades dos objetos //para comecar uma nova árvore Tela.Visible:=false; EdtValor.Clear; EdtValor.SetFocus; LbAltura.Caption:=''; Zerar; //Chama procedimento pra desabilitar botoes de seta DesabilitaBotoes; end; //Funcao que faz a validação do valor digitado pelo usuário function TFPrincipal.ValidaEdit(Edit: TEdit): boolean; begin result:=false; //Tenta transformar de string para inteiro, se der //erro, retorna falso Try strtoint(Edit.Text); Except MessageDlg('Valor Inválido',mterror,[mbok],0); Edit.Clear; Edit.SetFocus; exit; End; result:=true; end; //Faz o calculo da altura do No e armazena no campo Alt do seu registro procedure TFPrincipal.CalculaAltura(out t: ArvB); var alte, altd: integer; begin If t^.esq<>nil Then alte:=t^.esq.alt Else alte:=0; If t^.dir<>nil Then altd:=t^.dir.alt Else altd:=0; If alte>altd Then t^.alt:=alte+1 Else t^.alt:=altd+1; end; procedure TFPrincipal.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin //Verifica se tecla digitada é uma seta pra //qualquer lado, se for, chama procedimento //do botao conforme seu lado If Key=VK_DOWN Then BtBaixo.OnClick(Sender) Else If Key=VK_UP Then BtCima.OnClick(Sender) Else If Key=VK_LEFT Then BtEsquerda.OnClick(Sender) Else If Key=VK_RIGHT Then BtDireita.OnClick(Sender); end; //Procedimento que desabilita botoes de seta procedure TFPrincipal.DesabilitaBotoes; begin BtEsquerda.Visible:=false; BtDireita.Visible:=false; BtCima.Visible:=false; BtBaixo.Visible:=false; end; procedure TFPrincipal.HabilitaBotoes; begin BtEsquerda.Visible:=true; BtDireita.Visible:=true; BtCima.Visible:=true; BtBaixo.Visible:=true; end; procedure TFPrincipal.Sobre1Click(Sender: TObject); begin FSobre.ShowModal; end; procedure TFPrincipal.Sair1Click(Sender: TObject); begin close; end; procedure TFPrincipal.Zerar; var cont: integer; begin For cont:=1 to 50 do ListaFolha[cont]:=''; EstrBinaria:=true; Cheia:=true; Completa:=true; UltNivel:=0; contfolha:=1; end; function TFPrincipal.BuscarFolha(x: String): boolean; var cont: integer; begin result:=false; For cont:=1 to 50 do Begin If x=ListaFolha[cont] Then Begin result:=true; exit; End; End; end; procedure TFPrincipal.CalculaNivel(out t: ArvB; Niv: integer); begin If t=nil Then exit; t^.niv:=niv; If t^.niv>UltNivel Then UltNivel:=t^.niv; //Varre sub-arvore esquerda CalculaNivel(t^.esq,Niv+1); //Varre sub-arvore direita CalculaNivel(t^.dir,Niv+1); end; procedure TFPrincipal.LimparArvoreClick(Sender: TObject); begin FreeMem(t,SizeOf(ArvB)); t:=nil; coluna:=230; linha:=0; LimparDesenho; //Alterando propriedades dos objetos //para comecar uma nova árvore Tela.Visible:=false; EdtValor.Clear; EdtValor.SetFocus; LbAltura.Caption:=''; Zerar; showmessage('Árvore zerada com sucesso.'); end; end.
unit VrtecForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, MPlayer, ComCtrls, StdCtrls, Math, ExtCtrls, jvShape, VrtecConst, jpeg, Menus; type // sRazno: razne slike in zvoki (klovn-smeh, avto-brmbrm ...) TSection = (sLiki, sBarve, sZivali, sCrke, sFilmi, sText, sRazno); const SectionArray: array [TSection] of AnsiString = ('Liki', 'Barve', 'Zivali', 'Crke', 'Filmi', 'Text', 'Razno'); type TWay = (wUp, wDown); TForm1 = class(TForm) mPlay: TMediaPlayer; StatusBar1: TStatusBar; lCrka: TLabel; ColorBox1: TColorBox; Label1: TLabel; sShape: TShape; iImage: TImage; MainMenu1: TMainMenu; miZvok: TMenuItem; miPiskanje: TMenuItem; miGlasovi: TMenuItem; cbZivali: TComboBox; cbRazno: TComboBox; miShowSection: TMenuItem; miProperties: TMenuItem; miLoop: TMenuItem; miSection: TMenuItem; cbFilmi: TComboBox; procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ColorBox1Change(Sender: TObject); procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure miPiskanjeClick(Sender: TObject); procedure miGlasoviClick(Sender: TObject); procedure cbZivaliChange(Sender: TObject); procedure cbRaznoChange(Sender: TObject); procedure cbFilmiChange(Sender: TObject); procedure FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure mPlayNotify(Sender: TObject); private FSection: TSection; FTextStr: AnsiString; FLetter: TLabel; FShape: TjvShape; FShapeIndex: integer; FColorIndex: integer; FImage: TImage; FKeyPressCount: integer; FAnimalIndex: integer; FPiskanje: boolean; FGlasovi: boolean; FShowMovieCount: integer; procedure ChangeSection; procedure ChangeTextColor(Way: TWay); procedure ChangeFont(Way: TWay); procedure ChangeShape(Way: TWay); function GetRandPos(Ctrl: TControl): TRect; function GetRandColor: TColor; procedure Play(FileName: AnsiString); procedure Stop; { Private declarations } public { Public declarations } procedure ShowShape(Key: char); procedure ShowColor(Key: char); procedure ShowAnimal(Key: char); procedure ShowLetter(Key: char); procedure ShowMovie(Key: char); procedure ShowRazno(Key: char); procedure StartText; procedure ShowText(Key: char); procedure ShowSpecial(Key: word); end; var Form1: TForm1; implementation uses Types; {$R *.dfm} procedure TForm1.Stop; begin try if mPlay.Mode in [mpOpen, mpPlaying] then begin mPlay.Stop; mPlay.Close; end; except end; end; procedure TForm1.Play(FileName: AnsiString); var FileExt: AnsiString; Dx, Dy: integer; Rect: TRect; label Ponovi; begin if not FGlasovi then Exit; Ponovi: FileExt := ExtractFileExt(FileName); if not FileExists(FileName) then begin if FileExt = '' then begin FileName := ChangeFileExt(FileName, '.mp3'); if not FileExists(FileName) then Goto Ponovi end; if FileExt = '.mp3' then FileName := ChangeFileExt(FileName, '.wav'); if (FileExt = '.wav') then FileName := ChangeFileExt(FileName, '.mp3'); end; if FileExists(FileName) then begin mPlay.Display := nil; if FileExt = '.mpg' then mPlay.Display := Self; mPlay.FileName := FileName; mPlay.Wait := True; mPlay.Open; if FileExt = '.mpg' then begin Rect := mPlay.DisplayRect; OffsetRect(Rect, 10, 25); mPlay.DisplayRect := Rect; end; FPiskanje := False; mPlay.Play; end; end; procedure TForm1.ChangeFont(Way: TWay); begin if FLetter = nil then Exit; case Way of wDown: begin FLetter.Font.Size := FLetter.Font.Size - 2; if FLetter.Font.Size <= 20 then FLetter.Font.Size := 20; end; wUp: begin FLetter.Font.Size := FLetter.Font.Size + 2; if FLetter.Font.Size >= lCrka.Font.Size * 2 then FLetter.Font.Size := lCrka.Font.Size *2; end; end; end; procedure TForm1.ChangeTextColor(Way: TWay); begin case Way of wUp: begin if ColorBox1.ItemIndex = 0 then ColorBox1.ItemIndex := ColorBox1.Items.Count - 1 else ColorBox1.ItemIndex := ColorBox1.ItemIndex - 1; end; wDown: begin if ColorBox1.ItemIndex = ColorBox1.Items.Count - 1 then ColorBox1.ItemIndex := 0 else ColorBox1.ItemIndex := ColorBox1.ItemIndex + 1; end; end; if FLetter <> nil then FLetter.Font.Color := ColorBox1.Colors[ColorBox1.ItemIndex]; if FShape <> nil then FShape.Brush.Color := ColorBox1.Colors[ColorBox1.ItemIndex]; end; function TForm1.GetRandPos(Ctrl: TControl): TRect; var Top, Left: integer; begin Result := Ctrl.BoundsRect; Top := RandomRange(0, Form1.ClientHeight - (Ctrl.ClientHeight+20)); Left := RandomRange(0, Form1.ClientWidth - (Ctrl.ClientWidth+20)); Result.Top := Top; Result.Left := Left; Result.Bottom := Result.Top + Ctrl.ClientHeight; Result.Right := Result.Left + Ctrl.ClientWidth; end; function TForm1.GetRandColor: TColor; var Index: integer; begin Index := RandomRange(0, ColorBox1.Items.Count-1 ); ColorBox1.ItemIndex := Index; Result := ColorBox1.Colors[Index]; end; procedure TForm1.ChangeShape(Way: TWay); var tmpShape: TjvShapeType; begin if FShape = nil then Exit; tmpShape := FShape.Shape; case Way of wUp: begin if FShape.Shape = jstRectangle then tmpShape := jstflower else Dec(tmpShape); end; wDown: begin if FShape.Shape = jstflower then tmpShape := jstRectangle else Inc(tmpShape); end; end; FShape.Shape := tmpShape; end; procedure TForm1.ShowShape(Key: Char); var VoiceName: AnsiString; i: integer; begin if FShape = nil then FShape := TjvShape.Create(Self); FShape.Visible := True; FShape.BoundsRect := GetRandPos(sShape); FShape.Brush.Color := GetRandColor; FShape.Pen.Width := 5; FShape.Pen.Color := clBlack; FShape.Shape := ShapeArray[FShapeIndex].Type_; FShape.Parent := Self; VoiceName := ShapeArray[FShapeIndex].Voice; if FShapeIndex = High(ShapeArray) then FShapeIndex := Low(ShapeArray) else Inc(FShapeIndex); Play(PathLiki + VoiceName + '.mp3'); end; procedure TForm1.ShowColor(Key: Char); var VoiceName: AnsiString; begin Form1.Color := ColorArray[FColorIndex].Color; VoiceName := ColorArray[FColorIndex].Voice; if FColorIndex = High(ColorArray) then FColorIndex := Low(ColorArray) else Inc(FColorIndex); Play(PathBarve + VoiceName + '.mp3'); end; procedure TForm1.ShowAnimal(Key: Char); var index: integer; FileName: AnsiString; Value: AnsiString; begin if AnimalArray.Count = 0 then begin FKeyPressCount := 10; Exit; end; if FImage = nil then FImage := TImage.Create(Self); FImage.Visible := True; FImage.BoundsRect := GetRandPos(sShape); FImage.Transparent := True; FImage.Stretch := True; // Change from aray of used item to current array if AnimalArray.Count = 0 then begin AnimalArray.Assign(UsedAnimalArray); UsedAnimalArray.Clear; end; index := RandomRange(0, AnimalArray.Count); Value := AnimalArray[index]; UsedAnimalArray.Add(AnimalArray[index]); AnimalArray.Delete(index); cbZivali.ItemIndex := cbZivali.Items.IndexOf(Value); FileName := PathZivali + Value + '.jpg'; if FileExists(FileName) then FImage.Picture.LoadFromFile(FileName); FImage.Parent := Self; Play(PathZivali + Value); end; procedure TForm1.ShowLetter(Key: Char); var VoiceName: AnsiString; i: integer; begin if FLetter <> nil then FLetter.Visible := False; FLetter := TLabel.Create(Self); FLetter.Font := lCrka.Font; FLetter.Font.Color := ColorBox1.Colors[ColorBox1.ItemIndex]; FLetter.Transparent := True; FLetter.BoundsRect := GetRandPos(lCrka); FLetter.Caption := UpperCase(Key); FLetter.Parent := Self; VoiceName := UpperCase(Key); try // VoiceName := PChar(LetterArray.Data[Pointer(Key)]); except end; Play(PathCrke + VoiceName + '.mp3'); end; procedure TForm1.ShowMovie(Key: Char); var Value, FileName: AnsiString; begin if FilmiArray.Count = 0 then Exit; if FShowMovieCount = FilmiArray.Count then begin FKeyPressCount := 10; FShowMovieCount := 0; Exit; end; Value := FilmiArray[0]; FilmiArray.Move(0, FilmiArray.Count-1); Inc(FShowMovieCount); Play(PathFilmi + Value + '.mpg'); end; procedure TForm1.ShowRazno(Key: char); var index: integer; FileName: AnsiString; Value: AnsiString; begin if RaznoArray.Count = 0 then begin FKeyPressCount := 10; Exit; end; if FImage = nil then FImage := TImage.Create(Self); FImage.Visible := True; FImage.BoundsRect := GetRandPos(sShape); FImage.Transparent := True; FImage.Stretch := True; // Change from aray of used item to current array if RaznoArray.Count = 0 then begin RaznoArray.Assign(UsedRaznoArray); UsedRaznoArray.Clear; end; index := RandomRange(0, RaznoArray.Count); Value := RaznoArray[index]; UsedRaznoArray.Add(RaznoArray[index]); RaznoArray.Delete(index); cbRazno.ItemIndex := cbRazno.Items.IndexOf(Value); FileName := PathRazno + Value + '.jpg'; if FileExists(FileName) then FImage.Picture.LoadFromFile(FileName); FImage.Parent := Self; Play(PathRazno + Value); end; procedure TForm1.ShowSpecial(Key: Word); var tmpIndex: integer; FileName: AnsiString; begin if FImage = nil then FImage := TImage.Create(Self); FImage.Visible := True; FImage.BoundsRect := GetRandPos(sShape); FImage.Transparent := True; FImage.Stretch := True; FileName := ''; try FileName := PathRazno + PChar(SpecialArray.Data[Pointer(Key)]) + '.jpg'; cbRazno.ItemIndex := cbRazno.Items.IndexOf(PChar(SpecialArray.Data[Pointer(Key)])); except end; if FileExists(FileName) then FImage.Picture.LoadFromFile(FileName); FImage.Parent := Self; Play(PathRazno + PChar(SpecialArray.Data[Pointer(Key)])); end; procedure TForm1.StartText; begin if FLetter <> nil then FLetter.Visible := False; FLetter := TLabel.Create(Self); FLetter.Parent := Self; FLetter.Font := lCrka.Font; FLetter.Font.Color := ColorBox1.Colors[ColorBox1.ItemIndex]; FLetter.Transparent := True; FLetter.BoundsRect := lCrka.BoundsRect; FLetter.Top := (Form1.Height div 2) - (FLetter.Height div 2); FLetter.Left := 0; FLetter.Caption := ''; end; procedure TForm1.ShowText(Key: Char); begin Play(PathCrke + UpperCase(Key) + '.mp3'); FLetter.Caption := FLetter.Caption + UpperCase(Key); end; procedure TForm1.ChangeSection; begin if FSection = High(FSection) then begin // loop on fist section FSection := Low(FSection); if Assigned(FLetter) then FLetter.Visible := False; if Assigned(FShape) then FShape.Visible := False; if Assigned(FImage) then FImage.Visible := False; end else Inc(FSection); // Skip Text section on loop if (FSection = sText) and (FKeyPressCount >= 10) then Inc(FSection); if FSection = sText then StartText; StatusBar1.Panels[0].Text := SectionArray[FSection]; end; procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var tmpSection: TSection; begin Stop; if ((Key = VK_SPACE) or (FKeyPressCount >= 10)) then begin tmpSection := FSection; ChangeSection; while not miShowSection.Items[Ord(FSection)].Checked do begin // We come thru all section and none was checked if tmpSection = FSection then Break; ChangeSection; end; Key := 0; FKeyPressCount := 0; end; // Windows key if Key = 91 then Form1.BringToFront; if Shift = [] then case Key of // Special show on space key VK_SPACE, VK_INSERT, VK_DELETE: ShowSpecial(Key); VK_UP: ChangeTextColor(wUp); VK_DOWN: ChangeTextColor(wDown); VK_RETURN: begin ShowSpecial(Key); Key := 0; StartText; end; end else case Key of VK_UP: case FSection of sCrke, sText: ChangeFont(wUp); sLiki: ChangeShape(wUp); end; VK_DOWN: case FSection of sCrke, sText: ChangeFont(wDown); sLiki: ChangeShape(wDown); end; end; end; procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char); begin if Key = ' ' then ShowSpecial(VK_SPACE); if (Key = ' ') or (Key = Char(13)) then Exit; if Assigned(FImage) then FImage.Visible := False; if Assigned(FShape) then FShape.Visible := False; try case FSection of sLiki: ShowShape(Key); sBarve: ShowColor(Key); sZivali: ShowAnimal(Key); sCrke: ShowLetter(Key); sFilmi: ShowMovie(Key); sRazno: ShowRazno(Key); sText: ShowText(Key); end; if miLoop.Checked and (FSection <> sText) then Inc(FKeyPresscount); except end; Key := #0; end; procedure TForm1.FormShow(Sender: TObject); begin lCrka.Visible := False; sShape.Visible := False; iImage.Visible := False; FSection := sRazno; StatusBar1.Panels[0].Text := SectionArray[FSection]; end; procedure TForm1.FormCreate(Sender: TObject); var i: TSection; tmpMenuItem: TMenuItem; j: integer; FileName: AnsiString; begin // for j:= 0 to 126 do begin // FileName := PathCrke + {Format('%.3d',[j]) + '-' +}Chr(j) + '.txt'; // CopyFile(PathCrke + '_prazen.txt', PChar(FileName), False); // end; { for j:= Low(ColorArray) to High(ColorArray) do begin FileName := PathBarve + ColorArray[j].Voice + '.txt'; CopyFile(PathCrke + '_prazen.txt', PChar(FileName), False); end; } { for j:= Low(ShapeArray) to High(ShapeArray) do begin FileName := PathLiki + ShapeArray[j].Voice + '.txt'; CopyFile(PathCrke + '_prazen.txt', PChar(FileName), False); end; } FShapeIndex := Low(ShapeArray); FColorIndex := Low(ColorArray); FGlasovi:= True; FPiskanje := True; for i:= Low(SectionArray) to High(SectionArray) do begin tmpMenuItem := TMenuItem.Create(Self); tmpMenuItem.Caption := SectionArray[i]; tmpMenuItem.OnClick := miSection.OnClick; tmpMenuItem.Tag := Ord(i); tmpMenuItem.AutoCheck := miSection.AutoCheck; tmpMenuItem.Checked := miSection.Checked; miShowSection.Add(tmpMenuItem); end; miShowSection.Remove(miSection); for j:= 0 to RaznoArray.Count - 1 do cbRazno.AddItem(RaznoArray[j], nil); for j:= 0 to AnimalArray.Count - 1 do cbZivali.AddItem(AnimalArray[j], nil); for j:= 0 to FilmiArray.Count - 1 do cbFilmi.AddItem(FilmiArray[j], nil); Randomize; end; procedure TForm1.ColorBox1Change(Sender: TObject); begin case FSection of sLiki: if Assigned(FShape) then FShape.Brush.Color := ColorBox1.Colors[ColorBox1.ItemIndex]; sBarve: Form1.Color := ColorBox1.Colors[ColorBox1.ItemIndex]; sCrke: if Assigned(FLetter) then FLetter.Font.Color := ColorBox1.Colors[ColorBox1.ItemIndex]; sText: if Assigned(FLetter) then FLetter.Font.Color := ColorBox1.Colors[ColorBox1.ItemIndex]; end; ColorBox1.Enabled := False; ColorBox1.Enabled := True; end; procedure TForm1.FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if FPiskanje then Windows.Beep(100+X, 10); Canvas.Ellipse(X-5,y-5,x+5,y+5); end; procedure TForm1.miPiskanjeClick(Sender: TObject); begin FPiskanje := miPiskanje.Checked; end; procedure TForm1.miGlasoviClick(Sender: TObject); begin FGlasovi := miGlasovi.Checked; end; procedure TForm1.cbZivaliChange(Sender: TObject); var FileName, Value: AnsiString; begin if FImage = nil then FImage := TImage.Create(Self); FImage.BoundsRect := GetRandPos(sShape); FImage.Transparent := True; FImage.Stretch := True; Value := cbZivali.Items[cbZivali.ItemIndex]; FileName := PathZivali + Value + '.jpg'; if FileExists(FileName) then FImage.Picture.LoadFromFile(FileName); FImage.Parent := Self; Play(PathZivali + Value); cbZivali.Enabled := False; cbZivali.Enabled := True; end; procedure TForm1.cbRaznoChange(Sender: TObject); var FileName, Value: AnsiString; begin if FImage = nil then FImage := TImage.Create(Self); FImage.BoundsRect := GetRandPos(sShape); FImage.Transparent := True; FImage.Stretch := True; Value := cbRazno.Items[cbRazno.ItemIndex]; FileName := PathRazno + Value + '.jpg'; if FileExists(FileName) then FImage.Picture.LoadFromFile(FileName); FImage.Parent := Self; Play(PathRazno + Value); cbRazno.Enabled := False; cbRazno.Enabled := True; end; procedure TForm1.cbFilmiChange(Sender: TObject); var Value: AnsiString; begin Value := cbFilmi.Items[cbFilmi.ItemIndex]; Play(PathFilmi + Value + '.mpg'); cbFilmi.Enabled := False; cbFilmi.Enabled := True; end; procedure TForm1.FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin case Button of mbLeft: ShowSpecial(VK_LBUTTON); mbRight: ShowSpecial(VK_RBUTTON); end; end; procedure TForm1.mPlayNotify(Sender: TObject); begin FPiskanje := True; OutputDebugstring(PChar('Play')); end; end.
unit Geo; interface type TDMSFormat = (D, DM, DMS); TDecimalPlaces = (Zero = 0, Two = 2, Four = 4); function FloatingPointMod(const Dividend, Divisor : double) : double; function ParseDMS(const value : string) : double; function ToDMS (const deg: double; const dmsFormat : TDMSFormat; const dp : TDecimalPlaces) : string; function ToLat(const deg : double; const format : TDMSFormat; const dp : TDecimalPlaces) : string; function ToLon(const deg : double; const format : TDMSFormat; const dp : TDecimalPlaces) : string; function ToBearing(const deg : double; const format : TDMSFormat; const dp : TDecimalPlaces) : string; implementation uses Math, SysUtils, StrUtils; function FloatingPointMod(const Dividend, Divisor : double) : double; var quotient : integer; begin quotient := Trunc( Dividend / Divisor); Result := Dividend - (quotient * Divisor); end; // Parses string representing degrees/minutes/seconds into numeric degrees // // This is very flexible on formats, allowing signed decimal degrees, or deg-min-sec optionally // suffixed by compass direction (NSEW). A variety of separators are accepted (eg 3º 37' 09"W) // or fixed-width format without separators (eg 0033709W). Seconds and minutes may be omitted. // (Note minimal validation is done). // // @param {String|Number} dmsStr: Degrees or deg/min/sec in variety of formats // @returns {Number} Degrees as decimal number // @throws {TypeError} dmsStr is an object, perhaps DOM object without .value? function parseDMS(const value : string) : double; var a : double; dms : string; begin try Result := StrToFloat(value); except Result := NaN; end; // // check for signed decimal degrees without NSEW, if so return it directly // if (typeof dmsStr === 'number' && isFinite(dmsStr)) return Number(dmsStr); // // // strip off any sign or compass dir'n & split out separate d/m/s // var dms = String(dmsStr).trim().replace(/^-/,'').replace(/[NSEW]$/i,'').split(/[^0-9.,]+/); // if (dms[dms.length-1]=='') dms.splice(dms.length-1); // from trailing symbol // // if (dms == '') return NaN; // // // and convert to decimal degrees... // switch (dms.length) { // case 3: // interpret 3-part result as d/m/s // var deg = dms[0]/1 + dms[1]/60 + dms[2]/3600; // break; // case 2: // interpret 2-part result as d/m // var deg = dms[0]/1 + dms[1]/60; // break; // case 1: // just d (possibly decimal) or non-separated dddmmss // var deg = dms[0]; // // check for fixed-width unseparated format eg 0033709W // //if (/[NS]/i.test(dmsStr)) deg = '0' + deg; // - normalise N/S to 3-digit degrees // //if (/[0-9]{7}/.test(deg)) deg = deg.slice(0,3)/1 + deg.slice(3,5)/60 + deg.slice(5)/3600; // break; // default: // return NaN; // } // if (/^-|[WS]$/i.test(dmsStr.trim())) deg = -deg; // take '-', west and south as -ve // return Number(deg); end; // Convert decimal degrees to deg/min/sec format // - degree, prime, double-prime symbols are added, but sign is discarded, though no compass // direction is added // // @private // @param {Number} deg: Degrees // @param {String} [format=dms]: Return value as 'd', 'dm', 'dms' // @param {Number} [dp=0|2|4]: No of decimal places to use - default 0 for dms, 2 for dm, 4 for d // @returns {String} deg formatted as deg/min/secs according to specified format // @throws {TypeError} deg is an object, perhaps DOM object without .value? function ToDMS(const deg: double; const dmsFormat : TDMSFormat; const dp : TDecimalPlaces) : string; var degrees, minutes, seconds : double; begin Result := ''; if (IsNaN(deg) or IsInfinite(deg)) then exit ; // give up here if we can't make a number from deg case dmsFormat of D : begin case dp of Zero: Result := FormatFloat('000."º"', degrees); Two: Result := FormatFloat('000.00"º"', degrees); Four: Result := FormatFloat('000.0000"º"', degrees) end; end; DM : begin minutes := deg * 60; // convert degrees to minutes degrees := Floor(minutes / 60); // get degress minutes := FloatingPointMod(minutes, 60); // get whole minutes case dp of Zero: Result := FormatFloat('000"º"', degrees) + FormatFloat('00"''"', minutes); Two: Result := FormatFloat('000"º"', degrees) + FormatFloat('00.00"''"', minutes); Four: Result := FormatFloat('000"º"', degrees) + FormatFloat('00.0000"''"', minutes); end; end; DMS : begin seconds := ( deg * 3600); // convert degrees to seconds & round degrees := Floor(seconds / 3600); minutes := FloatingPointMod(Floor(seconds / 60), 60); seconds := FloatingPointMod(seconds, 60); case dp of Zero: Result := FormatFloat('000"º"', degrees) + FormatFloat('00"''"', minutes) + FormatFloat('00', seconds) + '"'; Two: Result := FormatFloat('000"º"', degrees) + FormatFloat('00"''"', minutes) + FormatFloat('00.00', seconds) + '"'; Four: Result := FormatFloat('000"º"', degrees) + FormatFloat('00"''"', minutes) + FormatFloat('00.0000', seconds) + '"'; end; end; end; end; // Convert numeric degrees to deg/min/sec latitude (suffixed with N/S) // // @param {Number} deg: Degrees // @param {String} [format=dms]: Return value as 'd', 'dm', 'dms' // @param {Number} [dp=0|2|4]: No of decimal places to use - default 0 for dms, 2 for dm, 4 for d // @returns {String} Deg/min/seconds function ToLat(const deg : double; const format : TDMSFormat; const dp : TDecimalPlaces) : string; var lat : string; begin lat := ToDMS(deg, format, dp); Result := RightStr(lat, Length(lat) - 1); if (deg < 0) then begin Result := Result + 'S'; end else begin Result := Result + 'N'; end; end; // Convert numeric degrees to deg/min/sec longitude (suffixed with E/W) // // @param {Number} deg: Degrees // @param {String} [format=dms]: Return value as 'd', 'dm', 'dms' // @param {Number} [dp=0|2|4]: No of decimal places to use - default 0 for dms, 2 for dm, 4 for d // @returns {String} Deg/min/seconds function ToLon(const deg : double; const format : TDMSFormat; const dp : TDecimalPlaces) : string; var lon : string; begin lon := ToDMS(deg, format, dp); if (deg < 0) then begin lon := lon + 'W'; end else begin lon := lon + 'E'; end; end; // Convert numeric degrees to deg/min/sec as a bearing (0º..360º) // // @param {Number} deg: Degrees // @param {String} [format=dms]: Return value as 'd', 'dm', 'dms' // @param {Number} [dp=0|2|4]: No of decimal places to use - default 0 for dms, 2 for dm, 4 for d // @returns {String} Deg/min/seconds function ToBearing(const deg : double; const format : TDMSFormat; const dp : TDecimalPlaces) : string; var deg1 : double; bearing : string; begin deg1 := FloatingPointMod(deg + 360, 360); // normalise -ve values to 180º..360º bearing := ToDMS(deg1, format, dp); Result := StringReplace(Bearing, '360', '0', []); // just in case rounding took us up to 360º! end; end.
unit uRegisterMachine; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Dialogs, strutils; type commandLine = record command: string; Value: Word; end; type registerArray = array of Longword; commandList = array of commandLine; commandLog = record b : String; command: commandLine; sysOutput : String; registers : registerArray; end; type commandLogSum = array of commandLog; { RegisterMachine } RegisterMachine = class private registerData: registerArray; programData: commandList; rawStringData: TStringList; executeLog: commandLogSum; errorMessage: string; //RegisterMachine FUNCTIONS/COMMANDS function LOAD(c: Word): String; function STORE(c : Word) : String; function ADD(c : Word) : String; function SUB(c : Word) : String; function MULT(c : Word) : String; function &DIV(c : Word) : String; function CLOAD(c: Word): String; function CADD(c : Longword) : String; function CSUB(c : Longword) : String; function CMULT(c : Longword) : String; function CDIV(c : Longword) : String; function JZERO(var j, b : Word) : String; function JNZERO(var j, b : Word) : String; function &GOTO(var j, b : Word) : String; function &END : String; public constructor Create(rawStringList: TStringList); class function verifyCommand(s: String): String; function GetRegisterData: registerArray; procedure SetRegisterData(NewValue: Longword; Index: integer); procedure SetRegisterData(NewArray: registerArray); function GetProgramData: commandList; procedure SetProgramData(NewValue: commandLine; Index: integer); function GetRawStringData: TStringList; class procedure DeleteComments(var s: string; CommentSymbol: string); function GetErrorMessage: string; function GetExecuteLog: commandLogSum; procedure SetErrorMessage(NewValue: string); procedure ProcessFile; procedure RenderRegisters; procedure RenderCommands; function Execute(regs : registerArray): boolean; const commands: array[0..14] of string = ('LOAD', 'STORE', 'ADD', 'SUB', 'MULT', 'DIV', 'GOTO', 'END', 'CLOAD', 'CADD', 'CMULT', 'CSUB', 'CDIV', 'JZERO', 'JNZERO'); RegisterCommands: array[0..5] of string = ('LOAD', 'STORE', 'ADD', 'SUB', 'MULT', 'DIV'); moveCommands : array[0..3] of String = ('GOTO', 'JZERO', 'JNZERO', 'END'); end; implementation //REGISTER MACHINE FUNCTIONS function RegisterMachine.LOAD(c: Word): String; begin SetRegisterData(GetRegisterData[c], 0); Result := 'A lädt Zahl ' + IntToStr(GetRegisterData[c]) + ' aus c(' + IntToStr(c) + ')'; end; function RegisterMachine.STORE(c: Word): String; begin SetRegisterData(GetRegisterData[0], c); Result := 'A speichert Zahl ' + IntToStr(GetRegisterData[c]) + ' in c(' + IntToStr(c) + ')'; end; function RegisterMachine.ADD(c: Word): String; begin SetRegisterData(GetRegisterData[0] + GetRegisterData[c], 0); Result := 'A wird um ' + inttoStr(GetRegisterData[c]) + ' aus c(' + IntToStr(c) + ') erhöht'; end; function RegisterMachine.SUB(c: Word): String; var res : Integer; begin res := GetRegisterData[0] - GetRegisterData[c]; if res < 0 then begin GetRegisterData[0] := 0; Result := 'A wird um ' + inttoStr(GetRegisterData[c]) + ' aus c(' + IntToStr(c) + ') bis auf 0 verringert'; end else begin SetRegisterData(res, 0); Result := 'A wird um ' + inttostr(GetRegisterData[c]) + ' aus c(' + IntToStr(c) + ') verringert'; end; end; function RegisterMachine.MULT(c: Word): String; begin SetRegisterData(GetRegisterData[0] * GetRegisterData[c], 0); Result := 'A wird mit ' + inttostr(GetRegisterData[c]) + ' aus c(' + IntToStr(c) + ') multipliziert'; end; function RegisterMachine.&div(c: Word): String; begin if GetRegisterData[c] <> 0 then begin SetRegisterData(GetRegisterData[0] div GetRegisterData[c], 0); Result := 'A wird durch ' + inttostr(GetRegisterData[c]) + ' aus c(' + IntToStr(c) + ') dividiert'; end else Result := 'ERROR'; end; function RegisterMachine.CLOAD(c: Word): String; begin SetRegisterData(c, 0); Result := 'A lädt Konstante ' + IntToStr(c); end; function RegisterMachine.CADD(c: Longword): String; begin SetRegisterData(GetRegisterData[0] + c, 0); Result := 'A um ' + IntToStr(c) + ' erhöht'; end; function RegisterMachine.CSUB(c: Longword): String; var res : Integer; begin res := GetRegisterData[0] - c; if res < 0 then begin GetRegisterData[0] := 0; Result := 'A wird um ' + IntToStr(c) + ' bis auf 0 verringert'; end else begin SetRegisterData(res, 0); Result := 'A wird um ' + IntToStr(c) + ' verringert'; end; end; function RegisterMachine.CMULT(c: Longword): String; begin SetRegisterData(GetRegisterData[0] * c, 0); Result := 'A mit ' + IntToStr(c) + ' multipliziert'; end; function RegisterMachine.CDIV(c: Longword): String; begin if c <> 0 then begin SetRegisterData(GetRegisterData[0] div c, 0); Result := 'A wird durch ' + IntToStr(c) + ' dividiert'; end else Result := 'ERROR'; end; function RegisterMachine.JZERO(var j, b: Word): String; begin if GetRegisterData[0] = 0 then begin b := j; Result := 'A ist 0 -> Sprung zur ' + IntToStr(j) + ' . Programmzeile'; end else begin Result := 'A ist nicht 0 -> Sprung zur nächsten Programmzeile'; b := b +1; end; end; function RegisterMachine.JNZERO(var j, b: Word): String; begin if GetRegisterData[0] <> 0 then begin b := j; Result := 'A ist nicht 0 -> Sprung zur ' + IntToStr(j) + '. Programmzeile'; end else begin Result := 'A ist 0 -> Sprung zur nächsten Programmzeile'; b := b +1; end; end; function RegisterMachine.&goto(var j, b: Word): String; begin b := j; Result := 'Sprung zur ' + IntToStr(j) + '. Programmzeile' ; end; function RegisterMachine.&end: String; begin Result := 'Ende des Ablaufs'; end; //FORMATTING AND INITIALIZE constructor RegisterMachine.Create(rawStringList: TStringList); begin SetErrorMessage(''); //initialize ErrorMessage rawStringData := rawStringList; //pass Data ProcessFile; RenderCommands; RenderRegisters; end; //checks if command is legal with Error feedback class function RegisterMachine.verifyCommand(s: String): String; var temp : Integer; line, errM: String; procedure addToResult(var s: String; const addS: String); begin if s <> '' then s := s + sLineBreak + addS else s := addS; end; begin errM := ''; DeleteComments(s, '//'); s:= trim(s); line := UpperCase(ExtractDelimited(2, s, [' '])); if not AnsiMatchText(line, commands) then //Type 2 Error: illegal command addToResult(errM, s + ': illegal command ' + line); if not TryStrToInt(ExtractDelimited(1, s, [' ']), temp) then //Type 1 Error illegal index addToResult(errM, s + ': illegal index ' + ExtractDelimited(1, s, [' '])); if (line <> 'END') AND (not TryStrToInt(ExtractDelimited(3, s, [' ']), temp)) then //Type 3 Error illegal value addToResult(errM, s + ': illegal value ' + ExtractDelimited(3, s, [' '])); if (line = 'END') AND (Pos('END',s) <> Length(s) - 2) then addToResult(errM, s + ': illegal value ' + ExtractDelimited(3, s, [' '])); Result := errM; end; function RegisterMachine.GetRegisterData: registerArray; begin Result := registerData; end; procedure RegisterMachine.SetRegisterData(NewValue: Longword; Index: integer); begin registerData[Index] := NewValue; end; procedure RegisterMachine.SetRegisterData(NewArray: registerArray); begin registerData := NewArray; end; function RegisterMachine.GetProgramData: commandList; begin Result := programData; end; procedure RegisterMachine.SetProgramData(NewValue: commandLine; Index: integer); begin if index + 1 > Length(programData) then SetLength(programData, index + 1); programData[Index] := NewValue; end; function RegisterMachine.GetRawStringData: TStringList; begin Result := rawStringData; end; class procedure RegisterMachine.DeleteComments(var s: string; CommentSymbol: string); var position: integer; begin position := Pos(CommentSymbol, s); if position <> 0 then Delete(s, position, Length(s) - position + 1); end; function RegisterMachine.GetErrorMessage: string; begin Result := errorMessage; end; function RegisterMachine.GetExecuteLog: commandLogSum; begin Result := executeLog; end; procedure RegisterMachine.SetErrorMessage(NewValue: string); begin if errorMessage <> '' then errorMessage := GetErrorMessage + sLineBreak + NewValue else errorMessage := NewValue; end; procedure RegisterMachine.ProcessFile; var tempStr: string; i: integer; begin //Deletes Comments and empty lines GetRawStringData.Sort; i := 0; while i <> GetRawStringData.Count do begin tempStr := GetRawStringData.Strings[i]; DeleteComments(tempStr, '//'); GetRawStringData.Strings[i] := tempStr; Trim(GetRawStringData.Strings[i]); if GetRawStringData.Strings[i] = '' then begin GetRawStringData.Delete(i); end else i := i + 1; end; end; procedure RegisterMachine.RenderRegisters; var amount, i: integer; begin //Determines amount of registers amount := 0; for i := 0 to Length(GetProgramData) - 1 do begin if AnsiMatchText(GetProgramData[i].command, RegisterCommands) and (GetProgramData[i].Value > amount) then amount := GetProgramData[i].Value; end; SetLength(registerData, amount + 1); //one extra for the c(0) end; procedure RegisterMachine.RenderCommands; var i: integer; actualLine: commandLine; error : String; begin //creates programData with Error Handling for i := 0 to GetRawStringData.Count - 1 do begin error:= verifyCommand(GetRawStringData.Strings[i]); if error = '' then begin actualLine.command := UpperCase(ExtractDelimited(2, GetRawStringData.Strings[i], [' '])); if actualLine.command <> 'END' then actualLine.Value := StrToInt(ExtractDelimited(3, GetRawStringData.Strings[i], [' '])) else actualLine.Value:= 0; SetProgramData(actualLine, StrtoInt(ExtractDelimited(1, GetRawStringData.Strings[i], [' ']))); end else SetErrorMessage(error); end; for i := 0 to High(GetProgramData) do begin if GetProgramData[i].command = 'END' then exit; end; SetErrorMessage('no END command found'); end; function RegisterMachine.Execute(regs: registerArray): boolean; var line : commandLine; b : Word; i : Integer; begin Result := true; SetLength(executeLog, 1); SetRegisterData(0, 0); //fill RegisterData for i := 0 to High(regs) do begin SetRegisterData(regs[i], i + 1); end; i:= 1; b := 0; line.command:= ' '; line.Value:= 0; with GetExecuteLog[0] do begin //first Line of log sysOutput:= 'Anfangszustand'; registers := Copy(GetRegisterData, 0, Length(GetRegisterData)); command.command := ''; command.value := 0; b := ''; end; while line.command <> 'END' do begin line := GetProgramData[b]; SetLength(executeLog, i + 1); //invoke specific function case line.command of 'LOAD' : GetExecuteLog[i].sysOutput:= LOAD(line.value); 'STORE' : GetExecuteLog[i].sysOutput:= STORE(line.value); 'ADD' : GetExecuteLog[i].sysOutput:= ADD(line.value); 'SUB' : GetExecuteLog[i].sysOutput:= SUB(line.value); 'MULT' : GetExecuteLog[i].sysOutput:= MULT(line.value); 'DIV' : GetExecuteLog[i].sysOutput:= &DIV(line.value); 'CLOAD' : GetExecuteLog[i].sysOutput:= CLOAD(line.value); 'CADD' : GetExecuteLog[i].sysOutput:= CADD(line.value); 'CSUB' : GetExecuteLog[i].sysOutput:= CSUB(line.value); 'CMULT' : GetExecuteLog[i].sysOutput:= CMULT(line.value); 'CDIV' : GetExecuteLog[i].sysOutput:= CDIV(line.value); 'END' : GetExecuteLog[i].sysOutput:= &END; 'GOTO' : GetExecuteLog[i].sysOutput:= &GOTO(line.value, b); 'JZERO' : GetExecuteLog[i].sysOutput:= JZERO(line.value, b); 'JNZERO' : GetExecuteLog[i].sysOutput:= JNZERO(line.value, b); end; //set log GetExecuteLog[i].b := IntToStr(b); GetExecuteLog[i].command := line; GetExecuteLog[i].registers := Copy(GetRegisterData, 0 ,Length(GetRegisterData)); //if command is not a move command increment b if not AnsiMatchText(line.command, moveCommands) then b := b + 1; i := i + 1; //Handles infinity loops if i > 2000 then begin Result := false; Break; end; end; end; end.
unit PaymentMethod; interface type TMethod = (mdNone,mdCash,mdCheck,mdBankWithdrawal); type TPaymentMethod = class private FMethod: TMethod; FName: string; FCharge: real; public property Method: TMethod read FMethod write FMethod; property Name: string read FName write FName; property Charge: real read FCharge write FCharge; end; TPaymentMethods = array of TPaymentMethod; var pmtMethods: TPaymentMethods; implementation end.
unit SecurityMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseDocked, Vcl.StdCtrls, RzLabel, Vcl.ExtCtrls, RzPanel, SaveIntf, NewIntf; type TSecurityForms = (sfmChangePassword,sfmUsers,sfmRoles, sfmRights); TfrmSecurityMain = class(TfrmBaseDocked, ISave, INew) pnlOptions: TRzPanel; pnlDock: TRzPanel; urlChangePassword: TRzURLLabel; urlUsers: TRzURLLabel; urlRoles: TRzURLLabel; urlRights: TRzURLLabel; procedure urlChangePasswordClick(Sender: TObject); procedure urlUsersClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure urlRolesClick(Sender: TObject); procedure urlRightsClick(Sender: TObject); private { Private declarations } DOCKED_FORM: TSecurityForms; procedure GetActiveForm(var frm: TForm); procedure DockForm(const fm: TSecurityForms; const title: string = ''); public { Public declarations } function Save: boolean; procedure New; procedure Cancel; end; implementation {$R *.dfm} uses ChangePassword, IFinanceDialogs, Users, SecurityData, Roles, User, IFinanceGlobal, Rights; { TfrmSecurityMain } procedure TfrmSecurityMain.Cancel; var intf: ISave; frm: TForm; begin try GetActiveForm(frm); if Assigned(frm) then if Supports(frm,ISave,intf) then intf.Cancel; except on e:Exception do ShowErrorBox(e.Message); end; end; procedure TfrmSecurityMain.DockForm(const fm: TSecurityForms; const title: string); var frm: TForm; control: integer; begin if (pnlDock.ControlCount = 0) or (fm <> DOCKED_FORM) then begin control := 0; while control < pnlDock.ControlCount do begin if pnlDock.Controls[control] is TForm then begin (pnlDock.Controls[control] as TForm).Close; (pnlDock.Controls[control] as TForm).Free; end; Inc(control); end; // instantiate form case fm of sfmChangePassword: frm := TfrmChangePassword.Create(self); sfmUsers: frm := TfrmUsers.Create(self); sfmRoles: frm := TfrmRoles.Create(self); sfmRights: frm := TfrmRights.Create(self); else frm := TForm.Create(self); end; DOCKED_FORM := fm; frm.ManualDock(pnlDock); frm.Show; end else ShowInfoBox('Window is already open.'); end; procedure TfrmSecurityMain.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; dmSecurity.Destroy; end; procedure TfrmSecurityMain.FormCreate(Sender: TObject); begin inherited; dmSecurity := TdmSecurity.Create(self); // hide or show links //urlUsers.Visible := ifn.User.HasRight(S9VIEW_USERS9View_system_users,false); //urlRoles.Visible := ifn.User.HasRight(S9VIEW_ROLES9View_system_roles,false); end; procedure TfrmSecurityMain.GetActiveForm(var frm: TForm); begin frm := nil; // check if a popup is active if Application.MainForm <> Screen.ActiveForm then frm := Screen.ActiveForm else if pnlDock.ControlCount > 0 then frm := pnlDock.Controls[0] as TForm; end; procedure TfrmSecurityMain.New; var intf: INew; frm: TForm; begin try GetActiveForm(frm); if Assigned(frm) then if Supports(frm,INew,intf) then intf.New; except on e:Exception do ShowErrorBox(e.Message); end; end; procedure TfrmSecurityMain.urlUsersClick(Sender: TObject); begin inherited; DockForm(sfmUsers); end; function TfrmSecurityMain.Save: boolean; var intf: ISave; frm: TForm; begin Result := false; try GetActiveForm(frm); if Assigned(frm) then if Supports(frm, ISave, intf) then if intf.Save then Result := true; except end; end; procedure TfrmSecurityMain.urlChangePasswordClick(Sender: TObject); begin inherited; DockForm(sfmChangePassword); end; procedure TfrmSecurityMain.urlRightsClick(Sender: TObject); begin inherited; DockForm(sfmRights); end; procedure TfrmSecurityMain.urlRolesClick(Sender: TObject); begin inherited; DockForm(sfmRoles); end; end.
unit WinAPI.WinRT.Utils; interface uses WinAPI.WinRT, WinAPI.CommonTypes; type TApplicationProcessMessagesProc = procedure of object; procedure Await(const asyncInfo: IInterface; const AApplicationProcessMessage: TApplicationProcessMessagesProc); /// <summary> /// Converts Delphi's TDateTime to WinRT's Windows.Foundation.DateTime /// as explained in https://docs.microsoft.com/en-us/uwp/api/windows.foundation.datetime#remarks /// </summary> function TDateTimeToDateTime(const ADateTime: TDateTime): DateTime; /// <summary> /// Converts WinRT's Windows.Foundation.DateTime to Delphi's TDateTime /// as explained in https://docs.microsoft.com/en-us/uwp/api/windows.foundation.datetime#remarks /// </summary> function DateTimeToTDateTime(const ADateTime: DateTime): TDateTime; implementation uses WinAPI.Foundation, System.SysUtils, System.Classes, WinAPI.Windows, System.Win.WinRT; resourcestring StrApplicationProcessError = 'AApplicationProcessMessage must be assigned'; StrIAsyncInfoNotSupported = 'Interface not supports IAsyncInfo'; procedure Await(const asyncInfo: IInterface; const AApplicationProcessMessage: TApplicationProcessMessagesProc); var lOut: IAsyncInfo; lErr: Cardinal; begin Assert(Assigned(AApplicationProcessMessage), StrApplicationProcessError); if not Supports(asyncInfo, IAsyncInfo, lOut) then raise Exception.Create(StrIAsyncInfoNotSupported); while not(lOut.Status in [asyncStatus.Completed, asyncStatus.Canceled, asyncStatus.Error]) do begin Sleep(100); AApplicationProcessMessage(); end; lErr := HResultCode(lOut.ErrorCode); if lErr <> ERROR_SUCCESS then raise Exception.Create(SysErrorMessage(lErr)); end; function DateTimeToTDateTime(const ADateTime: DateTime): TDateTime; var lVal: Int64; lSystemTime: TSystemTime; lFileTime: TFileTime; begin lVal := ADateTime.UniversalTime; lFileTime.dwHighDateTime := (lVal and $FFFFFFFF00000000) shr 32; lFileTime.dwLowDateTime := lVal and $00000000FFFFFFFF; FileTimeToSystemTime(lFileTime, lSystemTime); Result := SystemTimeToDateTime(lSystemTime); end; function TDateTimeToDateTime(const ADateTime: TDateTime): DateTime; var lVal: Int64; lSystemTime: TSystemTime; lFileTime: TFileTime; begin DateTimeToSystemTime(ADateTime, lSystemTime); SystemTimeToFileTime(lSystemTime, lFileTime); lVal := lFileTime.dwHighDateTime; lVal := (lVal shl 32) or lFileTime.dwLowDateTime; Result.UniversalTime := lVal; end; end.
unit fOCMonograph; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ORFn, ORCtrls, rOrders, VA508AccessibilityManager, ExtCtrls; type TfrmOCMonograph = class(TForm) monoCmbLst: TComboBox; monoMemo: TCaptionMemo; cmdOK: TButton; VA508StaticText1: TVA508StaticText; VA508StaticText2: TVA508StaticText; VA508AccessibilityManager1: TVA508AccessibilityManager; VA508ComponentAccessibility1: TVA508ComponentAccessibility; procedure DisplayMonograph; procedure monoCmbLstChange(Sender: TObject); procedure cmdOKClick(Sender: TObject); procedure VA508ComponentAccessibility1CaptionQuery(Sender: TObject; var Text: string); private { Private declarations } public { Public declarations } end; var mList: TStringList; procedure ShowMonographs(monoList: TStringList); implementation {$R *.dfm} procedure ShowMonographs(monoList: TStringList); var i: Integer; frmOCMonograph: TfrmOCMonograph; begin if monoList.Count > 0 then begin mList := monoList; frmOCMonograph := TfrmOCMonograph.Create(Application); try for i := 0 to monoList.Count - 1 do begin frmOCMonograph.monoCmbLst.Items.Add(Piece(monoList[i], U, 2)); end; //frmOCMonograph.monoMemo.Clear; frmOCMonograph.monoCmbLst.ItemIndex := 0; frmOCMonograph.DisplayMonograph; frmOCMonograph.ShowModal; finally frmOCMonograph.Free; end; end; end; procedure TfrmOCMonograph.DisplayMonograph; var i: Integer; x: Integer; monograph: TStringList; begin x := -1; monograph := TStringList.Create; monoMemo.Clear; for i := 0 to mList.Count - 1 do begin if Piece(mList[i],'^',2)=monoCmbLst.Items[monoCmbLst.ItemIndex] then x := StrtoInt(Piece(mList[i],'^',1)); end; if (x > -1) then begin GetMonograph(monograph,x); for i := 0 to monograph.Count - 1 do begin monoMemo.Text := monoMemo.Text + monograph[i] + CRLF; end; end; end; procedure TfrmOCMonograph.cmdOKClick(Sender: TObject); begin self.Close; end; procedure TfrmOCMonograph.monoCmbLstChange(Sender: TObject); begin DisplayMonograph; end; procedure TfrmOCMonograph.VA508ComponentAccessibility1CaptionQuery( Sender: TObject; var Text: string); begin Text := monoCmbLst.SelText; end; end.
unit Monobank.Types; interface type /// <summary> /// Перелік курсів. Кожна валютна пара може мати одне і більше полів з rateSell, rateBuy, rateCross. /// </summary> TmonoCurrencyInfo = class private FcurrencyCodeA: Integer; FcurrencyCodeB: Integer; Fdate: Integer; FrateSell: Single; FrateBuy: Single; FrateCross: Single; public /// <summary> /// /// </summary> property CurrencyCodeA: Integer read FcurrencyCodeA; property CurrencyCodeB: Integer read FcurrencyCodeB; property Date: Integer read Fdate; property RateSell: Single read FrateSell; property RateBuy: Single read FrateBuy; property RateCross: Single read FrateCross; end; TmonoAccount = class private Fid: string; Fbalance: Int64; FcreditLimit: Int64; FcurrencyCode: Integer; FcashbackType: string; published /// <summary> /// Ідентифікатор рахунку /// </summary> property id: string read Fid write Fid; /// <summary> /// Баланс рахунку в мінімальних одиницях валюти (копійках, центах) /// </summary> property balance: Int64 read Fbalance write Fbalance; /// <summary> /// Кредитний ліміт /// </summary> property creditLimit: Int64 read FcreditLimit write FcreditLimit; /// <summary> /// Код валюти рахунку відповідно ISO 4217 /// </summary> property currencyCode: Integer read FcurrencyCode write FcurrencyCode; /// <summary> /// Тип кешбеку який нараховується на рахунок /// </summary> property cashbackType: string read FcashbackType write FcashbackType; end; /// <summary> /// Опис клієнта та його рахунків. /// </summary> TmonoUserInfo = class private Fname: string; Faccounts: TArray<TmonoAccount>; public /// <summary> /// Ім'я клієнта /// </summary> property Name: string read Fname; /// <summary> /// Перелік доступних рахунків /// </summary> property accounts: TArray<TmonoAccount> read Faccounts write Faccounts; end; TmonoStatementItem = class private Fid: string; Ftime: Integer; Fdescription: string; Fmcc: Integer; Fhold: boolean; Famount: Int64; FoperationAmount: Int64; FcurrencyCode: Integer; FcommissionRate: Int64; FcashbackAmount: Int64; Fbalance: int64; published property id: string read Fid write Fid; property time: Integer read Ftime write Ftime; property description: string read Fdescription write Fdescription; property mcc: Integer read Fmcc write Fmcc; property hold: boolean read Fhold write Fhold; property amount: Int64 read Famount write Famount; property operationAmount: Int64 read FoperationAmount write FoperationAmount; property currencyCode: Integer read FcurrencyCode write FcurrencyCode; property commissionRate: Int64 read FcommissionRate write FcommissionRate; property cashbackAmount: Int64 read FcashbackAmount write FcashbackAmount; property balance: int64 read Fbalance write Fbalance; end; implementation end.
object AzSnapshotBlob: TAzSnapshotBlob Left = 227 Top = 108 BorderStyle = bsDialog Caption = 'Create Snapshot Blob' ClientHeight = 462 ClientWidth = 512 Color = clBtnFace ParentFont = True OldCreateOrder = True Position = poScreenCenter PixelsPerInch = 96 TextHeight = 13 object Bevel1: TBevel Left = 8 Top = 8 Width = 496 Height = 409 Shape = bsFrame end object OKBtn: TButton Left = 348 Top = 423 Width = 75 Height = 25 Caption = 'Create' Default = True ModalResult = 1 TabOrder = 5 end object CancelBtn: TButton Left = 429 Top = 423 Width = 75 Height = 25 Cancel = True Caption = 'Cancel' ModalResult = 2 TabOrder = 4 end object GroupBox1: TGroupBox Left = 25 Top = 16 Width = 465 Height = 81 Caption = 'Conditions (optional)' TabOrder = 0 object Label1: TLabel Left = 16 Top = 24 Width = 72 Height = 13 Caption = 'Modified Since:' end object Label2: TLabel Left = 16 Top = 48 Width = 33 Height = 13 Caption = 'Match:' end object Label3: TLabel Left = 240 Top = 51 Width = 61 Height = 13 Caption = 'None Match:' end object Label4: TLabel Left = 240 Top = 24 Width = 85 Height = 13 Caption = 'Unmodified Since:' end object edtModifiedSince: TEdit Left = 94 Top = 21 Width = 132 Height = 21 TabOrder = 0 end object edtUnmodified: TEdit Left = 331 Top = 21 Width = 118 Height = 21 TabOrder = 1 end object edtNoneMatch: TEdit Left = 331 Top = 48 Width = 118 Height = 21 TabOrder = 3 end object edtMatch: TEdit Left = 94 Top = 48 Width = 132 Height = 21 TabOrder = 2 end end object vleMeta: TValueListEditor Left = 25 Top = 103 Width = 465 Height = 298 KeyOptions = [keyEdit, keyAdd, keyDelete, keyUnique] Options = [goFixedVertLine, goFixedHorzLine, goVertLine, goHorzLine, goColSizing, goEditing, goTabs, goAlwaysShowEditor, goThumbTracking] TabOrder = 1 TitleCaptions.Strings = ( 'Metadata Name' 'Value') ColWidths = ( 150 309) end object btnAddMetadata: TButton Left = 25 Top = 423 Width = 83 Height = 25 Caption = 'Add metadata' TabOrder = 2 OnClick = btnAddMetadataClick end object btnDelMetadata: TButton Left = 114 Top = 423 Width = 103 Height = 25 Caption = 'Remove Metadata' TabOrder = 3 OnClick = btnDelMetadataClick end end
unit ExtraChargeExcelDataModule; interface uses System.SysUtils, System.Classes, ExcelDataModule, Excel2010, Vcl.OleServer, CustomExcelTable, Data.DB, FireDAC.Comp.Client, FireDAC.Comp.DataSet, ExtraChargeSimpleQuery, ExtraChargeInterface; type TExtraChargeExcelTable = class(TCustomExcelTable) private FExtraChargeInt: IExtraCharge; FqExtraChargeSimple: TQueryExtraChargeSimple; function GetqExtraChargeSimple: TQueryExtraChargeSimple; function GetRange: TField; function GetWholeSale: TField; function GetExtraChargeType: TField; protected function CheckRange: Boolean; procedure SetFieldsInfo; override; property qExtraChargeSimple: TQueryExtraChargeSimple read GetqExtraChargeSimple; public constructor Create(AOwner: TComponent); override; function CheckRecord: Boolean; override; property ExtraChargeInt: IExtraCharge read FExtraChargeInt write FExtraChargeInt; property Range: TField read GetRange; property WholeSale: TField read GetWholeSale; property ExtraChargeType: TField read GetExtraChargeType; end; TExtraChargeExcelDM = class(TExcelDM) private function GetExcelTable: TExtraChargeExcelTable; { Private declarations } protected function CreateExcelTable: TCustomExcelTable; override; public property ExcelTable: TExtraChargeExcelTable read GetExcelTable; { Public declarations } end; implementation uses FieldInfoUnit, System.RegularExpressions, System.Variants, ErrorType, RecordCheck; constructor TExtraChargeExcelTable.Create(AOwner: TComponent); begin inherited; end; function TExtraChargeExcelTable.CheckRange: Boolean; var // AHigh: Integer; // ALow: Integer; ARecordCheck: TRecordCheck; begin Assert(ExtraChargeInt <> nil); ARecordCheck.ErrorType := etError; ARecordCheck.Row := ExcelRow.AsInteger; ARecordCheck.Col := Range.Index + 1; ARecordCheck.ErrorMessage := Range.AsString; // Ищем точно такой-же диапазон Result := not ExtraChargeInt.HaveDuplicate(ExtraChargeType.Value, Range.Value); // Если нашли дубликат диапазона if not Result then begin ARecordCheck.Description := 'Такой диапазон уже существует'; ProcessErrors(ARecordCheck); Exit; end; // ARecordCheck.Description := qExtraChargeSimple.CheckBounds(0, Range.AsString, ALow, AHigh ); // Result := ARecordCheck.Description.IsEmpty; // Если не нашли if not Result then ProcessErrors(ARecordCheck); end; function TExtraChargeExcelTable.CheckRecord: Boolean; begin Result := inherited; if Result then begin // Проверяем корректность диапазона Result := CheckRange; end; end; function TExtraChargeExcelTable.GetqExtraChargeSimple: TQueryExtraChargeSimple; begin if FqExtraChargeSimple = nil then FqExtraChargeSimple := TQueryExtraChargeSimple.Create(Self); Result := FqExtraChargeSimple; end; function TExtraChargeExcelTable.GetRange: TField; begin Result := FieldByName('Range'); end; function TExtraChargeExcelTable.GetWholeSale: TField; begin Result := FieldByName('WholeSale'); end; function TExtraChargeExcelTable.GetExtraChargeType: TField; begin Result := FieldByName('ExtraChargeType'); end; procedure TExtraChargeExcelTable.SetFieldsInfo; begin FieldsInfo.Add(TFieldInfo.Create('Range', True, 'Диапазон не может быть пустым')); FieldsInfo.Add(TFieldInfo.Create('Wholesale', True, 'Наценка не может быть пустой')); FieldsInfo.Add(TFieldInfo.Create('ExtraChargeType', True, 'Тип оптовой наценки не может быть пустым')); end; function TExtraChargeExcelDM.CreateExcelTable: TCustomExcelTable; begin Result := TExtraChargeExcelTable.Create(Self); end; function TExtraChargeExcelDM.GetExcelTable: TExtraChargeExcelTable; begin Result := CustomExcelTable as TExtraChargeExcelTable; end; {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} end.
unit araclar; interface uses System.SysUtils, System.Types, System.TypInfo, System.Classes, System.Zip; function TBytes2TByteDynArray(Bytes: TBytes): TByteDynArray; function TByteDynArray2TBytes(Bytes: TByteDynArray): TBytes; function EnumValues(const ATypeInfo: PTypeInfo): TStrings; function EnumValue(const ATypeInfo: PTypeInfo; Value: Integer): string; function FileToBase64(const AFileName: string): String; function Sikistir(Stream: TStream; FileName: string): TBytes; function Base64toBytes(const Base64: string): TBytes; implementation uses System.NetEncoding; function TBytes2TByteDynArray(Bytes: TBytes): TByteDynArray; var ByteDynArray: TByteDynArray; begin SetLength(ByteDynArray, Length(Bytes)); Move(Pointer(Bytes)^, Pointer(ByteDynArray)^, Length(Bytes)); TBytes2TByteDynArray := ByteDynArray; end; function TByteDynArray2TBytes(Bytes: TByteDynArray): TBytes; //var // Bytes: TByteDynArray; begin SetLength(Result, Length(Bytes)); Move(Pointer(Bytes)^, Pointer(Result)^, Length(Bytes)); // TBytes2TByteDynArray := ByteDynArray; end; function EnumValues(const ATypeInfo: PTypeInfo): TStrings; var i: Integer; begin Result := TStringList.Create; for i := GetTypeData(ATypeInfo).MinValue to GetTypeData(ATypeInfo).MaxValue do begin Result.Add(GetEnumName(ATypeInfo, i)); end; end; function EnumValue(const ATypeInfo: PTypeInfo; Value: Integer): string; begin EnumValue := GetEnumName(ATypeInfo, Ord(Value)); end; function FileToBase64(const AFileName: string): string; var FileStream: TStream; Base64Stream: TStringStream; begin FileStream := TFileStream.Create(AFileName, fmOpenRead); Base64Stream := TStringStream.Create; TBase64Encoding.Base64.Encode(FileStream, Base64Stream); Result := Base64Stream.DataString; FileStream.Free; Base64Stream.Free; end; function Base64toBytes(const Base64: string): TBytes; begin Base64toBytes := TBase64Encoding.Base64.DecodeStringToBytes(Base64); end; function Sikistir(Stream: TStream; FileName: string): TBytes; var // LZip: TZCompressionStream; ZipStream: TStream; ZipFile: TZipFile; begin ZipFile := TZipFile.Create(); ZipStream := TMemoryStream.Create; ZipFile.Open(ZipStream, TZipMode.zmWrite); Stream.Seek(0, 0); ZipFile.Add(Stream, FileName, TZipCompression.zcDeflate); ZipFile.Close; ZipStream.Seek(0, 0); SetLength(Result, ZipStream.Size); ZipStream.ReadBuffer(Result, ZipStream.Size); FreeAndNil(ZipStream); end; end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { SOAP Transports } { } { Copyright (c) 2001 Inprise Corporation } { } {*******************************************************} unit SoapHTTPTrans; interface uses SysUtils, Classes, WinSock, WinInet, WebNode, WSDLNode; type THTTPReqResp = class(TComponent, IInterface, IWebNode) private FUserSetURL: Boolean; FRefCount: Integer; FOwnerIsComponent: Boolean; FConnected: Boolean; FURL: string; FAgent: string; FUserName: string; FPassword: string; FURLHost: string; FURLSite: string; FURLPort: Integer; FURLScheme: Integer; FProxy: string; FProxyByPass: string; FInetRoot: HINTERNET; FInetConnect: HINTERNET; FWSDLView: TWSDLView; FSoapAction: string; FUseUTF8InHeader: Boolean; procedure SetURL(const Value: string); procedure InitURL(const Value: string); protected function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; public constructor Create(Owner: TComponent); override; class function NewInstance: TObject; override; procedure AfterConstruction; override; destructor Destroy; override; procedure Check(Error: Boolean); procedure Connect(Value: Boolean); function Send(const S: WideString): Integer; procedure Receive(Context: Integer; Resp: TStream); procedure Execute(const DataMsg: WideString; Resp: TStream); property URL: string read FURL write SetURL; property SoapAction: string read FSoapAction write FSoapAction; published property WSDLView: TWSDLView read FWSDLView write FWSDLView; property Agent: string read FAgent write FAgent; property UserName: string read FUserName write FUserName; property Password: string read FPassword write FPassword; property Proxy: string read FProxy write FProxy; property ProxyByPass: string read FProxyByPass write FProxyByPass; property UseUTF8InHeader: Boolean read FUseUTF8InHeader write FUseUTF8InHeader; end; implementation {$IFDEF MSWINDOWS} uses Windows, Variants, SoapConst, XMLDoc, XMLIntf, WSDLIntf, InvokeRegistry; constructor THTTPReqResp.Create(Owner: TComponent); begin inherited; FInetRoot := nil; FInetConnect := nil; FUserSetURL := False; FAgent := 'Borland SOAP 1.1'; end; destructor THTTPReqResp.Destroy; begin inherited; end; class function THTTPReqResp.NewInstance: TObject; begin Result := inherited NewInstance; THTTPReqResp(Result).FRefCount := 1; end; procedure THTTPReqResp.AfterConstruction; begin inherited; FOwnerIsComponent := Assigned(Owner) and (Owner is TComponent); InterlockedDecrement(FRefCount); end; { IInterface } function THTTPReqResp._AddRef: Integer; begin Result := InterlockedIncrement(FRefCount) end; function THTTPReqResp._Release: Integer; begin Result := InterlockedDecrement(FRefCount); { If we are not being used as a TComponent, then use refcount to manage our lifetime as with TInterfacedObject. } if (Result = 0) and not FOwnerIsComponent then Destroy; end; procedure THTTPReqResp.Check(Error: Boolean); var ErrCode: Integer; S: string; begin ErrCode := GetLastError; if Error and (ErrCode <> 0) then begin SetLength(S, 256); FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM or FORMAT_MESSAGE_FROM_HMODULE, Pointer(GetModuleHandle('wininet.dll')), ErrCode, 0, PChar(S), Length(S), nil); SetLength(S, StrLen(PChar(S))); while (Length(S) > 0) and (S[Length(S)] in [#10, #13]) do SetLength(S, Length(S) - 1); raise Exception.Create(S); end; end; procedure THTTPReqResp.SetURL(const Value: string); begin if Value <> '' then FUserSetURL := True else FUserSetURL := False; InitURL(Value); end; procedure THTTPReqResp.InitURL(const Value: string); var URLComp: TURLComponents; P: PChar; begin if Value <> '' then begin FillChar(URLComp, SizeOf(URLComp), 0); URLComp.dwStructSize := SizeOf(URLComp); URLComp.dwSchemeLength := 1; URLComp.dwHostNameLength := 1; URLComp.dwURLPathLength := 1; P := PChar(Value); InternetCrackUrl(P, 0, 0, URLComp); if not (URLComp.nScheme in [INTERNET_SCHEME_HTTP, INTERNET_SCHEME_HTTPS]) then raise Exception.Create(SInvalidURL); FURLScheme := URLComp.nScheme; FURLPort := URLComp.nPort; FURLHost := Copy(Value, URLComp.lpszHostName - P + 1, URLComp.dwHostNameLength); FURLSite := Copy(Value, URLComp.lpszUrlPath - P + 1, URLComp.dwUrlPathLength); end else begin FURLPort := 0; FURLHost := ''; FURLSite := ''; FURLScheme := 0; end; FURL := Value; end; procedure THTTPReqResp.Connect(Value: Boolean); var AccessType: Integer; begin if Value then begin if Length(FProxy) > 0 then AccessType := INTERNET_OPEN_TYPE_PROXY else AccessType := INTERNET_OPEN_TYPE_PRECONFIG; FInetRoot := InternetOpen(PChar(FAgent), AccessType, PChar(FProxy), PChar(FProxyByPass), 0); if InternetAttemptConnect(0) <> ERROR_SUCCESS then SysUtils.Abort; Check(not Assigned(FInetRoot)); try FInetConnect := InternetConnect(FInetRoot, PChar(FURLHost), FURLPort, PChar(FUserName), PChar(FPassword), INTERNET_SERVICE_HTTP, 0, Cardinal(Self)); Check(not Assigned(FInetConnect)); except InternetCloseHandle(FInetRoot); end; end else if not Value then begin if Assigned(FInetConnect) then InternetCloseHandle(FInetConnect); FInetConnect := nil; if Assigned(FInetRoot) then InternetCloseHandle(FInetRoot); FInetRoot := nil; end; end; const MaxStatusTest = 4096; procedure THTTPReqResp.Receive(Context: Integer; Resp: TStream); var Size, Downloaded, Status, Len, Index: DWord; S: string; begin Len := SizeOf(Status); Index := 0; if HttpQueryInfo(Pointer(Context), HTTP_QUERY_STATUS_CODE or HTTP_QUERY_FLAG_NUMBER, @Status, Len, Index) and (Status >= 300) then begin Index := 0; Size := MaxStatusTest; SetLength(S, Size); if HttpQueryInfo(Pointer(Context), HTTP_QUERY_STATUS_TEXT, @S[1], Size, Index) then begin SetLength(S, Size); raise Exception.CreateFmt('%s (%d)', [S, Status]); end; end; Len := 0; repeat Check(not InternetQueryDataAvailable(Pointer(Context), Size, 0, 0)); if Size > 0 then begin SetLength(S, Size); Check(not InternetReadFile(Pointer(Context), @S[1], Size, Downloaded)); Resp.Write(S[1], Size); end; until Size = 0; end; function THTTPReqResp.Send(const S: WideString): Integer; var Request: HINTERNET; RetVal, Flags: DWord; P: Pointer; AcceptTypes: array of PChar; ActionHeader: string; WireData: string; ContentHeader: string; const ContentHeaderUTF8 = 'Content-Type: text/xml charset="utf-8"'; ContentHeaderNoUTF8 = 'Content-Type: text/xml'; begin if UseUTF8InHeader then ContentHeader := ContentHeaderUTF8 else ContentHeader := ContentHeaderNoUTF8; if not FConnected then begin Connect(True); FConnected := True; end; SetLength(AcceptTypes, 3); AcceptTypes[0] := PChar('application/octet-stream'); AcceptTypes[1] := PChar('text/xml'); AcceptTypes[2] := nil; Flags := INTERNET_FLAG_KEEP_CONNECTION or INTERNET_FLAG_NO_CACHE_WRITE; if FURLScheme = INTERNET_SCHEME_HTTPS then Flags := Flags or INTERNET_FLAG_SECURE; Request := HttpOpenRequest(FInetConnect, 'POST', PChar(FURLSite), nil, nil, Pointer(AcceptTypes), Flags, Integer(Self)); Check(not Assigned(Request)); if FSoapAction = '' then ActionHeader := SHTTPSoapAction + ':' else ActionHeader := SHTTPSoapAction + ': ' + '"' + FSoapAction + '"'; HttpAddRequestHeaders(Request, PChar(ActionHeader), Length(ActionHeader), HTTP_ADDREQ_FLAG_ADD); HttpAddRequestHeaders(Request, PChar(ContentHeader), Length(ContentHeader), HTTP_ADDREQ_FLAG_ADD); WireData := UTF8Encode(S); while True do begin Check(not HttpSendRequest(Request, nil, 0, @WireData[1], Length(WireData))); RetVal := InternetErrorDlg(GetDesktopWindow(), Request, GetLastError, FLAGS_ERROR_UI_FILTER_FOR_ERRORS or FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS or FLAGS_ERROR_UI_FLAGS_GENERATE_DATA, P); case RetVal of ERROR_SUCCESS: break; ERROR_CANCELLED: SysUtils.Abort; ERROR_INTERNET_FORCE_RETRY: {Retry the operation}; end; end; Result := Integer(Request); end; {$ENDIF} {$IFDEF LINUX} uses WSDLIntf, SoapConst; constructor THTTPReqResp.Create(Obj: THTTPReqResp); begin inherited Create(Obj); end; procedure THTTPReqResp.Check(Error: Boolean); begin end; procedure THTTPReqResp.SetURL(const Value: string); begin FUserSetURL := True; FURL := Value; end; procedure THTTPReqResp.Connect(Value: Boolean); begin end; function THTTPReqResp.Receive(Context: Integer): string; begin end; function THTTPReqResp.Send(const S: string; Address: ISoapAddress): Integer; begin end; {$ENDIF} procedure THTTPReqResp.Execute(const DataMsg: WideString; Resp: TStream); var Binding: string; Context: Integer; ExtName: WideString; begin if not FUserSetURL and (WSDLVIew <> nil) then begin if not WSDLView.WSDL.Active then WSDLView.WSDL.Active := True; Binding := WSDLView.WSDL.GetBindingForServicePort(WSDLView.Service, WSDLView.Port); ExtName := InvRegistry.GetMethExternalName(WSDLView.IntfInfo, WSDLVIew.Operation); if ExtName = '' then ExtName := WSDLVIew.Operation; FSoapAction := WSDLView.WSDL.GetSoapOperationAttribute(Binding, ExtName, WSDLIntf.SSoapAction); FURL := WSDLView.WSDL.GetSoapAddressForServicePort(WSDLView.Service, WSDLView.Port); InitURL(FURL); end; Context := Send(DataMsg); Receive(Context, Resp); end; end.
(*****************************************************************************) { Project Android MQTT broker test Android Application to test a connection with a MQTT Broker There must be chosen a free MQTT broker, as "test.mosquitto.org"; //"broker.hivemq.com"; //"iot.eclipse.com"; //"mqtt.fluux.io"; //"test.mosca.io"; //"broker.mqttdashboard.com";, and the port is the open MQTT port 1883 To test this application the sketch test_eclipse.ino must be previously stored on the IoT board. The topics that the IoT board publishes are Estado/Led, Estado/Botao and TopicIoTboard71, and its subscribes to the topic MessFromClient71. According to the message sent from this application, the IoT board put on/off the led, returns the button state, and prints the request on the serial monitor. } // Copyright: Fernando Pazos // december 2019 (*****************************************************************************) unit HeaderFooterTemplate; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, TMS.MQTT.Global, FMX.Edit, FMX.ScrollBox, FMX.Memo, FMX.ListBox, TMS.MQTT.Client, FMX.Objects, FMX.Controls.Presentation; type TMainForm = class(TForm) Header: TToolBar; Footer: TToolBar; HeaderLabel: TLabel; Circle1: TCircle; led: TCircle; Label1: TLabel; TMSMQTTClient1: TTMSMQTTClient; brokerLbl: TLabel; portLbl: TLabel; BrokerList: TComboBox; MemoLog: TMemo; Edit1: TEdit; SendBtn: TButton; Label2: TLabel; ConnectBtn: TSpeedButton; DisconnectBtn: TSpeedButton; procedure BrokerListChange(Sender: TObject); procedure ConnectBtnClick(Sender: TObject); procedure DisconnectBtnClick(Sender: TObject); procedure MemoLogChange(Sender: TObject); procedure SendBtnClick(Sender: TObject); procedure TMSMQTTClient1ConnectedStatusChanged(ASender: TObject; const AConnected: Boolean; AStatus: TTMSMQTTConnectionStatus); procedure TMSMQTTClient1PublishReceived(ASender: TObject; APacketID: Word; ATopic: string; APayload: TArray<System.Byte>); private { Private declarations } public { Public declarations } end; var MainForm: TMainForm; implementation {$R *.fmx} {$R *.NmXhdpiPh.fmx ANDROID} {$R *.SmXhdpiPh.fmx ANDROID} {$R *.Surface.fmx MSWINDOWS} {$R *.SSW3.fmx ANDROID} //event executed when a broker URL is selected from the list box procedure TMainForm.BrokerListChange(Sender: TObject); var LIndex:integer; begin LIndex:=BrokerList.ItemIndex; TMSMQTTClient1.BrokerHostName:=BrokerList.Items[LIndex]; end; //Event executed when the Connect button is pressed procedure TMainForm.ConnectBtnClick(Sender: TObject); begin TMSMQTTClient1.Connect(); end; //Event executed when the disconnect button os pressed procedure TMainForm.DisconnectBtnClick(Sender: TObject); begin TMSMQTTClient1.Disconnect(); end; //EVENT executed when MemoLog is on change to scroll the memoLog until the last row procedure TMainForm.MemoLogChange(Sender: TObject); begin //SendMessage(MemoLog.Handle, EM_LINESCROLL, 0,MemoLog.Lines.Count); end; //Event executed when the Send button os pressed procedure TMainForm.SendBtnClick(Sender: TObject); begin if Edit1.Text<>'' then begin TMSMQTTClient1.Publish('MessFromClient71',Edit1.Text); Edit1.Text:=''; end; end; //Event executed when the Connection state changes //It toggles the connect and disconnect enabled status, and put on/off the drawn led //prints on the memo log window the connection status. //when connected, subscribes to the topics Estado/Led, Estado/Botao and TopicIoTboard71 procedure TMainForm.TMSMQTTClient1ConnectedStatusChanged(ASender: TObject; const AConnected: Boolean; AStatus: TTMSMQTTConnectionStatus); begin if (AConnected) then begin ConnectBtn.Enabled:=False; BrokerList.Enabled:=False; SendBtn.Enabled:=True; DisconnectBtn.Enabled:=True; Edit1.Enabled:=True; TMSMQTTClient1.Subscribe('Estado/Led'); TMSMQTTClient1.Subscribe('Estado/Botao'); TMSMQTTClient1.Subscribe('TopicIoTboard71'); TMSMQTTClient1.Subscribe('AnalogInput'); Led.Fill.Color:=$FFFF0000; //led color=red MemoLog.Lines.Add('Client connected to server '+#13#10+TMSMQTTClient1.BrokerHostName+' at '+FormatDateTime('hh:nn:ss', Now)); end else begin ConnectBtn.Enabled:=True; BrokerList.Enabled:=True; SendBtn.Enabled:=False; DisconnectBtn.Enabled:=False; Edit1.Enabled:=False; Led.Fill.Color:=$FF800000; //led color=maroon MemoLog.Lines.Add('Client disconnected from server '+#13#10+TMSMQTTClient1.BrokerHostName+' at '+FormatDateTime('hh:nn:ss', Now)); case AStatus of csNotConnected: MemoLog.Lines.Add('Client not connected'); //csConnectionRejected_InvalidProtocolVersion: ; //csConnectionRejected_InvalidIdentifier: ; csConnectionRejected_ServerUnavailable: MemoLog.Lines.Add('Server Unavailable'); //csConnectionRejected_InvalidCredentials: ; csConnectionRejected_ClientNotAuthorized: MemoLog.Lines.Add('Client not authorized'); csConnectionLost: MemoLog.Lines.Add('Connection lost'); //csConnecting: ; //csReconnecting: ; //csConnected: ; end; end; end; //Event executed when a message is received from the publisher (IoT board) //It prints the received message on the Memo Log window procedure TMainForm.TMSMQTTClient1PublishReceived(ASender: TObject; APacketID: Word; ATopic: string; APayload: TArray<System.Byte>); var msg:string; begin msg := TEncoding.UTF8.GetString(APayload); MemoLog.Lines.Add('Message received from the publisher'+#13#10+'['+ATopic+']: '+msg); end; end.
unit uSimpleDirections; interface uses SysUtils, Classes; type TSimpleStep = class(TObject) private fLocation: String; fDistanceHTML: String; fDescriptionHTML: String; fUniqueStepID: Integer; public property Location: String read FLocation write FLocation; property DescriptionHTML: String read FDescriptionHTML write FDescriptionHTML; property DistanceHTML: String read FDistanceHTML write FDistanceHTML; property UniqueStepID: Integer read fUniqueStepID write fUniqueStepID; end; TSimpleWaypoint = class(TObject) private fSteps: TList; fLocation, fAddress, fRouteDistanceHTML, fRouteDurationHTML: String; function GetStep(Index: Integer): TSimpleStep; public constructor Create(const aLocation, aAddress, aRouteDistanceHTML, aRouteDurationHTML: String); destructor Destroy; override; procedure Clear; procedure AddStep(const aLocation, aStepDescriptionHTML, aStepDistanceHTML: String; aUniqueStepID: Integer); function Count: Integer; property Steps[Index: Integer]: TSimpleStep read GetStep; property Location: String read fLocation; property Address: String read fAddress; property RouteDistanceHTML: String read fRouteDistanceHTML; property RouteDurationHTML: String read fRouteDurationHTML; end; TSimpleDirections = class(TObject) private fCurrentWaypoint: Integer; fWaypoints: TList; fUniqueStepID: Integer; function GetWaypoint(Index: Integer): TSimpleWaypoint; public constructor Create; destructor Destroy; override; procedure Clear; procedure AddWaypoint(const aLocation, aAddress, aRouteDistanceHTML, aRouteDurationHTML: String); procedure AddStep(const aLocation, aStepDescriptionHTML, aStepDistanceHTML: String); function Count: Integer; function FindStep(aUniqueStepID: Integer): TSimpleStep; property Waypoints[Index: Integer]: TSimpleWaypoint read GetWaypoint; end; implementation { TSimpleDirections } constructor TSimpleDirections.Create; begin fWaypoints := TList.Create; end; destructor TSimpleDirections.Destroy; begin Clear; fWaypoints.Free; inherited; end; function TSimpleDirections.FindStep(aUniqueStepID: Integer): TSimpleStep; var i, j: Integer; wp: TSimpleWaypoint; s: TSimpleStep; begin Result := nil; for i := 0 to Count - 1 do begin wp := Waypoints[i]; for j := 0 to wp.Count - 1 do begin s := wp.Steps[j]; if s.UniqueStepID = aUniqueStepID then begin Result := s; break; end; end; end; end; function TSimpleDirections.GetWaypoint(Index: Integer): TSimpleWaypoint; begin Result := TSimpleWaypoint(fWaypoints[Index]); end; procedure TSimpleDirections.Clear; var wp: TSimpleWaypoint; begin while fWaypoints.Count > 0 do begin wp := TSimpleWaypoint(fWaypoints[0]); wp.Free; fWaypoints.Delete(0); end; fUniqueStepID := 0; end; function TSimpleDirections.Count: Integer; begin Result := fWaypoints.Count; end; procedure TSimpleDirections.AddWaypoint(const aLocation, aAddress, aRouteDistanceHTML, aRouteDurationHTML: String); var wp: TSimpleWaypoint; begin wp := TSimpleWaypoint.Create(aLocation, aAddress, aRouteDistanceHTML, aRouteDurationHTML); fWaypoints.Add(wp); fCurrentWaypoint := fWayPoints.Count - 1; end; procedure TSimpleDirections.AddStep(const aLocation, aStepDescriptionHTML, aStepDistanceHTML: String); begin Inc(fUniqueStepID); TSimpleWaypoint(fWaypoints[fCurrentWaypoint]).AddStep(aLocation, aStepDescriptionHTML, aStepDistanceHTML, fUniqueStepID); end; { TSimpleWaypoint } constructor TSimpleWaypoint.Create(const aLocation, aAddress, aRouteDistanceHTML, aRouteDurationHTML: String); begin fSteps := TList.Create; fLocation := aLocation; fAddress := aAddress; fRouteDistanceHTML := aRouteDistanceHTML; fRouteDurationHTML := aRouteDurationHTML; end; destructor TSimpleWaypoint.Destroy; begin Clear; fSteps.Free; inherited; end; function TSimpleWaypoint.GetStep(Index: Integer): TSimpleStep; begin Result := TSimpleStep(fSteps[Index]); end; procedure TSimpleWaypoint.Clear; var s: TSimpleStep; begin while fSteps.Count > 0 do begin s := TSimpleStep(fSteps[0]); s.Free; fSteps.Delete(0); end; end; function TSimpleWaypoint.Count: Integer; begin Result := fSteps.Count; end; procedure TSimpleWaypoint.AddStep(const aLocation, aStepDescriptionHTML, aStepDistanceHTML: String; aUniqueStepID: Integer); var s: TSimpleStep; begin s := TSimpleStep.Create; s.Location := aLocation; s.DescriptionHTML := aStepDescriptionHTML; s.DistanceHTML := aStepDistanceHTML; s.UniqueStepID := aUniqueStepID; fSteps.Add(s); end; end.
unit OpenGLEngine; interface uses Windows, OpenGL; // Устанавливаем формат пикселей procedure setupPixelFormat(DC:HDC); // инциализируем OpenGL procedure GLInit; implementation procedure setupPixelFormat(DC:HDC); const pfd:TPIXELFORMATDESCRIPTOR = ( nSize:sizeof(TPIXELFORMATDESCRIPTOR); // size nVersion:1; // version dwFlags:PFD_SUPPORT_OPENGL or PFD_DRAW_TO_WINDOW or PFD_DOUBLEBUFFER; // support double-buffering iPixelType:PFD_TYPE_RGBA; // color type cColorBits:24; // preferred color depth cRedBits:0; cRedShift:0; // color bits (ignored) cGreenBits:0; cGreenShift:0; cBlueBits:0; cBlueShift:0; cAlphaBits:0; cAlphaShift:0; // no alpha buffer cAccumBits: 0; cAccumRedBits: 0; // no accumulation buffer, cAccumGreenBits: 0; // accum bits (ignored) cAccumBlueBits: 0; cAccumAlphaBits: 0; cDepthBits:16; // depth buffer cStencilBits:0; // no stencil buffer cAuxBuffers:0; // no auxiliary buffers iLayerType:PFD_MAIN_PLANE; // main layer bReserved: 0; dwLayerMask: 0; dwVisibleMask: 0; dwDamageMask: 0; // no layer, visible, damage masks ); var pixelFormat:integer; begin pixelFormat := ChoosePixelFormat(DC, @pfd); if (pixelFormat = 0) then exit; if (SetPixelFormat(DC, pixelFormat, @pfd) <> TRUE) then exit; end; procedure GLInit; begin // Установка матирицы вида glMatrixMode(GL_PROJECTION); glFrustum(-0.1, 0.1, -0.1, 0.1, 0.3, 25.0); // position viewer glMatrixMode(GL_MODELVIEW); glEnable(GL_DEPTH_TEST); end; end.
{ *********************************************************************** } { } { Delphi Runtime Library } { } { Copyright (c) 1995-2001 Borland Software Corporation } { } { *********************************************************************** } {*******************************************************} { Conversions engine, no built in conversion types } {*******************************************************} unit ConvUtils; interface uses SysUtils, Math, Types; type TConvFamily = type Word; TConvType = type Word; TConversionProc = function(const AValue: Double): Double; TConvTypeArray = array of TConvType; TConvFamilyArray = array of TConvFamily; // Simple conversion between two measurement types function Convert(const AValue: Double; const AFrom, ATo: TConvType): Double; overload; // Complex conversion between two double measurement types. An example of // this would be converting miles per hour to meters per minute (speed) or // gallons per minute to liters per hour (flow). There are lots of // combinations but not all of them make much sense. function Convert(const AValue: Double; const AFrom1, AFrom2, ATo1, ATo2: TConvType): Double; overload; // Convert from and to the base unit type for a particular conversion family function ConvertFrom(const AFrom: TConvType; const AValue: Double): Double; function ConvertTo(const AValue: Double; const ATo: TConvType): Double; // Add/subtract two values together and return the result in a specified type function ConvUnitAdd(const AValue1: Double; const AType1: TConvType; const AValue2: Double; const AType2, AResultType: TConvType): Double; function ConvUnitDiff(const AValue1: Double; const AType1: TConvType; const AValue2: Double; const AType2, AResultType: TConvType): Double; // Increment/decrement a value by a value of a specified type function ConvUnitInc(const AValue: Double; const AType, AAmountType: TConvType): Double; overload; function ConvUnitInc(const AValue: Double; const AType: TConvType; const AAmount: Double; const AAmountType: TConvType): Double; overload; function ConvUnitDec(const AValue: Double; const AType, AAmountType: TConvType): Double; overload; function ConvUnitDec(const AValue: Double; const AType: TConvType; const AAmount: Double; const AAmountType: TConvType): Double; overload; // Test to see if a given value is within the previous (or next) given units of // of a certian type function ConvUnitWithinPrevious(const AValue, ATest: Double; const AType: TConvType; const AAmount: Double; const AAmountType: TConvType): Boolean; function ConvUnitWithinNext(const AValue, ATest: Double; const AType: TConvType; const AAmount: Double; const AAmountType: TConvType): Boolean; // Comparison and Equality testing function ConvUnitCompareValue(const AValue1: Double; const AType1: TConvType; const AValue2: Double; const AType2: TConvType): TValueRelationship; function ConvUnitSameValue(const AValue1: Double; const AType1: TConvType; const AValue2: Double; const AType2: TConvType): Boolean; // (un)Registation of conversion types. You should unregister your conversion // types when the unit that registered them is finalized or is no longer used. function RegisterConversionType(const AFamily: TConvFamily; const ADescription: string; const AFactor: Double): TConvType; overload; function RegisterConversionType(const AFamily: TConvFamily; const ADescription: string; const AToCommonProc, AFromCommonProc: TConversionProc): TConvType; overload; procedure UnregisterConversionType(const AType: TConvType); // (un)Registation of conversion families. You should unregister your // conversion families when the unit that registered them is finalized or is // no longer used. function RegisterConversionFamily(const ADescription: string): TConvFamily; procedure UnregisterConversionFamily(const AFamily: TConvFamily); // Compatibility testing function CompatibleConversionTypes(const AFrom, ATo: TConvType): Boolean; function CompatibleConversionType(const AType: TConvType; const AFamily: TConvFamily): Boolean; // Discovery support functions procedure GetConvTypes(const AFamily: TConvFamily; out ATypes: TConvTypeArray); procedure GetConvFamilies(out AFamilies: TConvFamilyArray); // String parsing support function StrToConvUnit(AText: string; out AType: TConvType): Double; function TryStrToConvUnit(AText: string; out AValue: Double; out AType: TConvType): Boolean; function ConvUnitToStr(const AValue: Double; const AType: TConvType): string; // Description format/parsing function function ConvTypeToDescription(const AType: TConvType): string; function ConvFamilyToDescription(const AFamily: TConvFamily): string; function DescriptionToConvType(const ADescription: string; out AType: TConvType): Boolean; overload; function DescriptionToConvType(const AFamily: TConvFamily; const ADescription: string; out AType: TConvType): Boolean; overload; function DescriptionToConvFamily(const ADescription: string; out AFamily: TConvFamily): Boolean; // ConvType to Family support function ConvTypeToFamily(const AType: TConvType): TConvFamily; overload; function TryConvTypeToFamily(const AType: TConvType; out AFamily: TConvFamily): Boolean; overload; function ConvTypeToFamily(const AFrom, ATo: TConvType): TConvFamily; overload; function TryConvTypeToFamily(const AFrom, ATo: TConvType; out AFamily: TConvFamily): Boolean; overload; // Error procs procedure RaiseConversionError(const AText: string); overload; procedure RaiseConversionError(const AText: string; const AArgs: array of const); overload; procedure RaiseConversionRegError(AFamily: TConvFamily; const ADescription: string); type EConversionError = class(Exception); const CIllegalConvFamily: TConvFamily = 0; CIllegalConvType: TConvType = 0; var GConvUnitToStrFmt: string = '%f %s'; // Custom conversion type support type TConvTypeInfo = class(TObject) private FDescription: string; FConvFamily: TConvFamily; FConvType: TConvType; public constructor Create(const AConvFamily: TConvFamily; const ADescription: string); function ToCommon(const AValue: Double): Double; virtual; abstract; function FromCommon(const AValue: Double): Double; virtual; abstract; property ConvFamily: TConvFamily read FConvFamily; property ConvType: TConvType read FConvType; property Description: string read FDescription; end; TConvTypeList = array of TConvTypeInfo; TConvTypeFactor = class(TConvTypeInfo) private FFactor: Double; protected property Factor: Double read FFactor; public constructor Create(const AConvFamily: TConvFamily; const ADescription: string; const AFactor: Double); function ToCommon(const AValue: Double): Double; override; function FromCommon(const AValue: Double): Double; override; end; TConvTypeProcs = class(TConvTypeInfo) private FToCommonProc: TConversionProc; FFromCommonProc: TConversionProc; public constructor Create(const AConvFamily: TConvFamily; const ADescription: string; const AToCommonProc, AFromCommonProc: TConversionProc); function ToCommon(const AValue: Double): Double; override; function FromCommon(const AValue: Double): Double; override; end; function RegisterConversionType(AConvTypeInfo: TConvTypeInfo; out AType: TConvType): Boolean; overload; implementation uses RTLConsts; const CListGrowthDelta = 16; // Comprehension of the following types and functions are not required in // order to use this unit. They are provided as a way to iterate through // the declared conversion families and types. type TConvFamilyInfo = class(TObject) private FDescription: string; FConvFamily: TConvFamily; public constructor Create(const AConvFamily: TConvFamily; const ADescription: string); property ConvFamily: TConvFamily read FConvFamily; property Description: string read FDescription; end; TConvFamilyList = array of TConvFamilyInfo; var GConvFamilyList: TConvFamilyList; GConvTypeList: TConvTypeList; GLastConvFamily: TConvFamily; GLastConvType: TConvType; GConvFamilySync: TMultiReadExclusiveWriteSynchronizer; GConvTypeSync: TMultiReadExclusiveWriteSynchronizer; procedure RaiseConversionError(const AText: string); begin raise EConversionError.Create(AText); end; procedure RaiseConversionError(const AText: string; const AArgs: array of const); begin raise EConversionError.CreateFmt(AText, AArgs); end; procedure RaiseConversionRegError(AFamily: TConvFamily; const ADescription: string); begin RaiseConversionError(SConvDuplicateType, [ADescription, ConvFamilyToDescription(AFamily)]); end; function GetConvFamilyInfo(const AFamily: TConvFamily; out AConvFamilyInfo: TConvFamilyInfo): Boolean; begin GConvFamilySync.BeginRead; try Result := AFamily < Length(GConvFamilyList); if Result then begin AConvFamilyInfo := GConvFamilyList[AFamily]; Result := Assigned(AConvFamilyInfo); end; finally GConvFamilySync.EndRead; end; end; function GetConvInfo(const AType: TConvType; out AConvTypeInfo: TConvTypeInfo): Boolean; overload; begin GConvTypeSync.BeginRead; try Result := AType < Length(GConvTypeList); if Result then begin AConvTypeInfo := GConvTypeList[AType]; Result := Assigned(AConvTypeInfo); end; finally GConvTypeSync.EndRead; end; end; function GetConvInfo(const AType: TConvType; out AConvTypeInfo: TConvTypeInfo; out AConvFamilyInfo: TConvFamilyInfo): Boolean; overload; begin Result := GetConvInfo(AType, AConvTypeInfo) and GetConvFamilyInfo(AConvTypeInfo.ConvFamily, AConvFamilyInfo); end; function GetConvInfo(const AType: TConvType; out AConvFamilyInfo: TConvFamilyInfo): Boolean; overload; var LConvTypeInfo: TConvTypeInfo; begin Result := GetConvInfo(AType, LConvTypeInfo) and GetConvFamilyInfo(LConvTypeInfo.ConvFamily, AConvFamilyInfo); end; function GetConvInfo(const AFrom, ATo: TConvType; out AFromTypeInfo, AToTypeInfo: TConvTypeInfo; out AConvFamilyInfo: TConvFamilyInfo): Boolean; overload; var LFromFamilyInfo: TConvFamilyInfo; begin Result := GetConvInfo(AFrom, AFromTypeInfo, LFromFamilyInfo) and GetConvInfo(ATo, AToTypeInfo, AConvFamilyInfo) and (AConvFamilyInfo = LFromFamilyInfo); end; function GetConvInfo(const AFrom, ATo: TConvType; out AFromTypeInfo, AToTypeInfo: TConvTypeInfo): Boolean; overload; begin Result := GetConvInfo(AFrom, AFromTypeInfo) and GetConvInfo(ATo, AToTypeInfo) and (AFromTypeInfo.ConvFamily = AToTypeInfo.ConvFamily); end; function GetConvInfo(const AFrom, ATo, AResult: TConvType; out AFromTypeInfo, AToTypeInfo, AResultTypeInfo: TConvTypeInfo): Boolean; overload; begin Result := GetConvInfo(AFrom, AFromTypeInfo) and GetConvInfo(ATo, AToTypeInfo) and GetConvInfo(AResult, AResultTypeInfo) and (AFromTypeInfo.ConvFamily = AToTypeInfo.ConvFamily) and (AToTypeInfo.ConvFamily = AResultTypeInfo.ConvFamily); end; function GetConvInfo(const AFrom, ATo: TConvType; out AConvFamilyInfo: TConvFamilyInfo): Boolean; overload; var LFromFamilyInfo: TConvFamilyInfo; begin Result := GetConvInfo(AFrom, LFromFamilyInfo) and GetConvInfo(ATo, AConvFamilyInfo) and (AConvFamilyInfo = LFromFamilyInfo); end; function ConvTypeToFamily(const AType: TConvType): TConvFamily; begin if not TryConvTypeToFamily(AType, Result) then RaiseConversionError(SConvUnknownType, [Format(SConvUnknownDescriptionWithPrefix, [HexDisplayPrefix, AType])]); end; function TryConvTypeToFamily(const AType: TConvType; out AFamily: TConvFamily): Boolean; var LTypeInfo: TConvTypeInfo; begin Result := GetConvInfo(AType, LTypeInfo); if Result then AFamily := LTypeInfo.ConvFamily; end; function ConvTypeToFamily(const AFrom, ATo: TConvType): TConvFamily; begin if not TryConvTypeToFamily(AFrom, ATo, Result) then RaiseConversionError(SConvIncompatibleTypes2, [ConvTypeToDescription(AFrom), ConvTypeToDescription(ATo)]); end; function TryConvTypeToFamily(const AFrom, ATo: TConvType; out AFamily: TConvFamily): Boolean; var LFromTypeInfo, LToTypeInfo: TConvTypeInfo; begin Result := GetConvInfo(AFrom, LFromTypeInfo) and GetConvInfo(ATo, LToTypeInfo) and (LFromTypeInfo.ConvFamily = LToTypeInfo.ConvFamily); if Result then AFamily := LFromTypeInfo.ConvFamily; end; function CompatibleConversionTypes(const AFrom, ATo: TConvType): Boolean; var LFamily: TConvFamily; begin Result := TryConvTypeToFamily(AFrom, ATo, LFamily); end; function CompatibleConversionType(const AType: TConvType; const AFamily: TConvFamily): Boolean; var LTypeInfo: TConvTypeInfo; begin if not GetConvInfo(AType, LTypeInfo) then RaiseConversionError(SConvUnknownType, [Format(SConvUnknownDescriptionWithPrefix, [HexDisplayPrefix, AType])]); Result := LTypeInfo.ConvFamily = AFamily; end; function Convert(const AValue: Double; const AFrom, ATo: TConvType): Double; var LFromTypeInfo, LToTypeInfo: TConvTypeInfo; begin if not GetConvInfo(AFrom, ATo, LFromTypeInfo, LToTypeInfo) then RaiseConversionError(SConvIncompatibleTypes2, [ConvTypeToDescription(AFrom), ConvTypeToDescription(ATo)]); Result := LToTypeInfo.FromCommon(LFromTypeInfo.ToCommon(AValue)); end; function Convert(const AValue: Double; const AFrom1, AFrom2, ATo1, ATo2: TConvType): Double; begin Result := Convert(Convert(AValue, AFrom1, ATo1), ATo2, AFrom2); end; function ConvertFrom(const AFrom: TConvType; const AValue: Double): Double; var LFromTypeInfo: TConvTypeInfo; begin if not GetConvInfo(AFrom, LFromTypeInfo) then RaiseConversionError(SConvUnknownType, [Format(SConvUnknownDescriptionWithPrefix, [HexDisplayPrefix, AFrom])]); Result := LFromTypeInfo.ToCommon(AValue); end; function ConvertTo(const AValue: Double; const ATo: TConvType): Double; var LToTypeInfo: TConvTypeInfo; begin if not GetConvInfo(ATo, LToTypeInfo) then RaiseConversionError(SConvUnknownType, [Format(SConvUnknownDescriptionWithPrefix, [HexDisplayPrefix, ATo])]); Result := LToTypeInfo.FromCommon(AValue); end; function ConvUnitAdd(const AValue1: Double; const AType1: TConvType; const AValue2: Double; const AType2, AResultType: TConvType): Double; var LType1Info, LType2Info, LResultTypeInfo: TConvTypeInfo; begin if not GetConvInfo(AType1, AType2, AResultType, LType1Info, LType2Info, LResultTypeInfo) then RaiseConversionError(SConvIncompatibleTypes3, [ConvTypeToDescription(AType1), ConvTypeToDescription(AType2), ConvTypeToDescription(AResultType)]); Result := LResultTypeInfo.FromCommon(LType1Info.ToCommon(AValue1) + LType2Info.ToCommon(AValue2)); end; function ConvUnitDiff(const AValue1: Double; const AType1: TConvType; const AValue2: Double; const AType2, AResultType: TConvType): Double; begin Result := ConvUnitAdd(AValue1, AType1, -AValue2, AType2, AResultType); end; function ConvUnitInc(const AValue: Double; const AType, AAmountType: TConvType): Double; begin Result := ConvUnitInc(AValue, AType, 1, AAmountType); end; function ConvUnitInc(const AValue: Double; const AType: TConvType; const AAmount: Double; const AAmountType: TConvType): Double; var LTypeInfo, LAmountTypeInfo: TConvTypeInfo; begin if not GetConvInfo(AType, AAmountType, LTypeInfo, LAmountTypeInfo) then RaiseConversionError(SConvIncompatibleTypes2, [ConvTypeToDescription(AType), ConvTypeToDescription(AAmountType)]); Result := AValue + LTypeInfo.FromCommon(LAmountTypeInfo.ToCommon(AAmount)); end; function ConvUnitDec(const AValue: Double; const AType, AAmountType: TConvType): Double; begin Result := ConvUnitInc(AValue, AType, -1, AAmountType); end; function ConvUnitDec(const AValue: Double; const AType: TConvType; const AAmount: Double; const AAmountType: TConvType): Double; begin Result := ConvUnitInc(AValue, AType, -AAmount, AAmountType); end; function ConvUnitWithinPrevious(const AValue, ATest: Double; const AType: TConvType; const AAmount: Double; const AAmountType: TConvType): Boolean; begin Result := (ATest <= AValue) and (ATest >= ConvUnitDec(AValue, AType, AAmount, AAmountType)); end; function ConvUnitWithinNext(const AValue, ATest: Double; const AType: TConvType; const AAmount: Double; const AAmountType: TConvType): Boolean; begin Result := (ATest >= AValue) and (ATest <= ConvUnitInc(AValue, AType, AAmount, AAmountType)); end; function ConvUnitCompareValue(const AValue1: Double; const AType1: TConvType; const AValue2: Double; const AType2: TConvType): TValueRelationship; var LType1Info, LType2Info: TConvTypeInfo; begin if not GetConvInfo(AType1, AType2, LType1Info, LType2Info) then RaiseConversionError(SConvIncompatibleTypes2, [ConvTypeToDescription(AType1), ConvTypeToDescription(AType2)]); Result := CompareValue(LType1Info.ToCommon(AValue1), LType2Info.ToCommon(AValue2)); end; function ConvUnitSameValue(const AValue1: Double; const AType1: TConvType; const AValue2: Double; const AType2: TConvType): Boolean; var LType1Info, LType2Info: TConvTypeInfo; begin if not GetConvInfo(AType1, AType2, LType1Info, LType2Info) then RaiseConversionError(SConvIncompatibleTypes2, [ConvTypeToDescription(AType1), ConvTypeToDescription(AType2)]); Result := SameValue(LType1Info.ToCommon(AValue1), LType2Info.ToCommon(AValue2)); end; function RegisterConversionType(AConvTypeInfo: TConvTypeInfo; out AType: TConvType): Boolean; begin GConvTypeSync.BeginWrite; try Result := not DescriptionToConvType(AConvTypeInfo.ConvFamily, AConvTypeInfo.Description, AType); if Result then begin Inc(GLastConvType); if GLastConvType > Length(GConvTypeList) - 1 then SetLength(GConvTypeList, GLastConvType + CListGrowthDelta); AType := GLastConvType; AConvTypeInfo.FConvType := AType; GConvTypeList[AType] := AConvTypeInfo; end; finally GConvTypeSync.EndWrite; end; end; function RegisterConversionType(const AFamily: TConvFamily; const ADescription: string; const AFactor: Double): TConvType; var LInfo: TConvTypeInfo; begin LInfo := TConvTypeFactor.Create(AFamily, ADescription, AFactor); if not RegisterConversionType(LInfo, Result) then begin LInfo.Free; RaiseConversionRegError(AFamily, ADescription); end; end; function RegisterConversionType(const AFamily: TConvFamily; const ADescription: string; const AToCommonProc, AFromCommonProc: TConversionProc): TConvType; var LInfo: TConvTypeInfo; begin LInfo := TConvTypeProcs.Create(AFamily, ADescription, AToCommonProc, AFromCommonProc); if not RegisterConversionType(LInfo, Result) then begin LInfo.Free; RaiseConversionRegError(AFamily, ADescription); end; end; procedure FreeConversionType(const AType: TConvType); var LConvTypeInfo: TConvTypeInfo; begin if GetConvInfo(AType, LConvTypeInfo) then begin GConvTypeList[AType] := nil; LConvTypeInfo.Free; end; end; procedure UnregisterConversionType(const AType: TConvType); begin GConvTypeSync.BeginWrite; try FreeConversionType(AType); finally GConvTypeSync.EndWrite; end; end; function RegisterConversionFamily(const ADescription: string): TConvFamily; var LFamily: TConvFamily; begin GConvFamilySync.BeginWrite; try if DescriptionToConvFamily(ADescription, LFamily) then RaiseConversionError(SConvDuplicateFamily, [ADescription]); Inc(GLastConvFamily); if GLastConvFamily > Length(GConvFamilyList) - 1 then SetLength(GConvFamilyList, GLastConvFamily + CListGrowthDelta); Result := GLastConvFamily; GConvFamilyList[Result] := TConvFamilyInfo.Create(Result, ADescription); finally GConvFamilySync.EndWrite; end; end; procedure UnregisterConversionFamily(const AFamily: TConvFamily); var I: Integer; LConvFamilyInfo: TConvFamilyInfo; begin GConvFamilySync.BeginWrite; try if GetConvFamilyInfo(AFamily, LConvFamilyInfo) then begin GConvTypeSync.BeginWrite; try for I := 0 to Length(GConvTypeList) - 1 do if Assigned(GConvTypeList[I]) and (GConvTypeList[I].FConvFamily = AFamily) then FreeConversionType(I); finally GConvTypeSync.EndWrite; end; GConvFamilyList[AFamily] := nil; LConvFamilyInfo.Free; end; finally GConvFamilySync.EndWrite; end; end; procedure CleanUpLists; var I: Integer; LConvFamilyInfo: TConvFamilyInfo; LConvTypeInfo: TConvTypeInfo; begin GConvTypeSync.BeginWrite; try for I := 0 to Length(GConvTypeList) - 1 do begin LConvTypeInfo := GConvTypeList[I]; if Assigned(LConvTypeInfo) then begin GConvTypeList[I] := nil; LConvTypeInfo.Free; end; end; SetLength(GConvTypeList, 0); finally GConvTypeSync.EndWrite; end; GConvFamilySync.BeginWrite; try for I := 0 to Length(GConvFamilyList) - 1 do begin LConvFamilyInfo := GConvFamilyList[I]; if Assigned(LConvFamilyInfo) then begin GConvFamilyList[I] := nil; LConvFamilyInfo.Free; end; end; SetLength(GConvFamilyList, 0); finally GConvFamilySync.EndWrite; end; end; { TConvFamilyInfo } constructor TConvFamilyInfo.Create(const AConvFamily: TConvFamily; const ADescription: string); begin inherited Create; FConvFamily := AConvFamily; FDescription := ADescription; end; { TConvTypeInfo } constructor TConvTypeInfo.Create(const AConvFamily: TConvFamily; const ADescription: string); var LConvFamilyInfo: TConvFamilyInfo; begin inherited Create; if not GetConvFamilyInfo(AConvFamily, LConvFamilyInfo) then RaiseConversionError(SConvUnknownFamily, [Format(SConvUnknownDescriptionWithPrefix, [HexDisplayPrefix, AConvFamily])]); FConvFamily := AConvFamily; FDescription := ADescription; end; { TConvTypeFactor } constructor TConvTypeFactor.Create(const AConvFamily: TConvFamily; const ADescription: string; const AFactor: Double); begin inherited Create(AConvFamily, ADescription); if AFactor = 0 then raise EZeroDivide.CreateFmt(SConvFactorZero, [ADescription]); FFactor := AFactor; end; function TConvTypeFactor.FromCommon(const AValue: Double): Double; begin Result := AValue / FFactor; end; function TConvTypeFactor.ToCommon(const AValue: Double): Double; begin Result := AValue * FFactor; end; { TConvTypeProcs } constructor TConvTypeProcs.Create(const AConvFamily: TConvFamily; const ADescription: string; const AToCommonProc, AFromCommonProc: TConversionProc); begin inherited Create(AConvFamily, ADescription); FToCommonProc := AToCommonProc; FFromCommonProc := AFromCommonProc; end; function TConvTypeProcs.FromCommon(const AValue: Double): Double; begin Result := FFromCommonProc(AValue); end; function TConvTypeProcs.ToCommon(const AValue: Double): Double; begin Result := FToCommonProc(AValue); end; // Conversion support function StrToConvUnit(AText: string; out AType: TConvType): Double; begin if not TryStrToConvUnit(AText, Result, AType) then RaiseConversionError(SConvStrParseError, [AText]); end; function TryStrToConvUnit(AText: string; out AValue: Double; out AType: TConvType): Boolean; var LSpaceAt: Integer; LType: string; LValue: Extended; begin AText := TrimLeft(AText); LSpaceAt := Pos(' ', AText); if LSpaceAt > 0 then begin Result := TryStrToFloat(Copy(AText, 1, LSpaceAt - 1), LValue); if Result then begin LType := Trim(Copy(AText, LSpaceAt + 1, MaxInt)); Result := (LType <> '') and DescriptionToConvType(LType, AType); end; end else begin AType := CIllegalConvType; Result := TryStrToFloat(AText, LValue); end; if Result then AValue := LValue; end; function ConvUnitToStr(const AValue: Double; const AType: TConvType): string; begin Result := Format(GConvUnitToStrFmt, [AValue, ConvTypeToDescription(AType)]); end; // Discovery support functions procedure GetConvTypes(const AFamily: TConvFamily; out ATypes: TConvTypeArray); var I, LCount: Integer; begin GConvTypeSync.BeginRead; try LCount := 0; for I := 0 to Length(GConvTypeList) - 1 do if Assigned(GConvTypeList[I]) and (GConvTypeList[I].ConvFamily = AFamily) then Inc(LCount); SetLength(ATypes, LCount); LCount := 0; for I := 0 to Length(GConvTypeList) - 1 do if Assigned(GConvTypeList[I]) and (GConvTypeList[I].ConvFamily = AFamily) then begin ATypes[LCount] := GConvTypeList[I].ConvType; Inc(LCount); end; finally GConvTypeSync.EndRead; end; end; procedure GetConvFamilies(out AFamilies: TConvFamilyArray); var I, LCount: Integer; begin GConvFamilySync.BeginRead; try LCount := 0; for I := 0 to Length(GConvFamilyList) - 1 do if Assigned(GConvFamilyList[I]) then Inc(LCount); SetLength(AFamilies, LCount); LCount := 0; for I := 0 to Length(GConvFamilyList) - 1 do if Assigned(GConvFamilyList[I]) then begin AFamilies[LCount] := GConvFamilyList[I].ConvFamily; Inc(LCount); end; finally GConvFamilySync.EndRead; end; end; function ConvTypeToDescription(const AType: TConvType): string; var LConvTypeInfo: TConvTypeInfo; begin if AType = CIllegalConvType then Result := SConvIllegalType else if GetConvInfo(AType, LConvTypeInfo) then Result := LConvTypeInfo.Description else Result := Format(SConvUnknownDescriptionWithPrefix, [HexDisplayPrefix, AType]); end; function ConvFamilyToDescription(const AFamily: TConvFamily): string; var LConvFamilyInfo: TConvFamilyInfo; begin if AFamily = CIllegalConvFamily then Result := SConvIllegalFamily else if GetConvFamilyInfo(AFamily, LConvFamilyInfo) then Result := LConvFamilyInfo.Description else Result := Format(SConvUnknownDescriptionWithPrefix, [HexDisplayPrefix, AFamily]); end; function DescriptionToConvType(const ADescription: string; out AType: TConvType): Boolean; var I: Integer; begin Result := False; GConvTypeSync.BeginRead; try for I := 0 to Length(GConvTypeList) - 1 do if Assigned(GConvTypeList[I]) and AnsiSameText(ADescription, GConvTypeList[I].Description) then begin // if duplicate is found if Result then begin Result := False; Exit; end; AType := I; Result := True; end; finally GConvTypeSync.EndRead; end; end; function DescriptionToConvType(const AFamily: TConvFamily; const ADescription: string; out AType: TConvType): Boolean; var I: Integer; begin Result := False; GConvTypeSync.BeginRead; try for I := 0 to Length(GConvTypeList) - 1 do if Assigned(GConvTypeList[I]) and (GConvTypeList[I].ConvFamily = AFamily) and AnsiSameText(ADescription, GConvTypeList[I].Description) then begin AType := I; Result := True; Break; end; finally GConvTypeSync.EndRead; end; end; function DescriptionToConvFamily(const ADescription: string; out AFamily: TConvFamily): Boolean; var I: Integer; begin Result := False; GConvFamilySync.BeginRead; try for I := 0 to Length(GConvFamilyList) - 1 do if Assigned(GConvFamilyList[I]) and AnsiSameText(ADescription, GConvFamilyList[I].Description) then begin AFamily := I; Result := True; Break; end; finally GConvFamilySync.EndRead; end; end; initialization GConvFamilySync := TMultiReadExclusiveWriteSynchronizer.Create; GConvTypeSync := TMultiReadExclusiveWriteSynchronizer.Create; finalization CleanUpLists; FreeAndNil(GConvFamilySync); FreeAndNil(GConvTypeSync); end.
unit CheckerBoardAdapter; interface uses ExtCtrls, CBTypes, // DeepBrew DataTypes, Thinker; type TCheckerBoardAdapter = class private //FTimer : TTimer; FThinker : TThinkerThread; FSearchStartedAt : Cardinal; FLastUpdateAt : Cardinal; FSearchTime : Cardinal; FOutput : PChar; // procedure HandleTimeUp (aSender : TObject); // procedure HandleSearchEnded (aSender: TObject); function IsSquareSetOnBitBoard(const aBitBoard: TBitBoard; aSquare: Integer): Boolean; procedure SetSquareOnBitBoard(var aBitBoard: TBitBoard; aSquare: Integer); procedure ConvertToBitBoard (var aCBBoard : TCBBoard); procedure ConvertFromBitBoard (var aCBBoard : TCBBoard); procedure UpdateSearchStats; function MustStopSearch : Boolean; public constructor Create; destructor Destroy; override; procedure GetMove (var aCBBoard : TCBBoard; aCBColor : Integer; aMaxTime : Double; aStr : PChar; var aPlayNow : Boolean; aInfo : Integer ); function EngineCommand(aInput: PChar; aReply: PChar): Integer; end; implementation uses SysUtils, Windows, // DeepBrew Utils, Hashing; constructor TCheckerBoardAdapter.Create; begin PreInitialise; FThinker := TThinkerThread.Create(True); FThinker.NodeCounter := 0; FThinker.FreeOnTerminate := False; FThinker.OnCheckSearchTerminated := MustStopSearch; //FThinker.OnTerminate := HandleSearchEnded; // FTimer := TTimer.Create(nil); // FTimer.Enabled := False; // FTimer.Interval := 5000; // FTimer.OnTimer := HandleTimeUp; end; // TCheckerBoardAdapter.Create destructor TCheckerBoardAdapter.Destroy; begin try FreeAndNil (FThinker); //FreeAndNil (FTimer); finally inherited Destroy; end; end; // TCheckerBoardAdapter.Destroy //procedure TCheckerBoardAdapter.HandleTimeUp(aSender: TObject); //begin // FThinker.Terminate; //end; // TCheckerBoardAdapter.HandleTimeUp //procedure TCheckerBoardAdapter.HandleSearchEnded(aSender: TObject); //begin // //memo1.Lines.Text := GetSearchResults; // FTimer.Enabled := False; //end; // TCheckerBoardAdapter.HandleSearchEnded procedure TCheckerBoardAdapter.UpdateSearchStats; var timeSpent : Cardinal; nodesPerSec : Cardinal; result : string; begin timeSpent := (FSearchStartedAt - GetTickCount) div 1000; nodesPerSec := (FThinker.NodeCounter div timeSpent); // TODO use Format result := 'Best ' + MoveToString(FThinker.BestSoFar); result := result + '; Score ' + IntToStr(FThinker.Score); result := result + '; Depth ' + IntToStr(FThinker.MinDepth) + '/' + IntToStr(PeakDepth); result := result + '; ' + IntToStr(FThinker.NodeCounter) + ' nodes (' + IntToStr(nodesPerSec) + '/sec)'; result := result + '; ' + IntToStr(nHashHits) + ' hash hits'; StrCopy(FOutPut, PChar (result)); end; // TCheckerBoardAdapter.UpdateSearchStats procedure TCheckerBoardAdapter.GetMove (var aCBBoard : TCBBoard; aCBColor : Integer; aMaxTime : Double; aStr : PChar; var aPlayNow : Boolean; aInfo : Integer ); begin ConvertToBitBoard (aCBBoard); //FTimer.Interval := Trunc (aMaxTime * 1000); if aCBColor = CB_BLACK then begin Board.SideToMove := BLACK_TO_MOVE; end else if aCBColor = CB_WHITE then begin Board.SideToMove := WHITE_TO_MOVE; end; FSearchTime := Trunc(aMaxTime * 1000); FOutPut := aStr; // TODO implement aPlayNow // aInfo not used here, contains some flags (new game started etc.) //FThinker.SearchTime := Trunc (aMaxTime * 1000); FSearchStartedAt := GetTickCount; FLastUpdateAt := FSearchStartedAt; FThinker.Resume; //FTimer.Enabled := True; FThinker.WaitFor; // waits for thread to finish ConvertFromBitBoard(aCBBoard); // TODO Get rid of HandleTimeUp; put code here end; // TCheckerBoardAdapter.StartSearch procedure TCheckerBoardAdapter.SetSquareOnBitBoard ( var aBitBoard :TBitBoard; aSquare : Integer ); begin aBitBoard := (aBitBoard or (1 shl (aSquare - 1))) end; // TCheckerBoardAdapter.SetSquare function TCheckerBoardAdapter.IsSquareSetOnBitBoard( const aBitBoard : TBitBoard; aSquare : Integer ): Boolean; begin result := (aBitBoard and (1 shl (aSquare - 1))) <> 0; end; // TForm1.IsSquareOccupied procedure TCheckerBoardAdapter.ConvertToBitBoard(var aCBBoard: TCBBoard); var i : Integer; square : Integer; begin Board.BlackPieces := 0; Board.BlackKings := 0; Board.WhitePieces := 0; Board.WhiteKings := 0; for i := 1 to 32 do begin square := GetCBSquare(aCBBoard, i); case square of CB_MAN or CB_WHITE : SetSquareOnBitBoard (Board.WhitePieces, i); CB_MAN or CB_BLACK : SetSquareOnBitBoard (Board.BlackPieces, i); CB_KING or CB_WHITE: SetSquareOnBitBoard (Board.WhiteKings, i); CB_KING or CB_BLACK: SetSquareOnBitBoard (Board.BlackKings, i); end; end; end; // TCheckerBoardAdapter.ConvertToBitBoard procedure TCheckerBoardAdapter.ConvertFromBitBoard(var aCBBoard: TCBBoard); var i : Integer; begin for i := 1 to 32 do begin if IsSquareSetOnBitBoard (Board.WhitePieces, i) then begin SetCBSquare(aCBBoard, i, CB_MAN or CB_WHITE); end else if IsSquareSetOnBitBoard (Board.BlackPieces, i) then begin SetCBSquare(aCBBoard, i, CB_MAN or CB_BLACK); end else if IsSquareSetOnBitBoard (Board.WhiteKings, i) then begin SetCBSquare(aCBBoard, i, CB_KING or CB_WHITE); end else if IsSquareSetOnBitBoard (Board.BlackKings, i) then begin SetCBSquare(aCBBoard, i, CB_KING or CB_BLACK); end; end; end; // TCheckerBoardAdapter.ConvertFromBitBoard function TCheckerBoardAdapter.MustStopSearch: Boolean; begin result := GetTickCount - FSearchStartedAt > FSearchTime; // Update search stats only every 500 ms as expensive operation if GetTickCount - FSearchStartedAt > 500 then begin FSearchStartedAt := GetTickCount; UpdateSearchStats; end; end; // TCheckerBoardAdapter.MustStopSearch function TCheckerBoardAdapter.EngineCommand(aInput, aReply: PChar): Integer; begin if (Pos('name', aInput) > 0) then begin StrCopy(aReply, 'Deep Brew 1.1'); result := Ord(True); end else if (Pos('get gametype', aInput ) > 0) then begin StrCopy(aReply, '21'); result := Ord(True); end else if (Pos('get protocolversion', aInput) > 0) then begin StrCopy(aReply, '2'); result := Ord(True); end else begin result := Ord(False); end; end; // TCheckerBoardAdapter.EngineCommand end.
unit NtUtils.Sam.Security; interface uses Winapi.WinNt, Ntapi.ntsam, NtUtils.Exceptions, NtUtils.Security.Acl, NtUtils.Security.Sid; type TAce = NtUtils.Security.Acl.TAce; IAcl = NtUtils.Security.Acl.IAcl; TAcl = NtUtils.Security.Acl.TAcl; ISid = NtUtils.Security.Sid.ISid; { Query security } // Security descriptor (free with SamFreeMemory) function SamxQuerySecurityObject(SamHandle: TSamHandle; SecurityInformation: TSecurityInformation; out SecDesc: PSecurityDescriptor): TNtxStatus; // Owner function SamxQueryOwnerObject(SamHandle: TSamHandle; out Owner: ISid): TNtxStatus; // Primary group function SamxQueryPrimaryGroupObject(SamHandle: TSamHandle; out PrimaryGroup: ISid): TNtxStatus; // DACL function SamxQueryDaclObject(SamHandle: TSamHandle; out Dacl: IAcl): TNtxStatus; // SACL function SamxQuerySaclObject(SamHandle: TSamHandle; out Sacl: IAcl): TNtxStatus; // Mandatory label function SamxQueryLabelObject(SamHandle: TSamHandle; out Sacl: IAcl): TNtxStatus; { Set security } // Security descriptor function SamxSetSecurityObject(SamHandle: TSamHandle; SecInfo: TSecurityInformation; const SecDesc: TSecurityDescriptor): TNtxStatus; // Owner function SamxSetOwnerObject(SamHandle: TSamHandle; Owner: ISid): TNtxStatus; // Primary group function SamxSetPrimaryGroupObject(SamHandle: TSamHandle; Group: ISid): TNtxStatus; // DACL function SamxSetDaclObject(SamHandle: TSamHandle; Dacl: IAcl): TNtxStatus; // SACL function SamxSetSaclObject(SamHandle: TSamHandle; Sacl: IAcl): TNtxStatus; // Mandatory label function SamxSetLabelObject(SamHandle: TSamHandle; Sacl: IAcl): TNtxStatus; implementation { Query security } // Security descriptor (free with SamFreeMemory) function SamxQuerySecurityObject(SamHandle: TSamHandle; SecurityInformation: TSecurityInformation; out SecDesc: PSecurityDescriptor): TNtxStatus; begin Result.Location := 'SamQuerySecurityObject'; Result.LastCall.Expects(RtlxComputeReadAccess(SecurityInformation), @NonSpecificAccessType); Result.Status := SamQuerySecurityObject(SamHandle, SecurityInformation, SecDesc); end; // Owner function SamxQueryOwnerObject(SamHandle: TSamHandle; out Owner: ISid): TNtxStatus; var pSD: PSecurityDescriptor; begin Result := SamxQuerySecurityObject(SamHandle, OWNER_SECURITY_INFORMATION, pSD); if not Result.IsSuccess then Exit; Result := RtlxGetOwnerSD(pSD, Owner); SamFreeMemory(pSD); end; // Primary group function SamxQueryPrimaryGroupObject(SamHandle: TSamHandle; out PrimaryGroup: ISid): TNtxStatus; var pSD: PSecurityDescriptor; begin Result := SamxQuerySecurityObject(SamHandle, GROUP_SECURITY_INFORMATION, pSD); if not Result.IsSuccess then Exit; Result := RtlxGetPrimaryGroupSD(pSD, PrimaryGroup); SamFreeMemory(pSD); end; // DACL function SamxQueryDaclObject(SamHandle: TSamHandle; out Dacl: IAcl): TNtxStatus; var pSD: PSecurityDescriptor; begin Result := SamxQuerySecurityObject(SamHandle, DACL_SECURITY_INFORMATION, pSD); if not Result.IsSuccess then Exit; Result := RtlxGetDaclSD(pSD, Dacl); SamFreeMemory(pSD); end; // SACL function SamxQuerySaclObject(SamHandle: TSamHandle; out Sacl: IAcl): TNtxStatus; var pSD: PSecurityDescriptor; begin Result := SamxQuerySecurityObject(SamHandle, SACL_SECURITY_INFORMATION, pSD); if not Result.IsSuccess then Exit; Result := RtlxGetSaclSD(pSD, Sacl); SamFreeMemory(pSD); end; // Mandatory label function SamxQueryLabelObject(SamHandle: TSamHandle; out Sacl: IAcl): TNtxStatus; var pSD: PSecurityDescriptor; begin Result := SamxQuerySecurityObject(SamHandle, LABEL_SECURITY_INFORMATION, pSD); if not Result.IsSuccess then Exit; Result := RtlxGetSaclSD(pSD, Sacl); SamFreeMemory(pSD); end; { Set security } // Security descriptor function SamxSetSecurityObject(SamHandle: TSamHandle; SecInfo: TSecurityInformation; const SecDesc: TSecurityDescriptor): TNtxStatus; begin Result.Location := 'SamSetSecurityObject'; Result.LastCall.Expects(RtlxComputeWriteAccess(SecInfo), @NonSpecificAccessType); Result.Status := SamSetSecurityObject(SamHandle, SecInfo, SecDesc); end; // Owner function SamxSetOwnerObject(SamHandle: TSamHandle; Owner: ISid): TNtxStatus; var SD: TSecurityDescriptor; begin Result := RtlxPrepareOwnerSD(SD, Owner); if Result.IsSuccess then Result := SamxSetSecurityObject(SamHandle, OWNER_SECURITY_INFORMATION, SD); end; // Primary group function SamxSetPrimaryGroupObject(SamHandle: TSamHandle; Group: ISid): TNtxStatus; var SD: TSecurityDescriptor; begin Result := RtlxPreparePrimaryGroupSD(SD, Group); if Result.IsSuccess then Result := SamxSetSecurityObject(SamHandle, GROUP_SECURITY_INFORMATION, SD); end; // DACL function SamxSetDaclObject(SamHandle: TSamHandle; Dacl: IAcl): TNtxStatus; var SD: TSecurityDescriptor; begin Result := RtlxPrepareDaclSD(SD, Dacl); if Result.IsSuccess then Result := SamxSetSecurityObject(SamHandle, DACL_SECURITY_INFORMATION, SD); end; // SACL function SamxSetSaclObject(SamHandle: TSamHandle; Sacl: IAcl): TNtxStatus; var SD: TSecurityDescriptor; begin Result := RtlxPrepareSaclSD(SD, Sacl); if Result.IsSuccess then Result := SamxSetSecurityObject(SamHandle, SACL_SECURITY_INFORMATION, SD); end; // Mandatory label function SamxSetLabelObject(SamHandle: TSamHandle; Sacl: IAcl): TNtxStatus; var SD: TSecurityDescriptor; begin Result := RtlxPrepareSaclSD(SD, Sacl); if Result.IsSuccess then Result := SamxSetSecurityObject(SamHandle, LABEL_SECURITY_INFORMATION, SD); end; end.
unit MongoDb; interface uses Bson; type TMongoClient = class(TObject) private FHandle: Pointer; procedure SetHandle(const Value: Pointer); public constructor Create(const url: string='mongodb://localhost:27017/'); destructor Destroy; override; property Handle : Pointer read FHandle write SetHandle; end; TReadMode = (READ_PRIMARY, READ_SECONDARY, READ_PRIMARY_PREFERRED, READ_SECONDARY_PREFFERED, READ_NEAREST); TReadPrefs = packed record mode: TReadMode; tags: TBson; end; PTReadPrefs= ^TReadPrefs; TQUERY_FLAGS = (QUERY_NONE, QUERY_TAILABLE_CURSOR, QUERY_SLAVE_OK, QUERY_OPLOG_REPLAY, QUERY_NO_CURSOR_TIMEOUT, QUERY_AWAIT_DATA, QUERY_EXHAUST, QUERY_PARTIAL); TUPDATE_FLAGS = (UPDATE_NONE, UPDATE_INSERT, UPDATE_MULTI_UPDATE); TINSERT_FLAGS = (INSERT_NONE, INSERT_CONTINUE_ON_ERROR); TREMOVE_FLAGS = (REMOVE_NONE, REMOVE_SINGLE_REMOVE); TMongoCursor = class(TObject) private FHandle: Pointer; FBson: TBson; procedure SetHandle(const Value: Pointer); public constructor Create; destructor Destroy; override; function next: boolean; function has_next: boolean; function current: TBson; property Handle : Pointer read FHandle write SetHandle; end; TIndexOptGeo = packed record twod_sphere_version: byte; twod_bits_precision: byte; two_location_min: double; two_location_max: double; //padding byte *[32] end; TIndexOpt = packed record is_initalized: boolean; background: boolean; unique: boolean; name: PChar; drop_dups: boolean; sparse: boolean; expire_after_seconds: integer; v: integer; weight: PTBsonType; default_language: PChar; language_override: PChar; geo_options: TIndexOptGeo; storage_options: ^Integer; partial_filter_expression: PTBsonType; //padding void *[5] end; TWriteConcern = packed record fsync: shortint; journal: shortint; w: integer; wtimeout: integer; wtag: PChar; frozen: boolean; compiled: PTBsonType; compiled_gle: PTBsonType; end; PTWriteConcern= ^TWriteConcern; TMongoCollection = class(TObject) private FHandle: Pointer; FConnection: TMongoClient; FDatabase: string; FCollection: string; FQueryCount: Integer; procedure SetHandle(const Value: Pointer); public constructor Create(AConnection: TMongoClient; const ADatabase: string; const ACollection: string); destructor Destroy; override; function drop(var Error: TBsonError): boolean; function create_index(const keys: TBson; var Error: TBsonError): boolean; overload; function create_index(const keys: TBson; opt: TIndexOpt; var Error: TBsonError): boolean; overload; function drop_index(const name: string; var Error: TBsonError): boolean; function get_name: string; function get_last_error: TBson; function find_and_modify(query: TBson; sort: TBson; update: TBson; fields: TBson; remove: boolean; upsert: boolean; new: boolean; Reply: TBson; var Error: TBsonError): boolean; function find(const query: TBson; limit: longint=0): TMongoCursor; overload; function find(flag: TQUERY_FLAGS; skip: longint; limit: longint; batch_size: longint; const query: TBson; const fields: TBson; read_prefs: PTReadPrefs): TMongoCursor; overload; procedure find(ACursor: TMongoCursor; const query: TBson; limit: longint=0); overload; procedure find(ACursor: TMongoCursor; flag: TQUERY_FLAGS; skip, limit, batch_size: Integer; const query, fields: TBson; read_prefs: PTReadPrefs); overload; function find_indexes(var Error: TBsonError): TMongoCursor; function count(const query: TBson; limit: int64=0): int64; overload; function count(flag: TQUERY_FLAGS; const query: TBson; skip: int64; limit: int64; read_prefs: PTReadPrefs): int64; overload; function update(const selector: TBson; const update: TBson; var Error: TBsonError): boolean; overload; function update(flag: TUPDATE_FLAGS; const selector: TBson; const update: TBson; const write_concern: PTWriteConcern; var Error: TBsonError): boolean; overload; function insert(const document: TBson; var Error: TBsonError): boolean; overload; function insert(flag: TINSERT_FLAGS; const document: TBson; const write_concern: PTWriteConcern; var Error: TBsonError): boolean; overload; function remove(const selector: TBson; var Error: TBsonError): boolean; overload; function remove(flag: TREMOVE_FLAGS; const selector: TBson; const write_concern: PTWriteConcern; var Error: TBsonError): boolean; overload; function rename(const new_db: string; const new_name: string; drop_target_before_rename: boolean; var Error: TBsonError): boolean; function save(const document: TBson; const write_concern: PTWriteConcern; var Error: TBsonError): boolean; function copy: TMongoCollection; function command_simple(const command: TBson; const read_prefs: PTReadPrefs; var Reply: TBson; var Error: TBsonError): boolean; function validate(const options: TBSon; var Reply: TBson; var Error: TBsonError): boolean; function stats(const options: TBson; var Reply: TBson; var Error: TBsonError): boolean; property QueryCount: Integer read FQueryCount; property Handle : Pointer read FHandle write SetHandle; property Database: string read FDatabase; property Collection: string read FCollection; end; const //origin is the current c mongodb driver in version 1.3.4 MongoDll = 'libmongoc-1.0.dll'; procedure mongo_init; cdecl; external MongoDll name 'mongoc_init'; procedure mongo_cleanup; cdecl; external MongoDll name 'mongoc_cleanup'; function mongo_client_new(url: PChar): Pointer; cdecl; external MongoDll name 'mongoc_client_new'; procedure mongo_client_destroy(Handle: Pointer); cdecl; external MongoDll name 'mongoc_client_destroy'; function mongo_client_get_collection(client: Pointer; FDatabase: PChar; FCollection: PChar): Pointer; cdecl; external MongoDll name 'mongoc_client_get_collection'; procedure mongo_collection_destroy(FCollection: Pointer); cdecl; external MongoDll name 'mongoc_collection_destroy'; function mongo_collection_find(FCollection: Pointer; flag: integer; skip: longint; limit: longint; batch_size: longint; query: Pointer; fields: Pointer; read_prefs: PTReadPrefs): TMongoCursor; cdecl; external MongoDll name 'mongoc_collection_find'; function mongo_collection_drop(FCollection: Pointer; Error: PTBsonError): boolean; cdecl; external MongoDll name 'mongoc_collection_drop'; function mongo_collection_drop_index(FCollection: Pointer; const name: PChar; Error: PTBsonError): boolean; cdecl; external MongoDll name 'mongoc_collection_drop_index'; function mongo_collection_create_index(FCollection: Pointer; const keys: Pointer; opt: Pointer; Error: PTBsonError): boolean; cdecl; external MongoDll name 'mongoc_collection_create_index'; function mongo_collection_get_name(FCollection: Pointer): AnsiString; cdecl; external MongoDll name 'mongoc_collection_get_name'; function mongo_collection_count(FCollection: Pointer; const queryflag: integer; query: Pointer; skip: int64; limit: int64; const read_prefs: Pointer): int64; cdecl; external MongoDll name 'mongoc_collection_count'; function mongo_collection_update(FCollection: Pointer; updateflags: integer; const selector: Pointer; const update: Pointer; const write_concern: PTWriteConcern; Error: PTBsonError): boolean; cdecl; external MongoDll name 'mongoc_collection_update'; function mongo_collection_insert(FCollection: Pointer; insertflags: integer; const document: Pointer; const write_concern: PTWriteConcern; Error: PTBsonError): boolean; cdecl; external MongoDll name 'mongoc_collection_insert'; function mongo_collection_remove(FCollection: Pointer; removeflags: integer; const selector: Pointer; const write_concern: PTWriteConcern; Error: PTBsonError): Boolean; cdecl; external MongoDll name 'mongoc_collection_remove'; function mongo_collection_copy(FCollection: Pointer): Pointer; cdecl; external MongoDll name 'mongoc_collection_copy'; function mongo_collection_stats(FCollection: Pointer; const options: Pointer; Reply: Pointer; Error: PTBsonError): boolean; cdecl; external MongoDll name 'mongoc_collection_stats'; function mongo_collection_rename(FCollection: Pointer; const new_db: PChar; const new_name: PChar; drop_target_before_rename: boolean; Error: PTBsonError): boolean; cdecl; external MongoDll name 'mongoc_collection_rename'; function mongo_collection_save(FCollection: Pointer; document: Pointer; const write_concern: PTWriteConcern; Error: PTBsonError): boolean; cdecl; external MongoDll name 'mongoc_collection_save'; function mongo_collection_get_last_error(FCollection: Pointer): Pointer; cdecl; external MongoDll name 'mongoc_collection_get_last_error'; function mongo_collection_validate(FCollection: Pointer; options: Pointer; Reply: Pointer; Error: PTBsonError): boolean; cdecl; external MongoDll name 'mongoc_collection_validate'; function mongo_collection_command_simple(FCollection: Pointer; const command: Pointer; const read_prefs: Pointer; Reply: Pointer; Error: PTBsonError): boolean; cdecl; external MongoDll name 'mongoc_collection_command_simple'; function mongo_collection_find_indexes(FCollection: Pointer; Error: PTBsonError): Pointer; cdecl; external MongoDll name 'mongoc_collection_find_indexes'; function mongo_collection_find_and_modify(FCollection: Pointer; Query: PTBsonType; Sort: PTBsonType; Update: PTBsonType; Fields: PTBsonType; Remove: boolean; Upsert: boolean; new: boolean; Reply: PTBsonType; Error: PTBsonError): boolean; cdecl; external MongoDll name 'mongoc_collection_find_and_modify'; procedure mongo_cursor_destroy(const cursor: Pointer);cdecl; external MongoDll name 'mongoc_cursor_destroy'; function mongo_cursor_next(const cursor: Pointer; document: Pointer): Boolean; cdecl; external MongoDll name 'mongoc_cursor_next'; function mongo_cursor_has_more(const cursor: Pointer): Boolean; cdecl; external MongoDll name 'mongoc_cursor_more'; function mongo_cursor_clone(const cursor: Pointer): Pointer; external MongoDll name 'mongoc_cursor_clone'; function mongo_cursor_current(const cursor: Pointer): Pointer; cdecl; external MongoDll name 'mongoc_cursor_current'; implementation function utf8_encode(const str: string): string; begin Result:=str; end; function utf8_decode(const str: string): string; begin Result:=str; end; constructor TMongoClient.Create(const url: string='mongodb://localhost:27017/'); begin inherited Create; Handle:=mongo_client_new(PChar(utf8_encode(url))); end; destructor TMongoClient.Destroy; begin mongo_client_destroy(Handle); inherited; end; constructor TMongoCollection.Create(AConnection: TMongoClient; const ADatabase: string; const ACollection: string); var utf8_database, utf8_collection: string; begin inherited Create; utf8_database:=utf8_encode(ADatabase); utf8_collection:=utf8_encode(ACollection); FConnection:=AConnection; FDatabase:=utf8_database; FCollection:=utf8_collection; Handle:=mongo_client_get_collection(FConnection.Handle, PChar(utf8_database), PChar(utf8_collection)); end; destructor TMongoCollection.Destroy; begin mongo_collection_destroy(Handle); inherited; end; function TMongoCollection.update(const selector: TBson; const update: TBson; var Error: TBsonError): boolean; begin Result:=self.update(UPDATE_NONE, selector, update, nil, Error); end; function TMongoCollection.update(flag: TUPDATE_FLAGS; const selector: TBson; const update: TBson; const write_concern: PTWriteConcern; var Error: TBsonError): boolean; begin Result:=mongo_collection_update(Handle, ord(flag), selector.Handle, update.Handle, write_concern, @Error); end; function TMongoCollection.insert(const document: TBson; var Error: TBsonError): Boolean; begin Result:=insert(INSERT_NONE, document, nil, Error); end; function TMongoCollection.insert(flag: TINSERT_FLAGS; const document: TBson; const write_concern: PTWriteConcern; var Error: TBsonError): boolean; begin Result:=mongo_collection_insert(Handle, ord(flag), document.Handle, write_concern, @Error); end; function TMongoCollection.remove(const selector: TBson; var Error: TBsonError): boolean; begin Result:=remove(REMOVE_NONE, selector, nil, Error); end; function TMongoCollection.remove(flag: TREMOVE_FLAGS; const selector: TBson; const write_concern: PTWriteConcern; var Error: TBsonError): boolean; begin Result:=mongo_collection_remove(Handle, ord(flag), selector.Handle, write_concern, @Error); end; function TMongoCollection.rename(const new_db: string; const new_name: string; drop_target_before_rename: boolean; var Error: TBsonError): boolean; begin Result:=mongo_collection_rename(Handle, PChar(new_db), PChar(new_name), drop_target_before_rename, @Error); end; function TMongoCollection.save(const document: TBson; const write_concern: PTWriteConcern; var Error: TBsonError): boolean; begin Result:=mongo_collection_save(Handle, document.Handle, write_concern, @Error); end; function TMongoCollection.find_indexes(var Error: TBsonError): TMongoCursor; begin Result:=TMongoCursor.Create; Result.Handle:=mongo_collection_find_indexes(Handle, @Error); end; function TMongoCollection.find(const query: TBson; limit: longint=0): TMongoCursor; begin Result:=find(QUERY_NONE, 0, limit, 0, query, nil, nil); end; //helper to avoid redundancy function AccessAttributeIfPossible(bson: TBson): pointer; begin if bson <> nil then Result:=bson.Handle else Result:=bson; end; procedure TMongoCollection.find(ACursor: TMongoCursor; flag: TQUERY_FLAGS; skip: longint; limit: longint; batch_size: longint; const query: TBson; const fields: TBson; read_prefs: PTReadPrefs); var query_handle, fields_handle: pointer; number: integer; begin Inc(FQueryCount); query_handle := AccessAttributeIfPossible(query); fields_handle:= AccessAttributeIfPossible(fields); //strange but so defined in mongoc_flags.h number:=ord(flag); if number > 0 then number:=1 shl ord(flag); ACursor.Handle:=mongo_collection_find(Handle, number, skip, limit, batch_size, query_handle, fields_handle, read_prefs); end; function TMongoCollection.drop(var Error: TBsonError): boolean; begin Result:=mongo_collection_drop(Handle, @Error); end; function TMongoCollection.get_name: string; begin Result:=utf8_decode(string(mongo_collection_get_name(Handle))); end; function TMongoCollection.drop_index(const name: string; var Error: TBsonError): boolean; var utf8_name: string; begin utf8_name:=utf8_encode(name); Result:=mongo_collection_drop_index(Handle, PChar(utf8_name), @Error); end; function TMongoCollection.create_index(const keys: TBson; var Error: TBsonError): boolean; begin Result:=mongo_collection_create_index(Handle, keys.Handle, nil, @Error); end; function TMongoCollection.create_index(const keys: TBson; opt: TIndexOpt; var Error: TBsonError): boolean; begin Result:=mongo_collection_create_index(Handle, keys.Handle, @opt, @Error); end; function TMongoCollection.count(const query: TBson; limit: int64=0): int64; begin Result:=self.count(QUERY_NONE, query, 0, limit, nil); end; function TMongoCollection.count(flag: TQUERY_FLAGS; const query: TBson; skip: int64; limit: int64; read_prefs: PTReadPrefs): int64; begin Result:=mongo_collection_count(Handle, 0, query.Handle, skip, limit, read_prefs); end; function TMongoCollection.get_last_error: TBson; begin Result:=TBson.Create(mongo_collection_get_last_error(Handle)); end; function TMongoCollection.copy: TMongoCollection; begin Result:=TMongoCollection.Create(self.FConnection, self.FDatabase, self.FCollection); Result.Handle:=mongo_collection_copy(Handle); end; function TMongoCollection.command_simple(const command: TBson; const read_prefs: PTReadPrefs; var Reply: TBson; var Error: TBsonError): boolean; begin Result:=mongo_collection_command_simple(Handle, command.Handle, read_prefs, Reply.Handle, @Error); end; function TMongoCollection.validate(const options: TBson; var Reply: TBson; var Error: TBsonError): boolean; begin Result:=mongo_collection_validate(Handle, options.Handle, Reply.Handle, @Error); end; function TMongoCollection.stats(const options: TBson; var Reply: TBson; var Error: TBsonError): boolean; begin Result:=mongo_collection_stats(Handle, options.Handle, Reply.Handle, @Error); end; function TMongoCollection.find_and_modify(Query: TBson; Sort: TBson; Update: TBson; Fields: TBson; Remove: boolean; Upsert: boolean; New: boolean; Reply: TBson; var Error: TBsonError): boolean; var query_handle, sort_handle, update_handle, fields_handle, reply_handle : PTBsonType; begin query_handle:=AccessAttributeIfPossible(Query); sort_handle:=AccessAttributeIfPossible(Sort); update_handle:=AccessAttributeIfPossible(Update); fields_handle:=AccessAttributeIfPossible(Fields); reply_handle:=AccessAttributeIfPossible(Reply); Result:=mongo_collection_find_and_modify(Handle, query_handle, sort_handle, update_handle, fields_handle, Remove, Upsert, New, reply_handle, @Error); end; function TMongoCursor.has_next: boolean; begin Result:=mongo_cursor_has_more(Handle); end; function TMongoCursor.current: TBson; begin Result:=FBson; end; function TMongoCursor.next: boolean; begin Result:=mongo_cursor_next(Handle, FBson.PHandle); { if not Result then mongo_cursor_destroy(FHandle); } end; destructor TMongoCursor.Destroy; begin FBson.Free; inherited; end; constructor TMongoCursor.Create; begin if Assigned(FBson) then FBson.Free; FBson:=TBson.Create; FHandle:=nil; end; function TMongoCollection.find(flag: TQUERY_FLAGS; skip, limit, batch_size: Integer; const query, fields: TBson; read_prefs: PTReadPrefs): TMongoCursor; begin //returned instance cursor should be freed Result:=TMongoCursor.Create; find(Result, flag, skip, limit, batch_size, query, fields, read_prefs); end; procedure TMongoCollection.find(ACursor: TMongoCursor; const query: TBson; limit: Integer); begin find(ACursor, QUERY_NONE, 0, limit, 0, query, nil, nil); end; procedure TMongoCursor.SetHandle(const Value: Pointer); begin if Assigned(FHandle) then mongo_cursor_destroy(FHandle); FHandle:=Value; end; procedure TMongoClient.SetHandle(const Value: Pointer); begin if Assigned(FHandle) then mongo_client_destroy(FHandle); FHandle:=Value; end; procedure TMongoCollection.SetHandle(const Value: Pointer); begin if Assigned(FHandle) then mongo_collection_destroy(FHandle); FHandle:=Value; end; initialization mongo_init; finalization mongo_cleanup; end.
{******************************************} { Design-Time Options Editor Dialog } { Copyright (c) 2003-2004 by David Berneda } { All Rights Reserved } {******************************************} unit TeeDesignOptions; {$I TeeDefs.inc} interface uses SysUtils, Classes, {$IFDEF CLX} QGraphics, QControls, QForms, QDialogs, QStdCtrls, {$ELSE} Graphics, Controls, Forms, Dialogs, StdCtrls, {$ENDIF} TeCanvas, {$IFNDEF TEELITE} TeeTranslate, {$ENDIF} TeeProcs, TeeGalleryPanel, TeeEditCha; type TOptionsForm = class(TForm) GroupBox1: TGroupBox; Label1: TLabel; Button1: TButton; Label2: TLabel; GroupBox2: TGroupBox; CBSmooth: TCheckBox; Label3: TLabel; CBGalleryMode: TComboFlat; GroupBox3: TGroupBox; Button2: TButton; Button3: TButton; CBSize: TCheckBox; CBPosition: TCheckBox; CBTree: TCheckBox; Button4: TButton; GroupNewChart: TGroupBox; Label4: TLabel; CBTheme: TComboFlat; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button4Click(Sender: TObject); private { Private declarations } {$IFNDEF TEELITE} OldLang : Integer; procedure ChangeLangLabel; {$ENDIF} public { Public declarations } end; // Index of Theme to use as default for new created Charts at design-time var TeeNewChartTheme : Integer=0; implementation uses {$IFNDEF TEELITE} {$IFNDEF TEENOTHEMES} TeeThemeEditor, {$ENDIF} {$ENDIF} {$IFNDEF LINUX} Registry, {$ENDIF} TeeConst; {$R *.dfm} procedure TOptionsForm.Button1Click(Sender: TObject); begin {$IFNDEF TEELITE} if TeeAskLanguage then ChangeLangLabel; {$ENDIF} end; procedure TOptionsForm.FormCreate(Sender: TObject); begin {$IFNDEF TEELITE} OldLang:=TeeLanguageRegistry; ChangeLangLabel; {$ENDIF} CBSmooth.Checked:=TChartGalleryPanel.DefaultSmooth; CBGalleryMode.ItemIndex:=TChartGalleryPanel.DefaultMode; CBPosition.Checked:=TeeReadBoolOption(TeeMsg_RememberPosition,True); CBSize.Checked:=TeeReadBoolOption(TeeMsg_RememberSize,True); CBTree.Checked:=TeeReadBoolOption(TeeMsg_TreeMode,False); {$IFNDEF TEELITE} {$IFNDEF TEENOTHEMES} AddChartThemes(CBTheme.Items); CBTheme.ItemIndex:=TeeReadIntegerOption(TeeMsg_DefaultTheme,0); {$ENDIF} {$ENDIF} {$IFDEF LINUX} Button4.Visible:=False; {$ENDIF} {$IFDEF TEELITE} GroupBox1.Hide; GroupNewChart.Hide; {$ENDIF} TeeTranslateControl(Self); end; {$IFNDEF TEELITE} procedure TOptionsForm.ChangeLangLabel; begin with TAskLanguage.Create(nil) do try Self.Label2.Caption:=LBLangs.Items[LBLangs.ItemIndex]; finally Free; end; end; {$ENDIF} procedure TOptionsForm.Button3Click(Sender: TObject); begin {$IFNDEF TEELITE} if OldLang<>TeeLanguageRegistry then TeeLanguageSaveRegistry(OldLang); {$ENDIF} ModalResult:=mrCancel; end; procedure TOptionsForm.Button2Click(Sender: TObject); begin if CBSmooth.Checked<>TChartGalleryPanel.DefaultSmooth then TChartGalleryPanel.SaveSmooth(CBSmooth.Checked); if CBGalleryMode.ItemIndex<>TChartGalleryPanel.DefaultMode then TChartGalleryPanel.SaveMode(CBGalleryMode.ItemIndex); if CBPosition.Checked<>TeeReadBoolOption(TeeMsg_RememberPosition,True) then TeeSaveBoolOption(TeeMsg_RememberPosition,CBPosition.Checked); if CBSize.Checked<>TeeReadBoolOption(TeeMsg_RememberSize,True) then TeeSaveBoolOption(TeeMsg_RememberSize,CBSize.Checked); if CBTree.Checked<>TeeReadBoolOption(TeeMsg_TreeMode,False) then TeeSaveBoolOption(TeeMsg_TreeMode,CBTree.Checked); {$IFNDEF TEELITE} {$IFNDEF TEENOTHEMES} if CBTheme.ItemIndex<>TeeReadIntegerOption(TeeMsg_DefaultTheme,0) then begin TeeNewChartTheme:=CBTheme.ItemIndex; TeeSaveIntegerOption(TeeMsg_DefaultTheme,TeeNewChartTheme); end; {$ENDIF} {$ENDIF} ModalResult:=mrOk; end; procedure TOptionsForm.Button4Click(Sender: TObject); begin {$IFNDEF LINUX} with TRegistry.Create do try if OpenKey(TeeMsg_EditorKey,True) then begin DeleteValue('Left'); DeleteValue('Top'); DeleteValue('Width'); DeleteValue('Height'); end; finally Free; end; {$ENDIF} end; end.
unit BCEditor.Editor.LeftMargin.Colors; interface uses Classes, Graphics, Consts, BCEditor.Consts; type TBCEditorLeftMarginColors = class(TPersistent) strict private FActiveLineBackground: TColor; FBackground: TColor; FBookmarkPanelBackground: TColor; FBorder: TColor; FLineNumberLine: TColor; FLineStateModified: TColor; FLineStateNormal: TColor; FOnChange: TNotifyEvent; procedure SetActiveLineBackground(const Value: TColor); procedure SetBackground(const Value: TColor); procedure SetBookmarkPanelBackground(const Value: TColor); procedure SetBorder(const Value: TColor); procedure SetLineNumberLine(const Value: TColor); procedure SetLineStateModified(const Value: TColor); procedure SetLineStateNormal(const Value: TColor); procedure DoChange; public constructor Create; procedure Assign(Source: TPersistent); override; published property ActiveLineBackground: TColor read FActiveLineBackground write SetActiveLineBackground default clActiveLineBackground; property Background: TColor read FBackground write SetBackground default clLeftMarginBackground; property BookmarkPanelBackground: TColor read FBookmarkPanelBackground write SetBookmarkPanelBackground default clLeftMarginBackground; property Border: TColor read FBorder write SetBorder default clLeftMarginBackground; property LineNumberLine: TColor read FLineNumberLine write SetLineNumberLine default clLeftMarginFontForeground; property LineStateModified: TColor read FLineStateModified write SetLineStateModified default clYellow; property LineStateNormal: TColor read FLineStateNormal write SetLineStateNormal default clLime; property OnChange: TNotifyEvent read FOnChange write FOnChange; end; implementation { TBCEditorLeftMarginColors } constructor TBCEditorLeftMarginColors.Create; begin inherited; FActiveLineBackground := clActiveLineBackground; FBackground := clLeftMarginBackground; FBookmarkPanelBackground := clLeftMarginBackground; FBorder := clLeftMarginBackground; FLineNumberLine := clLeftMarginFontForeground; FLineStateModified := clYellow; FLineStateNormal := clLime; end; procedure TBCEditorLeftMarginColors.Assign(Source: TPersistent); begin if Source is TBCEditorLeftMarginColors then with Source as TBCEditorLeftMarginColors do begin Self.FActiveLineBackground := FActiveLineBackground; Self.FBackground := FBackground; Self.FBookmarkPanelBackground := FBookmarkPanelBackground; Self.FBorder := FBorder; Self.FLineNumberLine := FLineNumberLine; Self.FLineStateModified := FLineStateModified; Self.FLineStateNormal := FLineStateNormal; Self.DoChange; end else inherited; end; procedure TBCEditorLeftMarginColors.DoChange; begin if Assigned(FOnChange) then FOnChange(Self); end; procedure TBCEditorLeftMarginColors.SetActiveLineBackground(const Value: TColor); begin if Value <> FActiveLineBackground then begin FActiveLineBackground := Value; DoChange; end; end; procedure TBCEditorLeftMarginColors.SetBackground(const Value: TColor); begin if Value <> FBackground then begin FBackground := Value; DoChange; end; end; procedure TBCEditorLeftMarginColors.SetBookmarkPanelBackground(const Value: TColor); begin if Value <> FBookmarkPanelBackground then begin FBookmarkPanelBackground := Value; DoChange; end; end; procedure TBCEditorLeftMarginColors.SetBorder(const Value: TColor); begin if Value <> FBorder then begin FBorder := Value; DoChange; end; end; procedure TBCEditorLeftMarginColors.SetLineNumberLine(const Value: TColor); begin if Value <> FLineNumberLine then begin FLineNumberLine := Value; DoChange; end; end; procedure TBCEditorLeftMarginColors.SetLineStateModified(const Value: TColor); begin if Value <> FLineStateModified then begin FLineStateModified := Value; DoChange; end; end; procedure TBCEditorLeftMarginColors.SetLineStateNormal(const Value: TColor); begin if Value <> FLineStateNormal then begin FLineStateNormal := Value; DoChange; end; end; end.