text
stringlengths
14
6.51M
unit u_asm; {$mode objfpc}{$H+} interface uses Classes, SysUtils, u_common, u_consts, u_writers; type TCodeSection = class(TObject) public Lines: TStringList; Constants: TConstantManager; Outp: TMemoryStream; Vars: TStringList; constructor Create(sl: TStringList; vars_lst: TStringList; cnsts: TConstantManager); destructor Destroy; override; procedure ParseSection; procedure GenerateCode(Stream: TStream); end; implementation {** Code section **} constructor TCodeSection.Create(sl: TStringList; vars_lst: TStringList; cnsts: TConstantManager); begin Outp := TMemoryStream.Create; Lines := sl; Constants := cnsts; Vars := vars_lst; inherited Create; end; destructor TCodeSection.Destroy; begin Outp.Free; inherited Destroy; end; type TComand = ( {** for stack **} bcPH, // [top] = [var] bcPK, // [var] = [top] bcPHL, bcPKL, bcPP, // pop bcSDP, // stkdrop bcSWP, // [top] <-> [top-1] {** jump's **} bcJP, // jump [top] bcJZ, // [top] == 0 ? jp [top-1] bcJN, // [top] <> 0 ? jp [top-1] bcJC, // jp [top] & push callback point as ip+1 bcJR, // jp to last callback point & rem last callback point bcJRP, {** for untyped's **} bcEQ, // [top] == [top-1] ? [top] = true : [top] = false bcBG, // [top] > [top-1] ? [top] = true : [top] = false bcBE, // [top] >= [top-1] ? [top] = true : [top] = false bcNOT, // [top] = ![top] bcAND, // [top] = [top] and [top-1] bcOR, // [top] = [top] or [top-1] bcXOR, // [top] = [top] xor [top-1] bcSHR, // [top] = [top] shr [top-1] bcSHL, // [top] = [top] shl [top-1] bcNEG, // [top] = -[top] bcINC, // [top]++ bcDEC, // [top]-- bcADD, // [top] = [top] + [top-1] bcSUB, // [top] = [top] - [top-1] bcMUL, // [top] = [top] * [top-1] bcDIV, // [top] = [top] / [top-1] bcMOD, // [top] = [top] % [top-1] bcIDIV, // [top] = [top] \ [top-1] bcMV, // [top]^ = [top-1]^ bcMVBP, // [top]^^ = [top-1]^ bcGVBP, // [top]^ = [top-1]^^ bcMVP, // [top]^ = [top-1] {** memory operation's **} bcMS, // memory map size = [top] bcNW, // [top] = @new bcMC, // copy [top] bcMD, // double [top] bcNA, // [top] = @new array[ [top] ] of pointer bcTF, // [top] = typeof( [top] ) bcTMC, // [top].type = type of class bcSF, // [top] = sizeof( [top] ) bcGC, // garbage collect {** array's **} bcAL, // length( [top] as array ) bcSL, // setlength( [top] as array, {stack} ) bcPA, // push ([top] as array)[top-1] bcSA, // peek [top-2] -> ([top] as array)[top-1] {** constant's **} bcPHC, // push copy of const bcPHCP, // push pointer to original const {** external call's **} bcINV, // call external method {** for thread's **} bcPHN, // push null bcCTHR, // [top] = thread(method = [top], arg = [top+1]):id bcSTHR, // suspendthread(id = [top]) bcRTHR, // resumethread(id = [top]) bcTTHR, // terminatethread(id = [top]) bcTHSP, // set thread priority bcPLC, // push last callback bcPCT, // push context bcLCT, // load context bcJRX, // jp to last callback point & rem last callback point twice {** for try..catch..finally block's **} bcTR, // try @block_catch = [top], @block_end = [top+1] bcTRS, // success exit from try/catch block bcTRR, // raise exception, message = [top] {** for string's **} bcSTRD, // strdel bcCHORD, bcORDCH, bcTHREXT,//stop code execution bcDBP, //debug method call bcRST, bcRLD, bcRDP ); procedure TCodeSection.ParseSection; var p1, p2: cardinal; s, bf: string; v: Int64; begin p1 := 0; p2 := 0; while p2 < Lines.Count do begin s := Trim(Lines[p2]); if Length(s) > 0 then begin if (s[length(s)] = ':') then begin Constants.AddConstCardinal(copy(s, 1, length(s) - 1), p1); Lines.Delete(p2); Dec(p2); Dec(p1); end; bf := Tk(s, 1); if (bf = 'push') or (bf = 'peek') or (bf = 'pushc') or (bf = 'pushm') or (bf = 'pushcp') then Inc(p1, 5) else Inc(p1); end; Inc(p2); end; while Lines.Count > 0 do begin s := Trim(Lines[0]); bf := Tk(s, 1); Lines.Delete(0); if length(s) = 0 then // skip line else if bf = 'push' then begin v := Vars.IndexOf(Tk(s, 2)); if v = -1 then AsmErr('Invalid variable <' + Tk(s, 2) + '> call.'); if Pos('.', Tk(s, 2)) > 0 then Outp.WriteByte(byte(bcPHL)) else Outp.WriteByte(byte(bcPH)); St_WriteCardinal(Outp, v); s := ''; end else if bf = 'peek' then begin v := Vars.IndexOf(Tk(s, 2)); if v = -1 then AsmErr('Invalid variable <' + Tk(s, 2) + '> call.'); if Pos('.', Tk(s, 2)) > 0 then Outp.WriteByte(byte(bcPKL)) else Outp.WriteByte(byte(bcPK)); St_WriteCardinal(Outp, v); s := ''; end else if bf = 'pushc' then begin Outp.WriteByte(byte(bcPHC)); St_WriteCardinal(Outp, Constants.GetAddr(Tk(s, 2))); s := ''; end else if bf = 'pushcp' then begin Outp.WriteByte(byte(bcPHCP)); St_WriteCardinal(Outp, Constants.GetAddr(Tk(s, 2))); s := ''; end else if bf = 'pop' then Outp.WriteByte(byte(bcPP)) else if bf = 'stkdrop' then Outp.WriteByte(byte(bcSDP)) else if bf = 'swp' then Outp.WriteByte(byte(bcSWP)) else if bf = 'jp' then Outp.WriteByte(byte(bcJP)) else if bf = 'jz' then Outp.WriteByte(byte(bcJZ)) else if bf = 'jn' then Outp.WriteByte(byte(bcJN)) else if bf = 'jc' then Outp.WriteByte(byte(bcJC)) else if bf = 'jr' then Outp.WriteByte(byte(bcJR)) else if bf = 'eq' then Outp.WriteByte(byte(bcEQ)) else if bf = 'bg' then Outp.WriteByte(byte(bcBG)) else if bf = 'be' then Outp.WriteByte(byte(bcBE)) else if bf = 'not' then Outp.WriteByte(byte(bcNOT)) else if bf = 'and' then Outp.WriteByte(byte(bcAND)) else if bf = 'or' then Outp.WriteByte(byte(bcOR)) else if bf = 'xor' then Outp.WriteByte(byte(bcXOR)) else if bf = 'shr' then Outp.WriteByte(byte(bcSHR)) else if bf = 'shl' then Outp.WriteByte(byte(bcSHL)) else if bf = 'neg' then Outp.WriteByte(byte(bcNEG)) else if bf = 'inc' then Outp.WriteByte(byte(bcINC)) else if bf = 'dec' then Outp.WriteByte(byte(bcDEC)) else if bf = 'add' then Outp.WriteByte(byte(bcADD)) else if bf = 'sub' then Outp.WriteByte(byte(bcSUB)) else if bf = 'mul' then Outp.WriteByte(byte(bcMUL)) else if bf = 'div' then Outp.WriteByte(byte(bcDIV)) else if bf = 'mod' then Outp.WriteByte(byte(bcMOD)) else if bf = 'idiv' then Outp.WriteByte(byte(bcIDIV)) else if bf = 'mov' then Outp.WriteByte(byte(bcMV)) else if bf = 'movbp' then Outp.WriteByte(byte(bcMVBP)) else if bf = 'gvbp' then Outp.WriteByte(byte(bcGVBP)) else if bf = 'movp' then Outp.WriteByte(byte(bcMVP)) else if bf = 'msz' then Outp.WriteByte(byte(bcMS)) else if bf = 'new' then Outp.WriteByte(byte(bcNW)) else if bf = 'copy' then Outp.WriteByte(byte(bcMC)) else if bf = 'pcopy' then Outp.WriteByte(byte(bcMD)) else if bf = 'newa' then Outp.WriteByte(byte(bcNA)) else if bf = 'typeof' then Outp.WriteByte(byte(bcTF)) else if bf = 'typemarkclass' then Outp.WriteByte(byte(bcTMC)) else if bf = 'sizeof' then Outp.WriteByte(byte(bcSF)) else if bf = 'alen' then Outp.WriteByte(byte(bcAL)) else if bf = 'salen' then Outp.WriteByte(byte(bcSL)) else if bf = 'pushai' then Outp.WriteByte(byte(bcPA)) else if bf = 'peekai' then Outp.WriteByte(byte(bcSA)) else if bf = 'gc' then Outp.WriteByte(byte(bcGC)) else if bf = 'invoke' then Outp.WriteByte(byte(bcINV)) else if bf = 'pushn' then Outp.WriteByte(byte(bcPHN)) else if bf = 'cthr' then Outp.WriteByte(byte(bcCTHR)) else if bf = 'sthr' then Outp.WriteByte(byte(bcSTHR)) else if bf = 'rthr' then Outp.WriteByte(byte(bcRTHR)) else if bf = 'tthr' then Outp.WriteByte(byte(bcTTHR)) else if bf = 'thsp' then Outp.WriteByte(byte(bcTHSP)) else if bf = 'plc' then Outp.WriteByte(byte(bcPLC)) else if bf = 'pct' then Outp.WriteByte(byte(bcPCT)) else if bf = 'lct' then Outp.WriteByte(byte(bcLCT)) else if bf = 'jrx' then Outp.WriteByte(byte(bcJRX)) else if bf = 'tr' then Outp.WriteByte(byte(bcTR)) else if bf = 'trs' then Outp.WriteByte(byte(bcTRS)) else if bf = 'trr' then Outp.WriteByte(byte(bcTRR)) else if bf = 'strd' then Outp.WriteByte(byte(bcSTRD)) else if bf = 'chord' then Outp.WriteByte(byte(bcCHORD)) else if bf = 'ordch' then Outp.WriteByte(byte(bcORDCH)) else if bf = 'threxit' then Outp.WriteByte(byte(bcTHREXT)) else if bf = 'dbgbreakpoint' then Outp.WriteByte(byte(bcDBP)) else if bf = 'rst' then Outp.WriteByte(byte(bcRST)) else if bf = 'rld' then Outp.WriteByte(byte(bcRLD)) else if bf = 'rdp' then Outp.WriteByte(byte(bcRDP)) else if bf = 'jrp' then Outp.WriteByte(byte(bcJRP)) else if Length(s) > 0 then AsmErr('Invalid token in line: "' + s + '"'); end; end; procedure TCodeSection.GenerateCode(Stream: TStream); begin Stream.WriteBuffer(Outp.Memory^, Outp.Size); end; end.
unit Mmx; {* MMX support unit. By Vladimir Kladov, 2003. } interface {$I KOLDEF.INC} uses Windows, Kol; type TCpuId = ( cpuNew486, cpuMMX, cpuMMX_Plus, cpu3DNow, cpu3DNow_Plus, cpuSSE, cpuSSE2 ); {* Enumeration type to represent CPU type. cpuOld486: Old 486 Processor and earlier cpuNew486: New 486 Processor to Pentium1 without MMX cpuMMX : MMX supported (but not SSE or SSE2) cpuSSE : MMX and SSE supported (but not SSE2) cpuSSE2 : MMX, SSE and SSE2 supported } TCpuCaps = set of TCpuId; function GetCPUType: TCpuCaps; {* Checks CPU (Intel PC x86 Architecture) for MMX support. |<p><p> Use following constants in shuffle commands (like "pshufw") as third operand to instruct to which locations (0,1,2,3) source parts should be placed: } const SH0000 = $00; SH0001 = $01; SH0002 = $02; SH0003 = $03; SH0010 = $04; SH0011 = $05; SH0012 = $06; SH0013 = $07; SH0020 = $08; SH0021 = $09; SH0022 = $0A; SH0023 = $0B; SH0030 = $0C; SH0031 = $0D; SH0032 = $0E; SH0033 = $0F; SH0100 = $10; SH0101 = $11; SH0102 = $12; SH0103 = $13; SH0110 = $14; SH0111 = $15; SH0112 = $16; SH0113 = $17; SH0120 = $18; SH0121 = $19; SH0122 = $1A; SH0123 = $1B; SH0130 = $1C; SH0131 = $1D; SH0132 = $1E; SH0133 = $1F; SH0200 = $20; SH0201 = $21; SH0202 = $22; SH0203 = $23; SH0210 = $24; SH0211 = $25; SH0212 = $26; SH0213 = $27; SH0220 = $28; SH0221 = $29; SH0222 = $2A; SH0223 = $2B; SH0230 = $2C; SH0231 = $2D; SH0232 = $2E; SH0233 = $2F; SH0300 = $30; SH0301 = $31; SH0302 = $32; SH0303 = $33; SH0310 = $34; SH0311 = $35; SH0312 = $36; SH0313 = $37; SH0320 = $38; SH0321 = $39; SH0322 = $3A; SH0323 = $3B; SH0330 = $3C; SH0331 = $3D; SH0332 = $3E; SH0333 = $3F; SH1000 = $40; SH1001 = $41; SH1002 = $42; SH1003 = $43; SH1010 = $44; SH1011 = $45; SH1012 = $46; SH1013 = $47; SH1020 = $48; SH1021 = $49; SH1022 = $4A; SH1023 = $4B; SH1030 = $4C; SH1031 = $4D; SH1032 = $4E; SH1033 = $4F; SH1100 = $50; SH1101 = $51; SH1102 = $52; SH1103 = $53; SH1110 = $54; SH1111 = $55; SH1112 = $56; SH1113 = $57; SH1120 = $58; SH1121 = $59; SH1122 = $5A; SH1123 = $5B; SH1130 = $5C; SH1131 = $5D; SH1132 = $5E; SH1133 = $5F; SH1200 = $60; SH1201 = $61; SH1202 = $62; SH1203 = $63; SH1210 = $64; SH1211 = $65; SH1212 = $66; SH1213 = $67; SH1220 = $68; SH1221 = $69; SH1222 = $6A; SH1223 = $6B; SH1230 = $6C; SH1231 = $6D; SH1232 = $6E; SH1233 = $6F; SH1300 = $70; SH1301 = $71; SH1302 = $72; SH1303 = $73; SH1310 = $74; SH1311 = $75; SH1312 = $76; SH1313 = $77; SH1320 = $78; SH1321 = $79; SH1322 = $7A; SH1323 = $7B; SH1330 = $7C; SH1331 = $7D; SH1332 = $7E; SH1333 = $7F; SH2000 = $80; SH2001 = $81; SH2002 = $82; SH2003 = $83; SH2010 = $84; SH2011 = $85; SH2012 = $86; SH2013 = $87; SH2020 = $88; SH2021 = $89; SH2022 = $8A; SH2023 = $8B; SH2030 = $8C; SH2031 = $8D; SH2032 = $8E; SH2033 = $8F; SH2100 = $90; SH2101 = $91; SH2102 = $92; SH2103 = $93; SH2110 = $94; SH2111 = $95; SH2112 = $96; SH2113 = $97; SH2120 = $98; SH2121 = $99; SH2122 = $9A; SH2123 = $9B; SH2130 = $9C; SH2131 = $9D; SH2132 = $9E; SH2133 = $9F; SH2200 = $A0; SH2201 = $A1; SH2202 = $A2; SH2203 = $A3; SH2210 = $A4; SH2211 = $A5; SH2212 = $A6; SH2213 = $A7; SH2220 = $A8; SH2221 = $A9; SH2222 = $AA; SH2223 = $AB; SH2230 = $AC; SH2231 = $AD; SH2232 = $AE; SH2233 = $AF; SH2300 = $B0; SH2301 = $B1; SH2302 = $B2; SH2303 = $B3; SH2310 = $B4; SH2311 = $B5; SH2312 = $B6; SH2313 = $B7; SH2320 = $B8; SH2321 = $B9; SH2322 = $BA; SH2323 = $BB; SH2330 = $BC; SH2331 = $BD; SH2332 = $BE; SH2333 = $BF; SH3000 = $C0; SH3001 = $C1; SH3002 = $C2; SH3003 = $C3; SH3010 = $C4; SH3011 = $C5; SH3012 = $C6; SH3013 = $C7; SH3020 = $C8; SH3021 = $C9; SH3022 = $CA; SH3023 = $CB; SH3030 = $CC; SH3031 = $CD; SH3032 = $CE; SH3033 = $CF; SH3100 = $D0; SH3101 = $D1; SH3102 = $D2; SH3103 = $D3; SH3110 = $D4; SH3111 = $D5; SH3112 = $D6; SH3113 = $D7; SH3120 = $D8; SH3121 = $D9; SH3122 = $DA; SH3123 = $DB; SH3130 = $DC; SH3131 = $DD; SH3132 = $DE; SH3133 = $DF; SH3200 = $E0; SH3201 = $E1; SH3202 = $E2; SH3203 = $E3; SH3210 = $E4; SH3211 = $E5; SH3212 = $E6; SH3213 = $E7; SH3220 = $E8; SH3221 = $E9; SH3222 = $EA; SH3223 = $EB; SH3230 = $EC; SH3231 = $ED; SH3232 = $EE; SH3233 = $EF; SH3300 = $F0; SH3301 = $F1; SH3302 = $F2; SH3303 = $F3; SH3310 = $F4; SH3311 = $F5; SH3312 = $F6; SH3313 = $F7; SH3320 = $F8; SH3321 = $F9; SH3322 = $FA; SH3323 = $FB; SH3330 = $FC; SH3331 = $FD; SH3332 = $FE; SH3333 = $FF; implementation var cpu: TCpuCaps = [ ]; function GetCPUType: TCpuCaps; var I, J: Integer; Vend1: array[ 0..3 ] of Char; begin Result := cpu; // old 486 and earlier if Result <> [] then Exit; I := 0; asm // check if bit 21 of EFLAGS can be set and reset PUSHFD POP EAX OR EAX, 1 shl 21 PUSH EAX POPFD PUSHFD POP EAX TEST EAX, 1 shl 21 JZ @@1 AND EAX, not( 1 shl 21 ) PUSH EAX POPFD PUSHFD POP EAX TEST EAX, 1 shl 21 JNZ @@1 INC [ I ] @@1: end; if I = 0 then Exit; // CPUID not supported Include( Result, cpuNew486 ); // at least cpuNew486 asm // get CPU features flags using CPUID command PUSH EBX MOV EAX, 0 DB $0F, $A2 //CPUID : EAX, EBX, EDX and ECX are changed!!! MOV [ Vend1 ], EBX MOV EAX, 1 DB $0F, $A2 //CPUID : EAX, EBX, EDX and ECX are changed!!! MOV [ I ], EDX // I := features information POP EBX end; if (I and (1 shl 23)) = 0 then Exit; // MMX not supported at all Include( Result, cpuMMX ); // MMX supported. if Vend1 = 'Auth' then // AuthenticAMD ? begin asm PUSH EBX MOV EAX, $80000001 DB $0F, $A2 //CPUID : EAX, EBX, EDX and ECX are changed!!! MOV [ J ], EDX POP EBX end; if (J and (1 shl 22)) <> 0 then Include( Result, cpuMMX_Plus ); // MMX+ supported. if (J and (1 shl 31)) <> 0 then begin Include( Result, cpu3DNow ); // 3DNow! supported. if (J and (1 shl 30)) <> 0 then Include( Result, cpu3DNow_Plus );// 3DNow!+ supported. end; end; if (I and (1 shl 25)) <> 0 then begin Include( Result, cpuSSE ); // SSE supported. if (I and (1 shl 26)) <> 0 then Include( Result, cpuSSE2 ); // SSE2 supported. end; cpu := Result; end; end.
program abc; uses crt,dos; const p = 1; m = 40; n = 40; type arr = array[1..p, 1..m, 1..n] of integer; {Zadannya korystuvats'koho typu "masyv"} vector=array [1..n*m] of integer; proc=procedure(var A:arr); vect=procedure(var C:vector); TTime=record Hours,Min,Sec,HSec:word; end; var A:arr; {Zminna typu masyv} C:vector; pr:proc; {Zminna protsedurnoho typu} vec:vect; T: integer; procedure BackSortArray(var a: arr); {Protsedura zapovnennya oberneno vporyadkovannoho masyvu} var i, j, k: word; {Zminni kordynat} l: word; {Zminna, za dopomohoyu yakoyi bude zapovnyuvatysya masyv} begin l := p * m * n; {Zminniy l prysvoyuyet'sya znachennya kil'kosti elementiv masyvu} for k := 1 to p do {Lichyl'nyky prokhodu po koordynatam masyvu} for i := 1 to m do for j := 1 to n do begin a[k, i, j] := l; {Prysvoyennya komirtsi masyvu znachennya l} dec(l); {Pry kozhnomu prokhodi lichyl'nyka, zminna l bude zmen'shuvatysya na 1} end; end; function ResTime(const STime,FTime:TTime):longint; begin ResTime:=360000*Longint(FTime.Hours)+ 6000*Longint(FTime.Min)+ 100*Longint(FTime.Sec)+ Longint(FTime.HSec)- 360000*Longint(STime.Hours)- 6000*Longint(STime.Min)- 100*Longint(STime.Sec)- Longint(STime.HSec); end; function Time(pr:proc):longint; var StartTime,FinishTime:TTime; begin with StartTime do GetTime(Hours,Min,Sec,HSec); pr(A); {Zapusk obranoyi protsedury sortuvannya} with FinishTime do GetTime(Hours,Min,Sec,HSec); Time:=ResTime(StartTime,FinishTime); end; procedure WORKAR1711(var a: arr);{Alhorytm "vstavka – obmin" z vykorystannyam dodatkovoho masyvu} var ii, k, j, i, B:integer; {ii: koordynata odnovymirnoho masyvu; k,i,j: koordynaty 3-vymirnoho masyvu; B-dodatkova komirka} Z:vector; {Dodatkovyy odnovymirnyy masyv} begin for k:=1 to p do {Lichyl'nyky prokhodu po koordynatam 3-vymirnoho masyvu} begin ii:=1; for i := 1 to m do for j := 1 to n do begin Z[ii] := a[k, i, j]; {Perepysuvannya elementiv dvovymirnoho masyvu do odnovymirnoho} inc(ii);{Pislya kozhnoho prokhodu lichyl'nyka, kordynata odnovymirnoho masyvu ii zbil'shuyet'sya na 1} end; for i:=2 to (n*m) do {Prokhid po odnovymirnomu masyvu} begin j:=i; while (j>1) and (Z[j]<Z[j-1]) do {Pochynayet'sya robota bezposeredn'o hibrydnoho alhorytmu "vstavka – obmin"} begin B:=Z[j]; {Zmina elementiv mistsyamy} Z[j]:=Z[j-1]; Z[j-1]:=B; j:=j-1; end; end; ii := 1; for i := 1 to m do {Lichyl'nyky prokhodu po koordynatam 2-vymirnoho masyvu} for j := 1 to n do begin a[k, i, j]:= Z[ii]; {Perepysuvannya elementiv odnovymirnoho masyvu do dvovymirnoho} inc(ii); {Pislya kozhnoho prokhodu lichyl'nyka, kordynata odnovymirnoho masyvu ii zbil'shuyet'sya na 1} end; end; end; begin write('Workaround 1:'); pr:=WORKAR1711; BackSortArray(A); T:=Time(pr); writeln(T); end;
(* Category: SWAG Title: DIRECTORY HANDLING ROUTINES Original name: 0033.PAS Description: Recursive Directory Author: DAVE JARVIS Date: 08-24-94 13:31 *) { On 05-25-94 ROBERT HARRISON wrote to ALL... RH> I'm trying to obtain the source for searching for files in all RH> directories and drives. Anyone happened to have the information RH> they would like to share with me? Thanks. ----------------- 8< ------------- } USES DOS, Crt; PROCEDURE Search; VAR Err : INTEGER; CurrDir : STRING; DirInfo : SearchRec; Begin FindFirst( '*.*', AnyFile, DirInfo ); Err := 0; WHILE Err = 0 DO Begin { If the directory wasn't . or .., then find all files in it ... } IF ((DirInfo.Attr AND Directory) = Directory) AND (Pos( '.', DirInfo.Name ) = 0) THEN Begin {$I-} ChDir( DirInfo.Name ); {$I+} { Find all files in subdirectory that was found } Search; DirInfo.Attr := 0; End ELSE Begin GetDir( 0, CurrDir ); WriteLn( DirInfo.Name ); FindNext( DirInfo ); Err := DosError; End; End; {$I-} ChDir( '..' ); {$I+} IF IOResult <> 0 THEN { Do Nothing...probably root directory... }; End; VAR CurDir : STRING; Begin ClrScr; GetDir( 0, CurDir ); { ChDir( 'C:\' ); } Search; ChDir( CurDir ); End.
unit DPM.IDE.ProjectController; interface uses System.Classes, VSoft.CancellationToken, DPM.IDE.Logger, DPM.Core.Package.Interfaces, DPM.IDE.ProjectTreeManager, DPM.IDE.EditorViewManager, DPM.Core.Package.Installer.Interfaces; type TProjectMode = (pmNone, pmSingle, pmGroup); IDPMIDEProjectController = interface ['{860448A2-1015-44A7-B051-0D29692B9986}'] //IDENotifier procedure ProjectOpening(const fileName : string); //does restore! procedure ProjectClosed(const fileName : string); procedure ProjectGroupClosed; //StorageNotifier procedure ProjectCreating(const fileName : string); procedure ProjectLoaded(const fileName : string); procedure ProjectClosing(const fileName : string); procedure ProjectSaving(const fileName : string); procedure BeginLoading(const mode : TProjectMode); procedure EndLoading(const mode : TProjectMode); end; // The Project controller is used to receive notifications from the IDE and funnel // them to the various parts of the IDE integration - views, project tree etc. TDPMIDEProjectController = class(TInterfacedObject, IDPMIDEProjectController) private FLogger : IDPMIDELogger; FEditorViewManager : IDPMEditorViewManager; FProjectTreeManager : IDPMProjectTreeManager; FProjectMode : TProjectMode; FPackageInstaller : IPackageInstaller; FInstallerContext : IPackageInstallerContext; FCancellationTokenSource : ICancellationTokenSource; FLastResult : boolean; protected //from IDENotifier procedure ProjectOpening(const fileName : string); procedure ProjectClosed(const fileName : string); procedure ProjectGroupClosed; procedure BeginLoading(const mode : TProjectMode); procedure EndLoading(const mode : TProjectMode); //from StorageNotifier procedure ProjectLoaded(const fileName : string); procedure ProjectClosing(const fileName : string); procedure ProjectCreating(const fileName : string); procedure ProjectSaving(const fileName : string); procedure RestoreProject(const fileName : string); public constructor Create(const logger : IDPMIDELogger; const packageInstaller : IPackageInstaller; const editorViewManager : IDPMEditorViewManager; const projectTreeManager : IDPMProjectTreeManager; const context : IPackageInstallerContext); destructor Destroy;override; end; implementation uses System.TypInfo, DPM.Core.Options.Common, DPM.Core.Options.Restore, DPM.IDE.Types; { TDPMIDEProjectController } procedure TDPMIDEProjectController.BeginLoading(const mode: TProjectMode); begin FProjectMode := mode; FLogger.Debug('ProjectController.BeginLoading : ' + GetEnumName(TypeInfo(TProjectMode),Ord(mode))); FCancellationTokenSource.Reset; FLastResult := true; FInstallerContext.Clear; end; constructor TDPMIDEProjectController.Create(const logger : IDPMIDELogger; const packageInstaller : IPackageInstaller; const editorViewManager : IDPMEditorViewManager; const projectTreeManager : IDPMProjectTreeManager; const context : IPackageInstallerContext); begin inherited Create; FProjectMode := TProjectMode.pmNone; FLogger := logger; FPackageInstaller := packageInstaller; FEditorViewManager := editorViewManager; FProjectTreeManager := projectTreeManager; FCancellationTokenSource := TCancellationTokenSourceFactory.Create; FInstallerContext := context; end; destructor TDPMIDEProjectController.Destroy; begin FEditorViewManager := nil; FPackageInstaller := nil; FProjectTreeManager := nil; inherited; end; procedure TDPMIDEProjectController.EndLoading(const mode: TProjectMode); begin FLogger.Debug('ProjectController.EndLoading : ' + GetEnumName(TypeInfo(TProjectMode),Ord(mode))); FProjectMode := pmNone; FLogger.EndRestore(FLastResult); FProjectTreeManager.EndLoading; end; procedure TDPMIDEProjectController.ProjectClosed(const fileName: string); begin FLogger.Debug('ProjectController.ProjectClosed : ' + fileName); FProjectTreeManager.ProjectClosed(FileName); FEditorViewManager.ProjectClosed(FileName); FInstallerContext.RemoveProject(fileName); end; procedure TDPMIDEProjectController.ProjectOpening(const fileName: string); begin FLogger.Debug('ProjectController.ProjectOpening : ' + fileName); RestoreProject(fileName); end; procedure TDPMIDEProjectController.ProjectClosing(const fileName: string); begin FLogger.Debug('ProjectController.ProjectClosing : ' + fileName); // using FileClosing as it fires earlier end; procedure TDPMIDEProjectController.ProjectCreating(const fileName: string); begin FLogger.Debug('ProjectController.ProjectCreating : ' + fileName); ProjectLoaded(fileName); end; procedure TDPMIDEProjectController.ProjectGroupClosed; begin FProjectTreeManager.ProjectGroupClosed; FEditorViewManager.ProjectGroupClosed; FInstallerContext.Clear; end; procedure TDPMIDEProjectController.ProjectLoaded(const fileName: string); begin FLogger.Debug('ProjectController.ProjectLoaded : ' + fileName); //queue the project for loading in the tree. FProjectTreeManager.ProjectLoaded(fileName); //this will be pmNone when reloading after external edit if FProjectMode = pmNone then begin FProjectTreeManager.EndLoading; //force tree update FEditorViewManager.ProjectLoaded(fileName); end; end; procedure TDPMIDEProjectController.ProjectSaving(const fileName: string); begin FLogger.Debug('ProjectController.ProjectSaving : ' + fileName); // not sure we need to do anything. end; procedure TDPMIDEProjectController.RestoreProject(const fileName: string); var options : TRestoreOptions; begin FLogger.Debug('ProjectController.RestoreProject : ' + fileName); if FCancellationTokenSource.Token.IsCancelled then exit; options := TRestoreOptions.Create; options.ApplyCommon(TCommonOptions.Default); options.ProjectPath := fileName; options.Validate(FLogger); options.CompilerVersion := IDECompilerVersion; FLogger.StartRestore(FCancellationTokenSource); FLastResult := FLastResult and FPackageInstaller.Restore(FCancellationTokenSource.Token, options, FInstallerContext); end; end.
unit Processor; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type TProcessor = class private FArchitecture: Integer; FModel: String; public constructor Create(); property Architecture: Integer read FArchitecture; property Model: String read FModel; end; implementation {$IFDEF WINDOWS} uses uWin32_Processor; {$ENDIF} constructor TProcessor.Create(); {$IFDEF LINUX} var CpuInfo: TStringList; Field, Line: String; LineNumber: Integer; begin FArchitecture := 0; FModel := ''; CpuInfo := TStringList.Create(); CpuInfo.LoadFromFile('/proc/cpuinfo'); LineNumber := CpuInfo.Count; for LineNumber := 0 to (CpuInfo.Count - 1) do begin Line := CpuInfo.Strings[LineNumber]; if (Pos(':', Line) > 0) then Field := Trim(Copy(Line, 1, Pos(':', Line) - 1)); if (Field = 'model name') then FModel := Trim(Copy(Line, Pos(':', Line) + 1, Length(Line) - Pos(':', Line))); if (Field = 'flags') then begin if ((Pos(' lm ', Line) > 0) and (FArchitecture < 64)) then FArchitecture := 64; if ((Pos(' tm ', Line) > 0) and (FArchitecture < 32)) then FArchitecture := 32; if ((Pos(' rm ', Line) > 0) and (FArchitecture < 16)) then FArchitecture := 16; end; if ( (FArchitecture > 0) and (Length(FModel) > 0) and (Field <> 'flags') ) then break; end; end; {$ENDIF} {$IFDEF WINDOWS} var Win32_Processor: TWin32_Processor; begin Win32_Processor:= TWin32_Processor.Create; FArchitecture := Win32_Processor.DataWidth; FModel := Win32_Processor.Name; end; {$ENDIF} end.
var str1 : string; str2 : string; begin str1 := 'Hello'; str2 := 'world'; write(str1, ''#20'', str2, ''#33'', ''#10''); end.
unit IRCUtils; { -ooooooooooooooooooooooooooooooooooooooooooooooooooooooooo- -o Título: IRCUtils o- -o Descrição: Biblioteca para interpretação do protocolo o- -o IRC o- -o Autor: Waack3(Davi Ramos) o- -o Última modificação: 07/03/02 22:53 o- -o As descrições individuais estão abaixo o- -ooooooooooooooooooooooooooooooooooooooooooooooooooooooooo- } interface uses StrUtils, SysUtils, Classes, Graphics; type {Conjunto dos tipos de menssagens} TIRCMsg = (imPrivMsg, imChaMsg, imServMsg, imDesconhecido, imMudNick, imDccChat, imDccSend, imCtcpPing, imCtcpTime, imCtcpVersion); const CI_BRANCO = $00FFFFFF; { 0} CI_PRETO = $00000000; { 1} CI_AZESCURO = $007F0000; { 2} CI_VDESCURO = $00009300; { 3} CI_VERMELHO = clRed; { 4} CI_MARROM = $0000007F; { 5} CI_ROXO = $009C009C; { 6} CI_LARANJA = $00007FFC; { 7} CI_AMARELO = clYellow; { 8} CI_VERDE = $0000FC00; { 9} CI_CIANO = $00939300; {10} CI_AZCLARO = clAqua; {11} CI_AZUL = $00FC0000; {12} CI_ROZA = clFuchsia; {13} CI_CINZA = $007F7F7F; {14} CI_CINZACLARO = $00D2D2D2; {15} {Analisa a menssagem IRC e retorna seu tipo e parâmetros} function AnalisarIRC(Entrada: string; var Saida: TStringList): TIRCMsg; implementation function AnalisarIRC(Entrada: string; var Saida: TStringList): TIRCMsg; var Nick, Ip, Texto, Host, Id, Comando, MenssagemUsr, Parametros: string; PosI: integer; ParamDccCtcp: TSplitArray; begin {Incicia variáveis} result:=imDesconhecido; Saida:=TStringList.Create; SetLength(ParamDccCtcp, 0); {Ao apresentar o ponto-vírgula indica que é uma menssagem vinda do servidor} if (Entrada[1] = ':') then begin {Presença de exclamação após o nick indica uma menssagem vinda de um usuário} if ((Pos('!', Entrada) < Pos(' ',Entrada)) and (Pos('!',Entrada) > 1)) then begin {Msg de usuário} Nick:=PegarStr(Entrada,2,Pos('!',Entrada) - 1); Ip:=PegarStr(Entrada,Pos('!',Entrada) + 1,Pos(' ',Entrada) - 1); Texto:=Estilete(Entrada,Pos(' ',Entrada) + 1,deDireita); Saida.Add(Nick); {Nick de origem} Saida.Add(Ip); {Ip de origem} {Separa Texto entre Comando, Parâmetros e a mennsagem enviada pelo usuário} Comando:=PegarStr(Texto, 1, Pos(' ', Texto) - 1); Parametros:=Estilete(Texto, Pos(' ', Texto) + 1, deDireita); {Tudo que vem após o comando} if (Comando = 'PRIVMSG') then begin MenssagemUsr:=Estilete(Parametros, Pos(':', Parametros) + 1, deDireita); {Menssagem para canal ou para PVT} if ((Parametros[1] = '#') or (Parametros[1] = '&')) then result:=imChaMsg else {Verifira se a menssagem é um requerimento DCC ou CTCP} if ((MenssagemUsr[1] = #1) and (MenssagemUsr[Length(MenssagemUsr)] = #1)) then {É um requerimento DCC ou CTCP. Será verificado agora seu tipo} begin MenssagemUsr:=PegarStr(MenssagemUsr, 2, Length(MenssagemUsr) - 1); {Retira caracteres #1} ParamDccCtcp:=Split(MenssagemUsr, #32); {Divide os parâmetros do DCC} if (ParamDccCtcp[0] = 'DCC') then begin {Requerimento DCC} if (ParamDccCtcp[1] = 'CHAT') then begin {DCC Subtipo CHAT} Saida.Add(ParamDccCtcp[2]); Saida.Add(ParamDccCtcp[3]); Saida.Add(ParamDccCtcp[4]); result:=imDccChat; end else if (ParamDccCtcp[1] = 'SEND') then begin {DCC Subtipo SEND} Saida.Add(ParamDccCtcp[2]); Saida.Add(ParamDccCtcp[3]); Saida.Add(ParamDccCtcp[4]); Saida.Add(ParamDccCtcp[5]); result:=imDccSend; end else begin result:=imDesconhecido; end; end else begin {É CTCP. Verifica agora se é Ping, Time ou Version} if (ParamDccCtcp[0] = 'PING') then {Envia pacotes PING} begin Saida.Add(ParamDccCtcp[1]); result:=imCtcpPing; end else if (ParamDccCtcp[0] = 'TIME') then {Pede hora local} result:=imCtcpTime else if (ParamDccCtcp[0] = 'VERSION') then {Pede string de versão} result:=imCtcpVersion else result:=imDesconhecido; {Tipo de menssagem não compreendido} end; end else {Se não é DCC ou CTCP então é uma menssagem normal} result:=imPrivMsg; {Gera saída, para caso de ser uma menssagem símples} if ((result = imChaMsg) or (result = imPrivMsg)) then begin Saida.Add(PegarStr(Parametros, 1, Pos(' ', Parametros))); {Nick/Canal de destino} Saida.Add(MenssagemUsr); {Menssagem recebida} end; end else if (Comando = 'NICK') then begin result:=imMudNick; {Algum cliente mudou de nick} {Gera saida} Saida.Add(Estilete(Parametros, Pos(':', Parametros) + 1, deDireita)); {Novo nick} end; end else begin {Msg de eventos do servidor} PosI:=Pos(' ',Entrada); Host:=PegarStr(Entrada,2,PosI - 1); Id:=PegarStr(Entrada,PosI + 1,Posicao(' ', Entrada, PosI + 1) - 1); PosI:=Posicao(' ', Entrada, PosI + 1); Texto:=Estilete(Entrada, PosI + 1, deDireita); Saida.Add(Host); {Host que originou menssagem} Saida.Add(Id); {ID(Número) da menssagem, que indica seu gênero} Saida.Add(Texto); {Menssagem enviada} result:=imServMsg; end; end; end; end.
{***************************************************************************} { } { DUnitX } { } { Copyright (C) 2013 Vincent Parrett } { } { vincent@finalbuilder.com } { http://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DUnitX.TestFixture; interface uses DUnitX.TestFramework, DUnitX.InternalInterfaces, DUnitX.WeakReference, DUnitX.Generics, Rtti; {$I DUnitX.inc} type TDUnitXTestFixture = class(TWeakReferencedObject, ITestFixture, ITestFixtureInfo) class var FRttiContext : TRttiContext; private FTestClass : TClass; FName : string; FNameSpace : string; FDescription : string; FEnabled : boolean; FTests : IList<ITest>; FTestInfos : IList<ITestInfo>; FSetupMethod : TTestMethod; FSetupFixtureMethod : TTestMethod; FTearDownMethod : TTestMethod; FTearDownFixtureMethod : TTestMethod; FFixtureInstance : TObject; FTestInOwnThread : boolean; FSetupFixtureMethodName: string; FSetupMethodName: string; FTearDownMethodName: string; FTearDownFixtureMethodName: string; FChildren : ITestFixtureList; protected //uses RTTI to buid the fixture & tests procedure GenerateFixtureFromClass; function GetEnabled: Boolean; procedure SetEnabled(const value: Boolean); function GetName: string; function GetNameSpace : string; function GetFullName : string; function GetDescription : string; function GetTests: IEnumerable<ITest>; function ITestFixtureInfo.GetTests = ITestFixtureInfo_GetTests; function ITestFixtureInfo_GetTests : IList<ITestInfo>; function GetTestClass : TClass; function GetSetupMethod : TTestMethod; function GetSetupFixtureMethod : TTestMethod; function GetTearDownMethod : TTestMethod; function GetTearDownFixtureMethod : TTestMethod; function GetTestInOwnThread : boolean; function GetSetupFixtureMethodName: string; function GetSetupMethodName: string; function GetTearDownMethodName: string; function GetTearDownFixtureMethodName: string; function GetTestCount : cardinal; function GetActiveTestCount : cardinal; function GetChildren: ITestFixtureList; function GetHasChildren : boolean; public constructor Create(const AName : string; const AClass : TClass); destructor Destroy;override; class constructor Create; end; implementation uses TypInfo, {$IFDEF MSWINDOWS} {$if CompilerVersion < 23 } Windows, {$else} WinAPI.Windows, // Delphi XE2 (CompilerVersion 23) added scopes in front of unit names {$ifend} {$ENDIF} SysUtils, DUnitX.Test, DUnitX.Utils; { TDUnitXTestFixture } constructor TDUnitXTestFixture.Create(const AName : string; const AClass : TClass); var i : integer; begin FTestClass := AClass; FTests := TDUnitXList<ITest>.Create; i := LastDelimiter('.',AName); if i <> 0 then begin FNameSpace := Copy(AName,1,i -1); FName := Copy(AName,i+1,Length(AName)); end else begin FName := AName; FNameSpace := AName; end; FEnabled := True; //TODO: Constructor doing "work" makes this harder to test and handle errors if the class isn't of the correct structure GenerateFixtureFromClass; end; destructor TDUnitXTestFixture.Destroy; begin if FFixtureInstance <> nil then FFixtureInstance.Free; FTests := nil; inherited; end; {$IFDEF MSWINDOWS} procedure PatchCodeDWORD(Code: PDWORD; Value: DWORD); // Self-modifying code - change one DWORD in the code segment var RestoreProtection, Ignore: DWORD; begin if VirtualProtect(Code, SizeOf(Code^), PAGE_EXECUTE_READWRITE, RestoreProtection) then begin Code^ := Value; VirtualProtect(Code, SizeOf(Code^), RestoreProtection, Ignore); FlushInstructionCache(GetCurrentProcess, Code, SizeOf(Code^)); end; end; const vmtRunnerIndex = System.vmtAutoTable; {$ENDIF} procedure TDUnitXTestFixture.GenerateFixtureFromClass; var rType : TRttiType; methods : TArray<TRttiMethod>; method : TRttiMethod; attributes : TArray<TCustomAttribute>; attribute : TCustomAttribute; meth : TMethod; newTest : ITest; fixtureAttrib : TestFixtureAttribute; testCases : TArray<TestCaseAttribute>; testCaseAttrib : TestCaseAttribute; testEnabled : boolean; begin rType := FRttiContext.GetType(FTestClass); System.Assert(rType <> nil); FFixtureInstance := FTestClass.Create; //If the fixture class was decorated with [TestFixture] then use it for the description. fixtureAttrib := nil; if rType.TryGetAttributeOfType<TestFixtureAttribute>(fixtureAttrib) then FDescription := fixtureAttrib.Description; methods := rType.GetMethods; for method in methods do begin meth.Code := method.CodeAddress; meth.Data := FFixtureInstance; attributes := method.GetAttributes; if Length(attributes) > 0 then begin for attribute in attributes do begin //first check if the method is our setup or teardown. if attribute.ClassType = SetupAttribute then begin FSetupMethod := TTestMethod(meth); FSetupMethodName := method.Name; end else if attribute.ClassType = SetupFixtureAttribute then begin FSetupFixtureMethod := TTestMethod(meth); FSetupFixtureMethodName := method.Name; end else if attribute.ClassType = TearDownAttribute then begin FTearDownMethod := TTestMethod(meth); FTearDownMethodName := method.Name; end else if attribute.ClassType = TearDownFixtureAttribute then begin FTearDownFixtureMethod := TTestMethod(meth); FTearDownFixtureMethodName := method.Name; end else if attribute.ClassType = TestInOwnThreadAttribute then FTestInOwnThread := true //TODO: Should add tests to the list even though they aren't enabled. else if ((attribute.ClassType = TestAttribute)) or ((attribute.ClassType <> TestAttribute) and (method.Visibility = TMemberVisibility.mvPublished) and (not method.HasAttributeOfType<TestAttribute>)) then begin if attribute.ClassType = TestAttribute then begin testEnabled := TestAttribute(attribute).Enabled; //find out if the test fixture has test cases. testCases := method.GetAttributesOfType<TestCaseAttribute>; if Length(testCases) > 0 then begin for testCaseAttrib in testCases do begin newTest := TDUnitXTestCase.Create(FFixtureInstance, Self, testCaseAttrib.Name, method.Name, method, testEnabled, testCaseAttrib.Values); newTest.Enabled := testEnabled; FTests.Add(newTest); end; end else begin newTest := TDUnitXTest.Create(Self, method.Name, TTestMethod(meth),testEnabled); FTests.Add(newTest); end; end else begin newTest := TDUnitXTest.Create(Self, method.Name, TTestMethod(meth),True); FTests.Add(newTest); end; end; end; end else if method.Visibility = TMemberVisibility.mvPublished then begin newTest := TDUnitXTest.Create(Self,method.Name,TTestMethod(meth),true); FTests.Add(newTest); end; end; end; function TDUnitXTestFixture.GetActiveTestCount: cardinal; begin //TODO: Return the active count, currently fudged to be the count. Result := GetTestCount; end; function TDUnitXTestFixture.GetChildren: ITestFixtureList; begin if FChildren = nil then FChildren := TTestFixtureList.Create; result := FChildren; end; function TDUnitXTestFixture.GetDescription: string; begin result := FDescription; end; function TDUnitXTestFixture.GetEnabled: Boolean; begin result := FEnabled; end; function TDUnitXTestFixture.GetFullName: string; begin if FName <> FNameSpace then result := FNameSpace + '.' + FName else Result := FName; end; function TDUnitXTestFixture.GetHasChildren: boolean; begin result := (FChildren <> nil) and (FChildren.Count > 0); end; function TDUnitXTestFixture.GetName: string; begin result := FName; end; function TDUnitXTestFixture.GetNameSpace: string; begin result := FNameSpace; end; function TDUnitXTestFixture.GetSetupFixtureMethod: TTestMethod; begin result := FSetupFixtureMethod; end; function TDUnitXTestFixture.GetSetupFixtureMethodName: string; begin result := FSetupFixtureMethodName; end; function TDUnitXTestFixture.GetSetupMethod: TTestMethod; begin result := FSetupMethod; end; function TDUnitXTestFixture.GetSetupMethodName: string; begin result := FSetupMethodName; end; function TDUnitXTestFixture.GetTearDownFixtureMethod: TTestMethod; begin result := FTearDownFixtureMethod; end; function TDUnitXTestFixture.GetTearDownFixtureMethodName: string; begin result := FTearDownFixtureMethodName; end; function TDUnitXTestFixture.GetTearDownMethod: TTestMethod; begin result := FTearDownMethod; end; function TDUnitXTestFixture.GetTearDownMethodName: string; begin result := FTearDownMethodName; end; function TDUnitXTestFixture.GetTestClass: TClass; begin result := FTestClass; end; function TDUnitXTestFixture.GetTestCount: cardinal; begin Result := FTests.Count; end; function TDUnitXTestFixture.GetTestInOwnThread: boolean; begin result := FTestInOwnThread; end; function TDUnitXTestFixture.GetTests: IEnumerable<ITest>; begin result := FTests; end; function TDUnitXTestFixture.ITestFixtureInfo_GetTests: IList<ITestInfo>; var test : ITest; begin //TODO: Need to test that this isn't accessed between updates to FTests. if FTestInfos = nil then begin FTestInfos := TDUnitXList<ITestInfo>.Create; for test in FTests do FTestInfos.Add(test as ITestInfo); end; result := FTestInfos; end; procedure TDUnitXTestFixture.SetEnabled(const value: Boolean); begin FEnabled := value; end; class constructor TDUnitXTestFixture.Create; begin FRttiContext := TRttiContext.Create; end; end.
unit Common.Barcode.IBarcode; interface uses FMX.Objects; type IBarcode = interface ['{866573A2-D281-48D3-9799-B7D218E6C6AC}'] function GetRawData: string; procedure SetRawData(const Value: string); function GetAddonData: string; procedure SetAddonData(const Value: string); function GetSVG: string; property RawData: string read GetRawData write SetRawData; property AddonData: string read GetAddonData write SetAddonData; property SVG: string read GetSVG; end; implementation end.
unit FileData; interface uses uColorTheme, SysUtils, Classes, uUtils, uArrayList, uScene, uPoint, uLine; { Used to store optional settings } type TSettings = class(TObject) theme: ColorTheme; builtinThemes, userThemes: ArrayList; dropSettings, showBanner: boolean; exitAction: String[255]; constructor Create(); end; { Reading/Writeing } procedure dropSettings(path: String; obj: TSettings); function restoreSettings(path: String): TSettings; procedure saveProject(path: String; theScene: Scene); function restoreProject(path: String): Scene; implementation // Settings constructor TSettings.Create(); begin dropSettings := false; showBanner := true; exitAction := 'ask'; builtinThemes := ArrayList.Create(); userThemes := ArrayList.Create(); builtinThemes.add(CT_DEFAULT_THEME); theme := builtinThemes.get(0) as ColorTheme; end; procedure dropSettings(path: String; obj: TSettings); var fs: TFileStream; i, n, k: integer; isBuiltin: boolean; r: ColorThemeRecord; begin newFile(path); fs := TFileStream.Create(path, fmOpenWrite); fs.Write(obj.exitAction, 255 * sizeOf(Char)); fs.Write(obj.dropSettings, sizeOf(Boolean)); fs.Write(obj.showBanner, sizeOf(Boolean)); n := obj.userThemes.size(); fs.Write(n, sizeOf(integer)); for i := 0 to n - 1 do begin r := ctToRecord(obj.userThemes.get(i) as ColorTheme); fs.Write(r, sizeOf(ColorThemeRecord)); end; // find current k := 0; isBuiltin := false; for i := 0 to obj.builtinThemes.size() - 1 do if obj.theme = obj.builtinThemes.get(i) then begin k := i; isBuiltin := true; break; end; if not isBuiltin then for i := 0 to obj.userThemes.size() - 1 do if obj.theme = obj.userThemes.get(i) then begin k := i; break; end; fs.Write(isBuiltin, sizeOf(boolean)); fs.Write(k, sizeOf(integer)); fs.Free; end; function restoreSettings(path: String): TSettings; var obj: TSettings; fs: TFileStream; i, n, k: integer; isBuiltin: boolean; r: ColorThemeRecord; begin restoreSettings := nil; if FileExists(path) then begin obj := TSettings.Create(); fs := TFileStream.Create(path, fmOpenRead); fs.Read(obj.exitAction, 255 * sizeOf(Char)); fs.Read(obj.dropSettings, sizeOf(Boolean)); fs.Read(obj.showBanner, sizeOf(Boolean)); fs.Read(n, sizeOf(integer)); for i := 0 to n - 1 do begin fs.Read(r, sizeOf(ColorThemeRecord)); obj.userThemes.add(ctToClass(r)); end; fs.Read(isBuiltin, sizeof(boolean)); fs.Read(k, sizeOf(integer)); if isBuiltin then obj.theme := obj.builtinThemes.get(k) as ColorTheme else obj.theme := obj.userThemes.get(k) as ColorTheme; fs.Free; restoreSettings := obj; end; end; procedure saveProject(path: String; theScene: Scene); var sr: SceneRecord; fs: TFileStream; i, j, a, b, c: integer; begin newFile(path); fs := TFileStream.Create(path, fmOpenWrite); sr := snToRecord(theScene); fs.Write(sr.currentLayer, sizeOf(integer)); a := Length(sr.layers); fs.Write(a, sizeOf(integer)); for i := 0 to a - 1 do begin fs.Write(sr.layers[i].name, 255 * sizeOf(char)); fs.Write(sr.layers[i].currentPoint, sizeOf(integer)); fs.Write(sr.layers[i].currentLine, sizeOf(integer)); b := length(sr.layers[i].points); c := length(sr.layers[i].lines); fs.Write(b, sizeOf(integer)); fs.Write(c, sizeOf(integer)); for j := 0 to b - 1 do fs.Write(sr.layers[i].points[j], sizeOf(PointRecord)); for j := 0 to c - 1 do fs.Write(sr.layers[i].lines[j], sizeOf(LineRecord)); end; fs.Free; end; function restoreProject(path: String): Scene; var sr: SceneRecord; fs: TFileStream; i, j, a, b, c: integer; begin restoreProject := nil; if FileExists(path) then begin fs := TFileStream.Create(path, fmOpenRead); fs.Read(sr.currentLayer, sizeOf(integer)); fs.Read(a, sizeOf(integer)); Setlength(sr.layers, a); for i := 0 to a - 1 do begin fs.Read(sr.layers[i].name, 255 * sizeOf(char)); fs.Read(sr.layers[i].currentPoint, sizeOf(integer)); fs.Read(sr.layers[i].currentLine, sizeOf(integer)); fs.Read(b, sizeOf(integer)); fs.Read(c, sizeOf(integer)); Setlength(sr.layers[i].points, b); Setlength(sr.layers[i].lines, c); for j := 0 to b - 1 do fs.Read(sr.layers[i].points[j], sizeOf(PointRecord)); for j := 0 to c - 1 do fs.Read(sr.layers[i].lines[j], sizeOf(LineRecord)); end; restoreProject := snToClass(sr); fs.Free; end; end; end.
namespace com.example.android.lunarlander; {* * Copyright (C) 2007 The Android Open Source Project * * 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. *} interface uses android.app, android.os, android.util, android.view, android.widget; type /// <summary> /// This is a simple LunarLander activity that houses a single LunarView. It /// demonstrates... /// /// - animating by calling invalidate() from draw() /// - loading and drawing resources /// - handling onPause() in an animation /// </summary> LunarLander = public class(Activity) private const MENU_EASY = 1; const MENU_HARD = 2; const MENU_MEDIUM = 3; const MENU_PAUSE = 4; const MENU_RESUME = 5; const MENU_START = 6; const MENU_STOP = 7; // A handle to the thread that's actually running the animation. var mLunarThread: LunarThread; // A handle to the View in which the game is running. var mLunarView: LunarView; public method onCreateOptionsMenu(mnu: Menu): Boolean; override; method onOptionsItemSelected(item: MenuItem): Boolean; override; protected method onCreate(savedInstanceState: Bundle); override; method onPause; override; method onSaveInstanceState(outState: Bundle); override; end; implementation /// <summary> /// Invoked when the Activity is created. /// </summary> /// <param name="savedInstanceState">a Bundle containing state saved from a previous execution, or nil if this is a new execution</param> method LunarLander.onCreate(savedInstanceState: Bundle); begin inherited; // tell system to use the layout defined in our XML file ContentView := R.layout.lunar_layout; // get handles to the LunarView from XML, and its LunarThread mLunarView := LunarView(findViewById(R.id.lunar)); mLunarThread := mLunarView.getThread; // give the LunarView a handle to the TextView used for messages mLunarView.setTextView(TextView(findViewById(R.id.text))); if savedInstanceState = nil then begin // we were just launched: set up a new game mLunarThread.setState(LunarThread.STATE_READY); Log.w(&Class.Name, 'SIS is null') end else begin // we are being restored: resume a previous game mLunarThread.restoreState(savedInstanceState); Log.w(&Class.Name, 'SIS is nonnull') end end; /// <summary> /// Invoked when the Activity loses user focus. /// </summary> method LunarLander.onPause; begin inherited; Log.w(&Class.Name, 'onPause'); mLunarThread.pause end; /// <summary> /// Notification that something is about to happen, to give the Activity a /// chance to save state. /// </summary> /// <param name="outState">a Bundle into which this Activity should save its state</param> method LunarLander.onSaveInstanceState(outState: Bundle); begin // just have the View's thread save its state into our Bundle inherited; mLunarThread.saveState(outState); Log.w(&Class.Name, 'SIS called') end; /// <summary> /// Invoked during init to give the Activity a chance to set up its Menu. /// </summary> /// <param name="menu">the Menu to which entries may be added</param> /// <returns>true</returns> method LunarLander.onCreateOptionsMenu(mnu: Menu): Boolean; begin inherited; mnu.&add(0, MENU_START, 0, R.string.menu_start); mnu.&add(0, MENU_STOP, 0, R.string.menu_stop); mnu.&add(0, MENU_PAUSE, 0, R.string.menu_pause); mnu.&add(0, MENU_RESUME, 0, R.string.menu_resume); mnu.&add(0, MENU_EASY, 0, R.string.menu_easy); mnu.&add(0, MENU_MEDIUM, 0, R.string.menu_medium); mnu.&add(0, MENU_HARD, 0, R.string.menu_hard); exit true end; /// <summary> /// Invoked when the user selects an item from the Menu. /// </summary> /// <param name="item">the Menu entry which was selected</param> /// <returns>true if the Menu item was legit (and we consumed it), false otherwise</returns> method LunarLander.onOptionsItemSelected(item: MenuItem): Boolean; begin case item.ItemId of MENU_START: mLunarThread.doStart; MENU_STOP: mLunarThread.setState(LunarThread.STATE_LOSE, Text[R.string.message_stopped]); MENU_PAUSE: mLunarThread.pause; MENU_RESUME: mLunarThread.unpause; MENU_EASY: mLunarThread.setDifficulty(LunarThread.DIFFICULTY_EASY); MENU_MEDIUM: mLunarThread.setDifficulty(LunarThread.DIFFICULTY_MEDIUM); MENU_HARD: mLunarThread.setDifficulty(LunarThread.DIFFICULTY_HARD); else exit false; end; exit true end; end.
unit fltReeUrzbUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxControls, cxContainer, cxEdit, cxLabel, cxLookAndFeelPainters, ActnList, StdCtrls, cxButtons, cxCheckBox, cxCurrencyEdit, cxGroupBox; type TfltReeUrzb = class(TForm) OkButton: TcxButton; ActionList1: TActionList; Action1: TAction; DelButton: TcxButton; RollButton: TcxButton; cxGroupBox1: TcxGroupBox; cxCheckDateRee: TcxCheckBox; cxDateEdit1: TcxDateEdit; cxDateEdit2: TcxDateEdit; cxCheckSumRee: TcxCheckBox; cxCurrencyEditSumRee1: TcxCurrencyEdit; cxCurrencyEditSumRee2: TcxCurrencyEdit; cxCheckRegNum: TcxCheckBox; cxTextEditNumRee: TcxTextEdit; cxCheckNumDog: TcxCheckBox; cxTextEditNumDog: TcxTextEdit; cxCheckReeNumDog: TcxCheckBox; cxTextEditDogReeNum: TcxTextEdit; cxCheckDogSum: TcxCheckBox; cxTextCurrencyDogSum1: TcxCurrencyEdit; cxTextCurrencyDogSum2: TcxCurrencyEdit; act1: TAction; procedure fltExecute(Sender: TObject); procedure OkButtonClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure cxCheckSumReeClick(Sender: TObject); procedure cxCheckDateReeClick(Sender: TObject); procedure cxCheckRegNumClick(Sender: TObject); procedure cxCheckReeNumDogClick(Sender: TObject); procedure cxCheckNumDogClick(Sender: TObject); procedure cxCheckDogSumClick(Sender: TObject); procedure closeExecute(Sender: TObject); procedure DelButtonClick(Sender: TObject); procedure RollButtonClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var fltReeUrzb: TfltReeUrzb; implementation uses ReeUrzbUnit, DateUtils; {$R *.dfm} procedure TfltReeUrzb.fltExecute(Sender: TObject); begin OkButtonClick(Self); end; procedure TfltReeUrzb.OkButtonClick(Sender: TObject); begin ModalResult := mrOk; end; procedure TfltReeUrzb.FormCreate(Sender: TObject); begin //cxCheckDateRee.Checked := True; //cxDateEdit1.SetFocus; {cxCheckSumRee.Checked := False; cxCurrencyEditSumRee1.Enabled := cxCheckSumRee.Checked; cxCurrencyEditSumRee2.Enabled := cxCheckSumRee.Checked; cxCheckRegNum.Checked := False; cxTextEditNumRee.Enabled := cxCheckRegNum.Checked; cxCheckNumDog.Checked := False; cxTextEditNumDog.Enabled := cxCheckNumDog.Checked; cxCheckReeNumDog.Checked := False; cxTextEditDogReeNum.Enabled := cxCheckReeNumDog.Checked; cxCheckDogSum.Checked := False; cxTextCurrencyDogSum1.Enabled := cxCheckDogSum.Checked; cxTextCurrencyDogSum2.Enabled := cxCheckDogSum.Checked; } end; procedure TfltReeUrzb.cxCheckSumReeClick(Sender: TObject); begin cxCurrencyEditSumRee1.Enabled := cxCheckSumRee.Checked; cxCurrencyEditSumRee2.Enabled := cxCheckSumRee.Checked; if Visible then if cxCurrencyEditSumRee1.Enabled then cxCurrencyEditSumRee1.SetFocus; end; procedure TfltReeUrzb.cxCheckDateReeClick(Sender: TObject); begin cxDateEdit1.Enabled := cxCheckDateRee.Checked; cxDateEdit2.Enabled := cxCheckDateRee.Checked; if Visible then if cxDateEdit1.Enabled then cxDateEdit1.SetFocus; end; procedure TfltReeUrzb.cxCheckRegNumClick(Sender: TObject); begin cxTextEditNumRee.Enabled := cxCheckRegNum.Checked; if Visible then if cxTextEditNumRee.Enabled then cxTextEditNumRee.SetFocus; end; procedure TfltReeUrzb.cxCheckReeNumDogClick(Sender: TObject); begin cxTextEditDogReeNum.Enabled := cxCheckReeNumDog.Checked; if Visible then if cxTextEditDogReeNum.Enabled then cxTextEditDogReeNum.SetFocus; end; procedure TfltReeUrzb.cxCheckNumDogClick(Sender: TObject); begin cxTextEditNumDog.Enabled := cxCheckNumDog.Checked; if Visible then if cxTextEditNumDog.Enabled then cxTextEditNumDog.SetFocus; end; procedure TfltReeUrzb.cxCheckDogSumClick(Sender: TObject); begin cxTextCurrencyDogSum1.Enabled := cxCheckDogSum.Checked; cxTextCurrencyDogSum2.Enabled := cxCheckDogSum.Checked; if Visible then if cxTextCurrencyDogSum1.Enabled then cxTextCurrencyDogSum1.SetFocus; end; procedure TfltReeUrzb.closeExecute(Sender: TObject); begin DelButtonClick(Self); end; procedure TfltReeUrzb.DelButtonClick(Sender: TObject); begin cxCheckSumRee.Checked := False; cxCheckRegNum.Checked := False; cxCheckNumDog.Checked := False; cxCheckReeNumDog.Checked := False; cxCheckDogSum.Checked := False; ModalResult := mrOk; end; procedure TfltReeUrzb.RollButtonClick(Sender: TObject); begin Close; end; end.
unit uMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TMain = class(TForm) ParseBtn: TButton; LogMemo: TMemo; procedure ParseBtnClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Main: TMain; implementation {$R *.dfm} uses System.Types, System.IOUtils, JSONLexer, JSONParser; procedure TMain.ParseBtnClick(Sender: TObject); var StringStream: TStringStream; Lexer: TJSONLexer; Parser: TJSONParser; Files: TStringDynArray; I: Integer; Path: string; begin Files := System.IOUtils.TDirectory.GetFiles('../../examples'); LogMemo.Clear(); for I := 0 to Length(Files) - 1 do begin Path := Files[I]; LogMemo.Lines.Add(Format('parsing json file "%s"', [Path])); Sleep(100); StringStream := TStringStream.Create(); try StringStream.LoadFromFile(Path); Lexer := TJSONLexer.Create(StringStream); try Parser := TJSONParser.Create(Lexer); try Parser.Parse(); finally Parser.Free(); end; finally Lexer.Free(); end; finally StringStream.Free(); end; end; end; end.
unit Invoice.Model.Entity.User; interface uses System.SysUtils, Data.DB, Invoice.Model.Interfaces, Invoice.Controller.Interfaces, Invoice.Controller.Query.Factory; type TModelEntityUser = class(TInterfacedObject, iEntity) private FQuery: iQuery; // procedure PreparateFields; public constructor Create(Connection: iModelConnection); destructor Destroy; Override; class function New(Connection: iModelConnection): iEntity; function List: iEntity; function ListWhere(aSQL: String): iEntity; function DataSet: TDataSet; function OrderBy(aFieldName: String): iEntity; end; implementation { TModelEntityUser } constructor TModelEntityUser.Create(Connection: iModelConnection); begin FQuery := TControllerQueryFactory.New.Query(Connection) end; function TModelEntityUser.DataSet: TDataSet; begin Result := FQuery.DataSet; end; destructor TModelEntityUser.Destroy; begin if FQuery.DataSet.Active then FQuery.Close; // inherited; end; function TModelEntityUser.List: iEntity; begin Result := Self; // FQuery.SQL('SELECT * FROM tbUser WHERE idUser = 0'); // FQuery.Open; // PreparateFields; end; function TModelEntityUser.ListWhere(aSQL: String): iEntity; begin Result := Self; // FQuery.SQL('SELECT * FROM tbUser WHERE ' + aSQL); // FQuery.Open; // PreparateFields; end; class function TModelEntityUser.New(Connection: iModelConnection): iEntity; begin Result := Self.Create(Connection); end; function TModelEntityUser.OrderBy(aFieldName: String): iEntity; begin FQuery.Order(aFieldName); end; procedure TModelEntityUser.PreparateFields; begin if (FQuery.DataSet.Fields.Count > 0) then begin FQuery.DataSet.Fields.FieldByName('idUser').ProviderFlags := [pfInWhere,pfInKey]; FQuery.DataSet.Fields.FieldByName('idUser').ReadOnly := True; FQuery.DataSet.Fields.FieldByName('idUser').DisplayWidth := 20; // FQuery.DataSet.Fields.FieldByName('nameFirst').ProviderFlags := [pfInUpdate]; FQuery.DataSet.Fields.FieldByName('nameFirst').ReadOnly := False; FQuery.DataSet.Fields.FieldByName('nameFirst').DisplayWidth := 100; // FQuery.DataSet.Fields.FieldByName('nameLast').ProviderFlags := [pfInUpdate]; FQuery.DataSet.Fields.FieldByName('nameLast').ReadOnly := False; FQuery.DataSet.Fields.FieldByName('nameLast').DisplayWidth := 100; // FQuery.DataSet.Fields.FieldByName('nameUser').ProviderFlags := [pfInUpdate]; FQuery.DataSet.Fields.FieldByName('nameUser').ReadOnly := False; FQuery.DataSet.Fields.FieldByName('nameUser').DisplayWidth := 100; // FQuery.DataSet.Fields.FieldByName('passUser').ProviderFlags := [pfInUpdate]; FQuery.DataSet.Fields.FieldByName('passUser').ReadOnly := False; FQuery.DataSet.Fields.FieldByName('passUser').DisplayWidth := 100; // FQuery.DataSet.Fields.FieldByName('activeUser').ProviderFlags := [pfInUpdate]; FQuery.DataSet.Fields.FieldByName('activeUser').ReadOnly := False; FQuery.DataSet.Fields.FieldByName('activeUser').DisplayWidth := 100; end; end; end.
unit Interfaces.Controller.GUI; interface uses System.Generics.Collections, Classes, Sysutils, System.Types, FMX.Layouts; type TBird = class private FX: Double; FY: Double; FWidth: Integer; FHeigth: Integer; FAngle: Double; FFlap: Boolean; FLayout: TLayout; public function GetRect: TRect; property X: Double read FX write FX; property Y: Double read FY write FY; property Width: Integer read FWidth write FWidth; property Heigth: Integer read FHeigth write FHeigth; property Angle: Double read FAngle write FAngle; property Flap: Boolean read FFlap write FFlap; property Layout: TLayout read FLayout write FLayout; end; type TPipe = class private FX: Double; FY: Double; FWidth: Integer; FHeigth: Integer; FAngle: Double; FTag: Integer; FTagFloat: Double; FAdded: Boolean; FDelete: Boolean; FLayout: TLayout; public function GetRect: TRect; property X: Double read FX write FX; property Y: Double read FY write FY; property Width: Integer read FWidth write FWidth; property Heigth: Integer read FHeigth write FHeigth; property Angle: Double read FAngle write FAngle; property Tag: Integer read FTag write FTag; property TagFloat: Double read FTagFloat write FTagFloat; property Added: Boolean read FAdded write FAdded; property Delete: Boolean read FDelete write FDelete; property Layout: TLayout read FLayout write FLayout; end; TPipes = TObjectList<TPipe>; type IAppGUI = interface; IAppController = interface procedure RegisterGUI(const AGUI: IAppGUI); procedure StartGame; procedure StopGame; procedure Replay; procedure Tapped; end; IAppGUI = interface procedure RegisterController(const AController: IAppController); function GetGamePanelWidth: Integer; function GetGamePanelHeight: Integer; procedure ResetGame; procedure SetScore(AScore: Integer); procedure GameOver(AScore, ABestScore: Integer); function GetHRatio: Integer; function GetScreenScale: Single; procedure SetBird(ABird: TBird); procedure AddPipe(APipe: TPipe); procedure RemovePipe(APipe: TPipe); procedure MovePipe(APipe: TPipe); end; implementation { TBird } function TBird.GetRect: TRect; begin Result:= Rect(Trunc(X),Trunc(Y),Trunc(X+Width),Trunc(Y+Heigth)); end; { TPipe } function TPipe.GetRect: TRect; begin Result:= Rect(Trunc(X),Trunc(Y),Trunc(X+Width),Trunc(Y+Heigth)); end; end.
{ @abstract Implements @link(TNtDevExpressChecker) checker extension class that checks DevExpress controls. To enable checking just add this unit into your project or add unit into any uses block. @longCode(# implementation uses NtDevExpressChecker; #) See @italic(Samples\Delphi\VCL\DevExpress\Checker) sample to see how to use the unit. } unit NtDevExpressChecker; interface uses Controls, NtChecker; type { @abstract Checker extension class that checks some complex DevExpress controls. } TNtDevExpressChecker = class(TNtCheckerExtension) public { @seealso(TNtCheckerExtension.Show) } function Show(checker: TFormChecker; control: TControl; var restoreControl: TControl): Boolean; override; { @seealso(TNtCheckerExtension.Restore) } function Restore(control, restoreControl: TControl): Boolean; override; { @seealso(TNtCheckerExtension.Ignore) } function Ignore(control: TControl; issueTypes: TFormIssueTypes): Boolean; override; end; implementation uses cxPC; function TNtDevExpressChecker.Show(checker: TFormChecker; control: TControl; var restoreControl: TControl): Boolean; var tabSheet: TcxTabSheet; begin tabSheet := checker.GetParent(control, TcxTabSheet) as TcxTabSheet; if tabSheet <> nil then begin restoreControl := tabSheet.PageControl.ActivePage; tabSheet.PageControl.ActivePage := tabSheet; tabSheet.PageControl.Update; Result := True; end else Result := False; end; function TNtDevExpressChecker.Restore(control, restoreControl: TControl): Boolean; var tabSheet: TcxTabSheet; begin if restoreControl is TcxTabSheet then begin tabSheet := TcxTabSheet(restoreControl); tabSheet.PageControl.ActivePage := tabSheet; tabSheet.PageControl.Update; Result := True; end else Result := False; end; function TNtDevExpressChecker.Ignore(control: TControl; issueTypes: TFormIssueTypes): Boolean; begin Result := (control is TcxTabSheet) and (itOverlap in issueTypes); end; initialization NtCheckerExtensions.Register(TNtDevExpressChecker); end.
unit feli_response; {$mode objfpc} interface uses fpjson; type FeliResponse = class(TObject) public authenticated: boolean; error, msg: ansiString; resCode: integer; function toTJsonObject(): TJsonObject; virtual; function toJson(): ansiString; virtual; end; FeliResponseDataObject = class(FeliResponse) public data: TJsonObject; function toTJsonObject(): TJsonObject; override; end; FeliResponseDataArray = class(FeliResponse) public data: TJsonArray; function toTJsonObject(): TJsonObject; override; end; implementation uses feli_logger, feli_stack_tracer; function FeliResponse.toTJsonObject(): TJsonObject; var resObject: TJsonObject; begin FeliStackTrace.trace('begin', 'function FeliResponse.toTJsonObject(): TJsonObject;'); resObject := TJsonObject.create(); resObject.add('status', resCode); resObject.add('authenticated', authenticated); if (error <> '') then resObject.add('error', error); if (msg <> '') then resObject.add('message', msg); result := resObject; FeliStackTrace.trace('end', 'function FeliResponse.toTJsonObject(): TJsonObject;'); end; function FeliResponse.toJson(): ansiString; var jsonObject: TJsonObject; begin FeliStackTrace.trace('begin', 'function FeliResponse.toJson(): ansiString;'); jsonObject := toTJsonObject(); result := jsonObject.formatJson; FeliStackTrace.trace('end', 'function FeliResponse.toJson(): ansiString;'); end; function FeliResponseDataArray.toTJsonObject(): TJsonObject; var resObject: TJsonObject; begin FeliStackTrace.trace('begin', 'function FeliResponseDataArray.toTJsonObject(): TJsonObject;'); resObject := TJsonObject.create(); resObject.add('status', resCode); resObject.add('authenticated', authenticated); if (error <> '') then resObject.add('error', error); resObject.add('data', data); result := resObject; FeliStackTrace.trace('end', 'function FeliResponseDataArray.toTJsonObject(): TJsonObject;'); end; function FeliResponseDataObject.toTJsonObject(): TJsonObject; var resObject: TJsonObject; begin FeliStackTrace.trace('begin', 'function FeliResponseDataObject.toTJsonObject(): TJsonObject;'); resObject := TJsonObject.create(); resObject.add('status', resCode); resObject.add('authenticated', authenticated); if (error <> '') then resObject.add('error', error); resObject.add('data', data); result := resObject; FeliStackTrace.trace('end', 'function FeliResponseDataObject.toTJsonObject(): TJsonObject;'); end; end.
unit Objekt.SepaBSPos; interface uses SysUtils, Classes, Objekt.SepaVZweck; type TSepaBSPos = class private fBetrag: Currency; fIBAN: string; fEmpfaenger: string; fBIC: string; fVZweck: TSepaVZweck; fWaehrung: string; fZahldatum: TDateTime; fEndToEnd: string; fSU_ID: Integer; public constructor Create; destructor Destroy; override; procedure Init; property Betrag: Currency read fBetrag write fBetrag; property IBAN: string read fIBAN write fIBAN; property Empfaenger: string read fEmpfaenger write fEmpfaenger; property Waehrung: string read fWaehrung write fWaehrung; property BIC: string read fBIC write FBIC; property VZweck: TSepaVZweck read fVZweck write fVZweck; property Zahldatum: TDateTime read fZahldatum write fZahldatum; property EndToEnd: string read fEndToEnd write fEndToEnd; property SU_ID: Integer read fSU_ID write fSU_ID; function VZweckStr: string; end; implementation { TSepaBSPos } constructor TSepaBSPos.Create; begin fVZweck := TSepaVZweck.Create; Init; end; destructor TSepaBSPos.Destroy; begin FreeAndNil(fVZweck); inherited; end; procedure TSepaBSPos.Init; begin fBetrag := 0; fIBAN := ''; fEmpfaenger := ''; fBIC := ''; fWaehrung := 'EUR'; fZahldatum := StrToDate('01.01.1999'); fEndToEnd := ''; fSU_ID := 0; fVZweck.Init; end; function TSepaBSPos.VZweckStr: string; begin Result := ''; if Trim(fVZweck.Zweck1) > '' then Result := Result + Trim(fVZweck.Zweck1) + ' '; if Trim(fVZweck.Zweck2) > '' then Result := Result + Trim(fVZweck.Zweck2) + ' '; if Trim(fVZweck.Zweck3) > '' then Result := Result + Trim(fVZweck.Zweck3) + ' '; if Trim(fVZweck.Zweck4) > '' then Result := Result + Trim(fVZweck.Zweck4) + ' '; Result := Trim(Result); end; end.
// файл board.pas unit board; interface uses Forms, Graphics, Types; Type Tletter = ( _a, _b, _c, _d, _e, _f, _g, _h ); Type Tposition = record x : Tletter; // координаты шахматных y : 1..8; // фигур на доске; end; type Tfigcolor = ( black, white ); // цвет фигур; Type Tid = record // идентификатор фигуры; pos : Tposition; // положение; color : Tfigcolor; // цвет фигуры; number: 0..16; // № фигуры // 0 - отсутствует, 1 - король, 2 - ферзь,... end;
unit RegistryCleaner_Msg; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, typinfo, PNGImage, StdCtrls, acPNG, Grids, AdvObj, BaseGrid, AdvGrid, AdvGlowButton, sLabel, ExtCtrls, AdvGroupBox, IniFiles, Dialogs, ShellAPI, ImgList, acAlphaImageList, Registry, AdvSplitter; const BEGIN_SYSTEM_CHANGE = 100; // Тип события END_SYSTEM_CHANGE = 101; APPLICATION_INSTALL = 0; // Тип точки восстановления CANCELLED_OPERATION = 13; MAX_DESC = 64; MIN_EVENT = 100; // Инфо о точки восстановления type PRESTOREPTINFOA = ^_RESTOREPTINFOA; _RESTOREPTINFOA = packed record dwEventType: DWORD; // Тип события - начало или конец dwRestorePtType: DWORD; // Тип контрольной точки - Установка или удалиние llSequenceNumber: INT64; // Sequence Number - 0 for begin szDescription: array [0..64] of ansichar; // Описание- название программы или операция end; RESTOREPOINTINFO = _RESTOREPTINFOA; PRESTOREPOINTINFOA = ^_RESTOREPTINFOA; // Статус, возвращаемый точкой восстановления PSMGRSTATUS = ^_SMGRSTATUS; _SMGRSTATUS = packed record nStatus: DWORD; // Status returned by State Manager Process llSequenceNumber: INT64; // Sequence Number for the restore point end; STATEMGRSTATUS = _SMGRSTATUS; PSTATEMGRSTATUS = ^_SMGRSTATUS; function SRSetRestorePointA(pRestorePtSpec: PRESTOREPOINTINFOA; pSMgrStatus: PSTATEMGRSTATUS): Bool; stdcall; external 'SrClient.dll' Name 'SRSetRestorePointA'; type TfmMsg = class(TForm) agbLogo: TAdvGroupBox; imgLogoBack: TImage; ThemeShapeMainCaption: TShape; ThemeImgMainCaption: TImage; albLogoText: TsLabel; imgWinTuning: TImage; ShapeBottom: TShape; ShapeLeft: TShape; ThemeImgLeft: TImage; ThemeImgLeftTemp: TImage; AlphaImgsStatus16: TsAlphaImageList; imgsAdditional: TsAlphaImageList; PanelCommon: TPanel; gbLog: TGroupBox; GridLog: TAdvStringGrid; PanelTop: TPanel; lbFixRegistryErrors: TLabel; gbErrorsToFixList: TGroupBox; lbStatusFixErrors: TLabel; GridFixErrorsList: TAdvStringGrid; SplitterRegFiles: TSplitter; btStart: TAdvGlowButton; btCancel: TAdvGlowButton; edLogDetails: TEdit; AlphaImgsSections16: TsAlphaImageList; procedure btOKClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure LoadPNG2Prog(dllname, resname: string; imgobj: TImage); procedure ApplyTheme; procedure LoadSections; procedure ThemeUpdateLeftIMG; procedure btStartClick(Sender: TObject); procedure btCancelClick(Sender: TObject); procedure AddLog(str: string; id: integer); procedure BackupRegKey(HKEYName: HKEY; KeyName, Comment: string; var ExportFile: TStringList); procedure BackupRegParams(HKEYName: HKEY; KeyName: string; var ExportFile: TStringList); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure GridLogClickCell(Sender: TObject; ARow, ACol: Integer); procedure ApplyLang; function CreateRestorePoint: boolean; procedure FormActivate(Sender: TObject); function GetRegKeyType(HKEYName: HKEY; KeyName, ParameterName: PChar): TRegDataType; private { Private declarations } IsLeftImgLoaded: Boolean; //загружена ли левая картинка в компонент ThemeImgLeftTemp - чтобы её оттуда каждый раз читать при изменении размера окна isReady: boolean; isLoaded: boolean; //Переменная нужна, чтобы не было изменений настроек при запуске программы public { Public declarations } ThemeName: string; //название темы оформления protected { Protected declarations } procedure CreateParams(var Params: TCreateParams); override; end; var fmMsg: TfmMsg; implementation uses RegistryCleaner_Results, DataMod; const ScreenWidth: LongInt = 1680; ScreenHeight: LongInt = 1050; REG_QWORD: Cardinal = 11; {$R *.dfm} {СОХРАНИТЬ ПОЗИЦИЮ ОКНА ПРИ ЗАКРЫТИИ} procedure SaveWndPosition(FormName: TForm; KeyToSave: PChar); external 'Functions.dll'; {ВОССТАНОВИТЬ ПОЗИЦИЮ ОКНА ПРИ ЗАПУСКЕ} procedure RestoreWndPosition(FormName: TForm; KeyToSave: PChar); external 'Functions.dll'; {ВЫВОДИМ РАЗНУЮ ИНФУ О ВЕРСИИ WINTUNING: ИНДЕКС, ГОД ОКОНЧАНИЯ ИСПОЛЬЗОВАНИЯ И ТД.} function GetWTVerInfo(info_id: integer): integer; external 'Functions.dll'; {ЧТЕНИЕ НАСТРОЕК ПРОГРАММЫ} function GetProgParam(paramname: PChar): PChar; external 'Functions.dll'; {ПРЕОБРАЗОВАНИЕ СТРОКИ ВИДА R,G,B В TCOLOR} function ReadRBG(instr: PChar): TColor; external 'Functions.dll'; {ОТКРЫТЬ ОПРЕДЕЛЁННЫЙ РАЗДЕЛ СПРАВКИ} procedure ViewHelp(page: PChar); stdcall; external 'Functions.dll'; {ПРЕОБРАЗОВАНИЕ СТРОКИ ВИДА %WinTuning_PATH% В C:\Program Files\WinTuning 7} function ThemePathConvert(InStr, InThemeName: PChar): PChar; external 'Functions.dll'; {ЧТЕНИЕ ЯЗЫКОВОЙ СТРОКИ ИЗ ОПРЕДЕЛЁННОГО ФАЙЛА} function ReadLangStr(FileName, Section, Caption: PChar): PChar; external 'Functions.dll'; {ЗАПУЩЕНА ЛИ 64-Х БИТНАЯ СИСТЕМА} function IsWOW64: Boolean; external 'Functions.dll'; {УЗНАЁМ ТИП ДАННЫХ В REGISTR} //function GetRegKeyType(HKEYName: HKEY; KeyName, ParameterName: PChar): Cardinal; external 'RegistryExtendedFunctions.dll'; {ВЫВОДИМ НАЗВАНИЕ ВЕРСИИ WINTUNING: [XP, VISTER, 7]} function GetCapInfo(WTVerID, info_id: integer): shortstring; external 'Functions.dll'; //========================================================= {ПРОДЕДУРА ПОЛУЧЕНИЯ ТИПА КЛЮЧА} //--------------------------------------------------------- function TfmMsg.GetRegKeyType(HKEYName: HKEY; KeyName, ParameterName: PChar): TRegDataType; var reg : tregistry; info : TRegDataInfo; begin reg := tregistry.create; try reg.RootKey := HKEYName; reg.OpenKey(KeyName,true); reg.GetDataInfo(ParameterName, info);//получаем о ней информацию finally reg.free; end; Result := info.RegData; end; //========================================================= //========================================================= {ОТОБРАЖАЕТ ФОРМУ НА ПАНЕЛИ ЗАДАЧ} //--------------------------------------------------------- procedure TfmMsg.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); with Params do begin ExStyle := ExStyle or WS_EX_APPWINDOW; WndParent := GetDesktopwindow; end; end; //========================================================= //========================================================= {ЗАГРУЗКА ИЗОБРАЖЕНИЯ В ОБЛАСТЬ НА ФОРМЕ} //--------------------------------------------------------- procedure TfmMsg.LoadPNG2Prog(dllname, resname: string; imgobj: TImage); var h: THandle; ResStream: TResourceStream; PNG: TPngImage; begin h:= LoadLibrary(PChar(dllname)); PNG := TPngImage.Create; ResStream := TResourceStream.Create(h, resname, rt_RCData); PNG.LoadFromStream(ResStream); imgobj.Picture.Assign(PNG); ResStream.free; PNG.Free; end; //========================================================= //========================================================= {ЗАМОСТИТЬ ЛЕВУЮ ПАНЕЛЬ КАРТИНКОЙ} //--------------------------------------------------------- procedure TfmMsg.ThemeUpdateLeftIMG; var x,y: integer; // левый верхний угол картинки ImgObjLeft: TImage; begin if ThemeImgLeft.Picture <> nil then ThemeImgLeft.Picture := nil; if IsLeftImgLoaded then begin ImgObjLeft := TImage.Create(Self); ImgObjLeft.Picture.Assign(ThemeImgLeftTemp.Picture); ImgObjLeft.AutoSize := True; x:=0; y:=0; while y < ThemeImgLeft.Height do begin while x < ThemeImgLeft.Width do begin ThemeImgLeft.Canvas.Draw(x,y,ImgObjLeft.Picture.Graphic); x:=x+ImgObjLeft.Width; end; x:=0; y:=y+ImgObjLeft.Height; end; ImgObjLeft.Free; end; end; //========================================================= //========================================================= {ЗАПОЛНЯЕМ СУЩЕСТВУЮЩИЕ РАЗДЕЛЫ} //--------------------------------------------------------- procedure TfmMsg.LoadSections; var i,j, ErrorsSelectedCount, LastIndex, SumErr: Integer; begin LastIndex := 1; SumErr := 0; for i := 0 to Length(fmDataMod.RegSections)-1 do begin ErrorsSelectedCount := 0; for j := 0 to Length(fmDataMod.RegErrors)-1 do begin if fmDataMod.RegErrors[j].SectionCode = i then begin if (fmDataMod.RegErrors[j].Enabled) AND (not fmDataMod.RegErrors[j].Excluded) then inc(ErrorsSelectedCount); end; end; if ErrorsSelectedCount>0 then begin GridFixErrorsList.AddRow; GridFixErrorsList.AddImageIdx(1,LastIndex,0,haBeforeText,vaCenter); GridFixErrorsList.GridCells[2, LastIndex] := fmDataMod.RegSections[i].Caption; GridFixErrorsList.AddImageIdx(2,LastIndex,i+3,haBeforeText,vaCenter); GridFixErrorsList.GridCells[3, LastIndex] := IntToStr(i); GridFixErrorsList.GridCells[4, LastIndex] := IntToStr(ErrorsSelectedCount); GridFixErrorsList.GridCells[5, LastIndex] := ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'Waiting'); inc(LastIndex); end; SumErr := SumErr + ErrorsSelectedCount; end; GridFixErrorsList.HideColumn(3); GridFixErrorsList.AutoSizeColumns(True); lbStatusFixErrors.Caption := stringReplace(ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'lbStatusFixErrors'), '%1', IntToStr(SumErr), [rfReplaceAll,rfIgnoreCase]); end; //========================================================= //========================================================= {ПРИМЕНЕНИЕ СКИНА} //========================================================= procedure TfmMsg.ApplyTheme; var ThemeFileName, StrTmp, ThemeName: string; ThemeFile: TIniFile; //ini-файл темы оформления begin //Языковые настройки ThemeName := GetProgParam('theme'); //Разделы ThemeFileName := ExtractFilePath(paramstr(0)) + 'Themes\' + ThemeName + '\Theme.ini'; if SysUtils.FileExists(ThemeFileName) then begin ThemeFile := TIniFile.Create(ThemeFileName); //Цвет окна Color := ReadRBG(PChar(ThemeFile.ReadString('Utilities', 'WndColor', '240,240,240'))); //Фон логотипа imgLogoBack.Visible := ThemeFile.ReadBool('Utilities', 'LogoBackImageShow', True); StrTmp := ThemePathConvert(PChar(ThemeFile.ReadString('Utilities', 'LogoBackImagePath', '')), PChar(ThemeName)); if SysUtils.FileExists(StrTmp) then imgLogoBack.Picture.LoadFromFile(StrTmp); //Левая картинка (левый фон) ThemeImgLeft.Visible := ThemeFile.ReadBool('Utilities', 'ImageLeftShow', False); StrTmp := ThemePathConvert(PChar(ThemeFile.ReadString('Utilities', 'ImageLeftPath', '')), PChar(ThemeName)); if SysUtils.FileExists(StrTmp) then begin IsLeftImgLoaded := True; ThemeImgLeftTemp.Picture.LoadFromFile(StrTmp); end; //Фон заголовка утилиты ThemeImgMainCaption.Visible := ThemeFile.ReadBool('Utilities', 'UtilCaptionBackImageShow', True); StrTmp := ThemePathConvert(PChar(ThemeFile.ReadString('Utilities', 'UtilCaptionBackImagePath', '')), PChar(ThemeName)); if SysUtils.FileExists(StrTmp) then ThemeImgMainCaption.Picture.LoadFromFile(StrTmp); //Цвет шрифта заголовка albLogoText.Font.Color := ReadRBG(PChar(ThemeFile.ReadString('Utilities', 'UtilCaptionFontColor', '53,65,79'))); //Цвет фона загловка утилиты в случае, если НЕТ картинки ThemeShapeMainCaption.Brush.Color := ReadRBG(PChar(ThemeFile.ReadString('Utilities', 'UtilCaptionBackgroundColor', '243,243,243'))); //Цвет борюда загловка утилиты ThemeShapeMainCaption.Brush.Color := ReadRBG(PChar(ThemeFile.ReadString('Utilities', 'UtilCaptionBackgroundColor', '243,243,243'))); ThemeShapeMainCaption.Pen.Color := ReadRBG(PChar(ThemeFile.ReadString('Utilities', 'UtilCaptionBorderColor', '210,220,227'))); ShapeLeft.Pen.Color := ReadRBG(PChar(ThemeFile.ReadString('Utilities', 'UtilCaptionBorderColor', '210,220,227'))); ShapeBottom.Pen.Color := ReadRBG(PChar(ThemeFile.ReadString('Utilities', 'UtilCaptionBorderColor', '210,220,227'))); agbLogo.BorderColor := ReadRBG(PChar(ThemeFile.ReadString('Utilities', 'UtilCaptionBorderColor', '210,220,227'))); //Нижний бордюрчик ShapeBottom.Brush.Color := ReadRBG(PChar(ThemeFile.ReadString('Utilities', 'BorderBottomColor', '243,245,248'))); ThemeFile.Free; end; end; //========================================================= //========================================================= {ДОБАВЛЕНИЕ СТРОКИ ЛОГА} //--------------------------------------------------------- procedure TfmMsg.AddLog(str: string; id: integer); var iconindex: integer; begin GridLog.AddRow; GridLog.Cells[1,GridLog.RowCount-1] := DateTimeToStr(now()); GridLog.Cells[2,GridLog.RowCount-1] := str; iconindex := -1; if id = 0 then iconindex := 0; //успешный пункт if id = 1 then iconindex := 1; //важный пункт if id = 2 then iconindex := 2; //просто пункт if id = 3 then iconindex := 3; //восстановленный пункт GridLog.AddImageIdx(1,GridLog.RowCount-1,3,haBeforeText,vaCenter); GridLog.AddImageIdx(2,GridLog.RowCount-1,iconindex,haBeforeText,vaCenter); GridLog.AutoSizeCol(0); GridLog.AutoSizeCol(1); GridLog.AutoSizeCol(2); GridLog.SelectRows(GridLog.RowCount-1,1); lbStatusFixErrors.Caption := str; Application.ProcessMessages; end; //========================================================= //========================================================= {ПРОДЕДУРА СОЗДАНИЯ КОПИИ КЛЮЧА РЕЕСТРА И ВСЕГО ЕГО СОДЕРЖИМОГО НА ЭКСПОРТ ДЛЯ ВОЗМОЖНОСТИ ВОССТАНОВЛЕНИЯ} //--------------------------------------------------------- procedure TfmMsg.BackupRegKey(HKEYName: HKEY; KeyName, Comment: string; var ExportFile: TStringList); var BackupReg: TRegistry; TrailingStr: string; //--------------------------------------------------------- procedure ProcessBranch(root: string); {recursive sub-procedure} var keys: TStringList; i: longint; s: string; {longstrings are on the heap, not on the stack!} begin case HKEYName of HKEY_CLASSES_ROOT: s := 'HKEY_CLASSES_ROOT'; HKEY_CURRENT_USER: s := 'HKEY_CURRENT_USER'; HKEY_LOCAL_MACHINE: s := 'HKEY_LOCAL_MACHINE'; HKEY_USERS: s := 'HKEY_USERS'; HKEY_PERFORMANCE_DATA: s := 'HKEY_PERFORMANCE_DATA'; HKEY_CURRENT_CONFIG: s := 'HKEY_CURRENT_CONFIG'; HKEY_DYN_DATA: s := 'HKEY_DYN_DATA'; end; if root[1] = '\' then TrailingStr := '' else TrailingStr := '\'; ExportFile.Add('[' + s + TrailingStr + root + ']'); {write section name in brackets} BackupReg.OpenKey(root, False); BackupRegParams(HKEYName, root, ExportFile); // ExportFile.Add(''); {write blank line} keys := TStringList.Create; try try BackupReg.GetKeynames(keys); {get all sub-branches} finally BackupReg.CloseKey; end; for i := 0 to keys.Count - 1 do ProcessBranch(root + '\' + keys[i]); finally keys.Free; {this branch is ready} end; end; { ProcessBranch} //--------------------------------------------------------- begin if KeyName[Length(KeyName)] = '\' then SetLength(KeyName, Length(KeyName) - 1); {No trailing backslash} ExportFile.Add(';'+Comment); BackupReg := TRegistry.Create(); if IsWOW64 then BackupReg.Access := KEY_WOW64_64KEY or KEY_ALL_ACCESS or KEY_WRITE or KEY_READ; BackupReg.RootKey := HKEYName; ProcessBranch(KeyName); {Call the function that writes the branch and all subbranches} BackupReg.Free; end; //========================================================= //========================================================= {ПРОДЕДУРА ПРЕОБРАЗОВАНИЯ ДЕСЯТИЧНОГО ЧИСЛА В ШЕСТНАДЦАТИРИЧНОЕ - ДВЕ ЗНАЧАЩИХ ЦИФРЫ(14 -> 0e, ...)} //--------------------------------------------------------- function InvertBytes(InStr: string): string; var OutStr: string; begin Result := ''; if Length(InStr)<>4 then begin Result := InStr; Exit; end; InStr := LowerCase(InStr); OutStr := '00,00'; OutStr[1] := InStr[3]; OutStr[2] := InStr[4]; OutStr[4] := InStr[1]; OutStr[5] := InStr[2]; Result := OutStr; end; //========================================================= //========================================================= {ПРОЦЕДУРА ДОБАВЛЕНИЯ HEX-ЗНАЧЕНИЯ (РАЗДЕЛЕНИЕ БОЛЬШОЙ СТРОКИ НА МНОГО СТРОК)} //--------------------------------------------------------- procedure AddHexToStringList(BeforeString, HEXString: string; var ExportFile: TStringList); const MAX_HEX_STR_SZ: integer = 25; var i, j, BeforeSize,HEXBytes,StrlCount: integer; tstr: TStringList; TempStr: string; NewLineCondition: boolean; begin BeforeSize := Length(BeforeString); tstr := TStringList.Create; tstr.text := stringReplace(LowerCase(HEXString), ',', #13#10, [rfReplaceAll]); HEXBytes := tstr.Count; TempStr := BeforeString; StrlCount := 0; j := 0; for i := 0 to HEXBytes-1 do begin TempStr := TempStr + tstr.Strings[i]; inc(j); if (i >= 0) AND (i < HEXBytes-1) then TempStr := TempStr + ','; if StrlCount = 0 then NewLineCondition := (i > 0) AND (i < HEXBytes-1) AND ((j mod (MAX_HEX_STR_SZ - Round(BeforeSize/3)+1))=0) else NewLineCondition := (i > 0) AND (i < HEXBytes-1) AND ((j mod MAX_HEX_STR_SZ)=0); if NewLineCondition then begin TempStr := TempStr + '\'; if StrlCount = 0 then ExportFile.Add(TempStr) else ExportFile.Add(' '+TempStr); TempStr := ''; inc(StrlCount); j := 0; end; end; if StrlCount = 0 then ExportFile.Add(TempStr) else ExportFile.Add(' '+TempStr); tstr.Free; end; //========================================================= //========================================================= {ПРИ КЛИКЕ ПО ЛОГУ} //--------------------------------------------------------- procedure TfmMsg.GridLogClickCell(Sender: TObject; ARow, ACol: Integer); begin edLogDetails.Text := GridLog.Cells[2,ARow]; end; //========================================================= //========================================================= {ПРОДЕДУРА СОЗДАНИЯ КОПИИ ПАРАМЕТРОВ ПЕРЕДАННОГО КЛЮЧА} //--------------------------------------------------------- procedure TfmMsg.BackupRegParams(HKEYName: HKEY; KeyName: string; var ExportFile: TStringList); var BackupReg: TRegistry; Values: TStringList; i,j: Integer; ParameterName, ValueName, ParameterToSave, ValueType, TempStr, KayNameWithoutTheTrailingSlashes: string; RegValueType: TRegDataType; begin BackupReg := TRegistry.Create(); if IsWOW64 then BackupReg.Access := KEY_WOW64_64KEY or KEY_ALL_ACCESS or KEY_WRITE or KEY_READ; BackupReg.RootKey := HKEYName; BackupReg.OpenKey(KeyName, True); Values := TStringList.Create; BackupReg.GetValueNames(Values); for i := 0 to Values.Count-1 do begin ParameterName := Values.Strings[i]; ParameterToSave := ParameterName; ParameterToSave := StringReplace(ParameterToSave, '\', '\\', [rfReplaceAll]); ParameterToSave := StringReplace(ParameterToSave, '"', '\"', [rfReplaceAll]); if ParameterName = '' then ParameterToSave := '@' //значение по умолчанию else ParameterToSave := '"'+ParameterToSave+'"'; // Memo2.Lines.Add('ParameterToSave4='+ParameterToSave); KayNameWithoutTheTrailingSlashes := KeyName; if KayNameWithoutTheTrailingSlashes[1] = '\' then KayNameWithoutTheTrailingSlashes := StringReplace(KayNameWithoutTheTrailingSlashes, '\', '', [rfIgnoreCase]); RegValueType := GetRegKeyType(HKEYName,PChar(KayNameWithoutTheTrailingSlashes),PChar(ParameterName)); if RegValueType=rdString then //Строка begin ValueName := BackupReg.ReadString(ParameterName); ValueName := StringReplace(ValueName, '\', '\\', [rfReplaceAll, rfIgnoreCase]); ValueName := StringReplace(ValueName, '"', '\"', [rfReplaceAll, rfIgnoreCase]); ValueName := '"'+ValueName+'"'; ValueType := ''; end; if RegValueType=rdInteger then //DWORD begin ValueName := LowerCase(IntToHex(BackupReg.ReadInteger(ParameterName),8)); ValueType := 'dword:'; end; if RegValueType=rdBinary then //HEX (бинарный тип, двоичный параметр) begin ValueName := LowerCase(BackupReg.GetDataAsString(ParameterName)); ValueType := 'hex:'; end; if (RegValueType=rdExpandString) then //Расширяемый строковой параметр begin TempStr := BackupReg.ReadString(ParameterName); ValueName := ''; for j := 1 to Length(TempStr) do begin ValueName := ValueName + InvertBytes(IntToHex(Ord(TempStr[j]),4)); if j <> Length(TempStr) then ValueName := ValueName + ','; end; ValueName := ValueName + ',00,00'; { buf := nil; BufSize := 0; BufSize := BackupReg.GetDataSize(ParameterName); SetLength(buf, BufSize); BackupReg.ReadBinaryData(ParameterName, buf, BufSize); ValueName := ''; for j := 0 to BufSize-1 do begin ValueName := ValueName + hexadecimal2D(buf[j],True); if j <> BufSize-1 then ValueName := ValueName + ','; end;} ValueType := 'hex(2):'; end; // if (RegValueType>rdBinary) or (RegValueType=rdUnknown) then //В случае, если параметр неизвестен - значит, скорее всего, это бинарный тип данных if (RegValueType=rdUnknown) then //В случае, если параметр неизвестен - значит, скорее всего, это бинарный тип данных begin ValueName := BackupReg.GetDataAsString(ParameterName); // ValueType := 'hex('+IntToHex(RegValueType,1)+'):'; ValueType := 'hex(4):'; end; { if RegValueType=REG_LINK then //REG_LINK begin ValueName := BackupReg.GetDataAsString(ParameterName); ValueType := 'hex(6):'; end; if RegValueType=REG_MULTI_SZ then //Мультистроковой параметр begin ValueName := BackupReg.GetDataAsString(ParameterName); ValueType := 'hex(7):'; end; if RegValueType=REG_NONE then //Не определено begin ValueName := BackupReg.GetDataAsString(ParameterName); ValueType := 'hex(0):'; end; if RegValueType=REG_RESOURCE_LIST then //<REG_RESOURCE_LIST (as comma-delimited list of hexadecimal values)> begin ValueName := BackupReg.GetDataAsString(ParameterName); ValueType := 'hex(8):'; end; if RegValueType=REG_QWORD then //<QWORD value (as comma-delimited list of 8 hexadecimal values, in little endian byte order)> begin ValueName := BackupReg.GetDataAsString(ParameterName); ValueType := 'hex(b):'; end; if RegValueType=REG_RESOURCE_REQUIREMENTS_LIST then //<REG_RESOURCE_REQUIREMENTS_LIST (as comma-delimited list of hexadecimal values)> begin ValueName := BackupReg.GetDataAsString(ParameterName); ValueType := 'hex(a):'; end;} if StrPos(PChar(ValueType), 'hex')<>nil then begin TempStr := ParameterToSave+'='+ValueType; AddHexToStringList(TempStr, ValueName, ExportFile); end else ExportFile.Add(ParameterToSave+'='+ValueType+ValueName+''); end; BackupReg.Free; end; //========================================================= //========================================================= {СОЗДАНИЕ КОНТРОЛЬНОЙ ТОЧКИ ВОССТАНОВЛЕНИЯ} //--------------------------------------------------------- function TfmMsg.CreateRestorePoint: boolean; var RestorePtSpec: RESTOREPOINTINFO; SMgrStatus: STATEMGRSTATUS; begin Result := False; TRY RestorePtSpec.dwEventType := BEGIN_SYSTEM_CHANGE; RestorePtSpec.dwRestorePtType := APPLICATION_INSTALL; RestorePtSpec.llSequenceNumber := 0; RestorePtSpec.szDescription := 'WinTuning Registry Cleaner Restore Point'; if (SRSetRestorePointA(@RestorePtSpec, @SMgrStatus)) then Result := True; EXCEPT END; end; //========================================================= {КНОПКА "ИСПРАВИТЬ"} //--------------------------------------------------------- procedure TfmMsg.btStartClick(Sender: TObject); var i, j, SectionIndex, OldErrorCount: integer; TempStr, StatusStr, StatusStr2, StatusStr3, CatFontColor: string; MYear,MMonth,MDay,MHour,MMinute,MSecond,MilSec: Word; NewStrLst: TStringList; begin if not isReady then begin btStart.Enabled := False; StatusStr := ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'LogStart'); AddLog(StatusStr,2); NewStrLst := TStringList.Create; NewStrLst.Add('Windows Registry Editor Version 5.00'); NewStrLst.Add(''); NewStrLst.Add(';WinTuning: Registry Cleaner Buckup File'); NewStrLst.Add(';2012-2018 (c) Ivan Saldikov'); NewStrLst.Add(';'+ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'BackupFileCommentFileCreatedOn')+': '+DateTimeToStr(now())); NewStrLst.Add(''); StatusStr := ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'LogSystemRestorePointBegin'); AddLog(StatusStr,2); if CreateRestorePoint then begin StatusStr := ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'LogSystemRestorePointOK'); AddLog(StatusStr,0); end else begin StatusStr := ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'LogSystemRestorePointError'); AddLog(StatusStr,2); end; for i := 1 to GridFixErrorsList.RowCount-1 do begin GridFixErrorsList.RemoveImageIdx(1,i); GridFixErrorsList.AddImageIdx(1,i,1,haBeforeText,vaCenter); GridFixErrorsList.GridCells[5, i] := ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'LogStart'); GridFixErrorsList.AutoSizeCol(4); GridFixErrorsList.Refresh; Application.ProcessMessages; StatusStr := stringReplace(ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'LogBeginSection'), '%1', GridFixErrorsList.Cells[2, i], [rfReplaceAll,rfIgnoreCase]); AddLog(StatusStr,2); SectionIndex := StrToInt(GridFixErrorsList.Cells[3, i]); OldErrorCount := fmDataMod.RegSections[SectionIndex].ErrorsCount; for j := 0 to Length(fmDataMod.RegErrors)-1 do begin if fmDataMod.RegErrors[j].SectionCode = SectionIndex then begin if (fmDataMod.RegErrors[j].Enabled) AND (not fmDataMod.RegErrors[j].Excluded) then begin AddLog(ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'LogSavingKeyBeforeProcessing'),0); BackupRegKey(fmDataMod.RegErrors[j].RootKey, fmDataMod.RegErrors[j].SubKey, fmDataMod.RegErrors[j].Text, NewStrLst); fmDataMod.RegErrorsFile.Add(fmDataMod.RegErrors[j].Text); fmDataMod.RegClean.RootKey := fmDataMod.RegErrors[j].RootKey; if fmDataMod.RegErrors[j].RootKey = HKEY_CLASSES_ROOT then TempStr := 'HKEY_CLASSES_ROOT'; if fmDataMod.RegErrors[j].RootKey = HKEY_LOCAL_MACHINE then TempStr := 'HKEY_LOCAL_MACHINE'; if fmDataMod.RegErrors[j].RootKey = HKEY_CURRENT_USER then TempStr := 'HKEY_CURRENT_USER'; fmDataMod.RegClean.OpenKey(fmDataMod.RegErrors[j].SubKey, True); TRY case fmDataMod.RegErrors[j].Solution of regDel: begin if fmDataMod.RegErrors[j].Parameter = '' then begin fmDataMod.RegClean.DeleteKey(fmDataMod.RegErrors[j].SubKey); StatusStr2 := stringReplace(ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'LogFixErrorInKey'), '%1', TempStr+fmDataMod.RegErrors[j].SubKey, [rfReplaceAll,rfIgnoreCase]); StatusStr := '"'+GridFixErrorsList.Cells[2, i]+'" - '+StatusStr2+': '+ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'LogKeyDeleted'); AddLog(StatusStr,0); end else begin fmDataMod.RegClean.DeleteValue(fmDataMod.RegErrors[j].Parameter); StatusStr3 := stringReplace(ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'LogParameterDeletedFromKey'), '%1', fmDataMod.RegErrors[j].Parameter, [rfReplaceAll,rfIgnoreCase]); StatusStr := '"'+GridFixErrorsList.Cells[2, i]+'" - '+StatusStr2+': '+StatusStr3; AddLog(StatusStr,0); end; end; regMod: begin fmDataMod.RegClean.WriteString(fmDataMod.RegErrors[j].Parameter, fmDataMod.RegErrors[j].NewValueData); if fmDataMod.RegErrors[j].Parameter = '' then fmDataMod.RegErrors[j].Parameter := '('+ReadLangStr('WinTuning_Common.lng', 'Common', 'Default')+')'; StatusStr3 := stringReplace(ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'LogParamNewValue'), '%1', fmDataMod.RegErrors[i].Parameter, [rfReplaceAll,rfIgnoreCase]); StatusStr3 := stringReplace(StatusStr3, '%2', fmDataMod.RegErrors[j].NewValueData, [rfReplaceAll,rfIgnoreCase]); StatusStr := '"'+GridFixErrorsList.Cells[2, i]+'" - '+StatusStr2+': '+StatusStr3; AddLog(StatusStr,0); end; end; fmDataMod.RegErrors[j].Fixed := True; fmDataMod.RegErrors[j].Enabled := False; inc(fmDataMod.RegSections[SectionIndex].ErrorsCount,-1); inc(fmDataMod.RegErrorsFound,-1); inc(fmDataMod.RegErrorsFixed); fmRegistryCleanerResults.lbStatFixed.Caption := stringReplace(ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'FixedErrorsCounterLog'), '%1', IntToStr(fmDataMod.RegErrorsFixed), [rfReplaceAll,rfIgnoreCase]); EXCEPT on E: Exception do begin StatusStr := stringReplace(ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'LogProcessingError'), '%1', TempStr+fmDataMod.RegErrors[j].SubKey, [rfReplaceAll,rfIgnoreCase]); AddLog(StatusStr,2); end; END; end; end; end; for j := 1 to fmRegistryCleanerResults.GridListOfSections.RowCount-1 do begin if StrToInt(fmRegistryCleanerResults.GridListOfSections.Cells[2,j])=SectionIndex then begin fmRegistryCleanerResults.GridListOfSections.Cells[1,j] := StringReplace(fmRegistryCleanerResults.GridListOfSections.Cells[1,j], '('+IntToStr(OldErrorCount)+')', '('+IntToStr(fmDataMod.RegSections[SectionIndex].ErrorsCount)+')', [rfReplaceAll,rfIgnoreCase]); end; end; for j := 1 to fmRegistryCleanerResults.GridCategories.RowCount-1 do begin if StrToInt(fmRegistryCleanerResults.GridCategories.Cells[1,j])=SectionIndex then begin if fmDataMod.RegSections[SectionIndex].ErrorsCount > 0 then CatFontColor := '#0500da' else CatFontColor := '#22355d'; fmRegistryCleanerResults.GridCategories.Cells[2,j] := fmDataMod.RegSections[SectionIndex].Caption + ' <font color="'+CatFontColor+'">('+IntToStr(fmDataMod.RegSections[SectionIndex].ErrorsCount)+')</font>'; end; end; fmRegistryCleanerResults.GridCategories.Refresh; GridFixErrorsList.RemoveImageIdx(1,i); GridFixErrorsList.AddImageIdx(1,i,2,haBeforeText,vaCenter); GridFixErrorsList.GridCells[5, i] := ReadLangStr('WinTuning_Common.lng', 'Common', 'Ready'); GridFixErrorsList.Refresh; Application.ProcessMessages; StatusStr := stringReplace(ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'LogSectionDone'), '%1', GridFixErrorsList.Cells[2, i], [rfReplaceAll,rfIgnoreCase]); AddLog(StatusStr,0); end; fmRegistryCleanerResults.GridDetails.BeginUpdate; fmRegistryCleanerResults.GridDetails.RemoveRows(1, fmRegistryCleanerResults.GridDetails.RowCount-1); fmRegistryCleanerResults.GridDetails.EndUpdate; fmRegistryCleanerResults.edParamValue.Text := ''; DecodeDate(now, MYear,MMonth,MDay); DecodeTime(now, MHour,MMinute,MSecond,MilSec); TempStr := 'WT_Backup_'+IntToStr(MYear)+'_'+IntToStr(MMonth)+'_'+IntToStr(MDay)+'_'+IntToStr(MHour)+'_'+IntToStr(MMinute)+'_'+IntToStr(MSecond); StatusStr2 := fmDataMod.PathToUtilityFolder+'Backups\'+TempStr+'.reg'; StatusStr := stringReplace(ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'LogSavingReg'), '%1', StatusStr2, [rfReplaceAll,rfIgnoreCase]); AddLog(StatusStr,1); if not DirectoryExists(fmDataMod.PathToUtilityFolder) then SysUtils.ForceDirectories(fmDataMod.PathToUtilityFolder); if not DirectoryExists(fmDataMod.PathToUtilityFolder+'Backups') then SysUtils.ForceDirectories(fmDataMod.PathToUtilityFolder+'Backups'); NewStrLst.SaveToFile(fmDataMod.PathToUtilityFolder+'Backups\'+TempStr+'.reg'); NewStrLst.Free; fmDataMod.RegErrorsFile.SaveToFile(fmDataMod.PathToUtilityFolder+'ErrExcpt'); fmRegistryCleanerResults.lbStatFound.Caption := ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'lbStatFound')+': '+IntToStr(fmDataMod.RegErrorsFound); StatusStr := ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'LogFixDone'); AddLog(StatusStr,0); if fmRegistryCleanerResults.agbErrorsList.Visible then begin fmRegistryCleanerResults.SelectedSectionIndex := -1; fmRegistryCleanerResults.GridCategories.OnClickCell(Self, fmRegistryCleanerResults.GridCategories.RealRow, fmRegistryCleanerResults.GridCategories.RealCol); end; btStart.Enabled := True; btStart.Caption := ReadLangStr('WinTuning_Common.lng', 'Common', 'Ready'); btCancel.Enabled := False; isReady := True; end else begin btCancel.Click; end; end; //========================================================= //========================================================= {КНОПКА "ОТМЕНА"} //--------------------------------------------------------- procedure TfmMsg.btCancelClick(Sender: TObject); begin Close; end; //========================================================= //========================================================= {КНОПКА "ЗАКРЫТЬ"} //--------------------------------------------------------- procedure TfmMsg.btOKClick(Sender: TObject); begin fmMsg.Close; end; //========================================================= //========================================================= {ПРИ ЗАКРЫТИИ ФОРМЫ} //--------------------------------------------------------- procedure TfmMsg.FormClose(Sender: TObject; var Action: TCloseAction); var RegCl: TRegistry; begin RegCl := TRegistry.Create; RegCl.RootKey := HKEY_CURRENT_USER; RegCl.OpenKey('\Software\WinTuning\RegistryCleaner', True); TRY RegCl.WriteInteger('gbLog', gbLog.Height); EXCEPT END; RegCl.CloseKey; RegCl.Free; SaveWndPosition(fmMsg, 'fmMsg'); end; //========================================================= //========================================================= {ПРИМЕНЕНИЕ ЯЗЫКА} //-------------------------------------------------------- procedure TfmMsg.ApplyLang; begin Caption := ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'fmMsg'); lbFixRegistryErrors.Caption := ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'fmMsg'); albLogoText.Caption := ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'Registry Cleaner'); gbErrorsToFixList.Caption := ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'gbErrorsToFixList'); GridFixErrorsList.ColumnHeaders.Strings[2] := ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'GridFixErrorsList_2'); GridFixErrorsList.ColumnHeaders.Strings[4] := ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'GridFixErrorsList_4'); GridFixErrorsList.ColumnHeaders.Strings[5] := ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'GridFixErrorsList_5'); gbLog.Caption := ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'gbLog'); GridLog.ColumnHeaders.Strings[1] := ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'GridLog_1'); GridLog.ColumnHeaders.Strings[2] := ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'GridLog_2'); btStart.Caption := ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'btClean'); btCancel.Caption := ReadLangStr('WinTuning_Common.lng', 'Common', 'Cancel'); end; //========================================================= //========================================================= {АКТИВАЦИЯ ФОРМЫ} //--------------------------------------------------------- procedure TfmMsg.FormActivate(Sender: TObject); begin if not isLoaded then RestoreWndPosition(fmMsg, 'fmMsg'); isLoaded := True; end; //========================================================= //========================================================= {СОЗДАНИЕ ФОРМЫ} //-------------------------------------------------------- procedure TfmMsg.FormCreate(Sender: TObject); var i: integer; begin isLoaded := False; // ДЕЛАЕМ ФОРМУ ОДИНАКОВОЙ ПО РАЗМЕРУ ПРИ РАЗЛИЧНЫХ РАСРЕШЕНИЯХ И РАЗМЕРАХ ШРИФТА scaled := True; Screen := TScreen.Create(nil); for i := componentCount - 1 downto 0 do with components[i] do begin if GetPropInfo(ClassInfo, 'font') <> nil then Font.Size := (ScreenWidth div screen.width) * Font.Size; end; //ЗАГРУЖАЕМ ГРАФИКУ LoadPNG2Prog('logo.dll', 'logo_wt_small', imgWinTuning); isReady := False; ApplyTheme; ApplyLang; LoadSections(); ThemeUpdateLeftIMG; // for i := 0 to fmDataMod.AlphaImgsSections16.Count-1 do AlphaImgsStatus16.AddImages(AlphaImgsSections16); fmDataMod.RegClean.RootKey := HKEY_CURRENT_USER; fmDataMod.RegClean.OpenKey('\Software\WinTuning\RegistryCleaner', True); if fmDataMod.RegClean.ValueExists('gbLog') then gbLog.Height := fmDataMod.RegClean.ReadInteger('gbLog'); end; //========================================================= end.
unit FormDataSet5b; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Grids, DBGrids, DB, DBClient, DSConnect, ExtCtrls, DBCtrls, StdCtrls, Mask, MasterForm, DBXCommon, DSClientProxy, DBXDBReaders, DBXJSON; type TFormDM5b = class(TFormMaster) DSProvDM5b: TDSProviderConnection; LCityTime: TLabel; LCDSCityTime: TLabel; BRegion: TButton; BCountry: TButton; BCity: TButton; BState: TButton; DBGrid2: TDBGrid; DBGrid3: TDBGrid; DBGrid4: TDBGrid; DBGrid5: TDBGrid; Button1: TButton; Button2: TButton; DSRegion: TDataSource; DSCountry: TDataSource; DSState: TDataSource; DSCity: TDataSource; CDSRegion: TClientDataSet; CDSCountry: TClientDataSet; CDSState: TClientDataSet; CDSCity: TClientDataSet; Label1: TLabel; procedure CDSCopyReconcileError(DataSet: TCustomClientDataSet; E: EReconcileError; UpdateKind: TUpdateKind; var Action: TReconcileAction); procedure BRegionClick(Sender: TObject); procedure BCountryClick(Sender: TObject); procedure BStateClick(Sender: TObject); procedure BCityClick(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private { Private declarations } public { Public declarations } procedure DoInit; override; procedure DoClose; override; procedure LinkAllDataSets; procedure UnLinkAllDataSets; end; var FormDM5b: TFormDM5b; implementation uses DMClient, RecError, LocationMigration, PerfCounter; {$R *.dfm} procedure TFormDM5b.BCityClick(Sender: TObject); var Cs: TDMDataSet5Client; Reader: TDBXReader; Counter: TPerfCounter; begin inherited; Cs := TDMDataSet5Client.Create(DMClientContainer.MyDSServer.DBXConnection, false); try Counter := TPerfCounter.Create; Counter.Start; // Execute process that you want to time: ... Reader := Cs.GetCity; Counter.Stop; LCityTime.Caption := 'Server Time:' + FloattoStr(Counter.TimingSeconds); Application.ProcessMessages; Counter.Start; CDSCity.DisableControls; if Assigned(Reader) then TDBXDataSetReader.CopyReaderToClientDataSet(Reader, CDSCity); CDSCity.EnableControls; Counter.Stop; DSCity.DataSet := CDSCity; LCDSCityTime.Caption := 'Client Time:' + FloattoStr(Counter.TimingSeconds); finally Cs.Free; end; end; procedure TFormDM5b.BCountryClick(Sender: TObject); var Cs: TDMDataSet5Client; Reader: TDBXReader; begin inherited; Cs := TDMDataSet5Client.Create(DMClientContainer.MyDSServer.DBXConnection, false); try Reader := Cs.GetCountry; if Assigned(Reader) then TDBXDataSetReader.CopyReaderToClientDataSet(Reader, CDSCountry); DSCountry.DataSet := CDSCountry; finally Cs.Free; end; end; procedure TFormDM5b.BRegionClick(Sender: TObject); var Cs: TDMDataSet5Client; Reader: TDBXReader; begin inherited; Cs := TDMDataSet5Client.Create(DMClientContainer.MyDSServer.DBXConnection, false); try Reader := Cs.GetRegion; if Assigned(Reader) then TDBXDataSetReader.CopyReaderToClientDataSet(Reader, CDSRegion); DSRegion.DataSet := CDSRegion; finally Cs.Free; end; end; procedure TFormDM5b.BStateClick(Sender: TObject); var Cs: TDMDataSet5Client; Reader: TDBXReader; begin inherited; Cs := TDMDataSet5Client.Create(DMClientContainer.MyDSServer.DBXConnection, false); try Reader := Cs.GetState; if Assigned(Reader) then TDBXDataSetReader.CopyReaderToClientDataSet(Reader, CDSState); DSState.DataSet := CDSState; finally Cs.Free; end; end; procedure TFormDM5b.Button1Click(Sender: TObject); begin inherited; LinkAllDataSets; end; procedure TFormDM5b.Button2Click(Sender: TObject); begin inherited; UnLinkAllDataSets; end; procedure TFormDM5b.CDSCopyReconcileError(DataSet: TCustomClientDataSet; E: EReconcileError; UpdateKind: TUpdateKind; var Action: TReconcileAction); begin HandleReconcileError(DataSet, UpdateKind, E); end; procedure TFormDM5b.DoClose; begin end; procedure TFormDM5b.doInit; begin end; procedure TFormDM5b.LinkAllDataSets; begin CDSCountry.IndexFieldNames := 'ID_REGION'; CDSCountry.MasterSource := DSRegion; CDSCountry.MasterFields := 'ID_REGION'; CDSState.IndexFieldNames := 'ID_COUNTRY'; CDSState.MasterSource := DSCountry; CDSState.MasterFields := 'ID_COUNTRY'; CDSCity.IndexFieldNames := 'ID_COUNTRY;ID_STATE'; CDSCity.MasterSource := DSState; CDSCity.MasterFields := 'ID_COUNTRY;ID_STATE'; end; procedure TFormDM5b.UnLinkAllDataSets; begin CDSCountry.MasterSource := nil; CDSCountry.MasterFields := EmptyStr; CDSCountry.IndexFieldNames := EmptyStr; CDSState.MasterSource := nil; CDSState.MasterFields := EmptyStr; CDSState.IndexFieldNames := EmptyStr; CDSCity.MasterSource := nil; CDSCity.MasterFields := EmptyStr; CDSCity.IndexFieldNames := EmptyStr; end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, SyntaxHighlighter, VirtualScrollingWinControl, SyntaxHighlightMemo, Math, Pascal, COW_RunTime, StrUtils, ComCtrls, TextEditorFooter; type TForm1 = class(TForm) SyntaxHighlightMemo1: TSyntaxHighlightMemo; SyntaxHighlighter1: TSyntaxHighlighter; TextEditorFooter1: TTextEditorFooter; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure SyntaxHighlighter1TokenizeLineClass(Sender: TObject; const LastLineClass: Byte; var NewLineClass: Byte; const TextBuffer: PAnsiChar; const TextLength: Integer); procedure SyntaxHighlighter1TokenizeLine(Sender: TObject; const LineClass: Byte; const TextBuffer: PAnsiChar; const TextLength: Integer; CharClass: PCharClassArray); private FPascalLexer:TDefaultLexer; public end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); begin FPascalLexer:=TDefaultLexer.Create(PascalLexerDefinition); // Création du lexer pour les éléments syntaxiques du Pascal end; procedure TForm1.FormDestroy(Sender: TObject); begin FPascalLexer.Destroy; // Libération de la mémoire occupée par la table du lexer end; procedure TForm1.SyntaxHighlighter1TokenizeLineClass(Sender: TObject; // Evénement appelé pour déterminer la classe d'une ligne. const LastLineClass: Byte; var NewLineClass: Byte; // Par exemple, LastLineClass vaut 2 si la ligne précédante contenait une const TextBuffer: PAnsiChar; const TextLength: Integer); // directive de précompilation non fermée. La valeur stockée dans var // NewLineClass servira pour la ligne d'après. Par convention, la première i:ICharBuffer; // ligne est de classe zéro. a:Integer; begin NewLineClass:=LastLineClass; if TextLength=0 then Exit; i:=TDefaultCharBuffer.Create(TextBuffer+#13); FPascalLexer.Init(i); // Initialisation du Lexer repeat // Tant qu'on n'est pas à la fin de la ligne case NewLineClass of // en fonction de la classe de la ligne d'avant 0:case FPascalLexer.GetNewLexem of // si on est dans le langage Pascal "normal" on extrait un nouveau lexème 3:NewLineClass:=1; // ...si c'est le début d'un bloc assembleur alors passage à la classe 1 11:NewLineClass:=2; // ... --- d'une directive de compilation --- 2 12:NewLineClass:=3; // ... --- d'un commentaire {} --- 3 13:NewLineClass:=4; // ... --- d'un commentaire (* *) --- 4 end; 1:begin // Si la ligne d'avant contenait un bloc asm non fermé a:=PosEx('end',TextBuffer,FPascalLexer.GetLastLexerPos); // on recherche le mot-clé "end" (A AMELIORER!) if a=0 then // S'il n'y est pas, pas la peine d'aller plus loin Break; NewLineClass:=0; // Sinon, passage à la classe 0 (Pascal standard) FPascalLexer.SetLastLexerPos(a+3); end; 2,3:begin // Si la ligne d'avant contenait une directive de compilation ou un commentaire {} non fermé a:=PosEx('}',TextBuffer,FPascalLexer.GetLastLexerPos); // on recherche la fin de la directive ou du commentaire : "}" if a=0 then // Idem Break; NewLineClass:=0; FPascalLexer.SetLastLexerPos(a+1); end; 4:begin // Si la ligne d'avant contenait un commentaire (* *) non fermé a:=PosEx('*)',TextBuffer,FPascalLexer.GetLastLexerPos); // on recherche la fin du commentaire : "*)" if a=0 then // Idem Break; NewLineClass:=0; FPascalLexer.SetLastLexerPos(a+2); end; end; until FPascalLexer.GetLexerPos>Cardinal(TextLength); i:=nil; // Libération de la mémoire via _Release implicite end; procedure TForm1.SyntaxHighlighter1TokenizeLine(Sender: TObject; // Evénement appelé pour déterminer la classe des caractères d'une ligne const LineClass: Byte; const TextBuffer: PAnsiChar; // Line Class contient la classe de la ligne précédante déterminée par const TextLength: Integer; CharClass: PCharClassArray); // l'événement ci-dessus var i:ICharBuffer; c,l:Byte; a:Integer; begin if TextLength=0 then Exit; i:=TDefaultCharBuffer.Create(TextBuffer+#13); FPascalLexer.Init(i); // Initialisation du Lexer l:=LineClass; repeat // Tant qu'on n'est pas à la fin de la ligne... case l of // En fonction de la classe courante... 0:begin // ...si on est dans du code Pascal, alors on extrait un lexème c:=FPascalLexer.GetNewLexem+1; case c of // En fonction de la valeur du lexème... 4:l:=1; // si c'est de l'assembleur passage à la classe assembleur 12:begin l:=2; // si c'est le début d'une directive de compilation changement de classe c:=10; // et changement du lexème pour avoir la bonne couleur end; 13:begin l:=3; // si c'est le début d'un commentaire { } alors changement de classe c:=11; // et changement du lexème pour avoir la bonne couleur end; 14:begin l:=4; // si c'est le début d'un commentaire (* *) alors changement de classe c:=11; // et changement du lexème pour avoir la bonne couleur end; 17:c:=0; // Lexème non reconnu, on le traite comme du texte normal end; a:=FPascalLexer.GetLexerPos-FPascalLexer.GetLastLexerPos; FillChar(CharClass[FPascalLexer.GetLastLexerPos-1],Min(a,TextLength-Integer(FPascalLexer.GetLastLexerPos)+1),c); // La classe des caractères end; // formant le lexème est définie 1:begin // Si on est dans un bloc asm a:=PosEx('end',TextBuffer,FPascalLexer.GetLastLexerPos); // on en cherche la fin if a=0 then a:=TextLength; // en on remplit la ligne avec la classe de caractères correspondante FillChar(CharClass[FPascalLexer.GetLastLexerPos-1],Min(a-Integer(FPascalLexer.GetLastLexerPos)+4,TextLength-Integer(FPascalLexer.GetLastLexerPos)+1),4); FPascalLexer.SetLastLexerPos(a+3); l:=0; end; 2:begin // Idem avec les directives de compilation a:=PosEx('}',TextBuffer,FPascalLexer.GetLastLexerPos); if a=0 then a:=TextLength; FillChar(CharClass[FPascalLexer.GetLastLexerPos-1],Min(a-Integer(FPascalLexer.GetLastLexerPos)+2,TextLength-Integer(FPascalLexer.GetLastLexerPos)+1),10); FPascalLexer.SetLastLexerPos(a+1); l:=0; end; 3:begin // Idem avec les commentaires { } a:=PosEx('}',TextBuffer,FPascalLexer.GetLastLexerPos); if a=0 then a:=TextLength; FillChar(CharClass[FPascalLexer.GetLastLexerPos-1],Min(a-Integer(FPascalLexer.GetLastLexerPos)+2,TextLength-Integer(FPascalLexer.GetLastLexerPos)+1),11); FPascalLexer.SetLastLexerPos(a+1); l:=0; end; 4:begin // Idem avec les commentaires (* *) a:=PosEx('*)',TextBuffer,FPascalLexer.GetLastLexerPos); if a=0 then a:=TextLength; FillChar(CharClass[FPascalLexer.GetLastLexerPos-1],Min(a-Integer(FPascalLexer.GetLastLexerPos)+3,TextLength-Integer(FPascalLexer.GetLastLexerPos)+1),11); FPascalLexer.SetLastLexerPos(a+2); l:=0; end; end; until FPascalLexer.GetLexerPos>Cardinal(TextLength); i:=nil; // Libération de la mémoire end; end.
(***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is TurboPower Async Professional * * The Initial Developer of the Original Code is * TurboPower Software * * Portions created by the Initial Developer are Copyright (C) 1991-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) {*********************************************************} {* EXCLNT1.PAS 4.06 *} {*********************************************************} {**********************Description************************} {* This client portion works with ExServer *} {* to implement a basic Winsock connection. *} {*********************************************************} {note: fill in wsAddress (property) in ApdWinsockPort1} {IP address} unit ExClnt1; interface uses WinTypes, WinProcs, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, AdPort, AdWnPort, AdWUtil, OoMisc; type TForm1 = class(TForm) ApdWinsockPort1: TApdWinsockPort; Button1: TButton; Label1: TLabel; Label2: TLabel; Label3: TLabel; procedure Button1Click(Sender: TObject); procedure ApdWinsockPort1WsConnect(Sender: TObject); procedure ApdWinsockPort1TriggerAvail(CP: TObject; Count: Word); procedure ApdWinsockPort1WsError(Sender: TObject; ErrCode: Integer); procedure ApdWinsockPort1WsDisconnect(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} procedure TForm1.Button1Click(Sender: TObject); {Connect button click - attempts to connect} begin ApdWinsockPort1.Open := not(ApdWinsockPort1.Open); if ApdWinsockPort1.Open then Label1.Caption := 'Attempting to connect'; end; procedure TForm1.ApdWinsockPort1WsConnect(Sender: TObject); {Event OnWsConnect -change Button1 after connected} begin Label1.Caption := 'Connected'; Button1.Caption := 'Disconnect'; ApdWinsockPort1.Output := 'Hello from Client'; end; procedure TForm1.ApdWinsockPort1TriggerAvail(CP: TObject; Count: Word); {Event OnTriggerAvail} var I : Word; begin for I := 1 to Count do Label2.Caption := Label2.Caption + ApdWinsockPort1.GetChar; end; procedure TForm1.ApdWinsockPort1WsError(Sender: TObject; ErrCode: Integer); {Event WsError - display error in Label3} begin Label1.Caption := 'Error...'; Label3.Caption := 'Code: ' + IntToStr(ErrCode); end; procedure TForm1.ApdWinsockPort1WsDisconnect(Sender: TObject); {Event WsDisconnect - Change Button1 back} begin Label1.Caption := ''; Label2.Caption := ''; Button1.Caption := 'Connect'; end; end.
unit UnitDirectXSlideShowCreator; interface uses Winapi.Windows, System.Classes, System.SysUtils, System.SyncObjs, System.Math, Vcl.Graphics, Vcl.Forms, Dmitry.Graphics.Utils, GraphicCrypt, uGraphicUtils, uMemory, uDXUtils, uConstants, uDBThread, uAssociations, uRAWImage, uJpegUtils, uBitmapUtils, uAnimatedJPEG, uProgramStatInfo, uPortableDeviceUtils, uSessionPasswords; type TDirectXSlideShowCreator = class(TDirectXSlideShowCreatorCustomThread) private { Private declarations } FInfo: TDirectXSlideShowCreatorInfo; FSynchBitmap: TBitmap; FBooleanParam: Boolean; FMonWidth, FMonHeight: Integer; protected function GetThreadID: string; override; procedure Execute; override; procedure ValidThread; procedure ActualThread; procedure SendImage(ImageToSend: TBitmap); procedure SendImageSynch; procedure ShowError(ErrorText: string); public constructor Create(Info: TDirectXSlideShowCreatorInfo); destructor Destroy; override; end; implementation uses DX_Alpha; constructor TDirectXSlideShowCreator.Create(Info: TDirectXSlideShowCreatorInfo); begin inherited Create(Info); FMonWidth := Info.Form.Width; FMonHeight := Info.Form.Height; FInfo := Info; FInfo.Manager.AddThread(Self); end; procedure TDirectXSlideShowCreator.ValidThread; begin FBooleanParam := TDirectShowForm(OwnerForm).IsValidThread(FInfo.SID); end; procedure TDirectXSlideShowCreator.ActualThread; begin FBooleanParam := TDirectShowForm(OwnerForm).IsActualThread(FInfo.SID); end; procedure TDirectXSlideShowCreator.SendImage(ImageToSend: TBitmap); var IsValid, IsActual: Boolean; begin repeat SynchronizeEx(ValidThread); IsValid := FBooleanParam; SynchronizeEx(ActualThread); IsActual := FBooleanParam; if not IsValid then Exit; if IsActual then Break; Sleep(10); until False; FSynchBitmap := ImageToSend; SynchronizeEx(SendImageSynch); end; procedure TDirectXSlideShowCreator.SendImageSynch; begin TDirectShowForm(OwnerForm).NewImage(FSynchBitmap); end; procedure TDirectXSlideShowCreator.ShowError(ErrorText: string); var ScreenImage: TBitmap; Text: string; R: TRect; begin ScreenImage := TBitmap.Create; try ScreenImage.Canvas.Pen.Color := 0; ScreenImage.Canvas.Brush.Color := 0; ScreenImage.Canvas.Font.Color := clWhite; ScreenImage.SetSize(FMonWidth, FMonHeight); Text := ErrorText; R := Rect(0, 0, FMonWidth, FMonHeight); ScreenImage.Canvas.TextRect(R, Text, [tfVerticalCenter, tfCenter]); FSynchBitmap := ScreenImage; SendImageSynch; finally F(ScreenImage); end; end; procedure TDirectXSlideShowCreator.Execute; var W, H: Integer; Zoom: Extended; Image, TempImage, ScreenImage: TBitmap; GraphicClass: TGraphicClass; FilePassword: string; Text_error_out: string; Graphic: TGraphic; begin inherited; FreeOnTerminate := True; Text_error_out := L('Unable to show file:'); try if not IsDevicePath(FInfo.FileName) and ValidCryptGraphicFile(FInfo.FileName) then begin FilePassword := SessionPasswords.FindForFile(FInfo.FileName); if FilePassword = '' then Exit; end; GraphicClass := TFileAssociations.Instance.GetGraphicClass(ExtractFileExt(FInfo.FileName)); if GraphicClass = nil then Exit; Graphic := GraphicClass.Create; try if not IsDevicePath(FInfo.FileName) and ValidCryptGraphicFile(FInfo.FileName) then begin F(Graphic); Graphic := DeCryptGraphicFile(FInfo.FileName, FilePassword, False); end else begin if Graphic is TRAWImage then TRAWImage(Graphic).IsPreview := True; if not IsDevicePath(FInfo.FileName) then Graphic.LoadFromFile(FInfo.FileName) else Graphic.LoadFromDevice(FInfo.FileName); end; case FInfo.Rotate and DB_IMAGE_ROTATE_MASK of DB_IMAGE_ROTATE_0, DB_IMAGE_ROTATE_180: JPEGScale(Graphic, FMonWidth, FMonHeight); DB_IMAGE_ROTATE_90, DB_IMAGE_ROTATE_270: JPEGScale(Graphic, FMonHeight, FMonWidth); end; //statistics if Graphic is TAnimatedJPEG then ProgramStatistics.Image3dUsed; Image := TBitmap.Create; try AssignGraphic(Image, Graphic); F(Graphic); ScreenImage := TBitmap.Create; try ScreenImage.Canvas.Pen.Color := 0; ScreenImage.Canvas.Brush.Color := 0; ScreenImage.SetSize(FMonWidth, FMonHeight); W := Image.Width; H := Image.Height; case FInfo.Rotate and DB_IMAGE_ROTATE_MASK of DB_IMAGE_ROTATE_0: begin ProportionalSize(FMonWidth, FMonHeight, W, H); if (Image.Width <> 0) and (Image.Height <> 0) then Zoom := Max(W / Image.Width, H / Image.Height) else Zoom := 1; if (Zoom < ZoomSmoothMin) then StretchCoolEx0(FMonWidth div 2 - W div 2, FMonHeight div 2 - H div 2, W, H, Image, ScreenImage, $000000) else begin XFillRect(FMonWidth div 2 - W div 2, FMonHeight div 2 - H div 2, W, H, ScreenImage, $000000); TempImage := TBitmap.Create; try TempImage.PixelFormat := pf24bit; TempImage.SetSize(W, H); SmoothResize(W, H, Image, TempImage); ThreadDraw(TempImage, ScreenImage, FMonWidth div 2 - W div 2, FMonHeight div 2 - H div 2); finally F(TempImage); end; end; end; DB_IMAGE_ROTATE_270: begin ProportionalSize(FMonHeight, FMonWidth, W, H); StretchCoolEx270(FMonWidth div 2 - H div 2, FMonHeight div 2 - W div 2, W, H, Image, ScreenImage, $000000) end; DB_IMAGE_ROTATE_90: begin ProportionalSize(FMonHeight, FMonWidth, W, H); StretchCoolEx90(FMonWidth div 2 - H div 2, FMonHeight div 2 - W div 2, W, H, Image, ScreenImage, $000000) end; DB_IMAGE_ROTATE_180: begin ProportionalSize(FMonWidth, FMonHeight, W, H); StretchCoolEx180(FMonWidth div 2 - W div 2, FMonHeight div 2 - H div 2, W, H, Image, ScreenImage, $000000) end; end; F(Image); SendImage(ScreenImage); finally F(ScreenImage); end; finally F(Image); end; finally F(Graphic); end; except on e: Exception do ShowError(e.Message); end; end; destructor TDirectXSlideShowCreator.Destroy; begin DirectXSlideShowCreatorManagers.RemoveThread(FInfo.Manager, Self); inherited; end; function TDirectXSlideShowCreator.GetThreadID: string; begin Result := 'Viewer'; end; end.
unit frm_SearchPhrase; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, EasyTaskPanelForm, StdCtrls, MPCommonObjects, EasyListview, ExtCtrls, ComCtrls, ShellCtrls, Mask, JvExMask, JvToolEdit, Buttons; type TfrmSearchPhrase = class(TEasyTaskPanelForm) reText: TRichEdit; cbCaseSens: TCheckBox; cbUseMask: TCheckBox; btnMaskHelp: TSpeedButton; Panel1: TPanel; Panel2: TPanel; procedure EasyTaskPanelFormCreate(Sender: TObject); procedure reTextChange(Sender: TObject); procedure cbCaseSensClick(Sender: TObject); procedure cbUseMaskClick(Sender: TObject); procedure EasyTaskPanelFormShow(Sender: TObject); private LastText: string; public { Public declarations } end; var frmSearchPhrase: TfrmSearchPhrase; implementation uses frm_Main; {$R *.dfm} procedure TfrmSearchPhrase.EasyTaskPanelFormCreate(Sender: TObject); begin frmSearchPhrase := Self; end; procedure TfrmSearchPhrase.reTextChange(Sender: TObject); var n, v, u: Integer; isMsk: Boolean; const chrs = ['?', '#', '$', '%', '@', '*', '^', '|', '_']; begin if not frmMain.IsLoaded then Exit; frmMain.ControlChanged(Sender); try if reText.Text = LastText then Exit; reText.Enabled := False; v := reText.SelStart; u := reText.SelLength; isMsk := False; for n := 1 to Length(reText.Text) do if reText.Text[n] in chrs then isMsk := True; reText.SelStart := 0; reText.SelLength := Length(reText.Text); reText.SelAttributes.Color := clBlack; //reText.SelAttributes.Style := []; if isMsk then for n := 1 to Length(reText.Text) do begin reText.SelStart := n-1; reText.SelLength := 1; if (reText.Text[n] in chrs) and (cbUseMask.Checked) then begin reText.SelAttributes.Color := clRed; // reText.SelAttributes.Style := [fsBold]; end; end; LastText := reText.Text; reText.SelStart := v; reText.SelLength := u; reText.Enabled := True; reText.SetFocus; except end; end; procedure TfrmSearchPhrase.cbCaseSensClick(Sender: TObject); begin frmMain.ControlChanged(Sender); end; procedure TfrmSearchPhrase.cbUseMaskClick(Sender: TObject); begin LastText := ''; reTextChange(Sender); end; procedure TfrmSearchPhrase.EasyTaskPanelFormShow(Sender: TObject); begin LastText := ''; reTextChange(Sender); end; end.
unit Nullpobug.Marubatsu; interface uses System.SysUtils ; type EStateError = class(Exception); EAleadyFilled = class(Exception); EInvalidDiagonaltype = class(Exception); EInvalidPlayerType = class(Exception); // ゲームのプレイヤータイプ TGamePlayerType = (gptPlayer, gptCPU); // ゲームの勝者 TGameWinner = (gwNone, gwPlayer, gwCPU); // ゲームの進行状態 TGameState = (gsInit, gsPlayerTurn, gsCPUTurn, gsEnd); // マス目の状態 TCellState = (csEmpty, csPlayer, csCPU); // 対角線の種類(\, /) TDiagonalType = (dtBackSlash, dtSlash); TGameTable = class private FCells: array [0..2, 0..2] of TCellState; public constructor Create; function GetCell(X, Y: Integer): TCellState; procedure SetCell(X, Y: Integer; State: TCellState); function IsFilledRow(X: Integer; State: TCellState): Boolean; function IsFilledCol(Y: Integer; State: TCellState): Boolean; function IsFilledDiagonal(DiagonalType: TDiagonalType; State: TCellState): Boolean; function GetWidth: Integer; function GetHeight: Integer; property Cell[X, Y: Integer]: TCellState read GetCell write SetCell; default; property Width: Integer read GetWidth; property Height: Integer read GetHeight; end; TGame = class private FState: TGameState; FTable: TGameTable; FWinner: TGameWinner; public constructor Create; destructor Destroy; override; procedure Start; overload; procedure Start(Starter: TGamePlayerType); overload; procedure Put(X, Y: Integer; Player: TGamePlayerType); procedure DetermineWinner; procedure UpdateState(NextPlayer: TGamePlayerType); procedure Finish(Winner: TGameWinner); property State: TGameState read FState; property Table: TGameTable read FTable; property Winner: TGameWinner read FWinner; end; function PlayerTypeToCellState(PlayerType: TGamePlayerType): TCellState; function PlayerTypeToWinner(PlayerType: TGamePlayerType): TGameWinner; implementation (* TGameTable *) constructor TGameTable.Create; var X, Y: Integer; begin // 盤面を空に設定する for X := Low(FCells) to High(FCells) do for Y := Low(FCells[X]) to High(FCells[X]) do FCells[X][Y] := csEmpty; end; function TGameTable.GetCell(X, Y: Integer): TCellState; (* 指定した位置のマス目の値を返す *) begin Result := FCells[X][Y]; end; procedure TGameTable.SetCell(X, Y: Integer; State: TCellState); (* 指定した位置のマス目の値を変更する *) begin FCells[X][Y] := State; end; function TGameTable.IsFilledRow(X: Integer; State: TCellState): Boolean; (* 指定した行がすべて同じ状態ならTrueを返す *) var Y: Integer; begin Result := True; for Y := Low(FCells[X]) to High(FCells[X]) do // 一つでも違う場合はFalseを返す if FCells[X][Y] <> State then begin Result := False; Exit; end; end; function TGameTable.IsFilledCol(Y: Integer; State: TCellState): Boolean; (* 指定した列がすべて同じ状態ならTrueを返す *) var X: Integer; begin Result := True; for X := Low(FCells) to High(FCells) do // 一つでも違う場合はFalseを返す if FCells[X][Y] <> State then begin Result := False; Exit; end; end; function TGameTable.IsFilledDiagonal(DiagonalType: TDiagonalType; State: TCellState): Boolean; (* 指定した斜めの値がすべて同じならTrueを返す *) var X, Y: Integer; begin Result := True; for X := Low(FCells) to High(FCells) do begin case DiagonalType of dtBackSlash: // \の判定 Y := X; dtSlash: // /の判定 Y := 2 - X; else raise EInvalidDiagonaltype.Create('Invalid diagonal type.'); end; if FCells[X][Y] <> State then begin Result := False; Exit; end; end; end; function TGameTable.GetWidth: Integer; (* テーブルの幅を返す *) begin Result := High(FCells) + 1; end; function TGameTable.GetHeight: Integer; (* テーブルの高さを返す *) begin Result := High(FCells[0]) + 1; end; (* end of TGameTable *) (* TGame *) constructor TGame.Create; (* コンストラクタ *) begin // ゲームの初期化 FState := gsInit; FTable := TGameTable.Create; FWinner := gwNone; end; destructor TGame.Destroy; begin FTable.Free; inherited Destroy; end; procedure TGame.Start; (* ゲームを開始する *) var Starter: TGamePlayerType; begin // ランダムで開始プレイヤーを決める Starter := TGamePlayerType(Random(Integer(High(TGamePlayerType)))); // プレイヤーを指定して開始 Start(Starter); end; procedure TGame.Start(Starter: TGamePlayerType); (* 開始プレイヤーを指定してゲームを開始する *) begin if State <> gsInit then raise EStateError.Create('Invalid state.'); UpdateState(Starter); end; procedure TGame.Put(X, Y: Integer; Player: TGamePlayerType); (* マルバツを置く *) begin // 対象のマス目が空でなければエラー if FTable[X, Y] <> csEmpty then raise EAleadyFilled.CreateFmt('(%d, %d) is already filled.', [X, Y]); case Player of gptPlayer: FTable[X, Y] := csPlayer; gptCPU: FTable[X, Y] := csCPU; end; end; procedure TGame.DetermineWinner; (* 勝敗の判定 縦、横、斜めのうちどれかが揃っていたら勝者を更新する *) var X, Y: Integer; DiagonalType: TDiagonalType; PlayerType: TGamePlayerType; begin for PlayerType in [gptPlayer, gptCPU] do begin // 横が揃っているかを判定 for Y := 0 to FTable.Height - 1 do if FTable.IsFilledRow(Y, PlayerTypeToCellState(PlayerType)) then begin // 揃っていたら勝者を設定して終了 Finish(PlayerTypeToWinner(PlayerType)); Exit; end; // 縦が揃っているかを判定 for X := 0 to FTable.Height - 1 do if FTable.IsFilledCol(X, PlayerTypeToCellState(PlayerType)) then begin // 揃っていたら勝者を設定して終了 Finish(PlayerTypeToWinner(PlayerType)); Exit; end; // 斜めが揃っているかを判定 for DiagonalType in [dtBackSlash, dtSlash] do if FTable.IsFilledDiagonal(DiagonalType, PlayerTypeToCellState(PlayerType)) then begin // 揃っていたら勝者を設定して終了 Finish(PlayerTypeToWinner(PlayerType)); Exit; end; end; end; procedure TGame.UpdateState(NextPlayer: TGamePlayerType); (* ゲームの状態を更新 NextPlayer: 次のプレイヤー *) begin // 終了している場合は何もしない if FState = gsEnd then Exit; // 勝敗を判定する DetermineWinner; // 勝者が確定しているなら終了する if FWinner <> gwNone then Exit; // 次のプレイヤーの状態に変更する case NextPlayer of gptPlayer: FState := gsPlayerTurn; gptCPU: FState := gsCPUTurn; end; end; procedure TGame.Finish(Winner: TGameWinner); (* 勝者を設定してゲームを終了状態にする *) begin FWinner := Winner; FState := gsEnd; end; (* end of TGame *) function PlayerTypeToCellState(PlayerType: TGamePlayerType): TCellState; (* TGamePlayerTypeに対応するTCellStateを返す *) begin case PlayerType of gptPlayer: Result := csPlayer; gptCPU: Result := csCPU; else raise EInvalidPlayerType.Create('Invalid player type.'); end; end; function PlayerTypeToWinner(PlayerType: TGamePlayerType): TGameWinner; (* TGamePlayerTypeに対応するTGameWinnerを返す *) begin case PlayerType of gptPlayer: Result := gwPlayer; gptCPU: Result := gwCPU; else raise EInvalidPlayerType.Create('Invalid player type.'); end; end; end.
unit uFrmEstimatedNew; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, PaideTodosGeral, siComp, siLangRT, StdCtrls, Buttons, ExtCtrls, DateBox, Mask, PowerADOQuery, ADODB, SuperComboADO, DB; type TFrmEstimatedNew = class(TFrmParentAll) btOK: TButton; Label4: TLabel; scStore: TSuperComboADO; Label1: TLabel; scCustomer: TSuperComboADO; Label3: TLabel; memOBS: TMemo; Label2: TLabel; memOBS2: TMemo; Label5: TLabel; lbAgent: TLabel; edtAgent: TEdit; btnNewAgent: TSpeedButton; btnOpenAgent: TSpeedButton; btnDelAgent: TSpeedButton; quDescTourist: TADOQuery; quDescTouristTipTouristGroup: TStringField; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btOKClick(Sender: TObject); procedure btnNewAgentClick(Sender: TObject); procedure btnDelAgentClick(Sender: TObject); procedure btnOpenAgentClick(Sender: TObject); private FDataSet: TPowerADOQuery; FIsInc: Boolean; FIDTrourGroup : Integer; procedure SetCaptionForm; procedure LoadValues; procedure SetLockedFields; procedure CreateEstimated; procedure UpdateEstimated; procedure RefreshTourGroup; public function Start(ADataSet: TPowerADOQuery; AIsInc: Boolean): Boolean; end; implementation uses uDM, uSystemConst, uDMGlobal, uMsgBox, uMsgConstant, uFrmChangeTourGroup, uFchTouristGroup, uSystemTypes; {$R *.dfm} { TFrmEstimatedNew } function TFrmEstimatedNew.Start(ADataSet: TPowerADOQuery; AIsInc: Boolean): Boolean; begin FDataSet := ADataSet; FIsInc := AIsInc; FIDTrourGroup := 0; SetCaptionForm; LoadValues; SetLockedFields; RefreshTourGroup; ShowModal; Result := (ModalResult = mrOK); end; procedure TFrmEstimatedNew.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; Action := caFree; end; procedure TFrmEstimatedNew.CreateEstimated; var IDEstimated: Integer; sIDCustomer: String; sTourGroup : String; begin inherited; if scCustomer.LookUpValue = '' then sIDCustomer := 'Null' else sIDCustomer := scCustomer.LookUpValue; if FIDTrourGroup = 0 then sTourGroup := 'Null' else sTourGroup := IntToStr(FIDTrourGroup); IDEstimated := DM.GetNextID(MR_INV_ESTIMATED_ID); with DM.quFreeSQL do begin if Active then Close; SQL.Clear; SQL.Add('INSERT INTO Estimated (IDEstimated, IDPessoa, IDUser, IDStore, EstimatedDate, OBS, OBS2, IDTouristGroup)'); SQL.Add('VALUES (' + IntToStr(IDEstimated) + ',' + sIDCustomer + ',' + IntTostr(DM.fUser.ID) + ','); SQL.Add(scStore.LookUpValue + ', GetDate(),' + QuotedStr(memOBS.Text) + ',' + QuotedStr(memOBS2.Text) + ',' + sTourGroup + ')'); ExecSQL; end; end; procedure TFrmEstimatedNew.btOKClick(Sender: TObject); begin if scStore.LookUpValue = '' then begin MsgBox(MSG_CRT_NO_STORE_SELECTED, vbInformation + vbOKOnly); ModalResult := mrNone; Exit; end; if FIsInc then CreateEstimated else UpdateEstimated; inherited; end; procedure TFrmEstimatedNew.UpdateEstimated; var sIDStore: String; sIDCustomer: String; sTourGroup : String; begin sIDStore := scStore.LookUpValue; if scCustomer.LookUpValue = '' then sIDCustomer := 'Null' else sIDCustomer := scCustomer.LookUpValue; if FIDTrourGroup = 0 then sTourGroup := 'Null' else sTourGroup := IntToStr(FIDTrourGroup); with DM.quFreeSQL do begin if Active then Close; SQL.Clear; SQL.Add('UPDATE Estimated'); SQL.Add('SET IDStore = ' + sIDStore + ', IDPessoa = ' + sIDCustomer); SQL.Add(', OBS = ' + QuotedStr(memOBS.Text) + ', OBS2 = ' + QuotedStr(memOBS2.Text)); SQL.Add(', IDTouristGroup = ' + sTourGroup); SQL.Add('WHERE IDEstimated = ' + FDataSet.FieldByName('IDEstimated').AsString); ExecSQL; end; end; procedure TFrmEstimatedNew.LoadValues; begin if FIsInc then scStore.LookUpValue := IntToStr(DM.fStore.ID) else begin scStore.LookUpValue := FDataSet.FieldByName('IDStore').AsString; scCustomer.LookUpValue := FDataSet.FieldByName('IDPessoa').AsString; memOBS.Text := FDataSet.FieldByName('OBS').AsString; memOBS2.Text := FDataSet.FieldByName('OBS2').AsString; FIDTrourGroup := FDataSet.FieldByName('IDTouristGroup').AsInteger; end; end; procedure TFrmEstimatedNew.SetLockedFields; begin if (not FIsInc) and (not FDataSet.FieldByName('IDPreSale').IsNull) then begin scStore.Enabled := False; scStore.ParentColor := True; scCustomer.Enabled := False; scCustomer.ParentColor := True; memOBS.Enabled := False; memOBS.ParentColor := True; memOBS2.Enabled := False; memOBS2.ParentColor := True; btnNewAgent.Enabled := False; btnOpenAgent.Enabled := False; btnDelAgent.Enabled := False; end; end; procedure TFrmEstimatedNew.SetCaptionForm; begin case DMGlobal.IDLanguage of LANG_ENGLISH: if FIsInc then Self.Caption := 'New Budget' else Self.Caption := 'Update Budget'; LANG_PORTUGUESE: if FIsInc then Self.Caption := 'Novo Orçamento' else Self.Caption := 'Alterar Orçamento'; LANG_SPANISH: if FIsInc then Self.Caption := 'Nuevo Presupuesto' else Self.Caption := 'Alterar Presupuesto'; end; end; procedure TFrmEstimatedNew.RefreshTourGroup; begin if FIDTrourGroup = 0 then edtAgent.Clear else with quDescTourist do try if Active then Close; Parameters.ParambyName('IDTouristGroup').Value := FIDTrourGroup; Open; edtAgent.Text := quDescTouristTipTouristGroup.AsString; finally Close; end; end; procedure TFrmEstimatedNew.btnNewAgentClick(Sender: TObject); var NewTourGroup: Integer; begin inherited; with TFrmChangeTourGroup.Create(Self) do NewTourGroup := Start; if NewTourGroup >= 0 then FIDTrourGroup := NewTourGroup; RefreshTourGroup; end; procedure TFrmEstimatedNew.btnDelAgentClick(Sender: TObject); begin inherited; FIDTrourGroup := 0; RefreshTourGroup; end; procedure TFrmEstimatedNew.btnOpenAgentClick(Sender: TObject); var PosID1, PosID2 : String; begin inherited; PosID1 := IntToStr(FIDTrourGroup); with TFchTouristGroup.Create(self) do begin Start(btAlt, nil, False, PosID1, PosID2, nil); Free; end; RefreshTourGroup; end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [ECF_IMPRESSORA] The MIT License Copyright: Copyright (C) 2014 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit EcfImpressoraVO; {$mode objfpc}{$H+} interface uses VO, Classes, SysUtils, FGL; type TEcfImpressoraVO = class(TVO) private FID: Integer; FNUMERO: Integer; FCODIGO: String; FSERIE: String; FIDENTIFICACAO: String; FMC: String; FMD: String; FVR: String; FTIPO: String; FMARCA: String; FMODELO: String; FMODELO_ACBR: String; FMODELO_DOCUMENTO_FISCAL: String; FVERSAO: String; FLE: String; FLEF: String; FMFD: String; FLACRE_NA_MFD: String; FDATA_INSTALACAO_SB: TDateTime; FHORA_INSTALACAO_SB: String; FDOCTO: String; FECF_IMPRESSORA: String; published property Id: Integer read FID write FID; property Numero: Integer read FNUMERO write FNUMERO; property Codigo: String read FCODIGO write FCODIGO; property Serie: String read FSERIE write FSERIE; property Identificacao: String read FIDENTIFICACAO write FIDENTIFICACAO; property Mc: String read FMC write FMC; property Md: String read FMD write FMD; property Vr: String read FVR write FVR; property Tipo: String read FTIPO write FTIPO; property Marca: String read FMARCA write FMARCA; property Modelo: String read FMODELO write FMODELO; property ModeloAcbr: String read FMODELO_ACBR write FMODELO_ACBR; property ModeloDocumentoFiscal: String read FMODELO_DOCUMENTO_FISCAL write FMODELO_DOCUMENTO_FISCAL; property Versao: String read FVERSAO write FVERSAO; property Le: String read FLE write FLE; property Lef: String read FLEF write FLEF; property Mfd: String read FMFD write FMFD; property LacreNaMfd: String read FLACRE_NA_MFD write FLACRE_NA_MFD; property DataInstalacaoSb: TDateTime read FDATA_INSTALACAO_SB write FDATA_INSTALACAO_SB; property HoraInstalacaoSb: String read FHORA_INSTALACAO_SB write FHORA_INSTALACAO_SB; property Docto: String read FDOCTO write FDOCTO; property EcfImpressora: String read FECF_IMPRESSORA write FECF_IMPRESSORA; end; TListaEcfImpressoraVO = specialize TFPGObjectList<TEcfImpressoraVO>; implementation initialization Classes.RegisterClass(TEcfImpressoraVO); finalization Classes.UnRegisterClass(TEcfImpressoraVO); end.
unit UnitSetWGAttr; // 欢乐幻灵·创招设置 interface uses Windows, Messages, SysUtils, Classes, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Math, frmTemplate; type TFormSetWGAttr = class(TfTemplate) GroupBox1: TGroupBox; Label7: TLabel; EditWGName: TEdit; Label10: TLabel; Label11: TLabel; Label12: TLabel; Label8: TLabel; Label9: TLabel; EditWGXS: TEdit; EditWGNL: TEdit; ComboBoxWGQS: TComboBox; ComboBoxWGGJ: TComboBox; ComboBoxWGBZ: TComboBox; gbGJConfig: TGroupBox; Label55: TLabel; Label56: TLabel; ComboBoxGJRank: TComboBox; ComboBoxGJLevel: TComboBox; Bevel1: TBevel; GroupBox14: TGroupBox; Label53: TLabel; Label14: TLabel; Label1: TLabel; CheckBoxAutoDeleteWG: TCheckBox; ComboBoxDeleteFromPos: TComboBox; CheckBoxRemainEasyWG: TCheckBox; CheckBoxLevelLimit: TCheckBox; EditLevelLimited: TEdit; CheckBoxDoFateCreateWG: TCheckBox; CheckBoxRemainXS: TCheckBox; EditRemainedXS: TEdit; procedure EditWGXSKeyPress(Sender: TObject; var Key: Char); procedure EditWGNLKeyPress(Sender: TObject; var Key: Char); procedure ComboBoxGJRankChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure SetFateEnableOrNot; procedure CheckBoxDoFateCreateWGClick(Sender: TObject); procedure CheckBoxRemainXSClick(Sender: TObject); procedure CheckBoxRemainEasyWGClick(Sender: TObject); procedure CheckBoxAutoDeleteWGClick(Sender: TObject); procedure CheckBoxLevelLimitClick(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } procedure LoadAttribute; procedure SaveAttribute; public { Public declarations } procedure DisableCreateWGObjs; procedure EnableCreateWGObjs; procedure SetCreateWGObjsEnabled(isEnable: Boolean); end; var FormSetWGAttr: TFormSetWGAttr; implementation uses IniFiles, ClsGames, UnitTypesAndVars, UnitGlobal, UnitClasses, UnitConsts; {$R *.dfm} procedure TFormSetWGAttr.EditWGXSKeyPress(Sender: TObject; var Key: Char); // 限制系数输入 begin if ((Key < '0') or (Key > '9')) and (Key <> '.') and (Key <> Chr(8)) and (Key <> Chr(13)) then begin ShowMessage('Error: Must be a number'); Key := Chr(0); end; end; procedure TFormSetWGAttr.EditWGNLKeyPress(Sender: TObject; var Key: Char); // 限制内力输入 begin if ((Key < '0') or (Key > '9')) and (Key <> Chr(8)) and (Key <> Chr(13)) then begin ShowMessage('Error: Must be a number'); Key := Chr(0); end; end; procedure TFormSetWGAttr.ComboBoxGJRankChange(Sender: TObject); // 设置过节队列 var i: integer; begin ComboBoxGJLevel.Clear; // 清除过节队列 case ComboBoxGJRank.ItemIndex of 0, 1, 4, 5: // 2、3转:地仙、天仙、夜叉、修罗 for i := 1 to 12 do ComboBoxGJLevel.Items.Add(inttostr(i * 100 - 1)); 2, 7: // 4转:大罗、魔神 for i := 1 to 13 do ComboBoxGJLevel.Items.Add(IntToStr(i * 100 - 1)); 3, 8: // 5转:天神、魔尊 for i := 1 to 4 do ComboBoxGJLevel.Items.Add(IntToStr(i * 300 - 1)); end; end; procedure TFormSetWGAttr.FormCreate(Sender: TObject); var i: integer; begin // 设置窗体位置 self.CFormName := IDS_WGAttrFormName; inherited; // 装载属性 LoadAttribute; ThisUser.GetWGs; // 获取武功信息 ComboBoxDeleteFromPos.Clear; // 清除删招点列表 for i := 0 to ThisUser.WGCountLimit - 1 do // 根据级别限制招数最大数 ComboBoxDeleteFromPos.Items.Add(inttostr(i + 1)); // 设置默认删招点 ComboBoxDeleteFromPos.ItemIndex := ComboBoxDeleteFromPos.Items.Count - 1; end; procedure TFormSetWGAttr.FormShow(Sender: TObject); begin Caption := '创招设置·' + HLInfoList.GlobalHL.UserName; SetFateEnableOrNot; //隐藏系数识别 CheckBoxRemainXS.Visible := False; EditRemainedXS.Visible := False; Label1.Visible := False; end; procedure TFormSetWGAttr.SetFateEnableOrNot; // 启用/关闭过节创招设置 var i: integer; begin // 启用/禁止过节设置部分 for i := 0 to gbGJConfig.ControlCount - 1 do gbGJConfig.Controls[i].Enabled := CheckBoxDoFateCreateWG.Checked; // 如果关闭过节设置,恢复默认过节参数 if not CheckBoxDoFateCreateWG.Checked then begin ComboBoxGJRank.ItemIndex := -1; ComboBoxGJLevel.ItemIndex := -1; end; end; procedure TFormSetWGAttr.CheckBoxDoFateCreateWGClick(Sender: TObject); // 过节创招 begin SetFateEnableOrNot; // 启用/关闭过节创招设置 if not CheckBoxDoFateCreateWG.Checked then exit; // 不是过节创招则退出 ThisUser.GetAttr; // 获得人物属性 // 设置人物过节转数 if ThisUser.Xianmo = UserAttrXian then // 仙 ComboBoxGJRank.ItemIndex := ThisUser.Rank - 2 else if ThisUser.Xianmo = UserAttrMo then // 魔 ComboBoxGJRank.ItemIndex := ThisUser.Rank + 2 else begin // 凡人、散仙 ComboBoxGJRank.ItemIndex := -1; CheckBoxDoFateCreateWG.Checked := False; SetFateEnableOrNot; exit; end; // 人物转数切换,刷新过节等级队列 ComboBoxGJRankChange(Sender); // 设置人物过节等级 if ThisUser.Rank <> 5 then ComboBoxGJLevel.ItemIndex := Floor((ThisUser.Level + 1) / 100) - 1 else ComboBoxGJLevel.ItemIndex := Floor((ThisUser.Level + 1) / 300) - 1; end; procedure TFormSetWGAttr.CheckBoxRemainXSClick(Sender: TObject); // 选择保留高系数招 // *******已经失效********** begin if CheckBoxRemainXS.Checked then CheckBoxRemainEasyWG.Checked:=False; EditRemainedXS.Enabled:=CheckBoxRemainXS.Checked; end; procedure TFormSetWGAttr.CheckBoxRemainEasyWGClick(Sender: TObject); // 选择保留容易招,设置相应状态(已经失效) begin if CheckBoxRemainEasyWG.Checked then CheckBoxRemainXS.Checked := False; EditRemainedXS.Enabled := CheckBoxRemainXS.Checked; Label1.Enabled := CheckBoxRemainXS.Checked; end; procedure TFormSetWGAttr.CheckBoxAutoDeleteWGClick(Sender: TObject); // 选择自动删招 begin ComboBoxDeleteFromPos.Enabled := CheckBoxAutoDeleteWG.Checked; CheckBoxRemainEasyWG.Enabled := CheckBoxAutoDeleteWG.Checked; CheckBoxRemainXS.Enabled := CheckBoxAutoDeleteWG.Checked; EditRemainedXS.Enabled := CheckBoxAutoDeleteWG.Checked and CheckBoxRemainXS.Checked; Label1.Enabled := CheckBoxAutoDeleteWG.Checked and CheckBoxRemainXS.Checked; end; procedure TFormSetWGAttr.DisableCreateWGObjs; begin SetCreateWGObjsEnabled(False); end; procedure TFormSetWGAttr.EnableCreateWGObjs; begin SetCreateWGObjsEnabled(True); ComboBoxDeleteFromPos.Enabled := CheckBoxAutoDeleteWG.Checked; CheckBoxRemainEasyWG.Enabled := CheckBoxAutoDeleteWG.Checked; CheckBoxRemainXS.Enabled := CheckBoxAutoDeleteWG.Checked; EditRemainedXS.Enabled := CheckBoxAutoDeleteWG.Checked and CheckBoxRemainXS.Checked; Label1.Enabled := CheckBoxAutoDeleteWG.Checked; EditLevelLimited.Enabled := CheckBoxLevelLimit.Checked; ComboBoxGJRank.Enabled := CheckBoxDoFateCreateWG.Checked; ComboBoxGJLevel.Enabled := CheckBoxDoFateCreateWG.Checked; end; procedure TFormSetWGAttr.SetCreateWGObjsEnabled(isEnable: Boolean); //设置那些组件是Enable,还是Disable begin EditWGName.Enabled := isEnable; EditWGXS.Enabled := isEnable; EditWGNL.Enabled := isEnable; ComboBoxWGQS.Enabled := isEnable; ComboBoxWGGJ.Enabled := isEnable; ComboBoxWGBZ.Enabled := isEnable; EditLevelLimited.Enabled := isEnable; Label14.Enabled := isEnable; CheckBoxLevelLimit.Enabled := isEnable; CheckBoxAutoDeleteWG.Enabled := isEnable; CheckBoxDoFateCreateWG.Enabled := isEnable; CheckBoxRemainEasyWG.Enabled := isEnable; CheckBoxRemainXS.Enabled := isEnable; ComboBoxDeleteFromPos.Enabled := isEnable; Label53.Enabled := isEnable; EditRemainedXS.Enabled := isEnable; Label1.Enabled := isEnable; ComboBoxGJRank.Enabled := isEnable; ComboBoxGJLevel.Enabled := isEnable; end; procedure TFormSetWGAttr.CheckBoxLevelLimitClick(Sender: TObject); // 选择停止创招等级 begin EditLevelLimited.Enabled := CheckBoxLevelLimit.Checked; end; procedure TFormSetWGAttr.LoadAttribute; // 装载属性 var iTmp: Integer; fTmp: Currency; begin with TIniFile.Create(IDS_UsersPath + HLInfoList.GlobalHL.UserName + '.Ini') do // 创招 try // 设置武功名称 self.EditWGName.Text := ReadString(IDS_WGAttrFormName, IDS_WG_Name, IDS_WG_NameDef); // 设置武功系数 fTmp := ReadFloat(IDS_WGAttrFormName, IDS_WG_XiShu, 1); if (fTmp <= 0) or (fTmp > 2) then fTmp := 1; EditWGXS.Text := FloatToStr(fTmp); // 设置武功内力 iTmp := ReadInteger(IDS_WGAttrFormName, IDS_WG_NeiLi, 100); EditWGNL.Text := IntToStr(iTmp); // 设置武功样式 iTmp := ReadInteger(IDS_WGAttrFormName, IDS_WG_ZiShi, 0); if (iTmp < 0) or (iTmp >= ComboBoxWGQS.Items.Count) then iTmp := 0; ComboBoxWGQS.ItemIndex := iTmp; iTmp := ReadInteger(IDS_WGAttrFormName, IDS_WG_GuiJi, 0); if (iTmp < 0) or (iTmp >= ComboBoxWGGJ.Items.Count) then iTmp := 0; ComboBoxWGGJ.ItemIndex := iTmp; iTmp := ReadInteger(IDS_WGAttrFormName, IDS_WG_BaoZha, 0); if (iTmp < 0) or (iTmp >= ComboBoxWGBZ.Items.Count) then iTmp := 0; ComboBoxWGBZ.ItemIndex := iTmp; finally Free; end; end; procedure TFormSetWGAttr.SaveAttribute; // 保存属性 begin with TIniFile.Create(IDS_UsersPath + HLInfoList.GlobalHL.UserName + '.Ini') do // 创招 try // 保存武功名称 WriteString(IDS_WGAttrFormName, IDS_WG_Name, self.EditWGName.Text); // 保存武功系数 WriteFloat(IDS_WGAttrFormName, IDS_WG_XiShu, StrToFloatDef(EditWGXS.Text, 1)); // 保存武功内力 WriteInteger(IDS_WGAttrFormName, IDS_WG_NeiLi, StrToIntDef(EditWGNL.Text, 100)); // 保存武功样式 WriteInteger(IDS_WGAttrFormName, IDS_WG_ZiShi, ComboBoxWGQS.ItemIndex); WriteInteger(IDS_WGAttrFormName, IDS_WG_GuiJi, ComboBoxWGGJ.ItemIndex); WriteInteger(IDS_WGAttrFormName, IDS_WG_BaoZha, ComboBoxWGBZ.ItemIndex); finally free; end; end; procedure TFormSetWGAttr.FormDestroy(Sender: TObject); begin // 保存属性 SaveAttribute; // 保存窗体位置 inherited; end; end.
namespace proholz.xsdparser; interface type XsdAttributeGroupVisitor = public class(XsdAnnotatedElementsVisitor) private // * // * The {@link XsdAttributeGroup} instance which owns this {@link XsdAttributeGroupVisitor} instance. This way this // * visitor instance can perform changes in the {@link XsdAttributeGroup} object. // // var owner: XsdAttributeGroup; public constructor(aowner: XsdAttributeGroup); method visit(element: XsdAttribute); override; end; implementation constructor XsdAttributeGroupVisitor(aowner: XsdAttributeGroup); begin inherited constructor(aowner); self.owner := aowner; end; method XsdAttributeGroupVisitor.visit(element: XsdAttribute); begin inherited visit(element); owner.addAttribute(ReferenceBase.createFromXsd(element)); end; end.
{Ingresar una matriz de MxN de enteros, escribir: a. Los elementos junto con la fila cuya suma de componentes sea la mayor. b. Los elementos junto con la columna cuya suma de componentes sea la menor. c- El minimo elemento de la matriz.} Program eje2; Type TM = array[1..4, 1..4] of integer; TV = array[1..4] of integer; Procedure LeerMatriz(Var Mat:TM; Var N,M:byte); Var i,j:byte; begin write('Ingrese la cantidad de filas: ');readln(N); write('Ingrese la cantidad de columnas: ');readln(M); For i:= 1 to N do For j:= 1 to M do begin write('Ingrese un numero para la posicion ',i:3,j:3,' : ');readln(Mat[i,j]); end; end; Procedure Imprime(Mat:TM; N,M:byte); Var i,j:byte; begin For i:= 1 to N do begin For j:= 1 to M do write(Mat[i,j]:3); writeln; end; end; Function Minimo(Mat: TM; N,M: byte): integer; Var i,j: byte; Min: integer; Begin Min:= Mat[1,1]; For i := 1 to N do For j:= 1 to M do If Min > Mat[i,j] Then Min:= Mat[I,j]; Minimo:= Min; End; Procedure FilaMayor(Mat:TM; SF:TV; N,M:byte); //La suma es un vector, osea, cada fila debemos sumarla mediante un vector. Var i,j,Fila:byte; Max:integer; begin Max:= 0; For i:= 1 to N do // Para calcular bien la suma de cada fila debemos recorrerla de esta forma. begin For j:= 1 to M do SF[i]:= SF[i] + Mat[i,j]; If (SF[i] > Max) then begin Max:= SF[i]; Fila:= i; end; end; writeln('La fila ',Fila,' tiene la mayor suma con: ',Max); For j:= 1 to M do write(Mat[Fila,j]:3); writeln; end; Procedure ColumnaMenor(Mat:TM;SC:TV; N,M:byte); Var i,j,Columna:byte; Min:integer; begin Min:= 999; For j:= 1 to M do // Para calcular bien la suma de cada columna debemos recorrerla de esta forma. begin For i:= 1 to N do SC[j]:= SC[j] + Mat[i,j]; If (SC[j] < Min) then begin Min:= SC[j]; Columna:= j; end; end; writeln('La columna ',Columna,' tiene la menor suma con: ',Min); For i:= 1 to N do writeln(Mat[i,Columna]:3); writeln; end; Var Mat:TM; SF,SC:TV; N,M:byte; Begin LeerMatriz(Mat,N,M); writeln; writeln('Matriz original'); Imprime(Mat,N,M); writeln; FilaMayor(Mat,SF,N,M); writeln; ColumnaMenor(Mat,SC,N,M); writeln; writeln('El minimo elemento de la matriz es: ',Minimo(Mat,N,M)); end.
unit frmSelectPartition; // Description: // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, OTFEFreeOTFEBase_U, fmeSelectPartition, ExtCtrls, SDUForms; type TfrmSelectPartition = class(TSDUForm) Label1: TLabel; pnlButtonCenter: TPanel; pbOK: TButton; pbCancel: TButton; fmeSelectPartition1: TfmeSelectPartition; procedure FormShow(Sender: TObject); procedure pbOKClick(Sender: TObject); procedure FormResize(Sender: TObject); procedure FormCreate(Sender: TObject); procedure fmeSelectPartitionSDUDiskPartitionsPanel1DblClick( Sender: TObject); procedure fmeSelectPartitionpnlNoPartitionDisplayDblClick( Sender: TObject); private procedure EnableDisableControls(); function GetPartition(): string; procedure fmeSelectPartitionChanged(Sender: TObject); public published property Partition: string read GetPartition; end; implementation {$R *.DFM} uses SDUGeneral, SDUDialogs; procedure TfrmSelectPartition.FormCreate(Sender: TObject); begin SDUClearPanel(pnlButtonCenter); end; procedure TfrmSelectPartition.FormResize(Sender: TObject); begin SDUCenterControl(pnlButtonCenter, ccHorizontal); end; procedure TfrmSelectPartition.FormShow(Sender: TObject); begin fmeSelectPartition1.AllowCDROM := TRUE; fmeSelectPartition1.OnChange := fmeSelectPartitionChanged; fmeSelectPartition1.Initialize(); EnableDisableControls(); end; procedure TfrmSelectPartition.pbOKClick(Sender: TObject); begin ModalResult := mrOK; end; procedure TfrmSelectPartition.EnableDisableControls(); begin pbOK.Enabled := (Partition <> ''); end; function TfrmSelectPartition.GetPartition(): string; begin Result := fmeSelectPartition1.SelectedDevice; end; procedure TfrmSelectPartition.fmeSelectPartitionChanged(Sender: TObject); begin EnableDisableControls(); end; procedure TfrmSelectPartition.fmeSelectPartitionSDUDiskPartitionsPanel1DblClick( Sender: TObject); begin pbOKClick(Sender); end; procedure TfrmSelectPartition.fmeSelectPartitionpnlNoPartitionDisplayDblClick( Sender: TObject); begin pbOKClick(Sender); end; END.
unit DreamChatStrings; interface uses Classes; type TDreamChatStringIDs = ( //[Form] I_COMMONCHAT, //'Общий' I_PRIVATE, //'Приват' I_LINE, //'Линия' I_MESSAGESBOARD, //Доска объявлений I_MESSAGESBOARDUPDATE, //Обновлена доска объявлений I_USERCONNECTED, //К нам приходит: I_USERDISCONNECTED, //Нас покинул : I_NOTANSWERING, I_PRIVATEWITH, //Личный чат с I_USERRENAME, //изменяет имя на //[PopUpMenu] I_CLOSE, //Закрыть I_REFRESH, //Обновить I_SAVELOG, //Сохранить лог I_PRIVATEMESSAGE, //Личное сообщение I_PRIVATEMESSAGETOALL, //Личное сообщение всем I_CREATELINE, //Создать линию I_TOTALIGNOR, //Игнорировать все сообщения I_USERINFO, //О пользователе I_COMETOPRIVATE, //Войти в приват I_COMETOLINE, //Войти в линию //[UserInfo] I_DISPLAYNICKNAME, I_NICKNAME, I_IP, I_COMPUTERNAME, I_LOGIN, I_CHATVER, I_COMMDLLVER, I_STATE, //[NewLine] I_INPUTPASSWORD, I_COMING, //Войти I_INPUTPASSANDLINENAME, //Введите название и пароль для новой линии: I_CREATE, I_NEWLINE, I_CANCEL, I_LINENAME, I_PASSWORD, //[MainPopUpMenu] I_EXIT, I_SEESHARE, //перейти к ресурсам компьютера I_WRITENICKNAME //Написать имя внизу ); TDreamChatStrings = class private FStrings: TStrings; function GetData(index: integer): string; procedure SetData(index: integer; value: string); constructor Create; destructor Destroy; override; public procedure Load(IniFileName: string); property Data[index: integer]: string read GetData write SetData; default; end; implementation uses IniFiles, SysUtils; { TDreamChatStrings } constructor TDreamChatStrings.Create; begin inherited Create; FStrings := TStringList.Create; end; destructor TDreamChatStrings.Destroy; begin FreeAndNil(FStrings); inherited Destroy; end; function TDreamChatStrings.GetData(index: integer): string; begin Result := FStrings.Values[IntToStr(index)]; end; procedure TDreamChatStrings.Load(IniFileName: string); var MemIniStrings: TMemIniFile; //i, i_end: integer; begin MemIniStrings := TMemIniFile.Create(IniFileName); //CurrLang := ExePath + ChatConfig.ReadString(TDreamChatConfig.Common {'Common'}, TDreamChatConfig.Language {'Language'}, 'Languages\English.lng'); MemIniStrings.ReadSection('Strings', FStrings); { i_end := Section.Count - 1; for i := 0 to i_end do begin FStrings.Add(MemIniStrings.ReadString('Strings', InttoStr(i + 10), ''));//Strings //EInternational.Add(MemIniStrings.ReadString('ErrorStrings', InttoStr(i + 10), '')); end;} end; procedure TDreamChatStrings.SetData(index: integer; value: string); begin end; end.
program RockPaperScissors; {$R *.res} uses crt; var temp: string; selection: char; procedure backgroundColour(var colour: string); begin if colour = 'Blue' then textBackground(Blue); clrScr; end; procedure waitKey; begin repeat until keyPressed; end; procedure ascii(var asciiType: string); begin if asciiType = 'logo' then begin writeln('==============================================================================='); writeln; writeln(' RRRRR PPPPP SSSSS'); writeln(' R R P P S'); writeln(' RRRRR - PPPPP - SSSS'); writeln(' R R P S'); writeln(' R RR OCK P APER SSSSS CISSORS'); writeln; writeln('==============================================================================='); writeln; end; if asciiType = 'titleTop' then begin writeln('-------------------------------------------------------------------------------'); writeln; writeln(' Rock-Paper-Scissors'); writeln; writeln('-------------------------------------------------------------------------------'); writeln; end; if asciiType = 'titleShort' then begin writeln(' Rock-Paper-Scissors'); writeln; writeln('-------------------------------------------------------------------------------'); writeln; end; if asciiType = 'titleLong' then begin writeln(' Rock-Paper-Scissors'); writeln(' Develop by Jason Kwok'); writeln; writeln('-------------------------------------------------------------------------------'); writeln; end; if asciiType = 'divideMiddle' then begin writeln; writeln('-------------------------------------------------------------------------------'); writeln; end; if asciiType = 'divideLast' then begin writeln; write('-------------------------------------------------------------------------------'); end; end; procedure intro; begin clrScr; temp := 'logo'; ascii(temp); temp := 'titleLong'; ascii(temp); writeln(' Loading, please wait...'); temp := 'divideLast'; ascii(temp); delay(2500); end; procedure menu; begin clrScr; temp := 'titleTop'; ascii(temp); writeln(' You can choose to play the game (1), or change the option of the game (2). '); writeln(' You can also choose to leave this program (9).'); temp := 'divideMiddle'; ascii(temp); writeln(' Menu options:'); writeln(' [1] Play'); writeln(' [2] Option'); writeln(' [9] LEAVE'); writeln(' *Please enter the NUMBER in front of each option.'); temp := 'divideMiddle'; ascii(temp); write('Please select an item: '); readln(selection); temp := 'divideLast'; ascii(temp); case selection of {'1':} {'2':} '9': halt; else menu; end; end; procedure gameMain; begin end; begin temp := 'Blue'; backgroundColour(temp); intro; menu; waitKey; end.
(* * FPG EDIT : Edit FPG file from DIV2, FENIX and CDIV * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * *) unit ufrmNewFPG; interface uses LCLIntf, LCLType, SysUtils, Classes, Graphics, Controls, Forms, ExtCtrls, Buttons, StdCtrls, uFPG, uPAL, uLanguage, uIniFile, uFrmMessageBox, Dialogs, FileUtil; type TfrmNewFPG = class(TForm) gbName: TGroupBox; edNombre: TEdit; gbType: TGroupBox; cbTipoFPG: TComboBox; gbPalette: TGroupBox; btLoadPal: TButton; btViewPal: TButton; bbAceptar: TBitBtn; bbCancelar: TBitBtn; odPalette: TOpenDialog; procedure bbCancelarClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure cbTipoFPGChange(Sender: TObject); procedure bbAceptarClick(Sender: TObject); procedure btLoadPalClick(Sender: TObject); procedure btViewPalClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure edNombreEnter(Sender: TObject); procedure edNombreExit(Sender: TObject); procedure cbTipoFPGEnter(Sender: TObject); procedure cbTipoFPGExit(Sender: TObject); private { Private declarations } _lng_str : string; procedure _set_lng; public { Public declarations } fpg:TFpg; end; var frmNewFPG: TfrmNewFPG; implementation uses ufrmPalette; {$R *.lfm} procedure TfrmNewFPG._set_lng; begin if _lng_str = inifile_language then Exit; _lng_str := inifile_language; end; procedure TfrmNewFPG.bbCancelarClick(Sender: TObject); begin FPG.needTable := true; Hide; end; procedure TfrmNewFPG.FormShow(Sender: TObject); begin cbTipoFPG.ItemIndex := 5; cbTipoFPGChange(Sender); end; procedure TfrmNewFPG.cbTipoFPGChange(Sender: TObject); begin gbPalette.Visible := false; btLoadPal.Enabled := false; btViewPal.Enabled := false; if (cbTipoFPG.ItemIndex = 1) then begin btLoadPal.Enabled := true; gbPalette.Visible := true; end; end; procedure TfrmNewFPG.bbAceptarClick(Sender: TObject); var i : integer; temp : string; begin // Si no se cargo la paleta en un FPG de 8 bits if (cbTipoFPG.ItemIndex = 1) and (not FPG.loadpalette) then begin feMessageBox(LNG_ERROR, LNG_NOTLOAD_PALETTE, 0, 0); Exit; end; i := Length(edNombre.Text); temp := LowerCase(edNombre.Text); if((temp[i - 3] <> '.') or (temp[i - 2] <> 'f') or (temp[i - 1] <> 'p') or (temp[i] <> 'g')) then edNombre.Text := edNombre.Text + '.fpg'; if FileExistsUTF8(edNombre.Text) { *Converted from FileExists* } then begin feMessageBox( LNG_ERROR, LNG_FILE_EXIST, 0, 0); Exit; end; FPG.Initialize; FPG.source := edNombre.Text; FPG.FileFormat := cbTipoFPG.ItemIndex; FPG.setMagic; ModalResult := mrOK; Hide; end; procedure TfrmNewFPG.btLoadPalClick(Sender: TObject); begin if not odPalette.Execute then Exit; if not FileExistsUTF8(odPalette.FileName) then begin feMessageBox( LNG_ERROR, LNG_FILE_NOTEXIST, 0, 0); Exit; end; if Load_PAL(fpg.palette, odPalette.FileName) then begin FPG.loadpalette := true; btViewPal.Enabled := true; end else begin FPG.loadpalette := false; btViewPal.Enabled := false; Exit; end; // Crea la tabla de conversión de imagenes a 8 bits if FPG.loadpalette then FPG.Create_table_16_to_8; end; procedure TfrmNewFPG.btViewPalClick(Sender: TObject); begin frmPalette.ShowModal; end; procedure TfrmNewFPG.FormActivate(Sender: TObject); begin _set_lng; end; procedure TfrmNewFPG.edNombreEnter(Sender: TObject); begin edNombre.Color := clWhite; end; procedure TfrmNewFPG.edNombreExit(Sender: TObject); begin edNombre.Color := clMedGray; end; procedure TfrmNewFPG.cbTipoFPGEnter(Sender: TObject); begin cbTipoFPG.Color := clWhite; end; procedure TfrmNewFPG.cbTipoFPGExit(Sender: TObject); begin cbTipoFPG.Color := clMedGray; end; end.
// // Generated by JavaToPas v1.5 20180804 - 082433 //////////////////////////////////////////////////////////////////////////////// unit android.net.wifi.hotspot2.PasspointConfiguration; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, Androidapi.JNI.os, android.net.wifi.hotspot2.pps.HomeSp, android.net.wifi.hotspot2.pps.Credential; type JPasspointConfiguration = interface; JPasspointConfigurationClass = interface(JObjectClass) ['{2619E543-527C-4789-83E6-8342B50BE45B}'] function _GetCREATOR : JParcelable_Creator; cdecl; // A: $19 function describeContents : Integer; cdecl; // ()I A: $1 function equals(thatObject : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $1 function getCredential : JCredential; cdecl; // ()Landroid/net/wifi/hotspot2/pps/Credential; A: $1 function getHomeSp : JHomeSp; cdecl; // ()Landroid/net/wifi/hotspot2/pps/HomeSp; A: $1 function hashCode : Integer; cdecl; // ()I A: $1 function init : JPasspointConfiguration; cdecl; overload; // ()V A: $1 function init(source : JPasspointConfiguration) : JPasspointConfiguration; cdecl; overload;// (Landroid/net/wifi/hotspot2/PasspointConfiguration;)V A: $1 function toString : JString; cdecl; // ()Ljava/lang/String; A: $1 procedure setCredential(credential : JCredential) ; cdecl; // (Landroid/net/wifi/hotspot2/pps/Credential;)V A: $1 procedure setHomeSp(homeSp : JHomeSp) ; cdecl; // (Landroid/net/wifi/hotspot2/pps/HomeSp;)V A: $1 procedure writeToParcel(dest : JParcel; flags : Integer) ; cdecl; // (Landroid/os/Parcel;I)V A: $1 property CREATOR : JParcelable_Creator read _GetCREATOR; // Landroid/os/Parcelable$Creator; A: $19 end; [JavaSignature('android/net/wifi/hotspot2/PasspointConfiguration')] JPasspointConfiguration = interface(JObject) ['{9CEF1F77-51E9-4F30-A736-D7CC6D7268E2}'] function describeContents : Integer; cdecl; // ()I A: $1 function equals(thatObject : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $1 function getCredential : JCredential; cdecl; // ()Landroid/net/wifi/hotspot2/pps/Credential; A: $1 function getHomeSp : JHomeSp; cdecl; // ()Landroid/net/wifi/hotspot2/pps/HomeSp; A: $1 function hashCode : Integer; cdecl; // ()I A: $1 function toString : JString; cdecl; // ()Ljava/lang/String; A: $1 procedure setCredential(credential : JCredential) ; cdecl; // (Landroid/net/wifi/hotspot2/pps/Credential;)V A: $1 procedure setHomeSp(homeSp : JHomeSp) ; cdecl; // (Landroid/net/wifi/hotspot2/pps/HomeSp;)V A: $1 procedure writeToParcel(dest : JParcel; flags : Integer) ; cdecl; // (Landroid/os/Parcel;I)V A: $1 end; TJPasspointConfiguration = class(TJavaGenericImport<JPasspointConfigurationClass, JPasspointConfiguration>) end; implementation end.
{******************************************************************************} { } { Delphi PnHttpSysServer } { } { Copyright (c) 2018 pony,นโร๗(7180001@qq.com) } { } { Homepage: https://github.com/pony5551/PnHttpSysServer } { } {******************************************************************************} unit uPnMemory; {$I PnDefs.inc} interface { Get Complete Heap Status } function Get_HeapStatus:THeapStatus; { Check the ammount of memoy in use (bytes) } function Get_MemoryInUse:int64; { Check how much Address Space is used by the Application (KB) } function Get_AddressSpaceUsed:int64; implementation {$IFNDEF FPC} {$O-} {$ENDIF} {$IFDEF WINDOWS} uses Windows; function Get_AddressSpaceUsed: int64; var LMemoryStatus: TMemoryStatus; begin {Set the structure size} LMemoryStatus.dwLength := SizeOf(LMemoryStatus); {Get the memory status} GlobalMemoryStatus(LMemoryStatus); {The result is the total address space less the free address space} Result := (LMemoryStatus.dwTotalVirtual - LMemoryStatus.dwAvailVirtual) shr 10; end; {$ELSE} function Get_AddressSpaceUsed: int64; var hs :THeapStatus; begin // no funciton available? hs := GetHeapStatus; Result := hs.TotalCommitted end; {$ENDIF} function Get_HeapStatus:THeapStatus; begin Result:=GetHeapStatus; end; function Get_MemoryInUse:int64; begin Result:=GetHeapStatus.TotalAllocated; end; end.
unit uMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Edit, FMX.StdCtrls, FMX.Platform, FMX.Notification, FMX.ListBox, FMX.Layouts; type TSettingBadgeNumberForm = class(TForm) btnSetBadgeNumber: TButton; ToolBar1: TToolBar; Label1: TLabel; ListBox1: TListBox; ListBoxItem1: TListBoxItem; nbBadgeNumber: TNumberBox; btnBadgeNumberDown: TButton; btnBadgeNumberUp: TButton; btnResetBadgeNumber: TButton; NotificationC: TNotificationCenter; ToolBar2: TToolBar; SpeedButton1: TSpeedButton; procedure btnSetBadgeNumberClick(Sender: TObject); procedure btnBadgeNumberDownClick(Sender: TObject); procedure btnBadgeNumberUpClick(Sender: TObject); procedure btnResetBadgeNumberClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); private function GetBadgeNumber: single; public { Public declarations } end; var SettingBadgeNumberForm: TSettingBadgeNumberForm; implementation {$R *.fmx} procedure TSettingBadgeNumberForm.btnSetBadgeNumberClick(Sender: TObject); begin { set Icon Badge Number } if NotificationC.Supported then NotificationC.ApplicationIconBadgeNumber := Trunc(nbBadgeNumber.Value); end; procedure TSettingBadgeNumberForm.FormCreate(Sender: TObject); begin { display current Icon Badge Number } nbBadgeNumber.Value := GetBadgeNumber; end; procedure TSettingBadgeNumberForm.btnBadgeNumberDownClick(Sender: TObject); begin nbBadgeNumber.Value := nbBadgeNumber.Value - 1; end; procedure TSettingBadgeNumberForm.btnBadgeNumberUpClick(Sender: TObject); begin nbBadgeNumber.Value := nbBadgeNumber.Value + 1; end; procedure TSettingBadgeNumberForm.btnResetBadgeNumberClick(Sender: TObject); begin { reset Icon Badge Number } if NotificationC.Supported then NotificationC.ApplicationIconBadgeNumber := 0; nbBadgeNumber.Value := 0; end; function TSettingBadgeNumberForm.GetBadgeNumber; begin Result:= NotificationC.ApplicationIconBadgeNumber; end; procedure TSettingBadgeNumberForm.SpeedButton1Click(Sender: TObject); var MyNotification: TNotification; begin MyNotification := NotificationC.CreateNotification; try MyNotification.Number := Trunc(nbBadgeNumber.Value); MyNotification.Name := 'MyNotification'; MyNotification.AlertBody := 'Android Notification Numbers!'; MyNotification.FireDate := Now; NotificationC.ScheduleNotification(MyNotification); finally MyNotification.DisposeOf; end; end; end.
unit uRtHeadInfoReader; interface uses uBytesStream,Classes,SysUtils,uLKJRuntimeFile,Math, Windows; type TOrgHeadReader = class public constructor Create(); destructor Destroy; override; public procedure read(orgFileName: string;var HeadInfo: RLKJRTFileHeadInfo); private m_BytesStream : TBytesStream; function BCDToHex(nBcd: Byte): Integer; function MoreBcdToHex(nBegin, nLen: Integer): Integer; function ConvertFactory(b : byte): TLKJFactory; function ConvertTrainType(b: byte): TLKJTrainType; function ConvertBenBu(b: byte): TLKJBenBu; end; implementation { TOrgHeadReader } function TOrgHeadReader.BCDToHex(nBcd: Byte): Integer; begin Result := (nBcd div 16) * 10 + (nBcd mod 16); end; function TOrgHeadReader.ConvertFactory(b: byte): TLKJFactory; begin if b = $53 then Result := sfSiWei else Result :=sfZhuZhou; end; function TOrgHeadReader.ConvertTrainType(b: byte): TLKJTrainType; begin if b mod 2 = 1 then Result := ttPassenger else Result := ttCargo; end; function TOrgHeadReader.ConvertBenBu(b: byte): TLKJBenBu; begin if ((b mod 4) div 2) = 1 then Result := bbBu else Result := bbBen; end; constructor TOrgHeadReader.Create; begin m_BytesStream := TBytesStream.Create(128); end; destructor TOrgHeadReader.Destroy; begin m_BytesStream.Free; inherited; end; function TOrgHeadReader.MoreBcdToHex(nBegin, nLen: Integer): Integer; var i: integer; k: Extended; l: Integer; begin k := 0; l := 0; for i := nLen - 1 downto 0 do begin k := k + BcdToHex(m_BytesStream.GetBuffer(nBegin + i)^) * Power(100, l); Inc(l); end; Result := Round(k); end; procedure TOrgHeadReader.read(orgFileName: string;var HeadInfo: RLKJRTFileHeadInfo); begin FillChar(HeadInfo,SizeOf(RLKJRTFileHeadInfo),0); m_BytesStream.LoadFromFile(orgFileName); HeadInfo.nLocoType := MoreBcdToHex(56, 3); HeadInfo.nLocoID := MoreBcdToHex(60, 3); with m_BytesStream do begin HeadInfo.strTrainHead := chr(Get(10))+chr(Get(10)) + chr(Get(10))+chr(Get(10)); HeadInfo.Factory := ConvertFactory(Get(86)); HeadInfo.DTFileHeadDt := EncodeDate(BCDToHex(Get(2))+2000,BCDToHex(Get(3)), BCDToHex(Get(4))) + EncodeTime(MoreBcdToHex(5, 1),MoreBcdToHex(6, 1),MoreBcdToHex(7, 1),0); end; HeadInfo.nTrainNo := MoreBcdToHex(14, 3) mod 1000000; HeadInfo.nLunJing := MoreBcdToHex(64, 3); HeadInfo.nJKLineID := MoreBcdToHex(19, 2); HeadInfo.nDataLineID := MoreBcdToHex(17, 1); HeadInfo.nFirstDriverNO := MoreBcdToHex(24, 4); HeadInfo.nSecondDriverNO := MoreBcdToHex(28, 4); HeadInfo.nDeviceNo:= MoreBcdToHex(89, 3); HeadInfo.nTotalWeight := MoreBcdToHex(34, 3); HeadInfo.nSum := MoreBcdToHex(52, 2); HeadInfo.nLoadWeight := MoreBcdToHex(37, 3); HeadInfo.nJKVersion := MoreBcdToHex(78,4); HeadInfo.nDataVersion := MoreBcdToHex(82,4); HeadInfo.nStartStation := MoreBcdToHex(22, 2); HeadInfo.TrainType := ConvertTrainType(MoreBcdToHex(9, 1) mod 4); HeadInfo.BenBu := ConvertBenBu(MoreBcdToHex(9, 1) mod 4); end; end.
unit UnitEditorFullScreenForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, Themes, Vcl.PlatformDefaultStyleActnCtrls, Vcl.ActnPopup, Menus, Dmitry.Utils.System, uConstants, uMemory, uDBForm, uBitmapUtils, uDBIcons; type TEditorFullScreenForm = class(TDBForm) PmMain: TPopupActionBar; Close1: TMenuItem; N1: TMenuItem; SelectBackGroundColor1: TMenuItem; ColorDialog1: TColorDialog; procedure FormPaint(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Close1Click(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure SelectBackGroundColor1Click(Sender: TObject); procedure FormResize(Sender: TObject); private { Private declarations } CurrentImage: TBitmap; DrawImage: TBitmap; procedure LoadLanguage; protected function GetFormID: string; override; procedure WndProc(var Message: TMessage); override; public { Public declarations } procedure SetImage(Image: TBitmap); procedure CreateDrawImage; end; var EditorFullScreenForm: TEditorFullScreenForm; implementation {$R *.dfm} procedure TEditorFullScreenForm.FormPaint(Sender: TObject); begin Canvas.Draw(ClientWidth div 2 - DrawImage.Width div 2, Clientheight div 2 - DrawImage.Height div 2, DrawImage); end; procedure TEditorFullScreenForm.FormResize(Sender: TObject); begin Repaint; end; function TEditorFullScreenForm.GetFormID: string; begin Result := 'Editor'; end; procedure TEditorFullScreenForm.SetImage(Image: TBitmap); begin CurrentImage := Image; end; procedure TEditorFullScreenForm.WndProc(var Message: TMessage); var DC: HDC; BrushInfo: TagLOGBRUSH; Brush: HBrush; begin if (Message.Msg = WM_ERASEBKGND) and StyleServices.Enabled then begin Message.Result := 1; DC := TWMEraseBkgnd(Message).DC; if DC = 0 then Exit; brushInfo.lbStyle := BS_SOLID; brushInfo.lbColor := ColorToRGB(Color); Brush := CreateBrushIndirect(brushInfo); FillRect(DC, Rect(0, 0, Width, Height), Brush); if(Brush > 0) then DeleteObject(Brush); Exit; end; inherited; end; procedure TEditorFullScreenForm.FormCreate(Sender: TObject); begin DrawImage := TBitmap.Create; DrawImage.PixelFormat := pf24bit; LoadLanguage; PmMain.Images := Icons.ImageList; Close1.ImageIndex := DB_IC_EXIT; SelectBackGroundColor1.ImageIndex := DB_IC_DESKTOP; end; procedure TEditorFullScreenForm.FormDestroy(Sender: TObject); begin F(DrawImage); end; procedure TEditorFullScreenForm.Close1Click(Sender: TObject); begin Close; end; procedure TEditorFullScreenForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Release; end; procedure TEditorFullScreenForm.CreateDrawImage; var W, H: Integer; begin W := CurrentImage.Width; H := CurrentImage.Height; ProportionalSize(Monitor.Width, Monitor.Height, W, H); DoResize(W, H, CurrentImage, DrawImage); end; procedure TEditorFullScreenForm.FormKeyPress(Sender: TObject; var Key: Char); begin if Ord(Key) = VK_ESCAPE then Close; if (Key = #10) and CtrlKeyDown and Focused then Close; end; procedure TEditorFullScreenForm.LoadLanguage; begin BeginTranslate; try Close1.Caption := L('Close'); SelectBackGroundColor1.Caption := L('Select background color'); finally EndTranslate; end; end; procedure TEditorFullScreenForm.SelectBackGroundColor1Click(Sender: TObject); begin ColorDialog1.Color := Color; if ColorDialog1.Execute then Color := ColorDialog1.Color; Refresh; end; end.
unit UnitFormCDExport; interface uses Winapi.Windows, Winapi.Messages, Winapi.ShellApi, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.StdCtrls, Vcl.Menus, Vcl.ImgList, Vcl.Buttons, Vcl.PlatformDefaultStyleActnCtrls, Vcl.ActnPopup, Vcl.AppEvnts, Vcl.Imaging.pngimage, DragDrop, DropTarget, Dmitry.Controls.Base, Dmitry.Controls.ComboBoxExDB, Dmitry.Controls.WatermarkedEdit, Dmitry.Controls.LoadingSign, DragDropFile, UnitCDMappingSupport, UnitDBFileDialogs, uAssociatedIcons, uDBIcons, uMemory, uCDMappingTypes, uDBForm, uDBContext, uDBManager, uShellIntegration, uRuntime, uConstants, uTranslateUtils, uProgramStatInfo, uFormInterfaces; type TFormCDExport = class(TDBForm, ICDExportForm) CDListView: TListView; PanelBottom: TPanel; PanelTop: TPanel; ComboBoxPathList: TComboBoxExDB; ButtonAddItems: TButton; ButtonRemoveItems: TButton; ButtonCreateDirectory: TButton; LabelInfo: TLabel; Image1: TImage; LabelCDLabel: TLabel; EditLabel: TWatermarkedEdit; LabelPath: TLabel; ButtonExport: TButton; CheckBoxDeleteFiles: TCheckBox; CheckBoxModifyDB: TCheckBox; PopupMenuListView: TPopupActionBar; Copy1: TMenuItem; Cut1: TMenuItem; Paste1: TMenuItem; N1: TMenuItem; Delete1: TMenuItem; N2: TMenuItem; Open1: TMenuItem; ImageListIcons: TImageList; LabelExportDirectory: TLabel; LabelExportSize: TLabel; EditCDSize: TEdit; EditExportDirectory: TEdit; ButtonChooseDirectory: TButton; DestroyTimer: TTimer; DropFileTarget1: TDropFileTarget; N3: TMenuItem; Rename1: TMenuItem; N4: TMenuItem; AddItems1: TMenuItem; ApplicationEvents1: TApplicationEvents; CheckBoxCreatePortableDB: TCheckBox; LsMain: TLoadingSign; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure DestroyTimerTimer(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure CDListViewDblClick(Sender: TObject); procedure ButtonRemoveItemsClick(Sender: TObject); procedure DropFileTarget1Drop(Sender: TObject; ShiftState: TShiftState; APoint: TPoint; var Effect: Integer); procedure ButtonCreateDirectoryClick(Sender: TObject); procedure ButtonChooseDirectoryClick(Sender: TObject); procedure ButtonAddItemsClick(Sender: TObject); procedure ComboBoxPathListSelect(Sender: TObject); procedure ButtonExportClick(Sender: TObject); procedure Rename1Click(Sender: TObject); procedure CDListViewEditing(Sender: TObject; Item: TListItem; var AllowEdit: Boolean); procedure CDListViewEdited(Sender: TObject; Item: TListItem; var S: String); procedure PopupMenuListViewPopup(Sender: TObject); procedure Copy1Click(Sender: TObject); procedure Cut1Click(Sender: TObject); procedure Paste1Click(Sender: TObject); procedure ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean); procedure Open1Click(Sender: TObject); private { Private declarations } FContext: IDBContext; Mapping: TCDIndexMapping; procedure LoadLanguage; protected { Protected declarations } procedure CreateParams(var Params: TCreateParams); override; function GetFormID: string;override; public { Public declarations } procedure Execute; procedure DrawCurrentDirectory(ListView: TListView); procedure OnThreadEnd(Sender: TObject); procedure EnableControls(Value: Boolean); end; procedure DoCDExport; implementation uses FormManegerUnit, UnitCDExportThread, uManagerExplorer; {$R *.dfm} procedure DoCDExport; var FormCDExport: TFormCDExport; begin Application.CreateForm(TFormCDExport, FormCDExport); FormCDExport.Execute; end; { TFormCDExport } procedure TFormCDExport.Execute; begin Show; end; procedure TFormCDExport.FormCreate(Sender: TObject); begin FContext := DBManager.DBContext; CDListView.DoubleBuffered := True; Mapping := TCDIndexMapping.Create(FContext); EditCDSize.Text := SizeInText(Mapping.GetCDSize); DropFileTarget1.Register(CDListView); PopupMenuListView.Images := Icons.ImageList; RegisterMainForm(Self); ComboBoxPathList.ItemIndex := 0; LoadLanguage; Open1.ImageIndex := DB_IC_SHELL; Copy1.ImageIndex := DB_IC_COPY; Cut1.ImageIndex := DB_IC_CUT; Paste1.ImageIndex := DB_IC_PASTE; Delete1.ImageIndex := DB_IC_DELETE_INFO; Rename1.ImageIndex := DB_IC_RENAME; AddItems1.ImageIndex := DB_IC_NEW; end; procedure TFormCDExport.LoadLanguage; begin BeginTranslate; try Caption := L('Export photos to a removable disk'); LabelInfo.Caption := L('This dialog will help you to transfer a portion of photos stored on your hard drive - on CD \ DVD drive.$nl$' + 'Thus the information about the photographs will remain in the collection, and if you want to see photos of the program will ask you to insert the appropriate disc.$nl$' + 'Program does not record data on the disc, but only generates a folder designed to write to the disk. $nl$To write to disk data files using special software!'); LabelCDLabel.Caption := L('Create CD\DVD image with name') + ':'; EditLabel.WatermarkText := L('Name of drive'); LabelPath.Caption := L('Location') + ':'; ButtonAddItems.Caption := L('Add'); ButtonRemoveItems.Caption := L('Delete'); ButtonCreateDirectory.Caption := L('Create directory'); CDListView.Columns[0].Caption := L('File name'); CDListView.Columns[1].Caption := L('File size'); CDListView.Columns[2].Caption := L('Collection ID'); ButtonExport.Caption := L('Start export'); LabelExportDirectory.Caption := L('Directory for export') + ':'; ButtonChooseDirectory.Caption := L('Choose directory'); Open1.Caption := L('Open'); Copy1.Caption := L('Copy'); Cut1.Caption := L('Cut'); Paste1.Caption := L('Paste'); Delete1.Caption := L('Delete'); LabelExportSize.Caption := L('The size of files for export') + ':'; Rename1.Caption := L('Rename'); AddItems1.Caption := L('Add'); CheckBoxDeleteFiles.Caption := L('Delete original files after a successful export'); CheckBoxModifyDB.Caption := L('Adjust the information in the collection after a successful export'); CheckBoxCreatePortableDB.Caption := L('Create portable collection on disk'); finally EndTranslate; end; end; procedure TFormCDExport.FormDestroy(Sender: TObject); begin UnRegisterMainForm(Self); F(Mapping); FContext := nil; end; function TFormCDExport.GetFormID: string; begin Result := 'CDExport'; end; procedure TFormCDExport.DestroyTimerTimer(Sender: TObject); begin DestroyTimer.Enabled := False; Release; end; procedure TFormCDExport.FormClose(Sender: TObject; var Action: TCloseAction); begin DestroyTimer.Enabled := True; end; procedure TFormCDExport.DrawCurrentDirectory(ListView: TListView); var Level: TCDIndexMappingDirectory; I, ID: Integer; Item: TListItem; Size: Int64; PathList: TStrings; Icon: TIcon; begin ListView.Items.BeginUpdate; try ListView.Items.Clear; ImageListIcons.Clear; Level := Mapping.CurrentLevel; if Level.Parent <> nil then begin Item := ListView.Items.Add; Item.Caption := '[..]'; Item.Data := nil; Icon := TAIcons.Instance.GetIconByExt('', True, 16, True); try Item.ImageIndex := ImageListIcons.AddIcon(Icon); finally F(Icon); end; end; for I := 0 to Level.Count - 1 do begin Item := ListView.Items.Add; Item.Caption := Level[I].Name; Item.Data := Level[I]; Size := Mapping.GetCDSizeWithDirectory(Level[I]); if Size > 0 then Item.SubItems.Add(SizeInText(Size)) else Item.SubItems.Add(''); ID := Level[I].DB_ID; if ID > 0 then Item.SubItems.Add(IntToStr(ID)) else begin if Mapping.DirectoryHasDBFiles(Item.Data) then Item.SubItems.Add('+') else Item.SubItems.Add(''); end; if Level[I].IsFile then Icon := TAIcons.Instance.GetIconByExt(Level[I].RealFileName, False, 16, False) else Icon := TAIcons.Instance.GetIconByExt('', True, 16, True); try Item.ImageIndex := ImageListIcons.AddIcon(Icon); finally F(Icon); end; end; finally ListView.Items.EndUpdate; end; EditCDSize.Text := SizeInText(Mapping.GetCDSize); ComboBoxPathList.Items.Clear; PathList := Mapping.GetCurrentUpperDirectories; try for I := PathList.Count - 1 downto 0 do ComboBoxPathList.Items.Add(PathList[I]); ComboBoxPathList.ItemIndex := 0; finally F(PathList); end; end; procedure TFormCDExport.CDListViewDblClick(Sender: TObject); var Item: TListItem; begin Item := CDListView.Selected; if Item = nil then Exit; if Item.Data = nil then begin Mapping.GoUp; DrawCurrentDirectory(CDListView); Exit; end; if Item.Data <> nil then if not TCDIndexMappingDirectory(Item.Data).IsFile then begin Mapping.SelectDirectory(TCDIndexMappingDirectory(Item.Data).Name); DrawCurrentDirectory(CDListView); end else Open1Click(Sender); end; procedure TFormCDExport.ButtonRemoveItemsClick(Sender: TObject); var I: Integer; Item: TCDIndexMappingDirectory; begin for I := CDListView.Items.Count - 1 downto 0 do if CDListView.Items[I].Selected then begin Item := CDListView.Items[I].Data; if Item <> nil then begin if Item.IsFile then Mapping.DeleteFile(Item.name) else Mapping.DeleteDirectory(Item.name); end; Mapping.ClearClipBoard; end; DrawCurrentDirectory(CDListView); end; procedure TFormCDExport.DropFileTarget1Drop(Sender: TObject; ShiftState: TShiftState; APoint: TPoint; var Effect: Integer); var FileList: TStrings; begin FileList := TStringList.Create; try DropFileTarget1.Files.AssignTo(FileList); Mapping.AddRealItemsToCurrentDirectory(FileList); DrawCurrentDirectory(CDListView); finally F(FileList); end; end; procedure TFormCDExport.ButtonCreateDirectoryClick(Sender: TObject); var DirectoryName: string; begin DirectoryName := L('New folder'); if StringPromtForm.Query(L('Create directory'), L('Enter a name for the new directory'), DirectoryName) then begin Mapping.CreateDirectory(DirectoryName); DrawCurrentDirectory(CDListView); end; end; procedure TFormCDExport.ButtonChooseDirectoryClick(Sender: TObject); var Dir: string; begin Dir := DBSelectDir(Handle, L('Select a folder to export files')); if DirectoryExists(Dir) then EditExportDirectory.Text := Dir; end; procedure TFormCDExport.ButtonAddItemsClick(Sender: TObject); var Dialog: DBOpenDialog; begin Dialog := DBOpenDialog.Create; try Dialog.EnableMultyFileChooseWithDirectory; if Dialog.Execute then begin Mapping.AddRealItemsToCurrentDirectory(Dialog.GetFiles); DrawCurrentDirectory(CDListView); end; finally F(Dialog); end; end; procedure TFormCDExport.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); Params.WndParent := GetDesktopWindow; with Params do ExStyle := ExStyle or WS_EX_APPWINDOW; end; procedure TFormCDExport.ComboBoxPathListSelect(Sender: TObject); begin Mapping.SelectPath(ComboBoxPathList.Items[ComboBoxPathList.ItemIndex]); DrawCurrentDirectory(CDListView); end; procedure TFormCDExport.EnableControls(Value : boolean); begin LsMain.Visible := not Value; EditLabel.Enabled := Value; EditCDSize.Enabled := Value; PanelTop.Enabled := Value; ButtonAddItems.Enabled := Value; ButtonRemoveItems.Enabled := Value; ButtonCreateDirectory.Enabled := Value; CDListView.Enabled := Value; ButtonChooseDirectory.Enabled := Value; CheckBoxDeleteFiles.Enabled := Value; CheckBoxModifyDB.Enabled := Value; ButtonExport.Enabled := Value; CheckBoxCreatePortableDB.Enabled := Value; end; procedure TFormCDExport.ButtonExportClick(Sender: TObject); var DriveFreeSize: Int64; Options: TCDExportOptions; begin if (Pos(':', EditLabel.Text) > 0) or (Pos('\', EditLabel.Text) > 0) or (Pos('?', EditLabel.Text) > 0) or (EditLabel.Text = '') then begin MessageBoxDB(Handle, L('Please enter a disk label that uniquely identify a disk! The title character is not allowed ":", "\" and "?"'), L('Warning'), TD_BUTTON_OK, TD_ICON_WARNING); EditLabel.SetFocus; EditLabel.SelectAll; Exit; end; Mapping.CDLabel := EditLabel.Text; DriveFreeSize := DiskFree(Ord(AnsiLowerCase(EditExportDirectory.Text)[1]) - Ord('a') + 1); if Mapping.GetCDSize > DriveFreeSize then begin MessageBoxDB(Handle, Format(L('Can not copy files: detected insufficient disk space! Need %s, and free only %s!'), [SizeInText(Mapping.GetCDSize), SizeInText(DriveFreeSize)]), L('Warning'), TD_BUTTON_OK, TD_ICON_WARNING); Exit; end; if not Mapping.DirectoryHasDBFiles(Mapping.GetRoot) then begin if ID_YES <> MessageBoxDB(Handle, L('The exported data can not have files associated with the current collection! You may not have selected the correct collection! Continue to export?'), L('Warning'), TD_BUTTON_YESNO, TD_ICON_WARNING) then Exit; end; EnableControls(False); // in thread! ProgramStatistics.CDExportUsed; Options.ToDirectory := EditExportDirectory.Text; Options.DeleteFiles := CheckBoxDeleteFiles.Checked; Options.ModifyDB := CheckBoxModifyDB.Checked; Options.CreatePortableDB := CheckBoxCreatePortableDB.Checked; Options.OnEnd := OnThreadEnd; TCDExportThread.Create(Self, FContext, Mapping, Options); end; procedure TFormCDExport.Rename1Click(Sender: TObject); var Item : TListItem; begin Item := CDListView.Selected; if Item <> nil then Item.EditCaption; end; procedure TFormCDExport.CDListViewEditing(Sender: TObject; Item: TListItem; var AllowEdit: Boolean); begin if Item <> nil then if Item.Data = nil then AllowEdit := False; end; procedure TFormCDExport.CDListViewEdited(Sender: TObject; Item: TListItem; var S: String); var Data: TCDIndexMappingDirectory; begin Data := TCDIndexMappingDirectory(Item.Data); if Data.IsFile then if Mapping.FileExists(S) then begin S := Item.Caption; Exit; end; if not Data.IsFile then if Mapping.DirectoryExists(S) then begin S := Item.Caption; Exit; end; Data.name := S; end; procedure TFormCDExport.PopupMenuListViewPopup(Sender: TObject); begin Open1.Visible := (CDListView.SelCount = 1) and (TCDIndexMappingDirectory(CDListView.Selected.Data).RealFileName <> ''); Copy1.Visible := CDListView.SelCount > 0; Cut1.Visible := CDListView.SelCount > 0; Paste1.Visible := CDListView.SelCount = 0; Rename1.Visible := CDListView.SelCount = 1; Delete1.Visible := CDListView.SelCount > 0; end; procedure TFormCDExport.Copy1Click(Sender: TObject); var I: Integer; Item: TCDIndexMappingDirectory; List: TList; begin List := TList.Create; try for I := CDListView.Items.Count - 1 downto 0 do if CDListView.Items[I].Selected then begin Item := CDListView.Items[I].Data; List.Add(Item); end; Mapping.Copy(List); finally F(List); end; DrawCurrentDirectory(CDListView); end; procedure TFormCDExport.Cut1Click(Sender: TObject); var I: Integer; Item: TCDIndexMappingDirectory; List: TList; begin List := TList.Create; try for I := CDListView.Items.Count - 1 downto 0 do if CDListView.Items[I].Selected then begin Item := CDListView.Items[I].Data; List.Add(Item); end; Mapping.Cut(List); finally F(List); end; DrawCurrentDirectory(CDListView); end; procedure TFormCDExport.Paste1Click(Sender: TObject); begin Mapping.Paste; DrawCurrentDirectory(CDListView); end; procedure TFormCDExport.ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean); begin if Msg.Hwnd = CDListView.Handle then begin if Msg.message = WM_KEYDOWN then begin if (Msg.WParam = VK_DELETE) then ButtonRemoveItemsClick(ButtonRemoveItems); if (Msg.WParam = VK_RETURN) then CDListViewDblClick(CDListView); if (Msg.WParam = VK_F2) then Rename1Click(Rename1); end; end; end; procedure TFormCDExport.OnThreadEnd(Sender: TObject); var Directory: string; begin EnableControls(True); Directory := ExtractFilePath(EditExportDirectory.Text); Directory := Directory + Mapping.CDLabel; Directory := IncludeTrailingBackslash(Directory); MessageBoxDB(Handle, Format(L('Files written to disk successfully exported to the folder "%s"!'), [Directory]), L('Information'), TD_BUTTON_OK, TD_ICON_INFORMATION); with ExplorerManager.NewExplorer(False) do begin SetPath(Directory); Show; SetFocus; end; Close; end; procedure TFormCDExport.Open1Click(Sender: TObject); var I: Integer; Item: TCDIndexMappingDirectory; List: TList; FileName: string; begin List := TList.Create; try for I := CDListView.Items.Count - 1 downto 0 do if CDListView.Items[I].Selected then begin Item := CDListView.Items[I].Data; FileName := ProcessPath(Item.RealFileName); if FileName <> '' then begin ShellExecute(Handle, 'open', PChar(FileName), nil, PChar(ExtractFileDir(FileName)), SW_NORMAL); Exit; end; end; finally F(List); end; end; initialization FormInterfaces.RegisterFormInterface(ICDExportForm, TFormCDExport); end.
unit UClassDef; interface uses Windows, Messages, SysUtils, Variants, Classes, XSBuiltIns, Hashes; //base node class (abstract class) for default values type TNodeData = class Caption:string; ID:integer; end; rNodeData = record NodeData: TNodeData; end; type TBrokerNodeData = class(TNodeData) tel:string; end; type TImageData = class(TNodeData) isDirty:boolean; MainID:integer; ImageFileID:integer; LabelID:integer; MS:TMemoryStream; FileName:string; public constructor Create; destructor Destroy; override; end; rImageData = record ImageData: TImageData; end; type TPDFData = class(TNodeData) isDirty:boolean; MainID:integer; PDFFileID:integer; dateOfAddition:TDateTime; MS:TMemoryStream; //FileName:string; cacheFile:string; public constructor Create; destructor Destroy; override; end; rPDFData = record PDFData: TPDFData; end; type TTrainStationNodeData = class(TNodeData) trainLine:string; trainLineID:integer; end; type TRent = class private FID: integer; FdateTimeLastUpdated: TDateTime; FdateTimeAddition: TDateTime; procedure FsetID(i: integer); function FgetDateTimeLastUpdated: TDateTime; procedure FsetDateTimeLastUpdated(dateTimeLastUpdated:TDateTime);overload; function FgetDateTimeLastUpdatedAsString: string; procedure FsetDateTimeLastUpdated(dateTimeLastUpdated:string);overload; function FgetDateTimeAddition: TDateTime; procedure FsetDateTimeAddition(dateTimeAddition:TDateTime);overload; function FgetDateTimeAdditionAsString: string; procedure FsetDateTimeAddition(dateTimeAddition:string);overload; public name: string; location: string; locationHiddenPart: string; trainStationID1: integer; trainStation1WalkingMinutes: integer; trainStation1BusMinutes: integer; trainStation1BusStopName: string; trainStation1BusWalkMinutes: integer; trainStationID2: integer; trainStation2WalkingMinutes: integer; trainStation2BusMinutes: integer; trainStation2BusStopName: string; trainStation2BusWalkMinutes: integer; locationLatitude: string; locationLongitude: string; memo: string; //constructor Create(); published {property} property ID: integer read FID write FsetID; property dateTimeLastUpdatedAsDateTime: TDateTime read FgetDateTimeLastUpdated write FsetDateTimeLastUpdated; property dateTimeLastUpdatedAsString: String read FgetDateTimeLastUpdatedAsString write FsetDateTimeLastUpdated; property dateTimeAdditionAsDateTime: TDateTime read FgetDateTimeAddition write FsetDateTimeAddition; property dateTimeAdditionAsString: String read FgetDateTimeAdditionAsString write FsetDateTimeAddition; end; type TRentEx = class(TRent) private FDateTimeVacancyChecked: TDateTime; FDateBuildYearMonth : TDateTime; function FgetDateTimeVacancyChecked: TDateTime; procedure FsetDateTimeVacancyChecked(dateTimeVacancyChecked:TDateTime);overload; function FgetDateTimeVacancyCheckedAsString: string; procedure FsetDateTimeVacancyChecked(dateTimeVacancyChecked:string);overload; function FgetDateBuildYearMonth: TDateTime; procedure FsetDateBuildYearMonth(dateBuildYearMonth:TDateTime);overload; function FgetDateBuildYearMonthAsString: string; procedure FsetDateBuildYearMonth(dateBuildYearMonth:string);overload; public roomNum:string; typeID: integer; // price: extended;//real; kindID: integer; // priceKanrihi: extended;//real; priceReikin: extended;//real; priceReikinUnitID: integer; priceShikikin: extended;//real; priceShikikinUnitID: integer; floorIsBasement: boolean; floorLocation: integer; square: Extended; buildingStory: integer; buildingStoryBasement: integer; conditions:TIntegerHash; images:TObjectHash; PDFs:TObjectHash; brokerID: integer; //need property to return broker name and tell. href:string; isVacancy : boolean; published {property} property dateBuildYearMonthAsDateTime: TDateTime read FgetDateBuildYearMonth write FsetDateBuildYearMonth; property dateBuildYearMonthAsString: String read FgetDateBuildYearMonthAsString write FsetDateBuildYearMonth; property dateTimeVacancyCheckedAsDateTime: TDateTime read FgetDateTimeVacancyChecked write FsetDateTimeVacancyChecked; property dateTimeVacancyCheckedAsString: String read FgetDateTimeVacancyCheckedAsString write FsetDateTimeVacancyChecked; end; type TRentLiving = class(TRentEx) private public floorPlanID: integer; // compassID: integer; constructor Create; destructor Destroy; override; end; type TRentBusiness = class(TRentEx) private public tubo: Extended; constructor Create; destructor Destroy; override; end; implementation constructor TImageData.Create; begin inherited Create; // end; destructor TImageData.Destroy; begin if Assigned(self.MS) then MS.Free; inherited; end; constructor TPDFData.Create; begin inherited Create; // end; destructor TPDFData.Destroy; begin if Assigned(self.MS) then MS.Free; inherited; end; procedure TRent.FsetID(i: integer); begin if FID < 0 then begin FID := i; end; end; function TRent.FgetDateTimeLastUpdated: TDateTime; begin result := FdateTimeLastUpdated; end; procedure TRent.FsetDateTimeLastUpdated(dateTimeLastUpdated:TDateTime); begin FdateTimeLastUpdated := dateTimeLastUpdated; end; function TRent.FgetDateTimeLastUpdatedAsString: string; begin result := FormatDateTime('yyyy/MM/dd hh:mm:ss', FdateTimeLastUpdated); end; procedure TRent.FsetDateTimeLastUpdated(dateTimeLastUpdated:string); begin try FdateTimeLastUpdated := StrToDateTime(dateTimeLastUpdated); except // end; end; function TRent.FgetDateTimeAddition: TDateTime; begin result := FdateTimeAddition; end; procedure TRent.FsetDateTimeAddition(dateTimeAddition:TDateTime); begin FdateTimeAddition := dateTimeAddition; end; function TRent.FgetDateTimeAdditionAsString: string; begin result := FormatDateTime('yyyy/MM/dd hh:mm:ss', FdateTimeAddition); end; procedure TRent.FsetDateTimeAddition(dateTimeAddition:string); begin try FdateTimeAddition := StrToDateTime(dateTimeAddition); except FdateTimeAddition := Now(); end; end; constructor TRentLiving.Create; begin inherited Create; self.conditions := TIntegerHash.Create; self.images := TObjectHash.Create; self.PDFs := TObjectHash.Create; end; destructor TRentLiving.Destroy; begin self.conditions.Free; self.images.Free; self.PDFs.Free; inherited; end; constructor TRentBusiness.Create; begin inherited Create; self.conditions := TIntegerHash.Create; self.images := TObjectHash.Create; self.PDFs := TObjectHash.Create; end; destructor TRentBusiness.Destroy; begin self.conditions.Free; self.images.Free; self.PDFs.Free; inherited; end; function TRentEx.FgetDateTimeVacancyChecked: TDateTime; begin result := FDateTimeVacancyChecked; end; procedure TRentEx.FsetDateTimeVacancyChecked(dateTimeVacancyChecked:TDateTime); begin FDateTimeVacancyChecked := dateTimeVacancyChecked; end; function TRentEx.FgetDateTimeVacancyCheckedAsString: string; begin result := FormatDateTime('yyyy/MM/dd hh:mm:ss', FDateTimeVacancyChecked); end; procedure TRentEx.FsetDateTimeVacancyChecked(dateTimeVacancyChecked:string); begin try FDateTimeVacancyChecked := StrToDateTime(dateTimeVacancyChecked); except // end; end; function TRentEx.FgetDateBuildYearMonth: TDateTime; begin result := FDateBuildYearMonth; end; procedure TRentEx.FsetDateBuildYearMonth(dateBuildYearMonth:TDateTime); begin FDateBuildYearMonth := dateBuildYearMonth; end; function TRentEx.FgetDateBuildYearMonthAsString: string; begin result := FormatDateTime('yyyy/MM/dd', FDateBuildYearMonth) end; procedure TRentEx.FsetDateBuildYearMonth(dateBuildYearMonth:string); begin try FDateBuildYearMonth := StrToDateTime(dateBuildYearMonth); except // end; end; end.
unit uProduto; interface type TProduto = class strict private FCODIGO: String; FCONTROLE: String; FPRECO: double; FDESCRICAO: string; procedure SetCodigo(val: String); function GetCodigo: String; procedure SetControle(val: String); function GetControle: String; procedure SetPreco(val: double); function GetPreco: double; procedure SetDescricao(val: String); function GetDescricao: String; public property CODIGO: String read GetCodigo write SetCodigo; property CONTROLE: String read GetControle write SetControle; property PRECO: double read GetPreco write SetPreco; property DESCRICAO: String read GetDescricao write SetDescricao; constructor Create; destructor Destroy; override; end; implementation constructor TProduto.Create; begin inherited Create; end; destructor TProduto.Destroy; begin inherited Destroy; end; function TProduto.GetCodigo: String; begin Result := FCODIGO; end; function TProduto.GetControle: String; begin Result := FCONTROLE; end; function TProduto.GetDescricao: String; begin Result := FDESCRICAO; end; function TProduto.GetPreco: double; begin Result := FPRECO; end; procedure TProduto.SetCodigo(val: String); begin FCODIGO := val; end; procedure TProduto.SetControle(val: String); begin FCONTROLE := val; end; procedure TProduto.SetDescricao(val: String); begin FDESCRICAO := val; end; procedure TProduto.SetPreco(val: double); begin FPRECO := val; end; end.
Unit Utils; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} Interface Uses Vcl.Graphics; Procedure ErrorMessage(AMsg:WideString); Procedure WarningMessage(AMsg:WideString); Procedure InformationMessage(AMsg:WideString); Procedure WinErrorMessage(AMsg:WideString; ACode:Cardinal); Function BufferToHex(ABuffer:Pointer; ASize:NativeUInt):WideString; Procedure ColorToComponents(AColor:TColor; Var AR,AG,AB:Cardinal); Function ColorLuminance(AColor:TColor):Cardinal; Function ColorLuminanceHeur(AColor:TColor):Cardinal; Function IsAdmin:Boolean; {$IFDEF FPC} Function UIntToStr(AValue:UInt64):WideString; {$ENDIF} Function StringEscape(AString:WideString):WideString; Implementation Uses Windows, SysUtils, Classes; Procedure ErrorMessage(AMsg:WideString); begin MessageBoxW(0, PWideChar(AMsg), 'Error', MB_OK Or MB_ICONERROR); end; Procedure WarningMessage(AMsg:WideString); begin MessageBoxW(0, PWideChar(AMsg), 'Warning', MB_OK Or MB_ICONERROR); end; Procedure InformationMessage(AMsg:WideString); begin MessageBoxW(0, PWideChar(AMsg), 'Information', MB_OK Or MB_ICONINFORMATION); end; Procedure WinErrorMessage(AMsg:WideString; ACode:Cardinal); Var msg : WideString; begin msg := Format('%s'#13#10'Error code: %u'#13#10'Error message: %s', [AMsg, ACode, SysErrorMessage(ACode)]); ErrorMessage(msg); end; Function BufferToHex(ABuffer:Pointer; ASize:NativeUInt):WideString; Var l : TStringList; d : PByte; hexLine : WideString; dispLine : WideString; index : Integer; I : Integer; begin l := TStringList.Create; hexLine := ''; dispLine := ''; index := 0; d := ABuffer; For I := 0 To ASize - 1 Do begin hexLine := hexLine + ' ' + IntToHex(d^, 2); If d^ >= Ord(' ') Then dispLine := dispLine + Chr(d^) Else dispLine := dispLine + '.'; Inc(Index); Inc(d); If index = 16 Then begin l.Add(Format('%s %s', [hexLine, dispLine])); hexLine := ''; dispLine := ''; index := 0; end; end; If index > 0 Then begin For I := index To 16 - 1 Do hexLine := hexLine + ' '; l.Add(Format('%s %s', [hexLine, dispLine])); end; Result := l.Text; l.Free; end; Procedure ColorToComponents(AColor:TColor; Var AR,AG,AB:Cardinal); begin AR := (AColor And $0000FF); AG := (AColor Shr 8) ANd $FF; AB := (AColor Shr 16) And $FF; end; Function ColorLuminance(AColor:TColor):Cardinal; Const weights : Array [0..2] Of Double = ( 0.2126, 0.7152, 0.0722 ); Var cd : Double; I : Integer; components : Array [0..2] Of Cardinal; begin Result := 0; ColorToComponents(AColor, components[0], components[1], components[2]); For I := Low(components) To High(components) Do begin cd := components[I] / 255.0; If (cd <= 0.03928) Then cd := cd /12.92 Else cd := Exp(ln((cd + 0.055) / 1.055)*2.4); Inc(Result, Trunc(weights[I]*cd*10000.0)); end; end; Function ColorLuminanceHeur(AColor:TColor):Cardinal; Var r, g, b : Cardinal; begin ColorToComponents(AColor, r, g, b); Result := (r*2990 + g*5870 + b*1140) Div 1000; end; {$IFDEF FPC} Function UIntToStr(AValue:UInt64):WideString; Var digit : Cardinal; begin Result := ''; If AValue > 0 Then begin Repeat digit := AValue Mod 10; AValue := AValue Div 10; Result := Chr(digit + Ord('0')) + Result; Until AValue = 0; end Else Result := '0'; end; {$ENDIF} Function CheckTokenMembership(AToken:THandle; ASid:PSID; Var AAdmin:BOOL):BOOL; StdCall; External 'advapi32.dll'; Function IsAdmin:Boolean; const SECURITY_NT_AUTHORITY: TSIDIdentifierAuthority = (Value: (0, 0, 0, 0, 0, 5)); SECURITY_BUILTIN_DOMAIN_RID = $00000020; DOMAIN_ALIAS_RID_ADMINS = $00000220; var b: BOOL; AdministratorsGroup: PSID; begin Result := False; If AllocateAndInitializeSid( SECURITY_NT_AUTHORITY, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, AdministratorsGroup) Then begin If CheckTokenMembership(0, AdministratorsGroup, b) then Result := b; FreeSid(AdministratorsGroup); end; end; Function StringEscape(AString:WideString):WideString; Var ch : WideChar; I : Integer; begin Result := ''; For I := 1 To Length(AString) Do begin ch := AString[I]; Case ch Of #8 : Result := Result + '\b'; #10 : Result := Result + '\n'; #13 : Result := Result + '\r'; #27 : Result := Result + '\e'; '"' : Result := Result + '\"'; '\' : Result := Result + '\\'; '''' : Result := Result + '\'''; Else Result := Result + ch; end; end; end; End.
{ The MIT License (MIT) Copyright (c) 2014 FMXExpress.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. } unit GameAudioManager; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, FMX.Dialogs, FMX.Forms {$IFDEF ANDROID} , androidapi.jni.media, FMX.Helpers.Android, androidapi.jni.JavaTypes, androidapi.jni.GraphicsContentViewText, androidapi.JNIBridge, androidapi.Helpers {$ENDIF} {$IFDEF IOS} , MacApi.CoreFoundation, FMX.Platform.iOS, iOSapi.CocoaTypes, iOSapi.AVFoundation, iOSapi.Foundation {$ELSE} {$IFDEF MACOS} , MacApi.CoreFoundation, FMX.Platform.Mac, MacApi.CocoaTypes, MacApi.AppKit, MacApi.Foundation {$ENDIF} {$ENDIF} {$IFDEF MSWINDOWS} , MMSystem {$ENDIF} ; type TSoundRec = record SFilename: String; SName: String; SNameExt: string; SID: integer; end; PSoundRec = ^TSoundRec; {$IFDEF ANDROID} TOnSpoolLoadCallBack = class(TJavaLocal, JSoundPool_OnLoadCompleteListener) private public procedure onLoadComplete(soundPool: JSoundPool; sampleId, status: integer); cdecl; end; {$ENDIF} TGameAudioManager = Class Private fSoundsList: TList; {$IFDEF ANDROID} fAudioMgr: JAudioManager; fSoundPool: JSoundPool; {$ENDIF} function GetSoundsCount: integer; function GetSoundFromIndex(Aindex: integer): PSoundRec; Public Constructor Create; Destructor Destroy; override; function AddSound(ASoundFile: string): integer; procedure DeleteSound(AName: String); overload; procedure DeleteSound(Aindex: integer); overload; procedure PlaySound(AName: String); overload; procedure PlaySound(Aindex: integer); overload; property SoundsCount: integer read GetSoundsCount; property Sounds[Aindex: integer]: PSoundRec read GetSoundFromIndex; end; var GLoaded: Boolean; {$IFDEF IOS} Const _libAudioToolbox = '/System/Library/Frameworks/AudioToolbox.framework/AudioToolbox'; procedure AudioServicesPlaySystemSound(inSystemSoundID: integer); cdecl; external _libAudioToolbox name 'AudioServicesPlaySystemSound'; procedure AudioServicesCreateSystemSoundID(inFileURL: CFURLRef; var SystemSoundID: pinteger); cdecl; external _libAudioToolbox name 'AudioServicesCreateSystemSoundID'; procedure AudioServicesDisposeSystemSoundID(inSystemSoundID: integer); cdecl; external _libAudioToolbox name 'AudioServicesDisposeSystemSoundID'; procedure AudioServicesAddSystemSoundCompletion(inSystemSoundID: integer; inRunLoop: CFRunLoopRef; inRunLoopMode: CFStringRef; inCompletionRoutine: Pointer; inClientData: CFURLRef); cdecl; external _libAudioToolbox name 'AudioServicesAddSystemSoundCompletion'; {$ENDIF} implementation { TGameAudioManager } {$IFDEF ANDROID} procedure TOnSpoolLoadCallBack.onLoadComplete(soundPool: JSoundPool; sampleId, status: integer); begin GLoaded := True; end; {$ENDIF} {$IF Defined(IOS) OR Defined(MACOS)} procedure oncompleteionIosProc(SystemSndID: integer; var AData: Pointer); begin // place here the code to run when a sound finish playing end; {$ENDIF} constructor TGameAudioManager.Create; begin try fSoundsList := TList.Create; {$IFDEF ANDROID} fAudioMgr := TJAudioManager.Wrap ((SharedActivity.getSystemService(TJContext.JavaClass.AUDIO_SERVICE) as ILocalObject).GetObjectID); fSoundPool := TJSoundPool.JavaClass.init(4, TJAudioManager.JavaClass.STREAM_MUSIC, 0); {$ENDIF} except On E: Exception do Raise Exception.Create('[TGameAudioManager.Create] : ' + E.message); end; end; destructor TGameAudioManager.Destroy; var i: integer; wRec: PSoundRec; begin try for i := fSoundsList.Count - 1 downto 0 do begin wRec := fSoundsList[i]; Dispose(wRec); fSoundsList.Delete(i); end; fSoundsList.Free; {$IFDEF ANDROID} fSoundPool := nil; fAudioMgr := nil; {$ENDIF} inherited; except On E: Exception do Raise Exception.Create('[TGameAudioManager.Destroy] : ' + E.message); end; end; function TGameAudioManager.AddSound(ASoundFile: string): integer; var wSndRec: PSoundRec; {$IFDEF ANDROID} wOnAndroidSndComplete: JSoundPool_OnLoadCompleteListener; {$ENDIF} {$IFDEF IOS} wSndID: integer; wNSURL: CFURLRef; wNSFilename: CFStringRef; {$ENDIF} begin try New(wSndRec); wSndRec.SFilename := ASoundFile; wSndRec.SNameExt := ExtractFilename(ASoundFile); wSndRec.SName := ChangeFileExt(wSndRec.SNameExt, ''); {$IFDEF ANDROID} wOnAndroidSndComplete := TJSoundPool_OnLoadCompleteListener.Wrap ((TOnSpoolLoadCallBack.Create as ILocalObject).GetObjectID); fSoundPool.setOnLoadCompleteListener(wOnAndroidSndComplete); GLoaded := False; wSndRec.SID := fSoundPool.load(StringToJString(ASoundFile), 0); while not GLoaded do begin Sleep(10); Application.ProcessMessages; end; {$ENDIF} {$IFDEF IOS} wNSFilename := CFStringCreateWithCharacters(nil, PChar(ASoundFile), Length(ASoundFile)); wNSURL := CFURLCreateWithFileSystemPath(nil, wNSFilename, kCFURLPOSIXPathStyle, False); AudioServicesCreateSystemSoundID(wNSURL, pinteger(wSndID)); wSndRec.SID := wSndID; AudioServicesAddSystemSoundCompletion(wSndID, nil, nil, @oncompleteionIosProc, nil); {$ENDIF} Result := fSoundsList.Add(wSndRec); except On E: Exception do Raise Exception.Create('[TGameAudioManager.AddSound] : ' + E.message); end; end; procedure TGameAudioManager.DeleteSound(Aindex: integer); var wRec: PSoundRec; begin try if Aindex < fSoundsList.Count then begin wRec := fSoundsList[Aindex]; {$IFDEF ANDROID} fSoundPool.unload(wRec.SID); {$ENDIF} {$IFDEF IOS} AudioServicesDisposeSystemSoundID(wRec.SID); {$ENDIF} Dispose(wRec); fSoundsList.Delete(Aindex); end; except On E: Exception do Raise Exception.Create('[TGameAudioManager.DeleteSound] : ' + E.message); end; end; procedure TGameAudioManager.DeleteSound(AName: String); var i: integer; begin try for i := 0 to fSoundsList.Count - 1 do begin if CompareText(PSoundRec(fSoundsList[i]).SName, AName) = 0 then begin DeleteSound(i); Break; end; end; except On E: Exception do Raise Exception.Create('[TGameAudioManager.PlaySound] : ' + E.message); end; end; procedure TGameAudioManager.PlaySound(Aindex: integer); var wRec: PSoundRec; {$IFDEF ANDROID} wCurrVolume, wMaxVolume: Double; wVolume: Double; {$ENDIF} {$IFNDEF IOS} {$IFDEF MACOS} wNssound: NSSound; {$ENDIF} {$ENDIF} begin try if Aindex < fSoundsList.Count then begin wRec := fSoundsList[Aindex]; {$IFDEF ANDROID} if Assigned(fAudioMgr) then begin wCurrVolume := fAudioMgr.getStreamVolume (TJAudioManager.JavaClass.STREAM_MUSIC); wMaxVolume := fAudioMgr.getStreamMaxVolume (TJAudioManager.JavaClass.STREAM_MUSIC); wVolume := wCurrVolume / wMaxVolume; fSoundPool.play(wRec.SID, wVolume, wVolume, 1, 0, 1); end; {$ENDIF} {$IFDEF IOS} AudioServicesAddSystemSoundCompletion(wRec.SID, nil, nil, @oncompleteionIosProc, nil); AudioServicesPlaySystemSound(wRec.SID) {$ELSE} {$IFDEF MACOS} wNssound := TNSSound.Wrap (TNSSound.OCClass.soundNamed(NSSTR(wRec.SNameExt))); try wNssound.setLoops(False); wNssound.play; finally wNssound.Release; end; {$ENDIF} {$ENDIF} {$IFDEF MSWINDOWS} sndPlaySound(PChar(wRec.SFilename), SND_NODEFAULT Or SND_ASYNC); {$ENDIF} end; except On E: Exception do Raise Exception.Create('[Unknown Name] : ' + E.message); end; end; procedure TGameAudioManager.PlaySound(AName: String); var i: integer; begin try for i := 0 to fSoundsList.Count - 1 do begin if CompareText(PSoundRec(fSoundsList[i]).SName, AName) = 0 then begin PlaySound(i); Break; end; end; except On E: Exception do Raise Exception.Create('[TGameAudioManager.PlaySound] : ' + E.message); end; end; function TGameAudioManager.GetSoundsCount: integer; begin Result := fSoundsList.Count; end; function TGameAudioManager.GetSoundFromIndex(Aindex: integer): PSoundRec; begin if Aindex < fSoundsList.Count then Result := fSoundsList[Aindex] else Result := nil; end; end.
unit uPrint; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Buttons, StdCtrls, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxSpinEdit, cxCheckBox, ActnList, cxLookAndFeelPainters, cxButtons, DateUtils, uMainPerem; type TPrintForm = class(TForm) cxReport: TcxComboBox; lbl1: TLabel; chbPrinter: TcxCheckBox; chbChoosePrinter: TcxCheckBox; lbl2: TLabel; cxCopies: TcxSpinEdit; cxCheckEdit: TcxCheckBox; actlst1: TActionList; act1: TAction; btn1: TcxButton; btn2: TcxButton; actOk: TAction; actClose: TAction; cxBeg: TcxSpinEdit; lbl3: TLabel; lbl4: TLabel; cxEnd: TcxSpinEdit; cxMonthEnd: TcxComboBox; cxMonthBeg: TcxComboBox; procedure FormCreate(Sender: TObject); procedure act1Execute(Sender: TObject); procedure actOkExecute(Sender: TObject); procedure actCloseExecute(Sender: TObject); procedure cxReportPropertiesChange(Sender: TObject); private { Private declarations } public { Public declarations } end; var PrintForm: TPrintForm; implementation {$R *.dfm} procedure TPrintForm.FormCreate(Sender: TObject); var month, year:Word; begin cxReport.ItemIndex:=0; cxCopies.Value:=1; cxCheckEdit.Visible:=False; month:=MonthOf(PERS_PAY_PERIOD); year:=YearOf(PERS_PAY_PERIOD); cxMonthBeg.ItemIndex:=month-1; cxBeg.value:=year; cxMonthEnd.ItemIndex:=month-1; cxEnd.value:=year; cxMonthEnd.Enabled:=False; cxMonthBeg.Enabled:=False; cxBeg.Enabled:=False; cxEnd.Enabled:=False; lbl3.Enabled:=False; lbl4.Enabled:=False; chbChoosePrinter.Checked:=True; if ID_SYSTEM = 'STUD_CITY' then cxReport.Properties.Items.Add('Список боржників за період'); end; procedure TPrintForm.act1Execute(Sender: TObject); begin cxCheckEdit.Visible:=not(cxCheckEdit.Visible); end; procedure TPrintForm.actOkExecute(Sender: TObject); begin ModalResult:=mrOk; end; procedure TPrintForm.actCloseExecute(Sender: TObject); begin Close; end; procedure TPrintForm.cxReportPropertiesChange(Sender: TObject); begin if ((cxReport.ItemIndex = 3) or (cxReport.ItemIndex = 4) or (cxReport.ItemIndex = 6)) then begin cxMonthEnd.Enabled:=True; cxMonthBeg.Enabled:=True; cxBeg.Enabled:=True; cxEnd.Enabled:=True; lbl3.Enabled:=True; lbl4.Enabled:=True; end else begin cxMonthEnd.Enabled:=False; cxMonthBeg.Enabled:=False; cxBeg.Enabled:=False; cxEnd.Enabled:=False; lbl3.Enabled:=False; lbl4.Enabled:=False; end; end; end.
unit Objekt.DHLDeletionState; interface uses SysUtils, Classes, geschaeftskundenversand_api_2, Objekt.DHLStatusInformation; type TDHLDeletionState = class private fStatus: TDHLStatusinformation; fShipmentNumber: string; public constructor Create; destructor Destroy; override; property Status: TDHLStatusinformation read fStatus write fStatus; property ShipmentNumber: string read fShipmentNumber write fShipmentNumber; end; implementation { TDHLDeletionState } constructor TDHLDeletionState.Create; begin fStatus := TDHLStatusinformation.Create; end; destructor TDHLDeletionState.Destroy; begin FreeAndNil(fStatus); inherited; end; end.
unit OthelloCounters; interface uses FMX.Objects3D, System.Classes, FMX.MaterialSources, FMX.Ani, FMX.Types, FMX.Types3D, FMX.Dialogs; type TOthelloBlackMaterial = class(TLightMaterialSource) public constructor Create(aOwner : TComponent); reintroduce; end; TOthelloWhiteMaterial = class(TLightMaterialSource) public constructor Create(aOwner : TComponent); reintroduce; end; TOthelloState = (Unset, Black, White); TOthelloCounter = class(TDummy) type TOthelloCylinder = class(TCylinder) private FSphere : TSphere; procedure SetSubdivisionsAxes(const Value: Integer); function GetDepth: Single; function GetHeight: Single; function GetSubdivisionsAxes: Integer; function GetWidth: Single; function GetMaterialSource: TMaterialSource; procedure SetMaterialSource(const Value: TMaterialSource); protected procedure SetDepth(const Value: Single); reintroduce; procedure SetHeight(const Value: Single); reintroduce; procedure SetWidth(const Value: Single); reintroduce; public constructor Create(aOwner : TComponent; aOffset: Single); reintroduce; destructor Destroy; override; property Width : Single read GetWidth write SetWidth; property Height : Single read GetHeight write SetHeight; property Depth : Single read GetDepth write SetDepth; property SubdivisionsAxes : Integer read GetSubdivisionsAxes write SetSubdivisionsAxes; property MaterialSource : TMaterialSource read GetMaterialSource write SetMaterialSource; end; //const CylinderHeight = 0.2; strict private FBlackSide, FWhiteSide : TOthelloCylinder; FCounterState: TOthelloState; private function GetBlackMaterialSource: TMaterialSource; function GetWhiteMaterialSource: TMaterialSource; procedure SetBlackMaterialSource(const Value: TMaterialSource); procedure SetWhiteMaterialSource(const Value: TMaterialSource); procedure SetCounterState(const Value: TOthelloState); public constructor Create(aOwner : TComponent; aTileSize:Single; aBlackMaterial, aWhiteMaterial : TMaterialSource); reintroduce; property BlackMaterialSource : TMaterialSource read GetBlackMaterialSource write SetBlackMaterialSource; property WhiteMaterialSource : TMaterialSource read GetWhiteMaterialSource write SetWhiteMaterialSource; property CounterState : TOthelloState read FCounterState write SetCounterState; end; implementation uses System.UITypes, System.SysUtils; { TOthelloCounter } constructor TOthelloCounter.Create(aOwner: TComponent; aTileSize:Single; aBlackMaterial, aWhiteMaterial : TMaterialSource); function CreateCylinder(aPosition : Single): TOthelloCylinder; begin // Sort position in Dummy Result := TOthelloCylinder.Create(Self,aPosition); REsult.Parent := Self; Result.Height := aTileSize; Result.Width := aTileSize*4; Result.Depth := aTileSize; Result.SubdivisionsAxes := 32; end; begin inherited Create(aOwner); // The Counter is made up of two cylinders with 2 spheres. FBlackSide := CreateCylinder(aTileSize/2); FWhiteSide := CreateCylinder(-aTileSize/2); BlackMaterialSource := aBlackMaterial; WhiteMaterialSource := aWhiteMaterial; Self.Scale.X := 0.25; Self.Scale.Y := 0.25; Self.RotationAngle.X := -90; end; function TOthelloCounter.GetBlackMaterialSource: TMaterialSource; begin Assert(FBlackSide <> nil); Result := FBlackSide.MaterialSource; end; function TOthelloCounter.GetWhiteMaterialSource: TMaterialSource; begin Assert(FWhiteSide <> nil); Result := FWhiteSide.MaterialSource; end; procedure TOthelloCounter.SetBlackMaterialSource( const Value: TMaterialSource); begin Assert(FBlackSide <> nil); FBlackSide.MaterialSource := Value; end; procedure TOthelloCounter.SetCounterState(const Value: TOthelloState); begin if CounterState = Unset then begin case Value of Black: Self.RotationAngle.Z := 0; White: Self.RotationAngle.Z := 180; end; FCounterState := Value; end else if FCounterState <> Value then begin Self.AnimateFloat('RotationAngle.Z', Self.RotationAngle.Z+180, 1, TAnimationType.atInOut, TInterpolationType.itBack); Self.AnimateFloat('Position.Z', -2, 0.5); Self.AnimateFloatDelay('Position.Z', 0, 0.5, 0.5); FCounterState := Value; end; end; procedure TOthelloCounter.SetWhiteMaterialSource( const Value: TMaterialSource); begin Assert(FBlackSide <> nil); FWhiteSide.MaterialSource := Value; end; { TOthelloWhiteMaterial } constructor TOthelloWhiteMaterial.Create(aOwner: TComponent); begin inherited; Diffuse := TAlphaColorRec.White; Ambient := TAlphaColor($FF202020); Emissive := TAlphaColorRec.Null; Specular := TAlphaColor($FF606060); Shininess := 30; end; { TOthelloBlackMaterial } constructor TOthelloBlackMaterial.Create(aOwner: TComponent); begin inherited; Diffuse := TAlphaColor($FF202020); Ambient := TAlphaColor($FF202020); Emissive := TAlphaColorRec.Null; Specular := TAlphaColor($FF606060); Shininess := 30; end; { TOthelloCounter.TOthelloCylinder } constructor TOthelloCounter.TOthelloCylinder.Create(aOwner: TComponent; aOffset: Single); begin inherited Create(aOwner); FSphere := TSphere.Create(Self); FSphere.Parent := Self; // Setup current rotation angles Self.RotationAngle.X := 0; Self.RotationAngle.Y := 0; Self.RotationAngle.Z := 0; Self.SubdivisionsAxes := 32; Self.Position.Y := aOffset; FSphere.Position.Y := aOffset; FSphere.SubdivisionsHeight := 24; end; destructor TOthelloCounter.TOthelloCylinder.Destroy; begin FreeAndNil(FSphere); inherited; end; function TOthelloCounter.TOthelloCylinder.GetDepth: Single; begin Result := inherited Depth; end; function TOthelloCounter.TOthelloCylinder.GetHeight: Single; begin Result := inherited Height; end; function TOthelloCounter.TOthelloCylinder.GetMaterialSource: TMaterialSource; begin Result := inherited MaterialSource; end; function TOthelloCounter.TOthelloCylinder.GetSubdivisionsAxes: Integer; begin Result := inherited SubdivisionsAxes; end; function TOthelloCounter.TOthelloCylinder.GetWidth: Single; begin Result := inherited Width; end; procedure TOthelloCounter.TOthelloCylinder.SetDepth(const Value: Single); begin inherited Depth := Value; FSphere.Depth := Value; end; procedure TOthelloCounter.TOthelloCylinder.SetHeight(const Value: Single); begin inherited Height := Value; // FSphere.Height := Value; end; procedure TOthelloCounter.TOthelloCylinder.SetMaterialSource( const Value: TMaterialSource); begin inherited MaterialSource := Value; FSphere.MaterialSource := Value; end; procedure TOthelloCounter.TOthelloCylinder.SetSubdivisionsAxes( const Value: Integer); begin inherited SubdivisionsAxes := Value; FSphere.SubdivisionsAxes := Value; end; procedure TOthelloCounter.TOthelloCylinder.SetWidth(const Value: Single); begin inherited Width := Value; FSphere.Width := Value; end; end.
{ *****************************************************************} { Added Support for RoundRect (GraphicsPath + TGPGraphics) } { } { date : 05-11-2006 } { } { email : martin.walter@winningcubed.de } { } { *****************************************************************} unit GDIPOBJ2; interface uses Winapi.GDIPAPI, Winapi.GDIPOBJ; type TGPGraphicsPath2 = class(TGPGraphicsPath) public function AddRoundRect(Rect: TGPRectF; RX, RY: Single): TStatus; overload; function AddRoundRect(X, Y, Width, Height, RX, RY: Single): TStatus; overload; function Clone: TGPGraphicsPath2; end; implementation { TGPGraphicsPath2 } function TGPGraphicsPath2.AddRoundRect(Rect: TGPRectF; RX, RY: Single): TStatus; begin Result := AddRoundRect(Rect.X, Rect.Y, Rect.Width, Rect.Height, RX, RY); end; function TGPGraphicsPath2.AddRoundRect(X, Y, Width, Height, RX, RY: Single) : TStatus; begin Result := AddLine(X + RX, Y, X + Width - RX, Y); if Result <> OK then Exit; Result := AddArc(X + Width - 2 * RX, Y, 2 * RX, 2 * RY, 270, 90); if Result <> OK then Exit; Result := AddLine(X + Width, Y + RY,X + Width, Y + Height - RY); if Result <> OK then Exit; Result := AddArc(X + Width - 2 * RX, Y + Height - 2 * RY, 2 * RX, 2 * RY, 0, 90); if Result <> OK then Exit; Result := AddLine(X + Width - RX, Y + Height, X + RX, Y + Height); if Result <> OK then Exit; Result := AddArc(X, Y + Height - 2 * RY, 2 * RX, 2 * RY, 90, 90); if Result <> OK then Exit; Result := AddLine(X, Y + Height - RY, X, Y + RY); if Result <> OK then Exit; Result := AddArc(X, Y, 2 * RX, 2 * RY, 180, 90); if Result <> OK then Exit; Result := CloseFigure; end; function TGPGraphicsPath2.Clone: TGPGraphicsPath2; var ClonePath: GpPath; begin Clonepath := nil; SetStatus(GdipClonePath(nativePath, Clonepath)); result := TGPGraphicsPath2.Create(ClonePath); end; end.
unit o_baselistobj; interface uses SysUtils, Classes, Contnrs; type TBaseListObj = class private function GetCount: Integer; protected _List: TObjectList; public constructor Create; virtual; destructor Destroy; override; property Count: Integer read GetCount; procedure Delete(aIndex: Integer); procedure Clear; virtual; end; implementation { TBaseListObj } procedure TBaseListObj.Clear; begin _List.Clear; end; constructor TBaseListObj.Create; begin _List := TObjectList.Create; end; procedure TBaseListObj.Delete(aIndex: Integer); begin if aIndex > _List.Count then exit; _List.Delete(aIndex); end; destructor TBaseListObj.Destroy; begin FreeAndNil(_List); inherited; end; function TBaseListObj.GetCount: Integer; begin Result := _List.Count; end; end.
unit CustomAlphabetTest; interface uses DUnitX.TestFramework, uEnums, uIntXLibTypes, uIntX; type [TestFixture] TCustomAlphabetTest = class(TObject) public procedure AlphabetNull(); [Test] procedure CallAlphabetNull(); procedure AlphabetShort(); [Test] procedure CallAlphabetShort(); procedure AlphabetRepeatingChars(); [Test] procedure CallAlphabetRepeatingChars(); [Test] procedure Parse(); [Test] procedure ToStringTest(); end; implementation procedure TCustomAlphabetTest.AlphabetNull(); begin TIntX.Parse('', 20, pmFast); end; [Test] procedure TCustomAlphabetTest.CallAlphabetNull(); var TempMethod: TTestLocalMethod; begin TempMethod := AlphabetNull; Assert.WillRaise(TempMethod, EArgumentNilException); end; procedure TCustomAlphabetTest.AlphabetShort(); begin TIntX.Parse('', 20, '1234'); end; [Test] procedure TCustomAlphabetTest.CallAlphabetShort(); var TempMethod: TTestLocalMethod; begin TempMethod := AlphabetShort; Assert.WillRaise(TempMethod, EArgumentException); end; procedure TCustomAlphabetTest.AlphabetRepeatingChars(); begin TIntX.Parse('', 20, '0123456789ABCDEFGHIJ0'); end; [Test] procedure TCustomAlphabetTest.CallAlphabetRepeatingChars(); var TempMethod: TTestLocalMethod; begin TempMethod := AlphabetRepeatingChars; Assert.WillRaise(TempMethod, EArgumentException); end; [Test] procedure TCustomAlphabetTest.Parse(); begin Assert.AreEqual(19 * 20 + 18, Integer(TIntX.Parse('JI', 20, '0123456789ABCDEFGHIJ'))); end; [Test] procedure TCustomAlphabetTest.ToStringTest(); begin Assert.AreEqual('JI', TIntX.Create(19 * 20 + 18).ToString(20, '0123456789ABCDEFGHIJ')); end; initialization TDUnitX.RegisterTestFixture(TCustomAlphabetTest); end.
(* Category: SWAG Title: MENU MANAGEMENT ROUTINES Original name: 0010.PAS Description: Another Pickable Litebar Menu Author: KIM FORWOOD Date: 05-31-96 09:16 *) {============================================================================} PROGRAM LightBar; uses Crt; const UPARROW = #72; DNARROW = #80; PAGEUP = #73; PAGEDN = #81; HOMEKEY = #71; ENDKEY = #79; ENTER = #13; NUMITEMS = 4; StrLen = 14; ListArray : array[1..NUMITEMS] of string[StrLen] = ('Apples', 'Oranges', 'Bananas', 'Cumquats'); var Ch: char; CurrPos, OldPos: byte; PROCEDURE InitMenuBox(x,y: byte); var I: byte; begin Window(x,y,x+StrLen,y+NUMITEMS-1); TextAttr := $70; ClrScr; for I := 1 to NUMITEMS do begin GotoXY(1,I); Write(' ',ListArray[I]); end; CurrPos := 1; end; PROCEDURE GetKey(var Ch: char); begin Ch := UpCase(ReadKey); if Ch = #0 then Ch := UpCase(ReadKey); end; PROCEDURE WriteString(Place,Attr: byte); begin GotoXY(1,Place); TextAttr := Attr; ClrEol; Write(' ',ListArray[Place]); end; BEGIN InitMenuBox(10,3); repeat OldPos := CurrPos; WriteString(CurrPos,$30); GetKey(Ch); case Ch of UPARROW: if CurrPos > 1 then Dec(CurrPos) else CurrPos := NUMITEMS; DNARROW: if CurrPos < NUMITEMS then Inc(CurrPos) else CurrPos := 1; PAGEUP : CurrPos := 1; PAGEDN : CurrPos := NUMITEMS; HOMEKEY: CurrPos := 1; ENDKEY : CurrPos := NUMITEMS; ENTER : case CurrPos of 1: {Apples}; 2: {Oranges}; 3: {Bananas}; 4: {Cumquats}; end; else ; end; WriteString(OldPos,$70); until Ch = #27; Window(1,1,80,25); TextAttr := $07; ClrScr; END. {============================================================================}
program SDLTypeChecker; uses SDL, SysUtils; procedure outputEnum_SDL_bool(); var _SDL_bool : SDL_bool; begin WriteLn('Base Enum: SDL_bool Size: ', sizeof(SDL_bool)); for _SDL_bool := Low(SDL_bool) to High(SDL_bool) do begin try WriteLn(_SDL_bool, ' Value: ', LongInt(_SDL_bool)); except end; end; end; procedure outputEnum_SDL_DUMMY_ENUM(); var _SDL_DUMMY_ENUM : SDL_DUMMY_ENUM; begin WriteLn('Base Enum: SDL_DUMMY_ENUM Size: ', sizeof(SDL_DUMMY_ENUM)); for _SDL_DUMMY_ENUM := Low(SDL_DUMMY_ENUM) to High(SDL_DUMMY_ENUM) do begin try WriteLn(_SDL_DUMMY_ENUM, ' Value: ', LongInt(_SDL_DUMMY_ENUM)); except end; end; end; procedure outputEnum_SDL_assert_state(); var _SDL_assert_state : SDL_assert_state; begin WriteLn('Base Enum: SDL_assert_state Size: ', sizeof(SDL_assert_state)); for _SDL_assert_state := Low(SDL_assert_state) to High(SDL_assert_state) do begin try WriteLn(_SDL_assert_state, ' Value: ', LongInt(_SDL_assert_state)); except end; end; end; procedure outputEnum_SDL_errorcode(); var _SDL_errorcode : SDL_errorcode; begin WriteLn('Base Enum: SDL_errorcode Size: ', sizeof(SDL_errorcode)); for _SDL_errorcode := Low(SDL_errorcode) to High(SDL_errorcode) do begin try WriteLn(_SDL_errorcode, ' Value: ', LongInt(_SDL_errorcode)); except end; end; end; procedure outputEnum_SDL_ThreadPriority(); var _SDL_ThreadPriority : SDL_ThreadPriority; begin WriteLn('Base Enum: SDL_ThreadPriority Size: ', sizeof(SDL_ThreadPriority)); for _SDL_ThreadPriority := Low(SDL_ThreadPriority) to High(SDL_ThreadPriority) do begin try WriteLn(_SDL_ThreadPriority, ' Value: ', LongInt(_SDL_ThreadPriority)); except end; end; end; procedure outputEnum_SDL_AudioStatus(); var _SDL_AudioStatus : SDL_AudioStatus; begin WriteLn('Base Enum: SDL_AudioStatus Size: ', sizeof(SDL_AudioStatus)); for _SDL_AudioStatus := Low(SDL_AudioStatus) to High(SDL_AudioStatus) do begin try WriteLn(_SDL_AudioStatus, ' Value: ', LongInt(_SDL_AudioStatus)); except end; end; end; procedure outputEnum_SDL_BlendMode(); var _SDL_BlendMode : SDL_BlendMode; begin WriteLn('Base Enum: SDL_BlendMode Size: ', sizeof(SDL_BlendMode)); for _SDL_BlendMode := Low(SDL_BlendMode) to High(SDL_BlendMode) do begin try WriteLn(_SDL_BlendMode, ' Value: ', LongInt(_SDL_BlendMode)); except end; end; end; procedure outputEnum_SDL_WindowFlags(); var _SDL_WindowFlags : SDL_WindowFlags; begin WriteLn('Base Enum: SDL_WindowFlags Size: ', sizeof(SDL_WindowFlags)); for _SDL_WindowFlags := Low(SDL_WindowFlags) to High(SDL_WindowFlags) do begin try WriteLn(_SDL_WindowFlags, ' Value: ', LongInt(_SDL_WindowFlags)); except end; end; end; procedure outputEnum_SDL_WindowEventID(); var _SDL_WindowEventID : SDL_WindowEventID; begin WriteLn('Base Enum: SDL_WindowEventID Size: ', sizeof(SDL_WindowEventID)); for _SDL_WindowEventID := Low(SDL_WindowEventID) to High(SDL_WindowEventID) do begin try WriteLn(_SDL_WindowEventID, ' Value: ', LongInt(_SDL_WindowEventID)); except end; end; end; procedure outputEnum_SDL_GLattr(); var _SDL_GLattr : SDL_GLattr; begin WriteLn('Base Enum: SDL_GLattr Size: ', sizeof(SDL_GLattr)); for _SDL_GLattr := Low(SDL_GLattr) to High(SDL_GLattr) do begin try WriteLn(_SDL_GLattr, ' Value: ', LongInt(_SDL_GLattr)); except end; end; end; procedure outputEnum_SDL_Scancode(); var _SDL_Scancode : SDL_Scancode; begin WriteLn('Base Enum: SDL_Scancode Size: ', sizeof(SDL_Scancode)); for _SDL_Scancode := Low(SDL_Scancode) to High(SDL_Scancode) do begin try WriteLn(_SDL_Scancode, ' Value: ', LongInt(_SDL_Scancode)); except end; end; end; procedure outputEnum_SDL_Keymod(); var _SDL_Keymod : SDL_Keymod; begin WriteLn('Base Enum: SDL_Keymod Size: ', sizeof(SDL_Keymod)); for _SDL_Keymod := Low(SDL_Keymod) to High(SDL_Keymod) do begin try WriteLn(_SDL_Keymod, ' Value: ', LongInt(_SDL_Keymod)); except end; end; end; procedure outputEnum_SDL_EventType(); var _SDL_EventType : SDL_EventType; begin WriteLn('Base Enum: SDL_EventType Size: ', sizeof(SDL_EventType)); for _SDL_EventType := Low(SDL_EventType) to High(SDL_EventType) do begin try WriteLn(_SDL_EventType, ' Value: ', LongInt(_SDL_EventType)); except end; end; end; procedure outputEnum_SDL_eventaction(); var _SDL_eventaction : SDL_eventaction; begin WriteLn('Base Enum: SDL_eventaction Size: ', sizeof(SDL_eventaction)); for _SDL_eventaction := Low(SDL_eventaction) to High(SDL_eventaction) do begin try WriteLn(_SDL_eventaction, ' Value: ', LongInt(_SDL_eventaction)); except end; end; end; procedure outputEnum_SDL_HintPriority(); var _SDL_HintPriority : SDL_HintPriority; begin WriteLn('Base Enum: SDL_HintPriority Size: ', sizeof(SDL_HintPriority)); for _SDL_HintPriority := Low(SDL_HintPriority) to High(SDL_HintPriority) do begin try WriteLn(_SDL_HintPriority, ' Value: ', LongInt(_SDL_HintPriority)); except end; end; end; procedure outputEnum_SDL_LogPriority(); var _SDL_LogPriority : SDL_LogPriority; begin WriteLn('Base Enum: SDL_LogPriority Size: ', sizeof(SDL_LogPriority)); for _SDL_LogPriority := Low(SDL_LogPriority) to High(SDL_LogPriority) do begin try WriteLn(_SDL_LogPriority, ' Value: ', LongInt(_SDL_LogPriority)); except end; end; end; procedure outputEnum_SDL_PowerState(); var _SDL_PowerState : SDL_PowerState; begin WriteLn('Base Enum: SDL_PowerState Size: ', sizeof(SDL_PowerState)); for _SDL_PowerState := Low(SDL_PowerState) to High(SDL_PowerState) do begin try WriteLn(_SDL_PowerState, ' Value: ', LongInt(_SDL_PowerState)); except end; end; end; procedure outputEnum_SDL_RendererFlags(); var _SDL_RendererFlags : SDL_RendererFlags; begin WriteLn('Base Enum: SDL_RendererFlags Size: ', sizeof(SDL_RendererFlags)); for _SDL_RendererFlags := Low(SDL_RendererFlags) to High(SDL_RendererFlags) do begin try WriteLn(_SDL_RendererFlags, ' Value: ', LongInt(_SDL_RendererFlags)); except end; end; end; procedure outputEnum_SDL_TextureAccess(); var _SDL_TextureAccess : SDL_TextureAccess; begin WriteLn('Base Enum: SDL_TextureAccess Size: ', sizeof(SDL_TextureAccess)); for _SDL_TextureAccess := Low(SDL_TextureAccess) to High(SDL_TextureAccess) do begin try WriteLn(_SDL_TextureAccess, ' Value: ', LongInt(_SDL_TextureAccess)); except end; end; end; procedure outputEnum_SDL_TextureModulate(); var _SDL_TextureModulate : SDL_TextureModulate; begin WriteLn('Base Enum: SDL_TextureModulate Size: ', sizeof(SDL_TextureModulate)); for _SDL_TextureModulate := Low(SDL_TextureModulate) to High(SDL_TextureModulate) do begin try WriteLn(_SDL_TextureModulate, ' Value: ', LongInt(_SDL_TextureModulate)); except end; end; end; begin outputEnum_SDL_bool(); outputEnum_SDL_DUMMY_ENUM(); outputEnum_SDL_assert_state(); outputEnum_SDL_errorcode(); outputEnum_SDL_ThreadPriority(); outputEnum_SDL_AudioStatus(); outputEnum_SDL_BlendMode(); outputEnum_SDL_WindowFlags(); outputEnum_SDL_WindowEventID(); outputEnum_SDL_GLattr(); outputEnum_SDL_Scancode(); outputEnum_SDL_Keymod(); outputEnum_SDL_EventType(); outputEnum_SDL_eventaction(); outputEnum_SDL_HintPriority(); outputEnum_SDL_LogPriority(); outputEnum_SDL_PowerState(); outputEnum_SDL_RendererFlags(); outputEnum_SDL_TextureAccess(); outputEnum_SDL_TextureModulate(); end.
{******************************************************************************} { } { Internet Protocol Helper API interface Unit for Object Pascal } { } { Portions created by Microsoft are Copyright (C) 1995-2001 Microsoft } { Corporation. All Rights Reserved. } { } { The original file is: iphlpapi.h, released July 2000. The original Pascal } { code is: IpHlpApi.pas, released September 2000. The initial developer of the } { Pascal code is Marcel van Brakel (brakelm@chello.nl). } { } { Portions created by Marcel van Brakel are Copyright (C) 1999-2001 } { Marcel van Brakel. All Rights Reserved. } { } { Contributor(s): John C. Penman (jcp@craiglockhart.com) } { Vladimir Vassiliev (voldemarv@hotpop.com) } { } { Obtained through: Joint Endeavour of Delphi Innovators (Project JEDI) } { } { You may retrieve the latest version of this file at the Project JEDI home } { page, located at http://delphi-jedi.org or my personal homepage located at } { http://members.chello.nl/m.vanbrakel2 } { } { The contents of this file are used with permission, subject to the Mozilla } { Public License Version 1.1 (the "License"); you may not use this file except } { in compliance with the License. You may obtain a copy of the License at } { http://www.mozilla.org/MPL/MPL-1.1.html } { } { Software distributed under the License is distributed on an "AS IS" basis, } { WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for } { the specific language governing rights and limitations under the License. } { } { Alternatively, the contents of this file may be used under the terms of the } { GNU Lesser General Public License (the "LGPL License"), in which case the } { provisions of the LGPL License are applicable instead of those above. } { If you wish to allow use of your version of this file only under the terms } { of the LGPL License and not to allow others to use your version of this file } { under the MPL, indicate your decision by deleting the provisions above and } { replace them with the notice and other provisions required by the LGPL } { License. If you do not delete the provisions above, a recipient may use } { your version of this file under either the MPL or the LGPL License. } { } { For more information about the LGPL: http://www.gnu.org/copyleft/lesser.html } { } {******************************************************************************} unit IpHlpApi; {$WEAKPACKAGEUNIT} {$HPPEMIT ''} {$HPPEMIT '#include "iphlpapi.h"'} {$HPPEMIT ''} //{$I WINDEFINES.INC} {.$DEFINE IPHLPAPI_LINKONREQUEST} {$IFDEF IPHLPAPI_LINKONREQUEST} {$DEFINE IPHLPAPI_DYNLINK} {$ENDIF} {.$DEFINE IPHLPAPI_DYNLINK} interface uses Windows, IpExport, IpRtrMib, IpTypes; ////////////////////////////////////////////////////////////////////////////// // // // IPRTRMIB.H has the definitions of the strcutures used to set and get // // information // // // ////////////////////////////////////////////////////////////////////////////// // #include <iprtrmib.h> // #include <ipexport.h> // #include <iptypes.h> ////////////////////////////////////////////////////////////////////////////// // // // The GetXXXTable APIs take a buffer and a size of buffer. If the buffer // // is not large enough, they APIs return ERROR_INSUFFICIENT_BUFFER and // // *pdwSize is the required buffer size // // The bOrder is a BOOLEAN, which if TRUE sorts the table according to // // MIB-II (RFC XXXX) // // // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // // // Retrieves the number of interfaces in the system. These include LAN and // // WAN interfaces // // // ////////////////////////////////////////////////////////////////////////////// {$IFNDEF IPHLPAPI_DYNLINK} function GetNumberOfInterfaces(var pdwNumIf: DWORD): DWORD; stdcall; {$EXTERNALSYM GetNumberOfInterfaces} { 返回本机网络接口数量 参数说明: pdwNumIf:[输出] 指向一个接收本机接口数量的变量。 备注:返回的接口数包括loopback接口。这个数目比GetAdaptersInfo和GetInterfaceInfo函 数返回的适配器数目要多一,因为那两个函数不返回loopback接口的信息。 返回值:成功,返回0;失败,返回错误代码。 } {$ELSE} var GetNumberOfInterfaces: function (var pdwNumIf: DWORD): DWORD; stdcall; {$EXTERNALSYM GetNumberOfInterfaces} {$ENDIF} ////////////////////////////////////////////////////////////////////////////// // // // Gets the MIB-II ifEntry // // The dwIndex field of the MIB_IFROW should be set to the index of the // // interface being queried // // // ////////////////////////////////////////////////////////////////////////////// {$IFNDEF IPHLPAPI_DYNLINK} function GetIfEntry(pIfRow: PMIB_IFROW): DWORD; stdcall; {$EXTERNALSYM GetIfEntry} { 返回指定接口的信息 pIfRow:[输入,输出] 成功返回一个指向本机接口信息的MIB_IFROW类型;输出,需设置 MIB_IFROW的dwIndex 为想要获取信息的接口的序号。 返回值:成功,返回0;失败,返回错误代码。 } {$ELSE} var GetIfEntry: function (pIfRow: PMIB_IFROW): DWORD; stdcall; {$EXTERNALSYM GetIfEntry} {$ENDIF} ////////////////////////////////////////////////////////////////////////////// // // // Gets the MIB-II IfTable // // // ////////////////////////////////////////////////////////////////////////////// {$IFNDEF IPHLPAPI_DYNLINK} function GetIfTable(pIfTable: PMIB_IFTABLE; var pdwSize: ULONG; bOrder: BOOL): DWORD; stdcall; {$EXTERNALSYM GetIfTable} { 获取MIB-II 接口表 参数说明: pIfTable:[输入]成功的话指向一个MIB_IFTABLE类型的缓冲区。 PdwSize:[输入,输出]指定pIfTable参数所占缓冲区的大小,如果缓冲区不是足够大返回 接口表,函数设置这个参数等于所必须的缓冲区大小。 bOrder:[输入]指定返回的接口表是否按接口序号按上升顺序排列。如果参数为TRUE那么按 上升顺序排列。 返回值:成功,返回0;失败,返回错误代码。 } {$ELSE} var GetIfTable: function (pIfTable: PMIB_IFTABLE; var pdwSize: ULONG; bOrder: BOOL): DWORD; stdcall; {$EXTERNALSYM GetIfTable} {$ENDIF} ////////////////////////////////////////////////////////////////////////////// // // // Gets the Interface to IP Address mapping // // // ////////////////////////////////////////////////////////////////////////////// {$IFNDEF IPHLPAPI_DYNLINK} function GetIpAddrTable(pIpAddrTable: PMIB_IPADDRTABLE; var pdwSize: ULONG; bOrder: BOOL): DWORD; stdcall; {$EXTERNALSYM GetIpAddrTable} { 获取网卡-IP地址映射表 参数说明: pIpAddrTable:[输出] 指向一个接收网卡-IP地址映射表的 MIB_IPADDRTABLE类型的指针。 pdwSize:[输入,输出]输入,指定pIpAddrTable 参数指向缓存的大小;输出,如果指定的 缓存大小不够大,将设置此参数为必须的大小。 bOrder:[输入] 指定返回的映射表是否按照IP地址排列。TRUE,按顺序排列。 返回值:成功,返回0;失败,返回错误代码。 } {$ELSE} var GetIpAddrTable: function (pIpAddrTable: PMIB_IPADDRTABLE; var pdwSize: ULONG; bOrder: BOOL): DWORD; stdcall; {$EXTERNALSYM GetIpAddrTable} {$ENDIF} ////////////////////////////////////////////////////////////////////////////// // // // Gets the current IP Address to Physical Address (ARP) mapping // // // ////////////////////////////////////////////////////////////////////////////// {$IFNDEF IPHLPAPI_DYNLINK} function GetIpNetTable(pIpNetTable: PMIB_IPNETTABLE; var pdwSize: ULONG; bOrder: BOOL): DWORD; stdcall; {$EXTERNALSYM GetIpNetTable} { 获取本机已探测的IP - 物理地址映射表 参数说明: pIpNetTable:[输出]指向一个返回IP至物理地址映射作为MIB_IPNETTABLE类型的缓存。 pdwSize:[输入,输出] 输入,指定pIpNetTable参数指向缓存的大小;输出,如果指定的缓存大小不够大,将设置此参数为必须的大小。 bOrder:[输入] 指定返回的映射表是否按照IP地址排列。TRUE,按序排列。 返回值:成功,返回0;失败,返回错误代码。 } {$ELSE} var GetIpNetTable: function (pIpNetTable: PMIB_IPNETTABLE; var pdwSize: ULONG; bOrder: BOOL): DWORD; stdcall; {$EXTERNALSYM GetIpNetTable} {$ENDIF} ////////////////////////////////////////////////////////////////////////////// // // // Gets the IP Routing Table (RFX XXXX) // // // ////////////////////////////////////////////////////////////////////////////// {$IFNDEF IPHLPAPI_DYNLINK} function GetIpForwardTable(pIpForwardTable: PMIB_IPFORWARDTABLE; var pdwSize: ULONG; bOrder: BOOL): DWORD; stdcall; {$EXTERNALSYM GetIpForwardTable} { 获取本机IP 路由表 参数说明: pIpForwardTable:[输出]指向接收IP路由表作为MIB_IPFORWARDTABLE类型的缓存 pdwSize:[输入,输出] 输入,指定 pIpForwardTable参数指向缓存的大小;输出,如果指 定的缓存大小不够大,将设置此参数为必须的大小。 bOrder:[输入] 指定返回的映射表是否按照种类排列。TRUE,按以下顺序排列:目的地地址; 生成路由的协议;多路径路由策略;下一跃点的地址。 返回值:成功,返回0;失败,返回错误代码。 } {$ELSE} var GetIpForwardTable: function (pIpForwardTable: PMIB_IPFORWARDTABLE; var pdwSize: ULONG; bOrder: BOOL): DWORD; stdcall; {$EXTERNALSYM GetIpForwardTable} {$ENDIF} ////////////////////////////////////////////////////////////////////////////// // // // Gets TCP Connection/UDP Listener Table // // // ////////////////////////////////////////////////////////////////////////////// {$IFNDEF IPHLPAPI_DYNLINK} function GetTcpTable(pTcpTable: PMIB_TCPTABLE; var pdwSize: DWORD; bOrder: BOOL): DWORD; stdcall; {$EXTERNALSYM GetTcpTable} { 获取当前TCP连接情况 参数说明: pTcpTable:[输入]指向包含了MIB_TCPTABLE类型的TCP 连接表。 pdwSize:[输入,输出]指向pTcpTable参数的缓冲区大小,如果分配的缓冲不够,那么就等 于最小需要缓冲。 bOrder:[输入]指定连接表是否按照类型排列。TRUE,那么就按以下类型顺序排列: Local IP address,Local port,Remote IP address,Remote port。 返回值:成功,返回0;失败,返回错误代码。 } function GetUdpTable(pUdpTable: PMIB_UDPTABLE; var pdwSize: DWORD; bOrder: BOOL): DWORD; stdcall; {$EXTERNALSYM GetUdpTable} { 获取当前UDP连接情况 参数说明: pUdpTable:[输出]指向一个缓存作为MIB_UDPTABLE类型用来接收UDP监听表。 pdwSize:[输入或输出]输入,指定pUdpTable参数所占缓存大小;输出,如果指定的缓存大 小不足,将设置为所须的大小。 bOrder:[输入]指定返回的表是否按分类排列。如果为TRUE,按以下分类排列:1、IP地址;2、端口。 返回值:成功,返回0;失败,返回错误代码。 } {$ELSE} var GetTcpTable: function (pTcpTable: PMIB_TCPTABLE; var pdwSize: DWORD; bOrder: BOOL): DWORD; stdcall; {$EXTERNALSYM GetTcpTable} GetUdpTable: function (pUdpTable: PMIB_UDPTABLE; var pdwSize: DWORD; bOrder: BOOL): DWORD; stdcall; {$EXTERNALSYM GetUdpTable} {$ENDIF} ////////////////////////////////////////////////////////////////////////////// // // // Gets IP/ICMP/TCP/UDP Statistics // // // ////////////////////////////////////////////////////////////////////////////// {$IFNDEF IPHLPAPI_DYNLINK} function GetIpStatistics(var pStats: MIB_IPSTATS): DWORD; stdcall; {$EXTERNALSYM GetIpStatistics} { 获取当前计算机的IP信息 参数说明: pStats:[输出] 指向一个包含IP信息的MIB_IPSTATS类型。 返回值:成功,返回0;失败,返回错误代码 } function GetIcmpStatistics(var pStats: MIB_ICMP): DWORD; stdcall; {$EXTERNALSYM GetIcmpStatistics} { 参数说明: pStats:[输出] 指向一个本机收到ICMP 统计表的MIB_ICMP类型。 返回值:成功,返回0;失败,返回错误代码。 } function GetTcpStatistics(var pStats: MIB_TCPSTATS): DWORD; stdcall; {$EXTERNALSYM GetTcpStatistics} { 获取本机TCP 信息列表 参数说明: pStats :[输出]指向一个接收本机TCP统计表的MIB_TCPSTATS类型 返回值:成功,返回0;失败,返回错误代码。 } function GetUdpStatistics(var pStats: MIB_UDPSTATS): DWORD; stdcall; {$EXTERNALSYM GetUdpStatistics} { 获取本机UDP信息列表 参数说明: pStats:[输出]指向一个接收到本机UDP统计表的MIB_UDPSTATS类型 返回值:成功,返回0;失败,返回错误代码。 } {$ELSE} var GetIpStatistics: function (var pStats: MIB_IPSTATS): DWORD; stdcall; {$EXTERNALSYM GetIpStatistics} GetIcmpStatistics: function (var pStats: MIB_ICMP): DWORD; stdcall; {$EXTERNALSYM GetIcmpStatistics} GetTcpStatistics: function (var pStats: MIB_TCPSTATS): DWORD; stdcall; {$EXTERNALSYM GetTcpStatistics} GetUdpStatistics: function (var pStats: MIB_UDPSTATS): DWORD; stdcall; {$EXTERNALSYM GetUdpStatistics} {$ENDIF} ////////////////////////////////////////////////////////////////////////////// // // // Used to set the ifAdminStatus on an interface. The only fields of the // // MIB_IFROW that are relevant are the dwIndex (index of the interface // // whose status needs to be set) and the dwAdminStatus which can be either // // MIB_IF_ADMIN_STATUS_UP or MIB_IF_ADMIN_STATUS_DOWN // // // ////////////////////////////////////////////////////////////////////////////// {$IFNDEF IPHLPAPI_DYNLINK} function SetIfEntry(const pIfRow: MIB_IFROW): DWORD; stdcall; {$EXTERNALSYM SetIfEntry} { 设置一个接口的管理状态 pIfRow:[输入] 指向一个MIB_IFROW类型。dwIndex成员指定了要设置管理状态的接口; dwAdminStatus成员指定了新的管理状态,为以下值之一: MIB_IF_ADMIN_STATUS_UP 接口可被管理; MIB_IF_ADMIN_STATUS_DOWN 接口不能被管理。 返回值:成功,返回0;失败,返回错误代码。 } {$ELSE} var SetIfEntry: function (const pIfRow: MIB_IFROW): DWORD; stdcall; {$EXTERNALSYM SetIfEntry} {$ENDIF} ////////////////////////////////////////////////////////////////////////////// // // // Used to create, modify or delete a route. In all cases the // // dwForwardIfIndex, dwForwardDest, dwForwardMask, dwForwardNextHop and // // dwForwardPolicy MUST BE SPECIFIED. Currently dwForwardPolicy is unused // // and MUST BE 0. // // For a set, the complete MIB_IPFORWARDROW structure must be specified // // // ////////////////////////////////////////////////////////////////////////////// {$IFNDEF IPHLPAPI_DYNLINK} function CreateIpForwardEntry(const pRoute: MIB_IPFORWARDROW): DWORD; stdcall; {$EXTERNALSYM CreateIpForwardEntry} { 创建一个路由到本地电脑IP路由表 pRoute:[输入]指向指定了新路由信息的MIB_IPFORWARDROW类型的指针,调用者必须指定这个 类型的所有成员值,必须指定PROTO_IP_NETMGMT作为MIB_IPFORWARDROW类型中 dwForwardProto成员的值。 返回值:成功,返回0;失败,返回错误代码。 备注:①修改现有的路由表中的路由,使用SetIpForwardEntry函数。 ②调用者不能指定路由协议,例如:PROTO_IP_OSPF作为MIB_IPFORWARDROW类型的dwForwardProto 成员的值,路由协议标识符仅仅用来识别通过路由表接收到的路由信息。 例如:PROTO_IP_OSPF被用来识别通过OSPF路由表接收到的路由信息。 ③MIB_IPFORWARDROW类型中的dwForwardPolicy成员在当前未使用,调用者应该将它设置为0。 ④MIB_IPFORWARDROW类型中的 DwForwardAge成员仅仅用来当路由和远程数据服务 (Remote Access Service :RRAS)正在运行,并且仅用于路由的PROTO_IP_NETMGMT类型。 ⑤这个函数执行了一个特许操作,需要有必须的权限才能执行。 } function SetIpForwardEntry(const pRoute: MIB_IPFORWARDROW): DWORD; stdcall; {$EXTERNALSYM SetIpForwardEntry} { 从本机IP路由表中修改一个现有的路由 pRoute:[输入]指向一个为现有路由指定了新信息的MIB_IPFORWARDROW类型。调用者必须将 此类型的dwForwardProto设置为PROTO_IP_NETMGMT。调用者同样必须指定该类型中 以下成员的值:dwForwardIfIndex,dwForwardDest,dwForwardMask,dwForwardNextHop,dwForwardPolicy。 返回值:成功,返回0;失败,返回错误代码。 备注:①在IP路由表中创建一个新的路由,使用CreateIpForwardEntry函数; ②调用者不能指定一个路由协议,比如:不能将MIB_IPFORWARDROW的dwForwardProto 设置为 PROTO_IP_OSPF。路由协议标识符(id)是用来标识通过指定的路由协议收到的路由信息。 例如:PROTO_IP_OSPF是用来标识通过OSPF路有协议收到的路由信息; ③MIB_IPFORWARDROW类型中的dwForwardPolicy成员目前没有使用,指定为0。 } function DeleteIpForwardEntry(const pRoute: MIB_IPFORWARDROW): DWORD; stdcall; {$EXTERNALSYM DeleteIpForwardEntry} { 从本地电脑的IP路由表中删除一个路由 pRoute: [输入] 指向一个MIB_IPFORWARDROW类型。这个类型指定了识别将要删除的路 由的信息。调用者必须指定类型中以下成员的值: dwForwardIfIndex;dwForwardDest;dwForwardMask;dwForwardNextHop;dwForwardPolicy。 返回值:成功,返回0;失败,返回错误代码。 备注:①MIB_IPFORWARDROW类型是GetIpForwardTable返回的。接下来,再将此类型投递给 DeleteForwardEntry函数,便可删除指定的路由条目了。 ② MIB_IPFORWARDROW类型的 dwForwardPolicy目前未使用,应该设置为0。 } {$ELSE} var CreateIpForwardEntry: function (const pRoute: MIB_IPFORWARDROW): DWORD; stdcall; {$EXTERNALSYM CreateIpForwardEntry} SetIpForwardEntry: function (const pRoute: MIB_IPFORWARDROW): DWORD; stdcall; {$EXTERNALSYM SetIpForwardEntry} DeleteIpForwardEntry: function (const pRoute: MIB_IPFORWARDROW): DWORD; stdcall; {$EXTERNALSYM DeleteIpForwardEntry} {$ENDIF} ////////////////////////////////////////////////////////////////////////////// // // // Used to set the ipForwarding to ON or OFF (currently only ON->OFF is // // allowed) and to set the defaultTTL. If only one of the fields needs to // // be modified and the other needs to be the same as before the other field // // needs to be set to MIB_USE_CURRENT_TTL or MIB_USE_CURRENT_FORWARDING as // // the case may be // // // ////////////////////////////////////////////////////////////////////////////// {$IFNDEF IPHLPAPI_DYNLINK} function SetIpStatistics(const pIpStats: MIB_IPSTATS): DWORD; stdcall; {$EXTERNALSYM SetIpStatistics} { 启用或者禁止转发IP包或设置本机TTL值 pIpStats:[输入] 指向一个MIB_IPSTATS类型。调用者应该为此类型的dwForwarding和 dwDefaultTTL成员设置新值。保持某个成员的值,使用MIB_USE_CURRENT_TTL或者 MIB_USE_CURRENT_FORWARDING。 返回值:成功,返回0;失败,返回错误代码。 备注:①在实际使用中,好像只能设置TTL的值,别的值设置有可能导致错误87( 参数错误)或者虽然调用成功,但是并没有达到预期那样设置成功; ②设置默认的生存时间(TTL),也可以使用SetIpTTL函数。 } {$ELSE} var SetIpStatistics: function (const pIpStats: MIB_IPSTATS): DWORD; stdcall; {$EXTERNALSYM SetIpStatistics} {$ENDIF} ////////////////////////////////////////////////////////////////////////////// // // // Used to set the defaultTTL. // // // ////////////////////////////////////////////////////////////////////////////// {$IFNDEF IPHLPAPI_DYNLINK} function SetIpTTL(nTTL: UINT): DWORD; stdcall; {$EXTERNALSYM SetIpTTL} { 设置本机默认的生存时间(time-to-live:TTL)值 参数说明: nTTL: [输入] 本机的新的生存时间(TTL) 返回值:成功,返回0;失败,返回错误代码。 } {$ELSE} SetIpTTL: function (nTTL: UINT): DWORD; stdcall; {$EXTERNALSYM SetIpTTL} {$ENDIF} ////////////////////////////////////////////////////////////////////////////// // // // Used to create, modify or delete an ARP entry. In all cases the dwIndex // // dwAddr field MUST BE SPECIFIED. // // For a set, the complete MIB_IPNETROW structure must be specified // // // ////////////////////////////////////////////////////////////////////////////// {$IFNDEF IPHLPAPI_DYNLINK} function CreateIpNetEntry(const pArpEntry: MIB_IPNETROW): DWORD; stdcall; {$EXTERNALSYM CreateIpNetEntry} { 在本地电脑的地址解析协议(ARP)表中创建一个ARP 参数说明: pArpEntry [输入] 指向一个指定了新接口信息的MIB_IPNETROW类型,调用者必须为这个类型 指定所有成员的值。 返回值:成功,返回0;失败,返回错误代码。 } function SetIpNetEntry(const pArpEntry: MIB_IPNETROW): DWORD; stdcall; {$EXTERNALSYM SetIpNetEntry} function DeleteIpNetEntry(const pArpEntry: MIB_IPNETROW): DWORD; stdcall; {$EXTERNALSYM DeleteIpNetEntry} { 在本地电脑的地址解析协议(ARP)表中删除一个ARP 参数说明: pArpEntry [输入] 指向一个指定了新接口信息的MIB_IPNETROW类型,调用者必须为这个类 型指定所有成员的值。 返回值:成功,返回0;失败,返回错误代码。 } function FlushIpNetTable(dwIfIndex: DWORD): DWORD; stdcall; {$EXTERNALSYM FlushIpNetTable} { 从ARP表中删除指定接口的ARP接口 dwIfIndex:[输入] 将要删除的ARP接口的序号 返回值:成功,返回0;失败,返回错误代码。 } {$ELSE} var CreateIpNetEntry: function (const pArpEntry: MIB_IPNETROW): DWORD; stdcall; {$EXTERNALSYM CreateIpNetEntry} SetIpNetEntry: function (const pArpEntry: MIB_IPNETROW): DWORD; stdcall; {$EXTERNALSYM SetIpNetEntry} DeleteIpNetEntry: function (const pArpEntry: MIB_IPNETROW): DWORD; stdcall; {$EXTERNALSYM DeleteIpNetEntry} FlushIpNetTable: function (dwIfIndex: DWORD): DWORD; stdcall; {$EXTERNALSYM FlushIpNetTable} {$ENDIF} ////////////////////////////////////////////////////////////////////////////// // // // Used to create or delete a Proxy ARP entry. The dwIndex is the index of // // the interface on which to PARP for the dwAddress. If the interface is // // of a type that doesnt support ARP, e.g. PPP, then the call will fail // // // ////////////////////////////////////////////////////////////////////////////// {$IFNDEF IPHLPAPI_DYNLINK} function CreateProxyArpEntry(dwAddress, dwMask, dwIfIndex: DWORD): DWORD; stdcall; {$EXTERNALSYM CreateProxyArpEntry} { 为本地电脑指定的IP地址创建一个代理服务器地址解析协议(Proxy Address Resolution Protocol :PARP) 接口. dwAddress:[输入] 作为代理服务器的电脑的IP地址。 dwMask:[输入]指定了dwAddress的IP地址对应的子网掩码。 dwIfIndex:[输入]代理服务地址解析协议(ARP)接口的索引通过dwAddress识别IP地址。换句话说,当dwAddress一个地址解析协议(ARP)请求在这个接口上被收到的时候,本地电脑的物理地址的接口作出响应。如果接口类型不支持地址解析协议(ARP),比如:端对端协议(PPP),那么调用失败。 返回值:成功,返回0;失败,返回错误代码。 } function DeleteProxyArpEntry(dwAddress, dwMask, dwIfIndex: DWORD): DWORD; stdcall; {$EXTERNALSYM DeleteProxyArpEntry} { 删除由dwAddress和dwIfIndex参数指定的PARP接口 dwAddress:[输入] 作为代理服务器的电脑的IP地址 dwMask:[输入] 对应dwAddress的子网掩码 dwIfIndex::[输入]对应IP 地址dwAddress指定的支持代理服务器地址解析协议(Proxy Address Resolution Protocol :PARP)的电脑的接口序号。 返回值:成功,返回0;失败,返回错误代码。 } {$ELSE} var CreateProxyArpEntry: function (dwAddress, dwMask, dwIfIndex: DWORD): DWORD; stdcall; {$EXTERNALSYM CreateProxyArpEntry} DeleteProxyArpEntry: function (dwAddress, dwMask, dwIfIndex: DWORD): DWORD; stdcall; {$EXTERNALSYM DeleteProxyArpEntry} {$ENDIF} ////////////////////////////////////////////////////////////////////////////// // // // Used to set the state of a TCP Connection. The only state that it can be // // set to is MIB_TCP_STATE_DELETE_TCB. The complete MIB_TCPROW structure // // MUST BE SPECIFIED // // // ////////////////////////////////////////////////////////////////////////////// {$IFNDEF IPHLPAPI_DYNLINK} function SetTcpEntry(const pTcpRow: MIB_TCPROW): DWORD; stdcall; {$EXTERNALSYM SetTcpEntry} { 设置TCP连接状态 参数说明: PTcpRow:[输入]指向MIB_TCPROW类型,这个类型指定了TCP连接的标识,也指定了TCP连接的 新状态。调用者必须指定此类型中所有成员的值。 备注:通常设置为MIB_TCP_STATE_DELETE_TCB(值为12)用来断开某个TCP连接,这也是唯 一可在运行时设置的状态。 返回值:成功,返回0;失败,返回错误代码。 } function GetInterfaceInfo(pIfTable: PIP_INTERFACE_INFO; var dwOutBufLen: ULONG): DWORD; stdcall; {$EXTERNALSYM GetInterfaceInfo} { 获得本机系统网络接口适配器的列表 参数说明: pIfTable: [输入] 指向一个指定一个包含了适配器列表的IP_INTERFACE_INFO类型的缓存。 这个缓存应当由调用者分配。 dwOutBufLen:[输出] 指向一个DWORD变量。如果pIfTable参数为空,或者缓存不够大,这个 参数返回必须的大小。 返回值:成功,返回0;失败,返回错误代码。 } function GetUniDirectionalAdapterInfo(pIPIfInfo: PIP_UNIDIRECTIONAL_ADAPTER_ADDRESS; var dwOutBufLen: ULONG): DWORD; stdcall; {$EXTERNALSYM GetUniDirectionalAdapterInfo(OUT PIP_UNIDIRECTIONAL_ADAPTER_ADDRESS pIPIfInfo} { 接收本机安装的单向适配器的信息 pIPIfInfo:[输出]指向一个接收本机已安装的单向适配器的信息的 IP_UNIDIRECTIONAL_ADAPTER_ADDRESS类型。 dwOutBufLen:[输出]指向一个ULONG变量用来保存pIPIfInfo参数缓存的大小。 返回值:成功,返回0;失败,返回错误代码。 } {$ELSE} var SetTcpEntry: function (const pTcpRow: MIB_TCPROW): DWORD; stdcall; {$EXTERNALSYM SetTcpEntry} GetInterfaceInfo: function (pIfTable: PIP_INTERFACE_INFO; var dwOutBufLen: ULONG): DWORD; stdcall; {$EXTERNALSYM GetInterfaceInfo} GetUniDirectionalAdapterInfo: function (pIPIfInfo: PIP_UNIDIRECTIONAL_ADAPTER_ADDRESS; var dwOutBufLen: ULONG): DWORD; stdcall; {$EXTERNALSYM GetUniDirectionalAdapterInfo(OUT PIP_UNIDIRECTIONAL_ADAPTER_ADDRESS pIPIfInfo} {$ENDIF} ////////////////////////////////////////////////////////////////////////////// // // // Gets the "best" outgoing interface for the specified destination address // // // ////////////////////////////////////////////////////////////////////////////// {$IFNDEF IPHLPAPI_DYNLINK} function GetBestInterface(dwDestAddr: IPAddr; var pdwBestIfIndex: DWORD): DWORD; stdcall; {$EXTERNALSYM GetBestInterface} { 返回包含到指定IP地址的最佳路由接口序号 dwDestAddr:[输入]目标IP地址 pdwBestIfIndex:[输出] 指向一个包含到指定IP地址的最佳路由接口序号的DWORD变量 返回值:成功,返回0;失败,返回错误代码。 } {$ELSE} var GetBestInterface: function (dwDestAddr: IPAddr; var pdwBestIfIndex: DWORD): DWORD; stdcall; {$EXTERNALSYM GetBestInterface} {$ENDIF} ////////////////////////////////////////////////////////////////////////////// // // // Gets the best (longest matching prefix) route for the given destination // // If the source address is also specified (i.e. is not 0x00000000), and // // there are multiple "best" routes to the given destination, the returned // // route will be one that goes out over the interface which has an address // // that matches the source address // // // ////////////////////////////////////////////////////////////////////////////// {$IFNDEF IPHLPAPI_DYNLINK} function GetBestRoute(dwDestAddr, dwSourceAddr: DWORD; pBestRoute: PMIB_IPFORWARDROW): DWORD; stdcall; {$EXTERNALSYM GetBestRoute} { 返回包含到指定IP地址的最佳路由 dwDestAddr:[输入]目标IP地址 dwSourceAddr:[输入]源IP地址。这个Ip地址是本地电脑上相应的接口,如果有多个最佳路 由存在,函数选择使用这个接口的路由。这个参数是可选的,调用者可以指定这个参数为0。 pBestRoute:[输出] 指向一个包含了最佳路由的MIB_IPFORWARDROW类型 返回值:成功,返回0;失败,返回错误代码。 } function NotifyAddrChange(var Handle: THandle; overlapped: POVERLAPPED): DWORD; stdcall; {$EXTERNALSYM NotifyAddrChange} { 当IP地址到接口的映射表发生改变,将引发一个通知 Handle:[输出]指向一个HANDLE变量,用来接收一个句柄handle使用到异步通知中。 警告:不能关掉这个句柄。 overlapped:[输入]指向一个OVERLAPPED类型,通知调用者任何IP地址到接口的映射表改变。 返回值:成功,如果调用者指定Handle和overlapped参数为空,返回NO_ERROR;如果调用者指 定非空参数,返回ERROR_IO_PENDING。失败,使用FormatMessage获取错误信息。 备注:①如果调用者指定Handle和overlapped参数为空,对NotifyAddrChange的调用将会被 阻止直到一个IP地址改变发生。 ②调用者指定了一个handle变量和一个OVERLAPPED类型,调用者可以使用返回的handle以 及OVERLAPPED类型来接收路由表改变的异步通知。 } function NotifyRouteChange(var Handle: THandle; overlapped: POVERLAPPED): DWORD; stdcall; {$EXTERNALSYM NotifyRouteChange} { IP路由表发生改变将引起一个通知 Handle:[输出]指向一个HANDLE变量,此变量接收一个用作异步通知的句柄。 overlapped:[输入]指向一个OVERLAPPED类型,此类型通知调用者路由表的每一个改变。 返回值:成功,如果调用者指定Handle和overlapped参数为空,返回NO_ERROR;如果调用者指 定非空参数,返回ERROR_IO_PENDING。失败,使用FormatMessage获取错误信息。 备注:①如果调用者指定Handle和overlapped参数为空,对NotifyRouteChange的调用将会被 阻止直到一个路由表改变发生。 ②调用者指定了一个handle变量和一个OVERLAPPED类型,调用者可以使用返回的handle 以及OVERLAPPED类型来接收路由表改变的异步通知。 } function GetAdapterIndex(AdapterName: LPWSTR; var IfIndex: ULONG): DWORD; stdcall; {$EXTERNALSYM GetAdapterIndex} { 从名称获得一个适配器的序号 AdapterName:[输入] 指定了适配器名称的Unicode字符串 IfIndex:[输出] 指向一个指向适配器序号的ULONG变量指针 返回值:成功,返回0;失败,返回错误代码。 } function AddIPAddress(Address: IPAddr; IpMask: IPMask; IfIndex: DWORD; var NTEContext, NTEInstance: ULONG): DWORD; stdcall; {$EXTERNALSYM AddIPAddress} { 增加一个IP地址 参数说明: Address:[输入]要增加的IP地址 IpMask:[输入]IP地址的子网掩码 IfIndex:[输入]增加IP地址的适配器,实际值为MIB_IPADDRTABLE.table(适配器编号).dwIndex NTEContext:[输出]成功则指向一个与这个IP地址关联的网络表接口(Net Table Entry:NTE)ULONG变量。调用者可以在稍后使用这个关系到调用DeleteIPAddress。 NTEInstance:[输出]成功则指向这个IP地址的网络表接口(Net Table Entry:NTE)实例。 返回值:成功,返回0;失败,返回错误代码。 备注:①增加的IP是临时的,当系统重新启动或者发生其它的PNP事件的时候这个IP就不存在 了,比如将网卡禁用,然后启用,就会发现之前调用函数AddIPAddress增加的的IP地址不存 在了。 ②有时候,调用这个函数,可能造成网络出错、系统Arp映射错误等,但可以禁用\启 用网卡恢复成正常状态。 } function DeleteIPAddress(NTEContext: ULONG): DWORD; stdcall; {$EXTERNALSYM DeleteIPAddress} { 删除一个IP地址 参数说明: NTEContext:[输入] IP地址关联的网络表接口(Net Table Entry:NTE),这个关联是之前 用AddIPAddress所创建的,在调用函数GetAdaptersInfo后,从获得的 IP_ADAPTER_INFO. IpAddressList. Context 中也可获得这个参数的值 返回值:成功,返回0;失败,返回错误代码。 备注:实际上函数DeleteIPAddress只能删除由函数AddIPAddress创建的IP地址。 } function GetNetworkParams(pFixedInfo: PFIXED_INFO; var pOutBufLen: ULONG): DWORD; stdcall; {$EXTERNALSYM GetNetworkParams} { 获取本机网络参数 参数说明: pFixedInfo:[输出]指向一个接收本机网络参数的数据块。 pOutBufLen:[输入,输出]指向一个ULONG变量,改变量指定了FixedInfo参数的大小。如果指 定的大小不够大,将设置为须要的大小并返回ERROR_BUFFER_OVERFLOW错误。 返回值:成功,返回0;失败,返回错误代码。 } function GetAdaptersInfo(pAdapterInfo: PIP_ADAPTER_INFO; var pOutBufLen: ULONG): DWORD; stdcall; {$EXTERNALSYM GetAdaptersInfo} { 获取本机网络适配器的信息 参数说明: pAdapterInfo:[输出] 指向一个IP_ADAPTER_INFO类型的连接表; pOutBufLen:[输入] 指定pAdapterInfo参数的大小,如果指定大小不足,GetAdaptersInfo 将此参数置为所需大小, 并返回一个ERROR_BUFFER_OVERFLOW错误代码。 返回值:成功,返回0;失败,返回错误代码。 备注:此函数不能获得回环(Loopback)适配器的信息 } function GetPerAdapterInfo(IfIndex: ULONG; pPerAdapterInfo: PIP_PER_ADAPTER_INFO; var pOutBufLen: ULONG): DWORD; stdcall; {$EXTERNALSYM GetPerAdapterInfo} { 返回与适配器相应的指定接口的信息 IfIndex:[输入] 一个接口的序号。函数将返回与这个序号相应的适配器接口信息。 pPerAdapterInfo:[输出]指向一个接收适配器信息的IP_PER_ADAPTER_INFO类型。 pOutBufLen:[输入]指向一个指定了IP_PER_ADAPTER_INFO类型ULONG变量。如果指定的大小不够大,将设置为须要的大小并返回ERROR_BUFFER_OVERFLOW错误。 返回值:成功,返回0;失败,返回错误代码。 备注:个人觉得实际使用时候,获取IfIndex比较困难,不如用GetAdaptersInfo。 } function IpReleaseAddress(const AdapterInfo: IP_ADAPTER_INDEX_MAP): DWORD; stdcall; {$EXTERNALSYM IpReleaseAddress} { 放一个之前通过DHCP获得的IP地址 AdapterInfo:[输入]指向一个IP_ADAPTER_INDEX_MAP类型,指定了要释放的和IP地址关联的适配器。 返回值:成功,返回0;失败,返回错误代码。 } function IpRenewAddress(const AdapterInfo: IP_ADAPTER_INDEX_MAP): DWORD; stdcall; {$EXTERNALSYM IpRenewAddress} { 更新一个之前通过DHCP获得的IP地址租期 AdapterInfo:[输入]指向一个IP_ADAPTER_INDEX_MAP类型,指定了与适配器关联的IP地址更新。 返回值:成功,返回0;失败,返回错误代码。 } function SendARP(const DestIP, SrcIP: IPAddr; pMacAddr: PULONG; var PhyAddrLen: ULONG): DWORD; stdcall; {$EXTERNALSYM SendARP} { 获得目的地IP(只能是所在局域网中的IP)对应的物理地址 参数说明: DestIP:[输入]目的地IP地址。 SrcIP:[输入]发送地IP地址。可选参数,调用者可以指定此参数为0。 pMacAddr:[输出]指向一个ULONG变量数组(array)。数组前6个字节(bytes)接收由 DestIP指定的目的地IP物理地址。 PhyAddrLen:[输入,输出]输入,指定用户设置pMacAddr接收MAC地址的最大缓存大小,单位 字节;输出,指定了写入pMacAddr的字节数量。 返回值:成功,返回0;失败,返回错误代码。 注意: inet_addr是Winsocket的函数而非"iphlpapi.dll"提供的函数,目的是将标准IP地址 ("xxx.xxx.xxx.xxx")的字符串转为电脑能识别的长整型的数据。 } function GetRTTAndHopCount(DestIpAddress: IPAddr; var HopCount: ULONG; MaxHops: ULONG; var RTT: ULONG): BOOL; stdcall; {$EXTERNALSYM GetRTTAndHopCount} { 测定到指定目的地往返时间和跳跃数 DestIpAddress :[输入]要测定RTT和跳跃数的目的地IP地址。 HopCount:[输出] 指向一个ULONG变量。这个变量接收由DestIpAddress参数指定的到目的地的跳跃数。 MaxHops:[输入] 寻找目的地的最大跳跃数目。如果跳跃数超过这个数目,函数将终止搜寻并返回FALSE。 RTT:[输出] 到达DestIpAddress指定的目的地的往返时间(Round-trip time),单位毫秒。 返回值:成功返回 1,否则返回0。 } function GetFriendlyIfIndex(IfIndex: DWORD): DWORD; stdcall; {$EXTERNALSYM GetFriendlyIfIndex} { 获得一个接口序号并返回一个反向兼容的接口序号 IfIndex:[输入] 来自反向兼容或者"友好"的接口序号 返回值:成功,返回0;失败,返回错误代码。 } function EnableRouter(var pHandle: THandle; pOverlapped: POVERLAPPED): DWORD; stdcall; {$EXTERNALSYM EnableRouter} { 增加涉及的enable-IP-forwarding要求的数目 pHandle:指向一个句柄 pOverlapped:指向一个OVERLAPPED类型。除了hEvent成员,类型中的其它成员必须设置为0。 hEvent成员应该包含一个有效的事件对象的句柄。使用CreateEvent函数来创建这个事件对象。 返回值:成功,返回ERROR_IO_PENDING;失败,调用FormatMessage获取更多错误信息。 } function UnenableRouter(pOverlapped: POVERLAPPED; lpdwEnableCount: LPDWORD): DWORD; stdcall; {$EXTERNALSYM UnenableRouter} { 减少涉及的enable-IP-forwarding要求数目 pOverlapped:指向一个OVERLAPPED类型。此类型必须和对EnableRouter的调用一样。 lpdwEnableCount:[out, optional]指向接收涉及剩余数目的DWORD变量。 备注:如果调用EnableRouter的进程没有调用UnenableRouter而终止,系统会减少IP推进涉 及的数目就象调用了UnenableRouter一样。调用UnenableRouter后,使用CloseHandle来关闭OVERLAPPED类型中的事件对象的句柄。 返回值:成功,返回0;失败,返回错误代码。 } {$ELSE} var GetBestRoute: function (dwDestAddr, dwSourceAddr: DWORD; pBestRoute: PMIB_IPFORWARDROW): DWORD; stdcall; {$EXTERNALSYM GetBestRoute} NotifyAddrChange: function (var Handle: THandle; overlapped: POVERLAPPED): DWORD; stdcall; {$EXTERNALSYM NotifyAddrChange} NotifyRouteChange: function (var Handle: THandle; overlapped: POVERLAPPED): DWORD; stdcall; {$EXTERNALSYM NotifyRouteChange} GetAdapterIndex: function (AdapterName: LPWSTR; var IfIndex: ULONG): DWORD; stdcall; {$EXTERNALSYM GetAdapterIndex} AddIPAddress: function (Address: IPAddr; IpMask: IPMask; IfIndex: DWORD; var NTEContext, NTEInstance: ULONG): DWORD; stdcall; {$EXTERNALSYM AddIPAddress} DeleteIPAddress: function (NTEContext: ULONG): DWORD; stdcall; {$EXTERNALSYM DeleteIPAddress} GetNetworkParams: function (pFixedInfo: PFIXED_INFO; var pOutBufLen: ULONG): DWORD; stdcall; {$EXTERNALSYM GetNetworkParams} GetAdaptersInfo: function (pAdapterInfo: PIP_ADAPTER_INFO; var pOutBufLen: ULONG): DWORD; stdcall; {$EXTERNALSYM GetAdaptersInfo} GetPerAdapterInfo: function (IfIndex: ULONG; pPerAdapterInfo: PIP_PER_ADAPTER_INFO; var pOutBufLen: ULONG): DWORD; stdcall; {$EXTERNALSYM GetPerAdapterInfo} IpReleaseAddress: function (const AdapterInfo: IP_ADAPTER_INDEX_MAP): DWORD; stdcall; {$EXTERNALSYM IpReleaseAddress} IpRenewAddress: function (const AdapterInfo: IP_ADAPTER_INDEX_MAP): DWORD; stdcall; {$EXTERNALSYM IpRenewAddress} SendARP: function (const DestIP, SrcIP: IPAddr; pMacAddr: PULONG; var PhyAddrLen: ULONG): DWORD; stdcall; {$EXTERNALSYM SendARP} GetRTTAndHopCount: function (DestIpAddress: IPAddr; var HopCount: ULONG; MaxHops: ULONG; var RTT: ULONG): BOOL; stdcall; {$EXTERNALSYM GetRTTAndHopCount} GetFriendlyIfIndex: function (IfIndex: DWORD): DWORD; stdcall; {$EXTERNALSYM GetFriendlyIfIndex} EnableRouter: function (var pHandle: THandle; pOverlapped: POVERLAPPED): DWORD; stdcall; {$EXTERNALSYM EnableRouter} UnenableRouter: function (pOverlapped: POVERLAPPED; lpdwEnableCount: LPDWORD): DWORD; stdcall; {$EXTERNALSYM UnenableRouter} {$ENDIF} {$IFDEF IPHLPAPI_LINKONREQUEST} function IpHlpApiInitAPI: Boolean; procedure IpHlpApiFreeAPI; {$ENDIF} function IpHlpApiCheckAPI: Boolean; implementation const iphlpapilib = 'iphlpapi.dll'; {$IFNDEF IPHLPAPI_DYNLINK} function GetNumberOfInterfaces; external iphlpapilib name 'GetNumberOfInterfaces'; function GetIfEntry; external iphlpapilib name 'GetIfEntry'; function GetIfTable; external iphlpapilib name 'GetIfTable'; function GetIpAddrTable; external iphlpapilib name 'GetIpAddrTable'; function GetIpNetTable; external iphlpapilib name 'GetIpNetTable'; function GetIpForwardTable; external iphlpapilib name 'GetIpForwardTable'; function GetTcpTable; external iphlpapilib name 'GetTcpTable'; function GetUdpTable; external iphlpapilib name 'GetUdpTable'; function GetIpStatistics; external iphlpapilib name 'GetIpStatistics'; function GetIcmpStatistics; external iphlpapilib name 'GetIcmpStatistics'; function GetTcpStatistics; external iphlpapilib name 'GetTcpStatistics'; function GetUdpStatistics; external iphlpapilib name 'GetUdpStatistics'; function SetIfEntry; external iphlpapilib name 'SetIfEntry'; function CreateIpForwardEntry; external iphlpapilib name 'CreateIpForwardEntry'; function SetIpForwardEntry; external iphlpapilib name 'SetIpForwardEntry'; function DeleteIpForwardEntry; external iphlpapilib name 'DeleteIpForwardEntry'; function SetIpStatistics; external iphlpapilib name 'SetIpStatistics'; function SetIpTTL; external iphlpapilib name 'SetIpTTL'; function CreateIpNetEntry; external iphlpapilib name 'CreateIpNetEntry'; function SetIpNetEntry; external iphlpapilib name 'SetIpNetEntry'; function DeleteIpNetEntry; external iphlpapilib name 'DeleteIpNetEntry'; function FlushIpNetTable; external iphlpapilib name 'FlushIpNetTable'; function CreateProxyArpEntry; external iphlpapilib name 'CreateProxyArpEntry'; function DeleteProxyArpEntry; external iphlpapilib name 'DeleteProxyArpEntry'; function SetTcpEntry; external iphlpapilib name 'SetTcpEntry'; function GetInterfaceInfo; external iphlpapilib name 'GetInterfaceInfo'; function GetUniDirectionalAdapterInfo; external iphlpapilib name 'GetUniDirectionalAdapterInfo'; function GetBestInterface; external iphlpapilib name 'GetBestInterface'; function GetBestRoute; external iphlpapilib name 'GetBestRoute'; function NotifyAddrChange; external iphlpapilib name 'NotifyAddrChange'; function NotifyRouteChange; external iphlpapilib name 'NotifyRouteChange'; function GetAdapterIndex; external iphlpapilib name 'GetAdapterIndex'; function AddIPAddress; external iphlpapilib name 'AddIPAddress'; function DeleteIPAddress; external iphlpapilib name 'DeleteIPAddress'; function GetNetworkParams; external iphlpapilib name 'GetNetworkParams'; function GetAdaptersInfo; external iphlpapilib name 'GetAdaptersInfo'; function GetPerAdapterInfo; external iphlpapilib name 'GetPerAdapterInfo'; function IpReleaseAddress; external iphlpapilib name 'IpReleaseAddress'; function IpRenewAddress; external iphlpapilib name 'IpRenewAddress'; function SendARP; external iphlpapilib name 'SendARP'; function GetRTTAndHopCount; external iphlpapilib name 'GetRTTAndHopCount'; function GetFriendlyIfIndex; external iphlpapilib name 'GetFriendlyIfIndex'; function EnableRouter; external iphlpapilib name 'EnableRouter'; function UnenableRouter; external iphlpapilib name 'UnenableRouter'; {$ELSE} var HIpHlpApi: THandle = 0; function IpHlpApiInitAPI: Boolean; begin Result := False; if HIphlpapi = 0 then HIpHlpApi := LoadLibrary(iphlpapilib); if HIpHlpApi > HINSTANCE_ERROR then begin @GetNetworkParams := GetProcAddress(HIpHlpApi, 'GetNetworkParams'); @GetAdaptersInfo := GetProcAddress(HIpHlpApi, 'GetAdaptersInfo'); @GetPerAdapterInfo := GetProcAddress(HIpHlpApi, 'GetPerAdapterInfo'); @GetAdapterIndex := GetProcAddress(HIpHlpApi, 'GetAdapterIndex'); @GetUniDirectionalAdapterInfo := GetProcAddress(HIpHlpApi, 'GetUniDirectionalAdapterInfo'); @GetNumberOfInterfaces := GetProcAddress(HIpHlpApi, 'GetNumberOfInterfaces'); @GetInterfaceInfo := GetProcAddress(HIpHlpApi, 'GetInterfaceInfo'); @GetFriendlyIfIndex := GetProcAddress(HIpHlpApi, 'GetFriendlyIfIndex'); @GetIfTable := GetProcAddress(HIpHlpApi, 'GetIfTable'); @GetIfEntry := GetProcAddress(HIpHlpApi, 'GetIfEntry'); @SetIfEntry := GetProcAddress(HIpHlpApi, 'SetIfEntry'); @GetIpAddrTable := GetProcAddress(HIpHlpApi, 'GetIpAddrTable'); @AddIPAddress := GetProcAddress(HIpHlpApi, 'AddIPAddress'); @DeleteIPAddress := GetProcAddress(HIpHlpApi, 'DeleteIPAddress'); @IpReleaseAddress := GetProcAddress(HIpHlpApi, 'IpReleaseAddress'); @IpRenewAddress := GetProcAddress(HIpHlpApi, 'IpRenewAddress'); @GetIpNetTable := GetProcAddress(HIpHlpApi, 'GetIpNetTable'); @CreateIpNetEntry := GetProcAddress(HIpHlpApi, 'CreateIpNetEntry'); @DeleteIpNetEntry := GetProcAddress(HIpHlpApi, 'DeleteIpNetEntry'); @CreateProxyArpEntry := GetProcAddress(HIpHlpApi, 'CreateProxyArpEntry'); @DeleteProxyArpEntry := GetProcAddress(HIpHlpApi, 'DeleteProxyArpEntry'); @SendARP := GetProcAddress(HIpHlpApi, 'SendARP'); @GetIpStatistics := GetProcAddress(HIpHlpApi, 'GetIpStatistics'); @GetIcmpStatistics := GetProcAddress(HIpHlpApi, 'GetIcmpStatistics'); @SetIpStatistics := GetProcAddress(HIpHlpApi, 'SetIpStatistics'); @SetIpTTL := GetProcAddress(HIpHlpApi, 'SetIpTTL'); @GetIpForwardTable := GetProcAddress(HIpHlpApi,'GetIpForwardTable'); @CreateIpForwardEntry := GetProcAddress(HIpHlpApi, 'CreateIpForwardEntry'); @GetTcpTable := GetProcAddress(HIpHlpApi, 'GetTcpTable'); @GetUdpTable := GetProcAddress(HIpHlpApi, 'GetUdpTable'); @GetTcpStatistics := GetProcAddress(HIpHlpApi, 'GetTcpStatistics'); @GetUdpStatistics := GetProcAddress(HIpHlpApi, 'GetUdpStatistics'); @SetIpForwardEntry := GetProcAddress(HIpHlpApi, 'SetIpForwardEntry'); @DeleteIpForwardEntry := GetProcAddress(HIpHlpApi, 'DeleteIpForwardEntry'); @SetIpNetEntry := GetProcAddress(HIpHlpApi, 'SetIpNetEntry'); @SetTcpEntry := GetProcAddress(HIpHlpApi, 'SetTcpEntry'); @GetBestRoute := GetProcAddress(HIpHlpApi, 'GetBestRoute'); @NotifyAddrChange := GetProcAddress(HIpHlpApi, 'NotifyAddrChange'); @NotifyRouteChange := GetProcAddress(HIpHlpApi, 'NotifyRouteChange'); @GetBestInterface := GetProcAddress(HIpHlpApi, 'GetBestInterface'); @GetRTTAndHopCount := GetProcAddress(HIpHlpApi, 'GetRTTAndHopCount'); @EnableRouter := GetProcAddress(HIpHlpApi, 'EnableRouter'); @UnenableRouter := GetProcAddress(HIpHlpApi, 'UnenableRouter'); Result := True; end; end; procedure IpHlpApiFreeAPI; begin if HIpHlpApi <> 0 then FreeLibrary(HIpHlpApi); HIpHlpApi := 0; end; {$ENDIF} function IpHlpApiCheckAPI: Boolean; begin {$IFDEF IPHLPAPI_DYNLINK} Result := HIpHlpApi <> 0; {$ELSE} Result := True; {$ENDIF} end; initialization {$IFDEF IPHLPAPI_DYNLINK} {$IFNDEF IPHLPAPI_LINKONREQUEST} IpHlpApiInitAPI; {$ENDIF} {$ENDIF} finalization {$IFDEF IPHLPAPI_DYNLINK} IpHlpApiFreeAPI; {$ENDIF} end.
unit tal_uguilauncher; {$mode objfpc}{$H+} interface uses Classes, SysUtils, tal_ilauncher, Forms; type { TGUILauncher } TGUILauncher = class(TInterfacedObject, ILauncher) private fMainForm: IMainForm; protected // ILauncher procedure Launch; protected procedure BeforeLaunch; virtual; procedure AfterLaunch; virtual; public procedure AfterConstruction; override; published property MainForm: IMainForm read fMainForm write fMainForm; end; implementation { TGUILauncher } procedure TGUILauncher.Launch; begin BeforeLaunch; try MainForm.StartUp; try Application.Run; finally MainForm.ShutDown; end; finally AfterLaunch; end; end; procedure TGUILauncher.BeforeLaunch; begin end; procedure TGUILauncher.AfterLaunch; begin end; procedure TGUILauncher.AfterConstruction; begin inherited AfterConstruction; // since mainform could be subject of dependency injection and as such could // be created during create of hierarchy of object, call to inititialization // is put here(at least on windows must be called before main form is created) Application.Initialize; end; end.
procedure PrintMemo; // Imprime um campo memo // Requer a unit Printers declarada na clausula uses da unit var i,col,lin:integer; begin col:=0; // posição da coluna lin:=0; // posição da linha printer.begindoc; for i := 0 to memo1.Lines.Count-1 do begin printer.Canvas.TextOut(col,lin, memo1.Lines[i]); lin := lin + 30; end; printer.Enddoc; end;
unit AutomaticReports; interface uses uCommonForm, Forms,SysUtils,uOilQuery,Ora, uOilStoredProc; procedure MakeAutomaticBasicElectronForm(ADateFrom, ADateTo: TDateTime); procedure MakeAutomaticReports(p_FileName: string); implementation uses RashReport,UReportClass,uTalonPriceReport,Main,TestDb,MovementReport, ReportManager,Rep_Debit,TalonPotrReport; //============================================================================== procedure AlertLog(p_ReportName,p_Error: string); var F: TextFile; begin AssignFile(F,'reports_errors.log'); Append(F); writeln(F,MAIN_ORG.NAME); writeln(F,p_ReportName+': '+p_Error); writeln(F); CloseFile(F); end; //============================================================================== procedure MakeAutomaticBasicElectronForm(ADateFrom, ADateTo: TDateTime); var RM: TRepManagerForm; begin // Базоваю электронная форма try Application.CreateForm(TRepManagerForm,RM); try RM.ActivePage := 120; RM.DateType := dtBetweenDates; RM.Show; RM.DateFrom := ADateFrom; RM.DateTo := ADateTo; RM.bbPrint.Click; finally RM.Free; end; except on E: Exception do AlertLog(TranslateText('Базоваю электронная форма'),E.Message); end; end; //============================================================================== procedure MakeAutomaticReports(p_FileName: string); var F:TRashReportForm; FTP: TTalonPriceReport; FTD: TTestDbForm; TP: TTalonPotrReportForm; MF: TMovementReportForm; RM: TRepManagerForm; BeginDate,EndDate: TDateTime; var RR: TReport; begin BeginDate:=StrToDate('01.01.2004'); EndDate:=StrToDate('31.01.2004'); // Остатки партий в резервуарах try RR:=TReport.Create; try RR.GetFromFile('НБ - Остатки партий'); // *NO_TRANSLATE* RR.Elements[RR.Elements.IndexOf('BEGINDATE')].Res.Add('RESULT='''+DateToStr(BeginDate)+''''); RR.Elements[RR.Elements.IndexOf('ORG1')].FillResFromMainOrg; RR.MakeReport; finally RR.Free; end; except on E: Exception do AlertLog(TranslateText('Остатки партий в резервуарах'),E.Message); end; // Остатки на АЗС try RR:=TReport.Create; try RR.GetFromFile('АЗС - Остатки'); // *NO_TRANSLATE* RR.Elements[RR.Elements.IndexOf('BEGINDATE')].Res.Add('RESULT='''+DateToStr(BeginDate)+''''); RR.Elements[RR.Elements.IndexOf('ORG1')].FillResFromMainOrg; RR.MakeReport; finally RR.Free; end; except on E: Exception do AlertLog(TranslateText('Остатки на АЗС'),E.Message); end; // Отпуск НБ+АЗС try Application.CreateForm(TRashReportForm,F); try F.DateEdit1.Date:=BeginDate; F.DateEdit2.Date:=EndDate; F.CMBSort.ItemIndex:=4; F.CBDate.Checked:=FALSE; F.CBOperation.Checked:=FALSE; F.CBSubPart.Checked:=FALSE; F.BitBtn1.Click; finally F.Free; end; except on E: Exception do AlertLog(TranslateText('Отпуск НБ+АЗС'),E.Message); end; // Наличие талонов в кассе try RR:=TReport.Create; try RR.GetFromFile('ТАЛ - Остатки в кассе'); // *NO_TRANSLATE* RR.Elements[RR.Elements.IndexOf('BEGINDATE')].Res.Add('RESULT='''+DateToStr(BeginDate)+''''); RR.Elements[RR.Elements.IndexOf('ORG1')].FillResFromMainOrg; RR.SetConfByType(2); RR.MakeReport; finally RR.Free; end; except on E: Exception do AlertLog(TranslateText('Наличие талонов в кассе'),E.Message); end; // О перемещении карточек try FTP := TTalonPriceReport.Create(Application); try FTP.ReportNumber := 4; FTP.deBeginDate.Date := BeginDate; FTP.deEndDate.Date := EndDate; FTP.MId := MAIN_ORG.ID; FTP.MInst := MAIN_ORG.INST; FTP.ceOrgName.Text := MAIN_ORG.NAME; FTP.BitBtn2.Click; finally FTP.Free; end; except on E: Exception do AlertLog(TranslateText('О перемещении карточек'),E.Message); end; // Проверки по талонам и карточкам try FTD := TTestDbForm.Create(Application); try FTD.PageControl1.ActivePage:=FTD.TabTalon; FTD.PageControl1Change(nil); FTD.bbPrintTalon.Click; {FTD.PageControl1.ActivePage:=FTD.TabCard; FTD.PageControl1Change(nil); FTD.bbPrintCard.Click;} finally FTD.Free; end; except on E: Exception do AlertLog(TranslateText('Проверки по талонам и карточкам'),E.Message); end; // Хранение Собственный НБ try RR:=TReport.Create; try RR.GetFromFile('ДВ - СобстХран'); // *NO_TRANSLATE* RR.Elements[RR.Elements.IndexOf('BEGINDATE')].Res.Add('RESULT='''+DateToStr(BeginDate)+''''); RR.Elements[RR.Elements.IndexOf('ENDDATE')].Res.Add('RESULT='''+DateToStr(EndDate)+''''); RR.Elements[RR.Elements.IndexOf('ORG1')].FillResFromMainOrg; RR.MakeReport; finally RR.Free; end; except on E: Exception do AlertLog(TranslateText('Хранение собственный НБ'),E.Message); end; // Собственный НБ+АЗС try MF:=TMovementReportForm.Create(Application); try MF.Tip:='Own'; MF.DateEdit1.Date:=BeginDate; MF.DateEdit2.Date:=EndDate; MF.BitBtn1.Click; finally MF.Free; end; except on E: Exception do AlertLog(TranslateText('Собственный НБ+АЗС'),E.Message); end; // Ведомость дебеторов и кредиторов try Application.CreateForm(TRepManagerForm,RM); try RM.Pattern:='Oplata.xls'; RM.Param_NB.activepage:='101'; RM.Date_NB.ActivePage:='Date_2'; RM.FormShow(nil); RM.From_Date2.Date:=BeginDate; RM.To_Date2.Date:=EndDate; RM.bbPrint.Click; finally RM.Free; end; except on E: Exception do AlertLog(TranslateText('Ведомость дебеторов и кредиторов'),E.Message); end; // Ведомость дебеторов и кредиторов по целевому типу "Талоны" try RM := TRepManagerForm.Create(Application); try RM.Pattern:='Oplata.xls'; RM.Param_NB.activepage:='101'; RM.Date_NB.ActivePage:='Date_2'; RM.FormShow(nil); RM.From_Date2.Date:=BeginDate; RM.To_Date2.Date:=EndDate; RM.cb101_Commission.Checked:=FALSE; RM.cb101_Other.Checked:=FALSE; vdbt_Part:='8'; RM.bbPrint.Click; finally RM.Free; end; except on E: Exception do AlertLog(TranslateText('Целевая талонная дебеторка'),E.Message); end; // Талоны - По потребителям - Движение try TP:=TTalonPotrReportForm.Create(Application); try TP.deBeginDate.Date:=BeginDate; TP.deEndDate.Date:=EndDate; TP.ReportNumber := 1; TP.rgTalonReportType.ItemIndex:=3; TP.rgTalonReportType.OnClick(nil); TP.BitBtn1.Click; finally TP.Free; end; except on E: Exception do AlertLog(TranslateText('Талоны по потребителям Движение'),E.Message); end; // Карты - По потребителям - Движение try TP:=TTalonPotrReportForm.Create(Application); try TP.deBeginDate.Date:=BeginDate; TP.deEndDate.Date:=EndDate; TP.ReportNumber := 2; TP.rgCardReportType.ItemIndex:=3; TP.rgCardReportType.OnClick(nil); TP.BitBtn1.Click; finally TP.Free; end; except on E: Exception do AlertLog(TranslateText('Карты по потребителям движение'),E.Message); end; // Дебеторка по талонам try FTP := TTalonPriceReport.Create(Application); try FTP.ReportNumber := 2; FTP.deBeginDate.Date := BeginDate; FTP.deEndDate.Date := EndDate; FTP.MId := MAIN_ORG.ID; FTP.MInst := MAIN_ORG.INST; FTP.ceOrgName.Text := MAIN_ORG.NAME; FTP.BitBtn2.Click; finally FTP.Free; end; except on E: Exception do AlertLog(TranslateText('Дебеторка по талонам'),E.Message); end; end; //============================================================================== end.
unit TpImageButton; interface uses Windows, Classes, Controls, StdCtrls, ExtCtrls, Graphics, Messages, SysUtils, Types, ThTag, ThAnchor, ThImageButton, TpControls, TpAnchor; type TTpImageButton = class(TThImageButton) private FOnClick: TTpEvent; FOnGenerate: TTpEvent; FUseAbsoluteUrl: Boolean; protected // function GetImageSrc: string; override; protected function CreateAnchor: TThAnchor; override; procedure Tag(inTag: TThTag); override; published property OnClick: TTpEvent read FOnClick write FOnClick; property OnGenerate: TTpEvent read FOnGenerate write FOnGenerate; property UseAbsoluteUrl: Boolean read FUseAbsoluteUrl write FUseAbsoluteUrl; end; implementation uses ThPathUtils{, TpProject, DocumentManager}; { TTpImageButton } function TTpImageButton.CreateAnchor: TThAnchor; begin Result := TTpAnchor.Create(Self); end; { function TTpImageButton.GetImageSrc: string; begin if UseAbsoluteUrl then begin Result := ExtractRelativePath(CurrentProject.Folder, Picture.PicturePath); Result := CurrentProject.Url + Result; end else Result := ExtractRelativePath(DocumentManagerForm.CurrentItem.Path, Picture.PicturePath); Result := ThPathToUrl(Result); end; } procedure TTpImageButton.Tag(inTag: TThTag); begin inherited; inTag.Add(tpClass, 'TTpImageButton'); inTag.Add('tpName', Name); inTag.Add('tpOnClick', OnClick); inTag.Add('tpOnGenerate', OnGenerate); end; end.
{ * ZIOThread * } { ****************************************************************************** } { * https://zpascal.net * } { * https://github.com/PassByYou888/zAI * } { * https://github.com/PassByYou888/ZServer4D * } { * https://github.com/PassByYou888/PascalString * } { * https://github.com/PassByYou888/zRasterization * } { * https://github.com/PassByYou888/CoreCipher * } { * https://github.com/PassByYou888/zSound * } { * https://github.com/PassByYou888/zChinese * } { * https://github.com/PassByYou888/zExpression * } { * https://github.com/PassByYou888/zGameWare * } { * https://github.com/PassByYou888/zAnalysis * } { * https://github.com/PassByYou888/FFMPEG-Header * } { * https://github.com/PassByYou888/zTranslate * } { * https://github.com/PassByYou888/InfiniteIoT * } { * https://github.com/PassByYou888/FastMD5 * } { ****************************************************************************** } unit ZIOThread; {$INCLUDE zDefine.inc} interface uses {$IFDEF FPC} FPCGenericStructlist, {$ENDIF FPC} CoreClasses, DoStatusIO; type TIOData = class; TIODataState = (idsDone, idsRunning, idsReady, idsInited); TIOThread_Call = procedure(Sender: TIOData); TIOThread_Method = procedure(Sender: TIOData) of object; {$IFDEF FPC} TIOThread_Proc = procedure(Sender: TIOData) is nested; {$ELSE FPC} TIOThread_Proc = reference to procedure(Sender: TIOData); {$ENDIF FPC} TIOData = class private FState: TIODataState; FOnCall: TIOThread_Call; FOnMethod: TIOThread_Method; FOnProc: TIOThread_Proc; public Data: Pointer; constructor Create; virtual; destructor Destroy; override; procedure Process; virtual; property OnCall: TIOThread_Call read FOnCall write FOnCall; property OnMethod: TIOThread_Method read FOnMethod write FOnMethod; property OnProc: TIOThread_Proc read FOnProc write FOnProc; end; TIODataQueue_Decl = {$IFDEF FPC}specialize {$ENDIF FPC} TGenericsList<TIOData>; TIODataQueue = class(TIODataQueue_Decl) public procedure Clean; end; TIO_Interface = interface function Count(): Integer; property QueueCount: Integer read Count; procedure EnQueue(Queue_: TIODataQueue); overload; procedure EnQueue(IOData: TIOData); overload; procedure EnQueueC(IOData: TIOData; Data: Pointer; OnCall: TIOThread_Call); procedure EnQueueM(IOData: TIOData; Data: Pointer; OnMethod: TIOThread_Method); procedure EnQueueP(IOData: TIOData; Data: Pointer; OnProc: TIOThread_Proc); function DeQueue(wait_: Boolean): TIOData; overload; procedure DeQueue(wait_: Boolean; Queue_: TIODataQueue); overload; procedure Wait; end; TIO_Thread = class(TCoreClassInterfacedObject, TIO_Interface) protected FCritical: TCritical; FThRunning: TAtomBool; FThNum: Integer; FQueue: TIODataQueue; procedure ThRun(Sender: TCompute); public constructor Create(ThNum_: Integer); destructor Destroy; override; procedure Reset(); procedure ClearQueue(); procedure ThEnd(); function Count(): Integer; property QueueCount: Integer read Count; procedure EnQueue(Queue_: TIODataQueue); overload; procedure EnQueue(IOData: TIOData); overload; procedure EnQueueC(IOData: TIOData; Data: Pointer; OnCall: TIOThread_Call); procedure EnQueueM(IOData: TIOData; Data: Pointer; OnMethod: TIOThread_Method); procedure EnQueueP(IOData: TIOData; Data: Pointer; OnProc: TIOThread_Proc); function DeQueue(wait_: Boolean): TIOData; overload; procedure DeQueue(wait_: Boolean; Queue_: TIODataQueue); overload; procedure Wait; class procedure Test(); end; TIO_Direct = class(TCoreClassInterfacedObject, TIO_Interface) protected FCritical: TCritical; FQueue: TIODataQueue; public constructor Create; destructor Destroy; override; procedure Reset(); procedure ClearQueue(); function Count(): Integer; property QueueCount: Integer read Count; procedure EnQueue(Queue_: TIODataQueue); overload; procedure EnQueue(IOData: TIOData); overload; procedure EnQueueC(IOData: TIOData; Data: Pointer; OnCall: TIOThread_Call); procedure EnQueueM(IOData: TIOData; Data: Pointer; OnMethod: TIOThread_Method); procedure EnQueueP(IOData: TIOData; Data: Pointer; OnProc: TIOThread_Proc); function DeQueue(wait_: Boolean): TIOData; overload; procedure DeQueue(wait_: Boolean; Queue_: TIODataQueue); overload; procedure Wait; class procedure Test(); end; TPost_ThreadPool = class; TPost_Thread = class private FOwner: TPost_ThreadPool; FBindTh: TCompute; FPost: TThreadPost; FActivted: TAtomBool; procedure ThRun(thSender: TCompute); public constructor Create(Owner_: TPost_ThreadPool); destructor Destroy; override; property BindTh: TCompute read FBindTh; property Post: TThreadPost read FPost; procedure PostC1(OnSync: TThreadPostCall1); procedure PostC2(Data1: Pointer; OnSync: TThreadPostCall2); procedure PostC3(Data1: Pointer; Data2: TCoreClassObject; Data3: Variant; OnSync: TThreadPostCall3); procedure PostC4(Data1: Pointer; Data2: TCoreClassObject; OnSync: TThreadPostCall4); procedure PostM1(OnSync: TThreadPostMethod1); procedure PostM2(Data1: Pointer; OnSync: TThreadPostMethod2); procedure PostM3(Data1: Pointer; Data2: TCoreClassObject; Data3: Variant; OnSync: TThreadPostMethod3); procedure PostM4(Data1: Pointer; Data2: TCoreClassObject; OnSync: TThreadPostMethod4); procedure PostP1(OnSync: TThreadPostProc1); procedure PostP2(Data1: Pointer; OnSync: TThreadPostProc2); procedure PostP3(Data1: Pointer; Data2: TCoreClassObject; Data3: Variant; OnSync: TThreadPostProc3); procedure PostP4(Data1: Pointer; Data2: TCoreClassObject; OnSync: TThreadPostProc4); end; TPost_ThreadPool_Decl = {$IFDEF FPC}specialize {$ENDIF FPC} TGenericsList<TPost_Thread>; TPost_ThreadPool = class(TPost_ThreadPool_Decl) private FCritical: TCritical; FQueueOptimized: Boolean; FNextID: Integer; procedure AddTh(th: TPost_Thread); procedure RemoveTh(th: TPost_Thread); public constructor Create(ThNum_: Integer); destructor Destroy; override; property QueueOptimized: Boolean read FQueueOptimized write FQueueOptimized; function ThNum: Integer; function TaskNum: Integer; procedure Wait(); overload; procedure Wait(th: TPost_Thread); overload; function Next_Thread: TPost_Thread; function MinLoad_Thread: TPost_Thread; function IDLE_Thread: TPost_Thread; procedure DoTestCall(); class procedure Test(); end; procedure Test_IOData_Call(Sender: TIOData); implementation procedure Test_IOData_Call(Sender: TIOData); begin TCompute.Sleep(0); end; constructor TIOData.Create; begin inherited Create; FState := idsInited; FOnCall := nil; FOnMethod := nil; FOnProc := nil; Data := nil; end; destructor TIOData.Destroy; begin inherited Destroy; end; procedure TIOData.Process; begin try if Assigned(FOnCall) then FOnCall(Self); if Assigned(FOnMethod) then FOnMethod(Self); if Assigned(FOnProc) then FOnProc(Self); except end; end; procedure TIODataQueue.Clean; var i: Integer; begin for i := 0 to Count - 1 do DisposeObject(items[i]); inherited Clear; end; procedure TIO_Thread.ThRun(Sender: TCompute); var i: Integer; d: TIOData; LTK, L: TTimeTick; begin AtomInc(FThNum); LTK := GetTimeTick(); while FThRunning.V do begin FCritical.Lock; d := nil; if FQueue.Count > 0 then for i := 0 to FQueue.Count - 1 do if FQueue[i].FState = idsReady then begin d := FQueue[i]; break; end; if d <> nil then begin d.FState := idsRunning; FCritical.UnLock; d.Process; FCritical.Lock; d.FState := idsDone; FCritical.UnLock; LTK := GetTimeTick(); end else begin FCritical.UnLock; L := GetTimeTick() - LTK; if L > 1000 then TCompute.Sleep(1); end; end; AtomDec(FThNum); end; constructor TIO_Thread.Create(ThNum_: Integer); var i: Integer; begin inherited Create; FCritical := TCritical.Create; FThRunning := TAtomBool.Create(True); FThNum := 0; FQueue := TIODataQueue.Create; for i := 0 to ThNum_ - 1 do TCompute.RunM({$IFDEF FPC}@{$ENDIF FPC}ThRun); while FThNum < ThNum_ do TCompute.Sleep(1); end; destructor TIO_Thread.Destroy; begin ThEnd(); FCritical.Free; FThRunning.Free; DisposeObject(FQueue); inherited Destroy; end; procedure TIO_Thread.Reset; var n, i: Integer; begin n := FThNum; ThEnd(); FThNum := 0; for i := 0 to n - 1 do TCompute.RunM({$IFDEF FPC}@{$ENDIF FPC}ThRun); while FThNum < n do TCompute.Sleep(1); end; procedure TIO_Thread.ClearQueue(); var i: Integer; begin FCritical.Lock; i := 0; while i < FQueue.Count do if FQueue[i].FState = idsDone then begin DisposeObject(FQueue[i]); FQueue.Delete(i); end else inc(i); FCritical.UnLock; end; procedure TIO_Thread.ThEnd(); var i: Integer; begin FThRunning.V := False; while FThNum > 0 do TCompute.Sleep(1); FCritical.Lock; for i := 0 to FQueue.Count - 1 do DisposeObject(FQueue[i]); FQueue.Clear; FCritical.UnLock; end; function TIO_Thread.Count(): Integer; begin FCritical.Lock; Result := FQueue.Count; FCritical.UnLock; end; procedure TIO_Thread.EnQueue(Queue_: TIODataQueue); var i: Integer; begin FCritical.Lock; for i := 0 to Queue_.Count - 1 do begin Queue_[i].FState := idsReady; FQueue.Add(Queue_[i]); end; FCritical.UnLock; end; procedure TIO_Thread.EnQueue(IOData: TIOData); begin if IOData.FState <> idsInited then RaiseInfo('illegal error.'); IOData.FState := idsReady; FCritical.Lock; FQueue.Add(IOData); FCritical.UnLock; end; procedure TIO_Thread.EnQueueC(IOData: TIOData; Data: Pointer; OnCall: TIOThread_Call); begin IOData.Data := Data; IOData.FOnCall := OnCall; EnQueue(IOData); end; procedure TIO_Thread.EnQueueM(IOData: TIOData; Data: Pointer; OnMethod: TIOThread_Method); begin IOData.Data := Data; IOData.FOnMethod := OnMethod; EnQueue(IOData); end; procedure TIO_Thread.EnQueueP(IOData: TIOData; Data: Pointer; OnProc: TIOThread_Proc); begin IOData.Data := Data; IOData.FOnProc := OnProc; EnQueue(IOData); end; function TIO_Thread.DeQueue(wait_: Boolean): TIOData; var n: Integer; begin repeat Result := nil; FCritical.Lock; n := FQueue.Count; if n > 0 then if FQueue[0].FState = idsDone then begin Result := FQueue[0]; FQueue.Delete(0); end; FCritical.UnLock; if (wait_) and (n = 0) then TCompute.Sleep(1); until (not wait_) or (n = 0) or (Result <> nil); end; procedure TIO_Thread.DeQueue(wait_: Boolean; Queue_: TIODataQueue); var n, doneNum: Integer; i: Integer; begin repeat doneNum := 0; FCritical.Lock; n := FQueue.Count; if n > 0 then begin i := 0; while i < FQueue.Count do begin if FQueue[i].FState = idsDone then begin Queue_.Add(FQueue[i]); FQueue.Delete(i); inc(doneNum); end else inc(i); end; end; FCritical.UnLock; if (wait_) and (n = 0) then TCompute.Sleep(1); until (not wait_) or (n = 0) or (doneNum = 0); end; procedure TIO_Thread.Wait; begin while Count > 0 do TCompute.Sleep(1); end; class procedure TIO_Thread.Test(); var i: Integer; d: TIOData; begin with TIO_Thread.Create(5) do begin for i := 0 to 1000 - 1 do EnQueueC(TIOData.Create, nil, {$IFDEF FPC}@{$ENDIF FPC}Test_IOData_Call); while Count > 0 do DeQueue(True).Free; Free; end; end; constructor TIO_Direct.Create; begin inherited Create; FCritical := TCritical.Create; FQueue := TIODataQueue.Create; end; destructor TIO_Direct.Destroy; begin ClearQueue(); FCritical.Free; DisposeObject(FQueue); inherited Destroy; end; procedure TIO_Direct.Reset; begin ClearQueue; end; procedure TIO_Direct.ClearQueue; var i: Integer; begin FCritical.Lock; for i := 0 to FQueue.Count - 1 do DisposeObject(FQueue[i]); FQueue.Clear; FCritical.UnLock; end; function TIO_Direct.Count: Integer; begin FCritical.Lock; Result := FQueue.Count; FCritical.UnLock; end; procedure TIO_Direct.EnQueue(Queue_: TIODataQueue); var i: Integer; begin FCritical.Lock; for i := 0 to Queue_.Count - 1 do begin Queue_[i].FState := idsRunning; Queue_[i].Process; Queue_[i].FState := idsDone; FQueue.Add(Queue_[i]); end; FCritical.UnLock; end; procedure TIO_Direct.EnQueue(IOData: TIOData); begin if IOData.FState <> idsInited then RaiseInfo('illegal error.'); FCritical.Lock; IOData.FState := idsRunning; IOData.Process; IOData.FState := idsDone; FQueue.Add(IOData); FCritical.UnLock; end; procedure TIO_Direct.EnQueueC(IOData: TIOData; Data: Pointer; OnCall: TIOThread_Call); begin IOData.Data := Data; IOData.FOnCall := OnCall; EnQueue(IOData); end; procedure TIO_Direct.EnQueueM(IOData: TIOData; Data: Pointer; OnMethod: TIOThread_Method); begin IOData.Data := Data; IOData.FOnMethod := OnMethod; EnQueue(IOData); end; procedure TIO_Direct.EnQueueP(IOData: TIOData; Data: Pointer; OnProc: TIOThread_Proc); begin IOData.Data := Data; IOData.FOnProc := OnProc; EnQueue(IOData); end; function TIO_Direct.DeQueue(wait_: Boolean): TIOData; var n: Integer; begin repeat Result := nil; FCritical.Lock; n := FQueue.Count; if n > 0 then if FQueue[0].FState = idsDone then begin Result := FQueue[0]; FQueue.Delete(0); end; FCritical.UnLock; until (not wait_) or (n = 0) or (Result <> nil); end; procedure TIO_Direct.DeQueue(wait_: Boolean; Queue_: TIODataQueue); var n, doneNum: Integer; i: Integer; begin repeat doneNum := 0; FCritical.Lock; n := FQueue.Count; if n > 0 then begin i := 0; while i < FQueue.Count do begin if FQueue[i].FState = idsDone then begin Queue_.Add(FQueue[i]); FQueue.Delete(i); inc(doneNum); end else inc(i); end; end; FCritical.UnLock; until (not wait_) or (n = 0) or (doneNum = 0); end; procedure TIO_Direct.Wait; begin while Count > 0 do TCompute.Sleep(1); end; class procedure TIO_Direct.Test; var i: Integer; d: TIOData; begin with TIO_Direct.Create do begin for i := 0 to 1000 - 1 do EnQueueC(TIOData.Create, nil, {$IFDEF FPC}@{$ENDIF FPC}Test_IOData_Call); while Count > 0 do DeQueue(True).Free; Free; end; end; procedure TPost_Thread.ThRun(thSender: TCompute); var L: Integer; LastTK, IdleTK: TTimeTick; begin FBindTh := thSender; FPost := TThreadPost.Create(thSender.ThreadID); FPost.OneStep := False; FPost.ResetRandomSeed := False; FActivted := TAtomBool.Create(True); FOwner.AddTh(Self); LastTK := GetTimeTick(); while FActivted.V do begin L := FPost.Progress(FPost.ThreadID); if L > 0 then LastTK := GetTimeTick() else begin IdleTK := GetTimeTick() - LastTK; if IdleTK > 1000 then TCompute.Sleep(1); end; end; FBindTh := nil; DisposeObjectAndNil(FPost); DisposeObjectAndNil(FActivted); FOwner.RemoveTh(Self); Free; end; constructor TPost_Thread.Create(Owner_: TPost_ThreadPool); begin inherited Create; FOwner := Owner_; FBindTh := nil; FPost := nil; FActivted := nil; TCompute.RunM(nil, Self, {$IFDEF FPC}@{$ENDIF FPC}ThRun); end; destructor TPost_Thread.Destroy; begin inherited Destroy; end; procedure TPost_Thread.PostC1(OnSync: TThreadPostCall1); begin FPost.PostC1(OnSync); end; procedure TPost_Thread.PostC2(Data1: Pointer; OnSync: TThreadPostCall2); begin FPost.PostC2(Data1, OnSync); end; procedure TPost_Thread.PostC3(Data1: Pointer; Data2: TCoreClassObject; Data3: Variant; OnSync: TThreadPostCall3); begin FPost.PostC3(Data1, Data2, Data3, OnSync); end; procedure TPost_Thread.PostC4(Data1: Pointer; Data2: TCoreClassObject; OnSync: TThreadPostCall4); begin FPost.PostC4(Data1, Data2, OnSync); end; procedure TPost_Thread.PostM1(OnSync: TThreadPostMethod1); begin FPost.PostM1(OnSync); end; procedure TPost_Thread.PostM2(Data1: Pointer; OnSync: TThreadPostMethod2); begin FPost.PostM2(Data1, OnSync); end; procedure TPost_Thread.PostM3(Data1: Pointer; Data2: TCoreClassObject; Data3: Variant; OnSync: TThreadPostMethod3); begin FPost.PostM3(Data1, Data2, Data3, OnSync); end; procedure TPost_Thread.PostM4(Data1: Pointer; Data2: TCoreClassObject; OnSync: TThreadPostMethod4); begin FPost.PostM4(Data1, Data2, OnSync); end; procedure TPost_Thread.PostP1(OnSync: TThreadPostProc1); begin FPost.PostP1(OnSync); end; procedure TPost_Thread.PostP2(Data1: Pointer; OnSync: TThreadPostProc2); begin FPost.PostP2(Data1, OnSync); end; procedure TPost_Thread.PostP3(Data1: Pointer; Data2: TCoreClassObject; Data3: Variant; OnSync: TThreadPostProc3); begin FPost.PostP3(Data1, Data2, Data3, OnSync); end; procedure TPost_Thread.PostP4(Data1: Pointer; Data2: TCoreClassObject; OnSync: TThreadPostProc4); begin FPost.PostP4(Data1, Data2, OnSync); end; procedure TPost_ThreadPool.AddTh(th: TPost_Thread); begin FCritical.Lock; Add(th); FCritical.UnLock; end; procedure TPost_ThreadPool.RemoveTh(th: TPost_Thread); var i: Integer; begin FCritical.Lock; i := 0; while i < Count do begin if items[i] = th then Delete(i) else inc(i); end; FCritical.UnLock; end; constructor TPost_ThreadPool.Create(ThNum_: Integer); var i: Integer; begin inherited Create; FCritical := TCritical.Create; FNextID := 0; FQueueOptimized := True; for i := 0 to ThNum_ - 1 do TPost_Thread.Create(Self); while ThNum() < ThNum_ do TCompute.Sleep(1); end; destructor TPost_ThreadPool.Destroy; var i: Integer; begin FCritical.Lock; for i := 0 to Count - 1 do items[i].FActivted.V := False; FCritical.UnLock; while ThNum > 0 do TCompute.Sleep(1); DisposeObject(FCritical); inherited Destroy; end; function TPost_ThreadPool.ThNum: Integer; begin FCritical.Lock; Result := Count; FCritical.UnLock; end; function TPost_ThreadPool.TaskNum: Integer; var i: Integer; begin FCritical.Lock; Result := 0; for i := 0 to Count - 1 do inc(Result, items[i].FPost.Count); FCritical.UnLock; end; procedure TPost_ThreadPool.Wait; begin while TaskNum > 0 do TCompute.Sleep(1); end; procedure TPost_ThreadPool.Wait(th: TPost_Thread); begin while th.FPost.Count > 0 do TCompute.Sleep(1); end; function TPost_ThreadPool.Next_Thread: TPost_Thread; begin if ThNum = 0 then RaiseInfo('pool is empty.'); FCritical.Acquire; try if FNextID >= Count then FNextID := 0; Result := items[FNextID]; inc(FNextID); finally FCritical.Release; end; end; function TPost_ThreadPool.MinLoad_Thread: TPost_Thread; var i, id_: Integer; th: TPost_Thread; begin if ThNum = 0 then RaiseInfo('pool is empty.'); FCritical.Acquire; try for i := 0 to Count - 1 do if (not items[i].FPost.Busy) then begin if (FQueueOptimized) and (i < Count - 1) then Move(i, Count - 1); Result := items[i]; exit; end; th := items[0]; id_ := 0; for i := 1 to Count - 1 do if items[i].FPost.Count < th.FPost.Count then begin th := items[i]; id_ := i; end; if (FQueueOptimized) and (id_ < Count - 1) then Move(id_, Count - 1); Result := th; finally FCritical.Release; end; end; function TPost_ThreadPool.IDLE_Thread: TPost_Thread; var i: Integer; begin if ThNum = 0 then RaiseInfo('pool is empty.'); FCritical.Acquire; Result := nil; try for i := 0 to Count - 1 do if not items[i].FPost.Busy then exit(items[i]); finally FCritical.Release; end; end; procedure TPost_ThreadPool.DoTestCall; begin DoStatus('current post thread: %d', [TCompute.CurrentThread.ThreadID]); end; class procedure TPost_ThreadPool.Test; var pool: TPost_ThreadPool; i: Integer; begin pool := TPost_ThreadPool.Create(2); for i := 0 to 9 do pool.Next_Thread.PostM1({$IFDEF FPC}@{$ENDIF FPC}pool.DoTestCall); pool.Wait; for i := 0 to 9 do pool.MinLoad_Thread.PostM1({$IFDEF FPC}@{$ENDIF FPC}pool.DoTestCall); pool.Wait; DisposeObject(pool); end; end.
unit UInventori; interface uses UTipe,UTanggal,USimulasi,UUI,sysutils; var DaftarBahanM : DaftarBahanMentah; DaftarBahanO : DaftarBahanOlahan; InventoriM : InventoriBahanMentah; InventoriO : InventoriBahanOlahan; function isBahanAda(input : string) : boolean; {menerima input nama bahan dan cek apakah bahan ada} function beliBahan(input : string; JumlahBeli : integer):longint; {Menerima nama Bahan dan Jumlah yang mau dibeli. Mengembalikan total harga yang dikeluarkan, mengembalikan -1 jika error} function jualOlahan(input : string; JumlahJual:integer):longint; {Menerima namaOlahan yang ingin dijual dan jumlah yang ingin dijual. Mengembalikan nilai uang yang didapat, mengembalikan -1 jika error} procedure kuranginBahan(input : string; var Error : boolean); {I.S : membaca namaBahan } {F.S : Mengurangi bahan sebanyak 1 , jika error variabel Error akan bernilai true} procedure hapusKadaluarsa(); {I.S : terdefinisi tanggal simulasi dan inventori} {F.S : Menghapus bahan-bahan yang sudah kadaluarsa, bahan mentah kadaluarsa berbeda-beda tergantung jenis bahan, untuk olahan kadaluarsa 3 hari dari setelah dibuat} procedure lihatInventori(); {I.S : InventoriM dan InventoriO terdefinisi} {F.S : Menampilkan daftar inventori keseluruhan} procedure olahBahan(input : string; var Error : boolean); {I.S : Menerima input Nama bahan olahan yang ingin diolah} {F.S : Mengolah bahan-bahan mentah menjadi 1 bahan olahan, jika error variabel Error akan bernilai true} procedure sortArray(); {I.S : InventoriM dan InventoriO terdefinisi} {F.S : Menyortir keseluruhan inventoriM dan inventoriO} function searchIndex(input : string; kode : string): integer; {Menerima nama bahan yang dicari beserta kode tempat mencari, lalu mengembalikan posisi indeks di daftar yang sesuai dan punya kadaluarsa paling cepat jika inventori, mengoutput -1 jika tidak ada} implementation procedure hapusKadaluarsa(); {Kamus Lokal} var i : integer; count : integer; {Algoritma hapusKadaluarsa} begin {cek inventori bahan mentah -> expired sesuai jenis bahan} count:=0; for i := 1 to InventoriM.Neff do begin {Jika dengan alasan tertentu tanggal beli bisa lebih dari tanggal simulasi, abaikan} if (isTanggalDuluan(InventoriM.TanggalBeli[i],SimulasiAktif.Tanggal))then begin {expired sesuai jenis bahan} if (selisihTanggal(InventoriM.TanggalBeli[i],SimulasiAktif.Tanggal) > InventoriM.Isi[i].Kadaluarsa) then begin count:= count + InventoriM.Jumlah[i]; InventoriM.Jumlah[i] := 0; inventoriM.Total:= inventoriM.Total - count; end; end; end; {cek inventori bahan olahan -> expired 3 hari} count:=0; for i := 1 to InventoriO.Neff do begin {Jika dengan alasan tertentu tanggal buat bisa lebih dari tanggal simulasi, abaikan} if(isTanggalDuluan(InventoriO.TanggalBuat[i],SimulasiAktif.Tanggal))then begin {expired 3 hari} if (selisihTanggal(InventoriO.TanggalBuat[i],SimulasiAktif.Tanggal)>3) then begin count := count + InventoriO.Jumlah[i]; InventoriO.Jumlah[i] := 0; inventoriO.Total := inventoriO.Total - count; end; end; end; end; procedure lihatInventori(); {KAMUS LOKAL} var i:integer; IsiTabel:Tabel; Ukuran:UkuranTabel; {ALGORITMA - lihatInventori} begin IsiTabel.Isi[1][1]:='NAMA BAHAN'; IsiTabel.Isi[1][2]:='JUMLAH'; IsiTabel.Isi[1][3]:='TANGGAL BELI'; Ukuran.Kolom:=3; Ukuran.Ukuran[1]:=20; Ukuran.Ukuran[2]:=11; Ukuran.Ukuran[3]:=11; for i := 1 to InventoriM.Neff do begin IsiTabel.Isi[i+1][1]:=InventoriM.Isi[i].Nama; IsiTabel.Isi[i+1][2]:=IntToStr(InventoriM.Jumlah[i]); IsiTabel.Isi[i+1][3]:=IntToStr(InventoriM.TanggalBeli[i].Hari)+'/'+IntToStr(InventoriM.TanggalBeli[i].Bulan)+'/'+IntToStr(InventoriM.TanggalBeli[i].Tahun); end; IsiTabel.NBar:=InventoriM.Neff+1; IsiTabel.NKol:=3; writeTabel(IsiTabel,Ukuran,'DAFTAR INVENTORI BAHAN MENTAH'); writelnText('Total : '+ IntToStr(InventoriM.Total)); writelnText(''); IsiTabel.Isi[1][1]:='NAMA BAHAN'; IsiTabel.Isi[1][2]:='JUMLAH'; IsiTabel.Isi[1][3]:='TANGGAL BUAT'; Ukuran.Kolom:=3; Ukuran.Ukuran[1]:=20; Ukuran.Ukuran[2]:=11; Ukuran.Ukuran[3]:=11; for i:=1 to InventoriO.Neff do begin IsiTabel.Isi[i+1][1]:=InventoriO.Isi[i].Nama; IsiTabel.Isi[i+1][2]:=IntToStr(InventoriO.Jumlah[i]); IsiTabel.Isi[i+1][3]:=IntToStr(InventoriO.TanggalBuat[i].Hari)+'/'+IntToStr(InventoriO.TanggalBuat[i].Bulan)+'/'+IntToStr(InventoriO.TanggalBuat[i].Tahun); end; IsiTabel.NBar:=InventoriO.Neff+1; IsiTabel.NKol:=3; writeTabel(IsiTabel,Ukuran,'DAFTAR INVENTORI BAHAN OLAHAN'); writelnText('Total : '+ IntToStr(InventoriO.Total)); end; function isBahanAda(input : string): boolean; {KAMUS LOKAL} var Ketemu : boolean; id:integer; {Algoritma - isBahanAda} begin Ketemu := false; id:=searchIndex(input, 'IM'); {jika id = -1 artinya tidak ketemu} if(id=-1)then begin id:=searchIndex(input, 'IO'); if(id<>-1)then begin Ketemu:=true; end; end else begin Ketemu := true; end; isBahanAda := Ketemu; end; function beliBahan(input : string; JumlahBeli : integer):longint; {KAMUS LOKAL} var j : integer; {increment} IndeksBahan : integer; {index bahan} BahanDibeli : BahanMentah; AdaSama : boolean; IndeksSama : integer; Uang : longint; {Algoritma BeliBahan} begin Uang:=-1; {cek apa masih ada kapasitas} if ((InventoriM.Total + InventoriO.Total + JumlahBeli) > SimulasiAktif.Kapasitas) then begin writeError('UInventori','Inventori tidak cukup'); end else begin {cek apa bahan ada} IndeksBahan := searchIndex(input, 'DM'); if (IndeksBahan <> -1) then begin {cek apa ada uang} if ((DaftarBahanM.Isi[IndeksBahan].Harga*JumlahBeli) > SimulasiAktif.TotalUang) then begin writeError('UInventori','Uang tidak cukup'); end else begin Uang:=DaftarBahanM.Isi[IndeksBahan].Harga*JumlahBeli; AdaSama := false; for j := 1 to InventoriM.Neff do begin {cek apa sudah ada entri} if (InventoriM.Isi[j].Nama = input) then begin {Kalau ada entri yang tanggalnya sama, catat} if (isTanggalSama(InventoriM.TanggalBeli[j],SimulasiAktif.Tanggal)) then begin AdaSama := true; IndeksSama := j; end; end; end; BahanDibeli := DaftarBahanM.Isi[IndeksBahan]; {menambahkan entri} if (not(AdaSama)) then begin InventoriM.Isi[InventoriM.Neff+1] := BahanDibeli; InventoriM.Jumlah[InventoriM.Neff+1] := JumlahBeli; InventoriM.TanggalBeli[InventoriM.Neff+1] := SimulasiAktif.Tanggal; InventoriM.Neff := InventoriM.Neff + 1; InventoriM.Total := InventoriM.Total + JumlahBeli; InventoriM.Sorted:=false; end else begin InventoriM.Jumlah[IndeksSama] := InventoriM.Jumlah[IndeksSama] + JumlahBeli; InventoriM.Total := InventoriM.Total + JumlahBeli; end; end; end else begin writeError('UInventori','Bahan yang ingin dibeli (' + input + ') tidak terdaftar'); end; end; beliBahan:=uang; end; function jualOlahan(input : string; JumlahJual:integer) : longint; {KAMUS LOKAL} var UangDapat : longint; IndeksBahan : integer; {Algoritma jualOlahan} begin UangDapat := -1; IndeksBahan := searchIndex(input, 'IO'); {cek apa ada yang mau dijual} if (IndeksBahan <> -1) then begin if (InventoriO.Jumlah[IndeksBahan] < JumlahJual) then begin writeError('UInventori','Bahan olahan yang ingin dijual (' + input + ') tidak cukup'); end else begin {Mengurangi nilai jumlah bahan olahan di inventori sebesar kuantitas yang dijual} InventoriO.Jumlah[IndeksBahan] := InventoriO.Jumlah[IndeksBahan] - JumlahJual; {Menambah UangDapat} UangDapat := (JumlahJual*InventoriO.Isi[IndeksBahan].Harga); InventoriO.Total := InventoriO.Total - JumlahJual; end; end else begin writeError('UInventori','Bahan olahan yang ingin dijual (' + input + ') tidak ada'); end; jualOlahan := UangDapat end; procedure olahBahan(input : string; var Error : boolean); {KAMUS LOKAL} var j : integer; IndeksBahan : integer; BisaBuat : boolean; AdaSama : boolean; IndeksSama : integer; BahanDibuat : BahanOlahan; isError : boolean; {Algoritma olahBahan} begin Error := false; {cari bahan olahan yg mau dibuat untuk tahu bahan-bahannya} IndeksBahan := searchIndex(input,'DO'); if (IndeksBahan <> -1) then begin BisaBuat := true; j := 1; {cek tiap item apakah ada bahannya} while ((j <= DaftarBahanO.Isi[IndeksBahan].JumlahBahan) and (BisaBuat)) do begin if (not(isBahanAda(DaftarBahanO.Isi[IndeksBahan].Bahan[j]))) then begin BisaBuat := false; writeError('UInventori','Tidak ada bahan yang dibutuhkan (' + DaftarBahanO.Isi[IndeksBahan].Bahan[j] + ')'); end; j := j+1; end; if(BisaBuat)then begin {kurangi bahan mentah yang diperlukan} for j := 1 to DaftarBahanO.Isi[IndeksBahan].JumlahBahan do begin kuranginBahan(DaftarBahanO.Isi[IndeksBahan].Bahan[j],isError); end; {cek apakah sudah ada entri bahan olahan dengan jenis dan tanggal sama} AdaSama := false; for j := 1 to InventoriO.Neff do begin //cek apa sudah ada entri if (InventoriO.Isi[j].Nama = input) then begin if (isTanggalSama(InventoriO.TanggalBuat[j],SimulasiAktif.Tanggal)) then begin AdaSama := true; IndeksSama := j; end; end; end; BahanDibuat := DaftarBahanO.Isi[IndeksBahan]; {tambah entri} if (not(AdaSama)) then begin InventoriO.Isi[InventoriO.Neff+1] := BahanDibuat; InventoriO.Jumlah[InventoriO.Neff+1] := 1; InventoriO.TanggalBuat[InventoriO.Neff +1] := SimulasiAktif.Tanggal; InventoriO.Neff := InventoriO.Neff + 1; InventoriO.Sorted := false; end else begin InventoriO.Jumlah[IndeksSama] := InventoriO.Jumlah[IndeksSama] + 1; end; InventoriO.Total := InventoriO.Total + 1; end else begin writeError('UInventori','Tidak bisa membuat ' + input); Error := true; end; end else begin writeError('UInventori','Tidak ada bahan olahan dengan nama ' + input); Error := true; end; end; procedure kuranginBahan(input : string; var Error : boolean); {KAMUS LOKAL} var IndeksBahan : integer; {Algoritma kuranginBahan} begin Error := false; {cari di inventori mentah} IndeksBahan := searchIndex(input, 'IM'); if (IndeksBahan <> -1) then begin {cek apa sudah habis} if (InventoriM.Jumlah[IndeksBahan] <> 0) then begin {kurangi} InventoriM.Jumlah[IndeksBahan] := InventoriM.Jumlah[IndeksBahan] - 1; InventoriM.Total := InventoriM.Total - 1; end else begin Error := true; end; end else begin {cari di inventori olahan jika di mentah tak ada} IndeksBahan := searchIndex(input, 'IO'); if (IndeksBahan <> -1) then begin {cek apa sudah habis} if (InventoriO.Jumlah[IndeksBahan] <> 0) then begin {kurangi} InventoriO.Jumlah[IndeksBahan] := InventoriO.Jumlah[IndeksBahan] - 1; InventoriO.Total := InventoriO.Total - 1; end else begin Error := true; end; end else begin Error := true; end; end; if (Error) then begin writeError('UInventori','Bahan ' + input + ' sudah habis atau tidak ada'); end; end; procedure sortArray(); {Kamus Lokal} var n1, n2 : integer; i : integer; tempM : BahanMentah; tempT : Tanggal; {temporary tanggal} tempJ : integer; {temporary jumlah} tempO : BahanOlahan; newn : integer; kondisi1: boolean; kondisi2: boolean; {Algoritma - sortArray} begin if(not(InventoriM.Sorted))then begin {sorting bubble sort} n1:= InventoriM.Neff; repeat newn:=0; for i:= 2 to InventoriM.Neff do begin {sorting alfabet} kondisi1:=InventoriM.Isi[i-1].Nama > InventoriM.Isi[i].Nama; kondisi2:=isTanggalDuluan(InventoriM.TanggalBeli[i],InventoriM.TanggalBeli[i-1])and(InventoriM.Isi[i-1].Nama = InventoriM.Isi[i].Nama); if (kondisi1 or kondisi2) then begin tempT:=InventoriM.TanggalBeli[i-1]; tempJ:=InventoriM.Jumlah[i-1]; tempM :=InventoriM.Isi[i-1]; InventoriM.Isi[i-1] := InventoriM.Isi[i]; InventoriM.TanggalBeli[i-1] := InventoriM.TanggalBeli[i]; InventoriM.Jumlah[i-1] := InventoriM.Jumlah[i]; InventoriM.Isi[i] := tempM; InventoriM.TanggalBeli[i]:=tempT; InventoriM.Jumlah[i]:=tempJ; newn := i; end; end; n1 := newn; until (n1 = 0); {hingga tersort} end; if(not(InventoriO.Sorted))then begin {sorting bubble sort} n2:= InventoriO.Neff; repeat newn:=0; for i:=2 to InventoriO.Neff do begin {sorting alfabet dan tanggal} kondisi1:=InventoriO.Isi[i-1].Nama > InventoriO.Isi[i].Nama; kondisi2:=isTanggalDuluan(InventoriO.TanggalBuat[i],InventoriO.TanggalBuat[i-1])and(InventoriO.Isi[i-1].Nama = InventoriO.Isi[i].Nama); if (kondisi1 or kondisi2) then begin tempT:=InventoriO.TanggalBuat[i-1]; tempJ:=InventoriO.Jumlah[i-1]; tempO:=InventoriO.Isi[i-1]; InventoriO.Isi[i-1]:= InventoriO.Isi[i]; InventoriO.TanggalBuat[i-1] := InventoriO.TanggalBuat[i]; InventoriO.Jumlah[i-1] := InventoriO.Jumlah[i]; InventoriO.Isi[i]:= tempO; InventoriO.TanggalBuat[i]:=tempT; InventoriO.Jumlah[i]:=tempJ; newn := i; end; end; n2:= newn; until (n2 = 0); {hingga tersort} end; InventoriM.Sorted := true; InventoriO.Sorted := true; end; function searchIndex(input : string; kode : string): integer; {KAMUS LOKAL} var i:integer; Indeks: array[1..NMAX] of integer; Neff : integer; IndeksDuluan:integer; {Algoritma - searchIndex} begin Neff := 0; Indeks[1] := -1; if (kode = 'IM') then begin for i := 1 to InventoriM.Neff do begin {cari bahan yang masih ada stok} if ((input = InventoriM.Isi[i].Nama)and(InventoriM.Jumlah[i]<>0)) then begin Neff:=Neff+1; Indeks[Neff] := i; end; end; {Jika >1 cari yang tanggalnya paling duluan} if Neff > 1 then begin IndeksDuluan:=1; for i:=1 to Neff do begin if(isTanggalDuluan(InventoriM.TanggalBeli[Indeks[i]],InventoriM.TanggalBeli[Indeks[IndeksDuluan]]))then begin IndeksDuluan:=i; end; end; Indeks[1]:=Indeks[IndeksDuluan]; end; end else if (kode = 'IO') then begin for i := 1 to InventoriO.Neff do begin {cari bahan yang masih ada stok} if ((input = InventoriO.Isi[i].Nama)and (InventoriO.Jumlah[i]<>0)) then begin Neff:=Neff+1; Indeks[Neff] := i; end; end; {Jika >1 cari yang tanggalnya paling duluan} if Neff > 1 then begin IndeksDuluan:=1; for i:=1 to Neff do begin if(isTanggalDuluan(InventoriO.TanggalBuat[Indeks[i]],InventoriO.TanggalBuat[Indeks[IndeksDuluan]]))then begin IndeksDuluan:=i; end; end; Indeks[1]:=Indeks[IndeksDuluan]; end; end else if (kode = 'DM') then begin for i := 1 to DaftarBahanM.Neff do begin if (input = DaftarBahanM.Isi[i].Nama) then begin Indeks[1] := i; break; end; end; end else if (kode = 'DO') then begin for i := 1 to DaftarBahanO.Neff do begin if (input = DaftarBahanO.Isi[i].Nama) then begin Indeks[1] := i; break; end; end; end; searchIndex := Indeks[1]; end; end.
unit Ils.Utils.Svc; interface uses SysUtils, StrUtils, DateUtils, SvcMgr, WinSvc, SyncObjs, IniFiles, JsonDataObjects, CINIFilesData, Ils.Logger, Ils.Utils.SaaS; type TKafkaProcessFunc = function( const AJSON: TJsonObject; const AMes: string; const AOffset: Int64; out OMessageDT: TDateTime ): Boolean of object; TCheckRepairDBFunc = function(): Boolean of object; function GetParam(AParam: string): string; function GetConfigSuffix(AParam: string = 'config'): string; procedure SvcBeforeInstallUninstall(const AService: TService; const AServiceName: string; const AServiceDisplayName: string; const AParamName: string = 'config'); procedure SvcAfterInstall(const AServiceName: string; const AParamName: string = 'config'); function GetInstanceName: string; function KafkaMPWrapper( const AMessage: AnsiString; const AOffset: Int64; const ATopic: AnsiString; const AProcessFunc: TKafkaProcessFunc; const ACheckDBFunc: TCheckRepairDBFunc; const ASyncDB: TCriticalSection; const ASyncINI: TCriticalSection; const ARAR: TRedisActivityReporter; var RPrevOffset: Int64; var RPrevDT: TDateTime ): Boolean; implementation function GetParam(AParam: string): string; var i: Integer; s: string; p1: Integer; p2: Integer; begin Result :=''; for i := 1 to ParamCount do begin s := ParamStr(i); p1 := Pos(LowerCase(AParam), LowerCase(s)); if p1 = 2 then begin p2 := Pos('=', s); if p2 > p1 then Result := Copy(s, p2 + 1, Length(s) - p2); Break; end; end; end; function GetConfigSuffix(AParam: string = 'config'): string; var ConfigParam: string; begin ConfigParam := GetParam(AParam); Result := IfThen(ConfigParam <> '', '_' + ConfigParam, ''); end; procedure SvcBeforeInstallUninstall(const AService: TService; const AServiceName: string; const AServiceDisplayName: string; const AParamName: string = 'config'); var ConfigParam: string; begin ConfigParam := GetParam(AParamName); if ( ConfigParam <> '' ) then begin AService.Name := AServiceName + '_' + ConfigParam; AService.DisplayName := AServiceDisplayName + ' ' + ConfigParam; end end; procedure SvcAfterInstall(const AServiceName: string; const AParamName: string = 'config'); var ConfigParam: string; SCManager: SC_HANDLE; OurService: SC_HANDLE; begin ConfigParam := GetParam(AParamName); if ( ConfigParam <> '' ) then begin SCManager := OpenSCManager( nil, nil, SC_MANAGER_ALL_ACCESS ); if ( SCManager <> 0 ) then begin OurService := OpenService( SCManager, PChar( AServiceName + '_' + ConfigParam ), SERVICE_ALL_ACCESS ); if ( OurService <> 0 ) then begin if not ChangeServiceConfig( OurService, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, PChar( ParamStr( 0 ) + ' /' + AParamName + '=' + ConfigParam ), nil, nil, nil, nil, nil, nil ) then raise Exception.Create( 'Не удалось изменение статуса службы' ); end else raise Exception.Create( 'Не удалось подключение к службе' ); end else raise Exception.Create( 'Не удалось подключение к менеджеру служб' ); end; end; function GetInstanceName: string; begin Result := IfThen(GetParam('config') = '', 'saas', GetParam('config')); end; function KafkaMPWrapper( const AMessage: AnsiString; const AOffset: Int64; const ATopic: AnsiString; const AProcessFunc: TKafkaProcessFunc; const ACheckDBFunc: TCheckRepairDBFunc; const ASyncDB: TCriticalSection; const ASyncINI: TCriticalSection; const ARAR: TRedisActivityReporter; var RPrevOffset: Int64; var RPrevDT: TDateTime ): Boolean; var MessageU, TopicU: string; NewDT: TDateTime; MessageDT: TDateTime; Speed: Double; JSONObj: TJsonObject; INIFile: TIniFile; //------------------------------------------------------------------------------ begin // инициализация MessageU := string(AMessage); TopicU := string(ATopic); Assert(Assigned(AProcessFunc), TopicU + ': параметр AProcessFunc должен присутствовать'); Assert(Assigned(ACheckDBFunc), TopicU + ': параметр ACheckDBFunc должен присутствовать'); Result := True; if (MessageU = '') then Exit; try // загрузка json JSONObj := nil; // затыкаем компилятор try JSONObj := TJsonObject.Parse(MessageU) as TJsonObject; except Exception.RaiseOuterException(Exception.Create(TopicU + ': ошибка разбора JSON сообщения:'#13#10 + MessageU)); end; // обработка try if Assigned(ASyncDB) then ASyncDB.Acquire(); try // if not ACheckDBFunc() then // Exit(False); // при потере связи с БД нужен перезапуск обработки try Result := AProcessFunc(JSONObj, MessageU, AOffset, MessageDT); except Result := False; Exception.RaiseOuterException(Exception.Create(TopicU + ': ошибка обработки JSON сообщения:'#13#10 + MessageU)); end; finally if Assigned(ASyncDB) then ASyncDB.Release(); end; finally JSONObj.Free(); end; except on Ex: Exception do begin ExceptionToLog(Ex, TopicU + '//' + IntToStr(AOffset)); end; end; // если сообщение обработано - сохраняем смещение сообщения if Result then try NewDT := Now(); if (SecondsBetween(NewDT, RPrevDT) >= 5) then begin if Assigned(ASyncINI) then ASyncINI.Acquire(); try INIFile := TIniFile.Create(ChangeFileExt(ParamStr(0), GetConfigSuffix() + CKafkaIdxDefExtDotted)); try Speed := (AOffset - RPrevOffset) / (NewDT - RPrevDT) / SecsPerDay; INIFile.WriteString(CIniKafkaOffsetSection, CIniKafkaOffset + '_' + TopicU, IntToStr(AOffset)); INIFile.WriteInteger(CIniStatSection, CIniStatPPS + '_' + TopicU, Round(Speed)); ToLog('Offset = ' + IntToStr(AOffset) + ', PPS = ' + FloatToStr(Speed) + ', time = ' + FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz', MessageDT)); if Assigned(ARAR) then ARAR.SaveLastActivity((AOffset - RPrevOffset), OneSecond); RPrevDT := NewDT; RPrevOffset := AOffset; finally INIFile.Free(); end; finally if Assigned(ASyncINI) then ASyncINI.Release(); end; end; except ToLog(TopicU + ': ошибка сохранения позиции ' + IntToStr(AOffset) + ' в ini-файл'); Result := False; // при ошибке сохранения позиции нужен перезапуск обработки end; end; end.
unit Main; {******************************************************************************* * * * Название модуля : * * * * uMain * * * * Назначение модуля : * * * * Формирование обновлений. Переименование скриптов, отображение результатов. * * * * Copyright © Год 2005, Автор: Найдёнов Е.А * * Copyright © Год 2015, Автор: Акмаев Т.Р. * * *******************************************************************************} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxGraphics, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, dxBar, dxBarExtItems, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, dxStatusBar, ImgList, cxContainer, RxMemDS, cxShellDlgs, cxShellBrowserDialog, cxTextEdit, cxMaskEdit, cxButtonEdit, Menus, cxCheckBox, StdCtrls, cxSplitter, cxMRUEdit, cxDropDownEdit, ExtCtrls, cxLookAndFeelPainters, cxButtons, FIBDatabase, pFIBDatabase, cxLabel, cxRadioGroup, cxCalc, ShellAPI, uLib, uTypes, BrowseFolderDlg; type TfmMain = class(TForm) Splitter : TcxSplitter; rgrFileType : TcxRadioGroup; pnlDBParams : TPanel; lblDescription : TcxLabel; btnTestConnect : TcxButton; grMain : TcxGrid; lvlMain : TcxGridLevel; tvwMain : TcxGridDBTableView; brmMain : TdxBarManager; bmnuMain : TdxBarPopupMenu; btnCopy : TdxBarLargeButton; btnExit : TdxBarLargeButton; btnBuild : TdxBarLargeButton; btnFilter : TdxBarLargeButton; btnSearch : TdxBarLargeButton; btnInvert : TdxBarLargeButton; btnRename : TdxBarLargeButton; btnUnRename : TdxBarLargeButton; btnSelectAll : TdxBarLargeButton; btnUnselectAll : TdxBarLargeButton; mnuBuild : TdxBarButton; mnuOnlyTest : TdxBarButton; mnuMergeScripts : TdxBarButton; btnCalcMaxUpdateNum : TdxBarButton; escMain : TcxEditStyleController; srpMain : TcxStyleRepository; cxsFooter : TcxStyle; cxsHeader : TcxStyle; cxsContent : TcxStyle; cxHotTrack : TcxStyle; cxsInactive : TcxStyle; cxsIndicator : TcxStyle; cxsSelection : TcxStyle; cxBackground : TcxStyle; cxsGroupByBox : TcxStyle; cxsContentOdd : TcxStyle; cxsContentEvent : TcxStyle; cxsColumnHeader : TcxStyle; cxsColumnHeaderClassic : TcxStyle; imlToolBar : TImageList; imlPopupMenu : TImageList; bdlgMain : TcxShellBrowserDialog; dsrMain : TDataSource; dstMain : TRxMemoryData; cbxProjects : TdxBarCombo; edtDateBeg : TdxBarDateCombo; edtDateEnd : TdxBarDateCombo; edtComment : TdxBarEdit; edtDateCreate : TdxBarDateCombo; edtScriptPath : TcxButtonEdit; edtUpdNumberMajor : TdxBarSpinEdit; edtFtrUpdNumMajor : TdxBarSpinEdit; edtUpdNumberMinor : TdxBarSpinEdit; edtFtrUpdNumMinor : TdxBarSpinEdit; stbMain : TdxStatusBar; stbMainContainer0 : TdxStatusBarContainerControl; pmnuExit : TMenuItem; pmnuCopy : TMenuItem; pmnuMain : TPopupMenu; pmnuBuild : TMenuItem; smnuBuild : TMenuItem; pmnuInvert : TMenuItem; pmnuRename : TMenuItem; pmnuFilter : TMenuItem; pmnuSearch : TMenuItem; pmnuUnRename : TMenuItem; smnuOnlyTest : TMenuItem; pmnuSelectAll : TMenuItem; pmnuUnSelectAll : TMenuItem; smnuMergeScripts : TMenuItem; cmnIsActive : TcxGridDBColumn; cmnFileSize : TcxGridDBColumn; cmnDateChange : TcxGridDBColumn; cmnScriptNames : TcxGridDBColumn; fnIS_ACTIVE : TBooleanField; fnFILE_SIZE : TFloatField; fnDATE_CHANGE : TDateTimeField; fnSCRIPT_NAME : TStringField; cciDateBeg : TdxBarControlContainerItem; cciDateEnd : TdxBarControlContainerItem; dbTestConnect : TpFIBDatabase; lblPeriod : TdxBarStatic; dlgDBPath : TOpenDialog; cbxDateBeg : TcxCheckBox; cbxDateEnd : TcxCheckBox; stbDBPath : TdxStatusBar; stbHotKeys : TdxStatusBar; stbDBParams : TdxStatusBar; stbDescription : TdxStatusBar; stbDBContainer1 : TdxStatusBarContainerControl; stbDBContainer2 : TdxStatusBarContainerControl; stbDBContainer3 : TdxStatusBarContainerControl; stbMainContainer2 : TdxStatusBarContainerControl; stbDBPathContainer2 : TdxStatusBarContainerControl; dxStatusBar1Container0 : TdxStatusBarContainerControl; edtLogin : TcxTextEdit; edtDBPath : TcxButtonEdit; edtPassword : TcxTextEdit; edtServerName : TcxMRUEdit; stbDBParamsContainer3: TdxStatusBarContainerControl; edtActiveProjects: TcxTextEdit; BrowseFolderDlg1: TBrowseFolderDlg; procedure FormCreate (Sender: TObject); procedure FormActivate (Sender: TObject); procedure FormShortCut (var Msg: TWMKey; var Handled: Boolean); procedure btnCopyClick (Sender: TObject); procedure btnExitClick (Sender: TObject); procedure btnBuildClick (Sender: TObject); procedure btnRenameClick (Sender: TObject); procedure btnFilterClick (Sender: TObject); procedure btnInvertClick (Sender: TObject); procedure btnSearchClick (Sender: TObject); procedure btnUnRenameClick (Sender: TObject); procedure btnSelectAllClick (Sender: TObject); procedure btnUnselectAllClick (Sender: TObject); procedure btnTestConnectClick (Sender: TObject); procedure btnCalcMaxUpdateNumClick (Sender: TObject); procedure tvwMainKeyDown (Sender: TObject; var Key: Word; Shift: TShiftState); procedure tvwMainCellClick (Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean); procedure cbxDateBegClick (Sender: TObject); procedure cbxDateEndClick (Sender: TObject); procedure edtUpdNumberMajorButtonClick (Sender: TdxBarSpinEdit; Button: TdxBarSpinEditButton); procedure edtFtrUpdNumMajorButtonClick (Sender: TdxBarSpinEdit; Button: TdxBarSpinEditButton); procedure edtScriptPathPropertiesButtonClick (Sender: TObject; AButtonIndex: Integer); procedure edtServerNamePropertiesChange (Sender: TObject); procedure tvwMainCustomDrawCell (Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean); procedure tvwMainDataControllerSummaryFooterSummaryItemsSummary (ASender: TcxDataSummaryItems; Arguments: TcxSummaryEventArguments; var OutArguments: TcxSummaryEventOutArguments); procedure edtLoginKeyDown (Sender: TObject; var Key: Word; Shift: TShiftState); procedure edtDBPathKeyDown (Sender: TObject; var Key: Word; Shift: TShiftState); procedure edtPasswordKeyDown (Sender: TObject; var Key: Word; Shift: TShiftState); procedure edtServerNameKeyDown (Sender: TObject; var Key: Word; Shift: TShiftState); procedure SplitterAfterOpen (Sender: TObject); procedure SplitterAfterClose (Sender: TObject); procedure edtDBPathPropertiesButtonClick (Sender: TObject; AButtonIndex: Integer); procedure rgrFileTypeClick (Sender: TObject); procedure cbxProjectsChange (Sender: TObject); procedure mnuOnlyTestClick (Sender: TObject); procedure mnuMergeScriptsClick (Sender: TObject); procedure dstMainAfterOpen (DataSet: TDataSet); procedure dstMainAfterClose (DataSet: TDataSet); procedure grMainDblClick(Sender: TObject); private FAppMode : TEnm_AppMode; FInitialize : Boolean; FUsrFileType : TUsrFileType; FUpdFilePath : String; FSearchParams : TPtr_SearchParams; FUpdFileExist : Boolean; FIBEscriptPath : String; FSelectedRecCount : Integer; function GetAppMode : TEnm_AppMode; function GetInitialize : Boolean; function GetUsrFileType : TUsrFileType; function GetUpdFilePath : String; function GetSearchParams : TPtr_SearchParams; function GetUpdFileExist : Boolean; function GetIBEscriptPath : String; function GetSelectedRecCount : Integer; procedure SetAppMode ( aValue: TEnm_AppMode ); procedure SetUsrFileType ( aValue: TUsrFileType ); procedure SetUpdFilePath ( aValue: String ); procedure SetSearchParams ( aValue: TPtr_SearchParams ); procedure SetUpdFileExist ( aValue: Boolean ); procedure SetIBEscriptPath ( aValue: String ); procedure SetSelectedRecCount ( aValue: Integer ); public property AppMode : TEnm_AppMode read GetAppMode write SetAppMode; property Initialize : Boolean read GetInitialize; property UsrFileType : TUsrFileType read GetUsrFileType write SetUsrFileType; property UpdFilePath : String read GetUpdFilePath write SetUpdFilePath; property SearchParams : TPtr_SearchParams read GetSearchParams write SetSearchParams; property UpdFileExist : Boolean read GetUpdFileExist write SetUpdFileExist; property IBEscriptPath : String read GetIBEscriptPath write SetIBEscriptPath; property SelectedRecCount : Integer read GetSelectedRecCount write SetSelectedRecCount; end; var fmMain: TfmMain; implementation uses uUtils, uSearch, StrUtils, FileUtil; resourcestring //Сообщения, оповещающие пользователя о результатах проверки соединения sNotFound = 'не найден'; sConnectOK = 'Соединение успешно установлено!'; sConnectErr = 'Не удалось установить соединение...'#13'Проверьте параметры соединения '; sErrorTestProcess = 'Невозможно продолжить процесс тестирования, поскольку'#13'файл скрипта, подлежащий тестированю, не найден'; sErrorUpdate = 'Файл обновления ОТТЕСТИРОВАН С ОШИБКАМИ!'#13'Показать файл-отчёт ошибок?'; sSuccessUpdate = 'Файл обновления УСПЕШНО ОТТЕСТИРОВАН!'; sModulesInvalid = 'Файлы архивов модулей не найдены, либо'#13'критерии фильтрации указаны неверно'; sErrorUpdateTest = 'Невозможно выполнить тестирование файла обновления,'#13'поскольку '; sInvalidUserName = 'имя пользователя не указано'; sInvalidPassword = 'пароль не указан'; sInvalidServerName = 'имя сервера не указано'; sInvalidDataBasePath = 'файл базы данных не найден'; sInvalidIBEscriptPath = 'программа применения скриптов не найдена'; sServerTypeUnknown = 'Сервер не определён'#13'Укажите тип сервера'; sServerNameUnknown = 'Сервер не определён'#13'Укажите имя сервера'; sLoginNotFound = 'Имя пользователя не определено'#13'Укажите имя пользователя'; sDBFileNotFound = 'Файл базы данных не найден'#13'Проверьте правильность указанного пути'; sPasswordNotFound = 'Пароль не определен'#13'Укажите пароль'; sSearchStrNotFound = 'Искомый текст '; sCopyAbort = 'Процесс копирования прерван!'; sFatalError = 'Критическая ошибка!'#13'Обратитесь к разработчикам'; sPathInvalid = 'Указанный путь не существует!'; //Delimiter sSearchInvalid = 'выполнить поиск, поскольку'#13#10; sScr_SearchInvalid = 'файлы скриптов отсутствуют'; sMod_SearchInvalid = 'файлы архивов модулей отсутствуют'; //Delimiter sScr_CopyInvalid = 'скопировать файлы скриптов,'; sMod_CopyInvalid = 'скопировать файлы архивов модулей,'; //Delimiter sScr_CanNotRename = 'Файлы скриптов, подлежащие переименованию, отсутствуют!'; sMod_CanNotRename = 'Файлы архивов модулей, подлежащие переименованию, отсутствуют!'; sBuildInvalid = 'собрать файл обновления,'; //Delimiter sScr_FilterInvalid = 'сформировать множество скриптов,'; sMod_FilterInvalid = 'сформировать множество архивов модулей,'; //Delimiter sScr_RenameInvalid = 'переименовать файлы скриптов,'; sMod_RenameInvalid = 'переименовать файлы архивов модулей,'; sInvertInvalid = 'инвертировать выделение,'; //Delimiter sScr_ScrLoadFailed = 'Не удалось загрузить скрипты'#13'Проверьте путь к скриптам'; sMod_ScrLoadFailed = 'Не удалось загрузить файлы архивов модулей'#13'Проверьте путь к архивам модулей'; //Delimiter sScr_CanNotUnRename = 'Файлы скриптов, подлежащие разименованию, отсутствуют!'; sMod_CanNotUnRename = 'Файлы архивов модулей, подлежащие разименованию, отсутствуют!'; sScrSetIsEmpty1 = 'Невозможно '; //Delimiter sScr_ScrSetIsEmpty2 = #13'поскольку отсутствуют выбранные скрипты'; sMod_ScrSetIsEmpty2 = #13'поскольку отсутствуют выбранные архивы модулей'; //Delimiter sScr_ScrSetIsEmpty3 = #13'поскольку файлы скриптов отсутствуют'; sMod_ScrSetIsEmpty3 = #13'поскольку файлы архивов модулей отсутствуют'; //Delimiter sScr_ScrDirNotFound = 'Путь к скриптам не найден'#13'Укажите путь к скриптам'; sMod_ScrDirNotFound = 'Путь к архивам модулей не найден'#13'Укажите путь к архивам модулей'; //Delimiter sScr_UnRenameInvalid = 'разименовать файлы скриптов,'; sMod_UnRenameInvalid = 'разименовать файлы архивов модулей,'; sCopyFilesError1 = 'Копирование файлов было выполнено с ошибками!'#13; sCopyFilesError2 = ' файл ((a)ов) из '; sCopyFilesError3 = ' отобранных удалось скопировать'; //Delimiter sScr_ScrFilterInvalid = 'Для заданных критериев фильтрации cкрипты не найдены'; sMod_ScrFilterInvalid = 'Для заданных критериев фильтрации архивы модулей не найдены'; sSelectAllInvalid = 'выделить все,'; sRenameFilesError1 = 'Переименование файлов было выполнено с ошибками!'#13; sRenameFilesError2 = ' файл ((a)ов) из '; sRenameFilesError3 = ' отобранных удалось переименовать'; sFileAlreadyExists1 = 'Файл с именем '; sFileAlreadyExists2 = #13'Уже существует. Перезаписать? '; sUpdateCannotCreate = 'Внимание! Невозможно продолжить формирование файла обновления, покольку в процессе'#13'его создания один из файлов скриптов был удалён(перемещен) или заблокирован для доступа'; sUnSelectAllInvalid = 'снять выделение для всех,'; sUnRenameFilesError1 = 'Разименование файлов было выполнено с ошибками!'#13; sUnRenameFilesError2 = ' файл ((a)ов) из '; sUnRenameFilesError3 = ' отобранных удалось разименовать'; sCopyFilesSuccessful = ' Файл ((a)ов) успешно скопировано!'; sFileCannotBeDeleted = #13' удалить не удалось. Возможно файл не существует или временно недоступен'; sUpdateNumberInvalid = #13'поскольку порядковый номер обновления(или его часть) отсутствует'; sScr_DescriptionPath = 'Путь к скриптам :'; sMod_DescriptionPath = 'Путь к модулям :'; sRenameFilesSuccessful = ' Файл ((a)ов) успешно переименовано!'; sUpdateCreateSuccessful = 'Файл обновления успешно собран!'; sUnRenameFilesSuccessful = ' Файл ((a)ов) успешно разименовано!'; sUpdateDateCreateInvalid = #13'поскольку дата создания обновления отсутствует'; const cCopyInvalid : array[0..1] of string = ( sScr_CopyInvalid, sMod_CopyInvalid ); cCanNotRename : array[0..1] of string = ( sScr_CanNotRename, sMod_CanNotRename ); cSearchInvalid : array[0..1] of string = ( sScr_SearchInvalid, sMod_SearchInvalid ); cFilterInvalid : array[0..1] of string = ( sScr_FilterInvalid, sMod_FilterInvalid ); cRenameInvalid : array[0..1] of string = ( sScr_RenameInvalid, sMod_RenameInvalid ); cScrLoadFailed : array[0..1] of string = ( sScr_ScrLoadFailed, sMod_ScrLoadFailed ); cCanNotUnRename : array[0..1] of string = ( sScr_CanNotUnRename, sMod_CanNotUnRename ); cScrSetIsEmpty2 : array[0..1] of string = ( sScr_ScrSetIsEmpty2, sMod_ScrSetIsEmpty2 ); cScrSetIsEmpty3 : array[0..1] of string = ( sScr_ScrSetIsEmpty3, sMod_ScrSetIsEmpty3 ); cScrDirNotFound : array[0..1] of string = ( sScr_ScrDirNotFound, sScr_ScrDirNotFound ); cUnRenameInvalid : array[0..1] of string = ( sScr_UnRenameInvalid, sMod_UnRenameInvalid ); cDescriptionPath : array[0..1] of string = ( sScr_DescriptionPath, sMod_DescriptionPath ); cScrFilterInvalid : array[0..1] of string = ( sScr_ScrFilterInvalid, sMod_ScrFilterInvalid ); {$R *.dfm} function TfmMain.GetAppMode: TEnm_AppMode; begin Result := FAppMode; end; function TfmMain.GetIBEscriptPath: String; begin Result := FIBEscriptPath; end; function TfmMain.GetInitialize: Boolean; begin Result := FInitialize; end; function TfmMain.GetUsrFileType: TUsrFileType; begin Result := FUsrFileType; end; function TfmMain.GetUpdFilePath: String; begin Result := FUpdFilePath; end; function TfmMain.GetSearchParams: TPtr_SearchParams; begin Result := FSearchParams; end; function TfmMain.GetUpdFileExist: Boolean; begin Result := FUpdFileExist; end; function TfmMain.GetSelectedRecCount: Integer; begin Result := FSelectedRecCount; end; procedure TfmMain.SetAppMode(aValue: TEnm_AppMode); begin FAppMode := aValue; end; procedure TfmMain.SetIBEscriptPath(aValue: String); begin FIBEscriptPath := aValue; end; procedure TfmMain.SetUsrFileType(aValue: TUsrFileType); begin FUsrFileType := aValue; end; procedure TfmMain.SetUpdFilePath(aValue: String); begin FUpdFilePath := aValue; end; procedure TfmMain.SetSearchParams(aValue: TPtr_SearchParams); begin FSearchParams := aValue; end; procedure TfmMain.SetUpdFileExist(aValue: Boolean); begin FUpdFileExist := aValue; end; procedure TfmMain.SetSelectedRecCount(aValue: Integer); begin FSelectedRecCount := aValue; end; //Выходим из приложения procedure TfmMain.btnExitClick(Sender: TObject); begin Close; end; //Инициализация переменных и значений обязательных полей ввода procedure TfmMain.FormCreate(Sender: TObject); var i, n : Integer; IniFileName : TFileName; DefIniParams : TStringList; begin try try FAppMode := amView; FInitialize := True; FSelectedRecCount := 0; edtDateBeg.Date := StrToDate( sDEF_SCR_DATE_BEG ); tvwMain.DataController.Summary.FooterSummaryValues[cmnIsActive.Index] := SelectedRecCount; tvwMain.DataController.Summary.FooterSummaryValues[cmnFileSize.Index] := cZERO; //Считываем умалчиваемые настройки из конфигурационного файла try IniFileName := ExtractFilePath( Application.ExeName ) + sINI_FILE_NAME; DefIniParams := TStringList.Create; ReadIniFile( IniFileName, cDefIniParams, DefIniParams ); edtLogin.Text := DefIniParams.Values[sKN_USER_NAME ]; edtDBPath.Text := DefIniParams.Values[sKN_DB_PATH ]; edtPassword.Text := DefIniParams.Values[sKN_PASSWORD ]; edtScriptPath.Text := DefIniParams.Values[sKN_SCR_PATH ]; edtServerName.Text := DefIniParams.Values[sKN_SERVER_NAME]; edtServerName.AddItem( DefIniParams.Values[sKN_SERVER_NAME] ); SetIBEscriptPath( DefIniParams.Values[sKN_IBESCRIPT_PATH] ); edtActiveProjects.Text := DefIniParams.Values[sKN_ACTIVE_PROJECTS]; finally if DefIniParams <> nil then FreeAndNil( DefIniParams ); end; //Заполняем выпадающий список названий активных проектов n := High( cProjectParams ); try cbxProjects.Items.BeginUpdate; for i := Low( cProjectParams ) to n do begin if pos(cProjectParams[i].KeyExpr,edtActiveProjects.Text)<>0 then cbxProjects.Items.Add( '('+cProjectParams[i].KeyExpr+')'+cProjectParams[i].Name ); end; cbxProjects.ItemIndex := 0; finally cbxProjects.Items.EndUpdate; end; except //Протоколируем ИС LogException( ExtractFilePath( Application.ExeName ) + sLOG_FILE_NAME ); Raise; end; except on E: Exception do MessageBox( Handle, PChar( sErrorTextExt + E.Message ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ) end; end; //Пытаемся загрузить скрипты для умалчиваемого пути procedure TfmMain.FormActivate(Sender: TObject); var Path : String; KeyExpr : String; LoadResult : TLoadScrResult; ScriptNames : TUsrStringList; FilterParams : TFilterParams; MaxUpdNumber : TUpdateNumInfo; begin try try if Initialize then begin //Проверяем корректность умалчиваемого пути if not DirectoryExists( edtScriptPath.Text ) then begin MessageBox( Handle, PChar( cScrDirNotFound[Ord( UsrFileType )] ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING ); edtScriptPath.Properties.OnButtonClick( nil, -1 ); end; //Формируем путь к скриптам с учётом завершающего слеша Path := Trim( edtScriptPath.Text ); SetDirEndDelimiter( Path ); FilterParams.ScriptPath := Path + sSCRIPTS_MASK; //Получаем составной номер обновления FilterParams.UpdateNumMajor := edtFtrUpdNumMajor.IntValue; FilterParams.UpdateNumMinor := edtFtrUpdNumMinor.IntValue; //Получаем ключевое выражение, соответствующее выбранному проекту KeyExpr := GetKeyExpr( cbxProjects.Text ); if KeyExpr = sEMPTY_STR then begin MessageBox( Handle, PChar( sFatalError ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); Exit; end else begin FilterParams.KeyExpr := KeyExpr; end; //Пытаемся загрузить скрипты try ScriptNames := TUsrStringList.Create; ScriptNames.Sorted := cDEF_CAN_SORT; ScriptNames.CaseSensitive := cDEF_CASE_SENSITIVE; with MaxUpdNumber do begin UpdateNumMajor := cZERO; UpdateNumMinor := cDEF_UPDATE_NUMBER; end; LoadResult := LoadScripts( FilterParams, ScriptNames, MaxUpdNumber ); //Анализируем результат загрузки скриптов case LoadResult of lrLoadSuccess : begin edtUpdNumberMajor.Value := MaxUpdNumber.UpdateNumMajor; edtUpdNumberMinor.Value := MaxUpdNumber.UpdateNumMinor + 1; try tvwMain.DataController.BeginUpdate; FillDataset( dstMain, ScriptNames, FSelectedRecCount ); finally tvwMain.DataController.EndUpdate; end; tvwMain.DataController.GotoFirst; end; lrScrNotFound : begin MessageBox( Handle, PChar( cScrLoadFailed[Ord( UsrFileType )] ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING ); end; lrFilterInvalid : begin MessageBox( Handle, PChar( cScrFilterInvalid[Ord( UsrFileType )] ), PChar( sMsgCaptionInf ), MB_OK or MB_ICONINFORMATION ); end; end; finally if ScriptNames <> nil then FreeAndNil( ScriptNames ); end; end; FInitialize := False; except FInitialize := False; LogException( ExtractFilePath( Application.ExeName ) + sLOG_FILE_NAME ); Raise; end; except on E: Exception do begin MessageBox( Handle, PChar( sErrorTextExt + e.Message ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); end; end; end; //Собираем файл обновления, склеивая его из множества выбранных файлов скриптов procedure TfmMain.mnuMergeScriptsClick(Sender: TObject); var i, n : Integer; Mode : Word; Buffer : PChar; ErrMsg : String; UpdPath : String; Comment : String; SpaceStr : String; DlgResult : Integer; UpdScript : TFileStream; ScriptPath : String; UpdComment : String; StarsCount : Integer; CurrScript : TFileStream; UpdFileName : String; FmtSettings : TFormatSettings; SelectedRec : String; CurrFileName : String; CommProjName : String; UpdateNumMajor : String; UpdateNumMinor : String; UpdDateCreateStr : String; CommScriptsCount : String; CommUpdDateCreate : String; IsUpdCreateSuccess : Boolean; begin try try SetUpdFileExist( False ); //Проверяем наличие отобранных пользователем скриптов if not dstMain.IsEmpty AND ( SelectedRecCount > 0 ) then begin UpdateNumMajor := Trim( edtUpdNumberMajor.Text ); UpdateNumMinor := Trim( edtUpdNumberMinor.Text ); //Проверяем главную часть порядкового номера обновления if UpdateNumMajor = sEMPTY_STR then begin MessageBox( Handle, PChar( sScrSetIsEmpty1 + sBuildInvalid + sUpdateNumberInvalid ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); edtUpdNumberMajor.SetFocus; Exit; end; //Проверяем дополнительную часть порядкового номера обновления if UpdateNumMinor = sEMPTY_STR then begin MessageBox( Handle, PChar( sScrSetIsEmpty1 + sBuildInvalid + sUpdateNumberInvalid ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); edtUpdNumberMinor.SetFocus; Exit; end; //Проверяем дату создания обновления if Trim( edtDateCreate.Text ) = sEMPTY_STR then begin MessageBox( Handle, PChar( sScrSetIsEmpty1 + sBuildInvalid + sUpdateDateCreateInvalid ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); edtDateCreate.SetFocus; Exit; end; ScriptPath := Trim( edtScriptPath.Text ); //Проверяем путь к хранилищу скриптов if not DirectoryExists( ScriptPath ) then begin MessageBox( Handle, PChar( cScrDirNotFound[Ord( UsrFileType )] ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING ); edtScriptPath.SetFocus; Exit; end; SetDirEndDelimiter( ScriptPath ); //Формируем собственно имя файла обновления FmtSettings.DateSeparator := cDATE_SEPARATOR; FmtSettings.ShortDateFormat := sFORMAT_DATE_TO_STR; UpdDateCreateStr := DateToStr( edtDateCreate.Date, FmtSettings ); //Получаем главную часть порядкового номера обновления if Length( UpdateNumMajor ) < cUPDATE_MAJ_RESERVED_CHAR_COUNT then begin UpdateNumMajor := DupeString( sZERO, cUPDATE_MAJ_RESERVED_CHAR_COUNT - Length( UpdateNumMajor ) ) + UpdateNumMajor; end; //Получаем дополнительную часть порядкового номера обновления if Length( UpdateNumMinor ) < cUPDATE_MIN_RESERVED_CHAR_COUNT then begin UpdateNumMinor := DupeString( sZERO, cUPDATE_MIN_RESERVED_CHAR_COUNT - Length( UpdateNumMinor ) ) + UpdateNumMinor; end; edtComment.Text := Trim( edtComment.Text ); if edtComment.Text <> sEMPTY_STR then edtComment.Text := sSPACE + edtComment.Text; UpdFileName := UpdDateCreateStr + sUPDATE_NUMBER + UpdateNumMajor + sMINUS + UpdateNumMinor + edtComment.Text + sSCRIPT_FILE_EXT; //Получаем путь для файла обновления if bdlgMain.Execute then begin UpdPath := bdlgMain.Path; bdlgMain.Path := ''; //Проверяем корректность указанного пользователем пути if DirectoryExists( UpdPath ) then begin SetDirEndDelimiter( UpdPath ); UpdFileName := UpdPath + UpdFileName; end else begin MessageBox( Handle, PChar( sPathInvalid ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); Exit; end; end else begin Exit; end; DlgResult := cDEF_DLG_RESULT; //Получаем режим формирования обновления if FileExists( UpdFileName ) then begin DlgResult := MessageBox( Handle, PChar( sFileAlreadyExists1 + UpdFileName + sFileAlreadyExists2 ), PChar( sMsgCaptionQst ), MB_YESNOCANCEL or MB_ICONQUESTION ); end; //Получаем режим работы с файлом case DlgResult of ID_YES : begin //Удаляем существующий файл обновления if not DeleteFile( UpdFileName ) then begin MessageBox( Handle, PChar( sFileAlreadyExists1 + UpdFileName + sFileCannotBeDeleted ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); Exit; end; Mode := fmCreate; end; ID_NO : begin Mode := fmOpenWrite; end; ID_CANCEL : begin Exit; end; cDEF_DLG_RESULT : begin Mode := fmCreate; end; end; //Формируем начальный комментарий для файла обновления SpaceStr := sSPACE; StarsCount := -1; StarsCount := Length( Trim( cbxProjects.Text ) ); if StarsCount < Length( Trim( edtDateCreate.Text ) ) then begin StarsCount := Length( Trim( edtDateCreate.Text ) ); end; //Выравниваем по правому краю с помощью пробелов строки начального комментария CommProjName := Trim( cbxProjects.Text ); SpaceStr := DupeString( sSPACE, StarsCount - Length( CommProjName ) ); CommProjName := sCommProjectName + CommProjName + SpaceStr; CommScriptsCount := IntToStr( SelectedRecCount ); SpaceStr := DupeString( sSPACE, StarsCount - Length( CommScriptsCount ) ); CommScriptsCount := sCommScriptsCount + CommScriptsCount + SpaceStr; CommUpdDateCreate := Trim( edtDateCreate.Text ); SpaceStr := DupeString( sSPACE, StarsCount - Length( CommUpdDateCreate ) ); CommUpdDateCreate := sCommUpdDateCreate + CommUpdDateCreate + SpaceStr; //Получаем количесто окаймляющих комментарий звёздочек CommProjName := sBRAKET_COMMENT_OP + sCommentBevel + CommProjName + sCommentBevel + sBRAKET_COMMENT_CL; CommScriptsCount := sBRAKET_COMMENT_OP + sCommentBevel + CommScriptsCount + sCommentBevel + sBRAKET_COMMENT_CL; CommUpdDateCreate := sBRAKET_COMMENT_OP + sCommentBevel + CommUpdDateCreate + sCommentBevel + sBRAKET_COMMENT_CL; StarsCount := Length( CommProjName ) - 2*Length( sBRAKET_COMMENT_OP ); Comment := sSTAR; Comment := DupeString( Comment, StarsCount ); //Формируем полный блок начального комментария Comment := sBRAKET_COMMENT_OP + Comment + sBRAKET_COMMENT_CL; UpdComment := sCRLF + Comment + sCRLF + CommProjName + sCRLF + CommUpdDateCreate + sCRLF + CommScriptsCount + sCRLF + Comment + sCRLF + sCRLF; try IsUpdCreateSuccess := True; SelectedRec := dstMain.FieldByName(sSCRIPT_NAME_FN).AsString; n := dstMain.RecordCount - 1; dstMain.DisableControls; dstMain.Last; //Записываем в файл обновления блок начального комментария UpdScript := TFileStream.Create( UpdFileName, Mode or fmShareDenyWrite ); UpdScript.Seek( 0, soFromEnd ); Buffer := StrNew( PChar( UpdComment ) ); StrPCopy( Buffer, UpdComment ); UpdScript.WriteBuffer( Buffer^, StrLen( Buffer ) ); StrDispose( Buffer ); //Копируем и вставляем содержимое каждого из отобранных файлов скриптов в результирующий файл обновления for i := 0 to n do begin if dstMain.FieldByName(sIS_ACTIVE_FN).AsBoolean then begin CurrFileName := ScriptPath + dstMain.FieldByName(sSCRIPT_NAME_FN).AsString; //Проверяем: не был ли удалён выбранный файл в процессе формирования результирующего файла обновления if FileExists( CurrFileName ) then begin try //Добавляем комментарий, содержащий имя файла скрипта включаемого в обновление UpdComment := sCommentFile + ExtractFileName( CurrFileName ) + sSPACE; Comment := sBRAKET_COMMENT_OP + DupeString( sSTAR, Length( UpdComment ) ) + sBRAKET_COMMENT_CL; UpdComment := sCRLF + sCRLF + sCRLF + Comment + sCRLF + sBRAKET_COMMENT_OP + UpdComment + sBRAKET_COMMENT_CL + sCRLF + Comment + sCRLF + sCRLF + sCRLF; Buffer := StrNew( PChar( UpdComment ) ); StrPCopy( Buffer, UpdComment ); UpdScript.Seek( 0, soFromEnd ); UpdScript.WriteBuffer( Buffer^, StrLen( Buffer ) ); //Копируем содержимое текущего скрипта в результирующий файла обновления CurrScript := TFileStream.Create( CurrFileName, fmOpenRead and fmShareDenyWrite ); UpdScript.Seek( 0, soFromEnd ); UpdScript.CopyFrom( CurrScript, CurrScript.Size ); finally StrDispose( Buffer ); FreeAndNil( CurrScript ); end; end else begin MessageBox( Handle, PChar( sUpdateCannotCreate ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); IsUpdCreateSuccess := False; Exit; end; end; dstMain.Prior; end; finally dstMain.Locate( sSCRIPT_NAME_FN, SelectedRec, [] ); dstMain.EnableControls; FreeAndNil( UpdScript ); //Оповещаем пользователя о результатах формирования обновления if IsUpdCreateSuccess then begin SetUpdFilePath( UpdFileName ); SetUpdFileExist( True ); if ( TComponent( Sender ).Name = mnuMergeScripts.Name ) OR ( TComponent( Sender ).Name = smnuMergeScripts.Name ) then MessageBox( Handle, PChar( sUpdateCreateSuccessful ), PChar( sMsgCaptionInf ), MB_OK or MB_ICONINFORMATION ) end else begin DeleteFile( UpdFileName ); end; end; end else begin if dstMain.IsEmpty then ErrMsg := cScrSetIsEmpty3[Ord( UsrFileType )] else ErrMsg := cScrSetIsEmpty2[Ord( UsrFileType )]; ErrMsg := sScrSetIsEmpty1 + sBuildInvalid + ErrMsg; MessageBox( Handle, PChar( ErrMsg ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING ); end; except LogException( ExtractFilePath( Application.ExeName ) + sLOG_FILE_NAME ); Raise; end; except on E: Exception do begin MessageBox( Handle, PChar( sErrorTextExt + e.Message ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); end; end; end; //Собираем файл обновления и тестируем его procedure TfmMain.btnBuildClick(Sender: TObject); var DBPath : String; ErrMsg : String; UserMsg : String; ErrCode : Integer; UserName : String; Password : String; DlgResult : Integer; TmpStrList : TStringList; ErrFileName : String; IBEscriptName : String; begin try try //Получаем результирующий файл обновления mnuMergeScripts.OnClick(Sender); //Тестируем результирующий файл обновления if UpdFileExist then begin mnuOnlyTestClick( Sender ); end; except LogException( ExtractFilePath( Application.ExeName ) + sLOG_FILE_NAME ); Raise; end; except on E: Exception do begin MessageBox( Handle, PChar( sErrorTextExt + e.Message ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); end; end; end; //Переименовываем помеченные файлы скриптов procedure TfmMain.btnRenameClick(Sender: TObject); var i, n : Integer; ErrMsg : String; Scripts : TStringList; CanRename : Boolean; ScriptPath : String; SelectedRec : String; OldFileName : String; NewFileName : String; RenameParams : TRenameParams; RenameFileCount : Integer; IsRenameSuccess : Boolean; begin try try if not dstMain.IsEmpty AND ( SelectedRecCount > 0 ) then begin //Получаем путь к хранилищу файлов скриптов ScriptPath := Trim( edtScriptPath.Text ); if not DirectoryExists( ScriptPath ) then begin MessageBox( Handle, PChar( cScrDirNotFound[Ord( UsrFileType )] ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING ); edtScriptPath.SetFocus; Exit; end; SetDirEndDelimiter( ScriptPath ); //Получаем ключевое выражение, соответствующее выбранному проекту RenameParams.KeyExpr := GetKeyExpr( cbxProjects.Text ); if RenameParams.KeyExpr = sEMPTY_STR then begin MessageBox( Handle, PChar( sFatalError ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); Exit; end; //Проверяем главную часть порядкового номера обновления if Trim( edtUpdNumberMajor.Text ) = sEMPTY_STR then begin MessageBox( Handle, PChar( sScrSetIsEmpty1 + cRenameInvalid[Ord( UsrFileType )] + sUpdateNumberInvalid ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING ); edtUpdNumberMajor.SetFocus; Exit; end else begin RenameParams.UpdateNumMajor := edtUpdNumberMajor.IntValue; end; //Проверяем дополнительную часть порядкового номера обновления if Trim( edtUpdNumberMinor.Text ) = sEMPTY_STR then begin MessageBox( Handle, PChar( sScrSetIsEmpty1 + cRenameInvalid[Ord( UsrFileType )] + sUpdateNumberInvalid ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING ); edtUpdNumberMinor.SetFocus; Exit; end else begin RenameParams.UpdateNumMinor := edtUpdNumberMinor.IntValue; end; //Проверяем дату создания обновления if Trim( edtDateCreate.Text ) = sEMPTY_STR then begin MessageBox( Handle, PChar( sScrSetIsEmpty1 + cRenameInvalid[Ord( UsrFileType )] + sUpdateDateCreateInvalid ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING ); edtDateCreate.SetFocus; Exit; end else begin RenameParams.DateCreate := edtDateCreate.Date; end; //Выставляем режим переименования RenameParams.RenameMode := rmRename; try RenameFileCount := 0; IsRenameSuccess := True; SelectedRec := dstMain.FieldByName(sSCRIPT_NAME_FN).AsString; n := dstMain.RecordCount - 1; tvwMain.BeginUpdate; dstMain.DisableControls; dstMain.First; for i := 0 to n do begin //Проверяем помечен ли текущий файл скрипта if dstMain.FieldByName(sIS_ACTIVE_FN).AsBoolean then begin OldFileName := ScriptPath + dstMain.FieldByName(sSCRIPT_NAME_FN).AsString; //Проверяем: не был ли удалён выбранный файл в процессе переименования файлов if FileExists( OldFileName ) then begin //Получаем новое имя скрипта NewFileName := sEMPTY_STR; CanRename := RenameScript( ExtractFileName( OldFileName ), NewFileName, RenameParams ); if CanRename then begin NewFileName := ScriptPath + NewFileName; //Переименовываем файл скрипта if RenameFile( OldFileName, NewFileName ) then begin NewFileName := ExtractFileName( NewFileName ); OldFileName := ExtractFileName( OldFileName ); //Обновляем соответствующую запись в НД if dstMain.Locate( sSCRIPT_NAME_FN, OldFileName, [] ) then begin dstMain.Edit; dstMain.FieldByName(sSCRIPT_NAME_FN).AsString := NewFileName; dstMain.Post; //Актуализируем информацию для позиционирования if OldFileName = SelectedRec then SelectedRec := NewFileName; end; Inc( RenameFileCount ); end else begin IsRenameSuccess := False; end; end; end else begin IsRenameSuccess := False; end; end; dstMain.Next; end; finally dstMain.Locate( sSCRIPT_NAME_FN, SelectedRec, [] ); dstMain.EnableControls; tvwMain.EndUpdate; //Оповещаем пользователя о результатах переименования if IsRenameSuccess then begin if RenameFileCount = 0 then MessageBox( Handle, PChar( cCanNotRename[Ord( UsrFileType )] ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING ) else MessageBox( Handle, PChar( IntToStr( RenameFileCount ) + sRenameFilesSuccessful ), PChar( sMsgCaptionInf ), MB_OK or MB_ICONINFORMATION ); end else MessageBox( Handle, PChar( sRenameFilesError1 + IntToStr( RenameFileCount ) + sRenameFilesError2 + IntToStr( SelectedRecCount ) + sRenameFilesError3 ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); end; end else begin if dstMain.IsEmpty then ErrMsg := cScrSetIsEmpty3[Ord( UsrFileType )] else ErrMsg := cScrSetIsEmpty2[Ord( UsrFileType )]; ErrMsg := sScrSetIsEmpty1 + cRenameInvalid[Ord( UsrFileType )] + ErrMsg; MessageBox( Handle, PChar( ErrMsg ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING ); end; except LogException( ExtractFilePath( Application.ExeName ) + sLOG_FILE_NAME ); Raise; end; except on E: Exception do begin MessageBox( Handle, PChar( sErrorTextExt + e.Message ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); end; end; end; //Формируем новое множество скриптов в соответствии с изменёнными критериями фильтрации procedure TfmMain.btnFilterClick(Sender: TObject); var i, n : Integer; Path : String; ErrMsg : String; KeyExpr : String; LoadResult : TLoadScrResult; ScriptNames : TUsrStringList; FilterParams : TFilterParams; CurrFileName : String; MaxUpdNumber : TUpdateNumInfo; CurrMaxUpdNum : TUpdateNumInfo; TmpLoadResult : TLoadScrResult; begin try try //Удаляем завершающий слеш для организации корректной проверки пути к скриптам Path := Trim( edtScriptPath.Text ); DelDirEndDelimiter( Path ); //Проверяем путь к скриптам if not DirectoryExists( Path ) then begin MessageBox( Handle, PChar( cScrDirNotFound[Ord( UsrFileType )] ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING ); edtScriptPath.Properties.OnButtonClick( nil, -1 ); end; //Формируем путь к скриптам с учётом завершающего слеша Path := Trim( edtScriptPath.Text ); SetDirEndDelimiter( Path ); FilterParams.ScriptPath := Path; //Получаем ключевое выражение, соответствующее выбранному проекту KeyExpr := GetKeyExpr( cbxProjects.Text ); if KeyExpr = sEMPTY_STR then begin MessageBox( Handle, PChar( sFatalError ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); Exit; end else begin FilterParams.KeyExpr := KeyExpr; end; //Проверяем главную часть порядкового номера обновления if Trim( edtFtrUpdNumMajor.Text ) = sEMPTY_STR then begin MessageBox( Handle, PChar( sScrSetIsEmpty1 + cFilterInvalid[Ord( UsrFileType )] + sUpdateNumberInvalid ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); edtFtrUpdNumMajor.SetFocus; Exit; end else begin FilterParams.UpdateNumMajor := edtFtrUpdNumMajor.IntValue; end; //Проверяем дополнительную часть порядкового номера обновления if Trim( edtFtrUpdNumMinor.Text ) = sEMPTY_STR then begin MessageBox( Handle, PChar( sScrSetIsEmpty1 + cFilterInvalid[Ord( UsrFileType )] + sUpdateNumberInvalid ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); edtFtrUpdNumMinor.SetFocus; Exit; end else begin FilterParams.UpdateNumMinor := edtFtrUpdNumMinor.IntValue; end; //Получаем нижнюю границу периода создания скриптов if cbxDateBeg.Checked then begin FilterParams.DateBeg := edtDateBeg.Text; end else begin FilterParams.DateBeg := sEMPTY_STR; end; //Получаем верхнюю границу периода создания скриптов if cbxDateEnd.Checked then begin FilterParams.DateEnd := edtDateEnd.Text; end else begin FilterParams.DateEnd := sEMPTY_STR; end; //Пытаемся загрузить скрипты try ScriptNames := TUsrStringList.Create; ScriptNames.Sorted := cDEF_CAN_SORT; ScriptNames.CaseSensitive := cDEF_CASE_SENSITIVE; case UsrFileType of ftScripts : begin FilterParams.ScriptPath := Path + sSCRIPTS_MASK; MaxUpdNumber.UpdateNumMajor := cZERO; MaxUpdNumber.UpdateNumMinor := cDEF_UPDATE_NUMBER; LoadResult:= LoadScripts( FilterParams, ScriptNames, MaxUpdNumber ); end; ftModules : begin LoadResult := lrModulesInvalid; MaxUpdNumber.UpdateNumMajor := cZERO; MaxUpdNumber.UpdateNumMinor := cDEF_UPDATE_NUMBER; CurrMaxUpdNum.UpdateNumMajor := cZERO; CurrMaxUpdNum.UpdateNumMinor := cDEF_UPDATE_NUMBER; n := High( cArchiveExt ); //Пытаемся загрузить любые архивы, содержащие модули for i := Low( cArchiveExt ) to n do begin FilterParams.ScriptPath := Path + cArchiveExt[i]; TmpLoadResult := LoadScripts( FilterParams, ScriptNames, CurrMaxUpdNum ); case TmpLoadResult of lrLoadSuccess : begin LoadResult := lrLoadSuccess; if MaxUpdNumber.UpdateNumMajor < CurrMaxUpdNum.UpdateNumMajor then MaxUpdNumber.UpdateNumMajor := CurrMaxUpdNum.UpdateNumMajor; if MaxUpdNumber.UpdateNumMinor < CurrMaxUpdNum.UpdateNumMinor then MaxUpdNumber.UpdateNumMinor := CurrMaxUpdNum.UpdateNumMinor; end; end; end; end; end; //Анализируем результат загрузки скриптов case LoadResult of lrLoadSuccess : begin edtUpdNumberMajor.Value := MaxUpdNumber.UpdateNumMajor; edtUpdNumberMinor.Value := MaxUpdNumber.UpdateNumMinor + 1; CurrFileName := dstMain.FieldByName(sSCRIPT_NAME_FN).AsString; try tvwMain.DataController.BeginUpdate; FillDataset( dstMain, ScriptNames, FSelectedRecCount, fmAppend ); tvwMain.DataController.UpdateData; finally tvwMain.DataController.EndUpdate; end; //Позиционируемся на активной до инвертирования записи tvwMain.DataController.BeginLocate; if not dstMain.Locate( sSCRIPT_NAME_FN, CurrFileName, [] ) then tvwMain.DataController.GotoFirst; tvwMain.DataController.EndLocate; end; lrScrNotFound : begin MessageBox( Handle, PChar( cScrLoadFailed[Ord( UsrFileType )] ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING ); end; lrFilterInvalid, lrModulesInvalid : begin if dstMain.Active then dstMain.Close; SetSelectedRecCount( 0 ); tvwMain.DataController.Summary.FooterSummaryValues[cmnIsActive.Index] := SelectedRecCount; tvwMain.DataController.Summary.FooterSummaryValues[cmnFileSize.Index] := cZERO; if LoadResult = lrFilterInvalid then begin ErrMsg := cScrFilterInvalid[Ord( UsrFileType )]; end else begin ErrMsg := sModulesInvalid; end; MessageBox( Handle, PChar( ErrMsg ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING ); end; end; finally if ScriptNames <> nil then FreeAndNil( ScriptNames ); end; except LogException( ExtractFilePath( Application.ExeName ) + sLOG_FILE_NAME ); Raise; end; except on E: Exception do begin MessageBox( Handle, PChar( sErrorTextExt + e.Message ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); end; end; end; //Копируем помеченные файлы procedure TfmMain.btnCopyClick(Sender: TObject); var i, n : Integer; ErrMsg : String; CopyPath : String; DlgResult : Integer; ScriptPath : String; SelectedRec : String; CopyFileName : String; CurrFileName : String; CopyFileCount : Integer; IsCopySuccess : Boolean; begin try try if not dstMain.IsEmpty AND ( SelectedRecCount > 0 ) then begin //Получаем путь к хранилищу файлов скриптов ScriptPath := Trim( edtScriptPath.Text ); if not DirectoryExists( ScriptPath ) then begin MessageBox( Handle, PChar( cScrDirNotFound[Ord( UsrFileType )] ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING ); edtScriptPath.SetFocus; Exit; end; SetDirEndDelimiter( ScriptPath ); //Получаем путь для копирования файлов скриптов { if bdlgMain.Execute then }begin{ CopyPath := bdlgMain.Path; if not DirectoryExists( CopyPath ) then begin MessageBox( Handle, PChar( sPathInvalid ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); Exit; end; } BrowseFolderDlg1.BrowseDialog('Выберите каталог для копирования', CopyPath); SetDirEndDelimiter( CopyPath ); bdlgMain.Path := ''; try CopyFileCount := 0; IsCopySuccess := True; SelectedRec := dstMain.FieldByName(sSCRIPT_NAME_FN).AsString; n := dstMain.RecordCount - 1; dstMain.DisableControls; dstMain.First; for i := 0 to n do begin //Проверяем помечен ли текущий файл скрипта if dstMain.FieldByName(sIS_ACTIVE_FN).AsBoolean then begin CopyFileName := ScriptPath + dstMain.FieldByName(sSCRIPT_NAME_FN).AsString; //Проверяем: не был ли удалён выбранный файл в процессе копирования файлов if FileExists( CopyFileName ) then begin CurrFileName := CopyPath + dstMain.FieldByName(sSCRIPT_NAME_FN).AsString; DlgResult := cDEF_DLG_RESULT; //Проверяем: существует ли уже файл, чье имя совпадает с копируемым if FileExists( CurrFileName ) then begin DlgResult := MessageBox( Handle, PChar( sFileAlreadyExists1 + CurrFileName + sFileAlreadyExists2 ), PChar( sMsgCaptionQst ), MB_YESNOCANCEL or MB_ICONQUESTION ); end; //Получаем режим работы с файлом case DlgResult of ID_YES : begin //Удаляем существующий файл скрипта if not DeleteFile( CurrFileName ) then begin MessageBox( Handle, PChar( sFileAlreadyExists1 + CurrFileName + sFileCannotBeDeleted ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); IsCopySuccess := False; dstMain.Next; Continue; end; CopyFile( CopyFileName, CurrFileName, nil ); Inc( CopyFileCount ); end; ID_CANCEL : begin Exit; end; cDEF_DLG_RESULT : begin CopyFile( CopyFileName, CurrFileName, nil ); Inc( CopyFileCount ); end; end; end else begin IsCopySuccess := False; end; end; dstMain.Next; end; finally dstMain.Locate( sSCRIPT_NAME_FN, SelectedRec, [] ); dstMain.EnableControls; //Оповещаем пользователя о результатах копирования if IsCopySuccess then begin if DlgResult = ID_CANCEL then MessageBox( Handle, PChar( sCopyAbort ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING ) else MessageBox( Handle, PChar( IntToStr( CopyFileCount ) + sCopyFilesSuccessful ), PChar( sMsgCaptionInf ), MB_OK or MB_ICONINFORMATION ); end else MessageBox( Handle, PChar( sCopyFilesError1 + IntToStr( CopyFileCount ) + sCopyFilesError2 + IntToStr( SelectedRecCount ) + sCopyFilesError3 ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); end; end; end else begin if dstMain.IsEmpty then ErrMsg := cScrSetIsEmpty3[Ord( UsrFileType )] else ErrMsg := cScrSetIsEmpty2[Ord( UsrFileType )]; ErrMsg := sScrSetIsEmpty1 + cCopyInvalid[Ord( UsrFileType )] + ErrMsg; MessageBox( Handle, PChar( ErrMsg ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING ); end; except LogException( ExtractFilePath( Application.ExeName ) + sLOG_FILE_NAME ); Raise; end; except on E: Exception do begin MessageBox( Handle, PChar( sErrorTextExt + e.Message ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); end; end; end; //Выделяем все записи procedure TfmMain.btnSelectAllClick(Sender: TObject); var ScrName : String; begin try try if not dstMain.IsEmpty then begin //Проверяем количество не помеченых записей if SelectedRecCount <> dstMain.RecordCount then begin ScrName := dstMain.FieldByName(sSCRIPT_NAME_FN).AsString; tvwMain.DataController.BeginUpdate; SelectedRecCount := SelectRecords( dstMain, smSelectAll ); tvwMain.DataController.EndUpdate; //Позиционируемся на активной до инвертирования записи tvwMain.DataController.BeginLocate; dstMain.Locate( sSCRIPT_NAME_FN, ScrName, [] ); tvwMain.DataController.EndLocate; end; end else begin MessageBox( Handle, PChar( sScrSetIsEmpty1 + sSelectAllInvalid + cScrSetIsEmpty3[Ord( UsrFileType )] ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING ); end; except LogException( ExtractFilePath( Application.ExeName ) + sLOG_FILE_NAME ); Raise; end; except on E: Exception do begin MessageBox( Handle, PChar( sErrorTextExt + e.Message ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); end; end; end; //Снимаем выделение для всех записей procedure TfmMain.btnUnselectAllClick(Sender: TObject); var ScrName : String; begin try try if not dstMain.IsEmpty then begin //Проверяем количество помеченых записей if SelectedRecCount <> 0 then begin ScrName := dstMain.FieldByName(sSCRIPT_NAME_FN).AsString; tvwMain.DataController.BeginUpdate; SelectedRecCount := SelectRecords( dstMain, smUnSelectAll ); tvwMain.DataController.EndUpdate; //Позиционируемся на активной до инвертирования записи tvwMain.DataController.BeginLocate; dstMain.Locate( sSCRIPT_NAME_FN, ScrName, [] ); tvwMain.DataController.EndLocate; end; end else begin MessageBox( Handle, PChar( sScrSetIsEmpty1 + sUnSelectAllInvalid + cScrSetIsEmpty3[Ord( UsrFileType )] ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING ); end; except LogException( ExtractFilePath( Application.ExeName ) + sLOG_FILE_NAME ); Raise; end; except on E: Exception do begin MessageBox( Handle, PChar( sErrorTextExt + e.Message ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); end; end; end; //Инвертируем выделение procedure TfmMain.btnInvertClick(Sender: TObject); var ScrName : String; begin try try if not dstMain.IsEmpty then begin ScrName := dstMain.FieldByName(sSCRIPT_NAME_FN).AsString; tvwMain.DataController.BeginUpdate; SelectedRecCount := SelectRecords( dstMain, smInvert ); tvwMain.DataController.EndUpdate; //Позиционируемся на активной до инвертирования записи tvwMain.DataController.BeginLocate; dstMain.Locate( sSCRIPT_NAME_FN, ScrName, [] ); tvwMain.DataController.EndLocate; end else begin MessageBox( Handle, PChar( sScrSetIsEmpty1 + sInvertInvalid + cScrSetIsEmpty3[Ord( UsrFileType )] ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING ); end; except LogException( ExtractFilePath( Application.ExeName ) + sLOG_FILE_NAME ); Raise; end except on E: Exception do begin MessageBox( Handle, PChar( sErrorTextExt + e.Message ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); end; end; end; //Получаем путь к хранилищу скриптов procedure TfmMain.edtScriptPathPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); var s: string; begin if DirectoryExists( Trim( edtScriptPath.Text ) ) then begin bdlgMain.Path := Trim( edtScriptPath.Text ); end; { if bdlgMain.Execute then begin edtScriptPath.Text := bdlgMain.Path; bdlgMain.Path := ''; end;} if BrowseFolderDlg1.BrowseDialog('Выберите папку со скриптами', s) Then edtScriptPath.Text := s; end; //Помечаем(снимаем пометку) для выбранной пользователем записи procedure TfmMain.tvwMainCellClick(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean); begin //Помечаем(снимаем пометку) для выбранной пользователем записи if ( ACellViewInfo.Item.Name = cmnIsActive.Name ) and ( AButton = mbLeft ) then begin aHandled := False; dstMain.Edit; if dstMain.FieldByName(sIS_ACTIVE_FN).AsBoolean then begin dstMain.FieldByName(sIS_ACTIVE_FN).AsBoolean := False; SelectedRecCount := SelectedRecCount - 1; end else begin dstMain.FieldByName(sIS_ACTIVE_FN).AsBoolean := True; SelectedRecCount := SelectedRecCount + 1; end; dstMain.Post; aHandled := True; end; end; //Показываем количество помеченных записей в "итоговой" строке procedure TfmMain.tvwMainDataControllerSummaryFooterSummaryItemsSummary( ASender: TcxDataSummaryItems; Arguments: TcxSummaryEventArguments; var OutArguments: TcxSummaryEventOutArguments); var i, n : Integer; TotalSize : Extended; SelectedSize : Extended; begin //Вычисляем кол-во отобранных файлов if Arguments.SummaryItem.Index = cmnIsActive.Index then begin OutArguments.SummaryValue := SelectedRecCount; end; //Вычисляем размер всех и отобранных файлов if Arguments.SummaryItem.Index = cmnFileSize.Index then begin TotalSize := 0; SelectedSize := 0; with tvwMain.DataController do begin n := RecordCount - 1; for i := 0 to n do begin TotalSize := TotalSize + Values[ i, cmnFileSize.Index ]; if Values[ i, cmnIsActive.Index ] then SelectedSize := SelectedSize + Values[ i, cmnFileSize.Index ]; end; end; OutArguments.SummaryValue := FormatFloat( sFMT_SEL_FILES_SIZE, SelectedSize ) + sSPACE + sSEPARATOR_FOLDER_UNX + sSPACE + FormatFloat( sFMT_ALL_FILES_SIZE, TotalSize ); end; end; //Активируем(деактивируем) поле ввода для задания нижней границы даты создания скриптов procedure TfmMain.cbxDateBegClick(Sender: TObject); begin if cbxDateBeg.Checked then begin edtDateBeg.ReadOnly := False; edtDateBeg.SetFocus; SetFocusedControl( grMain.Controller.Control ); end else begin edtDateBeg.ReadOnly := True; grMain.Controller.Control.SetFocus; end; end; //Активируем(деактивируем) поле ввода для задания верхней границы даты создания скриптов procedure TfmMain.cbxDateEndClick(Sender: TObject); begin if cbxDateEnd.Checked then begin edtDateEnd.ReadOnly := False; edtDateEnd.SetFocus; SetFocusedControl( grMain.Controller.Control ); end else begin edtDateEnd.ReadOnly := True; grMain.Controller.Control.SetFocus; end; end; //Помечаем(снимаем пометку) для выбранной пользователем записи procedure TfmMain.tvwMainKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin //Помечаем(снимаем пометку) для выбранной пользователем записи if not dstMain.IsEmpty AND ( Key = VK_SPACE ) then begin dstMain.Edit; if dstMain.FieldByName(sIS_ACTIVE_FN).AsBoolean then begin dstMain.FieldByName(sIS_ACTIVE_FN).AsBoolean := False; SelectedRecCount := SelectedRecCount - 1; end else begin dstMain.FieldByName(sIS_ACTIVE_FN).AsBoolean := True; SelectedRecCount := SelectedRecCount + 1; end; dstMain.Post; end; end; //Разименовываем помеченные файлы скриптов procedure TfmMain.btnUnRenameClick(Sender: TObject); var i, n : Integer; ErrMsg : String; Scripts : TStringList; ScriptPath : String; CanUnRename : Boolean; SelectedRec : String; OldFileName : String; NewFileName : String; RenameParams : TRenameParams; UnRenameFileCount : Integer; IsUnRenameSuccess : Boolean; begin try try if not dstMain.IsEmpty AND ( SelectedRecCount > 0 ) then begin //Получаем путь к хранилищу файлов скриптов ScriptPath := Trim( edtScriptPath.Text ); if not DirectoryExists( ScriptPath ) then begin MessageBox( Handle, PChar( cScrDirNotFound[Ord( UsrFileType )] ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING ); edtScriptPath.SetFocus; Exit; end; SetDirEndDelimiter( ScriptPath ); //Получаем ключевое выражение, соответствующее выбранному проекту RenameParams.KeyExpr := GetKeyExpr( cbxProjects.Text ); if RenameParams.KeyExpr = sEMPTY_STR then begin MessageBox( Handle, PChar( sFatalError ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); Exit; end; //Проверяем главную часть порядкового номера обновления if Trim( edtUpdNumberMajor.Text ) = sEMPTY_STR then begin MessageBox( Handle, PChar( sScrSetIsEmpty1 + cUnRenameInvalid[Ord( UsrFileType )] + sUpdateNumberInvalid ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING ); edtUpdNumberMajor.SetFocus; Exit; end else begin RenameParams.UpdateNumMajor := edtUpdNumberMajor.IntValue; end; //Проверяем дополнительную часть порядкового номера обновления if Trim( edtUpdNumberMinor.Text ) = sEMPTY_STR then begin MessageBox( Handle, PChar( sScrSetIsEmpty1 + cUnRenameInvalid[Ord( UsrFileType )] + sUpdateNumberInvalid ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING ); edtUpdNumberMinor.SetFocus; Exit; end else begin RenameParams.UpdateNumMinor := edtUpdNumberMinor.IntValue; end; //Проверяем дату создания обновления if Trim( edtDateCreate.Text ) = sEMPTY_STR then begin MessageBox( Handle, PChar( sScrSetIsEmpty1 + cUnRenameInvalid[Ord( UsrFileType )] + sUpdateDateCreateInvalid ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING ); edtDateCreate.SetFocus; Exit; end else begin RenameParams.DateCreate := edtDateCreate.Date; end; //Выставляем режим разименования RenameParams.RenameMode := rmUnRename; try UnRenameFileCount := 0; IsUnRenameSuccess := True; SelectedRec := dstMain.FieldByName(sSCRIPT_NAME_FN).AsString; n := dstMain.RecordCount - 1; tvwMain.BeginUpdate; dstMain.DisableControls; dstMain.First; for i := 0 to n do begin //Проверяем помечен ли текущий файл скрипта if dstMain.FieldByName(sIS_ACTIVE_FN).AsBoolean then begin OldFileName := ScriptPath + dstMain.FieldByName(sSCRIPT_NAME_FN).AsString; //Проверяем: не был ли удалён выбранный файл в процессе переименования файлов if FileExists( OldFileName ) then begin //Получаем новое имя скрипта NewFileName := sEMPTY_STR; CanUnRename := RenameScript( ExtractFileName( OldFileName ), NewFileName, RenameParams ); if CanUnRename then begin NewFileName := ScriptPath + NewFileName; //Переименовываем файл скрипта if RenameFile( OldFileName, NewFileName ) then begin NewFileName := ExtractFileName( NewFileName ); OldFileName := ExtractFileName( OldFileName ); //Обновляем соответствующую запись в НД if dstMain.Locate( sSCRIPT_NAME_FN, OldFileName, [] ) then begin dstMain.Edit; dstMain.FieldByName(sSCRIPT_NAME_FN).AsString := NewFileName; dstMain.Post; //Актуализируем информацию для позиционирования if OldFileName = SelectedRec then SelectedRec := NewFileName; end; Inc( UnRenameFileCount ); end else begin IsUnRenameSuccess := False; end; end; end else begin IsUnRenameSuccess := False; end; end; dstMain.Next; end; finally dstMain.Locate( sSCRIPT_NAME_FN, SelectedRec, [] ); dstMain.EnableControls; tvwMain.EndUpdate; //Оповещаем пользователя о результатах переименования if IsUnRenameSuccess then begin if UnRenameFileCount = 0 then MessageBox( Handle, PChar( cCanNotUnRename[Ord( UsrFileType )] ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING ) else MessageBox( Handle, PChar( IntToStr( UnRenameFileCount ) + sUnRenameFilesSuccessful ), PChar( sMsgCaptionInf ), MB_OK or MB_ICONINFORMATION ); end else MessageBox( Handle, PChar( sUnRenameFilesError1 + IntToStr( UnRenameFileCount ) + sUnRenameFilesError2 + IntToStr( SelectedRecCount ) + sUnRenameFilesError3 ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); end; end else begin if dstMain.IsEmpty then ErrMsg := cScrSetIsEmpty3[Ord( UsrFileType )] else ErrMsg := cScrSetIsEmpty2[Ord( UsrFileType )]; ErrMsg := sScrSetIsEmpty1 + cUnRenameInvalid[Ord( UsrFileType )] + ErrMsg; MessageBox( Handle, PChar( ErrMsg ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING ); end; except LogException( ExtractFilePath( Application.ExeName ) + sLOG_FILE_NAME ); Raise; end; except on E: Exception do begin MessageBox( Handle, PChar( sErrorTextExt + e.Message ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); end; end; end; //Передаём фокус ввода следующему елементу управления procedure TfmMain.edtServerNameKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RETURN then begin edtLogin.SetFocus; end; end; //Передаём фокус ввода следующему елементу управления procedure TfmMain.edtLoginKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RETURN then begin edtPassword.SetFocus; end; end; //Передаём фокус ввода следующему елементу управления procedure TfmMain.edtPasswordKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RETURN then begin edtDBPath.SetFocus; end; end; //Передаём фокус ввода следующему елементу управления procedure TfmMain.edtDBPathKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RETURN then begin btnTestConnect.SetFocus; end; end; //Запрещаем передачу фокуса ввода при нажатии клавиши "Tab" procedure TfmMain.SplitterAfterClose(Sender: TObject); begin edtServerName.TabStop := False; edtLogin.TabStop := False; edtPassword.TabStop := False; edtDBPath.TabStop := False; btnTestConnect.TabStop := False; end; //Разрешаем передачу фокуса ввода при нажатии клавиши "Tab" procedure TfmMain.SplitterAfterOpen(Sender: TObject); begin edtServerName.TabStop := True; edtLogin.TabStop := True; edtPassword.TabStop := True; edtDBPath.TabStop := True; btnTestConnect.TabStop := True; end; //Получаем путь к файлу БД для тестирования обновления procedure TfmMain.edtDBPathPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); begin dlgDBPath.Filter := sDEF_DB_FILTER; dlgDBPath.FileName := sEMPTY_STR; dlgDBPath.DefaultExt := sDEF_DB_EXT; if dlgDBPath.Execute then begin edtDBPath.Text := Trim( dlgDBPath.FileName ); end; end; //Проверяем параметры соединения procedure TfmMain.btnTestConnectClick(Sender: TObject); var DBPath : String; ErrMsg : String; UserMsg : String; ErrCode : Integer; UserName : String; Password : String; begin try try //Получаем параметры соединения DBPath := Trim( edtServerName.Text ) + sDBL_POINT; DBPath := DBPath + Trim( edtDBPath.Text ); UserName := Trim( edtLogin.Text ); Password := Trim( edtPassword.Text ); //Проверяем параметры соединения TestConnection( dbTestConnect, DBPath, UserName, Password, ErrMsg, ErrCode ); //Оповещаем пользователя о результатах проверки case ErrCode of -1 : begin MessageBox( Handle, PChar( sConnectOK ), PChar( sMsgCaptionInf ), MB_OK or MB_ICONINFORMATION ); end; else begin MessageBox( Handle, PChar( sConnectErr ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); end; end; except //Протоколируем ИС LogException( ExtractFilePath( Application.ExeName ) + sLOG_FILE_NAME ); Raise; end; except on E: Exception do MessageBox( Handle, PChar( sErrorTextExt + E.Message ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ) end; end; //Очищаем набор данных при изменении критериев фильтрации procedure TfmMain.cbxProjectsChange(Sender: TObject); begin tvwMain.BeginUpdate; dstMain.Close; tvwMain.EndUpdate; edtUpdNumberMajor.Text := sZERO; edtUpdNumberMinor.Text := sZERO; SetSelectedRecCount( 0 ); tvwMain.DataController.Summary.FooterSummaryValues[cmnIsActive.Index] := SelectedRecCount; tvwMain.DataController.Summary.FooterSummaryValues[cmnFileSize.Index] := cZERO; end; //Сохраняем имя сервера в списке недавно введенных значений procedure TfmMain.edtServerNamePropertiesChange(Sender: TObject); begin TcxMRUEdit( Sender ).ValidateEdit( False ); end; //Запоминаем тип файлов, над которыми будут выполняться действия procedure TfmMain.rgrFileTypeClick(Sender: TObject); begin case rgrFileType.ItemIndex of 0 : begin SetUsrFileType( ftScripts ); btnBuild.Visible := ivAlways; pmnuBuild.Visible := True; end; 1 : begin SetUsrFileType( ftModules ); btnBuild.Visible := ivNever; pmnuBuild.Visible := False; end; end; stbMain.Panels.BeginUpdate; stbMain.Panels[0].Text := cDescriptionPath[Ord( UsrFileType )]; stbMain.Panels.EndUpdate; SetFocusedControl( grMain.Controller.Control ); end; //Выичсляем максимальный номер обновления procedure TfmMain.btnCalcMaxUpdateNumClick(Sender: TObject); var i, n : Integer; KeyExpr : String; FilePath : String; ArrFileExt : TStrArray; MaxUpdNumber : TUpdateNumInfo; MaxUpdNumParams : TMaxUpdNumParams; CurrMaxUpdNumber : TUpdateNumInfo; begin try try FilePath := Trim( edtScriptPath.Text ); SetDirEndDelimiter( FilePath ); //Проверяем путь к скриптам if not DirectoryExists( FilePath ) then begin MessageBox( Handle, PChar( cScrDirNotFound[Ord( UsrFileType )] ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING ); Exit; end; //Получаем ключевое выражение, соответствующее выбранному проекту KeyExpr := GetKeyExpr( cbxProjects.Text ); if KeyExpr = sEMPTY_STR then begin MessageBox( Handle, PChar( sFatalError ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); Exit; end else begin MaxUpdNumParams.KeyExpr := KeyExpr; end; try //Получаем массив, содержащий маски файлов для поиска case UsrFileType of ftScripts : begin n := High( cScriptExt ); SetLength( ArrFileExt, n ); ArrFileExt := @cScriptExt; end; ftModules : begin n := High( cArchiveExt ); SetLength( ArrFileExt, n ); ArrFileExt := @cArchiveExt; end; end; //Инициализируем переменные with MaxUpdNumber do begin UpdateNumMajor := cZERO; UpdateNumMinor := cZERO; end; with CurrMaxUpdNumber do begin UpdateNumMajor := cZERO; UpdateNumMinor := cZERO; end; //Вычисляем максимальный номер обновления for i := 0 to n do begin MaxUpdNumParams.FilePath := FilePath + ArrFileExt[i]; CurrMaxUpdNumber := GetMaxUpdNumber( MaxUpdNumParams ); if MaxUpdNumber.UpdateNumMajor < CurrMaxUpdNumber.UpdateNumMajor then begin MaxUpdNumber.UpdateNumMajor := CurrMaxUpdNumber.UpdateNumMajor; end; if MaxUpdNumber.UpdateNumMinor < CurrMaxUpdNumber.UpdateNumMinor then begin MaxUpdNumber.UpdateNumMinor := CurrMaxUpdNumber.UpdateNumMinor; end; end; edtUpdNumberMajor.IntValue := MaxUpdNumber.UpdateNumMajor; edtUpdNumberMinor.IntValue := MaxUpdNumber.UpdateNumMinor + 1; finally if ArrFileExt <> nil then begin Finalize( ArrFileExt ); ArrFileExt := nil; end; end; except //Протоколируем ИС LogException( ExtractFilePath( Application.ExeName ) + sLOG_FILE_NAME ); Raise; end; except on E: Exception do MessageBox( Handle, PChar( sErrorTextExt + E.Message ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ) end; end; //Запоминаем введённое пользователем значение procedure TfmMain.edtUpdNumberMajorButtonClick(Sender: TdxBarSpinEdit; Button: TdxBarSpinEditButton); begin Sender.Value := Sender.CurValue; end; //Запоминаем введённое пользователем значение procedure TfmMain.edtFtrUpdNumMajorButtonClick(Sender: TdxBarSpinEdit; Button: TdxBarSpinEditButton); begin Sender.Value := Sender.CurValue; end; //Показываем метку, указывающую пользователю как загрузить файлы procedure TfmMain.dstMainAfterClose(DataSet: TDataSet); begin lblDescription.Visible := True; end; //Скрываем метку, указывающую пользователю как загрузить файлы procedure TfmMain.dstMainAfterOpen(DataSet: TDataSet); begin lblDescription.Visible := False; end; //Выполняем только тестирование файла обновления procedure TfmMain.mnuOnlyTestClick(Sender: TObject); var DBPath : String; ErrMsg : String; UserMsg : String; ErrCode : Integer; UserName : String; Password : String; DlgResult : Integer; TmpStrList : TStringList; ErrFileName : String; IBEscriptName : String; UpdateFilePath : String; begin try try //Проверяем путь к программе применения скриптов if not FileExists( IBEscriptPath ) then begin dlgDBPath.Filter := sDEF_EXE_FILTER; dlgDBPath.FileName := sDEF_IBESCRIPT_PATH; dlgDBPath.DefaultExt := sDEF_EXE_EXT; //Предоставляем пользователю возможность самому указать путь к программе применения скриптов if not dlgDBPath.Execute OR ( ExtractFileName( dlgDBPath.FileName ) <> sSCRIPT_EXECUTER_NAME ) then begin MessageBox( Handle, PChar( sErrorUpdateTest + sInvalidIBEscriptPath ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); Exit; end else begin SetIBEscriptPath( Trim( dlgDBPath.FileName ) ); end; end; //Получаем параметры соединения DBPath := Trim( edtServerName.Text ) + sDBL_POINT; DBPath := DBPath + Trim( edtDBPath.Text ); UserName := Trim( edtLogin.Text ); Password := Trim( edtPassword.Text ); //Проверяем параметры соединения TestConnection( dbTestConnect, DBPath, UserName, Password, ErrMsg, ErrCode ); if ErrCode <> -1 then begin MessageBox( Handle, PChar( sConnectErr ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); Exit; end; //Получаем путь к файлу, который подлежит тестированию if ( TComponent( Sender ).Name = mnuOnlyTest.Name ) OR ( TComponent( Sender ).Name = smnuOnlyTest.Name ) then begin dlgDBPath.Filter := sDEF_SQL_FILTER; dlgDBPath.FileName := sEMPTY_STR; dlgDBPath.DefaultExt := sSCRIPTS_MASK; //Предоставляем пользователю возможность самому указать путь к файлу скрипта if not dlgDBPath.Execute then begin MessageBox( Handle, PChar( sErrorTestProcess ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING ); Exit; end else begin UpdateFilePath := Trim( dlgDBPath.FileName ); end; end else begin UpdateFilePath := UpdFilePath; end; ErrFileName := ExtractFilePath( Application.ExeName ) + sUPDATE_ERRORS_FILE_NAME; IBEscriptName := sSCRIPT_EXECUTER_NAME_NO_EXT + sSPACE; fmMain.Repaint; fmMain.Cursor := crHourGlass; //Применяем скрипт с помощью утилиты IBEScript.exe CreateMyProcess( PAnsiChar( IBEscriptPath ), PAnsiChar( IBEscriptName + sTICKS + UpdateFilePath + sTICKS + sCOMMAND_LINE_SCRIPT_EXEC + sTICKS + ErrFileName + sTICKS + ' -D' + sTICKS + DBPath + sTICKS + ' -P' + Password + ' -U' + UserName ), SW_HIDE ); try TmpStrList := TStringList.Create; TmpStrList.LoadFromFile( ErrFileName ); //Анализируем результат применения скрипта if Pos( sEXECUTE_SCRIPT_STR, TmpStrList.Text ) = 0 then begin DlgResult := MessageBox( Handle, PChar( sErrorUpdate ), PChar( sMsgCaptionErr ), MB_YESNO or MB_ICONERROR ); //Выгружаем файл-отчет ошибок в блокнот if DlgResult = ID_YES then begin ShellExecute( Handle, PChar( sEXECUTE_OPERATION ), PChar( ErrFileName ), Nil, Nil, SW_NORMAL ); end; end else begin //Удаляем лог-файл для успешно примененённого скрипта DeleteFile( ErrFileName ); MessageBox( Handle, PChar( sSuccessUpdate ), PChar( sMsgCaptionInf ), MB_OK or MB_ICONINFORMATION ); end; finally if TmpStrList <> nil then FreeAndNil( TmpStrList ); fmMain.Cursor := crDefault; end; except LogException( ExtractFilePath( Application.ExeName ) + sLOG_FILE_NAME ); Raise; end; except on E: Exception do begin MessageBox( Handle, PChar( sErrorTextExt + e.Message ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); end; end; end; //Расскрашиваем неотобранные строки цветом, соответствующим неактивой строке procedure TfmMain.tvwMainCustomDrawCell(Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean); begin // end; //Организуем поиск текстовой строки procedure TfmMain.btnSearchClick(Sender: TObject); var fmSearch : TfmSearch; SearchResult : Boolean; CurrRecValue : String; vSearchParams : TPtr_SearchParams; begin try try if not dstMain.IsEmpty then begin try fmSearch := TfmSearch.Create( Self ); fmSearch.ShowModal; if fmSearch.ModalResult = mrOK then begin CurrRecValue := dstMain.FieldByName( sSCRIPT_NAME_FN ).AsString; //Освобождаем не используемые ресурсы if SearchParams <> nil then Dispose( SearchParams ); SearchParams := nil; //Получаем параметры поиска try New( vSearchParams ); with vSearchParams^ do begin TextSearch := Trim( fmSearch.edtSearch.Text ); Direction := TEnm_Direction( fmSearch.rgrDirection.ItemIndex ); CaseSensitive := fmSearch.cbxCaseSensitive.Checked; WholeWordsOnly := fmSearch.cbxWholeWords.checked; end; //Выполняем поиск SearchResult := FindText( dstMain, sSCRIPT_NAME_FN, vSearchParams ); if SearchResult then begin AppMode := amSearch; New( FSearchParams ); SearchParams^ := vSearchParams^; SearchParams^.FirstFound := dstMain.FieldByName( sSCRIPT_NAME_FN ).AsString; end else begin AppMode := amView; dstMain.Locate( sSCRIPT_NAME_FN, CurrRecValue, [] ); MessageBox( Handle, PChar( sSearchStrNotFound + sTICK + vSearchParams^.TextSearch + sTICK + sSPACE + sNotFound ), PChar( sMsgCaptionInf ), MB_OK or MB_ICONINFORMATION ); end; finally if vSearchParams <> nil then Dispose( vSearchParams ); vSearchParams := nil; end; end; finally if fmSearch <> nil then FreeAndNil( fmSearch ); end; end else begin MessageBox( Handle, PChar( sScrSetIsEmpty1 + sSearchInvalid + cSearchInvalid[Ord( UsrFileType )] ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING ); end; except LogException( ExtractFilePath( Application.ExeName ) + sLOG_FILE_NAME ); Raise; end except on E: Exception do begin MessageBox( Handle, PChar( sErrorTextExt + e.Message ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); end; end; end; //Обрабатываем горячие клавиши procedure TfmMain.FormShortCut(var Msg: TWMKey; var Handled: Boolean); var CurrRecValue : String; SearchResult : Boolean; begin case Msg.CharCode of VK_F3 : begin if AppMode = amSearch then begin CurrRecValue := dstMain.FieldByName( sSCRIPT_NAME_FN ).AsString; //Выполняем поиск SearchResult := FindText( dstMain, sSCRIPT_NAME_FN, SearchParams ); if not SearchResult OR ( dstMain.FieldByName( sSCRIPT_NAME_FN ).AsString = SearchParams^.FirstFound ) then begin AppMode := amView; dstMain.Locate( sSCRIPT_NAME_FN, CurrRecValue, [] ); MessageBox( Handle, PChar( sSearchStrNotFound + sTICK + SearchParams^.TextSearch + sTICK + sSPACE + sNotFound ), PChar( sMsgCaptionInf ), MB_OK or MB_ICONINFORMATION ); //Освобождаем не используемые ресурсы if SearchParams <> nil then Dispose( SearchParams ); SearchParams := nil; Exit; end; Handled := True; end; end; VK_ESCAPE : begin btnExit.Click; Handled := True; end; end; end; procedure TfmMain.grMainDblClick(Sender: TObject); begin // s := ScriptsPathEdit.Text + lbScripts.Items.Strings[lbScripts.ItemIndex]; // ShellExecute(0, 'open', 'notepad.exe', PAnsiChar(s), nil, SW_SHOW); end; end.
unit Base.View; // Herança // Todos os formulários descendem deste formulário. interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, dxBevel, Vcl.ExtCtrls, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus, dxSkinsCore, Vcl.StdCtrls, cxButtons, ormbr.factory.interfaces, cxControls, cxContainer, cxEdit, cxLabel, Tipos.Controller.Interf, dxGDIPlusClasses, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Silver, dxSkinOffice2016Colorful, dxSkinOffice2016Dark, dxSkinDarkRoom, dxSkinDarkSide, dxSkinMetropolisDark, dxSkinVisualStudio2013Dark, dxSkinBlack, dxSkinSilver, dxSkinVS2010; type TFBaseView = class(TForm) Panel1: TPanel; Panel2: TPanel; PnBotoes: TPanel; BtEncerrar: TcxButton; Panel3: TPanel; cxLabel1: TcxLabel; Panel4: TPanel; Panel5: TPanel; PnIconeTitulo: TPanel; ImIconeTitulo: TImage; PnTituloJanela: TPanel; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure BtEncerrarClick(Sender: TObject); private protected FConexao: IDBConnection; FOperacao: TTipoOperacao; public end; var FBaseView: TFBaseView; implementation {$R *.dfm} uses FacadeController; procedure TFBaseView.BtEncerrarClick(Sender: TObject); begin Close; end; procedure TFBaseView.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TFBaseView.FormCreate(Sender: TObject); begin FConexao := TFacadeController.New.ConexaoController.conexaoAtual; end; procedure TFBaseView.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_RETURN: Perform(WM_NEXTDLGCTL, 0, 0); VK_ESCAPE: Close; end; end; end.
unit uPNGUtils; interface uses System.Classes, Winapi.Windows, Vcl.Graphics, Vcl.Imaging.pngimage, Dmitry.Graphics.Types, uMemory, uBitmapUtils, uICCProfile, ZLib; procedure LoadPNGImageTransparent(PNG: TPNGImage; Bitmap: TBitmap); procedure LoadPNGImageWOTransparent(PNG: TPNGImage; Bitmap: TBitmap); procedure LoadPNGImage32bit(PNG: TPNGImage; Bitmap: TBitmap; BackGroundColor: TColor); procedure LoadPNGImage8BitWOTransparent(PNG: TPNGImage; Bitmap: TBitmap); procedure LoadPNGImage8bitTransparent(PNG: TPNGImage; Bitmap: TBitmap); procedure LoadPNGImagePalette(PNG: TPNGImage; Bitmap: TBitmap); procedure SavePNGImageTransparent(PNG: TPNGImage; Bitmap: TBitmap); procedure AssignPNG(Dest: TBitmap; Src: TPngImage); procedure ApplyPNGIccProfile(PngImage: TPngImage; DisplayProfileName: string); implementation procedure ApplyPNGIccProfile(PngImage: TPngImage; DisplayProfileName: string); var I, J :Integer; MSICC, D: TMemoryStream; DS: TDecompressionStream; PngChunk: TChunk; P: PAnsiChar; begin { 4.2.2.4. iCCP Embedded ICC profile If the iCCP chunk is present, the image samples conform to the color space represented by the embedded ICC profile as defined by the International Color Consortium [ICC]. The color space of the ICC profile must be an RGB color space for color images (PNG color types 2, 3, and 6), or a monochrome grayscale color space for grayscale images (PNG color types 0 and 4). The iCCP chunk contains: Profile name: 1-79 bytes (character string) Null separator: 1 byte Compression method: 1 byte Compressed profile: n bytes The format is like the zTXt chunk. (see the zTXt chunk specification). The profile name can be any convenient name for referring to the profile. It is case-sensitive and subject to the same restrictions as the keyword in a text chunk: it must contain only printable Latin-1 [ISO/IEC-8859-1] characters (33-126 and 161-255) and spaces (32), but no leading, trailing, or consecutive spaces. The only value presently defined for the compression method byte is 0, meaning zlib datastream with deflate compression (see Deflate/Inflate Compression). Decompression of the remainder of the chunk yields the ICC profile. } if not (PngImage.Header.ColorType in [COLOR_RGB, COLOR_RGBALPHA]) then //other types are not supported by little CMS Exit; for I := 0 to PngImage.Chunks.Count - 1 do begin PngChunk := PngImage.Chunks.Item[I]; if (PngChunk.Name = 'iCCP') then begin P := PngChunk.Data; for J := 0 to PngChunk.DataSize - 2 do begin if (P[J] = #0) and (P[J + 1] = #0) then begin D := TMemoryStream.Create; try D.Write(Pointer(NativeInt(PngChunk.Data) + J + 2)^, Integer(PngChunk.DataSize) - J - 3); D.Seek(0, soFromBeginning); DS := TDecompressionStream.Create(D); try MSICC := TMemoryStream.Create; try try MSICC.CopyFrom(DS, DS.Size); ConvertPngToDisplayICCProfile(PngImage, PngImage, MSICC.Memory, MSICC.Size, DisplayProfileName); except //ignore errors -> invalid or unsupported ICC profile Exit; end; finally F(MSICC); end; finally F(DS); end; finally F(D); end; Break; end; end; Break; end; end; end; procedure AssignPNG(Dest: TBitmap; Src: TPngImage); begin case Src.Header.ColorType of COLOR_GRAYSCALE: LoadPNGImage8BitWOTransparent(Src, Dest); COLOR_GRAYSCALEALPHA: LoadPNGImage8BitTransparent(Src, Dest); COLOR_PALETTE: LoadPNGImagePalette(Src, Dest); COLOR_RGB: LoadPNGImageWOTransparent(Src, Dest); COLOR_RGBALPHA: LoadPNGImageTransparent(Src, Dest); else Dest.Assign(Src); end; end; procedure SavePNGImageTransparent(PNG: TPNGImage; Bitmap: TBitmap); var I, J: Integer; DeltaS, DeltaSA, DeltaD: Integer; AddrLineS, AddrLineSA, AddrLineD: NativeInt; AddrS, AddrSA, AddrD: NativeInt; begin PNG.Chunks.Free; PNG.Canvas.Free; PNG.CreateBlank(COLOR_RGBALPHA, 8, Bitmap.Width, Bitmap.Height); AddrLineS := NativeInt(PNG.ScanLine[0]); AddrLineSA := NativeInt(PNG.AlphaScanline[0]); AddrLineD := NativeInt(Bitmap.ScanLine[0]); DeltaS := 0; DeltaSA := 0; DeltaD := 0; if PNG.Height > 1 then begin DeltaS := NativeInt(PNG.ScanLine[1]) - AddrLineS; DeltaSA := NativeInt(PNG.AlphaScanline[1]) - AddrLineSA; DeltaD := NativeInt(Bitmap.ScanLine[1])- AddrLineD; end; for I := 0 to PNG.Height - 1 do begin AddrS := AddrLineS; AddrSA := AddrLineSA; AddrD := AddrLineD; for J := 0 to PNG.Width - 1 do begin PRGB(AddrS)^ := PRGB(AddrD)^; Inc(AddrS, 3); Inc(AddrD, 3); PByte(AddrSA)^ := PByte(AddrD)^; Inc(AddrD, 1); Inc(AddrSA, 1); end; Inc(AddrLineS, DeltaS); Inc(AddrLineSA, DeltaSA); Inc(AddrLineD, DeltaD); end; end; procedure LoadPNGImageTransparent(PNG: TPNGImage; Bitmap: TBitmap); var I, J: Integer; DeltaS, DeltaSA, DeltaD: Integer; AddrLineS, AddrLineSA, AddrLineD: NativeInt; AddrS, AddrSA, AddrD: NativeInt; begin if Bitmap.PixelFormat <> pf32bit then Bitmap.PixelFormat := pf32bit; Bitmap.SetSize(PNG.Width, PNG.Height); AddrLineS := NativeInt(PNG.ScanLine[0]); AddrLineSA := NativeInt(PNG.AlphaScanline[0]); AddrLineD := NativeInt(Bitmap.ScanLine[0]); DeltaS := 0; DeltaSA := 0; DeltaD := 0; if PNG.Height > 1 then begin DeltaS := NativeInt(PNG.ScanLine[1]) - AddrLineS; DeltaSA := NativeInt(PNG.AlphaScanline[1]) - AddrLineSA; DeltaD := NativeInt(Bitmap.ScanLine[1])- AddrLineD; end; for I := 0 to PNG.Height - 1 do begin AddrS := AddrLineS; AddrSA := AddrLineSA; AddrD := AddrLineD; for J := 0 to PNG.Width - 1 do begin PRGB(AddrD)^ := PRGB(AddrS)^; Inc(AddrS, 3); Inc(AddrD, 3); PByte(AddrD)^ := PByte(AddrSA)^; if PByte(AddrD)^ = 0 then //integer is 4 bytes, but 4th byte is transparencity and it't = 0 PInteger(AddrD - 3)^ := 0; Inc(AddrD, 1); Inc(AddrSA, 1); end; Inc(AddrLineS, DeltaS); Inc(AddrLineSA, DeltaSA); Inc(AddrLineD, DeltaD); end; end; procedure LoadPNGImagePalette(PNG: TPNGImage; Bitmap: TBitmap); var I, J: Integer; P: Byte; DeltaS, DeltaD: Integer; AddrLineS, AddrLineD: NativeInt; AddrS, AddrD: NativeInt; Chunk: TChunkPLTE; TRNS: TChunktRNS; BitDepth, BitDepthD8, Rotater, ColorMask: Byte; begin if PNG.Transparent then Bitmap.PixelFormat := pf32bit else Bitmap.PixelFormat := pf24bit; Bitmap.SetSize(PNG.Width, PNG.Height); AddrLineS := NativeInt(PNG.ScanLine[0]); AddrLineD := NativeInt(Bitmap.ScanLine[0]); DeltaS := 0; DeltaD := 0; if PNG.Height > 1 then begin DeltaS := NativeInt(PNG.ScanLine[1]) - AddrLineS; DeltaD := NativeInt(Bitmap.ScanLine[1])- AddrLineD; end; BitDepth := PNG.Header.BitDepth; //1,2,4,8 only, 16 not supported by PNG specification //{2,16 bits for each pixel is not supported by windows bitmap} -> see PNG implementation if BitDepth = 2 then BitDepth := 4; if BitDepth = 16 then BitDepth := 8; BitDepthD8 := 8 - BitDepth; ColorMask := (255 shl BitDepthD8) and 255; Chunk := TChunkPLTE(PNG.Chunks.ItemFromClass(TChunkPLTE)); if not PNG.Transparent then begin for I := 0 to PNG.Height - 1 do begin AddrS := AddrLineS; AddrD := AddrLineD; for J := 0 to PNG.Width - 1 do begin Rotater := J * BitDepth mod 8; P := ((PByte(AddrS + (J * BitDepth) div 8)^ shl Rotater) and ColorMask) shr BitDepthD8; with Chunk.Item[P] do begin PRGB(AddrD)^.R := PNG.GammaTable[rgbRed]; PRGB(AddrD)^.G := PNG.GammaTable[rgbGreen]; PRGB(AddrD)^.B := PNG.GammaTable[rgbBlue]; end; Inc(AddrD, 3); end; Inc(AddrLineS, DeltaS); Inc(AddrLineD, DeltaD); end; end else begin TRNS := PNG.Chunks.ItemFromClass(TChunktRNS) as TChunktRNS; for I := 0 to PNG.Height - 1 do begin AddrS := AddrLineS; AddrD := AddrLineD; for J := 0 to PNG.Width - 1 do begin Rotater := J * BitDepth mod 8; P := ((PByte(AddrS + (J * BitDepth) div 8)^ shl Rotater) and ColorMask) shr BitDepthD8; with Chunk.Item[P] do begin PRGB32(AddrD)^.R := PNG.GammaTable[rgbRed]; PRGB32(AddrD)^.G := PNG.GammaTable[rgbGreen]; PRGB32(AddrD)^.B := PNG.GammaTable[rgbBlue]; PRGB32(AddrD)^.L := TRNS.PaletteValues[P]; end; Inc(AddrD, 4); end; Inc(AddrLineS, DeltaS); Inc(AddrLineD, DeltaD); end; end; end; procedure LoadPNGImage8bitTransparent(PNG: TPNGImage; Bitmap: TBitmap); var I, J: Integer; DeltaS, DeltaSA, DeltaD: Integer; AddrLineS, AddrLineSA, AddrLineD: NativeInt; AddrS, AddrSA, AddrD: NativeInt; begin if Bitmap.PixelFormat <> pf32bit then Bitmap.PixelFormat := pf32bit; Bitmap.SetSize(PNG.Width, PNG.Height); AddrLineS := NativeInt(PNG.ScanLine[0]); AddrLineSA := NativeInt(PNG.AlphaScanline[0]); AddrLineD := NativeInt(Bitmap.ScanLine[0]); DeltaS := 0; DeltaSA := 0; DeltaD := 0; if PNG.Height > 1 then begin DeltaS := NativeInt(PNG.ScanLine[1]) - AddrLineS; DeltaSA := NativeInt(PNG.AlphaScanline[1]) - AddrLineSA; DeltaD := NativeInt(Bitmap.ScanLine[1])- AddrLineD; end; for I := 0 to PNG.Height - 1 do begin AddrS := AddrLineS; AddrSA := AddrLineSA; AddrD := AddrLineD; for J := 0 to PNG.Width - 1 do begin PRGB(AddrD)^.R := PByte(AddrS)^; PRGB(AddrD)^.G := PByte(AddrS)^; PRGB(AddrD)^.B := PByte(AddrS)^; Inc(AddrS, 1); Inc(AddrD, 3); PByte(AddrD)^ := PByte(AddrSA)^; Inc(AddrD, 1); Inc(AddrSA, 1); end; Inc(AddrLineS, DeltaS); Inc(AddrLineSA, DeltaSA); Inc(AddrLineD, DeltaD); end; end; procedure LoadPNGImage8BitWOTransparent(PNG: TPNGImage; Bitmap: TBitmap); var I, J: Integer; DeltaS, DeltaD: Integer; AddrLineS, AddrLineD: NativeInt; AddrS, AddrD: NativeInt; BitDepth, BitDepthD8, ColorMask, P, Rotater, Multilpyer: Byte; begin if Bitmap.PixelFormat <> pf24bit then Bitmap.PixelFormat := pf24bit; Bitmap.SetSize(PNG.Width, PNG.Height); AddrLineS := NativeInt(PNG.ScanLine[0]); AddrLineD := NativeInt(Bitmap.ScanLine[0]); DeltaS := 0; DeltaD := 0; if PNG.Height > 1 then begin DeltaS := NativeInt(PNG.ScanLine[1]) - AddrLineS; DeltaD := NativeInt(Bitmap.ScanLine[1])- AddrLineD; end; BitDepth := PNG.Header.BitDepth; //1,2,4,8 only, 16 not supported by PNG specification //{2,16 bits for each pixel is not supported by windows bitmap} -> see PNG implementation if BitDepth = 2 then BitDepth := 4; if BitDepth = 16 then BitDepth := 8; BitDepthD8 := 8 - BitDepth; ColorMask := (255 shl BitDepthD8) and 255; Multilpyer := 1; case BitDepth of 1: Multilpyer := 255; 2: Multilpyer := 85; 4: Multilpyer := 17; 8: Multilpyer := 1; end; for I := 0 to PNG.Height - 1 do begin AddrS := AddrLineS; AddrD := AddrLineD; for J := 0 to PNG.Width - 1 do begin Rotater := J * BitDepth mod 8; P := ((PByte(AddrS + (J * BitDepth) div 8)^ shl Rotater) and ColorMask) shr BitDepthD8; PRGB(AddrD)^.R := P * Multilpyer; PRGB(AddrD)^.G := P * Multilpyer; PRGB(AddrD)^.B := P * Multilpyer; Inc(AddrD, 3); end; Inc(AddrLineS, DeltaS); Inc(AddrLineD, DeltaD); end; end; procedure LoadPNGImageWOTransparent(PNG: TPNGImage; Bitmap: TBitmap); var I, J: Integer; DeltaS, DeltaD: Integer; AddrLineS, AddrLineD: NativeInt; AddrS, AddrD: NativeInt; begin if Bitmap.PixelFormat <> pf24bit then Bitmap.PixelFormat := pf24bit; Bitmap.SetSize(PNG.Width, PNG.Height); AddrLineS := NativeInt(PNG.ScanLine[0]); AddrLineD := NativeInt(Bitmap.ScanLine[0]); DeltaS := 0; DeltaD := 0; if PNG.Height > 1 then begin DeltaS := NativeInt(PNG.ScanLine[1]) - AddrLineS; DeltaD := NativeInt(Bitmap.ScanLine[1])- AddrLineD; end; for I := 0 to PNG.Height - 1 do begin AddrS := AddrLineS; AddrD := AddrLineD; for J := 0 to PNG.Width - 1 do begin PRGB(AddrD)^ := PRGB(AddrS)^; Inc(AddrS, 3); Inc(AddrD, 3); end; Inc(AddrLineS, DeltaS); Inc(AddrLineD, DeltaD); end; end; procedure LoadPNGImage32bit(PNG: TPNGImage; Bitmap: TBitmap; BackGroundColor: TColor); var I, J: Integer; DeltaS, DeltaSA, DeltaD: Integer; AddrLineS, AddrLineD, AddrLineSA: NativeInt; AddrS, AddrD, AddrSA: NativeInt; R, G, B: Integer; W1, W2: Integer; S, D: PRGB; BPNG: TBitmap; begin //only ARBG is supported //for other formats -> use transform: PNG -> BMP -> Extract BMP24 case TPngImage(PNG).Header.ColorType of COLOR_GRAYSCALE, COLOR_GRAYSCALEALPHA, COLOR_PALETTE, COLOR_RGB: begin BPNG := TBitmap.Create; try AssignPNG(BPNG, PNG); LoadBMPImage32bit(BPNG, Bitmap, BackGroundColor); finally F(BPNG); end; Exit; end; end; BackGroundColor := ColorToRGB(BackGroundColor); R := GetRValue(BackGroundColor); G := GetGValue(BackGroundColor); B := GetBValue(BackGroundColor); if Bitmap.PixelFormat <> pf24bit then Bitmap.PixelFormat := pf24bit; Bitmap.SetSize(PNG.Width, PNG.Height); AddrLineS := NativeInt(PNG.ScanLine[0]); AddrLineSA := NativeInt(PNG.AlphaScanline[0]); AddrLineD := NativeInt(Bitmap.ScanLine[0]); DeltaS := 0; DeltaSA := 0; DeltaD := 0; if PNG.Height > 1 then begin DeltaS := NativeInt(PNG.ScanLine[1]) - AddrLineS; DeltaSA := NativeInt(PNG.AlphaScanline[1]) - AddrLineSA; DeltaD := NativeInt(Bitmap.ScanLine[1])- AddrLineD; end; for I := 0 to PNG.Height - 1 do begin AddrS := AddrLineS; AddrSA := AddrLineSA; AddrD := AddrLineD; for J := 0 to PNG.Width - 1 do begin S := PRGB(AddrS); D := PRGB(AddrD); W1 := PByte(AddrSA)^; W2 := 255 - W1; D.R := (R * W2 + S.R * W1 + $7F) div $FF; D.G := (G * W2 + S.G * W1 + $7F) div $FF; D.B := (B * W2 + S.B * W1 + $7F) div $FF; Inc(AddrS, 3); Inc(AddrSA, 1); Inc(AddrD, 3); end; Inc(AddrLineS, DeltaS); Inc(AddrLineSA, DeltaSA); Inc(AddrLineD, DeltaD); end; end; end.
unit LazyMainFrm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, LazyInitLib, Vcl.StdCtrls; type TForm30 = class(TForm) Button1: TButton; Label1: TLabel; Button2: TButton; Memo1: TMemo; Button3: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private-Deklarationen } MeinIntWert: ILazyInit<Integer>; fStrValue: ILazyInit<String>; group: ILazyGroup; value1: ILazyInit<String>; value2: ILazyInit<String>; public { Public-Deklarationen } end; var Form30: TForm30; implementation {$R *.dfm} procedure TForm30.Button1Click(Sender: TObject); begin Label1.Caption := IntToStr(MeinIntWert.Value); end; procedure TForm30.Button2Click(Sender: TObject); begin Memo1.Lines.Add('START'); group := LazyFactory.NewGroup; value1 := TLazyInit<String>.Create( function: String begin Memo1.Lines.Add('Init Value 1'); Result := 'ABC'; end, group); value2 := TLazyInit<String>.Create( function: String begin Memo1.Lines.Add('Init Value 2'); Result := 'DEF'; end, group); Memo1.Lines.Add('Set Label Caption'); Label1.Caption := value1.Value; Memo1.Lines.Add('Did Set Label Caption'); Memo1.Lines.Add('Set Button Caption'); Button2.Caption := value2.Value; Memo1.Lines.Add('Did Set Button Caption'); Memo1.Lines.Add('FINISH'); end; procedure TForm30.Button3Click(Sender: TObject); begin Label1.Caption := fStrValue.Value; end; procedure TForm30.FormCreate(Sender: TObject); begin MeinIntWert := TLazyInit<Integer>.Create( function: Integer begin Result := 4711; end); fStrValue := TLazyInitAsync<String>.Create( function: String begin Sleep(1500); Result := 'ABCEDF'; end); end; end.
unit pasjansql; {$IFDEF FPC} {$MODE Delphi} {$H+} {$ELSE} {$IFNDEF LINUX} {$DEFINE WIN32} {$ELSE} {$DEFINE UNIX} {$ENDIF} {$ENDIF} //JanSQL interface for libsql //2005 R.M. Tegel //Modified Artistic License // //For interfacing wit janSQL library by Jan Verhoeven 2002 //janSQL is a high-speed flat-file typeless sql engine released under Mozilla 1.1 license //little modified by me. interface uses {$IFDEF WIN32} Windows, {$ENDIF} Classes, SysUtils, {$IFNDEF FPC} janSQL, {$ENDIF} passql, sqlsupport; type TJanDB = class (TSQLDB) private FClientVersion: String; protected FDataDir: String; FAutoCommit: Boolean; FHostInfo:String; FInfo:String; FConnected: Boolean; FJanSQL: TJanSQL; procedure StoreResult(recordsetindex: Integer); function GetErrorMsg (Handle: Integer): String; procedure FillDBInfo; override; //Dak_Alpha function MapDatatype (_datatype: Integer): TSQLDataTypes; procedure StoreFields (recordsetindex: Integer); procedure StoreRow (recordsetindex: Integer; rowIndex: Integer; row: TResultRow); function FindRecordSet(Handle: Integer): Integer; public constructor Create (AOwner:TComponent); overload; override; constructor Create (AOwner:TComponent; DataBaseDirectory: String); overload; destructor Destroy; override; function Query (SQL:String):Boolean; override; function Connect (Host, User, Pass:String; DataBase:String=''):Boolean; override; function Use (Database:String):Boolean; override; procedure Close; override; function ExplainTable (Table:String): Boolean; override; function ShowCreateTable (Table:String): Boolean; override; function DumpTable (Table:String): Boolean; override; function DumpDatabase (Table:String): Boolean; override; function ShowTables: Boolean; override; procedure StartTransaction; override; procedure Commit; override; procedure Rollback; override; function Execute (SQL: String): THandle; override; function FetchRow (Handle: THandle; var row: TResultRow): Boolean; override; procedure FreeResult (Handle: THandle); override; //hide some properties property DllLoaded:Boolean read FDLLLoaded; property LibraryPath: String read FLibraryPath; published property ClientVersion: String read FClientVersion write FDummyString; end; implementation { TJanDB } procedure TJanDB.Close; var i: Integer; begin inherited; //not really a solution: // Use (''); for i := 1 to FJanSQL.RecordSetCount do //Dak_Alpha FJanSQL.ReleaseRecordset(i); //Dak_Alpha if Assigned(FOnClose) then FOnClose(Self); //Dak_Alpha FActive := False; //Dak_Alpha end; procedure TJanDB.Commit; begin inherited; FJanSQL.SQLDirect('COMMIT'); FAutoCommit := True; end; function TJanDB.Connect(Host, User, Pass:String; DataBase: String): Boolean; var i: Integer; begin i := FJanSQL.SQLDirect(Format('connect to ''%s''', [DataBase])); Result := i<>0; if Result then begin if DataBase[Length(DataBase)] in ['\','/'] then //Dak_Alpha FDataDir := DataBase else //Dak_Alpha if Pos('/',DataBase)>0 then //Dak_Alpha FDataDir := DataBase + '/' //Dak_Alpha else //Dak_Alpha FDataDir := DataBase + '\'; //Dak_Alpha FDatabase := Database; end; FActive := Result; if FActive then //Dak_Alpha begin //Dak_Alpha FillDBInfo; //Dak_Alpha if Assigned(FOnOpen) then FOnOpen(Self); //Dak_Alpha end; //Dak_Alpha end; constructor TJanDB.Create(AOwner: TComponent; DataBaseDirectory: String); begin inherited Create(AOwner); //our engine: FJanSQL := TJanSQL.Create; //default to autocommit. FAutoCommit := True; if DataBaseDirectory <> '' then Use (DatabaseDirectory); end; constructor TJanDB.Create(AOwner: TComponent); begin Create (AOwner, ''); end; destructor TJanDB.Destroy; begin if FActive then Close; //Dak_Alpha FJanSQL.Destroy; inherited; end; function TJanDB.DumpDatabase(Table: String): Boolean; begin //not implemented end; function TJanDB.DumpTable(Table: String): Boolean; begin Result := FormatQuery ('delete from %u', [Table]); end; function TJanDB.Execute(SQL: String): THandle; var i: Integer; begin Result := 0; if not FActive then exit; i := FJanSQL.SQLDirect(SQL); if i = 0 then //Dak_Alpha begin //Dak_Alpha FCurrentSet.FLastErrorText := FJanSQL.Error; //Dak_Alpha FCurrentSet.FLastError := -1; //Dak_Alpha end //Dak_Alpha else begin FCurrentSet.FLastErrorText := ''; //Dak_Alpha FCurrentSet.FLastError := 0; //Dak_Alpha if i > 0 then begin Result := Integer(FJanSQL.RecordSets[i]); UseResultSet (Result); FJanSQL.RecordSets[i].Cursor := 0; StoreFields (i); end; end; end; function TJanDB.ExplainTable(Table: String): Boolean; begin //not implemented end; function TJanDB.FetchRow(Handle: THandle; var row: TResultRow): Boolean; var i: Integer; jrs: TJanRecordSet; begin Result := False; if Handle=0 then exit; UseResultSet (Handle); row := FCurrentSet.FCurrentRow; row.Clear; i := FindRecordSet (Handle); if i=0 then exit; jrs := FJanSQL.RecordSets [i]; if not Assigned (jrs) then exit; if jrs.Cursor < jrs.recordcount then begin Result := True; StoreRow (i, jrs.Cursor, row); jrs.Cursor := jrs.Cursor + 1; end else begin row := FCurrentSet.FNilRow; Result := False; end; end; procedure TJanDB.FillDBInfo; var sr: TSearchRec; FileAttrs: Integer; begin inherited; //clears tables and indexes FileAttrs := 0; if FindFirst(FDataDir+'*.txt', FileAttrs, sr) = 0 then begin repeat Tables.Add(ChangeFileExt(sr.Name,'')); until FindNext(sr) <> 0; SysUtils.FindClose(sr); end; end; function TJanDB.FindRecordSet(Handle: Integer): Integer; var i: Integer; begin Result := 0; //finds corresponding recordset by our unique handle: for i := 1 to FJanSQL.RecordSetCount do if FJanSQL.RecordSets [i] = Pointer(Handle) then begin Result := i; break; end; end; procedure TJanDB.FreeResult(Handle: THandle); begin inherited; FJanSQL.ReleaseRecordset(FindRecordSet(Handle)); end; function TJanDB.GetErrorMsg(Handle: Integer): String; begin //note that index is ignored (!) Result := FJanSQL.Error; end; function TJanDB.MapDatatype(_datatype: Integer): TSQLDataTypes; begin Result := dtString; end; function TJanDB.Query(SQL: String): Boolean; var h: Integer; begin Result := False; if not FActive then exit; //janSQL has some bugs, therefore this exception catcher: try h := FJanSQL.SQLDirect(SQL); except on E: Exception do FCurrentSet.FLastErrorText := 'Exception in database parser: '+E.Message; end; if h = 0 then //Dak_Alpha begin //Dak_Alpha FCurrentSet.FLastErrorText := FJanSQL.Error; //Dak_Alpha FCurrentSet.FLastError := -1; //Dak_Alpha if Assigned (FOnError) then //Dak_Alpha try //Dak_Alpha FOnError(Self); //Dak_Alpha except end; //Dak_Alpha exit; //Dak_Alpha end //Dak_Alpha else //Dak_Alpha begin //Dak_Alpha FCurrentSet.FLastErrorText := ''; //Dak_Alpha FCurrentSet.FLastError := 0; //Dak_Alpha end; //Dak_Alpha if (h>0) then begin StoreResult (h); FJanSQL.ReleaseRecordset(h); end; if (h<>0) then begin if Assigned (FOnSuccess) then //Dak_Alpha try //Dak_Alpha FOnSuccess(Self); //Dak_Alpha except end; //Dak_Alpha if Assigned (FOnQueryComplete) then //Dak_Alpha try //Dak_Alpha FOnQueryComplete(Self); //Dak_Alpha except end; //Dak_Alpha if FAutoCommit then FJanSQL.SQLDirect('COMMIT'); end; Result := True; //Dak_Alpha end; procedure TJanDB.Rollback; begin FJanSQL.SQLDirect('rollback'); FAutoCommit := True; end; function TJanDB.ShowCreateTable(Table: String): Boolean; begin //nothing to do. end; function TJanDB.ShowTables: Boolean; begin //nothing to do. end; procedure TJanDB.StartTransaction; begin FAutoCommit := False; end; procedure TJanDB.StoreFields(recordsetindex: Integer); var Columns, i,j : Integer; jrs: TjanRecordSet; begin jrs := FJanSQL.RecordSets [recordsetindex]; if not Assigned(jrs) then exit; Columns := jrs.fieldcount; for i := 0 to Columns - 1 do begin j:=FCurrentSet.FFields.AddObject(jrs.FieldNames[i], TFieldDesc.Create); with TFieldDesc (FCurrentSet.FFields.Objects [j]) do begin name := jrs.FieldNames[i]; _datatype := 0; datatype := dtUnknown; //we could say string or whatever //but the engine is typeless. end; end; end; procedure TJanDB.StoreResult(recordsetindex: Integer); var i,res,odbcrow: Integer; NumCols: SmallInt; row: TResultRow; jrs: TjanRecordSet; cursor: Integer; begin CurrentResult.Clear; jrs := FJanSQL.RecordSets [recordsetindex]; if not Assigned(jrs) then if Assigned (FOnError) then begin try FOnError (Self); except end; exit; end; //fill fields info FCurrentSet.FColCount := jrs.fieldcount; FCurrentSet.FRowCount := jrs.recordcount; // FCurrentSet.FHasResult := False; //Dak_Alpha FCurrentSet.FHasResult := FCurrentSet.FColCount>0; //Dak_Alpha StoreFields (recordsetindex); for cursor := 0 to jrs.recordcount - 1 do begin FCurrentSet.FHasResult := True; if FCallBackOnly then i:=1 else i:=FCurrentSet.FRowCount; if cursor<FCurrentSet.FRowList.Count then begin row := TResultRow(FCurrentSet.FRowList[cursor]); row.Clear; row.FNulls.Clear; end else begin row := TResultRow.Create; row.FFields := FCurrentSet.FFields; //copy pointer to ffields array FCurrentSet.FRowList.Add(row); end; StoreRow (recordsetindex, cursor, row); if Assigned (FOnFetchRow) then try FOnFetchRow (Self, row); except end; end; // if Assigned (FOnSuccess) then //Dak_Alpha // try //Dak_Alpha // FOnSuccess(Self); //Dak_Alpha // except end; //Dak_Alpha // if Assigned (FOnQueryComplete) then //Dak_Alpha // try //Dak_Alpha // FOnQueryComplete(Self); //Dak_Alpha // except end; //Dak_Alpha end; procedure TJanDB.StoreRow(recordsetindex: Integer; RowIndex: Integer; row: TResultRow); var Value: String; //^PChar; i:Integer; ColCount: Integer; begin ColCount := FJanSQL.RecordSets[recordsetindex].fieldcount; if ColCount > 0 then begin for i := 0 to ColCount - 1 do begin //todo: keep //FJanSQL.RecordSets[0].Cursor; // Value := FJanSQL.RecordSets[recordsetindex].records[RowIndex].fields[i].value; if Value='' then row.FNulls.Add(Pointer(1)) else row.FNulls.Add(Pointer(0)); row.Add (Value); //inc (QS, length(Value)); end; end; end; function TJanDB.Use(Database: String): Boolean; begin Result := Connect ('','','',Database); end; end.
unit DinputGS ; interface uses OLE2,Windows, util1,Gdos; (*==========================================================================; * * DirectX 6 Delphi adaptation by Gérard Sadoc * *==========================================================================;*) const DIRECTINPUT_VERSION = $0500; {$Z4} {$A+} (* * GUIDS used by DirectInput objects *) CLSID_DirectInput: TGUID = ( D1:$25E609E0;D2:$B259;D3:$11CF;D4:($BF,$C7,$44,$45,$53,$54,$00,$00)); CLSID_DirectInputDevice: TGUID = ( D1:$25E609E1;D2:$B259;D3:$11CF;D4:($BF,$C7,$44,$45,$53,$54,$00,$00)); (**************************************************************************** * * Interfaces * ****************************************************************************) IID_IDirectInput:TGUID = ( D1: $89521360; D2:$AA8A; d3:$11CF; D4:($BF,$C7,$44,$45,$53,$54,$00,$00)); IID_IDirectInput2: TGUID = ( D1: $5944E662; D2:$AA8A; D3:$11CF; D4:($BF,$C7,$44,$45,$53,$54,$00,$00)); IID_IDirectInputDevice: TGUID = ( D1: $5944E680; D2:$C92E; D3:$11CF; D4:($BF,$C7,$44,$45,$53,$54,$00,$00)); IID_IDirectInputDevice2:TGUID = ( D1: $5944E682; D2:$C92E; D3:$11CF; D4:($BF,$C7,$44,$45,$53,$54,$00,$00)); IID_IDirectInputEffect: TGUID = ( D1: $E7E1F7C0; D2:$88D2; D3:$11D0; D4:($9A,$D0,$00,$A0,$C9,$A0,$6E,$35)); (**************************************************************************** * * Predefined object types * ****************************************************************************) GUID_XAxis: TGUID = ( D1: $A36D02E0; D2:$C9F3; D3:$11CF; D4:($BF,$C7,$44,$45,$53,$54,$00,$00)); GUID_YAxis: TGUID = ( D1: $A36D02E1; D2:$C9F3; D3:$11CF; D4:($BF,$C7,$44,$45,$53,$54,$00,$00)); GUID_ZAxis: TGUID = ( D1: $A36D02E2; D2:$C9F3; D3:$11CF; D4:($BF,$C7,$44,$45,$53,$54,$00,$00)); GUID_RxAxis: TGUID = ( D1: $A36D02F4; D2:$C9F3; D3:$11CF; D4:($BF,$C7,$44,$45,$53,$54,$00,$00)); GUID_RyAxis: TGUID = ( D1: $A36D02F5; D2:$C9F3; D3:$11CF; D4:($BF,$C7,$44,$45,$53,$54,$00,$00)); GUID_RzAxis: TGUID = ( D1: $A36D02E3; D2:$C9F3; D3:$11CF; D4:($BF,$C7,$44,$45,$53,$54,$00,$00)); GUID_Slider: TGUID = ( D1: $A36D02E4; D2:$C9F3; D3:$11CF; D4:($BF,$C7,$44,$45,$53,$54,$00,$00)); GUID_Button: TGUID = ( D1: $A36D02F0; D2:$C9F3; D3:$11CF; D4:($BF,$C7,$44,$45,$53,$54,$00,$00)); GUID_Key: TGUID = ( D1: $55728220; D2:$D33C; D3:$11CF; D4:($BF,$C7,$44,$45,$53,$54,$00,$00)); GUID_POV: TGUID = ( D1: $A36D02F2; D2:$C9F3; D3:$11CF; D4:($BF,$C7,$44,$45,$53,$54,$00,$00)); GUID_Unknown: TGUID = ( D1: $A36D02F3; D2:$C9F3; D3:$11CF; D4:($BF,$C7,$44,$45,$53,$54,$00,$00)); (**************************************************************************** * * Predefined product GUIDs * ****************************************************************************) GUID_SysMouse: TGUID = ( D1: $6F1D2B60; D2:$D5A0; D3:$11CF; D4:($BF,$C7,$44,$45,$53,$54,$00,$00)); GUID_SysKeyboard:TGUID = ( D1: $6F1D2B61; D2:$D5A0; D3:$11CF; D4:($BF,$C7,$44,$45,$53,$54,$00,$00)); GUID_Joystick:TGUID = ( D1: $6F1D2B70; D2:$D5A0; D3:$11CF; D4:($BF,$C7,$44,$45,$53,$54,$00,$00)); (**************************************************************************** * * Predefined force feedback effects * ****************************************************************************) GUID_ConstantForce:TGUID = ( D1: $13541C20; D2:$8E33; D3:$11D0; D4:($9A,$D0,$00,$A0,$C9,$A0,$6E,$35)); GUID_RampForce: TGUID = ( D1: $13541C21; D2:$8E33; D3:$11D0; D4:($9A,$D0,$00,$A0,$C9,$A0,$6E,$35)); GUID_Square: TGUID = ( D1: $13541C22; D2:$8E33; D3:$11D0; D4:($9A,$D0,$00,$A0,$C9,$A0,$6E,$35)); GUID_Sine: TGUID = ( D1: $13541C23; D2:$8E33; D3:$11D0; D4:($9A,$D0,$00,$A0,$C9,$A0,$6E,$35)); GUID_Triangle: TGUID = ( D1: $13541C24; D2:$8E33; D3:$11D0; D4:($9A,$D0,$00,$A0,$C9,$A0,$6E,$35)); GUID_SawtoothUp: TGUID = ( D1: $13541C25; D2:$8E33; D3:$11D0; D4:($9A,$D0,$00,$A0,$C9,$A0,$6E,$35)); GUID_SawtoothDown: TGUID = ( D1: $13541C26; D2:$8E33; D3:$11D0; D4:($9A,$D0,$00,$A0,$C9,$A0,$6E,$35)); GUID_Spring: TGUID = ( D1: $13541C27; D2:$8E33; D3:$11D0; D4:($9A,$D0,$00,$A0,$C9,$A0,$6E,$35)); GUID_Damper: TGUID = ( D1: $13541C28; D2:$8E33; D3:$11D0; D4:($9A,$D0,$00,$A0,$C9,$A0,$6E,$35)); GUID_Inertia: TGUID = ( D1: $13541C29; D2:$8E33; D3:$11D0; D4:($9A,$D0,$00,$A0,$C9,$A0,$6E,$35)); GUID_Friction: TGUID = ( D1: $13541C2A; D2:$8E33; D3:$11D0; D4:($9A,$D0,$00,$A0,$C9,$A0,$6E,$35)); GUID_CustomForce: TGUID = ( D1: $13541C2B; D2:$8E33; D3:$11D0; D4:($9A,$D0,$00,$A0,$C9,$A0,$6E,$35)); (**************************************************************************** * * Interfaces and Structures... * ****************************************************************************) (**************************************************************************** * * IDirectInputEffect * ****************************************************************************) DIEFT_ALL = $00000000; DIEFT_CONSTANTFORCE = $00000001; DIEFT_RAMPFORCE = $00000002; DIEFT_PERIODIC = $00000003; DIEFT_CONDITION = $00000004; DIEFT_CUSTOMFORCE = $00000005; DIEFT_HARDWARE = $000000FF; DIEFT_FFATTACK = $00000200; DIEFT_FFFADE = $00000400; DIEFT_SATURATION = $00000800; DIEFT_POSNEGCOEFFICIENTS = $00001000; DIEFT_POSNEGSATURATION = $00002000; DIEFT_DEADBAND = $00004000; {DIEFT_GETTYPE(n) = LOBYTE(n);} DI_DEGREES = 100; DI_FFNOMINALMAX = 10000; DI_SECONDS = 1000000; type TDICONSTANTFORCE= record lMagnitude:longint; end; PDICONSTANTFORCE=^TDICONSTANTFORCE; PCDICONSTANTFORCE=^TDICONSTANTFORCE; TDIRAMPFORCE=record lStart:longint; lEnd:longint; end; PDIRAMPFORCE=^TDIRAMPFORCE; PCDIRAMPFORCE=^TDIRAMPFORCE; TDIPERIODIC= record dwMagnitude:longint; lOffset:longint; dwPhase:longint; dwPeriod:longint; end; PDIPERIODIC=^TDIPERIODIC; PCDIPERIODIC=^TDIPERIODIC; TDICONDITION = record lOffset:longint; lPositiveCoefficient:longint; lNegativeCoefficient:longint; dwPositiveSaturation:longint; dwNegativeSaturation:longint; lDeadBand:longint; end; PDICONDITION=^TDICONDITION; PCDICONDITION=^TDICONDITION; TDICUSTOMFORCE= record cChannels:longint; dwSamplePeriod:longint; cSamples:longint; rglForceData:Pinteger; end; PDICUSTOMFORCE =^TDICUSTOMFORCE; PCDICUSTOMFORCE =^TDICUSTOMFORCE; TDIENVELOPE= record dwSize:longint; (* sizeof(DIENVELOPE) *) dwAttackLevel:longint; dwAttackTime:longint; (* Microseconds *) dwFadeLevel:longint; dwFadeTime:longint; (* Microseconds *) end; PDIENVELOPE=^TDIENVELOPE; PCDIENVELOPE=^TDIENVELOPE; TDIEFFECT= record dwSize:longint; (* sizeof(DIEFFECT) *) dwFlags:longint; (* DIEFF_* *) dwDuration:longint; (* Microseconds *) dwSamplePeriod:longint; (* Microseconds *) dwGain:longint; dwTriggerButton:longint; (* or DIEB_NOTRIGGER *) dwTriggerRepeatInterval:longint; (* Microseconds *) cAxes:longint; (* Number of axes *) rgdwAxes:^longint; (* Array of axes *) rglDirection:^longint; (* Array of directions *) lpEnvelope:PDIENVELOPE; (* Optional *) cbTypeSpecificParams:longint; (* Size of params *) lpvTypeSpecificParams:pointer; (* Pointer to params *) end; PDIEFFECT=^TDIEFFECT; PCDIEFFECT=^TDIEFFECT; const DIEFF_OBJECTIDS = $00000001; DIEFF_OBJECTOFFSETS = $00000002; DIEFF_CARTESIAN = $00000010; DIEFF_POLAR = $00000020; DIEFF_SPHERICAL = $00000040; DIEP_DURATION = $00000001; DIEP_SAMPLEPERIOD = $00000002; DIEP_GAIN = $00000004; DIEP_TRIGGERBUTTON = $00000008; DIEP_TRIGGERREPEATINTERVAL = $00000010; DIEP_AXES = $00000020; DIEP_DIRECTION = $00000040; DIEP_ENVELOPE = $00000080; DIEP_TYPESPECIFICPARAMS = $00000100; DIEP_ALLPARAMS = $000001FF; DIEP_START = $20000000; DIEP_NORESTART = $40000000; DIEP_NODOWNLOAD = $80000000; DIEB_NOTRIGGER = $FFFFFFFF; DIES_SOLO = $00000001; DIES_NODOWNLOAD = $80000000; DIEGES_PLAYING = $00000001; DIEGES_EMULATED = $00000002; type TDIEFFESCAPE= record dwSize:longint; dwCommand:longint; lpvInBuffer:pointer; cbInBuffer:longint; lpvOutBuffer:pointer; cbOutBuffer:longint; end; PDIEFFESCAPE=^TDIEFFESCAPE; IDirectInputEffect=class(IUnknown) (*** IDirectInputEffect methods ***) function Initialize(HINSTANCE:longint;dwVersion:DWORD;guid:TGUID):hresult; virtual ; stdcall ; abstract ; function GetEffectGuid(guid:PGUID):hresult; virtual ; stdcall ; abstract ; function GetParameters(peff:PDIEFFECT;dwFlags:DWORD):hresult; virtual ; stdcall ; abstract ; function SetParameters(peff:PCDIEFFECT;dwFlags:DWORD):hresult; virtual ; stdcall ; abstract ; function Start(dwIterations,dwFlags:DWORD) :hresult; virtual ; stdcall ; abstract ; function Stop :hresult; virtual ; stdcall ; abstract ; function GetEffectStatus(pdwFlags:PDWORD) :hresult; virtual ; stdcall ; abstract ; function Download :hresult; virtual ; stdcall ; abstract ; function Unload :hresult; virtual ; stdcall ; abstract ; function Escape(effEscape:PDIEFFESCAPE) :hresult; virtual ; stdcall ; abstract ; end; (**************************************************************************** * * IDirectInputDevice * ****************************************************************************) const DIDEVTYPE_DEVICE =1; DIDEVTYPE_MOUSE =2; DIDEVTYPE_KEYBOARD =3; DIDEVTYPE_JOYSTICK =4; DIDEVTYPE_HID =$00010000; DIDEVTYPEMOUSE_UNKNOWN =1; DIDEVTYPEMOUSE_TRADITIONAL =2; DIDEVTYPEMOUSE_FINGERSTICK =3; DIDEVTYPEMOUSE_TOUCHPAD =4; DIDEVTYPEMOUSE_TRACKBALL =5; DIDEVTYPEKEYBOARD_UNKNOWN =0; DIDEVTYPEKEYBOARD_PCXT =1; DIDEVTYPEKEYBOARD_OLIVETTI =2; DIDEVTYPEKEYBOARD_PCAT =3; DIDEVTYPEKEYBOARD_PCENH =4; DIDEVTYPEKEYBOARD_NOKIA1050 =5; DIDEVTYPEKEYBOARD_NOKIA9140 =6; DIDEVTYPEKEYBOARD_NEC98 =7; DIDEVTYPEKEYBOARD_NEC98LAPTOP =8; DIDEVTYPEKEYBOARD_NEC98106 =9; DIDEVTYPEKEYBOARD_JAPAN106 =10; DIDEVTYPEKEYBOARD_JAPANAX =11; DIDEVTYPEKEYBOARD_J3100 =12; DIDEVTYPEJOYSTICK_UNKNOWN =1; DIDEVTYPEJOYSTICK_TRADITIONAL =2; DIDEVTYPEJOYSTICK_FLIGHTSTICK =3; DIDEVTYPEJOYSTICK_GAMEPAD =4; DIDEVTYPEJOYSTICK_RUDDER =5; DIDEVTYPEJOYSTICK_WHEEL =6; DIDEVTYPEJOYSTICK_HEADTRACKER =7; { GET_DIDEVICE_TYPE(dwDevType) LOBYTE(dwDevType) GET_DIDEVICE_SUBTYPE(dwDevType) HIBYTE(dwDevType) } type TDIDEVCAPS_DX3 = record dwSize:Dword; dwFlags:Dword; dwDevType:Dword; dwAxes:Dword; dwButtons:Dword; dwPOVs:Dword; end; PDIDEVCAPS_DX3=^TDIDEVCAPS_DX3; TDIDEVCAPS = record dwSize:Dword; dwFlags:Dword; dwDevType:Dword; dwAxes:Dword; dwButtons:Dword; dwPOVs:Dword; dwFFSamplePeriod:Dword; dwFFMinTimeResolution:Dword; dwFirmwareRevision:Dword; dwHardwareRevision:Dword; dwFFDriverVersion:Dword; end; PDIDEVCAPS=^TDIDEVCAPS; const DIDC_ATTACHED =$00000001; DIDC_POLLEDDEVICE =$00000002; DIDC_EMULATED =$00000004; DIDC_POLLEDDATAFORMAT =$00000008; DIDC_FORCEFEEDBACK =$00000100; DIDC_FFATTACK =$00000200; DIDC_FFFADE =$00000400; DIDC_SATURATION =$00000800; DIDC_POSNEGCOEFFICIENTS =$00001000; DIDC_POSNEGSATURATION =$00002000; DIDC_DEADBAND =$00004000; DIDFT_ALL =$00000000; DIDFT_RELAXIS =$00000001; DIDFT_ABSAXIS =$00000002; DIDFT_AXIS =$00000003; DIDFT_PSHBUTTON =$00000004; DIDFT_TGLBUTTON =$00000008; DIDFT_BUTTON =$0000000C; DIDFT_POV =$00000010; DIDFT_COLLECTION =$00000040; DIDFT_NODATA =$00000080; DIDFT_ANYINSTANCE =$00FFFF00; DIDFT_INSTANCEMASK =DIDFT_ANYINSTANCE; { DIDFT_MAKEINSTANCE(n) ((WORD)(n) << 8) DIDFT_GETTYPE(n) LOBYTE(n) DIDFT_GETINSTANCE(n) LOWORD((n) >> 8) } DIDFT_FFACTUATOR =$01000000; DIDFT_FFEFFECTTRIGGER =$02000000; {DIDFT_ENUMCOLLECTION(n) ((WORD)(n) << 8)} DIDFT_NOCOLLECTION =$00FFFF00; type TDIOBJECTDATAFORMAT = record GUID: pguid; dwOfs:Dword; dwType:Dword; dwFlags:Dword; end; PDIOBJECTDATAFORMAT=^TDIOBJECTDATAFORMAT; PCDIOBJECTDATAFORMAT=^TDIOBJECTDATAFORMAT; TDIDATAFORMAT = record dwSize:Dword; dwObjSize:Dword; dwFlags:Dword; dwDataSize:Dword; dwNumObjs:Dword; rgodf:PDIOBJECTDATAFORMAT ; end; PDIDATAFORMAT=^TDIDATAFORMAT; PCDIDATAFORMAT=^TDIDATAFORMAT; const DIDF_ABSAXIS =$00000001; DIDF_RELAXIS =$00000002; var c_dfDIMouse: TDIDATAFORMAT ; c_dfDIKeyboard: TDIDATAFORMAT ; c_dfDIJoystick: TDIDATAFORMAT ; c_dfDIJoystick2: TDIDATAFORMAT ; (* These structures are defined for DirectX 3.0 compatibility *) type TDIDEVICEOBJECTINSTANCE_DX3 = record dwSize:Dword; guidType:Tguid; dwOfs:Dword; dwType:Dword; dwFlags:Dword; tszName:array[1..MAX_PATH] of char; end; PDIDEVICEOBJECTINSTANCE_DX3=^TDIDEVICEOBJECTINSTANCE_DX3; type PCDIDEVICEOBJECTINSTANCE_DX3 = ^TDIDEVICEOBJECTINSTANCE_DX3; TDIDEVICEOBJECTINSTANCE = record dwSize:Dword; guidType:Tguid; dwOfs:Dword; dwType:Dword; dwFlags:Dword; tszName:array[1..MAX_PATH] of char; dwFFMaxForce:Dword; dwFFForceResolution:Dword; wCollectionNumber:word; wDesignatorIndex:word; wUsagePage:word; wUsage:word; dwDimension:Dword; wExponent:word; wReserved:word; end; PDIDEVICEOBJECTINSTANCE = ^TDIDEVICEOBJECTINSTANCE; PCDIDEVICEOBJECTINSTANCE= ^TDIDEVICEOBJECTINSTANCE; LPDIENUMDEVICEOBJECTSCALLBACK= function(dev:PCDIDEVICEOBJECTINSTANCE;p:pointer):bool;stdCall; const DIDOI_FFACTUATOR =$00000001; DIDOI_FFEFFECTTRIGGER =$00000002; DIDOI_POLLED =$00008000; DIDOI_ASPECTPOSITION =$00000100; DIDOI_ASPECTVELOCITY =$00000200; DIDOI_ASPECTACCEL =$00000300; DIDOI_ASPECTFORCE =$00000400; DIDOI_ASPECTMASK =$00000F00; type TDIPROPHEADER = record dwSize:Dword; dwHeaderSize:Dword; dwObj:Dword; dwHow:Dword; end; PDIPROPHEADER=^TDIPROPHEADER; PCDIPROPHEADER=^TDIPROPHEADER; const DIPH_DEVICE =0; DIPH_BYOFFSET =1; DIPH_BYID =2; type TDIPROPDWORD = record diph: TDIPROPHEADER; dwData:DWORD; end; PDIPROPDWORD=^TDIPROPDWORD; PCDIPROPDWORD=^TDIPROPDWORD; TDIPROPRANGE = record diph: TDIPROPHEADER; lMin: longint; lMax: longint; end; PDIPROPRANGE= ^TDIPROPRANGE; PCDIPROPRANGE= ^TDIPROPRANGE; const DIPROPRANGE_NOMIN =$80000000; DIPROPRANGE_NOMAX =$7FFFFFFF; { #ifdef __cplusplus MAKEDIPROP(prop) /*(const GUID *)(prop)) #else MAKEDIPROP(prop) ((REFGUID)(prop)) #endif } DIPROP_BUFFERSIZE =1; DIPROP_AXISMODE =2; DIPROPAXISMODE_ABS =0; DIPROPAXISMODE_REL =1; DIPROP_GRANULARITY =3; DIPROP_RANGE =4; DIPROP_DEADZONE =5; DIPROP_SATURATION =6; DIPROP_FFGAIN =7; DIPROP_FFLOAD =8; DIPROP_AUTOCENTER =9; DIPROPAUTOCENTER_OFF =0; DIPROPAUTOCENTER_ON =1; DIPROP_CALIBRATIONMODE =10; DIPROPCALIBRATIONMODE_COOKED= 0; DIPROPCALIBRATIONMODE_RAW= 1; type TDIDEVICEOBJECTDATA = record dwOfs:Dword; dwData:Dword; dwTimeStamp:Dword; dwSequence:Dword; end; PDIDEVICEOBJECTDATA=^TDIDEVICEOBJECTDATA; PCDIDEVICEOBJECTDATA=^TDIDEVICEOBJECTDATA; const DIGDD_PEEK =$00000001; { DISEQUENCE_COMPARE(dwSequence1, cmp, dwSequence2) \ ((int)((dwSequence1) - (dwSequence2)) cmp 0) } DISCL_EXCLUSIVE =$00000001; DISCL_NONEXCLUSIVE =$00000002; DISCL_FOREGROUND =$00000004; DISCL_BACKGROUND =$00000008; (* These structures are defined for DirectX 3.0 compatibility *) type TDIDEVICEINSTANCE_DX3 = record dwSize:dword; guidInstance: Tguid; guidProduct: Tguid ; dwDevType:Dword; tszInstanceName: array[1..MAX_PATH] of char; tszProductName: array[1..MAX_PATH] of char; end; PDIDEVICEINSTANCE_DX3=^TDIDEVICEINSTANCE_DX3; PCDIDEVICEINSTANCE_DX3 =^TDIDEVICEINSTANCE_DX3; TDIDEVICEINSTANCE = record dwSize:Dword; guidInstance:Tguid; guidProduct:Tguid; dwDevType:Dword; tszInstanceName:array[1..MAX_PATH] of char; tszProductName:array[1..MAX_PATH] of char; guidFFDriver: Tguid; wUsagePage:word; wUsage:word; end; PDIDEVICEINSTANCE=^TDIDEVICEINSTANCE; PCDIDEVICEINSTANCE=^TDIDEVICEINSTANCE; IDirectInputDevice= class (IUnknown) (*** IDirectInputDeviceA methods ***) function GetCapabilities(DIDEVCAPS:PDIDEVCAPS) :hresult; virtual ; stdcall ; abstract ; function EnumObjects( enum:LPDIENUMDEVICEOBJECTSCALLBACK;pvref:pointer; dwFlags:DWORD) :hresult; virtual ; stdcall ; abstract ; function GetProperty( guid:TGUID;pdiph:PDIPROPHEADER) :hresult; virtual ; stdcall ; abstract ; function SetProperty(guid:TGUID;pdiph:PCDIPROPHEADER) :hresult; virtual ; stdcall ; abstract ; function Acquire :hresult; virtual ; stdcall ; abstract ; function Unacquire :hresult; virtual ; stdcall ; abstract ; function GetDeviceState(A: DWORD;B: pointer) :hresult; virtual ; stdcall ; abstract ; function GetDeviceData(cbObjectData:DWORD;rgdod:PDIDEVICEOBJECTDATA; pdwInOut:PDWORD;dwFlags:DWORD) :hresult; virtual ; stdcall ; abstract ; function SetDataFormat(lpdf: PCDIDATAFORMAT) :hresult; virtual ; stdcall ; abstract ; function SetEventNotification(event:THANDLE) :hresult; virtual ; stdcall ; abstract ; function SetCooperativeLevel(wnd:HWND;dwFlags:DWORD) :hresult; virtual ; stdcall ; abstract ; function GetObjectInfo(pdidoi:PDIDEVICEOBJECTINSTANCE;dwObj:DWORD; dwHow:DWORD) :hresult; virtual ; stdcall ; abstract ; function GetDeviceInfo(A:PDIDEVICEINSTANCE) :hresult; virtual ; stdcall ; abstract ; function RunControlPanel(hwndOwner:HWND;dwFlags:DWORD) :hresult; virtual ; stdcall ; abstract ; function Initialize(INST:integer;dwVersion:DWORD;GUID:Tguid) :hresult; virtual ; stdcall ; abstract ; end; const DISFFC_RESET =$00000001; DISFFC_STOPALL =$00000002; DISFFC_PAUSE =$00000004; DISFFC_CONTINUE =$00000008; DISFFC_SETACTUATORSON =$00000010; DISFFC_SETACTUATORSOFF =$00000020; DIGFFS_EMPTY =$00000001; DIGFFS_STOPPED =$00000002; DIGFFS_PAUSED =$00000004; DIGFFS_ACTUATORSON =$00000010; DIGFFS_ACTUATORSOFF =$00000020; DIGFFS_POWERON =$00000040; DIGFFS_POWEROFF =$00000080; DIGFFS_SAFETYSWITCHON =$00000100; DIGFFS_SAFETYSWITCHOFF =$00000200; DIGFFS_USERFFSWITCHON =$00000400; DIGFFS_USERFFSWITCHOFF =$00000800; DIGFFS_DEVICELOST =$80000000; type TDIEFFECTINFO= record dwSize:Dword; guid: TGUID; dwEffType:Dword; dwStaticParams:Dword; dwDynamicParams:Dword; tszName: array[1..MAX_PATH] of char; end; PDIEFFECTINFO=^TDIEFFECTINFO; PCDIEFFECTINFO=^TDIEFFECTINFO; LPDIENUMEFFECTSCALLBACK= function (inf:PCDIEFFECTINFO;p:pointer):bool; LPDIENUMCREATEDEFFECTOBJECTSCALLBACK= function (eff:IDIRECTINPUTEFFECT; p:pointer):BOOL; IDirectInputDevice2= class (IDirectInputDevice) (*** IDirectInputDevice2A methods ***) function CreateEffect(guid:TGUID;lpeff:PCDIEFFECT;var ppdeff:IDIRECTINPUTEFFECT; punkouter:pointer) :hresult; virtual ; stdcall ; abstract ; function EnumEffects(lpCallBack:LPDIENUMEFFECTSCALLBACK;pvref:pointer; dwEffType:DWORD) :hresult; virtual ; stdcall ; abstract ; function GetEffectInfo(pdei:PDIEFFECTINFO;guid:TGUID) :hresult; virtual ; stdcall ; abstract ; function GetForceFeedbackState(pdwOut:PDWORD) :hresult; virtual ; stdcall ; abstract ; function SendForceFeedbackCommand(dwFlags:DWORD) :hresult; virtual ; stdcall ; abstract ; function EnumCreatedEffectObjects(lpCallBack:LPDIENUMCREATEDEFFECTOBJECTSCALLBACK; pvRef:pointer;fl:DWORD) :hresult; virtual ; stdcall ; abstract ; function Escape(pesc:PDIEFFESCAPE) :hresult; virtual ; stdcall ; abstract ; function Poll :hresult; virtual ; stdcall ; abstract ; function SendDeviceData(cbObjectData:DWORD;rgdod:PDIDEVICEOBJECTDATA; pdwInOut:PDWORD;fl:DWORD) :hresult; virtual ; stdcall ; abstract ; end; (**************************************************************************** * * Mouse * ****************************************************************************) type TDIMOUSESTATE = record lX, lY, lZ :longint; rgbButtons:array[1..4] of byte; end; PDIMOUSESTATE=^TDIMOUSESTATE; const DIMOFS_X = 0; { FIELD_OFFSET(DIMOUSESTATE, lX)} DIMOFS_Y = 4; { FIELD_OFFSET(DIMOUSESTATE, lY)} DIMOFS_Z = 8; { FIELD_OFFSET(DIMOUSESTATE, lZ)} DIMOFS_BUTTON0=12; { FIELD_OFFSET(DIMOUSESTATE, rgbButtons) + 0)} DIMOFS_BUTTON1=13; { FIELD_OFFSET(DIMOUSESTATE, rgbButtons) + 1)} DIMOFS_BUTTON2=14; { FIELD_OFFSET(DIMOUSESTATE, rgbButtons) + 2)} DIMOFS_BUTTON3=15; { FIELD_OFFSET(DIMOUSESTATE, rgbButtons) + 3)} (**************************************************************************** * * Keyboard * ****************************************************************************) (**************************************************************************** * * DirectInput keyboard scan codes * ****************************************************************************) DIK_ESCAPE =$01; DIK_1 =$02; DIK_2 =$03; DIK_3 =$04; DIK_4 =$05; DIK_5 =$06; DIK_6 =$07; DIK_7 =$08; DIK_8 =$09; DIK_9 =$0A; DIK_0 =$0B; DIK_MINUS =$0C; (* - on main keyboard *) DIK_EQUALS =$0D; DIK_BACK =$0E; (* backspace *) DIK_TAB =$0F; DIK_Q =$10; DIK_W =$11; DIK_E =$12; DIK_R =$13; DIK_T =$14; DIK_Y =$15; DIK_U =$16; DIK_I =$17; DIK_O =$18; DIK_P =$19; DIK_LBRACKET =$1A; DIK_RBRACKET =$1B; DIK_RETURN =$1C; (* Enter on main keyboard *) DIK_LCONTROL =$1D; DIK_A =$1E; DIK_S =$1F; DIK_D =$20; DIK_F =$21; DIK_G =$22; DIK_H =$23; DIK_J =$24; DIK_K =$25; DIK_L =$26; DIK_SEMICOLON =$27; DIK_APOSTROPHE =$28; DIK_GRAVE =$29; (* accent grave *) DIK_LSHIFT =$2A; DIK_BACKSLASH =$2B; DIK_Z =$2C; DIK_X =$2D; DIK_C =$2E; DIK_V =$2F; DIK_B =$30; DIK_N =$31; DIK_M =$32; DIK_COMMA =$33; DIK_PERIOD =$34; (* . on main keyboard *) DIK_SLASH =$35; (* / on main keyboard *) DIK_RSHIFT =$36; DIK_MULTIPLY =$37; (* * on numeric keypad *) DIK_LMENU =$38; (* left Alt *) DIK_SPACE =$39; DIK_CAPITAL =$3A; DIK_F1 =$3B; DIK_F2 =$3C; DIK_F3 =$3D; DIK_F4 =$3E; DIK_F5 =$3F; DIK_F6 =$40; DIK_F7 =$41; DIK_F8 =$42; DIK_F9 =$43; DIK_F10 =$44; DIK_NUMLOCK =$45; DIK_SCROLL =$46; (* Scroll Lock *) DIK_NUMPAD7 =$47; DIK_NUMPAD8 =$48; DIK_NUMPAD9 =$49; DIK_SUBTRACT =$4A; (* - on numeric keypad *) DIK_NUMPAD4 =$4B; DIK_NUMPAD5 =$4C; DIK_NUMPAD6 =$4D; DIK_ADD =$4E; (* + on numeric keypad *) DIK_NUMPAD1 =$4F; DIK_NUMPAD2 =$50; DIK_NUMPAD3 =$51; DIK_NUMPAD0 =$52; DIK_DECIMAL =$53; (* . on numeric keypad *) DIK_F11 =$57; DIK_F12 =$58; DIK_F13 =$64; (* (NEC PC98) *) DIK_F14 =$65; (* (NEC PC98) *) DIK_F15 =$66; (* (NEC PC98) *) DIK_KANA =$70; (* (Japanese keyboard) *) DIK_CONVERT =$79; (* (Japanese keyboard) *) DIK_NOCONVERT =$7B; (* (Japanese keyboard) *) DIK_YEN =$7D; (* (Japanese keyboard) *) DIK_NUMPADEQUALS =$8D; (* = on numeric keypad (NEC PC98) *) DIK_CIRCUMFLEX =$90; (* (Japanese keyboard) *) DIK_AT =$91; (* (NEC PC98) *) DIK_COLON =$92; (* (NEC PC98) *) DIK_UNDERLINE =$93; (* (NEC PC98) *) DIK_KANJI =$94; (* (Japanese keyboard) *) DIK_STOP =$95; (* (NEC PC98) *) DIK_AX =$96; (* (Japan AX) *) DIK_UNLABELED =$97; (* (J3100) *) DIK_NUMPADENTER =$9C; (* Enter on numeric keypad *) DIK_RCONTROL =$9D; DIK_NUMPADCOMMA =$B3; (* , on numeric keypad (NEC PC98) *) DIK_DIVIDE =$B5; (* / on numeric keypad *) DIK_SYSRQ =$B7; DIK_RMENU =$B8; (* right Alt *) DIK_HOME =$C7; (* Home on arrow keypad *) DIK_UP =$C8; (* UpArrow on arrow keypad *) DIK_PRIOR =$C9; (* PgUp on arrow keypad *) DIK_LEFT =$CB; (* LeftArrow on arrow keypad *) DIK_RIGHT =$CD; (* RightArrow on arrow keypad *) DIK_END =$CF; (* End on arrow keypad *) DIK_DOWN =$D0; (* DownArrow on arrow keypad *) DIK_NEXT =$D1; (* PgDn on arrow keypad *) DIK_INSERT =$D2; (* Insert on arrow keypad *) DIK_DELETE =$D3; (* Delete on arrow keypad *) DIK_LWIN =$DB; (* Left Windows key *) DIK_RWIN =$DC; (* Right Windows key *) DIK_APPS =$DD; (* AppMenu key *) (* * Alternate names for keys, to facilitate transition from DOS. *) DIK_BACKSPACE =DIK_BACK; (* backspace *) DIK_NUMPADSTAR =DIK_MULTIPLY; (* * on numeric keypad *) DIK_LALT =DIK_LMENU; (* left Alt *) DIK_CAPSLOCK =DIK_CAPITAL ; (* CapsLock *) DIK_NUMPADMINUS =DIK_SUBTRACT; (* - on numeric keypad *) DIK_NUMPADPLUS =DIK_ADD ; (* + on numeric keypad *) DIK_NUMPADPERIOD =DIK_DECIMAL; (* . on numeric keypad *) DIK_NUMPADSLASH =DIK_DIVIDE; (* / on numeric keypad *) DIK_RALT =DIK_RMENU ; (* right Alt *) DIK_UPARROW =DIK_UP; (* UpArrow on arrow keypad *) DIK_PGUP =DIK_PRIOR; (* PgUp on arrow keypad *) DIK_LEFTARROW =DIK_LEFT; (* LeftArrow on arrow keypad *) DIK_RIGHTARROW =DIK_RIGHT; (* RightArrow on arrow keypad *) DIK_DOWNARROW =DIK_DOWN; (* DownArrow on arrow keypad *) DIK_PGDN =DIK_NEXT; (* PgDn on arrow keypad *) (**************************************************************************** * * Joystick * ****************************************************************************) type TDIJOYSTATE = record lX :longint; (* x-axis position *) lY :longint; (* y-axis position *) lZ :longint; (* z-axis position *) lRx :longint; (* x-axis rotation *) lRy :longint; (* y-axis rotation *) lRz :longint; (* z-axis rotation *) rglSlider:array[1..2] of longint;(* extra axes positions *) rgdwPOV:array[1..4] of Dword; (* POV directions *) rgbButtons:array[1..32] of byte; (* 32 buttons *) end; PDIJOYSTATE=^TDIJOYSTATE; TDIJOYSTATE2 = record lX :longint; (* x-axis position *) lY :longint; (* y-axis position *) lZ :longint; (* z-axis position *) lRx :longint; (* x-axis rotation *) lRy :longint; (* y-axis rotation *) lRz :longint; (* z-axis rotation *) rglSlider:array[1..2] of longint; (* extra axes positions *) rgdwPOV:array[1..4] of Dword; (* POV directions *) rgbButtons:array[1..128] of byte; (* 128 buttons *) lVX :longint; (* x-axis velocity *) lVY :longint; (* y-axis velocity *) lVZ :longint; (* z-axis velocity *) lVRx :longint; (* x-axis angular velocity *) lVRy :longint; (* y-axis angular velocity *) lVRz :longint; (* z-axis angular velocity *) rglVSlider:array[1..2] of longint;(* extra axes velocities *) lAX :longint; (* x-axis acceleration *) lAY :longint; (* y-axis acceleration *) lAZ :longint; (* z-axis acceleration *) lARx :longint; (* x-axis angular acceleration *) lARy :longint; (* y-axis angular acceleration *) lARz :longint; (* z-axis angular acceleration *) rglASlider:array[1..2] of longint;(* extra axes accelerations *) lFX :longint; (* x-axis force *) lFY :longint; (* y-axis force *) lFZ :longint; (* z-axis force *) lFRx :longint; (* x-axis torque *) lFRy :longint; (* y-axis torque *) lFRz :longint; (* z-axis torque *) rglFSlider:array[1..2] of longint;(* extra axes forces *) end; PDIJOYSTATE2=^TDIJOYSTATE2; { const DIJOFS_X FIELD_OFFSET(DIJOYSTATE, lX) DIJOFS_Y FIELD_OFFSET(DIJOYSTATE, lY) DIJOFS_Z FIELD_OFFSET(DIJOYSTATE, lZ) DIJOFS_RX FIELD_OFFSET(DIJOYSTATE, lRx) DIJOFS_RY FIELD_OFFSET(DIJOYSTATE, lRy) DIJOFS_RZ FIELD_OFFSET(DIJOYSTATE, lRz) DIJOFS_SLIDER(n) (FIELD_OFFSET(DIJOYSTATE, rglSlider) + \ (n) * sizeof(LONG)) DIJOFS_POV(n) (FIELD_OFFSET(DIJOYSTATE, rgdwPOV) + \ (n) * sizeof(DWORD)) DIJOFS_BUTTON(n) (FIELD_OFFSET(DIJOYSTATE, rgbButtons) + (n)) DIJOFS_BUTTON0 DIJOFS_BUTTON(0) DIJOFS_BUTTON1 DIJOFS_BUTTON(1) DIJOFS_BUTTON2 DIJOFS_BUTTON(2) DIJOFS_BUTTON3 DIJOFS_BUTTON(3) DIJOFS_BUTTON4 DIJOFS_BUTTON(4) DIJOFS_BUTTON5 DIJOFS_BUTTON(5) DIJOFS_BUTTON6 DIJOFS_BUTTON(6) DIJOFS_BUTTON7 DIJOFS_BUTTON(7) DIJOFS_BUTTON8 DIJOFS_BUTTON(8) DIJOFS_BUTTON9 DIJOFS_BUTTON(9) DIJOFS_BUTTON10 DIJOFS_BUTTON(10) DIJOFS_BUTTON11 DIJOFS_BUTTON(11) DIJOFS_BUTTON12 DIJOFS_BUTTON(12) DIJOFS_BUTTON13 DIJOFS_BUTTON(13) DIJOFS_BUTTON14 DIJOFS_BUTTON(14) DIJOFS_BUTTON15 DIJOFS_BUTTON(15) DIJOFS_BUTTON16 DIJOFS_BUTTON(16) DIJOFS_BUTTON17 DIJOFS_BUTTON(17) DIJOFS_BUTTON18 DIJOFS_BUTTON(18) DIJOFS_BUTTON19 DIJOFS_BUTTON(19) DIJOFS_BUTTON20 DIJOFS_BUTTON(20) DIJOFS_BUTTON21 DIJOFS_BUTTON(21) DIJOFS_BUTTON22 DIJOFS_BUTTON(22) DIJOFS_BUTTON23 DIJOFS_BUTTON(23) DIJOFS_BUTTON24 DIJOFS_BUTTON(24) DIJOFS_BUTTON25 DIJOFS_BUTTON(25) DIJOFS_BUTTON26 DIJOFS_BUTTON(26) DIJOFS_BUTTON27 DIJOFS_BUTTON(27) DIJOFS_BUTTON28 DIJOFS_BUTTON(28) DIJOFS_BUTTON29 DIJOFS_BUTTON(29) DIJOFS_BUTTON30 DIJOFS_BUTTON(30) DIJOFS_BUTTON31 DIJOFS_BUTTON(31) } (**************************************************************************** * * IDirectInput * ****************************************************************************) const DIENUM_STOP = 0; DIENUM_CONTINUE = 1; type LPDIENUMDEVICESCALLBACK= function(inst:PCDIDEVICEINSTANCE; p:pointer):bool;stdCall; const DIEDFL_ALLDEVICES =$00000000; DIEDFL_ATTACHEDONLY =$00000001; DIEDFL_FORCEFEEDBACK =$00000100; type IDirectInput= class(IUnknown) (*** IDirectInputA methods ***) function CreateDevice(guid:PGUID;var device:IDIRECTINPUTDEVICE; punkOuter:pointer) :hresult; virtual ; stdcall ; abstract ; function EnumDevices(dwDevType:DWORD;callBack:LPDIENUMDEVICESCALLBACK; pvRef:pointer;dwFlags:DWORD) :hresult; virtual ; stdcall ; abstract ; function GetDeviceStatus(guid:TGUID) :hresult; virtual ; stdcall ; abstract ; function RunControlPanel(wnd:HWND;dwFlags:DWORD) :hresult; virtual ; stdcall ; abstract ; function Initialize(HINSTANCE:longint;dwVersion:DWORD) :hresult; virtual ; stdcall ; abstract ; end; (* IdirectInput2 not documented *) IDirectInput2= class(IDirectInput) (*** IDirectInput2A methods ***) function FindDevice(guid:TGUID;st:Pchar;gu:PGUID) :hresult; virtual ; stdcall ; abstract ; end; var DirectInputCreate: function(HINSTANCE:longint;dwVersion:Dword; var ppDI:IDIRECTINPUT; punkOuter:pointer):hresult;stdCall; (**************************************************************************** * * Return Codes * ****************************************************************************) Const (* * The operation completed successfully. *) DI_OK = S_OK; (* * The device exists but is not currently attached. *) DI_NOTATTACHED = S_FALSE; (* * The device buffer overflowed. Some input was lost. *) DI_BUFFEROVERFLOW = S_FALSE; (* * The change in device properties had no effect. *) DI_PROPNOEFFECT = S_FALSE; (* * The operation had no effect. *) DI_NOEFFECT = S_FALSE; (* * The device is a polled device. As a result, device buffering * will not collect any data and event notifications will not be * signalled until GetDeviceState is called. *) DI_POLLEDDEVICE = $00000002; (* * The parameters of the effect were successfully updated by * IDirectInputEffect::SetParameters, but the effect was not * downloaded because the device is not exclusively acquired * or because the DIEP_NODOWNLOAD flag was passed. *) DI_DOWNLOADSKIPPED =$00000003; (* * The parameters of the effect were successfully updated by * IDirectInputEffect::SetParameters, but in order to change * the parameters, the effect needed to be restarted. *) DI_EFFECTRESTARTED =$00000004; (* * The parameters of the effect were successfully updated by * IDirectInputEffect::SetParameters, but some of them were * beyond the capabilities of the device and were truncated. *) DI_TRUNCATED =$00000008; (* * Equal to DI_EFFECTRESTARTED | DI_TRUNCATED. *) DI_TRUNCATEDANDRESTARTED =$0000000C; (* * The application requires a newer version of DirectInput. *) DIERR_OLDDIRECTINPUTVERSION =SEVERITY_ERROR or FACILITY_WIN32 or ERROR_OLD_WIN_VERSION; {MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIN32, ERROR_OLD_WIN_VERSION)} (* * The application was written for an unsupported prerelease version * of DirectInput. *) DIERR_BETADIRECTINPUTVERSION =SEVERITY_ERROR or FACILITY_WIN32 or ERROR_RMODE_APP; {MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIN32, ERROR_RMODE_APP)} (* * The object could not be created due to an incompatible driver version * or mismatched or incomplete driver components. *) DIERR_BADDRIVERVER =SEVERITY_ERROR or FACILITY_WIN32 or ERROR_BAD_DRIVER_LEVEL; {MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIN32, ERROR_BAD_DRIVER_LEVEL)} (* * The device or device instance or effect is not registered with DirectInput. *) DIERR_DEVICENOTREG = REGDB_E_CLASSNOTREG; (* * The requested object does not exist. *) DIERR_NOTFOUND =SEVERITY_ERROR or FACILITY_WIN32 or ERROR_FILE_NOT_FOUND; {MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIN32, ERROR_FILE_NOT_FOUND)} (* * The requested object does not exist. *) DIERR_OBJECTNOTFOUND =SEVERITY_ERROR or FACILITY_WIN32 or ERROR_FILE_NOT_FOUND; {MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIN32, ERROR_FILE_NOT_FOUND)} (* * An invalid parameter was passed to the returning function, * or the object was not in a state that admitted the function * to be called. *) DIERR_INVALIDPARAM = E_INVALIDARG; (* * The specified interface is not supported by the object *) DIERR_NOINTERFACE = E_NOINTERFACE; (* * An undetermined error occured inside the DInput subsystem *) DIERR_GENERIC = E_FAIL; (* * The DInput subsystem couldn't allocate sufficient memory to complete the * caller's request. *) DIERR_OUTOFMEMORY = E_OUTOFMEMORY; (* * The function called is not supported at this time *) DIERR_UNSUPPORTED = E_NOTIMPL; (* * This object has not been initialized *) DIERR_NOTINITIALIZED =SEVERITY_ERROR or FACILITY_WIN32 or ERROR_NOT_READY; {MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIN32, ERROR_NOT_READY)} (* * This object is already initialized *) DIERR_ALREADYINITIALIZED =SEVERITY_ERROR or FACILITY_WIN32 or ERROR_ALREADY_INITIALIZED; {MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIN32, ERROR_ALREADY_INITIALIZED)} (* * This object does not support aggregation *) DIERR_NOAGGREGATION = CLASS_E_NOAGGREGATION; (* * Another app has a higher priority level, preventing this call from * succeeding. *) DIERR_OTHERAPPHASPRIO = E_ACCESSDENIED; (* * Access to the device has been lost. It must be re-acquired. *) DIERR_INPUTLOST =SEVERITY_ERROR or FACILITY_WIN32 or ERROR_READ_FAULT; {MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIN32, ERROR_READ_FAULT)} (* * The operation cannot be performed while the device is acquired. *) DIERR_ACQUIRED =SEVERITY_ERROR or FACILITY_WIN32 or ERROR_BUSY; {MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIN32, ERROR_BUSY)} (* * The operation cannot be performed unless the device is acquired. *) DIERR_NOTACQUIRED =SEVERITY_ERROR or FACILITY_WIN32 or ERROR_INVALID_ACCESS; {MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIN32, ERROR_INVALID_ACCESS)} (* * The specified property cannot be changed. *) DIERR_READONLY = E_ACCESSDENIED; (* * The device already has an event notification associated with it. *) DIERR_HANDLEEXISTS = E_ACCESSDENIED; (* * Data is not yet available. *) E_PENDING =$80070007; (* * Unable to IDirectInputJoyConfig_Acquire because the user * does not have sufficient privileges to change the joystick * configuration. *) DIERR_INSUFFICIENTPRIVS =$80040200; (* * The device is full. *) DIERR_DEVICEFULL =$80040201; (* * Not all the requested information fit into the buffer. *) DIERR_MOREDATA =$80040202; (* * The effect is not downloaded. *) DIERR_NOTDOWNLOADED =$80040203; (* * The device cannot be reinitialized because there are still effects * attached to it. *) DIERR_HASEFFECTS =$80040204; (* * The operation cannot be performed unless the device is acquired * in DISCL_EXCLUSIVE mode. *) DIERR_NOTEXCLUSIVEACQUIRED =$80040205; (* * The effect could not be downloaded because essential information * is missing. For example, no axes have been associated with the * effect, or no type-specific information has been created. *) DIERR_INCOMPLETEEFFECT =$80040206; (* * Attempted to read buffered device data from a device that is * not buffered. *) DIERR_NOTBUFFERED =$80040207; (* * An attempt was made to modify parameters of an effect while it is * playing. Not all hardware devices support altering the parameters * of an effect while it is playing. *) DIERR_EFFECTPLAYING =$80040208; (**************************************************************************** * * Definitions for non-IDirectInput (VJoyD) features defined more recently * than the current sdk files * ****************************************************************************) (* * Flag to indicate that the dwReserved2 field of the JOYINFOEX structure * contains mini-driver specific data to be passed by VJoyD to the mini- * driver instead of doing a poll. *) JOY_PASSDRIVERDATA =$10000000; (* * Informs the joystick driver that the configuration has been changed * and should be reloaded from the registery. * dwFlags is reserved and should be set to zero *) var joyConfigChanged:function(dwFlags:DWORD ):hresult; (* * Hardware Setting indicating that the device is a headtracker *) const JOY_HWS_ISHEADTRACKER =$02000000; (* * Hardware Setting indicating that the VxD is used to replace * the standard analog polling *) JOY_HWS_ISGAMEPORTDRIVER =$04000000; (* * Hardware Setting indicating that the driver needs a standard * gameport in order to communicate with the device. *) JOY_HWS_ISANALOGPORTDRIVER =$08000000; (* * Hardware Setting indicating that VJoyD should not load this * driver, it will be loaded externally and will register with * VJoyD of it's own accord. *) JOY_HWS_AUTOLOAD =$10000000; (* * Hardware Setting indicating that the driver acquires any * resources needed without needing a devnode through VJoyD. *) JOY_HWS_NODEVNODE =$20000000; (* * Hardware Setting indicating that the VxD can be used as * a port 201h emulator. *) JOY_HWS_ISGAMEPORTEMULATOR =$40000000; (* * Usage Setting indicating that the settings are volatile and * should be removed if still present on a reboot. *) JOY_US_VOLATILE =$00000008; (**************************************************************************** * * Definitions for non-IDirectInput (VJoyD) features defined more recently * than the current ddk files * ****************************************************************************) Const (* * Poll type in which the do_other field of the JOYOEMPOLLDATA * structure contains mini-driver specific data passed from an app. *) JOY_OEMPOLL_PASSDRIVERDATA = 7; Implementation var dioKeyBoard:PDIOBJECTDATAFORMAT; dioMouse:PDIOBJECTDATAFORMAT; dioJK1:PDIOBJECTDATAFORMAT; dioJK2:PDIOBJECTDATAFORMAT; procedure aff(var t); var x:array[1..256] of TDIOBJECTDATAFORMAT ABSOLUTE t; i:integer; begin for i:=1 to 256 do with x[i] do messageCentral( Istr(longint(GUID))+' '+ Istr(dwOfs)+' '+ Istr(dwType)+' '+ Istr(dwFlags) ); end; procedure initDFDI; var f:file; res:intG; begin assignFile(f,trouverChemin('Dinput.lib')+'Dinput.lib'); Greset(f,1); if GIO<>0 then begin messageCentral('Unable to find Dinput.lib'); exit; end; getmem(dioKeyBoard,sizeof(TDIOBJECTDATAFORMAT)*256); Gseek(f,$1EFA); Gblockread(f,dioKeyBoard^,sizeof(TDIOBJECTDATAFORMAT)*256,res); Gseek(f,$2EFA); Gblockread(f,c_dfDIKeyboard,sizeof(c_dfDIKeyboard),res); c_dfDIKeyboard.rgodf:=dioKeyBoard; getmem(dioMouse,sizeof(TDIOBJECTDATAFORMAT)*7); Gseek(f,$3A4A); Gblockread(f,dioMouse^,sizeof(TDIOBJECTDATAFORMAT)*7,res); Gseek(f,$3ABA); Gblockread(f,c_dfDIMouse,sizeof(c_dfDIMouse),res); c_dfDIMouse.rgodf:=dioMouse; getmem(dioJK1,sizeof(TDIOBJECTDATAFORMAT)*164); Gseek(f,$0BD4); Gblockread(f,dioJK1^,sizeof(TDIOBJECTDATAFORMAT)*164,res); Gseek(f,$1614); Gblockread(f,c_dfDIJoyStick,sizeof(c_dfDIjoyStick),res); c_dfDIJoystick.rgodf:=dioJK1; getmem(dioJK2,sizeof(TDIOBJECTDATAFORMAT)*44); Gseek(f,$19A0); Gblockread(f,dioJK2^,sizeof(TDIOBJECTDATAFORMAT)*44,res); Gseek(f,$1C60); Gblockread(f,c_dfDIJoyStick2,sizeof(c_dfDIjoyStick2),res); c_dfDIJoystick2.rgodf:=dioJK2; Gclose(f); {aff(dioKeyBoard^);} if GIO<>0 then messageCentral('Error reading Dinput.lib'); end; var hMod: THandle; initialization begin hMod := GLoadLibrary('dinput.dll'); if (hMod <> 0) then begin DirectInputCreate := GetProcAddress( hMod, 'DirectInputCreateA' ); if not assigned(DirectInputCreate) then messageCentral('DirectInputCreate not found'); end else messageCentral('Dinput.dll not found'); initDFDI; end; finalization FreeLibrary( hMod ); end.
(* JSTAT ver 4.0 JRT Systems *) (* *) (* jstat computes several basic statistics on *) (* an input array. *) (* *) (* parameters: *) (* n - the number of data items in the *) (* input array *) (* x - the input array of real numbers, *) (* may be up to 1000 elements, *) (* actual variable in calling pgm *) (* may be much smaller array *) (* r - the computed statistics are stored *) (* in this record *) EXTERN TYPE jstat_interface = RECORD mean, standard_deviation, variance, skewness, kurtosis, m1, m2, m3, m4 : real; END; jstat_array = ARRAY [1..1000] OF real; {=================================================================} PROCEDURE jstat (n : integer; VAR x : jstat_array; VAR r : jstat_interface); VAR i : integer; total_x, total_x2, total_x3, total_x4 : real; {=================================================================} FUNCTION cube (x : real) : real; BEGIN cube := x * sqr(x); END; {=================================================================} FUNCTION sqrt (x : real) : real; VAR sq, a, b : real; exponent, i : integer; zap : RECORD CASE integer OF 0 : (num : real); 1 : (ch8 : ARRAY [1..8] OF char); END; BEGIN IF x = 0.0 THEN sqrt := 0.0 ELSE BEGIN sq := abs(x); zap.num := sq; exponent := ord(zap.ch8[1]); exponent := (exponent DIV 2) + 32; zap.ch8[1] := chr(exponent); a := zap.num; b := 0; i := 0; WHILE a <> b DO BEGIN b := sq / a; a := (a + b) / 2; i := i + 1; IF i > 4 THEN BEGIN i := 0; IF abs(a - b) < (1.0e-12 * a) THEN a := b; END; END; sqrt := a; END; (* else *) END; (* sqrt *) {=================================================================} PROCEDURE totals; VAR i : integer; tx, tx2, tx3, tx4 : real; sum_x, mean : real; BEGIN (* totals *) total_x := 0; total_x2 := 0; total_x3 := 0; total_x4 := 0; sum_x := 0; FOR i := 1 TO n DO sum_x := sum_x + x[i]; mean := sum_x / n; r.mean := mean; FOR i := 1 TO n DO BEGIN tx := x[i] - mean; tx2 := sqr(tx); tx3 := tx * tx2; tx4 := tx * tx3; total_x := total_x + tx; total_x2 := total_x2 + tx2; total_x3 := total_x3 + tx3; total_x4 := total_x4 + tx4; END; END; (* totals *) BEGIN (* jstat *) totals; r.m1 := total_x / n; r.m2 := total_x2 / n; r.m3 := total_x3 / n; r.m4 := total_x4 / n; r.standard_deviation := sqrt(r.m2); r.variance := r.m2; r.kurtosis := r.m4 / sqr(r.m2); r.skewness := r.m3 / sqrt(cube(r.m2)); END; (* jstat *) . 
unit ch341hw; {$mode objfpc}{$H+} interface uses Classes, SysUtils, basehw, msgstr, ch341dll, utilfunc; type { TCH341Hardware } TCH341Hardware = class(TBaseHardware) private FDevOpened: boolean; FDevHandle: Longint; FStrError: string; procedure SetI2CPins(scl, sda: cardinal); public constructor Create; destructor Destroy; override; function GetLastError: string; override; function DevOpen: boolean; override; procedure DevClose; override; //spi function SPIRead(CS: byte; BufferLen: integer; var buffer: array of byte): integer; override; function SPIWrite(CS: byte; BufferLen: integer; buffer: array of byte): integer; override; function SPIInit(speed: integer): boolean; override; procedure SPIDeinit; override; //I2C procedure I2CInit; override; procedure I2CDeinit; override; function I2CReadWrite(DevAddr: byte; WBufferLen: integer; WBuffer: array of byte; RBufferLen: integer; var RBuffer: array of byte): integer; override; procedure I2CStart; override; procedure I2CStop; override; function I2CReadByte(ack: boolean): byte; override; function I2CWriteByte(data: byte): boolean; override; //return ack //MICROWIRE function MWInit(speed: integer): boolean; override; procedure MWDeinit; override; function MWRead(CS: byte; BufferLen: integer; var buffer: array of byte): integer; override; function MWWrite(CS: byte; BitsWrite: byte; buffer: array of byte): integer; override; function MWIsBusy: boolean; override; end; implementation uses main; procedure TCH341Hardware.SetI2CPins(scl, sda: cardinal); var pins: cardinal; begin if scl > 0 then scl := $40000; if sda > 0 then sda := $80000; pins := 0; pins := pins or scl or sda; CH341SetOutput(FDevHandle, $10, 0, pins); end; constructor TCH341Hardware.Create; begin FDevHandle := -1; FHardwareName := 'CH341'; FHardwareID := CHW_CH341; end; destructor TCH341Hardware.Destroy; begin DevClose; end; function TCH341Hardware.GetLastError: string; begin result := FStrError; end; function TCH341Hardware.DevOpen: boolean; var i, err: integer; begin if FDevOpened then DevClose; for i:=0 to mCH341_MAX_NUMBER-1 do begin err := CH341OpenDevice(i); if not err < 0 then begin FDevHandle := i; Break; end; end; if err < 0 then begin FStrError := STR_CONNECTION_ERROR+ FHardwareName +'('+IntToStr(err)+')'; FDevHandle := -1; FDevOpened := false; Exit(false); end; FDevOpened := true; Result := true; end; procedure TCH341Hardware.DevClose; begin if FDevHandle >= 0 then begin CH341CloseDevice(FDevHandle); FDevHandle := -1; FDevOpened := false; end; end; //SPI___________________________________________________________________________ function TCH341Hardware.SPIInit(speed: integer): boolean; begin if not FDevOpened then Exit(false); Result := CH341SetStream(FDevHandle, %10000001); end; procedure TCH341Hardware.SPIDeinit; begin if not FDevOpened then Exit; CH341Set_D5_D0(FDevHandle, 0, 0); end; function TCH341Hardware.SPIRead(CS: byte; BufferLen: integer; var buffer: array of byte): integer; begin if not FDevOpened then Exit(-1); if (CS = 1) then if not CH341StreamSPI4(FDevHandle, $80, BufferLen, @buffer) then result :=-1 else result := BufferLen else begin CH341Set_D5_D0(FDevHandle, $29, 0); //Вручную дергаем cs if not CH341StreamSPI4(FDevHandle, 0, BufferLen, @buffer) then result :=-1 else result := BufferLen; end; end; function TCH341Hardware.SPIWrite(CS: byte; BufferLen: integer; buffer: array of byte): integer; begin if not FDevOpened then Exit(-1); if (CS = 1) then if not CH341StreamSPI4(FDevHandle, $80, BufferLen, @buffer) then result :=-1 else result := BufferLen else begin CH341Set_D5_D0(FDevHandle, $29, 0); //Вручную дергаем cs if not CH341StreamSPI4(FDevHandle, 0, BufferLen, @buffer) then result :=-1 else result := BufferLen; end end; //i2c___________________________________________________________________________ procedure TCH341Hardware.I2CInit; begin if not FDevOpened then Exit; CH341SetStream(FDevHandle, %10000001); SetI2CPins(1,1); end; procedure TCH341Hardware.I2CDeinit; begin if not FDevOpened then Exit; CH341Set_D5_D0(FDevHandle, 0, 0); SetI2CPins(1,1); end; function TCH341Hardware.I2CReadWrite(DevAddr: byte; WBufferLen: integer; WBuffer: array of byte; RBufferLen: integer; var RBuffer: array of byte): integer; var full_buff: array of byte; begin if not FDevOpened then Exit(-1); SetLength(full_buff, WBufferLen+1); move(WBuffer, full_buff[1], WBufferLen); full_buff[0] := DevAddr; if not CH341StreamI2C(FDevHandle, WBufferLen+1, @full_buff[0], RBufferLen, @RBuffer) then result := -1 else result := WBufferLen+RBufferLen; end; procedure TCH341Hardware.I2CStart; var mLength: Cardinal; mBuffer: array[0..mCH341_PACKET_LENGTH-1] of Byte; begin if not FDevOpened then Exit; mBuffer[0] := mCH341A_CMD_I2C_STREAM; // код команды mBuffer[1] := mCH341A_CMD_I2C_STM_STA; // код старт-бита mBuffer[2] := mCH341A_CMD_I2C_STM_END; // окончание пакета mLength := 3; // длина пакета CH341WriteData(FDevHandle, @mBuffer, @mLength); // запись блока данных end; procedure TCH341Hardware.I2CStop; var mLength: Cardinal; mBuffer: array[0..mCH341_PACKET_LENGTH-1] of Byte; begin if not FDevOpened then Exit; mBuffer[0] := mCH341A_CMD_I2C_STREAM; // код команды mBuffer[1] := mCH341A_CMD_I2C_STM_STO; // код стоп-бита mBuffer[2] := mCH341A_CMD_I2C_STM_END; // окончание пакета mLength := 3; // длина пакета CH341WriteData(FDevHandle, @mBuffer, @mLength); // запись блока данных end; function TCH341Hardware.I2CReadByte(ack: boolean): byte; function ReadBit(): byte; var pins: cardinal; begin SetI2CPins(0,1); //scl low SetI2CPins(1,1); //scl/sda hi CH341GetStatus(FDevHandle, @pins); if IsBitSet(pins, 23) then Result := 1 else Result := 0; end; var i: integer; data: byte; begin if not FDevOpened then Exit; data := 0; for i:=7 downto 0 do begin if (ReadBit = 1) then data := SetBit(data, i); end; //generate pulse for ack if not ack then begin SetI2CPins(0,1); //scl low SetI2CPins(0,1); //1 SetI2CPins(1,1); //scl hi end else begin SetI2CPins(0,1); //scl low SetI2CPins(0,0); //0 SetI2CPins(1,0); end; result := data; end; function TCH341Hardware.I2CWriteByte(data: byte): boolean; procedure SendBit(bit: byte); begin if boolean(bit) then begin SetI2CPins(0,0); //scl low SetI2CPins(0,1); SetI2CPins(1,1); end else begin SetI2CPins(0,0); SetI2CPins(0,0); SetI2CPins(1,0); end; end; var pins, i: cardinal; begin if not FDevOpened then Exit; for i:=7 downto 0 do begin if IsBitSet(data, i) then SendBit(1) else SendBit(0); end; //generate pulse for ack SetI2CPins(0,0); //scl low SetI2CPins(0,1); SetI2CPins(1,1); //scl hi //read ack CH341GetStatus(FDevHandle, @pins); SetI2CPins(0,0); Result := not IsBitSet(pins, 23); end; //MICROWIRE_____________________________________________________________________ function TCH341Hardware.MWInit(speed: integer): boolean; begin if not FDevOpened then Exit(false); Result := CH341SetStream(FDevHandle, %10000001); end; procedure TCH341Hardware.MWDeInit; begin if not FDevOpened then Exit; CH341Set_D5_D0(FDevHandle, 0, 0); end; function TCH341Hardware.MWRead(CS: byte; BufferLen: integer; var buffer: array of byte): integer; var bit_buffer: array of byte; i,j: integer; begin if not FDevOpened then Exit(-1); CH341Set_D5_D0(FDevHandle, %00101001, 1); //cs hi SetLength(bit_buffer, BufferLen*8); FillByte(bit_buffer[0], BufferLen*8, 1); //cs hi if CH341BitStreamSPI(FDevHandle, BufferLen*8, @bit_buffer[0]) then result := BufferLen else result := -1; //читаем биты for i:=0 to BufferLen-1 do begin for j:=0 to 7 do begin if IsBitSet(bit_buffer[(i*8)+j], 7) then //читаем DIN BitSet(1, buffer[i], 7-j) //устанавливаем биты от старшего к младшему else BitSet(0, buffer[i], 7-j); end; end; if Boolean(CS) then CH341Set_D5_D0(FDevHandle, %00101001, 0); end; function TCH341Hardware.MWWrite(CS: byte; BitsWrite: byte; buffer: array of byte): integer; var bit_buffer: array of byte; i,j: integer; begin if not FDevOpened then Exit(-1); if BitsWrite > 0 then begin CH341Set_D5_D0(FDevHandle, %00101001, 1); //cs hi SetLength(bit_buffer, ByteNum(BitsWrite)*8); FillByte(bit_buffer[0], Length(bit_buffer), 1); //cs hi for i:=0 to ByteNum(BitsWrite)-1 do begin for j:=0 to 7 do begin if IsBitSet(buffer[i], 7-j) then //читаем буфер BitSet(1, bit_buffer[(i*8)+j], 5) //устанавливаем биты от старшего к младшему else BitSet(0, bit_buffer[(i*8)+j], 5); end; end; //Отсылаем биты if CH341BitStreamSPI(FDevHandle, BitsWrite, @bit_buffer[0]) then result := BitsWrite else result := -1; if Boolean(CS) then CH341Set_D5_D0(FDevHandle, %00101001, 0); end; end; function TCH341Hardware.MWIsBusy: boolean; var port: byte; begin CH341Set_D5_D0(FDevHandle, %00101001, 0); CH341Set_D5_D0(FDevHandle, %00101001, 1); //cs hi CH341GetStatus(FDevHandle, @port); result := not IsBitSet(port, 7); CH341Set_D5_D0(FDevHandle, %00101001, 0); end; end.
unit Localizer; {$mode objfpc}{$H+} interface function LocalizeString(str:string):string; function SelectLocalized(rus:string; eng:string):string; implementation uses windows; function LocalizeString(str: string): string; begin result:=str; if str = 'stage_dl_masterlist' then begin result:=SelectLocalized('Загрузка мастер-списка...', 'Downloading master-list...'); end else if str = 'stage_parse_masterlist' then begin result:=SelectLocalized('Обработка мастер-списка...', 'Parsing master-list...'); end else if str = 'stage_calc_files' then begin result:=SelectLocalized('Анализ конфигурации...', 'Analyzing current configuration...'); end else if str = 'stage_update_downloader' then begin result:=SelectLocalized('Обновление загрузчика...', 'Updating downloader...'); end else if str = 'stage_dl_content' then begin result:=SelectLocalized('Загрузка файлов мода...', 'Downloading content...'); end else if str = 'stage_run_downloader_update' then begin result:=SelectLocalized('Установка обновления загрузчика...', 'Running update...'); end else if str = 'stage_finalizing' then begin result:=SelectLocalized('Настройка мода...', 'Finalizing...'); end else if str = 'stage_verifying' then begin result:=SelectLocalized('Верификация скачанных файлов...', 'Verifying resources...'); end else if str = 'stage_exiting' then begin result:=SelectLocalized('Завершение работы загрузчика.', 'Exiting updater.'); end else if str = 'err_master_start_dl' then begin result:=SelectLocalized('Не удалось начать загрузку мастер-списка.', 'Can''t start master-list download.'); end else if str = 'err_master_dl' then begin result:=SelectLocalized('Не удалось загрузить мастер-список.', 'Error while downloading master-list.'); end else if str = 'err_maintenance' then begin result:=SelectLocalized('Ведутся технические работы. Пожалуйста, попробуйте позже.', 'Maintenance is in progress, please try again later'); end else if str = 'err_updater_update_dl' then begin result:=SelectLocalized('Не удалось скачать обновление загрузчика.', 'Can''t download update for downloader.'); end else if str = 'err_invalid_masterlist' then begin result:=SelectLocalized('Содержимое мастер-списка повреждено', 'Invalid masterlist content'); end else if str = 'err_masterlist_open' then begin result:=SelectLocalized('Не удалось получить доступ к данным скачанного мастер-списка, проверьте наличие прав и настройки антивируса', 'Downloaded masterlist file is not available. Please check access rights and add the directory to the antivirus exclusions'); end else if str = 'err_cant_start_dl_thread' then begin result:=SelectLocalized('Не удалось начать загрузку', 'Problems while creating downloader thread'); end else if str = 'err_cant_start_calc_thread' then begin result:=SelectLocalized('Не удалось начать анализ конфигурации', 'Problems while creating checker thread'); end else if str = 'err_integrity_check_failure' then begin result:=SelectLocalized('Нарушена целостность скачанных файлов', 'Update integrity check failed.'); end else if str = 'err_bat_copy_fail' then begin result:=SelectLocalized('Не удалось записать BAT-файл для обновления, проверьте настройки антивируса или скопируйте файл с обновлением вручную', 'Can''t write BAT file, please check anti-virus settings or copy the update manually'); end else if str = 'err_cant_run_update' then begin result:=SelectLocalized('Не удалось запустить обновление, проверьте настройки антивируса или запустите обновление вручную', 'Can''t run update, please check anti-virus settings or copy the update manually'); end else if str = 'err_dl_not_successful' then begin result:=SelectLocalized('Загрузка не удалась.', 'Downloading is not successful.'); end else if str = 'err_cant_update_configs' then begin result:=SelectLocalized('Не удалось обновить конфигурационные файлы мода', 'Can''t update configs'); end else if str = 'err_caption' then begin result:=SelectLocalized('Ошибка!', 'Error!'); end else if str = 'err_warning' then begin result:=SelectLocalized('Внимание!', 'Warning!'); end else if str = 'msg_confirm' then begin result:=SelectLocalized('Требуется подтверждение', 'Please confirm'); end else if str = 'msg_congrats' then begin result:=SelectLocalized('Успех', 'Congratulations!'); end else if str = 'msg_select_game_dir' then begin result:=SelectLocalized('Пожалуйста, укажите директорию, в которой установлена оригинальная игра', 'Now please select a directory where the original game is installed'); end else if str = 'msg_no_game_in_dir' then begin result:=SelectLocalized('Похоже, что оригинальная игра НЕ установлена в директории', 'Looks like the game is NOT installed in the selected directory'); end else if str ='msg_continue_anyway' then begin result:=SelectLocalized('Продолжить в любом случае?', 'Continue anyway?'); end else if str ='msg_cancel_install' then begin result:=SelectLocalized('Прекратить установку?', 'Stop updating?'); end else if str ='msg_success_run_game' then begin result:=SelectLocalized('Мод был успешно обновлен. Желаете сыграть прямо сейчас?', 'The mod has been successfully updated. Do you want to run the game?'); end else if str ='msg_noactions_run_game' then begin result:=SelectLocalized('Файлы мода в актуальном состоянии, обновление не требуется. Желаете сыграть прямо сейчас?', 'The mod is in actual state, update is not needed. Do you want to run the game?'); end else if str ='retry_question' then begin result:=SelectLocalized('Попробовать еще раз?', 'Retry?'); end else if str ='next' then begin result:=SelectLocalized('Далее', 'Next'); end else if str ='caption_select_options' then begin result:=SelectLocalized('Выберите желаемые опции:', 'Please select options to install:'); end else if str ='category_downloader_update' then begin result:=SelectLocalized('Загрузчик обновлений мода (после его обновления будут запущены поиск и установка других обновлений для мода)', 'Mod updater (after its update we will start the search and installation of other updates)'); end else if str ='category_update_conflict_resolve' then begin result:=SelectLocalized('Разрешение конфликта установленных дополнений', 'Resolving conflict of installed addons'); end; end; function SelectLocalized(rus: string; eng: string): string; var locale:cardinal; const RUS_ID:cardinal=1049; begin locale:=GetSystemDefaultLangID(); if locale = RUS_ID then begin result:=rus; end else begin result:=eng; end; end; end.
(* Category: SWAG Title: STRING HANDLING ROUTINES Original name: 0008.PAS Description: ST-CASE2.PAS (Lowercase) Author: SWAG SUPPORT TEAM Date: 05-28-93 13:58 *) Function DnCase(Ch: Char): Char; Var n : Byte Absolute ch; begin Case ch of 'A'..'Z': n := n or 32; end; DnCase := chr(n); end; BEGIN Write( DnCase('A') ); END.
unit MT5.Connect; interface uses System.SysUtils, System.Net.Socket, System.Types, System.Classes, MT5.Protocol, MT5.RetCode, MT5.Utils, MT5.Types, System.SyncObjs; type TMTConnect = class private { private declarations } var FSocket: TSocket; FSocketRead: TSocket; FSocketWrite: TSocket; FSocketError: TSocket; FIPMT5: string; FPortMT5: Word; FTimeoutConnection: Integer; FCryptRand: string; FClientCommand: Integer; FIsCrypt: Boolean; FReadFDSet: PFDSet; FWriteFDSet: PFDSet; FErrorFDSet: PFDSet; const MAX_CLIENT_COMMAND = 16383; function CreateConnection: TMTRetCodeType; function ReadPacket(out AHeader: TMTHeaderProtocol): TArray<Byte>; protected { protected declarations } public { public declarations } constructor Create(AIPMT5: string; APortMT5: Word; const ATimeoutConnection: Integer = 5; AIsCrypt: Boolean = True); destructor Destroy; override; function Connect: TMTRetCodeType; procedure Disconnect; function Send(ACommand: string; AData: TArray<TMTQuery>; const AFirstRequest: Boolean = False): Boolean; function Read(const AAuthPacket: Boolean = False; AIsBinary: Boolean = False): TArray<Byte>; procedure SetCryptRand(ACrypt, APassword: string); end; implementation { TMTConnect } function TMTConnect.Connect: TMTRetCodeType; begin Result := CreateConnection; end; constructor TMTConnect.Create(AIPMT5: string; APortMT5: Word; const ATimeoutConnection: Integer; AIsCrypt: Boolean); begin FIPMT5 := AIPMT5; FPortMT5 := APortMT5; FTimeoutConnection := ATimeoutConnection; FIsCrypt := AIsCrypt; FClientCommand := 0; FSocket := nil; end; function TMTConnect.CreateConnection: TMTRetCodeType; begin try FSocket := TSocket.Create(TSocketType.TCP); FSocketRead := TSocket.Create(TSocketType.TCP); FSocketWrite := TSocket.Create(TSocketType.TCP); FSocketError := TSocket.Create(TSocketType.TCP); except Exit(TMTRetCodeType.MT_RET_ERR_NETWORK) end; try FSocket.Connect('', FIPMT5, '', FPortMT5); FSocketRead.Connect('', FIPMT5, '', FPortMT5); FSocketWrite.Connect('', FIPMT5, '', FPortMT5); FSocketError.Connect('', FIPMT5, '', FPortMT5); FReadFDSet := TFDSet.Create([FSocketRead]); FWriteFDSet := TFDSet.Create([FSocketWrite]); FErrorFDSet := TFDSet.Create([FSocketError]); case FSocket.Select(FReadFDSet, FWriteFDSet, FErrorFDSet, FTimeoutConnection) of TWaitResult.wrTimeout: Exit(TMTRetCodeType.MT_RET_ERR_TIMEOUT); TWaitResult.wrError: Exit(TMTRetCodeType.MT_RET_ERR_CONNECTION); end; except Exit(TMTRetCodeType.MT_RET_ERR_CONNECTION) end; Exit(TMTRetCodeType.MT_RET_OK) end; destructor TMTConnect.Destroy; begin if FSocketRead <> nil then FreeAndNil(FSocketRead); if FSocketWrite <> nil then FreeAndNil(FSocketWrite); if FSocketError <> nil then FreeAndNil(FSocketError); if FSocket <> nil then FreeAndNil(FSocket); inherited; end; procedure TMTConnect.Disconnect; begin if not Assigned(FSocket) then Exit; if not(TSocketState.Connected in FSocket.State) then Exit; FSocket.Close; end; function TMTConnect.Read(const AAuthPacket: Boolean; AIsBinary: Boolean): TArray<Byte>; var LData: TArray<Byte>; LHeader: TMTHeaderProtocol; begin if not Assigned(FSocket) then Exit(); if not(TSocketState.Connected in FSocket.State) then Exit(); Result := []; try while True do begin LData := ReadPacket(LHeader); if LHeader = nil then Break; if (FIsCrypt) and (not AAuthPacket) then begin { TODO -oCarlos -cImplement : Call DeCryptPacket } end; Result := Result + LData; if LHeader.Flag = 0 then Break; end; finally if LHeader <> nil then FreeAndNil(LHeader); end; if AIsBinary then begin { TODO -oCarlos -cImplement : Implement binary } end; end; function TMTConnect.ReadPacket(out AHeader: TMTHeaderProtocol): TArray<Byte>; var LReceiveData: TArray<Byte>; LRemainingData: TArray<Byte>; LData: TArray<Byte>; LCountRead: Integer; LNeedLen: Integer; LHeader: TMTHeaderProtocol; begin LHeader := nil; LData := []; LRemainingData := []; LNeedLen := 0; repeat Sleep(500); LCountRead := FSocket.Receive(LReceiveData, -1, [TSocketFlag.PEEK]); Sleep(500); FSocket.Receive(LReceiveData, LCountRead, [TSocketFlag.WAITALL]); if LCountRead = 0 then Break; LRemainingData := LRemainingData + LReceiveData; repeat if LNeedLen <= Length(LData) then begin if LHeader <> nil then FreeAndNil(LHeader); LHeader := TMTHeaderProtocol.GetHeader(LRemainingData); LNeedLen := LNeedLen + LHeader.SizeBody; LRemainingData := Copy(LRemainingData, TMTHeaderProtocol.HEADER_LENGTH, Length(LRemainingData) - TMTHeaderProtocol.HEADER_LENGTH); end; LData := LData + Copy(LRemainingData, 0, LHeader.SizeBody); LRemainingData := Copy(LRemainingData, LHeader.SizeBody, TMTHeaderProtocol.HEADER_LENGTH + Length(LRemainingData) - LHeader.SizeBody); if (Length(LData) = LHeader.SizeBody) then Break; if (LNeedLen = Length(LData)) then Break; if Length(LRemainingData) = 0 then Break; until (not True); if (LNeedLen = Length(LData)) and (Length(LRemainingData) = 0) then Break; if LHeader.Flag = 0 then Break; until (not True); AHeader := LHeader; Result := LData; end; function TMTConnect.Send(ACommand: string; AData: TArray<TMTQuery>; const AFirstRequest: Boolean): Boolean; var LQueryTemp: string; LQueryBody: TArray<Byte>; LBodyRequest: string; I: Integer; LHeaderString: string; LHeader: TArray<Byte>; LQuery: TArray<Byte>; LSendResult: Integer; begin Result := False; if not Assigned(FSocket) then Exit(False); if not(TSocketState.Connected in FSocket.State) then Exit(False); Inc(FClientCommand); if FClientCommand > MAX_CLIENT_COMMAND then FClientCommand := 1; LQueryTemp := ACommand; if Length(AData) > 0 then begin LQueryTemp := LQueryTemp + '|'; LBodyRequest := EmptyStr; for I := Low(AData) to High(AData) do begin if AData[I].Key = TMTProtocolConsts.WEB_PARAM_BODYTEXT then LBodyRequest := AData[I].Value else LQueryTemp := LQueryTemp + AData[I].Key + '=' + TMTUtils.Quotes(AData[I].Value) + '|' end; LQueryTemp := LQueryTemp + #13#10; if not LBodyRequest.IsEmpty then LQueryTemp := LQueryTemp + LBodyRequest; end else LQueryTemp := LQueryTemp + '|'#13#10; LQueryBody := TEncoding.Unicode.GetBytes(LQueryTemp); if (AFirstRequest) then LHeaderString := Format(TMTProtocolConsts.WEB_PREFIX_WEBAPI, [Length(LQueryBody), FClientCommand]) else LHeaderString := Format(TMTProtocolConsts.WEB_PACKET_FORMAT, [Length(LQueryBody), FClientCommand]); LHeader := TEncoding.ASCII.GetBytes(LHeaderString + '0'); LQuery := LHeader + LQueryBody; LSendResult := FSocket.Send(LQuery); Sleep(500); if LSendResult = Length(LQuery) then Result := True; end; procedure TMTConnect.SetCryptRand(ACrypt, APassword: string); var LOut: TArray<Byte>; I: Integer; begin FCryptRand := ACrypt; LOut := TMTUtils.GetMD5( TMTUtils.GetMD5( TEncoding.Unicode.GetBytes(APassword) + TEncoding.UTF8.GetBytes(TMTProtocolConsts.WEB_API_WORD) ) ); for I := 0 to 15 do begin LOut := TMTUtils.GetMD5( TMTUtils.GetFromHex( Copy(FCryptRand, I * 32, 32) ) + TMTUtils.GetFromHex(TMTUtils.GetHex(LOut)) ); end; end; end.
{----------------------------------------------------------------------------- Unit Name: frmPrefs Author: HochwimmerA Purpose: glData Preferences $Id: frmPrefs.pas,v 1.37 2004/07/08 09:50:58 hochwimmera Exp $ -----------------------------------------------------------------------------} unit frmPrefs; interface uses Windows,Messages,SysUtils,Variants,Classes,Graphics,Controls,Forms,Dialogs, StdCtrls, Buttons, ComCtrls, ExtCtrls, ImgList, // gldata Component Library geFloatEdit,geIntegerEdit; type TFormPreferences = class(TForm) bCancel: TBitBtn; bLoadArcInfoCLR: TButton; bLoadDataCLR: TButton; bLoadSurferCLR: TButton; bLoadVectorDataCLR: TButton; bOK: TBitBtn; bResetScale: TButton; bUpdate: TBitBtn; cbArcInfoColourMode: TComboBox; cbArcInfoPolygonMode: TComboBox; cbCameraStyle: TComboBox; cbLineMode: TComboBox; cbSurferColourMode : TComboBox; cbSurferPolygonMode : TComboBox; cbxAutoCenterPoints: TCheckBox; cbxArcInfoTwoSided: TCheckBox; cbxAutoCenterGrids: TCheckBox; cbxAutoProcess: TCheckBox; cbxColourScaleBorder: TCheckBox; cbxColourScaleContinous: TCheckBox; cbxColourScaleShowContours: TCheckBox; cbxDisplayAxes: TCheckBox; cbxDisplayLine: TCheckBox; cbxDisplayMarkers: TCheckBox; cbxDisplayPoints: TCheckBox; cbxFocusStatusBar: TCheckBox; cbxLightingShining: TCheckBox; cbxPointWireFrame: TCheckBox; cbxPromptTexArcInfo: TCheckBox; cbxPromptTexSurfer: TCheckBox; cbxShowColourScale: TCheckBox; cbxShowHUDScale: TCheckBox; cbxShowPipes: TCheckBox; cbxSurferTwoSided: TCheckBox; cbxTwoSideLighting: TCheckBox; ColourDialog: TColorDialog; ebArcInfoCLRFile: TEdit; ebDataCLRFile: TEdit; ebSurferCLRFile: TEdit; geArcInfoAlpha: TGEFloatEdit; geColourScaleAlpha: TGEFloatEdit; geDepthOfView: TGEFloatEdit; geFocalLength: TGEFloatEdit; geScaleX: TGEFloatEdit; geScaleY: TGEFloatEdit; geScaleZ: TGEFloatEdit; geSurferAlpha: TGEFloatEdit; geTileArcInfoX: TGEIntegerEdit; geTileArcInfoY: TGEIntegerEdit; geTileSurferX: TGEIntegerEdit; geTileSurferY: TGEIntegerEdit; geVectorMinLength: TGEFloatEdit; ImageList: TImageList; lblArcInfoBaseMap: TLabel; lblArcInfoBlankedColour: TLabel; lblArcInfoCLRFile: TLabel; lblArcInfoMaxColour: TLabel; lblArcInfoMinColour: TLabel; lblArcInfoPalette: TLabel; lblArcInfoPolygonMode: TLabel; lblArcInfoSingleColour: TLabel; lblCameraDepthOfView: TLabel; lblCameraStyle: TLabel; lblColourLine: TLabel; lblColourPoint: TLabel; lblDataCLRFile: TLabel; lblFocalLength: TLabel; lblLineMode: TLabel; lblPipeRadius: TLabel; lblPointColour: TLabel; lblPointNullColour: TLabel; lblPointMaxColour: TLabel; lblPointMinColour: TLabel; lblPointRadius: TLabel; lblScalarOptions: TLabel; lblScaleX: TLabel; lblScaleY: TLabel; lblScaleZ: TLabel; lblSurferAlpha: TLabel; lblSurferBaseMap: TLabel; lblSurferBlankedColour: TLabel; lblSurferCLRFile: TLabel; lblSurferMaxColour: TLabel; lblSurferMinColour: TLabel; lblSurferPalette: TLabel; lblSurferPolygonMode: TLabel; lblSurferSingleColour: TLabel; lblTileArcInfoY: TLabel; lblTileArcInfoX: TLabel; lblTileSurferX: TLabel; lblTileSurferY: TLabel; lblVectorDataCLRFile: TLabel; OpenDialogCLR: TOpenDialog; pcPreferences: TPageControl; pnlArcInfoBlankedColour: TPanel; pnlArcInfoColour: TPanel; pnlArcInfoMaxColour: TPanel; pnlArcInfoMinColour: TPanel; pnlBackgroundColour: TPanel; pnlColourLine: TPanel; pnlColourSetting: TPanel; pnlLeft: TPanel; pnlMaxPointColour: TPanel; pnlMinPointColour: TPanel; pnlNullPointColour: TPanel; pnlOptions: TPanel; pnlSurferBlankedColour: TPanel; pnlSurferColour: TPanel; pnlSurferMinColour: TPanel; pnlSurferMaxColour: TPanel; rgArcInfoOptions: TRadioGroup; rgPointOptions: TRadioGroup; rgSurferOptions: TRadioGroup; tsArcInfo: TTabSheet; tsAxes: TTabSheet; tsCamera: TTabSheet; tsData: TTabSheet; tsDisplay: TTabSheet; tsGeneral: TTabSheet; tsGrids: TTabSheet; tsHUD: TTabSheet; tsInterface: TTabSheet; tsLighting: TTabSheet; tsLines: TTabSheet; tsMarkers: TTabSheet; tsPipes: TTabSheet; tsScale: TTabSheet; tsSurfer: TTabSheet; tvPrefs: TTreeView; lblColourScaleAlpha: TLabel; pnlSinglePointColour: TPanel; lblPointSingleColour: TLabel; cbColourScaleType: TComboBox; ebScaleLabelFormat: TEdit; lblScaleLabelFormat: TLabel; cbxSurferSilentImport: TCheckBox; lblImportSurfer: TLabel; cbxSurferSilentLoad: TCheckBox; tsVectorData: TTabSheet; lblVectorOptions: TLabel; rgVectorDataOptions: TRadioGroup; lblVectorMaxColour: TLabel; lblVectorMinColour: TLabel; lblVectorSingleColour: TLabel; pnlSingleVectorColour: TPanel; pnlMinVectorColour: TPanel; pnlMaxVectorColour: TPanel; ebVectorDataCLRFile: TEdit; cbxRenderNullPoints: TCheckBox; cbxInvertMouseWheel: TCheckBox; cbxCameraStatusBar: TCheckBox; lblVectorScaleOptions: TLabel; bArrowLengthSync: TButton; lblVectorMinLength: TLabel; lblVectorMaxLength: TLabel; lblVectorMinArrowRadius: TLabel; lblVectorMaxArrowRadius: TLabel; bArrowHeadRadiusSync: TButton; lblVectorArrowHeadRadius: TLabel; lblVectorMinRadius: TLabel; lblVectorMaxRadius: TLabel; bArrowRadiusSync: TButton; Label4: TLabel; lblVectorMaxArrowLength: TLabel; lblVectorMinArrowLength: TLabel; Label5: TLabel; bArrowHeadLengthSync: TButton; Label2: TLabel; geMarkerRadius: TGEFloatEdit; gePipeRadius: TGEFloatEdit; geVectorMaxLength: TGEFloatEdit; geVectorMinRadius: TGEFloatEdit; geVectorMaxRadius: TGEFloatEdit; geVectorMaxArrowLength: TGEFloatEdit; geVectorMinArrowLength: TGEFloatEdit; geVectorMinArrowRadius: TGEFloatEdit; geVectorMaxArrowRadius: TGEFloatEdit; geVectorSlices: TGEIntegerEdit; geVectorStacks: TGEIntegerEdit; lblVectorSlices: TLabel; lblVectorStacks: TLabel; geCameraNearPlaneBias: TGEFloatEdit; lblCameraNearPlaneBias: TLabel; cbPointStyle: TComboBox; lblPointStyle: TLabel; tsGeothermal: TTabSheet; rgGeothermalOptions: TRadioGroup; bLoadGeothermalCLR: TButton; lblGeothermalCLR: TLabel; ebGeothermalCLRFile: TEdit; lblGeothermalMaxColour: TLabel; pnlGeothermalMaxColour: TPanel; lblGeothermalMinColour: TLabel; pnlGeothermalMinColour: TPanel; lblGeothermalSingleColour: TLabel; pnlGeothermalColour: TPanel; lblImportArcInfo: TLabel; cbxArcInfoSilentImport: TCheckBox; cbxArcInfoSilentLoad: TCheckBox; cbAntialiasing: TComboBox; lblAntialiasing: TLabel; sbModified: TStatusBar; tsScalarBox: TTabSheet; tsVectorBox: TTabSheet; lblScalarBoundingColour: TLabel; pnlScalarBoundingColour: TPanel; lblScalarBB: TLabel; pnlVectorBoundingColour: TPanel; lblVectorBoxLineColour: TLabel; lblVectorBB: TLabel; cbxVectorAA: TCheckBox; cbxVectorSmooth: TCheckBox; lblVectorBoxLinePattern: TLabel; geVectorLinePattern: TGEIntegerEdit; cbxScalarAA: TCheckBox; cbxScalarSmooth: TCheckBox; lblScalarBoxLinePattern: TLabel; geScalarLinePattern: TGEIntegerEdit; cbxSurferCreateVisible: TCheckBox; cbxLighting2Shining: TCheckBox; cbxHUDScaleSteps: TCheckBox; geHUDPoints: TGEIntegerEdit; cbShadeModel: TComboBox; lblShadeModel: TLabel; procedure bCancelClick(Sender: TObject); procedure bLoadArcInfoCLRClick(Sender: TObject); procedure bLoadDataCLRClick(Sender: TObject); procedure bLoadSurferCLRClick(Sender: TObject); procedure bOKClick(Sender: TObject); procedure bResetScaleClick(Sender: TObject); procedure bUpdateClick(Sender: TObject); procedure cbxArcInfoTwoSidedClick(Sender: TObject); procedure cbxSurferTwoSidedClick(Sender: TObject); procedure ebArcInfoCLRFileChange(Sender: TObject); procedure ebSurferCLRFileChange(Sender: TObject); procedure pnlArcInfoBlankedColourClick(Sender: TObject); procedure pnlArcInfoColourClick(Sender: TObject); procedure pnlArcInfoMaxColourClick(Sender: TObject); procedure pnlArcInfoMinColourClick(Sender: TObject); procedure pnlBackgroundColourClick(Sender: TObject); procedure pnlColourLineClick(Sender: TObject); procedure pnlColourSettingClick(Sender: TObject); procedure pnlMaxPointColourClick(Sender: TObject); procedure pnlMinPointColourClick(Sender: TObject); procedure pnlNullPointColourClick(Sender: TObject); procedure pnlSurferColourClick(Sender: TObject); procedure pnlSurferMaxColourClick(Sender: TObject); procedure pnlSurferMinColourClick(Sender: TObject); procedure pnlSurferBlankedColourClick(Sender: TObject); procedure tvPrefsClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure pnlSinglePointColourClick(Sender: TObject); procedure ebDataCLRFileChange(Sender: TObject); procedure pnlSingleVectorColourClick(Sender: TObject); procedure pnlMinVectorColourClick(Sender: TObject); procedure pnlMaxVectorColourClick(Sender: TObject); procedure bArrowLengthSyncClick(Sender: TObject); procedure bArrowHeadRadiusSyncClick(Sender: TObject); procedure bArrowRadiusSyncClick(Sender: TObject); procedure bArrowHeadLengthSyncClick(Sender: TObject); procedure UpdateModifiedOnly(Sender: TObject); procedure UpdateGeothermalModified(Sender:TObject); procedure UpdatedModifiedOnly(Sender: TObject); procedure UpdatedSurferModified(Sender: TObject); procedure bLoadVectorDataCLRClick(Sender: TObject); procedure ebVectorDataCLRFileChange(Sender: TObject); procedure bLoadGeothermalCLRClick(Sender: TObject); procedure ebGeothermalCLRFileChange(Sender: TObject); procedure pnlGeothermalColourClick(Sender: TObject); procedure pnlGeothermalMinColourClick(Sender: TObject); procedure pnlGeothermalMaxColourClick(Sender: TObject); procedure pnlScalarBoundingColourClick(Sender: TObject); procedure pnlVectorBoundingColourClick(Sender: TObject); private bModifiedArcInfo : boolean; bModifiedSurfer: boolean; bModifiedGeothermal : boolean; bUpdateMe : boolean; procedure SetArcInfoModified; procedure SetGeothermalModified; procedure SetSurferModified; procedure SetModified; procedure UpdateColour(pnl:TPanel;iMode:integer); public bContinue : boolean; bLoading : boolean; function IsArcInfoModified:boolean; function IsGeothermalModified:boolean; function IsSurferModified:boolean; end; implementation {$R *.dfm} // ----- TformPreferences.UpdateColour ----------------------------------------- procedure TformPreferences.UpdateColour(pnl:TPanel;iMode:integer); begin with ColourDialog do begin Color := pnl.Color; if Execute then begin pnl.Color := Color; case iMode of 1: SetModified; 2: SetSurferModified; 3: SetArcInfoModified; 4: SetGeothermalModified; end; end; end; end; // ----- TformPreferences.bCancelClick ----------------------------------------- procedure TformPreferences.bCancelClick(Sender: TObject); begin bContinue := false; end; // ----- TformPreferences.bLoadArcInfoCLRClick --------------------------------- procedure TformPreferences.bLoadArcInfoCLRClick(Sender: TObject); begin if OpenDialogCLR.Execute then ebArcInfoCLRFile.Text := OpenDialogCLR.FileName; end; // ----- TformPreferences.bLoadDataCLRClick ------------------------------------ procedure TformPreferences.bLoadDataCLRClick(Sender: TObject); begin if OpenDialogCLR.Execute then ebDataCLRFile.Text := OpenDialogCLR.FileName; end; // ----- TformPreferences.bLoadSurferCLRClick ---------------------------------- procedure TformPreferences.bLoadSurferCLRClick(Sender: TObject); begin if OpenDialogCLR.Execute then ebSurferCLRFile.Text := OpenDialogCLR.FileName; end; // ----- TformPreferences.bOKClick --------------------------------------------- procedure TformPreferences.bOKClick(Sender: TObject); begin bContinue := false; end; // ----- TformPreferences.bResetScaleClick ------------------------------------- procedure TformPreferences.bResetScaleClick(Sender: TObject); begin { geScaleX.Value := 1.0; geScaleY.Value := 1.0; geScaleZ.Value := 1.0; } end; // ----- TformPreferences.bUpdateClick ----------------------------------------- procedure TformPreferences.bUpdateClick(Sender: TObject); begin bContinue := true; bUpdateMe := true; end; // ----- TformPreferences.cbxArcInfoTwoSidedClick ------------------------------ procedure TformPreferences.cbxArcInfoTwoSidedClick(Sender: TObject); begin SetArcInfoModified; end; // ----- TformPreferences.cbxSurferTwoSidedClick ------------------------------- procedure TformPreferences.cbxSurferTwoSidedClick(Sender: TObject); begin SetSurferModified; end; // ----- TformPreferences.ebArcInfoCLRFileChange ------------------------------- procedure TformPreferences.ebArcInfoCLRFileChange(Sender: TObject); begin if (not FileExists(ebArcInfoCLRFile.Text)) then ebArcInfoCLRFile.Color := clInfoBk else ebArcInfoCLRFile.Color := clWindow; SetArcInfoModified; end; // ----- TformPreferences.ebSurferCLRFileChange -------------------------------- procedure TformPreferences.ebSurferCLRFileChange(Sender: TObject); begin if not FileExists(ebSurferCLRFile.Text) then ebSurferCLRFile.Color := clInfoBk else ebSurferCLRFile.Color := clWindow; SetSurferModified; end; // ----- TformPreferences.pnlArcInfoBlankedColourClick ------------------------- procedure TformPreferences.pnlArcInfoBlankedColourClick(Sender: TObject); begin UpdateColour(pnlArcInfoBlankedColour,3); end; // ----- TformPreferences.pnlArcInfoColourClick -------------------------------- procedure TformPreferences.pnlArcInfoColourClick(Sender: TObject); begin UpdateColour(pnlArcInfoColour,3); end; // ----- TformPreferences.pnlArcInfoMaxColourClick ----------------------------- procedure TformPreferences.pnlArcInfoMaxColourClick(Sender: TObject); begin UpdateColour(pnlArcInfoMaxColour,3); end; // ----- TformPreferences.pnlArcInfoMinColourClick ----------------------------- procedure TformPreferences.pnlArcInfoMinColourClick(Sender: TObject); begin UpdateColour(pnlArcInfoMinColour,3); end; // ----- TformPreferences.pnlBackgroundColourClick ----------------------------- procedure TformPreferences.pnlBackgroundColourClick(Sender: TObject); begin UpdateColour(pnlBackgroundColour,1); end; // ----- TformPreferences.pnlColourLineClick ----------------------------------- procedure TformPreferences.pnlColourLineClick(Sender: TObject); begin UpdateColour(pnlColourLine,1); end; // ----- TformPreferences.pnlColourSettingClick -------------------------------- procedure TformPreferences.pnlColourSettingClick(Sender: TObject); begin UpdateColour(pnlColourSetting,1); end; // ----- TformPreferences.pnlMaxPointColourClick ------------------------------- procedure TformPreferences.pnlMaxPointColourClick(Sender: TObject); begin UpdateColour(pnlMaxPointColour,1); end; // ----- TformPreferences.pnlMinPointColourClick ------------------------------- procedure TformPreferences.pnlMinPointColourClick(Sender: TObject); begin UpdateColour(pnlMinPointColour,1); end; // ----- TformPreferences.pnlNullPointColourClick ------------------------------ procedure TformPreferences.pnlNullPointColourClick(Sender: TObject); begin UpdateColour(pnlNullPointColour,1); end; // ----- TformPreferences.pnlSinglePointColourClick ---------------------------- procedure TformPreferences.pnlSinglePointColourClick(Sender: TObject); begin UpdateColour(pnlSinglePointColour,1); end; // ----- TformPreferences.pnlSurferBlankedColourClick -------------------------- procedure TformPreferences.pnlSurferBlankedColourClick(Sender: TObject); begin UpdateColour(pnlSurferBlankedColour,2); end; // ----- TformPreferences.pnlSurferColourClick --------------------------------- procedure TformPreferences.pnlSurferColourClick(Sender: TObject); begin UpdateColour(pnlSurferColour,2); end; // ----- TformPreferences.pnlSurferMaxColourClick ------------------------------ procedure TformPreferences.pnlSurferMaxColourClick(Sender: TObject); begin UpdateColour(pnlSurferMaxColour,2); end; // ----- TformPreferences.pnlSurferMinColourClick ------------------------------ procedure TformPreferences.pnlSurferMinColourClick(Sender: TObject); begin UpdateColour(pnlSurferMinColour,2); end; // ----- TformPreferences.tvPrefsClick ----------------------------------------- procedure TformPreferences.tvPrefsClick(Sender: TObject); begin if (tvPrefs.Selected.Text = 'General') then pcPreferences.ActivePage := tsGeneral else if (tvPrefs.Selected.Text = 'Interface') then pcPreferences.ActivePage := tsInterface else if (tvPrefs.Selected.Text = 'Display') then pcPreferences.ActivePage := tsDisplay else if (tvPrefs.Selected.Text = 'Axes') then pcPreferences.ActivePage := tsAxes else if (tvPrefs.Selected.Text = 'Markers') then pcPreferences.ActivePage := tsMarkers else if (tvPrefs.Selected.Text = 'Pipe') then pcPReferences.ActivePage := tsPipes else if (tvPrefs.Selected.Text = 'Lines') then pcPreferences.ActivePage := tsLines else if (tvPrefs.Selected.Text = 'Grids') then pcPreferences.ActivePage := tsGrids else if (tvPrefs.Selected.Text = 'Surfer') then pcPreferences.ActivePage := tsSurfer else if (tvPrefs.Selected.Text = 'ESRI ArcInfo') then pcPreferences.ActivePage := tsArcInfo else if (tvPrefs.Selected.Text = 'Camera') then pcPreferences.ActivePage := tsCamera else if (tvPrefs.Selected.Text = 'Scalar Data') then pcPreferences.ActivePage := tsData else if (tvPrefs.Selected.Text = 'Vector Data') then pcPreferences.ActivePage := tsVectorData else if (tvPrefs.Selected.Text = 'Lighting') then pcPreferences.ActivePage := tsLighting else if (tvPrefs.Selected.Text = 'HUD') then pcPreferences.ActivePage := tsHUD else if (tvPrefs.Selected.Text = 'Scale') then pcPreferences.ActivePage := tsScale else if (tvPrefs.Selected.Text = 'Geothermal') then pcPreferences.ActivePage := tsGeothermal else if (tvPrefs.Selected.text = 'Scalar Box') then pcPreferences.ActivePage := tsScalarBox else if (tvPRefs.Selected.Text ='Vector Box') then pcPreferences.ActivePage := tsVectorBox; end; // ----- TformPreferences.FormClose -------------------------------------------- procedure TformPreferences.FormClose(Sender: TObject; var Action: TCloseAction); begin // check for null entries for Edits { if (gePipeRadius.IsNull or geSurferAlpha.IsNull or geTileSurferX.IsNull or geTileSurferY.IsNull or geVectorMinLength.IsNull or geVectorMaxLength.IsNull or geVectorMinRadius.IsNull or geVectorMaxRadius.IsNull or geVectorMinArrowLength.IsNull or geVectorMaxArrowLength.IsNull or geVectorMinArrowRadius.IsNull or geVectorMaxArrowRadius.IsNull) then begin MessageDlg('NULL entries for numerical edit boxes are not allowed!',mtError, [mbOK],0); Action := caNone; end else begin if (geVectorMinLength.Value > geVectorMaxLength.Value) then geVectorMinLength.Value := geVectorMaxLength.Value; if (geVectorMinRadius.Value > geVectorMaxRadius.Value) then geVectorMinRadius.Value := geVectorMaxRadius.Value; if (geVectorMinArrowLength.Value > geVectorMaxArrowLength.Value) then geVectorMinArrowLength.Value := geVectorMaxArrowLength.Value; if (geVectorMinArrowRadius.Value > geVectorMaxArrowRadius.Value) then geVectorMinArrowRadius.Value := geVectorMaxArrowRadius.Value; if not bUpdateMe then bContinue := false; end; } end; // ----- TformPreferences.FormShow --------------------------------------------- procedure TformPreferences.FormShow(Sender: TObject); var sExePath,sCLRPath : string; i:integer; begin bLoading := true; // set up the spectrum path - where the CLR files should be sExePath := ExtractFilePath(ParamStr(0)); sCLRpath := sExePath + '\spectrums'; if DirectoryExists(sCLRPath) then OpenDialogCLR.InitialDir := sCLRPath else OpenDialogCLR.InitialDir := sExePath; bModifiedSurfer := false; bModifiedArcInfo := false; bModifiedGeothermal := false; bUpdateMe := false; with sbModified do begin Panels[0].Text := ''; Panels[1].Text := ''; Panels[2].text := ''; Panels[3].Text := ''; end; tvPrefs.FullExpand; for i:=0 to tvPrefs.Items.Count-1 do begin tvPrefs.Items[i].ImageIndex := 0; tvPrefs.Items[i].SelectedIndex := 1; end; // set the colour of the path accordingly ebSurferCLRFileChange(nil); ebArcInfoCLRFileChange(nil); ebDataCLRFileChange(nil); ebGeothermalCLRFileChange(nil); bLoading := false; end; // ----- TformPreferences.UpdatedArcInfoModified ------------------------------- procedure TformPreferences.UpdateModifiedOnly(Sender:TObject); begin SetArcInfoModified; end; // ----- TformPreferences.UpdateGeothermalModified ----------------------------- procedure TformPreferences.UpdateGeothermalModified(Sender:TObject); begin SetGeothermalModified; end; // ----- TformPreferences.UpdatedModifiedOnly ---------------------------------- procedure TformPreferences.UpdatedModifiedOnly(Sender: TObject); begin SetModified; end; // ----- TformPreferences.UpdatedSurferModified -------------------------------- procedure TformPreferences.UpdatedSurferModified(Sender: TObject); begin SetSurferModified; end; // ----- TformPreferences.SetArcInfoModified ----------------------------------- procedure TFormPreferences.SetArcInfoModified; begin if not (bLoading) and not bModifiedArcInfo then begin sbModified.Panels[0].text := 'Modified'; sbModified.Panels[2].text := 'ArcInfo Modified'; bModifiedArcInfo := true; tvPrefs.Items[15].ImageIndex := 2; tvPrefs.Items[15].SelectedIndex := 3; tvPrefs.Items[17].ImageIndex := 2; tvPrefs.Items[17].SelectedIndex := 3; tvPrefs.Invalidate; end; end; // ----- TformPreferences.SetGeothermalModified -------------------------------- procedure TFormPreferences.SetGeothermalModified; begin if not (bLoading) and not bModifiedArcInfo then begin sbModified.Panels[0].text := 'Modified'; sbModified.Panels[3].text := 'Geothermal Modified'; bModifiedGeothermal := true; tvPrefs.Items[18].ImageIndex := 2; tvPrefs.Items[18].SelectedIndex := 3; tvPrefs.Invalidate; end; end; // ----- TformPreferences.SetSurferModified ------------------------------------ procedure TFormPreferences.SetSUrferModified; var i:integer; begin if not (bLoading) and not bModifiedSurfer then begin sbModified.Panels[0].text := 'Modified'; sbModified.Panels[1].text := 'Surfer Modified'; bModifiedSurfer := true; for i:=15 to 16 do begin tvPrefs.Items[i].ImageIndex := 2; tvPrefs.Items[i].SelectedIndex := 3; end; tvPrefs.Invalidate; end; end; // ----- TformPreferences.SetModified ------------------------------------------ procedure TFormPreferences.SetModified; begin if not bLoading then sbModified.Panels[0].Text := 'Modified'; end; // ----- TFormPreferences.IsArcInfoModified ------------------------------------ function TFormPreferences.IsArcInfoModified:boolean; begin result := bModifiedArcInfo; end; // ----- TformPreferences.IsGeothermalModified --------------------------------- function TformPreferences.IsGeothermalModified:boolean; begin result := bModifiedGeothermal; end; // ----- TFormPreferences.IsSurferModified ------------------------------------- function TFormPreferences.IsSurferModified:boolean; begin result := bModifiedSurfer; end; // ----- TformPreferences.ebDataCLRFileChange ---------------------------------- procedure TformPreferences.ebDataCLRFileChange(Sender: TObject); begin if not FileExists(ebDataCLRFile.Text) then ebDataCLRFile.Color := clInfoBk else ebDataCLRFile.Color := clWindow; end; // ----- TformPreferences.pnlSingleVectorColourClick --------------------------- procedure TformPreferences.pnlSingleVectorColourClick(Sender: TObject); begin UpdateColour(pnlSingleVectorColour,1); end; // ----- TformPreferences.pnlMinVectorColourClick ------------------------------ procedure TformPreferences.pnlMinVectorColourClick(Sender: TObject); begin UpdateColour(pnlMinVectorColour,1); end; // ----- TformPreferences.pnlMaxVectorColourClick ------------------------------ procedure TformPreferences.pnlMaxVectorColourClick(Sender: TObject); begin UpdateColour(pnlMaxVectorColour,1); end; // ----- TformPreferences.bLengthSyncClick ------------------------------------- procedure TformPreferences.bArrowLengthSyncClick(Sender: TObject); begin ///geVectorMinlength.Value := geVectorMaxLength.Value; end; // ----- TformPreferences.bArrowRadiusSyncClick -------------------------------- procedure TformPreferences.bArrowRadiusSyncClick(Sender: TObject); begin ///geVectorMinRadius.Value := geVectorMaxRadius.Value; end; // ----- TformPreferences.bArrowHeadRadiusSyncClick ---------------------------- procedure TformPreferences.bArrowHeadRadiusSyncClick(Sender: TObject); begin geVectorMinArrowRadius.Value := geVectorMaxArrowRadius.Value; end; // ----- TformPreferences.bArrowHeadLengthSyncClick ---------------------------- procedure TformPreferences.bArrowHeadLengthSyncClick(Sender: TObject); begin ///geVectorMinArrowLength.Value := geVectorMaxArrowLength.Value; end; // ----- TformPreferences.bLoadVectorDataCLRClick ------------------------------ procedure TformPreferences.bLoadVectorDataCLRClick(Sender: TObject); begin if OpenDialogCLR.Execute then ebVectorDataCLRFile.Text := OpenDialogCLR.FileName; end; // ----- TformPreferences.ebVectorDataCLRFileChange ---------------------------- procedure TformPreferences.ebVectorDataCLRFileChange(Sender: TObject); begin if not FileExists(ebVectorDataCLRFile.Text) then ebVectorDataCLRFile.Color := clInfoBk else ebVectorDataCLRFile.Color := clWindow; end; // ----- TformPreferences.bLoadGeothermalCLRClick ------------------------------ procedure TformPreferences.bLoadGeothermalCLRClick(Sender: TObject); begin if OpenDialogCLR.Execute then ebGeothermalCLRFile.Text := OpenDialogCLR.FileName; end; // ----- TformPreferences.ebGeothermalCLRFileChange ---------------------------- procedure TformPreferences.ebGeothermalCLRFileChange(Sender: TObject); begin if not FileExists(ebGeothermalCLRFile.Text) then ebGeothermalCLRFile.Color := clInfoBk else ebGeothermalCLRFile.Color := clWindow; SetGeothermalModified; end; // ----- TformPreferences.pnlGeothermalColourClick ----------------------------- procedure TformPreferences.pnlGeothermalColourClick(Sender: TObject); begin UpdateColour(pnlGeothermalColour,4); end; // ----- TformPreferences.pnlGeothermalMinColourClick -------------------------- procedure TformPreferences.pnlGeothermalMinColourClick(Sender: TObject); begin UpdateColour(pnlGeothermalMinColour,4); end; // ----- TformPreferences.pnlGeothermalMaxColourClick -------------------------- procedure TformPreferences.pnlGeothermalMaxColourClick(Sender: TObject); begin UpdateColour(pnlGeothermalMaxColour,4); end; // ----- TformPreferences.pnlScalarBoundingColourClick ------------------------- procedure TformPreferences.pnlScalarBoundingColourClick(Sender: TObject); begin UpdateColour(pnlScalarBoundingColour,1); end; // ----- TformPreferences.pnlVectorBoundingColourClick ------------------------- procedure TformPreferences.pnlVectorBoundingColourClick(Sender: TObject); begin UpdateColour(pnlVectorBoundingColour,1); end; // ============================================================================= end.
namespace Calculator.Engine; interface uses RemObjects.Elements.RTL; type EvaluatorTokenType = private enum ( EOF, Number, Op_Add, Op_Sub, Op_Mul, Op_Div, Error ); EvaluatorError = private class(Exception) end; EvaluatorToken = private class public var Token: EvaluatorTokenType; var Value: String; var Offset: Integer; constructor(_token: EvaluatorTokenType; _value: String; _offset: Integer); end; Evaluator = public class private class var EOF: EvaluatorToken := new EvaluatorToken(EvaluatorTokenType.EOF, '', 0); var Tokens: List<EvaluatorToken>; var &Index: Integer := 0; property Current: EvaluatorToken read getCurrent; method getCurrent: EvaluatorToken; public // Evaluates a string expression like (1 + 2 * 4.5) and return the evaluated value method Evaluate(input: String): Double; private // Parses + and - expressions, this is split from * and / so that // + and - have a lower prescendence than * and / method ParseAdditionExpression: Double; // Parse * and / method ParseMultiplicationExpression: Double; method ParseValueExpression: Double; // Splits the string into parts; skipping whitespace class method Tokenize(input: String): List<EvaluatorToken>; end; implementation constructor EvaluatorToken(_token: EvaluatorTokenType; _value: String; _offset: Integer); begin self.Token := _token; self.Value := _value; self.Offset := _offset; end; method Evaluator.getCurrent: EvaluatorToken; begin if (Tokens <> nil) and (&Index < Tokens.Count) then exit Tokens[&Index]; exit EOF; end; method Evaluator.Evaluate(input: String): Double; begin Tokens := Tokenize(input); &Index := 0; exit ParseAdditionExpression(); end; method Evaluator.ParseAdditionExpression: Double; begin var l := ParseMultiplicationExpression(); while (Current.Token = EvaluatorTokenType.Op_Sub) or (Current.Token = EvaluatorTokenType.Op_Add) do begin var sub := Current.Token = EvaluatorTokenType.Op_Sub; inc(&Index); var r := ParseMultiplicationExpression(); if sub then l := l - r else l := l + r; end; exit l; end; method Evaluator.ParseMultiplicationExpression: Double; begin var l := ParseValueExpression(); while (Current.Token = EvaluatorTokenType.Op_Mul) or (Current.Token = EvaluatorTokenType.Op_Div) do begin var mul := Current.Token = EvaluatorTokenType.Op_Mul; inc(&Index); var r := ParseValueExpression(); if mul then l := l * r else l := l / r; end; exit l; end; method Evaluator.ParseValueExpression: Double; begin case Current.Token of EvaluatorTokenType.Op_Add: begin // Process +15 as unary inc(&Index); exit ParseValueExpression(); end; EvaluatorTokenType.Op_Sub: begin // Process -15 as unary inc(&Index); exit -ParseValueExpression(); end; EvaluatorTokenType.Number: begin var res := Current.Value; inc(&Index); exit Convert.ToDoubleInvariant(res); end; EvaluatorTokenType.EOF: begin raise new EvaluatorError('Unexected end of expression'); end; else begin raise new EvaluatorError('Unknown value at offset ' + Current.Offset); end; end; end; class method Evaluator.Tokenize(input: String): List<EvaluatorToken>; begin var res := new List<EvaluatorToken>(); // for parsing convenience so look ahead won't throw exceptions. input := input + #0#0; var i := 0; while i < input.Length do begin var c: Integer := i; case input[i] of #0: i := input.Length; '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.': begin c := i + 1; var gotDot := input[i] = '.'; while true do begin var ch := input[c]; if ((ch = '0') or (ch = '1') or (ch = '2') or (ch = '3') or (ch = '4') or (ch = '5') or (ch = '6') or (ch = '7') or (ch = '8') or (ch = '9') or (not gotDot and (ch = '.'))) then begin inc(c); if ch = '.' then gotDot := true; end else break; end; res.&Add(new EvaluatorToken(EvaluatorTokenType.Number, input.Substring(i, c - i), i)); i := c; end; '+': begin res.&Add(new EvaluatorToken(EvaluatorTokenType.Op_Add, '+', i)); inc(i); end; '-': begin res.&Add(new EvaluatorToken(EvaluatorTokenType.Op_Sub, '-', i)); inc(i); end; '*': begin res.&Add(new EvaluatorToken(EvaluatorTokenType.Op_Mul, '*', i)); inc(i); end; '/': begin res.&Add(new EvaluatorToken(EvaluatorTokenType.Op_Div, '/', i)); inc(i); end; ' ', #9, #13, #10: begin res.&Add(new EvaluatorToken(EvaluatorTokenType.Error, input[i].toString(), i)); inc(i); end; end; end; exit res; end; end.
// based on https://developer.gnome.org/gtk-tutorial/stable/c489.html namespace BasicGtkApp; uses atk, gobject, gio, gtk; /* !!! Please note: in order to run this sample, you need to manually copy it to a Linux PC or VM with an active GUI, and run it. !!! !!! GUI applications cannot be run via SSH or CrossBox 2. !!! To run this on Bash on Windows, set the :DISPLAY=:0 variable, and run an XServer locally, like Xming. */ type Program = class public class var window: ^GtkWindow; class method clicked(app: ^GtkWidget; userdata: ^Void); begin var dialog := ^GtkDialog(gtk_message_dialog_new(nil, GtkDialogFlags.GTK_DIALOG_DESTROY_WITH_PARENT, GtkMessageType.GTK_MESSAGE_INFO, GtkButtonsType.GTK_BUTTONS_OK, 'Hello World')); gtk_dialog_run (dialog); gtk_widget_destroy (dialog); end; class method Main(args: array of String): Int32; begin gtk_init(@ExternalCalls.nargs, @ExternalCalls.args); window := ^GtkWindow(gtk_window_new(GtkWindowType.GTK_WINDOW_TOPLEVEL)); gtk_window_set_title(window, 'RemObjects Oxygene - Island GTK Sample'); gtk_window_set_default_size(window, 200, 200); var button_box := gtk_hbutton_box_new(); gtk_container_add(window, button_box); var button := gtk_button_new_with_label('Hello World'); g_signal_connect_data(glib.gpointer(button), 'clicked', glib.GVoidFunc(^Void(@clicked)), nil, nil, GConnectFlags(0)); gtk_container_add(^GtkContainer(button_box), button); gtk_widget_show_all(window); gtk_main; end; end; end.
//------------------------------------------------------------------------------ //CharaOptions UNIT //------------------------------------------------------------------------------ // What it does- // This unit is used to gain access to configuration variables loaded from // Character.ini. // // Changes - // January 7th, 2007 - RaX - Broken out from ServerOptions. // //------------------------------------------------------------------------------ unit CharaOptions; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses IniFiles, Types; type //------------------------------------------------------------------------------ //TCharaOptions CLASS //------------------------------------------------------------------------------ TCharaOptions = class(TMemIniFile) private //private variables fID : LongWord; fPort : Word; fWANIP : String; fLANIP : String; fKey : String; fLoginIP : String; fLoginPort : Word; fLoginKey : String; fServerName : String; fShowFriendlyMessageOnDupLogin : Boolean; fMaxHairStyle : Byte; fMaxHairColor : Byte; fDefaultZeny : LongWord; fDefaultMap : String; fDefaultPoint : TPoint; fDefaultHeadTop : Word; fDefaultHeadMid : Word; fDefaultHeadLow : Word; fDefaultArmor : Word; fDefaultRightHand : Word; fDefaultLeftHand : Word; fDefaultShoes : Word; fDefaultGarment : Word; fDefaultAccessory1: Word; fDefaultAccessory2: Word; fIndySchedulerType : Byte; fIndyThreadPoolSize : Word; //Gets/Sets procedure SetPort(Value : Word); procedure SetWANIP(Value : String); procedure SetLANIP(Value : String); procedure SetLoginIP(Value : String); procedure SetLoginPort(Value : Word); procedure SetServerName(Value : String); public //Communication property ID : LongWord read fID; property Port : Word read fPort write SetPort; property WANIP : String read fWANIP write SetWANIP; property LANIP : String read fLANIP write SetLANIP; property LoginIP : String read fLoginIP write SetLoginIP; property LoginPort : Word read fLoginPort write SetLoginPort; property LoginKey : String read fLoginKey; //Security property Key : String read fKey; //Options property ServerName : String read fServerName write SetServerName; property ShowFriendlyMessageOnDupLogin : Boolean read fShowFriendlyMessageOnDupLogin write fShowFriendlyMessageOnDupLogin; property MaxHairStyle : Byte read fMaxHairStyle; property MaxHairColor : Byte read fMaxHairColor; property DefaultZeny: LongWord read fDefaultZeny write fDefaultZeny; property DefaultMap : String read fDefaultMap write fDefaultMap; property DefaultPoint : TPoint read fDefaultPoint write fDefaultPoint; property DefaultHeadTop: Word read fDefaultHeadTop write fDefaultHeadTop; property DefaultHeadMid: Word read fDefaultHeadMid write fDefaultHeadMid; property DefaultHeadLow: Word read fDefaultHeadLow write fDefaultHeadLow; property DefaultRightHand: Word read fDefaultRightHand write fDefaultRightHand; property DefaultLeftHand: Word read fDefaultLeftHand write fDefaultLeftHand; property DefaultArmor: Word read fDefaultArmor write fDefaultArmor; property DefaultGarment: Word read fDefaultGarment write fDefaultGarment; property DefaultShoes: Word read fDefaultShoes write fDefaultShoes; property DefaultAccessory1: Word read fDefaultAccessory1 write fDefaultAccessory1; property DefaultAccessory2: Word read fDefaultAccessory2 write fDefaultAccessory2; //Performance property IndySchedulerType : Byte read fIndySchedulerType; property IndyThreadPoolSize : Word read fIndyThreadPoolSize; //Public methods procedure Load; procedure Save; end; //------------------------------------------------------------------------------ implementation uses Classes, SysUtils, Math, NetworkConstants; //------------------------------------------------------------------------------ //Load() PROCEDURE //------------------------------------------------------------------------------ // What it does- // This routine is called to load the ini file values from file itself. // This routine contains multiple subroutines. Each one loads a different // portion of the ini. All changes to said routines should be documented in // THIS changes block. // // Changes - // September 21st, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharaOptions.Load; var Section : TStringList; //-------------------------------------------------------------------------- //LoadServer SUB PROCEDURE //-------------------------------------------------------------------------- procedure LoadServer; begin ReadSectionValues('Server', Section); fID := EnsureRange(StrToIntDef(Section.Values['ID'] ,1), Low(LongWord), High(LongWord)); end;{Subroutine LoadServer} //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //LoadCommunication SUB PROCEDURE //-------------------------------------------------------------------------- procedure LoadCommunication; begin ReadSectionValues('Communication', Section); if Section.Values['WANIP'] = '' then begin Section.Values['WANIP'] := '127.0.0.1'; end; fWANIP := Section.Values['WANIP']; if Section.Values['LANIP'] = '' then begin Section.Values['LANIP'] := '127.0.0.1'; end; fLANIP := Section.Values['LANIP']; fPort := EnsureRange(StrToIntDef(Section.Values['Port'], 6121), 1, MAX_PORT); if Section.Values['LoginIP'] = '' then begin Section.Values['LoginIP'] := '127.0.0.1'; end; fLoginIP := Section.Values['LoginIP']; fLoginPort := EnsureRange(StrToIntDef(Section.Values['LoginPort'], 6900), 1, MAX_PORT); fLoginKey := Section.Values['LoginKey']; end;{Subroutine LoadCommunication} //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //LoadSecurity SUB PROCEDURE //-------------------------------------------------------------------------- procedure LoadSecurity; begin ReadSectionValues('Security', Section); fKey := Section.Values['Key']; end;{Subroutine LoadSecurity} //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //LoadOptions SUB PROCEDURE //-------------------------------------------------------------------------- procedure LoadOptions; begin ReadSectionValues('Options', Section); if Section.Values['ServerName'] = '' then begin Section.Values['ServerName'] := 'Helios'; end; fServerName := Section.Values['ServerName']; fMaxHairStyle := EnsureRange(StrToIntDef(Section.Values['MaxHairStyle'], 25), 0, High(Byte)); fMaxHairColor := EnsureRange(StrToIntDef(Section.Values['MaxHairColor'], 8), 0, High(Byte)); {* Aeomin April 12th, 2007 If this Boolean set as false, char server will directly DC the client when attempt duplicate login, else wil send "Someone has already logged in with this ID"*} ShowFriendlyMessageOnDupLogin := StrToBoolDef(Section.Values['Show_FriendlyMessage_On_DuplicateLogin'] ,false); end;{Subroutine LoadOptions} //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //LoadCharacterDefaults SUB PROCEDURE //-------------------------------------------------------------------------- procedure LoadCharacterDefaults; begin ReadSectionValues('CharacterDefaults', Section); DefaultZeny := EnsureRange(StrToIntDef(Section.Values['Zeny'], 0), Low(LongWord), High(LongWord)); if Section.Values['Map'] = '' then begin Section.Values['Map'] := 'new_1-1'; end; DefaultMap := Section.Values['Map']; fDefaultPoint.X := EnsureRange(StrToIntDef(Section.Values['Point.X'], 53), Low(Word), High(Word)); fDefaultPoint.Y := EnsureRange(StrToIntDef(Section.Values['Point.Y'], 111), Low(Word), High(Word)); DefaultHeadTop := EnsureRange(StrToIntDef(Section.Values['HeadTop'], 0), Low(Word), High(Word)); DefaultHeadMid := EnsureRange(StrToIntDef(Section.Values['HeadMid'], 0), Low(Word), High(Word)); DefaultHeadLow := EnsureRange(StrToIntDef(Section.Values['HeadLow'], 0), Low(Word), High(Word)); DefaultRightHand := EnsureRange(StrToIntDef(Section.Values['RightHand'], 1201), Low(Word), High(Word)); DefaultLeftHand := EnsureRange(StrToIntDef(Section.Values['LeftHand'], 0), Low(Word), High(Word)); DefaultArmor := EnsureRange(StrToIntDef(Section.Values['Armor'], 2301), Low(Word), High(Word)); DefaultShoes := EnsureRange(StrToIntDef(Section.Values['Shoes'], 0), Low(Word), High(Word)); DefaultGarment := EnsureRange(StrToIntDef(Section.Values['Garment'], 0), Low(Word), High(Word)); DefaultAccessory1 := EnsureRange(StrToIntDef(Section.Values['Accessory1'], 0), Low(Word), High(Word)); DefaultAccessory2 := EnsureRange(StrToIntDef(Section.Values['Accessory2'], 0), Low(Word), High(Word)); end;{LoadCharacterDefaults} //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //LoadPerformance SUB PROCEDURE //-------------------------------------------------------------------------- procedure LoadPerformance; begin ReadSectionValues('Performance', Section); fIndySchedulerType := EnsureRange(StrToIntDef(Section.Values['Indy Scheduler Type'], 0), 0, 1); fIndyThreadPoolSize := EnsureRange(StrToIntDef(Section.Values['Indy Thread Pool Size'], 1), 1, High(Word)); end;{Subroutine LoadPerformance} //-------------------------------------------------------------------------- begin Section := TStringList.Create; Section.QuoteChar := '"'; Section.Delimiter := ','; LoadServer; LoadCommunication; LoadSecurity; LoadOptions; LoadCharacterDefaults; LoadPerformance; Section.Free; end;{Load} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Save() PROCEDURE //------------------------------------------------------------------------------ // What it does- // This routine saves all configuration values defined here to the .ini // file. // // Changes - // September 21st, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharaOptions.Save; begin //Server WriteString('Server','ID',IntToStr(ID)); //Communication WriteString('Communication','WANIP',WANIP); WriteString('Communication','LANIP',LANIP); WriteString('Communication','Port', IntToStr(Port)); WriteString('Communication','LoginIP',LoginIP); WriteString('Communication','LoginPort',IntToStr(LoginPort)); WriteString('Communication','LoginKey',LoginKey); //Security WriteString('Security','Key',Key); //Options WriteString('Options','ServerName',ServerName); WriteString('Options','Show_FriendlyMessage_On_DuplicateLogin',BoolToStr(fShowFriendlyMessageOnDupLogin)); WriteString('Options','MaxHairStyle',IntToStr(MaxHairStyle)); WriteString('Options','MaxHairColor',IntToStr(MaxHairColor)); //CharacterDefaults WriteString('CharacterDefaults','Zeny',IntToStr(DefaultZeny)); WriteString('CharacterDefaults','Map',DefaultMap); WriteString('CharacterDefaults','Point.X',IntToStr(fDefaultPoint.X)); WriteString('CharacterDefaults','Point.Y',IntToStr(DefaultPoint.Y)); WriteString('CharacterDefaults','HeadTop',IntToStr(DefaultHeadTop)); WriteString('CharacterDefaults','HeadMid',IntToStr(DefaultHeadMid)); WriteString('CharacterDefaults','HeadLow',IntToStr(DefaultHeadLow)); WriteString('CharacterDefaults','RightHand',IntToStr(DefaultRightHand)); WriteString('CharacterDefaults','LeftHand',IntToStr(DefaultLeftHand)); WriteString('CharacterDefaults','Armor',IntToStr(DefaultArmor)); WriteString('CharacterDefaults','Shoes',IntToStr(DefaultShoes)); WriteString('CharacterDefaults','Garment',IntToStr(DefaultGarment)); WriteString('CharacterDefaults','Accessory1',IntToStr(DefaultAccessory1)); WriteString('CharacterDefaults','Accessory2',IntToStr(DefaultAccessory2)); //Performance WriteString('Performance','Indy Scheduler Type',IntToStr(IndySchedulerType)); WriteString('Performance','Indy Thread Pool Size',IntToStr(IndyThreadPoolSize)); UpdateFile; end;{Save} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetWANIP() PROCEDURE //------------------------------------------------------------------------------ // What it does- // Property Set Routine for WAN IP of Character Server // Changes - // November 29th, 2006 - RaX - Created. // March 13th, 2007 - Aeomin - Modify Header. // //------------------------------------------------------------------------------ procedure TCharaOptions.SetWANIP(Value : String); begin if fWANIP <> Value then begin fWANIP := Value; WriteString('Communication', 'WANIP', WANIP); end; end;{SetWANIP} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetLANIP() PROCEDURE //------------------------------------------------------------------------------ // What it does- // Property Set Routine for LAN IP of Character Server // Changes - // November 29th, 2006 - RaX - Created. // March 13th, 2007 - Aeomin - Modify Header. // //------------------------------------------------------------------------------ procedure TCharaOptions.SetLANIP(Value : String); begin if fWANIP <> Value then begin fWANIP := Value; WriteString('Communication', 'LANIP', LANIP); end; end;{SetLANIP} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetServerName() PROCEDURE //------------------------------------------------------------------------------ // What it does- // Property Set Routine for ServerName. Ensures that if the server name is // changed for whatever reason, that it gets written to the .ini immediately. // // Changes - // September 21st, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharaOptions.SetServerName(Value : String); begin if fServerName <> Value then begin fServerName := Value; WriteString('Options', 'ServerName', ServerName); end; end;{SetServerName} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetPort() PROCEDURE //------------------------------------------------------------------------------ // What it does- // Property Set Routine for Port. Ensures that if the port is changed for // whatever reason, that it gets written to the .ini immediately. // // Changes - // September 21st, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharaOptions.SetPort(Value : word); begin if fPort <> value then begin fPort := value; WriteString('Communication', 'Port', IntToStr(Port)); end; end;{SetPort} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetLoginPort() PROCEDURE //------------------------------------------------------------------------------ // What it does- // Property Set Routine for Login Server Port. // Changes - // November 29th, 2006 - RaX - Created. // March 13th, 2007 - Aeomin - Modify Header. // //------------------------------------------------------------------------------ procedure TCharaOptions.SetLoginPort(Value : Word); begin if fLoginPort <> Value then begin fLoginPort := Value; WriteString('Communication', 'LoginPort', IntToStr(LoginPort)); end; end;{SetLoginPort} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetLoginIP() PROCEDURE //------------------------------------------------------------------------------ // What it does- // Property Set Routine for Login Server IP. // Changes - // November 29th, 2006 - RaX - Created. // //------------------------------------------------------------------------------ procedure TCharaOptions.SetLoginIP(Value : String); begin if fLoginIP <> Value then begin fLoginIP := Value; WriteString('Communication', 'LoginIP', LoginIP); end; end;{SetLoginIP} //------------------------------------------------------------------------------ end{CharaOptions}.
unit USMConexao; interface uses System.SysUtils, System.Classes, System.Json, DataSnap.DSProviderDataModuleAdapter, Datasnap.DSServer, Datasnap.DSAuth, Data.DBXFirebird, Data.DB, Data.SqlExpr, Data.FMTBcd, Datasnap.Provider, Datasnap.DBClient; type TSMConexao = class(TDSServerModule) CON_FB: TSQLConnection; SQL_ProximoCodigo: TSQLDataSet; DSP_ProximoCodigo: TDataSetProvider; CDS_ProximoCodigo: TClientDataSet; SQL_ExecuteReader: TSQLDataSet; DSP_ExecuteReader: TDataSetProvider; CDS_ExecuteReader: TClientDataSet; private { Private declarations } public { Public declarations } function ProximoCodigo(Tabela: String): Integer; function ExecuteReader(SQL: String): OleVariant; end; implementation {$R *.dfm} { TSMConexao } function TSMConexao.ExecuteReader(SQL: String): OleVariant; begin try CDS_ExecuteReader.Close; CDS_ExecuteReader.CommandText := SQL; CDS_ExecuteReader.Open; Result := CDS_ExecuteReader.Data except on E: Exception do raise Exception.Create('Não foi possível executar o Comando! ' + E.Message); end; end; function TSMConexao.ProximoCodigo(Tabela: String): Integer; begin CDS_ProximoCodigo.Close; CDS_ProximoCodigo.CommandText := 'select gen_id(GEN_'+Tabela+'_ID, 1) as CODIGO from RDB$DATABASE'; CDS_ProximoCodigo.Open; if not CDS_ProximoCodigo.IsEmpty then Result := CDS_ProximoCodigo.FieldByName('CODIGO').AsInteger else raise Exception.Create('Não foi possível Buscar o ProximoCodigo!'); end; end.
unit UIlsServiceUtils; interface uses System.SysUtils, Winapi.WinSvc; //function GetWorkParam(): string; function GetParamByName(const AParamName: string): string; function HasAnyParamOf(AParams: array of string): Boolean; procedure ChangeServiceParams(const AServiceName: string; const AServiceParamName: string; const AServiceParamValue: string); implementation function GetParamByName(const AParamName: string): string; var i: Integer; ConfigParam: string; begin Result := ''; for i := 1 to System.ParamCount do begin ConfigParam := ParamStr( I ); if (Length(ConfigParam) > (Length(AParamName) + 2)) and (LowerCase(Copy(ConfigParam, 1, (Length(AParamName) + 2))) = LowerCase('/' + AParamName + ':')) then begin Result := Copy(ConfigParam, Length(AParamName) + 3, MaxInt); Exit; end; end; end; function HasAnyParamOf(AParams: array of string): Boolean; var i, j: Integer; begin Result := False; for i := 1 to System.ParamCount do for j := Low(AParams) to High(AParams) do if Pos(LowerCase('/' + aparams[j]), LowerCase(ParamStr(i))) = 2 then Exit(True); end; procedure ChangeServiceParams(const AServiceName: string; const AServiceParamName: string; const AServiceParamValue: string); var //! // ConfigParam: string; //! менеджер служб SvcMgr: SC_HANDLE; //! служба Svc: SC_HANDLE; //------------------------------------------------------------------------------ begin if ( AServiceParamValue <> '' ) then begin SvcMgr := OpenSCManager( nil, nil, SC_MANAGER_ALL_ACCESS ); if ( SvcMgr <> 0 ) then begin Svc := OpenService( SvcMgr, PChar( AServiceName + '_' + AServiceParamValue ), SERVICE_ALL_ACCESS ); if ( Svc <> 0 ) then begin if not ChangeServiceConfig( Svc, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, PChar( ParamStr( 0 ) + ' /' + AServiceParamName + ':' + AServiceParamValue ), nil, nil, nil, nil, nil, nil ) then raise Exception.Create( 'Не удалось изменение статуса службы' ); end else raise Exception.Create( 'Не удалось подключение к службе' ); end else raise Exception.Create( 'Не удалось подключение к менеджеру служб' ); end else raise Exception.Create( 'Параметр клиента не задан' ); end; end.
unit SDURandPool; // Description: // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // { copyright tdk my code dual licenced under FreeOTFE licence and LGPL code marked as 'sdean' is freeotfe licence only was OTFEFreeOTFE_WizardCommon keeps a random pool - reads as needed from OS random sources ad internal 'mouse data' pool } interface uses SysUtils, Windows,//sdu SDUGeneral, //LibreCrypt pkcs11_library; type TRNG = ( rngCryptoAPI, rngMouseMovement, rngcryptlib, rngPKCS11, rngGPG ); TRNGSet = set of TRNG; EInsufficientRandom = class (Exception); TRandPool = class (TObject) private { private declarations } protected // Generate RNG data using GPG, assuming GPG is located under the specified // filename // function GenerateRNGDataGPG(bytesRequired: integer; GPGFilename: string; var randomData: TSDUBytes): boolean; // Generate RNG data using the MS CryptoAPI class function GenerateRNGDataMSCryptoAPI(bytesRequired: Integer; out randomData: TSDUBytes): Boolean; overload; class function GenerateRNGDataMSCryptoAPI(bytesRequired: Integer; szContainer: LPCSTR; szProvider: LPCSTR; dwProvType: DWORD; dwFlags: DWORD; out randomData: TSDUBytes): Boolean; overload; class function GenerateRandomData1Rng(rng: TRNG; bytesRequired: Integer; // Output out randomData: TSDUBytes): Boolean; overload; public { public declarations } constructor Create(); // singleton - dont call directly - use GetRandPool destructor Destroy(); override; //normaly only called on app exit // Generate RNG data using specified RNG // !! WARNING !! // If RNG_OPT_CRYPTLIB is specified as the RNG, cryptlibLoad must be called // beforehand, and cryptlibUnload after use class procedure GetRandomData(bytesRequired: Integer; // Output out randomData: TSDUBytes); class procedure FillRandomData(var randomData: array of Byte); class function CanUseCryptLib(): Boolean; //obsolete class procedure GenerateRandomData(bytesRequired: Integer; // Output var randomData: Ansistring); overload; // gpgFilename - Only MANDATORY if RNG_OPT_GPG specified as RNG class procedure SetUpRandPool(rngset: TRNGSet; // PKCS#11 specific SlotID: Integer; // GPG specific gpgFilename: String); end; // MouseRNG store procedure InitMouseRNGData(); procedure AddToMouseRNGData(random: Byte); function GetMouseRNGData(bytesRequired: Integer; var randomData: TSDUBytes): Boolean; function CountMouseRNGData(): Integer; procedure PurgeMouseRNGData(); function GetRandPool(): TRandPool; resourcestring PLEASE_REPORT_TO_FREEOTFE_DOC_ADDR = 'Please report seeing this message using the email address specified in the LibreCrypt documentation, ' + 'together with a brief description of what you were attempting to do.'; implementation uses Dialogs, MSCryptoAPI, // Required for showmessage //sdu lcDialogs, SDUi18n, //librecrypt cryptlib, PKCS11Lib, OTFEFreeOTFEBase_U; { // Load cryptlib, if possible, and initialise function cryptlibLoad(): Boolean; // Generate RNG data using cryptlib function GenerateRNGDataCryptlib(bytesRequired: Integer; var randomData: Ansistring): Boolean; // Unload cryptlib function cryptlibUnload(): Boolean; function GenerateRNGDataPKCS11(PKCS11Library: TPKCS11Library; SlotID: Integer; bytesRequired: Integer; var randomData: Ansistring): Boolean; } var _MouseRNGStore: TSDUBytes; _RandPool: TRandPool; _rngset: TRNGSet; _PKCS11Library: TPKCS11Library; _PKCS11SlotID: Integer; _gpgFilename: String; _inited: Boolean = False; _CanUseCryptlib: Boolean = False; // Generate RNG data using cryptlib function GenerateRNGDataCryptlib(bytesRequired: Integer; var randomData: TSDUBytes): Boolean; begin randomData := SDUStringToSDUBytes(cryptlib_RNG(bytesRequired)); // randomData := cryptlib_RNG(bytesRequired); Result := (Length(randomData) = bytesRequired); end; function GenerateRNGDataPKCS11(PKCS11Library: TPKCS11Library; SlotID: Integer; bytesRequired: Integer; var randomData: TSDUBytes): Boolean; begin Result := GetPKCS11RandomData(PKCS11Library, SlotID, bytesRequired, RandomData); if not Result then begin SDUMessageDlg( _('The selected PKCS#11 token could not be used to generate random data.') + SDUCRLF + SDUCRLF + _('Please select another RNG, and try again'), mtError ); end; end; // gpgFilename - Only MANDATORY if RNG_OPT_GPG specified as RNG class function TRandPool.GenerateRandomData1Rng(rng: TRNG; bytesRequired: Integer; // Output out randomData: TSDUBytes): Boolean; begin { TODO -otdk -crefactor : raise exception on error instead of result } SDUInitAndZeroBuffer(0, randomData); // randomData := ''; // Generate random data, if this hasn't already been done... case rng of // Mouse RNG.. rngMouseMovement: begin // Nothing to do; the random data has already been generated via the // interface Result := GetMouseRNGData(bytesRequired, randomData); end; // MS CryptoAPI... rngCryptoAPI: begin Result := GenerateRNGDataMSCryptoAPI(bytesRequired, randomData); Result := Result and (length(randomData) = bytesRequired); if not Result then begin SDUMessageDlg( _('The MS CryptoAPI could not be used to generate random data.') + SDUCRLF + SDUCRLF + _('Please select another RNG, and try again'), mtError ); end; end; // cryptlib... rngcryptlib: begin Result := GenerateRNGDataCryptlib(bytesRequired, randomData); Result := Result and (length(randomData) = bytesRequired); if not Result then begin SDUMessageDlg( _('cryptlib could not be used to generate random data.') + SDUCRLF + SDUCRLF + _( 'Please ensure the cryptlib DLL is in the correct location, and try again'), mtError ); end; end; // PKCS#11 token... rngPKCS11: begin Result := GenerateRNGDataPKCS11(_PKCS11Library, _PKCS11SlotID, bytesRequired, randomData); Result := Result and (length(randomData) = bytesRequired); if not Result then begin SDUMessageDlg( _('PKCS#11 token could not be used to generate random data.') + SDUCRLF + SDUCRLF + _( 'Please ensure token is inserted and configured correctly'), mtError ); end; end; // GPG... rngGPG: begin // not implemented Result := False; // allOK := GenerateRNGDataGPG( // bytesRequired, // gpgFilename, // randomData // ); Result := Result and (length(randomData) = bytesRequired); if not Result then begin SDUMessageDlg( _('GPG could not be used to generate random data.') + SDUCRLF + SDUCRLF + _('Please doublecheck the path to the GPG executable, and try again.'), mtError ); end; end; else begin raise Exception.Create('Unknown RNG selected' + SDUCRLF + SDUCRLF + PLEASE_REPORT_TO_FREEOTFE_DOC_ADDR); { SDUMessageDlg( _('Unknown RNG selected?!') + SDUCRLF + SDUCRLF + PLEASE_REPORT_TO_FREEOTFE_DOC_ADDR, mtError ); Result := False;} end; end; // Sanity check if Result then begin Result := (length(randomData) = bytesRequired); if not Result then begin raise EInsufficientRandom.Create(Format('%d bytes required %d found', [bytesRequired, length(randomData)])); { SDUMessageDlg( _('Insufficient random data generated?!') + SDUCRLF + SDUCRLF + PLEASE_REPORT_TO_FREEOTFE_DOC_ADDR, mtError ); Result := False; } end; end; end; //obsolete // gpgFilename - Only MANDATORY if RNG_OPT_GPG specified as RNG class procedure TRandPool.GenerateRandomData(bytesRequired: Integer; // Output var randomData: Ansistring); var randomBytes: TSDUBytes; begin GetRandomData(bytesRequired, randomBytes); randomData := SDUBytesToString(randomBytes); end; // gpgFilename - Only MANDATORY if RNG_OPT_GPG specified as RNG class procedure TRandPool.SetUpRandPool(rngset: TRNGSet; // PKCS#11 specific SlotID: Integer; // GPG specific gpgFilename: String); begin _rngset := rngset; _PKCS11Library := GetFreeOTFEBase().PKCS11Library; _PKCS11SlotID := SlotID; _gpgFilename := gpgFilename; _inited := True; end; class procedure TRandPool.FillRandomData( // Output var randomData: array of Byte); var currRandom: TSDUBytes; i: Integer; begin GetRandomData(length(randomData), currRandom); for i := 0 to high(currRandom) do randomData[i] := currRandom[i]; SafeSetLength(currRandom, 0); end; class procedure TRandPool.GetRandomData(bytesRequired: Integer; // Output out randomData: TSDUBytes); var currRNG: TRNG; currRandom: TSDUBytes; rngsUsed: Integer; ok: Boolean; begin assert(_inited); rngsUsed := 0; for currRNG := low(TRNG) to high(TRNG) do begin if (currRNG in _rngset) then begin SDUInitAndZeroBuffer(0, currRandom); ok := GenerateRandomData1Rng(currRNG, bytesRequired, currRandom); if not ok then begin // break; raise EInsufficientRandom.Create(''); end else begin randomData := SDUXOR(currRandom, randomData); Inc(rngsUsed); end; end; end; if (rngsUsed <= 0) then raise Exception.Create('No RNG selected'); end; (* function GenerateRNGDataGPG(bytesRequired: integer; GPGFilename: string; var randomData: TSDUBytes): boolean; begin // xxx - implement GPG integration showmessage('Using GPG to generate RNG data has not yet been implemented. Please select another RNG option'); randomData:= ''; Result := FALSE; end; *) class function TRandPool.GenerateRNGDataMSCryptoAPI(bytesRequired: Integer; out randomData: TSDUBytes): Boolean; begin Result := GenerateRNGDataMSCryptoAPI(bytesRequired, nil, MS_DEF_PROV, PROV_RSA_FULL, (CRYPT_VERIFYCONTEXT or CRYPT_MACHINE_KEYSET), randomData); if not (Result) then begin Result := GenerateRNGDataMSCryptoAPI(bytesRequired, nil, MS_DEF_PROV, PROV_RSA_FULL, (CRYPT_VERIFYCONTEXT or CRYPT_MACHINE_KEYSET or CRYPT_NEWKEYSET), randomData); end; if not (Result) then begin Result := GenerateRNGDataMSCryptoAPI(bytesRequired, '', '', PROV_RSA_FULL, CRYPT_VERIFYCONTEXT, randomData); end; end; class function TRandPool.GenerateRNGDataMSCryptoAPI(bytesRequired: Integer; szContainer: LPCSTR; szProvider: LPCSTR; dwProvType: DWORD; dwFlags: DWORD; out randomData: TSDUBytes): Boolean; var hProv: HCRYPTPROV; begin Result := False; if CryptAcquireContext(@hProv, szContainer, szProvider, dwProvType, dwFlags) then begin // Cleardown... // This is required in order that CrypGenRandom can overwrite with random // data SDUInitAndZeroBuffer(bytesRequired, randomData); // randomData := StringOfChar(AnsiChar(#0), bytesRequired); Result := CryptGenRandom(hProv, bytesRequired, PByte(randomData)); { TODO 1 -otdk -cinvestigate : PByte(string) can you do this? } CryptReleaseContext(hProv, 0); end; end; // Load cryptlib, if possible, and initialise function cryptlibLoad(): Boolean; var funcResult: Integer; begin Result := cryptlib_LoadDLL(); if Result then begin funcResult := cryptlib_cryptInit(); Result := cryptlib_cryptStatusOK(funcResult); if Result then begin funcResult := cryptlib_cryptAddRandom(nil, cryptlib_CRYPT_RANDOM_SLOWPOLL); Result := cryptlib_cryptStatusOK(funcResult); // If there was a problem, call end if not Result then cryptlib_cryptEnd(); end; // If there was a problem, unload the DLL if not Result then cryptlib_UnloadDLL(); end; end; // Unload cryptlib function cryptlibUnload(): Boolean; var funcResult: Integer; begin // Call "end" function on the DLL funcResult := cryptlib_cryptEnd(); Result := cryptlib_cryptStatusOK(funcResult); // Unload the DLL Result := Result and cryptlib_UnloadDLL(); end; // Initialize MouseRNG random data store procedure InitMouseRNGData(); begin SDUInitAndZeroBuffer(0, _MouseRNGStore); // _MouseRNGStore := ''; end; // Add byte to MouseRNG store procedure AddToMouseRNGData(random: Byte); begin SDUAddByte(_MouseRNGStore, random); // _MouseRNGStore := _MouseRNGStore + Ansichar(random); end; // Get first bytesRequired bytes of data from the MouseRNG store function GetMouseRNGData(bytesRequired: Integer; var randomData: TSDUBytes): Boolean; begin Result := False; SDUInitAndZeroBuffer(0, randomData); // randomData := ''; if ((bytesRequired * 8) <= CountMouseRNGData()) then begin randomData := Copy(_MouseRNGStore, 0, bytesRequired); Result := True; end; end; // Count the number of *bits* in the MouseRNG store function CountMouseRNGData(): Integer; begin Result := length(_MouseRNGStore) * 8; end; // Purge the current MouseRNG store procedure PurgeMouseRNGData(); //var // i: Integer; begin // Simple overwrite // for i := 1 to length(_MouseRNGStore) do begin // _MouseRNGStore[i] := Byte(i); //// _MouseRNGStore := Ansichar(i); // end; SDUInitAndZeroBuffer(0, _MouseRNGStore); // _MouseRNGStore := ''; end; // tdk code { TRandPool } class function TRandPool.CanUseCryptLib: Boolean; begin Result := _CanUseCryptlib; end; constructor TRandPool.Create; begin assert(_RandPool = nil, 'dont call ctor - use GetRandPool'); // Start cryptlib, if possible, as early as we can to allow it as much time // as possible to poll entropy _CanUseCryptlib := cryptlibLoad(); end; destructor TRandPool.Destroy; begin // Shutdown cryptlib, if used if _CanUseCryptlib then cryptlibUnload(); _CanUseCryptlib := False; end; function GetRandPool(): TRandPool; begin if _RandPool = nil then _RandPool := TRandPool.Create(); Result := _RandPool; end; initialization _RandPool := nil; finalization if _RandPool <> nil then FreeAndNil(_RandPool); end.
unit FEarthLocations; {Only things INTERACTIVE with the GLS 3D Display need to be on the same page as it To make this 'fit' into a tabsheet on main page the stuff on the right side: Open,Save,Print and Memo would be on another 'page' the stuff on the left would be divided into left and right sides with its own memo The Earthform Main page People Display would be the 'front page' It could be divided into 2 pages or not.. maybe 1 ..wider The Planet maker (ABCDE) could be another page} interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, VCL.Graphics, VCL.Controls, VCL.Forms, VCL.Dialogs, VCL.StdCtrls, VCL.Buttons, VCL.ComCtrls, VCL.ExtCtrls, GLTexture, GLColor; type TEarthLocationsFrm = class(TForm) Panel1: TPanel; OkBitBtn: TBitBtn; CancelBitBtn: TBitBtn; sDateEdit: TEdit; Label7: TLabel; Label6: TLabel; LatitudeEdit: TEdit; Label5: TLabel; LongitudeEdit: TEdit; Label4: TLabel; CountryEdit: TEdit; Label3: TLabel; CityEdit: TEdit; Label2: TLabel; NameEdit: TEdit; Label1: TLabel; Label8: TLabel; cbTypes: TComboBox; AddtoTypeBtn: TSpeedButton; ColorPanel: TPanel; TypeEdit: TEdit; Panel2: TPanel; RichEdit1: TRichEdit; ColorDialog1: TColorDialog; Panel3: TPanel; OpenBtn: TSpeedButton; SaveBtn: TSpeedButton; PrintBtn: TSpeedButton; ResetDefaultsBtn: TSpeedButton; SaveListBtn: TSpeedButton; SaveColorsBtn: TSpeedButton; NickNameEdit: TEdit; Label9: TLabel; EMailEdit: TEdit; Label10: TLabel; UrlEdit: TEdit; Label11: TLabel; DemoNameEdit: TEdit; Label12: TLabel; Label13: TLabel; sDOBDateEdit: TEdit; Label14: TLabel; TypeNameEdit: TEdit; Label15: TLabel; StateEdit: TEdit; Label16: TLabel; ClearMemoBtn: TSpeedButton; Label17: TLabel; GlowTrackBar: TTrackBar; PhotoEdit: TEdit; Label18: TLabel; OpenDialog1: TOpenDialog; PhotoBtn: TSpeedButton; HelpBtn: TSpeedButton; WordWrapCB: TCheckBox; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure OkBitBtnClick(Sender: TObject); procedure OpenBtnClick(Sender: TObject); procedure WordWrapCBClick(Sender: TObject); procedure SaveBtnClick(Sender: TObject); procedure PrintBtnClick(Sender: TObject); procedure AddtoTypeBtnClick(Sender: TObject); procedure SaveTypeList; procedure SaveColors; procedure ColorPanelClick(Sender: TObject); procedure ResetDefaultsBtnClick(Sender: TObject); procedure SaveListBtnClick(Sender: TObject); procedure SaveColorsBtnClick(Sender: TObject); procedure PhotoBtnClick(Sender: TObject); procedure HelpBtnClick(Sender: TObject); private public end; var EarthLocationsFrm: TEarthLocationsFrm; //------------------------------------------------------------------- implementation //------------------------------------------------------------------- uses FSpaceScene, uGlobals; {$R *.DFM} procedure TEarthLocationsFrm.FormClose(Sender: TObject; var Action: TCloseAction); begin {} end; procedure TEarthLocationsFrm.FormCreate(Sender: TObject); var S : string; F : TextFile; begin AssignFile(F,EarthDataPath+'EarthLocoList.txt'); Reset(F); try cbTypes.Clear; //EarthForm.cbTypes.Clear; while not eof(F) do begin Readln(F,S); {Delete the >Color part... or leave it as 'hint' If pos('>',S)>0 then S:=Copy(S,0,pos('>',S)-1);} cbTypes.Items.Add(S); //EarthForm.cbTypes.Items.Add(S); end; finally CloseFile(F); cbTypes.ItemIndex:=0; //EarthForm.cbTypes.ItemIndex:=0; end; end; procedure TEarthLocationsFrm.AddtoTypeBtnClick(Sender: TObject); begin {cbTypes TypeEdit.Text ColorPanel.Color} cbTypes.Items.Add(TypeEdit.Text); Inc(ColorIndex); SetLength(DotColorArray,ColorIndex+1); {GLTexture} DotColorArray[ColorIndex]:=ConvertWinColor(ColorPanel.Color); Application.ProcessMessages; SaveTypeList; SaveColors; end; procedure TEarthLocationsFrm.SaveTypeList; var F :TextFile; i : integer; sType : string; begin {cbTypes TypeEdit.Text ColorPanel.Color} AssignFile(F,EarthDataPath+'EarthLocoList.txt'); Rewrite(F); try For I:= 0 to cbTypes.items.Count- 1 do begin sType:= cbTypes.items[I]; Writeln(F,sType); end; finally CloseFile(F); end; end; procedure TEarthLocationsFrm.SaveColors; var F :TextFile; i : integer; scolor : string; begin AssignFile(F,EarthDataPath+'EarthLocoColors.txt'); Rewrite(F); try For I:= 0 to ColorIndex do begin scolor:= inttostr(ConvertColorVector(DotColorArray[I])); Writeln(F,scolor); end; finally CloseFile(F); end; end; {Add to List AND Save} procedure TEarthLocationsFrm.OkBitBtnClick(Sender: TObject); var F:TextFile; Lat,Lon:single; byteType,byteType2 : byte; sDateFormat, sName, sNickName, sCity, sState, sCountry,sPhoto, sEMail, sUrl, sDemoName, sTypeName, sDescription, sDateGLS,sDateDOB,sWhoWhereFormat : string; mp : TMarkerPosition; {iIndex : integer;} begin AssignFile(F,EarthDataPath+'EarthLoco.txt'); Append(f); try Writeln(F);{End the last one ?} {makes the date read right.. ignored later...} sDateFormat := FormatSettings.ShortDateFormat; // save it FormatSettings.ShortDateFormat := 'dd/mm/yyyy'; mp := Tmarkerposition.Create; {inc(markerIndex);} {now or later} markers.AddObject(IntToStr(markerIndex),mp); with TMarkerPosition(markers.Objects[markerIndex]) do begin If Length(LatitudeEdit.Text)= 0 then LatitudeEdit.Text:='0'; Lat := Strtofloat(LatitudeEdit.Text); Latitude := Lat; If Length(LongitudeEdit.Text)= 0 then LongitudeEdit.Text:='0'; Lon := Strtofloat(LongitudeEdit.Text); Longitude := Lon; byteType :=cbTypes.ItemIndex;// StrToInt(cbTypes.Text); MemberType := byteType; byteType2 :=GlowTrackBar.Position; Glow := byteType2; { fLatitude : single; ptsLocations ptsFlashLocations fLongitude : single; fmembertype, fGlow : byte; // 0..255 fTypeName, fName, fNickName, fCity, fState, fCountry: String; fDateAdded, fDateDOB: TDate; fEMail, fUrl, fDemoName, fDescription: String;} if Length(TypeNameEdit.Text)= 0 then TypeNameEdit.Text:=' '; sTypeName :=TypeNameEdit.Text; TypeName:=sTypeName; if Length(NameEdit.Text)= 0 then NameEdit.Text:=' '; sName :=NameEdit.Text; Name:=sName; if Length(NickNameEdit.Text)= 0 then NickNameEdit.Text:=' '; sNickName :=NickNameEdit.Text; NickName:=sNickName; if Length(CityEdit.Text)= 0 then CityEdit.Text:=' '; sCity :=CityEdit.Text; City:=sCity; If Length(StateEdit.Text)= 0 then StateEdit.Text:=' '; sState :=StateEdit.Text; State:=sState; If Length(CountryEdit.Text)= 0 then CountryEdit.Text:=' '; sCountry :=CountryEdit.Text; Country:=sCountry; If Length(sDateEdit.Text)= 0 then sDateEdit.Text:=Datetostr(Now); sDateGLS :=sDateEdit.Text;// StrToDate(Trim(sDate)); DateAdded := StrToDate(Trim(sDateGLS)); If Length(sDOBDateEdit.Text)= 0 then sDOBDateEdit.Text:=Datetostr(Now); sDateDOB :=sDOBDateEdit.Text; DateDOB := StrToDate(Trim(sDateDOB)); If Length(PhotoEdit.Text)= 0 then PhotoEdit.Text:=' '; sPhoto :=PhotoEdit.Text; Photo:=sPhoto; If Length(EMailEdit.Text)= 0 then EMailEdit.Text:=' '; sEMail :=EMailEdit.Text; EMail:=sEMail; If Length(UrlEdit.Text)= 0 then UrlEdit.Text:=' '; sUrl :=UrlEdit.Text; Url:=sUrl; If Length(DemoNameEdit.Text)= 0 then DemoNameEdit.Text:=' '; sDemoName :=DemoNameEdit.Text; DemoName:=sDemoName; sDescription :=RichEdit1.Text; If Length(sDescription)= 0 then sDescription:=' '; Description:=sDescription; sWhoWhereFormat:= LongitudeEdit.Text +' '+ LatitudeEdit.Text +' '+ inttostr(byteType) +' '+ inttostr(byteType2)+' '+ sTypeName+','+ sName+','+ sNickName+','+ sCity+','+ sState+','+ sCountry+','+ sDateGLS+','+sDateDOB+','+ sPhoto+','+ sEMail+','+ sUrl+','+ sDemoName+','+sDescription; Writeln(F,{Lon,Lat,byteType,byteType2,}sWhoWhereFormat); Flush(f);{MAKE it write NOW} end; inc(markerIndex); finally CloseFile(F); end;//finally FormatSettings.ShortDateFormat := sDateFormat; end; procedure TEarthLocationsFrm.OpenBtnClick(Sender: TObject); begin RichEdit1.Lines.LoadFromFile(EarthDataPath+'EarthLoco.txt'); end; procedure TEarthLocationsFrm.WordWrapCBClick(Sender: TObject); begin RichEdit1.WordWrap:= WordWrapCB.Checked; end; procedure TEarthLocationsFrm.SaveBtnClick(Sender: TObject); begin RichEdit1.Lines.SavetoFile(EarthDataPath+'EarthLoco.txt'); end; procedure TEarthLocationsFrm.PrintBtnClick(Sender: TObject); begin RichEdit1.Print(EarthDataPath+'EarthLoco.txt'); end; procedure TEarthLocationsFrm.ColorPanelClick(Sender: TObject); begin ColorDialog1.Color:= ColorPanel.Color; if ColorDialog1.Execute then ColorPanel.Color := ColorDialog1.Color; end; procedure TEarthLocationsFrm.ResetDefaultsBtnClick(Sender: TObject); begin ColorIndex:=7; SetLength(DotColorArray,ColorIndex+1); DotColorArray[0]:=clrSilver; DotColorArray[1]:=clrMandarinOrange; DotColorArray[2]:=clrYellow; DotColorArray[3]:=clrBlue; DotColorArray[4]:=clrRed; DotColorArray[5]:=clrPurple; DotColorArray[6]:=clrLime; DotColorArray[7]:=clrFlesh; cbTypes.Clear; cbTypes.Items.Add('0: Undecided Dabbler [clrSilver]'); cbTypes.Items.Add('1: GLS Developer [clrMandarinOrange]'); cbTypes.Items.Add('2: Content Creator [clrYellow]'); cbTypes.Items.Add('3: Game Developer FPS [clrBlue]'); cbTypes.Items.Add('4: Game Developer RTS Sims [clrRed]'); cbTypes.Items.Add('4: VR Simulation [clrPurple]'); cbTypes.Items.Add('6: Scientific Visualization [clrLime]'); cbTypes.Items.Add('7: Others [clrFlesh]'); cbTypes.Itemindex:=0; SpaceSceneFrm.cbTypes.Clear; {EarthForm.cbTypes.Items.Add(S);} SpaceSceneFrm.cbTypes.Items:=cbTypes.Items; // copied items to main form SpaceSceneFrm.cbTypes.ItemIndex:=0; end; procedure TEarthLocationsFrm.SaveListBtnClick(Sender: TObject); begin SaveTypeList; end; procedure TEarthLocationsFrm.SaveColorsBtnClick(Sender: TObject); begin SaveColors; end; procedure TEarthLocationsFrm.PhotoBtnClick(Sender: TObject); begin OpenDialog1.InitialDir:=EarthPhotoPath; if OpenDialog1.Execute then begin EarthPhotoPath:=OpenDialog1.InitialDir; PhotoEdit.Text:= ExtractFileName(OpenDialog1.FileName); end; end; procedure TEarthLocationsFrm.HelpBtnClick(Sender: TObject); begin Application.HelpContext(1300); end; end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, NtOrdinal, NtPattern; type TForm1 = class(TForm) Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label10: TLabel; Label11: TLabel; Label20: TLabel; Label101: TLabel; LanguageButton: TButton; FormGroup: TRadioGroup; PluralGroup: TRadioGroup; procedure FormCreate(Sender: TObject); procedure RadioClick(Sender: TObject); procedure LanguageButtonClick(Sender: TObject); private function GetOrdinalForm: TOrdinalForm; function GetPlural: TPlural; procedure UpdateValues; public property OrdinalForm: TOrdinalForm read GetOrdinalForm; property Plural: TPlural read GetPlural; end; var Form1: TForm1; implementation {$R *.dfm} uses NtLanguageDlg; function TForm1.GetOrdinalForm: TOrdinalForm; begin if FormGroup.ItemIndex = 0 then Result := ofShort else Result := ofLong end; function TForm1.GetPlural: TPlural; begin if PluralGroup.ItemIndex = 0 then Result := pfOne else Result := pfOther end; procedure TForm1.UpdateValues; procedure Process(count: Integer; messageLabel: TLabel); resourcestring SSingularSample = 'This is the %s attempt.'; //loc 0: Singular ordinal number such as "1st" or "first" SPluralSample = 'These are the %s attempts.'; //loc 0: Plural ordinal number such as "1st" or "first" begin if Plural = pfOne then messageLabel.Caption := Format(SSingularSample, [TNtOrdinal.Format(OrdinalForm, count, pfOne)]) else messageLabel.Caption := Format(SPluralSample, [TNtOrdinal.Format(OrdinalForm, count, pfOther)]); end; begin Process(1, Label1); Process(2, Label2); Process(3, Label3); Process(4, Label4); Process(5, Label5); Process(10, Label10); Process(11, Label11); Process(21, Label20); Process(101, Label101); end; procedure TForm1.FormCreate(Sender: TObject); begin FormGroup.ItemIndex := 0; PluralGroup.ItemIndex := 0; UpdateValues; end; procedure TForm1.RadioClick(Sender: TObject); begin UpdateValues; end; procedure TForm1.LanguageButtonClick(Sender: TObject); begin if TNtLanguageDialog.Select then UpdateValues; end; end.
unit Unit2; interface function GetValue: String; implementation function GetValue: String; begin Result := 'This is a sample'; end; end.
unit uFrmAdjustMinMaxAll; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, PaideTodosGeral, siComp, siLangRT, StdCtrls, Buttons, ExtCtrls; type TFrmAdjustMinMaxAll = class(TFrmParentAll) lbMin: TLabel; edtMin: TEdit; lbMax: TLabel; edtMax: TEdit; btnApply: TButton; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btCloseClick(Sender: TObject); procedure btnApplyClick(Sender: TObject); private function ValidateFields : Boolean; public function Start(var Min, Max: Double):Boolean; end; implementation uses uNumericFunctions; {$R *.dfm} { TFrmAdjustMinMaxAll } function TFrmAdjustMinMaxAll.Start(var Min, Max: Double): Boolean; begin Result := (ShowModal = mrOK); if edtMin.Text <> '' then Min := MyStrToDouble(edtMin.Text); if edtMax.Text <> '' then Max := MyStrToDouble(edtMax.Text); end; procedure TFrmAdjustMinMaxAll.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; Action := caFree; end; procedure TFrmAdjustMinMaxAll.btCloseClick(Sender: TObject); begin inherited; ModalResult := mrCancel; Close; end; procedure TFrmAdjustMinMaxAll.btnApplyClick(Sender: TObject); begin inherited; if not ValidateFields then ModalResult := mrNone; end; function TFrmAdjustMinMaxAll.ValidateFields: Boolean; begin Result := True; if (edtMin.Text <> '') and (edtMax.Text <> '') then if MyStrToDouble(edtMin.Text) >= MyStrToDouble(edtMax.Text) then begin Result := False; end; if (MyStrToDouble(edtMin.Text) < 0) or (MyStrToDouble(edtMax.Text) < 0) then begin Result := False; end; end; end.
{$i deltics.io.path.inc} unit Deltics.IO.Path; interface uses SysUtils, Deltics.Exceptions, Deltics.Uri; type EPathException = class(Exception); Path = class public class function Absolute(const aPath: String; const aRootPath: String = ''): String; class function AbsoluteToRelative(const aPath: String; const aBasePath: String = ''): String; class function Append(const aBase, aExtension: String): String; class function Branch(const aPath: String): String; overload; class function Branch(const aPath: String; var aParent: String): Boolean; overload; class function CurrentDir: String; class function Exists(const aPath: String): Boolean; class function IsAbsolute(const aPath: String): Boolean; class function IsNavigation(const aPath: String): Boolean; class function IsRelative(const aPath: String): Boolean; class function Leaf(const aPath: String): String; class function MakePath(const aElements: array of const): String; class function PathFromUri(const aUri: IUri): String; overload; class function PathFromUri(const aUri: String): String; overload; class function RelativeToAbsolute(const aPath: String; const aRootPath: String = ''): String; class function Volume(const aAbsolutePath: String): String; end; implementation uses Deltics.ConstArrays, Deltics.Strings; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Path.Absolute(const aPath, aRootPath: String): String; begin if IsAbsolute(aPath) then result := aPath else result := RelativeToAbsolute(aPath, aRootPath); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Path.AbsoluteToRelative(const aPath, aBasePath: String): String; var base: String; stem: String; nav: String; begin if NOT IsAbsolute(aPath) then raise EPathException.CreateFmt('''%s'' is not an absolute path', [aPath]); result := aPath; base := aBasePath; if base = '' then base := Path.CurrentDir; // If it is a sub-directory of the base path then we can just remove the base path // and prepend the "current directory" navigation if STR.BeginsWithText(aPath, base) then begin result := '.\' + Copy(aPath, Length(base) + 2, Length(aPath) - Length(base)); EXIT; end; // Otherwise, let's try progressively jumping up to parent directories and // if we eventually find a common root we can add directory navigation to // the relative path stem := base; nav := ''; while (stem <> '') do begin stem := Branch(stem); if nav <> '' then nav := '..\' + nav else nav := '..'; if STR.BeginsWithText(aPath, stem) then begin result := Append(nav, Copy(aPath, Length(stem) + 1, Length(aPath) - Length(stem))); BREAK; end; end; end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Path.Append(const aBase, aExtension: String): String; begin if aBase = '' then result := aExtension else if aExtension = '' then result := aBase else begin result := aBase; if aExtension[1] = '\' then begin if result[Length(result)] = '\' then SetLength(result, Length(result) - 1); end else if result[Length(result)] <> '\' then result := result + '\'; result := result + aExtension; end; end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Path.Branch(const aPath: String; var aParent: String): Boolean; { Returns in aParent the path containing the specified path or an empty string if the specified path has no parent. Examples: Branch( 'abc\def\ghi' ) ==> 'abc\def' Branch( 'abc' ) ==> '' Branch( 'c:\windows' ) ==> 'c:\' Branch( 'c:\windows\' ) ==> 'c:\' Branch( 'c:\' ) ==> '' Branch( '\\host\share' ) ==> '\\host' Branch( '\\host' ) ==> '' Branch( '\\host\' ) ==> '' } var i: Integer; begin result := FALSE; aParent := Trim(aPath); if Length(aParent) = 0 then EXIT; if aParent[Length(aParent)] = '\' then SetLength(aParent, Length(aParent) - 1); if (Length(aParent) >= 2) and (aParent[1] = '\') and (aParent[2] = '\') then {$ifdef DELPHIXE3__} result := Pos('\', aParent, 3) > 0 {$else} result := Pos('\', Copy(aParent, 3, Length(aParent) - 2)) > 0 {$endif} else result := Pos('\', aParent) > 0; if NOT result then begin aParent := ''; EXIT; end; for i := Length(aParent) downto 1 do begin if aParent[i] = '\' then begin SetLength(aParent, i - 1); BREAK; end; end; case Length(aParent) of 1 : if aParent[1] = '\' then aParent := ''; 2 : if aParent[2] = ':' then aParent := aParent + '\'; end; result := Length(aParent) > 0; end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Path.Branch(const aPath: String): String; begin Branch(aPath, result); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Path.CurrentDir: String; begin result := GetCurrentDir; end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Path.Exists(const aPath: String): Boolean; var target: UnicodeString; begin target := aPath; if NOT Path.IsAbsolute(target) then target := RelativeToAbsolute(target); result := DirectoryExists(target); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Path.IsAbsolute(const aPath: String): Boolean; begin result := (Copy(aPath, 1, 2) = '\\') or (Copy(aPath, 2, 2) = ':\'); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Path.IsNavigation(const aPath: String): Boolean; begin case Length(aPath) of 1 : result := aPath[1] = '.'; 2 : result := (aPath[1] = '.') and (aPath[2] = '.'); else result := FALSE; end; end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Path.IsRelative(const aPath: String): Boolean; begin result := NOT IsAbsolute(aPath); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Path.Leaf(const aPath: String): String; { Returns the file or folder identified by the specified path. Examples: Leaf( 'abc\def\ghi' ) ==> 'ghi' } begin result := ExtractFilename(aPath); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Path.MakePath(const aElements: array of const): String; var i: Integer; strs: StringArray; begin result := ''; SetLength(strs, 0); if Length(aElements) = 0 then EXIT; strs := ConstArray.AsStringArray(aElements); result := strs[0]; for i := 1 to High(strs) do result := Path.Append(result, strs[i]); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Path.PathFromUri(const aUri: String): String; var uri: IUri; begin uri := TUri.Create(aUri); result := uri.AsFilePath; end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Path.PathFromUri(const aUri: IUri): String; begin result := aUri.AsFilePath; end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Path.RelativeToAbsolute(const aPath: String; const aRootPath: String): String; var cd: String; begin result := aPath; try if IsAbsolute(aPath) then EXIT; if aRootPath = '' then cd := GetCurrentDir else cd := aRootPath; if NOT IsAbsolute(cd) then raise EPathException.Create('Specified root for relative path must be a fully qualified path (UNC or drive letter)'); if cd[Length(cd)] = '\' then SetLength(cd, Length(cd) - 1); if (aPath = '.') or (aPath = '.\') then begin result := cd; EXIT; end; if aPath = '..' then begin result := Branch(cd); EXIT; end; if aPath[1] = '\' then begin result := Path.Volume(cd) + aPath; end else if Copy(aPath, 1, 3) = '..\' then begin result := aPath; repeat Delete(result, 1, 3); cd := Branch(cd) until Copy(result, 1, 2) <> '..'; result := cd + '\' + result; end else if Copy(aPath, 1, 2) = '.\' then begin result := aPath; Delete(result, 1, 2); result := cd + '\' + result; end else result := cd + '\' + aPath; finally if (Length(result) > 0) and STR.EndsWith(result, '\') then STR.DeleteRight(result, 1); end; end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Path.Volume(const aAbsolutePath: String): String; var i: Integer; target: String; begin target := aAbsolutePath; if NOT Path.IsAbsolute(target) then raise EPathException.Create('Specified path must be a fully qualified path (UNC or drive letter)'); if target[2] = ':' then begin result := Copy(target, 1, 2); EXIT; end; if Copy(target, 1, 2) = '\\' then begin Delete(target, 1, 2); result := '\\'; i := Pos('\', target); if i > 0 then begin result := result + Copy(target, 1, i); Delete(target, 1, i); i := Pos('\', target); if i > 0 then begin result := result + Copy(target, 1, i - 1); EXIT; end; end; end; raise EPathException.CreateFmt('''%s'' is not a fully qualified path (UNC or drive letter)', [aAbsolutePath]); end; end.
unit ThItemStorage; interface uses ThTypes, ThClasses, ThItem; type TThItemStorage = class(TThInterfacedObject, IThObserver) private FSubject: IThSubject; FItems: TThItems; function GetItemCount: Integer; public constructor Create; destructor Destroy; override; procedure Notifycation(ACommand: IThCommand); procedure SetSubject(ASubject: IThSubject); property ItemCount: Integer read GetItemCount; end; implementation uses ThItemCommand, ThSystemCommand; { TThItemStorage } constructor TThItemStorage.Create; begin FItems := TThItems.Create; end; destructor TThItemStorage.Destroy; begin FSubject.UnregistObserver(Self); FItems.Free; inherited; end; function TThItemStorage.GetItemCount: Integer; begin Result := FItems.Count; end; procedure TThItemStorage.SetSubject(ASubject: IThSubject); begin FSubject := ASubject; FSubject.RegistObserver(Self); end; procedure TThItemStorage.Notifycation(ACommand: IThCommand); var I: Integer; Item: TThItem; begin if ACommand is TThCommandItemAdd then begin // 중복되는 일은 없겠지?? FItems.AddRange(TThCommandItemAdd(ACommand).Items); end else if ACommand is TThCommandSystemItemDestroy then begin for I := 0 to TTHCommandSystemItemDestroy(ACommand).Items.Count - 1 do begin Item := TTHCommandSystemItemDestroy(ACommand).Items[I]; if not Assigned(Item) then Continue; FItems.Remove(Item); Item.Free; end; end; end; end.
unit PromoClass; interface uses PromoDiscountInterface, dbClient, uSystemConst, PromoConfigClass, udm, PromoItemClass, contnrs, PromoDiscountFactoryClass; type TPromo = class private fPromoDiscountFactory: TPromoDiscountFactory; fFlatPromo: Boolean; protected fdiscount: IPromoDiscount; fPromoConfig: TPromoConfig; fDatePromo: TDateTime; procedure setPromoDiscount(arg_promoDiscount: IPromoDiscount); procedure addQuantity(arg_promoItem: TPromoItem); public ItemsPromoXList: TObjectList; constructor create(arg_item: TPromoItem); procedure setFlatPromo(arg_flat: Boolean); function getFlatPromo(): Boolean; function getPromoDiscount(arg_item: TPromoItem): Double; virtual; abstract; end; implementation { TPromo } constructor TPromo.create(arg_item: TPromoItem); begin fPromoDiscountFactory := TPromoDiscountFactory.Create(); fdiscount := fPromoDiscountFactory.createPromoDiscount(arg_item); itemsPromoXList := TObjectList.Create(true); end; function TPromo.getFlatPromo: Boolean; begin result := fFlatPromo; end; procedure TPromo.setFlatPromo(arg_flat: Boolean); begin fFlatPromo := arg_flat; end; procedure TPromo.setPromoDiscount(arg_promoDiscount: IPromoDiscount); begin fdiscount := arg_promoDiscount; end; procedure TPromo.addQuantity(arg_promoItem: TPromoItem); var i: Integer; itemPromo: TPromoItem; begin for i:= ItemsPromoXList.Count - 1 to 0 do begin itemPromo := TPromoItem(itemsPromoXlist.Items[i]); if ( itemPromo.getIdModel = arg_promoItem.getIdModel ) then begin arg_promoItem.addQuantityToToTal(arg_promoItem.getQuantity); break; end; end; end; end.
unit DPM.Core.Tests.PathUtils; interface uses DUnitX.TestFramework; type [TestFixture] TPathUtilsTests = class public [Test] [TestCase('Simple', 'c:\test\foo\..\bar,c:\test\bar')] [TestCase('SimpleDot', 'c:\test\foo\.\bar,c:\test\foo\bar')] [TestCase('UNC', '\\test\foo\..\bar,\\test\bar')] [TestCase('Unrooted', 'test\foo\..\bar,test\bar')] procedure TestCompressRelativePath(const input, expected : string); [Test] [TestCase('UNCBase1', '\\test,\foo\..\bar,\\test\bar')] [TestCase('UNCBase2', '\\test,foo\..\bar,\\test\bar')] [TestCase('UNCBase3', '\\test\,foo\..\bar,\\test\bar')] [TestCase('UNCBase4', '\\test\,\foo\..\bar,\\test\bar')] [TestCase('Rooted', 'c:\test\,foo\..\bar,c:\test\bar')] procedure TestCompressRelativePathWithBase(const base, input, expected : string); [Test] procedure TestIsRelativePath; end; implementation uses System.SysUtils, DPM.Core.Utils.Path; { TPathUtilsTests } procedure TPathUtilsTests.TestCompressRelativePath(const input, expected: string); var actual : string; begin actual := TPathUtils.CompressRelativePath(input); Assert.AreEqual(expected, actual); end; procedure TPathUtilsTests.TestCompressRelativePathWithBase(const base, input, expected: string); var actual : string; begin actual := TPathUtils.CompressRelativePath(Trim(base), Trim(input)); Assert.AreEqual(Trim(expected), actual); end; function IsRelativePath2(const Path: string): Boolean; var L: Integer; begin L := Length(Path); Result := (L > 0) and (Path[1] <> PathDelim) {$IFDEF MSWINDOWS}and (L > 1) and (Path[2] <> ':'){$ENDIF MSWINDOWS}; end; procedure TPathUtilsTests.TestIsRelativePath; begin Assert.IsTrue((IsRelativePath2('\\..\test'))); end; initialization TDUnitX.RegisterTestFixture(TPathUtilsTests); end.
unit uSysModules; interface uses Classes, SysUtils, Variants, ADODB; const //Import/Export CAT_PRICE_COM = 'CAT_PRICE_COM'; //Catalog - Price Comparison CAT_INV_UPD = 'CAT_INV_UPD'; //Catalog - Inventory Update CAT_SRCH = 'CAT_SRCH'; //Catalog - Catalog Search CAT_SYNC = 'CAT_SYNC'; //Catalog - Synchronize Data EXP_PO = 'EXP_PO'; //Export - Purchase Order EXP_PEACHTREE = 'EXP_PEACHTREE'; //Export - Peachtree IMP_PO = 'IMP_PO'; //Import - Purchase Order File IMP_INV = 'IMP_INV'; //Import - Inventory File IMP_ENTITY = 'IMP_ENTITY'; //Import - Entity File IMP_PET = 'IMP_PET'; //Import - Pet File type TSoftware = class SoftwareName : String; Expires : TDateTime; Computers : Integer; Users : Integer; Modules : WideString; end; TMainRetailSystem = class Key : String; FSoftwareList : TStringList; FQuery : TADOQuery; FADODBConnect: TADOConnection; function GetKey : Boolean; public constructor Create(); destructor Destroy(); override; end; { 1 - Pegar a chave do banco 2 - baixar do site http://license.mainretail.net/4D57ED29-7F37-464B-89B9-FD1A1ECAB4AE.lic 3 - Comparar a chave 4 - Preencher o objeto de software com modulos 5 - Gravar os modulos no banco de dados } implementation { TMainRetailSystem } constructor TMainRetailSystem.Create; begin FSoftwareList := TStringList.Create; FQuery := TADOQuery.Create(nil); end; destructor TMainRetailSystem.Destroy; var obj : TObject; begin if Assigned(FSoftwareList) then begin while FSoftwareList.Count > 0 do begin obj := FSoftwareList.Objects[0]; if (obj <> nil) then FreeAndNil(obj); FSoftwareList.Delete(0); end; FreeAndNil(FSoftwareList); end; FreeAndNil(FQuery); inherited; end; function TMainRetailSystem.GetKey: Boolean; begin Result := True; FQuery.Connection := FADODBConnect; end; end.
unit frmWizardCreateVolume; // Description: // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // interface uses // delphi Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ExtCtrls, MouseRNG, // sdu common Shredder, SDUGeneral, SDURandPool, SDUStdCtrls, SDUForms, SDUFrames, SDUSpin64Units, PasswordRichEdit, Spin64, //librecrypt specific OTFEFreeOTFEBase_U, VolumeFileAPI, // Required for TVOLUME_CRITICAL_DATA DriverAPI, // Required for CRITICAL_DATA_LEN fmeSelectPartition, OTFEFreeOTFE_PasswordRichEdit, frmWizard, OTFEFreeOTFE_InstructionRichEdit, lcDialogs, SDUDialogs, fmeNewPassword; type TfrmWizardCreateVolume = class (TfrmWizard) tsFilename: TTabSheet; tsHashCypherIV: TTabSheet; Label4: TLabel; Label5: TLabel; cbHash: TComboBox; cbCypher: TComboBox; tsRNGSelect: TTabSheet; tsSize: TTabSheet; Label6: TLabel; tsOffset: TTabSheet; pnlWarningOffset: TPanel; lblWarningOffset: TLabel; tsPassword: TTabSheet; reInstructFilename1: TLabel; reInstructOffset: TLabel; reInstructSize: TLabel; reInstructHashCypherIV: TLabel; reInstructRNGSelect1: TLabel; Label13: TLabel; GroupBox1: TGroupBox; pbBrowseFilename: TButton; Label7: TLabel; SaveDialog: TSDUSaveDialog; tsRNGMouseMovement: TTabSheet; reInstructRNGMouseMovement1: TLabel; tsSummary: TTabSheet; reSummary: TRichEdit; tsRNGGPG: TTabSheet; reInstructRNGGPG: TLabel; GroupBox2: TGroupBox; lblGPGFilename: TSDUFilenameLabel; pbBrowseGPG: TButton; GPGOpenDialog: TSDUOpenDialog; MouseRNG: TMouseRNG; tsMasterKeyLength: TTabSheet; reInstructMasterKeyLen: TLabel; Label2: TLabel; seMasterKeyLength: TSpinEdit64; Label9: TLabel; lblMouseRNGBits: TLabel; pbHashInfo: TButton; pbCypherInfo: TButton; tsFileOrPartition: TTabSheet; tsPartitionSelect: TTabSheet; reInstructPartitionSelect: TLabel; rgFileOrPartition: TRadioGroup; Label21: TLabel; ckPartitionHidden: TCheckBox; ckUsePerVolumeIV: TCheckBox; cbSectorIVGenMethod: TComboBox; lblSectorIVGenMethod: TLabel; tsPartitionWarning: TTabSheet; gbRNG: TGroupBox; ckRNGMouseMovement: TCheckBox; ckRNGCryptoAPI: TCheckBox; ckRNGcryptlib: TCheckBox; ckRNGPKCS11: TCheckBox; tsRNGPKCS11: TTabSheet; cbToken: TComboBox; lblToken: TLabel; pbRefresh: TButton; reInstructRNGPKCS11: TLabel; ckSizeEntirePartitionDisk: TCheckBox; lblPartitionDiskSize: TLabel; fmeSelectPartition: TfmeSelectPartition; reInstructSummary: TLabel; se64UnitByteOffset: TSDUSpin64Unit_Storage; se64UnitSize: TSDUSpin64Unit_Storage; reInstructWarningOffset1: TLabel; ckAutoMountAfterCreate: TCheckBox; tsKeyIterations: TTabSheet; reInstructKeyIterations1: TLabel; Label1: TLabel; seKeyIterations: TSpinEdit64; tsSalt: TTabSheet; seSaltLength: TSpinEdit64; Label8: TLabel; Label10: TLabel; tsDriveLetter: TTabSheet; lblInstructDriveLetter1: TLabel; Label11: TLabel; cbDriveLetter: TComboBox; tsCDBLocation: TTabSheet; reInstructCDBLocation: TLabel; rbCDBInVolFile: TRadioButton; rbCDBInKeyfile: TRadioButton; gbKeyfile: TGroupBox; lblKeyFilename: TSDUFilenameLabel; pbBrowseKeyfile: TButton; keySaveDialog: TSDUSaveDialog; tsPadding: TTabSheet; reInstructPadding: TLabel; Label12: TLabel; Label14: TLabel; tsChaff: TTabSheet; lblInstructChaff1: TLabel; ckRNGGPG: TCheckBox; lblFilename: TEdit; Label15: TLabel; reInstructPartitionWarning1: TLabel; lblWarningPartition: TLabel; rgOverwriteType: TRadioGroup; se64Padding: TSpinEdit64; lblFinished: TLabel; lblWelcomeBanner: TLabel; lblWelcomeClickNext: TLabel; lblInstructSalt1: TLabel; lblInstructFileOrPartition1: TLabel; lblInstructDriveLetter2: TLabel; reInstructRNGSelect2: TLabel; reInstructPartitionWarning2: TLabel; reInstructPartitionWarning3: TLabel; reInstructWarningOffset2: TLabel; reInstructWarningOffset4: TLabel; reInstructWarningOffset3: TLabel; lblInstructChaff4: TLabel; lblInstructChaff3: TLabel; lblInstructChaff2: TLabel; reInstructRNGSelect4: TLabel; reInstructRNGSelect3: TLabel; reInstructRNGSelect5: TLabel; reInstructRNGMouseMovement2: TLabel; reInstructKeyIterations3: TLabel; reInstructKeyIterations2: TLabel; lblInstructSalt4: TLabel; lblInstructSalt3: TLabel; lblInstructSalt2: TLabel; lblInstructFileOrPartition3: TLabel; lblInstructFileOrPartition2: TLabel; reInstructFilename2: TLabel; frmeNewPassword: TfrmeNewPassword; procedure pbBrowseFilenameClick(Sender: TObject); procedure ckRNGClick(Sender: TObject); procedure fmePasswordChange(Sender: TObject); procedure edByteOffsetChange(Sender: TObject); procedure SizeChanged(Sender: TObject); procedure pbBrowseGPGClick(Sender: TObject); procedure MouseRngByteGenerated(Sender: TObject; random: Byte); procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure cbHashCypherIVGenChange(Sender: TObject); procedure pbFinishClick(Sender: TObject); procedure seMasterKeyLengthChange(Sender: TObject); procedure seMasterKeyLengthExit(Sender: TObject); procedure pbHashInfoClick(Sender: TObject); procedure pbCypherInfoClick(Sender: TObject); procedure rbCDBLocationClick(Sender: TObject); procedure ckPartitionHiddenClick(Sender: TObject); procedure rgFileOrPartitionClick(Sender: TObject); procedure seSizeExit(Sender: TObject); procedure pbRefreshClick(Sender: TObject); procedure ckSizeEntirePartitionDiskClick(Sender: TObject); procedure seSizeChange(Sender: TObject); procedure se64ByteOffsetChange(Sender: TObject); procedure rbCDBLocationClick2(Sender: TObject); procedure pbBrowseKeyfileClick(Sender: TObject); procedure cbDriveLetterChange(Sender: TObject); private // Advanced options... // fkeyIterations: Integer; // fsaltLength: Integer; // Length in *bits* // frequestedDriveLetter: ansichar; // fCDBFilename: String; // fpaddingLength: ULONGLONG; // foverwriteWithChaff: Boolean; fNewVolumeMountedAs: Char; // These are ordered lists corresponding to the items shown in the combobox fHashKernelModeDriverNames: TStringList; fHashGUIDs: TStringList; fCypherKernelModeDriverNames: TStringList; fCypherGUIDs: TStringList; fIVGenMethodIDs: TStringList; fDeviceList: TStringList; fDeviceTitle: TStringList; // Used for overwriting ftempCypherDetails: TFreeOTFECypher_v3; ftempCypherUseKeyLength: Integer; // In *bits* ftempCypherKey: TSDUBytes; ftempCypherEncBlockNo: Int64; // fcanUseCryptlib: Boolean; fPKCS11TokensAvailable: Boolean; // When the user selects a cypher, we cache it's keysize for later use. // This is set to CYPHER_KEYSIZE_NOT_CACHED_FLAG_KEYSIZE to indicate no keysize is cached fcachedCypherKeysize: Integer; // When the user selects a cypher, we cache it's blocksize for later use. // This is set to CYPHER_BLOCKSIZE_NOT_CACHED_FLAG_BLOCKSIZE to indicate no blocksize is cached fcachedCypherBlocksize: Integer; // When the user selects a cypher, we cache it's mode for later use. fcachedCypherMode: TFreeOTFECypherMode; // Returns the keysize for the user's selected cypher, as returned by the // driver function selectedCypherKeySize(): Integer; // Returns the blocksize for the user's selected cypher, as returned by the // driver function selectedCypherBlockSize(): Integer; // Returns the cypher mode for the user's selected cypher, as returned by // the driver function selectedCypherMode(): TFreeOTFECypherMode; function GetRNGSet(): TRNGSet; function getIsPartition(): Boolean; function getVolFilename(): String; procedure SetVolFilename(filename: String); function getOffset(): ULONGLONG; // Note: The size returned *excludes* the size of the critical data function getSize(): ULONGLONG; // HashDriver - Kernel drivers: HashKernelDeviceName // DLL drivers: HashLibFilename function getHashDriver(): String; function getHashGUID(): TGUID; // CypherDriver - Kernel drivers: CypherKernelDeviceName // DLL drivers: CypherLibFilename function getCypherDriver(): Ansistring; function getCypherGUID(): TGUID; function GetSectorIVGenMethod(): TFreeOTFESectorIVGenMethod; procedure SetSectorIVGenMethod(sectorIVGenMethod: TFreeOTFESectorIVGenMethod); function GetUsePerVolumeIV(): Boolean; function GetMasterKeyLength(): Integer; // Returns length in *bits* // function GetRandomData_CDB(): Ansistring; function GetRandomData_PaddingKey(): TSDUBytes; function GetIsHidden(): Boolean; function GetCDBInVolFile(): Boolean; function GetAutoMountAfterCreate(): Boolean; procedure PopulateHashes(); procedure PopulateCyphers(); procedure PopulateSectorIVGenMethods(); procedure PopulatePKCS11Tokens(); procedure PopulateSummary(); procedure GetCDBFileAndOffset(out cdbFile: String; out cdbOffset: ULONGLONG); function OverwriteVolWithChaff(): Boolean; procedure GenerateOverwriteData(Sender: TObject; passNumber: Integer; bytesRequired: Cardinal; var generatedOK: Boolean; var outputBlock: TShredBlock ); function CreateNewVolume(): Boolean; procedure PostCreate(); procedure PostMount_Format_using_dll(); procedure Update_tempCypherUseKeyLength; function GetDriveLetter: Char; procedure SetDriveLetter(driveLetter: Char); function GetCDBFilename: String; procedure SetCDBFilename(CDBFilename: String); function GetPaddingLength: Int64; procedure SetPaddingLength(len: Int64); function GetOverwriteWithChaff: Boolean; procedure SetOverwriteWithChaff(secChaff: Boolean); protected procedure EnableDisableControls(); override; function IsTabComplete(checkTab: TTabSheet): Boolean; override; function IsTabSkipped(tabSheet: TTabSheet): Boolean; override; function IsTabRequired(tabSheet: TTabSheet): Boolean; override; function RNG_requiredBits(): Integer; procedure FormWizardStepChanged(Sender: TObject); public // property isPartition: Boolean Read GetIsPartition; // property volFilename: Ansistring Read GetVolFilename Write SetVolFilename; // property offset: ULONGLONG Read GetOffset; // property size: ULONGLONG Read GetSize; // property hashDriver: Ansistring Read GetHashDriver; // property hashGUID: TGUID Read GetHashGUID; // property cypherDriver: Ansistring Read GetCypherDriver; // property cypherGUID: TGUID Read GetCypherGUID; // property sectorIVGenMethod: TFreeOTFESectorIVGenMethod Read GetSectorIVGenMethod; // property usePerVolumeIV: Boolean Read GetUsePerVolumeIV; // property masterKeyLength: Integer Read GetMasterKeyLength; // In *bits* // property randomData_CDB: Ansistring Read GetRandomData_CDB; // property randomData_PaddingKey: Ansistring Read GetRandomData_PaddingKey; // property password: Ansistring Read GetPassword; // property keyIterations: Integer Read FKeyIterations Write FKeyIterations; // property saltLength: Integer Read FSaltLength Write FSaltLength; // In *bits* // property requestedDriveLetter: ansichar Read FRequestedDriveLetter Write fRequestedDriveLetter; // property keyFilename: String Read FCDBFilename Write FCDBFilename; // property CDBInVolFile: Boolean Read GetCDBInVolFile; // property paddingLength: ULONGLONG Read FPaddingLength Write FPaddingLength; // property overwriteWithChaff: Boolean Read FOverwriteWithChaff Write FOverwriteWithChaff; // property autoMountAfterCreate: Boolean Read GetAutoMountAfterCreate; // property newVolumeMountedAs: Ansichar Read fnewVolumeMountedAs Write fnewVolumeMountedAs; // property isHidden: Boolean Read GetIsHidden; procedure fmeSelectPartitionChanged(Sender: TObject); end; procedure Format_drive(drivesToFormat: DriveLetterString; frm: TForm); implementation {$R *.DFM} uses Math, ActiveX, // Required for IsEqualGUID ComObj, // Required for StringToGUID //sdu SDUi18n, SDPartitionImage, SDPartitionImage_File, SDFilesystem, SDFilesystem_FAT, //freeotfe/LibreCrypt OTFEConsts_U, // Required for OTFE_ERR_USER_CANCEL OTFEFreeOTFEDLL_U, PKCS11Lib, PartitionImageDLL; {$IFDEF _NEVER_DEFINED} // This is just a dummy const to fool dxGetText when extracting message // information // This const is never used; it's #ifdef'd out - SDUCRLF in the code refers to // picks up SDUGeneral.SDUCRLF const SDUCRLF = ''#13#10; {$ENDIF} const // If they're available, use these as defaults... DEFAULT_CYPHER_TITLE = 'AES (256 bit XTS)'; DEFAULT_HASH_TITLE = 'SHA-512'; DEFAULT_SECTOR_IV_GEN_METHOD = foivg64BitSectorID; DUMMY_GUID = '{00000000-0000-0000-0000-000000000000}'; CYPHER_KEYSIZE_NOT_CACHED_FLAG_KEYSIZE = -9999; CYPHER_BLOCKSIZE_NOT_CACHED_FLAG_BLOCKSIZE = -9999; WARNING_BORDER_WIDTH = 10; // (4GB - 1 byte) is the max file a FAT32 system can support MAX_FAT_FILESIZE: ULONGLONG = ((ULONGLONG(4) * ULONGLONG(BYTES_IN_GIGABYTE)) - ULONGLONG(1)); // for shformat // Format disk related functions ripped from the Unofficial Delphi FAQ (UDF) SHFMT_ID_DEFAULT = $FFFF; // Formating options SHFMT_OPT_QUICKFORMAT = $0000; SHFMT_OPT_FULL = $0001; SHFMT_OPT_SYSONLY = $0002; // Error codes SHFMT_ERROR = $FFFFFFFF; SHFMT_CANCEL = $FFFFFFFE; SHFMT_NOFORMAT = $FFFFFFFD; resourcestring FILEORPART_OPT_VOLUME_FILE = 'Container file'; FILEORPART_OPT_PARTITION = 'Partition/entire disk'; // External function in shell32.dll function SHFormatDrive(Handle: HWND; Drive, ID, Options: Word): Longint; stdcall; external 'shell32.dll' Name 'SHFormatDrive'; procedure TfrmWizardCreateVolume.FormShow(Sender: TObject); var idx: Integer; begin inherited; SDUTranslateComp(reInstructKeyIterations1); SDUTranslateComp(reInstructKeyIterations2); SDUTranslateComp(reInstructKeyIterations3); SDUTranslateComp(lblInstructSalt1); SDUTranslateComp(lblInstructSalt2); SDUTranslateComp(lblInstructSalt3); SDUTranslateComp(lblInstructSalt4); SDUTranslateComp(lblInstructDriveLetter1); SDUTranslateComp(lblInstructDriveLetter2); SDUTranslateComp(reInstructPartitionSelect); SDUTranslateComp(reInstructPartitionWarning1); SDUTranslateComp(reInstructPartitionWarning2); SDUTranslateComp(reInstructPartitionWarning3); SDUTranslateComp(lblInstructFileOrPartition1); SDUTranslateComp(lblInstructFileOrPartition2); SDUTranslateComp(lblInstructFileOrPartition3); SDUTranslateComp(reInstructCDBLocation); SDUTranslateComp(reInstructPadding); SDUTranslateComp(lblInstructChaff1); SDUTranslateComp(lblInstructChaff2); SDUTranslateComp(lblInstructChaff3); SDUTranslateComp(lblInstructChaff4); SDUTranslateComp(reInstructOffset); SDUTranslateComp(reInstructWarningOffset1); SDUTranslateComp(reInstructWarningOffset2); SDUTranslateComp(reInstructWarningOffset3); SDUTranslateComp(reInstructWarningOffset4); SDUTranslateComp(reInstructSize); { TODO 1 -otdk -ceasify : why mutiple of 512? simplify text } SDUTranslateComp(reInstructHashCypherIV); SDUTranslateComp(reInstructMasterKeyLen); SDUTranslateComp(reInstructRNGSelect1); SDUTranslateComp(reInstructRNGSelect2); SDUTranslateComp(reInstructRNGSelect3); SDUTranslateComp(reInstructRNGSelect4); SDUTranslateComp(reInstructRNGSelect5); SDUTranslateComp(reInstructRNGMouseMovement1); SDUTranslateComp(reInstructRNGMouseMovement2); SDUTranslateComp(reInstructRNGPKCS11); SDUTranslateComp(reInstructRNGGPG); SDUTranslateComp(reInstructSummary); // Center label (done dynamically due to language translation size // differences) SDUCenterControl(lblWelcomeBanner, ccHorizontal); SDUCenterControl(lblWelcomeClickNext, ccHorizontal); SDUCenterControl(lblWarningPartition, ccHorizontal); SDUCenterControl(lblWarningOffset, ccHorizontal); seKeyIterations.Value := DEFAULT_KEY_ITERATIONS; seSaltLength.Value := DEFAULT_SALT_LENGTH; SetDriveLetter(#0); SetCDBFilename(''); SetPaddingLength(0); SetOverwriteWithChaff(True); // preserve plausible deniability by defaulting to true ftempCypherUseKeyLength := 0; fnewVolumeMountedAs := #0; pnlWarningOffset.Caption := ''; // Create a border around the warning // We can't just place a bigger panel under the warning panel, as on a // Windows system with themes, the top panel turns red, and the (red) text // can't be read. { DONE 1 -otdk -crefactor : clean this up, just use background, - so can use align property } { TODO 1 -otdk -ccomplete : check text doesnt dissappear with themes -if so just reset colour } // tsFileOrPartition rgFileOrPartition.Items.Clear(); rgFileOrPartition.Items.Add(FILEORPART_OPT_VOLUME_FILE); rgFileOrPartition.Items.Add(FILEORPART_OPT_PARTITION); rgFileOrPartition.ItemIndex := rgFileOrPartition.Items.IndexOf(FILEORPART_OPT_VOLUME_FILE); // tsPartitionSelect // Setup and make sure nothing is selected fmeSelectPartition.AllowCDROM := False; fmeSelectPartition.OnChange := fmeSelectPartitionChanged; // fmeSelectPartition.Initialize(); fmeSelectPartition.Tag := 1; // tsFilename lblFilename.Text := ''; // tsOffset se64UnitByteOffset.Value := 0; // tsSize // Default to 25 MB // se64UnitSize.Value := DEFAULT_VOLUME_SIZE; // tsHashCypherIV PopulateHashes(); PopulateCyphers(); PopulateSectorIVGenMethods(); // Autoselect default, if available if (cbHash.Items.Count > 0) then begin idx := cbHash.Items.IndexOf(DEFAULT_HASH_TITLE); if (idx = -1) then begin // If we can't find the default, force the user to select manually idx := -1; end; cbHash.ItemIndex := idx; end; // Autoselect default, if available if (cbCypher.Items.Count > 0) then begin idx := cbCypher.Items.IndexOf(DEFAULT_CYPHER_TITLE); if (idx = -1) then begin // If we can't find the default, force the user to select manually idx := -1; end; cbCypher.ItemIndex := idx; end; // Default sector IV generation method SetSectorIVGenMethod(DEFAULT_SECTOR_IV_GEN_METHOD); // Default to using per-volume IVs ckUsePerVolumeIV.Checked := True; // tsMasterKeyLen seMasterKeyLength.Increment := 8; seMasterKeyLength.Value := DEFAULT_CYPHER_KEY_LENGTH; // In bits // tsRNG //MSCryptoAPI enabled as default (in dfm) ckRNGcryptlib.Enabled := GetRandPool().CanUseCryptLib; if ckRNGcryptlib.Enabled then ckRNGcryptlib.Checked := True; ckRNGPKCS11.Enabled := PKCS11LibraryReady(GetFreeOTFEBase().PKCS11Library); // tsRNGMouseMovement InitMouseRNGData(); // tsRNGPKCS11 PopulatePKCS11Tokens(); // tsRNGGPG lblGPGFilename.Caption := ''; // BECAUSE WE DEFAULTED TO USING A VOLUME *FILE*, WE MUST SET THE PARTITION // SELECT PAGE TO "DONE" HERE (otherwise, it'll never be flagged as complete // if the user doesn't switch) tsPartitionWarning.Tag := 1; tsPartitionSelect.Tag := 1; tsOffset.Tag := 1; // only reset if new file chosen (hidden) // BECAUSE WE DEFAULTED TO USING THE MOUSERNG, WE MUST SET THE GPG PAGE TO // "DONE" HERE (otherwise, it'll never be flagged as complete if the user // doens't switch RNGs) // tsRNGGPG.Tag := 1; set to not req'd ckAutoMountAfterCreate.Checked := True; // Note: ckAutoMountAfterCreate.Visible set in EnableDisableControls(...); // if it's set to FALSE here, the control still appears for some // reason?! lblFinished.Visible := False;//'click finished or next' UpdateUIAfterChangeOnCurrentTab(); end; //all non-skipped tabs that are not required to be completed are listed here function TfrmWizardCreateVolume.IsTabRequired(tabSheet: TTabSheet): Boolean; begin Result := not ((tabSheet = tsDriveLetter) or (tabSheet = tsHashCypherIV) or (tabSheet = tsChaff) or (tabSheet = tsMasterKeyLength) or (tabSheet = tsRNGSelect) or (tabSheet = tsRNGMouseMovement) or (tabSheet = tsRNGGPG) or (tabSheet = tsRNGPKCS11) or (tabSheet = tsKeyIterations) or (tabSheet = tsSalt) or (tabSheet = tsCDBLocation) or (tabSheet = tsPadding) or (tabSheet = tsSummary)); end; // Returns TRUE if the specified tab should be skipped, otherwise FALSE function TfrmWizardCreateVolume.IsTabSkipped(tabSheet: TTabSheet): Boolean; begin Result := inherited IsTabSkipped(tabSheet); // DLL doesn't currently support partitions if (tabSheet = tsFileOrPartition) then Result := (GetFreeOTFEBase() is TOTFEFreeOTFEDLL); // If the user isn't creating a volume within a volume file, skip that tab if (tabSheet = tsFilename) then Result := GetIsPartition(); // If the user isn't creating a volume on a partition, skip that tab if (tabSheet = tsPartitionWarning) then Result := not GetIsPartition(); // If the user isn't creating a volume on a partition, skip that tab if (tabSheet = tsPartitionSelect) then Result := not GetIsPartition(); // Skip offset if user isn't creating a hidden volume if (tabSheet = tsOffset) then Result := not GetIsHidden(); // If the user's selected cypher has a keysize >= 0, skip the tsMasterKeyLength tabsheet if (tabSheet = tsMasterKeyLength) then begin if ((cbHash.ItemIndex > -1) and (cbCypher.ItemIndex > -1)) then begin Result := (SelectedCypherKeySize() >= 0); end; end; // If the user *isn't* using the mouse movement RNG, skip the tsRNGMouseMovement tabsheet if (tabSheet = tsRNGMouseMovement) then Result := not (rngMouseMovement in GetRNGSet()); // If the user *isn't* using the PKCS#11 token RNG, skip the tsRNGPKCS11 tabsheet if (tabSheet = tsRNGPKCS11) then Result := not (rngPKCS11 in GetRNGSet()); // If the user *isn't* using the GPG RNG, skip the tsRNGGPG tabsheet if (tabSheet = tsRNGGPG) then Result := not (rngGPG in GetRNGSet()); end; procedure TfrmWizardCreateVolume.Update_tempCypherUseKeyLength; begin // If overwriting with encrypted data (chaff), find the size of the key required ftempCypherUseKeyLength := 0; if GetOverwriteWithChaff() then begin GetFreeOTFEBase().GetSpecificCypherDetails(GetCypherDriver(), GetCypherGUID(), ftempCypherDetails); // Get *real* random data for encryption key if (ftempCypherDetails.KeySizeRequired < 0) then begin // -ve keysize = arbitary keysize supported - just use 512 bits ftempCypherUseKeyLength := 512; end else begin if (ftempCypherDetails.KeySizeRequired > 0) then begin // +ve keysize = specific keysize - get sufficient bits ftempCypherUseKeyLength := ftempCypherDetails.KeySizeRequired; end; end; end; end; procedure TfrmWizardCreateVolume.EnableDisableControls(); var useSectorIVs: Boolean; begin inherited; pbHashInfo.Enabled := ((GetHashDriver <> '') and (not (IsEqualGUID(GetHashGUID(), StringToGUID(DUMMY_GUID))))); pbCypherInfo.Enabled := ((GetCypherDriver <> '') and (not (IsEqualGUID(GetCypherGUID(), StringToGUID(DUMMY_GUID))))); // If: // *) The selected cypher's blocksize is zero of variable, or // *) The cypher uses LRW, or // *) The cypher uses LRW // sector IVs aren't/cannot be used useSectorIVs := True; if (cbCypher.ItemIndex >= 0) then begin useSectorIVs := (SelectedCypherBlockSize() > 0) and (SelectedCypherMode() <> focmLRW) and (SelectedCypherMode() <> focmXTS); end; if not (useSectorIVs) then begin ckUsePerVolumeIV.Checked := False; SetSectorIVGenMethod(foivgNone); end; SDUEnableControl(cbSectorIVGenMethod, useSectorIVs); SDUEnableControl(ckUsePerVolumeIV, useSectorIVs); // Volume size related... // If the user is creating a volume on a partition/disk, give the user the // option of using the whole partition/disk's space // ...But if the user's creating a hidden partition - make sure they enter // the size // Weird, without this FALSE/TRUE, the ".Visible := " following it has no // effect; even though the ".Visible := " following *that* does?!! ckSizeEntirePartitionDisk.Visible := False; ckSizeEntirePartitionDisk.Visible := True; ckSizeEntirePartitionDisk.Visible := (GetIsPartition() and not (ckPartitionHidden.Checked) and not (fmeSelectPartition.SyntheticDriveLayout)); lblPartitionDiskSize.Visible := ckSizeEntirePartitionDisk.Visible; // If the control's not visible, don't let it be selected; the user enters // the size if not (ckSizeEntirePartitionDisk.Visible) then ckSizeEntirePartitionDisk.Checked := False; SDUEnableControl(se64UnitSize, not (ckSizeEntirePartitionDisk.Checked)); // Prevent user from disabling the automount when creating volumes using the // DLL version // Toggle the "automount after create" checkbox visible on/off. // For some reason, the Visible setting doesn't "take" if set to FALSE // in FormShow(...) (i.e. the control is still visible) ckAutoMountAfterCreate.Visible := True; ckAutoMountAfterCreate.Visible := False; ckAutoMountAfterCreate.Visible := not (GetFreeOTFEBase() is TOTFEFreeOTFEDLL); SDUEnableControl(gbKeyfile, rbCDBInKeyfile.Checked); { TODO 1 -otdk -crefactor : disable chaff if hidden - not used } end; procedure TfrmWizardCreateVolume.pbBrowseFilenameClick(Sender: TObject); begin SaveDialog.Filter := FILE_FILTER_FLT_VOLUMES; SaveDialog.DefaultExt := FILE_FILTER_DFLT_VOLUMES; SaveDialog.Options := SaveDialog.Options + [ofDontAddToRecent]; SDUOpenSaveDialogSetup(SaveDialog, GetVolFilename); if SaveDialog.Execute then begin SetVolFilename(SaveDialog.Filename); se64UnitByteOffset.Value := 0; if (FileExists(GetVolFilename)) then begin // Force the user to reenter their offset, by marking the offset tabsheet // as incomplete tsOffset.Tag := 0; end else begin // New file; critical data automatically stored at the start of the file; // zero offset tsOffset.Tag := 1; end; end; UpdateUIAfterChangeOnCurrentTab(); end; // This procedure will check to see if all items on the current tabsheet have // been successfully completed function TfrmWizardCreateVolume.IsTabComplete(checkTab: TTabSheet): Boolean; var randomBitsGenerated: Integer; testSize: Int64; volSizeWithCDB: ULONGLONG; volSizeWithCDBAndPadding: ULONGLONG; aSelectedCypherBlockSize: Integer; int64Zero: Int64; begin inherited; //if not req'd assume complete Result := not IsTabRequired(checkTab); if (checkTab = tsFileOrPartition) then begin // Ensure one option has been selected Result := (rgFileOrPartition.ItemIndex >= 0); end else if (checkTab = tsFilename) then begin // If we're creating a volume within a volume file, a filename must be specified if GetIsPartition() then Result := True else // Flag tabsheet complete if a filename has been specified Result := (GetVolFilename <> ''); end else if (checkTab = tsPartitionWarning) then begin // Warning only; nothing for the user to actually do on this tab Result := True; end else if (checkTab = tsPartitionSelect) then begin // If we're creating a volume on a partition, one must be selected if not GetIsPartition() then begin Result := True; end else begin Result := (fmeSelectPartition.SelectedDevice <> ''); end; end else if (checkTab = tsOffset) then begin // Check that the number entered is less than the max size... if GetIsPartition() then begin Result := (GetOffset() >= 0); end else begin Result := (GetOffset() < SDUGetFileSize(GetVolFilename())) and (GetOffset() >= 0); end; end else if (checkTab = tsSize) then begin // Some sensible minimum volume size // Use explicit int64 to prevent Delphi converting Size to int testSize := BYTES_IN_MEGABYTE; Result := (GetSize() >= testSize); if Result then begin // Min sector size testSize := ASSUMED_HOST_SECTOR_SIZE; Result := ((GetSize() mod testSize) = 0); end; if Result then begin volSizeWithCDB := GetSize(); if GetCDBInVolFile() then begin volSizeWithCDB := volSizeWithCDB + ULONGLONG(CRITICAL_DATA_LENGTH div 8); end; volSizeWithCDBAndPadding := volSizeWithCDB + GetPaddingLength(); if GetIsPartition() then begin if fmeSelectPartition.SyntheticDriveLayout then begin // We don't know the size of the selected drive/partition; assume user // input OK Result := True; end else begin // Note: fmeSelectPartition.SelectedSize() already takes into account // whether or not the "entire disk" option was selected on the // frame Result := ((fmeSelectPartition.SelectedSize() - GetOffset()) >= volSizeWithCDBAndPadding); end; end else if (FileExists(GetVolFilename)) then begin // If creating a hidden container, ensure that the existing file is large // enough to store the hidden container Result := ((SDUGetFileSize(GetVolFilename) - GetOffset()) >= volSizeWithCDBAndPadding); end else begin // It would be *nice* to check that the volume the filename is stored on // has enough storage for the requested size volume, but that is not // a priority to implement right now... // Always completed (seSize always returns a minimum of "1", and the // units must always be set to something) Result := True; end; end; end else if (checkTab = tsHashCypherIV) then begin Result := ((cbHash.ItemIndex > -1) and (cbCypher.ItemIndex > -1)); end else if (checkTab = tsMasterKeyLength) then begin // If the user's selected cypher has a keysize >= 0, skip the tsMasterKeyLength tabsheet if (SelectedCypherKeySize() >= 0) then begin Result := True; end else begin // Otherwise, the keysize must be a multiple of 8 bits Result := ((seMasterKeyLength.Value mod 8) = 0); end; end else if (checkTab = tsRNGSelect) then begin // Must have at least one RNG selected Result := (GetRNGSet() <> []); end else if (checkTab = tsRNGMouseMovement) then begin if not (rngMouseMovement in GetRNGSet) then begin // Mouse RNG not used - automatically completed Result := True; end else begin // This is a good place to update the display of the number of random bits // generated... randomBitsGenerated := CountMouseRNGData(); lblMouseRNGBits.Caption := Format(_('Random bits generated: %d/%d'), [randomBitsGenerated, RNG_requiredBits()]); Result := (randomBitsGenerated >= RNG_requiredBits()); MouseRNG.Enabled := not (Result); if MouseRNG.Enabled then MouseRNG.Color := clWindow else MouseRNG.Color := clBtnFace; end; end else if (checkTab = tsRNGPKCS11) then begin // Must have at least one RNG selected Result := (FPKCS11TokensAvailable and (cbToken.ItemIndex >= 0)); end else if (checkTab = tsRNGGPG) then begin // Flag tabsheet complete if a GPG executable has been specified Result := (lblGPGFilename.Caption <> ''); end else if (checkTab = tsPassword) then begin // Ensure the password is confirmed, and something has been entered as a // password Result := frmeNewPassword.IsPasswordValid; //enable 'finished' text iff done lblFinished.Visible := Result; end else if (checkTab = tsSummary) then begin // Always completed Result := True; end; if (checkTab = tsKeyIterations) then begin // Ensure number of key iterations is > 0 if (seKeyIterations.Value <= 0) then begin SDUMessageDlg(_('The number of key iterations must be 1 or more'), mtError); // pcAdvancedOpts.ActivePage := tsKeyIterations; ActiveControl := seKeyIterations; Result := False; end; end; if (checkTab = tsSalt) and Result then begin // Ensure salt length is a multiple of 8 bits if ((seSaltLength.Value mod 8) <> 0) then begin SDUMessageDlg(_('The salt length must be a multiple of 8'), mtError); // pcAdvancedOpts.ActivePage := tsSalt; ActiveControl := seSaltLength; Result := False; end; // Ensure salt length is a multiple of the cypher's blocksize aSelectedCypherBlockSize := SelectedCypherBlockSize(); if ((aSelectedCypherBlockSize > 0) and ((seSaltLength.Value mod aSelectedCypherBlockSize) <> 0)) then begin SDUMessageDlg(Format(_( 'The salt length must be a multiple of the cypher''s blocksize (%d)'), [aSelectedCypherBlockSize]), mtError); // pcAdvancedOpts.ActivePage := tsSalt; ActiveControl := seSaltLength; Result := False; end; end; if (checkTab = tsCDBLocation) and Result then begin // Either the user's selected to include the CDB in their volume file, or // they've specified a keyfilename Result := rbCDBInVolFile.Checked or (rbCDBInKeyfile.Checked and (GetCDBFilename() <> '')); if not Result then begin SDUMessageDlg(_( 'If you wish to store the container''s CDB in a keyfile, you must specify the file to use'), mtError); ActiveControl := tsCDBLocation; Result := False; end; end; if (checkTab = tsPadding) and Result then begin // Padding can't be less than zero int64Zero := 0; Result := (se64Padding.Value >= int64Zero); if not Result then begin SDUMessageDlg(_('The amount of padding data added to a container must be zero or greater'), mtError); ActiveControl := tsPadding; Result := False; end; end; if (checkTab = tsChaff) and Result then begin // If overwriting with encrypted data (chaff), find the size of the key required , and ensure can get that random data ftempCypherUseKeyLength := 0; if GetOverwriteWithChaff() then begin Update_tempCypherUseKeyLength; // If MouseRNG is being used, check that enough random data is availabe... if not (IsTabComplete(tsRNGMouseMovement)) then begin SDUMessageDlg( _( 'Additional random data is required in order to generate an encryption key for use when producing the padding data.'), mtInformation ); ActiveControl := tsRNGMouseMovement; Result := False; end; end; end; end; procedure TfrmWizardCreateVolume.ckRNGClick(Sender: TObject); begin InitMouseRNGData(); // Set unused tabsheets as complete // ...RNG mouse movement tsRNGMouseMovement.Tag := 1; if ckRNGMouseMovement.Checked then begin tsRNGMouseMovement.Tag := 0; end; // ...RNG GPG tsRNGGPG.Tag := 1; if ckRNGGPG.Checked then begin if (lblGPGFilename.Caption = '') then begin tsRNGGPG.Tag := 0; end; end; // ...RNG PKCS#11 token tsRNGPKCS11.Tag := 1; if ckRNGPKCS11.Checked then begin if not (FPKCS11TokensAvailable and (cbToken.ItemIndex >= 0)) then begin tsRNGPKCS11.Tag := 0; end; end; UpdateUIAfterChangeOnCurrentTab(); end; procedure TfrmWizardCreateVolume.ckSizeEntirePartitionDiskClick(Sender: TObject); begin UpdateUIAfterChangeOnCurrentTab(); end; procedure TfrmWizardCreateVolume.fmePasswordChange(Sender: TObject); begin UpdateUIAfterChangeOnCurrentTab(); end; function TfrmWizardCreateVolume.GetIsPartition(): Boolean; begin Result := (rgFileOrPartition.ItemIndex = rgFileOrPartition.Items.IndexOf( FILEORPART_OPT_PARTITION)); end; function TfrmWizardCreateVolume.GetIsHidden(): Boolean; begin // If: // a) The user wants to create the volume on a partition, and has // specified they want to create a hidden partition, or // b) The user wants to create the volume within a volume file, but has // specified the filename of an existing file Result := ((GetIsPartition()) and (ckPartitionHidden.Checked)) or ((not (GetIsPartition())) and (FileExists(GetVolFilename))); end; function TfrmWizardCreateVolume.GetVolFilename(): String; begin Result := ''; if GetIsPartition() then begin Result := fmeSelectPartition.SelectedDevice; end else begin Result := lblFilename.Text; end; end; procedure TfrmWizardCreateVolume.SetVolFilename(filename: String); begin lblFilename.Text := filename; end; function TfrmWizardCreateVolume.GetOffset(): ULONGLONG; begin Result := se64UnitByteOffset.Value; end; // Note: The size returned *excludes* the size of the critical data function TfrmWizardCreateVolume.GetSize(): ULONGLONG; var tmpSize: ULONGLONG; critSizeULL: ULONGLONG; begin if ckSizeEntirePartitionDisk.Checked then begin tmpSize := fmeSelectPartition.SelectedSize(); // If CDB forms part of the volume, reduce as appropriate if GetCDBInVolFile() then begin critSizeULL := (CRITICAL_DATA_LENGTH div 8); tmpSize := tmpSize - critSizeULL; end; end else begin // Calculate the number of bytes... // Note: The in64(...) cast is REQUIRED, otherwise Delphi will calculate the // value in 32 bits, and assign it to the 64 bit VolumeSize tmpSize := ULONGLONG(se64UnitSize.Value); end; Result := tmpSize; end; function TfrmWizardCreateVolume.GetHashDriver(): String; begin Result := ''; if (cbHash.ItemIndex >= 0) then begin Result := fHashKernelModeDriverNames[cbHash.ItemIndex]; end; end; function TfrmWizardCreateVolume.GetHashGUID(): TGUID; var strGUID: String; begin // Just some dummy GUID in case none selected strGUID := DUMMY_GUID; if (cbHash.ItemIndex >= 0) then begin strGUID := fHashGUIDs[cbHash.ItemIndex]; end; Result := StringToGUID(strGUID); end; function TfrmWizardCreateVolume.GetCypherDriver(): Ansistring; begin Result := ''; if (cbCypher.ItemIndex >= 0) then begin Result := fCypherKernelModeDriverNames[cbCypher.ItemIndex]; end; end; function TfrmWizardCreateVolume.GetCypherGUID(): TGUID; var strGUID: String; begin // Just some dummy GUID in case none selected strGUID := DUMMY_GUID; if (cbCypher.ItemIndex >= 0) then begin strGUID := fCypherGUIDs[cbCypher.ItemIndex]; end; Result := StringToGUID(strGUID); end; function TfrmWizardCreateVolume.GetSectorIVGenMethod(): TFreeOTFESectorIVGenMethod; begin Result := foivgUnknown; if (cbSectorIVGenMethod.ItemIndex >= 0) then begin Result := TFreeOTFESectorIVGenMethod( cbSectorIVGenMethod.Items.Objects[cbSectorIVGenMethod.ItemIndex]); end; end; procedure TfrmWizardCreateVolume.SetSectorIVGenMethod(sectorIVGenMethod: TFreeOTFESectorIVGenMethod); var i: Integer; idx: Integer; begin idx := -1; // Locate the appropriate idx for i := 0 to (cbSectorIVGenMethod.Items.Count - 1) do begin if (TFreeOTFESectorIVGenMethod(cbSectorIVGenMethod.Items.Objects[i]) = sectorIVGenMethod) then begin idx := i; break; end; end; cbSectorIVGenMethod.ItemIndex := idx; end; function TfrmWizardCreateVolume.GetUsePerVolumeIV(): Boolean; begin Result := ckUsePerVolumeIV.Checked; end; function TfrmWizardCreateVolume.GetRandomData_PaddingKey(): TSDUBytes; var len: Integer; begin // Use the last FPadWithEncryptedDataKeyLen bits as the CDB random data, // after the CDB random data // i := (CRITICAL_DATA_LENGTH div 8) + 1; len := (ftempCypherUseKeyLength div 8); { TODO 2 -otdk -crefactor : use randpool object that asserts if data isnt available - for now check not empty } GetRandPool().GetRandomData(len, Result); end; function TfrmWizardCreateVolume.GetMasterKeyLength(): Integer; begin Result := SelectedCypherKeySize(); if (Result < 0) then Result := seMasterKeyLength.Value; end; procedure TfrmWizardCreateVolume.edByteOffsetChange(Sender: TObject); begin UpdateUIAfterChangeOnCurrentTab(); end; procedure TfrmWizardCreateVolume.SizeChanged(Sender: TObject); begin UpdateUIAfterChangeOnCurrentTab(); end; procedure TfrmWizardCreateVolume.pbBrowseGPGClick(Sender: TObject); begin GPGOpenDialog.Filter := FILE_FILTER_FLT_EXECUTABLES; GPGOpenDialog.DefaultExt := FILE_FILTER_DFLT_EXECUTABLES; GPGOpenDialog.Options := GPGOpenDialog.Options + [ofDontAddToRecent]; SDUOpenSaveDialogSetup(GPGOpenDialog, lblGPGFilename.Caption); if GPGOpenDialog.Execute then begin lblGPGFilename.Caption := GPGOpenDialog.Filename; end; UpdateUIAfterChangeOnCurrentTab(); end; procedure TfrmWizardCreateVolume.MouseRNGByteGenerated(Sender: TObject; random: Byte); begin // Note: This is correct; if it's *less than* CRITICAL_DATA_LEN, then store it if (CountMouseRNGData() < RNG_requiredBits()) then begin AddToMouseRNGData(random); end; UpdateUIAfterChangeOnCurrentTab(); end; procedure TfrmWizardCreateVolume.PopulateHashes(); var tmpDisplayTitles: TStringList; i: Integer; hashDetails: TFreeOTFEHash; hashAcceptable: Boolean; begin tmpDisplayTitles := TStringList.Create(); try if (GetFreeOTFEBase().GetHashList(tmpDisplayTitles, fHashKernelModeDriverNames, fHashGUIDs)) then begin // Strip out all hashes which have: // length <= 0 or blocksize <= 0 // - they cannot be used to create new FreeOTFE volumes as they use // PBKDF2 (HMAC) to derive the critical data key; and PBKDF2 with HMAC // requires that the hash used has a defined length of greater than zero for i := (tmpDisplayTitles.Count - 1) downto 0 do begin if not (GetFreeOTFEBase().GetSpecificHashDetails(fHashKernelModeDriverNames[i], StringToGUID(fHashGUIDs[i]), hashDetails)) then begin // Just warn user, and ignore... SDUMessageDlg(Format(_('Unable to obtain hash details for %s'), [tmpDisplayTitles[i]]), mtWarning); hashAcceptable := False; end else begin hashAcceptable := (hashDetails.Length > 0) and (hashDetails.BlockSize > 0); end; // If the current hash algorithm is no use, don't add it to the list // offered to the user... if not (hashAcceptable) then begin tmpDisplayTitles.Delete(i); fHashKernelModeDriverNames.Delete(i); fHashGUIDs.Delete(i); end; end; // Populate the dropdown list offered to the user... cbHash.Items.Clear(); cbHash.Items.AddStrings(tmpDisplayTitles); if (cbHash.Items.Count = 0) then begin SDUMessageDlg( _( 'You do not appear to have any FreeOTFE hash drivers that can be used to create new LibreCrypt volumes installed and started.') + SDUCRLF + SDUCRLF + _( 'If you have only just installed LibreCrypt, you may need to restart your computer.'), mtError ); end; end else begin SDUMessageDlg( _('Unable to obtain list of hashes.') + SDUCRLF + SDUCRLF + _( 'Please ensure that you have one or more FreeOTFE hash drivers installed and started.') + SDUCRLF + SDUCRLF + _( 'If you have only just installed LibreCrypt, you may need to restart your computer.'), mtError ); end; finally tmpDisplayTitles.Free(); end; end; procedure TfrmWizardCreateVolume.PopulateCyphers(); var tmpDisplayTitles: TStringList; begin tmpDisplayTitles := TStringList.Create(); try if (GetFreeOTFEBase().GetCypherList(tmpDisplayTitles, fCypherKernelModeDriverNames, fCypherGUIDs)) then begin cbCypher.Items.Clear(); cbCypher.Items.AddStrings(tmpDisplayTitles); end else begin SDUMessageDlg( _('Unable to obtain list of cyphers.') + SDUCRLF + SDUCRLF + _('Please ensure that you have one or more FreeOTFE cypher drivers installed and started.') + SDUCRLF + SDUCRLF + _( 'If you have only just installed LibreCrypt, you may need to restart your computer.'), mtError ); end; finally tmpDisplayTitles.Free(); end; end; procedure TfrmWizardCreateVolume.PopulateSectorIVGenMethods(); var currMethod: TFreeOTFESectorIVGenMethod; begin cbSectorIVGenMethod.Items.Clear(); for currMethod := low(TFreeOTFESectorIVGenMethod) to high(TFreeOTFESectorIVGenMethod) do begin // Skip "Unknown" if (currMethod <> foivgUnknown) then begin cbSectorIVGenMethod.Items.AddObject(FreeOTFESectorIVGenMethodTitle[currMethod], Pointer(Ord(currMethod))); end; end; end; procedure TfrmWizardCreateVolume.FormWizardStepChanged(Sender: TObject); begin inherited; if (pcWizard.ActivePage = tsSummary) then begin PopulateSummary(); end else if (pcWizard.ActivePage = tsPartitionSelect) then begin // This shouldn't be needed, but without it, controls on this frame which // are set to "Visible := FALSE" by the frame remain visible. // Only call Initialize(...) the first time the tab is moved onto if (fmeSelectPartition.Tag = 1) then begin fmeSelectPartition.Initialize(); fmeSelectPartition.Tag := 0; end; end; if (pcWizard.ActivePage = tsPassword) then begin frmeNewPassword.SetFocus; frmeNewPassword.preUserKeyFirst.SetFocus; end; end; procedure TfrmWizardCreateVolume.FormCreate(Sender: TObject); var dl: ansichar; begin fHashKernelModeDriverNames := TStringList.Create(); fHashGUIDs := TStringList.Create(); fCypherKernelModeDriverNames := TStringList.Create(); fCypherGUIDs := TStringList.Create(); fIVGenMethodIDs := TStringList.Create(); fDeviceList := TStringList.Create(); fDeviceTitle := TStringList.Create(); fCachedCypherKeysize := CYPHER_KEYSIZE_NOT_CACHED_FLAG_KEYSIZE; fCachedCypherBlocksize := CYPHER_BLOCKSIZE_NOT_CACHED_FLAG_BLOCKSIZE; fCachedCypherMode := focmUnknown; // Start cryptlib, if possible, as early as we can to allow it as much time // as possible to poll entropy GetRandPool(); // fcanUseCryptlib := // tsKeyIterations // Need *some* upper value, otherwise setting MinValue won't work properly seKeyIterations.Increment := DEFAULT_KEY_ITERATIONS_INCREMENT; OnWizardStepChanged := FormWizardStepChanged; // tsRequestedDriveLetter cbDriveLetter.Items.Clear(); cbDriveLetter.Items.Add(_('Use default')); // for dl:='C' to 'Z' do for dl := 'A' to 'Z' do cbDriveLetter.Items.Add(dl + ':'); // Autoselect the "default" (first) entry cbDriveLetter.ItemIndex := 0; // tsCDBLocation rbCDBInKeyfile.Checked := False; rbCDBInVolFile.Checked := True; lblKeyFilename.Caption := ''; frmeNewPassword.OnChange := fmePasswordChange; end; procedure TfrmWizardCreateVolume.FormDestroy(Sender: TObject); begin fHashKernelModeDriverNames.Free(); fHashGUIDs.Free(); fCypherKernelModeDriverNames.Free(); fCypherGUIDs.Free(); fIVGenMethodIDs.Free(); fDeviceList.Free(); fDeviceTitle.Free(); PurgeMouseRNGData(); //overwrite any seed asap { for i := 1 to length(fCombinedRandomData) do begin fCombinedRandomData[i] := ansichar(i); end; } end; procedure TfrmWizardCreateVolume.rbCDBLocationClick2(Sender: TObject); begin EnableDisableControls(); end; procedure TfrmWizardCreateVolume.cbDriveLetterChange(Sender: TObject); begin inherited; UpdateUIAfterChangeOnCurrentTab(); end; procedure TfrmWizardCreateVolume.cbHashCypherIVGenChange(Sender: TObject); begin // Cypher changed; clear any cached keysize fCachedCypherKeysize := CYPHER_KEYSIZE_NOT_CACHED_FLAG_KEYSIZE; // Cypher changed; clear any cached blocksize fCachedCypherBlocksize := CYPHER_BLOCKSIZE_NOT_CACHED_FLAG_BLOCKSIZE; // Cypher changed; clear any cached mode fCachedCypherMode := focmUnknown; UpdateUIAfterChangeOnCurrentTab(); end; procedure TfrmWizardCreateVolume.PopulateSummary(); var totalSize: ULONGLONG; driveLetter: String; RNGs: String; ULLZero: ULONGLONG; PaddingLength: Int64; VolFilename: TFilename; volSize: ULONGLONG; begin // int64Zero to prevent 32/64 bit integer conversion ULLZero := 0; PaddingLength := GetPaddingLength(); VolFilename := GetVolFilename(); reSummary.Lines.Clear(); volSize := GetSize(); if GetIsPartition() then reSummary.Lines.Add(Format(_('Partition: %s'), [VolFilename])) else reSummary.Lines.Add(Format(_('Filename: %s'), [VolFilename])); if GetIsHidden() then reSummary.Lines.Add(Format(_('Hidden container starting at offset: %d'), [GetOffset()])); if GetCDBInVolFile() then begin if (PaddingLength > ULLZero) then begin totalSize := volSize + ULONGLONG(CRITICAL_DATA_LENGTH div 8) + PaddingLength; reSummary.Lines.Add(Format( _('Container size: %d + %d (for CDB) + %d (padding) = %d bytes'), [volSize, (CRITICAL_DATA_LENGTH div 8), PaddingLength, totalSize])); end else begin totalSize := volSize + ULONGLONG(CRITICAL_DATA_LENGTH div 8); reSummary.Lines.Add(Format( _('Container size: %d + %d (for CDB) = %d bytes'), [volSize, (CRITICAL_DATA_LENGTH div 8), totalSize])); end; reSummary.Lines.Add(_('CDB stored: At start of container file')); end else begin if (PaddingLength > ULLZero) then begin totalSize := volSize + PaddingLength; reSummary.Lines.Add(Format( _('Container size: %d + %d (padding) = %d bytes'), [volSize, PaddingLength, totalSize])); end else begin reSummary.Lines.Add(Format(_('Container size: %d bytes'), [volSize])); end; reSummary.Lines.Add(_('CDB stored: In separate keyfile')); reSummary.Lines.Add(Format(_('CDB keyfile: %s'), [GetCDBFilename()])); end; reSummary.Lines.Add(Format(_('Hash algorithm: %s'), [cbHash.Items[cbHash.ItemIndex]])); reSummary.Lines.Add(' ' + Format(_('[Hash driver: %s]'), [GetHashDriver()])); reSummary.Lines.Add(' ' + Format(_('[Hash GUID: %s]'), [GUIDToString(GetHashGUID())])); reSummary.Lines.Add(Format(_('Key iterations: %d'), [seKeyIterations.Value])); if (SelectedCypherBlockSize() <= 0) then begin reSummary.Lines.Add(_('Sector IVs will not be used (cypher has zero or variable blocksize)')); end else begin reSummary.Lines.Add(_('Cypher has fixed, defined blocksize; sector IVs will be used')); reSummary.Lines.Add(Format(_('Sector IV generation method: %s'), [FreeOTFESectorIVGenMethodTitle[GetSectorIVGenMethod()]])); if GetUsePerVolumeIV() then reSummary.Lines.Add(_('Sector IVs will be XORd with a per-container IV before use')) else reSummary.Lines.Add(_('A per-container IV will not be used')); end; reSummary.Lines.Add(Format(_('Cypher algorithm: %s'), [cbCypher.Items[cbCypher.ItemIndex]])); reSummary.Lines.Add(' ' + Format(_('[Cypher driver: %s]'), [GetCypherDriver()])); reSummary.Lines.Add(' ' + Format(_('[Cypher GUID: %s]'), [GUIDToString(GetCypherGUID())])); reSummary.Lines.Add(Format(_('Master key length: %d bits'), [GetMasterKeyLength()])); RNGs := ''; if ckRNGCryptoAPI.Checked then begin if (RNGs = '') then begin RNGS := RNGs + ckRNGCryptoAPI.Caption; end else begin RNGS := RNGs + ', ' + ckRNGCryptoAPI.Caption; end; end; if ckRNGMouseMovement.Checked then begin if (RNGs = '') then begin RNGS := RNGs + ckRNGMouseMovement.Caption; end else begin RNGS := RNGs + ', ' + ckRNGMouseMovement.Caption; end; end; if ckRNGcryptlib.Checked then begin if (RNGs = '') then begin RNGS := RNGs + ckRNGcryptlib.Caption; end else begin RNGS := RNGs + ', ' + ckRNGcryptlib.Caption; end; end; if ckRNGGPG.Checked then begin if (RNGs = '') then begin RNGS := RNGs + ckRNGGPG.Caption; end else begin RNGS := RNGs + ', ' + ckRNGGPG.Caption; end; end; reSummary.Lines.Add(Format(_('RNG: %s'), [RNGs])); reSummary.Lines.Add(_('Password: <entered>')); reSummary.Lines.Add(Format(_('Salt length: %d bits'), [seSaltLength.Value])); driveLetter := GetDriveLetter(); if (driveLetter = #0) then begin driveLetter := _('Use default'); end else begin driveLetter := driveLetter + ':'; end; reSummary.Lines.Add(Format(_('Requested drive letter: %s'), [driveLetter])); end; function TfrmWizardCreateVolume.GetRNGSet(): TRNGSet; begin Result := []; if ckRNGCryptoAPI.Checked then Result := Result + [rngCryptoAPI]; if ckRNGMouseMovement.Checked then Result := Result + [rngMouseMovement]; if ckRNGcryptlib.Checked then Result := Result + [rngcryptlib]; if ckRNGPKCS11.Checked then Result := Result + [rngPKCS11]; if ckRNGGPG.Checked then Result := Result + [rngGPG]; end; procedure TfrmWizardCreateVolume.pbFinishClick(Sender: TObject); begin inherited; if GetIsPartition() then begin if (SDUMessageDlg(_('You are about to create a new container on a disk/partition.' + SDUCRLF + SDUCRLF + 'This process will OVERWRITE that disk/partition.' + SDUCRLF + SDUCRLF + 'Are you SURE you wish to continue?'), mtWarning, [mbYes, mbNo], 0) = mrNo) then begin // Bail out... exit; end; end; //ensure chaff data is included Update_tempCypherUseKeyLength; GetRandPool.SetUpRandPool(GetRNGSet(), PKCS11TokenListSelected(cbToken), lblGPGFilename.Caption); // Result := GetRandPool.GetRandomData( (RNG_requiredBits() div 8), fCombinedRandomData); // *All* information required to create the new volume acquired - so create // the new volume try if CreateNewVolume() then begin PostCreate(); ModalResult := mrOk; end; except on E: EInsufficientRandom do SDUMessageDlg( _('Insufficient random data generated: ' + E.message) + SDUCRLF + SDUCRLF + PLEASE_REPORT_TO_FREEOTFE_DOC_ADDR, mtError ); end; // end; end; function TfrmWizardCreateVolume.CreateNewVolume(): Boolean; var volumeDetails: TVolumeDetailsBlock; CDBMetaData: TCDBMetaData; saltBytes: TSDUBytes; // randomPool: Ansistring; volumeFileSize: ULONGLONG; cdbFile: String; cdbOffset: ULONGLONG; userCancel: Boolean; junkBool: Boolean; fileCreateProbMsg: String; VolFilename: TFilename; // randBytes:TSDUBytes; saltStr: Ansistring; begin Result := True; VolFilename := GetVolFilename(); // Create the volume file, if not a partition // If the new volume is on a partition; we can skip creating a large file // on the localfilesystem if not GetIsPartition() then begin // Create the volume file (if it doesn't already exist) if (not (FileExists(VolFilename))) then begin volumeFileSize := GetSize(); // Add on the size of the CDB, if stored in volume file if GetCDBInVolFile() then begin volumeFileSize := volumeFileSize + ULONGLONG(CRITICAL_DATA_LENGTH div 8); end; // Add on the size of any padding volumeFileSize := volumeFileSize + GetPaddingLength(); Result := SDUCreateLargeFile(VolFilename, volumeFileSize, True, userCancel); if not Result then // If there was a problem, and not a user cancel, warn user if userCancel then begin SDUMessageDlg(_('Container creation canceled'), mtInformation); end else begin fileCreateProbMsg := Format(_( 'Unable to create Container; please ensure you have %s free on the relevant drive'), [SDUFormatAsBytesUnits(volumeFileSize)]); if (volumeFileSize >= MAX_FAT_FILESIZE) then begin fileCreateProbMsg := fileCreateProbMsg + SDUCRLF + SDUCRLF + _( 'Please note that FAT/FAT32 filesystems cannot store files that are 4GB or larger'); end; SDUMessageDlg(fileCreateProbMsg, mtError); end; end; // if (not(FileExists(filename))) then end; // if not(IsPartition) then if Result then begin // Overwrite volume with SPRNG data, if required // this also overwrites cdb and padding, cdb is created below { if hidden also overwrite from Offset? - this is arguably overkill bc should already have been overwritten, but perhaps if didnt do on outer vol then will stop attacker knowing size of data also less info leaked if attacker has b4/after snapshots for now not overwriting for performance } { TODO 1 -otdk -cenhance : instead default FOverwriteWithChaff to false for hidden vols so user can still change} if GetOffset() = 0 then Result := OverwriteVolWithChaff(); end; // Create separate CDB file, if needed if Result then begin if not GetCDBInVolFile() then begin Result := SDUCreateLargeFile(GetCDBFilename(), (CRITICAL_DATA_LENGTH div 8), False, junkBool); if not Result then begin SDUMessageDlg(_('Unable to create separate CDB keyfile.'), mtError); end; end; end; if Result then begin {$IFDEF FREEOTFE_DEBUG} GetFreeOTFEBase().DebugMsg('Populating critical data structure...'); {$ENDIF} // Create the volume file header // Note: No need to populate CDBMetaData.MACAlgorithm or // CDBMetaData.KDFAlgorithm as the function which writes the CDB out // populates them automatically CDBMetaData.MACAlgorithm := fomacUnknown; CDBMetaData.KDFAlgorithm := fokdfUnknown; CDBMetaData.HashDriver := GetHashDriver(); CDBMetaData.HashGUID := GetHashGUID(); CDBMetaData.CypherDriver := GetCypherDriver(); CDBMetaData.CypherGUID := GetCypherGUID(); {$IFDEF FREEOTFE_DEBUG} GetFreeOTFEBase().DebugMsg('Using hash driver: '+CDBMetaData.HashDriver); GetFreeOTFEBase().DebugMsg('Using hash: '+GUIDToString(CDBMetaData.HashGUID)); GetFreeOTFEBase().DebugMsg('Using cypher driver: '+CDBMetaData.CypherDriver); GetFreeOTFEBase().DebugMsg('Using cypher: '+GUIDToString(CDBMetaData.CypherGUID)); {$ENDIF} volumeDetails.CDBFormatID := CDB_FORMAT_ID; volumeDetails.PartitionLen := GetSize(); volumeDetails.VolumeFlags := 0; {$IFDEF FREEOTFE_DEBUG} GetFreeOTFEBase().DebugMsg('Container flags: '+inttostr(volumeDetails.VolumeFlags)+' bits'); {$ENDIF} volumeDetails.SectorIVGenMethod := GetSectorIVGenMethod(); { TODO 2 -otdk -csecurity : this copies data - but orig data not deleted so may be reused } // randomPool := GetRandomData_CDB(); volumeDetails.MasterKeyLength := GetMasterKeyLength(); // Grab 'n' bytes from the random pool to use as the master key GetRandPool().GetRandomData(volumeDetails.MasterKeyLength div 8, volumeDetails.MasterKey); //volumeDetails.MasterKey := SDUBytesToString( randBytes); assert(length(volumeDetails.MasterKey) = volumeDetails.MasterKeyLength div 8); // volumeDetails.MasterKey := Copy(randomPool, 1, (volumeDetails.MasterKeyLength div 8)); // SDUDeleteFromStart(randomPool, volumeDetails.MasterKeyLength div 8); // Delete(randomPool, 1, (volumeDetails.MasterKeyLength div 8)); {$IFDEF FREEOTFE_DEBUG} GetFreeOTFEBase().DebugMsg('Master key length: '+inttostr(volumeDetails.MasterKeyLength)+' bits'); GetFreeOTFEBase().DebugMsg('Master key follows:'); GetFreeOTFEBase().DebugMsg(volumeDetails.MasterKey); {$ENDIF} // Grab 'n' bytes from the random pool to use as the volume IV // *Only* if the cypher's blocksize is a fixed, +ve number of bits volumeDetails.VolumeIVLength := 0; if (SelectedCypherBlockSize() > 0) then if GetUsePerVolumeIV() then volumeDetails.VolumeIVLength := SelectedCypherBlockSize(); GetRandPool().GetRandomData(volumeDetails.VolumeIVLength div 8, volumeDetails.VolumeIV); // volumeDetails.VolumeIV := SDUBytesToString( randBytes); assert(length(volumeDetails.VolumeIV) = volumeDetails.VolumeIVLength div 8); // volumeDetails.VolumeIV := Copy(randomPool, 1, (volumeDetails.VolumeIVLength div 8)); // SDUDeleteFromStart(randomPool,volumeDetails.VolumeIVLength div 8 ); // Delete(randomPool, 1, (volumeDetails.VolumeIVLength div 8)); {$IFDEF FREEOTFE_DEBUG} GetFreeOTFEBase().DebugMsg('Volume IV length: '+inttostr(volumeDetails.VolumeIVLength)+' bits'); GetFreeOTFEBase().DebugMsg('Volume IV follows:'); GetFreeOTFEBase().DebugMsg(volumeDetails.VolumeIV); {$ENDIF} volumeDetails.RequestedDriveLetter := GetDriveLetter(); // Grab 'n' bytes from the random pool to use as the salt GetRandPool().GetRandomData(seSaltLength.Value div 8, saltBytes); saltStr := SDUBytesToString(saltBytes); assert(length(saltStr) = seSaltLength.Value div 8); // saltBytes := Copy(randomPool, 1, (seSaltLength.Value div 8)); // SDUDeleteFromStart(randomPool, (seSaltLength.Value div 8)); { DONE 1 -otdk -crefactor : have randpool object } // Delete(randomPool, 1, (seSaltLength.Value div 8)); {$IFDEF FREEOTFE_DEBUG} GetFreeOTFEBase().DebugMsg('About to write the critical data...'); GetFreeOTFEBase().DebugMsg(frmeNewPassword.GetKeyPhrase()); GetFreeOTFEBase().DebugMsg('Using salt... '); GetFreeOTFEBase().DebugMsg('-- begin salt --'); GetFreeOTFEBase().DebugMsg(saltBytes); GetFreeOTFEBase().DebugMsg('-- end salt --'); {$ENDIF} // Determine filename and offset within file storing CDB GetCDBFileAndOffset(cdbFile, cdbOffset); // Write the header to the file, starting from the specified offset if not (GetFreeOTFEBase().WriteVolumeCriticalData(cdbFile, cdbOffset, frmeNewPassword.GetKeyPhrase(), saltBytes, seKeyIterations.Value, volumeDetails, CDBMetaData)) then begin SDUMessageDlg( _('Unable to write critical data block.'), mtError ); Result := False; end; // if not(OTFEFreeOTFE.WriteVolumeCriticalData( end; // if result then //wipe sesitive data allocated SDUZeroBuffer(volumeDetails.MasterKey); SDUZeroBuffer(volumeDetails.VolumeIV); SDUZeroBuffer(saltBytes); end; procedure TfrmWizardCreateVolume.GetCDBFileAndOffset(out cdbFile: String; out cdbOffset: ULONGLONG); begin cdbFile := GetVolFilename(); cdbOffset := GetOffset(); if not GetCDBInVolFile() then begin // CDB stored in separate keyfile cdbFile := GetCDBFilename(); cdbOffset := 0; {$IFDEF FREEOTFE_DEBUG} GetFreeOTFEBase().DebugMsg('CDB stored in separate keyfile: '+cdbFile); {$ENDIF} end; end; // Post-creation functionality procedure TfrmWizardCreateVolume.PostCreate(); var MountedDrives: String; errMsg: WideString; cntMountOK: Integer; cntMountFailed: Integer; mountedOK: Boolean; tmpVolumeFiles: TStringList; cdbFile: String; cdbOffset: ULONGLONG; VolFilename: tfilename; begin if GetAutoMountAfterCreate() then begin VolFilename := GetVolFilename(); tmpVolumeFiles := TStringList.Create(); try mountedOK := False; tmpVolumeFiles.Add(VolFilename); GetCDBFileAndOffset(cdbFile, cdbOffset); if (VolFilename = cdbFile) then begin cdbFile := ''; end; MountedDrives := ''; if GetFreeOTFEBase().MountFreeOTFE(tmpVolumeFiles, frmeNewPassword.GetKeyPhrase(), cdbFile, '', // Empty string - read the CDB PKCS11_NO_SLOT_ID, nil, // PKCS#11 session not used nil, // PKCS#11 secret key not used seKeyIterations.Value, GetDriveLetter(), False, // Readonly DEFAULT_MOUNTAS, GetOffset(), GetCDBInVolFile(), seSaltLength.Value, True, // Mount for all users MountedDrives) then begin GetFreeOTFEBase().CountMountedResults( MountedDrives, cntMountOK, cntMountFailed ); if (cntMountOK = 1) then begin fnewVolumeMountedAs := MountedDrives[1]; mountedOK := True; end; end; finally tmpVolumeFiles.Free(); end; if mountedOK then begin { TODO 2 -otdk -cinvestigate : why only DLL - should always format after creation, even if use windows dlg } if (GetFreeOTFEBase() is TOTFEFreeOTFEDLL) then begin PostMount_Format_using_dll(); end else begin Format_Drive(FNewVolumeMountedAs, self); end; end; if not (mountedOK) then begin // Volumes couldn't be mounted for some reason... errMsg := _('Unable to open container.'); end; end; end; // Format the volume specified procedure TfrmWizardCreateVolume.PostMount_Format_using_dll(); var PartitionImage: TPartitionImageDLL; Filesystem: TSDFilesystem_FAT; begin if (GetFreeOTFEBase() is TOTFEFreeOTFEDLL) then begin PartitionImage := TPartitionImageDLL.Create(); PartitionImage.FreeOTFEObj := TOTFEFreeOTFEDLL(GetFreeOTFEBase()); PartitionImage.MountedAs := fnewVolumeMountedAs; // end else begin // // TODO test this - could reformat wrong drive! -for now use format_drive for non dll volumes // // PartitionImage := TSDPartitionImage_File.Create(); //// PartitionImage.GetFreeOTFEBase() := fFreeOTFEObj; // (PartitionImage as TSDPartitionImage_File).Filename := VolFilename; // // end; PartitionImage.Mounted := True; if not (PartitionImage.Mounted) then begin PartitionImage.Free(); PartitionImage := nil; SDUMessageDlg('Container could be opened, but not mounted as a partition image?!', mtError); end; if (PartitionImage <> nil) then begin Filesystem := TSDFilesystem_FAT.Create(); Filesystem.PartitionImage := PartitionImage; Filesystem.Format(); PartitionImage.Mounted := False; end; end; end; procedure TfrmWizardCreateVolume.seMasterKeyLengthChange(Sender: TObject); begin UpdateUIAfterChangeOnCurrentTab(); end; procedure TfrmWizardCreateVolume.seMasterKeyLengthExit(Sender: TObject); begin // Ensure master key length is a multiple of 8 bits if ((seMasterKeyLength.Value mod 8) <> 0) then begin SDUMessageDlg(_('The master key length must be a multiple of 8'), mtWarning); ActiveControl := seMasterKeyLength; end; UpdateUIAfterChangeOnCurrentTab(); end; // Returns the keysize for the user's selected cyppher, as returned by the // driver // Returns CYPHER_KEYSIZE_NOT_CACHED_FLAG_KEYSIZE on error function TfrmWizardCreateVolume.SelectedCypherKeySize(): Integer; var cypherDetails: TFreeOTFECypher_v3; begin Result := CYPHER_KEYSIZE_NOT_CACHED_FLAG_KEYSIZE; // Determine the keysize of the cypher selected // If we have it cached alredy, use it if (fCachedCypherKeysize <> CYPHER_KEYSIZE_NOT_CACHED_FLAG_KEYSIZE) then begin Result := fCachedCypherKeysize; end else if not (GetFreeOTFEBase().GetSpecificCypherDetails(GetCypherDriver(), GetCypherGUID(), cypherDetails)) then begin SDUMessageDlg(_('Unable to determine the keysize for your selected cypher.'), mtError); end else begin // Cache keysize and return... fCachedCypherKeysize := cypherDetails.KeySizeRequired; Result := fCachedCypherKeysize; end; end; // Returns the blocksize for the user's selected cyppher, as returned by the // driver // Returns CYPHER_BLOCKSIZE_NOT_CACHED_FLAG_BLOCKSIZE on error function TfrmWizardCreateVolume.SelectedCypherBlockSize(): Integer; var cypherDetails: TFreeOTFECypher_v3; begin Result := CYPHER_BLOCKSIZE_NOT_CACHED_FLAG_BLOCKSIZE; // Determine the blocksize of the cypher selected // If we have it cached alredy, use it if (fCachedCypherBlocksize <> CYPHER_BLOCKSIZE_NOT_CACHED_FLAG_BLOCKSIZE) then begin Result := fCachedCypherBlocksize; end else if not (GetFreeOTFEBase().GetSpecificCypherDetails(GetCypherDriver(), GetCypherGUID(), cypherDetails)) then begin SDUMessageDlg(_('Unable to determine the blocksize for your selected cypher.'), mtError); end else begin // Cache blocksize and return... fCachedCypherBlocksize := cypherDetails.BlockSize; Result := fCachedCypherBlocksize; end; end; // Returns the cypher mode for the user's selected cypher, as returned by // the driver function TfrmWizardCreateVolume.SelectedCypherMode(): TFreeOTFECypherMode; var cypherDetails: TFreeOTFECypher_v3; begin Result := focmUnknown; // If we have it cached alredy, use it if (fCachedCypherMode <> focmUnknown) then begin Result := fCachedCypherMode; end else if not (GetFreeOTFEBase().GetSpecificCypherDetails(GetCypherDriver(), GetCypherGUID(), cypherDetails)) then begin SDUMessageDlg(_('Unable to determine the cypher mode for your selected cypher.'), mtError); end else begin // Cache blocksize and return... fCachedCypherMode := cypherDetails.Mode; Result := fCachedCypherMode; end; end; procedure TfrmWizardCreateVolume.pbHashInfoClick(Sender: TObject); var deviceName: String; GUID: TGUID; begin deviceName := GetHashDriver(); GUID := GetHashGUID(); GetFreeOTFEBase().ShowHashDetailsDlg(deviceName, GUID); end; procedure TfrmWizardCreateVolume.pbCypherInfoClick(Sender: TObject); var deviceName: String; GUID: TGUID; begin deviceName := GetCypherDriver(); GUID := GetCypherGUID(); GetFreeOTFEBase().ShowCypherDetailsDlg(deviceName, GUID); end; procedure TfrmWizardCreateVolume.rbCDBLocationClick(Sender: TObject); begin UpdateUIAfterChangeOnCurrentTab(); end; procedure TfrmWizardCreateVolume.ckPartitionHiddenClick(Sender: TObject); begin se64UnitByteOffset.Value := 0; if (ckPartitionHidden.Checked) then begin // Force the user to reenter their offset, by marking the offset tabsheet // as incomplete tsOffset.Tag := 0; end else begin // New file; critical data automatically stored at the start of the file; // zero offset tsOffset.Tag := 1; end; UpdateUIAfterChangeOnCurrentTab(); end; procedure TfrmWizardCreateVolume.rgFileOrPartitionClick(Sender: TObject); begin // Size tab must be marked as incomplete if the user switched to partition, // just in case the user previously entered a size value that's now too big if GetIsPartition() then tsSize.Tag := 0; UpdateUIAfterChangeOnCurrentTab(); end; procedure TfrmWizardCreateVolume.se64ByteOffsetChange(Sender: TObject); begin UpdateUIAfterChangeOnCurrentTab(); end; procedure TfrmWizardCreateVolume.seSizeChange(Sender: TObject); begin UpdateUIAfterChangeOnCurrentTab(); end; procedure TfrmWizardCreateVolume.seSizeExit(Sender: TObject); var minSize: Int64; begin // Use explicit int64 to prevent Delphi converting Size to int minSize := (MIN_REC_VOLUME_SIZE * BYTES_IN_MEGABYTE); // Warn user if volume size smaller than PDA version/ hidden min if (GetSize() < minSize) then begin SDUMessageDlg( Format(_('Please note: If you would like to be able to add a hidden container to your container later, please use a size greater than %d MB'), [MIN_REC_VOLUME_SIZE]), mtWarning ); end; UpdateUIAfterChangeOnCurrentTab(); end; procedure TfrmWizardCreateVolume.PopulatePKCS11Tokens(); begin FPKCS11TokensAvailable := (PKCS11PopulateTokenList( GetFreeOTFEBase().PKCS11Library, cbToken) > 0); end; procedure TfrmWizardCreateVolume.pbRefreshClick(Sender: TObject); begin PopulatePKCS11Tokens(); end; procedure TfrmWizardCreateVolume.fmeSelectPartitionChanged(Sender: TObject); begin se64UnitByteOffset.Value := 0; lblPartitionDiskSize.Caption := Format(_('(Approx: %s)'), [SDUFormatAsBytesUnits(fmeSelectPartition.SelectedSize())]); // Size tab must be marked as incomplete tsSize.Tag := 0; UpdateUIAfterChangeOnCurrentTab(); end; function TfrmWizardCreateVolume.GetCDBInVolFile(): Boolean; begin Result := (Trim(GetCDBFilename()) = ''); end; function TfrmWizardCreateVolume.GetAutoMountAfterCreate(): Boolean; begin Result := ckAutoMountAfterCreate.Checked; end; {overwrites volume with 'chaff' from 'Offset' - uses seleced cypher and options as for enxn } function TfrmWizardCreateVolume.OverwriteVolWithChaff(): Boolean; var shredder: TShredder; overwriteOK: TShredResult; failMsg: String; // tmpZero: ULONGLONG; begin Result := True; // Short-circuit - no padding data // tmpZero := 0; { if (PaddingLength <= tmpZero) then begin Result := TRUE; exit; end;} { if IsPartition then begin Result := TRUE; exit; end; } if GetOverwriteWithChaff() then begin // Initilize zeroed IV for encryption ftempCypherEncBlockNo := 0; // Get *real* random data for encryption key ftempCypherKey := GetRandomData_PaddingKey(); shredder := TShredder.Create(nil); try shredder.FileDirUseInt := True; shredder.IntMethod := smPseudorandom; shredder.IntPasses := 1; shredder.IntSegmentOffset := GetOffset; // cdb is written after so can overwrite. if hidden dont overwrite main data // will be 0 for non hidden vols // shredder.IntSegmentLength := todo; ignored as quickshred = false // if PadWithEncryptedData then // begin // Note: Setting this event overrides shredder.IntMethod shredder.OnOverwriteDataReq := GenerateOverwriteData; // end // else // begin // shredder.OnOverwriteDataReq := nil; // end; { TODO 2 -otdk -ctest : this has not been tested for devices } if GetIsPartition() then overwriteOK := shredder.DestroyDevice(GetVolFilename(), False, False) else overwriteOK := shredder.DestroyFileOrDir(GetVolFilename(), { TODO 1 -otdk -ccheck : check use of quickshred here } False, // quickShred - do all False, // silent True // leaveFile ); if (overwriteOK = srSuccess) then begin // Do nothing... end else if (overwriteOK = srError) then begin failMsg := _('Overwrite of data FAILED.'); SDUMessageDlg(failMsg, mtError); Result := False; end else if (overwriteOK = srUserCancel) then begin SDUMessageDlg(_('Overwrite of data cancelled.'), mtInformation); Result := False; end; finally shredder.Free(); end; end; // if (Result) then SDUInitAndZeroBuffer(0, ftempCypherKey); // ftempCypherKey := ''; assert(SDUBytesToString(ftempCypherKey) = ''); ftempCypherEncBlockNo := 0; end; // The array passed in is zero-indexed; populate elements zero to "bytesRequired" procedure TfrmWizardCreateVolume.GenerateOverwriteData( Sender: TObject; passNumber: Integer; bytesRequired: Cardinal; var generatedOK: Boolean; var outputBlock: TShredBlock ); var i: Integer; tempArraySize: Cardinal; blocksizeBytes: Cardinal; plaintext: Ansistring; cyphertext: Ansistring; IV: Ansistring; localIV: Int64; sectorID: LARGE_INTEGER; tempCipherkeyStr: Ansistring; begin // Generate an array of random data containing "bytesRequired" bytes of data, // plus additional random data to pad out to the nearest multiple of the // cypher's blocksize bits // Cater for if the blocksize was -ve or zero if (ftempCypherDetails.BlockSize < 1) then begin blocksizeBytes := 1; end else begin blocksizeBytes := (ftempCypherDetails.BlockSize div 8); end; tempArraySize := bytesRequired + (blocksizeBytes - (bytesRequired mod blocksizeBytes)); plaintext := ''; for i := 1 to tempArraySize do begin plaintext := plaintext + Ansichar(random(256)); { DONE 2 -otdk -csecurity : This is not secure PRNG - but is encrypted below, so the result is secure } end; Inc(ftempCypherEncBlockNo); // Adjust the IV so that this block of encrypted pseudorandom data should be // reasonably unique IV := ''; if (ftempCypherDetails.BlockSize > 0) then begin IV := StringOfChar(AnsiChar(#0), (ftempCypherDetails.BlockSize div 8)); localIV := ftempCypherEncBlockNo; for i := 1 to min(sizeof(localIV), length(IV)) do begin IV[i] := Ansichar((localIV and $FF)); localIV := localIV shr 8; end; end; // Adjust the sectorID so that this block of encrypted pseudorandom data // should be reasonably unique sectorID.QuadPart := ftempCypherEncBlockNo; // Encrypt the pseudorandom data generated tempCipherkeyStr := SDUBytesToString(ftempCypherKey); if not (GetFreeOTFEBase().EncryptSectorData(GetCypherDriver(), GetCypherGUID(), sectorID, FREEOTFE_v1_DUMMY_SECTOR_SIZE, ftempCypherKey, IV, plaintext, cyphertext)) then begin SDUMessageDlg( _('Error: unable to encrypt pseudorandom data before using for overwrite buffer') + SDUCRLF + SDUCRLF + Format(_('Error #: %d'), [GetFreeOTFEBase().LastErrorCode]), mtError ); generatedOK := False; end else begin // Copy the encrypted data into the outputBlock for i := 0 to (bytesRequired - 1) do outputBlock[i] := Byte(cyphertext[i + 1]); generatedOK := True; end; end; function TfrmWizardCreateVolume.RNG_requiredBits(): Integer; begin Result := CRITICAL_DATA_LENGTH + ftempCypherUseKeyLength; // also same cypher used for chaff if GetOverwriteWithChaff() then Result := Result + ftempCypherUseKeyLength; end; function TfrmWizardCreateVolume.GetDriveLetter(): Char; begin Result := #0; if (cbDriveLetter.ItemIndex > 0) then Result := cbDriveLetter.Items[cbDriveLetter.ItemIndex][1]; end; procedure TfrmWizardCreateVolume.SetDriveLetter(driveLetter: Char); begin cbDriveLetter.ItemIndex := 0; if (driveLetter <> #0) then begin cbDriveLetter.ItemIndex := cbDriveLetter.Items.IndexOf(driveLetter + ':'); end; end; function TfrmWizardCreateVolume.GetCDBFilename(): String; begin Result := ''; if rbCDBInKeyfile.Checked then Result := trim(lblKeyFilename.Caption); end; procedure TfrmWizardCreateVolume.SetCDBFilename(CDBFilename: String); begin rbCDBInVolFile.Checked := True; lblKeyFilename.Caption := CDBFilename; if (CDBFilename <> '') then rbCDBInKeyfile.Checked := True; EnableDisableControls(); end; procedure TfrmWizardCreateVolume.pbBrowseKeyfileClick(Sender: TObject); begin keySaveDialog.Filter := FILE_FILTER_FLT_KEYFILES; keySaveDialog.DefaultExt := FILE_FILTER_DFLT_KEYFILES; keySaveDialog.Options := keySaveDialog.Options + [ofDontAddToRecent]; SDUOpenSaveDialogSetup(keySaveDialog, GetCDBFilename()); if keySaveDialog.Execute then SetCDBFilename(keySaveDialog.Filename); end; function TfrmWizardCreateVolume.GetPaddingLength(): Int64; begin Result := se64Padding.Value; end; procedure TfrmWizardCreateVolume.SetPaddingLength(len: Int64); begin se64Padding.Value := len; end; function TfrmWizardCreateVolume.GetOverwriteWithChaff(): Boolean; begin Result := rgOverwriteType.ItemIndex = 0;// first one is enxd end; procedure TfrmWizardCreateVolume.SetOverwriteWithChaff(secChaff: Boolean); begin rgOverwriteType.ItemIndex := Ifthen(secChaff, 0, 1); end; procedure Format_drive(drivesToFormat: DriveLetterString; frm: TForm); resourcestring FORMAT_CAPTION = 'Format'; var i: Integer; currDrive: DriveLetterChar; driveNum: Word; formatRet: DWORD; ok: Boolean; // hndle:HWND; begin ok := True; for i := 1 to length(drivesToFormat) do begin currDrive := drivesToFormat[i]; driveNum := Ord(currDrive) - Ord('A'); {TODO: use cmd line - se below} //http://stackoverflow.com/questions/2648305/format-drive-by-c formatRet := SHFormatDrive(frm.Handle, driveNum, SHFMT_ID_DEFAULT, SHFMT_OPT_FULL); if formatRet <> 0 then begin ok := False; break; end else begin { dialog only returns when done - use cmd line as above // close format dlg // see also http://stackoverflow.com/questions/15469657/why-is-findwindow-not-100-reliable hndle := FindWindow('IEFrame', NIL); if hndle>0 then begin PostMessage(hndle, WM_CLOSE, 0, 0); end; } end; end; // This is *BIZARRE*. // If you are running under Windows Vista, and you mount a volume for // yourself only, and then try to format it, the format will fail - even if // you UAC escalate to admin // That's one thing - HOWEVER! After it fails, for form's title is set to: // Format <current volume label> <drive letter>: // FREAKY! // OTOH, it does means we can detect and inform the user that the format // just failed... if (Pos(uppercase(FORMAT_CAPTION), uppercase(frm.Caption)) > 0) or not ok then begin frm.Caption := Application.Title; SDUMessageDlg( _('Your encrypted drive could not be formatted.') + SDUCRLF + SDUCRLF + _('Please lock this container and re-open it with the "Mount for all users" option checked, before trying again.'), mtError ); end; end; end.
unit URepositorioRequisicaoEstoque; interface uses URequisicaoEstoque ,UEntidade ,URepositorioDB ,UTipoMovimentacao ,URepositorioTipoMovimentacao ,UStatus ,URepositorioStatus ,UEmpresaMatriz ,URepositorioEmpresaMatriz ,UProduto ,URepositorioProduto ,UDeposito ,URepositorioDeposito ,UUsuario ,URepositorioUsuario ,Ulote ,URepositorioLote ,SqlExpr ; type TRepositorioRequisicaoEstoque = class (TRepositorioDB<TREQUISICAOESTOQUE>) private FRepositorioTipoMovimentacao : TRepositorioTipoMovimentacao; FRepositorioStatus : TRepositorioStatus; FRepositorioEmpresaMatriz : TRepositorioEmpresa; FRepositorioProduto : TRepositorioProduto; FRepositorioDepositoOrigem : TRepositorioDeposito; FRepositorioDepositoDestino : TRepositorioDeposito; FRepositorioUsuario : TRepositorioUsuario; FRepositorioLote : TRepositorioLote; public constructor Create; destructor Destroy; override; procedure AtribuiDBParaEntidade (const coRequisicaoEstoque: TREQUISICAOESTOQUE); override; procedure AtribuiEntidadeParaDB (const coRequisicaoEstoque: TREQUISICAOESTOQUE; const coSQLQuery: TSQLQuery); override; end; implementation uses UDM ,DB ,SysUtils ; { TRepositorioRequisicaoEstoque } procedure TRepositorioRequisicaoEstoque.AtribuiDBParaEntidade( const coRequisicaoEstoque: TREQUISICAOESTOQUE); begin inherited; with FSQLSelect do begin coRequisicaoEstoque.TIPO_MOVIMENTACAO := TTIPOMOVIMENTACAO ( FRepositorioTipoMovimentacao.Retorna (FieldByName (FLD_REQUISICAO_ESTOQUE_TIPO_MOVIMENTACAO).AsInteger)); coRequisicaoEstoque.DATA_EMISSAO := FieldByName(FLD_REQUISICAO_ESTOQUE_DATA_EMISSAO).Asdatetime; coRequisicaoEstoque.DATA_ENTRADA := FieldByName(FLD_REQUISICAO_ESTOQUE_DATA_ENTRADA).Asdatetime; coRequisicaoEstoque.STATUS := TSTATUS ( FRepositorioStatus.Retorna (FieldByName (FLD_REQUISICAO_ESTOQUE_STATUS).Asinteger)); coRequisicaoEstoque.EMPRESA := TEMPRESA ( FRepositorioEmpresaMatriz.Retorna (FieldByName(FLD_REQUISICAO_ESTOQUE_EMPRESA).Asinteger)); coRequisicaoEstoque.NUMERO_DOCUMENTO := FieldByName (FLD_REQUISICAO_ESTOQUE_NUMERO_DOCUMENTO).AsInteger; coRequisicaoEstoque.PRODUTO := TPRODUTO ( FRepositorioProduto.Retorna(FieldByName(FLD_REQUISICAO_ESTOQUE_PRODUTO).AsInteger)); coRequisicaoEstoque.QUANTIDADE := FieldByName (FLD_REQUISICAO_ESTOQUE_QUANTIDADE).AsFloat; coRequisicaoEstoque.CUSTO_UNITARIO := FieldByName (FLD_REQUISICAO_ESTOQUE_CUSTO_UNITARIO).AsFloat; coRequisicaoEstoque.DEPOSITO_DESTINO := TDEPOSITO ( FRepositorioDepositoDestino.Retorna (FieldByName(FLD_REQUISICAO_ESTOQUE_DEPOSITO_DESTINO).AsInteger)); coRequisicaoEstoque.LOTE := TLOTE ( FRepositorioLote.Retorna(FieldByName(FLD_REQUISICAO_ESTOQUE_LOTE).AsInteger)); coRequisicaoEstoque.USUARIO := TUSUARIO ( FRepositorioUsuario.Retorna(FieldByName(FLD_REQUISICAO_ESTOQUE_USUARIO).AsInteger)); coRequisicaoEstoque.DATA_INCLUSAO := FieldByName(FLD_REQUISICAO_ESTOQUE_DATA_INCLUSAO).AsDateTime; if (FieldByName(FLD_REQUISICAO_ESTOQUE_DEPOSITO_ORIGEM).AsInteger) > 0 then coRequisicaoEstoque.DEPOSITO_ORIGEM := TDEPOSITO ( FRepositorioDepositoOrigem.Retorna (FieldByName(FLD_REQUISICAO_ESTOQUE_DEPOSITO_ORIGEM).AsInteger)) else coRequisicaoEstoque.DEPOSITO_ORIGEM.ID := -1; if FieldByName(FLD_REQUISICAO_ESTOQUE_DATA_CANCELAMENTO).AsDateTime > FieldByName(FLD_REQUISICAO_ESTOQUE_DATA_ENTRADA).Asdatetime then coRequisicaoEstoque.DATA_CANCELAMENTO := FieldByName(FLD_REQUISICAO_ESTOQUE_DATA_CANCELAMENTO).AsDateTime; end; end; procedure TRepositorioRequisicaoEstoque.AtribuiEntidadeParaDB( const coRequisicaoEstoque: TREQUISICAOESTOQUE; const coSQLQuery: TSQLQuery); begin inherited; with coSQLQuery do begin ParamByName (FLD_REQUISICAO_ESTOQUE_TIPO_MOVIMENTACAO).AsInteger := coRequisicaoEstoque.TIPO_MOVIMENTACAO.ID; ParamByName (FLD_REQUISICAO_ESTOQUE_DATA_EMISSAO).AsDateTime := coRequisicaoEstoque.DATA_EMISSAO; ParamByName (FLD_REQUISICAO_ESTOQUE_DATA_ENTRADA).AsDateTime := coRequisicaoEstoque.DATA_ENTRADA; ParamByName (FLD_REQUISICAO_ESTOQUE_STATUS).AsInteger := coRequisicaoEstoque.STATUS.ID; ParamByName (FLD_REQUISICAO_ESTOQUE_EMPRESA).AsInteger := coRequisicaoEstoque.EMPRESA.ID; ParamByName (FLD_REQUISICAO_ESTOQUE_NUMERO_DOCUMENTO).asinteger := coRequisicaoEstoque.NUMERO_DOCUMENTO; ParamByName (FLD_REQUISICAO_ESTOQUE_PRODUTO).AsInteger := coRequisicaoEstoque.PRODUTO.ID; ParamByName (FLD_REQUISICAO_ESTOQUE_QUANTIDADE).AsFloat := coRequisicaoEstoque.QUANTIDADE; ParamByName (FLD_REQUISICAO_ESTOQUE_CUSTO_UNITARIO).AsFloat := coRequisicaoEstoque.CUSTO_UNITARIO; ParamByName (FLD_REQUISICAO_ESTOQUE_DEPOSITO_DESTINO).AsInteger := coRequisicaoEstoque.DEPOSITO_DESTINO.ID; ParamByName (FLD_REQUISICAO_ESTOQUE_LOTE).AsInteger := coRequisicaoEstoque.LOTE.ID; ParamByName (FLD_REQUISICAO_ESTOQUE_USUARIO).AsInteger := coRequisicaoEstoque.USUARIO.ID; ParamByName (FLD_REQUISICAO_ESTOQUE_DATA_INCLUSAO).AsDateTime := coRequisicaoEstoque.DATA_INCLUSAO; if coRequisicaoEstoque.DEPOSITO_ORIGEM.ID > 0 then ParamByName(FLD_REQUISICAO_ESTOQUE_DEPOSITO_ORIGEM).AsInteger := coRequisicaoEstoque.DEPOSITO_ORIGEM.ID else begin ParamByName(FLD_REQUISICAO_ESTOQUE_DEPOSITO_ORIGEM).DataType := ftInteger; ParamByName(FLD_REQUISICAO_ESTOQUE_DEPOSITO_ORIGEM).Bound := True; ParamByName(FLD_REQUISICAO_ESTOQUE_DEPOSITO_ORIGEM).Clear; end; if coRequisicaoEstoque.DATA_CANCELAMENTO > coRequisicaoEstoque.DATA_ENTRADA then ParamByName (FLD_REQUISICAO_ESTOQUE_DATA_CANCELAMENTO).AsDateTime := coRequisicaoEstoque.DATA_CANCELAMENTO else begin ParamByName(FLD_REQUISICAO_ESTOQUE_DATA_CANCELAMENTO).DataType := ftDateTime; ParamByName(FLD_REQUISICAO_ESTOQUE_DATA_CANCELAMENTO).Bound := True; ParamByName(FLD_REQUISICAO_ESTOQUE_DATA_CANCELAMENTO).Clear; end; end; end; constructor TRepositorioRequisicaoEstoque.Create; begin inherited Create (TREQUISICAOESTOQUE, TBL_REQUISICAO_ESTOQUE, FLD_ENTIDADE_ID,STR_REQUISICAO_ESTOQUE); FRepositorioTipoMovimentacao := TRepositorioTipoMovimentacao.create; FRepositorioStatus := TRepositorioStatus.Create; FRepositorioEmpresaMatriz := TRepositorioEmpresa.Create; FRepositorioProduto := TRepositorioProduto.Create; FRepositorioDepositoOrigem := TRepositorioDeposito.Create; FRepositorioDepositoDestino := TRepositorioDeposito.Create; FRepositorioLote := TRepositorioLote.Create; FRepositorioUsuario := TRepositorioUsuario.Create; end; destructor TRepositorioRequisicaoEstoque.Destroy; begin FreeAndNil(FRepositorioTipoMovimentacao); FreeAndNil(FRepositorioStatus); FreeAndNil(FRepositorioEmpresaMatriz); FreeAndNil(FRepositorioProduto); FreeAndNil(FRepositorioDepositoOrigem); FreeAndNil(FRepositorioDepositoDestino); FreeAndNil(FRepositorioLote); FreeAndNil(FRepositorioUsuario); inherited; end; end.
unit uFIRational; interface uses System.SysUtils, Winapi.Windows, FreeImage; type LONG = Longint; type TFIRational = class(TObject) private FNumerator, FDenominator: LONG; procedure Initialize(N, D: LONG); procedure Normalize; function GCD(A, B: LONG): LONG; function GetIntValue: Integer; function GetLongValue: LONG; function GetDoubleValue: Double; function Truncate: LONG; public constructor Create; overload; constructor Create(tag: PFITAG); overload; constructor Create(N, D: LONG); overload; function IsInteger: Boolean; function ToString: string; override; property Numerator: LONG read FNumerator; property Denominator: LONG read FDenominator; property IntValue: Integer read GetIntValue; property LongValue: LONG read GetLongValue; property DoubleValue: Double read GetDoubleValue; end; implementation /// Initialize and normalize a rational number procedure TFIRational.Initialize(N, D: LONG); begin if (D > 0) then begin FNumerator := N; FDenominator := D; // normalize rational Normalize; end else begin FNumerator := 0; FDenominator := 0; end; end; /// Default constructor constructor TFIRational.Create; begin FNumerator := 0; FDenominator := 0; end; /// Constructor with longs constructor TFIRational.Create(N, D: LONG); begin Initialize(N, D); end; /// Constructor with FITAG constructor TFIRational.Create(Tag: PFITAG); type DWORD_ARRAY = array[0..1] of DWORD; PDWORD_ARRAY = ^DWORD_ARRAY; DLONG_ARRAY = array[0..1] of LONG; PLONG_ARRAY = ^DLONG_ARRAY; var DWORDValue: PDWORD_ARRAY; LONGValue: PLONG_ARRAY; begin case FreeImage_GetTagType(tag) of FIDT_RATIONAL: // 64-bit unsigned fraction begin DWORDValue := FreeImage_GetTagValue(Tag); Initialize(DWORDValue[0], DWORDValue[1]); end; FIDT_SRATIONAL: // 64-bit signed fraction begin LONGValue := FreeImage_GetTagValue(Tag); Initialize(LONGValue[0], LONGValue[1]); end; end; end; {FIRational.FIRational(Single value) begin if (value = (Single)((LONG)value)) then begin FNumerator := (LONG)value; FDenominator := 1L; end else begin Integer k, count; LONG N[4]; Single x := fabs(value); Integer sign := (value > 0) ? 1 : -1; // make a continued-fraction expansion of x count := -1; for(k := 0; k < 4; k++) begin N[k] := (LONG)floor(x); count++; x - := (Single)N[k]; if(x = 0) then break; x := 1 / x; end; // compute the rational FNumerator := 1; FDenominator := N[count]; for(Integer i := count - 1; i > := 0; i--) begin if(N[i] = 0) then break; LONG _num := (N[i] * FNumerator + FDenominator); LONG _den := FNumerator; FNumerator := _num; FDenominator := _den; end; FNumerator * := sign; end; end; } /// Copy constructor {FIRational.FIRational (const FIRational(* C2PAS: RefOrBit? *)& r) begin initialize(r.FNumerator, r.FDenominator); end; } /// Assignement operator {FIRational(* C2PAS: RefOrBit? *)& FIRational.operator := (FIRational(* C2PAS: RefOrBit? *)& r) begin if (this <> (* C2PAS: RefOrBit? *)&r) then begin initialize(r.FNumerator, r.FDenominator); end; (* C2PAS: Exit *) Result := *this; end; } /// Get the numerator {LONG FIRational.getNumerator() begin (* C2PAS: Exit *) Result := FNumerator; end;} /// Get the denominator {LONG FIRational.getDenominator() begin (* C2PAS: Exit *) Result := FDenominator; end;} /// Calculate GCD function TFIRational.GCD(A, B: LONG): LONG; var Temp: LONG; begin while (b > 0) do begin // While non-zero value Temp := b; // Save current value b := a mod b; // Assign remainder of division a := Temp; // Copy old value end; Result := a; // Return GCD of numbers end; function TFIRational.GetIntValue: Integer; begin Result := Truncate(); end; function TFIRational.GetLongValue: LONG; begin Result := LONG(Truncate()); end; function TFIRational.GetDoubleValue: Double; begin if FDenominator > 0 then Result := FNumerator/FDenominator else Result := 0; end; /// Normalize numerator / denominator procedure TFIRational.Normalize(); var Common: LONG; begin if (FNumerator <> 1) and (FDenominator <> 1) then begin // Is there something to do? // Calculate GCD Common := GCD(FNumerator, FDenominator); if (Common <> 1) then begin // If GCD is not one FNumerator := FNumerator div Common; // Calculate new numerator FDenominator := FDenominator div Common; // Calculate new denominator end; end; if (FDenominator < 0) then begin // If sign is in denominator FNumerator := FNumerator * (-1); // Multiply num and den by -1 FDenominator := FDenominator * (-1); // To keep sign in numerator end; end; /// Checks if this rational number is an Integer, either positive or negative function TFIRational.IsInteger : Boolean; begin Result := ((FDenominator = 1) or ((FDenominator <> 0) and (FNumerator mod FDenominator = 0)) or ((FDenominator = 0) and (FNumerator = 0))); end; function TFIRational.Truncate: LONG; begin // Return truncated rational if FDenominator > 0 then Result := FNumerator div FDenominator else Result := 0; end; /// Convert as "numerator/denominator" function TFIRational.ToString: string; begin Result := ''; if IsInteger() then Result := IntToStr(IntValue) else Result := IntToStr(FNumerator) + '/' + IntToStr(FDenominator); end; end.
unit ojVirtualDrawTreeDesign; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ojVirtualTrees, StdCtrls, CheckLst; type TojVirtualDrawTreeDesignForm = class(TForm) chAutoOptionsList: TCheckListBox; Label1: TLabel; Label2: TLabel; chMiscOptionsList: TCheckListBox; Label3: TLabel; chPaintOptionsList: TCheckListBox; Label4: TLabel; chSelectionOptionsList: TCheckListBox; lblInfo: TLabel; Label5: TLabel; chAnimationOptionsList: TCheckListBox; btnRestoreAutoOptions: TButton; btnRestoreSelectionOptions: TButton; btnRestorePaintOptions: TButton; btnRestoreMiscOptions: TButton; btnRestoreAnimationOptions: TButton; procedure chAutoOptionsListClickCheck(Sender: TObject); procedure chMiscOptionsListClickCheck(Sender: TObject); procedure chPaintOptionsListClickCheck(Sender: TObject); procedure chSelectionOptionsListClickCheck(Sender: TObject); procedure chAutoOptionsListMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure chAnimationOptionsListClickCheck(Sender: TObject); procedure chAnimationOptionsListMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure chMiscOptionsListMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure chPaintOptionsListMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure chSelectionOptionsListMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure btnRestoreAutoOptionsClick(Sender: TObject); procedure btnRestoreSelectionOptionsClick(Sender: TObject); procedure btnRestorePaintOptionsClick(Sender: TObject); procedure btnRestoreMiscOptionsClick(Sender: TObject); procedure btnRestoreAnimationOptionsClick(Sender: TObject); private FVirtualTree: TojCustomVirtualDrawTree; protected procedure FillAutoOptionsList; procedure FillMiscOptionsList; procedure FillPaintOptionsList; procedure FillSelectionOptionsList; procedure FillAnimationOptionsList; public constructor Create(AOwner: TComponent; VirtualTree: TojCustomVirtualDrawTree);reintroduce;overload;virtual; function getVirtualTree: TojCustomVirtualDrawTree; public class procedure ShowDesigner(p_VirtualTree: TojCustomVirtualDrawTree); end; implementation uses typInfo; {$R *.dfm} type TFakeCustomVirtualDrawTree = class(TojCustomVirtualDrawTree); TFakeCustomVirtualTreeOptions = class(TCustomVirtualTreeOptions); { TVirtualDrawTreeDesignForm } procedure TojVirtualDrawTreeDesignForm.btnRestoreAnimationOptionsClick(Sender: TObject); var v_tree: TFakeCustomVirtualDrawTree; begin v_tree:= TFakeCustomVirtualDrawTree(getVirtualTree); TFakeCustomVirtualTreeOptions(v_tree.TreeOptions).AnimationOptions:= DefaultAnimationOptions; FillAnimationOptionsList; end; procedure TojVirtualDrawTreeDesignForm.btnRestoreAutoOptionsClick(Sender: TObject); var v_tree: TFakeCustomVirtualDrawTree; begin v_tree:= TFakeCustomVirtualDrawTree(getVirtualTree); TFakeCustomVirtualTreeOptions(v_tree.TreeOptions).AnimationOptions:= DefaultAnimationOptions; FillAutoOptionsList; end; procedure TojVirtualDrawTreeDesignForm.btnRestoreMiscOptionsClick(Sender: TObject); var v_tree: TFakeCustomVirtualDrawTree; begin v_tree:= TFakeCustomVirtualDrawTree(getVirtualTree); TFakeCustomVirtualTreeOptions(v_tree.TreeOptions).MiscOptions:= DefaultMiscOptions; FillMiscOptionsList; end; procedure TojVirtualDrawTreeDesignForm.btnRestorePaintOptionsClick(Sender: TObject); var v_tree: TFakeCustomVirtualDrawTree; begin v_tree:= TFakeCustomVirtualDrawTree(getVirtualTree); TFakeCustomVirtualTreeOptions(v_tree.TreeOptions).PaintOptions:= DefaultPaintOptions; FillPaintOptionsList; end; procedure TojVirtualDrawTreeDesignForm.btnRestoreSelectionOptionsClick(Sender: TObject); var v_tree: TFakeCustomVirtualDrawTree; begin v_tree:= TFakeCustomVirtualDrawTree(getVirtualTree); TFakeCustomVirtualTreeOptions(v_tree.TreeOptions).SelectionOptions:= DefaultSelectionOptions; FillSelectionOptionsList; end; procedure TojVirtualDrawTreeDesignForm.chAnimationOptionsListClickCheck(Sender: TObject); var v_opt: TVTAnimationOption; v_opts: TVTAnimationOptions; v_tree: TFakeCustomVirtualDrawTree; i: integer; begin v_opts:= []; v_tree:= TFakeCustomVirtualDrawTree(getVirtualTree); for i:= 0 to chAnimationOptionsList.Items.Count-1 do if chAnimationOptionsList.Checked[i] then begin v_opt:= TVTAnimationOption(GetEnumValue(TypeInfo(TVTAnimationOption), chAnimationOptionsList.Items[i])); v_opts:= v_opts + [v_opt]; end; TFakeCustomVirtualTreeOptions(v_tree.TreeOptions).AnimationOptions:= v_opts; end; procedure TojVirtualDrawTreeDesignForm.chAnimationOptionsListMouseMove( Sender: TObject; Shift: TShiftState; X, Y: Integer); var v_idx: Integer; v_opt: TVTAnimationOption; begin v_idx:= chAnimationOptionsList.ItemAtPos(Point(X, Y), TRUE); if v_idx >= 0 then begin v_opt:= TVTAnimationOption(GetEnumValue(TypeInfo(TVTAnimationOption), chAnimationOptionsList.Items[v_idx])); // lblInfo.Caption:= VTAutoOptionDescriptions[v_opt]; lblInfo.Caption:= chAnimationOptionsList.Items[v_idx] + ':' + sLineBreak + VTAnimationOptionDescriptions[v_opt]; end else lblInfo.Caption:= ''; end; procedure TojVirtualDrawTreeDesignForm.chAutoOptionsListClickCheck(Sender: TObject); var v_opt: TVTAutoOption; v_opts: TVTAutoOptions; v_tree: TFakeCustomVirtualDrawTree; i: integer; begin v_opts:= []; v_tree:= TFakeCustomVirtualDrawTree(getVirtualTree); for i:= 0 to chAutoOptionsList.Items.Count-1 do if chAutoOptionsList.Checked[i] then begin v_opt:= TVTAutoOption(GetEnumValue(TypeInfo(TVTAutoOption), chAutoOptionsList.Items[i])); v_opts:= v_opts + [v_opt]; end; TFakeCustomVirtualTreeOptions(v_tree.TreeOptions).AutoOptions:= v_opts; end; procedure TojVirtualDrawTreeDesignForm.chAutoOptionsListMouseMove( Sender: TObject; Shift: TShiftState; X, Y: Integer); var v_idx: Integer; v_opt: TVTAutoOption; begin v_idx:= chAutoOptionsList.ItemAtPos(Point(X, Y), TRUE); if v_idx >= 0 then begin v_opt:= TVTAutoOption(GetEnumValue(TypeInfo(TVTAutoOption), chAutoOptionsList.Items[v_idx])); // lblInfo.Caption:= VTAutoOptionDescriptions[v_opt]; lblInfo.Caption:= chAutoOptionsList.Items[v_idx] + ':' + sLineBreak + VTAutoOptionDescriptions[v_opt]; end else lblInfo.Caption:= ''; end; procedure TojVirtualDrawTreeDesignForm.chMiscOptionsListClickCheck(Sender: TObject); var v_opt: TVTMiscOption; v_opts: TVTMiscOptions; v_tree: TFakeCustomVirtualDrawTree; i: integer; begin v_opts:= []; v_tree:= TFakeCustomVirtualDrawTree(getVirtualTree); for i:= 0 to chMiscOptionsList.Items.Count-1 do if chMiscOptionsList.Checked[i] then begin v_opt:= TVTMiscOption(GetEnumValue(TypeInfo(TVTMiscOption), chMiscOptionsList.Items[i])); v_opts:= v_opts + [v_opt]; end; TFakeCustomVirtualTreeOptions(v_tree.TreeOptions).MiscOptions:= v_opts; end; procedure TojVirtualDrawTreeDesignForm.chMiscOptionsListMouseMove( Sender: TObject; Shift: TShiftState; X, Y: Integer); var v_idx: Integer; v_opt: TVTMiscOption; begin v_idx:= chMiscOptionsList.ItemAtPos(Point(X, Y), TRUE); if v_idx >= 0 then begin v_opt:= TVTMiscOption(GetEnumValue(TypeInfo(TVTMiscOption), chMiscOptionsList.Items[v_idx])); // lblInfo.Caption:= VTAutoOptionDescriptions[v_opt]; lblInfo.Caption:= chMiscOptionsList.Items[v_idx] + ':' + sLineBreak + VTMiscOptionDescriptions[v_opt]; end else lblInfo.Caption:= ''; end; procedure TojVirtualDrawTreeDesignForm.chPaintOptionsListClickCheck(Sender: TObject); var v_opt: TVTPaintOption; v_opts: TVTPaintOptions; v_tree: TFakeCustomVirtualDrawTree; i: integer; begin v_opts:= []; v_tree:= TFakeCustomVirtualDrawTree(getVirtualTree); for i:= 0 to chPaintOptionsList.Items.Count-1 do if chPaintOptionsList.Checked[i] then begin v_opt:= TVTPaintOption(GetEnumValue(TypeInfo(TVTPaintOption), chPaintOptionsList.Items[i])); v_opts:= v_opts + [v_opt]; end; TFakeCustomVirtualTreeOptions(v_tree.TreeOptions).PaintOptions:= v_opts; end; procedure TojVirtualDrawTreeDesignForm.chPaintOptionsListMouseMove( Sender: TObject; Shift: TShiftState; X, Y: Integer); var v_idx: Integer; v_opt: TVTPaintOption; begin v_idx:= chPaintOptionsList.ItemAtPos(Point(X, Y), TRUE); if v_idx >= 0 then begin v_opt:= TVTPaintOption(GetEnumValue(TypeInfo(TVTPaintOption), chPaintOptionsList.Items[v_idx])); // lblInfo.Caption:= VTAutoOptionDescriptions[v_opt]; lblInfo.Caption:= chPaintOptionsList.Items[v_idx] + ':' + sLineBreak + VTPaintOptionDescriptions[v_opt]; end else lblInfo.Caption:= ''; end; procedure TojVirtualDrawTreeDesignForm.chSelectionOptionsListClickCheck(Sender: TObject); var v_opt: TVTSelectionOption; v_opts: TVTSelectionOptions; v_tree: TFakeCustomVirtualDrawTree; i: integer; begin v_opts:= []; v_tree:= TFakeCustomVirtualDrawTree(getVirtualTree); for i:= 0 to chSelectionOptionsList.Items.Count-1 do if chSelectionOptionsList.Checked[i] then begin v_opt:= TVTSelectionOption(GetEnumValue(TypeInfo(TVTSelectionOption), chSelectionOptionsList.Items[i])); v_opts:= v_opts + [v_opt]; end; TFakeCustomVirtualTreeOptions(v_tree.TreeOptions).SelectionOptions:= v_opts; end; procedure TojVirtualDrawTreeDesignForm.chSelectionOptionsListMouseMove( Sender: TObject; Shift: TShiftState; X, Y: Integer); var v_idx: Integer; v_opt: TVTSelectionOption; begin v_idx:= chSelectionOptionsList.ItemAtPos(Point(X, Y), TRUE); if v_idx >= 0 then begin v_opt:= TVTSelectionOption(GetEnumValue(TypeInfo(TVTSelectionOption), chSelectionOptionsList.Items[v_idx])); // lblInfo.Caption:= VTAutoOptionDescriptions[v_opt]; lblInfo.Caption:= chSelectionOptionsList.Items[v_idx] + ':' + sLineBreak + VTSelectionOptionDescriptions[v_opt]; end else lblInfo.Caption:= ''; end; constructor TojVirtualDrawTreeDesignForm.Create(AOwner: TComponent; VirtualTree: TojCustomVirtualDrawTree); begin inherited Create(AOwner); FVirtualTree:= VirtualTree; self.Caption:= 'TVirtualDrawTreeDesignForm: '+ VirtualTree.Name; FillAutoOptionsList; FillMiscOptionsList; FillPaintOptionsList; FillSelectionOptionsList; FillAnimationOptionsList; end; procedure TojVirtualDrawTreeDesignForm.FillAnimationOptionsList; var v_tree: TFakeCustomVirtualDrawTree; v_opt: TVTAnimationOption; v_idx: Integer; begin chAnimationOptionsList.Items.Clear; v_tree:= TFakeCustomVirtualDrawTree(getVirtualTree); for v_opt:= Low(TVTAnimationOption) to High(TVTAnimationOption) do begin v_idx:= chAnimationOptionsList.Items.Add( GetEnumName(TypeInfo(TVTAnimationOption), Integer(v_opt)) ); chAnimationOptionsList.Checked[v_idx]:= (v_opt in TFakeCustomVirtualTreeOptions(v_tree.TreeOptions).AnimationOptions); end; end; procedure TojVirtualDrawTreeDesignForm.FillAutoOptionsList; var v_tree: TFakeCustomVirtualDrawTree; v_opt: TVTAutoOption; v_idx: Integer; begin chAutoOptionsList.Items.Clear; v_tree:= TFakeCustomVirtualDrawTree(getVirtualTree); for v_opt:= Low(TVTAutoOption) to High(TVTAutoOption) do begin v_idx:= chAutoOptionsList.Items.Add( GetEnumName(TypeInfo(TVTAutoOption), Integer(v_opt)) ); chAutoOptionsList.Checked[v_idx]:= (v_opt in TFakeCustomVirtualTreeOptions(v_tree.TreeOptions).AutoOptions); end; end; procedure TojVirtualDrawTreeDesignForm.FillMiscOptionsList; var v_tree: TFakeCustomVirtualDrawTree; v_opt: TVTMiscOption; v_idx: Integer; begin chMiscOptionsList.Items.Clear; v_tree:= TFakeCustomVirtualDrawTree(getVirtualTree); for v_opt:= Low(TVTMiscOption) to High(TVTMiscOption) do begin v_idx:= chMiscOptionsList.Items.Add( GetEnumName(TypeInfo(TVTMiscOption), Integer(v_opt)) ); chMiscOptionsList.Checked[v_idx]:= (v_opt in TFakeCustomVirtualTreeOptions(v_tree.TreeOptions).MiscOptions); end; end; procedure TojVirtualDrawTreeDesignForm.FillPaintOptionsList; var v_tree: TFakeCustomVirtualDrawTree; v_opt: TVTPaintOption; v_idx: Integer; begin chPaintOptionsList.Items.Clear; v_tree:= TFakeCustomVirtualDrawTree(getVirtualTree); for v_opt:= Low(TVTPaintOption) to High(TVTPaintOption) do begin v_idx:= chPaintOptionsList.Items.Add( GetEnumName(TypeInfo(TVTPaintOption), Integer(v_opt)) ); chPaintOptionsList.Checked[v_idx]:= (v_opt in TFakeCustomVirtualTreeOptions(v_tree.TreeOptions).PaintOptions); end; end; procedure TojVirtualDrawTreeDesignForm.FillSelectionOptionsList; var v_tree: TFakeCustomVirtualDrawTree; v_opt: TVTSelectionOption; v_idx: Integer; begin chSelectionOptionsList.Items.Clear; v_tree:= TFakeCustomVirtualDrawTree(getVirtualTree); for v_opt:= Low(TVTSelectionOption) to High(TVTSelectionOption) do begin v_idx:= chSelectionOptionsList.Items.Add( GetEnumName(TypeInfo(TVTSelectionOption), Integer(v_opt)) ); chSelectionOptionsList.Checked[v_idx]:= (v_opt in TFakeCustomVirtualTreeOptions(v_tree.TreeOptions).SelectionOptions); end; end; function TojVirtualDrawTreeDesignForm.getVirtualTree: TojCustomVirtualDrawTree; begin result:= FVirtualTree; end; class procedure TojVirtualDrawTreeDesignForm.ShowDesigner(p_VirtualTree: TojCustomVirtualDrawTree); var v_form: TojVirtualDrawTreeDesignForm; begin v_form:= TojVirtualDrawTreeDesignForm.Create(nil, p_VirtualTree); try v_form.ShowModal; finally FreeAndNil(v_form); end; end; end.
unit cls_migrate; {$mode objfpc}{$H+} interface uses Classes, SysUtils; const cns_Migr_010 = 0; cns_Sql_AddTableMetaStrings = 'create table if not exists TimeMetaStrings (' + '_id INTEGER, ' + 'pkey TEXT, ' + 'tms_Ctrl TEXT, ' + 'tms_Title TEXT, ' + 'tms_MetaDat TEXT, ' + 'tms_Date TEXT, ' + 'tms_VolgNr INTEGER, ' + 'PRIMARY KEY(_id )' + ')'; type { TAppMigrate } TAppMigrate = class public class procedure SelectMigration; class function DoMigr_010: Boolean; end; implementation uses globals; { TAppMigrate } class procedure TAppMigrate.SelectMigration; var lVerInt: integer; begin /// Haal huidige versie op lVerInt := StrToInt(StringReplace(cns_Apl_Version, '.', EmptyStr, [rfReplaceAll])); /// Update event inifile (is dat wel nodig?) if qCurrAppMigration = 0 then begin qCurrAppMigration := lVerInt; qIniPropStorage.WriteIniInteger(cns_Ini_CurrAppMigration, qCurrAppMigration); end; /// Migratiegetal normaal 1 hoger dan Versiegetal /// Migratiegetal is alleen maar vlag als een soort boolean, zodat /// wanneer ik het versie ophoog deze exit gepasseerd wordt if qCurrAppMigration > lVerInt then Exit; if qCurrAppMigration <= cns_Migr_010 then DoMigr_010; end; class function TAppMigrate.DoMigr_010:Boolean; begin Result := MainDataMod.ExecuteCmnds(cns_Sql_AddTableMetaStrings); /// Migratie getal 1 ophogen qIniPropStorage.WriteIniInteger(cns_Ini_CurrAppMigration, qCurrAppMigration + 1); end; end.
namespace MetalExample; interface // Buffer index values shared between shader and Oxygene code to ensure Metal shader buffer inputs match // Metal API buffer set calls const AAPLVertexInputIndexVertices = 0; const AAPLVertexInputIndexViewportSize = 1; type vector_float2 = Array[0..1] of Single; vector_float4 = Array[0..3] of Single; type // This structure defines the layout of each vertex in the array of vertices set as an input to our // Metal vertex shader. Since this header is shared between our .metal shader and C code, // we can be sure that the layout of the vertex array in our C code matches the layout that // our .metal vertex shader expects // At moment we need a dummy record inside because the shader is using vectortypes with a alignment of 16 // Used in Example1 AAPLVertex1 = record // Positions in pixel space // (e.g. a value of 100 indicates 100 pixels from the center) {$HIDE H7} position : vector_float2; // Is needed for 16 byte alignement used in Metal dummy : vector_float2; // Floating-point RGBA colors color : Color;//vector_float4; end; // Used in Example2 AAPLVertex2 = AAPLVertex1; //Used in Example 3 and 4 AAPLVertex3 = record // Positions in pixel space (i.e. a value of 100 indicates 100 pixels from the origin/center) position : vector_float2; // 2D texture coordinate textureCoordinate : vector_float2; end; type Color = record red, green, blue, alpha : Single; class method create(const r,g,b,a : Single) : Color; class method createRed() : Color; class method createGreen() : Color; class method createBlue() : Color; end; implementation class method Color.create(const r: single; const g: single; const b: single; const a: single): Color; begin result.red := r; result.green := g; result.blue := b; result.alpha := a; end; class method Color.createRed: Color; begin result.red := 1; result.green := 0; result.blue := 0; result.alpha := 1; end; class method Color.createGreen: Color; begin result.red := 0; result.green := 1; result.blue := 0; result.alpha := 1; end; class method Color.createBlue: Color; begin result.red := 0; result.green := 0; result.blue := 1; result.alpha := 1; end; end.
unit Mac.Services; interface uses Xplat.Services, MacApi.AppKit, FMX.Platform.Mac; type TMacPleaseWait = class(TInterfacedObject, IPleaseWaitService) private FView: NSProgressIndicator; public procedure StartWait; procedure StopWait; end; implementation uses FMX.Forms, FMX.Platform, Apple.Utils, Macapi.CocoaTypes; { TMacPleaseWait } procedure TMacPleaseWait.StartWait; const cnHeight = 30; cnWidth = 30; var lView: NSView; begin lView := ActiveView; FView := TNSProgressIndicator.Create; FView.initWithFrame(MakeNSRect( ((lView.bounds.size.width / 2) - (cnWidth / 2)), ((lView.bounds.size.height / 2) - (cnHeight /2)), cnWidth, cnHeight)); FView.setStyle(NSProgressIndicatorSpinningStyle); FView.setIndeterminate(True); lView.addSubview(FView); FView.startAnimation(PtrForObject(lView)); end; procedure TMacPleaseWait.StopWait; begin if Assigned(FView) then begin FView.stopAnimation(PtrForObject(ActiveView)); FView.removeFromSuperview; FView := nil; end; end; initialization TPlatformServices.Current.AddPlatformService(IPleaseWaitService, TMacPleaseWait.Create); finalization TPlatformServices.Current.RemovePlatformService(IPleaseWaitService); end.
unit uJSONUser; // ************************************************* // Generated By: JsonToDelphiClass - 0.65 // Project link: https://github.com/PKGeorgiev/Delphi-JsonToDelphiClass // Generated On: 2020-03-30 14:23:29 // ************************************************* // Created By : Petar Georgiev - 2014 // WebSite : http://pgeorgiev.com // ************************************************* interface uses Generics.Collections, Rest.Json; type TUserClass = class private FName: String; FPassword: String; FPath: String; public property name: String read FName write FName; property password: String read FPassword write FPassword; property path: String read FPath write FPath; function ToJsonString: string; class function FromJsonString(AJsonString: string): TUserClass; end; TUsersClass = class private FUser: TUserClass; public property user: TUserClass read FUser write FUser; constructor Create; destructor Destroy; override; function ToJsonString: string; class function FromJsonString(AJsonString: string): TUsersClass; end; implementation {TUserClass} function TUserClass.ToJsonString: string; begin result := TJson.ObjectToJsonString(self); end; class function TUserClass.FromJsonString(AJsonString: string): TUserClass; begin result := TJson.JsonToObject<TUserClass>(AJsonString) end; {TUsersClass} constructor TUsersClass.Create; begin inherited; FUser := TUserClass.Create(); end; destructor TUsersClass.Destroy; begin FUser.free; inherited; end; function TUsersClass.ToJsonString: string; begin result := TJson.ObjectToJsonString(self); end; class function TUsersClass.FromJsonString(AJsonString: string): TUsersClass; begin result := TJson.JsonToObject<TUsersClass>(AJsonString); end; end.
namespace CustomerList; interface uses System.Windows.Forms, System.Drawing, System.Data, System.Data.Common, System.Data.SqlClient; type MainForm = class(System.Windows.Forms.Form) {$REGION Windows Form Designer generated fields} private bSaveChanges: System.Windows.Forms.Button; MySQLDataAdapter: System.Data.SqlClient.SqlDataAdapter; MySQLConnection: System.Data.SqlClient.SqlConnection; sqlSelectCommand1: System.Data.SqlClient.SqlCommand; sqlInsertCommand1: System.Data.SqlClient.SqlCommand; sqlUpdateCommand1: System.Data.SqlClient.SqlCommand; sqlDeleteCommand1: System.Data.SqlClient.SqlCommand; DataGrid: System.Windows.Forms.DataGrid; tbConnectionString: System.Windows.Forms.TextBox; bConnect: System.Windows.Forms.Button; label1: System.Windows.Forms.Label; components: System.ComponentModel.Container := nil; method bSaveChanges_Click(sender: System.Object; e: System.EventArgs); method bConnect_Click(sender: System.Object; e: System.EventArgs); method InitializeComponent; {$ENDREGION} protected fMyDataset : DataSet; method Dispose(aDisposing: Boolean); override; method GetCustomer: DataTable; public constructor; class method Main; property MyDataset : DataSet read fMyDataset; property Customers : DataTable read GetCustomer; end; implementation {$REGION Construction and Disposition} constructor MainForm; begin InitializeComponent(); end; method MainForm.Dispose(aDisposing: boolean); begin if aDisposing then begin if assigned(components) then components.Dispose(); end; inherited Dispose(aDisposing); end; {$ENDREGION} {$REGION Windows Form Designer generated code} method MainForm.InitializeComponent; begin var resources: System.ComponentModel.ComponentResourceManager := new System.ComponentModel.ComponentResourceManager(typeOf(MainForm)); self.tbConnectionString := new System.Windows.Forms.TextBox(); self.label1 := new System.Windows.Forms.Label(); self.bConnect := new System.Windows.Forms.Button(); self.DataGrid := new System.Windows.Forms.DataGrid(); self.MySQLDataAdapter := new System.Data.SqlClient.SqlDataAdapter(); self.sqlDeleteCommand1 := new System.Data.SqlClient.SqlCommand(); self.MySQLConnection := new System.Data.SqlClient.SqlConnection(); self.sqlInsertCommand1 := new System.Data.SqlClient.SqlCommand(); self.sqlSelectCommand1 := new System.Data.SqlClient.SqlCommand(); self.sqlUpdateCommand1 := new System.Data.SqlClient.SqlCommand(); self.bSaveChanges := new System.Windows.Forms.Button(); (self.DataGrid as System.ComponentModel.ISupportInitialize).BeginInit(); self.SuspendLayout(); // // tbConnectionString // self.tbConnectionString.Anchor := (((System.Windows.Forms.AnchorStyles.Top or System.Windows.Forms.AnchorStyles.Left) or System.Windows.Forms.AnchorStyles.Right) as System.Windows.Forms.AnchorStyles); self.tbConnectionString.Location := new System.Drawing.Point(108, 16); self.tbConnectionString.Name := 'tbConnectionString'; self.tbConnectionString.Size := new System.Drawing.Size(344, 20); self.tbConnectionString.TabIndex := 0; self.tbConnectionString.Text := 'Data Source=localhost;Database=Northwind;Integrated Security=SSPI'; // // label1 // self.label1.Location := new System.Drawing.Point(8, 19); self.label1.Name := 'label1'; self.label1.Size := new System.Drawing.Size(100, 14); self.label1.TabIndex := 1; self.label1.Text := 'Connection String:'; // // bConnect // self.bConnect.Anchor := ((System.Windows.Forms.AnchorStyles.Top or System.Windows.Forms.AnchorStyles.Right) as System.Windows.Forms.AnchorStyles); self.bConnect.Location := new System.Drawing.Point(462, 15); self.bConnect.Name := 'bConnect'; self.bConnect.Size := new System.Drawing.Size(75, 23); self.bConnect.TabIndex := 2; self.bConnect.Text := '&Connect'; self.bConnect.Click += new System.EventHandler(@self.bConnect_Click); // // DataGrid // self.DataGrid.Anchor := ((((System.Windows.Forms.AnchorStyles.Top or System.Windows.Forms.AnchorStyles.Bottom) or System.Windows.Forms.AnchorStyles.Left) or System.Windows.Forms.AnchorStyles.Right) as System.Windows.Forms.AnchorStyles); self.DataGrid.DataMember := ''; self.DataGrid.HeaderForeColor := System.Drawing.SystemColors.ControlText; self.DataGrid.Location := new System.Drawing.Point(8, 56); self.DataGrid.Name := 'DataGrid'; self.DataGrid.Size := new System.Drawing.Size(525, 256); self.DataGrid.TabIndex := 3; // // MySQLDataAdapter // self.MySQLDataAdapter.DeleteCommand := self.sqlDeleteCommand1; self.MySQLDataAdapter.InsertCommand := self.sqlInsertCommand1; self.MySQLDataAdapter.SelectCommand := self.sqlSelectCommand1; self.MySQLDataAdapter.TableMappings.AddRange(array of System.Data.Common.DataTableMapping([new System.Data.Common.DataTableMapping('Table', 'Customers', array of System.Data.Common.DataColumnMapping([new System.Data.Common.DataColumnMapping('CustomerID', 'CustomerID'), new System.Data.Common.DataColumnMapping('CompanyName', 'CompanyName'), new System.Data.Common.DataColumnMapping('ContactName', 'ContactName'), new System.Data.Common.DataColumnMapping('ContactTitle', 'ContactTitle'), new System.Data.Common.DataColumnMapping('Address', 'Address'), new System.Data.Common.DataColumnMapping('City', 'City'), new System.Data.Common.DataColumnMapping('Region', 'Region'), new System.Data.Common.DataColumnMapping('PostalCode', 'PostalCode'), new System.Data.Common.DataColumnMapping('Country', 'Country'), new System.Data.Common.DataColumnMapping('Phone', 'Phone'), new System.Data.Common.DataColumnMapping('Fax', 'Fax')]))])); self.MySQLDataAdapter.UpdateCommand := self.sqlUpdateCommand1; // // sqlDeleteCommand1 // self.sqlDeleteCommand1.CommandText := resources.GetString('sqlDeleteCommand1.CommandText'); self.sqlDeleteCommand1.Connection := self.MySQLConnection; self.sqlDeleteCommand1.Parameters.AddRange(array of System.Data.SqlClient.SqlParameter([new System.Data.SqlClient.SqlParameter('@Original_CustomerID', System.Data.SqlDbType.NVarChar, 5, System.Data.ParameterDirection.Input, false, (0 as System.Byte), (0 as System.Byte), 'CustomerID', System.Data.DataRowVersion.Original, nil), new System.Data.SqlClient.SqlParameter('@Original_Address', System.Data.SqlDbType.NVarChar, 60, System.Data.ParameterDirection.Input, false, (0 as System.Byte), (0 as System.Byte), 'Address', System.Data.DataRowVersion.Original, nil), new System.Data.SqlClient.SqlParameter('@Original_City', System.Data.SqlDbType.NVarChar, 15, System.Data.ParameterDirection.Input, false, (0 as System.Byte), (0 as System.Byte), 'City', System.Data.DataRowVersion.Original, nil), new System.Data.SqlClient.SqlParameter('@Original_CompanyName', System.Data.SqlDbType.NVarChar, 40, System.Data.ParameterDirection.Input, false, (0 as System.Byte), (0 as System.Byte), 'CompanyName', System.Data.DataRowVersion.Original, nil), new System.Data.SqlClient.SqlParameter('@Original_ContactName', System.Data.SqlDbType.NVarChar, 30, System.Data.ParameterDirection.Input, false, (0 as System.Byte), (0 as System.Byte), 'ContactName', System.Data.DataRowVersion.Original, nil), new System.Data.SqlClient.SqlParameter('@Original_ContactTitle', System.Data.SqlDbType.NVarChar, 30, System.Data.ParameterDirection.Input, false, (0 as System.Byte), (0 as System.Byte), 'ContactTitle', System.Data.DataRowVersion.Original, nil), new System.Data.SqlClient.SqlParameter('@Original_Country', System.Data.SqlDbType.NVarChar, 15, System.Data.ParameterDirection.Input, false, (0 as System.Byte), (0 as System.Byte), 'Country', System.Data.DataRowVersion.Original, nil), new System.Data.SqlClient.SqlParameter('@Original_Fax', System.Data.SqlDbType.NVarChar, 24, System.Data.ParameterDirection.Input, false, (0 as System.Byte), (0 as System.Byte), 'Fax', System.Data.DataRowVersion.Original, nil), new System.Data.SqlClient.SqlParameter('@Original_Phone', System.Data.SqlDbType.NVarChar, 24, System.Data.ParameterDirection.Input, false, (0 as System.Byte), (0 as System.Byte), 'Phone', System.Data.DataRowVersion.Original, nil), new System.Data.SqlClient.SqlParameter('@Original_PostalCode', System.Data.SqlDbType.NVarChar, 10, System.Data.ParameterDirection.Input, false, (0 as System.Byte), (0 as System.Byte), 'PostalCode', System.Data.DataRowVersion.Original, nil), new System.Data.SqlClient.SqlParameter('@Original_Region', System.Data.SqlDbType.NVarChar, 15, System.Data.ParameterDirection.Input, false, (0 as System.Byte), (0 as System.Byte), 'Region', System.Data.DataRowVersion.Original, nil)])); // // MySQLConnection // self.MySQLConnection.ConnectionString := 'workstation id=BABYBEAST;packet size=4096;user id=sa;data source=".";persist security info=False;initial catalog=Northwind'; self.MySQLConnection.FireInfoMessageEventOnUserErrors := false; // // sqlInsertCommand1 // self.sqlInsertCommand1.CommandText := resources.GetString('sqlInsertCommand1.CommandText'); self.sqlInsertCommand1.Connection := self.MySQLConnection; self.sqlInsertCommand1.Parameters.AddRange(array of System.Data.SqlClient.SqlParameter([new System.Data.SqlClient.SqlParameter('@CustomerID', System.Data.SqlDbType.NVarChar, 5, 'CustomerID'), new System.Data.SqlClient.SqlParameter('@CompanyName', System.Data.SqlDbType.NVarChar, 40, 'CompanyName'), new System.Data.SqlClient.SqlParameter('@ContactName', System.Data.SqlDbType.NVarChar, 30, 'ContactName'), new System.Data.SqlClient.SqlParameter('@ContactTitle', System.Data.SqlDbType.NVarChar, 30, 'ContactTitle'), new System.Data.SqlClient.SqlParameter('@Address', System.Data.SqlDbType.NVarChar, 60, 'Address'), new System.Data.SqlClient.SqlParameter('@City', System.Data.SqlDbType.NVarChar, 15, 'City'), new System.Data.SqlClient.SqlParameter('@Region', System.Data.SqlDbType.NVarChar, 15, 'Region'), new System.Data.SqlClient.SqlParameter('@PostalCode', System.Data.SqlDbType.NVarChar, 10, 'PostalCode'), new System.Data.SqlClient.SqlParameter('@Country', System.Data.SqlDbType.NVarChar, 15, 'Country'), new System.Data.SqlClient.SqlParameter('@Phone', System.Data.SqlDbType.NVarChar, 24, 'Phone'), new System.Data.SqlClient.SqlParameter('@Fax', System.Data.SqlDbType.NVarChar, 24, 'Fax')])); // // sqlSelectCommand1 // self.sqlSelectCommand1.CommandText := 'SELECT CustomerID, CompanyName, ContactName, ContactTitle, Address, City, Region, PostalCode, Country, Phone, Fax FROM Customers'; self.sqlSelectCommand1.Connection := self.MySQLConnection; // // sqlUpdateCommand1 // self.sqlUpdateCommand1.CommandText := resources.GetString('sqlUpdateCommand1.CommandText'); self.sqlUpdateCommand1.Connection := self.MySQLConnection; self.sqlUpdateCommand1.Parameters.AddRange(array of System.Data.SqlClient.SqlParameter([new System.Data.SqlClient.SqlParameter('@CustomerID', System.Data.SqlDbType.NVarChar, 5, 'CustomerID'), new System.Data.SqlClient.SqlParameter('@CompanyName', System.Data.SqlDbType.NVarChar, 40, 'CompanyName'), new System.Data.SqlClient.SqlParameter('@ContactName', System.Data.SqlDbType.NVarChar, 30, 'ContactName'), new System.Data.SqlClient.SqlParameter('@ContactTitle', System.Data.SqlDbType.NVarChar, 30, 'ContactTitle'), new System.Data.SqlClient.SqlParameter('@Address', System.Data.SqlDbType.NVarChar, 60, 'Address'), new System.Data.SqlClient.SqlParameter('@City', System.Data.SqlDbType.NVarChar, 15, 'City'), new System.Data.SqlClient.SqlParameter('@Region', System.Data.SqlDbType.NVarChar, 15, 'Region'), new System.Data.SqlClient.SqlParameter('@PostalCode', System.Data.SqlDbType.NVarChar, 10, 'PostalCode'), new System.Data.SqlClient.SqlParameter('@Country', System.Data.SqlDbType.NVarChar, 15, 'Country'), new System.Data.SqlClient.SqlParameter('@Phone', System.Data.SqlDbType.NVarChar, 24, 'Phone'), new System.Data.SqlClient.SqlParameter('@Fax', System.Data.SqlDbType.NVarChar, 24, 'Fax'), new System.Data.SqlClient.SqlParameter('@Original_CustomerID', System.Data.SqlDbType.NVarChar, 5, System.Data.ParameterDirection.Input, false, (0 as System.Byte), (0 as System.Byte), 'CustomerID', System.Data.DataRowVersion.Original, nil), new System.Data.SqlClient.SqlParameter('@Original_Address', System.Data.SqlDbType.NVarChar, 60, System.Data.ParameterDirection.Input, false, (0 as System.Byte), (0 as System.Byte), 'Address', System.Data.DataRowVersion.Original, nil), new System.Data.SqlClient.SqlParameter('@Original_City', System.Data.SqlDbType.NVarChar, 15, System.Data.ParameterDirection.Input, false, (0 as System.Byte), (0 as System.Byte), 'City', System.Data.DataRowVersion.Original, nil), new System.Data.SqlClient.SqlParameter('@Original_CompanyName', System.Data.SqlDbType.NVarChar, 40, System.Data.ParameterDirection.Input, false, (0 as System.Byte), (0 as System.Byte), 'CompanyName', System.Data.DataRowVersion.Original, nil), new System.Data.SqlClient.SqlParameter('@Original_ContactName', System.Data.SqlDbType.NVarChar, 30, System.Data.ParameterDirection.Input, false, (0 as System.Byte), (0 as System.Byte), 'ContactName', System.Data.DataRowVersion.Original, nil), new System.Data.SqlClient.SqlParameter('@Original_ContactTitle', System.Data.SqlDbType.NVarChar, 30, System.Data.ParameterDirection.Input, false, (0 as System.Byte), (0 as System.Byte), 'ContactTitle', System.Data.DataRowVersion.Original, nil), new System.Data.SqlClient.SqlParameter('@Original_Country', System.Data.SqlDbType.NVarChar, 15, System.Data.ParameterDirection.Input, false, (0 as System.Byte), (0 as System.Byte), 'Country', System.Data.DataRowVersion.Original, nil), new System.Data.SqlClient.SqlParameter('@Original_Fax', System.Data.SqlDbType.NVarChar, 24, System.Data.ParameterDirection.Input, false, (0 as System.Byte), (0 as System.Byte), 'Fax', System.Data.DataRowVersion.Original, nil), new System.Data.SqlClient.SqlParameter('@Original_Phone', System.Data.SqlDbType.NVarChar, 24, System.Data.ParameterDirection.Input, false, (0 as System.Byte), (0 as System.Byte), 'Phone', System.Data.DataRowVersion.Original, nil), new System.Data.SqlClient.SqlParameter('@Original_PostalCode', System.Data.SqlDbType.NVarChar, 10, System.Data.ParameterDirection.Input, false, (0 as System.Byte), (0 as System.Byte), 'PostalCode', System.Data.DataRowVersion.Original, nil), new System.Data.SqlClient.SqlParameter('@Original_Region', System.Data.SqlDbType.NVarChar, 15, System.Data.ParameterDirection.Input, false, (0 as System.Byte), (0 as System.Byte), 'Region', System.Data.DataRowVersion.Original, nil)])); // // bSaveChanges // self.bSaveChanges.Anchor := ((System.Windows.Forms.AnchorStyles.Bottom or System.Windows.Forms.AnchorStyles.Right) as System.Windows.Forms.AnchorStyles); self.bSaveChanges.Location := new System.Drawing.Point(399, 320); self.bSaveChanges.Name := 'bSaveChanges'; self.bSaveChanges.Size := new System.Drawing.Size(137, 23); self.bSaveChanges.TabIndex := 4; self.bSaveChanges.Text := 'Save Changes'; self.bSaveChanges.Click += new System.EventHandler(@self.bSaveChanges_Click); // // MainForm // self.AutoScaleBaseSize := new System.Drawing.Size(5, 13); self.ClientSize := new System.Drawing.Size(544, 349); self.Controls.Add(self.bSaveChanges); self.Controls.Add(self.DataGrid); self.Controls.Add(self.bConnect); self.Controls.Add(self.label1); self.Controls.Add(self.tbConnectionString); self.Icon := (resources.GetObject('$this.Icon') as System.Drawing.Icon); self.MinimumSize := new System.Drawing.Size(500, 250); self.Name := 'MainForm'; self.Text := 'Oxygene ADO.NET Sample - Northwind Customer List'; (self.DataGrid as System.ComponentModel.ISupportInitialize).EndInit(); self.ResumeLayout(false); self.PerformLayout(); end; {$ENDREGION} {$REGION Application Entry Point} [STAThread] class method MainForm.Main; begin Application.EnableVisualStyles(); try with lForm := new MainForm() do Application.Run(lForm); except on E: Exception do begin MessageBox.Show(E.Message); end; end; end; {$ENDREGION} method MainForm.bConnect_Click(sender: System.Object; e: System.EventArgs); begin { Refreshes the connection string and opens the connection } if (MySQLConnection.State<>ConnectionState.Closed) then MySQLConnection.Close; MySQLConnection.ConnectionString := tbConnectionString.Text; MySQLConnection.Open; { Creates the dataset and binds it to the grid } fMyDataset := new DataSet; MySQLDataAdapter.Fill(MyDataset); DataGrid.DataSource := MyDataset.Tables['Customers']; end; method MainForm.GetCustomer : DataTable; begin result := MyDataset.Tables['Customers']; end; method MainForm.bSaveChanges_Click(sender: System.Object; e: System.EventArgs); begin { Saves the changes to the database } MySQLDataAdapter.Update(Customers); MessageBox.Show('Your changes have been saved!'); end; end.
unit uFrmInvoiceRefund; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, PaideTodosGeral, siComp, siLangRT, StdCtrls, Buttons, ExtCtrls, DB, ADODB, Mask, DBCtrls, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, cxDBData, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGrid, SuperComboADO, DBClient, Provider, mrBarCodeEdit, cxContainer, cxTextEdit, cxCurrencyEdit, clsInfoCashSale; const TYPE_INVOICE_REFUND = 0; TYPE_ITEM_REFUND = 1; type TFrmInvoiceRefund = class(TFrmParentAll) btnSave: TButton; quInvoice: TADOQuery; quInvoiceIDPreSale: TIntegerField; quInvoicePreSaleDate: TDateTimeField; quInvoiceTotInvoice: TFloatField; quInvoicePessoaFirstName: TStringField; quInvoicePessoaLastName: TStringField; quInvoiceIDTouristGroup: TIntegerField; quInvoiceOtherComissionID: TIntegerField; quInvoicePessoa: TStringField; quInvoiceSaleCode: TStringField; quInvoiceIDPessoa: TIntegerField; quInvoiceNote: TStringField; dsInvoice: TDataSource; lbInvoiceNumber: TLabel; Label19: TLabel; EditPreSaleDate: TDBEdit; lblInvoiceDate: TLabel; EditInvoiceDate: TDBEdit; Label1: TLabel; DBEdit1: TDBEdit; quInvoiceInvoiceDate: TDateTimeField; quInvoiceInvoiceCode: TStringField; DBEdit2: TDBEdit; quInvoiceQty: TFloatField; quInvoiceCostPrice: TBCDField; quInvoiceSalePrice: TBCDField; quInvoiceDiscount: TBCDField; quInvoiceModel: TStringField; quInvoiceDescription: TStringField; quInvoiceIDInventoryMov: TIntegerField; quInvoiceItemTotal: TFloatField; quInvoiceIDModel: TIntegerField; cmdItemRepair: TADOCommand; quInvoiceDateLastCost: TDateTimeField; quInvoiceLastCost: TBCDField; cdsItemRepair: TClientDataSet; dsItemRepair: TDataSource; cdsItemRepairIDModel: TIntegerField; cdsItemRepairModel: TStringField; cdsItemRepairDescription: TStringField; cdsItemRepairQty: TFloatField; cdsItemRepairCostPrice: TCurrencyField; cdsItemRepairIDVendor: TIntegerField; cdsItemRepairVendor: TStringField; cdsItemRepairIDDefectType: TIntegerField; cdsItemRepairDefectType: TStringField; cdsItemRepairObs: TStringField; cdsItemRepairID: TIntegerField; cdsItemRepairIDInventoryMov: TIntegerField; quInvoiceIDVendor: TIntegerField; quInvoiceVendor: TStringField; cdsItemRepairRA: TStringField; quInvoiceIDDepartment: TIntegerField; quInvoiceIDInvoice: TIntegerField; quItemCommission: TADODataSet; quItemCommissionIDCommission: TIntegerField; quItemCommissionCommissionPercent: TBCDField; cdsInvoice: TClientDataSet; dspInvoice: TDataSetProvider; cdsInvoiceIDPreSale: TIntegerField; cdsInvoiceIDInvoice: TIntegerField; cdsInvoicePreSaleDate: TDateTimeField; cdsInvoiceTotInvoice: TFloatField; cdsInvoicePessoaFirstName: TStringField; cdsInvoicePessoaLastName: TStringField; cdsInvoiceIDTouristGroup: TIntegerField; cdsInvoiceOtherComissionID: TIntegerField; cdsInvoicePessoa: TStringField; cdsInvoiceSaleCode: TStringField; cdsInvoiceIDPessoa: TIntegerField; cdsInvoiceNote: TStringField; cdsInvoiceInvoiceDate: TDateTimeField; cdsInvoiceInvoiceCode: TStringField; cdsInvoiceQty: TFloatField; cdsInvoiceCostPrice: TBCDField; cdsInvoiceSalePrice: TBCDField; cdsInvoiceDiscount: TBCDField; cdsInvoiceModel: TStringField; cdsInvoiceDescription: TStringField; cdsInvoiceIDInventoryMov: TIntegerField; cdsInvoiceItemTotal: TFloatField; cdsInvoiceIDModel: TIntegerField; cdsInvoiceDateLastCost: TDateTimeField; cdsInvoiceLastCost: TBCDField; cdsInvoiceIDVendor: TIntegerField; cdsInvoiceVendor: TStringField; cdsInvoiceIDDepartment: TIntegerField; quInvoiceRetorno: TBooleanField; cdsInvoiceRetorno: TBooleanField; lbBarcode: TLabel; edtBarcode: TmrBarCodeEdit; quInvoicePreInventoryMovID: TIntegerField; cdsInvoicePreInventoryMovID: TIntegerField; quInvoiceAction: TIntegerField; cdsInvoiceAction: TIntegerField; quItem: TADOQuery; quItemIDPreSale: TIntegerField; quItemIDInvoice: TIntegerField; quItemPreSaleDate: TDateTimeField; quItemInvoiceDate: TDateTimeField; quItemSaleCode: TStringField; quItemInvoiceCode: TStringField; quItemNote: TStringField; quItemPessoaFirstName: TStringField; quItemPessoaLastName: TStringField; quItemPessoa: TStringField; quItemIDPessoa: TIntegerField; quItemIDTouristGroup: TIntegerField; quItemOtherComissionID: TIntegerField; quItemIDInventoryMov: TIntegerField; quItemCostPrice: TBCDField; quItemSalePrice: TBCDField; quItemDiscount: TBCDField; quItemIDModel: TIntegerField; quItemModel: TStringField; quItemDescription: TStringField; quItemDateLastCost: TDateTimeField; quItemLastCost: TBCDField; quItemIDVendor: TIntegerField; quItemVendor: TStringField; quItemIDDepartment: TIntegerField; quItemRetorno: TBooleanField; quItemPreInventoryMovID: TIntegerField; quItemAction: TIntegerField; dspItem: TDataSetProvider; quItemTotInvoice: TFloatField; quItemItemTotal: TFloatField; quItemQty: TFloatField; pnlDetail: TPanel; pnlInvoiceItems: TPanel; Panel4: TPanel; grdInvoiceItems: TcxGrid; grdInvoiceItemsDB: TcxGridDBTableView; grdInvoiceItemsDBAction: TcxGridDBColumn; grdInvoiceItemsDBRetorna: TcxGridDBColumn; grdInvoiceItemsDBModel: TcxGridDBColumn; grdInvoiceItemsDBDescription: TcxGridDBColumn; grdInvoiceItemsDBQty: TcxGridDBColumn; grdInvoiceItemsDBCostPrice: TcxGridDBColumn; grdInvoiceItemsDBSalePrice: TcxGridDBColumn; grdInvoiceItemsDBDiscount: TcxGridDBColumn; grdInvoiceItemsDBItemTotal: TcxGridDBColumn; grdInvoiceItemsLevel: TcxGridLevel; Panel6: TPanel; pnlModelConfig: TPanel; pnlRepair: TPanel; grdItemRepair: TcxGrid; grdItemRepairDB: TcxGridDBTableView; grdItemRepairDBModel: TcxGridDBColumn; grdItemRepairDBDescription: TcxGridDBColumn; grdItemRepairDBQty: TcxGridDBColumn; grdItemRepairDBCostPrice: TcxGridDBColumn; grdItemRepairDBIDVendor: TcxGridDBColumn; grdItemRepairDBRA: TcxGridDBColumn; grdItemRepairDBIDDefectType: TcxGridDBColumn; grdItemRepairDBObs: TcxGridDBColumn; grdItemRepairLevel: TcxGridLevel; pnlUpdate: TPanel; Label3: TLabel; lbDefeito: TLabel; scDefectType: TSuperComboADO; scVendor: TSuperComboADO; edtRA: TEdit; lbRA: TLabel; Label4: TLabel; memOBS: TMemo; btnUpdate: TBitBtn; btnRemove: TBitBtn; Panel2: TPanel; Shape5: TShape; Label37: TLabel; Label38: TLabel; Label39: TLabel; Label40: TLabel; Label41: TLabel; dbedTax: TDBEdit; dbedOtherCost: TDBEdit; dbedSaleDiscount: TDBEdit; dbedItemDiscount: TDBEdit; dbedSubTotal: TDBEdit; lblItemDiscountSign: TLabel; lblSaleDiscountSign: TLabel; pnlSaleDiscount: TPanel; Shape1: TShape; Label2: TLabel; pnlRefund: TPanel; btnCalcRefund: TBitBtn; pnlTotalRefund: TPanel; lblRefund: TLabel; curreditRefund: TcxCurrencyEdit; quInvoiceSalesTax: TBCDField; cdsInvoiceSalesTax: TBCDField; quItemSalesTax: TBCDField; quInvoiceTaxIsent: TBooleanField; cdsInvoiceTaxIsent: TBooleanField; quInvoiceUnitDiscount: TBCDField; cdsInvoiceUnitDiscount: TBCDField; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure quInvoiceAfterOpen(DataSet: TDataSet); procedure btnSaveClick(Sender: TObject); procedure btCloseClick(Sender: TObject); procedure btnUpdateClick(Sender: TObject); procedure cdsInvoiceQtyChange(Sender: TField); procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); procedure edtBarcodeAfterSearchBarcode(Sender: TObject); procedure grdInvoiceItemsDBActionPropertiesEditValueChanged( Sender: TObject); procedure quItemAfterOpen(DataSet: TDataSet); procedure btnRemoveClick(Sender: TObject); procedure grdInvoiceItemsDBRetornaPropertiesEditValueChanged( Sender: TObject); //amfsouza June 20, 2012 - Calculate Refund procedure btnCalcRefundClick(Sender: TObject); private // Antonio 2013 Oct 22 - MR-37 cloneToGetOriginalData: TClientDataset; // Antonio June 13, 2013 saveRefundOriginalQty: double; //amfsouza October 08, 2012 - Item without invoice. selectedItemNoInvoice: Boolean; saleLevelDiscount: Currency; totalOnSale: Currency; totalValueItemsSelected: Currency; totalTaxSelected: Currency; infoCashSale: InfoCashSale; useCashSaleInfo: boolean; giveTotalCaption : String; giveNotTotalCaption: String; giveBackCaption: String; sActionRetrunSelf, sActionReturnVendor : String; FStartType : Integer; FExecuted : Boolean; FIDPreSale : Integer; FInvoiceRefund : String; FIDPreInvMov : Integer; fDepartment: Integer; function getValueIfIsLookTheSame(arg_number1, arg_number2: double): double; // Antonio June 20, 2013 function getDiscountToEachItem(arg_invoice: TClientDataset): double; function findInfoCashSale(pInvoiceNumber: Integer): boolean; //amfsouza October, 08 2012 - Hide/Show procedure HideShowToNotInvoiceItem(pVisible: Boolean = false); //amfouza July 13, 2012 procedure ShowRefund(pShowRefund: boolean = true); procedure AddTotalItemsSelected(pValue: Currency); procedure AddTotalTaxSelected(pValue: Currency); procedure OpenInvoice; procedure CloseInvoice; procedure RefreshInvoice; procedure CreateItemRepair(IDPreInvMov : Integer); function AddInvoiceRefund : Boolean; function ValidateRepair : Boolean; function VerifyInvoiceQty: Boolean; procedure AddItemRepair; procedure OpenVendor; procedure CloseVendor; procedure OpenDefect; procedure CloseDefect; public //amfsouza June 16, 2012: added objInfoCashSale parameter function Start(IDPreSale : Integer; InvoiceRefund : String; var AIDRefund: Integer; var ARefundDate : TDateTime; pInfoCashSale: InfoCashSale = nil) : Integer; function StartItem(arg_IdPreInventoryMov : Integer; arg_InfoCashSale: InfoCashSale = nil) : Boolean; function getIdRefund: Integer; function getRefundDate: TDateTime; end; implementation uses uDM, uDMGlobal, uSystemConst, uMsgBox, uMsgConstant, cxImageComboBox, uNumericFunctions; {$R *.dfm} { TFrmInvoiceRefund } function TFrmInvoiceRefund.StartItem(arg_IdPreInventoryMov : Integer; arg_InfoCashSale: InfoCashSale = nil) : Boolean; begin FIDPreInvMov := arg_IdPreInventoryMov; FStartType := TYPE_ITEM_REFUND; cdsInvoice.ProviderName := 'dspItem'; RefreshInvoice; // amfsouza June 16, 2012 - ini useCashSaleInfo := false; pnlSaleDiscount.Visible := useCashSaleInfo; infoCashSale := arg_InfoCashSale; if ( not findInfoCashSale(cdsInvoice.fieldByName('IdPreSale').Value) ) then begin result := false; close; end; dbedSubTotal.Text := FloatToStrF(infoCashSale.getSubtotal, ffNumber, 13, 2); dbedItemDiscount.Text := floatToStrF(infoCashSale.getItemDiscounts, ffNumber, 13, 2); dbedSaleDiscount.Text := floatToStrF(infoCashSale.getSaleDiscount, ffNumber, 13, 2); dbedOtherCost.Text := floatToStrF(infoCashSale.getOtherCosts, ffNumber, 13, 2); dbedTax.Text := floatToStrF(infoCashSale.getTax, ffNumber, 13, 2); if ( infoCashSale.getSaleDiscount > 0 ) then begin pnlSaleDiscount.visible := ( infoCashSale.getSaleDiscount > 0 ); useCashSaleInfo := true; end; // amfsouza June 16, 2012 - end scDefectType.ShowBtnUpdate := (DM.fUser.IDUserType = USER_TYPE_ADMINISTRATOR); scDefectType.ShowBtnAddNew := (DM.fUser.IDUserType = USER_TYPE_ADMINISTRATOR); ShowModal; //AIDRefund := cdsInvoice.fieldbyname('IDPreSale').AsInteger; //ARefundDate := cdsInvoice.fieldByname('InvoiceDate').AsDateTime; AddItemRepair; pnlInvoiceItems.Visible := False; edtBarcode.Visible := False; lbBarcode.Visible := False; DBEdit1.DataField := 'SaleCode'; //amfsouza October 08, 2012 HideShowToNotInvoiceItem(); ShowModal; Result := FExecuted; end; function TFrmInvoiceRefund.Start(IDPreSale: Integer; InvoiceRefund: String; var AIDRefund: Integer; var ARefundDate : TDateTime; pInfoCashSale: InfoCashSale): Integer; begin // amfsouza June 16, 2012 - ini useCashSaleInfo := false; pnlSaleDiscount.Visible := useCashSaleInfo; infoCashSale := pInfoCashSale; if ( not findInfoCashSale(strToInt(InvoiceRefund)) ) then begin close; exit; end; dbedSubTotal.Text := FloatToStrF(infoCashSale.getSubtotal, ffNumber, 13, 2); dbedItemDiscount.Text := floatToStrF(infoCashSale.getItemDiscounts, ffNumber, 13, 2); dbedSaleDiscount.Text := floatToStrF(infoCashSale.getSaleDiscount, ffNumber, 13, 2); dbedOtherCost.Text := floatToStrF(infoCashSale.getOtherCosts, ffNumber, 13, 2); dbedTax.Text := floatToStrF(infoCashSale.getTax, ffNumber, 13, 2); if ( infoCashSale.getSaleDiscount > 0 ) then begin pnlSaleDiscount.visible := ( infoCashSale.getSaleDiscount > 0 ); useCashSaleInfo := true; end; // amfsouza June 16, 2012 - end FStartType := TYPE_INVOICE_REFUND; FIDPreSale := IDPreSale; FInvoiceRefund := InvoiceRefund; scDefectType.ShowBtnUpdate := (DM.fUser.IDUserType = USER_TYPE_ADMINISTRATOR); scDefectType.ShowBtnAddNew := (DM.fUser.IDUserType = USER_TYPE_ADMINISTRATOR); cdsInvoice.ProviderName := 'dspInvoice'; RefreshInvoice; //amfsouza October 08, 2012 selectedItemNoInvoice := false; cloneToGetOriginalData := TClientDataset.Create(nil); cloneToGetOriginalData.Data := cdsInvoice.Data; // saveRefundOriginalQty := cdsInvoice.fieldByName('qty').Value; ShowModal; AIDRefund := cdsInvoice.fieldbyname('IDPreSale').AsInteger; ARefundDate := cdsInvoice.fieldByname('InvoiceDate').AsDateTime; if not FExecuted then Result := 0 else Result := 1; end; procedure TFrmInvoiceRefund.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; CloseVendor; CloseDefect; // Antonio 2013 Oct 22, MR-37 freeAndNil(cloneToGetOriginalData); Action := caFree; end; procedure TFrmInvoiceRefund.CloseInvoice; begin with cdsInvoice do if Active then Close; end; procedure TFrmInvoiceRefund.OpenInvoice; var saveSQLFromquInvoiceDesignTime: String; begin saveSQLFromquInvoiceDesignTime := quInvoice.SQL.Text; with cdsInvoice do if not Active then begin FetchParams; if FStartType = TYPE_INVOICE_REFUND then begin Params.ParamByName('Invoice').Value := FInvoiceRefund; Params.ParamByName('IDStore').Value := DM.fStore.ID; end else Params.ParamByName('IDPreInventoryMov').Value := FIDPreInvMov; Open; totalOnSale := 0; while ( not cdsInvoice.Eof ) do begin totalOnSale := totalOnSale + cdsInvoice.fieldByName('ItemTotal').Value; cdsInvoice.Next; end; end; end; procedure TFrmInvoiceRefund.RefreshInvoice; begin CloseInvoice; OpenInvoice; end; procedure TFrmInvoiceRefund.quInvoiceAfterOpen(DataSet: TDataSet); begin inherited; btnSave.Enabled := (quInvoice.RecordCount > 0); { //amfsouza June 16, 2012 rdbGiveTotal.Caption := format(giveTotalCaption, [self.infoCashSale.getTotalDue]); rdbNotGiveTotal.Caption := format(giveNotTotalCaption, [(self.infoCashSale.getTotalDue - self.infoCashSale.getSaleDiscount)]); curredtRefund.Text := floatToStrF(self.infoCashSale.getTotalDue, ffNumber, 13, 2); } TNumericField(dataset.FieldByName('ItemTotal')).DisplayFormat := '#,##0.00'; end; function TFrmInvoiceRefund.AddInvoiceRefund : Boolean; var iError, iIDPreInventMov, iID : Integer; discount: Double; _UnitDiscount: Double; // _ stands to local variable ( on stack ) begin Result := False; if not cdsItemRepair.IsEmpty then if not ValidateRepair then Exit; try DM.ADODBConnect.BeginTrans; // update invoice table to save invoice discount // showmessage(format('idpresale = %d, sale discount = %f', [fidpresale, infocashsale.getSaleDiscount])); dm.updateInvoiceSettingInvoiceDiscount(fIdpresale, (infoCashSale.getSaleDiscount * -1 )); with cdsInvoice do begin try DisableControls; First; while not EOF do begin if (FStartType = TYPE_INVOICE_REFUND) and cdsInvoice.fieldbyname('Retorno').Value then begin if cdsInvoice.fieldByName('Qty').Value > 0 then begin // Antonio June 20, 2013 discount := getDiscountToEachItem(cdsInvoice); // Antonio 09/09/2016 _unitDiscount := cdsInvoice.fieldByName('UnitDiscount').value; // To indicate refund movement iIDPreinventMov := -1; DM.fPOS.AddHoldItem(cdsInvoice.fieldByName('IDPessoa').AsInteger, FIDPresale, cdsInvoice.fieldbyname('IDModel').AsInteger, DM.fStore.IDStoreSale, (cdsInvoice.fieldbyname('Qty').AsFloat * -1), 0, cdsInvoice.fieldbyname('SalePrice').AsCurrency, cdsInvoice.fieldbyname('CostPrice').AsCurrency, DM.fUser.ID, DM.fUser.IDCommission, Now, Now, False, True, 0, //cdsInvoice.fieldbyname('PreInventoryMovID').Value, cdsInvoice.fieldbyname('IDDepartment').AsInteger, iError, iIDPreInventMov, 0, false, 0, 0, 0, '', 0, 0, _unitDiscount, // unit discount True, cdsInvoice.fieldbyname('SalePrice').AsCurrency, // manual price discount, 0, false, True); //Add Hold Commission try if quItemCommission.Active then quItemCommission.Close; quItemCommission.Parameters.ParamByName('IDInventoryMov').Value := cdsInvoice.fieldbyname('IDInventoryMov').AsInteger; quItemCommission.Open; if not quItemCommission.IsEmpty then begin DM.RunSQL('DELETE FROM SaleItemCommission WHERE IDPreInventoryMov = ' + InttoStr(iIDPreInventMov) ); quItemCommission.First; while not quItemCommission.Eof do begin DM.fPOS.AddItemCommission('NULL', IntToStr(iIDPreInventMov), quItemCommissionIDCommission.AsInteger, quItemCommissionCommissionPercent.AsFloat); quItemCommission.Next; end; end; finally quItemCommission.Close; end; end else begin MsgBox(MSG_INF_QTY_MUST_BIGGER_ZERO, vbCritical + vbOkOnly); DM.ADODBConnect.RollbackTrans; Exit; end; end; //Enviar para reparo if cdsItemRepair.Active and (not cdsItemRepair.IsEmpty) then if cdsItemRepair.Locate('ID', cdsInvoice.fieldbyname('PreInventoryMovID').AsInteger,[]) then begin if (FStartType <> TYPE_INVOICE_REFUND) then iIDPreInventMov := cdsItemRepairID.AsInteger; with cmdItemRepair do begin Parameters.ParamByName('IDItemRepair').Value := DM.GetNextID(MR_DEFECT_TYPE_ID); Parameters.ParamByName('IDPreInventoryMov').Value := iIDPreInventMov; Parameters.ParamByName('Obs').Value := cdsItemRepairObs.AsString; Parameters.ParamByName('IDDefectType').Value := cdsItemRepairIDDefectType.AsInteger; Parameters.ParamByName('RA').Value := cdsItemRepairRA.AsString; Parameters.ParamByName('IDVendor').Value := cdsItemRepairIDVendor.AsInteger; Execute; end; end; Next; end; finally // CalculateRefundByOption(cboDiscountType.ItemIndex, curredtRefund.Value); EnableControls; end; end; DM.ADODBConnect.CommitTrans; except DM.ADODBConnect.RollbackTrans; MsgBox(MSG_INF_ERROR, vbOKOnly + vbInformation); end; Result := True; end; procedure TFrmInvoiceRefund.btnSaveClick(Sender: TObject); begin inherited; //Antonio June 19, 2013, 2012 if ( not selectedItemNoInvoice ) then begin ShowRefund(false); infoCashSale.setSaleDiscount(saleLevelDiscount); end; if AddInvoiceRefund then begin FExecuted := True; Close; end; end; procedure TFrmInvoiceRefund.btCloseClick(Sender: TObject); begin inherited; FExecuted := False; infoCashSale.setNewTotalDue(0); infoCashSale.setNewTotalSaved(0); infoCashSale.setSubtotal(0); infocashsale.setItemDiscounts(0); infocashSale.setSaleDiscount(0); infoCashSale.setOtherCosts(0); infocashSale.setTax(0); infoCashSale.setTotalDue(0); infoCashSale.setTotalSaved(0); end; function TFrmInvoiceRefund.ValidateRepair: Boolean; begin Result := False; with cdsItemRepair do begin if not Active then Exit; try DisableControls; First; while not EOF do begin if FieldByName('IDVendor').AsInteger = 0 then begin Result := False; MsgBox(MSG_CRT_NO_VENDOR, vbOKOnly + vbInformation); Exit; end; if FieldByName('IDdefectType').AsInteger = 0 then begin Result := False; MsgBox(MSG_CRT_NO_EMPTY_DEFECT, vbOKOnly + vbInformation); Exit; end; Next; end; finally EnableControls; end; end; Result := True; end; procedure TFrmInvoiceRefund.CreateItemRepair(IDPreInvMov : Integer); begin with cdsItemRepair do begin if not Active then CreateDataSet; if not Locate('ID', IDPreInvMov, []) then if cdsInvoice.fieldbyname('Retorno').Value then begin Append; FieldByName('ID').AsInteger := IDPreInvMov; FieldByName('IDModel').AsInteger := cdsInvoice.fieldbyname('IDModel').AsInteger; FieldByName('IDInventoryMov').AsInteger := cdsInvoice.fieldbyname('IDInventoryMov').AsInteger; FieldByName('IDVendor').AsInteger := cdsInvoice.fieldbyname('IDVendor').AsInteger; FieldByName('Vendor').AsString := cdsInvoice.fieldbyname('Vendor').AsString; FieldByName('Model').AsString := cdsInvoice.fieldbyname('Model').AsString; FieldByName('Description').AsString := cdsInvoice.fieldbyname('Description').AsString; FieldByName('Qty').AsFloat := Abs(cdsInvoice.fieldbyname('Qty').AsFloat); FieldByName('CostPrice').AsCurrency := cdsInvoice.fieldbyname('CostPrice').AsCurrency; Post; end; end; end; procedure TFrmInvoiceRefund.btnUpdateClick(Sender: TObject); begin inherited; with cdsItemRepair do if Active and (not IsEmpty) then begin Edit; if scVendor.LookUpValue <> '' then begin FieldByName('IDVendor').AsInteger := StrToInt(scVendor.LookUpValue); FieldByName('Vendor').AsString := scVendor.Text; end; if scDefectType.LookUpValue <> '' then begin FieldByName('IDDefectType').AsInteger := StrToInt(scDefectType.LookUpValue); FieldByName('DefectType').AsString := scDefectType.Text; end; if edtRA.Text <> '' then FieldByName('RA').AsString := edtRA.Text; if memOBS.Text <> '' then FieldByName('Obs').AsString := memOBS.Text; Post; end; end; procedure TFrmInvoiceRefund.cdsInvoiceQtyChange(Sender: TField); begin inherited; if cdsInvoice.FieldByName('Qty').Value > cdsInvoice.FieldByName('Qty').OldValue then begin MsgBox(MSG_INF_WRONG_QTY, vbCritical + vbOKOnly); cdsInvoice.Cancel; end; end; procedure TFrmInvoiceRefund.FormShow(Sender: TObject); begin inherited; if edtBarcode.CanFocus then edtBarcode.SetFocus; OpenVendor; OpenDefect; end; procedure TFrmInvoiceRefund.FormCreate(Sender: TObject); begin inherited; edtBarcode.CheckBarcodeDigit := DM.fSystem.SrvParam[PARAM_REMOVE_BARCODE_DIGIT]; edtBarcode.MinimalDigits := DM.fSystem.SrvParam[PARAM_MIN_BARCODE_LENGTH]; edtBarcode.RunSecondSQL := DM.fSystem.SrvParam[PARAM_SEARCH_MODEL_AFTER_BARCODE]; case DMGlobal.IDLanguage of LANG_ENGLISH : begin sActionRetrunSelf := 'Return to shelf'; sActionReturnVendor := 'Return to vendor'; end; LANG_PORTUGUESE : begin sActionRetrunSelf := 'Retornar para revender'; sActionReturnVendor := 'Retornar para fornecedor'; end; LANG_SPANISH : begin sActionRetrunSelf := 'Regresa a la tienda'; sActionReturnVendor := 'Volver al Distribuidor'; end; end; TcxImageComboBoxProperties(grdInvoiceItemsDBAction.Properties).Items[0].Description := sActionRetrunSelf; TcxImageComboBoxProperties(grdInvoiceItemsDBAction.Properties).Items[1].Description := sActionReturnVendor; giveTotalCaption := 'Refund Less Discount %n Back'; giveNotTotalCaption := 'Refund With Discount give %n Back'; giveBackCaption := 'Refund Less'; end; procedure TFrmInvoiceRefund.edtBarcodeAfterSearchBarcode(Sender: TObject); var IDModel: Integer; bFound: Boolean; begin inherited; with edtBarcode do begin if SearchResult then begin bFound := False; IDModel := GetFieldValue('IDModel'); cdsInvoice.First; while not cdsInvoice.Eof do begin if (IDModel = cdsInvoice.fieldbyname('IDModel').Value) and (not cdsInvoice.fieldbyname('Retorno').Value) then begin cdsInvoice.Edit; cdsInvoice.fieldbyname('Retorno').Value := True; cdsInvoice.Post; bFound := True; Break; end; cdsInvoice.Next; end; if not bFound then MsgBox(MSG_CRT_NO_BARCODE, vbCritical + vbOkOnly); end else MsgBox(MSG_CRT_NO_BARCODE, vbCritical + vbOkOnly); end; edtBarcode.Clear; end; function TFrmInvoiceRefund.VerifyInvoiceQty: Boolean; begin Result := True; with cdsInvoice do if FieldByName('Retorno').AsBoolean then Result := (FieldByName('Qty').AsFloat > 0); end; procedure TFrmInvoiceRefund.grdInvoiceItemsDBActionPropertiesEditValueChanged( Sender: TObject); begin inherited; cdsInvoice.Edit; cdsInvoice.fieldbyname('Retorno').AsBoolean := True; if not VerifyInvoiceQty then begin MsgBox(MSG_INF_QTY_MUST_BIGGER_ZERO, vbCritical + vbOkOnly); Exit; end; CreateItemRepair(cdsInvoice.fieldbyname('PreInventoryMovID').AsInteger); end; procedure TFrmInvoiceRefund.quItemAfterOpen(DataSet: TDataSet); begin inherited; btnSave.Enabled := (quItem.RecordCount > 0); end; procedure TFrmInvoiceRefund.btnRemoveClick(Sender: TObject); begin inherited; with cdsItemRepair do if Active and (not IsEmpty) then begin Edit; Delete; end; end; procedure TFrmInvoiceRefund.AddItemRepair; begin with cdsInvoice do if Active and (not IsEmpty) then begin Edit; cdsInvoice.FieldByName('Action').AsInteger := 1; cdsInvoice.fieldbyname('Retorno').AsBoolean := True; Post; CreateItemRepair(FIDPreInvMov); end; end; procedure TFrmInvoiceRefund.CloseVendor; begin DM.LookUpFornecedor.Close; end; procedure TFrmInvoiceRefund.OpenVendor; begin DM.LookUpFornecedor.Open; end; procedure TFrmInvoiceRefund.CloseDefect; begin DM.LookUpDefectType.Close; end; procedure TFrmInvoiceRefund.OpenDefect; begin DM.LookUpDefectType.Open; end; function TFrmInvoiceRefund.findInfoCashSale(pInvoiceNumber: Integer): Boolean; var qry: TADOQuery; totalDue: Currency; totalDiscount: Currency; begin try result := false; try qry := TADOQuery.Create(nil); qry.Connection := dm.ADODBConnect; qry.sql.add('select SubTotal, ItemDiscount, InvoiceDiscount, '); qry.sql.add(' AditionalExpenses, Tax, TotalDiscount'); qry.sql.add('from Invoice where InvoiceCode = :invoicecode'); qry.Parameters.ParamByName('invoicecode').Value := pInvoiceNumber; qry.Open; totalDue := 0; if ( not qry.IsEmpty ) then begin infoCashSale.setSubtotal(qry.fieldByName('SubTotal').Value); infoCashSale.setItemDiscounts(qry.fieldByName('ItemDiscount').Value); infoCashSale.setSaleDiscount(qry.fieldByName('InvoiceDiscount').Value); infoCashSale.setOtherCosts(qry.fieldByName('AditionalExpenses').Value); infoCashSale.setTax(qry.fieldByName('Tax').Value); if ( qry.FieldByName('TotalDiscount').IsNull ) then begin totalDiscount := 0; end else begin totalDiscount := qry.fieldByName('TotalDiscount').Value; end; infoCashSale.setTotalSaved(totalDiscount); totalDue := qry.fieldByName('SubTotal').Value - (qry.fieldByName('ItemDiscount').Value + qry.fieldByName('InvoiceDiscount').Value) + qry.fieldByName('AditionalExpenses').Value + qry.fieldByName('Tax').Value; infoCashSale.setTotalDue(totalDue); result := true; end else begin application.messageBox('Invoice Not Found', 'Refund', mb_OK + mb_IconStop); end; except on e: Exception do raise Exception.Create('select error in Invoice: ' + e.Message); end; finally freeAndNil(qry); end; end; procedure TFrmInvoiceRefund.AddTotalItemsSelected(pValue: Currency); begin totalValueItemsSelected := totalValueItemsSelected + pValue; end; procedure TFrmInvoiceRefund.grdInvoiceItemsDBRetornaPropertiesEditValueChanged( Sender: TObject); var return: boolean; begin inherited; pnlTotalRefund.Visible := false; end; procedure TFrmInvoiceRefund.btnCalcRefundClick(Sender: TObject); begin ShowRefund(true); end; procedure TFrmInvoiceRefund.AddTotalTaxSelected(pValue: Currency); begin totalTaxSelected := totalTaxSelected + pValue; end; procedure TFrmInvoiceRefund.ShowRefund(pShowRefund: boolean = true); var return: boolean; hasSelected: boolean; taxSelected: Currency; totalSaleItem: Currency; totalItemDiscountInRefund: Currency; discount: Double; begin inherited; curreditRefund.Value := 0; totalValueItemsSelected := 0; totalTaxSelected := 0; saleLevelDiscount := 0; totalItemDiscountInRefund := 0; hasSelected := false; discount := 0; cdsInvoice.First; while ( not cdsInvoice.Eof ) do begin return := cdsInvoice.FieldByName('retorno').AsBoolean; if ( return) then begin // Antonio June 20, 2013 discount := getDiscountToEachItem(cdsInvoice); totalItemDiscountInRefund := totalItemDiscountInRefund + discount; totalSaleItem := ( cdsInvoice.fieldByName('SalePrice').Value * cdsInvoice.fieldByName('Qty').Value ) - discount; AddTotalItemsSelected(totalSaleItem); taxSelected := ( (cdsInvoice.fieldByName('SalePrice').Value * cdsInvoice.fieldByName('Qty').Value) - discount) * cdsInvoice.fieldByName('SalesTax').Value; AddTotalTaxSelected(taxSelected); hasSelected := true; end; cdsInvoice.Next; end; if ( hasSelected ) then begin saleLevelDiscount := infoCashSale.getSaleDiscount * (totalValueItemsSelected) / totalOnSale; // to fix refund when there is tax exempt on invoice if ( dsInvoice.dataset.fieldbyname('TaxIsent').AsBoolean = true ) then begin totalTaxSelected := 0; end; curreditRefund.Value := ((-1)* totalValueItemsSelected ) + saleLevelDiscount - (totalTaxSelected); currEditRefund.value := getValueIfIsLookTheSame(dsInvoice.dataset.fieldByName('TotInvoice').Value, curreditRefund.value); // Antonio 2013 Nov 01, MR-86 totalItemDiscountInRefund := getValueIfisLookTheSame(strToFloat(dbedItemDiscount.Text), totalItemDiscountInRefund); // Antonio 2013 Oct 29, MR-83 //totalItemDiscountInRefund := strToFloat(dbedItemDiscount.Text); infoCashSale.setItemDiscounts(TotalItemdiscountInRefund); //showmessage(format('sale discount = %.2f * total value items selected = %.2f / total on sale = %.2f', [infoCashSale.getSaleDiscount, totalValueItemsSelected, currEditRefund.Value] )); if ( pShowRefund ) then pnlTotalRefund.Visible := true; end; end; procedure TFrmInvoiceRefund.HideShowToNotInvoiceItem(pVisible: Boolean); begin panel2.Visible := pvisible; shape1.Visible := panel2.Visible; label2.Visible := panel2.Visible; pnlRefund.Visible := shape1.visible; selectedItemNoInvoice := true; end; function TFrmInvoiceRefund.getIdRefund: Integer; begin result := cdsInvoice.fieldByName('IdRefund').Value; end; function TFrmInvoiceRefund.getRefundDate: TDateTime; begin result := cdsInvoice.fieldByname('InvoiceDate').AsDateTime; end; function TFrmInvoiceRefund.getDiscountToEachItem(arg_invoice: TClientDataset): double; var originalQtyFromInvoice: Integer; begin // Antonio 2013 Oct 22, MR-37 originalQtyFromInvoice := 1; // default to avoid exception cloneToGetOriginalData.Filter := format('IdInventoryMov = %d', [arg_invoice.FieldByName('IdInventoryMov').AsInteger]); cloneToGetOriginalData.Filtered := true; if ( not cloneToGetOriginalData.IsEmpty ) then begin originalQtyFromInvoice := cloneToGetOriginalData.fieldByname('Qty').Value; end; if ( originalQtyFromInvoice > 0 ) then begin result := ( arg_invoice.fieldByName('Discount').Value /originalQtyFromInvoice ) * arg_Invoice.fieldByName('Qty').Value; end; end; function TFrmInvoiceRefund.getValueIfIsLookTheSame(arg_number1, arg_number2: double): double; const ref = 1000000; verySmallNumber = 1/ref; var proportionalDiff: Double; begin proportionalDiff := abs( (abs(arg_number2) - abs(arg_number1)) / ref ); if ( proportionalDiff < verySmallNumber ) then arg_number2 := arg_number1; result := arg_number2; end; end.
unit uFrmImportTransferNumber; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, PaideTodosGeral, siComp, siLangRT, StdCtrls, Buttons, ExtCtrls, DB, ADODB, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, cxDBData, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGrid; type TFrmImportTransferNumber = class(TFrmParentAll) Label1: TLabel; edtTransferNum: TEdit; btnSave: TButton; quTransfer: TADODataSet; quTransferIDModelTransf: TIntegerField; quTransferImported: TBooleanField; grdTransfers: TcxGrid; grdTransfersDB: TcxGridDBTableView; grdTransfersLevel: TcxGridLevel; dsTransfer: TDataSource; quTransferData: TDateTimeField; quTransferSystemUser: TStringField; quTransferStoreOrigem: TStringField; quTransferStoreDestino: TStringField; quTransferNumber: TStringField; grdTransfersDBData: TcxGridDBColumn; grdTransfersDBStoreOrigem: TcxGridDBColumn; grdTransfersDBStoreDestino: TcxGridDBColumn; grdTransfersDBNumber: TcxGridDBColumn; btnSearch: TBitBtn; procedure btnSaveClick(Sender: TObject); procedure btCloseClick(Sender: TObject); procedure btnSearchClick(Sender: TObject); procedure edtTransferNumChange(Sender: TObject); private FIDTranfer : Integer; function ValidateTransfer:Boolean; procedure RefreshTransfers; public function Start(var IDTransfer : Integer):Boolean; end; implementation uses uDM, uMsgBox, uMsgConstant; {$R *.dfm} { TFrmImportTransferNumber } function TFrmImportTransferNumber.Start(var IDTransfer: Integer): Boolean; begin FIDTranfer := -1; ShowModal; IDTransfer := FIDTranfer; Result := (FIDTranfer<>-1); end; function TFrmImportTransferNumber.ValidateTransfer: Boolean; begin Result := True; if Trim(edtTransferNum.Text) = '' then begin MsgBox(MSG_INF_NOT_VALID_TRANFER_NUM, vbOKOnly + vbCritical); Result := False; Exit; end; with quTransfer do begin Try if IsEmpty then FIDTranfer := -1 else FIDTranfer := quTransferIDModelTransf.AsInteger; if FIDTranfer = -1 then begin MsgBox(MSG_INF_NOT_FOUND_TRANFER_NUM, vbOKOnly + vbCritical); edtTransferNum.SelectAll; FIDTranfer := -1; Result := False; end else if (FieldByName('Imported').AsBoolean) then begin MsgBox(MSG_INF_TRANF_ALREADY_IMPORTED, vbOKOnly + vbCritical); edtTransferNum.SelectAll; FIDTranfer := -1; Result := False; end; finally if Result then Close; end; end; end; procedure TFrmImportTransferNumber.btnSaveClick(Sender: TObject); begin inherited; if ValidateTransfer then Close; end; procedure TFrmImportTransferNumber.btCloseClick(Sender: TObject); begin inherited; Close; end; procedure TFrmImportTransferNumber.RefreshTransfers; begin with quTransfer do begin if Active then Close; Parameters.ParamByName('Number').Value := edtTransferNum.Text; Open; end; end; procedure TFrmImportTransferNumber.btnSearchClick(Sender: TObject); begin inherited; RefreshTransfers; btnSearch.Default := False; btnSave.Default := True; end; procedure TFrmImportTransferNumber.edtTransferNumChange(Sender: TObject); begin inherited; btnSearch.Default := True; btnSave.Default := False; end; end.