text
stringlengths
14
6.51M
unit bioniccommando_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} nz80,mcs51,m68000,main_engine,controls_engine,gfx_engine,ym_2151,rom_engine, pal_engine,sound_engine; function iniciar_bionicc:boolean; implementation const bionicc_rom:array[0..3] of tipo_roms=( (n:'tse_02.1a';l:$10000;p:0;crc:$e4aeefaa),(n:'tse_04.1b';l:$10000;p:$1;crc:$d0c8ec75), (n:'tse_03.2a';l:$10000;p:$20000;crc:$b2ac0a45),(n:'tse_05.2b';l:$10000;p:$20001;crc:$a79cb406)); bionicc_sound:tipo_roms=(n:'ts_01b.4e';l:$8000;p:0;crc:$a9a6cafa); bionicc_mcu:tipo_roms=(n:'ts.2f';l:$1000;p:0;crc:$3ed7f0be); bionicc_char:tipo_roms=(n:'tsu_08.8l';l:$8000;p:0;crc:$9bf0b7a2); bionicc_bg:array[0..1] of tipo_roms=( (n:'tsu_07.5l';l:$8000;p:0;crc:$9469efa4),(n:'tsu_06.4l';l:$8000;p:$8000;crc:$40bf0eb4)); bionicc_fg:array[0..7] of tipo_roms=( (n:'ts_12.17f';l:$8000;p:0;crc:$e4b4619e),(n:'ts_11.15f';l:$8000;p:$8000;crc:$ab30237a), (n:'ts_17.17g';l:$8000;p:$10000;crc:$deb657e4),(n:'ts_16.15g';l:$8000;p:$18000;crc:$d363b5f9), (n:'ts_13.18f';l:$8000;p:$20000;crc:$a8f5a004),(n:'ts_18.18g';l:$8000;p:$28000;crc:$3b36948c), (n:'ts_23.18j';l:$8000;p:$30000;crc:$bbfbe58a),(n:'ts_24.18k';l:$8000;p:$38000;crc:$f156e564)); bionicc_sprites:array[0..7] of tipo_roms=( (n:'tse_10.13f';l:$8000;p:0;crc:$d28eeacc),(n:'tsu_09.11f';l:$8000;p:$8000;crc:$6a049292), (n:'tse_15.13g';l:$8000;p:$10000;crc:$9b5593c0),(n:'tsu_14.11g';l:$8000;p:$18000;crc:$46b2ad83), (n:'tse_20.13j';l:$8000;p:$20000;crc:$b03db778),(n:'tsu_19.11j';l:$8000;p:$28000;crc:$b5c82722), (n:'tse_22.17j';l:$8000;p:$30000;crc:$d4dedeb3),(n:'tsu_21.15j';l:$8000;p:$38000;crc:$98777006)); //DIP bionicc_dip:array [0..8] of def_dip=( (mask:$7;name:'Coin A';number:8;dip:((dip_val:$0;dip_name:'4C 1C'),(dip_val:$1;dip_name:'3C 1C'),(dip_val:$2;dip_name:'2C 1C'),(dip_val:$7;dip_name:'1C 1C'),(dip_val:$6;dip_name:'1C 2C'),(dip_val:$5;dip_name:'1C 3C'),(dip_val:$4;dip_name:'1C 4C'),(dip_val:$3;dip_name:'1C 6C'),(),(),(),(),(),(),(),())), (mask:$38;name:'Coin B';number:8;dip:((dip_val:$0;dip_name:'4C 1C'),(dip_val:$8;dip_name:'3C 1C'),(dip_val:$10;dip_name:'2C 1C'),(dip_val:$38;dip_name:'1C 1C'),(dip_val:$30;dip_name:'1C 2C'),(dip_val:$28;dip_name:'1C 3C'),(dip_val:$20;dip_name:'1C 4C'),(dip_val:$18;dip_name:'1C 6C'),(),(),(),(),(),(),(),())), (mask:$80;name:'Flip Screen';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$300;name:'Lives';number:4;dip:((dip_val:$300;dip_name:'3'),(dip_val:$200;dip_name:'4'),(dip_val:$100;dip_name:'5'),(dip_val:$0;dip_name:'7'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$400;name:'Cabinet';number:2;dip:((dip_val:$400;dip_name:'Upright'),(dip_val:$0;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$1800;name:'Bonus Life';number:4;dip:((dip_val:$1800;dip_name:'20k 40k 100k 60k+'),(dip_val:$1000;dip_name:'30k 50k 120k 70k+'),(dip_val:$800;dip_name:'20k 60k'),(dip_val:$0;dip_name:'30k 70k'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$6000;name:'Difficulty';number:4;dip:((dip_val:$4000;dip_name:'Easy'),(dip_val:$6000;dip_name:'Medium'),(dip_val:$2000;dip_name:'Hard'),(dip_val:$0;dip_name:'Hardest'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$8000;name:'Freeze';number:2;dip:((dip_val:$8000;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); var scroll_fg_x,scroll_fg_y,scroll_bg_x,scroll_bg_y:word; rom:array[0..$1ffff] of word; ram,ram2,fg_ram,bg_ram:array[0..$1fff] of word; txt_ram:array[0..$7ff] of word; //MCU audiocpu_to_mcu,mcu_to_audiocpu,mcu_p1,mcu_p3:byte; procedure update_video_bionicc; var f,color,x,y,nchar,atrib,sx,sy,pos:word; begin fill_full_screen(3,1024); for f:=$0 to $440 do begin //BG x:=f mod 33; y:=f div 33; sx:=x+((scroll_bg_x and $1f8) shr 3); sy:=y+((scroll_bg_y and $1f8) shr 3); pos:=(sx and $3f)+((sy and $3f)*64); atrib:=bg_ram[(pos shl 1)+1] and $ff; color:=(atrib and $18) shr 3; if (gfx[1].buffer[pos] or buffer_color[color+$40]) then begin nchar:=(bg_ram[pos shl 1] and $ff) or ((atrib and $7) shl 8); put_gfx_trans_flip(x*8,y*8,nchar,color shl 4,4,1,(atrib and $80)<>0,(atrib and $40)<>0); gfx[1].buffer[f]:=false; end; end; //FG for f:=$0 to $120 do begin // $121=17*17 x:=f mod 17; //17 --> numero de filas (numero de x) que queremos y:=f div 17; //scroll and [numero_maximo_scroll-long_gfx_x] shr [numero bits long_gfx_x] (por ejemplo 16 bits --> shr 4) sx:=x+((scroll_fg_x and $3f0) shr 4); sy:=y+((scroll_fg_y and $3f0) shr 4); //sx and [numero_maximo_scroll-long_gfx_x] shr [numero bits long_gfx_x] por ejemplo antes $3f0 shr 4=$3f //(sy and [igual que antes])*[numero de filas de la pantalla total] (este caso 1024/16=64) pos:=(sx and $3f)+((sy and $3f)*64); atrib:=fg_ram[(pos shl 1)+1] and $ff; if (atrib and $c0)<>$c0 then begin color:=(atrib and $18) shr 3; if (gfx[2].buffer[pos] or buffer_color[color+$44]) then begin nchar:=(fg_ram[pos shl 1] and $ff) or ((atrib and $7) shl 8); put_gfx_trans_flip_alt(x*16,y*16,nchar,(color shl 4)+256,5,2,(atrib and $80)<>0,(atrib and $40)<>0,0); if (atrib and $20)<>0 then put_gfx_trans_flip_alt(x*16,y*16,nchar,(color shl 4)+256,6,2,(atrib and $80)<>0,(atrib and $40)<>0,1) else put_gfx_block_trans(x*16,y*16,6,16,16); gfx[2].buffer[pos]:=false; end; end; end; //text for f:=$0 to $3ff do begin atrib:=txt_ram[$400+f] and $ff; color:=atrib and $3f; if (gfx[0].buffer[f] or buffer_color[color]) then begin x:=f and $1f; y:=f shr 5; nchar:=(txt_ram[f] and $ff) or ((atrib and $c0) shl 2); put_gfx_trans(x*8,y*8,nchar,(color shl 2)+768,1,0); gfx[0].buffer[f]:=false; end; end; // back scroll_x_y(4,3,scroll_bg_x and $7,scroll_bg_y and $7); scroll_x_y(5,3,scroll_fg_x and $f,scroll_fg_y and $f); //sprites for f:=$9f downto 0 do begin nchar:=buffer_sprites_w[f*4] and $7ff; if nchar<>$7ff then begin atrib:=buffer_sprites_w[(f*4)+1]; color:=((atrib and $3c) shl 2)+512; y:=buffer_sprites_w[(f*4)+2]; x:=buffer_sprites_w[(f*4)+3]; put_gfx_sprite(nchar,color,(atrib and 2)<>0,false,3); actualiza_gfx_sprite(x,y,3,3); end; end; scroll_x_y(6,3,scroll_fg_x and $f,scroll_fg_y and $f); //front actualiza_trozo(0,0,256,256,1,0,0,256,256,3); actualiza_trozo_final(0,16,256,224,3); fillchar(buffer_color,MAX_COLOR_BUFFER,0); end; procedure eventos_bionicc; begin if event.arcade then begin //P2 if arcade_input.but1[1] then marcade.in0:=(marcade.in0 and $fffe) else marcade.in0:=(marcade.in0 or $1); if arcade_input.but0[1] then marcade.in0:=(marcade.in0 and $fffd) else marcade.in0:=(marcade.in0 or $2); if arcade_input.right[1] then marcade.in0:=(marcade.in0 and $fffb) else marcade.in0:=(marcade.in0 or $4); if arcade_input.left[1] then marcade.in0:=(marcade.in0 and $fff7) else marcade.in0:=(marcade.in0 or $8); if arcade_input.down[1] then marcade.in0:=(marcade.in0 and $ffef) else marcade.in0:=(marcade.in0 or $10); if arcade_input.up[1] then marcade.in0:=(marcade.in0 and $ffdf) else marcade.in0:=(marcade.in0 or $20); //P1 if arcade_input.but1[0] then marcade.in0:=(marcade.in0 and $ffbf) else marcade.in0:=(marcade.in0 or $40); if arcade_input.but0[0] then marcade.in0:=(marcade.in0 and $ff7f) else marcade.in0:=(marcade.in0 or $80); if arcade_input.right[0] then marcade.in0:=(marcade.in0 and $feff) else marcade.in0:=(marcade.in0 or $100); if arcade_input.left[0] then marcade.in0:=(marcade.in0 and $fdff) else marcade.in0:=(marcade.in0 or $200); if arcade_input.down[0] then marcade.in0:=(marcade.in0 and $fbff) else marcade.in0:=(marcade.in0 or $400); if arcade_input.up[0] then marcade.in0:=(marcade.in0 and $f7ff) else marcade.in0:=(marcade.in0 or $800); //system if arcade_input.start[1] then marcade.in0:=(marcade.in0 and $efff) else marcade.in0:=(marcade.in0 or $1000); if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $dfff) else marcade.in0:=(marcade.in0 or $2000); if arcade_input.coin[1] then marcade.in0:=(marcade.in0 and $bfff) else marcade.in0:=(marcade.in0 or $4000); if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $7fff) else marcade.in0:=(marcade.in0 or $8000); end; end; procedure bionicc_principal; var frame_m,frame_s,frame_mcu:single; f:byte; begin init_controls(false,false,false,true); frame_m:=m68000_0.tframes; frame_s:=z80_0.tframes; frame_mcu:=mcs51_0.tframes; while EmuStatus=EsRuning do begin for f:=0 to $ff do begin //main m68000_0.run(frame_m); frame_m:=frame_m+m68000_0.tframes-m68000_0.contador; //sound z80_0.run(frame_s); frame_s:=frame_s+z80_0.tframes-z80_0.contador; //mcu mcs51_0.run(frame_mcu); frame_mcu:=frame_mcu+mcs51_0.tframes-mcs51_0.contador; case f of 127:m68000_0.irq[4]:=HOLD_LINE; 239:begin m68000_0.irq[2]:=HOLD_LINE; update_video_bionicc; copymemory(@buffer_sprites_w,@ram[$400],$280*2); end; end; end; eventos_bionicc; video_sync; end; end; function bionicc_getword(direccion:dword):word; begin direccion:=direccion and $fffff; case direccion of 0..$3ffff:bionicc_getword:=rom[direccion shr 1]; $e0000..$e3fff:bionicc_getword:=ram[(direccion and $3fff) shr 1]; $e4000..$e7fff:case (direccion and 3) of 0:bionicc_getword:=marcade.in0; 2:bionicc_getword:=marcade.dswa; end; $ec000..$effff:bionicc_getword:=txt_ram[(direccion and $fff) shr 1]; $f0000..$f3fff:bionicc_getword:=fg_ram[(direccion and $3fff) shr 1]; $f4000..$f7fff:bionicc_getword:=bg_ram[(direccion and $3fff) shr 1]; $f8000..$f87ff:bionicc_getword:=buffer_paleta[(direccion and $7ff) shr 1]; $fc000..$fffff:bionicc_getword:=ram2[(direccion and $3fff) shr 1]; end; end; procedure bionicc_putword(direccion:dword;valor:word); procedure cambiar_color(pos,data:word); var bright:byte; color:tcolor; begin bright:=data and $0f; color.r:=((data shr 12) and $0f)*$11; color.g:=((data shr 8) and $0f)*$11; color.b:=((data shr 4) and $0f)*$11; if ((bright and $08)=0) then begin color.r:=color.r*($07+bright) div $0e; color.g:=color.g*($07+bright) div $0e; color.b:=color.b*($07+bright) div $0e; end; set_pal_color(color,pos); case pos of 0..63:buffer_color[(pos shr 4)+$40]:=true; 256..319:buffer_color[((pos shr 4) and $3)+$44]:=true; 768..1023:buffer_color[(pos shr 2) and $3f]:=true; end; end; begin direccion:=direccion and $fffff; case direccion of 0..$3ffff:; $e0000..$e3fff:ram[(direccion and $3fff) shr 1]:=valor; $e4000..$e7fff:case (direccion and 3) of 0:; //flip 2:z80_0.change_nmi(PULSE_LINE); end; $e8010:if scroll_fg_x<>valor then begin if abs((scroll_fg_x and $3f0)-(valor and $3f0))>15 then fillchar(gfx[2].buffer,$1000,1); scroll_fg_x:=valor and $3ff; end; $e8012:if scroll_fg_y<>valor then begin if abs((scroll_fg_y and $3f0)-(valor and $3f0))>15 then fillchar(gfx[2].buffer,$1000,1); scroll_fg_y:=valor and $3ff; end; $e8014:if scroll_bg_x<>valor then begin if abs((scroll_bg_x and $1f8)-(valor and $1f8))>7 then fillchar(gfx[1].buffer,$1000,1); scroll_bg_x:=valor and $1ff; end; $e8016:if scroll_bg_y<>valor then begin if abs((scroll_bg_y and $1f8)-(valor and $1f8))>7 then fillchar(gfx[1].buffer,$1000,1); scroll_bg_y:=valor and $1ff; end; $e801a:begin //dmaon_w mcs51_0.change_irq0(ASSERT_LINE); m68000_0.change_halt(ASSERT_LINE); end; $ec000..$effff:if txt_ram[(direccion and $fff) shr 1]<>valor then begin txt_ram[(direccion and $fff) shr 1]:=valor; gfx[0].buffer[(direccion and $7ff) shr 1]:=true; end; $f0000..$f3fff:if fg_ram[(direccion and $3fff) shr 1]<>valor then begin fg_ram[(direccion and $3fff) shr 1]:=valor; gfx[1].buffer[(direccion and $3fff) shr 2]:=true; end; $f4000..$f7fff:if bg_ram[(direccion and $3fff) shr 1]<>valor then begin bg_ram[(direccion and $3fff) shr 1]:=valor; gfx[2].buffer[(direccion and $3fff) shr 2]:=true; end; $f8000..$f87ff:if (buffer_paleta[(direccion and $7ff) shr 1]<>valor) then begin buffer_paleta[(direccion and $7ff) shr 1]:=valor; cambiar_color((direccion and $7ff) shr 1,valor); end; $fc000..$fffff:ram2[(direccion and $3fff) shr 1]:=valor; end; end; function bionicc_snd_getbyte(direccion:word):byte; begin case direccion of 0..$7fff,$c000..$c7ff:bionicc_snd_getbyte:=mem_snd[direccion]; $8001:bionicc_snd_getbyte:=ym2151_0.status; $a000:bionicc_snd_getbyte:=mcu_to_audiocpu; end; end; procedure bionicc_snd_putbyte(direccion:word;valor:byte); begin case direccion of 0..$7fff:; $8000:ym2151_0.reg(valor); $8001:ym2151_0.write(valor); $a000:audiocpu_to_mcu:=valor; $c000..$c7ff:mem_snd[direccion]:=valor; end; end; procedure bionicc_sound_update; begin ym2151_0.update; end; function in_port1:byte; begin in_port1:=audiocpu_to_mcu; end; procedure out_port1(valor:byte); begin mcu_p1:=valor; end; procedure out_port3(valor:byte); begin // 7------- read strobe // -6------ write strobe // --5----- dma // ---4---- int1 ack // ----3--- int1 // -----2-- int0 // ------1- int0 flip-flop preset // -------0 int0 ack //mcs51_0.change_irq0(CLEAR_LINE); if (((mcu_p3 and 1)<>0) and ((valor and 1)=0)) then begin mcs51_0.change_irq0(CLEAR_LINE); m68000_0.change_halt(CLEAR_LINE); end; if (((mcu_p3 and $10)<>0) and ((valor and $10)=0)) then mcs51_0.change_irq1(CLEAR_LINE); if (((mcu_p3 and $40)<>0) and ((valor and $40)=0)) then mcu_to_audiocpu:=mcu_p1; mcu_p3:=valor; end; function mcu_ext_ram_read(direccion:word):byte; var address:dword; res:byte; begin res:=$ff; if ((mcu_p3 and $20)=0) then begin direccion:=direccion and $7ff; // various address bits are pulled high because the mcu doesn't drive them // the 3 upper address bits (p2.0, p2.1, p2.2) are connected to a14 to a16 address:=$e3e01 or ((direccion and $700) shl 6) or ((direccion and $ff) shl 1); res:=bionicc_getword(address); end; mcu_ext_ram_read:=res; end; procedure mcu_ext_ram_write(direccion:word;valor:byte); var address:dword; begin if ((mcu_p3 and $20)=0) then begin direccion:=direccion and $7ff; address:=$e3e01 or ((direccion and $700) shl 6) or ((direccion and $ff) shl 1); bionicc_putword(address,valor); end; end; //Main procedure reset_bionicc; begin m68000_0.reset; z80_0.reset; mcs51_0.reset; ym2151_0.reset; reset_audio; marcade.in0:=$ffff; scroll_fg_x:=0; scroll_fg_y:=0; scroll_bg_x:=0; scroll_bg_y:=0; audiocpu_to_mcu:=0; mcu_to_audiocpu:=0; mcu_p1:=0; mcu_p3:=0; end; function iniciar_bionicc:boolean; var memoria_temp:array[0..$3ffff] of byte; const pf_x:array[0..15] of dword=(0,1,2,3, 8,9,10,11, (8*4*8)+0,(8*4*8)+1,(8*4*8)+2,(8*4*8)+3,(8*4*8)+8,(8*4*8)+9,(8*4*8)+10,(8*4*8)+11); pf_y:array[0..15] of dword=(0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16, 8*16, 9*16, 10*16, 11*16, 12*16, 13*16, 14*16, 15*16); ps_x:array[0..15] of dword=(0,1,2,3,4,5,6,7, (16*8)+0,(16*8)+1,(16*8)+2,(16*8)+3,(16*8)+4,(16*8)+5,(16*8)+6,(16*8)+7); ps_y:array[0..15] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 8*8, 9*8, 10*8, 11*8, 12*8, 13*8, 14*8, 15*8); begin llamadas_maquina.bucle_general:=bionicc_principal; llamadas_maquina.reset:=reset_bionicc; iniciar_bionicc:=false; iniciar_audio(false); //Pantallas screen_init(1,256,256,true); screen_init(3,512,512,false,true); screen_init(4,256+8,256+8); screen_mod_scroll(4,264,256,255,264,256,255); screen_init(5,256+16,256+16,true); screen_mod_scroll(5,272,256,255,272,256,255); screen_init(6,256+16,256+16,true); screen_mod_scroll(6,272,256,255,272,256,255); iniciar_video(256,224); //Main CPU m68000_0:=cpu_m68000.create(12000000,256); m68000_0.change_ram16_calls(bionicc_getword,bionicc_putword); //Sound CPU z80_0:=cpu_z80.create(3579545,256); z80_0.change_ram_calls(bionicc_snd_getbyte,bionicc_snd_putbyte); z80_0.init_sound(bionicc_sound_update); //Sound Chips ym2151_0:=ym2151_chip.create(3579545); //cargar roms if not(roms_load16w(@rom,bionicc_rom)) then exit; //cargar sonido if not(roms_load(@mem_snd,bionicc_sound)) then exit; //MCU mcs51_0:=cpu_mcs51.create(6000000,256); mcs51_0.change_io_calls(nil,in_port1,nil,nil,nil,out_port1,nil,out_port3); mcs51_0.change_ram_calls(mcu_ext_ram_read,mcu_ext_ram_write); if not(roms_load(mcs51_0.get_rom_addr,bionicc_mcu)) then exit; //convertir chars if not(roms_load(@memoria_temp,bionicc_char)) then exit; init_gfx(0,8,8,1024); gfx[0].trans[3]:=true; gfx_set_desc_data(2,0,128,4,0); convert_gfx(0,0,@memoria_temp,@pf_x,@pf_y,false,false); //convertir bg if not(roms_load(@memoria_temp,bionicc_bg)) then exit; init_gfx(1,8,8,2048); gfx[1].trans[15]:=true; gfx_set_desc_data(4,0,128,($8000*8)+4,$8000*8,4,0); convert_gfx(1,0,@memoria_temp,@pf_x,@pf_y,false,false); //convertir fg if not(roms_load(@memoria_temp,bionicc_fg)) then exit; init_gfx(2,16,16,2048); gfx[2].trans_alt[0,15]:=true; gfx[2].trans_alt[1,1]:=true; gfx[2].trans_alt[1,2]:=true; gfx[2].trans_alt[1,3]:=true; gfx[2].trans_alt[1,4]:=true; gfx[2].trans_alt[1,5]:=true; gfx[2].trans_alt[1,15]:=true; gfx_set_desc_data(4,0,512,($20000*8)+4,$20000*8,4,0); convert_gfx(2,0,@memoria_temp,@pf_x,@pf_y,false,false); //convertir sprites if not(roms_load(@memoria_temp,bionicc_sprites)) then exit; init_gfx(3,16,16,2048); gfx[3].trans[15]:=true; gfx_set_desc_data(4,0,256,$30000*8,$20000*8,$10000*8,0); convert_gfx(3,0,@memoria_temp,@ps_x,@ps_y,false,false); //DIP marcade.dswa:=$dfff; marcade.dswa_val:=@bionicc_dip; //final reset_bionicc; iniciar_bionicc:=true; end; end.
//Exercício 3: Escreva um algoritmo que receba uma temperatura em graus celsius e coverta-a para graus Farenheit. // Exibir as duas temperaturas. Fórmula : Tf = (9/5) * Tc + 32. { Solução em Portugol Algoritmo Exercicio3; //Tc = temperatura em celsius Var //Tf = temperatura em farenheit Tf,Tc : real Inicio exiba('Programa que converte temperaturas de Celsius para Farenheit.'); exiba('Digite uma temperatura em celsius: '); leia(Tc); Tf <- (9/5) * Tc + 32; exiba(Tc,' º celsius é equivalente a ' ,Tf,' º farenheit.'); Fim. } // Solução em Pascal Program Exercicio; uses crt; var Tf,Tc : real; begin clrscr; // Esse comando limpa a tela do terminal que abre quando executamos o programa. writeln('Programa que converte temperaturas de Celsius para Farenheit.'); writeln('Digite uma temperatura em celsius: '); readln(Tc); Tf := (9/5) * Tc + 32; writeln(Tc,' º celsius é equivalente a ' ,Tf,' º farenheit.'); repeat until keypressed; end.
unit EmailOrdering.Models.Config; interface uses REST.Json, DCPcrypt2, IdSMTP, DCPsha1, DCPrc4; type /// config file for storing information related to this application /// password in encypted using the below key and the DCPcrypt2 library TConfig = class private FsmtpPort: Word; FsmtpPassword: string; FsmtpUsername: string; FsmtpAuthType: string; FsmtpHost: string; FmemberNumber: string; FrequestAcceptCharset: string; FrequestResource: string; FrequestBaseUrl: string; FrequestAccept: string; FapiKey: string; FrequestConfirmationURL: string; FserverPort: string; procedure SetsmtpHost(const Value: string); procedure SetsmtpPassword(const Value: string); procedure SetsmtpPort(const Value: Word); procedure SetsmtpUsername(const Value: string); function GetsmtpPassword: string; procedure SetmemberNumber(const Value: string); procedure SetrequestAccept(const Value: string); procedure SetrequestAcceptCharset(const Value: string); procedure SetrequestBaseUrl(const Value: string); procedure SetrequestResource(const Value: string); procedure SetapiKey(const Value: string); procedure SetrequestConfirmationURL(const Value: string); procedure SetserverPort(const Value: string); public property requestBaseUrl: string read FrequestBaseUrl write SetrequestBaseUrl; property requestAccept: string read FrequestAccept write SetrequestAccept; property requestAcceptCharset: string read FrequestAcceptCharset write SetrequestAcceptCharset; property requestResource: string read FrequestResource write SetrequestResource; property requestConfirmationURL: string read FrequestConfirmationURL write SetrequestConfirmationURL; property smtpHost: string read FsmtpHost write SetsmtpHost; property smtpPort: Word read FsmtpPort write SetsmtpPort; property smtpAuthType: string read FsmtpAuthType write FsmtpAuthType; property smtpUsername: string read FsmtpUsername write SetsmtpUsername; property smtpPassword: string read GetsmtpPassword write SetsmtpPassword; property memberNumber: string read FmemberNumber write SetmemberNumber; property apiKey: string read FapiKey write SetapiKey; property serverPort: string read FserverPort write SetserverPort; function GetAuthType: IdSMTP.TIdSMTPAuthenticationType; function GetPasswordAst(): string; procedure Save; class function GetInstance : TConfig; static; class function Decrypt(value: string): string; static; class function Encrypt(value: string): string; static; end; implementation uses System.JSON, System.SysUtils, EmailOrdering.Models.ConfigKey, EmailOrdering.SharedData, System.IOUtils; { TConfig } class function TConfig.Encrypt(value: string): string; var Cipher: TDCP_rc4; begin Cipher:= TDCP_rc4.Create(nil); Cipher.InitStr(TConfigKey.Value,TDCP_sha1); Result := Cipher.EncryptString(value); Cipher.Burn; Cipher.Free; end; function TConfig.GetsmtpPassword: string; begin if (self.FsmtpPassword = '') then raise Exception.Create('Password is blank'); Result := TConfig.Decrypt(self.FsmtpPassword); end; function TConfig.GetAuthType: IdSMTP.TIdSMTPAuthenticationType; begin if self.FsmtpAuthType = 'satNone' then Result:= TIdSMTPAuthenticationType.satNone else if self.FsmtpAuthType = 'satDefault' then Result:= TIdSMTPAuthenticationType.satDefault else if self.FsmtpAuthType = 'satSASL' then Result:= TIdSMTPAuthenticationType.satSASL else Result:= TIdSMTPAuthenticationType.satNone; end; class function TConfig.Decrypt(value: string): string; var Cipher: TDCP_rc4; begin Cipher:= TDCP_rc4.Create(nil); Cipher.InitStr(TConfigKey.Value,TDCP_sha1); // initialize the cipher with a hash of the passphrase Result := Cipher.DecryptString(value); Cipher.Burn; Cipher.Free; end; class function TConfig.GetInstance : TConfig; begin if fileexists(TSharedData.ConfigFilePath) then begin Result := TJson.JsonToObject<TConfig>(TFile.ReadAllText(TSharedData.ConfigFilePath)); exit; end; Result:= TConfig.Create; //set default values Result.requestBaseUrl:= 'http://10.1.1.15:7778'; Result.requestAccept:= 'application/json'; Result.requestAcceptCharset := ''; Result.requestResource := 'api/orders'; Result.requestConfirmationURL := 'http://10.1.1.15:7778/orders/confirmation/'; end; procedure TConfig.Save; begin forcedirectories(System.SysUtils.ExtractFilePath(TSharedData.ConfigFilePath)); TFile.WriteAllText(TSharedData.ConfigFilePath, TJson.ObjectToJsonString(self)); end; function TConfig.GetPasswordAst(): string; var I: Integer; begin Result:= ''; for I := 0 to self.smtpPassword.Length - 1 do Result:= Result + '*'; end; {$region 'Getters and Setters'} procedure TConfig.SetserverPort(const Value: string); begin FserverPort := Value; end; procedure TConfig.SetsmtpHost(const Value: string); begin FsmtpHost := Value; end; procedure TConfig.SetapiKey(const Value: string); begin FapiKey := Value; end; procedure TConfig.SetmemberNumber(const Value: string); begin FmemberNumber := Value; end; procedure TConfig.SetrequestAccept(const Value: string); begin FrequestAccept := Value; end; procedure TConfig.SetrequestAcceptCharset(const Value: string); begin FrequestAcceptCharset := Value; end; procedure TConfig.SetrequestBaseUrl(const Value: string); begin FrequestBaseUrl := Value; end; procedure TConfig.SetrequestConfirmationURL(const Value: string); begin FrequestConfirmationURL := Value; end; procedure TConfig.SetrequestResource(const Value: string); begin FrequestResource := Value; end; procedure TConfig.SetsmtpPassword(const Value: string); begin FsmtpPassword := TConfig.Encrypt(Value); end; procedure TConfig.SetsmtpPort(const Value: Word); begin FsmtpPort := Value; end; procedure TConfig.SetsmtpUsername(const Value: string); begin FsmtpUsername := Value; end; {$endregion} end.
{==============================================================================} { } { Multicast event handling class } { } { ©František Milt 2014-05-07 } { } { Version 1.0.2 } { } {==============================================================================} unit MulticastEvent; interface uses Classes; type PMethod = ^TMethod; TEvent = procedure of object; {==============================================================================} {--- TMulticastEvent declaration ----------------------------------------------} {==============================================================================} TMulticastEvent = class(TObject) private fOwner: TObject; fMethods: TList; Function GetMethods(Index: Integer): TMethod; Function GetMethodsCount: Integer; protected public constructor Create(aOwner: TObject = nil); destructor Destroy; override; Function IndexOf(const Handler: TEvent): Integer; virtual; Function Add(const Handler: TEvent; AllowDuplicity: Boolean = False): Integer; virtual; Function Remove(const Handler: TEvent; RemoveAll: Boolean = True): Integer; virtual; procedure Delete(Index: Integer); virtual; procedure Clear; virtual; procedure Call; virtual; property Methods[Index: Integer]: TMethod read GetMethods; published property Owner: TObject read fOwner; property Count: Integer read GetMethodsCount; end; {==============================================================================} {--- TMulticastNotifyEvent declaration ----------------------------------------} {==============================================================================} TMulticastNotifyEvent = class(TMulticastEvent) public Function IndexOf(const Handler: TNotifyEvent): Integer; reintroduce; Function Add(const Handler: TNotifyEvent; AllowDuplicity: Boolean = False): Integer; reintroduce; Function Remove(const Handler: TNotifyEvent; RemoveAll: Boolean = True): Integer; reintroduce; procedure Call(Sender: TObject); reintroduce; end; implementation {==============================================================================} {--- TMulticastEvent implementation -------------------------------------------} {==============================================================================} {=== TMulticastEvent // Private routines ======================================} Function TMulticastEvent.GetMethods(Index: Integer): TMethod; begin Result := TMethod(fMethods[Index]^); end; //------------------------------------------------------------------------------ Function TMulticastEvent.GetMethodsCount: Integer; begin Result := fMethods.Count; end; {=== TMulticastEvent // Public routines =======================================} constructor TMulticastEvent.Create(aOwner: TObject = nil); begin inherited Create; fOwner := aOwner; fMethods := TList.Create; end; //------------------------------------------------------------------------------ destructor TMulticastEvent.Destroy; begin Clear; fMethods.Free; inherited; end; //------------------------------------------------------------------------------ Function TMulticastEvent.IndexOf(const Handler: TEvent): Integer; begin For Result := 0 to Pred(fMethods.Count) do If (PMethod(fMethods[Result])^.Code = TMethod(Handler).Code) and (PMethod(fMethods[Result])^.Data = TMethod(Handler).Data) then Exit; Result := -1; end; //------------------------------------------------------------------------------ Function TMulticastEvent.Add(const Handler: TEvent; AllowDuplicity: Boolean = False): Integer; var NewItem: PMethod; begin If Assigned(TMethod(Handler).Code) and Assigned(TMethod(Handler).Data) then begin Result := IndexOf(Handler); If (Result < 0) or AllowDuplicity then begin New(NewItem); NewItem^.Code := TMethod(Handler).Code; NewItem^.Data := TMethod(Handler).Data; Result := fMethods.Add(NewItem); end; end else Result := -1; end; //------------------------------------------------------------------------------ Function TMulticastEvent.Remove(const Handler: TEvent; RemoveAll: Boolean = True): Integer; begin repeat Result := IndexOf(Handler); If Result >= 0 then Delete(Result); until not RemoveAll or (Result < 0); end; //------------------------------------------------------------------------------ procedure TMulticastEvent.Delete(Index: Integer); begin Dispose(PMethod(fMethods[Index])); fMethods.Delete(Index); end; //------------------------------------------------------------------------------ procedure TMulticastEvent.Clear; var i: Integer; begin For i := 0 to Pred(fMethods.Count) do Dispose(PMethod(fMethods[i])); fMethods.Clear; end; //------------------------------------------------------------------------------ procedure TMulticastEvent.Call; var i: Integer; begin For i := 0 to Pred(fMethods.Count) do TEvent(fMethods[i]^); end; {==============================================================================} {--- TMulticastNotifyEvent implementation -------------------------------------} {==============================================================================} {=== TMulticastNotifyEvent // Public routines =================================} Function TMulticastNotifyEvent.IndexOf(const Handler: TNotifyEvent): Integer; begin Result := inherited IndexOf(TEvent(Handler)); end; //------------------------------------------------------------------------------ Function TMulticastNotifyEvent.Add(const Handler: TNotifyEvent; AllowDuplicity: Boolean = False): Integer; begin Result := inherited Add(TEvent(Handler),AllowDuplicity); end; //------------------------------------------------------------------------------ Function TMulticastNotifyEvent.Remove(const Handler: TNotifyEvent; RemoveAll: Boolean = True): Integer; begin Result := inherited Remove(TEvent(Handler),RemoveAll); end; //------------------------------------------------------------------------------ procedure TMulticastNotifyEvent.Call(Sender: TObject); var i: Integer; begin For i := 0 to Pred(Count) do TNotifyEvent(Methods[i])(Sender); end; end.
unit fmuFont; interface uses // VCL ComCtrls, StdCtrls, Controls, Classes, SysUtils, Graphics, // This untPages, untUtil, untDriver, Spin; type { TfmFont } TfmFont = class(TPage) Memo: TMemo; btnGetFontMetrics: TButton; lblFontType: TLabel; btnGetFontsMetrics: TButton; seFontType: TSpinEdit; procedure btnGetFontMetricsClick(Sender: TObject); procedure btnGetFontsMetricsClick(Sender: TObject); private procedure AddLine(V1, V2: Variant); procedure AddLineWidth(V1, V2: Variant; TextWidth: Integer); end; implementation {$R *.DFM} { TfmFont } procedure TfmFont.AddLineWidth(V1, V2: Variant; TextWidth: Integer); begin Memo.Lines.Add(Format(' %-*s: %s', [TextWidth, String(V1), String(V2)])); end; procedure TfmFont.AddLine(V1, V2: Variant); begin AddLineWidth(V1, V2, 24); end; procedure TfmFont.btnGetFontMetricsClick(Sender: TObject); var CharCount: Integer; begin EnableButtons(False); try Memo.Clear; Driver.FontType := seFontType.Value; if Driver.GetFontMetrics = 0 then begin Memo.Lines.Add(''); AddLine('Ширина печати в точках', Driver.PrintWidth); AddLine('Ширина символа в точках', Driver.CharWidth); AddLine('Высота символа в точках', Driver.CharHeight); AddLine('Количество шрифтов', Driver.FontCount); if Driver.CharWidth > 0 then begin CharCount := Trunc(Driver.PrintWidth/Driver.CharWidth); AddLine('Символов в строке', CharCount); end; end; finally EnableButtons(True); end; end; procedure TfmFont.btnGetFontsMetricsClick(Sender: TObject); var i: Integer; Count: Integer; CharCount: Integer; begin EnableButtons(False); Memo.Lines.BeginUpdate; try Memo.Clear; // Шрифт 1 есть всегда Driver.FontType := 1; if Driver.GetFontMetrics = 0 then begin Memo.Lines.Add(''); AddLine('Количество шрифтов', Driver.FontCount); Count := Driver.FontCount; for i := 1 to Count do begin Driver.FontType := i; if Driver.GetFontMetrics <> 0 then Break; Memo.Lines.Add(' ' + StringOfChar('-', 33)); AddLine('Номер шрифта', i); AddLine('Ширина печати в точках', Driver.PrintWidth); AddLine('Ширина символа в точках', Driver.CharWidth); AddLine('Высота символа в точках', Driver.CharHeight); if Driver.CharWidth > 0 then begin CharCount := Trunc(Driver.PrintWidth/Driver.CharWidth); AddLine('Символов в строке', CharCount); end; end; end; // Прокручиваем Memo на начало Memo.SelStart := 0; Memo.SelLength := 0; finally EnableButtons(True); Memo.Lines.EndUpdate; end; end; end.
unit Unbound.GameState.Playing; interface uses Pengine.Color, Unbound.GameState, Unbound.Game, Unbound.Game.Renderer, Unbound.Game.Serialization, Unbound.Game.WorldFeatures; type TGameStatePlaying = class(TGameState) private FGame: TGame; FRenderer: TGameRenderer; protected procedure DoLoad; override; procedure DoUnload; override; public procedure Render; override; end; implementation { TGameStatePlaying } procedure TGameStatePlaying.DoLoad; var TestGamePack: TGamePackEditable; UBSMap: TUBSMap; Material: TTerrainMaterialEditable; WorldGenerator: TWorldGeneratorEditable; Feature: TWorldFeatureHeightmapEditable; Noise: TNoise2Editable; begin Material := TTerrainMaterialEditable.Create; Material.SetColor(ColorRGB(1, 0, 1)); Noise := TNoise2Editable.Create; Noise.SetSeed(42); Feature := TWorldFeatureHeightmapEditable.Create; Feature.AddNoise(Noise); WorldGenerator := TWorldGeneratorEditable.Create; WorldGenerator.AddFeature(Feature); TestGamePack := TGamePackEditable.Create; TestGamePack.SetName('Test'); TestGamePack.GenerateNewGUID; TestGamePack.AddMaterial(Material); TestGamePack.AddWorldGenerator(WorldGenerator); FGame := TGame.Create; FGame.AddGamePack(TestGamePack); WorldGenerator.Free; Feature.Free; Material.Free; Noise.Free; TestGamePack.Free; FRenderer := TGameRenderer.Create(FGame); end; procedure TGameStatePlaying.DoUnload; begin FRenderer.Free; FGame.Free; end; procedure TGameStatePlaying.Render; begin FRenderer.Camera.Render; end; end.
unit UnitSimpleBankServerTests; interface uses DUnitX.TestFramework, UnitSimpleBank; type [TestFixture] TSimpleBankServerTests = class public [Test] procedure TestCreateAccount; [Test] [TestCase('Test Normal Deposit','500,600')] [TestCase('Test Negative Deposit','500,-600')] procedure TestDeposit(const InitDeposit : Currency; const DepositAmount: Currency); [Test] [TestCase('TestNormalDrawing','500,300')] [TestCase('TestOverDrawing','500,600')] procedure TestWithDraw(const InitDeposit : Currency; const WithDrawAmount: Currency); [Test] procedure TestMiniStatement; end; implementation uses SysUtils; procedure TSimpleBankServerTests.TestCreateAccount; var Expected : String; Actual : String; aSimpleBank : TSimpleBank; anAccount : IAccount; begin //Arrange Expected := 'Steven'+FloatToStrF(100, ffCurrency,4,2); aSimpleBank := TSimpleBank.Create; try //Act anAccount := TAccount.Create('Steven',100); aSimpleBank.CreateAccount(anAccount); actual := aSimpleBank.AccountName+ FloatToStrF(aSimpleBank.Balance, ffCurrency,4,2); //Assert Assert.AreEqual(Expected, actual, 'Simple Bank Create Account unsuccessful' ); finally aSimpleBank.Free; end; end; procedure TSimpleBankServerTests.TestDeposit(const InitDeposit : Currency; const DepositAmount: Currency); var Expected: Currency; Actual: Currency; aSimpleBank : TSimpleBank; anAccount : IAccount; begin aSimpleBank := TSimpleBank.Create; try anAccount := TAccount.Create('Steven',InitDeposit); aSimpleBank.CreateAccount(anAccount); //Arrange Expected := InitDeposit + DepositAmount; //Act aSimpleBank.Deposit(DepositAmount); Actual := aSimpleBank.Balance; //Assert Assert.AreEqual(Expected, Actual, 'aSimpleBank Deposit unsuccessful'); finally aSimpleBank.Free; end; end; procedure TSimpleBankServerTests.TestWithDraw(const InitDeposit : Currency; const WithDrawAmount: Currency); var Expected: Currency; Actual: Currency; aSimpleBank : TSimpleBank; anAccount : IAccount; begin aSimpleBank := TSimpleBank.Create; try anAccount := TAccount.Create('Steven',InitDeposit); aSimpleBank.CreateAccount(anAccount); //Arrange Expected := InitDeposit - WithDrawAmount; //Act aSimpleBank.WithDraw(WithDrawAmount); Actual := aSimpleBank.Balance; //Assert Assert.AreEqual(Expected, Actual, 'aSimpleBank WithDraw unsuccessful'); finally aSimpleBank.Free; end; end; procedure TSimpleBankServerTests.TestMiniStatement; var Expected: Integer; Actual: Integer; aSimpleBank : TSimpleBank; anAccount : IAccount; begin //Arrange Expected := 5; aSimpleBank := TSimpleBank.Create; try //Act anAccount := TAccount.Create('Steven',1000); aSimpleBank.CreateAccount(anAccount); aSimpleBank.Deposit(268); aSimpleBank.Deposit(380); aSimpleBank.WithDraw(525); Actual := aSimpleBank.PrintMiniStatement; //Assert Assert.AreEqual(Expected, Actual, 'aSimpleBank MiniStatement unsuccessful'); finally aSimpleBank.Free; end; end; initialization TDUnitX.RegisterTestFixture(TSimpleBankServerTests); end.
unit PatchMemory; Interface uses Windows, ImageHlp, SysUtils; var BasePointer: pointer; type TPatchMemory = Class Debug: Boolean; //Отладочная печать DllNameToPatch: String; //Имя DLL, в секции импорта которой будем производить изменения DllNameToFind: String; //Имя DLL, функцию которой мы хотим перехватить (например, 'KERNEL32.dll') FuncNameToFind: String; //Функция, которую мы хотим перехватить (например, 'CreateProcessA') NewFunctionAddr: Pointer; //Адрес функции - заменителя OldFunctionAddr: Pointer; //Старый адрес замещенной функции function Patch():Boolean; //Выполняет замену стандартной функции на нашу procedure UnPatch; //Отменяет патчинг Constructor Create; Destructor Destroy; Override; private AddrWherePatching: Pointer; //Для UnPatch function GetDwordByRVA(rva: dword):dword; function GetStringByRVA(rva: dword):pchar; function GetPointerByRVA(rva: DWORD):Pointer; function GetRVAByPointer(P: Pointer):DWORD; procedure WriteDwordToMemory(Kuda: Pointer; Data: DWORD); function GetDwordFromMemory(addr: Pointer):DWORD; // function GetPointerFromAddr(addr: DWORD):Pointer; procedure say(s:String); end; ////////////////////////////////////////////////////////// implementation ////////////////////////////////////////////////////////// procedure TPatchMemory.say(s:String); //Отладочная печать begin if Debug then MessageBox(0,pchar(s),'',0); end; ////////////////////////////////////////////////////////////// Constructor TPatchMemory.Create; begin inherited Create; debug:=False; end; ////////////////////////////////////////////////////////////// destructor TPatchMemory.Destroy; begin say('Destroy'); inherited Destroy; end; ////////////////////////////////////////////////// function TPatchMemory.GetDwordByRVA(rva: dword):dword; //Получает значение (4 байтовое целое без знака - DWORD) из памяти по //смещению (RVA) begin asm push ebx; mov ebx, [rva]; add ebx, [BasePointer]; mov eax, [ebx]; mov Result, eax; pop ebx; end; end; ////////////////////////////////////////////////// function TPatchMemory.GetStringByRVA(rva: dword):pchar; //Получает строку по указателю RVA begin asm mov eax, [rva]; add eax, [BasePointer]; mov Result, eax; end; end; ////////////////////////////////////////////////// function TPatchMemory.GetPointerByRVA(rva: DWORD):Pointer; //Получает указатель из RVA (т.е. прибавляет к rva значение BasePointer) begin asm mov eax, rva; add eax, [BasePointer]; mov Result, eax; end; end; ////////////////////////////////////////////////// function TPatchMemory.GetDwordFromMemory(addr: Pointer):DWORD; begin asm push ebx; mov ebx, [addr]; mov eax, [ebx]; mov Result, eax; pop ebx; end; end; ////////////////////////////////////////////////// function TPatchMemory.GetRVAByPointer(P: Pointer):DWORD; //Получает указатель RVA из указателя //(т.е. вычитает из указателя значение BasePointer) begin asm mov eax, [p]; sub eax, BasePointer; mov Result, eax; end; end; ////////////////////////////////////////////////// Procedure TPatchMemory.WriteDwordToMemory( //Пишем 4 байта в память по указателю. Kuda: Pointer; //Адрес куда пишем Data: DWORD //Значение которое пишем ); var BytesWritten: DWORD; var hProcess: THandle; var old: DWORD; begin hProcess := Windows.GetCurrentProcess(); //Разрешаем доступ на запись по указанному адресу Windows.VirtualProtect(//Функция WinAPI kuda, //адрес 4, //число байт (будут затронуты 1 или 2 страницы памяти размером 4К) PAGE_EXECUTE_READWRITE, //атрибуты доступа @old); //сюда будут возвращены старые атрибуты BytesWritten:=0; //Записываем 4 байта Windows.WriteProcessMemory(//Функция WinAPI hProcess, kuda, @data, 4, BytesWritten); //Восстанавливаем прежние атрибуты доступа Windows.VirtualProtect(//Функция WinAPI kuda, 4, old, @old); end; ////////////////////////////////////////////////////////// function TPatchMemory.Patch():boolean; var ulSize: ULONG; var rva: DWORD; var ImportTableOffset: pointer; var OffsetDllName: DWORD; var OffsetFuncAddrs: DWORD; var FunctionAddr: DWORD; var DllName: String; //var FuncAddrToFind: DWORD; var OffsetFuncNames: DWORD; var pFuncName: pchar; var dFuncName: DWORD; var nFuncName: Integer; var nFuncAddr: Integer; var ok: Integer; begin Result:=False; //В Windows 2000 DLL в этот момент, возможно, еще не загружена if DWORD(GetModuleHandle(pchar(DllNameToPatch)))=0 then begin LoadLibrary(pchar(DllNameToPatch)); end; //Получаем адрес функции, который мы хотим найти в таблице IAT say(DllNameToFind+' '+FuncNameToFind); (* FuncAddrToFind:= DWORD( GetProcAddress(//Функция Windows API GetModuleHandle(//Функция Windows API pchar(DllNameToFind) ), pchar(FuncNameToFind) )); *) // say('FuncAddrToFind: '+IntToHex(FuncAddrToFind,8)); // OldFunctionAddr:=Pointer(FuncAddrToFind); //Получаем адрес, по которому расположена в памяти dll - "жертва". BasePointer:=pointer(GetModuleHandle(//Функция Windows API pChar(DllNameToPatch))); //Получаем смещение таблицы импорта ImportTableOffset:= ImageDirectoryEntryToData( //Функция Windows API BasePointer, TRUE, IMAGE_DIRECTORY_ENTRY_IMPORT, ulSize); //Переводим смещение таблицы импорта в формат RVA //(смещение относительно начала DLL) rva:=GetRvaByPointer(ImportTableOffset); repeat {Проходим по таблице импорта. Каждая запись в таблице импорта имеет длину 20 байт: +0 - указатель на таблицу имен функций +4 - ? +8 - ? +12 - Указатель (RVA) на имя DLL +16 - указатель на таблицу адресов функций } OffsetDllName := GetDwordByRVA(rva+12); if OffsetDllName = 0 then break; //Если таблица кончилась, выходим DllName := GetStringByRVA(OffsetDllName);//Имя DLL if LowerCase(Trim(DllName))=LowerCase(Trim(DllNameToFind)) then begin OffsetFuncNames:=GetDwordByRVA(rva+0); //Таблица имен функций //if LowerCase(DllNameToPatch)='dbeng32.dll' then //MessageBox(0, pchar(IntToHex(OffsetFuncNames,8)), pchar(DllNameToFind+' '+DllNameToPatch+' '+FuncNameToFind), 0); nFuncName:=0; ok:=0; repeat //Цикл по списку имен функций DLL dFuncName:=GetDwordByRva(OffsetFuncNames); if dFuncName=0 then break; inc(nFuncName); pFuncName:=GetStringByRva(dFuncName); inc(pFuncName,2); //if debug then //MessageBox(0, pchar(IntToHex(GetDwordByRva(OffsetFuncNames),8)), pchar(DllNameToFind+' '+DllNameToPatch+' '+FuncNameToFind), 0); //MessageBox(0, pFuncName, pchar(DllNameToFind+' '+DllNameToPatch+' '+FuncNameToFind), 0); if LowerCase(Trim(''+pFuncName))=LowerCase(Trim(FuncNameToFind)) then begin ok:=1; break; //нашли end; inc(OffsetFuncNames,4); until False; if ok=1 then begin OffsetFuncAddrs:=GetDwordByRva(rva+16); nFuncAddr:=0; repeat //Цикл по списку функций DLL FunctionAddr:=Dword(GetDwordByRva(OffsetFuncAddrs)); if FunctionAddr=0 then break; //Если функции закончились, выходим inc(nFuncAddr); //if (FunctionAddr=FuncAddrToFind) then begin if nFuncAddr=nFuncName then begin //Нашли - выполняем патч AddrWherePatching:=GetPointerByRva(OffsetFuncAddrs); say('AddrWherePatching: '+IntToHex(Dword(AddrWherePatching),8)); OldFunctionAddr:=Pointer(GetDwordFromMemory(AddrWherePatching)); Result:=True; // MessageBox(0, pchar(IntToHex(Dword(OldFunctionAddr), 8)), // pchar(DllNameToPatch+' '+FuncNameToFind+' sleep_dbf'), 0); //OldFunctionAddr:=OldFunctionAddr1; WriteDwordToMemory( AddrWherePatching, DWORD(NewFunctionAddr)); say('AddrWherePatching: '+IntToHex(Dword(AddrWherePatching),8)); end; inc(OffsetFuncAddrs,4); until false; end; end; rva:=rva+20; until false; end; ////////////////////////////////////////////////////////// procedure TPatchMemory.UnPatch; begin say('AddrWherePatching: '+IntToHex(Dword(AddrWherePatching),8)); say('OldFunctionAddr: '+IntToHex(Dword(OldFunctionAddr),8)); WriteDwordToMemory( AddrWherePatching, DWORD(OldFunctionAddr)); end; end.
unit uMain; {$mode delphi}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, {$IFDEF FPC} registry, {$ENDIF} Quick.Config.Json, Generics.Collections; type TMyPriority = (msLow, msMed, msHigh); TWinPos = class private fPosX : Integer; fPosY : Integer; published property PosX : Integer read fPosX write fPosX; property PosY : Integer read fPosY write fPosY; end; TProcessType = class private fId : Integer; fPriority : TMyPriority; fRedundant : Boolean; published property Id : Integer read fId write fId; property Priority : TMyPriority read fPriority write fPriority; property Redundant : Boolean read fRedundant write fRedundant; end; TWorker = class private fName : string; fActive : Boolean; published property Name : string read fName write fName; property Active : Boolean read fActive write fActive; end; TMyConfig2 = class(TAppConfigJson) private fhola : Integer; published property hola : Integer read fhola write fhola; end; TArraySizes = array of Integer; TArrayHistory = array of TProcessType; TMyConfig = class(TAppConfigJson) private fTitle : string; fHidden : Boolean; fSessionName: string; fSizes : TArraySizes; fLastFilename : string; fWindowPos : TWinPos; fHistory : TArrayHistory; fComplex : TProcessType; fModifyDate : TDateTime; //fWorkList : TObjectList<TWorker>; public procedure Init; destructor Destroy; override; procedure DefaultValues; override; property Hidden : Boolean read fHidden write fHidden; published property Title : string read fTitle write fTitle; property SessionName : string read fSessionName write fSessionName; property Sizes : TArraySizes read fSizes write fSizes; property LastFilename : string read fLastFilename write fLastFilename; property WindowPos : TWinPos read fWindowPos write fWindowPos; property History : TArrayHistory read fHistory write fHistory; property Complex : TProcessType read fComplex write fComplex; property ModifyDate : TDateTime read fModifyDate write fModifyDate; //property WorkList : TObjectList<TWorker> read fWorkList write fWorkList; end; { TForm1 } TForm1 = class(TForm) btnSaveJson: TButton; btnLoadJson: TButton; meInfo: TMemo; procedure btnLoadJsonClick(Sender: TObject); procedure btnSaveJsonClick(Sender: TObject); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure FormCreate(Sender: TObject); procedure OnConfigFileModified; private public procedure SetConfig(cConfig: TMyConfig); function TestConfig(cConfig1, cConfig2 : TMyConfig) : Boolean; end; var Form1: TForm1; ConfigJson : TMyConfig; ConfigTest : TMyConfig; implementation {$R *.lfm} uses Quick.Json.Serializer; { TForm1 } procedure TForm1.btnSaveJsonClick(Sender: TObject); begin SetConfig(ConfigJson); ConfigJson.Save; meInfo.Lines.Add(ConfigJson.ToJson); meInfo.Lines.Add('Saved Config in Json at ' + DateTimeToStr(ConfigJson.LastSaved)); end; procedure TForm1.btnLoadJsonClick(Sender: TObject); begin meInfo.Lines.Add('Load ConfigJson'); ConfigJson.Load; meInfo.Lines.Add(ConfigJson.ToJSON); if TestConfig(ConfigTest,ConfigJson) then meInfo.Lines.Add('Test passed successfully!'); end; function TForm1.TestConfig(cConfig1, cConfig2 : TMyConfig) : Boolean; var i : Integer; begin 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); //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 TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin if Assigned(ConfigTest) then ConfigTest.Free; if Assigned(ConfigJson) then ConfigJson.Free; end; procedure TForm1.FormCreate(Sender: TObject); begin ConfigTest := TMyConfig.Create(''); SetConfig(ConfigTest); ConfigJson := TMyConfig.Create('.\Config.json'); ConfigJson.Provider.CreateIfNotExists := True; ConfigJson.Provider.ReloadIfFileChanged := True; ConfigJson.Provider.OnFileModified := OnConfigFileModified; end; procedure TForm1.OnConfigFileModified; begin meInfo.Lines.Add('Config file modified'); end; procedure TForm1.SetConfig(cConfig: TMyConfig); var processtype : TProcessType; begin cConfig.Title := 'hola'; cConfig.SessionName := 'Session01'; cConfig.LastFileName := 'C:\library.txt'; cConfig.Sizes := [1,2,3,4,5,6,7]; cConfig.Complex := TProcessType.Create; cConfig.Complex.Id := 1; cConfig.Complex.Redundant := True; cConfig.Complex.Priority := TMyPriority.msMed; cConfig.WindowPos := TWinPos.Create; cConfig.WindowPos.PosX := 100; cConfig.WindowPos.PosY := 200; processtype := TProcessType.Create; processtype.Id := 1; processtype.Priority := msLow; processtype.Redundant := True; cConfig.History := [processtype]; cConfig.ModifyDate := Now(); end; { TMyConfig } procedure TMyConfig.Init; begin inherited; //WorkList := TObjectList<TWorker>.Create(True); DefaultValues; end; procedure TMyConfig.DefaultValues; begin fTitle := 'Default value'; end; destructor TMyConfig.Destroy; begin //if Assigned(WorkList) then WorkList.Free; inherited; end; end.
{!DOCTOPIC}{ Math module } {!DOCREF} { @method: var Math = TObjMath; @desc: This module provides you with a few math-related functions. } {======| Table of contents |====================================================] function TObjMath.Modulo(X,Y:Extended): Extended; overload; function TObjMath.Modulo(X,Y:Int32): Int32; overload; function TObjMath.Sign(X:Int32): Int8; overload; function TObjMath.Sign(X:Int64): Int8; overload; function TObjMath.Sign(X:Single): Int8; overload; function TObjMath.Sign(X:Double): Int8; overload; function TObjMath.Sign(X:Extended): Int8; overload; function TObjMath.DeltaAngle(x,y:Extended): Extended; function TObjMath.DistManhattan(pt1,pt2: TPoint): Extended; function TObjMath.DistEuclidean(pt1,pt2: TPoint): Extended; function TObjMath.DistChebyshev(pt1,pt2: TPoint): Extended; function TObjMath.DistQuasiEuclidean(pt1,pt2: TPoint): Extended; function TObjMath.DistToLine(Pt,sA,sB:TPoint): Extended; function TObjMath.InCircle(const Pt, Center: TPoint; Radius: Integer): Boolean; function TObjMath.InEllipse(const Pt,Center:TPoint; YRad, XRad: Integer): Boolean; function TObjMath.InRect(const Pt:TPoint; const A,B,C,D:TPoint): Boolean; function TObjMath.InPoly(x,y:Integer; const Poly:TPointArray): Boolean; function TObjMath.InPolyR(x,y:Integer; const Poly:TPointArray): Boolean; function TObjMath.InPolyW(x,y:Integer; const Poly:TPointArray): Boolean; (* Prime *) function TObjMath.IsPrime(n: Int64): Boolean; Inline; function TObjMath.NextPrime(n: Int64): Int64; inline; function TObjMath.PrevPrime(n: Int64): Int64; inline; (* Next power of two minus 1 *) function TObjMath.NextPow2m1(n:Int32): Int32; [===============================================================================} {!DOCREF} { @method: function Math.Modulo(X,Y:Extended): Extended; overload; @desc: "Real" modulus function as seen in: WolframAlpha, MatLab and Python, and many more "modern" programming languages. } function TObjMath.Modulo(X,Y:Extended): Extended; overload; begin Result := exp_Modulo(X,Y); end; {!DOCREF} { @method: function Math.Modulo(X,Y:Int32): Int32; overload; @desc: "Real" modulus function as seen in: WolframAlpha, MatLab and Python, and many more "modern" programming languages. } function TObjMath.Modulo(X,Y:Int32): Int32; overload; begin Result := exp_IModulo(X,Y); end; {!DOCREF} { @method: function Math.Sign(X:Extended): Int8; @desc: Results: c'-1 if x < 0' || c'0 if x = 0' || c'1 if x > 0' } function TObjMath.Sign(X:Extended): uInt8; overload; begin if (x > 0) then Exit(1) else if (x < 0) then Exit(-1) else Exit(0); end; {!DOCREF} { @method: function Math.DistManhattan(pt1,pt2: TPoint): Extended; @desc: Computes the 'Manhattan distance' between the two given points 'pt1' and 'pt2' } function TObjMath.DistManhattan(pt1,pt2: TPoint): Extended; begin Result := exp_DistManhattan(pt1,pt2); end; {!DOCREF} { @method: function Math.DistEuclidean(pt1,pt2: TPoint): Extended; @desc: Computes the 'Euclidean distance' between the two given points 'pt1' and 'pt2' } function TObjMath.DistEuclidean(pt1,pt2: TPoint): Extended; begin Result := exp_DistEuclidean(pt1,pt2); end; {!DOCREF} { @method: function Math.DistChebyshev(pt1,pt2: TPoint): Extended; @desc: Computes the 'Chebyshev distance' between the two given points 'pt1' and 'pt2' } function TObjMath.DistChebyshev(pt1,pt2: TPoint): Extended; begin Result := exp_DistChebyshev(pt1,pt2); end; {!DOCREF} { @method: function Math.DistQuasiEuclidean(pt1,pt2: TPoint): Extended; @desc: Computes the distance between the two given points 'pt1' and 'pt2'. QuasiEuclidian is very similar to euclidean distance, but is cheaper to compute. "Result" is more in the shape of a octagon, then a circle. } function TObjMath.DistQuasiEuclidean(pt1,pt2: TPoint): Extended; begin Result := exp_DistOctagonal(pt1,pt2); end; {!DOCREF} { @method: function Math.DistToLine(Pt,sA,sB:TPoint): Extended; @desc: Calculates the distance from Point 'pt' to the line segment defined by 'sA->sB' } function TObjMath.DistToLine(Pt,sA,sB:TPoint): Extended; begin Result := exp_DistToLine(Pt,sA,sB); end; {!DOCREF} { @method: function Math.InCircle(const Pt, Center: TPoint; Radius: Integer): Boolean; @desc: Check if the point 'Pt' is within the given circle } function TObjMath.InCircle(const Pt, Center: TPoint; Radius: Integer): Boolean; begin Result := exp_InCircle(Pt, Center, Radius); end; {!DOCREF} { @method: function Math.InEllipse(const Pt,Center:TPoint; YRad, XRad: Integer): Boolean; @desc: Check if the point 'Pt' is within the given ellipse } function TObjMath.InEllipse(const Pt,Center:TPoint; YRad, XRad: Integer): Boolean; begin Result := exp_InEllipse(Pt, Center, YRad, XRad); end; {!DOCREF} { @method: function Math.InRect(const Pt:TPoint; const A,B,C,D:TPoint): Boolean; @desc: Checks if the point 'Pt' is within the given rectangle. } function TObjMath.InRect(const Pt:TPoint; const A,B,C,D:TPoint): Boolean; begin Result := exp_InRect(Pt, A,B,C,D); end; {!DOCREF} { @method: function Math.InPoly(x,y:Integer; const Poly:TPointArray): Boolean; @desc: Checks of the given point defined by 'x' and 'y' is within a polygon defined by 'Poly' } function TObjMath.InPoly(x,y:Integer; const Poly:TPointArray): Boolean; begin Result := exp_InPoly(x,y, poly); end; function TObjMath.InPolyR(x,y:Integer; const Poly:TPointArray): Boolean; begin Result := exp_InPolyR(x,y, poly); end; function TObjMath.InPolyW(x,y:Integer; const Poly:TPointArray): Boolean; begin Result := exp_InPolyW(x,y, poly); end; {!DOCREF} { @method: function Math.IsPrime(n: Int64): Boolean; Inline; @desc: Returns `True` if `n` is a prime number, otherwise it returns `False` } function TObjMath.IsPrime(n: Int64): Boolean; var i:Integer; Hi: Single; begin if (n = 2) then Exit(True); if (n and 2 = 0) or (n<=1) then Exit(False); Hi := Sqrt(n)+1; i := 3; while i <= Hi do begin if ((n mod i) = 0) then Exit(False); i := i + 2; end; Result := True; end; {!DOCREF} { @method: function Math.NextPrime(n: Int64): Int64; @desc: Returns the prime that comes next after the number `n`. } function TObjMath.NextPrime(n: Int64): Int64; begin Inc(n); while Not(IsPrime(n)) do Inc(n); Result := n; end; {!DOCREF} { @method: function Math.PrevPrime(n: Int64): Int64; @desc: Returns the prime before `n`. } function TObjMath.PrevPrime(n: Int64): Int64; begin Dec(n); while Not(IsPrime(n)) do Dec(n); Result := n; end; {!DOCREF} { @method: function Math.NextPow2m1(n:Int32): Int32; @desc: Returns the next power of two minus 1, very quick! } function TObjMath.NextPow2m1(n:Int32): Int32; begin n := n - 1; n := n or (n shr 1); n := n or (n shr 2); n := n or (n shr 4); n := n or (n shr 8); n := n or (n shr 16); n := n or (n shr 32); Result := n; end;
{* CSI 1101-X, Winter, 1999 *} {* Assignment 6, Question #2 *} {* Identification: Mark Sattolo, student# 428500 *} {* tutorial group DGD-4, t.a. = Jensen Boire *} program a6q2 (input,output) ; type bits = 0..1 ; nodeptr = ^node ; node = record bit: bits ; next: nodeptr end ; number = nodeptr ; { Note: a "number" points to the least significant digit, which then points to the second least significant digit, etc. This arrangement is unintuitive, but since most of the operations process the digits in this order, it makes their code very simple and efficient. The two routines for which this is NOT convenient are read and write, which must convert between this internal order and the normal left-to-right ordering of the bits. } var memory_count: integer; YESorNO: char; { *************** MEMORY MANAGEMENT ************************* } { get_node - Returns a pointer to a new node. } procedure get_node( var P: nodeptr ); BEGIN memory_count := memory_count + 1 ; new( P ) END ; { return_node - Make the node pointed at by P "free" (available to get_node).} procedure return_node(var P: nodeptr) ; BEGIN memory_count := memory_count - 1 ; {**** note: there is no bogus bit value so to try to make bugs visible I flip the bit when the node is freed. ****} P^.bit := 1 - P^.bit ; P^.next := nil ; dispose( P ) ; P := nil END ; { ******************************************************* } { destroy - returns all dynamic memory associated with N } procedure destroy(var N:number) ; BEGIN if N <> nil then BEGIN destroy(N^.next) ; return_node(N) END END; { proc destroy } procedure read_number( var N:number ) ; var b: char ; {*************} { Insert sub-procedure insert_at_front instead of repeating the code 4x in the main procedure. } procedure insert_at_front(var L:number; V: bits) ; var p: nodeptr ; BEGIN get_node(p) ; p^.bit := V ; p^.next := L ; L := p ; END; { proc insert_at_front } {*************} BEGIN N := Nil ; { bus error if N not initialized } { continue loop until end-of-line } while (not eoln) do BEGIN { read char by char } read(b) ; { set node bit to 1 or 0 } if (b = '1') then insert_at_front(N, 1) else if (b = '0') then insert_at_front(N, 0) else BEGIN writeln('Error: improper input value: converting to 0.') ; { Any non-bit values are converted to a 0 bit. } insert_at_front(N, 0) ; END; { else } END; { while } { clear the end-of-line char } readln ; { No value entered is equivalent to a single 0 bit. } if N = Nil then insert_at_front(N, 0) ; END; { proc read_number } procedure write_number( N: number ) ; {*************} { Much simpler to do this write recursively, and need to have the recursive call in a sub-procedure so can have a 'writeln' statement in the main procedure. This way, the output is formatted properly in procedure assignment6q2. } procedure recursive_write(Nx: number) ; BEGIN if Nx <> Nil then BEGIN recursive_write(Nx^.next) ; { Recursive calls will continue until the end } write(Nx^.bit) { of the list (Nil) is reached. Then all the bits } END { will print out in reverse order. } END; { proc recursive_write } {*************} BEGIN recursive_write(N) ; { Need a writeln at the end of the entire number for proper output. } writeln ; END; { proc write_number } procedure add ( N1,N2: number; var SUM: number) ; var { use an integer 'tempsum' to do the initial bit addition } tempsum: integer ; { have bits 'inbit' & 'carry' for the bit sum & carry respectively } inbit, carry: bits ; { need temp pointers p1 & p2 to step through N1 & N2 in the loop } p1, p2: number ; {*************} { Insert the sub-procedure insert_at_end instead of repeating the code 2x in the main procedure. } procedure insert_at_end(var L:number; V: bits) ; BEGIN if L = nil then BEGIN get_node(L) ; L^.bit := V ; L^.next := nil ; END { if } else insert_at_end(L^.next, V) ; END; { proc insert_at_end } {*************} BEGIN carry := 0 ; { set carry for least significant bit to 0 } { p1 and p2 get N1 and N2 respectively } p1 := N1 ; p2 := N2 ; SUM := Nil ; { bus error if SUM not initialized } { continue through loop while either p1 (N1) or p2 (N2) still contain bits. } while ((p1 <> Nil) or (p2 <> Nil)) do BEGIN if (p1 = Nil) then tempsum := p2^.bit + carry { if no p1 only: sum = p2 + carry } else if (p2 = Nil) then tempsum := p1^.bit + carry { if no p2 only: sum = p1 + carry } else tempsum := p1^.bit + p2^.bit + carry ; { if p1 & p2: sum = p1 + p2 + carry } { convert the tempsum to a bit and set carry } if (tempsum < 2) then BEGIN inbit := tempsum ; { if tempsum = 0 or 1, then inbit = tempsum } carry := 0 ; { & carry = 0 } END else BEGIN inbit := (tempsum - 2) ; { if tempsum >= base (2), then inbit = tempsum - base } carry := 1 ; { & carry = 1 } END ; insert_at_end(SUM, inbit) ; { insert the current bit into SUM } { move the pointers p1 & p2 if they are not at Nil } if p1 <> Nil then p1 := p1^.next ; if p2 <> Nil then p2 := p2^.next ; END; { while } { after the loop: if there is a final carry, insert it into SUM } if (carry = 1) then insert_at_end(SUM, carry) ; END; { proc add } { =========== TESTING PROCEDURES ============= } procedure assignment6q2; var N1,N2,Sum: number ; BEGIN writeln('please enter your first binary number'); read_number(N1); writeln('please enter your second binary number'); read_number(N2); write('N1 = '); write_number(N1); write('N2 = '); write_number(N2); add(N1,N2,Sum); write('Sum = '); write_number(Sum); destroy(N1) ; destroy(N2) ; destroy(Sum) END ; {***** YOU MUST CHANGE THIS PROCEDURE TO DESCRIBE YOURSELF *****} procedure identify_myself ; { Writes who you are to the screen } BEGIN writeln ; writeln('CSI 1101-X (winter,1999). Assignment #6, Question #2.') ; writeln('Mark Sattolo, student# 428500.') ; writeln('tutorial section DGD-4, t.a. = Jensen Boire'); writeln END ; BEGIN { main program } identify_myself ; repeat memory_count := 0 ; assignment6q2 ; writeln('Amount of dynamic memory allocated but not returned (should be 0) ', memory_count:0) ; writeln('Do you wish to continue (y or n) ?') ; readln(YESorNO); until (YESorNO <> 'y') END.
unit uTesteuKeyGen; interface uses DUnitX.TestFramework, System.SysUtils; type [TestFixture] TTesteuKeyGen = class(TObject) public [Test] [TestCase('Teste01', '25/09/1990, 912345678912343')] [TestCase('Teste02', '25/09/2000, 125351351351351')] procedure testGeracaoSerial(const data:Tdate; const cnpj:Int64); [Test] [TestCase('Teste03', '25/09/2016, 468468768823437')] [TestCase('Teste04', '25/09/2017, 998465461201351')] procedure testGeracaoNovoSerial(const data:TDate; const cnpj:Int64); [Test] [TestCase('Teste05', '25/09/2060, 912345321823437')] [TestCase('Teste06', '25/09/2060, 784569841201351')] procedure testGeracaoNovoSerialNaValidade(const data:TDate; const cnpj:Int64); [Test] [TestCase('Teste07', '25/09/2015, 782345411823437')] [TestCase('Teste08', '21/02/2016, 021547874984684')] procedure testGeracaoNovoSerialVencido(const data:TDate; const cnpj:Int64); [Test] [TestCase('Teste09', '25/09/2021, 782345411823437, 20/09/2021')] [TestCase('Teste10', '21/02/2044, 021547874984684, 20/02/2044')] procedure testGeracaoValidade(const data:TDate; const cnpj:Int64; const validade:TDate); end; implementation uses uGerarSerial, uValidaSerial; { TTesteuKeyGen } //Verifica somente se é um serial válido procedure TTesteuKeyGen.testGeracaoNovoSerial(const data:TDate; const cnpj:Int64); var novoSerial : string; validadeDeUso : TDate; begin novoSerial := getNovoSerial(True, data, FloatToStr(cnpj)); validadeDeUso := validarSerial(novoSerial, FloatToStr(cnpj)); validadeDeUso := StrToDateDef(DateToStr(validadeDeUso), 0); Assert.IsTrue(validadeDeUso <> 0); end; //Verifica se é valido e se está dentro da validade procedure TTesteuKeyGen.testGeracaoNovoSerialNaValidade(const data: TDate; const cnpj: Int64); var novoSerial : string; validadeDeUso : TDate; begin novoSerial := getNovoSerial(True, data, FloatToStr(cnpj)); validadeDeUso := validarSerial(novoSerial, FloatToStr(cnpj)); validadeDeUso := StrToDateDef(DateToStr(validadeDeUso), 0); Assert.IsTrue((validadeDeUso <> 0) and (validadeDeUso > Date)); end; //Verifica se é valido e se ja está vencido procedure TTesteuKeyGen.testGeracaoNovoSerialVencido(const data: TDate; const cnpj: Int64); var novoSerial : string; validadeDeUso : TDate; begin novoSerial := getNovoSerial(True, data, FloatToStr(cnpj)); validadeDeUso := validarSerial(novoSerial, FloatToStr(cnpj)); validadeDeUso := StrToDateDef(DateToStr(validadeDeUso), 0); Assert.IsTrue((validadeDeUso <> 0) and (validadeDeUso < Date)); end; procedure TTesteuKeyGen.testGeracaoSerial(const data:TDate; const cnpj:Int64); var novoSerial : string; begin novoSerial := getNovoSerial(True, data, IntToStr(cnpj)); Assert.IsNotEmpty(novoSerial); end; //O vencimento cairá sempre no dia 20 de cada mês procedure TTesteuKeyGen.testGeracaoValidade(const data: TDate; const cnpj: Int64; const validade: TDate); var novoSerial : string; validadeDeUso : TDate; begin novoSerial := getNovoSerial(True, data, FloatToStr(cnpj)); validadeDeUso := validarSerial(novoSerial, FloatToStr(cnpj)); validadeDeUso := StrToDateDef(DateToStr(validadeDeUso), 0); Assert.IsTrue(validadeDeUso = validade); end; initialization TDUnitX.RegisterTestFixture(TTesteuKeyGen); end.
unit dcEditbtn; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, DataController, dbctrls, db, ffsException, ToolEdit, dcEdit; type TdcEditBtn = class(TComboEdit) private Fclearing: boolean; FEditChars: TdcEditChars; FLetterFilter: string; procedure Setclearing(const Value: boolean); function GetDatabufIndex: integer; procedure SetDataBufIndex(const Value: integer); procedure SetEditChars(const Value: TdcEditChars); procedure SetLetterFilter(const Value: string); private { Private declarations } fdcLink : TdcLink; fTranData : String; frequired : boolean; OldReadonly : boolean; OriginalData : string; FImageList: TImageList; FImageIndex: integer; procedure SetImageList(const Value: TImageList); procedure SetImageIndex(const Value: integer); procedure SetImage; property clearing:boolean read Fclearing write Setclearing; protected { Protected declarations } // std data awareness function GetDataField:string; procedure SetDataField(value:string); // data controller function GetDataController:TDataController; procedure SetDataController(value:TDataController); function GetDataSource:TDataSource; procedure SetDataSource(value:TDataSource); procedure ReadData(sender:TObject); procedure WriteData(sender:TObject); procedure ClearData(sender:TObject); procedure Change;override; procedure DoEnter;override; procedure DoExit;override; procedure KeyPress(var Key: Char);override; public { Public declarations } constructor Create(AOwner:Tcomponent);override; destructor Destroy;override; property TranData : String read fTranData; published { Published declarations } property Align; property EditChars:TdcEditChars read FEditChars write SetEditChars; property DataController : TDataController read GetDataController write setDataController; property DataField : String read GetDataField write SetDataField; property Required : boolean read fRequired write fRequired; property DataSource : TDataSource read getDataSource write SetDataSource; property ImageList: TImageList read FImageList write SetImageList; property ImageIndex:integer read FImageIndex write SetImageIndex; property DatabufIndex:integer read GetDatabufIndex write SetDataBufIndex; property LetterFilter:string read FLetterFilter write SetLetterFilter; end; procedure Register; implementation constructor TdcEditBtn.Create(AOwner:Tcomponent); begin inherited; fdclink := tdclink.create(self); with fdcLink do begin OnReadData := ReadData; OnWriteData := WriteData; OnClearData := ClearData; end; ClickKey := scNone; FEditChars := [dceLetters, dceNumbers, dceSpace, dceAllOther]; // default value // ButtonWidth := 0; end; destructor TdcEditBtn.Destroy; begin fdclink.Free; inherited; end; function TdcEditBtn.getdatasource; begin result := fdclink.DataSource; end; procedure TdcEditBtn.SetDatasource(value:TDataSource); begin end; procedure TdcEditBtn.SetDataController(value:TDataController); begin fdcLink.datacontroller := value; end; function TdcEditBtn.GetDataController:TDataController; begin result := fdcLink.DataController; end; function TdcEditBtn.GetDataField:string; begin result := fdcLink.FieldName; end; procedure TdcEditBtn.SetDataField(value:string); begin fdcLink.FieldName := value; end; procedure TdcEditBtn.ReadData; begin if not assigned(fdclink.DataController) then exit; OriginalData := ''; if (DataBufIndex = 0) and (DataField <> '') then OriginalData := fdcLink.DataController.dcStrings.StrVal[DataField] else if assigned(fdclink.datacontroller.databuf) then OriginalData := fdclink.datacontroller.databuf.AsString[DataBufIndex]; Text := OriginalData; end; procedure TdcEditBtn.ClearData; begin clearing := true; if assigned(fdclink.Field) then begin maxlength := fdclink.Field.Size; text := trim(fdclink.Field.DefaultExpression); end else text := ''; clearing := false; end; procedure TdcEditBtn.WriteData; var olddata : string; begin if ReadOnly then exit; if not assigned(fdclink.DataController) then exit; if assigned(fdclink.field) then begin olddata := fdclink.Field.AsString; if trim(text) <> trim(olddata) then begin if trim(text) = '' then fTranData := '~' else fTranData := trim(text); end; end; if (DataBufIndex = 0) and (DataField <> '') then fdcLink.DataController.dcStrings.StrVal[DataField] := text else if assigned(fdclink.datacontroller.databuf) then fdclink.datacontroller.databuf.asString[DataBufIndex] := text; end; procedure Register; begin RegisterComponents('FFS Data Entry', [TdcEditBtn]); end; procedure TdcEditBtn.DoEnter; begin OldReadOnly := ReadOnly; if DataController <> nil then begin if DataController.ReadOnly then ReadOnly := true; end; inherited; end; procedure TdcEditBtn.DoExit; begin ReadOnly := OldReadOnly; inherited; end; procedure TdcEditBtn.Change; begin if assigned(fdclink.datacontroller) then if not clearing then fdclink.BeginEdit; inherited; end; procedure TdcEditBtn.SetImageList(const Value: TImageList); begin FImageList := Value; SetImage; end; procedure TdcEditBtn.SetImage; var bmp : TBitmap; begin if (csDesigning in componentstate) then exit; if ImageIndex < 0 then exit; if assigned(ImageList) and (ImageIndex < ImageList.Count) then begin bmp := TBitmap.Create; ImageList.GetBitmap(ImageIndex, bmp); Glyph := bmp; bmp.FreeImage; bmp.free; end; end; procedure TdcEditBtn.SetImageIndex(const Value: integer); begin FImageIndex := Value; SetImage; end; procedure TdcEditBtn.Setclearing(const Value: boolean); begin Fclearing := Value; end; function TdcEditBtn.GetDatabufIndex: integer; begin result := 0; if assigned(fdclink.Datacontroller) then if assigned(fdclink.datacontroller.databuf) then result := fdclink.datacontroller.databuf.FieldNameToIndex(fdclink.FieldName); end; procedure TdcEditBtn.KeyPress(var Key: Char); var echar : TdcEditChar; begin if (Key > #31) then begin if letterfilter > '' then begin if pos(key,letterfilter) = 0 then key := #0; end; if key > #0 then begin echar := dceAllOther; case key of 'A'..'Z', 'a'..'z' : echar := dceLetters; '0'..'9' : echar := dceNumbers; '-' : echar := dceDash; ' ' : echar := dceSpace; end; if not (echar in EditChars) then key := #0; end; end; inherited KeyPress(Key); end; procedure TdcEditBtn.SetDataBufIndex(const Value: integer); begin end; procedure TdcEditBtn.SetEditChars(const Value: TdcEditChars); begin FEditChars := Value; end; procedure TdcEditBtn.SetLetterFilter(const Value: string); begin FLetterFilter := Value; end; end.
unit DM_main; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, DBTables, Db, DBXpress, SqlExpr, ZConnect, ZMySqlCon, ZTransact, ZMySqlTr, QuickRpt, unitTheWayUtils; type TDMMain = class(TDataModule) Database: TZMySqlDatabase; Transaction: TZMySqlTransact; procedure DMMainCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); private { Private declarations } public { Public declarations } options: TOptions; end; var DMMain: TDMMain; implementation {$R *.DFM} procedure TDMMain.DMMainCreate(Sender: TObject); var I: Integer; Temp: TComponent; begin //Carrega opções options:=TOptions.Create; options.setDefault; options.Load; //Conecta à database try Database.Connected := False; Database.Database := options.dbname; Database.Host := options.ip_dbserver; Database.Port := IntToStr(options.port_dbServer); Database.Login := options.dblogin; Database.Password := options.dbpasswd; Database.Connected := True; except beep; ShowMessage('ATENÇÃO: Não foi possível conectar ao banco de dados! Verifique as configurações na configuração geral.'); exit; end; for I := ComponentCount - 1 downto 0 do begin Temp := Components[I]; if (Temp is TDBDataset) then begin TDBDataset(Temp).active := true; end; end; processaContasAReceber; end; procedure TDMMain.DataModuleDestroy(Sender: TObject); begin options.Save; end; end.
unit U_Sorting.Viewer; interface uses U_SortClass, U_Sort.Bubble, U_Sort.Insertion, U_Sort.Selection, U_Sort.Comb, FMX.Controls, FMX.Layouts, System.Classes, FMX.Types, FMX.Forms, System.SysUtils, FMX.Objects, FMX.Effects, FMX.Controls.Presentation, FMX.StdCtrls, rtti, FMX.Filter.Effects, System.Types, FMX.Edit, FMX.EditBox, FMX.SpinBox; type TSortingViewer = class(TForm) Layout1: TLayout; Layout2: TLayout; Layout3: TLayout; Layout4: TLayout; Text1: TText; ShadowEffect1: TShadowEffect; bBubbleSort: TButton; Button2: TButton; Button3: TButton; Button4: TButton; Button5: TButton; Button6: TButton; Button7: TButton; Button8: TButton; Button9: TButton; bInsertionSort: TButton; bSelectionSort: TButton; bCombSort: TButton; Button13: TButton; Button14: TButton; Button15: TButton; ShadowEffect2: TShadowEffect; Layout5: TLayout; Rectangle1: TRectangle; Layout6: TLayout; Label1: TLabel; SpinBox1: TSpinBox; Timer1: TTimer; procedure bBubbleSortClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure bInsertionSortClick(Sender: TObject); procedure bSelectionSortClick(Sender: TObject); procedure bCombSortClick(Sender: TObject); procedure Timer1Timer(Sender: TObject); private var fSort : TSortClass; retorno : Boolean; procedure sort(tipo : Integer); procedure bloqueio(); public { Public declarations } end; var SortingViewer: TSortingViewer; implementation {$R *.fmx} procedure TSortingViewer.bBubbleSortClick(Sender: TObject); begin Text1.Text := 'SortingAlghoritms - BubbleSort'; Self.sort(0); end; procedure TSortingViewer.bCombSortClick(Sender: TObject); begin Text1.Text := 'SortingAlghoritms - CombSort'; Self.sort(3); end; procedure TSortingViewer.bInsertionSortClick(Sender: TObject); begin Text1.Text := 'SortingAlghoritms - InsertionSort'; Self.sort(1); end; procedure TSortingViewer.bloqueio; var I: Integer; item: TControl; begin Timer1.Enabled := not Timer1.Enabled; for I := 0 to Layout4.ControlsCount - 1 do begin item := Layout4.Controls[I]; if item.ClassType = TButton then begin TButton(item).Enabled := not TButton(item).Enabled; end; end; end; procedure TSortingViewer.bSelectionSortClick(Sender: TObject); begin Text1.Text := 'SortingAlghoritms - SelectionSort'; Self.sort(2); end; procedure TSortingViewer.FormCreate(Sender: TObject); var ScreenSize: TSize; begin ScreenSize := Screen.Size; Self.Width := trunc(ScreenSize.Width * 0.8); Self.Height := trunc(ScreenSize.Height * 0.8); Self.Layout2.Size.Height := 50; Self.Layout4.Size.Width := 140; end; procedure TSortingViewer.sort(tipo : Integer); begin ShadowEffect1.UpdateParentEffects; if Assigned(fSort) then begin fSort.Free; end; case tipo of 0: fSort := TSortBubble.Create(Layout5, SpinBox1.Value); 1: fSort := TSortInsertion.Create(Layout5, SpinBox1.Value); 2: fSort := TSortSelection.Create(Layout5, SpinBox1.Value); 3: fSort := TSortComb.Create(Layout5, SpinBox1.Value); end; Self.bloqueio(); fSort.sort(); end; procedure TSortingViewer.Timer1Timer(Sender: TObject); begin if fSort.Finalizado then begin Self.bloqueio(); end; end; end.
unit ChatHistoryKeywordsPack; {* Набор слов словаря для доступа к экземплярам контролов формы ChatHistory } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Chat\Forms\ChatHistoryKeywordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "ChatHistoryKeywordsPack" MUID: (4A6EA397035D_Pack) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3IntfUses ; {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL) implementation {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3ImplUses , ChatHistory_Form , tfwPropertyLike {$If Defined(Nemesis)} , nscChatMemo {$IfEnd} // Defined(Nemesis) , tfwScriptingInterfaces , TypInfo , tfwTypeInfo , tfwControlString , kwBynameControlPush , TtfwClassRef_Proxy , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *4A6EA397035D_Packimpl_uses* //#UC END# *4A6EA397035D_Packimpl_uses* ; type TkwChatHistoryFormHistoryEditor = {final} class(TtfwPropertyLike) {* Слово скрипта .TChatHistoryForm.HistoryEditor } private function HistoryEditor(const aCtx: TtfwContext; aChatHistoryForm: TChatHistoryForm): TnscChatMemo; {* Реализация слова скрипта .TChatHistoryForm.HistoryEditor } 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; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwChatHistoryFormHistoryEditor Tkw_Form_ChatHistory = {final} class(TtfwControlString) {* Слово словаря для идентификатора формы ChatHistory ---- *Пример использования*: [code]форма::ChatHistory TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Form_ChatHistory Tkw_ChatHistory_Control_HistoryEditor = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола HistoryEditor ---- *Пример использования*: [code]контрол::HistoryEditor TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ChatHistory_Control_HistoryEditor Tkw_ChatHistory_Control_HistoryEditor_Push = {final} class(TkwBynameControlPush) {* Слово словаря для контрола HistoryEditor ---- *Пример использования*: [code]контрол::HistoryEditor:push pop:control:SetFocus ASSERT[code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ChatHistory_Control_HistoryEditor_Push function TkwChatHistoryFormHistoryEditor.HistoryEditor(const aCtx: TtfwContext; aChatHistoryForm: TChatHistoryForm): TnscChatMemo; {* Реализация слова скрипта .TChatHistoryForm.HistoryEditor } begin Result := aChatHistoryForm.HistoryEditor; end;//TkwChatHistoryFormHistoryEditor.HistoryEditor class function TkwChatHistoryFormHistoryEditor.GetWordNameForRegister: AnsiString; begin Result := '.TChatHistoryForm.HistoryEditor'; end;//TkwChatHistoryFormHistoryEditor.GetWordNameForRegister function TkwChatHistoryFormHistoryEditor.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TnscChatMemo); end;//TkwChatHistoryFormHistoryEditor.GetResultTypeInfo function TkwChatHistoryFormHistoryEditor.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwChatHistoryFormHistoryEditor.GetAllParamsCount function TkwChatHistoryFormHistoryEditor.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TChatHistoryForm)]); end;//TkwChatHistoryFormHistoryEditor.ParamsTypes procedure TkwChatHistoryFormHistoryEditor.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству HistoryEditor', aCtx); end;//TkwChatHistoryFormHistoryEditor.SetValuePrim procedure TkwChatHistoryFormHistoryEditor.DoDoIt(const aCtx: TtfwContext); var l_aChatHistoryForm: TChatHistoryForm; begin try l_aChatHistoryForm := TChatHistoryForm(aCtx.rEngine.PopObjAs(TChatHistoryForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aChatHistoryForm: TChatHistoryForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(HistoryEditor(aCtx, l_aChatHistoryForm)); end;//TkwChatHistoryFormHistoryEditor.DoDoIt function Tkw_Form_ChatHistory.GetString: AnsiString; begin Result := 'ChatHistoryForm'; end;//Tkw_Form_ChatHistory.GetString class procedure Tkw_Form_ChatHistory.RegisterInEngine; begin inherited; TtfwClassRef.Register(TChatHistoryForm); end;//Tkw_Form_ChatHistory.RegisterInEngine class function Tkw_Form_ChatHistory.GetWordNameForRegister: AnsiString; begin Result := 'форма::ChatHistory'; end;//Tkw_Form_ChatHistory.GetWordNameForRegister function Tkw_ChatHistory_Control_HistoryEditor.GetString: AnsiString; begin Result := 'HistoryEditor'; end;//Tkw_ChatHistory_Control_HistoryEditor.GetString class procedure Tkw_ChatHistory_Control_HistoryEditor.RegisterInEngine; begin inherited; TtfwClassRef.Register(TnscChatMemo); end;//Tkw_ChatHistory_Control_HistoryEditor.RegisterInEngine class function Tkw_ChatHistory_Control_HistoryEditor.GetWordNameForRegister: AnsiString; begin Result := 'контрол::HistoryEditor'; end;//Tkw_ChatHistory_Control_HistoryEditor.GetWordNameForRegister procedure Tkw_ChatHistory_Control_HistoryEditor_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('HistoryEditor'); inherited; end;//Tkw_ChatHistory_Control_HistoryEditor_Push.DoDoIt class function Tkw_ChatHistory_Control_HistoryEditor_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::HistoryEditor:push'; end;//Tkw_ChatHistory_Control_HistoryEditor_Push.GetWordNameForRegister initialization TkwChatHistoryFormHistoryEditor.RegisterInEngine; {* Регистрация ChatHistoryForm_HistoryEditor } Tkw_Form_ChatHistory.RegisterInEngine; {* Регистрация Tkw_Form_ChatHistory } Tkw_ChatHistory_Control_HistoryEditor.RegisterInEngine; {* Регистрация Tkw_ChatHistory_Control_HistoryEditor } Tkw_ChatHistory_Control_HistoryEditor_Push.RegisterInEngine; {* Регистрация Tkw_ChatHistory_Control_HistoryEditor_Push } TtfwTypeRegistrator.RegisterType(TypeInfo(TChatHistoryForm)); {* Регистрация типа TChatHistoryForm } {$If Defined(Nemesis)} TtfwTypeRegistrator.RegisterType(TypeInfo(TnscChatMemo)); {* Регистрация типа TnscChatMemo } {$IfEnd} // Defined(Nemesis) {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL) end.
unit xn.grid.data; interface uses Generics.Collections, xn.grid.common, xn.list; type // ******************************************************************************** // ******************************************************************************** TxnGridSortItem = record type TKind = (gskStr, gskNum); TOrder = (gsoAsc, gsoDesc); private fIndex: integer; fKind: TKind; fOrder: TOrder; public constructor Create(aIndex: integer; aKind: TKind; aOrder: TOrder); end; IxnGridSortItems = IxnList<TxnGridSortItem>; TxnGridSortItems = TxnList<TxnGridSortItem>; // ******************************************************************************** // ******************************************************************************** TxnGridFilterItem = record type TCase = (gfcCaseSensitive, gfcCaseInsensitive); TKind = (gfkStr, gfkNum); private fIndex: integer; fKind: TKind; fCase: TCase; fValue: variant; public constructor Create(aIndex: integer; aValue: variant; aKind: TKind; aCase: TCase); end; IxnGridFilterItems = IxnList<TxnGridFilterItem>; TxnGridFilterItems = TxnList<TxnGridFilterItem>; // ******************************************************************************** // ******************************************************************************** TxnGridData = class(TInterfacedObject, IxnGridData) private fData: IxnGridData; fIndex: TList<integer>; public function RowCountGet: integer; virtual; function AsDebug: String; virtual; function ValueString(aCol, aRow: integer): String; virtual; function ValueFloat(aCol, aRow: integer): Double; virtual; end; // ******************************************************************************** // ******************************************************************************** TxnGridDataSort = class(TxnGridData) strict private fItems: IxnGridSortItems; function Comparer(const aLeft, aRight: TArray<variant>): integer; function Getter(const aIndex: integer): TArray<variant>; procedure Sort(aStart, aStop: integer); overload; public constructor Create(aGridData: IxnGridData; aSortItems: IxnGridSortItems); destructor Destroy; override; procedure Fill; virtual; procedure Sort; overload; function Seek1(aKeys: TArray<variant>): integer; function Seek2(aKeys: TArray<variant>): integer; end; TxnGridDataFilter = class(TxnGridData) strict private fItems: IxnGridFilterItems; function Comparer(const aLeft, aRight: TArray<variant>): integer; function Getter(const aIndex: integer): TArray<variant>; public constructor Create(aGridData: IxnGridData; aFilterItems: IxnGridFilterItems); destructor Destroy; override; procedure Fill; virtual; end; implementation uses System.SysUtils; { TxnGridSortItem } constructor TxnGridSortItem.Create(aIndex: integer; aKind: TKind; aOrder: TOrder); begin fIndex := aIndex; fKind := aKind; fOrder := aOrder; end; { TxnGridFilterItem } constructor TxnGridFilterItem.Create(aIndex: integer; aValue: variant; aKind: TKind; aCase: TCase); begin fIndex := aIndex; fKind := aKind; fCase := aCase; fValue := aValue; end; { TxnGridData } function TxnGridData.AsDebug: String; var i: integer; begin for i := 0 to fIndex.Count - 1 do Result := Result + ValueString(0, i) + ','; end; function TxnGridData.RowCountGet: integer; begin Result := fIndex.Count end; function TxnGridData.ValueFloat(aCol, aRow: integer): Double; begin Result := fData.ValueFloat(aCol, fIndex[aRow]); end; function TxnGridData.ValueString(aCol, aRow: integer): String; begin Result := fData.ValueString(aCol, fIndex[aRow]); end; { TxnGridDataSort } procedure TxnGridDataSort.Sort(aStart, aStop: integer); var iStart: integer; iStop: integer; iPivot: TArray<variant>; begin iStart := aStart; iStop := aStop; iPivot := Getter((iStart + iStop) div 2); repeat while (Comparer(Getter(iStart), iPivot) < 0) do Inc(iStart); while (Comparer(Getter(iStop), iPivot) > 0) do Dec(iStop); if iStart <= iStop then begin if iStart <> iStop then fIndex.Exchange(iStart, iStop); Inc(iStart); Dec(iStop); end; until iStart > iStop; if iStop > aStart then Sort(aStart, iStop); if iStart < aStop then Sort(iStart, aStop); end; function TxnGridDataSort.Comparer(const aLeft, aRight: TArray<variant>): integer; var t: variant; l: variant; r: variant; i: integer; begin for i := Low(aLeft) to High(aLeft) do begin l := aLeft[i]; r := aRight[i]; if (fItems[i].fOrder = gsoDesc) then begin t := l; l := r; r := t; end; if l < r then exit(-1) else if l > r then exit(+1); end; exit(0); end; constructor TxnGridDataSort.Create(aGridData: IxnGridData; aSortItems: IxnGridSortItems); begin fData := aGridData; fItems := aSortItems; fIndex := TList<integer>.Create; Fill; end; destructor TxnGridDataSort.Destroy; begin fIndex.Free; inherited; end; procedure TxnGridDataSort.Fill; var i: integer; begin fIndex.Clear; for i := 0 to fData.RowCountGet - 1 do fIndex.Add(i); end; function TxnGridDataSort.Getter(const aIndex: integer): TArray<variant>; var i: integer; begin SetLength(Result, fItems.Count); for i := 0 to fItems.Count - 1 do if (fItems[i].fKind = gskStr) then Result[i] := ValueString(fItems[i].fIndex, aIndex) else Result[i] := ValueFloat(fItems[i].fIndex, aIndex) end; function TxnGridDataSort.Seek1(aKeys: TArray<variant>): integer; var iStart: integer; iStop: integer; iPivot: integer; iComparer: integer; begin // returns the actual index of the item in the list // -1 if the item is not found iStart := 0; iStop := fIndex.Count - 1; if fIndex.Count = 0 then exit(-1); Result := -1; while iStart <= iStop do begin iPivot := (iStart + iStop) div 2; iComparer := Comparer(Getter(iPivot), aKeys); if iComparer = 0 then exit(iPivot) else if iComparer > 0 then iStop := iPivot - 1 else iStart := iPivot + 1; end; end; function TxnGridDataSort.Seek2(aKeys: TArray<variant>): integer; var iStart: integer; iStop: integer; oStart: integer; oStop: integer; iPivot: integer; iComparer: integer; iOther: integer; begin // returns the expected index of the item in the list // -1 if the item is after the last item of the list iStart := 0; oStart := 0; iStop := fIndex.Count - 1; oStop := fIndex.Count - 1; if fIndex.Count = 0 then exit(0); Result := -1; while iStart <= iStop do begin iPivot := (iStart + iStop) div 2; iComparer := Comparer(Getter(iPivot), aKeys); if iComparer = 0 then exit(iPivot) else if iComparer > 0 then begin if iPivot > oStart then begin iOther := Comparer(Getter(iPivot - 1), aKeys); if iOther = 0 then exit(iPivot - 1) else if iOther < 0 then exit(iPivot); end; iStop := iPivot - 1 end else begin if iPivot < oStop then begin iOther := Comparer(Getter(iPivot + 1), aKeys); if iOther = 0 then exit(iPivot + 1) else if iOther > 0 then exit(iPivot + 1); end; iStart := iPivot + 1; end; end; if Comparer(Getter(oStart), aKeys) > 0 then exit(oStart); end; procedure TxnGridDataSort.Sort; begin if fIndex.Count > 0 then if fItems.Count > 0 then Sort(0, fIndex.Count - 1); end; { TxnGridDataFilter } function TxnGridDataFilter.Comparer(const aLeft, aRight: TArray<variant>): integer; var l: variant; r: variant; i: integer; begin for i := Low(aLeft) to High(aLeft) do begin l := aLeft[i]; r := aRight[i]; if fItems[i].fCase = gfcCaseInsensitive then begin l := LowerCase(l); r := LowerCase(r); end; if l < r then exit(-1) else if l > r then exit(+1); end; exit(0); end; constructor TxnGridDataFilter.Create(aGridData: IxnGridData; aFilterItems: IxnGridFilterItems); begin fData := aGridData; fItems := aFilterItems; fIndex := TList<integer>.Create; Fill; end; destructor TxnGridDataFilter.Destroy; begin fIndex.Free; inherited; end; procedure TxnGridDataFilter.Fill; var i: integer; a: TArray<variant>; begin SetLength(a, fItems.Count); for i := 0 to fItems.Count - 1 do a[i] := fItems[i].fValue; fIndex.Clear; for i := 0 to fData.RowCountGet - 1 do if Comparer(a, Getter(i)) = 0 then fIndex.Add(i); end; function TxnGridDataFilter.Getter(const aIndex: integer): TArray<variant>; var i: integer; begin SetLength(Result, fItems.Count); for i := 0 to fItems.Count - 1 do if (fItems[i].fKind = gfkStr) then Result[i] := fData.ValueString(fItems[i].fIndex, aIndex) else Result[i] := fData.ValueFloat(fItems[i].fIndex, aIndex) end; end.
unit FullScreenService; interface uses FMX.Forms; type /// FullScreenWindowService that is created. TFullScreenServiceiOS = class(TInterfacedObject, IFMXFullScreenWindowService) private FOriginalBoarderStyle : TFmxFormBorderStyle; public function GetFullScreen(const AForm: TCommonCustomForm): Boolean; procedure SetFullScreen(const AForm: TCommonCustomForm; const AValue: Boolean); procedure SetShowFullScreenIcon(const AForm: TCommonCustomForm; const AValue: Boolean); end; var FullScreenServiceiOS : TFullScreenServiceiOS; implementation uses FMX.Platform; { TFullScreenServiceiOS } function TFullScreenServiceiOS.GetFullScreen( const AForm: TCommonCustomForm): Boolean; begin if AForm = nil then Exit(False); Result := AForm.BorderStyle = TFmxFormBorderStyle.None; end; procedure TFullScreenServiceiOS.SetFullScreen(const AForm: TCommonCustomForm; const AValue: Boolean); begin if AForm = nil then Exit; if AValue then begin if AForm.BorderStyle <> TFmxFormBorderStyle.None then FOriginalBoarderStyle := AForm.BorderStyle; AForm.BorderStyle := TFmxFormBorderStyle.None end else begin if (FOriginalBoarderStyle = TFmxFormBorderStyle.None) and (AValue = False) then FOriginalBoarderStyle := TFmxFormBorderStyle.Sizeable; AForm.BorderStyle := FOriginalBoarderStyle; end; end; procedure TFullScreenServiceiOS.SetShowFullScreenIcon( const AForm: TCommonCustomForm; const AValue: Boolean); begin end; procedure RegisterFullScreenServiceiOS; begin FullScreenServiceiOS := TFullScreenServiceiOS.Create; TPlatformServices.Current.AddPlatformService(IFMXFullScreenWindowService, FullScreenServiceiOS); end; {$IFDEF IOS} initialization RegisterFullScreenServiceiOS; {$ENDIF} end.
unit Unit30; interface uses System.Classes; //uses System.Classes; type // {$VARPROPSETTER ON} TCores = (cAzul, cAmarelo); TMinhaClasse = class private FNumero: integer; FItems:TStringList; FCores:TCores; FCor: TCores; function GetNumero: integer; procedure SetNumero(const Value: integer); function GetItems(idx: integer): string; procedure SetItems(idx: integer; const Value: string); procedure SetCor(const Value: TCores); function GetCor: TCores; public constructor create;//override; destructor destroy;override; property Numero: integer read GetNumero write SetNumero; property Items[ idx:integer] :string read GetItems write SetItems; published property Cor:TCores read GetCor write SetCor stored cAmarelo; end; implementation { TMinhaClasse } constructor TMinhaClasse.create; begin inherited; FCor := cAmarelo; FItems := TStringList.Create; FItems.Add('tstst'); end; destructor TMinhaClasse.destroy; begin FItems.Free; inherited; end; function TMinhaClasse.GetCor: TCores; begin result := FCores; end; function TMinhaClasse.GetItems(idx: integer): string; begin result := FItems[idx]; end; function TMinhaClasse.GetNumero: integer; begin Result := FNumero; end; procedure TMinhaClasse.SetCor(const Value: TCores); begin FCor := Value; end; procedure TMinhaClasse.SetItems(idx: integer; const Value: string); begin FItems[idx] := value; end; procedure TMinhaClasse.SetNumero(const Value: integer); begin Value := Value +1; FNumero := Value; end; end.
unit tmsXlsFormulaMessages; {$INCLUDE ..\FLXCOMPILER.INC} {$INCLUDE ..\FLXCONFIG.INC} interface uses tmsUFlxMessages; //Resources on this unit are not localized, to avoid having different //interfaces to formulas for different languages. //Of course, you are free to translate them to your language, //so a user can read or write the formula text the same way //he does it on his Excel version. But keep in mind that if you //write a formula in your code, you will have to write it in your language, //and if you later compile your app on other language, it will not work. const fmiErrNull = $00; fmiErrDiv0 = $07; fmiErrValue = $0F; fmiErrRef = $17; fmiErrName = $1D; fmiErrNum = $24; fmiErrNA = $2A; resourcestring fmErrNull='#NULL!'; fmErrDiv0='#DIV/0!'; fmErrValue='#VALUE!'; fmErrRef='#REF!'; fmErrName='#NAME?'; fmErrNum='#NUM!'; fmErrNA='#N/A'; fmErrUnknown='#FLEXCEL_UNKNOWN'; fmErrStart='#'; fmTrue='TRUE'; fmFalse='FALSE'; fmStartFormula='='; //as in =a1*2 or {=1+2} fmFormulaDecimal='.'; //as in '1.2' fmFormulaThousands=','; //as in '1,300' fmFunctionSep=','; //Argument separator on a function. //For example, if fmFunctionSep=';' we should //write "Max(a1;a2)" //If you want to localize this, you could use fmFunctionSep=ListSeparator fmUnion =','; //as in "=a1, b2" fmIntersect =' '; //as in a1 a2 fmSingleQuote=''''; fmOpenArray='{'; fmCloseArray='}'; fmOpenParen='('; fmCloseParen=')'; fmArrayRowSep=';'; // Separates 2 rows on an array. It is '\' in spanish fmArrayColSep=','; // Separates 2 columns on an array. Ex: {1,2}. It is ';' in spanish //If you want to localize this, you could use fmArrayColSep=ListSeparator fmAbsoluteRef='$'; //as in $A$3 fmRangeSep=':'; //as in A1:A3 fmExternalRef='!'; //as in Sheet1!a1 fmWorkbookOpen='['; //as in c:\[book1.xls]Sheet1!a1 fmWorkbookClose=']'; fmTableText='TABLE'; //those here shouldnt change fmPlus='+'; fmMinus='-'; fmMul='*'; fmDiv='/'; fmPower='^'; fmPercent='%'; fmStr='"'; fmAnd='&'; fmLT='<'; fmLE='<='; fmEQ='='; fmGE='>='; fmGT='>'; fmNE='<>'; function FmFloatToStr(const Value: Extended): string; function FmStrToFloat(const Value:string ): Extended; const attr_bitFSpace=$00; attr_bitFEnter=$01; attr_bitFPreSpace=$02; attr_bitFPreEnter=$03; attr_bitFPostSpace=$04; attr_bitFPostEnter=$05; attr_bitFPreFmlaSpace=$06; type TFmReturnType=(fmValue, fmRef, fmArray); TCellFunctionData=record Index: integer; Name: UTF16String; MinArgCount: integer; MaxArgCount: integer; Volatile: boolean; ReturnType: TFmReturnType; ParamType: UTF16String; end; const {$INCLUDE XlsFunctionNames.inc} {$INCLUDE XlsPtgs.inc} implementation uses SysUtils; function FmFloatToStr(const Value: Extended): string; { This is a non-localized version of FloatToStr It will always use "." as decimal separator. If you are localizing this unit to your language, change this function to be: function FmFloatToStr(const Value: Extended): string; begin Result:=FloatToStr(Value); end; And it will use your current locale to get the decimal separator. Just remember that if you for example use "," as decimal sep, you should also change fmArrayColSep, fmFunctionSep and all vars with value="," } //we cant use TFormatSettings as it does not work on D5 or kylix; begin {$IFDEF NOFORMATSETTINGS} Result:=FloatToStr(Value); if ThousandSeparator<>fmFormulaThousands then Result:=StringReplace(Result, ThousandSeparator, '',[rfReplaceAll]); if DecimalSeparator<> fmFormulaDecimal then Result:=StringReplace(Result, DecimalSeparator, fmFormulaDecimal,[rfReplaceAll]); {$ELSE} Result:=FloatToStr(Value, InvariantFormatSettings^); {$ENDIF} end; function FmStrToFloat(const Value:string ): Extended; { This is a non-localized version of StrToFloat It will always use "." as decimal separator. If you are localizing this unit to your language, change this function to be: function FmStrToFloat(const Value:string ): Extended; begin Result:=StrToFloat(Value); end; And it will use your current locale to get the decimal separator. Just remember that if you for example use "," as decimal sep, you should also change fmArrayColSep, fmFunctionSep and all vars with value="," } //we cant use TFormatSettings as it does not work on D5 or kylix; {$IFDEF NOFORMATSETTINGS} var v: string; begin v:=Value; if ThousandSeparator<>fmFormulaThousands then v:=StringReplace(v, fmFormulaThousands, '',[rfReplaceAll]); if DecimalSeparator<> fmFormulaDecimal then v:=StringReplace(v, fmFormulaDecimal, DecimalSeparator,[rfReplaceAll]); Result:=StrToFloat(v); end; {$ELSE} begin Result:=StrtoFloat(Value, InvariantFormatSettings^); end; {$ENDIF} end.
(* libltc - en+decode linear timecode Copyright (C) 2006-2012 Robin Gareus <robin@gareus.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. Conversion to Pascal Copyright 2014 (c) Oleksandr Nazaruk <support@freehand.com.ua> based on libltc-1.1.3 *) unit FH.LIBLTC.TIMECODE; interface uses System.SysUtils, FH.LIBLTC.LTC; (** * SMPTE Timezones *) Type SMPTETimeZonesStruct = packed record code : byte; //actually 6 bit! timezone : array[0..5] of char; end; (** * SMPTE Timezone codes as per http://www.barney-wol.net/time/timecode.html *) const smpte_time_zones : array[0..57] of SMPTETimeZonesStruct = ( (* code; timezone: timezone (UTC+) Standard time Daylight saving *) ( code: $00; timezone: '+0000' (* Greenwich *) (* - *) ), ( code: $00; timezone: '-0000' (* Greenwich *) (* - *) ), ( code: $01; timezone: '-0100' (* Azores *) (* - *) ), ( code: $02; timezone: '-0200' (* Mid-Atlantic *) (* - *) ), ( code: $03; timezone: '-0300' (* Buenos Aires *) (* Halifax *) ), ( code: $04; timezone: '-0400' (* Halifax *) (* New York *) ), ( code: $05; timezone: '-0500' (* New York *) (* Chicago *) ), ( code: $06; timezone: '-0600' (* Chicago Denver *) (* - *) ), ( code: $07; timezone: '-0700' (* Denver *) (* Los Angeles *) ), ( code: $08; timezone: '-0800' (* Los Angeles *) (* - *) ), ( code: $09; timezone: '-0900' (* Alaska *) (* - *) ), ( code: $10; timezone: '-1000' (* Hawaii *) (* - *) ), ( code: $11; timezone: '-1100' (* Midway Island *) (* - *) ), ( code: $12; timezone: '-1200' (* Kwaialein *) (* - *) ), ( code: $13; timezone: '+1300' (* - *) (* New Zealand *) ), ( code: $14; timezone: '+1200' (* New Zealand *) (* - *) ), ( code: $15; timezone: '+1100' (* Solomon Islands *) (* - *) ), ( code: $16; timezone: '+1000' (* Guam *) (* - *) ), ( code: $17; timezone: '+0900' (* Tokyo *) (* - *) ), ( code: $18; timezone: '+0800' (* Beijing *) (* - *) ), ( code: $19; timezone: '+0700' (* Bangkok *) (* - *) ), ( code: $20; timezone: '+0600' (* Dhaka *) (* - *) ), ( code: $21; timezone: '+0500' (* Islamabad *) (* - *) ), ( code: $22; timezone: '+0400' (* Abu Dhabi *) (* - *) ), ( code: $23; timezone: '+0300' (* Moscow *) (* - *) ), ( code: $24; timezone: '+0200' (* Eastern Europe *) (* - *) ), ( code: $25; timezone: '+0100' (* Central Europe *) (* - *) ), (* ( code: $26; timezone: 'Undefined' Reserved; do not use ),*) (* ( code: $27; timezone: 'Undefined' Reserved; do not use ),*) ( code: $28; timezone: 'TP-03' (* Time precision class 3 *) (* - *) ), ( code: $29; timezone: 'TP-02' (* Time precision class 2 *) (* - *) ), ( code: $30; timezone: 'TP-01' (* Time precision class 1 *) (* - *) ), ( code: $31; timezone: 'TP-00' (* Time precision class 0 *) (* - *) ), ( code: $0A; timezone: '-0030' (* - *) (* - *) ), ( code: $0B; timezone: '-0130' (* - *) (* - *) ), ( code: $0C; timezone: '-0230' (* - *) (* Newfoundland *) ), ( code: $0D; timezone: '-0330' (* Newfoundland *) (* - *) ), ( code: $0E; timezone: '-0430' (* - *) (* - *) ), ( code: $0F; timezone: '-0530' (* - *) (* - *) ), ( code: $1A; timezone: '-0630' (* - *) (* - *) ), ( code: $1B; timezone: '-0730' (* - *) (* - *) ), ( code: $1C; timezone: '-0830' (* - *) (* - *) ), ( code: $1D; timezone: '-0930' (* Marquesa Islands *) (* - *) ), ( code: $1E; timezone: '-1030' (* - *) (* - *) ), ( code: $1F; timezone: '-1130' (* - *) (* - *) ), ( code: $2A; timezone: '+1130' (* Norfolk Island *) (* - *) ), ( code: $2B; timezone: '+1030' (* Lord Howe Is. *) (* - *) ), ( code: $2C; timezone: '+0930' (* Darwin *) (* - *) ), ( code: $2D; timezone: '+0830' (* - *) (* - *) ), ( code: $2E; timezone: '+0730' (* - *) (* - *) ), ( code: $2F; timezone: '+0630' (* Rangoon *) (* - *) ), ( code: $3A; timezone: '+0530' (* Bombay *) (* - *) ), ( code: $3B; timezone: '+0430' (* Kabul *) (* - *) ), ( code: $3C; timezone: '+0330' (* Tehran *) (* - *) ), ( code: $3D; timezone: '+0230' (* - *) (* - *) ), ( code: $3E; timezone: '+0130' (* - *) (* - *) ), ( code: $3F; timezone: '+0030' (* - *) (* - *) ), ( code: $32; timezone: '+1245' (* Chatham Island *) (* - *) ), (* ( code: $33; timezone: 'Undefined' Reserved; do not use ),*) (* ( code: $34; timezone: 'Undefined' Reserved; do not use ),*) (* ( code: $35; timezone: 'Undefined' Reserved; do not use ),*) (* ( code: $36; timezone: 'Undefined' Reserved; do not use ),*) (* ( code: $37; timezone: 'Undefined' Reserved; do not use ),*) ( code: $38; timezone: '+XXXX' (* User defined time offset *) (* - *) ), (* ( code: $39; timezone: 'Undefined' Unknown Unknown ),*) (* ( code: $39; timezone: 'Undefined' Unknown Unknown ),*) ( code: $FF; timezone: '' (* The End *) ) ); procedure smpte_set_timezone_string(frame: TLTCFrameRAW; var stime: TSMPTETimecode); procedure ltc_frame_to_time(var stime: TSMPTETimecode; frame: TLTCFrameRAW; flags: integer); implementation procedure smpte_set_timezone_string(frame: TLTCFrameRAW; var stime: TSMPTETimecode); var i : integer; code : byte; timezone : array[0..5] of char; user7, user8 : byte; begin user7:= (frame.b7 and $10) or (frame.b7 and $20) or (frame.b7 and $40) or (frame.b7 and $80); user8:= (frame.b8 and $10) or (frame.b8 and $20) or (frame.b8 and $40) or (frame.b8 and $80); code := user7 + (user8 shl 4); strpcopy(timezone, '+0000'); for i:= 0 to length(smpte_time_zones)-1 do begin if ( smpte_time_zones[i].code = code ) then begin StrPCopy(timezone, smpte_time_zones[i].timezone); break; end; end; StrPCopy(stime.timezone, timezone); end; (* OK *) procedure ltc_frame_to_time(var stime: TSMPTETimecode; frame: TLTCFrameRAW; flags: integer); var frame_units : byte; frame_tens : byte; secs_units : byte; secs_tens : byte; hours_units : byte; hours_tens : byte; mins_units : byte; mins_tens : byte; user5, user6 : byte; user3, user4 : byte; user1, user2 : byte; begin if (LTC_BG_FLAGS(flags) = LTC_USE_DATE) then begin smpte_set_timezone_string(frame, stime); user1:= (frame.b1 and $10) or (frame.b1 and $20) or (frame.b1 and $40) or (frame.b1 and $80); user2:= (frame.b2 and $10) or (frame.b2 and $20) or (frame.b2 and $40) or (frame.b2 and $80); user3:= (frame.b3 and $10) or (frame.b3 and $20) or (frame.b3 and $40) or (frame.b3 and $80); user4:= (frame.b4 and $10) or (frame.b4 and $20) or (frame.b4 and $40) or (frame.b4 and $80); user5:= (frame.b5 and $10) or (frame.b5 and $20) or (frame.b5 and $40) or (frame.b5 and $80); user6:= (frame.b6 and $10) or (frame.b6 and $20) or (frame.b6 and $40) or (frame.b6 and $80); stime.years := user5 + user6*10; stime.months := user3 + user4*10; stime.days := user1 + user2*10; end else begin stime.years := 0; stime.months := 0; stime.days := 0; strpCopy(stime.timezone,'+0000'); end; frame_units:= (frame.b1 and $01) or (frame.b1 and $02) or (frame.b1 and $04) or (frame.b1 and $08); frame_tens:= (frame.b2 and $01) or (frame.b2 and $02); secs_units:= (frame.b3 and $01) or (frame.b3 and $02) or (frame.b3 and $04) or (frame.b3 and $08); secs_tens:= (frame.b4 and $01) or (frame.b4 and $02) or (frame.b4 and $04); mins_units:= (frame.b5 and $01) or (frame.b5 and $02) or (frame.b5 and $04) or (frame.b5 and $08); mins_tens:= (frame.b6 and $01) or (frame.b6 and $02) or (frame.b6 and $04); hours_units:= (frame.b7 and $01) or (frame.b7 and $02) or (frame.b7 and $04) or (frame.b7 and $08); hours_tens:= (frame.b8 and $01) or (frame.b8 and $02); stime.hours := hours_units + hours_tens*10; stime.mins := mins_units + mins_tens*10; stime.secs := secs_units + secs_tens*10; stime.frame := frame_units + frame_tens*10; end; end.
unit kwPopReminderMove; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ScriptEngine" // Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwPopReminderMove.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::vtControlsFromStackWords::pop_reminder_Move // // *Формат:* // {code} // aDeltaX aDeltaY aReminderRatio aReminder pop:Reminder:Move // {code} // *Описание:* Перемещение линейки со значаками на aDetaX по горизонтали и на aDeltaY по вертикали // относительно текущей позиции. *Внимание! aDeltaX и aDeltaY - смещения, а не координаты!* // aReminderRatio - нужно ли запоминать положение. Полный аналог перемещения с помощью мыши. // // *Прммер:* // {code} // CONST "Красная медаль с восклицательным знаком" 'OldBaseWarning' // // 500 500 true "Красная медаль с восклицательным знаком" byname:control:Push pop:Reminder:Move // {code} // Смещает медали на 500 пикселей по горизонтали и 500 пикселей по вертикали относительно текущего // положения. // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\ScriptEngine\seDefine.inc} interface {$If not defined(NoScripts)} uses vtCustomReminder, tfwScriptingInterfaces, Controls, Classes ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type {$Include ..\ScriptEngine\kwVTCustomReminder.imp.pas} TkwPopReminderMove = {final} class(_kwVTCustomReminder_) {* *Формат:* [code] aDeltaX aDeltaY aReminderRatio aReminder pop:Reminder:Move [code] *Описание:* Перемещение линейки со значаками на aDetaX по горизонтали и на aDeltaY по вертикали относительно текущей позиции. *Внимание! aDeltaX и aDeltaY - смещения, а не координаты!* aReminderRatio - нужно ли запоминать положение. Полный аналог перемещения с помощью мыши. *Прммер:* [code] CONST "Красная медаль с восклицательным знаком" 'OldBaseWarning' 500 500 true "Красная медаль с восклицательным знаком" byname:control:Push pop:Reminder:Move [code] Смещает медали на 500 пикселей по горизонтали и 500 пикселей по вертикали относительно текущего положения. } protected // realized methods procedure DoWithvtCustomReminder(const aReminder: TvtCustomReminder; const aCtx: TtfwContext); override; public // overridden public methods class function GetWordNameForRegister: AnsiString; override; end;//TkwPopReminderMove {$IfEnd} //not NoScripts implementation {$If not defined(NoScripts)} uses tfwAutoregisteredDiction, tfwScriptEngine, Windows, afwFacade, Forms ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type _Instance_R_ = TkwPopReminderMove; {$Include ..\ScriptEngine\kwVTCustomReminder.imp.pas} // start class TkwPopReminderMove procedure TkwPopReminderMove.DoWithvtCustomReminder(const aReminder: TvtCustomReminder; const aCtx: TtfwContext); //#UC START# *4FFD36D9017A_4FFD37650303_var* var l_DeltaX : Integer; l_DeltaY : Integer; l_Remember : Boolean; //#UC END# *4FFD36D9017A_4FFD37650303_var* begin //#UC START# *4FFD36D9017A_4FFD37650303_impl* if aCtx.rEngine.IsTopBool then begin l_Remember := aCtx.rEngine.PopBool; if aCtx.rEngine.IsTopInt then begin l_DeltaY := aCtx.rEngine.PopInt; if aCtx.rEngine.IsTopInt then l_DeltaX := aCtx.rEngine.PopInt else Assert(False, 'Не задано смещение по оси X'); TvtHackCustomReminder(aReminder).MoveReminder(l_DeltaX, l_DeltaY, l_Remember); end // if aCtx.rEngine.IsTopInt then else Assert(False, 'Не задано смещение по оси Y'); end // if aCtx.rEngine.IsTopBool then else Assert(False, 'Не задан флаг для необходимости запоминания координат!'); //#UC END# *4FFD36D9017A_4FFD37650303_impl* end;//TkwPopReminderMove.DoWithvtCustomReminder class function TkwPopReminderMove.GetWordNameForRegister: AnsiString; {-} begin Result := 'pop:reminder:Move'; end;//TkwPopReminderMove.GetWordNameForRegister {$IfEnd} //not NoScripts initialization {$If not defined(NoScripts)} {$Include ..\ScriptEngine\kwVTCustomReminder.imp.pas} {$IfEnd} //not NoScripts end.
unit Flics; // Copyright (c) 1996 Jorge Romero Gomez, Merchise. interface uses GDI; const // Magic signatures idHeaderFLI = $AF11; idHeaderFLC = $AF12; idPrefix = $F100; idFrame = $F1FA; // types of chunk in a FLI frame idColor = 11; idLC = 12; idBlack = 13; idBRun = 15; idCopy = 16; // types of chunk added by FLC idColor256 = 4; idSS2 = 7; idXlat256 = 18; // Internal to a PSTAMP chunk idPStamp = 18; // bit defines for flags field idFinished = $01; // finished writing FLI idLooped = $02; // FLI has a loop frame type TOldFliHeader = packed record Size : longint; // size of entire animation file Magic : word; // always $AF11 Frames : word; // Should be < 4000 Width : word; // 320 Height : word; // 200 Depth : word; // always 8 Flags : word; // always 0 Speed : word; // # of jiffies to delay between frames (1/70s) Reserved : array[0..109] of byte; end; type TFliHeader = packed record Size : longint; // size of entire animation file Magic : word; // always $AF12 Frames : word; // Should be < 4000, doesn't include ring frame Width : word; Height : word; Depth : word; // always 8 Flags : word; // Set to 3 after ring frame is written and header // updated. Indicates that the file was properly // finished and closed Speed : longint; // # of miliseconds to delay between frames (1/1000s) Reserved1 : word; Created : longint; // MSDOS-formatted datetime of file's creation Creator : longint; // Serial # of fli creator (FlicLib = 'FLIB') Updated : longint; // MSDOS-formatted datetime of file's most recent update Updater : longint; // Serial # of fli updater (FlicLib = 'FLIB') AspectX : word; AspectY : word; // A 320x200 flic is usually 6:5 Reserved2 : array[0..37] of byte; oFrame1 : longint; // Offset from the beginning of the file to the first frame chunk oFrame2 : longint; // Offset from the beginning of the file to the 2nd frame chunk Reserved3 : array[0..39] of byte; end; type TFliPrefix = packed record Size : longint; Magic : word; Chunks : word; Reserved : array[0..7] of byte; end; type PFliFrame = ^TFliFrame; TFliFrame = packed record Size : longint; Magic : word; Chunks : word; Reserved : array[0..7] of byte; end; type TFliChunkGeneric = packed record Size : longint; Magic : word; end; type PFliChunk = ^TFliChunk; TFliChunk = TFliChunkGeneric; type PColorPacket = ^TColorPacket; TColorPacket = packed record Skip : byte; Count : byte; Rgb : array[0..0] of TDosRgb; end; PFliChunkColor256 = ^TFliChunkColor256; TFliChunkColor256 = // FLI_COLOR256: 256-level colors packed record Size : longint; Magic : word; Count : word; Packets : array[0..0] of TColorPacket; end; type // FLI_COLOR: 64-level colors PFliChunkColor = PFliChunkColor256; TFliChunkColor = TFliChunkColor256; type PFliChunkBlack = ^TFliChunkBlack; TFliChunkBlack = // FLI_BLACK: No data packed record Size : longint; Magic : word; end; type PFliChunkCopy = ^TFliChunkCopy; TFliChunkCopy = // FLI_COPY: No compression packed record Size : longint; Magic : word; Pixels : array[0..0] of byte; end; type TBRunPacket = packed record TypeSize : byte; Pixels : array[0..0] of byte; end; TBRunLinePacket = packed record Count : byte; // Not useful, just ignore this field Packets : array[0..0] of TBRunPacket; end; PFliChunkBRun = ^TFliChunkBRun; TFliChunkBRun = // FLI_BRUN: Byte run length compression packed record Size : longint; Magic : word; Lines : array[0..0] of TBRunLinePacket; end; type TLCPacket = packed record Skip : byte; TypeSize : byte; Pixels : array[0..0] of byte; end; TLCLinePacket = packed record x : byte; Count : byte; Packets : array[0..0] of TLCPacket; end; PFliChunkLC = ^TFliChunkLC; TFliChunkLC = // FLI_LC: Byte aligned delta compression packed record Size : longint; Magic : word; DeltaY : word; Count : word; Lines : array[0..0] of TLCLinePacket; end; type TSS2Packet = packed record Skip : byte; TypeSize : byte; Pixels : array[0..0] of word; end; TSS2HeaderPacket = packed record case TypeSize : word of 1 : // TypeSize & 3FFF has Packet Count (Packets : array[0..0] of TSS2Packet); 2 : // Low order byte is last byte of line (); 3 : // TypeSize & 3FFF has Line Skip Count (); end; TSS2LinePacket = packed record Header : array[0..0] of TSS2HeaderPacket; end; PFliChunkSS2 = ^TFliChunkSS2; TFliChunkSS2 = // FLI_SS2: Word aligned delta compression packed record Size : longint; Magic : word; Count : word; Lines : array[0..0] of TSS2LinePacket; end; type PStampChunkXlat256 = ^TStampChunkXlat256; TStampChunkXlat256 = // Color translation table packed record Size : longint; Magic : word; Table : array[0..255] of byte; end; type PFliChunkPStamp = ^TFliChunkPStamp; TFliChunkPStamp = // FLI_PSTAMP: Postage Stamp Image packed record Size : longint; Magic : word; Height : word; Width : word; xlate : word; end; const FliTimerResolution = 14; // 14.27ms = 1jiffie var SixCubePalette : T256LogPalette; procedure InitSixCubePalette; function SixCubeIndex( r, g, b : byte) : integer; implementation function SixCubeIndex( r, g, b : byte) : integer; begin Result := 10 + ((r * 6) div 256) * 36 + ((6 * g) div 256) * 6 + ((6 * b) div 256); end; procedure InitSixCubePalette; var r, g, b, i : byte; begin i := 10; for r := 0 to 5 do for g := 0 to 5 do for b := 0 to 5 do begin with SixCubePalette.Entries[i] do begin peRed := r * 256 div 6; peGreen := g * 256 div 6; peBlue := b * 256 div 6; peFlags := 0; end; inc( i); end; end; end.
unit SingleDriverRoute10StopsTestDataProviderUnit; interface uses SysUtils, BaseOptimizationParametersProviderUnit, AddressUnit, RouteParametersUnit, OptimizationParametersUnit; type TSingleDriverRoute10StopsTestDataProvider = class(TBaseOptimizationParametersProvider) protected function MakeAddresses(): TAddressesArray; override; function MakeRouteParameters(): TRouteParameters; override; procedure CorrectForResponse(OptimizationParameters: TOptimizationParameters); override; public end; implementation { TSingleDriverRoute10StopsTestDataProvider } uses DateUtils, EnumsUnit, UtilsUnit, JSONDictionaryIntermediateObjectUnit; type TAddressTag = record AddressString: String; Latitude, Longitude: double; constructor Create(AddressString: String; Latitude, Longitude: double); function Equals(Address: TAddress): boolean; end; var Addresses: TArray<TAddressTag>; function GetAddressIndexByTag(Tag: TAddressTag; Addresses: TAddressesArray): integer; var i: integer; begin Result := -1; for i := 0 to Length(Addresses) - 1 do if Tag.Equals(Addresses[i]) then Exit(i); end; procedure TSingleDriverRoute10StopsTestDataProvider.CorrectForResponse( OptimizationParameters: TOptimizationParameters); function Index(index: integer): integer; begin Result := GetAddressIndexByTag(Addresses[index], OptimizationParameters.Addresses); end; var RouteParameters: TRouteParameters; i: integer; begin inherited; RouteParameters := OptimizationParameters.Parameters.Value as TRouteParameters; RouteParameters.IsUpload := False; RouteParameters.RT := False; RouteParameters.DisableOptimization := False; RouteParameters.StoreRoute := True; RouteParameters.RouteDate := 0; RouteParameters.RouteMaxDuration := 86399; RouteParameters.TravelMode := TTravelMode.Driving; RouteParameters.Metric := TMetric.Matrix; RouteParameters.Parts := 10; RouteParameters.Dirm := 5; RouteParameters.DM := 1; RouteParameters.MemberId := '1'; RouteParameters.LockLast := False; RouteParameters.Avoid := TAvoid.Empty; RouteParameters.HasTrailer := False; RouteParameters.MinTourSize := 0; RouteParameters.OptimizationQuality := 1; RouteParameters.Ip := '2998453096'; OptimizationParameters.Addresses[Index(0)].RouteDestinationId := 193721035; OptimizationParameters.Addresses[Index(0)].MemberId := 1; OptimizationParameters.Addresses[Index(0)].CurbsideLatitude := 33.1326752; OptimizationParameters.Addresses[Index(0)].CurbsideLongitude := -83.2447433; OptimizationParameters.Addresses[Index(0)].SequenceNo := 0; OptimizationParameters.Addresses[Index(0)].DriveTimeToNextDestination := 48; OptimizationParameters.Addresses[Index(0)].DistanceToNextDestination := 0.21; OptimizationParameters.Addresses[Index(1)].RouteDestinationId := 193721036; OptimizationParameters.Addresses[Index(1)].MemberId := 1; OptimizationParameters.Addresses[Index(1)].CurbsideLatitude := 33.1296959; OptimizationParameters.Addresses[Index(1)].CurbsideLongitude := -83.2457733; OptimizationParameters.Addresses[Index(1)].SequenceNo := 1; OptimizationParameters.Addresses[Index(1)].IsDepot := False; OptimizationParameters.Addresses[Index(1)].RouteId := 'FC3D90EDECBAA80F46C37EAFBE4ADB36'; OptimizationParameters.Addresses[Index(1)].DriveTimeToNextDestination := 312; OptimizationParameters.Addresses[Index(1)].DistanceToNextDestination := 1.4; OptimizationParameters.Addresses[Index(1)].TrackingNumber := 'NR173QRE'; OptimizationParameters.Addresses[Index(1)].CustomFields := TDictionaryStringIntermediateObject.Create; OptimizationParameters.Addresses[Index(2)].RouteDestinationId := 193721037; OptimizationParameters.Addresses[Index(2)].MemberId := 1; OptimizationParameters.Addresses[Index(2)].CurbsideLatitude := 33.143497; OptimizationParameters.Addresses[Index(2)].CurbsideLongitude := -83.224487; OptimizationParameters.Addresses[Index(2)].SequenceNo := 8; OptimizationParameters.Addresses[Index(2)].IsDepot := False; OptimizationParameters.Addresses[Index(2)].RouteId := 'FC3D90EDECBAA80F46C37EAFBE4ADB36'; OptimizationParameters.Addresses[Index(2)].DriveTimeToNextDestination := 921; OptimizationParameters.Addresses[Index(2)].DistanceToNextDestination := 5.86; OptimizationParameters.Addresses[Index(2)].TrackingNumber := 'X70P9K70'; OptimizationParameters.Addresses[Index(2)].CustomFields := TDictionaryStringIntermediateObject.Create; OptimizationParameters.Addresses[Index(3)].RouteDestinationId := 193721038; OptimizationParameters.Addresses[Index(3)].MemberId := 1; OptimizationParameters.Addresses[Index(3)].CurbsideLatitude := 33.1417847; OptimizationParameters.Addresses[Index(3)].CurbsideLongitude := -83.2375183; OptimizationParameters.Addresses[Index(3)].SequenceNo := 3; OptimizationParameters.Addresses[Index(3)].IsDepot := False; OptimizationParameters.Addresses[Index(3)].RouteId := 'FC3D90EDECBAA80F46C37EAFBE4ADB36'; OptimizationParameters.Addresses[Index(3)].DriveTimeToNextDestination := 29; OptimizationParameters.Addresses[Index(3)].DistanceToNextDestination := 0.13; OptimizationParameters.Addresses[Index(3)].TrackingNumber := 'Q76PXM7V'; OptimizationParameters.Addresses[Index(3)].CustomFields := TDictionaryStringIntermediateObject.Create; OptimizationParameters.Addresses[Index(4)].RouteDestinationId := 193721039; OptimizationParameters.Addresses[Index(4)].MemberId := 1; OptimizationParameters.Addresses[Index(4)].CurbsideLatitude := 33.1410866; OptimizationParameters.Addresses[Index(4)].CurbsideLongitude := -83.2382584; OptimizationParameters.Addresses[Index(4)].SequenceNo := 7; OptimizationParameters.Addresses[Index(4)].IsDepot := False; OptimizationParameters.Addresses[Index(4)].RouteId := 'FC3D90EDECBAA80F46C37EAFBE4ADB36'; OptimizationParameters.Addresses[Index(4)].DriveTimeToNextDestination := 380; OptimizationParameters.Addresses[Index(4)].DistanceToNextDestination := 1.85; OptimizationParameters.Addresses[Index(4)].TrackingNumber := 'RQEPR8QN'; OptimizationParameters.Addresses[Index(4)].CustomFields := TDictionaryStringIntermediateObject.Create; OptimizationParameters.Addresses[Index(5)].RouteDestinationId := 193721040; OptimizationParameters.Addresses[Index(5)].MemberId := 1; OptimizationParameters.Addresses[Index(5)].CurbsideLatitude := 33.1420364; OptimizationParameters.Addresses[Index(5)].CurbsideLongitude := -83.2388458; OptimizationParameters.Addresses[Index(5)].SequenceNo := 6; OptimizationParameters.Addresses[Index(5)].IsDepot := False; OptimizationParameters.Addresses[Index(5)].RouteId := 'FC3D90EDECBAA80F46C37EAFBE4ADB36'; OptimizationParameters.Addresses[Index(5)].DriveTimeToNextDestination := 14; OptimizationParameters.Addresses[Index(5)].DistanceToNextDestination := 0.06; OptimizationParameters.Addresses[Index(5)].TrackingNumber := 'Y3NPGE3Q'; OptimizationParameters.Addresses[Index(5)].CustomFields := TDictionaryStringIntermediateObject.Create; OptimizationParameters.Addresses[Index(6)].RouteDestinationId := 193721041; OptimizationParameters.Addresses[Index(6)].MemberId := 1; OptimizationParameters.Addresses[Index(6)].CurbsideLatitude := 33.14307; OptimizationParameters.Addresses[Index(6)].CurbsideLongitude := -83.239334; OptimizationParameters.Addresses[Index(6)].SequenceNo := 5; OptimizationParameters.Addresses[Index(6)].IsDepot := False; OptimizationParameters.Addresses[Index(6)].RouteId := 'FC3D90EDECBAA80F46C37EAFBE4ADB36'; OptimizationParameters.Addresses[Index(6)].DriveTimeToNextDestination := 24; OptimizationParameters.Addresses[Index(6)].DistanceToNextDestination := 0.11; OptimizationParameters.Addresses[Index(6)].TrackingNumber := 'ZLDPVNLY'; OptimizationParameters.Addresses[Index(6)].CustomFields := TDictionaryStringIntermediateObject.Create; OptimizationParameters.Addresses[Index(7)].RouteDestinationId := 193721042; OptimizationParameters.Addresses[Index(7)].MemberId := 1; OptimizationParameters.Addresses[Index(7)].CurbsideLatitude := 33.1427345; OptimizationParameters.Addresses[Index(7)].CurbsideLongitude := -83.237442; OptimizationParameters.Addresses[Index(7)].SequenceNo := 2; OptimizationParameters.Addresses[Index(7)].IsDepot := False; OptimizationParameters.Addresses[Index(7)].RouteId := 'FC3D90EDECBAA80F46C37EAFBE4ADB36'; OptimizationParameters.Addresses[Index(7)].DriveTimeToNextDestination := 0; OptimizationParameters.Addresses[Index(7)].DistanceToNextDestination := 0; OptimizationParameters.Addresses[Index(7)].TrackingNumber := 'PLKP0DLM'; OptimizationParameters.Addresses[Index(7)].CustomFields := TDictionaryStringIntermediateObject.Create; OptimizationParameters.Addresses[Index(8)].RouteDestinationId := 193721043; OptimizationParameters.Addresses[Index(8)].MemberId := 1; OptimizationParameters.Addresses[Index(8)].CurbsideLatitude := 33.1438713; OptimizationParameters.Addresses[Index(8)].CurbsideLongitude := -83.2373428; OptimizationParameters.Addresses[Index(8)].SequenceNo := 4; OptimizationParameters.Addresses[Index(8)].IsDepot := False; OptimizationParameters.Addresses[Index(8)].RouteId := 'FC3D90EDECBAA80F46C37EAFBE4ADB36'; OptimizationParameters.Addresses[Index(8)].DriveTimeToNextDestination := 44; OptimizationParameters.Addresses[Index(8)].DistanceToNextDestination := 0.2; OptimizationParameters.Addresses[Index(8)].TrackingNumber := 'LGM3KQGK'; OptimizationParameters.Addresses[Index(8)].CustomFields := TDictionaryStringIntermediateObject.Create; OptimizationParameters.Addresses[Index(9)].RouteDestinationId := 193721044; OptimizationParameters.Addresses[Index(9)].MemberId := 1; OptimizationParameters.Addresses[Index(9)].CurbsideLatitude := 33.0814629; OptimizationParameters.Addresses[Index(9)].CurbsideLongitude := -83.2085114; OptimizationParameters.Addresses[Index(9)].SequenceNo := 9; OptimizationParameters.Addresses[Index(9)].IsDepot := False; OptimizationParameters.Addresses[Index(9)].RouteId := 'FC3D90EDECBAA80F46C37EAFBE4ADB36'; OptimizationParameters.Addresses[Index(9)].TrackingNumber := 'DQ9MGE6V'; OptimizationParameters.Addresses[Index(9)].CustomFields := TDictionaryStringIntermediateObject.Create; for i := 0 to 9 do begin OptimizationParameters.Addresses[Index(i)].OptimizationProblemId := 'E589A245F11E3E1E82457703BFAAB14D'; OptimizationParameters.Addresses[Index(i)].TimeframeViolationTime := 0; OptimizationParameters.Addresses[Index(i)].TimeframeViolationRate := 0; OptimizationParameters.Addresses[Index(i)].AddressStopType := astDelivery; OptimizationParameters.Addresses[Index(i)].Geocoded := False; OptimizationParameters.Addresses[Index(i)].FailedGeocoding := False; OptimizationParameters.Addresses[Index(i)].IsVisited := False; OptimizationParameters.Addresses[Index(i)].IsDeparted := False; OptimizationParameters.Addresses[Index(i)].Weight := 0; OptimizationParameters.Addresses[Index(i)].Cost := 0; OptimizationParameters.Addresses[Index(i)].Revenue := 0; OptimizationParameters.Addresses[Index(i)].Cube := 0; OptimizationParameters.Addresses[Index(i)].Pieces := 0; OptimizationParameters.Addresses[Index(i)].DestinationNoteCount := 0; end; // OptimizationParameters.Addresses[Index(9)].CustomFields := TDictionaryStringIntermediateObject.Create; end; function TSingleDriverRoute10StopsTestDataProvider.MakeAddresses: TAddressesArray; var FirstAddress: TAddress; i: integer; begin Result := TAddressesArray.Create(); FirstAddress := TAddress.Create( Addresses[0].AddressString, Addresses[0].Latitude, Addresses[0].Longitude, 0); //indicate that this is a departure stop // single depot routes can only have one departure depot FirstAddress.IsDepot := True; // input as many custom fields as needed, custom data is passed through to mobile devices and to the manifest FirstAddress.AddCustomField('color', 'red'); FirstAddress.AddCustomField('size', 'huge'); AddAddress(FirstAddress, Result); for i := 1 to High(Addresses) do AddAddress(TAddress.Create( Addresses[i].AddressString, Addresses[i].Latitude, Addresses[i].Longitude, 0), Result); end; function TSingleDriverRoute10StopsTestDataProvider.MakeRouteParameters: TRouteParameters; begin Result := TRouteParameters.Create(); Result.AlgorithmType := TAlgorithmType.TSP; Result.StoreRoute := False; Result.RouteName := 'Single Driver Route 10 Stops'; Result.RouteDate := 53583232;//TUtils.ConvertToUnixTimestamp(IncDay(Now, 1)); Result.RouteTime := 60 * 60 * 7; Result.Optimize := TOptimize.Distance; Result.DistanceUnit := TDistanceUnit.MI; Result.DeviceType := TDeviceType.Web; end; { TAddressTag } constructor TAddressTag.Create(AddressString: String; Latitude, Longitude: double); begin Self.AddressString := AddressString; Self.Latitude := Latitude; Self.Longitude := Longitude; end; function TAddressTag.Equals(Address: TAddress): boolean; begin Result := (AddressString = Address.AddressString) and (Latitude = Address.Latitude) and (Longitude = Address.Longitude); end; initialization SetLength(Addresses, 10); Addresses[0] := TAddressTag.Create('151 Arbor Way Milledgeville GA 31061', 33.132675170898, -83.244743347168); Addresses[1] := TAddressTag.Create('230 Arbor Way Milledgeville GA 31061', 33.129695892334, -83.24577331543); Addresses[2] := TAddressTag.Create('148 Bass Rd NE Milledgeville GA 31061', 33.143497, -83.224487); Addresses[3] := TAddressTag.Create('117 Bill Johnson Rd NE Milledgeville GA 31061', 33.141784667969, -83.237518310547); Addresses[4] := TAddressTag.Create('119 Bill Johnson Rd NE Milledgeville GA 31061', 33.141086578369, -83.238258361816); Addresses[5] := TAddressTag.Create('131 Bill Johnson Rd NE Milledgeville GA 31061', 33.142036437988, -83.238845825195); Addresses[6] := TAddressTag.Create('138 Bill Johnson Rd NE Milledgeville GA 31061', 33.14307, -83.239334); Addresses[7] := TAddressTag.Create('139 Bill Johnson Rd NE Milledgeville GA 31061', 33.142734527588, -83.237442016602); Addresses[8] := TAddressTag.Create('145 Bill Johnson Rd NE Milledgeville GA 31061', 33.143871307373, -83.237342834473); Addresses[9] := TAddressTag.Create('221 Blake Cir Milledgeville GA 31061', 33.081462860107, -83.208511352539); end.
unit z80daisy; interface type tipo_z80_daisy=record ack:function(n:byte):byte; reti:procedure(n:byte); state:function(n:byte):byte; device_num:byte; end; const Z80_DAISY_INT=$01; // interrupt request mask */ Z80_DAISY_IEO=$02; // interrupt disable mask (IEO) */ Z80_PIO_TYPE=0; Z80_CTC0_TYPE=$10; Z80_DAISY_NONE=$FF; Z80_MAX_DAISY=3-1; var z80daisy_llamadas:array[0..Z80_MAX_DAISY] of tipo_z80_daisy; z80daisy_num_dev:integer; function z80daisy_ack:byte; procedure z80daisy_reti; function z80daisy_state:boolean; procedure z80daisy_init(tipo0:byte=Z80_DAISY_NONE;tipo1:byte=Z80_DAISY_NONE;tipo2:byte=Z80_DAISY_NONE;numero0:byte=0;numero1:byte=0;numero2:byte=0); implementation uses z80pio,z80ctc; procedure poner_llamadas_por_tipo(pos,tipo:byte); begin case tipo of Z80_PIO_TYPE:begin z80daisy_llamadas[pos].ack:=z80pio_irq_ack; z80daisy_llamadas[pos].reti:=z80pio_irq_reti; z80daisy_llamadas[pos].state:=z80pio_irq_state; end; Z80_CTC0_TYPE:begin z80daisy_llamadas[pos].state:=ctc0_irq_state; z80daisy_llamadas[pos].ack:=ctc0_irq_ack; z80daisy_llamadas[pos].reti:=ctc0_irq_reti; end; Z80_DAISY_NONE:begin z80daisy_llamadas[pos].ack:=nil; z80daisy_llamadas[pos].reti:=nil; z80daisy_llamadas[pos].state:=nil; end; end; end; procedure z80daisy_init(tipo0,tipo1,tipo2:byte;numero0,numero1,numero2:byte); begin poner_llamadas_por_tipo(0,tipo0); z80daisy_llamadas[0].device_num:=numero0; if tipo0<>Z80_DAISY_NONE then z80daisy_num_dev:=0 else z80daisy_num_dev:=-1; poner_llamadas_por_tipo(1,tipo1); z80daisy_llamadas[1].device_num:=numero1; if tipo1<>Z80_DAISY_NONE then z80daisy_num_dev:=z80daisy_num_dev+1; poner_llamadas_por_tipo(2,tipo2); z80daisy_llamadas[2].device_num:=numero2; if tipo2<>Z80_DAISY_NONE then z80daisy_num_dev:=z80daisy_num_dev+1; end; function z80daisy_ack:byte; var f,state:byte; begin for f:=0 to z80daisy_num_dev do begin if @z80daisy_llamadas[f].state<>nil then begin state:=z80daisy_llamadas[f].state(z80daisy_llamadas[f].device_num); if (state and Z80_DAISY_INT)<>0 then begin z80daisy_ack:=z80daisy_llamadas[f].ack(z80daisy_llamadas[f].device_num); exit; end; end; end; z80daisy_ack:=$ff; end; procedure z80daisy_reti; var f,state:byte; begin // loop over all devices; dev[0] is highest priority */ for f:=0 to z80daisy_num_dev do begin if @z80daisy_llamadas[f].state<>nil then begin state:=z80daisy_llamadas[f].state(z80daisy_llamadas[f].device_num); //if this device is asserting the IEO line, that's the one we want */ if (state and Z80_DAISY_IEO)<>0 then begin z80daisy_llamadas[f].reti(z80daisy_llamadas[f].device_num); exit; end; end; end; end; function z80daisy_state:boolean; var f,state:byte; begin for f:=0 to z80daisy_num_dev do begin if @z80daisy_llamadas[f].state<>nil then begin state:=z80daisy_llamadas[f].state(z80daisy_llamadas[f].device_num); // if this device is asserting the INT line, that's the one we want */ if (state and Z80_DAISY_INT)<>0 then begin z80daisy_state:=true; exit; end; // if this device is asserting the IEO line, it blocks everyone else */ if (state and Z80_DAISY_IEO)<>0 then begin z80daisy_state:=false; exit; end; end; end; z80daisy_state:=false; end; end.
Program playcmfp; {*************************************************************************** * Programme de d‚monstration pour l'Unit‚ CMFTOOL, (W) en Turbo-Pascal 6.0* *************************************************************************** * (C) 1992 MICRO APPLICATION * * Auteur : Axel Stolz * *************************************************************************** * La limite haute de la m‚moire du programme principal doit ˆtre * * diminu‚e sinon tout l'espace m‚moire disponible sera utilis‚, ne * * laissant plus suffisamment de place pour le driver et l'‚chantillon * * num‚rique * *************************************************************************** } {$M 16384,0,65535} Uses CMFTool,Crt; VAR Check : BOOLEAN; { flag pour test bool‚en } SongName : String; { nom du fichier CMF sous forme string } SongBuffer : CMFDataTyp; { buffer de donn‚es pour le fichier CMF } PROCEDURE Erreur; { * ENTRE : aucune, les donn‚es proviennent de la variable globale * CMFErrStat * SORTIE : aucune * FONCTION : Affiche le type d'erreur venant de se produire avec le * num‚ro d'erreur. Termine le programme avec le niveau * d'erreur correspondant au num‚ro. } BEGIN Write('Erreur #',CMFErrStat:3,' ='); PrintCMFErrMessage; WriteLn; HALT(CMFErrStat); END; BEGIN ClrScr; { sortir une erreur lorsque le driver SBFMDRV n'est pas install‚ } IF Not (CMFDriverInstalled) THEN Erreur; GotoXY(25,5); Write (' SBFMDRV Version ',Hi(CMFGetVersion):2,'.'); WriteLn(Lo(CMFGetVersion):2,' est charg‚.'); { transmet le num‚ro de version utilis‚ } GotoXY(15,8); Write ('Le driver utilise l''interruption systŠme (IRQ) nø. '); WriteLn(CMFDriverIRQ:3); writeln;writeln; write('Nom du fichier CMF … ‚couter : '); readln(SongName); { Chargement du fichier du morceau d‚sir‚ } Check := CMFGetSongBuffer(SongBuffer,SongName); IF NOT(Check) THEN Erreur; {Ici vous pouvez transposer le morceau charg‚ vers le haut ou le bas, suivant que la valeur transmise est positive ou n‚gative. La valeur 0 indique que le morceau doit ˆtre jou‚ avec la tonalit‚ d'origine. } CMFSetTransposeOfs(0); { vous pouvez exp‚rimenter avec des valeurs } { diffusion du morceau } Check := CMFPlaySong(SongBuffer); IF NOT(Check) THEN Erreur; GotoXY(37,16); WriteLn('Song-Status'); { Pendant la diffusion du morceau, transmet en permanence le status-byte } REPEAT GotoXY(41,17);Write(CMFStatusByte:3); UNTIL (KeyPressed OR (CMFStatusByte = 0)); { Si une touche a ‚t‚ appuy‚e, alors interrompre le morceau } IF KeyPressed THEN BEGIN Check := CMFStopSong; ClrScr; IF NOT(Check) THEN Erreur; END; { Remettre le driver dans son ‚tat de mise en service } Check := CMFResetDriver; IF NOT(Check) THEN Erreur; { Lib‚rer … nouveau la m‚moire occup‚e par le fichier du morceau } Check := CMFFreeSongBuffer(SongBuffer); IF NOT(Check) THEN Erreur; END.
unit RegisterAccountResponseUnit; interface uses REST.Json.Types, GenericParametersUnit, NullableBasicTypesUnit, JSONNullableAttributeUnit, CommonTypesUnit; type TRegisterAccountResponse = class(TGenericParameters) private [JSONName('status')] FStatus: boolean; [JSONName('session_id')] [Nullable] FSessionId: NullableString; [JSONName('session_guid')] [Nullable] FSessionGuid: NullableString; [JSONName('member_id')] [Nullable] FMemberId: NullableInteger; [JSONName('api_key')] [Nullable] FApiKey: NullableString; [JSONName('account_type_id')] [Nullable] FAccountTypeId: NullableInteger; [JSONName('account_type_alias')] [Nullable] FAccountTypeAlias: NullableInteger; [JSONName('max_stops_per_route')] [Nullable] FMaxStopsPerRoute: NullableInteger; [JSONName('max_routes')] [Nullable] FMaxRoutes: NullableInteger; [JSONName('routes_planned')] [Nullable] FRoutesPlanned: NullableInteger; [JSONName('errors')] FErrors: TStringArray; public constructor Create; override; property Status: boolean read FStatus write FStatus; property SessionId: NullableString read FSessionId write FSessionId; property SessionGuid: NullableString read FSessionGuid write FSessionGuid; property MemberId: NullableInteger read FMemberId write FMemberId; property ApiKey: NullableString read FApiKey write FApiKey; property AccountTypeId: NullableInteger read FAccountTypeId write FAccountTypeId; property AccountTypeAlias: NullableInteger read FAccountTypeAlias write FAccountTypeAlias; property MaxStopsPerRoute: NullableInteger read FMaxStopsPerRoute write FMaxStopsPerRoute; property MaxRoutes: NullableInteger read FMaxRoutes write FMaxRoutes; property RoutesPlanned: NullableInteger read FRoutesPlanned write FRoutesPlanned; property Errors: TStringArray read FErrors write FErrors; end; implementation constructor TRegisterAccountResponse.Create; begin inherited; SetLength(FErrors, 0); FSessionId := NullableString.Null; FSessionGuid := NullableString.Null; FMemberId := NullableInteger.Null; FApiKey := NullableString.Null; FAccountTypeId := NullableInteger.Null; FAccountTypeAlias := NullableInteger.Null; FMaxStopsPerRoute := NullableInteger.Null; FMaxRoutes := NullableInteger.Null; FRoutesPlanned := NullableInteger.Null; end; end.
{ Subroutine SST_R_SYO_JTARGETS_MAKE (TARG_IN, TARG_OUT, MOD_YES, MOD_NO, MOD_ERR) * * Create subordinate jump targets in TARG_OUT, using the existing jump targets * TARG_IN as a template. The MOD_xxx arguments specify modifications from * the template for the yes, no, and error cases. The modifier arguments * are SST symbol pointers. These are either actual pointers to label * symbols, or one of the special "symbol" pointers LAB_xxx_K in the * SST_R_SYO common block. A pointer to a real label symbol indicates that * label is the jump target. The special pointer values have the following * meanings: * * LAB_FALL_K - The jump target is to fall thru. No jump is required. * * LAB_SAME_K - The jump target will be an indirect reference to the * corresponding one in TARG_IN. } module sst_r_syo_jtargets_make; define sst_r_syo_jtargets_make; %include 'sst_r_syo.ins.pas'; procedure sst_r_syo_jtargets_make ( {make new jump targets from old and modifiers} in targ_in: jump_targets_t; {old jump targets} out targ_out: jump_targets_t; {resulting new jump targets} in mod_yes: sst_symbol_p_t; {modifier for YES branch} in mod_no: sst_symbol_p_t; {modifier for NO branch} in mod_err: sst_symbol_p_t); {modifier for ERR branch} val_param; { ********************************** * * Local subroutine DO_TARGET (JTI, JTO, JMOD) * * Create individual jump target JTO from template JTI with modifier JMOD. } procedure do_target ( in jti_p: jump_target_p_t; {pointer to template jump target} out jto: jump_target_t; {output jump_target} in jmod: sst_symbol_p_t); {modifier to apply from template to output} val_param; begin { * Handle "same" modifier case. } if jmod = lab_same_k then begin {modifier is "same" ?} jto.flags := jti_p^.flags + [jflag_indir_k]; jto.indir_p := jti_p; return; end; { * Handle "fall thru" modifier case. } if jmod = lab_fall_k then begin {modifier is "fall thru" ?} jto.flags := [jflag_fall_k, jflag_mfset_k]; jto.lab_p := nil; return; end; { * Modifier is explicit label. } jto.flags := [jflag_mfset_k]; jto.lab_p := jmod; end; { ********************************** * * Start of main routine. } begin do_target (addr(targ_in.yes), targ_out.yes, mod_yes); {do YES case} do_target (addr(targ_in.no), targ_out.no, mod_no); {do NO case} do_target (addr(targ_in.err), targ_out.err, mod_err); {do ERR case} end;
unit ProcessDemoMainForm; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, Buttons, StdCtrls, ExtCtrls, Process, LCLProc, ComCtrls; type { TMultipleProcessDemoForm } TMultipleProcessDemoForm = class(TForm) Process2:TProcess; Process2GroupBox:TGroupBox; Process2InputLabel:TLabel; Process2InputMemo:TMemo; Process2OutputLabel:TLabel; Process2OutputMemo:TMemo; Process2SendInputButton:TButton; Process2StartButton:TButton; CommandLine2LabeledEdit:TLabeledEdit; ReadOutputIdleTimer:TIdleTimer; Process1:TProcess; Process1SendInputButton:TButton; Process1StartButton:TButton; CloseButton:TButton; CommandLine1LabeledEdit:TLabeledEdit; Process1InputLabel:TLabel; Process1OutputLabel1:TLabel; Process1InputMemo:TMemo; Process1GroupBox1:TGroupBox; Process1OutputMemo:TMemo; ProcessPanel:TPanel; ProcessSplitter:TSplitter; StatusBar1:TStatusBar; procedure CloseButtonClick(Sender:TObject); procedure MultipleProcessDemoFormClose(Sender:TObject; var CloseAction:TCloseAction); procedure ProcessSendInputButtonClick(Sender:TObject); procedure ProcessStartButtonClick(Sender:TObject); procedure ReadOutputIdleTimerTimer(Sender:TObject); private { private declarations } procedure StartProcess(Process: TProcess; StartButton: TButton; const CommandLine: string); procedure SendInput(Process: TProcess; InputMemo: TMemo); public { public declarations } end; var MultipleProcessDemoForm: TMultipleProcessDemoForm; implementation { TMultipleProcessDemoForm } procedure TMultipleProcessDemoForm.CloseButtonClick(Sender:TObject); begin Close; end; procedure TMultipleProcessDemoForm.MultipleProcessDemoFormClose(Sender:TObject; var CloseAction:TCloseAction); begin if Process1.Running then Process1.Terminate(0); if Process2.Running then Process2.Terminate(0); end; procedure TMultipleProcessDemoForm.ProcessSendInputButtonClick(Sender:TObject); begin if Sender=Process1SendInputButton then SendInput(Process1, Process1InputMemo); if Sender=Process2SendInputButton then SendInput(Process2, Process2InputMemo); end; procedure TMultipleProcessDemoForm.ProcessStartButtonClick(Sender:TObject); begin if Sender=Process1StartButton then StartProcess(Process1, Process1StartButton, CommandLine1LabeledEdit.Text); if Sender=Process2StartButton then StartProcess(Process2, Process2StartButton, CommandLine2LabeledEdit.Text); end; procedure TMultipleProcessDemoForm.ReadOutputIdleTimerTimer(Sender:TObject); var NoMoreOutput: boolean; procedure DoStuffForProcess(Process: TProcess; StartButton: TButton; OutputMemo: TMemo); var Buffer: string; BytesAvailable: DWord; BytesRead:LongInt; begin if not StartButton.Enabled then StartButton.Enabled := not Process.Running; if Process.Running then begin BytesAvailable := Process.Output.NumBytesAvailable; BytesRead := 0; while BytesAvailable>0 do begin SetLength(Buffer, BytesAvailable); BytesRead := Process.OutPut.Read(Buffer[1], BytesAvailable); OutputMemo.Text := OutputMemo.Text + copy(Buffer,1, BytesRead); BytesAvailable := Process.Output.NumBytesAvailable; NoMoreOutput := false; end; if BytesRead>0 then OutputMemo.SelStart := Length(OutputMemo.Text); end; end; begin repeat NoMoreOutput := true; DoStuffForProcess(Process1, Process1StartButton, Process1OutputMemo); DoStuffForProcess(Process2, Process2StartButton, Process2OutputMemo); until noMoreOutput; end; procedure TMultipleProcessDemoForm.StartProcess(Process:TProcess; StartButton: TButton; const CommandLine: string); begin if not Process.Running then begin StartButton.Enabled := false; Process.CommandLine := CommandLine; Process.Execute; end; end; procedure TMultipleProcessDemoForm.SendInput(Process:TProcess;InputMemo:TMemo); var InputStrings: string; begin if Process.Running then begin InputStrings := InputMemo.Lines.Text; Process.Input.Write(InputStrings[1], length(InputStrings)); end; end; initialization {$I processdemomainform.lrs} end.
unit ReachMatrix; interface const rchNone = 0; rchRoad = 1; rchReach = 2; type TReachMapArray = array[0..99] of byte; PReachMapArray = ^TReachMapArray; type TReachMatrix = class public constructor Create(rCnt, cCnt : integer); private fRows : integer; fCols : integer; fMatrix : PReachMapArray; private function GetElem(i, j : integer) : byte; procedure SetElem(i, j : integer; value : byte); public procedure Fill(value : byte); public property Elems[i, j : integer] : byte read GetElem write SetElem; default; end; implementation // TReachMatrix constructor TReachMatrix.Create(rCnt, cCnt : integer); begin fRows := rCnt; fCols := cCnt; ReallocMem(fMatrix, rCnt*cCnt*sizeof(fMatrix[0])); Fill(rchNone); end; function TReachMatrix.GetElem(i, j : integer) : byte; begin if (i >= 0) and (j >= 0) and (i < fRows) and (j < fCols) then result := fMatrix[i*fCols + j] else result := 0; end; procedure TReachMatrix.SetElem(i, j : integer; value : byte); begin if (i >= 0) and (j >= 0) and (i < fRows) and (j < fCols) then fMatrix[i*fCols + j] := value; end; procedure TReachMatrix.Fill(value : byte); begin FillChar(fMatrix^, fRows*fCols*sizeof(fMatrix[0]), value); end; end.
unit evButton; { Библиотека "Эверест" } { Автор: Люлин А.В. } { Модуль: evButton - } { Начат: 07.10.1998 15:39 } { $Id: evButton.pas,v 1.25 2013/12/09 14:09:17 fireton Exp $ } // $Log: evButton.pas,v $ // Revision 1.25 2013/12/09 14:09:17 fireton // - без этого модуля не собираются проекты Архивариуса // // Revision 1.23 2012/08/29 14:48:49 kostitsin // [$378542059], // [$378560607] // // Revision 1.22 2012/08/29 13:21:30 kostitsin // [$378542059] // // Revision 1.21 2007/12/04 12:46:59 lulin // - перекладываем ветку в HEAD. // // Revision 1.18.14.5 2007/04/20 13:24:03 lulin // - не пишем мусор. // // Revision 1.18.14.4 2007/04/20 11:07:19 lulin // - убираем ненужную функциональность. // // Revision 1.18.14.3 2007/04/20 09:06:04 lulin // - убираем ненужную функциональность. // // Revision 1.18.14.2 2007/04/02 06:34:02 lulin // - вычищено ненужное свойство. // // Revision 1.18.14.1 2007/01/05 14:37:18 lulin // - cleanup. // // Revision 1.18 2004/11/30 13:31:36 mmorozov // new: published property TevButton.AutoSize; // // Revision 1.17 2004/09/14 09:14:20 lulin // - cleanup: редко используемые поля убраны под define'ы. // - упорядочено наследование. // - поправлены имена. // // Revision 1.16 2004/09/13 15:50:24 lulin // - cleanup: выкинул лишний модуль из Toolbar 97. // - bug fix: за Мишей - не компилировался VCM. // // Revision 1.15 2003/12/26 16:51:12 law // - new behavior: переделана логика обработки BottonCombo - теперь если меню нету, то и стрелки вниз нету. // - bug fix: иногда при восстановлении из истории портился Caption главного окна. // // Revision 1.14 2003/08/01 11:46:04 law // - bug fix: не "залипали" кнопки. // // Revision 1.13 2001/10/05 11:39:24 law // - cleanup: убрано восстановление ImageIndex. // // Revision 1.12 2001/10/04 16:01:49 law // - new behavior: в _TevCustomButton теперь используются TevCustomAction. // // Revision 1.11 2001/09/21 09:58:54 law // - cleanup. // // Revision 1.10 2001/08/29 07:59:54 law // - new behavior: добавлены свойства по умолчанию. // // Revision 1.9 2001/06/25 16:20:44 voba // - new behavior: свойство Enabled теперь сохраняется для операции ev_ccNone. // // Revision 1.8 2001/04/13 08:28:59 law // - new behavior: по другому сделана обработка стандаотных операций. // // Revision 1.7 2000/12/19 15:52:40 law // - убраны ненужные директивы компиляции. // // Revision 1.6 2000/12/15 15:10:34 law // - вставлены директивы Log. // {$Include evDefine.inc } {$Include TB97Ver.inc} interface uses Classes, Controls, tb97Ctls, l3Types {$IfDef evNeedDisp} , evStandardActions {$EndIf evNeedDisp} ; type TevCustomButton = class(TCustomToolbarButton97) protected // internal methods function GlyphStored: Bool; override; {-} function GlyphMaskStored: Boolean; override; {-} protected // property methods {$IfDef evNeedDisp} function pm_GetOperation: TevOperation; procedure pm_SetOperation(Value: TevOperation); {-} {$EndIf evNeedDisp} protected // internal methods function EnabledStored: Bool; {-} procedure DoClick; override; {-} function GetActionLinkClass: TControlActionLinkClass; override; {-} procedure ActionChange(Sender: TObject; CheckDefaults: Boolean); override; {-} function HackCheck: Boolean; virtual; {-} public // public methods constructor Create(anOwner: TComponent); override; {-} public /// public properties {$IfDef evNeedDisp} property Operation: TevOperation read pm_GetOperation write pm_SetOperation default ev_ccNone; {-} {$EndIf evNeedDisp} property Enabled stored EnabledStored; {-} property Glyph; {-} property GlyphMask; {-} property DisplayMode default dmGlyphOnly; {-} published // published properties property Top default 0; {-} property Width default 23; {-} property Height default 23; {-} end;//TevCustomButton TevCustomButtonActionLink = class(TToolbarButton97ActionLink, IUnknown) protected // internal methods // IUnknown function _AddRef: Integer; stdcall; {* - реализация метода _AddRef интерфейса IUnknown, увеличивает число ссылок на объект. } function _Release: Integer; stdcall; {* - реализация метода _Release интерфейса IUnknown, уменьшает число ссылок на объект и уничтожает его, если число ссылок становится = 0. } function QueryInterface(const IID: TGUID; out Obj): HResult; virtual; stdcall; {-} protected // internal methods procedure SetHint(const Value: string); override; {-} end;//TevCustomButtonActionLink TevButton = class(TevCustomButton) published property AutoSize; {$IfDef evNeedDisp} property Operation; {$EndIf evNeedDisp} property Hint; {$IFDEF Delphi4} property Action; {$ENDIF} property Alignment; property AllowAllUp; {$IFDEF Delphi4} property Anchors; {$ENDIF} property Cancel; property Color; {$IFDEF Delphi4} property Constraints; {$ENDIF} property GroupIndex; property Default; property DisplayMode; property Down; property DragCursor; property DragMode; property DropdownAlways; property DropdownArrow; property DropdownArrowWidth; property DropdownCombo; property DropdownMenu; property Caption; property Enabled; property Flat; property Font; property Glyph; property GlyphMask; property HelpContext; property ImageIndex; property Images; property Layout; property Margin; property ModalResult; property NoBorder; property NumGlyphs; property Opaque; property ParentFont; property ParentColor; property ParentShowHint; {$IfDef tb97NeedRepeating} property Repeating; property RepeatDelay; property RepeatInterval; {$EndIf tb97NeedRepeating} property ShowBorderWhenInactive; property ShowHint; property Spacing; property Visible; property WordWrap; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; {$IfDef tb97NeedOnDropdown} property OnDropdown; {$EndIf tb97NeedOnDropdown} property OnEndDrag; property OnMouseDown; {$IfDef tb97NeedMouseEvents} property OnMouseEnter; property OnMouseExit; {$EndIf tb97NeedMouseEvents} property OnMouseMove; property OnMouseUp; property OnStartDrag; end;//TevButton implementation uses ActnList {$IfDef evNeedDisp} , evAction, evDisp {$EndIf evNeedDisp} ; { start class TevCustomButton } constructor TevCustomButton.Create(anOwner: TComponent); //override; {-} begin inherited; Width := 23; Height := 23; DisplayMode := dmGlyphOnly; end; function TevCustomButton.GlyphStored: Bool; {-} begin Result := inherited GlyphStored AND ((Images = nil) OR (ImageIndex < 0)); end; function TevCustomButton.GlyphMaskStored: Boolean; //override; {-} begin Result := inherited GlyphMaskStored AND ((Images = nil) OR (ImageIndex < 0)); end; {$IfDef evNeedDisp} function TevCustomButton.pm_GetOperation: TevOperation; {-} begin if (Action Is TevCustomAction) then Result := TevCustomAction(Action).Operation else Result := ev_ccNone; end; procedure TevCustomButton.pm_SetOperation(Value: TevOperation); {-} begin if (Operation <> Value) then Action := evOperationDispatcher.GetAction(Value); end; {$EndIf evNeedDisp} function TevCustomButton.HackCheck: Boolean; //virtual; {-} begin Result := true; end; procedure TevCustomButton.DoClick; //override; {-} var l_Checked : Bool; begin if (Action = nil) then inherited else begin l_Checked := Down; Action.Tag := Tag; inherited; if HackCheck then Down := l_Checked; end; end; function TevCustomButton.GetActionLinkClass: TControlActionLinkClass; //override; {-} begin Result := TevCustomButtonActionLink; end; function TevCustomButton.EnabledStored: Bool; {-} begin {$IfDef evNeedDisp} Result := (Operation = ev_ccNone); {$Else evNeedDisp} Result := true; {$EndIf evNeedDisp} end; procedure TevCustomButton.ActionChange(Sender: TObject; CheckDefaults: Boolean); //override; {-} {$IfDef evNeedDisp} var l_Hint : String; {$EndIf evNeedDisp} begin {$IfDef evNeedDisp} if (Hint = '') OR not (csLoading in ComponentState) OR (Operation = ev_ccNone) then inherited else begin l_Hint := Hint; try inherited; finally Hint := l_Hint; end;//try..finally end;//Hint = '' {$Else evNeedDisp} inherited; {$EndIf evNeedDisp} end; // start class TevCustomButtonActionLink procedure TevCustomButtonActionLink.SetHint(const Value: string); //override; {-} begin {$IfDef evNeedDisp} if (FClient Is TevCustomButton) then begin with TevCustomButton(FClient) do begin if (Hint = '') OR not (csLoading in ComponentState) OR (Operation = ev_ccNone) then inherited; end; end//FClient Is TevCustomButton else {$EndIf evNeedDisp} inherited; end; function TevCustomButtonActionLink._AddRef: Integer; //stdcall; {* - реализация метода _AddRef интерфейса IUnknown, увеличивает число ссылок на объект. } begin Result := -1; end; function TevCustomButtonActionLink._Release: Integer; //stdcall; {* - реализация метода _Release интерфейса IUnknown, уменьшает число ссылок на объект и уничтожает его, если число ссылок становится = 0. } begin Result := -1; end; function TevCustomButtonActionLink.QueryInterface(const IID: TGUID; out Obj): HResult; //virtual; //stdcall; {-} begin if TObject(Self).GetInterface(IID, Obj) then Result := S_Ok else Result := E_NoInterface; end; end.
{=============================================================================== MD5 Hash Calculation ©František Milt 15.9.2013 Version 1.2.1 ===============================================================================} unit MD5; interface uses Classes; type TMD5Hash = Record PartA: LongWord; PartB: LongWord; PartC: LongWord; PartD: LongWord; end; PMD5Hash = ^TMD5Hash; const InitialMD5: TMD5Hash = ( PartA: $67452301; PartB: $EFCDAB89; PartC: $98BADCFE; PartD: $10325476); Function MD5toString(const Hash: TMD5Hash): String; Function StringToMD5(HashString: String): TMD5Hash; Function CompareMD5(const Hash1, Hash2: TMD5Hash): Boolean; Function BufferMD5(const Hash: TMD5Hash; const Buffer; const BuffSize: Integer): TMD5Hash; Function LastBufferMD5(const Hash: TMD5Hash; const Buffer; const BuffSize: Integer; Size: Int64 = -1): TMD5Hash; Function StreamMD5(const InputStream: TStream): TMD5Hash; Function StringMD5(const Text: String): TMD5Hash; Function FileMD5(const FileName: String): TMD5Hash; implementation {.$DEFINE LargeBuffers} {.$DEFINE UseStringStream} uses Windows, SysUtils, Math; const cFAB = $80; // bin 10000000 cChunkSize = 64; // 512 bits {$IFDEF LargeBuffers} cChunksPerBuffer = 16384; // =>1MiB BufferSize {$ELSE} cChunksPerBuffer = 64; // =>4KiB BufferSize {$ENDIF} cBufferSize = cChunksPerBuffer * cChunkSize; // size of read buffer ShiftCoefs: Array[0..63] of LongWord = ( 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21); SinusCoefs: Array[0..63] of LongWord = ( $D76AA478,$E8C7B756,$242070DB,$C1BDCEEE,$F57C0FAF,$4787C62A,$A8304613,$FD469501, $698098D8,$8B44F7AF,$FFFF5BB1,$895CD7BE,$6B901122,$FD987193,$A679438E,$49B40821, $F61E2562,$C040B340,$265E5A51,$E9B6C7AA,$D62F105D,$02441453,$D8A1E681,$E7D3FBC8, $21E1CDE6,$C33707D6,$F4D50D87,$455A14ED,$A9E3E905,$FCEFA3F8,$676F02D9,$8D2A4C8A, $FFFA3942,$8771F681,$6D9D6122,$FDE5380C,$A4BEEA44,$4BDECFA9,$F6BB4B60,$BEBFBC70, $289B7EC6,$EAA127FA,$D4EF3085,$04881D05,$D9D4D039,$E6DB99E5,$1FA27CF8,$C4AC5665, $F4292244,$432AFF97,$AB9423A7,$FC93A039,$655B59C3,$8F0CCC92,$FFEFF47D,$85845DD1, $6FA87E4F,$FE2CE6E0,$A3014314,$4E0811A1,$F7537E82,$BD3AF235,$2AD7D2BB,$EB86D391); ModuloCoefs: Array[0..63] of LongWord = ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1, 6, 11, 0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2, 0, 7, 14, 5, 12, 3, 10, 1, 8, 15, 6, 13, 4, 11, 2, 9); //------------------------------------------------------------------------------ Function ChunkHash(Hash: TMD5Hash; const Chunk): TMD5Hash; var i: Integer; Temp: LongWord; FuncResult: LongWord; ChunkWords: Array[0..15] of LongWord absolute Chunk; Function LeftRotate(Number,Shift: LongWord): LongWord; register {$IFDEF PUREPASCAL} begin Result := (Number shl Shift) or (Number shr (32 - Shift)); end; {$ELSE} asm mov CL, DL rol EAX, CL end; {$ENDIF} begin Result := Hash; For i := 0 to 63 do begin Case i of 0..15: FuncResult := (Hash.PartB and Hash.PartC) or ((not Hash.PartB) and Hash.PartD); 16..31: FuncResult := (Hash.PartD and Hash.PartB) or (Hash.PartC and (not Hash.PartD)); 32..47: FuncResult := Hash.PartB xor Hash.PartC xor Hash.PartD; else {48..63:}FuncResult := Hash.PartC xor (Hash.PartB or (not Hash.PartD)); end; Temp := Hash.PartD; Hash.PartD := Hash.PartC; Hash.PartC := Hash.PartB; Hash.PartB := Hash.PartB + LeftRotate(Hash.PartA + FuncResult + SinusCoefs[i] + ChunkWords[ModuloCoefs[i]], ShiftCoefs[i]); Hash.PartA := Temp; end; Inc(Result.PartA,Hash.PartA); Inc(Result.PartB,Hash.PartB); Inc(Result.PartC,Hash.PartC); Inc(Result.PartD,Hash.PartD); end; //------------------------------------------------------------------------------ Function MD5toString(const Hash: TMD5Hash): String; var HashArray: Array[0..15] of Byte absolute Hash; i: Integer; begin Result := ''; For i := Low(HashArray) to High(HashArray) do Result:= Result + (IntToHex(HashArray[i],2)); Result := AnsiLowerCase(Result); end; Function StringToMD5(HashString: String): TMD5Hash; var HashArray: Array[0..15] of Byte absolute Result; i: Integer; begin If Length(HashString) < 32 then HashString := StringOfChar('0',32 - Length(HashString)) + HashString else If Length(HashString) > 32 then HashString := Copy(HashString,Length(HashString) - 31,32); For i := 0 to 15 do HashArray[i] := StrToInt('$' + Copy(HashString,(i * 2) + 1,2)); end; Function CompareMD5(const Hash1, Hash2: TMD5Hash): Boolean; begin Result := (Hash1.PartA = Hash2.PartA) and (Hash1.PartB = Hash2.PartB) and (Hash1.PartC = Hash2.PartC) and (Hash1.PartD = Hash2.PartD); end; //------------------------------------------------------------------------------ Function BufferMD5(const Hash: TMD5Hash; const Buffer; const BuffSize: Integer): TMD5Hash; type TChunkBuffer = Array[0..cChunkSize - 1] of Byte; PChunkBuffer = ^TChunkBuffer; var i: Integer; ChunkPtr: PChunkBuffer; begin Result := Hash; ChunkPtr := @Buffer; For i := 1 to (BuffSize div cChunkSize) do begin Result := ChunkHash(Result,ChunkPtr^); Inc(ChunkPtr); end; end; Function LastBufferMD5(const Hash: TMD5Hash; const Buffer; const BuffSize: Integer; Size: Int64 = -1): TMD5Hash; var HelpBuffer: Pointer; Chunks: Integer; begin If Size < 0 then Size := BuffSize; If BuffSize <= 0 then Chunks := 1 else Chunks := Ceil((BuffSize + SizeOf(Int64) + 1) / cChunkSize); HelpBuffer := AllocMem(Chunks * cChunkSize); try CopyMemory(HelpBuffer,@Buffer,BuffSize); PByteArray(HelpBuffer)^[BuffSize] := cFAB; PInt64(@PByteArray(HelpBuffer)[(Chunks * cChunkSize) - SizeOf(Int64)])^ := Size * 8; Result := BufferMD5(Hash,HelpBuffer^,Chunks * cChunkSize); finally FreeMem(HelpBuffer,Chunks * cChunkSize); end; end; Function StreamMD5(const InputStream: TStream): TMD5Hash; var Buffer: Pointer; Readed: Integer; begin If Assigned(InputStream) then begin GetMem(Buffer,cBufferSize); try Result := InitialMD5; InputStream.Position := 0; Repeat Readed := InputStream.Read(Buffer^,cBufferSize); If Readed < cBufferSize then Result := LastBufferMD5(Result,Buffer^,Readed,InputStream.Size) else Result := BufferMD5(Result,Buffer^,Readed); Until Readed < cBufferSize; InputStream.Position := 0; finally FreeMem(Buffer,cBufferSize); end; end; end; Function StringMD5(const Text: String): TMD5Hash; {$IFDEF UseStringStream} var StringStream: TStringStream; begin StringStream := TStringStream.Create(Text); try Result := StreamMD5(StringStream); finally StringStream.Free; end; end; {$ELSE} begin Result := LastBufferMD5(InitialMD5,PChar(Text)^,Length(Text) * SizeOf(Char)); end; {$ENDIF} Function FileMD5(const FileName: String): TMD5Hash; var FileStream: TFileStream; begin FileStream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try Result := StreamMD5(FileStream); finally FileStream.Free; end; end; end.
unit GX_eDate; interface {$I GX_CondDefine.inc} uses Classes, Controls, Forms, StdCtrls, GX_EditorExpert, GX_ConfigurationInfo, GX_BaseForm; type TDateExpert = class(TEditorExpert) private FDateFormat: string; protected procedure InternalSaveSettings(Settings: TExpertSettings); override; procedure InternalLoadSettings(Settings: TExpertSettings); override; public class function GetName: string; override; constructor Create; override; function GetDefaultShortCut: TShortCut; override; function GetDisplayName: string; override; procedure Configure; override; procedure Execute(Sender: TObject); override; function GetHelpString: string; override; property DateFormat: string read FDateFormat write FDateFormat; end; type TfmDateFormat = class(TfmBaseForm) lblFormat: TLabel; cbFormat: TComboBox; btnOK: TButton; btnCancel: TButton; end; implementation uses SysUtils, GX_OtaUtils; {$R *.dfm} { TDateExpert } procedure TDateExpert.Configure; begin with TfmDateFormat.Create(nil) do try cbFormat.Text := DateFormat; if ShowModal = mrOk then DateFormat := cbFormat.Text; finally Free; end; end; constructor TDateExpert.Create; begin inherited Create; FDateFormat := {$IFDEF GX_VER220_up}FormatSettings.{$ENDIF}ShortDateFormat; end; procedure TDateExpert.Execute(Sender: TObject); resourcestring SInvalidDateTimeFormat = 'Invalid date/time format'; var InsertString: string; begin try InsertString := FormatDateTime(FDateFormat, Date + Time); except on E: EConvertError do InsertString := SInvalidDateTimeFormat; end; GxOtaInsertLineIntoEditor(InsertString); end; function TDateExpert.GetDefaultShortCut: TShortCut; begin Result := scCtrl + scAlt + Ord('A'); end; function TDateExpert.GetDisplayName: string; resourcestring SDateExpertName = 'Insert Date/Time'; begin Result := SDateExpertName; end; function TDateExpert.GetHelpString: string; resourcestring SDateExpertHelp = ' This expert inserts the current date/time at the cursor position in ' + 'the code editor. The format of the date/time text is configurable ' + 'using standard VCL date format specifiers. See the FormatDateTime ' + 'help topic in the VCL documentation for full details.'; begin Result := SDateExpertHelp; end; class function TDateExpert.GetName: string; begin Result := 'DateTime'; end; procedure TDateExpert.InternalLoadSettings(Settings: TExpertSettings); begin inherited InternalLoadSettings(Settings); DateFormat := Settings.ReadString('Format', FDateFormat); // Do not localize end; procedure TDateExpert.InternalSaveSettings(Settings: TExpertSettings); begin inherited InternalSaveSettings(Settings); Settings.WriteString('Format', DateFormat); // Do not localize end; initialization RegisterEditorExpert(TDateExpert); end.
program Project1; Type str25=string[25]; TBookRec= record Title,Author,ISBN:str25; Price:real; end; Procedure EnterNewBook(var newBook:TBookRec); begin writeln('Please enter the book details: '); write('Book Name: '); readln(newBook.title); write('Author: '); readln(newBook.Author); write('ISBN: '); readln(newBook.ISBN); write('Price: '); readln(newBook.Price); end; var bookRecArray:array[1..10] of TBookRec; tempBookRec:TBookRec; bookRecFile:File of TBookRec; i:1..10; begin assign(bookRecFile, 'bookrec.dat'); reWrite(bookRecFile); for i:=1 to 10 do begin EnterNewBook(bookRecArray[i]); {bookRecArray[i] now contains the book details} write(bookRecFile,bookRecArray[i]); end; close(bookRecFile); writeln('Thanks for entering the book details.'); writeln('They are saved in a file!'); write('Now choose a record to display from 1 to 10: '); readln(i); ReSet(bookRecFile); seek(bookRecFile,i-1); read(bookRecFile,tempBookRec); Close(bookRecFile); writeln('Here are the book details of record #',i,':'); writeln; writeln('Title: ',tempBookRec.Title); writeln('Author: ',tempBookRec.Author); writeln('ISBN: ',tempBookRec.ISBN); writeln('Price: ',tempBookRec.Price); readln; end.
unit GX_LibrarySource; {$I GX_CondDefine.inc} {$IFDEF BCB} {$OBJEXPORTALL ON} {$ENDIF BCB} interface uses ToolsAPI; // Errors here indicate that you didn't link to the DesignIde package // This function needs to be interface-visible, otherwise // C++Builder 5 complains about a missing EXTDEF symbol // for this export. Do not call this function yourself. function InitWizard(const BorlandIDEServices: IBorlandIDEServices; RegisterProc: TWizardRegisterProc; var Terminate: TWizardTerminateProc): Boolean; stdcall; implementation uses Windows, GX_GxUtils, GX_OtaUtils, GX_VerDepConst, GX_GExperts, GX_MessageBox, GX_CodeLib, GX_GrepExpert, GX_ExpertManager, GX_PeInformation, GX_GenericUtils; const InvalidIndex = -1; var FExpertIndex: Integer = InvalidIndex; { Remove the wizard from the IDE. } procedure FinalizeWizard; var WizardServices: IOTAWizardServices; begin if FExpertIndex <> InvalidIndex then begin Assert(Assigned(BorlandIDEServices)); WizardServices := BorlandIDEServices as IOTAWizardServices; Assert(Assigned(WizardServices)); WizardServices.RemoveWizard(FExpertIndex); FExpertIndex := InvalidIndex; end; end; { Register the wizard. } function InitWizard(const BorlandIDEServices: IBorlandIDEServices; RegisterProc: TWizardRegisterProc; var Terminate: TWizardTerminateProc): Boolean; stdcall; var WizardServices: IOTAWizardServices; begin Result := (BorlandIDEServices <> nil); if Result and (not BuiltWithPackages) then begin Result := False; ShowNoPackagesError; end; if Result then begin Assert(ToolsAPI.BorlandIDEServices = BorlandIDEServices); Terminate := FinalizeWizard; WizardServices := BorlandIDEServices as IOTAWizardServices; Assert(Assigned(WizardServices)); FExpertIndex := WizardServices.AddWizard(TGExperts.Create as IOTAWizard); Result := (FExpertIndex >= 0); end; end; exports {$IFDEF GX_BCB} InitWizard name WizardEntryPoint; {$ELSE} InitWizard name WizardEntryPoint, ShowExpertManager, ShowPeInfo, InstallGExperts, ShowCodeLib, ShowGrep; {$ENDIF GX_BCB} // --------------------------------------------- type TGxMultipleInstancesMessage = class(TGxMsgBoxAdaptor) protected function GetMessage: string; override; end; { TGxMultipleInstancesMessage } function TGxMultipleInstancesMessage.GetMessage: string; resourcestring SMultipleGExpertsInstances = 'Multiple instances of this version of GExperts are currently running. ' + 'This is usually caused by multiple instances of the same IDE running at once (check in the Task Manager if you don''t see them all). ' + 'Please be aware that the last IDE instance to save any settings ' + 'will overwrite any previously saved settings from other instances.'; begin Result := SMultipleGExpertsInstances; end; var GXGeneralMutex: THandle; GXVersionMutex: THandle; procedure CreateInstanceMutexes; begin // This mutex signals that at least one copy of GExperts is running // The installer uses this to determine if it should allow installation GXGeneralMutex := CreateMutex(nil, False, 'GExperts.Addin.For.Borland.IDEs'); GXVersionMutex := CreateMutex(nil, False, PChar('GExperts.Addin.For.Borland.IDEs.Under.' + GxOtaGetIDEProductIdentifier + MajorVersionNumberChar)); if (GXVersionMutex <> 0) and (GetLastError = ERROR_ALREADY_EXISTS) then begin // The mutex already exists, so there is a good chance that a copy // of this version of GExperts is already loaded into memory. ShowGxMessageBox(TGxMultipleInstancesMessage); end; end; procedure DestroyInstanceMutexes; begin if GXGeneralMutex <> 0 then CloseHandle(GXGeneralMutex); if GXVersionMutex <> 0 then CloseHandle(GXVersionMutex); end; initialization CreateInstanceMutexes; finalization DestroyInstanceMutexes; end.
unit xdg_decoration_unstable_v1_protocol; {$mode objfpc} {$H+} {$interfaces corba} interface uses Classes, Sysutils, ctypes, wayland_util, wayland_client_core, wayland_protocol, xdg_shell_unstable_v6_protocol; type Pzxdg_decoration_manager_v1 = Pointer; Pzxdg_toplevel_decoration_v1 = Pointer; Pzxdg_decoration_manager_v1_listener = ^Tzxdg_decoration_manager_v1_listener; Tzxdg_decoration_manager_v1_listener = record end; const ZXDG_TOPLEVEL_DECORATION_V1_ERROR_UNCONFIGURED_BUFFER = 0; // xdg_toplevel has a buffer attached before configure ZXDG_TOPLEVEL_DECORATION_V1_ERROR_ALREADY_CONSTRUCTED = 1; // xdg_toplevel already has a decoration object ZXDG_TOPLEVEL_DECORATION_V1_ERROR_ORPHANED = 2; // xdg_toplevel destroyed before the decoration object ZXDG_TOPLEVEL_DECORATION_V1_MODE_CLIENT_SIDE = 1; // no server-side window decoration ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE = 2; // server-side window decoration type Pzxdg_toplevel_decoration_v1_listener = ^Tzxdg_toplevel_decoration_v1_listener; Tzxdg_toplevel_decoration_v1_listener = record configure : procedure(data: Pointer; AZxdgToplevelDecorationV1: Pzxdg_toplevel_decoration_v1; AMode: DWord); cdecl; end; TZxdgDecorationManagerV1 = class; TZxdgToplevelDecorationV1 = class; IZxdgDecorationManagerV1Listener = interface ['IZxdgDecorationManagerV1Listener'] end; IZxdgToplevelDecorationV1Listener = interface ['IZxdgToplevelDecorationV1Listener'] procedure zxdg_toplevel_decoration_v1_configure(AZxdgToplevelDecorationV1: TZxdgToplevelDecorationV1; AMode: DWord); end; { TZxdgDecorationManagerV1 } TZxdgDecorationManagerV1 = class(TWLProxyObject) private const _DESTROY = 0; const _GET_TOPLEVEL_DECORATION = 1; public destructor Destroy; override; function GetToplevelDecoration(AToplevel: TZxdgToplevelV6; AProxyClass: TWLProxyObjectClass = nil {TZxdgToplevelDecorationV1}): TZxdgToplevelDecorationV1; function AddListener(AIntf: IZxdgDecorationManagerV1Listener): LongInt; end; TZxdgToplevelDecorationV1 = class(TWLProxyObject) private const _DESTROY = 0; const _SET_MODE = 1; const _UNSET_MODE = 2; public destructor Destroy; override; procedure SetMode(AMode: DWord); procedure UnsetMode; function AddListener(AIntf: IZxdgToplevelDecorationV1Listener): LongInt; end; var zxdg_decoration_manager_v1_interface: Twl_interface; zxdg_toplevel_decoration_v1_interface: Twl_interface; implementation var vIntf_zxdg_decoration_manager_v1_Listener: Tzxdg_decoration_manager_v1_listener; vIntf_zxdg_toplevel_decoration_v1_Listener: Tzxdg_toplevel_decoration_v1_listener; destructor TZxdgDecorationManagerV1.Destroy; begin wl_proxy_marshal(FProxy, _DESTROY); inherited Destroy; end; function TZxdgDecorationManagerV1.GetToplevelDecoration( AToplevel: TZxdgToplevelV6; AProxyClass: TWLProxyObjectClass ): TZxdgToplevelDecorationV1; var id: Pwl_proxy; begin id := wl_proxy_marshal_constructor(FProxy, _GET_TOPLEVEL_DECORATION, @zxdg_toplevel_decoration_v1_interface, nil, AToplevel.Proxy); if AProxyClass = nil then AProxyClass := TZxdgToplevelDecorationV1; Result := TZxdgToplevelDecorationV1(AProxyClass.Create(id)); if not AProxyClass.InheritsFrom(TZxdgToplevelDecorationV1) then Raise Exception.CreateFmt('%s does not inherit from %s', [AProxyClass.ClassName, TZxdgToplevelDecorationV1]); end; function TZxdgDecorationManagerV1.AddListener(AIntf: IZxdgDecorationManagerV1Listener): LongInt; begin FUserDataRec.ListenerUserData := Pointer(AIntf); Result := wl_proxy_add_listener(FProxy, @vIntf_zxdg_decoration_manager_v1_Listener, @FUserDataRec); end; destructor TZxdgToplevelDecorationV1.Destroy; begin wl_proxy_marshal(FProxy, _DESTROY); inherited Destroy; end; procedure TZxdgToplevelDecorationV1.SetMode(AMode: DWord); begin wl_proxy_marshal(FProxy, _SET_MODE, AMode); end; procedure TZxdgToplevelDecorationV1.UnsetMode; begin wl_proxy_marshal(FProxy, _UNSET_MODE); end; function TZxdgToplevelDecorationV1.AddListener(AIntf: IZxdgToplevelDecorationV1Listener): LongInt; begin FUserDataRec.ListenerUserData := Pointer(AIntf); Result := wl_proxy_add_listener(FProxy, @vIntf_zxdg_toplevel_decoration_v1_Listener, @FUserDataRec); end; procedure zxdg_toplevel_decoration_v1_configure_Intf(AData: PWLUserData; Azxdg_toplevel_decoration_v1: Pzxdg_toplevel_decoration_v1; AMode: DWord); cdecl; var AIntf: IZxdgToplevelDecorationV1Listener; begin if AData = nil then Exit; AIntf := IZxdgToplevelDecorationV1Listener(AData^.ListenerUserData); AIntf.zxdg_toplevel_decoration_v1_configure(TZxdgToplevelDecorationV1(AData^.PascalObject), AMode); end; const pInterfaces: array[0..9] of Pwl_interface = ( (nil), (nil), (nil), (nil), (nil), (nil), (nil), (nil), (@zxdg_toplevel_decoration_v1_interface), (@zxdg_toplevel_v6_interface) ); zxdg_decoration_manager_v1_requests: array[0..1] of Twl_message = ( (name: 'destroy'; signature: ''; types: @pInterfaces[0]), (name: 'get_toplevel_decoration'; signature: 'no'; types: @pInterfaces[8]) ); zxdg_toplevel_decoration_v1_requests: array[0..2] of Twl_message = ( (name: 'destroy'; signature: ''; types: @pInterfaces[0]), (name: 'set_mode'; signature: 'u'; types: @pInterfaces[0]), (name: 'unset_mode'; signature: ''; types: @pInterfaces[0]) ); zxdg_toplevel_decoration_v1_events: array[0..0] of Twl_message = ( (name: 'configure'; signature: 'u'; types: @pInterfaces[0]) ); initialization Pointer(vIntf_zxdg_toplevel_decoration_v1_Listener.configure) := @zxdg_toplevel_decoration_v1_configure_Intf; zxdg_decoration_manager_v1_interface.name := 'zxdg_decoration_manager_v1'; zxdg_decoration_manager_v1_interface.version := 1; zxdg_decoration_manager_v1_interface.method_count := 2; zxdg_decoration_manager_v1_interface.methods := @zxdg_decoration_manager_v1_requests; zxdg_decoration_manager_v1_interface.event_count := 0; zxdg_decoration_manager_v1_interface.events := nil; zxdg_toplevel_decoration_v1_interface.name := 'zxdg_toplevel_decoration_v1'; zxdg_toplevel_decoration_v1_interface.version := 1; zxdg_toplevel_decoration_v1_interface.method_count := 3; zxdg_toplevel_decoration_v1_interface.methods := @zxdg_toplevel_decoration_v1_requests; zxdg_toplevel_decoration_v1_interface.event_count := 1; zxdg_toplevel_decoration_v1_interface.events := @zxdg_toplevel_decoration_v1_events; end.
program TESTCOLL ( OUTPUT ) ; (********) (*$A+ *) (********) type POS_INT = 0 .. 30 ; var I : POS_INT ; TIME : INTEGER ; static TESTDUMP : INTEGER ; TESTCHAR : array [ 1 .. 10 ] of CHAR ; function FIBONACCI ( J : POS_INT ) : INTEGER ; (******************************) (* to evaluate fibonacci # j, *) (* for j >= 0 *) (* subject to int overflow *) (******************************) type BUFFER = array [ 1 .. 40000 ] of INTEGER ; PBUFFER = -> BUFFER ; static ANZCALL : INTEGER ; var CP : -> CHAR ; C : CHAR ; P : PBUFFER ; x1 : buffer; x2 : buffer; begin (* FIBONACCI *) NEW ( P ) ; ANZCALL := ANZCALL + 1 ; if J = 5 then begin CP := ADDR ( C ) ; CP := PTRADD ( CP , 8000000 ) ; CP -> := 'A' ; end (* then *) ; if J = 0 then FIBONACCI := 0 else if J = 1 then FIBONACCI := 1 else FIBONACCI := FIBONACCI ( J - 1 ) + FIBONACCI ( J - 3 ) ; end (* FIBONACCI *) ; begin (* HAUPTPROGRAMM *) TESTDUMP := 42 ; TESTCHAR := 'Oppolzer' ; for I := 10 to 25 do begin TIME := CLOCK ( 0 ) ; WRITELN ( ' fibonacci # ' , I : 3 , ' is ' , FIBONACCI ( I ) : 8 , ' (Comp.time = ' , CLOCK ( 0 ) - TIME : 5 , ' Milli Sec.)' ) ; end (* for *) end (* HAUPTPROGRAMM *) .
{************************************************************************} { TRTFLabel component } { for Delphi & C++Builder } { } { written by } { TMS Software } { copyright © 1999-2013 } { Email : info@tmssoftware.com } { Website : http://www.tmssoftware.com } { } { The source code is given as is. The author is not responsible } { for any possible damage done due to the use of this code. } { The component can be freely used in any application. The complete } { source code remains property of the author and may not be distributed, } { published, given or sold in any form as such. No parts of the source } { code can be included in any other component or application without } { written authorization of the author. } {************************************************************************} unit RTFLabel; {$I TMSDEFS.INC} interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, StdCtrls, richedit, comctrls, forms {$IFDEF DELPHIXE3_LVL} , System.UITypes {$ENDIF} ; const MAJ_VER = 1; // Major version nr. MIN_VER = 3; // Minor version nr. REL_VER = 2; // Release nr. BLD_VER = 2; // Build nr. // version history // v1.0.0.0 : First release // v1.3.1.0 : New : Added public method PaintTo() // v1.3.2.0 : Improved : Performance for handling rich text strings // v1.3.2.1 : Fixed : Painting issues // v1.3.2.2 : Fixed : Issue with accessing RTFLabel.RTF helper rich edit control type TRichText = string; {$IFDEF DELPHIXE2_LVL} [ComponentPlatformsAttribute(pidWin32 or pidWin64)] {$ENDIF} TRTFLabel = class(TCustomLabel) private { Private declarations } FRichedit: TRichEdit; FRichtext: TRichText; Fupdatecount: integer; FWordWrap: boolean; FPainting: boolean; procedure RTFPaint(Canvas:TCanvas;ARect:TRect); procedure RTFResizeRequest(Sender: TObject; Rect: TRect); function GetRichEdit:TRichEdit; procedure SetWordWrap(const Value: boolean); function GetVersion: string; procedure SetVersion(const Value: string); protected { Protected declarations } function GetVersionNr: Integer; virtual; procedure Paint; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Loaded; override; property RTF: TRichEdit read GetRichEdit; procedure ShowRTF; procedure BeginUpdate; procedure EndUpdate; procedure CopyFromRichEdit(richedit:TRichEdit); procedure CopyToRichEdit(richedit:TRichEdit); procedure Print(Caption:string); procedure PaintTo(ACanvas: TCanvas); published { Published declarations } property RichText: TRichText read FRichText write FRichText; property Align; property Color; property Transparent; property Visible; property Hint; property ShowHint; property FocusControl; property ParentShowHint; property DragCursor; property DragMode; property Anchors; property BiDiMode; property Constraints; property DragKind; property ParentBiDiMode; property PopupMenu; property OnEndDock; property OnStartDock; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; property WordWrap:boolean read FWordWrap write SetWordWrap; property Version: string read GetVersion write SetVersion; end; implementation procedure TRTFLabel.BeginUpdate; begin inc(FUpdateCount); end; procedure TRTFLabel.EndUpdate; begin if FUpdateCount > 0 then begin dec(FUpdateCount); if (FUpdateCount = 0) then ShowRTF; end; end; function TRTFLabel.GetRichEdit: TRichEdit; begin if Assigned(Parent) and Assigned(FRichEdit) then begin FRichEdit.Parent := Parent; // if FRichEdit.Parent.HandleAllocated then // begin // FRichEdit.Lines.Clear; // FRichEdit.Selattributes := FRichEdit.DefAttributes; // end; Result := FRichEdit; end else Result := nil; end; procedure TRTFLabel.ShowRTF; var ms: TStringStream; begin if not Assigned(Parent) then Exit; if not Assigned(FRichEdit) then Exit; if not Parent.HandleAllocated then Exit; FRichEdit.Parent := Parent; ms := TStringStream.Create(''); try FRichEdit.Lines.SaveToStream(ms); RichText := ms.DataString; finally ms.Free; end; Repaint; FRichEdit.Parent := nil; end; procedure TRTFLabel.RTFPaint(Canvas: TCanvas; ARect:TRect); const RTF_OFFSET :integer = 1; type rFormatRange = record hdcSrc: HDC; hdcTarget: HDC; rc: TRect; rcPage: TRect; chrg: TCharRange; end; var ms: TStringStream; fr: rFORMATRANGE; nLogPixelsX,nLogPixelsY: Integer; begin ms := TStringStream.Create(''); try ms.WriteString(RichText); ms.position := 0; FRichedit.Lines.LoadFromStream(ms); finally ms.free; end; FillChar(fr, SizeOf(TFormatRange), 0); nLogPixelsX := GetDeviceCaps(Canvas.Handle,LOGPIXELSX); nLogPixelsY := GetDeviceCaps(Canvas.Handle,LOGPIXELSY); if nLogPixelsX = 0 then nLogPixelsX := 96; if nLogPixelsY = 0 then nLogPixelsY := 96; if Transparent then Sendmessage(frichedit.handle,EM_SETBKGNDCOLOR,0,colortorgb(Parent.Brush.Color)) else Sendmessage(frichedit.handle,EM_SETBKGNDCOLOR,0,colortorgb(Color)); with fr do begin fr.hdcSrc := Canvas.Handle; fr.hdctarget := Canvas.Handle; fr.rcPage.left:=round(((arect.left+RTF_OFFSET)/nLogPixelsX)*1440); fr.rcPage.top:=round(((arect.top+RTF_OFFSET)/nLogPixelsY)*1440); fr.rcPage.right:=fr.rcPage.left+round(((arect.right-arect.left-RTF_OFFSET)/nLogPixelsX) * 1440); fr.rcPage.bottom:=(fr.rcPage.top+round(((arect.bottom-arect.top-RTF_OFFSET)/nLogPixelsY) * 1440)); fr.rc.left:=fr.rcPage.left; { 1440 TWIPS = 1 inch. } fr.rc.top:=fr.rcPage.top; fr.rc.right:=fr.rcPage.right; fr.rc.bottom:=fr.rcPage.bottom; fr.chrg.cpMin := 0; fr.chrg.cpMax := -1; end; SendMessage(frichedit.Handle,EM_FORMATRANGE,1,longint(@fr)); //clear the richtext cache SendMessage(frichedit.Handle,EM_FORMATRANGE,0,0); end; procedure TRTFLabel.Paint; var r: TRect; es: Integer; begin //Caption := ''; inherited Paint; if FUpdateCount > 0 then Exit; if not Assigned(FRichEdit) then Exit; if FPainting then Exit; FPainting := true; FRichEdit.Parent := Parent; if not FRichedit.Parent.HandleAllocated then begin FPainting := false; Exit; end; es := GetWindowLong(FRichEdit.handle,GWL_EXSTYLE); es := es OR WS_EX_TRANSPARENT; SetWindowLong(FRichEdit.Handle,GWL_EXSTYLE,es); frichedit.brush.style := bsClear; frichedit.height:=0; r.left := 0; r.right := r.left + Width; r.top := 0; r.bottom := r.top + Height; SetBkMode(Canvas.Handle,1); RTFPaint(Canvas,r); FRichedit.Parent := nil; FPainting := false; end; procedure TRTFLabel.PaintTo(ACanvas: TCanvas); begin FRichEdit.Parent := Parent; RTFPaint(ACanvas, ClientRect); FRichedit.Parent := nil; end; constructor TRTFLabel.Create(AOwner: TComponent); begin inherited; FRichEdit := TRichEdit.Create(self); FRichEdit.OnResizeRequest := RTFResizeRequest; AutoSize := false; Caption := ''; FUpdateCount := 0; end; destructor TRTFLabel.Destroy; begin FRichEdit.Free; FRichEdit := nil; inherited; end; procedure TRTFLabel.Loaded; var s: string; i: integer; begin inherited; FRichEdit.Visible := False; FRichEdit.Left := 0; FRichEdit.Top := 0; FRichEdit.Width := 10; FRichEdit.Height := 10; FRichEdit.WordWrap := False; FRichEdit.BorderStyle := bsNone; s := FRichText; {$IFDEF DELPHI_UNICODE} if (Length(s) > 0) and (ord(s[1]) > 255) then {$ENDIF} begin for i := 1 to length(s) do s[i] := char($FF and ord(s[i])); FRichText := s; end; Caption := ''; end; procedure TRTFLabel.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited MouseDown(Button,Shift,X,Y); end; procedure TRTFLabel.CopyFromRichEdit(RichEdit: TRichEdit); var ss: TStringStream; begin ss := TStringStream.Create(''); try RichEdit.Lines.SaveToStream(ss); RichText := ss.DataString; finally ss.Free; end; Repaint; end; procedure TRTFLabel.CopyToRichEdit(richedit: TRichEdit); var ms: TStringStream; begin ms := TStringStream.Create(''); try ms.WriteString(RichText); ms.Position := 0; RichEdit.PlainText := False; RichEdit.Lines.LoadFromStream(ms); finally ms.Free; end; end; procedure TRTFLabel.Print(Caption: string); begin if Assigned(Parent) and Assigned(FRichEdit) then begin FRichEdit.Parent := Parent; if FRichEdit.Parent.Handleallocated then begin Copytorichedit(fRichEdit); FRichEdit.print(Caption); end; FRichEdit.Parent := nil; end; end; procedure TRTFLabel.RTFResizeRequest(Sender: TObject; Rect: TRect); begin // outputdebugstring(pchar(inttostr(rect.left)+':'+inttostr(rect.top)+':'+inttostr(rect.right)+':'+inttostr(rect.bottom))); // self.BoundsRect:=rect; end; procedure TRTFLabel.SetWordWrap(const Value: boolean); begin FWordWrap := Value; if Assigned(Parent) and Assigned(FRichEdit) and not (csLoading in ComponentState) then FRichEdit.WordWrap := Value; end; function TRTFLabel.GetVersion: string; var vn: Integer; begin vn := GetVersionNr; Result := IntToStr(Hi(Hiword(vn)))+'.'+IntToStr(Lo(Hiword(vn)))+'.'+IntToStr(Hi(Loword(vn)))+'.'+IntToStr(Lo(Loword(vn))); end; function TRTFLabel.GetVersionNr: Integer; begin Result := MakeLong(MakeWord(BLD_VER,REL_VER),MakeWord(MIN_VER,MAJ_VER)); end; procedure TRTFLabel.SetVersion(const Value: string); begin end; end.
unit uImportaNFeTXT; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, StdCtrls, Buttons, CheckLst, FileCtrl, JvExStdCtrls, JvListBox,uImportaNFe, JvDriveCtrls, Dialogs, JvBaseDlg, JvSelectDirectory, DB, funcoes, ZAbstractRODataset, ZAbstractDataset, ZDataset, JvExControls, JvXPCore, JvXPButtons, ComCtrls, ExtCtrls, Registry, Menus; type TfrmImportaNFeTXT = class(TForm) CheckListBox1: TCheckListBox; JvSelectDirectory1: TJvSelectDirectory; qrNotasItens: TZQuery; qrNotas: TZQuery; StatusBar1: TStatusBar; Panel1: TPanel; btnDiretorio: TJvXPButton; btnLocalizar: TJvXPButton; btnTodos: TJvXPButton; btnNenhum: TJvXPButton; btnGerar: TJvXPButton; PopupMenu1: TPopupMenu; Editarnotasapsgerao1: TMenuItem; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnDiretorioClick(Sender: TObject); procedure btnLocalizarClick(Sender: TObject); procedure btnTodosClick(Sender: TObject); procedure btnNenhumClick(Sender: TObject); procedure StatusBar1DrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel; const Rect: TRect); procedure btnGerarClick(Sender: TObject); procedure CheckListBox1DblClick(Sender: TObject); procedure CheckListBox1ClickCheck(Sender: TObject); private { Private declarations } CaminhoTXT: string; ProgressBar1: TProgressBar; FArquivo: string; FTipoArquivo: TTipoArquivo; procedure SetStatusBar; function AlgumaNotaSelecionada: Boolean; function TodasNotasSelecionadas: Boolean; function NenhumaNotaSeleconada: Boolean; procedure NewImportaNFe(const AList: TCheckListBox); procedure TrataBotoes; procedure SetTipoArquivo(const Value: TTipoArquivo); public { Public declarations } property TipoArquivo: TTipoArquivo read FTipoArquivo write SetTipoArquivo; end; var frmImportaNFeTXT: TfrmImportaNFeTXT; implementation uses udmPrincipal, uAtualizaTXTReceita; {$R *.dfm} procedure TfrmImportaNFeTXT.FormCreate(Sender: TObject); var ProgressBarStyle: integer; Reg: TRegistry; begin FArquivo := 'TXT'; Reg := TRegistry.Create; try with Reg do begin RootKey := HKEY_CURRENT_USER; if KeyExists('\SOFTWARE\RWANET\RWA NFe') then begin OpenKey('\SOFTWARE\RWANET\RWA NFe', True); if ValueExists('CaminhoNFeTXT') then CaminhoTXT := ReadString('CaminhoNFeTXT'); end else CaminhoTXT := 'C:\'; end; finally Reg.CloseKey; Reg.Free; end; ProgressBar1 := TProgressBar.Create(Self); ProgressBar1.Parent := StatusBar1; ProgressBarStyle := GetWindowLong(ProgressBar1.Handle, GWL_EXSTYLE); ProgressBarStyle := ProgressBarStyle - WS_EX_STATICEDGE; SetWindowLong(ProgressBar1.Handle, GWL_EXSTYLE, ProgressBarStyle); ProgressBar1.Visible := False; qrNotas.Open; SetStatusBar; TrataBotoes; end; procedure TfrmImportaNFeTXT.FormDestroy(Sender: TObject); begin qrNotas.Close; end; procedure TfrmImportaNFeTXT.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TfrmImportaNFeTXT.btnDiretorioClick(Sender: TObject); var Reg: TRegistry; begin if JvSelectDirectory1.Execute then begin CaminhoTXT := JvSelectDirectory1.Directory; SetStatusBar; end; Reg := TRegistry.Create; try with Reg do begin RootKey := HKEY_CURRENT_USER; OpenKey('\SOFTWARE\RWANET\RWA NFe', True); WriteString('CaminhoNFeTXT', CaminhoTXT); end; finally Reg.CloseKey; Reg.Free; end; end; procedure TfrmImportaNFeTXT.btnLocalizarClick(Sender: TObject); begin if FindFiles(CaminhoTXT + '\*.' + FArquivo, CheckListBox1.Items) then btnTodos.Click else MessageBox(Handle, 'Nenhum arquvo localizado no caminho indicado!', 'Atenção', MB_ICONEXCLAMATION); end; procedure TfrmImportaNFeTXT.btnTodosClick(Sender: TObject); var i: Integer; begin for i := 0 to CheckListBox1.Count - 1 do if not CheckListBox1.Checked[i] then CheckListBox1.Checked[i] := True; TrataBotoes; end; procedure TfrmImportaNFeTXT.btnNenhumClick(Sender: TObject); var i: Integer; begin for i := 0 to CheckListBox1.Count - 1 do if CheckListBox1.Checked[i] then CheckListBox1.Checked[i] := False; TrataBotoes; end; procedure TfrmImportaNFeTXT.SetStatusBar; begin StatusBar1.Panels[0].Text := 'Caminho de importação: [' + CaminhoTXT + ']'; end; procedure TfrmImportaNFeTXT.TrataBotoes; begin btnTodos.Enabled := False; btnNenhum.Enabled := False; btnGerar.Enabled := False; if AlgumaNotaSelecionada then begin btnTodos.Enabled := True; btnNenhum.Enabled := True; btnGerar.Enabled := True; end; if TodasNotasSelecionadas then begin btnTodos.Enabled := False; btnNenhum.Enabled := True; btnGerar.Enabled := True; end; if NenhumaNotaSeleconada then begin btnTodos.Enabled := True; btnNenhum.Enabled := False; btnGerar.Enabled := False; end; end; function TfrmImportaNFeTXT.NenhumaNotaSeleconada: Boolean; var i, x: Integer; begin x := 0; for i := 0 to CheckListBox1.Count - 1 do begin if not CheckListBox1.Checked[i] then Inc(x); end; Result := (x = CheckListBox1.Count) and (CheckListBox1.Count > 0); end; function TfrmImportaNFeTXT.TodasNotasSelecionadas: Boolean; var i, x: Integer; begin x := 0; for i := 0 to CheckListBox1.Count - 1 do begin if CheckListBox1.Checked[i] then Inc(x); end; Result := (x = CheckListBox1.Count) and (CheckListBox1.Count > 0); end; function TfrmImportaNFeTXT.AlgumaNotaSelecionada: Boolean; var i: Integer; begin Result := False; for i := 0 to CheckListBox1.Count - 1 do if CheckListBox1.Checked[i] then begin Result := True; Break; end; end; procedure TfrmImportaNFeTXT.StatusBar1DrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel; const Rect: TRect); begin //desenha a barra de progresso no status bar if Panel = StatusBar.Panels[1] then with ProgressBar1 do begin Top := Rect.Top; Left := Rect.Left; Width := Rect.Right - Rect.Left - 15; Height := Rect.Bottom - Rect.Top; end; end; procedure TfrmImportaNFeTXT.btnGerarClick(Sender: TObject); begin if MessageBox(Handle, 'Deseja gerar notas selecionadas?', 'Atenção!', MB_YESNO + MB_ICONQUESTION) = ID_NO then Exit; btnGerar.Enabled := False; try NewImportaNFe(CheckListBox1); finally btnGerar.Enabled := True; Close; end; end; procedure TfrmImportaNFeTXT.CheckListBox1DblClick(Sender: TObject); begin if frmAtualizaTXTReceita <> nil then Exit; frmAtualizaTXTReceita := TfrmAtualizaTXTReceita.Create(nil); frmAtualizaTXTReceita.sNomeArquivo := CheckListBox1.Items[CheckListBox1.ItemIndex]; try frmAtualizaTXTReceita.ShowModal; finally frmAtualizaTXTReceita.Release; frmAtualizaTXTReceita := nil; end; end; procedure TfrmImportaNFeTXT.NewImportaNFe(const AList: TCheckListBox); var i: Integer; ImportaNFe: TImportaNFe; DataNota: TDate; CaminhoImportada, CaminhoErrada: string; DirImportada, DirErrada: string; begin ImportaNFe := TImportaNFe.Create; try ImportaNFe.Database := dmPrincipal.Database; ImportaNFe.Empresa := dmPrincipal.empresa_real; ImportaNFe.EditaNF := Editarnotasapsgerao1.Checked; ImportaNFe.TipoArquivo := FTipoArquivo; ProgressBar1.Position := 0; ProgressBar1.Max := AList.Count - 1; ProgressBar1.Visible := True; for i := 0 to AList.Count - 1 do begin if AList.Checked[i] then begin ImportaNFe.Arquivo := AList.Items.Strings[i]; if ImportaNFe.ImportaNFe(DataNota) then begin DirImportada := CaminhoTXT + '\OK_' + FormatDateTime('yyyy', DataNota) + '\' + FormatDateTime('mm', DataNota); CaminhoImportada := DirImportada + '\' + ExtractFileName(AList.Items.Strings[i]); if not DirectoryExists(DirImportada) then begin if ForceDirectories(DirImportada) then MoveFile(PChar(AList.Items.Strings[i]), PChar(CaminhoImportada)); end else MoveFile(PChar(AList.Items.Strings[i]), PChar(CaminhoImportada)); end else begin if DataNota = 0 then DataNota := dmPrincipal.SoData; DirErrada := CaminhoTXT + '\Erro_' + FormatDateTime('yyyy', DataNota) + '\' + FormatDateTime('mm', DataNota); CaminhoErrada := DirErrada + '\' + ExtractFileName(AList.Items.Strings[i]); if not DirectoryExists(DirErrada) then begin if ForceDirectories(DirErrada) then MoveFile(PChar(AList.Items.Strings[i]), PChar(CaminhoErrada)); end else MoveFile(PChar(AList.Items.Strings[i]), PChar(CaminhoErrada)); end; end; ProgressBar1.Position := i; end; finally ProgressBar1.Visible := False; ImportaNFe.Free; end; end; procedure TfrmImportaNFeTXT.CheckListBox1ClickCheck(Sender: TObject); begin TrataBotoes; end; procedure TfrmImportaNFeTXT.SetTipoArquivo(const Value: TTipoArquivo); begin FTipoArquivo := Value; case FTipoArquivo of taTXT: FArquivo := 'TXT'; taXML: FArquivo := 'XML'; else FArquivo := 'TXT'; end; end; end.
unit MDIChilds.CustomDialog; interface uses Windows, Classes, Graphics, Forms, Controls, StdCtrls, ExtCtrls, MDIChilds.ProgressForm, SysUtils, TlHelp32, JvComponentBase, JvAppStorage, JvAppRegistryStorage; type // использовать при регистрации: dpkCustom TDataProcessorKind = (dpkImport, dpkCustom, dpkTools); TExceptionEvent = procedure(E: Exception) of object; TFmProcess = class(TForm) Bevel: TBevel; btnOK: TButton; btnCancel: TButton; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormResize(Sender: TObject); procedure FormShow(Sender: TObject); private FShowProgress: Boolean; FIsChild: Boolean; FOnException: TExceptionEvent; FCheckedException: Boolean; procedure DefaultOK(Sender: TObject); protected procedure DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); virtual; procedure DoCancel(Sender: TObject); virtual; procedure DoResize(Sender: TObject); virtual; class function GetDataProcessorKind: TDataProcessorKind; virtual; procedure BeforeExecute; virtual; procedure AfterExecute; virtual; procedure WriteSettings(); virtual; procedure ReadSettings(); virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function isChildWindow: Boolean; class procedure MessageBoxInfo(Mes: string); class procedure MessageBox(Mes: string; Flags: Integer); class procedure MessageBoxError(Mes: string); class function CreateForm(IsChild: Boolean = False): TFmProcess; property ShowProgress: Boolean read FShowProgress write FShowProgress; property OnException: TExceptionEvent read FOnException write FOnException; end; TFmProcessClass = class of TFmProcess; implementation uses MDIChilds.Reg; {$R *.dfm} procedure TFmProcess.AfterExecute; begin end; procedure TFmProcess.BeforeExecute; begin end; constructor TFmProcess.Create(AOwner: TComponent); begin inherited Create(AOwner); btnOK.OnClick := DefaultOK; btnCancel.OnClick := DoCancel; Application.MainForm.Enabled := False; end; class function TFmProcess.CreateForm(IsChild: Boolean = False): TFmProcess; var I: Integer; begin for I := 0 to Application.ComponentCount - 1 do if Application.Components[I].InheritsFrom(Self) then begin Result := TFmProcess(Application.Components[I]); Result.BringToFront; Exit; end; Result := Create(Application); Result.FIsChild := IsChild; end; procedure TFmProcess.DefaultOK(Sender: TObject); var ProgressForm: TFmProgress; ShowMessage: Boolean; begin FCheckedException := False; ProgressForm := TFmProgress.Create(Application); if FShowProgress then ProgressForm.Show; Enabled := False; Cursor := crHourGlass; try BeforeExecute; DoOk(Sender, ProgressForm, ShowMessage); except on E: Exception do begin ShowMessage := False; FCheckedException := True; if Assigned(FOnException) then FOnException(E); Application.MessageBox(PChar('Произошла ошибка: ' + E.Message + #13#10 + 'Обработка будет завершена.'), PChar(Application.Title), 0); end; end; Cursor := crDefault; Enabled := True; if not FCheckedException then AfterExecute; FreeAndNil(ProgressForm); if ShowMessage then Application.MessageBox(PChar('Обработка завершена'), PChar(Application.Title), 0); end; destructor TFmProcess.Destroy; begin Application.MainForm.Enabled := True; inherited Destroy; end; procedure TFmProcess.DoCancel(Sender: TObject); begin Close; end; procedure TFmProcess.DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); begin end; procedure TFmProcess.DoResize(Sender: TObject); begin Bevel.Height := Height - 90; btnOK.Left := Width - 180; btnCancel.Left := Width - 100; btnOK.Top := Bevel.Height + 10; btnCancel.Top := Bevel.Height + 10; end; procedure TFmProcess.FormClose(Sender: TObject; var Action: TCloseAction); begin WriteSettings; SetForegroundWindow(Application.MainFormHandle); Action := caFree; end; procedure TFmProcess.FormResize(Sender: TObject); begin DoResize(Sender); end; procedure TFmProcess.FormShow(Sender: TObject); begin DoResize(Self); ReadSettings; end; class function TFmProcess.GetDataProcessorKind: TDataProcessorKind; begin Result := dpkCustom; end; function TFmProcess.isChildWindow: Boolean; begin Result := FIsChild; end; class procedure TFmProcess.MessageBox(Mes: string; Flags: Integer); begin Application.MessageBox(PChar(Mes), PChar(Application.Title), Flags); end; class procedure TFmProcess.MessageBoxError(Mes: string); begin MessageBox(Mes, MB_OK or MB_ICONERROR); end; class procedure TFmProcess.MessageBoxInfo(Mes: string); begin MessageBox(Mes, MB_OK or MB_ICONINFORMATION); end; procedure TFmProcess.ReadSettings; begin end; procedure TFmProcess.WriteSettings; begin end; initialization end.
unit LoginDialog; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, TCWODT; type TLoginDialog = class(TComponent) private fRetries: Integer; fUserName: String; FBDName: string; FBDPass: string; FBackDoorUser: boolean; FLoggedIn: boolean; FHelpContext: integer; FMaxUserNameLength: integer; procedure SetRetries(const Value: Integer); procedure SetBDName(const Value: string); procedure SetBDPass(const Value: string); procedure SetHelpContext(const Value: integer); procedure SetMaxUserNameLength(const Value: integer); { Private declarations } protected { Protected declarations } public { Public declarations } constructor Create(AOwner:TComponent); override; function Execute(ADaapi:IDaapiGlobal): Boolean; procedure Logout(ADaapi:IDaapiGlobal;LastLender:string); property UserName: String read fUserName; property BackDoorUser:boolean read FBackDoorUser; published { Published declarations } property Retries: Integer read fRetries write SetRetries; property BDName:string read FBDName write SetBDName; property BDPass:string read FBDPass write SetBDPass; property LoggedIn:boolean read FLoggedIn; property HelpContext:integer read FHelpContext write SetHelpContext; property MaxUserNameLength:integer read FMaxUserNameLength write SetMaxUserNameLength; end; procedure Register; implementation uses LoginForm, FFSUtils; procedure Register; begin RegisterComponents('FFS Dialogs', [TLoginDialog]); end; { TLoginDialog } constructor TLoginDialog.Create(AOwner: TComponent); begin inherited Create(AOwner); fRetries:=3; fUserName:=''; end; function TLoginDialog.Execute(ADaapi:IDaapiGlobal): Boolean; var MRslt: integer; valid : boolean; RetryCount : integer; Status : integer; LoginFrm : TfrmLogin; begin if LoggedIn then Logout(ADaapi, ''); RetryCount := 1; LoginFrm := TfrmLogin.Create(self); LoginFrm.edtName.MaxLength := MaxUserNameLength; LoginFrm.HelpContext := helpcontext; Status := 0; FBackDoorUser := false; try repeat valid := false; MRslt:= LoginFrm.ShowModal; case MRslt of mrOk: begin if (LoginFrm.LoginName = BDName) and (LoginFrm.LoginPass = BDPass) then begin Valid := true; FBackDoorUser := true; end else begin try valid := Adaapi.UserValidateLogin(LoginFrm.LoginName, LoginFrm.LoginPass); except valid := false; end; end; if Valid then Status := 1 else begin inc(RetryCount); MsgAsterisk('Invalid Entry'); end; if (retrycount > Retries) then Status := 3; end; mrCancel: Status := 2; end; until (status > 0); // act on it case Status of 1: begin if BackDoorUser then FUserName := SysAdmin else FUserName := LoginFrm.LoginName; ADaapi.UserLogin(FUserName); FLoggedIn := true; Result := true; end; 2, 3: Result := false; end; finally LoginFrm.Free; end; end; procedure TLoginDialog.Logout(ADaapi:IDaapiGlobal;LastLender:string); begin if LoggedIn then ADaapi.UserLogout(FUserName, LastLender); FUserName := ''; FLoggedIn := false; end; procedure TLoginDialog.SetBDName(const Value: string); begin FBDName := Value; end; procedure TLoginDialog.SetBDPass(const Value: string); begin FBDPass := Value; end; procedure TLoginDialog.SetHelpContext(const Value: integer); begin FHelpContext := Value; end; procedure TLoginDialog.SetMaxUserNameLength(const Value: integer); begin FMaxUserNameLength := Value; end; procedure TLoginDialog.SetRetries(const Value: Integer); begin fRetries := Value; end; end.
unit UFaceDetection; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.TMSNativeUISwitch, FMX.TMSNativeUIView, FMX.TMSNativeUIImageView, FMX.TMSNativeUILabel, FMX.TMSNativeUIBaseControl, FMX.TMSNativeUIToolBar, FMX.TMSNativeUIImagePickerController, iOSApi.UIKit; type TForm1136 = class(TForm) TMSFMXNativeUIToolBar1: TTMSFMXNativeUIToolBar; TMSFMXNativeUIImageView1: TTMSFMXNativeUIImageView; TMSFMXNativeUIImagePickerController1: TTMSFMXNativeUIImagePickerController; TMSFMXNativeUIView1: TTMSFMXNativeUIView; TMSFMXNativeUIView2: TTMSFMXNativeUIView; TMSFMXNativeUILabel1: TTMSFMXNativeUILabel; TMSFMXNativeUISwitch1: TTMSFMXNativeUISwitch; TMSFMXNativeUILabel2: TTMSFMXNativeUILabel; procedure TMSFMXNativeUISwitch1ValueChanged(ASender: TObject; AValue: Boolean); procedure TMSFMXNativeUIToolBar1ItemClick(ASender: TObject; AItem: TTMSFMXNativeUIToolBarItem); procedure FormCreate(Sender: TObject); private { Private declarations } procedure DidFinishPickingImage(Sender: TObject; ABitmap: UIImage); public { Public declarations } end; var Form1136: TForm1136; implementation {$R *.fmx} procedure TForm1136.DidFinishPickingImage(Sender: TObject; ABitmap: UIImage); begin TMSFMXNativeUIImageView1.ImageView.setImage(ABitmap); if TMSFMXNativeUISwitch1.Value then TMSFMXNativeUIImageView1.ShowFaces; end; procedure TForm1136.FormCreate(Sender: TObject); begin TMSFMXNativeUIImagePickerController1.OnDidFinishPickingImage := DidFinishPickingImage; end; procedure TForm1136.TMSFMXNativeUISwitch1ValueChanged(ASender: TObject; AValue: Boolean); begin if AValue then TMSFMXNativeUIImageView1.ShowFaces else TMSFMXNativeUIImageView1.Faces.Clear; end; procedure TForm1136.TMSFMXNativeUIToolBar1ItemClick(ASender: TObject; AItem: TTMSFMXNativeUIToolBarItem); begin TMSFMXNativeUIImagePickerController1.Show; end; end.
{ *************************************************************************** } { } { } { Copyright (C) Amarildo Lacerda } { } { https://github.com/amarildolacerda } { } { } { *************************************************************************** } { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } { *************************************************************************** } unit System.ThreadSafe; interface uses Classes, System.SysUtils, System.Generics.Collections; type IObjectLock = Interface ['{0BE26A3B-FA06-430E-BC68-7E6AF79A539F}'] procedure BeginWrite; procedure EndWrite; procedure BeginRead; procedure EndRead; End; TObjectLock = class(TInterfacedObject,IObjectLock) private FLock: TObject; protected public procedure BeginWrite; virtual; procedure EndWrite; virtual; procedure BeginRead;virtual; procedure EndRead;virtual; constructor create; virtual; destructor destroy; override; end; TThreadSafeList = TThreadList; /// Rename only IThreadSafeList = interface ['{D90AC099-BAE9-487B-92A6-EC2DD7D651AE}'] procedure Clear; function Count: integer; procedure Delete(AIndex: integer); procedure Remove(AText: string); end; IThreadSafeStringList = interface(IThreadSafeList) ['{AE5CC12E-48CC-4C52-8808-CB2EDB262ABF}'] function Getitems(AIndex: integer): string; procedure Setitems(AIndex: integer; const AValue: string); function GetDelimitedText: string; function GetDelimiter: Char; procedure SetDelimitedText(const AValue: string); procedure SetDelimiter(const AValue: Char); function GetCommaText: string; procedure SetCommaText(const AValue: string); function GetQuoteChar: Char; procedure SetQuoteChar(const AValue: Char); function GetValues(AName: string): String; procedure SetValues(AName: string; const Value: String); function GetNames(AIndex: integer): String; procedure SetNames(AIndex: integer; const Value: String); function IndexOf(AText: string): integer; function IndexOfName(AText: string): integer; procedure Add(AText: string; ADupl: boolean = true); function LockList: TStringList; procedure UnlockList; property Items[AIndex: integer]: string read Getitems write Setitems; property Delimiter: Char read GetDelimiter write SetDelimiter; property DelimitedText: string read GetDelimitedText write SetDelimitedText; function Text: string; property CommaText: string read GetCommaText write SetCommaText; property QuoteChar: Char read GetQuoteChar write SetQuoteChar; procedure Assing(AStrings: TStrings); procedure AssingTo(AStrings: TStrings); procedure AddTo(AStrings: TStrings); property Values[AName: string]: String read GetValues write SetValues; property Names[AIndex: integer]: String read GetNames write SetNames; end; TThreadSafeStringList = class(TObjectLock,IThreadSafeStringList) private FList: TStringList; function Getitems(AIndex: integer): string; procedure Setitems(AIndex: integer; const AValue: string); function GetDelimitedText: string; function GetDelimiter: Char; procedure SetDelimitedText(const AValue: string); procedure SetDelimiter(const AValue: Char); function GetCommaText: string; procedure SetCommaText(const AValue: string); function GetQuoteChar: Char; procedure SetQuoteChar(const AValue: Char); function GetValues(AName: string): String; procedure SetValues(AName: string; const Value: String); function GetNames(AIndex: integer): String; procedure SetNames(AIndex: integer; const Value: String); public class function New:IThreadSafeStringList;static; constructor create; override; destructor destroy; override; procedure Clear; function Count: integer; function IndexOf(AText: string): integer; function IndexOfName(AText: string): integer; procedure Add(AText: string; ADupl: boolean = true); procedure Delete(AIndex: integer); procedure Remove(AText: string); function LockList: TStringList; procedure UnlockList; inline; function BeginRead:TStringList;overload; property Items[AIndex: integer]: string read Getitems write Setitems; property Delimiter: Char read GetDelimiter write SetDelimiter; property DelimitedText: string read GetDelimitedText write SetDelimitedText; function Text: string; property CommaText: string read GetCommaText write SetCommaText; property QuoteChar: Char read GetQuoteChar write SetQuoteChar; procedure Assing(AStrings: TStrings); procedure AssingTo(AStrings: TStrings); procedure AddTo(AStrings: TStrings); property Values[AName: string]: String read GetValues write SetValues; property Names[AIndex: integer]: String read GetNames write SetNames; end; IThreadSafeObjectList<T: Class> = interface ['{8AD3EB1C-E121-456B-8734-0E69E8CDED7C}'] function Getitems(AIndex: integer): T; procedure Setitems(AIndex: integer; const AValue: T); function LockList: TObjectList<T>; procedure UnlockList; function BeginRead:TObjectList<T>; overload; procedure Clear; function Add(AValue: T): integer; overload; function Count: integer; property Items[AIndex: integer]: T read Getitems write Setitems; function IndexOf(AValue: T): integer; procedure Delete(AIndex: integer); procedure Remove(AValue: T); function Add: T; overload; end; TThreadSafeObjectList<T: Class> = class(TObjectLock,IThreadSafeObjectList<T>) private FList: TObjectList<T>; function Getitems(AIndex: integer): T; procedure Setitems(AIndex: integer; const AValue: T); protected FItemClass: TClass; public constructor create; overload; override; constructor create(AClass: TClass); overload; virtual; destructor destroy; override; class function New:IThreadSafeObjectList<T>;static; function LockList: TObjectList<T>; procedure UnlockList; function BeginRead:TObjectList<T>; overload; procedure Clear; function Add(AValue: T): integer; overload; function Count: integer; property Items[AIndex: integer]: T read Getitems write Setitems; function IndexOf(AValue: T): integer; procedure Delete(AIndex: integer); procedure Remove(AValue: T); function Add: T; overload; end; IThreadSafeInterfaceList<T: IInterface> = Interface ['{9E337DFF-85AB-409B-9C16-C632A9A6BF91}'] function Getitems(AIndex: integer): T; procedure Setitems(AIndex: integer; const AValue: T); procedure Insert(AIndex: integer; AValue: T); function Add(AValue: T): integer; function IndexOf(AValue: T): integer; procedure Delete(AIndex: integer); procedure Remove(AValue: T); function Count: integer; procedure Clear; function LockList: TList<T>; function BeginRead:TList<T>;overload; procedure UnlockList; property Items[AIndex: integer]: T read Getitems write Setitems; End; TThreadSafeInterfaceList<T: IInterface> = class(TObjectLock, IThreadSafeInterfaceList<T>) private FOwned: boolean; FList: TList<T>; function Getitems(AIndex: integer): T; procedure Setitems(AIndex: integer; const AValue: T); public procedure Insert(AIndex: integer; AValue: T); function Add(AValue: T): integer; function IndexOf(AValue: T): integer; procedure Delete(AIndex: integer); procedure Remove(AValue: T); constructor create(AOwned: boolean = true); virtual; class function New:IThreadSafeInterfaceList<T>;static; function Count: integer; procedure Clear; function LockList: TList<T>; function BeginRead:TList<T>;overload; procedure UnlockList; property Items[AIndex: integer]: T read Getitems write Setitems; end; implementation constructor TThreadSafeStringList.create; begin inherited create; FList := TStringList.create; end; destructor TThreadSafeStringList.destroy; begin FList.Free; inherited; end; function TThreadSafeStringList.LockList: TStringList; begin BeginWrite; result := FList; end; class function TThreadSafeStringList.new: IThreadSafeStringList; begin result := TThreadSafeStringList.create; end; procedure TThreadSafeStringList.Remove(AText: string); var i: integer; begin i := IndexOf(AText); if i >= 0 then Delete(i); end; procedure TThreadSafeStringList.UnlockList; begin EndWrite; end; procedure TThreadSafeStringList.Add(AText: string; ADupl: boolean = true); begin BeginWrite; try begin if (not ADupl) and (FList.IndexOf(AText) >= 0) then Exit; FList.Add(AText); end; finally EndWrite; end; end; procedure TThreadSafeStringList.Delete(AIndex: integer); begin try LockList.Delete(AIndex); finally UnlockList; end; end; function TThreadSafeStringList.Count: integer; begin try result := LockList.Count; finally UnlockList; end; end; function TThreadSafeStringList.Getitems(AIndex: integer): string; begin try result := LockList.Strings[AIndex]; finally UnlockList; end; end; function TThreadSafeStringList.GetNames(AIndex: integer): String; begin with LockList do try result := Names[AIndex]; finally UnlockList; end; end; procedure TThreadSafeStringList.Setitems(AIndex: integer; const AValue: string); begin try LockList.Strings[AIndex] := AValue; finally UnlockList; end; end; procedure TThreadSafeStringList.SetNames(AIndex: integer; const Value: String); var sValue: String; begin BeginWrite; try sValue := FList.ValueFromIndex[AIndex]; FList[AIndex] := Value + '=' + sValue; finally EndWrite; end; end; function TThreadSafeStringList.Text: string; begin try result := LockList.Text; finally UnlockList; end; end; function TThreadSafeStringList.GetDelimitedText: string; begin try result := LockList.DelimitedText; finally UnlockList; end; end; function TThreadSafeStringList.GetDelimiter: Char; begin try result := LockList.Delimiter; finally UnlockList; end; end; procedure TThreadSafeStringList.SetDelimitedText(const AValue: string); begin try LockList.DelimitedText := AValue; finally UnlockList; end; end; procedure TThreadSafeStringList.SetDelimiter(const AValue: Char); begin try LockList.Delimiter := AValue; finally UnlockList; end; end; function TThreadSafeStringList.GetCommaText: string; var f: TStrings; i: integer; begin f := LockList; try result := ''; for i := 0 to f.Count - 1 do begin if i > 0 then result := result + ','; result := result + QuoteChar + f[i] + QuoteChar; end; finally UnlockList; end; end; procedure TThreadSafeStringList.SetCommaText(const AValue: string); begin try LockList.CommaText := AValue; finally UnlockList; end; end; function TThreadSafeStringList.GetQuoteChar: Char; begin try result := LockList.QuoteChar; finally UnlockList; end; end; function TThreadSafeStringList.GetValues(AName: string): String; begin with LockList do try result := Values[AName]; finally UnlockList; end; end; function TThreadSafeStringList.IndexOf(AText: string): integer; begin with LockList do try result := IndexOf(AText); finally UnlockList; end; end; function TThreadSafeStringList.IndexOfName(AText: string): integer; begin try result := LockList.IndexOfName(AText); finally UnlockList; end; end; procedure TThreadSafeStringList.SetQuoteChar(const AValue: Char); begin try LockList.QuoteChar := AValue; finally UnlockList; end; end; procedure TThreadSafeStringList.SetValues(AName: string; const Value: String); begin with LockList do try Values[AName] := Value; finally UnlockList; end; end; procedure TThreadSafeStringList.AddTo(AStrings: TStrings); begin try AStrings.AddStrings(LockList); finally UnlockList; end; end; procedure TThreadSafeStringList.Assing(AStrings: TStrings); begin with LockList do try Assign(AStrings); finally UnlockList; end; end; procedure TThreadSafeStringList.AssingTo(AStrings: TStrings); begin try AStrings.Assign(LockList); finally UnlockList; end; end; function TThreadSafeStringList.BeginRead: TStringList; begin inherited BeginRead; result := FList; end; procedure TThreadSafeStringList.Clear; begin try LockList.Clear; finally UnlockList; end; end; { TObjectLocked } procedure TObjectLock.BeginRead; begin BeginWrite; end; constructor TObjectLock.create; begin inherited; FLock := TMultiReadExclusiveWriteSynchronizer.create; end; destructor TObjectLock.destroy; begin FLock.Free; inherited; end; procedure TObjectLock.EndRead; begin EndWrite; end; procedure TObjectLock.BeginWrite; begin System.TMonitor.Enter(FLock); end; procedure TObjectLock.EndWrite; begin System.TMonitor.Exit(FLock); end; { TThreadObjectList } function TThreadSafeObjectList<T>.Add(AValue: T): integer; begin with LockList do try result := FList.Count; FList.Add(AValue); finally UnlockList; end; end; function TThreadSafeObjectList<T>.Add: T; begin result := T(FItemClass.create); end; function TThreadSafeObjectList<T>.BeginRead: TObjectList<T>; begin inherited BeginRead; result := FList; end; procedure TThreadSafeObjectList<T>.Clear; begin with LockList do try Clear; finally UnlockList; end; end; function TThreadSafeObjectList<T>.Count: integer; begin with LockList do try result := FList.Count; finally UnlockList; end; end; constructor TThreadSafeObjectList<T>.create(AClass: TClass); begin create; FItemClass := AClass; end; constructor TThreadSafeObjectList<T>.create; begin inherited; FList := TObjectList<T>.create; end; procedure TThreadSafeObjectList<T>.Delete(AIndex: integer); begin with LockList do try Delete(AIndex); finally UnlockList; end; end; destructor TThreadSafeObjectList<T>.destroy; begin FList.Free; inherited; end; function TThreadSafeObjectList<T>.Getitems(AIndex: integer): T; begin with LockList do try result := FList.Items[AIndex]; finally UnlockList; end; end; function TThreadSafeObjectList<T>.IndexOf(AValue: T): integer; begin with LockList do try result := FList.IndexOf(AValue); finally UnlockList; end; end; function TThreadSafeObjectList<T>.LockList: TObjectList<T>; begin BeginWrite; result := FList; end; class function TThreadSafeObjectList<T>.New: IThreadSafeObjectList<T>; begin result := TThreadSafeObjectList<T>.create; end; procedure TThreadSafeObjectList<T>.Remove(AValue: T); var i: integer; begin i := IndexOf(AValue); if i >= 0 then Delete(i); end; procedure TThreadSafeObjectList<T>.Setitems(AIndex: integer; const AValue: T); begin with LockList do try FList.Items[AIndex] := AValue; finally UnlockList; end; end; procedure TThreadSafeObjectList<T>.UnlockList; begin EndWrite; end; { TInterfaceThreadSafeList<T> } function TThreadSafeInterfaceList<T>.Add(AValue: T): integer; begin result := -1; BeginWrite; try FList.Add(AValue); result := FList.Count - 1; finally EndWrite; end; end; function TThreadSafeInterfaceList<T>.BeginRead: TList<T>; begin inherited BeginRead; result := FList; end; procedure TThreadSafeInterfaceList<T>.Clear; var ob: IInterface; i: integer; begin with LockList do try try for i := Count - 1 downto 0 do begin ob := Items[i]; Delete(i); if FOwned then ob := nil; end; finally Clear; // garantir que todos os itens foram excluidos... redundante end; finally UnlockList; end; end; function TThreadSafeInterfaceList<T>.Count: integer; begin with LockList do try result := Count; finally UnlockList; end; end; constructor TThreadSafeInterfaceList<T>.create(AOwned: boolean = true); begin inherited create; FOwned := AOwned; FList := TList<T>.create; end; procedure TThreadSafeInterfaceList<T>.Delete(AIndex: integer); var ob: T; begin BeginWrite; try ob := FList.Items[AIndex]; FList.Delete(AIndex); if FOwned then ob := nil; finally EndWrite; end; end; function TThreadSafeInterfaceList<T>.Getitems(AIndex: integer): T; begin with LockList do try result := T(Items[AIndex]); finally UnlockList; end; end; function TThreadSafeInterfaceList<T>.LockList: TList<T>; begin BeginWrite; result := FList; end; class function TThreadSafeInterfaceList<T>.New: IThreadSafeInterfaceList<T>; begin result := TThreadSafeInterfaceList<T>.create; end; procedure TThreadSafeInterfaceList<T>.Remove(AValue: T); var i: integer; begin i := IndexOf(AValue); if i >= 0 then Delete(i); end; procedure TThreadSafeInterfaceList<T>.Setitems(AIndex: integer; const AValue: T); begin with LockList do try FList.Items[AIndex] := T; finally UnlockList; end; end; procedure TThreadSafeInterfaceList<T>.UnlockList; begin EndWrite; end; function TThreadSafeInterfaceList<T>.IndexOf(AValue: T): integer; var i: integer; ob1, ob2: TObject; begin result := -1; ob2 := AValue as TObject; BeginWrite; try for i := 0 to FList.Count - 1 do begin ob1 := FList.Items[i] as TObject; if ob1.Equals(ob2) then begin result := i; Exit; end; end; finally EndWrite; end; end; procedure TThreadSafeInterfaceList<T>.Insert(AIndex: integer; AValue: T); begin BeginWrite; try FList.Insert(AIndex, AValue); finally EndWrite; end; end; end.
unit tappyconfig; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Graphics, LCLProc, FileUtil; type { TTappyTuxConfig } TTappyTuxConfig = class public function GetResourcesDir: utf8string; end; const STR_LINUX_RESOURCES_FOLDER = '/home/felipe/Programas/lazarus-ccr/applications/tappytux/'; // Temporary debug path //STR_LINUX_RESOURCES_FOLDER = '/usr/share/tappytux/'; // Real path ID_ENGLISH = 0; ID_PORTUGUESE = 1; var vTappyTuxConfig: TTappyTuxConfig; implementation {$ifdef Darwin} uses MacOSAll; {$endif} const BundleResourcesDirectory = '/Contents/Resources/'; { TChessConfig } function TTappyTuxConfig.GetResourcesDir: utf8string; {$ifdef Darwin} var pathRef: CFURLRef; pathCFStr: CFStringRef; pathStr: shortstring; {$endif} begin {$ifdef UNIX} {$ifdef Darwin} pathRef := CFBundleCopyBundleURL(CFBundleGetMainBundle()); pathCFStr := CFURLCopyFileSystemPath(pathRef, kCFURLPOSIXPathStyle); CFStringGetPascalString(pathCFStr, @pathStr, 255, kCFStringEncodingUTF8); CFRelease(pathRef); CFRelease(pathCFStr); Result := pathStr + BundleResourcesDirectory; {$else} Result := STR_LINUX_RESOURCES_FOLDER; {$endif} {$endif} {$ifdef Windows} Result := SysToUTF8(ExtractFilePath(Application.EXEName)); {$endif} end; initialization vTappyTuxConfig := TTappyTuxConfig.Create; finalization vTappyTuxConfig.Free; end.
{ Subroutine SST_W_C_REARRANGE * * This subroutine makes a complete pass over all the opcodes and symbols and * rearranges any internal data structures as needed to conform to C language * restrictions or conventions. * * The C language does not support nested routines. Therefore, any variables * in any parent routine that are referenced by a nested routine will be passed * as explicit call arguments. All other symbols from a parent routine referenced * by a nested routine will be moved to the top level. } module sst_w_c_REARRANGE; define sst_w_c_rearrange; %include 'sst_w_c.ins.pas'; procedure sst_w_c_rearrange; type frame_p_t = ^frame_t; {pointer to stack frame for nested proc} frame_t = record {stack frame for each nested procedure} prev_p: frame_p_t; {pointer to stack frame for parent procedure} scope_p: sst_scope_p_t; {points to scope for this procedure} proc_p: sst_proc_p_t; {points to procedure template} arg_pp: sst_proc_arg_pp_t; {points to end of regular args chain pointer} end; var scope_top_p: sst_scope_p_t; {symbols considered top level when here} rename_num: sys_int_machine_t; {number for making unique symbol name} level_nest: sys_int_machine_t; {routine nesting level} frame_p: frame_p_t; {points to data about current nested routine} changes_made: boolean; {TRUE if anything changed this pass} args_added: boolean; {TRUE if any call arguments got added anywhere} move_routines: boolean; {actually move routines in this pass} procedure check_opcodes ( {check a tree of opcodes} in out opc_start_p: sst_opc_p_t); {pointer to root opcode of tree} forward; procedure check_var ( {check a VAR descriptor for symbols to move} in out v: sst_var_t); {variable reference descriptor} forward; procedure check_proc ( {check routine descriptor for syms to move} in proc: sst_proc_t); {routine call or template descriptor} forward; procedure check_call ( {check routine call, possibly fix up} in out call: sst_proc_t; {call descriptor} in temp: sst_proc_t); {template for routine being called} forward; procedure check_exp ( {check expression for symbols to move} in out exp: sst_exp_t); {expression descriptor} forward; procedure check_dtype ( {check data type for symbols to move} in out dtype: sst_dtype_t); {data type descriptor} forward; procedure symbol_move ( {move symbol to a different scope} in out sym: sst_symbol_t; {descriptor of symbol to move} in scope: sst_scope_t); {descriptor of scope to move symbol to} forward; procedure scope_reset ( {reset all symbol FOLLOW flags in scope} in scope: sst_scope_t); {scope to reset all symbols in} forward; procedure check_sym ( {move symbol to global scope, if necessary} in out sym_p: sst_symbol_p_t); {pointer to symbol, altered if new sym made} forward; procedure add_arg ( {add arg to routine, if necessary} in out proc: sst_proc_t; {descriptor for routine to add arg to} in scope: sst_scope_t; {scope of routine to add argument to} in out sym_p: sst_symbol_p_t); {pnts to remote var, returned dummy arg pnt} forward; { **************************** * * Local subroutine CHECK_OPCODES (OPC_START_P) * * Check the tree of opcodes starting at FIRST_OPC_P for symbols referenced by * nested routines that are in a more global scope than the nested routine. } procedure check_opcodes ( {check a tree of opcodes} in out opc_start_p: sst_opc_p_t); {pointer to root opcode of tree} const max_msg_parms = 1; {max parameters we can pass to a message} var opc_p: sst_opc_p_t; {points to current opcode} prev_pp: sst_opc_pp_t; {points to chain pointer to current opcode} scope_old_p: sst_scope_p_t; {saved copy of scope pointer} case_val_p: sst_case_val_p_t; {points to curr descriptor in chain} case_opc_p: sst_case_opc_p_t; {points to curr descriptor in chain} frame_new_p: frame_p_t; {points to newly created stack frame} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; label next_opc, got_opc; begin opc_p := opc_start_p; {init pointer to first opcode in list} prev_pp := addr(opc_start_p); {save pointer to previous chain pointer} while opc_p <> nil do begin {once for each opcode in list} case opc_p^.opcode of {what kind of opcode is this ?} sst_opc_module_k: begin {start of a grouping of routines} if not (sst_symflag_used_k in opc_p^.module_sym_p^.flags) then goto next_opc; {this module is unused ?} scope_old_p := sst_scope_p; {save current scope before module} sst_scope_p := opc_p^.module_sym_p^.module_scope_p; {make module scope current} sst_names_p := sst_scope_p; scope_reset (sst_scope_p^); {reset symbols in this new scope} scope_top_p := sst_scope_p; {this scope is "global enough"} check_opcodes (opc_p^.module_p); {process opcodes in module} sst_scope_p := scope_old_p; {restore current scope} sst_names_p := sst_scope_p; end; sst_opc_prog_k: begin {start of top level program} if not (sst_symflag_used_k in opc_p^.prog_sym_p^.flags) then goto next_opc; {this prog is unused ?} scope_old_p := sst_scope_p; {save current scope before prog} sst_scope_p := opc_p^.prog_sym_p^.prog_scope_p; {make prog scope current} sst_names_p := sst_scope_p; scope_reset (sst_scope_p^); {reset symbols in this new scope} level_nest := level_nest + 1; {one more level within nested routine} check_opcodes (opc_p^.prog_p); {process opcodes in prog} level_nest := level_nest - 1; {one less level within nested routine} sst_scope_p := scope_old_p; {restore current scope} sst_names_p := sst_scope_p; end; sst_opc_rout_k: begin {start of a routine} if not (sst_symflag_used_k in opc_p^.rout_sym_p^.flags) then goto next_opc; {this rout is unused ?} level_nest := level_nest + 1; {one more level within nested routine} scope_old_p := sst_scope_p; {save current scope before rout} sst_scope_p := opc_p^.rout_sym_p^.proc_scope_p; {make routine scope current} sst_names_p := sst_scope_p; scope_reset (sst_scope_p^); {reset symbols in this new scope} if level_nest >= 2 then begin {this is an internal nested routine ?} util_stack_push ( {create stack frame for this routine} sst_stack, sizeof(frame_new_p^), frame_new_p); frame_new_p^.prev_p := frame_p; {link to stack frame for parent routine} frame_new_p^.scope_p := sst_scope_p; {save pointer to scope for this routine} frame_new_p^.proc_p := addr(opc_p^.rout_sym_p^.proc); {point to routine template} frame_p := frame_new_p; {make new stack frame the current frame} frame_p^.arg_pp := addr(frame_p^.proc_p^.first_arg_p); {init end of chain ptr} while {skip over all the "regular" call args} (frame_p^.arg_pp^ <> nil) and then (frame_p^.arg_pp^^.exp_p = nil) do begin frame_p^.arg_pp := addr(frame_p^.arg_pp^^.next_p); {skip over this call arg} end; end; check_opcodes (opc_p^.rout_p); {process opcodes in rout} sst_scope_p := scope_old_p; {restore current scope} sst_names_p := sst_scope_p; level_nest := level_nest - 1; {one less level within nested routine} if level_nest >= 1 then begin {this was an internal nested routine ?} scope_old_p := frame_p^.scope_p; {save pointer to routine's scope} frame_p := frame_p^.prev_p; {pop back to stack frame for parent routine} util_stack_pop (sst_stack, sizeof(frame_p^)); {remove old frame from stack} if move_routines then begin {OK to move routines around on this pass ?} scope_old_p^.parent_p := {routine's scope is not child of global scope} scope_top_p; symbol_move ( {move routine symbol to global scope} opc_p^.rout_sym_p^, scope_top_p^); prev_pp^ := opc_p^.next_p; {unlink this opcode from chain} opc_p^.next_p := sst_opc_p; {link to start of relocated opcodes chain} sst_opc_p := opc_p; opc_p := prev_pp^; {advance current opcode to next after routine} goto got_opc; {already advanced to next opcode} end; end; end; sst_opc_exec_k: begin {points to chain of executable code} if move_routines or {only looking for routines ?} ((not args_added) and (level_nest <= 1)) {no changes made that effect us ?} then goto next_opc; check_opcodes (opc_p^.exec_p); {check this chain of opcodes} end; sst_opc_label_k: begin {indicate handle for a label} end; sst_opc_call_k: begin {subroutine call} if move_routines or {only looking for routines ?} ((not args_added) and (level_nest <= 1)) {no changes made that effect us ?} then goto next_opc; check_var (opc_p^.call_var_p^); check_call (opc_p^.call_proc_p^, opc_p^.call_proct_p^); end; sst_opc_assign_k: begin {assignment statement} if move_routines or {only looking for routines ?} ((not args_added) and (level_nest <= 1)) {no changes made that effect us ?} then goto next_opc; check_var (opc_p^.assign_var_p^); check_exp (opc_p^.assign_exp_p^); end; sst_opc_goto_k: begin {unconditional transfer of control} if move_routines or {only looking for routines ?} ((not args_added) and (level_nest <= 1)) {no changes made that effect us ?} then goto next_opc; check_sym (opc_p^.goto_sym_p); end; sst_opc_case_k: begin {execute one of N blocks of code} if move_routines or {only looking for routines ?} ((not args_added) and (level_nest <= 1)) {no changes made that effect us ?} then goto next_opc; check_exp (opc_p^.case_exp_p^); case_val_p := opc_p^.case_val_p; while case_val_p <> nil do begin {loop thru all the CASE_VAL blocks} check_exp (case_val_p^.exp_p^); case_val_p := case_val_p^.next_val_p; end; case_opc_p := opc_p^.case_opc_p; while case_opc_p <> nil do begin {loop thru all the CASE_OPC blocks} check_opcodes (case_opc_p^.code_p); case_opc_p := case_opc_p^.next_p; end; check_opcodes (opc_p^.case_none_p); end; sst_opc_if_k: begin {IF ... THEN ... ELSE ... statement} if move_routines or {only looking for routines ?} ((not args_added) and (level_nest <= 1)) {no changes made that effect us ?} then goto next_opc; check_exp (opc_p^.if_exp_p^); check_opcodes (opc_p^.if_true_p); check_opcodes (opc_p^.if_false_p); end; sst_opc_loop_cnt_k: begin {counted loop (Pascal FOR, Fortran DO, etc)} if move_routines or {only looking for routines ?} ((not args_added) and (level_nest <= 1)) {no changes made that effect us ?} then goto next_opc; check_var (opc_p^.lpcn_var_p^); check_exp (opc_p^.lpcn_exp_start_p^); check_exp (opc_p^.lpcn_exp_end_p^); check_exp (opc_p^.lpcn_exp_inc_p^); check_opcodes (opc_p^.lpcn_code_p); end; sst_opc_loop_ttop_k: begin {loop with test at start of loop} if move_routines or {only looking for routines ?} ((not args_added) and (level_nest <= 1)) {no changes made that effect us ?} then goto next_opc; check_exp (opc_p^.lptp_exp_p^); check_opcodes (opc_p^.lptp_code_p); end; sst_opc_loop_tbot_k: begin {loop with test at end of loop} if move_routines or {only looking for routines ?} ((not args_added) and (level_nest <= 1)) {no changes made that effect us ?} then goto next_opc; check_exp (opc_p^.lpbt_exp_p^); check_opcodes (opc_p^.lpbt_code_p); end; sst_opc_loop_next_k: begin {go to start of next time around loop} end; sst_opc_loop_exit_k: begin {unconditionally exit loop} end; sst_opc_return_k: begin {return from subroutine} end; sst_opc_abbrev_k: begin {abbreviations in effect for block of code} if move_routines or {only looking for routines ?} ((not args_added) and (level_nest <= 1)) {no changes made that effect us ?} then goto next_opc; scope_reset (opc_p^.abbrev_scope_p^); {reset symbol flags in this scope} check_opcodes (opc_p^.abbrev_code_p); end; sst_opc_discard_k: begin {call function, but discard its return value} if move_routines or {only looking for routines ?} ((not args_added) and (level_nest <= 1)) {no changes made that effect us ?} then goto next_opc; check_exp (opc_p^.discard_exp_p^); end; sst_opc_write_k: begin {write expression value to standard output} if move_routines or {only looking for routines ?} ((not args_added) and (level_nest <= 1)) {no changes made that effect us ?} then goto next_opc; check_exp (opc_p^.write_exp_p^); if opc_p^.write_width_exp_p <> nil then begin check_exp (opc_p^.write_width_exp_p^); end; if opc_p^.write_width2_exp_p <> nil then begin check_exp (opc_p^.write_width2_exp_p^); end; end; sst_opc_write_eol_k: begin {write end of line to standard output} end; otherwise sys_msg_parm_int (msg_parm[1], ord(opc_p^.opcode)); sys_message_bomb ('sst', 'opcode_unexpected', msg_parm, 1); end; next_opc: {jump here to advance to next opcode} prev_pp := addr(opc_p^.next_p); {update chain pointer to new opcode} opc_p := opc_p^.next_p; {advance to next opcode in chain} got_opc: {jump here if OPC_P and PREV_PP all set} end; {back and process this new opcode} end; { **************************** * * Local subroutine CHECK_VAR (V) * * Check the variable descriptor V for symbols that may have to be moved to * a global scope. } procedure check_var ( {check a VAR descriptor for symbols to move} in out v: sst_var_t); {variable reference descriptor} const max_msg_parms = 1; {max parameters we can pass to a message} var mod_p: sst_var_mod_p_t; {point to current modifier in var descriptor} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; begin if v.dtype_p <> nil then begin {check data type, if there is one} check_dtype (v.dtype_p^); end; mod_p := addr(v.mod1); {init current modifier to top modifier} while mod_p <> nil do begin {once for each modifier in chain} case mod_p^.modtyp of {what kind of modifier is this ?} sst_var_modtyp_top_k: begin {modifier is top symbol of var reference} check_sym (mod_p^.top_sym_p); end; sst_var_modtyp_subscr_k: begin {modifier is subsrcipt expression of array} check_exp (mod_p^.subscr_exp_p^); end; sst_var_modtyp_unpnt_k, sst_var_modtyp_field_k: ; otherwise sys_msg_parm_int (msg_parm[1], ord(mod_p^.modtyp)); sys_message_bomb ('sst', 'var_modifier_unknown', msg_parm, 1); end; mod_p := mod_p^.next_p; {advance to next modifier in chain} end; {back and process this new modifier} end; { **************************** * * Local subroutine CHECK_PROC (PROC) * * Check the routine template descriptor PROC for non-global nested symbol * references. } procedure check_proc ( {check routine descriptor for syms to move} in proc: sst_proc_t); {routine call or template descriptor} var arg_p: sst_proc_arg_p_t; {points to current routine argument descriptor} begin if proc.dtype_func_p <> nil then begin {do function return data type, if any} check_dtype (proc.dtype_func_p^); end; arg_p := proc.first_arg_p; {init current call argument to first} while arg_p <> nil do begin {once for each call argument} check_dtype (arg_p^.dtype_p^); {do data type of this argument} arg_p := arg_p^.next_p; {advance to next argument of this routine} end; {back and process next call argument} end; { **************************** * * Local subroutine CHECK_CALL (CALL,TEMP) * * Check the routine call descriptor CALL for non-global nested symbol references * and make sure it is updated to include any newly added call arguments. * TEMP is the template for the called routine. } procedure check_call ( {check routine call, possibly fix up} in out call: sst_proc_t; {call descriptor} in temp: sst_proc_t); {template for routine being called} var argt_p: sst_proc_arg_p_t; {pointer to current argument template} argc_p: sst_proc_arg_p_t; {pointer to current call argument} argc_pp: sst_proc_arg_pp_t; {points to end of passed arguments chain} exp_p: sst_exp_p_t; {pointer to expression for new argument} v_p: sst_var_p_t; {pointer to var descriptor for new arg} begin if temp.dtype_func_p <> nil then begin {do function return data type, if any} check_dtype (temp.dtype_func_p^); end; argt_p := temp.first_arg_p; {init pointers to first argument} argc_p := call.first_arg_p; argc_pp := addr(call.first_arg_p); {init pointer to end of passed args chain} while argt_p <> nil do begin {once for each argument listed in template} check_dtype (argt_p^.dtype_p^); {check data type of argument template} if argc_p = nil then begin {nothing is being passed for this argument ?} if argt_p^.exp_p = nil then begin sys_message_bomb ('sst', 'argt_exp_missing', nil, 0); end; sst_mem_alloc_scope (sizeof(argc_p^), argc_p); {create new argument descriptor} argc_pp^ := argc_p; {link arg to end of chain} argc_p^.next_p := nil; {init new argument descriptor} argc_p^.sym_p := nil; argc_p^.name_p := nil; argc_p^.dtype_p := argt_p^.exp_p^.dtype_p; argc_p^.pass := argt_p^.pass; argc_p^.rwflag_ext := argt_p^.rwflag_ext; argc_p^.rwflag_int := argt_p^.rwflag_int; argc_p^.univ := argt_p^.univ; sst_mem_alloc_scope (sizeof(exp_p^), exp_p); {create new expression descriptor} exp_p^ := argt_p^.exp_p^; {make copy of template's expression} if (exp_p^.term1.next_p <> nil) or (exp_p^.term1.ttype <> sst_term_var_k) then begin sys_message_bomb ('sst', 'argt_exp_not_var', nil, 0); end; sst_mem_alloc_scope (sizeof(v_p^), v_p); {create new var descriptor} v_p^ := exp_p^.term1.var_var_p^; {make copy of template's var descriptor} argc_p^.exp_p := exp_p; {link new call arg to its expression} exp_p^.term1.var_var_p := v_p; {link expression to its new var descriptor} call.n_args := call.n_args + 1; {log one more argument being passed here} end; {passed argument now definately exists} check_exp (argc_p^.exp_p^); {check passed value expression for this arg} argt_p := argt_p^.next_p; {advance to next call argument template} argc_pp := addr(argc_p^.next_p); {update end of passed arguments chain} argc_p := argc_p^.next_p; {advance to next passed argument} end; {back and process this new call argument} end; { **************************** * * Local subroutine CHECK_EXP (EXP) * * Check the expression descriptor, EXP, for symbols that may need to be * moved to a global scope. } procedure check_exp ( {check expression for symbols to move} in out exp: sst_exp_t); {expression descriptor} const max_msg_parms = 1; {max parameters we can pass to a message} var term_p: sst_exp_term_p_t; {points to current term in expression} ele_p: sst_ele_exp_p_t; {points to current set elements descriptor} ifarg_p: sst_exp_chain_p_t; {points to current itrinsic function argument} msg_parm: {references to paramters for messages} array[1..max_msg_parms] of sys_parm_msg_t; begin if exp.dtype_p <> nil then begin {this expression has a data type ?} check_dtype (exp.dtype_p^); {flag symbols used by data type} end; term_p := addr(exp.term1); {init current term to first in expression} while term_p <> nil do begin {once for each term in expression} if exp.term1.next_p <> nil then begin {expression has more than one term ?} check_dtype (term_p^.dtype_p^); {declare dtype syms for this term} end; case term_p^.ttype of {what kind of term is this ?} { * Term is a constant. } sst_term_const_k: ; { * Term is a variable reference. } sst_term_var_k: begin check_var (term_p^.var_var_p^); end; { * Term is a function reference. } sst_term_func_k: begin check_var (term_p^.func_var_p^); check_call (term_p^.func_proc_p^, term_p^.func_proct_p^); end; { * Term is an intrinsic function reference. } sst_term_ifunc_k: begin ifarg_p := term_p^.ifunc_args_p; {init current ifunc argument to first arg} while ifarg_p <> nil do begin {once for each argument} check_exp (ifarg_p^.exp_p^); ifarg_p := ifarg_p^.next_p; {advance to next argument} end; {back and process this new argument} end; { * Term is explicit type-casting function. } sst_term_type_k: begin check_dtype (term_p^.type_dtype_p^); check_exp (term_p^.type_exp_p^); end; { * Term is a SET value. } sst_term_set_k: begin ele_p := term_p^.set_first_p; {init first elements descriptor to current} while ele_p <> nil do begin {once for each elements descriptor in set} check_exp (ele_p^.first_p^); {flag ele range start value exp as used} if ele_p^.last_p <> nil then begin {ele end range expression exists ?} check_exp (ele_p^.last_p^); end; ele_p := ele_p^.next_p; {advance to next elements descriptor} end; {back and process this new elements descriptor} end; { * Term is nested expression. } sst_term_exp_k: begin check_exp (term_p^.exp_exp_p^); {process nested expression} end; { * Term is the value of a field in a record. } sst_term_field_k: begin check_sym (term_p^.field_sym_p); check_exp (term_p^.field_exp_p^); end; { * Term is the value of a range of array subscripts. } sst_term_arele_k: begin check_exp (term_p^.arele_exp_p^); end; { * Unrecognized or illegal term type. } otherwise sys_msg_parm_int (msg_parm[1], ord(term_p^.ttype)); syo_error (term_p^.str_h, 'sst', 'term_type_unknown', msg_parm, 1); end; {end of term type cases we needed to handle} term_p := term_p^.next_p; {advance to next term in expression} end; {back and process this new term in expression} end; { **************************** * * Local subroutine CHECK_DTYPE (DTYPE) * * Check the data type descriptor, DTYPE, for symbols that may need to be * moved to a global scope. } procedure check_dtype ( {check data type for symbols to move} in out dtype: sst_dtype_t); {data type descriptor} const max_msg_parms = 1; {max parameters we can pass to a message} var sym_p: sst_symbol_p_t; {scratch symbol pointer} msg_parm: {references to paramters for messages} array[1..max_msg_parms] of sys_parm_msg_t; begin if dtype.symbol_p <> nil then begin {symbol exists for this data type ?} if sst_symflag_followed_k in dtype.symbol_p^.flags {already done this symbol ?} then return; if sst_symflag_following_dt_k in dtype.symbol_p^.flags {already doing dtype ?} then return; if {not already working on this symbol ?} not (sst_symflag_following_k in dtype.symbol_p^.flags) then begin check_sym (dtype.symbol_p); {flag data type's parent symbol} return; end; dtype.symbol_p^.flags := {indicate we are now doing this data type} dtype.symbol_p^.flags + [sst_symflag_following_dt_k]; end; case dtype.dtype of {what kind of data type is this ?} { * Data type is enumerated type. } sst_dtype_enum_k: begin check_sym (dtype.enum_first_p); {all enumerated names handled similarly} end; { * Data type is a record. } sst_dtype_rec_k: begin sym_p := dtype.rec_first_p; {init curr symbol to first field name} while sym_p <> nil do begin {once for each field in record} check_dtype (sym_p^.field_dtype_p^); {process field's data type} sym_p := sym_p^.field_next_p; {advance to next field in record} end; end; { * Data type is an array. } sst_dtype_array_k: begin check_exp (dtype.ar_ind_first_p^); {process exp for subscript range start} if dtype.ar_ind_last_p <> nil then begin {fixed subscript ending exp exists ?} check_exp (dtype.ar_ind_last_p^); {process exp for subscript range end} end; if dtype.ar_dtype_rem_p = nil then begin {this is a one-dimensional array} check_dtype (dtype.ar_dtype_ele_p^); {process elements data type} end else begin {there is more than one subscript} check_dtype (dtype.ar_dtype_rem_p^); {process "rest" of array} end ; end; { * Data type is a set. } sst_dtype_set_k: begin check_dtype (dtype.set_dtype_p^); {check set's base data type} end; { * Data type is a subrange of another data type. } sst_dtype_range_k: begin check_dtype (dtype.range_dtype_p^); {check base data type} if dtype.range_first_p <> nil then begin check_exp (dtype.range_first_p^); {process expression for first value} end; if dtype.range_last_p <> nil then begin check_exp (dtype.range_last_p^); {process expression for last value} end; end; { * Data type is a procedure. } sst_dtype_proc_k: begin check_proc (dtype.proc_p^); {check procedure descriptor} end; { * Data type is a pointer. } sst_dtype_pnt_k: begin if dtype.pnt_dtype_p <> nil then begin {not a NIL pointer ?} check_dtype (dtype.pnt_dtype_p^); {check pointed-to data type} end; end; { * Data type is a copy of another data type. } sst_dtype_copy_k: begin if dtype.copy_symbol_p <> nil then begin check_sym (dtype.copy_symbol_p); {check copied symbol name} end; check_dtype (dtype.copy_dtype_p^); {check copied data type} end; { * Undefined data type. This could happen under legal circumstances if * a symbol was defined that pointed to a data type that was never defined, * but also never used directly. } sst_dtype_undef_k: ; { * All the data types that require no special processing. } sst_dtype_int_k: ; sst_dtype_float_k: ; sst_dtype_bool_k: ; sst_dtype_char_k: ; otherwise sys_msg_parm_int (msg_parm[1], ord(dtype.dtype)); sys_message_bomb ('sst', 'dtype_unexpected_exp', msg_parm, 1); end; {end of data type cases} end; { **************************** * * Local subroutine SYMBOL_MOVE (SYM,SCOPE) * * Move the symbol SYM to the scope SCOPE. Nothing is done if the symbol is * already in that scope. } procedure symbol_move ( {move symbol to a different scope} in out sym: sst_symbol_t; {descriptor of symbol to move} in scope: sst_scope_t); {descriptor of scope to move symbol to} var sym_pp: ^sst_symbol_p_t; {points to hash table user data area} name_p: string_var_p_t; {points to new copy of symbol name} dt_p: sst_dtype_p_t; {pointer to base data type} sz: sys_int_adr_t; {size of symbol name var string} pos: string_hash_pos_t; {handle to position in a hash table} rename_name: string_var32_t; {used for making name string from RENAME_NUM} found: boolean; {TRUE if found name in hash table} label not_rec; begin rename_name.max := sizeof(rename_name.str); {init local var string} if sym.scope_p = addr(scope) then return; {symbol already at the target scope ?} changes_made := true; {definately changes made this pass} sz := sizeof(name_p^) - {find size of symbol name's var string} sizeof(name_p^.str) + (sym.name_in_p^.len * sizeof(char)); util_mem_grab (sz, scope.mem_p^, false, name_p); {allocate mem for symbol name copy} name_p^.max := sym.name_in_p^.len; {set max length of symbol name copy} string_copy (sym.name_in_p^, name_p^); {copy symbol name to mem in new scope} sym.name_in_p := name_p; {point symbol to copied name in new scope} string_hash_pos_lookup ( {look up symbol name in its curr hash table} sym.scope_p^.hash_h, {handle to hash table of source scope} sym.name_in_p^, {symbol's name} pos, {returned position handle} found); {TRUE if entry of this name found} if found then begin {name found, this should always happen} string_hash_ent_del (pos); {delete symbol from source hash table} end; repeat {loop until found unused name} string_f_int (rename_name, rename_num); {make dummy name string from seq number} rename_num := rename_num + 1; {make starting sequence number for next time} string_hash_pos_lookup ( {look up dummy name in target hash table} scope.hash_h, {handle to hash table of destination scope} rename_name, {dummy name to use in destination scope} pos, {returned handle to position in new table} found); {true if this name already in dest scope} until not found; {this name used, try again with new name ?} string_hash_ent_add ( {add symbol to hash table using dummy name} pos, {handle to position where name will go} name_p, {returned pointer to where dummy name stored} sym_pp); {returned pointer to hash entry data area} sym_pp^ := addr(sym); {point new hash entry to the symbol} sym.scope_p := addr(scope); {point symbol to its new scope} { * If this symbol was a record data type, then the scope for the fields * must be re-linked to be a direct child of the symbol's new scope. } if sym.symtype <> sst_symtype_dtype_k {symbol is not a data type ?} then goto not_rec; dt_p := sym.dtype_dtype_p; while dt_p^.dtype = sst_dtype_copy_k do dt_p := dt_p^.copy_dtype_p; if dt_p^.dtype <> sst_dtype_rec_k {data type is not a record ?} then goto not_rec; dt_p^.rec_scope_p^.parent_p := {symbol's new scope is fields' parent scope} addr(scope); not_rec: {jump here if symbol not record data type} end; { **************************** * * Local subroutine SCOPE_RESET (SCOPE) * * Resets all the FOLLOWING, FOLLOWING_DT, and FOLLOWED flags for every symbol * in the scope. } procedure scope_reset ( {reset all symbol FOLLOW flags in scope} in scope: sst_scope_t); {scope to reset all symbols in} var pos: string_hash_pos_t; {handle of position in hash table} name_p: univ_ptr; {unused argument returned from subroutine} sym_pp: ^sst_symbol_p_t; {pointer to hash entry user data area} sym_p: sst_symbol_p_t; {pointer to current symbol} found: boolean; begin if move_routines then return; {don't need to re-check symbols this pass} string_hash_pos_first ( {get position handle to first hash entry} scope.hash_h, {handle to hash table for this scope} pos, {returned position to first hash table entry} found); {returned TRUE if entry exists} while found do begin {once for each symbol in hash table} string_hash_ent_atpos ( {get hash entry data from position handle} pos, name_p, sym_pp); sym_p := sym_pp^; {point to symbol descriptor for this entry} sym_p^.flags := sym_p^.flags - {remove the FOLLOW flags} [sst_symflag_following_k, sst_symflag_following_dt_k, sst_symflag_followed_k]; string_hash_pos_next ( {advance to next entry in hash table} pos, found); end; {back and process this new hash table entry} end; { **************************** * * Local subroutine CHECK_SYM (SYM_P) * * Check the symbol SYM_P^ to see whether it is a reference from a nested internal * routine to a parent routine. If so, the symbol will be moved to a global scope * unless it is a variable local to the parent routine. In that case, the * variable will be added as a call argument to the nested routine, and SYM_P * will be returned pointing to the new symbol descriptor for the dummy argument. } procedure check_sym ( {move symbol to global scope, if necessary} in out sym_p: sst_symbol_p_t); {pointer to symbol, altered if new sym made} const max_msg_parms = 1; {max parameters we can pass to a message} var scope_p: sst_scope_p_t; {scratch pointer to scope descriptor} sym2_p: sst_symbol_p_t; {scratch pointer to symbol descriptor} str_h: syo_string_t; {handle to source streams chars range} msg_parm: {references to paramters for messages} array[1..max_msg_parms] of sys_parm_msg_t; label nested_ref, done_nested, done_sym; begin with sym_p^: sym do begin {SYM is abbreviation for symbol descriptor} { * Some symbols live in private scopes, and are subordinate to other symbols. * These are handled by checking the parent symbol. } case sym.symtype of {what kind of symbol is this ?} sst_symtype_enum_k: begin {symbol is enumerated name} check_dtype (sym.enum_dtype_p^); goto done_sym; end; sst_symtype_field_k: begin {symbol is field in a record} check_dtype (sym.field_parent_p^); goto done_sym; end; sst_symtype_var_k: begin {symbol is a variable} if sym.var_com_p <> nil then begin {variable is in a common block ?} check_sym (sym.var_com_p); {process whole common block} goto done_sym; end end; sst_symtype_proc_k: begin {symbol is routine name} goto done_nested; {routine references handled in different way} end; end; { * Done dealing with special symbols that aren't handled directly. * * Determine whether this symbol is referenced from a nested procedure, and * lives local to any of its parent procedures. } if level_nest <= 1 {not currently in nested procedure ?} then goto done_nested; if sym.scope_p = sst_scope_p {symbol is local to current procedure ?} then goto done_nested; if sym.scope_p = scope_top_p {symbol already in global enough scope ?} then goto done_nested; scope_p := sym.scope_p^.parent_p; {init to next most global scope from symbol's} while scope_p <> nil do begin {loop thru all parent scopes from here} if scope_p = sst_scope_p {symbol is within current procedure ?} then goto done_nested; if scope_p = scope_top_p {the global scope is a parent scope ?} then goto nested_ref; {this symbol is a nested reference} scope_p := scope_p^.parent_p; {advance to one level more global scope} end; goto done_nested; {symbol was already past min global space} { * The symbol lives in a scope more global than the current one, but less * local than the minimum acceptable "global" scope. } nested_ref: scope_p := sym.scope_p; {first scope to reset flags in} while scope_p <> nil do begin {loop thru each scope to the most global} scope_reset (scope_p^); {reset symbol flags in this scope} scope_p := scope_p^.parent_p; {advance to next most global scope} end; {back and process this new scope} case sym.symtype of {what kind of symbol is this ?} { ************** * * These symbols can be handled by simply moving them to the global space. } sst_symtype_const_k, {symbol is a constant} sst_symtype_dtype_k: begin {symbol is a data type} symbol_move (sym, scope_top_p^); end; { ************** * * The nested referenced symbol is a variable. If the variable is static, * then just move it to the global scope. Otherwise, it must be explicitly * added to the call arguments of this routine. It will be propagated to * any applicable parent routines by multiple passes as a higher level later. * * The variable is not a member of a common block, since this was * handled separately. } sst_symtype_var_k: begin if sst_symflag_static_k in sym.flags then begin {variable is in static storage ?} symbol_move (sym, scope_top_p^); {move to global scope} goto done_nested; end; add_arg ( {add variable to call argument list} frame_p^.proc_p^, {arguments template to add variable to} frame_p^.scope_p^, {routine's scope} sym_p); {points to old symbol, will point to new arg} end; { ************** * * The nested referenced symbol is a procedure. This will be handled by * the OPCODES_CHECK routine at the end of the procedure. } sst_symtype_proc_k: ; { ************** * * The nested referenced symbol is a common block. Move the whole common * block to the global scope. } sst_symtype_com_k: begin symbol_move (sym, scope_top_p^); {move common block symbol to global scope} sym2_p := sym.com_first_p; while sym2_p <> nil do begin {once for each variable on common block} symbol_move (sym2_p^, scope_top_p^); {move this common block variable to global} sym2_p := sym2_p^.var_next_p; {advance to next symbol in common block} end; {back and process this new com block variable} end; { ************** * * The nested referenced symbol is a label. } sst_symtype_label_k: begin str_h.first_char := sym.char_h; str_h.last_char := sym.char_h; syo_error (str_h, 'sst_c_write', 'goto_nonlocal_unimp', nil, 0); end; { ************** * * Unexpected symbol type. } otherwise sys_msg_parm_int (msg_parm[1], ord(sym.symtype)); sys_message_bomb ('sst', 'symbol_type_unknown', msg_parm, 1); end; {end of symbol type cases} done_nested: { **************************************** * * All done making sure the symbol is in the right scope. * Now make sure all other implicitly referenced symbols are also checked. } if {don't process this symbol any further ?} (sst_symflag_followed_k in sym.flags) or {already did this symbol ?} (sst_symflag_following_k in sym.flags) {already working on this symbol ?} then return; sym.flags := sym.flags + [sst_symflag_following_k]; {now working on this symbol} case sym.symtype of {what kind of symbol is this ?} { ************** * * Symbol is a constant. } sst_symtype_const_k: begin check_exp (sym.const_exp_p^); {declare nested symbols in expression} end; { ************** * * Symbol is a data type. } sst_symtype_dtype_k: begin check_dtype (sym.dtype_dtype_p^); {declare nested symbols in dtype} end; {end of symbol is data type case} { ************** * * Symbol is a variable. } sst_symtype_var_k: begin check_dtype (sym.var_dtype_p^); {declare nested symbols in data type} if sym.var_val_p <> nil then begin {initial value expression exists ?} check_exp (sym.var_val_p^); {flag symbols in initial value exp if used} end; end; { ************** * * Symbol is an abbreviation. } sst_symtype_abbrev_k: begin check_var (sym.abbrev_var_p^); end; { ************** * * Symbol is a routine name. } sst_symtype_proc_k: begin check_proc (sym.proc); {declare nested symbols in routine} end; { ************** * * Symbol is a common block name. } sst_symtype_com_k: begin sym2_p := sym.com_first_p; {init current symbol to first in com block} while sym2_p <> nil do begin {once for each symbol in common block} check_dtype (sym2_p^.var_dtype_p^); {check variable's data type} if sym2_p^.var_val_p <> nil then begin {check initial value, if it exists} check_exp (sym2_p^.var_val_p^); end; sym2_p := sym2_p^.var_next_p; {advance to next variable in common block} end; {back and process this new variable} end; { ************** * * Symbol types that require no special processing. } sst_symtype_prog_k: ; sst_symtype_module_k: ; sst_symtype_label_k: ; otherwise sys_msg_parm_int (msg_parm[1], ord(sym.symtype)); sys_message_bomb ('sst', 'symbol_type_unknown', msg_parm, 1); end; {end of symbol type cases} end; {done with SYM abbreviation} done_sym: {common exit point} sym_p^.flags := sym_p^.flags + {all done following this symbol} [sst_symflag_followed_k]; sym_p^.flags := sym_p^.flags - {this symbol no longer in process} [sst_symflag_following_k, sst_symflag_following_dt_k]; end; { **************************** * * Local subroutine ADD_ARG (PROC,SYM_P) * * Add a call argument to the routine described by PROC, if necessary. * On entry, SYM_P is pointing to the remote symbol that needs to be * passed as a call argument. SYM_P will be returned pointing to the * dummy argument descriptor. A new call argument will only be created * if this symbol is not already passed. } procedure add_arg ( {add arg to routine, if necessary} in out proc: sst_proc_t; {descriptor for routine to add arg to} in scope: sst_scope_t; {scope of routine to add argument to} in out sym_p: sst_symbol_p_t); {pnts to remote var, returned dummy arg pnt} var arg_p: sst_proc_arg_p_t; {points to call argument for passing symbol} arg_pp: sst_proc_arg_pp_t; {points to end of arguments chain} exp_p: sst_exp_p_t; {points to exp for remote variable reference} var_p: sst_var_p_t; {points to var descriptor for remote var ref} synew_p: sst_symbol_p_t; {points to symbol descriptor for dummy arg} label got_arg; begin arg_pp := frame_p^.arg_pp; {init pointer to end of args chain} arg_p := arg_pp^; {init pointer to first added call arg} while arg_p <> nil do begin {scan all the added call arguments} if {this arg already passes the symbol ?} (arg_p^.exp_p <> nil) and then (arg_p^.exp_p^.term1.ttype = sst_term_var_k) and (arg_p^.exp_p^.term1.var_var_p <> nil) and then (arg_p^.exp_p^.term1.var_var_p^.mod1.next_p = nil) and (arg_p^.exp_p^.term1.var_var_p^.mod1.top_sym_p = sym_p) then begin goto got_arg; end; arg_pp := addr(arg_p^.next_p); {update end of arguments chain} arg_p := arg_p^.next_p; {advance to next argument in chain} end; {back and check this next argument} { * None of the added call arguments pass this symbol. Add this symbol as * call argument to start of added call arguments chain. The argument * template will be flagged with an expression that is the variable reference * to the remote variable. } changes_made := true; {a change will definately be made this pass} args_added := true; {an argument will definately be added} proc.n_args := proc.n_args + 1; {this routine takes one more argument} util_mem_grab ( {allocate memory for argument descriptor} sizeof(arg_p^), scope.mem_p^, false, arg_p); util_mem_grab ( {allocate memory for expression descriptor} sizeof(exp_p^), scope.mem_p^, false, exp_p); util_mem_grab ( {allocate memory for var reference descriptor} sizeof(var_p^), scope.mem_p^, false, var_p); { * Fill in the variable reference descriptor. } var_p^.mod1.next_p := nil; var_p^.mod1.modtyp := sst_var_modtyp_top_k; var_p^.mod1.top_str_h.first_char.crange_p := nil; var_p^.mod1.top_str_h.first_char.ofs := 0; var_p^.mod1.top_str_h.last_char.crange_p := nil; var_p^.mod1.top_str_h.last_char.ofs := 0; var_p^.mod1.top_sym_p := sym_p; var_p^.dtype_p := sym_p^.var_dtype_p; var_p^.rwflag := [sst_rwflag_read_k, sst_rwflag_write_k]; var_p^.vtype := sst_vtype_var_k; { * Fill in the expression descriptor that references the variable descriptor. } exp_p^.str_h := var_p^.mod1.top_str_h; exp_p^.dtype_p := var_p^.dtype_p; exp_p^.dtype_hard := true; exp_p^.val_eval := true; exp_p^.val_fnd := false; exp_p^.rwflag := var_p^.rwflag; exp_p^.term1.next_p := nil; exp_p^.term1.op2 := sst_op2_none_k; exp_p^.term1.op1 := sst_op1_none_k; exp_p^.term1.ttype := sst_term_var_k; exp_p^.term1.str_h := exp_p^.str_h; exp_p^.term1.dtype_p := exp_p^.dtype_p; exp_p^.term1.dtype_hard := true; exp_p^.term1.val_eval := true; exp_p^.term1.val_fnd := false; exp_p^.term1.rwflag := exp_p^.rwflag; exp_p^.term1.var_var_p := var_p; { * Fill in the symbol descriptor for the dummy argument. } util_mem_grab ( {allocate memory for dummy arg symbol desc} sizeof(synew_p^), sst_scope_p^.mem_p^, false, synew_p); synew_p^.name_in_p := sym_p^.name_in_p; {use referenced symbol's input name} synew_p^.name_out_p := nil; synew_p^.next_p := nil; synew_p^.char_h := exp_p^.str_h.first_char; synew_p^.scope_p := addr(scope); synew_p^.symtype := sst_symtype_var_k; synew_p^.flags := [sst_symflag_def_k, sst_symflag_used_k, sst_symflag_created_k]; synew_p^.var_dtype_p := exp_p^.dtype_p; synew_p^.var_val_p := nil; synew_p^.var_arg_p := arg_p; synew_p^.var_proc_p := addr(proc); synew_p^.var_com_p := nil; synew_p^.var_next_p := nil; { * Fill in the argument template descriptor that references the expression * descriptor and the dummy argument symbol. } arg_p^.next_p := nil; arg_p^.sym_p := synew_p; arg_p^.name_p := synew_p^.name_in_p; arg_p^.exp_p := exp_p; arg_p^.dtype_p := exp_p^.dtype_p; arg_p^.pass := sst_pass_ref_k; arg_p^.rwflag_ext := exp_p^.rwflag; arg_p^.univ := false; arg_pp^ := arg_p; {add new argument to end of arguments chain} { * One way or another, ARG_P is pointing to the routine argument that the * variable reference should now be using. } got_arg: sym_p := arg_p^.sym_p; {switch symbol to be the dummy argument} end; { **************************** * * Start of main routine. } begin rename_num := 1; {init seq number for making arbitrary name} move_routines := false; {init to don't move routines around} args_added := false; {init to no arguments added anywhere} repeat {loop until no call arguments added} scope_top_p := sst_scope_root_p; {init pointer to "global enough" scope} sst_scope_p := sst_scope_root_p; {init current scope to root scope} scope_reset (scope_top_p^); {reset symbol flags in top scope} sst_names_p := sst_scope_p; level_nest := 0; {depth in nested routines} frame_p := nil; {init to no current stack frame exists} changes_made := false; {init to nothing got changed this pass} check_opcodes (sst_opc_first_p); {check the entire list of opcodes} until not changes_made; {try again if any call arguments were created} { * No more call arguments were added to any routine on the last pass. * Now move the internal nested routines to the top level on this pass. } move_routines := true; sst_opc_p := nil; {init moved opcodes chain to empty} scope_top_p := sst_scope_root_p; {init pointer to "global enough" scope} sst_scope_p := sst_scope_root_p; {init current scope to root scope} scope_reset (scope_top_p^); {reset symbol flags in top scope} level_nest := 0; {depth in nested routines} frame_p := nil; {init to no current stack frame exists} check_opcodes (sst_opc_first_p); {check the entire list of opcodes} if sst_opc_p <> nil then begin {moved opcodes chain is not empty ?} sst_opc_next_pp := addr(sst_opc_first_p); {init pointer to next opcode pointer} while sst_opc_next_pp^ <> nil do begin {loop to find end of opcode chain} sst_opc_next_pp := addr(sst_opc_next_pp^^.next_p); {advance one link in chain} end; sst_opc_next_pp^ := sst_opc_p; {link moved opcodes to end of chain} end; end;
unit mcCodeInsightManager; interface uses SysUtils, ToolsAPI; type TCustomCodeInsightManager = class(TInterfacedObject, IOTACodeInsightManager) public function GetOptionSetName: string; { returns a description of the language which we handle } function GetName: string; { returns a unique IDString to the services module } function GetIDString: string; { returns whether we should be able to be invoked or not } function GetEnabled: Boolean; { sets the active state to Value so this manager may be turned off } procedure SetEnabled(Value: Boolean); { returns a charset used to get the token at the current editor position. This is used for retrieving the seed text when code completion is invoked as well as retrieving the token from the editor when we are typing for look ahead. The PreValidating parameter should be used to add special tokens to the charset for retrieval from the editor. For instance, C++ might add ['.', '-', '>'] to the returned charset when it is prevalidating. } function EditorTokenValidChars(PreValidating: Boolean): TSysCharSet; { the implementor should set Allow to True if it wishes to be invoked for the key 'Key'. 'Key' is the key which the user pressed to invoke code completion. There are four special values to 'Key' when invoked by the code insight timer. They are as follows: #0 : Code completion was requested. #1 : Parameter insight was requested. #2 : A browse was requested. #3 : a symbol hint was requested. } procedure AllowCodeInsight(var Allow: Boolean; const Key: Char); { the implementor should return true if it wishes to allow the token 'str' to be a valid code point for Code Insight. } function PreValidateCodeInsight(const Str: string): Boolean; { returns whether the symbol at index 'Index' as browseable in the Code completion viewer } function IsViewerBrowsable(Index: Integer): Boolean; { returns whether the code completion viewer allows multi-select } function GetMultiSelect: Boolean; { returns the symbol list to the caller } procedure GetSymbolList(out SymbolList: IOTACodeInsightSymbolList); { determines whether or not the key 'Key' which was entered into the editor should close the code completion viewer or not (set CloseViewer to True or False depending on your choice). Also, the implementor should inform the manager whether or not it should accept the symbol at the currently selected index/indices. } procedure OnEditorKey(Key: Char; var CloseViewer: Boolean; var Accept: Boolean); { returns true if this manager should handle this file } function HandlesFile(const AFileName: string): Boolean; { returns the longest symbol class text for measurement for the viewer. i.e. 'constructor' is longer than 'var' } function GetLongestItem: string; { returns a parameter list to the manager } procedure GetParameterList(out ParameterList: IOTACodeInsightParameterList); { given key 'AChar' which was entered into the editor and the current element (atComment, atIdentifier, etc), return how code insight should be invoked and which type of invocation it should be. As an example, GetCodeInsightType() might be implemented something like this: ... begin InvokeType := itManual; if not ((AElement = atString) and (AChar <> #1)) and not (AElement = atComment) then begin case AChar of #0: CodeInsightType := citCodeInsight; #1: CodeInsightType := citParameterCodeInsight; #2: CodeInsightType := citBrowseCodeInsight; #3: CodeInsightType := citHintCodeInsight; '.': begin CodeInsightType := citCodeInsight; InvokeType := itTimer; end; '(': begin CodeInsightType := citParameterCodeInsight; InvokeType := itTimer; end; end; end else CodeInsightType := citNone; end; } procedure GetCodeInsightType(AChar: Char; AElement: Integer; out CodeInsightType: TOTACodeInsightType; out InvokeType: TOTAInvokeType); { returns true if invocation was successful. HowInvoked informs the implementor whether it was invoked via timer, manual, etc... Str is the text to seed to viewer with and is used for the initial filtering in the viewer. } function InvokeCodeCompletion(HowInvoked: TOTAInvokeType; var Str: string): Boolean; { returns true if invocation was successful. HowInvoked informs the implementor whether it was invoked via timer, manual, etc... SelectedIndex is the index of the current parameter for the method/proc. } function InvokeParameterCodeInsight(HowInvoked: TOTAInvokeType; var SelectedIndex: Integer): Boolean; { tells the manager where it should anchor the parameter hint window. A default value (EdPos) is provided for the implementor to change if they so wish. } procedure ParameterCodeInsightAnchorPos(var EdPos: TOTAEditPos); { returns the index of the parameter which should be highlighted based upon EdPos. This is used to reduce extra codeinsight invocations as an implementor might store off the editor positions of parameters on the first invocation. return a -1 if you want to be reinvoked. } function ParameterCodeInsightParamIndex(EdPos: TOTAEditPos): Integer; { return the hint string for the position in the editor (HintLine/HintCol are the editor coordinates) } function GetHintText(HintLine, HintCol: Integer): string; { return a FileName and LineNumber for the symbol which is requested to be browsed to. if Index > -1 then it is an index into the symbol list and the browse was requested by a user clicking in the code completion viewer. return false if you'd like to inform the user that the requested operation failed otherwise return true. if you wish to fail by not informing the user, set AFileName = '' and ALineNum = 0. if Index is -1, you should use the global CodeInsightServices() and request the EditView from it. This should be able to give you any information you require. } function GotoDefinition(out AFileName: string; out ALineNum: Integer; Index: Integer = -1): Boolean; { called when the code completion is completed. Accepted is true if the user has requested the item hinted to them in the viewer otherwise Accepted is false. DisplayParams should be set to true if the implementor would like to be requeried for parameter invocation. It is up to the implementor to insert the text into the editor. One way might be to use CodeInsightServices.InsertText(StrToInsert, ShouldReplace); Another might be to acquire the EditView from CodeInsightServices.GetEditView() and do the insertion yourself. } procedure Done(Accepted: Boolean; out DisplayParams: Boolean); property Name: string read GetName; property MultiSelect: Boolean read GetMultiSelect; property Enabled: Boolean read GetEnabled write SetEnabled; end; implementation uses DbugIntf, Dialogs, mcCodeInsideSymbols, StrUtils; { TCustomCodeInsightManager } procedure TCustomCodeInsightManager.AllowCodeInsight(var Allow: Boolean; const Key: Char); begin Allow := True; end; procedure TCustomCodeInsightManager.Done(Accepted: Boolean; out DisplayParams: Boolean); begin if not Accepted then Exit; DisplayParams := False; (BorlandIDEServices as IOTACodeInsightServices).InsertText('%message%', True); DbugIntf.SendDebugEx(Format('INTERCEPT: Done', []), mtInformation ); end; function TCustomCodeInsightManager.EditorTokenValidChars( PreValidating: Boolean): TSysCharSet; begin Result := ['%','m','e','s','a','g']; end; procedure TCustomCodeInsightManager.GetCodeInsightType(AChar: Char; AElement: Integer; out CodeInsightType: TOTACodeInsightType; out InvokeType: TOTAInvokeType); begin InvokeType := itManual; if not ((AElement = atString) and (AChar <> #1)) and not (AElement = atComment) then begin case AChar of #0: CodeInsightType := citCodeInsight; #1: CodeInsightType := citParameterCodeInsight; #2: CodeInsightType := citBrowseCodeInsight; #3: CodeInsightType := citHintCodeInsight; '.': begin CodeInsightType := citCodeInsight; InvokeType := itTimer; end; '(': begin CodeInsightType := citParameterCodeInsight; InvokeType := itTimer; end; end; end else CodeInsightType := citNone; end; function TCustomCodeInsightManager.GetEnabled: Boolean; begin Result := True; end; function TCustomCodeInsightManager.GetHintText(HintLine, HintCol: Integer): string; begin Result := 'Custom Hint text'; end; function TCustomCodeInsightManager.GetIDString: string; begin Result := 'My Custom Code Insight'; end; function TCustomCodeInsightManager.GetLongestItem: string; begin Result := 'abcdefghijklmnopqrstuvw'; end; function TCustomCodeInsightManager.GetMultiSelect: Boolean; begin Result := False; end; function TCustomCodeInsightManager.GetName: string; begin Result := 'Delphi'; end; function TCustomCodeInsightManager.GetOptionSetName: string; begin Result := 'My Custom Options'; end; procedure TCustomCodeInsightManager.GetParameterList( out ParameterList: IOTACodeInsightParameterList); begin ParameterList := nil; DbugIntf.SendDebugEx(Format('INTERCEPT: GetParameterList', []), mtInformation ); end; procedure TCustomCodeInsightManager.GetSymbolList( out SymbolList: IOTACodeInsightSymbolList); var symbols: TCodeInsightSymbolList; begin symbols := TCodeInsightSymbolList.Create; SymbolList := symbols; symbols.AddSymbol('message'); DbugIntf.SendDebugEx(Format('INTERCEPT: GetSymbolList', []), mtInformation ); end; function TCustomCodeInsightManager.GotoDefinition(out AFileName: string; out ALineNum: Integer; Index: Integer): Boolean; begin Result := False; //not supported DbugIntf.SendDebugEx(Format('INTERCEPT: GotoDefinition', []), mtInformation ); end; function TCustomCodeInsightManager.HandlesFile( const AFileName: string): Boolean; begin //Result := ExtractFileName(AFileName) = 'Unit7.pas'; Result := StartsText('my', ExtractFileName(AFileName)); end; function TCustomCodeInsightManager.InvokeCodeCompletion( HowInvoked: TOTAInvokeType; var Str: string): Boolean; begin Result := True; DbugIntf.SendDebugEx(Format('INTERCEPT: InvokeCodeCompletion(%s)', [str]), mtInformation ); end; function TCustomCodeInsightManager.InvokeParameterCodeInsight( HowInvoked: TOTAInvokeType; var SelectedIndex: Integer): Boolean; begin Result := False; DbugIntf.SendDebugEx(Format('INTERCEPT: InvokeParameterCodeInsight', []), mtInformation ); end; function TCustomCodeInsightManager.IsViewerBrowsable(Index: Integer): Boolean; begin Result := False; DbugIntf.SendDebugEx(Format('INTERCEPT: IsViewerBrowsable', []), mtInformation ); end; procedure TCustomCodeInsightManager.OnEditorKey(Key: Char; var CloseViewer, Accept: Boolean); begin CloseViewer := False; Accept := True; DbugIntf.SendDebugEx(Format('INTERCEPT: OnEditorKey(%s)', [Key]), mtInformation ); end; procedure TCustomCodeInsightManager.ParameterCodeInsightAnchorPos( var EdPos: TOTAEditPos); begin DbugIntf.SendDebugEx(Format('INTERCEPT: ParameterCodeInsightAnchorPos', []), mtInformation ); end; function TCustomCodeInsightManager.ParameterCodeInsightParamIndex( EdPos: TOTAEditPos): Integer; begin Result := 0; DbugIntf.SendDebugEx(Format('INTERCEPT: ParameterCodeInsightParamIndex', []), mtInformation ); end; function TCustomCodeInsightManager.PreValidateCodeInsight( const Str: string): Boolean; begin Result := True; DbugIntf.SendDebugEx(Format('INTERCEPT: PreValidateCodeInsight(%s)', [str]), mtInformation ); end; procedure TCustomCodeInsightManager.SetEnabled(Value: Boolean); begin DbugIntf.SendDebugEx(Format('INTERCEPT: SetEnabled(%s)', [BoolToStr(Value, True)]), mtInformation ); end; var idx: Integer; initialization (BorlandIDEServices as IOTACodeInsightServices).AddCodeInsightManager( TCustomCodeInsightManager.Create ); finalization (BorlandIDEServices as IOTACodeInsightServices).RemoveCodeInsightManager(idx); end.
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, System.Bluetooth, System.Beacon, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts, System.Beacon.Components, System.Bluetooth.Components, FMX.TabControl, FMX.ScrollBox, FMX.Memo; type TForm1 = class(TForm) TabControl1: TTabControl; TabItem1: TTabItem; TabItem2: TTabItem; TabItem3: TTabItem; Bluetooth1: TBluetooth; BluetoothLE1: TBluetoothLE; Beacon1: TBeacon; GridPanelLayout2: TGridPanelLayout; Button1: TButton; GridPanelLayout1: TGridPanelLayout; Button3: TButton; Button4: TButton; GridPanelLayout3: TGridPanelLayout; Button5: TButton; Button6: TButton; Memo1: TMemo; Memo2: TMemo; Memo3: TMemo; procedure Button1Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure Button5Click(Sender: TObject); procedure Button6Click(Sender: TObject); procedure Beacon1ParseServiceData(const Sender: TObject; const AData: TServiceDataRawData; var BeaconInfo: TBeaconInfo; var Handled: Boolean); procedure Beacon1BeaconEnter(const Sender: TObject; const ABeacon: IBeacon; const CurrentBeaconList: TBeaconList); procedure BluetoothLE1Connect(Sender: TObject); procedure BluetoothLE1CharacteristicRead(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic; AGattStatus: TBluetoothGattStatus); procedure BluetoothLE1CharacteristicReadRequest(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic; var AGattStatus: TBluetoothGattStatus); procedure BluetoothLE1CharacteristicSubscribed(const Sender: TObject; const AClientId: string; const ACharacteristic: TBluetoothGattCharacteristic); procedure BluetoothLE1CharacteristicUnSubscribed(const Sender: TObject; const AClientId: string; const ACharacteristic: TBluetoothGattCharacteristic); procedure BluetoothLE1CharacteristicWrite(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic; AGattStatus: TBluetoothGattStatus); procedure BluetoothLE1CharacteristicWriteRequest(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic; var AGattStatus: TBluetoothGattStatus; const AValue: TByteDynArray); procedure BluetoothLE1ConnectedDevice(const Sender: TObject; const ADevice: TBluetoothLEDevice); procedure BluetoothLE1DescriptorRead(const Sender: TObject; const ADescriptor: TBluetoothGattDescriptor; AGattStatus: TBluetoothGattStatus); procedure BluetoothLE1DescriptorWrite(const Sender: TObject; const ADescriptor: TBluetoothGattDescriptor; AGattStatus: TBluetoothGattStatus); procedure BluetoothLE1Disconnect(Sender: TObject); procedure BluetoothLE1DisconnectDevice(const Sender: TObject; const ADevice: TBluetoothLEDevice); procedure BluetoothLE1DiscoverLEDevice(const Sender: TObject; const ADevice: TBluetoothLEDevice; Rssi: Integer; const ScanResponse: TScanResponse); procedure BluetoothLE1EndDiscoverDevices(const Sender: TObject; const ADeviceList: TBluetoothLEDeviceList); procedure BluetoothLE1EndDiscoverServices(const Sender: TObject; const AServiceList: TBluetoothGattServiceList); procedure BluetoothLE1ReadRSSI(const Sender: TObject; ARssiValue: Integer; AGattStatus: TBluetoothGattStatus); procedure BluetoothLE1ReliableWriteCompleted(const Sender: TObject; AGattStatus: TBluetoothGattStatus); procedure BluetoothLE1ServiceAdded(const Sender: TObject; const AService: TBluetoothGattService; const AGattStatus: TBluetoothGattStatus); procedure BluetoothLE1ServicesDiscovered(const Sender: TObject; const AServiceList: TBluetoothGattServiceList); procedure Beacon1BeaconError(const Sender: TObject; AError: TBeaconError; const ErrorMsg: string; const ABeacon: TBeaconInfo); procedure Beacon1BeaconExit(const Sender: TObject; const ABeacon: IBeacon; const CurrentBeaconList: TBeaconList); procedure Beacon1BeaconProximity(const Sender: TObject; const ABeacon: IBeacon; Proximity: TBeaconProximity); private { Déclarations privées } public { Déclarations publiques } end; var Form1: TForm1; implementation {$R *.fmx} procedure TForm1.Beacon1BeaconEnter(const Sender: TObject; const ABeacon: IBeacon; const CurrentBeaconList: TBeaconList); var i: Integer; ch: string; begin Memo2.Lines.add(ABeacon.DeviceIdentifier + ' est proche'); ch := ''; for i := 0 to length(ABeacon.AdditionalData) - 1 do begin ch := ch + ABeacon.AdditionalData[i].ToHexString + ' '; end; if ch.length > 0 then Memo2.Lines.add('=> ' + ch); end; procedure TForm1.Beacon1BeaconError(const Sender: TObject; AError: TBeaconError; const ErrorMsg: string; const ABeacon: TBeaconInfo); begin memo2.Lines.Add('Beacon '+ABeacon.DeviceIdentifier); Memo2.Lines.Add('=> '+ErrorMsg); end; procedure TForm1.Beacon1BeaconExit(const Sender: TObject; const ABeacon: IBeacon; const CurrentBeaconList: TBeaconList); begin Memo2.Lines.Add('Bye bye '+ABeacon.DeviceIdentifier); end; procedure TForm1.Beacon1BeaconProximity(const Sender: TObject; const ABeacon: IBeacon; Proximity: TBeaconProximity); begin Memo2.Lines.add('Proximity '+abeacon.DeviceIdentifier+' : '+ord(proximity).ToString); end; procedure TForm1.Beacon1ParseServiceData(const Sender: TObject; const AData: TServiceDataRawData; var BeaconInfo: TBeaconInfo; var Handled: Boolean); var i: Integer; ch: string; begin Memo2.Lines.add('ServiceData ' + AData.Key.ToString + ' pour ' + BeaconInfo.DeviceIdentifier); ch := ''; for i := 0 to length(AData.Value) - 1 do begin ch := ch + AData.Value[i].ToHexString + ' '; end; if ch.length > 0 then Memo2.Lines.add('=> ' + ch); end; procedure TForm1.BluetoothLE1CharacteristicRead(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic; AGattStatus: TBluetoothGattStatus); begin Memo3.Lines.add('CharacteristicRead'); end; procedure TForm1.BluetoothLE1CharacteristicReadRequest(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic; var AGattStatus: TBluetoothGattStatus); begin Memo3.Lines.add('CharacteristicReadReuest'); end; procedure TForm1.BluetoothLE1CharacteristicSubscribed(const Sender: TObject; const AClientId: string; const ACharacteristic: TBluetoothGattCharacteristic); begin Memo3.Lines.add('BluetoothLE1CharacteristicSubscribed'); end; procedure TForm1.BluetoothLE1CharacteristicUnSubscribed(const Sender: TObject; const AClientId: string; const ACharacteristic: TBluetoothGattCharacteristic); begin Memo3.Lines.add('BluetoothLE1CharacteristicUnSubscribed'); end; procedure TForm1.BluetoothLE1CharacteristicWrite(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic; AGattStatus: TBluetoothGattStatus); begin Memo3.Lines.add('BluetoothLE1CharacteristicWrite'); end; procedure TForm1.BluetoothLE1CharacteristicWriteRequest(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic; var AGattStatus: TBluetoothGattStatus; const AValue: TByteDynArray); begin Memo3.Lines.add('BluetoothLE1CharacteristicWriteRequest'); end; procedure TForm1.BluetoothLE1Connect(Sender: TObject); begin Memo3.Lines.add('onConnect'); end; procedure TForm1.BluetoothLE1ConnectedDevice(const Sender: TObject; const ADevice: TBluetoothLEDevice); begin Memo3.Lines.add('BluetoothLE1ConnectedDevice'); end; procedure TForm1.BluetoothLE1DescriptorRead(const Sender: TObject; const ADescriptor: TBluetoothGattDescriptor; AGattStatus: TBluetoothGattStatus); begin Memo3.Lines.add('BluetoothLE1DescriptorRead'); end; procedure TForm1.BluetoothLE1DescriptorWrite(const Sender: TObject; const ADescriptor: TBluetoothGattDescriptor; AGattStatus: TBluetoothGattStatus); begin Memo3.Lines.add('BluetoothLE1DescriptorWrite'); end; procedure TForm1.BluetoothLE1Disconnect(Sender: TObject); begin Memo3.Lines.add('BluetoothLE1Disconnect'); end; procedure TForm1.BluetoothLE1DisconnectDevice(const Sender: TObject; const ADevice: TBluetoothLEDevice); begin Memo3.Lines.add('BluetoothLE1DisconnectDevice'); end; procedure TForm1.BluetoothLE1DiscoverLEDevice(const Sender: TObject; const ADevice: TBluetoothLEDevice; Rssi: Integer; const ScanResponse: TScanResponse); begin Memo3.Lines.add('BluetoothLE1DiscoverLEDevice'); end; procedure TForm1.BluetoothLE1EndDiscoverDevices(const Sender: TObject; const ADeviceList: TBluetoothLEDeviceList); begin Memo3.Lines.add('BluetoothLE1EndDiscoverDevices'); end; procedure TForm1.BluetoothLE1EndDiscoverServices(const Sender: TObject; const AServiceList: TBluetoothGattServiceList); begin Memo3.Lines.add('BluetoothLE1EndDiscoverServices'); end; procedure TForm1.BluetoothLE1ReadRSSI(const Sender: TObject; ARssiValue: Integer; AGattStatus: TBluetoothGattStatus); begin Memo3.Lines.add('BluetoothLE1ReadRSSI'); end; procedure TForm1.BluetoothLE1ReliableWriteCompleted(const Sender: TObject; AGattStatus: TBluetoothGattStatus); begin Memo3.Lines.add('BluetoothLE1ReliableWriteCompleted'); end; procedure TForm1.BluetoothLE1ServiceAdded(const Sender: TObject; const AService: TBluetoothGattService; const AGattStatus: TBluetoothGattStatus); begin Memo3.Lines.add('BluetoothLE1ServiceAdded'); end; procedure TForm1.BluetoothLE1ServicesDiscovered(const Sender: TObject; const AServiceList: TBluetoothGattServiceList); begin Memo3.Lines.add('BluetoothLE1ServicesDiscovered'); end; procedure TForm1.Button1Click(Sender: TObject); var i, j: Integer; begin Bluetooth1.Enabled := true; Memo1.Lines.Clear; for i := 0 to Bluetooth1.PairedDevices.Count - 1 do begin Memo1.Lines.add('Device : ' + Bluetooth1.PairedDevices[i].DeviceName + ' / ' + Bluetooth1.PairedDevices[i].Address); for j := 0 to Bluetooth1.PairedDevices[i].LastServiceList.Count - 1 do begin Memo1.Lines.add(' => ' + Bluetooth1.PairedDevices[i] .LastServiceList[j].Name); end; end; Memo1.Lines.add('Recherche terminée.'); Bluetooth1.Enabled:=false; end; procedure TForm1.Button3Click(Sender: TObject); var i: Integer; begin BluetoothLE1.Enabled := true; BluetoothLE1.DiscoverDevices(2500); Memo1.Lines.add('Recherche terminée.'); end; procedure TForm1.Button4Click(Sender: TObject); begin BluetoothLE1.Enabled := false; end; procedure TForm1.Button5Click(Sender: TObject); begin Beacon1.Enabled := true; end; procedure TForm1.Button6Click(Sender: TObject); begin Beacon1.Enabled := false; end; end.
unit ULog; interface uses Classes; type PTextFile = ^TextFile; TLog = class(TObject) constructor Create(Path: String); destructor Destroy;override; procedure Append(msg:String); function Read(fromPos, Count:Integer):String; private Files:TStringList; baseDir:String; pTF:PTextFile; origin:Integer; size:Integer; end; const LogRecMaxSize = 256; implementation uses FileCtrl, SysUtils; const nRecsInOneFile = 65536; maskFileRecs = nRecsInOneFile - 1; function GetTextFile(fileName:string):PTextFile; begin GetMem(Result,SizeOf(Result^)); AssignFile(Result^,fileName); Append(Result^); end; procedure FreeAndNilTF(var f:PTextFile); begin if f=nil then exit; CloseFile(f^); FreeMem(f,SizeOf(f^)); f:=nil; end; function IntToHex8Str(x:Integer):String; const hexChars:String = '0123456789ABCDEF'; var i:Integer; begin SetLength(Result,8); for i:=0 to 7 do begin Result[8-i]:=hexChars[(x and $F) + 1]; x:=x shr 4; end; end; function IntFromHexStr(s:String):Integer; var i:Integer; digit:Integer; begin Result:=0; for i:=1 to Length(s) do begin Result:=Result*16; digit:=-1; if s[i]<'9' then digit:=s[i]-'0'; else digit:=s[i]-'F'+10; if (0<=digit) and (digit<15) then Inc(Result,digit); end; end; function IntToBinStr(x:Integer):String; begin SetLength(Result,sizeof(x)); Move(x,s[1],sizeof(x)); end; function IntFromBinStr(s:String):Integer; begin Move(s[1],Result,sizeof(Result)); end; { TLog } procedure TLog.Append(msg: String); var L:Integer; begin if (pTF=nil) or (size>=65536) then begin if pTF<>nil then FreeAndNilTF(pTF); Inc(origin,size); size:=0; pTF:=GetTextFile(baseDir+'\'+IntToHex8Str(origin)); Files.AddObject(IntToBinStr(origin),TObject(-1)); end; L:=Length(msg); if L<>LogRecMaxSize then SetLength(msg, 0, LogRecMaxSize); if L<LogRecMaxSize then FillChar(msg[L+1],LogRecMaxSize-L,0); msg[LogRecMaxSize-1]:=#13; msg[LogRecMaxSize-0]:=#10; Write(pTF^,msg); Flush(pTF^); Inc(size); end; constructor TLog.Create(Path: String); var pos:Integer; sr:TSearchRec; r:Integer; currLogFile:TFileName; begin Files:=TStringList.Create; Files.Sorted:=true; ForceDirectories(Path); baseDir:=Path; origin:=0; size:=0; currLogFile:=''; r:=FindFirst(Path,faAnyFile,var sr); try while r=0 do begin try pos:=IntFromHexStr(sr.Name); if pos>origin then begin currLogFile:=sr.Name; origin:=pos; size:=sr.Size div LogRecMaxSize; end; Files.AddObject(IntToBinStr(pos),TObject(sr.Size)); except end; r:=FindNext(sr); end; finally FindClose(sr); end; if currLogFile<>'' then f:=GetTextFile(baseDir+'\'+currLogFile); else lastSize:=0; end; destructor TLog.Destroy; begin FreeAndNil(Files); FreeAndNilTF(pTF); inherited; end; function TLog.Read(fromPos, Count: Integer): String; var i, j, n, orig, cnt, savedPos:Integer; lst:TStringList; f:File; buf:array of byte; s:string; begin savedPos:= if Files.Count>0 then begin i:=IntFromBinStr(Files[0]); if fromPos<i then fromPos:=i; end; if fromPos+Count > origin+size then Count:=origin+size-fromPos; lst:=TStringList.Create; lastPos:=fromPos+Count; SetLength(buf,LogRecMaxSize); while fromPos<lastPos do begin orig:=fromPos and not maskFileRecs; if orig=origin then i:=size else i:=nRecsInOneFile; cnt:=orig + i - fromPos; AssignFile(f,baseDir+'\'+IntToHex8Str(orig)); Reset(f); if fromPos>orig then Seek(f,(fromPos-orig)*LogRecMaxSize); for i:=0 to cnt-1 do begin BlockRead(f,buf[0],Length(buf)); j:=0; n:=Length(buf)-2; while (j<n) and (buf[j]=0) do Inc(j); if j>0 then begin SetLength(s,j); Move(buf[0],s[1],j); end else s:=''; lst.Add(s); end; CloseFile(f); Inc(fromPos,cnt); end; end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpISO7816d4Padding; {$I ..\..\Include\CryptoLib.inc} interface uses ClpIBlockCipherPadding, ClpIISO7816d4Padding, ClpISecureRandom, ClpCryptoLibTypes; resourcestring SCorruptedPadBlock = 'Pad Block Corrupted'; type /// <summary> /// A padder that adds the padding according to the scheme referenced in /// ISO 7814-4 - scheme 2 from ISO 9797-1. The first byte is $80, rest is $00 /// </summary> TISO7816d4Padding = class sealed(TInterfacedObject, IISO7816d4Padding, IBlockCipherPadding) strict private /// <returns> /// return the name of the algorithm the cipher implements. /// </returns> function GetPaddingName: String; inline; public /// <summary> /// Initialise the padder. /// </summary> /// <param name="random"> /// a SecureRandom if available. /// </param> procedure Init(const random: ISecureRandom); /// <summary> /// Return the name of the algorithm the cipher implements. /// </summary> property PaddingName: String read GetPaddingName; /// <summary> /// add the pad bytes to the passed in block, returning the number of /// bytes added. /// </summary> /// <param name="input"> /// input block to pad /// </param> /// <param name="inOff"> /// offset to start the padding from in the block /// </param> /// <returns> /// returns number of bytes added /// </returns> function AddPadding(const input: TCryptoLibByteArray; inOff: Int32): Int32; /// <summary> /// return the number of pad bytes present in the block. /// </summary> /// <param name="input"> /// block to count pad bytes in /// </param> /// <returns> /// the number of pad bytes present in the block. /// </returns> /// <exception cref="EInvalidCipherTextCryptoLibException"> /// if the padding is badly formed or invalid. /// </exception> function PadCount(const input: TCryptoLibByteArray): Int32; end; implementation { TISO7816d4Padding } function TISO7816d4Padding.AddPadding(const input: TCryptoLibByteArray; inOff: Int32): Int32; var added: Int32; begin added := (System.Length(input) - inOff); input[inOff] := Byte($80); System.Inc(inOff); while (inOff < System.Length(input)) do begin input[inOff] := Byte(0); System.Inc(inOff); end; result := added; end; function TISO7816d4Padding.GetPaddingName: String; begin result := 'ISO7816-4'; end; {$IFNDEF _FIXINSIGHT_} procedure TISO7816d4Padding.Init(const random: ISecureRandom); begin // nothing to do. end; {$ENDIF} function TISO7816d4Padding.PadCount(const input: TCryptoLibByteArray): Int32; var count: Int32; begin count := System.Length(input) - 1; while ((count > 0) and (input[count] = 0)) do begin System.Dec(count); end; if (input[count] <> Byte($80)) then begin raise EInvalidCipherTextCryptoLibException.CreateRes(@SCorruptedPadBlock); end; result := System.Length(input) - count; end; end.
unit sygwHelperForm; interface uses Windows, Messages, SysUtils, Classes, Controls, Forms, StdCtrls, ExtCtrls, BaseForm, zsHelperMessage; type TfrmZSHelper = class(TfrmBase) btnbuy: TButton; mmo1: TMemo; pb1: TPaintBox; edtLeft: TEdit; edtTop: TEdit; btnMain: TButton; btnlaunch: TButton; edStock: TEdit; edPrice: TEdit; btnConfirmDeal: TButton; edMoney: TEdit; btnConfirmPwd: TButton; btnUnlock: TButton; btnCheckMoney: TButton; edNum: TEdit; btnSale: TButton; btnCheckDealPanelSize: TButton; procedure btnMainClick(Sender: TObject); procedure btnlaunchClick(Sender: TObject); procedure btnbuyClick(Sender: TObject); procedure btnConfirmDealClick(Sender: TObject); procedure btnConfirmPwdClick(Sender: TObject); procedure btnUnlockClick(Sender: TObject); procedure btnCheckMoneyClick(Sender: TObject); procedure btnSaleClick(Sender: TObject); procedure btnCheckDealPanelSizeClick(Sender: TObject); protected function GetBuyPriceStep1(APrice: double): double; function GetBuyPriceStep2(APrice: double): double; procedure SaveBuyConfig; procedure LoadBuyConfig; procedure CreateParams(var Params: TCreateParams); override; procedure WMStockBuy(var Message: TMessage); message WM_StockBuy; procedure WMStockBuy_XueQiu(var Message: TMessage); message WM_StockBuy_XueQiu; procedure WMStockSale_XueQiu(var Message: TMessage); message WM_StockSale_XueQiu; public constructor Create(Owner: TComponent); override; end; implementation {$R *.dfm} uses UtilsWindows, CommCtrl, sygwLoginUtils, IniFiles, UtilsApplication, sygwVariants, sygwMainWindow, sygwLoginWindow; constructor TfrmZSHelper.Create(Owner: TComponent); begin inherited; LoadBuyConfig; end; procedure TfrmZSHelper.CreateParams(var Params: TCreateParams); begin inherited; Params.WinClassName := 'WndZSHelper'; Params.Caption := ''; Self.Caption := ''; end; procedure TfrmZSHelper.btnMainClick(Sender: TObject); begin if FindZSMainWindow(@GZsDealSession) then begin CheckZSMainWindow(@GZsDealSession.MainWindow); if nil <> GZsDealSession.MainWindow.HostWindowPtr then begin mmo1.Lines.Add('main wnd:' + IntToHex(GZsDealSession.MainWindow.HostWindowPtr.WindowHandle, 2)); end; mmo1.Lines.Add('tree wnd:' + IntToHex(GZsDealSession.MainWindow.WndFunctionTree, 2)); ClickMenuOrderMenuItem(@GZsDealSession.MainWindow); end; end; procedure TfrmZSHelper.WMStockBuy(var Message: TMessage); var tmpStock: AnsiString; begin tmpStock := IntToStr(Message.WParam); if 7 = Length(tmpStock) then tmpStock := Copy(tmpStock, 2, maxint); if BuyStock(@GZsDealSession, tmpStock, Message.LParam / 1000, 10000) then begin // 出错 可能未 开通创业板权限 ConfirmDeal(@GZsDealSession); end; end; function TfrmZSHelper.GetBuyPriceStep1(APrice: double): double; begin Result := 0; if APrice < 10 then begin Result := APrice * 0.995; exit; end; if APrice < 20 then begin Result := APrice * 0.993; // 0.002 exit; end; if APrice < 30 then begin Result := APrice * 0.990; // 0.003 exit; end; if APrice < 40 then begin Result := APrice * 0.986; // 0.004 exit; end; if APrice < 50 then begin Result := APrice * 0.981; // 0.005 exit; end; end; function TfrmZSHelper.GetBuyPriceStep2(APrice: double): double; begin Result := 0; if APrice < 10 then begin Result := APrice * 0.985; Exit; end; if APrice < 20 then begin Result := APrice * 0.982; // 0.003 exit; end; if APrice < 30 then begin Result := APrice * 0.979; // 0.003 exit; end; if APrice < 40 then begin Result := APrice * 0.975; // 0.004 exit; end; if APrice < 50 then begin Result := APrice * 0.970; // 0.005 exit; end; if APrice < 60 then begin Result := APrice * 0.960; // 0.01 exit; end; end; procedure TfrmZSHelper.WMStockBuy_XueQiu(var Message: TMessage); var tmpNewPrice: double; tmpPrice: double; begin if 0 <> Message.WParam then begin tmpPrice := Message.LParam / 1000; tmpNewPrice := GetBuyPriceStep1(tmpPrice); if 0 < tmpNewPrice then PostMessage(Handle, WM_StockBuy, Message.WParam, Trunc(tmpNewPrice * 1000)); tmpNewPrice := GetBuyPriceStep2(tmpPrice); if 0 < tmpNewPrice then PostMessage(Handle, WM_StockBuy, Message.WParam, Trunc(tmpNewPrice * 1000)); end; end; procedure TfrmZSHelper.WMStockSale_XueQiu(var Message: TMessage); begin if 0 <> Message.WParam then begin end; end; procedure TfrmZSHelper.LoadBuyConfig; var tmpIni: TIniFile; begin tmpIni := TIniFile.Create(ChangeFileExt(ParamStr(0), '.ini')); try edStock.Text := tmpIni.ReadString('Test', 'Stock', ''); edPrice.Text := tmpIni.ReadString('Test', 'Price', '0.00'); edMoney.Text := tmpIni.ReadString('Test', 'Money', '5000'); finally tmpIni.Free; end; end; procedure TfrmZSHelper.SaveBuyConfig; var tmpIni: TIniFile; begin tmpIni := TIniFile.Create(ChangeFileExt(ParamStr(0), '.ini')); try tmpIni.WriteString('Test', 'Stock', Trim(edStock.Text)); tmpIni.WriteString('Test', 'Price', FormatFloat('0.00', StrToFloatDef(Trim(edPrice.Text), 0))); tmpIni.WriteString('Test', 'Money', IntToStr(StrToIntDef(Trim(edMoney.Text), 5000))); finally tmpIni.Free; end; end; procedure TfrmZSHelper.btnbuyClick(Sender: TObject); var tmpStock: AnsiString; tmpPrice: double; begin tmpStock := Trim(edStock.Text); tmpPrice := StrToFloatDef(Trim(edPrice.Text), 0); SaveBuyConfig(); if BuyStock(@GZsDealSession, tmpStock, tmpPrice, StrToIntDef(edMoney.Text, 5000)) then begin // 出错 可能未 开通创业板权限 ConfirmDeal(@GZsDealSession); end; end; procedure TfrmZSHelper.btnSaleClick(Sender: TObject); var tmpStock: AnsiString; tmpPrice: double; tmpNum: integer; begin tmpStock := Trim(edStock.Text); tmpPrice := StrToFloatDef(Trim(edPrice.Text), 0); tmpNum := StrToIntDef(edNum.Text, 100); if SaleStock(@GZsDealSession, tmpStock, tmpPrice, tmpNum) then begin // 出错 非交易时间内 下单 ConfirmDeal(@GZsDealSession); end; end; procedure TfrmZSHelper.btnCheckDealPanelSizeClick(Sender: TObject); begin inherited; if nil = GZsDealSession.MainWindow.HostWindowPtr then begin if not FindZSMainWindow(@GZsDealSession) then exit; end; CheckZSMainWindow(@GZsDealSession.MainWindow); CheckDealPanelSize(@GZsDealSession.MainWindow); end; procedure TfrmZSHelper.btnCheckMoneyClick(Sender: TObject); begin if nil = GZsDealSession.MainWindow.HostWindowPtr then begin if not FindZSMainWindow(@GZsDealSession) then exit; end; CheckZSMoneyWindow(@GZsDealSession.MainWindow); end; procedure TfrmZSHelper.btnConfirmDealClick(Sender: TObject); var tmpWnd: HWND; begin FindZSDealConfirmDialogWindow(@GZsDealSession); if nil <> GZsDealSession.DealConfirmDialog then begin CheckZSDialogWindow(GZsDealSession.DealConfirmDialog); if IsWindow(GZsDealSession.DealConfirmDialog.OKButton) then begin tmpWnd := GZsDealSession.DealConfirmDialog.WindowHandle; if IsWindow(tmpWnd) then begin ForceBringFrontWindow(tmpWnd); SleepWait(20); ForceBringFrontWindow(tmpWnd); SleepWait(20); end; ClickButtonWnd(GZsDealSession.DealConfirmDialog.OKButton); end; end; // end; procedure TfrmZSHelper.btnUnlockClick(Sender: TObject); begin { 各种可能出现的 对话框 } if nil = GZsDealSession.MainWindow.HostWindowPtr then begin if not FindZSMainWindow(@GZsDealSession) then exit; end; FindZSLockPanelWindow(@GZsDealSession); end; procedure TfrmZSHelper.btnConfirmPwdClick(Sender: TObject); var tmpWnd: HWND; tmpIsChecked: Integer; begin { 各种可能出现的 对话框 } if nil = GZsDealSession.MainWindow.HostWindowPtr then begin if not FindZSMainWindow(@GZsDealSession) then exit; end; FindZSPasswordConfirmDialogWindow(@GZsDealSession); if nil <> GZsDealSession.DealPasswordConfirmDialogWindow.HostWindowPtr then begin CheckZSPasswordConfirmDialogWindow(@GZsDealSession.DealPasswordConfirmDialogWindow); tmpWnd := GZsDealSession.DealPasswordConfirmDialogWindow.WndNoInputNextCheck; if IsWindow(tmpWnd) then begin tmpIsChecked := SendMessage(tmpWnd, BM_GETCHECK, 0, 0); if 0 = tmpIsChecked then begin ClickButtonWnd(tmpWnd); end; end; tmpWnd := GZsDealSession.DealPasswordConfirmDialogWindow.WndPasswordEdit; if IsWindow(tmpWnd) then begin InputEditWnd(tmpWnd, '111111'); end; tmpWnd := GZsDealSession.DealPasswordConfirmDialogWindow.HostWindowPtr.OKButton; if IsWindow(tmpWnd) then begin ClickButtonWnd(tmpWnd); end; end; // end; procedure TfrmZSHelper.btnlaunchClick(Sender: TObject); begin AutoLogin(@GZsDealSession); end; end.
{ Double commander ------------------------------------------------------------------------- Executes file operations with administrator privileges Copyright (C) 2016 Alexander Koblov (alexx2000@mail.ru) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA } unit uAdministrator; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Dialogs, uFileSystemFileSource, uFile, uFileSystemDeleteOperation; type EAccessDenied = class(Exception); procedure ExecuteOperation(const FileList: String); procedure Delete(Helper: TFileSystemDeleteOperation; Files: TFiles; Index: Integer); implementation uses uFileSource, uFileSourceOperationMessageBoxesUI, dmCommonData, uOSUtils, uGlobs, uGlobsPaths, uOperationsManager, uFileSourceOperation, DCXmlConfig, uFileSourceOperationOptions, uSpecialDir, uVariableMenuSupport, DCOSUtils, uDCUtils; type { TDummy } TDummy = class procedure Finish(Operation: TFileSourceOperation; State: TFileSourceOperationState); end; var Dummy: TDummy; FFileSourceOperationMessageBoxesUI: TFileSourceOperationMessageBoxesUI; procedure Initialize; begin LoadPaths; LoadWindowsSpecialDir; LoadVariableMenuSupport; InitGlobs; Dummy:= TDummy.Create; Application.CreateForm(TdmComData, dmComData); // common data FFileSourceOperationMessageBoxesUI := TFileSourceOperationMessageBoxesUI.Create; end; procedure Delete(Xml: TXmlConfig); var Files: TFiles; ANode: TXmlNode; FileSource: IFileSource; Operation: TFileSystemDeleteOperation; begin ANode:= Xml.FindNode(Xml.RootNode, 'FileList'); if Assigned(ANode) then begin Files:= TFiles.Create(Xml.GetAttr(aNode, 'Path', EmptyStr)); ANode:= ANode.FirstChild; while Assigned(ANode) do begin if ANode.CompareName('Item') = 0 then begin Files.Add(TFileSystemFileSource.CreateFileFromFile(Xml.GetAttr(aNode, 'Name', EmptyStr))); end; ANode:= ANode.NextSibling; end; FileSource:= TFileSystemFileSource.GetFileSource; Operation:= FileSource.CreateDeleteOperation(Files) as TFileSystemDeleteOperation; Operation.SkipErrors:= False; Operation.Recycle:= Xml.GetValue(Xml.RootNode, 'Recycle', False); Operation.SymLinkOption:= TFileSourceOperationOptionSymLink(Xml.GetValue(Xml.RootNode, 'SymLinkOption', Integer(fsooslNone))); Operation.DeleteReadOnly:= TFileSourceOperationOptionGeneral(Xml.GetValue(Xml.RootNode, 'DeleteReadOnly', Integer(fsoogNone))); Operation.AddUserInterface(FFileSourceOperationMessageBoxesUI); Operation.AddStateChangedListener([fsosStopped], @Dummy.Finish); OperationsManager.AddOperation(Operation, True); end; end; procedure Delete(Helper: TFileSystemDeleteOperation; Files: TFiles; Index: Integer); var I: Integer; Xml: TXmlConfig; ANode: TXmlNode; SubNode: TXmlNode; FileName: String; begin FileName:= GetTempFileName; Xml:= TXmlConfig.Create(FileName); Xml.SetValue(Xml.RootNode, 'Operation', 0); Xml.SetValue(Xml.RootNode, 'Recycle', Helper.Recycle); Xml.SetValue(Xml.RootNode, 'DeleteReadOnly', Integer(Helper.DeleteReadOnly)); Xml.SetValue(Xml.RootNode, 'SymLinkOption', Integer(Helper.SymLinkOption)); ANode := Xml.AddNode(Xml.RootNode, 'FileList'); Xml.SetAttr(ANode, 'Path', Files.Path); for I:= Index to Files.Count - 1 do begin SubNode := Xml.AddNode(ANode, 'Item'); Xml.SetAttr(SubNode, 'Name', Files[I].FullPath); end; Xml.Save; Xml.Free; ExecCmdAdmin(ParamStrU(0), '--config-dir=' + QuoteStr(gpCfgDir) + ' ' + '--operation=' + QuoteStr(FileName)); end; procedure ExecuteOperation(const FileList: String); var Xml: TXmlConfig; begin try Initialize; Xml:= TXmlConfig.Create(FileList, True); try case Xml.GetValue(Xml.RootNode, 'Operation', -1) of 0: Delete(Xml); end; finally Xml.Free; mbDeleteFile(FileList); end; Application.Run; Halt(0); except on E: Exception do begin ShowMessage(E.Message); Halt(1); end; end; end; { TDummy } procedure TDummy.Finish(Operation: TFileSourceOperation; State: TFileSourceOperationState); begin Application.Terminate; end; end.
object frmConnection: TfrmConnection Left = 480 Top = 345 BorderStyle = bsDialog Caption = 'Connection Settings' ClientHeight = 167 ClientWidth = 369 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -12 Font.Name = 'MS Sans Serif' Font.Style = [] OldCreateOrder = False Position = poScreenCenter PixelsPerInch = 96 TextHeight = 13 object Label1: TLabel Left = 35 Top = 60 Width = 47 Height = 13 Alignment = taRightJustify Caption = 'Server IP:' end object Label2: TLabel Left = 27 Top = 87 Width = 56 Height = 13 Alignment = taRightJustify Caption = 'Server Port:' end object Label3: TLabel Left = 14 Top = 5 Width = 341 Height = 42 AutoSize = False Caption = 'Please enter the connection settings' WordWrap = True end object edtIP: TEdit Left = 87 Top = 55 Width = 255 Height = 21 Color = 16774637 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -12 Font.Name = 'MS Sans Serif' Font.Style = [] ParentFont = False TabOrder = 0 end object edtPort: TEdit Left = 87 Top = 83 Width = 75 Height = 21 Color = 16774637 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -12 Font.Name = 'MS Sans Serif' Font.Style = [] ParentFont = False TabOrder = 1 end object BitBtn1: TBitBtn Left = 170 Top = 124 Width = 86 Height = 29 Kind = bkOK NumGlyphs = 2 TabOrder = 2 end object BitBtn2: TBitBtn Left = 267 Top = 124 Width = 86 Height = 29 Kind = bkCancel NumGlyphs = 2 TabOrder = 3 end end
unit VTiffHigherLevel; interface uses Windows, SysUtils, Classes, Graphics, LibTiffDelphi; {uses LibTiffDelphi, download it here: http://www.awaresystems.be/imaging/tiff/delphi.html } procedure WriteBmpToTiff(h: HBitmap; fn: PAnsiChar); function ReadTIFFIntoBitmap( S: TStream; B: TBitmap; Page: Integer; var PagesCount: Integer): Boolean; implementation procedure TIFFReadRGBAImageSwapRB(Width,Height: Cardinal; Memory: Pointer); {$IFDEF DELPHI_5} type PCardinal = ^Cardinal; {$ENDIF} var m: PCardinal; n: Cardinal; o: Cardinal; begin m:=Memory; for n:=0 to Width*Height-1 do begin o:=m^; m^:= (o and $FF00FF00) or {G and A} ((o and $00FF0000) shr 16) or {B} ((o and $000000FF) shl 16); {R} Inc(m); end; end; function ReadTIFFIntoBitmap(S: TStream; B: TBitmap; Page: Integer; var PagesCount: Integer): Boolean; var OpenTiff: PTIFF; FirstPageWidth,FirstPageHeight: Cardinal; B2: TBitmap; ScaleX, ScaleY: Single; Units: Cardinal; begin Result := False; PagesCount := 1; Units := 0; ScaleX := 1.0; ScaleY := 1.0; OpenTiff := TIFFOpenStream(S,'r'); if OpenTiff = nil then Exit; //raise Exception.Create('Cannot open TIFF stream'); PagesCount := TIFFNumberOfDirectories(OpenTiff); TIFFSetDirectory(OpenTiff, Page); TIFFGetField(OpenTiff, TIFFTAG_RESOLUTIONUNIT, @Units); TIFFGetField(OpenTiff, TIFFTAG_XRESOLUTION, @ScaleX); TIFFGetField(OpenTiff, TIFFTAG_YRESOLUTION, @ScaleY); TIFFGetField(OpenTiff,TIFFTAG_IMAGEWIDTH,@FirstPageWidth); TIFFGetField(OpenTiff,TIFFTAG_IMAGELENGTH,@FirstPageHeight); try B.PixelFormat := pf32bit; B.Width := FirstPageWidth; B.Height := FirstPageHeight; except TIFFClose(OpenTiff); Exit; //raise Exception.Create('Cannot create bitmap buffer'); end; TIFFReadRGBAImage(OpenTiff,FirstPageWidth,FirstPageHeight, B.Scanline[FirstPageHeight-1],0); TIFFClose(OpenTiff); TIFFReadRGBAImageSwapRB(FirstPageWidth,FirstPageHeight, B.Scanline[FirstPageHeight-1]); Result := True; if (Units<>RESUNIT_NONE) and (ScaleX<>ScaleY) then begin B2:= TBitmap.Create; B2.PixelFormat:= B.PixelFormat; if ScaleY > ScaleX then begin B2.Width:= Trunc(B.Width * (ScaleY/ScaleX)); B2.Height:= B.Height; end else begin B2.Width:= B.Width; B2.Height:= Trunc(B.Height * (ScaleX/ScaleY)); end; B2.Canvas.Brush.Color:= clWhite; B2.Canvas.FillRect(Rect(0, 0, B2.Width, B2.Height)); B2.Canvas.StretchDraw(Rect(0, 0, B2.Width, B2.Height), B); { //Test B2.Canvas.Brush.Color:= clYellow; B2.Canvas.FillRect(Rect(0, 0, B2.Width, B2.Height)); B2.Canvas.Draw(0, 0, B); } B.Width:= B2.Width; B.Height:= B2.Height; B.Canvas.Draw(0, 0, B2); {Messagebox(0, PChar(Format('was %d-%d, %d-%d', [B.Width, B.Height, B2.Width, B2.Height])), '',0); } FreeAndNil(B2); end; end; //---------- procedure WriteBitmapToTiff(Bitmap: TBitmap; const Filename: string); var OpenTiff: PTIFF; RowsPerStrip: Longword; StripMemory: Pointer; StripIndex: Longword; StripRowOffset: Longword; StripRowCount: Longword; ma,mb: PByte; nx,ny: Longword; begin if (Bitmap.PixelFormat<>pf24bit) and (Bitmap.PixelFormat<>pf32bit) then raise Exception.Create('WriteBitmapToTiff is designed for 24bit and 32bit bitmaps only'); RowsPerStrip:=((256*1024) div (Bitmap.Width*3)); if RowsPerStrip>Bitmap.Height then RowsPerStrip:=Bitmap.Height else if RowsPerStrip=0 then RowsPerStrip:=1; StripMemory:=GetMemory(RowsPerStrip*Bitmap.Width*3); OpenTiff:=TIFFOpen(PAnsiChar(Filename),'w'); if OpenTiff=nil then begin FreeMemory(StripMemory); raise Exception.Create('Unable to create file '''+Filename+''''); end; TIFFSetField(OpenTiff,TIFFTAG_IMAGEWIDTH,Bitmap.Width); TIFFSetField(OpenTiff,TIFFTAG_IMAGELENGTH,Bitmap.Height); TIFFSetField(OpenTiff,TIFFTAG_PHOTOMETRIC,PHOTOMETRIC_RGB); TIFFSetField(OpenTiff,TIFFTAG_SAMPLESPERPIXEL,3); TIFFSetField(OpenTiff,TIFFTAG_BITSPERSAMPLE,8); TIFFSetField(OpenTiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG); TIFFSetField(OpenTiff,TIFFTAG_COMPRESSION,COMPRESSION_LZW); TIFFSetField(OpenTiff,TIFFTAG_PREDICTOR,2); TIFFSetField(OpenTiff,TIFFTAG_ROWSPERSTRIP,RowsPerStrip); StripIndex:=0; StripRowOffset:=0; while StripRowOffset<Bitmap.Height do begin StripRowCount:=RowsPerStrip; if StripRowCount>Bitmap.Height-StripRowOffset then StripRowCount:=Bitmap.Height-StripRowOffset; if Bitmap.PixelFormat=pf24bit then begin mb:=StripMemory; for ny:=StripRowOffset to StripRowOffset+StripRowCount-1 do begin ma:=Bitmap.ScanLine[ny]; for nx:=0 to Bitmap.Width-1 do begin mb^:=PByte(Cardinal(ma)+2)^; Inc(mb); mb^:=PByte(Cardinal(ma)+1)^; Inc(mb); mb^:=PByte(Cardinal(ma)+0)^; Inc(mb); Inc(ma,3); end; end; end else begin mb:=StripMemory; for ny:=StripRowOffset to StripRowOffset+StripRowCount-1 do begin ma:=Bitmap.ScanLine[ny]; for nx:=0 to Bitmap.Width-1 do begin mb^:=PByte(Cardinal(ma)+2)^; Inc(mb); mb^:=PByte(Cardinal(ma)+1)^; Inc(mb); mb^:=PByte(Cardinal(ma)+0)^; Inc(mb); Inc(ma,4); end; end; end; if TIFFWriteEncodedStrip(OpenTiff,StripIndex, StripMemory,StripRowCount*Bitmap.Width*3)=0 then begin TIFFClose(OpenTiff); FreeMemory(StripMemory); raise Exception.Create('Failed to write '''+Filename+''''); end; Inc(StripIndex); Inc(StripRowOffset,StripRowCount); end; TIFFClose(OpenTiff); FreeMem(StripMemory); end; procedure WriteBmpToTiff(h: HBitmap; fn: PAnsiChar); var b: TBitmap; begin b:= TBitmap.Create; b.PixelFormat:= pf24bit; try b.Handle:= h; WriteBitmapToTiff(b, AnsiString(fn)); finally b.Free; end; end; end.
unit vos_win32_hw_power; interface implementation (* GetSystemPowerStatus wmi Select EstimatedChargeRemaining from Win32_Battery var SPS: TSystemPowerStatus; begin GetSystemPowerStatus(SPS); OutputDebugString(PWideChar('电源状态:' + IntToStr(SPS.ACLineStatus))); OutputDebugString(PWideChar('电池状态:' + IntToStr(SPS.BatteryFlag))); OutputDebugString(PWideChar('电量百分比:' + IntToStr(SPS.BatteryLifePercent))); OutputDebugString(PWideChar('剩余能量:' + IntToStr(SPS.BatteryLifeTime) + '秒')); OutputDebugString(PWideChar('总能量:' + IntToStr(SPS.BatteryFullLifeTime) + '秒')); end; strComputer = "." Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2") Set colItems = objWMIService.ExecQuery( _ "SELECT * FROM Win32_Battery",,48) For Each objItem in colItems Wscript.Echo "----------" Wscript.Echo "Win32_Battery instance" Wscript.Echo "----------" Wscript.Echo "EstimatedChargeRemaining: " & objItem.EstimatedChargeRemaining Next *) end.
unit tmsUXlsTokenArray; {$INCLUDE ..\FLXCOMPILER.INC} interface uses tmsXlsMessages, SysUtils, Math; type ETokenException= class (EExcelException) public Token: integer; constructor Create(const aToken: integer;const aDummy1: integer; const ADummy2: integer); end; //************************************************************* {**} procedure UXlsTokenArray_ArrangeInsertRowsAndCols(const Data: PArrayOfByte; const atPos, afPos: integer; const InsRowPos, InsRowOffset, CopyRowOffset: integer; const InsColPos, InsColOffset, CopyColOffset: integer; const SheetInfo: TSheetInfo; const AllowedAbsolute: boolean); {**} procedure UXlsTokenArray_ArrangeInsertSheets(const Data: PArrayOfByte; const atPos, afPos: integer; const SheetInfo: TSheetInfo); {**} procedure UXlsTokenArray_ArrangeSharedFormulas(const Data: PArrayOfByte; const atPos, afPos: integer; const SharedRow, SharedCol: integer); //************************************************************* implementation uses tmsUXlsFormula, tmsUXlsBaseRecordLists; procedure CreateInvalidRef(var Token: byte); begin if Token in tk_Ref then Inc(Token, tk_RefToRefErr) else if Token in tk_Area then Inc(Token, tk_AreaToAreaErr) else if Token in tk_Ref3D then Inc(Token, tk_Ref3DToRef3DErr) else if Token in tk_Area3D then Inc(Token, tk_Area3DToArea3DErr) else if not (Token in tk_RefErr + tk_Ref3DErr + tk_AreaErr + tk_Area3DErr) then raise ETokenException.Create(Token,0,0); end; procedure IncWordRef( const Pdata: PArrayOfByte; const tPos: integer; const InsPos, Offset: integer; const Max: integer; const tkPos: integer; const CheckInside: boolean); var w: int64; begin w:=Pdata^[tPos] or (PData^[tPos+1] shl 8); //Handle deletes... if CheckInside and (Offset<0) and (InsPos >=0) and (w>= InsPos) and (w<Inspos - Offset) then begin CreateInvalidRef( PData[tkPos]); exit; end; inc(w, Offset); if (w<0) or (w>Max) then begin CreateInvalidRef( PData[tkPos]); exit; end; Pdata^[tPos]:= byte(w); Pdata^[tPos+1]:= hi(word(w)); end; procedure IncByteRef( const Pdata: PArrayOfByte; const tPos: integer; const InsPos, Offset: integer; const Max: integer; const tkPos: integer; const CheckInside: boolean); var w: int64; begin w:=Pdata^[tPos]; //Handle deletes... if CheckInside and (Offset<0) and (InsPos >=0) and (w>= InsPos) and (w<Inspos - Offset) then begin CreateInvalidRef( PData[tkPos]); exit; end; inc(w, Offset); if (w<0) or (w>Max) then begin CreateInvalidRef( PData[tkPos]); exit; end; Pdata^[tPos]:= w; end; procedure IncW(const pData: PArrayOfByte; const tPos: integer; const Offset: integer); var w: ^Word; begin w:=@(PData[tPos]); inc(w^, Offset); end; procedure DeleteRowsArea(const tPos: Integer; const InsRowPos, InsRowOffset, r1, r2: integer; const Data: PArrayOfByte; const tkPos: Integer); begin if (r1 >= InsRowPos) then if (r2 < InsRowPos - InsRowOffset) then //range is all inside the deleted range CreateInvalidRef(Data[tkPos]) else begin //Do NOT DELETE full columns sum(a:a). should always remain this. (Except when deleting the full range on another sheet); //A funny one: Sum(a65536:a65536), when deleting a row, will convert to sum(a65535:65536). Only second row will wrap. IncWordRef(Data, tPos, InsRowPos, Max((InsRowPos - r1), (InsRowOffset)), Max_Rows, tkPos, false); if (r2<Max_Rows) then IncWordRef(Data, tPos + 2, InsRowPos, InsRowOffset, Max_Rows, tkPos, false); end else begin if (r2>=Max_Rows) then exit; if (r2 >= InsRowPos) then IncWordRef(Data, tPos + 2, InsRowPos, Max((InsRowPos - r2) - 1, InsRowOffset), Max_Rows, tkPos, false); end; end; procedure DeleteColsArea(const tPos: Integer; const InsRowPos, InsRowOffset, r1, r2: integer; const Data: PArrayOfByte; const tkPos: Integer); begin //Not implemented yet, until we adapt this to ranges. end; procedure ArrangeTokenOperand(Token: integer;const Data: ParrayOfByte; var tPos: integer; const InsRowPos, InsRowOffset, CopyRowOffset: integer; const InsColPos, InsColOffset, CopyColOffset: integer; const SheetInfo: TSheetInfo; const InsertingSheet: boolean; const SharedRow, SharedCol: integer; const AllowedAbsolute: boolean); var AbsoluteRowRef, AbsoluteColRef: boolean; LocalSheet: integer; tkPos: integer; Name, NewName: TNameRecord; NameList: TNameRecordList; i: integer; begin // Shared formulas if (SharedRow>=0) and (Token in tk_RefN+ tk_AreaN) then begin Inc(Data[tPos],$24-$2C); Token:=Data[tPos]; end; tkPos:=tPos; inc(tPos); LocalSheet:= SheetInfo.FormulaSheet; if Token in tk_Ref3D+ tk_Area3D+ tk_Ref3DErr + tk_Area3DErr then begin if Assigned(SheetInfo.GetSheet) then begin LocalSheet:=SheetInfo.GetSheet(GetWord(Data, tPos)); if InsertingSheet and (LocalSheet=SheetInfo.FormulaSheet) and Assigned(SheetInfo.SetSheet) then SetWord(Data, tPos, SheetInfo.SetSheet(SheetInfo.InsSheet)); //this copies external refs to the old sheet to the new sheet end; inc(tPos, 2); end; if Token in tk_Array then begin inc(tPos,7); //Values are stored outside the formula end else if (Token in tk_Name) or (Token in tk_NameX) then begin if (Token in tk_NameX) then inc(tPos, 2); if (SheetInfo.Names <> nil) then begin NameList := SheetInfo.Names as TNameRecordList; Name := NameList[GetWord(Data, tPos) - 1]; LocalSheet:=Name.RangeSheet; if InsertingSheet and ((LocalSheet=SheetInfo.FormulaSheet) or (LocalSheet<0)) then begin for i :=0 to NameList.Count - 1 do begin NewName := NameList[i]; if (NewName.RangeSheet = SheetInfo.InsSheet) and (NewName.Name = Name.Name) then begin SetWord(Data, tPos, i+1); break; end; end; end; end; inc(tPos, 4); end else if Token in tk_Ref + tk_RefErr + tk_Ref3D + tk_Ref3DErr then begin if (LocalSheet= SheetInfo.InsSheet) then begin if GetWord(Data, tPos)>= InsRowPos then IncWordRef(Data, tPos, InsRowPos, InsRowOffset, Max_Rows, tkpos, true); if Data[tPos+2]>= InsColPos then IncByteRef(Data, tPos+2, InsColPos, InsColOffset, Max_Columns, tkpos, true); end; AbsoluteRowRef:= AllowedAbsolute and ((GetWord(Data, tPos+2) and $8000) <> $8000); if not AbsoluteRowRef then IncWordRef(Data, tPos, -1, CopyRowOffset, Max_Rows, tkpos, true); AbsoluteColRef:= AllowedAbsolute and ((GetWord(Data, tPos+2) and $4000) <> $4000); if not AbsoluteColRef then IncByteRef(Data, tPos+2, -1, CopyColOffset, Max_Columns, tkpos, true); if SharedRow>=0 then begin AbsoluteRowRef:= AllowedAbsolute and ((GetWord(Data, tPos+2) and $8000) <> $8000); if not AbsoluteRowRef then IncW(Data, tPos, SharedRow); AbsoluteColRef:= AllowedAbsolute and ((GetWord(Data, tPos+2) and $4000) <> $4000); if not AbsoluteColRef then IncW(Data, tPos+2, SharedCol); end; inc(tPos,4); end else if Token in tk_RefN then inc(tPos,4)//This is used in conditional formats, besides shared formulas else if Token in tk_Area + tk_AreaErr + tk_Area3D + tk_Area3DErr then begin if (LocalSheet= SheetInfo.InsSheet) then begin if InsRowOffset<0 then DeleteRowsArea(tpos, InsRowPos, InsRowOffset, GetWord(Data, tPos), GetWord(Data, tPos+2), Data, tkpos) else begin if GetWord(Data, tPos)>= InsRowPos then IncWordRef(Data, tPos, InsRowPos, InsRowOffset, Max_Rows, tkpos, true); if (GetWord(Data, tPos+2)>= InsRowPos) and (GetWord(Data, tPos+2)<>Max_Rows) then IncWordRef(Data, tPos+2, InsRowPos, InsRowOffset, Max_Rows, tkpos, true); end; if InsColOffset<0 then DeleteColsArea(tpos+4, InsColPos, InsColOffset, GetWord(Data, tPos+4), GetWord(Data, tPos+6), Data, tkpos) else begin if Data[tPos+4]>= InsColPos then IncByteRef(Data, tPos+4, InsColPos, InsColOffset, Max_Columns, tkpos, true); if (Data[tPos+6]>= InsColPos) and (Data[tPos+6]<>Max_Columns) then IncByteRef(Data, tPos+6, InsColPos, InsColOffset, Max_Columns, tkpos, true); end; end; AbsoluteRowRef:= AllowedAbsolute and ((GetWord(Data, tPos+4) and $8000) <> $8000); if not AbsoluteRowRef then IncWordRef(Data, tPos, -1, CopyRowOffset, Max_Rows, tkpos, true); AbsoluteRowRef:= AllowedAbsolute and ((GetWord(Data, tPos+6) and $8000) <> $8000); if not AbsoluteRowRef then IncWordRef(Data, tPos+2, -1, CopyRowOffset, Max_Rows, tkpos, true); AbsoluteColRef:= AllowedAbsolute and ((GetWord(Data, tPos+4) and $4000) <> $4000); if not AbsoluteColRef then IncByteRef(Data, tPos+4, -1, CopyColOffset, Max_Columns, tkpos, true); AbsoluteColRef:= AllowedAbsolute and ((GetWord(Data, tPos+6) and $4000) <> $4000); if not AbsoluteColRef then IncByteRef(Data, tPos+6, -1, CopyColOffset, Max_Columns, tkpos, true); if SharedRow>=0 then begin AbsoluteRowRef:= AllowedAbsolute and ((GetWord(Data, tPos+4) and $8000) <> $8000); if not AbsoluteRowRef then IncW(Data, tPos, SharedRow); AbsolutecolRef:= AllowedAbsolute and ((GetWord(Data, tPos+4) and $4000) <> $4000); if not AbsoluteColRef then IncW(Data, tPos+4, SharedCol); AbsoluteRowRef:= AllowedAbsolute and ((GetWord(Data, tPos+6) and $8000) <> $8000); if not AbsoluteRowRef then IncW(Data, tPos+2, SharedRow); AbsoluteColRef:= AllowedAbsolute and ((GetWord(Data, tPos+6) and $4000) <> $4000); if not AbsoluteColRef then IncW(Data, tPos+6, SharedCol); end; inc(tPos,8); end else if Token in tk_AreaN then inc(tPos,8) //PENDING: Arreglar inserts en CFs else raise ETokenException.Create(Token,0,0); end; procedure ArrangeTokenTableAndArray(const Data: ParrayOfByte; var tPos: integer; const InsRowPos, InsRowOffset, CopyRowOffset: integer; const InsColPos, InsColOffset, CopyColOffset: integer; const SheetInfo: TSheetInfo; const InsertingSheet: boolean; const SharedRow, SharedCol: integer; const AllowedAbsolute: boolean); begin inc(tpos,5); if (SheetInfo.FormulaSheet<>SheetInfo.InsSheet)or (SharedRow>0) or (SharedCol>0) or InsertingSheet then exit; if GetWord(Data, tpos-4)>=InsRowPos then IncWordRef(Data, tPos-4, InsRowPos, InsRowOffset, Max_Rows, tPos-5, true); IncWordRef(Data, tPos-4, -1, CopyRowOffset, Max_Rows, tpos-5, true); if Data[tPos-2]>=InsColPos then IncByteRef(Data, tPos-2, InsColPos, InsColOffset, Max_Columns, tPos-5, true); IncByteRef(Data, tPos-2, -1, CopyColOffset, Max_Columns, tPos-5, true); end; procedure ArrangeTokenArray(const Data: PArrayOfByte; const atPos, afPos: integer; const InsRowPos, InsRowOffset, CopyRowOffset: integer; const InsColPos, InsColOffset, CopyColOffset: integer; const SheetInfo: TSheetInfo; const InsertingSheet: boolean; const SharedRow, SharedCol: integer; const AllowedAbsolute: boolean); var tPos, fPos: integer; Token: byte; begin; tPos:=atPos; fPos:=afPos; while tPos<fPos do begin Token:= Data[tPos]; if Token in tk_UnaryOps + tk_BinaryOps + [tk_MissArg] then inc(tPos) else if Token = tk_Str then inc(tPos,1 + GetStrLen(false, Data,tPos+1, False, 0)) else if Token in [tk_Err, tk_Bool] then inc(tPos,1+1) else if Token in [tk_Int]+ tk_Func then inc(tPos,1+2) else if Token in tk_FuncVar then inc(tPos,1+3) else if Token in [tk_Num] then inc(tPos,1+8) else if Token=tk_Attr then begin if (Data[tPos+1] and $04)=$04 then inc(tPos, (GetWord(Data, tPos+2)+1)*2); inc(tPos, 1+3); end else if Token in tk_Operand then ArrangeTokenOperand(Token, Data, tPos, InsRowPos, InsRowOffset, CopyRowOffset, InsColPos, InsColOffset, CopyColOffset, SheetInfo, InsertingSheet, SharedRow, SharedCol, AllowedAbsolute) else if Token=tk_Table then ArrangeTokenTableAndArray(Data, tPos, InsRowPos, InsRowOffset, CopyRowOffset, InsColPos, InsColOffset, CopyColOffset, SheetInfo, InsertingSheet, SharedRow, SharedCol, AllowedAbsolute) else if Token=tk_MemFunc then inc(tPos, 2+ 1) //GetWord(Data, tPos+1)) else if Token=tk_ArrayFormula then ArrangeTokenTableAndArray(Data, tPos, InsRowPos, InsRowOffset, CopyRowOffset, InsColPos, InsColOffset, CopyColOffset, SheetInfo, InsertingSheet, SharedRow, SharedCol, AllowedAbsolute) else raise ETokenException.Create(Token,0,0); end; end; procedure UXlsTokenArray_ArrangeInsertRowsAndCols(const Data: PArrayOfByte; const atPos, afPos: integer; const InsRowPos, InsRowOffset, CopyRowOffset: integer; const InsColPos, InsColOffset, CopyColOffset: integer; const SheetInfo: TSheetInfo; const AllowedAbsolute: boolean); begin ArrangeTokenArray(Data, atPos, afPos, InsRowPos, InsRowOffset, CopyRowOffset, InsColPos, InsColOffset, CopyColOffset, SheetInfo, false, -1, -1, AllowedAbsolute); end; procedure UXlsTokenArray_ArrangeInsertSheets(const Data: PArrayOfByte; const atPos, afPos: integer; const SheetInfo: TSheetInfo); begin ArrangeTokenArray(Data, atPos, afPos, 0, 0, 0, 0, 0, 0, SheetInfo, true, -1, -1, true); end; procedure UXlsTokenArray_ArrangeSharedFormulas(const Data: PArrayOfByte; const atPos, afPos: integer; const SharedRow, SharedCol: integer); var SheetInfo: TSheetInfo; begin SheetInfo.InsSheet:=0; SheetInfo.FormulaSheet:=0; SheetInfo.GetSheet:=nil; SheetInfo.SetSheet:=nil; SheetInfo.Names:=nil; ArrangeTokenArray(Data, atPos, afPos, 0, 0, 0, 0, 0, 0, SheetInfo, false, SharedRow, SharedCol, true); end; { ETokenException } constructor ETokenException.Create(const aToken: integer;const aDummy1: integer; const ADummy2: integer); begin Token:= aToken; inherited CreateFmt(ErrBadToken, [Token]); end; end.
program convert2; {$mode objfpc}{$H+} uses Interfaces, process, Classes, SysUtils, CustApp, CsvDocument, Sqlite3DS, FileUtil; type { TConvert2 } TConvert2 = class(TCustomApplication) private CSV: TCSVDocument; SQlite: TSqlite3Dataset; protected procedure DoRun; override; procedure GenerateAndroidDB(output: string); procedure LoadCSV(FileName: string); procedure ImportData(Table: string); public constructor Create(TheOwner: TComponent); override; destructor Destroy; override; procedure WriteHelp; virtual; end; { Convert2 } procedure ExecuteCommand(cmd, path: string); var AProcess: TProcess; begin WriteLn(cmd); AProcess := TProcess.Create(nil); AProcess.CurrentDirectory := path; AProcess.CommandLine := cmd; AProcess.Options := AProcess.Options + [poWaitOnExit, poUsePipes]; AProcess.ShowWindow := swoNone; try AProcess.Execute; except on Ex: Exception do begin WriteLn(''); WriteLn('Error: ' + Ex.Message); WriteLn(''); end; end; AProcess.Free; end; procedure TConvert2.DoRun; var output: string; ygodata, ygoeffect: string; path: string; begin if HasOption('h','help') then begin WriteHelp; Terminate; Exit; end; if HasOption('data') then begin ygodata:= GetOptionValue('data'); end; if HasOption('effect') then begin ygoeffect := GetOptionValue('effect'); end; if HasOption('output') then begin output:=GetOptionValue('output'); end; if (ygodata = '') or (ygoeffect = '') or (output = '') then begin WriteHelp; Terminate; Exit; end; WriteLn('Start importing...'); GenerateAndroidDB(output); LoadCSV(ygodata); ImportData('YGODATA'); WriteLn(''); LoadCSV(ygoeffect); ImportData('YGOEFFECT'); WriteLn(''); WriteLn('Import finish'); Terminate; end; procedure TConvert2.GenerateAndroidDB(output: string); var dbPath: string; begin dbPath:= output + '/yugioh.db'; if FileExists(dbPath) then begin DeleteFile(dbPath); end; SQlite.FileName:=dbPath; SQlite.SQL:='create table android_metadata(locale text)'; SQlite.ExecSQL; SQlite.SQL:='insert into android_metadata values (''en_US'')'; SQlite.ExecSQL; SQlite.SQL:='CREATE TABLE YGODATA (_id int primary key,CardID int,CardPhAl text,CardCamp text,JPCardName text,SCCardName text,TCCardName text,ENCardName text,ENCardName2 text,JPCardType text,SCCardType text,TCCardType text,ENCardType text,JPDCardType text,SCDCardType text,TCDCardType text,ENDCardType text,JPCardRace text,SCCardRace text,TCCardRace text,ENCardRace text,CardBagNum text,JPCardAttribute text,SCCardAttribute text,TCCardAttribute text,ENCardAttribute text,CardStarNum int,SCCardRare text,TCCardRare text,ENCardRare text,CardAtk int,CardAtk2 text,CardDef int,CardDef2 text,JPCardDepict text,SCCardDepict text,TCCardDepict text,ENCardDepict text,SCCardBan text,TCCardBan text,ENCardBan text,CardIsYKDT int,CardIsTKEN int,CardIsCZN text,CardPass text,CardAdjust text,CardLover int,CardUnion text,CardOnceName text,CardAbbrName text,CardEfficeType text)'; SQlite.ExecSQL; SQlite.SQL:='create table YGOEFFECT(_id int primary key, ID int, EFFECT text)'; SQlite.ExecSQL; end; procedure TConvert2.LoadCSV(FileName: string); begin with TStringList.Create do begin LoadFromFile(FileName); CSV.CSVText:=Text; Free; end; end; function GetFieldTypeName(cn: string): string; var r: string; begin r := ''; if (cn = 'TIntegerField') or (cn = 'TWordField') or (cn = 'TLongintField') then begin r := 'int'; end else begin r := 'text'; end; Result := r; end; procedure TConvert2.ImportData(Table: string); var rc: Integer; cc: Integer; i, j: Integer; s: string; begin cc := CSV.ColCount[1]; rc := CSV.RowCount; SQlite.Close; SQlite.SQL:=''; SQlite.TableName:=Table; SQlite.Open; for i:=1 to rc - 1 do begin SQlite.Insert; SQlite.Fields[0].AsInteger:=StrToInt(CSV.Cells[0, i]); for j:=0 to cc - 1 do begin if GetFieldTypeName(SQlite.Fields[j+1].ClassName) = 'int' then begin SQlite.Fields[j+1].AsInteger:=StrToIntDef(CSV.Cells[j, i], 0); end else begin s := Trim(CSV.Cells[j, i]); s := StringReplace(s, ' ','',[rfReplaceAll,rfIgnoreCase]); if s = '' then begin s := ' '; end; SQlite.Fields[j+1].AsString := s; end; end; SQlite.Post; Write(Format(#13'Importing %s Data: %d', [Table, i])); end; SQlite.ApplyUpdates; end; constructor TConvert2.Create(TheOwner: TComponent); begin inherited Create(TheOwner); StopOnException:=True; CSV := TCSVDocument.Create; SQlite := TSqlite3Dataset.Create(nil); end; destructor TConvert2.Destroy; begin CSV.Free; SQlite.Free; inherited Destroy; end; procedure TConvert2.WriteHelp; begin WriteLn('Data Prepare: '); WriteLn(' mdb-export YGODAT.DAT YGODATA > YGODATA.CSV'); WriteLn(' mdb-export YGODAT.DAT YGOEFFECT > YGOEFFECT.CSV'); writeln('Usage: ',ExeName,' -h'); WriteLn(' -data <YGODATA.CSV>'); WriteLn(' -effect <YGOEFFECT.CSV>'); WriteLn(' -output <output path>'); end; var Application: TConvert2; begin Application:=TConvert2.Create(nil); Application.Title:='Convert2'; Application.Run; Application.Free; end.
unit nsBaseNode; // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\Data\Tree\nsBaseNode.pas" // Стереотип: "SimpleClass" // Элемент модели: "TnsBaseNode" MUID: (4ADDF4470087) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface uses l3IntfUses , nsPrimCacheableNode , l3Tree_TLB , BaseTreeSupportUnit ; type TnsBaseNode = class; InsCacheable = interface ['{DFCFB2AE-BBBB-44F4-963F-AB185ED1AAAB}'] procedure ClearNums(aRecursive: Boolean); function Next: InsCacheable; end;//InsCacheable InsLastCache = interface ['{AF66F55C-8880-4568-A079-B9E5C2EC90E8}'] function Get_LastChild: Il3Node; procedure Set_LastChild(const aValue: Il3Node); property LastChild: Il3Node read Get_LastChild write Set_LastChild; end;//InsLastCache TnsBaseNode = class(TnsPrimCacheableNode, InsCacheable, InsLastCache) private f_AllChildrenCount: Integer; f_ChildNode: Il3Node; f_LastChild: Il3Node; f_NextNode: Il3Node; protected f_TotalNumInParent: Integer; f_ParentNode: Pointer; f_PrevNode: Pointer; protected function pm_GetLastChild: Il3Node; procedure pm_SetLastChild(const aValue: Il3Node); procedure ClearCache; virtual; procedure CallNextClearNums; virtual; procedure DoClearNums; virtual; function InsCacheableNext: InsCacheable; procedure InsCacheableClearNums(aRecursive: Boolean); procedure ClearNums(aRecursive: Boolean); function Next: InsCacheable; function Get_LastChild: Il3Node; procedure Set_LastChild(const aValue: Il3Node); procedure Cleanup; override; {* Функция очистки полей объекта. } procedure Set_ChildNode(const aValue: Il3Node); override; function Get_AllChildrenCount: Integer; override; function Get_ChildNode: Il3Node; override; procedure DoSortChilds(const aChild: Il3Node = nil); override; function DoGetNumInParent(aOnlyOneLevel: Boolean = False): Integer; override; procedure DoReleaseChilds; override; procedure DoIncAllChildrenCount(aInc: Integer); override; procedure ClearFields; override; public constructor Create(const aNode: INode; aNumInParent: Integer; aTotalNumInParent: Integer); reintroduce; class function Make(const aNode: INode; aNumInParent: Integer = -1; aTotalNumInParent: Integer = -1): Il3Node; reintroduce; public property ChildNode: Il3Node read f_ChildNode write f_ChildNode; property LastChild: Il3Node read pm_GetLastChild write pm_SetLastChild; property NextNode: Il3Node read f_NextNode write f_NextNode; end;//TnsBaseNode implementation uses l3ImplUses , SysUtils , l3Nodes , l3Types , l3TreeInterfaces //#UC START# *4ADDF4470087impl_uses* //#UC END# *4ADDF4470087impl_uses* ; function TnsBaseNode.pm_GetLastChild: Il3Node; //#UC START# *4ADEE7A00336_4ADDF4470087get_var* //#UC END# *4ADEE7A00336_4ADDF4470087get_var* begin //#UC START# *4ADEE7A00336_4ADDF4470087get_impl* Result := f_LastChild; //#UC END# *4ADEE7A00336_4ADDF4470087get_impl* end;//TnsBaseNode.pm_GetLastChild procedure TnsBaseNode.pm_SetLastChild(const aValue: Il3Node); //#UC START# *4ADEE7A00336_4ADDF4470087set_var* //#UC END# *4ADEE7A00336_4ADDF4470087set_var* begin //#UC START# *4ADEE7A00336_4ADDF4470087set_impl* f_LastChild := aValue; //#UC END# *4ADEE7A00336_4ADDF4470087set_impl* end;//TnsBaseNode.pm_SetLastChild constructor TnsBaseNode.Create(const aNode: INode; aNumInParent: Integer; aTotalNumInParent: Integer); //#UC START# *4AE05F2A0067_4ADDF4470087_var* //#UC END# *4AE05F2A0067_4ADDF4470087_var* begin //#UC START# *4AE05F2A0067_4ADDF4470087_impl* DoClearNums; inherited Create(aNode, aNumInParent); f_AllChildrenCount := -1; f_TotalNumInParent := aTotalNumInParent; //#UC END# *4AE05F2A0067_4ADDF4470087_impl* end;//TnsBaseNode.Create class function TnsBaseNode.Make(const aNode: INode; aNumInParent: Integer = -1; aTotalNumInParent: Integer = -1): Il3Node; var l_Inst : TnsBaseNode; begin l_Inst := Create(aNode, aNumInParent, aTotalNumInParent); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TnsBaseNode.Make procedure TnsBaseNode.ClearCache; //#UC START# *4ADEE7F1039D_4ADDF4470087_var* //#UC END# *4ADEE7F1039D_4ADDF4470087_var* begin //#UC START# *4ADEE7F1039D_4ADDF4470087_impl* f_AdapterCaption := nil; f_AllChildrenCount := -1; //#UC END# *4ADEE7F1039D_4ADDF4470087_impl* end;//TnsBaseNode.ClearCache procedure TnsBaseNode.CallNextClearNums; //#UC START# *4ADEE7FC0068_4ADDF4470087_var* var l_Cacheable : InsCacheable; //#UC END# *4ADEE7FC0068_4ADDF4470087_var* begin //#UC START# *4ADEE7FC0068_4ADDF4470087_impl* l_Cacheable := InsCacheableNext; while (l_Cacheable <> nil) do begin l_Cacheable.ClearNums(false); l_Cacheable := l_Cacheable.Next; end;//while (l_Cacheable //#UC END# *4ADEE7FC0068_4ADDF4470087_impl* end;//TnsBaseNode.CallNextClearNums procedure TnsBaseNode.DoClearNums; //#UC START# *4ADEE99702C7_4ADDF4470087_var* //#UC END# *4ADEE99702C7_4ADDF4470087_var* begin //#UC START# *4ADEE99702C7_4ADDF4470087_impl* f_NumInParent := -1; f_TotalNumInParent := -1; //#UC END# *4ADEE99702C7_4ADDF4470087_impl* end;//TnsBaseNode.DoClearNums function TnsBaseNode.InsCacheableNext: InsCacheable; //#UC START# *4ADEE9B203C9_4ADDF4470087_var* //#UC END# *4ADEE9B203C9_4ADDF4470087_var* begin //#UC START# *4ADEE9B203C9_4ADDF4470087_impl* Supports(f_NextNode, InsCacheable, Result); //#UC END# *4ADEE9B203C9_4ADDF4470087_impl* end;//TnsBaseNode.InsCacheableNext procedure TnsBaseNode.InsCacheableClearNums(aRecursive: Boolean); //#UC START# *4ADEE9D002E9_4ADDF4470087_var* //#UC END# *4ADEE9D002E9_4ADDF4470087_var* begin //#UC START# *4ADEE9D002E9_4ADDF4470087_impl* DoClearNums; if aRecursive then CallNextClearNums; //#UC END# *4ADEE9D002E9_4ADDF4470087_impl* end;//TnsBaseNode.InsCacheableClearNums procedure TnsBaseNode.ClearNums(aRecursive: Boolean); //#UC START# *4ADEE648003C_4ADDF4470087_var* //#UC END# *4ADEE648003C_4ADDF4470087_var* begin //#UC START# *4ADEE648003C_4ADDF4470087_impl* InsCacheableClearNums(aRecursive); //#UC END# *4ADEE648003C_4ADDF4470087_impl* end;//TnsBaseNode.ClearNums function TnsBaseNode.Next: InsCacheable; //#UC START# *4ADEE659029C_4ADDF4470087_var* //#UC END# *4ADEE659029C_4ADDF4470087_var* begin //#UC START# *4ADEE659029C_4ADDF4470087_impl* Result := InsCacheableNext; //#UC END# *4ADEE659029C_4ADDF4470087_impl* end;//TnsBaseNode.Next function TnsBaseNode.Get_LastChild: Il3Node; //#UC START# *4ADEE67A002B_4ADDF4470087get_var* //#UC END# *4ADEE67A002B_4ADDF4470087get_var* begin //#UC START# *4ADEE67A002B_4ADDF4470087get_impl* Result := LastChild; //#UC END# *4ADEE67A002B_4ADDF4470087get_impl* end;//TnsBaseNode.Get_LastChild procedure TnsBaseNode.Set_LastChild(const aValue: Il3Node); //#UC START# *4ADEE67A002B_4ADDF4470087set_var* //#UC END# *4ADEE67A002B_4ADDF4470087set_var* begin //#UC START# *4ADEE67A002B_4ADDF4470087set_impl* LastChild := aValue; //#UC END# *4ADEE67A002B_4ADDF4470087set_impl* end;//TnsBaseNode.Set_LastChild procedure TnsBaseNode.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_4ADDF4470087_var* //#UC END# *479731C50290_4ADDF4470087_var* begin //#UC START# *479731C50290_4ADDF4470087_impl* ClearCache; inherited; //#UC END# *479731C50290_4ADDF4470087_impl* end;//TnsBaseNode.Cleanup procedure TnsBaseNode.Set_ChildNode(const aValue: Il3Node); //#UC START# *4ADEEFA00164_4ADDF4470087_var* //#UC END# *4ADEEFA00164_4ADDF4470087_var* begin //#UC START# *4ADEEFA00164_4ADDF4470087_impl* ChildNode := aValue; //#UC END# *4ADEEFA00164_4ADDF4470087_impl* end;//TnsBaseNode.Set_ChildNode function TnsBaseNode.Get_AllChildrenCount: Integer; //#UC START# *54C78C200291_4ADDF4470087_var* procedure CountChild(const aNode: Il3Node); begin Inc(Result, aNode.AllChildrenCount); Inc(Result); end; //#UC END# *54C78C200291_4ADDF4470087_var* begin //#UC START# *54C78C200291_4ADDF4470087_impl* if (f_AllChildrenCount < 0) then begin Result := 0; IterateF(l3L2NA(@CountChild), imOneLevel); f_AllChildrenCount := Result; end else Result := f_AllChildrenCount; //#UC END# *54C78C200291_4ADDF4470087_impl* end;//TnsBaseNode.Get_AllChildrenCount function TnsBaseNode.Get_ChildNode: Il3Node; //#UC START# *54C78E2702B3_4ADDF4470087_var* //#UC END# *54C78E2702B3_4ADDF4470087_var* begin //#UC START# *54C78E2702B3_4ADDF4470087_impl* Result := ChildNode; //#UC END# *54C78E2702B3_4ADDF4470087_impl* end;//TnsBaseNode.Get_ChildNode procedure TnsBaseNode.DoSortChilds(const aChild: Il3Node = nil); //#UC START# *54C8E0850062_4ADDF4470087_var* var lChild, lNextNode, lNextOfChild : Il3InternalNode; lEndList : Boolean; lUserParam : Pointer; procedure lpMoveNode(const aMoveNode : Il3InternalNode; const aNextNode : Il3InternalNode); begin // Если aMoveNode и так стоит перед aNextNode или она единственная, то ничего делать не надо if (not aMoveNode.IsLast and (aMoveNode.NextNode As Il3InternalNode).IsSame(aNextNode)) or (aMoveNode.IsFirst and aMoveNode.IsLast) then exit; Notify(ntMoveBegin, aMoveNode); try lUserParam := nil; aMoveNode.BeginMove(lUserParam); try // aMoveNode перемещается из конца списка if aMoveNode.IsLast then LastChild := aMoveNode.PrevNode else if not aMoveNode.IsFirst then (aMoveNode.NextNode As Il3InternalNode).PrevNode := aMoveNode.PrevNode else (aMoveNode.NextNode As Il3InternalNode).PrevNode := nil; // aMoveNode перемещается из начала списка if aMoveNode.IsFirst then ChildNode := aMoveNode.NextNode else if not aMoveNode.IsLast then (aMoveNode.PrevNode As Il3InternalNode).NextNode := aMoveNode.NextNode else (aMoveNode.PrevNode As Il3InternalNode).NextNode := nil; // aMoveNode перемещается в конец списка if aNextNode = nil then begin aMoveNode.NextNode := nil; aMoveNode.PrevNode := LastChild; (aMoveNode.PrevNode As Il3InternalNode).NextNode := aMoveNode; LastChild := aMoveNode; end else // aMoveNode перемещается в начало списка if aNextNode.IsFirst then begin ChildNode := aMoveNode; aMoveNode.PrevNode := nil; aMoveNode.NextNode := aNextNode; aNextNode.PrevNode := aMoveNode; end else begin // вставляем aMoveNode перед aNextNode aMoveNode.PrevNode := aNextNode.PrevNode; aMoveNode.NextNode := aNextNode; (aNextNode.PrevNode As Il3InternalNode).NextNode := aMoveNode; aNextNode.PrevNode := aMoveNode; end; // Cбрасываем закэшированные NumInParent и TotalNumInParent (aMoveNode as InsCacheable).ClearNums(true); finally aMoveNode.EndMove(lUserParam); end;//try..finally finally Notify(ntMoveEnd, aMoveNode); end;//try..finally end;//lpMoveNode //#UC END# *54C8E0850062_4ADDF4470087_var* begin //#UC START# *54C8E0850062_4ADDF4470087_impl* if not HasChild or // если в текущей ветке нет детей или ChildNode.IsLast then // если в ветке всего один элемент - то ничего делать не надо exit; if (aChild <> nil) then // Позиционирование указанного элемента относительно остальных детей begin // Позиционирование указанного элемента относительно остальных детей if not IsSame(aChild.ParentNode) then exit; lNextNode := (ChildNode as Il3InternalNode); lChild := aChild as Il3InternalNode; // Ищем позицию для перемещения для lСhild, начиная с lNextNode while true do begin if not lChild.IsSame(lNextNode) then begin if CompareChild(lChild, lNextNode) < 0 then Break; // позиция для перемещения найдена end;//not lChild.IsSameNode(lNextNode) lNextNode := lNextNode.NextNode as Il3InternalNode; if lNextNode.IsFirst then // просмотрен весь список детей begin lNextNode := nil; // будем перемещать lChild в конец списка. Break; end; end;//while true lpMoveNode(lChild, lNextNode); // перемещение end//aChild <> nil else // Сортировка всех детей в ветке begin lChild := ChildNode.NextNode as Il3InternalNode; lEndList := lChild.IsLast; while true do begin lNextNode := ChildNode as Il3InternalNode; while true do begin if not lChild.IsSame(lNextNode) then begin if (CompareChild(lChild, lNextNode) < 0) then begin lNextOfChild := lChild.NextNode as Il3InternalNode; if lNextNode.IsLast then lpMoveNode(lChild, nil) else lpMoveNode(lChild, lNextNode); lChild := lNextOfChild; Break; end end else begin lChild := lChild.NextNode as Il3InternalNode; Break; end; lNextNode := lNextNode.NextNode as Il3InternalNode; end;//while true if lEndList then Break; {конец списка} lEndList := lChild.IsLast; end;//while true end;//aChild <> nil //#UC END# *54C8E0850062_4ADDF4470087_impl* end;//TnsBaseNode.DoSortChilds function TnsBaseNode.DoGetNumInParent(aOnlyOneLevel: Boolean = False): Integer; //#UC START# *54C8E1F30128_4ADDF4470087_var* //#UC END# *54C8E1F30128_4ADDF4470087_var* begin //#UC START# *54C8E1F30128_4ADDF4470087_impl* if aOnlyOneLevel then Result := inherited DoGetNumInParent(aOnlyOneLevel) else begin if (f_TotalNumInParent < 0) then f_TotalNumInParent := inherited DoGetNumInParent(false); Result := f_TotalNumInParent; end;//aOnlyOneLevel //#UC END# *54C8E1F30128_4ADDF4470087_impl* end;//TnsBaseNode.DoGetNumInParent procedure TnsBaseNode.DoReleaseChilds; //#UC START# *54C8E22F0223_4ADDF4470087_var* //#UC END# *54C8E22F0223_4ADDF4470087_var* begin //#UC START# *54C8E22F0223_4ADDF4470087_impl* Notify(ntChildClear, Self); AllChildrenCount := 0; ChildNode := nil; AdapterNode := nil; LastChild := nil; //#UC END# *54C8E22F0223_4ADDF4470087_impl* end;//TnsBaseNode.DoReleaseChilds procedure TnsBaseNode.DoIncAllChildrenCount(aInc: Integer); //#UC START# *54C8E4A8037A_4ADDF4470087_var* //#UC END# *54C8E4A8037A_4ADDF4470087_var* begin //#UC START# *54C8E4A8037A_4ADDF4470087_impl* if (aInc <> 0) then begin if (f_AllChildrenCount >= 0) then f_AllChildrenCount := f_AllChildrenCount + aInc else AllChildrenCount; if (ParentNode <> nil) then ParentNode.IncAllChildrenCount(aInc); CallNextClearNums; end; //#UC END# *54C8E4A8037A_4ADDF4470087_impl* end;//TnsBaseNode.DoIncAllChildrenCount procedure TnsBaseNode.ClearFields; begin ChildNode := nil; LastChild := nil; NextNode := nil; inherited; end;//TnsBaseNode.ClearFields end.
unit GraphEditors; interface uses Classes, Forms, Dialogs, ExtDlgs, DsgnIntf, TypInfo, SysUtils, CanvasBmp, SpeedBmp, PlayerAnim, PlayerFlic, PlayerRle, PlayerGif; type TSpeedBitmapProperty = class( TClassProperty ) public procedure SetValue( const Value: string ); override; procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; type TFlicPlayerProperty = class( TClassProperty ) public procedure SetValue( const Value: string ); override; procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; type TRlePlayerProperty = class( TClassProperty ) public procedure SetValue( const Value: string ); override; procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; type TGifPlayerProperty = class( TClassProperty ) public procedure SetValue( const Value: string ); override; procedure Edit; override; function GetAttributes : TPropertyAttributes; override; end; type TStretchBltModeProperty = class( TOrdinalProperty ) public function GetAttributes : TPropertyAttributes; override; procedure GetValues( Proc : TGetStrProc ); override; procedure SetValue( const Value: string ); override; function GetValue: string; override; end; procedure Register; implementation uses CommRez; // TStretchBltMode type TStretchValue = record Name : string; Value : integer; end; const StretchValues : array[0..4] of TStretchValue = ( ( Name : 'stUnknown'; Value : -1 ), ( Name : 'stAndScans'; Value : 1 ), ( Name : 'stOrScans'; Value : 2 ), ( Name : 'stDeleteScans'; Value : 3 ), ( Name : 'stHalftone'; Value : 4 ) ); procedure TStretchBltModeProperty.GetValues( Proc : TGetStrProc ); var i : integer; begin for i := Low( StretchValues ) + 1 to High( StretchValues ) do Proc( StretchValues[i].Name ); end; procedure TStretchBltModeProperty.SetValue( const Value: string ); var LoCase : string; i : integer; begin LoCase := LowerCase( Value ); for i := Low( StretchValues ) + 1 to High( StretchValues ) do if LowerCase( StretchValues[i].Name ) = LoCase then SetOrdValue( StretchValues[i].Value ); end; function TStretchBltModeProperty.GetValue: string; begin Result := StretchValues[GetOrdValue].Name; end; function TStretchBltModeProperty.GetAttributes : TPropertyAttributes; begin Result := [paValueList, paRevertable]; end; // TSpeedBitmap procedure TSpeedBitmapProperty.Edit; var OpenDialog : TOpenPictureDialog; begin OpenDialog := TOpenPictureDialog.Create( Application ); with OpenDialog do try Options := [ofFileMustExist, ofHideReadOnly]; Filter := SBitmapFilesMask; DefaultExt := 'bmp'; if Execute then SetValue( Filename ); finally OpenDialog.Free; end; end; function TSpeedBitmapProperty.GetAttributes : TPropertyAttributes; begin if GetOrdValue <> 0 then Result := [paDialog, paSubproperties, paRevertable] else Result := [paDialog, paRevertable]; end; procedure TSpeedBitmapProperty.SetValue( const Value: string ); var Bitmap : TSpeedBitmap; begin Bitmap := TSpeedBitmap( GetOrdValue ); if not Assigned( Bitmap ) then begin Bitmap := TSpeedBitmap.Create; SetOrdValue( integer( Bitmap ) ); end; with Bitmap do if Value <> '' then LoadFromFile( Value ) else Empty := true; end; // TFlicPlayer procedure TFlicPlayerProperty.Edit; var OpenDialog : TOpenPictureDialog; begin OpenDialog := TOpenPictureDialog.Create( Application ); with OpenDialog do try Options := [ofFileMustExist, ofHideReadOnly]; Filter := SBitmapFilesMask; DefaultExt := '.bmp'; if Execute then SetValue( Filename ); finally OpenDialog.Free; end; end; function TFlicPlayerProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paRevertable]; end; procedure TFlicPlayerProperty.SetValue( const Value: string ); var Flic : TFlicPlayer; begin Flic := TFlicPlayer( GetOrdValue ); (* if not Assigned( Flic ) then begin Flic := TFlicPlayer.Create; SetOrdValue( integer( Flic ) ); end; *) with Flic do LoadFromFile( Value ); end; // TGifPlayer procedure TGifPlayerProperty.Edit; var OpenDialog : TOpenPictureDialog; begin OpenDialog := TOpenPictureDialog.Create( Application ); with OpenDialog do try Options := [ofFileMustExist, ofHideReadOnly]; Filter := SGifFilesMask; DefaultExt := '.gif'; if Execute then SetValue( Filename ); finally OpenDialog.Free; end; end; function TGifPlayerProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paRevertable]; end; procedure TGifPlayerProperty.SetValue( const Value: string ); var Gif : TGifPlayer; begin Gif := TGifPlayer( GetOrdValue ); (* if not Assigned( Gif ) then begin Gif := TGifPlayer.Create; SetOrdValue( integer( Gif ) ); end; *) with Gif do LoadFromFile( Value ); end; // TRlePlayer procedure TRlePlayerProperty.Edit; var OpenDialog : TOpenPictureDialog; begin OpenDialog := TOpenPictureDialog.Create( Application ); with OpenDialog do try Options := [ofFileMustExist, ofHideReadOnly]; Filter := SRleAnimFilesMask; DefaultExt := '.rla'; if Execute then SetValue( Filename ); finally OpenDialog.Free; end; end; function TRlePlayerProperty.GetAttributes : TPropertyAttributes; begin Result := [paDialog, paRevertable]; end; procedure TRlePlayerProperty.SetValue( const Value: string ); var Rle : TRlePlayer; begin Rle := TRlePlayer( GetOrdValue ); (* if not Assigned( Rle ) then begin Rle := TRlePlayer.Create; SetOrdValue( integer( Rle ) ); end; *) with Rle do LoadFromFile( Value ); end; // VCL Registration procedure Register; begin RegisterPropertyEditor( TypeInfo( TStretchBltMode ), nil, '', TStretchBltModeProperty ); RegisterPropertyEditor( TypeInfo( TSpeedBitmap ), nil, '', TSpeedBitmapProperty ); RegisterPropertyEditor( TypeInfo( TFlicPlayer ), nil, '', TFlicPlayerProperty ); RegisterPropertyEditor( TypeInfo( TGifPlayer ), nil, '', TGifPlayerProperty ); RegisterPropertyEditor( TypeInfo( TRlePlayer ), nil, '', TRlePlayerProperty ); end; end.
unit uROWebsocketServer; interface uses Classes, //copied from: http://code.google.com/p/bauglir-websocket/downloads/detail?name=BauglirWebSocket2_pascal_library.2.0.4.zip WebSocket2, CustomServer2, uROServer, uROBaseHTTPServer, SysUtils; type TROWebsocketServer = class(TROServer) protected FServer: TWebSocketServer; procedure ServerAfterAddConnection(Server: TCustomServer; aConnection: TCustomConnection); procedure WebSocketConnectionDataFull(aSender: TWebSocketCustomConnection; aCode: integer; aData: TMemoryStream); protected FActive: Boolean; FPort: Integer; procedure IntSetActive(const Value: boolean); override; function IntGetActive : boolean; override; function GetPort: Integer;override; procedure SetPort(const Value: Integer);override; function GetServerType: TROServerType; override; public constructor Create(aComponent: TComponent); override; destructor Destroy; override; property Port; end; implementation uses uROClientIntf; { TROWebsocketServer } constructor TROWebsocketServer.Create(aComponent: TComponent); begin inherited; end; destructor TROWebsocketServer.Destroy; begin // inherited; end; function TROWebsocketServer.GetPort: Integer; begin Result := FPort; end; function TROWebsocketServer.GetServerType: TROServerType; begin Result := rstTCP; end; function TROWebsocketServer.IntGetActive: boolean; begin Result := FActive; end; procedure TROWebsocketServer.IntSetActive(const Value: boolean); begin inherited; FActive := Value; if FActive then begin FServer := TWebSocketServer.Create('0.0.0.0', IntToStr(Self.Port) ); FServer.OnAfterAddConnection := ServerAfterAddConnection; FServer.Start; end else begin //FServer.Stop; FServer.FreeOnTerminate := True; FServer.CloseAllConnections(0, 'Server stop'); FServer.TerminateThread; //FServer.WaitFor(); //FreeAndNil(FServer); end; end; procedure TROWebsocketServer.ServerAfterAddConnection(Server: TCustomServer; aConnection: TCustomConnection); begin if aConnection is TWebSocketCustomConnection then begin (aConnection as TWebSocketCustomConnection).OnReadFull := WebSocketConnectionDataFull; (aConnection as TWebSocketCustomConnection).FullDataProcess := True; end; end; procedure TROWebsocketServer.SetPort(const Value: Integer); begin inherited; FPort := Value; end; type TTempTransport = class(TInterfacedObject, IROTransport) protected FROServer: TROServer; {IROTransport} function GetTransportObject: TObject; public constructor Create(aROServer: TROServer); end; procedure TROWebsocketServer.WebSocketConnectionDataFull( aSender: TWebSocketCustomConnection; aCode: integer; aData: TMemoryStream); var strmResponse: TMemoryStream; begin strmResponse := TMemoryStream.Create; try Self.DispatchMessage( TTempTransport.Create(Self), aData, strmResponse); with TStreamReader.Create(strmResponse) do begin aSender.SendText(ReadToEnd); Free; end; //aSender.SendBinary(strmResponse); finally strmResponse.Free; end; end; { TTempTransport } constructor TTempTransport.Create(aROServer: TROServer); begin FROServer := aROServer; end; function TTempTransport.GetTransportObject: TObject; begin Result := FROServer; end; end.
unit View.CadastroEnregadores; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxSkinsCore, dxSkinsDefaultPainters, cxClasses, dxLayoutContainer, dxLayoutControl, Common.ENum, Common.Utils, Global.Parametros, cxContainer, cxEdit, dxLayoutcxEditAdapters, cxLabel, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator, dxDateRanges, cxDataControllerConditionalFormattingRulesManagerDialog, cxDBData, cxGridLevel, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxDBLookupComboBox, cxSpinEdit, cxTextEdit, cxMaskEdit, cxButtonEdit; type Tview_TemplateCadastro = class(TForm) layoutControlPadraoGroup_Root: TdxLayoutGroup; layoutControlPadrao: TdxLayoutControl; labelTitle: TcxLabel; layoutItemLabelTitle: TdxLayoutItem; memTableEntregadores: TFDMemTable; memTableEntregadorescod_cadastro: TIntegerField; memTableEntregadorescod_entregador: TIntegerField; memTableEntregadoresnom_fantasia: TStringField; memTableEntregadorescod_agente: TIntegerField; memTableEntregadoresdat_codigo: TDateField; memTableEntregadoresdes_chave: TStringField; memTableEntregadorescod_grupo: TIntegerField; memTableEntregadoresval_verba: TFloatField; memTableEntregadoresnom_executante: TStringField; memTableEntregadoresdom_ativo: TIntegerField; memTableEntregadoresdat_manutencao: TDateTimeField; memTableEntregadorescod_tabela: TIntegerField; gridEntregadoresDBTableView1: TcxGridDBTableView; gridEntregadoresLevel1: TcxGridLevel; gridEntregadores: TcxGrid; layoutItemGridEntregadores: TdxLayoutItem; dsEntregadores: TDataSource; gridEntregadoresDBTableView1cod_cadastro: TcxGridDBColumn; gridEntregadoresDBTableView1cod_entregador: TcxGridDBColumn; gridEntregadoresDBTableView1nom_fantasia: TcxGridDBColumn; gridEntregadoresDBTableView1cod_agente: TcxGridDBColumn; gridEntregadoresDBTableView1dat_codigo: TcxGridDBColumn; gridEntregadoresDBTableView1des_chave: TcxGridDBColumn; gridEntregadoresDBTableView1cod_grupo: TcxGridDBColumn; gridEntregadoresDBTableView1val_verba: TcxGridDBColumn; gridEntregadoresDBTableView1nom_executante: TcxGridDBColumn; gridEntregadoresDBTableView1dom_ativo: TcxGridDBColumn; gridEntregadoresDBTableView1dat_manutencao: TcxGridDBColumn; gridEntregadoresDBTableView1cod_tabela: TcxGridDBColumn; mtbTipos: TFDMemTable; mtbTiposcod_tipo: TIntegerField; mtbTiposdes_tipo: TStringField; mtbTiposdes_colunas: TStringField; dsTipos: TDataSource; layoutControlCadastroGroup_Root: TdxLayoutGroup; layoutControlCadastro: TdxLayoutControl; layoutItemCadastro: TdxLayoutItem; buttonEditPessoa: TcxButtonEdit; layoutItemCodigoCadastro: TdxLayoutItem; textEditNomePessoa: TcxTextEdit; layoutItemNomePessoa: TdxLayoutItem; dxLayoutAutoCreatedGroup1: TdxLayoutAutoCreatedGroup; private { Private declarations } public { Public declarations } end; var view_TemplateCadastro: Tview_TemplateCadastro; implementation {$R *.dfm} uses Data.SisGeF; end.
{******************************************************************************} { } { Delphi FB4D Library } { Copyright (c) 2018-2022 Christoph Schneider } { Schneider Infosystems AG, Switzerland } { https://github.com/SchneiderInfosystems/FB4D } { } {******************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {******************************************************************************} unit FB4D.PerUserReadWrite; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.JSON, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Objects, FMX.Edit, FMX.Controls.Presentation, FMX.TabControl, FMX.Layouts, FB4D.Interfaces, FB4D.Configuration, FB4D.SelfRegistrationFra; type TfmxMain = class(TForm) TabControl: TTabControl; tabAuth: TTabItem; tabRTDBAccess: TTabItem; lblUserInfo: TLabel; layUserInfo: TLayout; btnSignOut: TButton; FraSelfRegistration: TFraSelfRegistration; edtDBMessage: TEdit; lblStatus: TLabel; btnWrite: TButton; procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnSignOutClick(Sender: TObject); procedure edtDBMessageChangeTracking(Sender: TObject); procedure btnWriteClick(Sender: TObject); private fConfig: IFirebaseConfiguration; fEvent: IFirebaseEvent; fUID: string; function GetSettingFilename: string; function LoadLastToken: string; procedure SaveToken; procedure OnUserLogin(const Info: string; User: IFirebaseUser); procedure WipeToTab(ActiveTab: TTabItem); procedure StartListening; procedure OnDBEvent(const Event: string; Params: TRequestResourceParam; JSONObj: TJSONObject); procedure OnDBError(const RequestID, ErrMsg: string); procedure OnDBWritten(ResourceParams: TRequestResourceParam; Val: TJSONValue); procedure OnDBStop(Sender: TObject); function DBPath: TRequestResourceParam; end; var fmxMain: TfmxMain; implementation uses System.IniFiles, System.IOUtils, FB4D.Helpers; {$R *.fmx} resourcestring rsUserInfo = 'Logged in with eMail: %s'#13'User ID: %s'; rsHintRTDBRules = 'Hint to permission error:'#13#13 + 'Before you can write into the real time database add the following'#13 + 'text in the Firebase console as rule for the Realtime Database:'#13#13 + '{'#13 + ' "rules": {'#13 + ' "UserMsg": {'#13 + ' "$uid": {'#13 + ' ".read": "(auth != null) && (auth.uid == $uid)",'#13 + ' ".write": "(auth != null) && (auth.uid == $uid)" '#13 + ' }'#13 + ' }'#13 + ' }'#13 + '}'#13; const // Alternative way by entering // ApiKey = '<Your Firebase ApiKey listed in the Firebase Console>'; // ProjectID = '<Your Project ID listed in the Firebase Console>'; // FirebaseURL = '<The URL of your RealTime DB from the Firebase Console>'; {$IFDEF MSWINDOWS} GoogleServiceJSON = '..\..\..\google-services.json'; {$ENDIF} {$IFDEF MACOS} GoogleServiceJSON = '../Resources/Startup/google-services.json'; {$ENDIF} procedure TfmxMain.FormCreate(Sender: TObject); begin fConfig := TFirebaseConfiguration.Create(GoogleServiceJSON); // Alternative with constants for ApiKey and ProjectID // fConfig := TFirebaseConfiguration.Create(ApiKey, ProjectID, '', FirebaseURL); fUID := ''; end; procedure TfmxMain.FormShow(Sender: TObject); begin Caption := Caption + ' [' + TFirebaseHelpers.GetConfigAndPlatform + ']'; TabControl.ActiveTab := tabAuth; FraSelfRegistration.Initialize(fConfig.Auth, OnUserLogin, LoadLastToken); end; procedure TfmxMain.FormClose(Sender: TObject; var Action: TCloseAction); begin SaveToken; end; function TfmxMain.GetSettingFilename: string; var FileName: string; begin FileName := ChangeFileExt(ExtractFileName(ParamStr(0)), ''); result := IncludeTrailingPathDelimiter( {$IFDEF IOS} TPath.GetDocumentsPath {$ELSE} TPath.GetHomePath {$ENDIF} ) + FileName + TFirebaseHelpers.GetPlatform + '.ini'; end; function TfmxMain.LoadLastToken: string; var IniFile: TIniFile; begin IniFile := TIniFile.Create(GetSettingFilename); try result := IniFile.ReadString('LastAccess', 'Token', ''); finally IniFile.Free; end; end; procedure TfmxMain.SaveToken; var IniFile: TIniFile; begin IniFile := TIniFile.Create(GetSettingFilename); try if fConfig.Auth.Authenticated then // Attention: Refreshtoken is stored in the inifile in plain text // Better would be to encrypt it with a secret key IniFile.WriteString('LastAccess', 'Token', fConfig.Auth.GetRefreshToken) else IniFile.DeleteKey('LastAccess', 'Token'); finally IniFile.Free; end; end; procedure TfmxMain.OnUserLogin(const Info: string; User: IFirebaseUser); begin fUID := User.UID; lblUserInfo.Text := Format(rsUserInfo, [User.EMail, fUID]); StartListening; end; procedure TfmxMain.btnSignOutClick(Sender: TObject); begin fConfig.Auth.SignOut; fUID := ''; WipeToTab(tabAuth); FraSelfRegistration.StartEMailEntering; end; procedure TfmxMain.WipeToTab(ActiveTab: TTabItem); var c: integer; begin if TabControl.ActiveTab <> ActiveTab then begin ActiveTab.Visible := true; {$IFDEF ANDROID} TabControl.ActiveTab := ActiveTab; {$ELSE} TabControl.GotoVisibleTab(ActiveTab.Index, TTabTransition.Slide, TTabTransitionDirection.Normal); {$ENDIF} for c := 0 to TabControl.TabCount - 1 do TabControl.Tabs[c].Visible := TabControl.Tabs[c] = ActiveTab; end; end; procedure TfmxMain.StartListening; begin WipeToTab(tabRTDBAccess); fEvent := fConfig.RealTimeDB.ListenForValueEvents(DBPath, OnDBEvent, OnDBStop, OnDBError, nil); lblStatus.Text := 'Firebase RT DB connected'; end; procedure TfmxMain.OnDBStop(Sender: TObject); begin Caption := 'DB Listener was stopped - restart App'; end; procedure TfmxMain.OnDBEvent(const Event: string; Params: TRequestResourceParam; JSONObj: TJSONObject); begin if Event = cEventPut then begin edtDBMessage.Text := JSONObj.GetValue<string>(cData); btnWrite.Enabled := false; lblStatus.Text := 'Last read: ' + DateTimeToStr(now); end; end; procedure TfmxMain.OnDBWritten(ResourceParams: TRequestResourceParam; Val: TJSONValue); begin lblStatus.Text := 'Last write: ' + DateTimeToStr(now); end; procedure TfmxMain.OnDBError(const RequestID, ErrMsg: string); begin if SameText(ErrMsg, 'Permission denied') or SameText(ErrMsg, 'Unauthorized') then lblStatus.Text := rsHintRTDBRules else lblStatus.Text := 'Error: ' + ErrMsg; end; procedure TfmxMain.btnWriteClick(Sender: TObject); var Data: TJSONValue; begin Data := TJSONString.Create(edtDBMessage.Text); try fConfig.RealTimeDB.Put(DBPath, Data, OnDBWritten, OnDBError); finally Data.Free; end; btnWrite.Enabled := false; end; procedure TfmxMain.edtDBMessageChangeTracking(Sender: TObject); begin btnWrite.Enabled := true; end; function TfmxMain.DBPath: TRequestResourceParam; begin Assert(not fUID.IsEmpty, 'UID missing'); result := ['UserMsg', fUID]; end; end.
unit VisualControls; interface uses Classes, Controls, Windows, SysUtils, Messages, ExtCtrls; //TVisualControl must be the ancestor of any form that pretending to use as a control, //setting IsControl property to true (Viewing a Form as Text). //See TControl.IsControl property in Delphi help. //It is necessary to declare PixelsInch and TextHeight variables because //Delphi's environment save these variables as they were Control's variables //instead of Form's variables. So it is necessary to declare these two variables //in order to load the correct Form(Control in this case) data from the .dfm file. //AlignedControl property specify the control that is aligned in the client area. //Assigning a value to AlignedControl align that control in the client area //according to the value of the ControlAligmnet property. Note that the control //specified AlignedControl property must be a child of the control. type TControlAlignment = (caBottom, caBottomCenter, caBottomLeft, caBottomRight, caCenter, caLeft, caLeftBottom, caLeftCenter, caLeftTop, caNone, caDefault, caRight, caRightBottom, caRightCenter, caRightTop, caTop, caTopCenter, caTopLeft, caTopRight ); TAligningControlEvent = procedure(Control : Tcontrol; Alignment : TControlAlignment) of object; type TVisualControl = class(TPanel) private procedure WMSize(var Message); message WM_SIZE; protected procedure Loaded; override; public constructor Create(aOwner : TComponent); override; destructor Destroy; override; published property Align default alClient; property DragCursor; property DragMode; property Enabled; property Caption; property ClientHeight; property ClientWidth; property Color; property Ctl3D; property Font; property ParentColor default true; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; private PPI : integer; TH : integer; published property PixelsPerInch : integer read PPI write PPI; property TextHeight : integer read TH write TH; private fDACPos : TRect; fControlAlignment : TControlAlignment; fAlignedControl : TControl; fOnAlgnCtrl : TAligningControlEvent; procedure AlignControl; procedure SetAlignedControl(value : TControl); procedure SetControlAlignment(value : TControlAlignment); function IsReallyShowing : boolean; public property AlignedControl : TControl read fAlignedControl write SetAlignedControl; property ControlAlignment : TControlAlignment read fControlAlignment write SetControlAlignment default caCenter; property OnAligningControl : TAligningControlEvent read fOnAlgnCtrl write fOnAlgnCtrl; property DefaultAlignedControlPosition : TRect read fDACPos; property ReallyShowing : boolean read IsReallyShowing; protected procedure SetParent(which : TWinControl); override; // >< end; type EVisualControlError = class (Exception); implementation uses Forms; { TVisualControl } constructor TVisualControl.Create(aOwner : TComponent); // >< begin inherited; //Align := alClient; fAlignedControl := nil; fControlAlignment := caCenter; end; destructor TVisualControl.Destroy; begin Destroying; RemoveFixupReferences(Self, ''); inherited; end; procedure TVisualControl.Loaded; begin inherited; { if not (csDesigning in ComponentState) then Name := ''; for i := 0 to pred(ComponentCount) do Components[i].Name := ''; } Caption := ''; ParentColor := true; BevelInner := bvNone; BevelOuter := bvNone; end; procedure TVisualControl.WMSize(var Message); begin inherited; //AlignControl; end; procedure TVisualControl.AlignControl; begin if (fAlignedControl <> nil) and (fAlignedControl.Align = alNone) then if Assigned(fOnAlgnCtrl) then fOnAlgnCtrl(fAlignedControl, fControlAlignment) else with fAlignedControl do case fControlAlignment of caBottom : begin Top := (Self.Height - Height); end; caBottomCenter : begin Left := (Self.Width div 2) - (Width div 2); Top := (Self.Height - Height); end; caBottomLeft, caLeftBottom : begin Left := 0; Top := (Self.Height - Height); end; caBottomRight, caRightBottom : begin Left := (Self.Width - Width); Top := (Self.Height - Height); end; caCenter : begin Left := (Self.Width div 2) - (Width div 2); Top := (Self.Height div 2) - (Height div 2); end; caLeft : begin Left := 0; end; caLeftCenter : begin Left := 0; Top := (Self.Height div 2) - (Height div 2); end; caLeftTop, caTopLeft : begin Left := 0; Top := 0; end; caDefault : begin Left := fDACPos.Left; Top := fDACPos.Top; end; caRight : begin Left := (Self.Width - Width); end; caRightCenter : begin Left := (Self.Width - Width); Top := (Self.Height div 2) - (Height div 2); end; caRightTop, caTopRight : begin Left := (Self.Width - Width); Top := 0; end; caTop : begin Top := 0; end; caTopCenter : begin Left := (Self.Width div 2) - (Width div 2); Top := 0; end; end; end; procedure TVisualControl.SetAlignedControl(value : TControl); begin fAlignedControl := value; if value <> nil then begin fDACPos := value.BoundsRect; AlignControl; end else fDACPos := Rect(0, 0, 0, 0); end; procedure TVisualControl.SetControlAlignment(value : TControlAlignment); begin fControlAlignment := value; AlignControl; end; function TVisualControl.IsReallyShowing : boolean; function OneIsHidden( Control : TControl ) : boolean; begin result := not Control.Visible or ((Control.Parent <> nil) and OneIsHidden( Control.Parent )); end; begin result := not OneIsHidden( self ); end; procedure TVisualControl.SetParent(which : TWinControl); // >< begin inherited; if Parent <> nil then InitInheritedComponent(Self, TCustomControl); end; end.
unit FastBitmap; {$mode objfpc}{$H+} interface uses Classes; type TFastBitmapPixel = integer; (*TFastBitmapPixel = record Blue: Byte; Green: Byte; Red: Byte; end;*) PFastBitmapPixel = ^TFastBitmapPixel; TFastBitmapPixelComponents = packed record B, G, R, A: byte; end; const FastPixelSize = SizeOf(TFastBitmapPixel); type { TFastBitmap } TFastBitmap = class private FPixelsData: PByte; FSize: TPoint; function GetPixel(X, Y: integer): TFastBitmapPixel; inline; procedure SetPixel(X, Y: integer; const AValue: TFastBitmapPixel); inline; procedure SetSize(const AValue: TPoint); public constructor Create; destructor Destroy; override; procedure RandomImage; property Size: TPoint read FSize write SetSize; property Pixels[X, Y: integer]: TFastBitmapPixel read GetPixel write SetPixel; property PixelsData: PByte read FPixelsData; end; function RGBA(red, green, blue, alpha: byte): integer; function SwapBRComponent(Value: integer): integer; inline; function NoSwapBRComponent(Value: integer): integer; inline; implementation function RGBA(red, green, blue, alpha: byte): integer; var tmp: TFastBitmapPixelComponents; begin tmp.R := red; tmp.G := green; tmp.B := blue; tmp.A := alpha; Result := TFastBitmapPixel(tmp); end; function SwapBRComponent(Value: integer): integer; begin // Result := (Value and $00ff00) or ((Value shr 16) and $ff) or ((Value and $ff) shl 16); Result := Value; TFastBitmapPixelComponents(Result).R := TFastBitmapPixelComponents(Value).B; TFastBitmapPixelComponents(Result).B := TFastBitmapPixelComponents(Value).R; end; function NoSwapBRComponent(Value: integer): integer; begin // Result := (Value and $00ff00) or ((Value shr 16) and $ff) or ((Value and $ff) shl 16); Result := Value; TFastBitmapPixelComponents(Result).B := TFastBitmapPixelComponents(Value).B; TFastBitmapPixelComponents(Result).R := TFastBitmapPixelComponents(Value).R; end; { TFastBitmap } function TFastBitmap.GetPixel(X, Y: integer): TFastBitmapPixel; begin Result := PFastBitmapPixel(FPixelsData + (Y * FSize.X + X) * FastPixelSize)^; end; procedure TFastBitmap.SetPixel(X, Y: integer; const AValue: TFastBitmapPixel); begin PFastBitmapPixel(FPixelsData + (Y * FSize.X + X) * FastPixelSize)^ := AValue; end; procedure TFastBitmap.SetSize(const AValue: TPoint); begin if (FSize.X = AValue.X) and (FSize.Y = AValue.X) then Exit; FSize := AValue; FPixelsData := ReAllocMem(FPixelsData, FSize.X * FSize.Y * FastPixelSize); end; constructor TFastBitmap.Create; begin Size := Point(0, 0); end; destructor TFastBitmap.Destroy; begin FreeMem(FPixelsData); inherited Destroy; end; procedure TFastBitmap.RandomImage; var I, X, Y: integer; begin for I := 0 to 2 do for Y := 0 to (Size.Y div 2) - 1 do for X := 0 to (Size.X div 3) - 1 do Pixels[X + (I * (Size.X div 3)), Y] := 255 shl (I * 8); for Y := (Size.Y div 2) to Size.Y - 1 do for X := 0 to Size.X - 1 do Pixels[X, Y] := Random(256) or (Random(256) shl 16) or (Random(256) shl 8); end; end.
unit usvcServidorSite; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.SvcMgr, System.Win.Registry, Horse, Horse.CORS, Horse.Jhonson, Horse.OctetStream, Horse.HandleException, Horse.Commons, Horse.Provider.Console, uLogArquivo, Firedac.Stan.Option, Firedac.Stan.Error, Firedac.UI.Intf, Firedac.Phys.Intf, Firedac.Stan.Def, Firedac.Stan.Pool, Firedac.Stan.Async, Firedac.Phys, Firedac.Stan.Param, Firedac.DatS, Firedac.DApt.Intf, Firedac.DApt, Firedac.Comp.DataSet, Firedac.Comp.Client, Firedac.Stan.Intf, Firedac.Stan.ExprFuncs, Firedac.Phys.SQLiteDef, Firedac.Phys.SQLite; type TsvcServidorSite = class(TService) procedure ServiceAfterInstall(Sender: TService); procedure ServiceExecute(Sender: TService); procedure ServiceStart(Sender: TService; var Started: Boolean); procedure ServiceStop(Sender: TService; var Stopped: Boolean); procedure ServiceCreate(Sender: TObject); procedure ServiceShutdown(Sender: TService); private { Private declarations } FDManager: TFDManager; public { Public declarations } function GetServiceController: TServiceController; override; end; var svcServidorSite: TsvcServidorSite; implementation {$R *.dfm} uses uRotas, Rotas.Bancos, uFuncoes; procedure ServiceController(CtrlCode: DWord); stdcall; begin svcServidorSite.Controller(CtrlCode); end; function TsvcServidorSite.GetServiceController: TServiceController; begin Result := ServiceController; end; procedure TsvcServidorSite.ServiceAfterInstall(Sender: TService); var regEdit: TRegistry; begin Log.Info('Gerando as informações de registro do serviço.'); regEdit := TRegistry.Create(KEY_READ or KEY_WRITE); try regEdit.RootKey := HKEY_LOCAL_MACHINE; if regEdit.OpenKey('\SYSTEM\CurrentControlSet\Services\' + Name, False) then begin regEdit.WriteString('Description', 'Serviço responsável pelo envio de dados.'); regEdit.CloseKey; end; finally FreeAndNil(regEdit); end; end; procedure TsvcServidorSite.ServiceCreate(Sender: TObject); var sAux: String; oDef: IFDStanConnectionDef; oPars: TFDPhysSQLiteConnectionDefParams; begin Log.Info('ServiceCreate'); FDManager := TFDManager.Create(nil); oDef := FDManager.ConnectionDefs.AddConnectionDef; oDef.Name := 'PRINCIPAL'; oPars := TFDPhysSQLiteConnectionDefParams(oDef.Params); oPars.DriverID := 'SQLite'; oPars.Database := LerIni('CONFIGURACAO', 'BANCODADOS'); oPars.Pooled := True; FDManager.Active := True; THorse.Use(CORS); THorse.Use(Jhonson); THorse.Use(OctetStream); THorse.Use(HandleException); THorse .Get('/ping', GetPing) .Get('/pdf', GetPDF) .Get('/bancos', Bancos_Get) .Get('/bancos/:id', Bancos_Get); end; procedure TsvcServidorSite.ServiceExecute(Sender: TService); var sAux: String; I: Integer; begin if IsConsole then Exit; Log.Info('Iniciando o serviço'); I := 0; try while not Terminated do begin { "Dorme" 1.5 segundos, para não sobrecarregar o processamento. Somente 1.5 seg para não dar problema caso queira parar o serviço } Sleep(1500); {$IFNDEF DEBUG} ServiceThread.ProcessRequests(False); Inc(I); {$ENDIF} end; finally Log.Info('Finalizando o serviço'); end; end; procedure TsvcServidorSite.ServiceShutdown(Sender: TService); begin Log.Info('ServiceShutdown'); end; procedure TsvcServidorSite.ServiceStart(Sender: TService; var Started: Boolean); begin FDManager.Active := True; THorse.Listen(9000, procedure(Horse: THorse) begin if IsConsole then Writeln(Format('Server is runing on %s:%d', [Horse.Host, Horse.Port])) else Log.Info(Format('Server is runing on %s:%d', [Horse.Host, Horse.Port])); end); end; procedure TsvcServidorSite.ServiceStop(Sender: TService; var Stopped: Boolean); begin Log.Info('Parando o serviço.'); THorse.StopListen; end; end.
unit UAccount; interface uses UAccountInfo, URawBytes; type TAccount = Record account: Cardinal; // FIXED value. Account number accountInfo : TAccountInfo; balance: UInt64; // Balance, always >= 0 updated_block: Cardinal; // Number of block where was updated n_operation: Cardinal; // count number of owner operations (when receive, this is not updated) name : TRawBytes; // Protocol 2. Unique name account_type : Word; // Protocol 2. Layer 2 use case previous_updated_block : Cardinal; // New Build 1.0.8 -> Only used to store this info to storage. It helps App to search when an account was updated. NOT USED FOR HASH CALCULATIONS! End; PAccount = ^TAccount; var CT_Account_NUL : TAccount; implementation initialization Initialize(CT_Account_NUL); end.
unit m3DBDocumentPart; {* Реализация части документа. } // Модуль: "w:\common\components\rtl\Garant\m3\m3DBDocumentPart.pas" // Стереотип: "SimpleClass" // Элемент модели: "Tm3DBDocumentPart" MUID: (4742DCFF02DC) {$Include w:\common\components\rtl\Garant\m3\m3Define.inc} interface uses l3IntfUses , m3BaseObject , m3DBInterfaces , l3Filer , m3PrimDB , ActiveX , m3StorageInterfaces ; type Tm3DBDocumentPart = class(Tm3BaseObject, Im3DBDocumentPart) {* Реализация части документа. } private f_Document: Im3DBDocument; f_Level: Integer; f_Filer: Tl3CustomFiler; protected function pm_GetDocument: Im3DBDocument; function pm_GetInfo: Tm3DBDocumentInfo; procedure pm_SetInfo(const aValue: Tm3DBDocumentInfo); function Open(aMode: Tm3StoreAccess = m3_saRead; aDocPart: Tm3DocPartSelector = m3_defDocPart; aIndex: Integer = 0): IStream; {* Открывает поток в документе. } function DateTime: TDateTime; procedure Cleanup; override; {* Функция очистки полей объекта. } procedure ClearFields; override; public constructor Create(aDB: Tm3PrimDB; const aDoc: Im3DBDocument; aLevel: Integer = 0; aFiler: Tl3CustomFiler = nil); reintroduce; class function Make(aDB: Tm3PrimDB; const aDoc: Im3DBDocument; aLevel: Integer = 0; aFiler: Tl3CustomFiler = nil): Im3DBDocumentPart; reintroduce; end;//Tm3DBDocumentPart implementation uses l3ImplUses , SysUtils , m3DB , m2MemLib , m3StorageTools , l3String , m3BackupTools , m3NewVersionStream , l3Base , m3DBProxyWriteStream , l3Types , m3Const , l3ForkStream , m3Exceptions , ComObj , m2COMLib , Windows , l3Date //#UC START# *4742DCFF02DCimpl_uses* //#UC END# *4742DCFF02DCimpl_uses* ; constructor Tm3DBDocumentPart.Create(aDB: Tm3PrimDB; const aDoc: Im3DBDocument; aLevel: Integer = 0; aFiler: Tl3CustomFiler = nil); //#UC START# *555B37CA01B6_4742DCFF02DC_var* //#UC END# *555B37CA01B6_4742DCFF02DC_var* begin //#UC START# *555B37CA01B6_4742DCFF02DC_impl* inherited Create(aDB); f_Level := aLevel; f_Document := aDoc; aFiler.SetRefTo(f_Filer); //#UC END# *555B37CA01B6_4742DCFF02DC_impl* end;//Tm3DBDocumentPart.Create class function Tm3DBDocumentPart.Make(aDB: Tm3PrimDB; const aDoc: Im3DBDocument; aLevel: Integer = 0; aFiler: Tl3CustomFiler = nil): Im3DBDocumentPart; var l_Inst : Tm3DBDocumentPart; begin l_Inst := Create(aDB, aDoc, aLevel, aFiler); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//Tm3DBDocumentPart.Make function Tm3DBDocumentPart.pm_GetDocument: Im3DBDocument; //#UC START# *4725D0FB008B_4742DCFF02DCget_var* //#UC END# *4725D0FB008B_4742DCFF02DCget_var* begin //#UC START# *4725D0FB008B_4742DCFF02DCget_impl* Result := f_Document; //#UC END# *4725D0FB008B_4742DCFF02DCget_impl* end;//Tm3DBDocumentPart.pm_GetDocument function Tm3DBDocumentPart.pm_GetInfo: Tm3DBDocumentInfo; //#UC START# *4725D11802BD_4742DCFF02DCget_var* var l_ID : Integer; l_Summ : IStream; l_Length : LongInt; l_ContentType : AnsiString; //#UC END# *4725D11802BD_4742DCFF02DCget_var* begin //#UC START# *4725D11802BD_4742DCFF02DCget_impl* Result := Tm3DBDocumentInfo_C(0); if (f_DB <> nil) then with f_DB do begin (* Start(m3_saRead);*) try l_ID := f_Document.ID; l_Summ := Open(m3_saRead, m3_dsInfo); // ^^^^ if (l_Summ = nil) and (f_Level <> Cm3ConstVersion) {not f_IsConst} then l_Summ := f_Document.GetConst.Open(m3_saRead, m3_dsInfo); // if (l_Summ <> nil) then begin if (l_Summ.Read(@l_Length, SizeOf(l_Length), nil) = S_False) then Exit; if (l_Length > 0) then begin SetLength(l_ContentType, l_Length); if (l_Summ.Read(@l_ContentType[1], l_Length, nil) = S_False) then begin SetLength(l_ContentType, 0); Exit; end;//l_Summ.Read.. end; l_Summ.Read(@Result.rIndexID, SizeOf(Result.rIndexID), nil); if l_Summ.Read(@Result.rRelID, SizeOf(Result.rRelID), nil) = S_False then Result.rRelID := 0; if l_Summ.Read(@Result.rRightsMask, SizeOf(Result.rRightsMask), nil) = S_False then Result.rRightsMask := 0; if l_Summ.Read(@Result.rLockedBy, SizeOf(Result.rLockedBy), nil) = S_False then Result.rLockedBy := 0; if l_Summ.Read(@Result.rDocType, SizeOf(Result.rDocType), nil) = S_False then Result.rDocType := 0; if l_Summ.Read(@Result.rExtDocID, SizeOf(Result.rExtDocID), nil) = S_False then Result.rExtDocID := 0; l_Summ := nil; end;//l_Summ <> nil finally (* Finish;*) end;//try..finally end;//with f_DB //#UC END# *4725D11802BD_4742DCFF02DCget_impl* end;//Tm3DBDocumentPart.pm_GetInfo procedure Tm3DBDocumentPart.pm_SetInfo(const aValue: Tm3DBDocumentInfo); //#UC START# *4725D11802BD_4742DCFF02DCset_var* var l_Info : Tm3DBDocumentInfo; l_Summ : IStream; l_Length : LongInt; l_ContentType : AnsiString; //#UC END# *4725D11802BD_4742DCFF02DCset_var* begin //#UC START# *4725D11802BD_4742DCFF02DCset_impl* if (f_DB <> nil) then with f_DB do begin if (f_Level = Cm3ConstVersion) then raise Exception.Create('pm_SetInfo to ConstPart') (* else Start(m3_saReadWrite)*); try l_Info := pm_GetInfo; if (m2MEMCompare(@l_Info, @aValue, SizeOf(l_Info)) <> 0) then begin l_Summ := Open(m3_saReadWrite, m3_dsInfo); if (l_Summ <> nil) then begin l_ContentType := ''; l_Length := Length(l_ContentType); l_Summ.Write(@l_Length, SizeOf(l_Length), nil); if (l_Length <> 0) then l_Summ.Write(@l_ContentType[1], l_Length, nil); l_Summ.Write(@aValue.rIndexID, SizeOf(aValue.rIndexID), nil); l_Summ.Write(@aValue.rRelID, SizeOf(aValue.rRelID), nil); l_Summ.Write(@aValue.rRightsMask, SizeOf(aValue.rRightsMask), nil); l_Summ.Write(@aValue.rLockedBy, SizeOf(aValue.rLockedBy), nil); l_Summ.Write(@aValue.rDocType, SizeOf(aValue.rDocType), nil); l_Summ.Write(@aValue.rExtDocID, SizeOf(aValue.rExtDocID), nil); l_Summ := nil; end;//l_Summ <> nil end;//pm_GetContentType <> aValue finally (* Finish;*) end;//try..finally end;//with f_DB //#UC END# *4725D11802BD_4742DCFF02DCset_impl* end;//Tm3DBDocumentPart.pm_SetInfo function Tm3DBDocumentPart.Open(aMode: Tm3StoreAccess = m3_saRead; aDocPart: Tm3DocPartSelector = m3_defDocPart; aIndex: Integer = 0): IStream; {* Открывает поток в документе. } //#UC START# *4725D13E031C_4742DCFF02DC_var* function OpenStream(anIndex : Tm3DBStreamIndex): IStream; var l_WasInProcess : Boolean; function GetVersionForWrite(var theBase: Im3IndexedStorage; aPart: Tm3DBPart): IStream; var l_DocStorage : Im3IndexedStorage; function CheckNotExist: Boolean; var l_S : IStream; begin//CheckNotExist l_S := m3COMOpenStream(l_DocStorage, l3PCharLen(m3_cDocPartName[anIndex.rPart]), m3_saRead, false); Result := (l_S = nil); end;//CheckNotExist var l_Storage : Im3IndexedStorage; l_ObjStorage : Im3IndexedStorage; l_Stream : IStream; l_Version : Integer; begin//GetVersionForWrite Result := nil; l_Storage := m3COMOpenStorage(theBase, anIndex.rID, m3_saReadWrite, true); if (l_Storage <> nil) then begin theBase := nil; if not l_WasInProcess then if not f_DB.IsExclusive then f_DB.CloseBase; end;//l_Storage <> nil try Assert(l_Storage <> nil); l_Storage.SetIndexParam(16, 16); l_Stream := m3COMOpenStream(l_Storage, 0, m3_saRead, false); try if (l_Stream = nil) OR (l_Stream.Read(@l_Version, SizeOf(l_Version), nil) = S_False) then l_Version := 0; finally l_Stream := nil; end;//try..finally except l_Version := 0; end;//try..except if (l_Version > 0) then // - пытаемся открыть поток в предыдущей версии begin l_DocStorage := m3COMOpenStorage(l_Storage, l_Version, m3_saReadWrite, false); if (l_DocStorage <> nil) then try l_DocStorage.SetIndexParam(16, 16); if (anIndex.rPart = m3_dsObject) then begin l_ObjStorage := m3COMOpenStorage(l_DocStorage, l3PCharLen(m3_cDocPartNameW[anIndex.rPart]), m3_saReadWrite, True); if (l_ObjStorage <> nil) then try Result := m3COMOpenStream(l_ObjStorage, anIndex.rIdx, m3_saRead, false); if (Result = nil) then // - не было такого потока Result := m3COMOpenStream(l_ObjStorage, // - создаем его anIndex.rIdx, m3_saReadWrite, true) else Result := nil; // - поток был - его перезаписывать не надо finally l_ObjStorage := nil; end;//try..finally end//aPartSelector = m3_dsObject else begin if not l_DocStorage.ElementExists(l3PCharLen(m3_cDocPartName[anIndex.rPart])) then (* Result := m3COMOpenStream(l_DocStorage, l3PCharLen(m3_cDocPartName[anIndex.rPart]), m3_saRead, false); if (Result = nil) then*) // - не было такого потока Result := m3COMOpenStream(l_DocStorage, l3PCharLen(m3_cDocPartNameW[anIndex.rPart]), m3_saReadWrite, true) // - создаем его else Result := nil; // - поток был - его перезаписывать не надо end;//aPartSelector = m3_dsObject finally l_DocStorage := nil; end;//try..finally end;//l_Version > 0 if (Result = nil) then // - не удалось открыть поток в предыдущей версии begin while true do begin Inc(l_Version); l_DocStorage := m3COMOpenStorage(l_Storage, l_Version, m3_saReadWrite, true); try if (l_DocStorage <> nil) then l_DocStorage.SetIndexParam(16, 16); if (anIndex.rPart = m3_dsObject) then begin l_ObjStorage := m3COMOpenStorage(l_DocStorage, l3PCharLen(m3_cDocPartNameW[anIndex.rPart]), m3_saReadWrite, True); try Result := m3COMOpenStream(l_ObjStorage, anIndex.rIdx, m3_saReadWrite, true); if f_DB.NeedProxy then Result := Tm3NewVersionStream.Make(Result, f_DB, Tm3DBStreamIndexEx_CV( anIndex, aPart, l_Version)); finally l_ObjStorage := nil; end;//try..finally end//aPartSelector = m3_dsObject else begin if not CheckNotExist then begin l3System.Msg2Log('Поток ' + m3_cDocPartName[anIndex.rPart] + ' уже существует в ' + IntToStr(anIndex.rID) + '.' + IntToStr(l_Version)); continue; end;//not CheckNotExist Result := m3COMOpenStream(l_DocStorage, l3PCharLen(m3_cDocPartNameW[anIndex.rPart]), m3_saReadWrite, true); if f_DB.NeedProxy then Result := Tm3NewVersionStream.Make(Result, f_DB, Tm3DBStreamIndexEx_CV( anIndex, aPart, l_Version)); end;//anIndex.rPart = m3_dsObject finally l_DocStorage := nil; end;//try..finally break; end;//while true end//Result = nil else // - удалось открыть поток в предыдущей версии if f_DB.NeedProxy then Result := Tm3DBProxyWriteStream.Make(Result, f_DB, Tm3DBStreamIndexEx_CV( anIndex, aPart, l_Version)); // - надо его завернуть end;//GetVersionForWrite function GetConstStream(const aBase: Im3IndexedStorage): IStream; var l_DocStorage : Im3IndexedStorage; l_ObjStorage : Im3IndexedStorage; begin m3COMSafeOpenStorage(aBase, anIndex.rID, aMode, aMode <> m3_saRead, l_DocStorage); try if (l_DocStorage <> nil) then if (anIndex.rPart = m3_dsObject) then begin m3COMSafeOpenStorage(l_DocStorage, l3PCharLen(m3_cDocPartName[anIndex.rPart]), aMode, aMode <> m3_saRead, l_ObjStorage); try if (l_ObjStorage <> nil) then m3COMSafeOpenStream(l_ObjStorage, anIndex.rIdx, aMode, aMode <> m3_saRead, Result); finally l_ObjStorage := nil; end; end else m3COMSafeOpenStream(l_DocStorage, l3PCharLen(m3_cDocPartName[anIndex.rPart]), aMode, aMode <> m3_saRead, Result); finally l_DocStorage := nil; end;//try..finally end;// procedure l_TuneFiler(aFiler: Tl3CustomFiler); begin//l_TuneFiler f_DB.TuneFiler(aFiler); if (aMode <> m3_saRead) then aFiler.Mode := l3_fmWrite; end;//l_TuneFiler var l_Filer : Tl3CustomFiler; l_Base : Im3IndexedStorage; function TryRestoreElement(const aDest: Im3IndexedStorage; //const aSource: Im3IndexedStorage; aPart: Tm3DBPart): IStream; var l_Name : WideString; l_Res : hResult; l_Base : Im3IndexedStorage; begin//TryRestoreElement Result := nil; if (aDest = nil) then Exit; l_Name := WideString(Format(m3IndexPrefixFormatStr, [anIndex.rID])); try //l_Res := aDest.DestroyElement(PWideChar(l_Name)); l_Res := aDest.DeleteStore(anIndex.rID); except on E: Exception do begin l3System.Msg2Log('Ошибка при удалении элемента #' + l_Name); l3System.Exception2Log(E); Exit; end;//on E: Exception end;//try..except if l3IOk(l_Res) then begin try l_Base := aDest; try Result := GetVersionForWrite(l_Base, aPart); finally l_Base := nil; end;//try..finally except Result := nil; end;//try..except end;//l3IOk(aDest.DestroyElement(PWideChar(l_Name))) end;//TryRestoreElement procedure MakeFork; var l_Fork : Tl3ForkStream; l_Bkp : Im3IndexedStorage; l_S1 : IStream; l_S2 : IStream; begin//MakeFork // делаем форк l_Fork := nil; try l_Bkp := f_DB.GetBackupStorage(aMode); try try l_S1 := GetVersionForWrite(l_Base, m3_bpVersion); except on Em3InvalidStreamSize do begin l3System.Msg2Log('Видимо битый файл sav'); l_S1 := TryRestoreElement(l_Base, m3_bpVersion); end;//on Em3InvalidStreamSize on Em3InvalidStoreData do begin l3System.Msg2Log('Видимо битый файл sav'); l_S1 := nil; end;//Em3InvalidStoreData end;//try..except if (l_Bkp = nil) then l_S2 := nil else begin try l_S2 := GetVersionForWrite(l_Bkp, m3_bpBackup); except on Em3InvalidStreamSize do begin l3System.Msg2Log('Видимо битый файл bkp'); l_S2 := TryRestoreElement(l_Bkp, m3_bpBackup); end;//on Em3InvalidStreamSize on Em3InvalidStoreData do begin l3System.Msg2Log('Видимо битый файл sav'); l_S2 := nil; end;//Em3InvalidStoreData end;//try..except end;//l_Bkp = nil if (l_S1 = nil) AND (l_S2 = nil) then raise Exception.Create('Некуда писать документ'); if (l_S1 = nil) then begin l_Filer.COMStream := l_S2; Exit; end;//l_S1 = nil if (l_S2 = nil) then begin l_Filer.COMStream := l_S1; Exit; end;//l_S2 = nil l_Fork := Tl3ForkStream.MakeI(l_S1, l_S2); l_S1 := nil; l_S2 := nil; finally l_Bkp := nil end;//try..finally l_Filer.Stream := l_Fork; finally FreeAndNil(l_Fork); end;//try..finally end;//MakeFork (* procedure CheckWasModified; var l_List : Tl3LongintList; l_Index : Integer; begin//CheckWasModified l_List := Tl3LongintList.MakeSorted; try f_DB.LoadList(cModified, l_List); if l_List.FindData(anIndex.rID, l_Index) then raise Exception.Create('Документ ' + IntToStr(anIndex.rID) + ' числится в списке модифицированных, однако не находится в переменной части'); finally FreeAndNil(l_List); end;//try..finally end;//CheckWasModified*) function m3GetDocumentForRead(const aBase: Im3IndexedStorage; aDocHandle: Integer): Im3IndexedStorage; begin try Result := m3COMOpenStorage(aBase, aDocHandle, m3_saRead, false); except on E: EOleSysError do begin if (E.ErrorCode = STG_E_LOCKVIOLATION) then raise else l3System.Exception2Log(E); end;//on EOleSysError on E: Exception do l3System.Exception2Log(E); end;//try..except end;//m3GetDocumentForRead function m3GetDocumentVersionForRead(const aDocument: Im3IndexedStorage; aNotEmpty: Boolean; aDocPart: Tm3DocPartSelector; aIndex: Integer; aLevel: Integer): IStream; var l_DocStorage : Im3IndexedStorage; l_ObjStorage : Im3IndexedStorage; l_Stream : IStream; l_Version : Integer; l_Max : Integer; begin Result := nil; try if (aDocument = nil) then Exit; l_Stream := m3COMOpenStream(aDocument, 0, m3_saRead, false); try if (l_Stream = nil) OR (l_Stream.Read(@l_Version, SizeOf(l_Version), nil) = S_False) then Exit; finally l_Stream := nil; end;//try..finally l_Max := l_Version; while true do begin l_Version := l_Max - aLevel; if (l_Version <= 0) then break; if (aDocPart = m3_defDocPart) then // - других потоков в старом не было l_Stream := m3COMOpenStream(aDocument, l_Version, m3_saRead, false) // - пытаемся открыть без потока main else l_Stream := nil; try if (l_Stream = nil) then // - не получилось - пытаемся открыть директорию для версии begin l_DocStorage := m3COMOpenStorage(aDocument, l_Version, m3_saRead, false); try if aDocPart = m3_dsObject then begin m3COMSafeOpenStorage(l_DocStorage, l3PCharLen(m3_cDocPartName[aDocPart]), m3_saRead, False, l_ObjStorage); try if (l_ObjStorage <> nil) then m3COMSafeOpenStream(l_ObjStorage, aIndex, m3_saRead, False, l_Stream); finally l_ObjStorage := nil; end; end else m3COMSafeOpenStream(l_DocStorage, l3PCharLen(m3_cDocPartName[aDocPart]), m3_saRead, false, l_Stream); finally l_DocStorage := nil; end;//try..finally end//l_Stream = nil else if (aDocPart <> m3_defDocPart) then l_Stream := nil; if (aDocPart = m3_dsInfo) AND (l_Stream = nil) then m3COMSafeOpenStream(aDocument, l3PCharLen(m3_cDocPartName[aDocPart]), m3_saRead, false, l_Stream); // - читаем информацию о документе из корневого каталога версии Result := l_Stream; if (Result <> nil) then begin if (not aNotEmpty OR (m2COMGetSize(Result) > 0)) then // - проверяем на то, что открылся непустой поток break else Result := nil; end;//Result <> nil finally l_Stream := nil; end;//try..finally Inc(aLevel); end;//while true except on E: EOleSysError do begin if (E.ErrorCode = STG_E_LOCKVIOLATION) then raise else l3System.Exception2Log(E); end;//on EOleSysError on E: Exception do l3System.Exception2Log(E); end;//try..except end;//m3GetDocumentVersionForRead var l_TryCount : Integer; l_Doc : Im3IndexedStorage; begin//OpenStream l_WasInProcess := true; // - инициализируем более безобидным значением l_TryCount := 0; while (l_TryCount < m3_cMaxTry) do begin Inc(l_TryCount); Result := nil; try l_Filer := Tl3CustomFiler.Create; try l_Filer.Handle := anIndex.rID; l_TuneFiler(l_Filer); l_WasInProcess := f_DB.InProcess; if (f_Level = Cm3ConstVersion) then f_DB.StartEx(m3_saRead, aMode) else f_DB.StartEx(aMode, m3_saRead); try if (f_Level = Cm3ConstVersion) then begin l_Base := f_DB.MainStorage(aMode); try if (aMode = m3_saRead) OR not f_DB.NeedProxy then l_Filer.COMStream := GetConstStream(l_Base) else l_Filer.COMStream := Tm3DBProxyWriteStream.Make( GetConstStream(l_Base), f_DB, Tm3DBStreamIndexEx_C( anIndex, m3_bpConst)); finally l_Base := nil; end;//try..finally end//f_IsConst else begin l_Base := f_DB.GetVersionsStorage(aMode); try if (aMode = m3_saRead) then begin l_Doc := m3GetDocumentForRead(l_Base, anIndex.rID); try l_Base := nil; if not l_WasInProcess then if not f_DB.IsExclusive then f_DB.CloseBase; l_Filer.COMStream := m3GetDocumentVersionForRead(l_Doc, False, anIndex.rPart, anIndex.rIdx, f_Level); finally l_Doc := nil; end;//try..finally (* l_Filer.COMStream := m3GetVersionForRead(l_Base, anIndex.rID, False, anIndex.rPart, anIndex.rIdx, f_Level);*) (* if (l_Filer.COMStream = nil) then begin if (l_Base <> nil) then begin l_Base := nil; l_Base := f_DB.GetBackupStorage(m3_saReadWrite{aMode}); l_Filer.COMStream := m3GetVersionForRead(l_Base, anIndex.rID, False, anIndex.rPart, anIndex.rIdx, f_Level); // if (l_Filer.COMStream = nil) then // CheckWasModified; end;//l_Base <> nil end;//l_Filer.COMStream = nil*) end//aMode = m3_saRead else begin if f_DB.NeedsFork then MakeFork else l_Filer.COMStream := GetVersionForWrite(l_Base, m3_bpVersion); end;//aMode = m3_saRead finally l_Base := nil; end;//try..finally if (l_Filer.COMStream = nil) then Exit; end;//f_IsConst Supports(l_Filer, IStream, Result); finally f_DB.Finish; end;//try..finally finally FreeAndNil(l_Filer); end;//try..finally except on E: EOleSysError do begin if (E.ErrorCode = STG_E_LOCKVIOLATION) then begin f_DB.CloseBase; // - стараемся отпустить всё по-максимуму if (l_TryCount >= m3_cMaxTry) then raise else begin l3System.Msg2Log('Номер попытки залочки: ' + IntToStr(l_TryCount)); Sleep(Random(m3_cMaxSleep)); continue; end;//l_TryCount >= m3_cMaxTry end//E.ErrorCode = STG_E_LOCKVIOLATION else begin l3System.Exception2Log(E); raise; end;//else end;//on E: EOleSysError on E: Exception do begin l3System.Exception2Log(E); raise; end;//on E: Exception end;//try..excepy break; end;//while (l_TryCount < m3_cMaxTry) end;//OpenStream //#UC END# *4725D13E031C_4742DCFF02DC_var* begin //#UC START# *4725D13E031C_4742DCFF02DC_impl* Result := nil; if (f_Filer <> nil) then Supports(f_Filer, IStream, Result) else if (f_DB <> nil) then begin if (aMode <> m3_saRead) then if (aDocPart = m3_dsObject) then begin if (aIndex < 0) then aIndex := f_Document.GetFreeObjectID; Assert(aIndex >= 0, 'Отрицательных объектов не бывает'); end;//aDocPart = m3_dsObject Result := OpenStream(Tm3DBStreamIndex_C(f_Document.ID, aDocPart, aIndex)); end;//f_DB <> nil //#UC END# *4725D13E031C_4742DCFF02DC_impl* end;//Tm3DBDocumentPart.Open function Tm3DBDocumentPart.DateTime: TDateTime; //#UC START# *555CAF230331_4742DCFF02DC_var* var l_Storage : Im3IndexedStorage; l_Stream : IStream; l_Version : Integer; //#UC END# *555CAF230331_4742DCFF02DC_var* begin //#UC START# *555CAF230331_4742DCFF02DC_impl* Result := BadDateTime; if (f_Level = Cm3ConstVersion) then Exit; try l_Storage := f_DB.GetVersionsStorage(m3_saRead); try l_Storage := m3COMOpenStorage(l_Storage, f_Document.ID, m3_saRead, false); if (l_Storage = nil) then Exit; l_Stream := m3COMOpenStream(l_Storage, 0, m3_saRead, false); try if (l_Stream.Read(@l_Version, SizeOf(l_Version), nil) = S_False) then Exit; Dec(l_Version, f_Level); Dec(l_Version); if (l_Version < 0) then Exit; m2COMSeek(l_Stream, l_Version * SizeOf(Result)); if (l_Stream.Read(@Result, SizeOf(Result), nil) = S_False) then Result := BadDateTime; finally l_Stream := nil; end;//try..finally finally l_Storage := nil; end;//try..finally except on E: Exception do l3System.Exception2Log(E); end;//try..except //#UC END# *555CAF230331_4742DCFF02DC_impl* end;//Tm3DBDocumentPart.DateTime procedure Tm3DBDocumentPart.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_4742DCFF02DC_var* //#UC END# *479731C50290_4742DCFF02DC_var* begin //#UC START# *479731C50290_4742DCFF02DC_impl* FreeAndNil(f_Filer); f_Document := nil; inherited; //#UC END# *479731C50290_4742DCFF02DC_impl* end;//Tm3DBDocumentPart.Cleanup procedure Tm3DBDocumentPart.ClearFields; begin f_Document := nil; inherited; end;//Tm3DBDocumentPart.ClearFields end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpDerApplicationSpecific; {$I ..\Include\CryptoLib.inc} interface uses Classes, SysUtils, ClpCryptoLibTypes, ClpArrayUtils, ClpAsn1TaggedObject, ClpAsn1Tags, ClpDerOutputStream, ClpIProxiedInterface, ClpIDerApplicationSpecific, ClpIAsn1EncodableVector, ClpAsn1Object; resourcestring SMalformedObject = 'Malformed Object %s'; SUnSupportedTag = 'Unsupported Tag Number'; SInvalidDerLength = 'DER Length More Than 4 Bytes: %d'; SCorruptedStream = 'Corrupted Stream - Invalid High Tag Number Found'; type /// <summary> /// Base class for an application specific object /// </summary> TDerApplicationSpecific = class(TAsn1Object, IDerApplicationSpecific) strict private var FisConstructed: Boolean; Ftag: Int32; Foctets: TCryptoLibByteArray; function GetApplicationTag: Int32; inline; function GetLengthOfHeader(const data: TCryptoLibByteArray): Int32; inline; class function ReplaceTagNumber(newTag: Int32; const input: TCryptoLibByteArray): TCryptoLibByteArray; static; strict protected function Asn1Equals(const asn1Object: IAsn1Object): Boolean; override; function Asn1GetHashCode(): Int32; override; public constructor Create(isConstructed: Boolean; tag: Int32; const octets: TCryptoLibByteArray); overload; constructor Create(tag: Int32; const octets: TCryptoLibByteArray); overload; constructor Create(tag: Int32; const obj: IAsn1Encodable); overload; constructor Create(isExplicit: Boolean; tag: Int32; const obj: IAsn1Encodable); overload; constructor Create(tagNo: Int32; const vec: IAsn1EncodableVector); overload; function isConstructed(): Boolean; inline; function GetContents(): TCryptoLibByteArray; inline; /// <summary> /// Return the enclosed object assuming explicit tagging. /// </summary> /// <returns> /// the resulting object /// </returns> /// <exception cref="ClpCryptoLibTypes|EIOCryptoLibException"> /// if reconstruction fails. /// </exception> function GetObject(): IAsn1Object; overload; inline; /// <summary> /// Return the enclosed object assuming implicit tagging. /// </summary> /// <param name="derTagNo"> /// the type tag that should be applied to the object's contents. /// </param> /// <returns> /// the resulting object /// </returns> /// <exception cref="ClpCryptoLibTypes|EIOCryptoLibException"> /// if reconstruction fails. /// </exception> function GetObject(derTagNo: Int32): IAsn1Object; overload; inline; procedure Encode(const derOut: TStream); override; property ApplicationTag: Int32 read GetApplicationTag; end; implementation { TDerApplicationSpecific } function TDerApplicationSpecific.GetApplicationTag: Int32; begin result := Ftag; end; function TDerApplicationSpecific.GetContents: TCryptoLibByteArray; begin result := Foctets; end; function TDerApplicationSpecific.isConstructed: Boolean; begin result := FisConstructed; end; function TDerApplicationSpecific.GetLengthOfHeader (const data: TCryptoLibByteArray): Int32; var &length, Size: Int32; begin Length := data[1]; // TODO: assumes 1 byte tag if (Length = $80) then begin result := 2; // indefinite-length encoding Exit; end; if (Length > 127) then begin Size := Length and $7F; // Note: The invalid long form "0xff" (see X.690 8.1.3.5c) will be caught here if (Size > 4) then begin raise EInvalidOperationCryptoLibException.CreateResFmt (@SInvalidDerLength, [Size]); end; result := Size + 2; Exit; end; result := 2; end; constructor TDerApplicationSpecific.Create(tag: Int32; const obj: IAsn1Encodable); begin Create(true, tag, obj); end; constructor TDerApplicationSpecific.Create(tag: Int32; const octets: TCryptoLibByteArray); begin Create(false, tag, octets); end; constructor TDerApplicationSpecific.Create(isConstructed: Boolean; tag: Int32; const octets: TCryptoLibByteArray); begin Inherited Create(); FisConstructed := isConstructed; Ftag := tag; Foctets := octets; end; function TDerApplicationSpecific.Asn1Equals(const asn1Object : IAsn1Object): Boolean; var other: IDerApplicationSpecific; begin if (not Supports(asn1Object, IDerApplicationSpecific, other)) then begin result := false; Exit; end; result := (isConstructed = other.isConstructed) and (ApplicationTag = other.ApplicationTag) and TArrayUtils.AreEqual(GetContents, other.GetContents); end; function TDerApplicationSpecific.Asn1GetHashCode: Int32; var HashCode: Int32; begin case isConstructed of true: HashCode := 1; false: HashCode := 0; end; result := HashCode xor Ftag xor TArrayUtils.GetArrayHashCode(Foctets); end; constructor TDerApplicationSpecific.Create(tagNo: Int32; const vec: IAsn1EncodableVector); var bOut: TMemoryStream; bs: TCryptoLibByteArray; i: Int32; val: IAsn1Encodable; begin Inherited Create(); Ftag := tagNo; FisConstructed := true; bOut := TMemoryStream.Create(); try i := 0; while i <> vec.Count do begin try val := vec[i]; bs := val.GetDerEncoded(); bOut.Write(bs[0], System.Length(bs)); except on e: EIOCryptoLibException do begin raise EInvalidOperationCryptoLibException.CreateResFmt (@SMalformedObject, [e.Message]); end; end; System.Inc(i); end; System.SetLength(Foctets, bOut.Size); bOut.Position := 0; bOut.Read(Foctets[0], bOut.Size); finally bOut.Free; end; end; procedure TDerApplicationSpecific.Encode(const derOut: TStream); var classBits: Int32; begin classBits := TAsn1Tags.Application; if (isConstructed) then begin classBits := classBits or TAsn1Tags.Constructed; end; (derOut as TDerOutputStream).WriteEncoded(classBits, Ftag, Foctets); end; constructor TDerApplicationSpecific.Create(isExplicit: Boolean; tag: Int32; const obj: IAsn1Encodable); var asn1Obj: IAsn1Object; data, tmp: TCryptoLibByteArray; lenBytes: Int32; begin Inherited Create(); asn1Obj := obj.ToAsn1Object(); data := asn1Obj.GetDerEncoded(); FisConstructed := TAsn1TaggedObject.isConstructed(isExplicit, asn1Obj); Ftag := tag; if (isExplicit) then begin Foctets := data; end else begin lenBytes := GetLengthOfHeader(data); System.SetLength(tmp, System.Length(data) - lenBytes); System.Move(data[lenBytes], tmp[0], System.Length(tmp) * System.SizeOf(Byte)); Foctets := tmp; end; end; function TDerApplicationSpecific.GetObject: IAsn1Object; begin result := FromByteArray(GetContents()); end; function TDerApplicationSpecific.GetObject(derTagNo: Int32): IAsn1Object; var orig, tmp: TCryptoLibByteArray; begin if (derTagNo >= $1F) then begin raise EIOCryptoLibException.CreateRes(@SUnSupportedTag); end; orig := GetEncoded(); tmp := ReplaceTagNumber(derTagNo, orig); if ((orig[0] and TAsn1Tags.Constructed) <> 0) then begin tmp[0] := tmp[0] or TAsn1Tags.Constructed; end; result := FromByteArray(tmp); end; class function TDerApplicationSpecific.ReplaceTagNumber(newTag: Int32; const input: TCryptoLibByteArray): TCryptoLibByteArray; var tagNo, index, b, remaining: Int32; tmp: TCryptoLibByteArray; begin tagNo := input[0] and $1F; index := 1; // // with tagged object tag number is bottom 5 bits, or stored at the start of the content // if (tagNo = $1F) then begin b := input[index]; System.Inc(index); // X.690-0207 8.1.2.4.2 // "c) bits 7 to 1 of the first subsequent octet shall not all be zero." if ((b and $7F) = 0) then // Note: -1 will pass begin raise EIOCryptoLibException.CreateRes(@SCorruptedStream); end; while ((b and $80) <> 0) do begin b := input[index]; System.Inc(index); end; end; remaining := System.Length(input) - index; System.SetLength(tmp, 1 + remaining); tmp[0] := Byte(newTag); System.Move(input[index], tmp[1], remaining * System.SizeOf(Byte)); result := tmp; end; end.
unit kinveyDataModule; interface uses System.SysUtils, System.Classes, IPPeerClient, REST.OpenSSL, REST.Backend.ServiceTypes, REST.Backend.MetaTypes, System.JSON, REST.Backend.KinveyServices, REST.Backend.Providers, REST.Backend.ServiceComponents, REST.Backend.KinveyProvider; type TDataModule1 = class(TDataModule) KinveyProvider1: TKinveyProvider; BackendUsers1: TBackendUsers; private { Private declarations } public { Public declarations } procedure SignUp(const AUsername, APassword, AFullname, AEmail: string); end; var DataModule1: TDataModule1; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} { TDataModule1 } procedure TDataModule1.SignUp(const AUsername, APassword, AFullname, AEmail: string); var UserData: TJSONObject; CreatedObject: TBackendEntityValue; begin UserData := TJSONObject.Create; try UserData.AddPair('fullname', AFullname); UserData.AddPair('email', AEmail); BackendUsers1.Users.SignupUser(AUsername, APassword, UserData, CreatedObject); finally UserData.Free; end; end; end.
unit RSPageControl; { *********************************************************************** } { } { RSPak Copyright (c) Rozhenko Sergey } { http://sites.google.com/site/sergroj/ } { sergroj@mail.ru } { } { This file is a subject to any one of these licenses at your choice: } { BSD License, MIT License, Apache License, Mozilla Public License. } { } { *********************************************************************** ) Now controls get WM_KILLFOCUS and WM_SETFOCUS messages when swiching between pages. This is another way to fix the bug described in RSComboBox unit. { *********************************************************************** } {$I RSPak.inc} interface uses Forms, Windows, Messages, SysUtils, Classes, Controls, ComCtrls, RSCommon, RSQ; {$I RSWinControlImport.inc} type TRSPageControl = class(TPageControl) private FOnCreateParams: TRSCreateParamsEvent; FProps: TRSWinControlProps; FRuntimeTabIndex: integer; function GetTab(index: integer): TTabSheet; protected procedure CreateParams(var Params:TCreateParams); override; procedure Loaded; override; procedure Change; override; procedure TranslateWndProc(var Msg:TMessage); procedure WndProc(var Msg:TMessage); override; public constructor Create(AOwner:TComponent); override; // Includes only visible sheets: property Tabs[index: integer]: TTabSheet read GetTab; published property RuntimeTabIndex: integer read FRuntimeTabIndex write FRuntimeTabIndex default -1; property OnCanResize; property OnDblClick; property OnResize; {$I RSWinControlProps.inc} end; procedure register; implementation procedure register; begin RegisterComponents('RSPak', [TRSPageControl]); end; { ******************************** TRSPageControl ******************************** } constructor TRSPageControl.Create(AOwner:TComponent); begin inherited Create(AOwner); WindowProc:=TranslateWndProc; FRuntimeTabIndex:=-1; end; procedure TRSPageControl.CreateParams(var Params:TCreateParams); begin inherited CreateParams(Params); if Assigned(FOnCreateParams) then FOnCreateParams(Params); end; function TRSPageControl.GetTab(index: integer): TTabSheet; begin result:= TTabSheet(inherited Tabs.Objects[index]); end; procedure TRSPageControl.Loaded; begin inherited Loaded; if not (csDesigning in ComponentState) and (FRuntimeTabIndex>=0) and (FRuntimeTabIndex<PageCount) then TabIndex:=FRuntimeTabIndex; end; procedure TRSPageControl.Change; var Form: TCustomForm; h, h1:Hwnd; begin inherited; Form:= GetParentForm(Self); h:= GetFocus; if Form.ActiveControl<>nil then h1:= Form.ActiveControl.Handle else h1:= 0; // This will update Form.ActiveControl and do other stuff if h1 <> h then begin SendMessage(h1, WM_KILLFOCUS, h, 0); SendMessage(h, WM_SETFOCUS, h1, 0); end; end; procedure TRSPageControl.TranslateWndProc(var Msg:TMessage); var b: boolean; begin if assigned(FProps.OnWndProc) then begin b:=false; FProps.OnWndProc(Self, Msg, b, WndProc); if b then exit; end; WndProc(Msg); end; procedure TRSPageControl.WndProc(var Msg:TMessage); begin RSProcessProps(self, Msg, FProps); inherited; end; end.
unit furqExprEval; interface uses Variants, furqTypes, furqContext, JclStringLists; type TfurqToken = ( // сущности языка etIdentifier, etNumber, etString, // действия (арифметические и логические) etPlus, etMinus, etDivide, etMultiply, etAnd, etOr, etNot, // операции сравнения etEqual, etNotEqual, etLesser, etLesserOrEqual, etGreater, etGreaterOrEqual, etSimular, // структурные токены etIF, etThen, etElse, // служебные etLBrasket, etRBrasket, etAmpersand, etComma, etSymbol, etEOF, // особый пользовательский токен etCustom ); TfurqLexer = class(TObject) private f_AllowSpacesInIdent: Boolean; f_DetectStrings: Boolean; f_Pos: Integer; f_Source: string; f_Token: TfurqToken; f_TokenEnd: Integer; f_TokenStart: Integer; f_TokenValue: Variant; function pm_GetCurChar: Char; procedure pm_SetSource(const Value: string); protected property CurChar: Char read pm_GetCurChar; public constructor Create; procedure NextToken(aCustomCharset: TCharSet = []); procedure Reset; procedure SetSourceCustom(const aSource: string; aCustomCharset: TCharset); property AllowSpacesInIdent: Boolean read f_AllowSpacesInIdent write f_AllowSpacesInIdent; property DetectStrings: Boolean read f_DetectStrings write f_DetectStrings; property Source: string read f_Source write pm_SetSource; property Token: TfurqToken read f_Token; property TokenEnd: Integer read f_TokenEnd; property TokenStart: Integer read f_TokenStart; property TokenValue: Variant read f_TokenValue; end; IfurqEvalNode = interface(IInterface) ['{CA576088-5564-4C13-9333-578C10741583}'] function Evaluate: Variant; end; TfurqEvalNode = class(TInterfacedObject, IfurqEvalNode) public function Evaluate: Variant; virtual; abstract; end; TfurqUnaryEvalNode = class(TfurqEvalNode) protected f_Value: IfurqEvalNode; public constructor Create(aValue: IfurqEvalNode); destructor Destroy; override; end; TfurqBinaryEvalNode = class(TfurqEvalNode) protected f_First: IfurqEvalNode; f_Second: IfurqEvalNode; public constructor Create(aFirst, aSecond: IfurqEvalNode); destructor Destroy; override; end; TfurqConstEvalNode = class(TfurqEvalNode) private f_Value: Variant; public constructor Create(const aValue: Variant); function Evaluate: Variant; override; end; TfurqNegateEvalNode = class(TfurqUnaryEvalNode) public function Evaluate: Variant; override; end; TfurqNotEvalNode = class(TfurqUnaryEvalNode) public function Evaluate: Variant; override; end; TfurqSummaEvalNode = class(TfurqBinaryEvalNode) public function Evaluate: Variant; override; end; TfurqSubtractEvalNode = class(TfurqBinaryEvalNode) public function Evaluate: Variant; override; end; TfurqMultiplyEvalNode = class(TfurqBinaryEvalNode) public function Evaluate: Variant; override; end; TfurqDivideEvalNode = class(TfurqBinaryEvalNode) public function Evaluate: Variant; override; end; TfurqOrEvalNode = class(TfurqBinaryEvalNode) public function Evaluate: Variant; override; end; TfurqAndEvalNode = class(TfurqBinaryEvalNode) public function Evaluate: Variant; override; end; TfurqExprEvaluator = class(TObject) private f_Context: TfurqContext; f_Expression: IfurqEvalNode; f_Lexer: TfurqLexer; function CompileFactor: TfurqEvalNode; function CompileLevel0(const aSkip: Boolean): TfurqEvalNode; function CompileLevel1(const aSkip: Boolean): TfurqEvalNode; function CompileLevel2(const aSkip: Boolean): TfurqEvalNode; function CompileLevel3(const aSkip: Boolean): TfurqEvalNode; function CompileLevel4(const aSkip: Boolean): TfurqEvalNode; function CompileLevel5(const aSkip: Boolean): TfurqEvalNode; procedure CompileSource; function GetIdentifierValue(aIdentName: string): Variant; function GetInventoryAmount(aName: string; anAmount: Extended): Extended; function pm_GetResultValue: Variant; function pm_GetSource: string; procedure pm_SetSource(const Value: string); public constructor Create(aContext: TFURQContext); destructor Destroy; override; property ResultValue: Variant read pm_GetResultValue; property Source: string read pm_GetSource write pm_SetSource; end; TfurqEqualEvalNode = class(TfurqBinaryEvalNode) public function Evaluate: Variant; override; end; TfurqLesserEvalNode = class(TfurqBinaryEvalNode) public function Evaluate: Variant; override; end; TfurqLesserOrEqualEvalNode = class(TfurqBinaryEvalNode) public function Evaluate: Variant; override; end; TfurqGreaterEvalNode = class(TfurqBinaryEvalNode) public function Evaluate: Variant; override; end; TfurqGreaterOrEqualEvalNode = class(TfurqBinaryEvalNode) public function Evaluate: Variant; override; end; TfurqNotEqualEvalNode = class(TfurqBinaryEvalNode) public function Evaluate: Variant; override; end; EFURQExpressionError = class(EFURQRunTimeError); TfurqSimularEvalNode = class(TfurqBinaryEvalNode) public function Evaluate: Variant; override; end; type TEvalSet = set of Byte; function ParseAndEvalToArray(const aContext: TFURQContext; const aSource: string; aToEval: TEvalSet): IJclStringList; implementation uses Windows, SysUtils, StrUtils, JclStrings ; type TKeywordRec = record rWord: string; rToken: TfurqToken; end; const ki_And = 1; ki_Or = 2; ki_Not = 3; ki_IF = 4; ki_THEN = 5; ki_ELSE = 6; cMaxKeywordIdx = ki_ELSE; cKeywordArray: array [ki_And..cMaxKeywordIdx] of TKeywordRec = ( (rWord: 'and'; rToken: etAnd), (rWord: 'or'; rToken: etOr), (rWord: 'not'; rToken: etNot), (rWord: 'if'; rToken: etIF), (rWord: 'then'; rToken: etThen), (rWord: 'else'; rToken: etElse) ); const sOpenParenthis = 'незакрытая скобка'; sFactorNeeded = 'ожидается константа или переменная'; sSyntaxError = 'неверный ситаксис'; const cWhitespaces = [#1..#32]; cMaxIdentifierLen = 1024; // Функция поднятия ошибки procedure RaiseExprError(const aTxt: string); begin raise EFURQExpressionError.CreateFmt('Ошибка в выражении: %s', [aTxt]); end; function ParseAndEvalToArray(const aContext: TFURQContext; const aSource: string; aToEval: TEvalSet): IJclStringList; var l_Lex: TfurqLexer; l_Eval: TfurqExprEvaluator; l_StartPos: Integer; l_ParamNo: Byte; procedure GetNextParam; var l_Idx: Integer; l_Param: string; begin l_Param := Trim(Copy(aSource, l_StartPos, l_Lex.TokenStart - l_StartPos)); l_Idx := Result.Add(l_Param); if (l_Param <> '') and (l_ParamNo in aToEval) then begin try l_Eval.Source := l_Param; Result.Variants[l_Idx] := l_Eval.ResultValue; except Result.Variants[l_Idx] := Null; end; end; l_StartPos := l_Lex.TokenEnd; Inc(l_ParamNo); end; begin Result := JclStringList; l_ParamNo := 1; l_Eval := TfurqExprEvaluator.Create(aContext); try l_Lex := TfurqLexer.Create; try l_Lex.Source := aSource; l_StartPos := 1; while True do begin case l_Lex.Token of etComma: GetNextParam; etEOF : begin GetNextParam; Break; end; end; l_Lex.NextToken; end; finally FreeAndNil(l_Lex); end; finally FreeAndNil(l_Eval); end; end; constructor TfurqLexer.Create; begin inherited; f_DetectStrings := True; f_AllowSpacesInIdent := True; end; procedure TfurqLexer.NextToken(aCustomCharset: TCharSet = []); var l_SSPos : Integer; l_SubStr: string; procedure LoadFromSet(aSet: TCharSet); begin while (CurChar in aSet) do begin Inc(l_SSPos); l_SubStr[l_SSPos] := CurChar; Inc(f_Pos); if (l_SSPos = cMaxIdentifierLen) then Break; end; end; function IsKeyword(const aStr: string): Boolean; var I: Integer; l_Str: string; begin Result := False; l_Str := LowerCase(aStr); for I := 1 to cMaxKeywordIdx do if l_Str = cKeywordArray[I].rWord then begin Result := True; Exit; end; end; procedure LoadIdent; // идентификаторы могут содержать пробелы и не должны путаться с ключевыми словами var l_LastIdStartPos: Integer; l_NextIdent: string; l_AdditionalPart: string; begin LoadFromSet(cIdentMidSet); SetLength(l_SubStr, l_SSPos); if IsKeyword(l_SubStr) then Exit; l_AdditionalPart := ''; try while True do begin if (CurChar = ' ') and f_AllowSpacesInIdent then begin l_LastIdStartPos := f_Pos; while CurChar = ' ' do begin l_AdditionalPart := l_AdditionalPart + CurChar; Inc(f_Pos); end; if CurChar in cIdentStartSet then begin l_NextIdent := CurChar; Inc(f_Pos); while CurChar in cIdentMidSet do begin l_NextIdent := l_NextIdent + CurChar; Inc(f_Pos); end; if IsKeyword(l_NextIdent) then begin f_Pos := l_LastIdStartPos; Exit; end; l_AdditionalPart := l_AdditionalPart + l_NextIdent; end; end else Break; end; finally if l_AdditionalPart <> '' then l_SubStr := Trim(l_SubStr + l_AdditionalPart); end; end; procedure SetToken(aToken: TfurqToken); begin f_TokenStart := f_Pos; f_Token := aToken; Inc(f_Pos); f_TokenEnd := f_Pos; end; procedure SetTokenEnd(aToken: TfurqToken); begin f_Token := aToken; Inc(f_Pos); f_TokenEnd := f_Pos; end; procedure GetRegularToken; var I : Integer; l_Value: Longword; l_SubStrLow: string; l_QuoteChar: Char; begin f_Token := etSymbol; f_TokenValue := Unassigned; case CurChar of #0: begin f_Token := etEOF; f_TokenStart := f_Pos; f_TokenEnd := f_Pos; f_TokenValue := Unassigned; end; 'a'..'z','A'..'Z','А'..'Я','а'..'я','_', 'Ё', 'ё': begin f_TokenStart := f_Pos; SetLength(l_SubStr, cMaxIdentifierLen); l_SubStr[1] := CurChar; l_SSPos := 1; Inc(f_Pos); LoadIdent; l_SubStrLow := LowerCase(l_SubStr); for I := 1 to cMaxKeywordIdx do if l_SubStrLow = cKeywordArray[I].rWord then begin f_Token := cKeywordArray[I].rToken; Break; end; if f_Token = etSymbol then begin f_Token := etIdentifier; f_TokenValue := l_SubStr; end; f_TokenEnd := f_Pos; end; '0'..'9': begin f_TokenStart := f_Pos; SetLength(l_SubStr, cMaxIdentifierLen); l_SubStr[1] := CurChar; l_SSPos := 1; Inc(f_Pos); LoadFromSet(['0'..'9']); if (UpCase(CurChar) = 'X') and (l_SSPos = 1) and (l_SubStr[1] = '0') then // это hex-значение begin l_SSPos := 0; Inc(f_Pos); LoadFromSet(['0'..'9', 'a'..'f', 'A'..'F']); SetLength(l_SubStr, l_SSPos); l_SubStr := '$'+l_SubStr; f_Token := etNumber; l_Value := StrToInt64Def(l_SubStr, 0); f_TokenValue := l_Value; f_TokenValue := VarAsType(f_TokenValue, varDouble); end else begin if CurChar = '.' then // у числа есть дробная часть begin Inc(l_SSPos); l_SubStr[l_SSPos] := CurChar; Inc(f_Pos); LoadFromSet(['0'..'9']); end; SetLength(l_SubStr, l_SSPos); f_Token := etNumber; DecimalSeparator := '.'; // иногда он слетает f_TokenValue := StrToFloatDef(l_SubStr, 0.0); end; f_TokenEnd := f_Pos; end; '"', '''': begin if DetectStrings then begin l_QuoteChar := CurChar; f_TokenStart := f_Pos; l_SubStr := ''; Inc(f_Pos); while not (CurChar in [l_QuoteChar, #0]) do begin l_SubStr := l_SubStr + CurChar; Inc(f_Pos); end; if CurChar <> #0 then begin Inc(f_Pos); f_Token := etString; f_TokenValue := l_SubStr; end else f_Token := etEOF; f_TokenEnd := f_Pos; end else SetToken(etSymbol); end; '*': SetToken(etMultiply); '/': SetToken(etDivide); '+': SetToken(etPlus); '-': SetToken(etMinus); '(': SetToken(etLBrasket); ')': SetToken(etRBrasket); '&': SetToken(etAmpersand); ',': SetToken(etComma); '<': begin f_TokenStart := f_Pos; Inc(f_Pos); case CurChar of '=': SetTokenEnd(etLesserOrEqual); '>': SetTokenEnd(etNotEqual); else begin f_Token := etLesser; f_TokenEnd := f_Pos; end; end; end; '>': begin f_TokenStart := f_Pos; Inc(f_Pos); if CurChar = '=' then SetTokenEnd(etGreaterOrEqual) else begin f_Token := etGreater; f_TokenEnd := f_Pos; end; end; '=': begin f_TokenStart := f_Pos; Inc(f_Pos); if CurChar = '=' then SetTokenEnd(etSimular) else begin f_Token := etEqual; f_TokenEnd := f_Pos; end; end; else SetToken(etSymbol); end; end; procedure GetCustomToken; begin if CurChar in aCustomCharset then begin f_TokenStart := f_Pos; SetLength(l_SubStr, cMaxIdentifierLen); l_SubStr[1] := CurChar; l_SSPos := 1; Inc(f_Pos); LoadFromSet(aCustomCharset); SetLength(l_SubStr, l_SSPos); f_Token := etCustom; f_TokenValue := l_SubStr; f_TokenEnd := f_Pos; end else GetRegularToken; end; begin while CurChar in cWhitespaces do Inc(f_Pos); if aCustomCharset <> [] then GetCustomToken else GetRegularToken; end; function TfurqLexer.pm_GetCurChar: Char; begin if f_Pos <= Length(f_Source) then Result := f_Source[f_Pos] else Result := #0; end; procedure TfurqLexer.pm_SetSource(const Value: string); begin f_Source := Value; Reset; end; procedure TfurqLexer.Reset; begin f_Pos := 1; NextToken; end; procedure TfurqLexer.SetSourceCustom(const aSource: string; aCustomCharset: TCharset); begin f_Source := aSource; f_Pos := 1; NextToken(aCustomCharset); end; constructor TfurqUnaryEvalNode.Create(aValue: IfurqEvalNode); begin inherited Create; f_Value := aValue; end; destructor TfurqUnaryEvalNode.Destroy; begin f_Value := nil; inherited; end; constructor TfurqBinaryEvalNode.Create(aFirst, aSecond: IfurqEvalNode); begin inherited Create; f_First := aFirst; f_Second := aSecond; end; destructor TfurqBinaryEvalNode.Destroy; begin f_First := nil; f_Second := nil; inherited; end; constructor TfurqConstEvalNode.Create(const aValue: Variant); begin inherited Create; f_Value := aValue; end; function TfurqConstEvalNode.Evaluate: Variant; begin Result := f_Value; end; function TfurqNegateEvalNode.Evaluate: Variant; begin Result := - EnsureReal(f_Value.Evaluate); end; function TfurqNotEvalNode.Evaluate: Variant; var l_Val: Extended; begin l_Val := EnsureReal(f_Value.Evaluate); if l_Val <> 0 then Result := 0.0 else Result := 1.0; end; function TfurqSummaEvalNode.Evaluate: Variant; var l_V1, l_V2: Variant; begin l_V1 := f_First.Evaluate; l_V2 := f_Second.Evaluate; if (VarType(l_V1) = varString) and (VarType(l_V2) = varString) then Result := EnsureString(l_V1) + EnsureString(l_V2) else Result := EnsureReal(l_V1) + EnsureReal(l_V2); end; function TfurqSubtractEvalNode.Evaluate: Variant; begin Result := EnsureReal(f_First.Evaluate) - EnsureReal(f_Second.Evaluate); end; function TfurqMultiplyEvalNode.Evaluate: Variant; begin Result := EnsureReal(f_First.Evaluate) * EnsureReal(f_Second.Evaluate); end; function TfurqDivideEvalNode.Evaluate: Variant; begin Result := EnsureReal(f_First.Evaluate) / EnsureReal(f_Second.Evaluate); end; function TfurqOrEvalNode.Evaluate: Variant; var l_V1, l_V2: Extended; begin l_V1 := EnsureReal(f_First.Evaluate); l_V2 := EnsureReal(f_Second.Evaluate); if (l_V1 <> 0.0) or (l_V2 <> 0.0) then Result := 1.0 else Result := 0.0; end; function TfurqAndEvalNode.Evaluate: Variant; var l_V1, l_V2: Extended; begin l_V1 := EnsureReal(f_First.Evaluate); l_V2 := EnsureReal(f_Second.Evaluate); if (l_V1 <> 0.0) and (l_V2 <> 0.0) then Result := 1.0 else Result := 0.0; end; constructor TfurqExprEvaluator.Create(aContext: TFURQContext); begin inherited Create; f_Context := aContext; f_Lexer := TfurqLexer.Create; DecimalSeparator := '.'; // иногда он слетает end; destructor TfurqExprEvaluator.Destroy; begin FreeAndNil(f_Lexer); f_Expression := nil; inherited; end; function TfurqExprEvaluator.CompileFactor: TfurqEvalNode; var l_NeedDoNext: Boolean; l_Val: Extended; begin Result := nil; l_NeedDoNext := True; // наивысший приоритет - константы, переменные и скобки case f_Lexer.Token of etIdentifier : Result := TfurqConstEvalNode.Create(GetIdentifierValue(f_Lexer.f_TokenValue)); etNumber, etString : begin if f_Lexer.Token = etNumber then begin l_Val := f_Lexer.f_TokenValue; f_Lexer.NextToken; if f_Lexer.Token = etIdentifier then // это попытка опросить инвентарь begin Result := TfurqConstEvalNode.Create(GetInventoryAmount(f_Lexer.TokenValue, l_Val)); end else // не, это просто число begin Result := TfurqConstEvalNode.Create(l_Val); l_NeedDoNext := False; // мы уже переместились на шаг вперед end; end else Result := TfurqConstEvalNode.Create(f_Lexer.f_TokenValue); end; etLBrasket : begin Result := CompileLevel0(True); if f_Lexer.Token <> etRBrasket then RaiseExprError(sOpenParenthis); end; else RaiseExprError(sFactorNeeded); end; if l_NeedDoNext then f_Lexer.NextToken; end; function TfurqExprEvaluator.CompileLevel0(const aSkip: Boolean): TfurqEvalNode; begin // уровень низшего приоритета, OR Result := CompileLevel1(aSkip); while True do begin case f_Lexer.Token of etOr : Result := TfurqOrEvalNode.Create(Result, CompileLevel1(True)); else Break; end; end; end; function TfurqExprEvaluator.CompileLevel1(const aSkip: Boolean): TfurqEvalNode; begin // уровень низкого приоритета, AND Result := CompileLevel2(aSkip); while True do begin case f_Lexer.Token of etAnd : Result := TfurqAndEvalNode.Create(Result, CompileLevel2(True)); else Break; end; end; end; function TfurqExprEvaluator.CompileLevel2(const aSkip: Boolean): TfurqEvalNode; begin // уровень низкого приоритета, операции сравнения Result := CompileLevel3(aSkip); while True do begin case f_Lexer.Token of etEqual : Result := TfurqEqualEvalNode.Create(Result, CompileLevel3(True)); etNotEqual : Result := TfurqNotEqualEvalNode.Create(Result, CompileLevel3(True)); etSimular : Result := TfurqSimularEvalNode.Create(Result, CompileLevel3(True)); etGreater : Result := TfurqGreaterEvalNode.Create(Result, CompileLevel3(True)); etLesser : Result := TfurqLesserEvalNode.Create(Result, CompileLevel3(True)); etGreaterOrEqual : Result := TfurqGreaterOrEqualEvalNode.Create(Result, CompileLevel3(True)); etLesserOrEqual : Result := TfurqLesserOrEqualEvalNode.Create(Result, CompileLevel3(True)); else Break; end; end; end; function TfurqExprEvaluator.CompileLevel3(const aSkip: Boolean): TfurqEvalNode; begin // уровень низкого приоритета, сложение и вычитание Result := CompileLevel4(aSkip); while True do begin case f_Lexer.Token of etPlus : Result := TfurqSummaEvalNode.Create(Result, CompileLevel4(True)); etMinus : Result := TfurqSubtractEvalNode.Create(Result, CompileLevel4(True)); else Break; end; end; end; function TfurqExprEvaluator.CompileLevel4(const aSkip: Boolean): TfurqEvalNode; begin // уровень среднего приоритета, умножение и деление Result := CompileLevel5(aSkip); while True do begin case f_Lexer.Token of etMultiply : Result := TfurqMultiplyEvalNode.Create(Result, CompileLevel5(True)); etDivide : Result := TfurqDivideEvalNode.Create(Result, CompileLevel5(True)); else Break; end; end; end; function TfurqExprEvaluator.CompileLevel5(const aSkip: Boolean): TfurqEvalNode; begin // уровень высокого приоритета, унарные операции if aSkip then f_Lexer.NextToken; case f_Lexer.Token of etPlus : Result := CompileLevel5(True); // унарный плюс - нифига не значит etMinus : Result := TfurqNegateEvalNode.Create(CompileLevel5(True)); // унарный минус etNot : Result := TfurqNotEvalNode.Create(CompileLevel5(True)); // операция NOT else Result := CompileFactor; end; end; procedure TfurqExprEvaluator.CompileSource; begin f_Expression := nil; try f_Expression := CompileLevel0(False); except f_Expression := nil; raise; end; end; function TfurqExprEvaluator.GetIdentifierValue(aIdentName: string): Variant; var l_Temp: string; l_Range: Integer; begin if AnsiStartsText('rnd', aIdentName) then // кажется, это запрос случайного числа begin l_Temp := Copy(aIdentName, 4, MaxInt); if l_Temp <> '' then begin l_Range := StrToIntDef(l_Temp, 0); if l_Range > 0 then // это рандом с диапазоном begin Result := Random(l_Range) + 1; Exit; end; end else begin Result := Random; // ага, от 0 до 1 Exit; end; end; if f_Context.IsVariableExists(aIdentName) then Result := f_Context.Variables[aIdentName] else begin if f_Context.Inventory.IndexOf(aIdentName) <> -1 then Result := 1 else Result := 0; end; end; function TfurqExprEvaluator.GetInventoryAmount(aName: string; anAmount: Extended): Extended; var l_Idx: Integer; begin Result := 0.0; l_Idx := f_Context.Inventory.IndexOf(aName); if (l_Idx >= 0) and (f_Context.Inventory.Variants[l_Idx] >= anAmount) then Result := 1.0; end; function TfurqExprEvaluator.pm_GetResultValue: Variant; begin if f_Expression <> nil then Result := f_Expression.Evaluate else Result := Unassigned; end; function TfurqExprEvaluator.pm_GetSource: string; begin Result := f_Lexer.Source; end; procedure TfurqExprEvaluator.pm_SetSource(const Value: string); begin if f_Lexer.Source <> Value then begin f_Lexer.Source := Value; CompileSource; end; end; function TfurqEqualEvalNode.Evaluate: Variant; var l_V1, l_V2: Variant; begin l_V1 := f_First.Evaluate; l_V2 := f_Second.Evaluate; if VarType(l_V1) = varString then begin if EnsureString(l_V1) = EnsureString(l_V2) then Result := 1.0 else Result := 0.0; end else if EnsureReal(l_V1) = EnsureReal(l_V2) then Result := 1.0 else Result := 0.0; end; function TfurqLesserEvalNode.Evaluate: Variant; begin if EnsureReal(f_First.Evaluate) < EnsureReal(f_Second.Evaluate) then Result := 1.0 else Result := 0.0; end; function TfurqLesserOrEqualEvalNode.Evaluate: Variant; begin if EnsureReal(f_First.Evaluate) <= EnsureReal(f_Second.Evaluate) then Result := 1.0 else Result := 0.0; end; function TfurqGreaterEvalNode.Evaluate: Variant; begin if EnsureReal(f_First.Evaluate) > EnsureReal(f_Second.Evaluate) then Result := 1.0 else Result := 0.0; end; function TfurqGreaterOrEqualEvalNode.Evaluate: Variant; begin if EnsureReal(f_First.Evaluate) >= EnsureReal(f_Second.Evaluate) then Result := 1.0 else Result := 0.0; end; function TfurqNotEqualEvalNode.Evaluate: Variant; var l_V1, l_V2: Variant; begin l_V1 := f_First.Evaluate; l_V2 := f_Second.Evaluate; if VarType(l_V1) = varString then begin if EnsureString(l_V1) <> EnsureString(l_V2) then Result := 1.0 else Result := 0.0; end else if EnsureReal(l_V1) <> EnsureReal(l_V2) then Result := 1.0 else Result := 0.0; end; function TfurqSimularEvalNode.Evaluate: Variant; var l_S1, l_S2: string; begin l_S1 := AnsiUpperCase(EnsureString(f_First.Evaluate)); l_S2 := AnsiUpperCase(EnsureString(f_Second.Evaluate)); if l_S2 <> '' then begin if StrMatches(l_S2, l_S1) then Result := 1.0 else Result := 0.0; end else if l_S1 = '' then // если поисковая строка пустая, то сравниваем с пустой строкой Result := 1.0 else Result := 0.0; 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.3 2004.02.03 5:45:04 PM czhower Name changes Rev 1.2 1/21/2004 1:57:38 PM JPMugaas InitComponent Rev 1.1 10/12/2003 2:01:46 PM BGooijen Compiles in DotNet Rev 1.0 11/14/2002 02:16:44 PM JPMugaas 2002-Feb-07 Pete Mee - Modified interface: GetAsRFC882 is now GetAsRFC822. ;-) - Fixed GetAsTTimeStamp (was way out). 2001-Nov-10 Pete Mee - Added SetFromDOSDateTime. 2001-Mar-29 Pete Mee - Fixed bug in SetFromRFC822. As luck would have it, my PC has changed to BST from GMT, so I caught the error. Change use of GMTToLocalDateTime to StrInternetToDateTime. 2001-Mar-27 Pete Mee - Added GetTimeZoneHour, GetTimeZoneMinutes, GetTimeZoneAsString and corresponding properties, TimeZoneHour, TimeZoneMinutes and TimeZoneAsString. - Added SetFromRFC822 and SetFromISO8601. 2001-Mar-26 Pete Mee - Fixed bug in AddDays. Was adding an extra day in the wrong centuary. - Fixed bug in AddDays. Was not altering the year with large additions. 2001-Mar-23 Pete Mee - Fixed bug in SubtractMilliseconds. - GetBeatOfDay is more accurate (based on milliseconds instead of seconds). 2001-Mar-21 Pete Mee - Altered Day, Seond and Millisecond properties to use their respective Set methods. - Added SetTimeZone, Zero, ZeroTime and ZeroDate. - Altered SetYear and SetDay to cope with the value 0. 2000-Sep-16 Pete Mee - SetYear no longer accepts zero but instead simply exits. 2000-Aug-01 Pete Mee - Fix bugs in AddDays & SubtractDays. Depending on the day of the year, the calculations could have been incorrect. Now 'rounds off' to the nearest year before any other calculation. 2000-Jul-28 Pete Mee - Fix bugs in AddDays & SubtractDays. 3 days in 400 years lost, 1 day in 100 years lost. 2000-May-11 Pete Mee - Added GetAsRFC822, GetAsISO8601 2000-May-03 Pete Mee - Added detection of Day, Week and Month (various formats). 2000-May-02 Pete Mee - Started TIdDateTimeStamp } unit IdDateTimeStamp; { Development notes: The Calendar used is the Gregorian Calendar (modern western society). This Calendar's use started somtime in the 1500s but wasn't adopted by some countries until the early 1900s. No attempt is made to cope with any other Calendars. No attempt is made to cope with any Atomic time quantity less than a leap year (i.e., an exact number of seconds per day and an exact number of days per year / leap year - no leap seconds, no 1/4 days, etc). The implementation revolves around the Milliseconds, Seconds, Days and Years. The heirarchy is as follows: Milliseconds modify seconds. (0-999 Milliseconds) Seconds modify days. (0-59 Seconds) Days modify years. (1-365/366 Days) Years modify years. (..., -2, -1, 1, ...) All other time units are translated into necessary component parts. I.e., a week is 7 days, and hour is 3600 seconds, a minute is 60 seconds, etc... The implementation could be easily expanded to represent decades, centuries, nanoseconds, and beyond in both directions. Milliseconds are included to provide easy conversion from TTimeStamp and back (and hence TDateTime). The current component is designed to give good functionality for the majority (if not all) of Internet component requirements (including Swatch's Internet Time). It is also not limited to the 2038 bug of many of today's OSs (32-bit signed number of seconds from 1st Jan 1970 = 19th Jan 2038 03:14:07, or there abouts). NB: This implementation is factors slower than those of the TDateTime and TTimeStamp components of standard Delphi. It's main use lies in the conversion to / from ISO 8601 and RFC 822 formats as well as dates ranging beyond 2037 and before 1970 (though TTimeStamp is capable here). It's also the only date component I'm aware of that complies with RFC 2550 "Y10K and Beyond"... one of those RFCs in the same category as RFC 1149, IP over Avian Carriers. ;-) Pete Mee } { ToDo: Allow localisation date / time strings generated (i.e., to zone name). ToDo: Rework SetFromRFC822 as it is (marginally) limited by it's conversion to TDateTime. ToDo: Conversion between Time Zones. } interface {$i IdCompilerDefines.inc} uses IdBaseComponent; const // Some basic constants IdMilliSecondsInSecond = 1000; IdSecondsInMinute = 60; IdMinutesInHour = 60; IdHoursInDay = 24; IdDaysInWeek = 7; IdDaysInYear = 365; IdDaysInLeapYear = 366; IdYearsInShortLeapYearCycle = 4; IdDaysInShortLeapYearCycle = IdDaysInLeapYear + (IdDaysInYear * 3); IdDaysInShortNonLeapYearCycle = IdDaysInYear * IdYearsInShortLeapYearCycle; IdDaysInFourYears = IdDaysInShortLeapYearCycle; IdYearsInCentury = 100; IdDaysInCentury = (25 * IdDaysInFourYears) - 1; IdDaysInLeapCentury = IdDaysInCentury + 1; IdYearsInLeapYearCycle = 400; IdDaysInLeapYearCycle = IdDaysInCentury * 4 + 1; IdMonthsInYear = 12; // Beat time is Swatch's "Internet Time" http://www.swatch.com/ {Do not Localize} IdBeatsInDay = 1000; // Some compound constants IdHoursInHalfDay = IdHoursInDay div 2; IdSecondsInHour = IdSecondsInMinute * IdMinutesInHour; IdSecondsInDay = IdSecondsInHour * IdHoursInDay; IdSecondsInHalfDay = IdSecondsInHour * IdHoursInHalfDay; IdSecondsInWeek = IdDaysInWeek * IdSecondsInDay; IdSecondsInYear = IdSecondsInDay * IdDaysInYear; IdSecondsInLeapYear = IdSecondsInDay * IdDaysInLeapYear; IdMillisecondsInMinute = IdSecondsInMinute * IdMillisecondsInSecond; IdMillisecondsInHour = IdSecondsInHour * IdMillisecondsInSecond; IdMillisecondsInDay = IdSecondsInDay * IdMillisecondsInSecond; IdMillisecondsInWeek = IdSecondsInWeek * IdMillisecondsInSecond; SShortMonthNameJan = 'Jan'; SShortMonthNameFeb = 'Feb'; SShortMonthNameMar = 'Mar'; SShortMonthNameApr = 'Apr'; SShortMonthNameMay = 'May'; SShortMonthNameJun = 'Jun'; SShortMonthNameJul = 'Jul'; SShortMonthNameAug = 'Aug'; SShortMonthNameSep = 'Sep'; SShortMonthNameOct = 'Oct'; SShortMonthNameNov = 'Nov'; SShortMonthNameDec = 'Dec'; SLongMonthNameJan = 'January'; SLongMonthNameFeb = 'February'; SLongMonthNameMar = 'March'; SLongMonthNameApr = 'April'; SLongMonthNameMay = 'May'; SLongMonthNameJun = 'June'; SLongMonthNameJul = 'July'; SLongMonthNameAug = 'August'; SLongMonthNameSep = 'September'; SLongMonthNameOct = 'October'; SLongMonthNameNov = 'November'; SLongMonthNameDec = 'December'; SShortDayNameSun = 'Sun'; SShortDayNameMon = 'Mon'; SShortDayNameTue = 'Tue'; SShortDayNameWed = 'Wed'; SShortDayNameThu = 'Thu'; SShortDayNameFri = 'Fri'; SShortDayNameSat = 'Sat'; SLongDayNameSun = 'Sunday'; SLongDayNameMon = 'Monday'; SLongDayNameTue = 'Tuesday'; SLongDayNameWed = 'Wednesday'; SLongDayNameThu = 'Thursday'; SLongDayNameFri = 'Friday'; SLongDayNameSat = 'Saturday'; IdDaysInMonth : array[1..IdMonthsInYear] of byte = ( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ); IdMonthNames : array[0..IdMonthsInYear] of string = ( '', {Do not Localize} SLongMonthNameJan, SLongMonthNameFeb, SLongMonthNameMar, SLongMonthNameApr, SLongMonthNameMay, SLongMonthNameJun, SLongMonthNameJul, SLongMonthNameAug, SLongMonthNameSep, SLongMonthNameOct, SLongMonthNameNov, SLongMonthNameDec ); IdMonthShortNames : array[0..IdMonthsInYear] of string = ( '', // Used for GetMonth {Do not Localize} SShortMonthNameJan, SShortMonthNameFeb, SShortMonthNameMar, SShortMonthNameApr, SShortMonthNameMay, SShortMonthNameJun, SShortMonthNameJul, SShortMonthNameAug, SShortMonthNameSep, SShortMonthNameOct, SShortMonthNameNov, SShortMonthNameDec ); IdDayNames : array[0..IdDaysInWeek] of string = ( '', SLongDayNameSun, SLongDayNameMon, SLongDayNameTue, {Do not Localize} SLongDayNameWed, SLongDayNameThu, SLongDayNameFri, SLongDayNameSat ); IdDayShortNames : array[0..IdDaysInWeek] of string = ( '', SShortDayNameSun, SShortDayNameMon, SShortDayNameTue, {Do not Localize} SShortDayNameWed, SShortDayNameThu, SShortDayNameFri, SShortDayNameSat ); // Area Time Zones TZ_NZDT = 13; // New Zealand Daylight Time TZ_IDLE = 12; // International Date Line East TZ_NZST = TZ_IDLE;// New Zealand Standard Time TZ_NZT = TZ_IDLE; // New Zealand Time TZ_EADT = 11; // Eastern Australian Daylight Time TZ_GST = 10; // Guam Standard Time / Russia Zone 9 TZ_JST = 9; // Japan Standard Time / Russia Zone 8 TZ_CCT = 8; // China Coast Time / Russia Zone 7 TZ_WADT = TZ_CCT; // West Australian Daylight Time TZ_WAST = 7; // West Australian Standard Time / Russia Zone 6 TZ_ZP6 = 6; // Chesapeake Bay / Russia Zone 5 TZ_ZP5 = 5; // Chesapeake Bay / Russia Zone 4 TZ_ZP4 = 4; // Russia Zone 3 TZ_BT = 3; // Baghdad Time / Russia Zone 2 TZ_EET = 2; // Eastern European Time / Russia Zone 1 TZ_MEST = TZ_EET; // Middle European Summer Time TZ_MESZ = TZ_EET; // Middle European Summer Zone TZ_SST = TZ_EET; // Swedish Summer Time TZ_FST = TZ_EET; // French Summer Time TZ_CET = 1; // Central European Time TZ_FWT = TZ_CET; // French Winter Time TZ_MET = TZ_CET; // Middle European Time TZ_MEWT = TZ_CET; // Middle European Winter Time TZ_SWT = TZ_CET; // Swedish Winter Time TZ_GMT = 0; // Greenwich Meanttime TZ_UT = TZ_GMT; // Universla Time TZ_UTC = TZ_GMT; // Universal Time Co-ordinated TZ_WET = TZ_GMT; // Western European Time TZ_WAT = -1; // West Africa Time TZ_BST = TZ_WAT; // British Summer Time TZ_AT = -2; // Azores Time TZ_ADT = -3; // Atlantic Daylight Time TZ_AST = -4; // Atlantic Standard Time TZ_EDT = TZ_AST; // Eastern Daylight Time TZ_EST = -5; // Eastern Standard Time TZ_CDT = TZ_EST; // Central Daylight Time TZ_CST = -6; // Central Standard Time TZ_MDT = TZ_CST; // Mountain Daylight Time TZ_MST = -7; // Mountain Standard Time TZ_PDT = TZ_MST; // Pacific Daylight Time TZ_PST = -8; // Pacific Standard Time TZ_YDT = TZ_PST; // Yukon Daylight Time TZ_YST = -9; // Yukon Standard Time TZ_HDT = TZ_YST; // Hawaii Daylight Time TZ_AHST = -10; // Alaska-Hawaii Standard Time TZ_CAT = TZ_AHST;// Central Alaska Time TZ_HST = TZ_AHST; // Hawaii Standard Time TZ_EAST = TZ_AHST;// East Australian Standard Time TZ_NT = -11; // -None- TZ_IDLW = -12; // International Date Line West // Military Time Zones TZM_A = TZ_WAT; TZM_Alpha = TZM_A; TZM_B = TZ_AT; TZM_Bravo = TZM_B; TZM_C = TZ_ADT; TZM_Charlie = TZM_C; TZM_D = TZ_AST; TZM_Delta = TZM_D; TZM_E = TZ_EST; TZM_Echo = TZM_E; TZM_F = TZ_CST; TZM_Foxtrot = TZM_F; TZM_G = TZ_MST; TZM_Golf = TZM_G; TZM_H = TZ_PST; TZM_Hotel = TZM_H; TZM_J = TZ_YST; TZM_Juliet = TZM_J; TZM_K = TZ_AHST; TZM_Kilo = TZM_K; TZM_L = TZ_NT; TZM_Lima = TZM_L; TZM_M = TZ_IDLW; TZM_Mike = TZM_M; TZM_N = TZ_CET; TZM_November = TZM_N; TZM_O = TZ_EET; TZM_Oscar = TZM_O; TZM_P = TZ_BT; TZM_Papa = TZM_P; TZM_Q = TZ_ZP4; TZM_Quebec = TZM_Q; TZM_R = TZ_ZP5; TZM_Romeo = TZM_R; TZM_S = TZ_ZP6; TZM_Sierra = TZM_S; TZM_T = TZ_WAST; TZM_Tango = TZM_T; TZM_U = TZ_CCT; TZM_Uniform = TZM_U; TZM_V = TZ_JST; TZM_Victor = TZM_V; TZM_W = TZ_GST; TZM_Whiskey = TZM_W; TZM_X = TZ_NT; TZM_XRay = TZM_X; TZM_Y = TZ_IDLE; TZM_Yankee = TZM_Y; TZM_Z = TZ_GMT; TZM_Zulu = TZM_Z; type { TODO: I'm sure these are stored in a unit elsewhere... need to find out } {Do not Localize} TDays = (TDaySun, TDayMon, TDayTue, TDayWed, TDayThu, TDayFri, TDaySat); TMonths = (TMthJan, TMthFeb, TMthMar, TMthApr, TMthMay, TMthJun, TMthJul, TMthAug, TMthSep, TMthOct, TMthNov, TMthDec); TIdDateTimeStamp = class(TIdBaseComponent) protected FDay : Integer; FIsLeapYear : Boolean; FMillisecond : Integer; FSecond : Integer; FTimeZone : Integer; // Number of minutes + / - from GMT / UTC FYear : Integer; procedure CheckLeapYear; procedure SetDateFromISO8601(AString : String); procedure SetTimeFromISO8601(AString : String); procedure InitComponent; override; public procedure AddDays(ANumber : Cardinal); procedure AddHours(ANumber : Cardinal); procedure AddMilliseconds(ANumber : Cardinal); procedure AddMinutes(ANumber : Cardinal); procedure AddMonths(ANumber : Cardinal); procedure AddSeconds(ANumber : Cardinal); procedure AddTDateTime(ADateTime : TDateTime); procedure AddTIdDateTimeStamp(AIdDateTime : TIdDateTimeStamp); procedure AddTTimeStamp(ATimeStamp : TIdDateTimeStamp); procedure AddWeeks(ANumber : Cardinal); procedure AddYears(ANumber : Cardinal); function GetAsISO8601Calendar : String; function GetAsISO8601Ordinal : String; function GetAsISO8601Week : String; function GetAsRFC822 : String; {TODO : function GetAsRFC977DateTime : String;} function GetAsTDateTime : TDateTime; function GetAsTTimeStamp : TIdDateTimeStamp; function GetAsTimeOfDay : String; // HH:MM:SS function GetBeatOfDay : Integer; function GetDaysInYear : Integer; function GetDayOfMonth : Integer; function GetDayOfWeek : Integer; function GetDayOfWeekName : String; function GetDayOfWeekShortName : String; function GetHourOf12Day : Integer; function GetHourOf24Day : Integer; function GetIsMorning : Boolean; function GetMinuteOfDay : Integer; function GetMinuteOfHour : Integer; function GetMonthOfYear : Integer; function GetMonthName : String; function GetMonthShortName : String; function GetSecondsInYear : Integer; function GetSecondOfMinute : Integer; function GetTimeZoneAsString: String; function GetTimeZoneHour: Integer; function GetTimeZoneMinutes: Integer; function GetWeekOfYear : Integer; procedure SetFromDOSDateTime(ADate, ATime : Word); procedure SetFromISO8601(AString : String); procedure SetFromRFC822(AString : String); procedure SetFromTDateTime(ADateTime : TDateTime); procedure SetFromTTimeStamp(ATimeStamp : TIdDateTimeStamp); procedure SetDay(ANumber : Integer); procedure SetMillisecond(ANumber : Integer); procedure SetSecond(ANumber : Integer); procedure SetTimeZone(const Value: Integer); procedure SetYear(ANumber : Integer); procedure SubtractDays(ANumber : Cardinal); procedure SubtractHours(ANumber : Cardinal); procedure SubtractMilliseconds(ANumber : Cardinal); procedure SubtractMinutes(ANumber : Cardinal); procedure SubtractMonths(ANumber : Cardinal); procedure SubtractSeconds(ANumber : Cardinal); procedure SubtractTDateTime(ADateTime : TDateTime); procedure SubtractTIdDateTimeStamp(AIdDateTime : TIdDateTimeStamp); procedure SubtractTTimeStamp(ATimeStamp : TIdDateTimeStamp); procedure SubtractWeeks(ANumber : Cardinal); procedure SubtractYears(ANumber : Cardinal); procedure Zero; procedure ZeroDate; procedure ZeroTime; property AsISO8601Calendar : String read GetAsISO8601Calendar; property AsISO8601Ordinal : String read GetAsISO8601Ordinal; property AsISO8601Week : String read GetAsISO8601Week; property AsRFC822 : String read GetAsRFC822; property AsTDateTime : TDateTime read GetAsTDateTime; property AsTTimeStamp : TIdDateTimeStamp read GetAsTTimeStamp; property AsTimeOfDay : String read GetAsTimeOfDay; property BeatOfDay : Integer read GetBeatOfDay; property Day : Integer read FDay write SetDay; property DaysInYear : Integer read GetDaysInYear; property DayOfMonth : Integer read GetDayOfMonth; property DayOfWeek : Integer read GetDayOfWeek; property DayOfWeekName : String read GetDayOfWeekName; property DayOfWeekShortName : String read GetDayOfWeekShortName; property HourOf12Day : Integer read GetHourOf12Day; property HourOf24Day : Integer read GetHourOf24Day; property IsLeapYear : Boolean read FIsLeapYear; property IsMorning : Boolean read GetIsMorning; property Millisecond : Integer read FMillisecond write SetMillisecond; property MinuteOfDay : Integer read GetMinuteOfDay; property MinuteOfHour : Integer read GetMinuteOfHour; property MonthOfYear : Integer read GetMonthOfYear; property MonthName : String read GetMonthName; property MonthShortName : String read GetMonthShortName; property Second : Integer read FSecond write SetSecond; property SecondsInYear : Integer read GetSecondsInYear; property SecondOfMinute : Integer read GetSecondOfMinute; property TimeZone : Integer read FTimeZone write SetTimeZone; property TimeZoneHour : Integer read GetTimeZoneHour; property TimeZoneMinutes : Integer read GetTimeZoneMinutes; property TimeZoneAsString : String read GetTimeZoneAsString; property Year : Integer read FYear write SetYear; property WeekOfYear : Integer read GetWeekOfYear; end; implementation uses IdGlobal, IdGlobalProtocols, IdStrings, SysUtils; const MaxWeekAdd : Cardinal = $FFFFFFFF div IdDaysInWeek; MaxMinutesAdd : Cardinal = $FFFFFFFF div IdSecondsInMinute; DIGITS : String = '0123456789'; {Do not Localize} function LocalDateTimeToTimeStamp(ADateTime: TDateTime): TIdDateTimeStamp; var Year, Month, Day, Hour, Minute, Second, MSec: Word; begin DecodeDate(ADateTime, Year, Month, Day); DecodeTime(ADateTime, Hour, Minute, Second, MSec); Result := TIdDateTimeStamp.Create; Result.Zero; Result.AddYears(Year); Result.AddMonths(Month); Result.AddDays(Day); Result.AddHours(Hour); Result.AddMinutes(Minute); Result.AddSeconds(Second); Result.AddMilliseconds(MSec); end; procedure ValidateTimeStamp(const ATimeStamp: TIdDateTimeStamp); begin IdGlobal.ToDo('ValidateTimeStamp() function in IdDateTimeStamp.pas is not implemented yet'); {do not localize} // if (ATimeStamp.Time < 0) or (ATimeStamp.Date <= 0) then // EIdExceptionBase.CreateFmt('''%d.%d'' is not a valid timestamp', [ATimeStamp.Date, ATimeStamp.Time]); end; function LocalTimeStampToDateTime(const ATimeStamp: TIdDateTimeStamp): TDateTime; begin ValidateTimeStamp(ATimeStamp); Result := EncodeDate(ATimeStamp.Year, ATimeStamp.MonthOfYear, ATimeStamp.DayOfMonth) + EncodeTime(ATimeStamp.HourOf24Day, ATimeStamp.MinuteOfHour, ATimeStamp.SecondOfMinute, ATimeStamp.Millisecond); end; /////////////////// // TIdDateTimeStamp /////////////////// procedure TIdDateTimeStamp.InitComponent; begin inherited InitComponent; Zero; FTimeZone := 0; end; procedure TIdDateTimeStamp.AddDays; var i : Integer; begin // First 'round off' the current day of the year. This is done to prevent {Do not Localize} // miscalculations in leap years and also as an optimisation for small // increments. if (ANumber > Cardinal(DaysInYear - FDay)) and (not (FDay = 1)) then begin ANumber := ANumber - Cardinal(DaysInYear - FDay); FDay := 0; AddYears(1); end else begin // The number of days added is contained within this year. FDay := FDay + Integer(ANumber); if FDay > DaysInYear then begin ANumber := FDay; FDay := 0; AddDays(ANumber); end; Exit; end; if ANumber >= IdDaysInLeapYearCycle then begin i := ANumber div IdDaysInLeapYearCycle; AddYears(i * IdYearsInLeapYearCycle); ANumber := ANumber - Cardinal(i * IdDaysInLeapYearCycle); end; if ANumber >= IdDaysInLeapCentury then begin while ANumber >= IDDaysInLeapCentury do begin i := FYear div 100; if i mod 4 = 3 then begin // Going forward through a 'leap' century {Do not Localize} AddYears(IdYearsInCentury); ANumber := ANumber - Cardinal(IdDaysInLeapCentury); end else begin AddYears(IdYearsInCentury); ANumber := ANumber - Cardinal(IdDaysInCentury); end; end; end; if ANumber >= IdDaysInShortLeapYearCycle then begin i := ANumber div IdDaysInShortLeapYearCycle; AddYears(i * IdYearsInShortLeapYearCycle); ANumber := ANumber - Cardinal(i * IdDaysInShortLeapYearCycle); end; i := GetDaysInYear; while Integer(ANumber) > i do begin AddYears(1); Dec(ANumber, i); i := GetDaysInYear; end; if FDay + Integer(ANumber) > i then begin AddYears(1); Dec(ANumber, i - FDay); FDay := ANumber; end else begin Inc(FDay, ANumber); end; end; procedure TIdDateTimeStamp.AddHours; var i : Cardinal; begin i := ANumber div IdHoursInDay; AddDays(i); Dec(ANumber, i * IdHoursInDay); AddSeconds(ANumber * IdSecondsInHour); end; procedure TIdDateTimeStamp.AddMilliseconds; var i : Cardinal; begin i := ANumber div IdMillisecondsInDay; if i > 0 then begin AddDays(i); Dec(ANumber, i * IdMillisecondsInDay); end; i := ANumber div IdMillisecondsInSecond; if i > 0 then begin AddSeconds(i); Dec(ANumber, i * IdMillisecondsInSecond); end; Inc(FMillisecond, ANumber); while FMillisecond > IdMillisecondsInSecond do begin // Should only happen once... AddSeconds(1); Dec(FMillisecond, IdMillisecondsInSecond); end; end; procedure TIdDateTimeStamp.AddMinutes; begin // Convert down to seconds while ANumber > MaxMinutesAdd do begin AddSeconds(MaxMinutesAdd); Dec(ANumber, MaxMinutesAdd); end; AddSeconds(ANumber * IdSecondsInMinute); end; procedure TIdDateTimeStamp.AddMonths; var i : Integer; begin i := ANumber div IdMonthsInYear; AddYears(i); Dec(ANumber, i * IdMonthsInYear); i := MonthOfYear; while ANumber > 0 do begin if i = 12 then begin i := 1; end; if (i = 2) and (IsLeapYear) then begin AddDays(IdDaysInMonth[i] + 1); end else begin AddDays(IdDaysInMonth[i]); end; Dec(ANumber); Inc(i); end; end; procedure TIdDateTimeStamp.AddSeconds; var i : Cardinal; begin i := ANumber Div IdSecondsInDay; if i > 0 then begin AddDays(i); ANumber := ANumber - (i * IdSecondsInDay); end; Inc(FSecond, ANumber); while FSecond > IdSecondsInDay do begin // Should only ever happen once... AddDays(1); Dec(FSecond, IdSecondsInDay); end; end; procedure TIdDateTimeStamp.AddTDateTime; begin // todo: // AddTTimeStamp(DateTimeToTimeStamp(ADateTime)); end; procedure TIdDateTimeStamp.AddTIdDateTimeStamp; begin { TODO : Check for accuracy } AddYears(AIdDateTime.Year); AddDays(AIdDateTime.Day); AddSeconds(AIdDateTime.Second); AddMilliseconds(AIdDateTime.Millisecond); end; procedure TIdDateTimeStamp.AddTTimeStamp; begin AddTIdDateTimeStamp(ATimeStamp); end; procedure TIdDateTimeStamp.AddWeeks; begin // Cannot add years as there are not exactly 52 weeks in the year and there // is no exact match between weeks and the 400 year leap cycle // Convert down to days... while ANumber > MaxWeekAdd do begin AddDays(MaxWeekAdd); Dec(ANumber, MaxWeekAdd); end; AddDays(ANumber * IdDaysInWeek); end; procedure TIdDateTimeStamp.AddYears; begin {TODO: Capture overflow because adding Cardinal to Integer } if (FYear <= -1) and (Integer(ANumber) >= -FYear) then begin Inc(ANumber); end; Inc(FYear, ANumber); CheckLeapYear; end; procedure TIdDateTimeStamp.CheckLeapYear; begin // Nested if done to prevent unnecessary calcs on slower machines if FYear mod 4 = 0 then begin if FYear mod 100 = 0 then begin if FYear mod 400 = 0 then begin FIsLeapYear := True; end else begin FIsLeapYear := False; end; end else begin FIsLeapYear := True; end; end else begin FIsLeapYear := False; end; {TODO : If (FIsLeapYear = false) and (FDay = IdDaysInLeapYear) then begin and, do what? } end; function TIdDateTimeStamp.GetAsISO8601Calendar : String; begin Result := IntToStr(FYear) + '-' {Do not Localize} + IntToStr(MonthOfYear) + '-' {Do not Localize} + IntToStr(DayOfMonth) + 'T' {Do not Localize} + AsTimeOfDay; end; function TIdDateTimeStamp.GetAsISO8601Ordinal : String; begin Result := IntToStr(FYear) + '-' {Do not Localize} + IntToStr(FDay) + 'T' {Do not Localize} + AsTimeOfDay; end; function TIdDateTimeStamp.GetAsISO8601Week : String; begin Result := IntToStr(FYear) + '-W' {Do not Localize} + IntToStr(WeekOfYear) + '-' {Do not Localize} + IntToStr(DayOfWeek) + 'T' {Do not Localize} + AsTimeOfDay; end; function TIdDateTimeStamp.GetAsRFC822 : String; begin Result := IdDayShortNames[DayOfWeek] + ', ' {Do not Localize} + IntToStr(DayOfMonth) + ' ' {Do not Localize} + IdMonthShortNames[MonthOfYear] + ' ' {Do not Localize} + IntToStr(Year) + ' ' {Do not Localize} + AsTimeOfDay + ' ' {Do not Localize} + TimeZoneAsString; end; function TIdDateTimeStamp.GetAsTDateTime : TDateTime; begin Result := LocalTimeStampToDateTime(GetAsTTimeStamp); end; function TIdDateTimeStamp.GetAsTTimeStamp : TIdDateTimeStamp; begin Result := Self; end; function TIdDateTimeStamp.GetAsTimeOfDay : String; begin Result := IndyFormat('%.2d:%.2d:%.2d', {Do not localize} [HourOf24Day, MinuteOfHour, SecondOfMinute]); end; function TIdDateTimeStamp.GetBeatOfDay : Integer; var i64 : Int64; DTS : TIdDateTimeStamp; begin // Check if FTimeZone <> TZ_MET then begin // Rather than messing about with this instance, create // a new one. DTS := TIdDateTimeStamp.Create; try DTS.SetYear(FYear); DTS.SetDay(FDay); DTS.SetSecond(FSecond); DTS.SetMillisecond(FMillisecond); DTS.SetTimeZone(TZ_MET); DTS.AddMinutes( (TZ_MET * IdMinutesInHour) - FTimeZone); Result := DTS.GetBeatOfDay; finally DTS.Free; end; end else begin i64 := (FSecond * IdMillisecondsInSecond) + FMillisecond; i64 := i64 * IdBeatsInDay; i64 := i64 div IdMillisecondsInDay; Result := Integer(i64); end; end; function TIdDateTimeStamp.GetDaysInYear : Integer; begin if IsLeapYear then begin Result := IdDaysInLeapYear; end else begin Result := IdDaysInYear; end; end; function TIdDateTimeStamp.GetDayOfMonth : Integer; var count, mnth, days : Integer; begin mnth := MonthOfYear; if IsLeapYear and (mnth > 2) then begin days := 1; end else begin days := 0; end; for count := 1 to mnth - 1 do begin Inc(days, IdDaysInMonth[count]); end; days := Day - days; if days < 0 then begin Result := 0; end else begin Result := days; end; end; function TIdDateTimeStamp.GetDayOfWeek : Integer; var a, y, m, d, mnth : Integer; begin // Thanks to the "FAQ About Calendars" by Claus Tøndering for this algorithm // http://www.tondering.dk/claus/calendar.html mnth := MonthOfYear; a := (14 - mnth) div 12; y := Year - a; m := mnth + (12 * a) - 2; d := DayOfMonth + y + (y div 4) - (y div 100) + (y div 400) + ((31 * m) div 12); d := d mod 7; Result := d + 1; end; function TIdDateTimeStamp.GetDayOfWeekName : String; begin result := IdDayNames[GetDayOfWeek]; end; function TIdDateTimeStamp.GetDayOfWeekShortName : String; begin result := IdDayShortNames[GetDayOfWeek]; end; function TIdDateTimeStamp.GetHourOf12Day : Integer; var hr : Integer; begin hr := GetHourOf24Day; if hr > IdHoursInHalfDay then begin Dec(hr, IdHoursInHalfDay); end; Result := hr; end; function TIdDateTimeStamp.GetHourOf24Day : Integer; begin Result := Second div IdSecondsInHour; end; function TIdDateTimeStamp.GetIsMorning : Boolean; begin Result := Second <= (IdSecondsInHalfDay + 1); end; function TIdDateTimeStamp.GetMinuteOfDay : Integer; begin Result := Second div IdSecondsInMinute; end; function TIdDateTimeStamp.GetMinuteOfHour : Integer; begin Result := GetMinuteOfDay - (IdMinutesInHour * GetHourOf24Day); end; function TIdDateTimeStamp.GetMonthOfYear : Integer; var AddOne, Count : Byte; Today : Integer; begin Result := 0; if IsLeapYear then begin AddOne := 1; end else begin AddOne := 0; end; Today := Day; Count := 1; while Count <> 13 do begin if Count = 2 then begin if Today > IdDaysInMonth[Count] + AddOne then begin Dec(Today, IdDaysInMonth[Count] + AddOne); end else begin Result := Count; Break; end; end else begin if Today > IdDaysInMonth[Count] then begin Dec(Today, IdDaysInMonth[Count]); end else begin Result := Count; Break; end; end; Inc(Count); end; end; function TIdDateTimeStamp.GetMonthName : String; begin Result := IdMonthNames[MonthOfYear]; end; function TIdDateTimeStamp.GetMonthShortName : String; begin Result := IdMonthShortNames[MonthOfYear]; end; function TIdDateTimeStamp.GetSecondsInYear : Integer; begin if IsLeapYear then begin Result := IdSecondsInLeapYear; end else begin Result := IdSecondsInYear; end; end; function TIdDateTimeStamp.GetSecondOfMinute : Integer; begin Result := Second - (GetMinuteOfDay * IdSecondsInMinute); end; function TIdDateTimeStamp.GetTimeZoneAsString: String; var i : Integer; begin i := GetTimeZoneHour; if i < 0 then begin if i < -9 then begin Result := IntToStr(i); end else begin Result := '-0' + IntToStr(Abs(i)); {Do not Localize} end; end else if i <= 9 then begin Result := '+0' + IntToStr(i); {Do not Localize} end else begin Result := '+' + IntToStr(i); {Do not Localize} end; i := GetTimeZoneMinutes; if i <= 9 then begin Result := Result + '0'; {Do not Localize} end; Result := Result + IntToStr(i); end; function TIdDateTimeStamp.GetTimeZoneHour: Integer; begin Result := FTimeZone div 60; end; function TIdDateTimeStamp.GetTimeZoneMinutes: Integer; begin Result := Abs(FTimeZone) mod 60; end; function TIdDateTimeStamp.GetWeekOfYear : Integer; var w : Integer; DT : TIdDateTimeStamp; begin DT := TIdDateTimeStamp.Create; try DT.SetYear(Year); w := DT.DayOfWeek; // Get the first day of this year & hence number of // days of the first week that are in the previous year w := w + Day - 2; // Get complete weeks w := w div 7; Result := w + 1; finally DT.Free; end; end; procedure TIdDateTimeStamp.SetFromDOSDateTime(ADate, ATime: Word); begin Zero; SetYear(1980); AddYears(ADate shr 9); AddMonths(((ADate and $1E0) shr 5) - 1); AddDays((ADate and $1F) - 1); AddHours(ATime shr 11); AddMinutes((ATime and $7E0) shr 5); AddSeconds((ATime and $1F) - 1); end; procedure TIdDateTimeStamp.SetDateFromISO8601(AString: String); var i, week : Integer; s : String; begin // AString should be in one of three formats: // Calender - YYYY-MM-DD // Ordinal - YYYY-XXX where XXX is the day of the year // Week - YYYY-WXX-D where W is a literal and XX is the week of the year. i := IndyPos('-', AString); {Do not Localize} if i > 0 then begin s := Trim(Copy(AString, 1, i - 1)); AString := Trim(Copy(AString, i + 1, MaxInt)); i := FindFirstNotOf('0123456789', s); {Do not Localize} if i = 0 then begin SetYear(IndyStrToInt(s)); if Length(AString) > 0 then begin i := IndyPos('-', AString); {Do not Localize} if TextStartsWith(AString, 'W') then {Do not Localize} begin // Week format s := Trim(Copy(AString, 2, i - 2)); AString := Trim(Copy(AString, i + 1, MaxInt)); week := -1; i := -1; if (Length(AString) > 0) and (FindFirstNotOf(DIGITS, AString) = 0) then begin i := IndyStrToInt(AString); end; if (Length(s) > 0) and (FindFirstNotOf(DIGITS, AString) = 0) then begin week := IndyStrToInt(s); end; if (week > 0) and (i >= 0) then begin Dec(week); FDay := 1 + (IdDaysInWeek * week); // Now have the correct week of the year if i < GetDayOfWeek then begin SubtractDays(GetDayOfWeek - i); end else begin AddDays(i - GetDayOfWeek); end; end; end else if i > 0 then begin // Calender format s := Trim(Copy(AString, 1, i - 1)); AString := Trim(Copy(AString, i + 1, MaxInt)); // Set the day first due to internal format. if (Length(AString) > 0) and (FindFirstNotOf(DIGITS, s) = 0) then begin SetDay(IndyStrToInt(AString)); end; // Add the months. if (Length(s) > 0) and (FindFirstNotOf(DIGITS, s) = 0) then begin AddMonths(IndyStrToInt(s) - 1); end; end else begin // Ordinal format i := FindFirstNotOf(DIGITS, AString); if i = 0 then begin SetDay(IndyStrToInt(AString)); end; end; end; end; end; end; procedure TIdDateTimeStamp.SetTimeFromISO8601(AString: String); var i : Integer; Hour, Minute : String; begin // AString should be in the format of HH:MM:SS where : is a literal. i := IndyPos(':', AString); {Do not Localize} Hour := Trim(Copy(AString, 1, i - 1)); AString := Trim(Copy(AString, i + 1, MaxInt)); i := IndyPos(':', AString); {Do not Localize} Minute := Trim(Copy(AString, 1, i - 1)); AString := Trim(Copy(AString, i + 1, MaxInt)); // Set seconds first due to internal format. if (Length(AString) > 0) and (FindFirstNotOf(DIGITS, AString) = 0) then begin SetSecond(IndyStrToInt(AString)); end; if (Length(Minute) > 0) and (FindFirstNotOf(DIGITS, Minute) = 0) then begin AddMinutes(IndyStrToInt(Minute)); end; if (Length(Hour) > 0) and (FindFirstNotOf(DIGITS, Hour) = 0) then begin AddHours(IndyStrToInt(Hour)); end; end; procedure TIdDateTimeStamp.SetFromISO8601(AString: String); var i : Integer; begin Zero; i := IndyPos('T', AString); {Do not Localize} if i > 0 then begin SetDateFromISO8601(Trim(Copy(AString, 1, i - 1))); SetTimeFromISO8601(Trim(Copy(AString, i + 1, MaxInt))); end else begin SetDateFromISO8601(AString); SetTimeFromISO8601(AString); end; end; procedure TIdDateTimeStamp.SetFromRFC822(AString: String); begin SetFromTDateTime(StrInternetToDateTime(AString)) end; procedure TIdDateTimeStamp.SetFromTDateTime(ADateTime : TDateTime); var LStamp: TIdDateTimeStamp; begin LStamp := LocalDateTimeToTimeStamp(ADateTime); try SetFromTTimeStamp(LStamp); finally FreeAndNil(LStamp); end; end; procedure TIdDateTimeStamp.SetFromTTimeStamp(ATimeStamp : TIdDateTimeStamp); begin FDay := ATimeStamp.Day; FMillisecond := ATimeStamp.Millisecond; FIsLeapYear := ATimeStamp.IsLeapYear; FSecond := ATimeStamp.Second; FTimeZone := ATimeStamp.TimeZone; FYear := ATimeStamp.Year; end; procedure TIdDateTimeStamp.SetDay(ANumber : Integer); begin if ANumber > 0 then begin FDay := 0; AddDays(ANumber); end else begin FDay := 1; end; end; procedure TIdDateTimeStamp.SetMillisecond(ANumber : Integer); begin FMillisecond := 0; AddMilliseconds(ANumber); end; procedure TIdDateTimeStamp.SetSecond(ANumber : Integer); begin FSecond := 0; AddSeconds(ANumber); end; procedure TIdDateTimeStamp.SetTimeZone(const Value: Integer); begin FTimeZone := Value; end; procedure TIdDateTimeStamp.SetYear(ANumber : Integer); begin If ANumber = 0 then begin FYear := 1; end else begin FYear := ANumber; end; CheckLeapYear; end; procedure TIdDateTimeStamp.SubtractDays(ANumber : Cardinal); var i : Integer; begin if ANumber = 0 then begin Exit; end; // First remove the number of days in this year. As with AddDays this // is both an optimisation and a fix for calculations that begin in leap years. if ANumber >= Cardinal(FDay - 1) then begin ANumber := ANumber - Cardinal(FDay - 1); FDay := 1; end else begin FDay := FDay - Integer(ANumber); end; // Subtract the number of whole leap year cycles = 400 years if ANumber >= IdDaysInLeapYearCycle then begin i := ANumber div IdDaysInLeapYearCycle; SubtractYears(i * IdYearsInLeapYearCycle); ANumber := ANumber - Cardinal(i * IdDaysInLeapYearCycle); end; // Next subtract the centuries, checking for the century that is passed through if ANumber >= IdDaysInLeapCentury then begin while ANumber >= IdDaysInLeapCentury do begin i := FYear div 100; if i mod 4 = 0 then begin // Going back through a 'leap' century {Do not Localize} SubtractYears(IdYearsInCentury); ANumber := ANumber - Cardinal(IdDaysInLeapCentury); end else begin SubtractYears(IdYearsInCentury); ANumber := ANumber - Cardinal(IdDaysInCentury); end; end; end; // Subtract multiples of 4 ("Short" Leap year cycle) if ANumber >= IdDaysInShortLeapYearCycle then begin while ANumber >= IdDaysInShortLeapYearCycle do begin // Round off current year to nearest four. i := (FYear shr 2) shl 2; if SysUtils.IsLeapYear(i) then begin // Normal SubtractYears(IdYearsInShortLeapYearCycle); ANumber := ANumber - Cardinal(IdDaysInShortLeapYearCycle); end else begin // Subtraction crosses a 100-year (but not 400-year) boundary. Add the // same number of years, but one less day. SubtractYears(IdYearsInShortLeapYearCycle); ANumber := ANumber - Cardinal(IdDaysInShortNonLeapYearCycle); end; end; end; // Now the individual years while ANumber > Cardinal(DaysInYear) do begin SubtractYears(1); Dec(ANumber, DaysInYear); if Self.IsLeapYear then begin // Correct the assumption of a non-leap year AddDays(1); end; end; // and finally the remainders if ANumber >= Cardinal(FDay) then begin SubtractYears(1); ANumber := ANumber - Cardinal(FDay); Day := DaysInYear - Integer(ANumber); end else begin Dec(FDay, ANumber); end; end; procedure TIdDateTimeStamp.SubtractHours(ANumber : Cardinal); var i : Cardinal; begin i := ANumber div IdHoursInDay; SubtractDays(i); Dec(ANumber, i * IdHoursInDay); SubtractSeconds(ANumber * IdSecondsInHour); end; procedure TIdDateTimeStamp.SubtractMilliseconds(ANumber : Cardinal); var i : Cardinal; begin if ANumber = 0 then begin Exit; end; i := ANumber div IdMillisecondsInDay; SubtractDays(i); Dec(ANumber, i * IdMillisecondsInDay); i := ANumber div IdMillisecondsInSecond; SubtractSeconds(i); Dec(ANumber, i * IdMillisecondsInSecond); Dec(FMillisecond, ANumber); while FMillisecond <= 0 do begin SubtractSeconds(1); // FMillisecond is already negative, so add it. FMillisecond := IdMillisecondsInSecond + FMillisecond; end; end; procedure TIdDateTimeStamp.SubtractMinutes(ANumber : Cardinal); begin // Down size to seconds while ANumber > MaxMinutesAdd do begin SubtractSeconds(MaxMinutesAdd * IdSecondsInMinute); Dec(ANumber, MaxMinutesAdd); end; SubtractSeconds(ANumber * IdSecondsInMinute); end; procedure TIdDateTimeStamp.SubtractMonths(ANumber : Cardinal); var i : Integer; begin i := ANumber div IdMonthsInYear; SubtractYears(i); Dec(ANumber, i * IdMonthsInYear); while ANumber > 0 do begin i := MonthOfYear; if i = 1 then begin i := 13; end; if (i = 3) and (IsLeapYear) then begin SubtractDays(IdDaysInMonth[2] + 1); end else begin SubtractDays(IdDaysInMonth[i - 1]); end; Dec(ANumber); end; end; procedure TIdDateTimeStamp.SubtractSeconds(ANumber : Cardinal); var i : Cardinal; begin if ANumber = 0 then begin Exit; end; i := ANumber div IdSecondsInDay; SubtractDays(i); Dec(ANumber, i * IdSecondsInDay); Dec(FSecond, ANumber); If FSecond < 0 then begin SubtractDays(1); FSecond := IdSecondsInDay + FSecond; end; end; procedure TIdDateTimeStamp.SubtractTDateTime(ADateTime : TDateTime); var LStamp : TIdDateTimeStamp; begin LStamp := LocalDateTimeToTimeStamp(ADateTime); try SubtractTIdDateTimeStamp(LStamp); finally FreeAndNil(LStamp); end; end; procedure TIdDateTimeStamp.SubtractTIdDateTimeStamp(AIdDateTime : TIdDateTimeStamp); begin { TODO : Check for accuracy } SubtractYears(AIdDateTime.Year); SubtractDays(AIdDateTime.Day); SubtractSeconds(AIdDateTime.Second); SubtractMilliseconds(AIdDateTime.Millisecond); end; procedure TIdDateTimeStamp.SubtractTTimeStamp(ATimeStamp : TIdDateTimeStamp); begin SubtractTIdDateTimeStamp(ATimeStamp); end; procedure TIdDateTimeStamp.SubtractWeeks(ANumber : Cardinal); begin if ANumber = 0 then begin Exit; end; // Down size to subtracting Days while ANumber > MaxWeekAdd do begin SubtractDays(MaxWeekAdd * IdDaysInWeek); Dec(ANumber, MaxWeekAdd * IdDaysInWeek); end; SubtractDays(ANumber * IdDaysInWeek); end; procedure TIdDateTimeStamp.SubtractYears(ANumber : Cardinal); begin if (FYear > 0) and (ANumber >= Cardinal(FYear)) then begin Inc(ANumber); end; FYear := FYear - Integer(ANumber); CheckLeapYear; end; procedure TIdDateTimeStamp.Zero; begin ZeroDate; ZeroTime; FTimeZone := 0; end; procedure TIdDateTimeStamp.ZeroDate; begin SetYear(1); SetDay(1); end; procedure TIdDateTimeStamp.ZeroTime; begin SetSecond(0); SetMillisecond(0); end; end.
// -------------------------------------------------------------------------- // Archivo del Proyecto Ventas // Página del proyecto: http://sourceforge.net/projects/ventas // -------------------------------------------------------------------------- // Este archivo puede ser distribuido y/o modificado bajo lo terminos de la // Licencia Pública General versión 2 como es publicada por la Free Software // Fundation, Inc. // -------------------------------------------------------------------------- unit Funciones; interface uses SysUtils, Classes,{$IFDEF MSWINDOWS} Windows, {$ENDIF} Math, Messages; const FECHA_DBMS = 'mm/dd/yyyy'; FECHA_HORA_DBMS = 'mm/dd/yyyy hh:nn:ss.zzz'; HORA_DBMS = 'hh:nn:ss'; OBTENER_FECHA_HORA = 'CAST(''NOW'' AS TIMESTAMP)'; OBTENER_FECHA = 'CAST(''NOW'' AS DATE)'; OBTENER_HORA = 'CAST(''NOW'' AS TIME)'; // Constantes para formato de valores FLOTANTE_2DEC = '#,###,##0.00'; FLOTANTE_3DEC = '#,###,##0.000'; FLOTANTE_4DEC = '#,###,##0.0000'; ENTERO = '#,##0'; PORCENTAJE = '#,##0.00%'; type TMensajes = class procedure ControlarMensaje(var Mensaje: TMsg; var Controlado: Boolean); end; //-- function NumFloat(sNumeroTexto :string; wDecimales :Word) :string; function StrZero(rNumero: Extended; iTamanio, iDecimales: integer): string; function QuitarAcentos(sString :String): String; function RemoverCaracteresEsp(sString : String) : String; function StrTran(sString, sBusqueda, sNuevaString : String) : String; //-- function Iif(BooleanExpr:Boolean; IfTrue, IfFalse:Variant):Variant; {$IFDEF MSWINDOWS} function NombreEquipo: string; {$ENDIF} function ValidaCorreo(sCorreo: string): boolean; implementation { procedimientos y funciones } function StrZero(rNumero: Extended; iTamanio, iDecimales: integer): string; var TempStr: string; begin Str(rNumero:0:iDecimales,TempStr); while length(TempStr) < iTamanio do Insert('0',TempStr,1); Result := TempStr; end; function NumFloat(sNumeroTexto :string; wDecimales :Word) :string; var i : Word; sString, sDecimales : string; begin sString := ''; for i := 1 to Length(sNumeroTexto) do begin if sNumeroTexto[i] = DecimalSeparator then sString := sString+sNumeroTexto[i] else if (sNumeroTexto[i] in ['0'..'9']) then sString := sString+sNumeroTexto[i]; end; if Pos(DecimalSeparator,sString) = 0 then sString := sString+','+StringOfChar('0',wDecimales) else begin sDecimales := Copy(sString,Pos(',',sString)+1,wDecimales); sDecimales := sDecimales+StringOfChar('0',wDecimales-Length(sDecimales)); sString := Copy(sString,1,Pos(',',sString)-1)+','+sDecimales; end; Result := StringReplace(sString,',','.',[rfReplaceAll]); end; function Iif(BooleanExpr:Boolean; IfTrue, IfFalse:Variant):Variant; begin if BooleanExpr Then Result := IfTrue Else Result := IFFalse; end; function QuitarAcentos(sString :String): String; const ConAcento = 'àâêôûãõáéíóúçüÀÂÊÔÛÃÕÁÉÍÓÚÇÜ'; SinAcento = 'aaeouaoaeioucuAAEOUAOAEIOUCU'; var i : Integer; begin for i := 1 to Length(sString) do begin if Pos(sString[i],ConAcento)<>0 then sString[i] := SinAcento[Pos(sString[i],ConAcento)]; end; Result := sString; end; {$IFDEF MSWINDOWS} // Retorna el nombre del computadora function NombreEquipo: string; var wI: DWord; begin wI := MAX_COMPUTERNAME_LENGTH + 1; SetLength(Result, wI); Windows.GetComputerName(PChar(Result), wI); Result := string(PChar(Result)); end; {$ENDIF} function RemoverCaracteresEsp(sString : String) : String; begin sString := StrTran(sString,' ',''); sString := StrTran(sString,'.',''); sString := StrTran(sString,',',''); sString := StrTran(sString,'/',''); sString := StrTran(sString,'\',''); sString := StrTran(sString,'|',''); sString := StrTran(sString,':',''); sString := StrTran(sString,'(',''); sString := StrTran(sString,')',''); sString := StrTran(sString,'-',''); sString := StrTran(sString,'=',''); sString := StrTran(sString,';',''); sString := StrTran(sString,':',''); sString := StrTran(sString,'''',''); sString := StrTran(sString,'"',''); Result := sString; end; function StrTran(sString, sBusqueda, sNuevaString : String) : String; var i : integer; begin for i := 1 to Length(sString) do begin if Copy(sString,i,1) = sBusqueda then begin Delete(sString,i,1); Insert(sNuevaString,sString,i); end; end; Result := sString; end; procedure TMensajes.ControlarMensaje(var Mensaje: TMsg; var Controlado: Boolean); var i: SmallInt; begin if Mensaje.message = WM_MOUSEWHEEL then begin Mensaje.message := WM_KEYDOWN; Mensaje.lParam := 0; i := HiWord(Mensaje.wParam) ; if i > 0 then Mensaje.wParam := VK_UP else Mensaje.wParam := VK_DOWN; Controlado := False; end; end; function ValidaCorreo(sCorreo: string): boolean; const // Caracteres válidos en un "átomo" ATOM_CHARS = [#33..#255] - ['(', ')', '<', '>', '@', ',', ';', ':', '\', '/', '"', '.', '[', ']', #127]; // Caracteres válidos en una "cadena-entrecomillada" QUOTED_STRING_CHARS = [#0..#255] - ['"', #13, '\']; // Caracteres válidos en un subdominio LETTERS = ['A'..'Z', 'a'..'z']; LETTERS_DIGITS = ['0'..'9', 'A'..'Z', 'a'..'z']; SUBDOMAIN_CHARS = ['-', '0'..'9', 'A'..'Z', 'a'..'z']; type States = (STATE_BEGIN, STATE_ATOM, STATE_QTEXT, STATE_QCHAR, STATE_QUOTE, STATE_LOCAL_PERIOD, STATE_EXPECTING_SUBDOMAIN, STATE_SUBDOMAIN, STATE_HYPHEN); var State: States; i, n, iSubdomains: integer; c: char; begin State := STATE_BEGIN; n := Length(sCorreo); i := 1; iSubdomains := 1; while (i <= n) do begin c := sCorreo[i]; case State of STATE_BEGIN: if c in atom_chars then State := STATE_ATOM else if c = '"' then State := STATE_QTEXT else break; STATE_ATOM: if c = '@' then State := STATE_EXPECTING_SUBDOMAIN else if c = '.' then State := STATE_LOCAL_PERIOD else if not (c in atom_chars) then break; STATE_QTEXT: if c = '\' then State := STATE_QCHAR else if c = '"' then State := STATE_QUOTE else if not (c in quoted_string_chars) then break; STATE_QCHAR: State := STATE_QTEXT; STATE_QUOTE: if c = '@' then State := STATE_EXPECTING_SUBDOMAIN else if c = '.' then State := STATE_LOCAL_PERIOD else break; STATE_LOCAL_PERIOD: if c in atom_chars then State := STATE_ATOM else if c = '"' then State := STATE_QTEXT else break; STATE_EXPECTING_SUBDOMAIN: if c in letters then State := STATE_SUBDOMAIN else break; STATE_SUBDOMAIN: if c = '.' then begin Inc(iSubdomains); State := STATE_EXPECTING_SUBDOMAIN end else if c = '-' then State := STATE_HYPHEN else if not (c in letters_digits) then break; STATE_HYPHEN: if c in letters_digits then State := STATE_SUBDOMAIN else if c <> '-' then break; end; Inc(i); end; if i <= n then Result := False else Result := (State = STATE_SUBDOMAIN) and (iSubdomains >= 2); //si sCorreo esta vacio regresa true if sCorreo = '' then Result := true; end; end.
inherited dmOsAutomaticas: TdmOsAutomaticas OldCreateOrder = True inherited qryManutencao: TIBCQuery SQLInsert.Strings = ( 'INSERT INTO STWOPETAUTOS' ' (INDICADOR, TIPO_FRETE, REMETENTE, DESTINATARIO, REDESPACHANTE' + ', CONSIGNATARIO, RESPONSAVEL, OS_VEICULO, VEICULO, MOTORISTA, UL' + 'TIMA_GERACAO, DT_ALTERACAO, OPERADOR)' 'VALUES' ' (:INDICADOR, :TIPO_FRETE, :REMETENTE, :DESTINATARIO, :REDESPAC' + 'HANTE, :CONSIGNATARIO, :RESPONSAVEL, :OS_VEICULO, :VEICULO, :MOT' + 'ORISTA, :ULTIMA_GERACAO, :DT_ALTERACAO, :OPERADOR)') SQLDelete.Strings = ( 'DELETE FROM STWOPETAUTOS' 'WHERE' ' INDICADOR = :Old_INDICADOR') SQLUpdate.Strings = ( 'UPDATE STWOPETAUTOS' 'SET' ' INDICADOR = :INDICADOR, TIPO_FRETE = :TIPO_FRETE, REMETENTE = ' + ':REMETENTE, DESTINATARIO = :DESTINATARIO, REDESPACHANTE = :REDES' + 'PACHANTE, CONSIGNATARIO = :CONSIGNATARIO, RESPONSAVEL = :RESPONS' + 'AVEL, OS_VEICULO = :OS_VEICULO, VEICULO = :VEICULO, MOTORISTA = ' + ':MOTORISTA, ULTIMA_GERACAO = :ULTIMA_GERACAO, DT_ALTERACAO = :DT' + '_ALTERACAO, OPERADOR = :OPERADOR' 'WHERE' ' INDICADOR = :Old_INDICADOR') SQLRefresh.Strings = ( 'SELECT INDICADOR, TIPO_FRETE, REMETENTE, DESTINATARIO, REDESPACH' + 'ANTE, CONSIGNATARIO, RESPONSAVEL, OS_VEICULO, VEICULO, MOTORISTA' + ', ULTIMA_GERACAO, DT_ALTERACAO, OPERADOR FROM STWOPETAUTOS' 'WHERE' ' INDICADOR = :Old_INDICADOR') SQLLock.Strings = ( 'SELECT NULL FROM STWOPETAUTOS' 'WHERE' 'INDICADOR = :Old_INDICADOR' 'FOR UPDATE WITH LOCK') SQL.Strings = ( 'SELECT' ' OAUT.INDICADOR, ' ' OAUT.TIPO_FRETE, ' ' OAUT.REMETENTE, ' ' OAUT.DESTINATARIO, ' ' OAUT.REDESPACHANTE, ' ' OAUT.CONSIGNATARIO, ' ' OAUT.RESPONSAVEL, ' ' OAUT.OS_VEICULO, ' ' OAUT.VEICULO, ' ' OAUT.MOTORISTA, ' ' OAUT.ULTIMA_GERACAO, ' ' OAUT.DT_ALTERACAO, ' ' OAUT.OPERADOR,' ' TPV.DESCRICAO NM_OSVEICULO,' ' VEI.PLACA PLC_VEICULO,' ' MOT.NOME NM_MOTORISTA,' ' REM.NOME NM_REMETENTE,' ' DES.NOME NM_DESTINATARIO,' ' RED.NOME NM_REDESPACHANTE,' ' CON.NOME NM_CONSIGNATARIO' 'FROM STWOPETAUTOS OAUT' 'LEFT JOIN STWOPETTPVE TPV ON TPV.CODIGO = OAUT.OS_VEICULO' 'LEFT JOIN STWOPETVEI VEI ON VEI.FROTA = OAUT.VEICULO' 'LEFT JOIN STWOPETMOT MOT ON MOT.CPF = OAUT.MOTORISTA' 'LEFT JOIN STWOPETCLI REM ON REM.CGC = OAUT.REMETENTE' 'LEFT JOIN STWOPETCLI DES ON DES.CGC = OAUT.DESTINATARIO' 'LEFT JOIN STWOPETCLI RED ON RED.CGC = OAUT.REDESPACHANTE' 'LEFT JOIN STWOPETCLI CON ON CON.CGC = OAUT.CONSIGNATARIO') object qryManutencaoINDICADOR: TIntegerField FieldName = 'INDICADOR' Required = True end object qryManutencaoTIPO_FRETE: TStringField FieldName = 'TIPO_FRETE' Size = 1 end object qryManutencaoREMETENTE: TStringField FieldName = 'REMETENTE' Size = 18 end object qryManutencaoDESTINATARIO: TStringField FieldName = 'DESTINATARIO' Size = 18 end object qryManutencaoREDESPACHANTE: TStringField FieldName = 'REDESPACHANTE' Size = 18 end object qryManutencaoCONSIGNATARIO: TStringField FieldName = 'CONSIGNATARIO' Size = 18 end object qryManutencaoRESPONSAVEL: TStringField FieldName = 'RESPONSAVEL' Size = 18 end object qryManutencaoOS_VEICULO: TIntegerField FieldName = 'OS_VEICULO' end object qryManutencaoVEICULO: TStringField FieldName = 'VEICULO' Size = 8 end object qryManutencaoMOTORISTA: TStringField FieldName = 'MOTORISTA' Size = 18 end object qryManutencaoULTIMA_GERACAO: TDateTimeField FieldName = 'ULTIMA_GERACAO' end object qryManutencaoDT_ALTERACAO: TDateTimeField FieldName = 'DT_ALTERACAO' end object qryManutencaoOPERADOR: TStringField FieldName = 'OPERADOR' end object qryManutencaoNM_OSVEICULO: TStringField FieldName = 'NM_OSVEICULO' ProviderFlags = [] ReadOnly = True end object qryManutencaoPLC_VEICULO: TStringField FieldName = 'PLC_VEICULO' ProviderFlags = [] ReadOnly = True Size = 8 end object qryManutencaoNM_MOTORISTA: TStringField FieldName = 'NM_MOTORISTA' ProviderFlags = [] ReadOnly = True Size = 40 end object qryManutencaoNM_REMETENTE: TStringField FieldName = 'NM_REMETENTE' ProviderFlags = [] ReadOnly = True Size = 40 end object qryManutencaoNM_DESTINATARIO: TStringField FieldName = 'NM_DESTINATARIO' ProviderFlags = [] ReadOnly = True Size = 40 end object qryManutencaoNM_REDESPACHANTE: TStringField FieldName = 'NM_REDESPACHANTE' ProviderFlags = [] ReadOnly = True Size = 40 end object qryManutencaoNM_CONSIGNATARIO: TStringField FieldName = 'NM_CONSIGNATARIO' ProviderFlags = [] ReadOnly = True Size = 40 end end inherited qryLocalizacao: TIBCQuery SQL.Strings = ( 'SELECT' ' OAUT.INDICADOR, ' ' OAUT.TIPO_FRETE, ' ' OAUT.REMETENTE, ' ' OAUT.DESTINATARIO, ' ' OAUT.REDESPACHANTE, ' ' OAUT.CONSIGNATARIO, ' ' OAUT.RESPONSAVEL, ' ' OAUT.OS_VEICULO, ' ' OAUT.VEICULO, ' ' OAUT.MOTORISTA, ' ' OAUT.ULTIMA_GERACAO, ' ' OAUT.DT_ALTERACAO, ' ' OAUT.OPERADOR,' ' TPV.DESCRICAO NM_OSVEICULO,' ' VEI.PLACA PLC_VEICULO,' ' MOT.NOME NM_MOTORISTA,' ' REM.NOME NM_REMETENTE,' ' DES.NOME NM_DESTINATARIO,' ' RED.NOME NM_REDESPACHANTE,' ' CON.NOME NM_CONSIGNATARIO' 'FROM STWOPETAUTOS OAUT' 'LEFT JOIN STWOPETTPVE TPV ON TPV.CODIGO = OAUT.OS_VEICULO' 'LEFT JOIN STWOPETVEI VEI ON VEI.FROTA = OAUT.VEICULO' 'LEFT JOIN STWOPETMOT MOT ON MOT.CPF = OAUT.MOTORISTA' 'LEFT JOIN STWOPETCLI REM ON REM.CGC = OAUT.REMETENTE' 'LEFT JOIN STWOPETCLI DES ON DES.CGC = OAUT.DESTINATARIO' 'LEFT JOIN STWOPETCLI RED ON RED.CGC = OAUT.REDESPACHANTE' 'LEFT JOIN STWOPETCLI CON ON CON.CGC = OAUT.CONSIGNATARIO') object qryLocalizacaoINDICADOR: TIntegerField FieldName = 'INDICADOR' Required = True end object qryLocalizacaoTIPO_FRETE: TStringField FieldName = 'TIPO_FRETE' Size = 1 end object qryLocalizacaoREMETENTE: TStringField FieldName = 'REMETENTE' Size = 18 end object qryLocalizacaoDESTINATARIO: TStringField FieldName = 'DESTINATARIO' Size = 18 end object qryLocalizacaoREDESPACHANTE: TStringField FieldName = 'REDESPACHANTE' Size = 18 end object qryLocalizacaoCONSIGNATARIO: TStringField FieldName = 'CONSIGNATARIO' Size = 18 end object qryLocalizacaoRESPONSAVEL: TStringField FieldName = 'RESPONSAVEL' Size = 18 end object qryLocalizacaoOS_VEICULO: TIntegerField FieldName = 'OS_VEICULO' end object qryLocalizacaoVEICULO: TStringField FieldName = 'VEICULO' Size = 8 end object qryLocalizacaoMOTORISTA: TStringField FieldName = 'MOTORISTA' Size = 18 end object qryLocalizacaoULTIMA_GERACAO: TDateTimeField FieldName = 'ULTIMA_GERACAO' end object qryLocalizacaoDT_ALTERACAO: TDateTimeField FieldName = 'DT_ALTERACAO' end object qryLocalizacaoOPERADOR: TStringField FieldName = 'OPERADOR' end object qryLocalizacaoNM_OSVEICULO: TStringField FieldName = 'NM_OSVEICULO' ReadOnly = True end object qryLocalizacaoPLC_VEICULO: TStringField FieldName = 'PLC_VEICULO' ReadOnly = True Size = 8 end object qryLocalizacaoNM_MOTORISTA: TStringField FieldName = 'NM_MOTORISTA' ReadOnly = True Size = 40 end object qryLocalizacaoNM_REMETENTE: TStringField FieldName = 'NM_REMETENTE' ReadOnly = True Size = 40 end object qryLocalizacaoNM_DESTINATARIO: TStringField FieldName = 'NM_DESTINATARIO' ReadOnly = True Size = 40 end object qryLocalizacaoNM_REDESPACHANTE: TStringField FieldName = 'NM_REDESPACHANTE' ReadOnly = True Size = 40 end object qryLocalizacaoNM_CONSIGNATARIO: TStringField FieldName = 'NM_CONSIGNATARIO' ReadOnly = True Size = 40 end end end
unit tstNSRCGenerator; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "DailyTest" // Модуль: "w:/common/components/rtl/Garant/Daily/tstNSRCGenerator.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi Tests::DailyTest::NSRCUtils::TtstNSRCGenerator // // Обертка над TddGenerator для чтения данных о внешних файлах и запоминания их в тесте для // последующей проверки. // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\Daily\TestDefine.inc.pas} interface {$If defined(nsTest) AND not defined(NoScripts)} uses ddNSRCGenerator ; {$IfEnd} //nsTest AND not NoScripts {$If defined(nsTest) AND not defined(NoScripts)} type ItstNSRCListner = interface(IUnknown) ['{A89ABBCC-F4DD-4B5B-8AA4-50EA93C9907A}'] procedure ExtractFileEvent(const aFileName: AnsiString); {* Событие выливки внешнего файла. } end;//ItstNSRCListner TtstNSRCGenerator = class(TddNSRCGenerator) {* Обертка над TddGenerator для чтения данных о внешних файлах и запоминания их в тесте для последующей проверки. } private // private fields f_Listner : ItstNSRCListner; protected // overridden protected methods procedure SaveObjFileName(const aFileName: AnsiString); override; public // public methods procedure LinkNSRCListner(const aListner: ItstNSRCListner); procedure UnLinkNSRCListner(const aListner: ItstNSRCListner); end;//TtstNSRCGenerator {$IfEnd} //nsTest AND not NoScripts implementation {$If defined(nsTest) AND not defined(NoScripts)} // start class TtstNSRCGenerator procedure TtstNSRCGenerator.LinkNSRCListner(const aListner: ItstNSRCListner); //#UC START# *4D70B25B0190_4D70B17C001C_var* //#UC END# *4D70B25B0190_4D70B17C001C_var* begin //#UC START# *4D70B25B0190_4D70B17C001C_impl* Assert(f_Listner = nil); f_Listner := aListner; //#UC END# *4D70B25B0190_4D70B17C001C_impl* end;//TtstNSRCGenerator.LinkNSRCListner procedure TtstNSRCGenerator.UnLinkNSRCListner(const aListner: ItstNSRCListner); //#UC START# *4D70B2A203B9_4D70B17C001C_var* //#UC END# *4D70B2A203B9_4D70B17C001C_var* begin //#UC START# *4D70B2A203B9_4D70B17C001C_impl* Assert(f_Listner = aListner); f_Listner := nil; //#UC END# *4D70B2A203B9_4D70B17C001C_impl* end;//TtstNSRCGenerator.UnLinkNSRCListner procedure TtstNSRCGenerator.SaveObjFileName(const aFileName: AnsiString); //#UC START# *4D70C8250128_4D70B17C001C_var* //#UC END# *4D70C8250128_4D70B17C001C_var* begin //#UC START# *4D70C8250128_4D70B17C001C_impl* f_Listner.ExtractFileEvent(aFileName); //#UC END# *4D70C8250128_4D70B17C001C_impl* end;//TtstNSRCGenerator.SaveObjFileName {$IfEnd} //nsTest AND not NoScripts end.
// -------------------------------------------------------------------------- // Archivo del Proyecto Ventas // Página del proyecto: http://sourceforge.net/projects/ventas // -------------------------------------------------------------------------- // Este archivo puede ser distribuido y/o modificado bajo lo terminos de la // Licencia Pública General versión 2 como es publicada por la Free Software // Fundation, Inc. // -------------------------------------------------------------------------- unit Empresa; interface uses SysUtils, Types, Classes, QGraphics, QControls, QForms, QDialogs, QStdCtrls, QButtons, QExtCtrls, IniFiles, DB; type TfrmEmpresa = class(TForm) grpProveed: TGroupBox; Label2: TLabel; Label4: TLabel; txtNombre: TEdit; txtRFC: TEdit; btnCancelar: TBitBtn; btnAplicar: TBitBtn; grpDomicilio: TGroupBox; Label16: TLabel; Label21: TLabel; Label22: TLabel; Label23: TLabel; Label24: TLabel; txtCalle: TEdit; txtColonia: TEdit; txtLocalidad: TEdit; txtEstado: TEdit; txtCp: TEdit; Label34: TLabel; txtTelefono: TEdit; Label35: TLabel; txtFax: TEdit; Label36: TLabel; txtCorreo: TEdit; Label1: TLabel; txtPagina: TEdit; dlgAbrir: TOpenDialog; grpLogo: TGroupBox; Label3: TLabel; txtRutaLogo: TEdit; btnDir: TBitBtn; pnlLogo: TPanel; imgLogo: TImage; Label5: TLabel; btnAceptar: TBitBtn; procedure btnAplicarClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure Salta(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnDirClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); private procedure RecuperaConfig; procedure GuardaDatos; procedure LimpiaDatos; public sNombre : String; bCambios : boolean; end; var frmEmpresa: TfrmEmpresa; implementation uses dm; {$R *.xfm} procedure TfrmEmpresa.btnAplicarClick(Sender: TObject); begin if(Length(txtNombre.Text) > 0) then begin GuardaDatos; sNombre := txtNombre.Text; bCambios := True; if ((Sender as TBitBtn).Name = 'btnAceptar') then Close; end else Application.MessageBox('Introduce el nombre de la empresa','Error',[smbOK],smsCritical); end; procedure TfrmEmpresa.GuardaDatos; begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('SELECT rfc FROM empresa'); Open; if(EOF) then begin Close; SQL.Clear; SQL.Add('INSERT INTO empresa (rfc,nombre,calle,'); SQL.Add('colonia, localidad, estado, cp, telefono, fax,'); SQL.Add('correoe,paginaweb, fecha) VALUES('); SQL.Add('''' + txtRfc.Text + ''',''' + txtNombre.Text + ''','); SQL.Add('''' + txtCalle.Text + ''',''' + txtColonia.Text + ''','); SQL.Add('''' + txtLocalidad.Text + ''',''' + txtEstado.Text + ''','); SQL.Add('''' + txtCp.Text + ''',''' + txtTelefono.Text + ''','); SQL.Add('''' + txtFax.Text + ''',''' + txtCorreo.Text + ''','); SQL.Add('''' + txtPagina.Text + ''','); SQL.Add(''''+ FormatDateTime('mm/dd/yyyy hh:nn:ss',Now)+ ''')'); end else begin Close; SQL.Clear; SQL.Add('UPDATE empresa SET '); SQL.Add('rfc = ''' + txtRfc.Text + ''','); SQL.Add('nombre = ''' + txtNombre.Text + ''','); SQL.Add('calle = ''' + txtCalle.Text + ''','); SQL.Add('colonia = ''' + txtColonia.Text + ''','); SQL.Add('localidad = ''' + txtLocalidad.Text + ''','); SQL.Add('estado = ''' + txtEstado.Text + ''','); SQL.Add('cp = ''' + txtCp.Text + ''','); SQL.Add('telefono = ''' + txtTelefono.Text + ''','); SQL.Add('fax = ''' + txtFax.Text + ''','); SQL.Add('correoe = ''' + txtCorreo.Text + ''','); SQL.Add('paginaweb = ''' + txtPagina.Text + ''','); SQL.Add('fecha = ''' + FormatDateTime('mm/dd/yyyy hh:nn:ss',Now) + ''''); end; ExecSQL; if(FileExists(txtRutaLogo.Text)) then begin Close; SQL.Clear; SQL.Add('UPDATE empresa SET logo = :blbLogo'); ParamByName('blbLogo').LoadFromFile(txtRutaLogo.Text, ftGraphic); ExecSQL; end; end; end; procedure TfrmEmpresa.FormShow(Sender: TObject); var fldCampo : TField; stStream : TStream; begin bCambios := False; LimpiaDatos; with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('SELECT * FROM empresa'); Open; fldCampo := FieldByName('logo'); stStream := CreateBlobStream(fldCampo, bmRead); imgLogo.Picture.Bitmap.LoadFromStream(stStream); txtRfc.Text := Trim(FieldByName('rfc').AsString); txtNombre.Text := Trim(FieldByName('nombre').AsString); txtCalle.Text := Trim(FieldByName('calle').AsString); txtColonia.Text := Trim(FieldByName('colonia').AsString); txtLocalidad.Text := Trim(FieldByName('localidad').AsString); txtEstado.Text := Trim(FieldByName('estado').AsString); txtCp.Text := Trim(FieldByName('cp').AsString); txtTelefono.Text := Trim(FieldByName('telefono').AsString); txtFax.Text := Trim(FieldByName('fax').AsString); txtCorreo.Text := Trim(FieldByName('correoe').AsString); txtPagina.Text := Trim(FieldByName('paginaweb').AsString); Close; end; end; procedure TfrmEmpresa.LimpiaDatos; begin txtRfc.Clear; txtNombre.Clear; txtCalle.Clear; txtColonia.Clear; txtLocalidad.Clear; txtEstado.Clear; txtCp.Clear; txtTelefono.Clear; txtFax.Clear; txtCorreo.Clear; txtPagina.Clear; txtRutalogo.Clear; end; procedure TfrmEmpresa.Salta(Sender: TObject; var Key: Word; Shift: TShiftState); begin {Inicio (36), Fin (35), Izquierda (37), derecha (39), arriba (38), abajo (40)} if(Key >= 30) and (Key <= 122) and (Key <> 35) and (Key <> 36) and not ((Key >= 37) and (Key <= 40)) then if( Length((Sender as TEdit).Text) = (Sender as TEdit).MaxLength) then SelectNext(Sender as TWidgetControl, true, true); end; procedure TfrmEmpresa.btnDirClick(Sender: TObject); begin if(dlgAbrir.Execute) then begin txtRutaLogo.Text := dlgAbrir.FileName; imgLogo.Picture.LoadFromFile(dlgAbrir.FileName); end; end; procedure TfrmEmpresa.RecuperaConfig; var iniArchivo : TIniFile; sIzq, sArriba : String; begin iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'config.ini'); with iniArchivo do begin //Recupera la posición Y de la ventana sArriba := ReadString('Empresa', 'Posy', ''); //Recupera la posición X de la ventana sIzq := ReadString('Empresa', 'Posx', ''); if (Length(sIzq) > 0) and (Length(sArriba) > 0) then begin Left := StrToInt(sIzq); Top := StrToInt(sArriba); end; Free; end; end; procedure TfrmEmpresa.FormClose(Sender: TObject; var Action: TCloseAction); var iniArchivo : TIniFile; begin iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'config.ini'); with iniArchivo do begin // Registra la posición y de la ventana WriteString('Empresa', 'Posy', IntToStr(Top)); // Registra la posición X de la ventana WriteString('Empresa', 'Posx', IntToStr(Left)); // Registra la ruta del logo de la empresa WriteString('Empresa', 'RutaLogo', txtRutaLogo.Text); Free; end; end; procedure TfrmEmpresa.FormCreate(Sender: TObject); begin RecuperaConfig; end; end.
unit Model.VerbaCEP; interface type TVerbaCEP = class private var FID: System.Integer; FCEPInicial: System.string; FCEPFinal: System.string; FVerba: System.Double; FGrupo: System.Integer; FFaixa: System.Integer; FLog: System.string; public property ID: System.Integer read FID write FID; property CEPInicial: System.string read FCEPInicial write FCEPInicial; property CEPFinal: System.string read FCEPFinal write FCEPFinal; property Verba: System.Double read FVerba write FVerba; property Grupo: System.Integer read Fgrupo write FGrupo; property Faixa: System.Integer read FFaixa write FFaixa; property Log: System.string read FLog write FLog; constructor Create; overload; constructor Create(pFID: System.Integer; pFCEPInicial: System.string; pFCEPFinal: System.string; pFVerba: System.Double; pFGrupo: System.Integer; pFFaixa: System.Integer; pFLog: System.string); overload; end; implementation constructor TVerbaCEP.Create; begin inherited Create; end; constructor TVerbaCEP.Create(pFID: Integer; pFCEPInicial: string; pFCEPFinal: string; pFVerba: Double; pFGrupo: Integer; pFFaixa: Integer; pFLog: string); begin FID := pFID; FCEPInicial := pFCEPInicial; FCEPFinal := pFCEPFinal; FVerba := pFVerba; FGrupo := pFGrupo; FFaixa := pFFaixa; FLog := pFLog; end; end.
unit msmOperation; // Модуль: "w:\common\components\gui\Garant\msm\msmOperation.pas" // Стереотип: "SimpleClass" // Элемент модели: "TmsmOperation" MUID: (57CEB1C1010D) {$Include w:\common\components\msm.inc} interface uses l3IntfUses , l3ProtoObject , msmOperations , msmModels {$If NOT Defined(NoVCL)} , ActnList {$IfEnd} // NOT Defined(NoVCL) ; type TmsmOperation = {abstract} class(Tl3ProtoObject, ImsmOperation) private f_Caption: AnsiString; f_Model: ImsmModel; f_Action: TAction; protected function pm_GetAction: TAction; function GetCaption: AnsiString; virtual; procedure DoDoIt; virtual; abstract; function GetEnabled: Boolean; virtual; abstract; procedure InitOperationParams(var theParams: TmsmOperationParams); virtual; function Caption: AnsiString; procedure DoIt; function Get_Action: TAction; function Enabled: Boolean; function Get_Params: TmsmOperationParams; procedure Cleanup; override; {* Функция очистки полей объекта. } procedure ClearFields; override; public constructor Create(const aCaption: AnsiString; const aModel: ImsmModel); reintroduce; class function Make(const aCaption: AnsiString; const aModel: ImsmModel): ImsmOperation; reintroduce; protected property Model: ImsmModel read f_Model; property Action: TAction read pm_GetAction; end;//TmsmOperation implementation uses l3ImplUses , msmOperationAction , msmImages //#UC START# *57CEB1C1010Dimpl_uses* , SysUtils //#UC END# *57CEB1C1010Dimpl_uses* ; function TmsmOperation.pm_GetAction: TAction; //#UC START# *57EB5F2E0209_57CEB1C1010Dget_var* //#UC END# *57EB5F2E0209_57CEB1C1010Dget_var* begin //#UC START# *57EB5F2E0209_57CEB1C1010Dget_impl* if (f_Action = nil) then f_Action := TmsmOperationAction.Create(Self); Result := f_Action; //#UC END# *57EB5F2E0209_57CEB1C1010Dget_impl* end;//TmsmOperation.pm_GetAction function TmsmOperation.GetCaption: AnsiString; //#UC START# *57CEB1E803C0_57CEB1C1010D_var* //#UC END# *57CEB1E803C0_57CEB1C1010D_var* begin //#UC START# *57CEB1E803C0_57CEB1C1010D_impl* Result := f_Caption; //#UC END# *57CEB1E803C0_57CEB1C1010D_impl* end;//TmsmOperation.GetCaption constructor TmsmOperation.Create(const aCaption: AnsiString; const aModel: ImsmModel); //#UC START# *57CEB3750096_57CEB1C1010D_var* //#UC END# *57CEB3750096_57CEB1C1010D_var* begin //#UC START# *57CEB3750096_57CEB1C1010D_impl* f_Caption := aCaption; f_Model := aModel; inherited Create; //#UC END# *57CEB3750096_57CEB1C1010D_impl* end;//TmsmOperation.Create class function TmsmOperation.Make(const aCaption: AnsiString; const aModel: ImsmModel): ImsmOperation; var l_Inst : TmsmOperation; begin l_Inst := Create(aCaption, aModel); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TmsmOperation.Make procedure TmsmOperation.InitOperationParams(var theParams: TmsmOperationParams); //#UC START# *57EBADA9033E_57CEB1C1010D_var* //#UC END# *57EBADA9033E_57CEB1C1010D_var* begin //#UC START# *57EBADA9033E_57CEB1C1010D_impl* // - ничего не делаем //#UC END# *57EBADA9033E_57CEB1C1010D_impl* end;//TmsmOperation.InitOperationParams function TmsmOperation.Caption: AnsiString; //#UC START# *57CEACFF03A3_57CEB1C1010D_var* //#UC END# *57CEACFF03A3_57CEB1C1010D_var* begin //#UC START# *57CEACFF03A3_57CEB1C1010D_impl* Result := GetCaption; //#UC END# *57CEACFF03A3_57CEB1C1010D_impl* end;//TmsmOperation.Caption procedure TmsmOperation.DoIt; //#UC START# *57CEAD1C0068_57CEB1C1010D_var* //#UC END# *57CEAD1C0068_57CEB1C1010D_var* begin //#UC START# *57CEAD1C0068_57CEB1C1010D_impl* DoDoIt; //#UC END# *57CEAD1C0068_57CEB1C1010D_impl* end;//TmsmOperation.DoIt function TmsmOperation.Get_Action: TAction; //#UC START# *57EB68C602CD_57CEB1C1010Dget_var* //#UC END# *57EB68C602CD_57CEB1C1010Dget_var* begin //#UC START# *57EB68C602CD_57CEB1C1010Dget_impl* Result := Self.Action; //#UC END# *57EB68C602CD_57CEB1C1010Dget_impl* end;//TmsmOperation.Get_Action function TmsmOperation.Enabled: Boolean; //#UC START# *57EB6CCA0101_57CEB1C1010D_var* //#UC END# *57EB6CCA0101_57CEB1C1010D_var* begin //#UC START# *57EB6CCA0101_57CEB1C1010D_impl* try Result := Self.GetEnabled; except on EAbstractError do Result := false; end;//try..except //#UC END# *57EB6CCA0101_57CEB1C1010D_impl* end;//TmsmOperation.Enabled function TmsmOperation.Get_Params: TmsmOperationParams; //#UC START# *57EBACCE031B_57CEB1C1010Dget_var* //#UC END# *57EBACCE031B_57CEB1C1010Dget_var* begin //#UC START# *57EBACCE031B_57CEB1C1010Dget_impl* Result := TmsmOperationParams_C(Self.Caption, Self.Enabled); InitOperationParams(Result); //#UC END# *57EBACCE031B_57CEB1C1010Dget_impl* end;//TmsmOperation.Get_Params procedure TmsmOperation.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_57CEB1C1010D_var* //#UC END# *479731C50290_57CEB1C1010D_var* begin //#UC START# *479731C50290_57CEB1C1010D_impl* FreeAndNil(f_Action); inherited; //#UC END# *479731C50290_57CEB1C1010D_impl* end;//TmsmOperation.Cleanup procedure TmsmOperation.ClearFields; begin f_Caption := ''; f_Model := nil; inherited; end;//TmsmOperation.ClearFields end.
unit abstract_tree_comand; interface //чтобы историю изменений можно было хранить вместе со всем остальным TAbstractTreeCommand=class(TAbstractCommand) private fNext,fPrev,fBranch: TAbstractTreeCommand; fTurnLeft: Boolean; protected fActiveBranch: Boolean; public procedure Clear; override; function EqualsByAnyOtherName(what: TStreamingClass): boolean; override; published //мы могли бы не сохранять Prev в файл, а восстанавливать его при загрузке //cэкономит сколько-нибудь памяти, около 31 байт на команду property Prev: TAbstractTreeCommand read fPrev write fPrev; property Next: TAbstractTreeCommand read fNext write fNext; property Branch: TAbstractTreeCommand read fBranch write fBranch; property ActiveBranch: Boolean read fActiveBranch write fActiveBranch default false; property TurnLeft: Boolean read fTurnLeft write fTurnLeft default false; end; implementation (* TAbstractTreeCommand *) procedure TAbstractTreeCommand.Clear; begin Next:=nil; Prev:=nil; Branch:=nil; ActiveBranch:=false; fImageIndex:=-1; end; function TAbstractTreeCommand.EqualsByAnyOtherName(what: TStreamingClass): boolean; var t: TAbstractTreeCommand absolute what; buName: string; buNext,buPrev,buBranch: TAbstractTreeCommand; buActiveBranch,buTurnLeft: boolean; buHash: T4x4LongWordRecord; bin1,bin2: TMemoryStream; tmpName: string; ComponentWithSameName: TComponent; begin if ClassType=what.ClassType then begin //нынче команды очень сложные пошли, завязанные на документ //выдернуть их из документа - не поймут, что происходит //придется действовать аккуратно... //сначала записываем наш родной компонент bin1:=TMemoryStream.Create; try bin1.WriteComponent(self); bin1.Seek(0,soFromBeginning); // self.saveFormat:=fCyr; // self.SaveToFile('wtf1.txt'); //теперь можно поменять имя второй команде, если там не существует компонента с таким же //именем tmpName:=Name; if Assigned(t.Owner) and (Name<>t.Name) and Assigned(t.Owner.FindComponent(Name)) then begin //небольшая чехарда ComponentWithSameName:=t.Owner.FindComponent(Name); ComponentWithSameName.Name:=''; //возможно, что это были мы... end else ComponentWithSameName:=nil; //можем безболезненно провести сравнение "на месте" buName:=t.Name; buNext:=t.next; buPrev:=t.prev; buBranch:=t.Branch; buActiveBranch:=t.ActiveBranch; buTurnLeft:=t.TurnLeft; t.Name:=tmpName; //очень вероятно, что мы переименовали себя чтобы избежать конфликта t.Next:=Next; t.Prev:=Prev; t.Branch:=Branch; t.ActiveBranch:=ActiveBranch; t.TurnLeft:=TurnLeft; if t is THashedCommand then begin buHash:=HashedT.fHash; HashedT.fHash:=(self as THashedCommand).fHash; end; bin2:=TMemoryStream.Create; try bin2.WriteComponent(t); bin2.Seek(0,soFromBeginning); if bin1.Size<>bin2.Size then Result:=false else Result:=Comparemem(bin1.Memory,bin2.Memory,bin1.Size); finally bin2.free; end; // if Result=false then begin // what.saveFormat:=fCyr; // what.SaveToFile('wtf2.txt'); // end; finally bin1.Free; end; t.Name:=buName; t.Next:=buNext; t.Prev:=buPrev; t.Branch:=buBranch; t.ActiveBranch:=buActiveBranch; t.TurnLeft:=buTurnLeft; if Assigned(ComponentWithSameName) then ComponentWithSameName.Name:=tmpName; if t is THashedCommand then HashedT.fHash:=buHash; end else Result:=false; end; end.
unit LocalOrdersUnit; interface uses Classes, Contnrs, SysUtils, DbUnit; type // Служебная записка TLocOrderItem = class(TDbItem) public From: string; Dest: string; Text: string; Reply: string; Author: string; Signed: boolean; //constructor Create(); //destructor Destroy(); function GetValue(const FName: string): string; override; procedure SetValue(const FName, FValue: string); override; end; // Список служебных записок TLocOrderList = class(TDbItemList) private Filter: string; public FileName: string; constructor Create(); reintroduce; function NewItem(): TDbItem; override; procedure LoadList(); procedure SaveList(); procedure Sort(); procedure SetFilter(AFilter: string); end; implementation uses MainFunc; //=========================================== // TLocOrderItem //=========================================== function TLocOrderItem.GetValue(const FName: string): string; begin if FName='id' then result:=IntToStr(self.ID) else if FName='from' then result:=self.From else if FName='dest' then result:=self.Dest else if FName='text' then result:=self.Text else if FName='reply' then result:=self.Reply else if FName='author' then result:=self.Author else if FName='signed' then result:=BoolToStr(self.Signed) else if FName='timestamp' then result:=DateTimeToStr(self.Timestamp) else result:=''; end; procedure TLocOrderItem.SetValue(const FName, FValue: string); begin if FName='id' then self.ID:=StrToIntDef(FValue, 0) else if FName='from' then self.From:=FValue else if FName='dest' then self.Dest:=FValue else if FName='text' then self.Text:=FValue else if FName='reply' then self.Reply:=FValue else if FName='author' then self.Author:=FValue else if FName='signed' then self.Signed:=(FValue<>'0') else if FName='timestamp' then self.Timestamp:=StrToDateTimeDef(FValue, self.Timestamp); end; //=========================================== // TLocOrderList //=========================================== constructor TLocOrderList.Create(); var ti: TDbTableInfo; begin ti:=DbDriver.GetDbTableInfo('loc_orders'); if not Assigned(ti) then begin ti:=TDbTableInfo.Create(); with ti do begin TableName:='loc_orders'; AddField('id','I'); AddField('from','S'); AddField('dest','S'); AddField('text','S'); AddField('reply','S'); AddField('author','S'); AddField('signed','B'); AddField('timestamp','D'); end; end; inherited Create(ti); self.Filter:=''; end; function TLocOrderList.NewItem(): TDbItem; var NewItem: TLocOrderItem; begin NewItem:=TLocOrderItem.Create(); self.AddItem(NewItem, true); result:=NewItem; end; procedure TLocOrderList.LoadList(); begin DbDriver.GetTable(self, Filter); end; procedure TLocOrderList.SaveList(); begin DbDriver.SetTable(self); end; function CompareFunc(Item1, Item2: Pointer): Integer; begin {> 0 (positive) Item1 is less than Item2 0 Item1 is equal to Item2 < 0 (negative) Item1 is greater than Item2} result := Round(TLocOrderItem(Item1).Timestamp - TLocOrderItem(Item2).Timestamp); //if result=0 then result := AnsiCompareStr(TLocOrderItem(Item1).Desc, TLocOrderItem(Item2).Desc); end; procedure TLocOrderList.Sort(); begin inherited Sort(@CompareFunc); end; procedure TLocOrderList.SetFilter(AFilter: string); begin self.Filter:=AFilter; self.LoadList(); end; end.
unit uMemoEditor; interface uses uEditorBase, Classes, SysUtils, StdCtrls, Controls, Graphics, Dialogs; type TMemoEditor = Class(TEditorBase) private FMemo: TMemo; protected procedure DoLoadFromFile(FileName: string); override; function DoSaveFile(FileName: string): Boolean; override; // 判断是否需要保存,通过当前编辑器的状态来判断 // 如果编辑其状态处于编辑状态,那么就需要保存,否则就处于已保存状态。 function GetSaved: Boolean; override; function GetText: string; override; public constructor Create(ParentComponent: TComponent); destructor Destroy; override; function GetWordWarp: Boolean; override; // 是否分行 procedure SetWordWarp(WordWarp: Boolean); override; function CanUndo: Boolean; override; procedure Undo; override; function CanRedo: Boolean; override; procedure Redo; override; function CanCopy: Boolean; override; procedure Copy; override; function CanCut: Boolean; override; procedure Cut; override; function CanPaster: Boolean; override; procedure Paster; override; function CanDeleteSelection: Boolean; override; procedure DelectSelection; override; procedure SetFont(Font: TFont); override; function FindNext(Text: String; Option: TFindOptions): Boolean; override; function Replace(FindText, ReplaceText: String; Option: TFindOptions): Integer; override; // 获得Memo中选中的文本 function GetSelectText: String; override; // 全选 procedure SelectAll; override; End; implementation { TMemoEditor } function TMemoEditor.CanCopy: Boolean; begin Result := FMemo.SelLength <> 0; end; function TMemoEditor.CanCut: Boolean; begin Result := FMemo.SelLength <> 0; end; function TMemoEditor.CanDeleteSelection: Boolean; begin Result := FMemo.SelLength <> 0; end; function TMemoEditor.CanPaster: Boolean; begin Result := True; end; function TMemoEditor.CanRedo: Boolean; begin Result := True; end; function TMemoEditor.CanUndo: Boolean; begin Result := True; end; procedure TMemoEditor.Copy; begin FMemo.CopyToClipboard; end; constructor TMemoEditor.Create(ParentComponent: TComponent); begin FMemo := TMemo.Create(nil); FMemo.Parent := TWinControl(ParentComponent); FMemo.Align := alclient; FMemo.Enabled := True; FMemo.WordWrap := False; FMemo.ScrollBars := ssBoth; if FMemo.CanFocus then FMemo.SetFocus; end; procedure TMemoEditor.Cut; begin FMemo.CutToClipboard; end; procedure TMemoEditor.DelectSelection; begin FMemo.ClearSelection; end; destructor TMemoEditor.Destroy; begin FMemo.Free; FMemo := nil; inherited; end; procedure TMemoEditor.DoLoadFromFile(FileName: string); begin FMemo.Lines.LoadFromFile(FileName); end; function TMemoEditor.DoSaveFile(FileName: string): Boolean; begin FMemo.Lines.SaveToFile(FileName); end; function TMemoEditor.FindNext(Text: String; Option: TFindOptions): Boolean; var TextStr: string; iPosition: Integer; iLastPos: Integer; begin Result := False; // 向上或者向下查找 if frDown in Option then TextStr := System.Copy(FMemo.Text, FMemo.SelStart + FMemo.SelLength + 1, Length(FMemo.Text)) else TextStr := System.Copy(FMemo.Text, 0, FMemo.SelStart); // 大小写是否匹配 if frMatchCase in Option then begin TextStr := UpperCase(TextStr); Text := UpperCase(Text); end; if frDown in Option then begin iPosition := Pos(TextStr, Text); if iPosition = 0 then Exit; FMemo.SelStart := FMemo.SelStart + FMemo.SelLength + iPosition; end else begin iLastPos := 0; repeat iPosition := Pos(TextStr, Text); if iPosition <> 0 then begin TextStr := System.Copy(TextStr, iPosition, Length(TextStr)); iLastPos := iLastPos + iPosition; end; until iPosition = 0; if iLastPos = 0 then Exit; FMemo.SelStart := iLastPos; end; end; function TMemoEditor.GetSaved: Boolean; begin Result := FMemo.Modified; end; function TMemoEditor.GetSelectText: String; begin Result := FMemo.SelText; end; function TMemoEditor.GetText: string; begin Result := FMemo.Lines.Text; end; function TMemoEditor.GetWordWarp: Boolean; begin Result := FMemo.WordWrap; end; procedure TMemoEditor.Paster; begin FMemo.PasteFromClipboard; end; procedure TMemoEditor.Redo; begin FMemo.Undo; end; function TMemoEditor.Replace(FindText, ReplaceText: String; Option: TFindOptions): Integer; begin end; procedure TMemoEditor.SelectAll; begin FMemo.SelectAll; end; procedure TMemoEditor.SetFont(Font: TFont); begin FMemo.Font := Font; end; procedure TMemoEditor.SetWordWarp(WordWarp: Boolean); begin FMemo.WordWrap := WordWarp; if WordWarp then FMemo.ScrollBars := ssVertical else FMemo.ScrollBars := ssBoth; end; procedure TMemoEditor.Undo; begin FMemo.Undo; end; end.
unit uRevendaVO; interface type TRevendaVO = class private FAtivo: Boolean; FCodigo: Integer; FId: Integer; FIdStr: string; FNome: string; public property Ativo: Boolean read FAtivo write FAtivo; property Codigo: Integer read FCodigo write FCodigo; property Id: Integer read FId write FId; property IdStr: string read FIdStr write FIdStr; property Nome: string read FNome write FNome; end; implementation end.
{ *************************************************************************** Copyright (c) 2016-2021 Kike Pérez Unit : Quick.HttpClient Description : Json Http Client Author : Kike Pérez Version : 1.1 Created : 22/05/2018 Modified : 02/08/2021 This file is part of QuickLib: https://github.com/exilon/QuickLib *************************************************************************** Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *************************************************************************** } unit Quick.HttpClient; {$i QuickLib.inc} interface uses Classes, SysUtils, Quick.Commons, {$IFDEF DELPHIXE8_UP} System.Net.HttpClient, System.Net.URLClient, System.NetConsts, System.JSON; {$ELSE} {$IFDEF DELPHIXE7_UP} System.JSON, {$ENDIF} IdHTTP, IdException, {$IFDEF FPC} fpjson; {$ELSE} Data.DBXJSON; {$ENDIF} {$ENDIF} type IHttpRequestResponse = interface ['{64DC58F7-B551-4619-85E9-D13E781529CD}'] function StatusCode : Integer; function StatusText : string; function Response : TJSONObject; end; THttpRequestResponse = class(TInterfacedObject,IHttpRequestResponse) private fStatusCode : Integer; fStatusText : string; fResponse : TJSONObject; public {$IFDEF DELPHIXE8_UP} constructor Create(aResponse : IHTTPResponse; const aContent : string); {$ELSE} constructor Create(aResponse : TIdHTTPResponse; const aContent : string); {$ENDIF} destructor Destroy; override; function StatusCode : Integer; function StatusText : string; function Response : TJSONObject; end; TJsonHttpClient = class private {$IFDEF DELPHIXE8_UP} fHTTPClient : System.Net.HttpClient.THTTPClient; {$ELSE} fHTTPClient : TIdHTTP; {$ENDIF} fUserAgent : string; fContentType : string; fResponseTimeout : Integer; fConnectionTimeout : Integer; fHandleRedirects : Boolean; procedure SetContentType(const aValue: string); procedure SetUserAgent(const aValue: string); procedure SetResponseTimeout(const aValue: Integer); procedure SetConnectionTimeout(const aValue: Integer); procedure SetHandleRedirects(const aValue: Boolean); public constructor Create; destructor Destroy; override; property UserAgent : string read fUserAgent write SetUserAgent; property ContentType : string read fContentType write SetContentType; property ResponseTimeout : Integer read fResponseTimeout write SetResponseTimeout; property ConnectionTimeout : Integer read fConnectionTimeout write SetConnectionTimeout; property HandleRedirects : Boolean read fHandleRedirects write SetHandleRedirects; function Get(const aURL : string) : IHttpRequestResponse; function Post(const aURL, aInContent : string; aHeaders : TPairList = nil) : IHttpRequestResponse; overload; function Post(const aURL : string; aInContent : TStream) : IHttpRequestResponse; overload; function Post(const aURL : string; aJsonContent : TJsonObject) : IHttpRequestResponse; overload; function Put(const aURL, aInContent : string) : IHttpRequestResponse; end; implementation const DEF_USER_AGENT = 'XLHttpClient'; constructor TJsonHttpClient.Create; begin {$IFDEF DELPHIXE8_UP} fHTTPClient := THTTPClient.Create; fHTTPClient.ContentType := 'application/json'; fHTTPClient.UserAgent := DEF_USER_AGENT; {$ELSE} fHTTPClient := TIdHTTP.Create(nil); fHTTPClient.Request.ContentType := 'application/json'; fHTTPClient.Request.UserAgent := DEF_USER_AGENT; {$ENDIF} end; destructor TJsonHttpClient.Destroy; begin fHTTPClient.Free; inherited; end; function TJsonHttpClient.Get(const aURL : string) : IHttpRequestResponse; var {$IFDEF DELPHIXE8_UP} resp : IHTTPResponse; {$ELSE} resp : TIdHTTPResponse; {$ENDIF} bodycontent : TStringStream; responsecontent : TStringStream; begin bodycontent := TStringStream.Create; try responsecontent := TStringStream.Create; try {$IFDEF DELPHIXE8_UP} resp := fHTTPClient.Get(aURL,responsecontent,nil); {$ELSE} {$If Defined(FPC) OR Not Defined(DELPHIXE8_UP)} fHTTPClient.Get(aURL,responsecontent); {$ELSE} fHTTPClient.Get(aURL,responsecontent,nil); {$ENDIF} resp := fHTTPClient.Response; {$ENDIF} Result := THttpRequestResponse.Create(resp,responsecontent.DataString); finally responsecontent.Free; end; finally bodycontent.Free; end; end; function TJsonHttpClient.Post(const aURL, aInContent : string; aHeaders : TPairList = nil) : IHttpRequestResponse; var pair : TPairItem; {$IFDEF DELPHIXE8_UP} resp : IHTTPResponse; headers : TArray<TNameValuePair>; {$ELSE} resp : TIdHTTPResponse; {$ENDIF} responsecontent : TStringStream; postcontent : TStringStream; begin postcontent := TStringStream.Create(Utf8Encode(aInContent)); try //postcontent.WriteString(aInContent); responsecontent := TStringStream.Create; try {$IFDEF DELPHIXE8_UP} if aHeaders <> nil then begin for pair in aHeaders do begin headers := headers + [TNameValuePair.Create(pair.Name,pair.Value)]; end; end; resp := fHTTPClient.Post(aURL,postcontent,responsecontent,headers); {$ELSE} if aHeaders <> nil then begin for pair in aHeaders do begin fHttpClient.Request.CustomHeaders.Values[pair.Name] := pair.Value; end; end; {$IFDEF FPC} try fHTTPClient.Post(aURL,postcontent,responsecontent); fHTTPClient.Disconnect(False); except on E : Exception do begin if e.ClassType <> EIdConnClosedGracefully then raise; end; end; {$ELSE} fHTTPClient.Post(aURL,postcontent,responsecontent); {$ENDIF} resp := fHTTPClient.Response; {$ENDIF} Result := THttpRequestResponse.Create(resp,responsecontent.DataString); finally responsecontent.Free; end; finally postcontent.Free; end; end; function TJsonHttpClient.Post(const aURL : string; aInContent : TStream) : IHttpRequestResponse; var {$IFDEF DELPHIXE8_UP} resp : IHTTPResponse; {$ELSE} resp : TIdHTTPResponse; {$ENDIF} responsecontent : TStringStream; begin //postcontent.WriteString(aInContent); responsecontent := TStringStream.Create; try {$IFDEF DELPHIXE8_UP} resp := fHTTPClient.Post(aURL,aInContent,responsecontent); {$ELSE} {$IFDEF FPC} try fHTTPClient.Post(aURL,aInContent,responsecontent); fHTTPClient.Disconnect(False); except on E : Exception do begin if e.ClassType <> EIdConnClosedGracefully then raise; end; end; {$ELSE} fHTTPClient.Post(aURL,aInContent,responsecontent); {$ENDIF} resp := fHTTPClient.Response; {$ENDIF} Result := THttpRequestResponse.Create(resp,responsecontent.DataString); finally responsecontent.Free; end; end; function TJsonHttpClient.Post(const aURL : string; aJsonContent : TJsonObject) : IHttpRequestResponse; begin {$IFDEF DELPHIXE8_UP} Result := Self.Post(aURL,aJsonContent.ToJSON); {$ELSE} {$IFDEF FPC} Result := Self.Post(aURL,aJsonContent.AsJson); {$ELSE} Result := Self.Post(aURL,aJsonContent.ToString); {$ENDIF} {$ENDIF} end; function TJsonHttpClient.Put(const aURL, aInContent : string) : IHttpRequestResponse; var {$IFDEF DELPHIXE8_UP} resp : IHTTPResponse; {$ELSE} resp : TIdHTTPResponse; {$ENDIF} responsecontent : TStringStream; postcontent : TStringStream; begin postcontent := TStringStream.Create(Utf8Encode(aInContent)); try //postcontent.WriteString(aInContent); responsecontent := TStringStream.Create; try {$IFDEF DELPHIXE8_UP} resp := fHTTPClient.Put(aURL,postcontent,responsecontent); {$ELSE} {$IFDEF FPC} try fHTTPClient.Put(aURL,postcontent,responsecontent); fHTTPClient.Disconnect(False); except on E : Exception do begin if e.ClassType <> EIdConnClosedGracefully then raise; end; end; {$ELSE} fHTTPClient.Post(aURL,postcontent,responsecontent); {$ENDIF} resp := fHTTPClient.Response; {$ENDIF} Result := THttpRequestResponse.Create(resp,responsecontent.DataString); finally responsecontent.Free; end; finally postcontent.Free; end; end; procedure TJsonHttpClient.SetConnectionTimeout(const aValue: Integer); begin fConnectionTimeout := aValue; {$IFDEF DELPHIXE8_UP} {$IFDEF DELPHIRX102_UP} //in previous versions don't exists ConnectionTimeout property fHTTPClient.ConnectionTimeout := aValue; {$ENDIF} {$ELSE} fHTTPClient.ConnectTimeout := aValue; {$ENDIF} end; procedure TJsonHttpClient.SetContentType(const aValue: string); begin fContentType := aValue; {$IFDEF DELPHIXE8_UP} fHTTPClient.ContentType := aValue; {$ELSE} fHTTPClient.Request.ContentType := aValue; {$ENDIF} end; procedure TJsonHttpClient.SetHandleRedirects(const aValue: Boolean); begin fHandleRedirects := aValue; {$IFDEF DELPHIXE8_UP} fHTTPClient.HandleRedirects := aValue; {$ELSE} fHTTPClient.HandleRedirects := aValue; {$ENDIF} end; procedure TJsonHttpClient.SetResponseTimeout(const aValue: Integer); begin fResponseTimeout := aValue; {$IFDEF DELPHIXE8_UP} {$IFDEF DELPHIRX102_UP} //in previous versions don't exist ResponseTimeout property fHTTPClient.ResponseTimeout := aValue; {$ENDIF} {$ELSE} fHTTPClient.ReadTimeout := aValue; {$ENDIF} end; procedure TJsonHttpClient.SetUserAgent(const aValue: string); begin fUserAgent := aValue; {$IFDEF DELPHIXE8_UP} fHTTPClient.UserAgent := aValue; {$ELSE} fHTTPClient.Request.UserAgent := aValue; {$ENDIF} end; { THttpRequestResponse } {$IFDEF DELPHIXE8_UP} constructor THttpRequestResponse.Create(aResponse: IHTTPResponse; const aContent : string); begin fStatusCode := aResponse.StatusCode; fStatusText := aResponse.StatusText; if aContent <> '' then fResponse := TJSONObject.ParseJSONValue(aContent) as TJSONObject; //if response is not json, get as json result if fResponse = nil then begin fResponse := TJSONObject.Create; fResponse.AddPair('Result',aContent); end; end; {$ELSE} constructor THttpRequestResponse.Create(aResponse : TIdHTTPResponse; const aContent : string); begin fStatusCode := aResponse.ResponseCode; fStatusText := aResponse.ResponseText; {$If Defined(FPC) OR Defined(DELPHIXE8_UP)} if (aContent.Contains('{')) and (aContent.Contains('}')) then fResponse := GetJSON(aContent) as TJsonObject; {$ELSE} if (aContent.Contains('{')) and (aContent.Contains('}')) then fResponse:= TJsonObject.ParseJSONValue(aContent) as TJsonObject; {$ENDIF} //if response is not json, get as json result if fResponse = nil then begin fResponse := TJSONObject.Create; {$IFDEF DELPHIXE4_UP} fResponse.AddPair('Result',aContent); {$ELSE} fResponse.Add('Result',aContent); {$ENDIF} end; end; {$ENDIF} destructor THttpRequestResponse.Destroy; begin if Assigned(fResponse) then fResponse.Free; inherited; end; function THttpRequestResponse.Response: TJSONObject; begin Result := fResponse; end; function THttpRequestResponse.StatusCode: Integer; begin Result := fStatusCode; end; function THttpRequestResponse.StatusText: string; begin Result := fStatusText; end; 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_ * Implements a Vector4D class *********************************************************************************************************************** } Unit TERRA_Vector4D; {$I terra.inc} Interface Uses TERRA_Math, TERRA_Vector3D, TERRA_Matrix4x4; Type PVector4D = ^Vector4D; Vector4D=Packed {$IFDEF USE_OLD_OBJECTS}Object{$ELSE}Record{$ENDIF} X:Single; Y:Single; Z:Single; W:Single; Function Equals(Const B:Vector4D):Boolean; Procedure Transform(Const M:Matrix4x4); // Returns a normalized Vector4D Procedure Normalize; {$IFDEF BENCHMARK} Procedure TransformSSE(Const M:Matrix4x4); Procedure NormalizeSSE; {$ENDIF} Procedure Add(Const B:Vector4D); Procedure Subtract(Const B:Vector4D); Procedure Scale(Const V:Single); Function Length:Single; End; Color4F = Vector4D; Const Vector4DOne:Vector4D=(X:1.0; Y:1.0; Z:1.0; W:1.0); Vector4DZero:Vector4D=(X:0.0; Y:0.0; Z:0.0; W:0.0); Function VectorCreate4D(Const X,Y,Z,W:Single):Vector4D;Overload; Function VectorCreate4D(Const V:Vector3D):Vector4D;Overload; // Multiplies two Vector4Ds Function Vector4DMultiply(Const A,B:Vector4D):Vector4D; Function Vector4DAdd(Const A,B:Vector4D):Vector4D; Function Vector4DScale(Const A:Vector4D; Const Value:Single):Vector4D; // Returns the dot product between two vectors Function Vector4DDot(Const A,B:Vector4D):Single; {$IFDEF FPC}Inline;{$ENDIF} Implementation Uses Math{$IFDEF SSE},TERRA_SSE{$ENDIF}{$IFDEF NEON_FPU},TERRA_NEON{$ENDIF}; Function VectorCreate4D(Const X,Y,Z,W:Single):Vector4D; Begin Result.X := X; Result.Y := Y; Result.Z := Z; Result.W := W; End; Function VectorCreate4D(Const V:Vector3D):Vector4D; Begin Result.X := V.X; Result.Y := V.Y; Result.Z := V.Z; Result.W := 1.0; End; Function Vector4D.Length:Single; Begin Result := Sqrt(Sqr(X) + Sqr(Y) + Sqr(Z) + Sqr(W)); End; Function Vector4D.Equals(Const B:Vector4D):Boolean; Begin Result := (Self.X=B.X) And (Self.Y=B.Y) And(Self.Z=B.Z) And(Self.W=B.W); End; Function Vector4DDot(Const A,B:Vector4D):Single; {$IFDEF FPC}Inline;{$ENDIF} Begin {$IFDEF NEON_FPU} Result := dot4_neon_hfp(@A,@B); {$ELSE} Result := (A.X*B.X)+(A.Y*B.Y)+(A.Z*B.Z)+(A.W*B.W); {$ENDIF} End; Function Vector4DMultiply(Const A,B:Vector4D):Vector4D; Begin Result.X := A.X * B.X; Result.Y := A.Y * B.Y; Result.Z := A.Z * B.Z; Result.W := A.W * B.W; End; {$IFDEF SSE} {$IFDEF BENCHMARK} Procedure Vector4D.NormalizeSSE; Register; {$ELSE} Procedure Vector4D.Normalize; Register; {$ENDIF} Asm movups xmm0, [eax] movaps xmm2, xmm0 // store copy of the vector mulps xmm0, xmm0 // xmm0 = (sqr(x), sqr(y), sqr(z), sqr(w)) movaps xmm1, xmm0 movaps xmm3, xmm0 shufps xmm1, xmm1, 55h // xmm1 = (sqr(y), sqr(y), sqr(y), sqr(y)) addps xmm1, xmm0 // add both shufps xmm0, xmm0, 0AAh // xmm1 = (sqr(z), sqr(z), sqr(z), sqr(z)) addps xmm0, xmm1 // sum x + y + z shufps xmm3, xmm3, 0FFh // xmm2 = (sqr(w), sqr(w), sqr(w), sqr(w)) addps xmm0, xmm3 // sum all shufps xmm0, xmm0, 0h // broadcast length xorps xmm1, xmm1 ucomiss xmm0, xmm1 // check for zero length je @@END rsqrtps xmm0, xmm0 // get reciprocal of length of vector mulps xmm2, xmm0 // normalize movups [eax], xmm2 // store normalized result @@END: End; {$ENDIF} {$IFDEF BENCHMARK}{$UNDEF SSE}{$ENDIF} {$IFNDEF SSE} Procedure Vector4D.Normalize; Var Len:Single; {$IFDEF NEON_FPU} Temp:Vector4D; {$ENDIF} Begin {$IFDEF NEON_FPU} Temp := Self; normalize4_neon(@Temp, @Self); {$ELSE} Len := Sqrt(Sqr(X) + Sqr(Y) + Sqr(Z) + Sqr(W)); If (Len<=0) Then Exit; Len := 1.0 / Len; X := X * Len; Y := Y * Len; Z := Z * Len; W := W * Len; {$ENDIF} End; {$IFDEF BENCHMARK} {$ENDIF} {$ENDIF} {$IFDEF BENCHMARK}{$DEFINE SSE}{$ENDIF} Procedure Vector4D.Add(Const B:Vector4D); Begin X := X + B.X; Y := Y + B.Y; Z := Z + B.Z; W := W + B.W; End; Procedure Vector4D.Subtract(Const B:Vector4D); Begin X := X - B.X; Y := Y - B.Y; Z := Z - B.Z; W := W - B.W; End; Procedure Vector4D.Scale(Const V:Single); Begin X := X * V; Y := Y * V; Z := Z * V; W := W * V; End; Function Vector4DAdd(Const A,B:Vector4D):Vector4D; Begin With Result Do Begin X := A.X + B.X; Y := A.Y + B.Y; Z := A.Z + B.Z; W := A.W + B.W; End; End; Function Vector4DScale(Const A:Vector4D; Const Value:Single):Vector4D; Begin With Result Do Begin X := A.X * Value; Y := A.Y * Value; Z := A.Z * Value; W := A.W * Value; End; End; {$IFDEF SSE} {$IFDEF BENCHMARK} Procedure Vector4D.TransformSSE(Const M:Matrix4x4); Register; {$ELSE} Procedure Vector4D.Transform(Const M:Matrix4x4); Register; {$ENDIF} Asm // copy vector, Matrix4x4 and result vector to registers mov ecx, eax mov edx, M movups xmm4, [edx] movups xmm5, [edx+$10] movups xmm6, [edx+$20] movups xmm7, [edx+$30] // calc x * m_1X movss xmm0, [ecx] shufps xmm0, xmm0, 0 //mulps xmm0, [edx] mulps xmm0, xmm4 // calc y * m_2X movss xmm1, [ecx+4] shufps xmm1, xmm1, 0 //mulps xmm1, [edx+16] mulps xmm1, xmm5 // calc z * m_3X movss xmm2, [ecx+8] shufps xmm2, xmm2, 0 //mulps xmm2, [edx+32] mulps xmm2, xmm6 // calc w * m_3X movss xmm3, [ecx+12] shufps xmm3, xmm3, 0 //mulps xmm3, [edx+48] mulps xmm3, xmm7 // calc final result addps xmm0, xmm1 addps xmm2, xmm3 addps xmm0, xmm2 // save result movups [eax], xmm0 End; {$ENDIF} {$IFDEF BENCHMARK}{$UNDEF SSE}{$ENDIF} {$IFNDEF SSE} Procedure Vector4D.Transform(Const M:Matrix4x4); {$IFDEF FPC}Inline;{$ENDIF} Var QX,QY,QZ,QW:Single; {$IFDEF NEON_FPU} Temp:Vector4D; {$ENDIF} Begin {$IFDEF NEON_FPU} Temp := Self; matvec4_neon(@M,@Temp,@Self); {$ELSE} QX := X; QY := Y; QZ := Z; QW := W; X := QX*M.V[0] + QY*M.V[4] + QZ*M.V[8] + QW*M.V[12]; Y := QX*M.V[1] + QY*M.V[5] + QZ*M.V[9] + QW*M.V[13]; Z := QX*M.V[2] + QY*M.V[6] + QZ*M.V[10] + QW*M.V[14]; W := QX*M.V[3] + QY*M.V[7] + QZ*M.V[11] + QW*M.V[15]; {$ENDIF} End; {$ENDIF} End.
unit MainU; interface uses Winapi.Windows, System.Actions, Winapi.Messages, System.SysUtils, System.UITypes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Grids, Vcl.ActnList, System.Classes, Vcl.AppEvnts, TileU, GameBoardU, Vcl.ExtCtrls, TransparentPanelU; type TFormMain = class(TForm) actDown: TAction; actExit: TAction; ActionList1: TActionList; actLeft: TAction; actRestart: TAction; actRight: TAction; actUp: TAction; GameBoardGrid: TStringGrid; Panel1: TPanel; Label1: TLabel; Label2: TLabel; Panel2: TPanel; Label3: TLabel; Label4: TLabel; Shape1: TShape; Shape2: TShape; Label5: TLabel; Label6: TLabel; LabelScore: TLabel; LabelBest: TLabel; procedure actExitExecute(Sender: TObject); procedure ActionList1Update(Action: TBasicAction; var Handled: Boolean); procedure actLeftExecute(Sender: TObject); procedure actRestartExecute(Sender: TObject); procedure FormClose(aSender: TObject; var aAction: TCloseAction); procedure FormCreate(aSender: TObject); procedure FormResize(Sender: TObject); procedure GameBoardGridDrawCell(aSender: TObject; aCol: Integer; aRow: Integer; aRect: TRect; aState: TGridDrawState); private procedure OnGameStateChanged(const aOldState, aNewState: TGameState); procedure UpdateScreen; end; var FormMain: TFormMain; implementation uses System.StrUtils, HighscoreU; {$R *.dfm} procedure TFormMain.actExitExecute(Sender: TObject); begin if (GameBoard.Score = 0) or (MessageDlg('Exit the game?', mtConfirmation, [mbOK, mbCancel], 0) = mrOK) then Application.Terminate; end; procedure TFormMain.ActionList1Update(Action: TBasicAction; var Handled: Boolean); begin UpdateScreen; end; procedure TFormMain.actLeftExecute(Sender: TObject); begin GameBoard.Swap(TDirection((Sender as TComponent).Tag)); end; procedure TFormMain.actRestartExecute(Sender: TObject); begin if (GameBoard.Score = 0) or (MessageDlg('Restart game?', mtConfirmation, [mbYes, mbNo], 0) = mrYes) then GameBoard.NewGame; end; procedure TFormMain.FormClose(aSender: TObject; var aAction: TCloseAction); begin actExit.Execute; end; procedure TFormMain.FormCreate(aSender: TObject); const NoSelection: TGridRect = (Left: 0; Top: - 1; Right: 0; Bottom: - 1); begin with TTransparentPanel.Create(Self) do begin Parent := Self; Align := alClient; end; Application.ActionUpdateDelay := 1; GameBoardGrid.Selection := NoSelection; GameBoardGrid.DoubleBuffered := True; GameBoard.NewGame.OnGameStateChanged := OnGameStateChanged; end; procedure TFormMain.FormResize(Sender: TObject); begin with GameBoardGrid do begin DefaultRowHeight := (ClientHeight - (RowCount - 1) * GridLineWidth) div RowCount; DefaultColWidth := (ClientWidth - (ColCount - 1) * GridLineWidth) div ColCount; end; end; procedure TFormMain.GameBoardGridDrawCell(aSender: TObject; aCol: Integer; aRow: Integer; aRect: TRect; aState: TGridDrawState); var CellCenter: TPoint; TextSize: TSize; Tile: TTile; begin Tile := GameBoard.Tile[aRow + 1, aCol + 1]; GameBoardGrid.Canvas.FillRect(aRect); GameBoardGrid.Canvas.Brush.Color := Tile.Color; GameBoardGrid.Canvas.Font.Color := Tile.TextColor; GameBoardGrid.Canvas.Font.Style := [fsBold]; GameBoardGrid.Canvas.Font.Size := 22; GameBoardGrid.Canvas.Font.Name := 'Tahoma'; TextSize := GameBoardGrid.Canvas.TextExtent(Tile.Caption); CellCenter.Y := (aRect.Bottom - aRect.Top) div 2 + aRect.Top; CellCenter.X := (aRect.Right - aRect.Left) div 2 + aRect.Left; GameBoardGrid.Canvas.TextRect(aRect, CellCenter.X - TextSize.cx div 2, CellCenter.Y - TextSize.cy div 2, Tile.Caption); end; procedure TFormMain.OnGameStateChanged(const aOldState, aNewState: TGameState); var Message: String; Player: String; begin case aNewState of gsLost: message := 'You lost with %d points. Click "OK" to try again.'; gsWon: message := 'You won with %d points. Click "OK" to restart or "Cancel" to continue.'; gsHiScore: begin Player := InputBox(Application.Title, 'You have set a new high score, please enter your name', ''); if Player <> '' then Highscore.WriteHighScore(Player, GameBoard.Score); LabelBest.Caption := Highscore.ReadScore.ToString; end; end; if aNewState in [gsLost, gsWon] then if MessageDlg(Format(message, [GameBoard.Score]), mtCustom, [mbOK], 0) = mrOK then GameBoard.NewGame; end; procedure TFormMain.UpdateScreen; var Row: Integer; Col: Integer; begin for Row := 0 to GameBoardGrid.RowCount - 1 do for Col := 0 to GameBoardGrid.ColCount - 1 do GameBoardGrid.Cells[Col, Row] := GameBoard.Tile[Row + 1, Col + 1].Caption; LabelScore.Caption := GameBoard.Score.ToString; LabelBest.Caption := Highscore.ReadScore.ToString; end; end.
program Candy; {$F+} type shape = (round, rectangular, triangular) ; filling = (liquor, nuts, nougat) ; candy_fxn = function(dim1, dim2:real):real ; const ShapeString : array [shape] of string = ('round', 'rectangular', 'triangular'); FillString : array [filling] of string = ('liquor', 'nuts', 'nougat'); var top: shape ; fill: filling ; hite, dim1, dim2, candy_wt: real ; input_param: string ; response: char ; function surface_round(radius, nought:real):real ; begin surface_round := Pi * radius * radius ; end; function surface_rectangular(side1, side2:real):real ; begin surface_rectangular := side1 * side2 ; end; function surface_triangular(base, height:real):real ; begin surface_triangular := 0.5 * base * height ; end; function total_weight(surface:candy_fxn; shape_param:shape; fill_param:filling; height,dim1,dim2:real):real ; var unit_weight_of_filling: integer ; begin unit_weight_of_filling := ord(fill_param) + 2 ; total_weight := surface(dim1, dim2) * height * unit_weight_of_filling ; end; begin writeln('Mark Sattolo 428500, CSI3125, DGD-2, Homework#4') ; writeln ; repeat candy_wt := 0.0 ; (*just to keep the compiler quiet*) write('Enter the shape of the candy top: '); readln(input_param); top := round ; while (top < triangular) and (ShapeString[top] <> input_param) do inc(top) ; write('Enter the type of filling: '); readln(input_param); fill := liquor ; while (fill < nougat) and (FillString[fill] <> input_param) do inc(fill) ; write('Enter the height of the candy: '); readln(hite); write('Enter the dimensions of the top: '); readln(dim1, dim2); case top of round: candy_wt := total_weight(surface_round, round, fill, hite, dim1, dim2) ; rectangular: candy_wt := total_weight(surface_rectangular, rectangular, fill, hite, dim1, dim2) ; triangular: candy_wt := total_weight(surface_triangular, triangular, fill, hite, dim1, dim2) ; end;(*case*) writeln('This is a ', ShapeString[top], ' candy filled with ', FillString[fill], ' which weighs ', candy_wt:6:2, ' grams.') ; writeln; write('Another candy to enter? [Y/N] '); readln(response) ; until response in ['N', 'n'] ; writeln('It''s been a pleasure serving you - bye for now.') ; end.
object Form3: TForm3 Left = 295 Top = 255 BorderStyle = bsDialog Caption = 'Informa'#231#245'es de Jogo' ClientHeight = 147 ClientWidth = 439 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] OldCreateOrder = False PixelsPerInch = 96 TextHeight = 13 object Memo1: TMemo Left = 0 Top = 0 Width = 437 Height = 145 Lines.Strings = ( 'Escolha seu personagem, distribua pontos como preferir.' 'Pontos:' 'For'#231'a: Dados de ataque caso em sua vez caia em um quadro j'#225' ocup' + 'ado' 'Destrteza: Dados de defesa caso algu'#233'm caia em um quadrado ocupa' + 'do por voc'#234 'Movimento: B'#244'nus de movimento. Ap'#243's andar, voc'#234' escolhe a dire'#231#227 + 'o que quer andar' 'a mais, ent'#227'o anda o equivalente a seu total de pontos. O uso de' + 'sta habilidade '#233' opcional.' 'Jogo:' 'Cada cor no tabuleiro representa algo, batalha, item, passagem s' + 'ecreta, etc.....' 'O objetivo do jogo '#233' roubar ao menos um ovo de drag'#227'o e retornar' + ' para o in'#237'cio sem que ' 'algu'#233'm o ven'#231'a em batalha.') ReadOnly = True TabOrder = 0 end end
unit TickServiceMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.SvcMgr, Vcl.Dialogs, Vcl.ExtCtrls, OverbyteApSrvCli, TicklerTypes, TTSDirectDaapi, ProgramSettings, TickServCore; type TsvcTicklerServer = class(TService) procedure ServiceCreate(Sender: TObject); procedure ServiceDestroy(Sender: TObject); procedure ServiceStart(Sender: TService; var Started: Boolean); procedure ServiceStop(Sender: TService; var Stopped: Boolean); private fSettings: TProgramSettings; fCoreServer: TTickCoreServer; procedure ClientConnected(Sender: TObject; CliWSocket: TClientWSocket); public function GetServiceController: TServiceController; override; end; var svcTicklerServer: TsvcTicklerServer; implementation {$R *.dfm} procedure ServiceController(CtrlCode: DWord); stdcall; begin svcTicklerServer.Controller(CtrlCode); end; procedure TsvcTicklerServer.ServiceCreate(Sender: TObject); begin fSettings := TProgramSettings.Create(nil); fSettings.RegistryKey := 'Software\FFS\TicklerServer\'; if ParamCount = 0 then fSettings.RegistryKey := fSettings.RegistryKey + 'Tickler Server\' else fSettings.RegistryKey := fSettings.RegistryKey + ParamStr(1) + '\'; fSettings.ReadSettings; if fSettings.DirWork.IsEmpty then fSettings.DirWork := 'C:\TicklerData\'; fCoreServer := TTickCoreServer.Create(fSettings.DirWork, fSettings.ServerPort); fCoreServer.MidwareServer.OnClientConnected := ClientConnected; end; procedure TsvcTicklerServer.ServiceDestroy(Sender: TObject); begin fSettings.Free; fCoreServer.Free; end; procedure TsvcTicklerServer.ServiceStart(Sender: TService; var Started: Boolean); begin fCoreServer.Start; end; procedure TsvcTicklerServer.ServiceStop(Sender: TService; var Stopped: Boolean); begin fCoreServer.Stop; end; procedure TsvcTicklerServer.ClientConnected(Sender: TObject; CliWSocket: TClientWSocket); begin // Limit the number of users, unless this is still a trial period if (fCoreServer.MidwareServer.ClientCount > fCoreServer.PrivDaapi.SecureGetNumberOfUsers) and fCoreServer.PrivDaapi.SecureRegistered then CliWSocket.Close; end; function TsvcTicklerServer.GetServiceController: TServiceController; begin Result := ServiceController; end; end.
unit TestWSController; {$ifndef VER3}{$fatal WS tests requires FPC 3}{$endif} {$mode objfpc}{$H+} interface uses Classes, typinfo, HTTPDefs, fpcunit, JCoreWSIntf, JCoreWSInvokers, JCoreWSRequest, JCoreWSController; type { TTestWSMethodRegistry } TTestWSMethodRegistry = class(TTestCase) private procedure ProcObj(const AObject: TObject); function FncObj: TObject; private FMethodData: TJCoreWSMethodData; FRegistry: IJCoreWSMethodRegistry; function GetRegistry: IJCoreWSMethodRegistry; protected function CreateMethodData(const AMethodTypeInfo: PTypeInfo): TJCoreWSMethodData; procedure TearDown; override; property Registry: IJCoreWSMethodRegistry read GetRegistry; published procedure WithAmbiguity; procedure WithInheritance; procedure WithoutConflict; procedure EmptyList; procedure InvokerNotFound; end; { TTestWSControllerClass } TTestWSControllerClass = class(TTestCase) private FController: TJCoreWSControllerClass; FRegistry: IJCoreWSMethodRegistry; protected function CreateController(const AClass: TClass; const ANane: string = ''): TJCoreWSControllerClass; procedure RegisterInvokers(const AInvokers: array of TJCoreWSMethodInvokerClass); procedure SetUp; override; procedure TearDown; override; published procedure ValidControllerName; procedure ParamControllerName; procedure UnsupportedMethod; procedure InvokeFunctionRead; procedure InvokeProcedureSave; end; { TTestWSControllerRequest } TTestWSControllerRequest = class(TTestCase) private FControllers: TJCoreWSRESTRequestHandler; FRequest: TRequest; FResponse: TResponse; FRouter: IJCoreWSRequestRouter; protected procedure SetUp; override; procedure TearDown; override; property Router: IJCoreWSRequestRouter read FRouter; property Controllers: TJCoreWSRESTRequestHandler read FControllers; property Request: TRequest read FRequest; property Response: TResponse read FResponse; published procedure ImplicitFncObjInvoker; procedure ImplicitProcObjInvoker; procedure InvokeForMethodGet; procedure InvokeForMethodPost; procedure MethodPattern; procedure NotFoundIfPatternUnread; procedure NotFoundIfPathInfoUnread; end; { TTestRequest } TTestRequest = class(TRequest) end; { TTestResponse } TTestResponse = class(TResponse) protected procedure DoSendContent; override; procedure DoSendHeaders(Headers: TStrings); override; end; { TTestInvokerProc } TTestInvokerProc = class(TJCoreWSMethodInvoker) public function Match(const AMethodData: TJCoreWSMethodData): Boolean; override; procedure Invoke(const AMethodData: TJCoreWSMethodData; const ARequest: TRequest; const AResponse: TResponse; const AMethod: TMethod); override; end; { TTestInvokerProcAmbiguous } TTestInvokerProcAmbiguous = class(TJCoreWSMethodInvoker) public function Match(const AMethodData: TJCoreWSMethodData): Boolean; override; procedure Invoke(const AMethodData: TJCoreWSMethodData; const ARequest: TRequest; const AResponse: TResponse; const AMethod: TMethod); override; end; { TTestInvokerProcInherited } TTestInvokerProcInherited = class(TTestInvokerProc) public function Match(const AMethodData: TJCoreWSMethodData): Boolean; override; procedure Invoke(const AMethodData: TJCoreWSMethodData; const ARequest: TRequest; const AResponse: TResponse; const AMethod: TMethod); override; end; { TTestInvokerFnc } TTestInvokerFnc = class(TJCoreWSMethodInvoker) public function Match(const AMethodData: TJCoreWSMethodData): Boolean; override; procedure Invoke(const AMethodData: TJCoreWSMethodData; const ARequest: TRequest; const AResponse: TResponse; const AMethod: TMethod); override; end; { TClient } TClient = class(TPersistent) private FName: string; published property Name: string read FName write FName; end; { TClientController } TClientController = class(TPersistent) public class var ReadingName: string; class var WritingName: string; published function Get: TClient; procedure Post(const AClient: TClient); function Read: TClient; procedure Save(const AClient: TClient); end; { TProduct } TProduct = class(TPersistent) private FDescription: string; published property Description: string read FDescription write FDescription; end; { TProductController } TProductController = class(TPersistent) public class var Data: string; published function Read: TProduct; procedure Save(const AProduct: TProduct); end; { TTestClientInvokerController } TTestClientInvokerController = class(TJCoreWSMethodInvoker) public destructor Destroy; override; class var Data: string; function Match(const AMethodData: TJCoreWSMethodData): Boolean; override; procedure Invoke(const AMethodData: TJCoreWSMethodData; const ARequest: TRequest; const AResponse: TResponse; const AMethod: TMethod); override; end; TTestMethodRegistry = class(TJCoreWSMethodRegistry) end; implementation uses sysutils, testregistry, JCoreClasses, JCoreDIC; { TTestWSMethodRegistry } procedure TTestWSMethodRegistry.ProcObj(const AObject: TObject); begin end; function TTestWSMethodRegistry.FncObj: TObject; begin Result := nil; end; function TTestWSMethodRegistry.GetRegistry: IJCoreWSMethodRegistry; begin if not Assigned(FRegistry) then FRegistry := TJCoreWSMethodRegistry.Create; Result := FRegistry; end; function TTestWSMethodRegistry.CreateMethodData(const AMethodTypeInfo: PTypeInfo): TJCoreWSMethodData; begin FreeAndNil(FMethodData); FMethodData := TJCoreWSMethodData.Create(AMethodTypeInfo); Result := FMethodData; end; procedure TTestWSMethodRegistry.TearDown; begin inherited TearDown; FreeAndNil(FMethodData); FRegistry := nil; end; procedure TTestWSMethodRegistry.WithAmbiguity; begin Registry.AddInvoker([TTestInvokerProc, TTestInvokerProcAmbiguous]); try Registry.FindInvoker(CreateMethodData(TypeInfo(@ProcObj))); Fail('EJCoreWS(3104) expected'); except on E: EJCoreWS do if E.Code <> 3104 then raise; end; end; procedure TTestWSMethodRegistry.WithInheritance; var VInvoker: TJCoreWSMethodInvoker; begin Registry.AddInvoker([TTestInvokerProc, TTestInvokerProcInherited]); VInvoker := Registry.FindInvoker(CreateMethodData(TypeInfo(@ProcObj))); AssertNotNull('invoker', VInvoker); AssertEquals('invoker class', 'TTestInvokerProcInherited', VInvoker.ClassName); end; procedure TTestWSMethodRegistry.WithoutConflict; var VInvoker: TJCoreWSMethodInvoker; begin Registry.AddInvoker([TTestInvokerProc, TTestInvokerFnc]); VInvoker := Registry.FindInvoker(CreateMethodData(TypeInfo(@FncObj))); AssertNotNull('invoker', VInvoker); AssertEquals('invoker class', 'TTestInvokerFnc', VInvoker.ClassName); end; procedure TTestWSMethodRegistry.EmptyList; var VInvoker: TJCoreWSMethodInvoker; begin VInvoker := Registry.FindInvoker(CreateMethodData(TypeInfo(@FncObj))); AssertNull('invoker', VInvoker); end; procedure TTestWSMethodRegistry.InvokerNotFound; var VInvoker: TJCoreWSMethodInvoker; begin Registry.AddInvoker([TTestInvokerProc]); VInvoker := Registry.FindInvoker(CreateMethodData(TypeInfo(@FncObj))); AssertNull('invoker', VInvoker); end; { TTestWSControllerClass } function TTestWSControllerClass.CreateController(const AClass: TClass; const ANane: string ): TJCoreWSControllerClass; begin FreeAndNil(FController); FController := TJCoreWSControllerClass.Create(AClass, ANane); Result := FController; end; procedure TTestWSControllerClass.RegisterInvokers(const AInvokers: array of TJCoreWSMethodInvokerClass); begin FRegistry.AddInvoker(AInvokers); end; procedure TTestWSControllerClass.SetUp; begin inherited SetUp; TJCoreDIC.Register(IJCoreWSMethodRegistry, TTestMethodRegistry, jdsApplication); TJCoreDIC.Locate(IJCoreWSMethodRegistry, FRegistry); TClientController.ReadingName := '<unset>'; TClientController.WritingName := '<unset>'; TTestClientInvokerController.Data := ''; end; procedure TTestWSControllerClass.TearDown; begin inherited TearDown; FRegistry := nil; FreeAndNil(FController); TJCoreDIC.Unregister(IJCoreWSMethodRegistry, TTestMethodRegistry); end; procedure TTestWSControllerClass.ValidControllerName; begin AssertEquals('controller name', 'client', CreateController(TClientController).ControllerURLFrag); end; procedure TTestWSControllerClass.ParamControllerName; begin AssertEquals('controller name', 'cli', CreateController(TClientController, 'cli').ControllerURLFrag); end; procedure TTestWSControllerClass.UnsupportedMethod; var VController: TJCoreWSControllerClass; VMethod: TJCoreWSControllerMethod; begin VController := CreateController(TClientController); VController.AddMethod(@TClientController.Get, TypeInfo(@TClientController.Get)); VMethod := VController.FindMethod('get'); AssertNotNull('method not null', VMethod); try VMethod.HandleRequest(nil, nil); Fail('EJCoreWS(3101) expected'); except on E: EJCoreWS do if E.Code <> 3101 then raise; end; end; procedure TTestWSControllerClass.InvokeFunctionRead; var VController: TJCoreWSControllerClass; VMethod: TJCoreWSControllerMethod; begin RegisterInvokers([TTestClientInvokerController]); VController := CreateController(TClientController); VController.AddMethod(@TClientController.Read, TypeInfo(@TClientController.Read)); VMethod := VController.FindMethod('read'); AssertNotNull('method not null', VMethod); TClientController.ReadingName := 'joe'; VMethod.HandleRequest(nil, nil); AssertEquals('client name', 'joe', TTestClientInvokerController.Data); end; procedure TTestWSControllerClass.InvokeProcedureSave; var VController: TJCoreWSControllerClass; VMethod: TJCoreWSControllerMethod; begin RegisterInvokers([TTestClientInvokerController]); VController := CreateController(TClientController); VController.AddMethod(@TClientController.Save, TypeInfo(@TClientController.Save)); VMethod := VController.FindMethod('save'); AssertNotNull('method not null', VMethod); TClientController.ReadingName := 'jack'; VMethod.HandleRequest(nil, nil); AssertEquals('client name', 'jack', TClientController.WritingName); end; { TTestWSControllerRequest } procedure TTestWSControllerRequest.SetUp; begin inherited SetUp; FRouter := TJCoreWSRESTRequestRouter.Create; FControllers := TJCoreWSRESTRequestHandler.Create; FRouter.AddRequestHandler(FControllers, '/api'); FRequest := TTestRequest.Create; FResponse := TTestResponse.Create(FRequest); FResponse.Contents.LineBreak := '\n'; TClientController.ReadingName := '<unset>'; TClientController.WritingName := '<unset>'; end; procedure TTestWSControllerRequest.TearDown; begin inherited TearDown; FreeAndNil(FResponse); FreeAndNil(FRequest); FRouter := nil; end; procedure TTestWSControllerRequest.ImplicitFncObjInvoker; begin Controllers.AddController(TClientController). AddMethod(@TClientController.Read, TypeInfo(@TClientController.Read)); Request.PathInfo := '/api/client/read'; TClientController.ReadingName := 'bill'; Router.RouteRequest(Request, Response); AssertEquals('response content', '{"Name":"bill"}\n', Response.Content); AssertEquals('response code', 200, Response.Code); end; procedure TTestWSControllerRequest.ImplicitProcObjInvoker; begin Controllers.AddController(TClientController). AddMethod(@TClientController.Save, TypeInfo(@TClientController.Save)); Request.PathInfo := '/api/client/save'; Request.Content:='{ "Name": "jack" }'; Router.RouteRequest(Request, Response); AssertEquals('client name', 'jack', TClientController.WritingName); AssertEquals('response code', 200, Response.Code); end; procedure TTestWSControllerRequest.InvokeForMethodGet; begin Controllers.AddController(TClientController). AddMethod(@TClientController.Get, TypeInfo(@TClientController.Get)); Request.Method := 'GET'; Request.PathInfo := '/api/client'; TClientController.ReadingName := 'john'; Router.RouteRequest(Request, Response); AssertEquals('response content', '{"Name":"john"}\n', Response.Content); AssertEquals('response code', 200, Response.Code); end; procedure TTestWSControllerRequest.InvokeForMethodPost; begin Controllers.AddController(TClientController). AddMethod(@TClientController.Post, TypeInfo(@TClientController.Post)); Request.Method := 'POST'; Request.PathInfo := '/api/client'; Request.Content:='{ "Name": "Jack" }'; Router.RouteRequest(Request, Response); AssertEquals('client name', 'Jack', TClientController.WritingName); AssertEquals('response code', 200, Response.Code); end; procedure TTestWSControllerRequest.MethodPattern; begin Controllers.AddController(TClientController). AddMethod(@TClientController.Read, TypeInfo(@TClientController.Read), ':id'); Request.PathInfo := '/api/client/read/14'; TClientController.ReadingName := 'jimmy'; Router.RouteRequest(Request, Response); AssertEquals('id', '14', Request.QueryFields.Values['id']); AssertEquals('client name', '{"Name":"jimmy"}\n', Response.Content); AssertEquals('response code', 200, Response.Code); end; procedure TTestWSControllerRequest.NotFoundIfPatternUnread; begin Controllers.AddController(TClientController). AddMethod(@TClientController.Read, TypeInfo(@TClientController.Read), ':id'); Request.PathInfo := '/api/client/read'; Router.RouteRequest(Request, Response); AssertEquals('response code', 404, Response.Code); end; procedure TTestWSControllerRequest.NotFoundIfPathInfoUnread; begin Controllers.AddController(TClientController). AddMethod(@TClientController.Read, TypeInfo(@TClientController.Read)); Request.PathInfo := '/api/client/read/14'; Router.RouteRequest(Request, Response); AssertEquals('response code', 404, Response.Code); end; { TTestResponse } procedure TTestResponse.DoSendContent; begin end; procedure TTestResponse.DoSendHeaders(Headers: TStrings); begin end; { TTestInvokerProc } function TTestInvokerProc.Match(const AMethodData: TJCoreWSMethodData): Boolean; begin Result := AMethodData.MatchProcedure([TObject]); end; procedure TTestInvokerProc.Invoke(const AMethodData: TJCoreWSMethodData; const ARequest: TRequest; const AResponse: TResponse; const AMethod: TMethod); begin end; { TTestInvokerProcAmbiguous } function TTestInvokerProcAmbiguous.Match(const AMethodData: TJCoreWSMethodData): Boolean; begin Result := AMethodData.MatchProcedure([TObject]); end; procedure TTestInvokerProcAmbiguous.Invoke(const AMethodData: TJCoreWSMethodData; const ARequest: TRequest; const AResponse: TResponse; const AMethod: TMethod); begin end; { TTestInvokerProcInherited } function TTestInvokerProcInherited.Match(const AMethodData: TJCoreWSMethodData): Boolean; begin Result := AMethodData.MatchProcedure([TObject]); end; procedure TTestInvokerProcInherited.Invoke(const AMethodData: TJCoreWSMethodData; const ARequest: TRequest; const AResponse: TResponse; const AMethod: TMethod); begin end; { TTestInvokerFnc } function TTestInvokerFnc.Match(const AMethodData: TJCoreWSMethodData): Boolean; begin Result := AMethodData.MatchFunction([], TObject); end; procedure TTestInvokerFnc.Invoke(const AMethodData: TJCoreWSMethodData; const ARequest: TRequest; const AResponse: TResponse; const AMethod: TMethod); begin end; { TClientController } function TClientController.Get: TClient; begin Result := Read; end; procedure TClientController.Post(const AClient: TClient); begin Save(AClient); end; function TClientController.Read: TClient; begin Result := TClient.Create; Result.Name := ReadingName; end; procedure TClientController.Save(const AClient: TClient); begin WritingName := AClient.Name; end; { TProductController } function TProductController.Read: TProduct; begin Result := TProduct.Create; Result.Description := 'sand'; end; procedure TProductController.Save(const AProduct: TProduct); begin Data := AProduct.Description; end; { TTestClientInvokerController } destructor TTestClientInvokerController.Destroy; begin inherited Destroy; end; function TTestClientInvokerController.Match(const AMethodData: TJCoreWSMethodData): Boolean; begin Result := True; end; procedure TTestClientInvokerController.Invoke(const AMethodData: TJCoreWSMethodData; const ARequest: TRequest; const AResponse: TResponse; const AMethod: TMethod); type TObjectFnc = function: TObject of object; TObjectProc = procedure(const AObject: TObject) of object; var VClient: TClient; begin case AMethodData.MethodKind of mkFunction: begin VClient := TObjectFnc(AMethod)() as TClient; Data := VClient.Name; FreeAndNil(VClient); end; mkProcedure: begin VClient := TClient.Create; try VClient.Name := TClientController.ReadingName; TObjectProc(AMethod)(VClient); finally FreeAndNil(VClient); end; end; end; end; initialization RegisterTest('jcore.ws.controller', TTestWSMethodRegistry); RegisterTest('jcore.ws.controller', TTestWSControllerClass); RegisterTest('jcore.ws.controller', TTestWSControllerRequest); end.
unit main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, Menus; type TForm1 = class(TForm) Button1: TButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation Uses TERRA_Utils, TERRA_Application, TERRA_VCLApplication, TERRA_OS, TERRA_Scene, TERRA_Texture, TERRA_Viewport, TERRA_FileManager, TERRA_SpriteManager, TERRA_PNG, TERRA_GraphicsManager, TERRA_Math, TERRA_Vector2D, TERRA_Color; {$R *.dfm} Type MyScene = Class(Scene) Procedure RenderSprites(V:Viewport); Override; End; Var _Tex:Texture = Nil; _Scene:MyScene; { MyScene } Procedure MyScene.RenderSprites(V: Viewport); Var S:QuadSprite; Angle:Single; Begin // A rotating sprite in the bottom, with Scale = 4x Angle := RAD * ((Application.GetTime() Div 15) Mod 360); S := SpriteManager.Instance.DrawSprite(100, 100, 50, _Tex); S.SetScaleAndRotationRelative(VectorCreate2D(0.5, 0.5), 4.0, Angle); // Calculate rotation, in degrees, from current time End; Procedure TForm1.FormCreate(Sender: TObject); Begin VCLApplication.Create(Self); // Added Asset folder to search path FileManager.Instance.AddPath('assets'); // Load a Tex _Tex := TextureManager.Instance['ghost']; // Create a scene and set it as the current scene _Scene := MyScene.Create; GraphicsManager.Instance.SetScene(_Scene); // set background color GraphicsManager.Instance.ActiveViewport.BackgroundColor := ColorGreen; End; procedure TForm1.FormDestroy(Sender: TObject); begin ReleaseObject(_Scene); Application.Instance.Terminate(); end; procedure TForm1.Button1Click(Sender: TObject); begin Forms.Application.Terminate(); end; end.
unit UPrimsMazeGenerator; //Fully annotated interface uses Classes, SysUtils, UMazeHandler, UListHandler, UInterface, UAStarSearch; type BoolArray = Array of Boolean; procedure Generate(Maze: TMazeHandler); procedure MoveItem(Position: integer; FromThis, ToThis: TListHandler); procedure SetIn(firstCell: Boolean; outMaze, inMaze, frontier: TListHandler; Maze: TMazeHandler); procedure ReturnFrontiersToFind(inMaze, frontier: TListHandler; ItemsToFind: TwoDArray; ItemsToFindLength, MazeLastIndex: integer; var ToBeRemoved: BoolArray); procedure AdjustItemsToFind(CheckedIndex, ItemsToFindLength: integer; var ToSearchList: OneDArray; list: TListHandler); procedure DetermineStartAndFinish(Maze: TMazeHandler); implementation // Adjusts ToSearch considering an item has been removed from the list being // searched procedure AdjustItemsToFind(CheckedIndex, ItemsToFindLength: integer; var ToSearchList: OneDArray; list: TListHandler); var ToCheck: integer; begin if CheckedIndex <> (ItemsToFindLength - 1) then begin for ToCheck := (CheckedIndex + 1) to (ItemsToFindLength - 1) do begin // Checks whether the index referenced in ToSearchList references the last // index before the item was removed if ToSearchList[ToCheck] = (list.getLastIndex + 1) then begin // Changes the reference to the position of the item removed, // which holds the value of what used to be the last index in the list ToSearchList[ToCheck] := ToSearchList[CheckedIndex]; end; end; end; end; // Ensure that the neighbours to a specified cell are not in inMaze procedure ReturnFrontiersToFind(inMaze, frontier: TListHandler; ItemsToFind: TwoDArray; ItemsToFindLength, MazeLastIndex: integer; var ToBeRemoved: BoolArray); var index, indexInMaze, indexNeighbours, LastIndex, NeighboursLength: integer; Neighbours: TwoDArray; begin setLength(ToBeRemoved, ItemsToFindLength); LastIndex := ItemsToFindLength - 1; for index := 0 to LastIndex do begin ToBeRemoved[index] := false; end; for index := 0 to LastIndex do begin setLength(Neighbours, 4, 2); // Finds the neighbours of the specified cell UInterface.ReturnItemsToFind(ItemsToFind[index, 0], ItemsToFind[index, 1], MazeLastIndex, Neighbours, NeighboursLength); for indexInMaze := 0 to inMaze.getLastIndex do begin // Checks that the neighbours of the specified cell against all cells in // inMaze for indexNeighbours := 0 to (NeighboursLength - 1) do begin // If it is a neighbour to another cell, mark it to be removed as a // possibility if (inMaze.GetItem(indexInMaze, 0) = Neighbours[indexNeighbours, 0]) and (inMaze.GetItem(indexInMaze, 1) = Neighbours[indexNeighbours, 1]) then begin ToBeRemoved[index] := true; end; end; end; end; end; // Moves an item from a list to another list, deleting it from the original procedure MoveItem(Position: integer; FromThis, ToThis: TListHandler); begin ToThis.AddItem(FromThis.GetItem(Position, 0), FromThis.GetItem(Position, 1)); FromThis.RemoveItem(Position); end; // Sets a cell to air in the maze, and updates the lists to follow the algorithm procedure SetIn(firstCell: Boolean; outMaze, inMaze, frontier: TListHandler; Maze: TMazeHandler); var x, y, randomIndex, ItemsToFindLength, indexItemsToFind: integer; ItemsToFind: TwoDArray; ToSearchOutMaze, ToSearchFrontier: OneDArray; ToBeRemoved: BoolArray; begin setLength(ItemsToFind, 4, 2); setLength(ToSearchOutMaze, 4); // If the maze has no spaces in it if firstCell then begin // Picks a wall in the maze at random randomIndex := random((outMaze.getLastIndex + 1)); x := outMaze.GetItem(randomIndex, 0); y := outMaze.GetItem(randomIndex, 1); // Finds the frontiers for this wall (the walls adjacent to it) UInterface.ReturnItemsToFind(x, y, Maze.getLastIndex, ItemsToFind, ItemsToFindLength); ToSearchOutMaze := outMaze.FindSetOfItems(ItemsToFind, ItemsToFindLength); // Makes the wall picked a space in the maze Maze.SetEmpty(x, y); MoveItem(randomIndex, outMaze, inMaze); AdjustItemsToFind(0, ItemsToFindLength, ToSearchOutMaze, outMaze); // Adds the frontiers to the frontier list for indexItemsToFind := 0 to (ItemsToFindLength - 1) do begin MoveItem(ToSearchOutMaze[indexItemsToFind], outMaze, frontier); AdjustItemsToFind(indexItemsToFind, ItemsToFindLength, ToSearchOutMaze, outMaze); end; end // If the maze already has space in it else begin setLength(ToSearchFrontier, 4); // Picks the a wall in the maze at random from the frontiers available randomIndex := random((frontier.getLastIndex + 1)); x := frontier.GetItem(randomIndex, 0); y := frontier.GetItem(randomIndex, 1); // Finds the frontiers for this wall UInterface.ReturnItemsToFind(x, y, Maze.getLastIndex, ItemsToFind, ItemsToFindLength); ReturnFrontiersToFind(inMaze, frontier, ItemsToFind, ItemsToFindLength, Maze.getLastIndex, ToBeRemoved); ToSearchOutMaze := outMaze.FindSetOfItems(ItemsToFind, ItemsToFindLength); // Makes the wall picked a space in the maze Maze.SetEmpty(x, y); MoveItem(randomIndex, frontier, inMaze); // Adds the frontiers to the frontier list ToSearchFrontier := frontier.FindSetOfItems(ItemsToFind, ItemsToFindLength); for indexItemsToFind := 0 to (ItemsToFindLength - 1) do begin // If the frontier was found in outMaze if ToSearchOutMaze[indexItemsToFind] <> -1 then begin if ToBeRemoved[indexItemsToFind] then begin outMaze.RemoveItem(ToSearchOutMaze[indexItemsToFind]); end else begin MoveItem(ToSearchOutMaze[indexItemsToFind], outMaze, frontier); end; AdjustItemsToFind(indexItemsToFind, ItemsToFindLength, ToSearchOutMaze, outMaze); end else begin // If the frontier is already a frontier if ToSearchFrontier[indexItemsToFind] <> -1 then begin if ToBeRemoved[indexItemsToFind] then begin frontier.RemoveItem(ToSearchFrontier[indexItemsToFind]); AdjustItemsToFind(indexItemsToFind, ItemsToFindLength, ToSearchFrontier, frontier); end; end; end; end; end; end; // Determines all the possible start and finish cells, and then select a start // and finish cell from them based on the route length produced by an A* Search procedure DetermineStartAndFinish(Maze: TMazeHandler); var PossibleSquares: TwoDArray; MaxSquares, PSLength, x, y, index, startIndex, MazeLength, startX, startY, tempendX, tempendY, routeLength, maxrouteLength: integer; Route: TRoute; begin MazeLength := Maze.GetMazeLength; // Finds the possible start and finish squares MaxSquares := (MazeLength - 2) * 2 + (MazeLength - 4) * 2; setLength(PossibleSquares, MaxSquares, 2); PSLength := 0; for x := 1 to MazeLength - 2 do begin if (Maze.GetWall(x, 1) = false) then begin PossibleSquares[PSLength, 0] := x; PossibleSquares[PSLength, 1] := 0; inc(PSLength); end; if (Maze.GetWall(x, MazeLength - 2) = false) then begin PossibleSquares[PSLength, 0] := x; PossibleSquares[PSLength, 1] := MazeLength - 1; inc(PSLength); end; end; for y := 2 to MazeLength - 3 do begin if (Maze.GetWall(1, y) = false) then begin PossibleSquares[PSLength, 0] := 0; PossibleSquares[PSLength, 1] := y; inc(PSLength); end; if (Maze.GetWall(MazeLength - 2, y) = false) then begin PossibleSquares[PSLength, 0] := MazeLength - 1; PossibleSquares[PSLength, 1] := y; inc(PSLength); end; end; // Uses A star search to find longest path and sets the start and finish // according to this path maxrouteLength := -1; startIndex := random(PSLength - 1); startX := PossibleSquares[startIndex, 0]; startY := PossibleSquares[startIndex, 1]; for index := 0 to (PSLength - 1) do begin if index <> startIndex then begin Maze.SetStartAndFinish(startX, startY, PossibleSquares[index, 0], PossibleSquares[index, 1]); Route := UAStarSearch.FindSolution(Maze); routeLength := length(Route); if routeLength > maxrouteLength then begin tempendX := PossibleSquares[index, 0]; tempendY := PossibleSquares[index, 1]; maxrouteLength := routeLength; end // If they're the same length, pick the one which is closer to the the // start, as this produces a more complex path else if routeLength = maxrouteLength then begin if (abs(PossibleSquares[index, 0] - startX) + abs(PossibleSquares[index, 1] - startY)) < (abs(tempendX - startX) + abs(tempendY - startY)) then begin tempendX := PossibleSquares[index, 0]; tempendY := PossibleSquares[index, 1]; end; end; Maze.UnsetStartAndFinish(startX, startY, PossibleSquares[index, 0], PossibleSquares[index, 1]); end; end; Maze.SetStartAndFinish(startX, startY, tempendX, tempendY); end; // Generate the maze using Prim's Maze Generator algorithm procedure Generate(Maze: TMazeHandler); var frontier, outMaze, inMaze: TListHandler; MazeLength: integer; begin MazeLength := Maze.GetMazeLength; // Initalises lists, completing step 1 of algorithm outMaze := TListHandler.Create(MazeLength, true); frontier := TListHandler.Create(MazeLength, false); inMaze := TListHandler.Create(MazeLength, false); // Carries out step 2 of algorithm SetIn(true, outMaze, inMaze, frontier, Maze); // Carries out step 3 of algorithm while not((frontier.getLastIndex) = -1) do begin SetIn(false, outMaze, inMaze, frontier, Maze); end; // Carries out step 4 of algorithm Maze.AddExternalWalls; DetermineStartAndFinish(Maze); // Destroys classes FreeAndNil(outMaze); FreeAndNil(frontier); FreeAndNil(inMaze); end; end.
unit BaseFormsDesign; interface {$i BaseForms.inc} procedure Register; implementation {$R 'BaseFormsDesign.dcr'} uses BaseForms, Classes, SysUtils, Windows, Graphics, DesignIntf, DesignEditors, ToolsApi, TypInfo, DMForm, WCtlForm; { misc } procedure AddUnitToUses(Module: IOTAModule; UnitName: string); const UnitFileSize = 8192; // 8k ought to be enough for everybody! (we're dealing with a new default unit) var Editor: IOTASourceEditor; Reader: IOTAEditReader; Writer: IOTAEditWriter; Buffer, P: PAnsiChar; StartPos: Integer; begin Buffer := {$IFDEF UNICODE}AnsiStrAlloc{$ELSE}StrAlloc{$ENDIF}(UnitFileSize); Editor := (Module.GetModuleFileEditor(0)) as IOTASourceEditor; try Reader := Editor.CreateReader; try StartPos := Reader.GetText(0, Buffer, UnitFileSize); P := StrPos(Buffer, 'uses'); // Locate uses P := StrPos(P, ';'); // Locate the semi-colon afterwards if Assigned(P) then StartPos := Integer(P - Buffer) else StartPos := -1; finally Reader := nil; { get rid of reader before we use writer } end; if StartPos <> -1 then begin Writer := Editor.CreateWriter; try Writer.CopyTo(StartPos); Writer.Insert(PAnsiChar(AnsiString(', ' + UnitName))); finally Writer := nil; end; end; finally Editor := nil; StrDispose(Buffer); end; end; { TCustomBaseFormWizard } type TCustomBaseFormWizard = class(TNotifierObject, IOTARepositoryWizard, IOTARepositoryWizard60, {$ifdef DELPHI8_UP}IOTARepositoryWizard80,{$endif} {$ifdef DELPHI16_UP}IOTARepositoryWizard160,{$endif} IOTAWizard, IOTAProjectWizard, IOTAFormWizard) protected function ThisFormClass: TComponentClass; virtual; abstract; function ThisUnitName: string; function ThisAncestorName: string; function ThisFormIconName: string; public // IOTARepositoryWizard function GetAuthor: string; function GetComment: string; function GetPage: string; function GetGlyph: Cardinal; // IOTARepositoryWizard60 function GetDesigner: string; {$ifdef DELPHI8_UP} // IOTARepositoryWizard80 function GetGalleryCategory: IOTAGalleryCategory; function GetPersonality: string; {$endif} {$ifdef DELPHI16_UP} // IOTARepositoryWizard160 function GetFrameworkTypes: TArray<string>; function GetPlatforms: TArray<string>; {$endif} // IOTAWizard function GetIDString: string; function GetName: string; virtual; function GetState: TWizardState; procedure Execute; // IOTAProjectWizard // IOTAFormWizard end; TBaseDataModuleWizard = class(TCustomBaseFormWizard) protected function ThisFormClass: TComponentClass; override; public function GetName: string; override; end; TBaseDataModuleModule = TDataModuleCustomModule; TBaseFormWizard = class(TCustomBaseFormWizard) protected function ThisFormClass: TComponentClass; override; public function GetName: string; override; end; TBaseFormModule = class(TCustomModule) class function DesignClass: TComponentClass; override; end; TBaseFrameWizard = class(TCustomBaseFormWizard) protected function ThisFormClass: TComponentClass; override; public function GetName: string; override; end; TBaseFrameModule = class(TWinControlCustomModule) public function Nestable: Boolean; override; end; procedure Register; begin RegisterCustomModule(TBaseDataModule, TBaseDataModuleModule); RegisterPackageWizard(TBaseDataModuleWizard.Create); RegisterCustomModule(TBaseForm, TBaseFormModule); RegisterPackageWizard(TBaseFormWizard.Create); RegisterCustomModule(TBaseFrame, TBaseFrameModule); RegisterPackageWizard(TBaseFrameWizard.Create); end; { TBaseFormCreator } type TBaseFormCreator = class(TInterfacedObject, IOTACreator, IOTAModuleCreator) private FAncestorName: string; public // IOTACreator function GetCreatorType: string; function GetExisting: Boolean; function GetFileSystem: string; function GetOwner: IOTAModule; function GetUnnamed: Boolean; // IOTAModuleCreator function GetAncestorName: string; function GetImplFileName: string; function GetIntfFileName: string; function GetFormName: string; function GetMainForm: Boolean; function GetShowForm: Boolean; function GetShowSource: Boolean; function NewFormFile(const FormIdent, AncestorIdent: string): IOTAFile; function NewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; function NewIntfSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; procedure FormCreated(const FormEditor: IOTAFormEditor); public constructor Create(const AncestorName: string); end; constructor TBaseFormCreator.Create(const AncestorName: string); begin inherited Create; FAncestorName := AncestorName; end; procedure TBaseFormCreator.FormCreated(const FormEditor: IOTAFormEditor); begin end; function TBaseFormCreator.GetAncestorName: string; begin Result := FAncestorName; end; function TBaseFormCreator.GetCreatorType: string; begin Result := sForm; end; function TBaseFormCreator.GetExisting: Boolean; begin Result := False; end; function TBaseFormCreator.GetFileSystem: string; begin Result := ''; end; function TBaseFormCreator.GetFormName: string; begin Result := ''; end; function TBaseFormCreator.GetImplFileName: string; begin Result := ''; end; function TBaseFormCreator.GetIntfFileName: string; begin Result := ''; end; function TBaseFormCreator.GetMainForm: Boolean; begin Result := False; end; function TBaseFormCreator.GetOwner: IOTAModule; begin Result := GetActiveProject; end; function TBaseFormCreator.GetShowForm: Boolean; begin Result := True; end; function TBaseFormCreator.GetShowSource: Boolean; begin Result := True; end; function TBaseFormCreator.GetUnnamed: Boolean; begin Result := True; end; function TBaseFormCreator.NewFormFile(const FormIdent, AncestorIdent: string): IOTAFile; begin Result := nil; end; function TBaseFormCreator.NewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; begin Result := nil; end; function TBaseFormCreator.NewIntfSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; begin Result := nil; end; { TCustomBaseFormWizard } function TCustomBaseFormWizard.ThisUnitName: string; begin Result := string(GetTypeData(PTypeInfo(ThisFormClass.ClassInfo)).UnitName); end; function TCustomBaseFormWizard.ThisAncestorName: string; begin Result := ThisFormClass.ClassName; Delete(Result, 1, 1); // drop the 'T' end; function TCustomBaseFormWizard.ThisFormIconName: string; begin Result := UpperCase(ThisFormClass.ClassName); end; function TCustomBaseFormWizard.GetAuthor: string; begin Result := 'delphinotes.ru'; end; function TCustomBaseFormWizard.GetComment: string; begin Result := ''; end; function TCustomBaseFormWizard.GetPage: string; begin Result := 'New'; end; function TCustomBaseFormWizard.GetGlyph: Cardinal; begin Result := LoadIcon(HInstance, PChar(ThisFormIconName)); end; function TCustomBaseFormWizard.GetDesigner: string; begin Result := dVCL; end; {$ifdef DELPHI8_UP} function TCustomBaseFormWizard.GetGalleryCategory: IOTAGalleryCategory; var Category: IOTAGalleryCategory; CatManager: IOTAGalleryCategoryManager; begin CatManager := (BorlandIDEServices as IOTAGalleryCategoryManager); Assert(Assigned(CatManager)); Category := CatManager.FindCategory(sCategoryDelphiNewFiles); Assert(Assigned(Category)); Result := Category; end; function TCustomBaseFormWizard.GetPersonality: string; begin Result := sDelphiPersonality; end; {$endif} {$ifdef DELPHI16_UP} function TCustomBaseFormWizard.GetFrameworkTypes: TArray<string>; begin SetLength(Result, 1); Result[0] := sFrameworkTypeVCL; end; function TCustomBaseFormWizard.GetPlatforms: TArray<string>; begin SetLength(Result, 1); Result[0] := 'Win32'; end; {$endif} function TCustomBaseFormWizard.GetIDString: string; begin Result := 'DelphiNotes.New' + ThisAncestorName + '.Wizard'; end; function TCustomBaseFormWizard.GetName: string; begin Result := ThisAncestorName; end; function TCustomBaseFormWizard.GetState: TWizardState; begin Result := [wsEnabled]; end; procedure TCustomBaseFormWizard.Execute; var ModuleServices: IOTAModuleServices; Creator: IOTACreator; Module: IOTAModule; begin ModuleServices := (BorlandIDEServices as IOTAModuleServices); Creator := TBaseFormCreator.Create(ThisAncestorName); Module := ModuleServices.CreateModule(Creator); AddUnitToUses(Module, ThisUnitName); end; { TBaseDataModuleWizard } function TBaseDataModuleWizard.ThisFormClass: TComponentClass; begin Result := TBaseDataModule; end; function TBaseDataModuleWizard.GetName: string; begin Result := 'Base Data Module'; end; { TBaseFormWizard } function TBaseFormWizard.ThisFormClass: TComponentClass; begin Result := TBaseForm; end; function TBaseFormWizard.GetName: string; begin Result := 'Base Form'; end; { TBaseFormModule } class function TBaseFormModule.DesignClass: TComponentClass; begin Result := TBaseForm; end; { TBaseFrameModule } function TBaseFrameModule.Nestable: Boolean; begin Result := True; end; { TBaseFrameWizard } function TBaseFrameWizard.ThisFormClass: TComponentClass; begin Result := TBaseFrame; end; function TBaseFrameWizard.GetName: string; begin Result := 'Base Frame'; end; end.
unit HighScoreU; interface uses System.Win.Registry, WinApi.Windows; type THighScoreRecord = record Player: String; Score: Integer; end; THighScore = class private const KEY_PLAYER: String = 'Player'; KEY_SCORE: String = 'Score'; Section = 'High Score'; var FInifile: TRegistryIniFile; class var FInstance: THighScore; constructor Create; reintroduce; function ReadInteger(const Ident: String): Integer; function ReadString(const Ident: String): String; procedure WriteInteger(const Ident: String; Value: Integer); procedure WriteString(const Ident, Value: String); public class destructor Destroy; destructor Destroy; override; procedure DeleteHighScore; function HasHighScore: Boolean; function ReadHighScore: THighScoreRecord; function ReadPlayer: String; function ReadScore: Integer; procedure WriteHighScore(const aPlayer: String; const aScore: Integer); overload; procedure WriteHighScore(const aHighScore: THighScoreRecord); overload; end; function Highscore: THighScore; implementation uses System.Sysutils; function Highscore: THighScore; begin if THighScore.FInstance = nil then THighScore.Create; Result := THighScore.FInstance; end; constructor THighScore.Create; begin inherited; FInifile := TRegistryIniFile.Create('Software\Borrisholt\2048'); FInstance := self; end; destructor THighScore.Destroy; begin FInifile.Free; inherited; end; class destructor THighScore.Destroy; begin FreeAndNil(FInstance); end; procedure THighScore.DeleteHighScore; begin FInifile.EraseSection(Section); end; function THighScore.HasHighScore: Boolean; begin Result := ReadScore <> 0; end; function THighScore.ReadHighScore: THighScoreRecord; begin Result.Player := ReadString(KEY_PLAYER); Result.Score := ReadInteger(KEY_SCORE); end; function THighScore.ReadInteger(const Ident: String): Integer; begin Result := FInifile.ReadInteger(Section, Ident, 0); end; function THighScore.ReadPlayer: String; begin Result := ReadHighScore.Player; end; function THighScore.ReadScore: Integer; begin Result := ReadHighScore.Score; end; function THighScore.ReadString(const Ident: String): String; begin Result := FInifile.ReadString(Section, Ident, ''); end; procedure THighScore.WriteHighScore(const aPlayer: String; const aScore: Integer); begin if aScore = 0 then exit; WriteString(KEY_PLAYER, aPlayer); WriteInteger(KEY_SCORE, aScore); end; procedure THighScore.WriteHighScore(const aHighScore: THighScoreRecord); begin WriteHighScore(aHighScore.Player, aHighScore.Score); end; procedure THighScore.WriteInteger(const Ident: String; Value: Integer); begin FInifile.WriteInteger(Section, Ident, Value); end; procedure THighScore.WriteString(const Ident, Value: String); begin FInifile.WriteString(Section, Ident, Value); end; end.
unit DW.Template.CustomPlatform; {*******************************************************} { } { Kastri Free } { } { DelphiWorlds Cross-Platform Library } { } {*******************************************************} {$I DW.GlobalDefines.inc} interface type TTemplate = class; TCustomPlatformTemplate = class(TObject) private FTemplate: TTemplate; protected property Template: TTemplate read FTemplate; public constructor Create(const ATemplate: TTemplate); virtual; destructor Destroy; override; end; TTemplate = class(TObject) private FPlatformTemplate: TCustomPlatformTemplate; protected // public constructor Create; destructor Destroy; override; end; implementation uses {$IF Defined(IOS)} DW.Template.iOS; {$ELSEIF Defined(ANDROID)} DW.Template.Android; {$ELSE} DW.Template.Default; {$ENDIF} { TCustomPlatformTemplate } constructor TCustomPlatformTemplate.Create(const ATemplate: TTemplate); begin inherited Create; FTemplate := ATemplate; end; destructor TCustomPlatformTemplate.Destroy; begin // inherited; end; { TTemplate } constructor TTemplate.Create; begin inherited; FPlatformTemplate := TPlatformTemplate.Create(Self); end; destructor TTemplate.Destroy; begin FPlatformTemplate.Free; inherited; end; end.
unit m3StgMgr; {* Классы-менеджеры для работы с IStorage. } // $Id: m3stgmgr.pas,v 1.60 2016/04/20 14:57:20 lulin Exp $ // $Log: m3stgmgr.pas,v $ // Revision 1.60 2016/04/20 14:57:20 lulin // - делаем так, чтобы тест индексации мог работать по нескольку раз и без предварительных пасов руками. // // Revision 1.59 2016/04/20 14:24:08 lulin // - делаем так, чтобы тест индексации мог работать по нескольку раз и без предварительных пасов руками. // // Revision 1.58 2016/04/13 11:27:49 lulin // - улучшаем диагностику - выводим имя файла. // // Revision 1.57 2015/05/14 11:40:17 lulin // {RequestLink:588034502}. Оптимизируем очистку кеша. // // Revision 1.56 2015/05/13 10:59:48 lulin // - чистим код. // // Revision 1.55 2015/05/12 11:05:35 lulin // {RequestLink:588034502}. // // Revision 1.54 2015/05/12 10:15:10 lulin // {RequestLink:588034502}. // // Revision 1.53 2014/12/08 13:07:44 lulin // - рисуем на модели. // // Revision 1.52 2014/12/05 13:23:08 lulin // - рисуем на модели. // // Revision 1.51 2014/12/05 12:34:00 lulin // - рисуем на модели. // // Revision 1.50 2014/10/16 13:06:04 lulin // - перетряхиваем зависимости между классами. // // Revision 1.49 2014/10/16 09:02:51 lulin // - очередной раз удаляем "совсем старое хранилище". // // Revision 1.48 2014/10/03 13:42:00 lulin // - кешируем менеджеры блоков. // // Revision 1.47 2014/10/03 11:16:43 lulin // - готовимся к кешированию хранилищ, а точнее - менеджеров блоков и связанных с ними потоков. // // Revision 1.46 2014/10/03 10:10:23 lulin // - готовимся к кешированию хранилищ, а точнее - менеджеров блоков и связанных с ними потоков. // // Revision 1.45 2014/10/03 09:44:33 lulin // - готовимся к кешированию хранилищ, а точнее - менеджеров блоков и связанных с ними потоков. // // Revision 1.44 2014/09/19 15:13:35 lulin // - оптимизируем. // // Revision 1.42 2014/09/18 14:49:42 lulin // - при копировании в бекап создаем новое хранилище. // // Revision 1.41 2014/09/16 16:30:27 lulin // - бекап пытаемся писать в новом формате. // // Revision 1.40 2014/09/16 11:17:37 lulin // - возвращаем нарезку. // // Revision 1.39 2014/09/16 10:43:22 lulin // - возвращаем старую реализацию хранилища. // // Revision 1.38 2014/09/16 07:39:36 lulin // - чистим код. // // Revision 1.37 2014/09/12 09:56:22 lulin // - информационный поток открываем в том же режиме, что и все остальные. // // Revision 1.36 2014/09/11 15:45:24 lulin // - продолжаем рефакторинг внутреннего устройства хранилища. // // Revision 1.35 2014/09/11 13:44:20 lulin // - готовимся к открытию постоянной части в режине на чтение без залочек. // // Revision 1.34 2014/09/11 11:28:19 lulin // - продолжаем рефакторинг внутреннего устройства хранилища. // // Revision 1.33 2014/09/10 16:40:13 lulin // - продолжаем рефакторинг внутреннего устройства хранилища. // // Revision 1.32 2014/09/10 16:17:35 lulin // - чистим код. // // Revision 1.31 2014/09/10 16:02:08 lulin // - где возможно, там используем эксклюзивный доступ. // // Revision 1.30 2014/09/10 15:29:46 lulin // - готовимся к эксклюзивной работе с хранилищами. // // Revision 1.29 2014/09/04 15:00:07 lulin // - выделяем новый тип блоков - "без мусора". // // Revision 1.28 2014/08/29 12:15:51 lulin // - заменяем условную директиву на переменную. // // Revision 1.27 2014/08/29 11:32:05 lulin // - даём методу более вменяемое название. // // Revision 1.26 2014/08/29 11:22:08 lulin // - заменяем условную директиву на переменную. // // Revision 1.25 2014/08/25 15:44:34 lulin // - вставляем диагностику заголовка потока. // // Revision 1.23 2013/04/12 16:25:08 lulin // - отлаживаем под XE3. // // Revision 1.22 2012/05/29 10:01:11 voba // no message // // Revision 1.21 2012/05/29 09:44:12 lulin // {RequestLink:367210517} // // Revision 1.20 2012/05/29 09:38:47 lulin // {RequestLink:367210517} // // Revision 1.19 2012/05/25 14:17:21 lulin // - делаем "кошерную" операцию проверки существования файла. // // Revision 1.17 2012/05/24 09:03:56 voba // - bug fix // // Revision 1.16 2012/05/22 13:29:42 lulin // {RequestLink:365838449} // // Revision 1.15 2012/05/22 11:59:11 lulin // {RequestLink:365838449} // // Revision 1.14 2012/05/05 14:06:24 lulin // {RequestLink:361038156} // // Revision 1.13 2012/05/05 12:11:45 lulin // {RequestLink:361038156} // // Revision 1.12 2012/05/05 11:37:29 lulin // {RequestLink:361038156} // // Revision 1.11 2012/05/05 11:20:48 lulin // {RequestLink:361038156} // // Revision 1.10 2012/05/04 19:44:39 lulin // {RequestLink:361038156} // // Revision 1.8 2012/05/04 10:04:36 lulin // {RequestLink:361038156} // // Revision 1.7 2012/05/04 08:31:15 lulin // {RequestLink:361038156} // // Revision 1.6 2011/12/28 09:29:10 lulin // {RequestLink:325257155} // - чистим код. // // Revision 1.5 2009/03/12 19:08:25 lulin // - <K>: 138969458. Чистка устаревшего кода. // // Revision 1.4 2009/03/12 12:28:45 lulin // - <K>: 138969458. Удаляем ненужные файлы, методы и классы. // // Revision 1.3 2009/03/12 12:08:19 lulin // - <K>: 138969458. Удаляем ненужные методы и классы. // // Revision 1.2 2006/02/02 15:33:56 voba // - new beh. при создании файла-хранилища проверяется и при необходимости достраивается путь к нему // // Revision 1.1 2004/09/02 08:09:49 law // - cleanup. // // Revision 1.8 2004/05/20 11:36:31 law // - bug fix: вместо %1 в сообщении об ошибке теперь пишется имя файла. // // Revision 1.7 2002/04/26 13:16:15 law // - cleanup. // // Revision 1.6 2002/02/21 15:58:17 law // - optimization. // // Revision 1.5 2001/11/29 17:02:43 law // - new directive: _m3NeedStorageFixer. // // Revision 1.4 2001/11/28 15:10:02 law // - bug fix: поправлен PlugIn для Far'а - не читал архивированные хранилища. // // Revision 1.3 2001/11/28 14:19:32 law // - new behavior: сделано создание хранилищ с автоматической паковкой. // // Revision 1.2 2001/10/26 17:43:32 law // - comments: xHelpGen. // {$I m3Define.inc} interface uses Windows, SysUtils, ActiveX, COMObj, l3FileUtils, m2COMLib, m3StorageInterfaces, m3ArchiveStorage ; const def_ReadModeStorageUseCompression = m3_stArchive; def_FullModeStorageUseCompression = m3_stArchive; type Tm3StorageManager = class protected class function SharedMode: Cardinal; virtual; abstract; public class procedure IterateStorageFiles(const aName : AnsiString; aDoFile : TFileProcessingFunc); class procedure DeleteStorageFile(const aName : AnsiString); class function RenameStorageFile(const anOldName : AnsiString; const aNewName : AnsiString): Boolean; class function StorageFileExists(const aName : AnsiString): Boolean; class function UseSplitted: Boolean; class function HasSplitted(const aName : AnsiString): Boolean; class function HasSolid(const aName : AnsiString): Boolean; end;//Tm3StorageManager Tm3ReadModeStorageManager = class(Tm3StorageManager) {* Менеджер для создания ReadOnly хранилищ. } protected class function SharedMode: Cardinal; override; class function MakeInterface(const AStream : IStream; UseCompression : Tm3StorageType ): Im3StorageHolder; overload; {* Открывает хранилище в потоке. } class function MakeSafeInterface(out AResult : Im3IndexedStorage; const AStream : IStream; UseCompression : Tm3StorageType ): HRESULT; overload; {* Открывает хранилище в потоке (без исключительных ситуаций). } public class function MakeInterface(const AName : WideString; UseCompression : Tm3StorageType = def_ReadModeStorageUseCompression ): Im3IndexedStorage; overload; {* Открывает хранилище на диске. } class function MakeSafeInterface(out AResult : Im3IndexedStorage; const AName : WideString; UseCompression : Tm3StorageType = def_ReadModeStorageUseCompression ): HRESULT; overload; {* Открывает хранилище на диске (без исключительных ситуаций). } end;//Tm3ReadModeStorageManager Tm3FullModeStorageManager = class(Tm3StorageManager) {* Менеджер для создания хранилищ. } protected class function SharedMode: Cardinal; override; class function MakeInterface(const AStream: IStream; UseCompression : Tm3StorageType ): Im3StorageHolder; overload; {* Открывает хранилище в потоке. } class function MakeSafeInterface(out AResult: Im3IndexedStorage; const AStream: IStream; UseCompression : Tm3StorageType ): HRESULT; overload; {* Открывает хранилище в потоке (без исключительных ситуаций). } public class function MakeInterface(const AName: WideString; UseCompression : Tm3StorageType = def_FullModeStorageUseCompression ): Im3IndexedStorage; overload; {* Открывает хранилище на диске. } class function MakeSafeInterface(out AResult: Im3IndexedStorage; const AName: WideString; UseCompression : Tm3StorageType = def_FullModeStorageUseCompression ): HRESULT; overload; {* Открывает хранилище на диске (без исключительных ситуаций). } end;//Tm3FullModeStorageManager Tm3FullModeExclusiveStorageManager = class(Tm3FullModeStorageManager) protected class function SharedMode: Cardinal; override; end;//Tm3FullModeExclusiveStorageManager Tm3ReadModeExclusiveStorageManager = class(Tm3ReadModeStorageManager) protected class function SharedMode: Cardinal; override; end;//Tm3ReadModeExclusiveStorageManager Tm3FullModeBackupStorageManager = class(Tm3FullModeStorageManager) end;//Tm3FullModeBackupStorageManager Tm3FullModeBackupExclusiveStorageManager = class(Tm3FullModeBackupStorageManager) protected class function SharedMode: Cardinal; override; end;//Tm3FullModeBackupExclusiveStorageManager Tm3ReadModeBackupStorageManager = class(Tm3ReadModeStorageManager) end;//Tm3ReadModeBackupStorageManager Tm3ConstantStorageManager = class(Tm3ReadModeStorageManager) protected class function SharedMode: Cardinal; override; end;//Tm3ConstantStorageManager implementation uses StrUtils, l3Base, m3SplittedFileStream, m3RootStreamManagerPrim, m3RootStreamManager, m3StorageHolder, m3StorageHolderList, m3TempStream, m3FileStream, m3StorageService ; // Tm3ReadModeStorageManager class function Tm3ReadModeStorageManager.SharedMode: Cardinal; begin Result := FILE_SHARE_READ or FILE_SHARE_WRITE; end; const cFileMacro = '%1'; class function Tm3ReadModeStorageManager.MakeInterface(const aName : WideString; UseCompression : Tm3StorageType = def_ReadModeStorageUseCompression): Im3IndexedStorage; const CAccess = GENERIC_READ; CDistribution = OPEN_EXISTING; CFlags = FILE_ATTRIBUTE_NORMAL; begin if Tm3StorageHolder.GetFromCache(aName, STGM_READ, UseCompression, SharedMode, Result) then Exit; if not StorageFileExists(aName) then begin Result := nil; Exit; end;//not StorageFileExists(aName) try if HasSplitted(aName) then begin Assert(not HasSolid(aName), 'Существуют и кусочная и некусочная части: ' + aName); Result := MakeInterface(Tm3SplittedFileStream.Make(AName, CAccess, SharedMode, CDistribution, CFlags), UseCompression).StoreToCache(aName, SharedMode); end//HasSplitted(aName) else if {UseSplitted AND }not HasSolid(aName) then Result := MakeInterface(Tm3SplittedFileStream.Make(AName, CAccess, SharedMode, CDistribution, CFlags), UseCompression).StoreToCache(aName, SharedMode) else Result := MakeInterface(Tm3FileStream.Make(AName, CAccess, SharedMode, CDistribution, CFlags), UseCompression).StoreToCache(aName, SharedMode); except on E: EOleSysError do begin if (E.ErrorCode = STG_E_INVALIDHEADER) OR (Pos(cFileMacro, E.Message) > 0) then raise EOleSysError.Create(ANSIReplaceStr(E.Message, cFileMacro, '"' + aName + '"'), E.ErrorCode, E.HelpContext) else raise; end;//on E: EOleSysError end;//try..except end; class function Tm3ReadModeStorageManager.MakeSafeInterface(out AResult: Im3IndexedStorage; const AName: WideString; UseCompression : Tm3StorageType = def_ReadModeStorageUseCompression): HRESULT; begin Result := S_OK; try AResult := MakeInterface(AName, UseCompression); except on E: EOutOfMemory do Result := STG_E_INSUFFICIENTMEMORY; on E: EOleSysError do Result := E.ErrorCode; else Result := E_UNEXPECTED; end;//try..except end; class function Tm3ReadModeStorageManager.MakeInterface(const AStream : IStream; UseCompression : Tm3StorageType): Im3StorageHolder; begin Result := Tm3ArchiveStorage.Make(STGM_READ, AStream, UseCompression); end; class function Tm3ReadModeStorageManager.MakeSafeInterface(out AResult : Im3IndexedStorage; const AStream : IStream; UseCompression : Tm3StorageType): HRESULT; begin Result := S_OK; try AResult := MakeInterface(aStream, UseCompression).Storage; except on E: EOutOfMemory do Result := STG_E_INSUFFICIENTMEMORY; on E: EOleSysError do Result := E.ErrorCode; else Result := E_UNEXPECTED; end;//try..except end; // Tm3FullModeStorageManager class function Tm3FullModeStorageManager.SharedMode: Cardinal; begin Result := FILE_SHARE_READ or FILE_SHARE_WRITE; end; class function Tm3FullModeStorageManager.MakeInterface(const aName: WideString; UseCompression : Tm3StorageType = def_FullModeStorageUseCompression): Im3IndexedStorage; const CAccess = GENERIC_READ or GENERIC_WRITE; CDistribution = OPEN_ALWAYS; CFlags = FILE_ATTRIBUTE_NORMAL; begin if (AName = '') then Result := MakeInterface(Tm3TempStream.Make, UseCompression).StoreToCache(aName, SharedMode) else begin if Tm3StorageHolder.GetFromCache(aName, STGM_READWRITE, UseCompression, SharedMode, Result) then Exit; l3FileUtils.MakeDir(ExtractFilePath(AName)); try if HasSplitted(aName) then begin Assert(not HasSolid(aName), 'Существуют и кусочная и некусочная части: ' + aName); Result := MakeInterface(Tm3SplittedFileStream.Make(AName, CAccess, SharedMode, CDistribution, CFlags), UseCompression).StoreToCache(aName, SharedMode); end//HasSplitted(aName) else if UseSplitted AND not HasSolid(AName) then Result := MakeInterface(Tm3SplittedFileStream.Make(AName, CAccess, SharedMode, CDistribution, CFlags), UseCompression).StoreToCache(aName, SharedMode) else Result := MakeInterface(Tm3FileStream.Make(AName, CAccess, SharedMode, CDistribution, CFlags), UseCompression).StoreToCache(aName, SharedMode); except on E: EOleSysError do begin if (E.ErrorCode = STG_E_INVALIDHEADER) OR (Pos(cFileMacro, E.Message) > 0) then raise EOleSysError.Create(ANSIReplaceStr(E.Message, cFileMacro, '"' + aName + '"'), E.ErrorCode, E.HelpContext) else raise; end;//on E: EOleSysError end;//try..except end;//AName = '' end; class function Tm3FullModeStorageManager.MakeSafeInterface(out AResult: Im3IndexedStorage; const AName: WideString; UseCompression : Tm3StorageType = def_FullModeStorageUseCompression): HRESULT; begin Result := S_OK; try AResult := MakeInterface(AName, UseCompression); except on E: EOutOfMemory do Result := STG_E_INSUFFICIENTMEMORY; on E: EOleSysError do Result := E.ErrorCode; else Result := E_UNEXPECTED; end;//try..except end; class function Tm3FullModeStorageManager.MakeInterface(const AStream: IStream; UseCompression : Tm3StorageType): Im3StorageHolder; begin Result := Tm3ArchiveStorage.Make(STGM_READWRITE, AStream, UseCompression); end; class function Tm3FullModeStorageManager.MakeSafeInterface(out AResult: Im3IndexedStorage; const AStream: IStream; UseCompression : Tm3StorageType): HRESULT; begin Result := S_OK; try AResult := MakeInterface(aStream, UseCompression).Storage; except on E: EOutOfMemory do Result := STG_E_INSUFFICIENTMEMORY; on E: EOleSysError do Result := E.ErrorCode; else Result := E_UNEXPECTED; end;//try..except end; // start class Tm3StorageManager class procedure Tm3StorageManager.IterateStorageFiles(const aName : AnsiString; aDoFile : TFileProcessingFunc); var l_Ext : AnsiString; function DoFile(const aFileName: AnsiString; aData: Pointer): Boolean; begin//DoFile if (Pos('.etalon.', aFileName) > 0) then //if AnsiEndsStr('.etalon' + l_Ext, aFileName) then Result := true else Result := aDoFile(aFileName, aData); end;//DoFile var l_FPStub : Pointer; const cMaskPart = '.*'; var l_Mask : AnsiString; l_Folder : AnsiString; begin l_Ext := ExtractFileExt(aName); aDoFile(aName, nil); aDoFile(Tm3SplittedFileStream.NormalizeFileName(aName) + m3_cInfoFileNameExt + l_Ext, nil); aDoFile(Tm3SplittedFileStream.NormalizeFileName(aName) + l_Ext + cLockLogExt, nil); l_Folder := ExtractFilePath(aName); l_Mask := Tm3SplittedFileStream.NormalizeFileName(ExtractFileName(aName)) + cMaskPart + l_Ext; l_FPStub := l3LocalStub(@DoFile); try ProcessFilesWithMask(l_Folder, l_Mask, l_FPStub); finally l3FreeLocalStub(l_FPStub); end;//try..finally end; class procedure Tm3StorageManager.DeleteStorageFile(const aName : AnsiString); function DoFile(const aFileName: AnsiString): Boolean; begin//DoFile Result := true; if FileExists(aFileName) then DeleteFile(aFileName); end;//DoFile var l_FPStub : Pointer; begin Tm3StorageHolderList.Drop(aName); l_FPStub := l3LocalStub(@DoFile); try IterateStorageFiles(aName, l_FPStub); finally l3FreeLocalStub(l_FPStub); end;//try..finally end; class function Tm3StorageManager.UseSplitted: Boolean; begin Result := Tm3StorageService.Instance.UseSplitted; end; class function Tm3StorageManager.HasSplitted(const aName : AnsiString): Boolean; var l_Ext : AnsiString; l_Name : AnsiString; begin l_Ext := ExtractFileExt(aName); l_Name := Tm3SplittedFileStream.NormalizeFileName(aName) + m3_cInfoFileNameExt + l_Ext; Result := FileExists(l_Name); end; class function Tm3StorageManager.HasSolid(const aName : AnsiString): Boolean; begin Result := FileExists(aName); end; class function Tm3StorageManager.StorageFileExists(const aName : AnsiString): Boolean; function DoFile(const aFileName: AnsiString): Boolean; begin//DoFile Result := true; if FileExists(aFileName) then begin StorageFileExists := true; Result := false; end;//FileExists(aFileName) end;//DoFile var l_FPStub : Pointer; begin Result := false; l_FPStub := l3LocalStub(@DoFile); try IterateStorageFiles(aName, l_FPStub); finally l3FreeLocalStub(l_FPStub); end;//try..finally end; class function Tm3StorageManager.RenameStorageFile(const anOldName : AnsiString; const aNewName : AnsiString) : Boolean; var l_PathNew : AnsiString; l_StartOld : AnsiString; l_StartNew : AnsiString; function DoFile(const aFileName: AnsiString): Boolean; var l_Name : AnsiString; begin//DoFile Result := true; if FileExists(aFileName) then begin l_Name := ExtractFileName(aFileName); if AnsiStartsText(l_StartOld, l_Name) then begin Delete(l_Name, 1, Length(l_StartOld)); l_Name := l_StartNew + l_Name; end//AnsiStartsText(l_StartOld, l_Name) else Assert(false, 'Какая-то беда с переименованием файлов'); l_Name := l_PathNew + l_Name; if FileExists(l_Name) then DeleteFile(l_Name); if RenameFile(aFileName, l_Name) then RenameStorageFile := true else Assert(false, Format('Какая-то беда с переименованием файлов %s в %s', [aFileName, l_Name])); end;//FileExists(aFileName) end;//DoFile var l_FPStub : Pointer; begin Tm3StorageHolderList.Drop(anOldName); Result := false; l_PathNew := ExtractFilePath(aNewName); if (l_PathNew = '') then l_PathNew := ExtractFilePath(anOldName); l_StartOld := Tm3SplittedFileStream.NormalizeFileName(ExtractFileName(anOldName)); l_StartNew := Tm3SplittedFileStream.NormalizeFileName(ExtractFileName(aNewName)); l_FPStub := l3LocalStub(@DoFile); try IterateStorageFiles(anOldName, l_FPStub); finally l3FreeLocalStub(l_FPStub); end;//try..finally end; class function Tm3FullModeExclusiveStorageManager.SharedMode: Cardinal; begin Result := 0; end; class function Tm3ReadModeExclusiveStorageManager.SharedMode: Cardinal; begin Result := 0; end; class function Tm3ConstantStorageManager.SharedMode: Cardinal; begin Result := FILE_SHARE_READ; end; class function Tm3FullModeBackupExclusiveStorageManager.SharedMode: Cardinal; begin Result := 0; end; end.
// ----------------------------------------------------------------------------- // Project: bitmap resampler // Module: resample // Description: Interpolated Bitmap Resampling using filters. // Version: 01.03 // Release: 1 // Date: 19-DEC-2009 // Target: Free Pascal 2.2.4, Lazarus 0.9.29 // Author(s): anme: Anders Melander, anders@melander.dk // Alexx2000: Alexander Koblov, alexx2000@mail.ru // Copyright (c) 1997,98 by Anders Melander // Copyright (c) 2009 by Alexander Koblov // Formatting: 2 space indent, 8 space tabs, 80 columns. // ----------------------------------------------------------------------------- // This software is copyrighted as noted above. It may be freely copied, // modified, and redistributed, provided that the copyright notice(s) is // preserved on all copies. // // There is no warranty or other guarantee of fitness for this software, // it is provided solely "as is". Bug reports or fixes may be sent // to the author, who may or may not act on them as he desires. // // You may not include this software in a program or other software product // without supplying the source, or without informing the end-user that the // source is available for no extra charge. // // If you modify this software, you should include a notice in the "Revision // history" section giving the name of the person performing the modification, // the date of modification, and the reason for such modification. // ----------------------------------------------------------------------------- // Here's some additional copyrights for you: // // From filter.c: // The authors and the publisher hold no copyright restrictions // on any of these files; this source code is public domain, and // is freely available to the entire computer graphics community // for study, use, and modification. We do request that the // comment at the top of each file, identifying the original // author and its original publication in the book Graphics // Gems, be retained in all programs that use these files. // // ----------------------------------------------------------------------------- // Revision history: // // 0100 110997 anme - Adapted from fzoom v0.20 by Dale Schumacher. // // 0101 110198 anme - Added Lanczos3 and Mitchell filters. // - Fixed range bug. // Min value was not checked on conversion from Single to // byte. // - Numerous optimizations. // - Added TImage stretch on form resize. // - Added support for Delphi 2 via TCanvas.Pixels. // - Renamed module from stretch to resample. // - Moved demo code to separate module. // // 0102 150398 anme - Fixed a problem that caused all pixels to be shifted // 1/2 pixel down and to the right (in source // coordinates). Thanks to David Ullrich for the // solution. // 0103 191209 Alexx2000 // - Ported to FreePascal/Lazarus // - Added alpha channel support // ----------------------------------------------------------------------------- // Credits: // The algorithms and methods used in this library are based on the article // "General Filtered Image Rescaling" by Dale Schumacher which appeared in the // book Graphics Gems III, published by Academic Press, Inc. // // The edge offset problem was fixed by: // * David Ullrich <ullrich@hardy.math.okstate.edu> // ----------------------------------------------------------------------------- // To do (in rough order of priority): // * Implement Dale Schumacher's "Optimized Bitmap Scaling Routines". // * Fix BoxFilter. // * Optimize to use integer math instead of floating point where possible. // ----------------------------------------------------------------------------- unit uReSample; interface {$mode delphi}{$R-} {$IF (FPC_VERSION > 2) or ((FPC_VERSION = 2) and (FPC_RELEASE >= 5))} {$POINTERMATH ON} {$ENDIF} uses SysUtils, Classes, Graphics; type // Type of a filter for use with Stretch() TFilterProc = function(Value: Single): Single; // Sample filters for use with Stretch() function SplineFilter(Value: Single): Single; function BellFilter(Value: Single): Single; function TriangleFilter(Value: Single): Single; function BoxFilter(Value: Single): Single; function HermiteFilter(Value: Single): Single; function Lanczos3Filter(Value: Single): Single; function MitchellFilter(Value: Single): Single; // Interpolator // Src: Source bitmap // Dst: Destination bitmap // filter: Weight calculation filter // fwidth: Relative sample radius procedure Stretch(Src, Dst: TRasterImage; filter: TFilterProc; fwidth: single); // ----------------------------------------------------------------------------- // // List of Filters // // ----------------------------------------------------------------------------- const ResampleFilters: array[0..6] of record Name: string; // Filter name Filter: TFilterProc;// Filter implementation Width: Single; // Suggested sampling width/radius end = ( (Name: 'Box'; Filter: BoxFilter; Width: 0.5), (Name: 'Triangle'; Filter: TriangleFilter; Width: 1.0), (Name: 'Hermite'; Filter: HermiteFilter; Width: 1.0), (Name: 'Bell'; Filter: BellFilter; Width: 1.5), (Name: 'B-Spline'; Filter: SplineFilter; Width: 2.0), (Name: 'Lanczos3'; Filter: Lanczos3Filter; Width: 3.0), (Name: 'Mitchell'; Filter: MitchellFilter; Width: 2.0) ); implementation uses Math, IntfGraphics, GraphType, FPImage; // ----------------------------------------------------------------------------- // // Filter functions // // ----------------------------------------------------------------------------- // Hermite filter function HermiteFilter(Value: Single): Single; begin // f(t) = 2|t|^3 - 3|t|^2 + 1, -1 <= t <= 1 if (Value < 0.0) then Value := -Value; if (Value < 1.0) then Result := (2.0 * Value - 3.0) * Sqr(Value) + 1.0 else Result := 0.0; end; // Box filter // a.k.a. "Nearest Neighbour" filter // anme: I have not been able to get acceptable // results with this filter for subsampling. function BoxFilter(Value: Single): Single; begin if (Value > -0.5) and (Value <= 0.5) then Result := 1.0 else Result := 0.0; end; // Triangle filter // a.k.a. "Linear" or "Bilinear" filter function TriangleFilter(Value: Single): Single; begin if (Value < 0.0) then Value := -Value; if (Value < 1.0) then Result := 1.0 - Value else Result := 0.0; end; // Bell filter function BellFilter(Value: Single): Single; begin if (Value < 0.0) then Value := -Value; if (Value < 0.5) then Result := 0.75 - Sqr(Value) else if (Value < 1.5) then begin Value := Value - 1.5; Result := 0.5 * Sqr(Value); end else Result := 0.0; end; // B-spline filter function SplineFilter(Value: Single): Single; var tt : single; begin if (Value < 0.0) then Value := -Value; if (Value < 1.0) then begin tt := Sqr(Value); Result := 0.5*tt*Value - tt + 2.0 / 3.0; end else if (Value < 2.0) then begin Value := 2.0 - Value; Result := 1.0/6.0 * Sqr(Value) * Value; end else Result := 0.0; end; // Lanczos3 filter function Lanczos3Filter(Value: Single): Single; function SinC(Value: Single): Single; begin if (Value <> 0.0) then begin Value := Value * Pi; Result := sin(Value) / Value end else Result := 1.0; end; begin if (Value < 0.0) then Value := -Value; if (Value < 3.0) then Result := SinC(Value) * SinC(Value / 3.0) else Result := 0.0; end; function MitchellFilter(Value: Single): Single; const B = (1.0 / 3.0); C = (1.0 / 3.0); var tt : single; begin if (Value < 0.0) then Value := -Value; tt := Sqr(Value); if (Value < 1.0) then begin Value := (((12.0 - 9.0 * B - 6.0 * C) * (Value * tt)) + ((-18.0 + 12.0 * B + 6.0 * C) * tt) + (6.0 - 2 * B)); Result := Value / 6.0; end else if (Value < 2.0) then begin Value := (((-1.0 * B - 6.0 * C) * (Value * tt)) + ((6.0 * B + 30.0 * C) * tt) + ((-12.0 * B - 48.0 * C) * Value) + (8.0 * B + 24 * C)); Result := Value / 6.0; end else Result := 0.0; end; // ----------------------------------------------------------------------------- // // Interpolator // // ----------------------------------------------------------------------------- type // Contributor for a pixel TContributor = record pixel: integer; // Source pixel weight: single; // Pixel weight end; TContributorList = array[0..0] of TContributor; PContributorList = ^TContributorList; // List of source pixels contributing to a destination pixel TCList = record n : integer; p : PContributorList; end; TCListList = array[0..0] of TCList; PCListList = ^TCListList; TRGBA = packed record r, g, b, a : single; end; // Physical bitmap pixel TColorRGBA = packed record r, g, b, a : BYTE; end; PColorRGBA = ^TColorRGBA; // Physical bitmap scanline (row) TRGBAList = packed array[0..0] of TColorRGBA; PRGBAList = ^TRGBAList; function CreateAlphaFromMask(Bitmap: TRasterImage): TLazIntfImage; var SrcIntfImage: TLazIntfImage; x, y, xStop, yStop: Integer; Color: TFPColor; begin SrcIntfImage := TLazIntfImage.Create(Bitmap.RawImage, False); with SrcIntfImage do begin if MaskData = nil then Exit(SrcIntfImage); Result := TLazIntfImage.Create(Width, Height, [riqfRGB, riqfAlpha]); Result.CreateData; xStop := Width - 1; yStop := Height - 1; end; for x:= 0 to xStop do for y:= 0 to yStop do begin Color := SrcIntfImage.Colors[x, y]; if SrcIntfImage.Masked[x, y] then Color.Alpha := Low(Color.Alpha) else Color.Alpha := High(Color.Alpha); Result.Colors[x, y] := Color; end; SrcIntfImage.Free; end; procedure Stretch(Src, Dst: TRasterImage; filter: TFilterProc; fwidth: single); var xscale, yscale : single; // Zoom scale factors i, j, k : integer; // Loop variables center : single; // Filter calculation variables width, fscale, weight : single; // Filter calculation variables left, right : integer; // Filter calculation variables n : integer; // Pixel number Work : PRGBAList; contrib : PCListList; rgba : TRGBA; color : TColorRGBA; SourceLine , DestLine : PRGBAList; SrcDelta : integer; SrcIntfImage, DstIntfImage : TLazIntfImage; SrcWidth , SrcHeight , DstWidth , DstHeight : integer; function Color2RGBA(Color: TFPColor): TColorRGBA; inline; begin Result.r := Color.Red shr 8; Result.g := Color.Green shr 8; Result.b := Color.Blue shr 8; Result.a := Color.Alpha shr 8; end; function RGBA2Color(Color: TColorRGBA): TFPColor; inline; begin Result.Red := Color.r shl 8; Result.Green := Color.g shl 8; Result.Blue := Color.b shl 8; Result.Alpha := Color.a shl 8; end; begin DstWidth := Dst.Width; DstHeight := Dst.Height; SrcWidth := Src.Width; SrcHeight := Src.Height; if (SrcWidth < 1) or (SrcHeight < 1) then raise Exception.Create('Source bitmap too small'); // Create intermediate buffer to hold horizontal zoom Work := GetMem(DstWidth * SrcHeight * SizeOf(TColorRGBA)); try // xscale := DstWidth / SrcWidth; // yscale := DstHeight / SrcHeight; // Improvement suggested by David Ullrich: if (SrcWidth = 1) then xscale:= DstWidth / SrcWidth else xscale:= (DstWidth - 1) / (SrcWidth - 1); if (SrcHeight = 1) then yscale:= DstHeight / SrcHeight else yscale:= (DstHeight - 1) / (SrcHeight - 1); {++++++++++++++++++++} if Src.RawImage.Description.AlphaPrec = 0 then // if bitmap has not alpha channel SrcIntfImage := CreateAlphaFromMask(Src) else begin SrcIntfImage := TLazIntfImage.Create(Src.RawImage, False); end; DstIntfImage := TLazIntfImage.Create(DstWidth, DstHeight, [riqfRGB, riqfAlpha]); DstIntfImage.CreateData; {++++++++++++++++++++} // -------------------------------------------- // Pre-calculate filter contributions for a row // ----------------------------------------------- GetMem(contrib, DstWidth* sizeof(TCList)); // Horizontal sub-sampling // Scales from bigger to smaller width if (xscale < 1.0) then begin width := fwidth / xscale; fscale := 1.0 / xscale; for i := 0 to DstWidth-1 do begin contrib^[i].n := 0; GetMem(contrib^[i].p, trunc(width * 2.0 + 1) * sizeof(TContributor)); center := i / xscale; // Original code: // left := ceil(center - width); // right := floor(center + width); left := floor(center - width); right := ceil(center + width); for j := left to right do begin weight := filter((center - j) / fscale) / fscale; if (weight = 0.0) then continue; if (j < 0) then n := -j else if (j >= SrcWidth) then n := SrcWidth - j + SrcWidth - 1 else n := j; k := contrib^[i].n; contrib^[i].n := contrib^[i].n + 1; contrib^[i].p^[k].pixel := n; contrib^[i].p^[k].weight := weight; end; end; end else // Horizontal super-sampling // Scales from smaller to bigger width begin for i := 0 to DstWidth-1 do begin contrib^[i].n := 0; GetMem(contrib^[i].p, trunc(fwidth * 2.0 + 1) * sizeof(TContributor)); center := i / xscale; // Original code: // left := ceil(center - fwidth); // right := floor(center + fwidth); left := floor(center - fwidth); right := ceil(center + fwidth); for j := left to right do begin weight := filter(center - j); if (weight = 0.0) then continue; if (j < 0) then n := -j else if (j >= SrcWidth) then n := SrcWidth - j + SrcWidth - 1 else n := j; k := contrib^[i].n; contrib^[i].n := contrib^[i].n + 1; contrib^[i].p^[k].pixel := n; contrib^[i].p^[k].weight := weight; end; end; end; // ---------------------------------------------------- // Apply filter to sample horizontally from Src to Work // ---------------------------------------------------- for k := 0 to SrcHeight-1 do begin {++++++++++++++++++++} DestLine := Work + k * DstWidth; {++++++++++++++++++++} for i := 0 to DstWidth-1 do begin rgba.r := 0.0; rgba.g := 0.0; rgba.b := 0.0; rgba.a := 0.0; for j := 0 to contrib^[i].n-1 do begin {++++++++++++++++++++} color := Color2RGBA(SrcIntfImage.Colors[contrib^[i].p^[j].pixel, k]); {++++++++++++++++++++} weight := contrib^[i].p^[j].weight; if (weight = 0.0) then continue; rgba.r := rgba.r + color.r * weight; rgba.g := rgba.g + color.g * weight; rgba.b := rgba.b + color.b * weight; rgba.a := rgba.a + color.a * weight; end; if (rgba.r > 255.0) then color.r := 255 else if (rgba.r < 0.0) then color.r := 0 else color.r := round(rgba.r); if (rgba.g > 255.0) then color.g := 255 else if (rgba.g < 0.0) then color.g := 0 else color.g := round(rgba.g); if (rgba.b > 255.0) then color.b := 255 else if (rgba.b < 0.0) then color.b := 0 else color.b := round(rgba.b); if (rgba.a > 255.0) then color.a := 255 else if (rgba.a < 0.0) then color.a := 0 else color.a := round(rgba.a); {++++++++++++++++++++} // Set new pixel value DestLine^[i] := color; {++++++++++++++++++++} end; end; // Free the memory allocated for horizontal filter weights for i := 0 to DstWidth-1 do FreeMem(contrib^[i].p); FreeMem(contrib); // ----------------------------------------------- // Pre-calculate filter contributions for a column // ----------------------------------------------- GetMem(contrib, DstHeight* sizeof(TCList)); // Vertical sub-sampling // Scales from bigger to smaller height if (yscale < 1.0) then begin width := fwidth / yscale; fscale := 1.0 / yscale; for i := 0 to DstHeight-1 do begin contrib^[i].n := 0; GetMem(contrib^[i].p, trunc(width * 2.0 + 1) * sizeof(TContributor)); center := i / yscale; // Original code: // left := ceil(center - width); // right := floor(center + width); left := floor(center - width); right := ceil(center + width); for j := left to right do begin weight := filter((center - j) / fscale) / fscale; if (weight = 0.0) then continue; if (j < 0) then n := -j else if (j >= SrcHeight) then n := SrcHeight - j + SrcHeight - 1 else n := j; k := contrib^[i].n; contrib^[i].n := contrib^[i].n + 1; contrib^[i].p^[k].pixel := n; contrib^[i].p^[k].weight := weight; end; end end else // Vertical super-sampling // Scales from smaller to bigger height begin for i := 0 to DstHeight-1 do begin contrib^[i].n := 0; GetMem(contrib^[i].p, trunc(fwidth * 2.0 + 1) * sizeof(TContributor)); center := i / yscale; // Original code: // left := ceil(center - fwidth); // right := floor(center + fwidth); left := floor(center - fwidth); right := ceil(center + fwidth); for j := left to right do begin weight := filter(center - j); if (weight = 0.0) then continue; if (j < 0) then n := -j else if (j >= SrcHeight) then n := SrcHeight - j + SrcHeight - 1 else n := j; k := contrib^[i].n; contrib^[i].n := contrib^[i].n + 1; contrib^[i].p^[k].pixel := n; contrib^[i].p^[k].weight := weight; end; end; end; // -------------------------------------------------- // Apply filter to sample vertically from Work to Dst // -------------------------------------------------- {++++++++++++++++++++} SourceLine := Work; SrcDelta := DstWidth; {++++++++++++++++++++} for k := 0 to DstWidth-1 do begin for i := 0 to DstHeight-1 do begin rgba.r := 0; rgba.g := 0; rgba.b := 0; rgba.a := 0; // weight := 0.0; for j := 0 to contrib^[i].n-1 do begin {++++++++++++++++++++} color := PColorRGBA(SourceLine+contrib^[i].p^[j].pixel*SrcDelta)^; {++++++++++++++++++++} weight := contrib^[i].p^[j].weight; if (weight = 0.0) then continue; rgba.r := rgba.r + color.r * weight; rgba.g := rgba.g + color.g * weight; rgba.b := rgba.b + color.b * weight; rgba.a := rgba.a + color.a * weight; end; if (rgba.r > 255.0) then color.r := 255 else if (rgba.r < 0.0) then color.r := 0 else color.r := round(rgba.r); if (rgba.g > 255.0) then color.g := 255 else if (rgba.g < 0.0) then color.g := 0 else color.g := round(rgba.g); if (rgba.b > 255.0) then color.b := 255 else if (rgba.b < 0.0) then color.b := 0 else color.b := round(rgba.b); if (rgba.a > 255.0) then color.a := 255 else if (rgba.a < 0.0) then color.a := 0 else color.a := round(rgba.a); {++++++++++++++++++++} DstIntfImage.Colors[k, i]:= RGBA2Color(color); {++++++++++++++++++++} end; {++++++++++++++++++++} Inc(SourceLine); {++++++++++++++++++++} end; // Free the memory allocated for vertical filter weights for i := 0 to DstHeight-1 do FreeMem(contrib^[i].p); FreeMem(contrib); Dst.LoadFromIntfImage(DstIntfImage); finally FreeMem(Work); DstIntfImage.Free; SrcIntfImage.Free; end; end; end.
$TITLE M68IO - M68000 I/O Routines module m68io options check, special (word); $PAGE includes $SYSTEM pascal $SYSTEM pasist $SYSTEM ptmcon $SYSTEM paspt.typ $SYSTEM pasif.typ $SYSTEM m68cg.typ $SYSTEM m68gen $SYSTEM m68cgu $SYSTEM m68set $SYSTEM m68str $SYSTEM m68utl $SYSTEM m68exp $PAGE locals var getputstring_flag : boolean; file_arg_addr : op_desc; getputstring_desc: string_descriptor; rt_routine: rt_symbol; get_put_block: op_desc; $PAGE rt_open_call public function rt_open_call (input_file : expr) : op_desc; var local_open_mode : file_modes; local_rts : rt_symbol; local_flags : packed record case boolean of true : (word : uns_word; fill : 0..2**20 - 1); false : (bit : packed array [0..15] of boolean); end; local_string_addr : string_descriptor; local_opt_set : set_desc; local_target_set : set_desc; local_op_desc : op_desc; local_element_size : uns_word; local_counter : 0..15; local_low_value : 0..15; local_high_value : 0..15; begin local_flags.word := 0; with input_file^ do begin (* get the filename string *) if operand[1] = nil then local_string_addr := fetchtranslated (operand[2], actual_length) else local_string_addr := fetchtranslated (operand[1], actual_length); (* get the users option set *) local_opt_set := set_fetch (operand[3], 0, bits_per_word, no_preference, true); (* get the runtime symbol and set some of the option flags *) local_open_mode := desc.base^.file_kind; if local_open_mode = textfile then begin case opcode of open_op : local_rts := rt_open_text; rewrite_op : local_rts := rt_rewrite_text; reset_op : local_rts := rt_reset_text; end; end else begin if local_open_mode = typedfile then begin local_flags.bit[12] := true; local_rts := rt_open_typed; local_element_size := (desc.base^.comp_size + bits_per_byte - 1) div bits_per_byte; end else begin local_flags.bit[12] := true; local_flags.bit[13] := true; local_rts := rt_open_binary; end; end; if operand[1] <> nil then local_flags.bit[10] := true; local_flags.bit[11] := desc.base^.packable; if opcode in [rewrite_op, update_op] then local_flags.bit[14] := true; (* output file *) if opcode in [open_op, reset_op, update_op] then local_flags.bit[15] := true; (* input file *) (* push the element size, for typed files only *) if local_open_mode = typedfile then pushi (local_element_size, size_word); (* push the filename string pointer and length *) pushstring (local_string_addr, nonvarying); pushlength (local_string_addr); (* free the string descriptor *) free_string (local_string_addr); (* set and push option word, and free the set descriptor, if necessary *) with local_opt_set do begin if nargs = 0 then pushi (local_flags.word, size_word) else begin if nargs = 2 then begin if aconstp (arg[1], local_low_value) and aconstp (arg[2], local_high_value) then begin for local_counter := local_low_value to local_high_value do local_flags.bit[local_counter] := true; pushi (local_flags.word, size_word); end else begin pushi (0, size_word); with local_target_set do begin nargs := 3; in_temp := false; arg[1] := stack_top_word; arg[2] := int_desc (0, size_long, true); arg[3] := int_desc (1, size_long, true); end (* with local_target_set *); if ops_equal (arg[1], arg[2]) then begin emit_bit_inst (1, local_opt_set, local_target_set); set_free (local_opt_set); end else genset (local_opt_set, local_target_set); gen_im (or_opc, local_flags.word, stack_top_word); end; end else begin local_op_desc := duplicate_desc (arg[1]); local_op_desc.value_size := size_word; push (local_op_desc, size_word); set_free (local_opt_set); gen_im (or_opc, local_flags.word, stack_top_word); end; end; end (* with local_opt_set *); (* generate the call to the runtime routine *) gen_rt (local_rts); (* return the result descriptor *) rt_open_call := pop_long; end (* with input_file^ *); end (* rt_open_call *); $PAGE free_file (* FREE_FILE fetches the 'file variable' expression associated with an I/O operation. This routine is useful when the file variable expression must be fetched and immediately freed, simply to keep register usage counts correct. A simple 'FREE ( FETCH ( EXP ) )' will not work since the 'file' variable may in fact be a IN_STR_OP or OUT_STR_OP (i.e., the I/O operation may be a GET/PUT STRING operation) *) public procedure free_file ( exp: expr ); begin with exp^ do begin if (opcode = in_str_op) or (opcode = out_str_op) then free_string ( fetchstring ( exp, no_length, no_limit ) ) else free_desc ( fetch ( exp, all_modes, immediate_mode, any_size, false ) ); end; end (* proc free_file *) ; $PAGE rt_io_call public procedure rt_io_call (input_file : expr; input_rts : rt_symbol); var local_op_desc : op_desc; begin local_op_desc := fetch (input_file, nonstack_modes + stack_modes, postincrement_mode, any_size, true); push (local_op_desc, size_long); gen_rt (input_rts); end (* rt_io_call *); $PAGE rt_seek_call public procedure rt_seek_call (input_file : expr; input_index : expr); var local_file_addr : op_desc; local_index_addr : op_desc; begin (* fetch all parameters *) local_file_addr := fetch (input_file, nonstack_modes, immediate_mode, any_size, true); local_index_addr := fetch (input_index, nonstack_modes, immediate_mode, any_size, true); (* push all parameters *) push (local_index_addr, size_long); push (local_file_addr, size_long); (* generate the runtime call *) gen_rt (rt_seek); end (* rt_seek_call *); $PAGE io_begins public procedure io_begins (input_node : tuple); var areg: addr_regs; str_desc: string_descriptor; temp_desc: op_desc; (* FREE_RHS is passed as a parameter to MOVE_STRING to free the source string being copied to a temporary. *) procedure free_rhs; begin free_string ( str_desc ); end; begin with input_node^.file_arg^ do begin if opcode = in_str_op then begin (* getstring *) str_desc := fetchstring ( input_node^.file_arg, actual_length, no_limit ); init_string_descriptor ( getputstring_desc ); with getputstring_desc do begin type_desc := str_desc.type_desc; max_len := str_desc.max_len; len_addr := duplicate_desc ( str_desc.len_addr ); (* Allocate a temporary into which the source string will be copied. *) if type_desc.str_flex then base_addr := get_temp ( duplicate_desc ( len_addr ), false ) else base_addr := get_temp ( int_desc ( max_len, size_word, false ), false ); text_valid := true; text_addr := duplicate_desc ( base_addr ); end (* with *); move_string ( getputstring_desc, str_desc, false, free_rhs, false, false ); (* Allocate and initialize the runtime's control block. *) get_put_block := get_temp ( int_desc ( 8, size_long, false ), false ); get_put_block := increment_addr ( get_put_block, 6 ); get_put_block.value_size := size_word; gen_mm ( move_opc, getputstring_desc.len_addr, get_put_block ); get_put_block := increment_addr ( get_put_block, -2 ); gen_m ( clr_opc, get_put_block ); get_put_block := increment_addr ( get_put_block, -4 ); get_put_block.value_size := size_long; areg := get_areg (); gen_mm ( lea_opc, getputstring_desc.base_addr, reg_desc ( areg, size_long, true ) ); gen_rm ( move_opc, areg, get_put_block ); free_reg ( areg ); rt_routine := rt_getstring; getputstring_flag := true; end else if opcode = out_str_op then begin (* putstring *) str_desc := fetchstring ( input_node^.file_arg, max_length, no_limit ); (* Allocate a temporary for the putstring, in case the target string overlaps. *) init_string_descriptor ( getputstring_desc ); with getputstring_desc do begin type_desc := str_desc.type_desc; max_len := str_desc.max_len; if type_desc.str_flex then begin if type_desc.str_kind = varying then base_addr := str_varying_dynamic_temp ( str_desc.len_addr ) else base_addr := get_temp ( duplicate_desc ( str_desc.len_addr ), false ); end else begin if type_desc.str_kind = varyi then base_addr := get_temp ( int_desc ( str_desc.max_len + 2, size_word, false ), false ) else base_addr := get_temp ( int_desc ( str_desc.max_len, size_word, false ), false ); end; if type_desc.str_kind = varying then begin (* Init length to zero *) getputstring_desc.len_addr := duplicate_desc ( getputstring_desc.base_addr ); getputstring_desc.len_addr.value_size := size_word; temp_desc := skip_desc_word ( getputstring_desc ); gen_m ( clr_opc, temp_desc ); free_desc ( temp_desc ); rt_routine := rt_putstring_varying; end else begin getputstring_desc.len_addr := duplicate_desc ( str_desc.len_addr ); rt_routine := rt_putstring_fixed; end; end; (* Allocate the runtime's control block and initialize it. *) get_put_block := get_temp ( int_desc ( 8, size_long, false ), false ); get_put_block := increment_addr ( get_put_block, 6 ); get_put_block.value_size := size_word; if str_desc.type_desc.str_flex then gen_mm ( move_opc, str_desc.len_addr, get_put_block ) else gen_im ( move_opc, str_desc.max_len, get_put_block ); get_put_block := increment_addr ( get_put_block, -2 ); gen_m ( clr_opc, get_put_block ); get_put_block := increment_addr ( get_put_block, -4 ); areg := get_areg (); gen_mm ( lea_opc, getputstring_desc.base_addr, reg_desc ( areg, size_long, true ) ); get_put_block.value_size := size_long; gen_rm ( move_opc, areg, get_put_block ); free_reg ( areg ); free_string ( str_desc ); getputstring_flag := true; end else begin (* file i/o *) getputstring_flag := false; file_arg_addr := fetch (input_node^.file_arg, nonstack_modes, immediate_mode, any_size, true); free_desc (file_arg_addr); end; end (* with input_node^.file_arg^ *); end (* io_begins *); $PAGE io_ends public procedure io_ends (input_node : tuple); var str_desc: string_descriptor; length_word_addr, len_desc: op_desc; (* FREE_BOTH_STRINGS is passed as a parameter to MOVE_STRING to free the string descriptors for the temporary and destination strings in a PUTSTRING operation. *) procedure free_both_strings; begin free_string ( getputstring_desc ); free_string ( str_desc ); end; begin if getputstring_flag then begin (* If this was a putstring to a fixed string, call the runtime to pad the target. *) if rt_routine = rt_putstring_fixed then begin pusha ( get_put_block ); gen_rt ( rt_putstring_pad ); end; if rt_routine = rt_getstring then begin free_string ( getputstring_desc ); free_file ( input_node^.file_arg ); end else begin (* For a putstring we must copy the temporary to the target string. *) str_desc := fetchstring ( input_node^.file_arg, max_length, no_limit ); if str_desc.type_desc.str_kind = varying then begin (* must copy length word *) length_word_addr := skip_desc_word ( str_desc ); len_desc := skip_desc_word ( getputstring_desc ); gen_mm ( move_opc, len_desc, length_word_addr ); free_desc ( len_desc ); free_desc ( length_word_addr ); end; move_string ( str_desc, getputstring_desc, false, free_both_strings, false, false ); end end else begin (* file code *) free_file ( input_node^.file_arg ); end; end (* io_ends *); $PAGE check_desc procedure check_desc (var var_desc : op_desc; input_desc : expr_type_desc); var local_desc : op_desc; local_size : 1..4; begin (* Double precision real numbers always have a base type of REAL, which confuses OPS_TYPE into believing they are SIZE_LONG. Since no action by CHECK_DESC should be necessary anyway, we merely assert that such reals are where they should be. *) if (input_desc.kind = reals) andif (input_desc.precision > srealprec) then begin assert (not (var_desc.mode in register_modes + [immediate_mode] + stack_modes)); end else begin ops_type (local_desc, input_desc.base, false); var_desc := coerce (var_desc, nonstack_modes, var_desc.mode, [local_desc.value_size], local_desc.signed_value); if var_desc.mode in register_modes + [immediate_mode] then begin if var_desc.mode in register_modes then begin case var_desc.value_size of size_byte : local_size := 1; size_word : local_size := 2; size_long : local_size := 4; end (* case *); local_desc := get_temp (int_desc (local_size, no_size, true), false); local_desc.value_size := var_desc.value_size; gen_mm (move_opc, var_desc, local_desc); end else begin assert (var_desc.cst_part.kind = absolute_sc); local_desc := gen_cst (var_desc.cst_part.offset, local_desc.value_size); end; free_desc (var_desc); var_desc := local_desc; end; end; end (* check_desc *); $PAGE read_write_call public procedure read_write_call (input_node : tuple) options assembly; var local_flags : packed record case boolean of true : (word : uns_word; fill : 0..2**20-1); false : (bit : packed array [0..15] of boolean); end; local_string_addr : string_descriptor; local_item_addr : op_desc; local_width_addr : op_desc; local_prec_addr : op_desc; local_def_ptr : def; local_chkblk_op: op_desc; local_check_input_flag : boolean; begin local_flags.word := 0; with input_node^ do begin if rw_mode = binaryrw then begin (* binary read/write *) (* fetch all parameters *) local_item_addr := fetch (rw_item, nonstack_modes, immediate_mode, any_size, true); local_width_addr := fetch (rw_width, nonstack_modes, immediate_mode, any_size, true); (* process all parameters *) push (local_width_addr, size_long); check_desc (local_item_addr, rw_item^.desc); pusha (local_item_addr); push (duplicate_desc (file_arg_addr), size_long); (* generate the runtime call *) if opcode = read_op then gen_rt (rt_read_binary) else gen_rt (rt_write_binary); end else begin (* text or typed read/write *) (* fetch all parameters *) if rw_item^.desc.kind = strings then begin if opcode = read_op then local_string_addr := fetchstring (rw_item, max_length, no_limit) else local_string_addr := fetchtranslated (rw_item, actual_length); end else begin if (rw_item^.desc.kind = reals) andif (rw_item^.desc.precision > srealprec) then local_item_addr := dfetch (rw_item, descriptors[null_mode], false) else local_item_addr := fetch (rw_item, nonstack_modes, immediate_mode, any_size, true); end; if rw_width <> nil then local_width_addr := fetch (rw_width, nonstack_modes, immediate_mode, any_size, true); if rw_precision <> nil then begin local_prec_addr := fetch (rw_precision, nonstack_modes, immediate_mode, any_size, true); if rw_mode = realrw then begin (* TEMP FIX --- take precision from item, not RW_PRECISION *) free_desc ( local_prec_addr ); local_prec_addr := int_desc ( rw_item^.desc.precision, size_long, false ); end; end; (* process subrange limits, if any *) local_check_input_flag := false; if (chk_inp_opt in cur_block^.semantic_options) and (opcode = read_op) and (rw_mode in [decimalrw, octalrw, hexrw, realrw, fixedrw, floatrw]) then local_check_input_flag := true; if local_check_input_flag then begin with rw_item^.desc do begin if kind = ints then begin if (base^.minval = minimum (longword)) and (base^.maxval = maximum (longword)) then local_check_input_flag := false; end else begin if (base^.minval = type_real^.rminval) and (base^.maxval = type_real^.rmaxval) then local_check_input_flag := false; end; end (* with rw_item^.desc *); end; if local_check_input_flag then begin local_def_ptr := def_create (const_def); gen_def (cst_area, local_def_ptr); with rw_item^.desc do begin if kind = ints then begin gen_long (cst_area, (base^.minval, absolute_sc), false); gen_long (cst_area, (base^.maxval, absolute_sc), false); end else begin if rw_item^.desc.precision > srealprec then begin gen_dreal (cst_area, base^.minval); gen_dreal (cst_area, base^.maxval); end else begin gen_sreal (cst_area, base^.minval); gen_sreal (cst_area, base^.maxval); end; end; end (* with rw_item^.desc *); local_chkblk_op := descriptors [pc_displacement_mode]; local_chkblk_op.cst_part := def_reloc (local_def_ptr); pusha (local_chkblk_op) end; (* process field width, if any *) if rw_width <> nil then push (local_width_addr, size_long); (* process string length word, if any *) if rw_item^.desc.kind = strings then pushlength (local_string_addr) else if rw_item^.desc.kind = chars then (* fake length word *) pushi (1, size_word); (* process precision, for reals only *) if rw_precision <> nil then push (local_prec_addr, size_long) else if (rw_item^.desc.kind = reals) andif (rw_mode = floatrw) then pushi (0, size_long); (* Supply dummy precision to be ignored *) (* process option word *) case rw_item^.desc.kind of ints : begin local_flags.bit[9] := (rw_mode = hexrw); local_flags.bit[10] := (rw_mode = octalrw); end; reals: begin if rw_item^.desc.precision > srealprec then local_flags.bit[14] := true else local_flags.bit[15] := true; if rw_mode = fixedrw then local_flags.bit[7] := true; if rw_mode = floatrw then begin local_flags.bit[8] := true; if rw_precision <> nil then local_flags.bit[7] := true; end; end; strings : begin if local_string_addr.type_desc.str_kind = varying then begin local_flags.bit[14] := true; local_flags.bit[15] := true; end else local_flags.bit[13] := true; end; chars : begin local_flags.bit[13] := true; end; bools : begin local_flags.bit[13] := true; local_flags.bit[15] := true; end; end (* case *); local_flags.bit[12] := (rw_mode = leftrw); local_flags.bit[11] := (rw_width <> nil); local_flags.bit[6] := local_check_input_flag; pushi (local_flags.word, size_word); (* process item address *) with rw_item^.desc do begin if kind = strings then begin if (opcode = read_op) and (local_string_addr.type_desc.str_kind = varying) then pushstring (local_string_addr, varying) else pushstring (local_string_addr, nonvarying); free_string (local_string_addr); end else begin check_desc (local_item_addr, rw_item^.desc); pusha (local_item_addr); end; end (* with rw_item^.desc *); if (rw_item^.desc.kind = reals) andif (rw_item^.desc.precision > srealprec) then dfpop; if getputstring_flag then begin pusha ( get_put_block ); gen_rt ( rt_routine ); end else begin push (duplicate_desc (file_arg_addr), size_long); if opcode = read_op then gen_rt (rt_read_text) else gen_rt (rt_write_text); end; end; free_file ( rw_file ); end (* with input_node^ *); end (* read_write_call *). c`yž
unit testfile_GenericClass; interface type TGenericArray<T> = array of T; type TMyData<T> = class(TObject) public function Add(const aExistingSet: TGenericArray<T>; const aNewValue: T): TGenericArray<T>; end; implementation { TMyData<T> } function TMyData<T>.Add(const aExistingSet: TGenericArray<T>; const aNewValue: T): TGenericArray<T>; begin { You could append the new value to the existing set and return it here. } end; end.
unit Model.Generator.Params; interface uses System.SysUtils, Model.Interfaces; type TModelGeneratorParams = class(TInterfacedObject, iModelGeneratorParams) private [weak] FParent : iModelGenerator; FDisplay : TProc<string>; FDiretorio : String; FPrefixo : String; FProjeto : String; FCaptalizar : Boolean; FSwaggerDoc : Boolean; FRemoverCaracter : Boolean; public constructor Create( aParent : iModelGenerator); Destructor Destroy; override; class function New( aParent : iModelGenerator) : iModelGeneratorParams; function Captalizar( aValue: Boolean) : iModelGeneratorParams; overload; function Captalizar: Boolean; overload; function SwaggerDoc( aValue: Boolean) : iModelGeneratorParams; overload; function SwaggerDoc : Boolean; overload; function RemoverCaracter( aValue: Boolean) : iModelGeneratorParams; overload; function RemoverCaracter: Boolean; overload; function Display( aDisplay : TProc<string>) : iModelGeneratorParams; overload; function Display(aValue : String): iModelGeneratorParams; overload; function Diretorio( aValue : String) : iModelGeneratorParams; overload; function Diretorio : String; overload; function Prefixo( aValue : String) : iModelGeneratorParams; overload; function Prefixo: String; overload; function Projeto( aValue : String) : iModelGeneratorParams; overload; function Projeto: String; overload; function &End :iModelGenerator; end; implementation { TModelGeneratorParams } function TModelGeneratorParams.Captalizar(aValue: Boolean): iModelGeneratorParams; begin Result := Self; FCaptalizar := aValue; end; function TModelGeneratorParams.Captalizar: Boolean; begin Result := FCaptalizar; end; function TModelGeneratorParams.&End: iModelGenerator; begin Result := FParent; end; constructor TModelGeneratorParams.Create( aParent : iModelGenerator); begin FCaptalizar := False; FRemoverCaracter := False; FProjeto := ''; FParent := aParent; end; destructor TModelGeneratorParams.Destroy; begin inherited; end; function TModelGeneratorParams.Diretorio(aValue: String): iModelGeneratorParams; begin Result := Self; FDiretorio := aValue; end; function TModelGeneratorParams.Diretorio: String; begin Result := FDiretorio; end; function TModelGeneratorParams.Display(aValue : String): iModelGeneratorParams; begin Result := Self; FDisplay(aValue); end; function TModelGeneratorParams.Display(aDisplay: TProc<string>): iModelGeneratorParams; begin Result := Self; FDisplay := aDisplay; end; class function TModelGeneratorParams.New( aParent : iModelGenerator) : iModelGeneratorParams; begin Result := Self.Create(aParent); end; function TModelGeneratorParams.Prefixo: String; begin Result := FPrefixo; end; function TModelGeneratorParams.Projeto: String; begin Result := FProjeto; end; function TModelGeneratorParams.Projeto(aValue: String): iModelGeneratorParams; begin Result := Self; FProjeto := aValue; end; function TModelGeneratorParams.Prefixo(aValue: String): iModelGeneratorParams; begin Result := Self; FPrefixo := aValue; end; function TModelGeneratorParams.RemoverCaracter(aValue: Boolean): iModelGeneratorParams; begin Result := Self; FRemoverCaracter := aValue; end; function TModelGeneratorParams.RemoverCaracter: Boolean; begin Result := FRemoverCaracter; end; function TModelGeneratorParams.SwaggerDoc: Boolean; begin Result := FSwaggerDoc; end; function TModelGeneratorParams.SwaggerDoc(aValue: Boolean): iModelGeneratorParams; begin Result := Self; FSwaggerDoc := aValue; end; end.
unit uCategoriaController; interface uses System.SysUtils, uDMCategoria, uRegras, uEnumerador, uDM, Data.DB, Vcl.Forms, uFuncoesSIDomper; type TCategoriaController = class private FModel: TDMCategoria; FOperacao: TOperacao; procedure Post; public procedure Filtrar(ACampo, ATexto, AAtivo: string; AContem: Boolean = False); procedure FiltrarCodigo(ACodigo: Integer); procedure LocalizarId(AId: Integer); procedure LocalizarCodigo(ACodigo: integer); procedure Novo(AIdUsuario: Integer); procedure Editar(AId: Integer; AFormulario: TForm); procedure Salvar(AIdUsuario: Integer); procedure Excluir(AIdUsuario, AId: Integer); procedure Cancelar(); procedure Imprimir(AIdUsuario: Integer); function ProximoId(): Integer; function ProximoCodigo(): Integer; procedure Pesquisar(AId, Codigo: Integer); function CodigoAtual: Integer; property Model: TDMCategoria read FModel write FModel; constructor Create(); destructor Destroy; override; end; implementation { TProdutoController } procedure TCategoriaController.Cancelar; begin if FModel.CDSCadastro.State in [dsEdit, dsInsert] then FModel.CDSCadastro.Cancel; end; function TCategoriaController.CodigoAtual: Integer; begin Result := FModel.CDSCadastroCat_Codigo.AsInteger; end; constructor TCategoriaController.Create; begin inherited Create; FModel := TDMCategoria.Create(nil); end; destructor TCategoriaController.Destroy; begin FreeAndNil(FModel); inherited; end; procedure TCategoriaController.Editar(AId: Integer; AFormulario: TForm); var Negocio: TServerModule2Client; Resultado: Boolean; begin if AId = 0 then raise Exception.Create('Não há Registro para Editar!'); dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try try FModel.CDSCadastro.Close; Resultado := Negocio.Editar(CCategoriaPrograma, dm.IdUsuario, AId); FModel.CDSCadastro.Open; TFuncoes.HabilitarCampo(AFormulario, Resultado); dm.Desconectar; except On E: Exception do begin dm.ErroConexao(E.Message); end; end; FOperacao := opEditar; finally FreeAndNil(Negocio); end; end; procedure TCategoriaController.Excluir(AIdUsuario, AId: Integer); var Negocio: TServerModule2Client; begin if AId = 0 then raise Exception.Create('Não há Registro para Excluir!'); dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try try Negocio.Excluir(CCategoriaPrograma, AIdUsuario, AId); FModel.CDSConsulta.Delete; dm.Desconectar; except on E: Exception do begin dm.ErroConexao(E.Message); end; end; finally FreeAndNil(Negocio); end; end; procedure TCategoriaController.Filtrar(ACampo, ATexto, AAtivo: string; AContem: Boolean); var Negocio: TServerModule2Client; begin dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try try FModel.CDSConsulta.Close; Negocio.Filtrar(CCategoriaPrograma, ACampo, ATexto, AAtivo, AContem); FModel.CDSConsulta.Open; dm.Desconectar; except On E: Exception do begin dm.ErroConexao(E.Message); end; end; finally FreeAndNil(Negocio); end; end; procedure TCategoriaController.FiltrarCodigo(ACodigo: Integer); var Negocio: TServerModule2Client; begin dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try try FModel.CDSConsulta.Close; Negocio.FiltrarCodigo(CCategoriaPrograma, ACodigo); FModel.CDSConsulta.Open; dm.Desconectar; except on E: Exception do begin dm.ErroConexao(E.Message); end; end; finally FreeAndNil(Negocio); end; end; procedure TCategoriaController.Imprimir(AIdUsuario: Integer); var Negocio: TServerModule2Client; begin dm.Conectar; Negocio := TServerModule2Client.Create(dm.Conexao.DBXConnection); try try Negocio.Relatorio(CCategoriaPrograma, AIdUsuario); FModel.Rel.Print; dm.Desconectar; except on E: Exception do begin dm.ErroConexao(E.Message); end; end; finally FreeAndNil(Negocio); end; end; procedure TCategoriaController.LocalizarCodigo(ACodigo: integer); var Negocio: TServerModule2Client; begin dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try try FModel.CDSCadastro.Close; Negocio.LocalizarCodigo(CCategoriaPrograma, ACodigo); FModel.CDSCadastro.Open; dm.Desconectar; except on E: Exception do begin dm.ErroConexao(E.Message); end; end; finally FreeAndNil(Negocio); end; end; procedure TCategoriaController.LocalizarId(AId: Integer); var Negocio: TServerModule2Client; begin dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try try FModel.CDSCadastro.Close; Negocio.LocalizarId(CCategoriaPrograma, AId); FModel.CDSCadastro.Open; dm.Desconectar; except On E: Exception do begin dm.ErroConexao(E.Message); end; end; finally FreeAndNil(Negocio); end; end; procedure TCategoriaController.Novo(AIdUsuario: Integer); var Negocio: TServerModule2Client; begin dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try try FModel.CDSCadastro.Close; Negocio.Novo(CCategoriaPrograma, AIdUsuario); FModel.CDSCadastro.Open; FModel.CDSCadastro.Append; FModel.CDSCadastroCat_Codigo.AsInteger := ProximoCodigo(); FOperacao := opIncluir; dm.Desconectar; except On E: Exception do begin dm.ErroConexao(E.Message); end; end; finally FreeAndNil(Negocio); end; end; procedure TCategoriaController.Pesquisar(AId, Codigo: Integer); begin if AId > 0 then LocalizarId(AId) else LocalizarCodigo(Codigo); end; procedure TCategoriaController.Post; begin if FModel.CDSConsulta.State in [dsEdit, dsInsert] then FModel.CDSConsulta.Post; end; function TCategoriaController.ProximoCodigo: Integer; var Negocio: TServerModule2Client; iCodigo: Integer; begin dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try try iCodigo := StrToInt(Negocio.ProximoCodigo(CCategoriaPrograma).ToString); Result := iCodigo; dm.Desconectar; except on E: Exception do begin dm.ErroConexao(E.Message); end; end; finally FreeAndNil(Negocio); end; end; function TCategoriaController.ProximoId: Integer; var Negocio: TServerModule2Client; iCodigo: Integer; begin dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try try iCodigo := StrToInt(Negocio.ProximoId(CCategoriaPrograma).ToString); Result := iCodigo; dm.Desconectar; except on E: Exception do begin dm.ErroConexao(E.Message); end; end; finally FreeAndNil(Negocio); end; end; procedure TCategoriaController.Salvar(AIdUsuario: Integer); var Negocio: TServerModule2Client; ConsultaSQL: string; id: Integer; begin if FModel.CDSCadastroCat_Codigo.AsInteger <= 0 then raise Exception.Create('Informe o Código!'); if Trim(FModel.CDSCadastroCat_Nome.AsString) = '' then raise Exception.Create('Informe o Nome!'); dm.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try Post(); Negocio.Salvar(CCategoriaPrograma, AIdUsuario); FModel.CDSCadastro.ApplyUpdates(0); FOperacao := opNavegar; dm.Desconectar; finally FreeAndNil(Negocio); end; end; end.
unit Rule_STD; interface uses BaseRule, BaseRuleData; (*// STD 含义:求标准差。 用法:STD(X,N)为X的N日估算标准差。 //*) type TRule_STD = class(TBaseRule) protected FParamN: Word; fFloatRet: PArray; function GetStdValueF(AIndex: integer): double; procedure SetParamN(const Value: Word); procedure ComputeInt64; procedure ComputeFloat; public constructor Create(ADataType: TRuleDataType = dtDouble); override; destructor Destroy; override; procedure Execute; override; procedure Clear; override; property ValueF[AIndex: integer]: double read GetStdValueF; property ParamN: Word read FParamN write SetParamN; end; implementation { TRule_STD } constructor TRule_STD.Create(ADataType: TRuleDataType = dtDouble); begin inherited; fParamN := 2; fFloatRet := nil; end; destructor TRule_STD.Destroy; begin Clear; inherited; end; procedure TRule_Std.Execute; begin Clear; if Assigned(OnGetDataLength) then begin fBaseRuleData.DataLength := OnGetDataLength; case fBaseRuleData.DataType of dtInt64: begin ComputeInt64; end; dtDouble: begin ComputeFloat; end; end; end; end; procedure TRule_Std.Clear; begin CheckInArray(fFloatRet); fBaseRuleData.DataLength := 0; end; procedure TRule_Std.ComputeInt64; var tmpInt64_Meta: PArray; tmpInt64_v1: PArray; tmpInt64_Ret: PArray; i, j: integer; tmpInt64: int64; begin if Assigned(OnGetDataI) then begin if fFloatRet = nil then fFloatRet := CheckOutArrayDouble; tmpInt64_Ret := CheckOutArrayInt64; tmpInt64_Meta := CheckOutArrayInt64; tmpInt64_v1 := CheckOutArrayInt64; try SetArrayLength(tmpInt64_Ret, fBaseRuleData.DataLength); SetArrayLength(tmpInt64_Meta, fBaseRuleData.DataLength); SetArrayLength(tmpInt64_v1, fBaseRuleData.DataLength); SetArrayLength(fFloatRet, fBaseRuleData.DataLength); //tmpInt64_MetaNode := tmpInt64_Meta.FirstValueNode; //tmpInt64_v1Node := tmpInt64_v1.FirstValueNode; //tmpInt64_RetNode := tmpInt64_Ret.FirstValueNode; //tmpFloatRetNode := fFloatRet.FirstValueNode; for i := 0 to fBaseRuleData.DataLength - 1 do begin tmpInt64 := OnGetDataI(i); //tmpInt64_Meta.Value[i] := tmpInt64; SetArrayInt64Value(tmpInt64_Meta, i, tmpInt64); //fFloatRet.value[i] := 0; // ------------------------------- //tmpInt64_v1.Value[i] := 0; SetArrayInt64Value(tmpInt64_v1, i, 0); for j := 0 to fParamN - 1 do begin //tmpInt64 := tmpInt64_v1.Value[i] + tmpInt64_v1.Value[i - j]; tmpInt64 := GetArrayInt64Value(tmpInt64_v1, i) + GetArrayInt64Value(tmpInt64_v1, i - j); //tmpInt64_v1.Value[i] := tmpInt64; SetArrayInt64Value(tmpInt64_v1, i, tmpInt64); end; //tmpInt64 := Round(tmpInt64_v1.Value[i] / fParamN); tmpInt64 := Round(GetArrayInt64Value(tmpInt64_v1, i) / fParamN); //tmpInt64_v1.Value[i] := tmpInt64; SetArrayInt64Value(tmpInt64_v1, i, tmpInt64); // ------------------------------- SetArrayInt64Value(tmpInt64_Ret, i, 0); for j := 0 to fParamN - 1 do begin tmpInt64 := (GetArrayInt64Value(tmpInt64_Meta, i - j) - GetArrayInt64Value(tmpInt64_v1, i)); tmpInt64 := GetArrayInt64Value(tmpInt64_Ret, i) + tmpInt64 * tmpInt64; SetArrayInt64Value(tmpInt64_Ret, i, tmpInt64); end; // ------------------------------- SetArrayDoubleValue(fFloatRet, i, Sqrt(GetArrayInt64Value(tmpInt64_Ret, i) / (fParamN - 1))); // ------------------------------- end; SetArrayLength(tmpInt64_Meta, 0); SetArrayLength(tmpInt64_v1, 0); SetArrayLength(tmpInt64_Ret, 0); finally CheckInArray(tmpInt64_Ret); CheckInArray(tmpInt64_Meta); CheckInArray(tmpInt64_v1); end; end; end; (* STD(CLOSE,10), ------------------------------------- x := (x[n] + x[n - 1] + x[1]) / n ------------------------------------- v := (x[n]-x)^2 + (x[n - 1]-x)^2 + (x[1]-x)^2 v := v / (n - 1) std = sqrt(v); ------------------------------------- sqrt(4) = 2 *) procedure TRule_Std.ComputeFloat; var tmpFloat_Meta: PArray; //tmpFloat_MetaNode: PArrayDoubleNode; tmpFloat_v1: PArray; //tmpFloat_v1Node: PArrayDoubleNode; //tmpFloatRetNode: PArrayDoubleNode; i, j, tmpCounter: integer; tmpV: double; tmpValue: double; begin if Assigned(OnGetDataF) then begin if fFloatRet = nil then fFloatRet := CheckOutArrayDouble; tmpFloat_Meta := CheckOutArrayDouble; tmpFloat_v1 := CheckOutArrayDouble; try SetArrayLength(fFloatRet, fBaseRuleData.DataLength); SetArrayLength(tmpFloat_Meta, fBaseRuleData.DataLength); SetArrayLength(tmpFloat_v1, fBaseRuleData.DataLength); //tmpFloat_MetaNode := tmpFloat_Meta.FirstValueNode; //tmpFloat_v1Node := tmpFloat_v1.FirstValueNode; //tmpFloatRetNode := fFloatRet.FirstValueNode; for i := 0 to fBaseRuleData.DataLength - 1 do begin tmpValue := OnGetDataF(i); SetArrayDoubleValue(tmpFloat_Meta, i, tmpValue); // ------------------------------- SetArrayDoubleValue(tmpFloat_v1, i, 0); tmpCounter := 0; for j := 0 to fParamN - 1 do begin if i >= j then begin tmpValue := GetArrayDoubleValue(tmpFloat_v1, i) + GetArrayDoubleValue(tmpFloat_Meta, i - j); SetArrayDoubleValue(tmpFloat_v1, i, tmpValue); Inc(tmpCounter); end else begin Break; end; end; tmpValue := GetArrayDoubleValue(tmpFloat_v1, i) / tmpCounter; SetArrayDoubleValue(tmpFloat_v1, i, tmpValue); // ------------------------------- tmpValue := 0; for j := 0 to tmpCounter - 1 do begin tmpv := GetArrayDoubleValue(tmpFloat_Meta, i - j) - GetArrayDoubleValue(tmpFloat_v1, i); tmpValue := tmpValue + tmpv * tmpv; end; // ------------------------------- if tmpCounter > 1 then begin tmpValue := tmpValue / (tmpCounter - 1); tmpValue := Sqrt(tmpValue); end else begin tmpValue := 0; end; SetArrayDoubleValue(fFloatRet, i, tmpValue); // ------------------------------- end; SetArrayLength(tmpFloat_Meta, 0); SetArrayLength(tmpFloat_v1, 0); finally CheckInArray(tmpFloat_Meta); CheckInArray(tmpFloat_v1); end; end; end; procedure TRule_Std.SetParamN(const Value: Word); begin if Value > 0 then begin FParamN := Value; end; end; function TRule_Std.GetStdValueF(AIndex: integer): double; begin Result := 0; if fBaseRuleData.DataType = dtDouble then Result := GetArrayDoubleValue(fFloatRet, AIndex); end; end.