text
stringlengths
14
6.51M
unit kwPopEditorGetSelectionTextInFormat; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ScriptEngine" // Автор: Люлин А.В. // Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwPopEditorGetSelectionTextInFormat.pas" // Начат: 14.11.2011 16:34 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::EditorFromStackKeyWords::pop_editor_GetSelectionTextInFormat // // Получает текст параграфа в указанном формате // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\ScriptEngine\seDefine.inc} interface {$If not defined(NoScripts)} uses evCustomEditorWindow, tfwScriptingInterfaces, Controls, Classes ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type {$Include ..\ScriptEngine\kwEditorFromStackWord.imp.pas} TkwPopEditorGetSelectionTextInFormat = class(_kwEditorFromStackWord_) {* Получает текст параграфа в указанном формате } protected // realized methods procedure DoWithEditor(const aCtx: TtfwContext; anEditor: TevCustomEditorWindow); override; public // overridden public methods class function GetWordNameForRegister: AnsiString; override; end;//TkwPopEditorGetSelectionTextInFormat {$IfEnd} //not NoScripts implementation {$If not defined(NoScripts)} uses l3Utils, nevBase, evParaTools, evdBlockNameAdder, tfwAutoregisteredDiction, tfwScriptEngine, Windows, afwFacade, Forms ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type _Instance_R_ = TkwPopEditorGetSelectionTextInFormat; {$Include ..\ScriptEngine\kwEditorFromStackWord.imp.pas} // start class TkwPopEditorGetSelectionTextInFormat procedure TkwPopEditorGetSelectionTextInFormat.DoWithEditor(const aCtx: TtfwContext; anEditor: TevCustomEditorWindow); //#UC START# *4F4CB81200CA_4EC10AB3000A_var* var l_F : Integer; l_G : InevTagGenerator; //#UC END# *4F4CB81200CA_4EC10AB3000A_var* begin //#UC START# *4F4CB81200CA_4EC10AB3000A_impl* if aCtx.rEngine.IsTopString then l_F := l3GetClipboardByFormatName(aCtx.rEngine.PopDelphiString) else l_F := aCtx.rEngine.PopInt; l_G := nil; TevdBlockNameAdder.SetTo(l_G); aCtx.rEngine.PushString(EvAsString(anEditor.View.Control.Selection.GetBlock.Data, l_F, false, l_G)); //#UC END# *4F4CB81200CA_4EC10AB3000A_impl* end;//TkwPopEditorGetSelectionTextInFormat.DoWithEditor class function TkwPopEditorGetSelectionTextInFormat.GetWordNameForRegister: AnsiString; {-} begin Result := 'pop:editor:GetSelectionTextInFormat'; end;//TkwPopEditorGetSelectionTextInFormat.GetWordNameForRegister {$IfEnd} //not NoScripts initialization {$If not defined(NoScripts)} {$Include ..\ScriptEngine\kwEditorFromStackWord.imp.pas} {$IfEnd} //not NoScripts end.
unit uTransferAntarGudang; interface uses uModel, System.SysUtils, System.Generics.Collections; type TTransferAntarGudangItem = class; TTransferAntarGudang = class(TappObject) private FCabang: TCabang; FKeterangan: string; FNoBukti: string; FPetugas: string; FTglBukti: TDatetime; FTransferAntarGudangItems: Tobjectlist<TTransferAntarGudangItem>; FGudangAsal: tgudang; FGudangTujuan: tgudang; function GetTransferAntarGudangItems: Tobjectlist<TTransferAntarGudangItem>; procedure SetCabang(const Value: TCabang); procedure SetGudangAsal(const Value: tgudang); procedure SetGudangTujuan(const Value: tgudang); public destructor Destroy; override; published property Cabang: TCabang read FCabang write SetCabang; property Keterangan: string read FKeterangan write FKeterangan; property NoBukti: string read FNoBukti write FNoBukti; property Petugas: string read FPetugas write FPetugas; property TglBukti: TDatetime read FTglBukti write FTglBukti; property TransferAntarGudangItems: Tobjectlist<TTransferAntarGudangItem> read GetTransferAntarGudangItems write FTransferAntarGudangItems; property GudangAsal: tgudang read FGudangAsal write SetGudangAsal; property GudangTujuan: tgudang read FGudangTujuan write SetGudangTujuan; end; TTransferAntarGudangItem = class(TAppObjectItem) private FBarang: TBarang; FBarangSatuangItemID: String; FHarga: Double; FKonversi: double; FQty: Double; FTransferAntarGudang: TTransferAntarGudang; FUOM: TUOM; public destructor Destroy; override; function GetHeaderField: string; override; procedure SetHeaderProperty(AHeaderProperty : TAppObject); override; property BarangSatuangItemID: String read FBarangSatuangItemID write FBarangSatuangItemID; published property Barang: TBarang read FBarang write FBarang; property Harga: Double read FHarga write FHarga; property Konversi: double read FKonversi write FKonversi; property Qty: Double read FQty write FQty; property TransferAntarGudang: TTransferAntarGudang read FTransferAntarGudang write FTransferAntarGudang; property UOM: TUOM read FUOM write FUOM; end; implementation destructor TTransferAntarGudangItem.Destroy; begin inherited; Barang.Free; UOM.Free; end; function TTransferAntarGudangItem.GetHeaderField: string; begin Result := 'TransferAntarGudang'; end; procedure TTransferAntarGudangItem.SetHeaderProperty(AHeaderProperty : TAppObject); begin Self.TransferAntarGudang := TTransferAntarGudang(AHeaderProperty); end; destructor TTransferAntarGudang.Destroy; begin inherited; GudangAsal.Free; GudangTujuan.Free; Cabang.Free; end; function TTransferAntarGudang.GetTransferAntarGudangItems: Tobjectlist<TTransferAntarGudangItem>; begin if FTransferAntarGudangItems = nil then FTransferAntarGudangItems := TObjectList<TTransferAntarGudangItem>.Create(False); Result := FTransferAntarGudangItems; end; procedure TTransferAntarGudang.SetCabang(const Value: TCabang); begin FreeAndNil(FCabang); FCabang := Value; end; procedure TTransferAntarGudang.SetGudangAsal(const Value: tgudang); begin FreeAndNil(FGudangAsal); FGudangAsal := Value; end; procedure TTransferAntarGudang.SetGudangTujuan(const Value: tgudang); begin FreeAndNil(FGudangTujuan); FGudangTujuan := Value; end; end.
{: This unit implements a Quicksort procedure that can be used to sort anything as well as a binary sarch function. This is u_dzQuicksort in dzlib http://blog.dummzeuch.de/dzlib/ @author(Thomas Mueller http://www.dummzeuch.de) } unit GX_dzQuicksort; interface type TCompareItemsMeth = function(_Idx1, _Idx2: Integer): Integer of object; TSwapItemsMeth = procedure(_Idx1, _Idx2: Integer) of object; // for binary search TCompareToItemMeth1 = function(const _Key; _Idx: Integer): Integer of object; TCompareToItemMeth2 = function(_Key: pointer; _Idx: Integer): Integer of object; {: Call Quicksort with two method pointers for comparing and swapping two elements. @longcode(## Quicksort(0, Count-1, self.CompareItems, self.SwapItems); ##) } procedure QuickSort(_Left, _Right: Integer; _CompareMeth: TCompareItemsMeth; _SwapMeth: TSwapItemsMeth); overload; type IQSDataHandler = interface ['{C7B22837-F9C0-4228-A2E3-DC8BBF27DBA9}'] function Compare(_Idx1, _Idx2: Integer): Integer; procedure Swap(_Idx1, _Idx2: Integer); end; procedure QuickSort(_Left, _Right: Integer; _DataHandler: IQSDataHandler); overload; {: Call BinarySearch with a method pointer that compares an index to the Item sought. @param Index contains the index where the item is supposed to be (Its index, if it was found or the index where it would be inserted if not) @param Duplicates determines whether duplicates are allowed in the list or not @returns true, if the item was found, false otherwise @longcode(## Found := BinarySearch(0, count-1, Idx, Key, Self.CompareToKey); ##) } function BinarySearch(_Left, _Right: Integer; var _Index: Integer; const _Key; _CompareMeth: TCompareToItemMeth1; _Duplicates: Boolean = False): Boolean; overload; function BinarySearch(_Left, _Right: Integer; var _Index: Integer; _Key: pointer; _CompareMeth: TCompareToItemMeth2; _Duplicates: Boolean = False): Boolean; overload; type ICompareToKey = interface ['{CEB61050-D71F-4F67-B9BC-FD496A079F75}'] function CompareTo(_Idx: Integer): Integer; end; function BinarySearch(_Left, _Right: Integer; var _Index: Integer; _CompareInt: ICompareToKey; _Duplicates: Boolean = False): Boolean; overload; implementation procedure QuickSort(_Left, _Right: Integer; _DataHandler: IQSDataHandler); overload; var I, J, P: Integer; begin if _Left >= _Right then exit; repeat I := _Left; J := _Right; P := (_Left + _Right) shr 1; repeat while _DataHandler.Compare(I, P) < 0 do Inc(I); while _DataHandler.Compare(J, P) > 0 do Dec(J); if I <= J then begin if I < J then _DataHandler.Swap(I, J); if P = I then P := J else if P = J then P := I; Inc(I); Dec(J); end; until I > J; if _Left < J then QuickSort(_Left, J, _DataHandler); _Left := I; until I >= _Right; end; procedure QuickSort(_Left, _Right: Integer; _CompareMeth: TCompareItemsMeth; _SwapMeth: TSwapItemsMeth); var I, J, P: Integer; begin if _Left >= _Right then exit; repeat I := _Left; J := _Right; P := (_Left + _Right) shr 1; repeat while _CompareMeth(I, P) < 0 do Inc(I); while _CompareMeth(J, P) > 0 do Dec(J); if I <= J then begin if I < J then _SwapMeth(I, J); if P = I then P := J else if P = J then P := I; Inc(I); Dec(J); end; until I > J; if _Left < J then QuickSort(_Left, J, _CompareMeth, _SwapMeth); _Left := I; until I >= _Right; end; function BinarySearch(_Left, _Right: Integer; var _Index: Integer; const _Key; _CompareMeth: TCompareToItemMeth1; _Duplicates: Boolean = False): Boolean; var p, c: LongInt; begin Result := False; while _Left <= _Right do begin p := (_Left + _Right) shr 1; c := _CompareMeth(_Key, p); if c > 0 then _Left := p + 1 else begin _Right := p - 1; if c = 0 then begin Result := True; if not _Duplicates then _Left := p; end; end; end; _Index := _Left; end; function BinarySearch(_Left, _Right: Integer; var _Index: Integer; _Key: pointer; _CompareMeth: TCompareToItemMeth2; _Duplicates: Boolean = False): Boolean; var p, c: LongInt; begin Result := False; while _Left <= _Right do begin p := (_Left + _Right) shr 1; c := _CompareMeth(_Key, p); if c > 0 then _Left := p + 1 else begin _Right := p - 1; if c = 0 then begin Result := True; if not _Duplicates then _Left := p; end; end; end; _Index := _Left; end; function BinarySearch(_Left, _Right: Integer; var _Index: Integer; _CompareInt: ICompareToKey; _Duplicates: Boolean = False): Boolean; var p, c: LongInt; begin Result := False; while _Left <= _Right do begin p := (_Left + _Right) shr 1; c := _CompareInt.CompareTo(p); if c > 0 then _Left := p + 1 else begin _Right := p - 1; if c = 0 then begin Result := True; if not _Duplicates then _Left := p; end; end; end; _Index := _Left; end; end.
unit vlm_5030; interface uses {$IFDEF WINDOWS}windows,{$else}main_engine,{$ENDIF} sound_engine,timer_engine; const FR_SIZE=4; // samples per interpolator */ IP_SIZE_SLOWER=(240 div FR_SIZE); IP_SIZE_SLOW=(200 div FR_SIZE); IP_SIZE_NORMAL=(160 div FR_SIZE); IP_SIZE_FAST=(120 div FR_SIZE); IP_SIZE_FASTER=(80 div FR_SIZE); PH_RESET=0; PH_IDLE=1; PH_SETUP=2; PH_WAIT=3; PH_RUN=4; PH_STOP=5; PH_END=6; // ROM Tables */ VLM5030_speed_table:array[0..8-1] of integer=( IP_SIZE_NORMAL, IP_SIZE_FAST, IP_SIZE_FASTER, IP_SIZE_FASTER, IP_SIZE_NORMAL, IP_SIZE_SLOWER, IP_SIZE_SLOW, IP_SIZE_SLOW ); // This is the energy lookup table */ // sampled from real chip */ energytable:array[0..$20-1] of byte=( 0, 2, 4, 6, 10, 12, 14, 18, // 0-7 22, 26, 30, 34, 38, 44, 48, 54, // 8-15 62, 68, 76, 84, 94,102,114,124, // 16-23 136,150,164,178,196,214,232,254 // 24-31 ); // This is the pitch lookup table */ pitchtable:array[0..$20-1] of byte=( 1, // 0 : random mode */ 22, // 1 : start=22 */ 23, 24, 25, 26, 27, 28, 29, 30, // 2- 9 : 1step */ 32, 34, 36, 38, 40, 42, 44, 46, // 10-17 : 2step */ 50, 54, 58, 62, 66, 70, 74, 78, // 18-25 : 4step */ 86, 94, 102,110,118,126 // 26-31 : 8step */ ); K1_table:array[0..63] of integer= ( -24898, -25672, -26446, -27091, -27736, -28252, -28768, -29155, -29542, -29929, -30316, -30574, -30832, -30961, -31219, -31348, -31606, -31735, -31864, -31864, -31993, -32122, -32122, -32251, -32251, -32380, -32380, -32380, -32509, -32509, -32509, -32509, 24898, 23995, 22963, 21931, 20770, 19480, 18061, 16642, 15093, 13416, 11610, 9804, 7998, 6063, 3999, 1935, 0, -1935, -3999, -6063, -7998, -9804, -11610, -13416, -15093, -16642, -18061, -19480, -20770, -21931, -22963, -23995 ); K2_table:array[0..31] of integer= ( 0, -3096, -6321, -9417, -12513, -15351, -18061, -20770, -23092, -25285, -27220, -28897, -30187, -31348, -32122, -32638, 0, 32638, 32122, 31348, 30187, 28897, 27220, 25285, 23092, 20770, 18061, 15351, 12513, 9417, 6321, 3096 ); K3_table:array[0..15] of integer= ( 0, -3999, -8127, -12255, -16384, -20383, -24511, -28639, 32638, 28639, 24511, 20383, 16254, 12255, 8127, 3999 ); K5_table:array[0..7] of integer= ( 0, -8127, -16384, -24511, 32638, 24511, 16254, 8127 ); type vlm5030_chip=class(snd_chip_class) constructor Create(clock:integer;rom_size:dword;amplificador:byte); destructor free; public procedure reset; procedure update; function get_bsy:byte; procedure data_w(data:byte); function get_rom_addr:pbyte; procedure set_st(pin:byte); procedure set_rst(pin:byte); procedure update_vcu(pin:byte); function save_snapshot(data:pbyte):word; procedure load_snapshot(data:pbyte); private rom:pbyte; address_mask:integer; address:word; pin_BSY:byte; pin_ST:byte; pin_VCU:byte; pin_RST:byte; latch_data:byte; vcu_addr_h:word; parameter:byte; phase:byte; // state of option paramter */ frame_size:integer; pitch_offset:integer; interp_step:byte; interp_count:byte; // number of interp periods */ sample_count:byte; // sample number within interp */ pitch_count:byte; // these contain data describing the current and previous voice frames */ old_energy:word; old_pitch:byte; old_k:array[0..10-1] of integer; target_energy:word; target_pitch:byte; target_k:array[0..10-1] of integer; new_energy:word; new_pitch:byte; new_k:array[0..10-1] of integer; // these are all used to contain the current state of the sound generation */ current_energy:cardinal; current_pitch:cardinal; current_k:array[0..10-1] of integer; x:array[0..10-1] of integer; out_:integer; function get_bits(sbit,bits:integer):integer; function parse_frame:integer; procedure update_stream; procedure setup_parameter(param:byte); end; var vlm5030_0:vlm5030_chip; procedure vlm5030_update_stream; implementation // start VLM5030 with sound rom */ constructor vlm5030_chip.Create(clock:integer;rom_size:dword;amplificador:byte); begin getmem(self.rom,rom_size); //emulation_rate:= clock / 440; // reset input pins */ self.pin_RST:=0; self.pin_ST:=0; self.pin_VCU:= 0; self.latch_data:= 0; self.reset; self.phase:= PH_IDLE; self.amp:=amplificador; // memory size */ self.address_mask:=rom_size-1; self.tsample_num:=init_channel; //timer interno timers.init(sound_status.cpu_num,sound_status.cpu_clock/(clock/440),vlm5030_update_stream,nil,true); self.out_:=0; end; destructor vlm5030_chip.free; begin if self.rom<>nil then begin freemem(self.rom); self.rom:=nil; end; end; function vlm5030_chip.get_rom_addr; begin get_rom_addr:=self.rom; end; procedure vlm5030_chip.reset; begin self.phase:=PH_RESET; self.address:=0; self.vcu_addr_h:=0; self.pin_BSY:=0; self.old_energy:=0; self.old_pitch:=0; self.new_energy:=0; self.new_pitch:=0; self.current_energy:=0; self.current_pitch:= 0; self.target_energy:=0; self.target_pitch:= 0; fillchar(self.old_k[0],10*4,0); fillchar(self.new_k[0],10*4,0); fillchar(self.current_k,10*4,0); fillchar(self.target_k,10*4,0); self.interp_count:=0; self.sample_count:=0; self.pitch_count:= 0; fillchar(self.x[0],10*4,0); // reset parameters */ self.setup_parameter($00); end; function vlm5030_chip.save_snapshot(data:pbyte):word; var temp:pbyte; size:word; begin temp:=data; copymemory(temp,@self.address_mask,4);inc(temp,4);size:=4; copymemory(temp,@self.address,2);inc(temp,2);size:=size+2; temp^:=self.pin_BSY;inc(temp);size:=size+1; temp^:=self.pin_ST;inc(temp);size:=size+1; temp^:=self.pin_VCU;inc(temp);size:=size+1; temp^:=self.pin_RST;inc(temp);size:=size+1; temp^:=self.latch_data;inc(temp);size:=size+1; copymemory(temp,@self.vcu_addr_h,2);inc(temp,2);size:=size+2; temp^:=self.parameter;inc(temp);size:=size+1; temp^:=self.phase;inc(temp);size:=size+1; copymemory(temp,@self.frame_size,4);inc(temp,4);size:=size+4; copymemory(temp,@self.pitch_offset,4);inc(temp,4);size:=size+4; temp^:=self.interp_step;inc(temp);size:=size+1; temp^:=self.interp_count;inc(temp);size:=size+1; temp^:=self.sample_count;inc(temp);size:=size+1; temp^:=self.pitch_count;inc(temp);size:=size+1; copymemory(temp,@self.old_energy,2);inc(temp,2);size:=size+2; temp^:=self.old_pitch;inc(temp);size:=size+1; copymemory(temp,@self.old_k[0],4*10);inc(temp,4*10);size:=size+(4*10); copymemory(temp,@self.target_energy,2);inc(temp,2);size:=size+2; temp^:=self.target_pitch;inc(temp);size:=size+1; copymemory(temp,@self.target_k[0],4*10);inc(temp,4*10);size:=size+(4*10); copymemory(temp,@self.new_energy,2);inc(temp,2);size:=size+2; temp^:=self.new_pitch;inc(temp);size:=size+1; copymemory(temp,@self.new_k[0],4*10);inc(temp,4*10);size:=size+(4*10); copymemory(temp,@self.current_energy,4);inc(temp,4);size:=size+4; copymemory(temp,@self.current_pitch,4);inc(temp,4);size:=size+4; copymemory(temp,@self.current_k[0],4*10);inc(temp,4*10);size:=size+(4*10); copymemory(temp,@self.x[0],4*10);inc(temp,4*10);size:=size+(4*10); copymemory(temp,@self.out_,4);size:=size+4; save_snapshot:=size; end; procedure vlm5030_chip.load_snapshot(data:pbyte); var temp:pbyte; begin temp:=data; copymemory(@self.address_mask,temp,4);inc(temp,4); copymemory(@self.address,temp,2);inc(temp,2); self.pin_BSY:=temp^;inc(temp); self.pin_ST:=temp^;inc(temp); self.pin_VCU:=temp^;inc(temp); self.pin_RST:=temp^;inc(temp); self.latch_data:=temp^;inc(temp); copymemory(@self.vcu_addr_h,temp,2);inc(temp,2); self.parameter:=temp^;inc(temp); self.phase:=temp^;inc(temp); copymemory(@self.frame_size,temp,4);inc(temp,4); copymemory(@self.pitch_offset,temp,4);inc(temp,4); self.interp_step:=temp^;inc(temp); self.interp_count:=temp^;inc(temp); self.sample_count:=temp^;inc(temp); self.pitch_count:=temp^;inc(temp); copymemory(@self.old_energy,temp,2);inc(temp,2); self.old_pitch:=temp^;inc(temp); copymemory(@self.old_k[0],temp,4*10);inc(temp,4*10); copymemory(@self.target_energy,temp,2);inc(temp,2); self.target_pitch:=temp^;inc(temp); copymemory(@self.target_k[0],temp,4*10);inc(temp,4*10); copymemory(@self.new_energy,temp,2);inc(temp,2); self.new_pitch:=temp^;inc(temp); copymemory(@self.new_k[0],temp,4*10);inc(temp,4*10); copymemory(@self.current_energy,temp,4);inc(temp,4); copymemory(@self.current_pitch,temp,4);inc(temp,4); copymemory(@self.current_k[0],temp,4*10);inc(temp,4*10); copymemory(@self.x[0],temp,4*10);inc(temp,4*10); copymemory(@self.out_,temp,4); end; function vlm5030_chip.get_bits(sbit,bits:integer):integer; var data:integer; ptemp:pbyte; begin ptemp:=self.rom; inc(ptemp,(self.address+(sbit shr 3)) and self.address_mask); copymemory(@data,ptemp,2); data:=data shr (sbit and 7); data:=data and ($ff shr (8-bits)); get_bits:=data; end; // get next frame */ function vlm5030_chip.parse_frame:integer; var cmd:byte; i,nums:integer; ptemp:pbyte; begin // remember previous frame */ self.old_energy:=self.new_energy; self.old_pitch:=self.new_pitch; for i:=0 to 9 do self.old_k[i]:= self.new_k[i]; // command byte check */ ptemp:=self.rom; inc(ptemp,self.address and self.address_mask); cmd:=ptemp^; if (cmd and $01)<>0 then begin // extend frame */ self.new_energy:=0; self.new_pitch:=0; for i:=0 to 9 do self.new_k[i]:=0; self.address:=self.address+1; if (cmd and $02 )<>0 then begin // end of speech */ // logerror("VLM5030 %04X end \n",chip->address ); */ parse_frame:=0; exit; end else begin // silent frame */ nums:= ( (cmd shr 2)+1 )*2; // logerror("VLM5030 %04X silent %d frame\n",chip->address,nums ); */ parse_frame:=nums * FR_SIZE; exit; end; end; // pitch */ self.new_pitch:=(pitchtable[get_bits(1,5)] + self.pitch_offset ) and $ff; // energy */ self.new_energy:= energytable[get_bits(6,5)]; // 10 K's */ self.new_k[9]:= K5_table[get_bits(11,3)]; self.new_k[8]:= K5_table[get_bits(14,3)]; self.new_k[7]:= K5_table[get_bits(17,3)]; self.new_k[6]:= K5_table[get_bits(20,3)]; self.new_k[5]:= K5_table[get_bits(23,3)]; self.new_k[4]:= K5_table[get_bits(26,3)]; self.new_k[3]:= K3_table[get_bits(29,4)]; self.new_k[2]:= K3_table[get_bits(33,4)]; self.new_k[1]:= K2_table[get_bits(37,5)]; self.new_k[0]:= K1_table[get_bits(42,6)]; self.address:=self.address+6; //logerror("VLM5030 %04X voice \n",chip->address ); parse_frame:=FR_SIZE; end; // decode and buffering data */ procedure vlm5030_chip.update_stream; var interp_effect,i,current_val:integer; u:array[0..11-1] of integer; val:integer; label phase_stop; begin // running */ if ((self.phase=PH_RUN) or (self.phase=PH_STOP)) then begin // playing speech */ //while (length > 0) do begin // check new interpolator or new frame */ if (self.sample_count=0) then begin if (self.phase=PH_STOP) then begin self.phase:=PH_END; self.sample_count:= 1; goto phase_stop; // continue to end phase */ end; self.sample_count:= self.frame_size; // interpolator changes */ if (self.interp_count=0) then begin // change to new frame */ self.interp_count:=parse_frame; // with change phase */ if (self.interp_count=0) then begin // end mark found */ self.interp_count:= FR_SIZE; self.sample_count:= self.frame_size; // end -> stop time */ self.phase:= PH_STOP; end; // Set old target as new start of frame */ self.current_energy:= self.old_energy; self.current_pitch:= self.old_pitch; for i:=0 to 9 do self.current_k[i]:=self.old_k[i]; // is this a zero energy frame? */ if (self.current_energy=0) then begin //mame_printf_debug("processing frame: zero energy\n");*/ self.target_energy:= 0; self.target_pitch:= self.current_pitch; for i:=0 to 9 do self.target_k[i]:=self.current_k[i]; end else begin self.target_energy:= self.new_energy; self.target_pitch:= self.new_pitch; for i:=0 to 9 do self.target_k[i]:=self.new_k[i]; end; end; // next interpolator */ // Update values based on step values 25% , 50% , 75% , 100% */ self.interp_count:=self.interp_count-self.interp_step; // 3,2,1,0 -> 1,2,3,4 */ interp_effect:= FR_SIZE - (self.interp_count mod FR_SIZE); self.current_energy:= self.old_energy + (self.target_energy - self.old_energy) * interp_effect div FR_SIZE; if (self.old_pitch>1) then self.current_pitch:= self.old_pitch + (self.target_pitch - self.old_pitch) * interp_effect div FR_SIZE; for i:=0 to 9 do self.current_k[i]:=self.old_k[i] + (self.target_k[i] - self.old_k[i]) * interp_effect div FR_SIZE; end; // calcrate digital filter */ if (self.old_energy=0) then begin // generate silent samples here */ current_val:=0; end else if (self.old_pitch <= 1) then begin // generate unvoiced samples here */ if (random(256) and 1)<>0 then current_val:=self.current_energy else current_val:=-self.current_energy; end else begin // generate voiced samples here */ if (self.pitch_count=0) then current_val:=self.current_energy else current_val:=0; end; // Lattice filter here */ u[10]:=current_val; for i:=9 downto 0 do u[i]:=u[i+1]-((self.current_k[i] * self.x[i]) div 32768); for i:=9 downto 1 do self.x[i]:=self.x[i-1] + ((self.current_k[i-1] * u[i-1]) div 32768); self.x[0]:=u[0]; // clipping, buffering */ if (u[0] > 511) then val:=511 shl 6 else if (u[0] < -511) then val:=-511 shl 6 else val:=u[0] shl 6; self.out_:=trunc(val*self.amp); if self.out_<-32767 then self.out_:=-32767 else if self.out_>32767 then self.out_:=32767; // sample count */ self.sample_count:=self.sample_count-1; // pitch */ self.pitch_count:=self.pitch_count+1; if (self.pitch_count >= self.current_pitch ) then self.pitch_count:=0; //end; //del while exit; end; // stop phase */ phase_stop: case (self.phase) of PH_SETUP:if (self.sample_count<=1) then begin self.sample_count:=0; // logerror("VLM5030 BSY=H\n" ); */ // pin_BSY = 1; */ self.phase:=PH_WAIT; end else begin self.sample_count:=self.sample_count-1; end; PH_END:if (self.sample_count<=1) then begin self.sample_count:= 0; // logerror("VLM5030 BSY=L\n" ); */ self.pin_BSY:= 0; self.phase:= PH_IDLE; end else begin self.sample_count:=self.sample_count-1; end; end; // silent buffering self.out_:=0; end; // get BSY pin level */ function vlm5030_chip.get_bsy:byte; begin get_bsy:=self.pin_BSY; end; // latch contoll data */ procedure vlm5030_chip.data_w(data:byte); begin self.latch_data:=data; end; // setup parameteroption when RST=H */ procedure vlm5030_chip.setup_parameter(param:byte); begin // latch parameter value */ self.parameter:=param; // bit 0,1 : 4800bps / 9600bps , interporator step */ if (param and 2)<>0 then // bit 1 = 1 , 9600bps */ self.interp_step:= 4 // 9600bps : no interporator */ else if(param and 1)<>0 then // bit1 = 0 & bit0 = 1 , 4800bps */ self.interp_step:= 2 // 4800bps : 2 interporator */ else // bit1 = bit0 = 0 : 2400bps */ self.interp_step:= 1; // 2400bps : 4 interporator */ // bit 3,4,5 : speed (frame size) */ self.frame_size:=VLM5030_speed_table[(param shr 3) and 7]; // bit 6,7 : low / high pitch */ if (param and $80)<>0 then // bit7=1 , high pitch */ self.pitch_offset:= -8 else if (param and $40)<>0 then // bit6=1 , low pitch */ self.pitch_offset:= 8 else self.pitch_offset:= 0; end; // set RST pin level : reset / set table address A8-A15 */ procedure vlm5030_chip.set_rst(pin:byte); begin if self.pin_RST<>0 then begin if (pin=0) then begin // H -> L : latch parameters */ self.pin_RST:= 0; self.setup_parameter(self.latch_data); end; end else begin if (pin<>0) then begin // L -> H : reset chip */ self.pin_RST:= 1; if self.pin_BSY<>0 then begin self.reset; end; end; end; end; // set VCU pin level : ?? unknown */ procedure vlm5030_chip.update_vcu(pin:byte); begin // direct mode / indirect mode */ self.pin_VCU:= pin; end; // set ST pin level : set table address A0-A7 / start speech */ procedure vlm5030_chip.set_st(pin:byte); var table:integer; ptemp:pbyte; begin if (self.pin_ST<>pin) then begin // pin level is change */ if (pin=0) then begin // H -> L */ self.pin_ST:= 0; if( self.pin_VCU<>0 ) then begin // direct access mode & address High */ self.vcu_addr_h:=(self.latch_data shl 8) + $01; end else begin // start speech */ // check access mode */ if (self.vcu_addr_h<>0) then begin // direct access mode */ self.address:= (self.vcu_addr_h and $ff00) + self.latch_data; self.vcu_addr_h:= 0; end else begin // indirect accedd mode */ table:= (self.latch_data and $fe) + ((self.latch_data and 1) shl 8); ptemp:=self.rom; inc(ptemp,table and self.address_mask); self.address:=(ptemp^ shl 8); inc(ptemp); self.address:=self.address or ptemp^; end; // logerror("VLM5030 %02X start adr=%04X\n",table/2,chip->address ); */ // reset process status */ self.sample_count:= self.frame_size; self.interp_count:= FR_SIZE; // clear filter */ // start after 3 sampling cycle */ self.phase:= PH_RUN; end; end else begin // L -> H */ self.pin_ST:= 1; // setup speech , BSY on after 30ms? */ self.phase:= PH_SETUP; self.sample_count:= 1; // wait time for busy on */ self.pin_BSY:= 1; end; end; end; procedure vlm5030_chip.update; begin tsample[self.tsample_num,sound_status.posicion_sonido]:=self.out_; if sound_status.stereo then tsample[self.tsample_num,sound_status.posicion_sonido+1]:=self.out_; end; procedure vlm5030_update_stream; begin vlm5030_0.update_stream; end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. $Log$ Rev 1.38 11/15/2004 11:59:12 PM JPMugaas Hopefully, this should handle IPv6 addresses in SOCKS bind and listen. Rev 1.37 11/12/2004 11:30:18 AM JPMugaas Expansions for IPv6. Rev 1.36 11/11/2004 10:25:24 PM JPMugaas Added OpenProxy and CloseProxy so you can do RecvFrom and SendTo functions from the UDP client with SOCKS. You must call OpenProxy before using RecvFrom or SendTo. When you are finished, you must use CloseProxy to close any connection to the Proxy. Connect and disconnect also call OpenProxy and CloseProxy. Rev 1.35 11/11/2004 3:42:50 AM JPMugaas Moved strings into RS. Socks will now raise an exception if you attempt to use SOCKS4 and SOCKS4A with UDP. Those protocol versions do not support UDP at all. Rev 1.34 11/10/2004 10:55:58 PM JPMugaas UDP Association bug fix - we now send 0's for IP address and port. Rev 1.33 11/10/2004 10:38:42 PM JPMugaas Bug fixes - UDP with SOCKS now works. Rev 1.32 11/10/2004 9:42:54 PM JPMugaas 1 in a reserved position should be 0 in a UDP request packet. Rev 1.31 11/9/2004 8:18:00 PM JPMugaas Attempt to add SOCKS support in UDP. Rev 1.30 03/07/2004 10:08:22 CCostelloe Removed spurious code that generates warning Rev 1.29 6/9/04 7:44:44 PM RLebeau various ReadBytes() tweaks updated MakeSocks4Request() to call AIOHandler.WriteBufferCancel() on error. Rev 1.28 2004.05.20 1:39:58 PM czhower Last of the IdStream updates Rev 1.27 2004.05.20 9:19:24 AM czhower Removed unused var Rev 1.26 5/19/2004 10:44:42 PM DSiders Corrected spelling for TIdIPAddress.MakeAddressObject method. Rev 1.25 5/19/2004 2:44:40 PM JPMugaas Fixed compiler warnings in TIdSocksInfo.Listen. Rev 1.24 5/8/2004 3:45:34 PM BGooijen Listen works in Socks 4 now Rev 1.23 5/7/2004 4:52:44 PM JPMugaas Bind in SOCKS4 should work a bit better. There's still some other work that needs to be done on it. Rev 1.22 5/7/2004 8:54:54 AM JPMugaas Attempt to add SOCKS4 bind. Rev 1.21 5/7/2004 7:43:24 AM JPMugaas Checked Bas's changes. Rev 1.20 5/7/2004 5:53:20 AM JPMugaas Removed some duplicate code to reduce the probability of error. Rev 1.19 5/7/2004 1:44:12 AM BGooijen Bind Rev 1.18 5/6/2004 6:47:04 PM JPMugaas Attempt to work on bind further. Rev 1.16 5/6/2004 5:32:58 PM JPMugaas Port was being mangled because the compiler was assuming you wanted a 4 byte byte order instead of only a two byte byte order function. IP addresses are better handled. At least I can connect again. Rev 1.15 5/5/2004 2:09:40 PM JPMugaas Attempt to reintroduce bind and listen functionality for FTP. Rev 1.14 2004.03.07 11:48:44 AM czhower Flushbuffer fix + other minor ones found Rev 1.13 2004.02.03 4:16:52 PM czhower For unit name changes. Rev 1.12 2/2/2004 2:33:04 PM JPMugaas Should compile better. Rev 1.11 2/2/2004 12:23:16 PM JPMugaas Attempt to fix the last Todo concerning IPv6. Rev 1.10 2/2/2004 11:43:08 AM BGooijen DotNet Rev 1.9 2/2/2004 12:00:08 AM BGooijen Socks 4 / 4A working again Rev 1.8 2004.01.20 10:03:34 PM czhower InitComponent Rev 1.7 1/11/2004 10:45:56 PM BGooijen Socks 5 works on D7 now, Socks 4 almost Rev 1.6 2003.10.11 5:50:34 PM czhower -VCL fixes for servers -Chain suport for servers (Super core) -Scheduler upgrades -Full yarn support Rev 1.5 2003.10.01 1:37:34 AM czhower .Net Rev 1.4 2003.09.30 7:37:28 PM czhower Updates for .net Rev 1.3 4/2/2003 3:23:00 PM BGooijen fixed and re-enabled Rev 1.2 2003.01.10 8:21:04 PM czhower Removed more warnings Rev 1.1 2003.01.10 7:21:14 PM czhower Removed warnings Rev 1.0 11/13/2002 08:58:56 AM JPMugaas } unit IdSocks; interface {$I IdCompilerDefines.inc} //we need to put this in Delphi mode to work. uses Classes, IdAssignedNumbers, IdException, IdBaseComponent, IdComponent, IdCustomTransparentProxy, IdGlobal, IdIOHandler, IdIOHandlerSocket, IdSocketHandle; type EIdSocksUDPNotSupportedBySOCKSVersion = class(EIdException); TSocksVersion = (svNoSocks, svSocks4, svSocks4A, svSocks5); TSocksAuthentication = (saNoAuthentication, saUsernamePassword); const ID_SOCKS_AUTH = saNoAuthentication; ID_SOCKS_VER = svNoSocks; type TIdSocksInfo = class(TIdCustomTransparentProxy) protected FAuthentication: TSocksAuthentication; FVersion: TSocksVersion; FUDPSocksAssociation : TIdIOHandlerSocket; // function DisasmUDPReplyPacket(const APacket : TIdBytes; var VHost : String; var VPort : TIdPort; var VIPVersion: TIdIPVersion): TIdBytes; function MakeUDPRequestPacket(const AData: TIdBytes; const AHost: String; const APort: TIdPort) : TIdBytes; function GetEnabled: Boolean; override; procedure InitComponent; override; procedure AuthenticateSocks5Connection(AIOHandler: TIdIOHandler); // This must be defined with an port value that's a word so that we use the 2 byte Network Order byte functions instead // the 4 byte or 8 byte functions. If we use the wrong byte order functions, we can get a zero port value causing an error. procedure MakeSocks4Request(AIOHandler: TIdIOHandler; const AHost: string; const APort: TIdPort; const ARequest : Byte); procedure MakeSocks5Request(AIOHandler: TIdIOHandler; const AHost: string; const APort: TIdPort; const ARequest : Byte; var VBuf : TIdBytes; var VLen : Integer); procedure MakeSocks4Connection(AIOHandler: TIdIOHandler; const AHost: string; const APort: TIdPort); procedure MakeSocks4Bind(AIOHandler: TIdIOHandler; const AHost: string; const APort: TIdPort); procedure MakeSocks5Connection(AIOHandler: TIdIOHandler; const AHost: string; const APort: TIdPort; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); procedure MakeSocks5Bind(AIOHandler: TIdIOHandler; const AHost: string; const APort: TIdPort; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); procedure MakeConnection(AIOHandler: TIdIOHandler; const AHost: string; const APort: TIdPort; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); override; function MakeSocks4Listen(AIOHandler: TIdIOHandler; const ATimeOut:integer):boolean; function MakeSocks5Listen(AIOHandler: TIdIOHandler; const ATimeOut:integer):boolean; //association for UDP procedure MakeSocks5UDPAssociation(AHandle : TIdSocketHandle); procedure CloseSocks5UDPAssociation; public procedure Assign(ASource: TPersistent); override; destructor Destroy; override; procedure Bind(AIOHandler: TIdIOHandler; const AHost: string; const APort: TIdPort; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); override; function Listen(AIOHandler: TIdIOHandler; const ATimeOut:integer):boolean;override; procedure OpenUDP(AHandle : TIdSocketHandle; const AHost: string = ''; const APort: TIdPort = 0; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); override; function RecvFromUDP(AHandle: TIdSocketHandle; var ABuffer : TIdBytes; var VPeerIP: string; var VPeerPort: TIdPort; var VIPVersion: TIdIPVersion; AMSec: Integer = IdTimeoutDefault): Integer; override; procedure SendToUDP(AHandle: TIdSocketHandle; const AHost: string; const APort: TIdPort; const AIPVersion: TIdIPVersion; const ABuffer : TIdBytes); override; procedure CloseUDP(AHandle: TIdSocketHandle); override; published property Authentication: TSocksAuthentication read FAuthentication write FAuthentication default ID_SOCKS_AUTH; property Host; property Password; property Port default IdPORT_SOCKS; property IPVersion; property Username; property Version: TSocksVersion read FVersion write FVersion default ID_SOCKS_VER; property ChainedProxy; End;//TIdSocksInfo implementation uses IdResourceStringsCore, IdExceptionCore, IdIPAddress, IdStack, IdTCPClient, IdIOHandlerStack, SysUtils; { TIdSocksInfo } procedure TIdSocksInfo.Assign(ASource: TPersistent); begin if ASource is TIdSocksInfo then begin with TIdSocksInfo(ASource) do begin Self.FAuthentication := Authentication; Self.FVersion := Version; end; end; // always allow TIdCustomTransparentProxy to assign its properties as well inherited Assign(ASource); end; procedure TIdSocksInfo.MakeSocks4Request(AIOHandler: TIdIOHandler; const AHost: string; const APort: TIdPort; const ARequest : Byte); var LIpAddr: String; LBufferingStarted: Boolean; begin LBufferingStarted := not AIOHandler.WriteBufferingActive; if LBufferingStarted then begin AIOHandler.WriteBufferOpen; end; try AIOHandler.Write(Byte(4)); // Version AIOHandler.Write(ARequest); // Opcode AIOHandler.Write(Word(APort)); // Port if Version = svSocks4A then begin LIpAddr := '0.0.0.1'; {Do not Localize} end else begin LIpAddr := GStack.ResolveHost(AHost,Id_IPv4); end; AIOHandler.Write(Byte(IndyStrToInt(Fetch(LIpAddr,'.'))));// IP AIOHandler.Write(Byte(IndyStrToInt(Fetch(LIpAddr,'.'))));// IP AIOHandler.Write(Byte(IndyStrToInt(Fetch(LIpAddr,'.'))));// IP AIOHandler.Write(Byte(IndyStrToInt(Fetch(LIpAddr,'.'))));// IP AIOHandler.Write(Username); AIOHandler.Write(Byte(0));// Username if Version = svSocks4A then begin AIOHandler.Write(AHost); AIOHandler.Write(Byte(0));// Host end; if LBufferingStarted then begin AIOHandler.WriteBufferClose; //flush everything end; except if LBufferingStarted then begin AIOHandler.WriteBufferCancel; //cancel everything end; raise; end; end; procedure TIdSocksInfo.MakeSocks4Connection(AIOHandler: TIdIOHandler; const AHost: string; const APort: TIdPort); var LResponse: TIdBytes; begin MakeSocks4Request(AIOHandler, AHost, APort,$01); //connect AIOHandler.ReadBytes(LResponse, 8, False); case LResponse[1] of // OpCode 90: ;// request granted, do nothing 91: raise EIdSocksRequestFailed.Create(RSSocksRequestFailed); 92: raise EIdSocksRequestServerFailed.Create(RSSocksRequestServerFailed); 93: raise EIdSocksRequestIdentFailed.Create(RSSocksRequestIdentFailed); else raise EIdSocksUnknownError.Create(RSSocksUnknownError); end; end; procedure TIdSocksInfo.MakeSocks5Request(AIOHandler: TIdIOHandler; const AHost: string; const APort: TIdPort; const ARequest : Byte; var VBuf : TIdBytes; var VLen : Integer); var LIP : TIdIPAddress; LAddr: TIdBytes; begin // Connection process VBuf[0] := $5; // socks version VBuf[1] := ARequest; //request method VBuf[2] := $0; // reserved // address type: IP V4 address: X'01' {Do not Localize} // DOMAINNAME: X'03' {Do not Localize} // IP V6 address: X'04' {Do not Localize} LIP := TIdIPAddress.MakeAddressObject(AHost); if Assigned(LIP) then begin try if LIP.AddrType = Id_IPv6 then begin VBuf[3] := $04; //IPv6 address end else begin VBuf[3] := $01; //IPv4 address end; LAddr := LIP.HToNBytes; CopyTIdBytes(LAddr, 0, VBuf, 4, Length(LAddr)); VLen := 4 + Length(LAddr); finally FreeAndNil(LIP); end; end else begin LAddr := ToBytes(AHost); VBuf[3] := $3; // host name VBuf[4] := IndyMin(Length(LAddr), 255); if VBuf[4] > 0 then begin CopyTIdBytes(LAddr, 0, VBuf, 5, VBuf[4]); end; VLen := 5 + VBuf[4]; end; // port CopyTIdWord(GStack.HostToNetwork(APort), VBuf, VLen); VLen := VLen + 2; end; procedure TIdSocksInfo.MakeSocks5Connection(AIOHandler: TIdIOHandler; const AHost: string; const APort: TIdPort; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); var Lpos: Integer; LBuf: TIdBytes; begin AuthenticateSocks5Connection(AIOHandler); SetLength(LBuf, 255); MakeSocks5Request(AIOHandler, AHost, APort, $01, LBuf, Lpos); LBuf := ToBytes(LBuf, Lpos); AIOHandler.WriteDirect(LBuf); // send the connection packet try AIOHandler.ReadBytes(LBuf, 5, False); // Socks server replies on connect, this is the first part except raise EIdSocksServerRespondError.Create(RSSocksServerRespondError); end; case LBuf[1] of 0: ;// success, do nothing 1: raise EIdSocksServerGeneralError.Create(RSSocksServerGeneralError); 2: raise EIdSocksServerPermissionError.Create(RSSocksServerPermissionError); 3: raise EIdSocksServerNetUnreachableError.Create(RSSocksServerNetUnreachableError); 4: raise EIdSocksServerHostUnreachableError.Create(RSSocksServerHostUnreachableError); 5: raise EIdSocksServerConnectionRefusedError.Create(RSSocksServerConnectionRefusedError); 6: raise EIdSocksServerTTLExpiredError.Create(RSSocksServerTTLExpiredError); 7: raise EIdSocksServerCommandError.Create(RSSocksServerCommandError); 8: raise EIdSocksServerAddressError.Create(RSSocksServerAddressError); else raise EIdSocksUnknownError.Create(RSSocksUnknownError); end; // type of destination address is domain name case LBuf[3] of // IP V4 1: Lpos := 4 + 2; // 4 is for address and 2 is for port length // FQDN 3: Lpos := LBuf[4] + 2; // 2 is for port length // IP V6 4: Lpos := 16 + 2; // 16 is for address and 2 is for port length end; try // Socks server replies on connect, this is the second part // RLebeau: why -1? AIOHandler.ReadBytes(LBuf, Lpos-1, False); // just write it over the first part for now except raise EIdSocksServerRespondError.Create(RSSocksServerRespondError); end; end; procedure TIdSocksInfo.MakeSocks4Bind(AIOHandler: TIdIOHandler; const AHost: string; const APort: TIdPort); var LResponse: TIdBytes; LClient: TIdTcpClient; begin LClient := TIdTCPClient.Create(nil); try // SetLength(LResponse, 255); SetLength(LResponse, 8); TIdIOHandlerSocket(AIOHandler).TransparentProxy := nil; LClient.IOHandler := AIOHandler; LClient.Host := Host; LClient.Port := Port; LClient.Connect; TIdIOHandlerSocket(AIOHandler).TransparentProxy := Self; MakeSocks4Request(AIOHandler, AHost, APort, $02); //bind AIOHandler.ReadBytes(LResponse, 2, False); case LResponse[1] of // OpCode 90: ;// request granted, do nothing 91: raise EIdSocksRequestFailed.Create(RSSocksRequestFailed); 92: raise EIdSocksRequestServerFailed.Create(RSSocksRequestServerFailed); 93: raise EIdSocksRequestIdentFailed.Create(RSSocksRequestIdentFailed); else raise EIdSocksUnknownError.Create(RSSocksUnknownError); end; try // Socks server replies on connect, this is the second part AIOHandler.ReadBytes(LResponse, 6, False); //overwrite the first part for now TIdIOHandlerSocket(AIOHandler).Binding.SetBinding(BytesToIPv4Str(LResponse, 2), LResponse[0]*256+LResponse[1]); except raise EIdSocksServerRespondError.Create(RSSocksServerRespondError); end; finally LClient.IOHandler := nil; FreeAndNil(LClient); end; end; procedure TIdSocksInfo.MakeConnection(AIOHandler: TIdIOHandler; const AHost: string; const APort: TIdPort; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); begin case Version of svSocks4, svSocks4A: MakeSocks4Connection(AIOHandler, AHost, APort); svSocks5: MakeSocks5Connection(AIOHandler, AHost, APort); end; end; function TIdSocksInfo.GetEnabled: Boolean; Begin Result := Version in [svSocks4, svSocks4A, svSocks5]; End;// procedure TIdSocksInfo.InitComponent; begin inherited InitComponent; Authentication := ID_SOCKS_AUTH; Version := ID_SOCKS_VER; Port := IdPORT_SOCKS; FIPVersion := ID_DEFAULT_IP_VERSION; FUDPSocksAssociation := TIdIOHandlerStack.Create; end; procedure TIdSocksInfo.AuthenticateSocks5Connection( AIOHandler: TIdIOHandler); var Lpos: Integer; LBuf, LUsername, LPassword : TIdBytes; LRequestedAuthMethod, LServerAuthMethod, LUsernameLen, LPasswordLen : Byte; begin // keep the compiler happy LUsername := nil; LPassword := nil; SetLength(LBuf, 3); // defined in rfc 1928 if Authentication = saNoAuthentication then begin LBuf[2] := $0 // No authentication end else begin LBuf[2] := $2; // Username password authentication end; LRequestedAuthMethod := LBuf[2]; LBuf[0] := $5; // socks version LBuf[1] := $1; // number of possible authentication methods AIOHandler.WriteDirect(LBuf); try AIOHandler.ReadBytes(LBuf, 2, False); // Socks server sends the selected authentication method except On E: Exception do begin raise EIdSocksServerRespondError.Create(RSSocksServerRespondError); end; end; LServerAuthMethod := LBuf[1]; if (LServerAuthMethod <> LRequestedAuthMethod) or (LServerAuthMethod = $FF) then begin raise EIdSocksAuthMethodError.Create(RSSocksAuthMethodError); end; // Authentication process if Authentication = saUsernamePassword then begin LUsername := ToBytes(Username); LPassword := ToBytes(Password); LUsernameLen := IndyMin(Length(LUsername), 255); LPasswordLen := IndyMin(Length(LPassword), 255); SetLength(LBuf, 3 + LUsernameLen + LPasswordLen); LBuf[0] := 1; // version of subnegotiation LBuf[1] := LUsernameLen; Lpos := 2; if LUsernameLen > 0 then begin CopyTIdBytes(LUsername, 0, LBuf, Lpos, LUsernameLen); Lpos := Lpos + LUsernameLen; end; LBuf[Lpos] := LPasswordLen; Lpos := Lpos + 1; if LPasswordLen > 0 then begin CopyTIdBytes(LPassword, 0, LBuf, Lpos, LPasswordLen); end; AIOHandler.WriteDirect(LBuf); // send the username and password try AIOHandler.ReadBytes(LBuf, 2, False); // Socks server sends the authentication status except On E: Exception do begin raise EIdSocksServerRespondError.Create(RSSocksServerRespondError); end; end; if LBuf[1] <> $0 then begin raise EIdSocksAuthError.Create(RSSocksAuthError); end; end; end; procedure TIdSocksInfo.MakeSocks5Bind(AIOHandler: TIdIOHandler; const AHost: string; const APort: TIdPort; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); var Lpos: Integer; LBuf: TIdBytes; LClient: TIdTCPClient; LType : Byte; LAddress: TIdIPv6Address; begin LClient := TIdTCPClient.Create(nil); try SetLength(LBuf, 255); TIdIOHandlerSocket(AIOHandler).TransparentProxy := nil; LClient.IOHandler := AIOHandler; LClient.Host := Host; LClient.IPVersion := IPVersion; LClient.Port := Port; LClient.Connect; TIdIOHandlerSocket(AIOHandler).TransparentProxy := Self; AuthenticateSocks5Connection(AIOHandler); // Bind process MakeSocks5Request(AIOHandler, AHost, APort, $02, LBuf, LPos); //bind request // AIOHandler.Write(LBuf, LPos); // send the connection packet try AIOHandler.ReadBytes(LBuf, 4, False); // Socks server replies on connect, this is the first part except raise EIdSocksServerRespondError.Create(RSSocksServerRespondError); end; case LBuf[1] of 0: ;// success, do nothing 1: raise EIdSocksServerGeneralError.Create(RSSocksServerGeneralError); 2: raise EIdSocksServerPermissionError.Create(RSSocksServerPermissionError); 3: raise EIdSocksServerNetUnreachableError.Create(RSSocksServerNetUnreachableError); 4: raise EIdSocksServerHostUnreachableError.Create(RSSocksServerHostUnreachableError); 5: raise EIdSocksServerConnectionRefusedError.Create(RSSocksServerConnectionRefusedError); 6: raise EIdSocksServerTTLExpiredError.Create(RSSocksServerTTLExpiredError); 7: raise EIdSocksServerCommandError.Create(RSSocksServerCommandError); 8: raise EIdSocksServerAddressError.Create(RSSocksServerAddressError); else raise EIdSocksUnknownError.Create(RSSocksUnknownError); end; LType := LBuf[3]; // type of destination address is domain name case LType of // IP V4 1: Lpos := 4 + 2; // 4 is for address and 2 is for port length // FQDN 3: Lpos := LBuf[4] + 2; // 2 is for port length // IP V6 4: LPos := 16 + 2; // 16 is for address and 2 is for port length end; try // Socks server replies on connect, this is the second part AIOHandler.ReadBytes(LBuf, Lpos, False); //overwrite the first part for now case LType of 1 : begin //IPv4 TIdIOHandlerSocket(AIOHandler).Binding.SetPeer(BytesToIPv4Str(LBuf), LBuf[4]*256+LBuf[5], Id_IPv4); end; 3 : begin TIdIOHandlerSocket(AIOHandler).Binding.SetPeer(GStack.ResolveHost(BytesToString(LBuf,0,LPos-2)), LBuf[4]*256+LBuf[5], TIdIOHandlerSocket(AIOHandler).IPVersion); end; 4 : begin BytesToIPv6(LBuf, LAddress); TIdIOHandlerSocket(AIOHandler).Binding.SetPeer(IPv6AddressToStr(LAddress), LBuf[16]*256+LBuf[17], Id_IPv6); end; end; except raise EIdSocksServerRespondError.Create(RSSocksServerRespondError); end; finally LClient.IOHandler := nil; FreeAndNil(LClient); end; end; procedure TIdSocksInfo.Bind(AIOHandler: TIdIOHandler; const AHost: string; const APort: TIdPort; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); begin case Version of svSocks4, svSocks4A: MakeSocks4Bind(AIOHandler, AHost, APort); svSocks5: MakeSocks5Bind(AIOHandler, AHost, APort, AIPVersion); end; end; function TIdSocksInfo.Listen(AIOHandler: TIdIOHandler; const ATimeOut: integer): boolean; begin Result := False; case Version of svSocks4, svSocks4A: Result := MakeSocks4Listen(AIOHandler, ATimeOut); svSocks5: Result := MakeSocks5Listen(AIOHandler, ATimeOut); end; end; function TIdSocksInfo.MakeSocks5Listen(AIOHandler: TIdIOHandler; const ATimeOut: integer): boolean; var Lpos: Integer; LBuf: TIdBytes; LType : Byte; LAddress: TIdIPv6Address; begin SetLength(LBuf, 255); Result := TIdIOHandlerSocket(AIOHandler).Binding.Readable(ATimeOut); if Result then begin AIOHandler.ReadBytes(LBuf, 4, False); // Socks server replies on connect, this is the first part case LBuf[1] of 0: ;// success, do nothing 1: raise EIdSocksServerGeneralError.Create(RSSocksServerGeneralError); 2: raise EIdSocksServerPermissionError.Create(RSSocksServerPermissionError); 3: raise EIdSocksServerNetUnreachableError.Create(RSSocksServerNetUnreachableError); 4: raise EIdSocksServerHostUnreachableError.Create(RSSocksServerHostUnreachableError); 5: raise EIdSocksServerConnectionRefusedError.Create(RSSocksServerConnectionRefusedError); 6: raise EIdSocksServerTTLExpiredError.Create(RSSocksServerTTLExpiredError); 7: raise EIdSocksServerCommandError.Create(RSSocksServerCommandError); 8: raise EIdSocksServerAddressError.Create(RSSocksServerAddressError); else raise EIdSocksUnknownError.Create(RSSocksUnknownError); end; LType := LBuf[3]; // type of destination address is domain name case LType of // IP V4 1: Lpos := 4 + 2; // 4 is for address and 2 is for port length // FQDN 3: Lpos := LBuf[4] + 2; // 2 is for port length // IP V6 - 4: else Lpos := 16 + 2; // 16 is for address and 2 is for port length end; // Socks server replies on connect, this is the second part AIOHandler.ReadBytes(LBuf, Lpos, False); // just write it over the first part for now case LType of 1 : begin //IPv4 TIdIOHandlerSocket(AIOHandler).Binding.SetPeer(BytesToIPv4Str(LBuf), LBuf[4]*256+LBuf[5], Id_IPv4); end; 3 : begin //FQN TIdIOHandlerSocket(AIOHandler).Binding.SetPeer(GStack.ResolveHost(BytesToString(LBuf,0,LPos-2)), LBuf[4]*256+LBuf[5], TIdIOHandlerSocket(AIOHandler).IPVersion); end; else begin //IPv6 BytesToIPv6(LBuf, LAddress); TIdIOHandlerSocket(AIOHandler).Binding.SetPeer(IPv6AddressToStr(LAddress), LBuf[16]*256+LBuf[17], Id_IPv6); end; end; end; end; function TIdSocksInfo.MakeSocks4Listen(AIOHandler: TIdIOHandler; const ATimeOut: integer): boolean; var LBuf: TIdBytes; begin SetLength(LBuf, 6); Result := TIdIOHandlerSocket(AIOHandler).Binding.Readable(ATimeOut); if Result then begin AIOHandler.ReadBytes(LBuf, 2, False); // Socks server replies on connect, this is the first part case LBuf[1] of // OpCode 90: ;// request granted, do nothing 91: raise EIdSocksRequestFailed.Create(RSSocksRequestFailed); 92: raise EIdSocksRequestServerFailed.Create(RSSocksRequestServerFailed); 93: raise EIdSocksRequestIdentFailed.Create(RSSocksRequestIdentFailed); else raise EIdSocksUnknownError.Create(RSSocksUnknownError); end; // Socks server replies on connect, this is the second part AIOHandler.ReadBytes(LBuf, 6, False); // just write it over the first part for now TIdIOHandlerSocket(AIOHandler).Binding.SetPeer(BytesToIPv4Str(LBuf, 2), LBuf[0]*256+LBuf[1]); end; end; procedure TIdSocksInfo.CloseSocks5UDPAssociation; begin if Assigned(FUDPSocksAssociation) then begin FUDPSocksAssociation.Close; end; end; procedure TIdSocksInfo.MakeSocks5UDPAssociation(AHandle: TIdSocketHandle); var Lpos: Integer; LBuf: TIdBytes; LIPVersion : TIdIPVersion; begin FUDPSocksAssociation.Host := Self.Host; FUDPSocksAssociation.Port := Self.Port; FUDPSocksAssociation.IPVersion := Self.IPVersion; LIPVersion := Self.IPVersion; FUDPSocksAssociation.Open; try SetLength(LBuf, 255); AuthenticateSocks5Connection(FUDPSocksAssociation); // Associate process //For SOCKS5 Associate, the IP address and port is the client's IP address and port which may //not be known if IPVersion = Id_IPv4 then begin MakeSocks5Request(FUDPSocksAssociation, '0.0.0.0', 0, $03, LBuf, LPos); //associate request end else begin MakeSocks5Request(FUDPSocksAssociation, '::0', 0, $03, LBuf, LPos); //associate request end; // FUDPSocksAssociation.Write(LBuf, LPos); // send the connection packet try FUDPSocksAssociation.ReadBytes(LBuf, 2, False); // Socks server replies on connect, this is the first part )VER and RSP except raise EIdSocksServerRespondError.Create(RSSocksServerRespondError); end; case LBuf[1] of 0: ;// success, do nothing 1: raise EIdSocksServerGeneralError.Create(RSSocksServerGeneralError); 2: raise EIdSocksServerPermissionError.Create(RSSocksServerPermissionError); 3: raise EIdSocksServerNetUnreachableError.Create(RSSocksServerNetUnreachableError); 4: raise EIdSocksServerHostUnreachableError.Create(RSSocksServerHostUnreachableError); 5: raise EIdSocksServerConnectionRefusedError.Create(RSSocksServerConnectionRefusedError); 6: raise EIdSocksServerTTLExpiredError.Create(RSSocksServerTTLExpiredError); 7: raise EIdSocksServerCommandError.Create(RSSocksServerCommandError); 8: raise EIdSocksServerAddressError.Create(RSSocksServerAddressError); else raise EIdSocksUnknownError.Create(RSSocksUnknownError); end; FUDPSocksAssociation.ReadBytes(LBuf, 2, False); //Now get RSVD and ATYPE feilds // type of destination address is domain name case LBuf[1] of // IP V4 1: begin Lpos := 4 + 2; // 4 is for address and 2 is for port length LIPVersion := Id_IPv4; end; // FQDN 3: Lpos := LBuf[4] + 2; // 2 is for port length // IP V6 4: begin LPos := 16 + 2; // 16 is for address and 2 is for port length LIPVersion := Id_IPv6; end; end; try // Socks server replies on connect, this is the second part FUDPSocksAssociation.ReadBytes(LBuf, Lpos, False); //overwrite the first part for now AHandle.SetPeer( (FUDPSocksAssociation as TIdIOHandlerStack).Binding.PeerIP ,LBuf[4]*256+LBuf[5],LIPVersion); AHandle.Connect; except raise EIdSocksServerRespondError.Create(RSSocksServerRespondError); end; except on E: Exception do begin FUDPSocksAssociation.Close; raise; end; end; end; procedure TIdSocksInfo.CloseUDP(AHandle: TIdSocketHandle); begin case Version of svSocks4, svSocks4A: raise EIdSocksUDPNotSupportedBySOCKSVersion.Create(RSSocksUDPNotSupported); svSocks5: CloseSocks5UDPAssociation; end; end; procedure TIdSocksInfo.OpenUDP(AHandle: TIdSocketHandle; const AHost: string=''; const APort: TIdPort=0; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); begin case Version of svSocks4, svSocks4A: raise EIdSocksUDPNotSupportedBySOCKSVersion.Create(RSSocksUDPNotSupported); svSocks5: MakeSocks5UDPAssociation(AHandle); end; end; function TIdSocksInfo.DisasmUDPReplyPacket(const APacket : TIdBytes; var VHost : String; var VPort : TIdPort; var VIPVersion: TIdIPVersion): TIdBytes; { +----+------+------+----------+----------+----------+ |RSV | FRAG | ATYP | DST.ADDR | DST.PORT | DATA | +----+------+------+----------+----------+----------+ | 2 | 1 | 1 | Variable | 2 | Variable | +----+------+------+----------+----------+----------+ 01 2 3 The fields in the UDP request header are: o RSV Reserved X'0000' o FRAG Current fragment number o ATYP address type of following addresses: o IP V4 address: X'01' o DOMAINNAME: X'03' o IP V6 address: X'04' o DST.ADDR desired destination address o DST.PORT desired destination port o DATA user data } var LLen : Integer; LIP6 : TIdIPv6Address; i : Integer; begin if Length(APacket) < 5 then begin Exit; end; // type of destination address is domain name case APacket[3] of // IP V4 1: begin LLen := 4 + 4; //4 IPv4 address len, 4- 2 reserved, 1 frag, 1 atype VHost := BytesToIPv4Str(APacket, 4); VIPVersion := Id_IPv4; end; // FQDN 3: begin LLen := APacket[4] +4; // 2 is for port length, 4 - 2 reserved, 1 frag, 1 atype if Length(APacket)< (5+LLen) then begin Exit; end; VHost := BytesToString(APacket, 5, APacket[4]); // VIPVersion is pre-initialized by the receiving socket before DisasmUDPReplyPacket() is called end; // IP V6 - 4: else begin LLen := 16 + 4; // 16 is for address, 2 is for port length, 4 - 2 reserved, 1 frag, 1 atype BytesToIPv6(APacket, LIP6, 5); for i := 0 to 7 do begin LIP6[i] := GStack.NetworkToHost(LIP6[i]); end; VHost := IPv6AddressToStr(LIP6); VIPVersion := Id_IPv6; end; end; VPort := APacket[LLen]*256 + APacket[LLen+1]; LLen := LLen + 2; SetLength(Result, Length(APacket)-LLen); CopyTIdBytes(APacket, LLen, Result, 0, Length(APacket)-LLen); end; function TIdSocksInfo.MakeUDPRequestPacket(const AData: TIdBytes; const AHost : String; const APort : TIdPort) : TIdBytes; { +----+------+------+----------+----------+----------+ |RSV | FRAG | ATYP | DST.ADDR | DST.PORT | DATA | +----+------+------+----------+----------+----------+ | 2 | 1 | 1 | Variable | 2 | Variable | +----+------+------+----------+----------+----------+ 01 2 3 The fields in the UDP request header are: o RSV Reserved X'0000' o FRAG Current fragment number o ATYP address type of following addresses: o IP V4 address: X'01' o DOMAINNAME: X'03' o IP V6 address: X'04' o DST.ADDR desired destination address o DST.PORT desired destination port o DATA user data } var LLen : Integer; LIP : TIdIPAddress; LAddr: TIdBytes; begin SetLength(Result, 1024); Result[0] := 0; Result[1] := 0; Result[2] := 0; //no fragmentation - too lazy to implement it // address type: IP V4 address: X'01' {Do not Localize} // DOMAINNAME: X'03' {Do not Localize} // IP V6 address: X'04' {Do not Localize} LIP := TIdIPAddress.MakeAddressObject(AHost); if Assigned(LIP) then begin try if LIP.AddrType = Id_IPv6 then begin Result[3] := $04; //IPv6 address end else begin Result[3] := $01; //IPv4 address end; LLen := 4; LAddr := LIP.HToNBytes; CopyTIdBytes(LAddr, 0, Result, 4, Length(LAddr)); LLen := LLen + Length(LAddr); finally FreeAndNil(LIP); end; end else begin LAddr := ToBytes(AHost); Result[3] := $3; // host name Result[4] := IndyMin(Length(LAddr), 255); if Result[4] > 0 then begin CopyTIdBytes(LAddr, 0, Result, 5, Result[4]); end; LLen := 5 + Result[4]; end; // port CopyTIdWord(GStack.HostToNetwork(APort), Result, LLen); LLen := LLen + 2; //now do the rest of the packet SetLength(Result, LLen + Length(AData)); CopyTIdBytes(AData, 0, Result, LLen, Length(AData)); end; function TIdSocksInfo.RecvFromUDP(AHandle: TIdSocketHandle; var ABuffer : TIdBytes; var VPeerIP: string; var VPeerPort: TIdPort; var VIPVersion: TIdIPVersion; AMSec: Integer = IdTimeoutDefault): Integer; var LBuf : TIdBytes; begin case Version of svSocks4, svSocks4A: raise EIdSocksUDPNotSupportedBySOCKSVersion.Create(RSSocksUDPNotSupported); end; SetLength(LBuf, Length(ABuffer)+200); if not AHandle.Readable(AMSec) then begin Result := 0; VPeerIP := ''; {Do not Localize} VPeerPort := 0; VIPVersion := ID_DEFAULT_IP_VERSION; Exit; end; Result := AHandle.RecvFrom(LBuf, VPeerIP, VPeerPort, VIPVersion); SetLength(LBuf, Result); LBuf := DisasmUDPReplyPacket(LBuf, VPeerIP, VPeerPort, VIPVersion); Result := Length(LBuf); CopyTIdBytes(LBuf, 0, ABuffer, 0, Result); end; procedure TIdSocksInfo.SendToUDP(AHandle: TIdSocketHandle; const AHost: string; const APort: TIdPort; const AIPVersion: TIdIPVersion; const ABuffer : TIdBytes); var LBuf : TIdBytes; begin case Version of svSocks4, svSocks4A: raise EIdSocksUDPNotSupportedBySOCKSVersion.Create(RSSocksUDPNotSupported); end; LBuf := MakeUDPRequestPacket(ABuffer, AHost, APort); AHandle.Send(LBuf, 0); end; destructor TIdSocksInfo.Destroy; begin FreeAndNil(FUDPSocksAssociation); inherited Destroy; end; end.
{server icon from http://www.fasticon.com} unit unit1; {$mode objfpc}{$H+} interface uses SysUtils, Classes, Controls, Forms, StdCtrls, LCLIntf, httpswebserver; type { TForm1 } TForm1 = class(TForm) Memo1: TMemo; btnStartStop: TButton; btnOpenLog: TButton; btnClearLog: TButton; procedure btnStartStopClick(Sender: TObject); procedure btnOpenLogClick(Sender: TObject); procedure btnClearLogClick(Sender: TObject); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); private LogFile: string; protected public end; var Form1 : TForm1; MyServer: THTTPWebServer; implementation {$R *.lfm} procedure TForm1.btnStartStopClick(Sender: TObject); begin if MyServer.ServerActive then begin MyServer.Stop; Memo1.Append('Server stopped'); btnStartStop.Caption:='Start Server'; end else begin LogFile:=GetCurrentDir + DirectorySeparator + ChangeFileExt(ExtractFileName(Application.ExeName),'.log'); MyServer.LogFile:=LogFile; MyServer.Start; Memo1.Append('Server started'); btnStartStop.Caption:=Uppercase('stop server'); end; end; procedure TForm1.btnClearLogClick(Sender: TObject); begin if FileExists(LogFile) then DeleteFile(LogFile); Memo1.Append('Log cleared'); end; procedure TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin MyServer.Stop; end; procedure TForm1.btnOpenLogClick(Sender: TObject); begin OpenDocument(LogFile); end; end.
unit Cautious_controls; interface uses Cautious_Edit,StdCtrls,Controls,Classes,Messages,graphics,TypInfo; type TDisablingCheckBox=class(TCheckBox) private fControlToDisable: TControl; procedure SetControlToDisable(value: TControl); public constructor Create(owner: TComponent); override; procedure Notification(aComponent: TComponent; operation: TOperation); override; procedure Click; override; published property ControlToDisable: TControl read fControlToDisable write SetControlToDisable; end; TDisablingRadioButton=class(TRadioButton) private fControlToDisable: TControl; procedure CautiousChange; procedure SetControlToDisable(value: TControl); procedure BMSetCheck(var Message: TMessage); message BM_SETCHECK; public procedure Notification(aComponent: TComponent; operation: TOperation); override; published property ControlToDisable: TControl read fControlToDisable write SetControlToDisable; end; TDisablingGroupBox=class(TGroupBox) protected procedure Notification(AComponent: TComponent;operation: TOperation); override; private procedure CMEnabledChanged(var Message: TMessage); message CM_ENABLEDCHANGED; end; TCautiousExtender=class(TLabel) private fControl1,fControl2: TControl; procedure SetControl1(value: TControl); procedure SetControl2(value: TControl); procedure CMEnabledChanged(var Message: TMessage); message CM_ENABLEDCHANGED; published property Control1: TControl read fcontrol1 write SetControl1; property Control2: TControl read fcontrol2 write SetControl2; property enabled; end; TIntegerEdit=class(TCautiousEdit) private fTestBtmp: TBitmap; fTypeData: PTypeData; fTypeInfo: PPTypeInfo; fExpressionRoot: TComponent; function get_value: Integer; procedure set_value(value: Integer); procedure SetTypeInfo(value: PPTypeInfo); function WithinBounds(value: Integer; out errmsg: string): boolean; protected procedure SetExpressionRoot(value: TComponent); override; function GetExpressionRoot: TComponent; override; public procedure Change; override; function isValid: boolean; constructor Create(owner: TComponent); override; destructor Destroy; override; property TypeInfo: PPTypeInfo read fTypeInfo write SetTypeInfo; published property value: Integer Read get_value Write set_value stored false; end; TFloatEdit = class(TCautiousEdit) private fExpressionRoot: TComponent; function get_value: Real; procedure set_value(value: Real); protected procedure SetExpressionRoot(value: TComponent); override; function GetExpressionRoot: TComponent; override; public constructor Create(owner: TComponent); override; procedure Change; override; function isValid: boolean; published property value: Real Read get_value Write set_value; end; procedure Register; implementation uses float_expression_lib,sysUtils,math; (* TDisablingCheckBox *) procedure TDisablingCheckBox.Notification(aComponent: TComponent; operation: TOperation); begin if (operation=opRemove) and (aComponent=fControlToDisable) then fControlToDisable:=nil; inherited; end; procedure TDisablingCheckBox.SetControlToDisable(value: TControl); begin if Assigned(fControlToDisable) then begin EnableControl(fControlToDisable,self); fControlToDisable.RemoveFreeNotification(self); end; fControlToDisable:=value; if Assigned(value) then begin value.FreeNotification(self); Click; end; end; procedure TDisablingCheckBox.Click; begin if Assigned(fControlToDisable) then begin if Checked then EnableControl(fControlToDisable,self) else DisableControl(fControlToDisable,self); end; inherited Click; end; constructor TDisablingCheckBox.Create(owner: TComponent); begin inherited Create(owner); end; (* TCautiousExtender *) procedure TCautiousExtender.SetControl1(value: TControl); begin if Assigned(fControl1) then begin EnableControl(fControl1,self); fControl1.RemoveFreeNotification(self); end; fControl1:=value; if Assigned(value) then begin value.FreeNotification(self); // Click; end; end; procedure TCautiousExtender.SetControl2(value: TControl); begin if Assigned(fControl2) then begin EnableControl(fControl2,self); fControl2.RemoveFreeNotification(self); end; fControl2:=value; if Assigned(value) then begin value.FreeNotification(self); // Click; end; end; procedure TCautiousExtender.CMEnabledChanged(var Message: TMessage); begin if enabled then begin if Assigned(control1) then EnableControl(control1,self); if Assigned(control2) then EnableControl(control2,self); end else begin if Assigned(control1) then DisableControl(control1,self); if Assigned(control2) then DisableControl(control2,self); end; end; (* TDisablingRadioButton *) procedure TDisablingRadioButton.Notification(aComponent: TComponent; operation: TOperation); begin if (operation=opRemove) and (aComponent=fControlToDisable) then fControlToDisable:=nil; inherited; end; procedure TDisablingRadioButton.SetControlToDisable(value: TControl); begin if Assigned(fControlToDisable) then begin EnableControl(fControlToDisable,self); fControlToDisable.RemoveFreeNotification(self); end; fControlToDisable:=value; if Assigned(value) then begin value.FreeNotification(self); CautiousChange; end; end; procedure TDisablingRadioButton.CautiousChange; begin if Assigned(fControlToDisable) then begin if Checked then EnableControl(fControlToDisable,self) else DisableControl(fControlToDisable,self); end; end; procedure TDisablingRadioButton.BMSetCheck(var Message: TMessage); begin CautiousChange; inherited; end; (* TDisablingGroupBox *) procedure TDisablingGroupBox.CMEnabledChanged(var Message: TMessage); var i: Integer; begin for I:= 0 to ControlCount -1 do begin Controls[i].Enabled:=enabled; end; inherited; end; procedure TDisablingGroupBox.Notification(AComponent: TComponent; operation: TOperation); var i: Integer; begin if operation=opInsert then begin for I:= 0 to ControlCount -1 do begin if Assigned(Controls[i]) then Controls[i].Enabled:=enabled; end; end; inherited Notification(AComponent,operation); end; (* TFloatEdit *) function TFloatEdit.get_value: Real; var res: Extended; expr: TFloatExpression; E: Exception; begin if AllowExpressions then begin expr:=TFloatExpression.Create(nil); expr.SetRootComponent(fExpressionRoot); expr.SetString(text); if expr.isCorrect then Result:=expr.getValue else begin Result:=0; if not (csDesigning in self.ComponentState) then begin E:=Exception.CreateFMT('TFloatLabel: %s',[expr.errorMsg]); expr.Free; //не хотим терять память Raise E; end; end; expr.Free; end else if TryStrToFloat(text,res) then begin Result:=res; end else begin Result:=0; if not (csDesigning in self.ComponentState) then Raise Exception.Create('TFloatLabel: Not a number'); end; end; procedure TFloatEdit.Change; var res: Extended; expr: TFloatExpression; resourcestring FloatEditNotARealNumberMsg = 'Не является действительным числом'; begin if AllowExpressions then begin expr:=TFloatExpression.Create(nil); expr.SetRootComponent(fExpressionRoot); expr.SetString(text); if expr.isCorrect then ReturnToNormal else TurnRed(expr.errorMsg); expr.Free; end else if TryStrToFloat(text,res) then ReturnToNormal else TurnRed(FloatEditNotARealNumberMsg); inherited Change; end; procedure TFloatEdit.set_value(value: Real); begin text:=FloatToStr(value); end; constructor TFloatEdit.Create(owner: TComponent); begin inherited Create(owner); if (csDesigning in ComponentState) then value:=0; end; function TFloatEdit.isValid: Boolean; var t: Extended; expr: TFloatExpression; begin if AllowExpressions then begin expr:=TFloatExpression.Create(nil); expr.SetRootComponent(fExpressionRoot); expr.SetString(text); Result:=expr.isCorrect; expr.Free; end else Result:=TryStrToFloat(text,t); end; procedure TFloatEdit.SetExpressionRoot(value: TComponent); begin fExpressionRoot:=value; end; function TFloatEdit.GetExpressionRoot: TComponent; begin Result:=fExpressionRoot; end; (* TIntegerEdit *) function TIntegerEdit.WithinBounds(value: Integer; out errmsg: string): boolean; resourcestring IntegerNotWithinRange = 'допустимые значения для %s: %d..%d'; begin if Assigned(fTypeInfo) then begin Result:=(value>=fTypeData^.MinValue) and (value<=fTypeData^.MaxValue); if not Result then errmsg:=Format(IntegerNotWithinRange,[fTypeInfo^.Name,fTypeData^.MinValue,fTypeData^.MaxValue]); end else Result:=true; end; function TIntegerEdit.get_value: Integer; var res: Integer; expr: TFloatExpression; errmsg: string; begin if AllowExpressions then begin expr:=TFloatExpression.Create(nil); expr.SetRootComponent(fExpressionRoot); expr.SetString(text); if expr.isCorrect then begin Result:=expr.getIntegerValue; if not WithinBounds(Result,errmsg) and not (csDesigning in ComponentState) then begin expr.Free; Raise Exception.Create(errmsg); end; end else begin Result:=0; if not (csDesigning in ComponentState) then begin errmsg:=expr.errorMsg; expr.Free; raise Exception.CreateFmt('TIntegerEdit: %s',[errMsg]); end; end; expr.Free; end else if TryStrToInt(text,res) then begin Result:=res; end else begin Result:=0; if not (csDesigning in self.ComponentState) then Raise Exception.Create('TIntegerEdit: Not a number'); end; end; function TIntegerEdit.isValid: boolean; var t: Integer; expr: TFloatExpression; errmsg: String; begin if AllowExpressions then begin expr:=TFloatExpression.Create(nil); expr.SetRootComponent(fExpressionRoot); expr.SetString(text); Result:=expr.isCorrect and WithinBounds(expr.getIntegerValue,errmsg); expr.Free; end else Result:=TryStrToInt(text,t) and WithinBounds(t,errmsg); end; procedure TIntegerEdit.Change; var res: Integer; expr: TFloatExpression; errMsg: string; resourcestring IntegerEditNotAnIntegerNumberMsg = 'Не является целым числом'; begin if AllowExpressions then begin expr:=TFloatExpression.Create(nil); expr.SetRootComponent(fExpressionRoot); expr.SetString(text); if expr.isCorrect then if WithinBounds(expr.getIntegerValue,errMsg) then ReturnToNormal else TurnRed(errMsg) else TurnRed(expr.errorMsg); expr.Free; end else if TryStrToInt(text,res) then if WithinBounds(res,errMsg) then ReturnToNormal else TurnRed(errMsg) else TurnRed(IntegerEditNotAnIntegerNumberMsg); inherited Change; end; procedure TIntegerEdit.set_value(value: Integer); begin text:=IntToStr(value); end; constructor TIntegerEdit.Create(owner: TComponent); begin inherited Create(owner); fTestBtmp:=TBitmap.Create; if (csDesigning in ComponentState) then value:=0; end; destructor TIntegerEdit.Destroy; begin fTestBtmp.Free; inherited Destroy; end; procedure TIntegerEdit.SetTypeInfo(value: PPTypeInfo); var mi,ma: Integer; begin fTypeInfo:=value; fTypeData:=GetTypeData(value^); if Assigned(fTypeData) then begin fTestBtmp.Canvas.Font:=Font; mi:=fTestBtmp.Canvas.TextWidth(IntToStr(fTypeData^.MinValue)); ma:=fTestBtmp.Canvas.TextWidth(IntToStr(fTypeData^.MaxValue)); ClientWidth:=Max(mi,ma)+5; end; end; procedure TIntegerEdit.SetExpressionRoot(value: TComponent); begin fExpressionRoot:=value; end; function TIntegerEdit.GetExpressionRoot: TComponent; begin Result:=fExpressionRoot; end; procedure Register; begin RegisterComponents('CautiousEdit',[TDisablingCheckBox,TDisablingRadioButton,TDisablingGroupBox, TCautiousExtender,TIntegerEdit, TFloatEdit]); end; end.
{********************************************************************* * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Autor: Brovin Y.D. * E-mail: y.brovin@gmail.com * ********************************************************************} unit FGX.FlipView.Effect; interface uses FMX.Presentation.Style, FMX.Controls.Presentation, FMX.Filter.Effects, FMX.Ani, FMX.Objects, FMX.Controls.Model, FMX.Graphics, FMX.Presentation.Messages, FMX.Controls, FGX.FlipView.Presentation, FGX.FlipView.Types, FGX.FlipView; type { TfgFlipViewEffectPresentation } TfgFlipViewEffectPresentation = class(TfgStyledFlipViewBasePresentation) private [Weak] FNextImage: TBitmap; FTransitionEffect: TImageFXEffect; FTransitionAnimaton: TFloatAnimation; { Event handlers } procedure HandlerFinishAnimation(Sender: TObject); protected { Messages From Model} procedure MMEffectOptionsChanged(var AMessage: TDispatchMessage); message TfgFlipViewMessages.MM_EFFECT_OPTIONS_CHANGED; protected procedure RecreateEffect; { Styles } procedure ApplyStyle; override; procedure FreeStyle; override; public procedure ShowNextImage(const ANewItemIndex: Integer; const ADirection: TfgDirection; const AAnimate: Boolean); override; end; implementation uses System.Types, System.SysUtils, System.Rtti, FMX.Presentation.Factory, FMX.Types, FGX.Asserts, System.Classes, System.Math; { TfgFlipViewEffectPresentation } procedure TfgFlipViewEffectPresentation.ApplyStyle; var NewImage: TBitmap; begin inherited ApplyStyle; { Image container for current slide } if ImageContainer <> nil then begin ImageContainer.Visible := True; ImageContainer.Margins.Rect := TRectF.Empty; NewImage := Model.CurrentImage; if NewImage <> nil then ImageContainer.Bitmap.Assign(Model.CurrentImage); FTransitionEffect := Model.EffectOptions.TransitionEffectClass.Create(nil); FTransitionEffect.Enabled := False; FTransitionEffect.Stored := False; FTransitionEffect.Parent := ImageContainer; FTransitionAnimaton := TFloatAnimation.Create(nil); FTransitionAnimaton.Parent := FTransitionEffect; FTransitionAnimaton.Enabled := False; FTransitionAnimaton.Stored := False; FTransitionAnimaton.PropertyName := 'Progress'; FTransitionAnimaton.StopValue := 100; FTransitionAnimaton.Duration := Model.EffectOptions.Duration; FTransitionAnimaton.OnFinish := HandlerFinishAnimation; end; end; procedure TfgFlipViewEffectPresentation.FreeStyle; begin FTransitionEffect := nil; FTransitionAnimaton := nil; inherited FreeStyle; end; procedure TfgFlipViewEffectPresentation.HandlerFinishAnimation(Sender: TObject); begin try if (FNextImage <> nil) and (ImageContainer <> nil) then ImageContainer.Bitmap.Assign(FNextImage); if FTransitionEffect <> nil then FTransitionEffect.Enabled := False; finally Model.FinishChanging; end; end; procedure TfgFlipViewEffectPresentation.MMEffectOptionsChanged(var AMessage: TDispatchMessage); begin RecreateEffect; FTransitionAnimaton.Duration := Model.EffectOptions.Duration; end; procedure TfgFlipViewEffectPresentation.RecreateEffect; var EffectClass: TfgImageFXEffectClass; begin AssertIsNotNil(Model); AssertIsNotNil(Model.EffectOptions); AssertIsNotNil(Model.EffectOptions.TransitionEffectClass); // We don't recreat effect, if current effect class is the same as a Options class. EffectClass := Model.EffectOptions.TransitionEffectClass; if FTransitionEffect is EffectClass then Exit; if FTransitionEffect <> nil then begin FTransitionEffect.Parent := nil; FTransitionAnimaton := nil; end; FreeAndNil(FTransitionEffect); FTransitionEffect := EffectClass.Create(nil); FTransitionEffect.Enabled := False; FTransitionEffect.Stored := False; FTransitionEffect.Parent := ImageContainer; FTransitionAnimaton := TFloatAnimation.Create(nil); FTransitionAnimaton.Parent := FTransitionEffect; FTransitionAnimaton.Enabled := False; FTransitionAnimaton.Stored := False; FTransitionAnimaton.PropertyName := 'Progress'; FTransitionAnimaton.StopValue := 100; FTransitionAnimaton.Duration := Model.EffectOptions.Duration; FTransitionAnimaton.OnFinish := HandlerFinishAnimation; end; procedure TfgFlipViewEffectPresentation.ShowNextImage(const ANewItemIndex: Integer; const ADirection: TfgDirection; const AAnimate: Boolean); var RttiCtx: TRttiContext; RttiType: TRttiType; TargetBitmapProperty: TRttiProperty; TargetBitmap: TBitmap; begin inherited; if (csDesigning in ComponentState) or not AAnimate then begin FNextImage := nil; if ImageContainer <> nil then ImageContainer.Bitmap.Assign(Model.CurrentImage); Model.FinishChanging; end else begin FNextImage := Model.CurrentImage; if (FTransitionAnimaton <> nil) and (FTransitionAnimaton <> nil) then begin FTransitionAnimaton.Stop; if not (FTransitionEffect is Model.EffectOptions.TransitionEffectClass) then RecreateEffect; RttiCtx := TRttiContext.Create; try RttiType := RttiCtx.GetType(FTransitionEffect.ClassInfo); TargetBitmapProperty := RttiType.GetProperty('Target'); TargetBitmap := TBitmap(TargetBitmapProperty.GetValue(FTransitionEffect).AsObject); TargetBitmap.Assign(Model.CurrentImage); finally RttiCtx.Free; end; FTransitionEffect.Enabled := True; FTransitionAnimaton.StartValue := 0; FTransitionAnimaton.Start; end; end; end; initialization TPresentationProxyFactory.Current.Register('fgFlipView-Effect', TStyledPresentationProxy<TfgFlipViewEffectPresentation>); finalization TPresentationProxyFactory.Current.Unregister('fgFlipView-Effect', TStyledPresentationProxy<TfgFlipViewEffectPresentation>); end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Buttons, StdCtrls, Math; type TfrmGeldeenhede_Omskakeling = class(TForm) lblOmskakelingKoers: TLabel; lblsTotaleUitgawesRenV_Vreem: TLabel; lblSakgeldVreem: TLabel; lblTotaleUitgawesRenV: TLabel; lblSakgeld: TLabel; lblRandNodig: TLabel; edtOmskakelingKoers: TEdit; edtTotaleKosteVreem: TEdit; edtSakgeldVreem: TEdit; btnBereken: TButton; bmbReset: TBitBtn; bmbClose: TBitBtn; procedure btnBerekenClick(Sender: TObject); procedure bmbResetClick(Sender: TObject); procedure FormActivate(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmGeldeenhede_Omskakeling: TfrmGeldeenhede_Omskakeling; sOmsakelingKoers, sTotaleUitgawesRenV_Vreem, sSakgeld_Vreem, sTotaleUitgawesRenV, sSakgeld, sRandNodig : string; implementation {$R *.dfm} procedure TfrmGeldeenhede_Omskakeling.btnBerekenClick(Sender: TObject); var eVeranderKoers, eTotaleUitgawesRenV, eSakgeld, eTotaleR_Nodig : extended; begin eVeranderKoers := StrToFloat(edtOmskakelingKoers.text); eTotaleUitgawesRenV := StrToFloat(edtTotaleKosteVreem.Text) * eVeranderKoers; eSakgeld := StrToFloat(edtSakgeldVreem.Text) * eVeranderKoers; eTotaleR_Nodig := eTotaleUitgawesRenV + eSakgeld; sTotaleUitgawesRenV := 'Die reis en verblyfuitgawes (in Rand) :' + FloatToStrF(eTotaleUitgawesRenV, ffFixed, 5, 2); lblTotaleUitgawesRenV.Caption := sTotaleUitgawesRenV; sSakgeld := 'Die hoeveelheid sakgeld (in Rand) :' + FloatToStrF(eSakgeld, ffFixed, 5, 2); lblSakgeld.Caption := sSakgeld; sRandNodig := 'Die totale bedrag wat benodig word (in Rand) :' + FloatToStrF(eTotaleR_Nodig,ffFixed, 5, 2); lblRandNodig.Caption := sRandNodig; end; procedure TfrmGeldeenhede_Omskakeling.bmbResetClick(Sender: TObject); begin edtOmskakelingKoers.clear; edtSakgeldVreem.clear; edtTotaleKosteVreem.clear; edtOmskakelingKoers.setfocus; sTotaleUitgawesRenV := 'Die reis en verblyfuitgawes (in Rand) :'; lblTotaleUitgawesRenV.Caption := sTotaleUitgawesRenV; sSakgeld := 'Die hoeveelheid sakgeld (in Rand) :'; lblSakgeld.Caption := sSakgeld; sRandNodig := 'Die totale bedrag wat benodig word (in Rand) :'; lblRandNodig.Caption := sRandNodig; end; procedure TfrmGeldeenhede_Omskakeling.FormActivate(Sender: TObject); begin edtOmskakelingKoers.setfocus; end; end. // sOmsakelingKoers, sTotaleKosteVreem, sSakgeldVreem, // sSakgeld, sRandNodig : string; // Wat is die omskakelingskoers van die teiken-geldeenheid? (D.i Hoeveel // Rand het jy nodig om een eenheid van die vreemde geldeenheid aan te koop?) // Wat is die totale reis en verblyfuitgawes (in die vreemde geldeenheid)? // Wat is die geskatte hoeveelheid sakgeld wat benodig word (in die vreemde geldeenheid)? // Die reis en verblyfuitgawes (in Rand) : // Die hoeveelheid sakgeld (in Rand) : // Die totale bedrag wat benodig word (in Rand) :
unit Exportar; interface uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, Buttons, ExtCtrls, Dialogs, Mask, ToolEdit; type TExportDlg = class(TForm) OKBtn: TButton; CancelBtn: TButton; Bevel1: TBevel; Label1: TLabel; cbArchivo: TComboEdit; OpenDlg: TOpenDialog; rgFormato: TRadioGroup; rgReg: TRadioGroup; Label2: TLabel; edTitulo: TEdit; procedure cbArchivoButtonClick(Sender: TObject); procedure rgFormatoClick(Sender: TObject); private { Private declarations } procedure SetNombre(Indice: integer); public { Public declarations } end; var ExportDlg: TExportDlg; implementation {$R *.dfm} procedure TExportDlg.cbArchivoButtonClick(Sender: TObject); begin if OpenDlg.Execute then cbArchivo.Text := OpenDlg.FileName; end; procedure TExportDlg.rgFormatoClick(Sender: TObject); begin SetNombre( rgFormato.ItemIndex ); end; procedure TExportDlg.SetNombre( Indice: integer ); var Extension: string; begin case ( rgFormato.ItemIndex ) of 0: Extension := '.TXT'; 1: Extension := '.XLS'; 2: Extension := '.HTML'; // 3: end; cbArchivo.Text := ChangeFileExt( cbArchivo.Text, Extension ); end; end.
unit clEnderecosEmpresas; interface uses clendereco, clConexao, Vcl.Dialogs, System.SysUtils; type TEndrecosEmpresa = class(TEndereco) private FEmpresa: Integer; FSequencia: Integer; FTipo: String; FCorrespondencia: Integer; conexao : TConexao; procedure SetEmpresa(val: Integer); procedure SetSequencia(val: Integer); procedure SetTipo(val: String); procedure SetCorrespondencia(val: Integer); procedure MaxSeq; public property Sequencia: Integer read FSequencia write SetSequencia; property Empresa: Integer read FEmpresa write SetEmpresa; property Tipo: String read FTipo write SetTipo; property Correspondencia: Integer read FCorrespondencia write SetCorrespondencia; constructor Create; destructor Destroy; override; function Validar: Boolean; function Insert: Boolean; function Update: Boolean; function Delete(sFiltro: String): Boolean; function getObject(sId: String; sFiltro: String): Boolean; function getField(sCampo: String; sColuna: String): String; function getObjects: Boolean; end; const TABLENAME = 'CAD_ENDERECOS_EMPRESA'; implementation uses udm; procedure TEndrecosEmpresa.SetEmpresa(val: Integer); begin FEmpresa := val; end; procedure TEndrecosEmpresa.SetSequencia(val: Integer); begin FSequencia := val; end; procedure TEndrecosEmpresa.SetTipo(val: String); begin fTipo := val; end; procedure TEndrecosEmpresa.SetCorrespondencia(val: Integer); begin FCorrespondencia := val; end; constructor TEndrecosEmpresa.Create; begin inherited Create; conexao := TConexao.Create; end; destructor TEndrecosEmpresa.Destroy; begin conexao.Free; inherited Destroy; end; function TEndrecosEmpresa.Validar: Boolean; begin Result := False; if Self.Empresa = 0 then begin MessageDlg('Código de Empresa inválido!',mtWarning,[mbCancel],0); Exit; end; if Self.Empresa = 0 then begin MessageDlg('Sequência de Endereço de Empresa inválida!',mtWarning,[mbCancel],0); Exit; end; if Self.Tipo.IsEmpty then begin MessageDlg('Informe o Tipo de Endereço da Empresa!',mtWarning,[mbCancel],0); Exit; end; if Self.Endereco.IsEmpty then begin MessageDlg('Informe o Endereço da Empresa!',mtWarning,[mbCancel],0); Exit; end; if Self.Numero.IsEmpty then begin MessageDlg('Informe o Número do Endereço da Empresa (caso não exista informe SN ou 0)!',mtWarning,[mbCancel],0); Exit; end; if Self.Bairro.IsEmpty then begin MessageDlg('Informe o Bairro do Endereço da Empresa!',mtWarning,[mbCancel],0); Exit; end; if Self.Cidade.IsEmpty then begin MessageDlg('Informe a Cidade do Endereço da Empresa!',mtWarning,[mbCancel],0); Exit; end; if Self.UF.IsEmpty then begin MessageDlg('Informe a Sigla do Estado do Endereço da Empresa!',mtWarning,[mbCancel],0); Exit; end; Result := True; end; function TEndrecosEmpresa.Insert: Boolean; begin try Result := False; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; MaxSeq; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; dm.QryCRUD.SQL.Text := 'INSERT INTO ' + TABLENAME + ' ( ' + 'COD_AGENTE, ' + 'SEQ_ENDERECO, ' + 'DES_TIPO, ' + 'DOM_CORRESPONDENCIA,' + 'DES_LOGRADOURO, ' + 'NUM_LOGRADOURO, ' + 'DES_COMPLEMENTO, ' + 'DES_BAIRRO, ' + 'NOM_CIDADE, ' + 'UF_ESTADO, ' + 'NUM_CEP, ' + 'DES_REFERENCIA) ' + 'VALUES(' + ':CODIGO, ' + ':SEQUENCIA, ' + ':TIPO, ' + ':CORRESPONDENCIA, ' + ':ENDERECO, ' + ':NUMERO, ' + ':COMPLEMENTO, ' + ':BAIRRO, ' + ':CIDADE, ' + ':UF, ' + ':CEP, ' + ':REFERENCIA);'; dm.QryCRUD.ParamByName('CODIGO').AsInteger := Self.Empresa; dm.QryCRUD.ParamByName('SEQUENCIA').AsInteger := Self.Sequencia; dm.QryCRUD.ParamByName('TIPO').AsString := Self.Tipo; dm.QryCRUD.ParamByName('ENDERECO').AsString := Self.Endereco; dm.QryCRUD.ParamByName('NUMERO').AsString := Self.Numero; dm.QryCRUD.ParamByName('COMPLEMENTO').AsString := Self.Complemento; dm.QryCRUD.ParamByName('CORRESPONDENCIA').AsInteger := Self.Correspondencia; dm.QryCRUD.ParamByName('BAIRRO').AsString := Self.Bairro; dm.QryCRUD.ParamByName('CIDADE').AsString := Self.Cidade; dm.QryCRUD.ParamByName('UF').AsString := Self.UF; dm.QryCRUD.ParamByName('CEP').AsString := Self.Cep; dm.QryCRUD.ParamByName('REFERENCIA').AsString := Self.Referencia; dm.ZConn.PingServer; dm.QryCRUD.ExecSQL; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TEndrecosEmpresa.Update: Boolean; begin try Result := False; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; dm.QryCRUD.SQL.Text := 'UPDATE ' + TABLENAME + ' SET ' + 'DES_TIPO = :TIPO, ' + 'DOM_CORRESPONDENCIA = :CORRESPONDENCIA, ' + 'DES_LOGRADOURO = :ENDERECO, ' + 'NUM_LOGRADOURO = :NUMERO, ' + 'DES_COMPLEMENTO = :COMPLEMENTO, ' + 'DES_BAIRRO = :BAIRRO, ' + 'NOM_CIDADE = :CIDADE, ' + 'UF_ESTADO = :UF, ' + 'NUM_CEP = :CEP, ' + 'DES_REFERENCIA = :REFERENCIA ' + 'WHERE COD_EMPRESA = :CODIGO AND SEQ_ENDERECO = :SEQUENCIA'; dm.QryCRUD.ParamByName('CODIGO').AsInteger := Self.Empresa; dm.QryCRUD.ParamByName('SEQUENCIA').AsInteger := Self.Sequencia; dm.QryCRUD.ParamByName('TIPO').AsString := Self.Tipo; dm.QryCRUD.ParamByName('CORRESPONDENCIA').AsInteger := Self.Correspondencia; dm.QryCRUD.ParamByName('ENDERECO').AsString := Self.Endereco; dm.QryCRUD.ParamByName('NUMERO').AsString := Self.Numero; dm.QryCRUD.ParamByName('COMPLEMENTO').AsString := Self.Complemento; dm.QryCRUD.ParamByName('BAIRRO').AsString := Self.Bairro; dm.QryCRUD.ParamByName('CIDADE').AsString := Self.Cidade; dm.QryCRUD.ParamByName('UF').AsString := Self.UF; dm.QryCRUD.ParamByName('CEP').AsString := Self.Cep; dm.QryCRUD.ParamByName('REFERENCIA').AsString := Self.Referencia; dm.ZConn.PingServer; dm.QryCRUD.ExecSQL; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TEndrecosEmpresa.Delete(sFiltro: String): Boolean; begin try Result := False; if sFiltro.IsEmpty then begin Exit; end; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; dm.QryCRUD.SQL.Add('DELETE FROM ' + TABLENAME); if sFiltro = 'CODIGO' then begin dm.QryCRUD.SQL.Add('WHERE COD_EMPRESA = :CODIGO'); dm.QryCRUD.ParamByName('CODIGO').AsInteger := Self.Empresa; end else if sFiltro = 'TIPO' then begin dm.QryCRUD.SQL.Add('WHERE COD_EMPRESA = :CODIGO AND DES_TIPO = :TIPO'); dm.QryCRUD.ParamByName('CODIGO').AsInteger := Self.Empresa; dm.QryCRUD.ParamByName('TIPO').AsString := Self.Tipo; end; dm.ZConn.PingServer; dm.QryCRUD.ExecSQL; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TEndrecosEmpresa.getObject(sId: String; sFiltro: String): Boolean; begin try Result := False; if sId.IsEmpty then begin Exit; end; if sFiltro.IsEmpty then begin Exit; end; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; dm.QryGetObject.SQL.Add('SELECT * FROM ' + TABLENAME); if sFiltro = 'CODIGO' then begin dm.QryGetObject.SQL.Add('WHERE COD_EMPRESA = :CODIGO'); dm.QryGetObject.ParamByName('CODIGO').AsInteger := StrToInt(sId); end else if sFiltro = 'SEQUENCIA' then begin dm.QryGetObject.SQL.Add('WHERE COD_EMPRESA = :CODIGO AND SEQ_ENDERECO = :SEQUENCIA'); dm.QryGetObject.ParamByName('CODIGO').AsInteger := Self.Empresa; dm.QryGetObject.ParamByName('SEQUENCIA').AsInteger := StrToInt(sId); end else if sFiltro = 'TIPO' then begin dm.QryGetObject.SQL.Add('WHERE DES_TIPO = :TIPO'); dm.QryGetObject.ParamByName('TIPO').AsString := sId; end else if sFiltro = 'ENDERECO' then begin dm.QryGetObject.SQL.Add('WHERE DES_LOGRADOURO LIKE :ENDERECO'); dm.QryGetObject.ParamByName('ENDERECO').AsString := sId; end else if sFiltro = 'BAIRRO' then begin dm.QryGetObject.SQL.Add('WHERE DES_BAIRRO LIKE :BAIRRO'); dm.QryGetObject.ParamByName('BAIRRO').AsString := sId; end else if sFiltro = 'CIDADE' then begin dm.QryGetObject.SQL.Add('WHERE DES_CIDADE LIKE :CIDADE'); dm.QryGetObject.ParamByName('CIDADE').AsString := sId; end else if sFiltro = 'UF' then begin dm.QryGetObject.SQL.Add('WHERE UF_ESTADO = :UF'); dm.QryGetObject.ParamByName('UF').AsString := sId; end else if sFiltro = 'CEP' then begin dm.QryGetObject.SQL.Add('WHERE NUM_CEP = :CEP'); dm.QryGetObject.ParamByName('CEP').AsString := sId; end; dm.ZConn.PingServer; dm.QryGetObject.Open; if (not dm.QryGetObject.IsEmpty) then begin dm.QryGetObject.First; Self.Empresa := dm.QryGetObject.FieldByName('COD_AGENTE').AsInteger; Self.Sequencia := dm.QryGetObject.FieldByName('SEQ_ENDERECO').AsInteger; Self.Tipo := dm.QryGetObject.FieldByName('DES_TIPO').AsString; Self.Endereco := dm.QryGetObject.FieldByName('DES_LOGRADOURO').AsString; Self.Numero := dm.QryGetObject.FieldByName('NUM_LOGRADOURO').AsString; Self.Complemento := dm.QryGetObject.FieldByName('DES_COMPLEMENTO').AsString; Self.Bairro := dm.QryGetObject.FieldByName('DES_BAIRRO').AsString; Self.Cidade := dm.QryGetObject.FieldByName('NOM_CIDADE').AsString; Self.Cep := dm.QryGetObject.FieldByName('NUM_CEP').AsString; Self.Referencia := dm.QryGetObject.FieldByName('DES_REFERENCIA').AsString; Self.UF := dm.QryGetObject.FieldByName('UF_ESTADO').AsString; Self.Correspondencia := dm.QryGetObject.FieldByName('DOM_CORRESPONDENCIA').AsInteger; Result := True; Exit; end; dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TEndrecosEmpresa.getField(sCampo: String; sColuna: String): String; begin try Result := ''; if sCampo.IsEmpty then begin Exit; end; if sColuna.IsEmpty then begin Exit; end; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; dm.qryFields.Close; dm.qryFields.SQL.Clear; dm.qryFields.SQL.Add('SELECT ' + sCampo + ' FROM ' + TABLENAME); if sColuna = 'CODIGO' then begin dm.qryFields.SQL.Add('WHERE COD_EMPRESA = :CODIGO'); dm.qryFields.ParamByName('CODIGO').AsInteger := sELF.Empresa; end else if sColuna = 'SEQUENCIA' then begin dm.qryFields.SQL.Add('WHERE COD_EMPRESA = :CODIGO AND SEQ_ENDERECO = :SEQUENCIA'); dm.qryFields.ParamByName('CODIGO').AsInteger := Self.Empresa; dm.qryFields.ParamByName('SEQUENCIA').AsInteger := Self.Sequencia; end else if sColuna = 'TIPO' then begin dm.qryFields.SQL.Add('WHERE DES_TIPO = :TIPO'); dm.qryFields.ParamByName('TIPO').AsString := Self.Tipo; end else if sColuna = 'ENDERECO' then begin dm.qryFields.SQL.Add('WHERE DES_LOGRADOURO = :ENDERECO'); dm.qryFields.ParamByName('ENDERECO').AsString := Self.Endereco; end else if sColuna = 'BAIRRO' then begin dm.qryFields.SQL.Add('WHERE DES_BAIRRO = :BAIRRO'); dm.qryFields.ParamByName('BAIRRO').AsString := Self.Bairro; end else if sColuna = 'CIDADE' then begin dm.qryFields.SQL.Add('WHERE DES_CIDADE = :CIDADE'); dm.qryFields.ParamByName('CIDADE').AsString := Self.Cidade; end else if sColuna = 'UF' then begin dm.qryFields.SQL.Add('WHERE UF_ESTADO = :UF'); dm.qryFields.ParamByName('UF').AsString := Self.UF; end else if sColuna = 'CEP' then begin dm.qryFields.SQL.Add('WHERE NUM_CEP = :CEP'); dm.qryFields.ParamByName('CEP').AsString := Self.Cep; end; dm.ZConn.PingServer; dm.qryFields.Open; dm.qryFields.Open; if (not dm.qryFields.IsEmpty) then begin dm.qryFields.First; Result := dm.qryFields.FieldByName(sCampo).AsString; end; dm.qryFields.Close; dm.qryFields.SQL.Clear; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TEndrecosEmpresa.getObjects: Boolean; begin try Result := False; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; if dm.qryGetObject.Active then begin dm.qryGetObject.Close; end; dm.qryGetObject.SQL.Clear; dm.qryGetObject.SQL.Add('SELECT * FROM ' + TABLENAME); dm.ZConn.PingServer; dm.qryGetObject.Open; if (not dm.qryGetObject.IsEmpty) then begin Result := True; Exit; end; dm.qryGetObject.Close; dm.qryGetObject.SQL.Clear; except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; procedure TEndrecosEmpresa.MaxSeq; begin Try dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; dm.QryGetObject.SQL.Text := 'SELECT MAX(SEQ_ENDERECO) AS SEQUENCIA FROM ' + TABLENAME + ' WHERE COD_EMPRESA = :EMPRESA'; dm.QryGetObject.ParamByName('EMPRESA').AsInteger := Self.Empresa; dm.ZConn.PingServer; dm.QryGetObject.Open; if (not dm.QryGetObject.IsEmpty) then begin dm.QryGetObject.First; end; Self.Sequencia := (dm.QryGetObject.FieldByName('SEQUENCIA').AsInteger) + 1; dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; end.
unit stringutils; interface uses SysUtils, classes; procedure SymbolSeparated( str : string; symbol : char; res : TStringList ); function stringToId( str : string; texts : array of string; Ids : array of integer ) : integer; implementation procedure SymbolSeparated( str : string; symbol : char; res : TStringList ); var i : integer; tmp : string; begin tmp := ''; for i := 1 to length(str) do begin if str[i] <> symbol then tmp := tmp + str[i] else begin res.Add( tmp ); tmp := ''; end; end; if tmp <> '' then res.Add( tmp ); end; function stringToId( str : string; texts : array of string; Ids : array of integer ) : integer; var i : integer; begin i := 0; while (i < length(texts)) and (CompareText(str, texts[i]) <> 0) do inc( i ); if i < length(texts) then result := Ids[i] else result := -1; end; end.
//************************************************************************************************** // // Unit uAbout // unit for the Delphi Preview Handler https://github.com/RRUZ/delphi-preview-handler // // 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 uAbout.pas. // // The Initial Developer of the Original Code is Rodrigo Ruz V. // Portions created by Rodrigo Ruz V. are Copyright (C) 2011-2023 Rodrigo Ruz V. // All Rights Reserved. // //************************************************************************************************** unit uAbout; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, pngimage, Vcl.ImgList; type TFrmAbout = class(TForm) Panel1: TPanel; Button1: TButton; Image1: TImage; Label1: TLabel; LabelVersion: TLabel; MemoCopyRights: TMemo; Button3: TButton; btnCheckUpdates: TButton; ImageList1: TImageList; LinkLabel1: TLinkLabel; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Button3Click(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure Image3Click(Sender: TObject); procedure LinkLabel1Click(Sender: TObject); procedure btnCheckUpdatesClick(Sender: TObject); private { Private declarations } public { Public declarations } end; implementation uses ShellApi, uMisc; {$R *.dfm} procedure TFrmAbout.btnCheckUpdatesClick(Sender: TObject); var LBinaryPath, LUpdaterPath: string; begin LBinaryPath:=GetModuleLocation(); LUpdaterPath := ExtractFilePath(LBinaryPath)+'Updater.exe'; ShellExecute(0, 'open', PChar(LUpdaterPath), PChar(Format('"%s"', [LBinaryPath])), '', SW_SHOWNORMAL); end; procedure TFrmAbout.Button1Click(Sender: TObject); begin Close(); end; procedure TFrmAbout.Button3Click(Sender: TObject); begin ShellExecute(Handle, 'open', PChar('https://github.com/RRUZ/delphi-preview-handler'), nil, nil, SW_SHOW); end; procedure TFrmAbout.FormClose(Sender: TObject; var Action: TCloseAction); begin Action:=caFree; end; procedure TFrmAbout.FormCreate(Sender: TObject); var FileVersionStr: string; begin FileVersionStr:=uMisc.GetFileVersion(GetModuleLocation()); LabelVersion.Caption := Format('Version %s', [FileVersionStr]); MemoCopyRights.Lines.Add( 'Author Rodrigo Ruz - https://github.com/RRUZ - © 2011-2015 all rights reserved.'); MemoCopyRights.Lines.Add('https://github.com/RRUZ/delphi-preview-handler'); MemoCopyRights.Lines.Add(''); MemoCopyRights.Lines.Add('Third Party libraries and tools used'); MemoCopyRights.Lines.Add('SynEdit http://synedit.svn.sourceforge.net/viewvc/synedit/ all rights reserved.'); MemoCopyRights.Lines.Add(''); MemoCopyRights.Lines.Add('VCL Styles Utils https://github.com/RRUZ/vcl-styles-utils all rights reserved.'); MemoCopyRights.Lines.Add(''); MemoCopyRights.Lines.Add('This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/)'); MemoCopyRights.Lines.Add(''); MemoCopyRights.Lines.Add('Go Delphi Go'); end; procedure TFrmAbout.Image3Click(Sender: TObject); begin ShellExecute(Handle, 'open', 'http://tp.embarcadero.com/ctprefer?partner_id=1445&product_id=0',nil,nil, SW_SHOWNORMAL) ; end; procedure TFrmAbout.LinkLabel1Click(Sender: TObject); begin ShellExecute(Handle, 'open', PChar('https://github.com/RRUZ/delphi-preview-handler'), nil, nil, SW_SHOW); end; end.
unit UnitControl; interface uses Math, TypeControl; type TUnit = class private FId: Int64; FX: Double; FY: Double; protected constructor Create(const id: Int64; const x: Double; const y: Double); public function GetId: Int64; property Id: Int64 read GetId; function GetX: Double; property X: Double read GetX; function GetY: Double; property Y: Double read GetY; function GetDistanceTo(x: Double; y: Double): Double; overload; function GetDistanceTo(otherUnit: TUnit): Double; overload; function GetSquaredDistanceTo(x: Double; y: Double): Double; overload; function GetSquaredDistanceTo(otherUnit: TUnit): Double; overload; destructor Destroy; override; end; TUnitArray = array of TUnit; implementation constructor TUnit.Create(const id: Int64; const x: Double; const y: Double); begin FId := id; FX := x; FY := y; end; function TUnit.GetId: Int64; begin result := FId; end; function TUnit.GetX: Double; begin result := FX; end; function TUnit.GetY: Double; begin result := FY; end; function TUnit.getDistanceTo(x: Double; y: Double): Double; begin result := Sqrt(Sqr(FX - x) + Sqr(FY - y)); end; function TUnit.getDistanceTo(otherUnit: TUnit): Double; begin result := GetDistanceTo(otherUnit.FX, otherUnit.FY); end; function TUnit.getSquaredDistanceTo(x: Double; y: Double): Double; begin result := Sqr(FX - x) + Sqr(FY - y); end; function TUnit.getSquaredDistanceTo(otherUnit: TUnit): Double; begin result := GetSquaredDistanceTo(otherUnit.FX, otherUnit.FY); end; destructor TUnit.Destroy; begin inherited; end; end.
unit Providers.Mascaras.Factory; interface uses Providers.Mascaras.Intf; type TMascaras = class public class function CPF: IMascaras; class function CNPJ: IMascaras; class function Data: IMascaras; class function Telefone: IMascaras; class function Celular: IMascaras; class function CEP: IMascaras; class function Hora: IMascaras; end; implementation { TMascaras } uses Providers.Mascara.CPF, Providers.Mascara.CNPJ, Providers.Mascara.Data, Providers.Mascara.Celular, Providers.Mascara.Telefone, Providers.Mascara.CEP, Providers.Mascara.Hora; class function TMascaras.Celular: IMascaras; begin Result := TMascaraCelular.Create; end; class function TMascaras.CEP: IMascaras; begin Result := TMascaraCEP.Create; end; class function TMascaras.CNPJ: IMascaras; begin Result := TMascaraCNPJ.Create; end; class function TMascaras.CPF: IMascaras; begin Result := TMascaraCPF.Create; end; class function TMascaras.Data: IMascaras; begin Result := TMascaraData.Create; end; class function TMascaras.Hora: IMascaras; begin Result := TMascaraHora.Create; end; class function TMascaras.Telefone: IMascaras; begin Result := TMascaraTelefone.Create; end; end.
(* SimUnit.pas *) (* Library of Pascal functions/procedures used by Sim68k.pas November 1999 *) unit simunit; INTERFACE (* Constants and types. DO NOT REDEFINE them in Sim68k.pas *) const (* Data Size *) byteSize = 0; wordSize = 1; longSize = 2; type bit = boolean; (* True = 1, False = 0 *) twobits = 0..3; byte = $00..$FF; (* $80.. $7F, in 2's CF *) word = $0000..$FFFF; (* $8000..$7FFF, in 2's CF *) long = $80000000..$7FFFFFFF; (* $80000000..$7FFFFFFF, in 2's CF *) function Byte2Hex(Binary:byte) : string; (* Conversion of a byte to a hexadecimal string. For display only.*) function Word2Hex(Binary:word) : string; (* Conversion of a word to a hexadecimal string. For display only.*) function Long2Hex(Binary:long) : string; (* Conversion of a long word to a hexadecimal string. For display only.*) function Hex2Word(hex: string) : word; (* Conversion of a hexadecimal string to a word. *) function GetBits (V:word; FirstBit, LastBit:byte):word; (* Returns a substring of bits between FirstBit and LastBit from V whose type is word *) procedure SetBit (var V:word; Position:byte; Value:bit); (* Sets the bit of V indicated by Position to Value (false or true) *) procedure SetBits (var V:word; First, Last:byte; Value:word); (* Sets the bits of V between First and Last to the least significant bits of Value. *) procedure SetByte (var V:word; MSB:bit; Value:byte); (* Sets the byte of V whose type is word to Value *) (* MSB: false = Least Significant Byte, true = Most Significant Byte *) function GetWord (V:long; MSW:bit):word; (* Gets one word from V whose type is long. *) (* MSW: false = Least Significant Word, true = Most Significant Word *) procedure SetWord (var V:long; MSW:bit; Value:word); (* Sets one word of V whose type is long to Value. *) (* MSW: false = Least Significant Word, true = Most Significant Word *) function GetBitsL (V:long; FirstBit, LastBit:byte):long; (* Returns a substring of bits between FirstBit and LastBit from V whose type is long *) procedure SetBitL (var V:long; Position:byte; Value:bit); (* Sets the bit of V (whose type is long) indicated by Position to Value (false or true) *) procedure SetBitsL (var V:long; First, Last:byte; Value:long); (* Sets the bits of V (whose type is long) between First and Last to the least significant bits of Value *) procedure SetByteL (var V:long; Position:twobits; Value:byte); (* Sets one byte of V (whose type is long) indicated by position to Value. *) IMPLEMENTATION (***************************************************************************) (* *) (* Functions for converting from a byte or word to hexadecimal string. *) (* *) (***************************************************************************) function Byte2Hex(Binary:byte) : string; (* Conversion of a byte to a hexadecimal string. For display only.*) var hexDigit : byte; hexString: string ; i : integer; begin hexString := ''; for i := 0 to 1 do begin hexDigit := Binary MOD $10; if hexDigit < $A then hexString := chr(48+hexDigit) + hexString (* 0 to 9 *) else hexString := chr(55+hexDigit) + hexString; (* A to F *) Binary := Binary DIV $10 end; Byte2Hex := hexString (* Here is the string *) end; function Word2Hex(Binary:word) : string; (* Conversion of a word to a hexadecimal string. For display only.*) var hexDigit : byte; hexString: string ; i : integer; begin hexString := ''; for i := 0 to 3 do begin hexDigit := Binary MOD $10; if hexDigit < $A then hexString := chr(48+hexDigit) + hexString (* 0 to 9 *) else hexString := chr(55+hexDigit) + hexString; (* A to F *) Binary := Binary DIV $10 end; Word2Hex := hexString (* Here is the String *) end; function Long2Hex(Binary:long) : string; (* Conversion of a long word to a hexadecimal string. For display only.*) var hexDigit : byte; hexString: string ; i : integer; tempW : word; begin hexString := ''; (* the least significant word *) tempW := Binary AND $0000FFFF; for i := 0 to 3 do begin hexDigit := tempW MOD $10; if hexDigit < $A then hexString := chr(48+hexDigit) + hexString (* 0 a 9 *) else hexString := chr(55+hexDigit) + hexString; (* A a F *) tempW := tempW DIV $10 end; (* the most significant word *) tempW := (Binary AND $FFFF0000) SHR 16; for i := 0 to 3 do begin hexDigit := tempW MOD $10; if hexDigit < $A then hexString := chr(48+hexDigit) + hexString (* 0 a 9 *) else hexString := chr(55+hexDigit) + hexString; (* A a F *) tempW := tempW DIV $10 end; Long2Hex := hexString (* Here is the string *) end; function Hex2Word(hex: string) : word; (* Conversion of a hexadecimal string to a word. *) var hexWord : word ; i : integer; begin hexWord := 0; for i := 1 to length(hex) do begin if hex[i] <= '9' then hexWord := Ord(hex[i])-48 + hexWord*16 (* 0 a 9 *) else hexWord := Ord(hex[i])-55 + hexWord*16; (* A a F *) end; Hex2Word := hexWord (* Here is the Word *) end; (***************************************************************************) (* *) (* Functions for bit manipulation. *) (* *) (* Pascal, unlike C does not have operators that allow easy manipulation *) (* of bits within a byte or word. The following procedures and functions *) (* are designed to help you manipulate (extract and set) the bits. *) (* You may use or modify these procedures/functions or create others. *) (* *) (***************************************************************************) function GetBits (V:word; FirstBit, LastBit:byte):word; (* Returns a substring of bits between FirstBit and LastBit from V whose type is word *) (* Ex: 1111 11 *) (* Bit Positions: 5432 1098 7654 3210 *) (* V = $1234 (or %0001 0010 0011 0100) *) (* FirstBit = 3, LastBit = 9 *) (* The bits from 3 to 9 are %10 0011 0, *) (* The function returns $0046 (%0000 0000 0100 0110) *) begin GetBits := (V SHR FirstBit) AND ( (2 SHL (LastBit-FirstBit)) -1) end; procedure SetBit (var V:word; Position:byte; Value:bit); (* Sets the bit of V indicated by Position to Value (false or true) *) (* Example: If V=$0000, SetBit(V, 6, True) modifies V as $0040 *) begin V := (V AND ($FFFF - (1 SHL Position))) OR (ORD(Value) SHL Position) end; procedure SetBits (var V:word; First, Last:byte; Value:word); (* Sets the bits of V between First and Last to the least significant bits of Value. *) (* Example: If V=$F0F0, SetBits(V, 4, 11, $00BA) modifies V as $FBA0 *) var pos: Integer; begin for pos := First to Last do SetBit (V, pos, GetBits(Value, pos-First, pos-First)=1); end; procedure SetByte (var V:word; MSB:bit; Value:byte); (* Sets the byte of V whose type is word to Value *) (* MSB: false = Least Significant Byte, true = Most Significant Byte *) (* Example: If V=$1234, SetByte(V, True, $BD) modifies V as $BD34 *) begin if MSB then V := (V AND $00FF) OR (Value SHL 8) else V := (V AND $FF00) OR Value end; function GetWord (V:long; MSW:bit):word; (* Gets one word from V whose type is long. *) (* MSW: false = Least Significant Word, true = Most Significant Word *) Var TmpW:word; begin if MSW then TmpW := (V AND $FFFF0000) SHR 16 else TmpW := V AND $0000FFFF; GetWord := TmpW; end; procedure SetWord (var V:long; MSW:bit; Value:word); (* Sets one word of V whose type is long to Value. *) (* MSW: false = Least Significant Word, true = Most Significant Word *) begin if MSW then V := (V AND $0000FFFF) OR (Value SHL 16) else V := (V AND $FFFF0000) OR Value end; function GetBitsL (V:long; FirstBit, LastBit:byte):long; (* Returns a substring of bits between FirstBit and LastBit from V whose type is long *) begin GetBitsL := (V SHR FirstBit) AND ( (2 SHL (LastBit-FirstBit)) -1) end; procedure SetBitL (var V:long; Position:byte; Value:bit); (* Sets the bit of V (whose type is long) indicated by Position to Value (false or true) *) begin V := (V AND ($FFFFFFFF - (1 SHL Position))) OR (ORD(Value) SHL Position) end; procedure SetBitsL (var V:long; First, Last:byte; Value:long); (* Sets the bits of V (whose type is long) between First and Last to the least significant bits of Value *) var pos: Integer; begin for pos := First to Last do SetBitL (V, pos, GetBitsL(value, pos-First, pos-First)=1); end; procedure SetByteL (var V:long; Position:twobits; Value:byte); (* Sets one byte of V (whose type is long) indicated by position to value. *) begin case Position of 0: V := (V AND $FFFFFF00) OR Value; 1: V := (V AND $FFFF00FF) OR (Value SHL 8); 2: V := (V AND $FF00FFFF) OR (Value SHL 16); 3: V := (V AND $00FFFFFF) OR (Value SHL 24); end; end; (* Initialization : not necessary. *) end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.5 12/2/2004 9:26:44 PM JPMugaas Bug fix. Rev 1.4 11/11/2004 10:25:24 PM JPMugaas Added OpenProxy and CloseProxy so you can do RecvFrom and SendTo functions from the UDP client with SOCKS. You must call OpenProxy before using RecvFrom or SendTo. When you are finished, you must use CloseProxy to close any connection to the Proxy. Connect and disconnect also call OpenProxy and CloseProxy. Rev 1.3 11/11/2004 3:42:52 AM JPMugaas Moved strings into RS. Socks will now raise an exception if you attempt to use SOCKS4 and SOCKS4A with UDP. Those protocol versions do not support UDP at all. Rev 1.2 2004.05.20 11:39:12 AM czhower IdStreamVCL Rev 1.1 6/4/2004 5:13:26 PM SGrobety EIdMaxCaptureLineExceeded message string Rev 1.0 2004.02.03 4:19:50 PM czhower Rename Rev 1.15 10/24/2003 4:21:56 PM DSiders Addes resource string for stream read exception. Rev 1.14 2003.10.16 11:25:22 AM czhower Added missing ; Rev 1.13 10/15/2003 11:11:06 PM DSiders Added resource srting for exception raised in TIdTCPServer.SetScheduler. Rev 1.12 10/15/2003 11:03:00 PM DSiders Added resource string for circular links from transparent proxy. Corrected spelling errors. Rev 1.11 10/15/2003 10:41:34 PM DSiders Added resource strings for TIdStream and TIdStreamProxy exceptions. Rev 1.10 10/15/2003 8:48:56 PM DSiders Added resource strings for exceptions raised when setting thread component properties. Rev 1.9 10/15/2003 8:35:28 PM DSiders Added resource string for exception raised in TIdSchedulerOfThread.NewYarn. Rev 1.8 10/15/2003 8:04:26 PM DSiders Added resource strings for exceptions raised in TIdLogFile, TIdReply, and TIdIOHandler. Rev 1.7 10/15/2003 1:03:42 PM DSiders Created resource strings for TIdBuffer.Find exceptions. Rev 1.6 2003.10.14 1:26:44 PM czhower Uupdates + Intercept support Rev 1.5 10/1/2003 10:49:02 PM GGrieve Rework buffer for Octane Compability Rev 1.4 7/1/2003 8:32:32 PM BGooijen Added RSFibersNotSupported Rev 1.3 7/1/2003 02:31:34 PM JPMugaas Message for invalid IP address. Rev 1.2 5/14/2003 6:40:22 PM BGooijen RS for transparent proxy Rev 1.1 1/17/2003 05:06:04 PM JPMugaas Exceptions for scheduler string. Rev 1.0 11/13/2002 08:42:02 AM JPMugaas } unit IdResourceStringsCore; interface {$i IdCompilerDefines.inc} resourcestring RSNoBindingsSpecified = 'No bindings specified.'; RSCannotAllocateSocket = 'Cannot allocate socket.'; RSSocksUDPNotSupported = 'UDP is not support in this SOCKS version.'; RSSocksRequestFailed = 'Request rejected or failed.'; RSSocksRequestServerFailed = 'Request rejected because SOCKS server cannot connect.'; RSSocksRequestIdentFailed = 'Request rejected because the client program and identd report different user-ids.'; RSSocksUnknownError = 'Unknown socks error.'; RSSocksServerRespondError = 'Socks server did not respond.'; RSSocksAuthMethodError = 'Invalid socks authentication method.'; RSSocksAuthError = 'Authentication error to socks server.'; RSSocksServerGeneralError = 'General SOCKS server failure.'; RSSocksServerPermissionError = 'Connection not allowed by ruleset.'; RSSocksServerNetUnreachableError = 'Network unreachable.'; RSSocksServerHostUnreachableError = 'Host unreachable.'; RSSocksServerConnectionRefusedError = 'Connection refused.'; RSSocksServerTTLExpiredError = 'TTL expired.'; RSSocksServerCommandError = 'Command not supported.'; RSSocksServerAddressError = 'Address type not supported.'; RSInvalidIPAddress = 'Invalid IP Address'; RSInterceptCircularLink = '%d: Circular links are not allowed'; RSNotEnoughDataInBuffer = 'Not enough data in buffer. (%d/%d)'; RSTooMuchDataInBuffer = 'Too much data in buffer.'; RSCapacityTooSmall = 'Capacity cannot be smaller than Size.'; RSBufferIsEmpty = 'No bytes in buffer.'; RSBufferRangeError = 'Index out of bounds.'; RSFileNotFound = 'File "%s" not found'; RSNotConnected = 'Not Connected'; RSObjectTypeNotSupported = 'Object type not supported.'; RSIdNoDataToRead = 'No data to read.'; RSReadTimeout = 'Read timed out.'; RSReadLnWaitMaxAttemptsExceeded = 'Max line read attempts exceeded.'; RSAcceptTimeout = 'Accept timed out.'; RSReadLnMaxLineLengthExceeded = 'Max line length exceeded.'; RSRequiresLargeStream = 'Set LargeStream to True to send streams greater than 2GB'; RSDataTooLarge = 'Data is too large for stream'; RSConnectTimeout = 'Connect timed out.'; RSICMPNotEnoughtBytes = 'Not enough bytes received'; RSICMPNonEchoResponse = 'Non-echo type response received'; RSThreadTerminateAndWaitFor = 'Cannot call TerminateAndWaitFor on FreeAndTerminate threads'; RSAlreadyConnected = 'Already connected.'; RSTerminateThreadTimeout = 'Terminate Thread Timeout'; RSNoExecuteSpecified = 'No execute handler found.'; RSNoCommandHandlerFound = 'No command handler found.'; RSCannotPerformTaskWhileServerIsActive = 'Cannot perform task while server is active.'; RSThreadClassNotSpecified = 'Thread Class Not Specified.'; RSMaximumNumberOfCaptureLineExceeded = 'Maximum number of line allowed exceeded'; // S.G. 6/4/2004: IdIOHandler.DoCapture RSNoCreateListeningThread = 'Cannot create listening thread.'; RSInterceptIsDifferent = 'The IOHandler already has a different Intercept assigned'; //scheduler RSchedMaxThreadEx = 'The maximum number of threads for this scheduler is exceeded.'; //transparent proxy RSTransparentProxyCannotBind = 'Transparent proxy cannot bind.'; RSTransparentProxyCanNotSupportUDP = 'UDP Not supported by this proxy.'; //Fibers RSFibersNotSupported = 'Fibers are not supported on this system.'; // TIdICMPCast RSIPMCastInvalidMulticastAddress = 'The supplied IP address is not a valid multicast address [224.0.0.0 to 239.255.255.255].'; RSIPMCastNotSupportedOnWin32 = 'This function is not supported on Win32.'; RSIPMCastReceiveError0 = 'IP Broadcast Receive Error = 0.'; // Log strings RSLogConnected = 'Connected.'; RSLogDisconnected = 'Disconnected.'; RSLogEOL = '<EOL>'; // End of Line RSLogCR = '<CR>'; // Carriage Return RSLogLF = '<LF>'; // Line feed RSLogRecv = 'Recv '; // Receive RSLogSent = 'Sent '; // Send RSLogStat = 'Stat '; // Status RSLogFileAlreadyOpen = 'Unable to set Filename while log file is open.'; RSBufferMissingTerminator = 'Buffer terminator must be specified.'; RSBufferInvalidStartPos = 'Buffer start position is invalid.'; RSIOHandlerCannotChange = 'Cannot change a connected IOHandler.'; RSIOHandlerTypeNotInstalled = 'No IOHandler of type %s is installed.'; RSReplyInvalidCode = 'Reply Code is not valid: %s'; RSReplyCodeAlreadyExists = 'Reply Code already exists: %s'; RSThreadSchedulerThreadRequired = 'Thread must be specified for the scheduler.'; RSNoOnExecute = 'You must have an OnExecute event.'; RSThreadComponentLoopAlreadyRunning = 'Cannot set Loop property when the Thread is already running.'; RSThreadComponentThreadNameAlreadyRunning = 'Cannot set ThreadName when the Thread is already running.'; RSStreamProxyNoStack = 'A Stack has not been created for converting the data type.'; RSTransparentProxyCyclic = 'Transparent Proxy Cyclic error.'; RSTCPServerSchedulerAlreadyActive = 'Cannot change the scheduler while the server is Active.'; RSUDPMustUseProxyOpen = 'You must use proxyOpen'; //ICMP stuff RSICMPTimeout = 'Timeout'; //Destination Address -3 RSICMPNetUnreachable = 'net unreachable;'; RSICMPHostUnreachable = 'host unreachable;'; RSICMPProtUnreachable = 'protocol unreachable;'; RSICMPPortUnreachable = 'Port Unreachable'; RSICMPFragmentNeeded = 'Fragmentation Needed and Don''t Fragment was Set'; RSICMPSourceRouteFailed = 'Source Route Failed'; RSICMPDestNetUnknown = 'Destination Network Unknown'; RSICMPDestHostUnknown = 'Destination Host Unknown'; RSICMPSourceIsolated = 'Source Host Isolated'; RSICMPDestNetProhibitted = 'Communication with Destination Network is Administratively Prohibited'; RSICMPDestHostProhibitted = 'Communication with Destination Host is Administratively Prohibited'; RSICMPTOSNetUnreach = 'Destination Network Unreachable for Type of Service'; RSICMPTOSHostUnreach = 'Destination Host Unreachable for Type of Service'; RSICMPAdminProhibitted = 'Communication Administratively Prohibited'; RSICMPHostPrecViolation = 'Host Precedence Violation'; RSICMPPrecedenceCutoffInEffect = 'Precedence cutoff in effect'; //for IPv6 RSICMPNoRouteToDest = 'no route to destination'; RSICMPAAdminDestProhibitted = 'communication with destination administratively prohibited'; RSICMPSourceFilterFailed = 'source address failed ingress/egress policy'; RSICMPRejectRoutToDest = 'reject route to destination'; // Destination Address - 11 RSICMPTTLExceeded = 'time to live exceeded in transit'; RSICMPHopLimitExceeded = 'hop limit exceeded in transit'; RSICMPFragAsmExceeded = 'fragment reassembly time exceeded.'; //Parameter Problem - 12 RSICMPParamError = 'Parameter Problem (offset %d)'; //IPv6 RSICMPParamHeader = 'erroneous header field encountered (offset %d)'; RSICMPParamNextHeader = 'unrecognized Next Header type encountered (offset %d)'; RSICMPUnrecognizedOpt = 'unrecognized IPv6 option encountered (offset %d)'; //Source Quench Message -4 RSICMPSourceQuenchMsg = 'Source Quench Message'; //Redirect Message RSICMPRedirNet = 'Redirect datagrams for the Network.'; RSICMPRedirHost = 'Redirect datagrams for the Host.'; RSICMPRedirTOSNet = 'Redirect datagrams for the Type of Service and Network.'; RSICMPRedirTOSHost = 'Redirect datagrams for the Type of Service and Host.'; //echo RSICMPEcho = 'Echo'; //timestamp RSICMPTimeStamp = 'Timestamp'; //information request RSICMPInfoRequest = 'Information Request'; //mask request RSICMPMaskRequest = 'Address Mask Request'; // Traceroute RSICMPTracePacketForwarded = 'Outbound Packet successfully forwarded'; RSICMPTraceNoRoute = 'No route for Outbound Packet; packet discarded'; //conversion errors RSICMPConvUnknownUnspecError = 'Unknown/unspecified error'; RSICMPConvDontConvOptPresent = 'Don''t Convert option present'; RSICMPConvUnknownMandOptPresent = 'Unknown mandatory option present'; RSICMPConvKnownUnsupportedOptionPresent = 'Known unsupported option present'; RSICMPConvUnsupportedTransportProtocol = 'Unsupported transport protocol'; RSICMPConvOverallLengthExceeded = 'Overall length exceeded'; RSICMPConvIPHeaderLengthExceeded = 'IP header length exceeded'; RSICMPConvTransportProtocol_255 = 'Transport protocol > 255'; RSICMPConvPortConversionOutOfRange = 'Port conversion out of range'; RSICMPConvTransportHeaderLengthExceeded = 'Transport header length exceeded'; RSICMPConv32BitRolloverMissingAndACKSet = '32 Bit Rollover missing and ACK set'; RSICMPConvUnknownMandatoryTransportOptionPresent = 'Unknown mandatory transport option present'; //mobile host redirect RSICMPMobileHostRedirect = 'Mobile Host Redirect'; //IPv6 - Where are you RSICMPIPv6WhereAreYou = 'IPv6 Where-Are-You'; //IPv6 - I am here RSICMPIPv6IAmHere = 'IPv6 I-Am-Here'; // Mobile Regestration request RSICMPMobReg = 'Mobile Registration Request'; //Skip RSICMPSKIP = 'SKIP'; //Security RSICMPSecBadSPI = 'Bad SPI'; RSICMPSecAuthenticationFailed = 'Authentication Failed'; RSICMPSecDecompressionFailed = 'Decompression Failed'; RSICMPSecDecryptionFailed = 'Decryption Failed'; RSICMPSecNeedAuthentication = 'Need Authentication'; RSICMPSecNeedAuthorization = 'Need Authorization'; //IPv6 Packet Too Big RSICMPPacketTooBig = 'Packet Too Big (MTU = %d)'; { TIdCustomIcmpClient } // TIdSimpleServer RSCannotUseNonSocketIOHandler = 'Cannot use a non-socket IOHandler'; implementation end.
unit DAO.Menus; interface uses FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Control.Sistema, Model.Menus; type TMenusDAO = class private FConexao: TConexao; public constructor Create; function Inserir(AMenus: TMenus): Boolean; function Alterar(AMenus: TMenus): Boolean; function Excluir(AMenus: TMenus): Boolean; function Pesquisar(aParam: array of variant): TFDQuery; end; const TABLENAME = 'seguranca_menus'; implementation { TMenusDAO } function TMenusDAO.Alterar(AMenus: TMenus): Boolean; var FDQuery : TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery; FDQuery.ExecSQL('UPDATE ' + TABLENAME + ' SET DES_MENU = :PDES_MENU WHERE COD_SISTEMA = :PCOD_SISTEMA ' + 'AND COD_MODULO = :PCOD_MODULO AND COD_MENU = :PCOD_MENU', [Amenus.Descricao, AMenus.Sistema, AMenus.Modulo, AMenus.Codigo]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; constructor TMenusDAO.Create; begin FConexao := TConexao.Create; end; function TMenusDAO.Excluir(AMenus: TMenus): Boolean; var FDQuery : TFDQuery; begin try FDQuery := FConexao.ReturnQuery; Result := False; FDQuery.ExecSQL('DELETE FROM ' + TABLENAME + 'WHERE COD_SISTEMA = :PCOD_SISTEMA AND COD_MODULO = :PCOD_MODULO AND ' + 'COD_MENU = :PCOD_MENU', [AMenus.Sistema, AMenus.Modulo, AMenus.Codigo]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TMenusDAO.Inserir(AMenus: TMenus): Boolean; var FDQuery : TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery; FDQuery.ExecSQL('INSERT INTO ' + TABLENAME + ' (COD_SISTEMA, COD_MODULO, COD_MENU, DES_MENU) VALUES ' + ':P(COD_SISTEMA, :PCOD_MODULO, :PCOD_MENU, :PDES_MENU)', [AMenus.Sistema, AMenus.Modulo, AMenus.Codigo, AMenus.Descricao]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TMenusDAO.Pesquisar(aParam: array of variant): TFDQuery; var FDQuery: TFDQuery; begin FDQuery := FConexao.ReturnQuery(); if Length(aParam) < 2 then Exit; FDQuery.SQL.Clear; FDQuery.SQL.Add('select * from ' + TABLENAME); if aParam[0] = 'MODULO' then begin FDQuery.SQL.Add('WHERE COD_MODULO = :PCOD_MODULO'); FDQuery.ParamByName('PCOD_MODULO').AsInteger := aParam[1]; end; if aParam[0] = 'SISTEMA' then begin FDQuery.SQL.Add('WHERE COD_SISTEMA = :PCOD_SISTEMA'); FDQuery.ParamByName('PCOD_SISTEMA').AsInteger := aParam[1]; end; if aParam[0] = 'CODIGO' then begin FDQuery.SQL.Add('WHERE COD_MENU = :PCOD_MENU'); FDQuery.ParamByName('PCOD_MENU').AsInteger := aParam[1]; end; if aParam[0] = 'DESCRICAO' then begin FDQuery.SQL.Add('WHERE DES_MODULO = :PDES_MODULO'); FDQuery.ParamByName('PDES_MODULO').AsString := aParam[1]; end; if aParam[0] = 'MENU' then begin FDQuery.SQL.Add('WHERE COD_SISTEMA = :PCOD_SISTEMA AND COD_MODULO = :PCOD_MODULO AND COD_MENU = :PCOD_MENU'); FDQuery.ParamByName('PCOD_SISTEMA').AsInteger := aParam[1]; FDQuery.ParamByName('PCOD_MODULO').AsString := aParam[2]; FDQuery.ParamByName('PCOD_MENU').AsInteger := aParam[3]; end; if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add('WHERE ' + aParam[1]); end; if aParam[0] = 'APOIO' then begin FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT ' + aParam[1] + ' FROM ' + TABLENAME + ' ' + aParam[2]); end; FDQuery.Open(); Result := FDQuery; end; end.
(** This module contains the main wizard / menu wizard code for the IDE plugin. @Version 1.0 @Author David Hoyle @Date 07 Apr 2016 **) Unit WizardInterface; Interface Uses ToolsAPI, Menus, ExtCtrls, IDEOptionsInterface; {$INCLUDE CompilerDefinitions.inc} Type (** This class defines the main wizard interfaces for the application. **) TWizardTemplate = Class(TNotifierObject, IOTAWizard, IOTAMenuWizard) {$IFDEF D2005} Strict {$ENDIF} Private {$IFDEF DXE00} FOpFrame : TIDEHelpHelperIDEOptionsInterface; {$ENDIF} {$IFDEF D2005} Strict {$ENDIF} Protected Public {$IFDEF DXE00} Constructor Create; Destructor Destroy; Override; {$ENDIF} // IOTAWizard Function GetIDString: String; Function GetName: String; Function GetState: TWizardState; Procedure Execute; // IOTAMenuWizard Function GetMenuText: String; End; Implementation { TWizardTemplate } Uses DockableBrowserForm; {$IFDEF DXE00} (** A constructor for the TWizardTemplate class. @precon None. @postcon Creates and instance of the IDE Options Interface and registers it with the system. **) Constructor TWizardTemplate.Create; Begin FOpFrame := TIDEHelpHelperIDEOptionsInterface.Create; (BorlandIDEServices As INTAEnvironmentOptionsServices).RegisterAddInOptions(FOpFrame); End; (** A destructor for the TWizardTemplate class. @precon None. @postcon Unregisters the IDE Options Interface from the system. **) Destructor TWizardTemplate.Destroy; Begin (BorlandIDEServices As INTAEnvironmentOptionsServices).UnregisterAddInOptions(FOpFrame); FOpFrame := Nil; Inherited Destroy; End; {$ENDIF} (** This is the Exceute method for the IOTAWizard interface. @precon None. @postcon This is invoked when the menu item on the Help menu is selected and it displays the dockable browser. **) Procedure TWizardTemplate.Execute; Begin TfrmDockableBrowser.ShowDockableBrowser; End; (** This is the GetIDString method for the IOTAWizard interface. @precon None. @postcon Returns a ID string for the wizard. @return a String **) Function TWizardTemplate.GetIDString: String; Begin Result := 'DGH IDE HelpHelper'; End; (** This is the GetMenuText method for the IOTAMenuWizard interface. @precon None. @postcon Returns the menu text to be displayed under the Help menu. @return a String **) Function TWizardTemplate.GetMenuText: String; Begin Result := 'IDE Help Helper'; End; (** This is the GetName method for the IOTAWizard interface. @precon None. @postcon Returns the name of the wizard. @return a String **) Function TWizardTemplate.GetName: String; Begin Result := 'DGH IDE Help Helper'; End; (** This is the GetState method for the IOTAWizard interface. @precon None. @postcon Returns a set telling the IDe that this wizard is enabled. @return a TWizardState **) Function TWizardTemplate.GetState: TWizardState; Begin Result := [wsEnabled]; End; End.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.6 3/23/2005 4:52:28 AM JPMugaas Expansion with MLSD and WIN32.ea fact in MLSD directories as described by: http://www.raidenftpd.com/kb/kb000000049.htm This returns Win32 file attributes including some that Borland does not support. Rev 1.5 12/8/2004 8:35:18 AM JPMugaas Minor class restructure to support Unisys ClearPath. Rev 1.4 11/29/2004 2:45:30 AM JPMugaas Support for DOS attributes (Read-Only, Archive, System, and Hidden) for use by the Distinct32, OS/2, and Chameleon FTP list parsers. Rev 1.3 10/26/2004 9:27:34 PM JPMugaas Updated references. Rev 1.2 6/27/2004 1:45:36 AM JPMugaas Can now optionally support LastAccessTime like Smartftp's FTP Server could. I also made the MLST listing object and parser support this as well. Rev 1.1 6/4/2004 2:11:00 PM JPMugaas Added an indexed read-only Facts property to the MLST List Item so you can get information that we didn't parse elsewhere. MLST is extremely flexible. Rev 1.0 4/20/2004 2:43:20 AM JPMugaas Abstract FTPList objects for reuse. } unit IdFTPListTypes; interface {$i IdCompilerDefines.inc} uses Classes, IdFTPList; type { For FTP servers using OS/2 and other MS-DOS-like file systems that report file attributes } TIdDOSAttributes = class(TPersistent) protected FFileAttributes: Cardinal; function GetRead_Only: Boolean; procedure SetRead_Only(const AValue: Boolean); function GetHidden: Boolean; procedure SetHidden(const AValue: Boolean); function GetSystem: Boolean; procedure SetSystem(const AValue: Boolean); function GetArchive: Boolean; procedure SetArchive(const AValue: Boolean); function GetDirectory: Boolean; procedure SetDirectory(const AValue: Boolean); function GetNormal: Boolean; procedure SetNormal(const AValue: Boolean); public procedure Assign(Source: TPersistent); override; function GetAsString: String; virtual; function AddAttribute(const AString : String) : Boolean; published property FileAttributes : Cardinal read FFileAttributes write FFileAttributes; property AsString : String read GetAsString; // can't be ReadOnly because that's a reserved word property Read_Only : Boolean read GetRead_Only write SetRead_Only; property Archive : Boolean read GetArchive write SetArchive; property System : Boolean read GetSystem write SetSystem; property Directory : Boolean read GetDirectory write SetDirectory; property Hidden : Boolean read GetHidden write SetHidden; property Normal : Boolean read GetNormal write SetNormal; end; { Win32 Extended Attributes as in WIN32_FIND_DATA data structure in the Windows API. Analagous to the System.IO.FileAttributes enumeration in .Net } TIdWin32ea = class(TIdDOSAttributes) protected function GetDevice: Boolean; procedure SetDevice(const AValue: Boolean); function GetTemporary: Boolean; procedure SetTemporary(const AValue: Boolean); function GetSparseFile: Boolean; procedure SetSparseFile(const AValue: Boolean); // this is also called a junction and it works like a Unix Symbolic link to a dir function GetReparsePoint: Boolean; procedure SetReparsePoint(const AValue: Boolean); function GetCompressed: Boolean; procedure SetCompressed(const AValue: Boolean); function GetOffline: Boolean; procedure SetOffline(const AValue: Boolean); function GetNotContextIndexed: Boolean; procedure SetNotContextIndexed(const AValue: Boolean); function GetEncrypted: Boolean; procedure SetEncrypted(const AValue: Boolean); public function GetAsString: String; override; published property Device : Boolean read GetDevice write SetDevice; property Temporary : Boolean read GetTemporary write SetTemporary; property SparseFile : Boolean read GetSparseFile write SetSparseFile; property ReparsePoint : Boolean read GetReparsePoint write SetReparsePoint; property Compressed : Boolean read GetCompressed write SetCompressed; property Offline : Boolean read GetOffline write SetOffline; property NotContextIndexed : Boolean read GetNotContextIndexed write SetNotContextIndexed; property Encrypted : Boolean read GetEncrypted write SetEncrypted; end; //For NLST and Cisco IOS TIdMinimalFTPListItem = class(TIdFTPListItem) public constructor Create(AOwner: TCollection); override; end; //This is for some mainframe items which are based on records TIdRecFTPListItem = class(TIdFTPListItem) protected //These are for VM/CMS which uses a record type of file system FRecLength : Integer; FRecFormat : String; FNumberRecs : Integer; property RecLength : Integer read FRecLength write FRecLength; property RecFormat : String read FRecFormat write FRecFormat; property NumberRecs : Integer read FNumberRecs write FNumberRecs; end; { listing formats that include Creation timestamp information } TIdCreationDateFTPListItem = class(TIdFTPListItem) protected FCreationDate: TDateTime; public constructor Create(AOwner: TCollection); override; property CreationDate: TDateTime read FCreationDate write FCreationDate; end; // for MLST, MLSD listing outputs TIdMLSTFTPListItem = class(TIdCreationDateFTPListItem) protected FAttributesAvail : Boolean; FAttributes : TIdWin32ea; FCreationDateGMT : TDateTime; FLastAccessDate: TDateTime; FLastAccessDateGMT : TDateTime; FLinkedItemName : String; //Unique ID for an item to prevent yourself from downloading something twice FUniqueID : String; //MLIST things FMLISTPermissions : String; function GetFact(const AName : String) : String; public constructor Create(AOwner: TCollection); override; destructor Destroy; override; //Creation time values are for MLSD data output and can be returned by the //the MLSD parser in some cases property ModifiedDateGMT; property CreationDateGMT : TDateTime read FCreationDateGMT write FCreationDateGMT; property LastAccessDate: TDateTime read FLastAccessDate write FLastAccessDate; property LastAccessDateGMT : TDateTime read FLastAccessDateGMT write FLastAccessDateGMT; //Valid only with EPLF and MLST property UniqueID : string read FUniqueID write FUniqueID; //MLIST Permissions property MLISTPermissions : string read FMLISTPermissions write FMLISTPermissions; property Facts[const Name: string] : string read GetFact; property AttributesAvail : Boolean read FAttributesAvail write FAttributesAvail; property Attributes : TIdWin32ea read FAttributes; property LinkedItemName : String read FLinkedItemName write FLinkedItemName; end; //for some parsers that output an owner sometimes TIdOwnerFTPListItem = class(TIdFTPListItem) protected FOwnerName : String; public property OwnerName : String read FOwnerName write FOwnerName; end; { This class type is used by Novell Netware, Novell Print Services for Unix with DOS namespace, and HellSoft FTPD for Novell Netware } TIdNovellBaseFTPListItem = class(TIdOwnerFTPListItem) protected FNovellPermissions : String; public property NovellPermissions : string read FNovellPermissions write FNovellPermissions; end; //Bull GCOS 8 uses this and Unix will use a descendent TIdUnixPermFTPListItem = class(TIdOwnerFTPListItem) protected FUnixGroupPermissions: string; FUnixOwnerPermissions: string; FUnixOtherPermissions: string; public property UnixOwnerPermissions: string read FUnixOwnerPermissions write FUnixOwnerPermissions; property UnixGroupPermissions: string read FUnixGroupPermissions write FUnixGroupPermissions; property UnixOtherPermissions: string read FUnixOtherPermissions write FUnixOtherPermissions; end; // Unix and Novell Netware Print Services for Unix with NFS namespace need to use this TIdUnixBaseFTPListItem = class(TIdUnixPermFTPListItem) protected FLinkCount: Integer; FGroupName: string; FLinkedItemName : string; public property LinkCount: Integer read FLinkCount write FLinkCount; property GroupName: string read FGroupName write FGroupName; property LinkedItemName : string read FLinkedItemName write FLinkedItemName; end; TIdDOSBaseFTPListItem = class(TIdFTPListItem) protected FAttributes : TIdDOSAttributes; procedure SetAttributes(AAttributes : TIdDOSAttributes); public constructor Create(AOwner: TCollection); override; destructor Destroy; override; property Attributes : TIdDOSAttributes read FAttributes write SetAttributes; end; {These are needed for interpretting Win32.ea in some MLSD output} const IdFILE_ATTRIBUTE_READONLY = $00000001; IdFILE_ATTRIBUTE_HIDDEN = $00000002; IdFILE_ATTRIBUTE_SYSTEM = $00000004; IdFILE_ATTRIBUTE_DIRECTORY = $00000010; IdFILE_ATTRIBUTE_ARCHIVE = $00000020; IdFILE_ATTRIBUTE_DEVICE = $00000040; IdFILE_ATTRIBUTE_NORMAL = $00000080; IdFILE_ATTRIBUTE_TEMPORARY = $00000100; IdFILE_ATTRIBUTE_SPARSE_FILE = $00000200; IdFILE_ATTRIBUTE_REPARSE_POINT = $00000400; IdFILE_ATTRIBUTE_COMPRESSED = $00000800; IdFILE_ATTRIBUTE_OFFLINE = $00001000; IdFILE_ATTRIBUTE_NOT_CONTENT_INDEXED = $00002000; IdFILE_ATTRIBUTE_ENCRYPTED = $00004000; implementation uses IdException, IdFTPCommon, IdGlobal, SysUtils; { TIdMinimalFTPListItem } constructor TIdMinimalFTPListItem.Create(AOwner: TCollection); begin inherited Create(AOwner); FSizeAvail := False; FModifiedAvail := False; end; { TIdMLSTFTPListItem } constructor TIdMLSTFTPListItem.Create(AOwner: TCollection); begin inherited Create(AOwner); FAttributesAvail := False; FAttributes := TIdWin32ea.Create; end; destructor TIdMLSTFTPListItem.Destroy; begin FreeAndNil(FAttributes); inherited Destroy; end; function TIdMLSTFTPListItem.GetFact(const AName: String): String; var LFacts : TStrings; begin LFacts := TStringList.Create; try ParseFacts(Data, LFacts); Result := LFacts.Values[AName]; finally FreeAndNil(LFacts); end; end; { TIdDOSBaseFTPListItem } constructor TIdDOSBaseFTPListItem.Create(AOwner: TCollection); begin inherited Create(AOwner); FAttributes := TIdDOSAttributes.Create; end; destructor TIdDOSBaseFTPListItem.Destroy; begin FreeAndNil(FAttributes); inherited Destroy; end; procedure TIdDOSBaseFTPListItem.SetAttributes( AAttributes: TIdDOSAttributes); begin FAttributes.Assign(AAttributes); end; { TIdDOSAttributes } function TIdDOSAttributes.AddAttribute(const AString: String): Boolean; var i : Integer; S: String; begin S := UpperCase(AString); for i := 1 to Length(S) do begin case CharPosInSet(S, i, 'RASHW-D') of //R 1 : Read_Only := True; //A 2 : Archive := True; //S 3 : System := True; //H 4 : Hidden := True; //W - W was added only for Distinct32's FTP server which reports 'w' if you //write instead of a r for read-only 5 : Read_Only := False; 6,7 : ;//for the "-" and "d" that Distinct32 may give else begin Result := False; //failure Exit; end; end; end; Result := True; end; procedure TIdDOSAttributes.Assign(Source: TPersistent); begin if Source is TIdDOSAttributes then begin FFileAttributes := (Source as TIdDOSAttributes).FFileAttributes; end else begin inherited Assign(Source); end; end; function TIdDOSAttributes.GetAsString: String; //This is just a handy thing for some programs to try //to output attribute bits similarly to the DOS //ATTRIB command // //which is like this: // // R C:\File //A SH C:\File begin Result := ' '; if Archive then begin Result[1] := 'A'; end; if System then begin Result[4] := 'S'; end; if Hidden then begin Result[5] := 'H'; end; if Read_Only then begin Result[6] := 'R'; end; end; function TIdDOSAttributes.GetRead_Only: Boolean; begin Result := (FFileAttributes and IdFILE_ATTRIBUTE_READONLY) > 0; end; function TIdDOSAttributes.GetHidden: Boolean; begin Result := (FFileAttributes and IdFILE_ATTRIBUTE_HIDDEN) > 0; end; function TIdDOSAttributes.GetSystem: Boolean; begin Result := (FFileAttributes and IdFILE_ATTRIBUTE_SYSTEM) > 0; end; function TIdDOSAttributes.GetDirectory: Boolean; begin Result := (FFileAttributes and IdFILE_ATTRIBUTE_DIRECTORY) > 0; end; function TIdDOSAttributes.GetArchive: Boolean; begin Result := (FFileAttributes and IdFILE_ATTRIBUTE_ARCHIVE) > 0; end; function TIdDOSAttributes.GetNormal: Boolean; begin Result := (FFileAttributes and IdFILE_ATTRIBUTE_NORMAL) > 0; end; procedure TIdDOSAttributes.SetRead_Only(const AValue: Boolean); begin if AValue then begin FFileAttributes := FFileAttributes or IdFILE_ATTRIBUTE_READONLY; end else begin FFileAttributes := FFileAttributes and (not IdFILE_ATTRIBUTE_READONLY); end; end; procedure TIdDOSAttributes.SetHidden(const AValue: Boolean); begin if AValue then begin FFileAttributes := FFileAttributes or IdFILE_ATTRIBUTE_HIDDEN; end else begin FFileAttributes := FFileAttributes and (not IdFILE_ATTRIBUTE_HIDDEN); end; end; procedure TIdDOSAttributes.SetSystem(const AValue: Boolean); begin if AValue then begin FFileAttributes := FFileAttributes or IdFILE_ATTRIBUTE_SYSTEM; end else begin FFileAttributes := FFileAttributes and (not IdFILE_ATTRIBUTE_SYSTEM); end; end; procedure TIdDOSAttributes.SetDirectory(const AValue: Boolean); begin if AValue then begin FFileAttributes := FFileAttributes or IdFILE_ATTRIBUTE_DIRECTORY; end else begin FFileAttributes := FFileAttributes and (not IdFILE_ATTRIBUTE_DIRECTORY); end; end; procedure TIdDOSAttributes.SetArchive(const AValue: Boolean); begin if AValue then begin FFileAttributes := FFileAttributes or IdFILE_ATTRIBUTE_ARCHIVE; end else begin FFileAttributes := FFileAttributes and (not IdFILE_ATTRIBUTE_ARCHIVE); end; end; procedure TIdDOSAttributes.SetNormal(const AValue: Boolean); begin if AValue then begin FFileAttributes := FFileAttributes or IdFILE_ATTRIBUTE_NORMAL; end else begin FFileAttributes := FFileAttributes and (not IdFILE_ATTRIBUTE_NORMAL); end; end; { TIdCreationDateFTPListItem } constructor TIdCreationDateFTPListItem.Create(AOwner: TCollection); begin inherited Create(AOwner); SizeAvail := False; ModifiedAvail := False; end; { TIdWin32ea } function TIdWin32ea.GetDevice: Boolean; begin Result := (FFileAttributes and IdFILE_ATTRIBUTE_DEVICE) > 0; end; function TIdWin32ea.GetTemporary: Boolean; begin Result := (FFileAttributes and IdFILE_ATTRIBUTE_TEMPORARY) > 0; end; function TIdWin32ea.GetSparseFile: Boolean; begin Result := (FFileAttributes and IdFILE_ATTRIBUTE_SPARSE_FILE) > 0; end; function TIdWin32ea.GetReparsePoint: Boolean; begin Result := (FFileAttributes and IdFILE_ATTRIBUTE_REPARSE_POINT) > 0; end; function TIdWin32ea.GetCompressed: Boolean; begin Result := (FFileAttributes and IdFILE_ATTRIBUTE_COMPRESSED) > 0; end; function TIdWin32ea.GetOffline: Boolean; begin Result := (FFileAttributes and IdFILE_ATTRIBUTE_OFFLINE) > 0; end; function TIdWin32ea.GetNotContextIndexed: Boolean; begin Result := (FFileAttributes and IdFILE_ATTRIBUTE_NOT_CONTENT_INDEXED) > 0; end; function TIdWin32ea.GetEncrypted: Boolean; begin Result := (FFileAttributes and IdFILE_ATTRIBUTE_ENCRYPTED) > 0; end; procedure TIdWin32ea.SetDevice(const AValue: Boolean); begin if AValue then begin FFileAttributes := FFileAttributes or IdFILE_ATTRIBUTE_DEVICE; end else begin FFileAttributes := FFileAttributes and (not IdFILE_ATTRIBUTE_DEVICE); end; end; procedure TIdWin32ea.SetTemporary(const AValue: Boolean); begin if AValue then begin FFileAttributes := FFileAttributes or IdFILE_ATTRIBUTE_TEMPORARY; end else begin FFileAttributes := FFileAttributes and (not IdFILE_ATTRIBUTE_TEMPORARY); end; end; procedure TIdWin32ea.SetSparseFile(const AValue: Boolean); begin if AValue then begin FFileAttributes := FFileAttributes or IdFILE_ATTRIBUTE_SPARSE_FILE; end else begin FFileAttributes := FFileAttributes and (not IdFILE_ATTRIBUTE_SPARSE_FILE); end; end; procedure TIdWin32ea.SetReparsePoint(const AValue: Boolean); begin if AValue then begin FFileAttributes := FFileAttributes or IdFILE_ATTRIBUTE_NORMAL; end else begin FFileAttributes := FFileAttributes and (not IdFILE_ATTRIBUTE_NORMAL); end; end; procedure TIdWin32ea.SetCompressed(const AValue: Boolean); begin if AValue then begin FFileAttributes := FFileAttributes or IdFILE_ATTRIBUTE_NORMAL; end else begin FFileAttributes := FFileAttributes and (not IdFILE_ATTRIBUTE_NORMAL); end; end; procedure TIdWin32ea.SetOffline(const AValue: Boolean); begin if AValue then begin FFileAttributes := FFileAttributes or IdFILE_ATTRIBUTE_OFFLINE; end else begin FFileAttributes := FFileAttributes and (not IdFILE_ATTRIBUTE_OFFLINE); end; end; procedure TIdWin32ea.SetNotContextIndexed(const AValue: Boolean); begin if AValue then begin FFileAttributes := FFileAttributes or IdFILE_ATTRIBUTE_NOT_CONTENT_INDEXED; end else begin FFileAttributes := FFileAttributes and (not IdFILE_ATTRIBUTE_NOT_CONTENT_INDEXED); end; end; procedure TIdWin32ea.SetEncrypted(const AValue: Boolean); begin if AValue then begin FFileAttributes := FFileAttributes or IdFILE_ATTRIBUTE_ENCRYPTED; end else begin FFileAttributes := FFileAttributes and (not IdFILE_ATTRIBUTE_ENCRYPTED); end; end; function TIdWin32ea.GetAsString: String; //we'll do this similarly to 4NT //which renders the bits like this order: //RHSADENTJPCOI begin Result := ' '; if Read_Only then begin Result[1] := 'R'; end; if Hidden then begin Result[2] := 'H'; end; if System then begin Result[3] := 'S'; end; if Archive then begin Result[4] := 'A'; end; if Directory then begin Result[5] := 'D'; end; if Encrypted then begin Result[6] := 'E'; end; if Normal then begin Result[7] := 'N'; end; if Temporary then begin Result[8] := 'T'; end; if ReparsePoint then begin Result[9] := 'J'; end; if SparseFile then begin Result[10] := 'P'; end; if Compressed then begin Result[11] := 'C'; end; if Offline then begin Result[12] := 'O'; end; if NotContextIndexed then begin Result[13] := 'I'; end; end; end.
unit TCPSocket; interface uses scktcomp, winsock, Sysutils, consts, RTLConsts, windows, StatusThread, Classes, SyncObjs; type TSocket = winsock.TSocket; TTCPHost = record IP: String; Port: Word; end; TSimpleTCPSocket = class private function GetPeerAddr: SockAddr_In; protected FSocket: TSocket; FConnected: Boolean; procedure Error(Source: string); public function ReceiveBuf(var Buf; Size: Word): Integer; function ReceiveLength: Integer; function SendBuf(var Buf; Size: Word): Integer; constructor Create(Socket: TSocket = INVALID_SOCKET); procedure Close; destructor Destroy; override; function Accept: TSocket; procedure Bind(Port: Word); function Connect(IP: String; Port: Word): boolean; function RemoteHost: TTCPHost; procedure Listen; function Connected: Boolean; function SelectWrite(Timeout: Word): Boolean; end; TTCPSocket = class(TSimpleTCPSocket) public procedure ReceiveBuf(var Buf; Size: Word); procedure SendBuf(var Buf; Size: Word); end; TSimpleServerClientConnect = procedure(Sender: TObject; newSocket: TSocket) of object; TSimpleServer = class(TSThread) private NewSocket: TSocket; FServerPort: Integer; FServerActive: Boolean; Started: TEvent; procedure DoOnClientConnect; public ListenSocket: TTCPSocket; OnClientConnect: TSimpleServerClientConnect; property ServerPort: Integer read FServerPort; procedure Execute; override; function Start(Port: Integer): Boolean; procedure Stop; destructor Destroy; override; constructor Create; //ListenSocket, Aktiviert wenn Server aktiv (s. StartServer, StopServer) end; TSimpleServerComponent = class(TComponent) private FOnClientConnect: TSimpleServerClientConnect; procedure SetOnClientConnect(p: TSimpleServerClientConnect); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published SimpleServer: TSimpleServer; property OnClientConnect: TSimpleServerClientConnect read FOnClientConnect write SetOnClientConnect; end; var WSAData: TWSAData; function GetHostByName(Host: String): in_addr; procedure Register; implementation procedure Startup; var ErrorCode: Integer; begin ErrorCode := WSAStartup($0101, WSAData); if ErrorCode <> 0 then raise ESocketError.CreateResFmt(@sWindowsSocketError, [SysErrorMessage(ErrorCode), ErrorCode, 'WSAStartup']); end; function TSimpleTCPSocket.Accept: TSocket; begin //Nur für Listen Sockets, blockiert bis anfrage von clients, erstellt neuen Socket dessen Handle mit Result zurückgegeben wird! "Lauscht" aber dann weiter! Result := winsock.accept(FSocket,nil,nil); if Result = INVALID_SOCKET then Error('Accept'); end; procedure TSimpleTCPSocket.Bind(Port: Word); var sockaddr: sockaddr_in; begin //vor listen aufzurufen! sockaddr.sin_family := AF_INET; sockaddr.sin_port := htons(Port); sockaddr.sin_addr.S_addr := INADDR_ANY; if (winsock.bind(FSocket,sockaddr,sizeof(sockaddr)) = SOCKET_ERROR) then Error('Bind'); end; procedure TSimpleTCPSocket.Close; begin FConnected := False; closesocket(FSocket); end; function TSimpleTCPSocket.Connect(IP: String; Port: Word): boolean; var sockaddr: sockaddr_in; begin sockaddr.sin_family := AF_INET; sockaddr.sin_port := htons(Port); sockaddr.sin_addr.S_addr := inet_addr(PChar(IP)); if sockaddr.sin_addr.S_addr = -1 then sockaddr.sin_addr := getHostByName(IP); if (winsock.connect(FSocket,sockaddr,sizeof(sockaddr)) = SOCKET_ERROR) then Error('Connect') else FConnected := True; Result := FConnected; end; function TSimpleTCPSocket.Connected: Boolean; begin Result := FConnected; if Result then GetPeerAddr; //-> das müsste ja dann gehen!? (wenn nicht is er nichtmehr verbunden!) end; constructor TSimpleTCPSocket.Create(Socket: TSocket = INVALID_SOCKET); begin inherited Create; Startup; FSocket := Socket; FConnected := False; if FSocket = INVALID_SOCKET then begin FSocket := winsock.Socket(AF_INET,SOCK_STREAM,0); if FSocket = INVALID_SOCKET then Error('Create'); end else FConnected := True; end; destructor TSimpleTCPSocket.Destroy; begin Close; inherited; end; procedure TSimpleTCPSocket.Error(Source: string); var ErrorCode: Integer; begin ErrorCode := WSAGetLastError; if ErrorCode <> 0 then begin Close; raise ESocketError.Create(SysErrorMessage(ErrorCode) + ' (' + inttostr(ErrorCode) + ') API: ' + Source); end; end; function TSimpleTCPSocket.GetPeerAddr: SockAddr_In; var length: integer; begin length := sizeof(Result); if getpeername(FSocket,Result,length) = SOCKET_ERROR then Error('GetPeerAddress'); end; procedure TSimpleTCPSocket.Listen; var r: Integer; begin r := winsock.listen(FSocket,SOMAXCONN); if (r = SOCKET_ERROR) then Error('Listen'); end; function TSimpleTCPSocket.ReceiveBuf(var Buf; Size: Word): Integer; begin if not FConnected then raise ESocketError.Create('API: ReceiveBuf, Socket nicht verbunden!'); Result := recv(FSocket, Buf, Size, 0); if (Result = SOCKET_ERROR) then Error('ReceiveBuf'); if Result = 0 then Close; end; function TSimpleTCPSocket.ReceiveLength: Integer; begin Result := 0; if FConnected then if ioctlsocket(FSocket, FIONREAD, Longint(Result)) = SOCKET_ERROR then Error('ReceiveLength'); end; function TSimpleTCPSocket.RemoteHost: TTCPHost; var PeerAddr: SockAddr_In; begin PeerAddr := getpeeraddr; Result.IP := inet_ntoa(peeraddr.sin_addr); Result.Port := ntohs(peeraddr.sin_port); end; function TSimpleTCPSocket.SelectWrite(Timeout: Word): Boolean; var fds: TFDSET; time: TTimeval; count: integer; begin FD_ZERO(fds); FD_SET(FSocket, fds); time.tv_sec := Timeout div 1000; time.tv_usec := Timeout - Time.tv_sec*1000; count := Select(0,nil,@fds,nil,@time); if count = SOCKET_ERROR then Error('SelectWrite'); Result := count = 1; end; function TSimpleTCPSocket.SendBuf(var Buf; Size: Word): Integer; begin if not FConnected then raise ESocketError.Create('API: SendBuf, Socket nicht verbunden!'); Result := send(FSocket, Buf, Size, 0); if Result = SOCKET_ERROR then Error('SendBuf'); end; function GetHostByName(Host: String): in_addr; var hostaddr: PHostEnt; begin hostaddr := winsock.gethostbyname(Pchar(Host)); if hostaddr <> nil then Result := PInAddr(hostaddr^.h_addr^)^ else Result.S_addr := -1; end; procedure TTCPSocket.ReceiveBuf(var Buf; Size: Word); var ReadPos,ReadCount: Word; ReadPointer: Pointer; begin ReadPos := 0; repeat ReadPointer := Pointer(Cardinal(@Buf) + ReadPos); ReadCount := inherited ReceiveBuf(ReadPointer^,Size-ReadPos); ReadPos := ReadPos + ReadCount; until (not FConnected)or(ReadPos = Size); end; procedure TTCPSocket.SendBuf(var Buf; Size: Word); var SendPos,SendCount: Word; SendPointer: Pointer; begin SendPos := 0; repeat SendPointer := Pointer(Cardinal(@Buf) + SendPos); SendCount := inherited SendBuf(SendPointer^,Size-SendPos); SendPos := SendPos + SendCount; until (not FConnected)or(SendPos = Size); end; procedure TSimpleServer.Stop; begin FServerActive := False; if ListenSocket <> nil then ListenSocket.Close; end; function TSimpleServer.Start(Port: Integer): Boolean; begin if FServerActive then raise Exception.Create('TSimpleServer.Start: Server Already Started!'); FServerPort := Port; FServerActive := True; Started.ResetEvent; Resume; Result := (Started.WaitFor(high(Cardinal)) = wrSignaled)and(FServerActive); end; procedure TSimpleServer.Execute; begin inherited; ReturnValue := STILL_ACTIVE; Status := 'Started...'; while not Terminated do begin if FServerActive then begin ListenSocket := TTCPSocket.Create; try ListenSocket.Bind(FServerPort); ListenSocket.Listen; Started.SetEvent; while (not Terminated)and(FServerActive) do begin Status := 'Listening...'; NewSocket := ListenSocket.Accept; if NewSocket <> INVALID_SOCKET then begin Status := 'Notifying new client'; if Assigned(OnClientConnect) then try Synchronize(DoOnClientConnect); except on E: Exception do begin Status := 'Exception while notifying new client in ' + Name + ':' + E.Message + ' (' + E.ClassName + ')'; end; end; end; Sleep(100); end; except on E: Exception do begin Status := 'Exception while listening in ' + Name + ':' + E.Message + ' (' + E.ClassName + ') -> Server Paused'; FServerActive := False; Started.SetEvent; end; end; ListenSocket.Free; end //If FServerActive then else begin Status := 'Paused'; Suspend; end; end; Status := 'Stopped'; ReturnValue := 0; end; procedure TSimpleServer.DoOnClientConnect; begin OnClientConnect(Self,NewSocket); end; destructor TSimpleServer.Destroy; begin Terminate; if FServerActive then begin FServerActive := False; ListenSocket.Close; end; Resume; if ReturnValue = STILL_ACTIVE then WaitFor; Started.Free; inherited; end; constructor TSimpleServer.Create; begin inherited Create(False); FServerActive := False; FreeOnTerminate := False; Started := TEvent.Create(nil,True,False,''); end; procedure Register; begin RegisterComponents('nice things', [TSimpleServerComponent]); end; constructor TSimpleServerComponent.Create(AOwner: TComponent); begin inherited; SimpleServer := TSimpleServer.Create; end; destructor TSimpleServerComponent.Destroy; begin SimpleServer.Free; inherited; end; procedure TSimpleServerComponent.SetOnClientConnect( p: TSimpleServerClientConnect); begin SimpleServer.OnClientConnect := p; FOnClientConnect := p; end; end.
unit D_TextMessages; // $Id: D_TextMessages.pas,v 1.4 2013/04/19 13:05:03 lulin Exp $ // $Log: D_TextMessages.pas,v $ // Revision 1.4 2013/04/19 13:05:03 lulin // - портируем. // // Revision 1.3 2012/02/20 08:48:00 narry // Сообщение о состоянии экспорта (340167865) // interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, OvcBase, l3Interfaces, afwControl, afwInputControl, vtLister, StdCtrls, afwControlPrim, afwBaseControl; type TdlgTextMessages = class(TForm) Lister: TvtLister; Button1: TButton; procedure ListerGetStrItem(Sender: TObject; Index: Integer; var ItemString: Il3CString); procedure FormShow(Sender: TObject); procedure Button1Click(Sender: TObject); function ListerGetItemImageIndex(Sender: TObject; Index: Integer): Integer; private { Private declarations } public { Public declarations } procedure IncomingMessages(aCount: Integer; const aLastMsg: AnsiString); end; var dlgTextMessages: TdlgTextMessages; implementation uses l3Base, ArchiUserRequestManager; {$R *.dfm} procedure TdlgTextMessages.ListerGetStrItem(Sender: TObject; Index: Integer; var ItemString: Il3CString); begin ItemString := Tl3CConstDelphiString.MakeI(ArchiRequestManager.TextMessages[Index]); end; procedure TdlgTextMessages.FormShow(Sender: TObject); begin Lister.Total := ArchiRequestManager.TextMessages.Count; end; procedure TdlgTextMessages.Button1Click(Sender: TObject); begin ModalResult := mrOK; end; function TdlgTextMessages.ListerGetItemImageIndex(Sender: TObject; Index: Integer): Integer; begin Result := 2; end; procedure TdlgTextMessages.IncomingMessages(aCount: Integer; const aLastMsg: AnsiString); begin Lister.Total := ArchiRequestManager.TextMessages.Count; end; end.
unit ssDBTreeView; interface uses SysUtils, Classes, Controls, cxControls, cxContainer, cxTreeView, DB, ComCtrls, DBGrids; type TssDBTreeView = class; TssTreeViewDataLink = class(TDataLink) private FControl: TssDBTreeView; protected procedure ActiveChanged; override; end; TssDBTreeView = class(TcxTreeView) private FDataLink: TssTreeViewDataLink; FDisplayField: string; FParentField: string; FKeyField: string; FAllItems: string; procedure SetDataSource(Value: TDataSource); procedure SetDisplayField(const Value: string); procedure SetKeyField(const Value: string); procedure SetParentField(const Value: string); function GetDataSource: TDataSource; procedure SetAllItems(const Value: string); function InternalLocate(ANode: TTreeNode; const AValue: integer): boolean; protected procedure RefreshTree; virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function Locate(const AValue: integer): boolean; function GetNode(const AValue: integer): TTreeNode; published property ParentField: string read FParentField write SetParentField; property DisplayField: string read FDisplayField write SetDisplayField; property KeyField: string read FKeyField write SetKeyField; property DataSource: TDataSource read GetDataSource write SetDataSource; property AllItems: string read FAllItems write SetAllItems; end; implementation constructor TssDBTreeView.Create(AOwner: TComponent); begin inherited; FDataLink:=TssTreeViewDataLink.Create; FDataLink.FControl:=Self; end; destructor TssDBTreeView.Destroy; begin FDataLink.Free; inherited; end; function TssDBTreeView.GetDataSource: TDataSource; begin Result := FDataLink.DataSource; end; function TssDBTreeView.GetNode(const AValue: integer): TTreeNode; var i: integer; begin Result:=nil; for i:=0 to Items.Count-1 do if Integer(Items[i].Data)=AValue then begin Result:=Items[i]; end; end; function TssDBTreeView.InternalLocate(ANode: TTreeNode; const AValue: integer): boolean; var i: integer; FExp: boolean; begin Result:=False; if Integer(ANode.Data)=AValue then begin Selected:=ANode; Result:=True; Exit; end; FExp:=ANode.Expanded; ANode.Expand(False); for i:=0 to ANode.Count-1 do if InternalLocate(ANode.Item[i], AValue) then begin Result:=True; Exit; end; if not FExp then ANode.Collapse(False); end; function TssDBTreeView.Locate(const AValue: integer): boolean; var i: integer; begin Result:=False; for i:=0 to Items.Count-1 do begin if InternalLocate(Items[i], AValue) then begin Result:=True; Exit; end; end; end; procedure TssDBTreeView.RefreshTree; var FNode: TTreeNode; procedure SetChildren(ANode: TTreeNode; AID: integer); var BM: TBookmark; FNode: TTreeNode; begin with FDataLink.DataSet do begin BM:=GetBookmark; try First; while not Eof do begin if (fieldbyname(FParentField).AsInteger=AID) and (fieldbyname(FKeyField).AsInteger<>AID) then begin FNode:=Self.Items.AddChild(ANode, fieldbyname(FDisplayField).AsString); FNode.Data:=pointer(fieldbyname(FKeyField).AsInteger); SetChildren(FNode, fieldbyname(FKeyField).AsInteger); if AutoExpand then FNode.Expand(False); end; Next; end; GotoBookmark(BM); finally FreeBookmark(BM); end; end; end; begin if FDataLink.DataSet=nil then Exit; with FDataLink.DataSet do begin Self.Items.Clear; if not Active then Exit; if FAllItems<>'' then begin FNode:=Self.Items.Add(nil, FAllItems); FNode.Data:=Pointer(-1); end; while not Eof do begin if fieldbyname(FParentField).AsInteger=fieldbyname(FKeyField).AsInteger then begin FNode:=Self.Items.Add(nil, fieldbyname(FDisplayField).AsString); FNode.Data:=pointer(fieldbyname(FKeyField).AsInteger); SetChildren(FNode, fieldbyname(FKeyField).AsInteger); if AutoExpand then FNode.Expand(False); end; Next; end; if Self.Items.Count>0 then Self.Selected:=Self.Items[0]; end; end; procedure TssDBTreeView.SetAllItems(const Value: string); var FNode: TTreeNode; begin if FDataLink.DataSource=nil then Exit; if FAllItems<>Value then begin FAllItems:=Value; FNode:=GetNode(-1); if FNode=nil then begin FNode:=Items.AddFirst(nil, FAllItems); FNode.Data:=pointer(-1); end else begin if Trim(Value)='' then Items.Delete(FNode) else FNode.Text:=Value; end; end; end; procedure TssDBTreeView.SetDataSource(Value: TDataSource); begin if FDataLink.DataSource<>Value then begin FDataLink.DataSource := Value; if Value <> nil then Value.FreeNotification(Self); RefreshTree; end; end; procedure TssDBTreeView.SetDisplayField(const Value: string); begin if FDisplayField<>Value then begin FDisplayField := Value; RefreshTree; end; end; procedure TssDBTreeView.SetKeyField(const Value: string); begin if FKeyField<>Value then begin FKeyField := Value; RefreshTree; end; end; procedure TssDBTreeView.SetParentField(const Value: string); begin if FParentField<>Value then begin FParentField := Value; RefreshTree; end; end; { TssTreeViewDataLink } procedure TssTreeViewDataLink.ActiveChanged; begin FControl.RefreshTree; end; end.
unit evContentsTree; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "Everest" // Автор: Инишев Д.А. // Модуль: "w:/common/components/gui/Garant/Everest/evContentsTree.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi::Everest::ContentsTree::TevContentsTree // // Дерево оглавления. // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\Everest\evDefine.inc} interface uses k2Interfaces, l3Tree_TLB, nevTools, evInternalInterfaces, l3Tree, l3IID, nevBase ; type TevContentsTree = class(Tl3Tree, InevSubChangeListner) {* Дерево оглавления. } private // private fields f_ContentsNodeFilter : InevContentsNodeFilter; private // private methods procedure CreateRootChild(const aDocument: Ik2Tag); protected // realized methods procedure SubChanged(const aSub: InevTag; aChangeType: TevChangeType); {* Саб добавлен/удален. } protected // overridden protected methods procedure Cleanup; override; {* Функция очистки полей объекта. } function COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult; override; {* Реализация запроса интерфейса } public // overridden public methods procedure Changed; override; {* нотификация о завершении изменения состояния объекта. Для перекрытия и использования в потомках. } public // public methods constructor Create(const aDocument: Ik2Tag); reintroduce; virtual; class function Make(const aDocument: Ik2Tag): Il3Tree; end;//TevContentsTree implementation uses evContentsNodeFilter, SysUtils, l3Base, l3Nodes, l3Types, evNode, Block_Const, l3Interfaces, evContentsNodeFactory, l3TreeInterfaces ; // start class TevContentsTree procedure TevContentsTree.CreateRootChild(const aDocument: Ik2Tag); //#UC START# *4EAE7B0803B7_4DFEEEA000DA_var* //#UC END# *4EAE7B0803B7_4DFEEEA000DA_var* begin //#UC START# *4EAE7B0803B7_4DFEEEA000DA_impl* RootNode.InsertChild(TevContentsNodeFactory.CreateContentsNode(aDocument, nil, f_ContentsNodeFilter)); with f_ContentsNodeFilter do ColorNode(RootNode.ChildNode); //#UC END# *4EAE7B0803B7_4DFEEEA000DA_impl* end;//TevContentsTree.CreateRootChild constructor TevContentsTree.Create(const aDocument: Ik2Tag); //#UC START# *4DFEF08201FC_4DFEEEA000DA_var* var l_Root : InevNode; l_RootNode : Il3SimpleRootNode; //#UC END# *4DFEF08201FC_4DFEEEA000DA_var* begin //#UC START# *4DFEF08201FC_4DFEEEA000DA_impl* f_ContentsNodeFilter := TevContentsNodeFilter.Make(aDocument); l_RootNode := TevContentsNodeFactory.CreateRoot; inherited Create; Set_RootNode(l_RootNode); CreateRootChild(aDocument); //#UC END# *4DFEF08201FC_4DFEEEA000DA_impl* end;//TevContentsTree.Create class function TevContentsTree.Make(const aDocument: Ik2Tag): Il3Tree; //#UC START# *4DFEF0A30330_4DFEEEA000DA_var* var l_CT : TevContentsTree; //#UC END# *4DFEF0A30330_4DFEEEA000DA_var* begin //#UC START# *4DFEF0A30330_4DFEEEA000DA_impl* l_CT := Create(aDocument); try Result := l_CT; l_CT.CommonExpanded := True; finally l3Free(l_CT); end;//try..finally //#UC END# *4DFEF0A30330_4DFEEEA000DA_impl* end;//TevContentsTree.Make procedure TevContentsTree.SubChanged(const aSub: InevTag; aChangeType: TevChangeType); //#UC START# *48EDB20501DD_4DFEEEA000DA_var* function lp_InParaEX(const anAtom : Ik2Tag; aTypeID : Long; out theParent : Ik2Tag): Boolean; var l_Parent : Ik2Tag; begin Result := false; l_Parent := anAtom.Owner; while (l_Parent <> nil) AND l_Parent.IsValid do begin if l_Parent.InheritsFrom(aTypeID) then begin theParent := l_Parent; Result := True; Break; end;//l_Parent.IhneritsFrom(aTypeID) l_Parent := l_Parent.Owner; end;//while l_Parent.IsValid end; var l_Node : InevNode; l_Root : InevNode; l_Expanded : Boolean; l_ParentBlock : InevTag; //#UC END# *48EDB20501DD_4DFEEEA000DA_var* begin //#UC START# *48EDB20501DD_4DFEEEA000DA_impl* if aSub.IsValid then begin if aChangeType = ev_chtDocument then begin if Supports(Get_RootNode, InevNode, l_Root) then begin l_Root.ReleaseChilds; f_ContentsNodeFilter.ChangeDocument(aSub); CreateRootChild(aSub); end; // if Supports(Get_RootNode, InevNode, l_Root) then Exit; end; // if aChangeType = ev_chtDcoument then if Supports(RootNode, InevNode, l_Root) then begin if aChangeType = ev_chtAdded then begin f_ContentsNodeFilter.CheckTagList; lp_InParaEX(aSub, k2_idBlock, l_ParentBlock); if l_ParentBlock <> nil then if not l_ParentBlock.IsValid then //Нет смысла искать сам блок в дереве (если использовать _evInPara), если он только что добавился... l_ParentBlock := nil; end // if anAdded then else begin l_ParentBlock := aSub; f_ContentsNodeFilter.AddFilterTag(aSub); end; l_Node := FindNodeByTag(l_Root, l_ParentBlock, imExpandOnly); if l_Node <> nil then begin if aChangeType = ev_chtDeleted then l_Node := l_Node.ParentNode; if (l_Node <> nil) and l_Node.HasChild then begin l_Expanded := IsExpanded(l_Node); l_Node.Changing; try l_Node.ReleaseChilds; if l_Expanded then ChangeExpand(l_Node, sbSelect); finally l_Node.Changed; end; end // if (l_Node <> nil) and l_Node.HasChild then else // V - http://mdp.garant.ru/pages/viewpage.action?pageId=300028777 if (l_Node <> nil) and (l_Node.GetLevel = 1) and (aChangeType = ev_chtAdded) then l_Node.ReleaseChilds; end; // if l_Node <> nil then end; // if Supports(RootNode, InevNode, l_Root) then end; // if aSub.IsValid then //#UC END# *48EDB20501DD_4DFEEEA000DA_impl* end;//TevContentsTree.SubChanged procedure TevContentsTree.Cleanup; //#UC START# *479731C50290_4DFEEEA000DA_var* //#UC END# *479731C50290_4DFEEEA000DA_var* begin //#UC START# *479731C50290_4DFEEEA000DA_impl* inherited; f_ContentsNodeFilter := nil; //#UC END# *479731C50290_4DFEEEA000DA_impl* end;//TevContentsTree.Cleanup procedure TevContentsTree.Changed; //#UC START# *4A5CC00B03D5_4DFEEEA000DA_var* //#UC END# *4A5CC00B03D5_4DFEEEA000DA_var* begin //#UC START# *4A5CC00B03D5_4DFEEEA000DA_impl* try inherited; except on EDoChangedAlreadyDone do ; end; //#UC END# *4A5CC00B03D5_4DFEEEA000DA_impl* end;//TevContentsTree.Changed function TevContentsTree.COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult; //#UC START# *4A60B23E00C3_4DFEEEA000DA_var* //#UC END# *4A60B23E00C3_4DFEEEA000DA_var* begin //#UC START# *4A60B23E00C3_4DFEEEA000DA_impl* if IID.EQ(InevContentsNodeFilter) then begin InevContentsNodeFilter(Obj) := f_ContentsNodeFilter; Result.SetOk; end else Result := inherited COMQueryInterface(IID, Obj); //#UC END# *4A60B23E00C3_4DFEEEA000DA_impl* end;//TevContentsTree.COMQueryInterface end.
unit UseDict; interface uses SysUtils, Generics.Defaults, Generics.Collections, tfNumerics, tfGNumerics; // HashTableSize must be a power of 2 function DLog(const Value, Base, Modulo: BigInteger; HashTableSize: Integer = 1024 * 1024): Int64; implementation function DLog(const Value, Base, Modulo: BigInteger; HashTableSize: Integer): Int64; var HashTable: TBigIntegerDictionary<Integer>; Factor, Acc: BigInteger; I: Integer; begin Assert(Base > 1); if Value = 1 then begin Result:= 0; Exit; end; // todo: BigInteger Factor:= BigInteger.ModInverse(Base, Modulo); Assert((Base * Factor) mod Modulo = 1, 'ModInverse'); Assert(Factor < Modulo, 'ModInverse'); HashTable:= TBigIntegerDictionary<Integer>.Create; try Acc:= Value; //writeln(DateTimeToStr(now)); for I:= 0 to HashTableSize - 1 do begin //if I < 5 then writeln(Acc.ToString); HashTable.Add(Acc, I); Acc:= (Acc * Factor) mod Modulo; end; //writeln(DateTimeToStr(now)); // todo: BigInteger Factor:= BigInteger.ModPow(Base, HashTableSize, Modulo); Acc:= 1; for I:= 0 to HashTableSize - 1 do begin // 2^20 - 1 // if I < 5 then writeln(Acc.ToString); if HashTable.ContainsKey(Acc) then begin Result:= I; Result:= HashTable[Acc] + Result * HashTableSize; //writeln(DateTimeToStr(now)); Exit; end; Acc:= (Acc * Factor) mod Modulo; // if I mod 1000 = 0 then Writeln(I); end; raise Exception.Create('DLog failed'); finally HashTable.Free; end; end; end.
unit csServerCommandsManager; interface Uses l3Base, Classes, CsDataPipe, csCommandsManager, csCommandsTypes, ddAppConfigTypes, ddServerTask; type TcsServerCommandsManager = class(TcsCommandsManager) private public procedure AddCommand(aID: TcsCommands; aCaption: String; aOnExecute: TNotifyEvent); overload; procedure AddCommand(aCaption: String; aNeedRespond: Boolean; aOnExecute: TNotifyEvent; aLinkTask: TddTaskClass = nil); overload; procedure cs_GetCommands(aPipe: TCSDataPipe); end; implementation uses l3Memory, csQueryTypes, SysUtils, csCommandsConst, DT_UserConst, csProcessTask; procedure TcsServerCommandsManager.AddCommand(aID: TcsCommands; aCaption: String; aOnExecute: TNotifyEvent); var l_Command: TcsCommand; begin if CommandExists(aID, l_Command) then begin l_Command.Caption:= aCaption; l_Command.OnExecute:= aOnExecute; end else begin l_Command:= TcsCommand.Create; l_Command.CommandID:= Ord(aID); l_Command.Caption:= aCaption; l_Command.OnExecute:= aOnExecute; Add(l_Command); end; end; procedure TcsServerCommandsManager.AddCommand(aCaption: String; aNeedRespond: Boolean; aOnExecute: TNotifyEvent; aLinkTask: TddTaskClass = nil); var l_Command: TcsCommand; begin l_Command:= TcsCommand.Create; l_Command.CommandID:= c_CommandBaseIndex + Succ(Count); l_Command.NeedRespond:= aNeedRespond; l_Command.Caption:= aCaption; l_Command.OnExecute:= aOnExecute; if aLinkTask <> nil then l_Command.LinkTask:= aLinkTask.Create(nil, usServerService) as TddProcessTask; Add(l_Command); end; procedure TcsServerCommandsManager.cs_GetCommands(aPipe: TCSDataPipe); var l_Stream: TStream; i, l_Count: Integer; begin Acquire; try l_Stream:= Tl3MemoryStream.Create; try l_Count:= Count; l_Stream.Write(l_Count, SizeOf(l_Count)); for i:= 0 to Pred(Count) do Commands[i].Save(l_Stream); aPipe.Write(l_Stream); finally l3Free(l_Stream); end; finally Leave; end; end; end.
unit Sequences; interface uses Classes; type PSingle=^Single; TDynamicArrayOfSingle=array of Single; TSequence=class(TObject) private FItems:TDynamicArrayOfSingle; function Get_LastValue: Single; function Get_Items(i: Integer): Single; function Get_PItems(i: Integer): PSingle; function Get_ItemsLength: Integer; function Get_Trend(i: Integer): Single; public LastTrendItem:Integer; constructor Create(aSize:Integer; TrendWindowSize:Integer=15); procedure Add(Value:Single); property LastValue:Single read Get_LastValue; property PItems[i:Integer]:PSingle read Get_PItems; property Items[i:Integer]:Single read Get_Items; property ItemsLength:Integer read Get_ItemsLength; property Trend[i:Integer]:Single read Get_Trend; protected function Next(Value:Single):Single;virtual;abstract; end; TDiffSequence=class(TSequence) constructor Create(Size:Integer; Alpha1,Alpha2:Double); protected FAlpha1,S1:Double; FAlpha2,S2:Double; PrevValue:Double; NotFirst:Boolean; function Next(Value:Single):Single;override; end; TDispSequence=class(TSequence) constructor Create(Size:Integer; Samples:Integer); protected Samples:array of Single; PrevValue:Single; NotFirst:Boolean; function Next(Value:Single):Single;override; end; implementation uses Student; procedure CalcKB(Src:PSingle; n: Integer; var K,B:Double); var i:Integer; Xi,Yi:Single; p,q,r,s:Double; begin p:=0; q:=0; r:=0; s:=0; for i:=0 to n-1 do begin Xi:=i; Yi:=Src^; Inc(Src); p:=p+Xi*Xi; q:=q+Xi; r:=r+Xi*Yi; s:=s+Yi; end; try K:=(n*r-q*s)/(n*p-q*q); except K:=0; end; B:=(s-K*q)/n; end; { TSequence } procedure TSequence.Add(Value: Single); var L1:Integer; begin L1:=Length(FItems)-1; Move(FItems[1],FItems[0],L1*SizeOf(Single)); FItems[L1]:=Next(Value); end; constructor TSequence.Create(aSize: Integer; TrendWindowSize:Integer=15); begin inherited Create; LastTrendItem:=TrendWindowSize-1; SetLength(FItems,TrendWindowSize+aSize); end; function TSequence.Get_Items(i: Integer): Single; begin Result:=FItems[LastTrendItem+i]; end; function TSequence.Get_LastValue: Single; begin Result:=FItems[Length(FItems)-1]; end; function TSequence.Get_ItemsLength: Integer; begin Result:=Length(FItems)-LastTrendItem-1; end; function TSequence.Get_PItems(i: Integer): PSingle; begin Result:=@(FItems[LastTrendItem+i]); end; function TSequence.Get_Trend(i: Integer): Single; begin Result:=(FItems[LastTrendItem+i]-FItems[i])/LastTrendItem; end; { TDiffSequence } function TDiffSequence.Next(Value: Single):Single; var D:Double; begin if NotFirst then begin { S2:=S2*FAlpha2+Value*(1-FAlpha2); Value:=Value-S2; D:=(Value-PrevValue); PrevValue:=Value; S1:=S1*FAlpha1+D*(1-FAlpha1); Result:=S1; end else begin NotFirst:=True; S2:=Value; S1:=0; PrevValue:=0; Result:=0; end; (*} D:=Value;//-PrevValue; S1:=S1*FAlpha1+D*(1-FAlpha1); S2:=S2*FAlpha2+D*(1-FAlpha2); D:=S1;//-S2; Result:=D;//-PrevValue; PrevValue:=D; end else begin NotFirst:=True; S2:=Value; S1:=Value; PrevValue:=0; Result:=0; end; //*) end; constructor TDiffSequence.Create(Size: Integer; Alpha1,Alpha2: Double); begin inherited Create(Size); FAlpha1:=Alpha1; FAlpha2:=Alpha2; end; { TDispSequence } constructor TDispSequence.Create(Size, Samples: Integer); begin inherited Create(Size); SetLength(Self.Samples,Samples); end; function TDispSequence.Next(Value: Single): Single; var i,n0,n:Integer; Sum,Avg:Double; K,B,X:Double; begin if NotFirst then begin Move(Samples[0],Samples[1],(Length(Samples)-1)*SizeOf(Single)); Samples[0]:=Value; end else begin for i:=High(Samples) downto 0 do Samples[i]:=Value; NotFirst:=True; PrevValue:=0; end; { Sum:=0; for i:=High(Samples) downto 0 do Sum:=Sum+Samples[i]; Avg:=Sum/Length(Samples); Sum:=0; for i:=High(Samples) downto 0 do Sum:=Sum+Sqr(Avg-Samples[i]); X:=Sqrt(Sum/Length(Samples))*10; Result:=X-PrevValue; PrevValue:=X; (* //} CalcKB(@(Samples[0]),Length(Samples),K,B); Sum:=0; X:=B; n:=Length(Samples); for i:=0 to n-1 do begin Sum:=Sum+Sqr(X-Samples[i]); X:=X+K; end; Result:=Sqrt(Sum)/n*10; //*) end; end.
unit DateL; interface uses Classes, Dates, Contnrs; type // inheritance based TDateListI = class (TObjectList) protected procedure SetObject (Index: Integer; Item: TDate); function GetObject (Index: Integer): TDate; public function Add (Obj: TDate): Integer; procedure Insert (Index: Integer; Obj: TDate); property Objects [Index: Integer]: TDate read GetObject write SetObject; default; end; // wrapper based TDateListW = class(TObject) private FList: TObjectList; procedure SetObject (Index: Integer; Obj: TDate); function GetObject (Index: Integer): TDate; function GetCount: Integer; public constructor Create; destructor Destroy; override; function Add (Obj: TDate): Integer; function Remove (Obj: TDate): Integer; function IndexOf (Obj: TDate): Integer; property Count: Integer read GetCount; property Objects [Index: Integer]: TDate read GetObject write SetObject; default; end; implementation // inherited version function TDateListI.Add (Obj: TDate): Integer; begin Result := inherited Add (Obj) end; procedure TDateListI.SetObject (Index: Integer; Item: TDate); begin inherited SetItem (Index, Item) end; function TDateListI.GetObject (Index: Integer): TDate; begin Result := inherited GetItem (Index) as TDate; end; procedure TDateListI.Insert(Index: Integer; Obj: TDate); begin inherited Insert(Index, Obj); end; // embedded version constructor TDateListW.Create; begin inherited Create; FList := TObjectList.Create; end; destructor TDateListW.Destroy; begin FList.Free; inherited Destroy; end; function TDateListW.GetObject (Index: Integer): TDate; begin Result := FList [Index] as TDate; end; procedure TDateListW.SetObject (Index: Integer; Obj: TDate); begin FList[Index] := Obj; end; function TDateListW.GetCount: Integer; begin Result := FList.Count; end; function TDateListW.Add (Obj: TDate): Integer; begin Result := FList.Add (Obj); end; // another method you can optionally add {function TDateListW.Equals(List: TDateListW): Boolean; var I: Integer; begin Result := False; if List.Count <> FList.Count then Exit; for I := 0 to List.Count - 1 do if List[I] <> FList[I] then Exit; Result := True; end;} function TDateListW.IndexOf(Obj: TDate): Integer; begin Result := fList.IndexOf (Obj); end; // another method you can optionally add {procedure TDateListW.Insert(Index: Integer; Obj: TDate); begin fList.Insert (Index, Obj); end;} function TDateListW.Remove(Obj: TDate): Integer; begin Result := fList.Remove (Obj); end; end.
unit tdADSIEnum; interface uses System.SysUtils, System.StrUtils, System.Classes, System.TypInfo, System.DateUtils, System.Math, System.Generics.Collections, Winapi.Windows, Winapi.ActiveX, ActiveDs_TLB, MSXML2_TLB, JwaActiveDS, ADC.Types, ADC.DC, ADC.Attributes, ADC.ADObject, ADC.ADObjectList, ADC.Common, ADC.AD; type TADSIEnum = class(TThread) private FProgressProc: TProgressProc; FExceptionProc: TExceptionProc; FProgressValue: Integer; FExceptionCode: ULONG; FExceptionMsg: string; FDomainDN: string; FDomainHostName: string; FAttrCatalog: TAttrCatalog; FAttributes: array of WideString; FOutList: TADObjectList<TADObject>; FObj: TADObject; FSearchRes: IDirectorySearch; FSearchHandle: PHandle; FMaxPwdAge_Secs: Int64; FMaxPwdAge_Days: Int64; procedure FillEventList(AStringStream: TStringStream; AOutList: TStringList); procedure ProcessObjects; procedure SyncProgress; procedure SyncException; procedure Clear; procedure GetMaxPasswordAge; function TimestampToDateTime(ATime: ActiveDS_TLB._LARGE_INTEGER): TDateTime; protected destructor Destroy; override; procedure Execute; override; procedure DoProgress(AProgress: Integer); overload; procedure DoProgress; overload; procedure DoException(AMsg: string; ACode: ULONG); public constructor Create(ARootDSE: IADs; AAttrCatalog: TAttrCatalog; AOutList: TADObjectList<TADObject>; AProgressProc: TProgressProc; AExceptionProc: TExceptionProc; CreateSuspended: Boolean = False); reintroduce; end; implementation { TADObjectInfoEnum } procedure TADSIEnum.Clear; begin if Terminated then FOutList.Clear; FProgressProc := nil; FExceptionProc := nil; FProgressValue := 0; FExceptionCode := 0; FExceptionMsg := ''; FAttrCatalog := nil; FOutList.SortObjects; FOutList := nil; FObj := nil; FSearchRes.CloseSearchHandle(Pointer(FSearchHandle)); CoUninitialize; end; constructor TADSIEnum.Create(ARootDSE: IADs; AAttrCatalog: TAttrCatalog; AOutList: TADObjectList<TADObject>; AProgressProc: TProgressProc; AExceptionProc: TExceptionProc; CreateSuspended: Boolean); var i: Integer; v: OleVariant; begin inherited Create(CreateSuspended); FreeOnTerminate := True; FAttrCatalog := AAttrCatalog; FOutList := AOutList; FOutList.Clear; FProgressProc := AProgressProc; FExceptionProc := AExceptionProc; if ARootDSE = nil then begin Self.Terminate; DoException('No server binding.', 0); Exit; end; v := ARootDSE.Get('defaultNamingContext'); FDomainDN := VariantToStringWithDefault(v, ''); VariantClear(v); v := ARootDSE.Get('dnsHostName'); FDomainHostName := VariantToStringWithDefault(v, ''); VariantClear(v); SetLength(FAttributes, FAttrCatalog.Count); for i := 0 to FAttrCatalog.Count - 1 do begin if FAttrCatalog[i]^.Name = '' then FAttributes[i] := '<Undefined>' else FAttributes[i] := FAttrCatalog[i]^.Name; end; end; destructor TADSIEnum.Destroy; begin inherited; end; procedure TADSIEnum.DoProgress; begin FProgressValue := FProgressValue + 1; Synchronize(SyncProgress); end; procedure TADSIEnum.Execute; var objFilter: string; pDomain: IADsDomain; hRes: HRESULT; SearchPrefs: array of ADS_SEARCHPREF_INFO; begin CoInitialize(nil); try if Terminated then raise Exception.Create('No server binding.'); { Извлекаем срок действия пароля из политики домена } GetMaxPasswordAge; { Осуществляем поиск в домене атрибутов и их значений } hRes := ADsOpenObject( PChar('LDAP://' + FDomainHostName + '/' + FDomainDN), nil, nil, ADS_SECURE_AUTHENTICATION or ADS_SERVER_BIND, IID_IDirectorySearch, @FSearchRes ); if Succeeded(hRes) then begin SetLength(SearchPrefs, 3); with SearchPrefs[0] do begin dwSearchPref := ADS_SEARCHPREF_PAGESIZE; vValue.dwType := ADSTYPE_INTEGER; vValue.__MIDL____MIDL_itf_ads_0000_00000000.Integer := ADC_SEARCH_PAGESIZE; end; with SearchPrefs[1] do begin dwSearchPref := ADS_SEARCHPREF_PAGED_TIME_LIMIT; vValue.dwType := ADSTYPE_INTEGER; vValue.__MIDL____MIDL_itf_ads_0000_00000000.Integer := 60; end; with SearchPrefs[2] do begin dwSearchPref := ADS_SEARCHPREF_SEARCH_SCOPE; vValue.dwType := ADSTYPE_INTEGER; vValue.__MIDL____MIDL_itf_ads_0000_00000000.Integer := ADS_SCOPE_SUBTREE; end; // with SearchPrefs[3] do // begin // dwSearchPref := ADS_SEARCHPREF_EXTENDED_DN; // vValue.dwType := ADSTYPE_INTEGER; // vValue.__MIDL____MIDL_itf_ads_0000_00000000.Integer := 1; // end; hRes := FSearchRes.SetSearchPreference(SearchPrefs[0], Length(SearchPrefs)); objFilter := '(|' + '(&(objectCategory=person)(objectClass=user))' + '(objectCategory=group)' + '(objectCategory=computer)' + ')'; DoProgress(0); FSearchRes.ExecuteSearch( PWideChar(objFilter), PWideChar(@FAttributes[0]), Length(FAttributes), Pointer(FSearchHandle) ); ProcessObjects; end; Clear; except on E: Exception do begin DoException(E.Message, hRes); Clear; end; end; end; procedure TADSIEnum.DoProgress(AProgress: Integer); begin FProgressValue := AProgress; Synchronize(SyncProgress); end; procedure TADSIEnum.FillEventList( AStringStream: TStringStream; AOutList: TStringList); var XMLDoc: IXMLDOMDocument; XMLNodeList: IXMLDOMNodeList; XMLNode: IXMLDOMNode; i: Integer; eventString: string; begin AOutList.Clear; XMLDoc := CoDOMDocument60.Create; try XMLDoc.async := False; XMLDoc.load(TStreamAdapter.Create(AStringStream) as IStream); if XMLDoc.parseError.errorCode = 0 then begin XMLNodeList := XMLDoc.documentElement.selectNodes('event'); for i := 0 to XMLNodeList.length - 1 do begin XMLNode := XMLNodeList.item[i].selectSingleNode('date'); eventString := XMLNode.text; XMLNode := XMLNodeList.item[i].selectSingleNode('description'); eventString := eventString + '=' + XMLNode.text; AOutList.Add(eventString); end; end; finally XMLDoc := nil; end; end; procedure TADSIEnum.GetMaxPasswordAge; const ONE_HUNDRED_NANOSECOND = 0.000000100; SECONDS_IN_DAY = 86400; var hRes: HRESULT; pDomain: IADs; v: OleVariant; d: LARGE_INTEGER; begin hRes := ADsOpenObject( PChar('LDAP://' + FDomainHostName + '/' + FDomainDN), nil, nil, ADS_SECURE_AUTHENTICATION or ADS_SERVER_BIND, IID_IADs, @pDomain ); if Succeeded(hRes) then begin v := pDomain.Get('maxPwdAge'); d.HighPart := (IDispatch(v) as IADsLargeInteger).HighPart; d.LowPart := (IDispatch(v) as IADsLargeInteger).LowPart; VariantClear(v); if d.LowPart = 0 then begin FMaxPwdAge_Secs := 0; FMaxPwdAge_Days := 0; end else begin d.QuadPart := d.HighPart; d.QuadPart := d.QuadPart shl 32; d.QuadPart := d.QuadPart + d.LowPart; FMaxPwdAge_Secs := Abs(Round(d.QuadPart * ONE_HUNDRED_NANOSECOND)); FMaxPwdAge_Days := Round(FMaxPwdAge_Secs / SECONDS_IN_DAY); end; end; pDomain := nil; end; procedure TADSIEnum.SyncException; begin if Assigned(FExceptionProc) then FExceptionProc(FExceptionMsg, FExceptionCode); end; procedure TADSIEnum.SyncProgress; begin if Assigned(FProgressProc) then FProgressProc(FProgressValue); end; function TADSIEnum.TimestampToDateTime( ATime: ActiveDS_TLB._LARGE_INTEGER): TDateTime; var int64Value: Int64; LocalTime: TFileTime; SystemTime: TSystemTime; FileTime : TFileTime; begin int64Value := ATime.QuadPart; if int64Value = 0 then Result := 0 else try {int64Value := LastLogon.HighPart; int64Value := int64Value shl 32; int64Value := int64Value + LastLogon.LowPart;} Result := EncodeDate(1601,1,1); FileTime := TFileTime(int64Value); if FileTimeToLocalFileTime(FileTime, LocalTime) then if FileTimeToSystemTime(LocalTime, SystemTime) then Result := SystemTimeToDateTime(SystemTime); except Result := 0; end; end; procedure TADSIEnum.ProcessObjects; var i: Integer; hRes: HRESULT; col: ADS_SEARCH_COLUMN; attr: TADAttribute; memStream: TMemoryStream; strStream: TStringStream; d: TDateTime; begin hRes := FSearchRes.GetNextRow(FSearchHandle); while (hRes <> S_ADS_NOMORE_ROWS) do begin if Terminated then Break; FObj := TADObject.Create; FObj.DomainHostName := FDomainHostName; for i := 0 to FAttrCatalog.Count - 1 do begin attr := FAttrCatalog[i]^; hRes := FSearchRes.GetColumn(FSearchHandle, PWideChar(string(attr.Name)), col); if Succeeded(hRes) then if attr.ObjProperty = 'nearestEvent' then begin strStream := TStringStream.Create; try strStream.Write( col.pAdsvalues^.__MIDL____MIDL_itf_ads_0000_00000000.OctetString.lpValue^, col.pAdsvalues^.__MIDL____MIDL_itf_ads_0000_00000000.OctetString.dwLength ); strStream.Seek(0, soFromBeginning); FillEventList(strStream, FObj.events); finally strStream.Free; end; end else case IndexText(attr.Name, [ 'lastLogon', { 0 } 'pwdLastSet', { 1 } 'badPwdCount', { 2 } 'groupType', { 3 } 'userAccountControl', { 4 } 'objectSid', { 5 } 'thumbnailPhoto', { 6 } 'distinguishedName', { 7 } 'primaryGroupToken' { 8 } ] ) of 0: begin { lastLogon } SetFloatProp( FObj, string(attr.ObjProperty), Self.TimestampToDateTime(col.pAdsvalues^.__MIDL____MIDL_itf_ads_0000_00000000.LargeInteger) ); end; 1: begin { pwdLastSet } begin d := Self.TimestampToDateTime(col.pAdsvalues^.__MIDL____MIDL_itf_ads_0000_00000000.LargeInteger); if d > 0 then SetFloatProp(FObj, string(attr.ObjProperty), IncSecond(d, FMaxPwdAge_Secs)) else SetFloatProp(FObj, string(attr.ObjProperty), 0) end; end; 2..4: begin { badPwdCount, groupType, userAccountControl } SetOrdProp( FObj, string(attr.ObjProperty), col.pAdsvalues^.__MIDL____MIDL_itf_ads_0000_00000000.Integer ); end; 5: begin { objectSid } SetPropValue( FObj, string(attr.ObjProperty), SIDToString(col.pAdsvalues^.__MIDL____MIDL_itf_ads_0000_00000000.OctetString.lpValue) ); end; 6: begin { thumbnailPhoto } memStream := TMemoryStream.Create; try memStream.Write( col.pAdsvalues^.__MIDL____MIDL_itf_ads_0000_00000000.OctetString.lpValue^, col.pAdsvalues^.__MIDL____MIDL_itf_ads_0000_00000000.OctetString.dwLength ); memStream.Seek(0, soFromBeginning); FObj.thumbnailPhoto.LoadFromStream(memStream); finally memStream.Free; end; end; 7: begin { distinguishedName } SetPropValue( FObj, string(attr.ObjProperty), string(col.pAdsvalues^.__MIDL____MIDL_itf_ads_0000_00000000.CaseIgnoreString) ); end; { primaryGroupToken } 8: begin SetOrdProp( FObj, string(attr.ObjProperty), col.pAdsvalues^.__MIDL____MIDL_itf_ads_0000_00000000.Integer ); end else begin { Все текстовые атрибуты } SetPropValue( FObj, string(attr.ObjProperty), string(col.pAdsvalues^.__MIDL____MIDL_itf_ads_0000_00000000.CaseIgnoreString) ); end; end; FSearchRes.FreeColumn(col); end; FOutList.Add(FObj); DoProgress; hRes := FSearchRes.GetNextRow(Pointer(FSearchHandle)); end; end; procedure TADSIEnum.DoException(AMsg: string; ACode: ULONG); begin FExceptionCode := ACode; FExceptionMsg := AMsg; Synchronize(SyncException); end; end.
unit udmCodigoIMO; interface uses Windows, System.UITypes,Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, udmPadrao, DBAccess, IBC, DB, MemDS; type TdmCodigoIMO = class(TdmPadrao) qryManutencaoCODIGO: TStringField; qryManutencaoGRUPO: TStringField; qryManutencaoDESCRICAO: TStringField; qryManutencaoOPERADOR: TStringField; qryManutencaoDT_ALTERACAO: TDateTimeField; qryLocalizacaoCODIGO: TStringField; qryLocalizacaoGRUPO: TStringField; qryLocalizacaoDESCRICAO: TStringField; qryLocalizacaoOPERADOR: TStringField; qryLocalizacaoDT_ALTERACAO: TDateTimeField; protected procedure MontaSQLBusca(DataSet: TDataSet = nil); override; procedure MontaSQLRefresh; override; private FGrupo: string; FCodigo: string; { Private declarations } public function LocalizarPorCodigo(DataSet: TIBCQuery): Boolean; property Codigo: string read FCodigo write FCodigo; property Grupo: string read FGrupo write FGrupo; end; const SQL_DEFAULT = ' SELECT CODIGO,' + ' GRUPO, ' + ' DESCRICAO, ' + ' OPERADOR, ' + ' DT_ALTERACAO '+ ' FROM CODIGOS_IMO'; var dmCodigoIMO: TdmCodigoIMO; implementation {$R *.dfm} { TdmCodigoIMO } function TdmCodigoIMO.LocalizarPorCodigo(DataSet: TIBCQuery): Boolean; begin if DataSet = nil then DataSet := qryLocalizacao; with (DataSet as TIBCQuery) do begin Close; SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('WHERE CODIGO = :CODIGO'); SQL.Add('ORDER BY GRUPO'); ParamByName('CODIGO').AsString := FCodigo; open; Result := not IsEmpty; end; end; procedure TdmCodigoIMO.MontaSQLBusca(DataSet: TDataSet); begin inherited; with (DataSet as TIBCQuery) do begin SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('WHERE CODIGO = :CODIGO'); SQL.Add(' AND GRUPO = :GRUPO'); SQL.Add('ORDER BY GRUPO'); ParamByName('CODIGO').AsString := FCodigo; ParamByName('GRUPO').AsString := FGrupo; end; end; procedure TdmCodigoIMO.MontaSQLRefresh; begin inherited; with qryManutencao do begin SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('ORDER BY GRUPO'); end; end; initialization RegisterClass(TdmCodigoIMO) finalization UnRegisterClass(TdmCodigoIMO) end.
unit GX_eConvertStrings; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, GX_BaseForm; type TPasteAsType = (paRaw, paStringArray, paAdd, paSLineBreak, paChar10, paChar13, paChars1310, paCRLF, paCR_LF); type TfmEConvertStrings = class(TfmBaseForm) m_Input: TMemo; l_Input: TLabel; m_Output: TMemo; l_Output: TLabel; chk_QuoteStrings: TCheckBox; chk_AppendSpace: TCheckBox; b_CopyToClipboard: TButton; b_Insert: TButton; b_Close: TButton; chk_ExtractRaw: TCheckBox; rg_ConvertType: TRadioGroup; l_Prefix: TLabel; ed_Prefix: TEdit; b_PasteFromClipboard: TButton; b_ToSQL: TButton; b_ToTStrings: TButton; procedure chk_ExtractRawClick(Sender: TObject); procedure rg_ConvertTypeClick(Sender: TObject); procedure b_CopyToClipboardClick(Sender: TObject); procedure ed_PrefixChange(Sender: TObject); procedure m_InputChange(Sender: TObject); procedure b_InsertClick(Sender: TObject); procedure chk_QuoteStringsClick(Sender: TObject); procedure chk_AppendSpaceClick(Sender: TObject); procedure b_PasteFromClipboardClick(Sender: TObject); procedure FormResize(Sender: TObject); procedure b_ToSQLClick(Sender: TObject); procedure b_ToTStringsClick(Sender: TObject); private FUpdating: Boolean; procedure SetData(_sl: TStrings); procedure ConvertStrings; procedure ExtractRawStrings(_sl: TStrings; _AddBaseIndent: Boolean); function DetermineIndent(_sl: TStrings): Integer; procedure ConvertToCode(_sl: TStrings; _PasteAsType: TPasteAsType; _QuoteStrings: Boolean; _AppendSpace: Boolean; const _Prefix: string); procedure LoadSettings; procedure SaveSettings; public constructor Create(_Owner: TComponent); override; destructor Destroy; override; class procedure Execute(_bmp: TBitmap; _sl: TStrings); end; implementation {$R *.dfm} uses StrUtils, Clipbrd, GX_dzVclUtils, GX_GenericUtils, GX_OtaUtils, GX_EditorExpert, GX_ConfigurationInfo, ToolsAPI; type TConvertStringsExpert = class(TEditorExpert) public class function GetName: string; override; function GetDisplayName: string; override; procedure Execute(Sender: TObject); override; function GetHelpString: string; override; // Returns false function HasConfigOptions: Boolean; override; end; const SINGLE_QUOTE = ''''; const cPasteAsTypeText: array[TPasteAsType] of string = ( '%s', '%s,', 'Add(%s);', '%s + sLineBreak +', '%s + #10 +', '%s + #13 +', '%s + #13#10 +', '%s + CRLF +', '%s + CR_LF +'); class procedure TfmEConvertStrings.Execute(_bmp: TBitmap; _sl: TStrings); var frm: TfmEConvertStrings; begin frm := TfmEConvertStrings.Create(Application); try ConvertBitmapToIcon(_bmp, frm.Icon); frm.SetData(_sl); frm.ShowModal; finally FreeAndNil(frm); end; end; constructor TfmEConvertStrings.Create(_Owner: TComponent); begin inherited; TControl_SetMinConstraints(Self); end; destructor TfmEConvertStrings.Destroy; begin try SaveSettings; except // we are being called in the destructor -> ignore any exceptions end; inherited; end; procedure TfmEConvertStrings.FormResize(Sender: TObject); var cw: Integer; w: Integer; x: Integer; m: Integer; begin m := m_Input.Left; cw := ClientWidth; x := (cw - rg_ConvertType.Width) div 2; chk_ExtractRaw.Left := x; rg_ConvertType.Left := x; chk_QuoteStrings.Left := x; chk_AppendSpace.Left := x; l_Prefix.Left := x; ed_Prefix.Left := x; b_ToSQL.Left := x; b_ToTStrings.Left := x + b_ToSQL.Width + m; w := x - 2 * m; m_Input.Width := w; m_Output.Width := w; x := cw - w - m; l_Output.Left := x; m_Output.Left := x; end; procedure TfmEConvertStrings.SaveSettings; var GXSettings: TGExpertsSettings; Settings: TExpertSettings; begin // Do not localize any of the following lines. Settings := nil; GXSettings := TGExpertsSettings.Create; try Settings := TExpertSettings.Create(GXSettings, TConvertStringsExpert.ConfigurationKey); Settings.SaveForm('Window', Self); Settings.WriteBool('ExtractRaw', chk_ExtractRaw.Checked); Settings.WriteInteger('ConvertType', rg_ConvertType.ItemIndex); Settings.WriteBool('QuoteStrings', chk_QuoteStrings.Checked); Settings.WriteBool('AppendSpace', chk_AppendSpace.Checked); finally FreeAndNil(Settings); FreeAndNil(GXSettings); end; end; procedure TfmEConvertStrings.SetData(_sl: TStrings); var Prefix: string; p: Integer; begin FUpdating := True; try m_Input.Lines.Assign(_sl); Prefix := Trim(GxOtaGetCurrentSelection(False)); if Prefix = '' then begin Prefix := Trim(GxOtaGetCurrentLine); GxOtaSelectCurrentLine(GxOtaGetCurrentSourceEditor); end; // multiple lines? Only take the first p := Pos(CR, Prefix); if p > 0 then Prefix := LeftStr(Prefix, p - 1); if Prefix <> '' then begin // Does it contain a '('? -> cut it there, we don't want parameters p := Pos('(', Prefix); if p > 0 then Prefix := LeftStr(Prefix, p - 1); // now look up the last '.', that's where we append the .Add() p := LastDelimiter('.', Prefix); if p > 0 then Prefix := LeftStr(Prefix, p) else begin // no '.'? -> add one Prefix := Prefix + '.'; end; ed_Prefix.Text := Prefix; end; LoadSettings; finally FUpdating := False; end; ConvertStrings; end; procedure TfmEConvertStrings.LoadSettings; var GXSettings: TGExpertsSettings; Settings: TExpertSettings; begin // Do not localize any of the following lines. Settings := nil; GXSettings := TGExpertsSettings.Create; try Settings := TExpertSettings.Create(GXSettings, TConvertStringsExpert.ConfigurationKey); Settings.LoadForm('Window', Self); chk_ExtractRaw.Checked := Settings.ReadBool('ExtractRaw', True); rg_ConvertType.ItemIndex := Settings.ReadInteger('ConvertType', Ord(paAdd)); chk_QuoteStrings.Checked := Settings.ReadBool('QuoteStrings', True); chk_AppendSpace.Checked := Settings.ReadBool('AppendSpace', True); finally FreeAndNil(Settings); FreeAndNil(GXSettings); end; end; function TfmEConvertStrings.DetermineIndent(_sl: TStrings): Integer; var i: Integer; Line: string; FCP: Integer; begin Result := MaxInt; for i := 0 to _sl.Count - 1 do begin Line := _sl[i]; FCP := GetFirstCharPos(Line, [' ', #09], False); if FCP < Result then Result := FCP; end; end; procedure TfmEConvertStrings.ExtractRawStrings(_sl: TStrings; _AddBaseIndent: Boolean); var i, FirstCharPos, FirstQuotePos, LastQuotePos: Integer; Line, BaseIndent: string; begin if _sl.Count = 0 then Exit; FirstCharPos := DetermineIndent(_sl); // this works, because FirstCharPos is the smallest Indent for all lines BaseIndent := LeftStr(_sl[0], FirstCharPos - 1); for i := 0 to _sl.Count - 1 do begin Line := Trim(Copy(_sl[i], FirstCharPos, MaxInt)); FirstQuotePos := GetFirstCharPos(Line, [SINGLE_QUOTE], True); LastQuotePos := GetLastCharPos(Line, [SINGLE_QUOTE], True); if (FirstQuotePos > 0) and (LastQuotePos > 0) then begin Line := Copy(Line, FirstQuotePos, LastQuotePos - FirstQuotePos + 1); Line := AnsiDequotedStr(Line, SINGLE_QUOTE); Line := TrimRight(Line); if _AddBaseIndent then Line := BaseIndent + Line; _sl[i] := Line; end; end; end; procedure TfmEConvertStrings.ConvertToCode(_sl: TStrings; _PasteAsType: TPasteAsType; _QuoteStrings: Boolean; _AppendSpace: Boolean; const _Prefix: string); var i, FirstCharPos: Integer; ALine, BaseIndent, ALineStart, ALineEnd, ALineStartBase, AAddDot: string; begin FirstCharPos := DetermineIndent(_sl); // this works, because FirstCharPos is the smallest Indent for all lines BaseIndent := LeftStr(_sl[0], FirstCharPos - 1); ALineStart := ''; ALineEnd := ''; ALineStartBase := ''; AAddDot := ''; case _PasteAsType of paRaw: ; // no change paStringArray: ALineEnd := ','; paAdd: begin ALineStart := _Prefix + 'Add('; ALineEnd := ');'; end; paSLineBreak: ALineEnd := ' + sLineBreak +'; paChar10: ALineEnd := '#10 +'; paChar13: ALineEnd := '#13 +'; paChars1310: ALineEnd := '#13#10 +'; paCRLF: ALineEnd := ' + CRLF +'; paCR_LF: ALineEnd := ' + CR_LF +'; end; for i := 0 to _sl.Count - 1 do begin ALine := Copy(_sl[i], FirstCharPos, MaxInt); if _QuoteStrings then ALine := AnsiQuotedStr(ALine + IfThen(_AppendSpace, ' '), SINGLE_QUOTE); ALine := ALineStart + ALine; if ALineStartBase <> '' then ALine := IfThen(i = 0, AAddDot, ALineStartBase) + ALine; if (i < _sl.Count - 1) or (_PasteAsType = paAdd) then ALine := ALine + ALineEnd; _sl[i] := BaseIndent + ALine; end; end; procedure TfmEConvertStrings.ConvertStrings; var sl: TStrings; PasteAsType: TPasteAsType; QuoteStrings: Boolean; AppendSpace: Boolean; begin if FUpdating then Exit; sl := TStringList.Create; try PasteAsType := TPasteAsType(rg_ConvertType.ItemIndex); QuoteStrings := chk_QuoteStrings.Checked; AppendSpace := chk_AppendSpace.Checked; sl.Assign(m_Input.Lines); if chk_ExtractRaw.Checked then ExtractRawStrings(sl, True); if sl.Count > 0 then begin ConvertToCode(sl, PasteAsType, QuoteStrings, AppendSpace, ed_Prefix.Text); end; m_Output.Lines.Assign(sl); finally FreeAndNil(sl); end; end; procedure TfmEConvertStrings.m_InputChange(Sender: TObject); begin ConvertStrings; end; procedure TfmEConvertStrings.ed_PrefixChange(Sender: TObject); begin ConvertStrings; end; procedure TfmEConvertStrings.rg_ConvertTypeClick(Sender: TObject); begin ConvertStrings; end; procedure TfmEConvertStrings.chk_AppendSpaceClick(Sender: TObject); begin ConvertStrings; end; procedure TfmEConvertStrings.chk_ExtractRawClick(Sender: TObject); begin ConvertStrings; end; procedure TfmEConvertStrings.chk_QuoteStringsClick(Sender: TObject); begin ConvertStrings; end; procedure TfmEConvertStrings.b_CopyToClipboardClick(Sender: TObject); begin Clipboard.AsText := m_Output.Lines.Text; end; procedure TfmEConvertStrings.b_InsertClick(Sender: TObject); var i: Integer; Lines: TStrings; begin Lines := m_Output.Lines; for i := 0 to Lines.Count - 1 do begin GxOtaInsertLineIntoEditor(Lines[i] + sLineBreak); end; ModalResult := mrOk; end; procedure TfmEConvertStrings.b_PasteFromClipboardClick(Sender: TObject); begin m_Input.Lines.Text := Clipboard.AsText; end; procedure TfmEConvertStrings.b_ToTStringsClick(Sender: TObject); begin FUpdating := True; try chk_ExtractRaw.Checked := True; rg_ConvertType.ItemIndex := Integer(paAdd); chk_QuoteStrings.Checked := True; chk_AppendSpace.Checked := True; finally FUpdating := False; end; ConvertStrings; end; procedure TfmEConvertStrings.b_ToSQLClick(Sender: TObject); begin FUpdating := True; try chk_ExtractRaw.Checked := True; rg_ConvertType.ItemIndex := Integer(paRaw); chk_QuoteStrings.Checked := False; chk_AppendSpace.Checked := False; finally FUpdating := False; end; ConvertStrings; end; { TConvertStringsExpert } procedure TConvertStringsExpert.Execute(Sender: TObject); var sl: TStringList; begin sl := TStringList.Create; try sl.Text := GxOtaGetCurrentSelection(False); if sl.Count = 0 then sl.Text := Clipboard.AsText; TfmEConvertStrings.Execute(GetBitmap, sl); finally FreeAndNil(sl); end; end; function TConvertStringsExpert.GetDisplayName: string; resourcestring SConvertStringsName = 'Convert Strings'; begin Result := SConvertStringsName; end; function TConvertStringsExpert.GetHelpString: string; resourcestring SConvertStringsHelp = ' This expert takes the selected code lines (or the text on the clipboard), ' + 'optionally removes the strings that are used to make them proper Delphi code, ' + 'leaving you with just the raw strings.' + sLineBreak + ' It then uses the selected string prefix/suffix combination to create new strings, ' + 'that can be pasted back the editor or copied to the clipboard.' + sLineBreak + ' To use it, select the string constants in the Delphi editor and ' + 'activate this expert.'; begin Result := SConvertStringsHelp; end; class function TConvertStringsExpert.GetName: string; begin Result := 'ConvertStrings'; end; function TConvertStringsExpert.HasConfigOptions: Boolean; begin Result := False; end; initialization RegisterEditorExpert(TConvertStringsExpert); end.
unit TestHash; interface uses System.Classes, ZMHashTable; type TZMHashTableX = class(TZMHashTable) private FActive: Integer; FDupHashes: Integer; FMaxLinks: Integer; FTotalLinks: Integer; procedure BuildDup(var AStr: string; Node: TZMHashEntry); procedure DumpEntries(SL: TStringList); function DupHashes(const Link: TZMHashEntry): string; procedure DumpHT(SL: TStringList; I: Integer); procedure DumpSummary(SL: TStringList); function MakeName: string; protected public procedure Dump; end; implementation uses System.SysUtils, ZMUtils; procedure TZMHashTableX.BuildDup(var AStr: string; Node: TZMHashEntry); begin FDupHashes := FDupHashes + 1; if AStr <> '' then AStr := AStr + ','; AStr := AStr + Format('<%x, %s>',[Node.Hash, Node.EntryName]); end; function TZMHashTableX.DupHashes(const Link: TZMHashEntry): string; var Node: TZMHashEntry; TheHash: cardinal; begin Result := ''; if Link = nil then exit; TheHash := Link.Hash; Node := Link.HTNext; while Node <> nil do begin if Node.Hash = TheHash then BuildDup(Result, Node); Node := Node.HTNext; end; if Result <> '' then Result := Format('<<%x, %s>>; %s',[Link.Hash, Link.EntryName, Result]) end; procedure TZMHashTableX.Dump; var SL: TStringList; begin SL := TStringList.Create; try DumpEntries(SL); DumpSummary(SL); SL.SaveToFile(MakeName); finally SL.Free; end; end; procedure TZMHashTableX.DumpEntries(SL: TStringList); var I: Integer; begin for I := 0 to Size - 1 do begin if FTable[I] <> nil then begin DumpHT(SL, I); FActive := FActive + 1; end; end; end; procedure TZMHashTableX.DumpHT(SL: TStringList; I: Integer); var Cnt: Integer; Link: TZMHashEntry; S: string; begin Cnt := 0; Link := FTable[I]; while Link <> nil do begin Inc(Cnt); S := S + DupHashes(Link); Link := Link.HTNext; end; SL.Add(Format('%4d, %d, %s',[I, Cnt, S])); FTotalLinks := FTotalLinks + Cnt; if Cnt > FMaxLinks then FMaxLinks := Cnt; end; procedure TZMHashTableX.DumpSummary(SL: TStringList); begin SL.Add(' ------'); SL.Add(Format('Size = %d',[Size])); SL.Add(Format('Count = %d',[Count])); SL.Add(Format('Active = %d, %g%%',[FActive, (FActive / Count) * 100.0])); SL.Add(Format('Links = %d',[FTotalLinks])); SL.Add(Format('Max Links = %d',[FMaxLinks])); SL.Add(Format('Dup hashes = %d',[FDupHashes])); end; function TZMHashTableX.MakeName: string; var VerDate: cardinal; begin VerDate := Cardinal(DateTimeToFileDate(Now)); Result := Format('e:\tmp\HT%X.txt',[VerDate]); end; end.
{ Inno Setup Preprocessor Copyright (C) 2001-2002 Alex Yackimoff $Id: CParser.pas,v 1.3 2009/04/01 15:47:44 mlaan Exp $ } unit CParser; interface uses SysUtils; type EParsingError = class(Exception) Position: Integer; end; TTokenKind = (tkError, tkEOF, tkIdent, tkNumber, tkString, opGreater, opLess, opGreaterEqual, opLessEqual, opEqual, opNotEqual, opOr, opAnd, opAdd, opSubtract, opBwOr, opXor, opMul, opDiv, opBwAnd, opShl, opShr, opMod, opNot, opBwNot, opAssign, opAgnAdd, opAgnSub, opAgnOr, opAgnXor, opAgnMul, opAgnDiv, opAgnAnd, opAgnShl, opAgnShr, opAgnMod, opInc, opDec, tkOpenParen, tkOpenBracket, tkOpenBrace, tkCloseParen, tkCloseBracket, tkCloseBrace, tkPeriod, tkComma, tkColon, tkSemicolon, tkQuestion, tkPtr); TTokenKinds = set of TTokenKind; TCTokenizer = class(TObject) private FEscapeSequences: Boolean; FExprStart: PChar; FIdent: string; FToken: TTokenKind; FNextTokenKnown: Boolean; FNextToken: TTokenKind; FNextTokenPos: PChar; FNextIdent: string; FStoredPos: PChar; procedure IllegalChar(C: Char); function InternalNextToken: TTokenKind; protected FExpr: PChar; FExprOffset: Integer; procedure EndOfExpr; procedure Error(const Message: string); procedure ErrorFmt(const Message: string; Args: array of const); public constructor Create(const Expression: string; EscapeSequences: Boolean); procedure SkipBlanks; function NextToken: TTokenKind; function NextTokenExpect(Expected: TTokenKinds): TTokenKind; function TokenInt: Longint; function PeekAtNextToken: TTokenKind; function PeekAtNextTokenString: string; procedure Store; procedure Restore; procedure SetPos(NewPos: PChar); property Token: TTokenKind read FToken; property TokenString: string read FIdent; end; const ExpressionStartTokens = [tkOpenParen, tkIdent, tkNumber, tkString, opNot, opBwNot, opAdd, opSubtract, opInc, opDec, tkPtr]; implementation uses IsppConsts, CmnFunc2; { TCTokenizer } constructor TCTokenizer.Create(const Expression: string; EscapeSequences: Boolean); begin FExpr := PChar(Expression); FExprStart := FExpr; FEscapeSequences := EscapeSequences; end; procedure TCTokenizer.SkipBlanks; begin while CharInSet(FExpr^, [#1..#32]) do Inc(FExpr); if (FExpr^ = '/') and (FExpr[1] = '*') then begin Inc(FExpr, 2); while True do begin while not CharInSet(FExpr^, [#0, '*']) do Inc(FExpr); if (FExpr^ = '*') then if FExpr[1] = '/' then begin Inc(FExpr, 2); SkipBlanks; Exit; end else Inc(FExpr) else Error('Unterminated comment'); end; end end; function TCTokenizer.InternalNextToken: TTokenKind; procedure Promote(T: TTokenKind); begin Result := T; Inc(FExpr); end; function GetString(QuoteChar: Char): string; var P: PChar; S: string; I: Integer; C: Byte; procedure Unterminated; begin if FExpr^ = #0 then Error('Unterminated string'); end; begin Inc(FExpr); Result := ''; while True do begin P := FExpr; while not CharInSet(FExpr^, [#0, '\', QuoteChar]) do Inc(FExpr); SetString(S, P, FExpr - P); Result := Result + S; Unterminated; if FExpr^ = QuoteChar then begin Inc(FExpr); Break; end; Inc(FExpr); Unterminated; case FExpr^ of #0: Unterminated; '0'..'7':// octal 400 = $100 begin C := 0; I := 0; while CharInSet(FExpr^, ['0'..'7']) and (I < 3) do begin Inc(I); C := (C shl 3) + (Ord(FExpr^) - Ord('0')); Inc(FExpr); Unterminated; end; Result := Result + Char(C); Continue; end; 'a': Result := Result + #7; 'b': Result := Result + #8; 'f': Result := Result + #12; 'n': Result := Result + #10; 'r': Result := Result + #13; 't': Result := Result + #8; 'v': Result := Result + #11; 'x': begin Inc(FExpr); C := 0; I := 0; while CharInSet(FExpr^, ['0'..'9', 'A'..'F', 'a'..'f']) and (I < 2) do begin Inc(I); C := C shl 4; case FExpr^ of '0'..'9': C := C + (Ord(FExpr^) - Ord('0')); 'A'..'F': C := C + (Ord(FExpr^) - Ord('A')) + $0A; else C := C + (Ord(FExpr^) - Ord('a')) + $0A; end; Inc(FExpr); Unterminated; end; Result := Result + Char(C); Continue; end; else Result := Result + FExpr^ end; Inc(FExpr); end; SkipBlanks; if FExpr^ = QuoteChar then Result := Result + GetString(QuoteChar); end; var P: PChar; begin SkipBlanks; Result := tkError; case FExpr^ of #0: begin Result := tkEOF; Exit; end; '!': if FExpr[1] = '=' then Promote(opNotEqual) else Result := opNot; '&': case FExpr[1] of '&': Promote(opAnd); '=': Promote(opAgnAnd) else Result := opBwAnd end; '|': case FExpr[1] of '|': Promote(opOr); '=': Promote(opAgnOr) else Result := opBwOr end; '^': if FExpr[1] = '=' then Promote(opAgnXor) else Result := opXor; '=': if FExpr[1] = '=' then Promote(opEqual) else Result := opAssign; '>': case FExpr[1] of '>': begin Promote(opShr); if FExpr[1] = '=' then Promote(opAgnShr); end; '=': Promote(opGreaterEqual) else Result := opGreater end; '<': case FExpr[1] of '<': begin Promote(opShl); if FExpr[1] = '=' then Promote(opAgnShl); end; '=': Promote(opLessEqual) else Result := opLess end; '+': case FExpr[1] of '=': Promote(opAgnAdd); '+': Promote(opInc) else Result := opAdd end; '-': case FExpr[1] of '=': Promote(opAgnSub); '-': Promote(opDec) else Result := opSubtract end; '/': if FExpr[1] = '=' then Promote(opAgnDiv) else Result := opDiv; '%': if FExpr[1] = '=' then Promote(opAgnMod) else Result := opMod; '*': if FExpr[1] = '=' then Promote(opAgnMul) else Result := opMul; '?': Result := tkQuestion; ':': Result := tkColon; ';': Result := tkSemicolon; ',': Result := tkComma; '.': Result := tkPeriod; '~': Result := opBwNot; '(': Result := tkOpenParen; '[': Result := tkOpenBracket; '{': Result := tkOpenBrace; ')': Result := tkCloseParen; ']': Result := tkCloseBracket; '}': Result := tkCloseBrace; '@': Result := tkPtr; 'A'..'Z', '_', 'a'..'z': begin P := FExpr; repeat Inc(FExpr) until not CharInSet(FExpr^, ['0'..'9', 'A'..'Z', '_', 'a'..'z']); SetString(FIdent, P, FExpr - P); Result := tkIdent; Exit; end; '0'..'9': begin P := FExpr; repeat Inc(FExpr) until not CharInSet(FExpr^, ['0'..'9', 'A'..'F', 'X', 'a'..'f', 'x']); SetString(FIdent, P, FExpr - P); while CharInSet(FExpr^, ['L', 'U', 'l', 'u']) do Inc(FExpr); Result := tkNumber; Exit; end; '"', '''': begin if FEscapeSequences then FIdent := GetString(FExpr^) else FIdent := AnsiExtractQuotedStr(FExpr, FExpr^); Result := tkString; Exit; end; end; if Result = tkError then IllegalChar(FExpr^); Inc(FExpr) end; function TCTokenizer.PeekAtNextToken: TTokenKind; var P: PChar; SaveIdent: string; begin if not FNextTokenKnown then begin P := FExpr; SaveIdent := FIdent; FNextToken := InternalNextToken; FNextIdent := FIdent; FIdent := SaveIdent; FNextTokenPos := FExpr; FExpr := P; FNextTokenKnown := True; end; Result := FNextToken; end; function TCTokenizer.NextToken: TTokenKind; begin if FNextTokenKnown then begin FToken := FNextToken; FIdent := FNextIdent; FExpr := FNextTokenPos; FNextTokenKnown := False; end else FToken := InternalNextToken; Result := FToken; end; function TCTokenizer.PeekAtNextTokenString: string; begin PeekAtNextToken; Result := FNextIdent; end; function TCTokenizer.TokenInt: Longint; var E: Integer; begin Val(FIdent, Result, E); if E <> 0 then Error('Cannot convert to integer'); end; procedure TCTokenizer.Restore; begin FExpr := FStoredPos; FNextTokenKnown := False; end; procedure TCTokenizer.Store; begin FStoredPos := FExpr; end; function TCTokenizer.NextTokenExpect(Expected: TTokenKinds): TTokenKind; function GetFriendlyTokenDesc(T: TTokenKind; Found: Boolean): string; const TokenNames: array[TTokenKind] of string = ('illegal character', 'end of expression', 'identifier', 'number', 'string literal', 'right angle bracket (">")', 'left angle bracket ("<")', 'greater-or-equal-to operator (">=")', 'less-or-equal-to operator ("<=")', 'equality operator ("==")', 'inequality operator ("!=")', 'logical OR operator ("||")', 'logical AND operator ("&&")', 'plus sign ("+")', 'minus sign ("-")', 'OR sign ("|")', 'XOR operator ("^")', 'star sign ("*")', 'slash ("/")', 'AND sign ("&")', 'SHL operator ("<<")', 'SHR operator (">>")', 'percent sign ("%")', 'exclamation sign ("!")', 'tilde ("~")', 'equal sign ("=")', 'compound assignment operator ("+=")', 'compound assignment operator ("-=")', 'compound assignment operator ("|=")', 'compound assignment operator ("^=")', 'compound assignment operator ("*=")', 'compound assignment operator ("/=")', 'compound assignment operator ("&=")', 'compound assignment operator ("<<=")', 'compound assignment operator (">>=")', 'compound assignment operator ("%=")', 'increment operator ("++")', 'decrement operator ("--")', 'opening parenthesis ("(")', 'opening bracket ("[")', 'opening brace ("{")', 'closing parenthesis (")")', 'closing bracket ("]")', 'closing brace ("}")', 'period (".")', 'comma (",")', 'colon (":")', 'semicolon (";")', 'question sign ("?")', 'call-context-of operator ("@")'); begin case T of tkIdent: if Found then Result := Format('identifier "%s"', [TokenString]) else Result := 'identifier'; tkNumber: if Found then Result := Format('number %d (0x%0:.2x)', [TokenInt]) else Result := 'number'; else Result := TokenNames[T]; end; end; function Capitalize(const S: string): string; begin if (S <> '') and CharInSet(S[1], ['a'..'z']) then Result := UpCase(S[1]) + Copy(S, 2, MaxInt) else Result := S; end; var M1, M2: string; I: TTokenKind; C: Integer; begin Result := NextToken; if not (Result in Expected) then begin C := 0; if Expected * ExpressionStartTokens = ExpressionStartTokens then begin M2 := 'expression'; Expected := Expected - ExpressionStartTokens; end; for I := Low(TTokenKind) to High(TTokenKind) do if I in Expected then begin Inc(C); if M2 <> '' then begin if M1 <> '' then M1 := M1 + ', '; M1 := M1 + M2; M2 := ''; end; M2 := GetFriendlyTokenDesc(I, False); end; if M2 <> '' then if M1 <> '' then begin if C > 2 then M1 := M1 + ','; M1 := M1 + ' or ' + M2 end else M1 := M2; Error(Capitalize(Format('%s expected but %s found', [M1, GetFriendlyTokenDesc(Token, True)]))); end; end; procedure TCTokenizer.EndOfExpr; begin NextTokenExpect([tkEOF, tkSemicolon]) end; procedure TCTokenizer.Error(const Message: string); begin ErrorFmt(Message, []); end; procedure TCTokenizer.ErrorFmt(const Message: string; Args: array of const); var E: EParsingError; begin E := EParsingError.CreateFmt(Message, Args); if FExprOffset <> -1 then E.Position := FExprOffset + (FExpr - FExprStart) + 1; raise E; end; procedure TCTokenizer.IllegalChar(C: Char); begin raise EParsingError.CreateFmt(SIllegalChar, [C, Ord(C)]); end; procedure TCTokenizer.SetPos(NewPos: PChar); begin FExpr := NewPos; FNextTokenKnown := False; end; end.
unit uProdutoVO; interface uses System.SysUtils, uKeyField, uTableName; type [TableName('Produto')] TProduto = class private FId: Integer; FCodigo: Integer; FNome: string; FAtivo: Boolean; public [KeyField('Prod_Id')] property Id: Integer read FId write FId; [FieldName('Prod_Codigo')] property Codigo: Integer read FCodigo write FCodigo; [FieldName('Prod_Nome')] property Nome: string read FNome write FNome; [FieldName('Prod_Ativo')] property Ativo: Boolean read FAtivo write FAtivo; end; implementation end.
unit DMX.Data.DSRepDataSets; interface uses System.Classes, Data.DB; type TDataSetRepDataSet = class(TCollectionItem) private FDataSet: TDataSet; FDataName: string; published property DataSet: TDataSet read FDataSet write FDataSet; property DataName: string read FDataName write FDataName; end; TDataSetRepDataSets = class(TCollection) private function GetItems(AIndex: Integer): TDataSetRepDataSet; procedure SetItmes(AIndex: Integer; const Value: TDataSetRepDataSet); public function Add: TDataSetRepDataSet; overload; function Add(ADataName: string; ADataSet: TDataSet): TDataSetRepDataSet; overload; procedure Remove(ADataSet: TDataSet); function FindDataSet(const ADataName: string): TDataSetRepDataSet; property Items[AIndex: Integer]: TDataSetRepDataSet read GetItems write SetItmes; default; end; implementation { TDataSetRepDataSets } function TDataSetRepDataSets.Add(ADataName: string; ADataSet: TDataSet): TDataSetRepDataSet; begin Result := Add; Result.DataName := ADataName; Result.DataSet := ADataSet; end; function TDataSetRepDataSets.FindDataSet(const ADataName: string): TDataSetRepDataSet; var I: Integer; begin Result := nil; for I := 0 to Count - 1 do if Items[I].DataName = ADataName then Exit(Items[I]); end; function TDataSetRepDataSets.Add: TDataSetRepDataSet; begin Result := TDataSetRepDataSet(inherited Add); end; function TDataSetRepDataSets.GetItems(AIndex: Integer): TDataSetRepDataSet; begin Result := TDataSetRepDataSet(inherited Items[AIndex]); end; procedure TDataSetRepDataSets.Remove(ADataSet: TDataSet); var I: Integer; begin for I := Count - 1 downto 0 do begin if Items[I].DataSet = ADataSet then begin Items[I].DataSet := nil; Items[I].Free; end; end; end; procedure TDataSetRepDataSets.SetItmes(AIndex: Integer; const Value: TDataSetRepDataSet); begin inherited Items[AIndex] := Value; end; end.
unit vector_lib; interface uses Classes,streaming_class_lib,sysUtils,simple_parser_lib,quaternion_lib,variants,TypInfo; type TVector=class(TStreamingClass) private fx,fy,fz: Real; function vector2str: string; procedure str2vector(str: string); function getLength: Real; public constructor Create(owner: TComponent); overload; override; constructor Create(ax: Real=0;ay: Real=0;az: Real=0); reintroduce; overload; constructor Create(str: string); reintroduce; overload; constructor CopyFrom(vector: TVector); procedure Clear; override; procedure VectorAssign(source: TVector); //быстрее, чем обычный Assign procedure Assign(source: TPersistent); overload; override; procedure Assign(ax,ay,az: Real); reintroduce; overload; procedure add(source: TVector); procedure sub(by: TVector); procedure normalize; procedure negate; procedure Mul(by: Real); procedure Divide(by: Real); procedure Vector_multiply(by: TVector); procedure Ortogonalize(axis: TVector); function ProjectionLiesOnVectorItself(axis: TVector): boolean; procedure rotateX(angle: Real); procedure rotateZ(angle: Real); procedure rotateY(angle: Real); procedure GenerateTwoPerpVectors(av1,av2: TVector); procedure rotate_by_quat(q: TAbstractQuaternion); function getLength_squared: Real; //Monte-Carlo methods procedure GenerateRandomVector_by_quat; procedure GenerateRandomVector_by_ball; procedure GenerateRandomVector_by_Marsalia; procedure GenerateRandomVector_by_spheric; procedure GenerateRandomPointInBall; procedure GenerateRandomPointInBall_by_spheric; class function scalar_product(M0,M1: TVector): Real; class function cos_between(M0,M1: TVector): Real; class function line_distance(M0,M1: TVector): Real; class function distance_between(M0,M1: TVector): Real; class function distance_squared(M0,M1: TVector): Real; published property X: Real read fX write fX; property Y: Real read fY write fY; property Z: Real read fZ write fZ; property Value: string read vector2str write str2vector stored false; property Length: Real read getLength; property Length_squared: Real read getLength_squared; end; TVectorVarData = packed record VType: TVarType; Reserved1, Reserved2, Reserved3: Word; VVector: TVector; Reserved4: LongInt; end; TVectorVariantType=class(TPublishableVariantType) protected function GetInstance(const V: TVarData): TObject; override; function RightPromotion(const V: TVarData; const Operator: TVarOp; out RequiredVarType: TVarType): Boolean; override; function LeftPromotion(const V: TVarData; const Operator: TVarOp; out RequiredVarType: TVarType): Boolean; override; public function DoProcedure(const V: TVarData; const Name: string; const Arguments: TVarDataArray): Boolean; override; procedure Clear(var V: TVarData); override; procedure Copy(var Dest: TVarData; const Source: TVarData; const Indirect: Boolean); override; procedure Cast(var Dest: TVarData; const Source: TVarData); override; procedure CastTo(var Dest: TVarData; const Source: TVarData; const AVarType: TVarType); override; procedure UnaryOp(var Right: TVarData; const Operator: Integer); override; procedure BinaryOp(var Left: TVarData; const Right: TVarData; const Operator: TVarOp); override; end; function VarVector: TVarType; function VarVectorCreate(x: Real=0; y:Real=0; z:Real=0): Variant; overload; function VarVectorCreate(str: string): Variant; overload; function VarVectorCreate(vector: TVector): Variant; overload; function LineDistance(p1,p2: Variant): Real; function VectorMul(p1,p2: Variant): Variant; function VectorLength(p: Variant): Real; implementation uses math; var VectorVariantType: TVectorVariantType; constructor TVector.Create(owner: TComponent); begin inherited Create(owner); SetSubComponent(true); end; constructor TVector.Create(ax: Real=0; ay: Real=0; az: Real=0); begin Create(nil); x:=ax; y:=ay; z:=az; end; constructor TVector.Create(str: string); begin Create(nil); value:=str; end; constructor TVector.CopyFrom(vector: TVector); begin Create(nil); Assign(vector); end; procedure TVector.Clear; begin x:=0; y:=0; z:=0; end; procedure TVector.Assign(source: TPersistent); var t: TVector absolute source; begin if source is TVector then begin x:=t.x; y:=t.y; z:=t.z; end else Inherited Assign(source); end; procedure TVector.VectorAssign(source: TVector); begin x:=source.X; y:=source.Y; z:=source.Z; end; procedure TVector.Assign(ax,ay,az: Real); begin x:=ax; y:=ay; z:=az; end; function TVector.vector2str: string; begin result:='('+FloatToStr(x)+';'+FloatToStr(y)+';'+FloatToStr(z)+')'; end; procedure TVector.str2vector(str: string); var p: TSimpleParser; ch: char; begin p:=TSimpleParser.Create(str); ch:=p.getChar; if ch<>'(' then Raise Exception.Create('Tvector.str2vector: first character is"'+ ch+'" not "("'); x:=p.getFloat; if p.getChar<>';' then Raise Exception.Create('Tvector.str2vector: wrong separator between x and y, must be ";"'); y:=p.getFloat; if p.getChar<>';' then Raise Exception.Create('Tvector.str2vector: wrong separator between y and z, must be ";"'); z:=p.getFloat; if p.getChar<>')' then Raise Exception.Create('Tvector.str2vector: wrong character after z value, must be ")"'); if not p.eof then Raise Exception.Create('Tvector.str2vector: end of file expected'); p.Free; end; procedure TVector.add(source: TVector); begin x:=x+source.x; y:=y+source.y; z:=z+source.z; end; procedure TVector.sub(by: TVector); begin x:=x-by.x; y:=y-by.y; z:=z-by.z; end; procedure TVector.normalize; var norm: Real; begin norm:=x*x+y*y+z*z; assert(norm>0,name+': vector normalize: zero-length vector'); norm:=sqrt(norm); x:=x/norm; y:=y/norm; z:=z/norm; end; procedure TVector.negate; begin x:=-x; y:=-y; z:=-z; end; function TVector.getLength: Real; begin result:=sqrt(x*x+y*y+z*z); end; function TVector.getLength_squared: Real; begin Result:=x*x+y*y+z*z; end; procedure TVector.Mul(by: Real); begin x:=x*by; y:=y*by; z:=z*by; end; procedure TVector.Divide(by: Real); begin x:=x/by; y:=y/by; z:=z/by; end; procedure TVector.Vector_multiply(by: TVector); var xt,yt: Real; begin xt:=x; yt:=y; x:=yt*by.z-z*by.y; y:=z*by.x-xt*by.z; z:=xt*by.y-yt*by.x; end; procedure TVector.Ortogonalize(axis: TVector); var a: Real; begin //этот вариант должен быть существенно быстрее a:=TVector.scalar_product(self,axis)/axis.Length_squared; x:=x-a*axis.x; y:=y-a*axis.Y; z:=z-a*axis.Z; end; function TVector.ProjectionLiesOnVectorItself(axis: TVector): boolean; var k: Real; begin //проверяем, что "наш" вектор, давая проекцию на v, ляжет на него, т.е в единицах //v будет составлять от 0 до 1 длины k:=TVector.scalar_product(self,axis)/axis.Length_squared; Result:=(k>=0) and (k<=1); end; procedure TVector.rotateX(angle: Real); var t,si,co: Real; begin si:=sin(angle); co:=cos(angle); t:=y; y:=y*co-z*si; z:=t*si+z*co; end; procedure TVector.rotateZ(angle: Real); var t,si,co: Real; begin si:=sin(angle); co:=cos(angle); t:=x; x:=x*co-y*si; y:=t*si+y*co; end; procedure TVector.rotateY(angle: Real); var t,si,co: Real; begin si:=sin(angle); co:=cos(angle); t:=z; z:=z*co-x*si; x:=t*si+x*co; end; procedure TVector.GenerateTwoPerpVectors(av1,av2: TVector); begin assert(abs(length_squared-1)<1e-5, 'GenerateTwoPerpVectors: v1 not normalized'); if abs(X)>0.577350269189626 then av1.Assign(0,1,0) else av1.Assign(1,0,0); av1.Vector_multiply(self); av1.normalize; av2.VectorAssign(self); av2.Vector_multiply(av1); end; class function TVector.scalar_product(M0,M1: TVector): Real; begin result:=M0.x*M1.x+M0.y*M1.y+M0.z*M1.z; end; class function TVector.cos_between(M0,M1: TVector): Real; begin result:=scalar_product(M0,M1)/M0.Length/M1.Length; end; class function TVector.distance_between(M0,M1: TVector): Real; begin Result:=Sqrt(sqr(M0.X-M1.X)+Sqr(M0.Y-M1.Y)+Sqr(M0.Z-M1.Z)); end; class function TVector.distance_squared(M0,M1: TVector): Real; begin Result:=sqr(M0.X-M1.X)+sqr(M0.Y-M1.Y)+sqr(M0.Z-M1.Z); end; class function TVector.line_distance(M0,M1: TVector): Real; //M0, M1 - координаты точек //найти расстояние от начала координат до отрезка, который их соединяет var t: TVector; k: Real; begin t:=TVector.Create; t.Assign(M1); t.sub(M0); k:=-scalar_product(t,M0)/scalar_product(t,t); if k<=0 then result:=M0.Length else if k>=1 then result:=M1.Length else begin t.Mul(-k); t.sub(M0); result:=t.Length; end; t.Free; end; procedure TVector.rotate_by_quat(q: TAbstractQuaternion); var t,n: TQuaternion; begin t:=TQuaternion.Create(nil); t.Assign(q); t.conjugate; n:=TQuaternion.Create(nil,0,x,y,z); //наш родной вектор t.left_mul(n); t.left_mul(q); x:=t.x; y:=t.y; z:=t.z; t.Free; n.Free; end; procedure TVector.GenerateRandomVector_by_quat; var a,x1,y1,z1,L: Real; begin repeat a:=2*random-1; x1:=2*random-1; y1:=2*random-1; z1:=2*random-1; L:=a*a+x1*x1+y1*y1+z1*z1; until L<=1; fx:=(a*a+x1*x1-y1*y1-z1*z1)/L; fy:=2*(x1*y1-a*z1)/L; fz:=2*(x1*z1+a*y1)/L; end; procedure TVector.GenerateRandomVector_by_ball; var L: Real; begin repeat fx:=2*random-1; fy:=2*random-1; fz:=2*random-1; L:=fx*fx+fy*fy+fz*fz; until L<=1; L:=1/sqrt(L); fx:=fx*L; fy:=fy*L; fz:=fz*L; end; procedure TVector.GenerateRandomVector_by_Marsalia; var L,alp: Real; begin repeat fx:=2*random-1; fy:=2*random-1; L:=fx*fx+fy*fy; until L<=1; alp:=2*sqrt(1-L); fx:=fx*alp; fy:=fy*alp; fz:=2*L-1; end; procedure TVector.GenerateRandomVector_by_spheric; var theta,phi: Real; const twopi=6.28318530717959; begin theta:=twopi*random; phi:=arcsin(2*random-1); fy:=sin(phi); phi:=cos(phi); fx:=cos(theta)*phi; fy:=sin(theta)*phi; end; procedure TVector.GenerateRandomPointInBall; begin repeat fx:=random*2-1; fy:=random*2-1; fz:=random*2-1; until fx*fx+fy*fy+fz*fz<=1; end; procedure TVector.GenerateRandomPointInBall_by_spheric; var theta,phi,r: Real; const twopi=6.28318530717959; begin theta:=random*twopi; phi:=arcsin(2*random-1); // r:=power(random,0.3333333333); r:=max(random,random); r:=max(r,random); fy:=r*sin(phi); r:=r*cos(phi); fx:=r*cos(theta); fz:=r*sin(theta); end; (* TVectorVariantType *) function TVectorVariantType.GetInstance(const V: TVarData): TObject; begin Result:=TVectorVarData(V).VVector; end; procedure TVectorVariantType.Clear(var V: TVarData); begin V.VType:=varEmpty; FreeAndNil(TVectorVarData(V).VVector); end; procedure TVectorVariantType.Copy(var Dest: TVarData; const Source: TVarData; const Indirect: Boolean); begin if Indirect and VarDataIsByRef(Source) then VarDataCopyNoInd(Dest, Source) else with TVectorVarData(Dest) do begin VType := VarType; VVector := TVector.Create; VVector.Assign(TVectorVarData(source).VVector); end; end; procedure TVectorVariantType.Cast(var Dest: TVarData; const Source: TVarData); begin TVectorVarData(Dest).VVector:=TVector.Create; TVectorVarData(Dest).VVector.Value:=VarDataToStr(Source); //вряд ли кто-то будет подсовывать числа, а если даже подсунет //они преобразуются в строку, а в этой строке вектор по-любому не выйдет. Dest.VType:=varType; end; procedure TVectorVariantType.CastTo(var Dest: TVarData; const Source: TVarData; const AVarType: TVarType); var LTemp: TVarData; begin if Source.VType = VarType then //бывает еще не определенный Variant case AVarType of varOleStr: VarDataFromOleStr(Dest, TVectorVarData(Source).VVector.Value); varString: VarDataFromStr(Dest, TVectorVarData(Source).VVector.Value); varSingle,varDouble,varCurrency,varInteger: RaiseCastError; else VarDataInit(LTemp); try VarDataFromStr(Ltemp,TVectorVarData(Source).VVector.Value); VarDataCastTo(Dest, LTemp, AVarType); finally VarDataClear(LTemp); end; end else inherited; end; function TVectorVariantType.RightPromotion(const V: TVarData; const Operator: TVarOp; out RequiredVarType: TVarType): Boolean; begin if Operator=opMultiply then Case V.VType of varInteger, varSingle,varDouble,varCurrency,varShortInt,varByte,varWord,varLongWord: RequiredVarType:=V.VType; else RequiredVarType:=VarType; end else RequiredVarType:=VarType; Result:=True; end; function TVectorVariantType.LeftPromotion(const V: TVarData; const Operator: TVarOp; out RequiredVarType: TVarType): Boolean; begin if Operator=opMultiply then Case V.VType of varInteger, varSingle,varDouble,varCurrency,varShortInt,varByte,varWord,varLongWord: RequiredVarType:=V.VType; else RequiredVarType:=VarType; end else if (Operator = opAdd) and VarDataIsStr(V) then RequiredVarType:=varString else RequiredVarType := VarType; Result:=True; end; procedure TVectorVariantType.UnaryOp(var Right: TVarData; const Operator: Integer); begin if (Right.VType=VarType) and (Operator=opNegate) then TVectorVarData(Right).VVector.Mul(-1) else RaiseInvalidOp; end; procedure TVectorVariantType.BinaryOp(var Left: TVarData; const Right: TVarData; const Operator: TVarOp); var LTemp: TVarData; begin if Right.VType = VarType then case Left.VType of varString: case Operator of opAdd: Variant(Left) := Variant(Left) + TVectorVarData(Right).VVector.Value; else RaiseInvalidOp; end; varInteger, varSingle,varDouble,varCurrency,varShortInt,varByte,varWord,varLongWord: case Operator of opMultiply: begin VarDataInit(LTemp); try VarDataCastTo(LTemp, Left, varDouble); Variant(Left):=VarVectorCreate; TVectorVarData(Left).VVector.Assign(TVectorVarData(right).VVector); TVectorVarData(Left).VVector.Mul(LTemp.VDouble); finally VarDataClear(LTemp); end; end; else RaiseInvalidOp; end; else if Left.VType = VarType then case Operator of opAdd: TVectorVarData(Left).VVector.Add(TVectorVarData(Right).VVector); opSubtract: TVectorVarData(Left).VVector.Sub(TVectorVarData(Right).VVector); opMultiply: //скаляр. умножение Variant(Left):=TVector.scalar_product(TVectorVarData(Left).VVector,TVectorVarData(Right).VVector); // RaiseInvalidop; else RaiseInvalidOp; end else RaiseInvalidOp; end else if Operator=opMultiply then begin VarDataInit(LTemp); try VarDataCastTo(LTemp, Right, varDouble); TVectorVarData(Left).VVector.Mul(LTemp.VDouble); finally VarDataClear(LTemp); end; end else RaiseInvalidOp; end; function TVectorVariantType.DoProcedure(const V: TVarData; const Name: string; const Arguments: TVarDataArray): Boolean; begin Result:=true; If (Name='ROTATEBYX') and (Length(Arguments)=1) then TVectorVarData(V).VVector.rotateX(Variant(Arguments[0])) else if (Name='ROTATEBYY') and (Length(Arguments)=1) then TVectorVarData(V).VVector.rotateY(Variant(Arguments[0])) else if (Name='ROTATEBYZ') and (Length(Arguments)=1) then TVectorVarData(V).VVector.rotateZ(Variant(Arguments[0])) else if (Name='VECTORMUL') and (Length(Arguments)=1) and (Arguments[0].VType=VarType) then TVectorVarData(V).VVector.Vector_multiply(TVectorVarData(Arguments[0]).vvector) else if (Name='NORMALIZE') and (Length(Arguments)=0) then TVectorVarData(V).VVector.normalize else Result:=False; end; (* 'Fabric' *) function VarVector: TVarType; begin Result:=VectorVariantType.VarType; end; procedure VarVectorCreateInto(var ADest: Variant; const AVector: TVector); begin VarClear(ADest); TVectorVarData(ADest).VType := VarVector; TVectorVarData(ADest).VVector := AVector; end; function VarVectorCreate(X: Real=0; Y: Real=0; Z: Real=0): Variant; begin VarVectorCreateInto(Result,TVector.Create(X,Y,Z)); end; function VarVectorCreate(str: string): Variant; begin VarVectorCreateInto(Result,TVector.Create(str)); end; function VarVectorCreate(vector: TVector): Variant; begin VarVectorCreateInto(Result,TVector.CopyFrom(vector)); end; function LineDistance(p1,p2: Variant): Real; begin if (TVectorVarData(p1).VType=varVector) and (TVectorVarData(p2).VType=varVector) then begin Result:=TVector.line_distance(TVectorVarData(p1).VVector,TVectorVarData(p2).VVector); end else Raise Exception.Create('LineDistance: wrong variant type, should be vector'); end; function VectorMul(p1,p2: Variant): Variant; var v: TVector; begin v:=TVector.Create(nil); v.Assign(TVectorVarData(p1).VVector); v.Vector_multiply(TVectorVarData(p2).VVector); VarVectorCreateInto(Result,v); end; function VectorLength(p: Variant): Real; begin Result:=TVectorVarData(p).VVector.Length; end; initialization RegisterClass(TVector); VectorVariantType:=TVectorVariantType.Create; finalization FreeAndNil(VectorVariantType); end.
unit BaiduMapAPI.ViewService.Android; //author:Xubzhlin //Email:371889755@qq.com //百度地图API 地图服务 单元 //官方链接:http://lbsyun.baidu.com/ //TAndroidBaiduMapViewService 百度地图 安卓 地图服务 interface uses System.Classes, System.Generics.Collections, System.Types, FMX.Maps, Androidapi.JNI.Embarcadero, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNIBridge, Androidapi.JNI.baidu.mapapi, Androidapi.JNI.baidu.mapapi.map, Androidapi.JNI.baidu.mapapi.model, BaiduMapAPI.ViewService; type TAndroidBaiduMapViewService = class; TOnMapBaseListener = class(TJavaLocal) private [weak] FViewService:TAndroidBaiduMapViewService; public constructor Create(MapViewService:TAndroidBaiduMapViewService); end; //地图点击监听 用户Marker、Polyline以外的覆盖物点击 TOnMapClickListener = class(TOnMapBaseListener, JBaiduMap_OnMapClickListener) procedure onMapClick(P1: JLatLng); cdecl; function onMapPoiClick(P1: JMapPoi): Boolean; cdecl; end; //Marker 点击监听 TOnMarkerClickListener = class(TOnMapBaseListener, JBaiduMap_OnMarkerClickListener) function onMarkerClick(P1: JMarker): Boolean; cdecl; end; //Polyline 点击监听 TOnPolylineClickListener = class(TOnMapBaseListener, JBaiduMap_OnPolylineClickListener) function onPolylineClick(P1: JPolyline): Boolean; cdecl; end; TAndroidBaiduMapViewService = class(TBaiduMapViewService) private FMapView:JMapView; FBMMap:JBaiduMap; FJNativeLayout:JNativeLayout; FOnMarkerClickListener:TOnMarkerClickListener; FMapObjects:TDictionary<Integer, TMapObjectBase>; procedure InitInstance; procedure RealignView; function BuildMarkerOptions(const D: TMapMarkerDescriptor): JMarkerOptions; function BuildCircleOptions(const D: TMapCircleDescriptor): JCircleOptions; function BuildPolygonOptions(const D: TMapPolygonDescriptor): JPolygonOptions; function BuildPolylineOptions(const D: TMapPolylineDescriptor): JPolylineOptions; function GetMapObject<T: TMapObjectBase>(const Key: Integer): T; procedure PutMapObject<T: TMapObjectBase>(const Key: Integer; const MapObject: T); procedure RemoveMapObject(const Key: Integer); protected procedure DoShowBaiduMap; override; procedure DoUpdateBaiduMapFromControl; override; function DoAddMarker(const Descriptor: TMapMarkerDescriptor):TBaiduMapMarker; override; function DoAddPolyline(const Descriptor: TMapPolylineDescriptor):TMapPolyline; override; function DoAddPolygon(const Descriptor: TMapPolygonDescriptor):TMapPolygon; override; function DoAddCircle(const Descriptor: TMapCircleDescriptor): TMapCircle; override; procedure DoSetCenterCoordinate(const Coordinate:TMapCoordinate); override; procedure DoSetZoomLevel(Level:Single); override; procedure DoSetVisible(const Value: Boolean); override; public constructor Create(AKey:String); override; destructor Destroy; override; end; implementation uses FMX.Platform.Android, FMX.Forms, FMX.Helpers.Android, Androidapi.JNI.JavaUtil, FMX.Surfaces, Androidapi.Helpers, FMX.Graphics, System.IOUtils, System.SysUtils; type TAndroidMapMarker = class(TBaiduMapMarker) private FJavaMarker: JMarker; [Weak] FMapView: TAndroidBaiduMapViewService; public constructor Create(const Descriptor: TMapMarkerDescriptor); override; destructor Destroy; override; procedure SetJMarker(Marker: JMarker); procedure SetHostView(MapView: TAndroidBaiduMapViewService); procedure Remove; override; procedure SetVisible(const Value: Boolean); override; end; TAndroidMapCircle = class(TMapCircle) private FJavaCircle: JCircle; [Weak] FMapView: TAndroidBaiduMapViewService; public destructor Destroy; override; procedure SetJCircle(Circle: JCircle); procedure SetHostView(MapView: TAndroidBaiduMapViewService); procedure Remove; override; procedure SetVisible(const Value: Boolean); override; end; TAndroidMapPolygon = class(TMapPolygon) private FJavaPolygon: JPolygon; [Weak] FMapView: TAndroidBaiduMapViewService; public destructor Destroy; override; procedure SetJPolygon(Polygon: JPolygon); procedure SetHostView(MapView: TAndroidBaiduMapViewService); procedure Remove; override; procedure SetVisible(const Value: Boolean); override; end; TAndroidMapPolyline = class(TMapPolyline) private FJavaPolyline: JPolyline; [Weak] FMapView: TAndroidBaiduMapViewService; public destructor Destroy; override; procedure SetJPolyline(Polyline: JPolyline); procedure SetHostView(MapView: TAndroidBaiduMapViewService); procedure Remove; override; procedure SetVisible(const Value: Boolean); override; end; function CoordToLatLng(const C: TMapCoordinate): JLatLng; begin Result := TJLatLng.JavaClass.init(C.Latitude, C.Longitude) end; function CreateBitmapDescriptorFromBitmap(const Bitmap: TBitmap): JBitmapDescriptor; var Surface: TBitmapSurface; JavaBitmap: JBitmap; begin Result := nil; Surface := TBitmapSurface.Create; try Surface.Assign(Bitmap); JavaBitmap := TJBitmap.JavaClass.createBitmap(Surface.Width, Surface.Height, TJBitmap_Config.JavaClass.ARGB_8888); if SurfaceToJBitmap(Surface, JavaBitmap) then Result := TJBitmapDescriptorFactory.JavaClass.fromBitmap(JavaBitmap); finally Surface.DisposeOf; end; end; { TAndroidBaiduMapViewService } function TAndroidBaiduMapViewService.BuildCircleOptions( const D: TMapCircleDescriptor): JCircleOptions; var Stroke:JStroke; begin Stroke:=TJStroke.JavaClass.init(trunc(D.StrokeWidth), D.StrokeColor); Result := TJCircleOptions.JavaClass.init .center(CoordToLatLng(D.Center)) .fillColor(D.FillColor) .stroke(Stroke) .radius(trunc(D.Radius)) .zIndex(trunc(D.ZIndex)); end; function TAndroidBaiduMapViewService.BuildMarkerOptions( const D: TMapMarkerDescriptor): JMarkerOptions; begin Result := TJMarkerOptions.JavaClass.init.alpha(D.Opacity) .anchor(D.Origin.X, D.Origin.Y) .draggable(D.Draggable) .flat(D.Appearance = TMarkerAppearance.Flat) .position(CoordToLatLng(D.Position)) .rotate(D.Rotation) .title(StringToJString(D.Title)) .visible(D.Visible); if D.Icon <> nil then Result := Result.icon(CreateBitmapDescriptorFromBitmap(D.Icon)); end; function TAndroidBaiduMapViewService.BuildPolygonOptions( const D: TMapPolygonDescriptor): JPolygonOptions; var Vertex: TMapCoordinate; List: JArrayList; Stroke:JStroke; begin Stroke:=TJStroke.JavaClass.init(trunc(D.StrokeWidth), D.StrokeColor); List := TJArrayList.JavaClass.init; for Vertex in D.Outline.Points do List.add(CoordToLatLng(Vertex)); Result := TJPolygonOptions.JavaClass.init .fillColor(D.FillColor) .stroke(Stroke) .points(JList(List)) .zIndex(trunc(D.ZIndex)); end; function TAndroidBaiduMapViewService.BuildPolylineOptions( const D: TMapPolylineDescriptor): JPolylineOptions; var List: JList; Vertex: TMapCoordinate; begin Result := TJPolylineOptions.JavaClass.init .width(trunc(D.StrokeWidth)) .color(D.StrokeColor) .zIndex(trunc(D.ZIndex)); List := TJList.Create; for Vertex in D.Points.Points do List.add(CoordToLatLng(Vertex)); Result.points(List); end; constructor TAndroidBaiduMapViewService.Create(AKey: String); begin inherited Create(AKey); FMapObjects:=TDictionary<Integer, TMapObjectBase>.Create; end; destructor TAndroidBaiduMapViewService.Destroy; begin FMapObjects.DisposeOf; FOnMarkerClickListener.DisposeOf; FBMMap:=nil; FMapView:=nil; FJNativeLayout := nil; inherited; end; function TAndroidBaiduMapViewService.DoAddCircle( const Descriptor: TMapCircleDescriptor): TMapCircle; var R: TAndroidMapCircle; begin R := TAndroidMapCircle.Create(Descriptor); R.SetHostView(Self); Result:=R; if FBMMap <> nil then begin R.SetJCircle(TUIThreadCaller.Call<TMapCircleDescriptor,JCircle>( function(D: TMapCircleDescriptor): JCircle begin Result := JCircle(FBMMap.addOverlay(BuildCircleOptions(D))); end, Descriptor)); if R.FJavaCircle <> nil then PutMapObject<TMapCircle>(R.FJavaCircle.hashCode, Result); end; end; function TAndroidBaiduMapViewService.DoAddMarker( const Descriptor: TMapMarkerDescriptor): TBaiduMapMarker; var R: TAndroidMapMarker; begin R := TAndroidMapMarker.Create(Descriptor); R.SetHostView(Self); Result := R; if FMapView <> nil then begin R.SetJMarker(TUIThreadCaller.Call<TMapMarkerDescriptor,JMarker>( function(D: TMapMarkerDescriptor): JMarker begin Result := JMarker(FBMMap.addOverlay(BuildMarkerOptions(D))); end, Descriptor)); if R.FJavaMarker <> nil then begin PutMapObject<TBaiduMapMarker>(R.FJavaMarker.hashCode, Result); end; end; end; function TAndroidBaiduMapViewService.DoAddPolygon( const Descriptor: TMapPolygonDescriptor): TMapPolygon; var R: TAndroidMapPolygon; begin R := TAndroidMapPolygon.Create(Descriptor); R.SetHostView(Self); Result := R; if FMapView <> nil then begin R.SetJPolygon(TUIThreadCaller.Call<TMapPolygonDescriptor, JPolygon>( function(D: TMapPolygonDescriptor): JPolygon begin Result := JPolygon(FBMMap.addOverlay(BuildPolygonOptions(D))); end, Descriptor)); if R.FJavaPolygon <> nil then PutMapObject<TMapPolygon>(R.FJavaPolygon.hashCode, Result); end; end; function TAndroidBaiduMapViewService.DoAddPolyline( const Descriptor: TMapPolylineDescriptor): TMapPolyline; var R: TAndroidMapPolyline; begin R := TAndroidMapPolyline.Create(Descriptor); R.SetHostView(Self); Result := R; if FMapView <> nil then begin R.SetJPolyline(TUIThreadCaller.Call<TMapPolylineDescriptor,JPolyline>( function(D: TMapPolylineDescriptor): JPolyline begin Result := JPolyline(FBMMap.addOverlay(BuildPolylineOptions(D))); end, Descriptor)); if R.FJavaPolyline <> nil then PutMapObject<TMapPolyline>(R.FJavaPolyline.hashCode, Result); end; end; procedure TAndroidBaiduMapViewService.DoSetCenterCoordinate( const Coordinate: TMapCoordinate); var Builder:JMapStatus_Builder; MapStatusUpdate:JMapStatusUpdate; begin Builder:=TJMapStatus_Builder.JavaClass.init; Builder.target(TJLatLng.JavaClass.init(Coordinate.Latitude, Coordinate.Longitude)); MapStatusUpdate:=TJMapStatusUpdateFactory.JavaClass.newMapStatus(Builder.build); CallInUIThread( procedure begin FBMMap.setMapStatus(MapStatusUpdate); end); end; procedure TAndroidBaiduMapViewService.DoSetVisible(const Value: Boolean); begin if FMapView = nil then exit; CallInUiThread(procedure begin if Value then FMapView.onResume else FMapView.onPause; end); end; procedure TAndroidBaiduMapViewService.DoSetZoomLevel(Level: Single); var Builder:JMapStatus_Builder; MapStatusUpdate:JMapStatusUpdate; begin Builder:=TJMapStatus_Builder.JavaClass.init; Builder.zoom(Level); MapStatusUpdate:=TJMapStatusUpdateFactory.JavaClass.newMapStatus(Builder.build); CallInUIThread( procedure begin FBMMap.setMapStatus(MapStatusUpdate); end); end; procedure TAndroidBaiduMapViewService.DoShowBaiduMap; begin InitInstance; end; procedure TAndroidBaiduMapViewService.DoUpdateBaiduMapFromControl; begin CallInUiThread(RealignView); end; function TAndroidBaiduMapViewService.GetMapObject<T>(const Key: Integer): T; var TmpResult: TMapObjectBase; begin if FMapObjects.TryGetValue(Key, TmpResult) then try Result := TmpResult as T; except on EInvalidCast do Result := nil; end; end; procedure TAndroidBaiduMapViewService.InitInstance; var Rect: JRect; begin CallInUIThread( procedure begin FJNativeLayout := TJNativeLayout.JavaClass.init(SharedActivity, MainActivity.getWindow.getDecorView.getWindowToken); FMapView := TJMapView.JavaClass.init(SharedActivityContext); FBMMap := FMapView.getMap; //注册Marker 点击事件 FOnMarkerClickListener:=TOnMarkerClickListener.Create(Self); FBMMap.setOnMarkerClickListener(FOnMarkerClickListener); Rect := TJRect.JavaClass.init(0, 0, Round(Control.Size.Height), Round(Control.Size.Width)); FMapView.requestFocus(0, Rect); FJNativeLayout.setPosition(0, 0); FJNativeLayout.setSize(Round(Control.Size.Height), Round(Control.Size.Width)); FJNativeLayout.setControl(FMapView); RealignView; end); end; procedure TAndroidBaiduMapViewService.PutMapObject<T>(const Key: Integer; const MapObject: T); var MObject: TMapObjectBase; begin if FMapObjects.TryGetValue(Key, MObject) then FMapObjects[Key] := MapObject else FMapObjects.Add(Key, MapObject); end; procedure TAndroidBaiduMapViewService.RealignView; const MapExtraSpace = 100; // To be sure that destination rect will fit to fullscreen var MapRect: TRectF; RoundedRect: TRect; LSizeF: TPointF; LRealBounds: TRectF; LRealPosition, LRealSize: TPointF; begin if (FJNativeLayout <> nil) then begin LRealPosition := Control.LocalToAbsolute(TPointF.Zero) * Scale; LSizeF := TPointF.Create(Control.Size.Size.cx, Control.Size.Size.cy); LRealSize := Control.LocalToAbsolute(LSizeF) * Scale; LRealBounds := TRectF.Create(LRealPosition, LRealSize); MapRect := TRectF.Create(0, 0, Control.Width * MapExtraSpace, Control.Height * MapExtraSpace); RoundedRect := MapRect.FitInto(LRealBounds).Round; if not Control.ParentedVisible then RoundedRect.Left := Round(Screen.Size.cx * Scale); FJNativeLayout.setPosition(RoundedRect.TopLeft.X, RoundedRect.TopLeft.Y); FJNativeLayout.setSize(RoundedRect.Width, RoundedRect.Height); end; end; procedure TAndroidBaiduMapViewService.RemoveMapObject(const Key: Integer); begin FMapObjects.Remove(Key); end; { TAndroidMapMarker } constructor TAndroidMapMarker.Create(const Descriptor: TMapMarkerDescriptor); begin inherited; end; destructor TAndroidMapMarker.Destroy; begin Remove; inherited; end; procedure TAndroidMapMarker.Remove; begin inherited; TUIThreadCaller.InvokeIfNotNil<JMarker>(procedure (M: JMarker) begin M.remove; end, FJavaMarker); FMapView.RemoveMapObject(FJavaMarker.hashCode); end; procedure TAndroidMapMarker.SetHostView(MapView: TAndroidBaiduMapViewService); begin FMapView:=MapView; end; procedure TAndroidMapMarker.SetJMarker(Marker: JMarker); begin FJavaMarker := Marker; end; procedure TAndroidMapMarker.SetVisible(const Value: Boolean); begin inherited; TUIThreadCaller.InvokeIfNotNil<JMarker>( procedure (M: JMarker) begin M.setVisible(Value); end, FJavaMarker); end; { TAndroidMapCircle } destructor TAndroidMapCircle.Destroy; begin Remove; inherited; end; procedure TAndroidMapCircle.Remove; begin inherited; TUIThreadCaller.InvokeIfNotNil<JCircle>( procedure (C: JCircle) begin C.remove; end, FJavaCircle); FMapView.RemoveMapObject(FJavaCircle.hashCode); end; procedure TAndroidMapCircle.SetHostView(MapView: TAndroidBaiduMapViewService); begin FMapView := MapView; end; procedure TAndroidMapCircle.SetJCircle(Circle: JCircle); begin FJavaCircle := Circle; end; procedure TAndroidMapCircle.SetVisible(const Value: Boolean); begin inherited; TUIThreadCaller.InvokeIfNotNil<JCircle>( procedure (C: JCircle) begin C.setVisible(Value) end, FJavaCircle); end; { TAndroidMapPolygon } destructor TAndroidMapPolygon.Destroy; begin Remove; inherited; end; procedure TAndroidMapPolygon.Remove; begin inherited; TUIThreadCaller.InvokeIfNotNil<JPolygon>( procedure (P: JPolygon) begin P.remove; end, FJavaPolygon); FMapView.RemoveMapObject(FJavaPolygon.hashCode); end; procedure TAndroidMapPolygon.SetHostView(MapView: TAndroidBaiduMapViewService); begin FMapView := MapView; end; procedure TAndroidMapPolygon.SetJPolygon(Polygon: JPolygon); begin FJavaPolygon := Polygon; end; procedure TAndroidMapPolygon.SetVisible(const Value: Boolean); begin inherited; TUIThreadCaller.InvokeIfNotNil<JPolygon>( procedure (P: JPolygon) begin P.setVisible(Value); end, FJavaPolygon); end; { TAndroidMapPolyline } destructor TAndroidMapPolyline.Destroy; begin Remove; inherited; end; procedure TAndroidMapPolyline.Remove; begin inherited; TUIThreadCaller.InvokeIfNotNil<JPolyline>( procedure (P: JPolyline) begin P.remove; end, FJavaPolyline); FMapView.RemoveMapObject(FJavaPolyline.hashCode); end; procedure TAndroidMapPolyline.SetHostView(MapView: TAndroidBaiduMapViewService); begin FMapView := MapView; end; procedure TAndroidMapPolyline.SetJPolyline(Polyline: JPolyline); begin FJavaPolyline := Polyline; end; procedure TAndroidMapPolyline.SetVisible(const Value: Boolean); begin inherited; TUIThreadCaller.InvokeIfNotNil<JPolyline>( procedure (P: JPolyline) begin P.setVisible(Value); end, FJavaPolyline); end; { TOnMapBaseListener } constructor TOnMapBaseListener.Create( MapViewService: TAndroidBaiduMapViewService); begin inherited Create; FViewService:=MapViewService; end; { TOnMapClickListener } procedure TOnMapClickListener.onMapClick(P1: JLatLng); begin if FViewService<>nil then end; function TOnMapClickListener.onMapPoiClick(P1: JMapPoi): Boolean; begin end; { TOnMarkerClickListener } function TOnMarkerClickListener.onMarkerClick(P1: JMarker): Boolean; var hashcode:integer; P:Pointer; Marker:TBaiduMapMarker; begin if (FViewService<>nil) and (P1<>nil) then begin Marker:=FViewService.GetMapObject<TBaiduMapMarker>(P1.hashCode); if Marker<>nil then FViewService.DoMarkerClick(Marker); end; end; { TOnPolylineClickListener } function TOnPolylineClickListener.onPolylineClick(P1: JPolyline): Boolean; begin end; end.
unit rc4; interface type TRC4 = class private fStrKey : string; fBytKeyAry : array[0..255] of byte; fBytCypherAry : array[0..255] of byte; private procedure InitializeCypher; procedure SetKey(pStrKey : string); public function Apply(pStrMessage : string) : string; function toHex(pStrMessage : string) : string; function toBin(pStrMessage : string) : string; public property Key : string read fStrKey write SetKey; end; implementation // TRC4 procedure TRC4.InitializeCypher; var lBytJump : integer; lBytIndex : integer; lBytTemp : byte; begin // init the array with the a[i]=i for lBytIndex := 0 To 255 do fBytCypherAry[lBytIndex] := lBytIndex; // Switch values of Cypher arround based off of index and Key value lBytJump := 0; for lBytIndex := 0 to 255 do begin // Figure index To switch lBytJump := (lBytJump + fBytCypherAry[lBytIndex] + fBytKeyAry[lBytIndex]) mod 256; // Do the switch lBytTemp := fBytCypherAry[lBytIndex]; fBytCypherAry[lBytIndex] := fBytCypherAry[lBytJump]; fBytCypherAry[lBytJump] := lBytTemp; end; end; procedure TRC4.SetKey(pStrKey : string); var lLngKeyLength : integer; lLngIndex : integer; begin // if the key is diff and not empty, change it if (pStrKey <> '') and (pStrKey <> fStrKey) then begin fStrKey := pStrKey; lLngKeyLength := Length(pStrKey); // spread the key all over the array for lLngIndex := 0 To 255 do fBytKeyAry[lLngIndex] := byte(pStrKey[lLngIndex mod lLngKeyLength]); end; end; function TRC4.Apply(pStrMessage : string) : string; var lBytIndex : integer; lBytJump : integer; lBytTemp : byte; lBytY : byte; lLngT : integer; lLngX : integer; len : integer; begin len := length(pStrMessage); if (len > 0) and (fStrKey <> '') then begin SetLength(result, len); InitializeCypher; lBytIndex := 0; lBytJump := 0; for lLngX := 1 To len do begin lBytIndex := (lBytIndex + 1) mod 256; // wrap index lBytJump := (lBytJump + fBytCypherAry[lBytIndex]) mod 256; // ' wrap J+S() // Add/Wrap those two lLngT := (fBytCypherAry[lBytIndex] + fBytCypherAry[lBytJump]) mod 256; // Switcheroo lBytTemp := fBytCypherAry[lBytIndex]; fBytCypherAry[lBytIndex] := fBytCypherAry[lBytJump]; fBytCypherAry[lBytJump] := lBytTemp; lBytY := fBytCypherAry[lLngT]; // Character Encryption ... result[lLngX] := char(byte(pStrMessage[lLngX]) xor lBytY); end; end else result := pStrMessage; end; function TRC4.toHex(pStrMessage : string) : string; const HEX_DIGITS : array[0..15] of char = '0123456789ABCDEF'; var len : integer; i : integer; tmp : byte; begin len := Length(pStrMessage); if pStrMessage <> '' then begin SetLength(result, 2*len); for i := 1 to len do begin tmp := byte(pStrMessage[i]); result[2*i-1] := HEX_DIGITS[(tmp and $0F)]; result[2*i] := HEX_DIGITS[(tmp and $F0) shr 4]; end; end else result := ''; end; function TRC4.toBin(pStrMessage : string) : string; function htoi(l, h : char) : char; var l1 : byte; h1 : byte; begin l1 := ord(l); if l1 >= ord('A') then l1 := 10 + l1 - ord('A') else l1 := l1 - ord('0'); h1 := ord(h); if h1 >= ord('A') then h1 := 10 + h1 - ord('A') else h1 := h1 - ord('0'); result := char(byte(l1) or (byte(h1) shl 4)); end; var len : integer; i : integer; begin len := Length(pStrMessage); if (len > 0) and (len mod 2 = 0) then begin SetLength(result, len div 2); for i := 1 to len div 2 do result[i] := htoi(pStrMessage[2*i-1], pStrMessage[2*i]); end else result := ''; end; end.
program exFunction; var a, b : string; c, d : integer; (*function definition *) function max(num1, num2: integer): integer; var (* local variable declaration *) result: integer; begin if (num1 > num2) then result := num1 else result := num2; max := result; end; begin a := 'letra a'; b := 'letra b'; c := 100; d := 200; min(c, d); { a função min não existe } end.
unit HGM.WinAPI.ShellDlg; interface uses Vcl.Dialogs, System.UITypes; function AskYesNo(aCaption, aQuestion:string):Boolean; implementation function AskYesNo(aCaption, aQuestion:string):Boolean; begin Result:=False; with TTaskDialog.Create(nil) do begin Caption:=aCaption; CommonButtons:=[tcbYes, tcbNo]; DefaultButton:=tcbYes; Flags:=[tfUseHiconMain, tfAllowDialogCancellation, tfUseCommandLinksNoIcon]; MainIcon:=0; Title:=aQuestion; try if Execute then Result:=ModalResult = idYes else Result:=False; finally Free; end; end; end; end.
unit Unit_Principal; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Menus, Unit_Persistencia, Unit_Clientes, Unit_Produtos, Unit_Supermercado, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls, Vcl.Mask, Unit_Fornecedor, Unit_Caixa, Unit_ContasReceber, Unit_ContasPagar; type TSuperMercadoDEF = class(TForm) MenuPrincipal: TMainMenu; Clientes: TMenuItem; Cadastro: TMenuItem; Fornecedores: TMenuItem; Produtos: TMenuItem; PanelPrincipal: TPanel; PanelPrincipalInferior: TPanel; btn_Fechar: TBitBtn; BitBtn1: TBitBtn; label_NomeFantasia: TLabel; label_RazaoSocial: TLabel; label_InscricaoEstadual: TLabel; label_CNPJ: TLabel; label_Endereco: TLabel; label_Telefone: TLabel; label_Email: TLabel; label_NomeResponsavel: TLabel; label_TelefoneResponsavel: TLabel; label_Lucro: TLabel; ransaesFiscais1: TMenuItem; SaidadeProdutosvenda1: TMenuItem; ContasaReceber1: TMenuItem; Caixa1: TMenuItem; ContasaPagar1: TMenuItem; EntradadeProdutos1: TMenuItem; BussinessIntelligence1: TMenuItem; Relatrios1: TMenuItem; Grficos1: TMenuItem; procedure ClientesClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure BitBtn1Click(Sender: TObject); procedure btn_FecharClick(Sender: TObject); procedure ProdutosClick(Sender: TObject); procedure FornecedoresClick(Sender: TObject); procedure SaidadeProdutosvenda1Click(Sender: TObject); procedure Caixa1Click(Sender: TObject); procedure ContasaReceber1Click(Sender: TObject); procedure ContasaPagar1Click(Sender: TObject); procedure EntradadeProdutos1Click(Sender: TObject); procedure Relatrios1Click(Sender: TObject); procedure Grficos1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var SuperMercadoDEF: TSuperMercadoDEF; implementation {$R *.dfm} uses Unit_Venda, Unit_Compra, Unit_Relatorio, Unit_Grafico; procedure TSuperMercadoDEF.BitBtn1Click(Sender: TObject); begin Application.CreateForm(Tfrm_Supermercado, frm_Supermercado); frm_Supermercado.ShowModal; frm_Supermercado.Destroy; end; procedure TSuperMercadoDEF.btn_FecharClick(Sender: TObject); begin Application.Terminate; end; procedure TSuperMercadoDEF.Caixa1Click(Sender: TObject); begin Application.CreateForm(Tfrm_Caixa, frm_Caixa); frm_Caixa.ShowModal; frm_Caixa.Destroy; end; procedure TSuperMercadoDEF.ClientesClick(Sender: TObject); begin Application.CreateForm(Tfrm_Clientes, frm_Clientes); frm_Clientes.ShowModal; frm_Clientes.Destroy; end; procedure TSuperMercadoDEF.ContasaPagar1Click(Sender: TObject); begin Application.CreateForm(Tfrm_ContasPagar, frm_ContasPagar); frm_ContasPagar.ShowModal; frm_ContasPagar.Destroy; end; procedure TSuperMercadoDEF.ContasaReceber1Click(Sender: TObject); begin Application.CreateForm(Tfrm_ContasReceber, frm_ContasReceber); frm_ContasReceber.ShowModal; frm_ContasReceber.Destroy; end; procedure TSuperMercadoDEF.EntradadeProdutos1Click(Sender: TObject); begin Application.CreateForm(Tfrm_Compra, frm_Compra); frm_Compra.ShowModal; frm_Compra.Destroy; end; procedure TSuperMercadoDEF.FormCreate(Sender: TObject); var Temp : Dados_Supermercado; begin try Temp := Recupera_Dados_Supermercado; label_NomeFantasia.Caption := Temp.Sup_NomeFantasia; label_RazaoSocial.Caption := Temp.Sup_RazaoSocial; label_InscricaoEstadual.Caption := Temp.sup_InscricaoEstadual; label_CNPJ.Caption := Temp.sup_CNPJ; label_Endereco.Caption := Temp.sup_Endereco; label_Lucro.Caption := Temp.sup_Lucro; label_Telefone.Caption := Temp.sup_Telefone; label_Email.Caption := Temp.sup_Email; label_NomeResponsavel.Caption := Temp.sup_NomeResponsavel; label_TelefoneResponsavel.Caption := Temp.Sup_TelefoneResponsavel; except End; // label_NomeFantasia.Caption := Temp.Sup_NomeFantasia; end; procedure TSuperMercadoDEF.FornecedoresClick(Sender: TObject); begin Application.CreateForm(Tfrm_Fornecedores, frm_Fornecedores); frm_Fornecedores.ShowModal; frm_Fornecedores.Destroy; end; procedure TSuperMercadoDEF.Grficos1Click(Sender: TObject); begin Application.CreateForm(Tfrm_Grafico, frm_Grafico); frm_Grafico.ShowModal; frm_Grafico.Destroy; end; procedure TSuperMercadoDEF.ProdutosClick(Sender: TObject); begin Application.CreateForm(Tfrm_Produtos, frm_Produtos); frm_Produtos.ShowModal; frm_Produtos.Destroy; end; procedure TSuperMercadoDEF.Relatrios1Click(Sender: TObject); begin Application.CreateForm(Tfrm_Relatorio, frm_Relatorio); frm_Relatorio.ShowModal; frm_Relatorio.Destroy; end; procedure TSuperMercadoDEF.SaidadeProdutosvenda1Click(Sender: TObject); begin Application.CreateForm(Tfrm_Venda, frm_Venda); frm_Venda.ShowModal; frm_Venda.Destroy; end; end.
unit Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.Generics.Collections, Quick.Commons, Quick.Config.YAML; type TMyPriority = (msLow, msMed, msHigh); TWinPos = class private fPosX : Integer; fPosY : Integer; fFixed : Boolean; published property PosX : Integer read fPosX write fPosX; property PosY : Integer read fPosY write fPosY; property Fixed : Boolean read fFixed write fFixed; end; TProcessType = record Id : Integer; Priority : TMyPriority; Redundant : Boolean; end; TJob = class private fJobName : string; fTimeElapsed : Integer; published property JobName : string read fJobName write fJobName; property TimeElapsed : Integer read fTimeElapsed write fTimeElapsed; end; TWorker = class private fName : string; fJob : TJob; fLevels : TArray<Integer>; fActive : Boolean; published property Name : string read fName write fName; property Job : TJob read fJob write fJob; property Levels : TArray<Integer> read fLevels write fLevels; property Active : Boolean read fActive write fActive; public constructor Create; destructor Destroy; override; end; TMyConfig = class(TAppConfigYAML) private fTitle : string; fHidden : Boolean; fSessionName: string; fSizes : TArray<Integer>; fMethods : TArray<string>; fLastFilename : string; fWindowPos : TWinPos; fHistory : TArray<TProcessType>; fComplex : TProcessType; fDefaultWorker : TWorker; fModifyDate : TDateTime; fWorkList : TObjectList<TWorker>; published [TCommentProperty('Sizes array is simple')] property Sizes : TArray<Integer> read fSizes write fSizes; property LastFilename : string read fLastFilename write fLastFilename; property Methods : TArray<string> read fMethods write fMethods; property WindowPos : TWinPos read fWindowPos write fWindowPos; [TCommentProperty('Array of records')] property History : TArray<TProcessType> read fHistory write fHistory; property Complex : TProcessType read fComplex write fComplex; property DefaultWorker : TWorker read fDefaultWorker write fDefaultWorker; property ModifyDate : TDateTime read fModifyDate write fModifyDate; property Title : string read fTitle write fTitle; property SessionName : string read fSessionName write fSessionName; [TCommentProperty('List of work tasks config')] property WorkList : TObjectList<TWorker> read fWorkList write fWorkList; public destructor Destroy; override; procedure Init; override; procedure DefaultValues; override; end; TMainForm = class(TForm) meInfo: TMemo; btnLoadFile: TButton; btnSaveFile: TButton; procedure FormCreate(Sender: TObject); procedure btnSaveFileClick(Sender: TObject); procedure btnLoadFileClick(Sender: TObject); procedure SetConfig(cConfig: TMyConfig); function TestConfig(cConfig1, cConfig2 : TMyConfig) : Boolean; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure OnFileModified; end; var MainForm: TMainForm; ConfigTest : TMyConfig; ConfigYaml : TMyConfig; implementation {$R *.dfm} procedure TMainForm.btnLoadFileClick(Sender: TObject); var sl : TStringList; s : string; begin meInfo.Lines.Add('Load ConfigReg'); ConfigYaml.Load; meInfo.Lines.Add(ConfigYaml.ToYAML); if TestConfig(configtest,ConfigYaml) then meInfo.Lines.Add('Test passed successfully!'); end; procedure TMainForm.btnSaveFileClick(Sender: TObject); begin ConfigYaml.Free; ConfigYaml := TMyConfig.Create('.\config.yml'); SetConfig(ConfigYaml); ConfigYaml.Save; meInfo.Lines.Add('Saved Config in Yaml at ' + DateTimeToStr(ConfigYaml.LastSaved)); end; procedure TMainForm.SetConfig(cConfig : TMyConfig); var winpos : TWinpos; protype : TProcessType; i : Integer; worker : TWorker; begin cConfig.LastFilename := 'library.txt'; cConfig.Sizes := [23,11,554,12,34,29,77,30,48,59,773,221,98,3,22,983,122,231,433,12,31,987]; cConfig.DefaultWorker.Levels := [10,12,14,18,20]; cConfig.WindowPos.PosX := 640; cConfig.WindowPos.PosX := 480; cConfig.WindowPos.Fixed := True; cConfig.Methods := ['GET','POST','PUT','DELETE','HEAD']; protype.Id := 5; protype.Priority := msHigh; protype.Redundant := False; cConfig.Complex := protype; cConfig.DefaultWorker.Name := 'Process ' + i.ToString; cConfig.DefaultWorker.Job.JobName := 'Job ' + i.ToString; cConfig.DefaultWorker.Job.TimeElapsed := i * Random(1000); cConfig.DefaultWorker.Active := Boolean(Random(1)); cConfig.Title := 'a fresh title'; cConfig.SessionName := 'First Session'; for I := 0 to 5 do begin worker := TWorker.Create; worker.Name := 'Process ' + i.ToString; worker.Levels := [10,12,14,18,20]; worker.Job.JobName := 'Job ' + i.ToString; worker.Job.TimeElapsed := i * Random(1000); worker.Active := Boolean(Random(1)); cConfig.WorkList.Add(worker); end; for i := 0 to 2 do begin protype.Id := i; protype.Priority := msLow; protype.Redundant := True; cConfig.History := cConfig.History + [protype]; end; cConfig.ModifyDate := Now(); end; function TMainForm.TestConfig(cConfig1, cConfig2 : TMyConfig) : Boolean; var i : Integer; begin Result := False; try Assert(cConfig1.LastFilename = cConfig2.LastFilename); for i := Low(cConfig1.Sizes) to High(cConfig1.Sizes) do Assert(cConfig1.Sizes[i] = cConfig2.Sizes[i]); Assert(cConfig1.WindowPos.PosX = cConfig2.WindowPos.PosX); Assert(cConfig1.WindowPos.PosX = cConfig2.WindowPos.PosX); Assert(cConfig1.Complex.Priority = cConfig2.Complex.Priority); Assert(cConfig1.Complex.Redundant = cConfig2.Complex.Redundant); Assert(cConfig1.Title = cConfig2.Title); Assert(cConfig1.WorkList.Count = cConfig2.WorkList.Count); for i := 0 to cConfig1.WorkList.Count - 1 do begin Assert(cConfig1.WorkList[i].Name = cConfig2.WorkList[i].Name); Assert(cConfig1.WorkList[i].Active = cConfig2.WorkList[i].Active); end; for i := 0 to High(cConfig1.History) do begin Assert(cConfig1.History[i].Priority = cConfig2.History[i].Priority); Assert(cConfig1.History[i].Redundant = cConfig2.History[i].Redundant); end; Result := True; except ShowMessage('Configuration not has been saved previously or has a corruption problem'); end; end; procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction); begin if Assigned(ConfigYaml) then ConfigYaml.Free; if Assigned(ConfigTest) then ConfigTest.Free; end; procedure TMainForm.FormCreate(Sender: TObject); begin ConfigYaml := TMyConfig.Create('.\config.yml'); ConfigYaml.Provider.OnFileModified := OnFileModified; ConfigYaml.Provider.ReloadIfFileChanged := False; //create config test to compare later ConfigTest := TMyConfig.Create(''); SetConfig(ConfigTest); end; procedure TMainForm.OnFileModified; begin meInfo.Lines.Add('Config file modified. Config will be reload'); end; { TMyConfig } procedure TMyConfig.Init; begin inherited; fWorkList := TObjectList<TWorker>.Create(True); fWindowPos := TWinPos.Create; fDefaultWorker := TWorker.Create; DefaultValues; end; procedure TMyConfig.DefaultValues; begin inherited; fTitle := 'Default value'; end; destructor TMyConfig.Destroy; begin if Assigned(fWorkList) then fWorkList.Free; if Assigned(fDefaultWorker) then fDefaultWorker.Free; if Assigned(fWindowPos) then fWindowPos.Free; inherited; end; { TWorker } constructor TWorker.Create; begin fJob := TJob.Create; end; destructor TWorker.Destroy; begin fJob.Free; inherited; end; end.
unit TurnOffTimeMachine_Form; //////////////////////////////////////////////////////////////////////////////// // Библиотека : Проект Немезис. // Назначение : Диалог выключения машины времени. // Версия : $Id: TurnOffTimeMachine_Form.pas,v 1.5 2013/05/15 14:31:43 morozov Exp $ //////////////////////////////////////////////////////////////////////////////// interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Mask, ExtCtrls, vtCombo, vtDateEdit, vtLabel, vtRadioButton, vcmInterfaces, vcmBase, vcmEntityForm, vcmEntities, vcmComponent, vcmBaseEntities, l3InterfacedComponent, PresentationInterfaces, PrimTurnOffTimeMachine_Form, PrimTurnOffTimeMachineOptions_Form, eeButton, vtButton ; type Ten_TurnOffTimeMachine = class(TvcmEntityFormRef) Entities : TvcmEntities; pbDialogIcon: TPaintBox; lblTurnOnTimeMachineInfo: TvtLabel; rb_totmChangeDate: TvtRadioButton; rb_totmStayInCurrentRedaction: TvtRadioButton; btnOk: TvtButton; btnCancel: TvtButton; deChangeDate: TvtDblClickDateEdit; rb_totmGotoActualRedaction: TvtRadioButton; procedure btnOkClick(Sender: TObject); procedure deChangeDateChange(Sender: TObject); procedure pbDialogIconPaint(Sender: TObject); procedure vcmEntityFormRefCreate(Sender: TObject); procedure vcmEntityFormRefShow(Sender: TObject); end; implementation uses vcmForm, vcmExternalInterfaces, DataAdapter, bsConvert, nsConst, StdRes ; {$R *.DFM} procedure Ten_TurnOffTimeMachine.btnOkClick(Sender: TObject); begin DoOk; end; procedure Ten_TurnOffTimeMachine.deChangeDateChange(Sender: TObject); begin rb_totmChangeDate.Checked := True; end; procedure Ten_TurnOffTimeMachine.pbDialogIconPaint(Sender: TObject); begin with Sender as TPaintBox do dmStdRes.LargeImageList.Draw(Canvas, Width - c_LargeSizeIcon, (Height - c_LargeSizeIcon) div 2, cTimeMachineOff); end; procedure Ten_TurnOffTimeMachine.vcmEntityFormRefCreate(Sender: TObject); begin rb_totmChangeDate.Font.Charset := RUSSIAN_CHARSET; rb_totmStayInCurrentRedaction.Font.Charset := RUSSIAN_CHARSET; end; procedure Ten_TurnOffTimeMachine.vcmEntityFormRefShow(Sender: TObject); //http://mdp.garant.ru/pages/viewpage.action?pageId=449678181 begin rb_totmGotoActualRedaction.Top := lblTurnOnTimeMachineInfo.Top + lblTurnOnTimeMachineInfo.Height + 15; rb_totmStayInCurrentRedaction.Top := rb_totmGotoActualRedaction.Top + rb_totmGotoActualRedaction.Height + 12; rb_totmChangeDate.Top := rb_totmStayInCurrentRedaction.Top + rb_totmStayInCurrentRedaction.Height + 12; deChangeDate.Top := rb_totmChangeDate.Top + rb_totmChangeDate.Height + 7; btnOk.Top := deChangeDate.Top + deChangeDate.Height + 19; btnCancel.Top := btnOk.Top; Self.ClientHeight := btnOk.Top + btnOk.Height + 17; end; end.
program TM1638_sample; uses RaspberryPi, GlobalConfig, GlobalConst, GlobalTypes, Platform, Threads, SysUtils, Classes, Ultibo, Console, TM1638; var TM1630Ac: TTM1630; Handle: TWindowHandle; procedure Setup(); begin {Let's create a console window again but this time on the left side of the screen} Handle := ConsoleWindowCreate(ConsoleDeviceGetDefault, CONSOLE_POSITION_FULL, True); {To prove that worked let's output some text on the console window} ConsoleWindowWriteLn(Handle, 'TM1638 sample'); try TM1630Ac := TTM1630.Create; except on E: Exception do begin TM1630Ac := nil; ConsoleWindowWriteLn(Handle, 'Setup() error: ' + E.Message); end; end; end; procedure Loop(); var i: Byte; begin try i := 0; while i <= 15 do begin TM1630Ac.Start(); TM1630Ac.ShiftOut(soLsbFirst, $C1 + i); // led on TM1630Ac.ShiftOut(soLsbFirst, 1); TM1630Ac.Stop(); Sleep(100); TM1630Ac.Start(); TM1630Ac.ShiftOut(soLsbFirst, $C1 + i); // led off TM1630Ac.ShiftOut(soLsbFirst, 0); TM1630Ac.Stop(); Sleep(10); Inc(i, 2); end; except on E: Exception do begin TM1630Ac.Free; TM1630Ac := nil; ConsoleWindowWriteLn(Handle, 'Loop() error: ' + E.Message); end; end; end; begin Setup(); while Assigned(TM1630Ac) do Loop(); ConsoleWindowWriteLn(Handle, ''); ConsoleWindowWriteLn(Handle, 'Bye'); {Halt the main thread if we ever get to here} ThreadHalt(0); end.
unit WPTBarConfig; { ----------------------------------------------------------------------------- Copyright (C) 2002-2015 by wpcubed GmbH - Author: Julian Ziersch info: http://www.wptools.de mailto:support@wptools.de __ __ ___ _____ _ _____ / / /\ \ \/ _ \/__ \___ ___ | |___ |___ | \ \/ \/ / /_)/ / /\/ _ \ / _ \| / __| / / \ /\ / ___/ / / | (_) | (_) | \__ \ / / \/ \/\/ \/ \___/ \___/|_|___/ /_/ ***************************************************************************** * WPRTEDefs - WPTools 7 RTF Engine Data Structures and the basic RTFEngine * This unit contains all important objects and helper classes ----------------------------------------------------------------------------- THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. ----------------------------------------------------------------------------- } // call WPToolbarConfigurate to configure the toolbar // WPToolbarConfigurate( WPToolbar1, Self, 'Configure Toolbar' ); interface {$I WPINC.INC} uses {$IFDEF DELPHIXE} Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Types, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Buttons, Vcl.StdCtrls, Vcl.ExtCtrls, VCL.ActnList, {$ELSE} Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Buttons, StdCtrls, ExtCtrls, {$ENDIF} WPRTEDEFS, WPUtil, WPCtrRich, WPCtrMemo, WPActnStr, WPTbar, WPRTEDefsConsts ; type TWPToolbarConfiguration = class(TWPShadedForm) Panel1: TPanel; PanelBottom: TPanel; Button1: TButton; Button2: TButton; SelectedList: TListBox; AllList: TListBox; AddOne: TButton; DelOne: TButton; AddAll: TButton; DelAll: TButton; AddSpace: TButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure AllListDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); procedure AddOneClick(Sender: TObject); procedure AddAllClick(Sender: TObject); procedure DelAllClick(Sender: TObject); procedure DelOneClick(Sender: TObject); procedure SelectedListClick(Sender: TObject); procedure AllListClick(Sender: TObject); procedure SelectedListDragDrop(Sender, Source: TObject; X, Y: Integer); procedure SelectedListMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure SelectedListDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure AddSpaceClick(Sender: TObject); private procedure Apply; public AllIcons: TStringList; WPToolbar: TWPToolBar; StartingPoint: TPoint; SortCombosFirst: Boolean; end; {:: Use this procedure to show the configuration dialog of the TWPToolbar. Please note that the toolbar will be automaticlly switched to use the ConfigString and not the selection sets. <example> WPToolbarConfigurate( WPToolbar1, Self, 'Configure Toolbar' ); </example> } function WPToolbarConfigurate(Source: TWPToolBar; ParentForm: TForm; Caption: String = ''): Boolean; implementation {$R *.dfm} function WPToolbarConfigurate(Source: TWPToolBar; ParentForm: TForm; Caption: String = ''): Boolean; var dia: TWPToolbarConfiguration; oldconfig, s: String; oldShowAllElements: TWPToolBarShowAllElements; i, h: Integer; bDoNotUseString : Boolean; begin dia := TWPToolbarConfiguration.Create(ParentForm); try WPMakeToolbarIconList(dia.AllIcons, Source.ActionList); dia.WPToolbar := Source; dia.SelectedList.Items.Clear; dia.AllList.Items.Assign(dia.AllIcons); dia.Caption := Caption; if Source.ButtonHeight > 22 then begin dia.AllList.ItemHeight := Source.ButtonHeight + 8; dia.SelectedList.ItemHeight := Source.ButtonHeight + 8; end; oldShowAllElements := Source.ShowAllElements; bDoNotUseString := false; h := Source.Height; s := ''; Result := False; oldconfig := Source.ConfigString; if (Source.ConfigString = '') or (Source.ShowAllElements <> wpSelectedElements) then begin //Source.BeginUpdate; oldconfig := Source._AutoConfigString; Source.ConfigString := oldconfig; // ';'; Source.ShowAllElements := wpSelectedElements; bDoNotUseString := true; //Source.EndUpdate; end; i := 1; while i<=Length(oldconfig) do begin if (oldconfig[i]='|') or (oldconfig[i]='-') then begin dia.SelectedList.Items.Add('|'); end else if oldconfig[i]='[' then begin inc(i); s := ''; while (i<=Length(oldconfig)) and (oldconfig[i]<>']') do begin s := s + oldconfig[i]; inc(i); end; dia.SelectedList.Items.Add('[' + s + ']'); s := ''; end else begin if (oldconfig[i] > #32) and (oldconfig[i] <> ';') and (oldconfig[i] <> ']') and (oldconfig[i] <> '[') then s := s + oldconfig[i]; if Length(s) = 2 then begin dia.SelectedList.Items.Add(s); s := ''; end; end; inc(i); end; if dia.ShowModal <> mrOk then begin if bDoNotUseString then Source.ConfigString := '' else Source.ConfigString := oldconfig; Source.Height := h; Source.ShowAllElements := oldShowAllElements; end else Result := true; finally dia.Free; end; end; // Adds the remaining to the end procedure TWPToolbarConfiguration.AddAllClick(Sender: TObject); var i: Integer; begin SelectedList.Items.BeginUpdate; try for i := 0 to AllList.Items.Count - 1 do if SelectedList.Items.IndexOf(AllList.Items[i]) < 0 then SelectedList.Items.Add(AllList.Items[i]); finally SelectedList.Items.EndUpdate; end; Apply; end; // Add one ore more selected procedure TWPToolbarConfiguration.AddOneClick(Sender: TObject); var i: Integer; begin SelectedList.Items.BeginUpdate; try for i := 0 to AllList.Items.Count - 1 do if AllList.Selected[i] and (SelectedList.Items.IndexOf(AllList.Items[i]) < 0) then SelectedList.Items.Add(AllList.Items[i]); finally SelectedList.Items.EndUpdate; end; Apply; end; procedure TWPToolbarConfiguration.AddSpaceClick(Sender: TObject); var i : Integer; begin SelectedList.Items.BeginUpdate; try for i := SelectedList.Items.Count - 1 downto 0 do if SelectedList.Selected[i] then begin SelectedList.Items.Insert(i+1, '|'); end; finally SelectedList.Items.EndUpdate; end; Apply; end; procedure TWPToolbarConfiguration.DelAllClick(Sender: TObject); begin SelectedList.Items.Clear; Apply; end; procedure TWPToolbarConfiguration.DelOneClick(Sender: TObject); var i: Integer; begin for i := SelectedList.Items.Count - 1 downto 0 do if SelectedList.Selected[i] then SelectedList.Items.Delete(i); Apply; end; procedure TWPToolbarConfiguration.AllListClick(Sender: TObject); begin AddOne.Enabled := AllList.SelCount > 0; end; procedure TWPToolbarConfiguration.AllListDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); var s: String; i: Integer; bit: TBitmap; rec: TWPMakeToolbarIconListRec; pic: TWPImageListItem; Caption, Hint: string; begin s := (Control as TListBox).Items[Index]; i := AllIcons.IndexOf(s); if s = '|' then begin i := TListBox(Control).Canvas.Pen.Width; TListBox(Control).Canvas.FillRect(Rect); TListBox(Control).Canvas.Pen.Width := 3; TListBox(Control).Canvas.MoveTo(Rect.Left+2, (Rect.Top+Rect.Bottom) div 2); TListBox(Control).Canvas.LineTo(Rect.Right-2, (Rect.Top+Rect.Bottom) div 2); TListBox(Control).Canvas.Pen.Width := i; end else if i >= 0 then begin rec := TWPMakeToolbarIconListRec(AllIcons.Objects[i]); if rec <> nil then begin WPGetActionHintCap(rec.Group,rec.Command,Caption, Hint); if Copy(rec.ID, 1, 1) = '[' then begin if rec.Action = nil then begin TListBox(Control).Canvas.Pen.Color := clRed; TListBox(Control).Canvas.Rectangle(Rect); TListBox(Control).Canvas.TextOut(Rect.Left + 16, Rect.Top + 2, rec.ID); end else begin TListBox(Control).Canvas.FillRect(Rect); if (rec.Action.ActionList.Images <> nil) then rec.Action.ActionList.Images.Draw(TListBox(Control).Canvas, Rect.Left + 2, Rect.Top, rec.Action.ImageIndex); TListBox(Control).Canvas.Brush.Style := bsClear; TListBox(Control).Canvas.Pen.Color := clBtnFace; TListBox(Control).Canvas.TextOut(Rect.Left + 40, Rect.Top + 2, rec.Action.Caption); TListBox(Control).Canvas.Rectangle(Rect); end; end else if Copy(rec.ID, 1, 1) = '1' then begin TListBox(Control).Canvas.Pen.Color := clBlack; TListBox(Control).Canvas.Rectangle(Rect); TListBox(Control).Canvas.TextOut(Rect.Left + 16, Rect.Top + 2, rec.ImageName); end else begin TListBox(Control).Canvas.FillRect(Rect); if (WPToolbar <> nil) and (WPToolbar.WPImageList <> nil) then pic := WPToolbar.WPImageList.GetImage(WPToolbar.ButtonHeight, WPToolbar.ButtonHeight, False, False, False) else pic := nil; if pic <> nil then begin WPCopyRectFromImageList(TListBox(Control).Canvas, Rect.Left + 2, Rect.Top + 2, WPToolbar.ButtonHeight, WPToolbar.ButtonHeight, pic, rec.IconNr, False, False); if Caption='' then TListBox(Control).Canvas.TextOut(Rect.Left + 32, Rect.Top + 2, rec.ImageName); end else begin bit := WPGetImageBitmapForIconName(rec.ImageName); if bit = nil then TListBox(Control).Canvas.TextOut(Rect.Left + 16, Rect.Top + 2, rec.ID + '=' + rec.ImageName) else begin // This sometimes does not draw anything - use TransparentBlt instead // TListBox(Control).Canvas.Draw(Rect.Left + 4, Rect.Top + 4, bit); {$IFNDEF DELPHI6ANDUP} TListBox(Control).Canvas.CopyRect( {$IFDEF DELPHIXE}System.{$ENDIF}Classes.Rect( Rect.Left + 4, Rect.Top + 4, Rect.Left + 4+bit.Height, Rect.Top + 4+bit.Height ), bit.Canvas, {$IFDEF DELPHIXE}System.{$ENDIF}Classes.Rect(0,0,bit.Height,bit.Height)); {$ELSE} if bit.TransparentMode=tmAuto then TListBox(Control).Canvas.CopyRect( {$IFDEF DELPHIXE}System.{$ENDIF}Classes.Rect( Rect.Left + 4, Rect.Top + 4, Rect.Left + 4+bit.Height, Rect.Top + 4+bit.Height ), bit.Canvas, {$IFDEF DELPHIXE}System.{$ENDIF}Classes.Rect(0,0,bit.Height,bit.Height)) else TransparentBlt( TListBox(Control).Canvas.Handle, Rect.Left + 4, Rect.Top + 4, bit.Height, bit.Height, bit.Canvas.Handle, 0,0, bit.Height, bit.Height, bit.TransparentColor); {$ENDIF} end; end; TListBox(Control).Canvas.TextOut(Rect.Left + 40, Rect.Top + 2, Caption); end; end; end; end; procedure TWPToolbarConfiguration.Apply; var i, c: Integer; s: String; done: Boolean; begin c := 0; i := SelectedList.Items.Count - 1; while i >= c do begin s := SelectedList.Items[i]; if SortCombosFirst and (Copy(s, 1, 1) = '1') then begin SelectedList.Items.Move(i, 0); inc(c); end else if s = '' then SelectedList.Items.Delete(i); dec(i); end; if SortCombosFirst then repeat done := true; for i := 0 to c - 2 do if SelectedList.Items[i + 1][2] < SelectedList.Items[i][2] then begin SelectedList.Items.Exchange(i, i + 1); done := False; end; until (done); if WPToolbar <> nil then begin s := ''; for i := 0 to SelectedList.Items.Count - 1 do s := s + SelectedList.Items[i]; if s='' then s := ';'; WPToolbar.ConfigString := s; end; end; procedure TWPToolbarConfiguration.FormCreate(Sender: TObject); begin AllIcons := TStringList.Create; // AllIcons.Duplicates := dupError; AllIcons.Sorted := true; AllList.Items := AllIcons; end; procedure TWPToolbarConfiguration.FormDestroy(Sender: TObject); var i: Integer; begin for i := 0 to AllIcons.Count - 1 do AllIcons.Objects[i].Free; AllIcons.Free; end; procedure TWPToolbarConfiguration.SelectedListClick(Sender: TObject); begin DelOne.Enabled := SelectedList.SelCount > 0; AddSpace.Enabled := SelectedList.SelCount > 0; end; procedure TWPToolbarConfiguration.SelectedListDragDrop(Sender, Source: TObject; X, Y: Integer); var ListBox, DestListbox: TListBox; i, TargetIndex: Integer; SelectedItems: TStringList; begin ListBox := Source as TListBox; DestListbox := Sender as TListBox; TargetIndex := DestListbox.ItemAtPos(Point(X, Y), False); if TargetIndex <> -1 then begin SelectedItems := TStringList.Create; try DestListbox.Items.BeginUpdate; try for i := ListBox.Items.Count - 1 downto 0 do begin if ListBox.Selected[i] then begin SelectedItems.AddObject(ListBox.Items[i], ListBox.Items.Objects[i]); if DestListbox = ListBox then begin ListBox.Items.Delete(i); if i < TargetIndex then dec(TargetIndex); end; end; end; for i := SelectedItems.Count - 1 downto 0 do if (SelectedItems[i]='|') or (DestListbox.Items.IndexOf(SelectedItems[i]) < 0) then // Do not duplicate begin DestListbox.Items.InsertObject(TargetIndex, SelectedItems[i], SelectedItems.Objects[i]); DestListbox.Selected[TargetIndex] := true; inc(TargetIndex); end; finally DestListbox.Items.EndUpdate; end; finally SelectedItems.Free; end; end; Apply; end; procedure TWPToolbarConfiguration.SelectedListDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); begin Accept := true; end; procedure TWPToolbarConfiguration.SelectedListMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin StartingPoint.X := X; StartingPoint.Y := Y; end; end.
unit uServer; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, IdGlobal, IdYarn, Winapi.Winsock2, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IdBaseComponent, IdComponent, IdCustomTCPServer, IdTCPServer, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.WinXCtrls, Vcl.Themes, IdContext, IdScheduler, IdSchedulerOfThread, IdThreadSafe, IdTCPConnection, IdSync; type TMyContext = class(TIdServerContext) public Tag: Integer; Queue: TIdThreadSafeStringList; constructor Create(AConnection: TIdTCPConnection; AYarn: TIdYarn; AList: TIdContextThreadList = nil); override; destructor Destroy; override; end; type TfServer = class(TForm) idtcpsrvr1: TIdTCPServer; edtIP: TLabeledEdit; edtPort: TLabeledEdit; lblVclStyle: TLabel; cbxVclStyles: TComboBox; mmoLog: TMemo; btnListen: TButton; procedure cbxVclStylesChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure idtcpsrvr1Connect(AContext: TIdContext); procedure idtcpsrvr1Exception(AContext: TIdContext; AException: Exception); procedure idtcpsrvr1Disconnect(AContext: TIdContext); procedure idtcpsrvr1Execute(AContext: TIdContext); procedure btnListenClick(Sender: TObject); procedure idtcpsrvr1Status(ASender: TObject; const AStatus: TIdStatus; const AStatusText: string); private { Private declarations } procedure ShowConnectSetSockOpt(); procedure ShowConnectWSAIoctl(); // procedure ShowConnect(tcpID: Cardinal; tcpIP: string; tcpPort: Word); procedure ShowConnect(); procedure ShowDisconnect(); procedure ShowException(); public { Public declarations } end; var fServer: TfServer; implementation uses uPublic; {$R *.dfm} { TMyContext } constructor TMyContext.Create(AConnection: TIdTCPConnection; AYarn: TIdYarn; AList: TIdContextThreadList); begin inherited; Queue := TIdThreadSafeStringList.Create; end; destructor TMyContext.Destroy; begin Queue.Free; inherited; end; { TfServer } procedure TfServer.btnListenClick(Sender: TObject); var p: Word; n: Integer; L: TList; begin if (btnListen.Caption = '关闭') then begin L := idtcpsrvr1.Contexts.LockList; try for n := 0 to L.Count - 1 do begin TIdServerContext(L.Items[n]).Connection.Disconnect; end; finally idtcpsrvr1.Contexts.UnlockList; end; idtcpsrvr1.Active := False; btnListen.Caption := '打开'; end else if (btnListen.Caption = '打开') then begin p := StrToIntDef(edtPort.Text, 0); if not(p > 0) then Exit; idtcpsrvr1.Bindings.Clear; idtcpsrvr1.Bindings.Add.IP := edtIP.Text; idtcpsrvr1.Bindings.Add.Port := p; idtcpsrvr1.Active := True; btnListen.Caption := '关闭'; end; end; procedure TfServer.cbxVclStylesChange(Sender: TObject); begin TStyleManager.SetStyle(cbxVclStyles.Text); end; procedure TfServer.FormCreate(Sender: TObject); var StyleName: string; begin for StyleName in TStyleManager.StyleNames do cbxVclStyles.Items.Add(StyleName); cbxVclStyles.ItemIndex := cbxVclStyles.Items.IndexOf(TStyleManager.ActiveStyle.Name); // idtcpsrvr1.ContextClass := TMyContext; end; procedure TfServer.idtcpsrvr1Connect(AContext: TIdContext); var opt: DWORD; inKlive, outKlive: TTCP_KeepAlive; begin // 这里不能直接操作VCL控件,OnConnect,OnDisConnect,OnException,OnExecute都是在线程里面执行 // 心跳包 AContext.Connection.Socket.Binding -> AContext.Binding opt := 1; if Winapi.Winsock2.setsockopt(AContext.Binding.Handle, SOL_SOCKET, SO_KEEPALIVE, @opt, SizeOf(opt)) <> 0 then begin TIdNotify.NotifyMethod(ShowConnectSetSockOpt); closesocket(AContext.Binding.Handle); end; inKlive.OnOff := 1; inKlive.KeepAliveTime := 1000 * 3; inKlive.KeepAliveInterval := 1000; if Winapi.Winsock2.WSAIoctl(AContext.Binding.Handle, SIO_KEEPALIVE_VALS, @inKlive, SizeOf(inKlive), @outKlive, SizeOf(outKlive), opt, nil, nil) = SOCKET_ERROR then begin TIdNotify.NotifyMethod(ShowConnectWSAIoctl); closesocket(AContext.Binding.Handle); end; // 中文处理 // AContext.Connection.IOHandler.DefStringEncoding := IndyTextEncoding_UTF8(); // TMyContext(AContext).Queue.Clear; // ??idtcpsrvr1.Contexts.LockList.Count也要进行UnLockList,之前调试一直出现问题无法退出程序就是此处原因 TMyContext(AContext).Tag := idtcpsrvr1.Contexts.LockList.Count + 1; try finally idtcpsrvr1.Contexts.UnlockList; end; // // mmoLog.Lines.Add('【' + IntToStr(AContext.Binding.Handle) + '|' + AContext.Binding.PeerIP + ':' + // IntToStr(AContext.Binding.PeerPort) + '】Connect.'); // TIdNotify.NotifyMethod(ShowConnect(AContext.Binding.Handle, AContext.Binding.PeerIP, AContext.Binding.PeerPort)); TIdNotify.NotifyMethod(ShowConnect); end; procedure TfServer.idtcpsrvr1Disconnect(AContext: TIdContext); begin // 这里不能直接操作VCL控件,OnConnect,OnDisConnect,OnException,OnExecute都是在线程里面执行 TMyContext(AContext).Queue.Clear; // 连接断开 // mmoLog.Lines.Add('【' + AContext.Binding.PeerIP + ':' + IntToStr(AContext.Binding.PeerPort) + '】Disconnect.'); TIdNotify.NotifyMethod(ShowDisconnect); end; procedure TfServer.idtcpsrvr1Exception(AContext: TIdContext; AException: Exception); begin // 这里不能直接操作VCL控件,OnConnect,OnDisConnect,OnException,OnExecute都是在线程里面执行 // mmoLog.Lines.Add('客户端' + AContext.Binding.PeerIP + '异常断开'); if AContext.Connection.Connected then AContext.Connection.Disconnect; TIdNotify.NotifyMethod(ShowException); end; procedure TfServer.idtcpsrvr1Execute(AContext: TIdContext); var pIP: string; rcvMsg, sendMsg: AnsiString; pPort: Word; rcvBuff, sendBuff: TIdBytes; rcvLen, sendLen, n: Integer; L, Q: TStringList; MyContext: TMyContext; begin // 这里不能直接操作VCL控件,OnConnect,OnDisConnect,OnException,OnExecute都是在线程里面执行 AContext.Connection.IOHandler.CheckForDataOnSource(10); if not(AContext.Connection.IOHandler.InputBufferIsEmpty()) then begin pIP := AContext.Binding.PeerIP; pPort := AContext.Binding.PeerPort; rcvLen := AContext.Connection.IOHandler.InputBuffer.Size; AContext.Connection.IOHandler.ReadBytes(rcvBuff, rcvLen, False); SetLength(rcvMsg, rcvLen); Move(rcvBuff[0], rcvMsg[1], rcvLen); // L := nil; try MyContext := TMyContext(AContext); Q := MyContext.Queue.Lock; try if (Q.Count > 0) then begin L := TStringList.Create; L.Assign(Q); Q.Clear; end; finally MyContext.Queue.Unlock; end; // mmoLog.Lines.Add(pIP + ':' + IntToStr(pPort) + '>>' + rcvMsg); if L <> nil then begin for n := 0 to Q.Count - 1 do begin // AContext.Connection.IOHandler.Write(Q.Strings[n]); end; end; // 处理数据 // sendMsg := ProcessAbnormal(True, rcvMsg); sendMsg := rcvMsg; // 发送结果 sendLen := Length(sendMsg); SetLength(sendBuff, sendLen); Move(sendMsg[1], sendBuff[0], sendLen); AContext.Connection.IOHandler.Write(sendBuff, sendLen); mmoLog.Lines.Add('TCP发送数据:' + sendMsg); finally L.Free; end; end; end; procedure TfServer.idtcpsrvr1Status(ASender: TObject; const AStatus: TIdStatus; const AStatusText: string); begin end; // procedure TfServer.ShowConnect(tcpID: Cardinal; tcpIP: string; tcpPort: Word); procedure TfServer.ShowConnect; begin // mmoLog.Lines.Add('【' + IntToStr(tcpID) + '|' + tcpIP + ':' + IntToStr(tcpPort) + '】Connect.'); mmoLog.Lines.Add(yyyyMMddHHmmss + 'Connect.'); end; procedure TfServer.ShowConnectSetSockOpt; begin mmoLog.Lines.Add(yyyyMMddHHmmss + 'setsockopt KeepAlive Error!'); end; procedure TfServer.ShowConnectWSAIoctl; begin mmoLog.Lines.Add(yyyyMMddHHmmss + 'WSAIoctl KeepAlive Error!'); end; procedure TfServer.ShowDisconnect; begin mmoLog.Lines.Add(yyyyMMddHHmmss + 'Disconnect.'); end; procedure TfServer.ShowException; begin mmoLog.Lines.Add(yyyyMMddHHmmss + 'Exception.'); end; end.
{ GDAX/Coinbase-Pro client library tester Copyright (c) 2018 mr-highball Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. } unit test; {$MODE DELPHI} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ComCtrls, StdCtrls, ExtCtrls, Grids, gdax.api.types, gdax.api.authenticator, gdax.api.accounts, gdax.api.orders, gdax.api.consts, gdax.api.ticker, gdax.api.book, gdax.api.candles; type { TGDAXTester } TGDAXTester = class(TForm) arrow_fills_back: TShape; arrow_fills_forward: TShape; btn_auth_test: TButton; btn_base_web_test: TButton; btn_product_test: TButton; btn_accounts_test: TButton; btn_test_fills: TButton; btn_test_order: TButton; btn_test_ledger: TButton; chk_order_stop: TCheckBox; chk_auth_time: TCheckBox; chk_order_post: TCheckBox; chk_sandbox: TCheckBox; combo_ledger_accounts: TComboBox; combo_fills_products: TComboBox; combo_order_type: TComboBox; combo_order_ids: TComboBox; combo_order_side: TComboBox; edit_order_price: TEdit; edit_order_size: TEdit; edit_auth_key: TLabeledEdit; edit_auth_secret: TLabeledEdit; edit_auth_pass: TLabeledEdit; edit_product_quote: TLabeledEdit; lbl_fills_total: TLabel; lbl_fills_total_size: TLabel; lbl_fills_total_price: TLabel; lbl_fills_total_fees: TLabel; lbl_ledger_count: TLabel; lbl_ledger_ids: TLabel; lbl_fills_prods: TLabel; list_ledger: TListBox; list_fills: TListBox; list_products: TListBox; memo_order_output: TMemo; memo_base_web: TMemo; memo_auth_result: TMemo; pctrl_main: TPageControl; grid_accounts: TStringGrid; arrow_ledger_forward: TShape; arrow_ledger_back: TShape; ts_fills: TTabSheet; ts_ledger: TTabSheet; ts_order: TTabSheet; ts_accounts: TTabSheet; ts_products: TTabSheet; ts_fpc_web: TTabSheet; ts_auth: TTabSheet; procedure btn_accounts_testClick(Sender: TObject); procedure btn_auth_testClick(Sender: TObject); procedure btn_base_web_testClick(Sender: TObject); procedure btn_product_testClick(Sender: TObject); procedure btn_test_fillsClick(Sender: TObject); procedure btn_test_ledgerClick(Sender: TObject); procedure btn_test_orderClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure pctrl_mainChange(Sender: TObject); procedure ts_fillsShow(Sender: TObject); private FAuthenticator:IGDAXAuthenticator; FAccountsLoaded:Boolean; FFillsLoaded:Boolean; FLedger:IGDAXAccountLedger; FFills:IGDAXFills; procedure LedgerMoveForward(Sender:TObject); procedure LedgerMoveBack(Sender:TObject); procedure FillsMoveForward(Sender:TObject); procedure FillsMoveBack(Sender:TObject); procedure InitAuthenticator; procedure InitOrderTab; procedure InitLedgerTab; procedure InitFillsTab; function TestTimeEndpoint:String; function TestProducts(Const AQuoteCurrencyFilter:String):IGDAXProducts; function TestAccounts:IGDAXAccounts; function TestOrder(Const AProductID:String;Const ASide:TOrderSide; Const AType:TOrderType;Const APostOnly,AStop:Boolean;Const APrice,ASize:Extended; Out Success:Boolean;Out Content:String):IGDAXOrder; function TestLedger(Const AAcctID:String; Out Content,Error:String; Out Success:Boolean):IGDAXAccountLedger; function TestFills(Const AProductID:String; Out Content,Error:String; Out Success:Boolean):IGDAXFills; public end; var GDAXTester: TGDAXTester; implementation uses gdax.api.time, gdax.api.products, gdax.api.fills, gdax.api.currencies; {$R *.lfm} { TGDAXTester } procedure TGDAXTester.FormCreate(Sender: TObject); begin FAccountsLoaded := False;; FAuthenticator := TGDAXAuthenticatorImpl.Create; pctrl_main.ActivePage := ts_auth; InitOrderTab; InitLedgerTab; InitFillsTab; end; procedure TGDAXTester.btn_auth_testClick(Sender: TObject); var LSig:String; LEpoch:Integer; begin InitAuthenticator; memo_auth_result.Lines.Clear; LSig := FAuthenticator.GenerateAccessSignature( roGET, BuildFullEndpoint(GDAX_END_API_ACCTS,gdSand), LEpoch ); FAuthenticator.BuildHeaders(memo_auth_result.Lines,LSig,LEpoch); end; procedure TGDAXTester.btn_accounts_testClick(Sender: TObject); var LCol:TGridColumn; LAccts:IGDAXAccounts; I:Integer; begin grid_accounts.Clear; grid_accounts.ColCount:=5; LCol := grid_accounts.Columns.Add; LCol.Title.Caption:='Account ID'; LCol := grid_accounts.Columns.Add; LCol.Title.Caption:='Available'; LCol := grid_accounts.Columns.Add; LCol.Title.Caption:='Balance'; LCol := grid_accounts.Columns.Add; LCol.Title.Caption:='Currency'; LCol := grid_accounts.Columns.Add; LCol.Title.Caption:='Holds'; LAccts := TestAccounts; grid_accounts.RowCount := LAccts.Accounts.Count; for I:=1 to Pred(LAccts.Accounts.Count) do begin grid_accounts.Cells[1,I]:=LAccts.Accounts[I].AcctID; grid_accounts.Cells[2,I]:=FloatToStr(LAccts.Accounts[I].Available); grid_accounts.Cells[3,I]:=FloatToStr(LAccts.Accounts[I].Balance); grid_accounts.Cells[4,I]:=LAccts.Accounts[I].Currency; grid_accounts.Cells[5,I]:=FloatToStr(LAccts.Accounts[I].Holds); end; end; procedure TGDAXTester.btn_base_web_testClick(Sender: TObject); var LTicker:IGDAXTicker; LCandles:IGDAXCandles; LCurrencies:IGDAXCurrencies; LError,LContent:String; begin InitAuthenticator; LTicker := TGDAXTickerImpl.Create; LTicker.Product := TGDAXProductImpl.Create; LTicker.Product.ID:='btc-usd'; LCandles := TGDAXCandlesImpl.Create; LCandles.Product := LTicker.Product; LCurrencies := TGDAXCurrenciesImpl.Create; LCurrencies.Authenticator := FAuthenticator; LTicker.Authenticator := FAuthenticator; LCandles.Authenticator := FAuthenticator; memo_base_web.Lines.Clear; memo_base_web.Lines.Add(TestTimeEndpoint); memo_base_web.Lines.Add('ticker test'); if not LTicker.Get(LContent,LError) then begin memo_base_web.Lines.Add('--Failure--'); end else memo_base_web.Append('min order size: ' + FloatToStr(LTicker.Product.BaseMinSize)); memo_base_web.Lines.Add(LContent); memo_base_web.Lines.Add('candles test'); if not LCandles.Get(LContent,LError) then memo_base_web.Lines.Add('--Failure--'); memo_base_web.Lines.Add(LContent); memo_base_web.Lines.Add('currencies test'); if not LCurrencies.Get(LContent,LError) then memo_base_web.Lines.Add('--Failure--'); memo_base_web.Lines.Add(LContent); end; procedure TGDAXTester.btn_product_testClick(Sender: TObject); var I:Integer; LProducts:IGDAXProducts; begin list_products.Clear; LProducts := TestProducts(edit_product_quote.Text); for I:=0 to Pred(LProducts.Products.Count) do list_products.Items.Add(LProducts.Products[I].ID); end; procedure TGDAXTester.btn_test_fillsClick(Sender: TObject); var I:Integer; LContent,LError:String; LSuccess:Boolean; LEntries:TFillEntryArray; begin list_fills.Clear; if not ((Sender=arrow_fills_back) or (Sender=arrow_fills_forward)) then begin FFills := nil; FFills := TestFills( combo_fills_products.Items.ValueFromIndex[combo_fills_products.ItemIndex], LContent, LError, LSuccess ); end; LEntries := FFills.Entries; for I:=0 to High(LEntries) do begin list_fills.Items.Add( Format( 'Product:%s Side:%s Price:%f', [ LEntries[I].ProductID, OrderSideToString(LEntries[I].Side), LEntries[I].Price ] ) ); end; lbl_fills_total.Caption:='Total:'+IntToStr(Length(LEntries)); lbl_fills_total_size.Caption:='TotalSize:'+FloatToStr(FFills.TotalSize[[osBuy,osSell]]); lbl_fills_total_fees.Caption:='TotalFees:'+FloatToStr(FFills.TotalFees[[osBuy,osSell]]); lbl_fills_total_price.Caption:='TotalPrice:'+FloatToStr(FFills.TotalPrice[[osBuy,osSell]]); end; procedure TGDAXTester.btn_test_ledgerClick(Sender: TObject); var I:Integer; LContent,LError:String; LSuccess:Boolean; begin list_ledger.Clear; if not ((Sender=arrow_ledger_back) or (Sender=arrow_ledger_forward)) then begin FLedger := nil; FLedger := TestLedger( combo_ledger_accounts.Items.ValueFromIndex[combo_ledger_accounts.ItemIndex], LContent, LError, LSuccess ); end; for I:=0 to High(FLedger.Entries) do begin list_ledger.Items.Add( Format( 'Type:%s Amount:%f', [ LedgerTypeToString(FLedger.Entries[I].LedgerType), FLedger.Entries[I].Amount ] ) ); end; lbl_ledger_count.Caption := IntToStr(Length(FLedger.Entries)); end; procedure TGDAXTester.btn_test_orderClick(Sender: TObject); var LOrder:IGDAXOrder; LContent:String; LType:TOrderType; LSide:TOrderSide; LSuccess:Boolean; LError:string; begin LType := StringToOrderType(combo_order_type.Text); LSide := StringToOrderSide(combo_order_side.Text); LOrder := TestOrder( combo_order_ids.Items[combo_order_ids.ItemIndex], LSide, LType, chk_order_post.Checked, chk_order_stop.Checked, StrToFloatDef(edit_order_price.Text,1), StrToFloatDef(edit_order_size.Text,1), LSuccess, LContent ); memo_order_output.Clear; if not LSuccess then begin memo_order_output.Lines.Add('order not successful'); memo_order_output.Text := LContent; Exit; end; memo_order_output.Text := LContent; while not ( LOrder.OrderStatus in [stActive,stOpen,stDone,stCancelled,stRejected,stSettled] ) do begin Application.ProcessMessages; Sleep(1000 div GDAX_PRIVATE_REQUESTS_PSEC); memo_order_output.Lines.Add('polling for status'); if not LOrder.Get(LContent,LError) then begin memo_order_output.Lines.Add('error occurred during polling: ' + LError); Exit; end; memo_order_output.Lines.Add(LContent); end; end; procedure TGDAXTester.FormDestroy(Sender: TObject); begin FAuthenticator := nil; end; procedure TGDAXTester.pctrl_mainChange(Sender: TObject); var I:Integer; LAccounts:IGDAXAccounts; begin if not FAccountsLoaded then begin combo_ledger_accounts.Clear; LAccounts := TestAccounts; for I:=0 to Pred(LAccounts.Accounts.Count) do combo_ledger_accounts.Items.Add( LAccounts.Accounts[I].Currency + '=' + LAccounts.Accounts[I].AcctID ); FAccountsLoaded := True; end; end; procedure TGDAXTester.ts_fillsShow(Sender: TObject); var I:Integer; LProducts:IGDAXProducts; begin if not FFillsLoaded then begin combo_fills_products.Clear; LProducts := TestProducts(''); for I:=0 to Pred(LProducts.Products.Count) do combo_fills_products.Items.Add(LProducts.Products[I].ID); FFillsLoaded := True; end; end; procedure TGDAXTester.LedgerMoveForward(Sender: TObject); var LError:String; begin if Assigned(FLedger) then begin if not FLedger.Paged.Move( pdAfter, LError ) then ShowMessage(LError); btn_test_ledgerClick(Sender); end; end; procedure TGDAXTester.LedgerMoveBack(Sender: TObject); var LError:String; begin if Assigned(FLedger) then begin if not FLedger.Paged.Move( pdBefore, LError ) then ShowMessage(LError); btn_test_ledgerClick(Sender); end; end; procedure TGDAXTester.FillsMoveForward(Sender: TObject); var LError:String; begin if Assigned(FFills) then begin if not FFills.Paged.Move( pdAfter, LError ) then ShowMessage(LError); btn_test_fillsClick(Sender); end; end; procedure TGDAXTester.FillsMoveBack(Sender: TObject); var LError:String; begin if Assigned(FFills) then begin if not FFills.Paged.Move( pdBefore, LError ) then ShowMessage(LError); btn_test_fillsClick(Sender); end; end; procedure TGDAXTester.InitAuthenticator; begin FAuthenticator.Key := edit_auth_key.Text; FAuthenticator.Passphrase := edit_auth_pass.Text; FAuthenticator.Secret := edit_auth_secret.Text; if chk_sandbox.Checked then FAuthenticator.Mode := gdSand else FAuthenticator.Mode := gdProd; FAuthenticator.UseLocalTime := chk_auth_time.Checked; end; procedure TGDAXTester.InitOrderTab; var I:Integer; begin combo_order_type.Clear; combo_order_side.Clear; for I := Low(ORDER_SIDES) to High(ORDER_SIDES) do combo_order_side.Items.Add(ORDER_SIDES[I]); for I := Low(ORDER_TYPES) to High(ORDER_TYPES) do combo_order_type.Items.Add(ORDER_TYPES[I]); end; procedure TGDAXTester.InitLedgerTab; begin arrow_ledger_forward.OnClick := LedgerMoveForward; arrow_ledger_back.OnClick := LedgerMoveBack; end; procedure TGDAXTester.InitFillsTab; begin arrow_fills_back.OnClick := FillsMoveBack; arrow_fills_forward.OnClick := FillsMoveForward; end; function TGDAXTester.TestTimeEndpoint: String; var LTime:IGDAXTime; LError:String; begin InitAuthenticator; LTime := TGDAXTimeImpl.Create; LTime.Authenticator := FAuthenticator; if not LTime.Get(Result,LError) then Result:= LError + sLineBreak + BuildFullEndpoint(GDAX_END_API_TIME,FAuthenticator.Mode) + sLineBreak + Result; end; function TGDAXTester.TestProducts( Const AQuoteCurrencyFilter: String): IGDAXProducts; var LContent,LError:String; begin InitAuthenticator; Result := TGDAXProductsImpl.Create; Result.Authenticator := FAuthenticator; Result.QuoteCurrency := AQuoteCurrencyFilter; if not Result.Get(LContent,LError) then raise Exception.Create(LError); end; function TGDAXTester.TestAccounts: IGDAXAccounts; var LContent,LError:String; begin InitAuthenticator; Result := TGDAXAccountsImpl.Create; Result.Authenticator := FAuthenticator; if not Result.Get(LContent,LError) then raise Exception.Create(LError); end; function TGDAXTester.TestOrder(Const AProductID: String; Const ASide: TOrderSide; Const AType: TOrderType; Const APostOnly, AStop: Boolean; Const APrice, ASize: Extended; out Success: Boolean; out Content: String): IGDAXOrder; var LError:String; begin Success := False; InitAuthenticator; Result := TGDAXOrderImpl.Create; Result.Authenticator := FAuthenticator; Result.Product.ID := AProductID; Result.Product.Authenticator := FAuthenticator; Result.Product.Get(Content, LError); Result.Side := ASide; Result.OrderType := AType; Result.Size := ASize; Result.Price := APrice; Result.StopOrder := AStop; Result.PostOnly := APostOnly; if not Result.Post(Content,LError) then begin Content := LError; Exit; end; //if we made a successful web call, check the status to see if the order //actually was "successful" case Result.OrderStatus of stUnknown: begin Success := False; Content:='order status is unknown after web call' + sLineBreak + Content; Exit; end; stRejected: begin Success := False; Content:='Rejected: ' + Result.RejectReason + sLineBreak + Content; Exit; end; end; Success := True; end; function TGDAXTester.TestLedger(Const AAcctID: String; out Content, Error: String; out Success: Boolean): IGDAXAccountLedger; begin Success := False; InitAuthenticator; Result := TGDAXAccountLedgerImpl.Create; Result.Authenticator := FAuthenticator; Result.AcctID := AAcctID; if not Result.Get(Content,Error) then Exit; Success := True; end; function TGDAXTester.TestFills(Const AProductID: String; out Content, Error: String; out Success: Boolean): IGDAXFills; begin Success := False; InitAuthenticator; Result := TGDAXFillsImpl.Create; Result.Authenticator := FAuthenticator; Result.ProductID := AProductID; if not Result.Get(Content,Error) then Exit; Success := True; end; end.
unit l3Script; { Библиотека "L3 (Low Level Library)" } { Автор: Люлин А.В. © } { Модуль: l3Script - } { Начат: 03.10.2007 16:59 } { $Id: l3Script.pas,v 1.12 2007/10/04 16:30:13 lulin Exp $ } // $Log: l3Script.pas,v $ // Revision 1.12 2007/10/04 16:30:13 lulin // - определяем количество параметров. // // Revision 1.11 2007/10/04 15:47:01 lulin // - добавлены параметры команд. // // Revision 1.10 2007/10/04 14:48:57 lulin // - добавлены алиасы. // // Revision 1.9 2007/10/04 14:30:18 lulin // - сделана передача строкового параметра. // // Revision 1.8 2007/10/04 14:04:55 lulin // - определяем пространства имен. // // Revision 1.7 2007/10/03 17:30:00 lulin // - проверяем существование объекта. // // Revision 1.6 2007/10/03 17:09:17 lulin // - выводим список команд. // // Revision 1.5 2007/10/03 16:37:18 lulin // - теперь в операцию передается консоль. // // Revision 1.4 2007/10/03 16:12:57 lulin // - не добавляем перевод строки - консоль сама должна это сделать. // // Revision 1.3 2007/10/03 16:10:37 lulin // - типизируем объекты, которые могут выполнять команды. // // Revision 1.2 2007/10/03 15:36:19 lulin // - сделано определение команд. // // Revision 1.1 2007/10/03 13:22:59 lulin // - добавлен файл. // {$Include l3Define.inc } interface uses l3Chars, l3Interfaces, l3Types, l3Base ; type Tl3ParamDef = record rSep : Char; rMax : Integer; rFill : Integer; end;//Tl3ParamDef Tl3OpContext = object public rTarget : TObject; rCmd : Il3CString; rTail : Il3CString; rCon : Il3Console; protected rParam : Tl3ParamDef; public function Params: Tl3CStringArray; {-} function IntParams: TLongArray; {-} end;//Tl3OpContext Tl3OpProc = procedure (const aTarget: Tl3OpContext); Tl3Script = class; Tl3OpString = class(Tl3String) private // internal fields f_Op : Tl3OpProc; f_Class : TClass; f_Script : Tl3Script; f_Param : Tl3ParamDef; protected // internal methods procedure Cleanup; override; {-} public // public methods function DefParams(aParamMax : Integer; aParamFill : Integer; aSep : Char = cc_Comma): Tl3OpString; {-} function Alias(const anAlias: String): Tl3OpString; {-} end;//Tl3OpString Tl3Script = class(Tl3Base, Il3Console) private // internal fields f_Ops : Tl3StringList; f_Spaces : Tl3StringList; f_Parent : Tl3Script; protected // internal methods procedure Shift(aDelta: Integer); {-} procedure Say(const aStr: Il3CString); {-} procedure Cleanup; override; {-} public // public methods function Space(const aName: Tl3WString; DoAdd: Boolean): Tl3Script; overload; function Space(const aName: String): Tl3Script; overload; {-} function Add(const aCmd : String; anOp : Tl3OpProc; aTargetClass : TClass): Tl3OpString; {-} function Cmd(const aCmd : Il3CString; const aTarget : array of TObject; const aCon : Il3Console): Boolean; {-} procedure Help(const aCon : Il3Console; const aStart : Il3CString); {-} end;//Tl3Script implementation uses SysUtils, l3String ; // start class Tl3OpContext function Tl3OpContext.Params: Tl3CStringArray; {-} begin Result := l3Split(rTail, rParam.rSep); end; function Tl3OpContext.IntParams: TLongArray; {-} var l_S : Tl3CStringArray; l_I : Integer; l_V : Integer; begin l_S := Params; SetLength(Result, rParam.rMax); for l_I := 0 to Pred(rParam.rMax) do Result[l_I] := rParam.rFill; for l_I := Low(l_S) to High(l_S) do if TryStrToInt(Trim(l3PCharLen2String(l3PCharLen(l_S[l_I]))), l_V) then Result[l_I] := l_V; end; // start class Tl3OpString procedure Tl3OpString.Cleanup; //override; {-} begin f_Script := nil; inherited; end; function Tl3OpString.DefParams(aParamMax : Integer; aParamFill : Integer; aSep : Char = cc_Comma): Tl3OpString; {-} begin Result := Self; f_Param.rSep := aSep; f_Param.rMax := aParamMax; f_Param.rFill := aParamFill; end; function Tl3OpString.Alias(const anAlias: String): Tl3OpString; {-} begin Result := f_Script.Add(anAlias, f_Op, f_Class); Result.f_Param := f_Param; end; // start class Tl3Script procedure Tl3Script.Cleanup; //override; {-} begin f_Parent := nil; l3Free(f_Spaces); l3Free(f_Ops); inherited; end; procedure Tl3Script.Shift(aDelta: Integer); {-} begin end; procedure Tl3Script.Say(const aStr: Il3CString); {-} begin end; type Tl3SpaceString = class(Tl3String) private // internal fields f_Script: Tl3Script; protected // internal methods procedure Cleanup; override; {-} end;//Tl3SpaceString procedure Tl3SpaceString.Cleanup; //override; {-} begin l3Free(f_Script); inherited; end; function Tl3Script.Space(const aName: Tl3WString; DoAdd: Boolean): Tl3Script; //overload; var l_Index : Integer; l_S : Tl3SpaceString; begin if (f_Spaces = nil) then begin if DoAdd then begin f_Spaces := Tl3StringList.MakeSorted; f_Spaces.Duplicates := l3_dupError; end//DoAdd else begin Result := nil; Exit; end;//DoAdd end;//f_Ops = nil if f_Spaces.Find(aName, l_Index) then Result := Tl3SpaceString(f_Spaces.Items[l_Index]).f_Script else if DoAdd then begin l_S := Tl3SpaceString.Make(aName); try l_S.f_Script := Tl3Script.Create; l_S.f_Script.f_Parent := Self; Result := l_S.f_Script; f_Spaces.Insert(l_Index, l_S); finally l3Free(l_S); end;//try.finally end//not f_Spaces.Find.. else Result := nil; end; function Tl3Script.Space(const aName: String): Tl3Script; {-} begin Result := Space(l3PCharLen(aName), true); end; function Tl3Script.Add(const aCmd : String; anOp : Tl3OpProc; aTargetClass : TClass): Tl3OpString; {-} var l_Index : Integer; l_S : Tl3OpString; begin if (f_Ops = nil) then begin f_Ops := Tl3StringList.MakeSorted; f_Ops.Duplicates := l3_dupError; end;//f_Ops = nil if f_Ops.Find(aCmd, l_Index) then raise Exception.CreateFmt('Команда %s уже существует', [aCmd]) else begin l_S := Tl3OpString.Make(l3PCharLen(aCmd)); try l_S.f_Op := anOp; l_S.f_Class := aTargetClass; l_S.f_Script := Self; l3FillChar(l_S.f_Param, SizeOf(l_S.f_Param)); Result := l_S; f_Ops.Insert(l_Index, l_S); finally l3Free(l_S); end;//try.finally end;//not f_Ops.Find.. end; function Tl3Script.Cmd(const aCmd : Il3CString; const aTarget : array of TObject; const aCon : Il3Console): Boolean; {-} var l_Index : Integer; l_I : Integer; l_S : Tl3OpString; l_C : Tl3OpContext; l_Pref : Il3CString; l_Space : Tl3Script; l_Cmd : Il3CString; begin if (aCon = nil) then l_C.rCon := Self else l_C.rCon := aCon; if (f_Spaces <> nil) then begin l3Split(aCmd, cc_Dot, l_Pref, l_Cmd); if not l3IsNil(l_Cmd) then begin l_Space := Space(l_Pref.AsWStr, false); if (l_Space <> nil) then if l_Space.Cmd(l_Cmd, aTarget, aCon) then Exit; end;//not l3IsNil(l_Cmd) end;//f_Spaces <> nil l3Split(aCmd, cc_HardSpace, l_Pref, l_Cmd); Result := (f_Ops <> nil) AND f_Ops.Find(l3PCharLen(l_Pref), l_Index); if Result then begin l_S := Tl3OpString(f_Ops.Items[l_Index]); for l_I := Low(aTarget) to High(aTarget) do begin l_C.rTarget := aTarget[l_I]; if (l_C.rTarget <> nil) AND l_C.rTarget.InheritsFrom(l_S.f_Class) then begin l_C.rTarget := aTarget[l_I]; l_C.rCmd := l_Pref; l_C.rTail := l_Cmd; l_C.rParam := l_S.f_Param; l_S.f_Op(l_C); Exit; end;//aTarget[l_I].InheritsFrom(l_S.f_Class) end;//for l_I Result := false; l_C.rCon.Say(l3Fmt('No target for command: %s', [aCmd])); end//Result else if (f_Parent = nil) then l_C.rCon.Say(l3Fmt('Bad command: %s', [aCmd])); end; procedure Tl3Script.Help(const aCon : Il3Console; const aStart : Il3CString); {-} var l_I : Integer; l_S : Il3CString; l_P : Il3CString; l_T : Il3CString; l_Op : Tl3OpString; begin if (aCon <> nil) then begin if (f_Spaces <> nil) then for l_I := f_Spaces.Lo to f_Spaces.Hi do begin l3Split(aStart, cc_Dot, l_P, l_T); l_S := l3CStr(f_Spaces.Items[l_I]); if l3Starts(l_P, l_S) then begin aCon.Say(l_S); aCon.Shift(+1); Tl3SpaceString(f_Spaces.Items[l_I]).f_Script.Help(aCon, l_T); aCon.Shift(-1); end;//l3Starts(l_P, l_S) end;//for l_I if (f_Ops <> nil) then for l_I := f_Ops.Lo to f_Ops.Hi do begin l_Op := Tl3OpString(f_Ops.Items[l_I]); l_S := l3CStr(l_Op); if l3Starts(aStart, l_S) then begin with l_Op.f_Param do if (rMax > 0) then l_S := l3Cat(l_S, ' [' + l3Dup(IntToStr(rFill), rMax, rSep) + ']'); aCon.Say(l_S); end;//l3Starts(aStart, l_S) end;//for l_I end;//aCon <> nil end; end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.Generics.Collections; type TForm1 = class(TForm) Button1: TButton; Button2: TButton; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private CacheImages: TDictionary<Int64, TStrings>; GarbageCollectionObjectList: TObjectList<TStrings>; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); begin CacheImages := TDictionary<Int64, TStrings>.Create; GarbageCollectionObjectList := TObjectList<TStrings>.Create; end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin CacheImages.Free; GarbageCollectionObjectList.Free; end; procedure TForm1.Button1Click(Sender: TObject); begin var Stringona := TStringList.Create; Stringona.Text := DateTimeToStr(now); CacheImages.AddOrSetValue(CacheImages.Count + 1, Stringona); CacheImages.TrimExcess; GarbageCollectionObjectList.Add(Stringona); end; procedure TForm1.Button2Click(Sender: TObject); begin var Chave := Random(CacheImages.Count)+1; try var Conteudo := CacheImages.ExtractPair(Chave).Value.Text; ShowMessage(chave.ToString + ': ' + Conteudo); except ShowMessage(chave.ToString + ': NÃO EXISTE!'); end; end; end.
unit CacheManagerRDO; interface uses SyncObjs, RDOInterfaces, CacheHistory; const MaxWorlds = 20; ConnectionTime = 20*1000; ProxyTimeOut = 2*60*1000; ExpireTTL = 1; type IWorldProxy = interface procedure Lock; procedure Unlock; function GetName : string; function IsConnected : boolean; function GetCache(Id, kind, info : integer) : string; function RenewCache(Agent, ObjId : string) : string; function GetMSVersion : integer; procedure CheckHistory; property Name : string read GetName; property MSVersion : integer read GetMSVersion; end; ICacher = interface function GetWorldProxy(Name : string) : IWorldProxy; end; TWorldProxy = class(TInterfacedObject, IWorldProxy) public constructor Create(aName : string; aProxy : OleVariant; MSVer : integer); destructor Destroy; override; private fName : string; fProxy : OleVariant; fCriticalSec : TCriticalSection; fConnected : boolean; fMSVersion : integer; fHistory : TCacheHistory; public procedure Lock; procedure Unlock; function GetName : string; function IsConnected : boolean; function GetCache(Id, kind, info : integer) : string; function RenewCache(Agent, ObjId : string) : string; function GetMSVersion : integer; procedure CheckHistory; public property Name : string read GetName; private procedure Disconnect(const Conn : IRDOConnection); end; TWorldProxiyArray = array[0..MaxWorlds] of IWorldProxy; TWorldProxies = class public constructor Create; destructor Destroy; override; private fCount : integer; fWorlds : TWorldProxiyArray; fCriticalSec : TCriticalSection; public procedure Lock; procedure Unlock; function IniRDOForWorld(const Name : string; index : integer) : IWorldProxy; function GetWorldProxy(Name : string) : IWorldProxy; procedure CheckHistories; public property Proxies[index :string] : IWorldProxy read GetWorldProxy; default; end; function CreateExpireDate(ttl : integer) : TDateTime; var WorldProxies : TWorldProxies = nil; implementation uses Windows, SysUtils, ActiveX, ComObj, Registry, CacheRegistryKeys, Collection, CacheObjects, CacheCommon, WinSockRDOConnection, RDOObjectProxy; function CreateExpireDate(ttl : integer) : TDateTime; begin result := Now + EncodeTime(0, ttl, 0, 0); end; // TWorldProxy constructor TWorldProxy.Create(aName : string; aProxy : OleVariant; MSVer : integer); begin inherited Create; fName := aName; fProxy := aProxy; fCriticalSec := TCriticalSection.Create; fConnected := true; fMSVersion := MSVer; fHistory := TCacheHistory.Create;//(1*60*1000); end; destructor TWorldProxy.Destroy; begin fCriticalSec.Free; inherited; end; procedure TWorldProxy.Lock; begin fCriticalSec.Enter; end; procedure TWorldProxy.Unlock; begin fCriticalSec.Leave; end; function TWorldProxy.IsConnected : boolean; begin result := fConnected; end; function TWorldProxy.GetName : string; begin result := fName; end; function TWorldProxy.GetCache(Id, kind, info : integer) : string; var ObjId : string; exp : TDateTime; begin try Lock; try ObjId := IntToStr(Id) + IntToStr(kind) + IntToStr(info); if fHistory.ExpiredObj(ObjId) then begin fHistory.Lock; try result := fProxy.GetCache(Id, kind, info); if result = resOK then begin exp := CreateExpireDate(ExpireTTL); fHistory.AddRecord(ObjId, exp); end; finally fHistory.Unlock end; end else result := resOK; finally Unlock; end; except result := resError; end; end; function TWorldProxy.RenewCache(Agent, ObjId : string) : string; var exp : TDateTime; begin try Lock; try if fHistory.ExpiredObj(ObjId) then begin fHistory.Lock; try result := fProxy.RenewCache(Agent, ObjId); if result = resOK then begin exp := CreateExpireDate(ExpireTTL); fHistory.AddRecord(ObjId, exp); end; finally fHistory.Unlock end; end else result := resOK; finally Unlock; end; except result := resError; end; end; function TWorldProxy.GetMSVersion : integer; begin result := fMSVersion; end; procedure TWorldProxy.CheckHistory; begin Lock; try fHistory.ClearExpired; finally Unlock; end; end; procedure TWorldProxy.Disconnect(const Conn : IRDOConnection); begin fConnected := false; end; // TWorldProxies constructor TWorldProxies.Create; begin inherited Create; fCriticalSec := TCriticalSection.Create; end; destructor TWorldProxies.Destroy; begin fCriticalSec.Free; inherited; end; procedure TWorldProxies.Lock; begin fCriticalSec.Enter; end; procedure TWorldProxies.Unlock; begin fCriticalSec.Leave; end; function TWorldProxies.IniRDOForWorld(const Name : string; index : integer) : IWorldProxy; var ServerAddr : string; ServerPort : integer; ClientConn : IRDOConnectionInit; Proxy : OleVariant; Reg : TRegistry; WorldProxy : TWorldProxy; MSVer : integer; begin try Reg := TRegistry.Create; Reg.RootKey := HKEY_LOCAL_MACHINE; if Reg.OpenKey(WorldsKey + Name, false) then begin ServerAddr := Reg.ReadString('Server'); ServerPort := Reg.ReadInteger('Port'); MSVer := Reg.ReadInteger('Version'); ClientConn := TWinSockRDOConnection.Create; ClientConn.Server := ServerAddr; ClientConn.Port := ServerPort; if ClientConn.Connect(ConnectionTime) then begin Proxy := TRDOObjectProxy.Create as IDispatch; Proxy.SetConnection(ClientConn); Proxy.TimeOut := ProxyTimeOut; Proxy.BindTo(MSObjectCacherName); WorldProxy := TWorldProxy.Create(Name, Proxy, MSVer); (ClientConn as IRDOConnection).OnDisconnect := WorldProxy.Disconnect; result := WorldProxy; { $IFDEF CACHESERVER} // >> ?? // Add a new world RDO proxy fWorlds[index] := result; if index = fCount then inc(fCount); { $ENDIF} end else result := nil; end else result := nil; except result := nil; end; end; function TWorldProxies.GetWorldProxy(Name : string) : IWorldProxy; var i : integer; begin try Name := uppercase(Name); Lock; try i := 0; while (i < fCount) and (fWorlds[i].Name <> Name) do inc(i); if (i < fCount) and fWorlds[i].IsConnected then result := fWorlds[i] else result := IniRDOForWorld(Name, i) finally Unlock; end; except result := nil; end; end; procedure TWorldProxies.CheckHistories; var i : integer; begin Lock; try for i := 0 to pred(fCount) do fWorlds[i].CheckHistory; finally Unlock; end; end; initialization WorldProxies := TWorldProxies.Create; finalization {$IFDEF CACHESERVER} WorldProxies.Free; // >> Why it crashes if it is working within an OLE-Automation dll? {$ENDIF} end.
unit evCellsCharOffsets; {* работа со смещениями ячеек } // Модуль: "w:\common\components\gui\Garant\Everest\evCellsCharOffsets.pas" // Стереотип: "SimpleClass" // Элемент модели: "TevCellsCharOffsets" MUID: (4F2F6CA40273) {$Include w:\common\components\gui\Garant\Everest\evDefine.inc} interface uses l3IntfUses , l3ProtoObject , evOneCharLongIntList , evEditorInterfaces , edCellTypesList ; type TevCellsCharOffsets = class(Tl3ProtoObject) {* работа со смещениями ячеек } private f_Offsets: TevOneCharLongIntList; {* Смещения ячеек } f_Widths: TevOneCharLongIntList; {* Ширина ячеек по этому смещению } f_Width: Integer; {* Текущая ширина ячейки } f_Offset: Integer; {* Текущее смещение } f_Index: Integer; f_UsingCount: Integer; private procedure CheckList; protected procedure Cleanup; override; {* Функция очистки полей объекта. } public procedure AddCellWidthAndRecalc; procedure Clear; function FindOffset(const aOffsetList: TevCellsCharOffsets; var anIndex: Integer): Boolean; overload; function FindOffset(anOffset: Integer; var anIndex: Integer): Boolean; overload; function LastWidth: Integer; function PrevWidth: Integer; function GetNextOffset: Integer; procedure SetCurrent(anIndex: Integer); function GetOffset: Integer; procedure SetWidth(aWidth: Integer); function GetWidth: Integer; procedure UpdateWidth(anIndex: Integer; aDelta: Integer); function Equals(const anIterator: IedCellsIterator): Boolean; overload; procedure CopyData(const aData: TevCellsCharOffsets; const anIterator: IedCellsIterator); function GetRowWidth: Integer; procedure AlignByPrevious(const aData: TevCellsCharOffsets); function Equals(const anIterator: IedCellsIterator; aForTempate: Boolean): Boolean; overload; procedure IncUsingCount; function GetWidthByIndex(anIndex: Integer): Integer; function GetOffsetByIndex(anIndex: Integer): Integer; function GetCount: Integer; procedure AlignByOffset(anOffset: Integer; anIndex: Integer; aCellTypeList: TedCellTypesList); end;//TevCellsCharOffsets implementation uses l3ImplUses , SysUtils , l3UnitsTools {$If Defined(k2ForEditor)} , evTableCellUtils {$IfEnd} // Defined(k2ForEditor) , evExcept //#UC START# *4F2F6CA40273impl_uses* //#UC END# *4F2F6CA40273impl_uses* ; procedure TevCellsCharOffsets.AddCellWidthAndRecalc; //#UC START# *4F2F6D94002E_4F2F6CA40273_var* //#UC END# *4F2F6D94002E_4F2F6CA40273_var* begin //#UC START# *4F2F6D94002E_4F2F6CA40273_impl* CheckList; f_Offsets.Add(f_Offset); f_Widths.Add(f_Width); Inc(f_Offset, f_Width); //#UC END# *4F2F6D94002E_4F2F6CA40273_impl* end;//TevCellsCharOffsets.AddCellWidthAndRecalc procedure TevCellsCharOffsets.Clear; //#UC START# *4F2F6DAB0114_4F2F6CA40273_var* //#UC END# *4F2F6DAB0114_4F2F6CA40273_var* begin //#UC START# *4F2F6DAB0114_4F2F6CA40273_impl* if (f_Offsets <> nil) then begin f_Offsets.Clear; f_Widths.Clear; f_Offset := 0; f_Width := 0; f_Index := 0; f_UsingCount := 0; end; // if (f_Offsets <> nil) then //#UC END# *4F2F6DAB0114_4F2F6CA40273_impl* end;//TevCellsCharOffsets.Clear function TevCellsCharOffsets.FindOffset(const aOffsetList: TevCellsCharOffsets; var anIndex: Integer): Boolean; //#UC START# *4F2F6DC40150_4F2F6CA40273_var* //#UC END# *4F2F6DC40150_4F2F6CA40273_var* begin //#UC START# *4F2F6DC40150_4F2F6CA40273_impl* Result := f_Offsets <> nil; if Result then begin Result := f_Offsets.FindData(aOffsetList.f_Offset, anIndex); if Result then begin f_Width := f_Widths[anIndex]; f_Offset := f_Offsets[anIndex]; end; // if Result then end; // if Result then //#UC END# *4F2F6DC40150_4F2F6CA40273_impl* end;//TevCellsCharOffsets.FindOffset function TevCellsCharOffsets.FindOffset(anOffset: Integer; var anIndex: Integer): Boolean; //#UC START# *4F2F6DEE0354_4F2F6CA40273_var* //#UC END# *4F2F6DEE0354_4F2F6CA40273_var* begin //#UC START# *4F2F6DEE0354_4F2F6CA40273_impl* Result := f_Offsets <> nil; if Result then begin Result := f_Offsets.FindData(anOffset, anIndex); if Result then begin f_Width := f_Widths[anIndex]; f_Offset := f_Offsets[anIndex]; end; // if Result then end; // if Result then //#UC END# *4F2F6DEE0354_4F2F6CA40273_impl* end;//TevCellsCharOffsets.FindOffset function TevCellsCharOffsets.LastWidth: Integer; //#UC START# *4F2F6E25013C_4F2F6CA40273_var* //#UC END# *4F2F6E25013C_4F2F6CA40273_var* begin //#UC START# *4F2F6E25013C_4F2F6CA40273_impl* f_Index := f_Widths.Count; Result := PrevWidth; //#UC END# *4F2F6E25013C_4F2F6CA40273_impl* end;//TevCellsCharOffsets.LastWidth function TevCellsCharOffsets.PrevWidth: Integer; //#UC START# *4F2F6E47025D_4F2F6CA40273_var* //#UC END# *4F2F6E47025D_4F2F6CA40273_var* begin //#UC START# *4F2F6E47025D_4F2F6CA40273_impl* Dec(f_Index); if f_Index >= 0 then Result := f_Widths[f_Index] else Result := 0; //#UC END# *4F2F6E47025D_4F2F6CA40273_impl* end;//TevCellsCharOffsets.PrevWidth function TevCellsCharOffsets.GetNextOffset: Integer; //#UC START# *4F2F6E6301E4_4F2F6CA40273_var* //#UC END# *4F2F6E6301E4_4F2F6CA40273_var* begin //#UC START# *4F2F6E6301E4_4F2F6CA40273_impl* Result := f_Offset + f_Width; //#UC END# *4F2F6E6301E4_4F2F6CA40273_impl* end;//TevCellsCharOffsets.GetNextOffset procedure TevCellsCharOffsets.SetCurrent(anIndex: Integer); //#UC START# *4F2F6E8500D5_4F2F6CA40273_var* //#UC END# *4F2F6E8500D5_4F2F6CA40273_var* begin //#UC START# *4F2F6E8500D5_4F2F6CA40273_impl* f_Width := f_Widths[anIndex]; f_Offset := f_Offsets[anIndex]; //#UC END# *4F2F6E8500D5_4F2F6CA40273_impl* end;//TevCellsCharOffsets.SetCurrent function TevCellsCharOffsets.GetOffset: Integer; //#UC START# *4F2F6EAB0342_4F2F6CA40273_var* //#UC END# *4F2F6EAB0342_4F2F6CA40273_var* begin //#UC START# *4F2F6EAB0342_4F2F6CA40273_impl* Result := f_Offset; //#UC END# *4F2F6EAB0342_4F2F6CA40273_impl* end;//TevCellsCharOffsets.GetOffset procedure TevCellsCharOffsets.SetWidth(aWidth: Integer); //#UC START# *4F2F6EC7021E_4F2F6CA40273_var* //#UC END# *4F2F6EC7021E_4F2F6CA40273_var* begin //#UC START# *4F2F6EC7021E_4F2F6CA40273_impl* f_Width := aWidth; //#UC END# *4F2F6EC7021E_4F2F6CA40273_impl* end;//TevCellsCharOffsets.SetWidth function TevCellsCharOffsets.GetWidth: Integer; //#UC START# *4F2F6EE10292_4F2F6CA40273_var* //#UC END# *4F2F6EE10292_4F2F6CA40273_var* begin //#UC START# *4F2F6EE10292_4F2F6CA40273_impl* Result := f_Width; //#UC END# *4F2F6EE10292_4F2F6CA40273_impl* end;//TevCellsCharOffsets.GetWidth procedure TevCellsCharOffsets.UpdateWidth(anIndex: Integer; aDelta: Integer); //#UC START# *4F2F6EFA02E7_4F2F6CA40273_var* //#UC END# *4F2F6EFA02E7_4F2F6CA40273_var* begin //#UC START# *4F2F6EFA02E7_4F2F6CA40273_impl* if anIndex = -1 then begin f_Offset := f_Offset + aDelta; f_Widths.Last := f_Widths.Last + aDelta; end // if anIndex = -1 then else f_Widths[anIndex] := f_Widths[anIndex] + aDelta; //#UC END# *4F2F6EFA02E7_4F2F6CA40273_impl* end;//TevCellsCharOffsets.UpdateWidth function TevCellsCharOffsets.Equals(const anIterator: IedCellsIterator): Boolean; //#UC START# *4F2FC2F502F6_4F2F6CA40273_var* const cnTooBigCellWidth = 1000000; var i : Integer; l_Cell : IedCell; l_Delta : Integer; l_Result : Boolean; //#UC END# *4F2FC2F502F6_4F2F6CA40273_var* begin //#UC START# *4F2FC2F502F6_4F2F6CA40273_impl* Result := False; Assert(f_Widths <> nil); l_Result := anIterator.CellsCount = f_Widths.Count; if l_Result then begin l_Cell := anIterator.First(False); l_Delta := 4 * evCellWidthEpsilon; for i := 0 to f_Widths.Count - 1 do begin l_Result := Abs(l_Cell.Width - f_Widths[i]) <= l_Delta; if not l_Result then l_Result := ((l_Cell.Width < evCellWidthEpsilon) or (l_Cell.Width > cnTooBigCellWidth)) and not l_Cell.IsEmptyCell; if not l_Result then Break; l_Cell := anIterator.Next; end; // for i := 0 to f_Widths.Count - 1 do if l_Result then Result := True; end; // if not l_Result then //#UC END# *4F2FC2F502F6_4F2F6CA40273_impl* end;//TevCellsCharOffsets.Equals procedure TevCellsCharOffsets.CopyData(const aData: TevCellsCharOffsets; const anIterator: IedCellsIterator); //#UC START# *4F2FCECA004D_4F2F6CA40273_var* var l_Cell : IedCell; l_Offset : Integer; //#UC END# *4F2FCECA004D_4F2F6CA40273_var* begin //#UC START# *4F2FCECA004D_4F2F6CA40273_impl* CheckList; if anIterator = nil then begin f_Widths.Assign(aData.f_Widths); f_Offsets.Assign(aData.f_Offsets); end // if anIterator = nil then else begin f_Widths.Capacity := anIterator.CellsCount; f_Offsets.Capacity := anIterator.CellsCount; l_Cell := anIterator.First(False); l_Offset := 0; while l_Cell <> nil do begin f_Widths.Add(l_Cell.Width); f_Offsets.Add(l_Offset); Inc(l_Offset, l_Cell.Width); l_Cell := anIterator.Next; end; // while l_Cell <> nil do end; // if anIterator = nil then //#UC END# *4F2FCECA004D_4F2F6CA40273_impl* end;//TevCellsCharOffsets.CopyData procedure TevCellsCharOffsets.CheckList; //#UC START# *4F2FD1E202A4_4F2F6CA40273_var* //#UC END# *4F2FD1E202A4_4F2F6CA40273_var* begin //#UC START# *4F2FD1E202A4_4F2F6CA40273_impl* if (f_Offsets = nil) then f_Offsets := TevOneCharLongIntList.Make; if (f_Widths = nil) then f_Widths := TevOneCharLongIntList.Make; //#UC END# *4F2FD1E202A4_4F2F6CA40273_impl* end;//TevCellsCharOffsets.CheckList function TevCellsCharOffsets.GetRowWidth: Integer; //#UC START# *4FAB832701E6_4F2F6CA40273_var* var i : Integer; l_Count : Integer; //#UC END# *4FAB832701E6_4F2F6CA40273_var* begin //#UC START# *4FAB832701E6_4F2F6CA40273_impl* Result := 0; l_Count := f_Widths.Count - 1; for i := 0 to l_Count do begin //if (i = l_Count) and (f_Widths[i] = evCellWidthEpsilon) then Break; // http://mdp.garant.ru/pages/viewpage.action?pageId=206078013 Inc(Result, f_Widths[i]); end; // for i := 0 to l_Count do //#UC END# *4FAB832701E6_4F2F6CA40273_impl* end;//TevCellsCharOffsets.GetRowWidth procedure TevCellsCharOffsets.AlignByPrevious(const aData: TevCellsCharOffsets); //#UC START# *4FC773170099_4F2F6CA40273_var* var l_Index : Integer; l_PrevIndex : Integer; l_RowWidth : Integer; l_RightIndent : Integer; //#UC END# *4FC773170099_4F2F6CA40273_var* begin //#UC START# *4FC773170099_4F2F6CA40273_impl* l_Index := f_Widths.Count - 1; l_PrevIndex := aData.f_Widths.Count - 1; if l_Index <= l_PrevIndex then begin l_RowWidth := aData.GetRowWidth; while l_Index > 0 do begin f_Widths[l_Index] := aData.f_Widths[l_PrevIndex]; Dec(l_RowWidth, f_Widths[l_Index]); Dec(l_Index); Dec(l_PrevIndex); end; // while l_Index > 0 do f_Widths[l_Index] := l_RowWidth; end; // if l_Index < aData.f_Widths.Count then //#UC END# *4FC773170099_4F2F6CA40273_impl* end;//TevCellsCharOffsets.AlignByPrevious function TevCellsCharOffsets.Equals(const anIterator: IedCellsIterator; aForTempate: Boolean): Boolean; //#UC START# *50937BBB01BF_4F2F6CA40273_var* var i : Integer; l_Cell : IedCell; l_Count : Integer; l_Equal : Integer; l_Result : Boolean; //#UC END# *50937BBB01BF_4F2F6CA40273_var* begin //#UC START# *50937BBB01BF_4F2F6CA40273_impl* Result := False; l_Count := f_Widths.Count; l_Result := anIterator.CellsCount <> l_Count; if not l_Result then begin l_Cell := anIterator.First(False); l_Equal := 0; for i := 0 to l_Count - 1 do begin if (Abs(l_Cell.Width - f_Widths[i]) < l_Cell.Width div 2) then Inc(l_Equal); l_Cell := anIterator.Next; end; // for i := 0 to l_List.Count - 1 do l_Result := l_Equal >= l_Count div 2; if not aForTempate and not l_Result then l_Result := f_UsingCount > 1; if l_Result then Result := True; end; // if not l_Result then //#UC END# *50937BBB01BF_4F2F6CA40273_impl* end;//TevCellsCharOffsets.Equals procedure TevCellsCharOffsets.IncUsingCount; //#UC START# *509383B202C4_4F2F6CA40273_var* //#UC END# *509383B202C4_4F2F6CA40273_var* begin //#UC START# *509383B202C4_4F2F6CA40273_impl* Inc(f_UsingCount); //#UC END# *509383B202C4_4F2F6CA40273_impl* end;//TevCellsCharOffsets.IncUsingCount function TevCellsCharOffsets.GetWidthByIndex(anIndex: Integer): Integer; //#UC START# *52F1EC8D0285_4F2F6CA40273_var* //#UC END# *52F1EC8D0285_4F2F6CA40273_var* begin //#UC START# *52F1EC8D0285_4F2F6CA40273_impl* Result := f_Widths[anIndex]; //#UC END# *52F1EC8D0285_4F2F6CA40273_impl* end;//TevCellsCharOffsets.GetWidthByIndex function TevCellsCharOffsets.GetOffsetByIndex(anIndex: Integer): Integer; //#UC START# *52F1ECC0021F_4F2F6CA40273_var* //#UC END# *52F1ECC0021F_4F2F6CA40273_var* begin //#UC START# *52F1ECC0021F_4F2F6CA40273_impl* Result := f_Offsets[anIndex]; //#UC END# *52F1ECC0021F_4F2F6CA40273_impl* end;//TevCellsCharOffsets.GetOffsetByIndex function TevCellsCharOffsets.GetCount: Integer; //#UC START# *52F1ECE3002C_4F2F6CA40273_var* //#UC END# *52F1ECE3002C_4F2F6CA40273_var* begin //#UC START# *52F1ECE3002C_4F2F6CA40273_impl* Result := f_Offsets.Count; //#UC END# *52F1ECE3002C_4F2F6CA40273_impl* end;//TevCellsCharOffsets.GetCount procedure TevCellsCharOffsets.AlignByOffset(anOffset: Integer; anIndex: Integer; aCellTypeList: TedCellTypesList); //#UC START# *52F1ED3803C8_4F2F6CA40273_var* var i : Integer; l_Delta: Integer; //#UC END# *52F1ED3803C8_4F2F6CA40273_var* begin //#UC START# *52F1ED3803C8_4F2F6CA40273_impl* l_Delta := f_Offsets[anIndex] - anOffset; for i := anIndex - 1 downto 0 do if aCellTypeList[i] = ed_ctEmptyAndNotFramed then begin f_Widths[i] := f_Widths[i] - l_Delta; f_Offsets[i + 1] := f_Offsets[i] + f_Widths[i]; Break; end; // if aCellTypeList[i] = ed_EmptyAndNotFramed then //#UC END# *52F1ED3803C8_4F2F6CA40273_impl* end;//TevCellsCharOffsets.AlignByOffset procedure TevCellsCharOffsets.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_4F2F6CA40273_var* //#UC END# *479731C50290_4F2F6CA40273_var* begin //#UC START# *479731C50290_4F2F6CA40273_impl* if f_Offsets <> nil then f_Offsets.Clear; FreeAndNil(f_Offsets); if f_Widths <> nil then f_Widths.Clear; FreeAndNil(f_Widths); f_UsingCount := 0; inherited; //#UC END# *479731C50290_4F2F6CA40273_impl* end;//TevCellsCharOffsets.Cleanup end.
unit UAccessUser; interface uses Classes, UAccessBase, UAccessContainer; type TSAVAccessUser = class(TSAVAccessContainer) private FDomain: string; procedure SetDomain(const Value: string); protected public property Domain: string read FDomain write SetDomain; constructor Create; overload; constructor Create(aBase: TSAVAccessBase; const aDomain, aCaption, aSID, aDescription: string); overload; procedure Save; override; procedure Open(aBase: TSAVAccessBase; const aCaption, aSID: string; const aDescription: string = ''; const aParam: string = ''; const aVersion: TVersionString = ''); override; function Load(aSID: string = ''): Boolean; override; procedure GetGroups(List: TStrings); procedure Clear; override; function GroupDelete(const aSID: string): Boolean; procedure UpdateVersion; override; end; implementation uses SAVLib, SAVLib_DBF, KoaUtils, SysUtils, VKDBFDataSet, VKDBFNTX, VKDBFIndex, VKDBFSorters, UAccessConstant, DB, IniFiles; { TSAVAccessUser } constructor TSAVAccessUser.Create; begin inherited Create; ContainerType := 'U'; end; procedure TSAVAccessUser.Clear; begin inherited; FDomain := ''; end; constructor TSAVAccessUser.Create(aBase: TSAVAccessBase; const aDomain, aCaption, aSID, aDescription: string); begin Create; Open(aBase, aCaption, aSID, aDescription, aDomain); Save; end; procedure TSAVAccessUser.GetGroups(List: TStrings); var Ini01: TIniFile; list1: TStringList; table1: TVKDBFNTX; i: Integer; begin List.Clear; Ini01 := TIniFile.Create(IncludeTrailingPathDelimiter(WorkDir) + csContainerCfg); list1 := TStringList.Create; ini01.ReadSectionValues(csIniGroups, list1); FreeAndNil(Ini01); table1 := TVKDBFNTX.Create(nil); SAVLib_DBF.InitOpenDBF(table1, IncludeTrailingPathDelimiter(Bases.JournalsDir) + csTableGroups, 64); table1.Open; for i := 0 to list1.Count - 1 do if table1.Locate(csFieldSID, list1.Names[i], []) then List.Add(table1.fieldByName(csFieldCaption).AsString + '=' + list1.Names[i]) else List.Add(csNotFound + '=' + list1.Names[i]); table1.Close; FreeAndNil(table1); FreeAndNil(list1); end; function TSAVAccessUser.Load(aSID: string = ''): Boolean; var table1: TVKDBFNTX; s: string; begin // inherited; if aSID = '' then s := SID else s := aSID; table1 := TVKDBFNTX.Create(nil); SAVLib_DBF.InitOpenDBF(table1, Bases.JournalsPath + csTableUsers, 64); table1.Open; Result := table1.Locate(csFieldSID, s, []); if Result then begin SID := s; Caption := table1.fieldByName(csFieldCaption).AsString; Description := table1.FieldByName(csFieldDescription).AsString; ID := table1.FieldByName(csFieldID).AsInteger; Domain := table1.FieldByName(csFieldDomain).AsString; WorkDir := IncludeTrailingPathDelimiter(Bases.UsersDir) + SID; ReadVersion; end; table1.Close; FreeAndNil(table1); end; procedure TSAVAccessUser.Save; var table1: TVKDBFNTX; begin inherited; table1 := TVKDBFNTX.Create(nil); SAVLib_DBF.InitOpenDBF(table1, Bases.JournalsPath + csTableUsers, 66); with table1.Indexes.Add as TVKNTXIndex do NTXFileName := Bases.JournalsPath + csIndexUserName; with table1.Indexes.Add as TVKNTXIndex do NTXFileName := Bases.JournalsPath + csIndexUserVersion; table1.Open; if table1.FLock then begin if not (table1.Locate(csFieldSID, SID, [])) then begin table1.Append; table1.FieldByName(csFieldSID).AsString := SID; table1.FieldByName(csFieldID).AsInteger := table1.GetNextAutoInc(csFieldID); table1.FieldByName(csFieldDomain).AsString := Domain; end else table1.Edit; table1.FieldByName(csFieldCaption).AsString := Caption; table1.FieldByName(csFieldDescription).AsString := Description; table1.FieldByName(csFieldVersion).AsString := GetNewVersion; Version := table1.FieldByName(csFieldVersion).AsString; ID := table1.FieldByName(csFieldID).AsInteger; table1.Post; table1.UnLock; end else raise Exception.Create(csFLockError + Table1.DBFFileName); table1.Close; FreeAndNil(table1); WorkDir := IncludeTrailingPathDelimiter(Bases.UsersDir) + SID; ForceDirectories(WorkDir); WriteVersion; end; procedure TSAVAccessUser.SetDomain(const Value: string); begin FDomain := Value; end; procedure TSAVAccessUser.Open(aBase: TSAVAccessBase; const aCaption, aSID: string; const aDescription: string = ''; const aParam: string = ''; const aVersion: TVersionString = ''); begin WorkDir := IncludeTrailingPathDelimiter(aBase.UsersDir) + aSID; inherited Open(aBase, aCaption, aSID, aDescription, aParam, aVersion); FDomain := aParam; end; function TSAVAccessUser.GroupDelete(const aSID: string): Boolean; var Ini01: TIniFile; begin Result := True; Ini01 := TIniFile.Create(IncludeTrailingPathDelimiter(WorkDir) + csContainerCfg); Ini01.DeleteKey(csIniGroups, aSID); FreeAndNil(Ini01); try Ini01 := TIniFile.Create(IncludeTrailingPathDelimiter(Bases.GroupsDir) + aSID + '\' + csContainerCfg); Ini01.DeleteKey(csIniUsers, SID); except Result := False; end; if Assigned(Ini01) then FreeAndNil(Ini01); end; procedure TSAVAccessUser.UpdateVersion; var table1: TVKDBFNTX; begin inherited; table1 := TVKDBFNTX.Create(nil); InitOpenDBF(table1, Bases.JournalsPath + csTableUsers, 66); with table1.Indexes.Add as TVKNTXIndex do NTXFileName := Bases.JournalsPath + csIndexUserVersion; table1.Open; if table1.Locate(csFieldSID, SID, []) then begin if table1.FLock then begin table1.Edit; table1.FieldByName(csFieldVersion).AsString := Version; table1.Post; table1.UnLock; end else raise Exception.Create(csFLockError + Table1.DBFFileName); end; table1.Close; FreeAndNil(table1); end; end.
unit kwQueryCardSetCanSaveState; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "F1 Shell Words" // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/F1_Shell_Words/kwQueryCardSetCanSaveState.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<ScriptKeyword::Class>> F1 Поддержка тестов::F1 Shell Words::F1 Shell Words::QueryCard_SetCanSaveState // // Устанавливает флаг того может ли карточка запроса писать своё состояние // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\GbaNemesis\nsDefine.inc} interface uses Classes {$If not defined(Admin)} , PrimQueryCard_Form {$IfEnd} //not Admin {$If not defined(NoScripts)} , tfwScriptingInterfaces {$IfEnd} //not NoScripts , Forms, Controls ; type {$Include ..\F1_Shell_Words\QueryCardFormWord.imp.pas} TkwQueryCardSetCanSaveState = {final} class(_QueryCardFormWord_) {* Устанавливает флаг того может ли карточка запроса писать своё состояние } protected // realized methods procedure DoQueryCardForm(aForm: TPrimQueryCardForm; const aCtx: TtfwContext); override; public // overridden public methods {$If not defined(NoScripts)} class function GetWordNameForRegister: AnsiString; override; {$IfEnd} //not NoScripts end;//TkwQueryCardSetCanSaveState implementation uses SysUtils, afwFacade {$If not defined(NoVCM)} , vcmForm {$IfEnd} //not NoVCM {$If not defined(NoScripts)} , tfwAutoregisteredDiction {$IfEnd} //not NoScripts {$If not defined(NoScripts)} , tfwScriptEngine {$IfEnd} //not NoScripts , Windows ; type _Instance_R_ = TkwQueryCardSetCanSaveState; {$Include ..\F1_Shell_Words\QueryCardFormWord.imp.pas} // start class TkwQueryCardSetCanSaveState procedure TkwQueryCardSetCanSaveState.DoQueryCardForm(aForm: TPrimQueryCardForm; const aCtx: TtfwContext); //#UC START# *4F69AE600137_4F69AF3E01C0_var* //#UC END# *4F69AE600137_4F69AF3E01C0_var* begin //#UC START# *4F69AE600137_4F69AF3E01C0_impl* aForm.CanWriteMgrSettings := aCtx.rEngine.PopBool; //#UC END# *4F69AE600137_4F69AF3E01C0_impl* end;//TkwQueryCardSetCanSaveState.DoQueryCardForm {$If not defined(NoScripts)} class function TkwQueryCardSetCanSaveState.GetWordNameForRegister: AnsiString; {-} begin Result := 'QueryCard:SetCanSaveState'; end;//TkwQueryCardSetCanSaveState.GetWordNameForRegister {$IfEnd} //not NoScripts initialization {$Include ..\F1_Shell_Words\QueryCardFormWord.imp.pas} end.
unit BTypes; { Common basic type definitions } interface {$I STD.INC} (* ************************************************************************ DESCRIPTION : Common basic type definitions REQUIREMENTS : TP5-7, D1-D7/D9-D12, FPC, VP, WDOSX EXTERNAL DATA : --- MEMORY USAGE : --- DISPLAY MODE : --- REFERENCES : --- Version Date Author Modification ------- -------- ------- ------------------------------------------ 0.10 15.04.06 W.Ehrhardt Initial version 0.11 15.04.06 we With $ifdef HAS_XTYPES 0.12 15.04.06 we FPC1_0 and pShortInt 0.13 09.09.08 we UInt32 = cardinal $ifdef HAS_CARD32 0.14 12.11.08 we Str127, Ptr2Inc 0.15 14.11.08 we BString, char8 0.16 21.11.08 we __P2I: type cast pointer to integer for masking etc 0.17 02.12.08 we Use pchar and pAnsiChar for pchar8 if possible 0.18 27.02.09 we pBoolean 0.19 14.02.12 we extended = double $ifdef SIMULATE_EXT64 ************************************************************************ *) (* ------------------------------------------------------------------------- (C) Copyright 2006-2012 Wolfgang Ehrhardt 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. ---------------------------------------------------------------------------- *) {$IFDEF BIT16} type Int8 = ShortInt; { 8 bit signed integer } Int16 = Integer; { 16 bit signed integer } Int32 = Longint; { 32 bit signed integer } UInt8 = Byte; { 8 bit unsigned integer } UInt16 = Word; { 16 bit unsigned integer } UInt32 = Longint; { 32 bit unsigned integer } Smallint = Integer; Shortstring = string; pByte = ^Byte; pBoolean = ^Boolean; pShortInt = ^ShortInt; pWord = ^Word; pSmallInt = ^Smallint; pLongint = ^Longint; {$ELSE} type Int8 = ShortInt; { 8 bit signed integer } Int16 = Smallint; { 16 bit signed integer } Int32 = Longint; { 32 bit signed integer } UInt8 = Byte; { 8 bit unsigned integer } UInt16 = Word; { 16 bit unsigned integer } {$IFDEF HAS_CARD32} UInt32 = Cardinal; { 32 bit unsigned integer } {$ELSE} UInt32 = Longint; { 32 bit unsigned integer } {$ENDIF} {$IFNDEF HAS_XTYPES} pByte = ^Byte; pBoolean = ^Boolean; pShortInt = ^ShortInt; pWord = ^Word; pSmallInt = ^Smallint; pLongint = ^Longint; {$ENDIF} {$IFDEF FPC} {$IFDEF VER1_0} pBoolean = ^Boolean; pShortInt = ^ShortInt; {$ENDIF} {$ENDIF} {$ENDIF} type Str255 = string; { Handy type to avoid problems with 32 bit and/or unicode } Str127 = string; type pInt8 = ^Int8; pInt16 = ^Int16; pInt32 = ^Int32; pUInt8 = ^UInt8; pUInt16 = ^UInt16; pUInt32 = ^UInt32; pStr255 = ^Str255; pStr127 = ^Str127; {$IFDEF BIT16} {$IFDEF V7Plus} type BString = string[255]; { String of 8 bit characters } pBString = ^BString; char8 = char; { 8 bit characters } pchar8 = pchar; {$ELSE} type BString = string[255]; { String of 8 bit characters } pBString = ^BString; char8 = char; { 8 bit characters } pchar8 = ^char; {$ENDIF} {$ELSE} {$IFDEF UNICODE} type BString = string; { String of 8 bit characters } pBString = string; char8 = string; { 8 bit characters } pchar8 = string; {$ELSE} type BString = AnsiString; { String of 8 bit characters } pBString = pAnsiString; char8 = AnsiChar; { 8 bit characters } pchar8 = pAnsiChar; {$ENDIF} {$ENDIF} {$IFDEF V7Plus} type Ptr2Inc = pByte; { Type cast to increment untyped pointer } {$ELSE} type Ptr2Inc = Longint; { Type cast to increment untyped pointer } {$ENDIF} {$IFDEF FPC} {$IFDEF VER1} type __P2I = Longint; { Type cast pointer to integer for masking etc } {$ELSE} type __P2I = PtrUInt; { Type cast pointer to integer for masking etc } {$ENDIF} {$ELSE} {$IFDEF BIT64} type __P2I = NativeInt; { Type cast pointer to integer for masking etc } {$ELSE} type __P2I = Longint; { Type cast pointer to integer for masking etc } {$ENDIF} {$ENDIF} {$IFDEF SIMULATE_EXT64} type extended = double; { Debug simulation EXT64 } {$ENDIF} implementation end.
unit CAppTemplateClass; interface //CTRL + K + I indent //CTRL + K + U unindent //CTRL + left click go to code /// <summary> /// Removes the specified item from the collection /// </summary> /// <param name="Item">The item to remove /// /// </param> /// <param name="Collection">The group containing the item /// </param> /// <remarks> /// If parameter "Item" is null, an exception is raised. /// <see cref="EArgumentNilException"/> /// </remarks> /// <returns>True if the specified item is successfully removed;/// /// otherwise False is returned. /// /// </returns> type TMemoryStream = class private {$region 'Private Members'} m_FCapacity: Longint; {$endregion } {$REGION 'PRIVATE PROCEDURES'} PROCEDURE SETCAPACITY(NEWCAPACITY: LONGINT); {$ENDREGION} protected {$region 'Protected Virtual Functions'} function Realloc(var NewCapacity: Longint): Pointer; virtual; {$endregion} {$region 'Proteced Properties'} //property Capacity: Longint read FCapacity write SetCapacity; {$endregion} public {$region 'Constructors/Destructors'} destructor Destroy; //override; {$endregion } {$region 'Public Procedures'} /// <summary> /// Removes the specified item from the collection /// </summary> /// <remarks> /// If parameter "Item" is null, an exception is raised. /// <see cref="EArgumentNilException"/> /// </remarks> procedure Clear(); /// <summary> /// Removes the specified item from the collection /// </summary> /// <remarks> /// If parameter "Item" is null, an exception is raised. /// <see cref="EArgumentNilException"/> /// </remarks> procedure Load(); /// <summary> /// Removes the specified item from the collection /// </summary> /// <remarks> /// If parameter "Item" is null, an exception is raised. /// <see cref="EArgumentNilException"/> /// </remarks> procedure LoadFromFile(const FileName: string); /// <summary> /// Removes the specified item from the collection /// </summary> /// <remarks> /// If parameter "Item" is null, an exception is raised. /// <see cref="EArgumentNilException"/> /// </remarks> procedure TestMe(); {$ENDREGION} {$region 'Public Functions' } function Write(const Buffer; Count: Longint): Longint;// override; {$endregion} end; implementation {$Region 'Implementation of Constructors/Destructors'} destructor TMemoryStream.Destroy; begin end; {$endregion} {$Region 'Implementation of Protected Procedures'} // sets capacity of a memory stream procedure TMemoryStream.SetCapacity(NewCapacity: Integer); begin //TODO end; /// <summary> /// Removes the specified item from the collection /// </summary> /// <remarks> /// If parameter "Item" is null, an exception is raised. /// <see cref="EArgumentNilException"/> /// </remarks> /// <returns> /// True if the specified item is successfully removed; /// otherwise False is returned. /// </returns> procedure TMemoryStream.TestMe; begin end; {$endregion} {$Region 'Implementation of Public Procedures'} //clears the data procedure TMemoryStream.Clear(); var num: integer; begin //TODO end; //loads the data procedure TMemoryStream.Load(); begin end; /// <summary> /// Removes the specified item from the collection /// </summary> procedure TMemoryStream.LoadFromFile(const FileName: string); begin end; {$endregion} {$region 'Implementation of Protected Functions'} //realocate memory function TMemoryStream.Realloc(var NewCapacity: Integer) : Pointer; begin //TODO Result := nil; end; {$endregion} {$region 'Implementation of Public Functions'} function TMemoryStream.Write(const Buffer; Count: Longint) : Longint; // override; begin //TODO end; {$endregion} END.
unit TreeViewWordsPack; // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\TreeViewWordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "TreeViewWordsPack" MUID: (512F47C80388) {$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc} interface {$If NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3IntfUses ; {$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoVCL) implementation {$If NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3ImplUses , ComCtrls , tfwClassLike , tfwScriptingInterfaces , TypInfo , TreeNodeWordsPack , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *512F47C80388impl_uses* //#UC END# *512F47C80388impl_uses* ; type TkwPopTreeViewGetItem = {final} class(TtfwClassLike) {* Слово скрипта pop:TreeView:GetItem } private function GetItem(const aCtx: TtfwContext; aTreeView: TTreeView; anIndex: Integer): TTreeNode; {* Реализация слова скрипта pop:TreeView:GetItem } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopTreeViewGetItem function TkwPopTreeViewGetItem.GetItem(const aCtx: TtfwContext; aTreeView: TTreeView; anIndex: Integer): TTreeNode; {* Реализация слова скрипта pop:TreeView:GetItem } //#UC START# *55C9CBCD0127_55C9CBCD0127_512F402F01BA_Word_var* //#UC END# *55C9CBCD0127_55C9CBCD0127_512F402F01BA_Word_var* begin //#UC START# *55C9CBCD0127_55C9CBCD0127_512F402F01BA_Word_impl* Result := aTreeView.Items[anIndex]; //#UC END# *55C9CBCD0127_55C9CBCD0127_512F402F01BA_Word_impl* end;//TkwPopTreeViewGetItem.GetItem class function TkwPopTreeViewGetItem.GetWordNameForRegister: AnsiString; begin Result := 'pop:TreeView:GetItem'; end;//TkwPopTreeViewGetItem.GetWordNameForRegister function TkwPopTreeViewGetItem.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TTreeNode); end;//TkwPopTreeViewGetItem.GetResultTypeInfo function TkwPopTreeViewGetItem.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 2; end;//TkwPopTreeViewGetItem.GetAllParamsCount function TkwPopTreeViewGetItem.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TTreeView), TypeInfo(Integer)]); end;//TkwPopTreeViewGetItem.ParamsTypes procedure TkwPopTreeViewGetItem.DoDoIt(const aCtx: TtfwContext); var l_aTreeView: TTreeView; var l_anIndex: Integer; begin try l_aTreeView := TTreeView(aCtx.rEngine.PopObjAs(TTreeView)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aTreeView: TTreeView : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_anIndex := aCtx.rEngine.PopInt; except on E: Exception do begin RunnerError('Ошибка при получении параметра anIndex: Integer : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(GetItem(aCtx, l_aTreeView, l_anIndex)); end;//TkwPopTreeViewGetItem.DoDoIt initialization TkwPopTreeViewGetItem.RegisterInEngine; {* Регистрация pop_TreeView_GetItem } TtfwTypeRegistrator.RegisterType(TypeInfo(TTreeView)); {* Регистрация типа TTreeView } TtfwTypeRegistrator.RegisterType(TypeInfo(TTreeNode)); {* Регистрация типа TTreeNode } TtfwTypeRegistrator.RegisterType(TypeInfo(Integer)); {* Регистрация типа Integer } {$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoVCL) end.
unit ExtTimer; interface uses SyncObjs; type TTimerProc = procedure of object; TExtTimer = class public constructor Create(aInterval : integer); destructor Destroy; override; private fLock : TCriticalSection; procedure EnterSync; procedure LeaveSync; private fInterval : integer; fResolution : integer; fId : integer; fEnabled : boolean; procedure SetEnabled(aEnabled : boolean); procedure SetInterval(aInterval : integer); public property Enabled : boolean read fEnabled write SetEnabled; property Resolution : integer read fResolution write fResolution; property Interval : integer read fInterval write SetInterval; public OnTimer : TTimerProc; private procedure Tick; end; implementation uses Windows, mmSystem; procedure TimerProc(uTimerID, uMessage : UINT; dwUser, dw1, dw2 : DWORD); stdcall; var Timer : TExtTimer absolute dwUser; begin Timer.Tick; end; constructor TExtTimer.Create(aInterval : integer); begin inherited Create; Assert(aInterval > 0, 'TExtTimer.Create: Invalid timer interval'); fLock := TCriticalSection.Create; fInterval := aInterval; fResolution := 10; end; destructor TExtTimer.Destroy; begin Enabled := false; fLock.Free; inherited; end; procedure TExtTimer.EnterSync; begin fLock.Enter; end; procedure TExtTimer.LeaveSync; begin fLock.Leave; end; procedure TExtTimer.SetEnabled(aEnabled : boolean); begin if aEnabled <> fEnabled then begin fEnabled := aEnabled; if fId <> 0 then begin EnterSync; try timeKillEvent(fId); fId := 0; finally LeaveSync; end; end; if fEnabled then fId := timeSetEvent(fInterval, fResolution, @TimerProc, integer(Self), TIME_PERIODIC); end; end; procedure TExtTimer.SetInterval(aInterval : integer); begin fInterval := aInterval; if Enabled then begin Enabled := false; Enabled := true; end; end; procedure TExtTimer.Tick; begin if Enabled and assigned(OnTimer) then try EnterSync; try OnTimer; finally LeaveSync; end; except Assert(false); end; end; end.
unit PHPUtils; {$mode delphi} {** * Light PHP Edit project * * This file is part of the "Mini Library" * * @url http://www.sourceforge.net/projects/minilib * @license modifiedLGPL (modified of http://www.gnu.org/licenses/lgpl.html) * See the file COPYING.MLGPL, included in this distribution, * @author Zaher Dirkey *} interface uses SysUtils, Classes, Dialogs, IniFiles; type TPHPStrings = class(THashedStringList) public function GetSplitName(S: string): string; function GetSplitValue(S: string): string; function SetSplitValue(S, Value: string): string; function IndexOfName(const Name: string): Integer; override; function IndexOfLastName(const Name: string): Integer; function IndexOfNameValue(const Name, Value: string): Integer; function FindValue(const Name, Value: string): Integer; end; { TPHPIniFile } TPHPIniFile = class(TCustomIniFile) private FSections: TStringList; function AddSection(const Section: string): TPHPStrings; function GetCaseSensitive: Boolean; procedure LoadValues; procedure SetCaseSensitive(Value: Boolean); public constructor Create(const AFileName: string; AEscapeLineFeeds : Boolean = False); override; destructor Destroy; override; procedure Clear; procedure DeleteKey(const Section, Ident: string); override; procedure EraseSection(const Section: string); override; procedure GetStrings(List: TStrings); procedure ReadSection(const Section: string; Strings: TStrings); override; procedure ReadSections(Strings: TStrings); override; procedure ReadSectionValues(const Section: string; Strings: TStrings); override; function ReadString(const Section, Ident, Default: string): string; override; procedure SetStrings(List: TStrings); procedure UpdateFile; override; procedure WriteString(const Section, Ident, Value: string); override; procedure AppendString(const Section, Ident, Value: string); function FindValue(const Section, Ident, Value: string): string; procedure CommentString(const Section, Ident, Value: string); property CaseSensitive: Boolean read GetCaseSensitive write SetCaseSensitive; end; const cNameValueSeparator = '='; implementation { TPHPStrings } function TPHPStrings.FindValue(const Name, Value: string): Integer; var P: Integer; S: string; I: Integer; begin Result := -1; for I := 0 to GetCount - 1 do begin S := Get(I); P := AnsiPos(cNameValueSeparator, S); if (P <> 0) and (SameText(GetSplitName(S), Name)) and (AnsiPos(UpperCase(Value), UpperCase(GetSplitValue(S))) > 0) then begin Result := I; break; end; end; end; function TPHPStrings.GetSplitName(S: string): string; var P: Integer; begin P := AnsiPos(cNameValueSeparator, S); if (P <> 0) then begin Result := TrimRight(Copy(S, 1, P - 1)); end else Result := ''; end; function TPHPStrings.GetSplitValue(S: string): string; var P: Integer; begin P := AnsiPos(cNameValueSeparator, S); if (P <> 0) then begin Result := Copy(S, P + 1, MaxInt); P := AnsiPos(';', Result); //must ingore the qouted strings when search for ; if P > 0 then Result := Trim(Copy(Result, 1, P - 1)) else Result := Trim(Result); end; end; function TPHPStrings.IndexOfLastName(const Name: string): Integer; var P: Integer; S: string; I: Integer; begin Result := -1; for I := 0 to GetCount - 1 do begin S := Get(I); P := AnsiPos(cNameValueSeparator, S); if (P <> 0) and (SameText(GetSplitName(S), Name)) then begin Result := I; end; end; end; function TPHPStrings.IndexOfName(const Name: string): Integer; var P: Integer; S: string; I: Integer; begin Result := -1; for I := 0 to GetCount - 1 do begin S := Get(I); P := AnsiPos(cNameValueSeparator, S); if (P <> 0) then if (SameText(GetSplitName(S), Name)) then begin Result := I; break; end; end; end; function TPHPStrings.IndexOfNameValue(const Name, Value: string): Integer; var P: Integer; S: string; I: Integer; begin Result := -1; for I := 0 to GetCount - 1 do begin S := Get(I); P := AnsiPos(cNameValueSeparator, S); if (P <> 0) and (SameText(GetSplitName(S), Name)) and (SameText(GetSplitValue(S), Value)) then begin Result := I; break; end; end; end; function TPHPStrings.SetSplitValue(S, Value: string): string; var P: Integer; begin P := AnsiPos(cNameValueSeparator, S); if (P <> 0) then begin Result := Trim(Copy(S, 1, P - 1)); P := AnsiPos(';', S); if P > 0 then Result := Result + ' = ' + Value + Copy(S, P, MaxInt) else Result := Result + ' = ' + Value; end; end; { TPHPIniFile } constructor TPHPIniFile.Create(const AFileName: string; AEscapeLineFeeds: Boolean); begin inherited Create(AFileName); FSections := TPHPStrings.Create; // FSections.CaseSensitive := True; LoadValues; end; destructor TPHPIniFile.Destroy; begin if FSections <> nil then Clear; FSections.Free; inherited Destroy; end; function TPHPIniFile.AddSection(const Section: string): TPHPStrings; begin Result := TPHPStrings.Create; try TPHPStrings(Result).CaseSensitive := CaseSensitive; FSections.AddObject(Section, Result); except Result.Free; raise; end; end; procedure TPHPIniFile.Clear; var I: Integer; begin for I := 0 to FSections.Count - 1 do TObject(FSections.Objects[I]).Free; FSections.Clear; end; procedure TPHPIniFile.DeleteKey(const Section, Ident: string); var I, J: Integer; Strings: TStrings; begin I := FSections.IndexOf(Section); if I >= 0 then begin Strings := TStrings(FSections.Objects[I]); J := Strings.IndexOfName(Ident); if J >= 0 then Strings.Delete(J); end; end; procedure TPHPIniFile.EraseSection(const Section: string); var I: Integer; begin I := FSections.IndexOf(Section); if I >= 0 then begin TStrings(FSections.Objects[I]).Free; FSections.Delete(I); end; end; function TPHPIniFile.GetCaseSensitive: Boolean; begin Result := FSections.CaseSensitive; end; procedure TPHPIniFile.GetStrings(List: TStrings); var I, J: Integer; Strings: TStrings; S: string; begin List.BeginUpdate; try for I := 0 to FSections.Count - 1 do begin List.Add('[' + FSections[I] + ']'); Strings := TStrings(FSections.Objects[I]); for J := 0 to Strings.Count - 1 do begin S := Strings[J]; List.Add(S); end; if S <> '' then //if last line in section not empty we add a new empty line List.Add(''); end; finally List.EndUpdate; end; end; procedure TPHPIniFile.LoadValues; var List: TStringList; begin if (FileName <> '') and FileExists(FileName) then begin List := TStringList.Create; try List.LoadFromFile(FileName); SetStrings(List); finally List.Free; end; end else Clear; end; procedure TPHPIniFile.ReadSection(const Section: string; Strings: TStrings); var I, J: Integer; SectionStrings: TStrings; begin Strings.BeginUpdate; try Strings.Clear; I := FSections.IndexOf(Section); if I >= 0 then begin SectionStrings := TStrings(FSections.Objects[I]); for J := 0 to SectionStrings.Count - 1 do Strings.Add(SectionStrings.Names[J]); end; finally Strings.EndUpdate; end; end; procedure TPHPIniFile.ReadSections(Strings: TStrings); begin Strings.Assign(FSections); end; procedure TPHPIniFile.ReadSectionValues(const Section: string; Strings: TStrings); var I: Integer; begin Strings.BeginUpdate; try Strings.Clear; I := FSections.IndexOf(Section); if I >= 0 then Strings.Assign(TStrings(FSections.Objects[I])); finally Strings.EndUpdate; end; end; function TPHPIniFile.ReadString(const Section, Ident, Default: string): string; var I: Integer; Strings: TPHPStrings; begin I := FSections.IndexOf(Section); if I >= 0 then begin Strings := (FSections.Objects[I] as TPHPStrings); I := Strings.IndexOfName(Ident); if I >= 0 then begin Result := Strings.GetSplitValue(Strings[I]); Exit; end; end; Result := Default; end; procedure TPHPIniFile.SetCaseSensitive(Value: Boolean); var I: Integer; begin if Value <> FSections.CaseSensitive then begin FSections.CaseSensitive := Value; for I := 0 to FSections.Count - 1 do with TPHPStrings(FSections.Objects[I]) do begin CaseSensitive := Value; Changed; end; TPHPStrings(FSections).Changed; end; end; procedure TPHPIniFile.SetStrings(List: TStrings); var I: Integer; S: string; Strings: TStrings; begin Clear; Strings := nil; for I := 0 to List.Count - 1 do begin S := Trim(List[I]); if (S <> '') and (S[1] = '[') and (S[Length(S)] = ']') then begin Delete(S, 1, 1); SetLength(S, Length(S) - 1); Strings := AddSection(Trim(S)); end else if Strings <> nil then Strings.Add(S); end; end; procedure TPHPIniFile.UpdateFile; var List: TStringList; begin List := TStringList.Create; try GetStrings(List); List.SaveToFile(FileName); finally List.Free; end; end; procedure TPHPIniFile.WriteString(const Section, Ident, Value: string); var I: Integer; Strings: TPHPStrings; begin I := FSections.IndexOf(Section); if I >= 0 then Strings := (FSections.Objects[I] as TPHPStrings) else Strings := AddSection(Section); I := Strings.IndexOfName(Ident); if I >= 0 then Strings[I] := Strings.SetSplitValue(Strings[I], Value) else begin I := Strings.IndexOfName(';' + Ident); if I >= 0 then Strings[I] := Strings.SetSplitValue(Strings[I], Value) else Strings.Add(Ident + ' = ' + Value); end; end; procedure TPHPIniFile.AppendString(const Section, Ident, Value: string); var I, J: Integer; Strings: TPHPStrings; begin I := FSections.IndexOf(Section); if I >= 0 then Strings := (FSections.Objects[I] as TPHPStrings) else Strings := AddSection(Section); I := Strings.IndexOfNameValue(Ident, Value); // if ident with value is found if I >= 0 then Strings[I] := Strings.SetSplitValue(Strings[I], Value) else begin I := Strings.IndexOfNameValue(';' + Ident, Value); // if ident with value is commented if I >= 0 then Strings[I] := Strings.SetSplitValue(Strings[I], Value) else begin I := Strings.IndexOfLastName(Ident); // find the near of idents J := Strings.IndexOfLastName(';' + Ident); if I < J then I := J; if I >= 0 then Strings.Insert(I + 1, Ident + ' = ' + Value) else Strings.Add(Ident + ' = ' + Value); end; end end; procedure TPHPIniFile.CommentString(const Section, Ident, Value: string); var I: Integer; Strings: TPHPStrings; begin I := FSections.IndexOf(Section); if I >= 0 then Strings := (FSections.Objects[I] as TPHPStrings) else Strings := AddSection(Section); I := Strings.IndexOfNameValue(Ident, Value); // if ident with value is found if I >= 0 then Strings[I] := ';' + Ident + ' = ' + Value; end; function TPHPIniFile.FindValue(const Section, Ident, Value: string): string; var I: Integer; Strings: TPHPStrings; begin I := FSections.IndexOf(Section); if I >= 0 then Strings := (FSections.Objects[I] as TPHPStrings) else Strings := AddSection(Section); I := Strings.FindValue(Ident, Value); // if ident with value is found if I >= 0 then Result := Strings.GetSplitValue(Strings[I]) else begin I := Strings.FindValue(';' + Ident, Value); // if ident with value is commented if I >= 0 then Result := Strings.GetSplitValue(Strings[I]); end; end; end.
unit LoggerInterface; interface uses System.SyncObjs; type TMessageStatus = (msCritical, msWarning, msInfo); ILogger = interface (IInterface) procedure Add(AMessage: string; AMessageStatus: TMessageStatus); function GetAddMessageEvent: TEvent; function GetLastMessages: TArray<String>; property AddMessageEvent: TEvent read GetAddMessageEvent; end; implementation end.
{ DBAExplorer - Oracle Admin Management Tool Copyright (C) 2008 Alpaslan KILICKAYA 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 3 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, see <http://www.gnu.org/licenses/>. } unit OraUser; interface uses Classes, SysUtils, Ora, OraStorage, DB,DBQuery, Forms, Dialogs, VirtualTable, OraRole, OraSysPrivs, OraQuota; type TUser = class(TObject) private FUSERNAME, FUSER_ID, FPASSWORD, FACCOUNT_STATUS, FLOCK_DATE, FEXPIRY_DATE, FDEFAULT_TABLESPACE, FTEMPORARY_TABLESPACE, FCREATED, FPROFILE, FINITIAL_RSRC_CONSUMER_GROUP, FEXTERNAL_NAME: String; FRoleList : TRoleList; FPrivList: TPrivList; FQuotaList: TQuotaList; FOraSession: TOraSession; function GetDSProfilesList: TVirtualTable; function GetDSTemporaryTablespaceList: TVirtualTable; function GetUserDetail: String; function GetStatus: string; public property USERNAME: String read FUSERNAME write FUSERNAME; property USER_ID: String read FUSER_ID write FUSER_ID; property PASSWORD: String read FPASSWORD write FPASSWORD; property ACCOUNT_STATUS: String read FACCOUNT_STATUS write FACCOUNT_STATUS; property LOCK_DATE: String read FLOCK_DATE write FLOCK_DATE; property EXPIRY_DATE: String read FEXPIRY_DATE write FEXPIRY_DATE; property DEFAULT_TABLESPACE: String read FDEFAULT_TABLESPACE write FDEFAULT_TABLESPACE; property TEMPORARY_TABLESPACE: String read FTEMPORARY_TABLESPACE write FTEMPORARY_TABLESPACE; property CREATED: String read FCREATED write FCREATED; property PROFILE: String read FPROFILE write FPROFILE; property INITIAL_RSRC_CONSUMER_GROUP: String read FINITIAL_RSRC_CONSUMER_GROUP write FINITIAL_RSRC_CONSUMER_GROUP; property EXTERNAL_NAME: String read FEXTERNAL_NAME write FEXTERNAL_NAME; property RoleList : TRoleList read FRoleList write FRoleList; property PrivList : TPrivList read FPrivList write FPrivList; property QuotaList: TQuotaList read FQuotaList write FQuotaList; property DSProfilesList: TVirtualTable read GetDSProfilesList; property DSTemporaryTablespaceList: TVirtualTable read GetDSTemporaryTablespaceList; property Status: String read GetStatus; property OraSession: TOraSession read FOraSession write FOraSession; procedure SetDDL; function GetDDL: string; function GetAlterDDL(AUser: TUser): string; function CreateUser(UserScript: string) : boolean; function AlterUser(UserScript: string) : boolean; function DropUser: boolean; constructor Create; destructor Destroy; override; end; function GetUsers: string; function GetUsersAndRoles: string; implementation uses Util, frmSchemaBrowser, OraScripts, Languages; resourcestring strUserDrop = 'User %s has been dropped.'; strUserAltered = 'User %s has been altered.'; strUserCreated = 'User %s has been created.'; function GetUsers: string; begin result := 'select * from sys.all_users order by username '; end; function GetUsersAndRoles: string; begin result := 'SELECT username name FROM all_users ' +'UNION ' +'SELECT ''PUBLIC'' FROM DUAL ' +'ORDER BY 1 asc '; end; constructor TUser.Create; begin inherited; FRoleList := TRoleList.Create; FPrivList := TPrivList.Create; FQuotaList:= TQuotaList.Create; end; destructor TUser.destroy; begin FRoleList.Free; FPrivList.Free; FQuotaList.Free; inherited; end; function TUser.GetUserDetail: String; begin Result := 'Select * FROM dba_users ' +'WHERE USERNAME = :pName '; end; function TUser.GetStatus: string; begin result := FUSERNAME+' ( Created: '+FCREATED +' )'; end; function TUser.GetDSProfilesList: TVirtualTable; var q1: TOraQuery; begin result := TVirtualTable.Create(nil); q1 := TOraQuery.Create(nil); q1.Session := OraSession; q1.SQL.Text := GetProfiles; q1.Open; CopyDataSet(q1, result); q1.Close; end; function TUser.GetDSTemporaryTablespaceList: TVirtualTable; var q1: TOraQuery; begin result := TVirtualTable.Create(nil); q1 := TOraQuery.Create(nil); q1.Session := OraSession; q1.SQL.Text := GetTemporaryTablespaces; q1.Open; CopyDataSet(q1, result); q1.Close; end; procedure TUser.SetDDL; var q1: TOraQuery; begin if FUSERNAME = '' then exit; q1 := TOraQuery.Create(nil); q1.Session := OraSession; q1.SQL.Text := GetUserDetail; q1.ParamByName('pName').AsString := FUSERNAME; q1.Open; FUSERNAME := q1.FieldByName('USERNAME').AsString; FUSER_ID := q1.FieldByName('USER_ID').AsString; FPASSWORD := q1.FieldByName('PASSWORD').AsString; FACCOUNT_STATUS := q1.FieldByName('ACCOUNT_STATUS').AsString; FLOCK_DATE := q1.FieldByName('LOCK_DATE').AsString; FEXPIRY_DATE := q1.FieldByName('EXPIRY_DATE').AsString; FDEFAULT_TABLESPACE := q1.FieldByName('DEFAULT_TABLESPACE').AsString; FTEMPORARY_TABLESPACE := q1.FieldByName('TEMPORARY_TABLESPACE').AsString; FCREATED := q1.FieldByName('CREATED').AsString; FPROFILE := q1.FieldByName('PROFILE').AsString; FINITIAL_RSRC_CONSUMER_GROUP := q1.FieldByName('INITIAL_RSRC_CONSUMER_GROUP').AsString; FEXTERNAL_NAME := q1.FieldByName('EXTERNAL_NAME').AsString; Q1.close; FRoleList.OraSession := FOraSession; FRoleList.GRANTEE := FUSERNAME; FRoleList.SetDDL; FPrivList.OraSession := FOraSession; FPrivList.GRANTEE := FUSERNAME; FPrivList.SetDDL; FQuotaList.OraSession := FOraSession; FQuotaList.USER := FUSERNAME; FQuotaList.SetDDL; end; function TUser.GetDDL: string; begin result := 'CREATE USER '+FUSERNAME+' IDENTIFIED BY '+ FPASSWORD; if FDEFAULT_TABLESPACE <> '' then result := result + ln + 'DEFAULT TABLESPACE '+FDEFAULT_TABLESPACE; if FTEMPORARY_TABLESPACE <> '' then result := result + ln + 'TEMPORARY TABLESPACE '+FTEMPORARY_TABLESPACE; if FPROFILE <> '' then result := result + ln + 'PROFILE '+FPROFILE; if FEXPIRY_DATE <> '' then result := result + ln + 'PASSWORD EXPIRE '; if FACCOUNT_STATUS <> 'OPEN' then result := result + ln + 'ACCOUNT LOCK ' else result := result + ln + 'ACCOUNT UNLOCK '; result := result +';'; result := result + ln; result := result + FRoleList.GetDDL; result := result + ln; result := result + FPrivList.GetDDL; result := result + ln; result := result + FQuotaList.GetDDL; end; function TUser.GetAlterDDL(AUser: TUser): string; begin if FPASSWORD <> '' then result := result + ln + ' IDENTIFIED BY '+FPASSWORD; if (FDEFAULT_TABLESPACE <> '') and (FDEFAULT_TABLESPACE <> Auser.DEFAULT_TABLESPACE) then result := result + ln + 'DEFAULT TABLESPACE '+FDEFAULT_TABLESPACE; if (FTEMPORARY_TABLESPACE <> '') and (FTEMPORARY_TABLESPACE <> AUser.TEMPORARY_TABLESPACE) then result := result + ln + 'TEMPORARY TABLESPACE '+FTEMPORARY_TABLESPACE; if (FPROFILE <> '') and (FPROFILE <> AUser.PROFILE) then result := result + ln + 'PROFILE '+FPROFILE; if (FEXPIRY_DATE <> '') and (FEXPIRY_DATE <> AUser.EXPIRY_DATE) then result := result + ln + 'PASSWORD EXPIRE '; if (FACCOUNT_STATUS <> AUser.ACCOUNT_STATUS) then begin if (FACCOUNT_STATUS <> 'OPEN') then result := result + ln + 'ACCOUNT LOCK ' else result := result + ln + 'ACCOUNT UNLOCK '; end; if result <> '' then result := 'ALTER USER '+FUSERNAME + result +';'+ln; result := result + FRoleList.GetAlterDDL(AUser.RoleList); result := result + ln; result := result + FPrivList.GetAlterDDL(AUser.PrivList); result := result + ln; result := result + FQuotaList.GetDDL; end; function TUser.CreateUser(UserScript: string) : boolean; begin result := false; if FUSERNAME = '' then exit; result := ExecSQL(UserScript,Format(ChangeSentence('strUserCreated',strUserCreated),[FUSERNAME]) , FOraSession); end; function TUser.AlterUser(UserScript: string) : boolean; begin result := false; if FUSERNAME = '' then exit; result := ExecSQL(UserScript, Format(ChangeSentence('strUserAltered',strUserAltered),[FUSERNAME]), FOraSession); end; function TUser.DropUser: boolean; var FSQL: string; begin result := false; if FUSERNAME = '' then exit; FSQL := 'drop user '+FUSERNAME; result := ExecSQL(FSQL, Format(ChangeSentence('strUserDrop',strUserDrop),[FUSERNAME]), FOraSession); end; end.
unit Eagle.Alfred.HelpCommand; interface uses System.SysUtils, Console, Eagle.ConsoleIO, Eagle.Alfred.Command, Eagle.Alfred.CreateCommand; type THelpCommand = class(TInterfacedObject, ICommand) private FConsoleIO: IConsoleIO; public constructor Create(ConsoleIO: IConsoleIO); procedure Execute; procedure Help; end; implementation { THelpCommand } constructor THelpCommand.Create(ConsoleIO: IConsoleIO); begin FConsoleIO := ConsoleIO; end; procedure THelpCommand.Execute; begin Help; end; procedure THelpCommand.Help; begin FConsoleIO.WriteInfo(' Alfred - Code Generate for Delphi'); FConsoleIO.WriteInfo('-----------------------------------------------------'); FConsoleIO.WriteInfo('Para obter mais informações sobre um comando específico,'); FConsoleIO.WriteInfo('digite nome_do_comando HELP'); FConsoleIO.WriteInfo(''); FConsoleIO.WriteInfo('CREATE Cria arquivos relacionados às operções de CRUD'); FConsoleIO.WriteInfo('PROJECT Gerencia informações relacionadas ao projeto'); FConsoleIO.WriteInfo('MIGRATE Gerencia a criação e execução dos arquivos de migração do DB'); FConsoleIO.WriteInfo(''); end; end.
unit YWRTLUtils; interface type TAttributeType = class of TCustomAttribute; function GetStoredAttributeNames(T: TClass) : TArray<String>; function GetClassesWithAttributes(T : TClass; S : String): TArray<TClass>; overload; function GetClassesWithAttributes(T : TClass; S : TAttributeType): TArray<TClass>; overload; function GetAttribute(T : TClass; S : TAttributeType): TCustomAttribute; function GetAttributes(T : TClass; S : TAttributeType): TArray<TCustomAttribute>; implementation uses classes, sysutils, System.Rtti, Generics.Collections; function GetAttribute(T : TClass; S : TAttributeType): TCustomAttribute; var C : TRttiContext; I : TRttiType; A : TCustomAttribute; begin Result := nil; C := TRttiContext.Create; try I := C.GetType(T); for A in I.GetAttributes do begin if A is S then begin Result := A; exit; end; end; finally C.Free; end; end; function GetAttributes(T : TClass; S : TAttributeType): TArray<TCustomAttribute>; var C : TRttiContext; I : TRttiType; A : TCustomAttribute; N : integer; begin SetLength(Result,20); N := 0; C := TRttiContext.Create; try I := C.GetType(T); for A in I.GetAttributes do begin if A is S then begin if N=Length(Result) then SetLength(Result,Length(Result)+20); Result[N] := A; inc(N); end; end; finally C.Free; end; SetLength(Result,N); end; function GetClassesWithAttributes(T : TClass; S : String): TArray<TClass>; var C : TRttiContext; I : TRttiType; A : TCustomAttribute; S1,S2 : integer; begin S := S.ToUpper.Trim; C := TRttiContext.Create; S1 := 0; S2 := 0; try for I in C.GetTypes do begin if I.IsInstance and I.AsInstance.MetaclassType.InheritsFrom(T) then begin for A in I.GetAttributes do begin if (A is StoredAttribute)and(StoredAttribute(A).Name.ToUpper.Trim=S) then begin if S1=S2 then begin inc(s2,20); setlength(Result,s2); end; Result[S1] := I.AsInstance.MetaclassType; inc(S1); end; end; end; end; setlength(Result,s1); finally C.Free; end; end; function GetClassesWithAttributes(T : TClass; S : TAttributeType): TArray<TClass>; var C : TRttiContext; I : TRttiType; A : TCustomAttribute; S1,S2 : integer; begin C := TRttiContext.Create; S1 := 0; S2 := 0; try for I in C.GetTypes do begin if I.IsInstance and I.AsInstance.MetaclassType.InheritsFrom(T) then begin for A in I.GetAttributes do begin if A is S then begin if S1=S2 then begin inc(s2,20); setlength(Result,s2); end; Result[S1] := I.AsInstance.MetaclassType; inc(S1); end; end; end; end; setlength(Result,s1); finally C.Free; end; end; function GetStoredAttributeNames(T:TClass) : TArray<String>; var C : TRttiContext; I : TRttiType; A : TCustomAttribute; S1,S2 : integer; begin C := TRttiContext.Create; s1 := 0; s2 := 0; try I := C.GetType(T); for A in I.GetAttributes do begin if A is StoredAttribute then begin if s1=s2 then begin inc(s2,20); setlength(Result,s2); end; Result[s1] := StoredAttribute(A).Name; inc(s1); end; end; SetLength(Result,s1); finally C.Free; end; end; end.
unit K358976777; {* [Requestlink:358976777] } // Модуль: "w:\archi\source\projects\Archi\Tests\K358976777.pas" // Стереотип: "TestCase" // Элемент модели: "TK358976777" MUID: (4F8FDEE8009B) {$Include w:\archi\source\projects\Archi\arDefine.inc} interface {$If Defined(nsTest) AND Defined(InsiderTest)} uses l3IntfUses {$If NOT Defined(NoScripts)} , ArchiInsiderTest {$IfEnd} // NOT Defined(NoScripts) ; type TK358976777 = class({$If NOT Defined(NoScripts)} TArchiInsiderTest {$IfEnd} // NOT Defined(NoScripts) ) {* [Requestlink:358976777] } protected function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } end;//TK358976777 {$IfEnd} // Defined(nsTest) AND Defined(InsiderTest) implementation {$If Defined(nsTest) AND Defined(InsiderTest)} uses l3ImplUses , TestFrameWork //#UC START# *4F8FDEE8009Bimpl_uses* //#UC END# *4F8FDEE8009Bimpl_uses* ; {$If NOT Defined(NoScripts)} function TK358976777.GetFolder: AnsiString; {* Папка в которую входит тест } begin Result := 'DialogTest'; end;//TK358976777.GetFolder function TK358976777.GetModelElementGUID: AnsiString; {* Идентификатор элемента модели, который описывает тест } begin Result := '4F8FDEE8009B'; end;//TK358976777.GetModelElementGUID initialization TestFramework.RegisterTest(TK358976777.Suite); {$IfEnd} // NOT Defined(NoScripts) {$IfEnd} // Defined(nsTest) AND Defined(InsiderTest) end.
unit Outliner_Form; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "Forms" // Автор: Инишев Д.А. // Модуль: "w:/common/components/gui/Garant/Daily/Forms/Outliner_Form.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<VCMForm::Class>> Shared Delphi Operations For Tests::TestForms::Forms::Outliner::OutlinerForm // // Форма для тестирования списка // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! interface {$If defined(nsTest) AND not defined(NoVCM)} uses vcmInterfaces, vcmEntityForm, vcmUserControls, l3StringIDEx, vtOutlinerControl {$If not defined(NoScripts)} , tfwScriptingInterfaces {$IfEnd} //not NoScripts {$If not defined(NoScripts)} , tfwInteger {$IfEnd} //not NoScripts {$If not defined(NoScripts)} , kwBynameControlPush {$IfEnd} //not NoScripts {$If not defined(NoScripts)} , tfwControlString {$IfEnd} //not NoScripts , OutlinerForm_ut_OutlinerForm_UserType, Classes {a}, l3InterfacedComponent {a}, vcmComponent {a}, vcmBaseEntities {a}, vcmEntities {a}, vcmExternalInterfaces {a} ; {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} const { OutlinerFormIDs } fm_OutlinerFormForm : TvcmFormDescriptor = (rFormID : (rName : 'OutlinerFormForm'; rID : 0); rFactory : nil); { Идентификатор формы TOutlinerFormForm } type OutlinerFormFormDef = interface(IUnknown) {* Идентификатор формы OutlinerForm } ['{0BC56D56-6AF0-47F9-9D0B-4AE7FEEE4483}'] end;//OutlinerFormFormDef TOutlinerFormForm = {final form} class(TvcmEntityForm, OutlinerFormFormDef) {* Форма для тестирования списка } Entities : TvcmEntities; private // private fields f_TreeControl : TvtOutlinerControl; {* Поле для свойства TreeControl} protected procedure MakeControls; override; protected // overridden protected methods procedure InitControls; override; {* Процедура инициализации контролов. Для перекрытия в потомках } public // public properties property TreeControl: TvtOutlinerControl read f_TreeControl; end;//TOutlinerFormForm {$IfEnd} //nsTest AND not NoVCM implementation {$R *.DFM} {$If defined(nsTest) AND not defined(NoVCM)} uses Controls {$If not defined(NoScripts)} , tfwScriptEngine {$IfEnd} //not NoScripts , l3MessageID ; {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} var { Локализуемые строки ut_OutlinerFormLocalConstants } str_ut_OutlinerFormCaption : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ut_OutlinerFormCaption'; rValue : 'Форма для тестирования списка'); { Заголовок пользовательского типа "Форма для тестирования списка" } type Tkw_OutlinerForm_Control_TreeControl = class(TtfwControlString) {* Слово словаря для идентификатора контрола TreeControl ---- *Пример использования*: [code] контрол::TreeControl TryFocus ASSERT [code] } protected // overridden protected methods {$If not defined(NoScripts)} function GetString: AnsiString; override; {$IfEnd} //not NoScripts end;//Tkw_OutlinerForm_Control_TreeControl // start class Tkw_OutlinerForm_Control_TreeControl {$If not defined(NoScripts)} function Tkw_OutlinerForm_Control_TreeControl.GetString: AnsiString; {-} begin Result := 'TreeControl'; end;//Tkw_OutlinerForm_Control_TreeControl.GetString {$IfEnd} //not NoScripts type Tkw_OutlinerForm_Control_TreeControl_Push = class(TkwBynameControlPush) {* Слово словаря для контрола TreeControl ---- *Пример использования*: [code] контрол::TreeControl:push pop:control:SetFocus ASSERT [code] } protected // overridden protected methods {$If not defined(NoScripts)} procedure DoDoIt(const aCtx: TtfwContext); override; {$IfEnd} //not NoScripts end;//Tkw_OutlinerForm_Control_TreeControl_Push // start class Tkw_OutlinerForm_Control_TreeControl_Push {$If not defined(NoScripts)} procedure Tkw_OutlinerForm_Control_TreeControl_Push.DoDoIt(const aCtx: TtfwContext); {-} begin aCtx.rEngine.PushString('TreeControl'); inherited; end;//Tkw_OutlinerForm_Control_TreeControl_Push.DoDoIt {$IfEnd} //not NoScripts type Tkw_Form_OutlinerForm = class(TtfwControlString) {* Слово словаря для идентификатора формы OutlinerForm ---- *Пример использования*: [code] 'aControl' форма::OutlinerForm TryFocus ASSERT [code] } protected // overridden protected methods {$If not defined(NoScripts)} function GetString: AnsiString; override; {$IfEnd} //not NoScripts end;//Tkw_Form_OutlinerForm // start class Tkw_Form_OutlinerForm {$If not defined(NoScripts)} function Tkw_Form_OutlinerForm.GetString: AnsiString; {-} begin Result := 'OutlinerFormForm'; end;//Tkw_Form_OutlinerForm.GetString {$IfEnd} //not NoScripts type Tkw_OutlinerForm_TreeControl_ControlInstance = class(TtfwWord) {* Слово словаря для доступа к экземпляру контрола TreeControl формы OutlinerForm } protected // realized methods {$If not defined(NoScripts)} procedure DoDoIt(const aCtx: TtfwContext); override; {$IfEnd} //not NoScripts end;//Tkw_OutlinerForm_TreeControl_ControlInstance // start class Tkw_OutlinerForm_TreeControl_ControlInstance {$If not defined(NoScripts)} procedure Tkw_OutlinerForm_TreeControl_ControlInstance.DoDoIt(const aCtx: TtfwContext); {-} begin aCtx.rEngine.PushObj((aCtx.rEngine.PopObj As TOutlinerFormForm).TreeControl); end;//Tkw_OutlinerForm_TreeControl_ControlInstance.DoDoIt {$IfEnd} //not NoScripts procedure TOutlinerFormForm.InitControls; //#UC START# *4A8E8F2E0195_4D4697F30281_var* //#UC END# *4A8E8F2E0195_4D4697F30281_var* begin //#UC START# *4A8E8F2E0195_4D4697F30281_impl* inherited; f_TreeControl.Align := alClient; //#UC END# *4A8E8F2E0195_4D4697F30281_impl* end;//TOutlinerFormForm.InitControls procedure TOutlinerFormForm.MakeControls; begin inherited; f_TreeControl := TvtOutlinerControl.Create(Self); f_TreeControl.Name := 'TreeControl'; f_TreeControl.Parent := Self; with AddUsertype(ut_OutlinerFormName, str_ut_OutlinerFormCaption, str_ut_OutlinerFormCaption, false, -1, -1, '', nil, nil, nil, vcm_ccNone) do begin end;//with AddUsertype(ut_OutlinerFormName end; {$IfEnd} //nsTest AND not NoVCM initialization {$If defined(nsTest) AND not defined(NoVCM)} // Регистрация Tkw_OutlinerForm_Control_TreeControl Tkw_OutlinerForm_Control_TreeControl.Register('контрол::TreeControl', TvtOutlinerControl); {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} // Регистрация Tkw_OutlinerForm_Control_TreeControl_Push Tkw_OutlinerForm_Control_TreeControl_Push.Register('контрол::TreeControl:push'); {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} // Регистрация фабрики формы OutlinerForm fm_OutlinerFormForm.SetFactory(TOutlinerFormForm.Make); {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} // Регистрация Tkw_Form_OutlinerForm Tkw_Form_OutlinerForm.Register('форма::OutlinerForm', TOutlinerFormForm); {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} // Регистрация Tkw_OutlinerForm_TreeControl_ControlInstance TtfwScriptEngine.GlobalAddWord('.TOutlinerFormForm.TreeControl', Tkw_OutlinerForm_TreeControl_ControlInstance); {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} // Инициализация str_ut_OutlinerFormCaption str_ut_OutlinerFormCaption.Init; {$IfEnd} //nsTest AND not NoVCM end.
unit xpr.lexer; { Author: Jarl K. Holta License: GNU Lesser GPL (http://www.gnu.org/licenses/lgpl.html) A straight forward tokenizer } {$I express.inc} interface uses Classes, SysUtils, xpr.dictionary, xpr.express; type (* Tokenizer, used to turn text into an array of TTokens It's not the most efficient implementation, nor the most "easy", it's something in between. *) TTokenizer = record private FArrHigh: Int32; public Data: String; Pos,lineStart: Int32; Tokens: TTokenArray; DocPos: TDocPos; function Next(): Char; inline; function Peek(n:Int32=1): Char; inline; function Current: Char; inline; function Prev: Char; inline; function Next_CheckNewline: Char; inline; procedure Append(token:TTokenKind; value:string=''); inline; procedure AppendInc(token:TTokenKind; value:string=''; n:Int32=1); inline; procedure Extend(t:TTokenizer); inline; procedure AddToken(cases:array of string; token:TTokenKind); procedure AddIdent(); inline; procedure AddNumber(); inline; procedure AddChar(); inline; procedure AddString(); inline; procedure HandleComment(); inline; procedure Tokenize(expr:String); end; (* Types needed to store reserved words *) TKeywordMap = specialize TDictionary<string, TTokenKind>; (* Types needed to store operator precedence, and associativity *) TOperatorPrecedence = record prec, assoc: Int8; end; TOperatorPrecedenceMap = specialize TDictionary<string, TOperatorPrecedence>; const lparen: TToken = (token:tk_paren; value:'('); rparen: TToken = (token:tk_paren; value:')'); lsquare:TToken = (token:tk_square; value:'['); rsquare:TToken = (token:tk_square; value:']'); lbrace: TToken = (token:tk_paren; value:'{'); rbrace: TToken = (token:tk_paren; value:'}'); var KeywordMap: TKeywordMap; PrecedenceMap, UnaryPrecedenceMap: TOperatorPrecedenceMap; function Tokenize(script:string): TTokenizer; function Keyword(kw:string): TToken; inline; function TkToString(x:TTokenKind): string; inline; procedure TestLexer(fileName:string; printTokens:Boolean; nRounds:Int32=5); implementation uses xpr.utils; type TReservedName = record name: string; tok: TTokenKind; end; TOperatorValue = record op: string; prec: Int8; assoc: Int8; end; const ReservedWords: array [0..27] of TReservedName = ( (name:'break'; tok:tk_keyword), (name:'case'; tok:tk_keyword), (name:'continue'; tok:tk_keyword), (name:'do'; tok:tk_keyword), (name:'else'; tok:tk_keyword), (name:'elif'; tok:tk_keyword), (name:'end'; tok:tk_keyword), (name:'for'; tok:tk_keyword), (name:'func'; tok:tk_keyword), (name:'if'; tok:tk_keyword), (name:'in'; tok:tk_keyword), (name:'time'; tok:tk_keyword), (name:'print'; tok:tk_keyword), (name:'repeat'; tok:tk_keyword), (name:'return'; tok:tk_keyword), (name:'then'; tok:tk_keyword), (name:'var'; tok:tk_keyword), (name:'while'; tok:tk_keyword), (name:'None'; tok:tk_None), (name:'True'; tok:tk_bool), (name:'False'; tok:tk_bool), (name:'div'; tok:tk_fact), (name:'shl'; tok:tk_bitwise), (name:'shr'; tok:tk_bitwise), (name:'in'; tok:tk_logical), (name:'and'; tok:tk_logical), (name:'or'; tok:tk_logical), (name:'not'; tok:tk_logical) ); BinPrecedence: array [0..30] of TOperatorValue = ( (op:'if'; prec:1; assoc:-1), (op:'=>'; prec:1; assoc:-1), (op:':='; prec:1; assoc:-1), (op:'+='; prec:1; assoc:-1), (op:'-='; prec:1; assoc:-1), (op:'*='; prec:1; assoc:-1), (op:'/='; prec:1; assoc:-1), (op:'&='; prec:1; assoc:-1), (op:'|='; prec:1; assoc:-1), (op:'^='; prec:1; assoc:-1), (op:'and'; prec:2; assoc:-1), (op:'or'; prec:2; assoc:-1), (op:'='; prec:3; assoc:1), (op:'!='; prec:3; assoc:1), (op:'<'; prec:4; assoc:1), (op:'>'; prec:4; assoc:1), (op:'<='; prec:4; assoc:1), (op:'>='; prec:4; assoc:1), (op:'|'; prec:5; assoc:1), (op:'&'; prec:5; assoc:1), (op:'^'; prec:5; assoc:1), (op:'in'; prec:6; assoc:1), (op:'+'; prec:6; assoc:1), (op:'-'; prec:6; assoc:1), (op:'*'; prec:7; assoc:1), (op:'div'; prec:7; assoc:1), (op:'/'; prec:7; assoc:1), (op:'%'; prec:7; assoc:1), (op:'shl'; prec:7; assoc:1), (op:'shr'; prec:7; assoc:1), (op:'**'; prec:8; assoc:1) ); UnaryPrecedence: array [0..5] of TOperatorValue = ( (op:'++'; prec:0; assoc:0), (op:'--'; prec:0; assoc:0), (op:'+'; prec:0; assoc:0), (op:'-'; prec:0; assoc:0), (op:'~'; prec:0; assoc:0), (op:'not'; prec:0; assoc:0) ); function Keyword(kw:string): TToken; begin Result.Token := tk_keyword; Result.Value := kw; end; function TkToString(x:TTokenKind): string; var str:String; begin WriteStr(str, x); Result := str; end; function Tokenize(script:string): TTokenizer; begin Result.Pos := 0; Result.Tokenize(script); end; function TTokenizer.Next(): Char; begin Result := data[pos+1]; Inc(pos); end; function TTokenizer.Peek(n:Int32=1): Char; begin Result := data[pos+n]; end; function TTokenizer.Current: Char; begin Result := data[pos]; end; function TTokenizer.Prev: Char; begin if pos-1 >= 0 then Result := data[pos-1] else Result := #0; end; function TTokenizer.Next_CheckNewline: Char; begin if (Current+Peek() = #13#10) then begin Inc(DocPos.line); Inc(pos); lineStart := pos+1; end else if (Current = #10) or (Current = #13) then begin Inc(DocPos.line); lineStart := pos+1; end; Inc(pos); Result := data[pos]; end; procedure TTokenizer.Append(token:TTokenKind; value:String=''); begin if FArrHigh >= Length(tokens) then SetLength(tokens, 2 * Length(tokens)); tokens[FArrHigh].value := value; tokens[FArrHigh].token := token; tokens[FArrHigh].docpos := DocPos; Inc(FArrHigh); end; procedure TTokenizer.AppendInc(token:TTokenKind; value:String=''; n:Int32=1); var i:Int32; begin if FArrHigh >= Length(tokens) then SetLength(tokens, 2 * Length(tokens)); tokens[FArrHigh].value := value; tokens[FArrHigh].token := token; tokens[FArrHigh].docpos := DocPos; Inc(FArrHigh); for i:=0 to n-1 do Next(); end; procedure TTokenizer.Extend(t:TTokenizer); var i:Int32; begin for i:=0 to t.FArrHigh-1 do self.Append(t.tokens[i].token,t.tokens[i].value); end; procedure TTokenizer.AddToken(cases:array of string; token:TTokenKind); var i:Int32; begin for i:=0 to High(cases) do if Slice(data,pos,pos+Length(cases[i])-1) = cases[i] then begin self.Append(token,cases[i]); Inc(pos, Length(cases[i])); Exit; end; raise Exception.Create('Undefined symbol'); end; procedure TTokenizer.AddIdent(); var i:Int32; tmp:String; tok:TTokenKind; begin i := pos; Inc(pos); while Current in ['a'..'z','A'..'Z','_','0'..'9'] do Inc(pos); tmp := Slice(data, i, pos-1); tok := KeywordMap.GetDef(tmp, tk_ident); self.Append(tok, tmp); end; procedure TTokenizer.AddNumber(); var i:Int32; begin i := pos; Inc(pos); while (self.Current in ['0'..'9',#32]) do Inc(pos); if self.Current = '.' then begin Next(); while self.Current in ['0'..'9',#32] do Inc(pos); self.Append(tk_float, StringReplace(Slice(data,i,pos-1), #32, '', [rfReplaceAll])); end else self.Append(tk_int, StringReplace(Slice(data,i,pos-1), #32, '', [rfReplaceAll])); end; procedure TTokenizer.AddChar(); var i:Int32; begin i := pos; Inc(pos); while self.Current in ['0'..'9'] do Inc(pos); self.Append(tk_char, chr(StrToInt(Slice(data,i+1,pos-1)))); end; procedure TTokenizer.AddString(); var i:Int32; begin i := pos; Inc(pos); while (Current <> data[i]) and (Current <> #0) do Next_CheckNewline; self.Append(tk_string, Slice(data,i+1,pos-1)); Inc(pos); end; procedure TTokenizer.HandleComment(); begin if data[pos] = '/' then begin while not(Current in [#10,#13,#0]) do Inc(pos); end else begin Inc(pos); while (Current <> #0) and (Current+Peek <> '*)') do Next_CheckNewline; Inc(pos, 2); end; end; procedure TTokenizer.Tokenize(expr:String); begin SetLength(tokens, 1); FArrHigh := 0; data := Expr + #0#0; pos := 1; //DocPos.filename := '__main__'; DocPos.Line := 1; lineStart := 0; while data[pos] <> #0 do begin DocPos.column := Pos - lineStart; case data[pos] of #10: begin {$IFDEF loose_semicolon} self.AppendInc(tk_newline, '', 1); {$ELSE} Next; {$ENDIF} Inc(DocPos.line); lineStart := pos; end; #1..#9: Next; #11..#32: Next; ';': self.AppendInc(tk_semicolon, data[pos], 1); '.': self.AppendInc(tk_dot, data[pos], 1); ',': self.AppendInc(tk_comma, data[pos], 1); ':': if Peek() = '=' then self.AppendInc(tk_assign, data[pos]+data[pos+1], 2) else self.AppendInc(tk_colon, data[pos], 1); '<','>','=','!': if Peek() = '>' then self.AppendInc(tk_assign, data[pos]+data[pos+1], 2) else self.AddToken(['<=','>=','!=','>','<','='], tk_cmp); '&','|','^','~': if Peek() = '=' then self.AppendInc(tk_assign, data[pos]+data[pos+1], 2) else self.AddToken(['&','|','^','~'], tk_bitwise); '+','-': if Peek() = '=' then self.AppendInc(tk_assign, data[pos]+'=', 2) else self.AddToken(['++','--','+','-'], tk_sum); '/','*','%': if Peek() = '=' then self.AppendInc(tk_assign, data[pos]+data[pos+1], 2) else if (Current() = '/') and (Peek() = '/') then self.HandleComment() else self.AddToken(['/','*','%'], tk_fact); '(',')': if Peek() = '*' then self.HandleComment() else self.AddToken(['(',')'], tk_paren); '[',']': self.AddToken(['[',']'], tk_square); '{','}': self.AddToken(['{','}'], tk_brace); 'a'..'z','A'..'Z','_': self.AddIdent(); '0'..'9': self.AddNumber(); '#': self.AddChar(); #34,#39: self.AddString(); #0: break; else raise Exception.Create('Invalid symbol "'+data[pos]+'" / #'+IntToStr(Ord(data[pos]))); end; end; Self.Append(tk_unknown,''); SetLength(tokens, FArrHigh); end; procedure TestLexer(fileName:String; printTokens:Boolean; nRounds:Int32=5); var t:TTokenizer; i:Int32; d,best,sum:Double; doc:String; f:TStringList; begin best := $FFFFFF; f := TStringList.Create(); f.LoadFromFile(fileName); doc := f.Text; f.Free(); sum := 0; for i:=0 to nRounds do begin d := MarkTime(); t.Tokenize(doc); d := MarkTime() - d; if d < best then best := d; sum += d; end; WriteLn(Format('best: %.4f ms | sum: %.4f ms',[best,sum])); WriteLn('------------------------------------'); if printTokens then for i:=0 to High(t.tokens) do WriteLn(t.Tokens[i].ToString()); end; procedure InitModule(); var i:Int32; myOperator:TOperatorPrecedence; begin (* load keywords *) KeywordMap := TKeywordMap.Create(@HashStr); for i:=0 to High(ReservedWords) do KeywordMap.Add(ReservedWords[i].name, ReservedWords[i].tok); (* load operators: Assoc, and Precedence *) PrecedenceMap := TOperatorPrecedenceMap.Create(@HashStr); for i:=0 to High(BinPrecedence) do begin myOperator.assoc := BinPrecedence[i].assoc; myOperator.prec := BinPrecedence[i].prec; PrecedenceMap.Add(BinPrecedence[i].op, myOperator); end; UnaryPrecedenceMap := TOperatorPrecedenceMap.Create(@HashStr); for i:=0 to High(UnaryPrecedence) do begin myOperator.assoc := UnaryPrecedence[i].assoc; myOperator.prec := UnaryPrecedence[i].prec; UnaryPrecedenceMap.Add(UnaryPrecedence[i].op, myOperator); end; end; initialization InitModule(); end.
unit K590757091; {* [Requestlink:590757091] } // Модуль: "w:\common\components\rtl\Garant\Daily\K590757091.pas" // Стереотип: "TestCase" // Элемент модели: "K590757091" MUID: (5510067D003A) // Имя типа: "TK590757091" {$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas} interface {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3IntfUses , RTFtoEVDWriterTest ; type TK590757091 = class(TRTFtoEVDWriterTest) {* [Requestlink:590757091] } protected function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } end;//TK590757091 {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) implementation {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3ImplUses , TestFrameWork //#UC START# *5510067D003Aimpl_uses* //#UC END# *5510067D003Aimpl_uses* ; function TK590757091.GetFolder: AnsiString; {* Папка в которую входит тест } begin Result := '7.11'; end;//TK590757091.GetFolder function TK590757091.GetModelElementGUID: AnsiString; {* Идентификатор элемента модели, который описывает тест } begin Result := '5510067D003A'; end;//TK590757091.GetModelElementGUID initialization TestFramework.RegisterTest(TK590757091.Suite); {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) end.
unit TestUnit1; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, Unit1; type // Test methods for class TSquare TestTSquare = class(TTestCase) strict private FSquare: TSquare; public procedure SetUp; override; procedure TearDown; override; published procedure TestSquare; procedure TestNegativeA; end; implementation procedure TestTSquare.SetUp; begin FSquare := TSquare.Create; end; procedure TestTSquare.TearDown; begin FSquare.Free; end; procedure TestTSquare.TestNegativeA; var ReturnValue: Integer; a: Integer; ExpectedVal: Integer; begin // TODO: Setup method call parameters a := -5; ExpectedVal := 20; ReturnValue := FSquare.Square(a); // TODO: Validate method results CheckEquals(ExpectedVal, ReturnValue); // Fail('It must be implemented'); end; procedure TestTSquare.TestSquare; var ReturnValue: Integer; a: Integer; ExpectedVal: Integer; begin // TODO: Setup method call parameters a := 5; ExpectedVal := 20; ReturnValue := FSquare.Square(a); // TODO: Validate method results CheckEquals(ExpectedVal, ReturnValue); end; initialization // Register any test cases with the test runner RegisterTest(TestTSquare.Suite); end.
unit uPrinc; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Buttons, Vcl.ComCtrls; type Tform1 = class(TForm) m1: TMemo; pn0: TPanel; cbCampo: TComboBox; cbOper: TComboBox; edtvrl: TEdit; btnMore: TBitBtn; lstFiltro: TListBox; cbOperLog: TComboBox; btnSearch: TBitBtn; Label1: TLabel; procedure FormCreate(Sender: TObject); procedure btnMoreClick(Sender: TObject); procedure btnSearchClick(Sender: TObject); procedure lstFiltroDblClick(Sender: TObject); procedure lstFiltroKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private function VerificaCamposValidos: Boolean; procedure clearFields; { Private declarations } public { Public declarations } nrFiltro: Word; end; var form1: Tform1; const SELECT_PADRAO = ' SELECT * FROM table WHERE 1=1 '; implementation {$R *.dfm} procedure Tform1.btnSearchClick(Sender: TObject); begin m1.Text := lstFiltro.Items.Text; end; procedure Tform1.btnMoreClick(Sender: TObject); begin if VerificaCamposValidos then begin if nrFiltro = 0 then begin cbOperLog.Visible := True; lstFiltro.Items.Add(SELECT_PADRAO); end; lstFiltro.Items.Add(cbOperLog.Text+' '+cbCampo.Text+' '+cbOper.Text+' '+edtvrl.Text); Inc(nrFiltro); clearFields; end; end; function Tform1.VerificaCamposValidos(): Boolean; begin if (edtvrl.Text <> '') and (cbCampo.ItemIndex > 0) then begin //campos devem estar preenchidos if nrFiltro = 0 then Result := True //se for primeira linha da consulta, é válido. pq é SELECT_PADRAO else Result := (cbOperLog.Text <> ''); //é válido se o operador lógico estiver preenchido end; end; procedure Tform1.clearFields(); begin edtvrl.Clear; cbCampo.ItemIndex := 0; cbOper.ItemIndex := 0; cbOperLog.ItemIndex := 0; end; procedure Tform1.FormCreate(Sender: TObject); begin m1.Lines.Clear; cbOperLog.Visible := False; end; procedure Tform1.lstFiltroDblClick(Sender: TObject); begin if lstFiltro.ItemIndex <> 0 then lstFiltro.DeleteSelected; end; procedure Tform1.lstFiltroKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key = VK_DELETE) and (lstFiltro.ItemIndex <> 0) then lstFiltro.DeleteSelected; end; end.
unit uMenuInicial; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.ListView.Types, FMX.ListView, FMX.Controls.Presentation, FMX.StdCtrls, udmPrincipal, System.Rtti, System.Bindings.Outputs, Fmx.Bind.Editors, Data.Bind.EngExt, Fmx.Bind.DBEngExt, Data.Bind.Components, Data.Bind.DBScope, uConstantes, FMX.ListView.Appearances, FMX.ListView.Adapters.Base; type TFMenuInicial = class(TForm) ToolBar1: TToolBar; ListView1: TListView; BindSourceDB1: TBindSourceDB; BindingsList1: TBindingsList; LinkListControlToField1: TLinkListControlToField; btnInserir: TButton; btnExecutar: TButton; btnDeletar: TButton; btnEditar: TButton; procedure FormShow(Sender: TObject); procedure btnInserirClick(Sender: TObject); procedure ListView1ItemClick(const Sender: TObject; const AItem: TListViewItem); procedure btnEditarClick(Sender: TObject); procedure btnExecutarClick(Sender: TObject); procedure btnDeletarClick(Sender: TObject); private ItemClicado : TListViewItem; vgSKeyProduto : String; procedure pcdGeraJSONItens; procedure pcdGravarJSON(poStringList: TStringList); { Private declarations } public procedure setAtualizarLista(); { Public declarations } end; var FMenuInicial: TFMenuInicial; implementation uses uPrincipal; {$R *.fmx} procedure TFMenuInicial.btnDeletarClick(Sender: TObject); begin if dmPrincipal.FDConsultaProduto.IsEmpty then begin ShowMessage('Não é possível excluir, pois não há itens lançados!'); end else begin MessageDlg('Deseja excluir o item ' + dmPrincipal.FDConsultaProdutoDESCRICAO.AsString + ' ?', System.UITypes.TMsgDlgType.mtInformation, [System.UITypes.TMsgDlgBtn.mbYes, System.UITypes.TMsgDlgBtn.mbNo], 0, procedure(const BotaoPressionado: TModalResult) begin case BotaoPressionado of mrYes: begin begin dmPrincipal.FDConsultas.Close; dmPrincipal.FDConsultas.SQL.Add('DELETE FROM PRODUTOS WHERE KEY_EMPRESA = :KEY_EMPRESA AND KEY_PRODUTO = :KEY_PRODUTO'); dmPrincipal.FDConsultas.ParamByName('KEY_EMPRESA').AsString := dmPrincipal.FDConsultaProdutoKEY_EMPRESA.AsString; dmPrincipal.FDConsultas.ParamByName('KEY_PRODUTO').AsString := dmPrincipal.FDConsultaProdutoKEY_PRODUTO.AsString; dmPrincipal.FDConsultas.ExecSQL; setAtualizarLista; end; end; end; end); end; end; procedure TFMenuInicial.btnEditarClick(Sender: TObject); begin if dmPrincipal.FDConsultaProduto.IsEmpty then begin ShowMessage('Não é possível editar, pois não há itens lançados!'); end else begin if not Assigned(FPrincipal) then Application.CreateForm(TFPrincipal, FPrincipal); FPrincipal.setTelaInicial(True, constkey_empresa, vgSKeyProduto); FPrincipal.Show; end; end; procedure TFMenuInicial.btnExecutarClick(Sender: TObject); begin if dmPrincipal.FDConsultaProduto.IsEmpty then begin ShowMessage('Não é possível gerar o arquivo, pois não há itens lançados!'); end else begin pcdGeraJSONItens; end; end; procedure TFMenuInicial.btnInserirClick(Sender: TObject); begin if not Assigned(FPrincipal) then Application.CreateForm(TFPrincipal, FPrincipal); FPrincipal.setTelaInicial(False, constkey_empresa, ''); FPrincipal.Show; end; procedure TFMenuInicial.FormShow(Sender: TObject); begin setAtualizarLista; end; procedure TFMenuInicial.ListView1ItemClick(const Sender: TObject; const AItem: TListViewItem); begin ItemClicado := AItem; vgSKeyProduto := ListView1.Items[AItem.Index-1].Text; end; procedure TFMenuInicial.setAtualizarLista; var vliRecNo : Integer; begin vliRecNo := dmPrincipal.FDConsultaProduto.RecNo; dmPrincipal.FDConsultaProduto.Close; dmPrincipal.FDConsultaProduto.Open(); dmPrincipal.FDConsultaProduto.RecNo := vliRecNo; end; procedure TFMenuInicial.pcdGeraJSONItens(); var vlOStringList : TStringList; vlSEspacoInicialProduto, vlsEspacoCamposProduto, virgulaFinal : String; vlICount : Integer; begin vlSEspacoInicialProduto := ' '; vlsEspacoCamposProduto := ' '; virgulaFinal := ','; vlICount := 1; vlOStringList := TStringList.Create; try vlOStringList.Add('{'); vlOStringList.Add(' "cardapio_itens" : {'); vlOStringList.Add(' "-LNIt3Xv5j-bLDcr6p4E" : {'); dmPrincipal.FDConsultaProduto.First; while not dmPrincipal.FDConsultaProduto.Eof do begin if vlICount = dmPrincipal.FDConsultaProduto.RecordCount then virgulaFinal := ''; vlOStringList.Add(vlSEspacoInicialProduto + '"' + dmPrincipal.FDConsultaProdutoKEY_PRODUTO.AsString+'" : {'); vlOStringList.Add(vlsEspacoCamposProduto + '"complemento" : "'+dmPrincipal.FDConsultaProdutoCOMPLEMENTOS.AsString+'",'); vlOStringList.Add(vlsEspacoCamposProduto + '"descricao" : "'+dmPrincipal.FDConsultaProdutoDESCRICAO.AsString+'",'); vlOStringList.Add(vlsEspacoCamposProduto + '"grupo" : "'+dmPrincipal.FDConsultaProdutoGRUPO.AsString+'",'); vlOStringList.Add(vlsEspacoCamposProduto + '"key_empresa" : "'+dmPrincipal.FDConsultaProdutoKEY_EMPRESA.AsString+'",'); vlOStringList.Add(vlsEspacoCamposProduto + '"key_produto" : "'+dmPrincipal.FDConsultaProdutoKEY_PRODUTO.AsString+'",'); vlOStringList.Add(vlsEspacoCamposProduto + '"valor_inteira" : "'+dmPrincipal.FDConsultaProdutoVALOR_INTEIRA.AsString+'",'); vlOStringList.Add(vlsEspacoCamposProduto + '"valor_meia" : "'+dmPrincipal.FDConsultaProdutoVALOR_MEIA.AsString+'"'); vlOStringList.Add(vlSEspacoInicialProduto+'}'+virgulaFinal); Inc(vlICount); dmPrincipal.FDConsultaProduto.Next; end; vlOStringList.Add(' }'); vlOStringList.Add(' }'); vlOStringList.Add('}'); pcdGravarJSON(vlOStringList); finally FreeAndNil(vlOStringList); end; end; procedure TFMenuInicial.pcdGravarJSON(poStringList: TStringList); begin if not DirectoryExists(System.SysUtils.GetCurrentDir+'\JSON_Itens') then ForceDirectories(System.SysUtils.GetCurrentDir+'\JSON_Itens'); poStringList.SaveToFile(System.SysUtils.GetCurrentDir + '\JSON_Itens\cardapio_itens_'+FormatDateTime('ddmmYYYY', Now)+'.json'); end; end.
unit WindowsLocationInfo; interface uses System.Sensors, System.SysUtils, System.Net.HttpClient, System.Net.HTTPClientComponent, XSuperObject, System.Classes; type TWindowsLocationInfo = class class function GetLocation: TLocationCoord2D; end; implementation class function TWindowsLocationInfo.GetLocation: TLocationCoord2D; begin Result.Latitude:=52.505616; Result.Longitude:= 13.393037; end; end.
unit uMJD.Messages; interface resourcestring rsErroConexaoBD = 'Ocorreu um erro ao tentar conectar com o banco de dados'; rsOperacaoNaoSuportada = 'Operação %s não suportada'; rsProtocoloNaoInformado = 'Protocolo não informado'; rsStatusNaoSuportado = 'Status %s não suportado'; rsConexaoFalhou = 'Conexão falhou. ' + #13#10 + 'Erro: %s' + #13#10 + 'Mensagem: %s'; rsServidorNaoRespondendo = 'Servidor não está respondendo'; rsConfirmaExclusao = 'Confirma o excluir?'; rsSelecioneRegistro = 'Selecione um registro'; rsInformeNome = 'Informe o nome'; implementation end.
{*********************************************************************************************************************** * * TERRA Game Engine * ========================================== * * Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@gmail.com) * *********************************************************************************************************************** * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ********************************************************************************************************************** * TERRA_Skeleton * Implements the Skeleton class used for mesh skinning *********************************************************************************************************************** } Unit TERRA_MeshSkeleton; {$I terra.inc} Interface Uses TERRA_String, TERRA_Utils, TERRA_Stream, TERRA_Resource, TERRA_Vector3D, TERRA_Math, TERRA_Matrix4x4, TERRA_Vector2D, TERRA_Color, TERRA_Quaternion, TERRA_ResourceManager; Type MeshSkeleton = Class; MeshBone = Class(TERRAObject) Name:TERRAString; Index:Integer; Parent:MeshBone; Owner:MeshSkeleton; Color:Color; Selected:Boolean; StartPosition:Vector3D; {$IFNDEF NO_ROTS} StartRotation:Vector3D; AbsoluteRotation:Quaternion; RelativeRotation:Quaternion; {$ENDIF} AbsoluteMatrix:Matrix4x4; RelativeMatrix:Matrix4x4; Ready:Boolean; Procedure Init; Procedure Release; Override; Function Read(Source:Stream):TERRAString; Procedure Write(Dest:Stream); Function GetLength():Single; End; MeshSkeleton = Class(TERRAObject) Protected _BoneList:Array Of MeshBone; _BoneCount:Integer; _Hash:Cardinal; Public Name:String; // BindPose:Array Of Matrix4x4; Procedure Release; Override; Procedure Init(); Procedure Clone(Other:MeshSkeleton); Procedure Read(Source:Stream); Procedure Write(Dest:Stream); Function AddBone:MeshBone; Function GetBone(Index:Integer):MeshBone; Overload; Function GetBone(Const Name:TERRAString):MeshBone; Overload; Function GetBoneLength(Index:Integer):Single; Procedure Render(Const Transform:Matrix4x4; Instance:Pointer); Property BoneCount:Integer Read _BoneCount; Property Hash:Cardinal Read _Hash; End; Implementation Uses TERRA_Error, TERRA_Log, TERRA_Application, TERRA_OS, TERRA_FileManager, TERRA_Mesh, TERRA_GraphicsManager, TERRA_FileStream, TERRA_FileUtils; { MeshBone } Procedure MeshBone.Release; Begin // do nothing End; Function MeshBone.GetLength: Single; Var P:Vector3D; Begin If (Self.Parent=Nil) Then Result := 0 Else Begin P := VectorSubtract(Self.StartPosition, Parent.StartPosition); Result := P.Length(); End; End; Procedure MeshBone.Init; Begin If (Ready) Then Exit; If (Assigned(Parent)) And (Not Parent.Ready) Then Parent.Init; {$IFNDEF NO_ROTS} RelativeMatrix := Matrix4x4Multiply4x3(Matrix4x4Translation(startPosition), Matrix4x4Rotation(startRotation)); RelativeRotation := QuaternionRotation(StartRotation); {$ELSE} RelativeMatrix := Matrix4x4Translation(startPosition); {$ENDIF} // Each bone's final matrix is its relative matrix concatenated onto its // parent's final matrix (which in turn is ....) // If ( Parent = nil ) Then // this is the root node Begin AbsoluteMatrix := RelativeMatrix; {$IFNDEF NO_ROTS} AbsoluteRotation := QuaternionZero; {$ENDIF} End Else // not the root node Begin // m_final := parent's m_final * m_rel (matrix concatenation) AbsoluteMatrix := Matrix4x4Multiply4x3(Parent.AbsoluteMatrix, RelativeMatrix); {$IFNDEF NO_ROTS} AbsoluteRotation := QuaternionMultiply(Parent.AbsoluteRotation, RelativeRotation); {$ENDIF} End; Ready := True; End; Function MeshBone.Read(Source:Stream):TERRAString; Var I:Integer; Begin Source.ReadString(Name); Source.ReadString(Result); Parent := Nil; Source.Read(@StartPosition, SizeOf(Vector3D)); {$IFNDEF NO_ROTS} Source.Read(@StartRotation, SizeOf(Vector3D)); {$ELSE} Source.Skip(SizeOf(Vector3D)); {$ENDIF} Ready := False; End; Procedure MeshBone.Write(Dest:Stream); Begin Dest.WriteString(Name); If (Assigned(Parent)) Then Dest.WriteString(Parent.Name) Else Dest.WriteString(''); Dest.Write(@StartPosition, SizeOf(StartPosition)); {$IFNDEF NO_ROTS} Dest.Write(@StartRotation, SizeOf(StartRotation)); {$ELSE} Dest.Write(@StartPosition, SizeOf(StartPosition)); {$ENDIF} End; { MeshSkeleton } Function MeshSkeleton.AddBone:MeshBone; Begin Inc(_BoneCount); SetLength(_BoneList, _BoneCount); Result := MeshBone.Create; _BoneList[ Pred(_BoneCount)] := Result; Result.Color := ColorWhite; Result.Selected := False; End; Function MeshSkeleton.GetBone(Index:Integer):MeshBone; Begin If (Index<0) Or (Index>=_BoneCount) Then Result := Nil Else Result := (_BoneList[Index]); End; Procedure MeshSkeleton.Render(Const Transform:Matrix4x4; Instance:Pointer); Var I:Integer; A, B:Vector3D; Begin {$IFDEF PCs} GraphicsManager.Instance.BeginColorShader(ColorWhite, Transform); glLineWidth(2); GraphicsManager.Instance.SetFog(False); GraphicsManager.Instance.SetBlendMode(blendNone); glDepthMask(True); glDepthRange(0,0.0001); glBegin(GL_LINES); For I:=0 To Pred(_BoneCount) Do Begin If Assigned(Instance) Then Begin A := MeshInstance(MeshInstance(Instance)).BoneMatrixList[Succ(I)].Transform(VectorZero); If (Assigned(_BoneList[I].Parent)) Then B := MeshInstance(MeshInstance(Instance)).BoneMatrixList[Succ(_BoneList[I].Parent.Index)].Transform(VectorZero) Else Continue; End Else Begin A := _BoneList[I].AbsoluteMatrix.Transform(VectorZero); If (Assigned(_BoneList[I].Parent)) Then B := _BoneList[_BoneList[I].Parent.Index].AbsoluteMatrix.Transform(VectorZero) Else Continue; End; With A Do glVertex3f(X,Y,Z); With B Do glVertex3f(X,Y,Z); End; glEnd; glPointSize(10); glBegin(GL_POINTS); For I:=0 To Pred(_BoneCount) Do Begin If Assigned(Instance) Then A := MeshInstance(MeshInstance(Instance)).BoneMatrixList[Succ(I)].Transform(VectorZero) Else A := _BoneList[I].AbsoluteMatrix.Transform(VectorZero); With A Do glVertex3f(X,Y,Z); End; glEnd; (* QuadObj:=gluNewQuadric; gluQuadricNormals(QuadObj, GLU_NONE); gluQuadricTexture(QuadObj, False); For I:=0 To Pred(_BoneCount) Do Begin A := MeshInstance(Instance).BoneMatrixList[Succ(I)].Transform(VectorZero); Shader.SetUniform('modelMatrix', MatrixMultiply4x3(Transform, MatrixTranslation(A))); gluSphere(QuadObj, 0.25, 8, 8); End; gluDeleteQuadric(QuadObj); *) glDepthMask(True); glDepthRange(0,1); GraphicsManager.Instance.EndColorShader; {$ENDIF} End; Procedure MeshSkeleton.Read(Source: Stream); Var Parents:Array Of TERRAString; I:Integer; Begin Source.Read(@_BoneCount, 4); SetLength(_BoneList, _BoneCount); SetLength(Parents, _BoneCount); For I:=0 To Pred(_BoneCount) Do _BoneList[I] := Nil; For I:=0 To Pred(_BoneCount) Do Begin _BoneList[I] := MeshBone.Create; _BoneList[I].Index := I; _BoneList[I].Owner := Self; _BoneList[I].Ready := False; _BoneList[I].Color := ColorWhite; _BoneList[I].Selected := False; Parents[I] := _BoneList[I].Read(Source); End; For I:=0 To Pred(_BoneCount) Do _BoneList[I].Parent := Self.GetBone(Parents[I]); Self.Init(); End; Procedure MeshSkeleton.Init; Var I:Integer; Begin For I:=0 To Pred(_BoneCount) Do _BoneList[I].Ready := False; For I:=0 To Pred(_BoneCount) Do _BoneList[I].Init(); (*SetLength(BindPose, Succ(_BoneCount)); BindPose[0] := Matrix4x4Identity; For I:=0 To Pred(_BoneCount) Do BindPose[Succ(I)] := _BoneList[I].AbsoluteMatrix;*) For I:=0 To Pred(_BoneCount) Do _BoneList[I].AbsoluteMatrix := Matrix4x4Inverse(_BoneList[I].AbsoluteMatrix); End; Procedure MeshSkeleton.Write(Dest: Stream); Var I:Integer; Begin Dest.Write(@_BoneCount, 4); For I:=0 To Pred(_BoneCount) Do _BoneList[I].Write(Dest); End; Procedure MeshSkeleton.Release; Var I:Integer; Begin _BoneCount := Length(_BoneList); For I:=0 To Pred(_BoneCount) Do ReleaseObject(_BoneList[I]); SetLength(_BoneList, 0); End; Function MeshSkeleton.GetBone(Const Name:TERRAString): MeshBone; Var I:Integer; Begin For I:=0 To Pred(_BoneCount) Do If (StringEquals(Name, _BoneList[I].Name)) Then Begin Result := _BoneList[I]; Exit; End; Result := Nil; End; Function MeshSkeleton.GetBoneLength(Index: Integer): Single; Var A, B:Vector3D; Begin If (Index<0) Or (_BoneList[Index].Parent = Nil) Then Begin Result := 0; Exit; End; A := _BoneList[Index].AbsoluteMatrix.Transform(VectorZero); B := _BoneList[_BoneList[Index].Parent.Index].AbsoluteMatrix.Transform(VectorZero); Result := A.Distance(B); End; Procedure MeshSkeleton.Clone(Other: MeshSkeleton); Var I:Integer; Bone:MeshBone; Begin If (Other = Nil) Then Exit; Self.Name := Other.Name; Self._Hash := Application.GetTime(); For I:=0 To Pred(_BoneCount) Do ReleaseObject(_BoneList[I]); Self._BoneCount := Other._BoneCount; SetLength(Self._BoneList, _BoneCount); For I:=0 To Pred(_BoneCount) Do Begin Bone := Other.GetBone(I); _BoneList[I] := MeshBone.Create; _BoneList[I].Name := Bone.Name; _BoneList[I].Index := I; _BoneList[I].Owner := Self; _BoneList[I].Color := Bone.Color; _BoneList[I].Selected := Bone.Selected; _BoneList[I].StartPosition := Bone.StartPosition; {$IFNDEF NO_ROTS} _BoneList[I].StartRotation := Bone.StartRotation; {$ENDIF} _BoneList[I].Ready := Bone.Ready; _BoneList[I].AbsoluteMatrix := Bone.AbsoluteMatrix; _BoneList[I].RelativeMatrix := Bone.RelativeMatrix; {$IFNDEF NO_ROTS} _BoneList[I].AbsoluteRotation := Bone.AbsoluteRotation; _BoneList[I].RelativeRotation := Bone.RelativeRotation; {$ENDIF} If Assigned(Bone.Parent) Then _BoneList[I].Parent := Self.GetBone(Bone.Parent.Name) Else _BoneList[I].Parent := Nil; End; (* SetLength(BindPose, Succ(_BoneCount)); For I:=0 To _BoneCount Do BindPose[I] := Other.BindPose[I];*) End; End.
unit ValidationRules.TIsEmptyValidationRule; interface uses System.SysUtils, System.Variants, Framework.Interfaces; type TIsEmptyValidationRule = class(TInterfacedObject, IValidationRule) const IS_EMPTY_MESSAGE = 'Field is empty'; strict private FAcceptEmtpy: Boolean; procedure SetAcceptEmtpy(const AAcceptEmpty: Boolean); public constructor Create(const AAcceptEmpty: Boolean); destructor Destroy; override; function Parse(const AValue: Variant; var AReasonForRejection: String): Boolean; end; implementation { TIsEmptyValidationRule } constructor TIsEmptyValidationRule.Create(const AAcceptEmpty: Boolean); begin inherited Create; SetAcceptEmtpy(AAcceptEmpty); end; destructor TIsEmptyValidationRule.Destroy; begin inherited; end; function TIsEmptyValidationRule.Parse(const AValue: Variant; var AReasonForRejection: String): Boolean; begin Result := FAcceptEmtpy; if not Result then Result := (Trim(AValue) <> ''); if not Result then AReasonForRejection := Self.IS_EMPTY_MESSAGE; end; procedure TIsEmptyValidationRule.SetAcceptEmtpy(const AAcceptEmpty: Boolean); begin if FAcceptEmtpy <> AAcceptEmpty then FAcceptEmtpy := AAcceptEmpty; end; end.
unit ObjectContainer; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ImgList, ComCtrls, EditableObjects, Editors; type TObjectContainerEditor = class(TInPlaceVisualControl) lvItems: TListView; Images: TImageList; procedure lvItemsDblClick(Sender: TObject); public procedure UpdateObject; override; procedure setEditableObject( aEditableObject : TEditableObject; options : integer ); override; function ProcessMessage( msg : integer; var data ) : boolean; override; private fEditingChilds : boolean; procedure Clear; procedure InsertObject( EditableObject : TEditableObject ); end; var ObjectContainerEditor: TObjectContainerEditor; implementation uses EditorMain, NativeEdObjects; {$R *.DFM} // TObjectContainerEditor procedure TObjectContainerEditor.UpdateObject; begin end; procedure TObjectContainerEditor.setEditableObject( aEditableObject : TEditableObject; options : integer ); var i : integer; begin inherited; Clear; if (fEditableObject.Options and OPT_ALLOWNEW) <> 0 then with lvItems.Items.Add do begin ImageIndex := 0; Data := nil; Caption := 'New...'; end; fEditingChilds := boolean(options and VOP_EDITCHILDREN); if not fEditingChilds then for i := 0 to pred(fEditableObject.Properties.Count) do InsertObject( TEditableObject( fEditableObject.Properties[i] )) else for i := 0 to pred(fEditableObject.Children.Count) do InsertObject( TEditableObject( fEditableObject.Children[i] )) end; function TObjectContainerEditor.ProcessMessage( msg : integer; var data ) : boolean; var edObject : TEditableObject absolute data; begin result := true; case msg of MSG_GETSELOBJECT : begin edObject := nil; if (lvItems.Selected <> nil) and (lvItems.Selected.Data <> nil) then edObject := TEditableObject(lvItems.Selected.Data); end; else result := inherited ProcessMessage( msg, data ); end; end; procedure TObjectContainerEditor.Clear; begin lvItems.Items.Clear; end; procedure TObjectContainerEditor.InsertObject( EditableObject : TEditableObject ); begin with lvItems.Items.Add do begin ImageIndex := 0; Data := EditableObject; Caption := EditableObject.Name; end; end; procedure TObjectContainerEditor.lvItemsDblClick(Sender: TObject); var newObject : TEditableObject; begin if lvItems.Selected <> nil then if lvItems.Selected.Data <> nil then TEditableObject(lvItems.Selected.Data).Edit( VOP_SHOWINMAINCONTROL, EditorMainForm.pnRight ) else begin newObject := fEditableObject.ObjectEditor.CreateNewObject; if newObject <> nil then begin if not fEditingChilds then fEditableObject.Properties.Insert( newObject ) else begin if newObject is TNativeMetaEditableObject then TNativeMetaEditableObject(newObject).Parent := TMetaEditableobject(fEditableObject); fEditableObject.Children.Insert( newObject ); end; InsertObject( newObject ); end; end; end; end.
//UDEBUG code already inserted. Please do not remove this line. unit xIBQuery; interface uses {$IFDEF ZEOS}ZDataset, ZStoredProcedure,{$ENDIF} {$IFDEF IBO}IB_Components, IB_Query,{$ENDIF} {$IFDEF IBX}IBCustomDataSet, IBQuery,{$ENDIF} SysUtils, Classes, DB; type TxIBQuery = class( {$IFDEF ZEOS}TZQuery{$ENDIF} {$IFDEF IBO}IB_Query{$ENDIF} {$IFDEF IBX}TIBQuery{$ENDIF} ) private FMacroChar: Char; FMacros: TParams; procedure SetMacroChar(const Value: Char); procedure SetMacros(const Value: TParams); procedure CreateMacros(AList: TParams; const AStr: string); {$IFDEF IBX} FSQLStrings: TStringList; function GetSQLStrings: TStringList; procedure SetSQLStrings(const Value: TStringList); {$ENDIF} function GetSQLText: String; procedure SetSQLText(const Value: String); protected procedure QueryChanged(Sender: TObject); procedure PSExecute; override; procedure OpenCursor(InfoQuery: Boolean); override; public constructor Create(AOwner: TComponent); overload; override; destructor Destroy; override; procedure ExpandMacros; procedure Execute;{$IFDEF IBO}override;{$ENDIF} published property MacroChar: Char read FMacroChar write SetMacroChar; property Macros: TParams read FMacros write SetMacros; {$IFDEF IBX} property SQL: TStrings read GetSQL write SetSQL; {$ENDIF} property SQLText: String read GetSQLText write SetSQLText; end; //============================================================================================== //============================================================================================== //============================================================================================== implementation uses {$IFDEF UDEBUG}udebug,{$ENDIF} StrUtils, xStrUtils; const DefMacroChar : Char = '%'; {$IFDEF UDEBUG} var DEBUG_unit_ID: Integer; Debugging: Boolean; DEBUG_group_ID: String = ''; {$ENDIF} //============================================================================================== constructor TxIBQuery.Create(AOwner: TComponent); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TxIBQuery.Create') else _udebug := nil;{$ENDIF} inherited; self. FMacros := TParams.Create;//(Self, TParams); FMacroChar := DefMacroChar; {$IFDEF IBX}FSQL := TStringList.Create;{$ENDIF} //TStringList(SQL).OnChange := QueryChanged; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TxIBQuery.CreateMacros(AList: TParams; const AStr: string); var i: integer; TempStr: String; AddMacro: boolean; CurChar: Char; FPar: TParam; {$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TxIBQuery.CreateMacros') else _udebug := nil;{$ENDIF} TempStr := ''; AddMacro := False; AList.Clear; for i := 1 to Length(AStr) do begin CurChar := AStr[i]; if CurChar = FMacroChar then AddMacro := True else if (CurChar in [' ', ',', ')', ';', '=', #13, #10]) and (TempStr <> '') then begin FPar := TParam.Create(FMacros); FPar.Name := TempStr; FPar.DataType := ftString; TempStr := ''; AddMacro := False; end else if AddMacro then TempStr := TempStr + CurChar; end; if TempStr <> '' then begin FPar := TParam.Create(FMacros); FPar.Name := TempStr; FPar.DataType := ftString; end; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== destructor TxIBQuery.Destroy; {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TxIBQuery.Destroy') else _udebug := nil;{$ENDIF} FMacros.Free; {$IFDEF IBX}FreeAndNil(FSQL);{$ENDIF} inherited; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TxIBQuery.Execute; {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TxIBQuery.Execute') else _udebug := nil;{$ENDIF} ExpandMacros; {$IFDEF ZEOS}ExecSQL;{$ENDIF} {$IFDEF IBO}inherited;{$ENDIF} {$IFDEF IBX}ExecSQL;{$ENDIF} {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TxIBQuery.ExpandMacros; var Res: string; i: integer; {$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TxIBQuery.ExpandMacros') else _udebug := nil;{$ENDIF} Res := SQL.Text; for i := 0 to FMacros.Count-1 do begin Res := ReplaceStr(Res, FMacroChar + FMacros[i].Name, FMacros[i].AsString); end; inherited SQL.Text := Res; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== {$IFDEF IBX} function TxIBQuery.GetSQLStrings: TStringList; {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TxIBQuery.GetSQLStrings') else _udebug := nil;{$ENDIF} Result := FSQLStrings; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TxIBQuery.SetSQLStrings(const Value: TStringList); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TxIBQuery.SetSQLStrings') else _udebug := nil;{$ENDIF} FSQLstrings.Assign(Value); {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; {$ENDIF} // IBX section //============================================================================================== function TxIBQuery.GetSQLText: String; {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TxIBQuery.GetSQLText') else _udebug := nil;{$ENDIF} Result := SQL.Text; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TxIBQuery.SetSQLText(const Value: String); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin if SQL.Text = Value then Exit; {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TxIBQuery.SetSQLText') else _udebug := nil;{$ENDIF} SQL.Text := Value; QueryChanged(nil); {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TxIBQuery.OpenCursor(InfoQuery: Boolean); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TxIBQuery.OpenCursor') else _udebug := nil;{$ENDIF} ExpandMacros; inherited; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TxIBQuery.PSExecute; {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TxIBQuery.PSExecute') else _udebug := nil;{$ENDIF} ExpandMacros; inherited; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TxIBQuery.QueryChanged(Sender: TObject); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TxIBQuery.QueryChanged') else _udebug := nil;{$ENDIF} CreateMacros(FMacros, SQL.Text); //inherited SQL.Assign(SQL); {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TxIBQuery.SetMacroChar(const Value: Char); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TxIBQuery.SetMacroChar') else _udebug := nil;{$ENDIF} FMacroChar := Value; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TxIBQuery.SetMacros(const Value: TParams); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TxIBQuery.SetMacros') else _udebug := nil;{$ENDIF} FMacros.Assign(Value); {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== initialization {$IFDEF UDEBUG} Debugging := False; DEBUG_unit_ID := debugRegisterUnit('xIBQuery', @Debugging, DEBUG_group_ID); {$ENDIF} //============================================================================================== finalization {$IFDEF UDEBUG} //debugUnregisterUnit(DEBUG_unit_ID); {$ENDIF} end.
unit regexpname; (******************************************************************************* * Autor: Ulrich Hornung * Date: 05.05.2008 * * This Unit extend the TRegExpr-Class with named sub-expressions * ******************************************************************************) interface uses regexpr, Classes; type Tregexpn = class private namelist: array of string; procedure addsubexprname(nr: integer; name: string); procedure namedsubexpr(ex: string); public //Use this to access subexpressions by index! regexpr: TRegExpr; //Use this to start a new matching: function match(subject: string; Offset: Integer = 1): boolean; //Use this to continue matching: function matchnext: boolean; constructor Create; destructor Destroy; override; //Use this to set the (named)regular exprassion procedure setexpression(expr: string; namedsubex: boolean = true); //Use this to get the content of a named subexpression, //after successfull matching function getsubexpr(name: string): string; //keine Ahnung, nicht implementiert! function EscapeString(s: string): String; //Use this to get the name of the subexpression at index "nr" function MatchName(nr: integer): string; //Use this to get a list of all named subexpressions and its values // Format: <name> -> "<value>" <name2> -> "<value2>" ... function SubExListToStr: string; end; implementation uses SysUtils, StrUtils; procedure Tregexpn.addsubexprname(nr: integer; name: string); begin if nr >= 0 then begin if nr >= length(namelist) then setlength(namelist,nr+1); namelist[nr] := name; end else raise Exception.Create('regexpn.addsubexprname: negative nameindex!'); end; constructor Tregexpn.Create; begin inherited; regexpr := TRegExpr.Create; end; destructor Tregexpn.Destroy; begin regexpr.Free; inherited; end; function Tregexpn.EscapeString(s: string): String; begin Result := s; end; function Tregexpn.getsubexpr(name: string): string; var i: integer; begin Result := ''; i := 0; while i < length(namelist) do begin if name = namelist[i] then begin Result := regexpr.Match[i]; break; end; inc(i); end; end; function Tregexpn.matchnext: boolean; begin result := regexpr.ExecNext; end; function Tregexpn.match(subject: string; Offset: Integer = 1): boolean; begin regexpr.InputString := subject; result := regexpr.ExecPos(Offset); end; procedure Tregexpn.namedsubexpr(ex: string); var p, pe, i: integer; exn, exname: string; begin exn := ''; i := 0; p := Pos('(',ex); while (p > 0) do begin if ((p = 1)or(ex[p-1] <> '\')) then begin pe := PosEx('>',ex,p); inc(i); if ((copy(ex,p,3) = '(?<')and(pe > 0)) then begin exname := copy(ex,p+3,pe-(p+3)); Delete(ex,p+1,pe-p); addsubexprname(i,exname); end; //else addsubexprname(i,''); end; exn := exn + copy(ex,1,p); Delete(ex,1,p); p := Pos('(',ex); end; exn := exn + ex; regexpr.Expression := exn; end; procedure Tregexpn.setexpression(expr: string; namedsubex: boolean = true); begin SetLength(namelist,0); if namedsubex then namedsubexpr(expr) else regexpr.Expression := expr; end; function Tregexpn.MatchName(nr: integer): string; begin if nr < length(namelist) then Result := namelist[nr] else Result := ''; end; function Tregexpn.SubExListToStr: string; var i: integer; begin Result := ''; for i := 0 to length(namelist)-1 do if (namelist[i] <> '') then begin Result := Result + namelist[i] + ' -> "' + getsubexpr(namelist[i]) + '" '; end; end; end.
unit NPSAddForma; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Mask, DBCtrlsEh, Vcl.ImgList, Vcl.Buttons, FIBQuery, pFIBQuery; type TNPSAddForm = class(TForm) ilSmiles: TImageList; cbRating: TDBComboBoxEh; bbCancel: TBitBtn; bbOk: TBitBtn; mmoNotice: TDBMemoEh; lbl1: TLabel; qInsert: TpFIBQuery; procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure bbOkClick(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure cbRatingKeyPress(Sender: TObject; var Key: Char); private { Private declarations } public { Public declarations } end; function AddNpsRating(const aCustomer_id: int64): int64; implementation uses DM; {$R *.dfm} function AddNpsRating(const aCustomer_id: int64): int64; var frm: TNPSAddForm; v : integer; begin Result := -1; frm := TNPSAddForm.Create(application); try if frm.showmodal = mrOk then begin if TryStrToInt(frm.cbRating.Text, v) then begin frm.qInsert.ParamByName('CUSTOMER_ID').AsInteger := aCustomer_id; frm.qInsert.ParamByName('Rating').AsInteger := v; frm.qInsert.ParamByName('NOTICE').AsString := frm.mmoNotice.Lines.Text; frm.qInsert.Transaction.StartTransaction; frm.qInsert.ExecQuery; frm.qInsert.Transaction.Commit; end; end; finally frm.Free; end; end; procedure TNPSAddForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Shift = [ssCtrl]) and (Ord(Key) = VK_RETURN) then bbOkClick(Sender); end; procedure TNPSAddForm.bbOkClick(Sender: TObject); var AllFine: Boolean; i: Integer; begin AllFine := False; if TryStrToInt(cbRating.Text, i) and (Length(mmoNotice.Lines.Text) > 3) then AllFine := (i >= 0) and (i <= 10); if AllFine then ModalResult := mrOk; end; procedure TNPSAddForm.FormKeyPress(Sender: TObject; var Key: Char); begin if (Key = #13 { VK_RETURN } ) and (ActiveControl = cbRating) then begin Key := #0; PostMessage(Self.Handle, WM_NEXTDLGCTL, 0, 0); end; end; procedure TNPSAddForm.cbRatingKeyPress(Sender: TObject; var Key: Char); begin if not(CharInSet(Key, ['0' .. '9', #8 { VK_BACK } , #40 { VK_DOWN } , #38 { VK_UP } , #27 { VK_ESCAPE } ])) then Key := #0 end; end.
unit nevControlPara; // Модуль: "w:\common\components\gui\Garant\Everest\new\nevControlPara.pas" // Стереотип: "SimpleClass" // Элемент модели: "TnevControlPara" MUID: (48D11BE0015E) {$Include w:\common\components\gui\Garant\Everest\evDefine.inc} interface {$If Defined(k2ForEditor)} uses l3IntfUses , nevTextPara , nevTools , evQueryCardInt , l3Variant , l3Interfaces , evdTypes , nevBase ; type TnevControlPara = class(TnevTextPara, IevCommonControl, IevControl, IevControlFriend) protected function Get_Enabled: Boolean; function Get_Checked: Boolean; procedure Set_Checked(aValue: Boolean); function Get_Flat: Boolean; function Get_Name: Tl3WString; function Get_Text: Tl3WString; function Get_ControlType: TevControlType; function Get_Upper: Boolean; procedure Set_Upper(aValue: Boolean); function pm_GetCollapsed: Boolean; procedure pm_SetCollapsed(aValue: Boolean); function GetControl: IevEditorControl; {* Получить контрол по ссылке. } function TreatCollapsedAsHidden: Boolean; override; function GetText: TnevStr; override; public class function Make(aTag: Tl3Variant): IevControlFriend; reintroduce; end;//TnevControlPara {$IfEnd} // Defined(k2ForEditor) implementation {$If Defined(k2ForEditor)} uses l3ImplUses , l3StringIDEx , k2Tags , l3String , afwFacade , afwInterfaces //#UC START# *48D11BE0015Eimpl_uses* //#UC END# *48D11BE0015Eimpl_uses* ; const {* Локализуемые строки Local } str_MemoHintForConsult: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'MemoHintForConsult'; rValue : 'Введите текст запроса'); {* 'Введите текст запроса' } class function TnevControlPara.Make(aTag: Tl3Variant): IevControlFriend; var l_Inst : TnevControlPara; begin l_Inst := Create(aTag); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TnevControlPara.Make function TnevControlPara.Get_Enabled: Boolean; //#UC START# *47C7CDC802F0_48D11BE0015Eget_var* //#UC END# *47C7CDC802F0_48D11BE0015Eget_var* begin //#UC START# *47C7CDC802F0_48D11BE0015Eget_impl* Result := GetRedirect.BoolA[k2_tiEnabled]; //#UC END# *47C7CDC802F0_48D11BE0015Eget_impl* end;//TnevControlPara.Get_Enabled function TnevControlPara.Get_Checked: Boolean; //#UC START# *47C7CDD80342_48D11BE0015Eget_var* //#UC END# *47C7CDD80342_48D11BE0015Eget_var* begin //#UC START# *47C7CDD80342_48D11BE0015Eget_impl* Result := GetRedirect.BoolA[k2_tiChecked]; //#UC END# *47C7CDD80342_48D11BE0015Eget_impl* end;//TnevControlPara.Get_Checked procedure TnevControlPara.Set_Checked(aValue: Boolean); //#UC START# *47C7CDD80342_48D11BE0015Eset_var* //#UC END# *47C7CDD80342_48D11BE0015Eset_var* begin //#UC START# *47C7CDD80342_48D11BE0015Eset_impl* GetRedirect.BoolW[k2_tiChecked, nil] := aValue; //#UC END# *47C7CDD80342_48D11BE0015Eset_impl* end;//TnevControlPara.Set_Checked function TnevControlPara.Get_Flat: Boolean; //#UC START# *47C7CDE7036F_48D11BE0015Eget_var* //#UC END# *47C7CDE7036F_48D11BE0015Eget_var* begin //#UC START# *47C7CDE7036F_48D11BE0015Eget_impl* Result := GetRedirect.BoolA[k2_tiFlat]; //#UC END# *47C7CDE7036F_48D11BE0015Eget_impl* end;//TnevControlPara.Get_Flat function TnevControlPara.Get_Name: Tl3WString; //#UC START# *47C7CE080350_48D11BE0015Eget_var* //#UC END# *47C7CE080350_48D11BE0015Eget_var* begin //#UC START# *47C7CE080350_48D11BE0015Eget_impl* Result := GetRedirect.PCharLenA[k2_tiName]; //#UC END# *47C7CE080350_48D11BE0015Eget_impl* end;//TnevControlPara.Get_Name function TnevControlPara.Get_Text: Tl3WString; //#UC START# *47C7CE18022D_48D11BE0015Eget_var* //#UC END# *47C7CE18022D_48D11BE0015Eget_var* begin //#UC START# *47C7CE18022D_48D11BE0015Eget_impl* Result := pm_GetText{GetRedirect.PCharLenA[k2_tiText]}; //#UC END# *47C7CE18022D_48D11BE0015Eget_impl* end;//TnevControlPara.Get_Text function TnevControlPara.Get_ControlType: TevControlType; //#UC START# *47C7CE270211_48D11BE0015Eget_var* //#UC END# *47C7CE270211_48D11BE0015Eget_var* begin //#UC START# *47C7CE270211_48D11BE0015Eget_impl* Result := TevControlType(GetRedirect.IntA[k2_tiType]); //#UC END# *47C7CE270211_48D11BE0015Eget_impl* end;//TnevControlPara.Get_ControlType function TnevControlPara.Get_Upper: Boolean; //#UC START# *47C7CE3500E1_48D11BE0015Eget_var* //#UC END# *47C7CE3500E1_48D11BE0015Eget_var* begin //#UC START# *47C7CE3500E1_48D11BE0015Eget_impl* Result := GetRedirect.BoolA[k2_tiUpper]; //#UC END# *47C7CE3500E1_48D11BE0015Eget_impl* end;//TnevControlPara.Get_Upper procedure TnevControlPara.Set_Upper(aValue: Boolean); //#UC START# *47C7CE3500E1_48D11BE0015Eset_var* //#UC END# *47C7CE3500E1_48D11BE0015Eset_var* begin //#UC START# *47C7CE3500E1_48D11BE0015Eset_impl* GetRedirect.BoolW[k2_tiUpper, nil{StartOp}] := aValue; //#UC END# *47C7CE3500E1_48D11BE0015Eset_impl* end;//TnevControlPara.Set_Upper function TnevControlPara.pm_GetCollapsed: Boolean; //#UC START# *47C7CEFB0205_48D11BE0015Eget_var* //#UC END# *47C7CEFB0205_48D11BE0015Eget_var* begin //#UC START# *47C7CEFB0205_48D11BE0015Eget_impl* Result := GetRedirect.BoolA[k2_tiCollapsed]; //#UC END# *47C7CEFB0205_48D11BE0015Eget_impl* end;//TnevControlPara.pm_GetCollapsed procedure TnevControlPara.pm_SetCollapsed(aValue: Boolean); //#UC START# *47C7CEFB0205_48D11BE0015Eset_var* //#UC END# *47C7CEFB0205_48D11BE0015Eset_var* begin //#UC START# *47C7CEFB0205_48D11BE0015Eset_impl* GetRedirect.BoolW[k2_tiCollapsed,nil] := aValue; Invalidate([nev_spExtent]); //#UC END# *47C7CEFB0205_48D11BE0015Eset_impl* end;//TnevControlPara.pm_SetCollapsed function TnevControlPara.GetControl: IevEditorControl; {* Получить контрол по ссылке. } //#UC START# *47CD77350118_48D11BE0015E_var* //#UC END# *47CD77350118_48D11BE0015E_var* begin //#UC START# *47CD77350118_48D11BE0015E_impl* GetRedirect.QT(IevEditorControl, Result); //#UC END# *47CD77350118_48D11BE0015E_impl* end;//TnevControlPara.GetControl function TnevControlPara.TreatCollapsedAsHidden: Boolean; //#UC START# *4D596369028C_48D11BE0015E_var* //#UC END# *4D596369028C_48D11BE0015E_var* begin //#UC START# *4D596369028C_48D11BE0015E_impl* Result := false; //#UC END# *4D596369028C_48D11BE0015E_impl* end;//TnevControlPara.TreatCollapsedAsHidden function TnevControlPara.GetText: TnevStr; //#UC START# *4D7255870102_48D11BE0015E_var* //#UC END# *4D7255870102_48D11BE0015E_var* begin //#UC START# *4D7255870102_48D11BE0015E_impl* Result := inherited GetText; // Для английской версии хинт не нужен // http://mdp.garant.ru/pages/viewpage.action?pageId=497680583 if (afw.Application <> nil) then if (afw.Application.LocaleInfo.Language <> afw_lngEnglish) AND l3IsNil(Result) AND (Get_ControlType = ev_ctMemoEdit) then Result := str_MemoHintForConsult.AsWStr; //#UC END# *4D7255870102_48D11BE0015E_impl* end;//TnevControlPara.GetText initialization str_MemoHintForConsult.Init; {* Инициализация str_MemoHintForConsult } {$IfEnd} // Defined(k2ForEditor) end.
unit MPWS.MainForm; 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.Edit, FMX.Controls.Presentation, MPWS.WebServer; type TMainForm = class(TForm) ButtonStart: TButton; ButtonStop: TButton; EditPort: TEdit; PortLabel: TLabel; procedure ButtonStartClick(Sender: TObject); procedure ButtonStopClick(Sender: TObject); private FServer: TWebServer; procedure ApplicationIdle(Sender: TObject; var Done: Boolean); public constructor Create(AOwner: TComponent); override; end; var MainForm: TMainForm; implementation {$R *.fmx} constructor TMainForm.Create(AOwner: TComponent); begin inherited; Application.OnIdle := ApplicationIdle; FServer := TWebServer.Create(Self); end; procedure TMainForm.ApplicationIdle(Sender: TObject; var Done: Boolean); begin ButtonStart.Enabled := not FServer.IsActive; ButtonStop.Enabled := FServer.IsActive; EditPort.Enabled := not FServer.IsActive; end; procedure TMainForm.ButtonStartClick(Sender: TObject); begin FServer.Port := StrToInt(EditPort.Text); FServer.Start; end; procedure TMainForm.ButtonStopClick(Sender: TObject); begin FServer.Stop; end; end.
unit MainExamplesUnit; interface uses Classes, SysUtils; type TExamples = class public class procedure Run; end; implementation uses System.Generics.Collections, DataObjectUnit, Route4MeExamplesUnit, NullableBasicTypesUnit, AddressUnit, AddressBookContactUnit, OutputUnit, ConnectionUnit, OrderUnit, CommonTypesUnit, AddOrderToRouteParameterProviderUnit, AddOrderToRouteRequestUnit, EnumsUnit, UserParameterProviderUnit, UserParametersUnit; const //your api key c_ApiKey = '11111111111111111111111111111111'; class procedure TExamples.Run; var Examples: TRoute4MeExamples; i: integer; DataObject, DataObject1, DataObject2: TDataObject; RouteSingleDriverRoute10Stops: TDataObjectRoute; RouteId_SingleDriverRoute10Stops: NullableString; RouteId_SingleDriverRoundTrip: NullableString; RouteIdToMoveTo: NullableString; DestinationIds: TArray<integer>; RouteDestinationIdToMove, AfterDestinationIdToMoveAfter: NullableInteger; OptimizationProblemId: NullableString; RouteId_MultipleDepotMultipleDriver: NullableString; RouteId_MultipleDepotMultipleDriverTimeWindow: NullableString; RouteId_SingleDepotMultipleDriverNoTimeWindow: NullableString; RouteId_MultipleDepotMultipleDriverWith24StopsTimeWindow: NullableString; RouteId_SingleDriverMultipleTimeWindows: NullableString; DestinationToRemove: TAddress; GetRouteDirections, GetRoutePathPoints: boolean; RouteId_DuplicateRoute: NullableString; RouteIdsToDelete: TListString; RouteIdsToMerge: TListString; Contact1, Contact2: TAddressBookContact; AddressIdsToRemove: TList<integer>; TerritoryId: NullableString; Order1, Order2: TOrder; OrderIdsToRemove: TList<integer>; Connection: TConnection; Routes: TDataObjectRouteList; OrderedAddresses: TOrderedAddressArray; ParametersProvider: IAddOrderToRouteParameterProvider; UserParameters: TUserParameters; AddNewUserParameterProvider: IUserParameterProvider; Parameters: TAddOrderToRouteRequest; RouteId: String; RouteDestinationId: integer; AddressId: NullableInteger; MemberId: integer; EMail: String; Limit, Offset: integer; SessionGuid: NullableString; begin try Connection := TConnection.Create(c_ApiKey); Examples := TRoute4MeExamples.Create(TOutputConsole.Create, Connection); try try Randomize; AddNewUserParameterProvider := TUserParameterProvider.Create; EMail := 'marketing@kcswest.com'; UserParameters := AddNewUserParameterProvider.GetParameters(EMail); try MemberId := Examples.AddNewUser(UserParameters); Examples.GetUserDetails(MemberId); UserParameters.MemberId := MemberId; UserParameters.FirstName := 'John'; Examples.UpdateUser(UserParameters); SessionGuid := Examples.Authentication(UserParameters.Email, UserParameters.Password); finally FreeAndNil(UserParameters); end; if SessionGuid.IsNotNull then Examples.ValidateSession(SessionGuid, MemberId); Examples.GetUsers(); Examples.RemoveUser(MemberId); Examples.BatchForwardGeocodeAddress('Los20%Angeles20%International20%Airport,20%CA'); DataObject1 := Examples.SingleDriverRoute10Stops(); if (DataObject1 <> nil) and (DataObject1.Routes <> nil) and (Length(DataObject1.Routes) > 0) then begin RouteSingleDriverRoute10Stops := DataObject1.Routes[0]; RouteId_SingleDriverRoute10Stops := RouteSingleDriverRoute10Stops.RouteId; Examples.ResequenceRouteDestinations(RouteSingleDriverRoute10Stops); Examples.ResequenceAllRouteDestinations(RouteId_SingleDriverRoute10Stops); end else begin RouteSingleDriverRoute10Stops := nil; RouteId_SingleDriverRoute10Stops := NullableString.Null; WriteLn('ResequenceRouteDestinations, ResequenceAllRouteDestinations not called. ' + 'RouteSingleDriverRoute10Stops = null.'); end; if (RouteSingleDriverRoute10Stops <> nil) then Examples.ShareRoute(RouteSingleDriverRoute10Stops.RouteId, 'oooooo@gmail.com'); DestinationIds := Examples.AddRouteDestinationsOptimally(RouteId_SingleDriverRoute10Stops); if (Length(DestinationIds) > 0) then Examples.RemoveRouteDestination(RouteId_SingleDriverRoute10Stops, DestinationIds[0]); DestinationIds := Examples.AddRouteDestinations(RouteId_SingleDriverRoute10Stops); if (Length(DestinationIds) > 0) then Examples.RemoveRouteDestination(RouteId_SingleDriverRoute10Stops, DestinationIds[0]); DataObject2 := Examples.SingleDriverRoundTrip(); if (DataObject2 <> nil) and (DataObject2.Routes <> nil) and (Length(DataObject2.Routes) > 0) then RouteId_SingleDriverRoundTrip := DataObject2.Routes[0].RouteId else RouteId_SingleDriverRoundTrip := NullableString.Null; RouteIdToMoveTo := routeId_SingleDriverRoundTrip; if (DataObject1 <> nil) and (Length(DataObject1.Routes) > 0) and (Length(DataObject1.Routes[0].Addresses) > 1) and (DataObject1.Routes[0].Addresses[1].RouteDestinationId.IsNotNull) then RouteDestinationIdToMove := DataObject1.Routes[0].Addresses[1].RouteDestinationId.Value else RouteDestinationIdToMove := NullableInteger.Null; if (DataObject2 <> nil) and (Length(DataObject2.Routes) > 0) and (Length(DataObject2.Routes[0].Addresses) > 1) and (DataObject2.Routes[0].Addresses[0].RouteDestinationId.IsNotNull) then AfterDestinationIdToMoveAfter := DataObject2.Routes[0].Addresses[0].RouteDestinationId.Value else AfterDestinationIdToMoveAfter := NullableInteger.Null; if RouteIdToMoveTo.IsNotNull and RouteDestinationIdToMove.IsNotNull and AfterDestinationIdToMoveAfter.IsNotNull then Examples.MoveDestinationToRoute(RouteIdToMoveTo, RouteDestinationIdToMove, AfterDestinationIdToMoveAfter) else WriteLn(Format( 'MoveDestinationToRoute not called. routeDestinationId = %d, afterDestinationId = %d.', [RouteDestinationIdToMove.Value, AfterDestinationIdToMoveAfter.Value])); OptimizationProblemId := Examples.SingleDriverRoundTripGeneric(); DataObject := Examples.MultipleDepotMultipleDriver(); try if (DataObject <> nil) and (Length(DataObject.Routes) > 0) then RouteId_MultipleDepotMultipleDriver := DataObject.Routes[0].RouteId else RouteId_MultipleDepotMultipleDriver := NullableString.Null; finally FreeAndNil(DataObject); end; DataObject := Examples.MultipleDepotMultipleDriverTimeWindow(); try if (DataObject <> nil) and (Length(DataObject.Routes) > 0) then RouteId_MultipleDepotMultipleDriverTimeWindow := DataObject.Routes[0].RouteId else RouteId_MultipleDepotMultipleDriverTimeWindow := NullableString.Null; finally FreeAndNil(DataObject); end; DataObject := Examples.SingleDepotMultipleDriverNoTimeWindow(); try if (DataObject <> nil) and (Length(DataObject.Routes) > 0) then RouteId_SingleDepotMultipleDriverNoTimeWindow := DataObject.Routes[0].RouteId else RouteId_SingleDepotMultipleDriverNoTimeWindow := NullableString.Null; finally FreeAndNil(DataObject); end; DataObject := Examples.MultipleDepotMultipleDriverWith24StopsTimeWindow(); try if (DataObject <> nil) and (Length(DataObject.Routes) > 0) then RouteId_MultipleDepotMultipleDriverWith24StopsTimeWindow := DataObject.Routes[0].RouteId else RouteId_MultipleDepotMultipleDriverWith24StopsTimeWindow := NullableString.Null; finally FreeAndNil(DataObject); end; DataObject := Examples.SingleDriverMultipleTimeWindows(); try if (DataObject <> nil) and (Length(DataObject.Routes) > 0) then RouteId_SingleDriverMultipleTimeWindows := DataObject.Routes[0].RouteId else RouteId_SingleDriverMultipleTimeWindows := NullableString.Null; finally FreeAndNil(DataObject); end; if (OptimizationProblemId.IsNotNull) then Examples.GetOptimization(OptimizationProblemId) else WriteLn('GetOptimization not called. OptimizationProblemID is null.'); Examples.GetOptimizations(); if (OptimizationProblemId.IsNotNull) then DataObject := Examples.AddDestinationToOptimization(OptimizationProblemId, True) else begin WriteLn('AddDestinationToOptimization not called. optimizationProblemID is null.'); DataObject := nil; end; try if (OptimizationProblemId.IsNotNull) then begin if (DataObject <> nil) and (Length(DataObject.Addresses) > 0) then begin DestinationToRemove := DataObject.Addresses[High(DataObject.Addresses)]; Examples.RemoveDestinationFromOptimization(OptimizationProblemId, DestinationToRemove.RouteDestinationId, False); end else WriteLn('RemoveDestinationFromOptimization not called. DestinationToRemove is null.'); end else WriteLn('RemoveDestinationFromOptimization not called. OptimizationProblemID is null.'); finally FreeAndNil(DataObject); end; if (OptimizationProblemId.IsNotNull) then Examples.ReOptimization(OptimizationProblemId) else WriteLn('ReOptimization not called. OptimizationProblemID is null.'); if (RouteId_SingleDriverRoute10Stops.IsNotNull) then begin Examples.UpdateRoute(RouteId_SingleDriverRoute10Stops); Examples.UpdateRoutesCustomFields(RouteId_SingleDriverRoute10Stops, RouteDestinationIdToMove); Examples.ReoptimizeRoute(RouteId_SingleDriverRoute10Stops); GetRouteDirections := True; GetRoutePathPoints := True; Examples.GetRoute(RouteId_SingleDriverRoute10Stops, GetRouteDirections, GetRoutePathPoints); end else WriteLn('UpdateRoute, UpdateRoutesCustomFields, ReoptimizeRoute, GetRoute not called. ' + 'routeId_SingleDriverRoute10Stops is null.'); Limit := 10; Offset := 5; Routes := Examples.GetRoutes(Limit, Offset); try RouteIdsToMerge := TListString.Create; try if (Routes.Count > 0) then RouteIdsToMerge.Add(Routes[0].RouteId); if (Routes.Count > 1) then RouteIdsToMerge.Add(Routes[1].RouteId); if (RouteIdsToMerge.Count > 0) then Examples.MergeRoutes(RouteIdsToMerge) else WriteLn('RouteIdsToMerge.Count = 0. MergeRoutes not called.'); finally FreeAndNil(RouteIdsToMerge); end; finally FreeAndNil(Routes); end; Examples.GetAreaAddedActivities; Examples.GetAreaUpdatedActivities; Examples.GetAreaRemovedActivities; Examples.GetDestinationDeletedActivities; Examples.GetDestinationOutOfSequenceActivities; Examples.GetDriverArrivedEarlyActivities; Examples.GetDriverArrivedLateActivities; Examples.GetDriverArrivedOnTimeActivities; Examples.GetGeofenceEnteredActivities; Examples.GetGeofenceLeftActivities; Examples.GetAllDestinationInsertedActivities; Examples.GetAllDestinationMarkedAsDepartedActivities; Examples.GetAllDestinationMarkedAsVisitedActivities; Examples.GetMemberCreatedActivities; Examples.GetMemberDeletedActivities; Examples.GetMemberModifiedActivities; Examples.GetDestinationMovedActivities; Examples.GetAllNoteInsertedActivities; Examples.GetRouteDeletedActivities; Examples.GetRouteOptimizedActivities; Examples.GetRouteOwnerChangedActivities; Examples.GetDestinationUpdatedActivities; Limit := 5; Offset := 0; Examples.GetAllActivities(Limit, Offset); if (RouteId_SingleDriverRoute10Stops.IsNotNull) then begin Examples.LogSpecificMessage('Test User Activity ' + DateTimeToStr(Now), RouteId_SingleDriverRoute10Stops); Examples.GetTeamActivities(RouteId_SingleDriverRoute10Stops, Limit, Offset); Examples.GetDestinationInsertedActivities(RouteId_SingleDriverRoute10Stops); Examples.GetDestinationMarkedAsDepartedActivities(RouteId_SingleDriverRoute10Stops); Examples.GetNoteInsertedActivities(RouteId_SingleDriverRoute10Stops); end else WriteLn('LogCustomActivity not called. routeId_SingleDriverRoute10Stops is null.'); Randomize; // Address Book Contact1 := Examples.CreateLocation('Test FirstName 1', 'Test Address 1'); Contact2 := Examples.CreateLocation('Test FirstName 2', 'Test Address 2'); try Examples.GetLocations(); Examples.GetLocationsByIds([Contact1.Id, Contact2.Id]); Examples.GetLocation('FirstName'); Examples.LocationSearch('FirstName', ['first_name', 'address_1']); Examples.DisplayRouted(); if (Contact1 <> nil) then begin AddressId := Contact1.Id; Contact1.LastName := 'Updated ' + IntToStr(Random(100)); Examples.UpdateLocation(Contact1); end else WriteLn('contact1 = null. UpdateAddressBookContact not called.'); AddressIdsToRemove := TList<integer>.Create(); try if (Contact1 <> nil) then AddressIdsToRemove.Add(Contact1.Id); if (Contact2 <> nil) then AddressIdsToRemove.Add(Contact2.Id); Examples.RemoveLocations(AddressIdsToRemove.ToArray()); finally FreeAndNil(AddressIdsToRemove); end; finally FreeAndNil(Contact2); FreeAndNil(Contact1); end; // Addresses if (RouteIdToMoveTo.IsNotNull) and (RouteDestinationIdToMove <> 0) then begin RouteId := RouteIdToMoveTo; RouteDestinationId := RouteDestinationIdToMove; Examples.GetAddress(RouteId, RouteDestinationId); Examples.MarkAddressAsDetectedAsVisited(RouteId, RouteDestinationId, True); Examples.MarkAddressAsDetectedAsDeparted(RouteId, RouteDestinationId, True); if AddressId.IsNotNull then begin MemberId := 1; // todo: в ответ возвращается 0, а не status=true/false. Может MemberId нужен другой? Examples.MarkAddressAsVisited(RouteId, AddressId, MemberId, True); // todo: status возвращается False, может MemberId нужен другой? Examples.MarkAddressAsDeparted(RouteId, AddressId, MemberId, True); end; Examples.AddAddressNote(RouteId, RouteDestinationId); Examples.GetAddressNotes(RouteId, RouteDestinationId); end else WriteLn('AddAddressNote, GetAddress, GetAddressNotes not called. routeIdToMoveTo == null || routeDestinationIdToMove == 0.'); RouteId_DuplicateRoute := NullableString.Null; if (RouteId_SingleDriverRoute10Stops.IsNotNull) then RouteId_DuplicateRoute := Examples.DuplicateRoute(RouteId_SingleDriverRoute10Stops) else WriteLn('DuplicateRoute not called. routeId_SingleDriverRoute10Stops is null.'); //disabled by default, not necessary for optimization tests //not all accounts are capable of storing gps data //if (RouteId_SingleDriverRoute10Stops.IsNotNull) then //begin // ExamplesOld.SetGPSPosition(RouteId_SingleDriverRoute10Stops); // ExamplesOld.TrackDeviceLastLocationHistory(RouteId_SingleDriverRoute10Stops); //end //else // WriteLn('SetGPSPosition, TrackDeviceLastLocationHistory not called. routeId_SingleDriverRoute10Stops is null.'); RouteIdsToDelete := TListString.Create(); try if (RouteId_SingleDriverRoute10Stops.IsNotNull) then RouteIdsToDelete.Add(RouteId_SingleDriverRoute10Stops); if (RouteId_SingleDriverRoundTrip.IsNotNull) then RouteIdsToDelete.Add(RouteId_SingleDriverRoundTrip); if (RouteId_DuplicateRoute.IsNotNull) then RouteIdsToDelete.Add(RouteId_DuplicateRoute); if (RouteId_MultipleDepotMultipleDriver.IsNotNull) then RouteIdsToDelete.Add(RouteId_MultipleDepotMultipleDriver); if (RouteId_MultipleDepotMultipleDriverTimeWindow.IsNotNull) then RouteIdsToDelete.Add(RouteId_MultipleDepotMultipleDriverTimeWindow); if (RouteId_SingleDepotMultipleDriverNoTimeWindow.IsNotNull) then RouteIdsToDelete.Add(RouteId_SingleDepotMultipleDriverNoTimeWindow); if (RouteId_MultipleDepotMultipleDriverWith24StopsTimeWindow.IsNotNull) then RouteIdsToDelete.Add(RouteId_MultipleDepotMultipleDriverWith24StopsTimeWindow); if (RouteId_SingleDriverMultipleTimeWindows.IsNotNull) then RouteIdsToDelete.Add(RouteId_SingleDriverMultipleTimeWindows); if (RouteIdsToDelete.Count > 0) then Examples.DeleteRoutes(RouteIdsToDelete.ToArray()) else WriteLn('RouteIdsToDelete.Count = 0. DeleteRoutes not called.'); finally FreeAndNil(RouteIdsToDelete); end; // Remove optimization if (OptimizationProblemId.IsNotNull) then Examples.RemoveOptimization(OptimizationProblemId) else WriteLn('RemoveOptimization not called. OptimizationProblemID is null.'); // Avoidance Zones TerritoryId := Examples.AddCircleAvoidanceZone(); TerritoryId := Examples.AddRectangularAvoidanceZone(); TerritoryId := Examples.AddPolygonAvoidanceZone(); Examples.GetAvoidanceZones(); if (TerritoryId.IsNotNull) then Examples.GetAvoidanceZone(TerritoryId) else WriteLn('GetAvoidanceZone not called. territoryId is null.'); if (TerritoryId.IsNotNull) then Examples.UpdateAvoidanceZone(TerritoryId) else WriteLn('UpdateAvoidanceZone not called. territoryId is null.'); if (TerritoryId.IsNotNull) then Examples.DeleteAvoidanceZone(TerritoryId) else WriteLn('DeleteAvoidanceZone not called. territoryId is null.'); // Territories TerritoryId := Examples.AddCircleTerritory(); TerritoryId := Examples.AddRectangularTerritory(); TerritoryId := Examples.AddPolygonTerritory(); Examples.GetTerritories(); if (TerritoryId.IsNotNull) then Examples.GetTerritory(TerritoryId) else WriteLn('GetTerritory not called. territoryId is null.'); if (TerritoryId.IsNotNull) then Examples.UpdateTerritory(TerritoryId) else WriteLn('GetTerritory not called. territoryId is null.'); if (TerritoryId.IsNotNull) then Examples.RemoveTerritory(TerritoryId) else WriteLn('RemoveTerritory not called. territoryId is null.'); // Orders Order1 := Examples.AddOrder(); Order2 := Examples.AddOrder(); try // Get an order by order_id Examples.GetOrder(Order1.Id); // Get all the orders created under the specific Route4Me account. Examples.GetOrders(); // Retrieve orders inserted on a specified date Examples.GetOrders(Now); // Retrieve orders scheduled for a specified date Examples.GetOrdersScheduledFor(Now); // Search for all order records which contain specified text in any field Examples.GetOrdersWithSpecifiedText('John'); if (Order1 <> nil) then begin Order1.LastName := 'Updated ' + IntToStr(Random(100)); Examples.UpdateOrder(Order1); end else WriteLn('Order1 == null. UpdateOrder not called.'); // AddOrderToRoute sample DataObject := Examples.MultipleDepotMultipleDriver(); try if (DataObject <> nil) then begin ParametersProvider := TAddOrderToRouteParameterProvider.Create; OrderedAddresses := ParametersProvider.GetAddresses; try OrderedAddresses[0].OrderId := Order1.Id; OrderedAddresses[1].OrderId := Order2.Id; // AddOrderToOptimization sample OptimizationProblemId := DataObject.OptimizationProblemId; Examples.AddOrderToOptimization(OptimizationProblemId, DataObject.Parameters, OrderedAddresses); // AddOrderToRoute sample if (Length(DataObject.Routes) > 0) then begin RouteId_MultipleDepotMultipleDriver := DataObject.Routes[0].RouteId; Examples.AddOrderToRoute(RouteId_MultipleDepotMultipleDriver, DataObject.Parameters, OrderedAddresses); end; finally for i := Length(OrderedAddresses) - 1 downto 0 do FreeAndNil(OrderedAddresses[i]); ParametersProvider := nil; end; Examples.DeleteRoutes([RouteId_MultipleDepotMultipleDriver]); end; finally FreeAndNil(DataObject); end; OrderIdsToRemove := TList<integer>.Create(); try if (Order1 <> nil) then OrderIdsToRemove.Add(Order1.Id); if (Order2 <> nil) then OrderIdsToRemove.Add(Order2.Id); Examples.RemoveOrders(OrderIdsToRemove.ToArray()); finally FreeAndNil(OrderIdsToRemove); end; finally FreeAndNil(Order2); FreeAndNil(Order1); end; Examples.GenericExample(Connection); Examples.GenericExampleShortcut(Connection); except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; finally FreeAndNil(Examples); end; finally WriteLn(''); WriteLn('Press any key'); ReadLn; end; end; end.
unit MenuGroupDialog; interface uses System.SysUtils, System.Generics.Collections, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, UDialog, FMX.Objects, UModel; type TGroupDialog = class(TDialogFrame) MenuGroupBtn1: TButton; MenuGroupBtn2: TButton; MenuGroupBtn3: TButton; MenuGroupBtn4: TButton; MenuGroupBtn5: TButton; PageupBtn: TButton; PageDownBtn: TButton; CancelBtn: TButton; Instructionlbl: TLabel; Rectangle2: TRectangle; procedure MenuGroupBtnClick(Sender: TObject); procedure PageupBtnClick(Sender: TObject); procedure PageDownBtnClick(Sender: TObject); procedure CancelBtnClick(Sender: TObject); private { Private declarations } BtnList: TList<TButton>; TotalPageCount: Integer; CurrentpageCount: Integer; StartIndex, EndIndex: Integer; procedure ShowCurrentPage(PageNumber: Integer); procedure CaculateIdxRange; procedure CaculateMaxPage; public { Public declarations } MenuGroups: TMenuGroups; Constructor Create(ParentForm: TForm; ParentPanel: TPanel; CallBackProc: IProcessDialogResult); end; var GroupDialog: TGroupDialog; implementation {$R *.fmx} { TDialogFrame1 } procedure TGroupDialog.CaculateIdxRange; var IsLastPage: Boolean; begin IsLastPage := (CurrentpageCount = TotalPageCount); if IsLastPage then begin StartIndex := (TotalPageCount - 1) * BtnList.Count; EndIndex := MenuGroups.MenuGroupList.Count - 1 end else begin StartIndex := (CurrentpageCount - 1) * BtnList.Count; EndIndex := CurrentpageCount * BtnList.Count - 1; end; end; procedure TGroupDialog.CaculateMaxPage; begin if (MenuGroups.MenuGroupList.Count mod BtnList.Count) = 0 then TotalPageCount := MenuGroups.MenuGroupList.Count div BtnList.Count else TotalPageCount := MenuGroups.MenuGroupList.Count div BtnList.Count + 1; end; procedure TGroupDialog.CancelBtnClick(Sender: TObject); begin DialogResult := mrCancel; FProcessDialogResult.ProcessDialogResult; end; constructor TGroupDialog.Create(ParentForm: TForm; ParentPanel: TPanel; CallBackProc: IProcessDialogResult); begin inherited; BtnList := TList<TButton>.Create; BtnList.Add(MenuGroupBtn1); BtnList.Add(MenuGroupBtn2); BtnList.Add(MenuGroupBtn3); BtnList.Add(MenuGroupBtn4); BtnList.Add(MenuGroupBtn5); Rectangle2.Width := Rectangle1.Width - 2; Rectangle2.Height := 50; Rectangle2.Position.X := 1; Rectangle2.Position.Y := 1; Instructionlbl.Width := Rectangle2.Width; Instructionlbl.Height := Rectangle2.Height; Instructionlbl.Position.X := 0; Instructionlbl.Position.Y := 0; MenuGroups := TMenuGroups.Create; CurrentpageCount := 1; ShowCurrentPage(CurrentPageCount); end; procedure TGroupDialog.MenuGroupBtnClick(Sender: TObject); begin ReturnString := (Sender as TButton).TagString; DialogResult := mrOK; FProcessDialogResult.ProcessDialogResult; end; procedure TGroupDialog.PageDownBtnClick(Sender: TObject); begin if CurrentpageCount < TotalPageCount then begin Inc(CurrentpageCount); ShowCurrentPage(CurrentpageCount); end; end; procedure TGroupDialog.PageupBtnClick(Sender: TObject); begin if CurrentpageCount > 1 then begin Dec(CurrentpageCount); ShowCurrentPage(CurrentpageCount); end; end; procedure TGroupDialog.ShowCurrentPage(PageNumber: Integer); var i: Integer; begin CaculateMaxPage; CaculateIdxRange; if MenuGroups.MenuGroupList.Count <> 0 then begin for i := 0 to (EndIndex - StartIndex) do begin BtnList.items[i].Text := MenuGroups.MenuGroupList.items[StartIndex + i] .GroupDescription; BtnList.items[i].TagString := MenuGroups.MenuGroupList.items [StartIndex + i].GroupCode; end; for i := (EndIndex - StartIndex) + 1 to BtnList.Count - 1 do begin BtnList.items[i].Text := ''; BtnList.items[i].TagString := ''; end; end else begin for i := 0 to BtnList.Count - 1 do begin BtnList.items[i].Text := ''; BtnList.items[i].TagString := ''; end; end; end; end.
unit MyPlayground; interface uses GraphABC, MySnake, MyApple, MyQueue; type Playground = class x1: integer; y1: integer; x2: integer; y2: integer; cellSize: integer; field: array [,] of integer; const emptyId :integer = 0; const borderId: integer = 1; const snakeId: integer = 2; const snakeHeadId :integer = 4; const appleId: integer = 3; snake: MySnake.Snake; apple: MyApple.Apple; constructor Create(iX1: integer; iY1: integer; iX2: integer; iY2: integer; iCellSize: integer); procedure Render(); procedure Update(x1:integer; y1:integer; x2:integer; y2:integer); procedure SetPlaygroundObjects(); procedure SetBorder; function GetArrayOfEmptys():MyQueue.Queue; function ItShouldBe(x:integer; y:integer):string; function ItShouldBeBorder(x:integer; y:integer):boolean; function ItShouldBeApple(x:integer; y:integer):boolean; function ItShouldBeSnake(x:integer; y:integer):boolean; function ItShouldBeSnakeHead(x:integer; y:integer):boolean; function Width(): integer; function Heigth(): integer; function Columns(): integer; function Rows(): integer; end; implementation constructor Playground.Create(iX1: integer; iY1: integer; iX2: integer; iY2: integer; iCellSize: integer); begin x1 := iX1; y1 := iY1; x2 := iX2; y2 := iY2; cellSize := iCellSize; SetLength(field, Columns(), Rows()); snake := MySnake.Snake.Create(3, 3); apple := MyApple.Apple.Create(1, 1); SetPlaygroundObjects(); end; // procedure procedure Playground.SetPlaygroundObjects(); begin for var j := 0 to rows() - 1 do for var i := 0 to columns() - 1 do begin case ItShouldBe(i ,j) of 'Border': field[i, j] := borderId; 'Apple': field[i, j] := appleId; 'Snake': field[i, j] := snakeId; 'Snake Head': field[i, j] :=snakeHeadId; 'Empty': field[i, j] := emptyId; end; end; end; procedure Playground.SetBorder(); begin for var i := 0 to rows() - 1 do for var j := 0 to columns() - 1 do begin if (i = 0) or (i = (rows() - 1)) or (j = 0) or (j = columns() - 1) then field[i, j] := borderId; end; end; procedure Playground.Render(); var currentColor:GraphABC.Color; begin GraphABC.SetPenColor(clDarkBlue); GraphABC.DrawRectangle(x1, y1, x1 + cellSize * Columns() + 1, y1 + cellSize * Rows() + 1); for var i := 1 to Columns() - 1 do begin GraphABC.SetPenColor(rgb(211, 211, 211)); GraphABC.Line(x1 + i * cellSize, y1, x1 + i * cellSize, y1 + cellSize * Rows()); end; for var i := 1 to Rows() - 1 do begin GraphABC.SetPenColor(rgb(211, 211, 211)); GraphABC.Line(x1, y1 + i * cellSize, x1 + cellSize * Columns(), y1 + i * cellSize); end; for var j := 0 to rows() - 1 do for var i := 0 to columns() - 1 do begin case field[i, j] of borderId : currentColor := rgb(32, 178, 170); snakeId : currentColor := rgb(70, 130, 180); snakeHeadId: currentColor := rgb(238, 130, 238); appleId: currentColor := rgb(144, 238, 144); emptyId: currentColor := rgb(240, 248, 255); end; GraphABC.SetBrushColor(currentColor); GraphABC.FillRect(x1 + i * cellsize + 1, y1 + j * cellsize + 1, x1 + i * cellsize + cellsize, y1 + j * cellsize + cellsize); end; end; procedure Playground.Update(x1:integer; y1:integer; x2:integer; y2:integer); begin Self.x1 := x1; Self.y1 := y1; Self.x2 := x2; Self.y2 := y2; SetLength(field, Columns(), Rows()); SetPlaygroundObjects(); end; // function function Playground.GetArrayOfEmptys():MyQueue.Queue; begin Result := MyQueue.Queue.Create(); for var j:=0 to Rows()-1 do begin for var i:=0 to Columns()-1 do begin if (field[i,j]=emptyId)then begin Result.Push(i,j); end; end; end; end; function Playground.ItShouldBeBorder(x:integer; y:integer):boolean; begin if (y = 0) or (y = (rows() - 1)) or (x = 0) or (x = columns() - 1) then begin Result := true; end; end; function Playground.ItShouldBeApple(x:integer; y:integer):boolean; begin if (apple.x = x) and (apple.y = y) then begin Result := True; end; end; function Playground.ItShouldBeSnake(x:integer; y:integer):boolean; begin for var i := 1 to snake.queue.length - 1 do begin if (snake.queue.queue[i, 0] = x) and (snake.queue.queue[i, 1] = y) then begin Result := True; exit; end; end; end; function Playground.ItShouldBeSnakeHead(x:integer; y:integer):boolean; begin if (snake.GetHead()[0] = x) and (snake.GetHead()[1] = y) then begin Result := True; end; end; function Playground.ItShouldBe(x:integer; y:integer):string; begin Result := 'Empty'; if ItShouldBeSnakeHead(x, y) then begin Result := 'Snake Head'; exit; end; if ItShouldBeSnake(x, y) then begin Result := 'Snake'; exit; end; if ItShouldBeBorder(x, y) then begin Result := 'Border'; exit; end; if ItShouldBeApple(x, y) then begin Result := 'Apple'; exit; end; end; function Playground.Width(): integer; begin Result := x2 - x1; end; function Playground.Heigth(): integer; begin Result := y2 - y1; end; function Playground.Columns(): integer; begin Result := Width() div cellSize; end; function Playground.Rows(): integer; begin Result := Heigth() div cellSize; end; initialization finalization end.
unit kwDeleteFilesByMask; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ScriptEngine" // Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwDeleteFilesByMask.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::FileProcessing::DeleteFilesByMask // // DeleteFilesByMask - очищает директорию. // *Формат:* aMask aDirName DeleteFilesByMask // * aDirName - имя директории. // * aMask - маска, по которой отбираются файлы. // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\ScriptEngine\seDefine.inc} interface {$If not defined(NoScripts)} uses tfwScriptingInterfaces ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type {$Include ..\ScriptEngine\tfwAutoregisteringWord.imp.pas} TkwDeleteFilesByMask = {final} class(_tfwAutoregisteringWord_) {* DeleteFilesByMask - очищает директорию. *Формат:* aMask aDirName DeleteFilesByMask * aDirName - имя директории. * aMask - маска, по которой отбираются файлы. } protected // realized methods procedure DoDoIt(const aCtx: TtfwContext); override; public // overridden public methods class function GetWordNameForRegister: AnsiString; override; end;//TkwDeleteFilesByMask {$IfEnd} //not NoScripts implementation {$If not defined(NoScripts)} uses l3FileUtils, tfwAutoregisteredDiction, tfwScriptEngine ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type _Instance_R_ = TkwDeleteFilesByMask; {$Include ..\ScriptEngine\tfwAutoregisteringWord.imp.pas} // start class TkwDeleteFilesByMask procedure TkwDeleteFilesByMask.DoDoIt(const aCtx: TtfwContext); //#UC START# *4DAEEDE10285_5135F182020A_var* var l_Mask : AnsiString; l_Folder : AnsiString; //#UC END# *4DAEEDE10285_5135F182020A_var* begin //#UC START# *4DAEEDE10285_5135F182020A_impl* if aCtx.rEngine.IsTopString then begin l_Folder := aCtx.rEngine.PopDelphiString; if aCtx.rEngine.IsTopString then begin l_Mask := aCtx.rEngine.PopDelphiString; DeleteFilesByMask(l_Folder, l_Mask); end // if aCtx.rEngine.IsTopString then else RunnerAssert(False, 'Не задана маска файлов для удаления!', aCtx); end else RunnerAssert(False, 'Не задана папка для удаления файлов!', aCtx); //#UC END# *4DAEEDE10285_5135F182020A_impl* end;//TkwDeleteFilesByMask.DoDoIt class function TkwDeleteFilesByMask.GetWordNameForRegister: AnsiString; {-} begin Result := 'DeleteFilesByMask'; end;//TkwDeleteFilesByMask.GetWordNameForRegister {$IfEnd} //not NoScripts initialization {$If not defined(NoScripts)} {$Include ..\ScriptEngine\tfwAutoregisteringWord.imp.pas} {$IfEnd} //not NoScripts end.
unit MFichas.View.Dialog.AberturaCaixa; 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.Objects, FMX.Edit, FMX.Controls.Presentation, FMX.Layouts; type TFrameViewAberturaCaixa = class(TFrame) LayoutPrincipal: TLayout; RectanglePrincipal: TRectangle; LayoutRectangleTop: TLayout; LabelTitulo: TLabel; LayoutRectangleClient: TLayout; LabelValor: TLabel; EditValor: TEdit; LayoutRectangleBottom: TLayout; LayoutDireita: TLayout; RoundRectBotaoConfirmar: TRoundRect; LabelBotaoConfirmar: TLabel; LayoutEsquerda: TLayout; RoundRectBotaoCancelar: TRoundRect; LabelBotaoCancelar: TLabel; RectangleSombra: TRectangle; private { Private declarations } public { Public declarations } procedure ConfigurarTamanhoDoModal(AParent: TForm); end; implementation {$R *.fmx} { TFrameViewAberturaCaixa } procedure TFrameViewAberturaCaixa.ConfigurarTamanhoDoModal(AParent: TForm); begin Self.Align := TAlignLayout.Contents; Self.Visible := False; Self.Parent := AParent; Self.RectanglePrincipal.Margins.Top := AParent.Height / 3.5; Self.RectanglePrincipal.Margins.Bottom := AParent.Height / 3.5; Self.RectanglePrincipal.Margins.Left := AParent.Width / 10; Self.RectanglePrincipal.Margins.Right := AParent.Width / 10; Self.Visible := True; end; end.
program parser_test; var i,j,num : integer; function divides(x,y : integer) : boolean; begin divides := y = x*(y div x) end; function mul(x,y : integer) : boolean; begin divides := y = x*(y div x) end; procedure DrawLine(X : integer; Y : integer); var Counter, t : integer; begin GotoXy(X,Y); {here I use the parameters} textcolor(green); for Counter := 1 to 10 do begin write(chr(196)); end; end; begin writestring("How many ?"); num := readint(); writestring("Divisor ?"); i := readint(); writeint(i); for j := 1 to num do begin writestring("###########"); writeint(j); if divides(i,j) then writestring("yes") else writestring("no"); writeint(j mod i) end end.
unit kwCase; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ScriptEngine" // Автор: Люлин А.В. // Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwCase.pas" // Начат: 29.04.2011 21:00 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi Scripting::ScriptEngine::Scripting::TkwCase // // Аналог Case из Delphi // {code} // CASE // 1 ( 1 . ) // 2 ( 2 . ) // DEFAULT ( 'else' . ) // ENDCASE // {code} // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\ScriptEngine\seDefine.inc} interface {$If not defined(NoScripts)} uses tfwScriptingInterfaces, l3Interfaces, kwCompiledWord, l3ParserInterfaces ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type {$Include ..\ScriptEngine\tfwBeginLikeWord.imp.pas} TkwCase = class(_tfwBeginLikeWord_) {* Аналог Case из Delphi [code] CASE 1 ( 1 . ) 2 ( 2 . ) DEFAULT ( 'else' . ) ENDCASE [code] } protected // realized methods function EndBracket(const aContext: TtfwContext): AnsiString; override; protected // overridden protected methods function CompiledWordClass: RkwCompiledWord; override; public // overridden public methods class function GetWordNameForRegister: AnsiString; override; end;//TkwCase {$IfEnd} //not NoScripts implementation {$If not defined(NoScripts)} uses kwCompiledCase, l3Parser, kwInteger, kwString, SysUtils, TypInfo, l3Base, kwIntegerFactory, kwStringFactory, l3String, l3Chars, tfwAutoregisteredDiction, tfwScriptEngine ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type _Instance_R_ = TkwCase; {$Include ..\ScriptEngine\tfwBeginLikeWord.imp.pas} // start class TkwCase function TkwCase.EndBracket(const aContext: TtfwContext): AnsiString; //#UC START# *4DB6C99F026E_4DBAEE8103DB_var* //#UC END# *4DB6C99F026E_4DBAEE8103DB_var* begin //#UC START# *4DB6C99F026E_4DBAEE8103DB_impl* Result := 'ENDCASE'; //#UC END# *4DB6C99F026E_4DBAEE8103DB_impl* end;//TkwCase.EndBracket class function TkwCase.GetWordNameForRegister: AnsiString; //#UC START# *4DB0614603C8_4DBAEE8103DB_var* //#UC END# *4DB0614603C8_4DBAEE8103DB_var* begin //#UC START# *4DB0614603C8_4DBAEE8103DB_impl* Result := 'CASE'; //#UC END# *4DB0614603C8_4DBAEE8103DB_impl* end;//TkwCase.GetWordNameForRegister function TkwCase.CompiledWordClass: RkwCompiledWord; //#UC START# *4DBAEE0D028D_4DBAEE8103DB_var* //#UC END# *4DBAEE0D028D_4DBAEE8103DB_var* begin //#UC START# *4DBAEE0D028D_4DBAEE8103DB_impl* Result := TkwCompiledCase; //#UC END# *4DBAEE0D028D_4DBAEE8103DB_impl* end;//TkwCase.CompiledWordClass {$IfEnd} //not NoScripts initialization {$If not defined(NoScripts)} {$Include ..\ScriptEngine\tfwBeginLikeWord.imp.pas} {$IfEnd} //not NoScripts end.
{ Original Pyhton Code From: https://github.com/patgo25/RenaultRadioCodes Delphi 7 Convertion by direstraits96 16-07-2021 } unit RenaultRadioCalculator; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, XPMan; type TForm1 = class(TForm) Edit1: TEdit; Button1: TButton; Label1: TLabel; Label2: TLabel; XPManifest1: TXPManifest; procedure Button1Click(Sender: TObject); procedure Edit1KeyPress(Sender: TObject; var Key: Char); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} Function CalculateRenaultCode(Precode:String):String; var A,B,C,D:integer; Code:Single; begin if (Length(Precode)>=4) and (Precode[1] in ['A'..'Z','a'..'z']) and (Precode[2] in ['0'..'9']) and (Precode[3] in ['0'..'9']) and (Precode[4] in ['0'..'9']) then begin Precode:=UpperCase(Precode); //UpperCase All the String A:= Ord(Precode[1])*5; B:= Ord(Precode[2]) + A*2 -698; C:= Ord(Precode[4]) + Ord(Precode[3])*5*2 +b -528; D:= ((C Shl 3)-C) Mod 100; //Shift the integer value of C to right by 3 and get the remainder from dividing by 100 Code:= Int(D/10) + (D Mod 10) *5*2+ ((259 Mod B) Mod 100)*5*5*4; //This code Adds zeros(0) before the code depending on the result size if(Length(FloatToStr(Code))=4) then Result:=FloatToStr(Code); if(Length(FloatToStr(Code))=3) then Result:='0'+FloatToStr(Code); if(Length(FloatToStr(Code))=2) then Result:='00'+FloatToStr(Code); if(Length(FloatToStr(Code))=1) then Result:='000'+FloatToStr(Code); end else Result:='Invalid Precode'; exit; end; procedure TForm1.Button1Click(Sender: TObject); begin Label1.Caption:=CalculateRenaultCode(Edit1.Text); end; procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char); begin Key := UpCase(Key); //Convert To Uppercase if Key = #13 then //If key is Enter (Return) begin Key := #0; //No Sound Button1.Click; //Emulate Click to Calculate Code end; end; end.
unit evControlsBlockHotSpotTesterPrim; // Модуль: "w:\common\components\gui\Garant\Everest\evControlsBlockHotSpotTesterPrim.pas" // Стереотип: "SimpleClass" // Элемент модели: "TevControlsBlockHotSpotTesterPrim" MUID: (4A27B51303A7) {$Include w:\common\components\gui\Garant\Everest\evDefine.inc} interface {$If Defined(evNeedHotSpot)} uses l3IntfUses , evDocumentPartHotSpotTester , nevGUIInterfaces , nevTools , evQueryCardInt , l3Units , afwInterfaces ; type TContrBlockActFlags = ( ev_cbNoAction , ev_cbMainSurface , ev_cbButton );//TContrBlockActFlags TevControlsBlockHotSpotTesterPrim = class(TevDocumentPartHotSpotTester, IevMouseMoveHandler) private f_CommonControl: IevCommonControl; protected function pm_GetCommonControl: IevCommonControl; function GetControl: IevQueryGroup; function PtToPara(const aPt: TafwPoint): Tl3Point; function MouseInBtn(const aPt: Tl3Point): Boolean; function TransMouseMove(const aView: InevControlView; const aKeys: TevMouseState; out theActiveElement: InevActiveElement): Boolean; {* Собственно реальный MouseMove, передаваемый редактору } procedure Cleanup; override; {* Функция очистки полей объекта. } procedure ClearFields; override; protected property CommonControl: IevCommonControl read pm_GetCommonControl; end;//TevControlsBlockHotSpotTesterPrim {$IfEnd} // Defined(evNeedHotSpot) implementation {$If Defined(evNeedHotSpot)} uses l3ImplUses , SysUtils , evControlsBlockConst //#UC START# *4A27B51303A7impl_uses* //#UC END# *4A27B51303A7impl_uses* ; function TevControlsBlockHotSpotTesterPrim.pm_GetCommonControl: IevCommonControl; //#UC START# *4A27B7B10328_4A27B51303A7get_var* //#UC END# *4A27B7B10328_4A27B51303A7get_var* begin //#UC START# *4A27B7B10328_4A27B51303A7get_impl* if f_CommonControl = nil then Supports(ParaX, IevCommonControl, f_CommonControl); Result := f_CommonControl; //#UC END# *4A27B7B10328_4A27B51303A7get_impl* end;//TevControlsBlockHotSpotTesterPrim.pm_GetCommonControl function TevControlsBlockHotSpotTesterPrim.GetControl: IevQueryGroup; //#UC START# *4A27B59E000D_4A27B51303A7_var* //#UC END# *4A27B59E000D_4A27B51303A7_var* begin //#UC START# *4A27B59E000D_4A27B51303A7_impl* GetRedirect.QT(IevQueryGroup, Result); //#UC END# *4A27B59E000D_4A27B51303A7_impl* end;//TevControlsBlockHotSpotTesterPrim.GetControl function TevControlsBlockHotSpotTesterPrim.PtToPara(const aPt: TafwPoint): Tl3Point; //#UC START# *4A27B66101A0_4A27B51303A7_var* //#UC END# *4A27B66101A0_4A27B51303A7_var* begin //#UC START# *4A27B66101A0_4A27B51303A7_impl* Result := Tl3Point(aPt).Sub(Tl3Rect(thisMap.Bounds).TopLeft); //#UC END# *4A27B66101A0_4A27B51303A7_impl* end;//TevControlsBlockHotSpotTesterPrim.PtToPara function TevControlsBlockHotSpotTesterPrim.MouseInBtn(const aPt: Tl3Point): Boolean; //#UC START# *4A27B6890151_4A27B51303A7_var* var l_Width : Integer; //#UC END# *4A27B6890151_4A27B51303A7_var* begin //#UC START# *4A27B6890151_4A27B51303A7_impl* l_Width := thisMap.FI.rLimitWidth; Result := (aPt.X >= (l_Width - evControlBlockBtnWidth)) and (aPt.X <= l_Width) and (aPt.Y >= evControlBlockTop) and (aPt.Y <= (evControlBlockBefore - evControlBlockTop)); //#UC END# *4A27B6890151_4A27B51303A7_impl* end;//TevControlsBlockHotSpotTesterPrim.MouseInBtn function TevControlsBlockHotSpotTesterPrim.TransMouseMove(const aView: InevControlView; const aKeys: TevMouseState; out theActiveElement: InevActiveElement): Boolean; {* Собственно реальный MouseMove, передаваемый редактору } //#UC START# *48E2638F0358_4A27B51303A7_var* var l_Control : IevQueryGroup; l_Pt : Tl3Point; l_Upper : Boolean; //#UC END# *48E2638F0358_4A27B51303A7_var* begin //#UC START# *48E2638F0358_4A27B51303A7_impl* l_Control := GetControl; if l_Control <> nil then begin l_Pt := PtToPara(aKeys.rPoint); l_Upper := MouseInBtn(l_Pt) and l_Control.CanCollapsed; if l_Upper <> CommonControl.Upper then CommonControl.Upper := l_Upper; if l_Upper then l_Control.UpperChange; end; Result := True; //#UC END# *48E2638F0358_4A27B51303A7_impl* end;//TevControlsBlockHotSpotTesterPrim.TransMouseMove procedure TevControlsBlockHotSpotTesterPrim.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_4A27B51303A7_var* //#UC END# *479731C50290_4A27B51303A7_var* begin //#UC START# *479731C50290_4A27B51303A7_impl* f_CommonControl := nil; inherited; //#UC END# *479731C50290_4A27B51303A7_impl* end;//TevControlsBlockHotSpotTesterPrim.Cleanup procedure TevControlsBlockHotSpotTesterPrim.ClearFields; begin f_CommonControl := nil; inherited; end;//TevControlsBlockHotSpotTesterPrim.ClearFields {$IfEnd} // Defined(evNeedHotSpot) end.
unit cmdlinecfg; {$mode delphi}{$H+} interface uses Classes, SysUtils, contnrs; type TCmdLineCfgValues = record CmdLineValue : String; // the actual command that goes to the cmd line DisplayName : String; // the default display name (in English) Condition : String; // condition for the value of the option end; { TCmdLineCfgOption } TCmdLineCfgOption = class(TObject) private procedure AssureSizeForIndex(AIndex: Integer); public Section : String; // the secion of the option SubSection : String; // logical sub-section of the option Name : String; // the "code" of the option, to be saved into project settings (to be backward compatible) OptType : String; // option type - free form type option options Key : String; // the key that needs to go MasterKey : String; // the key values will be combined into a single Key, prefixed with the MasterKey // example: two options -Ct -Co will be combined into -Cto, if both have -C as master key. AliasToKey : string; // the key is deprecated and it's alias to a newer and better key Display : String; // the default description of the option Condition : String; // the condition for the option (in general) Values : array of TCmdLineCfgValues; // cmd line value used with the key ValCount : Integer; // the total number of values isMultiple : Boolean; constructor Create; procedure SetValue(const AValue: string; Index: Integer = 0); procedure SetValDisplay(const DispName: string; Index: Integer = 0); procedure SetCondition(const Condition: string; Index: Integer = 0); end; { TCmdLineCfg } TCmdLineCfg = class(TObject) private fHash : TFPHashObjectList; isValid : Boolean; public Options : TList; Executable : String; // the executable code. Doesn't have to be the actual command-line executable name Version : String; // human-readable version name FromVersion : String; // the previous version of configuration TestKey : String; // the command that should return the TestValue TestValue : String; // expected test value to confirm the version. constructor Create; destructor Destroy; override; function FindOption(const name: string): TCmdLineCfgOption; end; { TCmdLineOptionValue } TCmdLineOptionValue = class(TObject) Option : TCmdLineCfgOption; Value : String; constructor Create(AOption: TCmdLineCfgOption=nil; const AValue: string = ''); end; procedure CmdLineDebug(cfg: TCmdLineCfg); procedure CmdLineDebugOption(opt: TCmdLineCfgOption); function CmdLineMakeOptions(values: TList {of TCmdLineOptionValue}): string; // returns the substring for thr command-line, by replacing %value% from the "Key" param // is ValueType is switch, simply returns the key, if Value is not an empty string // Example #1 // Key = -Ck%value% // ValueType = int // Value = 5000 // Result = -Ck5000 // Example #2 // Key = -Fu%value% // ValueType = filename // Value = /usr/bin/my files/test.pas // Result = -Fu"/usr/bin/my files/test.pas" function CmdLineCollectValue(const Key, ValueType, Value: string): string; function CmdLineGenerateName(const Key,Name: String): String; // Automatically sets the name based by CmdLineGenerateName // Empty type is not allow, so defaults to "switch" // Chagnes type from "switch" to either "string" ot "select" // if the Key has a value (string), or there's a list of options given (select) procedure CmdLineOptionNormalize(opt: TCmdLineCfgOption); implementation procedure CmdLineOptionNormalize(opt: TCmdLineCfgOption); var tp: string; begin if not Assigned(opt) then Exit; opt.Name:=CmdLineGenerateName(opt.Key, opt.Name); if opt.OptType='' then opt.OptType:='switch'; tp:=AnsiLowerCase(opt.OptType); if (pos('%value%', AnsiLowercase(opt.Key))>0) and (tp='switch')then begin if opt.ValCount>1 then opt.OptType:='select' else opt.OptType:='string'; end;; end; function CmdLineGenerateName(const Key,Name: String): String; begin Result:=Name; if Name='' then Result:=StringReplace(Key, '%value%', '', [rfIgnoreCase,rfReplaceAll]); end; { TCmdLineOptionValue } constructor TCmdLineOptionValue.Create(AOption: TCmdLineCfgOption; const AValue: string); begin inherited Create; Option:=AOption; Value:=AValue; end; { TCmdLineCfgOption } procedure TCmdLineCfgOption.AssureSizeForIndex(AIndex: Integer); begin while length(Values)<=AIndex do begin if length(Values)=0 then SetLength(Values, 4) else SetLength(Values, length(Values)*2); end; if ValCount<=AIndex then ValCount:=AIndex+1; end; constructor TCmdLineCfgOption.Create; begin inherited Create; end; procedure TCmdLineCfgOption.SetValue(const AValue: string; Index: Integer); begin AssureSizeForIndex(Index); Values[Index].CmdLineValue:=AValue; end; procedure TCmdLineCfgOption.SetValDisplay(const DispName: string; Index: Integer); begin AssureSizeForIndex(Index); Values[Index].DisplayName:=DispName; end; procedure TCmdLineCfgOption.SetCondition(const Condition: string; Index: Integer ); begin AssureSizeForIndex(Index); Values[Index].Condition:=Condition; end; { TCmdLineCfg } constructor TCmdLineCfg.Create; begin Options:=TList.Create; fHash:=TFPHashObjectList.Create(false); end; destructor TCmdLineCfg.Destroy; var i : integer; begin for i:=0 to Options.Count-1 do TCmdLineCfgOption(Options[i]).Free; Options.Free; fHash.Free; inherited Destroy; end; function TCmdLineCfg.FindOption(const name: string): TCmdLineCfgOption; var i : integer; l : string; opt : TCmdLineCfgOption; begin if not isValid then begin for i:=0 to Options.Count-1 do begin opt := TCmdLineCfgOPtion(Options[i]); fHash.Add( opt.Name, opt); end; isValid:=true; end; Result:=TCmdLineCfgOption(fHash.Find(name)); end; procedure CmdLineDebugOption(opt: TCmdLineCfgOption); var i : integer; begin if (opt.Section<>'') or (opt.SubSection<>'') then writeln(opt.Name, ' [', opt.Section,'/',opt.SubSection,']'); writeln('key: ', opt.key,' (',opt.Display,')'); writeln('type: ', opt.OptType); if opt.isMultiple then writeln('multiple values allowed'); if opt.MasterKey<>'' then writeln('masterkey: ', opt.MasterKey); for i:=0 to opt.ValCount-1 do begin writeln(' value: ', opt.Values[i].CmdLineValue,' ', opt.Values[i].DisplayName ); if opt.Values[i].Condition<>'' then writeln(' condition: ', opt.Values[i].Condition); end; end; procedure CmdLineDebug(cfg: TCmdLineCfg); var i : integer; begin writeln('executable: ', cfg.Executable); writeln('version: ', cfg.Version); writeln('test key: ', cfg.TestKey); writeln('test value: ', cfg.TestValue); writeln('total options: ', cfg.Options.Count); writeln; for i:=0 to cfg.Options.Count-1 do begin CmdLineDebugOption(TCmdLineCfgOption(cfg.Options[i])); writeln; end; end; function CheckQuotes(const v: string): string; var i : integer; begin Result:=v; for i:=1 to length(v) do if (v[i] in [' ','<','>',#39]) then begin //todo: how to handle quotes in parameter value? Result:='"'+v+'"'; Exit; end; end; function CmdLineCollectValue(const Key, ValueType, Value: string): string; var l : string; j : Integer; vl : string; const ValueParam = '%value%'; begin if Value='' then begin Result:=''; Exit; end; l:=LowerCase(ValueType); if l='switch' then begin Result:=Key // no values expected end else begin vl:=CheckQuotes(Value); Result:=Key; j:=Pos(ValueParam, LowerCase(Result)); if j>0 then begin //%value% is present in key declaration Delete(Result, j, length(ValueParam)); // replacing any %% with % Result:=StringReplace(Result, '%%', '%', [rfIgnoreCase, rfReplaceAll]); Insert(vl, Result, j); end else //%value% is not present in key declaration, so just attach it to the key Result:=Key+StringReplace(Key, '%%', '%', [rfIgnoreCase, rfReplaceAll])+vl; end; end; function CmdLineMakeOptions(values: TList {of TCmdLineOption}): string; var i : Integer; j : Integer; masters : TStringList; vl : TCmdLineOptionValue; v : string; mk : string; begin Result:=''; masters := TStringList.Create; try for i:=0 to values.Count-1 do begin vl:=TCmdLineOptionValue(values[i]); if vl.Option = nil then Continue; v:=CmdLineCollectValue(vl.Option.Key, vl.Option.OptType, vl.Value); if v='' then Continue; mk:=vl.Option.MasterKey; if mk<>'' then begin j:=masters.IndexOfName(mk); v:=Copy(v, length(mk)+1, length(v)); if j<0 then masters.Values[mk]:=v else masters.ValueFromIndex[j]:=masters.ValueFromIndex[j]+v; end else begin if Result='' then Result:=v else Result:=Result+' '+v; end; end; for i:=0 to masters.Count-1 do begin v:=masters.Names[i]+masters.ValueFromIndex[i]; if Result='' then Result:=v else Result:=Result+' '+v; end; finally masters.Free; end; end; end.
unit GlobalData; interface uses SysUtils, Classes, GsDocument, Generics.Collections, Forms, Windows, Variants, VirtualTrees, ComObj, Parsers.Excel; type TGsDocumentList = TObjectList<TGsDocument>; function Documents: TGsDocumentList; function GetStringHash(Str: string): Cardinal; function ComponentsDir: string; function PluginsDir: string; function GetComputerID: Integer; function TempDir: string; function FullRemoveDir(Dir: string; DeleteAllFilesAndFolders, StopIfNotAllDeleted, RemoveRoot: Boolean): Boolean; function FullDirectoryCopy(SourceDir, TargetDir: string; StopIfNotAllCopied, OverWriteFiles: Boolean): Boolean; function ConvertToFloat(Value: string): Real; function CheckPackageInstalled(AFileName: string): Boolean; function GetCheckSum(FileName: string): DWORD; procedure InstallPackage(AFileName: string); procedure ExportVirtualStringTreeToExcel(VirtualStringTree: TVirtualStringTree); implementation uses JclSysInfo; type TExtInfo = class public FileName: string; CRC: DWORD; end; var DL: TGsDocumentList; InstalledExt: TObjectList<TExtInfo>; function GetCheckSum(FileName: string): DWORD; var F: file of DWORD; P: Pointer; Fsize: DWORD; Buffer: array [0 .. 500] of DWORD; begin FileMode := 0; AssignFile(F, FileName); Reset(F); Seek(F, FileSize(F) div 2); Fsize := FileSize(F) - 1 - FilePos(F); if Fsize > 500 then Fsize := 500; BlockRead(F, Buffer, Fsize); Close(F); P := @Buffer; asm xor eax, eax xor ecx, ecx mov edi , p @again: add eax, [edi + 4*ecx] inc ecx cmp ecx, fsize jl @again mov @result, eax end; end; function CheckPackageInstalled(AFileName: string): Boolean; var I: Integer; begin result := False; for I := 0 to InstalledExt.Count - 1 do if AnsiSameText(InstalledExt[I].FileName, ExtractFileName(AFileName)) and (InstalledExt[I].CRC = GetCheckSum(AFileName)) then Exit(True); end; procedure ReadInstalledExtensions(); var FS: TFileStream; R: TReader; ExtFileName: string; N: Integer; I: Integer; ExtInfo: TExtInfo; begin InstalledExt.Clear; ExtFileName := ExtractFilePath(Application.ExeName) + 'ext.dat'; if not FileExists(ExtFileName) then Exit; try FS := TFileStream.Create(ExtFileName, fmOpenRead); try R := TReader.Create(FS, 2048); try R.ReadListBegin; Assert(R.ReadInteger = $FF00AA); N := R.ReadInteger; for I := 0 to N - 1 do begin ExtInfo := TExtInfo.Create; ExtInfo.FileName := R.ReadString; ExtInfo.CRC := Cardinal(R.ReadInteger); InstalledExt.add(ExtInfo); end; R.ReadListEnd; finally R.Free; end; finally FS.Free; end; except // ничего страшного, компонент переустановится end; end; procedure WriteInstalledExtensions(); var FS: TFileStream; W: TWriter; ExtFileName: string; I: Integer; begin if InstalledExt.Count > 0 then begin ExtFileName := ExtractFilePath(Application.ExeName) + 'ext.dat'; FS := TFileStream.Create(ExtFileName, fmCreate); try W := TWriter.Create(FS, 2048); try W.WriteListBegin; W.WriteInteger($FF00AA); W.WriteInteger(InstalledExt.Count); for I := 0 to InstalledExt.Count - 1 do begin W.WriteString(InstalledExt[I].FileName); W.WriteInteger(Integer(InstalledExt[I].CRC)); end; W.WriteListEnd; finally W.Free; end; finally FS.Free; end; end; end; procedure InstallPackage(AFileName: string); var Ext: TExtInfo; I: Integer; F: Boolean; begin F := False; for I := 0 to InstalledExt.Count - 1 do if AnsiSameText(InstalledExt[I].FileName, ExtractFileName(AFileName)) then begin InstalledExt[I].CRC := GetCheckSum(AFileName); F := True; Break; end; if not F then begin Ext := TExtInfo.Create; Ext.FileName := ExtractFileName(AFileName); Ext.CRC := GetCheckSum(AFileName); InstalledExt.add(Ext); end; end; function GetStringHash(Str: string): Cardinal; var I: Integer; begin result := 0; for I := 1 to Length(Str) do begin result := result + Ord(Str[I]) div 2; result := result - (result shl 13) or (result shr 19); end; result := Abs(result); end; function GetComputerID: Integer; begin result := GetStringHash(JclSysInfo.GetBIOSName + JclSysInfo.GetWindowsVersionNumber + JclSysInfo.GetLocalUserName); end; procedure ExportVirtualStringTreeToExcel(VirtualStringTree: TVirtualStringTree); var ExcelApp, Workbook, Worksheet, Range, Data: OleVariant; iCol, iRow, ColCount, RowCount: Integer; // FNodeData : PVSTDocument; FNode: PVirtualNode; begin // Verbindung zu Excel herstellen ExcelApp := CreateOleObject('Excel.Application'); if not VarIsNull(ExcelApp) then begin // Neues Workbook öffnen Workbook := ExcelApp.Workbooks.add; // Worksheet auswählen Worksheet := Workbook.ActiveSheet; if not VarIsNull(Workbook) then begin RowCount := VirtualStringTree.TotalCount; ColCount := VirtualStringTree.Header.Columns.Count; if (RowCount > 0) and (ColCount > 0) then begin // Bereich auswählen Range := Worksheet.Range[TExcelBook.R1C1ToCRAddress(1, 1), TExcelBook.R1C1ToCRAddress(RowCount, ColCount)]; if not VarIsNull(Range) then begin Data := VarArrayCreate([0, RowCount - 1, 0, ColCount - 1], varVariant); with VirtualStringTree do begin FNode := GetFirst; for iRow := 0 to RowCount - 1 do begin // FNodeData := GetNodeData(FNode); for iCol := 0 to ColCount - 1 do begin Data[iRow, iCol] := '''' + VirtualStringTree.Text[FNode, iCol]; // FNodeData^.Columns[iCol]; end; FNode := GetNext(FNode); end; end; Range.Value := Data; // Range.Columns.AutoFit; // Excel anzeigen Workbook.Activate; ExcelApp.Visible := True; end; end; end else raise Exception.Create('neues Workbook konnte nicht angelegt werden'); end else raise Exception.Create('Excel.Application konnte nicht geladen werden'); end; function ConvertToFloat(Value: string): Real; var I: Integer; begin Value := Trim(Value); if Value = '-' then Value := '0'; if Value = '' then Value := '0'; Value := StringReplace(Value, ' ', '', [rfReplaceAll]); Value := StringReplace(Value, ' ', '', [rfReplaceAll]); for I := 0 to 31 do Value := StringReplace(Value, Chr(I), '', [rfReplaceAll]); Value := StringReplace(Value, '.', ',', []); result := StrToFloatDef(Value, -666); if result = -666 then begin raise Exception.Create('Ошибка преобразования в число: ' + Value); end; end; {$WARNINGS OFF} function FullRemoveDir(Dir: string; DeleteAllFilesAndFolders, StopIfNotAllDeleted, RemoveRoot: Boolean): Boolean; var I: Integer; SRec: TSearchRec; FN: string; begin result := False; if not DirectoryExists(Dir) then Exit; result := True; // Добавляем слэш в конце и задаем маску - "все файлы и директории" Dir := IncludeTrailingBackslash(Dir); I := FindFirst(Dir + '*', faAnyFile, SRec); try while I = 0 do begin // Получаем полный путь к файлу или директорию FN := Dir + SRec.Name; // Если это директория if SRec.Attr = faDirectory then begin // Рекурсивный вызов этой же функции с ключом удаления корня if (SRec.Name <> '') and (SRec.Name <> '.') and (SRec.Name <> '..') then begin if DeleteAllFilesAndFolders then FileSetAttr(FN, faArchive); result := FullRemoveDir(FN, DeleteAllFilesAndFolders, StopIfNotAllDeleted, True); if not result and StopIfNotAllDeleted then Exit; end; end else // Иначе удаляем файл begin if DeleteAllFilesAndFolders then FileSetAttr(FN, faArchive); result := DeleteFile(PChar(FN)); if not result and StopIfNotAllDeleted then Exit; end; // Берем следующий файл или директорию I := FindNext(SRec); end; finally SysUtils.FindClose(SRec); end; if not result then Exit; if RemoveRoot then // Если необходимо удалить корень - удаляем if not RemoveDir(Dir) then result := False; end; function FullDirectoryCopy(SourceDir, TargetDir: string; StopIfNotAllCopied, OverWriteFiles: Boolean): Boolean; var SR: TSearchRec; I: Integer; begin result := False; SourceDir := IncludeTrailingBackslash(SourceDir); TargetDir := IncludeTrailingBackslash(TargetDir); if not DirectoryExists(SourceDir) then Exit; if not ForceDirectories(TargetDir) then Exit; I := FindFirst(SourceDir + '*', faAnyFile, SR); try while I = 0 do begin if (SR.Name <> '') and (SR.Name <> '.') and (SR.Name <> '..') then begin if SR.Attr = faDirectory then result := FullDirectoryCopy(SourceDir + SR.Name, TargetDir + SR.Name, StopIfNotAllCopied, OverWriteFiles) else if not(not OverWriteFiles and FileExists(TargetDir + SR.Name)) then result := CopyFile(PChar(SourceDir + SR.Name), PChar(TargetDir + SR.Name), False) else result := True; if not result and StopIfNotAllCopied then Exit; end; I := FindNext(SR); end; finally SysUtils.FindClose(SR); end; end; {$WARNINGS ON} function ComponentsDir: string; begin result := ExtractFilePath(Application.ExeName) + 'Components\'; end; function PluginsDir: string; begin result := ExtractFilePath(Application.ExeName) + 'Plugins\'; end; function TempDir: string; begin result := ExtractFilePath(Application.ExeName) + 'Temp\'; end; function Documents: TGsDocumentList; begin if DL = nil then DL := TGsDocumentList.Create; result := DL; end; initialization DL := nil; InstalledExt := TObjectList<TExtInfo>.Create; ReadInstalledExtensions; finalization FreeAndNil(DL); WriteInstalledExtensions; InstalledExt.Free; end.
unit Updater; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs; type TUpdateStartEvent = procedure (Sender : TObject; UpdateFileName:string) of object; TUpdater = class(tcomponent) private FOnUpdate: TUpdateStartEvent; FUpdatePath: String; FCopyCaption: string; FRelatedFiles: TStringList; procedure SetOnUpdate(const Value: TUpdateStartEvent); procedure SetUpdatePath(const Value: String); procedure SetCopyCaption(const Value: string); procedure SetRelatedFiles(const Value: TStringList); { Private declarations } protected { Protected declarations } public { Public declarations } constructor Create(AOwner:TComponent);override; destructor Destroy;override; procedure PerformUpdate; procedure UpdateRelatedFiles; published { Published declarations } property UpdatePath:String read FUpdatePath write SetUpdatePath; property CopyCaption:string read FCopyCaption write SetCopyCaption; property OnUpdate:TUpdateStartEvent read FOnUpdate write SetOnUpdate; property RelatedFiles:TStringList read FRelatedFiles write SetRelatedFiles; end; procedure Register; implementation procedure Register; begin RegisterComponents('FFS Common', [TUpdater]); end; { TUpdater } procedure TUpdater.PerformUpdate; var Allow : boolean; updtFile : string; Age1, Age2 : integer; begin Age1 := FileAge(application.exename); if Age1 > -1 then begin updtFile := updatePath; if updtFile > '' then begin updtfile := updtFile + extractFileName(application.ExeName); Age2 := FileAge(updtfile); if Age2 > -1 then begin if Age2 > Age1 then begin Allow := true; if assigned(OnUpdate) then OnUpdate(self, updtFile); end; end; end; end; end; procedure TUpdater.UpdateRelatedFiles; var updtFile : string; Age1, Age2 : integer; fname : string; x : integer; begin for x := 0 to RelatedFiles.Count - 1 do begin fname := RelatedFiles[x]; Age1 := FileAge(fname); updtFile := updatePath; if updtFile > '' then begin updtfile := updtFile + fname; Age2 := FileAge(updtfile); if Age2 > -1 then begin if Age2 > Age1 then begin try fname := extractfilepath(application.ExeName) + fname; copyfile(pchar(updtFile), pchar(fname), false); except end; end; end; end; end; end; procedure TUpdater.SetCopyCaption(const Value: string); begin FCopyCaption := Value; end; procedure TUpdater.SetOnUpdate(const Value: TUpdateStartEvent); begin FOnUpdate := Value; end; procedure TUpdater.SetRelatedFiles(const Value: TStringList); begin FRelatedFiles.Assign(Value); end; procedure TUpdater.SetUpdatePath(const Value: String); begin FUpdatePath := trim(Value); if FUpdatePath > '' then begin if copy(FUpdatePath, length(FUpdatePath),1) <> '\' then FUpdatePath := FUpdatePath + '\'; end; end; constructor TUpdater.Create(AOwner: TComponent); begin inherited; FRelatedFiles := TStringList.create; end; destructor TUpdater.Destroy; begin FRelatedFiles.Free; inherited; end; end.
{ Date Created: 5/22/00 11:17:32 AM } unit InfoINSCODESTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoINSCODESRecord = record PCompanyCode: String[4]; PDraftAccount: String[2]; PTrackingCode: String[2]; PName: String[60]; PAddress: String[30]; PCityState: String[25]; PZip: String[10]; End; TInfoINSCODESBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoINSCODESRecord end; TEIInfoINSCODES = (InfoINSCODESPrimaryKey); TInfoINSCODESTable = class( TDBISAMTableAU ) private FDFCompanyCode: TStringField; FDFDraftAccount: TStringField; FDFTrackingCode: TStringField; FDFName: TStringField; FDFAddress: TStringField; FDFCityState: TStringField; FDFZip: TStringField; procedure SetPCompanyCode(const Value: String); function GetPCompanyCode:String; procedure SetPDraftAccount(const Value: String); function GetPDraftAccount:String; procedure SetPTrackingCode(const Value: String); function GetPTrackingCode:String; procedure SetPName(const Value: String); function GetPName:String; procedure SetPAddress(const Value: String); function GetPAddress:String; procedure SetPCityState(const Value: String); function GetPCityState:String; procedure SetPZip(const Value: String); function GetPZip:String; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEIInfoINSCODES); function GetEnumIndex: TEIInfoINSCODES; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; virtual; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoINSCODESRecord; procedure StoreDataBuffer(ABuffer:TInfoINSCODESRecord); property DFCompanyCode: TStringField read FDFCompanyCode; property DFDraftAccount: TStringField read FDFDraftAccount; property DFTrackingCode: TStringField read FDFTrackingCode; property DFName: TStringField read FDFName; property DFAddress: TStringField read FDFAddress; property DFCityState: TStringField read FDFCityState; property DFZip: TStringField read FDFZip; property PCompanyCode: String read GetPCompanyCode write SetPCompanyCode; property PDraftAccount: String read GetPDraftAccount write SetPDraftAccount; property PTrackingCode: String read GetPTrackingCode write SetPTrackingCode; property PName: String read GetPName write SetPName; property PAddress: String read GetPAddress write SetPAddress; property PCityState: String read GetPCityState write SetPCityState; property PZip: String read GetPZip write SetPZip; procedure Validate; virtual; published property Active write SetActive; property EnumIndex: TEIInfoINSCODES read GetEnumIndex write SetEnumIndex; end; { TInfoINSCODESTable } procedure Register; implementation function TInfoINSCODESTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TInfoINSCODESTable.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TInfoINSCODESTable.GenerateNewFieldName } function TInfoINSCODESTable.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TInfoINSCODESTable.CreateField } procedure TInfoINSCODESTable.CreateFields; begin FDFCompanyCode := CreateField( 'CompanyCode' ) as TStringField; FDFDraftAccount := CreateField( 'DraftAccount' ) as TStringField; FDFTrackingCode := CreateField( 'TrackingCode' ) as TStringField; FDFName := CreateField( 'Name' ) as TStringField; FDFAddress := CreateField( 'Address' ) as TStringField; FDFCityState := CreateField( 'CityState' ) as TStringField; FDFZip := CreateField( 'Zip' ) as TStringField; end; { TInfoINSCODESTable.CreateFields } procedure TInfoINSCODESTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoINSCODESTable.SetActive } procedure TInfoINSCODESTable.Validate; begin { Enter Validation Code Here } end; { TInfoINSCODESTable.Validate } procedure TInfoINSCODESTable.SetPCompanyCode(const Value: String); begin DFCompanyCode.Value := Value; end; function TInfoINSCODESTable.GetPCompanyCode:String; begin result := DFCompanyCode.Value; end; procedure TInfoINSCODESTable.SetPDraftAccount(const Value: String); begin DFDraftAccount.Value := Value; end; function TInfoINSCODESTable.GetPDraftAccount:String; begin result := DFDraftAccount.Value; end; procedure TInfoINSCODESTable.SetPTrackingCode(const Value: String); begin DFTrackingCode.Value := Value; end; function TInfoINSCODESTable.GetPTrackingCode:String; begin result := DFTrackingCode.Value; end; procedure TInfoINSCODESTable.SetPName(const Value: String); begin DFName.Value := Value; end; function TInfoINSCODESTable.GetPName:String; begin result := DFName.Value; end; procedure TInfoINSCODESTable.SetPAddress(const Value: String); begin DFAddress.Value := Value; end; function TInfoINSCODESTable.GetPAddress:String; begin result := DFAddress.Value; end; procedure TInfoINSCODESTable.SetPCityState(const Value: String); begin DFCityState.Value := Value; end; function TInfoINSCODESTable.GetPCityState:String; begin result := DFCityState.Value; end; procedure TInfoINSCODESTable.SetPZip(const Value: String); begin DFZip.Value := Value; end; function TInfoINSCODESTable.GetPZip:String; begin result := DFZip.Value; end; procedure TInfoINSCODESTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('CompanyCode, String, 4, N'); Add('DraftAccount, String, 2, N'); Add('TrackingCode, String, 2, N'); Add('Name, String, 60, N'); Add('Address, String, 30, N'); Add('CityState, String, 25, N'); Add('Zip, String, 10, N'); end; end; procedure TInfoINSCODESTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, CompanyCode, Y, Y, N, N'); end; end; procedure TInfoINSCODESTable.SetEnumIndex(Value: TEIInfoINSCODES); begin case Value of InfoINSCODESPrimaryKey : IndexName := ''; end; end; function TInfoINSCODESTable.GetDataBuffer:TInfoINSCODESRecord; var buf: TInfoINSCODESRecord; begin fillchar(buf, sizeof(buf), 0); buf.PCompanyCode := DFCompanyCode.Value; buf.PDraftAccount := DFDraftAccount.Value; buf.PTrackingCode := DFTrackingCode.Value; buf.PName := DFName.Value; buf.PAddress := DFAddress.Value; buf.PCityState := DFCityState.Value; buf.PZip := DFZip.Value; result := buf; end; procedure TInfoINSCODESTable.StoreDataBuffer(ABuffer:TInfoINSCODESRecord); begin DFCompanyCode.Value := ABuffer.PCompanyCode; DFDraftAccount.Value := ABuffer.PDraftAccount; DFTrackingCode.Value := ABuffer.PTrackingCode; DFName.Value := ABuffer.PName; DFAddress.Value := ABuffer.PAddress; DFCityState.Value := ABuffer.PCityState; DFZip.Value := ABuffer.PZip; end; function TInfoINSCODESTable.GetEnumIndex: TEIInfoINSCODES; var iname : string; begin iname := uppercase(indexname); if iname = '' then result := InfoINSCODESPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoINSCODESTable, TInfoINSCODESBuffer ] ); end; { Register } function TInfoINSCODESBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PCompanyCode; 2 : result := @Data.PDraftAccount; 3 : result := @Data.PTrackingCode; 4 : result := @Data.PName; 5 : result := @Data.PAddress; 6 : result := @Data.PCityState; 7 : result := @Data.PZip; end; end; end. { InfoINSCODESTable }
unit abstract_command_lib; interface uses Introspected_streaming_class,classes; type TAbstractCommand=class(TIntrospectedStreamingClass) //чтобы историю изменений можно было хранить вместе со всем остальным public class function ImageIndex: Integer; virtual; constructor Create(Aowner: TComponent); override; function Execute: Boolean; virtual; abstract; function Undo: boolean; virtual; abstract; function caption: string; virtual; procedure ResolveMemory; virtual; function NameToDateTime: TDateTime; function NameToDate(aName: TComponentName): Integer; end; //самые-самые "зайчатки", заработает даже в command_list TAbstractCommandIterator = class public function GetCommand(out command: TAbstractCommand): Boolean; virtual; abstract; end; TAbstractCommandContainer=class(TIntrospectedStreamingClass) public procedure Add(command: TAbstractCommand); virtual; abstract; procedure Undo; virtual; abstract; procedure Redo; virtual; abstract; function UndoEnabled: Boolean; virtual; abstract; function RedoEnabled: Boolean; virtual; abstract; function CheckForExistingCommand(command: TAbstractCommand): boolean; virtual; abstract; procedure JumpToBranch(command: TAbstractCommand); virtual; abstract; function currentExecutedCommand: TAbstractCommand; virtual; abstract; //и просто тек. команду возвр. //и как начало итератора. Executed-чтобы помнить, мы стоим на состоянии ПОСЛЕ ее вып. function GetUndoIterator: TAbstractCommandIterator; virtual; abstract; function GetRedoIterator: TAbstractCommandIterator; virtual; abstract; //для списков undo/redo function GetAllCommandsIterator: TAbstractCommandIterator; virtual; abstract; function IsEmpty: Boolean; virtual; abstract; end; //команда, после которой не должно выполняться других команд, взамен - возврат на //предыдущий шаг и новое ветвление. Мотивация: сохранение в формат с потерями, //запрет на продолжение работы с искаженным документом, возвращение к исходному ITerminalCommand = interface ['{902F14E5-FCFB-4F72-ABCB-B71819D36D8A}'] //увы, "классовая дискриминация":функциональность закладывается в TCommandTree, //она по-разному обрабатывает команды в зависимость от их "наследственности" end; TAbstractCommandContainerClass = class of TAbstractCommandContainer; procedure RegisterCommandContainerClass(value: TAbstractCommandContainerClass); function GetCommandContainerClass: TAbstractCommandContainerClass; implementation uses sysutils,strutils; var ContainerClass: TAbstractCommandContainerClass; constructor TAbstractCommand.Create(AOwner: TComponent); var t: TTimeStamp; begin inherited Create(AOwner); //у любой уважающей себя команды должно быть имя //закодируем в него время и дату создания компоненты t:=DateTimeToTimeStamp(Now); //дата и время до мс еще не гарантируют уникальность - много команд может возн. //одновременно ensureCorrectName('c'+IntToHex(t.Date,8)+IntToHex(t.Time,8),AOwner); Clear; end; function TAbstractCommand.caption: string; begin result:=self.ClassName; end; function TAbstractCommand.NameToDateTime: TDateTime; var t: TTimeStamp; begin t.Date:=StrToInt('0x'+midstr(Name,2,8)); t.Time:=StrToInt('0x'+MidStr(Name,10,8)); Result:=TimeStampToDateTime(t); end; function TAbstractCommand.NameToDate(aname: TComponentName): Integer; begin Result:=StrToInt('0x'+midstr(aName,2,8)); end; procedure TAbstractCommand.ResolveMemory; begin //здесь можно отправиться в прошлое/альтернат. вселенную, //чтобы узнать необходимую информацию //назад в будущее можно не возвращаться, эту процедуру вызовет только CommandTree, //он сам потом возвратится в настоящее. end; class function TAbstractCommand.ImageIndex: Integer; begin Result:=-1; end; procedure RegisterCommandContainerClass(value: TAbstractCommandContainerClass); begin if Assigned(ContainerClass) then raise Exception.CreateFMT( 'Cannot register command container %s because %s already registered', [value.ClassName,ContainerClass.ClassName]); ContainerClass:=value; end; function GetCommandContainerClass: TAbstractCommandContainerClass; begin Result:=ContainerClass; end; end.
unit UProximityClient; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Math, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Layouts, FMX.Memo, System.Bluetooth, FMX.Controls.Presentation, FMX.Edit, FMX.ListBox; type TPosition = (poNear, poFar, poSoFar, poUnknown); TfrmProximityForm = class(TForm) pnlLog: TPanel; Memo1: TMemo; pnlMain: TPanel; btnScan: TButton; lblDevice: TLabel; Splitter1: TSplitter; tmrReadRSSI: TTimer; lblRSSI: TLabel; lblDistance: TLabel; lblDist2: TLabel; lblTxPower: TLabel; lblLinkLossAlert: TLabel; lblImmediateAlert: TLabel; Button1: TButton; Button2: TButton; Edit1: TEdit; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; lblPosition: TLabel; btnConnect: TButton; cbbDevice: TComboBox; ListBoxItem1: TListBoxItem; ListBoxItem2: TListBoxItem; procedure btnScanClick(Sender: TObject); procedure tmrReadRSSITimer(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnConnectClick(Sender: TObject); private { Private declarations } FBLEManager: TBluetoothLEManager; FBLEDevice: TBluetoothLEDevice; FServicesDiscovered: boolean; FTxPowerValue: Integer; FTXPowerService: TBluetoothGattService; FImmediateAlertService: TBluetoothGattService; FLinkLossService: TBluetoothGattService; FTXPowerLevelCharact: TBluetoothGattCharacteristic; FImmediateAlertLevelCharact: TBluetoothGattCharacteristic; FLinkLossAlertLevelCharact: TBluetoothGattCharacteristic; FCurrentPosition: TPosition; FNearCount: Integer; FFarCount: Integer; FSoFarCount: Integer; procedure DoDiscoveryEndEvent(const Sender: TObject; const ADeviceList: TBluetoothLEDeviceList); procedure DoServicesDiscovered(const Sender: TObject; const AServiceList: TBluetoothGattServiceList); procedure DoCharacteristicRead(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic; AGattStatus: TBluetoothGattStatus); procedure DoCharacteristicWrite(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic; AGattStatus: TBluetoothGattStatus); procedure DoReadRSSI(const Sender: TObject; ARssiValue: Integer; AGattStatus: TBluetoothGattStatus); procedure DoScan; procedure GetServiceAndCharacteristics; procedure EnableRSSIMonitorize(Enabled: boolean); procedure WriteLinkLossAlertLevel(AlertLevel: Byte); procedure WriteImmediateAlertLevel(AlertLevel: Byte); procedure CheckDistanceThreshold(PathLoss: Integer); procedure SetPosition(Position: TPosition); procedure UpdateCurrentPosition(Position: TPosition); public { Public declarations } end; const // ProximityDeviceName = 'esmacrosarioc01'; CProximityDeviceName = 'Bluetooth LE Service'; ServiceUUID = ''; CharactUUID = ''; LINK_LOSS_SERVICE: TBluetoothUUID = '{00001803-0000-1000-8000-00805F9B34FB}'; IMMEDIATE_ALERT_SERVICE: TBluetoothUUID = '{00001802-0000-1000-8000-00805F9B34FB}'; TX_POWER_SERVICE: TBluetoothUUID = '{00001804-0000-1000-8000-00805F9B34FB}'; ALERT_LEVEL_CHARACTERISTIC: TBluetoothUUID = '{00002A06-0000-1000-8000-00805F9B34FB}'; TX_POWER_LEVEL_CHARACTERISTIC: TBluetoothUUID = '{00002A07-0000-1000-8000-00805F9B34FB}'; var frmProximityForm: TfrmProximityForm; ProximityDeviceName: string; implementation {$R *.fmx} { TForm6 } procedure TfrmProximityForm.btnConnectClick(Sender: TObject); begin if FBLEDevice.Services.Count = 0 then Memo1.Lines.Add('No services found!') else GetServiceAndCharacteristics; end; procedure TfrmProximityForm.btnScanClick(Sender: TObject); begin btnConnect.Enabled := False; //if cbbDevice.Selected.Text>'' then ProximityDeviceName := cbbDevice.Selected.Text; DoScan; end; procedure TfrmProximityForm.Button1Click(Sender: TObject); begin WriteLinkLossAlertLevel(strtoint(Edit1.Text)); end; procedure TfrmProximityForm.Button2Click(Sender: TObject); begin WriteImmediateAlertLevel(strtoint(Edit1.Text)); end; procedure TfrmProximityForm.CheckDistanceThreshold(PathLoss: Integer); begin if PathLoss < 25 then //WriteImmediateAlertLevel(0) SetPosition(poNear) else if PathLoss < 45 then //WriteImmediateAlertLevel(1) SetPosition(poFar) else //WriteImmediateAlertLevel(2); SetPosition(poSoFar); end; procedure TfrmProximityForm.DoCharacteristicRead(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic; AGattStatus: TBluetoothGattStatus); var LValue: Integer; begin if ACharacteristic.UUID = TX_POWER_LEVEL_CHARACTERISTIC then begin if Length(ACharacteristic.Value)>0 then begin LValue := ACharacteristic.Value[0]; // SINT8 : Max=20 : Min -100 if LValue>20 then LValue := LValue - 255; FTxPowerValue := LValue; end; Memo1.Lines.Add('FTxPowerValue=' + FTxPowerValue.ToString ); end; if ACharacteristic.UUID = ALERT_LEVEL_CHARACTERISTIC then begin if (ACharacteristic.GetService.UUID = LINK_LOSS_SERVICE) and (Length(ACharacteristic.Value)>0) then begin LValue := ACharacteristic.Value[0]; lblLinkLossAlert.Text := LValue.ToString; Memo1.Lines.Add('Link Loss Alert=' + LValue.ToString ); end end; end; procedure TfrmProximityForm.DoCharacteristicWrite(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic; AGattStatus: TBluetoothGattStatus); begin //Memo1.Lines.Add('Charact ' + ACharacteristic.UUIDName + ' writed! Value: ' + ACharacteristic.Value[0].ToString ); end; procedure TfrmProximityForm.DoDiscoveryEndEvent(const Sender: TObject; const ADeviceList: TBluetoothLEDeviceList); var I: Integer; WaitTime: Integer; begin // log Memo1.Lines.Add(ADeviceList.Count.ToString + ' devices discovered:'); for I := 0 to ADeviceList.Count - 1 do Memo1.Lines.Add(ADeviceList[I].DeviceName); FBLEDevice := nil; for I := 0 to FBLEManager.LastDiscoveredDevices.Count - 1 do if FBLEManager.LastDiscoveredDevices[I].DeviceName = ProximityDeviceName then begin FBLEDevice := FBLEManager.LastDiscoveredDevices[I]; break; end; if FBLEDevice = nil then lblDevice.Text := 'Device not found' else begin lblDevice.Text := ProximityDeviceName; FBLEDevice.OnServicesDiscovered := DoServicesDiscovered; FBLEDevice.OnCharacteristicRead := DoCharacteristicRead; FBLEDevice.OnReadRSSI := DoReadRSSI; FBLEDevice.OnCharacteristicWrite := DoCharacteristicWrite; FServicesDiscovered := False; FBLEDevice.DiscoverServices; //{$IFDEF MACOS} // //Wait for OnServicesDiscovered event // WaitTime := 8; // repeat // Application.ProcessMessages; // Sleep(500); // Dec(WaitTime) // until (FServicesDiscovered) or (WaitTime=0); //{$ENDIF} // // if FBLEDevice.Services.Count = 0 then begin // Memo1.Lines.Add('No services found!'); // end // else // GetServiceAndCharacteristics; end; end; procedure TfrmProximityForm.DoReadRSSI(const Sender: TObject; ARssiValue: Integer; AGattStatus: TBluetoothGattStatus); var LRatioDB: Integer; LRatioLinear, LDistance: Double; begin //Discard wrong values if ARssiValue>0 then Exit; lblTxPower.Text := FTxPowerValue.ToString; lblRSSI.Text := ARssiValue.ToString + ' dBm'; LRatioDB := FTxPowerValue - ARssiValue; LRatioLinear := Power(10, LRatioDB / 10); LDistance := Sqrt(LRatioLinear); lblDistance.Text := LDistance.ToString; lblDist2.Text := IntToStr(FTxPowerValue - ARssiValue); CheckDistanceThreshold(FTxPowerValue - ARssiValue); end; procedure TfrmProximityForm.DoScan; begin lblDevice.Text := ''; FBLEManager.StartDiscovery(1500); end; procedure TfrmProximityForm.DoServicesDiscovered(const Sender: TObject; const AServiceList: TBluetoothGattServiceList); begin FServicesDiscovered := True; btnConnect.Enabled := True; end; procedure TfrmProximityForm.EnableRSSIMonitorize(Enabled: boolean); begin // enable timer tmrReadRSSI.Enabled := True; end; procedure TfrmProximityForm.FormShow(Sender: TObject); begin FBLEManager := TBluetoothLEManager.Current; FBLEManager.OnDiscoveryEnd := DoDiscoveryEndEvent; FCurrentPosition := poUnknown; ProximityDeviceName := CProximityDeviceName; DoScan; end; procedure TfrmProximityForm.GetServiceAndCharacteristics; var I, J, K: Integer; begin for I := 0 to FBLEDevice.Services.Count - 1 do begin memo1.Lines.Add(FBLEDevice.Services[I].UUIDName + ' : ' + FBLEDevice.Services[I].UUID.ToString); for J := 0 to FBLEDevice.Services[I].Characteristics.Count - 1 do begin memo1.Lines.Add('--> ' + FBLEDevice.Services[I].Characteristics[J].UUIDName + ' : ' + FBLEDevice.Services[I].Characteristics[J].UUID.ToString); for K := 0 to FBLEDevice.Services[I].Characteristics[J].Descriptors.Count - 1 do begin memo1.Lines.Add('----> ' + FBLEDevice.Services[I].Characteristics[J].Descriptors[K].UUIDName + ' : ' + FBLEDevice.Services[I].Characteristics[J].Descriptors[K].UUID.ToString); end; end; end; FLinkLossService := nil; FTXPowerService := nil; FImmediateAlertService := nil; FTXPowerLevelCharact := nil; FImmediateAlertLevelCharact := nil; FLinkLossAlertLevelCharact := nil; FLinkLossService := FBLEDevice.GetService(LINK_LOSS_SERVICE); if FLinkLossService<>nil then begin Memo1.Lines.Add('Service found'); FLinkLossAlertLevelCharact := FLinkLossService.GetCharacteristic(ALERT_LEVEL_CHARACTERISTIC); FBLEDevice.ReadCharacteristic(FLinkLossAlertLevelCharact); end; FImmediateAlertService := FBLEDevice.GetService(IMMEDIATE_ALERT_SERVICE); if FImmediateAlertService<>nil then begin Memo1.Lines.Add('Service found'); FImmediateAlertLevelCharact := FImmediateAlertService.GetCharacteristic(ALERT_LEVEL_CHARACTERISTIC); FBLEDevice.ReadCharacteristic(FImmediateAlertLevelCharact); end; FTXPowerService := FBLEDevice.GetService(TX_POWER_SERVICE); if FTXPowerService<>nil then begin Memo1.Lines.Add('Service found'); FTXPowerLevelCharact := FTXPowerService.GetCharacteristic(TX_POWER_LEVEL_CHARACTERISTIC); FTxPowerValue := 99; // Invalid value if FTXPowerLevelCharact<>nil then FBLEDevice.ReadCharacteristic(FTXPowerLevelCharact); end; WriteLinkLossAlertLevel(0); EnableRSSIMonitorize(True); end; procedure TfrmProximityForm.SetPosition(Position: TPosition); begin case Position of poUnknown: ; poNear: begin FNearCount := Min(FNearCount + 1, 2); FFarCount := 0; FSoFarCount := 0; if (FNearCount >= 2) and (FCurrentPosition <> poNear) then UpdateCurrentPosition(poNear); end; poFar: begin FNearCount := 0; FFarCount := Min(FFarCount + 1, 2); FSoFarCount := 0; if (FFarCount >= 2) and (FCurrentPosition <> poFar) then UpdateCurrentPosition(poFar); end; poSoFar: begin FNearCount := 0; FFarCount := 0; FSoFarCount := Min(FSoFarCount + 1, 2); if (FSoFarCount >= 2) and (FCurrentPosition <> poSoFar) then UpdateCurrentPosition(poSoFar); end; end; end; procedure TfrmProximityForm.tmrReadRSSITimer(Sender: TObject); begin FBLEDevice.ReadRemoteRSSI; end; procedure TfrmProximityForm.UpdateCurrentPosition(Position: TPosition); var LPosition: string; begin FCurrentPosition := Position; case Position of poUnknown: Exit; poNear: begin lblPosition.Text := 'Near'; end; poFar: begin lblPosition.Text := 'Far'; end; poSoFar: begin lblPosition.Text := 'So Far'; end; end; WriteImmediateAlertLevel(Ord(Position)); end; procedure TfrmProximityForm.WriteImmediateAlertLevel(AlertLevel: Byte); var LData: TBytes; begin SetLength(LData, 1); LData[0] := AlertLevel; if FImmediateAlertLevelCharact<>nil then begin FImmediateAlertLevelCharact.Value := LData; FBLEDevice.WriteCharacteristic(FImmediateAlertLevelCharact); Memo1.Lines.Add('FImmediateAlertLevelCharact service : ' + FImmediateAlertLevelCharact.GetService.UUIDName); Memo1.Lines.Add('Immediate Alert_Level Charact set to ' + AlertLevel.ToString ) end; end; procedure TfrmProximityForm.WriteLinkLossAlertLevel(AlertLevel: Byte); var LData: TBytes; begin SetLength(LData, 1); LData[0] := AlertLevel; if FLinkLossAlertLevelCharact<>nil then begin FLinkLossAlertLevelCharact.Value := LData; FBLEDevice.WriteCharacteristic(FLinkLossAlertLevelCharact); Memo1.Lines.Add('LinkLoss Alert_Level Charact set to ' + AlertLevel.ToString ) end; end; end.
unit f2DecorScript; interface uses Classes, d2dUtils; type Tf2DSOperatorType = (otMove, otColor, otRotate, otRotateSpeed, otScale, otPause, otRestart, otDelete); If2DSParameter = interface ['{2C80B9E2-0C5B-445C-AD71-B05264EFEF88}'] function GetValue: Double; procedure Save(const aFiler: Td2dFiler); end; If2DSOperator = interface ['{EFD68E7C-BBAB-461F-AE13-78C74BBC742A}'] function pm_GetIsAsync: Boolean; function pm_GetIsRelative: Boolean; function pm_GetOpType: Tf2DSOperatorType; function pm_GetParamCount: Integer; function pm_GetParams(Index: Integer): If2DSParameter; procedure Save(const aFiler: Td2dFiler); property IsAsync: Boolean read pm_GetIsAsync; property IsRelative: Boolean read pm_GetIsRelative; property OpType: Tf2DSOperatorType read pm_GetOpType; property ParamCount: Integer read pm_GetParamCount; property Params[Index: Integer]: If2DSParameter read pm_GetParams; end; Tf2DSParamPrim = class(TInterfacedObject, If2DSParameter) protected function GetValue: Double; virtual; abstract; procedure Save(const aFiler: Td2dFiler); virtual; abstract; end; Tf2SimpleParam = class(Tf2DSParamPrim) private f_Value: Double; protected function GetValue: Double; override; procedure Save(const aFiler: Td2dFiler); override; public constructor Create(const aValue: Double); constructor Load(const aFiler: Td2dFiler); end; Tf2RandomParam = class(Tf2DSParamPrim) private f_Min: Double; f_Max: Double; protected function GetValue: Double; override; procedure Save(const aFiler: Td2dFiler); override; public constructor Create(const aMin, aMax: Double); constructor Load(const aFiler: Td2dFiler); end; Tf2DSOperator = class(TInterfacedObject, If2DSOperator) private f_IsAsync: Boolean; f_IsRelative: Boolean; f_OpType: Tf2DSOperatorType; f_ParamList: IInterfaceList; private function pm_GetIsAsync: Boolean; function pm_GetIsRelative: Boolean; function pm_GetOpType: Tf2DSOperatorType; function pm_GetParamCount: Integer; function pm_GetParams(Index: Integer): If2DSParameter; public constructor Create(const aOpType: Tf2DSOperatorType; const aIsRelative: Boolean = False; const aIsAsync: Boolean = False); constructor Load(const aFiler: Td2dFiler); procedure AddParam(const aParam: If2DSParameter); procedure Save(const aFiler: Td2dFiler); property IsAsync: Boolean read pm_GetIsAsync write f_IsAsync; property IsRelative: Boolean read pm_GetIsRelative; property OpType: Tf2DSOperatorType read pm_GetOpType; property ParamCount: Integer read pm_GetParamCount; property Params[Index: Integer]: If2DSParameter read pm_GetParams; end; function CompileDSOperators(const aSource: string): IInterfaceList; procedure SaveDSOperators(const aList: IInterfaceList; const aFiler: Td2dFiler); function LoadDSOperators(const aFiler: Td2dFiler): IInterfaceList; implementation uses SysUtils, furqTypes, furqExprEval; const sDSCommandExpectedError = '[DS] Ожидалась команда (позиция %d)'; sDSUnknownCommandError = '[DS] Неизвестная команда, "%s"'; sDSParameterError = '[DS] Ошибка в параметре (позиция %d)'; sDSParametersNumberError = '[DS] Неверное число параметров (позиция %d)'; sDSMinMaxError = '[DS] Минимальное значение должно быть меньше максимального (позиция %d)'; ptSimple = 1; ptRandom = 2; procedure SaveDSParameters(const aParams: IInterfaceList; const aFiler: Td2dFiler); var I: Integer; begin aFiler.WriteInteger(aParams.Count); for I := 0 to aParams.Count - 1 do (aParams.Items[I] as If2DSParameter).Save(aFiler); end; function LoadDSParameters(const aFiler: Td2dFiler): IInterfaceList; var I, l_Count: Integer; l_Param: If2DSParameter; l_Type : Byte; begin Result := TInterfaceList.Create; l_Count := aFiler.ReadInteger; for I := 1 to l_Count do begin l_Type := aFiler.ReadByte; case l_Type of ptSimple: l_Param := Tf2SimpleParam.Load(aFiler); ptRandom: l_Param := Tf2RandomParam.Load(aFiler); end; Result.Add(l_Param); end; end; procedure SaveDSOperators(const aList: IInterfaceList; const aFiler: Td2dFiler); var I: Integer; begin aFiler.WriteInteger(aList.Count); for I := 0 to aList.Count - 1 do (aList.Items[I] as If2DSOperator).Save(aFiler); end; function LoadDSOperators(const aFiler: Td2dFiler): IInterfaceList; var I, l_Count: Integer; l_Op: If2DSOperator; begin Result := TInterfaceList.Create; l_Count := aFiler.ReadInteger; for I := 1 to l_Count do begin l_Op := Tf2DSOperator.Load(aFiler); Result.Add(l_Op); end; end; function CompileDSOperators(const aSource: string): IInterfaceList; var l_Lexer: TfurqLexer; l_IsRelative: Boolean; l_IsAsync : Boolean; l_OpType: Tf2DSOperatorType; l_Cmd : string; l_OpObj: Tf2DSOperator; l_OpI : If2DSOperator; l_Param : If2DSParameter; l_Min, l_Max: Double; procedure AssertToken(aToken: TfurqToken); begin if l_Lexer.Token <> aToken then raise EFURQRunTimeError.CreateFmt(sDSParameterError, [l_Lexer.TokenStart]); end; procedure AssertParamNumber(const aNumbers: array of integer); var I: Integer; begin for I := Low(aNumbers) to High(aNumbers) do if l_OpObj.ParamCount = aNumbers[I] then Exit; raise EFURQRunTimeError.CreateFmt(sDSParametersNumberError, [l_Lexer.TokenStart]); end; function LexNumber: Double; begin if l_Lexer.Token = etMinus then begin l_Lexer.NextToken; AssertToken(etNumber); Result := -l_Lexer.TokenValue; end else begin AssertToken(etNumber); Result := l_Lexer.TokenValue; end; end; begin Result := nil; l_Lexer := TfurqLexer.Create; try l_Lexer.AllowSpacesInIdent := False; l_Lexer.Source := aSource; while l_Lexer.Token <> etEOF do begin l_IsRelative := False; l_IsAsync := False; if l_Lexer.Token <> etIdentifier then raise EFURQRunTimeError.CreateFmt(sDSCommandExpectedError, [l_Lexer.TokenStart]); // пытаемся понять, что за команда l_Cmd := AnsiLowerCase(l_Lexer.TokenValue); if (Length(l_Cmd) > 4) or (Length(l_Cmd) < 2) then raise EFURQRunTimeError.CreateFmt(sDSUnknownCommandError, [l_Cmd]); // не бывает таких команд if (Length(l_Cmd) = 4) then begin if l_Cmd[4] = 'x' then begin l_IsAsync := True; SetLength(l_Cmd, 3); end else raise EFURQRunTimeError.CreateFmt(sDSUnknownCommandError, [l_Cmd]); // последней буквой может быть только "x" end; // начинаем опознание if l_Cmd = 'mov' then l_OpType := otMove else if l_Cmd = 'mvr' then begin l_OpType := otMove; l_IsRelative := True; end else if l_Cmd = 'rot' then begin l_OpType := otRotate; l_IsRelative := True; end else if l_Cmd = 'ang' then begin l_OpType := otRotate; end else if l_Cmd = 'col' then l_OpType := otColor else if l_Cmd = 'pau' then l_OpType := otPause else if l_Cmd = 'rsp' then begin l_OpType := otRotateSpeed; l_IsAsync := True; end else if l_Cmd = 'scl' then begin l_OpType := otScale; //l_IsAsync := True; end else if l_Cmd = 'rst' then begin l_OpType := otRestart; l_IsAsync := True; end else if l_Cmd = 'del' then begin l_OpType := otDelete; l_IsAsync := True; end else raise EFURQRunTimeError.CreateFmt(sDSUnknownCommandError, [l_Cmd]); // не бывает таких команд l_OpObj := Tf2DSOperator.Create(l_OpType, l_IsRelative, l_IsAsync); l_OpI := l_OpObj; // чтоб грохнулось в случае чего // начинаем парсить параметры while True do begin l_Lexer.NextToken; if l_Lexer.Token in [etDivide, etEOF] then Break; if (l_OpObj.ParamCount > 0) then begin AssertToken(etComma); l_Lexer.NextToken; // если это не первый параметр, то должна быть запятая end; if (l_Lexer.Token = etNumber) or (l_Lexer.Token = etMinus) then begin // это обычный параметр l_Param := Tf2SimpleParam.Create(LexNumber); end else if (l_Lexer.Token = etIdentifier) and (AnsiLowerCase(l_Lexer.TokenValue) = 'r') then begin // парсим случайный параметр l_Lexer.NextToken; AssertToken(etLBrasket); l_Lexer.NextToken; l_Min := LexNumber; l_Lexer.NextToken; AssertToken(etComma); l_Lexer.NextToken; l_Max := LexNumber; l_Lexer.NextToken; AssertToken(etRBrasket); if l_Min >= l_Max then raise EFURQRunTimeError.CreateFmt(sDSMinMaxError, [l_Lexer.TokenStart]); l_Param := Tf2RandomParam.Create(l_Min, l_Max); end else raise EFURQRunTimeError.CreateFmt(sDSParameterError, [l_Lexer.TokenStart]); l_OpObj.AddParam(l_Param); end; // контролируем число параметров case l_OpType of otMove : begin AssertParamNumber([2,3]); if l_OpObj.ParamCount = 2 then // если просто присваивается положение, то команда асинхронна (ждать её выполнения не надо) l_OpObj.IsAsync := True; // иначе - надо (если не было "х" на конце команды) end; otColor : begin AssertParamNumber([1, 2, 4, 5]); if (l_OpObj.ParamCount = 1) or (l_OpObj.ParamCount = 4) then l_OpObj.IsAsync := True; end; otRotate : begin if not l_IsRelative then AssertParamNumber([1]) else AssertParamNumber([1,2]); if l_OpObj.ParamCount = 1 then l_OpObj.IsAsync := True; end; otRotateSpeed : AssertParamNumber([1]); otScale : begin AssertParamNumber([1,2]); if l_OpObj.ParamCount = 1 then l_OpObj.IsAsync := True; end; otPause : AssertParamNumber([1]); otRestart, otDelete : AssertParamNumber([0]); end; // добавляем в список if Result = nil then Result := TInterfaceList.Create; Result.Add(l_OpI); l_OpI := nil; l_Lexer.NextToken; end; finally FreeAndNil(l_Lexer); end; end; constructor Tf2SimpleParam.Create(const aValue: Double); begin inherited Create; f_Value := aValue; end; constructor Tf2SimpleParam.Load(const aFiler: Td2dFiler); begin inherited Create; f_Value := aFiler.ReadDouble; end; function Tf2SimpleParam.GetValue: Double; begin result := f_Value; end; procedure Tf2SimpleParam.Save(const aFiler: Td2dFiler); begin aFiler.WriteByte(ptSimple); aFiler.WriteDouble(f_Value); end; constructor Tf2RandomParam.Create(const aMin, aMax: Double); begin inherited Create; f_Min := aMin; f_Max := aMax; end; constructor Tf2RandomParam.Load(const aFiler: Td2dFiler); begin inherited Create; f_Min := aFiler.ReadDouble; f_Max := aFiler.ReadDouble; end; function Tf2RandomParam.GetValue: Double; begin Result := Random * (f_Max - f_Min) + f_Min; end; procedure Tf2RandomParam.Save(const aFiler: Td2dFiler); begin aFiler.WriteByte(ptRandom); aFiler.WriteDouble(f_Min); aFiler.WriteDouble(f_Max); end; constructor Tf2DSOperator.Create(const aOpType : Tf2DSOperatorType; const aIsRelative: Boolean = False; const aIsAsync : Boolean = False); begin inherited Create; f_OpType := aOpType; f_IsAsync := aIsAsync; f_IsRelative := aIsRelative; f_ParamList := TInterfaceList.Create; end; constructor Tf2DSOperator.Load(const aFiler: Td2dFiler); begin inherited Create; with aFiler do begin f_OpType := Tf2DSOperatorType(ReadByte); f_IsAsync := ReadBoolean; f_IsRelative := ReadBoolean; f_ParamList := LoadDSParameters(aFiler); end; end; procedure Tf2DSOperator.AddParam(const aParam: If2DSParameter); begin f_ParamList.Add(aParam) end; function Tf2DSOperator.pm_GetIsAsync: Boolean; begin Result := f_IsAsync; end; function Tf2DSOperator.pm_GetIsRelative: Boolean; begin Result := f_IsRelative; end; function Tf2DSOperator.pm_GetOpType: Tf2DSOperatorType; begin Result := f_OpType; end; function Tf2DSOperator.pm_GetParamCount: Integer; begin Result := f_ParamList.Count; end; function Tf2DSOperator.pm_GetParams(Index: Integer): If2DSParameter; begin Result := f_ParamList[Index] as If2DSParameter; end; procedure Tf2DSOperator.Save(const aFiler: Td2dFiler); begin with aFiler do begin WriteByte(Byte(f_OpType)); WriteBoolean(IsAsync); WriteBoolean(IsRelative); SaveDSParameters(f_ParamList, aFiler); end; end; end.
{$I ACBr.inc} unit pciotOperacaoTransporteR; interface uses SysUtils, Classes, {$IFNDEF VER130} Variants, {$ENDIF} pcnAuxiliar, pcnConversao, pciotCIOT, Dialogs, SOAPHTTPTrans, WinInet, SOAPConst, Soap.InvokeRegistry, ASCIOTUtil, ACBRUtil, IdCoderMIME; type TOperacaoTransporteR = class(TPersistent) private FLeitor: TLeitor; FOperacaoTransporte: TOperacaoTransporte; FSucesso: Boolean; FMensagem: String; FOperacao: TpciotOperacao; public constructor Create(AOwner: TOperacaoTransporte; AOperacao: TpciotOperacao = opObter); destructor Destroy; override; function LerXml: boolean; property Sucesso: Boolean read FSucesso write FSucesso; property Mensagem: String read FMensagem write FMensagem; published property Leitor: TLeitor read FLeitor write FLeitor; property OperacaoTransporte: TOperacaoTransporte read FOperacaoTransporte write FOperacaoTransporte; end; implementation { TOperacaoTransporteR } uses ASCIOT; constructor TOperacaoTransporteR.Create(AOwner: TOperacaoTransporte; AOperacao: TpciotOperacao = opObter); begin FLeitor := TLeitor.Create; FOperacaoTransporte := AOwner; FOperacao := AOperacao; end; destructor TOperacaoTransporteR.Destroy; begin FLeitor.Free; inherited Destroy; end; function TOperacaoTransporteR.LerXml: boolean; var ok: boolean; utf8: UTF8String; sPDF: WideString; stream: TMemoryStream; decoder: TIdDecoderMIME; sNomeArquivo: string; sArquivo: string; begin case FOperacao of opObter: begin if Leitor.rExtrai(1, 'ObterOperacaoTransportePdfResult') <> '' then begin FSucesso := Leitor.rCampo(tcStr, 'Sucesso ' + NAME_SPACE_EFRETE_OBJECTS, '/Sucesso') = 'true'; FMensagem := Leitor.rCampo(tcStr, 'Mensagem'); sPDF := Leitor.rCampo(tcEsp, 'Pdf'); try decoder := TIdDecoderMIME.Create(nil); stream := TMemoryStream.Create; decoder.DecodeStream(sPDF, stream); setString(utf8, PChar(stream.Memory), stream.Size); sArquivo := StringReplace(StringReplace(FOperacaoTransporte.NumeroCIOT, '\', '_', []), '/', '_', []) + '.pdf'; sNomeArquivo := PathWithDelim(TAmSCIOT( FOperacaoTransporte.Owner ).Configuracoes.Arquivos.PathPDF); if not DirectoryExists(sNomeArquivo) then ForceDirectories(sNomeArquivo); sNomeArquivo := sNomeArquivo + sArquivo; stream.SaveToFile(sNomeArquivo); finally decoder.Free; stream.Free; end; end; end; opAdicionar: begin if Leitor.rExtrai(1, 'AdicionarOperacaoTransporteResult') <> '' then begin FSucesso := Leitor.rCampo(tcStr, 'Sucesso ' + NAME_SPACE_EFRETE_OBJECTS, '/Sucesso') = 'true'; FMensagem := Leitor.rCampo(tcStr, 'Mensagem'); FOperacaoTransporte.NumeroCIOT := Leitor.rCampo(tcStr, 'CodigoIdentificacaoOperacao'); end; end; opRetificar: begin if Leitor.rExtrai(1, 'RetificarOperacaoTransporteResult') <> '' then begin FSucesso := Leitor.rCampo(tcStr, 'Sucesso ' + NAME_SPACE_EFRETE_OBJECTS, '/Sucesso') = 'true'; FMensagem := Leitor.rCampo(tcStr, 'Mensagem'); FOperacaoTransporte.DataRetificacao := Leitor.rCampo(tcDat, 'DataRetificacao'); end; end; opCancelar: begin if Leitor.rExtrai(1, 'CancelarOperacaoTransporteResult') <> '' then begin FSucesso := Leitor.rCampo(tcStr, 'Sucesso ' + NAME_SPACE_EFRETE_OBJECTS, '/Sucesso') = 'true'; FMensagem := Leitor.rCampo(tcStr, 'Mensagem'); FOperacaoTransporte.Cancelamento.Data := Leitor.rCampo(tcDat, 'Data'); FOperacaoTransporte.Cancelamento.Protocolo := Leitor.rCampo(tcStr, 'Protocolo'); end; end; opAdicionarViagem: begin if Leitor.rExtrai(1, 'AdicionarViagemResult') <> '' then begin FSucesso := Leitor.rCampo(tcStr, 'Sucesso ' + NAME_SPACE_EFRETE_OBJECTS, '/Sucesso') = 'true'; FMensagem := Leitor.rCampo(tcStr, 'Mensagem'); if FSucesso then begin FMensagem := Leitor.rExtrai(1, 'AdicionarViagemResult'); // 'QT VIAGEM: ' + Leitor.rCampo(tcInt, 'QuantidadeViagens') + #13 + // 'DC VIAGEM: ' + Leitor.rCampo(tcStr, 'DocumentoViagem') + #13 + // 'QT PAG: ' + Leitor.rCampo(tcInt, 'QuantidadePagamentos') + #13 + // 'DC PAG: ' + Leitor.rCampo(tcStr, 'DocumentoPagamento') + #13 + // 'MSG: ' + Leitor.rCampo(tcStr, 'Mensagem'); end; end; end; opAdicionarPagamento: begin if Leitor.rExtrai(1, 'AdicionarPagamentoResult') <> '' then begin FSucesso := Leitor.rCampo(tcStr, 'Sucesso ' + NAME_SPACE_EFRETE_OBJECTS, '/Sucesso') = 'true'; FMensagem := Leitor.rCampo(tcStr, 'Mensagem'); if FSucesso then begin FMensagem := Leitor.rExtrai(1, 'AdicionarPagamentoResult'); // 'QT : ' + Leitor.rCampo(tcInt, 'QuantidadePagamentos'); end; end; end; opCancelarPagamento: begin if Leitor.rExtrai(1, 'CancelarPagamentoResult') <> '' then begin FSucesso := Leitor.rCampo(tcStr, 'Sucesso ' + NAME_SPACE_EFRETE_OBJECTS, '/Sucesso') = 'true'; FMensagem := Leitor.rCampo(tcStr, 'Mensagem'); // FOperacaoTransporte.Cancelamento.Data := Leitor.rCampo(tcDat, 'Data'); // FOperacaoTransporte.Cancelamento.Protocolo := Leitor.rCampo(tcStr, 'Protocolo'); end; end; opEncerrar: begin if Leitor.rExtrai(1, 'EncerrarOperacaoTransporteResult') <> '' then begin FSucesso := Leitor.rCampo(tcStr, 'Sucesso ' + NAME_SPACE_EFRETE_OBJECTS, '/Sucesso') = 'true'; FMensagem := Leitor.rCampo(tcStr, 'Mensagem'); FOperacaoTransporte.ProtocoloEncerramento := Leitor.rCampo(tcStr, 'Protocolo'); end; end; end; Result := true; end; end.
unit UFormMain; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ATFileNotification, ExtCtrls, XPMan, Filectrl; type TFormMain = class(TForm) Label1: TLabel; EditDir: TEdit; btnBrowseDir: TButton; EditFile: TEdit; btnBrowseFile: TButton; Label2: TLabel; OpenDialog1: TOpenDialog; Bevel1: TBevel; btnWatchDir: TButton; btnWatchFile: TButton; Bevel2: TBevel; btnClose: TButton; Notif: TATFileNotification; GroupBox1: TGroupBox; chkSubtree: TCheckBox; chkFilenames: TCheckBox; chkDirnames: TCheckBox; chkAttr: TCheckBox; chkSize: TCheckBox; chkModif: TCheckBox; XPManifest1: TXPManifest; procedure btnBrowseDirClick(Sender: TObject); procedure btnBrowseFileClick(Sender: TObject); procedure btnWatchDirClick(Sender: TObject); procedure btnWatchFileClick(Sender: TObject); procedure btnCloseClick(Sender: TObject); procedure DirChanged(Sender: TObject); private { Private declarations } procedure NotifyDir; procedure NotifyFile; public { Public declarations } end; var FormMain: TFormMain; implementation {$R *.DFM} procedure TFormMain.NotifyDir; begin with Notif do begin Stop; Directory:= EditDir.Text; Subtree:= chkSubtree.Checked; Options:= []; if chkFilenames.Checked then Options:= Options+[foNotifyFilename]; if chkDirnames.Checked then Options:= Options+[foNotifyDirname]; if chkAttr.Checked then Options:= Options+[foNotifyAttributes]; if chkSize.Checked then Options:= Options+[foNotifySize]; if chkModif.Checked then Options:= Options+[foNotifyLastWrite]; Start; end; end; procedure TFormMain.NotifyFile; begin with Notif do begin Stop; FileName:= EditFile.Text; Options:= []; if chkFilenames.Checked then Options:= Options+[foNotifyFilename]; if chkDirnames.Checked then Options:= Options+[foNotifyDirname]; if chkAttr.Checked then Options:= Options+[foNotifyAttributes]; if chkSize.Checked then Options:= Options+[foNotifySize]; if chkModif.Checked then Options:= Options+[foNotifyLastWrite]; Start; end; end; procedure TFormMain.DirChanged(Sender: TObject); begin Application.MessageBox('Dir/file has been changed', 'Notification', MB_ICONWARNING or MB_TOPMOST); end; procedure TFormMain.btnBrowseDirClick(Sender: TObject); var Dir: string; begin if SelectDirectory('Directory to watch:', '', Dir) then EditDir.Text:= Dir; end; procedure TFormMain.btnBrowseFileClick(Sender: TObject); begin with OpenDialog1 do if Execute then begin EditFile.Text:= FileName; end; end; procedure TFormMain.btnWatchDirClick(Sender: TObject); begin if EditDir.Text<>'' then NotifyDir; end; procedure TFormMain.btnWatchFileClick(Sender: TObject); begin if EditFile.Text<>'' then NotifyFile; end; procedure TFormMain.btnCloseClick(Sender: TObject); begin Close; end; end.
{$include lem_directives.inc} unit GameWindow; interface uses Windows, Classes, Controls, Graphics, MMSystem, Forms, SysUtils, Dialogs, Math, ExtCtrls, GR32, GR32_Image, GR32_Layers, UMisc, UTools, LemCore, LemLevel, LemDosStyle, LemGraphicSet, LemDosGraphicSet, LemRendering, LemGame, GameControl, GameSkillPanel, GameBaseScreen; type TGameScroll = ( gsNone, gsRight, gsLeft ); TGameWindow = class(TGameBaseScreen) private fNeedReset: Boolean; { game eventhandler} procedure Game_Finished(Sender: TObject); { self eventhandlers } procedure Form_Activate(Sender: TObject); procedure Form_KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure Form_KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure Form_KeyPress(Sender: TObject; var Key: Char); procedure Form_MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure Form_MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); { app eventhandlers } procedure Application_Idle(Sender: TObject; var Done: Boolean); { gameimage eventhandlers } procedure Img_MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); procedure Img_MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); procedure Img_MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); { skillpanel eventhandlers } procedure SkillPanel_MinimapClick(Sender: TObject; const P: TPoint); { internal } procedure CheckResetCursor; procedure CheckScroll; procedure AddSaveState; procedure NextSaveState(Forwards: Boolean); procedure GotoSaveState(aTargetIteration: Integer); procedure CheckAdjustReleaseRate; procedure LoadReplay; procedure SetAdjustedGameCursorPoint(BitmapPoint: TPoint); procedure StartReplay; procedure StartReplay2(const aFileName: string); procedure InitializeCursor; procedure SaveShot; protected fGame : TLemmingGame; // reference to globalgame gamemechanics Img : TImage32; // the image in which the level is drawn (reference to inherited ScreenImg!) SkillPanel : TSkillPanelToolbar;// our good old dos skill panel fActivateCount : Integer; // used when activating the form ForceUpdateOneFrame : Boolean; // used when paused GameScroll : TGameScroll; // scrollmode IdealFrameTimeMS : Cardinal; // normal frame speed in milliseconds IdealFrameTimeMSFast : Cardinal; // fast forward framespeed in milliseconds IdealScrollTimeMS : Cardinal; // scroll speed in milliseconds PrevCallTime : Cardinal; // last time we did something in idle PrevScrollTime : Cardinal; // last time we scrolled in idle MouseClipRect : TRect; // we clip the mouse when there is more space CanPlay : Boolean; // use in idle en set to false whenever we don't want to play HCursor1 : HCURSOR; // normal play cursor HCursor2 : HCURSOR; // highlight play cursor LemCursorIconInfo : TIconInfo; // normal play cursor icon LemSelCursorIconInfo : TIconInfo; // highlight play cursor icon MaxDisplayScale : Integer; // calculated in constructor DisplayScale : Integer; // what's the zoomfactor (mostly 2, 3 or 4) MinScroll : Single; // scroll boundary for image MaxScroll : Single; // scroll boundary for image fSaveStates : TIntegerList; // list of savestates (only first is used) fSaveStateIndex : Integer; // index of current savestate (not used) fLastNukeKeyTime : Cardinal; fScrollSpeed : Integer; // fSystemCursor : Boolean; // fMouseBmp : TBitmap32; // fMouseLayer : TBitmapLayer; { overridden} procedure PrepareGameParams(Params: TDosGameParams); override; procedure CloseScreen(aNextScreen: TGameScreenType); override; { internal properties } property Game: TLemmingGame read fGame; public constructor Create(aOwner: TComponent); override; destructor Destroy; override; end; implementation uses FBaseDosForm; { TGameControllerForm } procedure TGameWindow.Application_Idle(Sender: TObject; var Done: Boolean); {------------------------------------------------------------------------------- • Main heartbeat of the program. • This method together with Game.UpdateLemmings() take care of most game-mechanics. • A bit problematic is the releaserate handling: if the game is paused it RR is handled here. if not it is handled by Game.UpdateLemmings(). -------------------------------------------------------------------------------} var CurrTime: Cardinal; Fast, ForceOne, TimeForFrame, TimeForFastForwardFrame, TimeForScroll, Hyper, Pause: Boolean; begin if not CanPlay or not Game.Playing or Game.GameFinished then Exit; // this makes sure this method is called very often :) Done := False; Pause := (Game.Paused) and (Game.CurrentIteration > 33); Fast := Game.FastForward; ForceOne := ForceUpdateOneFrame; ForceUpdateOneFrame := False; CurrTime := TimeGetTime; TimeForFrame := CurrTime - PrevCallTime > IdealFrameTimeMS; TimeForFastForwardFrame := Fast and (CurrTime - PrevCallTime > IdealFrameTimeMSFast); TimeForScroll := CurrTime - PrevScrollTime > IdealScrollTimeMS; Hyper := Game.HyperSpeed; // relax CPU if not Hyper or Fast then Sleep(1); if ForceOne or Hyper or TimeForFastForwardFrame or TimeForFrame or TimeForScroll then begin // PrevCallTime := CurrTime; --> line deleted and moved down // only in paused mode adjust RR. If not paused it's updated per frame. if Game.Paused then if (TimeForScroll and not Game.Replaying) or ForceOne then CheckAdjustReleaseRate; if TimeForScroll then begin PrevScrollTime := CurrTime; CheckScroll; end; //if ForceOne or not Game.Paused then THIS IS ORIGINAL BUT MAYBE WRONG if (TimeForFrame and not Pause) or (TimeForFastForwardFrame and not Pause) or (Forceone and Pause) or Hyper then begin PrevCallTime := CurrTime; Game.UpdateLemmings; end; if not Hyper then begin SkillPanel.RefreshInfo; SkillPanel.DrawMinimap(Game.MinimapBuffer); CheckResetCursor; end else begin if Game.CurrentIteration >= Game.TargetIteration then begin Game.HyperSpeedEnd; SkillPanel.RefreshInfo; SkillPanel.DrawMinimap(Game.MinimapBuffer); CheckResetCursor; end; end; end; end; procedure TGameWindow.GotoSaveState(aTargetIteration: Integer); {------------------------------------------------------------------------------- Go in hyperspeed from the beginning to aTargetIteration -------------------------------------------------------------------------------} var CurrentlyPaused: Boolean; ReplayGlitchFrames: Integer; begin CanPlay := False; CurrentlyPaused := Game.Paused; ReplayGlitchFrames := Game.ReplayGlitchIterations; Game.Start(True); Game.ReplayGlitchIterations := ReplayGlitchFrames; Game.HyperSpeedBegin(CurrentlyPaused); Game.TargetIteration := aTargetIteration; SkillPanel.RefreshInfo; CanPlay := True; end; procedure TGameWindow.CheckResetCursor; begin if FindControl(GetForegroundWindow()) = nil then begin fNeedReset := true; exit; end; if Screen.Cursor <> Game.CurrentCursor then begin Img.Cursor := Game.CurrentCursor; Screen.Cursor := Game.CurrentCursor; end; if fNeedReset then begin ClipCursor(@MouseClipRect); fNeedReset := false; end; {if ** need proper clip check here** begin ClipCursor(@MouseClipRect); end;} end; procedure TGameWindow.CheckScroll; begin case GameScroll of gsRight: begin //if Mouse. Img.OffsetHorz := Max(MinScroll * DisplayScale, Img.OffSetHorz - DisplayScale * 8 * fScrollSpeed); end; (* if Img.OffSetHorz > MinScroll * DisplayScale then begin Img.OffSetHorz := Img.OffSetHorz - DisplayScale * 8; end; *) gsLeft: begin Img.OffsetHorz := Min(MaxScroll * DisplayScale, Img.OffSetHorz + DisplayScale * 8 * fScrollSpeed); end; (* if Img.OffSetHorz < MaxScroll * DisplayScale then begin Img.OffSetHorz := Img.OffSetHorz + DisplayScale * 8; end; *) end; end; constructor TGameWindow.Create(aOwner: TComponent); var HScale, VScale: Integer; begin inherited Create(aOwner); // create game fGame := GlobalGame; // set ref to GlobalGame fGame.OnFinish := Game_Finished; fScrollSpeed := 1; fSaveStates := TIntegerList.Create; Img := ScreenImg; // set ref to inherited screenimg (just for a short name) Img.RepaintMode := rmOptimizer; Img.Color := clNone; Img.BitmapAlign := baCustom; Img.ScaleMode := smScale; // fMouseBmp := TBitmap32.create; // create toolbar SkillPanel := TSkillPanelToolbar.Create(Self); SkillPanel.Parent := Self; // IdealFrameTimeMS := 60; // IdealFrameTimeMSFast := 0; // IdealScrollTimeMS := 60; // calculate displayscale HScale := Screen.Width div 320; VScale := Screen.Height div 200; DisplayScale := HScale; if VScale < HScale then DisplayScale := VScale; MaxDisplayScale := DisplayScale; Self.KeyPreview := True; // set eventhandlers Self.OnActivate := Form_Activate; Self.OnKeyDown := Form_KeyDown; Self.OnKeyUp := Form_KeyUp; Self.OnKeyPress := Form_KeyPress; Self.OnMouseMove := Form_MouseMove; Self.OnMouseUp := Form_MouseUp; Img.OnMouseDown := Img_MouseDown; Img.OnMouseMove := Img_MouseMove; Img.OnMouseUp := Img_MouseUp; SkillPanel.Game := fGame; // this links the game to the infopainter interface as well SkillPanel.OnMinimapClick := SkillPanel_MinimapClick; Application.OnIdle := Application_Idle; end; destructor TGameWindow.Destroy; begin CanPlay := False; Application.OnIdle := nil; fSaveStates.Free; if SkillPanel <> nil then SkillPanel.Game := nil; if HCursor1 <> 0 then DestroyIcon(HCursor1); if HCursor2 <> 0 then DestroyIcon(HCursor2); // if fMouseBmp <> nil then // fMouseBmp.Free; inherited Destroy; end; procedure TGameWindow.Form_Activate(Sender: TObject); // activation eventhandler begin if fActivateCount = 0 then begin fGame.Start; CanPlay := True; end; Inc(fActivateCount) end; procedure TGameWindow.Form_KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var CurrTime: Cardinal; begin if Key = VK_ESCAPE then begin Game.Finish; // OnFinish eventhandler does the rest end; if not Game.Playing then Exit; // this is quite important: no gamecontrol if going fast if (Key <> VK_F11) and (Game.HyperSpeed or Game.FastForward) then Exit; with Game do begin if Shift = [] then begin if ((Key >= VK_F1) and (Key <= VK_F12)) or ((Key >= 48) and (Key <= 56)) or (Key = 187) or (Key = 189) then begin if (Key <> VK_F11) and (Key <> 48) then Game.RegainControl; case Key of VK_RETURN:; VK_F1: SetSelectedSkill(spbSlower, True); VK_F2: SetSelectedSkill(spbFaster, True); VK_F3: SetSelectedSkill(spbClimber, True); VK_F4: SetSelectedSkill(spbUmbrella, True); VK_F5: SetSelectedSkill(spbExplode, True); VK_F6: SetSelectedSkill(spbBlocker, True); VK_F7: SetSelectedSkill(spbBuilder, True); VK_F8: SetSelectedSkill(spbBasher, True); VK_F9: SetSelectedSkill(spbMiner, True); VK_F10: SetSelectedSkill(spbDigger, True); VK_F11: SetSelectedSkill(spbPause); 189: // minus button begin if not GameParams.StateControlEnabled then SetSelectedSkill(spbSlower, True); end; 187: SetSelectedSkill(spbFaster, True); // plus button // 48 through 56 correspond to the '0' through '8' keys 48: SetSelectedSkill(spbPause); 49: SetSelectedSkill(spbClimber, True); 50: SetSelectedSkill(spbUmbrella, True); 51: SetSelectedSkill(spbExplode, True); 52: SetSelectedSkill(spbBlocker, True); 53: SetSelectedSkill(spbBuilder, True); 54: SetSelectedSkill(spbBasher, True); 55: SetSelectedSkill(spbMiner, True); 56: SetSelectedSkill(spbDigger, True); VK_F12: begin // double keypress needed to prevent accidently nuking CurrTime := TimeGetTime; if CurrTime - fLastNukeKeyTime < 250 then SetSelectedSkill(spbNuke) else fLastNukeKeyTime := CurrTime; end; end; end // other keys else begin case Key of VK_LEFT : GameScroll := gsLeft; VK_RIGHT : GameScroll := gsRight; VK_RETURN : AddSaveState; VK_BACK : begin if GameParams.StateControlEnabled then NextSaveState(False); end; end; end; end; end; end; procedure TGameWindow.Form_KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if not Game.Playing then Exit; with Game do begin case Key of VK_F1 : SetSelectedSkill(spbSlower, False); VK_F2 : SetSelectedSkill(spbFaster, False); 189 : // minus button begin if not GameParams.StateControlEnabled then SetSelectedSkill(spbSlower, False); end; 187 : SetSelectedSkill(spbFaster, False); // plus button VK_LEFT : GameScroll := gsNone; VK_RIGHT : GameScroll := gsNone; end; end; end; procedure TGameWindow.SetAdjustedGameCursorPoint(BitmapPoint: TPoint); {------------------------------------------------------------------------------- convert the normal hotspot to the hotspot the game uses (4,9 instead of 7,7) -------------------------------------------------------------------------------} begin Game.CursorPoint := Point(BitmapPoint.X - 3, BitmapPoint.Y + 2); end; procedure TGameWindow.Img_MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); {------------------------------------------------------------------------------- mouse handling of the game -------------------------------------------------------------------------------} var HandleClick: Boolean; begin // interrupting hyperspeed can break the handling of savestates // so we're not allowing it if Game.Playing and not Game.HyperSpeed then begin Game.RegainControl; //Game.CursorPoint := SetAdjustedGameCursorPoint(Img.ControlToBitmap(Point(X, Y))); //Game.CursorPoint := Img.ControlToBitmap(Point(X, Y)); //umisc // debug creation of lemming (* if LemmixDebugMode then if ssCtrl in Shift then if ssAlt in Shift then begin Game.CreateLemmingAtCursorPoint;//lemgame Exit; end; *) // normal Game.RightMouseButtonHeldDown := ssRight in Shift; if Button = mbLeft then begin HandleClick := {not Game.Paused and} not Game.FastForward{ or UseClicksWhenPaused}; if HandleClick then begin Game.ProcessSkillAssignment; if Game.Paused and GameParams.StateControlEnabled then ForceUpdateOneFrame := True; end; end; end; end; procedure TGameWindow.Img_MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); begin if Game.Playing then begin Game.RightMouseButtonHeldDown := ssRight in Shift; (* if ssRight in Shift then fScrollSpeed := 2 else fScrollSpeed := 1; *) SetAdjustedGameCursorPoint(Img.ControlToBitmap(Point(X, Y))); //Game.CursorPoint := Img.ControlToBitmap(Point(X, Y)); if Game.Paused then Game.HitTest; // maybe move to idle if X >= Img.Width - 1 then GameScroll := gsRight else if X <= 0 then GameScroll := gsLeft else GameScroll := gsNone; end; Game.HitTestAutoFail := Y >= SkillPanel.Top; end; procedure TGameWindow.Img_MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); begin Game.RightMouseButtonHeldDown := ssRight in Shift; end; procedure TGameWindow.InitializeCursor; const PLAYCURSOR_DEFAULT = 1; PLAYCURSOR_LEMMING = 2; var bmpMask : TBitmap; bmpColor : TBitmap; procedure scalebmp(bmp:tbitmap; ascale:integer); var //bad code but it works for now b: tbitmap32; src,dst:trect; begin if ascale=1 then exit; b:=tbitmap32.create; src:=rect(0,0,bmp.width,bmp.height); dst:=rect(0,0,bmp.width * ascale, bmp.height*ascale); b.setsize(bmp.width*ascale, bmp.height*ascale); b.Draw(dst,src, bmp.canvas.handle); bmp.Width := b.width; bmp.height:=b.height; b.drawto(bmp.canvas.handle, 0, 0);// gr32 b.free; end; begin bmpMask := TBitmap.Create; bmpColor := TBitmap.Create; //bmpMask.LoadFromFile(apppath + 'dosgamecursormask1.bmp'); //bmpColor.LoadFromFile(apppath+'dosgamecursor1.bmp'); bmpMask.LoadFromResourceName(HINSTANCE, 'GAMECURSOR_DEFAULT_MASK'); bmpColor.LoadFromResourceName(HINSTANCE, 'GAMECURSOR_DEFAULT'); // bmpcolor.canvas.pixels[3,8]:=clred; ScaleBmp(bmpMask, DisplayScale); ScaleBmp(bmpColor, DisplayScale); (* if not fSystemCursor then begin fMouseBmp.Assign(bmpColor); fMouseBmp.DrawMode := dmTransparent; fMouseLayer := TBitmapLayer.Create(Img.Layers); fMouseLayer.LayerOptions := LOB_VISIBLE; fMouseLayer.Location := FloatRect(0, 0, fMouseBmp.Width, fMouseBmp.Height) end; *) with LemCursorIconInfo do begin fIcon := false; xHotspot := 7 * DisplayScale; //4 * displayscale;//7 * DisplayScale;//bmpmask.width div 2+displayscale; yHotspot := 7 * DisplayScale; //9 * displayscale;//7 * DisplayScale;//bmpmask.Height div 2+displayscale; hbmMask := bmpMask.Handle; hbmColor := bmpColor.Handle; end; HCursor1 := CreateIconIndirect(LemCursorIconInfo); Screen.Cursors[PLAYCURSOR_DEFAULT] := HCursor1; img.Cursor := PLAYCURSOR_DEFAULT; SkillPanel.img.cursor := PLAYCURSOR_DEFAULT; Self.Cursor := PLAYCURSOR_DEFAULT; bmpMask.Free; bmpColor.Free; ////////// bmpMask := TBitmap.Create; bmpColor := TBitmap.Create; // bmpMask.LoadFromFile(apppath + 'dosgamecursormask2.bmp'); // bmpColor.LoadFromFile(apppath+'dosgamecursor2.bmp'); bmpMask.LoadFromResourceName(HINSTANCE, 'GAMECURSOR_HIGHLIGHT_MASK'); bmpColor.LoadFromResourceName(HINSTANCE, 'GAMECURSOR_HIGHLIGHT'); scalebmp(bmpmask, DisplayScale); scalebmp(bmpcolor, DisplayScale); with LemSelCursorIconInfo do begin fIcon := false; xHotspot := 7 * DisplayScale; //4 * DisplayScale;//}bmpmask.width div 2+displayscale; yHotspot := 7 * DisplayScale; //9 * DisplayScale;//}bmpmask.Height div 2+displayscale; // xHotspot := 7 * 3;////5; // yHotspot := 7 * 3;//15; hbmMask := bmpMask.Handle; hbmColor := bmpColor.Handle; end; HCursor2 := CreateIconIndirect(LemSelCursorIconInfo); Screen.Cursors[PLAYCURSOR_LEMMING] := HCursor2; // Screen.Cursor := MyCursor; // Self.Cursor := HCursor1; bmpMask.Free; bmpColor.Free; end; procedure TGameWindow.PrepareGameParams(Params: TDosGameParams); {------------------------------------------------------------------------------- This method is called by the inherited ShowScreen -------------------------------------------------------------------------------} var Sca: Integer; StoredScale: Integer; // scale as stored in ini-file begin inherited; StoredScale := Params.ZoomFactor; // fSystemCursor := GameParams.UseSystemCursor; // set the final displayscale Sca := MaxDisplayScale; if (StoredScale > 0) and (StoredScale <= MaxDisplayScale) then begin Sca := StoredScale; DisplayScale := Sca; end; // correct if wrong zoomfactor in inifile if (StoredScale <> 0) and (StoredScale > MaxDisplayScale) then Params.ZoomFactor := Sca; GameParams.TargetBitmap := Img.Bitmap; fGame.PrepareParams(Params); // set timers IdealFrameTimeMSFast := 10; IdealScrollTimeMS := 60; // check superlemming if fGame.Level.Info.SuperLemming then IdealFrameTimeMS := 20 else IdealFrameTimeMS := 60; Img.Width := 320 * Sca; Img.Height := 160 * Sca; Img.Scale := Sca; Img.OffsetHorz := -GameParams.Level.Info.ScreenPosition * Sca; Img.Left := (Screen.Width - Img.Width) div 2; Img.Top := (Screen.Height - 200 * Sca) div 2; SkillPanel.Top := Img.Top + Img.Height; SkillPanel.left := Img.Left; SkillPanel.Width := Img.Width; SkillPanel.Height := 40 * Sca; MouseClipRect := Rect(Img.Left, Img.Top, Img.Left + Img.Width, SkillPanel.Top + SkillPanel.Height); SkillPanel.SetStyleAndGraph(Gameparams.Style, GameParams.GraphicSet, Sca); MinScroll := -(GAME_BMPWIDTH - 320); MaxScroll := 0; InitializeCursor; SetCursorPos(Screen.Width div 2, Screen.Height div 2); ClipCursor(@MouseClipRect); end; procedure TGameWindow.SkillPanel_MinimapClick(Sender: TObject; const P: TPoint); {------------------------------------------------------------------------------- This method is an eventhandler (TSkillPanel.OnMiniMapClick), called when user clicks in the minimap-area of the skillpanel. Here we scroll the game-image. -------------------------------------------------------------------------------} var // N: TPoint; O: Single; begin // Game.CurrentScreenPosition := Point(P.X, 0); O := -P.X * DisplayScale; O := O + Img.Width div 2; if O < MinScroll * DisplayScale then O := MinScroll * DisplayScale; if O > MaxScroll * DisplayScale then O := MaxScroll * DisplayScale; Img.OffSetHorz := O; end; procedure TGameWindow.Form_KeyPress(Sender: TObject; var Key: Char); begin case UpCase(Key) of // --------- CHEAT ---------------- 'C': begin Game.Cheat; // lemgame end; // --------- LOWERCASE ------------ // go 10 game seconds further ' ': if Game.Playing then begin if not Game.HyperSpeed then begin //windows.beep(448, 3); Game.HyperSpeedBegin; Game.TargetIteration := Game.CurrentIteration + 17 * 10; end end; // go back approximately 1 game second '-': if GameParams.StateControlEnabled and Game.Playing then begin if not Game.HyperSpeed then begin if (Game.CurrentIteration >= 17) then GotoSaveState(Game.CurrentIteration - 17) else GotoSaveState(0); end end; // go back 1 frame 'B': if GameParams.StateControlEnabled and Game.Playing then begin if not Game.HyperSpeed then begin if (Game.CurrentIteration >= 2) then GotoSaveState(Game.CurrentIteration - 2) else GotoSaveState(0); end end; // test method ClipCursor {'c': ClipCursor(@MouseClipRect);}//TestClip; // toggle fastforward 'F': if not Game.Paused then Game.FastForward := not Game.FastForward; '9': if not Game.Paused then Game.FastForward := not Game.FastForward; // hide/show lemming debug line // 'h': if LemmixDebugMode then ToggleDebugLemming; // hide/show frame info debug line // 'i': if LemmixDebugMode then ToggleFrameInfo; // hide/show lemming foot-pixel // 'l': if LemmixDebugMode then Game.DrawLemmingPixel := not Game.DrawLemmingPixel; // save snapshot image 'I': SaveShot; // load replay file 'L': if GameParams.StateControlEnabled then LoadReplay; // enable/disable music 'M': begin if gsoMusic in Game.SoundOpts then Game.SoundOpts := Game.SoundOpts - [gsoMusic] else Game.SoundOpts := Game.SoundOpts + [gsoMusic]; if gsoMusic in Game.SoundOpts then Game.SetSoundChannels(4) else Game.SetSoundChannels(7); end; // do next frame if paused 'N': {if LemmixDebugMode then} if GameParams.StateControlEnabled and Game.Paused then //if Game.Replaying then ForceUpdateOneFrame := True; {'p': ;}{ if Game.Playing and Game.Paused then if Game.CurrentIteration > 0 then begin if not Game.HyperSpeed then begin GotoSaveState(Game.CurrentIteration - 1); //Game.SetSelectedSkill(spbPause, True); // Game.Paused := True; //windows.beep(448, 3); // Game.HyperSpeedBegin; // Game.TargetIteration := Game.CurrentIteration - 1; end end; *) } // disable/enable skill assignment when paused // 'p': if LemmixDebugMode then UseClicksWhenPaused := not UseClicksWhenPaused; 'P': Game.SetSelectedSkill(spbPause); // start replay 'R': if GameParams.StateControlEnabled then StartReplay; // enable/disable sounds 'S': begin if gsoSound in Game.SoundOpts then Game.SoundOpts := Game.SoundOpts - [gsoSound] else Game.SoundOpts := Game.SoundOpts + [gsoSound]; end; // save current game to .\Replay\<leveltitle>.lrb // in addition a more or less readable version is saved too with the extension ".txt" 'U': Game.Save; 'Z': with Game do begin RegainControl; case SelectedSkill of spbUmbrella: SetSelectedSkill(spbClimber, True); spbExplode: SetSelectedSkill(spbUmbrella, True); spbBlocker: SetSelectedSkill(spbExplode, True); spbBuilder: SetSelectedSkill(spbBlocker, True); spbBasher: SetSelectedSkill(spbBuilder, True); spbMiner: SetSelectedSkill(spbBasher, True); spbDigger: SetSelectedSkill(spbMiner, True); end; end; 'X': with Game do begin RegainControl; case SelectedSkill of spbClimber: SetSelectedSkill(spbUmbrella, True); spbUmbrella: SetSelectedSkill(spbExplode, True); spbExplode: SetSelectedSkill(spbBlocker, True); spbBlocker: SetSelectedSkill(spbBuilder, True); spbBuilder: SetSelectedSkill(spbBasher, True); spbBasher: SetSelectedSkill(spbMiner, True); spbMiner: SetSelectedSkill(spbDigger, True); end; end; end; end; procedure TGameWindow.Form_MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin with MouseClipRect do if (Y >= Img.Top) and (Y <= Img.Top + Img.Height - 1) then begin if X <= Img.Left + DisplayScale then GameScroll := gsLeft else if X >= Img.Left + Img.Width - 1 + DisplayScale then GameScroll := gsRight else GameScroll := gsNone; end else GameScroll := gsNone; end; procedure TGameWindow.Form_MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin GameScroll := gsNone; end; procedure TGameWindow.SaveShot; var Dlg : TSaveDialog; SaveName: String; begin Dlg := TSaveDialog.Create(self); dlg.Filter := 'PNG Image (*.png)|*.png'; dlg.FilterIndex := 1; dlg.InitialDir := '"' + ExtractFilePath(Application.ExeName) + '/"'; dlg.DefaultExt := '.png'; if dlg.Execute then begin SaveName := dlg.FileName; Game.SaveGameplayImage(SaveName); end; Dlg.Free; end; procedure TGameWindow.CheckAdjustReleaseRate; {------------------------------------------------------------------------------- In the mainloop the decision is made if we really have to update -------------------------------------------------------------------------------} begin with Game do begin if SpeedingUpReleaseRate then begin // if not (Replaying and Paused) then AdjustReleaseRate(1) end else if SlowingDownReleaseRate then begin // if not (Replaying and Paused) then AdjustReleaseRate(-1) end; if InstReleaseRate = -1 then AdjustReleaseRate(-100) else if InstReleaseRate = 1 then AdjustReleaseRate(100); InstReleaseRate := 0; end; end; procedure TGameWindow.StartReplay; var ReplayGlitchFrames : Integer; begin CanPlay := False; ReplayGlitchFrames := Game.ReplayGlitchIterations; Game.SetGameResult; Game.Start(True); Game.ReplayGlitchIterations := ReplayGlitchFrames; SkillPanel.RefreshInfo; CanPlay := True; end; procedure TGameWindow.StartReplay2(const aFileName: string); begin CanPlay := False; { if CompareText(ExtractFileExt(aFileName), '.TXT') = 0 then Game.Recorder.LoadFromOldTxt(aFileName) else } Game.Recorder.LoadFromFile(aFileName); //SaveReplay; asdf // Game.Renderer.RenderWorld(Game.Level); // FillChar(SaveStates, SizeOf(SaveStates), 0); Game.Start(True); SkillPanel.RefreshInfo; CanPlay := True; end; procedure TGameWindow.LoadReplay; var OldCanPlay: Boolean; Dlg : TOpenDialog; s: string; begin OldCanPlay := CanPlay; CanPlay := False; s:=''; dlg:=topendialog.create(nil); try // dlg.DefaultExt := '*.lrb'; dlg.filename := '*.lrb'; if dlg.execute then begin s:=dlg.filename; end; finally dlg.free; end; if s <> '' then begin StartReplay2(s); exit; end; CanPlay := OldCanPlay; end; procedure TGameWindow.Game_Finished(Sender: TObject); begin {$ifdef testmode} if (GameParams.fTestMode and (GameParams.QuickTestMode in [2, 3])) then begin if GameParams.QuickTestMode = 3 then Game.Save(true); CloseScreen(gstExit) end else{$endif} CloseScreen(gstPostview); end; procedure TGameWindow.CloseScreen(aNextScreen: TGameScreenType); begin CanPlay := False; Application.OnIdle := nil; ClipCursor(nil); Cursor := crNone; // GameParams.NextScreen := gstPostview; Game.SetGameResult; GameParams.GameResult := Game.GameResultRec; with GameParams, GameResult do begin if gSuccess{$ifdef testmode}and (not GameParams.fTestMode){$endif} then WhichLevel := wlNext; end; Img.RepaintMode := rmFull; inherited CloseScreen(aNextScreen); end; procedure TGameWindow.AddSaveState; begin if fSaveStates.Count = 0 then fSaveStates.Add(Game.CurrentIteration) else fSaveStates[0] := Game.CurrentIteration; (* if fSaveStateIndex = fSaveStates.Count - 1 then begin fSaveStates.Add(Game.CurrentIteration); Inc(fSaveStateIndex); end else begin fSaveStates.SetCapacityAndCount(fSaveStateIndex + 1, 0); fSaveStates.Add(Game.CurrentIteration); Inc(fSaveStateIndex); end; *) // fSaveStates.SetCapacityAndCount(fSaveStateIndex + 1); // fSaveStates[fSaveStateIndex] := Game.CurrentIteration; classes utools end; procedure TGameWindow.NextSaveState(Forwards: Boolean); begin case Forwards of False: begin if fSaveStates.Count > 0 then GotoSaveState(fSaveStates[0]); (* if fSaveStateIndex >= 0 then begin GotoSaveState(fSaveStates[fSaveStateIndex]); Dec(fSaveStateIndex); end; *) end; True: begin if fSaveStates.Count > 0 then GotoSaveState(fSaveStates[0]); end; end; end; end. (* procedure TGameWindow.Form_Close(Sender: TObject; var Action: TCloseAction); begin CanPlay := False; Application.OnIdle := nil; ClipCursor(nil); GameParams.NextScreen := gstPostview; Game.SetGameResult; GameParams.GameResult := Game.GameResultRec; with GameParams, GameResult do begin if gSuccess then WhichLevel := wlNext; end; end; procedure TGameWindow.InitializeCursor; const PLAYCURSOR_DEFAULT = 1; PLAYCURSOR_LEMMING = 2; var bmpMask : TBitmap32; bmpColor : TBitmap32; procedure ScaleBmp(Bmp: TBitmap32; aScale: Integer); var //bad code but it works for now Temp: TBitmap32; Src, Dst: TRect; begin if aScale = 1 then Exit; Temp := TBitmap32.Create; Src := Rect(0, 0, Bmp.Width, Bmp.Height); Dst := Rect(0, 0, Bmp.Width * aScale, Bmp.Height * aScale); Temp.SetSize(Bmp.Width * aScale, Bmp.Height * aScale); Bmp.DrawTo(Temp, Dst, Src); Bmp.Width := Temp.Width; Bmp.Height := Temp.Height; Temp.DrawTo(Bmp, 0, 0); Temp.Free; end; begin bmpMask := TBitmap32.Create; bmpColor := TBitmap32.Create; //bmpMask.LoadFromFile(apppath + 'dosgamecursormask1.bmp'); //bmpColor.LoadFromFile(apppath+'dosgamecursor1.bmp'); bmpMask.LoadFromResourceName(HINSTANCE, 'GAMECURSOR_DEFAULT_MASK'); bmpColor.LoadFromResourceName(HINSTANCE, 'GAMECURSOR_DEFAULT'); // bmpcolor.canvas.pixels[3,8]:=clred; ScaleBmp(bmpMask, DisplayScale); ScaleBmp(bmpColor, DisplayScale); with LemCursorIconInfo do begin fIcon := false; xHotspot := 3 * displayscale + DisplayScale;//7 * DisplayScale;//bmpmask.width div 2+displayscale; yHotspot := 8 * displayscale + DisplayScale;//7 * DisplayScale;//bmpmask.Height div 2+displayscale; hbmMask := bmpMask.Handle; hbmColor := bmpColor.Handle; end; HCursor1 := CreateIconIndirect(LemCursorIconInfo); Screen.Cursors[PLAYCURSOR_DEFAULT] := HCursor1;//CreateIconIndirect(LemCursorIconInfo); img.Cursor := PLAYCURSOR_DEFAULT; SkillPanel.img.cursor := PLAYCURSOR_DEFAULT; Self.Cursor := PLAYCURSOR_DEFAULT; bmpMask.Free; bmpColor.Free; ////////// bmpMask := TBitmap32.Create; bmpColor := TBitmap32.Create; // bmpMask.LoadFromFile(apppath + 'dosgamecursormask2.bmp'); // bmpColor.LoadFromFile(apppath+'dosgamecursor2.bmp'); bmpMask.LoadFromResourceName(HINSTANCE, 'GAMECURSOR_HIGHLIGHT_MASK'); bmpColor.LoadFromResourceName(HINSTANCE, 'GAMECURSOR_HIGHLIGHT'); scalebmp(bmpmask, DisplayScale); scalebmp(bmpcolor, DisplayScale); with LemSelCursorIconInfo do begin fIcon := false; xHotspot := 3 * DisplayScale + DisplayScale;//}bmpmask.width div 2+displayscale; yHotspot := 8 * DisplayScale + DisplayScale;//}bmpmask.Height div 2+displayscale; // xHotspot := 7 * 3;////5; // yHotspot := 7 * 3;//15; hbmMask := bmpMask.Handle; hbmColor := bmpColor.Handle; end; HCursor2 := CreateIconIndirect(LemSelCursorIconInfo); Screen.Cursors[PLAYCURSOR_LEMMING] := HCursor2; // Screen.Cursor := MyCursor; // Self.Cursor := HCursor1; bmpMask.Free; bmpColor.Free; end; ////////////////////////// var BmpColor, BmpMask: TBitmap; Info: TIconInfo; Cur : HCURSOR; BmpColor := TBitmap.Create; BmpMask := TBitmap.Create; BmpColor.LoadFromSomething(...) BmpMask.LoadFromSomething(...) with Info do begin fIcon := False; xHotspot := 7 yHotspot := 7 hbmMask := BmpMask.Handle; hbmColor := BmpColor.Handle; end; Cur := CreateIconIndirect(LemCursorIconInfo); Screen.Cursors[1] := Cur; BmpColor.Free; BmpMask.Free;
{=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=] Copyright (c) 2013, Jarl K. <Slacky> Holta || http://github.com/WarPie All rights reserved. For more info see: Copyright.txt [=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=} {* Flips the matrices order. *} function FlipMat(const Mat:T2DByteArray): T2DByteArray; overload; var x,y,H,W:Integer; begin H := High(Mat); if (H = -1) then NewException('Matrix must be initalized'); W := High(Mat[0]); SetLength(Result, W+1,H+1); for y:=0 to H do for x:=0 to W do Result[x,y] := Mat[y,x]; end; function FlipMat(const Mat:T2DIntArray): T2DIntArray; overload; var x,y,H,W:Integer; begin H := High(Mat); if (H = -1) then NewException('Matrix must be initalized'); W := High(Mat[0]); SetLength(Result, W+1,H+1); for y:=0 to H do for x:=0 to W do Result[x,y] := Mat[y,x]; end; function FlipMat(const Mat:T2DFloatArray): T2DFloatArray; overload; var x,y,H,W:Integer; begin H := High(Mat); if (H = -1) then NewException('Matrix must be initalized'); W := High(Mat[0]); SetLength(Result, W+1,H+1); for y:=0 to H do for x:=0 to W do Result[x,y] := Mat[y,x]; end; function FlipMat(const Mat:T2DDoubleArray): T2DDoubleArray; overload; var x,y,H,W:Integer; begin H := High(Mat); if (H = -1) then NewException('Matrix must be initalized'); W := High(Mat[0]); SetLength(Result, W+1,H+1); for y:=0 to H do for x:=0 to W do Result[x,y] := Mat[y,x]; end; function FlipMat(const Mat:T2DExtArray): T2DExtArray; overload; var x,y,H,W:Integer; begin H := High(Mat); if (H = -1) then NewException('Matrix must be initalized'); W := High(Mat[0]); SetLength(Result, W+1,H+1); for y:=0 to H do for x:=0 to W do Result[x,y] := Mat[y,x]; end;
{******************************************************************************* 作者: dmzn@163.com 2009-7-1 描述: 全局定义 备注: *.活动窗体gActiveForm用于表示当前用户在操作的窗口 *.文件前缀sFilePostfix,指在后台管理相关文件的基础上,添加后缀标致. 例如配置文件Config.ini,加完后缀为Config_B.ini *******************************************************************************} unit USysGobal; interface uses Classes; var gOnCloseActiveForm: TNotifyEvent = nil; //窗口关闭 Resourcestring sFilePostfix = '_B'; //文件后缀 sMember_Man = 'Member_Man'; //男会员 sMember_Woman = 'Member_Woman'; //女会员 sList_Plan = 'List_Plan'; //方案列表 sList_Product = 'List_Product'; //产品列表 sButton_Member = 'Button_Member'; //会员管理 sButton_Plan = 'Button_Plan'; //方案管理 sButton_Sync = 'Button_Sync'; //数据同步 sButton_Exit = 'Button_Exit'; //退出系统 sButton_Return = 'Button_Return'; //返回主菜单 sButton_MyInfo = 'Button_MyInfo'; //会员信息 sButton_Contrast = 'Button_Contrast'; //图像对比 sButton_Pick = 'Button_Pick'; //图像采集 sGroup_System = 'Group_System'; //系统管理 sGroup_Member = 'Group_Member'; //会员列表 sGroup_Plan = 'Group_Plan'; //方案管理 sGroup_Product = 'Group_Product'; //产品列表 sGroup_SysFun = 'Group_SysFun'; //系统功能 sImageConfigFile = 'BeautyConfig.Ini'; //配置文件 sImageViewItem = 'ImageViewItem'; //图片查看框 sImagePointTitle = 'Point_Title'; //标题位置 sImageRectValid = 'RectValid'; //有效区域 sImageBgFile = 'Image_BgFile'; //背景文件 sImageBgStyle = 'Image_BgStyle'; //背景风格 sImageBrdSelected = 'Image_BorderSelected'; //选中边框 sImageBrdUnSelected = 'Image_BorderUnSelected'; //未选中边框 sImageExpandButton = 'ImageExpandButton'; //展开按钮 sImageExpandFile = 'Image_Expand'; //展开 sImageCollapse = 'Image_Collapse'; //合并 implementation end.