text
stringlengths
14
6.51M
unit RazMain; interface uses Math, DateUtils, StdRut, SysUtils, RazProbemBase, RazProbem ; type TOsebaIdx0 = 0..MxOseb ; TOsebeNaDMIEl = record last: 0..MxOsebNaDMI ; list: array[1..MxOsebNaDMI] of TDMI ; // seznam oseb, ki lahko delajo na nekem DMI pMest: smallint; // stevilo prostih mest tega DMI/dne end ; TOsebeNaDMI = array[0..MxDMI, TDanIdx] of TOsebeNaDMIEl ; // osebe, ki lahko delajo na nekem DMI, dne TVrstniRedVzorcev = array[1..MxOseb] of TSmIntRealPairArray ; TRazSolve = class(TRazProblem) private store: TObject ; // store je class TDMIValsStore OsebeNaDmi: TOsebeNaDMI ; // OsebeNaDMI[dmi,o] so vse osebe, ki lahko delajo na dmi, dne d oceneOseb: TSmIntRealPairArray ; mozniDMI: TSmIntRealPairArray ; nProstihMest, nMoznihOseb: TDanVzorecInt ; vrVzorcevGlob: TVrstniRedVzorcev ; poDanSkupinah: boolean ; tmposebe: array[TOsebaIdx] of TOseba ; iter, varMark: Cardinal ; function osebaNaDMI( dmi: TDMI ; d: TDanIdx ; o: TOsebaIdx ) : boolean ; // vrne true ce je oseba o v OsebeNaDMI[dmi,d].list function DelOsebaNaDMI( dmi: TDMI ; d: TDanIdx ; o: TOsebaIdx ) : boolean ; function skupDelMin( min: smallint ): smallint ; function skupDelDni( d: smallint ): smallint ; function initOsebeNaDMI2( var oList: TOsebeList; lIdx: TOsebaIdx; d: TDanIdx ): boolean ; function preveriVzorec( d: TDanIdx; o: TOsebaIdx; vv: TVrstaVzorca ): boolean ; procedure undoPribijDMIVal ; function propPribijDMIVal( dmi: TDMI; d: TDanIdx; o: TOsebaIdx ): boolean ; function propReduceDMIVal( dmi: TDMI; d: TDanIdx; o: TOsebaIdx ): boolean ; function propReduceKritNOk( d: TDanIdx; o: TOsebaIdx ): boolean ; // zbrise iz DMIVals[d,o] vse dmi ki krsijo kriterije in propagira spremembe s propReduceDMIVal function mozniDMIVzorca(vvDMI: TVrstaVzorca; d: TDanIdx; o: TOsebaIdx; var mDMI: TSmallIntArray) : boolean ; function dolociMestaVzorca(var oList: TOsebeList; fIdx, lIdx: TOsebaIdx; d: TDanIdx): boolean ; function oceniVzorceOsebe(o: TOsebaIdx; d: TDanIdx; vrVzorcev: TVrstniRedVzorcev ): smallint ; function canInsertDMI(d: TDanIdx; o: TOsebaIdx; dmi: TDMI ): boolean ; function canSwap(d: TDanIdx; o1, o2: TOsebaIdx ): boolean ; function popraviKritNOk(d: TDanIdx; sk: smallint ): boolean ; function sortOsebe(var oList: TOsebeList; lIdx: TOsebaIdx; d: TDanIdx): boolean ; procedure sortOsebePoMix(var oList: TOsebeList; fIdx, lIdx: TOsebaIdx; d: TDanIdx) ; procedure sortOsebePoUrah(var oList: TOsebeList; fIdx, lIdx: TOsebaIdx; d: TDanIdx) ; function razporediNeodvDnevi(oList: TOsebeList; lIdx: TOsebaIdx; d, doDne: TDanIdx) : boolean ; function razporediDan(oList: TOsebeList; lIdx: TOsebaIdx; d: TDanIdx) : boolean ; function razSkupino(oList: TOsebeList; lIdx: TOsebaIdx; d: TDanIdx) : boolean ; function razOsebeSkupine(var oList: TOsebeList; fIdx, lIdx: TOsebaIdx; d: TDanIdx) : boolean ; procedure postaviDMIValsOut( var DMIVals: TDMIVals ); procedure popraviOsebeNaDMI( d: TDanIdx; o: TOsebaIdx; var newDMIVals: TDMIValsEl ) ; protected StartTime: LongWord ; public DMIVals: TDMIVals ; DMIValsOut: TDMIValsOut ; Status: smallint ; PREVERI_PRIH_KRIT: boolean ; popravljajKrsenja: boolean ; FastAndSloppy: boolean ; VrstaSortaOseb: smallint ; stMinVSkupini, stDniVSkupini: smallint ; procedure wrtRazpored(oList: TOsebeList; lIdx: TOsebaIdx ) ; procedure izpisiDMI ; constructor Create ; procedure prepare ; function solve : boolean ; //function solveBrezSkupin: boolean ; procedure settings ; virtual ; function krsitveKrit( var krsitve: TkrsitveKrit ): integer ; end ; {TRazSolve} TDMIValsElPlus = record mark: Cardinal; d: TDanIdx ; o: TOsebaIdx ; el: TDMIValsEl ; vKrit: TKritValList ; // vrednosti kriterijev za osebo end ; TDMIValsStore = class private sto: array[1..MxStore] of TDMIValsElPlus ; function lastMark: Cardinal; public last: integer ; constructor Create ; procedure clear ; function put( mark: Cardinal; d: TDanIdx; o: TOsebaIdx; var DMIValsEl: TDMIValsEl; var vK: TKritValList ): boolean ; function restore( mark: Cardinal; var DMIVals: TDMIVals; var sel: TRazSolve ): boolean ; end ; implementation // ******* // ******* class TDMIValsStore constructor TDMIValsStore.Create ; begin last := 0 ; end ; {Create} function TDMIValsStore.lastMark: Cardinal; begin lastMark := sto[last].mark ; end ; procedure TDMIValsStore.clear ; begin last := 0 ; end ; {clear} function TDMIValsStore.put( mark: Cardinal; d: TDanIdx; o: TOsebaIdx; var DMIValsEl: TDMIValsEl; var vK: TKritValList ): boolean ; begin last := last + 1 ; Result := true ; if last > MxStore then Result := false else begin sto[last].mark := mark ; sto[last].d := d ; sto[last].o := o ; sto[last].el := DMIValsEl ; sto[last].vKrit := vK ; // msg( 'Put: mark='+IntToStr(mark)+' d='+IntToStr(d)+' o='+IntToStr(o) ) ; end ; end ; {put} function TDMIValsStore.restore( mark: Cardinal; var DMIVals: TDMIVals; var sel: TRazSolve): boolean ; var i: integer ; d: TDanIdx; o: TOsebaIdx; vv: TVrstaVzorca ; begin // ce (store[last].mark < mark) je bil v propPribitDMI DMI ze ustrezno pribit in // smo povecali varMar, store[last].mark pa ne restore := false ; if (last = 0) or (sto[last].mark < mark) then exit ; if (sto[last].mark > mark) then begin sel.MsgHalt( 'TDMIValsStore.restore: zadnji dodani > varMatk',4, -1, -1 ) ; exit ; end ; i := last ; while (i > 0) and (sto[i].mark = mark) do begin d := sto[i].d ; o := sto[i].o ; if (DMIVals[d, o].nVals=1) and (sto[i].el.nVals<>1) then begin vv := sel.VrstaVzDMI(DMIVals[d, o].Vals[1]) ; sel.osebe[o].nePribiti := sel.osebe[o].nePribiti + 1 ; sel.nProstihMest[d,vv] := sel.nProstihMest[d,vv] + 1 ; sel.nMoznihOseb[d,vv] := sel.nMoznihOseb[d,vv] + 1 ; if vv <> 0 then // brisemo ze razporejen delovni dan (predpostavlja da oseba ni bila fiksirana) sel.osebe[o].delovni := sel.osebe[o].delovni - 1 ; end ; sel.osebe[o].vKrit := sto[i].vKrit ; // popravi se osebeNaDMI sel.popraviOsebeNaDMI( d, o, sto[i].el ) ; DMIVals[d, o] := sto[i].el ; i := i - 1 ; end ; last := i ; restore := true ; end ; {restore} // ******* // ******* class TRazSolve procedure TRazSolve.wrtRazpored(oList: TOsebeList; lIdx: TOsebaIdx ) ; var o, k: TOsebaIdx ; i: smallint ; s: String ; begin for k := 1 to lIdx do begin o := oList[k] ; s := '' ; for i := 1 to nDni do begin s := s + ' '+IntToStr(DMIVals[i,o].vals[1]); if DMIVals[i,o].nVals <> 1 then s := s + '*' ; if DMIVals[i,o].vals[1] < 10 then s := s + ' ' ; if i mod 10 = 0 then s := s + ' ' ; end ; s := s + ' * o' + intToStr(o) ; msg(s) ; end ; end ; {wrtRazpored} procedure TRazSolve.izpisiDMI; var oList: TOsebeList ; //i: smallint; // BUG do 8.6.2007 i: smallint; begin wrtKrit ; for i := 1 to nOseb do oList[i] := i ; msg( '********** RESITEV ********** iter= '+IntToStr(iter) ) ; wrtRazpored(oList, nOseb) ; end ; {izpisiDMI} function TRazSolve.DelOsebaNaDMI( dmi: TDMI ; d: TDanIdx ; o: TOsebaIdx ) : boolean ; // iz OsebeNaDMI[dmi,d] zbrise oseb o var dmiListIdx: 1..MxDMIList ; begin for dmiListIdx := 1 to OsebeNaDMI[dmi,d].last do if OsebeNaDMI[dmi,d].list[dmiListIdx] = o then begin OsebeNaDMI[dmi,d].list[dmiListIdx] := OsebeNaDMI[dmi,d].list[OsebeNaDMI[dmi,d].last] ; OsebeNaDMI[dmi,d].last := OsebeNaDMI[dmi,d].last - 1 ; DelOsebaNaDMI := true ; exit ; end ; DelOsebaNaDMI := false ; end ; {DelOsebaNaDMI} function TRazSolve.osebaNaDMI( dmi: TDMI ; d: TDanIdx ; o: TOsebaIdx ) : boolean ; // vrne true ce je oseba o v OsebeNaDMI[dmi,d].list var dmiListIdx: 1..MxDMIList ; begin osebaNaDMI := true ; for dmiListIdx := 1 to OsebeNaDMI[dmi,d].last do if OsebeNaDMI[dmi,d].list[dmiListIdx] = o then exit ; osebaNaDMI := false ; end ; {osebaNaDMI} function TRazSolve.skupDelMin( min: smallint ): smallint ; // vrne skupino glede na opravljene delovne minute begin Result := 1 + min div stMinVSkupini ; end ; {skupDelMin} function TRazSolve.skupDelDni( d: smallint ): smallint ; // vrne skupino glede na opravljene delovne dni begin Result := 1 + d div StDniVSkupini ; end ; {skupDelDni} constructor TRazSolve.Create ; begin inherited Create ; store := TDMIValsStore.Create ; mozniDMI := TSmIntRealPairArray.Create(High(TDMIList)) ; poDanSkupinah := true ; // za F5 = po locenih skupinah vsak dan stDniVSkupini := 5 ; // dela ok -Arm2006 stMinVSkupini := 35*UraMinut ; // ustreza 4 do 6 del.dnem - dela dobro, Arm2007 VrstaSortaOseb := 2 ; // sortOsebePoUrah(oList, fIdx, lIdx, d) ; popravljajKrsenja := true ; PREVERI_PRIH_KRIT := true ; // tudi dobro po 14.2., celo malo bolje FastAndSloppy := true ; // ce true potem omeji st.resitev; lahko hitreje ce resitev ne obstaja end ; {TRazSolve.Create} procedure TRazSolve.settings ; begin end ; procedure TRazSolve.prepare ; // pripravi vse za sestavljanje razporeda in se klice pred sestavljanjem razporeda var d: TDanIdx; sk: smallint ; oList: TOsebeList ; lIdx: TOsebaIdx ; begin Status := -1 ; settings ; // override - spremeni nastavitve initProblem ; DMIVals := DMIValsInitial ; for d := 1 to nDni do begin povezaneOsebeDne( DMIVals, d ) ; for sk := 1 to stSk[d] do begin getOsebeSkupine( d, sk, oList, lIdx ) ; end ; end ; if (VrstaSortaOseb > 1) and not krit[PUrMesecMx].enabled then MsgHalt( 'PUrMesecMx mora biti omogocen da se uporablja za enakomerno razporeditev', 2, -1, -1) ; wrtKrit ; oceneOseb := TSmIntRealPairArray.Create(nOseb) ; varMark := 0 ; (store as TDMIValsStore).last := 0 ; // ne dovolimo undo fiksiranja oseb iter := 0 ; end ; {TRazSolve.prepare} procedure TRazSolve.postaviDMIValsOut( var DMIVals: TDMIVals ); // prepise trenutni razpored (v DMIVals) v DMIValsOut var d: TDanIdx ; o: TOsebaIdx ; begin for d := 1 to MxDnevi do for o := 1 to MxOseb do DMIValsOut[d,o] := DMIVals[d,o].Vals[1] ; end ; {postaviDMIValsOut} function TRazSolve.initOsebeNaDMI2( var oList: TOsebeList; lIdx: TOsebaIdx; d: TDanIdx ): boolean ; // priredi v vse OsebeNaDmi[dmi,d] vse tist osebe, ki lahko delajo na dmi // v vsak osebeNaDMI[dmi,d] vstavimo osebe, ki imajo dmi v svoj DMIVals[d,o] // in ki imajo stDMIvDP(dmi, d) > 0 (druge osebe se niso fiksirane na ta dmi) // vrne false ce resitev brez krsenja kriterijev ne obstaja var o, k: TOsebaIdx; dmi: TDMI ; dmiListIdx: TDMIListIdx ; vv: TVrstaVzorca ; dmiSkup: TDMISet ; stDMSkup: integer ; begin Result := True ; stDMSkup := 0 ; // na dmi=0 mora biti mora biti vedno tocno nOseb - st.vseh prostih mest osebeNaDMI[0,d].last := 0 ; osebeNaDMI[0,d].pMest := lIdx ; dmiSkup := dmiSk[d, skOseb[d, oList[1]]] ; for dmi := 1 to nDMI do begin if not (dmi in dmiSkup) then continue ; osebeNaDMI[dmi,d].last := 0 ; osebeNaDMI[dmi,d].pMest := stDMIvDP(dmi, d) ; stDMSkup := stDMSkup + osebeNaDMI[dmi,d].pMest ; osebeNaDMI[0,d].pMest := osebeNaDMI[0,d].pMest - osebeNaDMI[dmi,d].pMest ; end ; if stDMSkup > lIdx then MsgHalt('Premalo oseb za izvajanje dela dne '+IntToStr(d), 3, d, -1) ; for k := 1 to lIdx do begin o := oList[k] ; if DMIVals[d,o].nVals=1 then begin // uredimo tudi DDMIje z eno samo vrednostjo dmi := DMIVals[d,o].Vals[1] ; if not (dmi in dmiSkup) then MsgHalt('Nemogoce',0, d, o ) ; osebe[o].nePribiti := osebe[o].nePribiti - 1 ; if VrstaVzDMI(dmi) <> 0 then osebe[o].delovni := osebe[o].delovni + 1 ; osebeNaDMI[dmi,d].pMest := osebeNaDMI[dmi,d].pMest - 1 ; updateKrit( d, o, dmi ) ; if not kritOK( o ) then begin msg('Pribita oseba '+IntToStr(o)+' ne izpolnjuje kriterijev: na DMI '+IntToStr(dmi)+' dne d'+IntToStr(d)) ; Result := False ; exit ; end ; if OsebeNaDMI[dmi,d].pMest < 0 then begin msg('Prevec oseb na DMI '+IntToStr(dmi)+' dne d'+IntToStr(d)) ; Result := False ; exit ; end ; end else begin for dmiListIdx := 1 to DMIVals[d,o].nVals do begin dmi := DMIVals[d,o].Vals[dmiListIdx] ; if not (dmi in dmiSkup) then MsgHalt('Nemogoce',0, d, o ) ; osebeNaDMI[dmi,d].last := osebeNaDMI[dmi,d].last + 1 ; osebeNaDMI[dmi,d].list[osebeNaDMI[dmi,d].last] := o ; end ; end ; end ; for vv := 0 to MxVrstVzorcev do nProstihMest[d,vv] := 0 ; for dmi := 0 to nDMI do begin if not (dmi in dmiSkup) then continue ; vv := VrstaVzDMI(dmi) ; nProstihMest[d,vv] := nProstihMest[d,vv] + osebeNaDMI[dmi,d].pMest ; if (dmi > 0) and (osebeNaDMI[dmi,d].pMest > osebeNaDMI[dmi,d].last) then begin //msg('Premalo oseb za izvajanje dela na DMI '+IntToStr(dmi)+' dne '+IntToStr(d)) ; MsgHalt('Premalo oseb za izvajanje dela na DMI '+IntToStr(dmi)+' dne '+IntToStr(d), 3, d, dmi) ; Result := False ; exit ; end ; end ; end ; {initOsebeNaDMI2} procedure TRazSolve.popraviOsebeNaDMI( d: TDanIdx; o: TOsebaIdx; var newDMIVals: TDMIValsEl ) ; // popravi osebeNaDMI ce se DMIVals poveca v NewDMIVals (po restore, oz undoPribij) // domena DMIVals je manjsa od newDMIVals (v osebeNaDMI moramo dodati prej brisane osebe) var dmi: TDMI ; dmiListIdx: TDMIListIdx ; begin // za vse dmi iz newDMIVals vstavi osebo v osebeNaDmi for dmiListIdx := 1 to newDMIVals.nVals do begin dmi := newDMIVals.Vals[dmiListIdx] ; if not osebaNaDMI( dmi, d, o ) then begin osebeNaDMI[dmi,d].last := osebeNaDMI[dmi,d].last + 1 ; osebeNaDMI[dmi,d].list[osebeNaDMI[dmi,d].last] := o ; end ; end ; if newDMIVals.nVals=1 then begin// oseba fiksirana MsgHalt( 'Pribita Oseba v Store',0, d, o ) ; end else begin // newDMIVals[d, o] ni pribit // ce se pribit DMIVals spremeni v nepribit NewDMIVals se sproti eno delovno mesto na dmi if DMIVals[d, o].nVals=1 then begin dmi := DMIVals[d, o].Vals[1] ; osebeNaDMI[dmi,d].pMest := osebeNaDMI[dmi,d].pMest + 1 ; // eno delovno mesto na dmi vec end ; end ; end ; {popraviOsebeNaDMI} function TRazSolve.propReduceKritNOk( d: TDanIdx; o: TOsebaIdx ): boolean ; // zbrise iz DMIVals[d,o] vse dmi ki krsijo kriterije in propagira spremembe s propReduceDMIVal var dmi: TDMI ; dmiListIdx: TDMIListIdx ; tmpvKrit: TKritValList ; // vrednosti kriterijev za osebo dmiKrsiKrit: boolean ; begin if sprosceniKrit then begin Result := true ; exit ; end ; Result := false ; // za vse mozne dmi preveri ce pribitje na dmi krsi kaksen kriterije v naslednjih dneh for dmiListIdx := 1 to DMIVals[d,o].nVals do begin dmi := DMIVals[d,o].Vals[dmiListIdx] ; dmiKrsiKrit := false ; if not newKritOK( d, o, dmi ) then // ali dmi krsi kriterij dne d dmiKrsiKrit := true else if PREVERI_PRIH_KRIT then begin // preverim ce dmi krsi kriterije prihodnjih dni tmpvKrit := osebe[o].vKrit ; updateKrit( d, o, dmi ) ; dmiKrsiKrit := not prihKritOK( d, o, DMIVals ) ; osebe[o].vKrit := tmpvKrit ; // vrnem stare kriterije end ; if dmiKrsiKrit then begin // ce dmi krsi nek krierij ga zbrisem iz DMIVals[d,o] if not propReduceDMIVal( dmi, d, o ) then begin //msg('propReduceDMIVal' ) ; exit ; end ; end ; end ; Result := true ; end ; {propReduceKritNOk} function TRazSolve.propReduceDMIVal( dmi: TDMI; d: TDanIdx; o: TOsebaIdx ): boolean ; begin propReduceDMIVal := false ; if (DMIVals[d,o].nVals=1) and (DMIVals[d,o].Vals[1] = dmi) then begin //msg('propReduceDMIVal: dmi '+IntToStr(dmi)+' ze pribit na brisano vrednost!' ) ; exit ; end ; // if dmi = 0 then MsgHalt( 'propReduceDMIVal: Brisanje dmi=0',0 ) ; if not osebaNaDMI( dmi, d, o ) then begin // dmi smo ze prej pobrisali, ali osebo fiksirali na drug dmi // msg( 'propReduceDMIVal: OK, vrednost dmi ze prej zbrisana' ) ; propReduceDMIVal := true ; exit end ; if dmiVals[d, o].nVals = 1 then // po brisanju dmi prazna domena exit ; if osebeNaDMI[dmi,d].last <= osebeNaDMI[dmi,d].pMest then // premalo oseb po brisanju tega dmi exit ; if dmiVals[d, o].nVals = 2 then begin // pribijemo na drug dmi if dmi = dmiVals[d, o].Vals[1] then propReduceDMIVal := propPribijDMIVal( dmiVals[d, o].Vals[2], d, o ) else propReduceDMIVal := propPribijDMIVal( dmiVals[d, o].Vals[1], d, o ) ; exit ; end ; if not (store as TDMIValsStore).put( varMark, d, o, DMIVals[d,o], osebe[o].vKrit ) then MsgHalt( 'Povecaj const MxStore; Prevec dodanih elementov',4, d, o ) ; delDMIVal( dmi, DMIVals[d, o] ) ; DelOsebaNaDMI( dmi, d, o ) ; propReduceDMIVal := true ; end ; {TRazSolve.propReduceDMIVal} function TRazSolve.propPribijDMIVal( dmi: TDMI; d: TDanIdx; o: TOsebaIdx ): boolean ; var dmi1: TDMI ; i, oIstiDMI: TOsebaIdx ; pDMIVals: TDMIList ; pOsebeNaDMI: TOsebeNaDMIEl ; vv, vv1: TVrstaVzorca ; begin propPribijDMIVal := false ; for dmi1 := 0 to nDMI do // ali je na preostalih dmi1 dovolj oseb da zapolnejo vsa prosta mesta if (dmi1 <> dmi) and osebaNaDMI( dmi1, d, o ) then begin if osebeNaDMI[dmi1, d].last - 1 < osebeNaDMI[dmi1, d].pMest then exit ; end ; if (DMIVals[d,o].nVals=1) then begin // ze prej pribit DMI if DMIVals[d,o].Vals[1] <> dmi then MsgHalt('propPribijDMIVal: pribijanje na za pribit dmi '+IntToStr(dmi),0, d, o ) else propPribijDMIVal := true ; exit ; end ; if not newKritOK( d, o, dmi ) then begin// ali pribijanje krsi kriterije //msg( 'PropPrbijDMIVal: not newKritOK d='+IntToStr(d)+' o='+IntToStr(o) ) ; exit ; end ; vv := VrstaVzDMI(dmi) ; if (DMIVals[d, o].nVrsteVz[vv]<=0) then MsgHalt( 'propPribij: nVrsteVz[vv]<=0',0, d, o) ; pDMIVals := DMIVals[d, o].Vals ; pOsebeNaDMI := osebeNaDMI[dmi,d] ; if not (store as TDMIValsStore).put( varMark, d, o, DMIVals[d,o], osebe[o].vKrit ) then MsgHalt( 'Povecaj const MxStore; Prevec dodanih elementov',4, d, o ) ; updateKrit( d, o, dmi) ; for vv1 := 0 to MxVrstVzorcev do DMIVals[d, o].nVrsteVz[vv1] := 0 ; DMIVals[d, o].nVrsteVz[vv] := 1 ; osebe[o].nePribiti := osebe[o].nePribiti - 1 ; nProstihMest[d,vv] := nProstihMest[d,vv] - 1 ; nMoznihOseb[d,vv] := nMoznihOseb[d,vv] - 1 ; if vv <> 0 then osebe[o].delovni := osebe[o].delovni + 1 ; DMIVals[d,o].nVals := 1 ; DMIVals[d,o].Vals[1] := dmi ; osebeNaDMI[dmi, d].pMest := osebeNaDMI[dmi, d].pMest - 1 ; for dmi1 := 0 to nDMI do if DelOsebaNaDMI( dmi1, d, o ) then begin // zbrisemo o iz vseh drugih OsebeNaDMI[dmi1,dF] if osebeNaDMI[dmi1, d].last < osebeNaDMI[dmi1, d].pMest then // premalo oseb za dmi1 exit ; // moramo najbrz se naprej propagirati? end ; if (osebeNaDMI[dmi, d].pMest = 0) then begin // vsem osebam, ki so lahko delale na tem dmi, zbrisemo dmi iz njihove domene, ter propagiramo for i := 1 to pOsebeNaDMI.last do begin oIstiDMI := pOsebeNaDMI.list[i] ; if (oIstiDMI <> o) and not propReduceDMIVal( dmi, d, oIstiDMI ) then exit ; end ; end ; propPribijDMIVal := true ; if (osebeNaDMI[dmi, d].pMest = 1) and (osebeNaDMI[dmi,d].last = 1) then propPribijDMIVal := propPribijDMIVal( dmi, d, osebeNaDMI[dmi,d].list[osebeNaDMI[dmi,d].last]) ; end ; {TRazSolve.propPribijDMIVal} procedure TRazSolve.undoPribijDMIVal ; // prekilce pribitje osebe na dmi in naredi vse potrebno: poveca st. prostih mest, in // nalozi staro domeno domeno dmi iz storea begin (store as TDMIValsStore).restore( varMark, DMIVals, Self ) ; varMark := varMark - 1 ; // msg('undo: varMArk='+IntToStr(VarMArk) ) ; end ; {undoPribijDMIVal} function TRazSolve.canInsertDMI(d: TDanIdx; o: TOsebaIdx; dmi: TDMI ): boolean ; // preveri ce vstavitev dmi na DMIVals[d,o] ne krsi kriterij PDanPocitek s prejsnjim // in naslednjim dnem; preveri tudi PZapDniTedenMx var v1, v2, vMx1, vMx2, minUr: TKritVal ; dc, dS: TDanIdx ; oneOK: boolean ; dmiListIdx: TDMIListIdx ; dSstart: smallint ; begin Result := true ; if dmi = 0 then // prost dan lahko vedno vstavimo exit ; if not (krit[PDanPocitek].enabled) and (not krit[PZapUrTedenMx].enabled) and (not krit[PZapDniTedenMx].enabled) then exit ; if krit[PZapUrTedenMx].enabled or krit[PZapDniTedenMx].enabled then begin // meri najdaljso sekvenco 7 zaporednih dni zacensi z d-6 vMx1 := 0 ; vMx2 := 0 ; // mx. ure in mx.del.dnevi dSstart := d-6 ; for dS := MaxInt( 1, dSstart ) to d do begin // dS je zacetek sekvence dolz. 7 v1 := DMIList[dmi].ur ; // stejemo trajanje vstavljnega dmija v2 := 1 ; // en dan za vstavljneni dmi (zgoraj preverimo ce dmi<>prosto) for dc := dS to MinInt( nDni, dS+6 ) do begin // max 7 zaporednih dni if dc = d then // dmi dne d smo ze steli v v continue ; minUr := High(TKritVal) ; // dolocimo najkrajsi izmed moznih dmi oneOK := true ; for dmiListIdx := 1 to DMIVals[dc,o].nVals do begin minUr := MinInt( minUr, DMIList[DMIVals[dc,o].Vals[dmiListIdx]].ur ) ; oneOK := oneOK and (DMIVals[dc,o].Vals[dmiListIdx] <> 0) ; // true ce so vsi dmi<>prosto end ; if oneOK then begin // sigurno je del.dan v1 := v1 + minUr ; // steje vsoto najkrajsih dmijev vMx1 := MaxInt( vMx1, v1 ) ; v2 := v2 + 1 ; // steje del.dneve vMx2 := MaxInt( vMx2, v2 ) ; end else break ; end ; end ; Result := Result and valOK( vMx1, PZapUrTedenMx ) ; Result := Result and valOK( vMx2, PZapDniTedenMx ) ; // prej napaka end ; if krit[PDanPocitek].enabled then begin if d > 1 then begin if DMIVals[d-1,o].nVals > 1 then MsgHalt( 'canInsert: Nemogoce',0, d, o ) ; Result := Result and checkKritDanPocitek(DMIVals[d-1,o].Vals[1], dmi) ; end ; if d < nDni then begin oneOK := false ; for dmiListIdx := 1 to DMIVals[d+1,o].nVals do if checkKritDanPocitek(dmi, DMIVals[d+1,o].Vals[dmiListIdx]) then begin oneOK := true ; break ; end ; Result := Result and oneOK ; end ; end ; end ; {canInsertDMI} function TRazSolve.canSwap(d: TDanIdx; o1, o2: TOsebaIdx ): boolean ; // true ce lahko zamenjamo dmi-ja ze razporejenih oseb o1 in o2 // smiselno preverjati le ce sta o1 in o2 v isti skupini var dmi1, dmi2: TDMI ; dmiListIdx: TDMIListIdx ; ok, danPocitekEnabled, ZapUrTedenMxEnabled, ZapDniTedenMxEnabled: boolean ; i: TTipKriterija ; tKritEnabled: array[TTipKriterija] of boolean ; begin Result := false ; dmi1 := DMIVals[d,o1].Vals[1] ; dmi2 := DMIVals[d,o2].Vals[1] ; if dmi1=dmi2 then // nesmislena menjava exit ; if (dmi1 = 0) or (DMIVals[d,o1].nVals+DMIVals[d,o2].nVals>2) then MsgHalt('canSwap: Nemogoce',0, d, o1 ) ; if sprosceniKrit then MsgHalt('canSwap: Nemogoce',0, d, o1 ) ; // preverim ce lahko o2 dela na dmi1 in o1 na dmi2 ok := false ; for dmiListIdx := 1 to DMIValsInitial[d,o2].nVals do if dmi1 = DMIValsInitial[d,o2].Vals[dmiListIdx] then begin ok := true ; break ; end ; if not ok then exit ; ok := false ; for dmiListIdx := 1 to DMIValsInitial[d,o1].nVals do if dmi2 = DMIValsInitial[d,o1].Vals[dmiListIdx] then begin ok := true ; break ; end ; if not ok then exit ; ok := canInsertDMI( d, o2, dmi1) and canInsertDMI( d, o1, dmi2) ; if not ok then exit ; for i := Low(TTipKriterija) to High(TTipKriterija) do tKritEnabled[i] := krit[i].enabled ; krit[PDanPocitek].enabled := false ; // onemogoci kriterij PDanPocitek krit[PZapDniTedenMx].enabled := false ; krit[PZapUrTedenMx].enabled := false ; for i := Low(TTipKriterija) to High(TTipKriterija) do begin if not valOK( osebe[o1].vKrit[i], i ) then // onemogocim kriterij ki je krsen ze pred menjavo krit[i].enabled := false ; if not valOK( osebe[o2].vKrit[i], i ) then // onemogocim kriterij ki je krsen ze pred menjavo krit[i].enabled := false ; end ; if newKritOK(d, o2, dmi1) and newKritOK(d, o1, dmi2) then // odoborim menjavo Result := true ; for i := Low(TTipKriterija) to High(TTipKriterija) do krit[i].enabled := tKritEnabled[i] ; end ; {canSwap} function TRazSolve.popraviKritNOk(d: TDanIdx; sk: smallint ): boolean ; // popravi krsenje krit. oseb iz skupine sk dne d, z menjavami oseb v prejsnjih dneh // za vsako osebo o1 iz skupine sk, ki krsi kriterije in za vse prejsnje dneve pd // poskusaj o1 zamenjati z osebo o2, ki je v isti skupini kot o1 dne pd var pd: TDanIdx ; oList: TOsebeList; lIdx, lIdxPd, k, o1, o2: TOsebaIdx; vsajEnoKrsenje, okip, okiNPVkd, prihOK: boolean ; ds: TDanIdx ; dmi1, dmi2: TDMI ; kk: smallint ; dsstart: smallint ; begin Result := false ; vsajEnoKrsenje:= false ; getOsebeSkupine( d, sk, oList, lIdx ) ; //if d > 29 then // msg('30') ; for k := 1 to lIdx do begin o1 := oList[k] ; // izbere osebo o1 s krsenim krierijem if kritOk( o1 ) then continue else vsajEnoKrsenje:= true ; okip := kritOKIgnorePocitek( o1 ) ; // popravim le prej. dan ce je le krsenje PDanPocitek okiNPVkd := kritOKIgnoreNPVkd(o1 ) ; // popravim le sob, ned, praznike ce krsenje le teh dni dsstart := d ; dsstart := dsstart-vplivDniKritOsebe(o1) ; // prepreci underflow ds := MaxInt(1, dsstart ) ; for pd := d downto ds do begin // za trenutni dan in vse prejsnje dni pd if okiNPVkd and not (DP[pd].tipDne in [sob,ned,pra]) then continue ; if (DMIVals[pd,o1].Vals[1] = 0) or (DMIValsInitial[pd,o1].nVals = 1) then continue ; for o2 := 1 to nOseb do begin if skOseb[pd, o2] <> skOseb[pd, o1] then continue ; // za vse o2, ki so v skupini z o1 dne pd if (o1 = o2) or (DMIValsInitial[pd,o2].nVals = 1) then // menjava ene in iste osebe continue ; dmi1 := DMIVals[pd,o1].Vals[1] ; dmi2 := DMIVals[pd,o2].Vals[1] ; // preveri ce menjava zmanjsa skupno st. krsenih kriterijev kk kk := nKrsKritNow(o1) + nKrsKritNow(o2) ; if okip then begin // krsen le krit.pocitek; nujno da se dmi2 konca prej kot dmi1 if DMIList[dmi2].zac + DMIList[dmi2].ur >= DMIList[dmi1].zac + DMIList[dmi1].ur then continue ; end ; if canSwap(pd, o1, o2) then begin // o1 in o2 sta ze pribiti dne pd; o2 ni nujno pribita dne d DMIVals[pd, o1].Vals[1] := dmi2 ; DMIVals[pd, o2].Vals[1] := dmi1 ; recompAllKrit( d, o1, DMIVals ) ; recompAllKrit( d, o2, DMIVals ) ; // preveri ce o1 in o2 krsita gotove kriterije prihodnjih dni prihOK := true ; if PREVERI_PRIH_KRIT then prihOK := prihKritOk(d, o1, DMIVals ) and prihKritOk(d, o2, DMIVals ) ; if (not prihOK) or (kk <= nKrsKritNow(o1) + nKrsKritNow(o2)) then begin // naredi undo zamenjave DMIVals[pd, o1].Vals[1] := dmi1 ; DMIVals[pd, o2].Vals[1] := dmi2 ; recompAllKrit( d, o1, DMIVals ) ; recompAllKrit( d, o2, DMIVals ) ; end else begin msg( '--> popraviKrsenjeKrit: d='+IntToStr(d)+' pd='+IntToStr(pd)+': SWAP o'+IntToStr(o1)+ '('+IntToStr(DMIVals[pd,o2].Vals[1])+') with o'+IntToStr(o2)+'('+IntToStr(DMIVals[pd,o1].Vals[1])+')' ) ; Result := true ; exit ; end ; end ; end ; // za vse o2, ki so v skupini z o1 dne pd end ; // za vse prejsnje dni pd end ; if not vsajEnoKrsenje and sprosceniKrit then MsgHalt( 'Nemogoce: krit vseh oseb ok, d='+IntToStr(d),0, d, -1 ) ; end ; {popraviKritNOk} function TRazSolve.dolociMestaVzorca(var oList: TOsebeList; fIdx, lIdx: TOsebaIdx; d: TDanIdx): boolean ; // izracuna nMoznihOseb in nProstihMest var o, oListIdx: TOsebaIdx ; vv: TVrstaVzorca ; dmi: TDMI ; n: smallint ; dmiSkup: TDMISet ; begin Result := false ; for vv := 0 to MxVrstVzorcev do begin nProstihMest[d,vv] := 0 ; nMoznihOseb[d,vv] := 0 ; end ; dmiSkup := dmiSk[d, skOseb[d, oList[1]]] ; for dmi := 0 to nDMI do begin if not (dmi in dmiSkup) then continue ; vv := VrstaVzDMI(dmi) ; nProstihMest[d,vv] := nProstihMest[d,vv] + osebeNaDMI[dmi,d].pMest ; end ; for oListIdx := fIdx to lIdx do begin o := oList[oListIdx] ; n := 0 ; for vv := 0 to MxVrstVzorcev do begin if not preveriVzorec( d, o, vv ) then continue ; nMoznihOseb[d,vv] := nMoznihOseb[d,vv] + 1 ; n := n + 1 ; end ; if n = 0 then begin msg( 'oceniOsebeDne: nobenega moznega vzorca o'+IntToStr(o) ) ; exit ; end ; end ; // mora veljati: nProstihMest[0] := nOseb - vsehProstih ; // nOseb-vsehProstih ima ta dan prosto for vv := 0 to MxVrstVzorcev do begin if nMoznihOseb[d,vv] < nProstihMest[d,vv] then begin if not NOMSG then begin msg('Premalo razpolozljivih oseb - vzorca '+IntToStr(vv)+' ni mogoce razporediti dne '+IntToStr(d)) ; end ; exit ; // vzorca ni mogoce razporediti - premalo oseb end ; end ; Result := true ; end ; {oceniOsebeDne} function TRazSolve.preveriVzorec( d: TDanIdx; o: TOsebaIdx; vv: TVrstaVzorca ): boolean ; // preveri ce izbira tega vzorca ne krsi nVrsteVz ali nProstihMest begin Result := false ; if (DMIVals[d,o].nVals=1) then begin if VrstaVzDMI(DMIVals[d,o].Vals[1]) <> vv then exit ; end else begin if (DMIVals[d, o].nVrsteVz[vv]<=0) then exit ; if (nProstihMest[d,vv] < 1) then // vzorec ze zapolnjen exit ; if osebe[o].nePribiti <= 0 then begin // oseba ze popolnoma zasedene msg('PreveriVzorec: o'+IntToStr(o)+' ze popolnoma zasedena' ) ; exit ; end ; end ; Result := true ; end ; {preveriVzorec} function TRazSolve.sortOsebe(var oList: TOsebeList; lIdx: TOsebaIdx; d: TDanIdx): boolean ; // osebe sortira tako da so na zacetku oList tezje osebe oz. osebe ki so doslej delale manj // vrne false ce oceniOsebeDne ne uspe begin Result := dolociMestaVzorca( oList, 1, lIdx, d) ; if not Result then exit ; case VrstaSortaOseb of 1: sortOsebePoMix(oList, 1, lIdx, d) ; // Armorica 2006 2: sortOsebePoUrah(oList, 1, lIdx, d) ; else MsgHalt('VrstaSortaOseb nepravilna',0, -1, -1 ) ; end ; end ; {sortOsebe} procedure TRazSolve.sortOsebePoMix(var oList: TOsebeList; fIdx, lIdx: TOsebaIdx; d: TDanIdx) ; // osebe sortira tako da so na zacetku oList osebe, ki imajo manj moznih vzorcev // pribite osebe damo na zacetek seznama oseb var o, i: TOsebaIdx ; vv: TVrstaVzorca ; prioriteta: real ; // nizja prioriteta, prej osebo razporedimo nVz, nd, delDni : smallint ; begin // tiste osebe, ki imajo zazeljenost 0 ali 1 so ze fiksirane na vzorec 0 oz. vzorec <>0 oceneOseb.last := - 1 ; for i := fIdx to lIdx do begin o := oList[i] ; if (DMIVals[d,o].nVals=1) then begin prioriteta := 0 ; end else begin // vzorec ni pribit nVz := 0 ; nd := 0 ; for vv := 0 to MxVrstVzorcev do if preveriVzorec( d, o, vv ) then begin nVz := nVz + 1 ; nd := nd + DMIVals[d,o].nVrsteVz[vv] ; // stevilo dmijev tega vzorca vv end ; prioriteta := nVz ; // prioriteta je stevilo moznih vzorcev osebe if nVz > 0 then begin // upostevamo tudi delovne dni: osebe z manj delovnimi dnevi razporedimo prej delDni := skupDelDni(osebe[o].delovni) ; prioriteta := 10 * delDni + prioriteta ; end ; end ; oceneOseb.Add(o, prioriteta ) ; end ; oceneOseb.SortByR ; for o := fIdx to lIdx do oList[o] := oceneOseb.a[o-fIdx] ; end ; {sortOsebePoMix} procedure TRazSolve.sortOsebePoUrah(var oList: TOsebeList; fIdx, lIdx: TOsebaIdx; d: TDanIdx) ; // osebe sortira tako da so na zacetku oList osebe, ki imajo manj moznih vzorcev // pribite osebe damo na zacetek seznama oseb var o, i: TOsebaIdx ; vv: TVrstaVzorca ; prioriteta: real ; // nizja prioriteta, prej osebo razporedimo nVz, delUr : smallint ; begin // tiste osebe, ki imajo zazeljenost 0 ali 1 so ze fiksirane na vzorec 0 oz. vzorec <>0 oceneOseb.last := - 1 ; for i := fIdx to lIdx do begin o := oList[i] ; if (DMIVals[d,o].nVals=1) then begin prioriteta := 0 ; end else begin // vzorec ni pribit nVz := 0 ; for vv := 0 to MxVrstVzorcev do if preveriVzorec( d, o, vv ) then nVz := nVz + 1 ; prioriteta := nVz ; // prioriteta je stevilo moznih vzorcev osebe if nVz > 0 then begin // upostevamo tudi delovne dni: osebe z manj delovnimi dnevi razporedimo prej delUr := skupDelMin(PrenosMin[o]+osebe[o].vkrit[PUrMesecMx]) ; prioriteta := 10 * delUr + prioriteta ; end ; end ; oceneOseb.Add(o, prioriteta ) ; end ; oceneOseb.SortByR ; for o := fIdx to lIdx do oList[o] := oceneOseb.a[o-fIdx] ; end ; {sortOsebePoUrah} function TRazSolve.mozniDMIVzorca(vvDMI: TVrstaVzorca; d: TDanIdx; o: TOsebaIdx; var mDMI: TSmallIntArray) : boolean ; // za vse mozne vrednosti DMIjev vzorca vvDMI osebe o, dne d naredi forward checking in vrne // seznam mozniDMI v katerih so mozne vrednosti DMIja, urejene po LCV hevristiki // (najprej dmi z najvecjim st.prostih mest v DP in najmanj moznimi osebami); // Ce je vednost dmi 0 (prosti dmi) v DMIVals[d,o] jo dodamo na konec mozniDMI var dmi: TDMI ; vv: TVrstaVzorca ; i: integer ; begin mozniDMI.last := -1 ; for i := 1 to DMIVals[d,o].nVals do begin // za vsem mozne DMI vzorca vvDMI, osebe o, dne d dmi := DMIVals[d,o].Vals[i] ; vv := VrstaVzDMI(dmi) ; if vv <> vvDMI then continue ; // preveri kateri dmi so mozni za osebo o glede na zakonske kriterije if (DMIVals[d,o].nVals > 1) and not newKritOK(d, o, dmi) then MsgHalt( 'NEMOGOCE???: mozniDMIVzorca: kriteriji krseni',0, d, o ) ; if dmi = 0 then begin mozniDMI.Add( dmi, 0 ) ; // dmi=0 (prosto dodamo na konec seznama end else begin if (DMIVals[d, o].nVals=1) and (DMIVals[d, o].Vals[1] <> dmi) then MsgHalt('mozniDMIVzorca: dmi '+IntToStr(dmi)+' ze pribit!',3, d, o ) ; if (DMIVals[d, o].nVals<>1) and (osebeNaDMI[dmi, d].pMest = 0) then // dmi ze popolnoma zaseden continue ; // nepotrebno; tudi propReduceDMIV preveri ce je premalo oseb da bi opravile ta dmi if OsebeNaDMI[dmi,d].last < osebeNaDMI[dmi, d].pMest then begin MsgHalt('MozniDMIVzorca: premalo razpolozljivih oseb dne '+IntToStr(d)+' za dmi '+IntToStr(dmi),3, d, dmi ) ; continue ; end ; // najbolje najvecje st.prostih mest v DP in najmanjse st moznih oseb na tem dmi mozniDMI.Add( dmi, -1 * osebeNaDMI[dmi, d].pMest + 0.01 * OsebeNaDmi[dmi,d].last ) ; end ; end ; if mozniDMI.last >= 1 then begin mozniDMI.SortByR ; end ; Result := (mozniDMI.last >=0) ; if Result then begin // prepisemo mozniDMI v mDMI SetLength(mDMI,mozniDMI.last+1) ; for i := 0 to Length(mDMI)-1 do mDMI[i] := mozniDMI.a[i] ; end ; end ; {mozniDMIVzorca} function TRazSolve.oceniVzorceOsebe(o: TOsebaIdx; d: TDanIdx; vrVzorcev: TVrstniRedVzorcev ): smallint ; // doloci prioriteto oseb na vzorcih tega dne za vse osebe oList[fIdx..lIdx] // ce je vecja zazeljenost, bo vzorec izbran prej // vrne stevilo primernih vzorcev osebe var vv: TVrstaVzorca ; zazeljenost: real ; Dmin: real ; // max. st.del.dni osebe begin Result := -1 ; for vv := 0 to MxVrstVzorcev do begin vrVzorcev[o].a[vv] := vv; vrVzorcev[o].r[vv] := 0; if nMoznihOseb[d,vv] < nProstihMest[d,vv] then begin if not NOMSG then begin error('Premalo razpolozljivih oseb - vzorca '+IntToStr(vv)+' ni mogoce razporediti dne '+IntToStr(d)) ; end ; exit ; // vzorca ni mogoce razporediti - premalo oseb end ; if not preveriVzorec( d, o, vv ) then continue ; Dmin := 0.8 * nDni ; // preverimo ce je mozen vzorec naslednjega dne if (DMIVals[d,o].nVals=1) and (VrstaVzDMI(DMIVals[d,o].Vals[1])=vv) then zazeljenost := 50 else begin // vzorec ni pribit if vv=0 then begin // zazeljenost prostega dne = kolikor dni manjka do tega da bi dosegli nDni-Dmin prostih dni zazeljenost := max( 1, nDni-Dmin - osebe[o].delovni ) ; end else begin // zazeljenost delovnega dne = kolikor dni manjka da bi dosegli Dmin delovnih dni zazeljenost := max( 1, (Dmin - osebe[o].delovni) ) ; if nProstihMest[d,vv] > 0 then begin // oseba ima raje vzorec na katerem je manj moznih oseb zazeljenost := zazeljenost + 0.3 - 0.1 * min( 3, nMoznihOseb[d,vv]/nProstihMest[d,vv] ) ; // lahko dajemo prednost cim daljsim vzorcem: dajemo prednost istemu vzorcu, kot je prejsnji dan if d > 1 then begin if DMIVals[d-1,o].nVals <> 1 then MsgHalt( 'ni mogoce: dmi prejsnjega dne ni pribit',0, d, o ) ; if vv = VrstaVzDMI(DMIVals[d-1,o].Vals[1]) then zazeljenost := zazeljenost + 3 ; end ; end else // nProstihMest[d,vv] = 0 zazeljenost := 0 ; end ; end ; vrVzorcev[o].r[vv] := -1.0 * zazeljenost ; end ; vrVzorcev[o].SortByR ; vv := 0 ; while (vv < MxVrstVzorcev) and (vrVzorcev[o].r[vv] < 0) do vv := vv + 1 ; if (vrVzorcev[o].r[vv] < 0) then Result := vv else Result := vv-1 ; end ; {oceniVzorceOsebe} function TRazSolve.razOsebeSkupine(var oList: TOsebeList; fIdx, lIdx: TOsebaIdx; d: TDanIdx) : boolean ; // msg('Tipka F5: razpored po metodi BREZ VZORCOV, po SKUPINAH' ) ; var o: TOsebaIdx ; dmi: TDMI ; vv, v1: TVrstaVzorca ; i: smallint ; nVz: smallint ; mDMI: TSmallIntArray ; begin Result := false ; if fIdx > lIdx then begin // dan d uspesno razporejen Result := true ; exit ; end ; iter := iter + 1 ; o := oList[fIdx] ; nVz := oceniVzorceOsebe(o, d, vrVzorcevGlob) ; if nVz < 0 then // nobenega moznega vzorca osebe exit ; shMsgOsebe(fIdx) ; for v1 := 0 to nVz do begin vv := vrVzorcevGlob[o].a[v1] ; // vzorci so urejeni po narascajoci prioriteti if DMIVals[d,o].nVals<>1 then begin if (nProstihMest[d,vv]-1 > lIdx-fIdx) or (nProstihMest[d,vv] < 1) then continue ; // premalo oseb za vzorec end ; if not mozniDMIVzorca(vv, d, o, mDMI) then //uredi mozne vrednosti DMIja po LCV continue ; for i := 0 to Length(mDMI)-1 do begin dmi := mDMI[i] ; // prej huda napaka ker se mozniDMI rekurzivno spremeni varMark := varMark + 1 ; if not propPribijDMIVal( dmi, d, o ) then begin undoPribijDMIVal ; // moramo vrniti tudi stare kriterije continue ; end ; Result := razOsebeSkupine( oList, fIdx+1, lIdx, d ) ; // razporedi naslednjo osebo if Result then exit ; shMsgOsebe(fIdx) ; undoPribijDMIVal ; if FastAndSloppy then break ; end ; end ; end ; {razOsebeSkupine} function TRazSolve.razSkupino(oList: TOsebeList; lIdx: TOsebaIdx; d: TDanIdx) : boolean ; // msg('Tipka F5: razpored po metodi BREZ VZORCOV, po SKUPINAH' ) ; var o: TOsebaIdx ; begin Result := false ; if not initOsebeNaDMI2(oList, lIdx, d) then begin exit ; end ; for o := 1 to lIdx do if not propReduceKritNOk( d, oList[o] ) then begin// iz DMIVals[d,.] izloci dmi, ki krsijo kriterije exit ; end ; if not (sortOsebe(oList, lIdx, d) and razOsebeSkupine(oList, 1, lIdx, d)) then exit ; Result := true ; end ; {razSkupino} function TRazSolve.razporediDan(oList: TOsebeList; lIdx: TOsebaIdx; d: TDanIdx) : boolean ; // msg('Tipka F5: razpored po metodi BREZ VZORCOV, po SKUPINAH' ) ; var o, lIdx2: TOsebaIdx ; vv: TVrstaVzorca ; sk: smallint ; oList2: TOsebeList ; s: string ; allKritOk: boolean ; begin {razporediDan} Result := false ; for o := 1 to lIdx do begin vrVzorcevGlob[oList[o]] := TSmIntRealPairArray.Create(MxVrstVzorcev+1) ; for vv := 0 to MxVrstVzorcev do vrVzorcevGlob[oList[o]].Add(vv, 0); end ; for o := 1 to nOseb do // shrani osebe, kot so pred razporejanjem dne d tmposebe[o] := osebe[o] ; for sk := 1 to stSk[d] do begin getOsebeSkupine( d, sk, oList2, lIdx2 ) ; s := ' osebe: ' ; for o := 1 to lIdx2 do begin s := s + ' o' + IntToStr(oList2[o]) ; end ; if not razSkupino(oList2, lIdx2, d) then begin for o := 1 to lIdx2 do begin // naredi undo sprememb DMIVals[d,oList2[o]] := DMIValsInitial[d,oList2[o]] ; osebe[oList2[o]] := tmposebe[oList2[o]] ; end ; sprostiKriterije ; if not popravljajKrsenja then msg( 'Dan '+IntToStr(d)+s+' - KRITERIJI sprosceni' ) ; Result := razSkupino(oList2, lIdx2, d) ; vrniKriterije ; if not Result then begin //razpored dneva ne obstaja MsgHalt('Resitev za dan d'+IntToStr(d)+' s sproscenimi kriteriji ne obstaja!', 6, d, -1) ; exit ; end ; if not popravljajKrsenja then begin for o := 1 to lIdx2 do // uporabi kriterije oseb, ki niso krseni updateKritOKOnly(d, oList2[o], DMIVals[d,oList2[o]].Vals[1]) ; continue ; end ; for o := 1 to lIdx2 do // uporabi kriterije, ceprav so krseni updateKrit(d, oList2[o], DMIVals[d,oList2[o]].Vals[1]) ; repeat Result := popraviKritNOk(d, skOseb[d, oList2[1]]) ; allKritOk := true ; for o := 1 to lIdx2 do if not kritOk(oList2[o]) then allKritOk := false ; until allKritOk or not Result ; for o := 1 to lIdx2 do // vrni stare kriterije osebe[oList2[o]] := tmposebe[oList2[o]] ; for o := 1 to lIdx2 do // uporabi kriterije oseb, ki niso krseni updateKritOKOnly(d, oList2[o], DMIVals[d,oList2[o]].Vals[1]) ; if allKritOk then begin msg( 'Dan '+IntToStr(d)+s+' - KRITERIJI OK (menjave oz. krs.le prih.dnevi)' ) ; end else begin msg( 'Dan '+IntToStr(d)+s+' - KRITERIJI sprosceni' ) ; end ; end ; end ; // for sk := 1 to raz.stSk[d] do begin Result := true ; end ; {razporediDan} function TRazSolve.razporediNeodvDnevi(oList: TOsebeList; lIdx: TOsebaIdx; d, doDne: TDanIdx) : boolean ; // msg('Tipka F5: razpored po metodi BREZ VZORCOV, po SKUPINAH' ) ; begin {razporediNeodvDnevi} Result := false ; while d <= doDne do begin shMsgDan(d) ; Result := razporediDan( oList, lIdx, d ) ; if not Result then exit ; (store as TDMIValsStore).clear ; varMark := 0 ; d := d + 1 ; end ; if not NOMSG then msg( '********** RESITEV ********** iter= '+IntToStr(iter) ) ; msg( 'RazporediNEODV: Elapsed Milisconds = '+IntToStr(MilliSecondOfTheDay(Now)-StartTime) ) ; end ; {razporediNeodvDnevi} function TRazSolve.solve: boolean ; // sestavi razpored // msg('Tipka F5: razpored po metodi BREZ VZORCOV, po SKUPINAH' ) ; var oList: TOsebeList ; // i: smallint ; // !!! do 8.6.2007 BUG!!! smallint oseb > 128 i: smallint ; // po 8.6.2007 ok begin prepare ; for i := 1 to nOseb do oList[i] := i ; Status := 0 ; StartTime := MilliSecondOfTheDay(Now) ; Result := razporediNeodvDnevi(oList, nOseb, 1, nDni) ; if Result then begin Status := 1 ; postaviDMIValsOut(DMIVals ); end ; end ; {solve} function TRazSolve.krsitveKrit( var krsitve: TkrsitveKrit ): integer ; //TkrsitveKrit = array[1..MxOseb] of record // dodano 29.03.2007: spisek krsenih kriterijev oseb // dan: smallint ; // prvi dan ko oseba krsi nek kriterij; ce dan=0 potem oseba ne krsi kriterijev // kriterij: TTipKriterija ; // prvi krseni kriterij // vrKrit: TKritVal ; // vrednost prvega krsenega kriterija //end ; // JAKL: klices kot: // var stkrsenihKriterijev: integer ; krsitve: TkrsitveKrit ; // stkrsenihKriterijev := krsitveKrit( krsitve ) ; var o: TOsebaIdx; d: TDanIdx ; dmi: TDMI ; i, kkFirst, k: integer ; ik: TTipKriterija ; vv: TVrstaVzorca ; mxKrit: TKritValList ; prevKrit, osMxKrit: array[1..MxOseb] of TKritValList ; kk: boolean ; nKrsenih, nKrsInc: integer ; v: TkritVal ; begin // Prenosi se pri izracunu vrednosti kriterijev ne upostevajo initKriteriji ; nKrsenih := 0 ; // steje dni, ko so kriteriji krseni nKrsInc := 0 ; // steje dni, ko so kriteriji krseni in hkrati povecani; steje vse krsene kriterije za vse osebe for ik := Low(TTipKriterija) to High(TTipKriterija) do begin mxKrit[ik] := 0 ; for o := 1 to nOseb do begin prevKrit[o,ik] := 0 ; osMxKrit[o, ik] := 0 ; end ; end ; for o := 1 to nOseb do begin kk := false ; kkFirst := 0 ; krsitve[o].dan := 0 ; for d := 1 to nDni do begin prevKrit[o] := osebe[o].vKrit ; updateKrit(d, o, DMIVals[d,o].Vals[1]) ; for ik := Low(TTipKriterija) to High(TTipKriterija) do begin if ik = PVkdMesecMx then v := VkdMesecValToVkdCount(osebe[o].vKrit[ik]) else v := osebe[o].vKrit[ik] ; if v > mxKrit[ik] then mxKrit[ik] := v ; if v > osMxKrit[o,ik] then osMxKrit[o,ik] := v ; end ; if not kritOK(o) then begin // kriteriji krseni nKrsenih := nKrsenih + 1 ; kk := true ; if kkFirst = 0 then kkFirst := d ; for ik := Low(TTipKriterija) to High(TTipKriterija) do begin if not valOK( osebe[o].vKrit[ik], ik ) then begin if krsitve[o].dan = 0 then begin // prva krsitev; vstavi jo v krsitve krsitve[o].dan := d ; krsitve[o].kriterij := ik ; if (ik = PVkdMesecMx) then krsitve[o].vrKrit := VkdMesecValToVkdCount(osebe[o].vKrit[ik]) else krsitve[o].vrKrit := osebe[o].vKrit[ik] ; end ; if (ik <> PVkdMesecMx) and (prevKrit[o,ik] < osebe[o].vKrit[ik]) then nKrsInc := nKrsInc + 1 ; // dodatna krsitev kriterija if (ik = PVkdMesecMx) and (VkdMesecValToVkdCount(prevKrit[o,ik]) < VkdMesecValToVkdCount(osebe[o].vKrit[ik])) then nKrsInc := nKrsInc + 1 ; // dodatna krsitev kriterija end ; end ; end ; end ; end ; // for o := 1 to nOseb do Result := nKrsInc ; end ; {krsitveKrit} end.
unit Class_BILL_FL; interface uses Classes,SysUtils,Uni,UniEngine; type TBILLFL=class(TUniEngine) private FUNITLINK: string; FBILLIDEX: Integer; FBILLFLID: Integer; FPRODIDEX: Integer; FPRODNUMB: Integer; FPRODMONY: Extended; protected procedure SetParameters;override; function GetStrInsert:string;override; function GetStrUpdate:string;override; function GetStrDelete:string;override; public function GetStrsIndex:string;override; public function GetNextIdex:Integer;overload; function GetNextIdex(AUniConnection:TUniConnection):Integer;overload; public function CheckExist(AUniConnection:TUniConnection):Boolean;override; public destructor Destroy; override; constructor Create; published property UNITLINK: string read FUNITLINK write FUNITLINK; property BILLIDEX: Integer read FBILLIDEX write FBILLIDEX; property BILLFLID: Integer read FBILLFLID write FBILLFLID; property PRODIDEX: Integer read FPRODIDEX write FPRODIDEX; property PRODNUMB: Integer read FPRODNUMB write FPRODNUMB; property PRODMONY: Extended read FPRODMONY write FPRODMONY; public class function ReadDS(AUniQuery:TUniQuery):TUniEngine;override; class procedure ReadDS(AUniQuery:TUniQuery;var Result:TUniEngine);override; class function CopyIt(ABILLFL:TBILLFL):TBILLFL;overload; class procedure CopyIt(ABILLFL:TBILLFL;var Result:TBILLFL);overload; end; implementation { TBILLFL } procedure TBILLFL.SetParameters; begin inherited; with FUniSQL.Params do begin case FOptTyp of otAddx: begin ParamByName('UNIT_LINK').Value := UNITLINK; ParamByName('BILL_IDEX').Value := BILLIDEX; ParamByName('BILL_FLID').Value := BILLFLID; ParamByName('PROD_IDEX').Value := PRODIDEX; ParamByName('PROD_NUMB').Value := PRODNUMB; ParamByName('PROD_MONY').Value := PRODMONY; end; otEdit: begin ParamByName('UNIT_LINK').Value := UNITLINK; ParamByName('BILL_IDEX').Value := BILLIDEX; ParamByName('BILL_FLID').Value := BILLFLID; ParamByName('PROD_IDEX').Value := PRODIDEX; ParamByName('PROD_NUMB').Value := PRODNUMB; ParamByName('PROD_MONY').Value := PRODMONY; end; otDelt: begin ParamByName('UNIT_LINK').Value := UNITLINK; ParamByName('BILL_IDEX').Value := BILLIDEX; ParamByName('BILL_FLID').Value := BILLFLID; end; end; end; end; function TBILLFL.CheckExist(AUniConnection: TUniConnection): Boolean; begin Result:=CheckExist('TBL_BILL_FL',['UNIT_LINK',UNITLINK,'BILL_IDEX',BILLIDEX,'BILL_FLID',BILLFLID],AUniConnection); end; function TBILLFL.GetNextIdex: Integer; begin end; function TBILLFL.GetNextIdex(AUniConnection: TUniConnection): Integer; begin end; function TBILLFL.GetStrDelete: string; begin Result:='DELETE FROM TBL_BILL_FL WHERE UNIT_LINK=:UNIT_LINK AND BILL_IDEX=:BILL_IDEX AND BILL_FLID=:BILL_FLID'; end; function TBILLFL.GetStrInsert: string; begin Result:='INSERT INTO TBL_BILL_FL' +' ( UNIT_LINK, BILL_IDEX, BILL_FLID, PROD_IDEX, PROD_NUMB' +' , PROD_MONY)' +' VALUES' +' (:UNIT_LINK,:BILL_IDEX,:BILL_FLID,:PROD_IDEX,:PROD_NUMB' +' ,:PROD_MONY)'; end; function TBILLFL.GetStrsIndex: string; begin Result:=Format('%S-%D-%D',[UNITLINK,BILLIDEX,BILLFLID]); end; function TBILLFL.GetStrUpdate: string; begin Result:='UPDATE TBL_BILL_FL SET' +' PROD_IDEX=:PROD_IDEX,' +' PROD_NUMB=:PROD_NUMB,' +' PROD_MONY=:PROD_MONY' +' WHERE UNIT_LINK=:UNIT_LINK' +' AND BILL_IDEX=:BILL_IDEX' +' AND BILL_FLID=:BILL_FLID'; end; constructor TBILLFL.Create; begin end; destructor TBILLFL.Destroy; begin inherited; end; class function TBILLFL.ReadDS(AUniQuery: TUniQuery): TUniEngine; begin Result:=TBILLFL.Create; with TBILLFL(Result) do begin UNITLINK:=AUniQuery.FieldByName('UNIT_LINK').AsString; BILLIDEX:=AUniQuery.FieldByName('BILL_IDEX').AsInteger; BILLFLID:=AUniQuery.FieldByName('BILL_FLID').AsInteger; PRODIDEX:=AUniQuery.FieldByName('PROD_IDEX').AsInteger; PRODNUMB:=AUniQuery.FieldByName('PROD_NUMB').AsInteger; PRODMONY:=AUniQuery.FieldByName('PROD_MONY').AsFloat; end; end; class procedure TBILLFL.ReadDS(AUniQuery: TUniQuery; var Result: TUniEngine); begin if Result=nil then Exit; with TBILLFL(Result) do begin UNITLINK:=AUniQuery.FieldByName('UNIT_LINK').AsString; BILLIDEX:=AUniQuery.FieldByName('BILL_IDEX').AsInteger; BILLFLID:=AUniQuery.FieldByName('BILL_FLID').AsInteger; PRODIDEX:=AUniQuery.FieldByName('PROD_IDEX').AsInteger; PRODNUMB:=AUniQuery.FieldByName('PROD_NUMB').AsInteger; PRODMONY:=AUniQuery.FieldByName('PROD_MONY').AsFloat; end; end; class function TBILLFL.CopyIt(ABILLFL: TBILLFL): TBILLFL; begin Result:=TBILLFL.Create; TBILLFL.CopyIt(ABILLFL,Result) end; class procedure TBILLFL.CopyIt(ABILLFL:TBILLFL;var Result:TBILLFL); begin if Result=nil then Exit; Result.UNITLINK:=ABILLFL.UNITLINK; Result.BILLIDEX:=ABILLFL.BILLIDEX; Result.BILLFLID:=ABILLFL.BILLFLID; Result.PRODIDEX:=ABILLFL.PRODIDEX; Result.PRODNUMB:=ABILLFL.PRODNUMB; Result.PRODMONY:=ABILLFL.PRODMONY; end; end.
// ************************************************************************ // ***************************** CEF4Delphi ******************************* // ************************************************************************ // // CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based // browser in Delphi applications. // // The original license of DCEF3 still applies to CEF4Delphi. // // For more information about CEF4Delphi visit : // https://www.briskbard.com/index.php?lang=en&pageid=cef // // Copyright © 2017 Salvador Díaz Fau. All rights reserved. // // ************************************************************************ // ************ vvvv Original license and comments below vvvv ************* // ************************************************************************ (* * Delphi Chromium Embedded 3 * * Usage allowed under the restrictions of the Lesser GNU General Public License * or alternatively the restrictions of the Mozilla Public License 1.1 * * 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. * * Unit owner : Henri Gourvest <hgourvest@gmail.com> * Web site : http://www.progdigy.com * Repository : http://code.google.com/p/delphichromiumembedded/ * Group : http://groups.google.com/group/delphichromiumembedded * * Embarcadero Technologies, Inc is not permitted to use or redistribute * this source code without explicit permission. * *) unit uCEFDialogHandler; {$IFNDEF CPUX64} {$ALIGN ON} {$MINENUMSIZE 4} {$ENDIF} {$I cef.inc} interface uses {$IFDEF DELPHI16_UP} System.Classes, {$ELSE} Classes, {$ENDIF} uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes; type TCefDialogHandlerOwn = class(TCefBaseRefCountedOwn, ICefDialogHandler) protected function OnFileDialog(const browser: ICefBrowser; mode: TCefFileDialogMode; const title, defaultFilePath: ustring; acceptFilters: TStrings; selectedAcceptFilter: Integer; const callback: ICefFileDialogCallback): Boolean; virtual; public constructor Create; virtual; end; TCustomDialogHandler = class(TCefDialogHandlerOwn) protected FEvent: IChromiumEvents; function OnFileDialog(const browser: ICefBrowser; mode: TCefFileDialogMode; const title: ustring; const defaultFilePath: ustring; acceptFilters: TStrings; selectedAcceptFilter: Integer; const callback: ICefFileDialogCallback): Boolean; override; public constructor Create(const events: IChromiumEvents); reintroduce; virtual; destructor Destroy; override; end; implementation uses uCEFMiscFunctions, uCEFLibFunctions, uCEFBrowser, uCEFFileDialogCallback; function cef_dialog_handler_on_file_dialog(self: PCefDialogHandler; browser: PCefBrowser; mode: TCefFileDialogMode; const title, default_file_path: PCefString; accept_filters: TCefStringList; selected_accept_filter: Integer; callback: PCefFileDialogCallback): Integer; stdcall; var list: TStringList; i: Integer; str: TCefString; begin list := TStringList.Create; try for i := 0 to cef_string_list_size(accept_filters) - 1 do begin FillChar(str, SizeOf(str), 0); cef_string_list_value(accept_filters, i, @str); list.Add(CefStringClearAndGet(str)); end; with TCefDialogHandlerOwn(CefGetObject(self)) do Result := Ord(OnFileDialog(TCefBrowserRef.UnWrap(browser), mode, CefString(title), CefString(default_file_path), list, selected_accept_filter, TCefFileDialogCallbackRef.UnWrap(callback))); finally list.Free; end; end; constructor TCefDialogHandlerOwn.Create; begin CreateData(SizeOf(TCefDialogHandler)); with PCefDialogHandler(FData)^ do on_file_dialog := cef_dialog_handler_on_file_dialog; end; function TCefDialogHandlerOwn.OnFileDialog(const browser: ICefBrowser; mode: TCefFileDialogMode; const title, defaultFilePath: ustring; acceptFilters: TStrings; selectedAcceptFilter: Integer; const callback: ICefFileDialogCallback): Boolean; begin Result := False; end; // TCustomDialogHandler constructor TCustomDialogHandler.Create(const events: IChromiumEvents); begin inherited Create; FEvent := events; end; destructor TCustomDialogHandler.Destroy; begin FEvent := nil; inherited Destroy; end; function TCustomDialogHandler.OnFileDialog(const browser : ICefBrowser; mode : TCefFileDialogMode; const title : ustring; const defaultFilePath : ustring; acceptFilters : TStrings; selectedAcceptFilter : Integer; const callback : ICefFileDialogCallback): Boolean; begin if (FEvent <> nil) then Result := FEvent.doOnFileDialog(browser, mode, title, defaultFilePath, acceptFilters, selectedAcceptFilter, callback) else Result := inherited OnFileDialog(browser, mode, title, defaultFilePath, acceptFilters, selectedAcceptFilter, callback); end; end.
unit TpButton; interface uses Windows, SysUtils, Classes, Controls, Graphics, Types, ThWebControl, ThTag, ThButton, TpControls; type TTpButton = class(TThButton) private FOnClick: TTpEvent; FOnGenerate: TTpEvent; protected procedure Tag(inTag: TThTag); override; published property OnClick: TTpEvent read FOnClick write FOnClick; property OnGenerate: TTpEvent read FOnGenerate write FOnGenerate; end; implementation procedure TTpButton.Tag(inTag: TThTag); begin inherited; with inTag do begin //Add('tpname', Name); Add(tpClass, 'TTpButton'); Add('tpOnClick', OnClick); Add('tpOnGenerate', OnGenerate); end; end; end.
unit ibSHSQLPlayerEditors; interface uses SysUtils, Classes, DesignIntf, TypInfo, SHDesignIntf, ibSHDesignIntf; type TibSHDefaultSQLDialectPropEditor = class(TSHPropertyEditor) public function GetAttributes: TPropertyAttributes; override; procedure GetValues(AValues: TStrings); override; procedure SetValue(const Value: string); override; end; TibSHSQLPlayerModePropEditor = class(TSHPropertyEditor) private FValues: string; procedure Prepare; public constructor Create(APropertyEditor: TObject); override; destructor Destroy; override; function GetAttributes: TPropertyAttributes; override; procedure GetValues(AValues: TStrings); override; procedure SetValue(const Value: string); override; // property DDLExtractor: IibSHDDLExtractor read FDDLExtractor; end; TibSHSQLPlayerAfterErrorPropEditor = class(TSHPropertyEditor) private FValues: string; procedure Prepare; public constructor Create(APropertyEditor: TObject); override; destructor Destroy; override; function GetAttributes: TPropertyAttributes; override; procedure GetValues(AValues: TStrings); override; procedure SetValue(const Value: string); override; // property DDLExtractor: IibSHDDLExtractor read FDDLExtractor; end; implementation uses ibSHConsts, ibSHValues, ibSHMessages; { TibBTDefaultSQLDialectPropEditor } function TibSHDefaultSQLDialectPropEditor.GetAttributes: TPropertyAttributes; begin Result := [paValueList]; end; procedure TibSHDefaultSQLDialectPropEditor.GetValues(AValues: TStrings); begin AValues.Text := GetDefaultSQLDialect; end; procedure TibSHDefaultSQLDialectPropEditor.SetValue(const Value: string); begin if Assigned(Designer) and Designer.CheckPropValue(Value, GetDefaultSQLDialect) then inherited SetOrdValue(StrToInt(Value)); end; { TibSHSQLPlayerModePropEditor } constructor TibSHSQLPlayerModePropEditor.Create( APropertyEditor: TObject); begin inherited Create(APropertyEditor); Prepare; end; destructor TibSHSQLPlayerModePropEditor.Destroy; begin inherited; end; procedure TibSHSQLPlayerModePropEditor.Prepare; begin FValues := FormatProps(PlayerModes); end; function TibSHSQLPlayerModePropEditor.GetAttributes: TPropertyAttributes; begin Result := [paValueList]; end; procedure TibSHSQLPlayerModePropEditor.GetValues(AValues: TStrings); begin AValues.Text := FValues; end; procedure TibSHSQLPlayerModePropEditor.SetValue(const Value: string); begin // inherited SetValue(Value); if Designer.CheckPropValue(Value, FValues) then inherited SetStrValue(Value); end; { TibSHSQLPlayerAfterErrorPropEditor } constructor TibSHSQLPlayerAfterErrorPropEditor.Create( APropertyEditor: TObject); begin inherited Create(APropertyEditor); Prepare; end; destructor TibSHSQLPlayerAfterErrorPropEditor.Destroy; begin inherited; end; procedure TibSHSQLPlayerAfterErrorPropEditor.Prepare; begin FValues := FormatProps(PlayerAfterErrors); end; function TibSHSQLPlayerAfterErrorPropEditor.GetAttributes: TPropertyAttributes; begin Result := [paValueList]; end; procedure TibSHSQLPlayerAfterErrorPropEditor.GetValues( AValues: TStrings); begin AValues.Text := FValues; end; procedure TibSHSQLPlayerAfterErrorPropEditor.SetValue( const Value: string); begin if Designer.CheckPropValue(Value, FValues) then inherited SetStrValue(Value); end; end.
unit Lib.HeaderValues; interface uses System.Classes, Lib.HTTPContent, Lib.HTTPUtils; procedure GetHeaderRequestValues(const URL,HeaderName: string; Values: TStrings); implementation procedure GetHeaderRequestValues(const URL,HeaderName: string; Values: TStrings); var Protocol,Host,Resource: string; begin Values.Clear; if HeaderName='Host' then begin HTTPSplitURL(URL,Protocol,Host,Resource); Values.Add(Host); end else if HeaderName='Connection' then begin Values.Add('close'); Values.Add('keep-alive'); Values.Add('keep-alive, Upgrade'); Values.Add('Upgrade'); end else if HeaderName='Keep-Alive' then begin Values.Add('timeout=10'); end else if HeaderName='Cookie' then begin Values.Add('Name=Value'); end else if HeaderName='User-Agent' then begin Values.Add('Mozilla/5.0 (Windows NT 6.1; rv:61.0)'); end else if HeaderName='Accept' then begin Values.Add('*/*'); Values.Add('text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'); end else if HeaderName='Accept-Language' then begin Values.Add('ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3'); end else if HeaderName='Accept-Encoding' then begin Values.Add('gzip, deflate, br'); end else if HeaderName='Cache-Control' then begin Values.Add('max-age=0'); Values.Add('no-cache'); end else if HeaderName='Pragma' then begin Values.Add('no-cache'); end else if HeaderName='Upgrade' then begin Values.Add('websocket'); end else if HeaderName='If-Modified-Since' then begin Values.Add('Fri, 15 Feb 2019 21:10:37 GMT'); end else if HeaderName='Content-Length' then begin Values.Add('0'); end else if HeaderName='Upgrade-Insecure-Requests' then begin Values.Add('1'); end else if HeaderName='Authorization' then begin Values.Add('Basic STRING_BASE64'); end else if HeaderName='Content-Type' then begin HTTPGetContentTypes(Values); end; end; end.
unit uPassword; interface uses WinTypes, WinProcs, Classes, Graphics, Forms, Controls, StdCtrls, Buttons, DB, DBTables, SysUtils, Dialogs, ExtCtrls, Mask, ADODB, SuperComboADO, uSystemTypes, siComp, siLangRT; type TPassword = class(TForm) Label1: TLabel; EditPassword: TEdit; Panel1: TPanel; Panel9: TPanel; Panel3: TPanel; quRights: TADOQuery; quRightsIDUser: TIntegerField; quRightsCanAccess: TBooleanField; quRightsCanInsert: TBooleanField; quRightsCanDelete: TBooleanField; quRightsCanPrint: TBooleanField; quRightsCanUpdate: TBooleanField; quRightsMenuID: TIntegerField; quRightsSubMenuID: TIntegerField; quRightsIDUserType: TIntegerField; quRightsComissionID: TIntegerField; quRightsSystemUser: TStringField; cmbStore: TSuperComboADO; Label2: TLabel; Image1: TImage; quFuncRight: TADOQuery; quFuncRightIDUserType: TIntegerField; quFuncRightIDSysFunction: TIntegerField; quFuncRightAcesso: TBooleanField; btOK: TButton; btCancel: TButton; chkKeepLogin: TCheckBox; dsLookupStore: TDataSource; procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btCancelClick(Sender: TObject); procedure btOKClick(Sender: TObject); private { Private declarations } IsSuperUser:Boolean; AllowCommand : TSetCommandType; //FuncRights procedure CloseFuncRights; procedure OpenFuncRights; public { Public declarations } MenuName, SubMenuName : String; MyMenuItem : Integer; MySubMenuItem : Integer; Logged : Boolean; //Rodrigo - se for user permanente vericar em cada menu se pode entrar PermanentLogOn, PermanentCashLogOn : Boolean; function HasFuncRight(IDSysFunction : integer ) : Boolean; function SetRights(brwCommand : TSetCommandType) : TSetCommandType; function Start(IDMenu, IDSubMenu : integer) : boolean; function Login(Pw : String):Boolean; end; var Password: TPassword; implementation uses uDM, uMsgBox, uMsgConstant, uVarianteFunctions, uDMGlobal, uSystemConst; {$R *.DFM} procedure TPassword.OpenFuncRights; begin with quFuncRight do if not Active then Open; end; procedure TPassword.CloseFuncRights; begin with quFuncRight do if Active then Close; end; function TPassword.Start(IDMenu, IDSubMenu : integer) : boolean; begin MyMenuItem := IDMenu; MySubMenuItem := IDSubMenu; cmbStore.enabled := (MyMenuItem >= 3) or (MyMenuItem = -1); Result := // ** Manager PermanentLogOn or // ** Cashier com UnLock e opção CashRegister/CashRegister (PermanentCashLogOn and ((IDMenu = 1) and (IDSubMenu = 1))) or // ** O user passou a senha correta e está habilitado (ShowModal = mrOk); end; procedure TPassword.FormShow(Sender: TObject); begin inherited; Screen.Cursor := crDefault; EditPassword.Clear; if cmbStore.LookUpValue = '' then cmbStore.LookUpValue := IntToStr(DM.IDStore); EditPassword.SetFocus; end; procedure TPassword.FormCreate(Sender: TObject); begin inherited; Screen.Cursor := crHourGlass; //quRights.Prepare; PermanentLogOn := False; PermanentCashLogOn := False; // Abre a tabela de direitos por funcao e fica aberta ate terminar a aplicacao OpenFuncRights; inherited; Screen.Cursor := crDefault; end; procedure TPassword.FormDestroy(Sender: TObject); begin //quRights.UnPrepare; CloseFuncRights; end; procedure TPassword.btCancelClick(Sender: TObject); begin ModalResult := mrCancel; end; function TPassword.Login(PW : String):Boolean; begin Result := False; with DM.quFreeSQL do begin if Active then Close; SQL.Text := 'SELECT UserTypeID , IDUser, SystemUser , ComissionID, StoresAccess ' + 'FROM dbo.SystemUser SystemUser ' + 'WHERE Desativado = 0 AND SystemUser.PW = ' + Chr(39)+PW+Chr(39); Open; If RecordCount = 0 then begin Close; Exit; end; AllowCommand := []; DM.fUser.ID := FieldByName('IDUser').AsInteger; DM.fUser.IDUserType := FieldByName('UserTypeID').AsInteger; DM.fUser.UserName := FieldByName('SystemUser').AsString; PermanentLogOn := True; PermanentCashLogOn := False; DM.fUser.Password := PW; if FieldByName('StoresAccess').AsString <> '' then DM.StoreList := FieldByName('StoresAccess').AsString else DM.StoreList := IntToStr(DM.IDStore); Close; end; Result := True; end; procedure TPassword.btOKClick(Sender: TObject); begin if Trim(EditPassword.Text) = '' then begin EditPassword.SetFocus; MsgBox(MSG_INF_PASSWORD_CANNOT_BE_NULL, vbOKOnly + vbInformation); Exit; end; if Trim(cmbStore.Text) = '' then begin cmbStore.SetFocus; MsgBox(MSG_CRT_NO_STORE_SELECTED, vbOKOnly + vbInformation); Exit; end; DM.IDStore := StrToInt(cmbStore.LookUpValue); DM.StoreName := cmbStore.Text; PermanentLogOn := chkKeepLogin.Checked; //Nova Validacao with DM.quFreeSQL do begin if Active then Close; SQL.Text := 'SELECT IDUser, StoresAccess ' + 'FROM SystemUser SystemUser ' + 'WHERE Desativado = 0 AND SystemUser.PW = ' + Chr(39)+EditPassword.Text+Chr(39); Open; If RecordCount <> 0 then begin DM.fUser.ID := FieldByName('IDUser').AsInteger; if FieldByName('StoresAccess').AsString <> '' then DM.StoreList := FieldByName('StoresAccess').AsString else DM.StoreList := cmbStore.LookUpValue; end; Close; end; // Testa se e para setar o permanentLogOn do Manager if (MyMenuItem = -1) and (MySubMenuItem = -1) then begin with DM.quFreeSQL do begin if Active then Close; SQL.Text := 'SELECT UserTypeID , IDUser, SystemUser , ComissionID ' + 'FROM dbo.SystemUser SystemUser ' + 'WHERE Desativado = 0 AND SystemUser.PW = ' + Chr(39)+EditPassword.Text+Chr(39); Open; If RecordCount = 0 then begin MsgBox(MSG_INF_INVALID_PASSWORD, vbOKOnly + vbInformation); Close; Exit; end; AllowCommand := []; DM.fUser.ID := FieldByName('IDUser').AsInteger; DM.fUser.IDUserType := FieldByName('UserTypeID').AsInteger; DM.fUser.UserName := FieldByName('SystemUser').AsString; PermanentLogOn := True; PermanentCashLogOn := False; ModalResult := mrOK; DM.fUser.Password := EditPassword.Text; Close; Exit; end; end; // ** if MenuItem = -1 ... // ** Testa se e para setar o permanentLogOn do Cashier // ** Ivanil if (MyMenuItem = -2) and (MySubMenuItem = -2) then begin with DM.quFreeSQL do begin if Active then Close; SQL.Text := 'SELECT UserTypeID , IDUser, SystemUser , ComissionID ' + 'FROM SystemUser SystemUser ' + 'WHERE Desativado = 0 AND SystemUser.PW = ' + Chr(39)+EditPassword.Text+Chr(39); Open; if (FieldByName('UserTypeID').AsInteger = USER_TYPE_CASHIER) or (FieldByName('UserTypeID').AsInteger = USER_TYPE_CASHIER_PO) then begin AllowCommand := []; DM.fUser.ID := FieldByName('IDUser').AsInteger; DM.fUser.IDUserType := FieldByName('UserTypeID').AsInteger; DM.fUser.UserName := FieldByName('SystemUser').AsString; PermanentCashLogOn := True; PermanentLogOn := False; ModalResult := mrOK; Close; Exit; end else begin EditPassword.SelectAll; EditPassword.SetFocus; MsgBox(MSG_INF_NOT_CASHIER_PASWORD, vbOKOnly + vbInformation); Close; Exit; end; end; end; // ** if MenuItem = -2 ... with quRights do begin try if Active then Close; Parameters.ParambyName('Password').Value := EditPassword.Text; Parameters.ParambyName('MenuID').Value := MyMenuItem; Parameters.ParambyName('SubMenuID').Value := MySubMenuItem; Open; if not (EditPassword.Text = 'pinpinha') then begin IsSuperUser := False; if Bof and Eof then begin EditPassword.SelectAll; EditPassword.SetFocus; MsgBox(MSG_INF_INVALID_PASSWORD, vbOKOnly + vbInformation); Exit; end; //Pego o password para verificar se pode accessar o menu DM.fUser.Password := EditPassword.Text; DM.fUser.ID := quRightsIdUser.AsInteger; DM.fUser.IDUserType := quRightsIDUserType.AsInteger; DM.fUser.UserName := quRightsSystemUser.AsString; DM.fUser.IDUserType := quRightsIDUserType.AsInteger; end else begin IsSuperUser := True; DM.fUser.ID := 0; DM.fUser.IDUserType := USER_TYPE_MANAGER; DM.fUser.UserName := 'Super User'; end; AllowCommand := [btInc, btAlt, btExc, btImp]; if quRightsCanInsert.AsBoolean or IsSuperUser then AllowCommand := AllowCommand - [btInc]; if quRightsCanUpdate.AsBoolean or IsSuperUser then AllowCommand := AllowCommand - [btAlt]; if quRightsCanDelete.AsBoolean or IsSuperUser then AllowCommand := AllowCommand - [btExc]; if quRightsCanPrint.AsBoolean or IsSuperUser then AllowCommand := AllowCommand - [btImp]; ModalResult := mrOK; // Retorna True; finally Close; end; end; end; function TPassword.SetRights(brwCommand : TSetCommandType) : TSetCommandType; begin // Atribui direitos ao browse Result := brwCommand - AllowCommand; end; function TPassword.HasFuncRight(IDSysFunction : integer ) : Boolean; begin // Atribui que sempre vai ser chamada em retorno ao ultimo status de senha // digitada with quFuncRight do begin //verify the User Rights OpenFuncRights; if Locate('IDSysFunction;IDUserType', ConvVarArray(IntToStr(IDSysFunction)+';'+IntToStr(DM.fUser.IDUserType)), []) then begin Result := quFuncRightAcesso.AsBoolean; end else begin raise exception.Create('Access denied, call Administrator.'); end; end; end; end.
unit Files; {This unit defines abstract file class as well as implementation of simple disk file, buffered file and a text file} interface uses SysUtils; Const {OpenFileWrite flags} fm_Create=1; {Create new file} fm_LetReWrite=2;{Let rewrite file if exists - OpenFileWrite} fm_AskUser=4; {Ask user if something} fm_CreateAskRewrite=fm_Create+fm_LetRewrite+fm_AskUser; {OpenFileRead&Write flags} fm_Share=8; {Let share file} fm_Buffered=16; {Constants for text files} txt_bufsize=8096; txt_maxlinesize=4096; Type TFile=class Function GetFullName:String;virtual;abstract; Function GetShortName:String;virtual;abstract; Function Fread(var buf;size:integer):integer;virtual;abstract; Function Fwrite(var buf;size:integer):integer;virtual;abstract; Function Fsize:Longint;virtual;abstract; Function Fpos:Longint;virtual;abstract; Procedure Fseek(Pos:longint);virtual;abstract; Destructor FClose;virtual;abstract; end; TBufFile=class(TFile) f:TFile; pbuf:pchar; pos:Longint; bpos,bsize:word; bcapacity:word; Constructor CreateRead(bf:TFile); Constructor CreateWrite(bf:TFile); Function GetFullName:String;override; Function GetShortName:String;override; Function Fread(var buf;size:integer):integer;override; Function Fwrite(var buf;size:integer):integer;override; Function Fsize:Longint;override; Function Fpos:Longint;override; Procedure Fseek(Pos:longint);override; Destructor FClose;override; Private Procedure InitBuffer(size:word); Procedure ReadBuffer; Procedure WriteBuffer; end; TTextFile=Class f:TFile; bpos,bsize:word; buffer:array[0..txt_bufsize] of char; Constructor CreateRead(bf:TFile); Constructor CreateWrite(bf:TFile); Procedure Readln(var s:String); Procedure Writeln(s:String); Function Eof:Boolean; Destructor FClose; Private Procedure LoadBuffer; Procedure SeekEoln; end; TDiskFile=class(TFile) f:File; Constructor CreateRead(path:TFileName); Constructor CreateWrite(path:TFileName); Function GetFullName:String;override; Function GetShortName:String;override; Function Fread(var buf;size:integer):integer;override; Function Fwrite(var buf;size:integer):integer;override; Function Fsize:Longint;override; Function Fpos:Longint;override; Procedure Fseek(Pos:longint);override; Destructor FClose;override; end; Function OpenFileRead(path:TFileName;mode:word):TFile; Function OpenFileWrite(path:TFileName;mode:word):TFile; implementation Function OpenFileRead(path:TFileName;mode:word):TFile; begin Result:=TDiskFile.CreateRead(path); end; Function OpenFileWrite(path:TFileName;mode:word):TFile; begin Result:=TDiskFile.CreateWrite(path); end; Constructor TDiskFile.CreateRead(path:TFileName); begin Assign(f,path); FileMode:=0; Reset(f,1); end; Constructor TDiskFile.CreateWrite(path:TFileName); begin Assign(f,path); ReWrite(f,1); end; Function TDiskFile.GetFullName:String; begin Result:=TFileRec(f).name; end; Function TDiskFile.GetShortName:String; begin Result:=ExtractFileName(GetFullName); end; Function TDiskFile.Fread(var buf;size:integer):integer; begin BlockRead(f,buf,size,Result); end; Function TDiskFile.Fwrite(var buf;size:integer):integer; begin BlockWrite(f,buf,size,Result); end; Function TDiskFile.Fsize:Longint; begin Result:=FileSize(f); end; Function TDiskFile.Fpos:Longint; begin Result:=FilePos(f); end; Procedure TDiskFile.Fseek(Pos:longint); begin Seek(f,Pos); end; Destructor TDiskFile.FClose; begin CloseFile(f); end; {TTextFile methods} Destructor TTextFile.FClose; begin f.FClose; end; Constructor TTextFile.CreateRead(bf:TFile); begin f:=bf; f.Fseek(0); LoadBuffer; end; Constructor TTextFile.CreateWrite(bf:TFile); begin f:=bf; end; Procedure TTextFile.SeekEoln; var ps:Pchar; begin ps:=StrScan(@buffer[bpos],#10); if ps<>nil then {EoLn found} begin bpos:=ps-@buffer+1; if bpos=bsize then LoadBuffer; end else {Eoln not found} begin Repeat LoadBuffer; if eof then exit; ps:=StrScan(buffer,#10); Until(ps<>nil); bpos:=ps-@buffer; SeekEoln; end; end; Procedure TTextFile.Readln(var s:String); var ps,pend:Pchar; tmp:array[0..txt_maxlinesize-1] of char; ssize:word; l:word; begin s:=''; if bpos=bsize then LoadBuffer; if eof then exit; ps:=buffer+bpos; pend:=StrScan(ps,#10); if pend<>nil then begin ssize:=pend-ps; if ssize>txt_maxlinesize then ssize:=txt_maxlinesize; {Limit string size to 255 chars} s:=StrLCopy(tmp,ps,ssize); l:=Length(s); if l<>0 then if s[l]=#13 then SetLength(s,l-1); inc(bpos,ssize); SeekEoln; end else begin ssize:=bsize-bpos; if ssize>txt_maxlinesize then ssize:=txt_maxlinesize; s:=StrLCopy(tmp,ps,ssize); {copy the tail of the buffer} LoadBuffer; if eof then exit; pend:=StrScan(buffer,#10); if pend=nil then ssize:=bsize else ssize:=pend-@buffer; if ssize+length(s)>txt_maxlinesize then ssize:=txt_maxlinesize-length(s); s:=ConCat(s,StrLCopy(tmp,buffer,ssize)); inc(bpos,ssize); l:=Length(s); if l<>0 then if s[l]=#13 then SetLength(s,l-1); SeekEoln; end; end; Procedure TTextFile.Writeln(s:String); const eol:array[0..0] of char=#10; begin f.FWrite(s[1],length(s)); f.FWrite(eol,sizeof(eol)); end; Function TTextFile.Eof:Boolean; begin result:=bsize=0; end; Procedure TTextFile.LoadBuffer; var bytes:longint; begin bytes:=f.fsize-f.fpos; if bytes>txt_bufsize then bytes:=txt_bufsize; f.FRead(buffer,bytes); bpos:=0; bsize:=bytes; buffer[bsize]:=#0; end; {TBufFile methods} Procedure TBufFile.InitBuffer(size:word); begin bcapacity:=size; GetMem(pbuf,bcapacity); end; Procedure TBufFile.ReadBuffer; begin f.Fseek(fpos); { f.Fread(pbuf^,bcapacity} end; Procedure TBufFile.WriteBuffer; begin end; Constructor TBufFile.CreateRead(bf:TFile); begin InitBuffer(2048); f:=bf; ReadBuffer; end; Constructor TBufFile.CreateWrite(bf:TFile); begin end; Function TBufFile.GetFullName:String; begin result:=f.GetFullName; end; Function TBufFile.GetShortName:String; begin Result:=f.GetShortName; end; Function TBufFile.Fread(var buf;size:integer):integer; begin end; Function TBufFile.Fwrite(var buf;size:integer):integer; begin end; Function TBufFile.Fsize:Longint; begin end; Function TBufFile.Fpos:Longint; begin end; Procedure TBufFile.Fseek(Pos:longint); begin end; Destructor TBufFile.FClose; begin f.FClose; FreeMem(pbuf); end; end.
unit UMainForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, UTrieTree, Spin; type TMainForm = class(TForm) inputEdt: TEdit; fillTreeBtn: TButton; findFormsBtn: TButton; grp1: TGroupBox; treeView: TTreeView; res: TLabel; res_text: TLabel; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure fillTreeBtnClick(Sender: TObject); procedure findFormsBtnClick(Sender: TObject); procedure inputEdtKeyPress(Sender: TObject; var Key: Char); private tree: TTrieTree; function getInput: String; public { Public declarations } end; var MainForm: TMainForm; implementation {$R *.dfm} procedure TMainForm.FormCreate(Sender: TObject); begin tree := TTrieTree.Create(); end; procedure TMainForm.fillTreeBtnClick(Sender: TObject); var input: String; begin input := getInput; tree.push(input); tree.print(treeView); inputEdt.Clear; end; procedure TMainForm.findFormsBtnClick(Sender: TObject); begin res.Caption:= IntToStr(tree.GetWords); end; function TMainForm.getInput: String; begin result:= inputEdt.Text; end; procedure TMainForm.FormDestroy(Sender: TObject); begin tree.Free; end; procedure TMainForm.inputEdtKeyPress(Sender: TObject; var Key: Char); begin if (key >=' ') and ((Key<'a') or (Key>'z')) then key := #0; end; end.
unit BaseStockApp; interface uses BaseWinApp, BaseApp, StockAppPath, db_dealitem; type TBaseStockAppData = record StockItemDB: TDBDealItem; end; TBaseStockApp = class(TBaseWinApp) protected fBaseStockAppData: TBaseStockAppData; function GetPath: TBaseAppPath; override; function GetStockAppPath: TStockAppPath; public constructor Create(AppClassId: AnsiString); override; destructor Destroy; override; procedure InitializeDBStockItem(AIsLoadDBStockItemDic: Boolean = True); property StockItemDB: TDBDealItem read fBaseStockAppData.StockItemDB; property StockAppPath: TStockAppPath read GetStockAppPath; end; var GlobalBaseStockApp: TBaseStockApp = nil; implementation uses db_dealitem_Load; constructor TBaseStockApp.Create(AppClassId: AnsiString); begin inherited; FillChar(fBaseStockAppData, SizeOf(fBaseStockAppData), 0); GlobalBaseStockApp := Self; end; destructor TBaseStockApp.Destroy; begin if GlobalBaseStockApp = Self then GlobalBaseStockApp := nil; if nil <> fBaseStockAppData.StockItemDB then begin fBaseStockAppData.StockItemDB.Free; fBaseStockAppData.StockItemDB := nil; end; inherited; end; function TBaseStockApp.GetPath: TBaseAppPath; begin Result := GetStockAppPath; end; function TBaseStockApp.GetStockAppPath: TStockAppPath; begin if nil = fBaseWinAppData.AppPath then fBaseWinAppData.AppPath := TStockAppPath.Create(Self); Result := TStockAppPath(fBaseWinAppData.AppPath); end; procedure TBaseStockApp.InitializeDBStockItem(AIsLoadDBStockItemDic: Boolean = True); begin if nil = fBaseStockAppData.StockItemDB then begin fBaseStockAppData.StockItemDB := TDBDealItem.Create; if AIsLoadDBStockItemDic then begin db_dealitem_Load.LoadDBStockItemDic(Self, fBaseStockAppData.StockItemDB); end; end; end; end.
{ uMAPGraphic class to manipulate MAP files for DIV like Programs Copyright (C) 2013 DCelso <- gmail.com Esta código es software libre; usted puede redistribuirlo y/o modificarlo bajo los términos de la GNU General Public License publicada por la Free Software Foundation; sea versión 2 de la licencia, o (a su opción) cualquier posterior versión. Este código se distribuye con la esperanza de que sea útil, pero SIN NINGUNA GARANTÍA, ni siquiera la garantía implícita de COMERCIABILIDAD o IDONEIDAD PARA UN DETERMINADO FIN. Consulte la GNU General Public License para obtener más detalles. Una copia de la Licencia Pública General de GNU está disponible en la World Wide Web en <http://www.gnu.org/copyleft/gpl.html>. También puede obtenerlo por escrito a la Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit uMAPGraphic; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Graphics, Dialogs, IntfGraphics, FileUtil,LCLIntf, LCLType; const lmMap = 0; lmFPG = 1; lmFont = 2; type MAPGamut = record numcolors : Byte; mode : Byte; editable: Byte; unused: Byte; colors :array[0..31] of Byte; end; PMAPGamut = ^MAPGamut; { TMAPGraphic } TMAPGraphic = class(TBitmap) private Magic: array [0 .. 2] of Char; MSDOSEnd: array [0 .. 3] of Byte; Version: Byte; // width : word; // Not needed, stored in TBitmap // height : word; // Not needed, stored in TBitmap FCode: DWord; FbitsPerPixel: Word; // to get faster this attribute. FCDIVFormat: Boolean; // to get faster this attribute. procedure loadDataBitmap(Stream: TStream); procedure writeDataBitmap(Stream: TStream); procedure RGB24toBGR16(var byte0, byte1: Byte; red, green, blue: Byte); procedure RGB24toRGB16(var byte0, byte1: Byte; red, green, blue: Byte); procedure BGR16toRGB24(byte0, byte1: Byte; var red, green, blue: Byte); procedure RGB16toRGB24(byte0, byte1: Byte; var red, green, blue: Byte); function FindColor(index, rc, gc, bc: Integer): Integer; procedure SetFormat(cdiv : Boolean); procedure SetBitsPerPixel(bpp: word); procedure setMagic; function getName : String; procedure setName(str:String); function getFPName : String; procedure setFPName(str:String); procedure copyPixels(srcBitmap: TBitmap; x, y : Integer); procedure setAlpha( value: Byte; in_rect : TRect ); procedure stringToArray(var inarray: array of char; str: string; len: integer); public data8bits: array of Byte; bPalette: array [0 .. 767] of Byte; Gamuts: array [0 .. 15] of MAPGamut; (*Temporalmente publicas*) GraphSize: LongInt; // Needed for FPG Graphics FName: array [0 .. 31] of Char; FFPName: array [0 .. 11] of Char; // Needed for FPG Graphics NCPoints: LongInt; (* fin Temporalmente publicas*) CPoints : array[0..high(Word)*2] of Word; (*Para soporte de Tipografías*) Width_Offset : longint; // Ancho Height_Offset : longint; // Alto Horizontal_Offset: longint; // Desplazamiento vertical Vertical_Offset: longint; // Desplazamiento vertical file_Offset : longint; // Desplazamiento en el archivo procedure LoadFromFile(const Filename: string); override; procedure LoadFromStream(Stream: TStream); override; procedure LoadFromStream(Stream: TStream; loadmode: byte ); procedure SaveToFile(const Filename: string); override; procedure SaveToStream(Stream: TStream); override; procedure SaveToStream(Stream: TStream; savemode: byte); procedure CreateBitmap(bmp_src : TBitmap); procedure simulate1bppIn32bpp; procedure simulate8bppIn32bpp; procedure colorToTransparent(color1 : tcolor ; splitTo16b :boolean = false); class function GetFileExtensions: string; override; published property CDIVFormat : Boolean read FCDIVFormat write SetFormat default False; property bitsPerPixel : Word read FbitsPerPixel write setBitsPerPixel default 32; property CPointsCount : Integer read NCPoints write NCPoints; property Name : String read getName write setName; property FPName : String read getFPName write setFPName; property Code : DWord read FCode write FCode default 1; class function test(filename: string): boolean;static ; end; implementation { TMAPGraphic } class function TMAPGraphic.GetFileExtensions: string; begin Result := 'map'; end; class function TMAPGraphic.test(filename: string): boolean; var Stream : TStream; tmpMagic: array [0 .. 2] of Char; tmpMSDOSEnd: array [0 .. 3] of Byte; tmpVersion: Byte; begin Result := False; if not FileExistsUTF8(filename) { *Converted from FileExists* } then Exit; try Stream := TFileStream.Create(filename, fmOpenRead); except Exit; end; try Stream.Read(tmpMagic, 3); Stream.Read(tmpMSDOSEnd , 4); Stream.Read(tmpVersion, 1); except Stream.free; Exit; end; // Ficheros de 1 bit if (tmpMagic[0] = 'm') and (tmpMagic[1] = '0') and (tmpMagic[2] = '1') and (tmpMSDOSEnd [0] = 26 ) and (tmpMSDOSEnd [1] = 13 ) and (tmpMSDOSEnd [2] = 10 ) and (tmpMSDOSEnd [3] = 0) then begin Result := True; end; // Ficheros de 8 bits para DIV2, FENIX y CDIV if (tmpMagic[0] = 'm') and (tmpMagic[1] = 'a') and (tmpMagic[2] = 'p') and (tmpMSDOSEnd [0] = 26 ) and (tmpMSDOSEnd [1] = 13 ) and (tmpMSDOSEnd [2] = 10 ) and (tmpMSDOSEnd [3] = 0) then begin Result := True; end; // Ficheros de 16 bits para FENIX if (tmpMagic[0] = 'm') and (tmpMagic[1] = '1') and (tmpMagic[2] = '6') and (tmpMSDOSEnd [0] = 26 ) and (tmpMSDOSEnd [1] = 13 ) and (tmpMSDOSEnd [2] = 10 ) and (tmpMSDOSEnd [3] = 0) then begin Result := True; end; // Ficheros de 16 bits para CDIV if (tmpMagic[0] = 'c') and (tmpMagic[1] = '1') and (tmpMagic[2] = '6') and (tmpMSDOSEnd [0] = 26 ) and (tmpMSDOSEnd [1] = 13 ) and (tmpMSDOSEnd [2] = 10 ) and (tmpMSDOSEnd [3] = 0) then begin Result := True; end; // Ficheros de 24 bits if (tmpMagic[0] = 'm') and (tmpMagic[1] = '2') and (tmpMagic[2] = '4') and (tmpMSDOSEnd [0] = 26 ) and (tmpMSDOSEnd [1] = 13 ) and (tmpMSDOSEnd [2] = 10 ) and (tmpMSDOSEnd [3] = 0) then begin Result := True; end; // Ficheros de 32 bits if (tmpMagic[0] = 'm') and (tmpMagic[1] = '3') and (tmpMagic[2] = '2') and (tmpMSDOSEnd [0] = 26 ) and (tmpMSDOSEnd [1] = 13 ) and (tmpMSDOSEnd [2] = 10 ) and (tmpMSDOSEnd [3] = 0) then begin Result := True; end; FreeAndNil(Stream); end; procedure TMAPGraphic.LoadFromFile(const Filename: string); var f: TFileStream; begin if not FileExistsUTF8(Filename) { *Converted from FileExists* } then Exit; try f := TFileStream.Create(Filename, fmOpenRead); except Exit; end; try LoadFromStream(f); finally f.Free; end; end; procedure TMAPGraphic.LoadFromStream(Stream: TStream); begin LoadFromStream(Stream,lmMap); end; procedure TMAPGraphic.LoadFromStream(Stream: TStream; loadmode: byte ); var tmpWidth: word; tmpHeight: word; intWidth: LongInt; intHeight: LongInt; i: integer; tmpNCPoints :word; begin if (loadmode = lmMap) OR (loadmode = lmFPG) then begin if loadmode = lmMap then begin Stream.Read(Magic, 3); Stream.Read(MSDOSEnd, 4); Stream.Read(Version, 1); FbitsPerPixel := 0; FCDIVFormat := False; // Ficheros de 1 bit if (Magic[0] = 'm') and (Magic[1] = '0') and (Magic[2] = '1') and (MSDOSEnd[0] = 26) and (MSDOSEnd[1] = 13) and (MSDOSEnd[2] = 10) and (MSDOSEnd[3] = 0) then begin FbitsPerPixel := 0; end; // Ficheros de 8 bits para DIV2, FENIX y CDIV if (Magic[0] = 'm') and (Magic[1] = 'a') and (Magic[2] = 'p') and (MSDOSEnd[0] = 26) and (MSDOSEnd[1] = 13) and (MSDOSEnd[2] = 10) and (MSDOSEnd[3] = 0) then begin FbitsPerPixel := 8; end; // Ficheros de 16 bits para FENIX if (Magic[0] = 'm') and (Magic[1] = '1') and (Magic[2] = '6') and (MSDOSEnd[0] = 26) and (MSDOSEnd[1] = 13) and (MSDOSEnd[2] = 10) and (MSDOSEnd[3] = 0) then begin FbitsPerPixel := 16; end; // Ficheros de 16 bits para CDIV if (Magic[0] = 'c') and (Magic[1] = '1') and (Magic[2] = '6') and (MSDOSEnd[0] = 26) and (MSDOSEnd[1] = 13) and (MSDOSEnd[2] = 10) and (MSDOSEnd[3] = 0) then begin FbitsPerPixel := 16; end; // Ficheros de 24 bits if (Magic[0] = 'm') and (Magic[1] = '2') and (Magic[2] = '4') and (MSDOSEnd[0] = 26) and (MSDOSEnd[1] = 13) and (MSDOSEnd[2] = 10) and (MSDOSEnd[3] = 0) then begin FbitsPerPixel := 24; end; // Ficheros de 32 bits if (Magic[0] = 'm') and (Magic[1] = '3') and (Magic[2] = '2') and (MSDOSEnd[0] = 26) and (MSDOSEnd[1] = 13) and (MSDOSEnd[2] = 10) and (MSDOSEnd[3] = 0) then begin FbitsPerPixel := 32; end; Stream.Read(tmpWidth, 2); Stream.Read(tmpHeight, 2); Width := tmpWidth; Height := tmpHeight; end; Stream.Read(FCode, 4); if loadmode = lmFPG then begin Stream.Read(GraphSize,4); end; Stream.Read(FName, 32); if loadmode = lmFPG then begin Stream.Read(FFPName, 12); Stream.Read(intWidth, 4); Stream.Read(intHeight, 4); Width := intWidth; Height := intHeight; end; if (loadmode = lmMap) and (FbitsPerPixel = 8) then begin Stream.Read(bPalette, 768); Stream.Read(Gamuts, 576); for i := 0 to 767 do bPalette[i] := bPalette[i] shl 2; end; if loadmode = lmFPG then Stream.Read(ncpoints, 4) else begin Stream.Read(tmpNCPoints, 2); ncpoints:= tmpNCPoints; end; // Leemos los puntos de control del bitmap if ncpoints > 0 then begin Stream.Read(CPoints, ncpoints * 4); end; end; // Se carga la imagen resultante loadDataBitmap(Stream); end; procedure TMAPGraphic.loadDataBitmap(Stream: TStream); var lazBMP: TLazIntfImage; p_bytearray: PByteArray; i, j, k, z: integer; byte_line: array [0 .. 16383] of byte; lenLineBits: integer; lineBit: byte; bytesPerPixel: Word; begin // Se crea la imagen resultante PixelFormat := pf32bit; SetSize(Width, Height); bytesPerPixel:=FbitsPerPixel div 8; // Para usar en caso de un bit if FbitsPerPixel = 1 then begin lenLineBits := Width div 8; if (Width mod 8) <> 0 then lenLineBits := lenLineBits + 1; end; if FbitsPerPixel = 8 then SetLength(data8bits,Width*Height); lazBMP := CreateIntfImage; for k := 0 to Height - 1 do begin p_bytearray := lazBMP.GetDataLineStart(k); case FbitsPerPixel of 1: begin for j := 0 to lenLineBits - 1 do begin Stream.Read(lineBit, 1); for i := 0 to 7 do begin z := (j * 8) + i; if z < Width then begin if (lineBit and 128) = 128 then begin p_bytearray^[z * 4] := 255; p_bytearray^[(z * 4) + 1] := 255; p_bytearray^[(z * 4) + 2] := 255; p_bytearray^[(z * 4) + 3] := 255; end else begin p_bytearray^[z * 4] := 0; p_bytearray^[(z * 4) + 1] := 0; p_bytearray^[(z * 4) + 2] := 0; p_bytearray^[(z * 4) + 3] := 0; end; lineBit := lineBit shl 1; end else break; end; end; end; 8: begin Stream.Read(byte_line, Width * bytesPerPixel); for j := 0 to Width - 1 do begin data8bits[k*Width+j]:=byte_line[j]; p_bytearray^[j * 4] := bPalette[byte_line[j] * 3 + 2]; p_bytearray^[j * 4 + 1] := bPalette[byte_line[j] * 3 + 1]; p_bytearray^[j * 4 + 2] := bPalette[byte_line[j] * 3]; p_bytearray^[j * 4 + 3] := 255; if byte_line[j] = 0 then p_bytearray^[j * 4 + 3] := 0; end; end; 16: begin Stream.Read(byte_line, Width * bytesPerPixel); for j := 0 to Width - 1 do begin if FCDIVFormat then begin RGB16toRGB24(byte_line[j * 2 + 1], byte_line[j * 2], p_bytearray^[j * 4], p_bytearray^[(j * 4) + 1], p_bytearray^[(j * 4) + 2]); p_bytearray^[(j * 4) + 3] := 255; if ((p_bytearray^[j * 4] = $F8) and (p_bytearray^[j * 4 + 1] = 0) and (p_bytearray^[j * 4 + 2] = $F8)) then p_bytearray^[(j * 4) + 3] := 0; end else begin BGR16toRGB24(byte_line[j * 2 + 1], byte_line[j * 2], p_bytearray^[j * 4], p_bytearray^[(j * 4) + 1], p_bytearray^[(j * 4) + 2]); p_bytearray^[(j * 4) + 3] := 255; if (byte_line[j * 2 + 1] + byte_line[j * 2]) = 0 then p_bytearray^[(j * 4) + 3] := 0; end; end; end; 24: begin Stream.Read(byte_line, Width * bytesPerPixel); for j := 0 to Width - 1 do begin p_bytearray^[j * 4] := byte_line[j * 3]; p_bytearray^[j * 4 + 1] := byte_line[j * 3 + 1]; p_bytearray^[j * 4 + 2] := byte_line[j * 3 + 2]; p_bytearray^[j * 4 + 3] := 255; if (byte_line[j * 3 + 2] + byte_line[j * 3 + 1] + byte_line[j * 3]) = 0 then p_bytearray^[(j * 4) + 3] := 0; end; end; else // 32 bits Stream.Read(p_bytearray^, Width * bytesPerPixel) end; end; LoadFromIntfImage(lazBMP); lazBMP.Free; end; procedure TMAPGraphic.SaveToStream(Stream: TStream); begin saveToStream(Stream, lmMap); end; procedure TMAPGraphic.SaveToStream(Stream: TStream; savemode: byte); var i: word; aWidth, aHeight: word; wordNCPoints: Word; widthForFPG1: integer; begin if savemode=lmMap then begin MSDOSEnd[0] := 26; MSDOSEnd[1] := 13; MSDOSEnd[2] := 10; MSDOSEnd[3] := 0; Stream.Write(Magic, 3); Stream.Write(MSDOSEnd, 4); Stream.Write(Version, 1); aWidth := Width; aHeight := Height; Stream.Write(aWidth, 2); Stream.Write(aHeight, 2); end; if (savemode=lmFPG) OR (savemode=lmMap) then Stream.Write(FCode, 4); if savemode=lmFPG then begin if FbitsPerPixel = 1 then begin widthForFPG1 := Width; if (Width mod 8) <> 0 then widthForFPG1 := widthForFPG1 + 8 - (Width mod 8); graphSize := (widthForFPG1 div 8) * Height + 64; end else begin graphSize := (Width * Height * (FbitsPerPixel div 8)) + 64; end; if (ncpoints > 0) then graphSize := graphSize + (ncpoints * 4); Stream.Write(graphSize, 4); end; if (savemode=lmFPG) OR (savemode=lmMap) then Stream.Write(FName, 32); if savemode=lmFPG then begin Stream.Write(FFPName, 12); Stream.Write(Width, 4); Stream.Write(Height, 4); end; if (savemode=lmMap) and (FbitsPerPixel = 8) then begin for i := 0 to 767 do bPalette[i] := bPalette[i] shr 2; Stream.Write(bPalette, 768); Stream.Write(Gamuts, 576); for i := 0 to 767 do bPalette[i] := bPalette[i] shl 2; end; if savemode=lmFPG then Stream.Write(ncpoints, 4); if savemode=lmMap then begin wordNCPoints := ncpoints; Stream.Write(wordNCPoints, 2); end; if (savemode=lmFPG) OR (savemode=lmMap) then if ncpoints > 0 then Stream.Write(CPoints, ncpoints * 4); writeDataBitmap(Stream); end; procedure TMAPGraphic.writeDataBitmap(Stream: TStream); var lazBMP: TLazIntfImage; byte_line: array [0 .. 16383] of byte; byteForFPG1: byte; insertedBits: integer; p_bytearray: PByteArray; j, k: word; bytes_per_pixel : word; index8bit : byte; begin lazBMP := CreateIntfImage; bytes_per_pixel:= FbitsPerPixel div 8; for k := 0 to Height - 1 do begin p_bytearray := lazBmp.GetDataLineStart(k); case FbitsPerPixel of 1: begin insertedBits := 0; byteForFPG1 := 0; for j := 0 to Width - 1 do begin if (p_bytearray^[j * 4] shr 7) = 1 then begin byteForFPG1 := byteForFPG1 or 1; // bit más alto en 8 bits end; insertedBits := insertedBits + 1; if (insertedBits = 8) then begin Stream.Write(byteForFPG1, 1); byteForFPG1 := 0; insertedBits := 0; end else byteForFPG1 := byteForFPG1 shl 1; end; if insertedBits > 0 then begin byteForFPG1 := byteForFPG1 shl (7 - insertedBits); Stream.Write(byteForFPG1, 1); end; end; 8: begin for j := 0 to Width - 1 do begin if Code = 101 then begin index8bit:=0; end; byte_line[j] := 0; index8bit:=0; if length(data8bits) >0 then index8bit:= data8bits[k*Width+j]; if p_bytearray^[j * 4 + 3] <> 0 then begin if (p_bytearray^[j * 4] = bPalette[index8bit*3]) and (p_bytearray^[j * 4 + 1] = bPalette[index8bit*3 +1]) and (p_bytearray^[j * 4 + 2] = bPalette[index8bit*3 +2 ] ) then byte_line[j]:= index8bit else byte_line[j] := FindColor(0, p_bytearray^[j * 4 + 2], p_bytearray^[j * 4 + 1], p_bytearray^[j * 4]); end; end; Stream.Write(byte_line, Width); end; 16: begin for j := 0 to Width - 1 do begin if FCDIVFormat then if p_bytearray^[j * 4 + 3] <> 0 then RGB24toRGB16(byte_line[j * 2 + 1], byte_line[j * 2], p_bytearray^[j * 4], p_bytearray^[j * 4 + 1], p_bytearray^[j * 4 + 2]) else RGB24toRGB16(byte_line[j * 2 + 1], byte_line[j * 2], 248, 0, 248) else begin byte_line[j * 2] := 0; byte_line[j * 2 + 1] := 0; if p_bytearray^[j * 4 + 3] <> 0 then RGB24toBGR16(byte_line[j * 2 + 1], byte_line[j * 2], p_bytearray^[j * 4], p_bytearray^[j * 4 + 1], p_bytearray^[j * 4 + 2]); end; end; Stream.Write(byte_line, Width * bytes_per_pixel); end; 24: begin for j := 0 to Width - 1 do begin byte_line[j * 3] := 0; byte_line[j * 3 + 1] := 0; byte_line[j * 3 + 2] := 0; if p_bytearray^[j * 4 + 3] <> 0 then begin byte_line[j * 3] := p_bytearray^[j * 4]; byte_line[j * 3 + 1] := p_bytearray^[j * 4 + 1]; byte_line[j * 3 + 2] := p_bytearray^[j * 4 + 2]; end; end; Stream.Write(byte_line, Width * bytes_per_pixel); end; else // 32 bits begin Stream.Write(p_bytearray^, Width * bytes_per_pixel); end; end; end; lazBMP.Free; end; function TMAPGraphic.FindColor(index, rc, gc, bc: integer): integer; var dif_colors, temp_dif_colors, i: word; begin dif_colors := 800; Result := 0; for i := index to 255 do begin temp_dif_colors := Abs(rc - bPalette[i * 3]) + Abs(gc - bPalette[(i * 3) + 1]) + Abs(bc - bPalette[(i * 3) + 2]); if temp_dif_colors <= dif_colors then begin Result := i; dif_colors := temp_dif_colors; if dif_colors = 0 then Exit; end; end; end; procedure TMAPGraphic.SaveToFile(const Filename: string); var f: TFileStream; begin f := TFileStream.Create(filename, fmCreate); SaveToStream(f); f.Free; end; // Calcula las componentes RGB almacenadas en 2 bytes como BGR procedure TMAPGraphic.BGR16toRGB24(byte0, byte1: byte; var red, green, blue: byte); begin blue := byte0 and $F8; // me quedo 5 bits 11111000 green := (byte0 shl 5) or ((byte1 and $E0) shr 3); // me quedo 3 bits de byte0 y 3 bits de byte 1 (11100000) red := byte1 shl 3; // me quedo 5 bits end; // Calcula las componentes RGB almacenadas en 2 bytes como RGB procedure TMAPGraphic.RGB16toRGB24(byte0, byte1: byte; var red, green, blue: byte); begin red := byte0 and $F8; // me quedo 5 bits 11111000 green := (byte0 shl 5) or ((byte1 and $E0) shr 3); // me quedo 3 bits de byte0 y 3 bits de byte 1 (11100000) blue := byte1 shl 3; // me quedo 5 bits end; // Calcula las componentes BGR almacenandolas en 2 bytes como BGR procedure TMAPGraphic.RGB24toBGR16(var byte0, byte1: byte; red, green, blue: byte); begin // F8 = 11111000 // 1C = 00011100 byte0 := (blue and $F8) or (green shr 5); byte1 := ((green and $1C) shl 3) or (red shr 3); end; // Establece las componentes RGB almacenandolas en 2 bytes como RGB procedure TMAPGraphic.RGB24toRGB16(var byte0, byte1: byte; red, green, blue: byte); begin // F8 = 11111000 // 1C = 00011100 byte0 := (red and $F8) or (green shr 5); byte1 := ((green and $1C) shl 3) or (blue shr 3); end; procedure TMAPGraphic.SetFormat(cdiv : Boolean); begin FCDIVFormat:=cdiv; if cdiv then FbitsPerPixel:=16; setMagic; end; procedure TMAPGraphic.setMagic; var strBpp :String; begin if FCDIVFormat then begin magic[0]:='c'; end else begin magic[0]:='m'; end; if FbitsPerPixel = 8 then begin magic[1]:='a'; magic[2]:='p'; end else begin strBpp:= Format('%.2d',[FbitsPerPixel]); magic[1]:=strBpp[1]; magic[2]:=strBpp[2]; end; end; procedure TMAPGraphic.SetBitsPerPixel(bpp: word); begin FbitsPerPixel:=bpp; if FCDIVFormat then FbitsPerPixel:=16; setMagic; end; function TMAPGraphic.getName : String; var i : integer; begin result:=''; i:=0; while ( FName[i] <>char(0) ) and (i<32) do begin result:= result+FName[i]; i:=i+1; end; end; function TMAPGraphic.getFPName : String; var i : integer; begin result:=''; i:=0; while ( FFPName[i] <>char(0) ) and (i<12) do begin result:= result+FFPName[i]; i:=i+1; end; end; procedure TMAPGraphic.setName(str:String); begin stringToArray(FName,str,32); end; procedure TMAPGraphic.setFPName(str:String); begin stringToArray(FFPName,str,12); end; procedure TMAPGraphic.copyPixels(srcBitmap: TBitmap; x, y : Integer); var dstLazBitmap: TLazIntfImage; srcLazBitmap: TLazIntfImage; begin dstLazBitmap:=CreateIntfImage; srcLazBitmap:=srcBitmap.CreateIntfImage; dstLazBitmap.CopyPixels(srcLazBitmap,x,y); srcLazBitmap.free; LoadFromIntfImage(dstLazBitmap); dstLazBitmap.free; end; procedure TMAPGraphic.CreateBitmap(bmp_src : TBitmap); begin PixelFormat:=pf32bit; SetSize(bmp_src.Width, bmp_src.Height); CopyPixels(bmp_src,0,0); if bmp_src.PixelFormat<>pf32bit then setAlpha(255,Rect(0,0,Width,Height)); case FbitsPerPixel of 1: begin simulate1bppIn32bpp; end; 8: begin simulate8bppIn32bpp; end; 16: begin if FCDIVFormat then colorToTransparent(clFuchsia,true ) else colorToTransparent(clBlack,true ); end; 24: begin colorToTransparent(clBlack ); end; end; end; procedure TMAPGraphic.setAlpha( value: Byte; in_rect : TRect ); var lazBitmap: TLazIntfImage; k, j :integer; ppixel : PRGBAQuad; begin lazBitmap:= CreateIntfImage; for k := in_rect.top to in_rect.Bottom -1 do begin ppixel := lazBitmap.GetDataLineStart(k); for j := in_rect.Left to in_rect.Right - 1 do ppixel[j].Alpha := value; end; LoadFromIntfImage(lazBitmap); lazBitmap.free; end; procedure TMAPGraphic.simulate1bppIn32bpp; var lazBMP: TLazIntfImage; rgbaLine : PRGBAQuad; i, j : LongInt; begin lazBMP:=CreateIntfImage; for j := 0 to height - 1 do begin rgbaLine := lazBMP.GetDataLineStart(j); for i := 0 to width - 1 do begin if ((rgbaLine[i].Alpha shr 7) =1) and ((rgbaLine[i].Red shr 7) = 1) then begin rgbaLine[i].Red := 255; rgbaLine[i].Green := 255; rgbaLine[i].Blue := 255; rgbaLine[i].Alpha:= 255; end else begin rgbaLine[i].Red := 0; rgbaLine[i].Green := 0; rgbaLine[i].Blue := 0; rgbaLine[i].Alpha:= 0; end; end; end; LoadFromIntfImage(lazBMP); lazBMP.free; end; procedure TMAPGraphic.simulate8bppIn32bpp; var lazBMP_src: TLazIntfImage; p_src : PRGBAQuad; i, j : LongInt; pal_index : integer; begin lazBMP_src:= CreateIntfImage; for j := 0 to height - 1 do begin p_src := lazbmp_src.GetDataLineStart(j); for i := 0 to width - 1 do begin pal_index := FindColor(0, p_src[i].Red , p_src[i].Green, p_src[i].Blue); p_src[i].red := bpalette[pal_index * 3]; p_src[i].green := bpalette[(pal_index * 3)+1]; p_src[i].blue := bpalette[(pal_index * 3)+2]; if ((p_src[i].Alpha shr 7) = 1) and (pal_index<>0) then p_src[i].Alpha:=255 else p_src[i].Alpha:=0; end; end; LoadFromIntfImage(lazBMP_src); lazBMP_src.free; end; procedure TMAPGraphic.colorToTransparent( color1 : tcolor ; splitTo16b :boolean = false); var lazBMP_src: TLazIntfImage; p_src : PRGBAQuad; i, j : LongInt; curColor: TColor; begin if splitTo16b then color1:=RGB(GetRValue(color1) and $F8, GetGValue(color1) and $FC,GetBValue(color1) and $F8); lazBMP_src:= CreateIntfImage; for j := 0 to height - 1 do begin p_src := lazbmp_src.GetDataLineStart(j); for i := 0 to width - 1 do begin if splitTo16b then begin p_src[i].red := (p_src[i].red and $F8); p_src[i].green := (p_src[i].green and $FC); p_src[i].blue := (p_src[i].blue and $F8); end; curColor:=RGB(p_src[i].red, p_src[i].green,p_src[i].Blue ); if ((p_src[i].Alpha shr 7 )= 1 ) and (curColor <> color1) then p_src[i].Alpha := 255 else p_src[i].Alpha := 0; end; end; LoadFromIntfImage(lazBMP_src); lazBMP_src.free; end; procedure TMAPGraphic.stringToArray(var inarray: array of char; str: string; len: integer); var i: integer; begin for i := 0 to len - 1 do begin if i >= length(str) then inarray[i] := char(0) else inarray[i] := str[i + 1]; end; end; (* procedure TMAPGraphic.Assign(Source: TPersistent); var bmpIntf : TLazIntfImage; bmpIntf2 : TLazIntfImage; begin if Source is TBitmap then begin bmpIntf:=CreateIntfImage; bmpIntf2:=TBitmap(Source).CreateIntfImage; bmpIntf.CopyPixels(bmpIntf2,0,0); LoadFromIntfImage(bmpIntf); FreeAndNil(bmpIntf); FreeAndNil(bmpIntf2); end else inherited Assign(Source); end; *) initialization TPicture.RegisterFileFormat('map','DIV MAP Images', TMAPGraphic); end.
unit FMX.Rating; interface uses {$IFDEF UseNativeDraw} FMX.Graphics.Native, {$ENDIF}System.SysUtils, System.Classes, System.Types, System.UITypes, System.Math, System.Math.Vectors, FMX.Types, FMX.Controls, FMX.Graphics; type TOnRatingChange = procedure(Sender: TObject; AValue: Double) of object; TRatingColors = class(TPersistent) private FBackground: TBrush; FStroke: TStrokeBrush; FStarColor: TBrush; FOnChanged: TNotifyEvent; procedure SetBackground(const Value: TBrush); procedure SetStroke(const Value: TStrokeBrush); procedure SetStarColor(const Value: TBrush); procedure SetOnChanged(const Value: TNotifyEvent); { private declarations } protected { protected declarations } procedure DoChanged(Sender: TObject); public { public declarations } constructor Create; virtual; destructor Destroy; override; published { published declarations } property Background: TBrush read FBackground write SetBackground; property Stroke: TStrokeBrush read FStroke write SetStroke; property StarColor: TBrush read FStarColor write SetStarColor; property OnChanged: TNotifyEvent read FOnChanged write SetOnChanged; end; TRating = class(TControl) private FStarCount: Integer; FStarDistance: Double; FStarScale: Double; FMouseCapturing: Boolean; FSteps: Double; FOnRatingChange: TOnRatingChange; FColors: TRatingColors; FRating: Double; FStarsPathData: TPathData; procedure SetStarCount(const Value: Integer); procedure SetStarDistance(const Value: Double); procedure SetStarScale(const Value: Double); procedure SetSteps(const Value: Double); procedure SetOnRatingChange(const Value: TOnRatingChange); procedure SetColors(const Value: TRatingColors); procedure SetRating(const Value: Double); { Private declarations } protected { Protected declarations } procedure ColorsChanged(Sender: TObject); procedure CreateStars; procedure Paint; override; function CalcWidth: Double; function CalcHeight: Double; procedure CalcRatingFromMouse(X: Single); procedure DoStarChanged; procedure DoRatingChanged; procedure Resize; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override; procedure MouseMove(Shift: TShiftState; X, Y: Single); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override; public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; published { Published declarations } property Align; property Anchors; property ClipChildren; property ClipParent; property Cursor; property DragMode; property EnableDragHighlight; property Enabled; property Locked; property Height; property HitTest default False; property Padding; property Opacity; property Margins; property PopupMenu; property Position; property RotationAngle; property RotationCenter; property Scale; property Size; property TouchTargetExpansion; property Visible; property Width; property TabOrder; property TabStop; { Events } property OnPainting; property OnPaint; property OnResize; property OnResized; { Drag and Drop events } property OnDragEnter; property OnDragLeave; property OnDragOver; property OnDragDrop; property OnDragEnd; { Mouse events } property OnClick; property OnDblClick; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnMouseWheel; property OnMouseEnter; property OnMouseLeave; property StarCount: Integer read FStarCount write SetStarCount stored True nodefault; property StarDistance: Double read FStarDistance write SetStarDistance stored True nodefault; property StarScale: Double read FStarScale write SetStarScale stored True nodefault; property Steps: Double read FSteps write SetSteps stored True nodefault; property Rating: Double read FRating write SetRating stored True nodefault; property OnRatingChange: TOnRatingChange read FOnRatingChange write SetOnRatingChange; property Colors: TRatingColors read FColors write SetColors; end; procedure Register; const StarData = 'M 561.735,32.327 L 689.890,303.844 L 976.452,347.384 C 1021.944,354.296 1040.108,412.75' + '1 1007.190,446.302 L 799.832,657.649 L 848.783,956.075 C 856.553,1003.450 808.998,1039.' + '577 768.309,1017.210 L 512.000,876.312 L 255.691,1017.210 C 215.002,1039.577 167.447,10' + '03.450 175.217,956.075 L 224.168,657.649 L 16.810,446.302 C -16.108,412.751 2.056,354.2' + '96 47.548,347.384 L 334.110,303.844 L 462.265,32.327 C 482.609,-10.776 541.391,-10.776 ' + '561.735,32.327 Z'; implementation procedure Register; begin RegisterComponents('Material Design', [TRating]); end; { TRating } function TRating.CalcHeight: Double; begin Result := (32 * FStarScale); end; procedure TRating.CalcRatingFromMouse(X: Single); var StarWidth: Double; StarTrunc: Integer; DistanceCount: Double; TempRating: Double; PosX: Single; begin StarWidth := (32 * FStarScale); PosX := X; if FColors.Stroke.Kind <> TBrushKind.None then PosX := PosX - (Self.Colors.Stroke.Thickness / 2 * FStarScale); StarTrunc := Trunc(PosX * 1 / (StarWidth + FStarDistance * FStarScale)); DistanceCount := PosX - StarTrunc * StarWidth - StarTrunc * FStarDistance * FStarScale; if Trunc(StarTrunc + (DistanceCount / StarWidth)) - StarTrunc > 0 then TempRating := Trunc(StarTrunc + (DistanceCount / StarWidth)) else TempRating := StarTrunc + (DistanceCount / StarWidth); Rating := TempRating; Repaint; end; function TRating.CalcWidth: Double; begin Result := (32 * FStarScale * StarCount) + (StarDistance * FStarScale * (StarCount - 1)); end; procedure TRating.ColorsChanged(Sender: TObject); begin DoStarChanged; Repaint; end; constructor TRating.Create(AOwner: TComponent); begin inherited; AutoCapture := True; FMouseCapturing := False; FStarScale := 1; FStarDistance := 5; FStarCount := 5; FRating := 5; FSteps := 0.01; FColors := TRatingColors.Create; FColors.OnChanged := ColorsChanged; FStarsPathData := TPathData.Create; DoStarChanged; CreateStars; end; procedure TRating.CreateStars; var StarPathData: TPathData; I: Integer; CurrDistance: Double; begin CurrDistance := (32 * FStarScale) + (StarDistance * FStarScale); StarPathData := TPathData.Create; StarPathData.Data := StarData; StarPathData.FitToRect(TRectF.Create(0, 0, 32 * FStarScale, 32 * FStarScale)); FStarsPathData.Clear; try for I := 0 to StarCount - 1 do begin FStarsPathData.Data := FStarsPathData.Data + StarPathData.Data; StarPathData.Translate(CurrDistance, 0); end; finally StarPathData.Free; end; end; destructor TRating.Destroy; begin FColors.Free; FStarsPathData.Free; inherited; end; procedure TRating.DoRatingChanged; begin if Assigned(FOnRatingChange) then FOnRatingChange(Self, FRating); end; procedure TRating.DoStarChanged; var TempWidth, TempHeight: Single; begin TempWidth := CalcWidth; TempHeight := CalcHeight; if FColors.Stroke.Kind <> TBrushKind.None then begin TempWidth := TempWidth + FColors.Stroke.Thickness * FStarScale; TempHeight := TempHeight + FColors.Stroke.Thickness * FStarScale; end; Self.Width := TempWidth; Self.Height := TempHeight; end; procedure TRating.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin inherited; FMouseCapturing := True; end; procedure TRating.MouseMove(Shift: TShiftState; X, Y: Single); begin inherited; if not FMouseCapturing then exit; CalcRatingFromMouse(X); end; procedure TRating.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); var StarWidth: Double; StarTrunc: Integer; DistanceCount: Double; TempRating: Double; begin inherited; FMouseCapturing := False; CalcRatingFromMouse(X); end; procedure TRating.Paint; var I: Integer; TempPathData: TPathData; TotalFill: Double; Save: TCanvasSaveState; begin inherited; if (csDesigning in ComponentState) and not Locked then DrawDesignBorder; try if FRating > 0 then TotalFill := (32 * FStarScale) * (FRating) + (Ceil(FRating) - 1) * (FStarDistance * FStarScale) else TotalFill := 0; if FColors.Stroke.Kind <> TBrushKind.None then TotalFill := TotalFill + FColors.Stroke.Thickness / 2 * FStarScale; TempPathData := TPathData.Create; try TempPathData.Data := FStarsPathData.Data; {$IFDEF UseNativeDraw}Canvas.NativeDraw(TRectF.Create(0,0,self.Width, self.Height), procedure begin {$ENDIF} if FColors.Stroke.Kind <> TBrushKind.None then TempPathData.Translate(FColors.Stroke.Thickness / 2 * FStarScale, FColors.Stroke.Thickness / 2 * FStarScale); Canvas.BeginScene; Canvas.Fill.Assign(FColors.Background); Canvas.Stroke.Assign(FColors.Stroke); Canvas.Stroke.Thickness := FColors.Stroke.Thickness * FStarScale; if not GlobalUseGPUCanvas then Canvas.DrawPath(TempPathData, Opacity); Canvas.FillPath(TempPathData, Opacity); Canvas.EndScene; Save := Canvas.SaveState; Canvas.IntersectClipRect(TRectF.Create(0, 0, TotalFill, Height)); Canvas.Fill.Assign(FColors.StarColor); Canvas.FillPath(TempPathData, Opacity); Canvas.RestoreState(Save); {$IFDEF UseNativeDraw} end); {$ENDIF} finally TempPathData.Free end; finally end; end; procedure TRating.Resize; begin inherited; DoStarChanged; end; procedure TRating.SetColors(const Value: TRatingColors); begin FColors := Value; end; procedure TRating.SetOnRatingChange(const Value: TOnRatingChange); begin FOnRatingChange := Value; end; procedure TRating.SetRating(const Value: Double); var NewValue: Double; OldValue: Double; begin OldValue := FRating; if ((Frac(Value) - (Trunc(Frac(Value) / FSteps) * FSteps)) > FSteps / 3) then NewValue := Trunc(Value) + Trunc(Frac(Value) / FSteps) * FSteps + FSteps else NewValue := Trunc(Value) + Trunc(Frac(Value) / FSteps) * FSteps; NewValue := RoundTo(NewValue, -2); if NewValue <= 0 then FRating := 0 else if NewValue > FStarCount then FRating := FStarCount else FRating := NewValue; Repaint; if NewValue <> OldValue then DoRatingChanged; end; procedure TRating.SetStarCount(const Value: Integer); begin FStarCount := Value; CreateStars; SetRating(FRating); DoStarChanged; end; procedure TRating.SetStarDistance(const Value: Double); begin FStarDistance := Value; CreateStars; DoStarChanged; end; procedure TRating.SetStarScale(const Value: Double); begin FStarScale := Value; CreateStars; DoStarChanged; end; procedure TRating.SetSteps(const Value: Double); begin if Value > 1 then FSteps := 1 else if Value <= 0 then FSteps := 0.01 else FSteps := Value; end; { TRatingColors } constructor TRatingColors.Create; begin FBackground := TBrush.Create(TBrushKind.Solid, $FFEEEEEE); FStarColor := TBrush.Create(TBrushKind.Solid, $FFFFC107); FStroke := TStrokeBrush.Create(TBrushKind.Solid, $FF858585); FStroke.OnChanged := DoChanged; FStarColor.OnChanged := DoChanged; FBackground.OnChanged := DoChanged; end; destructor TRatingColors.Destroy; begin FBackground.Free; FStarColor.Free; FStroke.Free; inherited; end; procedure TRatingColors.DoChanged(Sender: TObject); begin if Assigned(FOnChanged) then FOnChanged(Self); end; procedure TRatingColors.SetBackground(const Value: TBrush); begin FBackground := Value; end; procedure TRatingColors.SetOnChanged(const Value: TNotifyEvent); begin FOnChanged := Value; end; procedure TRatingColors.SetStarColor(const Value: TBrush); begin FStarColor := Value; end; procedure TRatingColors.SetStroke(const Value: TStrokeBrush); begin FStroke := Value; end; end.
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls; type TForm1 = class(TForm) Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; LanguageButton: TButton; LoadedLabel: TLabel; Label5: TLabel; procedure FormCreate(Sender: TObject); procedure LanguageButtonClick(Sender: TObject); private procedure UpdateStrings; end; var Form1: TForm1; implementation {$R *.fmx} uses NtBase, NtResource, NtResourceString, FMX.NtLanguageDlg, FMX.NtTranslator; procedure TForm1.UpdateStrings; resourcestring SSample = 'This is a sample'; //loc This is a comment SNone = 'None'; SResource = 'Resource:'; SFile = 'File:'; SDirectory = 'Directory:'; var i: Integer; str: String; directories: TStringDynArray; begin Label2.Text := SSample; directories := NtResources.ResourceDirectories; str := directories[0]; for i := 1 to Length(directories) - 1 do str := str + sLineBreak + directories[i]; Label3.Text := str; case NtResources.TranslationSource of tsNone: str := SNone; tsResource: str := SResource; tsFile: str := SFile; tsDirectory: str := SDirectory; end; LoadedLabel.Text := Format('%s %s', [str, NtResources.TranslationSourceValue]); end; procedure TForm1.FormCreate(Sender: TObject); resourcestring SEnglish = 'English'; SFinnish = 'Finnish'; SGerman = 'German'; SFrench = 'French'; SJapanese = 'Japanese'; begin NtResources.Add('English', 'English', SEnglish, 'en'); NtResources.Add('Finnish', 'suomi', SFinnish, 'fi'); NtResources.Add('German', 'Deutsch', SGerman, 'de'); NtResources.Add('French', 'français', SFrench, 'fr'); NtResources.Add('Japanese', '日本語', SJapanese, 'ja'); if ParamCount > 0 then NtResources.LanguageId := ParamStr(1); _T(Self); UpdateStrings; end; procedure TForm1.LanguageButtonClick(Sender: TObject); begin if TNtLanguageDialog.Select('en', lnBoth) then UpdateStrings; end; initialization // Here you can specify a custom directory where you translation file(s) is located //NtResources.ResourcePath := 'D:\NT\Deploy\Samples\Delphi\FMX\ExternalFile\NtLangRes.ntres'; end.
unit ProductionModel; interface uses connection, Ragna, System.JSON, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.ConsoleUI.Wait, Data.DB, FireDAC.Comp.Client, FireDAC.Phys.PG, FireDAC.Phys.PGDef, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet, Horse, System.SysUtils, Dataset.serialize, System.Classes, System.NetEncoding, Soap.EncdDecd; Function save(productionJson: String): TFDQuery; Function findByProducerArea(id: integer): TFDQuery; function findByPk(id: integer): TFDQuery; function update(id: integer; productionJson: string ): TFDQuery; function delete(id: integer ): boolean; function findAll( page: integer; limit: integer; id_produtor: integer; tp_prod: string; area: string; data_inicio: string; data_fim: string; var tot_page: integer): TFDQuery; overload; function findAll( tp_prod: string; area: string; data_inicio: string; id_produtor: integer; data_fim: string; var tot_page: integer ): TFDQuery; overload; implementation function findAll( tp_prod: string; area: string; data_inicio: string; id_produtor: integer; data_fim: string; var tot_page: integer ): TFDQuery; begin DMConnection := TDMConnection.Create(DMConnection); const Production = DMConnection.Registro_producao_area; Production.close; Production.sql.clear; Production.sql.add('select '); Production.sql.add(' ap.nome_area, '); Production.sql.add(' um.nome, '); Production.sql.add(' um.sigla, '); Production.sql.add(' rp.* '); Production.sql.add('from '); Production.sql.add(' registro_producao rp inner join '); Production.sql.add(' areas_producao ap on '); Production.sql.add(' ap.id = rp.id_area_prod inner join'); Production.sql.add(' unidade_medida um on '); Production.sql.add(' um.id = rp.id_unidade '); if area <> '' then Production.sql.add(' and rp.id_area_prod = '+ area); if tp_prod <> '' then Production.sql.add(' and rp.tipo_prod = '+ QuotedStr(tp_prod)); if ((data_inicio <> '') and (data_fim <> '')) then Production.sql.add(' and rp.data_producao between ' + QuotedStr(data_inicio) + ' and ' + QuotedStr(data_fim) ); Production.sql.add( ' where ap.id_produtor = ' + intToStr(id_produtor)); Production.Open; Result := Production; end; function findAll( page: integer; limit: integer; id_produtor: integer; tp_prod: string; area: string; data_inicio: string; data_fim: string; var tot_page: integer): TFDQuery; begin DMConnection := TDMConnection.Create(DMConnection); const Production = DMConnection.Registro_producao_area; Production.close; Production.sql.clear; Production.sql.add('select '); Production.sql.add(' ap.nome_area, '); Production.sql.add(' um.nome, '); Production.sql.add(' um.sigla, '); Production.sql.add(' rp.* '); Production.sql.add('from '); Production.sql.add(' registro_producao rp inner join '); Production.sql.add(' areas_producao ap on '); Production.sql.add(' ap.id = rp.id_area_prod inner join'); Production.sql.add(' unidade_medida um on '); Production.sql.add(' um.id = rp.id_unidade '); if area <> '' then Production.sql.add(' and rp.id_area_prod = '+ area); if tp_prod <> '' then Production.sql.add(' and rp.tipo_prod = '+ QuotedStr(tp_prod)); if ((data_inicio <> '') and (data_fim <> '')) then Production.sql.add(' and rp.data_producao between ' + QuotedStr(data_inicio) + ' and ' + QuotedStr(data_fim) ); Production.sql.add( ' where ap.id_produtor = ' + intToStr(id_produtor)); Production.open; var tot := Trunc((Production.RowsAffected/limit)) < (Production.RowsAffected/limit); if tot then tot_page := Trunc(Production.RowsAffected/limit) + 1 else tot_page := Trunc(Production.RowsAffected/limit); Production.close; var initial := page - 1; initial := initial * limit; Production.SQL.Add('ORDER BY '); Production.SQL.Add('rp.id OFFSET :offset ROWS FETCH NEXT :limit ROWS ONLY;'); Production.ParamByName('offset').AsInteger := initial; Production.ParamByName('limit').AsInteger := limit; Production.Open; Result := Production; end; Function save(productionJson: string): TFDQuery; begin DMConnection := TDMConnection.Create(DMConnection); var Production := DMConnection.Registro_Producao; var jsonObj := TJSONObject .ParseJSONValue(TEncoding.UTF8.GetBytes(productionJson), 0) as TJSONObject; Production.New(jsonObj).OpenUp; Result := Production; end; function update(id: integer; productionJson: string ): TFDQuery; begin DMConnection := TDMConnection.Create(DMConnection); const Production = DMConnection.Registro_Producao; var jsonObj := TJSONObject .ParseJSONValue(TEncoding.UTF8.GetBytes(productionJson), 0) as TJSONObject; Production.where('id').Equals(id).OpenUp; Production.MergeFromJSONObject(jsonObj); Result := Production; end; function findByPk(id: integer): TFDQuery; begin DMConnection := TDMConnection.Create(DMConnection); var Production := DMConnection.Registro_Producao; Production.where('id').equals(id).OpenUp; Result := Production; end; Function findByProducerArea(id: integer): TFDQuery; begin DMConnection := TDMConnection.Create(DMConnection); var Production := DMConnection.Registro_Producao; Production.where('id_area_prod').equals(id).OpenUp; Result := Production; end; function delete(id: integer ): boolean; begin DMConnection := TDMConnection.Create(DMConnection); const Production = DMConnection.Registro_Producao; try Production.Remove(Production.FieldByName('id'), id).OpenUp; result:= true; except on E:Exception do result:= false; end; end; end.
unit ScaledGraphicDrawer_MainUnit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Imaging.pngimage, Vcl.Direct2D, Vcl.ExtCtrls, Vcl.ComCtrls; type TScaledGraphicDrawer_MainForm = class(TForm) PaintBox1: TPaintBox; Image1: TImage; Label1: TLabel; Label2: TLabel; RadioGroup1: TRadioGroup; TopPnl: TPanel; LeftPnl: TPanel; Panel3: TPanel; RightPnl: TPanel; Panel5: TPanel; PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; BMP: TImage; Label3: TLabel; RadioGroup2: TRadioGroup; procedure FormCreate(Sender: TObject); procedure PaintBox1Paint(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure RadioGroup1Click(Sender: TObject); procedure FormResize(Sender: TObject); procedure RadioGroup2Click(Sender: TObject); private { Private declarations } Buffer: TBitmap; public { Public declarations } end; var ScaledGraphicDrawer_MainForm: TScaledGraphicDrawer_MainForm; implementation {$R *.dfm} procedure TScaledGraphicDrawer_MainForm.FormCreate(Sender: TObject); begin Buffer := TBitmap.Create; Buffer.Assign(Image1.Picture.Graphic); Buffer.DisableScaledDrawer; Image1.Picture.Graphic.DisableScaledDrawer; end; procedure TScaledGraphicDrawer_MainForm.FormDestroy(Sender: TObject); begin Buffer.Free; end; procedure TScaledGraphicDrawer_MainForm.FormResize(Sender: TObject); begin LeftPnl.Width := Width div 2; RightPnl.Width := Width div 2; end; procedure TScaledGraphicDrawer_MainForm.PaintBox1Paint(Sender: TObject); begin PaintBox1.Canvas.StretchDraw(Rect(0, 0, PaintBox1.Width, PaintBox1.Height), Buffer); end; procedure TScaledGraphicDrawer_MainForm.RadioGroup1Click(Sender: TObject); begin case RadioGroup1.ItemIndex of 0: begin Buffer.EnableScaledDrawer(TD2DScaledGraphicDrawer); Image1.Picture.Graphic.EnableScaledDrawer(TD2DScaledGraphicDrawer); end; 1: begin Buffer.EnableScaledDrawer(TWICScaledGraphicDrawer); Image1.Picture.Graphic.EnableScaledDrawer(TWICScaledGraphicDrawer); end; 2: begin Buffer.DisableScaledDrawer; Image1.Picture.Graphic.DisableScaledDrawer; end; end; Image1.Repaint; PaintBox1.Repaint; end; procedure TScaledGraphicDrawer_MainForm.RadioGroup2Click(Sender: TObject); begin case RadioGroup2.ItemIndex of 0: BMP.Picture.Graphic.EnableScaledDrawer(TWICScaledGraphicDrawer); 1: BMP.Picture.Graphic.EnableScaledDrawer(TD2DScaledGraphicDrawer); 2: BMP.Picture.Graphic.DisableScaledDrawer; end; BMP.Repaint; end; end.
unit nsTypes; interface uses Winapi.Windows, System.Classes, Vcl.Controls, nsCrypt, nsGlobals, nsProcessFrm, nsMasks; type TWaitProgress = procedure(CurBlock, TotBlock: integer; var AClose: Boolean) of object; TCheckState = (csAll, csDelete, csRestore, csBackup); TItemState = (isNormal, isBackup, isBackupReplace, isBackupUpdate, isBackupNewVersion, isRestore, isRestoreToFolder, isDelete); TSendMail = (smNone, smOnFailure, smAlways); // 2.1 TSendMailContent = (mcComplete, mcFailed); TFileFormat = (fmProprietary, fmAsIs); TNSItem = class; TNSCollection = class; TNSProject = class(TComponent) private FItems: TNSCollection; FCrypt: TWinCrypt; FFileName: string; FProjPwd: string; FDisplayName: string; FHostName: string; FPassive: Boolean; FPort: string; FUserName: string; FMaxSize: cardinal; FPassword: string; FWasModified: Boolean; FStoreArchivePwd: Boolean; FHostDirName: string; FOpened: Boolean; FBackupMedia: TBackupMedia; FLocalFolder: string; FEncryptionMethod: TEncryptionMethod; FConnected: Boolean; FDefaultAction: TDefaultAction; FAutoMode: Boolean; FWriteLog: Boolean; FLogFile: TStringList; FKind: TProjectKind; // FIsRunning: Boolean; FNeedCrypting: Boolean; FAutoRefresh: Boolean; FSendLog: TSendMail; FIncMasks: TMaskItems; FExcMasks: TMaskItems; FCompressionLevel: byte; FDialupConnection: string; FHangUpOnCompleted: Boolean; FWaitForExtAppAfter: Boolean; FWaitForExtAppBefore: Boolean; FExtAppBefore: string; FExtAppAfter: string; FActiveVolumeIndex: integer; FActiveVolume: TNSProject; FTimeOutBefore: integer; FTimeOutAfter: integer; FAutoMangle: Boolean; FSyncMode: TSyncMode; FRestoring: Boolean; FRestoreCDDrive: string; FLastRunTime: TDateTime; FCDIndex: integer; FCDDrivePath: string; FCDErase: Boolean; FSendMailContect: TSendMailContent; FFileFormat: TFileFormat; FCDWriteable: Boolean; FBackupSize: int64; FMediaSize: int64; FAutoDialUp: Boolean; FNetPass: string; FNetUser: string; FNetPath: string; procedure SetProjPwd(const Value: string); function GetConnected: Boolean; procedure SetConnected(const Value: Boolean); procedure SetOpened(const Value: Boolean); function GetVolume(Index: integer): TNSProject; function GetVolumeCount: integer; function GetDisplayName: string; function GetVolumeIndex: integer; procedure SetActiveVolume(const Value: TNSProject); procedure SetActiveVolumeIndex(const Value: integer); procedure SetExcMasks(const Value: TMaskItems); procedure SetIncMasks(const Value: TMaskItems); procedure SetDisplayName(const Value: string); procedure SetKind(const Value: TProjectKind); procedure SetEncryptionMethod(const Value: TEncryptionMethod); procedure SetCompressionLevel(const Value: byte); procedure SetDefaultAction(const Value: TDefaultAction); procedure SetItems(const Value: TNSCollection); procedure SetAutoMangle(const Value: Boolean); procedure SetSyncMode(const Value: TSyncMode); function GetHostName: string; procedure SetLocalFolder(const Value: string); function GetIsCDMedia: Boolean; procedure SetFileFormat(const Value: TFileFormat); procedure SetNetPath(const Value: string); procedure SetNetUser(const Value: string); procedure SetHostDirName(const Value: string); protected HashValue: THashKey; FNasConnection: string; procedure ReadProjPwd(Reader: TReader); procedure WriteProjPwd(Writer: TWriter); procedure ReadPassword(Reader: TReader); procedure WritePassword(Writer: TWriter); procedure ReadNetPass(Reader: TReader); procedure WriteNetPass(Writer: TWriter); procedure DefineProperties(Filer: TFiler); override; function PackFile(const ANameInp: string; const ANameOut: string; var ASize: int64): Boolean; function UnPackFile(const ANameInp: string; const ANameOut: string; ANewHash: THashKey): Boolean; procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override; procedure AssignTo(Dest: TPersistent); override; // 2.1 // function InitWriting: Boolean; // function InitReading: Boolean; public FProgress: TfrmProcess; constructor Create(AOwner: TComponent); override; destructor Destroy; override; function OpenProject(const APassword: string): Boolean; function ConnectToMedia(const AWnd: HWnd): Boolean; function ReConnect: Boolean; procedure Disconnect; procedure ReInitCrypting; procedure Reset; procedure Refresh; function CloseProject: Boolean; function Rename(const ANewDisplayName: string): Boolean; function Move(const ANewLocation: string): Boolean; function GetNonProcCount(var ASize: int64): integer; function GetDeleteCount(var ASize: int64): integer; function GetBackupCount(var ASize: int64): integer; function GetRestoreCount(var ASize: int64): integer; function ProcessDelete: integer; function ProcessRestore: integer; function ProcessBackup: integer; // 2.1 function InitializeMedia(const AState: TCheckState): Boolean; function FinalizeMedia: Boolean; // procedure EraseCDMedia; function ImportCDMedia: Boolean; procedure KillProcessing; procedure StartLog; procedure EndLog; procedure TraceLog(const AOperation, AResult: string; const Rslt: Boolean); procedure LogMsg(const AMessage: string); function GetLog: TStrings; function CheckProject(ACheckFor: TCheckState): Boolean; function CheckVolumes(ACheckFor: TCheckState): Boolean; property Opened: Boolean read FOpened write SetOpened; property Connected: Boolean read GetConnected write SetConnected; function PathDelimiter: string; function IsValidExt(const AFileName: string): Boolean; procedure LoadFromStream(AStream: TStream); procedure SaveToStream(AStream: TStream); function LoadFromFile(const AFileName: string): Boolean; procedure SaveToFile(const AFileName: string; AShowProgress: Boolean); overload; procedure SaveToFile(AShowProgress: Boolean); overload; function GetCaption: string; function SupportsConnect: Boolean; property FileName: string read FFileName write FFileName; property WasModified: Boolean read FWasModified write FWasModified; property AutoMode: Boolean read FAutoMode write FAutoMode; property AutoRefresh: Boolean read FAutoRefresh write FAutoRefresh; property Progress: TfrmProcess read FProgress write FProgress; property ProjPwd: string read FProjPwd write SetProjPwd; property Password: string read FPassword write FPassword; // 3.0.0 property NetPass: string read FNetPass write FNetPass; // 2.0 procedure SetDefaultValues; function AddVolume: TNSProject; procedure DeleteVolume(Index: integer); property VolumeCount: integer read GetVolumeCount; property Volumes[index: integer]: TNSProject read GetVolume; property VolumeIndex: integer read GetVolumeIndex; property ActiveVolume: TNSProject read FActiveVolume write SetActiveVolume; property ActiveVolumeIndex: integer read FActiveVolumeIndex write SetActiveVolumeIndex; function GetVolumeString(const AFull: Boolean = True): string; procedure ExecuteExternal(const ABefore: Boolean); function NormalizePath(const APath: string): string; function ForceCollection(const APath: string): TNSCollection; function FindCollection(const APath: string): TNSCollection; procedure CleanProject; // 2.1 procedure SetProgress(const AOperation, AFileName: string; const ACurrent, ATotal: int64); function InitCDDrive: Boolean; property CDDrivePath: string read FCDDrivePath; property CDWriteable: Boolean read FCDWriteable; property BackupSize: int64 read FBackupSize write FBackupSize; property MediaSize: int64 read FMediaSize; published property Kind: TProjectKind read FKind write SetKind stored False; property DisplayName: string read GetDisplayName write SetDisplayName; property EncryptionMethod: TEncryptionMethod read FEncryptionMethod write SetEncryptionMethod; property MaxSize: cardinal read FMaxSize write FMaxSize; property StoreArchivePwd: Boolean read FStoreArchivePwd write FStoreArchivePwd; property WriteLog: Boolean read FWriteLog write FWriteLog; property IncMasks: TMaskItems read FIncMasks write SetIncMasks; property ExcMasks: TMaskItems read FExcMasks write SetExcMasks; property BackupMedia: TBackupMedia read FBackupMedia write FBackupMedia; property DefaultAction: TDefaultAction read FDefaultAction write SetDefaultAction; property LocalFolder: string read FLocalFolder write SetLocalFolder; property HostName: string read GetHostName write FHostName; property HostDirName: string read FHostDirName write SetHostDirName; property Passive: Boolean read FPassive write FPassive; property Port: string read FPort write FPort; property SendLog: TSendMail read FSendLog write FSendLog; property UserName: string read FUserName write FUserName; property Items: TNSCollection read FItems write SetItems; property CompressionLevel: byte read FCompressionLevel write SetCompressionLevel default ZCompressionMax; property DialupConnection: string read FDialupConnection write FDialupConnection stored False; property AutoDialUp: Boolean read FAutoDialUp write FAutoDialUp default False; property HangUpOnCompleted: Boolean read FHangUpOnCompleted write FHangUpOnCompleted default False; property ExtAppBefore: string read FExtAppBefore write FExtAppBefore; property WaitForExtAppBefore: Boolean read FWaitForExtAppBefore write FWaitForExtAppBefore; property ExtAppAfter: string read FExtAppAfter write FExtAppAfter; property WaitForExtAppAfter: Boolean read FWaitForExtAppAfter write FWaitForExtAppAfter; property TimeOutBefore: integer read FTimeOutBefore write FTimeOutBefore default 10; property TimeOutAfter: integer read FTimeOutAfter write FTimeOutAfter default 10; property AutoMangle: Boolean read FAutoMangle write SetAutoMangle default False; property SyncMode: TSyncMode read FSyncMode write SetSyncMode default smIndependent; property IsCDMedia: Boolean read GetIsCDMedia; property Restoring: Boolean read FRestoring; property RestoreCDDrive: string read FRestoreCDDrive write FRestoreCDDrive; // 2.1 property LastRunTime: TDateTime read FLastRunTime write FLastRunTime; property CDIndex: integer read FCDIndex write FCDIndex default -1; property CDErase: Boolean read FCDErase write FCDErase default False; property SendMailContect: TSendMailContent read FSendMailContect write FSendMailContect; property FileFormat: TFileFormat read FFileFormat write SetFileFormat; // 3.0.0 property NetPath: string read FNetPath write SetNetPath; property NetUser: string read FNetUser write SetNetUser; end; TNSVersion = class(TCollectionItem) private FSize: int64; FNumber: integer; FModified: TDateTime; FSizeOnMedia: int64; FExists: Boolean; protected public constructor Create(Collection: TCollection); override; published property Number: integer read FNumber write FNumber default 0; property Modified: TDateTime read FModified write FModified; property Size: int64 read FSize write FSize; property SizeOnMedia: int64 read FSizeOnMedia write FSizeOnMedia; property Exists: Boolean read FExists write FExists default True; end; TNSVersions = class(TCollection) private FOwner: TNSItem; function GetItem(Index: integer): TNSVersion; procedure SetItem(Index: integer; const Value: TNSVersion); protected public constructor Create(AOwner: TNSItem); overload; function Add: TNSVersion; property Items[index: integer]: TNSVersion read GetItem write SetItem; default; published end; TNSItem = class(TCollectionItem) private FModified: TDateTime; FSubItems: TNSCollection; FIsFolder: Boolean; FLocalPath: string; FCreated: TDateTime; FNotProcessed: Boolean; FState: TItemState; FVersions: TNSVersions; FDestFolder: string; FExists: Boolean; FBackupItem: Boolean; FProject: TNSProject; FDefAction: TDefaultAction; FUModified: TDateTime; FUSize: int64; FULocalPath: string; FRemoteName: string; procedure SetIsFolder(const Value: Boolean); function GetModified: TDateTime; function GetSize: int64; procedure SetModified(const Value: TDateTime); procedure SetSize(const Value: int64); function GetSizeOnMedia: int64; procedure SetSizeOnMedia(const Value: int64); function GetDestFolder: string; function GetVersion: integer; procedure SetExists(const Value: Boolean); procedure SetDefAction(const Value: TDefaultAction); function GetLocalPath: string; procedure SetLocalPath(const Value: string); function GetStoreFolder: Boolean; procedure SetNotProcessed(const Value: Boolean); procedure SetState(const Value: TItemState); procedure SetUModified(const Value: TDateTime); protected function GetDisplayName: string; override; procedure SetDisplayName(const Value: string); override; procedure SetBackupItem(const Value: Boolean); property Project: TNSProject read FProject; public FDisplayName: string; constructor Create(ACollection: TCollection); override; destructor Destroy; override; function GetPathOnMedia: string; property Size: int64 read GetSize write SetSize; property SizeOnMedia: int64 read GetSizeOnMedia write SetSizeOnMedia; property DestFolder: string read GetDestFolder write FDestFolder; property versionNumber: integer read GetVersion; function IndexOfVersion(AVersionNumber: integer): integer; function Rename(const ANewName: string): Boolean; function Mangle: Boolean; function IsNameMangled: Boolean; function DeleteVersion(const AVersion: integer): Boolean; function Backup: Boolean; function Restore: Boolean; function RestoreVersion(const ADestFolder: string; const AVersion: integer): Boolean; function FileNameOnServer(const AVersion: integer): string; function AuxFileName(const AVersion: integer): string; function VerifyPath: Boolean; procedure RollBack; procedure Refresh; function GetLocation: string; function NS_Name(const AVersion: integer): string; procedure ScanBackupFolder(const AProcessAll: Boolean); published property DisplayName: string read GetDisplayName write SetDisplayName; property IsFolder: Boolean read FIsFolder write SetIsFolder; property BackupItem: Boolean read FBackupItem write SetBackupItem; property LocalPath: string read GetLocalPath write SetLocalPath stored GetStoreFolder; property DefAction: TDefaultAction read FDefAction write SetDefAction default daReplace; property Created: TDateTime read FCreated write FCreated; property Modified: TDateTime read GetModified write SetModified; property UModified: TDateTime read FUModified write SetUModified; property uSize: int64 read FUSize write FUSize default 0; property ULocalPath: string read FULocalPath write FULocalPath stored GetStoreFolder; property NotProcessed: Boolean read FNotProcessed write SetNotProcessed default False; property State: TItemState read FState write SetState; property Exists: Boolean read FExists write SetExists; property SubItems: TNSCollection read FSubItems write FSubItems; property Versions: TNSVersions read FVersions write FVersions; property RemoteName: string read FRemoteName write FRemoteName; end; TNSCollection = class(TCollection) private FProject: TNSProject; FOwner: TNSItem; function GetItem(Index: integer): TNSItem; procedure SetItem(Index: integer; const Value: TNSItem); protected public constructor Create(AProject: TNSProject; AOwner: TNSItem); overload; function GetParentItem: TNSItem; function Add: TNSItem; function DeleteItem(Index: integer): Boolean; function DeleteFolder(Index: integer): Boolean; function FindItem(const ADispName: string): TNSItem; // new methods function GetPath: string; property Items[index: integer]: TNSItem read GetItem write SetItem; default; published end; TNSProjectHeader = class(TComponent) private FDisplayName: string; FEncryptionMethod: TEncryptionMethod; FKind: TProjectKind; FLastRunTime: TDateTime; FFileName: string; public procedure AssignProperties(const AProject: TNSProject); procedure LoadFromStream(AStream: TStream); procedure SaveToStream(AStream: TStream); function LoadFromFile(const AFileName: string): Boolean; public property FileName: string read FFileName write FFileName; published property Kind: TProjectKind read FKind write FKind; property DisplayName: string read FDisplayName write FDisplayName; property EncryptionMethod: TEncryptionMethod read FEncryptionMethod write FEncryptionMethod; property LastRunTime: TDateTime read FLastRunTime write FLastRunTime; end; var FRestoreMR: integer = mrNone; BurningRequired: Boolean; CurProject: TNSProject = nil; GlobalPurchaseURL: string; function FindFirstNew(ACollection: TNSCollection; ABaseName: string): string; implementation uses Vcl.Forms, Winapi.ShellAPI, System.SysUtils, System.StrUtils, System.DateUtils, WinInet, WinFTP, ziptools, abWaitDlg, cdWrapper, nsMainFrm, nsUtils, nsErrRestoreFrm, nsConfirmUpdateFrm, nsReplaceForm, nsActions, tsTaskman; const PrivateKey1 = '@vTjmrl)89TyUrfcvzx&*5l'; PrivateKey2 = '@vTjmrl)8#4bdrf_988uyhUTbhjbh_cvzx&*5l'; const PROJECT_BUF_SIZE = 1048576; var RestoreSR: TSearchRec; function CopyProgressRoutine(TotalFileSize: int64; TotalBytesTransferred: int64; StreamSize: int64; StreamBytesTransferred: int64; dwStreamNumber: DWORD; dwCallbackReason: DWORD; hSourceFile: THandle; hDestinationFile: THandle; lpData: Pointer): DWORD; stdcall; var frm: TfrmProcess; begin frm := TfrmProcess(lpData); if dwCallbackReason = 4 then frm.CopyProgressEx(TotalBytesTransferred, TotalFileSize, g_AbortProcess) else frm.CopyProgress(TotalBytesTransferred div MAXWORD, TotalFileSize div MAXWORD, g_AbortProcess); Application.ProcessMessages; if g_AbortProcess then Result := PROGRESS_STOP else Result := PROGRESS_CONTINUE; end; const dwHugeFile = 1024 * 1024 * 8; // file less 8 Mb we process in memory function ErrorMsg(ACode: DWORD): string; begin Result := Format(sCodeFormatted, [SysErrorMessage(ACode), ACode]); end; function FindFirstNew(ACollection: TNSCollection; ABaseName: string): string; var I: integer; List: TStringList; begin List := TStringList.Create; try for I := 0 to ACollection.Count - 1 do List.Add(ACollection.Items[I].DisplayName); List.Sorted := True; if List.IndexOf(ABaseName) = -1 then Result := ABaseName else begin I := 2; repeat Result := Format('%s (%d)', [ABaseName, I]); Inc(I); until List.IndexOf(Result) = -1; end; finally List.Free; end; end; { TNSCollection } function TNSCollection.Add: TNSItem; begin Result := TNSItem(inherited Add); if FOwner <> nil then begin Result.FDefAction := FOwner.FDefAction; end else begin Result.FDefAction := FProject.FDefaultAction; end; end; constructor TNSCollection.Create(AProject: TNSProject; AOwner: TNSItem); begin inherited Create(TNSItem); FProject := AProject; FOwner := AOwner; end; function TNSCollection.DeleteFolder(Index: integer): Boolean; var Item: TNSItem; DirName: string; sLog: string; begin Result := False; if g_AbortProcess then Exit; Item := Items[index]; if Item.Exists then begin DirName := Item.FileNameOnServer(-1); case FProject.BackupMedia of bmLocal, bmNAS: begin if Length(DirName) > MAX_PATH then begin Result := False; FProject.TraceLog(Format(sFolderDeletion, [DirName]), ErrorMsg(3), Result); end else begin RemoveDirectory(PChar(DirName)); FProject.TraceLog(Format(sFolderDeletion, [DirName]), ErrorMsg(GetLastError), Result); Result := not DirectoryExists(DirName); end; end; bmFTP: begin Result := DeleteFTPFolder(PChar(DirName)) = 0; FProject.TraceLog(Format(sFolderDeletion, [DirName]), StrPas(GetLastFTPResponse), Result); end; bmCD: begin Result := DiskWriter.RemoveDir(DirName); if Result then sLog := ErrorMsg(NO_ERROR) else sLog := ErrorMsg(ERROR_PATH_NOT_FOUND); FProject.TraceLog(Format(sFolderDeletion, [DirName]), sLog, Result); end; else Result := False; end; end else Result := True; if Result then begin if FProject.FProgress <> nil then NSChangeNotify(0, NSN_REMOVEFOLDER, NSN_FLUSH, Item.SubItems, Item) else Delete(index); end; end; function TNSCollection.DeleteItem(Index: integer): Boolean; var Ver: integer; RemoteFileName: string; sRealName: string; Item: TNSItem; tmpResult: Boolean; sLog: string; begin Result := False; if g_AbortProcess then Exit; Item := Items[index]; if FProject.Progress <> nil then with FProject.Progress do begin CurAction := sDeleting; CurItemSize := Item.SizeOnMedia; CurFile := Item.DisplayName; ProgressBar1.Position := 0; ProgressBar1.Max := Item.Versions.Count; Application.ProcessMessages; end; {$B+} if Item.Exists then begin RemoteFileName := Item.FileNameOnServer(-1); case FProject.BackupMedia of bmLocal, bmNAS: begin for Ver := 0 to Item.Versions.Count - 1 do begin sRealName := Item.FileNameOnServer(Item.Versions[Ver].Number); if Length(sRealName) > MAX_PATH then begin FProject.TraceLog(Format(sFileDeletion, [sRealName]), ErrorMsg(3), False); Result := False; end else begin tmpResult := DeleteFile(PChar(sRealName)); FProject.TraceLog(Format(sFileDeletion, [sRealName]), ErrorMsg(GetLastError), tmpResult); Result := Result or tmpResult; end; if FProject.Progress <> nil then with FProject.Progress do begin ProgressBar1.Position := ProgressBar1.Position + 1; Application.ProcessMessages; end; end; end; bmFTP: begin for Ver := 0 to Item.Versions.Count - 1 do begin sRealName := Item.FileNameOnServer(Item.Versions[Ver].Number); // sRealName := RemoteFileName + IntToHex(Item.Versions[Ver].Number, 3); tmpResult := DeleteFTPFile(PChar(sRealName)) = 0; FProject.TraceLog(Format(sFileDeletion, [sRealName]), StrPas(GetLastFTPResponse), tmpResult); Result := Result or tmpResult; if FProject.Progress <> nil then with FProject.Progress do begin ProgressBar1.Position := ProgressBar1.Position + 1; Application.ProcessMessages; end; end; end; bmCD: begin for Ver := 0 to Item.Versions.Count - 1 do begin sRealName := Item.FileNameOnServer(Item.Versions[Ver].Number); tmpResult := DiskWriter.RemoveFile(ExtractFilePath(RemoteFileName), ExtractFileName(sRealName)); if tmpResult then begin BurningRequired := True; sLog := ErrorMsg(NO_ERROR); end else sLog := ErrorMsg(ERROR_FILE_NOT_FOUND); FProject.TraceLog(Format(sFileDeletion, [sRealName]), sLog, tmpResult); Result := Result or tmpResult; if FProject.Progress <> nil then with FProject.Progress do begin ProgressBar1.Position := ProgressBar1.Position + 1; Application.ProcessMessages; end; end; end; end; end else Result := True; {$B-} if FProject.Progress <> nil then FProject.Progress.UpdateProgress; if Result then begin if FProject.Progress <> nil then NSChangeNotify(0, NSN_REMOVEITEM, NSN_FLUSH, Self, Item) else Self.Delete(index); end; end; function TNSCollection.FindItem(const ADispName: string): TNSItem; var I: integer; begin Result := nil; BeginUpdate; try for I := 0 to Count - 1 do if AnsiSameText(Items[I].FDisplayName, ADispName) then begin Result := Items[I]; Break; end; finally EndUpdate; end; end; function TNSCollection.GetItem(Index: integer): TNSItem; begin Result := TNSItem(inherited GetItem(index)); end; function TNSCollection.GetParentItem: TNSItem; begin Result := FOwner; end; function TNSCollection.GetPath: string; var ParItem: TNSItem; begin if FOwner = nil then Result := FProject.PathDelimiter else begin ParItem := GetParentItem; Result := EmptyStr; while ParItem <> nil do begin Result := ParItem.FDisplayName + FProject.PathDelimiter + Result; ParItem := TNSCollection(ParItem.Collection).GetParentItem; end; end; end; procedure TNSCollection.SetItem(Index: integer; const Value: TNSItem); begin inherited SetItem(index, Value); end; { TNSProject } constructor TNSProject.Create(AOwner: TComponent); begin inherited Create(AOwner); if AOwner is TfrmProcess then begin FProgress := TfrmProcess(AOwner); FAutoRefresh := g_AutoRefresh; end else begin if AOwner is TNSProject then FProgress := (AOwner as TNSProject).FProgress; FAutoRefresh := True; end; FCrypt := TWinCrypt.Create; FItems := TNSCollection.Create(Self, nil); FDisplayName := FormatDateTime('"AceBackup Project ("dd"_"mm"_"yyyy"_"hh"_"nn")', Now); FLogFile := TStringList.Create; FWriteLog := True; FIncMasks := TMaskItems.Create; FExcMasks := TMaskItems.Create; FCompressionLevel := ZCompressionDefault; FWaitForExtAppAfter := False; FWaitForExtAppBefore := False; FActiveVolume := Self; FActiveVolumeIndex := 0; FTimeOutBefore := 10; FTimeOutAfter := 10; // 11/6/2003 FDefaultAction := daUpdate; FRestoring := False; // 2.1 FCDIndex := -1; FKind := pkBackup; end; destructor TNSProject.Destroy; begin FLogFile.Free; FIncMasks.Free; FExcMasks.Free; FreeAndNil(FCrypt); if FItems <> nil then FItems.Free; inherited Destroy; end; { function TNSProject.GetCRC32(ADataStream: TStream): LongInt; var crc, checked, buffersize, fsize, count: LongInt; BufferArray: array[0..10239] of Byte; OriginalPos: LongInt; begin OriginalPos := ADataStream.Position; ADataStream.Seek(0, soFromBeginning); crc := LongInt($FFFFFFFF); fsize := ADataStream.Size; while True do begin if fsize <= 0 then break; if fsize >= 10240 then buffersize := 10240 else buffersize := fsize; Count := ADataStream.Read(BufferArray, BufferSize); checked := 0; while checked < Count do begin crc := ((crc shr 8) and $FFFFFF) xor FCRC32Table[(crc xor bufferArray[checked]) and $FF]; Inc(checked); end; Dec(fsize, buffersize); end; Result := crc xor LongInt($FFFFFFFF); ADataStream.Seek(OriginalPos, soFromBeginning); end; } { procedure TNSProject.InitCRC32; var crc, poly: LongInt; i, j: LongInt; begin poly := LongInt($FF726390); for i := 0 to 255 do begin crc := i; for j := 8 downto 1 do begin if (crc and 1) = 1 then crc := (crc shr 1) xor poly else crc := crc shr 1; end; FCRC32Table[i] := crc; end; end; } function TNSProject.LoadFromFile(const AFileName: string): Boolean; var FS: TFileStream; MS: TMemoryStream; // 2.1 Header: TNSProjectHeader; Reader: TReader; begin Result := False; if not FileExists(AFileName) then Exit; FFileName := AFileName; MS := TMemoryStream.Create; FS := TFileStream.Create(AFileName, fmOpenRead); if FProgress <> nil then begin frmWaitDlg := TfrmWaitDlg.Create(Application); frmWaitDlg.Show; frmWaitDlg.Update; Application.MainForm.Enabled := False; end; // 2.1 Header := TNSProjectHeader.Create(nil); try try // 2.1 try Header.LoadFromStream(FS); except FS.Position := 0; end; if FProgress <> nil then DecompressStream(FS, MS, frmWaitDlg.WaitProgress) else DecompressStream(FS, MS, nil); MS.Position := 0; Reader := TReader.Create(MS, PROJECT_BUF_SIZE); try Reader.ReadRootComponent(Self); finally Reader.Free; end; Result := True; except Result := False; end; finally FS.Free; MS.Free; if FProgress <> nil then begin Application.MainForm.Enabled := True; frmWaitDlg.Free; end; Header.Free; end; end; procedure TNSProject.LoadFromStream(AStream: TStream); begin if FItems.Count > 0 then FItems.Clear; if AStream.Size <> 0 then AStream.ReadComponent(Self); end; procedure TNSProject.SaveToFile(const AFileName: string; AShowProgress: Boolean); var FS: TFileStream; MS: TMemoryStream; Task: TTaskItem; Header: TNSProjectHeader; Writer: TWriter; begin if AFileName = EmptyStr then Exit; if not ForceDirectories(ExtractFilePath(AFileName)) then Exit; FileName := AFileName; if AShowProgress then begin frmWaitDlg := TfrmWaitDlg.Create(Application); frmWaitDlg.Show; frmWaitDlg.Update; Application.MainForm.Enabled := False; end; try MS := TMemoryStream.Create; FS := TFileStream.Create(AFileName, fmCreate); // 2.1 Header := TNSProjectHeader.Create(nil); try // 2.1 try Header.AssignProperties(Self); Header.SaveToStream(FS); except FS.Position := 0; end; Writer := TWriter.Create(MS, PROJECT_BUF_SIZE); try Writer.WriteDescendent(Self, nil); finally Writer.Free; end; MS.Position := 0; if AShowProgress then CompressStream(MS, FS, frmWaitDlg.WaitProgress, ZCompressionFastest) else CompressStream(MS, FS, nil, ZCompressionFastest); finally FS.Free; MS.Free; // 2.1 Header.Free; end; if frmMain.TaskManager.Active then begin Task := frmMain.TaskManager.ActivateTask(DisplayName); if Assigned(Task) then begin Task.Arguments := sUpdate + #34 + AFileName + #34; Task.SaveTask; end; end; finally if AShowProgress then begin Application.MainForm.Enabled := True; frmWaitDlg.Free; end; end; end; procedure TNSProject.SaveToFile(AShowProgress: Boolean); begin if FFileName <> EmptyStr then SaveToFile(FileName, AShowProgress); end; procedure TNSProject.SaveToStream(AStream: TStream); begin AStream.WriteComponent(Self); end; procedure TNSProject.SetProjPwd(const Value: string); var Index: integer; begin for index := 0 to VolumeCount - 1 do Volumes[index].FProjPwd := Value; end; function TNSProject.GetConnected: Boolean; begin Result := FConnected; end; procedure TNSProject.SetConnected(const Value: Boolean); begin FConnected := Value; end; procedure TNSProject.SetOpened(const Value: Boolean); begin if Value then FOpened := OpenProject(FProjPwd) else begin CloseProject; FOpened := False; end; end; function TNSProject.CloseProject: Boolean; var RemoteFolder: string; RemoteFileName: string; NeedPwdClean: Boolean; begin NeedPwdClean := (Self.EncryptionMethod <> tmNone) and Self.StoreArchivePwd; if NeedPwdClean then Self.StoreArchivePwd := False; try try if FFileName = EmptyStr then case FKind of pkArchive: FFileName := IncludeTrailingPathDelimiter(g_ProjectsDir) + DisplayName + sNsa; pkBackup: FFileName := IncludeTrailingPathDelimiter(g_ProjectsDir) + DisplayName + sNsb; end; SaveToFile(FileName, FProgress <> nil); Result := True; except Result := False; Exit; end; if not FConnected then begin if (FProgress = nil) and FHangUpOnCompleted then try InternetAutodialHangup(0); except end; if FProgress <> nil then PlaySoundEvent(SProjectClosedSound); Exit; end; case FBackupMedia of bmLocal: begin RemoteFolder := IncludeTrailingPathDelimiter(FLocalFolder) + DisplayName; Result := ForceDirectories(RemoteFolder); if not Result then Exit; RemoteFileName := IncludeTrailingPathDelimiter(RemoteFolder) + sRemoteFileName; Result := CopyFile(PChar(FFileName), PChar(RemoteFileName), False); end; bmFTP: begin RemoteFolder := IncludeTrailingPathDelimiter(FHostDirName) + FDisplayName; CreateFTPFolder(PChar(RemoteFolder)); CreateFTPFolder(PChar(IncludeTrailingPathDelimiter(RemoteFolder) + sArchives)); RemoteFileName := IncludeTrailingPathDelimiter(RemoteFolder) + sRemoteFileName; Result := UploadFTPFile(PChar(FFileName), PChar(RemoteFileName), nil) = 0; FinalizeFTPSession; if (FProgress = nil) and FHangUpOnCompleted then try InternetAutodialHangup(0); except end; end; bmNAS: begin RemoteFolder := IncludeTrailingPathDelimiter(FNasConnection) + DisplayName; Result := ForceDirectories(RemoteFolder); if Result then begin RemoteFileName := IncludeTrailingPathDelimiter(RemoteFolder) + sRemoteFileName; Result := CopyFile(PChar(FFileName), PChar(RemoteFileName), False); end; WNetCancelConnection2(PChar(FNasConnection), 0, True); FNasConnection := EmptyStr; end; else Result := False; end; FConnected := False; if FProgress <> nil then PlaySoundEvent(SProjectClosedSound); finally if NeedPwdClean then begin Self.StoreArchivePwd := True; try SaveToFile(FileName, FProgress <> nil); except end; end; end; end; procedure TNSProject.DefineProperties(Filer: TFiler); begin inherited; Filer.DefineProperty('Password', ReadPassword, WritePassword, True); Filer.DefineProperty('ProjPwd', ReadProjPwd, WriteProjPwd, True); Filer.DefineProperty('NetPass', ReadNetPass, WriteNetPass, True); end; function TNSProject.PathDelimiter: string; begin if FBackupMedia = bmFTP then Result := sSlash else Result := sBackslash; end; procedure TNSProject.ReadNetPass(Reader: TReader); begin FNetPass := TWinCrypt.CryptText(Reader.ReadString, PrivateKey1, False); end; procedure TNSProject.ReadPassword(Reader: TReader); begin FPassword := TWinCrypt.CryptText(Reader.ReadString, PrivateKey1, False); end; procedure TNSProject.WriteNetPass(Writer: TWriter); var Hash: string; begin Hash := TWinCrypt.CryptText(FNetPass, PrivateKey1, True); Writer.WriteString(Hash); end; procedure TNSProject.WritePassword(Writer: TWriter); var Hash: string; begin Hash := TWinCrypt.CryptText(FPassword, PrivateKey1, True); Writer.WriteString(Hash); end; procedure TNSProject.ReadProjPwd(Reader: TReader); begin FProjPwd := TWinCrypt.CryptText(Reader.ReadString, PrivateKey2, False); end; procedure TNSProject.WriteProjPwd(Writer: TWriter); var Hash: string; begin Hash := TWinCrypt.CryptText(FProjPwd, PrivateKey2, True); Writer.WriteString(Hash); end; procedure TNSProject.EndLog; var FN: string; FS: TStringList; begin if FWriteLog then begin ForceDirectories(g_LogDir); if not DirectoryExists(g_LogDir) then Exit; FN := IncludeTrailingPathDelimiter(g_LogDir) + DisplayName + sLog; FS := TStringList.Create; try if FileExists(FN) then FS.LoadFromFile(FN); FLogFile.Add(EmptyStr); FLogFile.Add(Format(sLogEnded, [DisplayName, GetVolumeString(True), DateTimeToStr(Now)])); FS.AddStrings(FLogFile); FS.SaveToFile(FN); finally FS.Free; end; end; end; procedure TNSProject.StartLog; var FS: TFileStream; FN: string; begin if FWriteLog then begin if not ForceDirectories(g_LogDir) then Exit; FN := IncludeTrailingPathDelimiter(g_LogDir) + DisplayName + sLog; if FileExists(FN) then begin FS := TFileStream.Create(FN, fmOpenRead or fmShareExclusive); try if FS.Size > MAXWORD then begin CopyFile(PChar(FN), PChar(ChangeFileExt(FN, sBak)), False); DeleteFile(PChar(FN)); end; finally FS.Free; end; end; end; FLogFile.Clear; FLogFile.Add(Format(sLogStarted, [DisplayName, GetVolumeString(True), DateTimeToStr(Now)])); end; function TNSProject.SupportsConnect: Boolean; begin case FBackupMedia of bmLocal: Result := GetDriveType(PChar(ExtractFileDrive(FLocalFolder))) <> DRIVE_FIXED; else Result := True; end; end; function TNSProject.ReConnect: Boolean; var RemoteFolder: string; begin Result := False; try case FBackupMedia of bmLocal: begin RemoteFolder := IncludeTrailingPathDelimiter(FLocalFolder) + DisplayName; Result := DirectoryExists(RemoteFolder); end; bmFTP: begin FinalizeFTPSession; if FDialupConnection <> EmptyStr then try Result := InternetAutodial(INTERNET_AUTODIAL_FORCE_UNATTENDED, Application.MainFormHandle); except Result := False; Exit; end; Result := InitializeFTPSession(g_ConnectType, (HostName), (UserName), (Password), (Port), (g_ProxyName), (g_ProxyPort), EmptyStr, EmptyStr, Passive) = 0; end; bmCD: begin Result := DiskWriter.CheckDeviceReady; end; bmNAS: begin Result := ConnectToNAS(0, NetPath, NetUser, NetPass, FNasConnection); end; end; finally FConnected := Result; end; end; function TNSProject.OpenProject(const APassword: string): Boolean; begin if Self.StoreArchivePwd or (Self.EncryptionMethod = tmNone) or (Self.ProjPwd = EmptyStr) then Result := True else Result := AnsiSameStr(Self.ProjPwd, APassword); FOpened := Result; end; function TNSProject.ConnectToMedia(const AWnd: HWnd): Boolean; var RemoteFolder: string; ArchiveFolder: string; begin Result := False; try case FBackupMedia of bmLocal: begin Result := FolderExists(FLocalFolder); if not Result then begin TraceLog(Format(sVerifyFolder, [FLocalFolder]), GetLastLocalResponse, Result); if AWnd <> 0 then MessageBox(AWnd, PChar(GetLastLocalResponse), PChar(sError), $00000030); Exit; end; RemoteFolder := IncludeTrailingPathDelimiter(FLocalFolder) + DisplayName; ArchiveFolder := IncludeTrailingPathDelimiter(RemoteFolder) + sArchives; Result := FolderExists(ArchiveFolder); if AWnd = 0 then Exit; if not Result then begin case MessageBox(GetActiveWindow, PChar(Format(sCreateDirConfirm, [ArchiveFolder])), PChar(sConfirm), $00000024) of idYes: begin Result := ForceDirectories(ArchiveFolder); g_dwLastError := GetLastError; if not Result then MessageBox(GetActiveWindow, PChar(Format(sErrorCreatingDir, [ArchiveFolder, GetLastLocalResponse])), PChar(sError), $00000030); end; idNo: begin Result := False; end; end; end; end; bmFTP: begin FinalizeFTPSession; if FAutoDialUp then try Result := InternetAutodial(INTERNET_AUTODIAL_FORCE_UNATTENDED, Application.MainFormHandle); except Result := False; Exit; end; Result := InitializeFTPSession(g_ConnectType, (HostName), (UserName), (Password), (Port), (g_ProxyName), (g_ProxyPort), EmptyStr, EmptyStr, Passive) = 0; TraceLog(Format(sConnectingTo, [HostName]), StrPas(GetLastFTPResponse), Result); if not Result then begin if AWnd <> 0 then MessageBox(AWnd, PChar(Format(sCouldNotConnect, [StrPas(GetLastFTPResponse)])), PChar(sError), $00000030); FinalizeFTPSession; Exit; end; RemoteFolder := IncludeTrailingPathDelimiter(HostDirName) + FDisplayName; CreateFTPFolder(PChar(RemoteFolder)); ArchiveFolder := IncludeTrailingPathDelimiter(RemoteFolder) + sArchives; CreateFTPFolder(PChar(ArchiveFolder)); Result := { FTPDirectoryExists(PChar(RemoteFolder)) and } FTPDirectoryExists(PChar(ArchiveFolder)); TraceLog(Format(sVerifiyng, [ArchiveFolder]), StrPas(GetLastFTPResponse), Result); if not Result then begin if AWnd <> 0 then case MessageBox(AWnd, PChar(Format(sCreateDirConfirm, [ArchiveFolder])), PChar(sConfirm), $00000024) of idYes: begin CreateFTPFolder(PChar(RemoteFolder)); CreateFTPFolder(PChar(ArchiveFolder)); Result := FTPDirectoryExists(PChar(RemoteFolder)) and FTPDirectoryExists(PChar(ArchiveFolder)); if not Result then MessageBox(0, PChar(Format(SCannotCreateDir, [ArchiveFolder]) + Format(sResponse, [StrPas(GetLastFTPResponse)])), PChar(sError), $00000030); end; idNo: begin Result := False; end; end; if not Result then begin FinalizeFTPSession; Exit; end; end; TraceLog(Format(sConnectingTo, [HostName]), StrPas(GetLastFTPResponse), Result); if not Result then begin if AWnd <> 0 then MessageBox(AWnd, PChar(Format(sCouldNotConnect, [StrPas(GetLastFTPResponse)])), PChar(sError), $00000030); FinalizeFTPSession; Exit; end; end; bmCD: begin Result := InitCDDrive; if not Result then begin TraceLog(SVerifyCD, SCDNotAvailable, Result); if AWnd <> 0 then MessageBox(AWnd, PChar(SCDNotAvailable), PChar(sError), $00000030); Exit; end; Result := DiskWriter.CheckDeviceReady; if not Result then begin TraceLog(SVerifyCD, SCDNotAvailable, Result); if AWnd <> 0 then MessageBox(AWnd, PChar(SCDNotAvailable), PChar(sError), $00000030); Exit; end; end; bmNAS: begin Result := ConnectToNAS(AWnd, NetPath, NetUser, NetPass, FNasConnection); end; end; finally FConnected := Result; end; if Result and (FProgress <> nil) then PlaySoundEvent(SConnectedSound); end; procedure TNSProject.Disconnect; begin case FBackupMedia of bmFTP: FinalizeFTPSession; bmNAS: WNetCancelConnection2(PChar(FNasConnection), 0, True); end; FConnected := False; end; function TNSProject.Rename(const ANewDisplayName: string): Boolean; var OldName: string; NewName: string; Task: TTaskItem; begin try case CurProject.BackupMedia of bmLocal: begin OldName := IncludeTrailingPathDelimiter(LocalFolder) + DisplayName; NewName := IncludeTrailingPathDelimiter(LocalFolder) + ANewDisplayName; Result := MoveFile(PChar(OldName), PChar(NewName)); end; bmFTP: begin OldName := IncludeTrailingPathDelimiter(HostDirName) + DisplayName; NewName := IncludeTrailingPathDelimiter(HostDirName) + ANewDisplayName; Result := RenameFTPFile(PChar(OldName), PChar(NewName)) = 0; end; bmCD: begin Result := False; end; bmNAS: begin OldName := IncludeTrailingPathDelimiter(FNetPath) + DisplayName; NewName := IncludeTrailingPathDelimiter(FNetPath) + ANewDisplayName; Result := MoveFile(PChar(OldName), PChar(NewName)); end; else Result := False; end; except Result := False; end; if not Result then Exit; if frmMain.TaskManager.Active then begin Task := frmMain.TaskManager.ActivateTask(FDisplayName); if Assigned(Task) then begin Task.SaveTask(ANewDisplayName); end; end; if Result then begin FDisplayName := ANewDisplayName; FWasModified := True; end; end; function TNSProject.Move(const ANewLocation: string): Boolean; var OldPath: string; NewPath: string; lpFileOp: TSHFileOpStruct; begin Result := False; try case CurProject.BackupMedia of bmLocal, bmNAS: begin if ANewLocation <> EmptyStr then Result := ForceDirectories(ANewLocation); if not Result then Exit; if CurProject.BackupMedia = bmLocal then OldPath := IncludeTrailingPathDelimiter(FLocalFolder) + DisplayName else OldPath := IncludeTrailingPathDelimiter(FNasConnection) + DisplayName; NewPath := IncludeTrailingPathDelimiter(ANewLocation) + DisplayName; FillChar(lpFileOp, SizeOf(TSHFileOpStruct), 0); with lpFileOp do begin wFunc := FO_MOVE; fFlags := FOF_SILENT or FOF_NOERRORUI; pFrom := PChar(OldPath + #0); pTo := PChar(NewPath + #0); end; Result := SHFileOperation(lpFileOp) = 0; if lpFileOp.fAnyOperationsAborted then Result := False; if Result then FLocalFolder := ANewLocation; end; bmFTP: begin CreateFTPFolder(PChar(ANewLocation)); OldPath := IncludeTrailingPathDelimiter(FHostDirName) + FDisplayName; NewPath := IncludeTrailingPathDelimiter(ANewLocation) + FDisplayName; Result := RenameFTPFile(PChar(OldPath), PChar(NewPath)) = 0; if Result then FHostDirName := ANewLocation; end; else Result := False; end; except Result := False; end; end; (* function TNSProject.AddBackupFolder(const AFolderName: string): TNSItem; var S: string; iPos: Integer; function iFindItem(const ACollection: TNSCollection): TNSItem; var Index: Integer; intPos: Integer; sDisplayName: string; CurItem: TNSItem; begin Result := nil; intPos := AnsiPos(sBackslash, S); if intPos > 0 then begin sDisplayName := Copy(S, 1, intPos - 1); Delete(S, 1, intPos); end else begin sDisplayName := S; S := EmptyStr; if sDisplayName = EmptyStr then Exit; end; for Index := 0 to ACollection.Count - 1 do begin CurItem := ACollection.Items[Index]; if not CurItem.IsFolder then Continue; if AnsiSameText(sDisplayName, CurItem.FDisplayName) then begin Result := CurItem; Result.UModified := Now; Result.NotProcessed := True; // Result.State := isBackup; Break; end; end; if Result <> nil then Exit; Result := ACollection.Add; Result.IsFolder := True; Result.FDisplayName := sDisplayName; Result.Created := Now; Result.UModified := Now; Result.NotProcessed := True; end; begin S := ExcludeTrailingPathDelimiter(AFolderName); iPos := AnsiPos(sColon, S); if iPos > 0 then begin Delete(S, iPos, 1); S := nsdPrefix + S; end; iPos := AnsiPos(sMachine, S); if iPos > 0 then begin Delete(S, iPos, 2); S := nscPrefix + S; end; Result := iFindItem(FItems); while (Result <> nil) and (S <> EmptyStr) do Result := iFindItem(Result.FSubItems); Result.BackupItem := True; Result.State := isBackup; end; *) function TNSProject.ProcessDelete: integer; function ProcessCollection(const ACollection: TNSCollection): integer; var Index: integer; CurItem: TNSItem; tmpResult: integer; begin Result := 0; ACollection.BeginUpdate; try for index := ACollection.Count - 1 downto 0 do begin if g_AbortProcess then Exit; CurItem := ACollection.Items[index]; if CurItem.IsFolder then begin if CurItem.State = isDelete then begin tmpResult := ProcessCollection(CurItem.SubItems); Result := Result + tmpResult; if tmpResult = 0 then if not ACollection.DeleteFolder(index) then Inc(Result); end else begin tmpResult := ProcessCollection(CurItem.SubItems); Result := Result + tmpResult; end; end else begin if CurItem.NotProcessed and (CurItem.State = isDelete) then begin if not ACollection.DeleteItem(index) then Inc(Result); end; end; end; finally ACollection.EndUpdate; end; end; begin LastRunTime := Now; Result := ProcessCollection(FItems); end; (* procedure TNSProject.ProcessAll(const AProcessAll: Boolean); var Count: Integer; OldSounds: Boolean; begin OldSounds := g_PlaySounds; if FProgress <> nil then begin PlaySoundEvent(SProcessStartSound); g_PlaySounds := False; end; StartLog; // ExecuteExternal(True); try FNeedClose := False; FIsRunning := True; if FProgress <> nil then begin Count := GetNonProcCount; FProgress.CurProgress := 0; FProgress.ProgressBar.Max := Count; FProgress.Caption := Format(sProcessing, [DisplayName]); FProgress.CurAction := sPrep; Application.MainForm.Enabled := False; FProgress.Show; end; ProcessDelete; if FKind = pkArchive then ProcessBackups(AProcessAll) else ProcessRegularBackups(AProcessAll); ProcessRestore; finally if FProgress <> nil then begin Application.MainForm.Enabled := True; FProgress.Hide; Application.MainForm.Update; end; // ExecuteExternal(False); EndLog; WasModified := True; FIsRunning := False; g_PlaySounds := OldSounds; if FProgress <> nil then PlaySoundEvent(SProcessCompletedSound); end; end; *) function TNSProject.PackFile(const ANameInp: string; const ANameOut: string; var ASize: int64): Boolean; var FStreamInp: TFileStream; AuxStream: TStream; FStreamOut: TFileStream; dwSignature: DWORD; sAuxName: string; pCancel: Bool; sSrcFile: string; hTmp: THandle; errCode: DWORD; begin Result := False; if g_AbortProcess then begin Exit; end; pCancel := False; hTmp := CreateFile(PChar(ANameInp), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, 0, 0); errCode := GetLastError; if hTmp <> INVALID_HANDLE_VALUE then CloseHandle(hTmp); if FileFormat = fmAsIs then begin if errCode in [ERROR_ACCESS_DENIED, ERROR_SHARING_VIOLATION] then begin Result := CopyFileRaw(PChar(ANameInp), PChar(ANameOut), @CopyProgressRoutine, FProgress, @pCancel, 0); end else begin if (Win32Platform = VER_PLATFORM_WIN32_NT) and (FProgress <> nil) then Result := CopyFileEx(PChar(ANameInp), PChar(ANameOut), @CopyProgressRoutine, FProgress, @pCancel, 0) else Result := CopyFile(PChar(ANameInp), PChar(ANameOut), False); end; ASize := FileGetSize(ANameOut); Exit; end; FStreamInp := nil; FStreamOut := nil; try try if errCode in [ERROR_ACCESS_DENIED, ERROR_SHARING_VIOLATION] then begin if not Result then Exit; sSrcFile := IncludeTrailingPathDelimiter(g_TempDir) + ExtractFileName(ANameInp); Result := CopyFileRaw(PChar(ANameInp), PChar(sSrcFile), @CopyProgressRoutine, FProgress, @pCancel, 0); if not Result then raise Exception.Create(SysErrorMessage(GetLastError)); FStreamInp := TFileStream.Create(sSrcFile, fmOpenRead or fmShareDenyWrite); end else FStreamInp := TFileStream.Create(ANameInp, fmOpenRead or fmShareDenyWrite); FStreamOut := TFileStream.Create(ANameOut, fmCreate or fmShareDenyWrite); Result := Assigned(FStreamInp) and Assigned(FStreamOut); except Result := False; end; if not Result then Exit; // new realisation // if FNeedCrypting and (CompressionLevel > 0) then begin dwSignature := SID_FACE; FStreamOut.WriteBuffer(dwSignature, SizeOf(DWORD)); FStreamOut.WriteBuffer(CompressionLevel, SizeOf(byte)); FStreamOut.WriteBuffer(byte(EncryptionMethod), SizeOf(byte)); FStreamOut.WriteBuffer(HashValue, SizeOf(HashValue)); end; if FNeedCrypting then begin if FProgress <> nil then with FProgress do begin CurAction := sCompressing; Application.ProcessMessages; end; sAuxName := ChangeFileExt(ANameOut, sCmp); if FStreamInp.Size > dwHugeFile then AuxStream := TFileStream.Create(sAuxName, fmCreate or fmShareDenyWrite) else AuxStream := TMemoryStream.Create; try try if FProgress <> nil then begin CompressStream(FStreamInp, AuxStream, FProgress.ZipProgress, CompressionLevel); with FProgress do begin CurAction := sEncrypting; Application.ProcessMessages; end; FCrypt.OnProgress := FProgress.HashProgress; end else begin CompressStream(FStreamInp, AuxStream, nil, CompressionLevel); end; AuxStream.Position := 0; FCrypt.EncryptFile(AuxStream, FStreamOut); ASize := FStreamOut.Size; Result := True; except Result := False; end; finally AuxStream.Free; DeleteFile(PChar(sAuxName)); end; end else try if FProgress <> nil then CompressStream(FStreamInp, FStreamOut, FProgress.ZipProgress, CompressionLevel) else CompressStream(FStreamInp, FStreamOut, nil, CompressionLevel); ASize := FStreamOut.Size; Result := True; except Result := False; end; if FileExists(sSrcFile) then DeleteFile(PChar(sSrcFile)); finally if Assigned(FStreamInp) then FStreamInp.Free; if Assigned(FStreamOut) then FStreamOut.Free; end; end; function TNSProject.UnPackFile(const ANameInp, ANameOut: string; ANewHash: THashKey): Boolean; var FStreamInp: TFileStream; AuxStream: TStream; // AuxStream: TMemoryStream; FStreamOut: TFileStream; dwSignature: DWORD; bBuffer: byte; // Commpression: Byte; sHash: THashKey; sEmpty: THashKey; sAuxName: string; sOldver: array [1 .. 8] of Char; begin if g_AbortProcess then begin Result := False; Exit; end; if FileFormat = fmAsIs then begin Result := CopyFile(PChar(ANameInp), PChar(ANameOut), False); Exit; end; FStreamInp := nil; FStreamOut := nil; try DeleteFile(PChar(ANameOut)); try FStreamInp := TFileStream.Create(ANameInp, fmOpenRead or fmShareDenyWrite); FStreamOut := TFileStream.Create(ANameOut, fmCreate or fmShareDenyWrite); Result := Assigned(FStreamInp) and Assigned(FStreamOut); except Result := False; end; if not Result then Exit; // new realisation FStreamInp.ReadBuffer(dwSignature, SizeOf(DWORD)); if (dwSignature = SID_FACE) or (dwSignature = SID_FACE_AB3) then begin // new format FStreamInp.ReadBuffer(bBuffer, SizeOf(byte)); FStreamInp.ReadBuffer(bBuffer, SizeOf(byte)); g_Encryption := TEncryptionMethod(bBuffer); // old version AB3 if (dwSignature = SID_FACE_AB3) then begin FStreamInp.ReadBuffer(sOldver, 8); Result := g_Encryption = tmNone; end else begin FStreamInp.ReadBuffer(sHash, SizeOf(sHash)); sEmpty := FCrypt.HashEmpty; if CompareMem(@ANewHash, @sEmpty, SizeOf(THashKey)) then Result := CompareMem(@sHash, @HashValue, SizeOf(THashKey)) else Result := CompareMem(@sHash, @ANewHash, SizeOf(THashKey)); end; sAuxName := ChangeFileExt(ANameOut, sCmp); if not Result then Exit; if g_Encryption <> tmNone then begin // Decryption needed if FStreamInp.Size > dwHugeFile then AuxStream := TFileStream.Create(sAuxName, fmCreate or fmShareDenyWrite) else AuxStream := TMemoryStream.Create; try if FProgress <> nil then with FProgress do begin CurAction := sDecrypt; Application.ProcessMessages; end; try if FProgress <> nil then FCrypt.OnProgress := FProgress.HashProgress else FCrypt.OnProgress := nil; FCrypt.DecryptFile(FStreamInp, AuxStream); AuxStream.Position := 0; if FProgress <> nil then with FProgress do begin CurAction := sDecompress; Application.ProcessMessages; end; if FProgress <> nil then DecompressStream(AuxStream, FStreamOut, FProgress.ZipProgress) else DecompressStream(AuxStream, FStreamOut, nil); Result := True; except Result := False; end; finally AuxStream.Free; DeleteFile(PChar(sAuxName)); end; end // Decryption needed else begin // No Decryption try if FProgress <> nil then DecompressStream(FStreamInp, FStreamOut, FProgress.ZipProgress) else DecompressStream(FStreamInp, FStreamOut, nil); Result := True; except Result := False; end; end; // No Decryption end // new format else begin // old format FStreamInp.Position := 0; if FNeedCrypting then begin if FStreamInp.Size > dwHugeFile then AuxStream := TFileStream.Create(sAuxName, fmCreate or fmShareDenyWrite) else AuxStream := TMemoryStream.Create; try try if FProgress <> nil then FCrypt.OnProgress := FProgress.HashProgress else FCrypt.OnProgress := nil; FCrypt.DecryptFile(FStreamInp, AuxStream); AuxStream.Position := 0; if FProgress <> nil then begin DecompressStream(AuxStream, FStreamOut, FProgress.ZipProgress); end else begin DecompressStream(AuxStream, FStreamOut, nil); end; Result := True; except Result := False; end; finally AuxStream.Free; DeleteFile(PChar(sAuxName)); end; end else try if FProgress <> nil then DecompressStream(FStreamInp, FStreamOut, FProgress.ZipProgress) else DecompressStream(FStreamInp, FStreamOut, nil); Result := True; except Result := False; end; end; finally if FStreamInp <> nil then FStreamInp.Free; if FStreamOut <> nil then FStreamOut.Free; end; end; function TNSProject.ProcessRestore: integer; function ProcessCollection(const ACollection: TNSCollection): integer; var Index: integer; CurItem: TNSItem; tmpResult: integer; begin Result := 0; ACollection.BeginUpdate; try for index := ACollection.Count - 1 downto 0 do begin if g_AbortProcess or (FRestoreMR = mrCancel) then Abort; Application.ProcessMessages; CurItem := ACollection.Items[index]; if CurItem.IsFolder then begin if CurItem.NotProcessed then begin tmpResult := ProcessCollection(CurItem.SubItems); Result := Result + tmpResult; end; end else begin if CurItem.NotProcessed and (CurItem.State = isRestore) and CurItem.Exists then if not CurItem.Restore then Inc(Result); end; end; finally ACollection.EndUpdate; end; end; begin LastRunTime := Now; FRestoreMR := mrNone; FillChar(RestoreSR, SizeOf(TSearchRec), #0); ReInitCrypting; FRestoring := True; Result := ProcessCollection(FItems); FRestoring := False; if FProgress <> nil then NSChangeNotify(0, NSN_STATUSCHANGED, NSN_FLUSHNOWAIT, nil, nil); end; function TNSProject.GetNonProcCount(var ASize: int64): integer; procedure ScanSubItems(const AItems: TNSCollection); var Index: integer; begin AItems.BeginUpdate; try for index := 0 to AItems.Count - 1 do with AItems[index] do begin if NotProcessed then begin if IsFolder then ScanSubItems(SubItems) else if (State <> isNormal) then begin Inc(Result); case State of isBackup, isBackupReplace, isBackupUpdate, isBackupNewVersion: ASize := ASize + uSize; isRestore, isRestoreToFolder: ASize := ASize + Size; isDelete: ASize := ASize + SizeOnMedia; end; end; end; end; finally AItems.EndUpdate; end; end; begin Result := 0; ASize := 0; ScanSubItems(FItems); Result := Result * 2; end; function TNSProject.CheckProject(ACheckFor: TCheckState): Boolean; var gResult: Boolean; iResult: integer; function ScanSubItems(ASubItems: TNSCollection): integer; var Index: integer; CurItem: TNSItem; tmpResult: integer; begin Result := 0; ASubItems.BeginUpdate; try for index := 0 to ASubItems.Count - 1 do begin CurItem := ASubItems.Items[index]; if CurItem.IsFolder then begin tmpResult := ScanSubItems(CurItem.SubItems); if tmpResult = 0 then begin if CurItem.Exists and (CurItem.State = isNormal) then CurItem.NotProcessed := False; end else CurItem.NotProcessed := True; Result := Result + tmpResult; end else if CurItem.NotProcessed then begin Inc(Result); case ACheckFor of csDelete: if CurItem.State = isDelete then gResult := False; csRestore: if CurItem.State in [isRestore, isRestoreToFolder] then gResult := False; csBackup: if (CurItem.State in [isBackup .. isBackupNewVersion]) then gResult := False; end; end; end; finally ASubItems.EndUpdate; end; end; begin gResult := True; iResult := ScanSubItems(FItems); if ACheckFor = csAll then Result := iResult = 0 else Result := gResult; end; procedure TNSProject.ReInitCrypting; begin FNeedCrypting := EncryptionMethod <> tmNone; FCrypt.Password := ProjPwd; HashValue := FCrypt.HashKey; end; procedure TNSProject.KillProcessing; begin g_AbortProcess := True; end; procedure TNSProject.Reset; procedure ScanSubItems(ACollection: TNSCollection); var Index: integer; CurItem: TNSItem; begin ACollection.BeginUpdate; try for index := ACollection.Count - 1 downto 0 do begin CurItem := ACollection.Items[index]; if not CurItem.Exists then ACollection.Delete(CurItem.Index) else begin if CurItem.IsFolder then ScanSubItems(CurItem.SubItems) else CurItem.RollBack; CurItem.State := isNormal; CurItem.NotProcessed := False; end; end; finally ACollection.EndUpdate; end; end; begin ScanSubItems(FItems); end; procedure TNSProject.Refresh; var cIndex: integer; cItem: TNSItem; begin g_AutoRefresh := False; g_AbortRefresh := False; FItems.BeginUpdate; try for cIndex := 0 to FItems.Count - 1 do begin if g_AbortRefresh then Abort; cItem := FItems[cIndex]; cItem.Refresh; end; finally FItems.EndUpdate; end; end; function TNSProject.IsValidExt(const AFileName: string): Boolean; var IncRslt: Boolean; ExcRslt: Boolean; begin if FIncMasks.Count = 0 then IncRslt := True else IncRslt := FIncMasks.Matches(AFileName); if FExcMasks.Count = 0 then ExcRslt := True else ExcRslt := not FExcMasks.Matches(AFileName); Result := IncRslt and ExcRslt; end; procedure TNSProject.TraceLog(const AOperation, AResult: string; const Rslt: Boolean); const Markers: array [Boolean] of Char = (#3, #1); begin FLogFile.Add(Markers[Rslt]); FLogFile.Add(Markers[Rslt] + sOperation + #9 + AOperation); FLogFile.Add(Markers[Rslt] + sResult + #9#9 + AResult); end; function TNSProject.GetLog: TStrings; begin Result := FLogFile; end; function TNSProject.GetCaption: string; begin case FBackupMedia of bmLocal, bmNAS: Result := Format(sCaption, [DisplayName, GetVolumeString(False)]); bmFTP: begin Result := Format(sCaption, [FDisplayName, GetVolumeString(False)]); end; bmCD: Result := Format(sCaption, [DisplayName, GetVolumeString(False)]); end; end; function TNSProject.GetDeleteCount(var ASize: int64): integer; procedure ScanSubItems(const AItems: TNSCollection); var Index: integer; begin AItems.BeginUpdate; try for index := 0 to AItems.Count - 1 do with AItems[index] do begin if NotProcessed then begin if IsFolder then ScanSubItems(SubItems) else if (State = isDelete) then begin Inc(Result); ASize := ASize + SizeOnMedia; end; end; end; finally AItems.EndUpdate; end; end; begin Result := 0; ASize := 0; ScanSubItems(FItems); Result := Result * 2; end; function TNSProject.GetBackupCount(var ASize: int64): integer; procedure ScanSubItems(const AItems: TNSCollection); var Index: integer; begin AItems.BeginUpdate; try for index := 0 to AItems.Count - 1 do with AItems[index] do begin if NotProcessed then begin if IsFolder then ScanSubItems(SubItems) else if (State in [isBackup .. isBackupNewVersion]) then begin Inc(Result); ASize := ASize + uSize; end; end; end; finally AItems.EndUpdate; end; end; begin Result := 0; ASize := 0; ScanSubItems(FItems); Result := Result * 2; end; function TNSProject.GetRestoreCount(var ASize: int64): integer; procedure ScanSubItems(const AItems: TNSCollection); var Index: integer; begin AItems.BeginUpdate; try for index := 0 to AItems.Count - 1 do with AItems[index] do begin if NotProcessed then begin if IsFolder then ScanSubItems(SubItems) else if (State in [isRestore, isRestoreToFolder]) then begin Inc(Result); ASize := ASize + Size; end; end; end; finally AItems.EndUpdate; end; end; begin Result := 0; ASize := 0; ScanSubItems(FItems); Result := Result * 2; end; procedure TNSProject.LogMsg(const AMessage: string); begin FLogFile.Add(#1); FLogFile.Add(#1 + AMessage); end; procedure TNSProject.ExecuteExternal(const ABefore: Boolean); var ExecRes: integer; ExeCmd: string; DoWait: Boolean; begin if ABefore then begin ExeCmd := FExtAppBefore; DoWait := FWaitForExtAppBefore; end else begin ExeCmd := FExtAppAfter; DoWait := FWaitForExtAppAfter; end; if ExeCmd <> EmptyStr then begin if DoWait then begin // TraceLog(Format(sExecutingExternalApp, [ExeCmd]), ''); if ABefore then ExecRes := ExecWait(ExeCmd, FTimeOutBefore) else ExecRes := ExecWait(ExeCmd, FTimeOutAfter); // if ExecRes <> 0 then TraceLog(Format(sExecutingExternalApp, [ExeCmd]), ErrorMsg(ExecRes), ExecRes = 0); // else // TraceLog(Format(sErrorExecute, [ExeCmd]), ErrorMsg(ExecRes)) end else begin // TraceLog(Format(sExecutingExternalApp, [ExeCmd]), ErrorMsg(GetLastError)); ExecuteApp(ExeCmd); TraceLog(Format(sExecutingExternalApp, [ExeCmd]), ErrorMsg(GetLastError), Boolean(GetLastError)); end; end; end; procedure TNSProject.GetChildren(Proc: TGetChildProc; Root: TComponent); var Index: integer; comp: TComponent; begin for index := 0 to ComponentCount - 1 do begin comp := Components[index]; if comp.Owner = Root then Proc(comp); end; end; function TNSProject.GetVolume(Index: integer): TNSProject; begin if index = 0 then Result := Self else Result := TNSProject(Components[index - 1]); end; function TNSProject.GetVolumeCount: integer; begin Result := ComponentCount + 1; end; function TNSProject.AddVolume: TNSProject; begin Result := TNSProject.Create(Self); end; procedure TNSProject.DeleteVolume(Index: integer); var Volume: TNSProject; begin Volume := Volumes[index]; RemoveComponent(Volume); Volume.Free; end; function TNSProject.GetDisplayName: string; begin if (Owner = nil) or not(Owner is TNSProject) then Result := FDisplayName else Result := (Owner as TNSProject).DisplayName; end; function TNSProject.GetVolumeIndex: integer; begin if (Owner = nil) or not(Owner is TNSProject) then Result := 0 else Result := ComponentIndex + 1; end; procedure TNSProject.SetActiveVolume(const Value: TNSProject); begin FActiveVolume := Value; FActiveVolumeIndex := FActiveVolume.VolumeIndex; end; procedure TNSProject.SetActiveVolumeIndex(const Value: integer); begin FActiveVolumeIndex := Value; FActiveVolume := Volumes[FActiveVolumeIndex]; end; function TNSProject.GetVolumeString(const AFull: Boolean): string; var S: string; begin case FBackupMedia of bmLocal: S := FLocalFolder; bmFTP: begin S := 'ftp://' + '/' + HostName + '/' + FHostDirName; S := StringReplace(S, '//', '/', [rfReplaceAll]); end; bmCD: begin S := DiskWriter.RecorderPath(CDIndex); end; bmNAS: S := NetPath; end; if AFull then Result := Format(sVolume + ' (%s)', [VolumeIndex, S]) else Result := S; end; procedure TNSProject.SetDefaultValues; begin if g_DefaultBackupDefined then begin FBackupMedia := TBackupMedia(g_DefaultBackupMedia); FLocalFolder := g_DefaultLocalFolder; FHostName := g_DefaultHostName; FPort := g_DefaultPort; FUserName := g_DefaultUserName; FPassword := g_DefaultPassword; FHostDirName := g_DefaultHostDirName; FPassive := g_DefaultUsePassive; FAutoDialUp := g_DefaultAutoDial; FHangUpOnCompleted := g_DefaultHangUpOnCompleted; end else begin FBackupMedia := TBackupMedia(g_LastMedia); LocalFolder := g_LastlocalFolder; NetPath := g_LastNetPath; FHostName := g_LastServer; FHostDirName := g_LastHostDir; FPort := g_DefaultPort; FUserName := g_LastUserName; FPassive := g_DefaultUsePassive; end; end; procedure TNSProject.AssignTo(Dest: TPersistent); begin if Dest is TNSProject then with Dest as TNSProject do begin FProjPwd := Self.FProjPwd; FDisplayName := Self.FDisplayName; FHostName := Self.FHostName; FPassive := Self.FPassive; FPort := Self.FPort; FUserName := Self.FUserName; FPassword := Self.FPassword; FStoreArchivePwd := Self.StoreArchivePwd; FHostDirName := Self.FHostDirName; FBackupMedia := Self.FBackupMedia; FLocalFolder := Self.FLocalFolder; FEncryptionMethod := Self.FEncryptionMethod; FDefaultAction := Self.FDefaultAction; FWriteLog := Self.FWriteLog; FKind := Self.FKind; FSendLog := Self.FSendLog; FIncMasks.SetMask(Self.FIncMasks.GetMask); FExcMasks.SetMask(Self.FExcMasks.GetMask); FCompressionLevel := Self.FCompressionLevel; FAutoDialUp := Self.FAutoDialUp; FHangUpOnCompleted := Self.FHangUpOnCompleted; FWaitForExtAppAfter := Self.FWaitForExtAppAfter; FWaitForExtAppBefore := Self.FWaitForExtAppBefore; FExtAppBefore := Self.FExtAppBefore; FExtAppAfter := Self.FExtAppAfter; FCDIndex := Self.FCDIndex; FCDErase := Self.FCDErase; FFileFormat := Self.FFileFormat; end; end; function TNSProject.CheckVolumes(ACheckFor: TCheckState): Boolean; var Index: integer; Volume: TNSProject; Rslt: Boolean; begin Result := True; for index := 0 to VolumeCount - 1 do begin Volume := Volumes[index]; Rslt := Volume.CheckProject(ACheckFor); {$B+} Result := Result and Rslt; {$B-} end; if SendLog = smAlways then SendReport(Self) else if (SendLog = smOnFailure) and not Result then SendReport(Self); end; procedure TNSProject.SetExcMasks(const Value: TMaskItems); var Index: integer; S: string; begin if csLoading in ComponentState then FExcMasks := Value else begin S := Value.GetMask; for index := 0 to VolumeCount - 1 do Volumes[index].FExcMasks.SetMask(S); end; end; procedure TNSProject.SetIncMasks(const Value: TMaskItems); var Index: integer; S: string; begin if csLoading in ComponentState then FIncMasks := Value else begin S := Value.GetMask; for index := 0 to VolumeCount - 1 do Volumes[index].FIncMasks.SetMask(S); end; end; procedure TNSProject.SetDisplayName(const Value: string); var Index: integer; begin if csLoading in ComponentState then FDisplayName := Value else for index := 0 to VolumeCount - 1 do Volumes[index].FDisplayName := Value; end; procedure TNSProject.SetKind(const Value: TProjectKind); var Index: integer; begin if csLoading in ComponentState then FKind := Value else for index := 0 to VolumeCount - 1 do Volumes[index].FKind := Value; end; procedure TNSProject.SetEncryptionMethod(const Value: TEncryptionMethod); var Index: integer; begin if csLoading in ComponentState then FEncryptionMethod := Value else for index := 0 to VolumeCount - 1 do Volumes[index].FEncryptionMethod := Value; end; procedure TNSProject.SetCompressionLevel(const Value: byte); var Index: integer; begin if csLoading in ComponentState then FCompressionLevel := Value else for index := 0 to VolumeCount - 1 do Volumes[index].FCompressionLevel := Value; end; procedure TNSProject.SetDefaultAction(const Value: TDefaultAction); var Index: integer; begin if csLoading in ComponentState then FDefaultAction := Value else for index := 0 to VolumeCount - 1 do Volumes[index].FDefaultAction := Value; end; procedure TNSProject.SetItems(const Value: TNSCollection); begin if FItems <> nil then FItems.Free; FItems := Value; FItems.FProject := Self; end; procedure TNSProject.SetAutoMangle(const Value: Boolean); var Index: integer; begin if csLoading in ComponentState then FAutoMangle := Value else for index := 0 to VolumeCount - 1 do Volumes[index].FAutoMangle := Value; end; procedure TNSProject.SetSyncMode(const Value: TSyncMode); var Index: integer; begin if csLoading in ComponentState then FSyncMode := Value else for index := 0 to VolumeCount - 1 do Volumes[index].FSyncMode := Value; end; function TNSProject.ForceCollection(const APath: string): TNSCollection; var nPos: integer; sBuffer: string; sItemName: string; xItem: TNSItem; begin sBuffer := AnsiReplaceStr(APath, sSlash, sBackslash); Result := FItems; if (APath = EmptyStr) or (APath = sBackslash) then Exit else begin while sBuffer <> EmptyStr do begin nPos := AnsiPos(sBackslash, sBuffer); if nPos > 0 then begin sItemName := Copy(sBuffer, 1, nPos - 1); Delete(sBuffer, 1, nPos); end else begin sItemName := sBuffer; sBuffer := EmptyStr; end; if (sItemName = EmptyStr) or (sItemName = sBackslash) then Exit; xItem := Result.FindItem(sItemName); if (xItem <> nil) and xItem.IsFolder then begin Result := xItem.FSubItems; end else begin xItem := Result.Add; xItem.IsFolder := True; xItem.DisplayName := sItemName; xItem.Created := Now; Result := xItem.FSubItems; end; end; end; end; function TNSProject.NormalizePath(const APath: string): string; var nPos: integer; begin Result := APath; nPos := AnsiPos(sColon, Result); if nPos > 0 then begin Delete(Result, nPos, 1); Result := nsdPrefix + Result; end else begin nPos := AnsiPos(sMachine, Result); if nPos > 0 then begin Delete(Result, nPos, 2); Result := nscPrefix + Result; end; end; Result := ExcludeTrailingPathDelimiter(Result); // SetLength(Result, Length(Result) - 1); if FBackupMedia = bmFTP then Result := AnsiReplaceStr(Result, sBackslash, sSlash); end; function TNSProject.FindCollection(const APath: string): TNSCollection; var nPos: integer; sBuffer: string; sItemName: string; xItem: TNSItem; begin sBuffer := AnsiReplaceStr(APath, sSlash, sBackslash); Result := FItems; if (APath = EmptyStr) or (APath = sBackslash) then Exit else begin while sBuffer <> EmptyStr do begin nPos := AnsiPos(sBackslash, sBuffer); if nPos > 0 then begin sItemName := Copy(sBuffer, 1, nPos - 1); Delete(sBuffer, 1, nPos); end else begin sItemName := sBuffer; sBuffer := EmptyStr; end; if (sItemName = EmptyStr) or (sItemName = sBackslash) then Exit; xItem := Result.FindItem(sItemName); if (xItem <> nil) and xItem.IsFolder then begin Result := xItem.FSubItems; end else begin Result := nil; Exit; end; end; end; end; function TNSProject.GetHostName: string; begin if Pos('ftp://', FHostName) = 1 then Result := Copy(FHostName, 7, MaxInt) else Result := FHostName; end; function TNSProject.ProcessBackup: integer; function ProcessCollection(const ACollection: TNSCollection): integer; var Index: integer; CurItem: TNSItem; tmpResult: integer; S: string; begin Result := 0; ACollection.BeginUpdate; try for index := ACollection.Count - 1 downto 0 do begin if g_AbortProcess then Break; Application.ProcessMessages; CurItem := ACollection.Items[index]; if CurItem.IsFolder then begin if CurItem.State <> isDelete then begin if CurItem.VerifyPath then begin CurItem.Exists := True; tmpResult := ProcessCollection(CurItem.SubItems); Result := Result + tmpResult; if CurItem.SubItems.Count = 0 then begin CurItem.State := isNormal; CurItem.NotProcessed := False; end; end else begin Inc(Result); CurItem.NotProcessed := True; S := IncludeTrailingPathDelimiter(CurItem.Project.LocalFolder) + CurItem.GetPathOnMedia + CurItem.DisplayName; TraceLog(Format(sCreateDir, [S]), ErrorMsg(GetLastError), False); end; end; end else begin if CurItem.NotProcessed and (CurItem.State in [isBackup .. isBackupNewVersion]) then begin if (FMediaSize > 0) and (FBackupSize > FMediaSize) then begin TraceLog(sAddingToCD, ErrorMsg(ERROR_HANDLE_DISK_FULL), False); CurItem.NotProcessed := True; Exit; end; if IsValidExt(CurItem.DisplayName) then begin if not CurItem.Backup then Inc(Result); end else Inc(Result); end; end; end; finally ACollection.EndUpdate; end; end; // var // lpFileOp: TSHFileOpStruct; // SRealFileName: string; begin LastRunTime := Now; FBackupSize := 0; // 2.1 Result := ProcessCollection(FItems); if FProgress <> nil then NSChangeNotify(0, NSN_STATUSCHANGED, NSN_FLUSHNOWAIT, nil, nil); end; procedure TNSProject.SetLocalFolder(const Value: string); begin FLocalFolder := Value; end; procedure TNSProject.SetNetPath(const Value: string); begin FNetPath := Value; end; procedure TNSProject.SetNetUser(const Value: string); begin FNetUser := Value; end; function TNSProject.GetIsCDMedia: Boolean; begin Result := False; // Result := GetDriveType(PChar(ExtractFileDrive(FLocalFolder))) = DRIVE_CDROM; end; procedure TNSProject.CleanProject; var Index: integer; Volume: TNSProject; RemoteFolder: string; begin if frmMain.TaskManager.Active then try if frmMain.TaskManager.ActivateTask(DisplayName) <> nil then frmMain.TaskManager.DeleteTask(DisplayName); except end; for index := 0 to VolumeCount - 1 do try Volume := Volumes[index]; case Volume.BackupMedia of bmLocal: begin RemoteFolder := IncludeTrailingPathDelimiter(Volume.LocalFolder) + DisplayName; RemoveDirectory(PChar(IncludeTrailingPathDelimiter(RemoteFolder) + sArchives)); RemoveDirectory(PChar(RemoteFolder)); end; bmFTP: begin if Volume.ConnectToMedia(Application.MainForm.Handle) then begin RemoteFolder := IncludeTrailingPathDelimiter(Volume.HostDirName) + DisplayName; DeleteFTPFolder(PChar(IncludeTrailingPathDelimiter(RemoteFolder) + sArchives)); DeleteFTPFolder(PChar(RemoteFolder)); end; end; bmNAS: begin RemoteFolder := IncludeTrailingPathDelimiter(Volume.FNasConnection) + DisplayName; RemoveDirectory(PChar(IncludeTrailingPathDelimiter(RemoteFolder) + sArchives)); RemoveDirectory(PChar(RemoteFolder)); end; end; except Continue; end; end; function TNSProject.InitCDDrive: Boolean; begin FCDDrivePath := EmptyStr; try Result := (CDIndex <> -1) and (CDIndex < DiskWriter.GetRecorderCount); if not Result then Exit; DiskWriter.SetActiveRecorder(CDIndex); FCDDrivePath := DiskWriter.DevicePath(CDIndex); except Result := False; end; end; function TNSProject.ImportCDMedia: Boolean; procedure ScanSubItems(const ACollection: TNSCollection); var I: integer; VerNo: integer; Item: TNSItem; sRemoteName: string; sLocalName: string; begin for I := 0 to ACollection.Count - 1 do begin if g_AbortProcess then Exit; Application.ProcessMessages; Item := ACollection[I]; if Item.IsFolder then begin sRemoteName := CDDrivePath + Item.GetPathOnMedia; if DirectoryExists(sRemoteName) then begin Item.VerifyPath; ScanSubItems(Item.SubItems); end; end else try for VerNo := 0 to Item.Versions.Count - 1 do begin if g_AbortProcess then Exit; Application.ProcessMessages; sRemoteName := CDDrivePath + Item.FileNameOnServer(Item.Versions[VerNo].FNumber); if FileExists(sRemoteName) then begin sLocalName := Item.AuxFileName(Item.Versions[VerNo].FNumber); if CopyFile(PChar(sRemoteName), PChar(sLocalName), True) then begin Result := True; sRemoteName := Item.GetPathOnMedia; DiskWriter.InsertFile(sRemoteName, sLocalName); end; end; end; except Continue; end; end; end; begin Result := False; ScanSubItems(FItems); end; procedure TNSProject.SetProgress(const AOperation, AFileName: string; const ACurrent, ATotal: int64); begin if FProgress = nil then Exit; FProgress.SetProgress(AOperation, AFileName, ACurrent, ATotal); end; function TNSProject.FinalizeMedia: Boolean; var lpFileOp: TSHFileOpStruct; sProjectFile: string; sOldProjectFile: string; begin Result := True; case BackupMedia of bmCD: begin DiskWriter.BurnerWriteDone := False; DiskWriter.BurnerEraseDone := False; if BurningRequired then begin DiskWriter.RecorderOpen; try SetProgress(EmptyStr, sInitCD, 0, 0); if DiskWriter.FilesCount = 0 then Exit; sOldProjectFile := Self.FileName; sProjectFile := IncludeTrailingPathDelimiter(g_TempDir + STmpFolder) + sRemoteFileName; Self.SaveToFile(sProjectFile, False); DiskWriter.InsertFile(sBackslash + Self.DisplayName + sBackslash, sProjectFile); Self.FileName := sOldProjectFile; if not DiskWriter.RecordDisk(True, False, True) then Exit; SetProgress(EmptyStr, sWriteToCD, 0, DiskWriter.GetClass.ImageSize); if FProgress <> nil then FProgress.ProgressBar2.Position := FProgress.ProgressBar2.Max div 2; repeat if g_AbortProcess then begin DiskWriter.AbortProcess; Break; end; Application.ProcessMessages; SetProgress(EmptyStr, sWriteToCD, DiskWriter.GetClass.BytesWritten div 2048, DiskWriter.GetClass.ImageSize); until DiskWriter.BurnerWriteDone or g_AbortProcess; finally DiskWriter.RecorderClose; DiskWriter.ReloadMedium; if DirectoryExists(g_TempDir + STmpFolder) then begin FillChar(lpFileOp, SizeOf(TSHFileOpStruct), #0); with lpFileOp do begin wFunc := FO_DELETE; fFlags := FOF_SILENT or FOF_NOERRORUI or FOF_NOCONFIRMATION; pFrom := PChar(g_TempDir + STmpFolder + #0); end; SHFileOperation(lpFileOp); end; end; end; end end; end; function TNSProject.InitializeMedia(const AState: TCheckState): Boolean; {$IFDEF USE_MCDB} var DirEntry: PDirEntry; {$ENDIF} begin BurningRequired := False; case BackupMedia of bmCD: try Result := DiskWriter.CheckDeviceReady; if not Result then begin TraceLog(Format(sVerifyFolder, [FCDDrivePath]), SCDNotAvailable, False); Exit; end; // CDWriter.WriteSpeed here? Result := DiskWriter.IsWriteableMedia; FCDWriteable := Result; if not Result then begin TraceLog(Format(sVerifyFolder, [FCDDrivePath]), SDiskClosed, False); Exit; end; // FMediaSize := int64(frmMain.CDWriter.GetMediaInfo.FreeBlocks) - 2048; if FMediaSize < 0 then FMediaSize := 0; FMediaSize := FMediaSize * 2048; {$IFDEF USE_MCDB} if ([AState] * [csAll, csBackup] <> []) then begin DirEntry := DiskWriter.CreateDir(DisplayName); Result := DirEntry <> nil; if not Result then Exit; DirEntry := DiskWriter.CreateDir(DirEntry, sArchives); Result := DirEntry <> nil; end; {$ENDIF} except Result := False; end; else begin Result := True; FMediaSize := -1; end; end; end; procedure TNSProject.SetFileFormat(const Value: TFileFormat); var Index: integer; begin if csLoading in ComponentState then FFileFormat := Value else for index := 0 to VolumeCount - 1 do Volumes[index].FFileFormat := Value; end; procedure TNSProject.SetHostDirName(const Value: string); begin FHostDirName := AnsiReplaceStr(Value, sBackslash, sSlash); end; { TNSItem } function TNSItem.Backup: Boolean; var LocalFileName: string; tmpSize: int64; RemoteFileName: string; TempFilename: string; sLog: string; SR: TSearchRec; xSize: int64; xSizeOnMedia: int64; xModified: TDateTime; pCancel: Bool; begin Result := False; LocalFileName := IncludeTrailingPathDelimiter(LocalPath) + Self.DisplayName; with FProject do try if g_AbortProcess then Exit; if FProgress <> nil then with FProgress do begin CurItemSize := uSize; CurFile := LocalFileName; CurAction := sCompressing; Application.ProcessMessages; if g_AbortProcess then Exit; end; if FindFirst(LocalFileName, faAnyFile, SR) <> 0 then begin FProject.TraceLog(Format(sBackupItem, [LocalFileName]), ErrorMsg(ERROR_FILE_NOT_FOUND), False); Exit; end; xSize := FileGetSize(SR); xModified := FileGetModified(SR); FindClose(SR); if FDefAction = daNewVersion then begin RemoteFileName := FileNameOnServer(Self.versionNumber + 1); TempFilename := AuxFileName(Self.versionNumber + 1); end else begin RemoteFileName := FileNameOnServer(Self.versionNumber); TempFilename := AuxFileName(Self.versionNumber); end; if FileFormat = fmAsIs then begin tmpSize := FileGetSize(LocalFileName); TempFilename := LocalFileName; Result := tmpSize <> -1; end else begin Result := PackFile(LocalFileName, TempFilename, tmpSize); end; if Result then begin xSizeOnMedia := tmpSize; tmpSize := (tmpSize div 2048 + 1) * 2048; FProject.BackupSize := FProject.BackupSize + tmpSize; end else begin sLog := ErrorMsg(GetLastError); FProject.TraceLog(Format(sBackupItem, [LocalFileName]), sLog, False); Exit; end; if FProgress <> nil then with FProgress do begin CurAction := sTransfer; if g_AbortProcess then Exit; end; case FProject.BackupMedia of bmLocal, bmNAS: begin Result := ForceDirectories(ExtractFilePath(RemoteFileName)); if not Result then begin sLog := ErrorMsg(ERROR_CANNOT_MAKE); end else begin pCancel := False; if (Win32Platform = VER_PLATFORM_WIN32_NT) and (FProgress <> nil) then Result := CopyFileEx(PChar(TempFilename), PChar(RemoteFileName), @CopyProgressRoutine, FProgress, @pCancel, 0) else Result := CopyFile(PChar(TempFilename), PChar(RemoteFileName), False); sLog := ErrorMsg(GetLastError); if FileFormat <> fmAsIs then DeleteFile(PChar(TempFilename)); end; if Result then begin State := isNormal; NotProcessed := False; Result := True; end; end; bmFTP: begin if FProgress <> nil then Result := UploadFTPFile(PChar(TempFilename), PChar(RemoteFileName), FProgress.FTPProgress) = 0 else Result := UploadFTPFile(PChar(TempFilename), PChar(RemoteFileName), nil) = 0; if not Result then if FProject.ReConnect then begin if FProgress <> nil then Result := UploadFTPFile(PChar(TempFilename), PChar(RemoteFileName), FProgress.FTPProgress) = 0 else Result := UploadFTPFile(PChar(TempFilename), PChar(RemoteFileName), nil) = 0; end; sLog := StrPas(GetLastFTPResponse); if Result then begin State := isNormal; NotProcessed := False; Result := True; end; if FileFormat <> fmAsIs then DeleteFile(PChar(TempFilename)); end; bmCD: begin RemoteFileName := ExtractFilePath(RemoteFileName); Result := DiskWriter.InsertFile(RemoteFileName, TempFilename) = 1; if Result then begin BurningRequired := True; State := isNormal; NotProcessed := False; Result := True; sLog := ErrorMsg(NO_ERROR); end else sLog := ErrorMsg(ERROR_PATH_NOT_FOUND); end; end; if Result then begin if FDefAction = daNewVersion then Self.Versions.Add; Self.Size := xSize; Self.FUSize := 0; Self.SizeOnMedia := xSizeOnMedia; Self.Modified := xModified; Self.FUModified := 0; Self.FULocalPath := EmptyStr; Self.Exists := True; State := isNormal; end; finally if FProgress <> nil then FProgress.UpdateProgress; FProject.TraceLog(Format(sBackupItem, [LocalFileName]), sLog, Result); end; end; constructor TNSItem.Create(ACollection: TCollection); begin inherited Create(ACollection); FProject := TNSCollection(ACollection).FProject; FSubItems := nil; FVersions := nil; end; function TNSItem.DeleteVersion(const AVersion: integer): Boolean; var RemoteFileName: string; sLog: string; // sSourceDir: string; // sSourceFile: string; begin Result := False; RemoteFileName := FileNameOnServer(AVersion); case FProject.BackupMedia of bmLocal, bmNAS: begin Result := DeleteFile(PChar(RemoteFileName)); sLog := ErrorMsg(GetLastError); end; bmFTP: begin Result := DeleteFTPFile(PChar(RemoteFileName)) = 0; if not Result then if FProject.ReConnect then Result := DeleteFTPFile(PChar(RemoteFileName)) = 0; sLog := StrPas(GetLastFTPResponse); end; bmCD: begin Result := False; { sSourceDir := GetPathOnMedia; sSourceFile := NS_Name(AVersion); Result := NSMainForm.CDBurner.RemoveFile(sSourceDir, sSourceFile); if Result then sLog := ErrorMsg(NO_ERROR) else sLog := ErrorMsg(ERROR_FILE_NOT_FOUND); } end; end; FProject.TraceLog(Format(sFileDeletion, [RemoteFileName]), sLog, Result); end; destructor TNSItem.Destroy; begin if FSubItems <> nil then FSubItems.Free; if FVersions <> nil then FVersions.Free; inherited Destroy; end; function TNSItem.FileNameOnServer(const AVersion: integer): string; begin Result := NS_Name(AVersion); with FProject do case BackupMedia of bmLocal: Result := IncludeTrailingPathDelimiter(FLocalFolder) + GetPathOnMedia + Result; bmFTP: Result := IncludeTrailingPathDelimiter(FHostDirName) + GetPathOnMedia + Result; bmCD: Result := GetPathOnMedia + Result; bmNAS: Result := IncludeTrailingPathDelimiter(FNasConnection) + GetPathOnMedia + Result; end; end; function TNSItem.GetDestFolder: string; begin if FDestFolder <> EmptyStr then Result := FDestFolder else Result := FLocalPath; end; function TNSItem.GetDisplayName: string; var iPos: integer; begin iPos := AnsiPos(nsdPrefix, FDisplayName); if iPos > 0 then begin Result := Copy(FDisplayName, 6, 1) + sDrive; Exit; end; iPos := AnsiPos(nscPrefix, FDisplayName); if iPos > 0 then begin Result := FDisplayName; Delete(Result, 1, 5); Result := sMachine + Result; Exit; end; Result := FDisplayName; end; function TNSItem.GetModified: TDateTime; begin if IsFolder then Result := FModified else if (FVersions <> nil) and (FVersions.Count > 0) then Result := FVersions.Items[FVersions.Count - 1].FModified else Result := 0; end; function TNSItem.GetPathOnMedia: string; var lOwner: TNSItem; begin Result := EmptyStr; lOwner := TNSCollection(Self.Collection).GetParentItem; with TNSCollection(Self.Collection).FProject do begin while lOwner <> nil do begin // Here must be FDisplayName Result := lOwner.FDisplayName + PathDelimiter + Result; lOwner := TNSCollection(lOwner.Collection).GetParentItem; end; case FBackupMedia of bmLocal: Result := DisplayName + #92 + sArchives + #92 + Result; bmFTP: Result := DisplayName + #47 + sArchives + #47 + Result; bmCD: Result := #92 + DisplayName + #92 + sArchives + #92 + Result; bmNAS: Result := DisplayName + #92 + sArchives + #92 + Result; end; end; end; function TNSItem.GetSize: int64; begin if (FVersions <> nil) and (FVersions.Count > 0) then Result := FVersions.Items[FVersions.Count - 1].FSize else Result := 0; end; function TNSItem.GetSizeOnMedia: int64; var Index: integer; begin Result := 0; if FVersions = nil then Exit; for index := 0 to FVersions.Count - 1 do if FVersions[index].Exists then Result := Result + FVersions[index].FSizeOnMedia; end; function TNSItem.GetVersion: integer; begin if (FVersions <> nil) and (FVersions.Count > 0) then Result := FVersions.Items[FVersions.Count - 1].FNumber else Result := 0; end; function TNSItem.IndexOfVersion(AVersionNumber: integer): integer; var Index: integer; begin Result := -1; if FVersions = nil then Exit; for index := 0 to FVersions.Count - 1 do if FVersions[index].FNumber = AVersionNumber then begin Result := index; Break; end; end; function TNSItem.NS_Name(const AVersion: integer): string; var tmpExt: string; nsz: string; tmpName: string; begin if FIsFolder or (FProject.FileFormat = fmAsIs) then Result := FDisplayName else begin tmpExt := ExtractFileExt(FDisplayName); if IsNameMangled then begin tmpName := FRemoteName; nsz := sMsz; end else begin tmpName := FDisplayName; nsz := sNsz; end; if AVersion >= 0 then nsz := nsz + IntToHex(AVersion, 3); if tmpExt <> EmptyStr then Result := ChangeFileExt(tmpName, tmpExt + nsz) else Result := ChangeFileExt(tmpName, nsz); end; end; function TNSItem.Rename(const ANewName: string): Boolean; var Path: string; OldName: string; NewName: string; Proj: TNSProject; nsz: string; VerNo: integer; begin Result := False; Proj := TNSCollection(Self.Collection).FProject; case Proj.BackupMedia of bmLocal: Path := IncludeTrailingPathDelimiter(Proj.LocalFolder) + GetPathOnMedia; bmFTP: Path := IncludeTrailingPathDelimiter(Proj.HostDirName) + GetPathOnMedia; bmNAS: Path := IncludeTrailingPathDelimiter(Proj.NetPath) + GetPathOnMedia; end; if IsNameMangled then begin OldName := Path + FRemoteName; NewName := Path + MangleFileName(ANewName); end else begin OldName := Path + FDisplayName; NewName := Path + ANewName; end; if Self.IsFolder then try case Proj.BackupMedia of bmLocal, bmNAS: Result := MoveFile(PChar(OldName), PChar(NewName)); bmFTP: Result := RenameFTPFile(PChar(OldName), PChar(NewName)) = 0 else Result := False; end; except Result := False; end else try {$B+} Result := False; for VerNo := 0 to Versions.Count - 1 do begin if FProject.FileFormat = fmAsIs then nsz := EmptyStr else begin if IsNameMangled then nsz := sMsz else nsz := sNsz; nsz := nsz + IntToHex(Versions[VerNo].Number, 3); end; case Proj.BackupMedia of bmLocal, bmNAS: Result := Result or MoveFile(PChar(OldName + nsz), PChar(NewName + nsz)); bmFTP: Result := Result or (RenameFTPFile(PChar(OldName + nsz), PChar(NewName + nsz)) = 0); end; end; except // Result := False; end; {$B-} if Result then begin FDisplayName := ANewName; if IsNameMangled then FRemoteName := MangleFileName(ANewName); end; end; function TNSItem.Restore: Boolean; var Method: TEncryptionMethod; pwd: string; RemoteFileName: string; TempFileName1: string; TempFileName2: string; DestFileName: string; sLog: string; tmpDate: TDateTime; mrResult: integer; sNewHash: THashKey; {$IFDEF USE_MCDB} sDirEntry: string; DirEntry: PDirEntry; sFileEntry: string; FileEntry: PFileEntry; {$ENDIF} pCancel: Bool; begin DestFileName := IncludeTrailingPathDelimiter(DestFolder) + Self.DisplayName; // Result := False; with FProject do try if FProgress <> nil then with FProgress do begin CurItemSize := Size; CurFile := DestFileName; CurAction := sTransfer; Application.ProcessMessages; if g_AbortProcess then begin Result := False; Exit; end; end; // if g_AbortProcess then Abort; if DestFolder <> EmptyStr then Result := ForceDirectories(DestFolder) else Result := False; if not Result then begin sLog := ErrorMsg(ERROR_CANNOT_MAKE); FProject.TraceLog(Format(sCreateDir, [DestFolder]), sLog, False); Exit; end; if g_AbortProcess then begin sLog := ErrorMsg(ERROR_REQUEST_ABORTED); TraceLog(Format(sRestoreFile, [GetPathOnMedia + Self.DisplayName]), sLog, False); Result := False; Exit; end; if FProgress <> nil then begin if (FRestoreMR <> mrYesToAll) and (FindFirst(DestFileName, faAnyFile, RestoreSR) = 0) then begin tmpDate := FileGetModified(RestoreSR); FRestoreMR := ReplaceLocalDlg(Self.DisplayName, DestFolder, Size, Modified, FileGetSize(RestoreSR), tmpDate); if FRestoreMR = mrNo then begin sLog := ErrorMsg(ERROR_REQUEST_ABORTED); TraceLog(Format(sRestoreFile, [GetPathOnMedia + Self.DisplayName]), sLog, False); Exit; end else if FRestoreMR = mrCancel then begin sLog := ErrorMsg(ERROR_REQUEST_ABORTED); TraceLog(Format(sRestoreFile, [GetPathOnMedia + Self.DisplayName]), sLog, False); Result := False; Exit; end; FindClose(RestoreSR); end; end; RemoteFileName := FileNameOnServer(versionNumber); if g_AbortProcess then begin sLog := ErrorMsg(ERROR_REQUEST_ABORTED); TraceLog(Format(sRestoreFile, [GetPathOnMedia + Self.DisplayName]), sLog, False); Result := False; Exit; end; case BackupMedia of bmLocal, bmNAS: begin TempFileName1 := RemoteFileName; Result := FileExists(TempFileName1); if not Result then sLog := ErrorMsg(ERROR_FILE_NOT_FOUND); end; bmFTP: begin TempFileName1 := AuxFileName(versionNumber); if FileExists(TempFileName1) then begin if not DeleteFile(PChar(TempFileName1)) then begin sLog := ErrorMsg(GetLastError); TraceLog(Format(sRestoreFile, [GetPathOnMedia + Self.DisplayName]), sLog, False); Exit; end; end; if FProgress <> nil then Result := DownloadFTPFile(PChar(TempFileName1), PChar(RemoteFileName), FProgress.FTPProgress) = 0 else Result := DownloadFTPFile(PChar(TempFileName1), PChar(RemoteFileName), nil) = 0; if g_AbortProcess then begin sLog := ErrorMsg(ERROR_REQUEST_ABORTED); TraceLog(Format(sRestoreFile, [GetPathOnMedia + Self.DisplayName]), sLog, False); Result := False; Exit; end; if not Result then if FProject.ReConnect then begin if FProgress <> nil then Result := DownloadFTPFile(PChar(TempFileName1), PChar(RemoteFileName), FProgress.FTPProgress) = 0 else Result := DownloadFTPFile(PChar(TempFileName1), PChar(RemoteFileName), nil) = 0; end; if not Result then sLog := StrPas(GetLastFTPResponse); end; bmCD: begin if FProject.CDWriteable then begin {$IFDEF USE_MCDB} sDirEntry := GetPathOnMedia; DirEntry := DiskWriter.GetClass.FindDir(sDirEntry); Result := DirEntry <> nil; if not Result then sLog := ErrorMsg(ERROR_PATH_NOT_FOUND) else begin sFileEntry := NS_Name(versionNumber); FileEntry := DiskWriter.GetClass.FindFile(DirEntry, sFileEntry); Result := FileEntry <> nil; if not Result then sLog := ErrorMsg(ERROR_FILE_NOT_FOUND) else begin TempFileName1 := AuxFileName(versionNumber); if FileExists(TempFileName1) then begin if not DeleteFile(PChar(TempFileName1)) then begin sLog := ErrorMsg(GetLastError); TraceLog(Format(sRestoreFile, [GetPathOnMedia + Self.DisplayName]), sLog, False); end; end; Result := DiskWriter.GetClass.ExtractFile(FileEntry, TempFileName1); if not Result then sLog := DiskWriter.GetClass.ErrorString; end; end; {$ENDIF} end else begin TempFileName1 := FProject.CDDrivePath + RemoteFileName; Result := FileExists(TempFileName1); if not Result then sLog := ErrorMsg(ERROR_FILE_NOT_FOUND); end; end; end; if not Result then begin TraceLog(Format(sRestoreFile, [GetPathOnMedia + Self.DisplayName]), sLog, False); Exit; end; TempFileName2 := IncludeTrailingPathDelimiter(g_TempDir) + Self.FDisplayName; if FileExists(TempFileName2) then begin if not DeleteFile(PChar(TempFileName2)) then begin sLog := ErrorMsg(GetLastError); TraceLog(Format(sRestoreFile, [GetPathOnMedia + Self.DisplayName]), sLog, False); Exit; end; end; if (FileFormat = fmAsIs) then begin Result := True; TempFileName2 := TempFileName1; end else begin Result := UnPackFile(TempFileName1, TempFileName2, FCrypt.HashEmpty); end; if g_AbortProcess then begin sLog := ErrorMsg(ERROR_REQUEST_ABORTED); TraceLog(Format(sRestoreFile, [GetPathOnMedia + Self.DisplayName]), sLog, False); Result := False; Exit; end; if not Result then begin if FProgress = nil then begin Result := False; sLog := ErrorMsg(ERROR_INVALID_DATA); TraceLog(Format(sDecryption, [GetPathOnMedia + Self.FDisplayName]), sLog, False); Exit; end else begin repeat if g_AbortProcess then begin sLog := ErrorMsg(ERROR_REQUEST_ABORTED); TraceLog(Format(sRestoreFile, [GetPathOnMedia + Self.DisplayName]), sLog, False); Result := False; Exit; end; DeleteFile(PChar(TempFileName2)); mrResult := ErrorRestoreDialog(FProgress, FProject, Self, Method, pwd); case mrResult of mrYes: begin FCrypt.Password := pwd; sNewHash := FCrypt.HashKey; Result := UnPackFile(TempFileName1, TempFileName2, sNewHash); ReInitCrypting; end; mrYesToAll: begin FCrypt.Password := pwd; sNewHash := FCrypt.HashKey; Result := UnPackFile(TempFileName1, TempFileName2, sNewHash); HashValue := sNewHash; end; mrIgnore: begin Result := False; sLog := ErrorMsg(ERROR_INVALID_DATA); TraceLog(Format(sDecryption, [GetPathOnMedia + Self.FDisplayName]), sLog, False); Exit; end else begin g_AbortProcess := True; Result := False; sLog := ErrorMsg(ERROR_INVALID_DATA); TraceLog(Format(sDecryption, [GetPathOnMedia + Self.FDisplayName]), sLog, False); Exit; end; end; until Result; end; end; pCancel := False; if (Win32Platform = VER_PLATFORM_WIN32_NT) and (FProgress <> nil) then Result := CopyFileEx(PChar(TempFileName2), PChar(DestFileName), @CopyProgressRoutine, FProgress, @pCancel, 0) else Result := CopyFile(PChar(TempFileName2), PChar(DestFileName), False); sLog := ErrorMsg(GetLastError); if FileFormat <> fmAsIs then DeleteFile(PChar(TempFileName2)); if BackupMedia = bmFTP then DeleteFile(PChar(TempFileName1)); // Restore original create and modified datetime if Modified > 1 then SetFileModifiedTime(DestFileName, Modified); if Result then begin State := isNormal; NotProcessed := False; DestFolder := EmptyStr; end; TraceLog(Format(sRestoreFile, [GetPathOnMedia + Self.DisplayName]), sLog, Result); finally if FProgress <> nil then with FProgress do begin UpdateProgress; Application.ProcessMessages; end; end; end; function TNSItem.RestoreVersion(const ADestFolder: string; const AVersion: integer): Boolean; var Method: TEncryptionMethod; pwd: string; RemoteFileName: string; TempFileName1: string; TempFileName2: string; DestFileName: string; mrResult: integer; I: integer; sNewHash: THashKey; sDestination: string; begin Result := False; sDestination := ADestFolder; with FProject do begin RemoteFileName := FileNameOnServer(AVersion); DestFileName := IncludeTrailingPathDelimiter(sDestination) + Self.DisplayName; case BackupMedia of bmLocal, bmNAS: begin TempFileName1 := RemoteFileName; Result := FileExists(TempFileName1); end; bmFTP: begin TempFileName1 := AuxFileName(AVersion); if FileExists(TempFileName1) then begin Result := DeleteFile(PChar(TempFileName1)); if not Result then Exit; end; Result := DownloadFTPFile(PChar(TempFileName1), PChar(RemoteFileName), nil) = 0; end; bmCD: begin TempFileName1 := FProject.CDDrivePath + RemoteFileName; Result := FileExists(TempFileName1); end; end; if not Result then Exit; TempFileName2 := IncludeTrailingPathDelimiter(g_TempDir) + Self.DisplayName; Result := UnPackFile(TempFileName1, TempFileName2, FCrypt.HashEmpty); if not Result then repeat mrResult := ErrorRestoreDialog(nil, FProject, Self, Method, pwd); case mrResult of mrYes: begin FCrypt.Password := pwd; sNewHash := FCrypt.HashKey; Result := UnPackFile(TempFileName1, TempFileName2, sNewHash); ReInitCrypting; end; mrYesToAll: begin FCrypt.Password := pwd; sNewHash := FCrypt.HashKey; Result := UnPackFile(TempFileName1, TempFileName2, sNewHash); HashValue := sNewHash; end else begin Result := False; Exit; end; end; until Result; if AnsiSameText(DestFileName, TempFileName2) then Result := True else begin Result := CopyFile(PChar(TempFileName2), PChar(DestFileName), False); DeleteFile(PChar(TempFileName2)); end; // Restore original create and modified datetime try for I := 0 to FVersions.Count - 1 do if FVersions.Items[I].Number = AVersion then begin if Versions.Items[I].Modified > 1 then SetFileModifiedTime(DestFileName, Versions[I].Modified); Break; end; except end; if BackupMedia = bmFTP then DeleteFile(PChar(TempFileName1)); end; end; procedure TNSItem.SetBackupItem(const Value: Boolean); begin FBackupItem := Value; end; procedure TNSItem.SetDisplayName(const Value: string); var iPos: integer; begin if not(csLoading in FProject.ComponentState) then if FProject.AutoMangle then FRemoteName := MangleFileName(Value); iPos := AnsiPos(sDrive, Value); if iPos > 0 then begin FDisplayName := nsdPrefix + Copy(Value, 1, 1); Exit; end; iPos := AnsiPos(sMachine, Value); if iPos > 0 then begin FDisplayName := nscPrefix + Copy(Value, 3, Length(Value)); Exit; end; FDisplayName := Value; end; procedure TNSItem.SetExists(const Value: Boolean); begin FExists := Value; if (FVersions <> nil) and (FVersions.Count > 0) then FVersions.Items[FVersions.Count - 1].FExists := Value; end; procedure TNSItem.SetIsFolder(const Value: Boolean); begin FIsFolder := Value; if FIsFolder then FSubItems := TNSCollection.Create(TNSCollection(Collection).FProject, Self) else begin FVersions := TNSVersions.Create(Self); if not(csLoading in FProject.ComponentState) then FVersions.Add; end; end; procedure TNSItem.SetModified(const Value: TDateTime); var Parent: TNSItem; begin if IsFolder then FModified := Value else if (FVersions <> nil) and (FVersions.Count > 0) then FVersions.Items[FVersions.Count - 1].FModified := Value; Parent := TNSCollection(Self.Collection).GetParentItem; if Parent <> nil then Parent.Modified := Now; end; procedure TNSItem.SetNotProcessed(const Value: Boolean); var Parent: TNSItem; begin FNotProcessed := Value; if Value then begin Parent := TNSCollection(Self.Collection).GetParentItem; if Parent <> nil then Parent.NotProcessed := Value; end; end; procedure TNSItem.SetSize(const Value: int64); begin if (FVersions <> nil) and (FVersions.Count > 0) then FVersions.Items[FVersions.Count - 1].FSize := Value; end; procedure TNSItem.SetSizeOnMedia(const Value: int64); begin if (FVersions <> nil) and (FVersions.Count > 0) then FVersions[FVersions.Count - 1].FSizeOnMedia := Value; end; function TNSItem.AuxFileName(const AVersion: integer): string; var // S: string; lOwner: TNSItem; begin case FProject.BackupMedia of bmCD: begin Result := EmptyStr; lOwner := TNSCollection(Self.Collection).GetParentItem; while lOwner <> nil do begin Result := IntToStr(lOwner.Index) + sBackslash + Result; lOwner := TNSCollection(lOwner.Collection).GetParentItem; end; Result := IncludeTrailingPathDelimiter(g_TempDir) + STmpFolder + sBackslash + Result; if ForceDirectories(Result) then Result := IncludeTrailingPathDelimiter(Result) + NS_Name(AVersion) else Result := IncludeTrailingPathDelimiter(g_TempDir) + NS_Name(AVersion); end; else Result := IncludeTrailingPathDelimiter(g_TempDir) + NS_Name(AVersion); end; end; function TNSItem.VerifyPath: Boolean; var RemoteFolder: string; DirEntry: PDirEntry; begin Result := False; if not IsFolder then Exit; case TNSCollection(Collection).FProject.BackupMedia of bmLocal: begin RemoteFolder := IncludeTrailingPathDelimiter(TNSCollection(Collection).FProject.LocalFolder) + GetPathOnMedia + FDisplayName; Result := ForceDirectories(RemoteFolder); end; bmFTP: begin RemoteFolder := IncludeTrailingPathDelimiter(TNSCollection(Collection).FProject.HostDirName) + GetPathOnMedia + FDisplayName; try CreateFTPFolder(PChar(RemoteFolder)); Result := True; except Result := False; end; end; bmCD: begin try RemoteFolder := GetPathOnMedia + FDisplayName; Result := RemoteFolder <> EmptyStr; if Result then begin DirEntry := DiskWriter.CreateDir(RemoteFolder); Result := DirEntry <> nil; end; except Result := False; end; end; bmNAS: begin RemoteFolder := IncludeTrailingPathDelimiter(TNSCollection(Collection).FProject.FNasConnection) + GetPathOnMedia + FDisplayName; Result := ForceDirectories(RemoteFolder); end; else Result := False; end; end; procedure TNSItem.SetLocalPath(const Value: string); begin if FIsFolder then Exit; { if FLocalPath <> EmptyStr then FOldLocalPath := FLocalPath else FOldLocalPath := Value; } FLocalPath := Value; end; procedure TNSItem.RollBack; begin FUSize := 0; FUModified := 0; FULocalPath := EmptyStr; { if FOldLocalPath <> EmptyStr then FLocalPath := FOldLocalPath; if FOldSize <> 0 then FVersions.Items[FVersions.Count - 1].FSize := FOldSize; if FOldModified > 1 then FVersions.Items[FVersions.Count - 1].FModified := FOldModified; } end; procedure TNSItem.SetDefAction(const Value: TDefaultAction); begin FDefAction := Value; end; function TNSItem.GetLocalPath: string; var Par: TNSItem; begin if not FIsFolder then Result := FLocalPath else begin Result := EmptyStr; Par := TNSCollection(Self.Collection).FOwner; while Par <> nil do begin Result := IncludeTrailingPathDelimiter(Par.DisplayName) + Result; Par := TNSCollection(Par.Collection).FOwner; end; end; end; function TNSItem.GetStoreFolder: Boolean; begin Result := not FIsFolder; end; function TNSItem.GetLocation: string; begin Result := GetPathOnMedia; if AnsiPos(sArchives, Result) > 0 then Delete(Result, 1, AnsiPos(sArchives, Result) + Length(sArchives)); if Result = EmptyStr then Result := sRoot; if AnsiPos(nsdPrefix, Result) > 0 then begin Delete(Result, 1, Length(nsdPrefix)); Insert(sColon, Result, 2); end else if AnsiPos(nscPrefix, Result) > 0 then begin Delete(Result, 1, Length(nscPrefix)); Result := sMachine + Result; end; end; procedure TNSItem.ScanBackupFolder(const AProcessAll: Boolean); var SR: TSearchRec; xItem: TNSItem; xPath: string; xTime: TDateTime; begin if FSubItems = nil then Exit; xPath := IncludeTrailingPathDelimiter(IncludeTrailingPathDelimiter(Self.LocalPath) + Self.DisplayName) + sFileMask; if FindFirst(xPath, faAnyFile, SR) <> 0 then Exit; repeat if (SR.Name = sDot) or (SR.Name = sDoubleDot) then Continue; if (SR.Attr and faDirectory <> faDirectory) then if not FProject.IsValidExt(SR.Name) then Continue; xTime := FileGetModified(SR); xItem := FSubItems.FindItem(SR.Name); if xItem = nil then begin // new item xItem := FSubItems.Add; xItem.IsFolder := (SR.Attr and faDirectory = faDirectory); xItem.DisplayName := SR.Name; if not xItem.IsFolder then begin xItem.LocalPath := IncludeTrailingPathDelimiter(Self.LocalPath) + Self.DisplayName; end; xItem.State := isBackup; xItem.Created := Now; xItem.UModified := xTime; xItem.uSize := FileGetSize(SR); xItem.NotProcessed := True; xItem.Exists := False; end // new item else begin // existing item if AProcessAll then case xItem.DefAction of daReplace: begin xItem.State := isBackupReplace; xItem.NotProcessed := True; xItem.UModified := xTime; xItem.uSize := FileGetSize(SR); end; daUpdate: begin if CompareDateTime(xItem.Modified, xTime) < 0 then begin xItem.State := isBackupUpdate; xItem.NotProcessed := True; xItem.UModified := xTime; xItem.uSize := FileGetSize(SR); end; end; daNewVersion: begin if CompareDateTime(xItem.Modified, xTime) < 0 then begin xItem.State := isBackupNewVersion; xItem.NotProcessed := True; xItem.UModified := xTime; xItem.uSize := FileGetSize(SR); end; end; end; end; // existing item xItem.BackupItem := True; until FindNext(SR) <> 0; FindClose(SR); end; procedure TNSItem.Refresh; var SR: TSearchRec; tmpDate: TDateTime; procedure ScanBackupItems; var xPath: string; rec: TSearchRec; xItem: TNSItem; begin if FSubItems = nil then Exit; xPath := IncludeTrailingPathDelimiter(IncludeTrailingPathDelimiter(LocalPath) + DisplayName) + sFileMask; if FindFirst(xPath, faAnyFile, rec) <> 0 then Exit; repeat if (rec.Name = sDot) or (rec.Name = sDoubleDot) then Continue; if (rec.Attr and faDirectory <> faDirectory) then if not FProject.IsValidExt(rec.Name) then Continue; xItem := FSubItems.FindItem(rec.Name); if xItem = nil then begin // new item xItem := FSubItems.Add; xItem.IsFolder := (rec.Attr and faDirectory = faDirectory); xItem.DisplayName := rec.Name; if not xItem.IsFolder then begin xItem.LocalPath := IncludeTrailingPathDelimiter(Self.LocalPath) + Self.DisplayName; end; xItem.State := isBackup; xItem.Exists := False; xItem.FCreated := Now; xItem.NotProcessed := True; xItem.Modified := FileGetModified(rec); xItem.Size := FileGetSize(rec); xItem.BackupItem := True; if xItem.IsFolder then xItem.Refresh; end // new item else begin // existing item xItem.Refresh; end; // existing item until FindNext(rec) <> 0; FindClose(rec); end; procedure ScanArchiveItems; var cIndex: integer; cItem: TNSItem; begin if FSubItems = nil then Exit; for cIndex := 0 to FSubItems.Count - 1 do begin if g_AbortRefresh then Abort; cItem := FSubItems[cIndex]; cItem.Refresh; end; // for cIndex end; begin if FIsFolder then begin if FBackupItem then ScanBackupItems else ScanArchiveItems; end else begin if FNotProcessed or g_AbortRefresh then Exit; if FindFirst(IncludeTrailingPathDelimiter(FLocalPath) + FDisplayName, faAnyFile, SR) <> 0 then Exit; tmpDate := FileGetModified(SR); if CompareDateTime(Modified, tmpDate) < 0 then begin if g_AutoRefresh or (ConfirmUpdateDlg(FProject, Self, SR) in [mrYes, mrYesToAll]) then begin State := isBackupUpdate; Modified := tmpDate; Size := FileGetSize(SR); NotProcessed := True; end; end; FindClose(SR); if g_AbortRefresh then Abort; end; end; procedure TNSItem.SetState(const Value: TItemState); var Parent: TNSItem; begin FState := Value; Parent := TNSCollection(Self.Collection).GetParentItem; if (Parent <> nil) and (Parent.State <> Self.State) then Parent.State := isNormal; end; procedure TNSItem.SetUModified(const Value: TDateTime); var Parent: TNSItem; begin FUModified := Value; Parent := TNSCollection(Self.Collection).GetParentItem; if Parent <> nil then Parent.UModified := Now; end; function TNSItem.Mangle: Boolean; var Path: string; OldName: string; NewName: string; Proj: TNSProject; nsz: string; VerNo: integer; begin if not Exists then begin RemoteName := MangleFileName(DisplayName); Result := True; end else begin Result := False; Proj := TNSCollection(Self.Collection).FProject; case Proj.BackupMedia of bmLocal: Path := IncludeTrailingPathDelimiter(Proj.LocalFolder) + GetPathOnMedia; bmFTP: Path := IncludeTrailingPathDelimiter(Proj.HostDirName) + GetPathOnMedia; bmNAS: Path := IncludeTrailingPathDelimiter(Proj.FNasConnection) + GetPathOnMedia; end; OldName := Path + DisplayName + sNsz; NewName := Path + MangleFileName(DisplayName) + sMsz; try {$B+} Result := False; for VerNo := 0 to Versions.Count - 1 do begin nsz := IntToHex(Versions[VerNo].Number, 3); case Proj.BackupMedia of bmLocal, bmNAS: Result := Result or MoveFile(PChar(OldName + nsz), PChar(NewName + nsz)); bmFTP: Result := Result or (RenameFTPFile(PChar(OldName + nsz), PChar(NewName + nsz)) = 0); end; end; except // Result := False; end; {$B-} end; if Result then RemoteName := MangleFileName(DisplayName); end; function TNSItem.IsNameMangled: Boolean; begin Result := (FRemoteName <> EmptyStr) and not AnsiSameText(FDisplayName, FRemoteName); end; { TNSVersions } function TNSVersions.Add: TNSVersion; var LastVersion: integer; begin if Count > 0 then LastVersion := Items[Count - 1].FNumber else LastVersion := -1; Result := TNSVersion(inherited Add); Result.FNumber := LastVersion + 1; end; constructor TNSVersions.Create(AOwner: TNSItem); begin inherited Create(TNSVersion); FOwner := AOwner; end; function TNSVersions.GetItem(Index: integer): TNSVersion; begin Result := TNSVersion(inherited GetItem(index)); end; procedure TNSVersions.SetItem(Index: integer; const Value: TNSVersion); begin inherited SetItem(index, Value); end; { TNSProjectHeader } procedure TNSProjectHeader.AssignProperties(const AProject: TNSProject); begin if AProject <> nil then begin Self.DisplayName := AProject.DisplayName; Self.Kind := AProject.Kind; Self.EncryptionMethod := AProject.EncryptionMethod; Self.LastRunTime := AProject.LastRunTime; end; end; function TNSProjectHeader.LoadFromFile(const AFileName: string): Boolean; var FS: TFileStream; begin Result := False; if not FileExists(AFileName) then Exit; FFileName := AFileName; FS := TFileStream.Create(AFileName, fmOpenRead); try LoadFromStream(FS); Result := True; finally FS.Free; end; end; procedure TNSProjectHeader.LoadFromStream(AStream: TStream); begin if AStream.Size <> 0 then AStream.ReadComponent(Self); end; procedure TNSProjectHeader.SaveToStream(AStream: TStream); begin AStream.WriteComponent(Self); end; { TNSVersion } constructor TNSVersion.Create(Collection: TCollection); begin inherited Create(Collection); FExists := True; end; initialization if GetClass('TNSProject') = nil then RegisterClass(TNSProject); if GetClass('TNSProjectHeader') = nil then RegisterClass(TNSProjectHeader); end.
unit brTindakanU; interface uses Dialogs, Classes, brCommonsU, System.SysUtils, System.StrUtils; type brTindakan = class(bridgeCommon) private function ambilJsonPostTindakan(idxstr : string) : string; function ambilJsonPostTindakanTunggal(id : string) : string; procedure masukkanDelTindakan(id : string); procedure masukkanGetTindakanRef(kdTkp : string); procedure masukkanPostTindakan(id : string); public function getTindakanRef (kdTkp : string; mulaiDari : string = '0' ; jumlahData : string = '100') : Boolean; function postTindakan(idxstr : string) : Boolean; function postTindakanTunggal(id : string) : Boolean; function delTindakan (id_tindakan : string) : Boolean; constructor Create; destructor destroy; // property Uri : string; end; implementation uses SynCommons, synautil; { brTindakan } function brTindakan.ambilJsonPostTindakan(idxstr : string): string; var sql0, sql1 : string; tes : string; i : Integer; V0 , V1, V2, list : Variant; begin Result := '{"i": 0 }'; parameter_bridging('TINDAKAN', 'POST'); sql0 := 'select * from jkn.tindakan_view where idxstr = %s and kd_tindakan_sk = 0 and bpjs_kunjungan is not null;'; sql1 := Format(sql0,[QuotedStr(idxstr)]); fdQuery.Close; fdQuery.SQL.Clear; fdQuery.SQL.Add(sql1); fdQuery.Open(); if fdQuery.IsEmpty then begin fdQuery.Close; Exit; end; fdQuery.First; list := _Arr([]); V1 := _Json(FormatJson); // myJson := _ObjFast([list]); // tambahi id untuk merubah database jika respon sukses V1.Add('id', ''); while not fdQuery.Eof do begin V1.id := fdQuery.FieldByName('id').AsString; V1.noKunjungan := fdQuery.FieldByName('bpjs_kunjungan').AsString; V1.kdTindakan := fdQuery.FieldByName('kd_tindakan').AsString; {/* if not fdQuery.FieldByName('kd_racikan').IsNull then V1.kdRacikan := fdQuery.FieldByName('kd_racikan').AsString; */} V1.biaya := fdQuery.FieldByName('biaya').AsInteger; if not fdQuery.FieldByName('keterangan').IsNull then V1.keterangan := fdQuery.FieldByName('keterangan').AsString; V1.hasil := fdQuery.FieldByName('hasil').AsInteger; list.Add(V1); fdQuery.Next; end; V0 := _Obj(['list', list]); Result := VariantSaveJSON(V0); //FileFromString(Result, 'tes_obat.json'); fdQuery.Close; end; function brTindakan.ambilJsonPostTindakanTunggal(id: string): string; var sql0, sql1 : string; tglStr : string; i : Integer; V1 : Variant; begin Result := ''; parameter_bridging('TINDAKAN', 'POST'); // DateTimeToString(tglSqlStr, 'YYYY-MM-DD', tgl); sql0 := 'select * from jkn.tindakan_view where id = %s and kd_tindakan_sk = 0 and bpjs_kunjungan is not null;'; sql1 := Format(sql0,[QuotedStr(id)]); // ShowMessage(idxstr); fdQuery.Close; fdQuery.SQL.Clear; fdQuery.SQL.Add(sql1); fdQuery.Open(); V1 := _Json(FormatJson); // ShowMessage(FormatJson); if not fdQuery.IsEmpty then begin // ShowMessage('not empty'); jejakIdxstr := fdQuery.FieldByName('idxstr').AsString; V1.kdTindakanSK := fdQuery.FieldByName('kd_tindakan_sk').AsInteger; V1.noKunjungan := fdQuery.FieldByName('bpjs_kunjungan').AsString; V1.kdTindakan := fdQuery.FieldByName('kd_tindakan').AsString; V1.biaya := fdQuery.FieldByName('biaya').AsInteger; if not fdQuery.FieldByName('keterangan').IsNull then V1.keterangan := fdQuery.FieldByName('keterangan').AsString; V1.hasil := fdQuery.FieldByName('hasil').AsInteger; fdQuery.Close; Result := VariantSaveJSON(V1); // FileFromString(Result, 'pendaftaran.json'); end else ShowMessage('data kosong'); //ShowMessage(Result); end; constructor brTindakan.Create; begin inherited Create; //aScript := TStringList.Create; end; function brTindakan.delTindakan(id_tindakan : string): Boolean; var sql0, sql1 : string; tglStr, jejak : string; kdTindakanSk, noKunjungan : string; ts : TMemoryStream; begin Result := False; parameter_bridging('TINDAKAN', 'DELETE'); // mencari parameter pendaftaran //ShowMessage('awal del'); sql0 := 'select kd_tindakan_sk, bpjs_kunjungan from jkn.tindakan_view where id = %s;'; sql1 := Format(sql0, [quotedStr(id_tindakan)]); fdQuery.Close; fdQuery.SQL.Clear; fdQuery.SQL.Add(sql1); fdQuery.Open; //jejak := id_tindakan; kdTindakanSk := fdQuery.FieldByName('kd_tindakan_sk').AsString; noKunjungan := fdQuery.FieldByName('bpjs_kunjungan').AsString; fdQuery.Close; Uri := StringReplace( Uri, '{kdTindakanSK}', kdTindakanSk, []); Uri := StringReplace( Uri, '{noKunjungan}', noKunjungan, []); //Uri := StringReplace(Uri, '{noUrut}', noUrut, []); //showMessage(kdTindakanSk); if StrToIntDef(kdTindakanSk, 0) > 0 then begin //showMessage('tes'); Result := httpDelete(Uri); jejakIdxstr := id_tindakan; if Result then masukkanDelTindakan(id_tindakan); end; FDConn.Close; end; destructor brTindakan.destroy; begin inherited; end; function brTindakan.getTindakanRef(kdTkp : string; mulaiDari, jumlahData: string): Boolean; var sql0, sql1 : string; begin Result := False; parameter_bridging('TINDAKAN REFERENSI', 'GET'); //ShowMessage(uri); Uri := StringReplace( Uri, '{kdTkp}', kdTkp, []); Uri := StringReplace( Uri, '{start}', mulaiDari, []); Uri := StringReplace(Uri, '{limit}', jumlahData, []); //ShowMessage(uri); Result:= httpGet(uri); if Result then masukkanGetTindakanRef(kdTkp); FDConn.Close; end; procedure brTindakan.masukkanDelTindakan(id : string); var dataResp, dataList : Variant; i : Integer; tSl : TStringList; sqlDel0, sqlDel1, sql0, sql1 : string; kdDiag, nmDiag : string; tglStr : string; nonSpesialis : Boolean; kdTindakanSk : integer; kdRacikan : string; begin // ShowMessage('awal masukkan get'); if logRest('DEL', 'TINDAKAN', tsResponse.Text) then begin // DateTimeToString(tglStr, 'YYYY-MM-DD', tgl); tsL := TStringList.Create; try dataResp := _jsonFast(tsResponse.Text); // ShowMessage(tsResponse.Text); sqlDel0 := 'update simpus.tindakan set kd_tindakan_sk = 0 where id_tindakan = %s;'; sqlDel1 := Format(sqlDel0, [quotedStr(id)]); tSl.Add(sqlDel1); finally jalankanScript(tSl); FreeAndNil(tSl); end; end; end; procedure brTindakan.masukkanGetTindakanRef(kdTkp : string); var dataResp, dataList : Variant; i : Integer; tSl : TStringList; sqlDel0, sqlDel1, sql0, sql1 : string; kdTindakan, nmTindakan : string; maxTarif : integer; withValue : Boolean; begin // ShowMessage('awal masukkan get'); if logRest('GET', 'TINDAKAN REFERENSI', tsResponse.Text) then begin sqlDel0 := 'delete from simpus.m_tindakan where adl_bpjs = 1 and kd_tkp = ' + QuotedStr(kdTkp) + ';'; sql0 := 'insert into simpus.m_tindakan(kd_tindakan, nm_tindakan, max_tarif, with_value, kd_tkp) values(%s, %s, %s, %s, %s);'; tsL := TStringList.Create; tSl.Add(sqlDel0); try dataResp := _jsonFast(tsResponse.Text); // ShowMessage(tsResponse.Text); for I := 0 to dataResp.response.list._count - 1 do begin kdTindakan := dataResp.response.list.Value(i).kdTindakan; nmTindakan := dataResp.response.list.Value(i).nmTindakan; // ShowMessage('BooltoStr (nonSpesialis, True)'); maxTarif := dataResp.response.list.Value(i).maxTarif; withValue := dataResp.response.list.Value(i).withValue; sql1 := Format(sql0, [QuotedStr(kdTindakan), quotedStr(nmTindakan), IntToStr(maxTarif), BoolToStr(withValue, True), QuotedStr(kdTkp)]); tSl.Add(sql1); // showMessage(sqlDel1); // showMessage(sql1); end; finally jalankanScript(tSl); FreeAndNil(tSl); end; end; end; procedure brTindakan.masukkanPostTindakan(id :string); var dataResp, dataList : Variant; i : Integer; tSl : TStringList; sqlDel0, sqlDel1, sql0, sql1 : string; kdDiag, nmDiag : string; tglStr : string; nonSpesialis : Boolean; kdTindakanSK : integer; kdRacikan : string; begin // ShowMessage('awal masukkan get'); if logRest('POST', 'TINDAKAN', tsResponse.Text) then begin tsL := TStringList.Create; try dataResp := _jsonFast(tsResponse.Text); // ShowMessage(tsResponse.Text); kdTindakanSK := dataResp.response.message; sqlDel0 := 'update simpus.tindakan set kd_tindakan_sk = %s where id_tindakan = %s;'; sqlDel1 := Format(sqlDel0, [IntToStr(kdTindakanSk), quotedStr(id)]); tSl.Add(sqlDel1); finally jalankanScript(tSl); FreeAndNil(tSl); end; end; end; function brTindakan.postTindakan(idxstr : string): Boolean; var sql0, sql1 : string; tglStr : string; no_urut : Integer; ts : TMemoryStream; V1, V2 : Variant; I: Integer; dataStr : string; js : string; id : string; begin Result := False; //parameter_bridging('OBAT', 'POST'); js := ambilJsonPostTindakan(idxstr); if Length(js) > 30 then begin V1 := _Json(js); ts := TMemoryStream.Create; if V1.list._count > 0 then begin try for I := 0 to V1.list._count - 1 do begin VarClear(V2); V2:= V1.List.Value(i); _Unique(V2); id := V2.id; //showMessage(id); V2.delete('id'); dataStr := VariantSaveJSON(V2); FormatJson := dataStr; ts.Clear; WriteStrToStream(ts, FormatJson); //ts.Write(dataStr[1], Length(dataStr)); //ShowMessage(dataStr); Result := httpPost(Uri, ts); jejakIdxstr := idxstr; if Result then masukkanPostTindakan(id); //FileFromString(dataStr, 'tes_obat'+ IntToStr(i)+'.json'); end; finally ts.Free; end; end; end; FDConn.Close; end; function brTindakan.postTindakanTunggal(id: string): Boolean; var mStream : TMemoryStream; js, jejak : string; begin //jejak := jejakIdxstr; Result := False; //ShowMessage('awal pendaftaran'); js := ambilJsonPostTindakanTunggal(id); //ShowMessage('akhir ambil json pendaftaran'); if Length(js) > 20 then begin mStream := TMemoryStream.Create; WriteStrToStream(mStream, js); FormatJson := js; //Uri := ReplaceStr(Uri, '{puskesmas}', puskesmas); //ShowMessage('awal post pendaftaran'); Result:= httpPost(Uri, mStream); jejakIdxstr := id; //ShowMessage('setelah post pendaftaran'); mStream.Free; end; if Result then masukkanPostTindakan(id); FDConn.Close; end; end.
{ Double Commander ------------------------------------------------------------------------- This unit contains UTF-8 versions of Find(First, Next, Close) functions Copyright (C) 2006-2020 Alexander Koblov (alexx2000@mail.ru) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA } unit uFindEx; {$macro on} {$mode objfpc}{$H+} {$modeswitch advancedrecords} interface uses SysUtils, DCBasicTypes {$IFDEF UNIX} , BaseUnix, DCUnix, uMasks {$ENDIF} {$IFDEF MSWINDOWS} , Windows {$ENDIF} {$IFDEF DARWIN} , MacOSAll {$ENDIF} ; const fffPortable = $80000000; fffElevated = $40000000; type {$IFDEF UNIX} TUnixFindHandle = record DirPtr: PDir; //en> directory pointer for reading directory FindPath: String; //en> file name path Mask: TMask; //en> object that will check mask end; PUnixFindHandle = ^TUnixFindHandle; {$ENDIF} PSearchRecEx = ^TSearchRecEx; TSearchRecEx = record Time : DCBasicTypes.TFileTime; // modification time Size : Int64; Attr : TFileAttrs; Name : String; Flags : UInt32; {$IF DEFINED(MSWINDOWS)} FindHandle : THandle; FindData : Windows.TWin32FindDataW; property PlatformTime: TFileTime read FindData.ftCreationTime; property LastAccessTime: TFileTime read FindData.ftLastAccessTime; {$ELSE} FindHandle : Pointer; FindData : BaseUnix.Stat; property PlatformTime: TUnixTime read FindData.st_ctime; property LastAccessTime: TUnixTime read FindData.st_atime; {$ENDIF} end; function FindFirstEx(const Path: String; Flags: UInt32; out SearchRec: TSearchRecEx): Integer; function FindNextEx(var SearchRec: TSearchRecEx): Integer; procedure FindCloseEx(var SearchRec: TSearchRecEx); implementation uses LazUTF8, uDebug {$IFDEF MSWINDOWS} , DCWindows, DCDateTimeUtils, uMyWindows {$ENDIF} {$IFDEF UNIX} , InitC, Unix, DCOSUtils, DCFileAttributes, DCConvertEncoding {$ENDIF}; {$IF DEFINED(LINUX)} {$define fpgeterrno:= fpgetCerrno} function fpOpenDir(dirname: PAnsiChar): pDir; cdecl; external clib name 'opendir'; function fpReadDir(var dirp: TDir): pDirent; cdecl; external clib name 'readdir64'; function fpCloseDir(var dirp: TDir): cInt; cdecl; external clib name 'closedir'; {$ENDIF} function mbFindMatchingFile(var SearchRec: TSearchRecEx): Integer; {$IFDEF MSWINDOWS} begin with SearchRec do begin if (Flags and fffPortable = 0) then Time:= TWinFileTime(FindData.ftLastWriteTime) else begin Time:= WinFileTimeToUnixTime(TWinFileTime(FindData.ftLastWriteTime)); end; FindData.dwFileAttributes:= ExtractFileAttributes(FindData); Size:= (Int64(FindData.nFileSizeHigh) shl 32) + FindData.nFileSizeLow; Name:= UTF16ToUTF8(UnicodeString(FindData.cFileName)); Attr:= FindData.dwFileAttributes; end; Result:= 0; end; {$ELSE} var UnixFindHandle: PUnixFindHandle absolute SearchRec.FindHandle; begin Result:= -1; if UnixFindHandle = nil then Exit; if (UnixFindHandle^.Mask = nil) or UnixFindHandle^.Mask.Matches(SearchRec.Name) then begin if fpLStat(UTF8ToSys(UnixFindHandle^.FindPath + SearchRec.Name), @SearchRec.FindData) >= 0 then begin with SearchRec.FindData do begin // On Unix a size for directory entry on filesystem is returned in StatInfo. // We don't want to use it. if fpS_ISDIR(st_mode) then SearchRec.Size:= 0 else begin SearchRec.Size:= Int64(st_size); end; SearchRec.Time:= DCBasicTypes.TFileTime(st_mtime); if (SearchRec.Flags and fffPortable = 0) then SearchRec.Attr:= DCBasicTypes.TFileAttrs(st_mode) else begin SearchRec.Attr:= UnixToWinFileAttr(SearchRec.Name, TFileAttrs(st_mode)); end; end; Result:= 0; end; end; end; {$ENDIF} function FindFirstEx(const Path: String; Flags: UInt32; out SearchRec: TSearchRecEx): Integer; {$IFDEF MSWINDOWS} var wsPath: UnicodeString; fInfoLevelId: FINDEX_INFO_LEVELS; begin SearchRec.Flags:= Flags; wsPath:= UTF16LongName(Path); if CheckWin32Version(6, 1) then begin fInfoLevelId:= FindExInfoBasic; Flags:= FIND_FIRST_EX_LARGE_FETCH; end else begin Flags:= 0; fInfoLevelId:= FindExInfoStandard; end; SearchRec.FindHandle:= FindFirstFileExW(PWideChar(wsPath), fInfoLevelId, @SearchRec.FindData, FindExSearchNameMatch, nil, Flags); if SearchRec.FindHandle = INVALID_HANDLE_VALUE then Result:= GetLastError else begin Result:= mbFindMatchingFile(SearchRec); end; end; {$ELSE} var UnixFindHandle: PUnixFindHandle; begin New(UnixFindHandle); SearchRec.Flags:= Flags; SearchRec.FindHandle:= UnixFindHandle; FillChar(UnixFindHandle^, SizeOf(TUnixFindHandle), 0); with UnixFindHandle^ do begin FindPath:= ExtractFileDir(Path); if FindPath = '' then begin FindPath := mbGetCurrentDir; end; FindPath:= IncludeTrailingBackSlash(FindPath); // Assignment of SearchRec.Name also needed if the path points to a specific // file and only a single mbFindMatchingFile() check needs to be done below. SearchRec.Name:= ExtractFileName(Path); // Check if searching for all files. If yes don't need to use Mask. if (SearchRec.Name <> '*') and (SearchRec.Name <> '') then // '*.*' searches for files with a dot in name so mask needs to be checked. begin // If searching for single specific file, just check if it exists and exit. if (Pos('?', SearchRec.Name) = 0) and (Pos('*', SearchRec.Name) = 0) then begin if mbFileSystemEntryExists(Path) and (mbFindMatchingFile(SearchRec) = 0) then Exit(0) else Exit(-1); end; Mask := TMask.Create(SearchRec.Name); end; DirPtr:= fpOpenDir(PAnsiChar(CeUtf8ToSys(FindPath))); if (DirPtr = nil) then Exit(fpgeterrno); end; Result:= FindNextEx(SearchRec); end; {$ENDIF} function FindNextEx(var SearchRec: TSearchRecEx): Integer; {$IFDEF MSWINDOWS} begin if FindNextFileW(SearchRec.FindHandle, SearchRec.FindData) then Result:= mbFindMatchingFile(SearchRec) else begin Result:= GetLastError; end; end; {$ELSE} var PtrDirEnt: pDirent; UnixFindHandle: PUnixFindHandle absolute SearchRec.FindHandle; begin Result:= -1; if UnixFindHandle = nil then Exit; if UnixFindHandle^.DirPtr = nil then Exit; PtrDirEnt:= fpReadDir(UnixFindHandle^.DirPtr^); while PtrDirEnt <> nil do begin SearchRec.Name:= CeSysToUtf8(PtrDirEnt^.d_name); Result:= mbFindMatchingFile(SearchRec); if Result = 0 then // if found then exit Exit else // else read next PtrDirEnt:= fpReadDir(UnixFindHandle^.DirPtr^); end; end; {$ENDIF} procedure FindCloseEx(var SearchRec: TSearchRecEx); {$IFDEF MSWINDOWS} begin if SearchRec.FindHandle <> INVALID_HANDLE_VALUE then Windows.FindClose(SearchRec.FindHandle); end; {$ELSE} var UnixFindHandle: PUnixFindHandle absolute SearchRec.FindHandle; begin if UnixFindHandle = nil then Exit; if UnixFindHandle^.DirPtr <> nil then fpCloseDir(UnixFindHandle^.DirPtr^); if Assigned(UnixFindHandle^.Mask) then UnixFindHandle^.Mask.Free; Dispose(UnixFindHandle); SearchRec.FindHandle:= nil; end; {$ENDIF} end.
unit Personification_MainForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxSplitter, cxGridLevel, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxClasses, dxBar, dxBarExtItems, IBase, ZProc, FIBDataSet, pFIBDataSet, FIBDatabase, pFIBDatabase, ExtCtrls, cxTextEdit, Dates, cxLabel, cxContainer, cxMaskEdit, cxDBEdit, PackageLoad, ZTypes, Unit_ZGlobal_Consts, cxCalendar, cxMemo, cxGridViewData, ActnList, ComCtrls, Personification_DM, dxStatusBar, ZcxLocateBar, zMessages, cxGridBandedTableView, cxGridDBBandedTableView, cxCheckBox, cxGridCustomPopupMenu, cxGridPopupMenu, Menus, Personification_export, ImgList, cxButtonEdit, cxSpinEdit, Personification_AddYearReport, z_uWaitForm, PersDatesAcc; type TMainFormF1df = class(TForm) BarManager: TdxBarManager; RefreshBtn: TdxBarLargeButton; ExitBtn: TdxBarLargeButton; AddReportBtn: TdxBarLargeButton; Styles: TcxStyleRepository; GridTableViewStyleSheetDevExpress: TcxGridTableViewStyleSheet; cxStyle1: TcxStyle; cxStyle2: TcxStyle; cxStyle3: TcxStyle; cxStyle4: TcxStyle; cxStyle5: TcxStyle; cxStyle6: TcxStyle; cxStyle7: TcxStyle; cxStyle8: TcxStyle; cxStyle9: TcxStyle; cxStyle10: TcxStyle; cxStyle11: TcxStyle; cxStyle12: TcxStyle; cxStyle13: TcxStyle; cxStyle14: TcxStyle; cxSplitter1: TcxSplitter; PanelCurrent: TPanel; Grid2Level1: TcxGridLevel; dxStatusBar1: TdxStatusBar; PanelPeople: TPanel; Grid1: TcxGrid; Grid1DBTableView1: TcxGridDBTableView; Grid1ClNumReport: TcxGridDBColumn; Grid1Level1: TcxGridLevel; ActionList: TActionList; SystemAction: TAction; Grid2DBBandedTableView1: TcxGridDBBandedTableView; Grid2: TcxGrid; GridBandedTableViewStyleSheetDevExpress: TcxGridBandedTableViewStyleSheet; cxStyle15: TcxStyle; cxStyle16: TcxStyle; cxStyle17: TcxStyle; cxStyle18: TcxStyle; cxStyle19: TcxStyle; cxStyle20: TcxStyle; cxStyle21: TcxStyle; cxStyle22: TcxStyle; cxStyle23: TcxStyle; cxStyle24: TcxStyle; cxStyle25: TcxStyle; cxStyle26: TcxStyle; cxStyle27: TcxStyle; cxStyle28: TcxStyle; cxStyle29: TcxStyle; cxStyle30: TcxStyle; grid1ClDateReport: TcxGridDBColumn; Grid2ClTin: TcxGridDBBandedColumn; Grid2ClBirthDate: TcxGridDBBandedColumn; Grid2ClFio: TcxGridDBBandedColumn; DelReportBtn: TdxBarLargeButton; cxGridPopupMenu1: TcxGridPopupMenu; Grid2ClSex: TcxGridDBBandedColumn; ExportBtn: TdxBarLargeButton; GroupBtn: TdxBarLargeButton; Grid2DBis_science: TcxGridDBBandedColumn; Panel1: TPanel; cxSplitter3: TcxSplitter; Panel3: TPanel; Grid3: TcxGrid; Grid3DBBandedTableView1: TcxGridDBBandedTableView; Grid3ClKodSetup: TcxGridDBBandedColumn; Grid3ClSumAll: TcxGridDBBandedColumn; Grid3ClPensiya: TcxGridDBBandedColumn; Grid3ClBol: TcxGridDBBandedColumn; Grid3ClSumPens: TcxGridDBBandedColumn; Grid3ClStaj: TcxGridDBBandedColumn; Grid3ClIsMain: TcxGridDBBandedColumn; Grid3ClIsInv: TcxGridDBBandedColumn; Grid3DBis_science: TcxGridDBBandedColumn; cxGridLevel1: TcxGridLevel; cxSplitter2: TcxSplitter; Panel2: TPanel; cxGrid1: TcxGrid; cxGridDBBandedTableView1: TcxGridDBBandedTableView; Grid3ClVo: TcxGridDBBandedColumn; Grid3ClVidOpl: TcxGridDBBandedColumn; Grid3ClSumma: TcxGridDBBandedColumn; Grid3ClP1: TcxGridDBBandedColumn; Grid3ClDepartment: TcxGridDBBandedColumn; Grid3ClSmeta: TcxGridDBBandedColumn; Grid3ClKodSetup3: TcxGridDBBandedColumn; Grid3ClReCount: TcxGridDBBandedColumn; Grid3ClNDay: TcxGridDBBandedColumn; Grid3ClClock: TcxGridDBBandedColumn; Grid3ClStavkaPercent: TcxGridDBBandedColumn; Grid3Level1: TcxGridLevel; procedure ExitBtnClick(Sender: TObject); procedure AddReportBtnClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure RefreshBtnClick(Sender: TObject); procedure DelReportBtnClick(Sender: TObject); procedure Grid1DBTableView1FocusedRecordChanged( Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean); procedure FormShow(Sender: TObject); procedure Grid2DBBandedTableView1KeyPress(Sender: TObject; var Key: Char); procedure Grid3ClKodSetupGetDisplayText(Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); procedure ExportBtnClick(Sender: TObject); procedure dxStatusBar1Resize(Sender: TObject); procedure GroupBtnClick(Sender: TObject); procedure Grid3DBBandedTableView1DblClick(Sender: TObject); procedure cxGridDBBandedTableView1DataControllerSummaryDefaultGroupSummaryItemsSummary( ASender: TcxDataSummaryItems; Arguments: TcxSummaryEventArguments; var OutArguments: TcxSummaryEventOutArguments); procedure cxGridDBBandedTableView1DataControllerSummaryFooterSummaryItemsSummary( ASender: TcxDataSummaryItems; Arguments: TcxSummaryEventArguments; var OutArguments: TcxSummaryEventOutArguments); procedure Grid3ClP1GetDisplayText(Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); procedure Grid3ClKodSetup3GetDisplayText( Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); procedure FormResize(Sender: TObject); private DM:TDM; PBarLocate:TZBarLocate; PLanguageIndex:Byte; public constructor Create(AOwner:TComponent;Db_Handle:TISC_DB_HANDLE);reintroduce; end; implementation uses Math, FIBQuery; {$R *.dfm} constructor TMainFormF1df.Create(AOwner:TComponent;Db_Handle:TISC_DB_HANDLE); begin inherited Create(AOwner); PLanguageIndex:=LanguageIndex; //****************************************************************************** Caption := FZ_Personification_Caption[PLanguageIndex]; AddReportBtn.Caption := AddReport_Caption[PLanguageIndex]; DelReportBtn.Caption := DelReport_Caption[PLanguageIndex]; ExitBtn.Caption := ExitBtn_Caption[PLanguageIndex]; RefreshBtn.Caption := RefreshBtn_Caption[PLanguageIndex]; Grid1ClNumReport.Caption := GridClNumberShort_Caption[pLanguageIndex]; grid1ClDateReport.Caption := GridClDate_Caption[pLanguageIndex]; Grid2ClFio.Caption := GridClFIO_Caption[PLanguageIndex]; Grid2ClTin.Caption := GridClTin_Caption[PLanguageIndex]; Grid2ClBirthDate.Caption := GridClDateCame_Caption[PLanguageIndex]; Grid3ClKodSetup.Caption := GridClKodSetup_Caption[pLanguageIndex]; Grid3ClSumAll.Caption := GridClAll_Caption[pLanguageIndex]; Grid3ClPensiya.Caption := GridClPensSum_Caption[pLanguageIndex]; Grid3ClBol.Caption := GridClHospSum_Caption[pLanguageIndex]; Grid3ClSumPens.Caption := GridClVznosSum_Caption[pLanguageIndex]; Grid3ClStaj.Caption := GridClStaj_Caption[pLanguageIndex]; Grid3ClVo.Caption := GridClKodVidOpl_Caption[PLanguageIndex]; Grid3ClVidOpl.Caption := GridClNameVidopl_Caption[PLanguageIndex]; Grid3ClSumma.Caption := GridClSumma_Caption[PLanguageIndex]; Grid3ClP1.Caption := GridClP1_Caption[PLanguageIndex]; Grid3ClDepartment.Caption := GridClKodDepartment_Caption[PLanguageIndex]; Grid3ClSmeta.Caption := GridClKodSmeta_Caption[PLanguageIndex]; Grid3ClKodSetup3.Caption := GridClKodSetup_Caption[PLanguageIndex]; Grid3ClReCount.Caption := ''; Grid3ClNDay.Caption := GridClNday_Caption[PLanguageIndex]; Grid3ClClock.Caption := GridClClock_Caption[PLanguageIndex]; Grid3ClStavkaPercent.Caption := GridClStavkaPercent_Caption[PLanguageIndex]; //Grid3DBBandedTableView1.DataController.Summary.FooterSummaryItems[1].Format := Itogo_Caption[PLanguageIndex]+':'; //****************************************************************************** DM := TDM.Create(self,Db_Handle); //****************************************************************************** dxStatusBar1.Panels[0].Text:= ShortCutToText(AddReportBtn.ShortCut)+'-'+AddReportBtn.Caption; dxStatusBar1.Panels[1].Text:= ShortCutToText(DelReportBtn.ShortCut)+'-'+DelReportBtn.Caption; dxStatusBar1.Panels[2].Text:= ShortCutToText(RefreshBtn.ShortCut)+'-'+RefreshBtn.Caption; dxStatusBar1.Panels[5].Text:= ShortCutToText(ExitBtn.ShortCut)+'-'+ExitBtn.Caption; //****************************************************************************** Grid1DBTableView1.DataController.DataSource := DM.DSource1; Grid2DBBandedTableView1.DataController.DataSource := DM.DSource2; Grid3DBBandedTableView1.DataController.DataSource := DM.DSource3; cxGridDBBandedTableView1.DataController.DataSource := DM.DSource4; //****************************************************************************** WindowState := wsMaximized; //****************************************************************************** end; procedure TMainFormF1df.ExitBtnClick(Sender: TObject); begin Close; end; procedure TMainFormF1df.AddReportBtnClick(Sender: TObject); var ViewForm:TFAddYearReport; begin ViewForm := TFAddYearReport.Create(Self,DM.DB.Handle); if ViewForm.ShowModal=mrYes then begin DM.DSet1.SQLs.InsertSQL.Text := 'execute procedure Z_EMPTY_PROC'; DM.DSet1.SQLs.RefreshSQL.Text := 'SELECT * FROM Z_PERSONIFICATION_REPORT_S_BY_K('+IntToStr(ViewForm.Id_report)+')'; DM.DSet1.Insert; DM.DSet1.Post; end; ViewForm.Destroy; end; procedure TMainFormF1df.FormClose(Sender: TObject; var Action: TCloseAction); begin if FormStyle=fsMDIChild then Action:=caFree; end; procedure TMainFormF1df.FormDestroy(Sender: TObject); begin if not(DM=nil) then DM.Destroy; end; procedure TMainFormF1df.RefreshBtnClick(Sender: TObject); begin DM.DSet3.Close; DM.DSet2.Close; DM.DSet1.CloseOpen(True); DM.DSet2.Open; DM.DSet3.Open; end; procedure TMainFormF1df.DelReportBtnClick(Sender: TObject); var wf:TForm; begin if ZShowMessage(Caption_Delete[PLanguageIndex],DeleteRecordQuestion_Text[PLanguageIndex],mtConfirmation,[mbYes,mbNo])=mrYes then try wf:=ShowWaitForm(self,zwfDeleteData); with DM do try StProc.StoredProcName := 'Z_PERSONIFICATION_REPORT_D'; StProc.Transaction.StartTransaction; StProc.Prepare; StProc.ParamByName('ID').AsInteger := DSet1['ID']; StProc.ExecProc; StProc.Transaction.Commit; DSet1.SQLs.DeleteSQL.Text := 'execute procedure Z_EMPTY_PROC'; DSet1.Delete; except on E:exception do begin ZShowMessage(Error_Caption[PLanguageIndex],e.Message,mtError,[mbOk]); StProc.Transaction.Rollback; end; end; finally CloseWaitForm(wf); end; end; procedure TMainFormF1df.Grid1DBTableView1FocusedRecordChanged( Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean); begin if (AFocusedRecord=nil) or (AFocusedRecord.Expandable) then begin Grid2DBBandedTableView1.DataController.DataSource:=nil; DelReportBtn.Enabled := False; end else begin Grid2DBBandedTableView1.DataController.DataSource:=DM.DSource2; DelReportBtn.Enabled := True; end; end; procedure TMainFormF1df.FormShow(Sender: TObject); begin Grid1DBTableView1FocusedRecordChanged(Grid1DBTableView1,nil,Grid1DBTableView1.Controller.FocusedRecord,True); FormResize(Self); end; procedure TMainFormF1df.Grid2DBBandedTableView1KeyPress(Sender: TObject; var Key: Char); begin If (Key in ['0'..'9']) then begin if (Grid2DBBandedTableView1.OptionsBehavior.IncSearchItem<>Grid2ClTin)then begin Grid2DBBandedTableView1.Controller.IncSearchingText := ''; Grid2DBBandedTableView1.OptionsBehavior.IncSearchItem := Grid2ClTin; end end else if (Grid2DBBandedTableView1.OptionsBehavior.IncSearchItem<>Grid2ClFio)then begin Grid2DBBandedTableView1.Controller.IncSearchingText := ''; Grid2DBBandedTableView1.OptionsBehavior.IncSearchItem := Grid2ClFIO; end; end; procedure TMainFormF1df.Grid3ClKodSetupGetDisplayText( Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); begin Atext:=KodSetupToPeriod(StrToInt(AText),0); end; procedure TMainFormF1df.ExportBtnClick(Sender: TObject); begin ExportToDBF(self,DM.DB.Handle,DM.DSet1['ID']); end; procedure TMainFormF1df.dxStatusBar1Resize(Sender: TObject); var i:integer; begin for i:=0 to dxStatusBar1.Panels.Count-1 do dxStatusBar1.Panels[i].Width := dxStatusBar1.Width div dxStatusBar1.Panels.Count; end; procedure TMainFormF1df.GroupBtnClick(Sender: TObject); begin Grid3DBBandedTableView1.OptionsView.GroupByBox := GroupBtn.Down; if Grid3DBBandedTableView1.OptionsView.GroupByBox then Grid3ClKodSetup.GroupIndex := 0 else Grid3ClKodSetup.GroupIndex := -1; Grid3ClKodSetup.Visible := not GroupBtn.Down; end; procedure TMainFormF1df.Grid3DBBandedTableView1DblClick(Sender: TObject); var id_anketa:Int64; begin if Grid3DBBandedTableView1.DataController.DataSource.DataSet.RecordCount>0 then begin id_anketa:=Grid2DBBandedTableView1.DataController.DataSource.DataSet['id']; with TFZDateAcc.Create(self,DM.DB.Handle,id_anketa, Grid3DBBandedTableView1.DataController.DataSource.DataSet['KOD_SETUP2'], Grid3DBBandedTableView1.DataController.DataSource.DataSet['is_science']) do begin ShowModal; Free; end; end; end; procedure TMainFormF1df.cxGridDBBandedTableView1DataControllerSummaryDefaultGroupSummaryItemsSummary( ASender: TcxDataSummaryItems; Arguments: TcxSummaryEventArguments; var OutArguments: TcxSummaryEventOutArguments); var AItem: TcxGridTableSummaryItem; begin AItem := TcxGridTableSummaryItem(Arguments.SummaryItem); if (AItem.Column = Grid3ClSumma) and (AItem.Kind = skSum) and (AItem.Position = spGroup) then begin if (AItem.Column.GroupIndex<Grid3ClP1.GroupIndex) and (VarToStr(cxGridDBBandedTableView1.DataController.Values[Arguments.RecordIndex, Grid3ClP1.Index]) ='F') then OutArguments.Value:=-OutArguments.Value; end; end; procedure TMainFormF1df.cxGridDBBandedTableView1DataControllerSummaryFooterSummaryItemsSummary( ASender: TcxDataSummaryItems; Arguments: TcxSummaryEventArguments; var OutArguments: TcxSummaryEventOutArguments); var AItem: TcxGridTableSummaryItem; begin AItem := TcxGridTableSummaryItem(Arguments.SummaryItem); if (AItem.Column = Grid3ClSumma) and (AItem.Kind = skSum) and (AItem.Position = spGroup) then begin if (AItem.Column.GroupIndex<Grid3ClP1.GroupIndex) and (VarToStr(cxGridDBBandedTableView1.DataController.Values[Arguments.RecordIndex, Grid3ClP1.Index]) ='F') then OutArguments.Value:=-OutArguments.Value; end; end; procedure TMainFormF1df.Grid3ClP1GetDisplayText( Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); begin if AText='False' then AText:=GridClP1_Text_False[PLanguageIndex]; if AText='True' then AText:=GridClP1_Text_True[PLanguageIndex]; end; procedure TMainFormF1df.Grid3ClKodSetup3GetDisplayText( Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); begin Atext:=KodSetupToPeriod(StrToInt(Atext),1); end; procedure TMainFormF1df.FormResize(Sender: TObject); begin Grid2.Height:=PanelPeople.Height div 8; Panel1.Height:=(PanelPeople.Height div 8)*7; cxSplitter3.Top:=Panel1.Top-1; PanelPeople.Width:=Self.ClientWidth div 4; cxSplitter1.Left:=PanelPeople.Left+PanelPeople.Width+1; Grid3.Height :=(Panel1.Height div 5)*3; Panel2.Height:=(Panel1.Height div 5)*2; cxSplitter2.Top:=Panel2.Top-1; cxGridDBBandedTableView1.ViewData.Expand(true); end; end.
unit uRelatAssPendentes; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, JvExStdCtrls, JvButton, JvCtrls, JvComponentBase, JvEnterTab, Vcl.Buttons, Vcl.Grids, Vcl.DBGrids, Vcl.Mask, JvExMask, JvToolEdit, Vcl.ExtCtrls, Data.DB, uDadosRelat; type TfrmRelatAssPendentes = class(TForm) GroupBox1: TGroupBox; Label1: TLabel; edtDataFim: TJvDateEdit; edtDataIni: TJvDateEdit; GroupBoxLista: TGroupBox; dbgGrid: TDBGrid; JvEnterAsTab: TJvEnterAsTab; btnOkAssinante: TJvImgBtn; rgAgrupar: TRadioGroup; DataSource: TDataSource; Panel1: TPanel; btnMarcarDesmarcar: TBitBtn; edtFiltro: TLabeledEdit; GroupBox2: TGroupBox; dbgZonas: TDBGrid; Panel2: TPanel; btnMarcarDesmarcarZonas: TBitBtn; edtFiltroZonas: TLabeledEdit; dsZonas: TDataSource; procedure btnOkAssinanteClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure dbgGridDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure dbgGridCellClick(Column: TColumn); procedure btnMarcarDesmarcarClick(Sender: TObject); procedure rgAgruparClick(Sender: TObject); procedure edtFiltroChange(Sender: TObject); procedure dbgZonasCellClick(Column: TColumn); procedure dbgZonasDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure btnMarcarDesmarcarZonasClick(Sender: TObject); procedure edtFiltroZonasChange(Sender: TObject); private { Private declarations } FModuloRelat: TdmDadosRelat; procedure ControlaTela; public { Public declarations } end; var frmRelatAssPendentes: TfrmRelatAssPendentes; implementation {$R *.dfm} procedure TfrmRelatAssPendentes.btnMarcarDesmarcarClick(Sender: TObject); begin case rgAgrupar.ItemIndex of 0: // Vendedore begin if btnMarcarDesmarcar.Tag = 0 then begin FModuloRelat.MarcarDesmarcarVendedores(true); btnMarcarDesmarcar.Tag := 1; end else begin FModuloRelat.MarcarDesmarcarVendedores(false); btnMarcarDesmarcar.Tag := 0; end; end; 1: // Grupo de vendedores begin if btnMarcarDesmarcar.Tag = 0 then begin FModuloRelat.MarcarDesmarcarGruposVendedores(true); btnMarcarDesmarcar.Tag := 1; end else begin FModuloRelat.MarcarDesmarcarGruposVendedores(false); btnMarcarDesmarcar.Tag := 0; end; end; 2: // Cobrador begin if btnMarcarDesmarcar.Tag = 0 then begin FModuloRelat.MarcarDesmarcarCobradores(true); btnMarcarDesmarcar.Tag := 1; end else begin FModuloRelat.MarcarDesmarcarCobradores(false); btnMarcarDesmarcar.Tag := 0; end; end; end; end; procedure TfrmRelatAssPendentes.btnMarcarDesmarcarZonasClick(Sender: TObject); begin if btnMarcarDesmarcarZonas.Tag = 0 then begin FModuloRelat.MarcarDesmarcarZonas(true); btnMarcarDesmarcarZonas.Tag := 1; end else begin FModuloRelat.MarcarDesmarcarZonas(false); btnMarcarDesmarcarZonas.Tag := 0; end; end; procedure TfrmRelatAssPendentes.btnOkAssinanteClick(Sender: TObject); begin FModuloRelat.ShowReportAssinaturasPendentes(rgAgrupar.ItemIndex, edtDataIni.Date, edtDataFim.Date); end; procedure TfrmRelatAssPendentes.ControlaTela; begin btnMarcarDesmarcar.Tag := 0; edtFiltro.Text := ''; case rgAgrupar.ItemIndex of 0: // Vendedor begin GroupBoxLista.Caption := 'Selecione os vendedores desejados'; FModuloRelat.CarregarVendedores; DataSource.DataSet := FModuloRelat.cdsVendedores; dbgGrid.Columns[1].FieldName := 'vencod'; dbgGrid.Columns[2].FieldName := 'vennome'; end; 1: // Grupo de vendedores begin GroupBoxLista.Caption := 'Selecione os grupos de vendedores desejados'; FModuloRelat.CarregarGruposVendedores; DataSource.DataSet := FModuloRelat.cdsGruposVendedores; dbgGrid.Columns[1].FieldName := 'gdvcod'; dbgGrid.Columns[2].FieldName := 'gdvdescr'; end; 2: // Cobrador begin GroupBoxLista.Caption := 'Selecione os cobradores desejados'; FModuloRelat.CarregarCobradores; DataSource.DataSet := FModuloRelat.cdsCobradores; dbgGrid.Columns[1].FieldName := 'cobcod'; dbgGrid.Columns[2].FieldName := 'cobnome'; end; end; end; procedure TfrmRelatAssPendentes.dbgGridCellClick(Column: TColumn); begin if Column.FieldName = 'CalcSelecionado' then begin if dbgGrid.DataSource.DataSet.RecordCount > 0 then begin dbgGrid.DataSource.DataSet.edit; dbgGrid.DataSource.DataSet.FieldByName('CalcSelecionado').Value := not dbgGrid.DataSource.DataSet.FieldByName('CalcSelecionado').AsBoolean; dbgGrid.DataSource.DataSet.Post; end; end; end; procedure TfrmRelatAssPendentes.dbgGridDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); const IS_CHECK : Array[Boolean] of Integer = (DFCS_BUTTONCHECK, DFCS_BUTTONCHECK or DFCS_CHECKED); var Check : Integer; R : TRect; begin with dbgGrid do begin if Column.FieldName = 'CalcSelecionado' then begin Canvas.FillRect(Rect); Check := IS_CHECK[Column.Field.AsBoolean]; R := Rect; InflateRect(R,-2,-2); //aqui manipula o tamanho do checkBox DrawFrameControl(Canvas.Handle,rect,DFC_BUTTON,Check) end; end; end; procedure TfrmRelatAssPendentes.dbgZonasCellClick(Column: TColumn); begin if Column.FieldName = 'CalcSelecionado' then begin if dbgZonas.DataSource.DataSet.RecordCount > 0 then begin dbgZonas.DataSource.DataSet.edit; dbgZonas.DataSource.DataSet.FieldByName('CalcSelecionado').Value := not dbgZonas.DataSource.DataSet.FieldByName('CalcSelecionado').AsBoolean; dbgZonas.DataSource.DataSet.Post; end; end; end; procedure TfrmRelatAssPendentes.dbgZonasDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); const IS_CHECK : Array[Boolean] of Integer = (DFCS_BUTTONCHECK, DFCS_BUTTONCHECK or DFCS_CHECKED); var Check : Integer; R : TRect; begin with dbgZonas do begin if Column.FieldName = 'CalcSelecionado' then begin Canvas.FillRect(Rect); Check := IS_CHECK[Column.Field.AsBoolean]; R := Rect; InflateRect(R,-2,-2); //aqui manipula o tamanho do checkBox DrawFrameControl(Canvas.Handle,rect,DFC_BUTTON,Check) end; end; end; procedure TfrmRelatAssPendentes.edtFiltroChange(Sender: TObject); var Filter: String; begin Filter := dbgGrid.Columns[2].FieldName + ' like ''%' + edtFiltro.Text + '%'''; DataSource.DataSet.Filtered := false; DataSource.DataSet.Filter := Filter; DataSource.DataSet.Filtered := True; end; procedure TfrmRelatAssPendentes.edtFiltroZonasChange(Sender: TObject); var Filter: String; begin Filter := dbgZonas.Columns[2].FieldName + ' like ''%' + edtFiltroZonas.Text + '%'''; dsZonas.DataSet.Filtered := false; dsZonas.DataSet.Filter := Filter; dsZonas.DataSet.Filtered := True; end; procedure TfrmRelatAssPendentes.FormCreate(Sender: TObject); begin FModuloRelat := TdmDadosRelat.Create(self); DataSource.DataSet := FModuloRelat.cdsCobradores; dsZonas.DataSet := FModuloRelat.cdsZonas; FModuloRelat.CarregarZonas; FModuloRelat.MarcarDesmarcarZonas(true); ControlaTela; end; procedure TfrmRelatAssPendentes.rgAgruparClick(Sender: TObject); begin ControlaTela; end; end.
{ Datamove - Conversor de Banco de Dados Firebird para Oracle licensed under a APACHE 2.0 Projeto Particular desenvolvido por Artur Barth e Gilvano Piontkoski para realizar conversão de banco de dados firebird para Oracle. Esse não é um projeto desenvolvido pela VIASOFT. Toda e qualquer alteração deve ser submetida à https://github.com/Arturbarth/Datamove } unit uParametrosConexao; interface uses uEnum; type IParametrosConexao = interface ['{63587B88-E13E-4DB7-A93D-12D6D4B3D6F8}'] function GetServer: string; function GetPorta: string; function GetBanco: string; function GetUsuario: string; function GetSenha: string; function GetDriverID: string; end; TParametrosConexao = class(TInterfacedObject, IParametrosConexao) private FBanco: string; FPooled: Boolean; FSenha: string; FUsuario: string; FPorta: string; FServer: string; FDriverID: string; procedure SetBanco(const Value: string); procedure SetPooled(const Value: Boolean); procedure SetPorta(const Value: string); procedure SetSenha(const Value: string); procedure SetServer(const Value: string); procedure SetUsuario(const Value: string); function GetBanco: string; function GetPorta: string; function GetSenha: string; function GetServer: string; function GetUsuario: string; procedure SetDriverID(const Value: string); function GetDriverID: string; { private declarations } protected { protected declarations } public { public declarations } property Server: string read GetServer write SetServer; property Porta: string read GetPorta write SetPorta; property Banco: string read GetBanco write SetBanco; property Usuario: string read GetUsuario write SetUsuario; property Senha: string read GetSenha write SetSenha; property DriverID: string read GetDriverID write SetDriverID; property Pooled: Boolean read FPooled write SetPooled; constructor Create(AServer, APorta, ABanco, AUsuario, ASenha, ADriverID: string); overload; class function New(AServer, APorta, ABanco, AUsuario, ASenha, ADriverID: string): IParametrosConexao; published { published declarations } end; implementation { TParametrosConexao } constructor TParametrosConexao.Create(AServer, APorta, ABanco, AUsuario, ASenha, ADriverID: string); begin SetServer(AServer); SetPorta(APorta); SetBanco(ABanco); SetUsuario(AUsuario); SetSenha(ASenha); SetDriverID(ADriverID); end; function TParametrosConexao.GetBanco: string; begin Result := FBanco; end; function TParametrosConexao.GetDriverID: string; begin Result := FDriverID; end; function TParametrosConexao.GetPorta: string; begin Result := FPorta; end; function TParametrosConexao.GetSenha: string; begin Result := FSenha; end; function TParametrosConexao.GetServer: string; begin Result := FServer; end; function TParametrosConexao.GetUsuario: string; begin Result := FUsuario; end; class function TParametrosConexao.New(AServer, APorta, ABanco, AUsuario, ASenha, ADriverID: string): IParametrosConexao; begin Result := TParametrosConexao.Create(AServer, APorta, ABanco, AUsuario, ASenha, ADriverID); end; procedure TParametrosConexao.SetBanco(const Value: string); begin FBanco := Value; end; procedure TParametrosConexao.SetDriverID(const Value: string); begin FDriverID := Value; end; procedure TParametrosConexao.SetPooled(const Value: Boolean); begin FPooled := Value; end; procedure TParametrosConexao.SetPorta(const Value: string); begin FPorta := Value; end; procedure TParametrosConexao.SetSenha(const Value: string); begin FSenha := Value; end; procedure TParametrosConexao.SetServer(const Value: string); begin FServer := Value; end; procedure TParametrosConexao.SetUsuario(const Value: string); begin FUsuario := Value; end; end. { Datamove - Conversor de Banco de Dados Firebird para Oracle licensed under a APACHE 2.0 Projeto Particular desenvolvido por Artur Barth e Gilvano Piontkoski para realizar conversão de banco de dados firebird para Oracle. Esse não é um projeto desenvolvido pela VIASOFT. Toda e qualquer alteração deve ser submetida à https://github.com/Arturbarth/Datamove }
{*************************************************************** Projekt Name: TBigNum Beschreibung: Mit TBigNum ist möglich mit großen Zahlen in Delphi, Kylix und Object Pascal zu rechnen. Copyright © 2003 Martin Winandy This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Kontakt: Martin Winandy Wenzelbachstr. 122 54595 Prüm Germany pmw14@web.de ****************************************************************} unit UniTBigNum; interface uses Windows; var ISystem: Byte; IMaxLenNachKomma: Integer; type TBigNum = class public Wert: AnsiString; Negativ: Bool; Komma: Integer; procedure EntferneNullen; function GroesserAls(BIZahl: TBigNum): Short; procedure Addiere(Summand1,Summand2: TBigNum); procedure Subtrahiere(Minuend,Subtrahend: TBigNum); procedure Multipliziere(Multiplikand,Multiplikator: TBigNum); procedure Dividiere(Dividend,Divisor: TBigNum); procedure Potenziere(Basis,Exponent: TBigNum); procedure ZieheWurzel(Basis,Exponent: TBigNum); procedure ToString(var SString: AnsiString); procedure ToRechnung(var SRechnung: AnsiString); procedure FromString(var SString: AnsiString); procedure FromRechnung(var SRechnung: AnsiString; IAnfang,ILaenge: Integer); procedure CopyFrom(BIZahl: TBigNum); procedure Runde; end; exports ISystem, IMaxLenNachKomma; implementation procedure TBigNum.EntferneNullen; var ISchleife: Integer; begin if length(Wert) = 1 then exit; if Komma > 1 then begin for ISchleife := 1 to Komma-1 do begin if not (Wert[ISchleife] = #0) then break; end; Delete(Wert,1,ISchleife-1); Dec(Komma,ISchleife-1); end; if length(Wert) > Komma then begin for ISchleife := length(Wert) downto Komma+1 do begin if not (Wert[ISchleife] = #0) then break; end; Delete(Wert,ISchleife+1,length(Wert)-ISchleife); end; end; function TBigNum.GroesserAls(BIZahl: TBigNum): Short; var IStelle,IEnde: Integer; begin if Komma > BIZahl.Komma then begin result := 1; exit; end else if Komma < BIZahl.Komma then begin result := -1; exit; end; if length(Wert) > length(BIZahl.Wert) then begin IEnde := length(BIZahl.Wert); result := 1; end else if length(Wert) < length(BIZahl.Wert) then begin IEnde := length(Wert); result := -1; end else begin IEnde := length(Wert); result := 0; end; for IStelle := 1 to IEnde do begin if Ord(Wert[IStelle]) > Ord(BIZahl.Wert[IStelle]) then begin result := 1; exit; end else if Ord(Wert[IStelle]) < Ord(BIZahl.Wert[IStelle]) then begin result := -1; exit; end end; end; procedure TBigNum.Addiere(Summand1,Summand2: TBigNum); var IStelle,IUebertrag,IZiffer1,IZiffer2, IPlusZiffernVorneZahl1,IPlusZiffernVorneZahl2,IPlusZiffernHintenZahl1: Integer; BISummand1,BISummand2: TBigNum; begin BISummand1 := TBigNum.Create; BISummand1.CopyFrom(Summand1); BISummand2 := TBigNum.Create; BISummand2.CopyFrom(Summand2); IPlusZiffernVorneZahl2 := 0; IPlusZiffernVorneZahl1 := 0; IPlusZiffernHintenZahl1 := 0; if BISummand1.Komma > BISummand2.Komma then begin IPlusZiffernVorneZahl2 := BISummand1.Komma-BISummand2.Komma; end else if BISummand2.Komma > BISummand1.Komma then begin IPlusZiffernVorneZahl1 := BISummand2.Komma-BISummand1.Komma; end; if length(BISummand2.Wert)+IPlusZiffernVorneZahl2 > length(BISummand1.Wert)+IPlusZiffernVorneZahl1 then begin IPlusZiffernHintenZahl1 := length(BISummand2.Wert)+IPlusZiffernVorneZahl2 - (length(BISummand1.Wert)+IPlusZiffernVorneZahl1); end; SetLength(Wert,IPlusZiffernVorneZahl1+length(BISummand1.Wert)+IPlusZiffernHintenZahl1); Komma := IPlusZiffernVorneZahl1+BISummand1.Komma; IUebertrag := 0; for IStelle := length(Wert) downto 1 do begin if (IStelle-IPlusZiffernVorneZahl1 >= 1) and (IStelle-IPlusZiffernVorneZahl1 <= length(BISummand1.Wert)) then IZiffer1 := Ord(BISummand1.Wert[IStelle-IPlusZiffernVorneZahl1]) else IZiffer1 := 0; if (IStelle-IPlusZiffernVorneZahl2 >= 1) and (IStelle-IPlusZiffernVorneZahl2 <= length(BISummand2.Wert)) then IZiffer2 := Ord(BISummand2.Wert[IStelle-IPlusZiffernVorneZahl2]) else IZiffer2 := 0; Wert[IStelle] := Char((IZiffer1+IZiffer2+IUebertrag) mod ISystem); IUebertrag := (IZiffer1+IZiffer2+IUebertrag) div ISystem; end; if IUebertrag > 0 then begin Wert := Char(IUebertrag)+Wert; Inc(Komma); end; BISummand1.Free; BISummand2.Free; end; procedure TBigNum.Subtrahiere(Minuend,Subtrahend: TBigNum); var IStelle, IUebertrag,IZiffer1,IZiffer2, IPlusZiffernVorneZahl1,IPlusZiffernVorneZahl2,IPlusZiffernHintenZahl1: Integer; BIMinuend,BISubtrahend: TBigNum; begin BIMinuend := TBigNum.Create; BIMinuend.CopyFrom(Minuend); BISubtrahend := TBigNum.Create; BISubtrahend.CopyFrom(Subtrahend); IPlusZiffernVorneZahl2 := 0; IPlusZiffernVorneZahl1 := 0; IPlusZiffernHintenZahl1 := 0; if BIMinuend.Komma > BISubtrahend.Komma then begin IPlusZiffernVorneZahl2 := BIMinuend.Komma-BISubtrahend.Komma; end else if BISubtrahend.Komma > BIMinuend.Komma then begin IPlusZiffernVorneZahl1 := BISubtrahend.Komma-BIMinuend.Komma; end; if length(BISubtrahend.Wert)+IPlusZiffernVorneZahl2 > length(BIMinuend.Wert)+IPlusZiffernVorneZahl1 then begin IPlusZiffernHintenZahl1 := length(BISubtrahend.Wert)+IPlusZiffernVorneZahl2 - (length(BIMinuend.Wert)+IPlusZiffernVorneZahl1); end; SetLength(Wert,IPlusZiffernVorneZahl1+length(BIMinuend.Wert)+IPlusZiffernHintenZahl1); Komma := IPlusZiffernVorneZahl1+BIMinuend.Komma; IUebertrag := 0; for IStelle := length(Wert) downto 1 do begin if (IStelle-IPlusZiffernVorneZahl1 >= 1) and (IStelle-IPlusZiffernVorneZahl1 <= length(BIMinuend.Wert)) then IZiffer1 := Ord(BIMinuend.Wert[IStelle-IPlusZiffernVorneZahl1]) else IZiffer1 := 0; if (IStelle-IPlusZiffernVorneZahl2 >= 1) and (IStelle-IPlusZiffernVorneZahl2 <= length(BISubtrahend.Wert)) then IZiffer2 := Ord(BISubtrahend.Wert[IStelle-IPlusZiffernVorneZahl2]) else IZiffer2 := 0; if IZiffer1-IZiffer2-IUebertrag >= 0 then begin Wert[IStelle] := Char(IZiffer1-IZiffer2-IUebertrag); IUebertrag := 0; end else begin Wert[IStelle] := Char(IZiffer1+ISystem-IZiffer2-IUebertrag); IUebertrag := 1; end; end; BIMinuend.Free; BISubtrahend.Free; end; procedure TBigNum.Multipliziere(Multiplikand,Multiplikator: TBigNum); var BIEins,BIMultiplikand,BIMultiplikator: TBigNum; begin BIMultiplikand := TBigNum.Create; BIMultiplikand.CopyFrom(Multiplikand); BIMultiplikator := TBigNum.Create; BIMultiplikator.CopyFrom(Multiplikator); Wert := #0; komma := 1; BIEins := TBigNum.Create; BIEins.Wert := #1; BIEins.Komma := 1; while not (BIMultiplikator.Wert = #0) do begin while (BIMultiplikator.GroesserAls(BIEins) > -1) do begin Addiere(self,BIMultiplikand); BIMultiplikator.Subtrahiere(BIMultiplikator,BIEins); BIMultiplikator.EntferneNullen; end; while (BIMultiplikator.GroesserAls(BIEins) = -1) and (not (BIMultiplikator.Wert = #0)) do begin if BIMultiplikand.Komma > 1 then Dec(BIMultiplikand.Komma) else Insert(#0,BIMultiplikand.Wert,1); Inc(BIMultiplikator.Komma); if BIMultiplikator.Komma > length(BIMultiplikator.Wert) then Insert(#0,BIMultiplikator.Wert,length(BIMultiplikator.Wert)); BIMultiplikand.EntferneNullen; BIMultiplikator.EntferneNullen; end; end; BIEins.Free; BIMultiplikand.Free; BIMultiplikator.Free; end; procedure TBigNum.Dividiere(Dividend,Divisor: TBigNum); var BIEins,BIDividend,BIDivisor: TBigNum; begin BIDividend := TBigNum.Create; BIDividend.CopyFrom(Dividend); BIDivisor := TBigNum.Create; BIDivisor.CopyFrom(Divisor); Wert := #0; komma := 1; BIEins := TBigNum.Create; BIEins.Wert := #1; BIEins.Komma := 1; while (not (BIDividend.Wert = #0)) and (length(Wert)-Komma < IMaxLenNachKomma+3) do begin while (BIDividend.GroesserAls(BIDivisor) > -1) do begin BIDividend.Subtrahiere(BIDividend,BIDivisor); BIDividend.EntferneNullen; Addiere(self,BIEins); end; while (BIDividend.GroesserAls(BIDivisor) = -1) and not (BIDividend.Wert = #0) do begin if BIDivisor.Komma > 1 then Dec(BIDivisor.Komma) else Insert(#0,BIDivisor.Wert,1); BIDivisor.EntferneNullen; if BIEins.Komma > 1 then Dec(BIEins.Komma) else Insert(#0,BIEins.Wert,1); BIEins.EntferneNullen; end; end; BIEins.Free; BIDividend.Free; BIDivisor.Free; end; procedure TBigNum.ZieheWurzel(Basis,Exponent: TBigNum); var BIBasis, BIExponent, BIMinimum, BIMaximum, BITempMinimum, BITempMaximum, BIZwei, BIEins, BIWurzel, BIErgebnis: TBigNum; begin BIBasis := TBigNum.Create; BIExponent := TBigNum.Create; BIMinimum := TBigNum.Create; BIMaximum := TBigNum.Create; BITempMinimum := TBigNum.Create; BITempMaximum := TBigNum.Create; BIEins := TBigNum.Create; BIZwei := TBigNum.Create; BIWurzel := TBigNum.Create; BIErgebnis := TBigNum.Create; BIBasis.CopyFrom(Basis); BIExponent.CopyFrom(Exponent); BIMinimum.Wert := #0; BIMinimum.Komma := 1; BIMaximum.CopyFrom(Basis); BIEins.Wert := #1; BIEins.Komma := 1; if ISystem = 2 then begin BIZwei.Wert := #1#0; BIZwei.Komma := 2; end else begin BIZwei.Wert := #2; BIZwei.Komma := 1; end; BITempMaximum.CopyFrom(BIMaximum); BITempMaximum.Runde; BITempMinimum.CopyFrom(BIMinimum); BITempMinimum.Runde; while BITempMaximum.GroesserAls(BITempMinimum) <> 0 do begin BIWurzel.Addiere(BIMaximum,BIMinimum); BIWurzel.Dividiere(BIWurzel,BIZwei); BIExponent.CopyFrom(Exponent); BIErgebnis.CopyFrom(BIEins); while BIExponent.GroesserAls(BIEins) > -1 do begin BIExponent.Subtrahiere(BIExponent,BIEins); BIExponent.EntferneNullen; BIErgebnis.Multipliziere(BIErgebnis,BIWurzel); end; if BIErgebnis.GroesserAls(BIBasis) = 1 then begin BIMaximum.CopyFrom(BIWurzel); BITempMaximum.CopyFrom(BIMaximum); BITempMaximum.Runde; end else begin BIMinimum.CopyFrom(BIWurzel); BITempMinimum.CopyFrom(BIMinimum); BITempMinimum.Runde; end; end; CopyFrom(BITempMaximum); BIBasis.Free; BIExponent.Free; BIMinimum.Free; BIMaximum.Free; BITempMinimum.Free; BITempMaximum.Free; BIEins.Free; BIZwei.Free; BIWurzel.Free; BIErgebnis.Free; end; procedure TBigNum.Potenziere(Basis,Exponent: TBigNum); var BIEins,BIBasis,BIExponent: TBigNum; begin BIBasis := TBigNum.Create; BIBasis.CopyFrom(Basis); BIExponent := TBigNum.Create; BIExponent.CopyFrom(Exponent); Wert := #1; komma := 1; BIEins := TBigNum.Create; BIEins.Wert := #1; BIEins.Komma := 1; while (BIExponent.GroesserAls(BIEins) > -1) do begin Multipliziere(self,BIBasis); BIExponent.Subtrahiere(BIExponent,BIEins); BIExponent.EntferneNullen; end; BIEins.Free; BIBasis.Free; BIExponent.Free; end; procedure TBigNum.ToString(var SString: AnsiString); var IStelle: Integer; begin SetLength(SString,length(Wert)); for IStelle := 1 to length(Wert) do begin if Ord(Wert[IStelle]) < 10 then SString[IStelle] := Char(Ord(Wert[IStelle])+48) else if Ord(Wert[IStelle]) >= 10 then SString[IStelle] := Char(Ord(Wert[IStelle])+55) end; if Komma < length(Wert) then Insert(',',SString,Komma+1); if Negativ then Insert('-',SString,1); end; procedure TBigNum.ToRechnung(var SRechnung: AnsiString); var IStelle: Integer; begin // Entferne überflüssige Nullen if length(Wert) > 1 then begin if Komma > 1 then begin for IStelle := 1 to Komma-1 do begin if not (Wert[IStelle] = #0) then break; end; Delete(Wert,1,IStelle-1); Dec(Komma,IStelle-1); end; if length(Wert) > Komma then begin for IStelle := length(Wert) downto Komma+1 do begin if not (Wert[IStelle] = #0) then break; end; Delete(Wert,IStelle+1,length(Wert)-IStelle); end; end; // Setze Komma SRechnung := Wert; if Komma < length(Wert) then Insert(#100 { , },SRechnung,Komma+1); // Setze Vorzeichen if Negativ then Insert(#102 { | },SRechnung,1); end; procedure TBigNum.FromString(var SString: AnsiString); var IStelle: Integer; IUnterschied: Byte; begin if Pos(',',SString) = 0 then begin Komma := length(SString); SetLength(Wert,length(SString)); end else begin Komma := Pos(',',SString)-1; SetLength(Wert,length(SString)-1); end; IUnterschied := 0; for IStelle := 1 to length(SString) do begin if Ord(SString[IStelle]) in [Ord('0')..Ord('9')] then Wert[IStelle-IUnterschied] := Char(Ord(SString[IStelle])-48) else if Ord(SString[IStelle]) in [Ord('A')..Ord('Z')] then Wert[IStelle-IUnterschied] := Char(Ord(SString[IStelle])-55) else Inc(IUnterschied); end; end; procedure TBigNum.FromRechnung(var SRechnung: AnsiString; IAnfang,ILaenge: Integer); var IStelle: Integer; IUnterschied: Byte; STemp: AnsiString; begin STemp := Copy(SRechnung,IAnfang,ILaenge); if Pos(#100 { , },STemp) = 0 then begin Komma := length(STemp); SetLength(Wert,length(STemp)); end else begin Komma := Pos(#100 { , },STemp)-1; SetLength(Wert,length(STemp)-1); end; IUnterschied := 0; for IStelle := 1 to length(STemp) do begin if STemp[IStelle] in [#0..#35] then Wert[IStelle-IUnterschied] := STemp[IStelle] else Inc(IUnterschied); end; if IAnfang > 1 then begin if SRechnung[IAnfang-1] = #102 { | } then Negativ := True else if SRechnung[IAnfang-1] = #104 { - } then Negativ := True else Negativ := False; end else Negativ := False; if IAnfang > 2 then begin if SRechnung[IAnfang-2] = #104 { - } then Negativ := not Negativ; end; end; procedure TBigNum.CopyFrom(BIZahl: TBigNum); begin Wert := BIZahl.Wert; Negativ := BIZahl.Negativ; Komma := BIZahl.Komma; end; procedure TBigNum.Runde; var ILetzteZiffer: Byte; BIZahl: TBigNum; IStelle: Integer; begin if Komma+IMaxLenNachKomma < length(Wert) then begin ILetzteZiffer := Ord(Wert[Komma+IMaxLenNachKomma+1]); Delete(Wert,Komma+IMaxLenNachKomma+1,length(Wert)); if ILetzteZiffer >= ISystem/2 then begin BIZahl := TBigNum.Create; SetLength(BIZahl.Wert,IMaxLenNachKomma+1); BIZahl.Komma := 1; for IStelle := 1 to length(BIZahl.Wert)-1 do BIZahl.Wert[IStelle] := #0; BIZahl.Wert[length(BIZahl.Wert)] := #1; Addiere(self,BIZahl); BIZahl.Free; end; end; EntferneNullen; end; end.
{******************************************************************************} { lazbbcontrols : Controls with properties unavailable in lazarus controls } { Added to lazbbComponents palette } { bb - sdtp - march 2022 } { TColorPicker : Combine color combobox with color dialog } { Popup menu to copy/paste colour name can be localized } { TSignalMeter : Like progress bar but more responsive } { TLFPTimer : TFPtimer addition to the palette } {******************************************************************************} unit lazbbcontrols; {$mode objfpc}{$H+} interface uses Classes, SysUtils, ExtCtrls, StdCtrls, LResources, Forms, Controls, Graphics, Dialogs, Buttons, Menus, Clipbrd, PropEdits, Messages, LCLIntf, lclproc, fptimer; Const ColorArr: array of string = ( 'clBlack', 'clMaroon', 'clGreen', 'clOlive', 'clNavy', 'clPurple', 'clTeal', 'clGray', 'clSilver', 'clRed', 'clLime', 'clYellow', 'clBlue', 'clFuchsia', 'clAqua', 'clMedGray', 'clWhite', 'clMoneyGreen', 'clSkyBlue', 'clCream', 'clNone', 'clDefault'); { Other constants } fRBoxWidth : Integer = 13; // Width of rectangular checkbox fRBoxHeight : Integer = 13; // Height of rectangular checkbox DT_SINGLELINE = $20; DT_NOPREFIX = $800; DT_CENTER = 1; DT_TOP = 0; DT_LEFT = 0; DT_BOTTOM = 8; type TBidiMod = (Disabled); TSCrollDirection= (sdLeftToRight, sdRightToLeft); // TChceckboxX TState = (cbUnchecked,cbChecked,cbGrayed); TType = (cbCross,cbMark,cbBullet,cbDiamond,cbRect, cbBMP); // Added TMouseState = (msMouseUp,msMouseDown); // TColorPicker // System color combo plus color dialog // ColorDialog title cannot change, so no title property TColorPicker = Class(TWinControl) private FColor: Tcolor; FItemHeight: Integer; FItemWidth: Integer; FItems: TStrings; FOnchange: TNotifyEvent; FMnuCopyCaption: String; FMnuPasteCaption: String; ColorCombo: TComboBox; ColorBtn: TSpeedButton; ColorDlg: TColorDialog; PopupMnu: TPopupMenu; MnuCopy, MnuPaste: TMenuItem; procedure DoResize(Sender: TObject); procedure DoDrawItem (Control: TWinControl; Index: Integer; ARect: TRect; State: TOwnerDrawState); procedure DoSelect(Sender: TObject); procedure DoBtnClick(Sender: TObject); procedure DoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure SetItemHeight(ih: integer); procedure SetItemWidth(iw: integer); procedure SetColor(cl: TColor); procedure MnuCopyClick(Sender: TObject); procedure MnuPasteClick(Sender: TObject); procedure SetMnuCopyCaption (mcpy: string); procedure SetMnuPasteCaption (mpast: string); procedure MnuPopup(Sender: TObject); protected public constructor Create(AOwner: TComponent); override; published property ItemHeight : integer read FItemHeight write SetItemHeight; property ItemWidth : integer read FItemWidth write SetItemWidth; property Color: TColor read FColor write SetColor; property MnuCopyCaption: String read FMnuCopyCaption write SetMnuCopyCaption; property MnuPasteCaption: string read FMnuPasteCaption write SetMnuPasteCaption; property Enabled; property TabOrder; Property Tabstop; property Visible; property Align; property Font; property Onchange: TNotifyEvent read fOnchange write FOnchange; end; TCheckBoxX = class(TCustomControl) private { Private declarations } fChecked : Boolean; fCaption : String; fColor : TColor; fState : TState; fFont : TFont; fAllowGrayed : Boolean; fFocus : Boolean; fType : TType; fCheckColor : TColor; fMouseState : TMouseState; fAlignment : TAlignment; fTextTop : Integer; // top of text fTextLeft : Integer; // left of text fBoxTop : Integer; // top of box fBoxLeft : Integer; // left of box fOnStateChange : TNotifyEvent; fBitMap : TbitMap; Procedure fSetAlignment(A : TAlignment); Procedure fSetAllowGrayed(Bo : Boolean); Procedure fSetCaption(S : String); Procedure fSetType(T : TType); Procedure fSetCheckColor(C : TColor); Procedure fSetChecked(Bo : Boolean); Procedure fSetColor(C : TColor); Procedure fSetFont(cbFont : TFont); Procedure fSetState(cbState : TState); protected Procedure Paint; override; Procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; Procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; Procedure WMKillFocus(var Message : TWMKillFocus); Message WM_KILLFOCUS; // Yes, this removes the focus rect! Procedure WMSetFocus(var Message : TWMSetFocus); Message WM_SETFOCUS; // If you are using the TAB or Shift-Tab key Procedure KeyDown(var Key : Word; Shift : TShiftState); override; // Interception of KeyDown Procedure KeyUp(var Key : Word; Shift : TShiftState); override; // Interception of KeyUp public { Public declarations } // If you put Create and Destroy under protected, // Delphi complains about that. //Bitmap: TBitmap; Constructor Create(AOwner : TComponent); override; Destructor Destroy; override; published Property Action; Property Alignment : TAlignment read fAlignment write fSetAlignment; Property AllowGrayed : Boolean read fAllowGrayed write fSetAllowGrayed; Property Anchors; Property BiDiMode; Property Caption: String read fCaption write fSetCaption; Property CheckBoxType : TType read fType write fSetType; Property CheckColor : TColor read fCheckColor write fsetCheckColor; Property Checked : Boolean read fChecked write fSetChecked; Property Color : TColor read fColor write fSetColor; Property Constraints; //Property Ctrl3D; Property Cursor; Property DragCursor; Property DragKind; Property DragMode; Property Enabled; Property Font : TFont read fFont write fSetFont; //Property Height; Property HelpContext; Property Hint; Property Left; Property Name; //Property PartenBiDiMode; Property ParentColor; //Property ParentCtrl3D; Property ParentFont; Property ParentShowHint; //Property PopMenu; Property ShowHint; Property State : TState read fState write fSetState; Property TabOrder; Property TabStop; Property Tag; Property Top; Property Visible; //Property Width; { --- Events --- } Property OnClick; Property OnContextPopup; Property OnDragDrop; Property OnDragOver; Property OnEndDock; Property OnEndDrag; Property OnEnter; Property OnExit; Property OnKeyDown; Property OnKeyPress; Property OnKeyUp; Property OnMouseDown; Property OnMouseMove; Property OnMouseUp; Property OnStartDock; Property OnStartDrag; property OnStateChange: TNotifyEvent read FOnStateChange write FOnStateChange; property Bitmap: TBitMap read fBitMap write fBitmap; end; type TTitlePanel = class(TCustomPanel) private fBorderLine: TBorderStyle; fBorderColor: TColor; procedure setBorderLine(bl: TBorderStyle); procedure SetBorderColor(bc: TColor); protected Procedure Paint; override; public Constructor Create(AOwner: TComponent); override; published property Align; property Alignment; property Anchors; property BorderLine: TBorderStyle read fBorderLine write setBorderLine; property BorderColor: TColor read fBorderColor write setBorderColor; property Caption; property ChildSizing; property ClientHeight; property ClientWidth; property Color; property Constraints; property DockSite; property DoubleBuffered; property DragCursor; property DragKind; property DragMode; property Enabled; property Font; property FullRepaint; property ParentBackground; property ParentBidiMode; property ParentColor; property ParentDoubleBuffered; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property UseDockManager default True; property Visible; property Wordwrap; property OnClick; property OnContextPopup; property OnDockDrop; property OnDockOver; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnGetSiteInfo; property OnGetDockCaption; property OnMouseDown; property OnMouseEnter; property OnMouseLeave; property OnMouseMove; property OnMouseUp; property OnMouseWheel; property OnMouseWheelDown; property OnMouseWheelUp; property OnPaint; property OnResize; property OnStartDock; property OnStartDrag; property OnUnDock; end; type TSignalMeterOrientation = (gmHorizontal, gmVertical); TSignalMeter = class(TGraphicControl) private { Private declarations } fValue : Double; fColorFore : TColor; fColorBack : TColor; fSignalUnit : ShortString; fValueMax : Double; fValueMin : Double; fDigits : Byte; fIncrement : Double; fShowIncrements : Boolean; fGapTop : Word; fGapBottom : Word; fBarThickness : Word; fMarkerColor : TColor; fShowMarker : Boolean; fShowTopText : Boolean; fShowValueMin : Boolean; fShowValueMax : Boolean; fOrientation : TSignalMeterOrientation; //Variables used internallly TopTextHeight: Word; fLeftMeter : Word; DisplayValue : String; DrawStyle : Integer; TheRect : TRect; //End of variables used internallly procedure SetValue(val : Double); procedure SetColorBack(val : TColor); procedure SetColorFore(val : TColor); procedure SetSignalUnit(val : ShortString); procedure SetValueMin(val : Double); procedure SetValueMax(val : Double); procedure SetDigits(val : Byte); procedure SetTransparent(val : Boolean); Function GetTransparent : Boolean; procedure SetIncrement(val : Double); procedure SetShowIncrements(val : Boolean); procedure SetGapTop(val : Word); procedure SetGapBottom(val : Word); procedure SetLeftMeter (val : Word); procedure SetBarThickness(val : Word); procedure SetMarkerColor(val : TColor); procedure SetShowMarker(val : Boolean); procedure SetShowTopText(val : Boolean); procedure SetShowValueMin(val : Boolean); procedure SetShowValueMax(val : Boolean); procedure DrawTopText; procedure DrawMeterBar; procedure DrawIncrements; Function ValueToPixels(val : Double) : Integer; procedure DrawValueMax; procedure DrawValueMin; procedure DrawMarker; procedure SetOrientation(Value: TSignalMeterOrientation); protected { Protected declarations } procedure Paint;override; procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED; public { Public declarations } constructor Create(AOwner : Tcomponent);override; destructor Destroy ; override; published { Published declarations } property Align; property Caption; property Visible; property Value : Double read fValue write SetValue; property Color; property ColorFore : Tcolor read fColorFore write SetColorFore; property ColorBack : Tcolor read fColorBack write SetColorBack; property SignalUnit : ShortString read fSignalUnit write SetSignalUnit; property ValueMin : Double read fValueMin write SetValueMin; property ValueMax : Double read fValueMax write SetValueMax; property Digits : Byte read fDigits write SetDigits; property Increment : Double read fIncrement write SetIncrement; property ShowIncrements : Boolean read fShowIncrements write SetShowIncrements; property Transparent : Boolean read GetTransparent write SetTransparent; property GapTop : Word read fGapTop write SetGapTop; property GapBottom : Word read fGapBottom write SetGapBottom; property LeftMeter : Word read fLeftMeter write SetLeftMeter; property BarThickness : Word read fBarThickness write SetBarThickness; property MarkerColor : TColor read fMarkerColor write SetMarkerColor; property ShowMarker : Boolean read fShowMarker write SetShowMarker; property ShowTopText : Boolean read fShowTopText write SetShowTopText; property ShowValueMin : Boolean read fShowValueMin write SetShowValueMin; property ShowValueMax : Boolean read fShowValueMax write SetShowValueMax; property Orientation: TSignalMeterOrientation read FOrientation write SetOrientation default gmVertical; end; type TLFPTimer = Class(TFPCustomTimer) private protected public published Property Enabled; Property Interval; Property UseTimerThread; Property OnTimer; Property OnStartTimer; Property OnStopTimer; end; procedure Register; implementation procedure Register; begin {$I lazbbcontrols_icon.lrs} RegisterComponents('lazbbComponents',[TColorPicker]); RegisterComponents('lazbbComponents',[TCheckBoxX]); RegisterComponents('lazbbComponents',[TTitlePanel]); RegisterComponents('lazbbComponents',[TSignalMeter]); RegisterComponents('lazbbComponents',[TLFPTimer]); // Hide some properties from {RegisterPropertyEditor(TypeInfo(Boolean), TColorPicker, 'Autosize', THiddenPropertyEditor); // Need IDEIntf packet } end; // TColorPicker constructor TColorPicker.Create(AOwner: TComponent); var AStr:String; begin {$I lazbbcontrols_icon.lrs} inherited; Caption:= ''; Width:= 128; OnResize:= @DoResize; ColorCombo:= TcomboBox.Create(self); ColorBtn:= TSpeedButton.Create(self); ColorCombo.Parent:= self; ColorCombo.Style:= csOwnerDrawfixed; ColorCombo.Left:= 0; ColorCombo.Top:= 0; Height:= 23; ItemHeight:= 15; ItemWidth:= 0; ColorCombo.height:= height; ColorCombo.ItemHeight:= ItemHeight; ColorCombo.ItemWidth:= ItemWidth; ColorCombo.width:= 100; ColorCombo.BorderStyle:= bsNone; ColorCombo.visible:= true; ColorCombo.Items:= TstringList.Create; ParentFont:= false; ColorCombo.Font:= Font; for AStr in ColorArr do ColorCombo.Items.Add (AStr); ColorCombo.ItemIndex:= ColorCombo.Items.Count-1; FColor:= clDefault; ColorCombo.OnDrawItem:= @DoDrawItem; ColorCombo.OnSelect:= @DoSelect; ColorCombo.OnKeyDown:= @DoKeyDown; ColorBtn.Parent:= self; ColorBtn.left:= 105; ColorBtn.Top:= 0; ColorBtn.Height:= Height; ColorBtn.Width:= Height; ColorBtn.Margin:= -1; ColorBtn.Visible:= true; ColorBtn.LoadGlyphFromLazarusResource('tcolorbtn'); ColorBtn.OnClick:= @DoBtnClick; ColorDlg:= TColorDialog.Create(self); PopupMnu:= TPopupMenu.Create(ColorCombo); PopupMnu.OnPopup:= @MnuPopup; MnuCopy := TMenuItem.Create(PopupMnu); MnuCopy.Caption := MnuCopyCaption; MnuCopy.ShortCut:= TextToShortCut('CTRL+C'); MnuCopy.OnClick := @MnuCopyClick; PopupMnu.Items.Add(MnuCopy); MnuPaste := TMenuItem.Create(PopupMnu); Mnupaste.Caption := MnuPasteCaption; MnuPaste.ShortCut:= TextToShortCut('CTRL+V'); ; MnuPaste.OnClick := @MnuPasteClick; PopupMnu.Items.Add(MnuPaste); PopupMenu:= PopupMnu; MnuCopyCaption:= 'Copy'; MnuPasteCaption:= 'Paste'; FItems:= TStringList.create; FItems.Assign(ColorCombo.Items); end; procedure TColorPicker.MnuCopyClick(Sender: TObject); begin Clipboard.AsText:= ColorCombo.Items [ColorCombo.ItemIndex]; end; procedure TColorPicker.MnuPasteClick(Sender: TObject); var col: TColor; begin try col:= StringToColor(Clipboard.AsText); SetColor(col); except ShowMessage('Wrong color value'); end; end; procedure TColorPicker.MnuPopup(Sender: TObject); var col: TColor; begin try // avoid to paste a wrong color name col:= StringToColor(Clipboard.AsText); MnuPaste.Enabled:= True; except MnuPaste.Enabled:= False; end; end; procedure TColorPicker.SetMnuCopyCaption(mcpy: string); begin if FMnuCopyCaption <> mcpy then begin FMnuCopyCaption:= mcpy; MnuCopy.Caption := mcpy; end; end; procedure TColorPicker.SetMnuPasteCaption(mpast: string); begin if FMnupasteCaption <> mpast then begin FMnuPasteCaption:= mpast; MnuPaste.Caption := mpast; if Assigned(FOnChange) then FOnChange(Self); end; end; procedure TColorPicker.SetItemHeight(ih: integer); begin if FItemHeight <> ih then begin FItemHeight:= ih; ColorCombo.ItemHeight:= ih; Height:= ColorCombo.Height; ColorBtn.Height:= Height; end; end; procedure TColorPicker.SetItemWidth(iw: integer); begin if FItemWidth <> iw then begin FItemWidth:= iw; ColorCombo.ItemWidth:= iw; end; end; procedure TColorPicker.SetColor(cl: TColor); var i: integer; newcol: boolean; begin if FColor <> cl then begin //ColorCombo.ItemIndex:=-1; newcol:=true; FColor:= cl; For i:= 0 to ColorCombo.Items.Count-1 do if ColorToString(cl)= ColorCombo.Items[i] then begin ColorCombo.ItemIndex:=i; newcol:= false; end; if newcol then begin ColorCombo.AddItem(ColorToString(cl), nil); ColorCombo.ItemIndex:= ColorCombo.Items.Count-1; ; end; end; end; procedure TColorPicker.DoResize(Sender: Tobject); begin ColorCombo.Width:= width-28; ColorBtn.Top:= 0; ColorBtn.left:= width-Height; ColorBtn.Height:= Height; ColorBtn.Width:= Height; ColorCombo.Height:= height; height:= ColorCombo.Height; end; procedure TColorPicker.DoSelect(Sender: TObject); begin FColor:= StringToColor(ColorCombo.Items[ColorCombo.ItemIndex]); if Assigned(FOnChange) then FOnChange(Self); end; // Owner draw paint combho with color procedure TColorPicker.DoDrawItem(Control: TWinControl; Index: Integer; ARect: TRect; State: TOwnerDrawState); var ltRect: TRect; txtTop: integer; ColTop: Integer; flRect: TRect; begin ColorCombo.Canvas.Font:= font; ColorCombo.Canvas.FillRect(ARect); //first paint normal background txtTop:= (ARect.Bottom-ARect.Top-ColorCombo.Canvas.TextHeight(ColorCombo.Items[Index])) div 2; // To vertically center text ColTop:= (ARect.Bottom-ARect.Top-13) div 2; // Vertically center color square ColorCombo.Canvas.TextRect(ARect, 22, ARect.Top+txtTop, ColorCombo.Items[Index]); //paint item text ltRect.Left := ARect.Left+2; //rectangle for color ltRect.Right := ltRect.Left+13; ltRect.Top := ARect.Top+ColTop; ltRect.Bottom := ltRect.Top+13 ; flrect.Left:= ltRect.Left+1; //Reduce 1 pixel flRect.Right:= ltRect.Right-1; //to see the lines around the colour flRect.Top:= ltRect.Top+1; flRect.Bottom:= ltRect.Bottom-1; // ColorCombo.Canvas.Rectangle(ltRect); ColorCombo.Canvas.Brush.Color := StringToColor(ColorCombo.Items[Index]); ColorCombo.Canvas.FillRect(flRect); end; procedure TColorPicker.DoBtnClick(Sender: TObject); begin ColorDlg.Color:= FColor; if ColorDlg.Execute then SetColor(ColorDlg.Color); end; // implement Ctrl-C and Ctrl-V to copy and paste procedure TColorPicker.DoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (ssCtrl in Shift) and (Key = Ord('C')) then begin MnuCopyClick(Sender); key:= 0; end; if (ssCtrl in Shift) and (Key = Ord('V')) then begin MnuPasteClick(Sender); key:= 0; end; end; // TCheckbox color Destructor TCheckBoxX.Destroy; Begin inherited Destroy; fBitMap.Free; End; Constructor TCheckBoxX.Create(AOwner : TComponent); Begin inherited Create(AOwner); Parent:= TWinControl(aOwner); Height := 17; Width := 97; fChecked := False; fColor := cldefault; fState := cbUnChecked; fFont := inherited Font; fAllowGrayed := False; fFocus := False; fMouseState := msMouseUp; fAlignment := taRightJustify; TabStop := True; // Sorry fBitMap:= TBitmap.Create; fCaption:= 'ChecBoxX'; End; Procedure TCheckBoxX.fSetAlignment(A : TAlignment); Begin If A <> fAlignment then Begin fAlignment := A; Invalidate; End; End; Procedure TCheckBoxX.fSetAllowGrayed(Bo : Boolean); Begin If fAllowGrayed <> Bo then Begin fAllowGrayed := Bo; If not fAllowGrayed then If fState = cbGrayed then Begin If fChecked then fState := cbChecked else fState := cbUnChecked; End; Invalidate; End; End; Procedure TCheckBoxX.fSetCaption(S : String); Begin If fCaption <> S then Begin fCaption := S; Invalidate; End; End; Procedure TCheckBoxX.fSetType(T : TType); Begin If fType <> T then Begin fType := T; Invalidate; End; End; Procedure TCheckBoxX.fSetCheckColor(C : TColor); Begin If fCheckColor <> C then Begin fCheckColor := C; Invalidate; End; End; Procedure TCheckBoxX.fSetChecked(Bo : Boolean); Begin If fChecked <> Bo then Begin fChecked := Bo; If fState <> cbGrayed then Begin If fChecked then fState := cbChecked else fState := cbUnChecked; End; Invalidate; End; End; Procedure TCheckBoxX.fSetColor(C : TColor); Begin If fColor <> C then Begin fColor := C; Invalidate; End; End; Procedure TCheckBoxX.fSetFont(cbFont : TFont); Var FntChanged : Boolean; Begin FntChanged := False; If fFont.Style <> cbFont.Style then Begin fFont.Style := cbFont.Style; FntChanged := True; End; If fFont.CharSet <> cbFont.Charset then Begin fFont.Charset := cbFont.Charset; FntChanged := True; End; If fFont.Size <> cbFont.Size then Begin fFont.Size := cbFont.Size; FntChanged := True; End; If fFont.Name <> cbFont.Name then Begin fFont.Name := cbFont.Name; FntChanged := True; End; If fFont.Color <> cbFont.Color then Begin fFont.Color := cbFont.Color; FntChanged := True; End; If FntChanged then Invalidate; End; Procedure TCheckBoxX.fSetState(cbState : TState); Begin If fState <> cbState then Begin fState := cbState; If (fState = cbChecked) then fChecked := True; If (fState = cbGrayed) then fAllowGrayed := True; If fState = cbUnChecked then fChecked := False; Invalidate; End; End; Procedure TCheckBoxX.Paint; Var I : Integer; fTextWidth,fTextHeight : Integer; Begin Canvas.Font.Size := Font.Size; Canvas.Font.Style := Font.Style; Canvas.Font.Color := Font.Color; Canvas.Font.Charset := Font.CharSet; fTextWidth := Canvas.TextWidth(Caption); fTextHeight := Canvas.TextHeight('Q'); If fAlignment = taRightJustify then begin fBoxTop := (Height - fRBoxHeight) div 2; fBoxLeft := 0; fTextTop := (Height - fTextHeight) div 2; fTextLeft := fBoxLeft + fRBoxWidth + 4; end else begin fBoxTop := (Height - fRBoxHeight) div 2; fBoxLeft := Width - fRBoxWidth; fTextTop := (Height - fTextHeight) div 2; fTextLeft := 1; end; // Selected colors Canvas.Pen.Color := fColor; Canvas.Brush.Style:= bsClear; If (fState = cbGrayed) or (enabled= false) then Begin fAllowGrayed := True; Canvas.Font.color:= clGrayText; Canvas.Pen.Color:= clGrayText; End; // Write caption Canvas.TextOut(fTextLeft,fTextTop,Caption); // Now prepare the checkbox outline Canvas.Brush.Style:= bsSolid; If (fState = cbChecked) then Canvas.Brush.Color := clWindow; If (fState = cbUnChecked) then Canvas.Brush.Color := clWindow; // Make the box clBtnFace when the mouse is down // just like the "standard" CheckBox If fMouseState = msMouseDown then Canvas.Brush.Color := clBtnFace; // Now fill the box brush with default blank colour Canvas.FillRect(Rect(fBoxLeft + 1, fBoxTop + 1, fBoxLeft + fRBoxWidth - 1, fBoxTop + fRBoxHeight - 1)); // Draw the rectangular checkbox to be the same as Lazarus checkbox Canvas.rectangle(fBoxLeft, fBoxTop, fBoxLeft + fRBoxWidth,fBoxTop + fRBoxHeight ); If fChecked then Begin Canvas.Pen.Color := fCheckColor; //clBlack; Canvas.Brush.Color := fCheckColor; //clBlack; // Paint the rectangle If fType = cbRect then Begin Canvas.FillRect(Rect(fBoxLeft + 1,fBoxTop + 1, fBoxLeft + fRBoxWidth - 1,fBoxTop + fRBoxHeight - 1)); End; // Paint the bullet If fType = cbBullet then Begin Canvas.Ellipse(fBoxLeft + 3,fBoxTop + 3, fBoxLeft + fRBoxWidth - 3,fBoxTop + fRBoxHeight - 3); End; // Paint the cross If fType = cbCross then Begin {Right-top to left-bottom} Canvas.MoveTo(fBoxLeft + fRBoxWidth - 5,fBoxTop + 3); Canvas.LineTo(fBoxLeft + 2,fBoxTop + fRBoxHeight - 4); Canvas.MoveTo(fBoxLeft + fRBoxWidth - 4,fBoxTop + 3); Canvas.LineTo(fBoxLeft + 2,fBoxTop + fRBoxHeight - 3); Canvas.MoveTo(fBoxLeft + fRBoxWidth - 4,fBoxTop + 4); Canvas.LineTo(fBoxLeft + 3,fBoxTop + fRBoxHeight - 3); {Left-top to right-bottom} Canvas.MoveTo(fBoxLeft + 3,fBoxTop + 4); Canvas.LineTo(fBoxLeft + fRBoxWidth - 4, fBoxTop + fRBoxHeight - 3); Canvas.MoveTo(fBoxLeft + 3,fBoxTop + 3); Canvas.LineTo(fBoxLeft + fRBoxWidth - 3, fBoxTop + fRBoxHeight - 3); //mid Canvas.MoveTo(fBoxLeft + 4,fBoxTop + 3); Canvas.LineTo(fBoxLeft + fRBoxWidth - 3, fBoxTop + fRBoxHeight - 4); End; // Paint the mark If fType = cbMark then For I := 0 to 2 do Begin {Left-mid to left-bottom} Canvas.MoveTo(fBoxLeft + 3,fBoxTop + 5 + I); Canvas.LineTo(fBoxLeft + 6,fBoxTop + 8 + I); {Left-bottom to right-top} Canvas.MoveTo(fBoxLeft + 6,fBoxTop + 6 + I); Canvas.LineTo(fBoxLeft + 10,fBoxTop + 2 + I); End; // Paint the diamond If fType = cbDiamond then Begin Canvas.Pixels[fBoxLeft + 06,fBoxTop + 03] := clBlack; Canvas.Pixels[fBoxLeft + 06,fBoxTop + 09] := clBlack; Canvas.MoveTo(fBoxLeft + 05,fBoxTop + 04); Canvas.LineTo(fBoxLeft + 08,fBoxTop + 04); Canvas.MoveTo(fBoxLeft + 05,fBoxTop + 08); Canvas.LineTo(fBoxLeft + 08,fBoxTop + 08); Canvas.MoveTo(fBoxLeft + 04,fBoxTop + 05); Canvas.LineTo(fBoxLeft + 09,fBoxTop + 05); Canvas.MoveTo(fBoxLeft + 04,fBoxTop + 07); Canvas.LineTo(fBoxLeft + 09,fBoxTop + 07); Canvas.MoveTo(fBoxLeft + 03,fBoxTop + 06); Canvas.LineTo(fBoxLeft + 10,fBoxTop + 06); // middle line End; // Paint the Bmp if fType = cbBmp then begin if assigned(Bitmap)then begin Canvas.Draw(fBoxLeft + 1,fBoxTop + 1, Bitmap); end; end; End; End; procedure TCheckBoxX.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); Begin // The MouseDown procedure is only called when the mouse // goes down WITHIN the control, so we don't have to check // the X and Y values. inherited MouseDown(Button, Shift, X, Y); fMouseState := msMouseDown; If fState <> cbGrayed then Begin SetFocus; // Set focus to this component // Windows sends a WM_KILLFOCUS message to all the // other components. fFocus := True; Invalidate; End; End; procedure TCheckBoxX.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); Begin // The MouseUp procedure is only called when the mouse // goes up WITHIN the control, so we don't have to check // the X and Y values. inherited MouseUp(Button, Shift, X, Y); If fState <> cbGrayed then begin fSetChecked(not fChecked); // Change the check if Assigned(FOnStateChange) then FOnStateChange(Self); end; fMouseState := msMouseUp; End; Procedure TCheckBoxX.KeyDown(var Key : Word; Shift : TShiftState); Begin If fFocus then If Shift = [] then If Key = 0032 then Begin fMouseState := msMouseDown; If fState <> cbGrayed then Begin SetFocus; // Set focus to this component // Windows sends a WM_KILLFOCUS message to all the // other components. fFocus := True; Invalidate; End; End; Inherited KeyDown(Key,Shift); End; Procedure TCheckBoxX.KeyUp(var Key : Word; Shift : TShiftState); Begin If fFocus then If Shift = [] then If Key = 0032 then Begin If fState <> cbGrayed then begin fSetChecked(not fChecked); // Change the check if Assigned(FOnStateChange) then FOnStateChange(Self); end; fMouseState := msMouseUp; End; Inherited KeyUp(Key,Shift); End; Procedure TCheckBoxX.WMKillFocus(var Message : TWMKillFocus); Begin fFocus := False; // Remove the focus rectangle of all the components, // which doesn't have the focus. Invalidate; End; Procedure TCheckBoxX.WMSetFocus(var Message : TWMSetFocus); begin fFocus := True; Invalidate; End; constructor TTitlePanel.Create(AOwner: TComponent); begin inherited Create(AOwner); Parent:= TWinControl(aOwner); fBorderLine:= bsSingle; Alignment:= taLeftJustify; FBorderColor:= clActiveBorder; end; procedure TTitlePanel.setBorderLine(bl: TBorderStyle); begin if bl <> fBorderLine then begin fBorderLine:= bl; Invalidate; end; end; procedure TTitlePanel.SetBorderColor(bc: TColor); begin if bc <> fBorderColor then begin fBorderColor:= bc; Invalidate; end; end; Procedure TTitlePanel.Paint; var style: TTextStyle; txth, txtw: integer; lmrg: integer; begin Canvas.Region.ClipRect; Canvas.Font:= Font; Style.SystemFont:= false; Canvas.Font.Style:= Font.Style; txth:= Canvas.TextHeight(caption); txtw:= Canvas.TextWidth(caption); lmrg:= 15; Case Alignment of taCenter: lmrg:= (width-txtw) div 2; taLeftJustify: lmrg:= 15; taRightJustify: lmrg:= width-txtw-15; end; // Remove background color on the full panel // replace with the parent/owner color Canvas.Brush.Color:= TWinControl(Parent).Color; Canvas.FillRect(Rect(0, 0, width, height)); // Fill color on the used surface Canvas.Brush.Color:= Color; Canvas.FillRect(Rect(0, 8, width, height)); Style.Opaque := True; //Top border with place for caption if BorderLine=bsSingle then begin Canvas.Pen.Color:= fBorderColor; Canvas.Line(0,8,lmrg,8); Canvas.Line(lmrg+txtw,8,width,8); Canvas.Line(width-1,8,width-1,height); Canvas.Line(0, height-1, width-1,height-1); Canvas.Line(0,8,0,height); end; Canvas.Brush.Style:= bsClear; Canvas.TextRect(Rect(lmrg, 0, txtw+lmrg, txth), lmrg ,0,caption, Style); end; constructor TSignalMeter.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := ControlStyle + [csOpaque, csReplicatable, csSetCaption]; width := 100; height := 200; fColorFore := clRed; fColorBack := clBtnFace; fMarkerColor := clBlue; fValueMin := 0; fValueMax := 100; fLeftMeter := 10; fIncrement := 10; fShowIncrements := true; fShowMarker := true; fValue := 0; fGapTop := 10; fGapBottom := 10; fBarThickness := 5; fSignalUnit := 'Units'; fOrientation := gmVertical; end; destructor TSignalMeter.Destroy; begin inherited Destroy; end; procedure TSignalMeter.SetOrientation(Value: TSignalMeterOrientation); begin if FOrientation <> Value then begin FOrientation := Value; Invalidate; end; end; procedure TSignalMeter.CMTextChanged(var Message: TMessage); begin Invalidate; end; procedure TSignalMeter.SetValue(val : Double); begin if (val <> fValue) and (val >= fValueMin) and (val <= fValueMax) then begin fValue := val; Invalidate; end; end; procedure TSignalMeter.SetColorFore(val : TColor); begin if val <> fColorFore then begin fColorFore := val; Invalidate; end; end; procedure TSignalMeter.SetColorBack(val : TColor); begin if val <> fColorBack then begin fColorBack := val; Invalidate; end; end; procedure TSignalMeter.SetSignalUnit(val : ShortString); begin if val <> fSignalUnit then begin fSignalUnit := val; Invalidate; end; end; procedure TSignalMeter.SetValueMin(val : Double); begin if (val <> fValueMin) and (val <= fValue) then begin fValueMin := val; Invalidate; end; end; procedure TSignalMeter.SetValueMax(val : Double); begin if (val <> fValueMax) and (val >= fValue) then begin fValueMax := val; Invalidate; end; end; procedure TSignalMeter.SetDigits(val : Byte); begin if (val <> fDigits) then begin fDigits := val; //Invalidate; end; end; procedure TSignalMeter.SetIncrement(val : Double); begin if (val <> fIncrement) and (val > 0) then begin fIncrement := val; Invalidate; end; end; procedure TSignalMeter.SetShowIncrements(val : Boolean); begin if (val <> fShowIncrements) then begin fShowIncrements := val; Invalidate; end; end; function TSignalMeter.GetTransparent : Boolean; begin Result := not (csOpaque in ControlStyle); end; procedure TSignalMeter.SetTransparent(Val : Boolean); begin if Val <> Transparent then begin if Val then ControlStyle := ControlStyle - [csOpaque] else ControlStyle := ControlStyle + [csOpaque]; Invalidate; end; end; procedure TSignalMeter.SetGapTop(val : Word); begin if (val <> fGapTop) then begin fGapTop := val; Invalidate; end; end; procedure TSignalMeter.SetGapBottom(val : Word); begin if (val <> fGapBottom) then begin fGapBottom := val; Invalidate; end; end; procedure TSignalMeter.SetLeftMeter(val : Word); begin if (val <> fLeftMeter) then begin fLeftMeter := val; Invalidate; end; end; procedure TSignalMeter.SetBarThickness(val : Word); begin if (val <> fBarThickness) and (val > 0) then begin fBarThickness := val; Invalidate; end; end; procedure TSignalMeter.SetMarkerColor(val : TColor); begin if (val <> fMarkerColor) then begin fMarkerColor := val; Invalidate; end; end; procedure TSignalMeter.SetShowMarker(val : Boolean); begin if (val <> fShowMarker) then begin fShowMarker := val; Invalidate; end; end; procedure TSignalMeter.SetShowTopText(val : Boolean); begin if (val <> fShowTopText) then begin fShowTopText := val; Invalidate; end ; end; procedure TSignalMeter.SetShowValueMin(val : Boolean); begin if (val <> fShowValueMin) then begin fShowValueMin := val; Invalidate; end; end; procedure TSignalMeter.SetShowValueMax(val : Boolean); begin if (val <> fShowValueMax) then begin fShowValueMax := val; Invalidate; end; end; procedure TSignalMeter.DrawIncrements; var i : Double; PosPixels : Word; begin if fShowIncrements then begin With Canvas do begin i := fValueMin; While i <= fValueMax do begin PosPixels := ValueToPixels(i); pen.color := clGray; MoveTo(LeftMeter + BarThickness + 3, PosPixels-1); LineTo(LeftMeter + BarThickness + 7, PosPixels-1); pen.color := clWhite; MoveTo(LeftMeter + BarThickness + 3, PosPixels); LineTo(LeftMeter + BarThickness + 7, PosPixels); i := i+fIncrement; end; end; end; end; procedure TSignalMeter.DrawMarker; begin If fShowMarker then begin With Canvas do begin pen.color := clWhite; Brush.Style := bsClear; MoveTo(LeftMeter - 2, ValueToPixels(fValue)); LineTo(LeftMeter - 6, ValueToPixels(fValue)-4); LineTo(LeftMeter - 6, ValueToPixels(fValue)+4); pen.color := clGray; LineTo(LeftMeter - 2, ValueToPixels(fValue)); pen.color := fMarkerColor; Brush.color := fMarkerColor; Brush.Style := bsSolid; Polygon([Point(LeftMeter - 3, ValueToPixels(fValue)), Point(LeftMeter - 5, ValueToPixels(fValue)-2), Point(LeftMeter - 5, ValueToPixels(fValue)+2), Point(LeftMeter - 3, ValueToPixels(fValue))]); end; end; end; procedure TSignalMeter.DrawTopText; begin If fShowTopText then begin With Canvas do begin DisplayValue := Caption; Brush.Style := bsClear; TheRect := ClientRect; DrawStyle := DT_SINGLELINE + DT_NOPREFIX + DT_CENTER + DT_TOP; Font.Style := [fsBold]; TopTextHeight := DrawText(Handle, PChar(DisplayValue), Length(DisplayValue), TheRect, DrawStyle); Font.Style := []; TheRect.Top := TopTextHeight; DisplayValue := FloatToStrF(Value, ffFixed, 8, fDigits) + ' ' + fSignalUnit; TopTextHeight := TopTextHeight + DrawText(Handle, PChar(DisplayValue), Length(DisplayValue), TheRect, DrawStyle); TopTextHeight := TopTextHeight + fGapTop; end; end else begin DisplayValue := ''; TopTextHeight:= GapTop; end; end; procedure TSignalMeter.DrawValueMin; begin If fShowValueMin then begin With Canvas do begin TheRect := ClientRect; TheRect.Left := LeftMeter + BarThickness + 10; TheRect.Top := TopTextHeight; TheRect.Bottom := Height - fGapBottom + 6; Brush.Style := bsClear; DrawStyle := DT_SINGLELINE + DT_NOPREFIX + DT_LEFT + DT_BOTTOM; DisplayValue := FloatToStrF(ValueMin, ffFixed, 8, fDigits) + ' ' + fSignalUnit; DrawText(Handle, PChar(DisplayValue), Length(DisplayValue), TheRect, DrawStyle); end; end; end; procedure TSignalMeter.DrawValueMax; begin If fShowValueMax then begin With Canvas do begin TheRect := ClientRect; TheRect.Left := LeftMeter + BarThickness + 10; TheRect.Top := TopTextHeight - 6; Brush.Style := bsClear; DrawStyle := DT_SINGLELINE + DT_NOPREFIX + DT_LEFT + DT_TOP; DisplayValue := FloatToStrF(ValueMax, ffFixed, 8, fDigits) + ' ' + fSignalUnit; DrawText(Handle, PChar(DisplayValue), Length(DisplayValue), TheRect, DrawStyle); end; end; end; procedure TSignalMeter.DrawMeterBar; begin Case fOrientation of gmHorizontal: With Canvas do begin pen.Color := fColorBack; Brush.Color := fColorBack; Brush.Style := bsSolid; //Rectangle(LeftMeter, ValueToPixels(fValueMax), LeftMeter + fBarThickness, ValueToPixels(fValueMin)); Rectangle (GapBottom, LeftMeter, ValueToPixels(fValueMax), LeftMeter+ fBarThickness); pen.Color := fColorFore; Brush.Color := fColorFore; Brush.Style := bsSolid; //Rectangle(LeftMeter + 1, ValueToPixels(fValue), LeftMeter + fBarThickness, ValueToPixels(fValueMin)); Rectangle (GapBottom , LeftMeter, ValueToPixels(fValue), LeftMeter+ fBarThickness); pen.color := clWhite; Brush.Style := bsClear; //MoveTo(LeftMeter + fBarThickness-1, ValueToPixels(fValueMax)); MoveTo(GapBottom , LeftMeter+ fBarThickness); //LineTo(LeftMeter, ValueToPixels(fValueMax)); LineTo(GapBottom, LeftMeter); //LineTo(LeftMeter, ValueToPixels(fValueMin)-1); LineTo(ValueToPixels(fValueMax),LeftMeter); pen.color := clGray; //LineTo(LeftMeter + fBarThickness, ValueToPixels(fValueMin)-1); LineTo(ValueToPixels(fValueMax), LeftMeter+ fBarThickness); //LineTo(LeftMeter + fBarThickness, ValueToPixels(fValueMax)); LineTo(GapBottom, LeftMeter + fBarThickness ); If (fValue > fValueMin) and (fValue < fValueMax) then begin pen.color := clWhite; //MoveTo(LeftMeter+1, ValueToPixels(fValue)); MoveTo(ValueToPixels(fValue), LeftMeter+1); //LineTo(LeftMeter + fBarThickness, ValueToPixels(fValue)); LineTo(ValueToPixels(fValue), LeftMeter+fBarThickness-1); pen.color := clGray; //MoveTo(LeftMeter+1, ValueToPixels(fValue)-1); MoveTo(ValueToPixels(fValue)+1, LeftMeter+1); //LineTo(LeftMeter + fBarThickness, ValueToPixels(fValue)-1); LineTo(ValueToPixels(fValue)+1, LeftMeter+fBarThickness-1); end; end; gmVertical: With Canvas do begin pen.Color := fColorBack; Brush.Color := fColorBack; Brush.Style := bsSolid; Rectangle(LeftMeter, ValueToPixels(fValueMax), LeftMeter + fBarThickness, ValueToPixels(fValueMin)); pen.Color := fColorFore; Brush.Color := fColorFore; Brush.Style := bsSolid; Rectangle(LeftMeter + 1, ValueToPixels(fValue), LeftMeter + fBarThickness, ValueToPixels(fValueMin)); pen.color := clWhite; Brush.Style := bsClear; MoveTo(LeftMeter + fBarThickness-1, ValueToPixels(fValueMax)); LineTo(LeftMeter, ValueToPixels(fValueMax)); LineTo(LeftMeter, ValueToPixels(fValueMin)-1); pen.color := clGray; LineTo(LeftMeter + fBarThickness, ValueToPixels(fValueMin)-1); LineTo(LeftMeter + fBarThickness, ValueToPixels(fValueMax)); If (fValue > fValueMin) and (fValue < fValueMax) then begin pen.color := clWhite; MoveTo(LeftMeter+1, ValueToPixels(fValue)); LineTo(LeftMeter + fBarThickness, ValueToPixels(fValue)); pen.color := clGray; MoveTo(LeftMeter+1, ValueToPixels(fValue)-1); LineTo(LeftMeter + fBarThickness, ValueToPixels(fValue)-1); end; end; end; end; Function TSignalMeter.ValueToPixels(val : Double) : Integer; var factor : Double; begin Result := 0; Case fOrientation of gmHorizontal: If fValueMax > fValueMin then begin Factor := (Width-fGapBottom-fGapTop)/(fValueMax-fValueMin); Result := Round(Factor*val+fGapBottom); end; gmVertical: If fValueMax > fValueMin then begin Factor := (Height-fGapBottom-TopTextHeight)/(fValueMin-fValueMax); Result := Round(Factor*val -Factor*fValueMax+TopTextHeight); end; end; end; procedure TSignalMeter.Paint; begin //if width < fLeftMeter+ fBarThickness + fLeftMeter then width := fLeftMeter+ fBarThickness + fLeftMeter; With Canvas do begin if not Transparent then begin Brush.Color := Self.Color; Brush.Style := bsSolid; FillRect(ClientRect); end; Brush.Style := bsClear; DrawTopText; DrawValueMin; DrawValueMax; DrawMeterBar; DrawMarker; DrawIncrements; end; end; end.
unit ColorBtn; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons; type TColorBtn = class(TButton) private IsFocused: boolean; FCanvas: TCanvas; F3DFrame: boolean; FButtonColor: TColor; procedure Set3DFrame(Value: boolean); procedure SetButtonColor(Value: TColor); procedure CNDrawItem(var Message: TWMDrawItem); message CN_DRAWITEM; procedure WMLButtonDblClk(var Message: TWMLButtonDblClk); message WM_LBUTTONDBLCLK; procedure DrawButtonText(const Caption: string; TRC: TRect; State: TButtonState; BiDiFlags: Longint); procedure CalcuateTextPosition(const Caption: string; var TRC: TRect; BiDiFlags: Longint); protected procedure CreateParams(var Params: TCreateParams); override; procedure SetButtonStyle(ADefault: boolean); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property ButtonColor: TColor read FButtonColor write SetButtonColor default clBtnFace; property Frame3D: boolean read F3DFrame write Set3DFrame default False; end; procedure Register; implementation { TColorBtn } constructor TColorBtn.Create(AOwner: TComponent); begin Inherited Create(AOwner); FCanvas:= TCanvas.Create; FButtonColor:= clBtnFace; F3DFrame:= False; end; destructor TColorBtn.Destroy; begin FCanvas.Free; Inherited Destroy; end; procedure TColorBtn.CreateParams(var Params: TCreateParams); begin Inherited CreateParams(Params); with Params do Style:= Style or BS_OWNERDRAW; end; procedure TColorBtn.Set3DFrame(Value: boolean); begin if F3DFrame <> Value then F3DFrame:= Value; end; procedure TColorBtn.SetButtonColor(Value: TColor); begin if FButtonColor <> Value then begin FButtonColor:= Value; Invalidate; end; end; procedure TColorBtn.WMLButtonDblClk(var Message: TWMLButtonDblClk); begin Perform(WM_LBUTTONDOWN, Message.Keys, Longint(Message.Pos)); end; procedure TColorBtn.SetButtonStyle(ADefault: Boolean); begin if IsFocused <> ADefault then IsFocused:= ADefault; end; procedure TColorBtn.CNDrawItem(var Message: TWMDrawItem); var RC: TRect; Flags: Longint; State: TButtonState; IsDown, IsDefault: Boolean; DrawItemStruct: TDrawItemStruct; begin DrawItemStruct:= Message.DrawItemStruct^; FCanvas.Handle:= DrawItemStruct.HDC; RC:= ClientRect; with DrawItemStruct do begin IsDown:= ItemState and ODS_SELECTED <> 0; IsDefault:= ItemState and ODS_FOCUS <> 0; if not Enabled then State:= bsDisabled else if IsDown then State:= bsDown else State:= bsUp; end; Flags:= DFCS_BUTTONPUSH or DFCS_ADJUSTRECT; if IsDown then Flags:= Flags or DFCS_PUSHED; if DrawItemStruct.ItemState and ODS_DISABLED <> 0 then Flags:= Flags or DFCS_INACTIVE; if IsFocused or IsDefault then begin FCanvas.Pen.Color:= clWindowFrame; FCanvas.Pen.Width:= 1; FCanvas.Brush.Style:= bsClear; FCanvas.Rectangle(RC.Left, RC.Top, RC.Right, RC.Bottom); InflateRect(RC, -1, -1); end; if IsDown then begin FCanvas.Pen.Color:= clBtnShadow; FCanvas.Pen.Width:= 1; FCanvas.Rectangle(RC.Left, RC.Top, RC.Right, RC.Bottom); InflateRect(RC, -1, -1); if F3DFrame then begin FCanvas.Pen.Color:= FButtonColor; FCanvas.Pen.Width:= 1; DrawFrameControl(DrawItemStruct.HDC, RC, DFC_BUTTON, Flags); end; end else DrawFrameControl(DrawItemStruct.HDC, RC, DFC_BUTTON, Flags); FCanvas.Brush.Color:= FButtonColor; FCanvas.FillRect(RC); InflateRect(RC, 1, 1); if IsFocused then begin RC:= ClientRect; InflateRect(RC, -1, -1); end; if IsDown then OffsetRect(RC, 1, 1); FCanvas.Font:= Self.Font; DrawButtonText(Caption, RC, State, 0); if IsFocused and IsDefault then begin RC:= ClientRect; InflateRect(RC, -4, -4); FCanvas.Pen.Color:= clWindowFrame; Windows.DrawFocusRect(FCanvas.Handle, RC); end; FCanvas.Handle:= 0; end; procedure TColorBtn.CalcuateTextPosition(const Caption: string; var TRC: TRect; BiDiFlags: Integer); var TB: TRect; TS, TP: TPoint; begin with FCanvas do begin TB:= Rect(0, 0, TRC.Right + TRC.Left, TRC.Top + TRC.Bottom); DrawText(Handle, PChar(Caption), Length(Caption), TB, DT_CALCRECT or BiDiFlags); TS := Point(TB.Right - TB.Left, TB.Bottom - TB.Top); TP.X := ((TRC.Right - TRC.Left) - TS.X + 1) div 2; TP.Y := ((TRC.Bottom - TRC.Top) - TS.Y + 1) div 2; OffsetRect(TB, TP.X + TRC.Left, TP.Y + TRC.Top); TRC:= TB; end; end; procedure TColorBtn.DrawButtonText(const Caption: string; TRC: TRect; State: TButtonState; BiDiFlags: Integer); begin with FCanvas do begin CalcuateTextPosition(Caption, TRC, BiDiFlags); Brush.Style:= bsClear; if State = bsDisabled then begin OffsetRect(TRC, 1, 1); Font.Color:= clBtnHighlight; DrawText(Handle, PChar(Caption), Length(Caption), TRC, DT_CENTER or DT_VCENTER or BiDiFlags); OffsetRect(TRC, -1, -1); Font.Color:= clBtnShadow; DrawText(Handle, PChar(Caption), Length(Caption), TRC, DT_CENTER or DT_VCENTER or BiDiFlags); end else DrawText(Handle, PChar(Caption), Length(Caption), TRC, DT_CENTER or DT_VCENTER or BiDiFlags); end; end; procedure Register; begin RegisterComponents('Samples', [TColorBtn]); end; end.
(* $Header: /SQL Toys/SqlFormatter/SqlConverters.pas 26 18-02-11 18:43 Tomek $ (c) Tomasz Gierka, github.com/SqlToys, 2015.06.14 *) {-------------------------------------- --------------------------------------} unit SqlConverters; interface uses SqlTokenizers, SqlStructs, SqlLister; const { converters settings values, same as icon numbers } SQCV_NONE = 0; SQCV_GROUP = 1; SQCV_ADD = 2; SQCV_REMOVE = 3; SQCV_UPPER = 4; SQCV_LOWER = 5; SQCV_SHORT = 6; SQCV_LONG = 7; { converter groups } SQCG_NONE = 0; SQCG_MAX = 6; SQCG_CASES = 1; SQCG_KEYWORD = 2; SQCG_DATA = 3; SQCG_JOIN = 4; SQCG_ORDER = 5; SQCG_LINES = 6; { converters = converter items } SQCC_NONE = 0; SQCC_MAX = 9; SQCC_CASE_KEYWORD = 1; SQCC_CASE_TABLE = 2; SQCC_CASE_TABLE_ALIAS = 3; SQCC_CASE_COLUMN = 4; SQCC_CASE_COLUMN_ALIAS = 5; SQCC_CASE_COLUMN_QUOTE = 6; SQCC_CASE_PARAM = 7; SQCC_CASE_FUNC = 8; SQCC_CASE_IDENT = 9; SQCC_KWD_AS_TABLES = 1; SQCC_KWD_AS_COLUMNS = 2; SQCC_DATA_INT = 1; SQCC_JOIN_INNER = 1; SQCC_JOIN_OUTER = 2; SQCC_JOIN_ON_LEFT = 3; SQCC_ORDER_KWD_LEN = 1; SQCC_ORDER_KWD_DEF = 2; SQCC_LINE_BEF_CLAUSE = 1; SQCC_EXC_SUBQUERY = 2; {should be sud node} SQCC_EXC_SHORT_QUERY = 3; {should be sud node} SQCC_LINE_AROUND_UNION = 4; procedure SqlConvertExecute( aGroup, aItem, aState: Integer; aNode: TGtSqlNode ); {---------------------------- Navigation procedures ---------------------------} //type TSqlNodeProcedure = procedure (aNode: TGtSqlNode); //type TSqlNodeCaseProcedure = procedure (aNode: TGtSqlNode; aCase: TGtSqlCaseOption); { TODO: move to TGtSqlNode.ForEach, TGtSqlNode.ForEachAndDeepInside } //procedure SqlToysExec_ForEach_Node ( aProc: TSqlNodeProcedure; aNode: TGtSqlNode; // aKind: TGtSqlNodeKind=gtsiNone; aKeyword: TGtLexTokenDef=nil; aName: String=''); //procedure SqlToysExec_ForEach_Node_Case ( aProc: TSqlNodeCaseProcedure; aNode: TGtSqlNode; // aCase: TGtSqlCaseOption = gtcoNoChange; // aKind: TGtSqlNodeKind=gtsiNone; aKeyword: TGtLexTokenDef=nil; aName: String=''); //procedure SqlToysExec_ForEach_DeepInside ( aProc: TSqlNodeProcedure; aNode: TGtSqlNode; // aKind: TGtSqlNodeKind=gtsiNone; aKeyword: TGtLexTokenDef=nil; aName: String=''); {----------------------------------- General ----------------------------------} //procedure SqlToysConvert_ExecuteAll(aNode: TGtSqlNode; aOptions: TGtListerSettingsArray; // aCaseOpt: TGtListerCaseSettingsArray); {------------------------------ Alias Converters ------------------------------} //procedure SqlToysConvert_ExprAlias_AddKeyword_AS(aNode: TGtSqlNode); //procedure SqlToysConvert_ExprAlias_RemoveKeyword_AS(aNode: TGtSqlNode); //procedure SqlToysConvert_TableAlias_AddKeyword_AS(aNode: TGtSqlNode); //procedure SqlToysConvert_TableAlias_RemoveKeyword_AS(aNode: TGtSqlNode); {------------------------------ Case Converters -------------------------------} //procedure SqlToysConvert_CaseKeyword(aNode: TGtSqlNode; aCase: TGtSqlCaseOption = gtcoNoChange); //procedure SqlToysConvert_CaseKeyword_Lower(aNode: TGtSqlNode); //procedure SqlToysConvert_CaseKeyword_Upper(aNode: TGtSqlNode); //procedure SqlToysConvert_CaseTableName(aNode: TGtSqlNode; aCase: TGtSqlCaseOption = gtcoNoChange); //procedure SqlToysConvert_CaseTableName_Lower(aNode: TGtSqlNode); //procedure SqlToysConvert_CaseTableName_Upper(aNode: TGtSqlNode); //procedure SqlToysConvert_CaseColumnName(aNode: TGtSqlNode; aCase: TGtSqlCaseOption = gtcoNoChange); //procedure SqlToysConvert_CaseColumnName_Lower(aNode: TGtSqlNode); //procedure SqlToysConvert_CaseColumnName_Upper(aNode: TGtSqlNode); //procedure SqlToysConvert_CaseTableAlias(aNode: TGtSqlNode; aCase: TGtSqlCaseOption = gtcoNoChange); //procedure SqlToysConvert_CaseTableAlias_Lower(aNode: TGtSqlNode); //procedure SqlToysConvert_CaseTableAlias_Upper(aNode: TGtSqlNode); //procedure SqlToysConvert_CaseColumnAlias(aNode: TGtSqlNode; aCase: TGtSqlCaseOption = gtcoNoChange); //procedure SqlToysConvert_CaseColumnAlias_Lower(aNode: TGtSqlNode); //procedure SqlToysConvert_CaseColumnAlias_Upper(aNode: TGtSqlNode); //procedure SqlToysConvert_CaseColumnQuotedAlias(aNode: TGtSqlNode; aCase: TGtSqlCaseOption = gtcoNoChange); //procedure SqlToysConvert_CaseColumnQuotedAlias_Lower(aNode: TGtSqlNode); //procedure SqlToysConvert_CaseColumnQuotedAlias_Upper(aNode: TGtSqlNode); //procedure SqlToysConvert_CaseParam(aNode: TGtSqlNode; aCase: TGtSqlCaseOption = gtcoNoChange); //procedure SqlToysConvert_CaseParam_Lower(aNode: TGtSqlNode); //procedure SqlToysConvert_CaseParam_Upper(aNode: TGtSqlNode); //procedure SqlToysConvert_CaseFunc(aNode: TGtSqlNode; aCase: TGtSqlCaseOption = gtcoNoChange); //procedure SqlToysConvert_CaseFunc_Lower(aNode: TGtSqlNode); //procedure SqlToysConvert_CaseFunc_Upper(aNode: TGtSqlNode); //procedure SqlToysConvert_CaseIdentifier(aNode: TGtSqlNode; aCase: TGtSqlCaseOption = gtcoNoChange); //procedure SqlToysConvert_CaseIdentifier_Lower(aNode: TGtSqlNode); //procedure SqlToysConvert_CaseIdentifier_Upper(aNode: TGtSqlNode); {---------------------------- Sort Order Converters ---------------------------} //procedure SqlToysConvert_SortOrder_ShortKeywords(aNode: TGtSqlNode); //procedure SqlToysConvert_SortOrder_LongKeywords(aNode: TGtSqlNode); //procedure SqlToysConvert_SortOrder_AddDefaultKeywords(aNode: TGtSqlNode); //procedure SqlToysConvert_SortOrder_RemoveDefaultKeywords(aNode: TGtSqlNode); {---------------------------- Datatype Converters -----------------------------} //procedure SqlToysConvert_DataType_IntToInteger(aNode: TGtSqlNode); //procedure SqlToysConvert_DataType_IntegerToInt(aNode: TGtSqlNode); {------------------------------- JOIN Converters ------------------------------} //procedure SqlToysConvert_Joins_AddInner(aNode: TGtSqlNode); //procedure SqlToysConvert_Joins_RemoveInner(aNode: TGtSqlNode); //procedure SqlToysConvert_Joins_AddOuter(aNode: TGtSqlNode); //procedure SqlToysConvert_Joins_RemoveOuter(aNode: TGtSqlNode); {-------------------------- JOIN condition Converters -------------------------} //procedure SqlToysConvert_JoinCond_RefToLeft(aNode: TGtSqlNode); implementation uses SysUtils; {----------------------------------- General ----------------------------------} //procedure SqlToysConvert_ExecuteAll(aNode: TGtSqlNode; aOptions: TGtListerSettingsArray; // aCaseOpt: TGtListerCaseSettingsArray); //begin //{------------------------------ Alias Converters ------------------------------} // if aOptions[ gtstTableAsKeywordCONVERTER ] // then SqlToysConvert_TableAlias_AddKeyword_AS( aNode ) // else SqlToysConvert_TableAlias_RemoveKeyword_AS( aNode ); // // if aOptions[ gtstExprAsKeywordCONVERTER ] // then SqlToysConvert_ExprAlias_AddKeyword_AS( aNode ) // else SqlToysConvert_ExprAlias_RemoveKeyword_AS( aNode ); //{------------------------------ Case Converters -------------------------------} ////procedure SqlToysConvert_CaseKeyword_Lower(aNode: TGtSqlNode); ////procedure SqlToysConvert_CaseKeyword_Upper(aNode: TGtSqlNode); // // SqlToysConvert_CaseTableName( aNode, aCaseOpt[ gtlcTableCONVERTER ] ); //// case aCaseOpt[ gtlcTableCONVERTER ] of //// gtcoNoChange : ; //// gtcoUpperCase : SqlToysConvert_CaseTableName_Upper( aNode ); //// gtcoLowerCase : SqlToysConvert_CaseTableName_Lower( aNode ); //// gtcoFirstCharUpper : ; //// gtcoFirstUseCase : ; //// end; // // SqlToysConvert_CaseColumnName( aNode, aCaseOpt[ gtlcColumnCONVERTER ] ); //// case aCaseOpt[ gtlcColumnCONVERTER ] of //// gtcoNoChange : ; //// gtcoUpperCase : SqlToysConvert_CaseColumnName_Upper( aNode ); //// gtcoLowerCase : SqlToysConvert_CaseColumnName_Lower( aNode ); //// gtcoFirstCharUpper : ; //// gtcoFirstUseCase : ; //// end; // // SqlToysConvert_CaseTableAlias( aNode, aCaseOpt[ gtlcTableAliasCONVERTER ] ); //// case aCaseOpt[ gtlcTableAliasCONVERTER ] of //// gtcoNoChange : ; //// gtcoUpperCase : SqlToysConvert_CaseTableAlias_Upper( aNode ); //// gtcoLowerCase : SqlToysConvert_CaseTableAlias_Lower( aNode ); //// gtcoFirstCharUpper : ; //// gtcoFirstUseCase : ; //// end; // // SqlToysConvert_CaseColumnAlias( aNode, aCaseOpt[ gtlcColumnAliasCONVERTER ] ); //// case aCaseOpt[ gtlcColumnAliasCONVERTER ] of //// gtcoNoChange : ; //// gtcoUpperCase : SqlToysConvert_CaseColumnAlias_Upper( aNode ); //// gtcoLowerCase : SqlToysConvert_CaseColumnAlias_Lower( aNode ); //// gtcoFirstCharUpper : ; //// gtcoFirstUseCase : ; //// end; // // SqlToysConvert_CaseColumnQuotedAlias( aNode, aCaseOpt[ gtlcColumnQuotedAliasCONVERTER ] ); //// case aCaseOpt[ gtlcColumnQuotedAliasCONVERTER ] of //// gtcoNoChange : ; //// gtcoUpperCase : SqlToysConvert_CaseColumnQuotedAlias_Upper( aNode ); //// gtcoLowerCase : SqlToysConvert_CaseColumnQuotedAlias_Lower( aNode ); //// gtcoFirstCharUpper : ; //// gtcoFirstUseCase : ; //// end; // // SqlToysConvert_CaseParam( aNode, aCaseOpt[ gtlcParameterCONVERTER ] ); //// case aCaseOpt[ gtlcParameterCONVERTER ] of //// gtcoNoChange : ; //// gtcoUpperCase : SqlToysConvert_CaseParam_Upper( aNode ); //// gtcoLowerCase : SqlToysConvert_CaseParam_Lower( aNode ); //// gtcoFirstCharUpper : ; //// gtcoFirstUseCase : ; //// end; // // SqlToysConvert_CaseFunc( aNode, aCaseOpt[ gtlcFunctionCONVERTER ] ); //// case aCaseOpt[ gtlcFunctionCONVERTER ] of //// gtcoNoChange : ; //// gtcoUpperCase : SqlToysConvert_CaseFunc_Upper( aNode ); //// gtcoLowerCase : SqlToysConvert_CaseFunc_Lower( aNode ); //// gtcoFirstCharUpper : ; //// gtcoFirstUseCase : ; //// end; // // SqlToysConvert_CaseIdentifier( aNode, aCaseOpt[ gtlcIdentifierCONVERTER ] ); //// case aCaseOpt[ gtlcIdentifierCONVERTER ] of //// gtcoNoChange : ; //// gtcoUpperCase : SqlToysConvert_CaseIdentifier_Upper( aNode ); //// gtcoLowerCase : SqlToysConvert_CaseIdentifier_Lower( aNode ); //// gtcoFirstCharUpper : ; //// gtcoFirstUseCase : ; //// end; //{---------------------------- Sort Order Converters ---------------------------} // if aOptions[ gtstSortShortCONVERTER ] // then SqlToysConvert_SortOrder_ShortKeywords( aNode ) // else SqlToysConvert_SortOrder_LongKeywords( aNode ); // // if aOptions[ gtstSkipAscendingCONVERTER ] // then SqlToysConvert_SortOrder_RemoveDefaultKeywords( aNode ) // else SqlToysConvert_SortOrder_AddDefaultKeywords( aNode ); //{---------------------------- Datatype Converters -----------------------------} // ////procedure SqlToysConvert_DataType_IntToInteger(aNode: TGtSqlNode); ////procedure SqlToysConvert_DataType_IntegerToInt(aNode: TGtSqlNode); // //{------------------------------- JOIN Converters ------------------------------} // if aOptions[ gtstInnerJoinCONVERTER ] // then SqlToysConvert_Joins_AddInner( aNode ) // else SqlToysConvert_Joins_RemoveInner( aNode ); // // if aOptions[ gtstOuterJoinCONVERTER ] // then SqlToysConvert_Joins_AddOuter( aNode ) // else SqlToysConvert_Joins_RemoveOuter( aNode ); //{-------------------------- JOIN condition Converters -------------------------} //// if aOptions[ gtstOnCondRefsFirstCONVERTER ] // if aOptions[ gtstJoinCondLeftSideOrderCONVERTER ] // then SqlToysConvert_JoinCond_RefToLeft( aNode ); //end; {---------------------------- Navigation procedures ---------------------------} { calls aProc for each node in aNode list } //procedure SqlToysExec_ForEach_Node ( aProc: TSqlNodeProcedure; aNode: TGtSqlNode; // aKind: TGtSqlNodeKind=gtsiNone; aKeyword: TGtLexTokenDef=nil; aName: String=''); ////var i: Integer; //begin // if not Assigned(aNode) then Exit; // // aNode.ForEach( aProc, False, {aNode,} aKind, aKeyword, aName ); // //// if not Assigned(aNode) then Exit; //// //// for i := 0 to aNode.Count -1 do //// if aNode[i].Check(aKind, aKeyword, aName) then aProc(aNode[i]); //end; //procedure SqlToysExec_ForEach_Node_Case ( aProc: TSqlNodeCaseProcedure; aNode: TGtSqlNode; // aCase: TGtSqlCaseOption = gtcoNoChange; // aKind: TGtSqlNodeKind=gtsiNone; aKeyword: TGtLexTokenDef=nil; aName: String=''); //var i: Integer; //begin // if not Assigned(aNode) then Exit; // // for i := 0 to aNode.Count -1 do // if aNode[i].Check(aKind, aKeyword, aName) then aProc(aNode[i], aCase); //end; { calls aProc for each node and its subnodes in aNode list } //procedure SqlToysExec_ForEach_DeepInside ( aProc: TSqlNodeProcedure; aNode: TGtSqlNode; // aKind: TGtSqlNodeKind=gtsiNone; aKeyword: TGtLexTokenDef=nil; aName: String=''); ////var i: Integer; //begin // if not Assigned(aNode) then Exit; // // aNode.ForEach( aProc, {aNode,} aKind, aKeyword, aName, True ); // //// for i := 0 to aNode.Count -1 do begin //// if aNode[i].Check(aKind, aKeyword, aName) then aProc(aNode[i]); //// //// { recursive call for each node } //// SqlToysExec_ForEach_DeepInside( aProc, aNode[i], aKind, aKeyword, aName ); //// end; //end; {--------------------------------- Converters ---------------------------------} { procedure for SELECT expr list iteration } procedure SqlToysConvert_ExprAlias_Iteration(aProc: TSqlNodeProcedure; aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if aNode.Check(gtsiExprList, gtkwSelect) then begin aNode.ForEach( aProc, False, gtsiExpr ); aNode.ForEach( aProc, False, gtsiExprTree ); end else if aNode.Check(gtsiDml, gtkwSelect) then begin aNode.ForEach( aProc, False, gtsiExprList, gtkwSelect ); end else if aNode.Check(gtsiQueryList) then begin aNode.ForEach( aProc, False, gtsiDml, gtkwSelect ); end; end; { procedure adds keyword AS to each top level expression in SELECT clause } procedure SqlToysConvert_ExprAlias_AddKeyword_AS(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if aNode.Check(gtsiExpr) or aNode.Check(gtsiExprTree) then begin aNode.AliasAsToken := aNode.AliasName <> ''; end else begin SqlToysConvert_ExprAlias_Iteration( SqlToysConvert_ExprAlias_AddKeyword_AS, aNode ); end; end; { procedure removes keyword AS from each top level expression in SELECT clause } procedure SqlToysConvert_ExprAlias_RemoveKeyword_AS(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if aNode.Check(gtsiExpr) or aNode.Check(gtsiExprTree) then begin aNode.AliasAsToken := False; end else begin SqlToysConvert_ExprAlias_Iteration( SqlToysConvert_ExprAlias_RemoveKeyword_AS, aNode ); end; end; { procedure for tables in FROM, UPDATE or DELETE clause iteration } procedure SqlToysConvert_TableAlias_Iteration(aProc: TSqlNodeProcedure; aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if aNode.Check(gtsiClauseTables) then begin aNode.ForEach( aProc, False, gtsiTableRef ); end else if aNode.Check(gtsiDml, gtkwSelect) then begin aNode.ForEach( aProc, False, gtsiClauseTables ); end else if aNode.Check(gtsiQueryList) then begin aNode.ForEach( aProc, False, gtsiDml, gtkwSelect ); end; end; { procedure adds keyword AS to each table in FROM, UPDATE or DELETE clause } procedure SqlToysConvert_TableAlias_AddKeyword_AS(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if aNode.Check(gtsiTableRef) then begin aNode.AliasAsToken := aNode.AliasName <> ''; end else begin SqlToysConvert_TableAlias_Iteration( SqlToysConvert_TableAlias_AddKeyword_AS, aNode ); end; end; { procedure removes keyword AS from each table in FROM, UPDATE or DELETE clause } procedure SqlToysConvert_TableAlias_RemoveKeyword_AS(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if aNode.Check(gtsiTableRef) then begin aNode.AliasAsToken := False; end else begin SqlToysConvert_TableAlias_Iteration( SqlToysConvert_TableAlias_RemoveKeyword_AS, aNode ); end; end; {------------------------------ Case Converters -------------------------------} //procedure SqlToysConvert_CaseKeyword(aNode: TGtSqlNode; aCase: TGtSqlCaseOption = gtcoNoChange); //begin // if not Assigned(aNode) then Exit; // // if aNode.Keyword <> gttkNone then aNode.Keyword := aNode.Keyword ; // // SqlToysExec_ForEach_Node_Case( SqlToysConvert_CaseKeyword, aNode, aCase ); //end; { procedure changes upper case keywords to lower case } procedure SqlToysConvert_CaseKeyword_Lower(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; // SqlToysExec_ForEach_Node( SqlToysConvert_CaseKeyword_Lower, aNode ); end; { procedure changes upper case keywords to lower case } procedure SqlToysConvert_CaseKeyword_Upper(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if aNode.Keyword <> gttkNone then aNode.Keyword := aNode.Keyword ; // SqlToysExec_ForEach_Node( SqlToysConvert_CaseKeyword_Upper, aNode ); end; //procedure SqlToysConvert_CaseTableName(aNode: TGtSqlNode; aCase: TGtSqlCaseOption = gtcoNoChange); //begin // if not Assigned(aNode) then Exit; // // if aNode.Kind = gtsiTableRef // then aNode.Name := UpperLowerStr( aNode.Name, aCase ); // // SqlToysExec_ForEach_Node_Case( SqlToysConvert_CaseTableName, aNode, aCase ); //end; procedure SqlToysConvert_CaseTableName_Lower(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if aNode.Kind = gtsiTableRef then aNode.Name := AnsiLowerCase( aNode.Name ); // SqlToysExec_ForEach_Node( SqlToysConvert_CaseTableName_Lower, aNode ); end; procedure SqlToysConvert_CaseTableName_Upper(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if aNode.Kind = gtsiTableRef then aNode.Name := AnsiUpperCase( aNode.Name ); // SqlToysExec_ForEach_Node( SqlToysConvert_CaseTableName_Upper, aNode ); end; //procedure SqlToysConvert_CaseTableAlias(aNode: TGtSqlNode; aCase: TGtSqlCaseOption = gtcoNoChange); //begin // if not Assigned(aNode) then Exit; // // if aNode.Kind = gtsiTableRef // then aNode.AliasName := UpperLowerStr( aNode.AliasName, aCase ); // // SqlToysExec_ForEach_Node_Case( SqlToysConvert_CaseTableAlias, aNode, aCase ); //end; procedure SqlToysConvert_CaseTableAlias_Lower(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if aNode.Kind = gtsiTableRef then aNode.AliasName := AnsiLowerCase( aNode.AliasName ); // SqlToysExec_ForEach_Node( SqlToysConvert_CaseTableAlias_Lower, aNode ); end; procedure SqlToysConvert_CaseTableAlias_Upper(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if aNode.Kind = gtsiTableRef then aNode.AliasName := AnsiUpperCase( aNode.AliasName ); // SqlToysExec_ForEach_Node( SqlToysConvert_CaseTableAlias_Upper, aNode ); end; //procedure SqlToysConvert_CaseColumnName(aNode: TGtSqlNode; aCase: TGtSqlCaseOption = gtcoNoChange); //begin // if not Assigned(aNode) then Exit; // // if (aNode.Kind = gtsiExpr) and (aNode.Keyword <> gttkParameterName) and (aNode.Name <> '') // and (aNode.Keyword <> gtkwFunction) // then aNode.Name := UpperLowerStr( aNode.Name, aCase ); // // SqlToysExec_ForEach_Node_Case( SqlToysConvert_CaseColumnName, aNode, aCase ); //end; procedure SqlToysConvert_CaseColumnName_Lower(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if (aNode.Kind = gtsiExpr) and (aNode.Keyword <> gttkParameterName) and (aNode.Name <> '') and (aNode.Keyword <> gtkwFunction) then aNode.Name := AnsiLowerCase( aNode.Name ); // SqlToysExec_ForEach_Node( SqlToysConvert_CaseColumnName_Lower, aNode ); end; procedure SqlToysConvert_CaseColumnName_Upper(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if (aNode.Kind = gtsiExpr) and (aNode.Keyword <> gttkParameterName) and (aNode.Name <> '') and (aNode.Keyword <> gtkwFunction) then aNode.Name := AnsiUpperCase( aNode.Name ); // SqlToysExec_ForEach_Node( SqlToysConvert_CaseColumnName_Upper, aNode ); end; //procedure SqlToysConvert_CaseColumnAlias(aNode: TGtSqlNode; aCase: TGtSqlCaseOption = gtcoNoChange); //begin // if not Assigned(aNode) then Exit; // // if (aNode.Kind = gtsiExprTree) and (aNode.AliasName <> '') and (Copy(aNode.AliasName,1,1) <> '"') // then aNode.AliasName := UpperLowerStr( aNode.AliasName, aCase ); // // SqlToysExec_ForEach_Node_Case( SqlToysConvert_CaseColumnAlias, aNode, aCase ); //end; procedure SqlToysConvert_CaseColumnAlias_Lower(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if (aNode.Kind = gtsiExprTree) and (aNode.AliasName <> '') and (Copy(aNode.AliasName,1,1) <> '"') then aNode.AliasName := AnsiLowerCase( aNode.AliasName ); // SqlToysExec_ForEach_Node( SqlToysConvert_CaseColumnAlias_Lower, aNode ); end; procedure SqlToysConvert_CaseColumnAlias_Upper(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if (aNode.Kind = gtsiExprTree) and (aNode.AliasName <> '') and (Copy(aNode.AliasName,1,1) <> '"') then aNode.AliasName := AnsiUpperCase( aNode.AliasName ); // SqlToysExec_ForEach_Node( SqlToysConvert_CaseColumnAlias_Upper, aNode ); end; //procedure SqlToysConvert_CaseParam(aNode: TGtSqlNode; aCase: TGtSqlCaseOption = gtcoNoChange); //begin // if not Assigned(aNode) then Exit; // // if (aNode.Kind = gtsiExpr) and (aNode.Keyword = gttkParameterName) and (aNode.Name <> '') // then aNode.Name := UpperLowerStr( aNode.Name, aCase ); // // SqlToysExec_ForEach_Node_Case( SqlToysConvert_CaseParam, aNode, aCase ); //end; procedure SqlToysConvert_CaseParam_Lower(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if (aNode.Kind = gtsiExpr) and (aNode.Keyword = gttkParameterName) and (aNode.Name <> '') then aNode.Name := AnsiLowerCase( aNode.Name ); // SqlToysExec_ForEach_Node( SqlToysConvert_CaseParam_Lower, aNode ); end; procedure SqlToysConvert_CaseParam_Upper(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if (aNode.Kind = gtsiExpr) and (aNode.Keyword = gttkParameterName) and (aNode.Name <> '') then aNode.Name := AnsiUpperCase( aNode.Name ); // SqlToysExec_ForEach_Node( SqlToysConvert_CaseParam_Upper, aNode ); end; //procedure SqlToysConvert_CaseFunc(aNode: TGtSqlNode; aCase: TGtSqlCaseOption = gtcoNoChange); //begin // if not Assigned(aNode) then Exit; // // if (aNode.Kind = gtsiExpr) and (aNode.Name <> '') and (aNode.Keyword = gtkwFunction) // then aNode.Name := UpperLowerStr( aNode.Name, aCase ); // // SqlToysExec_ForEach_Node_Case( SqlToysConvert_CaseFunc, aNode, aCase ); //end; procedure SqlToysConvert_CaseFunc_Lower(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if (aNode.Kind = gtsiExpr) and (aNode.Name <> '') and (aNode.Keyword = gtkwFunction) then aNode.Name := AnsiLowerCase( aNode.Name ); // SqlToysExec_ForEach_Node( SqlToysConvert_CaseFunc_Lower, aNode ); end; procedure SqlToysConvert_CaseFunc_Upper(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if (aNode.Kind = gtsiExpr) and (aNode.Name <> '') and (aNode.Keyword = gtkwFunction) then aNode.Name := AnsiUpperCase( aNode.Name ); // SqlToysExec_ForEach_Node( SqlToysConvert_CaseFunc_Upper, aNode ); end; //procedure SqlToysConvert_CaseColumnQuotedAlias(aNode: TGtSqlNode; aCase: TGtSqlCaseOption = gtcoNoChange); //begin // if not Assigned(aNode) then Exit; // // if (aNode.Kind = gtsiExprTree) and (aNode.AliasName <> '') and (Copy(aNode.AliasName,1,1) = '"') // then aNode.AliasName := UpperLowerStr( aNode.AliasName, aCase ); // // SqlToysExec_ForEach_Node_Case( SqlToysConvert_CaseColumnQuotedAlias, aNode, aCase ); //end; procedure SqlToysConvert_CaseColumnQuotedAlias_Lower(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if (aNode.Kind = gtsiExprTree) and (aNode.AliasName <> '') and (Copy(aNode.AliasName,1,1) = '"') then aNode.AliasName := AnsiLowerCase( aNode.AliasName ); // SqlToysExec_ForEach_Node( SqlToysConvert_CaseColumnQuotedAlias_Lower, aNode ); end; procedure SqlToysConvert_CaseColumnQuotedAlias_Upper(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if (aNode.Kind = gtsiExprTree) and (aNode.AliasName <> '') and (Copy(aNode.AliasName,1,1) = '"') then aNode.AliasName := AnsiUpperCase( aNode.AliasName ); // SqlToysExec_ForEach_Node( SqlToysConvert_CaseColumnQuotedAlias_Upper, aNode ); end; //procedure SqlToysConvert_CaseIdentifier(aNode: TGtSqlNode; aCase: TGtSqlCaseOption = gtcoNoChange); //begin // if not Assigned(aNode) then Exit; // // if (aNode.Kind = gtsiExpr) and (aNode.Name <> '') and (aNode.Keyword = gttkIdentifier) // then aNode.Name := UpperLowerStr( aNode.Name, aCase ); // // SqlToysExec_ForEach_Node_Case( SqlToysConvert_CaseIdentifier, aNode, aCase ); //end; procedure SqlToysConvert_CaseIdentifier_Lower(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if (aNode.Kind = gtsiExpr) and (aNode.Name <> '') and (aNode.Keyword = gttkIdentifier) then aNode.Name := AnsiLowerCase( aNode.Name ); // SqlToysExec_ForEach_Node( SqlToysConvert_CaseIdentifier_Lower, aNode ); end; procedure SqlToysConvert_CaseIdentifier_Upper(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if (aNode.Kind = gtsiExpr) and (aNode.Name <> '') and (aNode.Keyword = gttkIdentifier) then aNode.Name := AnsiUpperCase( aNode.Name ); // SqlToysExec_ForEach_Node( SqlToysConvert_CaseIdentifier_Upper, aNode ); end; {---------------------------- Sort Order Converters ---------------------------} { procedure for ORDER BY iteration } procedure SqlToysConvert_SortOrder_Iteration(aProc: TSqlNodeProcedure; aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if aNode.Check(gtsiExprList, gtkwOrder_By) then begin aNode.ForEach( aProc, False, gtsiExpr ); aNode.ForEach( aProc, False, gtsiExprTree ); end else if aNode.Check(gtsiDml, gtkwSelect) then begin aNode.ForEach( aProc, False, gtsiExprList, gtkwOrder_By ); end else if aNode.Check(gtsiQueryList) then begin aNode.ForEach( aProc, False, gtsiDml, gtkwSelect ); end; end; { procedure removes uses short ASC/DESC keywords in ORDER BY clause } procedure SqlToysConvert_SortOrder_ShortKeywords(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if aNode.Check(gtsiExpr) or aNode.Check(gtsiExprTree) then begin if aNode.SortOrder = gtkwAscending then aNode.SortOrder := gtkwAsc else if aNode.SortOrder = gtkwDescending then aNode.SortOrder := gtkwDesc ; // end else begin // SqlToysConvert_SortOrder_Iteration( SqlToysConvert_SortOrder_ShortKeywords, aNode ); end; end; { procedure removes uses long ASCENDING/DESCENDING keywords in ORDER BY clause } procedure SqlToysConvert_SortOrder_LongKeywords(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if aNode.Check(gtsiExpr) or aNode.Check(gtsiExprTree) then begin if aNode.SortOrder = gtkwAsc then aNode.SortOrder := gtkwAscending else if aNode.SortOrder = gtkwDesc then aNode.SortOrder := gtkwDescending ; // end else begin // SqlToysConvert_SortOrder_Iteration( SqlToysConvert_SortOrder_LongKeywords, aNode ); end; end; { procedure adds ASC keywords in ORDER BY clause with no sort order specified } procedure SqlToysConvert_SortOrder_AddDefaultKeywords(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if aNode.Check(gtsiExpr) or aNode.Check(gtsiExprTree) then begin if aNode.SortOrder = gttkNone then aNode.SortOrder := gtkwAscending; // end else begin // SqlToysConvert_SortOrder_Iteration( SqlToysConvert_SortOrder_AddDefaultKeywords, aNode ); end; end; { procedure removes ASC keywords in ORDER BY clause } procedure SqlToysConvert_SortOrder_RemoveDefaultKeywords(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if aNode.Check(gtsiExpr) or aNode.Check(gtsiExprTree) then begin if (aNode.SortOrder = gtkwAsc) or (aNode.SortOrder = gtkwAscending) then aNode.SortOrder := gttkNone; // end else begin // SqlToysConvert_SortOrder_Iteration( SqlToysConvert_SortOrder_RemoveDefaultKeywords, aNode ); end; end; {---------------------------- Datatype Converters -----------------------------} { converter changes datatype keyword from INT to INTEGER } procedure SqlToysConvert_DataType_IntToInteger(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if aNode.DataType = gtkwInt then begin aNode.DataType := gtkwInteger; end; // SqlToysExec_ForEach_DeepInside ( SqlToysConvert_DataType_IntToInteger, aNode ); end; { converter changes datatype keyword from INTEGER to INT } procedure SqlToysConvert_DataType_IntegerToInt(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if aNode.DataType = gtkwInteger then begin aNode.DataType := gtkwInt; end; // SqlToysExec_ForEach_DeepInside ( SqlToysConvert_DataType_IntegerToInt, aNode ); end; {------------------------------- JOIN Converters ------------------------------} { converter changes JOIN to INNER JOIN } procedure SqlToysConvert_Joins_AddInner(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if aNode.{JoinOp} Operand = gtkwInner then aNode.JoinInnerKeyword := True; // SqlToysExec_ForEach_DeepInside ( SqlToysConvert_Joins_AddInner, aNode ); end; { converter changes INNER JOIN to JOIN } procedure SqlToysConvert_Joins_RemoveInner(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if aNode.{JoinOp} Operand = gtkwInner then aNode.JoinInnerKeyword := False; // SqlToysExec_ForEach_DeepInside ( SqlToysConvert_Joins_RemoveInner, aNode ); end; { converter changes LEFT/RIGHT JOIN to LEFT/RIGHT OUTER JOIN } procedure SqlToysConvert_Joins_AddOuter(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if (aNode.{JoinOp} Operand = gtkwLeft) or (aNode.{JoinOp} Operand = gtkwRight) or (aNode.{JoinOp} Operand = gtkwFull) then aNode.JoinOuterKeyword := True; // SqlToysExec_ForEach_DeepInside ( SqlToysConvert_Joins_AddOuter, aNode ); end; { converter changes LEFT/RIGHT OUTER JOIN to LEFT/RIGHT JOIN } procedure SqlToysConvert_Joins_RemoveOuter(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if (aNode.{JoinOp} Operand = gtkwLeft) or (aNode.{JoinOp} Operand = gtkwRight) or (aNode.{JoinOp} Operand = gtkwFull) then aNode.JoinOuterKeyword := False; // SqlToysExec_ForEach_DeepInside ( SqlToysConvert_Joins_RemoveOuter, aNode ); end; {-------------------------- JOIN condition Converters -------------------------} { converts join condition } procedure SqlToysConvert_JoinCond_RefToLeft(aNode: TGtSqlNode); // gtstJoinCondLeftSideOrder => gtloCondLeftSideOrder => gtloCondEqualSwap // gtstOnCondRefsFirst => moves conds w. refs to top and conds wo. refs to bottom var sTableNameOrAlias: String; procedure CheckAndSwapCondExpressions(aCond: TGtSqlNode); begin if not Assigned(aCond) then Exit; if aCond.Kind <> gtsiCond then Exit; if aCond.{CompOp} Operand <> gttkEqual then Exit; if aCond.Count <> 2 then Exit; if aCond[0].ExprHasReferenceTo(sTableNameOrAlias) then Exit; if not aCond[1].ExprHasReferenceTo(sTableNameOrAlias) then Exit; { swaps condition sides } aCond[0].Name := '2'; aCond[1].Name := '1'; end; procedure CondTreeGoDeepInside(aCondTree: TGtSqlNode); var i: Integer; begin if not Assigned(aCondTree) then Exit; for i := 0 to aCondTree.Count - 1 do if aCondTree[i].Kind = gtsiCond then CheckAndSwapCondExpressions(aCondTree[i]) else if aCondTree[i].Kind = gtsiCondTree then CondTreeGoDeepInside(aCondTree[i]); end; begin if not Assigned(aNode) then Exit; if (aNode.Kind = gtsiCondTree) and (aNode.Keyword = gtkwOn) then begin sTableNameOrAlias := aNode.OwnerTableNameOrAlias ; CondTreeGoDeepInside(aNode); // end else begin // SqlToysExec_ForEach_DeepInside ( SqlToysConvert_JoinCond_RefToLeft, aNode ); end; end; {--------------------------------- Empty lines --------------------------------} { procedure adds empty line before clause } procedure SqlToysConvert_EmptyLine_Clause_Add(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if (aNode.Owner.Kind = gtsiDml) and not aNode.IsSubQuery and not aNode.IsShortQuery and aNode.IsClauseKeyword // ((aNode.Keyword = gtkwSelect) or // (aNode.Keyword = gtkwFrom) or (aNode.Keyword = gtkwWhere) or (aNode.Keyword = gtkwGroup_By) or // (aNode.Keyword = gtkwHaving) or (aNode.Keyword = gtkwOrder_By) or (aNode.Keyword = gtkwConnect_By) or // (aNode.Keyword = gtkwSet) or (aNode.Keyword = gtkwValues)) then aNode.EmptyLineBefore := True; end; { procedure removes empty line before clause } procedure SqlToysConvert_EmptyLine_Clause_Remove(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if (aNode.Owner.Kind = gtsiDml) and not aNode.IsSubQuery and not aNode.IsShortQuery and aNode.IsClauseKeyword // ((aNode.Keyword = gtkwSelect) or // (aNode.Keyword = gtkwFrom) or (aNode.Keyword = gtkwWhere) or (aNode.Keyword = gtkwGroup_By) or // (aNode.Keyword = gtkwHaving) or (aNode.Keyword = gtkwOrder_By) or (aNode.Keyword = gtkwConnect_By) or // (aNode.Keyword = gtkwSet) or (aNode.Keyword = gtkwValues)) then aNode.EmptyLineBefore := False; end; { procedure adds empty line before clause in subqueries } procedure SqlToysConvert_EmptyLine_ClauseSubquery_Add(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if (aNode.Owner.Kind = gtsiDml) and aNode.IsSubQuery and not aNode.IsShortQuery and aNode.IsClauseKeyword // ((aNode.Keyword = gtkwSelect) or // (aNode.Keyword = gtkwFrom) or (aNode.Keyword = gtkwWhere) or (aNode.Keyword = gtkwGroup_By) or // (aNode.Keyword = gtkwHaving) or (aNode.Keyword = gtkwOrder_By) or (aNode.Keyword = gtkwConnect_By) or // (aNode.Keyword = gtkwSet) or (aNode.Keyword = gtkwValues)) then aNode.EmptyLineBefore := True; end; { procedure removes empty line before clause in subqueries } procedure SqlToysConvert_EmptyLine_ClauseSubquery_Remove(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if (aNode.Owner.Kind = gtsiDml) and aNode.IsSubQuery and not aNode.IsShortQuery and aNode.IsClauseKeyword // ((aNode.Keyword = gtkwSelect) or // (aNode.Keyword = gtkwFrom) or (aNode.Keyword = gtkwWhere) or (aNode.Keyword = gtkwGroup_By) or // (aNode.Keyword = gtkwHaving) or (aNode.Keyword = gtkwOrder_By) or (aNode.Keyword = gtkwConnect_By) or // (aNode.Keyword = gtkwSet) or (aNode.Keyword = gtkwValues)) then aNode.EmptyLineBefore := False; end; { procedure adds empty line before clause in short queries } procedure SqlToysConvert_EmptyLine_ClauseShortQuery_Add(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if (aNode.Owner.Kind = gtsiDml) and not aNode.IsSubQuery and aNode.IsShortQuery and aNode.IsClauseKeyword // ((aNode.Keyword = gtkwSelect) or // (aNode.Keyword = gtkwFrom) or (aNode.Keyword = gtkwWhere) or (aNode.Keyword = gtkwGroup_By) or // (aNode.Keyword = gtkwHaving) or (aNode.Keyword = gtkwOrder_By) or (aNode.Keyword = gtkwConnect_By) or // (aNode.Keyword = gtkwSet) or (aNode.Keyword = gtkwValues)) then aNode.EmptyLineBefore := True; end; { procedure removes empty line before clause in short queries } procedure SqlToysConvert_EmptyLine_ClauseShortQuery_Remove(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if (aNode.Owner.Kind = gtsiDml) and not aNode.IsSubQuery and aNode.IsShortQuery and aNode.IsClauseKeyword // ((aNode.Keyword = gtkwSelect) or // (aNode.Keyword = gtkwFrom) or (aNode.Keyword = gtkwWhere) or (aNode.Keyword = gtkwGroup_By) or // (aNode.Keyword = gtkwHaving) or (aNode.Keyword = gtkwOrder_By) or (aNode.Keyword = gtkwConnect_By) or // (aNode.Keyword = gtkwSet) or (aNode.Keyword = gtkwValues)) then aNode.EmptyLineBefore := False; end; { procedure adds empty line around UNION, MINUS, etc } procedure SqlToysConvert_EmptyLine_Union_Add(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if (aNode.Kind = gtsiUnions) then begin aNode.EmptyLineBefore := True; aNode.EmptyLineAfter := True; end; end; { procedure adds empty line around UNION, MINUS, etc } procedure SqlToysConvert_EmptyLine_Union_Remove(aNode: TGtSqlNode); begin if not Assigned(aNode) then Exit; if (aNode.Kind = gtsiUnions) then begin aNode.EmptyLineBefore := False; aNode.EmptyLineAfter := False; end; end; {----------------------------------- General ----------------------------------} { executes converter } procedure SqlConvertExecute( aGroup, aItem, aState: Integer; aNode: TGtSqlNode ); overload; begin case aGroup of SQCG_CASES : case aItem of SQCC_CASE_KEYWORD : case aState of SQCV_UPPER : aNode.ForEach( SqlToysConvert_CaseKeyword_Upper, True ); SQCV_LOWER : aNode.ForEach( SqlToysConvert_CaseKeyword_Lower, True ); end; SQCC_CASE_TABLE : case aState of SQCV_UPPER : aNode.ForEach( SqlToysConvert_CaseTableName_Upper, True ); SQCV_LOWER : aNode.ForEach( SqlToysConvert_CaseTableName_Lower, True ); end; SQCC_CASE_TABLE_ALIAS : case aState of SQCV_UPPER : aNode.ForEach( SqlToysConvert_CaseTableAlias_Upper, True ); SQCV_LOWER : aNode.ForEach( SqlToysConvert_CaseTableAlias_Lower, True ); end; SQCC_CASE_COLUMN : case aState of SQCV_UPPER : aNode.ForEach( SqlToysConvert_CaseColumnName_Upper, True ); SQCV_LOWER : aNode.ForEach( SqlToysConvert_CaseColumnName_Lower, True ); end; SQCC_CASE_COLUMN_ALIAS : case aState of SQCV_UPPER : aNode.ForEach( SqlToysConvert_CaseColumnAlias_Upper, True ); SQCV_LOWER : aNode.ForEach( SqlToysConvert_CaseColumnAlias_Lower, True ); end; SQCC_CASE_COLUMN_QUOTE : case aState of SQCV_UPPER : aNode.ForEach( SqlToysConvert_CaseColumnQuotedAlias_Upper, True ); SQCV_LOWER : aNode.ForEach( SqlToysConvert_CaseColumnQuotedAlias_Lower, True ); end; SQCC_CASE_PARAM : case aState of SQCV_UPPER : aNode.ForEach( SqlToysConvert_CaseParam_Upper, True ); SQCV_LOWER : aNode.ForEach( SqlToysConvert_CaseParam_Lower, True ); end; SQCC_CASE_FUNC : case aState of SQCV_UPPER : aNode.ForEach( SqlToysConvert_CaseFunc_Upper, True ); SQCV_LOWER : aNode.ForEach( SqlToysConvert_CaseFunc_Lower, True ); end; SQCC_CASE_IDENT : case aState of SQCV_UPPER : aNode.ForEach( SqlToysConvert_CaseIdentifier_Upper, True ); SQCV_LOWER : aNode.ForEach( SqlToysConvert_CaseIdentifier_Lower, True ); end; end; SQCG_KEYWORD : case aItem of SQCC_KWD_AS_TABLES : case aState of SQCV_ADD : aNode.ForEach( SqlToysConvert_TableAlias_AddKeyword_AS, True ); SQCV_REMOVE : aNode.ForEach( SqlToysConvert_TableAlias_RemoveKeyword_AS, True ); end; SQCC_KWD_AS_COLUMNS : case aState of SQCV_ADD : aNode.ForEach( SqlToysConvert_ExprAlias_AddKeyword_AS, True ); SQCV_REMOVE : aNode.ForEach( SqlToysConvert_ExprAlias_RemoveKeyword_AS, True ); end; end; SQCG_DATA : case aItem of SQCC_DATA_INT : case aState of SQCV_SHORT : aNode.ForEach( SqlToysConvert_DataType_IntegerToInt, True ); SQCV_LONG : aNode.ForEach( SqlToysConvert_DataType_IntToInteger, True ); end; end; SQCG_JOIN : case aItem of SQCC_JOIN_INNER : case aState of SQCV_ADD : aNode.ForEach( SqlToysConvert_Joins_AddInner, True ); SQCV_REMOVE : aNode.ForEach( SqlToysConvert_Joins_RemoveInner, True ); end; SQCC_JOIN_OUTER : case aState of SQCV_ADD : aNode.ForEach( SqlToysConvert_Joins_AddOuter, True ); SQCV_REMOVE : aNode.ForEach( SqlToysConvert_Joins_RemoveOuter, True ); end; SQCC_JOIN_ON_LEFT : case aState of SQCV_ADD : aNode.ForEach( SqlToysConvert_JoinCond_RefToLeft, True ); end; end; SQCG_ORDER : case aItem of SQCC_ORDER_KWD_LEN : case aState of SQCV_SHORT : aNode.ForEach( SqlToysConvert_SortOrder_ShortKeywords, True ); SQCV_LONG : aNode.ForEach( SqlToysConvert_SortOrder_LongKeywords, True ); end; SQCC_ORDER_KWD_DEF : case aState of SQCV_ADD : aNode.ForEach( SqlToysConvert_SortOrder_AddDefaultKeywords, True ); SQCV_REMOVE : aNode.ForEach( SqlToysConvert_SortOrder_RemoveDefaultKeywords, True ); end; end; SQCG_LINES : case aItem of SQCC_LINE_BEF_CLAUSE : case aState of SQCV_ADD : aNode.ForEach( SqlToysConvert_EmptyLine_Clause_Add, True ); SQCV_REMOVE : aNode.ForEach( SqlToysConvert_EmptyLine_Clause_Remove, True ); end; SQCC_EXC_SUBQUERY : case aState of SQCV_ADD : aNode.ForEach( SqlToysConvert_EmptyLine_ClauseSubquery_Add, True ); SQCV_REMOVE : aNode.ForEach( SqlToysConvert_EmptyLine_ClauseSubquery_Remove, True ); end; SQCC_EXC_SHORT_QUERY : case aState of SQCV_ADD : aNode.ForEach( SqlToysConvert_EmptyLine_ClauseShortQuery_Add, True ); SQCV_REMOVE : aNode.ForEach( SqlToysConvert_EmptyLine_ClauseShortQuery_Remove, True ); end; SQCC_LINE_AROUND_UNION : case aState of SQCV_ADD : aNode.ForEach( SqlToysConvert_EmptyLine_Union_Add, True ); SQCV_REMOVE : aNode.ForEach( SqlToysConvert_EmptyLine_Union_Remove, True ); end; end; end; end; end.
unit Win32.DV; //------------------------------------------------------------------------------ // File: DV.h // Desc: DV typedefs and defines. // Copyright (c) 1997 - 2001, Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ // Updated to SDK 10.0.17763.0 // (c) Translation to Pascal by Norbert Sonnleitner {$mode delphi} interface uses Classes, SysUtils; const DV_DVSD_NTSC_FRAMESIZE = 120000; DV_DVSD_PAL_FRAMESIZE = 144000; DV_SMCHN = $0000e000; DV_AUDIOMODE = $00000f00; DV_AUDIOSMP = $38000000; DV_AUDIOQU = $07000000; DV_NTSCPAL = $00200000; DV_STYPE = $001f0000; //There are NTSC or PAL DV camcorders DV_NTSC = 0; DV_PAL = 1; //DV camcorder can output sd/hd/sl DV_SD = $00; DV_HD = $01; DV_SL = $02; //user can choice 12 bits or 16 bits audio from DV camcorder DV_CAP_AUD16Bits = $00; DV_CAP_AUD12Bits = $01; SIZE_DVINFO = $20; type TDVAudInfo = record bAudStyle: array [0..1] of byte; //LSB 6 bits for starting DIF sequence number //MSB 2 bits: 0 for mon. 1: stereo in one 5/6 DIF sequences, 2: stereo audio in both 5/6 DIF sequences //example: $00: mon, audio in first 5/6 DIF sequence // $05: mon, audio in 2nd 5 DIF sequence // $15: stereo, audio only in 2nd 5 DIF sequence // $10: stereo, audio only in 1st 5/6 DIF sequence // $20: stereo, left ch in 1st 5/6 DIF sequence, right ch in 2nd 5/6 DIF sequence // $26: stereo, rightch in 1st 6 DIF sequence, left ch in 2nd 6 DIF sequence bAudQu: array[0..1] of byte; //qbits, only support 12, 16, bNumAudPin: byte; //how many pin(language) wAvgSamplesPerPinPerFrm: array [0..1] of word; //samples size for one audio pin in one frame(which has 10 or 12 DIF sequence) wBlkMode: word; //45 for NTSC, 54 for PAL wDIFMode: word; //5 for NTSC, 6 for PAL wBlkDiv: word; //15 for NTSC, 18 for PAL end; PDVAudInfo = ^TDVAudInfo; implementation end.
unit CodeExplorer; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ImgList, ExtCtrls, Menus, EasyClasses, EasyEditSource, EasyEditor, PhpParser; type TCodeExplorerForm = class(TForm) TreeView: TTreeView; ExplorerImages: TImageList; PopupMenu1: TPopupMenu; ShowCode1: TMenuItem; procedure TreeViewDblClick(Sender: TObject); procedure FormHide(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } FEasyEdit: TEasyEdit; FEasyParser: TCustomEasyParser; //FNeedExpand: Boolean; FParser: TUnitInfo; FList: TStrings; protected function GetEasyParser: TCustomEasyParser; function GetNodeText(Node: TTreeNode): string; procedure AfterRefresh(inList: TStrings); procedure BeforeRefresh(inList: TStrings); procedure ExpandWithParent(Node: TTreeNode); procedure FillTree; procedure Parse; public { Public declarations } procedure UpdateExplorer; public property EasyEdit: TEasyEdit read FEasyEdit write FEasyEdit; property EasyParser: TCustomEasyParser read GetEasyParser write FEasyParser; end; implementation uses EditUnit, EasyUtils, EasyParser, EasyKeyMap; {$R *.DFM} const sPublicStr = 'public'; sClasses = 'classes'; sConstants = 'constants'; sVariables = 'variables'; sFunctions = 'functions'; procedure TCodeExplorerForm.FormCreate(Sender: TObject); begin FParser := TUnitInfo.Create; end; procedure TCodeExplorerForm.FormDestroy(Sender: TObject); begin FParser.Free; end; function TCodeExplorerForm.GetNodeText(Node: TTreeNode): string; begin Result := ''; while Node <> nil do begin if Result = '' then Result := Node.Text else Result := Result + '.' + Node.Text; Node := Node.Parent; end; end; procedure TCodeExplorerForm.ExpandWithParent(Node: TTreeNode); begin while Node <> nil do begin Node.Expand(False); Node := Node.Parent; end; end; procedure TCodeExplorerForm.BeforeRefresh(inList: TStrings); var Node: TTreeNode; begin with TreeView, Items do begin Node := GetFirstNode; while Node <> nil do begin if Node.Expanded then // if (Node.Data <> nil) and (TObject(Node.Data) is TElementInfo) then // inList.Add(TElementInfo(Node.Data).Name) // else inList.Add(GetNodeText(Node)); Node := Node.GetNextVisible; end; end; end; procedure TCodeExplorerForm.AfterRefresh(inList : TStrings); var Node: TTreeNode; s: string; begin with TreeView, Items do begin Node := GetFirstNode; while Node <> nil do begin // if (Node.Data <> nil) and (TObject(Node.Data) is TElementInfo) then // s := TElementInfo(Node.Data).Name // else s := GetNodeText(Node); if (inList.IndexOf(s) >= 0) then Node.Expanded := true; //ExpandWithParent(Node); Node := Node.GetNext; end; end; end; procedure TCodeExplorerForm.Parse; {$IFDEF EASY_WIDESTRINGS} var i: integer; AStrings: TStrings; {$ENDIF} begin if EasyEdit <> nil then with EasyEdit do begin FParser.Parser := TEasyEditorParser(EasyParser); {$IFDEF EASY_WIDESTRINGS} AStrings := TStringList.Create; try for i := 0 to Lines.Count - 1 do AStrings.Add(Lines[i]); FParser.ReparseStrings(AStrings); finally AStrings.Free; end; {$ELSE} FParser.ReparseStrings(Lines); {$ENDIF} end else FParser.ReparseStrings(nil); end; procedure TCodeExplorerForm.UpdateExplorer; begin Parse; //FNeedExpand := (Count = 0); FList := CreateSortedStrings; try BeforeRefresh(FList); FillTree; AfterRefresh(FList); finally FList.Free; end; end; procedure TCodeExplorerForm.FillTree; var node: TTreeNode; function _AddNode(inNode: TTreeNode; const s: string; ImageIndex: integer; Data: Pointer; Expand: Boolean): TTreeNode; begin Result := TreeView.Items.AddChildObject(inNode, s, Data); Result.ImageIndex := ImageIndex; Result.SelectedIndex := ImageIndex; if Expand then // if Data = nil then FList.Add(GetNodeText(Result)) // else // FList.Add(s); end; procedure ProcessScope(const ACaption: string; ImageIndex: integer; inNode: TTreeNode; AScope: TElementScope; Strings: TStrings; Expand: Boolean); var i: Integer; info: TElementInfo; aNode, n: TTreeNode; begin aNode := nil; with TreeView.Items, Strings do for i := 0 to Count - 1 do begin info := TElementInfo(Objects[i]); if (info <> nil) and (info.Scope = AScope) then begin if aNode = nil then aNode := _AddNode(inNode, ACaption, 0, nil, true);//Expand); if (info is TClassInfo) then begin n := _AddNode(aNode, info.Name, ImageIndex, info, false); ProcessScope('Fields', 2, n, sLocalVar, TClassInfo(info).Fields, false); ProcessScope('Methods', 1, n, sPublic, TClassInfo(info).Methods, true); end else if (info is TFunctionInfo) then begin {n :=} _AddNode(aNode, info.Name, ImageIndex, info, false); { ProcessScope('Globals', 2, n, sGlobalDecl, TFunctionInfo(info).GlobalDecls, true); ProcessScope('References', 2, n, sUsedVar, TFunctionInfo(info).UsedVars, true); } end else _AddNode(aNode, info.Name, ImageIndex, info, Expand); end; end; end; procedure ProcessStrings(const inCaption: string; inImageIndex: integer; inStrings: TStrings); begin //ProcessScope(inCaption, inImageIndex, node, sPublic, inStrings, FNeedExpand); ProcessScope(inCaption, inImageIndex, node, sPublic, inStrings, false); end; begin with TreeView, Items do begin BeginUpdate; try Clear; node := nil; with FParser do begin ProcessStrings(sConstants, 4, Constants); ProcessStrings(sClasses, 1, Classes); ProcessStrings(sVariables, 2, Variables); ProcessStrings(sFunctions, 1, Functions); end; finally EndUpdate; end; end; end; procedure TCodeExplorerForm.TreeViewDblClick(Sender: TObject); begin with TreeView do try if (Selected <> nil) and (TObject(Selected.Data) is TElementInfo) then begin if EasyEdit <> nil then with EasyEdit do begin EditSource.BeginSourceUpdate(oprNavigate); try EditSource.JumpToLine(TElementInfo(Selected.Data).LineNo); Navigate(cCenterLine); SetFocus; Windows.SetFocus(Handle); finally EditSource.EndSourceUpdate; end; end; end; except end; end; procedure TCodeExplorerForm.FormHide(Sender: TObject); begin if Parent is TPanel then Parent.Width := 1; end; function TCodeExplorerForm.GetEasyParser: TCustomEasyParser; begin if FEasyParser = nil then Result := EasyEdit.Parser else Result := FEasyParser; end; end.
(* InfixToPrefix 26.04.17 *) PROGRAM InfixToPrefix; CONST eosCh = Chr(0); TYPE SymbolCode = (noSy, (* error symbol *) eosSy, plusSy, minusSy, timesSy, divSy, leftParSy, righParSy, number, variable); VAR line: STRING; ch: CHAR; cnr: INTEGER; sy: SymbolCode; numberVal, variableStr: STRING; success: BOOLEAN; (* ====== Scanner ====== *) PROCEDURE NewCh; BEGIN IF cnr < Length(line) THEN BEGIN cnr := cnr + 1; ch := line[cnr]; END ELSE BEGIN ch := eosCh; END; END; PROCEDURE NewSy; VAR numberStr: STRING; code: INTEGER; BEGIN WHILE ch = ' ' DO BEGIN NewCh; END; CASE ch OF eosCh: BEGIN sy := eosSy; END; '+': BEGIN sy := plusSy; NewCh; END; '-': BEGIN sy := minusSy; NewCh; END; '*': BEGIN sy := timesSy; NewCh; END; '/': BEGIN sy := divSy; NewCh; END; '(': BEGIN sy := leftParSy; NewCh; END; ')': BEGIN sy := righParSy; NewCh; END; (* for numbers *) '0'..'9': BEGIN sy := number; numberStr := ''; WHILE (ch >= '0') AND (ch <= '9') DO BEGIN numberStr := numberStr + ch; NewCh; END; numberVal := numberStr; END; (* for characters *) 'A' .. 'Z', 'a'..'z': BEGIN sy := variable; variableStr := ''; WHILE ((ch >= 'A') AND (ch < 'Z')) OR ((ch >= 'a') AND (ch < 'z')) DO BEGIN variableStr := variableStr + ch; NewCh; END; END; ELSE sy := noSy; END; END; (* ====== PARSER ====== *) PROCEDURE S; FORWARD; PROCEDURE Expr(VAR e: STRING); FORWARD; PROCEDURE Term(VAR t: STRING); FORWARD; PROCEDURE Fact(VAR f: STRING); FORWARD; PROCEDURE S; VAR e: STRING; BEGIN Expr(e); IF NOT success THEN EXIT; (* SEM *) WriteLn('result= ', e); (* ENDSEM *) IF sy <> eosSy THEN BEGIN success := FALSE; EXIT; END; END; PROCEDURE Expr(VAR e: STRING); VAR t1, t2: STRING; BEGIN Term(t1); IF NOT success THEN EXIT; (* SEM *) e := t1; (* ENDSEM *) WHILE (sy = plusSy) OR (sy = minusSy) DO BEGIN CASE sy OF plusSy: BEGIN NewSy; Term(t2); IF NOT success THEN EXIT; (* SEM *) e := ' + ' + t1 + ' ' + t2; t1 := e; (* ENDSEM *) END; minusSy: BEGIN NewSy; Term(t2); IF NOT success THEN EXIT; (* SEM *) e := ' - ' + t1 + ' ' + t2; t1 := e; (* ENDSEM *) END; END; END; END; PROCEDURE Term(VAR t: STRING); VAR f1, f2: STRING; BEGIN Fact(f1); IF NOT success THEN EXIT; (* SEM *) t := f1; (* ENDSEM *) WHILE (sy = timesSy) OR (sy = divSy) DO BEGIN CASE sy OF timesSy: BEGIN NewSy; Fact(f2); IF NOT success THEN EXIT; (* SEM *) t := ' * ' + f1 + ' ' + f2; f1 := t; (* ENDSEM *) END; divSy: BEGIN NewSy; Fact(f2); IF NOT success THEN EXIT; (* SEM *) t := ' / ' + f1 + ' ' + f2; f1 := t; (* ENDSEM *) END; END; END; END; PROCEDURE Fact(VAR f: STRING); BEGIN CASE sy OF number: BEGIN (* SEM *) f := numberVal; (* ENDSEM *) NewSy; END; variable: BEGIN f := variableStr; NewSy; END; leftParSy: BEGIN NewSy; Expr(f); IF NOT success THEN EXIT; IF sy <> righParSy THEN BEGIN success:= FALSE; EXIT; END; NewSy; END; ELSE success := FALSE; END; END; (* ====== END PARSER ====== *) PROCEDURE SyntaxTest(str: STRING); BEGIN WriteLn('Infix: ', str); line := str; cnr := 0; NewCh; NewSy; success := TRUE; S; IF success THEN WriteLn('successful syntax analysis',#13#10) ELSE WriteLn('Error in column: ', cnr,#13#10); END; BEGIN (* Test cases *) SyntaxTest('(a + b) * c'); SyntaxTest('1 + 2 + 3'); SyntaxTest('(1 + 2) * a'); SyntaxTest('(((a + b) * c)'); SyntaxTest('a++3*4'); SyntaxTest('1+2+3+4+5+6+7+8'); END.
unit uBoleto.Impl; interface uses uBoleto.Intf; type TContaBancaria = class(TInterfacedObject, IContaBancaria) strict private FCodigoBanco: UInt16; public function GetCodigoBanco: UInt16; procedure SetCodigoBanco(const pCodigoBanco: UInt16); end; TCedente = class(TInterfacedObject, ICedente) strict private FNome: string; FContaBancaria: IContaBancaria; public constructor Create; function GetNome: string; procedure SetNome(const pNome: string); function GetContaBancaria: IContaBancaria; end; TSacado = class(TInterfacedObject, ISacado) strict private FNome: string; public function GetNome: string; procedure SetNome(const pNome: string); end; TBoleto = class(TInterfacedObject, IBoleto) strict private FCedente: ICedente; FSacado: ISacado; public constructor Create; function GetCedente: ICedente; function GetSacado: ISacado; end; implementation { TContaBancaria } function TContaBancaria.GetCodigoBanco: UInt16; begin Result := FCodigoBanco; end; procedure TContaBancaria.SetCodigoBanco(const pCodigoBanco: UInt16); begin FCodigoBanco := pCodigoBanco; end; { TCedente } constructor TCedente.Create; begin FContaBancaria := TContaBancaria.Create; end; function TCedente.GetContaBancaria: IContaBancaria; begin Result := FContaBancaria; end; function TCedente.GetNome: string; begin Result := FNome; end; procedure TCedente.SetNome(const pNome: string); begin FNome := pNome; end; { TSacado } function TSacado.GetNome: string; begin Result := FNome; end; procedure TSacado.SetNome(const pNome: string); begin FNome := pNome; end; { TBoleto } constructor TBoleto.Create; begin FCedente := TCedente.Create; FSacado := TSacado.Create; end; function TBoleto.GetCedente: ICedente; begin Result := FCedente; end; function TBoleto.GetSacado: ISacado; begin Result := FSacado; end; end.
unit ThStructuredDocument; interface uses Classes, ComCtrls, Graphics; type TThStructuredDocument = class(TStringList) protected function GetSection(const inName: string): TThStructuredDocument; function GetSubDocument(inIndex: Integer): TThStructuredDocument; protected function ShouldPublish(const inSection: string): Boolean; virtual; public destructor Destroy; override; procedure Clear; override; function PublishToString: string; procedure PublishToStrings(inStrings: TStrings); virtual; procedure RichPublish(inRichEdit: TRichEdit; inLevel: Integer = 0); virtual; public property SubDocument[inIndex: Integer]: TThStructuredDocument read GetSubDocument; property Section[const inName: string]: TThStructuredDocument read GetSection; default; end; implementation { TThStructuredDocument } destructor TThStructuredDocument.Destroy; begin Clear; inherited; end; function TThStructuredDocument.GetSubDocument( inIndex: Integer): TThStructuredDocument; begin Result := TThStructuredDocument(Objects[inIndex]); end; procedure TThStructuredDocument.Clear; var i: Integer; begin for i := 0 to Pred(Count) do if Objects[i] <> nil then SubDocument[i].Free; inherited; end; function TThStructuredDocument.GetSection( const inName: string): TThStructuredDocument; var i: Integer; begin i := IndexOf(inName); if (i < 0) then i := AddObject(inName, TThStructuredDocument.Create); Result := SubDocument[i]; end; function TThStructuredDocument.ShouldPublish(const inSection: string): Boolean; begin Result := true; end; procedure TThStructuredDocument.PublishToStrings(inStrings: TStrings); var i: Integer; begin for i := 0 to Pred(Count) do begin if Objects[i] = nil then inStrings.Add(Strings[i]) else begin if ShouldPublish(Strings[i]) then SubDocument[i].PublishToStrings(inStrings); end; end; end; procedure TThStructuredDocument.RichPublish(inRichEdit: TRichEdit; inLevel: Integer); const cN = 5; cColors: array[0..Pred(cN)] of TColor = ( clBlack, clNavy, clMaroon, clFuchsia, clGreen ); var i: Integer; procedure RichEmit; begin with inRichEdit do begin SelStart := MAXINT; SelAttributes.Color := cColors[inLevel mod cN]; //SelAttributes.Style := inStyle; SelText := StringOfChar(' ', inLevel * 2) + Strings[i] + #13#10; end; end; begin for i := 0 to Pred(Count) do if Objects[i] = nil then RichEmit else begin if ShouldPublish(Strings[i]) then SubDocument[i].RichPublish(inRichEdit, inLevel+1); end; end; function TThStructuredDocument.PublishToString: string; var s: TStringList; begin s := TStringList.Create; try PublishToStrings(s); Result := s.Text; finally s.Free; end; end; end.
unit HeaderFooterTemplate; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, uADStanIntf, uADStanOption, uADStanError, uADGUIxIntf, uADPhysIntf, uADStanDef, uADStanPool, uADStanAsync, uADPhysManager, uADStanParam, uADDatSManager, uADDAptIntf, uADDAptManager, Data.DB, uADCompDataSet, uADCompClient, FMX.Layouts, FMX.ListBox, System.Rtti, System.Bindings.Outputs, Fmx.Bind.Editors, Data.Bind.EngExt, Fmx.Bind.DBEngExt, Data.Bind.Components, Data.Bind.DBScope, FMX.Edit, uADCompGUIx, uADGUIxFMXWait, uADPhysIB; type THeaderFooterForm = class(TForm) Header: TToolBar; Footer: TToolBar; HeaderLabel: TLabel; ADConnection1: TADConnection; ADQuery1: TADQuery; ListBox1: TListBox; SearchBox1: TSearchBox; ADQuery1CUST_NO: TIntegerField; ADQuery1CUSTOMER: TStringField; ADQuery1CONTACT_FIRST: TStringField; ADQuery1CONTACT_LAST: TStringField; ADQuery1PHONE_NO: TStringField; ADQuery1ADDRESS_LINE1: TStringField; ADQuery1ADDRESS_LINE2: TStringField; ADQuery1CITY: TStringField; ADQuery1STATE_PROVINCE: TStringField; ADQuery1COUNTRY: TStringField; ADQuery1POSTAL_CODE: TStringField; ADQuery1ON_HOLD: TStringField; BindSourceDB1: TBindSourceDB; BindingsList1: TBindingsList; LinkFillControlToField1: TLinkFillControlToField; Button1: TButton; ADGUIxWaitCursor1: TADGUIxWaitCursor; ADPhysIBDriverLink1: TADPhysIBDriverLink; procedure Button1Click(Sender: TObject); procedure ADConnection1BeforeConnect(Sender: TObject); private { Private declarations } public { Public declarations } end; var HeaderFooterForm: THeaderFooterForm; implementation {$R *.fmx} procedure THeaderFooterForm.ADConnection1BeforeConnect(Sender: TObject); begin //ADConnection1.Params.Values['Database'] := '$(DOC)/EMPLOYEE.GDB' ADConnection1.Params.Values['Database'] := GetHomePath + PathDelim + 'Documents' + PathDelim + 'EMPLOYEE.GDB'; end; procedure THeaderFooterForm.Button1Click(Sender: TObject); begin ADConnection1.Open; ADQuery1.Open; end; end.
{******************************************************************************* Title: T2TiPDV Description: Permite a emissão dos relatórios do Sintegra e SPED Fiscal The MIT License Copyright: Copyright (C) 2012 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: alberteije@gmail.com @author T2Ti.COM @version 1.0 *******************************************************************************} unit UVendasPeriodo; {$mode objfpc}{$H+} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, MaskEdit, ComCtrls, DateUtils, ACBrBase, ACBrEnterTab, UBase; type { TFVendasPeriodo } TFVendasPeriodo = class(TFBase) ACBrEnterTab1: TACBrEnterTab; Image1: TImage; RadioGroup2: TRadioGroup; botaoConfirma: TBitBtn; botaoCancela: TBitBtn; panPeriodo: TPanel; Label1: TLabel; Label2: TLabel; mkeDataIni: TMaskEdit; mkeDataFim: TMaskEdit; PageControl1: TPageControl; PaginaSintegra: TTabSheet; PaginaSped: TTabSheet; Label3: TLabel; Label4: TLabel; Label5: TLabel; ComboBoxConvenio: TComboBox; ComboBoxNaturezaInformacoes: TComboBox; ComboBoxFinalidadeArquivo: TComboBox; Label6: TLabel; ComboBoxVersaoLeiauteSped: TComboBox; Label7: TLabel; ComboBoxFinalidadeArquivoSped: TComboBox; Label8: TLabel; ComboBoxPerfilSped: TComboBox; procedure botaoCancelaClick(Sender: TObject); procedure Confirma; procedure FormActivate(Sender: TObject); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure botaoConfirmaClick(Sender: TObject); procedure RadioGroup2Click(Sender: TObject); procedure mkeDataIniExit(Sender: TObject); procedure mkeDataFimExit(Sender: TObject); private { Private declarations } public { Public declarations } end; var FVendasPeriodo: TFVendasPeriodo; implementation uses UCaixa; {$R *.lfm} procedure TFVendasPeriodo.botaoConfirmaClick(Sender: TObject); begin Confirma; end; procedure TFVendasPeriodo.Confirma; var CodigoConvenio, NaturezaInformacao, FinalidadeArquivo, Versao, Perfil: Integer; begin if RadioGroup2.ItemIndex = 0 then begin if Application.MessageBox('Deseja gerar o arquivo do SINTEGRA (Convenio 57/95)?', 'Pergunta do Sistema', Mb_YesNo + Mb_IconQuestion) = IdYes then begin { 1 - Convênio 57/95 Versão 31/99 Alt. 30/02 2 - Convênio 57/95 Versão 69/02 Alt. 142/02 3 - Convênio 57/95 Alt. 76/03 } CodigoConvenio := StrToInt(Copy(ComboBoxConvenio.Text,1,1)); { 1 - Interestaduais - Somente operações sujeitas ao regime de Substituição Tributária 2 - Interestaduais - Operações com ou sem Substituição Tributária 3 - Totalidade das operações do informante } NaturezaInformacao := StrToInt(Copy(ComboBoxNaturezaInformacoes.Text,1,1)); { 1 - Normal 2 - Retificação total de arquivo: substituição total de informações prestadas pelo contribuinte referentes a este período 3 - Retificação aditiva de arquivo: acréscimo de informação não incluída em arquivos já apresentados 5 - Desfazimento: arquivo de informação referente a operações/prestações não efetivadas . Neste caso, o arquivo deverá conter, além dos registros tipo 10 e tipo 90, apenas os registros referentes as operações/prestações não efetivadas } FinalidadeArquivo := StrToInt(Copy(ComboBoxFinalidadeArquivo.Text,1,1)); //USintegra.GerarArquivoSintegra(mkeDataIni.Text,mkeDataFim.Text, CodigoConvenio, NaturezaInformacao, FinalidadeArquivo); end; end; if RadioGroup2.ItemIndex = 1 then begin if Application.MessageBox('Deseja gerar o arquivo do SPED FISCAL (Ato COTEPE/ICMS 09/08)?', 'Pergunta do Sistema', Mb_YesNo + Mb_IconQuestion) = IdYes then begin Versao := ComboBoxVersaoLeiauteSped.ItemIndex; FinalidadeArquivo := ComboBoxVersaoLeiauteSped.ItemIndex; Perfil := ComboBoxPerfilSped.ItemIndex; //USpedFiscal.GerarArquivoSpedFiscal(mkeDataIni.Text,mkeDataFim.Text, Versao, FinalidadeArquivo, Perfil); end; end; end; procedure TFVendasPeriodo.botaoCancelaClick(Sender: TObject); begin Close; end; procedure TFVendasPeriodo.FormActivate(Sender: TObject); begin Color := StringToColor(Sessao.Configuracao.CorJanelasInternas); mkeDataIni.Text := DateToStr(StartOfTheMonth(Now)); mkeDataFim.Text := DateToStr(EndOfTheMonth(Now)); mkeDataIni.SetFocus; end; procedure TFVendasPeriodo.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin CloseAction := caFree; end; procedure TFVendasPeriodo.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if key = 123 then Confirma; if key = VK_ESCAPE then botaoCancela.Click; end; procedure TFVendasPeriodo.mkeDataFimExit(Sender: TObject); begin if StrToDate(mkeDataIni.Text) > StrToDate(mkeDataFim.Text) then begin Application.MessageBox('Data inicial não pode ser maior que data final!', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); mkeDataFim.setFocus; end; end; procedure TFVendasPeriodo.mkeDataIniExit(Sender: TObject); begin mkeDataFim.Text := DateToStr(EndOfTheMonth(strtodate(mkeDataIni.Text))); end; procedure TFVendasPeriodo.RadioGroup2Click(Sender: TObject); begin if RadioGroup2.ItemIndex = 0 then begin; PageControl1.TabIndex := 0; end else begin PageControl1.TabIndex := 1; end; end; end.
unit SpPeople_FamilyForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DB, FIBDataSet, pFIBDataSet, cxDropDownEdit, cxDBEdit, cxMaskEdit, cxCalendar, cxControls, cxContainer, cxEdit, cxTextEdit, StdCtrls, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, cxLookAndFeelPainters, cxButtons, FIBDatabase, pFIBDatabase, cxCheckBox, ActnList, IBase; type TfFamilyEdit = class(TForm) Label1: TLabel; FIOEdit: TcxTextEdit; Label2: TLabel; BirthDateEdit: TcxDateEdit; RelationsDataSet: TpFIBDataSet; RelationsDataSetID_RELATION: TFIBIntegerField; RelationsDataSetNAME_RELATION: TFIBStringField; RelationsDataSetID_SEX: TFIBIntegerField; RelationsDataSetUNIQUE_REL: TFIBStringField; RelationsDataSource: TDataSource; RelationsComboBox: TcxLookupComboBox; OkBtn: TcxButton; cxButton1: TcxButton; DB: TpFIBDatabase; ReadTransaction: TpFIBTransaction; UseDateChB: TcxCheckBox; ActionList1: TActionList; OkAction: TAction; CancelAction: TAction; procedure RelationsComboBoxPropertiesChange(Sender: TObject); procedure UseDateChBPropertiesChange(Sender: TObject); procedure OkActionExecute(Sender: TObject); procedure CancelActionExecute(Sender: TObject); private { Private declarations } public IdRelation:Integer; FIO:String; BirthDate:TDate; UseDate:Boolean; constructor Create(AOwner:TComponent;ADB_HANDLE:TISC_DB_HANDLE;AIdRelation:Integer=-1;AFIO:String='';ABirthDate:TDateTime=-1); reintroduce; end; implementation {$R *.dfm} constructor TfFamilyEdit.Create(AOwner:TComponent;ADB_HANDLE:TISC_DB_HANDLE;AIdRelation:Integer=-1;AFIO:String='';ABirthDate:TDateTime=-1); begin inherited Create(AOwner); //****************************************************************************** DB.Handle:=ADB_HANDLE; ReadTransaction.Active:=True; RelationsDataSet.Open; IdRelation:=AIdRelation; RelationsComboBox.EditValue:=IdRelation; FIOEdit.Text:=AFIO; if ABirthDate<>-1 then begin BirthDateEdit.Date:=ABirthDate; BirthDateEdit.Enabled:=True; UseDateChB.Checked:=True; end else begin BirthDateEdit.Enabled:=False; UseDateChB.Checked:=False; end; end; procedure TfFamilyEdit.RelationsComboBoxPropertiesChange( Sender: TObject); begin IdRelation:=RelationsComboBox.EditValue; end; procedure TfFamilyEdit.UseDateChBPropertiesChange(Sender: TObject); begin BirthDateEdit.Enabled:=UseDateChB.Checked; end; procedure TfFamilyEdit.OkActionExecute(Sender: TObject); begin if IdRelation=-1 then begin MessageDlg('Не задано необхіднe поле'+''' Відносини ''',mtError,[mbOk],0); RelationsComboBox.SetFocus; Exit; end; if (BirthDateEdit.Text='') and (UseDateChB.Checked) then begin MessageDlg('Не задано необхіднe поле'+''' Дата народження ''',mtError,[mbOk],0); BirthDateEdit.SetFocus; Exit; end; FIO:=FIOEdit.Text; UseDate:=UseDateChB.Checked; if UseDate then BirthDate:=BirthDateEdit.Date; ModalResult:=mrOk; end; procedure TfFamilyEdit.CancelActionExecute(Sender: TObject); begin ModalResult:=mrCancel; end; end.
unit Adapt.WaypointEvent; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ interface uses SysUtils, ZConnection, ZDataset, Cache.Root, Cache.Elements, Adapter.MySQL, Event.Cnst; //------------------------------------------------------------------------------ type //------------------------------------------------------------------------------ //! //------------------------------------------------------------------------------ TEventWaypointMySQL = class(TCacheAdapterMySQL) protected function MakeObjFromReadQuery( const AQuery: TZQuery ): TCacheDataObjectAbstract; override; public constructor Create( const AReadConnection: TZConnection; const AWriteConnection: TZConnection ); procedure Flush( const ACache: TCache ); override; procedure Add( const ACache: TCache; const AObj: TCacheDataObjectAbstract ); override; procedure Change( const ACache: TCache; const AObj: TCacheDataObjectAbstract ); override; end; //------------------------------------------------------------------------------ implementation //------------------------------------------------------------------------------ //! запросы //------------------------------------------------------------------------------ const CSQLInsert = 'INSERT INTO waypointevent' + ' (VehicleID, WaypointID, DT, PlanHit, WorktimeHit, FeasibleHit, GUID, EventDepotGUID)' + ' VALUES (:v_id, :w_id, :dt, :h_plan, :h_worktime, :h_feasible, UUID_TO_BIN(:guid), UUID_TO_BIN(:ed_guid))'; CSQLUpdate = 'UPDATE waypointevent' + ' SET PlanHit = :h_plan, WorktimeHit = :h_worktime, FeasibleHit = :h_feasible' + ' WHERE VehicleID = :v_id' + ' AND WaypointID = :w_id' + ' AND DT = :dt'; CSQLReadBefore = 'SELECT MAX(DT) AS DT' + ' FROM waypointevent' + ' WHERE VehicleID = :v_id' + ' AND WaypointID = :w_id' + ' AND DT < :dt'; CSQLReadAfter = 'SELECT MIN(DT) AS DT' + ' FROM waypointevent' + ' WHERE VehicleID = :v_id' + ' AND WaypointID = :w_id' + ' AND DT > :dt'; CSQLReadRange = 'SELECT' + ' D.Duration, W.VehicleID, W.WaypointID, W.DT, W.PlanHit, W.WorktimeHit, W.FeasibleHit,' + ' BIN_TO_UUID(W.GUID) AS GUID, BIN_TO_UUID(W.EventDepotGUID) AS EventDepotGUID' + ' FROM waypointevent W, event_depot D' + ' WHERE W.EventDepotGUID = D.GUID' + ' AND W.VehicleID = :v_id' + ' AND W.WaypointID = :w_id' + ' AND W.DT >= :dt_from' + ' AND W.DT <= :dt_to'; CSQLDeleteRange = 'DELETE FROM waypointevent' + ' WHERE VehicleID = :v_id' + ' AND WaypointID = :w_id' + ' AND DT = :dt'; //------------------------------------------------------------------------------ // TEventWaypointMySQL //------------------------------------------------------------------------------ constructor TEventWaypointMySQL.Create( const AReadConnection: TZConnection; const AWriteConnection: TZConnection ); begin inherited Create( AReadConnection, AWriteConnection, CSQLInsert, CSQLUpdate, CSQLReadBefore, CSQLReadAfter, CSQLReadRange, CSQLDeleteRange ); end; procedure TEventWaypointMySQL.Flush( const ACache: TCache ); begin // end; procedure TEventWaypointMySQL.Add( const ACache: TCache; const AObj: TCacheDataObjectAbstract ); begin with TEventWaypoint(AObj) do begin FillParamsFromKey(ACache.Key, FInsertQry); FInsertQry.ParamByName(CSQLParamDT).AsDateTime := DTMark; FInsertQry.ParamByName('h_plan').AsInteger := Ord(PlanHit); FInsertQry.ParamByName('h_worktime').AsInteger := Ord(WorktimeHit); FInsertQry.ParamByName('h_feasible').AsInteger := Ord(FeasibleHit); FInsertQry.ParamByName('guid').AsString := GUID; FInsertQry.ParamByName('ed_guid').AsString := DepotGUID; FInsertQry.ExecSQL(); Origin := ooLoaded; Stored := Now(); end; end; procedure TEventWaypointMySQL.Change( const ACache: TCache; const AObj: TCacheDataObjectAbstract ); begin with TEventWaypoint(AObj) do begin FillParamsFromKey(ACache.Key, FUpdateQry); // if (Changed > Stored) then // begin FUpdateQry.ParamByName(CSQLParamDT).AsDateTime := DTMark; FUpdateQry.ParamByName('h_plan').AsInteger := Ord(PlanHit); FUpdateQry.ParamByName('h_worktime').AsInteger := Ord(WorktimeHit); FUpdateQry.ParamByName('h_feasible').AsInteger := Ord(FeasibleHit); FUpdateQry.ExecSQL(); Stored := Now(); // end; end; end; function TEventWaypointMySQL.MakeObjFromReadQuery( const AQuery: TZQuery ): TCacheDataObjectAbstract; begin with AQuery do begin Result := TEventWaypoint.Create( ooLoaded, FieldByName('VehicleID').AsInteger, FieldByName('WaypointID').AsInteger, FieldByName('DT').AsDateTime, FieldByName('Duration').AsFloat, FieldByName('PlanHit').AsInteger <> 0, FieldByName('WorktimeHit').AsInteger <> 0, FieldByName('FeasibleHit').AsInteger <> 0, '{' + FieldByName('GUID').AsString + '}', '{' + FieldByName('EventDepotGUID').AsString + '}' ); end; end; end.
unit Person; interface uses mORMot, SynCommons; type TSQLCity = class(TSQLRecord) private FName: RawUTF8; FState: RawUTF8; published property Name: RawUTF8 read FName write FName; property State: RawUTF8 read FState write FState; end; TSQLPerson = class(TSQLRecord) private fFirstname, fSurname: RawUTF8; FCity: TSQLCity; published property FirstName: RawUTF8 read fFirstname write fFirstname; property Surname: RawUTF8 read fSurname write fSurname; property City: TSQLCity read FCity write FCity; end; function CreatePersonModel: TSQLModel; implementation function CreatePersonModel: TSQLModel; begin Result := TSQLModel.Create([TSQLCity,TSQLPerson]); end; end.
unit Utilities; interface uses Windows; function GetLargeFileIcon(const fname: String): hIcon; function GetFileType(const fName: String): String; function GetSystemTemp: string; function MakeAttributeString(attr: Word): String; function MakeSizeString(size: Integer): String; function MoveDirectory(const source, destination: String): Boolean; // deletes total tree inclusive files and subfolders !! function DeleteDirectory(FolderName: String): Boolean; implementation uses SysUtils, ShellAPI, Graphics; function GetLargeFileIcon(const fname: String): hIcon; var info: SHFILEINFO; Flags: Cardinal; begin Flags := (SHGFI_ICON or SHGFI_LARGEICON or SHGFI_USEFILEATTRIBUTES); SHGetFileInfo(PChar(fName), FILE_ATTRIBUTE_NORMAL, info, 0, Flags); Result := info.hIcon; end; function GetFileType(const fName: String): String; var sfi: TSHFileInfo; begin SHGetFileInfo(PChar(fName), FILE_ATTRIBUTE_NORMAL, sfi, SizeOf(TSHFileInfo), SHGFI_TYPENAME or SHGFI_USEFILEATTRIBUTES); Result := sfi.szTypeName; if Result = '' then Result := AnsiUpperCase(fName) + ' File'; end; function GetSystemTemp: string; var buf: array[0..255] of Char; len: Integer; begin len := Windows.GetTempPath(255, buf); if buf[len-1] <> '\' then Result := Result + '\' else Result := buf; end; function MakeAttributeString(attr: Word): String; begin Result := ''; if faArchive and attr <> 0 then Result := Result + 'A'; if faHidden and attr <> 0 then Result := Result + 'H'; if faReadOnly and attr <> 0 then Result := Result + 'R'; if faSysFile and attr <> 0 then Result := Result + 'S'; end; function MakeSizeString(size: Integer): String; begin if size < 1000 then Result := IntToStr(size) + ' bytes' else if size < 1000000 then Result := IntToStr(size DIV 1024) + ' KB' else Result := IntToStr(size DIV 1024 DIV 1024) + ' ' + IntToStr(size DIV 1024) + ' KB' end; // directory functions from CodeBank by Mertkan Yildirimli - www.mertkan.com function DirOperations( Action : String; {COPY, DELETE, MOVE, RENAME} RenameOnCollision : Boolean; {Renames if directory exists} NoConfirmation : Boolean; {Responds "Yes to All" to any dialogs} Silent : Boolean; {No progress dialog is shown} ShowProgress : Boolean; {displays progress dialog but no file names} FromDir : String; {From directory} ToDir : String {To directory} ): Boolean; var SHFileOpStruct : TSHFileOpStruct; FromBuf, ToBuf: Array [0..255] of Char; begin try if not DirectoryExists(FromDir) then begin Result := False; Exit; end; Fillchar(SHFileOpStruct, Sizeof(SHFileOpStruct), 0 ); FillChar(FromBuf, Sizeof(FromBuf), 0 ); FillChar(ToBuf, Sizeof(ToBuf), 0 ); StrPCopy(FromBuf, FromDir); StrPCopy(ToBuf, ToDir); with SHFileOpStruct do begin Wnd := 0; if UpperCase(Action) = 'COPY' then wFunc := FO_COPY; if UpperCase(Action) = 'DELETE' then wFunc := FO_DELETE; if UpperCase(Action) = 'MOVE' then wFunc := FO_MOVE; if UpperCase(Action) = 'RENAME' then wFunc := FO_RENAME; pFrom := @FromBuf; pTo := @ToBuf; fFlags := FOF_ALLOWUNDO; if RenameOnCollision then fFlags := fFlags or FOF_RENAMEONCOLLISION; if NoConfirmation then fFlags := fFlags or FOF_NOCONFIRMATION; if Silent then fFlags := fFlags or FOF_SILENT; if ShowProgress then fFlags := fFlags or FOF_SIMPLEPROGRESS; end; Result := (SHFileOperation(SHFileOpStruct) = 0); except Result := False; end; end; function DeleteDirectory(FolderName: String): Boolean; begin FolderName := ExcludeTrailingPathDelimiter(FolderName); Result := DirOperations( 'DELETE', //Action : String; //COPY, DELETE, MOVE, RENAME False, //RenameOnCollision : Boolean; //Renames if directory exists True, //NoConfirmation : Boolean; //Responds "Yes to All" to any dialogs True, //Silent : Boolean; //No progress dialog is shown False, //ShowProgress : Boolean; //displays progress dialog but no file names FolderName, //FromDir : String; //From directory '' //ToDir : String //To directory ); end; function MoveDirectory(const source, destination: String): Boolean; begin Result := DirOperations( 'MOVE', {Action : String;} {COPY, DELETE, MOVE, RENAME} False, {RenameOnCollision : Boolean;} {Renames if directory exists} True, {NoConfirmation : Boolean;} {Responds "Yes to All" to any dialogs} True, {Silent : Boolean;} {No progress dialog is shown} False, {ShowProgress : Boolean;} {displays progress dialog but no file names} source, {FromDir : String;} {From directory} destination {ToDir : String} {To directory} ); end; end.
//--------------------------------------------------------------------------- // This software is Copyright (c) 2012 Alan Fletcher. // You may use thius software in any way you want and contribute back to the // author with any improvements you may have made to it. // You are also allowed to use this software or part of it for any purposes as long // as you retain this message and credit the author for it's contribuition. //--------------------------------------------------------------------------- unit fMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Rtti, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Media, FMX.Layouts, Data.Bind.EngExt, Fmx.Bind.DBEngExt, System.Bindings.Outputs, Fmx.Bind.Editors, Data.Bind.Components, fBase; type TForm1 = class(TfrmBase) MediaPlayer1: TMediaPlayer; OpenDialog1: TOpenDialog; btnPlay1: TButton; tbVolume1: TTrackBar; pnlPlayer1: TPanel; btnLoad1: TButton; GridLayout1: TGridLayout; lblStatus1: TLabel; pnlPlayer2: TPanel; tbVolume2: TTrackBar; btnPlay2: TButton; btnLoad2: TButton; lblStatus2: TLabel; MediaPlayer2: TMediaPlayer; pnlPlayer3: TPanel; tbVolume3: TTrackBar; btnPlay3: TButton; btnLoad3: TButton; lblStatus3: TLabel; MediaPlayer3: TMediaPlayer; pnlPlayer4: TPanel; tbVolume4: TTrackBar; btnPlay4: TButton; btnLoad4: TButton; lblStatus4: TLabel; MediaPlayer4: TMediaPlayer; pnlPlayer5: TPanel; tbVolume5: TTrackBar; btnPlay5: TButton; Button11: TButton; lblStatus5: TLabel; MediaPlayer5: TMediaPlayer; pnlPlayer6: TPanel; tbVolume6: TTrackBar; btnPlay6: TButton; btnLoad6: TButton; lblStatus6: TLabel; MediaPlayer6: TMediaPlayer; pnlPlayer7: TPanel; tbVolume7: TTrackBar; btnPlay7: TButton; btnLoad7: TButton; lblStatus7: TLabel; MediaPlayer7: TMediaPlayer; pnlPlayer8: TPanel; tbVolume8: TTrackBar; btnPlay8: TButton; btnLoad8: TButton; lblStatus8: TLabel; MediaPlayer8: TMediaPlayer; lblVolumeLevel1: TLabel; lblVolumeLevel2: TLabel; lblVolumeLevel3: TLabel; lblVolumeLevel4: TLabel; lblVolumeLevel5: TLabel; lblVolumeLevel6: TLabel; lblVolumeLevel7: TLabel; lblVolumeLevel8: TLabel; BindingsList1: TBindingsList; VolumeLevel1: TBindExprItems; VolumeLevel2: TBindExprItems; VolumeLevel3: TBindExprItems; VolumeLevel4: TBindExprItems; VolumeLevel5: TBindExprItems; VolumeLevel6: TBindExprItems; VolumeLevel7: TBindExprItems; VolumeLevel8: TBindExprItems; MediaPlayerStatus1: TBindExprItems; MediaPlayerStatus2: TBindExprItems; MediaPlayerStatus3: TBindExprItems; MediaPlayerStatus4: TBindExprItems; MediaPlayerStatus5: TBindExprItems; MediaPlayerStatus6: TBindExprItems; MediaPlayerStatus7: TBindExprItems; MediaPlayerStatus8: TBindExprItems; Timer1: TTimer; procedure HandleLoadMedia(Sender: TObject); procedure btnPlayClick(Sender: TObject); procedure HandleVolumeChangesByTrackbar(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } end; var Form1: TForm1; FNotifying: Integer; const // Component name prefix - used to find components on the forms MEDIA_PLAYER = 'MediaPlayer'; PLAY_BUTTON = 'btnPlay'; MEDIA_PLAYER_CONTROL ='MediaPlayerControl'; implementation {$R *.fmx} uses MediaPlayer.StateConversion, fScreens; //------------------------------------------------------------------------------------------------------------ // Loads media into the media player procedure TForm1.HandleLoadMedia(Sender: TObject); var MediaPlayer: TComponent; PlayButton: TComponent; begin // Only supported files OpenDialog1.Filter := TMediaCodecManager.GetFilterString; if (OpenDialog1.Execute) then begin // Tries to find the proper media player to load media onto MediaPlayer := GetObjectByName(MEDIA_PLAYER, (Sender as TComponent).Tag); // Makes sure it found a media player component if Assigned(MediaPlayer) and (MediaPlayer is TMediaPlayer) then begin // Attempts to load media (MediaPlayer as TMediaPlayer).Clear; (MediaPlayer as TMediaPlayer).FileName := OpenDialog1.FileName; if (MediaPlayer as TMediaPlayer).State = TMediaState.Stopped then begin // If media is recognized as valid then it enables the play button PlayButton := GetObjectByName(PLAY_BUTTON, (Sender as TComponent).Tag); if Assigned(PlayButton) and (PlayButton is TButton) then begin (PlayButton as TButton).Enabled := True; end; end; end; end; end; //------------------------------------------------------------------------------------------------------------ // Handles play button procedure TForm1.btnPlayClick(Sender: TObject); var MediaPlayer: TComponent; begin // Tries to find the proper media player MediaPlayer := GetObjectByName(MEDIA_PLAYER, (Sender as TComponent).Tag); // Makes sure it found a media player component if Assigned(MediaPlayer) and (MediaPlayer is TMediaPlayer) then begin // Does it have a valid media attached? if (MediaPlayer as TMediaPlayer).State <> TMediaState.Unavailable then // Figures if it needs to start or stop playback if (MediaPlayer as TMediaPlayer).State = TMediaState.Stopped then (MediaPlayer as TMediaPlayer).Play else (MediaPlayer as TMediaPlayer).Stop; end; end; //------------------------------------------------------------------------------------------------------------ procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin // removes screens form if Assigned(fScreenWall) then fScreenWall.Release; end; //------------------------------------------------------------------------------------------------------------ procedure TForm1.FormCreate(Sender: TObject); var MediaPlayer, MediaPlayerControl: TComponent; I: Integer; begin // Creates screens form fScreenWall := TfScreenWall.Create(nil); // Assigns all playes to all media controls for I := 1 to 8 do begin MediaPlayer := GetObjectByName(MEDIA_PLAYER, I); if Assigned(MediaPlayer) and (MediaPlayer is TMediaPlayer) then begin MediaPlayerControl := fScreenWall.GetObjectByName(MEDIA_PLAYER_CONTROL, I); if Assigned(MediaPlayerControl) and (MediaPlayerControl is TMediaPlayerControl) then begin (MediaPlayerControl as TMediaPlayerControl).MediaPlayer := (MediaPlayer as TMediaPlayer); end; end; end; // Shows the form fScreenWall.Show; end; //------------------------------------------------------------------------------------------------------------ // Handles volume changes procedure TForm1.HandleVolumeChangesByTrackbar(Sender: TObject); var MediaPlayer: TComponent; begin // Volume Commands can only come from TTrackbar if Sender is TTrackBar then begin MediaPlayer := GetObjectByName(MEDIA_PLAYER, (Sender as TComponent).Tag); if Assigned(MediaPlayer) and (MediaPlayer is TMediaPlayer) then begin (MediaPlayer as TMediaPlayer).Volume := (Sender as TTrackBar).Value/100; // Some controls send notifications when setting properties, // like TTrackBar if FNotifying = 0 then begin Inc(FNotifying); // Send notification to cause expression re-evaluation of dependent expressions try BindingsList1.Notify(Sender, ''); finally Dec(FNotifying); end; end; end; end; end; //------------------------------------------------------------------------------------------------------------ // Maintains labels in synch with media players procedure TForm1.Timer1Timer(Sender: TObject); var I: Integer; MediaPlayer: TComponent; begin for I := 1 to 8 do begin MediaPlayer := GetObjectByName(MEDIA_PLAYER, I); if Assigned(MediaPlayer) and (MediaPlayer is TMediaPlayer) then begin // Can it rewind the media? with (MediaPlayer as TMediaPlayer) do if State = TMediaState.Playing then if (Duration = CurrentTime) then begin Stop; CurrentTime := 0; end; // Send notification to cause expression re-evaluation of dependent expressions BindingsList1.Notify(MediaPlayer, ''); end; end; end; end.
//--------------------------------------------------------------------------- // Copyright 2012 The Open Source Electronic Health Record Agent // // 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 UnitTest; interface uses WinTypes, WinProcs, Classes, Graphics, Forms, Controls, Buttons, StdCtrls, ExtCtrls, Dialogs, SysUtils, MFunStr, XWBut1, TestFrameWork, TextTestRunner; var index: System.Integer; namearray: Array of string; suitearray: Array of ITestSuite; testfound: bool; procedure addSuite(suite: ITestSuite); procedure runTests(name: string); implementation procedure addSuite(suite: ITestSuite); begin TestFrameWork.RegisterTest(suite); namearray[index] := suite.Name; suitearray[index] := suite; index := index+1; end; procedure runTests(name: string); var i : integer; begin testfound := false; for i := 0 to index-1 do if namearray[i] = name then begin TextTestRunner.RunTest(suitearray[i],rxbHaltOnFailures); testfound := true; end; if Not testfound then begin WriteLn(Output, 'No registered tests match the supplied name: '+ name); end; end; begin index:=0; SetLength(namearray,20); SetLength(suitearray,20); end.
unit UTurret; interface uses W3System, UBullet, UPlayer, UPlat, UGlobalsNoUserTypes; type SidePlacedOn = (Left, Right, Top, Bottom); const WIDTH = TURRET_WIDTH; HEIGHT = TURRET_HEIGHT; MAXTIMESSHOT = 2; MINTIMETILLSHOOT = 20; type TTurret = class(TObject) X, Y : float; //The x and y position of the turret GravSpeed : float; //The speed it falls at after it has been shot down Angle : float; //The angle it is aiming it Placement : SidePlacedOn; //What side it will be placed on ShotsTillDead : integer; //How many times it can be shot till it dies TimeTillShoot : integer; //How many frames till it can shoot again isRand : boolean; //If the platform it is on is random platform PlatID : integer; //The ID number of the platform constructor Create(newX, newY, newAngle : float; Side : SidePlacedOn); procedure Update(player : TPlayer; Bullets : array of TBullet; Ais : array of TPlayer; FixedPlats, RandPlats : array of TPlat); procedure BulletHit(Bullet : TBullet); //Changes values on the bullet if it the turret procedure SetOnPlatform(Plat : TPlat); //Puts the Turret on the correct platforn in the right place procedure HasBeenHit(Bullets : array of TBullet); //Checks if a bullet has hit it function ShouldShoot(player : TPlayer; Ais : array of TPlayer; FixedPlats, RandPlats : array of TPlat; TargetAngle : float) : boolean; //Checks if it should shoot (if it would hit the player) function getTargetAngle(player : TPlayer) : float; //Gets the target angle needed end; implementation constructor TTurret.Create(newX, newY, newAngle : float; Side : SidePlacedOn); begin X := newX; Y := newY; GravSpeed := -4; //So that when it is shot down, it jumps up slightly then falls Angle := newAngle; Placement := Side; ShotsTillDead := MAXTIMESSHOT; TimeTillShoot := 0; end; procedure TTurret.Update(player : TPlayer; Bullets : array of TBullet; Ais : array of TPlayer; FixedPlats, RandPlats : array of TPlat); var //This is the target angle, that will hit the Player TargAngle : float; begin if (ShotsTillDead <= 0) and (Y <= maxY + 2500) then //If the turret is dead: begin Y += GravSpeed; //Make the Y go down, so it falls GravSpeed += 1; //Increase the gravity speed end else if ShotsTillDead > 0 then begin Angle := round(Angle) mod 360; //Uses the procedure to get the target angle TargAngle := getTargetAngle(player); if TargAngle < 0 then TargAngle := 360 - TargAngle; TargAngle := round(TargAngle) mod 360; //Change the angle so it gets closer to the target angle gradually if Placement = Bottom then //It will bug out as it skips from 0 deg to 359 degrees //so this is a separate bit of code that will inverse //the angles and act upon those, so no bugging out begin var ReverseTargAngle : float; var ReverseAngle : float; //Reverse the Target Angle if TargAngle >= 180 then ReverseTargAngle := 270 - (TargAngle - 270) else ReverseTargAngle := 90 + (90 - TargAngle); //Reverse the Angle if Angle >= 180 then ReverseAngle := 270 - (Angle - 270) else ReverseAngle := 90 + (90 - Angle); //Adjust the angle of the turret if ReverseTargAngle > ReverseAngle then begin if ReverseTargAngle - ReverseAngle < 1.5 then //This is so that it slowly moves round //rather than just jump to the correct angle Angle := TargAngle else Angle -= 2; end else begin if ReverseAngle - ReverseTargAngle < 1.5 then //This is so that it slowly moves round //rather than just jump to the correct angle Angle := TargAngle else Angle += 1.5; end; end //Adjust the angle of the turret else if TargAngle > Angle then begin if TargAngle - Angle < 1.5 then //This is so that it slowly moves round //rather than just jump to the correct angle Angle := TargAngle else Angle += 1.5; end else begin if Angle - TargAngle < 1.5 then //This is so that it slowly moves round //rather than just jump to the correct angle Angle := TargAngle else Angle -= 2; end; //If it is trying to move too far for its reach, set it to its maximum/minimum //angle for its placement Case Placement of Left : begin if Angle < 0 then Angle := 0; if Angle > 180 then Angle := 180; end; Right : begin if Angle > 360 then Angle := 360; if Angle < 180 then Angle := 180; end; Top : begin if Angle > 270 then Angle := 270; if Angle < 90 then Angle := 90; end; Bottom : begin if ((Angle < 270) and (Angle >= 180)) or (Angle < -90) then //In case the angle doesn't skip to 360 when it becomes negative Angle := 270; if (Angle > 90) and (Angle < 180) then Angle := 90; end; end; if (ShouldShoot(player, Ais, FixedPlats, RandPlats, TargAngle)) and (TimeTillShoot < 0) then begin var i := -1; repeat begin i += 1; end; until (Bullets[i].Shot = false) or (i >= High(Bullets)); if i >= High(Bullets) then i := High(Bullets) + 1; if Angle >= 180 then begin Bullets[i] := UBullet.TBullet.create(true, X + WIDTH/2 - UBullet.HEIGHT - 1, Y + HEIGHT/2, 15, Angle) end else Bullets[i] := UBullet.TBullet.create(false, X + WIDTH/2 - UBullet.HEIGHT - 1, Y + HEIGHT/2, 15, Angle); TimeTillShoot := MINTIMETILLSHOOT + 1; Bullets[i].update(maxX,player,Ais,FixedPlats,RandPlats); //Update the bullet so it moves and the turret has not shot itself Bullets[i].update(maxX,player,Ais,FixedPlats,RandPlats); Bullets[i].update(maxX,player,Ais,FixedPlats,RandPlats); end; dec(TimeTillShoot); //Decrease the time till shoot so it can shoot again after it reaches 0 //Checks if its been hit by a bullet. Done in this unit as due to the referencing, the bullet unit //can not as it will cause a circular unit reference HasBeenHit(Bullets); //Puts the turret on the platform correctly if isRand then SetOnPlatform(RandPlats[PlatID]) else SetOnPlatform(FixedPlats[PlatID]); end; end; procedure TTurret.SetOnPlatform(Plat : TPlat); begin if Placement = Bottom then //Put the turret on the centre top of the platform begin X := Plat.X + (Plat.Width / 2) - (WIDTH / 2); Y := Plat.Y - HEIGHT; end else if Placement = Top then //Put the turret on the centre bottom of the platform begin X := Plat.X + (Plat.Width / 2) - (WIDTH / 2); Y := Plat.Y + Plat.Height; end else if Placement = Left then //Put the turret on the centre right of the platform begin X := Plat.X + Plat.Width + 5; Y := Plat.Y + (Plat.Height / 2) - (HEIGHT / 2); end else if Placement = Right then //Put the turret on the centre left of the platform begin X := Plat.X - WIDTH - 5; Y := Plat.Y + (Plat.Height / 2) - (HEIGHT / 2); end; end; procedure TTurret.HasBeenHit(Bullets : array of TBullet); begin for var i := 0 to High(Bullets) do //iterate over all the bullets begin var BulletBounds := Bullets[i].BulletBounds(); //Gets the bullet's bounds //Checks the X collision if (BulletBounds[0][1] >= X) and (BulletBounds[0][0] <= X + WIDTH) then begin //Checks the Y collision if (BulletBounds[1][0] <= Y + HEIGHT) and (BulletBounds[1][1] >= Y) then //If both collided then it has been hit so needs to run the appropriate procedure BulletHit(Bullets[i]); end; end; end; function TTurret.ShouldShoot(player : TPlayer; Ais : array of TPlayer; FixedPlats, RandPlats : array of TPlat; TargetAngle : float) : boolean; var Bullet : TBullet; //This will be a test bullet to see if it hits begin if (Angle - TargetAngle <= 2) and (Angle - TargetAngle >= -2) then //If the angle is 2 degrees off the target //angle it will run code. This makes it more efficient //as it is not running the code unnecessarily begin //Spawns the test bullet how the turret usually would if Angle >= 180 then Bullet := TBullet.create(true, X + WIDTH/2 - UBullet.HEIGHT - 1, Y + HEIGHT/2, 15, Angle) else Bullet := TBullet.create(false, X + WIDTH/2 - UBullet.HEIGHT - 1, Y + HEIGHT/2, 15, Angle); repeat //Keep running the code until it has recieved a true result, or has exited //with false due to it hitting the wrong thing begin Bullet.Move(); //Moved the test bullet for var i := 0 to High(Ais) do //Iterate over the Ai units begin if Bullet.HitPlayer(Ais[i]) then //If the bullet hit the selected Ai unit Exit(true); //Exit with true as it would be hitting a target of some sort end; for var i := 0 to High(FixedPlats) do //Iterate over the fixed platforms begin if Bullet.HitPlat(FixedPlats[i]) then //If the test bullet has hit the selected fixed platform Exit(false); //Then it hit something unwanted so exit with false end; for var i := 0 to High(RandPlats) do //Iterate over the random platforms begin if Bullet.HitPlat(RandPlats[i]) then //If the test bullet has hit the selected random platform Exit(false); //Then it hit something unwanted so exit with false end; if (Bullet.X > maxX) or (Bullet.Y > maxY) or (Bullet.X < 0) or (Bullet.Y < 0) then //If the test bullet goes off screen Exit(false); end until (Bullet.HitPlayer(player)); Exit(true); end; Exit(false); end; procedure TTurret.BulletHit(Bullet : TBullet); begin if Bullet.FramesLeft = 3 then //If the bullet hasnt hit anything begin dec(ShotsTillDead); //record it has hit the turret dec(Bullet.FramesLeft); //and make the bullet recognize it has hit something end; end; function TTurret.getTargetAngle(player : TPlayer) : float; var DifferenceX, DifferenceY : float; //The difference in X and Y between the turret //and player, making it easy to use in the trigonometry begin DifferenceX := (player.X + (UPlayer.PLAYERHEAD / 2)) - X; DifferenceY := (player.Y + (UPlayer.PLAYERHEIGHT / 2)) - Y; if (DifferenceX = 0) and (DifferenceY = 0) then //If the player is on the turret Exit(0) else if (DifferenceX = 0) and (DifferenceY < 0) then //If the player is above the turret Exit(0) else if (DifferenceX = 0) and (DifferenceY > 0) then //If the player is under the turret Exit(180) else if (DifferenceX > 0) and (DifferenceY = 0) then //If the player is to the right of the turret Exit(90) else if (DifferenceX < 0) and (DifferenceY = 0) then //If the player is to the left of the turret Exit(270) //The trigonmetry below works out the angle in radians, throughout the program //we have been using degrees so at the end of each equation we need // / (Pi / 180) to convert it from radians to degrees else if (DifferenceX > 0) and (DifferenceY < 0) then //Angles 0 to 90 begin if DifferenceX >= DifferenceY * -1 then //Angles 45 to 90 //Uses the angle from the 90 degrees line (right) so it is Y / X //and needs the 90 - (ANGLE) to make it correct for this quadrant (upper right) //The DifferenceY is negative so needs the * -1 to make it positive so it works properly Exit(90 - (Tanh((DifferenceY * -1) / DifferenceX) / (Pi / 180))) else //Angles 0 to 44 //Uses the angle from the 0 degrees line (up) so is the X / Y Exit(Tanh(DifferenceX / (DifferenceY * -1)) / (Pi / 180)); end else if (DifferenceX > 0) and (DifferenceY > 0) then //Angles 90 to 180 begin if DifferenceX >= DifferenceY then //Angles 90 to 135 //Uses the angle from the 90 degrees line (right) so it is Y / X //and needs the 90 + (ANGLE) to make it correct for this quadrant (lower right) Exit(90 + (Tanh(DifferenceY / DifferenceX) / (Pi / 180))) else //Angles 136 to 180 //Uses the angle from the 180 degrees line (down) so it is X / Y //and needs to 180 - (ANGLE) to make it correct for this quadrant (lower right) Exit(180 - (Tanh(DifferenceX / DifferenceY) / (Pi / 180))); end else if (DifferenceX < 0) and (DifferenceY < 0) then //Angles 270 to 360 begin if DifferenceX <= DifferenceY then //Angles 270 to 315 //Uses the angle from the 270 degrees line (left) so it is Y / X //and needs the 270 + (ANGLE) to make it correct for the quadrant (upper left) //both are negative so they both need * -1 to make them positive so it works properly Exit(270 + (Tanh((DifferenceY * -1) / (DifferenceX * -1)) / (Pi / 180))) else //Angles 316 to 360 //Uses the angle from the 360 degrees line (up) so it is X / Y //and needs the 360 - (ANGLE) to make it correct for the quadrant (upper left) //both are negative so they both need * -1 to make them positive so it works properly Exit(360 - (Tanh((DifferenceX * -1) / (DifferenceY * -1)) / (Pi / 180))); end else if (DifferenceX < 0) and (DifferenceY > 0) then //Angles 180 to 270 begin if DifferenceX * -1 >= DifferenceY then //Angles 225 to 270 //Uses the angle from the 270 degrees line (left) so it is Y / X //and needs the 270 - (ANGLE) to make it correct for the quadrant (lower left) //the X is negative so it needs the * -1 to make it positive so it works properly Exit(270 - (Tanh(DifferenceY / (DifferenceX * -1)) / (Pi / 180))) else //Angles 224 to 180 //Uses the angle from the 180 degrees line (down) so it is X / Y //and needs the 180 + (ANGLE) to make it correct for the quadrant (lower left) //the X is negative so it needs the * -1 to make it positive so it works properly Exit(180 + (Tanh((DifferenceX * -1) / DifferenceY) / (Pi / 180))); end; end; end.
// файл figure.pas unit figure; interface uses board; //------------------------------------ // класс Шахматная фигура //------------------------------------ Type Tfigure = class protected ID : Tid; // идентификатор фигуры; board : Tboard; // используется board; function can_move( // правильность хода; to_position: Tposition ): Boolean; virtual; abstract; public procedure move ( to_position: Tposition); constructor Init ( ident : Tid; chessBoard : Tboard ); destructor delete; end;
{* ***** BEGIN LICENSE BLOCK ***** Copyright 2009, 2010 Sean B. Durkin This file is part of TurboPower LockBox 3. TurboPower LockBox 3 is free software being offered under a dual licensing scheme: LGPL3 or MPL1.1. The contents of this file are subject to the Mozilla Public License (MPL) 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/ Alternatively, you may redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. You should have received a copy of the Lesser GNU General Public License along with TurboPower LockBox 3. If not, see <http://www.gnu.org/licenses/>. TurboPower LockBox 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. In relation to LGPL, see the GNU Lesser General Public License for more details. In relation to MPL, see the MPL License for the specific language governing rights and limitations under the License. The Initial Developer of the Original Code for TurboPower LockBox version 2 and earlier was TurboPower Software. * ***** END LICENSE BLOCK ***** *} unit uTPLb_Asymetric; interface uses Classes, uTPLb_StreamCipher, uTPLb_CodecIntf; type TKeyStoragePart = (partPublic, partPrivate); TKeyStoragePartSet = set of TKeyStoragePart; TAsymtricKeyPart = class( TObject) protected function NominalKeyBitLength: cardinal; virtual; abstract; public procedure SaveToStream ( Store: TStream); virtual; abstract; procedure LoadFromStream( Store: TStream); virtual; abstract; function isEmpty: boolean; virtual; abstract; procedure Burn; virtual; abstract; end; TAsymetricKeyPair = class( TSymetricKey) public FPublicPart : TAsymtricKeyPart; FPrivatePart: TAsymtricKeyPart; constructor CreateEmpty; virtual; abstract; destructor Destroy; override; function HasParts: TKeyStoragePartSet; virtual; procedure SaveToStream( Stream: TStream); override; procedure StoreToStream( Store: TStream; Parts: TKeyStoragePartSet); virtual; function Can_StoreToStream( Parts: TKeyStoragePartSet): boolean; virtual; procedure LoadFromStream( Store: TStream; Parts: TKeyStoragePartSet); virtual; abstract; function NominalKeyBitLength: cardinal; procedure Burn; override; function Clone: TAsymetricKeyPair; virtual; end; TAsymetricKeyPairClass = class of TAsymetricKeyPair; TAsymetricEncDec = class( TInterfacedObject) protected FBytesProcessed: uint64; FSymetricCodec: ICodec; FSymetricCodecObj: TObject; constructor Create; virtual; procedure Reset; virtual; public destructor Destroy; override; end; TAsymetricEncryptor = class( TAsymetricEncDec, IStreamEncryptor) protected FPublicKey: TAsymtricKeyPart; // Non-owned. FCipherText: TStream; // Non-owned. constructor Start_Encrypt( PublicKey1: TAsymtricKeyPart; CipherText1: TStream); virtual; procedure Encrypt( const Plaintext: TStream); virtual; procedure End_Encrypt; virtual; public function GenerateSymetricKey: TSymetricKey; virtual; abstract; function VerifySignature( Document: TStream; // FCipherText is the signature to be verified. ProgressSender: TObject; ProgressEvent: TOnEncDecProgress; var wasAborted: boolean): boolean; virtual; abstract; end; TAsymetricEncryptorClass = class of TAsymetricEncryptor; TAsymetricDecryptor = class( TAsymetricEncDec, IStreamDecryptor) protected FPrivateKey: TAsymtricKeyPart; // Non-owned. FPlainText: TStream; // Non-owned. constructor Start_Decrypt( PrivateKey1: TAsymtricKeyPart; PlainText1: TStream); virtual; procedure Decrypt( const Ciphertext: TStream); virtual; procedure End_Decrypt; virtual; public function LoadSymetricKey( Ciphertext: TStream): TSymetricKey; virtual; abstract; procedure Sign( // FPlaintext is the document to be signed. Signature: TStream; ProgressSender: TObject; ProgressEvent: TOnEncDecProgress; var wasAborted: boolean); virtual; abstract; end; TAsymetricDecryptorClass = class of TAsymetricDecryptor; IAsymetric_Engine = interface( IStreamCipher) ['{F6B035A8-2829-4F43-B95C-14C77A22B379}'] procedure GenerateAsymetricKeyPair( KeySizeInBits: cardinal; ProgressSender: TObject; ProgressEvent: TGenerateAsymetricKeyPairProgress; var KeyPair: TAsymetricKeyPair; var wasAborted: boolean); procedure Sign( Document, Signature: TStream; PrivatePart: TAsymtricKeyPart; ProgressSender: TObject; ProgressEvent: TOnEncDecProgress; var wasAborted: boolean); function VerifySignature( Document, Signature: TStream; PublicPart: TAsymtricKeyPart; ProgressSender: TObject; ProgressEvent: TOnEncDecProgress; var wasAborted: boolean): boolean; function CreateFromStream( Store: TStream; Parts: TKeyStoragePartSet): TAsymetricKeyPair; end; ICodec_WithAsymetricSupport = interface( ICodec) ['{76B67794-CB5A-41BA-B519-9250FDC592C6}'] function Asymetric_Engine: IAsymetric_Engine; end; TAsymetric_Engine = class( TInterfacedObject, IStreamCipher, ICryptoGraphicAlgorithm, IAsymetric_Engine) protected // ICryptoGraphicAlgorithm function DisplayName: string; virtual; abstract; function ProgId: string; virtual; abstract; function Features: TAlgorithmicFeatureSet; virtual; function DefinitionURL: string; virtual; abstract; function WikipediaReference: string; virtual; abstract; // IStreamCipher = interface( ) function GenerateKey( Seed: TStream): TSymetricKey; function LoadKeyFromStream( Store: TStream): TSymetricKey; virtual; abstract; function SeedByteSize: integer; // Size that the input of the GenerateKey must be. function Parameterize( const Params: IInterface): IStreamCipher; function Start_Encrypt( Key: TSymetricKey; CipherText: TStream): IStreamEncryptor; virtual; function Start_Decrypt( Key: TSymetricKey; PlainText : TStream): IStreamDecryptor; virtual; function AsymetricKeyPairClass: TAsymetricKeyPairClass; virtual; abstract; function EncClass: TAsymetricEncryptorClass; virtual; abstract; function DecClass: TAsymetricDecryptorClass; virtual; abstract; public procedure GenerateAsymetricKeyPair( KeySizeInBits: cardinal; ProgressSender: TObject; ProgressEvent: TGenerateAsymetricKeyPairProgress; var KeyPair: TAsymetricKeyPair; var wasAborted: boolean); virtual; abstract; procedure Sign( Document, Signature: TStream; PrivatePart: TAsymtricKeyPart; ProgressSender: TObject; ProgressEvent: TOnEncDecProgress; var wasAborted: boolean); virtual; function VerifySignature( Document, Signature: TStream; PublicPart: TAsymtricKeyPart; ProgressSender: TObject; ProgressEvent: TOnEncDecProgress; var wasAborted: boolean): boolean; virtual; function CreateFromStream( Store: TStream; Parts: TKeyStoragePartSet): TAsymetricKeyPair; virtual; abstract; end; implementation uses SysUtils, uTPLb_StreamToBlock, uTPLb_AES, uTPLb_CBC, uTPLb_Codec, uTPLb_PointerArithmetic, Math; { TAsymetricKeyPair } procedure TAsymetricKeyPair.Burn; begin FPublicPart.Burn; FPrivatePart.Burn end; function TAsymetricKeyPair.Clone: TAsymetricKeyPair; var Memento: TStream; Parts: TKeyStoragePartSet; begin Parts := HasParts; result := TAsymetricKeyPairClass( ClassType).CreateEmpty; Memento := TMemoryStream.Create; try StoreToStream( Memento, Parts); Memento.Position := 0; result.LoadFromStream( Memento, Parts) finally Memento.Free end end; destructor TAsymetricKeyPair.Destroy; begin FPublicPart.Free; FPrivatePart.Free; inherited end; function TAsymetricKeyPair.HasParts: TKeyStoragePartSet; begin result := []; if assigned( FPublicPart) and (not FPublicPart.isEmpty) then Include( result, partPublic); if assigned( FPrivatePart) and (not FPrivatePart.isEmpty) then Include( result, partPrivate) end; function TAsymetricKeyPair.NominalKeyBitLength: cardinal; var Part : TAsymtricKeyPart; begin Part := FPublicPart; if not assigned( Part) then Part := FPrivatepart; if assigned( Part) then result := Part.NominalKeyBitLength else result := 0 end; function TAsymetricKeyPair.Can_StoreToStream( Parts: TKeyStoragePartSet): boolean; begin result := (Parts * HasParts) = Parts end; procedure TAsymetricKeyPair.SaveToStream( Stream: TStream); begin StoreToStream( Stream, [partPublic, partPrivate]) end; procedure TAsymetricKeyPair.StoreToStream( Store: TStream; Parts: TKeyStoragePartSet); var hasPart: boolean; begin if partPublic in Parts then begin hasPart := assigned( FPublicPart) and (not FPublicPart.isEmpty); Store.WriteBuffer( hasPart, SizeOf( hasPart)); if hasPart then FPublicPart.SaveToStream( Store) end; if partPrivate in Parts then begin hasPart := assigned( FPrivatePart) and (not FPrivatePart.isEmpty); Store.WriteBuffer( hasPart, SizeOf( hasPart)); if hasPart then FPrivatePart.SaveToStream( Store) end end; // Typically the concrete descendant of TAsymetricKeyPair will // implement LoadFromStream something like this .... //procedure TAsymetricKeyPair_DescendantClass.LoadFromStream( // Store: TStream; Parts: TKeyStoragePartSet); //var // hasPart: boolean; //begin //if partPublic in Parts then // begin // Store.ReadBuffer( hasPart, SizeOf( hasPart)); // FreeAndNil( FPublicPart); // if hasPart then // begin // if not assigned( FPublicPart) then // FPublicPart := TSomeClass.Create; // FPublicPart.LoadFromStream( Store) // end // else if assigned( FPublicPart) then // FPublicPart.Clear // end; //if partPrivate in Parts then // begin // Store.ReadBuffer( hasPart, SizeOf( hasPart)); // FreeAndNil( FPrivatePart); // if hasPart then // begin // if not assigned( FPrivatePart) then // FPrivatePart := TSomeClass.Create; // FPrivatePart.LoadFromStream( Store) // end // else if assigned( FPrivatePart) then // FPrivatePart.Clear // end //end; { TAsymetric_Engine } function TAsymetric_Engine.Features: TAlgorithmicFeatureSet; begin result := [ afOpenSourceSoftware, afDoesNotNeedSalt, // Only applicable to IStreamCiphers which are true // crytographic codecs, that is to say they do not have the // afCompressor or afConverter feature. Normally, stream ciphers will // be used by injecting a 64 bit salt of random data at the start // of the plaintext stream. However, if the cipher has this feature // (afDoesNotNeedSalt) it means it is already salting its own // tranform, or it cannot benefit from salt. In this case, users of // IStreamCipher, such as TCodec will not salt the plaintext. afAsymetric ] end; function TAsymetric_Engine.GenerateKey( Seed: TStream): TSymetricKey; begin result := nil end; function TAsymetric_Engine.Parameterize( const Params: IInterface): IStreamCipher; begin result := nil end; function TAsymetric_Engine.SeedByteSize: integer; begin result := -1 end; procedure TAsymetric_Engine.Sign( Document, Signature: TStream; PrivatePart: TAsymtricKeyPart; ProgressSender: TObject; ProgressEvent: TOnEncDecProgress; var wasAborted: boolean); var Dec: TAsymetricDecryptorClass; DecObj: TAsymetricDecryptor; isCounted: boolean; begin Dec := DecClass; DecObj := Dec.Start_Decrypt( PrivatePart, Document); isCounted := DecObj._AddRef <> -1; try if not assigned( ProgressSender) then ProgressSender := self; wasAborted := False; Document.Position := 0; Signature.Size := 0; DecObj.Sign( Signature, ProgressSender, ProgressEvent, wasAborted); finally DecObj._Release; if not isCounted then DecObj.Free end end; function TAsymetric_Engine.Start_Decrypt( Key: TSymetricKey; PlainText: TStream): IStreamDecryptor; begin if (Key is TAsymetricKeyPair) and Assigned( TAsymetricKeyPair( Key).FPrivatePart) then result := DecClass.Start_Decrypt( TAsymetricKeyPair( Key).FPrivatePart, PlainText) else result := nil end; function TAsymetric_Engine.Start_Encrypt( Key: TSymetricKey; CipherText: TStream): IStreamEncryptor; begin if (Key is TAsymetricKeyPair) and Assigned( TAsymetricKeyPair( Key).FPublicPart) then result := EncClass.Start_Encrypt( TAsymetricKeyPair( Key).FPublicPart, CipherText) else result := nil end; function TAsymetric_Engine.VerifySignature( Document, Signature: TStream; PublicPart: TAsymtricKeyPart; ProgressSender: TObject; ProgressEvent: TOnEncDecProgress; var wasAborted: boolean): boolean; var Enc: TAsymetricEncryptorClass; EncObj: TAsymetricEncryptor; isCounted: boolean; begin Enc := EncClass; Signature.Position := 0; EncObj := Enc.Start_Encrypt( PublicPart, Signature); isCounted := EncObj._AddRef <> -1; try if not assigned( ProgressSender) then ProgressSender := self; wasAborted := False; Document.Position := 0; result := EncObj.VerifySignature( Document, ProgressSender, ProgressEvent, wasAborted) finally EncObj._Release; if not isCounted then EncObj.Free end end; { TAsymetricEncDec } constructor TAsymetricEncDec.Create; begin FBytesProcessed := 0; FSymetricCodecObj := TSimpleCodec.Create; Supports( FSymetricCodecObj, ICodec, FSymetricCodec); FSymetricCodec.StreamCipher := TStreamToBlock_Adapter.Create; FSymetricCodec.BlockCipher := TAES.Create( 256); FSymetricCodec.ChainMode := TCBC.Create end; destructor TAsymetricEncDec.Destroy; begin FSymetricCodec := nil; FSymetricCodecObj.Free; inherited end; procedure TAsymetricEncDec.Reset; begin FSymetricCodec.Reset; FBytesProcessed := 0 end; { TAsymetricEncryptor } procedure TAsymetricEncryptor.Encrypt( const Plaintext: TStream); var Sz: cardinal; Xfer: cardinal; XferBuffer: TBytes; begin Sz := PlainText.Size - Plaintext.Position; if Sz <= 0 then Exit; if FBytesProcessed = 0 then begin FSymetricCodec.InitFromKey( GenerateSymetricKey); // Transfers ownership. FSymetricCodec.Begin_EncryptMemory( FCipherText) end; Inc(FBytesProcessed, Sz); if PlainText is TBytesStream then begin FSymetricCodec.EncryptMemory(TBytesStream(Plaintext).Bytes, Sz); PlainText.Seek(Sz, soCurrent) end else begin SetLength(XferBuffer, 256); while Sz > 0 do begin Xfer := Min(Sz, Length(XferBuffer)); Xfer := Plaintext.Read(XferBuffer, Xfer); if Xfer = 0 then Break; Dec(Sz, Xfer); FSymetricCodec.EncryptMemory(XferBuffer, Xfer) end; end end; procedure TAsymetricEncryptor.End_Encrypt; begin if FBytesProcessed > 0 then FSymetricCodec.End_EncryptMemory end; constructor TAsymetricEncryptor.Start_Encrypt( PublicKey1: TAsymtricKeyPart; CipherText1: TStream); begin inherited Create; FPublicKey := PublicKey1; FCipherText := CipherText1 end; { TAsymetricDecryptor } procedure TAsymetricDecryptor.Decrypt( const Ciphertext: TStream); var Sz: cardinal; Xfer: cardinal; XferBuffer: array[0..255] of byte; P1, P2: int64; KeyDelta: cardinal; begin P1 := Ciphertext.Position; Sz := Ciphertext.Size - P1; if Sz <= 0 then exit; if FBytesProcessed = 0 then begin FSymetricCodec.InitFromKey( LoadSymetricKey( Ciphertext)); // Transfers ownership. P2 := Ciphertext.Position; KeyDelta := P2 - P1; Inc( FBytesProcessed, KeyDelta); Dec( Sz, KeyDelta); FSymetricCodec.Begin_DecryptMemory( FPlainText) end; Inc( FBytesProcessed, Sz); if Ciphertext is TMemoryStream then begin FSymetricCodec.DecryptMemory( MemStrmOffset( TMemoryStream( Ciphertext), Ciphertext.Position)^, Sz); Ciphertext.Seek( Sz, soCurrent) end else begin while Sz > 0 do begin Xfer := Min( Sz, SizeOf( XferBuffer)); Xfer := Ciphertext.Read( XferBuffer, Xfer); if Xfer = 0 then break; Dec( Sz, Xfer); FSymetricCodec.DecryptMemory( XferBuffer, Xfer) end end end; procedure TAsymetricDecryptor.End_Decrypt; begin if FBytesProcessed > 0 then FSymetricCodec.End_DecryptMemory end; constructor TAsymetricDecryptor.Start_Decrypt( PrivateKey1: TAsymtricKeyPart; PlainText1: TStream); begin inherited Create; FPrivateKey := PrivateKey1; FPlainText := PlainText1 end; end.
unit mo17_intf; interface uses AppStruClasses, Forms, Classes, Ibase, Messages, Windows, Dialogs, SysUtils; type TMO17MainBook=class(TFMASAppModule,IFMASModule) private WorkMainForm:TForm; public procedure Run; procedure OnLanguageChange(var Msg:TMessage); message FMAS_MESS_CHANGE_LANG; procedure OnGridStylesChange(var Msg:TMessage); message FMAS_MESS_CHANGE_GSTYLE; destructor Destroy; override; end; implementation uses MO17MainForm; { TMOMainBook } destructor TMO17MainBook.Destroy; begin if Assigned(self.WorkMainForm) then self.WorkMainForm.Free; inherited Destroy; end; procedure TMO17MainBook.OnGridStylesChange(var Msg: TMessage); begin //Для будущей реализации end; procedure TMO17MainBook.OnLanguageChange(var Msg: TMessage); begin //Для будущей реализации end; procedure TMO17MainBook.Run; begin //Создаем MDI форму для показа результатов формирования //мемориального ордера "ГОЛОВНА_КНИГА" WorkMainForm:= TTMo14MainForm.Create( TComponent(self.InParams.Items['AOwner']^), TISC_DB_HANDLE(PInteger(self.InParams.Items['DbHandle'])^), PInteger(self.InParams.Items['Id_User'])^); end; initialization //Регистрация класса в глобальном реестре RegisterAppModule(TMO17MainBook,'mo_17form'); end.
{N empresas de transportes realizan envíos de cargas, por cada bulto se ingresa PESO de la carga (número real) y CATEGORIA (dato codificado: C - común , E - especial , A – aéreo). El precio se calcula a $25 por Kg para categoría común, $32.5 por Kg para categoría especial y $50 por Kg para categoría aérea. Se cobra recargo por sobrepeso: 30% si sobrepasa los 15 Kg, 20% si pesa más de 10 Kg y hasta 15Kg inclusive, 10% más de 5Kg y hasta 10 Kg inclusive. Se desea calcular y mostrar el importe a pagar por cada uno de bultos al final del proceso el total recaudado por cada empresa y por cada una de las tres categorías. Implementar y utilizar función Precio correctamente parametrizada que devuelva el importe a pagar por un bulto.} Program cargas; Function Precio(Peso:real; Cat:char):real; Var Pr:real; Begin Case Cat of 'C':Pr:= Peso * 25; 'E':Pr:= Peso * 32.5; 'A':Pr:= Peso * 50; end; If (Peso <= 10) then Pr:= Pr * 1.1 Else if (Peso <= 15) then Pr:= Pr * 1.2 Else Pr:= Pr * 1.3; Precio:= Pr; end; Var Emp:string[11]; i,N:byte; Cat,Esp:char; Peso,Pr,Acum,AcumC,AcumE,AcumA:real; arch:text; Begin AcumC:= 0; //Estras tres variables deben ser inicializadas antes del ciclo For porque sino no acumulará bien los resultados por categoria. AcumE:= 0; AcumA:= 0; assign(arch,'Cargas.txt');reset(arch); readln(arch,N); For i:= 1 to N do begin Acum:= 0; //Debe ser inicializada antes del ciclo while porque sino no acumulará bien el total por empresa. readln(arch,Emp); read(arch,Peso,Esp); while (Peso <> 0) do begin readln(arch,Cat); Pr:= Precio(Peso,Cat); Acum:= Acum + Pr; If (Cat = 'C') then AcumC:= AcumC + Pr Else if (Cat = 'E') then AcumE:= AcumE + Pr Else AcumA:= AcumA + Pr; writeln(Emp,' facturo por el bulto: ',Peso:2:0,Esp,Cat,' $',Pr:2:0); read(arch,Peso,Esp); end; readln(arch); writeln(Emp,' recaudo en total: $',Acum:2:0); writeln; end; close(arch); writeln('La categoria comun recaudo: $',AcumC:2:0); writeln('La categoria especial recaudo: $',AcumE:2:0); writeln('La categoria aerea recaudo: $',AcumA:2:0); end.
//============================================================================= // sgVectorShapes.pas //============================================================================= // // EXPERIMENTAL // // Contains code to create shapes - should allow vector graphics for // Sprites etc when complete... Needs lots of work. // // Change History: // Version 3.0: // - 2011-05-23: Andrew : Created. Removed this code from Geometry // //============================================================================= /// /// @module VectorShapes /// @static unit sgVectorShapes; interface uses sgTypes; type /// The ShapeKind is used to configure the drawing method for a /// shape. Each of these options provides an alternate way of /// rendering based upon the shapes points. /// /// @enum ShapeKind ShapeKind= ( pkPoint, pkCircle, // pkEllipse, pkLine, pkTriangle, pkLineList, pkLineStrip, // pkPolygon, pkTriangleStrip, pkTriangleFan, pkTriangleList ); /// @class ShapePrototype /// @pointer_wrapper /// @field pointer: pointer ShapePrototype = ^ShapePrototypeData; /// @class Shape /// @pointer_wrapper /// @field pointer: pointer Shape = ^ShapeData; /// The ShapeDrawingFn is a function pointer that points to a procedure /// that is capable of drawing a Shape. This is used when the shape /// is drawn be DrawShape and FillShape. /// /// @type ShapeDrawingFn ShapeDrawingFn = procedure(dest: Bitmap; s: Shape; filled: Boolean; const offset:Point2D); /// @struct ShapePrototypeData /// @via_pointer ShapePrototypeData = packed record points: Point2DArray; kind: ShapeKind; shapeCount: Longint; //the number of shapes using the prototype drawWith: ShapeDrawingFn; end; /// @struct ShapeData /// @via_pointer ShapeData = packed record pt: Point2D; prototype: ShapePrototype; color: Color; scale: Point2D; angle: single; ptBuffer: Point2DArray; subShapes: array of Shape; end; /// Returns the number of lines in a given shape /// /// @lib /// /// @class Shape /// @getter LineCount function ShapeLineCount(s: Shape): Longint; /// Returns an array of lines from a given shape. These are the lines that represent /// the shape. /// /// @lib LinesFromShape /// /// @class Shape /// @getter Lines /// @length ShapeLineCount function LinesFrom(s: shape): LinesArray; overload; /// Returns the vector needed to move shape ``s`` out of rectangle``bounds`` given the it was moving with the velocity specified. /// /// @lib /// @sn shape:%s vectorOutOfRect:%s givenHeading:%s /// /// @class Shape /// @method VectorOutOfRect /// @csn vectorOutOfRect:%s givenHeading:%s function ShapeVectorOutOfRect(s: shape; const bounds: Rectangle; const velocity: Vector ): vector; //---------------------------------------------------------------------------- // ShapePrototype creating functions //---------------------------------------------------------------------------- /// Create a shape prototype for a given point. /// /// @lib /// /// @class ShapePrototype /// @constructor /// @csn initPointPrototypeAt:%s function PointPrototypeFrom(const pt: Point2D): ShapePrototype; /// Create a shape prototype of a circle with a given radius ``r``. /// /// @lib /// @sn circlePrototypeFromPt:%s radius:%s /// /// @class ShapePrototype /// @constructor /// @csn initCirclePrototypeAt:%s withRadius:%s function CirclePrototypeFrom(const pt: Point2D; r: Single): ShapePrototype; // /// Create a shape prototype of an ellipse with a given width and height. // /// // /// @lib // /// @class ShapePrototype // /// @constructor // /// @csn initEllipsePrototypeAt:%s width:%s height:%s // function EllipsePrototypeFrom(const pt: Point2D; w, h: Single): ShapePrototype; /// Create a shape prototype for a line from ``startPt`` to ``endPt``. /// /// @lib /// @sn linePrototypeFromPt:%s toPt:%s /// /// @class ShapePrototype /// @constructor /// @csn initLinePrototypeFrom:%s to:%s function LinePrototypeFrom(const startPt, endPt: Point2D): ShapePrototype; /// Create a shape prototype for a triangle made of points ``pt1``, ``pt2``, and ``pt3``. /// /// @lib /// @sn trianglePrototypeFromPt1:%s pt2:%s pt3:%s /// /// @class ShapePrototype /// @constructor /// @csn initTrianglePrototype:%s point2:%s point3:%s function TrianglePrototypeFrom(const pt1, pt2, pt3: Point2D): ShapePrototype; /// Create a LineList prototype from the passed in points. There must be an /// even number of points, where each pair represents a line. /// /// @lib /// @sn lineListPrototypeFrom:%s /// /// @class ShapePrototype /// @constructor /// @csn initLineListPrototype:%s function LineListPrototypeFrom(const points: Point2DArray): ShapePrototype; /// Creates a LineStrip prototype where the points in the array represent the /// points on the line. The last point of the line does not join back to the starting /// point. /// /// @lib /// @sn lineStripPrototypeFrom:%s /// /// @class ShapePrototype /// @constructor /// @csn initLineStripPrototype:%s function LineStripPrototypeFrom(const points: Point2DArray): ShapePrototype; // /// Creates a Polygon from the passed in points, the polygon is made up of // /// the points in the array and the last point does join back to the start // /// point. // /// // /// @lib // function PolygonPrototypeFrom(const points: Point2DArray): ShapePrototype; /// Creates a triangle strip from the passed in points. The passed in array /// must contain at least three points. /// /// @lib /// @sn triangleStripPrototypeFrom:%s /// /// @class ShapePrototype /// @constructor /// @csn initTriangleStripPrototype:%s function TriangleStripPrototypeFrom(const points: Point2DArray): ShapePrototype; /// Creates a triangle fan from the passed in points. The fan is constructed from /// the first point combined with all other point pairs. The array must contain /// at least three points. /// /// @lib /// @sn triangleFanPrototypeFrom:%s /// /// @class ShapePrototype /// @constructor /// @csn initTriangleFanPrototype:%s function TriangleFanPrototypeFrom(const points: Point2DArray): ShapePrototype; /// Creates a triangle list from the passed in points. The list is a set of /// triangles. The number of points must be divisible by three. /// /// @lib /// @sn triangleListPrototypeFrom:%s /// /// @class ShapePrototype /// @constructor /// @csn initTriangleListPrototype:%s function TriangleListPrototypeFrom(const points: Point2DArray): ShapePrototype; /// Creates a shape prototype from the data in the points array. The kind /// indicates the type of shape prototype to create. /// /// @lib /// @sn prototypeFrom:%s kind:%s /// /// @class ShapePrototype /// @constructor /// @csn initShapePropertyFrom:%s withKind:%s function PrototypeFrom(const points: Point2DArray; kind:ShapeKind): ShapePrototype; /// Free the resources used by a ShapePrototype. /// /// @lib /// /// @class ShapePrototype /// @dispose procedure FreePrototype(var p: ShapePrototype); //---------------------------------------------------------------------------- // ShapePrototype functions and procedures //---------------------------------------------------------------------------- /// Returns the minimum number of points required for the given shape kind. /// /// @lib /// /// @class ShapePrototype /// @method MinimumPointsForKind /// @static function MinimumPointsForKind(k: ShapeKind): Longint; /// Returns the number of points allocated to this shape prototype. /// /// @lib /// /// @class ShapePrototype /// @getter PointCount function PrototypePointCount(p: ShapePrototype): Longint; /// Change the prototype's points to the passed in points. The number of points must /// be sufficient for the kind of shape being changed. /// /// @lib /// @sn prototype:%s setPointsTo:%s /// /// @class ShapePrototype /// @setter Points /// @length PrototypePointCount procedure PrototypeSetPoints(p: ShapePrototype; const points: Point2DArray); /// The prototype point locations. /// /// @lib /// /// @class ShapePrototype /// @getter Points /// @length PrototypePointCount function PrototypePoints(p: ShapePrototype): Point2DArray; /// Changes the prototype kind. This effects how shapes of this prototype /// are drawn to the screen, and the number of points required. /// /// @lib /// @sn prototype:%s setKindTo:%s /// /// @class ShapePrototype /// @setter Kind procedure PrototypeSetKind(p: ShapePrototype; kind: ShapeKind); /// The prototype kind. This effects how shapes of this prototype /// are drawn to the screen, and the number of points required. /// /// @lib /// /// @class ShapePrototype /// @getter Kind function PrototypeKind(p: ShapePrototype): ShapeKind; //---------------------------------------------------------------------------- // Shape Code //---------------------------------------------------------------------------- /// Create a shape from a given prototype at a set location in the game. /// /// @lib /// @sn prototype:%s createShapeAtPt:%s /// /// @class Shape /// @constructor /// @csn initShapeWithPrototype:%s atPoint:%s function ShapeAtPoint(p: ShapePrototype; const pt: Point2D): Shape; /// Free the resources used by a Shape. /// /// @lib /// @class Shape /// @dispose procedure FreeShape(var s: Shape); /// Recalculate the points of the shape. This will be required when a Shape's /// prototype is changed. /// /// @lib /// @class Shape /// @method UpdatePoints procedure UpdateShapePoints(s: Shape); /// Returns the number of points on this shape. /// /// @lib /// @class Shape /// @getter PointCount function ShapePointCount(s: Shape): Longint; /// Returns all of the points for a shape, based on its kind, angle /// and scale. /// /// @lib /// @class Shape /// @getter Points /// @length ShapePointCount function ShapePoints(s: Shape): Point2DArray; /// Change the angle of a Shape. /// /// @lib /// @sn shape:%s setAngleTo:%s /// /// @class Shape /// @setter Angle procedure ShapeSetAngle(s: Shape; angle: Single); /// Return the angle of a Shape. /// /// @lib /// /// @class Shape /// @getter Angle function ShapeAngle(s: Shape): Single; /// Change the scale of a Shape. /// /// @lib /// @sn shape:%s setScaleTo:%s /// /// @class Shape /// @setter Scale procedure ShapeSetScale(s: Shape; const scale: Point2D); /// Return the scale of a Shape. /// /// @lib /// /// @class Shape /// @getter Scale function ShapeScale(s: Shape): Point2D; /// Add a shape as a sub shape to a given parent shape. /// /// @lib /// @sn shape:%s addSubShape:%s /// /// @class Shape /// @method AddSubShape /// @csn addSubShape:%s procedure ShapeAddSubShape(parent, child: Shape); /// Gets the color of the shape s. /// /// @lib /// /// @class Shape /// @getter Color function ShapeColor(s: Shape): Color; /// Sets the color of the shape s. /// /// @lib /// @sn shape:%s setColorTo:%s /// /// @class Shape /// @setter Color procedure ShapeSetColor(s: Shape; c: Color); /// Sets the shape's prototype. /// /// @lib /// @sn shape:%s setPrototypeTo:%s /// /// @class Shape /// @setter ShapePrototype procedure ShapeSetPrototype(s: Shape; p: ShapePrototype); /// Returns the shape's ShapePrototype. /// /// @lib /// @sn shapeShapePrototype:%s /// /// @class Shape /// @getter ShapePrototype function ShapeShapePrototype(s: Shape): ShapePrototype; /// Returns true if the shape and rectangle intersect /// /// @lib /// @sn shape:%s intersectsRectangle:%s /// /// @class Shape /// @method IntersectsRectangle function ShapeRectangleIntersect(s: Shape; const rect: Rectangle): Boolean; /// Returns an axis aligned bounded box for the shape. /// /// @lib /// /// @class Shape /// @getter AABB function ShapeAABB(s: Shape): Rectangle; /// Returns the kind of the shape. /// /// @lib /// /// @class Shape /// @getter ShapeKind function ShapeShapeKind(s: Shape): ShapeKind; /// Returns the number of triangles in the Shape. /// /// @lib /// /// @class Shape /// @getter TriangleCount function ShapeTriangleCount(s: Shape): Longint; /// Returns the number of triangles in the Shape. /// /// @lib /// @sn shapeTriangleCount:%s kind:%s function ShapeKindTriangleCount(s: Shape; kind: ShapeKind): Longint; /// Returns the triangles for a triangle strip, list, or fan. /// /// @lib /// @sn shapeTriangles:%s /// @length ShapeTriangleCount /// /// @class Shape /// @method AsTriangles /// @csn triangles function ShapeTriangles(s: Shape): TriangleArray; overload; /// Returns the triangles for a triangle strip, list, or fan. /// /// @lib ShapeTrianglesForKind /// @sn shapeTriangles:%s forKind:%s /// @length ShapeKindTriangleCount /// /// @class Shape /// @overload AsTriangles AsTrianglesForKind /// @csn trianglesForKind:%s function ShapeTriangles(s: Shape; kind: ShapeKind): TriangleArray; /// Returns the triangles for a triangle strip, list, or fan with an offset. /// /// @lib ShapeTrianglesOffset /// @sn shapeTriangles:%s forKind:%s offset:%s /// @length ShapeKindTriangleCount /// /// @class Shape /// @overload AsTriangles AsTrianglesOffset /// @csn trianglesForKind:%s offset:%s function ShapeTriangles(s: Shape; kind: ShapeKind; const offset: Point2D): TriangleArray; /// Returns the number of lines in a given shape and kind. /// /// @lib /// @sn shapeLineCount:%s kind:%s function ShapeKindLineCount(s: Shape; kind: ShapeKind): Longint; /// Returns the lines for a triangle list or strip. /// /// @lib /// @sn shapeLines:%s /// @length ShapeLineCount /// /// @class Shape /// @method AsLines function ShapeLines(s: Shape): LinesArray; overload; /// Returns the lines for a triangle list or strip. /// /// @lib ShapeKindLines /// @sn shapeLines:%s forKind:%s /// @length ShapeKindLineCount /// /// @class Shape /// @overload AsLines AsLinesForKind /// @csn linesForKind:%s function ShapeLines(s: Shape; kind: ShapeKind): LinesArray; overload; /// Returns the lines for a triangle list or strip with offset. /// /// @lib ShapeLinesWithOffset /// @sn shapeLines:%s forKind:%s withOffset:%s /// @length ShapeLineCount /// /// @class Shape /// @overload AsLines AsLinesOffset /// @csn linesForKind:%s offset:%s function ShapeLines(s: Shape; kind: ShapeKind; const offset:Point2D): LinesArray; overload; /// Returns the triangle from the shapes details. /// /// @lib /// /// @class Shape /// @method AsTriangle function ShapeTriangle(s: Shape): Triangle; /// Returns the triangle from the shapes details with offset. /// /// @lib ShapeTriangleWithOffset /// @sn shape:%s asTriangleOffset:%s /// /// @class Shape /// @overload AsTriangle AsTriangleOffset function ShapeTriangle(s: Shape; const offset:Point2D): Triangle; /// Returns the line from the shapes details. /// /// @lib /// /// @class Shape /// @method AsLine function ShapeLine(s: Shape): LineSegment; /// Returns the line from the shapes details with offset. /// /// @lib ShapeLineOffset /// @sn shape:%s asLineOffset:%s /// /// @class Shape /// @overload AsLine AsLineOffset function ShapeLine(s: Shape; const offset:Point2D): LineSegment; /// Returns the circle from the shapes details. /// /// @lib /// /// @class Shape /// @method AsCircle function ShapeCircle(s: Shape): Circle; /// Returns the circle from the shapes details with offset. /// /// @lib ShapeCircleOffset /// @sn circleShape:%s offset:%s /// /// @class Shape /// @overload AsCircle AsCircleOffset function ShapeCircle(s: Shape; const offset:Point2D): Circle; /// Returns True if point 'pt' is in the shape. /// /// @lib /// @sn point:%s inShape:%s /// /// @class Point2D /// @method InShape function PointInShape(const pt: Point2d; s:Shape):Boolean; //--------------------------------------------------------------------------- // Shape drawing code //--------------------------------------------------------------------------- /// Draw the Shape s onto the destination bitmap. The filled Boolean indicates /// if the Shape should be filled. /// /// @lib DrawOrFillShapeOnto /// @sn drawOnto:%s shape:%s filled:%s /// /// @class Shape /// @overload Draw DrawOrFillOnto /// @self 2 /// @csn drawOnto:%s filled:%s procedure DrawShape(dest: Bitmap; s: Shape; filled: Boolean); overload; /// Draw the Shape s onto the destination bitmap. /// /// @lib DrawShapeOnto /// @sn drawOnto:%s shape:%s /// /// @class Shape /// @overload Draw DrawOnto /// @self 2 /// @csn drawOnto:%s procedure DrawShape(dest: Bitmap; s: Shape); overload; /// Fill the Shape s onto the destination bitmap. /// /// @lib FillShapeOnto /// @sn fillOnto:%s shape:%s /// /// @class Shape /// @overload Fill FillOnto /// @self 2 /// @csn fillOnto:%s procedure FillShape(dest: Bitmap; s: Shape); overload; /// Draw or fill the Shape s onto the screen at the /// shapes game coordinates. /// /// @lib DrawOrFillShape /// @sn drawShape:%s filled:%s /// /// @class Shape /// @overload Draw DrawOrFill /// @csn drawFilled:%s procedure DrawShape(s: Shape; filled: Boolean); overload; /// Draw the Shape s onto the screen at the /// shapes game coordinates. /// /// @lib DrawShape /// /// @class Shape /// @method Draw procedure DrawShape(s: Shape); overload; /// Fill the Shape s. /// /// @lib FillShape /// /// @class Shape /// @method Fill procedure FillShape(s: Shape); overload; /// Draw or fill the Shape s onto the screen using the /// Shape's location as screen coordinates. /// /// @lib DrawOrFillShapeOnScreen /// @sn drawShapeOnScreen:%s filled:%s /// /// @class Shape /// @overload DrawOnScreen DrawOrFillOnScreen /// @csn drawOnScreenFilled:%s procedure DrawShapeOnScreen(s: Shape; filled: Boolean); overload; /// Draw the Shape s onto the screen using the /// Shape's location as screen coordinates. /// /// @lib DrawShapeOnScreen /// /// @class Shape /// @method DrawOnScreen procedure DrawShapeOnScreen(s: Shape); overload; /// Fill the Shape s onto the screen using the /// Shape's location as screen coordinates. /// /// @lib FillShapeOnScreen /// /// @class Shape /// @method FillOnScreen procedure FillShapeOnScreen(s: Shape); overload; /// Draw the passed in shape to the specified bitmap. If filled the shape /// is drawn with a fill rather than drawn as a series of lines. This version /// Draws the first point of the shape as a pixel. /// /// @lib /// @sn drawOnto:%s pointShape:%s filled:%s offset:%s /// /// @class Shape /// @method DrawAsPoint /// @self 2 /// @csn drawPointOnto:%s filled:%s offset:%s procedure DrawShapeAsPoint(dest: Bitmap; s:Shape; filled: Boolean; const offset:Point2D); overload; /// Draw the passed in shape to the specified bitmap. If filled the shape /// is drawn with a fill rather than drawn as a series of lines. This version /// draws the shape as a circle, centered on the first point with a radius defined /// by the distance to the second point. /// /// @lib /// @sn drawOnto:%s circleShape:%s filled:%s offset:%s /// /// @class Shape /// @method DrawAsCircle /// @self 2 /// @csn drawCircleOnto:%s filled:%s offset:%s procedure DrawShapeAsCircle(dest: Bitmap; s:Shape; filled: Boolean; const offset:Point2D); overload; // /// Draw the passed in shape to the specified bitmap. If filled the shape // /// is drawn with a fill rather than drawn as a series of lines. // /// // /// @lib // /// @class Shape // /// @method DrawAsEllipse // /// @self 2 // procedure DrawShapeAsEllipse(dest: Bitmap; s:Shape; filled: Boolean); overload; /// Draw the passed in shape to the specified bitmap. If filled the shape /// is drawn with a fill rather than drawn as a series of lines. This version /// draws a line from the first point of the shape to the second point. /// /// @lib /// @sn drawOnto:%s lineShape:%s filled:%s offset:%s /// /// @class Shape /// @method DrawAsLine /// @self 2 /// @csn drawLineOnto:%s filled:%s offset:%s procedure DrawShapeAsLine(dest: Bitmap; s:Shape; filled: Boolean; const offset:Point2D); overload; /// Draw the passed in shape to the specified bitmap. If filled the shape /// is drawn with a fill rather than drawn as a series of lines. This version /// draws the shape as a triangle based on the first three points of the shape. /// /// @lib /// @sn drawOnto:%s triangleShape:%s filled:%s offset:%s /// /// @class Shape /// @method DrawAsTriangle /// @self 2 /// @csn drawTriangleOnto:%s filled:%s offset:%s procedure DrawShapeAsTriangle(dest: Bitmap; s:Shape; filled: Boolean; const offset:Point2D); overload; /// Draw the passed in shape to the specified bitmap. If filled the shape /// is drawn with a fill rather than drawn as a series of lines. This version /// draws the points as a list of lines. A shape with 4 points has two lines in its /// list. If an odd numer of points are supplied then the extra point will be skipped. /// In this way a shape with 5 points also has 2 lines. /// /// @lib /// @sn drawOnto:%s lineListShape:%s filled:%s offset:%s /// /// @class Shape /// @method DrawAsLineList /// @self 2 /// @csn drawLineListOnto:%s filled:%s offset:%s procedure DrawShapeAsLineList(dest: Bitmap; s: Shape; filled: Boolean; const offset:Point2D); /// Draw the passed in shape to the specified bitmap. If filled the shape /// is drawn with a fill rather than drawn as a series of lines. This version /// draws the shape as a line strip. A shape with three points has two lines, one /// from pt[0] to pt[1] and a second from pt[1] to pt[2]. /// /// @lib /// @sn drawOnto:%s lineStripShape:%s filled:%s offset:%s /// /// @class Shape /// @method DrawAsLineStrip /// @self 2 /// @csn drawLineStripOnto:%s filled:%s offset:%s procedure DrawShapeAsLineStrip(dest: Bitmap; s: Shape; filled: Boolean; const offset:Point2D); // / Draw the passed in shape to the specified bitmap. If filled the shape // / is drawn with a fill rather than drawn as a series of lines. This draws // / as a polygon where each point is connected to its neighbour and the // / first point is reconnected to the last point. // / // / @lib // / @sn drawOnto:%s polygonShape:%s filled:%s offset:%s // / // / @class Shape // / @method DrawAsPolygon // / @self 2 // / @csn drawPolygonOnto:%s filled:%s offset:%s //procedure DrawShapeAsPolygon(dest: Bitmap; s: Shape; filled: Boolean; const offset:Point2D); /// Draw the passed in shape to the specified bitmap. If filled the shape /// is drawn with a fill rather than drawn as a series of lines. This version /// draws the shape as a tan of triangles where each triangle is made up of /// the first point and two neighbouring points from the shape. /// /// @lib /// @sn drawOnto:%s triangleFanShape:%s filled:%s offset:%s /// /// @class Shape /// @method DrawAsTriangleFan /// @self 2 /// @csn drawTriangleFonOnto:%s filled:%s offset:%s procedure DrawShapeAsTriangleFan(dest: Bitmap; s: Shape; filled: Boolean; const offset:Point2D); /// Draw the passed in shape to the specified bitmap. If filled the shape /// is drawn with a fill rather than drawn as a series of lines. This version /// draws as a strip of triangles where each triangle is made up of the /// three neighbouring points. In this way 4 points gives two triangles. /// /// @lib /// @sn drawOnto:%s triangleStripShape:%s filled:%s offset:%s /// /// @class Shape /// @method DrawAsTriangleStrip /// @self 2 /// @csn drawTriangleStripOnto:%s filled:%s offset:%s procedure DrawShapeAsTriangleStrip(dest: Bitmap; s: Shape; filled: Boolean; const offset:Point2D); /// Draw the passed in shape to the specified bitmap. If filled the shape /// is drawn with a fill rather than drawn as a series of lines. This version /// draws as a triangle list, where each set of three points is drawn as an /// individual triangle and extra points are ignored. So 6, 7, and 8 points /// all create 2 triangles (pt[0] + pt[1] + pt[2] and pt[3] + pt[4] + pt[5]). /// /// @lib /// @sn drawOnto:%s triangleListShape:%s filled:%s offset:%s /// /// @class Shape /// @method DrawAsTriangleList /// @self 2 /// @csn drawTriangleListOnto:%s filled:%s offset:%s procedure DrawShapeAsTriangleList(dest: Bitmap; s: Shape; filled: Boolean; const offset:Point2D); /// Returns true if the sprite and the shape have collided. /// /// @lib SpriteShapeCollision /// @sn sprite:%s collisionWithShape:%s /// /// @class Sprite /// @method ShapeCollision function SpriteShapeCollision(s: Sprite; shp: Shape): Boolean; overload; implementation uses SysUtils, sgGeometry, sgShared, sgPhysics, sgGraphics, sgCamera, sgSprites, sgTrace, sgDrawingOptions; function PointOnLineList(const pt:point2d; const s:Shape):Boolean; var pts : Point2dArray; i :Longint; begin pts := ShapePoints(s); result:=False; for i := 0 to Length(pts) div 2 - 1 do begin if PointOnLine(pt, Linefrom(pts[i * 2], pts[i * 2 + 1])) then begin result:=True; exit; end end; end; function PointOnLineStrip(const pt:point2d; const s:Shape):Boolean; var pts : Point2dArray; i :Longint; begin pts := ShapePoints(s); result:=False; for i := 0 to Length(pts) - 2 do begin if PointOnLine(pt,Linefrom(pts[i], pts[i+ 1])) then begin result:=True; exit; end; end; end; function PointInTriangleList(const pt:point2d; const s:shape):Boolean; var pts : Point2dArray; i :Longint; begin pts := ShapePoints(s); result:=False; for i := 0 to Length(pts) div 3 - 1 do begin if PointInTriangle(pt, TriangleFrom( pts[i * 3].x, pts[i * 3].y, pts[i * 3 + 1].x, pts[i * 3 + 1].y, pts[i * 3 + 2].x, pts[i * 3 + 2].y)) then begin result:=True; exit; end end; end; function PointInTriangleFan(const pt:point2d; const s:shape):Boolean; var pts : Point2dArray; i :Longint; begin pts := ShapePoints(s); result:=False; for i := 0 to Length(pts) - 3 do begin if PointInTriangle(pt, TriangleFrom( pts[0].x,pts[0].y, pts[i + 1].x, pts[i + 1].y, pts[i + 2].x, pts[i + 2].y)) then begin result:=True; exit; end end; end; function PointInTriangleStrip(const pt:point2d; const s:shape):Boolean; var pts : Point2dArray; i :Longint; begin pts := ShapePoints(s); result:=False; for i := 0 to Length(pts) - 3 do begin if PointInTriangle(pt, TriangleFrom( pts[i].x,pts[i].y, pts[i + 1].x, pts[i + 1].y, pts[i + 2].x, pts[i + 2].y)) then begin result:=True; exit; end end; end; function PointInShape(const pt: Point2d; s:Shape):Boolean; var k : ShapeKind; pts : Point2dArray; begin k := PrototypeKind(s^.prototype); pts := ShapePoints(s); case k of pkPoint: result := PointOnPoint(pt, s^.pt); pkCircle: result := PointInCircle(pt, CircleAt(s^.pt,RoundInt(PointPointDistance(pts[0], pts[1])))); // pkEllipse: result := 2; pkLine: result := PointOnLine(pt, Linefrom(pts[0],pts[1])); pkTriangle: result := PointInTriangle(pt,TriangleFrom(pts[0],pts[1],pts[2])); pkLineList: result := PointOnLineList(pt,s); pkLineStrip: result := PointOnLineStrip(pt,s); //pkPolygon: result := 3; pkTriangleStrip: result := PointInTriangleStrip(pt,s); pkTriangleFan: result := PointInTriangleFan(pt,s); pkTriangleList: result := PointInTriangleList(pt,s); else begin RaiseException('Shape not Recognized when checking if point is in shape.'); exit; end; end; end; function LinesFromShapeAsTriangleStrip(s: shape): LinesArray; overload; var pts:Point2DArray; i:Longint; begin pts:= ShapePoints(s); //WriteLn('ShapeLineCount: ', ShapeLineCount(s)); SetLength(result, ShapeLineCount(s)); if Length(result) <= 0 then exit; for i := 0 to Length(pts) - 3 do begin result[i * 2] := LineFrom(pts[i], pts[i + 1]); result[i * 2 + 1] := LineFrom(pts[i], pts[i + 2]); //WriteLn(' Line ', LineToString(result[i*2])); //WriteLn(' Line ', LineToString(result[i*2 + 1])); end; result[high(result)] := LineFrom(pts[High(pts) - 1], pts[High(pts)]); //WriteLn(' Line ', LineToString(result[High(result)])); end; function LinesFrom(s: shape): LinesArray; overload; var k: ShapeKind; pts: Point2DArray; begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'LinesFrom(const tri: Triangle): LinesArray', ''); {$ENDIF} k := PrototypeKind(s^.prototype); pts := ShapePoints(s); case k of pkCircle: SetLength(result, 0); //pkLine: result := PointOnLine(pt, Linefrom(pts[0],pts[1])); pkTriangle: result := LinesFrom(TriangleFrom(pts[0],pts[1],pts[2])); //pkLineList: result := PointOnLineList(pt,s); //pkLineStrip: result := PointOnLineStrip(pt,s); pkTriangleStrip: result := LinesFromShapeAsTriangleStrip(s); //pkTriangleFan: result := PointInTriangleFan(pt,s); //pkTriangleList: result := PointInTriangleList(pt,s); else begin RaiseException('LinesFrom not implemented with this kind of shape.'); exit; end; end; {$IFDEF TRACE} TraceExit('sgGeometry', 'LinesFrom(const tri: Triangle): LinesArray', ''); {$ENDIF} end; function ShapeAABB(s: Shape): Rectangle; var pts : Point2DArray; minPt, maxPt: Point2D; i, max: Longint; r, l, t, b, temp: Single; subRect: Rectangle; kind: ShapeKind; begin pts := ShapePoints(s); result := RectangleFrom(0,0,0,0); kind := ShapeShapeKind(s); if (Longint(kind) = -1) or (Length(pts) < MinimumPointsForKind(kind)) then exit; minPt := pts[0]; maxPt := minPt; if kind = pkPoint then //do nothing as the point is the maximum else if kind = pkCircle then begin temp := PointPointDistance(pts[0], pts[1]); minPt.x := minPt.x - temp; minPt.y := minPt.y - temp; maxPt.x := maxPt.x + temp; maxPt.y := maxPt.y + temp; end else begin case kind of pkLine: max := 1; // line from 0 to 1 pkTriangle: max := 2; // triangle 0,1,2 pkLineList: max := High(pts) - (Length(pts) mod 2); // even numbers pkLineStrip: max := High(pts); // all points in strip pkTriangleList: max := High(pts) - (Length(pts) mod 3); //groups of 3 pkTriangleStrip: max := High(pts); pkTriangleFan: max := High(pts); else max := High(pts); end; for i := low(pts) + 1 to max do begin if pts[i].x < minPt.x then minPt.x := pts[i].x else if pts[i].x > maxPt.x then maxPt.x := pts[i].x; if pts[i].y < minPt.y then minPt.y := pts[i].y else if pts[i].Y > maxPt.y then maxPt.y := pts[i].y; end; end; for i := Low(s^.subShapes) to High(s^.subShapes) do begin subRect := ShapeAABB(s^.subShapes[i]); r := RectangleRight(subRect); l := RectangleLeft(subRect); t := RectangleTop(subRect); b := RectangleBottom(subRect); if l < minPt.x then minPt.x := l; if r > maxPt.x then maxPt.x := r; if t < minPt.y then minPt.y := t; if b > maxPt.y then maxPt.y := b; end; result := RectangleFrom(minPt, maxPt); //DrawRectangle(colorYellow, result); end; function ShapeCircle(s: Shape): Circle; begin result := ShapeCircle(s, PointAt(0,0)); end; function ShapeCircle(s: Shape; const offset: Point2D): Circle; var pts: Point2DArray; begin pts := ShapePoints(s); if length(pts) < 2 then begin result := CircleAt(0,0,0); exit; end; result := CircleAt(PointAdd(pts[0], offset), RoundInt(PointPointDistance(pts[0], pts[1]))); end; function ShapeLine(s: Shape): LineSegment; begin result := ShapeLine(s, PointAt(0,0)); end; function ShapeLine(s: Shape; const offset: Point2D): LineSegment; var pts: Point2DArray; begin pts := ShapePoints(s); if length(pts) < 2 then begin result := LineFrom(0,0,0,0); exit; end; result := LineFrom(PointAdd(pts[0], offset), PointAdd(pts[1], offset)); end; function ShapeTriangle(s: Shape): Triangle; begin result := ShapeTriangle(s, PointAt(0,0)); end; function ShapeTriangle(s: Shape; const offset: Point2D): Triangle; var pts: Point2DArray; begin pts := ShapePoints(s); if length(pts) < 3 then begin result := TriangleFrom(0,0,0,0,0,0); exit; end; result := TriangleFrom( PointAdd(pts[0], offset), PointAdd(pts[1], offset), PointAdd(pts[2], offset)); end; function ShapeTriangleCount(s: Shape): Longint; begin result := ShapeKindTriangleCount(s, ShapeShapeKind(s)); end; function ShapeKindTriangleCount(s: Shape; kind: ShapeKind): Longint; var pts: Longint; begin result := 0; pts := ShapePointCount(s); case kind of pkCircle: result := 0; pkLine: result := 0; pkTriangle: result := 1; pkLineList: result := 0; pkLineStrip: result := 0; //pkPolygon: result := 3; pkTriangleStrip, pkTriangleFan: result := pts - 2; pkTriangleList: result := pts div 3; else begin RaiseException('Shape not Recognized when getting line out of shape.'); exit; end; end; end; function ShapeLineCount(s: Shape): Longint; begin if assigned(s) then result := ShapeKindLineCount(s, ShapeShapeKind(s)) else result := 0; end; function ShapeKindLineCount(s: Shape; kind: ShapeKind): Longint; var pts: Longint; begin result := 0; pts := ShapePointCount(s); case kind of pkCircle: result := 0; pkLine: result := 1; pkTriangle: result := 3; pkLineList: result := pts div 2; pkLineStrip: result := pts - 1; //pkPolygon: result := 3; pkTriangleStrip, pkTriangleFan: begin result := 2 * pts - 3; if result < 0 then result := 0; end; pkTriangleList: result := (pts div 3) * 3; else begin RaiseException('Shape not Recognized when getting line out of shape.'); exit; end; end; end; function ShapeLines(s: Shape): LinesArray; begin if assigned(s) then result := ShapeLines(s, ShapeShapeKind(s), PointAt(0,0)) else result := nil; end; function ShapeLines(s: Shape; kind: ShapeKind): LinesArray; begin result := ShapeLines(s, kind, PointAt(0,0)); end; function ShapeLines(s: Shape; kind: ShapeKind; const offset: Point2D): LinesArray; var pts,pts1: Point2DArray; i: Longint; begin pts := ShapePoints(s); SetLength(pts1, length(pts)); if length(pts) < 2 then begin SetLength(result, 0); exit; end; if not ((kind = pkLineList) or (kind = pkLineStrip)) then exit; if kind = pkLineList then SetLength(result, Length(pts) div 2) else SetLength(result, Length(pts) - 1); for i := 0 to high(pts1) do pts1[i] := PointAdd(pts[i], offset); for i := 0 to High(result) do begin if kind = pkLineList then result[i] := LineFrom(pts1[i * 2], pts1[i * 2 + 1]) else // strip result[i] := LineFrom(pts1[i], pts1[i + 1]); end; end; function ShapeTriangles(s: Shape): TriangleArray; overload; begin if assigned(s) then result := ShapeTriangles(s, ShapeShapeKind(s)) else result := nil; end; function ShapeTriangles(s: Shape; kind: ShapeKind): TriangleArray; begin result := ShapeTriangles(s, kind, PointAt(0,0)); end; function ShapeTriangles(s: Shape; kind: ShapeKind; const offset: Point2D): TriangleArray; var pts, pts1: Point2DArray; i: Longint; begin SetLength(result, 0); if not ((kind = pkTriangleStrip) or (kind = pkTriangleFan) or (kind = pkTriangleList) or (kind = pkTriangle)) then exit; pts := ShapePoints(s); if length(pts) < 3 then begin exit; end; if kind = pkTriangleList then SetLength(result, Length(pts) div 3) else if kind = pkTriangle then SetLength(result, 1) else SetLength(result, Length(pts) - 2); SetLength(pts1, Length(pts)); for i := 0 to high(pts) do pts1[i] := PointAdd(pts[i], offset); for i := 0 to High(result) do begin case kind of pkTriangle: result[i] := TriangleFrom(pts1[i], pts1[i + 1], pts1[i + 2]); pkTriangleList: result[i] := TriangleFrom(pts1[i * 3], pts1[i * 3 + 1], pts1[i * 3 + 2]); pkTriangleStrip:result[i] := TriangleFrom(pts1[i], pts1[i + 1], pts1[i + 2]); pkTriangleFan: result[i] := TriangleFrom(pts1[0], pts1[i + 1], pts1[i + 2]); end; end; end; function ShapeRectangleIntersect(s: Shape; const rect: Rectangle): Boolean; var kind: ShapeKind; i: Longint; begin result := false; if not assigned(s) then exit; if not RectanglesIntersect(rect, ShapeAABB(s)) then exit; kind := ShapeShapeKind(s); case kind of pkPoint: result := true; pkCircle: result := CircleRectCollision(ShapeCircle(s), rect); pkLine: result := RectLineCollision(rect, ShapeLine(s)); pkTriangle: result := TriangleRectangleIntersect(ShapeTriangle(s), rect); pkLineList, pkLineStrip: result := LinesRectIntersect(ShapeLines(s, kind), rect); pkTriangleStrip, pkTriangleFan, pkTriangleList: result := TrianglesRectangleIntersect(ShapeTriangles(s, kind), rect); end; if not result then begin //Check sub shapes for i := 0 to High(s^.subShapes) do begin // if we have an intersection then return true if ShapeRectangleIntersect(s^.subShapes[i], rect) then begin result := true; exit; end; end; end; end; function ShapeVectorOutOfRect(s: shape; const bounds: Rectangle; const velocity: Vector ): vector; var maxIdx :Longint; begin result := VectorOverLinesFromLines(LinesFrom(bounds),LinesFrom(s), velocity, maxIdx); end; //============================================================================= function PointPrototypeFrom(const pt: Point2D): ShapePrototype; begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'PointPrototypeFrom(const pt: Point2D): ShapePrototype', ''); {$ENDIF} New(result); SetLength(result^.points, 1); result^.points[0] := pt; result^.kind := pkPoint; {$IFDEF TRACE} TraceExit('sgGeometry', 'PointPrototypeFrom(const pt: Point2D): ShapePrototype', ''); {$ENDIF} end; function CirclePrototypeFrom(const pt: Point2D; r: Single): ShapePrototype; begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'CirclePrototypeFrom(const pt: Point2D', ''); {$ENDIF} New(result); SetLength(result^.points, 2); result^.points[0] := pt; result^.points[1] := PointAt(r, r); result^.kind := pkCircle; {$IFDEF TRACE} TraceExit('sgGeometry', 'CirclePrototypeFrom(const pt: Point2D', ''); {$ENDIF} end; // function EllipsePrototypeFrom(const pt: Point2D; w, h: Single): ShapePrototype; // begin // New(result); // // SetLength(result^.points, 2); // result^.points[0] := pt; // result^.points[1] := PointAt(w, h); // result^.kind := pkEllipse; // end; function LinePrototypeFrom(const startPt, endPt: Point2D): ShapePrototype; begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'LinePrototypeFrom(const startPt, endPt: Point2D): ShapePrototype', ''); {$ENDIF} New(result); SetLength(result^.points, 2); result^.points[0] := startPt; result^.points[1] := endPt; result^.kind := pkLine; {$IFDEF TRACE} TraceExit('sgGeometry', 'LinePrototypeFrom(const startPt, endPt: Point2D): ShapePrototype', ''); {$ENDIF} end; function TrianglePrototypeFrom(const pt1, pt2, pt3: Point2D): ShapePrototype; begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'TrianglePrototypeFrom(const pt1, pt2, pt3: Point2D): ShapePrototype', ''); {$ENDIF} New(result); SetLength(result^.points, 3); result^.points[0] := pt1; result^.points[1] := pt2; result^.points[2] := pt3; result^.kind := pkTriangle; {$IFDEF TRACE} TraceExit('sgGeometry', 'TrianglePrototypeFrom(const pt1, pt2, pt3: Point2D): ShapePrototype', ''); {$ENDIF} end; function LineListPrototypeFrom(const points: Point2DArray): ShapePrototype; begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'LineListPrototypeFrom(const points: Point2DArray): ShapePrototype', ''); {$ENDIF} result := PrototypeFrom(points, pkLineList); {$IFDEF TRACE} TraceExit('sgGeometry', 'LineListPrototypeFrom(const points: Point2DArray): ShapePrototype', ''); {$ENDIF} end; function LineStripPrototypeFrom(const points: Point2DArray): ShapePrototype; begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'LineStripPrototypeFrom(const points: Point2DArray): ShapePrototype', ''); {$ENDIF} result := PrototypeFrom(points, pkLineStrip); {$IFDEF TRACE} TraceExit('sgGeometry', 'LineStripPrototypeFrom(const points: Point2DArray): ShapePrototype', ''); {$ENDIF} end; // function PolygonPrototypeFrom(const points: Point2DArray): ShapePrototype; // begin // {$IFDEF TRACE} // TraceEnter('sgGeometry', 'PolygonPrototypeFrom(const points: Point2DArray): ShapePrototype', ''); // {$ENDIF} // // result := PrototypeFrom(points, pkPolygon); // // {$IFDEF TRACE} // TraceExit('sgGeometry', 'PolygonPrototypeFrom(const points: Point2DArray): ShapePrototype', ''); // {$ENDIF} // end; function TriangleStripPrototypeFrom(const points: Point2DArray): ShapePrototype; begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'TriangleStripPrototypeFrom(const points: Point2DArray): ShapePrototype', ''); {$ENDIF} result := PrototypeFrom(points, pkTriangleStrip); {$IFDEF TRACE} TraceExit('sgGeometry', 'TriangleStripPrototypeFrom(const points: Point2DArray): ShapePrototype', ''); {$ENDIF} end; function TriangleFanPrototypeFrom(const points: Point2DArray): ShapePrototype; begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'TriangleFanPrototypeFrom(const points: Point2DArray): ShapePrototype', ''); {$ENDIF} result := PrototypeFrom(points, pkTriangleFan); {$IFDEF TRACE} TraceExit('sgGeometry', 'TriangleFanPrototypeFrom(const points: Point2DArray): ShapePrototype', ''); {$ENDIF} end; function TriangleListPrototypeFrom(const points: Point2DArray): ShapePrototype; begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'TriangleListPrototypeFrom(const points: Point2DArray): ShapePrototype', ''); {$ENDIF} result := PrototypeFrom(points, pkTriangleList); {$IFDEF TRACE} TraceExit('sgGeometry', 'TriangleListPrototypeFrom(const points: Point2DArray): ShapePrototype', ''); {$ENDIF} end; function PrototypeFrom(const points: Point2DArray; kind:ShapeKind): ShapePrototype; begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'PrototypeFrom(const points: Point2DArray', ''); {$ENDIF} if Length(points) < MinimumPointsForKind(kind) then begin RaiseException('Insufficient points assigned to shape given its kind. Min is ' + IntToStr(MinimumPointsForKind(kind)) + ' was supplied ' + IntToStr(Length(points))); exit; end; New(result); PrototypeSetKind(result, kind); PrototypeSetPoints(result, points); result^.shapeCount := 0; {$IFDEF TRACE} TraceExit('sgGeometry', 'PrototypeFrom(const points: Point2DArray', ''); {$ENDIF} end; procedure FreePrototype(var p: ShapePrototype); begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'FreePrototype(var p: ShapePrototype)', ''); {$ENDIF} if not Assigned(p) then exit; if p^.shapeCount > 0 then begin RaiseWarning('Freeing prototype while it is still used by ' + IntToStr(p^.shapeCount) + ' shapes.'); end; SetLength(p^.points, 0); Dispose(p); CallFreeNotifier(p); p := nil; {$IFDEF TRACE} TraceExit('sgGeometry', 'FreePrototype(var p: ShapePrototype)', ''); {$ENDIF} end; //============================================================================= function MinimumPointsForKind(k: ShapeKind): Longint; begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'MinimumPointsForKind(k: ShapeKind): Longint', ''); {$ENDIF} case k of pkPoint: result := 1; pkCircle: result := 2; // pkEllipse: result := 2; pkLine: result := 2; pkTriangle: result := 3; pkLineList: result := 2; pkLineStrip: result := 2; // pkPolygon: result := 3; pkTriangleStrip: result := 3; pkTriangleFan: result := 3; pkTriangleList: result := 3; end; {$IFDEF TRACE} TraceExit('sgGeometry', 'MinimumPointsForKind(k: ShapeKind): Longint', ''); {$ENDIF} end; function PrototypePointCount(p: ShapePrototype): Longint; begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'PrototypePointCount(p: ShapePrototype): Longint', ''); {$ENDIF} if not assigned(p) then result := 0 else result := Length(p^.points); {$IFDEF TRACE} TraceExit('sgGeometry', 'PrototypePointCount(p: ShapePrototype): Longint', ''); {$ENDIF} end; procedure PrototypeSetPoints(p: ShapePrototype; const points: Point2DArray); var i: Longint; begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'PrototypeSetPoints(p: ShapePrototype', ''); {$ENDIF} if not assigned(p) then exit; if Length(points) < MinimumPointsForKind(p^.kind) then begin RaiseException('Insufficient points assigned to shape given its kind. Min is ' + IntToStr(MinimumPointsForKind(p^.kind)) + ' was supplied ' + IntToStr(Length(points))); exit; end; SetLength(p^.points, Length(points)); for i := 0 to High(points) do begin p^.points[i] := points[i]; end; {$IFDEF TRACE} TraceExit('sgGeometry', 'PrototypeSetPoints(p: ShapePrototype', ''); {$ENDIF} end; function PrototypePoints(p: ShapePrototype): Point2DArray; begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'PrototypePoints(p: ShapePrototype): Point2DArray', ''); {$ENDIF} if not assigned(p) then SetLength(result,0) else result := p^.points; {$IFDEF TRACE} TraceExit('sgGeometry', 'PrototypePoints(p: ShapePrototype): Point2DArray', ''); {$ENDIF} end; procedure PrototypeSetKind(p: ShapePrototype; kind: ShapeKind); begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'PrototypeSetKind(p: ShapePrototype', ''); {$ENDIF} if not assigned(p) then begin RaiseException('No shape prototype supplied to set kind.'); exit; end; p^.kind := kind; case kind of pkPoint: p^.drawWith := @DrawShapeAsPoint; pkCircle: p^.drawWith := @DrawShapeAsCircle; // pkEllipse: p^.drawWith := @DrawShapeAsEllipse; pkLine: p^.drawWith := @DrawShapeAsLine; pkTriangle: p^.drawWith := @DrawShapeAsTriangle; pkLineList: p^.drawWith := @DrawShapeAsLineList; pkLineStrip: p^.drawWith := @DrawShapeAsLineStrip; // pkPolygon: p^.drawWith := @DrawShapeAsPolygon; pkTriangleStrip: p^.drawWith := @DrawShapeAsTriangleStrip; pkTriangleFan: p^.drawWith := @DrawShapeAsTriangleFan; pkTriangleList: p^.drawWith := @DrawShapeAsTriangleList; else p^.drawWith := nil; end; {$IFDEF TRACE} TraceExit('sgGeometry', 'PrototypeSetKind(p: ShapePrototype', ''); {$ENDIF} end; function PrototypeKind(p: ShapePrototype): ShapeKind; begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'PrototypeKind(p: ShapePrototype): ShapeKind', ''); {$ENDIF} if not assigned(p) then result := ShapeKind(-1) else result := p^.kind; {$IFDEF TRACE} TraceExit('sgGeometry', 'PrototypeKind(p: ShapePrototype): ShapeKind', ''); {$ENDIF} end; //============================================================================= function ShapeAtPoint(p: ShapePrototype; const pt: Point2D): Shape; begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'ShapeAtPoint(p: ShapePrototype', ''); {$ENDIF} New(result); result^.prototype := p; result^.pt := pt; result^.angle := 0.0; result^.scale := PointAt(1,1); result^.color := ColorWhite; SetLength(result^.subShapes, 0); if Assigned(p) then p^.shapeCount += 1; {$IFDEF TRACE} TraceExit('sgGeometry', 'ShapeAtPoint(p: ShapePrototype', ''); {$ENDIF} end; procedure FreeShape(var s: Shape); var i: Longint; begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'FreeShape(var s: Shape)', ''); {$ENDIF} if not Assigned(s) then exit; if Assigned(s^.prototype) then s^.prototype^.shapeCount -= 1; for i := 0 to High(s^.subShapes) do begin FreeShape(s^.subShapes[i]) end; SetLength(s^.subShapes, 0); Dispose(s); CallFreeNotifier(s); s := nil; {$IFDEF TRACE} TraceExit('sgGeometry', 'FreeShape(var s: Shape)', ''); {$ENDIF} end; procedure UpdateSubShapePoints(s: Shape; const parentM: Matrix2D); var m: Matrix2D; i: Longint; begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'UpdateSubShapePoints(s: Shape', ''); {$ENDIF} if not Assigned(s) then begin exit; end; // Copy the points from the prototype s^.ptBuffer := Copy(s^.prototype^.points, 0, Length(s^.prototype^.points)); // Scale, angle and translate based on this shape's position * parent's matrix //m := ScaleMatrix(s.scale) * RotationMatrix(s.angle) * TranslationMatrix(s.pt); m := ScaleRotateTranslateMatrix(s^.scale, s^.angle, s^.pt) * parentM; ApplyMatrix(m, s^.ptBuffer); for i := 0 to High(s^.subShapes) do begin UpdateSubShapePoints(s^.subShapes[i], m); end; {$IFDEF TRACE} TraceExit('sgGeometry', 'UpdateSubShapePoints(s: Shape', ''); {$ENDIF} end; procedure UpdateShapePoints(s: Shape); begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'UpdateShapePoints(s: Shape)', ''); {$ENDIF} UpdateSubShapePoints(s, IdentityMatrix()); {$IFDEF TRACE} TraceExit('sgGeometry', 'UpdateShapePoints(s: Shape)', ''); {$ENDIF} end; function ShapePoints(s: Shape): Point2DArray; begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'ShapePoints(s: Shape): Point2DArray', ''); {$ENDIF} if not Assigned(s) then begin SetLength(result, 0); exit; end; if not Assigned(s^.ptBuffer) then begin UpdateShapePoints(s); end; result := s^.ptBuffer; {$IFDEF TRACE} TraceExit('sgGeometry', 'ShapePoints(s: Shape): Point2DArray', ''); {$ENDIF} end; function ShapePointCount(s: Shape): Longint; begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'ShapePointCount(s: Shape): Longint', ''); {$ENDIF} if not Assigned(s) then begin result := 0; exit; end; result := PrototypePointCount(s^.prototype); {$IFDEF TRACE} TraceExit('sgGeometry', 'ShapePointCount(s: Shape): Longint', ''); {$ENDIF} end; procedure ShapeSetAngle(s: Shape; angle: Single); begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'ShapeSetAngle(s: Shape', ''); {$ENDIF} if not Assigned(s) then begin exit; end; s^.angle := angle; {$IFDEF TRACE} TraceExit('sgGeometry', 'ShapeSetAngle(s: Shape', ''); {$ENDIF} end; function ShapeAngle(s: Shape): Single; begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'ShapeAngle(s: Shape): Single', ''); {$ENDIF} if not Assigned(s) then begin result := 0; exit; end; result := s^.angle; {$IFDEF TRACE} TraceExit('sgGeometry', 'ShapeAngle(s: Shape): Single', ''); {$ENDIF} end; procedure ShapeSetScale(s: Shape; const scale: Point2D); begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'ShapeSetScale(s: Shape', ''); {$ENDIF} if not Assigned(s) then begin exit; end; s^.scale := scale; {$IFDEF TRACE} TraceExit('sgGeometry', 'ShapeSetScale(s: Shape', ''); {$ENDIF} end; function ShapeScale(s: Shape): Point2D; begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'ShapeScale(s: Shape): Point2D', ''); {$ENDIF} if not Assigned(s) then begin result := PointAt(0,0); exit; end; result := s^.scale; {$IFDEF TRACE} TraceExit('sgGeometry', 'ShapeScale(s: Shape): Point2D', ''); {$ENDIF} end; function ShapeShapePrototype(s: Shape): ShapePrototype; begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'ShapeShapePrototype(s: Shape): ShapePrototype', ''); {$ENDIF} if not Assigned(s) then begin result := nil; exit; end; result := s^.prototype; {$IFDEF TRACE} TraceExit('sgGeometry', 'ShapeShapePrototype(s: Shape): ShapePrototype', ''); {$ENDIF} end; procedure ShapeSetPrototype(s: Shape; p: ShapePrototype); begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'ShapeSetPrototype(s: Shape', ''); {$ENDIF} if not Assigned(s) then exit; if Assigned(s^.prototype) then s^.prototype^.shapeCount -= 1; s^.prototype := p; if Assigned(s^.prototype) then s^.prototype^.shapeCount += 1; {$IFDEF TRACE} TraceExit('sgGeometry', 'ShapeSetPrototype(s: Shape', ''); {$ENDIF} end; procedure ShapeAddSubShape(parent, child: Shape); begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'ShapeAddSubShape(parent, child: Shape)', ''); {$ENDIF} if not Assigned(parent) then exit; if not Assigned(child) then exit; SetLength(parent^.subShapes, Length(parent^.subShapes) + 1); parent^.subShapes[High(parent^.subShapes)] := child; {$IFDEF TRACE} TraceExit('sgGeometry', 'ShapeAddSubShape(parent, child: Shape)', ''); {$ENDIF} end; function ShapeColor(s: Shape): Color; begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'ShapeColor(s: Shape): Color', ''); {$ENDIF} if not Assigned(s) then begin result := ColorBlack; exit; end; result := s^.color; {$IFDEF TRACE} TraceExit('sgGeometry', 'ShapeColor(s: Shape): Color', ''); {$ENDIF} end; procedure ShapeSetColor(s: Shape; c: Color); begin {$IFDEF TRACE} TraceEnter('sgGeometry', 'ShapeSetColor(s: Shape', ''); {$ENDIF} if not Assigned(s) then begin exit; end; s^.color := c; {$IFDEF TRACE} TraceExit('sgGeometry', 'ShapeSetColor(s: Shape', ''); {$ENDIF} end; function ShapeShapeKind(s: Shape): ShapeKind; begin if not assigned(s) then begin result := ShapeKind(-1); exit; end; result := PrototypeKind(ShapeShapePrototype(s)); end; //============================================================================= procedure DrawShapeAsPoint(dest: Bitmap; s:Shape; filled: Boolean; const offset: Point2D); overload; var pts: Point2DArray; begin pts := ShapePoints(s); if length(pts) = 0 then exit; DrawPixel(dest, s^.color, PointAdd(pts[0], offset)); end; procedure DrawShapeAsCircle(dest: Bitmap; s:Shape; filled : Boolean; const offset: point2D); overload; var // r: Single; // pts: Point2DArray; c: Circle; begin c := ShapeCircle(s); //pts := ShapePoints(s); //if length(pts) < 2 then exit; //r := PointPointDistance(pts[0], pts[1]); if filled then FillCircle(s^.color, c, OptionDrawTo(dest)) //PointAdd(pts[0], offset), Round(r)); else DrawCircle(s^.color, c, OptionDrawTo(dest)) end; // procedure DrawShapeAsEllipse(dest: Bitmap; s:Shape; filled: Boolean; const offset: Point2D); overload; // var // pts: Point2DArray; // begin // pts := ShapePoints(s); // if length(pts) < 2 then exit; // // DrawEllipse(dest, s^.color, filled, // Round(pts[0].x+offset.X), // Round(pts[0].y+offset.Y), // Round(pts[1].x) - Round(pts[0].x), // Round(pts[1].y) - Round(pts[0].y)); // end; procedure DrawShapeAsLine(dest: Bitmap; s:Shape; filled: Boolean; const offset: Point2D); overload; var //pts: Point2DArray; ln: LineSegment; begin ln := ShapeLine(s); // pts := ShapePoints(s); // if length(pts) < 2 then exit; DrawLine(s^.color, ln, OptionDrawTo(dest)); //PointAdd(pts[0], offset), PointAdd(pts[1], offset)); end; procedure _DrawTriangles(dest: Bitmap; s: Shape; filled: Boolean; const offset: Point2D; kind: ShapeKind); var i: Longint; tri: TriangleArray; begin tri := ShapeTriangles(s, kind); for i := 0 to High(tri) do begin if filled then FillTriangle(s^.color, tri[i]) else DrawTriangle(s^.color, tri[i]); end; end; procedure DrawShapeAsTriangle(dest: Bitmap; s:Shape; filled: Boolean; const offset: Point2D); overload; // var // //pts: Point2DArray; // tri: Triangle; begin _DrawTriangles(dest, s, filled, offset, pkTriangle); // tri := ShapeTriangle(s); // // // pts := ShapePoints(s); // // if length(pts) < 3 then exit; // // if filled then // FillTriangle(dest, s^.color, tri) // //FillTriangle(dest, s^.color, pts[0].x+offset.X, pts[0].y+offset.Y, pts[1].x+offset.X, pts[1].y+offset.Y, pts[2].x+offset.X, pts[2].y+offset.Y) // else // DrawTriangle(dest, s^.color, tri); // //DrawTriangle(dest, s^.color, pts[0].x+offset.X, pts[0].y+offset.Y, pts[1].x+offset.X, pts[1].y+offset.Y, pts[2].x+offset.X, pts[2].y+offset.Y); end; procedure _DrawLines(dest: Bitmap; s: Shape; const offset: Point2D; kind: ShapeKind); var lines: LinesArray; i: Longint; begin lines := ShapeLines(s, kind, offset); for i := 0 to High(lines) do begin DrawLine(s^.color, lines[i], OptionDrawTo(dest)); end; end; procedure DrawShapeAsLineList(dest: Bitmap; s: Shape; filled: Boolean; const offset: Point2D); begin _DrawLines(dest, s, offset, pkLineList); end; // var // i: Longint; // pts: Point2DArray; // begin // pts := ShapePoints(s); // // for i := 0 to Length(pts) div 2 - 1 do // begin // DrawLine(dest, s^.color, PointAdd(pts[i * 2], offset), PointAdd(pts[i * 2 + 1], offset)); // end; // end; procedure DrawShapeAsLineStrip(dest: Bitmap; s: Shape; filled: Boolean; const offset: Point2D); begin _DrawLines(dest, s, offset, pkLineStrip); end; // var // i: Longint; // pts: Point2DArray; // begin // pts := ShapePoints(s); // // for i := 0 to Length(pts) - 2 do // begin // DrawLine(dest, s^.color, PointAdd(pts[i], offset), PointAdd(pts[i+ 1], offset)); // end; // end; {procedure DrawShapeAsPolygon(dest: Bitmap; s: Shape; filled: Boolean; const offset: Point2D); var i, l: Longint; pts: Point2DArray; begin pts := ShapePoints(s); if Length(pts) < 3 then exit; l := Length(pts); if filled then begin for i := 0 to Length(pts) - 3 do begin FillTriangle(dest, s^.color, pts[i].x,pts[i].y, pts[i + 1].x, pts[i + 1].y, pts[(i + 2) mod l].x, pts[(i + 2) mod l].y); end; end else begin for i := 0 to Length(pts) - 2 + 1 do begin DrawLine(dest, s^.color, pts[i], pts[(i+ 1) mod l]); end; end; end;} // procedure DrawTriangleFan(dest: Bitmap; s: Shape; const offset: Point2D); // // var // // i: Longint; // // pts: Point2DArray; // begin // DrawTriangleFan(dest, s, false, offset); // // pts := ShapePoints(s); // // // // for i := 0 to Length(pts) - 3 do // // begin // // DrawTriangle(dest, s^.color, // // pts[0].x+offset.X,pts[0].y+offset.Y, // // pts[i + 1].x+offset.X, pts[i + 1].y+offset.Y, // // pts[i + 2].x+offset.X, pts[i + 2].y+offset.Y); // // end; // end; // // procedure FillTriangleFan(dest: Bitmap; s: Shape; const offset: Point2D); // // var // // i: Longint; // // pts: Point2DArray; // begin // DrawTriangleFan(dest, s, true, offset); // // pts := ShapePoints(s); // // // // for i := 0 to Length(pts) - 3 do // // begin // // FillTriangle(dest, s^.color, // // pts[0].x+offset.X,pts[0].y+offset.Y, // // pts[i + 1].x+offset.X, pts[i + 1].y+offset.Y, // // pts[i + 2].x+offset.X, pts[i + 2].y+offset.Y); // // end; // end; procedure DrawShapeAsTriangleFan(dest: Bitmap; s: Shape; filled: Boolean; const offset: Point2D); begin //if filled then FillTriangleFan(dest, s, offset) else DrawTriangleFan(dest, s, offset); _DrawTriangles(dest, s, filled, offset, pkTriangleFan); end; // procedure DrawTriangleStrip(dest: Bitmap; s: Shape; const offset: Point2D); // begin // DrawTriangleStrip(dest, s, false, offset); // end; // // var // // i: Longint; // // pts: Point2DArray; // // begin // // pts := ShapePoints(s); // // // // for i := 0 to Length(pts) - 3 do // // begin // // DrawTriangle(dest, s^.color, // // pts[i].x+offset.X,pts[i].y+offset.Y, // // pts[i + 1].x+offset.X, pts[i + 1].y+offset.Y, // // pts[i + 2].x+offset.X, pts[i + 2].y+offset.Y); // // end; // // end; // // procedure FillTriangleStrip(dest: Bitmap; s: Shape; const offset: Point2D); // begin // DrawTriangleStrip(dest, s, true, offset); // end; // // // var // // i: Longint; // // pts: Point2DArray; // // begin // // pts := ShapePoints(s); // // // // for i := 0 to Length(pts) - 3 do // // begin // // FillTriangle(dest, s^.color, // // pts[i].x+offset.X,pts[i].y+offset.Y, // // pts[i + 1].x+offset.X, pts[i + 1].y+offset.Y, // // pts[i + 2].x+offset.X, pts[i + 2].y+offset.Y); // // end; // // end; procedure DrawShapeAsTriangleStrip(dest: Bitmap; s: Shape; filled: Boolean; const offset: Point2D); begin _DrawTriangles(dest, s, filled, offset, pkTriangleStrip); //if filled then FillTriangleStrip(dest, s, offset) else DrawTriangleStrip(dest, s, offset); end; // procedure DrawTriangleList(dest: Bitmap; s: Shape; const offset: Point2D); // begin // DrawTriangleList(dest, s, false, offset); // end; // // var // // i: Longint; // // pts: Point2DArray; // // begin // // pts := ShapePoints(s); // // // // for i := 0 to Length(pts) div 3 - 1 do // // begin // // DrawTriangle(dest, s^.color, // // pts[i * 3].x+offset.X, pts[i * 3].y+offset.Y, // // pts[i * 3 + 1].x+offset.X, pts[i * 3 + 1].y+offset.Y, // // pts[i * 3 + 2].x+offset.X, pts[i * 3 + 2].y+offset.Y); // // end; // // end; // // procedure FillTriangleList(dest: Bitmap; s: Shape; const offset: Point2D); // begin // DrawTriangleList(dest, s, true, offset); // end; // // var // // i: Longint; // // pts: Point2DArray; // // begin // // pts := ShapePoints(s); // // // // for i := 0 to Length(pts) div 3 - 1 do // // begin // // FillTriangle(dest, s^.color, // // pts[i * 3].x+offset.X, pts[i * 3].y+offset.Y, // // pts[i * 3 + 1].x+offset.X, pts[i * 3 + 1].y+offset.Y, // // pts[i * 3 + 2].x+offset.X, pts[i * 3 + 2].y+offset.Y); // // end; // // end; procedure DrawShapeAsTriangleList(dest: Bitmap; s: Shape; filled: Boolean; const offset: Point2D); begin _DrawTriangles(dest, s, filled, offset, pkTriangleList); //if filled then FillTriangleList(dest, s, offset) else DrawTriangleList(dest, s, offset); end; procedure DrawShape(dest: Bitmap; s: Shape; filled: Boolean; const offset: Point2D); overload; var i: Longint; begin s^.prototype^.drawWith(dest, s, filled, offset); for i := 0 to High(s^.subShapes) do begin DrawShape(dest, s^.subShapes[i], filled, offset); end; end; procedure DrawShape(dest: Bitmap; s: Shape; filled: Boolean); overload; begin DrawShape(dest, s, filled, PointAt(0,0)); end; procedure DrawShape(dest: Bitmap; s: Shape); overload; begin DrawShape(dest, s, false, PointAt(0,0)); end; procedure FillShape(dest: Bitmap; s: Shape); overload; begin DrawShape(dest, s, true, PointAt(0,0)); end; procedure DrawShape(s: Shape; filled: Boolean); overload; begin DrawShape(screen, s, filled, PointAt(-CameraX(), -CameraY())); end; procedure DrawShape(s: Shape); overload; begin DrawShape(screen, s, false, PointAt(-CameraX(), -CameraY())); end; procedure FillShape(s: Shape); overload; begin DrawShape(screen, s, true, PointAt(-CameraX, -CameraY)); end; procedure DrawShapeOnScreen(s: Shape; filled: Boolean); overload; begin DrawShape(screen, s, filled); end; procedure DrawShapeOnScreen(s: Shape); overload; begin DrawShapeOnScreen(s, false); end; procedure FillShapeOnScreen(s: Shape); overload; begin DrawShapeOnScreen(s, true); end; function SpriteShapeCollision(s: Sprite; shp: Shape): Boolean; overload; begin result := false; if s = nil then exit; if not ShapeRectangleIntersect(shp, SpriteCollisionRectangle(s)) then exit; // Check pixel level details if SpriteCollisionKind(s) = AABBCollisions then result := true else //TODO: add pixel level shape collisions result := true; //CellRectCollision(s^.collisionBitmap, SpriteCurrentCell(s), Round(s^.position.x), Round(s^.position.y), rect); end; end.
PROGRAM GetParameters(INPUT, OUTPUT); USES GPC; VAR Copy, Stringer: STRING; {Print parameters Querystring} PROCEDURE GetQueryStringParameters(Text: STRING); VAR i, Indexer, Count: INTEGER; BEGIN {GetQueryStringParameters} Copy := 'key'; FOR i := 1 to Length(Text) DO BEGIN {Print key} IF Copy = 'key' THEN IF Text[i] <> '=' THEN WRITE(Text[i]) ELSE BEGIN Copy := 'value'; WRITE(': '); CONTINUE END; {Print value} IF Copy = 'value' THEN IF Text[i] <> '&' THEN WRITE(Text[i]) ELSE BEGIN Copy := 'key'; WRITELN; CONTINUE END END END; {GetQueryStringParameters} BEGIN {GetParameters} WRITELN('Content-Type: text/plain'); WRITELN; Stringer := GetEnv('QUERY_STRING'); WRITELN('All parametrs:'); GetQueryStringParameters(Stringer); END. {GetParameters}
unit ibSHDDLExtractorEditors; interface uses SysUtils, Classes, DesignIntf, TypInfo, SHDesignIntf, ibSHDesignIntf, ibSHCommonEditors; type // -> Property Editors TibSHDDLExtractorPropEditor = class(TibBTPropertyEditor) private FDDLExtractor: IibSHDDLExtractor; FValues: string; procedure Prepare; public constructor Create(APropertyEditor: TObject); override; destructor Destroy; override; function GetAttributes: TPropertyAttributes; override; function GetValue: string; override; procedure GetValues(AValues: TStrings); override; procedure SetValue(const Value: string); override; procedure Edit; override; property DDLExtractor: IibSHDDLExtractor read FDDLExtractor; end; IibSHDDLExtractorModePropEditor = interface ['{030422C2-B39F-4A43-B9EF-AD15560D447D}'] end; IibSHDDLExtractorHeaderPropEditor = interface ['{A13FA874-A4EA-4D2E-8CF5-BE89FF026A7B}'] end; TibSHDDLExtractorModePropEditor = class(TibSHDDLExtractorPropEditor, IibSHDDLExtractorModePropEditor); TibSHDDLExtractorHeaderPropEditor = class(TibSHDDLExtractorPropEditor, IibSHDDLExtractorHeaderPropEditor); implementation uses ibSHConsts, ibSHValues; { TibSHDDLExtractorPropEditor } constructor TibSHDDLExtractorPropEditor.Create(APropertyEditor: TObject); begin inherited Create(APropertyEditor); Supports(Component, IibSHDDLExtractor, FDDLExtractor); Assert(DDLExtractor <> nil, 'DDLExtractor = nil'); Prepare; end; destructor TibSHDDLExtractorPropEditor.Destroy; begin FDDLExtractor := nil; inherited Destroy; end; procedure TibSHDDLExtractorPropEditor.Prepare; begin if Supports(Self, IibSHDDLExtractorModePropEditor) then FValues := FormatProps(ExtractModes); if Supports(Self, IibSHDDLExtractorHeaderPropEditor) then FValues := FormatProps(ExtractHeaders); end; function TibSHDDLExtractorPropEditor.GetAttributes: TPropertyAttributes; begin Result := inherited GetAttributes; Result := [paValueList]; end; function TibSHDDLExtractorPropEditor.GetValue: string; begin Result := inherited GetValue; end; procedure TibSHDDLExtractorPropEditor.GetValues(AValues: TStrings); begin inherited GetValues(AValues); AValues.Text := FValues; end; procedure TibSHDDLExtractorPropEditor.SetValue(const Value: string); begin inherited SetValue(Value); if Designer.CheckPropValue(Value, FValues) then inherited SetStrValue(Value); end; procedure TibSHDDLExtractorPropEditor.Edit; begin inherited Edit; end; end.
unit URegularFunctions; interface function convert_mass_to_volume_fractions( mass_fractions: array of real; density: array of real): array of real; function convert_mass_to_mole_fractions( mass_fractions: array of real; mr: array of real): array of real; function get_flow_density(mass_fractions: array of real; density: array of real): real; function get_average_mol_mass(mass_fractions: array of real; mr:array of real): real; function get_flow_cp(mass_fractions: array of real; coeffs: array of array of real; temperature: real): real; function normalize(x: array of real): array of real; function convert_mass_to_molar_fractions(mass_fractions:array of real; densities, mr: array of real): array of real; function convert_molar_to_mass_fractions(molar_fractions: array of real; mr: array of real): array of real; function get_ideal_gas_den(temperature, pressure: real; mr: array of real): array of real; function get_octane_number(c: array of real; octane_numbers: array of real; bi: array of real): real; implementation function convert_mass_to_volume_fractions( mass_fractions: array of real; density: array of real): array of real; begin result := ArrFill(mass_fractions.Length, 0.0); var s := 0.0; foreach var i in mass_fractions.Indices do s += mass_fractions[i] / density[i]; foreach var i in mass_fractions.Indices do result[i] := mass_fractions[i] / density[i] / s end; function convert_mass_to_mole_fractions( mass_fractions: array of real; mr: array of real): array of real; begin result := ArrFill(mass_fractions.Length, 0.0); var s := 0.0; foreach var i in mass_fractions.Indices do s += mass_fractions[i] / mr[i]; foreach var i in mass_fractions.Indices do result[i] := mass_fractions[i] / mr[i] / s end; function get_flow_density(mass_fractions: array of real; density: array of real): real; begin result := 0.0; foreach var i in mass_fractions.Indices do result += mass_fractions[i] / density[i]; result := 1 / result end; function get_average_mol_mass(mass_fractions: array of real; mr:array of real): real; begin result := 0.0; foreach var i in mass_fractions.Indices do result += mass_fractions[i] / mr[i]; result := 1 / result end; function get_flow_cp(mass_fractions: array of real; coeffs: array of array of real; temperature: real): real; begin result := 0.0; var cp := ArrFill(mass_fractions.Length, 0.0); foreach var i in mass_fractions.Indices do foreach var j in coeffs[i].Indices do cp[i] += coeffs[i][j] * temperature ** j; foreach var i in mass_fractions.Indices do result += mass_fractions[i] * cp[i] end; function normalize(x: array of real): array of real; begin result := ArrFill(x.Length, 0.0); var s := x.Sum; foreach var i in x.Indices do result[i] := x[i] / s end; function convert_mass_to_molar_fractions(mass_fractions:array of real; densities, mr: array of real): array of real; begin result := ArrFill(mass_fractions.Length, 0.0); var density := get_flow_density(mass_fractions, densities); foreach var i in mass_fractions.Indices do result[i] := mass_fractions[i] * density * 1000 / mr[i] end; function convert_molar_to_mass_fractions(molar_fractions: array of real; mr: array of real): array of real; begin result := ArrFill(molar_fractions.Length, 0.0); var d := 0.0; foreach var i in molar_fractions.Indices do d += molar_fractions[i] * mr[i]; foreach var i in molar_fractions.Indices do result[i] := molar_fractions[i] * mr[i] / d end; function get_ideal_gas_den(temperature, pressure: real; mr: array of real): array of real; begin result := ArrFill(mr.Length, 0.0); foreach var i in mr.Indices do result[i] := pressure * mr[i] / (8.314 * temperature) end; function get_octane_number(c: array of real; octane_numbers: array of real; bi: array of real): real; begin result := 0.0; foreach var i in c.Indices do result += octane_numbers[i] * c[i]; foreach var i in c.Indices do for var j := i + 1 to c.High do result += bi[i] * bi[j] * c[i] * c[j] end; end.
unit upgrade; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fphttpclient, {twexe units} exedata, wikiops, fileops, logger, version, {$ifdef unix} unixlib {$endif} {$ifdef windows} windowslib {$endif} ; function NeedUpgrade():boolean; implementation const VERSION_URL = 'http://ihm4u.github.io/twexe/rel/VERSION'; {$ifdef windows} UPGRADE_URL = 'http://ihm4u.github.io/twexe/rel/i386-win32/twexe.exe'; {$endif} {$ifdef linux} UPGRADE_URL = 'http://ihm4u.github.io/twexe/rel/x86_64-linux/twexe'; {$endif} function GetFromURL(const URL: string; const FileName: string = ''): string; var Httpc: TFPHTTPClient; begin Httpc := TFPHttpClient.Create(nil); Result := ''; try if FileName <> '' then Httpc.Get(URL, FileName) else Result := Httpc.Get(URL); finally FreeAndNil(Httpc); end; end; function VerToInt(const Ver:string; out Suffix:string):Integer; Var poz:Integer; Triad:string=''; begin Result := 0; Suffix := ''; Poz := Pos('-',Ver); Triad := Ver; If Poz <> 0 then begin Suffix := RightStr(Ver,Length(Ver)-Poz); //Do not include '-' Delete(Triad,poz,Length(Ver)-poz+1); //Delete '-' and suffix end; Triad := StringReplace(Triad,'.','',[rfReplaceAll]); Result:=StrToIntDef(Triad,0); end; //Return true if we need to upgrage function NewerVersionOnline(var OnlineVer:string):boolean; Var CurrSfx,OnlineSfx:string; nCurrVer,nOnlineVer:Integer; begin Result := False; OnlineVer := Trim(GetFromURL(VERSION_URL)); nCurrVer := VerToInt(_VERSION,CurrSfx); nOnlineVer:= VerToInt(OnlineVer,OnlineSfx); LogFmt('Online version is %s, current version is %s', [OnlineVer,_VERSION]); if nCurrVer < nOnlineVer then Result:=True else if (nCurrVer = nOnlineVer) and (CurrSfx <> OnlineSfx) then Result:=True; end; procedure Upgrade(const NewEXE:string); Var WikiName: string=''; O: string=''; Args: string; Ans: Integer; begin If not IAmShadow() then Raise Exception.Create('Upgrade must be done from shadow'); If not FileExists(NewExe) then Raise Exception.CreateFmt('Upgrade file ''%s'' does not exist.',[NewExe]); //We assume data has already been extracted in UnzippedDir If FindWikiFile(GetUnZipPath(),WikiName) then begin Args := '-p "' + WikiName + '"'; LogFmt('Running ''%s'' ''%s''',[NewExe,Args]); Ans:=RunCmd(NewEXE,Args,O); Sleep(200); //Give a little time for executable to close properly If (Ans<>0) or not CopyFile(WikiNameToExeName(WikiName),GetEXEFile(),True) then begin LogFmt('Exit code from conversion %d',[Ans]); Raise Exception.CreateFmt('Unable to convert ''%s'' to a twixie', [WikiName]); end; end; end; function NeedUpgrade():boolean; Var UpgDir,UpgFile, NewVer: string; begin Result := False; try if NewerVersionOnline(NewVer) then begin UpgDir := ConcatPaths([GetStoragePath(),'_upg']); UpgFile := ConcatPaths([UpgDir,ExtractFileName(GetEXEFile())]); MakeDirs(UpgDir + DirectorySeparator); Log('Downloading upgrade.'); GetFromURL(UPGRADE_URL,UpgFile); SetExecutePermission(UpgFile); Log('Download finished. Starting upgrade.'); Upgrade(UpgFile); Show('Upgraded to version '+NewVer); Result := True; ExitCode := 0; end; except on E:Exception do Error('Unable to upgrade: '+E.ToString); end; end; end.
unit FloatSpinEdit; interface uses Classes, QComCtrls, Qt, SysUtils, QConsts, QForms; procedure CheckRange(AMin, AMax: Real); type TFloatSpinEdit = class(TCustomSpinEdit) private FMin: Real; FMax: Real; FValue: Real; FOnChanged: TSEChangedEvent; function GetIncrement: Real; function GetMax: Real; function GetMin: Real; function GetValue: Real; procedure SetIncrement(AValue: Real); procedure SetMax(AValue: Real); procedure SetMin(AValue: Real); procedure SetValue(const AValue: Real); procedure SetRange(const AMin, AMax: Real); procedure ValueChangedHook(AValue: Real); cdecl; protected procedure Change(AValue: Real); dynamic; procedure HookEvents; override; property Max: Real read GetMax write SetMax; property Min: Real read GetMin write SetMin; property Increment: Real read GetIncrement write SetIncrement; property Value: Real read GetValue write SetValue; property OnChanged: TSEChangedEvent read FOnChanged write FOnChanged; public end; implementation procedure CheckRange(AMin, AMax: Real); begin if (AMax < AMin) or (AMin > AMax) then raise ERangeException.Create(Format(SInvalidRangeError,[AMin, AMax])); end; function TFloatSpinEdit.GetIncrement: Real; begin Result := QSpinBox_lineStep(Handle); end; function TFloatSpinEdit.GetMax: Real; begin Result := QSpinBox_maxValue(Handle); end; function TFloatSpinEdit.GetMin: Real; begin Result := QSpinBox_minValue(Handle); end; procedure TFloatSpinEdit.SetMin(AValue: Real); begin if (csLoading in ComponentState) then SetRange(AValue, FMax) else SetRange(AValue, Max); end; procedure TFloatSpinEdit.SetMax(AValue: Real); begin if (csLoading in ComponentState) then SetRange(FMin, AValue) else SetRange(Min, AValue); end; procedure TFloatSpinEdit.SetIncrement(AValue: Real); begin QSpinBox_setLineStep(Handle, Round(AValue)); end; procedure TFloatSpinEdit.SetRange(const AMin, AMax: Real); begin FMin := AMin; FMax := AMax; if not HandleAllocated or (csLoading in ComponentState) then Exit; try CheckRange(AMin, AMax); except FMin := Min; FMax := Max; raise; end; QRangeControl_setRange(RangeControl, Round(FMin), Round(FMax)); if Value < Min then Value := Min else if Value > Max then Value := Max; end; procedure TFloatSpinEdit.ValueChangedHook(AValue: Real); begin try Change(AValue); except Application.HandleException(Self); end; end; function TFloatSpinEdit.GetValue: Real; begin Result := StrToFloatDef(CleanText, Min); end; procedure TFloatSpinEdit.SetValue(const AValue: Real); var TempV: WideString; begin if AValue <> FValue then begin FValue := AValue; if FValue < FMin then FValue := FMin; if FValue > FMax then FValue := FMax; if not (csLoading in ComponentState) then QSpinBox_setValue(Handle, Round(FValue)); end; if not (csLoading in ComponentState) then begin TempV := Prefix + FloatToStr(FValue) + Suffix; if (SpecialText <> '') and (FValue = FMin) then TempV := SpecialText; QLineEdit_setText(QClxSpinBox_editor(Handle), PWideString(@TempV)); end; end; procedure TFloatSpinEdit.Change(AValue: Real); begin FValue := AValue; if Assigned(FOnChanged) then FOnChanged(Self, Round(AValue)); end; procedure TFloatSpinEdit.HookEvents; var Method: TMethod; begin inherited HookEvents; QSpinBox_valueChanged_Event(Method) := Round(ValueChangedHook); QSpinBox_hook_hook_valueChanged(QSpinBox_hookH(Hooks), Method); end; end.
unit GLConstants; interface uses BasicMathsTypes; const // Model Types C_MT_STANDARD = 0; C_MT_VOXEL = 1; // For Mesh.NormalsType C_NORMALS_DISABLED = 0; C_NORMALS_PER_VERTEX = 1; C_NORMALS_PER_FACE = 2; // For Mesh.ColoursType C_COLOURS_DISABLED = 0; C_COLOURS_PER_VERTEX = 1; C_COLOURS_PER_FACE = 2; C_COLOURS_FROM_TEXTURE = 3; // For Voxel Faces C_VOXEL_FACE_SIDE = 0; C_VOXEL_FACE_DEPTH = 1; C_VOXEL_FACE_HEIGHT = 2; // Lists C_LIST_NONE = 0; // Mesh Quality C_QUALITY_CUBED = 0; C_QUALITY_VISIBLE_CUBED = 1; C_QUALITY_VISIBLE_TRIS = 2; C_QUALITY_LANCZOS_QUADS = 3; C_QUALITY_2LANCZOS_4TRIS = 4; C_QUALITY_LANCZOS_TRIS = 5; C_QUALITY_VISIBLE_MANIFOLD = 6; C_QUALITY_SMOOTH_MANIFOLD = 7; C_QUALITY_HIGH = 8; C_QUALITY_MAX = C_QUALITY_HIGH; // Frequency normalization C_FREQ_NORMALIZER = 4/3; // Texture Type C_TTP_DIFFUSE = 0; C_TTP_NORMAL = 1; C_TTP_HEIGHT = 2; C_TTP_SPECULAR = 3; C_TTP_ALPHA = 4; C_TTP_AMBIENT = 5; C_TTP_ENVIRONMENT = 6; C_TTP_DECAL = 7; C_TTP_DISPLACEMENT = 8; C_TTP_DOT3BUMP = 9; // Angle Detection C_ANGLE_NONE = -99999; // Shader Types C_SHD_PHONG = 0; C_SHD_PHONG_1TEX = 1; C_SHD_PHONG_2TEX = 2; C_SHD_PHONG_DOT3TEX = 3; // Transparency C_TRP_OPAQUE = 1; C_TRP_GHOST = 0.05; C_TRP_INVISIBLE = 0; C_TRP_RGB_OPAQUE = 255; C_TRP_RGB_GHOST = 2; C_TRP_RGB_INVISIBLE = 0; // Texture minimum angle C_TEX_MIN_ANGLE = 0.7; // approximately cos 45' // Mesh Plugins C_MPL_BASE = 0; C_MPL_NORMALS = 1; C_MPL_NEIGHBOOR = 2; C_MPL_BUMPMAPDATA = 3; C_MPL_MESH = 4; C_MPL_HALFEDGE = 5; // Distance Functions {* C_DSF_IGNORE = 0; C_DSF_LINEAR = 1; C_DSF_CUBIC = 2; C_DSF_QUADRIC1D = 3; C_DSF_LINEAR1D = 4; C_DSF_CUBIC1D = 5; C_DSF_LANCZOS = 6; C_DSF_LANCZOS1DA1 = 7; C_DSF_LANCZOS1DA3 = 8; C_DSF_LANCZOS1DAC = 9; C_DSF_SINC1D = 10; C_DSF_EULER1D = 11; C_DSF_EULERSQUARED1D = 12; C_DSF_SINCINFINITE1D = 13; *} // To clean topological problems C_TOPO_DOESNT_EXIST = -2; C_TOPO_MAKRED_TO_DIE = -1; C_TOPO_X_POS = 0; C_TOPO_X_NEG = 1; C_TOPO_Y_POS = 2; C_TOPO_Y_NEG = 3; C_TOPO_Z_POS = 4; C_TOPO_Z_NEG = 5; C_ORI_XNEG_YNEG = 0; C_ORI_XPOS_YNEG = 1; C_ORI_XNEG_YPOS = 2; C_ORI_XPOS_YPOS = 3; C_ORI_XNEG_ZNEG = $10; C_ORI_XPOS_ZNEG = $11; C_ORI_XNEG_ZPOS = $14; C_ORI_XPOS_ZPOS = $15; C_ORI_YNEG_ZNEG = $20; C_ORI_YPOS_ZNEG = $22; C_ORI_YNEG_ZPOS = $24; C_ORI_YPOS_ZPOS = $26; // For bump mapping texture generation C_BUMP_DEFAULTSCALE = 2.2; // Remappables RemapColourMap : array [0..8] of TVector3b = ( ( //DarkRed R : 255; G : 3; B : 3; ), ( //DarkBlue R : 9; G : 53; B : 255; ), ( //DarkGreen R : 13; G : 255; B : 16; ), ( //White R : 255; G : 255; B : 255; ), ( //Orange R : 255; G : 160; B : 3; ), ( //Magenta R : 255; G : 105; B : 178; ), ( //Purple R : 255; G : 12; B : 252; ), ( //Gold R : 255; G : 203; B : 0; ), ( //DarkSky R : 24; G : 191; B : 255; ) ); // From MeshGeometryList C_GEO_BREP = 1; C_GEO_BREP3 = 2; C_GEO_BREP4 = 3; implementation end.
{================================================================================ Copyright (C) 1997-2002 Mills Enterprise Unit : rmDayView Purpose : This is a very basic PIM component. Date : 04-14-2002 Author : Ryan J. Mills Version : 1.92 ================================================================================} unit rmDayView; interface {$I CompilerDefines.INC} uses windows, Messages, controls, classes, graphics, extctrls, menus, forms, stdctrls, sysutils, rmLibrary, rmLabel, rmScrollableControl, math; const wm_PostedUpdate = wm_user+501; wm_DayViewItemDBLClicked = wm_user+502; wm_DayViewItemClicked = wm_User+503; wm_UpdateOverlaps = wm_user+504; wm_UpdateTops = wm_user+505; wm_updateHeights = wm_user+506; wm_updateHints = wm_user+507; wm_updateAll = wm_user+508; HintStr = '%s at %s for %d minute(s)'#13#10#13#10'%s'; type TrmHourBreakdown = (hb5Minutes, hb10Minutes, hb15Minutes, hb20Minutes, hb30Minutes, hb1Hour); TrmPercent = 1..100; TrmDayViewCollection = class; TrmCustomDayView = class; TrmDayView = class; TrmDayViewCollectionItem = class; TrmCustomDayViewItem = class(TCustomControl) private fCollectionItem : TrmDayViewCollectionItem; fLabel: TrmLabel; fNote: TrmLabel; fStartTime: TTime; fDayView: TrmDayView; fDuration: integer; fItemDesc : string; function GetItemColor: TColor; procedure SetItemColor(const Value: TColor); function GetCaption: TCaption; procedure SetCaption(const Value: TCaption); procedure SetStartTime(const Value: TTime); procedure SetDayView(const Value: TrmDayView); procedure SetDuration(const Value: integer); function GetPopup: TPopupMenu; procedure SetPopup(const Value: TPopupMenu); function GetItemFont: TFont; procedure SetItemFont(const Value: TFont); function Getcolor: TColor; procedure SetColor(const Value: TColor); procedure WMSetFocus(var Message: TWMSetFocus); message WM_SETFOCUS; procedure WMKillFocus(var Message: TWMSetFocus); message WM_KILLFOCUS; procedure wmupdateoverlaps(var message:Tmessage); message wm_UpdateOverlaps; procedure wmupdatetops(var message:Tmessage); message wm_updateTops; procedure wmupdateheights(var message:tmessage); message wm_updateheights; procedure wmupdateall(var message:tmessage); message wm_updateall; function GetItemDesc: string; procedure SetItemDesc(const Value: string); protected procedure HandleSetFocus; procedure DoClick(sender : TObject); procedure DoDblClick(Sender : TObject); property Font : TFont read GetItemFont write SetItemFont; property ItemColor : TColor read GetItemColor write SetItemColor default clBlue; property ItemDescription : string read GetItemDesc write SetItemDesc; property Color : TColor read Getcolor write SetColor; property Caption : TCaption read GetCaption write SetCaption; property StartTime : TTime read fStartTime write SetStartTime; property Duration : integer read fDuration write SetDuration; property DayView : TrmDayView read fDayView write SetDayView; property PopupMenu : TPopupMenu read GetPopup write SetPopup; property CollectionItem : TrmDayViewCollectionItem read fCollectionItem write fCollectionItem; procedure DoIntMouseEnter(sender:TObject); procedure DoIntMouseLeave(sender:TObject); public constructor create(AOwner:TComponent); override; procedure UpdateTop; procedure UpdateHeight; procedure UpdateOverlap; procedure UpdateHint; published end; TrmDayViewItem = class(TrmCustomDayViewItem) published property Caption; property Color; property Font; property DayView; property Duration; property ItemColor; property ItemDescription; property PopupMenu; property StartTime; property OnClick; property OnDblClick; end; TrmDayViewCollectionItem = class(TCollectionItem) private fDayViewItem : TrmDayViewItem; fTag: integer; function GetCaption: TCaption; function Getcolor: TColor; function GetDuration: integer; function GetItemColor: TColor; function GetItemFont: TFont; function GetPopup: TPopupMenu; function GetStartTime: TTime; procedure SetCaption(const Value: TCaption); procedure SetColor(const Value: TColor); procedure SetDuration(const Value: integer); procedure SetItemColor(const Value: TColor); procedure SetItemFont(const Value: TFont); procedure SetPopup(const Value: TPopupMenu); procedure SetStartTime(const Value: TTime); function GetShowHint: boolean; procedure SetShowHint(const Value: boolean); function GetItemDesc: string; procedure SetItemDesc(const Value: string); public constructor Create(Collection: TCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure UpdateViewDetails; procedure UpdateTop; procedure UpdateOverlap; published property Font : TFont read GetItemFont write SetItemFont; property ItemColor : TColor read GetItemColor write SetItemColor; property ItemDescription : string read GetItemDesc write SetItemDesc; property Color : TColor read Getcolor write SetColor; property Caption : TCaption read GetCaption write SetCaption; property StartTime : TTime read GetStartTime write SetStartTime; property Duration : integer read GetDuration write SetDuration; property PopupMenu : TPopupMenu read GetPopup write SetPopup; property ShowHint : boolean read GetShowHint write SetShowHint; property Tag : integer read fTag write fTag default 0; end; TrmDayViewCollection = class(TCollection) private FDayView: TrmDayView; FOnUpdate: TNotifyEvent; function GetItem(Index: Integer): TrmDayViewCollectionItem; procedure SetItem(Index: Integer; Value: TrmDayViewCollectionItem); protected function GetOwner: TPersistent; override; procedure Update(Item: TCollectionItem); override; public constructor Create(DayView: TrmCustomDayView); function Add: TrmDayViewCollectionItem; procedure Delete(Index: Integer); function Insert(Index: Integer): TrmDayViewCollectionItem; property Items[Index: Integer]: TrmDayViewCollectionItem read GetItem write SetItem; default; property OnCollectionUpdate: TNotifyEvent read fOnUpdate write fOnUpdate; end; TrmCustomDayView = class(TrmCustomScrollableControl) private fItems : TrmDayViewCollection; fRowHeight:integer; fHourlyBreakdown: TrmHourBreakDown; fDrawBuffer : TBitmap; fHourColWidth: integer; fDayStart: TTime; fDayEnd: TTime; fSelColor: tcolor; fColorDiff: TrmPercent; fOnItemClick: TNotifyEvent; fOnItemDblClick: TNotifyEvent; fSelectedItem: TrmDayViewCollectionItem; fSelItemChange: TNotifyEvent; procedure SetHourlyBreakdown(const Value: TrmHourBreakdown); procedure SetHourColWidth(const Value: integer); procedure setDayEnd(const Value: TTime); procedure SetDayStart(const Value: TTime); procedure SetSelColor(const Value: tcolor); function GetItemTime: TTime; procedure SetItemTime(const Value: TTime); procedure SetColorDiff(const Value: TrmPercent); function GetSelTimeCount: Integer; function GetSelTimeStart: TTime; procedure SetSelTimeCount(const Value: Integer); procedure SetSelTimeStart(const Value: TTime); procedure SetItems(const Value: TrmDayViewCollection); function GetTopIndex: integer; function GetTopTime: TTime; procedure SetTopIndex(const Value: integer); procedure SetTopTime(const Value: TTime); protected procedure CMBorderChanged(var Message: TMessage); message CM_BORDERCHANGED; procedure CMFontChanged(var Message: TMessagE); message cm_FontChanged; procedure CMFocusChanged(var Message: TCMFocusChanged); message CM_FOCUSCHANGED; procedure cmColorChanged(var Message:TMessage); message cm_colorchanged; procedure wmSize(var msg: twmSize); message wm_size; procedure wmEraseBKGrnd(var msg: tmessage); message wm_erasebkgnd; procedure wmDayViewItemDBLClicked(var msg:Tmessage); message wm_DayViewItemDBLClicked; procedure wmDayViewItemClicked(var msg:Tmessage); message wm_DayViewItemClicked; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure Paint; override; procedure Loaded; override; procedure DoItemClick(sender:TObject); procedure DoItemDblclick(sender:TObject); procedure DoItemsUpdate(sender:TObject); procedure SetSelectedItem(item : TrmDayViewCollectionItem); function IsTimeModIndex(aTime:TTime): boolean; procedure DoItemIndexChange; override; property HourlyBreakdown : TrmHourBreakdown read fHourlyBreakdown write SetHourlyBreakdown default hb30Minutes; property Color default clSkyBlue; property SelectedColor : tcolor read fSelColor write SetSelColor default clHighlight; property HourColWidth : integer read fHourColWidth write SetHourColWidth default 50; property OnItemClick : TNotifyEvent read fOnItemClick write fOnItemClick; property OnItemDblClick : TNotifyEvent read fOnItemDblClick write fOnItemDblClick; procedure VerticalScrollChange(sender:TObject); override; function MaxItemLength: integer; override; function MaxItemCount:integer; override; function VisibleItems: integer; override; function MaxItemHeight: integer; override; property DayStart:TTime read fDayStart write SetDayStart; property DayEnd:TTime read fDayEnd write setDayEnd; property ItemTime:TTime read GetItemTime write SetItemTime; property ColorDifference:TrmPercent read fColorDiff write SetColorDiff default 20; property Items : TrmDayViewCollection read fItems write SetItems; property InternalTopIndex; property OnSelectedItemChange : TNotifyEvent read fSelItemChange write fSelItemChange; public constructor create(AOwner: TComponent); override; destructor destroy; override; function RowTime(aRow:integer):TTime; function RowIndex(aTime:TTime):integer; function BlockTime:integer; procedure UpdateViewItems; procedure UpdateTops; procedure UpdateOverlaps; property SelTimeStart : TTime read GetSelTimeStart write SetSelTimeStart; property SelTimeCount : Integer read GetSelTimeCount write SetSelTimeCount; property SelStart; property SelCount; property SelectedItem : TrmDayViewCollectionItem read fSelectedItem; property TopTime: TTime read GetTopTime write SetTopTime; property TopIndex: integer read GetTopIndex write SetTopIndex; property Rowcount:integer read MaxItemCount; end; TrmDayView = class(TrmCustomDayView) published property Align; property BorderStyle; property DoubleBuffered; property SelectedColor; property DayStart; property DayEnd; property ColorDifference; property HourlyBreakdown; property Color; property Font; property HideSelection; property ShowFocusRect; property HourColWidth; property ItemIndex; property ItemTime; property Items; property MultiSelect; property TabStop; property PopupMenu; property ClientHeight; property ClientWidth; property Ctl3D; property Cursor; property Enabled; property Hint; property ParentFont; property ShowHint; property Visible; property OnItemClick; property OnItemDblClick; property OnMouseWheel; property OnMouseWheelDown; property OnMouseWheelUp; property OnResize; property OnContextPopup; property OnClick; property OnDblClick; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnSelectedItemChange; end; implementation const fHoursPerDay = 24; fMinsPerDay = 1440; function AdjustMinutes(OldTime:TTime; MinToAdd:integer):TTime; begin Result := ((OldTime * fMinsPerDay) + MinToAdd) / fMinsPerDay; end; { TrmCustomDayView } procedure TrmCustomDayView.CMBorderChanged(var Message: TMessage); begin inherited; Invalidate; end; procedure TrmCustomDayView.cmColorChanged(var Message: TMessage); begin inherited; invalidate; end; procedure TrmCustomDayView.CMFontChanged(var Message: TMessagE); begin inherited; canvas.font.size := canvas.Font.size + 9; try fRowHeight := Canvas.TextHeight('X'); finally canvas.font.size := font.size; end; end; constructor TrmCustomDayView.create(AOwner: TComponent); begin inherited; Height := 250; Width := 150; fRowHeight := 24; fHourColWidth := 50; TabStop := true; fColorDiff := 20; fHourlyBreakdown := hb30Minutes; fDrawBuffer := TBitmap.Create; color := clSkyBlue; fSelColor := clHighlight; BorderStyle := bsNone; ScrollBars := ssVertical; fDayStart := EncodeTime(9, 0, 0, 0); fDayEnd := EncodeTime(17, 0, 0, 0); fItems := TrmDayViewCollection.Create(self); fItems.OnCollectionUpdate := DoItemsUpdate; end; destructor TrmCustomDayView.destroy; begin fDrawBuffer.free; fItems.free; inherited; end; function TrmCustomDayView.MaxItemCount: integer; begin case fHourlyBreakdown of hb5Minutes : result := fHoursPerDay * 12; hb10Minutes : result := fHoursPerDay * 6; hb15Minutes : result := fHoursPerDay * 4; hb20Minutes : result := fHoursPerDay * 3; hb30Minutes : result := fHoursPerDay * 2; hb1Hour : result := fHoursPerDay; else result := 0; end; end; function TrmCustomDayView.MaxItemHeight: integer; begin result := fRowHeight; end; function TrmCustomDayView.MaxItemLength: integer; begin result := 0; end; procedure TrmCustomDayView.Paint; var loop : integer; wFocusRect, wTimeRect, wDataRect : TRect; wh, wm, ws, wms : word; wData : string; wDrawHourLine : boolean; wCanvas : TCanvas; windex : integer; begin if FDoubleBuffered then begin //set some of the defaults fDrawBuffer.Width := ClientWidth; fDrawBuffer.height := clientheight; wCanvas := fDrawBuffer.Canvas; end else wCanvas := Canvas; wCanvas.font.assign(font); wCanvas.Brush.Style := bsSolid; wCanvas.Brush.color := clBtnFace; wCanvas.FillRect(rect(0,0,fHourColWidth,clientheight)); //Set row times wTimeRect := rect(0, 0, fHourColWidth, fRowHeight); wDataRect := rect(fHourColWidth, 0, clientwidth, fRowHeight); wFocusRect := rect(-1,-1,-1,-1); for loop := 0 to VisibleItems-1 do begin if loop = 1 then inc(wDataRect.Top); wIndex := InternalTopIndex+loop; if wIndex >= MaxItemCount then break; decodetime(rowtime(wIndex), wh, wm, ws, wms); if ((windex >= rowindex(fDayStart)) and (wIndex < rowindex(fdayend))) then wCanvas.Brush.Color := color else wCanvas.Brush.color := DarkenColor(color, fColorDiff); if ((wIndex >= SelStart) and (wIndex <= SelStart+SelCount)) then begin if (Focused or not HideSelection) and not assigned(fSelectedItem) then wCanvas.Brush.Color := fSelColor; end; wCanvas.FillRect(wDataRect); wCanvas.Brush.Style := bsClear; wCanvas.Pen.Color := clBtnShadow; wCanvas.MoveTo(fHourColWidth, wTimeRect.top); wCanvas.lineto(fHourColWidth, wTimeRect.Bottom); if ShowFocusRect and Focused and (windex = ItemIndex) then wFocusRect := wDataRect; case fHourlyBreakdown of hb5Minutes: wDrawHourLine := (wm = 55); hb10Minutes: wDrawHourLine := (wm = 50); hb15Minutes: wDrawHourLine := (wm = 45); hb20Minutes: wDrawHourLine := (wm = 40); hb30Minutes: wDrawHourLine := (wm = 30); hb1Hour : wDrawHourLine := true; else wDrawHourLine := false; end; if wDrawHourLine then wCanvas.MoveTo(0, wTimeRect.Top+rectheight(wTimeRect)) else wCanvas.MoveTo(rectWidth(wTimeRect) div 2, wTimeRect.Top+rectheight(wTimeRect)); wCanvas.Pen.Color := DarkenColor(clDkGray, 50); wCanvas.LineTo(clientwidth, wTimeRect.Top+rectheight(wTimeRect)); if wm = 0 then begin wCanvas.font.style := [fsBold]; wCanvas.Font.size := wCanvas.Font.size + 8; if wh = 0 then begin wCanvas.TextRect(wTimeRect, wTimeRect.left+2, wTimeRect.top+((rectheight(wTimeRect) div 2) - (wCanvas.Textheight('12') div 2)), '12'); wdata := TimeAMString; end else if wh = 12 then begin wCanvas.TextRect(wTimeRect, wTimeRect.left+2, wTimeRect.top+((rectheight(wTimeRect) div 2) - (wCanvas.Textheight('12') div 2)), '12'); wdata := TimePMString; end else begin if wh < 12 then begin wData := inttostr(wh); if wh < 10 then wData := ' '+wData; wCanvas.TextRect(wTimeRect, wTimeRect.left+2, wTimeRect.top+((rectheight(wTimeRect) div 2) - (wCanvas.Textheight(wdata) div 2)), wdata); wdata := TimeAMString; end else begin wData := inttostr(wh-12); if wh-12 < 10 then wData := ' '+wData; wCanvas.TextRect(wTimeRect, wTimeRect.left+2, wTimeRect.top+((rectheight(wTimeRect) div 2) - (wCanvas.Textheight(wdata) div 2)), wdata); wdata := TimePMString; end; end; end else begin if wm < 10 then wdata := TimeSeparator+'0'+inttostr(wm) else wdata := TimeSeparator+inttostr(wm); end; wCanvas.Font.assign(font); wCanvas.TextRect(wTimeRect, wTimeRect.left+rectwidth(wTimeRect)-wCanvas.TextWidth(wdata)-4, wTimeRect.top+((rectheight(wTimeRect) div 2) - (wCanvas.Textheight(wdata) div 2)), wdata); OffsetRect(wTimeRect, 0, fRowheight); OffsetRect(wDataRect, 0, fRowheight); end; if wTimeRect.Top < ClientHeight then begin wCanvas.Brush.color := clbtnface; wCanvas.FillRect(rect(0, wTimeRect.top+1, clientwidth, clientheight)); end; case fHourlyBreakdown of hb5Minutes: wDrawHourLine := (wm = 55); hb10Minutes: wDrawHourLine := (wm = 50); hb15Minutes: wDrawHourLine := (wm = 45); hb20Minutes: wDrawHourLine := (wm = 40); hb30Minutes: wDrawHourLine := (wm = 30); hb1Hour : wDrawHourLine := true; else wDrawHourLine := false; end; wCanvas.Brush.color := DarkenColor(color, 20); if wDrawHourLine then wCanvas.MoveTo(0, wTimeRect.Top) else wCanvas.MoveTo(rectWidth(wTimeRect) div 2, wTimeRect.Top); wCanvas.LineTo(clientwidth, wTimeRect.Top); if not EqualRect(wFocusRect, rect(-1,-1,-1,-1)) then wCanvas.DrawFocusRect(wFocusRect); if FDoubleBuffered then BitBlt(Canvas.Handle, 0, 0, clientwidth, clientheight, fDrawBuffer.Canvas.Handle, 0, 0, SRCCOPY); end; function TrmCustomDayView.RowIndex(aTime: TTime): integer; var h, m, s, ms:word; minutes : integer; begin DecodeTime(aTime, h, m, s, ms); minutes := (h * 60) + m; case fHourlyBreakdown of hb5Minutes : result := minutes div 5; hb10Minutes : result := minutes div 10; hb15Minutes : result := minutes div 15; hb20Minutes : result := minutes div 20; hb30Minutes : result := minutes div 30; hb1Hour : result := minutes div 60; else result := 0; end; result := SetInRange(result, 0, MaxItemCount-1); end; function TrmCustomDayView.RowTime(aRow: integer): TTime; begin case fHourlyBreakdown of hb5Minutes : result := AdjustMinutes(0, arow * 5); hb10Minutes : result := AdjustMinutes(0, arow * 10); hb15Minutes : result := AdjustMinutes(0, arow * 15); hb20Minutes : result := AdjustMinutes(0, arow * 20); hb30Minutes : result := AdjustMinutes(0, arow * 30); hb1Hour : result := AdjustMinutes(0, arow * 60); else result := 0; end; if result < 0 then result := 0 else if result > 1 then result := 1; end; procedure TrmCustomDayView.setDayEnd(const Value: TTime); begin if (fDayEnd <> Value) and (fDayStart < Value) then begin fDayEnd := Value; invalidate; end; end; procedure TrmCustomDayView.SetDayStart(const Value: TTime); begin if (fDayStart <> Value) and (fDayEnd > Value) then begin fDayStart := Value; invalidate; end; end; procedure TrmCustomDayView.SetHourColWidth(const Value: integer); begin if fHourColWidth <> Value then begin fHourColWidth := Value; UpdateViewItems; invalidate; end; end; procedure TrmCustomDayView.SetHourlyBreakdown(const Value: TrmHourBreakdown); var wOldTime : TTime; begin if value <> fHourlyBreakdown then begin wOldTime := ItemTime; fHourlyBreakdown := Value; ItemTime := wOldTime; {//rjm UpdateViewItems; UpdateVScrollBar; Invalidate;} end; end; function TrmCustomDayView.VisibleItems: integer; begin Result := ClientHeight div fRowHeight; end; procedure TrmCustomDayView.wmEraseBKGrnd(var msg: tmessage); begin msg.result := 1; end; procedure TrmCustomDayView.SetSelColor(const Value: tcolor); begin if fSelColor <> Value then begin fSelColor := Value; invalidate; end; end; function TrmCustomDayView.GetItemTime: TTime; begin result := RowTime(ItemIndex); end; procedure TrmCustomDayView.SetItemTime(const Value: TTime); begin if ItemIndex <> RowIndex(value) then ItemIndex := RowIndex(value); end; procedure TrmCustomDayView.SetColorDiff(const Value: TrmPercent); begin if fColorDiff <> Value then begin fColorDiff := Value; invalidate; end; end; procedure TrmCustomDayView.CMFocusChanged(var Message: TCMFocusChanged); begin inherited; invalidate; end; function TrmCustomDayView.GetSelTimeCount:integer; begin result := ((SelStart+(SelCount+1)) - SelStart); case fHourlyBreakdown of hb5Minutes : result := result*5; hb10Minutes : result := result*10; hb15Minutes : result := result*15; hb20Minutes : result := result*20; hb30Minutes : result := result*30; hb1Hour : result := result*60; else result := 0; end; end; function TrmCustomDayView.GetSelTimeStart: TTime; begin result := RowTime(SelStart); end; procedure TrmCustomDayView.SetSelTimeCount(const Value: integer); begin case fHourlyBreakdown of hb5Minutes : SelCount := value div 5; hb10Minutes : SelCount := value div 10; hb15Minutes : SelCount := value div 15; hb20Minutes : SelCount := value div 20; hb30Minutes : SelCount := value div 30; hb1Hour : SelCount := value div 60; else SelCount := 0; end; end; procedure TrmCustomDayView.SetSelTimeStart(const Value: TTime); begin SelStart := RowIndex(Value); end; procedure TrmCustomDayView.Loaded; begin inherited; SetTopIndex(ItemIndex); UpdateVScrollBar; end; procedure TrmCustomDayView.UpdateViewItems; var loop : integer; begin for loop := 0 to Items.Count-1 do Items[loop].UpdateViewDetails; end; function TrmCustomDayView.BlockTime: integer; begin case fHourlyBreakdown of hb5Minutes : result := 5; hb10Minutes : result := 10; hb15Minutes : result := 15; hb20Minutes : result := 20; hb30Minutes : result := 30; hb1Hour : result := 60; else result := 0; end; end; procedure TrmCustomDayView.SetItems(const Value: TrmDayViewCollection); begin fItems := Value; UpdateViewItems; end; procedure TrmCustomDayView.VerticalScrollChange(sender: TObject); begin UpdateTops; end; Procedure TrmCustomDayView.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if (x > fHourColWidth) then inherited; end; procedure TrmCustomDayView.MouseMove(Shift: TShiftState; X, Y: Integer); begin if (x > fHourColWidth) then inherited; end; procedure TrmCustomDayView.DoItemClick(sender: TObject); begin if assigned(fonitemclick) then fOnItemClick(sender); end; procedure TrmCustomDayView.DoItemDblclick(sender: TObject); begin if assigned(fonitemdblclick) then fonitemdblclick(self); end; function TrmCustomDayView.IsTimeModIndex(aTime:TTime): boolean; var h, m, s, ms:word; minutes : integer; begin DecodeTime(aTime, h, m, s, ms); minutes := (h * 60) + m; case fHourlyBreakdown of hb5Minutes : result := (minutes mod 5) > 0; hb10Minutes : result := (minutes mod 10) > 0; hb15Minutes : result := (minutes mod 15) > 0; hb20Minutes : result := (minutes mod 20) > 0; hb30Minutes : result := (minutes mod 30) > 0; hb1Hour : result := (minutes mod 60) > 0; else result := false; end; end; procedure TrmCustomDayView.DoItemsUpdate(sender: TObject); begin // UpdateViewItems; end; procedure TrmCustomDayView.UpdateTops; var loop : integer; begin for loop := 0 to Items.Count-1 do Items[loop].UpdateTop; end; procedure TrmCustomDayView.SetSelectedItem(item: TrmDayViewCollectionItem); begin If fSelectedItem <> item then begin fSelectedItem := item; invalidate; if assigned(fSelItemChange) then fSelItemChange(self); end; end; procedure TrmCustomDayView.DoItemIndexChange; begin inherited; SetSelectedItem(nil); end; procedure TrmCustomDayView.wmSize(var msg: twmSize); begin inherited; if msg.width <> width then updateoverlaps; invalidate; end; procedure TrmCustomDayView.wmDayViewItemClicked(var msg: Tmessage); begin DoItemClick(self); end; procedure TrmCustomDayView.wmDayViewItemDBLClicked(var msg: Tmessage); begin DoItemDblclick(self); end; function TrmCustomDayView.GetTopIndex: integer; begin result := InternalTopIndex; end; function TrmCustomDayView.GetTopTime: TTime; begin result := RowTime(InternalTopIndex); end; procedure TrmCustomDayView.SetTopIndex(const Value: integer); begin InternalTopIndex := Value; end; procedure TrmCustomDayView.SetTopTime(const Value: TTime); begin InternalTopIndex := RowIndex(Value); end; procedure TrmCustomDayView.UpdateOverlaps; var loop : integer; begin for loop := 0 to Items.Count-1 do Items[loop].UpdateOverlap; end; { TrmCustomDayViewItem } constructor TrmCustomDayViewItem.create(AOwner: TComponent); begin inherited; ControlStyle := ControlStyle - [csAcceptsControls]; height := 45; width := 100; ParentShowHint := false; fItemDesc := 'Unknown Type'; fLabel := TrmLabel.create(self); fLabel.parent := self; fLabel.BorderStyle := rmbsNone; fLabel.align := alLeft; fLabel.width := 10; fLabel.Color := clBlue; fLabel.caption := ''; fLabel.AutoSize := false; fLabel.OnClick := DoClick; fLabel.OnDblClick := DoDblClick; fLabel.OnMouseEnter := DoIntMouseEnter; fLabel.OnMouseLeave := doIntMouseLeave; fNote := TrmLabel.create(self); fNote.Parent := self; fNote.Align := alClient; fNote.BorderStyle := rmbsSingle; fNote.Color := clBtnFace; fNote.Font.Color := clBtnText; fNote.WordWrap := true; fNote.OnClick := DoClick; fNote.OnDblClick := DoDblClick; fNote.OnMouseEnter := DoIntMouseEnter; fNote.OnMouseLeave := doIntMouseLeave; end; procedure TrmCustomDayViewItem.DoClick(sender: TObject); begin HandleSetFocus; PostMessage(fDayView.Handle, wm_DayViewItemClicked, 0, fCollectionItem.Tag); end; procedure TrmCustomDayViewItem.DoDblClick(Sender: TObject); begin HandleSetFocus; PostMessage(fDayView.Handle, wm_DayViewItemDBLClicked, 0, fCollectionItem.Tag); end; function TrmCustomDayViewItem.GetCaption: TCaption; begin result := fNote.Caption; updateHint; end; function TrmCustomDayViewItem.Getcolor: TColor; begin result := fNote.Color; end; function TrmCustomDayViewItem.GetItemColor: TColor; begin Result := fLabel.Color; end; function TrmCustomDayViewItem.GetItemFont: TFont; begin result := fNote.Font; end; function TrmCustomDayViewItem.GetPopup: TPopupMenu; begin Result := fLabel.PopupMenu; end; procedure TrmCustomDayViewItem.UpdateTop; begin if Assigned(fDayView) then top := (fDayView.MaxItemHeight * (fDayView.RowIndex(fStartTime)-fDayView.InternalTopIndex))+5; end; procedure TrmCustomDayViewItem.SetCaption(const Value: TCaption); begin fNote.Caption := value; UpdateHint; end; procedure TrmCustomDayViewItem.SetColor(const Value: TColor); begin fnote.color := value; end; procedure TrmCustomDayViewItem.SetDayView(const Value: TrmDayView); begin if fDayView <> value then begin fDayView := Value; if assigned(fDayView) then FreeNotification(fDayView); end; end; procedure TrmCustomDayViewItem.SetDuration(const Value: integer); begin if fDuration <> value then begin fDuration := Value; UpdateHint; fDayView.UpdateViewItems; end; end; procedure TrmCustomDayViewItem.SetItemColor(const Value: TColor); begin fLabel.Color := Value; end; procedure TrmCustomDayViewItem.SetItemFont(const Value: TFont); begin fNote.Font.Assign(value); end; procedure TrmCustomDayViewItem.SetPopup(const Value: TPopupMenu); begin fLabel.PopupMenu := value; fNote.PopupMenu := value; end; procedure TrmCustomDayViewItem.SetStartTime(const Value: TTime); begin if fStartTime <> value then begin fStartTime := Value; UpdateHint; fDayView.UpdateViewItems; end; end; procedure TrmCustomDayViewItem.UpdateHint; begin fNote.Hint := format(HintStr, [fItemDesc, timetostr(fStartTime), fduration, fNote.Caption]); fLabel.Hint := fNote.Hint; end; procedure TrmCustomDayViewItem.UpdateHeight; var wHeight : integer; wBlockCount : integer; begin if Assigned(fDayView) and (fduration > 0) then begin wBlockCount := fDayView.RowIndex(AdjustMinutes(fStartTime, fDuration)) - fDayView.RowIndex(fStartTime); if fDayView.IsTimeModIndex(AdjustMinutes(fStartTime, fDuration)) then inc(wBlockCount); wHeight := (fDayView.MaxItemHeight * wBlockCount); Height := SetInRange(wHeight, fDayView.MaxItemHeight, 10000)-10; end; end; procedure TrmCustomDayViewItem.UpdateOverlap; var loop : integer; wColl : TrmDayViewCollection; wItem : TrmDayViewItem; wStart, wEnd : integer; wMyStart, wMyEnd : integer; wCount : integer; wPosition : integer; wPassedSelf : boolean; begin wMyStart := fDayView.RowIndex(fStartTime); wMyEnd := fDayView.RowIndex(AdjustMinutes(fStartTime, fDuration)); if fDayView.IsTimeModIndex(AdjustMinutes(fStartTime, fDuration)) then inc(wMyEnd); wCount := 1; wPosition := 0; wPassedSelf := false; wColl := TrmDayViewCollection(fCollectionItem.Collection); for loop := 0 to wColl.Count-1 do begin wItem := wColl[loop].fDayViewItem; if wItem <> self then begin wStart := fDayView.RowIndex(wItem.StartTime); wEnd := fDayView.RowIndex(AdjustMinutes(wItem.StartTime, wItem.Duration)); if fDayView.IsTimeModIndex(AdjustMinutes(wItem.StartTime, wItem.Duration)) then inc(wEnd); if ((wStart >= wMyStart) and (wStart <= wMyEnd)) or ((wEnd >= wMyStart) and (wEnd <= wMyEnd)) then begin if not wPassedSelf then Inc(wPosition); inc(wCount); end; end else wPassedSelf := true; end; Width := (((fDayView.ClientWidth-fDayView.HourColWidth)-5)div wCount)-5; Left := fDayView.HourColWidth+(wPosition * width)+(5 * (wPosition+1)); end; procedure TrmCustomDayViewItem.WMKillFocus(var Message: TWMSetFocus); begin inherited; fNote.Color := clBtnFace; fNote.Font.Color := clBtnText; end; procedure TrmCustomDayViewItem.WMSetFocus(var Message: TWMSetFocus); var wClientArea : TRect; begin inherited; fNote.Color := clHighlight; fNote.Font.Color := clHighlightText; wClientArea := fDayView.ClientRect; wClientArea := rect(0,0,fDayView.ClientWidth, fDayView.ClientHeight); // OffsetRect(wClientArea, 0, fDayView.InternalTopIndex*fDayView.MaxItemHeight); if (Top < wClientarea.Top) then begin fdayview.InternalTopIndex := fDayView.RowIndex(fStartTime); fDayView.UpdateViewItems; end else if (top < wClientArea.bottom) and ((top+height) > wClientArea.Bottom) then begin fdayview.InternalTopIndex := fdayview.InternalTopIndex + ((height+5) div fdayview.maxitemheight); fDayView.UpdateViewItems; end else if (top > wClientArea.bottom) then begin fdayview.InternalTopIndex := fdayview.InternalTopIndex + (((top+(height*2))- wClientArea.bottom) div fDayView.MaxItemHeight); end; end; procedure TrmCustomDayViewItem.HandleSetFocus; begin if CanFocus then SetFocus; fDayView.SetSelectedItem(fCollectionItem); end; function TrmCustomDayViewItem.GetItemDesc: string; begin result := fItemDesc; end; procedure TrmCustomDayViewItem.SetItemDesc(const Value: string); begin if fItemDesc <> value then begin fItemDesc := value; UpdateHint; end; end; procedure TrmCustomDayViewItem.DoIntMouseEnter(sender: TObject); begin Application.HintHidePause := 300000; end; procedure TrmCustomDayViewItem.DoIntMouseLeave(sender: TObject); begin Application.HintHidePause := 2500; end; procedure TrmCustomDayViewItem.wmupdateall(var message: tmessage); begin UpdateTop; UpdateHeight; UpdateOverlap; updateHint; end; procedure TrmCustomDayViewItem.wmupdateheights(var message: tmessage); begin UpdateHeight; end; procedure TrmCustomDayViewItem.wmupdateoverlaps(var message: Tmessage); begin UpdateOverlap; end; procedure TrmCustomDayViewItem.wmupdatetops(var message: Tmessage); begin UpdateTop; end; { TrmDayViewCollectionItem } procedure TrmDayViewCollectionItem.Assign(Source: TPersistent); begin inherited; end; constructor TrmDayViewCollectionItem.Create(Collection: TCollection); begin inherited create(Collection); fDayViewItem := TrmDayViewItem.create(TrmDayViewCollection(Collection).FDayView); fDayViewItem.Parent := TrmDayViewCollection(Collection).FDayView; fDayViewItem.DayView := TrmDayViewCollection(Collection).FDayView; fDayViewItem.OnClick := TrmDayViewCollection(Collection).FDayView.DoItemClick; fDayViewItem.OnDblClick := TrmDayViewCollection(Collection).FDayView.DoItemDblclick; fDayViewItem.CollectionItem := self; fTag := 0; end; destructor TrmDayViewCollectionItem.Destroy; begin if fDayViewItem.DayView.SelectedItem = self then fDayViewItem.DayView.SetSelectedItem(nil); fDayViewItem.CollectionItem := nil; fDayViewItem.DayView := nil; fDayViewItem.Free; inherited; end; function TrmDayViewCollectionItem.GetCaption: TCaption; begin if fDayViewItem <> nil then result := fDayViewItem.Caption else result := ''; end; function TrmDayViewCollectionItem.Getcolor: TColor; begin if fDayViewItem <> nil then result := fDayViewItem.Color else result := clBtnFace; end; function TrmDayViewCollectionItem.GetDuration: integer; begin if fDayViewItem <> nil then result := fDayViewItem.Duration else result := 0; end; function TrmDayViewCollectionItem.GetItemColor: TColor; begin if fDayViewItem <> nil then result := fDayViewItem.ItemColor else result := clBlue; end; function TrmDayViewCollectionItem.GetItemDesc: string; begin if fDayViewItem <> nil then result := fDayViewItem.ItemDescription else result := ''; end; function TrmDayViewCollectionItem.GetItemFont: TFont; begin if fDayViewItem <> nil then result := fDayViewItem.Font else result := nil; end; function TrmDayViewCollectionItem.GetPopup: TPopupMenu; begin if fDayViewItem <> nil then result := fDayViewItem.PopupMenu else result := nil; end; function TrmDayViewCollectionItem.GetShowHint: boolean; begin if fDayViewItem <> nil then result := fDayViewItem.ShowHint else result := false; end; function TrmDayViewCollectionItem.GetStartTime: TTime; begin if fDayViewItem <> nil then result := fDayViewItem.StartTime else result := 0; end; procedure TrmDayViewCollectionItem.SetCaption(const Value: TCaption); begin if fDayViewItem <> nil then fDayViewItem.Caption := value; end; procedure TrmDayViewCollectionItem.SetColor(const Value: TColor); begin if fDayViewItem <> nil then fDayViewItem.color := value; end; procedure TrmDayViewCollectionItem.SetDuration(const Value: integer); begin if fDayViewItem <> nil then fDayViewItem.Duration := Value; end; procedure TrmDayViewCollectionItem.SetItemColor(const Value: TColor); begin if fDayViewItem <> nil then fDayViewItem.ItemColor := value end; procedure TrmDayViewCollectionItem.SetItemDesc(const Value: string); begin if fDayViewItem <> nil then fDayViewItem.ItemDescription := value; end; procedure TrmDayViewCollectionItem.SetItemFont(const Value: TFont); begin if fDayViewItem <> nil then fDayViewItem.font.assign(value); end; procedure TrmDayViewCollectionItem.SetPopup(const Value: TPopupMenu); begin if fDayViewItem <> nil then fDayViewItem.PopupMenu := value; end; procedure TrmDayViewCollectionItem.SetShowHint(const Value: boolean); begin if fDayViewItem <> nil then fDayViewItem.ShowHint := value; end; procedure TrmDayViewCollectionItem.SetStartTime(const Value: TTime); begin if fDayViewItem <> nil then fDayViewItem.StartTime := value; end; procedure TrmDayViewCollectionItem.UpdateOverlap; begin PostMessage(fDayViewItem.Handle, wm_UpdateOverlaps, 0, 0); end; procedure TrmDayViewCollectionItem.UpdateTop; begin PostMessage(fDayViewItem.Handle, wm_updateTops, 0, 0); end; procedure TrmDayViewCollectionItem.UpdateViewDetails; begin PostMessage(fDayViewItem.Handle, wm_updateAll, 0, 0); end; { TrmDayViewCollection } function TrmDayViewCollection.Add: TrmDayViewCollectionItem; begin Result := TrmDayViewCollectionItem(inherited Add); end; constructor TrmDayViewCollection.Create(DayView: TrmCustomDayView); begin inherited create(TrmDayViewCollectionItem); FDayView := TrmDayView(DayView); end; procedure TrmDayViewCollection.Delete(Index: Integer); begin inherited Delete(index); end; function TrmDayViewCollection.GetItem( Index: Integer): TrmDayViewCollectionItem; begin Result := TrmDayViewCollectionItem(inherited GetItem(Index)); end; function TrmDayViewCollection.GetOwner: TPersistent; begin result := FDayView; end; function TrmDayViewCollection.Insert( Index: Integer): TrmDayViewCollectionItem; begin Result := TrmDayViewCollectionItem(inherited Insert(index)); end; procedure TrmDayViewCollection.SetItem(Index: Integer; Value: TrmDayViewCollectionItem); begin inherited SetItem(Index, Value); end; procedure TrmDayViewCollection.Update(Item: TCollectionItem); begin inherited; if assigned(fOnUpdate) then fOnUpdate(item); end; end.
unit API_ORM_Bind; interface uses System.Generics.Collections, API_ORM; type TBindItem = record Control: TObject; Entity: TEntityAbstract; Index: Integer; end; TBind = class private FBindArray: TArray<TBindItem>; public procedure AddBind(aControl: TObject; aEntity: TEntityAbstract; aIndex: Integer = 0); procedure RemoveBind(aControl: TObject; aIndex: Integer = 0); function GetEntityByControl(aControl: TObject; aIndex: Integer = 0): TEntityAbstract; function GetControlByEntity(aEntity: TEntityAbstract): TObject; end; implementation procedure TBind.RemoveBind(aControl: TObject; aIndex: Integer = 0); var BindItem: TBindItem; i: Integer; begin i := -1; for BindItem in FBindArray do begin Inc(i); if (BindItem.Control = aControl) and (BindItem.Index = aIndex) then Delete(FBindArray, i, 1); end; end; function TBind.GetControlByEntity(aEntity: TEntityAbstract): TObject; var BindItem: TBindItem; begin Result := nil; for BindItem in FBindArray do if BindItem.Entity = aEntity then Exit(BindItem.Control); end; procedure TBind.AddBind(aControl: TObject; aEntity: TEntityAbstract; aIndex: Integer = 0); var BindItem: TBindItem; begin BindItem.Control := aControl; BindItem.Entity := aEntity; BindItem.Index := aIndex; FBindArray := FBindArray + [BindItem]; end; function TBind.GetEntityByControl(aControl: TObject; aIndex: Integer = 0): TEntityAbstract; var BindItem: TBindItem; begin Result := nil; for BindItem in FBindArray do begin if (BindItem.Control = aControl) and (BindItem.Index = aIndex) then Exit(BindItem.Entity); end; end; end.
(*----------------------------------------------------------------------------* * Direct3D sample from DirectX 9.0 SDK December 2006 * * Delphi adaptation by Alexey Barkovoy (e-mail: directx@clootie.ru) * * * * Supported compilers: Delphi 5,6,7,9; FreePascal 2.0 * * * * Latest version can be downloaded from: * * http://www.clootie.ru * * http://sourceforge.net/projects/delphi-dx9sdk * *----------------------------------------------------------------------------* * $Id: ShadowVolumeUnit.pas,v 1.16 2007/02/05 22:21:12 clootie Exp $ *----------------------------------------------------------------------------*) //-------------------------------------------------------------------------------------- // File: ShadowVolume.cpp // // Starting point for new Direct3D applications // // Copyright (c) Microsoft Corporation. All rights reserved. //-------------------------------------------------------------------------------------- {$I DirectX.inc} unit ShadowVolumeUnit; interface uses Windows, Messages, SysUtils, Math, StrSafe, DXTypes, Direct3D9, D3DX9, dxerr9, DXUT, DXUTcore, DXUTenum, DXUTmisc, DXUTgui, DXUTMesh, DXUTSettingsDlg; {.$DEFINE SYNCRO_BY_FENCE} {.$DEFINE DEBUG_VS} // Uncomment this line to debug vertex shaders {.$DEFINE DEBUG_PS} // Uncomment this line to debug pixel shaders const DEFMESHFILENAME = 'dwarf\dwarf.x'; MAX_NUM_LIGHTS = 6; ADJACENCY_EPSILON = 0.0001; EXTRUDE_EPSILON = 0.1; AMBIENT = 0.10; type TRenderType = (RENDERTYPE_SCENE, RENDERTYPE_SHADOWVOLUME, RENDERTYPE_COMPLEXITY); var g_vShadowColor: array[0..MAX_NUM_LIGHTS-1] of TD3DXVector4; type PLightInitData = ^TLightInitData; TLightInitData = record Position: TD3DXVector3; Color: TD3DXVector4; end; function LightInitData(const P: TD3DXVector3; const C: TD3DXVector4): TLightInitData; var g_LightInit: array[0..MAX_NUM_LIGHTS-1] of TLightInitData; type PPostProcVert = ^TPostProcVert; TPostProcVert = packed record x, y, z: Single; rhw: Single; end; const TPostProcVert_Decl: array [0..1] of TD3DVertexElement9 = ( (Stream: 0; Offset: 0; _Type: D3DDECLTYPE_FLOAT4; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_POSITIONT; UsageIndex: 0), {D3DDECL_END()}(Stream:$FF; Offset:0; _Type:D3DDECLTYPE_UNUSED; Method:TD3DDeclMethod(0); Usage:TD3DDeclUsage(0); UsageIndex:0) ); function PostProcVert(x, y, z, rhw: Single): TPostProcVert; type PShadowVert = ^TShadowVert; TShadowVert = packed record Position: TD3DXVector3; Normal: TD3DXVector3; end; PShadowVertArray = ^TShadowVertArray; TShadowVertArray = array[0..MaxInt div SizeOf(TShadowVert)-1] of TShadowVert; const TShadowVert_Decl: array [0..2] of TD3DVertexElement9 = ( (Stream: 0; Offset: 0; _Type: D3DDECLTYPE_FLOAT3; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_POSITION; UsageIndex: 0), (Stream: 0; Offset: 12; _Type: D3DDECLTYPE_FLOAT3; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_NORMAL; UsageIndex: 0), {D3DDECL_END()}(Stream:$FF; Offset:0; _Type:D3DDECLTYPE_UNUSED; Method:TD3DDeclMethod(0); Usage:TD3DDeclUsage(0); UsageIndex:0) ); type TMeshVert = packed record Position: TD3DXVector3; Normal: TD3DXVector3; Tex: TD3DXVector2; end; const TMeshVert_Decl: array [0..3] of TD3DVertexElement9 = ( (Stream: 0; Offset: 0; _Type: D3DDECLTYPE_FLOAT3; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_POSITION; UsageIndex: 0), (Stream: 0; Offset: 12; _Type: D3DDECLTYPE_FLOAT3; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_NORMAL; UsageIndex: 0), (Stream: 0; Offset: 24; _Type: D3DDECLTYPE_FLOAT2; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_TEXCOORD; UsageIndex: 0), {D3DDECL_END()}(Stream:$FF; Offset:0; _Type:D3DDECLTYPE_UNUSED; Method:TD3DDeclMethod(0); Usage:TD3DDeclUsage(0); UsageIndex:0) ); type PEdgeMapping = ^TEdgeMapping; TEdgeMapping = record m_anOldEdge: array[0..1] of Integer; // vertex index of the original edge m_aanNewEdge: array[0..1, 0..1] of Integer; // vertex indexes of the new edge // First subscript = index of the new edge // Second subscript = index of the vertex for the edge // CEdgeMapping() { FillMemory( m_anOldEdge, sizeof(m_anOldEdge), -1 ); FillMemory( m_aanNewEdge, sizeof(m_aanNewEdge), -1 ); } end; function EdgeMapping: TEdgeMapping; type TLight = record m_Position: TD3DXVector3; // Light position m_Color: TD3DXVector4; // Light color m_mWorld: TD3DXMatrixA16; // World transform end; //-------------------------------------------------------------------------------------- // Global variables //-------------------------------------------------------------------------------------- var g_pFont: ID3DXFont; // Font for drawing text g_pTextSprite: ID3DXSprite; // Sprite for batching draw text calls g_pEffect: ID3DXEffect; // D3DX effect interface g_pDefaultTex: IDirect3DTexture9; // Default texture for faces without one g_pMeshDecl: IDirect3DVertexDeclaration9; // Vertex declaration for the meshes g_pShadowDecl: IDirect3DVertexDeclaration9; // Vertex declaration for the shadow volume g_pPProcDecl: IDirect3DVertexDeclaration9; // Vertex declaration for post-process quad rendering g_Camera: CFirstPersonCamera; // Viewer's camera g_MCamera: CModelViewerCamera; // Camera for mesh control g_LCamera: CModelViewerCamera; // Camera for easy light movement control g_hRenderShadow: TD3DXHandle; // Technique handle for rendering shadow g_hShowShadow: TD3DXHandle; // Technique handle for showing shadow volume g_hRenderScene: TD3DXHandle; // Technique handle for rendering scene g_mWorldScaling: TD3DXMatrixA16; // Scaling to apply to mesh g_bShowHelp: Boolean = True; // If true, it renders the UI control text g_bShowShadowVolume: Boolean = False; // Whether the shadow volume is visibly shown. g_RenderType: TRenderType = RENDERTYPE_SCENE; // Type of rendering to perform g_nNumLights: Integer = 1; // Number of active lights g_Background: array[0..1] of CDXUTMesh; // Background meshes g_mWorldBack: array[0..1] of TD3DXMatrixA16;// Additional scaling and translation for background meshes g_nCurrBackground: Integer = 0; // Current background mesh g_LightMesh: CDXUTMesh; // Mesh to represent the light source g_Mesh: CDXUTMesh; // The mesh object g_pShadowMesh: ID3DXMesh; // The shadow volume mesh g_DialogResourceManager: CDXUTDialogResourceManager; // manager for shared resources of dialogs g_SettingsDlg: CD3DSettingsDlg; // Device settings dialog g_HUD: CDXUTDialog; // dialog for standard controls g_SampleUI: CDXUTDialog; // dialog for sample specific controls g_mProjection: TD3DXMatrixA16; g_aLights: array[0..MAX_NUM_LIGHTS-1] of TLight; // Light objects g_bLeftButtonDown: Boolean = False; g_bRightButtonDown: Boolean = False; g_bMiddleButtonDown: Boolean = False; //-------------------------------------------------------------------------------------- // UI control IDs //-------------------------------------------------------------------------------------- const IDC_TOGGLEFULLSCREEN = 1; IDC_TOGGLEREF = 3; IDC_CHANGEDEVICE = 4; IDC_RENDERTYPE = 5; IDC_ENABLELIGHT = 6; IDC_LUMINANCELABEL = 7; IDC_LUMINANCE = 8; IDC_BACKGROUND = 9; IDC_CHANGEMESH = 10; IDC_MESHFILENAME = 11; //-------------------------------------------------------------------------------------- // Forward declarations //-------------------------------------------------------------------------------------- function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall; function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall; function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall; function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall; procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall; procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall; function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall; procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall; procedure MouseProc(bLeftButtonDown, bRightButtonDown, bMiddleButtonDown, bSideButton1Down, bSideButton2Down: Boolean; nMouseWheelDelta: Integer; xPos, yPos: Integer; pUserContext: Pointer); stdcall; procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall; procedure OnLostDevice(pUserContext: Pointer); stdcall; procedure OnDestroyDevice(pUserContext: Pointer); stdcall; procedure InitApp; //todo: Fill bug report to MS //function LoadMesh(const pd3dDevice: IDirect3DDevice9; wszName: PWideChar; out ppMesh: ID3DXMesh): HRESULT; procedure RenderText; procedure CreateCustomDXUTobjects; procedure DestroyCustomDXUTobjects; implementation //-------------------------------------------------------------------------------------- // Takes an array of CEdgeMapping objects, then returns an index for the edge in the // table if such entry exists, or returns an index at which a new entry for the edge // can be written. // nV1 and nV2 are the vertex indexes for the old edge. // nCount is the number of elements in the array. // The function returns -1 if an available entry cannot be found. In reality, // this should never happens as we should have allocated enough memory. function FindEdgeInMappingTable(nV1, nV2: Integer; var pMapping: array of TEdgeMapping; nCount: Integer): Integer; var i: Integer; begin for i := 0 to nCount-1 do begin // If both vertex indexes of the old edge in mapping entry are -1, then // we have searched every valid entry without finding a match. Return // this index as a newly created entry. if ((pMapping[i].m_anOldEdge[0] = -1) and (pMapping[i].m_anOldEdge[1] = -1) or // Or if we find a match, return the index. (pMapping[i].m_anOldEdge[1] = nV1) and (pMapping[i].m_anOldEdge[0] = nV2)) then begin Result:= i; Exit; end; end; Result:= -1; // We should never reach this line end; //-------------------------------------------------------------------------------------- // Takes a mesh and generate a new mesh from it that contains the degenerate invisible // quads for shadow volume extrusion. function GenerateShadowMesh(const pd3dDevice: IDirect3DDevice9; const pMesh: ID3DXMesh; out ppOutMesh: ID3DXMesh): HRESULT; var pInputMesh: ID3DXMesh; pdwAdj: PDWORD; pdwPtRep: PDWordArray; pVBData: PShadowVert; pdwIBData: PDWordArray; dwNumEdges: DWORD; pMapping: array of TEdgeMapping; nNumMaps: DWORD; // Integer; // Number of entries that exist in pMapping pNewMesh: ID3DXMesh; pNewVBData: PShadowVertArray; pdwNewIBData: PDWordArray; nNextIndex: DWORD; // Integer; pNextOutVertex: PShadowVertArray; f: LongWord; v1, v2: TD3DXVector3; vNormal: TD3DXVector3; nIndex: Integer; nVertIndex: array[0..2] of Integer; pPatchVBData: PShadowVertArray; pdwPatchIBData: PDWordArray; pPatchMesh: ID3DXMesh; nNextVertex: Integer; i, i2: Integer; nVertShared: Integer; nBefore, nAfter: Integer; bNeed32Bit: Boolean; pFinalMesh: ID3DXMesh; pFinalVBData: PShadowVert; pwFinalIBData: PWordArray; begin ppOutMesh := nil; pMapping:= nil; // Convert the input mesh to a format same as the output mesh using 32-bit index. Result := pMesh.CloneMesh(D3DXMESH_32BIT, @TShadowVert_Decl, pd3dDevice, pInputMesh); if FAILED(Result) then Exit; DXUT_TRACE('Input mesh has %u vertices, %u faces'#10, [pInputMesh.GetNumVertices, pInputMesh.GetNumFaces]); // Generate adjacency information pdwAdj := nil; pdwPtRep := nil; try GetMem(pdwAdj, SizeOf(DWORD)*3*pInputMesh.GetNumFaces); GetMem(pdwPtRep, SizeOf(DWORD)*pInputMesh.GetNumVertices); except FreeMem(pdwAdj); FreeMem(pdwPtRep); Result:= E_OUTOFMEMORY; Exit; end; Result := pInputMesh.GenerateAdjacency(ADJACENCY_EPSILON, pdwAdj); if FAILED(Result) then begin FreeMem(pdwAdj); FreeMem(pdwPtRep); Exit; end; pInputMesh.ConvertAdjacencyToPointReps(pdwAdj, PDWORD(pdwPtRep)); FreeMem(pdwAdj); pVBData:= nil; pdwIBData:= nil; pInputMesh.LockVertexBuffer(0, Pointer(pVBData)); pInputMesh.LockIndexBuffer(0, Pointer(pdwIBData)); try // "Lock" data protected block if Assigned(pVBData) and Assigned(pdwIBData) then begin // Maximum number of unique edges = Number of faces * 3 dwNumEdges := pInputMesh.GetNumFaces * 3; try SetLength(pMapping, dwNumEdges); for i:= 0 to dwNumEdges - 1 do pMapping[i]:= EdgeMapping; // init them except pMapping:= nil; end; if Assigned(pMapping) then begin nNumMaps := 0; // Number of entries that exist in pMapping // Create a new mesh Result := D3DXCreateMesh(pInputMesh.GetNumFaces + dwNumEdges * 2, pInputMesh.GetNumFaces * 3, D3DXMESH_32BIT, @TShadowVert_Decl, pd3dDevice, pNewMesh); if SUCCEEDED(Result) then begin pNewVBData := nil; pdwNewIBData := nil; pNewMesh.LockVertexBuffer(0, Pointer(pNewVBData)); pNewMesh.LockIndexBuffer(0, Pointer(pdwNewIBData)); // nNextIndex is the array index in IB that the next vertex index value // will be store at. nNextIndex := 0; try // "cleanup" protected block if Assigned(pNewVBData) and Assigned(pdwNewIBData) then begin ZeroMemory(pNewVBData, pNewMesh.GetNumVertices * pNewMesh.GetNumBytesPerVertex); ZeroMemory(pdwNewIBData, SizeOf(DWORD) * pNewMesh.GetNumFaces * 3); // pNextOutVertex is the location to write the next // vertex to. pNextOutVertex := pNewVBData; // Iterate through the faces. For each face, output new // vertices and face in the new mesh, and write its edges // to the mapping table. for f := 0 to pInputMesh.GetNumFaces - 1 do begin // Copy the vertex data for all 3 vertices CopyMemory(pNextOutVertex, PChar(pVBData) + pdwIBData[f * 3]*SizeOf(TShadowVert), SizeOf(TShadowVert)); CopyMemory(@pNextOutVertex[1], PChar(pVBData) + pdwIBData[f * 3 + 1]*SizeOf(TShadowVert), SizeOf(TShadowVert)); CopyMemory(@pNextOutVertex[2], PChar(pVBData) + pdwIBData[f * 3 + 2]*SizeOf(TShadowVert), SizeOf(TShadowVert)); // Write out the face pdwNewIBData[nNextIndex] := f * 3; Inc(nNextIndex); pdwNewIBData[nNextIndex] := f * 3 + 1; Inc(nNextIndex); pdwNewIBData[nNextIndex] := f * 3 + 2; Inc(nNextIndex); // Compute the face normal and assign it to // the normals of the vertices. D3DXVec3Subtract(v1, pNextOutVertex[1].Position, pNextOutVertex[0].Position); D3DXVec3Subtract(v2, pNextOutVertex[2].Position, pNextOutVertex[1].Position); D3DXVec3Cross(vNormal, v1, v2); D3DXVec3Normalize(vNormal, vNormal); pNextOutVertex[0].Normal := vNormal; pNextOutVertex[1].Normal := vNormal; pNextOutVertex[2].Normal := vNormal; pNextOutVertex := @pNextOutVertex[3]; // Add the face's edges to the edge mapping table // Edge 1 nVertIndex[0] := pdwPtRep[pdwIBData[f * 3]]; nVertIndex[1] := pdwPtRep[pdwIBData[f * 3 + 1]]; nVertIndex[2] := pdwPtRep[pdwIBData[f * 3 + 2]]; nIndex := FindEdgeInMappingTable(nVertIndex[0], nVertIndex[1], pMapping, dwNumEdges); // If error, we are not able to proceed, so abort. if (-1 = nIndex) then begin Result := E_INVALIDARG; Exit; // goto cleanup; end; if (pMapping[nIndex].m_anOldEdge[0] = -1) and (pMapping[nIndex].m_anOldEdge[1] = -1) then begin // No entry for this edge yet. Initialize one. pMapping[nIndex].m_anOldEdge[0] := nVertIndex[0]; pMapping[nIndex].m_anOldEdge[1] := nVertIndex[1]; pMapping[nIndex].m_aanNewEdge[0][0] := f * 3; pMapping[nIndex].m_aanNewEdge[0][1] := f * 3 + 1; Inc(nNumMaps); end else begin // An entry is found for this edge. Create // a quad and output it. Assert(nNumMaps > 0); pMapping[nIndex].m_aanNewEdge[1][0] := f * 3; // For clarity pMapping[nIndex].m_aanNewEdge[1][1] := f * 3 + 1; // First triangle pdwNewIBData[nNextIndex] := pMapping[nIndex].m_aanNewEdge[0][1]; Inc(nNextIndex); pdwNewIBData[nNextIndex] := pMapping[nIndex].m_aanNewEdge[0][0]; Inc(nNextIndex); pdwNewIBData[nNextIndex] := pMapping[nIndex].m_aanNewEdge[1][0]; Inc(nNextIndex); // Second triangle pdwNewIBData[nNextIndex] := pMapping[nIndex].m_aanNewEdge[1][1]; Inc(nNextIndex); pdwNewIBData[nNextIndex] := pMapping[nIndex].m_aanNewEdge[1][0]; Inc(nNextIndex); pdwNewIBData[nNextIndex] := pMapping[nIndex].m_aanNewEdge[0][0]; Inc(nNextIndex); // pMapping[nIndex] is no longer needed. Copy the last map entry // over and decrement the map count. pMapping[nIndex] := pMapping[nNumMaps-1]; FillMemory(@pMapping[nNumMaps-1], SizeOf(pMapping[nNumMaps-1]), $ff); Dec(nNumMaps); end; // Edge 2 nIndex := FindEdgeInMappingTable(nVertIndex[1], nVertIndex[2], pMapping, dwNumEdges); // If error, we are not able to proceed, so abort. if (-1 = nIndex) then begin Result := E_INVALIDARG; Exit; // goto cleanup; end; if (pMapping[nIndex].m_anOldEdge[0] = -1) and (pMapping[nIndex].m_anOldEdge[1] = -1) then begin pMapping[nIndex].m_anOldEdge[0] := nVertIndex[1]; pMapping[nIndex].m_anOldEdge[1] := nVertIndex[2]; pMapping[nIndex].m_aanNewEdge[0][0] := f * 3 + 1; pMapping[nIndex].m_aanNewEdge[0][1] := f * 3 + 2; Inc(nNumMaps); end else begin // An entry is found for this edge. Create // a quad and output it. Assert(nNumMaps > 0); pMapping[nIndex].m_aanNewEdge[1][0] := f * 3 + 1; pMapping[nIndex].m_aanNewEdge[1][1] := f * 3 + 2; // First triangle pdwNewIBData[nNextIndex] := pMapping[nIndex].m_aanNewEdge[0][1]; Inc(nNextIndex); pdwNewIBData[nNextIndex] := pMapping[nIndex].m_aanNewEdge[0][0]; Inc(nNextIndex); pdwNewIBData[nNextIndex] := pMapping[nIndex].m_aanNewEdge[1][0]; Inc(nNextIndex); // Second triangle pdwNewIBData[nNextIndex] := pMapping[nIndex].m_aanNewEdge[1][1]; Inc(nNextIndex); pdwNewIBData[nNextIndex] := pMapping[nIndex].m_aanNewEdge[1][0]; Inc(nNextIndex); pdwNewIBData[nNextIndex] := pMapping[nIndex].m_aanNewEdge[0][0]; Inc(nNextIndex); // pMapping[nIndex] is no longer needed. Copy the last map entry // over and decrement the map count. pMapping[nIndex] := pMapping[nNumMaps-1]; FillMemory(@pMapping[nNumMaps-1], SizeOf(pMapping[nNumMaps-1]), $ff); Dec(nNumMaps); end; // Edge 3 nIndex := FindEdgeInMappingTable(nVertIndex[2], nVertIndex[0], pMapping, dwNumEdges); // If error, we are not able to proceed, so abort. if (-1 = nIndex) then begin Result := E_INVALIDARG; Exit; // goto cleanup; end; if (pMapping[nIndex].m_anOldEdge[0] = -1) and (pMapping[nIndex].m_anOldEdge[1] = -1) then begin pMapping[nIndex].m_anOldEdge[0] := nVertIndex[2]; pMapping[nIndex].m_anOldEdge[1] := nVertIndex[0]; pMapping[nIndex].m_aanNewEdge[0][0] := f * 3 + 2; pMapping[nIndex].m_aanNewEdge[0][1] := f * 3; Inc(nNumMaps); end else begin // An entry is found for this edge. Create // a quad and output it. Assert(nNumMaps > 0); pMapping[nIndex].m_aanNewEdge[1][0] := f * 3 + 2; pMapping[nIndex].m_aanNewEdge[1][1] := f * 3; // First triangle pdwNewIBData[nNextIndex] := pMapping[nIndex].m_aanNewEdge[0][1]; Inc(nNextIndex); pdwNewIBData[nNextIndex] := pMapping[nIndex].m_aanNewEdge[0][0]; Inc(nNextIndex); pdwNewIBData[nNextIndex] := pMapping[nIndex].m_aanNewEdge[1][0]; Inc(nNextIndex); // Second triangle pdwNewIBData[nNextIndex] := pMapping[nIndex].m_aanNewEdge[1][1]; Inc(nNextIndex); pdwNewIBData[nNextIndex] := pMapping[nIndex].m_aanNewEdge[1][0]; Inc(nNextIndex); pdwNewIBData[nNextIndex] := pMapping[nIndex].m_aanNewEdge[0][0]; Inc(nNextIndex); // pMapping[nIndex] is no longer needed. Copy the last map entry // over and decrement the map count. pMapping[nIndex] := pMapping[nNumMaps-1]; FillMemory(@pMapping[nNumMaps-1], SizeOf( pMapping[nNumMaps-1] ), $ff); Dec(nNumMaps); end; end; // Now the entries in the edge mapping table represent // non-shared edges. What they mean is that the original // mesh has openings (holes), so we attempt to patch them. // First we need to recreate our mesh with a larger vertex // and index buffers so the patching geometry could fit. DXUT_TRACE('Faces to patch: %d'#10, [nNumMaps]); // Create a mesh with large enough vertex and // index buffers. pPatchVBData := nil; pdwPatchIBData := nil; // Make enough room in IB for the face and up to 3 quads for each patching face Result := D3DXCreateMesh(nNextIndex div 3 + nNumMaps * 7, (pInputMesh.GetNumFaces + nNumMaps) * 3, D3DXMESH_32BIT, @TShadowVert_Decl, pd3dDevice, pPatchMesh); if FAILED(Result) then Exit; // goto cleanup; Result := pPatchMesh.LockVertexBuffer(0, Pointer(pPatchVBData)); if SUCCEEDED(Result) then Result := pPatchMesh.LockIndexBuffer(0, Pointer(pdwPatchIBData)); if Assigned(pPatchVBData) and Assigned(pdwPatchIBData) then begin ZeroMemory(pPatchVBData, SizeOf(TShadowVert) * (pInputMesh.GetNumFaces + nNumMaps) * 3); ZeroMemory(pdwPatchIBData, SizeOf(DWORD) * (nNextIndex + 3 * nNumMaps * 7)); // Copy the data from one mesh to the other CopyMemory(pPatchVBData, pNewVBData, SizeOf(TShadowVert) * pInputMesh.GetNumFaces * 3); CopyMemory(pdwPatchIBData, pdwNewIBData, SizeOf(DWORD) * nNextIndex); end else begin // Some serious error is preventing us from locking. // Abort and return error. pPatchMesh := nil; // goto cleanup; Exit; end; // Replace pNewMesh with the updated one. Then the code // can continue working with the pNewMesh pointer. pNewMesh.UnlockVertexBuffer; pNewMesh.UnlockIndexBuffer; pNewVBData := pPatchVBData; pdwNewIBData := pdwPatchIBData; pNewMesh := nil; pNewMesh := pPatchMesh; // Now, we iterate through the edge mapping table and // for each shared edge, we generate a quad. // For each non-shared edge, we patch the opening // with new faces. // nNextVertex is the index of the next vertex. nNextVertex := pInputMesh.GetNumFaces * 3; for i := 0 to nNumMaps-1 do begin if (pMapping[i].m_anOldEdge[0] <> -1) and (pMapping[i].m_anOldEdge[1] <> -1) then begin // If the 2nd new edge indexes is -1, // this edge is a non-shared one. // We patch the opening by creating new // faces. if (pMapping[i].m_aanNewEdge[1][0] = -1) or // must have only one new edge (pMapping[i].m_aanNewEdge[1][1] = -1) then begin // Find another non-shared edge that // shares a vertex with the current edge. for i2 := i + 1 to nNumMaps - 1 do begin if (pMapping[i2].m_anOldEdge[0] <> -1) and // must have a valid old edge (pMapping[i2].m_anOldEdge[1] <> -1) and ((pMapping[i2].m_aanNewEdge[1][0] = -1) or // must have only one new edge (pMapping[i2].m_aanNewEdge[1][1] = -1)) then begin nVertShared := 0; if (pMapping[i2].m_anOldEdge[0] = pMapping[i].m_anOldEdge[1]) then Inc(nVertShared); if (pMapping[i2].m_anOldEdge[1] = pMapping[i].m_anOldEdge[0]) then Inc(nVertShared); if (2 = nVertShared) then begin // These are the last two edges of this particular // opening. Mark this edge as shared so that a degenerate // quad can be created for it. pMapping[i2].m_aanNewEdge[1][0] := pMapping[i].m_aanNewEdge[0][0]; pMapping[i2].m_aanNewEdge[1][1] := pMapping[i].m_aanNewEdge[0][1]; Break; end else if (1 = nVertShared) then begin // nBefore and nAfter tell us which edge comes before the other. if (pMapping[i2].m_anOldEdge[0] = pMapping[i].m_anOldEdge[1]) then begin nBefore := i; nAfter := i2; end else begin nBefore := i2; nAfter := i; end; // Found such an edge. Now create a face along with two // degenerate quads from these two edges. pNewVBData[nNextVertex] := pNewVBData[pMapping[nAfter].m_aanNewEdge[0][1]]; pNewVBData[nNextVertex+1] := pNewVBData[pMapping[nBefore].m_aanNewEdge[0][1]]; pNewVBData[nNextVertex+2] := pNewVBData[pMapping[nBefore].m_aanNewEdge[0][0]]; // Recompute the normal D3DXVec3Subtract(v1, pNewVBData[nNextVertex+1].Position, pNewVBData[nNextVertex].Position); D3DXVec3Subtract(v2, pNewVBData[nNextVertex+2].Position, pNewVBData[nNextVertex+1].Position); D3DXVec3Normalize(v1, v1); D3DXVec3Normalize(v2, v2); D3DXVec3Cross(vNormal, v1, v2); pNewVBData[nNextVertex].Normal := vNormal; pNewVBData[nNextVertex+1].Normal := vNormal; pNewVBData[nNextVertex+2].Normal := vNormal; pdwNewIBData[nNextIndex] := nNextVertex; pdwNewIBData[nNextIndex+1] := nNextVertex + 1; pdwNewIBData[nNextIndex+2] := nNextVertex + 2; // 1st quad pdwNewIBData[nNextIndex+3] := pMapping[nBefore].m_aanNewEdge[0][1]; pdwNewIBData[nNextIndex+4] := pMapping[nBefore].m_aanNewEdge[0][0]; pdwNewIBData[nNextIndex+5] := nNextVertex + 1; pdwNewIBData[nNextIndex+6] := nNextVertex + 2; pdwNewIBData[nNextIndex+7] := nNextVertex + 1; pdwNewIBData[nNextIndex+8] := pMapping[nBefore].m_aanNewEdge[0][0]; // 2nd quad pdwNewIBData[nNextIndex+9] := pMapping[nAfter].m_aanNewEdge[0][1]; pdwNewIBData[nNextIndex+10] := pMapping[nAfter].m_aanNewEdge[0][0]; pdwNewIBData[nNextIndex+11] := nNextVertex; pdwNewIBData[nNextIndex+12] := nNextVertex + 1; pdwNewIBData[nNextIndex+13] := nNextVertex; pdwNewIBData[nNextIndex+14] := pMapping[nAfter].m_aanNewEdge[0][0]; // Modify mapping entry i2 to reflect the third edge // of the newly added face. if (pMapping[i2].m_anOldEdge[0] = pMapping[i].m_anOldEdge[1]) then begin pMapping[i2].m_anOldEdge[0] := pMapping[i].m_anOldEdge[0]; end else begin pMapping[i2].m_anOldEdge[1] := pMapping[i].m_anOldEdge[1]; end; pMapping[i2].m_aanNewEdge[0][0] := nNextVertex + 2; pMapping[i2].m_aanNewEdge[0][1] := nNextVertex; // Update next vertex/index positions Inc(nNextVertex, 3); Inc(nNextIndex, 15); Break; end; end; end; end else begin // This is a shared edge. Create the degenerate quad. // First triangle pdwNewIBData[nNextIndex] := pMapping[i].m_aanNewEdge[0][1]; Inc(nNextIndex); pdwNewIBData[nNextIndex] := pMapping[i].m_aanNewEdge[0][0]; Inc(nNextIndex); pdwNewIBData[nNextIndex] := pMapping[i].m_aanNewEdge[1][0]; Inc(nNextIndex); // Second triangle pdwNewIBData[nNextIndex] := pMapping[i].m_aanNewEdge[1][1]; Inc(nNextIndex); pdwNewIBData[nNextIndex] := pMapping[i].m_aanNewEdge[1][0]; Inc(nNextIndex); pdwNewIBData[nNextIndex] := pMapping[i].m_aanNewEdge[0][0]; Inc(nNextIndex); end; end; end; end; finally // cleanup:; if Assigned(pNewVBData) then begin pNewMesh.UnlockVertexBuffer; pNewVBData := nil; end; if Assigned(pdwNewIBData) then begin pNewMesh.UnlockIndexBuffer; pdwNewIBData := nil; end; if SUCCEEDED(Result) then begin // At this time, the output mesh may have an index buffer // bigger than what is actually needed, so we create yet // another mesh with the exact IB size that we need and // output it. This mesh also uses 16-bit index if // 32-bit is not necessary. DXUT_TRACE('Shadow volume has %u vertices, %u faces.'#10, [(pInputMesh.GetNumFaces + nNumMaps ) * 3, nNextIndex div 3]); bNeed32Bit := ( pInputMesh.GetNumFaces + nNumMaps ) * 3 > 65535; Result := D3DXCreateMesh(nNextIndex div 3, // Exact number of faces ( pInputMesh.GetNumFaces + nNumMaps ) * 3, D3DXMESH_WRITEONLY or IfThen(bNeed32Bit, D3DXMESH_32BIT,0), @TShadowVert_Decl, pd3dDevice, pFinalMesh); if SUCCEEDED(Result) then begin pNewMesh.LockVertexBuffer(0, Pointer(pNewVBData)); pNewMesh.LockIndexBuffer(0, Pointer(pdwNewIBData)); pFinalVBData := nil; pwFinalIBData := nil; pFinalMesh.LockVertexBuffer(0, Pointer(pFinalVBData)); pFinalMesh.LockIndexBuffer(0, Pointer(pwFinalIBData)); if Assigned(pNewVBData) and Assigned(pdwNewIBData) and Assigned(pFinalVBData) and Assigned(pwFinalIBData) then begin CopyMemory(pFinalVBData, pNewVBData, SizeOf(TShadowVert) * (pInputMesh.GetNumFaces + nNumMaps) * 3); if (bNeed32Bit) then CopyMemory(pwFinalIBData, pdwNewIBData, SizeOf(DWORD) * nNextIndex) else begin for i := 0 to nNextIndex - 1 do pwFinalIBData[i] := pdwNewIBData[i]; end; end; if Assigned(pNewVBData) then pNewMesh.UnlockVertexBuffer; if Assigned(pdwNewIBData) then pNewMesh.UnlockIndexBuffer; if Assigned(pFinalVBData) then pFinalMesh.UnlockVertexBuffer; if Assigned(pwFinalIBData) then pFinalMesh.UnlockIndexBuffer; // Release the old // pNewMesh := nil; pNewMesh := pFinalMesh; end; ppOutMesh := pNewMesh; end else pNewMesh:= nil; end; end; pMapping:= nil; // delete[] pMapping; end else Result := E_OUTOFMEMORY; end else Result := E_FAIL; finally // try // "Lock" data protected block if Assigned(pVBData) then pInputMesh.UnlockVertexBuffer; if Assigned(pdwIBData) then pInputMesh.UnlockIndexBuffer; FreeMem(pdwPtRep); pInputMesh := nil; // not necessary in Delphi end; end; //-------------------------------------------------------------------------------------- // Initialize the app //-------------------------------------------------------------------------------------- procedure InitApp; var pDSFormats: TD3DFormatArray; iY: Integer; L: Integer; m: TD3DXMatrixA16; begin // This sample requires a stencil buffer. See the callback function for details. SetLength(pDSFormats, 4); pDSFormats[0]:= D3DFMT_D24S8; pDSFormats[1]:= D3DFMT_D24X4S4; pDSFormats[2]:= D3DFMT_D15S1; pDSFormats[3]:= D3DFMT_D24FS8; DXUTGetEnumeration.PossibleDepthStencilFormatList:= pDSFormats; // Initialize dialogs g_SettingsDlg.Init(g_DialogResourceManager); g_HUD.Init(g_DialogResourceManager); g_SampleUI.Init(g_DialogResourceManager); g_HUD.SetCallback(OnGUIEvent); iY := 10; g_HUD.AddButton(IDC_TOGGLEFULLSCREEN, 'Toggle full screen', 35, iY, 125, 22); Inc(iY, 24); g_HUD.AddButton(IDC_TOGGLEREF, 'Toggle REF (F3)', 35, iY, 125, 22); Inc(iY, 24); g_HUD.AddButton(IDC_CHANGEDEVICE, 'Change device (F2)', 35, iY, 125, 22, VK_F2); g_SampleUI.SetCallback(OnGUIEvent); iY := 10; Inc(iY, 24); g_SampleUI.AddComboBox(IDC_BACKGROUND, 0, iY, 190, 22, 0, False); g_SampleUI.GetComboBox(IDC_BACKGROUND).SetDropHeight( 40); g_SampleUI.GetComboBox(IDC_BACKGROUND).AddItem('Background: Cell', Pointer(0)); g_SampleUI.GetComboBox(IDC_BACKGROUND).AddItem('Background: Field', Pointer(1)); Inc(iY, 24); g_SampleUI.AddComboBox(IDC_ENABLELIGHT, 0, iY, 190, 22, 0, false); g_SampleUI.GetComboBox(IDC_ENABLELIGHT).SetDropHeight( 90); g_SampleUI.GetComboBox(IDC_ENABLELIGHT).AddItem('1 light', Pointer(1)); g_SampleUI.GetComboBox(IDC_ENABLELIGHT).AddItem('2 lights', Pointer(2)); g_SampleUI.GetComboBox(IDC_ENABLELIGHT).AddItem('3 lights', Pointer(3)); g_SampleUI.GetComboBox(IDC_ENABLELIGHT).AddItem('4 lights', Pointer(4)); g_SampleUI.GetComboBox(IDC_ENABLELIGHT).AddItem('5 lights', Pointer(5)); g_SampleUI.GetComboBox(IDC_ENABLELIGHT).AddItem('6 lights', Pointer(6)); Inc(iY, 24); g_SampleUI.AddComboBox(IDC_RENDERTYPE, 0, iY, 190, 22, 0, False); g_SampleUI.GetComboBox(IDC_RENDERTYPE).SetDropHeight(50); g_SampleUI.GetComboBox(IDC_RENDERTYPE).AddItem('Scene with shadow', Pointer(RENDERTYPE_SCENE)); g_SampleUI.GetComboBox(IDC_RENDERTYPE).AddItem('Show shadow volume', Pointer(RENDERTYPE_SHADOWVOLUME)); g_SampleUI.GetComboBox(IDC_RENDERTYPE).AddItem('Shadow volume complexity', Pointer(RENDERTYPE_COMPLEXITY)); Inc(iY, 30); g_SampleUI.AddStatic(IDC_LUMINANCELABEL, 'Luminance: 15.0', 45, iY, 125, 22); Inc(iY, 20); g_SampleUI.AddSlider(IDC_LUMINANCE, 45, iY, 125, 22, 1, 40, 15); Inc(iY, 26); g_SampleUI.AddButton(IDC_CHANGEMESH, 'Change mesh', 80, iY, 120, 40); // Initialize cameras g_Camera.SetRotateButtons(True, False, False); g_MCamera.SetButtonMasks(MOUSE_RIGHT_BUTTON, 0, 0); g_LCamera.SetButtonMasks(MOUSE_MIDDLE_BUTTON, 0, 0); // Initialize the lights for L := 0 to MAX_NUM_LIGHTS-1 do begin D3DXMatrixScaling(g_aLights[L].m_mWorld, 0.1, 0.1, 0.1); D3DXMatrixTranslation(m, g_LightInit[L].Position.x, g_LightInit[L].Position.y, g_LightInit[L].Position.z); D3DXMatrixMultiply( g_aLights[L].m_mWorld, g_aLights[L].m_mWorld, m); g_aLights[L].m_Position := g_LightInit[L].Position; g_aLights[L].m_Color := g_LightInit[L].Color; end; // Initialize the scaling and translation for the background meshes // Hardcode the matrices since we only have two. D3DXMatrixTranslation(g_mWorldBack[0], 0.0, 2.0, 0.0); D3DXMatrixScaling(g_mWorldBack[1], 0.3, 0.3, 0.3); D3DXMatrixTranslation(m, 0.0, 1.5, 0.0); D3DXMatrixMultiply(g_mWorldBack[1], g_mWorldBack[1], m); end; //-------------------------------------------------------------------------------------- // Returns true if a particular depth-stencil format can be created and used with // an adapter format and backbuffer format combination. function IsDepthFormatOk(DepthFormat, AdapterFormat, BackBufferFormat: TD3DFormat): Boolean; begin Result:= False; // Verify that the depth format exists if Failed(DXUTGetD3DObject.CheckDeviceFormat(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, AdapterFormat, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, DepthFormat)) then Exit; // Verify that the backbuffer format is valid if Failed(DXUTGetD3DObject.CheckDeviceFormat(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, AdapterFormat, D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, BackBufferFormat)) then Exit; // Verify that the depth format is compatible if Failed(DXUTGetD3DObject.CheckDepthStencilMatch(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, AdapterFormat, BackBufferFormat, DepthFormat)) then Exit; Result:= True; end; //-------------------------------------------------------------------------------------- // Called during device initialization, this code checks the device for some // minimum set of capabilities, and rejects those that don't pass by returning false. //-------------------------------------------------------------------------------------- function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall; var pD3D: IDirect3D9; begin Result:= False; // Skip backbuffer formats that don't support alpha blending pD3D := DXUTGetD3DObject; if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType, AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, D3DRTYPE_TEXTURE, BackBufferFormat)) then Exit; // Must support pixel shader 2.0 if (pCaps.PixelShaderVersion < D3DPS_VERSION(2,0)) then Exit; // Must support stencil buffer if not IsDepthFormatOk(D3DFMT_D24S8, AdapterFormat, BackBufferFormat) and not IsDepthFormatOk(D3DFMT_D24X4S4, AdapterFormat, BackBufferFormat) and not IsDepthFormatOk(D3DFMT_D15S1, AdapterFormat, BackBufferFormat) and not IsDepthFormatOk(D3DFMT_D24FS8, AdapterFormat, BackBufferFormat) then Exit; Result:= True; end; //-------------------------------------------------------------------------------------- // This callback function is called immediately before a device is created to allow the // application to modify the device settings. The supplied pDeviceSettings parameter // contains the settings that the framework has selected for the new device, and the // application can make any desired changes directly to this structure. Note however that // DXUT will not correct invalid device settings so care must be taken // to return valid device settings, otherwise IDirect3D9::CreateDevice() will fail. //-------------------------------------------------------------------------------------- {static} var s_bFirstTime: Boolean = True; function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall; begin // Turn vsync off pDeviceSettings.pp.PresentationInterval := D3DPRESENT_INTERVAL_IMMEDIATE; g_SettingsDlg.DialogControl.GetComboBox(DXUTSETTINGSDLG_PRESENT_INTERVAL).Enabled := False; // If device doesn't support HW T&L or doesn't support 1.1 vertex shaders in HW // then switch to SWVP. if (pCaps.DevCaps and D3DDEVCAPS_HWTRANSFORMANDLIGHT = 0) or (pCaps.VertexShaderVersion < D3DVS_VERSION(1,1)) then pDeviceSettings.BehaviorFlags := D3DCREATE_SOFTWARE_VERTEXPROCESSING; // Debugging vertex shaders requires either REF or software vertex processing // and debugging pixel shaders requires REF. {$IFDEF DEBUG_VS} if (pDeviceSettings.DeviceType <> D3DDEVTYPE_REF) then with pDeviceSettings do begin BehaviorFlags := BehaviorFlags and not D3DCREATE_HARDWARE_VERTEXPROCESSING; BehaviorFlags := BehaviorFlags and not D3DCREATE_PUREDEVICE; BehaviorFlags := BehaviorFlags or D3DCREATE_SOFTWARE_VERTEXPROCESSING; end; {$ENDIF} {$IFDEF DEBUG_PS} pDeviceSettings.DeviceType := D3DDEVTYPE_REF; {$ENDIF} // This sample requires a stencil buffer. if IsDepthFormatOk(D3DFMT_D24S8, pDeviceSettings.AdapterFormat, pDeviceSettings.pp.BackBufferFormat) then pDeviceSettings.pp.AutoDepthStencilFormat := D3DFMT_D24S8 else if IsDepthFormatOk(D3DFMT_D24X4S4, pDeviceSettings.AdapterFormat, pDeviceSettings.pp.BackBufferFormat) then pDeviceSettings.pp.AutoDepthStencilFormat := D3DFMT_D24X4S4 else if IsDepthFormatOk(D3DFMT_D24FS8, pDeviceSettings.AdapterFormat, pDeviceSettings.pp.BackBufferFormat) then pDeviceSettings.pp.AutoDepthStencilFormat := D3DFMT_D24FS8 else if IsDepthFormatOk(D3DFMT_D15S1, pDeviceSettings.AdapterFormat, pDeviceSettings.pp.BackBufferFormat) then pDeviceSettings.pp.AutoDepthStencilFormat := D3DFMT_D15S1; // For the first device created if its a REF device, optionally display a warning dialog box if s_bFirstTime then begin s_bFirstTime := False; if (pDeviceSettings.DeviceType = D3DDEVTYPE_REF) then DXUTDisplaySwitchingToREFWarning; end; Result:= True; end; // Compute a matrix that scales Mesh to a specified size and centers around origin procedure ComputeMeshScaling(const Mesh: CDXUTMesh; out pmScalingCenter: TD3DXMatrix); var pVerts: Pointer; vCtr: TD3DXVector3; fRadius: Single; m: TD3DXMatrixA16; begin pVerts := nil; D3DXMatrixIdentity(pmScalingCenter); if SUCCEEDED(Mesh.Mesh.LockVertexBuffer(0, pVerts)) then begin if SUCCEEDED(D3DXComputeBoundingSphere(PD3DXVector3(pVerts), Mesh.Mesh.GetNumVertices, Mesh.Mesh.GetNumBytesPerVertex, vCtr, fRadius)) then begin D3DXMatrixTranslation(pmScalingCenter, -vCtr.x, -vCtr.y, -vCtr.z); D3DXMatrixScaling(m, 1.0 / fRadius, 1.0 / fRadius, 1.0 / fRadius); D3DXMatrixMultiply(pmScalingCenter, pmScalingCenter, m); end; Mesh.Mesh.UnlockVertexBuffer; end; end; //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has been // created, which will happen during application initialization and windowed/full screen // toggles. This is the best location to create D3DPOOL_MANAGED resources since these // resources need to be reloaded whenever the device is destroyed. Resources created // here should be released in the OnDestroyDevice callback. //-------------------------------------------------------------------------------------- function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall; var dwShaderFlags: DWORD; str: array[0..MAX_PATH-1] of WideChar; Caps: TD3DCaps9; vecEye: TD3DXVector3; vecAt: TD3DXVector3; lr: TD3DLockedRect; begin Result:= g_DialogResourceManager.OnCreateDevice(pd3dDevice); if V_Failed(Result) then Exit; Result:= g_SettingsDlg.OnCreateDevice(pd3dDevice); if V_Failed(Result) then Exit; // Initialize the vertex declaration Result:= pd3dDevice.CreateVertexDeclaration(@TMeshVert_Decl, g_pMeshDecl); if V_Failed(Result) then Exit; Result:= pd3dDevice.CreateVertexDeclaration(@TShadowVert_Decl, g_pShadowDecl); if V_Failed(Result) then Exit; Result:= pd3dDevice.CreateVertexDeclaration(@TPostProcVert_Decl, g_pPProcDecl); if V_Failed(Result) then Exit; // Initialize the font Result:= D3DXCreateFont(pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH or FF_DONTCARE, 'Arial', g_pFont); if V_Failed(Result) then Exit; // Define DEBUG_VS and/or DEBUG_PS to debug vertex and/or pixel shaders with the // shader debugger. Debugging vertex shaders requires either REF or software vertex // processing, and debugging pixel shaders requires REF. The // D3DXSHADER_FORCE_*_SOFTWARE_NOOPT flag improves the debug experience in the // shader debugger. It enables source level debugging, prevents instruction // reordering, prevents dead code elimination, and forces the compiler to compile // against the next higher available software target, which ensures that the // unoptimized shaders do not exceed the shader model limitations. Setting these // flags will cause slower rendering since the shaders will be unoptimized and // forced into software. See the DirectX documentation for more information about // using the shader debugger. dwShaderFlags := D3DXFX_NOT_CLONEABLE; {$IFDEF DEBUG} // Set the D3DXSHADER_DEBUG flag to embed debug information in the shaders. // Setting this flag improves the shader debugging experience, but still allows // the shaders to be optimized and to run exactly the way they will run in // the release configuration of this program. dwShaderFlags := dwShaderFlags or D3DXSHADER_DEBUG; {$ENDIF} {$IFDEF DEBUG_VS} dwShaderFlags := dwShaderFlags or D3DXSHADER_SKIPOPTIMIZATION or D3DXSHADER_DEBUG; {$ENDIF} {$IFDEF DEBUG_PS} dwShaderFlags := dwShaderFlags or D3DXSHADER_SKIPOPTIMIZATION or D3DXSHADER_DEBUG; {$ENDIF} // Read the D3DX effect file Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, 'ShadowVolume.fx'); if V_Failed(Result) then Exit; // If this fails, there should be debug output as to // they the .fx file failed to compile Result:= D3DXCreateEffectFromFileW(pd3dDevice, str, nil, nil, dwShaderFlags, nil, g_pEffect, nil); if V_Failed(Result) then Exit; // Determine the rendering techniques to use based on device caps Result:= pd3dDevice.GetDeviceCaps(Caps); if V_Failed(Result) then Exit; g_hRenderScene := g_pEffect.GetTechniqueByName('RenderScene'); // If 2-sided stencil is supported, use it. if (Caps.StencilCaps and D3DSTENCILCAPS_TWOSIDED <> 0) then begin g_hRenderShadow := g_pEffect.GetTechniqueByName('RenderShadowVolume2Sided'); g_hShowShadow := g_pEffect.GetTechniqueByName('ShowShadowVolume2Sided'); end else begin g_hRenderShadow := g_pEffect.GetTechniqueByName('RenderShadowVolume'); g_hShowShadow := g_pEffect.GetTechniqueByName('ShowShadowVolume'); end; // Load the meshes Result:= g_Background[0].CreateMesh(pd3dDevice, 'misc\cell.x'); if V_Failed(Result) then Exit; g_Background[0].SetVertexDecl(pd3dDevice, @TMeshVert_Decl); Result:= g_Background[1].CreateMesh(pd3dDevice, 'misc\seafloor.x'); if V_Failed(Result) then Exit; g_Background[1].SetVertexDecl(pd3dDevice, @TMeshVert_Decl); Result:= g_LightMesh.CreateMesh(pd3dDevice, 'misc\sphere0.x'); if V_Failed(Result) then Exit; g_LightMesh.SetVertexDecl(pd3dDevice, @TMeshVert_Decl); Result:= g_Mesh.CreateMesh(pd3dDevice, DEFMESHFILENAME); if V_Failed(Result) then Exit; g_Mesh.SetVertexDecl(pd3dDevice, @TMeshVert_Decl); // Compute the scaling matrix for the mesh so that the size of the mesh // that shows on the screen is consistent. ComputeMeshScaling(g_Mesh, g_mWorldScaling); // Setup the camera's view parameters vecEye := D3DXVector3(0.0, 0.0, -5.0); vecAt := D3DXVector3(0.0, 0.0, -0.0); g_Camera.SetViewParams(vecEye, vecAt); g_LCamera.SetViewParams(vecEye, vecAt); g_MCamera.SetViewParams(vecEye, vecAt); // Create the 1x1 white default texture Result:= pd3dDevice.CreateTexture(1, 1, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, g_pDefaultTex, nil); if V_Failed(Result) then Exit; Result:= g_pDefaultTex.LockRect(0, lr, nil, 0); if V_Failed(Result) then Exit; PDWORD(lr.pBits)^ := D3DCOLOR_RGBA(255, 255, 255, 255); Result:= g_pDefaultTex.UnlockRect(0); if V_Failed(Result) then Exit; Result:= S_OK; end; //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has been // reset, which will happen after a lost device scenario. This is the best location to // create D3DPOOL_DEFAULT resources since these resources need to be reloaded whenever // the device is lost. Resources created here should be released in the OnLostDevice // callback. //-------------------------------------------------------------------------------------- function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall; var fAspectRatio: Single; iY: Integer; begin Result:= g_DialogResourceManager.OnResetDevice; if V_Failed(Result) then Exit; Result:= g_SettingsDlg.OnResetDevice; if V_Failed(Result) then Exit; if Assigned(g_pFont) then begin Result:= g_pFont.OnResetDevice; if V_Failed(Result) then Exit; end; if Assigned(g_pEffect) then begin Result:= g_pEffect.OnResetDevice; if V_Failed(Result) then Exit; end; g_Background[0].RestoreDeviceObjects(pd3dDevice); g_Background[1].RestoreDeviceObjects(pd3dDevice); g_LightMesh.RestoreDeviceObjects(pd3dDevice); g_Mesh.RestoreDeviceObjects(pd3dDevice); // Create a sprite to help batch calls when drawing many lines of text Result:= D3DXCreateSprite(pd3dDevice, g_pTextSprite); if V_Failed(Result) then Exit; // Setup the camera's projection parameters fAspectRatio := pBackBufferSurfaceDesc.Width / pBackBufferSurfaceDesc.Height; g_Camera.SetProjParams(D3DX_PI/4, fAspectRatio, 0.1, 20.0); g_MCamera.SetWindow(pBackBufferSurfaceDesc.Width, pBackBufferSurfaceDesc.Height); g_LCamera.SetWindow(pBackBufferSurfaceDesc.Width, pBackBufferSurfaceDesc.Height); g_pEffect.SetFloat('g_fFarClip', 20.0 - EXTRUDE_EPSILON); V(g_pEffect.SetMatrix('g_mProj', g_Camera.GetProjMatrix^)); g_HUD.SetLocation(pBackBufferSurfaceDesc.Width-170, 0); g_HUD.SetSize(170, 170); g_SampleUI.SetLocation(0, pBackBufferSurfaceDesc.Height-200); g_SampleUI.SetSize(pBackBufferSurfaceDesc.Width, 150); iY := 10; Inc(iY, 24); g_SampleUI.GetControl(IDC_BACKGROUND).SetLocation(pBackBufferSurfaceDesc.Width - 200, iY); Inc(iY, 24); g_SampleUI.GetControl(IDC_ENABLELIGHT).SetLocation(pBackBufferSurfaceDesc.Width - 200, iY); Inc(iY, 24); g_SampleUI.GetControl(IDC_RENDERTYPE).SetLocation(pBackBufferSurfaceDesc.Width - 200, iY); Inc(iY, 30); g_SampleUI.GetControl(IDC_LUMINANCELABEL).SetLocation(pBackBufferSurfaceDesc.Width - 145, iY); Inc(iY, 20); g_SampleUI.GetControl(IDC_LUMINANCE).SetLocation(pBackBufferSurfaceDesc.Width - 145, iY); Inc(iY, 26); g_SampleUI.GetControl(IDC_CHANGEMESH).SetLocation(pBackBufferSurfaceDesc.Width - 120, iY); if Assigned(g_SampleUI.GetControl(IDC_MESHFILENAME)) then g_SampleUI.GetControl(IDC_MESHFILENAME).SetLocation(pBackBufferSurfaceDesc.Width - 540, iY); // Generate the shadow volume mesh GenerateShadowMesh(pd3dDevice, g_Mesh.Mesh, g_pShadowMesh); Result:= S_OK; end; //-------------------------------------------------------------------------------------- // This callback function will be called once at the beginning of every frame. This is the // best location for your application to handle updates to the scene, but is not // intended to contain actual rendering calls, which should instead be placed in the // OnFrameRender callback. //-------------------------------------------------------------------------------------- procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall; begin // Update the camera's position based on user input g_Camera.FrameMove(fElapsedTime); g_MCamera.FrameMove(fElapsedTime); g_LCamera.FrameMove(fElapsedTime); end; //-------------------------------------------------------------------------------------- // Simply renders the entire scene without any shadow handling. procedure RenderScene(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; bRenderLight: Boolean); var mWorldView: TD3DXMatrixA16; mViewProj: TD3DXMatrixA16; mWorldViewProjection: TD3DXMatrixA16; mm: TD3DXMatrixA16; hCurrTech: TD3DXHandle; vLightMat: TD3DXVector4; cPasses: LongWord; pMesh: ID3DXMesh; p, i, m: Integer; vAmb: TD3DXVector4; begin // Get the projection & view matrix from the camera class D3DXMatrixMultiply(mViewProj, g_Camera.GetViewMatrix^, g_Camera.GetProjMatrix^); // Render the lights if requested if bRenderLight then begin hCurrTech := g_pEffect.GetCurrentTechnique; // Save the current technique V(g_pEffect.SetTechnique('RenderSceneAmbient')); V(g_pEffect.SetTexture('g_txScene', g_pDefaultTex)); vLightMat := D3DXVector4(1.0, 1.0, 1.0, 1.0); V(g_pEffect.SetVector('g_vMatColor', vLightMat)); pMesh := g_LightMesh.Mesh; V(g_pEffect._Begin(@cPasses, 0)); for p := 0 to cPasses - 1 do begin V(g_pEffect.BeginPass(p)); for i := 0 to g_nNumLights - 1 do begin for m := 0 to g_LightMesh.m_dwNumMaterials - 1 do begin // mWorldView := g_aLights[i].m_mWorld * *g_LCamera.GetWorldMatrix * *g_Camera.GetViewMatrix; D3DXMatrixMultiply(mm, g_aLights[i].m_mWorld, g_LCamera.GetWorldMatrix^); D3DXMatrixMultiply(mWorldView, mm, g_Camera.GetViewMatrix^); // mWorldViewProjection := mWorldView * *g_Camera.GetProjMatrix; D3DXMatrixMultiply(mWorldViewProjection, mWorldView, g_Camera.GetProjMatrix^); V(g_pEffect.SetMatrix('g_mWorldView', mWorldView)); V(g_pEffect.SetMatrix('g_mWorldViewProjection', mWorldViewProjection)); V(g_pEffect.SetVector('g_vAmbient', g_aLights[i].m_Color)); // The effect interface queues up the changes and performs them // with the CommitChanges call. You do not need to call CommitChanges if // you are not setting any parameters between the BeginPass and EndPass. V(g_pEffect.CommitChanges); V(pMesh.DrawSubset(m)); end; end; V(g_pEffect.EndPass); end; V(g_pEffect._End); V(g_pEffect.SetTechnique(hCurrTech)); // Restore the old technique vAmb := D3DXVector4(AMBIENT, AMBIENT, AMBIENT, 1.0); V(g_pEffect.SetVector('g_vAmbient', vAmb)); end; // Render the background mesh V(pd3dDevice.SetVertexDeclaration(g_pMeshDecl)); // mWorldView := g_mWorldBack[g_nCurrBackground] * *g_Camera.GetViewMatrix; D3DXMatrixMultiply(mWorldView, g_mWorldBack[g_nCurrBackground], g_Camera.GetViewMatrix^); // mWorldViewProjection := g_mWorldBack[g_nCurrBackground] * mViewProj; D3DXMatrixMultiply(mWorldViewProjection, g_mWorldBack[g_nCurrBackground], mViewProj); V(g_pEffect.SetMatrix('g_mWorldViewProjection', mWorldViewProjection)); V(g_pEffect.SetMatrix('g_mWorldView', mWorldView)); V(g_pEffect._Begin(@cPasses, 0 )); for p := 0 to cPasses - 1 do begin V(g_pEffect.BeginPass(p)); pMesh := g_Background[g_nCurrBackground].Mesh; for i := 0 to g_Background[g_nCurrBackground].m_dwNumMaterials - 1 do begin V(g_pEffect.SetVector('g_vMatColor', PD3DXVECTOR4(@g_Background[g_nCurrBackground].m_pMaterials[i].Diffuse)^)); if Assigned(g_Background[g_nCurrBackground].m_pTextures[i]) then V(g_pEffect.SetTexture('g_txScene', g_Background[g_nCurrBackground].m_pTextures[i])) else V(g_pEffect.SetTexture('g_txScene', g_pDefaultTex)); // The effect interface queues up the changes and performs them // with the CommitChanges call. You do not need to call CommitChanges if // you are not setting any parameters between the BeginPass and EndPass. V(g_pEffect.CommitChanges); V(pMesh.DrawSubset(i)); end; V(g_pEffect.EndPass); end; V(g_pEffect._End); // Render the mesh V(pd3dDevice.SetVertexDeclaration(g_pMeshDecl)); // mWorldView = g_mWorldScaling * *g_MCamera.GetWorldMatrix() * *g_Camera.GetViewMatrix(); D3DXMatrixMultiply(mm, g_mWorldScaling, g_MCamera.GetWorldMatrix^); D3DXMatrixMultiply(mWorldView, mm, g_Camera.GetViewMatrix^); // mWorldViewProjection = mWorldView * *g_Camera.GetProjMatrix(); D3DXMatrixMultiply(mWorldViewProjection, mWorldView, g_Camera.GetProjMatrix^); V(g_pEffect.SetMatrix('g_mWorldViewProjection', mWorldViewProjection)); V(g_pEffect.SetMatrix('g_mWorldView', mWorldView)); V(g_pEffect._Begin(@cPasses, 0 )); for p := 0 to cPasses - 1 do begin V(g_pEffect.BeginPass(p)); pMesh := g_Mesh.Mesh; for i := 0 to g_Mesh.m_dwNumMaterials - 1 do begin V(g_pEffect.SetVector('g_vMatColor', PD3DXVECTOR4(@g_Mesh.m_pMaterials[i].Diffuse)^)); if Assigned(g_Mesh.m_pTextures[i]) then V(g_pEffect.SetTexture('g_txScene', g_Mesh.m_pTextures[i])) else V(g_pEffect.SetTexture('g_txScene', g_pDefaultTex)); // The effect interface queues up the changes and performs them // with the CommitChanges call. You do not need to call CommitChanges if // you are not setting any parameters between the BeginPass and EndPass. V(g_pEffect.CommitChanges); V(pMesh.DrawSubset(i)); end; V(g_pEffect.EndPass); end; V(g_pEffect._End); end; //-------------------------------------------------------------------------------------- // This callback function will be called at the end of every frame to perform all the // rendering calls for the scene, and it will also be called if the window needs to be // repainted. After this function has returned, DXUT will call // IDirect3DDevice9::Present to display the contents of the next buffer in the swap chain //-------------------------------------------------------------------------------------- procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall; var vAmb: TD3DXVector4; L, i, p: Integer; vLight: TD3DXVector4; cPasses: LongWord; pd3dsdBackBuffer: PD3DSurfaceDesc; quad: array[0..3] of TPostProcVert; {$IFDEF SYNCRO_BY_FENCE} fBackBuffer: IDirect3DSurface9; lr: TD3DLockedRect; fence: IDirect3DQuery9; {$ENDIF} begin // If the settings dialog is being shown, then // render it instead of rendering the app's scene if g_SettingsDlg.Active then begin g_SettingsDlg.OnRender(fElapsedTime); Exit; end; // Clear the render target and the zbuffer V(pd3dDevice.Clear(0, nil, D3DCLEAR_TARGET or D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(0, 66, 75, 121), 1.0, 0)); // Render the scene if SUCCEEDED(pd3dDevice.BeginScene) then begin DXUT_BeginPerfEvent(DXUT_PERFEVENTCOLOR, 'Demonstration Code'); // First, render the scene with only ambient lighting begin // CDXUTPerfEventGenerator g( DXUT_PERFEVENTCOLOR, L"Scene Ambient" ); D3DPERF_BeginEvent(DXUT_PERFEVENTCOLOR, 'Scene Ambient'); g_pEffect.SetTechnique('RenderSceneAmbient'); vAmb := D3DXVector4(AMBIENT, AMBIENT, AMBIENT, 1.0); V(g_pEffect.SetVector('g_vAmbient', vAmb)); RenderScene(pd3dDevice, fTime, fElapsedTime, True); D3DPERF_EndEvent; end; // Now process the lights. For each light in the scene, // render the shadow volume, then render the scene with // stencil enabled. begin // CDXUTPerfEventGenerator g( DXUT_PERFEVENTCOLOR, L"Shadow" ); D3DPERF_BeginEvent(DXUT_PERFEVENTCOLOR, 'Shadow'); for L := 0 to g_nNumLights - 1 do begin // Clear the stencil buffer if (g_RenderType <> RENDERTYPE_COMPLEXITY) then V(pd3dDevice.Clear(0, nil, D3DCLEAR_STENCIL, D3DCOLOR_ARGB(0, 170, 170, 170), 1.0, 0)); vLight := D3DXVector4(g_aLights[L].m_Position.x, g_aLights[L].m_Position.y, g_aLights[L].m_Position.z, 1.0); D3DXVec4Transform(vLight, vLight, g_LCamera.GetWorldMatrix^); D3DXVec4Transform(vLight, vLight, g_Camera.GetViewMatrix^); V(g_pEffect.SetVector('g_vLightView', vLight)); V(g_pEffect.SetVector('g_vLightColor', g_aLights[L].m_Color)); // Render the shadow volume case g_RenderType of RENDERTYPE_COMPLEXITY: g_pEffect.SetTechnique('RenderShadowVolumeComplexity'); RENDERTYPE_SHADOWVOLUME: g_pEffect.SetTechnique(g_hShowShadow); else g_pEffect.SetTechnique(g_hRenderShadow); end; g_pEffect.SetVector('g_vShadowColor', g_vShadowColor[L]); // If there was an error generating the shadow volume, // skip rendering the shadow mesh. The scene will show // up without shadow. if Assigned(g_pShadowMesh) then begin V(pd3dDevice.SetVertexDeclaration(g_pShadowDecl)); V(g_pEffect._Begin(@cPasses, 0)); for i := 0 to cPasses - 1 do begin V(g_pEffect.BeginPass(i)); V(g_pEffect.CommitChanges); V(g_pShadowMesh.DrawSubset(0)); V(g_pEffect.EndPass); end; V(g_pEffect._End); end; // // Render the scene with stencil and lighting enabled. // if (g_RenderType <> RENDERTYPE_COMPLEXITY) then begin g_pEffect.SetTechnique(g_hRenderScene); RenderScene(pd3dDevice, fTime, fElapsedTime, False); end; end; D3DPERF_EndEvent; end; if (g_RenderType = RENDERTYPE_COMPLEXITY) then begin // CDXUTPerfEventGenerator g( DXUT_PERFEVENTCOLOR, L"Complexity" ); D3DPERF_BeginEvent(DXUT_PERFEVENTCOLOR, 'Complexity'); // Clear the render target V(pd3dDevice.Clear(0, nil, D3DCLEAR_TARGET, D3DCOLOR_ARGB(0, 0, 0, 0), 1.0, 0)); // Render scene complexity visualization pd3dsdBackBuffer := DXUTGetBackBufferSurfaceDesc; quad[0] := PostProcVert(-0.5, -0.5, 0.5, 1.0); quad[1] := PostProcVert(pd3dsdBackBuffer.Width-0.5, -0.5, 0.5, 1.0); quad[2] := PostProcVert(-0.5, pd3dsdBackBuffer.Height-0.5, 0.5, 1.0); quad[3] := PostProcVert(pd3dsdBackBuffer.Width-0.5, pd3dsdBackBuffer.Height-0.5, 0.5, 1.0); pd3dDevice.SetVertexDeclaration(g_pPProcDecl); g_pEffect.SetTechnique('RenderComplexity'); g_pEffect._Begin(@cPasses, 0); for p := 0 to cPasses - 1 do begin g_pEffect.BeginPass(p); pd3dDevice.DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, quad, SizeOf(TPOSTPROCVERT)); g_pEffect.EndPass; end; g_pEffect._End; D3DPERF_EndEvent; end; DXUT_EndPerfEvent; // end of draw code {$IFDEF SYNCRO_BY_FENCE} DXUTGetD3DDevice.CreateQuery(D3DQUERYTYPE_EVENT, fence); {$ENDIF} // Miscellaneous rendering begin // CDXUTPerfEventGenerator g( DXUT_PERFEVENTCOLOR,"HUD / Stats"); D3DPERF_BeginEvent(DXUT_PERFEVENTCOLOR, 'HUD / Stats'); RenderText; g_HUD.OnRender(fElapsedTime); g_SampleUI.OnRender(fElapsedTime); D3DPERF_EndEvent; end; {$IFDEF SYNCRO_BY_FENCE} fence.Issue(D3DISSUE_END); {$ENDIF} V(pd3dDevice.EndScene); end; end; //-------------------------------------------------------------------------------------- // Render the help and statistics text. This function uses the ID3DXFont interface for // efficient text rendering. //-------------------------------------------------------------------------------------- procedure RenderText; var txtHelper: CDXUTTextHelper; pd3dsdBackBuffer: PD3DSurfaceDesc; begin // The helper object simply helps keep track of text position, and color // and then it calls pFont->DrawText( m_pSprite, strMsg, -1, &rc, DT_NOCLIP, m_clr ); // If NULL is passed in as the sprite object, then it will work however the // pFont->DrawText() will not be batched together. Batching calls will improves performance. txtHelper := CDXUTTextHelper.Create(g_pFont, g_pTextSprite, 15); pd3dsdBackBuffer := DXUTGetBackBufferSurfaceDesc; // Output statistics txtHelper._Begin; txtHelper.SetInsertionPos(5, 5); txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 0.0, 1.0 )); txtHelper.DrawTextLine(DXUTGetFrameStats(True)); // Show FPS txtHelper.DrawTextLine(DXUTGetDeviceStats); // Draw help if g_bShowHelp then begin txtHelper.SetInsertionPos(10, pd3dsdBackBuffer.Height-80); txtHelper.SetForegroundColor(D3DXColor(1.0, 0.75, 0.0, 1.0 )); txtHelper.DrawTextLine('Controls (F1 to hide):'); txtHelper.SetInsertionPos(20, pd3dsdBackBuffer.Height-65); txtHelper.DrawTextLine('Camera control: Left mouse'#10+ 'Mesh control: Right mouse'#10+ 'Light control: Middle mouse'#10+ 'Quit: ESC' ); end else begin txtHelper.SetInsertionPos(10, pd3dsdBackBuffer.Height-25); txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 1.0, 1.0)); txtHelper.DrawTextLine('Press F1 for help'); end; txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 1.0, 1.0 )); if not (g_bLeftButtonDown or g_bMiddleButtonDown or g_bRightButtonDown) then begin txtHelper.SetInsertionPos(pd3dsdBackBuffer.Width div 2 - 90, pd3dsdBackBuffer.Height - 40); txtHelper.DrawTextLine(#10'W/S/A/D/Q/E to move camera.'); end else begin txtHelper.SetInsertionPos(pd3dsdBackBuffer.Width div 2 - 70, pd3dsdBackBuffer.Height - 40); if g_bLeftButtonDown then begin txtHelper.DrawTextLine('Camera Control Mode'); end else if g_bMiddleButtonDown then begin txtHelper.DrawTextLine('Light Control Mode'); end; if g_bRightButtonDown then begin txtHelper.DrawTextLine('Model Control Mode'); end; txtHelper.SetInsertionPos(pd3dsdBackBuffer.Width div 2 - 130, pd3dsdBackBuffer.Height - 25); txtHelper.DrawTextLine('Move mouse to rotate. W/S/A/D/Q/E to move.'); end; if (g_RenderType = RENDERTYPE_COMPLEXITY) then begin txtHelper.SetInsertionPos(5, 70); txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 1.0, 1.0)); txtHelper.DrawTextLine('Shadow volume complexity:'); txtHelper.SetInsertionPos(5, 90); txtHelper.SetForegroundColor(D3DXColor(1.0, 0.0, 1.0, 1.0)); txtHelper.DrawTextLine('1 to 5 fills'#10); txtHelper.SetForegroundColor(D3DXColor(0.0, 0.0, 1.0, 1.0)); txtHelper.DrawTextLine('6 to 10 fills'#10); txtHelper.SetForegroundColor(D3DXColor(0.0, 1.0, 1.0, 1.0)); txtHelper.DrawTextLine('11 to 20 fills'#10); txtHelper.SetForegroundColor(D3DXColor(0.0, 1.0, 0.0, 1.0)); txtHelper.DrawTextLine('21 to 30 fills'#10); txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 0.0, 1.0)); txtHelper.DrawTextLine('31 to 40 fills'#10); txtHelper.SetForegroundColor(D3DXColor(1.0, 0.5, 0.0, 1.0)); txtHelper.DrawTextLine('41 to 50 fills'#10); txtHelper.SetForegroundColor(D3DXColor(1.0, 0.0, 0.0, 1.0)); txtHelper.DrawTextLine('51 to 70 fills'#10); txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 1.0, 1.0)); txtHelper.DrawTextLine('71 or more fills'#10); end; // Display an error message if unable to generate shadow mesh if (g_pShadowMesh = nil) then begin txtHelper.SetInsertionPos(5, 35); txtHelper.SetForegroundColor(D3DXColor(1.0, 0.0, 0.0, 1.0 )); txtHelper.DrawTextLine('Unable to generate closed shadow volume for this mesh'#10); txtHelper.DrawTextLine('No shadow will be rendered'); end; txtHelper._End; txtHelper.Free; end; //-------------------------------------------------------------------------------------- // Before handling window messages, DXUT passes incoming windows // messages to the application through this callback function. If the application sets // *pbNoFurtherProcessing to TRUE, then DXUT will not process this message. //-------------------------------------------------------------------------------------- function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall; begin Result:= 0; // Always allow dialog resource manager calls to handle global messages // so GUI state is updated correctly pbNoFurtherProcessing := g_DialogResourceManager.MsgProc(hWnd, uMsg, wParam, lParam); if pbNoFurtherProcessing then Exit; if g_SettingsDlg.IsActive then begin g_SettingsDlg.MsgProc(hWnd, uMsg, wParam, lParam); Exit; end; // Give the dialogs a chance to handle the message first pbNoFurtherProcessing := g_HUD.MsgProc(hWnd, uMsg, wParam, lParam); if pbNoFurtherProcessing then Exit; pbNoFurtherProcessing := g_SampleUI.MsgProc(hWnd, uMsg, wParam, lParam); if pbNoFurtherProcessing then Exit; // Pass all remaining windows messages to camera so it can respond to user input g_Camera.HandleMessages(hWnd, uMsg, wParam, lParam); g_MCamera.HandleMessages(hWnd, uMsg, wParam, lParam); g_LCamera.HandleMessages(hWnd, uMsg, wParam, lParam); end; //-------------------------------------------------------------------------------------- // As a convenience, DXUT inspects the incoming windows messages for // keystroke messages and decodes the message parameters to pass relevant keyboard // messages to the application. The framework does not remove the underlying keystroke // messages, which are still passed to the application's MsgProc callback. //-------------------------------------------------------------------------------------- procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall; begin if bKeyDown then begin case nChar of VK_F1: g_bShowHelp := not g_bShowHelp; end; end; end; procedure MouseProc(bLeftButtonDown, bRightButtonDown, bMiddleButtonDown, bSideButton1Down, bSideButton2Down: Boolean; nMouseWheelDelta: Integer; xPos, yPos: Integer; pUserContext: Pointer); stdcall; var bOldLeftButtonDown: Boolean; bOldRightButtonDown: Boolean; bOldMiddleButtonDown: Boolean; begin bOldLeftButtonDown := g_bLeftButtonDown; bOldRightButtonDown := g_bRightButtonDown; bOldMiddleButtonDown := g_bMiddleButtonDown; g_bLeftButtonDown := bLeftButtonDown; g_bMiddleButtonDown := bMiddleButtonDown; g_bRightButtonDown := bRightButtonDown; if (bOldLeftButtonDown and not g_bLeftButtonDown) then begin // Disable movement g_Camera.SetEnablePositionMovement(False); end else if (not bOldLeftButtonDown and g_bLeftButtonDown) then begin // Enable movement g_Camera.SetEnablePositionMovement(True); end; if (bOldRightButtonDown and not g_bRightButtonDown) then begin // Disable movement g_MCamera.SetEnablePositionMovement(False); end else if (not bOldRightButtonDown and g_bRightButtonDown) then begin // Enable movement g_MCamera.SetEnablePositionMovement(True); g_Camera.SetEnablePositionMovement(False); end; if (bOldMiddleButtonDown and not g_bMiddleButtonDown) then begin // Disable movement g_LCamera.SetEnablePositionMovement(False); end else if (not bOldMiddleButtonDown and g_bMiddleButtonDown) then begin // Enable movement g_LCamera.SetEnablePositionMovement(True); g_Camera.SetEnablePositionMovement(False); end; // If no mouse button is down at all, enable camera movement. if (not g_bLeftButtonDown and not g_bRightButtonDown and not g_bMiddleButtonDown) then g_Camera.SetEnablePositionMovement(True); end; //-------------------------------------------------------------------------------------- // Handles the GUI events //-------------------------------------------------------------------------------------- procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall; var fLuminance: Single; i: Integer; NewMesh: CDXUTMesh; pd3dsdBackBuffer: PD3DSurfaceDesc; begin case nControlID of IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen; IDC_TOGGLEREF: DXUTToggleREF; IDC_CHANGEDEVICE: with g_SettingsDlg do Active := not Active; IDC_RENDERTYPE: g_RenderType := TRenderType(size_t(CDXUTComboBox(pControl).GetSelectedData)); IDC_ENABLELIGHT: if (nEvent = EVENT_COMBOBOX_SELECTION_CHANGED) then begin g_nNumLights := Integer(size_t(g_SampleUI.GetComboBox(IDC_ENABLELIGHT).GetSelectedData)); end; IDC_LUMINANCE: if (nEvent = EVENT_SLIDER_VALUE_CHANGED) then begin fLuminance := CDXUTSlider(pControl).Value; // StringCchPrintf( wszText, 50, L"Luminance: %.1f", fLuminance ); g_SampleUI.GetStatic(IDC_LUMINANCELABEL).Text := PWideChar(WideFormat('Luminance: %.1f', [fLuminance])); for i := 0 to MAX_NUM_LIGHTS - 1 do begin if (g_aLights[i].m_Color.x > 0.5) then g_aLights[i].m_Color.x := fLuminance; if (g_aLights[i].m_Color.y > 0.5) then g_aLights[i].m_Color.y := fLuminance; if (g_aLights[i].m_Color.z > 0.5) then g_aLights[i].m_Color.z := fLuminance; end; end; IDC_BACKGROUND: if (nEvent = EVENT_COMBOBOX_SELECTION_CHANGED) then begin g_nCurrBackground := Integer(size_t(g_SampleUI.GetComboBox(IDC_BACKGROUND).GetSelectedData)); end; IDC_MESHFILENAME, IDC_CHANGEMESH: begin if (nControlID = IDC_MESHFILENAME) and (nEvent <> EVENT_EDITBOX_CHANGE) then begin NewMesh:= CDXUTMesh.Create; if SUCCEEDED(NewMesh.CreateMesh(DXUTGetD3DDevice, g_SampleUI.GetIMEEditBox(IDC_MESHFILENAME).Text)) and SUCCEEDED(NewMesh.SetVertexDecl(DXUTGetD3DDevice, @TMeshVert_Decl)) and SUCCEEDED(NewMesh.RestoreDeviceObjects(DXUTGetD3DDevice)) then begin g_Mesh.InvalidateDeviceObjects; g_Mesh.DestroyMesh; g_Mesh.Free; g_Mesh := NewMesh; // ZeroMemory(@NewMesh, SizeOf(NewMesh)); ComputeMeshScaling(g_Mesh, g_mWorldScaling); // Generate the shadow mesh SAFE_RELEASE(g_pShadowMesh); GenerateShadowMesh(DXUTGetD3DDevice, g_Mesh.Mesh, g_pShadowMesh); end; end; // Fall through to clean up the edit box and button if (nControlID = IDC_MESHFILENAME) and (nEvent <> EVENT_EDITBOX_CHANGE) or (nControlID = IDC_CHANGEMESH) then begin {end; IDC_CHANGEMESH: begin} pd3dsdBackBuffer := DXUTGetBackBufferSurfaceDesc; if Assigned(g_SampleUI.GetControl(IDC_MESHFILENAME)) then begin // If the edit box exists, clean up. g_SampleUI.RemoveControl(IDC_MESHFILENAME); // Change the button text back to "Change mesh" g_SampleUI.GetButton(IDC_CHANGEMESH).Text := 'Change mesh'; end else begin // Create a new edit box. g_SampleUI.AddIMEEditBox(IDC_MESHFILENAME, '', pd3dsdBackBuffer.Width - 540, 158, 415, 34); g_SampleUI.GetIMEEditBox(IDC_MESHFILENAME).SetText('Type mesh name and press Enter', True); g_SampleUI.RequestFocus(g_SampleUI.GetControl(IDC_MESHFILENAME)); // Change the button text to "Cancel" g_SampleUI.GetButton(IDC_CHANGEMESH).Text := 'Cancel'; end; end; end; end; end; //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has // entered a lost state and before IDirect3DDevice9::Reset is called. Resources created // in the OnResetDevice callback should be released here, which generally includes all // D3DPOOL_DEFAULT resources. See the "Lost Devices" section of the documentation for // information about lost devices. //-------------------------------------------------------------------------------------- procedure OnLostDevice; stdcall; begin g_DialogResourceManager.OnLostDevice; g_SettingsDlg.OnLostDevice; g_Background[0].InvalidateDeviceObjects; g_Background[1].InvalidateDeviceObjects; g_LightMesh.InvalidateDeviceObjects; g_Mesh.InvalidateDeviceObjects; SAFE_RELEASE(g_pShadowMesh); if Assigned(g_pFont) then g_pFont.OnLostDevice; if Assigned(g_pEffect) then g_pEffect.OnLostDevice; SAFE_RELEASE(g_pTextSprite); end; //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has // been destroyed, which generally happens as a result of application termination or // windowed/full screen toggles. Resources created in the OnCreateDevice callback // should be released here, which generally includes all D3DPOOL_MANAGED resources. //-------------------------------------------------------------------------------------- procedure OnDestroyDevice; stdcall; begin g_DialogResourceManager.OnDestroyDevice; g_SettingsDlg.OnDestroyDevice; g_Background[0].DestroyMesh; g_Background[1].DestroyMesh; g_LightMesh.DestroyMesh; g_Mesh.DestroyMesh; SAFE_RELEASE(g_pDefaultTex); SAFE_RELEASE(g_pEffect); SAFE_RELEASE(g_pFont); SAFE_RELEASE(g_pMeshDecl); SAFE_RELEASE(g_pShadowDecl); SAFE_RELEASE(g_pPProcDecl); end; function LightInitData(const P: TD3DXVector3; const C: TD3DXVector4): TLightInitData; begin Result.Position := P; Result.Color := C; end; procedure CreateCustomDXUTobjects; begin g_DialogResourceManager:= CDXUTDialogResourceManager.Create; // manager for shared resources of dialogs g_SettingsDlg:= CD3DSettingsDlg.Create; // Device settings dialog g_Camera:= CFirstPersonCamera.Create; g_MCamera:= CModelViewerCamera.Create; g_LCamera:= CModelViewerCamera.Create; g_Background[0]:= CDXUTMesh.Create; g_Background[1]:= CDXUTMesh.Create; g_LightMesh:= CDXUTMesh.Create; g_Mesh:= CDXUTMesh.Create; g_HUD := CDXUTDialog.Create; g_SampleUI := CDXUTDialog.Create; end; procedure DestroyCustomDXUTobjects; begin FreeAndNil(g_DialogResourceManager); FreeAndNil(g_SettingsDlg); FreeAndNil(g_Camera); FreeAndNil(g_MCamera); FreeAndNil(g_LCamera); FreeAndNil(g_Background[0]); FreeAndNil(g_Background[1]); FreeAndNil(g_LightMesh); FreeAndNil(g_Mesh); FreeAndNil(g_HUD); FreeAndNil(g_SampleUI); end; function PostProcVert(x, y, z, rhw: Single): TPostProcVert; begin Result.x := x; Result.y := y; Result.z := z; Result.rhw := rhw; end; function EdgeMapping: TEdgeMapping; begin with Result do begin FillMemory(@m_anOldEdge, SizeOf(m_anOldEdge), $FF); FillMemory(@m_aanNewEdge, SizeOf(m_aanNewEdge), $FF); end; end; initialization g_vShadowColor[0]:= D3DXVector4(0.0, 1.0, 0.0, 0.2); g_vShadowColor[1]:= D3DXVector4(1.0, 1.0, 0.0, 0.2); g_vShadowColor[2]:= D3DXVector4(1.0, 0.0, 0.0, 0.2); g_vShadowColor[3]:= D3DXVector4(0.0, 0.0, 1.0, 0.2); g_vShadowColor[4]:= D3DXVector4(1.0, 0.0, 1.0, 0.2); g_vShadowColor[5]:= D3DXVector4(0.0, 1.0, 1.0, 0.2); g_LightInit[0] := LightInitData(D3DXVector3(-2.0, 3.0, -3.0), D3DXVector4(15.0, 15.0, 15.0, 1.0)); if MAX_NUM_LIGHTS > 1 then g_LightInit[1] := LightInitData(D3DXVector3(2.0, 3.0, -3.0), D3DXVector4(15.0, 15.0, 15.0, 1.0)); if MAX_NUM_LIGHTS > 2 then g_LightInit[2] := LightInitData(D3DXVector3(-2.0, 3.0, 3.0), D3DXVector4(15.0, 15.0, 15.0, 1.0)); if MAX_NUM_LIGHTS > 3 then g_LightInit[3] := LightInitData(D3DXVector3(2.0, 3.0, 3.0), D3DXVector4(15.0, 15.0, 15.0, 1.0)); if MAX_NUM_LIGHTS > 4 then g_LightInit[4] := LightInitData(D3DXVector3(-2.0, 3.0, 0.0), D3DXVector4(15.0, 0.0, 0.0, 1.0)); if MAX_NUM_LIGHTS > 5 then g_LightInit[5] := LightInitData(D3DXVector3(2.0, 3.0, 0.0), D3DXVector4(0.0, 0.0, 15.0, 1.0)); end.
unit Chapter08._07_Solution1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, DeepStar.Utils; /// 200. Number of Islands /// https://leetcode.com/problems/number-of-islands/description/ /// 时间复杂度: O(n*m) /// 空间复杂度: O(n*m) type TSolution = class(TObject) public function numIslands(grid: TArr2D_chr): integer; end; procedure Main; implementation procedure Main; var grid: TArr2D_chr; res: integer; begin with TSolution.Create do begin grid := [ ['1', '1', '1', '1', '0'], ['1', '1', '0', '1', '0'], ['1', '1', '0', '0', '0'], ['0', '0', '0', '0', '0']]; res := numIslands(grid); WriteLn(res); grid := [ ['1', '1', '0', '0', '0'], ['1', '1', '0', '0', '0'], ['0', '0', '1', '0', '0'], ['0', '0', '0', '1', '1']]; res := numIslands(grid); WriteLn(res); Free; end; end; { TSolution } function TSolution.numIslands(grid: TArr2D_chr): integer; const D: TArr2D_int = ((-1, 0), (0, 1), (1, 0), (0, -1)); var visited: array of array of boolean; n, m: integer; function __inArea__(x, y: integer): boolean; begin Result := (x >= 0) and (y >= 0) and (x < n) and (y < m); end; // 从grid[x][y]的位置开始,进行 floodfill // 保证(x,y)合法,且grid[x][y]是没有被访问过的陆地 procedure __isLands__(x, y: integer); var newX, newY, i: integer; begin visited[x, y] := true; for i := 0 to High(D) do begin newX := x + D[i, 0]; newY := y + D[i, 1]; if __inArea__(newX, newY) and (not visited[newX, newY]) and (grid[newX, newY] = '1') then begin __isLands__(newX, newY); end; end; end; var i, j, res: integer; begin n := Length(grid); m := Length(grid[0]); SetLength(visited, n, m); for i := 0 to n - 1 do for j := 0 to m - 1 do visited[i, j] := false; res := 0; for i := 0 to n - 1 do begin for j := 0 to m - 1 do begin if (grid[i, j] = '1') and (not visited[i, j]) then begin __isLands__(i, j); res += 1; end; end; end; Result := res; end; end.
unit ibSHSQLGenerator; interface uses Classes, SysUtils, SHDesignIntf, ibSHDesignIntf, ibSHDriverIntf, ibSHSQLs, ibSHConsts, ibSHTxtRtns, pSHQStrings; type TibBTSQLGenerator = class(TSHComponent, IibSHSQLGenerator) private FCodeNormalizer: IibSHCodeNormalizer; procedure CatchCodeNormalizer; function NormalizeName(AComponent: IInterface; const AName: string): string; protected {IibSHSQLGenerator} procedure SetAutoGenerateSQLsParams(AComponent: TSHComponent); procedure GenerateSQLs(AComponent: TSHComponent); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; class function GetClassIIDClassFnc: TGUID; override; end; procedure Register; implementation procedure Register; begin SHRegisterComponents([TibBTSQLGenerator]); end; { TibBTSQLGenerator } procedure TibBTSQLGenerator.CatchCodeNormalizer; begin if not Assigned(FCodeNormalizer) then if Supports(Designer.GetDemon(IibSHCodeNormalizer), IibSHCodeNormalizer, FCodeNormalizer) then ReferenceInterface(FCodeNormalizer, opInsert); end; function TibBTSQLGenerator.NormalizeName(AComponent: IInterface; const AName: string): string; var // vRetriveDatabase: IibSHRetriveDatabase; vDatabase: IibSHDatabase; begin { CatchCodeNormalizer; if Assigned(FCodeNormalizer) and Supports(AComponent, IibSHRetriveDatabase, vRetriveDatabase) then Result := FCodeNormalizer.MetadataNameToSourceDDL(vRetriveDatabase.BTCLDatabase, AName) else Result := AName; } CatchCodeNormalizer; if Assigned(FCodeNormalizer) and Supports(AComponent, IibSHDatabase, vDatabase) then Result := FCodeNormalizer.MetadataNameToSourceDDL(vDatabase, AName) else Result := AName; end; procedure TibBTSQLGenerator.SetAutoGenerateSQLsParams( AComponent: TSHComponent); var vTableList: TStringList; S: string; I, J: Integer; vAllFieldsUsed: Boolean; vDatabase: IibSHDatabase; vData: IibSHData; function FieldCanBeKey(const AFieldName: string): Boolean; var I: Integer; S: string; begin Result := False; with AComponent as IibSHTable do begin for I := 0 to Pred(Fields.Count) do begin // S := GetField(I).Caption; S := Fields[I]; if SameText(AFieldName, S) then begin Result := (GetField(I).ComputedSource.Count = 0) and (GetField(I).FieldTypeID <> _BLOB); Break; end; end; end; end; begin if Assigned(AComponent) and Supports(AComponent, IibSHData, vData) then if Supports(AComponent, IibSHSQLEditor) then begin if not vData.Dataset.Active then begin vTableList := TStringList.Create; try AllSQLTables(vData.Dataset.SelectSQL.Text, vTableList); if (vTableList.Count = 1) and (not vData.ReadOnly) then begin vData.Dataset.InsertSQL.Text := 'INSERT'; vData.Dataset.UpdateSQL.Text := 'UPDATE'; vData.Dataset.DeleteSQL.Text := 'DELETE'; vData.Dataset.RefreshSQL.Text := 'SELECT'; vData.Dataset.SetAutoGenerateSQLsParams(vTableList[0], EmptyStr, False) end else begin vData.Dataset.InsertSQL.Text := EmptyStr; vData.Dataset.UpdateSQL.Text := EmptyStr; vData.Dataset.DeleteSQL.Text := EmptyStr; vData.Dataset.RefreshSQL.Text := EmptyStr; vData.Dataset.SetAutoGenerateSQLsParams(EmptyStr, EmptyStr, False) end; finally vTableList.Free; end; end; end else if Supports(AComponent, IibSHTable) then with (AComponent as IibSHTable) do begin if not vData.Dataset.Active then begin vData.Dataset.InsertSQL.Text := 'INSERT'; vData.Dataset.UpdateSQL.Text := 'UPDATE'; vData.Dataset.DeleteSQL.Text := 'DELETE'; vData.Dataset.RefreshSQL.Text := 'SELECT'; if Supports(AComponent, IibSHDatabase, vDatabase) and (vDatabase.DatabaseAliasOptions.DML.UseDB_KEY or vDatabase.DatabaseAliasOptions.DML.ShowDB_KEY) then begin S := NormalizeName(AComponent, AComponent.Caption); vData.Dataset.SelectSQL.Text := Format(SSelectWithDB_KEYTemplate, [S, S]); end else vData.Dataset.SelectSQL.Text := Format(SSelectTemplate, [NormalizeName(AComponent, AComponent.Caption)]); end else begin // vData.Dataset.InsertSQL.Text := 'INSERT'; // vData.Dataset.UpdateSQL.Text := 'UPDATE'; // vData.Dataset.DeleteSQL.Text := 'DELETE'; // vData.Dataset.RefreshSQL.Text := 'SELECT'; if Supports(AComponent, IibSHDatabase, vDatabase) and vDatabase.DatabaseAliasOptions.DML.UseDB_KEY then vData.Dataset.SetAutoGenerateSQLsParams(NormalizeName(AComponent, AComponent.Caption), 'DB_KEY', False) else begin S := EmptyStr; vAllFieldsUsed := False; //Первичные ключи if Constraints.Count > 0 then for I := 0 to Constraints.Count - 1 do if SameText(GetConstraint(I).ConstraintType, ConstraintTypes[0]) then begin for J := 0 to Pred(GetConstraint(I).Fields.Count) do if FieldCanBeKey(GetConstraint(I).Fields[J]) then S := S + NormalizeName(AComponent, GetConstraint(I).Fields[J]) + ';'; Break; end; //Уникальные индексы if (Length(S) = 0) and (Constraints.Count > 0) then for I := 0 to Constraints.Count - 1 do if SameText(GetConstraint(I).ConstraintType, ConstraintTypes[1]) then begin for J := 0 to Pred(GetConstraint(I).Fields.Count) do if FieldCanBeKey(GetConstraint(I).Fields[J]) then S := S + NormalizeName(AComponent, GetConstraint(I).Fields[J]) + ';'; Break; end; //Полный фарш if Length(S) = 0 then begin for I := 0 to Pred(Fields.Count) do if (GetField(I).ComputedSource.Count = 0) and (GetField(I).FieldTypeID <> _BLOB) then S := S + NormalizeName(AComponent, Fields[I]) + ';'; vAllFieldsUsed := Length(S) > 0; end; if Length(S) > 0 then begin Delete(S, Length(S), 1); vData.Dataset.SetAutoGenerateSQLsParams(NormalizeName(AComponent, AComponent.Caption), S, vAllFieldsUsed); end else vData.Dataset.SetAutoGenerateSQLsParams(EmptyStr, EmptyStr, False); end; end; end else if Supports(AComponent, IibSHView) then with AComponent as IibSHView do begin if not vData.Dataset.Active then begin vData.Dataset.InsertSQL.Text := 'INSERT'; vData.Dataset.UpdateSQL.Text := 'UPDATE'; vData.Dataset.DeleteSQL.Text := 'DELETE'; vData.Dataset.RefreshSQL.Text := 'SELECT'; if Supports(AComponent, IibSHDatabase, vDatabase) and (vDatabase.DatabaseAliasOptions.DML.UseDB_KEY or vDatabase.DatabaseAliasOptions.DML.ShowDB_KEY) then begin S := NormalizeName(AComponent, AComponent.Caption); vData.Dataset.SelectSQL.Text := Format(SSelectWithDB_KEYTemplate, [S, S]); end else vData.Dataset.SelectSQL.Text := Format(SSelectTemplate, [NormalizeName(AComponent, AComponent.Caption)]); end else begin // vData.Dataset.InsertSQL.Text := 'INSERT'; // vData.Dataset.UpdateSQL.Text := 'UPDATE'; // vData.Dataset.DeleteSQL.Text := 'DELETE'; // vData.Dataset.RefreshSQL.Text := 'SELECT'; if Supports(AComponent, IibSHDatabase, vDatabase) and vDatabase.DatabaseAliasOptions.DML.UseDB_KEY then vData.Dataset.SetAutoGenerateSQLsParams(NormalizeName(AComponent, AComponent.Caption), 'DB_KEY', False) else begin S := EmptyStr; //Полный фарш if Length(S) = 0 then for I := 0 to Pred(Fields.Count) do if (GetField(I).FieldTypeID <> _BLOB) then S := S + NormalizeName(AComponent, Fields[I]) + ';'; if Length(S) > 0 then begin Delete(S, Length(S), 1); vData.Dataset.SetAutoGenerateSQLsParams(NormalizeName(AComponent, AComponent.Caption), S, True); end else vData.Dataset.SetAutoGenerateSQLsParams(EmptyStr, EmptyStr, False); end; end; end else if Supports(AComponent, IibSHProcedure) then begin vData.Dataset.SelectSQL.Text := Format(SSelectTemplate, [NormalizeName(AComponent, (AComponent as IibSHProcedure).Caption)]); end; end; procedure TibBTSQLGenerator.GenerateSQLs(AComponent: TSHComponent); var vTableList: TStringList; S: string; I, J: Integer; vAllFieldsUsed: Boolean; vDatabase: IibSHDatabase; vData: IibSHData; function FieldCanBeKey(const AFieldName: string): Boolean; var I: Integer; S: string; begin Result := False; with AComponent as IibSHTable do begin for I := 0 to Pred(Fields.Count) do begin // S := GetField(I).Caption; S := Fields[I]; if SameText(AFieldName, S) then begin Result := (GetField(I).ComputedSource.Count = 0) and (GetField(I).FieldTypeID <> _BLOB); Break; end; end; end; end; begin if Assigned(AComponent) and Supports(AComponent, IibSHData, vData) then if Supports(AComponent, IibSHSQLEditor) then begin if vData.Dataset.Active then begin vTableList := TStringList.Create; try // AllSQLTables(vData.Dataset.SelectSQL.Text, vTableList); AllTables(vData.Dataset.SelectSQL.Text, vTableList); if (vTableList.Count = 1) and (not vData.ReadOnly) and ( not Supports(vData.Dataset.Database,IibSHDRVDatabaseExt) or (vData.Dataset.Database as IibSHDRVDatabaseExt).IsTableOrView(vTableList[0]) ) then begin { vData.Dataset.InsertSQL.Text := 'INSERT'; vData.Dataset.UpdateSQL.Text := 'UPDATE'; vData.Dataset.DeleteSQL.Text := 'DELETE'; vData.Dataset.RefreshSQL.Text := 'SELECT'; } vData.Dataset.InsertSQL.Text := EmptyStr; vData.Dataset.UpdateSQL.Text := EmptyStr; vData.Dataset.DeleteSQL.Text := EmptyStr; vData.Dataset.RefreshSQL.Text := EmptyStr; vData.Dataset.GenerateSQLs(vTableList[0], EmptyStr, False) end else begin vData.Dataset.InsertSQL.Text := EmptyStr; vData.Dataset.UpdateSQL.Text := EmptyStr; vData.Dataset.DeleteSQL.Text := EmptyStr; vData.Dataset.RefreshSQL.Text := EmptyStr; vData.Dataset.GenerateSQLs(EmptyStr, EmptyStr, False) end; finally vTableList.Free; end; end; end else if Supports(AComponent, IibSHTable) then with (AComponent as IibSHTable) do begin if not vData.Dataset.Active then begin if Supports(AComponent, IibSHDatabase, vDatabase) and (vDatabase.DatabaseAliasOptions.DML.UseDB_KEY or vDatabase.DatabaseAliasOptions.DML.ShowDB_KEY) then begin S := NormalizeName(AComponent, AComponent.Caption); vData.Dataset.SelectSQL.Text := Format(SSelectWithDB_KEYTemplate, [S, S]); end else vData.Dataset.SelectSQL.Text := Format(SSelectTemplate, [NormalizeName(AComponent, AComponent.Caption)]); end else begin vData.Dataset.InsertSQL.Text := 'INSERT'; vData.Dataset.UpdateSQL.Text := 'UPDATE'; vData.Dataset.DeleteSQL.Text := 'DELETE'; vData.Dataset.RefreshSQL.Text := 'SELECT'; if Supports(AComponent, IibSHDatabase, vDatabase) and vDatabase.DatabaseAliasOptions.DML.UseDB_KEY then vData.Dataset.GenerateSQLs(NormalizeName(AComponent, AComponent.Caption), 'DB_KEY', False) else begin S := EmptyStr; vAllFieldsUsed := False; //Первичные ключи if Constraints.Count > 0 then for I := 0 to Constraints.Count - 1 do if SameText(GetConstraint(I).ConstraintType, ConstraintTypes[0]) then begin for J := 0 to Pred(GetConstraint(I).Fields.Count) do if FieldCanBeKey(GetConstraint(I).Fields[J]) then S := S + NormalizeName(AComponent, GetConstraint(I).Fields[J]) + ';'; Break; end; //Уникальные индексы if (Length(S) = 0) and (Constraints.Count > 0) then for I := 0 to Constraints.Count - 1 do if SameText(GetConstraint(I).ConstraintType, ConstraintTypes[1]) then begin for J := 0 to Pred(GetConstraint(I).Fields.Count) do if FieldCanBeKey(GetConstraint(I).Fields[J]) then S := S + NormalizeName(AComponent, GetConstraint(I).Fields[J]) + ';'; Break; end; //Полный фарш if Length(S) = 0 then begin for I := 0 to Pred(Fields.Count) do if (GetField(I).ComputedSource.Count = 0) and (GetField(I).FieldTypeID <> _BLOB) then S := S + NormalizeName(AComponent, Fields[I]) + ';'; vAllFieldsUsed := Length(S) > 0; end; if Length(S) > 0 then begin Delete(S, Length(S), 1); vData.Dataset.GenerateSQLs(NormalizeName(AComponent, AComponent.Caption), S, vAllFieldsUsed); end else // vData.Dataset.SetAutoGenerateSQLsParams(EmptyStr, EmptyStr, False); vData.Dataset.GenerateSQLs(EmptyStr, EmptyStr, False); end; end; end else if Supports(AComponent, IibSHView) then with AComponent as IibSHView do begin if not vData.Dataset.Active then begin if Supports(AComponent, IibSHDatabase, vDatabase) and (vDatabase.DatabaseAliasOptions.DML.UseDB_KEY or vDatabase.DatabaseAliasOptions.DML.ShowDB_KEY) then begin S := NormalizeName(AComponent, AComponent.Caption); vData.Dataset.SelectSQL.Text := Format(SSelectWithDB_KEYTemplate, [S, S]); end else vData.Dataset.SelectSQL.Text := Format(SSelectTemplate, [NormalizeName(AComponent, AComponent.Caption)]); end else begin vData.Dataset.InsertSQL.Text := 'INSERT'; vData.Dataset.UpdateSQL.Text := 'UPDATE'; vData.Dataset.DeleteSQL.Text := 'DELETE'; vData.Dataset.RefreshSQL.Text := 'SELECT'; if Supports(AComponent, IibSHDatabase, vDatabase) and vDatabase.DatabaseAliasOptions.DML.UseDB_KEY then vData.Dataset.GenerateSQLs(NormalizeName(AComponent, AComponent.Caption), 'DB_KEY', False) else begin S := EmptyStr; //Полный фарш if Length(S) = 0 then for I := 0 to Pred(Fields.Count) do if (GetField(I).FieldTypeID <> _BLOB) then S := S + NormalizeName(AComponent, Fields[I]) + ';'; if Length(S) > 0 then begin Delete(S, Length(S), 1); vData.Dataset.GenerateSQLs(NormalizeName(AComponent, AComponent.Caption), S, True); end else // vData.Dataset.SetAutoGenerateSQLsParams(EmptyStr, EmptyStr, False); vData.Dataset.GenerateSQLs(EmptyStr, EmptyStr, False); end; end; end else if Supports(AComponent, IibSHProcedure) then begin vData.Dataset.SelectSQL.Text := Format(SSelectTemplate, [NormalizeName(AComponent, (AComponent as IibSHProcedure).Caption)]); end; end; constructor TibBTSQLGenerator.Create(AOwner: TComponent); begin inherited Create(AOwner); end; destructor TibBTSQLGenerator.Destroy; begin inherited; end; procedure TibBTSQLGenerator.Notification(AComponent: TComponent; Operation: TOperation); begin if (Operation = opRemove) then begin if AComponent.IsImplementorOf(FCodeNormalizer) then FCodeNormalizer := nil; end; inherited Notification(AComponent, Operation); end; class function TibBTSQLGenerator.GetClassIIDClassFnc: TGUID; begin Result := IibSHSQLGenerator; end; initialization Register; end.
unit Dmitry.Utils.Files; {$WARN SYMBOL_PLATFORM OFF} interface uses Winapi.Windows, System.Classes, System.SysUtils, System.StrUtils, System.Math, System.Win.Registry, Winapi.ShlObj, Winapi.ActiveX, Winapi.ShellAPI, Winapi.ACLApi, Winapi.AccCtrl, Dmitry.Memory, Dmitry.Utils.System, Dmitry.Utils.ShortCut, Dmitry.Utils.Network; type TDriveState = (DS_NO_DISK, DS_UNFORMATTED_DISK, DS_EMPTY_DISK, DS_DISK_WITH_FILES); type TCharBuffer = array of Char; type TFileProgress = procedure(FileName: string; BytesTotal, BytesDone: Int64; var BreakOperation: Boolean) of object; TSimpleFileProgress = reference to procedure(FileName: string; BytesTotal, BytesDone: Int64; var BreakOperation: Boolean); function IsDrive(S: string): Boolean; function IsShortDrive(S: string): Boolean; function IsNetworkServer(S: string): Boolean; function IsNetworkShare(S: string): Boolean; function CreateDirA(Dir: string): Boolean; function FileExistsSafe(FileName: string) : Boolean; function DirectoryExistsSafe(DirectoryPath: string) : Boolean; function ResolveShortcut(Wnd: HWND; ShortcutPath: string): string; function FileExistsEx(const FileName: TFileName) :Boolean; function GetFileDateTime(FileName: string): TDateTime; function GetFileNameWithoutExt(FileName: string): string; function GetDirectorySize(Folder: string): Int64; function GetFileSize(FileName: string): Int64; function GetFileSizeByName(FileName: string): Int64; function LongFileName(ShortName: string): string; function LongFileNameW(ShortName: string): string; function CopyFilesSynch(Handle: Hwnd; Src: TStrings; Dest: string; Move: Boolean; AutoRename: Boolean): Integer; procedure Copy_Move(Handle: THandle; Copy: Boolean; FileList: TStrings); function Mince(PathToMince: string; InSpace: Integer): string; function WindowsCopyFile(FromFile, ToDir: string): Boolean; function WindowsCopyFileSilent(FromFile, ToDir: string): Boolean; function DateModify(FileName: string): TDateTime; function GetFileDescription(FileName: string; UnknownFileDescription: string): string; function MrsGetFileType(StrFilename: string): string; function WipeFile(FileName: string; WipeCycles: Integer = 1; Progress: TSimpleFileProgress = nil): Boolean; function DeleteFiles(Handle: HWnd; Files: TStrings; ToRecycle: Boolean): Integer; function GetCDVolumeLabelEx(CDName: Char): string; function GetDriveVolumeLabel(CDName: AnsiChar): string; function DriveState(Driveletter: AnsiChar): TDriveState; function SilentDeleteFile(Handle: HWnd; FileName: string; ToRecycle: Boolean; HideErrors: Boolean = False): Integer; function SilentDeleteFiles(Handle: HWnd; Names: TStrings; ToRecycle: Boolean; HideErrors: Boolean = False): Integer; procedure DeleteDirectoryWithFiles(DirectoryName: string); procedure GetDirectoresOfPath(Dir: string; Listing: TStrings); procedure GetFilesOfPath(Dir: string; Listing: TStrings); procedure DelDir(Dir: string; Mask: string); function ReadTextFileInString(FileName: string): string; function ExtInMask(Mask: string; Ext: string): Boolean; function GetExt(Filename: string): string; function ProgramDir: string; function GetConvertedFileName(FileName, NewEXT: string): string; function GetConvertedFileNameWithDir(FileName, Dir, NewEXT: string): string; procedure TryOpenFSForRead(var FS: TFileStream; FileName: string; DelayReadFileOperation: Integer); function GetDirListing(Dir: String; Mask: string): TArray<string>; function GetCommonDirectory(FileNames: TStrings): string; function IsDirectoryHasDirectories(const Directory: string): Boolean; function GetAppDataDir: string; procedure ResetFileAttributes(FileName: string; FA: Integer); var CopyFilesSynchCount: Integer = 0; implementation function WipeFile(FileName: string; WipeCycles: Integer = 1; Progress: TSimpleFileProgress = nil): Boolean; var Buffer: array [0 .. 4095] of Byte; Max, N: Int64; I: Integer; FS: TFileStream; BreakOperation: Boolean; procedure RandomizeBuffer; var I: Integer; begin for I := Low(Buffer) to High(Buffer) do Buffer[I] := Random(256); end; begin Result := True; BreakOperation := False; FS := TFileStream.Create(FileName, fmOpenReadWrite or fmShareExclusive); try for I := 1 to WipeCycles do begin RandomizeBuffer; Max := FS.Size; FS.Position := 0; while Max > 0 do begin if Max > SizeOf(Buffer) then N := SizeOf(Buffer) else N := Max; FS.Write(Buffer, N); Max := Max - N; if Assigned(Progress) then begin Progress(FileName, FS.Size, FS.Position, BreakOperation); if BreakOperation then Exit(False); end; end; FlushFileBuffers(FS.Handle); end; finally F(FS); end; end; procedure ResetFileAttributes(FileName: string; FA: Integer); begin if (FA and faHidden) <> 0 then FA := FA - fahidden; if (FA and faReadOnly) <> 0 then FA := FA - faReadOnly; if (FA and faSysFile) <> 0 then FA := FA - faSysFile; FileSetAttr(FileName, FA); end; procedure TryOpenFSForRead(var FS: TFileStream; FileName: string; DelayReadFileOperation: Integer); var I: Integer; OldMode: Cardinal; begin FS := nil; OldMode := SetErrorMode(SEM_FAILCRITICALERRORS); try for I := 1 to 20 do begin try FS := TFileStream.Create(FileName, fmOpenRead or fmShareDenyNone); Break; except if GetLastError in [0, ERROR_PATH_NOT_FOUND, ERROR_INVALID_DRIVE, ERROR_NOT_READY, ERROR_FILE_NOT_FOUND, ERROR_GEN_FAILURE, ERROR_INVALID_NAME] then Exit; Sleep(DelayReadFileOperation); end; end; finally SetErrorMode(OldMode); end; end; function IsNetworkServer(S: string): Boolean; begin Result := False; S := ExcludeTrailingPathDelimiter(S); if (Length(S) > 2) and (Copy(S, 1, 2) = '\\') and (Copy(S, 3, 1) <> '\') and (PosEx('\', S, 3) = 0) then Result := True; end; function IsNetworkShare(S: string): Boolean; begin Result := False; S := ExcludeTrailingPathDelimiter(S); if (Length(S) > 2) and (Copy(S, 1, 2) = '\\') and (Copy(S, 3, 1) <> '\') and (PosEx('\', S, PosEx('\', S, 3) + 1) = 0) then Result := True; end; function IsShortDrive(S: string): Boolean; begin Result := (Length(S) = 2) and (S[2] = ':'); end; function IsDrive(S: string): Boolean; begin Result := IsShortDrive(S) or ((Length(S) = 3) and (S[2] = ':') and (S[3] = '\')); end; function CreateDirA(Dir: string): Boolean; var I: Integer; begin Result := DirectoryExistsSafe(Dir); if Result then Exit; Dir := ExcludeTrailingBackslash(Dir); if Length(Dir) < 3 then Exit; for I := 1 to Length(Dir) do try if (Dir[I] = '\') or (I = Length(Dir)) then if CreateDir(ExcludeTrailingBackslash(Copy(Dir, 1, I))) then Result := I = Length(Dir); except Result := False; Exit; end; end; function IsDirectoryHasDirectories(const Directory: string): Boolean; var FI: WIN32_FIND_DATA; OldMode: Cardinal; H: THandle; begin Result := False; OldMode := SetErrorMode(SEM_FAILCRITICALERRORS); try H := FindFirstFileEx( PChar(IncludeTrailingPathDelimiter(Directory) + '*'), FindExInfoStandard, @FI, FindExSearchLimitToDirectories, nil, 0); try if (H = INVALID_HANDLE_VALUE) then Exit(False); repeat if (string(fi.cFileName) <> '.') and (fi.cFileName <> '..') and (fi.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY > 0) then Exit(True) until (not FindNextFile(H, FI)); finally Winapi.Windows.FindClose(H); end; finally SetErrorMode(OldMode); end; end; function FileExistsSafe(FileName: string): Boolean; var OldMode: Cardinal; begin OldMode := SetErrorMode(SEM_FAILCRITICALERRORS); try Result := FileExists(FileName); finally SetErrorMode(OldMode); end; end; function DirectoryExistsSafe(DirectoryPath: string) : Boolean; var OldMode: Cardinal; begin OldMode := SetErrorMode(SEM_FAILCRITICALERRORS); try Result := DirectoryExists(DirectoryPath); finally SetErrorMode(OldMode); end; end; function GetFileNameWithoutExt(FileName: string): string; var I, N: Integer; begin Result := ''; if FileName = '' then Exit; N := 0; for I := Length(FileName) - 1 downto 1 do if FileName[I] = '\' then begin N := I; Break; end; Delete(FileName, 1, N); if FileName <> '' then if FileName[Length(FileName)] = '\' then Delete(FileName, Length(FileName), 1); for I := Length(FileName) downto 1 do begin if FileName[I] = '.' then begin FileName := Copy(FileName, 1, I - 1); Break; end; end; Result := FileName; end; function FileExistsEx(const FileName :TFileName) : Boolean; var Code :DWORD; begin Code := GetFileAttributes(PWideChar(FileName)); Result := (Code <> DWORD(-1)) and (Code and FILE_ATTRIBUTE_DIRECTORY = 0); end; function ResolveShortcut(Wnd: HWND; ShortcutPath: string): string; var ShortCut: TShortCut; begin ShortCut:= TShortCut.Create(ShortcutPath); try Result := ShortCut.Path; finally ShortCut.Free; end; end; function SetDirectoryWriteRights(lPath : String): Dword; var pDACL: PACL; pEA: PEXPLICIT_ACCESS_W; R: DWORD; begin pEA := AllocMem(SizeOf(EXPLICIT_ACCESS)); BuildExplicitAccessWithName(pEA, 'EVERYONE', GENERIC_WRITE or GENERIC_READ, GRANT_ACCESS, SUB_OBJECTS_ONLY_INHERIT); R := SetEntriesInAcl(1, pEA, nil, pDACL); if R = ERROR_SUCCESS then begin if SetNamedSecurityInfo(PWideChar(lPath), SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, nil, nil, pDACL, nil) <> ERROR_SUCCESS then result := 2 else result := 0; LocalFree(Cardinal(pDACL)); end else result := 1; end; function GetSpecialFolder(hWindow: HWND; Folder: Integer): String; var pMalloc: IMalloc; pidl: PItemIDList; Path: PWideChar; begin // get IMalloc interface pointer if (SHGetMalloc(pMalloc) <> S_OK) then begin MessageBox(hWindow, 'Couldn''t get pointer to IMalloc interface.','SHGetMalloc(pMalloc)', 16); exit; end; // retrieve path SHGetSpecialFolderLocation(hWindow, Folder, pidl); GetMem(Path, MAX_PATH); SHGetPathFromIDList(pidl, Path); Result := Path; FreeMem(Path); // free memory allocated by SHGetSpecialFolderLocation pMalloc.Free(pidl); end; function GetSpecialFolder2(FolderID : longint) : string; var Path : PWideChar; idList : PItemIDList; begin GetMem(Path, MAX_PATH); SHGetSpecialFolderLocation(0, FolderID, idList); SHGetPathFromIDList(idList, Path); Result := string(Path); FreeMem(Path); end; function GetDrives: string; begin Result := IncludeTrailingBackslash(GetSpecialFolder2(CSIDL_Drives)); end; function GetMyMusic: string; begin Result := IncludeTrailingBackslash(GetSpecialFolder2(13)); end; function GetTmpInternetDir: string; begin Result := IncludeTrailingBackslash(GetSpecialFolder2(CSIDL_INTERNET_CACHE)); end; function GetCookiesDir: string; begin Result := IncludeTrailingBackslash(GetSpecialFolder2(CSIDL_COOKIES)); end; function GetHistoryDir: string; begin Result := IncludeTrailingBackslash(GetSpecialFolder2(CSIDL_HISTORY)); end; function GetDesktop: string; begin Result := IncludeTrailingBackslash(GetSpecialFolder2(CSIDL_DESKTOP)); end; function GetDesktopDir: string; begin Result := IncludeTrailingBackslash(GetSpecialFolder2(CSIDL_DESKTOPDIRECTORY)); end; function GetProgDir: string; begin Result := IncludeTrailingBackslash(GetSpecialFolder2(CSIDL_PROGRAMS)); end; function GetMyDocDir: string; begin Result := IncludeTrailingBackslash(GetSpecialFolder2(CSIDL_PERSONAL)); end; function GetFavDir: string; begin Result := IncludeTrailingBackslash(GetSpecialFolder2(CSIDL_FAVORITES)); end; function GetStartUpDir: string; begin Result := IncludeTrailingBackslash(GetSpecialFolder2(CSIDL_STARTUP)); end; function GetRecentDir: string; begin Result := IncludeTrailingBackslash(GetSpecialFolder2(CSIDL_RECENT)); end; function GetSendToDir: string; begin Result := IncludeTrailingBackslash(GetSpecialFolder2(CSIDL_SENDTO)); end; function GetStartMenuDir: string; begin Result := IncludeTrailingBackslash(GetSpecialFolder2(CSIDL_STARTMENU)); end; function GetNetHoodDir: string; begin Result := IncludeTrailingBackslash(GetSpecialFolder2(CSIDL_NETHOOD)); end; function GetFontsDir: string; begin Result := IncludeTrailingBackslash(GetSpecialFolder2(CSIDL_FONTS)); end; function GetTemplateDir: string; begin Result := IncludeTrailingBackslash(GetSpecialFolder2(CSIDL_TEMPLATES)); end; function GetAppDataDir: string; begin Result := IncludeTrailingBackslash(GetSpecialFolder2(CSIDL_APPDATA)); end; function GetPrintHoodDir: string; begin Result := IncludeTrailingBackslash(GetSpecialFolder2(CSIDL_PRINTHOOD)); end; function GetFileDateTime(FileName: string): TDateTime; begin if not FileAge(FileName, Result) then Result := Now; end; function GetDirectorySize(Folder: string): Int64; var Found: Integer; SearchRec: TSearchRec; begin Result := 0; if Length(Trim(Folder)) < 2 then Exit; Folder := IncludeTrailingBackslash(Folder); Found := FindFirst(Folder + '*.*', FaAnyFile, SearchRec); while Found = 0 do begin if (SearchRec.name <> '.') and (SearchRec.name <> '..') then begin if FileExistsSafe(Folder + SearchRec.name) then Result := Result + Int64(SearchRec.FindData.NFileSizeLow) + Int64(SearchRec.FindData.NFileSizeHigh) * 2 * MaxInt else if DirectoryExists(Folder + SearchRec.name) then Result := Result + GetDirectorySize(Folder + '\' + SearchRec.name); end; Found := System.SysUtils.FindNext(SearchRec); end; FindClose(SearchRec); end; function FileTime2DateTime(FT: _FileTime): TDateTime; var FileTime: _SystemTime; begin FileTimeToLocalFileTime(FT, FT); FileTimeToSystemTime(FT, FileTime); Result := EncodeDate(FileTime.WYear, FileTime.WMonth, FileTime.WDay) + EncodeTime(FileTime.WHour, FileTime.WMinute, FileTime.WSecond, FileTime.WMilliseconds); end; function DateModify(FileName: string): TDateTime; var Ts: TSearchRec; begin Result := 0; if FindFirst(FileName, FaAnyFile, Ts) = 0 then Result := FileTime2DateTime(Ts.FindData.FtLastWriteTime); end; function GetFileSize(FileName: string): Int64; var FS: TFileStream; begin try {$I-} FS := TFileStream.Create(Filename, FmOpenRead or FmShareDenyNone); {$I+} except Result := -1; Exit; end; Result := FS.Size; FS.Free; end; function GetFileSizeByName(FileName: string): Int64; var FindData: TWin32FindData; HFind: THandle; begin Result := 0; HFind := FindFirstFile(PChar(FileName), FindData); if HFind <> INVALID_HANDLE_VALUE then begin Winapi.Windows.FindClose(HFind); if (FindData.DwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) = 0 then Result := Int64(FindData.NFileSizeHigh) * 2 * MaxInt + Int64(FindData.NFileSizeLow); end; end; function LongFileName(ShortName: string): string; var SR: TSearchRec; begin Result := ''; if (Pos('\\', ShortName) + Pos('*', ShortName) + Pos('?', ShortName) <> 0) or (not FileExistsSafe(ShortName) and not DirectoryExists(ShortName)) or (Length(ShortName) < 4) then begin Result := ShortName; Exit; end; if Pos('~1', ShortName) = 0 then begin Result := ShortName; Exit; end; while FindFirst(ShortName, FaAnyFile, SR) = 0 do begin { next part as prefix } Result := '\' + SR.name + Result; System.SysUtils.FindClose(SR); { the SysUtils, not the WinProcs procedure! } { directory up (cut before '\') } ShortName := ExtractFileDir(ShortName); if Length(ShortName) <= 2 then begin Break; { ShortName contains drive letter followed by ':' } end; end; Result := AnsiUpperCase(ExtractFileDrive(ShortName)) + Result; end; function LongFileNameW(ShortName: string): string; var SR: TSearchRec; begin Result := ''; if (Pos('\\', ShortName) + Pos('*', ShortName) + Pos('?', ShortName) <> 0) or (not FileExistsSafe(ShortName) and not DirectoryExists(ShortName)) or (Length(ShortName) < 4) then begin Result := ShortName; Exit; end; while FindFirst(ShortName, FaAnyFile, SR) = 0 do begin { next part as prefix } Result := '\' + SR.name + Result; System.SysUtils.FindClose(SR); { the SysUtils, not the WinProcs procedure! } { directory up (cut before '\') } ShortName := ExtractFileDir(ShortName); if Length(ShortName) <= 2 then begin Break; { ShortName contains drive letter followed by ':' } end; end; Result := AnsiUpperCase(ExtractFileDrive(ShortName)) + Result; end; function GetFileDescription(FileName: string; UnknownFileDescription: string): string; var Reg: TRegistry; S: string; begin Result := ''; Reg := TRegistry.Create(KEY_READ); try Reg.RootKey := HKEY_CLASSES_ROOT; if Reg.OpenKey(ExtractFileExt(FileName), False) then begin S := Reg.ReadString(''); Reg.CloseKey; if Reg.OpenKey(S, False) then Result := Reg.ReadString(''); end; finally F(Reg); end; if Result = '' then Result := UnknownFileDescription; end; function MrsGetFileType(StrFilename: string): string; var FileInfo: TSHFileInfo; OldMode: Cardinal; begin OldMode := SetErrorMode(SEM_FAILCRITICALERRORS); try FillChar(FileInfo, SizeOf(FileInfo), #0); SHGetFileInfo(PWideChar(StrFilename), 0, FileInfo, SizeOf(FileInfo), SHGFI_TYPENAME); Result := FileInfo.SzTypeName; finally SetErrorMode(oldMode); end; end; procedure CreateBuffer(Files: TStrings; var P: TCharBuffer); var I: Integer; S: string; begin for I := 0 to Files.Count - 1 do begin if S = '' then S := Files[I] else S := S + #0 + Files[I]; end; S := S + #0#0; SetLength(P, Length(S)); for I := 1 to Length(S) do P[I - 1] := S[I]; end; function CopyFilesSynch(Handle: Hwnd; Src: TStrings; Dest: string; Move: Boolean; AutoRename: Boolean): Integer; const DE_SAMEFILE = $71; var SHFileOpStruct: TSHFileOpStruct; SrcBuf: TCharBuffer; begin Inc(CopyFilesSynchCount); try CreateBuffer(Src, SrcBuf); with SHFileOpStruct do begin Wnd := Handle; if Move then WFunc := FO_MOVE else WFunc := FO_COPY; PFrom := Pointer(SrcBuf); PTo := PWideChar(Dest); FFlags := FOF_ALLOWUNDO; if AutoRename then FFlags := FFlags or FOF_RENAMEONCOLLISION; FAnyOperationsAborted := False; HNameMappings := nil; LpszProgressTitle := nil; end; Result := SHFileOperation(SHFileOpStruct); if Result = DE_SAMEFILE then begin SHFileOpStruct.FFlags := SHFileOpStruct.FFlags or FOF_RENAMEONCOLLISION; Result := SHFileOperation(SHFileOpStruct); end; SrcBuf := nil; finally Dec(CopyFilesSynchCount); end; end; function DeleteFiles(Handle: HWnd; Files: TStrings; ToRecycle: Boolean): Integer; var SHFileOpStruct: TSHFileOpStruct; Src: TCharBuffer; begin CreateBuffer(Files, Src); with SHFileOpStruct do begin Wnd := Handle; WFunc := FO_DELETE; PFrom := Pointer(Src); PTo := nil; FFlags := 0; if ToRecycle then FFlags := FOF_ALLOWUNDO; FAnyOperationsAborted := False; HNameMappings := nil; LpszProgressTitle := nil; end; Result := SHFileOperation(SHFileOpStruct); Src := nil; end; function SilentDeleteFile(Handle: HWnd; FileName: string; ToRecycle: Boolean; HideErrors: Boolean = False): Integer; var Files: TStrings; begin Files := TStringList.Create; try Files.Add(FileName); Result := SilentDeleteFiles(Handle, Files, ToRecycle, HideErrors); finally F(Files); end; end; function SilentDeleteFiles(Handle: HWnd; Names: TStrings; ToRecycle: Boolean; HideErrors: Boolean = False): Integer; var SHFileOpStruct: TSHFileOpStruct; Src: TCharBuffer; begin CreateBuffer(Names, Src); with SHFileOpStruct do begin Wnd := Handle; WFunc := FO_DELETE; PFrom := Pointer(Src); PTo := nil; FFlags := FOF_NOCONFIRMATION; if HideErrors then FFlags := FFlags or FOF_SILENT or FOF_NOERRORUI; if ToRecycle then FFlags := FFlags or FOF_ALLOWUNDO; FAnyOperationsAborted := False; HNameMappings := nil; LpszProgressTitle := nil; end; Result := SHFileOperation(SHFileOpStruct); Src := nil; end; function GetNetworkDriveLabel(NetworkPath: string): string; const EXPLORER_LABEL_PATH = 'Software\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2\'; var Reg: TRegistry; S: String; begin Reg := TRegistry.Create; try Reg.RootKey := HKEY_CURRENT_USER; S := StringReplace(NetworkPath, '\', '#', [rfReplaceAll]); if Reg.OpenKey(EXPLORER_LABEL_PATH + S, False) then Result := Reg.ReadString('_LabelFromReg'); if Result = '' then Result := NetworkPath; finally F(Reg); end; end; function GetCDVolumeLabelEx(CDName: Char): string; begin if GetDriveType(PChar(CDName + ':\')) <> DRIVE_REMOTE then Result := GetDriveVolumeLabel(AnsiChar(CDName)) else Result := GetNetworkDriveLabel(GetNetDrivePath(CDName)); end; function DriveState(DriveLetter: AnsiChar): TDriveState; var Mask: string; SRec: TSearchRec; OldMode: Cardinal; RetCode: Integer; begin OldMode := SetErrorMode(SEM_FAILCRITICALERRORS); try Mask := Char(Driveletter) + ':\*.*'; {$I-} { without exception } RetCode := FindFirst(Mask, FaAnyfile, SRec); FindClose(SRec); {$I+} case Retcode of 0: Result := DS_DISK_WITH_FILES; { at least one file is found } -18: Result := DS_EMPTY_DISK; { empty disk } -21: Result := DS_NO_DISK; { DOS ERROR_NOT_READY } else Result := DS_UNFORMATTED_DISK; { incorrect drive } end; finally SetErrorMode(OldMode); end; end; /// ///Handle: Application.Handle /// procedure Copy_Move(Handle: THandle; Copy: Boolean; FileList: TStrings); var HGlobal, ShGlobal: THandle; DropFiles: PDropFiles; REff: Cardinal; DwEffect: ^Word; RSize, ILen, I: Integer; Files: string; begin if (FileList.Count = 0) or (OpenClipboard(Handle) = False) then Exit; Files := ''; // File1#0File2#0#0 for I := 0 to FileList.Count - 1 do Files := Files + FileList[I] + #0; Files := Files + #0; ILen := Length(Files); try EmptyClipboard; RSize := SizeOf(TDropFiles) + SizeOf(Char) * ILen; HGlobal := GlobalAlloc(GMEM_SHARE or GMEM_MOVEABLE or GMEM_ZEROINIT, RSize); if HGlobal <> 0 then begin DropFiles := GlobalLock(HGlobal); DropFiles.PFiles := SizeOf(TDropFiles); DropFiles.FNC := False; DropFiles.FWide := True; Move(Files[1], (PByte(DropFiles) + SizeOf(TDropFiles))^, ILen * SizeOf(Char)); GlobalUnlock(HGlobal); ShGlobal := SetClipboardData(CF_HDROP, HGlobal); if (ShGlobal <> 0) then begin HGlobal := GlobalAlloc(GMEM_MOVEABLE, SizeOf(DwEffect)); if HGlobal <> 0 then begin DwEffect := GlobalLock(HGlobal); if Copy then DwEffect^ := DROPEFFECT_COPY else DwEffect^ := DROPEFFECT_MOVE; GlobalUnlock(HGlobal); REff := RegisterClipboardFormat(PWideChar('Preferred DropEffect')); // 'CFSTR_PREFERREDDROPEFFECT')); SetClipboardData(REff, HGlobal) end; end; end; finally CloseClipboard; end; end; function Mince(PathToMince: string; InSpace: Integer): string; { ========================================================= } // "C:\Program Files\Delphi\DDrop\TargetDemo\main.pas" // "C:\Program Files\..\main.pas" var Sl: TStringList; SHelp, SFile: string; IPos: Integer; begin SHelp := PathToMince; IPos := Pos('\', SHelp); if IPos = 0 then begin Result := PathToMince; end else begin Sl := TStringList.Create; try // Decode string while IPos <> 0 do begin Sl.Add(Copy(SHelp, 1, (IPos - 1))); SHelp := Copy(SHelp, (IPos + 1), Length(SHelp)); IPos := Pos('\', SHelp); end; if SHelp <> '' then begin Sl.Add(SHelp); end; // Encode string SFile := Sl[Sl.Count - 1]; Sl.Delete(Sl.Count - 1); Result := ''; while (Length(Result + SFile) < InSpace) and (Sl.Count <> 0) do begin Result := Result + Sl[0] + '\'; Sl.Delete(0); end; if Sl.Count = 0 then begin Result := Result + SFile; end else begin Result := Result + '..\' + SFile; end; finally F(Sl); end; end; end; function WindowsCopyFile(FromFile, ToDir: string): Boolean; var F: TShFileOpStruct; begin F.Wnd := 0; F.WFunc := FO_COPY; FromFile := FromFile + #0; F.PFrom := Pchar(FromFile); ToDir := ToDir + #0; F.PTo := Pchar(ToDir); F.FFlags := FOF_ALLOWUNDO or FOF_NOCONFIRMATION; Result := ShFileOperation(F) = 0; end; function WindowsCopyFileSilent(FromFile, ToDir: string): Boolean; var F: TShFileOpStruct; begin F.Wnd := 0; F.WFunc := FO_COPY; FromFile := FromFile + #0; F.PFrom := Pchar(FromFile); ToDir := ToDir + #0; F.PTo := Pchar(ToDir); F.FFlags := FOF_SILENT or FOF_NOCONFIRMATION; Result := ShFileOperation(F) = 0; end; procedure DeleteDirectoryWithFiles(DirectoryName: string); var Found: Integer; SearchRec: TSearchRec; begin if Length(DirectoryName) < 4 then Exit; DirectoryName := IncludeTrailingBackslash(DirectoryName); Found := FindFirst(DirectoryName + '*.*', FaAnyFile, SearchRec); try while Found = 0 do begin if (SearchRec.name <> '.') and (SearchRec.name <> '..') then begin if FileExistsSafe(DirectoryName + SearchRec.Name) then DeleteFile(DirectoryName + SearchRec.name); if DirectoryExists(DirectoryName + SearchRec.name) then DeleteDirectoryWithFiles(DirectoryName + SearchRec.name); end; Found := System.SysUtils.FindNext(SearchRec); end; finally FindClose(SearchRec); end; RemoveDir(DirectoryName); end; procedure GetDirectoresOfPath(Dir: string; Listing : TStrings); var Found: Integer; SearchRec: TSearchRec; begin Listing.Clear; Found := FindFirst(IncludeTrailingBackslash(Dir) + '*.*', FaDirectory, SearchRec); try while Found = 0 do begin if (SearchRec.name <> '.') and (SearchRec.name <> '..') then if (SearchRec.Attr and FaDirectory <> 0) then Listing.Add(SearchRec.name); Found := System.SysUtils.FindNext(SearchRec); end; finally FindClose(SearchRec); end; end; procedure GetFilesOfPath(Dir: string; Listing : TStrings); var Found: Integer; SearchRec: TSearchRec; begin Listing.Clear; Dir := IncludeTrailingBackslash(Dir); Found := FindFirst(Dir + '*.*', faAnyFile - FaDirectory, SearchRec); try while Found = 0 do begin if (SearchRec.Name <> '.') and (SearchRec.Name <> '..') then if (SearchRec.Attr and FaDirectory = 0) then Listing.Add(Dir + SearchRec.name); Found := System.SysUtils.FindNext(SearchRec); end; finally FindClose(SearchRec); end; end; procedure DelDir(Dir: string; Mask: string); var FileName : string; Found: Integer; SearchRec: TSearchRec; FileExists, DirectoryExists : Boolean; begin if Length(Dir) < 4 then Exit; Dir := IncludeTrailingBackSlash(Dir); Found := FindFirst(Dir + '*.*', FaAnyFile, SearchRec); try while Found = 0 do begin if (SearchRec.Name <> '.') and (SearchRec.Name <> '..') then begin FileName := Dir + SearchRec.Name; FileExists := (SearchRec.Attr and FaDirectory = 0); DirectoryExists := (SearchRec.Attr and FaDirectory <> 0); if FileExists and ExtinMask(Mask, GetExt(FileName)) then begin FileSetAttr(FileName, 0); DeleteFile(FileName); end else if DirectoryExists then DelDir(FileName, Mask); end; if (SearchRec.Attr and FaDirectory <> 0) then RemoveDir(FileName); Found := System.SysUtils.FindNext(SearchRec); end; finally FindClose(SearchRec); end; RemoveDir(Dir); end; function ReadTextFileInString(FileName: string): string; var FS: TFileStream; begin Result := ''; if not FileExists(FileName) then Exit; try FS := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try SetLength(Result, FS.Size); try FS.Read(Result[1], FS.Size); except Exit; end; finally F(FS); end; end; function GetExt(Filename : string) : string; var I, J: Integer; S: string; begin J := 0; for I := Length(Filename) downto 1 do begin if Filename[I] = '.' then begin J := I; Break; end; if Filename[I] = '\' then Break; end; S := ''; if J <> 0 then begin S := Copy(Filename, J + 1, Length(Filename) - J); for I := 1 to Length(S) do S[I] := Upcase(S[I]); end; Result := S; end; function ExtinMask(Mask: string; Ext: string): Boolean; begin Result := False; if Mask = '||' then begin Result := True; Exit; end; if Ext = '' then Exit; mask := '|' + AnsiUpperCase(Mask) + '|'; Ext := AnsiUpperCase(Ext); Result := Pos('|' + Ext + '|', Mask) > 0; end; function ProgramDir : string; begin Result := IncludeTrailingBackSlash(ExtractFileDir(ParamStr(0))); end; function GetConvertedFileName(FileName, NewEXT : string) : string; var S, Dir: string; I: Integer; begin Result := FileName; Dir := ExtractFileDir(Result); ChangeFileExt(Result, NewEXT); Result := Dir + GetFileNameWithoutExt(Result) + '.' + AnsiLowerCase(NewEXT); if not FileExists(Result) then Exit; S := Dir + ExtractFileName(Result); I := 1; while (FileExists(S)) do begin S := Dir + GetFileNameWithoutExt(Result) + ' (' + IntToStr(I) + ').' + NewEXT; Inc(I); end; Result := S; end; function GetConvertedFileNameWithDir(FileName, Dir, NewEXT : string) : string; var S: string; I: Integer; begin Result := FileName; Dir := IncludeTrailingBackslash(Dir); ChangeFileExt(Result, NewEXT); Result := Dir + GetFileNameWithoutExt(Result) + '.' + AnsiLowerCase(NewEXT); if not FileExists(Result) then Exit; S := Dir + ExtractFileName(Result); I := 1; while (FileExists(S)) do begin S := Dir + GetFileNameWithoutExt(Result) + ' (' + IntToStr(I) + ').' + NewEXT; Inc(I); end; Result := S; end; function GetDriveVolumeLabel(CDName: AnsiChar): string; var VolumeName, FileSystemName: array [0..MAX_PATH-1] of Char; VolumeSerialNo: DWord; MaxComponentLength,FileSystemFlags: Cardinal; OldMode: Cardinal; begin OldMode := SetErrorMode(SEM_FAILCRITICALERRORS); try if GetVolumeInformation(PChar(CDName + ':\'), VolumeName, MAX_PATH, @VolumeSerialNo, MaxComponentLength, FileSystemFlags, FileSystemName, MAX_PATH) then Result := VolumeName else Result := CDName + ':\'; finally SetErrorMode(OldMode); end; end; function GetDirListing(Dir: String; Mask: string): TArray<string>; var Found: Integer; SearchRec: TSearchRec; OldMode: Cardinal; function ExtInMask(Mask: string; Ext: string): Boolean; begin Result := Pos('|' + Ext + '|', Mask) <> -1; end; function GetExt(FileName: string): string; var S: string; begin S := ExtractFileExt(FileName); Result := AnsiUpperCase(Copy(S, 1, Length(S) - 1)); end; begin OldMode := SetErrorMode(SEM_FAILCRITICALERRORS); try SetLength(Result, 0); if Dir = '' then Exit; Dir := IncludeTrailingBackslash(Dir); Found := FindFirst(Dir + '*.*', FaAnyFile - FaDirectory, SearchRec); try while Found = 0 do begin if (SearchRec.name <> '.') and (SearchRec.name <> '..') then if ExtInMask(GetExt(SearchRec.name), Mask) then begin SetLength(Result, Length(Result) + 1); Result[Length(Result) - 1] := Dir + SearchRec.name; end; Found := System.SysUtils.FindNext(SearchRec); end; finally FindClose(SearchRec); end; finally SetErrorMode(OldMode); end; end; function GetCommonDir(Dir1 { Common dir } , Dir2 { Compare dir } : string): string; var I, C: Integer; begin if Dir1 = Dir2 then begin Result := Dir1; end else begin if Dir1 = Copy(Dir2, 1, Length(Dir1)) then begin Result := Dir1; Exit; end; C := Min(Length(Dir1), Length(Dir2)); for I := 1 to C do if Dir1[I] <> Dir2[I] then begin C := I; Break; end; Result := ExtractFilePath(Copy(Dir1, 1, C - 1)); end; end; function GetCommonDirectory(FileNames: TStrings): string; var I: Integer; S, Temp, D: string; Files: TStrings; begin Result := ''; if FileNames.Count = 0 then Exit; Files := TStringList.Create; try Files.Assign(FileNames); for I := 0 to Files.Count - 1 do Files[I] := ExtractFilePath(Files[I]); S := AnsiLowerCase(Copy(Files[0], 1, 2)); Temp := AnsiLowerCase(Files[0]); for I := 0 to Files.Count - 1 do begin Files[I] := AnsiLowerCase(Files[I]); if Length(Files[I]) < 2 then Exit; if S <> Copy(Files[I], 1, 2) then Exit; D := ExtractFilePath(Files[I]); if Length(Temp) > Length(D) then Temp := D; end; for I := 0 to Files.Count - 1 do Temp := GetCommonDir(Temp, Files[I]); Result := Temp; finally F(Files); end; end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, GL, GLU, StdCtrls, ExtCtrls,UrickGL, U3Dpolys; type TForm1 = class(TForm) Panel1: TPanel; Timer1: TTimer; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure Timer1Timer(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } public { Public declarations } Scene:TSceneGL; end; var Form1: TForm1; rx,ry,rz:word; implementation {$R *.DFM} procedure TForm1.FormCreate(Sender: TObject); var cube:Tentity; Face:TFace; light:Tlight; begin Scene:=TSceneGL.create; // Создаем новую сцену Cube:=TEntity.create; // Создаем пустой объект TEntity Cube.SetColor(90,200,150); // Инициируем цвета R,G,B Face:=cube.addFace; // Создаем 1-й face в исходном кубе всего 6 граней ( в кубе ) Face.AddVertex(1.0, 1.0, 1.0,0.0, 0.0, 1.0); // добавляем 1-й vertex Face.AddVertex(-1.0, 1.0, 1.0,0.0, 0.0, 1.0); // добавляем 2-й vertex Face.AddVertex(-1.0, -1.0, 1.0,0.0, 0.0, 1.0);// добавляем 3-й vertex Face.AddVertex(1.0, -1.0, 1.0,0.0, 0.0, 1.0);// добавляем 4-й vertex Face:=cube.addFace; Face.AddVertex(1.0, 1.0, -1.0,0.0, 0.0, -1.0); Face.AddVertex(1.0, -1.0, -1.0,0.0, 0.0, -1.0); Face.AddVertex(-1.0, -1.0, -1.0,0.0, 0.0, -1.0); Face.AddVertex(-1.0, 1.0, -1.0,0.0, 0.0, -1.0); Face:=cube.addFace; Face.AddVertex(-1.0, 1.0, 1.0,-1.0, 0.0, 0.0); Face.AddVertex(-1.0, 1.0, -1.0,-1.0, 0.0, 0.0); Face.AddVertex(-1.0, -1.0, -1.0,-1.0, 0.0, 0.0); Face.AddVertex(-1.0, -1.0, 1.0,-1.0, 0.0, 0.0); Face:=cube.addFace; Face.AddVertex(1.0, 1.0, 1.0,1.0, 0.0, 0.0); Face.AddVertex(1.0, -1.0, 1.0,1.0, 0.0, 0.0); Face.AddVertex(1.0, -1.0, -1.0,1.0, 0.0, 0.0); Face.AddVertex(1.0, 1.0, -1.0,1.0, 0.0, 0.0); Face:=cube.addFace; Face.AddVertex(-1.0, 1.0, -1.0,0.0, 1.0, 0.0); Face.AddVertex(-1.0, 1.0, 1.0,0.0, 1.0, 0.0); Face.AddVertex(1.0, 1.0, 1.0,0.0, 1.0, 0.0); Face.AddVertex(1.0, 1.0, -1.0,0.0, 1.0, 0.0); Face:=cube.addFace; Face.AddVertex(-1.0, -1.0, -1.0,0.0, -1.0, 0.0); Face.AddVertex(1.0, -1.0, -1.0,0.0, -1.0, 0.0); Face.AddVertex(1.0, -1.0, 1.0,0.0, -1.0, 0.0); Face.AddVertex(-1.0, -1.0, 1.0,0.0, -1.0, 0.0); with cube do begin move(0,0,-15); // Перемещаем куб в координаты x, y, z Rotate(-30,-30,-30); // и поворачиваем на угол end; Scene.Entities.add(cube);// добавим куб на сцену light:=Tlight.create(1); // создадим источник света и Scene.lights.add(light); // добавим его на сцену Scene.InitRC(panel1.handle); // передадим Handle Panel1 нашей сцене, // на ней будет происходить рендеринг Scene.UpdateArea(panel1.width,panel1.height); end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin Scene.free; // очищаем сцену end; procedure TForm1.Timer1Timer(Sender: TObject); begin inc(rx,1); if rx>360 then rx:=0; inc(ry,2); if ry>360 then ry:=0; dec(rz,1); if rz<0 then rz:=360; Tentity(Scene.Entities.Items[0]).Rotate(rx,ry,rz); // повернем куб Scene.Redraw; // ... и обновим сцену end; procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if key=Vk_Escape then close; // выход end; end.
unit Unit1; interface uses Winapi.OpenGL, Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.Buttons, Vcl.Forms, Vcl.Dialogs, GLWin32Viewer, GLCrossPlatform, GLBaseClasses, GLScene, GLObjects, GLCoordinates, GLColor, GLVectorGeometry, GLMesh, GLVectorFileObjects, GLState, GLGeomObjects, GLExtrusion, GLTypes, GLIsosurface, GLSimpleNavigation, GLMaterial; type TForm1 = class(TForm) Panel1: TPanel; GLScene1: TGLScene; GLSceneViewer1: TGLSceneViewer; GLCamera1: TGLCamera; GLDummyCube1: TGLDummyCube; GLLightSource1: TGLLightSource; CheckBox1: TCheckBox; ComboBox1: TComboBox; Label1: TLabel; Edit1: TEdit; Label2: TLabel; BitBtn1: TBitBtn; GLMesh1: TGLMesh; GLSimpleNavigation1: TGLSimpleNavigation; GLFreeForm1: TGLFreeForm; ComboBox2: TComboBox; procedure FormDestroy(Sender: TObject); procedure CheckBox1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ComboBox1Change(Sender: TObject); procedure BitBtn1Click(Sender: TObject); procedure ComboBox2Change(Sender: TObject); private mo: TMeshObject; MC: TGLMarchingCube; public //Public declarations end; var Form1: TForm1; implementation {$R *.dfm} // comment next line to use GLMesh instead GLFreeForm {$DEFINE UseGLFreeForm} procedure TForm1.CheckBox1Click(Sender: TObject); begin {$IFDEF UseGLFreeForm} if CheckBox1.Checked then GLFreeForm1.Material.PolygonMode := pmFill else GLFreeForm1.Material.PolygonMode := pmLines {$ELSE} if CheckBox1.Checked then GLMesh1.Material.PolygonMode := pmFill else GLMesh1.Material.PolygonMode := pmLines {$ENDIF} end; procedure TForm1.FormCreate(Sender: TObject); begin with GLLightSource1 do begin Position.SetPoint(100, 200, 300); Ambient.SetColor(0.6, 0.6, 0.0, 0.1); Diffuse.SetColor(0.2, 0.4, 1.0, 0.1); Specular.SetColor(1.0, 1.0, 1.0, 0.1) end; {$IFDEF UseGLFreeForm} GLMesh1.Visible := False; mo := TMeshObject.CreateOwned(GLFreeForm1.MeshObjects); mo.Mode := momFaceGroups; {$ELSE} GLFreeForm1.Visible := False; {$ENDIF} MC := TGLMarchingCube.Create(100, 100, 100); BitBtn1Click(nil) end; procedure TForm1.FormDestroy(Sender: TObject); begin MC.Free end; procedure TForm1.ComboBox1Change(Sender: TObject); begin Edit1.Text := floattostr(DemoScalarField[ComboBox1.ItemIndex].IsoValue); BitBtn1Click(nil) end; procedure TForm1.ComboBox2Change(Sender: TObject); begin {$IFDEF UseGLFreeForm} GLFreeForm1.Material.FaceCulling := TFaceCulling(ComboBox2.ItemIndex) {$ELSE} GLMesh1.Material.FaceCulling := TFaceCulling(ComboBox2.ItemIndex) {$ENDIF} end; procedure TForm1.BitBtn1Click(Sender: TObject); var IsoValue: TGLScalarValue; begin // try to accept user value, but if uncorrect assign a correct demo value IsoValue := StrToFloatDef(Edit1.Text, DemoScalarField[ComboBox1.ItemIndex] .IsoValue); Edit1.Text := FormatFloat('0.0000', IsoValue); MC.FillVoxelData(IsoValue, DemoScalarField[ComboBox1.ItemIndex].ScalarField); MC.Run; {$IFDEF UseGLFreeForm} mo.Free; mo := TMeshObject.CreateOwned(GLFreeForm1.MeshObjects); mo.Mode := momFaceGroups; MC.CalcMeshObject(mo, 0.6); {$ELSE} MC.CalcVertices(GLMesh1.Vertices); {$ENDIF} GLSceneViewer1.Invalidate; end; end.
unit ThStructuredHtml; interface uses Classes, ThStructuredDocument; type TThStructuredHtml = class(TThStructuredDocument) private FBodyOnly: Boolean; function GetHeaders: TStrings; // function GetScript: TStrings; function GetStyles: TStrings; function GetTitle: TStrings; protected function GetBody: TStrings; protected function ShouldPublish(const inSection: string): Boolean; override; public procedure NewDocument; procedure PublishToStrings(inStrings: TStrings); override; public property Body: TStrings read GetBody; property BodyOnly: Boolean read FBodyOnly write FBodyOnly; property Headers: TStrings read GetHeaders; // property Script: TStrings read GetScript; property Styles: TStrings read GetStyles; property Title: TStrings read GetTitle; end; const shDocType = 'DocType'; //shHtml = 'Html'; shHead = 'Head'; shTitle = 'Title'; shHeaders = 'Headers'; shStyles = 'Styles'; // shScript = 'Script'; shBody = 'Body'; //shJsLibs = '*JsLibs'; implementation { TThStructuredHtml } procedure TThStructuredHtml.NewDocument; const cDocType = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">'; begin Clear; //Section[shDocType]. Add(cDocType); Add('<html>'); Add('<head>'); // with Section[shHead] do begin Add('<title>'); Section[shTitle]; Add('</title>'); Section[shHeaders]; Add('<style type="text/css">'); Add('<!--'); Section[shStyles]; Add('-->'); Add('</style>'); // Add('<script language="javascript" type="text/javascript">'); // Add('<!--'); // Section[shScript]; // Add('-->'); // Add('</script>'); end; Add('</head>'); // Add('<body>'); Section[shBody]; // Add('</body>'); Add('</html>'); end; function TThStructuredHtml.ShouldPublish(const inSection: string): Boolean; begin Result := (inSection = '') or (inSection[1] <> '*'); //Result := (inSection <> shJsLibs); end; procedure TThStructuredHtml.PublishToStrings(inStrings: TStrings); begin if not BodyOnly then inherited else with Section[shBody] do PublishToStrings(inStrings); end; function TThStructuredHtml.GetBody: TStrings; begin Result := Section[shBody]; end; function TThStructuredHtml.GetHeaders: TStrings; begin Result := Section[shHeaders]; end; //function TThStructuredHtml.GetScript: TStrings; //begin // Result := Section[shScript]; //end; function TThStructuredHtml.GetStyles: TStrings; begin Result := Section[shStyles]; end; function TThStructuredHtml.GetTitle: TStrings; begin Result := Section[shTitle]; end; end.
(* Category: SWAG Title: OOP/TURBO VISION ROUTINES Original name: 0014.PAS Description: OOPMENU.PAS Author: SWAG SUPPORT TEAM Date: 05-28-93 13:53 *) { Menus in TV are instances of class tMenuBar, accessed via Pointer Type pMenuBar. A Complete menu is a Single-linked list, terminated With a NIL Pointer. Each item or node is just a Record that holds inFormation on what the node displays and responds to, and a Pointer to the next menu node in the list. I've written out a short bit of TV menu code that you can Compile and play With, and then you can highlight parts that you don't understand when you send back your reply. } Program TestMenu; Uses Objects, Drivers, Views, Menus, App; Const cmOpen = 100; (* Command message Constants *) cmClose = 101; Type pTestApp = ^tTestApp; tTestApp = Object(tApplication) Procedure InitMenuBar; Virtual; (* Do-nothing inherited method *) end; (* which you override *) (* Set up the menu by filling in the inherited method *) Procedure tTestApp.InitMenuBar; Var vRect : tRect; begin GetExtent(vRect); vRect.B.Y := vRect.A.Y + 1; MenuBar := New(pMenuBar, Init(vRect, NewMenu( NewSubMenu('~F~ile', hcNoConText, NewMenu( NewItem('~O~pen', 'Alt-O', kbAltO, cmOpen, hcNoConText, NewItem('~C~lose', 'Alt-C', kbAltC, cmClose, hcNoConText, NewItem('E~x~it', 'Alt-X', kbAltX, cmQuit, hcNoConText, NIL)))), NewSubMenu('~E~dit', hcNoConText, NewMenu( NewItem('C~u~t', 'Alt-U', kbAltU, cmCut, hcNoConText, NewItem('Cop~y~', 'Alt-Y', kbAltY, cmCopy, hcNoConText, NewItem('~P~aste', 'Alt-P', kbAltP, cmPaste, hcNoConText, NewItem('C~l~ear', 'Alt-L', kbAltL, cmClear, hcNoConText, NIL))))), NewSubMenu('~W~indow', hcNoConText, NewMenu( NewItem('Ca~s~cade', 'Alt-S', kbAltS, cmCascade, hcNoConText, NewItem('~T~ile', 'Alt-T', kbAltT, cmTile, hcNoConText, NIL))), NIL)))) )) end; Var vApp : pTestApp; begin New(vApp, Init); if vApp = NIL then begin WriteLn('Couldn''t instantiate the application'); Exit; end; vApp^.Run; vApp^.Done; end.
unit Frame.DHLShipmentOrder; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Objekt.DHLShipmentOrderRequestAPI, Objekt.DHLShipmentorderResponseList, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, Objekt.Downloadfile, Objekt.DHLUpdateShipmentOrderResponse, Objekt.DHLUpdateShipmentOrderRequestAPI, Objekt.DHLShipmentorderResponse, Objekt.DHLDeleteShipmentOrderRequestAPI, Objekt.DHLDeleteShipmentorderResponse, Objekt.DHLGetLabelRequestAPI, Objekt.DHLGetLabelResponse; type Tfra_DHLShipmentOrder = class(TFrame) Panel1: TPanel; btn_ErzeugeShipmentorder: TButton; Memo1: TMemo; btn_UpdateShipmentOrder: TButton; btn_DeleteShipmentorder: TButton; btn_GetLabel: TButton; procedure btn_ErzeugeShipmentorderClick(Sender: TObject); procedure btn_UpdateShipmentOrderClick(Sender: TObject); procedure btn_DeleteShipmentorderClick(Sender: TObject); procedure btn_GetLabelClick(Sender: TObject); private fDownloadfile: TDownloadfile; fShipmentOrderResponseList: TDHLShipmentorderResponseList; fShipmentOrder: TDHLShipmentOrderRequestAPI; procedure SendeShipmentOrder; procedure UpdateShipmentOrder; procedure DeleteShipmentOrder; procedure GetLabel; procedure FillUpdateShipmentOrder(U: TDHLUpdateShipmentOrderRequestAPI); procedure FillShipmentOrderRequest(R: TDHLShipmentOrderRequestAPI); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; implementation {$R *.dfm} { TFrame1 } uses Objekt.Allgemein; constructor Tfra_DHLShipmentOrder.Create(AOwner: TComponent); begin inherited; Memo1.Clear; fDownloadfile := TDownloadfile.Create; fShipmentOrder := nil; end; destructor Tfra_DHLShipmentOrder.Destroy; begin if fShipmentOrder <> nil then FreeAndNil(fShipmentOrder); FreeAndNil(fDownloadfile); inherited; end; procedure Tfra_DHLShipmentOrder.btn_ErzeugeShipmentorderClick(Sender: TObject); begin SendeShipmentOrder; end; procedure Tfra_DHLShipmentOrder.SendeShipmentOrder; var Cur: TCursor; i1: Integer; Filename: string; begin Cur := Screen.Cursor; if fShipmentOrder <> nil then FreeAndNil(fShipmentOrder); fShipmentOrder := TDHLShipmentOrderRequestAPI.Create; try Screen.Cursor := crHourGlass; FillShipmentOrderRequest(fShipmentOrder); fShipmentOrderResponseList := AllgemeinObj.DHLSend.SendShipmentOrder(fShipmentOrder, AllgemeinObj.DownloadPath + 'ShipmentOrder.xml'); Memo1.Clear; Memo1.Lines.Add('Statustext = ' + fShipmentOrderResponseList.StatusText); Memo1.Lines.Add('Statuscode = ' + IntToStr(fShipmentOrderResponseList.StatusCode)); Memo1.Lines.Add('Statusmessage = ' + fShipmentOrderResponseList.StatusMessage); for i1 := 0 to fShipmentOrderResponseList.Count -1 do begin Memo1.Lines.Add('ShipmentNumber = ' + fShipmentOrderResponseList.Item[i1].ShipmentNumber); Memo1.Lines.Add('SequenceNumber = ' + fShipmentOrderResponseList.Item[i1].SequenceNumber); Memo1.Lines.Add('LabelStatusText = ' + fShipmentOrderResponseList.Item[i1].LabelStatusText); Memo1.Lines.Add('LabelStatusCode = ' + IntToStr(fShipmentOrderResponseList.Item[i1].LabelStatusCode)); Memo1.Lines.Add('LabelStatusMessage = ' + fShipmentOrderResponseList.Item[i1].LabelStatusMessage); Memo1.Lines.Add('LabelUrl = ' + fShipmentOrderResponseList.Item[i1].LabelUrl); Memo1.Lines.Add('ReturnLabelUrl = ' + fShipmentOrderResponseList.Item[i1].ReturnLabelUrl); Memo1.Lines.Add('ExportLabelUrl = ' + fShipmentOrderResponseList.Item[i1].ExportLabelUrl); Memo1.Lines.Add('CodLabelUrl = ' + fShipmentOrderResponseList.Item[i1].CodLabelUrl); end; for i1 := 0 to fShipmentOrderResponseList.Count -1 do begin Filename := 'Label_' + fShipmentOrderResponseList.Item[i1].ShipmentNumber + '.pdf'; if (fShipmentOrderResponseList.StatusCode = 0) and (fShipmentOrderResponseList.Item[i1].LabelStatusCode = 0) then fDownloadfile.Download(fShipmentOrderResponseList.Item[i1].LabelUrl, AllgemeinObj.DownloadPath + Filename); end; finally Screen.Cursor := cur; end; end; procedure Tfra_DHLShipmentOrder.FillShipmentOrderRequest(R: TDHLShipmentOrderRequestAPI); begin R.Version.majorRelease := '2'; R.Version.minorRelease := '2'; R.ShipmentOrder.sequenceNumber := '123456'; r.ShipmentOrder.Shipment.Shipmentdetails.Product := 'V01PAK'; r.ShipmentOrder.Shipment.Shipmentdetails.AccountNumber := '22222222220101'; r.ShipmentOrder.Shipment.Shipmentdetails.CustomerReference := 'Kundennummer 123456'; r.ShipmentOrder.Shipment.Shipmentdetails.ShipmentDate := StrToDate('31.12.2018'); { r.ShipmentOrder.Shipment.Shipmentdetails.ShipmentItem.WeightKG := 5; r.ShipmentOrder.Shipment.Shipmentdetails.ShipmentItem.LengthCM := 60; r.ShipmentOrder.Shipment.Shipmentdetails.ShipmentItem.WidthCM := 30; r.ShipmentOrder.Shipment.Shipmentdetails.ShipmentItem.HeightCM := 15; } r.ShipmentOrder.Shipment.Shipmentdetails.ShipmentItem.WeightKG := 5; r.ShipmentOrder.Shipment.Shipmentdetails.ShipmentItem.LengthCM := 0; r.ShipmentOrder.Shipment.Shipmentdetails.ShipmentItem.WidthCM := 0; r.ShipmentOrder.Shipment.Shipmentdetails.ShipmentItem.HeightCM := 0; r.ShipmentOrder.Shipment.Shipmentdetails.Notification.recipientEmailAddress := 'Absender@muster.de'; r.ShipmentOrder.Shipment.Shipper.Name.Name1 := 'Absender Zeile 1'; r.ShipmentOrder.Shipment.Shipper.Name.Name2 := 'Absender Zeile 2'; r.ShipmentOrder.Shipment.Shipper.Name.Name3 := 'Absender Zeile 3'; r.ShipmentOrder.Shipment.Shipper.Adress.StreetName := 'Vegesacker Heerstr.'; r.ShipmentOrder.Shipment.Shipper.Adress.StreetNumber := '111'; r.ShipmentOrder.Shipment.Shipper.Adress.AddressAddition := '2.Etage'; r.ShipmentOrder.Shipment.Shipper.Adress.DispatchingInformation := 'Abgangsinformation'; r.ShipmentOrder.Shipment.Shipper.Adress.Zip := '28757'; r.ShipmentOrder.Shipment.Shipper.Adress.City := 'Bremen'; r.ShipmentOrder.Shipment.Shipper.Adress.Origin.Country := 'Germany'; r.ShipmentOrder.Shipment.Shipper.Adress.Origin.CountryISOCode := 'DE'; r.ShipmentOrder.Shipment.Shipper.Communication.Phone := '+49421123456'; r.ShipmentOrder.Shipment.Shipper.Communication.EMail := 'Empfaengerin@muster.de'; r.ShipmentOrder.Shipment.Shipper.Communication.ContactPerson := 'Frau Empfänger'; r.ShipmentOrder.Shipment.Receiver.Name1 := 'Empfänger Zeile 1'; r.ShipmentOrder.Shipment.Receiver.Address.Name2 := 'Empfänger Zeile 2'; r.ShipmentOrder.Shipment.Receiver.Address.Name3 := 'Empfänger Zeile 3'; r.ShipmentOrder.Shipment.Receiver.Address.StreetName := 'Neu-Galliner-Ring'; r.ShipmentOrder.Shipment.Receiver.Address.StreetNumber := '8'; r.ShipmentOrder.Shipment.Receiver.Address.AddressAddition := '3. Etage'; r.ShipmentOrder.Shipment.Receiver.Address.DispatchingInformation := '?'; r.ShipmentOrder.Shipment.Receiver.Address.Zip := '19258'; r.ShipmentOrder.Shipment.Receiver.Address.City := 'Gallin'; r.ShipmentOrder.Shipment.Receiver.Address.Origin.Country := 'Germany'; r.ShipmentOrder.Shipment.Receiver.Address.Origin.CountryISOCode := 'DE'; r.ShipmentOrder.Shipment.Receiver.Address.Origin.State := '?'; r.ShipmentOrder.Shipment.Receiver.Communication.Phone := '+49421123456789'; r.ShipmentOrder.Shipment.Receiver.Communication.EMail := 'empfaengerin@muster.de'; r.ShipmentOrder.Shipment.Receiver.Communication.ContactPerson := 'Frau Empfängerin'; r.ShipmentOrder.PrintOnlyIfCodeable.Active := '1'; end; procedure Tfra_DHLShipmentOrder.btn_UpdateShipmentOrderClick(Sender: TObject); begin // UpdateShipmentOrder; end; procedure Tfra_DHLShipmentOrder.UpdateShipmentOrder; var UpdateShipmentOrder: TDHLUpdateShipmentOrderRequestAPI; Response: TDHLUpdateShipmentOrderResponse; begin // UpdateShipmentOrder := TDHLUpdateShipmentOrderRequestAPI.Create; try FillUpdateShipmentOrder(UpdateShipmentOrder); Response := AllgemeinObj.DHLSend.SendUpdateShipmentOrder(UpdateShipmentOrder, AllgemeinObj.DownloadPath + 'UpdateShipmentOrder.xml'); Memo1.Clear; Memo1.Lines.Add('StatusText = ' + Response.Status.StatusText); Memo1.Lines.Add('StatusMessage = ' + Response.Status.StatusMessage); finally FreeAndNil(UpdateShipmentOrder); end; end; procedure Tfra_DHLShipmentOrder.FillUpdateShipmentOrder(U: TDHLUpdateShipmentOrderRequestAPI); var sr : TDHLShipmentorderResponse; begin sr := fShipmentOrderResponseList.Item[0]; u.ShipmentNumber := sr.ShipmentNumber; U.Version.majorRelease := '2'; U.Version.minorRelease := '2'; U.ShipmentOrder.sequenceNumber := fShipmentOrder.ShipmentOrder.sequenceNumber; U.ShipmentOrder.Shipment.Copy(fShipmentOrder.ShipmentOrder.Shipment); end; procedure Tfra_DHLShipmentOrder.btn_DeleteShipmentorderClick(Sender: TObject); begin // DeleteShipmentorder; end; procedure Tfra_DHLShipmentOrder.DeleteShipmentOrder; var DeleteShipmentOrder: TDHLDeleteShipmentOrderRequestAPI; Response: TDHLDeleteShipmentOrderResponse; i1: Integer; sr : TDHLShipmentorderResponse; begin sr := fShipmentOrderResponseList.Item[0]; DeleteShipmentOrder := TDHLDeleteShipmentOrderRequestAPI.Create; DeleteShipmentOrder.ShipmentNumber := sr.ShipmentNumber; //DeleteShipmentOrder.ShipmentNumber := '3745835968'; DeleteShipmentOrder.Version.minorRelease := '2'; DeleteShipmentOrder.Version.majorRelease := '2'; Response := AllgemeinObj.DHLSend.SendDeleteShipmentOrder(DeleteShipmentOrder, AllgemeinObj.DownloadPath + 'DeleteShipmentOrder.xml'); Memo1.Clear; Memo1.Lines.Add('StatusText = ' + Response.Status.StatusText); Memo1.Lines.Add('StatusMessage = ' + Response.Status.StatusMessage); for i1 := 0 to Response.DeletionState.Count -1 do begin Memo1.Lines.Add('D.StatusText = ' + Response.DeletionState.Item[i1].Status.StatusText); Memo1.Lines.Add('D.StatusMessage = ' + Response.DeletionState.Item[i1].Status.StatusMessage); Memo1.Lines.Add('D.ShipmentNumber = ' + Response.DeletionState.Item[i1].ShipmentNumber); end; FreeAndNil(DeleteShipmentOrder); end; procedure Tfra_DHLShipmentOrder.btn_GetLabelClick(Sender: TObject); begin GetLabel; end; procedure Tfra_DHLShipmentOrder.GetLabel; var GetLabel: TDHLGetLabelRequestAPI; Response: TDHLGetLabelResponse; i1: Integer; sr : TDHLShipmentorderResponse; begin //sr := fShipmentOrderResponseList.Item[0]; GetLabel := TDHLGetLabelRequestAPI.Create; //GetLabel.ShipmentNumber := sr.ShipmentNumber; GetLabel.ShipmentNumber := '222201010031989260'; GetLabel.Version.minorRelease := '2'; GetLabel.Version.majorRelease := '2'; Response := AllgemeinObj.DHLSend.SendGetLabel(GetLabel, AllgemeinObj.DownloadPath + 'GetLabel.xml'); Memo1.Clear; Memo1.Lines.Add('StatusText = ' + Response.Status.StatusText); Memo1.Lines.Add('StatusMessage = ' + Response.Status.StatusMessage); for i1 := 0 to Response.LabelData.Count -1 do begin Memo1.Lines.Add('L.StatusText = ' + Response.LabelData.Item[i1].Status.StatusText); Memo1.Lines.Add('L.StatusMessage = ' + Response.LabelData.Item[i1].Status.StatusMessage); Memo1.Lines.Add('ShipmentNumber = ' + Response.LabelData.Item[i1].ShipmentNumber); Memo1.Lines.Add('LabelUrl = ' + Response.LabelData.Item[i1].LabelUrl); end; FreeAndNil(GetLabel); end; end.
// Credit to Paul Bourke (pbourke@swin.edu.au) for the original Fortran 77 Program :)) // Conversion to Visual Basic by EluZioN (EluZioN@casesladder.com) // Conversion from VB to Delphi6 by Dr Steve Evans (steve@lociuk.com) /// //////////////////////////////////////////////////////////////////////////// // June 2002 Update by Dr Steve Evans (steve@lociuk.com): Heap memory allocation // added to prevent stack overflow when MaxVertices and MaxTriangles are very large. // Additional Updates in June 2002: // Bug in InCircle function fixed. Radius r := Sqrt(rsqr). // Check for duplicate points added when inserting new point. // For speed, all points pre-sorted in x direction using quicksort algorithm and // triangles flagged when no longer needed. The circumcircle centre and radius of // the triangles are now stored to improve calculation time. /// //////////////////////////////////////////////////////////////////////////// // You can use this code however you like providing the above credits remain in tact { ** Updated May 2003 - ARH code cleanups } unit cDelaunay; interface uses System.Types, Vcl.Dialogs, GLMesh, GLTexture, GLVectorGeometry, GLVectorTypes, GLColor; { ** unit constants - set as applicable } const MaxVertices = 500000; const MaxTriangles = 1000000; const ExPtTolerance = 0.000001; { ** points (vertices) } type dVertex = record x: Double; y: Double; z: Double; { ** added to save height of terrain } end; { ** reated Triangles, vv# are the vertex pointers } type dTriangle = record vv0: LongInt; vv1: LongInt; vv2: LongInt; precalc: Integer; xc, yc, r: Double; end; type TDVertex = array [0 .. MaxVertices] of dVertex; type PVertex = ^TDVertex; type TDTriangle = array [0 .. MaxTriangles] of dTriangle; type PTriangle = ^TDTriangle; type TDComplete = array [0 .. MaxTriangles] of Boolean; type PComplete = ^TDComplete; type TDEdges = array [0 .. 2, 0 .. MaxTriangles * 3] of LongInt; type PEdges = ^TDEdges; type TDelaunay = class private fHowMany: Integer; ftPoints: Integer; fGLMesh: TGLMesh; function InCircle(xp, yp, x1, y1, x2, y2, x3, y3: Double; var xc: Double; var yc: Double; var r: Double; j: Integer): Boolean; function Triangulate(nvert: Integer): Integer; function WhichSide(xp, yp, x1, y1, x2, y2: Double): Integer; public Triangle: PTriangle; Vertex: PVertex; constructor Create; destructor Destroy; procedure Mesh; procedure AddPoint(x, y, z: single); overload; procedure AddPoint(x, y: single); overload; procedure QuickSort(var A: PVertex; Low, High: Integer); procedure Draw; property HowMany: Integer read fHowMany write fHowMany; { ** Variable for total number of points (vertices) } property tPoints: Integer read ftPoints write ftPoints; property GLMesh: TGLMesh read fGLMesh write fGLMesh; end; implementation // ----- TDelaunay.InCircle ---------------------------------------------------- { ** return _TRUE_ if the point (xp,yp) lies inside the circumcircle made up by points (x1,y1) (x2,y2) (x3,y3). The circumcircle centre is returned in (xc,yc) and the radius r. Note: A point on the edge is inside the circumcircle } function TDelaunay.InCircle(xp, yp, x1, y1, x2, y2, x3, y3: Double; var xc: Double; var yc: Double; var r: Double; j: Integer): Boolean; const EPS = 1E-6; var m1, m2, mx1, mx2, my1, my2, dx, dy, rsqr, drsqr: Double; begin result := false; { ** check if xc,yc and r have already been calculated } if (Triangle^[j].precalc = 1) then begin xc := Triangle^[j].xc; yc := Triangle^[j].yc; r := Triangle^[j].r; rsqr := r * r; dx := xp - xc; dy := yp - yc; drsqr := dx * dx + dy * dy; end else begin if (abs(y1 - y2) < EPS) and (abs(y2 - y3) < EPS) then begin ShowMessage('InCircle - F - Points are coincident !'); exit; end; if (abs(y2 - y1) < EPS) then begin m2 := -(x3 - x2) / (y3 - y2); mx2 := 0.5 * (x2 + x3); my2 := 0.5 * (y2 + y3); xc := 0.5 * (x2 + x1); yc := m2 * (xc - mx2) + my2; end else if (abs(y3 - y2) < EPS) then begin m1 := -(x2 - x1) / (y2 - y1); mx1 := 0.5 * (x1 + x2); my1 := 0.5 * (y1 + y2); xc := 0.5 * (x3 + x2); yc := m1 * (xc - mx1) + my1; end else begin m1 := -(x2 - x1) / (y2 - y1); m2 := -(x3 - x2) / (y3 - y2); mx1 := 0.5 * (x1 + x2); mx2 := 0.5 * (x2 + x3); my1 := 0.5 * (y1 + y2); my2 := 0.5 * (y2 + y3); if ((m1 - m2) <> 0) then begin xc := (m1 * mx1 - m2 * mx2 + my2 - my1) / (m1 - m2); yc := m1 * (xc - mx1) + my1; end else begin xc := (x1 + x2 + x3) / 3; yc := (y1 + y2 + y3) / 3; end; end; dx := x2 - xc; dy := y2 - yc; rsqr := dx * dx + dy * dy; r := sqrt(rsqr); dx := xp - xc; dy := yp - yc; drsqr := dx * dx + dy * dy; { ** store the xc,yc and r for later use } Triangle^[j].precalc := 1; Triangle^[j].xc := xc; Triangle^[j].yc := yc; Triangle^[j].r := r; end; if (drsqr <= rsqr) then result := True; end; // ----- TDelaunay.Triangulate ------------------------------------------------- { ** takes as input NVERT vertices in arrays Vertex() Returned is a list of NTRI triangular faces in the raray Triangle(). These triangles are arranged in clockwise order } function TDelaunay.Triangulate(nvert: Integer): Integer; var complete: PComplete; edges: PEdges; nEdge: LongInt; { ** for super triangle } xmin, xmax, ymin, ymax, xmid, ymid, dx, dy, dmax, xc, yc, r: Double; { ** general variables } i, j, k, ntri: Integer; inc: Boolean; begin { ** allocate memory } GetMem(complete, sizeof(complete^)); GetMem(edges, sizeof(edges^)); { ** Find the maximum and minimum vertex bounds. This is to allow calculation of the bounding triangle } xmin := Vertex^[1].x; ymin := Vertex^[1].y; xmax := xmin; ymax := ymin; for i := 2 To nvert do begin if Vertex^[i].x < xmin then xmin := Vertex^[i].x; if Vertex^[i].x > xmax then xmax := Vertex^[i].x; if Vertex^[i].y < ymin then ymin := Vertex^[i].y; if Vertex^[i].y > ymax then ymax := Vertex^[i].y; end; dx := xmax - xmin; dy := ymax - ymin; if (dx > dy) then dmax := dx else dmax := dy; xmid := Trunc(0.5 * (xmax + xmin)); ymid := Trunc(0.5 * (ymax + ymin)); // Set up the supertriangle // This is a triangle which encompasses all the sample points. // The supertriangle coordinates are added to the end of the // vertex list. The supertriangle is the first triangle in // the triangle list. Vertex^[nvert + 1].x := (xmid - 2 * dmax); Vertex^[nvert + 1].y := (ymid - dmax); Vertex^[nvert + 2].x := xmid; Vertex^[nvert + 2].y := (ymid + 2 * dmax); Vertex^[nvert + 3].x := (xmid + 2 * dmax); Vertex^[nvert + 3].y := (ymid - dmax); Triangle^[1].vv0 := nvert + 1; Triangle^[1].vv1 := nvert + 2; Triangle^[1].vv2 := nvert + 3; Triangle^[1].precalc := 0; complete[1] := false; ntri := 1; // Include each point one at a time into the existing mesh For i := 1 To nvert do begin nEdge := 0; // Set up the edge buffer. // If the point (Vertex(i).x,Vertex(i).y) lies inside the circumcircle then the // three edges of that triangle are added to the edge buffer. j := 0; repeat j := j + 1; If complete^[j] <> True Then begin inc := InCircle(Vertex^[i].x, Vertex^[i].y, Vertex^[Triangle^[j].vv0].x, Vertex^[Triangle^[j].vv0].y, Vertex^[Triangle^[j].vv1].x, Vertex^[Triangle^[j].vv1].y, Vertex^[Triangle^[j].vv2].x, Vertex^[Triangle^[j].vv2].y, xc, yc, r, j); // Include this if points are sorted by X If (xc + r) < Vertex[i].x Then // complete[j] := True // Else // If inc Then begin edges^[1, nEdge + 1] := Triangle^[j].vv0; edges^[2, nEdge + 1] := Triangle^[j].vv1; edges^[1, nEdge + 2] := Triangle^[j].vv1; edges^[2, nEdge + 2] := Triangle^[j].vv2; edges^[1, nEdge + 3] := Triangle^[j].vv2; edges^[2, nEdge + 3] := Triangle^[j].vv0; nEdge := nEdge + 3; Triangle^[j].vv0 := Triangle^[ntri].vv0; Triangle^[j].vv1 := Triangle^[ntri].vv1; Triangle^[j].vv2 := Triangle^[ntri].vv2; Triangle^[j].precalc := Triangle^[ntri].precalc; Triangle^[j].xc := Triangle^[ntri].xc; Triangle^[j].yc := Triangle^[ntri].yc; Triangle^[j].r := Triangle^[ntri].r; Triangle^[ntri].precalc := 0; complete^[j] := complete^[ntri]; j := j - 1; ntri := ntri - 1; End; End; until j >= ntri; // Tag multiple edges // Note: if all triangles are specified anticlockwise then all // interior edges are opposite pointing in direction. For j := 1 To nEdge - 1 do begin If Not(edges^[1, j] = 0) And Not(edges^[2, j] = 0) Then begin For k := j + 1 To nEdge do begin If Not(edges^[1, k] = 0) And Not(edges^[2, k] = 0) Then begin If edges^[1, j] = edges^[2, k] Then begin If edges^[2, j] = edges^[1, k] Then begin edges^[1, j] := 0; edges^[2, j] := 0; edges^[1, k] := 0; edges^[2, k] := 0; End; End; End; end; End; end; // Form new triangles for the current point // Skipping over any tagged edges. // All edges are arranged in clockwise order. For j := 1 To nEdge do begin If Not(edges^[1, j] = 0) And Not(edges^[2, j] = 0) Then begin ntri := ntri + 1; Triangle^[ntri].vv0 := edges^[1, j]; Triangle^[ntri].vv1 := edges^[2, j]; Triangle^[ntri].vv2 := i; Triangle^[ntri].precalc := 0; complete^[ntri] := false; End; end; end; // Remove triangles with supertriangle vertices // These are triangles which have a vertex number greater than NVERT i := 0; repeat i := i + 1; If (Triangle^[i].vv0 > nvert) Or (Triangle^[i].vv1 > nvert) Or (Triangle^[i].vv2 > nvert) Then begin Triangle^[i].vv0 := Triangle^[ntri].vv0; Triangle^[i].vv1 := Triangle^[ntri].vv1; Triangle^[i].vv2 := Triangle^[ntri].vv2; i := i - 1; ntri := ntri - 1; End; until i >= ntri; Triangulate := ntri; // Free memory FreeMem(complete, sizeof(complete^)); FreeMem(edges, sizeof(edges^)); End; // ----- TDelaunay.Create ------------------------------------------------------ constructor TDelaunay.Create; begin { ** Initialise total points to 1, using base 0 causes problems in the functions } ftPoints := 1; fHowMany := 0; { ** allocate memory for the arrays } GetMem(Triangle, sizeof(Triangle^)); GetMem(Vertex, sizeof(Vertex^)); end; // ----- TDelaunay.Destroy ----------------------------------------------------- destructor TDelaunay.Destroy; begin { ** free memory for arrays } FreeMem(Triangle, sizeof(Triangle^)); FreeMem(Vertex, sizeof(Vertex^)); end; Function TDelaunay.WhichSide(xp, yp, x1, y1, x2, y2: Double): Integer; // Determines which side of a line the point (xp,yp) lies. // The line goes from (x1,y1) to (x2,y2) // Returns -1 for a point to the left // 0 for a point on the line // +1 for a point to the right var equation: Double; begin equation := ((yp - y1) * (x2 - x1)) - ((y2 - y1) * (xp - x1)); If equation > 0 Then WhichSide := -1 Else If equation = 0 Then WhichSide := 0 Else WhichSide := 1; End; procedure TDelaunay.Mesh; begin QuickSort(Vertex, 1, tPoints - 1); If tPoints > 3 Then HowMany := Triangulate(tPoints - 1); // 'Returns number of triangles created. end; procedure TDelaunay.AddPoint(x, y, z: single); var i, AE: Integer; begin // Check for duplicate points AE := 0; i := 1; while i < tPoints do begin If (abs(x - Vertex^[i].x) < ExPtTolerance) and (abs(y - Vertex^[i].y) < ExPtTolerance) Then AE := 1; inc(i); end; if AE = 0 then begin // Set Vertex coordinates where you clicked the pic box Vertex^[tPoints].x := x; Vertex^[tPoints].y := y; Vertex^[tPoints].z := z; // Increment the total number of points tPoints := tPoints + 1; end; end; procedure TDelaunay.AddPoint(x, y: single); var i, AE: Integer; begin // Check for duplicate points AE := 0; i := 1; while i < tPoints do begin If (abs(x - Vertex^[i].x) < ExPtTolerance) and (abs(y - Vertex^[i].y) < ExPtTolerance) Then AE := 1; inc(i); end; if AE = 0 then begin // Set Vertex coordinates where you clicked the pic box Vertex^[tPoints].x := x; Vertex^[tPoints].y := y; // Increment the total number of points tPoints := tPoints + 1; end; end; procedure TDelaunay.QuickSort(var A: PVertex; Low, High: Integer); // Sort all points by x procedure DoQuickSort(var A: PVertex; iLo, iHi: Integer); var Lo, Hi: Integer; Mid: Double; T: dVertex; begin Lo := iLo; Hi := iHi; Mid := A^[(Lo + Hi) div 2].x; repeat while A^[Lo].x < Mid do inc(Lo); while A^[Hi].x > Mid do Dec(Hi); if Lo <= Hi then begin T := A^[Lo]; A^[Lo] := A^[Hi]; A^[Hi] := T; inc(Lo); Dec(Hi); end; until Lo > Hi; if Hi > iLo then DoQuickSort(A, iLo, Hi); if Lo < iHi then DoQuickSort(A, Lo, iHi); end; begin DoQuickSort(A, Low, High); end; procedure TDelaunay.Draw; var // variable to hold how many triangles are created by the triangulate function i: Integer; p1, p2, p3: TAffineVector; begin GLMesh.Vertices.Clear; // Draw the created triangles if (HowMany > 0) then begin For i := 1 To HowMany do begin with GLMesh.Vertices do begin SetVector(p1, Vertex^[Triangle^[i].vv0].x, Vertex^[Triangle^[i].vv0].y, Vertex^[Triangle^[i].vv0].z); SetVector(p2, Vertex^[Triangle^[i].vv1].x, Vertex^[Triangle^[i].vv1].y, Vertex^[Triangle^[i].vv1].z); SetVector(p3, Vertex^[Triangle^[i].vv2].x, Vertex^[Triangle^[i].vv2].y, Vertex^[Triangle^[i].vv2].z); AddVertex(p3, NullVector, clrGray); AddVertex(p2, NullVector, clrGray); AddVertex(p1, NullVector, clrGray); end; end; end; end; // ============================================================================= end.
unit uMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uGame, uGameScreen, uGameScreen.MainMenu, uGameScreen.Credits, uGameScreen.NewGame, uGameScreen.MainGame, uGameScreen.InGameMenu, uGameScreen.AlphaVersion, uDebugInfo; type TfrmMain = class(TForm) procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormFocus(var Msg : TMessage); message WM_ACTIVATE; end; var frmMain: TfrmMain; Game: TdfGame; //Game screens MainMenu: TdfMainMenu; Credits: TdfCredits; NewGame: TdfNewGame; MainGame: TdfMainGame; InGameMenu: TdfInGameMenu; Alpha: TdfAlphaVersion; implementation {$R *.dfm} procedure TfrmMain.FormClose(Sender: TObject; var Action: TCloseAction); begin Game.Stop(); Game.Free; end; procedure TfrmMain.FormCreate(Sender: TObject); begin //Создаем объект игры Game := TdfGame.Create(Self); //Создаем игровые экраны MainMenu := TdfMainMenu(Game.AddGameScene(TdfMainMenu)); Credits := TdfCredits(Game.AddGameScene(TdfCredits)); NewGame := TdfNewGame(Game.AddGameScene(TdfNewGame)); MainGame := TdfMainGame(Game.AddGameScene(TdfMainGame)); InGameMenu := TdfInGameMenu(Game.AddGameScene(TdfInGameMenu)); Alpha := TdfAlphaVersion(Game.AddGameScene(TdfAlphaVersion)); //Строим еобходимые для них ассоциации MainMenu.SetGameScreens(NewGame, Credits); Credits.SetGameScreens(MainMenu); NewGame.SetGameScreens(MainGame); MainGame.SetGameScreens(InGameMenu, Alpha); InGameMenu.SetGameScreens(MainGame, MainMenu); Alpha.SetGameScreens(MainGame, MainMenu); Game.ActiveScreen := MainMenu; // Game.ActiveScene := MainGame; // Game.ActiveScreen := NewGame; //!!! Game.Start; end; procedure TfrmMain.FormFocus(var Msg: TMessage); begin if (Msg.WParam = WA_INACTIVE) and (Game.ActiveScreen = MainGame) then Game.NotifyGameScenes(InGameMenu, naShowModal); inherited; end; end.
unit UDParagraphs; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, UCrpe32; type TCrpeParagraphsDlg = class(TForm) pnlParagraphs: TPanel; lblNames: TLabel; lblFieldName: TLabel; lblTextStart: TLabel; lblCount: TLabel; lblTextEnd: TLabel; lbNumbers: TListBox; editTextStart: TEdit; editCount: TEdit; editTextEnd: TEdit; btnOk: TButton; btnClear: TButton; cbAlignment: TComboBox; gbIndent: TGroupBox; editFirstLine: TEdit; lblFirstLine: TLabel; lblLeft: TLabel; editLeft: TEdit; lblRight: TLabel; editRight: TEdit; rgUnits: TRadioGroup; btnTabStops: TButton; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure lbNumbersClick(Sender: TObject); procedure cbAlignmentChange(Sender: TObject); procedure editIndentEnter(Sender: TObject); procedure editIndentExit(Sender: TObject); procedure rgUnitsClick(Sender: TObject); procedure btnTabStopsClick(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure btnClearClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure InitializeControls(OnOff: boolean); procedure UpdateParagraphs; private { Private declarations } public { Public declarations } Crp : TCrpeParagraphs; PIndex : integer; PrevSize : string; end; var CrpeParagraphsDlg: TCrpeParagraphsDlg; bParagraphs : boolean; implementation {$R *.DFM} uses UCrpeUtl, UDTabStops, UCrpeClasses; {------------------------------------------------------------------------------} { FormCreate } {------------------------------------------------------------------------------} procedure TCrpeParagraphsDlg.FormCreate(Sender: TObject); begin bParagraphs := True; LoadFormPos(Self); btnOk.Tag := 1; PIndex := -1; end; {------------------------------------------------------------------------------} { FormShow } {------------------------------------------------------------------------------} procedure TCrpeParagraphsDlg.FormShow(Sender: TObject); begin UpdateParagraphs; end; {------------------------------------------------------------------------------} { UpdateParagraphs } {------------------------------------------------------------------------------} procedure TCrpeParagraphsDlg.UpdateParagraphs; var OnOff : boolean; i : integer; begin PIndex := -1; {Enable/Disable controls} if IsStrEmpty(Crp.Cr.ReportName) then OnOff := False else begin OnOff := (Crp.Count > 0); {Get Paragraphs Index} if OnOff then begin if Crp.ItemIndex > -1 then PIndex := Crp.ItemIndex else PIndex := 0; end; end; InitializeControls(OnOff); {Update list box} if OnOff then begin {Fill Numbers ListBox} for i := 0 to Crp.Count - 1 do lbNumbers.Items.Add(IntToStr(i)); editCount.Text := IntToStr(Crp.Count); lbNumbers.ItemIndex := PIndex; lbNumbersClick(Self); end; end; {------------------------------------------------------------------------------} { InitializeControls } {------------------------------------------------------------------------------} procedure TCrpeParagraphsDlg.InitializeControls(OnOff: boolean); var i : integer; begin {Enable/Disable the Form Controls} for i := 0 to ComponentCount - 1 do begin if TComponent(Components[i]).Tag = 0 then begin if Components[i] is TButton then TButton(Components[i]).Enabled := OnOff; if Components[i] is TRadioGroup then TRadioGroup(Components[i]).Enabled := OnOff; if Components[i] is TComboBox then begin TComboBox(Components[i]).Color := ColorState(OnOff); TComboBox(Components[i]).Enabled := OnOff; end; if Components[i] is TListBox then begin TListBox(Components[i]).Clear; TListBox(Components[i]).Color := ColorState(OnOff); TListBox(Components[i]).Enabled := OnOff; end; if Components[i] is TEdit then begin TEdit(Components[i]).Text := ''; if TEdit(Components[i]).ReadOnly = False then TEdit(Components[i]).Color := ColorState(OnOff); TEdit(Components[i]).Enabled := OnOff; end; end; end; end; {------------------------------------------------------------------------------} { lbNumbersClick } {------------------------------------------------------------------------------} procedure TCrpeParagraphsDlg.lbNumbersClick(Sender: TObject); begin PIndex := lbNumbers.ItemIndex; cbAlignment.ItemIndex := Ord(Crp[PIndex].Alignment); editTextStart.Text := IntToStr(Crp.Item.TextStart); editTextEnd.Text := IntToStr(Crp.Item.TextEnd); rgUnitsClick(Self); end; {------------------------------------------------------------------------------} { cbAlignmentChange } {------------------------------------------------------------------------------} procedure TCrpeParagraphsDlg.cbAlignmentChange(Sender: TObject); begin Crp.Item.Alignment := TCrHorizontalAlignment(cbAlignment.ItemIndex); end; {------------------------------------------------------------------------------} { editIndentEnter } {------------------------------------------------------------------------------} procedure TCrpeParagraphsDlg.editIndentEnter(Sender: TObject); begin PrevSize := TEdit(Sender).Text; end; {------------------------------------------------------------------------------} { editIndentExit } {------------------------------------------------------------------------------} procedure TCrpeParagraphsDlg.editIndentExit(Sender: TObject); begin if rgUnits.ItemIndex = 0 then {inches} begin if not IsFloating(TEdit(Sender).Text) then TEdit(Sender).Text := PrevSize else begin if TEdit(Sender).Name = 'editFirstLine' then Crp.Item.IndentFirstLine := InchesStrToTwips(TEdit(Sender).Text); if TEdit(Sender).Name = 'editLeft' then Crp.Item.IndentLeft := InchesStrToTwips(TEdit(Sender).Text); if TEdit(Sender).Name = 'editRight' then Crp.Item.IndentRight := InchesStrToTwips(TEdit(Sender).Text); UpdateParagraphs; {this will truncate any decimals beyond 3 places} end; end else {twips} begin if not IsNumeric(TEdit(Sender).Text) then TEdit(Sender).Text := PrevSize else begin if TEdit(Sender).Name = 'editFirstLine' then Crp.Item.IndentFirstLine := StrToInt(TEdit(Sender).Text); if TEdit(Sender).Name = 'editLeft' then Crp.Item.IndentLeft := StrToInt(TEdit(Sender).Text); if TEdit(Sender).Name = 'editRight' then Crp.Item.IndentRight := StrToInt(TEdit(Sender).Text); end; end; end; {------------------------------------------------------------------------------} { rgUnitsClick } {------------------------------------------------------------------------------} procedure TCrpeParagraphsDlg.rgUnitsClick(Sender: TObject); begin if rgUnits.ItemIndex = 0 then {inches} begin editFirstLine.Text := TwipsToInchesStr(Crp.Item.IndentFirstLine); editLeft.Text := TwipsToInchesStr(Crp.Item.IndentLeft); editRight.Text := TwipsToInchesStr(Crp.Item.IndentRight); end else {twips} begin editFirstLine.Text := IntToStr(Crp.Item.IndentFirstLine); editLeft.Text := IntToStr(Crp.Item.IndentLeft); editRight.Text := IntToStr(Crp.Item.IndentRight); end; end; {------------------------------------------------------------------------------} { btnTabStopsClick } {------------------------------------------------------------------------------} procedure TCrpeParagraphsDlg.btnTabStopsClick(Sender: TObject); begin CrpeTabStopsDlg := TCrpeTabStopsDlg.Create(Application); CrpeTabStopsDlg.Crt := Crp.Item.TabStops; CrpeTabStopsDlg.ShowModal; end; {------------------------------------------------------------------------------} { btnOkClick } {------------------------------------------------------------------------------} procedure TCrpeParagraphsDlg.btnOkClick(Sender: TObject); begin SaveFormPos(Self); Close; end; {------------------------------------------------------------------------------} { btnClearClick } {------------------------------------------------------------------------------} procedure TCrpeParagraphsDlg.btnClearClick(Sender: TObject); begin Crp.Clear; UpdateParagraphs; end; {------------------------------------------------------------------------------} { FormClose } {------------------------------------------------------------------------------} procedure TCrpeParagraphsDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin bParagraphs := False; Release; end; end.
(* BigInts: F.Li, 1998-11-22 ------- HDO, 2000-11-13 Artihmetic for arbitrary size integers which are represented as singly-linked lists. ==================================================================*) PROGRAM BigInts; (*$IFDEF WINDOWS, for Borland Pascal only*) USES WinCrt, Math; (*$ENDIF*) (*$DEFINE SIGNED*) (*when defined: first digit is sign +1 or -1*) CONST base = 1000; (*base of number system used in all*) (* calculations, big digits: 0 .. base - 1*) TYPE NodePtr = ^Node; Node = RECORD next: NodePtr; val: INTEGER; END; (*RECORD*) BigIntPtr = NodePtr; FUNCTION NewNode(val: INTEGER): NodePtr; VAR n: NodePtr; BEGIN New(n); (*IF n == NIL THEN ...*) n^.next := NIL; n^.val := val; NewNode := n; END; (*NewNode*) FUNCTION Zero: BigIntPtr; BEGIN Zero := NewNode(0); END; (*Zero*) PROCEDURE Append(VAR bi: BigIntPtr; val: INTEGER); VAR n, last: NodePtr; BEGIN n := NewNode(val); IF bi = NIL THEN bi := n ELSE BEGIN (*l <>NIL*) last := bi; WHILE last^.next <> NIL DO BEGIN last := last^.next; END; (*WHILE*) last^.next := n; END; (*ELSE*) END; (*Append*) PROCEDURE Prepend(VAR bi: BigIntPtr; val: INTEGER); VAR n: NodePtr; BEGIN n := NewNode(val); n^.next := bi; bi := n; END; (*Prepend*) FUNCTION Sign(bi: BigIntPtr): INTEGER; BEGIN (*$IFDEF SIGNED*) (*assert: bi <> NIL*) Sign := bi^.val; (*results in +1 or -1*) (*$ELSE*) WriteLn('Error in Sign: no sign node available'); Halt; (*$ENDIF*) END; (*Sign*) FUNCTION CopyOfBigInt(bi: BigIntPtr): BigIntPtr; VAR n: NodePtr; cBi: BigIntPtr; (*cBi = copy of BigIntPtr*) BEGIN cBi := NIL; n := bi; WHILE n <> NIL DO BEGIN Append(cBi, n^.val); n := n^.next; END; (*WHILE*) CopyOfBigInt := cBi; END; (*CopyOfBigInt*) PROCEDURE InvertBigInt(VAR bi: BigIntPtr); VAR iBi, next: NodePtr; (*iBi = inverted BigIntPtr*) BEGIN IF bi <> NIL THEN BEGIN iBi := bi; bi := bi^.next; iBi^.next := NIL; WHILE bi <> NIL DO BEGIN next := bi^.next; bi^.next := iBi; iBi := bi; bi := next; END; (*WHILE*) bi := iBi; END; (*IF*) END; (*InvertBigInt*) PROCEDURE DisposeBigInt(VAR bi: BigIntPtr); VAR next: NodePtr; BEGIN WHILE bi <> NIL DO BEGIN next := bi^.next; Dispose(bi); bi := next; END; (*WHILE*) END; (*DisposeBigInt*) (* ReadBigInt: reads BigIntPtr, version for base = 1000 Input syntax: BigIntPtr = { digit }. BigIntPtr = [+ | -] digit { digit }. The empty string is treated as zero, and as the whole input is read into one STRING, max. length is 255. -------------------------------------------------------*) PROCEDURE ReadBigInt(VAR bi: BigIntPtr); VAR s: STRING; (*input string*) iBeg, iEnd: INTEGER; (*begin and end of proper input *) bigDig, decDig: INTEGER; nrOfBigDigits, lenOfFirst: INTEGER; sign, i, j: INTEGER; PROCEDURE WriteWarning(warnPos: INTEGER); BEGIN WriteLn('Warning in ReadBigInt: ', 'character ', s[warnPos], ' in column ', warnPos, ' is treated as zero'); END; (*WriteWarning*) BEGIN (*ReadBigInt*) IF base <> 1000 THEN BEGIN WriteLn('Error in ReadBigInt: ', 'procedure currently works for base = 1000 only'); Halt; END; (*IF*) ReadLn(s); iEnd := Length(s); IF iEnd = 0 THEN bi := Zero ELSE BEGIN (*$IFDEF SIGNED*) IF s[1] = '-' THEN BEGIN sign := -1; iBeg := 2; END (*THEN*) ELSE IF s[1] = '+' THEN BEGIN sign := 1; iBeg := 2; END (*THEN*) ELSE BEGIN (*$ENDIF*) sign := 1; iBeg := 1; (*$IFDEF SIGNED*) END; (*ELSE*) (*$ENDIF*) WHILE (iBeg <= iEnd) AND ((s[iBeg] < '1') OR (s[iBeg] > '9')) DO BEGIN IF (s[iBeg] <> '0') AND (s[iBeg] <> ' ') THEN WriteWarning(iBeg); iBeg := iBeg + 1; END; (*WHILE*) (*get value from s[iBeg .. iEnd]*) IF iBeg > iEnd THEN bi := Zero ELSE BEGIN bi := NIL; nrOfBigDigits := (iEnd - iBeg) DIV 3 + 1; lenOfFirst := (iEnd - iBeg) MOD 3 + 1; FOR i := 1 TO nrOfBigDigits DO BEGIN bigDig := 0; FOR j := iBeg TO iBeg + lenOfFirst - 1 DO BEGIN IF (s[j] >= '0') AND (s[j] <= '9') THEN decDig := Ord(s[j]) - Ord('0') ELSE BEGIN WriteWarning(j); decDig := 0; END; (*ELSE*) bigDig := bigDig * 10 + decDig; END; (*FOR*) Prepend(bi, bigDig); iBeg := iBeg + lenOfFirst; lenOfFirst := 3; END; (*FOR*) (*$IFDEF SIGNED*) Prepend(bi, sign); (*$ENDIF*) END; (*IF*) END; (*ELSE*) END; (*ReadBigInt*) (* WriteBigInt: writes BigIntPtr, version for base = 1000 -------------------------------------------------------*) PROCEDURE WriteBigInt(bi: BigIntPtr); VAR revBi: BigIntPtr; n: NodePtr; BEGIN IF base <> 1000 THEN BEGIN WriteLn('Error in WriteBigInt: ', 'procedure currently works for base = 1000 only'); Halt; END; (*IF*) IF bi = NIL THEN Write('0') ELSE BEGIN (*$IFDEF SIGNED*) IF Sign(bi) = -1 THEN Write('-'); revBi := CopyOfBigInt(bi^.next); (*$ELSE*) revBi := CopyOfBigInt(bi); (*$ENDIF*) InvertBigInt(revBi); n := revBi; Write(n^.val); (*first big digit printed without leading zeros*) n := n^.next; WHILE n <> NIL DO BEGIN IF n^.val >= 100 THEN Write(n^.val) ELSE IF n^.val >= 10 THEN Write('0', n^.val) ELSE (*n^.val < 10*) Write('00', n^.val); n := n^.next; END; (*WHILE*) DisposeBigInt(revBi); (*release the copy*) END; (*IF*) END; (*WriteBigInt*) FUNCTION ANZ_Nodes(a : BigIntPtr): INTEGER; VAR count : INTEGER; BEGIN count := 1; WHILE a^.next <> NIL DO BEGIN a := a^.next; count := count + 1; END; ANZ_Nodes := count; END; (* Returns 2,1,0 - 2,1 determines which is bigger 0 means they are equal*) FUNCTION HigherBigInt (a, b: BigIntPtr) : INTEGER; VAR temp_a, temp_b : BigIntPtr; BEGIN temp_a := CopyOfBigInt(a); temp_b := CopyOfBigInt(b); InvertBigInt(temp_a); InvertBigInt(temp_b); WHILE (temp_a^.val = temp_b^.val) AND (temp_a^.next <> NIL) AND (temp_b^.next <> NIL) DO BEGIN temp_a := temp_a^.next; temp_b := temp_b^.next; END; IF (temp_a^.next = NIL) AND (temp_b^.next = NIL) THEN HigherBigInt := 0 ELSE IF (temp_a^.next <> NIL) AND (temp_b^.next = NIL) THEN HigherBigInt := 1 ELSE IF (temp_a^.next = NIL) AND (temp_b^.next <> NIL) THEN HigherBigInt := 2 ELSE IF temp_a^.val > temp_b^.val THEN HigherBigInt := 1 ELSE HigherBigInt := 2; END; FUNCTION Sum (a, b: BigIntPtr) : BigIntPtr; (*compute sum = a + b*) VAR result : BigIntPtr; VAR sign_a, sign_b, overflow, temp, anz_a, anz_b, ishigher : Integer; BEGIN IF a^.val = 0 THEN result := CopyOfBigInt(b); IF b^.val = 0 THEN result := CopyOfBigInt(a) ELSE BEGIN result := NIL; overflow := 0; ishigher := 0; sign_a := Sign(a); sign_b := Sign(b); anz_a := ANZ_Nodes(a); anz_b := ANZ_Nodes(b); IF anz_a > anz_b THEN ishigher := 1 ELSE IF anz_b > anz_a THEN ishigher := 2 ELSE ishigher := HigherBigInt(a,b); (* Set the sign of the result *) IF ((sign_a = 1) OR (sign_a = 0)) AND ((sign_b = 1) OR (sign_a = 0)) THEN Append(result,1) ELSE IF (sign_a = -1) AND (sign_b = -1) THEN Append(result,-1) ELSE IF (sign_a = -1) AND (sign_b = 1) THEN IF ishigher = 1 THEN Append(result,-1) ELSE Append(result,1) ELSE IF ishigher = 1 THEN Append(result,1) ELSE Append(result,-1); IF (ishigher = 0) AND (sign_a <> sign_b) THEN BEGIN result^.val := 1; Append(result,0); END ELSE BEGIN REPEAT IF a^.next <> NIL THEN a := a^.next ELSE a^.val := 0; IF b^.next <> NIL THEN b := b^.next ELSE b^.val := 0; IF ((sign_a = 1) AND (sign_b = 1)) OR ((sign_a = -1) AND (sign_b = -1)) THEN BEGIN temp := a^.val + b^.val + overflow; overflow := 0; END ELSE BEGIN IF ishigher = 1 THEN BEGIN IF a^.val >= b^.val THEN BEGIN temp := a^.val - b^.val + overflow; overflow := 0; END ELSE BEGIN temp := (1000 + a^.val) - b^.val + overflow; overflow := -1; END; END ELSE BEGIN IF b^.val >= a^.val THEN BEGIN temp := b^.val - a^.val + overflow; overflow := 0; END ELSE BEGIN temp := (1000 + b^.val) - a^.val + overflow; overflow := -1; END; END; END; IF temp >= 1000 THEN BEGIN overflow := 1; temp := temp - 1000; END ELSE IF temp < 0 then BEGIN temp := 1000 + temp; overflow := - 1; END; IF (temp = 0) AND ((a^.next = NIL) AND (b^.next = NIL)) THEN ELSE Append(result,temp); UNTIL ((a^.val = 0) AND (b^.val = 0)) AND ((a^.next = NIL) AND (b^.next = NIL)); END; END; Sum := result; END; (* Product of two Big Ints *) FUNCTION Product(a, b: BigIntPtr): BigIntPtr; (*compute product = a * b*) VAR result : BigIntPtr; sum_a,sum_b,sum_ab : int64; i : INTEGER; BEGIN IF (a^.val = 0) OR (b^.val = 0) THEN BEGIN result := NewNode(1); Append(result, 0); END ELSE IF Sign(a) <> Sign(b) THEN result := NewNode(-1) ELSE result := NewNode(1); i := 0; sum_a := 0; sum_b := 0; a := a^.next; b := b^.next; WHILE a <> NIL DO BEGIN sum_a := sum_a + (a^.val * (base ** i)); a := a^.next; i := i + 1; END; i:=0; WHILE b <> NIL DO BEGIN sum_b := sum_b + (b^.val * (base ** i)); b := b^.next; i := i + 1; END; sum_ab := sum_a * sum_b; WHILE sum_ab <> 0 DO BEGIN Append(result, (sum_ab MOD base)); sum_ab := sum_ab DIV base; END; Product := result; END; (*=== main program, for test purposes ===*) VAR bi : BigIntPtr; bi2: BigIntPtr; bi_temp : BigIntPtr; bi2_temp : BigIntPtr; sumbi : BigIntPtr; probi : BigIntPtr; BEGIN (*BigInts*) WriteLn(chr(205),chr(205),chr(185),' BigInt ',chr(204),chr(205),chr(205)); (*tests for ReadBigInt and WriteBigInt only*) Write('big int > '); ReadBigInt(bi); Write('big int > '); ReadBigInt(bi2); bi_temp := CopyOfBigInt(bi);; bi2_temp := CopyOfBigInt(bi2);; WriteLN; Write('Sum : '); sumbi := Sum(bi,bi2); WriteBigInt(sumbi); WriteLN; Write('Product : '); probi := Product(bi_temp, bi2_temp); WriteBigInt(probi); END. (*BigInts*)
unit ModflowCfpWriterUnit; interface uses CustomModflowWriterUnit, ModflowPackageSelectionUnit, Generics.Collections, PhastModelUnit, ScreenObjectUnit, DataSetUnit, GoPhastTypes, SysUtils, Classes, ModflowBoundaryDisplayUnit; type TCfpPipe = class; TCfpNode = class(TObject) private FNumber: Integer; FIsFixed: Boolean; FFixedHead: double; FPipes: TList<TCfpPipe>; FExchange: Double; FLayer: integer; FRow: Integer; FColumn: Integer; FElevation: double; FRechargeFraction: array of double; FRechargeFractionUsed: array of boolean; FRechargeFractionAnnotation: array of string; FRecordData: Boolean; constructor Create; public destructor Destroy; override; end; TCfpPipe = class(TObject) private FNode1: TCfpNode; FNode2: TCfpNode; FNumber: Integer; FDiameter: double; FTortuosity: double; FRoughnessHeight: Double; FLowerR: Double; FHigherR: Double; FRecordData: Boolean; function SameNodes(Node1, Node2: TCfpNode): boolean; function OtherNode(ANode: TCfpNode): TCfpNode; end; TModflowCfpWriter = class(TCustomPackageWriter) private FPipes: TObjectList<TCfpPipe>; FNodes: TObjectList<TCfpNode>; FNodeGrid: array of array of array of TCfpNode; FLayerCount: Integer; FRowCount: Integer; FColumnCount: Integer; FConduitFlowProcess: TConduitFlowProcess; // After @link(EvaluateConduitRecharge) is called, // @name contains a series of @link(TValueCellList)s; // one for each stress period. // Each such list contains series of @link(TValueCell)s. Each // @link(TValueCell) defines one boundary cell for one stress period. // @name is a TObjectList. FValues: TList; FCrchUsed: Boolean; FUseCOC: Boolean; FShouldWriteCRCH: Boolean; FShouldWriteCOC: Boolean; NameOfFile: string; procedure Evaluate; procedure EvaluateConduitRecharge; procedure WriteDataSet0; procedure WriteDataSet1; procedure WriteDataSets2and3; procedure WriteDataSet4; procedure WriteDataSet5; procedure WriteDataSet6; procedure WriteDataSet7; procedure WriteDataSet8; procedure WriteDataSets9to11; procedure WriteDataSet12; procedure WriteDataSet13; procedure WriteDataSet14; procedure WriteDataSet15; procedure WriteDataSet16; procedure WriteDataSet17; procedure WriteDataSet18; procedure WriteDataSet19; procedure WriteDataSet20; procedure WriteDataSet21; procedure WriteDataSet22; procedure WriteDataSets23to24; procedure WriteDataSet25; procedure WriteDataSet26; procedure WriteDataSet27; procedure WriteDataSet28; procedure WriteDataSet29; procedure WriteDataSets30to31; procedure WriteDataSet32; procedure WriteDataSet33; procedure WriteDataSet34; procedure WriteDataSet35; procedure WriteDataSet36; procedure WriteDataSet37; procedure WriteDataSets38to39; procedure WriteCrchFile(NameOfFile: string); procedure WriteCocFile(NameOfFile: string); procedure ClearTimeLists(AModel: TBaseModel); protected function Package: TModflowPackageSelection; override; class function Extension: string; override; public Constructor Create(Model: TCustomModel; EvaluationType: TEvaluationType); override; Destructor Destroy; override; procedure WriteFile(const AFileName: string); procedure UpdateDisplay(TimeLists: TModflowBoundListOfTimeLists); end; implementation uses ModflowGridUnit, ModflowCfpPipeUnit, Forms, frmProgressUnit, frmErrorsAndWarningsUnit, Math, ModflowCfpFixedUnit, LayerStructureUnit, ModflowCfpRechargeUnit, Contnrs, ModflowCellUnit, ModflowUnitNumbers, AbstractGridUnit; resourcestring StrTooManyConduitsAt = 'Too many conduits at a node. The following cells h' + 'ave more than the maximum allowed 6 conduits. (Layer, Row, Column)'; Str0d1d2d = '%0:d, %1:d, %2:d'; StrTheFollowingObject = 'The following objects define both conduits and fi' + 'xed heads in conduits. Thus, every node in the conduit will be a fixed he' + 'ad node. If that is not what you want, use a separate object to define th' + 'e CFP fixed head nodes.'; StrConduitRechargeNot = 'Conduit Recharge not defined.'; StrConduitRechargeWas = 'Conduit Recharge was selected but no conduit rec' + 'harge boundaries were defined.'; StrCFPDiameterIsNot = 'CFP Diameter is not assigned in the following object' + 's.'; StrCFPTortuosityIsNo = 'CFP Tortuosity is not assigned in the following obj' + 'ects.'; StrCFPRoughnessHeight = 'CFP Roughness Height is not assigned in the follow' + 'ing objects.'; StrCFPLowerCriticalR = 'CFP Lower Critical Reynolds number is not assigned' + ' in the following objects.'; StrCFPUpperCriticalR = 'CFP Upper Critical Reynolds number is not assigned' + ' in the following objects.'; StrCFPPipeElevationI = 'CFP pipe elevation is not assigned at the following' + ' cells.'; StrCFPNodeElevationHigh = 'CFP node elevation is too high.'; StrNodeNumber0d = 'Node number: %0:d; (Layer, Row, Column) = (%1:d, %2:d, ' + '%3:d)'; StrCFPNodeElevationLow = 'CFP node elevation is too low.'; StrTheConduitFlowPro = 'The Conduit Flow Process is not supported by MT3DM' + 'S.'; StrMT3DMSVersion53D = 'MT3DMS version 5.3 does not suppport the Conduit Fl' + 'ow Process.'; { TModflowCfpWriter } procedure TModflowCfpWriter.ClearTimeLists(AModel: TBaseModel); var ScreenObjectIndex: Integer; ScreenObject: TScreenObject; Boundary: TCfpRchFractionBoundary; // Boundary: TModflowBoundary; begin for ScreenObjectIndex := 0 to Model.ScreenObjectCount - 1 do begin ScreenObject := Model.ScreenObjects[ScreenObjectIndex]; if ScreenObject.Deleted then begin Continue; end; if not ScreenObject.UsedModels.UsesModel(Model) then begin Continue; end; Boundary := ScreenObject.ModflowCfpRchFraction; if Boundary <> nil then begin Boundary.ClearTimeLists(AModel); end; end; end; constructor TModflowCfpWriter.Create(Model: TCustomModel; EvaluationType: TEvaluationType); var Grid: TModflowGrid; begin inherited; FConduitFlowProcess := Model.ModflowPackages.ConduitFlowProcess; FPipes := TObjectList<TCfpPipe>.Create; FNodes := TObjectList<TCfpNode>.Create; Grid := Model.ModflowGrid; FLayerCount := Grid.LayerCount; FRowCount := Grid.RowCount; FColumnCount := Grid.ColumnCount; SetLength(FNodeGrid, FLayerCount, FRowCount, FColumnCount); FValues := TObjectList.Create; end; destructor TModflowCfpWriter.Destroy; begin FValues.Free; FPipes.Free; FNodes.Free; inherited; end; type TRealSparseDataSetCrack = class(TRealSparseDataSet); procedure TModflowCfpWriter.Evaluate; var ScreenObjectIndex: Integer; AScreenObject: TScreenObject; PipeBoundary: TCfpPipeBoundary; Diameter: TDataArray; PipeDiameter: double; Node1: TCfpNode; Node2: TCfpNode; NodeCreated: Boolean; PipeIndex: Integer; APipe: TCfpPipe; Pipe: TCfpPipe; Tortuosity: TDataArray; RoughnessHeight: TDataArray; LowerCriticalR: TDataArray; UpperCriticalR: TDataArray; PipeConducOrPerm: TDataArray; PipeElevation: TDataArray; TortuosityValue: double; RoughnessHeightValue: double; LowerCriticalRValue: double; UpperCriticalRValue: double; NodeIndex: Integer; ANode: TCfpNode; FixedHeadsArray: TDataArray; FixedHeads: TCfpFixedBoundary; CellList: TCellAssignmentList; OtherData: TObject; CellIndex: Integer; ACell1: TCellAssignment; ACell2: TCellAssignment; LocalGrid: TCustomModelGrid; begin frmErrorsAndWarnings.RemoveErrorGroup(Model, StrTooManyConduitsAt); frmErrorsAndWarnings.RemoveErrorGroup(Model, StrCFPDiameterIsNot); frmErrorsAndWarnings.RemoveErrorGroup(Model, StrCFPTortuosityIsNo); frmErrorsAndWarnings.RemoveErrorGroup(Model, StrCFPRoughnessHeight); frmErrorsAndWarnings.RemoveErrorGroup(Model, StrCFPLowerCriticalR); frmErrorsAndWarnings.RemoveErrorGroup(Model, StrCFPUpperCriticalR); frmErrorsAndWarnings.RemoveErrorGroup(Model, StrCFPNodeElevationHigh); frmErrorsAndWarnings.RemoveErrorGroup(Model, StrCFPNodeElevationLow); frmErrorsAndWarnings.RemoveErrorGroup(Model, StrCFPPipeElevationI); frmErrorsAndWarnings.RemoveWarningGroup(Model, StrTheFollowingObject); frmErrorsAndWarnings.RemoveWarningGroup(Model, StrTheConduitFlowPro); if Model.ModflowPackages.Mt3dBasic.IsSelected then begin frmErrorsAndWarnings.AddWarning(Model, StrTheConduitFlowPro, StrMT3DMSVersion53D); end; FUseCOC := False; if FConduitFlowProcess.PipesUsed then begin OtherData := nil; CellList := TCellAssignmentList.Create; try Diameter := Model.DataArrayManager.GetDataSetByName(KPipeDiameter); Tortuosity := Model.DataArrayManager.GetDataSetByName(KTortuosity); RoughnessHeight := Model.DataArrayManager.GetDataSetByName(KRoughnessHeight); LowerCriticalR := Model.DataArrayManager.GetDataSetByName(KLowerCriticalR); UpperCriticalR := Model.DataArrayManager.GetDataSetByName(KUpperCriticalR); PipeConducOrPerm := Model.DataArrayManager.GetDataSetByName(KPipeConductanceOrPer); PipeElevation := Model.DataArrayManager.GetDataSetByName(KCfpNodeElevation); Assert(Diameter <> nil); Assert(Tortuosity <> nil); Assert(RoughnessHeight <> nil); Assert(LowerCriticalR <> nil); Assert(UpperCriticalR <> nil); Assert(PipeConducOrPerm <> nil); Assert(PipeElevation <> nil); TRealSparseDataSetCrack(PipeConducOrPerm).Clear; TRealSparseDataSetCrack(PipeElevation).Clear; // TRealSparseDataSetCrack(FixedHeadsArray).Clear; for ScreenObjectIndex := 0 to Model.ScreenObjectCount - 1 do begin AScreenObject := Model.ScreenObjects[ScreenObjectIndex]; if AScreenObject.Deleted or not (AScreenObject.Count > 1) or (AScreenObject.ElevationCount <> ecOne) or not AScreenObject.UsedModels.UsesModel(Model) then begin Continue; end; PipeBoundary := AScreenObject.ModflowCfpPipes; if (PipeBoundary <> nil) and PipeBoundary.Used then begin FixedHeads := AScreenObject.ModflowCfpFixedHeads; if (FixedHeads <> nil) and FixedHeads.Used then begin frmErrorsAndWarnings.AddWarning(Model, StrTheFollowingObject, AScreenObject.Name, AScreenObject); end; TRealSparseDataSetCrack(Diameter).Clear; TRealSparseDataSetCrack(Tortuosity).Clear; TRealSparseDataSetCrack(RoughnessHeight).Clear; TRealSparseDataSetCrack(LowerCriticalR).Clear; TRealSparseDataSetCrack(UpperCriticalR).Clear; // don't clear PipeConducOrPerm or PipeElevation because // they are a cell properties not a pipe properties. AScreenObject.AssignValuesToDataSet(Diameter, Model, lctIgnore); AScreenObject.AssignValuesToDataSet(Tortuosity, Model, lctIgnore); AScreenObject.AssignValuesToDataSet(RoughnessHeight, Model, lctIgnore); AScreenObject.AssignValuesToDataSet(LowerCriticalR, Model, lctIgnore); AScreenObject.AssignValuesToDataSet(UpperCriticalR, Model, lctIgnore); AScreenObject.AssignValuesToDataSet(PipeConducOrPerm, Model, lctIgnore); if FConduitFlowProcess.CfpElevationChoice = cecIndividual then begin AScreenObject.AssignValuesToDataSet(PipeElevation, Model, lctIgnore); end; CellList.Clear; // Segments := AScreenObject.Segments[Model]; AScreenObject.GetCellsToAssign(Model.ModflowGrid, '0', OtherData, Diameter, CellList, alAll, Model); if CellList.Count > 1 then begin for CellIndex := 1 to CellList.Count - 1 do begin ACell1 := CellList[CellIndex-1]; ACell2 := CellList[CellIndex]; if ((ACell1.Column <> ACell2.Column) or (ACell1.Row <> ACell2.Row) or (ACell1.Layer <> ACell2.Layer)) and ((Abs(ACell1.Column - ACell2.Column) <= 1) and (Abs(ACell1.Row - ACell2.Row) <= 1) and (Abs(ACell1.Layer - ACell2.Layer) <= 1)) then begin if not Diameter.IsValue[ACell1.Layer, ACell1.Row, ACell1.Column] or not Diameter.IsValue[ACell2.Layer, ACell2.Row, ACell2.Column] then begin frmErrorsAndWarnings.AddError(Model, StrCFPDiameterIsNot, AScreenObject.Name, AScreenObject); Break; end; PipeDiameter := (Diameter.RealData[ACell1.Layer, ACell1.Row, ACell1.Column] + Diameter.RealData[ACell2.Layer, ACell2.Row, ACell2.Column])/2; if not Tortuosity.IsValue[ACell1.Layer, ACell1.Row, ACell1.Column] or not Tortuosity.IsValue[ACell2.Layer, ACell2.Row, ACell2.Column] then begin frmErrorsAndWarnings.AddError(Model, StrCFPTortuosityIsNo, AScreenObject.Name, AScreenObject); Break; end; TortuosityValue := (Tortuosity.RealData[ACell1.Layer, ACell1.Row, ACell1.Column] + Tortuosity.RealData[ACell2.Layer, ACell2.Row, ACell2.Column])/2; if not RoughnessHeight.IsValue[ACell1.Layer, ACell1.Row, ACell1.Column] or not RoughnessHeight.IsValue[ACell2.Layer, ACell2.Row, ACell2.Column] then begin frmErrorsAndWarnings.AddError(Model, StrCFPRoughnessHeight, AScreenObject.Name, AScreenObject); Break; end; RoughnessHeightValue := (RoughnessHeight.RealData[ACell1.Layer, ACell1.Row, ACell1.Column] + RoughnessHeight.RealData[ACell2.Layer, ACell2.Row, ACell2.Column])/2; if not LowerCriticalR.IsValue[ACell1.Layer, ACell1.Row, ACell1.Column] or not LowerCriticalR.IsValue[ACell2.Layer, ACell2.Row, ACell2.Column] then begin frmErrorsAndWarnings.AddError(Model, StrCFPLowerCriticalR, AScreenObject.Name, AScreenObject); Break; end; LowerCriticalRValue := (LowerCriticalR.RealData[ACell1.Layer, ACell1.Row, ACell1.Column] + LowerCriticalR.RealData[ACell2.Layer, ACell2.Row, ACell2.Column])/2; if not UpperCriticalR.IsValue[ACell1.Layer, ACell1.Row, ACell1.Column] or not UpperCriticalR.IsValue[ACell2.Layer, ACell2.Row, ACell2.Column] then begin frmErrorsAndWarnings.AddError(Model, StrCFPUpperCriticalR, AScreenObject.Name, AScreenObject); Break; end; UpperCriticalRValue := (UpperCriticalR.RealData[ACell1.Layer, ACell1.Row, ACell1.Column] + UpperCriticalR.RealData[ACell2.Layer, ACell2.Row, ACell2.Column])/2; Node1 := FNodeGrid[ACell1.Layer, ACell1.Row, ACell1.Column]; Node2 := FNodeGrid[ACell2.Layer, ACell2.Row, ACell2.Column]; NodeCreated := (Node1 = nil) or (Node2 = nil); if Node1 = nil then begin Node1 := TCfpNode.Create; FNodes.Add(Node1); Node1.FNumber := FNodes.Count; FNodeGrid[ACell1.Layer, ACell1.Row, ACell1.Column] := Node1; Node1.FLayer := ACell1.Layer; Node1.FRow := ACell1.Row; Node1.FColumn := ACell1.Column; end; Node1.FRecordData := PipeBoundary.RecordNodeValues or Node1.FRecordData; if Node2 = nil then begin Node2 := TCfpNode.Create; FNodes.Add(Node2); Node2.FNumber := FNodes.Count; FNodeGrid[ACell2.Layer, ACell2.Row, ACell2.Column] := Node2; Node2.FLayer := ACell2.Layer; Node2.FRow := ACell2.Row; Node2.FColumn := ACell2.Column; end; Node2.FRecordData := PipeBoundary.RecordNodeValues or Node2.FRecordData; Pipe := nil; if not NodeCreated then begin for PipeIndex := 0 to Node1.FPipes.Count - 1 do begin APipe := Node1.FPipes[PipeIndex]; if APipe.SameNodes(Node1, Node2) then begin Pipe := APipe; break; end; end; end; if Pipe = nil then begin Pipe := TCfpPipe.Create; FPipes.Add(Pipe); Pipe.FNumber := FPipes.Count; Pipe.FNode1 := Node1; Pipe.FNode2 := Node2; Node1.FPipes.Add(Pipe); Node2.FPipes.Add(Pipe); end; Pipe.FDiameter := PipeDiameter; Pipe.FTortuosity := TortuosityValue; Pipe.FRoughnessHeight := RoughnessHeightValue; Pipe.FLowerR := LowerCriticalRValue; Pipe.FHigherR := UpperCriticalRValue; Pipe.FRecordData := PipeBoundary.RecordPipeValues; end; end; end; end; end; LocalGrid := Model.Grid; FixedHeadsArray := Model.DataArrayManager.GetDataSetByName(KCfpFixedHeads); Assert(FixedHeadsArray <> nil); FixedHeadsArray.Initialize; for NodeIndex := 0 to FNodes.Count - 1 do begin ANode := FNodes[NodeIndex]; Assert(PipeConducOrPerm.IsValue[ ANode.FLayer, ANode.FRow, ANode.FColumn]); ANode.FExchange := PipeConducOrPerm.RealData[ ANode.FLayer, ANode.FRow, ANode.FColumn]; if FConduitFlowProcess.CfpElevationChoice = cecIndividual then begin if not PipeElevation.IsValue[ANode.FLayer, ANode.FRow, ANode.FColumn] then begin frmErrorsAndWarnings.AddError(Model, StrCFPPipeElevationI, Format(StrLayerRowCol, [ANode.FLayer+1, ANode.FRow+1, ANode.FColumn+1])); Break; end; ANode.FElevation := PipeElevation.RealData[ ANode.FLayer, ANode.FRow, ANode.FColumn]; if ANode.FElevation > LocalGrid.CellElevation[ANode.FColumn, ANode.FRow, ANode.FLayer] then begin frmErrorsAndWarnings.AddError(Model, StrCFPNodeElevationHigh, Format(StrNodeNumber0d, [ANode.FNumber, ANode.FLayer+1, ANode.FRow+1, ANode.FColumn+1])); end; if ANode.FElevation < LocalGrid.CellElevation[ANode.FColumn, ANode.FRow, ANode.FLayer+1] then begin frmErrorsAndWarnings.AddError(Model, StrCFPNodeElevationLow, Format(StrNodeNumber0d, [ANode.FNumber, ANode.FLayer+1, ANode.FRow+1, ANode.FColumn+1])); end; end; ANode.FIsFixed := FixedHeadsArray.IsValue[ ANode.FLayer, ANode.FRow, ANode.FColumn]; if ANode.FIsFixed then begin ANode.FFixedHead := FixedHeadsArray.RealData[ ANode.FLayer, ANode.FRow, ANode.FColumn]; end; end; finally CellList.Free; end; end; FCrchUsed := FConduitFlowProcess.PipesUsed and FConduitFlowProcess.ConduitRechargeUsed and Model.ModflowPackages.RchPackage.IsSelected; if FCrchUsed then begin EvaluateConduitRecharge end; end; procedure TModflowCfpWriter.EvaluateConduitRecharge; var ScreenObjectIndex: Integer; ScreenObject: TScreenObject; NoAssignmentErrorRoot: string; NoDefinedErrorRoot: string; Boundary: TCfpRchFractionBoundary; NodeIndex: Integer; ANode: TCfpNode; StressPeriodCount: Integer; StressPeriodIndex: Integer; CellList: TValueCellList; CellIndex: Integer; ACell: TCfpRchFraction_Cell; begin frmErrorsAndWarnings.BeginUpdate; try ClearTimeLists(Model); StressPeriodCount := Model.ModflowFullStressPeriods.Count; for NodeIndex := 0 to FNodes.Count - 1 do begin ANode := FNodes[NodeIndex]; SetLength(ANode.FRechargeFractionUsed, StressPeriodCount); SetLength(ANode.FRechargeFraction, StressPeriodCount); SetLength(ANode.FRechargeFractionAnnotation, StressPeriodCount); for StressPeriodIndex := 0 to StressPeriodCount - 1 do begin ANode.FRechargeFractionUsed[StressPeriodIndex] := False; end; end; RemoveNoDefinedError(NoDefinedErrorRoot); NoAssignmentErrorRoot := Format(StrNoBoundaryConditio, [Package.PackageIdentifier]); frmProgressMM.AddMessage(Format(StrEvaluatingSData, [Package.PackageIdentifier])); for ScreenObjectIndex := 0 to Model.ScreenObjectCount - 1 do begin if not frmProgressMM.ShouldContinue then begin Exit; end; ScreenObject := Model.ScreenObjects[ScreenObjectIndex]; if ScreenObject.Deleted then begin Continue; end; if not ScreenObject.UsedModels.UsesModel(Model) then begin Continue; end; Boundary := ScreenObject.ModflowCfpRchFraction;; if Boundary <> nil then begin if not ScreenObject.SetValuesOfEnclosedCells and not ScreenObject.SetValuesOfIntersectedCells then begin frmErrorsAndWarnings.AddError(Model, NoAssignmentErrorRoot, ScreenObject.Name, ScreenObject); end; frmProgressMM.AddMessage(Format(StrEvaluatingS, [ScreenObject.Name])); Boundary.GetCellValues(FValues, nil, Model); end; end; if (FValues.Count = 0) then begin frmErrorsAndWarnings.AddError(Model, StrConduitRechargeNot, StrConduitRechargeWas); end; for StressPeriodIndex := 0 to FValues.Count - 1 do begin CellList := FValues[StressPeriodIndex]; for CellIndex := 0 to CellList.Count - 1 do begin ACell := CellList[CellIndex] as TCfpRchFraction_Cell; ANode := FNodeGrid[ACell.Layer, ACell.Row, ACell.Column]; if ANode <> nil then begin ANode.FRechargeFractionUsed[StressPeriodIndex] := True; ANode.FRechargeFraction[StressPeriodIndex] := ACell.CfpRechargeFraction; ANode.FRechargeFractionAnnotation[StressPeriodIndex] := ACell.CfpRechargeFractionAnnotation; end; end; end; finally frmErrorsAndWarnings.EndUpdate; end; end; class function TModflowCfpWriter.Extension: string; begin result := '.cfp'; end; function TModflowCfpWriter.Package: TModflowPackageSelection; begin result := Model.ModflowPackages.ConduitFlowProcess; end; procedure TModflowCfpWriter.UpdateDisplay( TimeLists: TModflowBoundListOfTimeLists); var RechFractionsTimes: TModflowBoundaryDisplayTimeList; TimeIndex: Integer; StressPeriodCount: integer; RechFractionsArray: TModflowBoundaryDisplayDataArray; NodeIndex: Integer; ANode: TCfpNode; begin if not (Model as TPhastModel).CfpRechargeIsSelected(nil) then begin UpdateNotUsedDisplay(TimeLists); Exit; end; Evaluate; Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; RechFractionsTimes := TimeLists[0]; StressPeriodCount := Model.ModflowFullStressPeriods.Count; for TimeIndex := 0 to StressPeriodCount - 1 do begin RechFractionsArray := RechFractionsTimes[TimeIndex] as TModflowBoundaryDisplayDataArray; for NodeIndex := 0 to FNodes.Count - 1 do begin ANode := FNodes[NodeIndex]; if ANode.FRechargeFractionUsed[TimeIndex] then begin RechFractionsArray.RealData[ANode.FLayer, ANode.FRow, ANode.FColumn] := ANode.FRechargeFraction[TimeIndex]; RechFractionsArray.Annotation[ANode.FLayer, ANode.FRow, ANode.FColumn] := ANode.FRechargeFractionAnnotation[TimeIndex]; end; end; end; end; procedure TModflowCfpWriter.WriteDataSet0; begin // CFP requires that 1 and only 1 line be present in data set 0. WriteCommentLine(PackageID_Comment(Package)); end; procedure TModflowCfpWriter.WriteDataSet1; var Mode: Integer; OutDir: string; OutputFileName: string; begin Mode := 0; if FConduitFlowProcess.PipesUsed then begin Mode := Mode + 1; end; if FConduitFlowProcess.ConduitLayersUsed then begin Mode := Mode + 2; OutDir := ExtractFileDir(NameOfFile); OutDir := IncludeTrailingPathDelimiter(OutDir); OutputFileName := OutDir + 'turblam.txt'; Model.AddModelOutputFile(OutputFileName); end; WriteInteger(Mode); WriteString(' # Data Set 1: MODE'); NewLine; end; procedure TModflowCfpWriter.WriteDataSet12; var NNODES: Integer; ELEVATION: Double; NodeIndex: Integer; ANode: TCfpNode; NO_N: Integer; begin case FConduitFlowProcess.CfpElevationChoice of cecIndividual: begin for NodeIndex := 0 to FNodes.Count - 1 do begin ANode := FNodes[NodeIndex]; NO_N := ANode.FNumber; ELEVATION := ANode.FElevation; WriteInteger(NO_N); WriteFloat(ELEVATION); NewLine; end; end; cecGroup: begin NNODES := FNodes.Count; ELEVATION := FConduitFlowProcess.ElevationOffset; WriteInteger(NNODES); WriteFloat(ELEVATION); NewLine; end; else Assert(False); end; end; procedure TModflowCfpWriter.WriteDataSet13; begin case FConduitFlowProcess.CfpExchange of ceNodeConductance: begin WriteString('# SA_EXCHANGE = 0; pipe conductance for each node'); end; ceWallPermeability: begin WriteString('# SA_EXCHANGE = 1; conduit wall permeability for each node'); end else Assert(False); end; NewLine; end; procedure TModflowCfpWriter.WriteDataSet14; var SA_EXCHANGE: Integer; begin SA_EXCHANGE := Ord(FConduitFlowProcess.CfpExchange); WriteInteger(SA_EXCHANGE); NewLine; end; procedure TModflowCfpWriter.WriteDataSet15; begin WriteString('# criterion for convergence (EPSILON)'); NewLine; end; procedure TModflowCfpWriter.WriteDataSet16; var Epsilon: Double; begin Epsilon := FConduitFlowProcess.Epsilon; WriteFloat(Epsilon); NewLine; end; procedure TModflowCfpWriter.WriteDataSet17; begin WriteString('# maximum number for loop iterations (NITER)'); NewLine; end; procedure TModflowCfpWriter.WriteDataSet18; var NITER: Integer; begin NITER := FConduitFlowProcess.MaxIterations; WriteInteger(NITER); NewLine; end; procedure TModflowCfpWriter.WriteDataSet19; begin WriteString('# Relaxation parameter (RELAX)'); NewLine; end; procedure TModflowCfpWriter.WriteDataSet20; var RELAX: Double; begin RELAX := FConduitFlowProcess.Relax; WriteFloat(RELAX); NewLine; end; procedure TModflowCfpWriter.WriteDataSet21; begin case FConduitFlowProcess.CfpPrintIterations of cpiNoPrint: begin WriteString('# Print flag (P_NR); 0 = iteration results not printed'); end; cpiPrint: begin WriteString('# Print flag (P_NR); 1 = iteration results printed'); end; else Assert(False); end; NewLine; end; procedure TModflowCfpWriter.WriteDataSet22; var P_NR: Integer; begin P_NR := Ord(FConduitFlowProcess.CfpPrintIterations); WriteInteger(P_NR); NewLine; end; procedure TModflowCfpWriter.WriteDataSet25; var PipeIndex: Integer; APipe: TCfpPipe; NO_P: Integer; DIAMETER: Double; TORTUOSITY: Double; RHEIGHT: Double; LCRITREY_P: Double; TCRITREY_P: Double; begin for PipeIndex := 0 to FPipes.Count - 1 do begin APipe := FPipes[PipeIndex]; NO_P := APipe.FNumber; DIAMETER := APipe.FDiameter; TORTUOSITY := APipe.FTortuosity; RHEIGHT := APipe.FRoughnessHeight; LCRITREY_P := APipe.FLowerR; TCRITREY_P := APipe.FHigherR; WriteInteger(NO_P); WriteFloat(DIAMETER); WriteFloat(TORTUOSITY); WriteFloat(RHEIGHT); WriteFloat(LCRITREY_P); WriteFloat(TCRITREY_P); NewLine; end; end; procedure TModflowCfpWriter.WriteDataSet26; begin WriteString('# NodeNumber (NO_N), N_HEAD = -1 = not fixed; N_HEAD has positive value = piezometric heads for nodes with fixed head'); NewLine; end; procedure TModflowCfpWriter.WriteDataSet27; var NodeIndex: Integer; ANode: TCfpNode; NO_N: Integer; N_HEAD: Double; begin for NodeIndex := 0 to FNodes.Count - 1 do begin ANode := FNodes[NodeIndex]; NO_N := ANode.FNumber; WriteInteger(NO_N); if ANode.FIsFixed then begin N_HEAD := ANode.FFixedHead; WriteFloat(N_HEAD); end else begin WriteInteger(-1); end; NewLine; end; end; procedure TModflowCfpWriter.WriteDataSet28; begin case FConduitFlowProcess.CfpExchange of ceNodeConductance: begin WriteString('#Node number (NO_N), Conduit conductance (K_EXCHANGE)'); end; ceWallPermeability: begin WriteString('#Node number (NO_N), Conduit wall permeability (K_EXCHANGE)'); end; else Assert(False); end; NewLine; end; procedure TModflowCfpWriter.WriteDataSet29; var NodeIndex: integer; ANode: TCfpNode; NO_N: Integer; K_EXCHANGE: Double; begin for NodeIndex := 0 to FNodes.Count - 1 do begin ANode := FNodes[NodeIndex]; NO_N := ANode.FNumber; K_EXCHANGE := ANode.FExchange; WriteInteger(NO_N); WriteFloat(K_EXCHANGE); NewLine; end; end; procedure TModflowCfpWriter.WriteDataSet32; var LayerGroupIndex: Integer; ALayerGroup: TLayerGroup; NCL: Integer; LayerIndex: Integer; AConduitLayer: TConduitLayerItem; begin NCL := 0; // Start at 1 because first layer group defines the top of the model. for LayerGroupIndex := 1 to Model.LayerStructure.Count - 1 do begin ALayerGroup := Model.LayerStructure[LayerGroupIndex]; if ALayerGroup.RunTimeSimulated then begin for LayerIndex := 0 to Min(ALayerGroup.LayerCount, ALayerGroup.ConduitLayers.Count) - 1 do begin AConduitLayer := ALayerGroup.ConduitLayers[LayerIndex]; if AConduitLayer.IsConduitLayer then begin Inc(NCL); end; end; end; end; WriteInteger(NCL); NewLine; end; procedure TModflowCfpWriter.WriteDataSet33; begin WriteString('# Conduit layer numbers (CL)'); NewLine; end; procedure TModflowCfpWriter.WriteDataSet34; var CL: Integer; LayerGroupIndex: Integer; ALayerGroup: TLayerGroup; LayerIndex: Integer; AConduitLayer: TConduitLayerItem; begin CL := 0; for LayerGroupIndex := 1 to Model.LayerStructure.Count - 1 do begin ALayerGroup := Model.LayerStructure[LayerGroupIndex]; if ALayerGroup.RunTimeSimulated then begin for LayerIndex := 0 to Max(ALayerGroup.LayerCount, ALayerGroup.ConduitLayers.Count) - 1 do begin Inc(CL); if LayerIndex < ALayerGroup.ConduitLayers.Count then begin AConduitLayer := ALayerGroup.ConduitLayers[LayerIndex]; if AConduitLayer.IsConduitLayer then begin WriteInteger(CL); end; end; end; end; end; NewLine; end; procedure TModflowCfpWriter.WriteDataSet35; begin WriteString('# Water temperature, in degrees Celsius (LTEMP)'); NewLine; end; procedure TModflowCfpWriter.WriteDataSet36; var LTEMP: Double; begin LTEMP := FConduitFlowProcess.LayerTemperature; WriteFloat(LTEMP); NewLine; end; procedure TModflowCfpWriter.WriteDataSet37; begin WriteString('# mean void diameter (VOID), ' + 'lower critical Reynolds number (turbulent to laminar) (LCRITREY_L), ' + 'Upper critical Reynolds number (laminar to turbulent) (TCRITREY_L)'); NewLine; end; procedure TModflowCfpWriter.WriteDataSet4; var NNODES: Integer; NPIPES: Integer; NLAYERS: Integer; begin NNODES := FNodes.Count; NPIPES := FPipes.Count; NLAYERS := Model.ModflowLayerCount; WriteInteger(NNODES); WriteInteger(NPIPES); WriteInteger(NLAYERS); NewLine; end; procedure TModflowCfpWriter.WriteDataSet5; begin WriteString('# temperature or water in conduits (TEMPERATURE)'); NewLine; end; procedure TModflowCfpWriter.WriteDataSet6; var TEMPERATURE: Double; begin TEMPERATURE := FConduitFlowProcess.ConduitTemperature; WriteFloat(TEMPERATURE); NewLine; end; procedure TModflowCfpWriter.WriteDataSet7; begin WriteString('# Node number (NO_N), ' + 'Column, Row, and Layer numbers (MC, MR, ML), ' + 'Neighbor nodes (NB1, NB2, NB3, NB4, NB5, NB6), ' + 'Pipe numbers (PB1, PB2, PB3, PB4, PB5, PB6)'); NewLine; end; procedure TModflowCfpWriter.WriteDataSet8; var NodeIndex: Integer; ANode: TCfpNode; PipeIndex: Integer; APipe: TCfpPipe; OtherNode: TCfpNode; begin for NodeIndex := 0 to FNodes.Count - 1 do begin ANode := FNodes[NodeIndex]; WriteInteger(ANode.FNumber); WriteInteger(ANode.FColumn+1); WriteInteger(ANode.FRow+1); WriteInteger(Model.DataSetLayerToModflowLayer(ANode.FLayer)); if ANode.FPipes.Count > 6 then begin frmErrorsAndWarnings.AddError(Model, StrTooManyConduitsAt, Format(Str0d1d2d, [ANode.FLayer+1, ANode.FRow+1, ANode.FColumn+1])); end; for PipeIndex := 0 to Min(6, ANode.FPipes.Count) - 1 do begin APipe := ANode.FPipes[PipeIndex]; OtherNode := APipe.OtherNode(ANode); WriteInteger(OtherNode.FNumber); end; for PipeIndex := ANode.FPipes.Count+1 to 6 do begin WriteInteger(0); end; for PipeIndex := 0 to Min(6, ANode.FPipes.Count) - 1 do begin APipe := ANode.FPipes[PipeIndex]; WriteInteger(APipe.FNumber); end; for PipeIndex := ANode.FPipes.Count+1 to 6 do begin WriteInteger(0); end; NewLine; end; end; procedure TModflowCfpWriter.WriteDataSets23to24; begin WriteString('# Data for conduit parameters'); NewLine; WriteString('# Pipe number (NO_P), diameter (DIAMETER), ' + 'tortuosity (TORTUOSITY), roughness height (RHEIGHT), ' + 'lower critical Reynolds number (turbulent to laminar) (LCRITREY_P), ' + 'upper critical Reynolds number (laminar to turbulent) (TCRITREY_P)'); NewLine; end; procedure TModflowCfpWriter.WriteDataSets2and3; begin WriteString('# data for mode 1 (or 3) conduit pipe system'); NewLine; WriteString('# number of nodes (NNODES), number of conduits (NPIPES), number of layers (NLAYERS)'); NewLine; end; procedure TModflowCfpWriter.WriteDataSets30to31; begin WriteString('# Data for mode 2 (or 3) conduit layer system'); NewLine; WriteString('# Number of conduit layers (NCL)'); NewLine; end; procedure TModflowCfpWriter.WriteDataSets38to39; var ModelLayer: Integer; CL: Integer; LayerGroupIndex: Integer; ALayerGroup: TLayerGroup; LayerIndex: Integer; AConduitLayer: TConduitLayerItem; VOID: Double; LCRITREY_L: Double; TCRITREY_L: Double; begin ModelLayer := 0; CL := 0; for LayerGroupIndex := 1 to Model.LayerStructure.Count - 1 do begin ALayerGroup := Model.LayerStructure[LayerGroupIndex]; if ALayerGroup.RunTimeSimulated then begin for LayerIndex := 0 to Max(ALayerGroup.LayerCount, ALayerGroup.ConduitLayers.Count) - 1 do begin Inc(ModelLayer); if LayerIndex < ALayerGroup.ConduitLayers.Count then begin AConduitLayer := ALayerGroup.ConduitLayers[LayerIndex]; if AConduitLayer.IsConduitLayer then begin // Data Set 38 Inc(CL); WriteString(Format('# conduit layer %0:d, (Model layer %1:d)', [CL, ModelLayer])); NewLine; // Data Set 39 VOID := AConduitLayer.Void; LCRITREY_L := AConduitLayer.LowerCriticalReynoldsNumber; TCRITREY_L := AConduitLayer.HigherCriticalReynoldsNumber; WriteFloat(VOID); WriteFloat(LCRITREY_L); WriteFloat(TCRITREY_L); NewLine; end; end; end; end; end; end; procedure TModflowCfpWriter.WriteDataSets9to11; begin WriteString('# Node elevations (GEOHEIGHT)'); NewLine; case FConduitFlowProcess.CfpElevationChoice of cecIndividual: begin WriteString('# Option 1 selected'); NewLine; WriteString('# Node number (NO_N), Elevation with respect to datum (ELEVATION)'); NewLine; end; cecGroup: begin WriteString('# Option 2 selected'); NewLine; WriteString('# Number of nodes (NNODES), Elevation offset from cell center (ELEVATION)'); NewLine; end; else Assert(False); end; end; procedure TModflowCfpWriter.WriteFile(const AFileName: string); var ShouldWriteFile: boolean; begin if not Package.IsSelected or (Model.ModelSelection <> msModflowCfp) then begin Exit end; ShouldWriteFile := not Model.PackageGeneratedExternally(StrCFP); FShouldWriteCRCH := not Model.PackageGeneratedExternally(StrCRCH); FShouldWriteCOC := not Model.PackageGeneratedExternally(StrCOC); if not ShouldWriteFile and not FShouldWriteCRCH and not FShouldWriteCOC then begin Exit; end; if not FConduitFlowProcess.PipesUsed and not ShouldWriteFile then begin Exit; end; NameOfFile := FileName(AFileName); if ShouldWriteFile then begin WriteToNameFile(StrCFP, Model.UnitNumbers.UnitNumber(StrCFP), NameOfFile, foInput, Model); end; // if ShouldWriteFile then // begin Evaluate; Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; // end; if ShouldWriteFile then begin OpenFile(NameOfFile); try WriteDataSet0; WriteDataSet1; if FConduitFlowProcess.PipesUsed then begin WriteDataSets2and3; WriteDataSet4; WriteDataSet5; WriteDataSet6; WriteDataSet7; WriteDataSet8; WriteDataSets9to11; WriteDataSet12; WriteDataSet13; WriteDataSet14; WriteDataSet15; WriteDataSet16; WriteDataSet17; WriteDataSet18; WriteDataSet19; WriteDataSet20; WriteDataSet21; WriteDataSet22; WriteDataSets23to24; WriteDataSet25; WriteDataSet26; WriteDataSet27; WriteDataSet28; WriteDataSet29; end; if FConduitFlowProcess.ConduitLayersUsed then begin WriteDataSets30to31; WriteDataSet32; WriteDataSet33; WriteDataSet34; WriteDataSet35; WriteDataSet36; WriteDataSet37; WriteDataSets38to39; end; finally CloseFile; end; end; WriteCrchFile(NameOfFile); WriteCocFile(NameOfFile); end; procedure TModflowCfpWriter.WriteCocFile(NameOfFile: string); var NodeIndex: Integer; CocUsed: Boolean; PipeIndex: Integer; NNODES: Integer; NPIPES: Integer; ANode: TCfpNode; APipe: TCfpPipe; OutputFileName: string; OutDir: string; begin CocUsed := FConduitFlowProcess.PipesUsed and (FConduitFlowProcess.OutputInterval > 0) and FShouldWriteCOC; if CocUsed then begin NNODES := 0; for NodeIndex := 0 to FNodes.Count - 1 do begin if FNodes[NodeIndex].FRecordData then begin Inc(NNODES); end; end; NPIPES := 0; for PipeIndex := 0 to FPipes.Count - 1 do begin if FPipes[PipeIndex].FRecordData then begin Inc(NPIPES); end; end; if (NNODES > 0) or (NPIPES > 0) then begin NameOfFile := ChangeFileExt(NameOfFile, '.coc'); OutDir := ExtractFileDir(NameOfFile); OutDir := IncludeTrailingPathDelimiter(OutDir); WriteToNameFile(StrCOC, Model.UnitNumbers.UnitNumber(StrCOC), NameOfFile, foInput, Model); OpenFile(NameOfFile); try // Data Set 0 WriteCommentLine(File_Comment('COC')); // Data Set 1 WriteCommentLine('Number of nodes for output (NNODES)'); // Data set 2 WriteInteger(NNODES); NewLine; // Data set 3 WriteCommentLine('Node numbers, one per line (NODE_NUMBERS)'); // Data set 4 for NodeIndex := 0 to FNodes.Count - 1 do begin ANode := FNodes[NodeIndex]; if ANode.FRecordData then begin WriteInteger(ANode.FNumber); NewLine; OutputFileName := Format('%sNODE%.4d.OUT', [OutDir, ANode.FNumber]); Model.AddModelOutputFile(OutputFileName); end; end; // Data set 5 WriteCommentLine('Node output each n time steps (N_NTS)'); // Data set 6 WriteInteger(FConduitFlowProcess.OutputInterval); NewLine; // Data Set 7 WriteCommentLine('Number of conduits for output (NPIPES)'); // Data Set 8 WriteInteger(NPIPES); NewLine; // Data set 9 WriteCommentLine('Conduit numbers, one per line (PIPE_NUMBERS)'); // Data set 10 for PipeIndex := 0 to FPipes.Count - 1 do begin APipe := FPipes[PipeIndex]; if APipe.FRecordData then begin WriteInteger(APipe.FNumber); NewLine; OutputFileName := Format('%sTUBE%.4d.OUT', [OutDir, APipe.FNumber]); Model.AddModelOutputFile(OutputFileName); end; end; // Data set 11 WriteCommentLine('Conduit output each n time steps (T_NTS)'); // Data set 12 WriteInteger(FConduitFlowProcess.OutputInterval); NewLine; finally CloseFile; end; end; end; end; procedure TModflowCfpWriter.WriteCrchFile(NameOfFile: string); var ANode: TCfpNode; NodeIndex: Integer; IFLAG_CRCH: Integer; StressPeriodIndex: Integer; StressPeriodCount: Integer; begin if FCrchUsed and FShouldWriteCRCH then begin NameOfFile := ChangeFileExt(NameOfFile, '.crch'); WriteToNameFile(StrCRCH, Model.UnitNumbers.UnitNumber(StrCRCH), NameOfFile, foInput, Model); OpenFile(NameOfFile); try StressPeriodCount := Model.ModflowFullStressPeriods.Count; for StressPeriodIndex := 0 to StressPeriodCount - 1 do begin IFLAG_CRCH := FNodes.Count; // CRCH data set 1 WriteString('# Conduit Recharge data Stress Period '); WriteInteger(StressPeriodIndex + 1); NewLine; // Data Set 2; WriteInteger(IFLAG_CRCH); NewLine; // Data Set 3; for NodeIndex := 0 to FNodes.Count - 1 do begin ANode := FNodes[NodeIndex]; WriteInteger(ANode.FNumber); if ANode.FRechargeFractionUsed[StressPeriodIndex] then begin WriteFloat(ANode.FRechargeFraction[StressPeriodIndex]); end else begin WriteFloat(0); end; NewLine; end; end; finally CloseFile; end; end; end; { TCfpNode } constructor TCfpNode.Create; begin FPipes := TList<TCfpPipe>.Create; end; destructor TCfpNode.Destroy; begin FPipes.Free; inherited; end; { TCfpPipe } function TCfpPipe.OtherNode(ANode: TCfpNode): TCfpNode; begin if ANode = FNode1 then begin result := FNode2; end else if ANode = FNode2 then begin result := FNode1; end else begin Result := nil; Assert(False); end; end; function TCfpPipe.SameNodes(Node1, Node2: TCfpNode): boolean; begin result := ((Node1 = FNode1) and (Node2 = FNode2)) or ((Node1 = FNode2) and (Node2 = FNode1)); end; end.
unit DesignView; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, dcsystem, dcfdes, LrObserverList; type TDesignForm = class(TForm) DCLiteDesigner: TDCLiteDesigner; procedure DCLiteDesignerSelectionChanged(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure DCLiteDesignerDragDrop(Sender, Source, Target: TObject; X, Y: Integer); private { Private declarations } FOnSelectionChange: TNotifyEvent; FObservers: TLrObserverList; protected function GetSelectedComponents: TList; function GetSelection: TComponent; procedure SetSelection(const Value: TComponent); protected procedure AlignControls(AControl: TControl; var Rect: TRect); override; procedure DesignerMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure SelectionChange; procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN; public { Public declarations } procedure ActivateDesigner; procedure DeactivateDesigner; procedure LoadFromFile(const inFilename: string); procedure SaveToFile(const inFilename: string); procedure SetLimitInfo(inIndex: Integer; inComponent: TComponent; inActions: TAllowedActions = []); public property Observers: TLrObserverList read FObservers; property OnSelectionChange: TNotifyEvent read FOnSelectionChange write FOnSelectionChange; property Selection: TComponent read GetSelection write SetSelection; property SelectedComponents: TList read GetSelectedComponents; end; implementation {$R *.dfm} procedure TDesignForm.FormCreate(Sender: TObject); begin FObservers := TLrObserverList.Create; end; procedure TDesignForm.FormDestroy(Sender: TObject); begin Observers.Free; end; procedure TDesignForm.SetLimitInfo(inIndex: Integer; inComponent: TComponent; inActions: TAllowedActions = []); begin with DCLiteDesigner do begin while LimitInfos.Count <= inIndex do LimitInfos.Add; LimitInfos[inIndex].Component := inComponent; LimitInfos[inIndex].AllowedActions := inActions; end; end; procedure TDesignForm.LoadFromFile(const inFilename: string); var d: TDCLiteDesigner; begin d := DCLiteDesigner; RemoveComponent(d); d.LoadFromFile(Self, inFilename); Visible := false; DCLiteDesigner.Designer.PopupMenu := d.Designer.PopupMenu; d.Free; end; procedure TDesignForm.SaveToFile(const inFilename: string); begin DCLiteDesigner.SaveToFile(inFilename); end; procedure TDesignForm.ActivateDesigner; begin //DCLiteDesigner.OnDragOver := DCLiteDesignerDragOver; DCLiteDesigner.OnDragDrop := DCLiteDesignerDragDrop; DCLiteDesigner.Designer.OnMouseUp := DesignerMouseUp; DCLiteDesigner.Active := true; SelectionChange; DCLiteDesigner.Designer.BringContainersToFront; end; procedure TDesignForm.DeactivateDesigner; begin DCLiteDesigner.Active := false; end; procedure TDesignForm.DesignerMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin SetFocus; end; procedure TDesignForm.AlignControls(AControl: TControl; var Rect: TRect); var r: TRect; i: Integer; begin inherited; r := ClientRect; AdjustClientRect(r); for i := 0 to Pred(ControlCount) do with Controls[i] do begin if Left < r.Left then Left := r.Left; if Top < r.Top then Top := r.Top; end; end; function TDesignForm.GetSelectedComponents: TList; begin Result := DCLiteDesigner.Designer.SelectedComponents; end; procedure TDesignForm.SetSelection(const Value: TComponent); begin with DCLiteDesigner.Designer do if Value <> nil then SelectComponent(Value) else ClearSelection; end; function TDesignForm.GetSelection: TComponent; begin if (SelectedComponents <> nil) and (SelectedComponents.Count > 0) then Result := SelectedComponents[0] else Result := nil; end; procedure TDesignForm.DCLiteDesignerSelectionChanged(Sender: TObject); begin SelectionChange; end; procedure TDesignForm.SelectionChange; begin if Assigned(OnSelectionChange) then OnSelectionChange(Self); end; procedure TDesignForm.DCLiteDesignerDragDrop(Sender, Source, Target: TObject; X, Y: Integer); begin while (Target <> nil) and (Target is TControl) and not (Target is TWinControl) do Target := TControl(Target).Parent; if (Target <> nil) and (Target is TWinControl) then begin DCLiteDesigner.Designer.CreateComponent( TComponentClass(GetClass(DesignerInsertClass)), TComponent(Target), X, Y, 0, 0); DesignerInsertClass := ''; end; end; procedure TDesignForm.WMLButtonDown(var Message: TWMLButtonDown); begin // end; end.
unit FileInfo; interface uses SysUtils, Classes, Windows, MD4, AnidbConsts; //If set, FileDB will be saved to disk every time a change is made. //Otherwise it'll be only flushed on exit. {$DEFINE UPDATEDBOFTEN} type TFileInfo = record size: int64; ed2k: MD4Digest; lead: MD4Digest; StateSet: boolean; //the file have been added to Anidb at least once State: TAnidbFileState; //information that Anidb has about the file //some fields might be missing end; PFileInfo = ^TFileInfo; //Multithread unsafe TFileDb = class(TObject) protected FFilename: string; FFiles: array of PFileInfo; FLoaded: boolean; FChanged: boolean; public constructor Create(AFilename: string); destructor Destroy; override; function AddNew: PFileInfo; function FindByEd2k(ed2k: MD4Digest): PFileInfo; function FindByLead(lead: MD4Digest): PFileInfo; private //This implementation is subject to change, so I leave these protected. //In future versions I might change to not loading the file, but only indices, //and then looking in the contents directly. procedure Clear; procedure LoadFromStream(s: TStream); procedure SaveToStream(s: TStream); procedure LoadFromFile(Filename: string); procedure SaveToFile(Filename: string); public procedure Touch; //call to force loading db right now procedure Save; //to save DB at a critical points procedure Changed; //call every time you make a change end; TStreamExtender = class helper for TStream function ReadInt: integer; inline; procedure WriteInt(i: integer); inline; function ReadString: string; inline; procedure WriteString(s: string); inline; function ReadBool: boolean; inline; procedure WriteBool(b: boolean); inline; end; implementation function TStreamExtender.ReadInt: integer; begin ReadBuffer(Result, SizeOf(Result)); end; procedure TStreamExtender.WriteInt(i: integer); begin WriteBuffer(i, SizeOf(i)); end; function TStreamExtender.ReadString: string; begin SetLength(Result, ReadInt); ReadBuffer(Result[1], Length(Result)*SizeOf(Result[1])); end; procedure TStreamExtender.WriteString(s: string); begin if Length(s)<=0 then WriteInt(0) else WriteInt(Length(s)); WriteBuffer(s[1], Length(s)*SizeOf(s[1])); end; function TStreamExtender.ReadBool: boolean; begin Result := boolean(ReadInt); end; procedure TStreamExtender.WriteBool(b: boolean); begin WriteInt(integer(b)); end; constructor TFileDb.Create(AFilename: string); begin inherited Create; FFilename := AFilename; FLoaded := false; end; destructor TFileDb.Destroy; begin Save; //Even when UpdatingDBOften, no harm in checking FChanged again //Free memory Clear; inherited; end; function TFileDb.AddNew: PFileInfo; begin Touch; New(Result); ZeroMemory(Result, SizeOf(Result^)); SetLength(FFiles, Length(FFiles)+1); FFiles[Length(FFiles)-1] := Result; //Don't call Changed() just now because the data's still not set. //Clients must call Changed() after populating new record with (maybe default) info. end; function TFileDb.FindByEd2k(ed2k: MD4Digest): PFileInfo; var i: integer; begin Touch; Result := nil; for i := 0 to Length(FFiles) - 1 do if SameMd4(FFiles[i].ed2k, ed2k) then begin Result := FFiles[i]; exit; end; end; function TFileDb.FindByLead(lead: MD4Digest): PFileInfo; var i: integer; begin Touch; Result := nil; for i := 0 to Length(FFiles) - 1 do if SameMd4(FFiles[i].lead, lead) then begin Result := FFiles[i]; exit; end; end; //Clears data and releases all the memory. procedure TFileDb.Clear; var i: integer; begin for i := Length(FFiles) - 1 downto 0 do if FFiles[i] <> nil then begin Dispose(FFiles[i]); FFiles[i] := nil; end; SetLength(FFiles, 0); end; procedure TFileDb.LoadFromStream(s: TStream); var i: integer; begin Clear; SetLength(FFiles, s.ReadInt); for i := 0 to Length(FFiles) - 1 do FFiles[i] := nil; try for i := 0 to Length(FFiles) - 1 do begin New(FFiles[i]); s.ReadBuffer(FFiles[i]^, integer(@FFiles[i]^.State) - integer(@FFiles[i]^)); s.ReadBuffer(FFiles[i]^.State, integer(@FFiles[i]^.State.Source) - integer(@FFiles[i]^.State)); { Остаток - строки } FFiles[i].State.Source := s.ReadString; FFiles[i].State.Source_set := s.ReadBool; FFiles[i].State.Storage := s.ReadString; FFiles[i].State.Storage_set := s.ReadBool; FFiles[i].State.Other := s.ReadString; FFiles[i].State.Other_set := s.ReadBool; end; except Clear; //to not leave inconsistent array end; end; procedure TFileDb.SaveToStream(s: TStream); var i: integer; begin s.WriteInt(Length(FFiles)); for i := 0 to Length(FFiles) - 1 do begin s.WriteBuffer(FFiles[i]^, integer(@FFiles[i]^.State) - integer(@FFiles[i]^)); s.WriteBuffer(FFiles[i]^.State, integer(@FFiles[i]^.State.Source) - integer(@FFiles[i]^.State)); { Остаток - строки } s.WriteString(FFiles[i].State.Source); s.WriteBool(FFiles[i].State.Source_set); s.WriteString(FFiles[i].State.Storage); s.WriteBool(FFiles[i].State.Storage_set); s.WriteString(FFiles[i].State.Other); s.WriteBool(FFiles[i].State.Other_set); end; end; procedure TFileDb.LoadFromFile(Filename: string); var f: TFileStream; begin f := TFileStream.Create(Filename, fmOpenRead or fmShareDenyWrite); try LoadFromStream(f); finally FreeAndNil(f); end; end; procedure TFileDb.SaveToFile(Filename: string); var f: TFileStream; begin f := TFileStream.Create(Filename, fmCreate); try SaveToStream(f); finally FreeAndNil(f); end; end; procedure TFileDb.Touch; begin if not FLoaded then begin if FileExists(FFilename) then LoadFromFile(FFilename); FLoaded := true; end; end; procedure TFileDb.Save; begin //Save data if needed if FLoaded and FChanged then SaveToFile(FFilename); FChanged := false; end; procedure TFileDb.Changed; begin {$IFDEF UPDATEDBOFTEN} FChanged := true; Save; //Right now {$ELSE} FChanged := true; //Will save at a later time {$ENDIF} end; end.
{******************************************************************************* Title: T2TiPDV Description: Controle de importações The MIT License Copyright: Copyright (C) 2014 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: alberteije@gmail.com @author T2Ti.COM @version 2.0 *******************************************************************************} unit ImportaController; {$mode objfpc}{$H+} interface uses Classes, Dialogs, SysUtils, DB, LCLIntf, LCLType, LMessages, Forms, FileUtil, ZDataSet, Biblioteca, FPJSON; type TImportaController = class private protected public class function ImportarDadosDoPDV(pPathLocal: String): Boolean; class procedure GravarIntegracaoPDV(Identificador: String); end; implementation uses T2TiORM, IntegracaoPdvVO, NotaFiscalCabecalhoVO, NotaFiscalDetalheVO, R06VO, R07VO, EcfVendaCabecalhoVO, EcfVendaDetalheVO, EcfTotalTipoPagamentoVO, EcfMovimentoVO, EcfSuprimentoVO, EcfSangriaVO, EcfFechamentoVO, R02VO, R03VO, Sintegra60mVO, Sintegra60aVO, LogImportacaoController, ControleEstoqueController; { TImportaController } { Procedimento que faz o controle de importação dos registros que estão no arquivo } class function TImportaController.ImportarDadosDoPDV(pPathLocal: String): Boolean; var ObjetoIntegracaoPdvVO: TIntegracaoPdvVO; ObjetoNotaFiscalCabecalhoVO: TNotaFiscalCabecalhoVO; ObjetoEcfVendaCabecalhoVO: TEcfVendaCabecalhoVO; ObjetoR02VO: TR02VO; ObjetoR06VO: TR06VO; ObjetoEcfMovimentoVO: TEcfMovimentoVO; ObjetoSintegra60MVO: TSintegra60mVO; Filtro, Identificador, Objeto, NomeCaixa, Tupla: String; ArquivoTexto: TextFile; ListaParametros: TStringList; I, Contador: Integer; begin try FormatSettings.DecimalSeparator := '.'; Application.ProcessMessages; // Para contar o número de linhas Contador := 0; // Prepara o arquivo para ser utilizado AssignFile(ArquivoTexto, pPathLocal); Reset(ArquivoTexto); // Enquanto não chegar no final do arquivo que está sendo importado... while not Eof(ArquivoTexto) do begin try // Le uma linha do arquivo e armazena na variável Tupla Read(ArquivoTexto, Tupla); Inc(Contador); // Se houver dados na linha if Trim(Tupla) <> '' then begin // Identificador : Nome do Arquivo + Número da Linha Identificador := ExtractFileName(pPathLocal) + '_' + IntToStr(Contador); // Carrega os detalhes que vem no nome do arquivo numa lista para utilização ListaParametros := TStringList.Create; ExtractStrings(['_'],[], PChar(Identificador), ListaParametros); Objeto := ListaParametros[0]; NomeCaixa := ListaParametros[1]; // Consulta se o registro já foi inserido Filtro := 'IDENTIFICA = ' + QuotedStr(Identificador); ObjetoIntegracaoPdvVO := TIntegracaoPdvVO.Create; ObjetoIntegracaoPdvVO := TIntegracaoPdvVO(TT2TiORM.ConsultarUmObjeto(ObjetoIntegracaoPdvVO, Filtro, True)); // Só continua se o identificador não foi processado, ou seja, se a linha não foi gravada ainda na retaguarda if not Assigned(ObjetoIntegracaoPdvVO) then begin {$Region 'NF'} if Objeto = 'NF' then begin ObjetoNotaFiscalCabecalhoVO := TNotaFiscalCabecalhoVO(ObjetoNotaFiscalCabecalhoVO.ToObject(Tupla)); ObjetoNotaFiscalCabecalhoVO.IdGeradoCaixa := ObjetoNotaFiscalCabecalhoVO.Id; ObjetoNotaFiscalCabecalhoVO.NomeCaixa := NomeCaixa; ObjetoNotaFiscalCabecalhoVO.DataSincronizacao := Date; ObjetoNotaFiscalCabecalhoVO.HoraSincronizacao := TimeToStr(Now); ObjetoNotaFiscalCabecalhoVO.Id := 0; TT2TiORM.Inserir(ObjetoNotaFiscalCabecalhoVO); // Detalhes for I := 0 to Pred(ObjetoNotaFiscalCabecalhoVO.ListaNotaFiscalDetalheVO.Count) do begin ObjetoNotaFiscalCabecalhoVO.ListaNotaFiscalDetalheVO[I].IdGeradoCaixa := ObjetoNotaFiscalCabecalhoVO.ListaNotaFiscalDetalheVO[I].Id; ObjetoNotaFiscalCabecalhoVO.ListaNotaFiscalDetalheVO[I].NomeCaixa := NomeCaixa; ObjetoNotaFiscalCabecalhoVO.ListaNotaFiscalDetalheVO[I].DataSincronizacao := Date; ObjetoNotaFiscalCabecalhoVO.ListaNotaFiscalDetalheVO[I].HoraSincronizacao := TimeToStr(Now); ObjetoNotaFiscalCabecalhoVO.ListaNotaFiscalDetalheVO[I].Id := 0; TT2TiORM.Inserir(ObjetoNotaFiscalCabecalhoVO.ListaNotaFiscalDetalheVO[I]); if ObjetoNotaFiscalCabecalhoVO.ListaNotaFiscalDetalheVO[I].MovimentaEstoque = 'S' then TControleEstoqueController.AtualizarEstoque(ObjetoNotaFiscalCabecalhoVO.ListaNotaFiscalDetalheVO[I].Quantidade, ObjetoNotaFiscalCabecalhoVO.ListaNotaFiscalDetalheVO[I].IdProduto); end; GravarIntegracaoPDV(Identificador); end {$EndRegion 'NF'} {$Region 'VENDA'} else if Objeto = 'VENDA' then begin ObjetoEcfVendaCabecalhoVO := TEcfVendaCabecalhoVO(ObjetoEcfVendaCabecalhoVO.ToObject(Tupla)); ObjetoEcfVendaCabecalhoVO.IdGeradoCaixa := ObjetoEcfVendaCabecalhoVO.Id; ObjetoEcfVendaCabecalhoVO.NomeCaixa := NomeCaixa; ObjetoEcfVendaCabecalhoVO.DataSincronizacao := Date; ObjetoEcfVendaCabecalhoVO.HoraSincronizacao := TimeToStr(Now); ObjetoEcfVendaCabecalhoVO.Id := 0; TT2TiORM.Inserir(ObjetoEcfVendaCabecalhoVO); for I := 0 to Pred(ObjetoEcfVendaCabecalhoVO.ListaEcfVendaDetalheVO.Count) do begin ObjetoEcfVendaCabecalhoVO.ListaEcfVendaDetalheVO[I].IdGeradoCaixa := ObjetoEcfVendaCabecalhoVO.ListaEcfVendaDetalheVO[I].Id; ObjetoEcfVendaCabecalhoVO.ListaEcfVendaDetalheVO[I].NomeCaixa := NomeCaixa; ObjetoEcfVendaCabecalhoVO.ListaEcfVendaDetalheVO[I].DataSincronizacao := Date; ObjetoEcfVendaCabecalhoVO.ListaEcfVendaDetalheVO[I].HoraSincronizacao := TimeToStr(Now); ObjetoEcfVendaCabecalhoVO.ListaEcfVendaDetalheVO[I].Id := 0; TT2TiORM.Inserir(ObjetoEcfVendaCabecalhoVO.ListaEcfVendaDetalheVO[I]); if ObjetoEcfVendaCabecalhoVO.ListaEcfVendaDetalheVO[I].MovimentaEstoque = 'S' then TControleEstoqueController.AtualizarEstoque(ObjetoEcfVendaCabecalhoVO.ListaEcfVendaDetalheVO[I].Quantidade, ObjetoEcfVendaCabecalhoVO.ListaEcfVendaDetalheVO[I].IdEcfProduto); end; // TotalTipoPagamento for I := 0 to Pred(ObjetoEcfVendaCabecalhoVO.ListaEcfTotalTipoPagamentoVO.Count) do begin ObjetoEcfVendaCabecalhoVO.ListaEcfTotalTipoPagamentoVO[I].IdGeradoCaixa := ObjetoEcfVendaCabecalhoVO.ListaEcfTotalTipoPagamentoVO[I].Id; ObjetoEcfVendaCabecalhoVO.ListaEcfTotalTipoPagamentoVO[I].NomeCaixa := NomeCaixa; ObjetoEcfVendaCabecalhoVO.ListaEcfTotalTipoPagamentoVO[I].DataSincronizacao := Date; ObjetoEcfVendaCabecalhoVO.ListaEcfTotalTipoPagamentoVO[I].HoraSincronizacao := TimeToStr(Now); ObjetoEcfVendaCabecalhoVO.ListaEcfTotalTipoPagamentoVO[I].Id := 0; TT2TiORM.Inserir(ObjetoEcfVendaCabecalhoVO.ListaEcfTotalTipoPagamentoVO[I]); end; GravarIntegracaoPDV(Identificador); end {$EndRegion 'VENDA'} {$Region 'MOVIMENTO'} else if Objeto = 'MOVIMENTO' then begin ObjetoEcfMovimentoVO := TEcfMovimentoVO.Create; ObjetoEcfMovimentoVO := TEcfMovimentoVO(ObjetoEcfMovimentoVO.ToObject(Tupla)); ObjetoEcfMovimentoVO.IdGeradoCaixa := ObjetoEcfMovimentoVO.Id; ObjetoEcfMovimentoVO.NomeCaixa := NomeCaixa; ObjetoEcfMovimentoVO.DataSincronizacao := Date; ObjetoEcfMovimentoVO.HoraSincronizacao := TimeToStr(Now); ObjetoEcfMovimentoVO.Id := 0; TT2TiORM.Inserir(ObjetoEcfMovimentoVO); // Suprimento for I := 0 to Pred(ObjetoEcfMovimentoVO.ListaEcfSuprimentoVO.Count) do begin ObjetoEcfMovimentoVO.ListaEcfSuprimentoVO[I].IdGeradoCaixa := ObjetoEcfMovimentoVO.ListaEcfSuprimentoVO[I].Id; ObjetoEcfMovimentoVO.ListaEcfSuprimentoVO[I].NomeCaixa := NomeCaixa; ObjetoEcfMovimentoVO.ListaEcfSuprimentoVO[I].DataSincronizacao := Date; ObjetoEcfMovimentoVO.ListaEcfSuprimentoVO[I].HoraSincronizacao := TimeToStr(Now); ObjetoEcfMovimentoVO.ListaEcfSuprimentoVO[I].Id := 0; TT2TiORM.Inserir(ObjetoEcfMovimentoVO.ListaEcfSuprimentoVO[I]); end; // Sangria for I := 0 to Pred(ObjetoEcfMovimentoVO.ListaEcfSangriaVO.Count) do begin ObjetoEcfMovimentoVO.ListaEcfSangriaVO[I].IdGeradoCaixa := ObjetoEcfMovimentoVO.ListaEcfSangriaVO[I].Id; ObjetoEcfMovimentoVO.ListaEcfSangriaVO[I].NomeCaixa := NomeCaixa; ObjetoEcfMovimentoVO.ListaEcfSangriaVO[I].DataSincronizacao := Date; ObjetoEcfMovimentoVO.ListaEcfSangriaVO[I].HoraSincronizacao := TimeToStr(Now); ObjetoEcfMovimentoVO.ListaEcfSangriaVO[I].Id := 0; TT2TiORM.Inserir(ObjetoEcfMovimentoVO.ListaEcfSangriaVO[I]); end; // Fechamento for I := 0 to Pred(ObjetoEcfMovimentoVO.ListaEcfFechamentoVO.Count) do begin ObjetoEcfMovimentoVO.ListaEcfFechamentoVO[I].IdGeradoCaixa := ObjetoEcfMovimentoVO.ListaEcfFechamentoVO[I].Id; ObjetoEcfMovimentoVO.ListaEcfFechamentoVO[I].NomeCaixa := NomeCaixa; ObjetoEcfMovimentoVO.ListaEcfFechamentoVO[I].DataSincronizacao := Date; ObjetoEcfMovimentoVO.ListaEcfFechamentoVO[I].HoraSincronizacao := TimeToStr(Now); ObjetoEcfMovimentoVO.ListaEcfFechamentoVO[I].Id := 0; TT2TiORM.Inserir(ObjetoEcfMovimentoVO.ListaEcfFechamentoVO[I]); end; GravarIntegracaoPDV(Identificador); end {$EndRegion 'MOVIMENTO'} {$Region 'R02'} else if Objeto = 'R02' then begin ObjetoR02VO := TR02VO(ObjetoR02VO.ToObject(Tupla)); ObjetoR02VO.IdGeradoCaixa := ObjetoR02VO.Id; ObjetoR02VO.NomeCaixa := NomeCaixa; ObjetoR02VO.DataSincronizacao := Date; ObjetoR02VO.HoraSincronizacao := TimeToStr(Now); ObjetoR02VO.Id := 0; TT2TiORM.Inserir(ObjetoR02VO); // Detalhes for I := 0 to Pred(ObjetoR02VO.ListaR03VO.Count) do begin ObjetoR02VO.ListaR03VO[I].IdGeradoCaixa := ObjetoR02VO.ListaR03VO[I].Id; ObjetoR02VO.ListaR03VO[I].NomeCaixa := NomeCaixa; ObjetoR02VO.ListaR03VO[I].DataSincronizacao := Date; ObjetoR02VO.ListaR03VO[I].HoraSincronizacao := TimeToStr(Now); ObjetoR02VO.ListaR03VO[I].Id := 0; TT2TiORM.Inserir(ObjetoR02VO.ListaR03VO[I]); end; GravarIntegracaoPDV(Identificador); end {$EndRegion 'R02'} {$Region 'R06'} else if Objeto = 'R06' then begin ObjetoR06VO := TR06VO(ObjetoR06VO.ToObject(Tupla)); ObjetoR06VO.IdGeradoCaixa := ObjetoR06VO.Id; ObjetoR06VO.NomeCaixa := NomeCaixa; ObjetoR06VO.DataSincronizacao := Date; ObjetoR06VO.HoraSincronizacao := TimeToStr(Now); ObjetoR06VO.Id := 0; TT2TiORM.Inserir(ObjetoR06VO); GravarIntegracaoPDV(Identificador); end {$EndRegion 'R06'} {$Region 'SINTEGRA60M'} else if Objeto = 'SINTEGRA60M' then begin ObjetoSintegra60MVO := TSintegra60MVO(ObjetoSintegra60MVO.ToObject(Tupla)); ObjetoSintegra60MVO.IdGeradoCaixa := ObjetoSintegra60MVO.Id; ObjetoSintegra60MVO.NomeCaixa := NomeCaixa; ObjetoSintegra60MVO.DataSincronizacao := Date; ObjetoSintegra60MVO.HoraSincronizacao := TimeToStr(Now); ObjetoSintegra60MVO.Id := 0; TT2TiORM.Inserir(ObjetoSintegra60MVO); // Detalhes for I := 0 to Pred(ObjetoSintegra60MVO.ListaSintegra60AVO.Count) do begin ObjetoSintegra60MVO.ListaSintegra60AVO[I].IdGeradoCaixa := ObjetoSintegra60MVO.ListaSintegra60AVO[I].Id; ObjetoSintegra60MVO.ListaSintegra60AVO[I].NomeCaixa := NomeCaixa; ObjetoSintegra60MVO.ListaSintegra60AVO[I].DataSincronizacao := Date; ObjetoSintegra60MVO.ListaSintegra60AVO[I].HoraSincronizacao := TimeToStr(Now); ObjetoSintegra60MVO.ListaSintegra60AVO[I].Id := 0; TT2TiORM.Inserir(ObjetoSintegra60MVO.ListaSintegra60AVO[I]); end; GravarIntegracaoPDV(Identificador); end; {$EndRegion 'SINTEGRA60M'} end; end; except // Se ocorrer algum erro, grava o log de importação on E: Exception do TLogImportacaoController.GravarLogImportacao(Tupla, E.Message); end; Readln(ArquivoTexto); end; finally FormatSettings.DecimalSeparator := ','; ListaParametros := nil; ObjetoIntegracaoPdvVO := nil; ObjetoNotaFiscalCabecalhoVO := nil; ObjetoEcfVendaCabecalhoVO := nil; ObjetoEcfMovimentoVO := nil; ObjetoR02VO := nil; ObjetoR06VO := nil; CloseFile(ArquivoTexto); Result:=true; end; end; { Grava os dados do registro na tabela integracao_pdv } class procedure TImportaController.GravarIntegracaoPDV(Identificador: String); var ObjetoIntegracaoPdvVO: TIntegracaoPdvVO; begin try ObjetoIntegracaoPdvVO := TIntegracaoPdvVO.Create; ObjetoIntegracaoPdvVO.Identifica := Identificador; ObjetoIntegracaoPdvVO.DataIntegracao := Date; ObjetoIntegracaoPdvVO.HoraIntegracao := TimeToStr(Now); TT2TiORM.Inserir(ObjetoIntegracaoPdvVO); finally FreeAndNil(ObjetoIntegracaoPdvVO); end; end; end.
program binarytree; TYPE TreeNodePtr = ^TreeNode; VisitProcPtr = Procedure(node: TreeNodePtr); TreeNode = RECORD parent : TreeNodePtr; // pointer to the parent node left: TreeNodePtr; // pointer to the left node right: TreeNodePtr; // pointer to the right node ID: integer; // integer ID of the node visit: VisitProcPtr; // function pointer to functions that have no return value and a pointer to a node END; // A print-function that can be assigned to the node’s visit function pointer. The // function prints the node’s ID on STDOUT seperated by a single whitespace PROCEDURE print(node: TreeNodePtr); BEGIN write(node^.ID, ' '); END; // Insert new node with ID 'element' at the right place in the tree PROCEDURE insertID(VAR Tree : TreeNodePtr; insertID: integer); VAR InsertNode : TreeNodePtr; ParentPtr : TreeNodePtr; CurrentNodePtr : TreeNodePtr; BEGIN CurrentNodePtr := Tree; ParentPtr := NIL; WHILE (CurrentNodePtr <> NIL) DO IF CurrentNodePtr^.ID <> insertID THEN BEGIN ParentPtr := CurrentNodePtr; IF CurrentNodePtr^.ID > insertID THEN CurrentNodePtr := CurrentNodePtr^.left ELSE CurrentNodePtr := CurrentNodePtr^.right END; // Allocate the memory for the nodes dynamically at run-time New (insertNode); insertNode^.parent := ParentPtr; insertNode^.left := NIL; insertNode^.right := NIL; insertNode^.ID := insertID; insertNode^.visit := @print; IF ParentPtr = NIL THEN Tree := InsertNode ELSE IF ParentPtr^.ID > insertID THEN ParentPtr^.left := insertNode ELSE ParentPtr^.right := insertNode END; // Depth first traversal that traverses the tree from its root and invokes the visit method // (http://en.wikipedia.org/wiki/Tree_traversal#Depth-first) PROCEDURE depthFirstTraversal(root: TreeNodePtr); BEGIN IF root <> NIL THEN BEGIN // Visit the root. root^.visit(root); // Traverse the left subtree. depthFirstTraversal(root^.left); // Traverse the right subtree. depthFirstTraversal(root^.right); END END; VAR tree: TreeNodePtr; BEGIN // Creating empty tree by setting the "root" node to NIL tree := NIL; insertID(tree, 5); insertID(tree, 2); insertID(tree, 6); insertID(tree, 7); insertID(tree, 1); depthFirstTraversal(tree); END.
unit uI2XUndo; interface uses SysUtils, Classes, contnrs, Controls, StdCtrls, GR32_RangeBars, GR32_Image, ComCtrls, uStrUtil, Types, Grids ; const UNDO_FILE_PREFIX='~UNDO'; type TUndoAction = ( udNone = 0, udControlChange, udFileLoad, udImageLoad ); TRegionUndoAction = ( ruRegionMove, ruRegionAdd, ruRegionDelete, ruRegionRename ); TUndoItem = class( TObject ) //private public Parent : TObject; Action : TUndoAction; Ctl : TObject; Descr : string; OldValue : string; procedure Undo(); dynamic; end; TUndoImageItem = class( TUndoItem ) //private public CachedImageFileName : string; procedure Undo(); override; constructor Create(); virtual; destructor Destroy(); override; end; TUndoRegionItem = class( TUndoItem ) //private public Action : TRegionUndoAction; EleNodeDataXMLImage : string; NamePath : string; Template : TObject; procedure Undo(); override; constructor Create(); virtual; destructor Destroy(); override; end; TUndoStack = class(TStack) public function Push( AObject: TUndoItem ): TUndoItem; function Pop: TUndoItem; function Peek: TUndoItem; procedure Clear(); destructor Destroy(); override; end; TRequestRegionActionEvent = procedure(Sender: TObject; const Action : TRegionUndoAction; const ElementXMLImage : string; const NamePath : string ) of object; TRequestActionGridUpdateEvent = procedure(Sender: TObject; const Data : string ) of object; TUndoDebugEvent = procedure( Sender: TObject; DebugMessage : string ) of object; TI2XUndo = class(TObject) private FTempPath : string; FIsUndoing : boolean; FIsRedoing : boolean; undoStack : TUndoStack; redoStack : TUndoStack; lastUndoItem : TUndoItem; lastRedoItem : TUndoItem; prepUndoItem : TUndoItem; FOnChange : TNotifyEvent; FOnRequestRegionAction : TRequestRegionActionEvent; FOnRequestActionGridUpdate : TRequestActionGridUpdateEvent; FOnDebug : TUndoDebugEvent; FActiveUndoItem : TUndoItem; function GetCount: integer; function GetRedoAvailable: boolean; function GetUndoAvailable: boolean; procedure DoOnChange(); procedure dbg( const DebugMessage : string ); public procedure Prep( ctl : TObject; const OldValue : string; const ForcePrepChange : boolean = false ); procedure Add( ctl : TObject; const CurrentValue : string; const ForcePrep : boolean = false ); overload; procedure Add( ctl : TImgView32 ); overload; procedure Add( sg: TStringGrid); overload; procedure Add( region : TObject; action : TRegionUndoAction; template : TObject; const ForcePrep : boolean = false ); overload; procedure Undo(); procedure Redo(); procedure Clear(); property Count : integer read GetCount; property UndoAvailable : boolean read GetUndoAvailable; property RedoAvailable : boolean read GetRedoAvailable; property OnChange : TNotifyEvent read FOnChange write FOnChange; property OnDebug : TUndoDebugEvent read FOnDebug write FOnDebug; property ActiveUndoItem : TUndoItem read FActiveUndoItem; property IsUndoing : boolean read FIsUndoing; property IsRedoing : boolean read FIsRedoing; property TempPath : string read FTempPath write FTempPath; procedure RequestRegionAction( const Action : TRegionUndoAction; const ElementXMLImage : string; const NamePath : string ); procedure RequestActionGridUpdate( Grid : TObject; const Data : string ); property OnRequestRegionAction : TRequestRegionActionEvent read FOnRequestRegionAction write FOnRequestRegionAction; property OnRequestActionGridUpdate : TRequestActionGridUpdateEvent read FOnRequestActionGridUpdate write FOnRequestActionGridUpdate; constructor Create(); virtual; destructor Destroy(); override; end; var UndoTempPath : string; Undo : TI2XUndo; UndoItemFocus : TUndoItem; //function UpdateUndoItemFocus( ctl : TObject; val : string) : boolean; implementation uses uI2XTemplate, uImage2XML; function SetFocusOnControl(ctl: TWinControl): boolean; // This function will force the particular Class Types that we are interested in // to be active before we force a control to be active var ctrl, parentCtl, topCtl : TWinControl; nLastActiveIndex : integer; //sLastActivePage bHasFocus : boolean; begin try Result := false; topCtl := nil; parentCtl := ctl.Parent; nLastActiveIndex := -1; while ( parentCtl <> nil ) do begin if ( parentCtl.ClassName = 'TTabSheet' ) then nLastActiveIndex := TTabSheet(parentCtl).TabIndex; if (( parentCtl.ClassName = 'TPageControl' ) and ( nLastActiveIndex > -1 )) then begin TPageControl(parentCtl).ActivePageIndex := nLastActiveIndex; nLastActiveIndex := -1; end; parentCtl := parentCtl.Parent; end; ctl.SetFocus(); Result := true; finally end; end; { TUndoStack } procedure TUndoStack.Clear; var item : TUndoItem; i: integer; begin for i := self.List.Count -1 downto 0 do begin TUndoItem( List.Items[i] ).Free; List.Delete( i ); end; end; destructor TUndoStack.Destroy; begin Clear; inherited; end; function TUndoStack.Peek: TUndoItem; begin Result := TUndoItem(inherited Peek); end; function TUndoStack.Pop: TUndoItem; begin Result := TUndoItem(inherited Pop); end; function TUndoStack.Push(AObject: TUndoItem): TUndoItem; begin Result := TUndoItem(inherited Push(AObject)); end; { TUndoItem } procedure TUndoItem.Undo; var edt : TEdit; cbo : TComboBox; sld : TGaugeBar; mem : TMemo; sg : TStringGrid; oUndoParent : TI2XUndo; begin if ( ctl <> nil ) then begin oUndoParent := TI2XUndo( self.Parent ); if ( TObject(ctl).ClassName = 'TEdit' ) then begin edt := TEdit(ctl); SetFocusOnControl( edt ); edt.Text := self.OldValue; edt.SelectAll(); end else if ( TObject(ctl).ClassName = 'TComboBox' ) then begin cbo := TComboBox(ctl); SetFocusOnControl( cbo ); cbo.Text := self.OldValue; end else if ( TObject(ctl).ClassName = 'TMemo' ) then begin mem := TMemo(ctl); SetFocusOnControl( mem ); mem.Lines.Text := self.OldValue; //mem.SelStart := Length( mem.Lines.Text ); mem.SelectAll(); end else if ( TObject(ctl).ClassName = 'TGaugeBar' ) then begin sld := TGaugeBar(ctl); SetFocusOnControl( sld ); sld.Position := StrToInt( self.OldValue ); end else if ( TObject(ctl).ClassName = 'TStringGrid' ) then begin sg := TStringGrid(ctl); SetFocusOnControl( sg ); oUndoParent.RequestActionGridUpdate( self.Ctl, self.OldValue ); end; end; end; { TI2XUndo } procedure TI2XUndo.Add(ctl: TObject; const CurrentValue : string; const ForcePrep : boolean = false); var undoItem : TUndoItem; begin if ( not ( self.FIsUndoing or self.FIsRedoing )) then begin if ( ForcePrep ) then self.Prep( ctl, CurrentValue ); if ( prepUndoItem.Ctl = ctl ) then begin if (( lastUndoItem = nil ) or ( TObject(ctl) <> lastUndoItem.Ctl )) then begin undoItem := TUndoItem.Create(); undoItem.Ctl := ctl; undoItem.Action := udControlChange; undoItem.OldValue := prepUndoItem.OldValue; lastUndoItem := self.undoStack.Push( undoItem ); lastUndoItem.Parent := self; DoOnChange(); end; end; end; end; procedure TI2XUndo.Add(sg: TStringGrid); var undoItem : TUndoItem; begin if ( not ( self.FIsUndoing or self.FIsRedoing )) then begin if ( prepUndoItem.Ctl = TObject( sg ) ) then begin //Commenting the next 2 lines out will cause the app to add undo for each action //if (( lastUndoItem = nil ) or // ( lastUndoItem.Ctl <> TObject( sg ) )) then begin undoItem := TUndoItem.Create(); undoItem.Action := udControlChange; undoItem.OldValue := prepUndoItem.OldValue; undoItem.Ctl := sg; lastUndoItem := self.undoStack.Push( undoItem ); lastUndoItem.Parent := self; DoOnChange(); //end; end; end; end; procedure TI2XUndo.Add(ctl: TImgView32); var undoItem : TUndoImageItem; sImageFileNameTemp : string; begin if ( not ( self.FIsUndoing or self.FIsRedoing )) then begin sImageFileNameTemp := self.FTempPath + UNDO_FILE_PREFIX + uStrUtil.RandomString(6) + '.BMP'; ctl.Bitmap.SaveToFile( sImageFileNameTemp ); undoItem := TUndoImageItem.Create(); undoItem.CachedImageFileName := sImageFileNameTemp; undoItem.Ctl := ctl; lastUndoItem := self.undoStack.Push( undoItem ); lastUndoItem.Parent := self; DoOnChange(); end; end; procedure TI2XUndo.Add(region: TObject; action : TRegionUndoAction; template: TObject; const ForcePrep : boolean = false); var undoItem : TUndoRegionItem; begin if ( not ( self.FIsUndoing or self.FIsRedoing )) then begin if ( ForcePrep ) then begin self.Prep( region, CEleNodeData(region).AsXML( true ), ForcePrep ); lastUndoItem := nil; end; if ( prepUndoItem.Ctl = region ) then begin if (( lastUndoItem = nil ) or ( lastUndoItem.Ctl <> region )) then begin undoItem := TUndoRegionItem.Create(); undoItem.Action := action; undoItem.Template := template; undoItem.EleNodeDataXMLImage := prepUndoItem.OldValue; undoItem.NamePath := CEleNodeData( region ).NamePath; undoItem.Ctl := region; lastUndoItem := self.undoStack.Push( undoItem ); lastUndoItem.Parent := self; DoOnChange(); end; end; end; end; procedure TI2XUndo.Clear; begin undoStack.Clear; redoStack.Clear; lastRedoItem.Free; prepUndoItem.Free; lastRedoItem := TUndoItem.Create(); prepUndoItem := TUndoItem.Create(); FIsUndoing := false; FIsRedoing := false; end; constructor TI2XUndo.Create; begin undoStack := TUndoStack.Create(); redoStack := TUndoStack.Create(); lastRedoItem := TUndoItem.Create(); prepUndoItem := TUndoItem.Create(); FIsUndoing := false; FIsRedoing := false; end; procedure TI2XUndo.dbg(const DebugMessage: string); begin if ( Assigned( self.FOnDebug )) then self.FOnDebug( self, DebugMessage ); end; destructor TI2XUndo.Destroy; begin FreeAndNil( undoStack ); FreeAndNil( redoStack ); FreeAndNil( lastRedoItem ); FreeAndNil( prepUndoItem ); inherited; end; procedure TI2XUndo.DoOnChange; begin if ( Assigned( self.FOnChange )) then begin self.FOnChange( self ); end; end; function TI2XUndo.GetCount: integer; begin Result := undoStack.Count; end; function TI2XUndo.GetRedoAvailable: boolean; begin Result := ( self.lastRedoItem.Ctl <> nil ) end; function TI2XUndo.GetUndoAvailable: boolean; begin Result := ( self.undoStack.Count > 0 ); end; procedure TI2XUndo.Prep(ctl: TObject; const OldValue: string; const ForcePrepChange : boolean = false); begin if ( not ( self.FIsUndoing or self.FIsRedoing )) then begin if (( ForcePrepChange ) or ( prepUndoItem.Ctl <> ctl )) then begin prepUndoItem.Ctl := ctl; prepUndoItem.OldValue := OldValue; end; end; end; procedure TI2XUndo.Redo; var redoItem : TUndoItem; begin if ( self.RedoAvailable ) then begin try FIsRedoing := true; redoItem := redoStack.Pop; redoItem.Undo; FreeAndNil( redoItem ); DoOnChange(); finally FIsRedoing := false; end; end; end; procedure TI2XUndo.RequestActionGridUpdate(Grid: TObject; const Data: string); begin if ( Assigned( self.FOnRequestActionGridUpdate ) ) then begin self.FOnRequestActionGridUpdate( Grid, Data ); end; end; procedure TI2XUndo.RequestRegionAction(const Action: TRegionUndoAction; const ElementXMLImage: string; const NamePath : string ); begin if ( Assigned( self.FOnRequestRegionAction ) ) then begin self.FOnRequestRegionAction( self, Action, ElementXMLImage, NamePath ); end; end; procedure TI2XUndo.Undo; begin if ( self.UndoAvailable ) then begin try FIsUndoing := true; FActiveUndoItem := undoStack.Pop; FActiveUndoItem.Undo; DoOnChange(); finally FreeAndNil( FActiveUndoItem ); FIsUndoing := false; end; end; end; { TUndoImageItem } constructor TUndoImageItem.Create; begin self.Action := udImageLoad; end; destructor TUndoImageItem.Destroy; begin inherited; end; procedure TUndoImageItem.Undo; var iv : TImgView32; begin if ( ctl <> nil ) then begin if ( TObject(ctl).ClassName = 'TImgView32' ) then begin iv := TImgView32(ctl); iv.SetFocus(); iv.Bitmap.LoadFromFile( self.CachedImageFileName ); end; end; end; { TUndoRegionItem } constructor TUndoRegionItem.Create; begin end; destructor TUndoRegionItem.Destroy; begin inherited; end; procedure TUndoRegionItem.Undo; var oUndoParent : TI2XUndo; ele : CEleNodeData; begin try oUndoParent := TI2XUndo( self.Parent ); oUndoParent.RequestRegionAction( self.Action, self.EleNodeDataXMLImage, self.NamePath ); finally end; end; {* function UpdateUndoItemFocus( ctl : TObject; val : string) : boolean; Begin if ( TObject(UndoItemFocus.Ctl) = ctl ) then begin UndoItemFocus.Ctl := ctl; end; UndoItemFocus.OldValue := val; End; *} initialization Undo := TI2XUndo.Create(); Undo.TempPath := AppTempDir; UndoItemFocus := TUndoItem.Create(); finalization FreeAndNil( Undo ); FreeAndNil( UndoItemFocus ); END.
//------------------------------------------------------------------------------ //Event UNIT //------------------------------------------------------------------------------ // What it does- // The base Event class, provides the shared attributes of the specialized // events. // // Changes - // January 31st, 2007 - RaX - Created Header. // //------------------------------------------------------------------------------ unit Event; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface type //------------------------------------------------------------------------------ //TEvent //------------------------------------------------------------------------------ TRootEvent = class ExpiryTime : LongWord;//The time at which this event is set to go off Procedure Execute; Virtual; constructor Create(SetExpiryTime : LongWord); end; //------------------------------------------------------------------------------ implementation //------------------------------------------------------------------------------ //Execute UNIT //------------------------------------------------------------------------------ // What it does- // Just a random virtual event so the other child classes know what to // have =) // // Changes - // January 31st, 2007 - RaX - Created Header. // //------------------------------------------------------------------------------ Procedure TRootEvent.Execute; begin end;//Execute //------------------------------------------------------------------------------ constructor TRootEvent.Create(SetExpiryTime : LongWord); begin inherited Create; ExpiryTime := SetExpiryTime; end; end.
unit Unit2; interface uses System.SysUtils, System.Classes, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IniFiles, Forms, Vcl.ExtCtrls, IdGlobal, Superobject, DateUtils; type TReadArr = array of string; type TManager = class(TObject) private TextEncode: IIdTextEncoding; Timer1 : TTimer; procedure TCPClientDisconnected(Sender: TObject); procedure Timer1Timer(Sender: TObject); public TCPClient : TIdTCPClient; constructor Create; function ConnectToPhone(Host: string; Port: word): boolean; procedure DisconnectFromPhone; function SendToPhone(TX: string): string; procedure OnLinkError; function DecodeAnswer(RX: string): byte; function ReadClientBuf: TReadArr; procedure CreateTCPClient; procedure WorkSMSJSON(JSON: ISuperObject); function UnixDateToString(USec: Int64): string; end; var Manager : TManager; implementation uses Unit1; constructor TManager.Create; begin TextEncode := IndyTextEncoding_UTF8; TCPClient := nil; Timer1 := TTimer.Create(nil); Timer1.Interval := 100; Timer1.Enabled := False; Timer1.OnTimer := Timer1Timer; end; function TManager.ConnectToPhone(Host: string; Port: word): boolean; begin Result := True; LogOut('Try connect to the phone'); if TCPClient = nil then CreateTCPClient; TCPClient.Host := Host; TCPClient.Port := Port; try TCPClient.Connect; LogOut('Successful connection to the phone: ' + TCPClient.Host + ':' + IntToStr(TCPClient.Port)); Form1.SetControlsStatus(True); TCPClient.IOHandler.WriteLn('1234', TextEncode); //send password to the phone Timer1.Enabled := True; except LogOut('Error connecting to the phone: ' + TCPClient.Host + ':' + IntToStr(TCPClient.Port)); Result := False; end; end; procedure TManager.DisconnectFromPhone; begin TCPClient.Disconnect; Form1.SetControlsStatus(False); LogOut('Disconnecting from the phone'); Timer1.Enabled := False; end; procedure TManager.CreateTCPClient; begin TCPClient := TIdTCPClient.Create(); TCPClient.ConnectTimeout := 4000; TCPClient.ReadTimeout := 4000; TCPClient.OnDisconnected := TCPClientDisconnected; end; procedure TManager.OnLinkError; begin Timer1.Enabled := False; Form1.SetControlsStatus(False); TCPClient.Destroy; TCPClient := nil; CreateTCPClient; end; function TManager.SendToPhone(TX: string): string; var RX, Res: string; JSON: ISuperObject; i, PartCount: word; begin LogOut('TX = ' + TX); if TcpClient = nil then Exit; TCPClient.CheckForGracefulDisconnect(False); if not TCPClient.Connected then begin LogOut('Connection fail'); OnLinkError; Exit; end; try TCPClient.IOHandler.InputBuffer.Clear; TCPClient.IOHandler.WriteLn(TX, TextEncode); RX := TCPClient.IOHandler.ReadLn(TextEncode); LogOut('RX = ' + RX); except LogOut('Transmission error on the phone: ' + TX); OnLinkError; Exit; end; DecodeAnswer(RX); end; procedure TManager.WorkSMSJSON(JSON: ISuperObject); var i: integer; AddJSON: ISuperObject; USec: int64; begin for i := 0 to JSON.AsArray.Length - 1 do begin AddJSON := JSON.AsArray.O[i]; LogOut('Phone = ' + AddJSON.S[KeyAdres]); LogOut('SMS = ' + AddJSON.S[KeyBody]); LogOut('ID = ' + IntToStr(AddJSON.I[KeyID])); USec := Trunc(AddJSON.I[KeyDate]/1000); //phone transmits the time in milliseconds LogOut('Date = ' + UnixDateToString(USec)); end; end; function TManager.DecodeAnswer(RX: string): byte; var JSON, ArrJSON, ArrJSON2, AddJSON, AddJSON1, AddJSON2, AnswJSON: ISuperObject; Cmd:string; Arg:word; i,j : integer; begin Result := 0; try JSON := SO(RX); except Result := 1; LogOut('Package structure error'); Exit; end; Cmd := JSON.S[KeyCmd]; Arg := JSON.I[KeyArg]; AnswJSON := JSON.O[KeyAnswer]; if AnswJSON.AsObject.IsEmpty then Exit; if (Cmd = CmdGetSMSLast) or (Cmd = CmdGetSMS) or (Cmd = CmdGetSMSAfter) then begin AddJSON := JSON.O[KeyAnswer]; ArrJSON := AddJSON.O[KeySMS]; if not ArrJSON.IsType(stArray) then Exit; WorkSMSJSON(ArrJSON); end else if Cmd = CmdGetCmdList then begin ArrJSON := JSON.O[KeyAnswer]; if not ArrJSON.IsType(stArray) then Exit; for i := 0 to ArrJSON.AsArray.Length - 1 do begin AddJSON1 := ArrJSON.AsArray.O[i]; LogOut(AddJSON1.S[KeyCommand] + ' -> ' + AddJSON1.S[Keydescription]); end; end else if Cmd = CmdGetContact then begin AddJSON := JSON.O[KeyAnswer]; ArrJSON := AddJSON.O[KeyContacts]; if ArrJSON.IsType(stArray) then begin for i := 0 to ArrJSON.AsArray.Length - 1 do begin AddJSON1 := ArrJSON.AsArray.O[i]; LogOut('Account = ' + AddJSON1.S['display_name']); ArrJSON2 := AddJSON1.O[KeyPhones]; if not ArrJSON2.IsType(stArray) then Exit; for j := 0 to ArrJSON2.AsArray.Length - 1 do begin AddJSON2 := ArrJSON2.AsArray.O[j]; LogOut(' Phone = ' + AddJSON2.S['data1']); end; end; end; end; end; function TManager.UnixDateToString(USec: Int64): string; begin Result := DateTimeToStr(UnixToDateTime(USec)); end; procedure TManager.TCPClientDisconnected(Sender: TObject); begin LogOut('Disconnected'); end; function TManager.ReadClientBuf: TReadArr; var L: integer; begin SetLength(Result, 0); TCPClient.CheckForGracefulDisconnect(False); if not TCPClient.Connected then begin LogOut('Connection fail'); OnLinkError; Exit; end; while not TCPClient.Socket.InputBufferIsEmpty do begin L := Length(Result); SetLength(Result, L + 1); Result[L] := TCPClient.Socket.ReadLn(TextEncode); end; end; procedure TManager.Timer1Timer(Sender: TObject); var buf: TReadArr; i: integer; begin buf := Manager.ReadClientBuf; for i := 0 to High(buf) do begin LogOut(buf[i]); end; end; end.
unit BsLgotPeriods; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxControls, cxContainer, cxEdit, cxLabel, cxCheckBox, uConsts, uCommon_Funcs, uCommon_Loader, uCommon_Types, iBase; type TfrmLgotPeriod = class(TForm) lblDateBeg: TcxLabel; lblDateEnd: TcxLabel; DateBeg: TcxDateEdit; DateEnd: TcxDateEdit; btnOk: TcxButton; btnCancel: TcxButton; FullPeriod: TcxCheckBox; procedure btnOkClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure FullPeriodPropertiesChange(Sender: TObject); private { Private declarations } public { Public declarations } constructor Create(AOwner:TComponent; DbHandle:TISC_DB_HANDLE);reintroduce; end; var frmLgotPeriod: TfrmLgotPeriod; implementation {$R *.dfm} constructor TfrmLgotPeriod.Create(AOwner:TComponent; DbHandle:TISC_DB_HANDLE); var //HtKey:TbsShortCut; iLang:Byte; begin inherited Create(AOwner); //HtKey:=LoadShortCut(DbHandle, AOwner); iLang:=uCommon_Funcs.bsLanguageIndex(); btnCancel.Caption:=uConsts.bs_Cancel[iLang]; btnOk.Caption:=uConsts.bs_Accept[iLang]; end; procedure TfrmLgotPeriod.btnOkClick(Sender: TObject); begin ModalResult:=mrOk; end; procedure TfrmLgotPeriod.btnCancelClick(Sender: TObject); begin ModalResult:=mrCancel; end; procedure TfrmLgotPeriod.FullPeriodPropertiesChange(Sender: TObject); begin DateBeg.Enabled:=not FullPeriod.Checked; DateEnd.Enabled:=not FullPeriod.Checked; end; end.
unit FormTopologyAnalysis; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, TopologyAnalyzer, Voxel; type TFrmTopologyAnalysis = class(TForm) Bevel4: TBevel; BtOK: TButton; GbCollectedData: TGroupBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; LbLoneVoxels: TLabel; Lb3Faces: TLabel; Lb2Faces: TLabel; Lb1Face: TLabel; LbCorrectVoxels: TLabel; GbAnalysis: TGroupBox; Label7: TLabel; LbTopologyScore: TLabel; LbClassification: TLabel; Label8: TLabel; Label6: TLabel; Bevel2: TBevel; LbTotalVoxels: TLabel; GbExplanation: TGroupBox; Label9: TLabel; Label10: TLabel; Label11: TLabel; GroupBox1: TGroupBox; RbWholeModel: TRadioButton; RbJustSection: TRadioButton; CbSections: TComboBox; Label12: TLabel; procedure CbSectionsChange(Sender: TObject); procedure RbJustSectionClick(Sender: TObject); procedure RbWholeModelClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); procedure BtOKClick(Sender: TObject); private procedure ShowResults; public TopologyAnalyzer: CTopologyAnalyzer; // Constructors and Destructors. constructor Create(const _Voxel: TVoxelSection; Sender: TComponent); reintroduce; overload; destructor Destroy; override; end; implementation {$R *.dfm} uses FormMain; // Constructors and Destructors. procedure TFrmTopologyAnalysis.CbSectionsChange(Sender: TObject); begin if RbJustSection.Checked then begin TopologyAnalyzer.Load(FrmMain.Document.ActiveVoxel^.Section[CbSections.ItemIndex]); ShowResults(); end; end; constructor TFrmTopologyAnalysis.Create(const _Voxel: TVoxelSection; Sender: TComponent); var i : integer; begin TopologyAnalyzer := CTopologyAnalyzer.Create(_Voxel); inherited Create(Sender); for i := 0 to (FrmMain.Document.ActiveVoxel^.Header.NumSections-1) do begin CbSections.Items.Add(FrmMain.Document.ActiveVoxel^.Section[i].Name); end; CbSections.ItemIndex := _Voxel.Header.Number; end; destructor TFrmTopologyAnalysis.Destroy; begin TopologyAnalyzer.Free; inherited Destroy; end; procedure TFrmTopologyAnalysis.FormCreate(Sender: TObject); begin // ??? end; procedure TFrmTopologyAnalysis.FormShow(Sender: TObject); begin ShowResults(); end; procedure TFrmTopologyAnalysis.ShowResults(); begin LbCorrectVoxels.Caption := TopologyAnalyzer.GetCorrectVoxelsText(); Lb1Face.Caption := TopologyAnalyzer.GetNum1FaceText(); Lb2Faces.Caption := TopologyAnalyzer.GetNum2FacesText(); Lb3Faces.Caption := TopologyAnalyzer.GetNum3FacesText(); LbLoneVoxels.Caption := TopologyAnalyzer.GetLoneVoxelsText(); LbTotalVoxels.Caption := TopologyAnalyzer.GetTotalVoxelsText(); LbTopologyScore.Caption := TopologyAnalyzer.GetTopologyScoreText(); LbClassification.Caption := TopologyAnalyzer.GetClassificationText(); end; procedure TFrmTopologyAnalysis.RbJustSectionClick(Sender: TObject); begin RbWholeModel.Checked := false; RbJustSection.Checked := true; TopologyAnalyzer.Load(FrmMain.Document.ActiveVoxel^.Section[CbSections.ItemIndex]); ShowResults(); end; procedure TFrmTopologyAnalysis.RbWholeModelClick(Sender: TObject); begin RbWholeModel.Checked := true; RbJustSection.Checked := false; TopologyAnalyzer.LoadFullVoxel(FrmMain.Document.ActiveVoxel^); ShowResults(); end; procedure TFrmTopologyAnalysis.BtOKClick(Sender: TObject); begin Close; end; end.
unit Odontologia.Modelo.Entidades.Departamento; interface uses SimpleAttributes; type [Tabela('DDEPARTAMENTO')] TDDEPARTAMENTO = class private FDEP_NOMBRE : String; FDEP_COD_PAIS : Integer; FDEP_CODIGO : Integer; procedure SetDEP_COD_PAIS (const Value: Integer); procedure SetDEP_CODIGO (const Value: Integer); procedure SetDEP_NOMBRE (const Value: String); published [Campo('DEP_CODIGO'), Pk, AutoInc] property DEP_CODIGO : Integer read FDEP_CODIGO write SetDEP_CODIGO; [Campo('DEP_NOMBRE')] property DEP_NOMBRE : String read FDEP_NOMBRE write SetDEP_NOMBRE; [Campo('DEP_COD_PAIS')] property DEP_COD_PAIS : Integer read FDEP_COD_PAIS write SetDEP_COD_PAIS; end; implementation { TDDEPARTAMENTO } procedure TDDEPARTAMENTO.SetDEP_CODIGO(const Value: Integer); begin FDEP_CODIGO := Value; end; procedure TDDEPARTAMENTO.SetDEP_COD_PAIS(const Value: Integer); begin FDEP_COD_PAIS := Value; end; procedure TDDEPARTAMENTO.SetDEP_NOMBRE(const Value: String); begin FDEP_NOMBRE := Value; end; end.
unit uMainServer; // EMS Resource Module interface uses System.SysUtils, System.Classes, System.JSON, EMS.Services, EMS.ResourceAPI, EMS.ResourceTypes, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Stan.StorageBin, Data.DB, FireDAC.UI.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Phys, FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, FireDAC.ConsoleUI.Wait, Data.Bind.EngExt, System.Rtti, System.Bindings.Outputs, Data.Bind.Components, Data.Bind.DBScope, FireDAC.Stan.StorageJSON, FireDAC.Comp.Client, FireDAC.Phys.SQLiteVDataSet, FireDAC.Comp.DataSet, System.Variants, FireDAC.Phys.IBDef, FireDAC.Phys.IB, FireDAC.Phys.IBBase, FireDAC.Comp.BatchMove.DataSet, FireDAC.Comp.BatchMove, FireDAC.Comp.BatchMove.Text, FireDAC.Comp.UI {$IFDEF MSWINDOWS} , Windows {$ENDIF} ; type TMyFuncType = function(AContext: TEndpointContext; ARequest: TEndpointRequest; AResponse: TEndpointResponse): TMemoryStream of object; [ResourceName('v1')] TAutoTablesResource = class(TDataModule) EndpointQuery: TFDQuery; EndPointTable: TFDMemTable; BindingsList1: TBindingsList; FDStanStorageJSONLink1: TFDStanStorageJSONLink; EndPoints: TBindSourceDB; FDPhysIBDriverLink1: TFDPhysIBDriverLink; FDConnection: TFDConnection; AggregateSQL: TFDMemTable; FDBatchMoveCSV: TFDBatchMove; FDBatchMoveTextWriter: TFDBatchMoveTextWriter; FDBatchMoveDataSetReader: TFDBatchMoveDataSetReader; private procedure SaveDataSetToCSV(ADataSet: TFDDataSet; AStream: TStream); procedure SaveDataSetToStream(ADataSet: TFDDataSet; AStream: TStream; AContext: TEndpointContext); function GetFormatMimeType(AContext: TEndpointContext): String; function GetStorageFormat(const AFormat: String): TFDStorageFormat; procedure ResolveCustomMacros(const AMacros: String; AQuery: TFDQuery; ARequest: TEndpointRequest); procedure ResolveCustomParams(const AParams: String; AQuery: TFDQuery; ARequest: TEndpointRequest); procedure ResolveDefaultParams(AQuery: TFDQuery; AContext: TEndpointContext); function PermissionsCheck(const AGroups: string; AContext: TEndpointContext): Boolean; function ProcessRequest(const EndPoint, RequestType: String; AContext: TEndpointContext; ARequest: TEndpointRequest; AResponse: TEndpointResponse): TMemoryStream; function ProcessGet(const EndPoint: String; AContext: TEndpointContext; ARequest: TEndpointRequest; AResponse: TEndpointResponse): TMemoryStream; function ProcessPost(const EndPoint: String; AContext: TEndpointContext; ARequest: TEndpointRequest; AResponse: TEndpointResponse): TMemoryStream; function ProcessDelete(const EndPoint: String; AContext: TEndpointContext; ARequest: TEndpointRequest; AResponse: TEndpointResponse): TMemoryStream; procedure SetResponseStatus(StatusResult,StatusMessage: String; var ResponseStream: TMemoryStream); function GetTableGenerator(AConnection: TFDConnection; ATableName: String): String; published function customMethod(AContext: TEndpointContext; ARequest: TEndpointRequest; AResponse: TEndpointResponse): TMemoryStream; function Call(MethodName: string; AContext: TEndpointContext; ARequest: TEndpointRequest; AResponse: TEndpointResponse): TMemoryStream; [ResourceSuffix('{endpoint}/')] procedure Get(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse); [ResourceSuffix('{endpoint}/')] procedure Post(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse); [ResourceSuffix('{endpoint}/')] procedure DeleteItem(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse); end; const GET_REQUEST_TYPE = 'GET'; POST_REQUEST_TYPE = 'POST'; DELETE_REQUEST_TYPE = 'DELETE'; CSV_MIME_TYPE = 'text/csv'; XML_MIME_TYPE = 'application/xml'; JSON_MIME_TYPE = 'application/json'; BINARY_MIME_TYPE = 'application/octet-stream'; CSV_FORMAT = 'CSV'; XML_FORMAT = 'XML'; BINARY_FORMAT = 'BINARY'; FIELD_ENDPOINT = 'EndPoint'; FIELD_REQUESTTYPE = 'RequestType'; FIELD_ACTION = 'Action'; FIELD_TABLENAME = 'TableName'; FIELD_SQL = 'SQL'; FIELD_METHOD = 'Method'; FIELD_PARAMS = 'Params'; FIELD_MACROS = 'Macros'; FIELD_GROUPS = 'Groups'; FIELD_UNIQUEID = 'UniqueID'; implementation {%CLASSGROUP 'System.Classes.TPersistent'} {$R *.dfm} {$IFDEF MSWINDOWS} // https://stackoverflow.com/questions/1454501/how-do-i-run-a-command-line-program-in-delphi function GetDosOutput(CommandLine: string; Work: string = 'C:\'): string; { Run a DOS program and retrieve its output dynamically while it is running. } var SecAtrrs: TSecurityAttributes; StartupInfo: TStartupInfo; ProcessInfo: TProcessInformation; StdOutPipeRead, StdOutPipeWrite: THandle; WasOK: Boolean; pCommandLine: array[0..255] of AnsiChar; BytesRead: Cardinal; WorkDir: string; Handle: Boolean; begin Result := ''; with SecAtrrs do begin nLength := SizeOf(SecAtrrs); bInheritHandle := True; lpSecurityDescriptor := nil; end; CreatePipe(StdOutPipeRead, StdOutPipeWrite, @SecAtrrs, 0); try with StartupInfo do begin FillChar(StartupInfo, SizeOf(StartupInfo), 0); cb := SizeOf(StartupInfo); dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES; wShowWindow := SW_HIDE; hStdInput := GetStdHandle(STD_INPUT_HANDLE); // don't redirect stdin hStdOutput := StdOutPipeWrite; hStdError := StdOutPipeWrite; end; WorkDir := Work; Handle := CreateProcess(nil, PChar('cmd.exe /C ' + CommandLine), nil, nil, True, 0, nil, PChar(WorkDir), StartupInfo, ProcessInfo); CloseHandle(StdOutPipeWrite); if Handle then try repeat WasOK := windows.ReadFile(StdOutPipeRead, pCommandLine, 255, BytesRead, nil); if BytesRead > 0 then begin pCommandLine[BytesRead] := #0; Result := Result + pCommandLine; end; until not WasOK or (BytesRead = 0); WaitForSingleObject(ProcessInfo.hProcess, INFINITE); finally CloseHandle(ProcessInfo.hThread); CloseHandle(ProcessInfo.hProcess); end; finally CloseHandle(StdOutPipeRead); end; end; {$ENDIF} function TAutoTablesResource.customMethod(AContext: TEndpointContext; ARequest: TEndpointRequest; AResponse: TEndpointResponse): TMemoryStream; var StatusResult, StatusMessage: String; begin try {$IFDEF MSWINDOWS} StatusMessage := GetDosOutput('schtasks',''); {$ENDIF} except on E: Exception do begin StatusMessage := E.Message; end; end; Result := TMemoryStream.Create; StatusResult := 'ok'; SetResponseStatus(StatusResult,StatusMessage,Result); end; procedure TAutoTablesResource.ResolveCustomMacros(const AMacros: String; AQuery: TFDQuery; ARequest: TEndpointRequest); var I: Integer; SL: TStringList; begin if AMacros<>'' then begin SL := TStringList.Create; SL.StrictDelimiter := True; SL.CommaText := AMacros; for I := 0 to SL.Count-1 do begin EndPointQuery.MacroByName(SL[I]).AsRaw := ARequest.Params.Values[SL[I]]; end; SL.Free; end; end; procedure TAutoTablesResource.ResolveCustomParams(const AParams: String; AQuery: TFDQuery; ARequest: TEndpointRequest); var I: Integer; SL: TStringList; begin if AParams<>'' then begin SL := TStringList.Create; SL.StrictDelimiter := True; SL.CommaText := AParams; for I := 0 to SL.Count-1 do begin EndPointQuery.ParamByName(SL[I]).AsString := ARequest.Params.Values[SL[I]]; end; SL.Free; end; end; procedure TAutoTablesResource.ResolveDefaultParams(AQuery: TFDQuery; AContext: TEndpointContext); var AStream: TStringStream; AUserId, AUsername, ATenantId: String; begin if AContext.User<>nil then AUserId := AContext.User.UserId; if AContext.User<>nil then AUsername := AContext.User.UserName; if AContext.Tenant<>nil then ATenantId := AContext.Tenant.Id; if EndPointQuery.SQL.Text.IndexOf(':UserId')>-1 then begin AQuery.ParamByName('UserId').AsString := AUserId; end; if AQuery.SQL.Text.IndexOf(':UserName')>-1 then begin AQuery.ParamByName('UserName').AsString := AUserName; end; if AQuery.SQL.Text.IndexOf(':TenantId')>-1 then begin AQuery.ParamByName('TenantId').AsString := ATenantId; end; if AQuery.SQL.Text.IndexOf(':Body')>-1 then begin AStream := TStringStream.Create; if AContext.Request.Body.TryGetStream(TStream(AStream)) = True then begin AStream.Position := 0; AQuery.ParamByName('Body').AsString := AStream.DataString; end; AStream.Free; end; end; function TAutoTablesResource.PermissionsCheck(const AGroups: string; AContext: TEndpointContext): Boolean; begin Result := False; if AGroups<>'' then begin if AContext.User<>nil then if AContext.User.Groups<>nil then if (AContext.User.Groups.Contains(AGroups)=True) then Result := True; end else begin Result := True; end; end; procedure TAutoTablesResource.SetResponseStatus(StatusResult,StatusMessage: String; var ResponseStream: TMemoryStream); var StrStream: TStringStream; JSONStatus: TJSONObject; begin StrStream := TStringStream.Create; JSONStatus := TJSONObject.Create; JSONStatus.AddPair('status', StatusResult); if StatusMessage<>'' then JSONStatus.AddPair('message', StatusMessage); StrStream.WriteString(JSONStatus.ToJSON); StrStream.Position := 0; JSONStatus.Free; StrStream.SavetoStream(ResponseStream); end; // https://stackoverflow.com/questions/4186458/delphi-call-a-function-whose-name-is-stored-in-a-string function TAutoTablesResource.Call(MethodName: string; AContext: TEndpointContext; ARequest: TEndpointRequest; AResponse: TEndpointResponse): TMemoryStream; var M: TMethod; begin M.Code := Self.MethodAddress(MethodName); //find method code M.Data := Pointer(Self); //store pointer to object instance Result := TMyFuncType(m)(AContext, ARequest, AResponse); end; procedure TAutoTablesResource.SaveDataSetToCSV(ADataSet: TFDDataSet; AStream: TStream); begin FDBatchMoveDataSetReader.DataSet := ADataSet; FDBatchMoveTextWriter.Stream := TMemoryStream.Create; FDBatchMoveCSV.Execute; TMemoryStream(FDBatchMoveTextWriter.Stream).Position := 0; TMemoryStream(FDBatchMoveTextWriter.Stream).SaveToStream(AStream); TMemoryStream(FDBatchMoveTextWriter.Stream).Free; end; procedure TAutoTablesResource.SaveDataSetToStream(ADataSet: TFDDataSet; AStream: TStream; AContext: TEndpointContext); var AFormat: String; begin AContext.Request.Params.TryGetValue('format',AFormat); if SameText(AFormat,CSV_FORMAT) then begin SaveDataSetToCSV(ADataSet,AStream); end else ADataSet.SaveToStream(AStream,GetStorageFormat(AFormat)); end; function TAutoTablesResource.ProcessGet(const EndPoint: String; AContext: TEndpointContext; ARequest: TEndpointRequest; AResponse: TEndpointResponse): TMemoryStream; var DataTable: TFDTable; SL: TStringList; I, II: Integer; StatusResult,StatusMessage: String; SQLList: TStringList; begin Result := TMemoryStream.Create; if EndPoints.DataSet.Locate('EndPoint;RequestType',VarArrayOf([EndPoint,'GET']),[])=True then begin if PermissionsCheck(EndPoints.DataSet.FieldByName(FIELD_GROUPS).AsString,AContext)=True then begin { if EndPoints.DataSet.FieldByName(FIELD_ACTION).AsString='Table' then begin DataTable := TFDTable.Create(Self); DataTable.Connection := FDConnectionIB; //DataTable.LocalSQL := FDLocalSQL1; DataTable.Open(EndPoints.DataSet.FieldByName(FIELD_TABLENAME).AsString); DataTable.SaveToStream(Result,GetStorageFormat(AContext)); DataTable.Close; DataTable.Free; end else } if (EndPoints.DataSet.FieldByName(FIELD_ACTION).AsString='SQL') OR (EndPoints.DataSet.FieldByName(FIELD_ACTION).AsString='Table') then begin if (EndPoints.DataSet.FieldByName(FIELD_ACTION).AsString='Table') then begin EndPointQuery.SQL.Text := 'SELECT * FROM !TableName'; EndPointQuery.MacroByName('TableName').AsRaw := EndPoints.DataSet.FieldByName(FIELD_TABLENAME).AsString; end else EndPointQuery.SQL.Text := EndPoints.DataSet.FieldByName(FIELD_SQL).AsString; ResolveCustomMacros(EndPoints.DataSet.FieldByName(FIELD_MACROS).AsString, EndPointQuery, ARequest); ResolveCustomParams(EndPoints.DataSet.FieldByName(FIELD_PARAMS).AsString, EndPointQuery, ARequest); ResolveDefaultParams(EndPointQuery, AContext); EndPointQuery.Open; SaveDataSetToStream(EndPointQuery,Result,AContext); end else if EndPoints.DataSet.FieldByName(FIELD_ACTION).AsString='AggregateSQL' then begin SQLList := TStringList.Create; SQLList.Text := EndPoints.DataSet.FieldByName(FIELD_SQL).AsString; for I := 0 to SQLList.Count-1 do begin AggregateSQL.FieldDefs.Add(SQLList.Names[I],ftMemo); end; AggregateSQL.Open; AggregateSQL.Edit; for I := 0 to SQLList.Count-1 do begin EndPointQuery.SQL.Text := SQLList.ValueFromIndex[I]; ResolveCustomMacros(EndPoints.DataSet.FieldByName(FIELD_MACROS).AsString, EndPointQuery, ARequest); ResolveCustomParams(EndPoints.DataSet.FieldByName(FIELD_PARAMS).AsString, EndPointQuery, ARequest); ResolveDefaultParams(EndPointQuery, AContext); EndPointQuery.Open; EndPointQuery.First; AggregateSQL.FieldByName(SQLList.Names[I]).AsString := EndPointQuery.FieldByName(SQLList.Names[I]).AsString; EndPointQuery.Close; end; AggregateSQL.Post; SQLList.Free; SaveDataSetToStream(AggregateSQL,Result,AContext); end else if EndPoints.DataSet.FieldByName(FIELD_ACTION).AsString='Method' then begin try Result := Call(EndPoints.DataSet.FieldByName(FIELD_METHOD).AsString, AContext, ARequest, AResponse); except on E: Exception do begin AResponse.RaiseBadRequest('Bad Request',E.Message); end; end; end; end else AResponse.RaiseUnauthorized('Unauthorized','Group permissions do not allow access to this endpoint.'); end else AResponse.RaiseNotFound('Not Found','Requested endpoint not found.'); end; function TAutoTablesResource.GetTableGenerator(AConnection: TFDConnection; ATableName: String): String; var QuerySource: String; GenQuery: TFDQuery; AGenName: String; begin if (AConnection.DriverName='IB') OR (AConnection.DriverName='FB') OR (AConnection.DriverName='IBLITE') then begin GenQuery := TFDQuery.Create(Self); GenQuery.Connection := AConnection; GenQuery.Open('SELECT T.RDB$TRIGGER_SOURCE FROM RDB$TRIGGERS T, RDB$TYPES Y'+' WHERE T.RDB$RELATION_NAME=:P1 AND T.RDB$TRIGGER_NAME NOT LIKE ''CHECK%'' AND Y.RDB$FIELD_NAME=''RDB$TRIGGER_TYPE'' AND Y.RDB$TYPE_NAME=''PRE_STORE'' AND T.RDB$TRIGGER_TYPE=Y.RDB$TYPE',[ATableName]); GenQuery.First; if GenQuery.FindField('RDB$TRIGGER_SOURCE')<>nil then begin QuerySource := GenQuery.FieldByName('RDB$TRIGGER_SOURCE').AsWideString; AGenName := QuerySource.Substring(QuerySource.IndexOf('GEN_ID(')+7); AGenName := AGenName.Replace(AGenName.Substring(AGenName.IndexOf(',')),''); Result := AGenName; end; GenQuery.Close; GenQuery.Free; end; end; function TAutoTablesResource.ProcessPost(const EndPoint: String; AContext: TEndpointContext; ARequest: TEndpointRequest; AResponse: TEndpointResponse): TMemoryStream; var I, II: Integer; AStream: TStream; ResponseTable: TFDMemTable; RequestTable: TFDMemTable; DataTable: TFDQuery; SL: TStringList; CanPostData: Boolean; AggregateSQL: TFDMemTable; SQLList: TStringList; AGenName: String; begin Result := TMemoryStream.Create; if EndPoints.DataSet.Locate('EndPoint;RequestType',VarArrayOf([EndPoint,'POST']),[])=True then begin if PermissionsCheck(EndPoints.DataSet.FieldByName(FIELD_GROUPS).AsString,AContext)=True then begin if EndPoints.DataSet.FieldByName(FIELD_TABLENAME).AsString<>'' then begin RequestTable := TFDMemTable.Create(Self); if ARequest.Body.TryGetStream(AStream)=True then begin if ARequest.Body.ContentType='application/json' then RequestTable.LoadFromStream(AStream,TFDStorageFormat.sfJSON) else if (ARequest.Body.ContentType='application/xml') OR (ARequest.Body.ContentType='text/xml') then RequestTable.LoadFromStream(AStream,TFDStorageFormat.sfXML) else RequestTable.LoadFromStream(AStream,TFDStorageFormat.sfBINARY) end; RequestTable.First; DataTable := TFDQuery.Create(Self); DataTable.Connection := FDConnection; //DataTable.LocalSQL := FDLocalSQL1; DataTable.Open('SELECT * FROM ' + EndPoints.DataSet.FieldByName(FIELD_TABLENAME).AsString + ' WHERE 0=1'); AGenName := GetTableGenerator(FDConnection, EndPoints.DataSet.FieldByName(FIELD_TABLENAME).AsString); ResponseTable := TFDMemTable.Create(Self); ResponseTable.FieldDefs.Add(EndPoints.DataSet.FieldByName(FIELD_UNIQUEID).AsString,TFieldType.ftLargeint); ResponseTable.Open; while not RequestTable.EOF do begin CanPostData := False; if RequestTable.FieldByName(EndPoints.DataSet.FieldByName(FIELD_UNIQUEID).AsString).AsInteger=0 then begin DataTable.Append; CanPostData := True; end else begin if DataTable.Locate(EndPoints.DataSet.FieldByName(FIELD_UNIQUEID).AsString,RequestTable.FieldByName(EndPoints.DataSet.FieldByName(FIELD_UNIQUEID).AsString).AsString,[])=True then begin DataTable.Edit; CanPostData := True; end; end; if CanPostData=True then begin for I := 0 to DataTable.FieldDefs.Count-1 do begin if DataTable.FieldDefs.Items[I].Name.ToUpper=EndPoints.DataSet.FieldByName(FIELD_UNIQUEID).AsString then begin DataTable.FieldByName(DataTable.FieldDefs.Items[I].Name).Required := False; end else begin if RequestTable.FieldDefs.Find(DataTable.FieldDefs.Items[I].Name)<>nil then begin DataTable.FieldByName(DataTable.FieldDefs.Items[I].Name).AsString := RequestTable.FieldByName(DataTable.FieldDefs.Items[I].Name).AsString; end; end; end; DataTable.Post; ResponseTable.AppendRecord([VarToStr(FDConnection.GetLastAutoGenValue(AGenName))]); end; RequestTable.Next; end; SaveDataSetToStream(ResponseTable,Result,AContext); ResponseTable.Free; RequestTable.Free; end else if EndPoints.DataSet.FieldByName(FIELD_ACTION).AsString='SQL' then begin EndPointQuery.SQL.Text := EndPoints.DataSet.FieldByName(FIELD_SQL).AsString; ResolveCustomMacros(EndPoints.DataSet.FieldByName(FIELD_MACROS).AsString, EndPointQuery, ARequest); ResolveCustomParams(EndPoints.DataSet.FieldByName(FIELD_PARAMS).AsString, EndPointQuery, ARequest); ResolveDefaultParams(EndPointQuery, AContext); EndPointQuery.Open; SaveDataSetToStream(EndPointQuery,Result,AContext); end else if EndPoints.DataSet.FieldByName(FIELD_ACTION).AsString='AggregateSQL' then begin SQLList := TStringList.Create; SQLList.Text := EndPoints.DataSet.FieldByName(FIELD_SQL).AsString; for I := 0 to SQLList.Count-1 do begin AggregateSQL.FieldDefs.Add(SQLList.Names[I],ftString,512,False); end; AggregateSQL.Open; AggregateSQL.Edit; for I := 0 to SQLList.Count-1 do begin EndPointQuery.SQL.Text := SQLList.ValueFromIndex[I]; ResolveCustomMacros(EndPoints.DataSet.FieldByName(FIELD_MACROS).AsString, EndPointQuery, ARequest); ResolveCustomParams(EndPoints.DataSet.FieldByName(FIELD_PARAMS).AsString, EndPointQuery, ARequest); ResolveDefaultParams(EndPointQuery, AContext); EndPointQuery.Open; EndPointQuery.First; AggregateSQL.FieldByName(SQLList.Names[I]).AsString := EndPointQuery.FieldByName(SQLList.Names[I]).AsString; EndPointQuery.Close; end; AggregateSQL.Post; SQLList.Free; SaveDataSetToStream(AggregateSQL,Result,AContext); end else if EndPoints.DataSet.FieldByName(FIELD_ACTION).AsString='Method' then begin try Result := Call(EndPoints.DataSet.FieldByName(FIELD_METHOD).AsString, AContext, ARequest, AResponse); except on E: Exception do begin AResponse.RaiseBadRequest('Bad Request',E.Message); end; end; end; end else AResponse.RaiseUnauthorized('Unauthorized','Group permissions do not allow access to this endpoint.'); end else AResponse.RaiseNotFound('Not Found','Requested endpoint not found.'); end; function TAutoTablesResource.ProcessDelete(const EndPoint: String; AContext: TEndpointContext; ARequest: TEndpointRequest; AResponse: TEndpointResponse): TMemoryStream; var RowId: String; RowsAffected: Integer; ResponseTable: TFDMemTable; begin Result := TMemoryStream.Create; if EndPoints.DataSet.Locate('EndPoint;RequestType',VarArrayOf([EndPoint,'DELETE']),[])=True then begin if PermissionsCheck(EndPoints.DataSet.FieldByName(FIELD_GROUPS).AsString,AContext)=True then begin if ARequest.Params.TryGetValue(EndPoints.DataSet.FieldByName(FIELD_UNIQUEID).AsString,RowId)=True then begin if EndPoints.DataSet.FieldByName(FIELD_TABLENAME).AsString<>'' then begin EndPointQuery.ExecSQL('DELETE FROM '+EndPoints.DataSet.FieldByName(FIELD_TABLENAME).AsString+' WHERE ID=:P1',[RowId]); RowsAffected := EndPointQuery.RowsAffected; end else if EndPoints.DataSet.FieldByName(FIELD_SQL).AsString<>'' then begin EndPointQuery.ExecSQL(EndPoints.DataSet.FieldByName(FIELD_SQL).AsString,[RowId]); RowsAffected := EndPointQuery.RowsAffected; end else if EndPoints.DataSet.FieldByName(FIELD_METHOD).AsString<>'' then begin try Result := Call(EndPoints.DataSet.FieldByName(FIELD_METHOD).AsString, AContext, ARequest, AResponse); except on E: Exception do begin AResponse.RaiseBadRequest('Bad Request',E.Message); end; end; end; end; end else AResponse.RaiseUnauthorized('Unauthorized','Group permissions do not allow access to this endpoint.'); ResponseTable := TFDMemTable.Create(Self); ResponseTable.FieldDefs.Add('RowsAffected',TFieldType.ftLargeint); ResponseTable.Open; ResponseTable.AppendRecord([RowsAffected]); SaveDataSetToStream(ResponseTable,Result,AContext); ResponseTable.Free; end else AResponse.RaiseNotFound('Not Found','Requested endpoint not found.'); end; function TAutoTablesResource.GetFormatMimeType(AContext: TEndpointContext): String; var AFormat: String; begin AContext.Request.Params.TryGetValue('format',AFormat); if SameText(AFormat,CSV_FORMAT) then begin Result := CSV_MIME_TYPE; end else if SameText(AFormat,XML_FORMAT) then begin Result := XML_MIME_TYPE; end else if SameText(AFormat,BINARY_FORMAT) then begin Result := BINARY_MIME_TYPE; end else begin Result := JSON_MIME_TYPE; end; end; function TAutoTablesResource.GetStorageFormat(const AFormat: String): TFDStorageFormat; begin if SameText(AFormat,CSV_FORMAT) then begin Result := TFDStorageFormat.sfAuto; end else if SameText(AFormat,XML_FORMAT) then begin Result := TFDStorageFormat.sfXML; end else if SameText(AFormat,BINARY_FORMAT) then begin Result := TFDStorageFormat.sfBinary; end else begin Result := TFDStorageFormat.sfJSON; end; end; function TAutoTablesResource.ProcessRequest(const EndPoint, RequestType: String; AContext: TEndpointContext; ARequest: TEndpointRequest; AResponse: TEndpointResponse): TMemoryStream; begin if EndpointQuery.Connection=nil then EndpointQuery.Connection := FDConnection; if GetFormatMimeType(AContext)=CSV_MIME_TYPE then AResponse.Headers.SetValue('Content-Disposition', 'attachment;filename=export.csv'); if RequestType=GET_REQUEST_TYPE then begin Result := ProcessGet(EndPoint, AContext, ARequest, AResponse); end else if RequestType=POST_REQUEST_TYPE then begin Result := ProcessPost(EndPoint, AContext, ARequest, AResponse); end else if RequestType=DELETE_REQUEST_TYPE then begin Result := ProcessDelete(EndPoint, AContext, ARequest, AResponse); end; end; procedure TAutoTablesResource.Get(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse); begin // Sample code AResponse.Body.SetStream(ProcessRequest(ARequest.Params.Values['endpoint'],GET_REQUEST_TYPE, AContext, ARequest, AResponse),GetFormatMimeType(AContext),True); end; procedure TAutoTablesResource.Post(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse); begin AResponse.Body.SetStream(ProcessRequest(ARequest.Params.Values['endpoint'],POST_REQUEST_TYPE, AContext, ARequest, AResponse),GetFormatMimeType(AContext),True); end; procedure TAutoTablesResource.DeleteItem(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse); begin AResponse.Body.SetStream(ProcessRequest(ARequest.Params.Values['endpoint'],DELETE_REQUEST_TYPE, AContext, ARequest, AResponse),GetFormatMimeType(AContext),True); end; procedure Register; begin RegisterResource(TypeInfo(TAutoTablesResource)); end; initialization Register; end.
unit u_ast; {$mode objfpc}{$H+} interface uses Classes, SysUtils, u_tokens; type TMashBaseAST = class protected lastTk: TMashToken; public tokens: TList; nodes: TList; constructor Create(_tokens: TList); destructor Destroy; override; // Routines for tokens function Token(index: cardinal): TMashToken; inline; function NextToken(var index: cardinal): TMashToken; inline; function TkNotNull(tk: TMashToken): TMashToken; inline; function TkValue(tk: TMashToken): string; inline; function TkID(tk: TMashToken): TMashTokenID; inline; function TkCheck(tk: TMashToken): string; inline; function TkCheckID(tk: TMashToken): TMashTokenID; inline; function TkCheckType(tk: TMashToken): TMashTokenType; inline; function TkTokenValue(tk: TMashToken): string; inline; function TkTokenID(tk: TMashToken): TMashTokenID; inline; function TkWordValue(tk: TMashToken): string; inline; function TkStrValue(tk: TMashToken): string; inline; function TkDigitValue(tk: TMashToken): string; inline; end; implementation constructor TMashBaseAST.Create(_tokens: TList); begin self.tokens := _tokens; self.nodes := TList.Create; self.lastTk := nil; end; destructor TMashBaseAST.Destroy; begin FreeAndNil(self.nodes); end; function TMashBaseAST.Token(index: cardinal): TMashToken; begin if index < self.tokens.count then Result := TMashToken(self.tokens[index]) else Result := nil; end; function TMashBaseAST.NextToken(var index: cardinal): TMashToken; var tk: TMashToken; begin tk := self.Token(index); while tk <> nil do begin if tk.info <> ttEndOfLine then break; Inc(index); tk := self.Token(index); end; Result := tk; end; function TMashBaseAST.TkNotNull(tk: TMashToken): TMashToken; begin Result := tk; if tk = nil then raise Exception.Create( 'Invalid construction at line ' + IntToStr(self.lastTk.line + 1) + ' at file ''' + self.lastTk.filep^ + '''.' ); end; function TMashBaseAST.TkValue(tk: TMashToken): string; begin if tk = nil then raise Exception.Create( 'Invalid construction at line ' + IntToStr(self.lastTk.line + 1) + ' at file ''' + self.lastTk.filep^ + '''.' ); Result := tk.value; end; function TMashBaseAST.TkID(tk: TMashToken): TMashTokenID; begin if tk = nil then raise Exception.Create( 'Invalid construction at line ' + IntToStr(self.lastTk.line + 1) + ' at file ''' + self.lastTk.filep^ + '''.' ); Result := tk.short; end; function TMashBaseAST.TkCheck(tk: TMashToken): string; begin if tk <> nil then Result := tk.value else Result := ''; end; function TMashBaseAST.TkCheckID(tk: TMashToken): TMashTokenID; begin if tk <> nil then Result := tk.short else Result := tkNull; end; function TMashBaseAST.TkCheckType(tk: TMashToken): TMashTokenType; begin if tk <> nil then Result := tk.info else Result := ttNull; end; function TMashBaseAST.TkTokenValue(tk: TMashToken): string; begin if tk = nil then raise Exception.Create( 'Invalid construction at line ' + IntToStr(self.lastTk.line + 1) + ' at file ''' + self.lastTk.filep^ + ''', here should be language token.' ); if tk.info = ttToken then Result := tk.value else raise Exception.Create( 'Invalid token (' + tk.value + ') at line ' + IntToStr(tk.line + 1) + ' at file ''' + tk.filep^ + ''', here should be language token.' ); end; function TMashBaseAST.TkTokenID(tk: TMashToken): TMashTokenID; begin if tk = nil then raise Exception.Create( 'Invalid construction at line ' + IntToStr(self.lastTk.line + 1) + ' at file ''' + self.lastTk.filep^ + ''', here should be language token.' ); if tk.info = ttToken then Result := tk.short else raise Exception.Create( 'Invalid token (' + tk.value + ') at line ' + IntToStr(tk.line + 1) + ' at file ''' + tk.filep^ + ''', here should be language token.' ); end; function TMashBaseAST.TkWordValue(tk: TMashToken): string; begin if tk = nil then raise Exception.Create( 'Invalid construction at line ' + IntToStr(self.lastTk.line + 1) + ' at file ''' + self.lastTk.filep^ + ''', here should be word.' ); if tk.info = ttWord then Result := tk.value else raise Exception.Create( 'Invalid token (' + tk.value + ') at line ' + IntToStr(tk.line + 1) + ' at file ''' + tk.filep^ + ''', here should be word.' ); end; function TMashBaseAST.TkStrValue(tk: TMashToken): string; begin if tk = nil then raise Exception.Create( 'Invalid construction at line ' + IntToStr(self.lastTk.line + 1) + ' at file ''' + self.lastTk.filep^ + ''', here should be string constant.' ); if tk.info = ttString then Result := tk.value else raise Exception.Create( 'Invalid token (' + tk.value + ') at line ' + IntToStr(tk.line + 1) + ' at file ''' + tk.filep^ + ''', here should be string constant.' ); end; function TMashBaseAST.TkDigitValue(tk: TMashToken): string; begin if tk = nil then raise Exception.Create( 'Invalid construction at line ' + IntToStr(self.lastTk.line + 1) + ' at file ''' + self.lastTk.filep^ + ''', here should be digit constant.' ); if tk.info = ttDigit then Result := tk.value else raise Exception.Create( 'Invalid token (' + tk.value + ') at line ' + IntToStr(tk.line + 1) + ' at file ''' + tk.filep^ + ''', here should be digit constant.' ); end; end.
unit ibSHAutoReplace; interface uses Classes, Forms, SysUtils, Menus, SHDesignIntf, SHOptionsIntf, SHEvents, ibSHDesignIntf, ibSHConsts, pSHIntf, pSHAutoComplete; type TibBTAutoReplace = class(TSHComponent, ISHDemon, IpSHAutoComplete, IibSHAutoReplace) private FAutoComplete: TpSHAutoComplete; procedure DoOnOptionsChanged; protected {IpSHAutoComplete} function GetAutoComplete: TComponent; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; class function GetClassIIDClassFnc: TGUID; override; function ReceiveEvent(AEvent: TSHEvent): Boolean; override; property AutoComplete: TpSHAutoComplete read FAutoComplete; published end; implementation procedure Register; begin SHRegisterComponents([TibBTAutoReplace]); end; constructor TibBTAutoReplace.Create(AOwner: TComponent); var vDataRootDirectory: ISHDataRootDirectory; begin inherited Create(AOwner); FAutoComplete := TpSHAutoComplete.Create(nil); FAutoComplete.ShortCut := Menus.ShortCut(Ord(' '), []); if Supports(Designer.GetDemon(IibSHBranch), ISHDataRootDirectory, vDataRootDirectory) and FileExists(vDataRootDirectory.DataRootDirectory + InterBaseAutoReplaceFileName) then FAutoComplete.LoadFromFile(vDataRootDirectory.DataRootDirectory + InterBaseAutoReplaceFileName); DoOnOptionsChanged; end; destructor TibBTAutoReplace.Destroy; begin FAutoComplete.Free; inherited; end; function CodeCaseConv(AEditorCaseCode: TSHEditorCaseCode): TpSHCaseCode; begin case AEditorCaseCode of Lower: Result := ccLower; Upper: Result := ccUpper; NameCase: Result := ccNameCase; FirstUpper: Result := ccFirstUpper; None: Result := ccNone; Invert: Result := ccInvert; Toggle: Result := ccToggle; else Result := ccUpper; end; end; procedure TibBTAutoReplace.DoOnOptionsChanged; var vEditorCodeInsightOptions: ISHEditorCodeInsightOptions; begin if Supports(Designer.GetDemon(ISHEditorCodeInsightOptions), ISHEditorCodeInsightOptions, vEditorCodeInsightOptions) then begin FAutoComplete.CaseSQLCode := CodeCaseConv(vEditorCodeInsightOptions.CaseSQLKeywords); end; end; class function TibBTAutoReplace.GetClassIIDClassFnc: TGUID; begin Result := IibSHAutoReplace; end; function TibBTAutoReplace.ReceiveEvent(AEvent: TSHEvent): Boolean; begin with AEvent do case Event of SHE_OPTIONS_CHANGED: DoOnOptionsChanged; end; Result := inherited ReceiveEvent(AEvent); end; function TibBTAutoReplace.GetAutoComplete: TComponent; begin Result := FAutoComplete; end; initialization Register; end.
unit Demo.AreaChart.Stacking; interface uses System.Classes, System.Variants, Demo.BaseFrame, cfs.GCharts; type TDemo_AreaChart_Stacking = class(TDemoBaseFrame) public procedure GenerateChart; override; end; implementation procedure TDemo_AreaChart_Stacking.GenerateChart; var // Defined as TInterfacedObject No need try..finally Data: IcfsGChartData; ChartNotStacked: IcfsGChartProducer; ChartStacked: IcfsGChartProducer; ChartStacked100: IcfsGChartProducer; begin // Data Data := TcfsGChartData.Create; Data.DefineColumns([ TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Year'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Cars'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Trucks'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Drones'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Segways') ]); Data.AddRow(['2013', 870, 460, 10, 120]); Data.AddRow(['2014', 460, 720, 20, 60]); Data.AddRow(['2015', 930, 540, 140, 30]); Data.AddRow(['2016', 1000, 400, 80, Null]); // Chart Not Stacked ChartNotStacked := TcfsGChartProducer.Create; ChartNotStacked.ClassChartType := TcfsGChartProducer.CLASS_AREA_CHART; ChartNotStacked.Data.Assign(Data); ChartNotStacked.Options.Title('Not Stacked'); ChartNotStacked.Options.Legend('position', 'top'); ChartNotStacked.Options.Legend('maxLines', 3); // Chart Stacked ChartStacked := TcfsGChartProducer.Create; ChartStacked.ClassChartType := TcfsGChartProducer.CLASS_AREA_CHART; ChartStacked.Data.Assign(Data); ChartStacked.Options.Title('Stacked'); ChartStacked.Options.IsStacked(True); ChartStacked.Options.Legend('position', 'top'); ChartStacked.Options.Legend('maxLines', 3); // ChartStacked 100 % ChartStacked100 := TcfsGChartProducer.Create; ChartStacked100.ClassChartType := TcfsGChartProducer.CLASS_AREA_CHART; ChartStacked100.Data.Assign(Data); ChartStacked100.Options.Title('Stacked 100%'); ChartStacked100.Options.IsStacked('relative'); ChartStacked100.Options.Legend('position', 'top'); ChartStacked100.Options.Legend('maxLines', 3); ChartStacked100.Options.VAxis('minValue', 0); ChartStacked100.Options.VAxis('ticks', '[0, .3, .6, .9, 1]'); // Generate GChartsFrame.DocumentInit; GChartsFrame.DocumentSetBody( '<div style="display: flex; width: 100%; height: 50%;">' + '<div id="ChartStacked" style="width: 50%"></div>' + '<div id="ChartStacked100" style="flex-grow: 1;"></div>' + '</div>' + '<div style="display: flex; width: 100%; height: 50%;">' + '<div style="width: 25%"></div>' + '<div id="ChartNotStacked" style="width: 50%"></div>' + '<div style="width: 25%"></div>' + '</div>' ); GChartsFrame.DocumentGenerate('ChartNotStacked', ChartNotStacked); GChartsFrame.DocumentGenerate('ChartStacked', ChartStacked); GChartsFrame.DocumentGenerate('ChartStacked100', ChartStacked100); GChartsFrame.DocumentPost; end; initialization RegisterClass(TDemo_AreaChart_Stacking); end.
unit Dmitry.Utils.Network; interface {$WARN SYMBOL_PLATFORM OFF} uses Winapi.Windows, System.SysUtils, System.Classes; type TWNetOpenEnumW = function(dwScope, dwType, dwUsage: DWORD; lpNetResource: PNetResourceW; var lphEnum: THandle): DWORD stdcall; TWNetEnumResourceW = function(hEnum: THandle; var lpcCount: DWORD; lpBuffer: Pointer; var lpBufferSize: DWORD): DWORD stdcall; TWNetCloseEnumW = function(hEnum: THandle): DWORD stdcall; TWNetGetProviderNameW = function(dwNetType: DWORD; lpProviderName: PWideChar; var lpBufferSize: DWORD): DWORD stdcall; TWNetGetResourceParentW = function(lpNetResource: PNetResourceW; lpBuffer: Pointer; var cbBuffer: DWORD): DWORD stdcall; function FillNetLevel(Xxx: PNetResourceW; List: TStrings): Word; function FindAllComputers(Workgroup: string; Computers: TStrings): Cardinal; function GetResourceParent(ComputerName: string): string; function GetNetDrivePath(dr: Char): string; function WNetGetConnectionDelayed(lpLocalName: PWideChar; lpRemoteName: PWideChar; var lpnLength: DWORD): DWORD; stdcall; external mpr name 'WNetGetConnectionW' delayed; implementation var MPRDllHandle : THandle = 0; WNetOpenEnumW : TWNetOpenEnumW; WNetEnumResourceW : TWNetEnumResourceW; WNetCloseEnumW : TWNetCloseEnumW; WNetGetProviderNameW : TWNetGetProviderNameW; WNetGetResourceParentW : TWNetGetResourceParentW; function GetNetDrivePath(dr: Char): string; var sz: DWORD; begin Result := ''; sz := MAX_PATH; SetLength(Result, sz + 1); FillChar(Result[1], sz, #0); if WNetGetConnectionDelayed(PChar(Dr + ':'), PChar(Result), sz) = NO_ERROR then Result := Trim(Copy(Result, 1, Pos(#0, Result))); end; procedure InitInet; begin if MPRDllHandle = 0 then begin MPRDllHandle := LoadLibrary(mpr); WNetOpenEnumW := GetProcAddress(MPRDllHandle, 'WNetOpenEnumW'); WNetEnumResourceW := GetProcAddress(MPRDllHandle, 'WNetEnumResourceW'); WNetCloseEnumW := GetProcAddress(MPRDllHandle, 'WNetCloseEnum'); WNetGetProviderNameW := GetProcAddress(MPRDllHandle, 'WNetGetProviderNameW'); WNetGetResourceParentW := GetProcAddress(MPRDllHandle, 'WNetGetResourceParentW'); end; end; function FillNetLevel(Xxx: PNetResourceW; List: TStrings): Word; const NetRecorsPacket = 10; type PNRArr = ^TNRArr; TNRArr = array [0 .. NetRecorsPacket] of TNetResource; var X: PNRArr; Tnr: TNetResource; I: Integer; EntrReq, SizeReq: Cardinal; Twx: NativeUInt; WSName: string; begin InitInet; Result := WNetOpenEnumW(RESOURCE_GLOBALNET, RESOURCETYPE_ANY, RESOURCEUSAGE_CONTAINER, Xxx, Twx); if Result = ERROR_NO_NETWORK then Exit; if Result = NO_ERROR then begin New(X); EntrReq := 1; SizeReq := SizeOf(TNetResource) * NetRecorsPacket; while (Twx <> 0) and (WNetEnumResourceW(Twx, EntrReq, X, SizeReq) <> ERROR_NO_MORE_ITEMS) do begin for I := 0 to EntrReq - 1 do begin Move(X^[I], Tnr, SizeOf(Tnr)); case Tnr.DwDisplayType of RESOURCEDISPLAYTYPE_DOMAIN: begin if Tnr.LpRemoteName <> '' then WSName := Tnr.LpRemoteName else WSName := Tnr.LpComment; List.Add(WSName); end; RESOURCEDISPLAYTYPE_NETWORK: FillNetLevel(@Tnr, List); end; end; end; Dispose(X); WNetCloseEnumW(Twx); end; end; function FindAllComputers(Workgroup: string; Computers: TStrings): Cardinal; const NetRecorsPacket = 10; var EnumHandle: THandle; WorkgroupRS: TNetResource; Buf: array [1 .. NetRecorsPacket] of TNetResource; BufSize: Cardinal; Entries: Cardinal; begin InitInet; Computers.Clear; Workgroup := Workgroup + #0; FillChar(WorkgroupRS, SizeOf(WorkgroupRS), 0); with WorkgroupRS do begin DwScope := 2; DwType := 3; DwDisplayType := 1; DwUsage := 2; LpRemoteName := @Workgroup[1]; end; WNetOpenEnumW(RESOURCE_GLOBALNET, RESOURCETYPE_ANY, 0, @WorkgroupRS, EnumHandle); repeat Entries := 1; BufSize := SizeOf(Buf); Result := WNetEnumResourceW(EnumHandle, Entries, @Buf, BufSize); if (Result = NO_ERROR) and (Entries = 1) then Computers.Add(StrPas(Buf[1].LpRemoteName)) until (Entries <> 1) or (Result <> NO_ERROR); WNetCloseEnumW(EnumHandle); end; function GetResourceParent(ComputerName: string): string; var LpNetResource, LpNet: PNetResource; CbBuffer: DWORD; DwNetType: Cardinal; LpProviderName: PWideChar; begin InitInet; CbBuffer := 1000; DwNetType := WNNC_NET_LANMAN; GetMem(LpProviderName, CbBuffer); if WNetGetProviderNameW(DwNetType, LpProviderName, CbBuffer) = 0 then begin GetMem(LpNet, 1000); New(LpNetResource); CbBuffer := 1000; LpNetResource^.LpLocalName := nil; LpNetResource^.DwScope := 0; LpNetResource^.DwDisplayType := 0; LpNetResource^.DwUsage := 0; LpNetResource^.LpComment := nil; LpNetResource^.LpRemoteName := PWideChar(ComputerName); LpNetResource^.DwType := RESOURCETYPE_ANY; LpNetResource^.LpProvider := LpProviderName; if WNetGetResourceParentW(LpNetResource, LpNet, CbBuffer) = 0 then begin Result := StrPas(Lpnet^.LpRemoteName); end; FreeMem(LpNetResource); FreeMem(LpNet); end; Freemem(LpProviderName); end; end.
{$I eDefines.inc} unit iec104utils; interface uses SysUtils; // максимальное количество подключений const MAX_CLIENT_COUNT = 32; MAX_COMMANDS_COUNT = 128; type TIECFunctionFormat = (I_Format, S_Format, U_Format); TASDUDataBlockId = record ASDUType: Byte; // идентификатор типа NumberOfObjects: Byte; // количество объектов информации COT: Byte; // причина передачи SQ: Boolean; // формат "Information Object" Test: Boolean; // test PN: Boolean; // positiv/negativ ORG: Byte; // адрес инициатора, может отсутствовать! ASDUAddress: Word; // общий адрес ASDU end; TInformationObject = class private FASDUType: Byte; // идентификатор типа для общего опроса FSASDUType: Byte; // идентификатор типа для спонтанной передачи FIOAddress: LongWord; // адрес объекта информации FGroup: Integer; // группа, если 0, то не группа не используется FQuality: Boolean; // FChangeStatus: array[0..MAX_CLIENT_COUNT-1] of Boolean; // признаки изменений для каждого соединения FDataReady: Boolean; // значение установлено // FDT: TDateTime; // метка времени FDTValid: Boolean; FValue: Variant; // значение // function ByteValue(const AIndex: Integer = -1): Byte; function SingleValue(const AIndex: Integer = -1): Single; function IntegerValue(const AIndex: Integer = -1): Integer; function SmallIntValue(const AIndex: Integer = -1): SmallInt; function WordValue(const AIndex: Integer = -1): Word; function LWordValue(const AIndex: Integer = -1): LongWord; function DateTimeValue(const AIndex: Integer = -1): TDateTime; // function SIQ: Byte; function DIQ: Byte; function SEP: Byte; // Single event of protection equipment public constructor Create(AASDUType, ASASDUType: Byte; AIOAddress: LongWord; AGroup: Integer); // procedure SetValue(AValue: Variant); procedure SetBadQuality(); // function EncodeIOData(ASDU: PByteArray; ASpont: Boolean): Integer; // function ASDUType(ASpont: Boolean): Byte; function NeedSporadic(AIndex: Integer): Boolean; function SporadicSupported: Boolean; // procedure ClearChangeStatus(AIndex: Integer); procedure SetChangeStatus; // property IOAddress: LongWord read FIOAddress; property DataReady: Boolean read FDataReady; property Group: Integer read FGroup; end; // тип функции function IECFunctionFormat(B: Byte): TIECFunctionFormat; // передаваемый порядковый номер function IECGetNS(Buf: PByteArray): Word; // принимаемый порядковый номер function IECGetNR(Buf: PByteArray): Word; // function decodeCP56Time2a(Buf: PByteArray; var DT: TDateTime): Integer; // function encodeCP56Time2a(Buf: PByteArray; DT: TDateTime; ADTValid: Boolean): Integer; // function encodeCP24Time2a(Buf: PByteArray; DT: TDateTime; ADTValid: Boolean): Integer; // function decodeUInt16(Buf: PByteArray; var CP16: Word): Integer; // function encodeUInt16(Buf: PByteArray; CP16: Word): Integer; // function decodeUInt32(Buf: PByteArray; var CP32: LongWord): Integer; // function QCCDescription(V: Byte): String; implementation uses DateUtils, variants, iec104time, iec104defs; type TQualityElement = (qeBL, qeSB, qeNT, qeIV, qeOV, qeEI); TQDS = set of TQualityElement; // элементы описателя качества: // BL - блокировка значения // SB - есть замещение значения // NT - неактуальное значение // IV - недействительное значение // OV - есть переполнение // EI - elapsed time invalid function encodeQDS(const Quality: TQDS): Byte; var QDS: Byte; begin QDS:= 0; If qeBL in Quality then QDS:= QDS or $10; // BL - блокировка значения If qeSB in Quality then QDS:= QDS or $20; // SB - есть замещение значения If qeNT in Quality then QDS:= QDS or $40; // NT - неактуальное значение If qeIV in Quality then QDS:= QDS or $80; // IV - недействительное значения If qeOV in Quality then QDS:= QDS or $01; // OV - есть переполнение If qeEI in Quality then QDS:= QDS or $08; // EI - неверное время продолжительности Result:= QDS; end; // ------------------------------------------------------------------------------ constructor TInformationObject.Create(AASDUType, ASASDUType: Byte; AIOAddress: LongWord; AGroup: Integer); var I: Integer; begin inherited Create; // FASDUType:= AASDUType; FSASDUType:= ASASDUType; FIOAddress:= AIOAddress; FGroup:= AGroup; FQuality:= False; FDataReady:= False; For I:= 0 to MAX_CLIENT_COUNT-1 do FChangeStatus[I]:= False; end; procedure TInformationObject.SetValue(AValue: Variant); begin FDataReady:= True; If (not VarSameValue(AValue, FValue)) or (not FQuality) then begin FDT:= IECNow(); FDTValid:= IECTimeValid; FQuality:= True; FValue:= AValue; SetChangeStatus(); end; end; procedure TInformationObject.SetBadQuality(); begin If FQuality or (not FDataReady) then begin If not FDataReady then begin FDataReady:= True; FValue:= 0; end; FDT:= IECNow(); FDTValid:= IECTimeValid; FQuality:= False; SetChangeStatus(); end; end; function TInformationObject.ByteValue(const AIndex: Integer = -1): Byte; begin try If AIndex >= 0 then Result:= FValue[AIndex] else Result:= FValue; except Result:= 0; end; end; function TInformationObject.WordValue(const AIndex: Integer = -1): Word; begin try If AIndex >= 0 then Result:= FValue[AIndex] else Result:= FValue; except Result:= 0; end; end; function TInformationObject.LWordValue(const AIndex: Integer = -1): LongWord; begin try If AIndex >= 0 then Result:= FValue[AIndex] else Result:= FValue; except Result:= 0; end; end; function TInformationObject.SingleValue(const AIndex: Integer = -1): Single; begin try If AIndex >= 0 then Result:= FValue[AIndex] else Result:= FValue; except Result:= 0; end; end; function TInformationObject.DateTimeValue(const AIndex: Integer = -1): TDateTime; begin try If AIndex >= 0 then Result:= FValue[AIndex] else Result:= FValue; except Result:= 0; end; end; function TInformationObject.IntegerValue(const AIndex: Integer = -1): Integer; begin try If AIndex >= 0 then Result:= FValue[AIndex] else Result:= FValue; except Result:= 0; end; end; function TInformationObject.SmallIntValue(const AIndex: Integer = -1): SmallInt; begin try If AIndex >= 0 then Result:= FValue[AIndex] else Result:= FValue; except Result:= 0; end; end; function TInformationObject.SIQ: Byte; var B: Byte; begin If ByteValue() <> 0 then B:= 1 else B:= 0; If not FQuality then B:= B or encodeQDS([qeIV]); result:= B; end; function TInformationObject.DIQ: Byte; var B: Byte; begin Case ByteValue() of 0: B:= 1; // OFF 1: B:= 2; // ON else B:= 0; // неопределенное или промежуточное состояние end; If not FQuality then B:= B or encodeQDS([qeIV]); Result:= B; end; function TInformationObject.SEP: Byte; var B: Byte; begin Case ByteValue() of 0: B:= 1; // OFF 1: B:= 2; // ON else B:= 0; // неопределенное состояние end; If not FQuality then B:= B or encodeQDS([qeEI, qeIV]) else B:= B or encodeQDS([qeEI]); Result:= B; end; function TInformationObject.EncodeIOData(ASDU: PByteArray; ASpont: Boolean): Integer; var Offset: Integer; DT: TDateTime; IntV: Integer; SIntV: SmallInt; LWV: LongWord; SV: Single; WV: Word; begin Offset:= 0; // данные Case ASDUType(ASpont) of // одноэлементная информация M_SP_NA_1: begin // одноэлементная информация с описателем качества ASDU^[Offset]:= SIQ(); Offset:= Offset + 1; end; M_SP_TA_1: begin // одноэлементная информация с описателем качества и меткой времени ASDU^[Offset]:= SIQ(); Offset:= Offset + 1; Offset:= Offset + encodeCP24Time2a(@ASDU^[Offset], FDT, FDTValid); end; M_SP_TB_1: begin // одноэлементая информация с меткой времени CP56Time2a ASDU^[Offset]:= SIQ(); Offset:= Offset + 1; Offset:= Offset + encodeCP56Time2a(@ASDU^[Offset], FDT, FDTValid); end; // двухэлементная информация M_DP_NA_1: begin // двухэлементная информация ASDU^[Offset]:= DIQ(); Offset:= Offset + 1; end; M_DP_TA_1: begin // двухэлементная информация с меткой времени ASDU^[Offset]:= DIQ(); Offset:= Offset + 1; Offset:= Offset + encodeCP24Time2a(@ASDU^[Offset], FDT, FDTValid); end; M_DP_TB_1: begin // двухэлементная информация с меткой времени CP56Time2a ASDU^[Offset]:= DIQ(); Offset:= Offset + 1; Offset:= Offset + encodeCP56Time2a(@ASDU^[Offset], FDT, FDTValid); end; // информация о положении отпаек (отводов трансформатора) M_ST_NA_1: begin // информация о положении отпаек (отводов трансформатора) ASDU^[Offset]:= ByteValue(); Offset:= Offset + 1; If FQuality then ASDU^[Offset]:= 0 else ASDU^[Offset]:= encodeQDS([qeIV]); Offset:= Offset + 1; end; M_ST_TA_1: begin // информация о положении отпаек с меткой времени ASDU^[Offset]:= ByteValue(); Offset:= Offset + 1; If FQuality then ASDU^[Offset]:= 0 else ASDU^[Offset]:= encodeQDS([qeIV]); Offset:= Offset + 1; Offset:= Offset + encodeCP24Time2a(@ASDU^[Offset], FDT, FDTValid); end; M_ST_TB_1: begin // информация о положении отпаек с меткой времени CP56Time2a ASDU^[Offset]:= ByteValue(); Offset:= Offset + 1; If FQuality then ASDU^[Offset]:= 0 else ASDU^[Offset]:= encodeQDS([qeIV]); Offset:= Offset + 1; Offset:= Offset + encodeCP56Time2a(@ASDU^[Offset], FDT, FDTValid); end; // строка из 32-х бит M_BO_NA_1: begin // строка из 32-х бит LWV:= LWordValue(); Move(LWV, ASDU^[Offset], 4); Offset:= Offset + 4; If FQuality then ASDU^[Offset]:= 0 else ASDU^[Offset]:= encodeQDS([qeIV]); Offset:= Offset + 1; end; M_BO_TA_1: begin // строка из 32-х бит с меткой времени LWV:= LWordValue(); Move(LWV, ASDU^[Offset], 4); Offset:= Offset + 4; If FQuality then ASDU^[Offset]:= 0 else ASDU^[Offset]:= encodeQDS([qeIV]); Offset:= Offset + 1; Offset:= Offset + encodeCP24Time2a(@ASDU^[Offset], FDT, FDTValid); end; M_BO_TB_1: begin // строка из 32-х бит с меткой времени CP56Time2a LWV:= LWordValue(); Move(LWV, ASDU^[Offset], 4); Offset:= Offset + 4; If FQuality then ASDU^[Offset]:= 0 else ASDU^[Offset]:= encodeQDS([qeIV]); Offset:= Offset + 1; Offset:= Offset + encodeCP56Time2a(@ASDU^[Offset], FDT, FDTValid); end; // нормализованное значение измеряемой величины M_ME_NA_1: begin // нормализованное значение измеряемой величины SIntV:= SmallIntValue(); Move(SIntV, ASDU^[Offset], 2); Offset:= Offset + 2; If FQuality then ASDU^[Offset]:= 0 else ASDU^[Offset]:= encodeQDS([qeIV]); Offset:= Offset + 1; end; M_ME_ND_1: begin // нормализованное значение измеряемой величины без описателя качества SIntV:= SmallIntValue(); Move(SIntV, ASDU^[Offset], 2); Offset:= Offset + 2; end; M_ME_TA_1: begin // нормализованное значение измеряемой величины с меткой времени SIntV:= SmallIntValue(); Move(SIntV, ASDU^[Offset], 2); Offset:= Offset + 2; If FQuality then ASDU^[Offset]:= 0 else ASDU^[Offset]:= encodeQDS([qeIV]); Offset:= Offset + 1; Offset:= Offset + encodeCP24Time2a(@ASDU^[Offset], FDT, FDTValid); end; M_ME_TD_1: begin // нормализованное значение измеряемой величины с меткой времени CP56Time2a SIntV:= SmallIntValue(); Move(SIntV, ASDU^[Offset], 2); Offset:= Offset + 2; If FQuality then ASDU^[Offset]:= 0 else ASDU^[Offset]:= encodeQDS([qeIV]); Offset:= Offset + 1; Offset:= Offset + encodeCP56Time2a(@ASDU^[Offset], FDT, FDTValid); end; // масштабированное значение измеряемой величины M_ME_NB_1: begin // масштабированное значение измеряемой величины SIntV:= SmallIntValue(); Move(SIntV, ASDU^[Offset], 2); Offset:= Offset + 2; If FQuality then ASDU^[Offset]:= 0 else ASDU^[Offset]:= encodeQDS([qeIV]); Offset:= Offset + 1; end; M_ME_TB_1: begin // масштабированное значение измеряемой величины с меткой времени SIntV:= SmallIntValue(); Move(SIntV, ASDU^[Offset], 2); Offset:= Offset + 2; If FQuality then ASDU^[Offset]:= 0 else ASDU^[Offset]:= encodeQDS([qeIV]); Offset:= Offset + 1; Offset:= Offset + encodeCP24Time2a(@ASDU^[Offset], FDT, FDTValid); end; M_ME_TE_1: begin // масштабированное значение измеряемой величины с меткой времени CP56Time2a SIntV:= SmallIntValue(); Move(SIntV, ASDU^[Offset], 2); Offset:= Offset + 2; If FQuality then ASDU^[Offset]:= 0 else ASDU^[Offset]:= encodeQDS([qeIV]); Offset:= Offset + 1; Offset:= Offset + encodeCP56Time2a(@ASDU^[Offset], FDT, FDTValid); end; // короткий формат с плавающей точкой M_ME_NC_1: begin // значение измеряемой величины, короткий формат с плавающей точкой SV:= SingleValue(); Move(SV, ASDU^[Offset], 4); Offset:= Offset + 4; If FQuality then ASDU^[Offset]:= 0 else ASDU^[Offset]:= encodeQDS([qeIV]); Offset:= Offset + 1; end; M_ME_TC_1: begin // значение измеряемой величины, короткий формат с плавающей точкой с меткой времени SV:= SingleValue(); Move(SV, ASDU^[Offset], SizeOf(SV)); Offset:= Offset + SizeOf(SV); If FQuality then ASDU^[Offset]:= 0 else ASDU^[Offset]:= encodeQDS([qeIV]); Offset:= Offset + 1; Offset:= Offset + encodeCP24Time2a(@ASDU^[Offset], FDT, FDTValid); end; M_ME_TF_1: begin // значение измеряемой величины, короткий формат с плавающей точкой с меткой времени CP56Time2a SV:= SingleValue(); Move(SV, ASDU^[Offset], 4); Offset:= Offset + 4; If FQuality then ASDU^[Offset]:= 0 else ASDU^[Offset]:= encodeQDS([qeIV]); Offset:= Offset + 1; Offset:= Offset + encodeCP56Time2a(@ASDU^[Offset], FDT, FDTValid); end; // интегральная сумма M_IT_NA_1: begin // интегральная сумма // | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | // +---+---+---+---+---+---+---+---+ // 0 | Value | // 1 | Value | // 2 | Value | // 3 | S | Value | S - sign // 4 |IV |CA |CY | Seq number | IV:1 - invalid value; // CA:0 - counter was not adjusted since last reading // CA:1 - counter was adjusted since last reading // CY:0 - no counter overflow occurred in the corresponding integration period // CY:1 - counter overflow occurred in the corresponding integration period // Seq number - ??? IntV:= IntegerValue(); Move(IntV, ASDU^[Offset], 4); Offset:= Offset + 4; If FQuality then ASDU^[Offset]:= 0 else ASDU^[Offset]:= encodeQDS([qeIV]); Offset:= Offset + 1; end; M_IT_TA_1: begin // интегральная сумма с меткой времени IntV:= IntegerValue(); Move(IntV, ASDU^[Offset], 4); Offset:= Offset + 4; If FQuality then ASDU^[Offset]:= 0 else ASDU^[Offset]:= encodeQDS([qeIV]); Offset:= Offset + 1; Offset:= Offset + encodeCP24Time2a(@ASDU^[Offset], FDT, FDTValid); end; M_IT_TB_1: begin // интегральная сумма с меткой времени CP56Time2a IntV:= IntegerValue(); Move(IntV, ASDU^[Offset], 4); Offset:= Offset + 4; If FQuality then ASDU^[Offset]:= 0 else ASDU^[Offset]:= encodeQDS([qeIV]); Offset:= Offset + 1; Offset:= Offset + encodeCP56Time2a(@ASDU^[Offset], FDT, FDTValid); end; // события M_EP_TA_1: begin // информация о работе релейной защиты с меткой времени // SEP ASDU^[Offset]:= SEP(); Offset:= Offset + 1; // CP16Time2a - продолжительность Offset:= Offset + encodeUInt16(@ASDU^[Offset], 0); // CP24Time2a Offset:= Offset + encodeCP24Time2a(@ASDU^[Offset], FDT, FDTValid); end; M_EP_TD_1: begin // информация о работе релейной защиты с меткой времени CP56Time2a // SEP ASDU^[Offset]:= SEP(); Offset:= Offset + 1; // CP16Time2a Offset:= Offset + encodeUInt16(@ASDU^[Offset], 0); // CP56Time2a Offset:= Offset + encodeCP56Time2a(@ASDU^[Offset], FDT, FDTValid); end; // // команды C_SC_NA_1: begin // однопозиционная команда ASDU^[Offset]:= ByteValue(); Offset:= Offset + 1; end; C_SC_TA_1: begin // однопозиционная команда с меткой времени ASDU^[Offset]:= ByteValue(0); Offset:= Offset + 1; DT:= DateTimeValue(1); Offset:= Offset + encodeCP56Time2a(@ASDU^[Offset], DT, True); end; C_DC_NA_1: begin // двухпозиционная команда ASDU^[Offset]:= ByteValue(); Offset:= Offset + 1; end; C_DC_TA_1: begin // двухпозиционная команда с меткой времени ASDU^[Offset]:= ByteValue(0); Offset:= Offset + 1; DT:= DateTimeValue(1); Offset:= Offset + encodeCP56Time2a(@ASDU^[Offset], DT, True); end; C_RC_NA_1: begin // команда пошагового регулирования ASDU^[Offset]:= ByteValue(); Offset:= Offset + 1; end; C_RC_TA_1: begin // команда пошагового регулирования с меткой времени ASDU^[Offset]:= ByteValue(0); Offset:= Offset + 1; DT:= DateTimeValue(1); Offset:= Offset + encodeCP56Time2a(@ASDU^[Offset], DT, True); end; C_BO_NA_1: begin // строка из 32 бит LWV:= LWordValue(); Move(LWV, ASDU^[Offset], 4); Offset:= Offset + 4; end; C_BO_TA_1: begin // строка из 32 бит с меткой времени CP56Time2a LWV:= LWordValue(0); Move(LWV, ASDU^[Offset], 4); Offset:= Offset + 4; DT:= DateTimeValue(1); Offset:= Offset + encodeCP56Time2a(@ASDU^[Offset], DT, True); end; M_EI_NA_1: begin // конец инициализации (должен быть COT_INIT) // | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | // +---+---+---+---+---+---+---+---+ // 0 |BS1| couse of init | 0 - local power switch on // 1 - local manual reset // 2 - remote reset // BS1:0 - initialization with unchanged local parameters // BS1:1 - initialization after change of local parameters ASDU^[Offset]:= ByteValue(); Offset:= Offset + 1; end; C_IC_NA_1: begin // команда общего опроса ASDU^[Offset]:= ByteValue(); Offset:= Offset + 1; end; C_CI_NA_1: begin // команда опроса счётчиков ASDU^[Offset]:= ByteValue(); Offset:= Offset + 1; end; C_RD_NA_1: begin // команда опроса одного объекта // данные отсутствуют end; C_CS_NA_1: begin // Clock synchronization command DT:= DateTimeValue(); Offset:= Offset + encodeCP56Time2a(@ASDU^[Offset], DT, IECTimeValid); end; C_TS_NA_1: begin // тестирование канала связи ASDU^[Offset]:= $AA; // фиксированная тестовая константа ASDU^[Offset+1]:= $55; Offset:= Offset + 2; end; C_RP_NA_1: begin // установка процесса в начальное состояние ASDU^[Offset]:= ByteValue(); Offset:= Offset + 1; end; C_CD_NA_1: begin // команда определения запаздывания WV:= WordValue(); Offset:= Offset + encodeUInt16(@ASDU^[Offset], WV); end; C_TS_TA_1: begin // команда тестирования c меткой времени WV:= WordValue(0); DT:= DateTimeValue(1); Offset:= Offset + encodeUInt16(@ASDU^[Offset], WV); Offset:= Offset + encodeCP56Time2a(@ASDU^[Offset], DT, IECTimeValid); end; end; Result:= Offset; end; procedure TInformationObject.ClearChangeStatus(AIndex: Integer); begin FChangeStatus[AIndex]:= False; end; procedure TInformationObject.SetChangeStatus; var I: Integer; begin For I:= 0 to MAX_CLIENT_COUNT-1 do FChangeStatus[I]:= True; end; function TInformationObject.SporadicSupported: Boolean; begin Result:= FSASDUType > 0; end; function TInformationObject.NeedSporadic(AIndex: Integer): Boolean; begin Result:= FDataReady and FChangeStatus[AIndex] and SporadicSupported(); end; function TInformationObject.ASDUType(ASpont: Boolean): Byte; begin If ASpont and SporadicSupported then Result:= FSASDUType else Result:= FASDUType; end; // тип функции function IECFunctionFormat(B: Byte): TIECFunctionFormat; begin If (B and 1) = 0 then result:= I_Format else If (B and 3) = 1 then result:= S_Format else result:= U_Format; end; // передаваемый порядковый номер function IECGetNS(Buf: PByteArray): Word; begin result:= (Buf^[2] shr 1) + (Buf^[3] shl 7); end; // принимаемый порядковый номер function IECGetNR(Buf: PByteArray): Word; begin result:= (Buf^[4] shr 1) + (Buf^[5] shl 7); end; // function decodeCP56Time2a(Buf: PByteArray; var DT: TDateTime): Integer; var MS: Word; begin // | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | // +---+---+---+---+---+---+---+---+ // 0 | миллисекунды, младший байт | // 1 | миллисекунды, старший байт | 0..59999 мс // 2 |IV |RES| минуты | 0..59, IV - недействительное значение // 3 |SU | RES | часы | 0..23, SU - летнее время // 4 |дни недели | дни месяца | 1..7 (0 - не используется), 1..31 // 5 | RES | месяцы | 1..12 // 6 |RES| годы | 0..99 Result:= 7; try If (Buf^[2] and $80) = 0 then begin // значение действительно MS:= Buf^[0] + 256*Buf^[1]; DT:= EncodeDateTime((Buf^[6] and $7F) + 2000, // year Buf^[5] and $1F, // month Buf^[4] and $1F, // day Buf^[3] and $1F, // hour Buf^[2] and $3F, // minute MS div 1000, // second MS mod 1000); // msecond end else DT:= 0; // значение не действительно except DT:= 0; end; end; // function encodeCP56Time2a(Buf: PByteArray; DT: TDateTime; ADTValid: Boolean): Integer; var Year, Month, Day, Hour, Minute, Second, MSecond, MS: Word; begin try DecodeDateTime(DT, Year, Month, Day, Hour, Minute, Second, MSecond); MS:= Second*1000 + MSecond; Buf^[0]:= Lo(MS); Buf^[1]:= Hi(MS); Buf^[2]:= Minute; If not ADTValid then Buf^[2]:= Buf^[2] or $80; Buf^[3]:= Hour; Buf^[4]:= Day; Buf^[5]:= Month; Buf^[6]:= Year - 2000; except // некорректное время FillChar(Buf^, 7, 0); Buf^[2]:= $80; end; Result:= 7; end; // function encodeCP24Time2a(Buf: PByteArray; DT: TDateTime; ADTValid: Boolean): Integer; var Year, Month, Day, Hour, Minute, Second, MSecond, MS: Word; begin // | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | // +---+---+---+---+---+---+---+---+ // 0 | миллисекунды, младший байт | // 1 | миллисекунды, старший байт | 0..59999 мс // 2 |IV |RES| минуты | 0..59, IV - недействительное значение, RES=0 - Genuine time, RES=1 - Substituted time DecodeDateTime(DT, Year, Month, Day, Hour, Minute, Second, MSecond); MS:= Second*1000 + MSecond; Buf^[0]:= Lo(MS); Buf^[1]:= Hi(MS); Buf^[2]:= Minute; If not ADTValid then Buf^[2]:= Buf^[2] or $80; Result:= 3; end; // function decodeUInt16(Buf: PByteArray; var CP16: Word): Integer; begin CP16:= Buf^[0] + Buf^[1]*256; Result:= 2; end; // function encodeUInt16(Buf: PByteArray; CP16: Word): Integer; begin Buf^[0]:= Lo(CP16); Buf^[1]:= Hi(CP16); Result:= 2; end; // function decodeUInt32(Buf: PByteArray; var CP32: LongWord): Integer; begin CP32:= Buf^[0] + Buf^[1]*256 + Buf^[2]*256*256 + Buf^[3]*256*256*256; Result:= 4; end; // function QCCDescription(V: Byte): String; begin Case V of 0: result:= 'Not used'; 1..4: result:= 'Request of counters group ' + IntToStr(V); // запрос счётчиков группы N 5: result:= 'General request of counters'; // общий запрос счётчиков else result:= 'Reserv (' + IntToStr(V) + ')'; end; end; end.
unit UAssyncControler; interface uses Windows, SysUtils, Generics.Collections, RegistroControler, SyncObjs, Winapi.Messages, Classes; const WM_PROCEDIMENTOGENERICOASSYNC = WM_USER + 1; WM_TERMINATE = WM_USER + 2; Type TAssyncControler = class(TThread) private Cores : TSystemInfo; FilaDeProcedures: TList<TProc>; Msg : TMsg; Registro: TRegistro; procedure Dispatcher; procedure TriggerOciosidade; protected procedure Execute; override; public Constructor Create(CreateSuspended: Boolean = false);overload; Destructor Destroy; Override; procedure JogarProcedureNaFilaAssyncrona(CallBack: TProc); procedure Synchronize(AMethod: TThreadMethod); overload; inline; procedure Synchronize(AThreadProc: TThreadProcedure); overload; inline; end; var AssyncControler: TAssyncControler; implementation // Thread para execução assyncrona procedure TAssyncControler.Execute; begin FreeOnTerminate := not self.Finished; TriggerOciosidade; GetSystemInfo(Cores); while not Terminated do begin Dispatcher; end; end; procedure TAssyncControler.TriggerOciosidade; begin CreateAnonymousThread( Procedure Begin while true do begin Sleep(1);//Confira de 1 em 1 segundo se há trabalho para ser feito, se não há então termine if (Registro.QtdeProcAsync + FilaDeProcedures.Count) = 0 then begin Terminate; break; end; end; end).Start; end; Constructor TAssyncControler.Create(CreateSuspended: Boolean = false); begin inherited create(CreateSuspended); FilaDeProcedures := TList<TProc>.Create; Registro := TRegistro.Create; Registro.Lock := TCriticalSection.Create; end; Destructor TAssyncControler.Destroy; begin inherited; FilaDeProcedures.Free; FilaDeProcedures := nil; Registro.Lock.Free; Registro.Lock := nil; Registro.Free; Registro := nil; AssyncControler := nil; end; procedure TAssyncControler.Dispatcher; var ThreadAntiga : TThread; CallBack: TProc; begin Sleep(1); if PeekMessage(Msg, 0, 0, 0, PM_NOREMOVE) then begin if Integer(Cores.dwNumberOfProcessors) > 2 // 1 núcleo e 2 threads ou inferior then while Registro.QtdeProcAsync >= (Integer(Cores.dwNumberOfProcessors) - 1) do sleep(1) //Otimização para hardware não sobrecarregar de processos pessados. else while Registro.QtdeProcAsync > 2 do sleep(1); // ele só aceita realizar dois processos assyncronos por vez try try case Msg.Message of WM_PROCEDIMENTOGENERICOASSYNC: begin AssyncControler.CreateAnonymousThread( procedure begin Registro.QtdeProcAsync := Registro.QtdeProcAsync + 1; CallBack := FilaDeProcedures.ExtractAt(0); CallBack; Registro.QtdeProcAsync := Registro.QtdeProcAsync - 1; end).Start; end; WM_TERMINATE: Terminate; end; finally PeekMessage(Msg, 0, 0, 0, PM_REMOVE); end; except Self.Terminate; end; end; end; procedure TAssyncControler.JogarProcedureNaFilaAssyncrona(CallBack: TProc); begin FilaDeProcedures.Add(CallBack); PostThreadMessage(ThreadID, WM_PROCEDIMENTOGENERICOASSYNC, 0, 0); end; procedure TAssyncControler.Synchronize(AMethod: TThreadMethod); begin Synchronize(Self, AMethod); end; procedure TAssyncControler.Synchronize(AThreadProc: TThreadProcedure); begin Synchronize(Self, AThreadProc); end; end.
unit myclasses3; { 资产数据! 资产数据! 资产数据! 资产数据! 资产数据! 资产数据! 资产数据! 资产数据! 资产数据! } {$mode objfpc}{$H+} interface uses Classes, SysUtils; type //资产数据 {TCash 现金资产} TCash = class(Tcomponent) private FAvailable:double; // 可取 public constructor Create(AOwner:TComponent); override; destructor Destroy; override; procedure LoadFromFile(Filename:string); procedure SaveToFile(Filename:string); property Available:double read FAvailable write FAvailable; end; {TPropertyItem 持有股票} TPropertyItem = packed record Code:string[6]; //股代码 StockName:string[20]; Market:string[2]; //市场 cost:double; //成本价 quantity:integer; //数量 price:double; //现价 // Profit:double; //盈亏 // 这三个怎么表示,反复用Update吗 profitRatio:double; //盈亏比 // end; PPropertyItem = ^TPropertyItem; {TProperty 持仓资产列表} TProperty = class(Tcomponent) private Flist:Tlist; function GetCount: integer; public constructor Create(AOwner:TComponent); override; destructor Destroy;override; procedure Clear; function Totalinterest:double; //持仓总盈亏 function Frozen:double; // 总冻结资产 function Add(AValue:TPropertyItem):integer; //增加新持有股票 procedure Update(AIndex:integer; Avalue:TPropertyItem);//更新指定下标的数量 function Delete(AIndex:integer):boolean;//删除指定下标的股票(全卖出) procedure LoadFromFile(Afilename:String);//从文件读数据 procedure SaveToFile(AFilename:string);//保存数据到文件 function IndexOf(ACode,AMarket:string):integer;//查找 function Item(AIndex:integer):TPropertyItem;//返回数据 property Count:integer read GetCount; end; implementation { TCash } constructor TCash.Create(AOwner: TComponent); begin inherited Create(AOwner); end; destructor TCash.Destroy; begin inherited Destroy; end; procedure TCash.LoadFromFile(Filename: string); var Tmp,Tmp2:double; mFile:TFileStream; begin mFile:=TFileStream.Create(FileName,fmOpenRead); mFile.Seek(0,soBeginning); //从property.dat读取available的值 mFile.Read(Tmp,sizeof(double)); FAvailable:=Tmp; mFile.free; end; procedure TCash.SaveToFile(Filename: string); var mFile:TFileStream; begin //把available的值存入property.dat mFile:=TFileStream.Create(FileName,fmCreate); mFile.Seek(0,soBeginning); mFile.write(FAvailable,sizeof(double)); mFile.free; end; { TProperty } function TProperty.Totalinterest: double; var i:integer; Tmp:double; mItem:TPropertyItem; begin Tmp:=0; for i:=0 to Flist.Count-1 do begin mItem:=Self.Item(i); Tmp:=Tmp+mItem.Profit*mItem.quantity; end; Result:=Tmp; end; function TProperty.Frozen: double; var i:integer; Tmp:double; mItem:TPropertyItem; begin Tmp:=0; for i:=0 to Flist.Count-1 do begin mItem:=Self.Item(i); Tmp:=Tmp+mItem.price*mItem.Quantity; end; Result:=Tmp; end; function TProperty.GetCount: integer; begin Result:=FList.Count; end; constructor TProperty.Create(AOwner: TComponent); begin inherited Create(AOwner); FList:=TList.create; end; destructor TProperty.Destroy; begin Clear; FList.Free; inherited Destroy; end; procedure TProperty.Clear; var i:integer; begin for i:=0 to FList.Count-1 do begin Dispose(PPropertyItem(FList.Items[i])); end; FList.Clear; end; function TProperty.Add(AValue: TPropertyItem): integer; var m:PpropertyItem; begin new(m); m^.Code:=AValue.Code; m^.StockName:=AValue.StockName; m^.Market:=AValue.Market; m^.cost:=AValue.cost; m^.quantity:=AValue.quantity; m^.price:=AValue.price; m^.Profit:=AValue.Profit; m^.profitRatio:=AValue.profitRatio; Result:=Flist.Add(m); end; function TProperty.Delete(AIndex: integer): boolean; begin try Flist.Delete(AIndex); result:=true; except result:=False; end; end; procedure TProperty.Update(AIndex: integer; Avalue: TPropertyItem); var m:PPropertyItem; begin if AIndex < Flist.Count then begin m:=PPropertyItem(FList.Items[AIndex]); m^.Code:=AValue.Code; m^.StockName:=AValue.StockName; m^.Market:=AValue.Market; m^.cost:=AValue.cost; m^.quantity:=AValue.quantity; m^.price:=AValue.price; m^.Profit:=AValue.Profit; m^.profitRatio:=AValue.profitRatio; end; end; procedure TProperty.LoadFromFile(Afilename: String); var mcount:integer; mFile:TFileStream; i:integer; mItem:TPropertyItem; begin mFile:=TFileStream.Create(AFilename,fmOpenRead); mFile.Seek(0,soBeginning); mFile.Read(mcount,sizeof(mcount)); Clear; for i:=0 to mCount-1 do begin mFile.Read(mItem,sizeof(mItem)); Add(mItem); end; mFile.Free; end; procedure TProperty.SaveToFile(AFilename: string); var mcount:integer; mFile:TFileStream; i:integer; mItem:TPropertyItem; begin mFile:=TFileStream.Create(AFilename,fmCreate); mcount:=FList.Count; mFile.Seek(0,soBeginning); mFile.Write(mcount,sizeof(mcount)); for i:=0 to FList.Count-1 do begin mItem:=Self.Item(i); mFile.Write(mItem,sizeof(mItem)); end; mFile.Free; end; function TProperty.IndexOf(ACode, AMarket: string): integer; var i:integer; mItem:TPropertyItem; begin Result:=-1; for i:=0 to FList.Count-1 do begin mItem:=Self.Item(i); if (mItem.Code=ACode) and (mItem.Market=AMarket) then begin Result:=i; Break; end; end; end; function TProperty.Item(AIndex: integer): TPropertyItem; var m:PPropertyItem; begin m:=PPropertyItem(FList.Items[AIndex]); Result.Code:=m^.Code; Result.StockName:=m^.StockName; Result.Market:=m^.Market; Result.cost:=m^.cost; Result.quantity:=m^.quantity; Result.price:=m^.price; Result.Profit:=m^.Profit; Result.ProfitRatio:=m^.ProfitRatio; end; end.
(* Stack ADT 4 19.04.2017 *) (* ---------- *) (* implementing the stack as abstract data type - version 4 *) (* ========================================================= *) UNIT StackADT4; INTERFACE TYPE (* "verstecken" von stack daten *) Stack = POINTER; PROCEDURE NewStack(VAR s: Stack; max: INTEGER); PROCEDURE DisposeStack(VAR s: Stack); PROCEDURE Push(VAR s: Stack; e: INTEGER); PROCEDURE Pop(VAR s: Stack; VAR e: INTEGER); FUNCTION Empty(s: Stack): BOOLEAN; IMPLEMENTATION TYPE StackPtr = ^StackRec; StackRec = RECORD max : INTEGER; data: ARRAY[1..1] OF INTEGER; top: INTEGER; END; PROCEDURE NewStack(VAR s: Stack; max: INTEGER); VAR intSize: INTEGER; mem: INTEGER; BEGIN intSize := SizeOf(INTEGER); mem := intSize + intSize * max + intSize; GetMem(s, mem); (* typecast *) StackPtr(s)^.top := 0; StackPtr(s)^.max := max; END; PROCEDURE DisposeStack(VAR s: Stack); VAR intSize: INTEGER; mem: INTEGER; BEGIN intSize := SizeOf(INTEGER); mem := intSize + intSize * StackPtr(s)^.max + intSize; (* Alternative: 2 Byte for max + 2 Byte for each integer in data (size max) + 2 Byte for top *) (* FreeMem(s, 2 + max*2 + 2) *) FreeMem(s, mem); s := NIL; END; PROCEDURE Push(VAR s: Stack; e: INTEGER); BEGIN IF StackPtr(s)^.top = StackPtr(s)^.max THEN BEGIN WriteLn('Stack overflow'); END ELSE BEGIN StackPtr(s)^.top := StackPtr(s)^.top + 1; {$R-} StackPtr(s)^.data[StackPtr(s)^.top] := e; {$R+} END; END; PROCEDURE Pop(VAR s: Stack; VAR e: INTEGER); BEGIN IF StackPtr(s)^.top = 0 THEN BEGIN WriteLn('Stack underflow'); END ELSE BEGIN {$R-} e := StackPtr(s)^.data[StackPtr(s)^.top]; {$R+} StackPtr(s)^.top := StackPtr(s)^.top - 1; END; END; FUNCTION Empty(s: Stack): BOOLEAN; BEGIN Empty := StackPtr(s)^.top = 0; END; BEGIN END. (* StackADT4 *)
unit Odontologia.Controlador.Departamento; interface uses Data.DB, System.SysUtils, System.Generics.Collections, Odontologia.Controlador.Departamento.Interfaces, Odontologia.Controlador.Pais, Odontologia.Controlador.Pais.Interfaces, Odontologia.Modelo, Odontologia.Modelo.Entidades.Departamento, Odontologia.Modelo.Departamento.Interfaces; type TControllerDepartamento = class(TInterfacedObject, iControllerDepartamento) private FModel: iModelDepartamento; FDataSource: TDataSource; //Flista: TObjectList<TDDEPARTAMENTO>; FPais: iControllerPais; procedure DataChange (sender : tobject ; field : Tfield) ; public constructor Create; destructor Destroy; override; class function New: iControllerDepartamento; function DataSource(aDataSource: TDataSource): iControllerDepartamento; function Buscar : iControllerDepartamento; overload; function Buscar (aDepartamento : String) : iControllerDepartamento; overload; function Insertar : iControllerDepartamento; function Modificar: iControllerDepartamento; function Eliminar : iControllerDepartamento; function Entidad : TDDEPARTAMENTO; function Pais : iControllerPais; end; implementation { TControllerDepartamento } function TControllerDepartamento.Buscar: iControllerDepartamento; begin Result := Self; //Flista := TObjectList<TDDEPARTAMENTO>.Create; //FModel.DAO.Find(Flista); FDataSource.dataset.DisableControls; FModel.DAO.SQL.Fields('DDEPARTAMENTO.DEP_CODIGO AS CODIGO,') .Fields('DDEPARTAMENTO.DEP_NOMBRE AS NOMBRE,') .Fields('DDEPARTAMENTO.DEP_COD_PAIS AS COD_PAIS,') .Fields('DPAIS.PAI_NOMBRE AS PAIS') .Join('INNER JOIN DPAIS ON DPAIS.PAI_CODIGO = DDEPARTAMENTO.DEP_COD_PAIS ') //.Where('ID_PEDIDO = ' + intToStr(aId)) .Where('') .OrderBy('NOMBRE') .&End.Find; FDataSource.dataset.EnableControls; FDataSource.dataset.FieldByName('CODIGO').Visible := false; FDataSource.dataset.FieldByName('COD_PAIS').Visible := false; FDataSource.dataset.FieldByName('NOMBRE').DisplayWidth :=50; end; function TControllerDepartamento.Buscar(aDepartamento: String): iControllerDepartamento; begin Result := Self; //Flista := TObjectList<TDDEPARTAMENTO>.Create; FDataSource.dataset.DisableControls; FModel.DAO.SQL.Fields('DDEPARTAMENTO.DEP_CODIGO AS CODIGO,') .Fields('DDEPARTAMENTO.DEP_NOMBRE AS NOMBRE,') .Fields('DDEPARTAMENTO.DEP_COD_PAIS AS COD_PAIS,') .Fields('DPAIS.PAI_NOMBRE AS PAIS') .Join('INNER JOIN DPAIS ON DPAIS.PAI_CODIGO = DDEPARTAMENTO.DEP_COD_PAIS ') .Where('DEP_NOMBRE CONTAINING ' +QuotedStr(aDepartamento) + '') .OrderBy('NOMBRE') .&End.Find; FDataSource.dataset.EnableControls; FDataSource.dataset.FieldByName('CODIGO').Visible := false; FDataSource.dataset.FieldByName('COD_PAIS').Visible := false; FDataSource.dataset.FieldByName('NOMBRE').DisplayWidth :=50; end; constructor TControllerDepartamento.Create; begin FModel := TModel.New.Departamento; FPais := TcontrollerPais.New; end; procedure TControllerDepartamento.DataChange(sender: tobject; field: Tfield); begin // FPais.buscar(FDataSource.DataSet.FieldByName('PAIS').AsString); end; function TControllerDepartamento.DataSource(aDataSource: TDataSource) : iControllerDepartamento; begin Result := Self; FDataSource := aDataSource; FModel.DataSource(FDataSource); FDataSource.OnDataChange := DataChange; end; destructor TControllerDepartamento.Destroy; begin //Flista.Free; inherited; end; function TControllerDepartamento.Eliminar: iControllerDepartamento; begin Result := Self; FModel.DAO.Delete(FModel.Entidad); end; function TControllerDepartamento.Entidad: TDDEPARTAMENTO; begin Result := FModel.Entidad; end; function TControllerDepartamento.Insertar: iControllerDepartamento; begin Result := Self; FModel.DAO.Insert(FModel.Entidad); end; function TControllerDepartamento.Pais: iControllerPais; begin Result := FPais; end; function TControllerDepartamento.Modificar: iControllerDepartamento; begin Result := Self; FModel.DAO.Update(FModel.Entidad); end; class function TControllerDepartamento.New: iControllerDepartamento; begin Result := Self.Create; end; end.
unit Keyman.System.BuildISO6393Registry; interface type TBuildISO6393Registry = class class procedure Build(const ISO6393File, DestinationFile: string); end; implementation uses System.SysUtils, System.Classes; class procedure TBuildISO6393Registry.Build(const ISO6393File, DestinationFile: string); var FISO6393, FResult: TStringList; i: Integer; s: string; s6393: string; s6391: string; function GetField(var s: string): string; var i: Integer; begin i := 1; while i <= Length(s) do begin if s[i] = #9 then begin Result := Copy(s, 1, i-1); Delete(s, 1, i); Exit; end; Inc(i); end; Result := s; s := ''; end; begin FISO6393 := TStringList.Create; try FISO6393.LoadfromFile(ISO6393File); FResult := TStringList.Create; try FResult.Add('unit Keyman.System.Standards.ISO6393ToBCP47Registry;'); FResult.Add(''); FResult.Add('interface'); FResult.Add(''); FResult.Add('// File-Date: '+FormatDateTime('yyyy-mm-dd hh:nn:ss', Now)); FResult.Add('// Extracted from http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry'); FResult.Add('// Generated by build_standards_data'); FResult.Add(''); FResult.Add('uses'); FResult.Add(' System.Generics.Collections;'); FResult.Add(''); FResult.Add('type'); FResult.Add(' TISO6393ToBCP47Map = class'); FResult.Add(' public'); FResult.Add(' class procedure Fill(dict: TDictionary<string,string>);'); FResult.Add(' end;'); FResult.Add(''); FResult.Add('implementation'); FResult.Add(''); FResult.Add('{ TISO6393ToBCP47Map }'); FResult.Add(''); FResult.Add('class procedure TISO6393ToBCP47Map.Fill(dict: TDictionary<string, string>);'); FResult.Add('begin'); // Ignore first line which is a header for i := 1 to FISO6393.Count - 1 do begin s := FISO6393[i]; s6393 := GetField(s); // ID GetField(s); // Part2B GetField(s); // Part2T s6391 := GetField(s); // Part1 if s6391 <> '' then FResult.Add(' dict.Add('''+s6393+''','''+s6391+''');'); end; FResult.Add('end;'); FResult.Add(''); FResult.Add('end.'); FResult.SaveToFile(DestinationFile); finally FResult.Free; end; finally FISO6393.Free; end; end; end.
unit uShareUtils; interface uses System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Imaging.Jpeg, Vcl.Imaging.pngimage, uMemory, uGraphicUtils, uJpegUtils, uAssociatedIcons, uImageLoader, uDBEntities, uSettings; type TShareLinkData = record Url: string; Tag: string; end; type TUpdatePreviewProc = reference to procedure(Data: TMediaItem; Preview: TGraphic); TUpdateStreamProc = reference to procedure(Data: TMediaItem; S: TStream; ContentType: string); procedure ProcessImageForSharing(Data: TMediaItem; IsPreview: Boolean; UpdatePreviewProc: TUpdatePreviewProc; UpdateStreamProc: TUpdateStreamProc); implementation procedure ProcessImageForSharing(Data: TMediaItem; IsPreview: Boolean; UpdatePreviewProc: TUpdatePreviewProc; UpdateStreamProc: TUpdateStreamProc); var ContentType: string; UsePreviewForRAW: Boolean; NewGraphic: TGraphic; Original: TBitmap; Width, Height: Integer; IsJpegImageFormat, ResizeImage: Boolean; MS: TMemoryStream; Ico: TIcon; Flags: TImageLoadFlags; ImageInfo: ILoadImageInfo; begin try Width := 0; Height := 0; ResizeImage := AppSettings.ReadBool('Share', 'ResizeImage', True); if ResizeImage then begin Width := AppSettings.ReadInteger('Share', 'ImageWidth', 1920); Height := AppSettings.ReadInteger('Share', 'ImageWidth', 1920); end; if IsPreview then begin Width := 32; Height := 32; end; UsePreviewForRAW := AppSettings.ReadBool('Share', 'RAWPreview', True); IsJpegImageFormat := AppSettings.ReadInteger('Share', 'ImageFormat', 0) = 0; Flags := [ilfGraphic, ilfICCProfile, ilfEXIF, ilfPassword, ilfAskUserPassword, ilfThrowError]; if not (UsePreviewForRAW or IsPreview) then Flags := Flags + [ilfFullRAW]; if LoadImageFromPath(Data, -1, '', Flags, ImageInfo, Width, Height) then begin Original := ImageInfo.GenerateBitmap(Data, Width, Height, pf24Bit, clWhite, [ilboFreeGraphic, ilboRotate, ilboApplyICCProfile, ilboQualityResize]); try if Original <> nil then begin if IsPreview then begin UpdatePreviewProc(Data, Original); end else begin if IsJpegImageFormat then NewGraphic := TJpegImage.Create else NewGraphic := TPngImage.Create; try AssignToGraphic(NewGraphic, Original); F(Original); SetJPEGGraphicSaveOptions('ShareImages', NewGraphic); if NewGraphic is TJPEGImage then FreeJpegBitmap(TJPEGImage(NewGraphic)); MS := TMemoryStream.Create; try NewGraphic.SaveToStream(MS); if IsJpegImageFormat then ImageInfo.TryUpdateExif(MS, NewGraphic); MS.Seek(0, soFromBeginning); if IsJpegImageFormat then ContentType := 'image/jpeg' else ContentType := 'image/png'; UpdateStreamProc(Data, MS, ContentType); finally F(MS); end; finally F(NewGraphic); end; end; end; finally F(Original); end; end; except on e: Exception do begin Ico := TAIcons.Instance.GetIconByExt(Data.FileName, False, 32, False); try UpdatePreviewProc(Data, Ico); finally F(Ico); end; raise; end; end; end; end.
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Controls.Presentation; type TForm1 = class(TForm) NoPluralLabel: TLabel; NoPluralLabel0: TLabel; NoPluralLabel1: TLabel; NoPluralLabel2: TLabel; HomeLabel: TLabel; HomeLabel0: TLabel; HomeLabel1: TLabel; HomeLabel2: TLabel; PluralLabel: TLabel; PluralLabel0: TLabel; PluralLabel1: TLabel; PluralLabel2: TLabel; MultiPluralLabel: TLabel; MultiPluralLabel1: TLabel; MultiPluralLabel2: TLabel; MultiPluralLabel3: TLabel; MultiPluralLabel4: TLabel; LanguageButton: TButton; procedure FormCreate(Sender: TObject); procedure LanguageButtonClick(Sender: TObject); private procedure UpdateStrings; end; var Form1: TForm1; implementation {$R *.fmx} uses NtBase, NtPattern, NtResource, NtResourceString, // Turns on resource string translation FMX.NtLanguageDlg, FMX.NtTranslator; procedure TForm1.UpdateStrings; procedure ProcessNoPlural(count: Integer; lab: TLabel); resourcestring SFile = '%d file'; begin // On most languages this does not work except when count is 1 // Do not use code like this! lab.Text := Format(SFile, [count]); if TMultiPattern.IsSingleFormLanguage or (count = 1) or ((count = 0) and TMultiPattern.IsZeroLikeOne) then lab.TextSettings.FontColor := TAlphaColorRec.DarkGreen else lab.TextSettings.FontColor := TAlphaColorRec.Crimson; end; procedure ProcessHomeBrewed(count: Integer; lab: TLabel); resourcestring SFile1 = '%d file'; SFile2 = '%d files'; begin // This works on some Western languages (those that use similar plural rules as English) // but would fail for example in French. // Do not use code like this! if count = 1 then lab.Text := Format(SFile1, [count]) else lab.Text := Format(SFile2, [count]); if not TMultiPattern.IsSingleFormLanguage and (count = 0) and TMultiPattern.IsZeroLikeOne then lab.TextSettings.FontColor := TAlphaColorRec.Crimson else lab.TextSettings.FontColor := TAlphaColorRec.DarkGreen end; // The following two samples handle plural forms correctly. Use this kind of code in your applications. procedure ProcessPluralAware(count: Integer; lab: TLabel); resourcestring // This works on every count and language (expecting SFiles translated correctly with right patterns) // This message contains two patterns: one and other. // Localized strings will contain the patterns used by the target languages: // - German is like English: one and other // - Polish: one, paucal, other // - Japanese: other SFilesPlural = '{plural, one {%d file} other {%d files}}'; //loc 0: file count begin lab.Text := TMultiPattern.Format(SFilesPlural, count, [count]); lab.TextSettings.FontColor := TAlphaColorRec.DarkGreen; end; procedure ProcessMultiPlural(completed, total: Integer; lab: TLabel); resourcestring // This message contains two pluralized parameters. Contains three parts and seven patterns: // - The pattern start with a static text. // - Then it follows the first ICU part that has zero, one and other for completed parameter. // - Finally there is another ICU part for total steps. SMessagePlural = 'I have completed {plural, zero {none} one {one} other {%d}} {plural, zero {out of none steps} one {out of one step} other {out of %d steps}}'; begin lab.Text := TMultiPattern.Format(SMessagePlural, [completed, total]); lab.TextSettings.FontColor := TAlphaColorRec.DarkGreen; end; begin ProcessNoPlural(0, NoPluralLabel0); ProcessNoPlural(1, NoPluralLabel1); ProcessNoPlural(2, NoPluralLabel2); ProcessHomeBrewed(0, HomeLabel0); ProcessHomeBrewed(1, HomeLabel1); ProcessHomeBrewed(2, HomeLabel2); ProcessPluralAware(0, PluralLabel0); ProcessPluralAware(1, PluralLabel1); ProcessPluralAware(2, PluralLabel2); ProcessMultiPlural(0, 1, MultiPluralLabel1); ProcessMultiPlural(1, 1, MultiPluralLabel2); ProcessMultiPlural(1, 3, MultiPluralLabel3); ProcessMultiPlural(2, 3, MultiPluralLabel4); end; procedure TForm1.FormCreate(Sender: TObject); resourcestring SEnglish = 'English'; SFinnish = 'Finnish'; SGerman = 'German'; SFrench = 'French'; SJapanese = 'Japanese'; begin NtResources.Add('English', 'English', SEnglish, 'en'); NtResources.Add('Finnish', 'suomi', SFinnish, 'fi'); NtResources.Add('German', 'Deutsch', SGerman, 'de'); NtResources.Add('French', 'français', SFrench, 'fr'); NtResources.Add('Japanese', '日本語', SJapanese, 'ja'); _T(Self); UpdateStrings; end; procedure TForm1.LanguageButtonClick(Sender: TObject); begin if TNtLanguageDialog.Select then UpdateStrings; end; end.
unit AvgHospHands_MainForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, cxTextEdit, cxCurrencyEdit, cxLabel, cxGroupBox, StdCtrls, cxButtons, cxControls, cxContainer, cxEdit, cxRadioGroup, ZTypes, Unit_ZGlobal_Consts, ZProc, FIBQuery, pFIBQuery, pFIBStoredProc, FIBDatabase, pFIBDatabase, ZMessages, cxMaskEdit, ActnList; type TFAvgHospHands = class(TForm) RadioGroupTypeCount: TcxRadioGroup; YesBtn: TcxButton; CancelBtn: TcxButton; cxGroupBox1: TcxGroupBox; LabelAvgSum: TcxLabel; DB: TpFIBDatabase; Transaction: TpFIBTransaction; StProc: TpFIBStoredProc; EditAvgSumma: TcxMaskEdit; ActionList1: TActionList; YesBtnAction: TAction; procedure CancelBtnClick(Sender: TObject); procedure YesBtnActionExecute(Sender: TObject); private PParameter:TZAvgSumParameter; PLanguageIndex:byte; PIsOk:boolean; public constructor Create(Parameter:TZAvgSumParameter);reintroduce; property IsOk:Boolean read PIsOk; end; implementation {$R *.dfm} constructor TFAvgHospHands.Create(Parameter:TZAvgSumParameter); begin inherited Create(Parameter.Owner); PIsOk:=True; //***************************************************************************** PLanguageIndex:=LanguageIndex; Caption:=LabelAvgSum_Caption[PLanguageIndex]; YesBtn.Caption := YesBtn_Caption[PLanguageIndex]; CancelBtn.Caption := CancelBtn_Caption[PLanguageIndex]; RadioGroupTypeCount.Properties.Items[0].Caption:= LabelByDays_Caption[PLanguageIndex]; RadioGroupTypeCount.Properties.Items[1].Caption:=LabelByHours_Caption[PLanguageIndex]; LabelAvgSum.Caption:= LabelAvgSum_Caption[PLanguageIndex]; CancelBtn.Hint := CancelBtn.Caption+' (Esc)'; YesBtn.Hint:=YesBtn.Caption; //***************************************************************************** // EditAvgSumma.Properties.EditMask := '\d\d?\d?\d?\d?\d?\d?\d?\d?\d?\d?\d?\d? (['+ZSystemDecimalSeparator+']\d\d?)?'; //***************************************************************************** PParameter:=Parameter; DB.Handle:=PParameter.DB_Handle; try Transaction.StartTransaction; StProc.StoredProcName:='Z_HOSP_HANDS_AVG_S_BY_ID'; StProc.Prepare; StProc.ParamByName('ID_HOSP').AsInteger := PParameter.Id_Hosp_List; StProc.ParamByName('RMOVING').AsInteger := PParameter.rmoving; StProc.ExecProc; if not VarIsNull(StProc.ParamByName('IS_SMENA').AsVariant) then begin EditAvgSumma.Text := FloatToStrF(StProc.ParamByName('AVG_SUM').Asfloat,ffFixed,16,2); if VarToStr(StProc.ParamByName('IS_SMENA').AsVariant)='T' then RadioGroupTypeCount.ItemIndex:=1 else RadioGroupTypeCount.ItemIndex:=0; end; Transaction.Commit; except on E:exception do begin ZShowMessage(Error_Caption[PLanguageIndex],e.Message,mtError,[mbOK]); Transaction.Rollback; PIsOk:=False; end; end; end; procedure TFAvgHospHands.CancelBtnClick(Sender: TObject); begin ModalResult:=mrCancel; end; procedure TFAvgHospHands.YesBtnActionExecute(Sender: TObject); begin try Transaction.StartTransaction; StProc.StoredProcName:='Z_HOSP_HANDS_AVG_IUD'; StProc.Prepare; StProc.ParamByName('ID_HOSP').AsInteger := PParameter.Id_Hosp_List; StProc.ParamByName('RMoVING').AsInteger := PParameter.rmoving; if Trim(EditAvgSumma.Text)='' then begin StProc.ParamByName('IS_SMENA').AsVariant := Null; StProc.ParamByName('AVG_SUM').AsVariant := Null; end else begin StProc.ParamByName('IS_SMENA').AsString := ifThen(RadioGroupTypeCount.ItemIndex=0,'F','T'); StProc.ParamByName('AVG_SUM').AsDouble := StrToFloat(EditAvgSumma.Text); end; StProc.ExecProc; Transaction.Commit; ModalResult:=mrYes; except on E:exception do begin ZShowMessage(Error_Caption[PLanguageIndex],e.Message,mtError,[mbOK]); Transaction.Rollback; end; end; end; end.
unit uInstallScope; interface {$WARN SYMBOL_PLATFORM OFF} uses Generics.Collections, System.Classes, uMemory, {$IFNDEF EXTERNAL} uTranslate, {$ENDIF} OpenCV.Lib, Dmitry.Utils.System, uConstants; type //OBJECTS TInstallObject = class(TObject) end; TShortCut = class(TObject) public Name: string; Location: string; end; TShortCuts = class(TObject) private FShortCuts: TList; function GetCount: Integer; function GetItemByIndex(Index: Integer): TShortCut; public constructor Create; destructor Destroy; override; procedure Add(Name, Location: string); overload; procedure Add(Location: string); overload; property Count: Integer read GetCount; property Items[Index: Integer]: TShortCut read GetItemByIndex; default; end; TActionScope = (asInstall, asUninstall, asInstallFont, asUninstallFont); TFileAction = class(TObject) public CommandLine: string; Scope: TActionScope; end; TFileActions = class(TObject) private FActions: TList<TFileAction>; function GetCount: Integer; function GetItemByIndex(Index: Integer): TFileAction; public constructor Create; destructor Destroy; override; procedure Add(CommandLine: string; Scope: TActionScope); overload; property Count: Integer read GetCount; property Items[Index: Integer]: TFileAction read GetItemByIndex; default; end; TDiskObject = class(TInstallObject) private FShortCuts: TShortCuts; FActions: TFileActions; public Name: string; FinalDestination: string; Description: string; constructor Create(AName, AFinalDestination, ADescription: string); destructor Destroy; override; property ShortCuts: TShortCuts read FShortCuts; property Actions: TFileActions read FActions; end; TFileObject = class(TDiskObject) end; TDirectoryObject = class(TDiskObject) private FIsRecursive: Boolean; public property IsRecursive: Boolean read FIsRecursive write FIsRecursive; end; //COLLESTIONS TInstallScope = class end; TScopeFiles = class(TInstallScope) private FFiles: TList; function GetCount: Integer; function GetFileByIndex(Index: Integer): TDiskObject; public constructor Create; destructor Destroy; override; procedure Add(DiskObject: TDiskObject); property Count: Integer read GetCount; property Files[Index: Integer]: TDiskObject read GetFileByIndex; default; end; TUninstallOptions = class(TObject) private FDeleteUserSettings: Boolean; FDeleteAllCollections: Boolean; public constructor Create; property DeleteUserSettings: Boolean read FDeleteUserSettings write FDeleteUserSettings; property DeleteAllCollections: Boolean read FDeleteAllCollections write FDeleteAllCollections; end; // COMPLETE INSTALLLATION TInstall = class(TObject) private FFiles: TScopeFiles; FDestinationPath: string; FIsUninstall: Boolean; FUninstallOptions: TUninstallOptions; public constructor Create; virtual; destructor Destroy; override; property DestinationPath: string read FDestinationPath write FDestinationPath; property Files: TScopeFiles read FFiles; property IsUninstall: Boolean read FIsUninstall write FIsUninstall; property UninstallOptions: TUninstallOptions read FUninstallOptions; end; TPhotoDBInstall_V23 = class(TInstall) public constructor Create; override; end; function CurrentInstall: TInstall; implementation var FCurrentInstall: TInstall = nil; {$IFDEF EXTERNAL} function TA(StringToTranslate, Scope: string): string; begin Result := StringToTranslate; end; {$ENDIF} function CurrentInstall: TInstall; begin if FCurrentInstall = nil then FCurrentInstall := TPhotoDBInstall_V23.Create; Result := FCurrentInstall; end; { TShortCuts } procedure TShortCuts.Add(Name, Location: string); var ShortCut: TShortCut; begin ShortCut := TShortCut.Create; ShortCut.Name := Name; ShortCut.Location := Location; FShortCuts.Add(ShortCut); end; procedure TShortCuts.Add(Location: string); begin Add('', Location); end; constructor TShortCuts.Create; begin FShortCuts := TList.Create; end; destructor TShortCuts.Destroy; begin FreeList(FShortCuts); inherited; end; function TShortCuts.GetCount: Integer; begin Result := FShortCuts.Count; end; function TShortCuts.GetItemByIndex(Index: Integer): TShortCut; begin Result := FShortCuts[Index]; end; { TDiskObject } constructor TDiskObject.Create(AName, AFinalDestination, ADescription: string); begin Name := AName; FinalDestination := AFinalDestination; Description := ADescription; FShortCuts := TShortCuts.Create; FActions := TFileActions.Create; end; destructor TDiskObject.Destroy; begin F(FShortCuts); inherited; end; { TScopeFiles } procedure TScopeFiles.Add(DiskObject: TDiskObject); begin FFiles.Add(DiskObject); end; constructor TScopeFiles.Create; begin FFiles := TList.Create; end; destructor TScopeFiles.Destroy; begin FreeList(FFiles); inherited; end; function TScopeFiles.GetCount: Integer; begin Result := FFiles.Count; end; function TScopeFiles.GetFileByIndex(Index: Integer): TDiskObject; begin Result := FFiles[Index]; end; { TInstall } constructor TInstall.Create; begin FFiles := TScopeFiles.Create; FUninstallOptions := TUninstallOptions.Create; FIsUninstall := False; end; destructor TInstall.Destroy; begin F(FFiles); F(FUninstallOptions); inherited; end; { TPhotoDBInstall_V23 } constructor TPhotoDBInstall_V23.Create; var PhotoDBFile: TDiskObject; PhotoDBBridge: TDiskObject; ListFont: TDiskObject; {$IFDEF MEDIA_PLAYER} DirectoryObj: TDirectoryObject; {$ENDIF} begin inherited; Files.Add(TDirectoryObject.Create('Languages', '%PROGRAM%', '')); Files.Add(TDirectoryObject.Create('Licenses', '%PROGRAM%', '')); Files.Add(TDirectoryObject.Create('Cascades', '%PROGRAM%', '')); PhotoDBFile := TFileObject.Create(PhotoDBFileName, '%PROGRAM%', TA('Photo Database {V} helps you to find, protect and organize your photos.', 'System')); PhotoDBFile.FShortCuts.Add('%DESKTOP%\Photo Database {V}.lnk'); PhotoDBFile.FShortCuts.Add('%STARTMENU%\' + StartMenuProgramsPath + '\' + ProgramShortCutFile); PhotoDBFile.FShortCuts.Add('%STARTMENU%\' + StartMenuProgramsPath + '\' + TA('Home page', 'System') + '.lnk', 'http://photodb.illusdolphin.net/{LNG}'); Files.Add(PhotoDBFile); PhotoDBBridge := TFileObject.Create('PhotoDBBridge.exe', '%PROGRAM%', ''); PhotoDBBridge.Actions.Add('/regserver', asInstall); PhotoDBBridge.Actions.Add('/unregserver', asUnInstall); Files.Add(PhotoDBBridge); Files.Add(TFileObject.Create('Kernel.dll', '%PROGRAM%', '')); Files.Add(TFileObject.Create('FreeImage.dll', '%PROGRAM%', '')); Files.Add(TFileObject.Create(FormatEx('opencv_core{0}.dll', [CV_VERSION_DLL_PATH]), '%PROGRAM%', '')); Files.Add(TFileObject.Create(FormatEx('opencv_highgui{0}.dll', [CV_VERSION_DLL_PATH]), '%PROGRAM%', '')); Files.Add(TFileObject.Create(FormatEx('opencv_imgproc{0}.dll', [CV_VERSION_DLL_PATH]), '%PROGRAM%', '')); Files.Add(TFileObject.Create(FormatEx('opencv_objdetect{0}.dll', [CV_VERSION_DLL_PATH]), '%PROGRAM%', '')); Files.Add(TFileObject.Create(FormatEx('opencv_legacy{0}.dll', [CV_VERSION_DLL_PATH]), '%PROGRAM%', '')); Files.Add(TFileObject.Create(FormatEx('opencv_flann{0}.dll', [CV_VERSION_DLL_PATH]), '%PROGRAM%', '')); Files.Add(TFileObject.Create(FormatEx('opencv_features2d{0}.dll', [CV_VERSION_DLL_PATH]), '%PROGRAM%', '')); Files.Add(TFileObject.Create(FormatEx('opencv_calib3d{0}.dll', [CV_VERSION_DLL_PATH]), '%PROGRAM%', '')); Files.Add(TFileObject.Create(FormatEx('opencv_ml{0}.dll', [CV_VERSION_DLL_PATH]), '%PROGRAM%', '')); Files.Add(TFileObject.Create(FormatEx('opencv_video{0}.dll', [CV_VERSION_DLL_PATH]), '%PROGRAM%', '')); Files.Add(TFileObject.Create('UnInstall.exe', '%PROGRAM%', '')); Files.Add(TFileObject.Create('libeay32.dll', '%PROGRAM%', '')); Files.Add(TFileObject.Create('ssleay32.dll', '%PROGRAM%', '')); Files.Add(TFileObject.Create('lcms2.dll', '%PROGRAM%', '')); ListFont := TFileObject.Create('MyriadPro-Regular.otf', '%PROGRAM%', ''); ListFont.Actions.Add('Myriad Pro Regular (TrueType)', asInstallFont); ListFont.Actions.Add('Myriad Pro Regular (TrueType)', asUninstallFont); Files.Add(ListFont); Files.Add(TFileObject.Create('TransparentEncryption.dll', '%PROGRAM%', '')); Files.Add(TFileObject.Create('TransparentEncryption64.dll', '%PROGRAM%', '')); Files.Add(TFileObject.Create('PlayEncryptedMedia.exe', '%PROGRAM%', '')); Files.Add(TFileObject.Create('PlayEncryptedMedia64.exe', '%PROGRAM%', '')); {$IFDEF DBDEBUG} Files.Add(TFileObject.Create('FastMM_FullDebugMode.dll', '%PROGRAM%', '')); Files.Add(TFileObject.Create('PhotoDB.map', '%PROGRAM%', '')); {$ENDIF} Files.Add(TDirectoryObject.Create('Actions', '%PROGRAM%', '')); Files.Add(TDirectoryObject.Create('Scripts', '%PROGRAM%', '')); Files.Add(TDirectoryObject.Create('Images', '%PROGRAM%', '')); Files.Add(TDirectoryObject.Create('PlugInsEx', '%PROGRAM%', '')); Files.Add(TDirectoryObject.Create('Styles', '%PROGRAM%', '')); {$IFDEF MEDIA_PLAYER} DirectoryObj := TDirectoryObject.Create('MediaPlayer', '%PROGRAM%', ''); DirectoryObj.IsRecursive := True; Files.Add(DirectoryObj); //russian language Files.Add(TFileObject.Create('MediaPlayer\Lang\mpcresources.ru.dll', '%PROGRAM%', '')); {$ENDIF} end; { TFileActions } procedure TFileActions.Add(CommandLine: string; Scope: TActionScope); var FA: TFileAction; begin FA := TFileAction.Create; FA.CommandLine := CommandLine; FA.Scope := Scope; FActions.Add(FA); end; constructor TFileActions.Create; begin FActions := TList<TFileAction>.Create; end; destructor TFileActions.Destroy; begin FreeList(FActions); inherited; end; function TFileActions.GetCount: Integer; begin Result := FActions.Count; end; function TFileActions.GetItemByIndex(Index: Integer): TFileAction; begin Result := FActions[Index]; end; { TUninstallOptions } constructor TUninstallOptions.Create; begin FDeleteUserSettings := True; FDeleteAllCollections := False; end; initialization finalization F(FCurrentInstall); end.
{ ****************************************************************************** } { * Transform TextTable writen by QQ 600585@qq.com * } { * 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 TextTable; {$INCLUDE zDefine.inc} interface uses SysUtils, CoreClasses, DataFrameEngine, ListEngine, UnicodeMixedLib, MemoryStream64, TextParsing, PascalStrings; type TTranlateStyle = (tsPascalText, tsPascalComment, tsCText, tsCComment, tsNormalText, tsDFMText); TTextTableItem = record // origin info OriginText: SystemString; Category: SystemString; // ext pick info Picked: Boolean; // encode and import info index: Integer; DefineText: SystemString; // text style TextStyle: TTranlateStyle; // fast hash OriginHash: THash; DefineHash: THash; // project language originLanguage: Integer; DefineLanguage: Integer; RepCount: Integer; procedure InitSelf; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); end; PTextTableItem = ^TTextTableItem; TTextTable = class(TCoreClassObject) protected FList: TCoreClassList; function GetItems(index: Integer): PTextTableItem; public constructor Create; destructor Destroy; override; procedure Clear; function Count: Integer; property Items[index: Integer]: PTextTableItem read GetItems; default; procedure Delete(index: Integer); function GetMaxIndexNo: Integer; function GetOrigin(const s: SystemString): PTextTableItem; property origin[const s: SystemString]: PTextTableItem read GetOrigin; procedure AddCopy(var t: TTextTableItem); procedure AddText(AOriginText, ACategory: SystemString; APicked: Boolean); procedure AddPascalText(AOriginText, ACategory: SystemString; APicked: Boolean); procedure AddPascalComment(AOriginText, ACategory: SystemString; APicked: Boolean); procedure AddCText(AOriginText, ACategory: SystemString; APicked: Boolean); procedure AddCComment(AOriginText, ACategory: SystemString; APicked: Boolean); procedure AddDelphiFormText(AOriginText, ACategory: SystemString; APicked: Boolean); procedure ChangeDefineText(index: Integer; newDefine: U_String); function ExistsIndex(index: Integer): Boolean; function Search(AOriginText: SystemString): PTextTableItem; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure ExportToTextStream(stream: TCoreClassStream); procedure ImportFromTextStream(stream: TCoreClassStream); end; implementation procedure TTextTableItem.InitSelf; begin OriginText := ''; Category := ''; Picked := False; index := -1; DefineText := ''; TextStyle := tsNormalText; RepCount := 0; OriginHash := 0; DefineHash := 0; end; procedure TTextTableItem.LoadFromStream(stream: TCoreClassStream); var df: TDataFrameEngine; begin df := TDataFrameEngine.Create; df.DecodeFrom(stream); OriginText := df.Reader.ReadString; Category := df.Reader.ReadString; Picked := df.Reader.ReadBool; index := df.Reader.ReadInteger; DefineText := df.Reader.ReadString; TextStyle := TTranlateStyle(df.Reader.ReadInteger); RepCount := df.Reader.ReadInteger; OriginHash := df.Reader.ReadCardinal; DefineHash := df.Reader.ReadCardinal; originLanguage := df.Reader.ReadInteger; DefineLanguage := df.Reader.ReadInteger; DisposeObject(df); end; procedure TTextTableItem.SaveToStream(stream: TCoreClassStream); var df: TDataFrameEngine; begin df := TDataFrameEngine.Create; df.WriteString(OriginText); df.WriteString(Category); df.WriteBool(Picked); df.WriteInteger(index); df.WriteString(DefineText); df.WriteInteger(Integer(TextStyle)); df.WriteInteger(RepCount); df.WriteCardinal(OriginHash); df.WriteCardinal(DefineHash); df.WriteInteger(originLanguage); df.WriteInteger(DefineLanguage); df.EncodeTo(stream); DisposeObject(df); end; function TTextTable.GetItems(index: Integer): PTextTableItem; begin Result := FList[index]; end; constructor TTextTable.Create; begin inherited Create; FList := TCoreClassList.Create; end; destructor TTextTable.Destroy; begin Clear; DisposeObject(FList); inherited Destroy; end; procedure TTextTable.Clear; var i: Integer; p: PTextTableItem; begin for i := 0 to FList.Count - 1 do begin p := FList[i]; Dispose(p); end; FList.Clear; end; function TTextTable.Count: Integer; begin Result := FList.Count; end; procedure TTextTable.Delete(index: Integer); var p: PTextTableItem; begin p := FList[index]; Dispose(p); FList.Delete(index); end; function TTextTable.GetMaxIndexNo: Integer; var i: Integer; p: PTextTableItem; begin Result := 0; for i := 0 to FList.Count - 1 do begin p := PTextTableItem(FList[i]); if p^.index > Result then Result := p^.index; end; end; function TTextTable.GetOrigin(const s: SystemString): PTextTableItem; var i: Integer; p: PTextTableItem; begin Result := nil; for i := 0 to FList.Count - 1 do begin p := PTextTableItem(FList[i]); if (s = p^.OriginText) then Exit(p); end; end; procedure TTextTable.AddCopy(var t: TTextTableItem); var p: PTextTableItem; begin p := GetOrigin(t.OriginText); if p = nil then begin new(p); p^ := t; p^.RepCount := 1; FList.Add(p); end else begin p^.RepCount := p^.RepCount + 1; end; end; procedure TTextTable.AddText(AOriginText, ACategory: SystemString; APicked: Boolean); var p: PTextTableItem; begin p := GetOrigin(AOriginText); if p = nil then begin new(p); p^.OriginText := AOriginText; p^.Category := ACategory; p^.Picked := APicked; p^.index := GetMaxIndexNo + 1; p^.DefineText := AOriginText; p^.TextStyle := tsNormalText; p^.OriginHash := FastHashPSystemString(@AOriginText); p^.DefineHash := FastHashPSystemString(@p^.DefineText); p^.RepCount := 1; FList.Add(p); end else begin p^.RepCount := p^.RepCount + 1; end; end; procedure TTextTable.AddPascalText(AOriginText, ACategory: SystemString; APicked: Boolean); var p: PTextTableItem; begin p := GetOrigin(AOriginText); if p = nil then begin new(p); p^.OriginText := AOriginText; p^.Category := ACategory; p^.Picked := APicked; p^.index := GetMaxIndexNo + 1; p^.DefineText := AOriginText; p^.TextStyle := tsPascalText; p^.OriginHash := FastHashPSystemString(@AOriginText); p^.DefineHash := FastHashPSystemString(@p^.DefineText); p^.RepCount := 1; FList.Add(p); end else begin p^.RepCount := p^.RepCount + 1; end; end; procedure TTextTable.AddPascalComment(AOriginText, ACategory: SystemString; APicked: Boolean); var p: PTextTableItem; begin p := GetOrigin(AOriginText); if p = nil then begin new(p); p^.OriginText := AOriginText; p^.Category := ACategory; p^.Picked := APicked; p^.index := GetMaxIndexNo + 1; p^.DefineText := AOriginText; p^.TextStyle := tsPascalComment; p^.OriginHash := FastHashPSystemString(@AOriginText); p^.DefineHash := FastHashPSystemString(@p^.DefineText); p^.RepCount := 1; FList.Add(p); end else begin p^.RepCount := p^.RepCount + 1; end; end; procedure TTextTable.AddCText(AOriginText, ACategory: SystemString; APicked: Boolean); var p: PTextTableItem; begin p := GetOrigin(AOriginText); if p = nil then begin new(p); p^.OriginText := AOriginText; p^.Category := ACategory; p^.Picked := APicked; p^.index := GetMaxIndexNo + 1; p^.DefineText := AOriginText; p^.TextStyle := tsCText; p^.OriginHash := FastHashPSystemString(@AOriginText); p^.DefineHash := FastHashPSystemString(@p^.DefineText); p^.RepCount := 1; FList.Add(p); end else begin p^.RepCount := p^.RepCount + 1; end; end; procedure TTextTable.AddCComment(AOriginText, ACategory: SystemString; APicked: Boolean); var p: PTextTableItem; begin p := GetOrigin(AOriginText); if p = nil then begin new(p); p^.OriginText := AOriginText; p^.Category := ACategory; p^.Picked := APicked; p^.index := GetMaxIndexNo + 1; p^.DefineText := AOriginText; p^.TextStyle := tsCComment; p^.OriginHash := FastHashPSystemString(@AOriginText); p^.DefineHash := FastHashPSystemString(@p^.DefineText); p^.RepCount := 1; FList.Add(p); end else begin p^.RepCount := p^.RepCount + 1; end; end; procedure TTextTable.AddDelphiFormText(AOriginText, ACategory: SystemString; APicked: Boolean); var p: PTextTableItem; begin p := GetOrigin(AOriginText); if p = nil then begin new(p); p^.OriginText := AOriginText; p^.Category := ACategory; p^.Picked := APicked; p^.index := GetMaxIndexNo + 1; p^.DefineText := AOriginText; p^.TextStyle := tsDFMText; p^.OriginHash := FastHashPSystemString(@AOriginText); p^.DefineHash := FastHashPSystemString(@p^.DefineText); p^.RepCount := 1; FList.Add(p); end else begin p^.RepCount := p^.RepCount + 1; end; end; procedure TTextTable.ChangeDefineText(index: Integer; newDefine: U_String); var i: Integer; p: PTextTableItem; begin newDefine := umlCharReplace(newDefine, #9, #32).Text; while (newDefine.Len > 0) and (CharIn(newDefine.Last, [#13, #10])) do newDefine.DeleteLast; for i := 0 to FList.Count - 1 do begin p := FList[i]; if (p^.Picked) and (p^.index = index) then begin case p^.TextStyle of tsPascalText: p^.DefineText := TTextParsing.TranslateTextToPascalDecl(newDefine); tsPascalComment: p^.DefineText := TTextParsing.TranslateTextToPascalDeclComment(newDefine); tsCText: p^.DefineText := TTextParsing.TranslateTextToC_Decl(newDefine); tsCComment: p^.DefineText := TTextParsing.TranslateTextToC_DeclComment(newDefine); tsDFMText: p^.DefineText := TTextParsing.TranslateTextToPascalDeclWithUnicode(newDefine); else p^.DefineText := newDefine; end; p^.DefineHash := FastHashPSystemString(@p^.DefineText); end; end; end; function TTextTable.ExistsIndex(index: Integer): Boolean; var i: Integer; begin Result := True; for i := 0 to FList.Count - 1 do if index = PTextTableItem(FList[i])^.index then Exit; Result := False; end; function TTextTable.Search(AOriginText: SystemString): PTextTableItem; var hash: THash; i: Integer; p: PTextTableItem; begin hash := FastHashPSystemString(@AOriginText); for i := 0 to FList.Count - 1 do begin p := FList[i]; if (p^.OriginHash = hash) and (p^.OriginText = AOriginText) then begin Exit(p); end; end; Result := nil; end; procedure TTextTable.SaveToStream(stream: TCoreClassStream); var ms: TMemoryStream64; df: TDataFrameEngine; i: Integer; p: PTextTableItem; begin ms := TMemoryStream64.Create; df := TDataFrameEngine.Create; df.WriteInteger(FList.Count); for i := 0 to FList.Count - 1 do begin p := FList[i]; p^.SaveToStream(ms); ms.Position := 0; df.WriteStream(ms); ms.Clear; end; df.EncodeAsBRRC(stream); DisposeObject(ms); DisposeObject(df); end; procedure TTextTable.LoadFromStream(stream: TCoreClassStream); var ms: TMemoryStream64; df: TDataFrameEngine; i, c: Integer; p: PTextTableItem; begin Clear; ms := TMemoryStream64.Create; df := TDataFrameEngine.Create; df.DecodeFrom(stream); c := df.Reader.ReadInteger; for i := 0 to c - 1 do begin new(p); df.Reader.ReadStream(ms); ms.Position := 0; p^.LoadFromStream(ms); ms.Clear; FList.Add(p); end; DisposeObject(ms); DisposeObject(df); end; procedure TTextTable.ExportToTextStream(stream: TCoreClassStream); var expList: THashList; i: Integer; p: PTextTableItem; ns: TCoreClassStringList; n: TPascalString; begin expList := THashList.Create; ns := TCoreClassStringList.Create; for i := 0 to Count - 1 do begin p := Items[i]; if p^.Picked then if not expList.Exists(p^.OriginText) then begin expList.Add(p^.OriginText, p, False); case p^.TextStyle of tsPascalText: ns.Add(Format('%d=%s', [p^.index, TTextParsing.TranslatePascalDeclToText(p^.DefineText).Text])); tsCText: ns.Add(Format('%d=%s', [p^.index, TTextParsing.TranslateC_DeclToText(p^.DefineText).Text])); tsPascalComment: ns.Add(Format('%d=%s', [p^.index, TTextParsing.TranslatePascalDeclCommentToText(p^.DefineText).Text])); tsCComment: ns.Add(Format('%d=%s', [p^.index, TTextParsing.TranslateC_DeclCommentToText(p^.DefineText).Text])); tsDFMText: ns.Add(Format('%d=%s', [p^.index, TTextParsing.TranslatePascalDeclToText(p^.DefineText).Text])); else ns.Add(Format('%d=%s', [p^.index, p^.DefineText])); end; end; end; ns.SaveToStream(stream); DisposeObject(expList); DisposeObject(ns); end; procedure TTextTable.ImportFromTextStream(stream: TCoreClassStream); var ns: TCoreClassStringList; t: TTextParsing; CurrentItem: Integer; cp: Integer; nbPos, nePos: Integer; numText: U_String; Num: Integer; n: U_String; begin ns := TCoreClassStringList.Create; ns.LoadFromStream(stream); t := TTextParsing.Create(ns.Text, TTextStyle.tsText, nil); cp := 1; n := ''; Num := -1; CurrentItem := -1; while cp <= t.Len do begin if ((cp = 1) or (CharIn(t.GetChar(cp - 1), ns.LineBreak))) and (t.isNumber(cp)) then begin nbPos := cp; nePos := t.GetNumberEndPos(nbPos); numText := t.GetStr(nbPos, nePos); if CharIn(t.GetChar(nePos), ':=') then case umlGetNumTextType(numText) of ntUInt64, ntWord, ntByte, ntUInt: begin Num := umlStrToInt(numText.Text, 0); if n.Len >= length(ns.LineBreak) then n.Len := n.Len - length(ns.LineBreak); ChangeDefineText(CurrentItem, n); n := ''; CurrentItem := Num; cp := nePos + 1; Continue; end; end; end; n := n + t.GetChar(cp); inc(cp); end; if n.Len >= length(ns.LineBreak) then n.Len := n.Len - length(ns.LineBreak); ChangeDefineText(CurrentItem, n.Text); DisposeObject(ns); DisposeObject(t); end; end.
(* WLA: HDO, 2016-12-06 --- Wish list analyzer for the Christkind. ==========================================================*) PROGRAM WLA; (*$IFDEF WINDOWS*) USES WinCrt; (*$ENDIF*) TYPE wishPtr = ^wishersNode; wishersNode = RECORD next : wishPtr; name : STRING; END; (* END RECORD *) amazonListPtr = ^listElement; listElement = RECORD prev : amazonListPtr; next : amazonListPtr; item : STRING; n : INTEGER; wishers : wishPtr; END; (* END RECORD *) amazonList = RECORD first: amazonListPtr; last: amazonListPtr; END; (* END RECORD *) PROCEDURE InitAmazonList(VAR l : amazonList); BEGIN l.first := NIL; l.last := NIL; END; FUNCTION newWishNode(name : STRING) : wishPtr; VAR temp : wishPtr; BEGIN New(temp); temp^.next := NIL; temp^.name := name; newWishNode := temp; END; PROCEDURE appendToWishList(VAR list : wishPtr; node : wishPtr); VAR temp : wishPtr; BEGIN IF (list <> NIL) THEN BEGIN temp := list; WHILE (temp^.next <> NIL) DO temp := temp^.next; temp^.next := node; END ELSE list := node; END; FUNCTION newAmazonListNode(item, wisher : STRING) : amazonListPtr; VAR temp : amazonListPtr; BEGIN New(temp); temp^.prev := NIL; temp^.next := NIL; temp^.item := item; temp^.n := 1; temp^.wishers := newWishNode(wisher); newAmazonListNode := temp; END; (* Append to the amazon list *) (* if there is no toy in the list a new element will be made *) (* if a toy is already in the list, the name of the wisher will be added to the wisher list *) PROCEDURE appendToAmazonList(VAR amazon_List : amazonList; toy, wisher : STRING); VAR aListPtr, temp : amazonListPtr; BEGIN aListPtr := amazon_List.first; IF amazon_List.first = NIL THEN BEGIN aListPtr := newAmazonListNode(toy, wisher); amazon_List.first := aListPtr; amazon_List.last := aListPtr; END ELSE BEGIN WHILE aListPtr^.next <> NIL DO BEGIN IF aListPtr^.item = toy THEN break ELSE aListPtr := aListPtr^.next; END; IF aListPtr^.item = toy then BEGIN appendToWishList(aListPtr^.wishers,newWishNode(wisher)); aListPtr^.n := aListPtr^.n + 1; END ELSE BEGIN aListPtr := newAmazonListNode(toy, wisher); aListPtr^.prev := amazon_List.last; amazon_List.last^.next := aListPtr; amazon_List.last := alistPtr; END; END; END; (*#######################*) (* Printing to Console *) (*#######################*) PROCEDURE printWishers(wishers : wishPtr); VAR temp : wishPtr; BEGIN temp := wishers; WHILE temp <> NIL DO BEGIN Write(temp^.name, ' '); temp := temp^.next; END; END; PROCEDURE printAmazonList(list : amazonList); VAR temp : amazonListPtr; count : INTEGER; BEGIN temp := list.first; count := 1; WHILE temp <> NIL DO BEGIN WriteLn(count, '. Item:'); WriteLn('Name > ',temp^.item ,' | Count > ', temp^.n); WriteLn('Wishers: '); printWishers(temp^.wishers); WriteLn; WriteLn; count := count + 1; temp := temp^.next; END; END; VAR wishesFile: TEXT; line, wisher, toy: STRING; position : INTEGER; amazon_List : amazonList; BEGIN (*WLA*) InitAmazonList(amazon_List); WriteLn(chr(205),chr(205),chr(185),' Amazon wish list for XMas ',chr(204),chr(205),chr(205)); WriteLn; (* Read every line from txt *) Assign(wishesFile, 'Wishes.txt'); Reset(wishesFile); REPEAT ReadLn(wishesFile, line); position := pos(':',line); IF position <> 0 THEN wisher := Copy(line,1,position-1) ELSE appendToAmazonList(amazon_List,line,wisher); //WriteLn(wisher, ' ',position); UNTIL Eof(wishesFile); Close(wishesFile); printAmazonList(amazon_List); END. (*WLA*)
unit gr_ReeDolgDataModul; interface uses SysUtils, Classes, DB, FIBDataSet, pFIBDataSet, FIBDatabase, pFIBDatabase, frxClass, frxDBSet, frxDesgn, IBase, IniFiles, Forms, Dates, Variants, Unit_SprSubs_Consts, ZProc, Controls, FIBQuery, pFIBQuery, pFIBStoredProc, ZMessages, Dialogs, Math, Unit_SvodDocs_Consts, TypInfo, gr_uCommonConsts, gr_uCommonProc, gr_uWaitForm, gr_uCommonLoader, gr_uMessage, RxMemDS, frxExportXLS; Type TReeParam = record DB_Handle:TISC_DB_HANDLE; AOwner:TComponent; Kod_setup:integer; end; Type TReeDolgParam = record FoundationParam : TReeParam; Id_Sch : Variant; end; type TDM = class(TDataModule) DB: TpFIBDatabase; ReadTransaction: TpFIBTransaction; Designer: TfrxDesigner; DSetDolgData: TpFIBDataSet; ReportDBDSetDolgData: TfrxDBDataset; Report: TfrxReport; DSetSchs: TpFIBDataSet; ReportDBDSetSchsData: TfrxDBDataset; DataSource: TDataSource; frxXLSExport1: TfrxXLSExport; procedure ReportGetValue(const VarName: String; var Value: Variant); procedure DataModuleDestroy(Sender: TObject); private PKod_Setup:Integer; PLanguageIndex:byte; public function PrintSpr(AParameter:TReeDolgParam):variant; end; implementation {$R *.dfm} const NameReport ='\grReeDolg.fr3'; function TDM.PrintSpr(AParameter:TReeDolgParam):variant; var DateForm:tdate; i: byte; wf:TForm; begin DateForm:=ConvertKodToDate(AParameter.FoundationParam.Kod_setup); PKod_Setup:=AParameter.FoundationParam.Kod_setup; PLanguageIndex := IndexLanguage; DSetSchs.SQLs.SelectSQL.Text := 'SELECT * FROM GR_SVOD_SCHES('+VarToStrDef(AParameter.Id_Sch[0],'NULL')+','''+DateToStr(DateForm)+''' )'; DSetDolgData.SQLs.SelectSQL.Text := 'SELECT * FROM GR_REEDOLG_BYSCH(?ID_SCH,'+VarToStr(AParameter.FoundationParam.Kod_setup)+')'; try wf:=ShowWaitForm(TForm(AParameter.FoundationParam.AOwner),wfPrepareData); DB.Handle:=AParameter.FoundationParam.DB_Handle; DSetSchs.Open; for i:=1 to (VarArrayHighBound(AParameter.Id_Sch,1)-1) do begin DSetSchs.SQLs.InsertSQL.Text := 'SELECT * FROM GR_SVOD_SCHES('+VarToStrDef(AParameter.Id_Sch[i],'NULL')+','''+DateToStr(DateForm)+''' )'; DSetSchs.Insert; DSetSchs.Post; end; DSetDolgData.Open; except on E:Exception do begin CloseWaitForm(wf); ZShowMessage(Error_Caption,e.Message,mtError,[mbOK]); Exit; end; end; CloseWaitForm(wf); Report.Clear; Report.LoadFromFile(ExtractFilePath(Application.ExeName)+PathReports+NameReport,True); if grDesignReport then Report.DesignReport else Report.ShowReport; Report.Free; end; procedure TDM.ReportGetValue(const VarName: String; var Value: Variant); begin if UpperCase(VarName)='PKOD_SETUP' then Value:=KodSetupToPeriod(PKod_Setup,5); if UpperCase(VarName)='FIRM' then Value:=grNameFirm(DB.Handle); end; procedure TDM.DataModuleDestroy(Sender: TObject); begin if ReadTransaction.InTransaction then ReadTransaction.Commit; end; end.
namespace colorapplet; // Sample applet project by Brian Long (http://blong.com) // Translated from Michael McGuffin's DrawingWithColor2 applet // from http://profs.etsmtl.ca/mmcguffin/learn/java/03-color/ interface uses java.util, java.applet.*, java.awt; type ColorApplet = public class(Applet) private var width, height: Integer; const N = 25; // the number of colors created var spectrum: array of Color; // arrays of elements, each of type Color public method init(); override; method paint(g: Graphics); override; end; implementation method ColorApplet.init(); begin width := Size.width; height := Size.height; Background := Color.BLACK; spectrum := new Color[N]; // Generate the colors and store them in the array. for i: Integer := 0 to N - 1 do // Here we specify colors by Hue, Saturation, and Brightness, // each of which is a number in the range [0,1], and use // a utility routine to convert it to an RGB value before // passing it to the Color() constructor. spectrum[i] := new Color(Color.HSBtoRGB(i / Double(N), 1, 1)) end; method ColorApplet.paint(g: Graphics); const Msg = 'Cooper'; begin var radius: Integer := width / 3; var msgLen := g.FontMetrics.stringWidth(Msg); for i: Integer := 0 to N - 1 do begin // Compute (x,y) positions along a circle, // using the sine and cosine of an appropriately computed angle. var angle: Double := 2 * Math.PI * i / N; var x := Integer(radius * Math.cos(angle)); var y := Integer(radius * Math.sin(angle)); g.Color := spectrum[i]; g.drawString(Msg, (width - msgLen) / 2 + x, height / 2 + y) end; end; end.
unit fos_strutils; {$mode objfpc}{$H+} interface uses Classes, SysUtils,strutils; function FOS_AnsiContainsText(const AText, ASubText: string): Boolean;inline; function FOS_AnsiStartsText(const ASubText, AText: string): Boolean;inline; function FOS_AnsiEndsText(const ASubText, AText: string): Boolean;inline; function FOS_AnsiReplaceText(const AText, AFromText, AToText: string): string;inline; Function FOS_PosEx(const SubStr, S: string; Offset: Cardinal): Integer; Function FOS_PosEx(const SubStr, S: string): Integer;inline; // Offset: Cardinal = 1 Function FOS_PosEx(c:char; const S: string; Offset: Cardinal): Integer; implementation function FOS_AnsiContainsText(const AText, ASubText: string): Boolean; begin result := AnsiContainsText(atext,asubtext); end; function FOS_AnsiStartsText(const ASubText, AText: string): Boolean; begin result := AnsiStartsText(ASubText, AText); end; function FOS_AnsiEndsText(const ASubText, AText: string): Boolean; begin result := AnsiEndsText(ASubText, AText); end; function FOS_AnsiReplaceText(const AText, AFromText, AToText: string): string; begin result := AnsiReplaceText(AText, AFromText, AToText); end; function FOS_PosEx(const SubStr, S: string; Offset: Cardinal): Integer; begin result := posex(substr,s,offset); end; function FOS_PosEx(const SubStr, S: string): Integer; begin result := posex(substr,s); end; function FOS_PosEx(c: char; const S: string; Offset: Cardinal): Integer; begin result := posex(c,s,offset); end; end.
unit MVVM.Interfaces.Architectural; interface uses System.Classes, System.SysUtils, System.UITypes, MVVM.CommandFactory, MVVM.Interfaces, MVVM.Observable; type {$REGION 'MVVM-Layers'} IModel = interface(IObject) ['{28C9B05B-A5F5-49E1-913E-2AB10F9FB8F3}'] end; IViewModel = interface(IObject) ['{37E13CBF-FDB2-4C6B-948A-7D5F7A6D0AC5}'] procedure BindCommands(const AView: TComponent); procedure SetupViewModel; end; TViewModel = class abstract(TObservable, IViewModel, INotifyChangedProperty, INotifyFree) private FCommandsFactory: TCommandsFactory; protected procedure AfterConstruction; override; public constructor Create; reintroduce; destructor Destroy; override; procedure BindCommands(const AView: TComponent); procedure SetupViewModel; virtual; abstract; function GetAsObject: TObject; end; TViewModelClass = class of TViewModel; IView = interface(IObject) ['{44055F6F-42A8-43DD-B393-1CC700B8C7F8}'] procedure SetupView; end; IView<T: IViewModel> = interface(IView) ['{BF4DF63F-88A6-4971-A1D1-EF03620FA4C2}'] function GetViewModel: T; procedure InitView(AViewModel: T); property ViewModel: T read GetViewModel; end; IViewForm<T: IViewModel> = interface(IView<T>) ['{16407011-00BD-4BCA-9453-1D3F4E1C5DE1}'] procedure Execute; procedure ExecuteModal(const AResultProc: TProc<TModalResult>); end; {$ENDREGION} implementation uses MVVM.Utils; { TViewModel } procedure TViewModel.BindCommands(const AView: TComponent); begin //Utils.IdeDebugMsg('<TViewModel.BindCommands>'); FCommandsFactory.LoadCommandsAndActionsFrom(AView); FCommandsFactory.BindView(AView); end; constructor TViewModel.Create; begin //Utils.IdeDebugMsg('<TViewModel.Create>'); inherited; FCommandsFactory := TCommandsFactory.Create; end; destructor TViewModel.Destroy; begin FCommandsFactory.Free; inherited; end; function TViewModel.GetAsObject: TObject; begin Result := Self end; procedure TViewModel.AfterConstruction; begin inherited; FCommandsFactory.LoadCommandsAndActionsFrom(Self); end; end.
unit Option; interface uses System.SysUtils, System.Types, System.UITypes, System.Rtti, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Objects, FMX.ListBox, FMX.Layouts; type TOptionForm = class(TForm) ToolBar1: TToolBar; Label1: TLabel; Button1: TButton; ListBox1: TListBox; ListBoxGroupHeader1: TListBoxGroupHeader; ListBoxItem1: TListBoxItem; ListBoxItem2: TListBoxItem; ListBoxItem3: TListBoxItem; sEast: TSwitch; sCentral: TSwitch; sWest: TSwitch; ListBoxItem4: TListBoxItem; ListBoxGroupHeader2: TListBoxGroupHeader; DisableAdsListBoxItem: TListBoxItem; RestoreAdsListBoxItem: TListBoxItem; sEurope: TSwitch; EuropeListBoxItem: TListBoxItem; ConsumeListBoxItem: TListBoxItem; procedure Button1Click(Sender: TObject); procedure sWestSwitch(Sender: TObject); procedure sCentralSwitch(Sender: TObject); procedure sEastSwitch(Sender: TObject); procedure DisableAdsListBoxItemClick(Sender: TObject); procedure RestoreAdsListBoxItemClick(Sender: TObject); procedure EuropeListBoxItemClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure ConsumeListBoxItemClick(Sender: TObject); private procedure CheckState; public procedure DisablePurchaseItem; end; var OptionForm: TOptionForm = nil; procedure CreateOptions; procedure ShowOptions; implementation uses Main; {$R *.fmx} procedure CreateOptions; begin if not Assigned(OptionForm) then OptionForm := TOptionForm.Create(MainForm); end; procedure ShowOptions; begin if not Assigned(OptionForm) then OptionForm := TOptionForm.Create(MainForm); OptionForm.Show; end; procedure TOptionForm.Button1Click(Sender: TObject); begin Close; MainForm.OptionsDone; end; procedure TOptionForm.CheckState; begin sCentral.HitTest := sEast.IsChecked or sWest.IsChecked; sEast.HitTest := sCentral.IsChecked or sWest.IsChecked; sWest.HitTest := sCentral.IsChecked or sEast.IsChecked; end; procedure TOptionForm.FormShow(Sender: TObject); begin sCentral.IsChecked := MainForm.Central; sEast.IsChecked := MainForm.East; sWest.IsChecked := MainForm.West; CheckState; end; procedure TOptionForm.ConsumeListBoxItemClick(Sender: TObject); begin MainForm.ConsumeProducts; end; procedure TOptionForm.EuropeListBoxItemClick(Sender: TObject); begin MainForm.PurchaseEurope; // that would be awesome :)) end; procedure TOptionForm.RestoreAdsListBoxItemClick(Sender: TObject); begin MainForm.RestorePurchase; end; procedure TOptionForm.DisableAdsListBoxItemClick(Sender: TObject); begin MainForm.DisableAdverts; end; procedure TOptionForm.DisablePurchaseItem; begin Log.d('Disabling the no-ads purchase UI'); DisableAdsListBoxItem.Enabled := False; end; procedure TOptionForm.sCentralSwitch(Sender: TObject); begin MainForm.Central := sCentral.IsChecked; CheckState; end; procedure TOptionForm.sEastSwitch(Sender: TObject); begin MainForm.East := sEast.IsChecked; CheckState; end; procedure TOptionForm.sWestSwitch(Sender: TObject); begin MainForm.West := sWest.IsChecked; CheckState; end; end.
unit Support; { data module containing all non-visual non-database components (menus, dialogs) } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Spell32, Wwlocate, Menus, Wwfltdlg, stdctrls, db, comctrls, dbctrls; type TmodSupport = class(TDataModule) popRTF: TPopupMenu; mniInsert: TMenuItem; mniDelete: TMenuItem; N1: TMenuItem; mniBold: TMenuItem; mniItalic: TMenuItem; mniUnderline: TMenuItem; dlgLocate: TwwLocateDialog; dlgSpell: TSpellDlg; dlgFilter: TwwFilterDialog; procedure RTFPopup(Sender: TObject); procedure InsertClick(Sender: TObject); procedure DeleteClick(Sender: TObject); procedure BoldClick(Sender: TObject); procedure ItalicClick(Sender: TObject); procedure UnderlineClick(Sender: TObject); procedure FilterInitDialog(Dialog: TwwFilterDlg); procedure CheckMe(fld: tCustomEdit; ds: tdatasource; const frmopen,frmclose:boolean); procedure modSupportCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var modSupport: TmodSupport; implementation uses Data, DBRichEdit, common; {$R *.DFM} { POPUP MENU } { initializes the popup menu before displaying it 1. move focus to calling rich edit 2. show delete item if in protected text 3. show insert item if code insert dialog is open 4. set other options } procedure TmodSupport.RTFPopup(Sender: TObject); var i : Integer; begin with modSupport.popRTF.PopupComponent as TclDBRichCodeBtn do begin if not Focused then SetFocus; mniDelete.Visible := SelAttributes.Protected; for i := 0 to Pred( Screen.FormCount ) do begin if Screen.Forms[ i ].Name = 'frmCode' then begin mniInsert.Visible := True; Break; end; mniInsert.Visible := False; end; N1.Visible := ( mniDelete.Visible or mniInsert.Visible ); mniBold.Checked := ( fsBold in SelAttributes.Style ) and ( caBold in SelAttributes.ConsistentAttributes ); mniItalic.Checked := ( fsItalic in SelAttributes.Style ) and ( caItalic in SelAttributes.ConsistentAttributes ); mniUnderline.Checked := ( fsUnderline in SelAttributes.Style ) and ( caUnderline in SelAttributes.ConsistentAttributes ); end; end; procedure TmodSupport.InsertClick(Sender: TObject); //var fieldedcode:string; begin with popRTF.PopupComponent as TclDBRichCodeBtn do EmbedCode( modLibrary.tblCodeCode.AsString ); //fieldedcode := ''; with modlibrary do if tblcodefielded.value <> 1 then begin tblcode.edit; tblcodefielded.value := 1; tblcode.post; //fieldedcode := tblcodefielded.asstring; end; (* if fieldedcode <> '' then with modlibrary.ww_Query do begin close; databasename := '_QualPro'; sql.clear; sql.add('Update codes set fielded=1 where code='+fieldedcode); execsql; end; *) end; procedure TmodSupport.DeleteClick(Sender: TObject); begin with popRTF.PopupComponent as TclDBRichCodeBtn do RemoveCode; end; procedure TmodSupport.BoldClick(Sender: TObject); begin with popRTF.PopupComponent as TclDBRichCodeBtn do DoBold; end; procedure TmodSupport.ItalicClick(Sender: TObject); begin with popRTF.PopupComponent as TclDBRichCodeBtn do DoItalic; end; procedure TmodSupport.UnderlineClick(Sender: TObject); begin with popRTF.PopupComponent as TclDBRichCodeBtn do DoUnderline; end; { FILTER DIALOG } { removes the bold style from the dialog before displaying it } procedure TmodSupport.FilterInitDialog(Dialog: TwwFilterDlg); begin Dialog.Font.Style := [ ]; end; procedure TmodSupport.CheckMe(fld : tCustomEdit; ds:tdatasource; const frmopen,frmclose:boolean); begin with dlgSpell do begin ds.dataset.edit; closewin := false; if frmopen then show; if dlgSpell.SpellCheck( fld ) = mrOK then begin ds.dataset.post end else ds.dataset.cancel; if frmClose then close; closewin := true; end; end; procedure TmodSupport.modSupportCreate(Sender: TObject); var s : string; begin s := AliasPath('Question'); delete(s,pos('LIBRARY',uppercase(s)),7); s := s + 'Dictionaries'; dlgSpell.dictionaryPath := s; end; end.
(* MPC_SS 10.05.17 *) (* Syntax Analysator (scanner) für mini pascal*) UNIT MPC_SS; INTERFACE VAR success: BOOLEAN; PROCEDURE S; IMPLEMENTATION USES MP_Lex, SymTab, CodeGen, CodeDef; FUNCTION SyIsNot(expectedSy: SymbolCode): BOOLEAN; BEGIN success := success AND (sy = expectedSy); SyIsNot := NOT success; END; PROCEDURE SemErr(msg: STRING); BEGIN WriteLn('*** semantic error *', msg, '* in line ', syLnr, ' at position ', syCnr); (*if you want to stop parsing after a semantic error occured then add the following line: success := FALSE; *) END; (*SemErr*) PROCEDURE MP; FORWARD; PROCEDURE VarDecal; FORWARD; PROCEDURE StatSeq; FORWARD; PROCEDURE Stat; FORWARD; PROCEDURE Expr; FORWARD; PROCEDURE Term; FORWARD; PROCEDURE Fact; FORWARD; PROCEDURE S; BEGIN success := TRUE; MP; IF NOT success OR SyIsNot(eofSy) THEN WriteLn('Error in line ', syLnr, ' at position ', syCnr) ELSE WriteLn('Sucessfully parsed'); END; PROCEDURE MP; BEGIN (* SEM *) InitSymbolTable; InitCodeGenerator; (* END SEM *) IF SyIsNot(programSy) THEN EXIT; NewSy; IF SyIsNot(identSy) THEN EXIT; NewSy; IF SyIsNot(semicolonSy) THEN EXIT; NewSy; IF sy = varSy THEN BEGIN VarDecal; IF NOT success THEN EXIT; END; IF SyIsNot(beginSy) THEN EXIT; NewSy; StatSeq; IF NOT success THEN EXIT; (* SEM *) Emit1(EndOpc); (* END SEM *) IF SyIsNot(endSy) THEN EXIT; NewSy; IF SyIsNot(periodSy) THEN EXIT; NewSy; (* to get eofSy *) END; PROCEDURE VarDecal; (*Local*) VAR ok: BOOLEAN; (* END LOCAL *) BEGIN IF SyIsNot(varSy) THEN EXIT; NewSy; IF SyIsNot(identSy) THEN EXIT; (* SEM *) DeclVar(identStr, ok); (* ENDSEM *) NewSy; WHILE sy = commaSy DO BEGIN NewSy; IF SyIsNot(identSy) THEN EXIT; (* SEM *) DeclVar(identStr, ok); IF NOT ok THEN SemErr('multiple declaration'); (* ENDSEM *) NewSy; END; IF SyIsNot(colonSy) THEN EXIT; NewSy; IF SyIsNot(integerSy) THEN EXIT; NewSy; IF SyIsNot(semicolonSy) THEN EXIT; NewSy; END; PROCEDURE StatSeq; BEGIN Stat; IF NOT success THEN EXIT; WHILE sy = semicolonSy DO BEGIN NewSy; Stat; IF NOT success THEN EXIT; END; END; PROCEDURE Stat; (* LOCAL *) VAR destId: STRING; addr, addr1, addr2 : INTEGER; (* END LOCAL *) BEGIN CASE sy OF identSy: BEGIN (* SEM *) destId := identStr; IF NOT IsDecl(destId) THEN SemErr('var not declared') ELSE Emit2(LoadAddrOpc, AddrOf(destId)); (* ENDSEM *) NewSy; IF SyIsNot(assignSy) THEN EXIT; NewSy; Expr; IF NOT success THEN EXIT; (* SEM *) IF IsDecl(destId) THEN Emit1(StoreOpc); (* ENDSEM *) END; readSy: BEGIN NewSy; IF SyIsNot(leftParSy) THEN EXIT; NewSy; (* SEM *) IF NOT IsDecl(identStr) THEN SemErr('var not declared') ELSE Emit2(LoadAddrOpc, AddrOf(identStr)); (* ENDSEM *) IF SyIsNot(identSy) THEN EXIT; NewSy; IF SyIsNot(rightParSy) THEN EXIT; NewSy; END; writeSy: BEGIN NewSy; IF SyIsNot(leftParSy) THEN EXIT; NewSy; Expr; IF NOT success THEN EXIT; (* SEM *) Emit1(WriteOpc); (* ENDSEM *) IF SyIsNot(rightParSy) THEN EXIT; NewSy; END; beginSy: BEGIN NewSy; StatSeq; IF NOT success THEN EXIT; IF SyIsNot(endSy) THEN EXIT; NewSy; END; ifSy: BEGIN NewSy; IF SyIsNot(identSy) THEN EXIT; IF NOT ISDecl(identStr) THEN SemErr('variable not declared'); Emit2(LoadValOpc, AddrOf(identStr)); Emit2(JmpZOpc, 0); addr := CurAddr - 2; NewSy; IF SyIsNot(thenSy) THEN EXIT; NewSy; Stat; IF NOT success THEN EXIT; IF sy = elseSy THEN BEGIN Emit2(JmpOpc, 0); FixUp(addr, CurAddr); addr := CurAddr - 2; NewSy; Stat; IF NOT success THEN EXIT; FixUp(addr, CurAddr); END; END; whileSy: BEGIN NewSy; IF SyIsNot(identSy) THEN EXIT; IF NOT IsDecl(identStr) THEN SemErr('variable not declared'); addr1 := CurAddr; Emit2(LoadValOpc, AddrOf(identStr)); Emit2(JmpZOpc, 0); addr2 := CurAddr - 2; NewSy; IF SyIsNot(doSy) THEN EXIT; NewSy; Stat; IF NOT success THEN EXIT; Emit2(JmpOpc, addr1); FixUp(addr2, CurAddr); END; ELSE (* no statement *) END; END; PROCEDURE Expr; BEGIN Term; IF NOT success THEN EXIT; WHILE (sy = plusSy) OR (sy = minusSy) DO BEGIN CASE sy OF plusSy: BEGIN NewSy; Term; IF NOT success THEN EXIT; (* SEM *) Emit1(AddOpc); (* ENDSEM *) END; minusSy: BEGIN NewSy; Term; IF NOT success THEN EXIT; (* SEM *) Emit1(SubOpc); (* ENDSEM *) END; END; END; END; PROCEDURE Term; BEGIN Fact; IF NOT success THEN EXIT; WHILE (sy = timesSy) OR (sy = divSy) DO BEGIN CASE sy OF timesSy: BEGIN NewSy; Fact; IF NOT success THEN EXIT; (* SEM *) Emit1(MulOpc); (* ENDSEM *) END; divSy: BEGIN NewSy; Fact; IF NOT success THEN EXIT; (* SEM *) Emit1(DivOpc); (* ENDSEM *) END; END; END; END; PROCEDURE Fact; BEGIN CASE sy OF identSy: BEGIN (* SEM *) IF NOT IsDecl(identStr) THEN SemErr('var not decl.') ELSE Emit2(LoadValOpc, AddrOf(identStr)); (* ENDSEM *) NewSy; END; numberSy: BEGIN (* SEM *) Emit2(LoadConstOpc, numberVal); (* ENDSEM *) NewSy; END; leftParSy: BEGIN NewSy; Expr; IF NOT success THEN EXIT; IF sy <> rightParSy THEN BEGIN success:= FALSE; EXIT; END; NewSy; END; ELSE success := FALSE; END; END; END.